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/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,12 @@ pub trait Inputs {
fn work_crs(&self) -> rustgis_data::raster::Crs {
rustgis_data::raster::Crs::LonLat
}
/// The project's coordinate system (#2032 C3a), when it has one: the system a grid made from a
/// layer in degrees, or with no system, is made in when the run names none
/// ([`tools::raster_crs_in`]).
fn project_crs(&self) -> Option<rustgis_data::raster::Crs> {
None
}
/// 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> {
None
Expand Down
45 changes: 34 additions & 11 deletions crates/analysis/src/tools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -901,7 +901,7 @@ pub static TOOLS: &[ToolSpec] = &[
kind: K::Text,
required: false,
default: "",
help: "A projected coordinate system (e.g. EPSG:32618) to make the raster in, its units for the extent and pixel size; when empty, the projected one the layer is held in, or else was read in, else degrees; EPSG:4326 for degrees.",
help: "A projected coordinate system (e.g. EPSG:32618) to make the raster in, its units for the extent and pixel size; when empty, the projected one the layer is held in, or else was read in, else the project's projected one, else degrees; EPSG:4326 for degrees.",
},
P { name: "output", label: "Output Name", kind: K::Text, required: false, default: "", help: "" },
],
Expand Down Expand Up @@ -1067,7 +1067,7 @@ pub static TOOLS: &[ToolSpec] = &[
kind: K::Text,
required: false,
default: "",
help: "A projected coordinate system (e.g. EPSG:32618) to make the raster in, its units for the extent, pixel size and range; when empty, the projected one the layer is held in, or else was read in, else degrees; EPSG:4326 for degrees.",
help: "A projected coordinate system (e.g. EPSG:32618) to make the raster in, its units for the extent, pixel size and range; when empty, the projected one the layer is held in, or else was read in, else the project's projected one, else degrees; EPSG:4326 for degrees.",
},
P { name: "output", label: "Output Name", kind: K::Text, required: false, default: "", help: "" },
],
Expand Down Expand Up @@ -1317,7 +1317,7 @@ pub static TOOLS: &[ToolSpec] = &[
kind: K::Text,
required: false,
default: "",
help: "Projected coordinate system (e.g. EPSG:32618); defaults to the projected system the layer is held in, or else was read in; required when the layer has none or is in degrees.",
help: "Projected coordinate system (e.g. EPSG:32618); defaults to the projected system the layer is held in, or else was read in, else the project's projected system; required when none of these is set.",
},
P { name: "output", label: "Output Name", kind: K::Text, required: false, default: "", help: "Output raster layer name." },
],
Expand Down Expand Up @@ -4846,7 +4846,7 @@ fn idw_interpolation(inp: &dyn Inputs, p: &Json) -> Result<ToolResult, String> {
}
});
}
let (crs, crs_note) = raster_crs_in(ds, inp.work_crs(), p, "IDW Interpolation")?;
let (crs, crs_note) = raster_crs_in(ds, inp.work_crs(), inp.project_crs(), p, "IDW Interpolation")?;
let (pts, beyond_note) = points_from(inp.work_crs(), crs, pts)?;
let extent = match s(p, "extent").trim() {
"" => {
Expand Down Expand Up @@ -4939,7 +4939,7 @@ fn kriging_interpolation(inp: &dyn Inputs, p: &Json) -> Result<ToolResult, Strin
}
}
}
let (crs, crs_note) = raster_crs_in(ds, inp.work_crs(), p, "Ordinary Kriging")?;
let (crs, crs_note) = raster_crs_in(ds, inp.work_crs(), inp.project_crs(), p, "Ordinary Kriging")?;
let (raw_pts, beyond_note) = points_from(inp.work_crs(), crs, raw_pts)?;
// Points at the same place as one, so the kriging matrix isn't singular.
let pts = merge_coincident(raw_pts)?;
Expand Down Expand Up @@ -5141,13 +5141,33 @@ pub fn raster_crs(ds: &Dataset, p: &Json, tool: &str) -> Result<(Crs, Option<Str
}

/// [`raster_crs`] for a run in `work` ([`Inputs::work_crs`]): a layer held in its own projected
/// system makes its grid there unless `p` names another.
pub fn raster_crs_in(ds: &Dataset, work: Crs, p: &Json, tool: &str) -> Result<(Crs, Option<String>), String> {
if work == Crs::LonLat {
raster_crs_of(ds.crs, "was read in", &ds.name, p, tool)
} else {
raster_crs_of(Some(work), "is held in", &ds.name, p, tool)
/// system makes its grid there unless `p` names another; one in degrees, or with no system, makes
/// it in `project`, the project's system ([`Inputs::project_crs`]), when that is projected.
pub fn raster_crs_in(ds: &Dataset, work: Crs, project: Option<Crs>, p: &Json, tool: &str) -> Result<(Crs, Option<String>), String> {
if work != Crs::LonLat {
return raster_crs_of(Some(work), "is held in", &ds.name, p, tool);
}
if let Some(c) = project_raster_crs(ds.crs, project, p) {
let note = format!(
"{tool}: made in {}, the project's coordinate system, with its units for the extent and sizes, as '{}' {}; set crs to EPSG:4326 to make it in degrees",
c.label(),
ds.name,
if ds.crs.is_some() { "is in degrees" } else { "has no coordinate system" },
);
return Ok((c, Some(note)));
}
raster_crs_of(ds.crs, "was read in", &ds.name, p, tool)
}

/// The project's system (`project`) for a grid made from a layer read in `layer_crs` when the run
/// names none (`p`'s `crs`): only for a layer in degrees or with no system, and only a projected
/// system this version can project to.
fn project_raster_crs(layer_crs: Option<Crs>, project: Option<Crs>, p: &Json) -> Option<Crs> {
let unnamed = p.get("crs").is_none_or(|v| v.is_null() || v.as_str().is_some_and(|t| t.trim().is_empty()));
if !unnamed || layer_raster_crs(layer_crs).is_some() {
return None;
}
layer_raster_crs(project)?.ok()
}

/// [`raster_crs`] for a layer named `name` that `how` ("was read in", "is held in") `layer_crs`.
Expand Down Expand Up @@ -5445,6 +5465,9 @@ fn kernel_density_tool(inp: &dyn Inputs, p: &Json) -> Result<ToolResult, String>
let layer_crs = if inp.work_crs() == Crs::LonLat { ds.crs } else { Some(inp.work_crs()) };
let (crs, crs_note) = if !crs_text.is_empty() {
crs_with_compatibility_note(crs_text)?
} else if let Some(c) = project_raster_crs(layer_crs, inp.project_crs(), p) {
let how = if layer_crs.is_some() { "is in degrees" } else { "has no coordinate system" };
(c, Some(format!("made in {}, the project's coordinate system, as '{}' {how}", c.label(), ds.name)))
} else if let Some(c) = layer_crs {
(c, None)
} else {
Expand Down
55 changes: 46 additions & 9 deletions crates/data/src/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -630,21 +630,58 @@ pub fn default_export_note(ds: &Dataset, path: &str) -> Option<String> {
let ext = Path::new(path).extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase();
let own = ds.crs.filter(|&c| c != Crs::LonLat && PROJECTED_FORMATS.contains(&ext.as_str()))?;
(default_export_crs(ds, &ext) == Crs::LonLat).then(|| {
let why = if !matches!(ext.as_str(), "parquet" | "geoparquet") {
"has no EPSG code and no WKT definition RustGIS can write"
} else if own.epsg() == 0 {
"has no EPSG code"
} else {
"has no PROJJSON definition RustGIS can write"
};
format!(
"{path}: the coordinate system of {} ({}) {why}, so it is written in WGS 84 (EPSG:4326); give a \"crs\" to write another",
"{path}: the coordinate system of {} ({}) {}, so it is written in WGS 84 (EPSG:4326); give a \"crs\" to write another",
ds.name,
own.label()
own.label(),
unwritable(&ext, own)
)
})
}

/// Why a system can't be written to a file with extension `ext` ([`check_projected`]).
fn unwritable(ext: &str, crs: Crs) -> &'static str {
if !matches!(ext, "parquet" | "geoparquet") {
"has no EPSG code and no WKT definition RustGIS can write"
} else if crs.epsg() == 0 {
"has no EPSG code"
} else {
"has no PROJJSON definition RustGIS can write"
}
}

/// The system an export to `path` is written in when none is asked for, and what is said of it,
/// in a project whose coordinate system is `project` (#2032 C3a): as [`default_export_crs`] and
/// [`default_export_note`] for a dataset with a system of its own, or in a project without one. A
/// dataset with none of its own, in longitude/latitude, is written in the project's where the
/// format can say it, and that is said; in WGS 84, said, when the format can't hold that system.
/// Places that system can't hold are written as any export into it writes them (at 85.05° in Web
/// Mercator, said).
pub fn default_export_in(ds: &Dataset, path: &str, project: Option<Crs>) -> (Crs, Option<String>) {
let ext = Path::new(path).extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase();
let project = project.filter(|p| {
ds.crs.is_none()
&& ds.coord_crs() == Crs::LonLat
&& *p != Crs::LonLat
&& !p.is_geocentric()
&& PROJECTED_FORMATS.contains(&ext.as_str())
});
let Some(p) = project else { return (default_export_crs(ds, &ext), default_export_note(ds, path)) };
let in_wgs84 = |why: String| {
(
Crs::LonLat,
Some(format!(
"{path}: written in WGS 84 (EPSG:4326), not the project's coordinate system ({}), as {why}; give a \"crs\" to write another",
p.label()
)),
)
};
if check_projected(&ext, p).is_err() {
return in_wgs84(format!("that {}", unwritable(&ext, p)));
}
(p, Some(format!("{path}: written in {}, the project's coordinate system, as {} has none of its own", p.label(), ds.name)))
}

/// The dataset in `crs`'s coordinates, from the system it holds them in ([`Dataset::coord_crs`]),
/// by the direct operation between the two ([`Crs::to`]). A copy as it is when it holds them in
/// `crs`. Fails on a coordinate the system can't hold, naming its feature.
Expand Down
76 changes: 61 additions & 15 deletions crates/data/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -502,23 +502,33 @@ impl Dataset {
let to = self.held_in.to(crs)?;
if !to.is_identity() {
let lonlat = self.lonlat_conversion()?;
// Before the rows are copied (by the first change), which a cancelled command needn't.
stop_when_asked(0)?;
let mut features = self.features.clone();
for (i, f) in features.iter_mut().enumerate() {
stop_when_asked(i)?;
if let Some(g) = &f.geometry {
let mut past = false;
if crs == raster::Crs::WebMercator {
g.for_each_coord(|c| past |= c.is_finite() && lonlat.point(c).is_some_and(|l| l.y.abs() > rustgis_geom::MAX_LAT));
}
let held = (!past).then(|| convert_keeping_missing(&to, g, &HeldPlaces::default())).flatten();
f.geometry = Some(
held.ok_or_else(|| format!("{}: feature {} has a place that can't be held in {}", self.name, f.id, crs.label()))?,
);
let past = |g: &Geometry| {
let mut past = false;
if crs == raster::Crs::WebMercator {
g.for_each_coord(|c| past |= c.is_finite() && lonlat.point(c).is_some_and(|l| l.y.abs() > rustgis_geom::MAX_LAT));
}
past
};
let held = |g: &Geometry| (!past(g)).then(|| convert_keeping_missing(&to, g, &HeldPlaces::default())).flatten();
// Each place is converted once, and what goes in is what was checked (a second pass
// could convert otherwise, as grids arriving meanwhile change the operations): the
// converted geometries are kept beside the rows, then put in their place, so a refusal
// or a Cancel changes nothing. Only geometry is kept twice meanwhile, never the
// attributes, and rows no one else holds aren't copied.
let mut converted = Vec::with_capacity(self.features.len());
for (i, f) in self.features.iter().enumerate() {
stop_when_asked(i)?;
converted.push(match &f.geometry {
Some(g) => Some(
held(g)
.ok_or_else(|| format!("{}: feature {} has a place that can't be held in {}", self.name, f.id, crs.label()))?,
),
None => None,
});
}
for (f, g) in self.features.iter_mut().zip(converted) {
f.geometry = g;
}
self.features = features;
}
self.held_in = crs;
Ok(())
Expand Down Expand Up @@ -1468,6 +1478,42 @@ mod tests {
assert_eq!((polar.coord_crs(), polar.crs), (raster::Crs::LonLat, None));
}

/// Holding converts the rows where they are, with no copy of rows no one else holds; a Cancel,
/// or a place the system can't hold, found among the last rows changes none of them.
#[test]
fn holding_converts_in_place_and_a_cancel_or_refusal_changes_nothing() {
use crate::progress::tests::Counted;
let utm = raster::Crs::Epsg(32632);
let made = |last_lat: f64| {
let mut ds = Dataset::new("made", GeometryType::Point, vec![]);
for i in 0..600 {
let lat = if i == 599 { last_lat } else { 48.0 };
ds.push(Some(Geometry::Point(Coord::new(11.5, lat))), vec![]);
}
ds
};
let mut ds = made(48.0);
let (held, copied) = rows_copy::with(Box::new(|| {}), || ds.hold_in(utm));
held.unwrap();
assert!(!copied && ds.coord_crs() == utm, "converted where the rows are");
let Some(Geometry::Point(c)) = ds.features[0].geometry else { panic!("no point") };
let expected = raster::Crs::LonLat.to(utm).unwrap().point(Coord::new(11.5, 48.0)).unwrap();
assert_eq!((c.x.to_bits(), c.y.to_bits()), (expected.x.to_bits(), expected.y.to_bits()));
// Cancelled at the third check (row 512), after the first rows were looked at.
let mut ds = made(48.0);
let before = ds.features.clone();
let probe = std::sync::Arc::new(Counted { after_checks: Some(2), ..Default::default() });
{
let _g = crate::progress::install(Some(probe));
assert_eq!(ds.hold_in(utm), Err(DataError::Cancelled.to_string()));
}
assert!(ds.features.shares(&before) && ds.coord_crs() == raster::Crs::LonLat);
let mut polar = made(89.0);
let before = polar.features.clone();
assert!(polar.hold_in(raster::Crs::WebMercator).unwrap_err().contains("feature 600"));
assert!(polar.features.shares(&before) && polar.coord_crs() == raster::Crs::LonLat);
}

/// A dataset held in another system converts into it, and back, at the same places; one
/// reaching past where Web Mercator ends, or a window onto a source read in place, is refused
/// and left as it was.
Expand Down
8 changes: 7 additions & 1 deletion crates/engine/src/cmd/design.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2460,7 +2460,13 @@ fn check_topology(inputs: &[TopologyInput], tol: f64) -> Result<TopologyChecked,
Err(e) if matches!(rustgis_data::DataError::of_conversion(e.clone()), rustgis_data::DataError::Cancelled) => {
return Err(cancelled());
}
Err(e) => fell_back.push(format!("{} on '{}' ('{}' in {}: {e})", i.rule.label(), i.layer, i.by_layer, crs.label())),
Err(e) => {
// Its error starts with the covering data's own name, which the map's for the
// layer may not be: named once, as the map has it.
let source = i.by.as_ref().map_or("", |b| b.name.as_str());
let rest = e.strip_prefix(&format!("{source}: ")).unwrap_or(&e);
fell_back.push(format!("{} on '{}' ('{}' in {}: {rest})", i.rule.label(), i.layer, i.by_layer, crs.label()));
}
}
}
if let (Some((crs, Some(std::borrow::Cow::Owned(converted)))), Some(original)) = (&own, &i.by) {
Expand Down
Loading
Loading