diff --git a/crates/data/tests/utm_vs_proj.rs b/crates/data/tests/utm_vs_proj.rs index 4b96b9205f..9a5560582a 100644 --- a/crates/data/tests/utm_vs_proj.rs +++ b/crates/data/tests/utm_vs_proj.rs @@ -1,9 +1,11 @@ //! The UTM series in `rustgis-geom` (Karney's Krüger series) against proj4rs, which reprojects //! rasters and layers: the same places in every zone and band, both hemispheres, the Norway -//! and Svalbard zones and the zones' edges, within a millimetre. +//! and Svalbard zones and the zones' edges, within a millimeter. And UPS, the grid of the polar +//! areas, against proj4rs's polar stereographic at UPS's scale of 0.994 and 2,000,000 m false +//! origin (EPSG:5041 north, 5042 south), at random polar places and at the poles. use rustgis_data::raster::Crs; -use rustgis_geom::{Coord, utm}; +use rustgis_geom::{Coord, ups, utm}; /// A small deterministic generator (no dependency). struct Lcg(u64); @@ -96,3 +98,42 @@ fn standard_zones_bands_and_exceptions_agree_with_proj4rs() { assert!((by_code.x - want.x).abs() < 1e-6 && (by_code.y - want.y).abs() < 1e-6, "EPSG:{epsg}"); } } + +fn ups_proj(north: bool) -> rustgis_data::raster::Transformer { + let lat = if north { 90 } else { -90 }; + Crs::parse(&format!("+proj=stere +lat_0={lat} +lat_ts={lat} +k=0.994 +x_0=2000000 +y_0=2000000 +datum=WGS84 +units=m +no_defs")) + .unwrap() + .transformer() + .unwrap() +} + +/// Compares one polar place both ways; returns the largest difference in meters. +fn compare_ups(t: &rustgis_data::raster::Transformer, p: Coord, north: bool) -> f64 { + let (e, n) = ups::to_ups_in_zone(p, north).unwrap(); + let want = t.from_lonlat(p).unwrap(); + let dm = (e - want.x).abs().max((n - want.y).abs()); + assert!(dm < 1e-3, "north {north} at {p:?}: ours {e} {n}, proj4rs {} {}", want.x, want.y); + let back = ups::from_ups(north, want.x, want.y).unwrap(); + let theirs = t.to_lonlat(want).unwrap(); + // Compare on the ground: near the pole a millimeter is many degrees of longitude. + let (x, y) = ups::to_ups_in_zone(back, north).unwrap(); + let (tx, ty) = ups::to_ups_in_zone(theirs, north).unwrap(); + assert!((x - tx).abs().max((y - ty).abs()) < 1e-3, "north {north} at {p:?}: ours {back:?}, proj4rs {theirs:?}"); + dm +} + +#[test] +fn random_polar_places_agree_with_proj4rs() { + let mut r = Lcg(2026); + let (north_t, south_t) = (ups_proj(true), ups_proj(false)); + let mut worst = 0.0f64; + for _ in 0..5_000 { + let lon = -180.0 + r.next() * 360.0; + worst = worst.max(compare_ups(&north_t, Coord::new(lon, 84.0 + r.next() * 6.0), true)); + worst = worst.max(compare_ups(&south_t, Coord::new(lon, -80.0 - 1e-9 - r.next() * (10.0 - 2e-9)), false)); + } + for (p, north) in [(Coord::new(0.0, 90.0), true), (Coord::new(0.0, -90.0), false), (Coord::new(180.0, 84.0), true)] { + worst = worst.max(compare_ups(if north { &north_t } else { &south_t }, p, north)); + } + assert!(worst < 1e-3, "worst {worst} m"); +} diff --git a/crates/engine/src/cmd/search.rs b/crates/engine/src/cmd/search.rs index 952f66737d..47ba56cd8f 100644 --- a/crates/engine/src/cmd/search.rs +++ b/crates/engine/src/cmd/search.rs @@ -17,7 +17,7 @@ pub fn commands() -> Vec { vec![ // Not a view command: going to a feature selects it. C::new("map.search", "Search", "Map", search_cmd).inputs(search_inputs).roles(&[]).effects(crate::policy::Effects::NONE).params( - r#"{"query": "a latitude and longitude (40.7, -74.0; 40°42'N 74°0'W), a UTM position (33U 412345 5523456; 33 north 412345 5523456) or an MGRS reference (33UVP1234523456; 33U VP 12345 23456), a layer, a bookmark or a value in a layer's table", "limit"?: 1–50, "go"?: true (the first hit) | index}"#, + r#"{"query": "a latitude and longitude (40.7, -74.0; 40°42'N 74°0'W), a UTM position (33U 412345 5523456; 33 north 412345 5523456) or an MGRS reference (33UVP1234523456; 33U VP 12345 23456), north of 84° N or south of 80° S UPS (north 2077146 1562481) or polar MGRS (Z AC 77146 62481; ZAC7714662481), a layer, a bookmark or a value in a layer's table. Polar text that may be a name or a code (BAG123456) lists table hits first and answers coordinateMayBeText", "limit"?: 1–50, "go"?: true (the first hit) | index}"#, ), ] } @@ -136,9 +136,15 @@ pub struct Results { /// that doesn't hold its northing, square letters the zone doesn't use, `S` that may mean /// south); `None` when it isn't written as one, or reads. pub grid_error: Option, + /// Whether the coordinate among the hits was read from text that may as well be a name or a + /// code: a polar (UPS) reference, which starts with a letter (`BAG123456`), unless it is + /// plainly a place ([`plainly_polar_place`]). The search box still + /// offers to look the text up as a place. + pub coordinate_may_be_text: bool, } -/// Searches the active map for `query`: a coordinate first, then layers, bookmarks and features. +/// Searches the active map for `query`: a coordinate first, then layers, bookmarks and features; a +/// polar reference that may be a name or a code comes after them (see [`Results`]). pub fn search(s: &Session, query: &str, limit: usize) -> Results { search_map(s.map(), query, limit) } @@ -154,13 +160,19 @@ fn search_map(map: &rustgis_map::Map, query: &str, limit: usize) -> Results { // zone and band) isn't looked for in the tables; two whole numbers (an id, years, a range) // may be either, and so may a bare 100 km MGRS square, which names Sentinel-2's tiles (33UVP); // an MGRS reference with digits is plainly a coordinate. UTM and MGRS are the Earth's grids, - // so on another body's map they name no place. + // so on another body's map they name no place. Polar (UPS) references and positions start + // with a letter, as names and codes do (`BAG123456`, `A ST 12`): read_grid_reference reads + // them only as references are written ([`polar_form`]). Unless plainly a + // place ([`plainly_polar_place`]), the tables are still searched and the + // place comes after their hits, so a feature named so is found first. let mut plainly_coordinate = false; + let mut polar_place = None; if let Some(c) = parse_lat_lon(&q) { out.hits.push(Hit::Coordinate { lon: c.x, lat: c.y }); plainly_coordinate = q.chars().any(|c| matches!(c, '.' | '°' | 'º' | '\'' | '′' | '"' | '″') || c.is_alphabetic()); } else if map.body().is_earth() { match read_grid_reference(&q) { + Ok(c) if letter_led(&q) && !plainly_polar_place(&q) => polar_place = Some(c), Ok(c) => { out.hits.push(Hit::Coordinate { lon: c.x, lat: c.y }); plainly_coordinate = rustgis_geom::parse_mgrs(&q).map_or(true, |m| m.digits > 0); @@ -237,7 +249,14 @@ fn search_map(map: &rustgis_map::Map, query: &str, limit: usize) -> Results { } } } - out.hits.truncate(limit.max(1)); + let limit = limit.max(1); + // After every other hit, and only when they leave room, so no feature named like the + // reference is pushed out and `go` with any index still reaches the same feature. + if let Some(c) = polar_place.filter(|_| out.hits.len() < limit) { + out.hits.push(Hit::Coordinate { lon: c.x, lat: c.y }); + out.coordinate_may_be_text = true; + } + out.hits.truncate(limit); out } @@ -392,6 +411,10 @@ fn search_cmd(s: &mut Session, p: &Value) -> CmdResult { if let Some(e) = r.grid_error { out["gridError"] = json!(e.to_string()); } + if r.coordinate_may_be_text { + // The coordinate hit came from polar grid text that may as well be a name or a code. + out["coordinateMayBeText"] = json!(true); + } Ok(out) } @@ -408,18 +431,133 @@ pub fn parse_grid_reference(text: &str) -> Option { /// refused: [`GridError::Syntax`] for text written as neither form, otherwise the reason of the /// form it was written in. A 100 km square alone written with spaces (`5 Ave`, `4K TV`) is a /// number and a word as often as a reference, so one that names no square is -/// [`GridError::Syntax`] too; written as one word (`38TMJ`), it says why. +/// [`GridError::Syntax`] too; written as one word (`38TMJ`), it says why. A polar reference has +/// no zone number, so text that starts with a letter is read as one only when written as +/// references are ([`polar_form`]); UPS positions (`north 2077146 1562481`) are +/// read as [`rustgis_geom::parse_utm`] reads them. pub fn read_grid_reference(text: &str) -> Result { - match rustgis_geom::parse_mgrs(text) { + let mgrs = if !letter_led(text) { + rustgis_geom::parse_mgrs(text) + } else { + match polar_form(text) { + // As the readout writes it: plainly meant as a reference, so it says why it names no + // place. + // The square alone (`Z AC`) is a letter and a word as often (`A TO`), as `5 Ave` is: + // read if it names a square, text if not. + Some(PolarForm::Readout) if !text.bytes().any(|b| b.is_ascii_digit()) => { + rustgis_geom::parse_mgrs(text).map_err(|_| GridError::Syntax) + } + Some(PolarForm::Readout) => rustgis_geom::parse_mgrs(text), + // Compact forms look like codes too (`BAG123456`): read if they name a place, text if not. + Some(PolarForm::Compact) => rustgis_geom::parse_mgrs(text).map_err(|_| GridError::Syntax), + None => Err(GridError::Syntax), + } + }; + match mgrs { Ok(m) => m.centre(), Err(mgrs) => match rustgis_geom::parse_utm(text) { Err(GridError::Syntax) if spaced_square(text) => Err(GridError::Syntax), Err(GridError::Syntax) => Err(mgrs), + // A UPS position that names no place after GeographicLib's `n` or `s` may be a State + // Plane pair (`N 1350000 1350000`): text. After `north`, `south` or a half's letter + // (`Y 2392768 1607232`, two numbers in the lettered area) it says why. + Err(_) if letter_led(text) && !led_by_zone_word(text) && !led_by_half_letter(text) => Err(GridError::Syntax), utm => utm, }, } } +/// Whether text starts with a letter, as a polar (UPS) MGRS reference or position does; no +/// other grid reference does. +fn letter_led(text: &str) -> bool { + text.trim_start().starts_with(|c: char| c.is_ascii_alphabetic()) +} + +/// Whether polar text is plainly a place rather than a name or a code: any UPS position +/// [`rustgis_geom::parse_ups`] reads, led by the zone spelled out (`north 2077146 1562481`; +/// GeographicLib's `n …` may be text, as `N 1400000 2000000` is a State Plane pair) or the half's +/// letter (`Z 2077146 1562481`, `Y, 1735147, 2243078`), or polar MGRS written as the +/// readout writes it, spaced, in capitals, to the meter (`Z AC 77146 62481`). +fn plainly_polar_place(text: &str) -> bool { + let text = text.trim(); + // UPS with the zone or the half's letter before two numbers in the lettered area + // (`Y, 1735147, 2243078`) is plainly a position: no name or code is written that way. + if led_by_zone_word(text) { + return true; + } + if led_by_half_letter(text) && rustgis_geom::parse_ups(text).is_ok() { + return true; + } + polar_form(text) == Some(PolarForm::Readout) + && matches!(text.split_whitespace().collect::>().as_slice(), [_, _, e, n] if e.len() == 5 && n.len() == 5) +} + +/// The first word of text, in lowercase; it may be followed by a comma, as +/// [`rustgis_geom::parse_ups`] reads it (`north, 2077146, 1562481`). +fn first_word(text: &str) -> String { + text.trim().split(|c: char| c.is_whitespace() || c == ',').next().unwrap_or("").to_ascii_lowercase() +} + +/// Whether text starts with the UPS zone spelled out, `north` or `south`. +fn led_by_zone_word(text: &str) -> bool { + matches!(first_word(text).as_str(), "north" | "south") +} + +/// Whether text starts with a polar half's letter alone, `Y`, `Z`, `A` or `B`, as NGA writes a +/// UPS position (`Y, 1735147, 2243078`). +fn led_by_half_letter(text: &str) -> bool { + matches!(first_word(text).as_str(), "y" | "z" | "a" | "b") +} + +/// How letter-led text is written as a polar MGRS reference, if it is. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum PolarForm { + /// As the readout writes it: the half's letter, a space and the square's letters, in + /// capitals, then no digits or two equal groups (`Z AH`, `Z AH 12 34`). + Readout, + /// As one word with at least six digits attached, 100 m or finer (`ZAC7714662481`, any + /// case), or the three letters in capitals before two equal groups of at least three digits + /// (`ZFD 927 072`). + Compact, +} + +/// How letter-led text is written as a polar MGRS reference ([`PolarForm`]), rather than +/// as a word or code that happens to read as one (`ATL`, `Bay 12`, the flight `BAW1234`, +/// `A St 12`, `Apt 123456`); `None` for those. +fn polar_form(text: &str) -> Option { + let mut chars = text.trim().chars(); + let half = chars.next()?; + let rest = chars.as_str(); + let spaced = rest.starts_with(char::is_whitespace); + let rest = rest.trim_start(); + let letters: Vec = rest.chars().take(2).collect(); + if letters.len() != 2 || !letters.iter().all(char::is_ascii_alphabetic) { + return None; + } + let capitals = half.is_ascii_uppercase() && letters.iter().all(char::is_ascii_uppercase); + // The two letters are ASCII, so the digits start two bytes on. + let after = rest.get(2..).unwrap_or(""); + let digits = |s: &str| s.bytes().all(|b| b.is_ascii_digit()); + let groups: Vec<&str> = after.split_whitespace().collect(); + if spaced { + // The readout writes no digits (100 km) or two equal groups; a single number after a + // spaced, capitalized word is a house number (`A ST 12`, `Z ST 12`). + let as_written = match groups.as_slice() { + [] => true, + [e, n] => digits(e) && digits(n) && e.len() == n.len(), + _ => false, + }; + return (capitals && as_written).then_some(PolarForm::Readout); + } + let attached = after.starts_with(|c: char| c.is_ascii_digit()); + let compact = match groups.as_slice() { + [run] if attached => digits(run) && run.len() >= 6, + [e, n] => capitals && digits(e) && digits(n) && e.len() == n.len() && e.len() >= 3, + _ => false, + }; + compact.then_some(PolarForm::Compact) +} + /// Whether `text` has spaces and no digits after its leading number: written so, an MGRS /// reference is a 100 km square alone. fn spaced_square(text: &str) -> bool { @@ -698,7 +836,7 @@ mod tests { "38SAB4414084706", "38SMB441408470", "38TMB4414084706", - // Polar (UPS) references aren't read. + // A polar (UPS) letter after a zone number: UPS has no zone number. "38Z 444141 3684706", "38ZMB4414084706", "99X 1 2", @@ -795,6 +933,168 @@ mod tests { assert!(matches!(search(&s, "38SMB4414084706", 50).hits.first(), Some(Hit::Coordinate { .. }))); } + /// In the polar areas the grid is UPS: its MGRS references (no zone number) and positions are + /// found, while three letters alone (a 100 km square, or a word) aren't read as a reference. + #[test] + fn polar_grid_references_are_found() { + let s = Session::new(crate::sample::world_project()); + for q in ["ZFD9276707232", "Z FD 92767 07232", "zfd9276707232", "north 2392768 1607232", "Z 2392768 1607232"] { + match search(&s, q, 50).hits.first() { + Some(Hit::Coordinate { lon, lat }) => { + assert!((lon - 45.0).abs() < 1e-3 && (lat - 85.0).abs() < 1e-3, "{q}: {lon} {lat}") + } + other => panic!("{q}: {other:?}"), + } + } + match search(&s, "Y, 1735147, 2243078", 50).hits.first() { + Some(Hit::Coordinate { lon, lat }) => assert!(*lon < 0.0 && *lat > 86.0, "{lon} {lat}"), + other => panic!("{other:?}"), + } + // Words and street names, with or without numbers, are text: no coordinate, no grid error. + for q in [ + "Bay 12", + "Ban 12", + "Bad 34", + "Zag 56", + "Ave 12", + "Zoo 12", + "Elm 123", + "A 10 20", + "A1 12", + "B 12, 34", + "zap", + "ban", + "Box", + "Berlin", + "Bay", + "Zanzibar", + "Y", + "north 10 20", + "BAW1234", + "YUL1234", + "BAN12", + "Bay 12 34", + "Apt 12 14", + "Z Ah", + "B Ag", + "z ah", + // Codes and acronyms in capitals: airports, not polar squares. + "ATL", + "AUS", + "YUL", + "BBC", + "ABC", + "BRU", + "ZAH", + "BAN", + // A word and a long number, and phrases with digits. + "Apt 123456", + "Bay 123456", + "Bay 123 456", + "Box 123456", + "A St 12", + "a st 12", + "B St 12", + "ZAC 7714662481", + // All-caps addresses: a house number after a spaced word, not the readout's two groups. + "A ST 12", + "Z ST 12", + "B ST 5", + "A ST 123", + ] { + let r = search(&s, q, 50); + assert!(!r.hits.iter().any(|h| matches!(h, Hit::Coordinate { .. })), "{q}: {r:?}"); + assert_eq!(r.grid_error, None, "{q}"); + } + // A 100 km polar square written as the readout writes it, spaced, reads back; like + // `33UVP` it may also be a name, so the tables are still searched. So do the other + // written forms of a reference. + for q in ["Z AH", "B AN", "Z AH 12 34", "ZAH1234512345", "zac7714662481", "ZFD 927 072"] { + let r = search(&s, q, 50); + assert!(matches!(r.hits.first(), Some(Hit::Coordinate { .. })), "{q}: {r:?}"); + } + // A reference written as one, but with fewer than six digits as one word, is text: the + // flight BAW1234 looks the same as ZAH1234. + assert!(!search(&s, "ZAH1234", 50).hits.iter().any(|h| matches!(h, Hit::Coordinate { .. }))); + // A polar reference written as the readout writes it that names no place says why; a + // compact one may be a code (`ABC123456`), so it says nothing. + assert_eq!(search(&s, "Z DA 12345 12345", 50).grid_error, Some(GridError::Square)); + assert_eq!(search(&s, "Y RA 12345 12345", 50).grid_error, Some(GridError::OutsideZone)); + for q in ["ZDA1234512345", "YRA1234512345", "ABC123456", "YAA123456"] { + assert_eq!(search(&s, q, 50).grid_error, None, "{q}"); + } + // The square alone is a letter and a word as often, as `5 Ave` is: one that names no + // square (`A TO`, row O isn't used) is text and says nothing; one that names a square + // (`A ST`) is found but may be text. + for q in ["A TO", "Z DA", "Y RA"] { + let r = search(&s, q, 50); + assert!(!r.hits.iter().any(|h| matches!(h, Hit::Coordinate { .. })), "{q}: {r:?}"); + assert_eq!(r.grid_error, None, "{q}"); + } + assert!(search(&s, "A ST", 50).coordinate_may_be_text); + } + + /// A code that also reads as a polar reference (`BAG123456` is B AG 123 456, a place in + /// Antarctica) is still looked for in the tables, and a feature named so comes first, so + /// Enter or `go` goes to it rather than to the pole. + #[test] + fn features_named_like_polar_references_come_first() { + let mut s = Session::new(crate::sample::world_project()); + s.run("layer.addDataText", &json!({"fileName": "parts.csv", "text": "part,lon,lat\nBAG123456,10.0,50.0\n"})).unwrap(); + for q in ["BAG123456", "bag123456"] { + let r = search(&s, q, 50); + assert!(matches!(r.hits.first(), Some(Hit::Feature { value, .. }) if value == "BAG123456"), "{q}: {r:?}"); + assert!(r.hits.iter().any(|h| matches!(h, Hit::Coordinate { .. })), "{q}: {r:?}"); + // With room for one hit, it is the feature, not the place. + let one = search(&s, q, 1); + assert!(matches!(one.hits.as_slice(), [Hit::Feature { .. }]), "{q}: {one:?}"); + } + // Two features named so fill a limit of two: both are kept, ahead of any place. + s.run("layer.addDataText", &json!({"fileName": "more.csv", "text": "part,lon,lat\nBAG123456,11.0,51.0\n"})).unwrap(); + let two = search(&s, "BAG123456", 2); + assert!(matches!(two.hits.as_slice(), [Hit::Feature { .. }, Hit::Feature { .. }]), "{two:?}"); + // `go` goes to the feature, and the answer says the place may be text. + let v = s.run("map.search", &json!({"query": "BAG123456", "limit": 1, "go": true})).unwrap(); + assert!(v["hits"][0]["kind"] == "feature", "{v}"); + let v = s.run("map.search", &json!({"query": "BAG123456"})).unwrap(); + assert_eq!(v["coordinateMayBeText"], json!(true), "{v}"); + // With no feature named so, the place is the first hit, and within the limit; it may still + // be text, so the search box offers places too. A UTM reference is plainly a coordinate. + let r = search(&s, "ZAC7714662481", 1); + assert!(matches!(r.hits.as_slice(), [Hit::Coordinate { .. }]) && r.coordinate_may_be_text); + assert!(!search(&s, "38SMB4414084706", 50).coordinate_may_be_text); + // At limit 1 with a feature, the answer doesn't claim a place it left out. + let v = s.run("map.search", &json!({"query": "BAG123456", "limit": 1})).unwrap(); + assert!(v.get("coordinateMayBeText").is_none(), "{v}"); + // Pasted from the readout, a polar place is plainly a coordinate: first, no place search, + // and the tables aren't searched (a value written the same is not a hit). + s.run("layer.addDataText", &json!({"fileName": "odd.csv", "text": "v,lon,lat\nZ AC 77146 62481,1.0,1.0\n"})).unwrap(); + for q in [ + "north 2077146 1562481", + "South 2096454 1452981", + "north, 2077146, 1562481", + "Z AC 77146 62481", + "Z 2077146 1562481", + "Y, 1735147, 2243078", + ] { + let r = search(&s, q, 50); + assert!(matches!(r.hits.as_slice(), [Hit::Coordinate { .. }]) && !r.coordinate_may_be_text, "{q}: {r:?}"); + } + // Shorter than the readout writes it, or GeographicLib's `n …` (a State Plane pair looks the + // same), it may still be text. + for q in ["Z AC 7714 6248", "Z AC", "ZAC7714662481", "n 2077146 1562481", "N 2000000 1500000"] { + assert!(search(&s, q, 50).coordinate_may_be_text, "{q}"); + } + // One that names no UPS place after `n` (a State Plane pair near 81.8° N) says nothing; + // after `north` or a half's letter (Y east of 2,000,000 m is Z's) it says why. + assert_eq!(search(&s, "N 1350000 1350000", 50).grid_error, None); + for q in ["north 1350000 1350000", "Y 2392768 1607232", "a 2100000 1500000"] { + let r = search(&s, q, 50); + assert_eq!(r.grid_error, Some(GridError::OutsideZone), "{q}"); + assert!(!r.hits.iter().any(|h| matches!(h, Hit::Coordinate { .. })), "{q}"); + } + } + #[test] fn non_coordinates_are_refused() { for t in diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index 100dc87cd1..dd1b42cd3b 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -1,5 +1,5 @@ //! L0: coordinates, extents, the Web Mercator projection, geodesic measurement, map scale, and -//! UTM and MGRS coordinates ([`utm`]). +//! UTM and MGRS coordinates ([`utm`]), and UPS for the polar areas ([`ups`]). //! //! Everything here is plain math with no I/O. Longitude/latitude are WGS 84 degrees; projected //! coordinates are Web Mercator meters (EPSG:3857), which [`lonlat_to_plane`] continues beyond @@ -10,12 +10,14 @@ pub mod body; pub mod eqc; pub mod sinusoidal; pub mod triangulate; +pub mod ups; pub mod utm; pub mod world; pub use body::{BODIES, Body}; pub use eqc::EquidistantCylindrical; pub use sinusoidal::Sinusoidal; +pub use ups::{Ups, format_ups, from_ups, parse_ups, to_ups}; pub use utm::{GridError, Mgrs, Utm, format_mgrs, format_utm, parse_mgrs, parse_utm, to_mgrs, to_utm}; use std::sync::LazyLock; diff --git a/crates/geom/src/ups.rs b/crates/geom/src/ups.rs new file mode 100644 index 0000000000..fdf57b2577 --- /dev/null +++ b/crates/geom/src/ups.rs @@ -0,0 +1,491 @@ +//! WGS 84 Universal Polar Stereographic (UPS) coordinates: the grid of the polar areas, north of +//! 84° N and south of 80° S, where the UTM zones stop, and the 100 km squares MGRS uses there. +//! +//! The grid follows NGA.SIG.0012 (2014-03-25), "The Universal Grids and the Transverse Mercator +//! and Polar Stereographic Map Projections": +//! +//! - polar stereographic on WGS 84, with a scale of exactly 0.994 at the pole and a false easting +//! and false northing of 2,000,000 m (§10.1); +//! - the projection of eqs. (18)–(20) in §8, placed as eqs. (21) and (22) in §9.1 say: in both +//! zones the easting grows toward 90° E, and the northing grows toward 180° in the north and +//! toward 0° in the south, so the 2,000,000 m easting runs along the 0° and 180° meridians +//! (DMA TM 8358.2, §3-2.4); +//! - north UPS for latitudes of 84° N and more, south UPS for latitudes south of 80° S (§10.4): +//! 84° N itself is UPS, 80° S itself is UTM; +//! - MGRS in the polar areas (§§11.9–11.13, and NGA.STND.0037 §3-2c): no zone number, a letter for +//! the half (Y for western longitudes and Z for eastern ones in the north, A and B in the +//! south; the 0° and 180° meridians, at an easting of 2,000,000 m, are Z and B, by §§11.10 and +//! 11.11, where square 20 is ZA and BA), then the 100 km square's column and row letters, and +//! the digits truncated to the precision. +//! +//! The conformal latitude is the one in [`crate::utm`] (Karney 2011, eqs. 7–9 and 19–21), which +//! gives the same values as §2.8 and §2.9's PhiToChi and ChiToPhi. + +use std::fmt; +use std::sync::LazyLock; + +use crate::Coord; +use crate::utm::{ + GridError, MAX_REF_CHARS, ROUNDING_DEG, WGS84_A, conformal_tan, easting_and_northing, eccentricity, geographic_tan, wrap, +}; + +/// The northern limit of the UTM zones, where north UPS begins (degrees); 84° N itself is UPS. +pub const UPS_NORTH_FROM: f64 = crate::utm::UTM_MAX_LAT; +/// The southern limit of the UTM zones (degrees); south UPS is south of it, 80° S itself is UTM. +pub const UPS_SOUTH_OF: f64 = crate::utm::UTM_MIN_LAT; + +/// UPS's scale at the pole, exactly (NGA.SIG.0012 §10.1). +const K0: f64 = 0.994; +/// The false easting and false northing: the pole's grid coordinates (meters). +const FALSE_ORIGIN: f64 = 2_000_000.0; +/// MGRS 100 km square side (meters). +const SQUARE: f64 = 100_000.0; +/// The farthest from the pole (meters) an easting and northing are converted. Every distance maps +/// to some latitude (about 2° on the zone's side of the equator at 12,000 km, 25° beyond it at +/// 20,000 km); past this the numbers can only be typing errors, so they are refused. +const MAX_RADIUS: f64 = 20_000_000.0; + +/// k90 of NGA.SIG.0012 eq. (19): √(1 − e²) · exp(e · artanh e). +static K90: LazyLock = LazyLock::new(|| { + let e = eccentricity(); + (1.0 - e * e).sqrt() * (e * e.atanh()).exp() +}); + +/// The north zone's 100 km square column letters (band, column) from an easting of 1,300,000 m, +/// and its row letters from a northing of 1,300,000 m (NGA.SIG.0012 §11.10). +const NORTH_COLUMNS: [&[u8; 2]; 14] = [b"YR", b"YS", b"YT", b"YU", b"YX", b"YY", b"YZ", b"ZA", b"ZB", b"ZC", b"ZF", b"ZG", b"ZH", b"ZJ"]; +const NORTH_ROWS: &[u8; 14] = b"ABCDEFGHJKLMNP"; +/// The first 100 km square of the north zone's lettering, along either axis. +const NORTH_FIRST: i64 = 13; +/// The south zone's column letters from an easting of 800,000 m, and its row letters from a +/// northing of 800,000 m (NGA.SIG.0012 §11.11). +const SOUTH_COLUMNS: [&[u8; 2]; 24] = [ + b"AJ", b"AK", b"AL", b"AP", b"AQ", b"AR", b"AS", b"AT", b"AU", b"AX", b"AY", b"AZ", b"BA", b"BB", b"BC", b"BF", b"BG", b"BH", b"BJ", + b"BK", b"BL", b"BP", b"BQ", b"BR", +]; +const SOUTH_ROWS: &[u8; 24] = b"ABCDEFGHJKLMNPQRSTUVWXYZ"; +/// The first 100 km square of the south zone's lettering, along either axis. +const SOUTH_FIRST: i64 = 8; + +/// sin and cos of an angle in degrees, exact at multiples of 90°: on the 0° and 180° meridians the +/// easting is exactly 2,000,000 m, so a place there is in the Z or B half, as MGRS requires, and +/// longitude −180° falls on the same side as 180°. +fn sincosd(deg: f64) -> (f64, f64) { + let q = (deg / 90.0).round(); + let (s, c) = (deg - 90.0 * q).to_radians().sin_cos(); + match (q as i64).rem_euclid(4) { + 0 => (s, c), + 1 => (c, -s), + 2 => (-s, -c), + _ => (-c, s), + } +} + +/// The distance on the grid from the zone's own pole to a latitude measured toward that pole, in +/// meters: 2 a k0 / k90 · cos χ / (1 + sin χ), χ the conformal latitude (NGA.SIG.0012 eqs. 18 and +/// 21). cos χ / (1 + sin χ) is 1 / (τ′ + √(1 + τ′²)), written as √(1 + τ′²) − τ′ when τ′ is +/// negative so that it doesn't cancel. `None` at the other pole, where the projection has no +/// place. +fn polar_radius(lat: f64) -> Option { + if lat >= 90.0 { + return Some(0.0); + } + if lat <= -90.0 { + return None; + } + let taup = conformal_tan(lat.to_radians().tan()); + let h = taup.hypot(1.0); + let t = if taup >= 0.0 { 1.0 / (h + taup) } else { h - taup }; + let rho = 2.0 * WGS84_A * K0 / *K90 * t; + rho.is_finite().then_some(rho) +} + +/// The latitude, measured toward the zone's own pole, at a distance from that pole on the grid: +/// with r = ρ k90 / (2 a k0), tan χ = (1 − r²) / 2r (NGA.SIG.0012 eq. 20), then the latitude from +/// the conformal one. +fn latitude_at(rho: f64) -> Option { + if rho == 0.0 { + return Some(90.0); + } + let r = rho * *K90 / (2.0 * WGS84_A * K0); + let lat = geographic_tan((1.0 - r * r) / (2.0 * r))?.atan().to_degrees(); + lat.is_finite().then_some(lat) +} + +/// Which UPS zone a latitude lies in: `Some(true)` for north UPS (84° N to the pole), +/// `Some(false)` for south UPS (south of 80° S), `None` in the UTM latitudes, past a pole or for +/// a non-finite latitude. +pub fn ups_zone(lat: f64) -> Option { + if (UPS_NORTH_FROM..=90.0).contains(&lat) { + Some(true) + } else if (-90.0..UPS_SOUTH_OF).contains(&lat) { + Some(false) + } else { + None + } +} + +/// A place in UPS: the zone (north or south) and the easting and northing in meters; the pole is +/// at 2,000,000 m, 2,000,000 m. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Ups { + pub north: bool, + pub easting: f64, + pub northing: f64, +} + +impl Ups { + /// The zone spelled out, as the readout writes it: `north` or `south`. + pub fn hemisphere(&self) -> &'static str { + if self.north { "north" } else { "south" } + } +} + +impl fmt::Display for Ups { + /// `north 2392768 1607232`, `south 2096454 1452981`: the zone, then the easting and northing + /// rounded to the meter, as GeographicLib's `GeoConvert -u -l` writes UPS (UPS has no zone + /// number). + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{} {:.0} {:.0}", self.hemisphere(), self.easting.round(), self.northing.round()) + } +} + +/// A place's UPS coordinates; `None` in the UTM latitudes (80° S up to 84° N) and for a non-finite +/// place. +pub fn to_ups(c: Coord) -> Option { + // ups_zone refuses a non-finite latitude, and to_ups_in_zone a non-finite longitude. + let north = ups_zone(c.y)?; + let (easting, northing) = to_ups_in_zone(c, north)?; + Some(Ups { north, easting, northing }) +} + +/// A place's easting and northing in a UPS zone, as a projection to that zone works (EPSG:5041 +/// north, 5042 south), at any latitude but the other pole. `None` for a non-finite place, a +/// latitude past ±90° or the other pole. +pub fn to_ups_in_zone(c: Coord, north: bool) -> Option<(f64, f64)> { + if !c.is_finite() || c.y.abs() > 90.0 { + return None; + } + let rho = polar_radius(if north { c.y } else { -c.y })?; + let (sin, cos) = sincosd(wrap(c.x)); + let x = FALSE_ORIGIN + rho * sin; + let y = if north { FALSE_ORIGIN - rho * cos } else { FALSE_ORIGIN + rho * cos }; + (x.is_finite() && y.is_finite()).then_some((x, y)) +} + +/// The place (longitude, latitude) at an easting and northing in a UPS zone. The pole itself gets +/// longitude 0°. `None` for non-finite values, or an easting and northing more than 20,000 km from +/// the pole, which name no place. +pub fn from_ups(north: bool, easting: f64, northing: f64) -> Option { + if !easting.is_finite() || !northing.is_finite() { + return None; + } + let (dx, dy) = (easting - FALSE_ORIGIN, northing - FALSE_ORIGIN); + let rho = dx.hypot(dy); + if rho > MAX_RADIUS { + return None; + } + let lon = if rho == 0.0 { + 0.0 + } else if north { + dx.atan2(-dy).to_degrees() + } else { + dx.atan2(dy).to_degrees() + }; + let lat = latitude_at(rho)?; + Some(Coord::new(wrap(lon), if north { lat } else { -lat })) +} + +/// A place as `north 2392768 1607232` (see [`Ups`]'s `Display`); `None` in the UTM latitudes. +pub fn format_ups(c: Coord) -> Option { + to_ups(c).map(|u| u.to_string()) +} + +/// A zone's lettering: its column letter pairs, its row letters, and the index of its first +/// 100 km square along either axis (NGA.SIG.0012 §§11.10 and 11.11). +fn lettering(north: bool) -> (&'static [&'static [u8; 2]], &'static [u8], i64) { + if north { (&NORTH_COLUMNS, NORTH_ROWS, NORTH_FIRST) } else { (&SOUTH_COLUMNS, SOUTH_ROWS, SOUTH_FIRST) } +} + +/// The MGRS letters of the 100 km square holding a UPS easting and northing (whole meters): the +/// half's letter (Y, Z, A or B), then the square's column and row letters. `None` outside the +/// lettered area of the zone (NGA.SIG.0012 §§11.10 and 11.11). +pub(crate) fn square_letters(north: bool, easting: i64, northing: i64) -> Option<(char, char, char)> { + let (col, row) = (easting.div_euclid(100_000), northing.div_euclid(100_000)); + let (columns, rows, first) = lettering(north); + let pair = columns.get(usize::try_from(col - first).ok()?)?; + let row = rows.get(usize::try_from(row - first).ok()?)?; + Some((char::from(pair[0]), char::from(pair[1]), char::from(*row))) +} + +/// The zone and the south-west corner (easting, northing in meters) of the 100 km square that a +/// half's letter and the square's letters name. [`GridError::Band`] for a letter that isn't a +/// polar half, [`GridError::Square`] for square letters that half doesn't use. +pub(crate) fn square_origin(half: char, column: char, row: char) -> Result<(bool, f64, f64), GridError> { + let north = match half { + 'Y' | 'Z' => true, + 'A' | 'B' => false, + _ => return Err(GridError::Band), + }; + let (columns, rows, first) = lettering(north); + let col = columns.iter().position(|p| char::from(p[0]) == half && char::from(p[1]) == column).ok_or(GridError::Square)?; + let row = rows.iter().position(|r| char::from(*r) == row).ok_or(GridError::Square)?; + let at = |i: usize| (first + i as i64) as f64 * SQUARE; + Ok((north, at(col), at(row))) +} + +/// Whether a UPS cell (south-west corner `e0`, `n0`, side `cell`) reaches into its zone: the +/// point of the cell nearest the pole lies at 84° N or more in the north, south of 80° S in the +/// south, give or take `slop_deg` for rounding. Squares at the corners of a zone's lettering lie +/// wholly in the UTM latitudes, and a reference there names no UPS place. +pub(crate) fn cell_reaches_zone(north: bool, e0: f64, n0: f64, cell: f64, slop_deg: f64) -> bool { + let near_pole = |lo: f64| FALSE_ORIGIN.clamp(lo, lo + cell); + from_ups(north, near_pole(e0), near_pole(n0)).is_some_and(|p| in_zone(north, p.y, slop_deg)) +} + +/// Whether a latitude lies in a UPS zone (84° N or more, or south of 80° S), give or take +/// `slop_deg`. +fn in_zone(north: bool, lat: f64, slop_deg: f64) -> bool { + if north { lat >= UPS_NORTH_FROM - slop_deg } else { lat < UPS_SOUTH_OF + slop_deg } +} + +/// Whether a typed easting lies in a polar half's side of its zone: Y and A west of the +/// 2,000,000 m easting, Z and B on it and east of it (NGA.STND.0037 App. B-5b; the line itself +/// is Z and B by NGA.SIG.0012 §§11.10 and 11.11, where square 20 is ZA and BA). Full +/// coordinates are written rounded to the meter (NGA.STND.0037 App. A-2), so a place in Y or A +/// just west of the line may read 2,000,000: Y and A accept exactly that whole number too. +pub(crate) fn easting_in_half(half: char, easting: f64) -> bool { + match half { + 'Y' | 'A' => easting <= FALSE_ORIGIN, + 'Z' | 'B' => easting >= FALSE_ORIGIN, + _ => false, + } +} + +/// Whether an easting and northing lie in their zone's lettered area, where every UPS position +/// in the zone falls: 1,300,000 m up to 2,700,000 m in the north, 800,000 m up to 3,200,000 m in +/// the south, along both axes (NGA.SIG.0012 §§11.10 and 11.11). Numbers outside it aren't a UPS +/// position at all. +pub(crate) fn in_lettered_area(north: bool, easting: f64, northing: f64) -> bool { + let first = lettering(north).2 as f64 * SQUARE; + let span = first..(2.0 * FALSE_ORIGIN - first); + span.contains(&easting) && span.contains(&northing) +} + +/// Whether a letter names a polar half of MGRS. +pub(crate) fn is_polar_half(letter: char) -> bool { + matches!(letter, 'A' | 'B' | 'Y' | 'Z') +} + +/// Reads a UPS position, which has no zone number: the zone spelled out, `north 2392768 1607232` +/// or `south 2096454 1452981` (any case), as the readout writes it, or as GeographicLib's short +/// form, `n 2392768 1607232`; or the polar half's letter before the easting and northing, +/// `Y, 1735147, 2243078` (NGA.STND.0037 App. A-4), where Y and A lie west of the 2,000,000 m +/// easting (or on it, for a rounded coordinate) and Z and B on or east of it. Numbers outside the +/// zone's lettered area (north 1,300,000 up to 2,700,000 m, south 800,000 up to 3,200,000 m) +/// aren't a UPS position and read as text ([`GridError::Syntax`]): `A 10 20` is a road, and +/// `north 412345 5523456` a UTM position without its zone. A place inside it +/// must lie in the zone, at 84° N or more or south of 80° S, give or take the meter it was rounded +/// to. +pub fn parse_ups(text: &str) -> Result { + let text = text.trim(); + if text.chars().count() > MAX_REF_CHARS { + return Err(GridError::Syntax); + } + let mut chars = text.chars().peekable(); + let mut word = String::new(); + while let Some(c) = chars.next_if(char::is_ascii_alphabetic) { + word.push(c.to_ascii_uppercase()); + } + let (north, half) = match word.as_str() { + "NORTH" | "N" => (true, None), + "SOUTH" | "S" => (false, None), + "Y" | "Z" => (true, word.chars().next()), + "A" | "B" => (false, word.chars().next()), + _ => return Err(GridError::Syntax), + }; + // A space or comma after the word or letter: `north2000000 …` isn't written that way. + if !chars.peek().is_some_and(|c| c.is_whitespace() || *c == ',') { + return Err(GridError::Syntax); + } + let rest: String = chars.collect(); + let (easting, northing) = easting_and_northing(&rest)?; + if !in_lettered_area(north, easting, northing) { + // Not a UPS position: a road or a code (`A 10 20`), or a UTM position without its zone + // (`north 412345 5523456`), which "outside the zone" would mislead about. Text. + return Err(GridError::Syntax); + } + if half.is_some_and(|h| !easting_in_half(h, easting)) { + return Err(GridError::OutsideZone); + } + let p = from_ups(north, easting, northing).ok_or(GridError::OutsideZone)?; + if !in_zone(north, p.y, ROUNDING_DEG) { + return Err(GridError::OutsideZone); + } + Ok(p) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn c(lon: f64, lat: f64) -> Coord { + Coord::new(lon, lat) + } + + /// NGA.SIG.0012 §10.2 (north UPS, WGS 84): longitude, latitude → easting, northing, printed to + /// the micrometer. + #[test] + fn forward_matches_nga_table() { + let rows = [ + (90.0, 90.0, 2_000_000.000_000, 2_000_000.000_000), + (-179.0, 89.0, 1_998_062.320_046, 2_111_009.610_243), + (-90.0, 88.0, 1_777_930.731_071, 2_000_000.000_000), + (-1.0, 87.0, 1_994_185.827_038, 1_666_906.254_073), + (0.0, 86.0, 2_000_000.000_000, 1_555_731.570_643), + (1.0, 85.0, 2_009_694.068_153, 1_444_627.207_468), + (89.0, 84.0, 2_666_626.157_825, 1_988_363.997_132), + (90.0, 83.0, 2_778_095.750_322, 2_000_000.000_000), + (91.0, 82.0, 2_889_442.490_749, 2_015_525.276_426), + (179.0, 81.0, 2_017_473.190_606, 3_001_038.419_357), + (180.0, 80.0, 2_000_000.000_000, 3_112_951.136_955), + (0.0, 40.0, 2_000_000.000_000, -3_918_313.984_953), + (-90.0, 2.0, -10_206_568.118_587, 2_000_000.000_000), + ]; + for (lon, lat, e, n) in rows { + let (x, y) = to_ups_in_zone(c(lon, lat), true).unwrap(); + assert!((x - e).abs() < 2e-6 && (y - n).abs() < 2e-6, "{lon} {lat}: {x} {y}, want {e} {n}"); + // Back from our own easting and northing (NGA's are rounded to the micrometer, which + // near the pole is more than 1e-11° of longitude). + let back = from_ups(true, x, y).unwrap(); + assert!((back.y - lat).abs() < 1e-11, "{lon} {lat}: back {back:?}"); + if lat < 90.0 { + assert!((wrap(back.x - lon)).abs() < 1e-11, "{lon} {lat}: back {back:?}"); + } + } + } + + /// NGA.SIG.0012 §10.3 (south UPS, WGS 84): easting, northing → longitude, latitude, printed + /// to 1e-10°. The 180° meridian reads as −180° here (longitudes are in [−180°, 180°)). + #[test] + fn inverse_matches_nga_table() { + let rows = [ + (0.0, 0.0, -135.0, -64.916_412_333_2), + (1_000_000.0, 0.0, -153.434_948_822_9, -70.055_294_401_4), + (2_000_000.0, 0.0, -180.0, -72.126_361_016_3), + (1_000_000.0, 1_000_000.0, -135.0, -77.312_079_190_8), + (2_000_000.0, 1_000_000.0, 180.0, -81.010_663_264_5), + (2_000_000.0, 2_000_000.0, 0.0, -90.0), + (3_000_000.0, 2_000_000.0, 90.0, -81.010_663_264_5), + (2_000_000.0, 3_000_000.0, 0.0, -81.010_663_264_5), + (4_000_000.0, 4_000_000.0, 45.0, -64.916_412_333_2), + ]; + for (e, n, lon, lat) in rows { + let p = from_ups(false, e, n).unwrap(); + assert!((p.y - lat).abs() < 1e-9, "{e} {n}: {p:?}"); + assert!(wrap(p.x - lon).abs() < 1e-9, "{e} {n}: {p:?}"); + let (x, y) = to_ups_in_zone(p, false).unwrap(); + assert!((x - e).abs() < 1e-6 && (y - n).abs() < 1e-6, "{e} {n}: {x} {y}"); + } + } + + /// GeographicLib's `GeoConvert -u -l -p 0` for the same places. + #[test] + fn readout_matches_geoconvert() { + let cases = [ + (45.0, 85.0, "north 2392768 1607232"), + (170.0, -85.0, "south 2096454 1452981"), + (-180.0, 84.0, "north 2000000 2666728"), + (0.0, 90.0, "north 2000000 2000000"), + (0.0, -90.0, "south 2000000 2000000"), + ]; + for (lon, lat, want) in cases { + assert_eq!(format_ups(c(lon, lat)).as_deref(), Some(want), "{lon} {lat}"); + } + } + + #[test] + fn zones_follow_nga_ownership() { + assert_eq!(ups_zone(84.0), Some(true)); + assert_eq!(ups_zone(83.999_999), None); + assert_eq!(ups_zone(90.0), Some(true)); + assert_eq!(ups_zone(-80.0), None); + assert_eq!(ups_zone(-80.000_001), Some(false)); + assert_eq!(ups_zone(-90.0), Some(false)); + assert_eq!(ups_zone(90.5), None); + assert_eq!(ups_zone(f64::NAN), None); + assert!(to_ups(c(0.0, 0.0)).is_none()); + assert!(to_ups(c(f64::NAN, 85.0)).is_none()); + assert!(to_ups(c(0.0, f64::INFINITY)).is_none()); + } + + /// The 0° and 180° meridians are on the 2,000,000 m easting, so Z and B own them; −180° is + /// the same meridian as 180°. + #[test] + fn meridians_zero_and_180_are_on_the_central_easting() { + for lon in [0.0, 180.0, -180.0, 540.0] { + for (lat, north) in [(86.0, true), (-86.0, false)] { + let (x, _) = to_ups_in_zone(c(lon, lat), north).unwrap(); + assert_eq!(x, FALSE_ORIGIN, "{lon} {lat}"); + } + } + assert!(easting_in_half('Z', FALSE_ORIGIN) && !easting_in_half('Z', FALSE_ORIGIN - 0.1)); + assert!(easting_in_half('B', FALSE_ORIGIN) && !easting_in_half('B', FALSE_ORIGIN - 0.1)); + // A typed full coordinate is rounded: Y and A take the line itself, not past it. + assert!(easting_in_half('Y', FALSE_ORIGIN) && !easting_in_half('Y', FALSE_ORIGIN + 0.4)); + assert!(easting_in_half('A', FALSE_ORIGIN) && !easting_in_half('A', FALSE_ORIGIN + 1.0)); + } + + #[test] + fn the_other_pole_and_hostile_values_name_no_place() { + assert!(to_ups_in_zone(c(0.0, -90.0), true).is_none()); + assert!(to_ups_in_zone(c(0.0, 90.0), false).is_none()); + assert!(to_ups_in_zone(c(0.0, 90.5), true).is_none()); + assert!(from_ups(true, f64::NAN, 0.0).is_none()); + assert!(from_ups(true, 1e300, 1e300).is_none()); + assert!(from_ups(false, f64::INFINITY, 2e6).is_none()); + assert_eq!(from_ups(true, 2e6, 2e6), Some(c(0.0, 90.0))); + } + + #[test] + fn letters_follow_nga_tables() { + // NGA.SIG.0012 §11.10: YU then YX, ZC then ZF; rows A to P. + assert_eq!(square_letters(true, 1_300_000, 1_300_000), Some(('Y', 'R', 'A'))); + assert_eq!(square_letters(true, 1_699_999, 2_699_999), Some(('Y', 'U', 'P'))); + assert_eq!(square_letters(true, 1_700_000, 2_000_000), Some(('Y', 'X', 'H'))); + assert_eq!(square_letters(true, 2_000_000, 2_000_000), Some(('Z', 'A', 'H'))); + assert_eq!(square_letters(true, 2_300_000, 2_000_000), Some(('Z', 'F', 'H'))); + assert_eq!(square_letters(true, 2_699_999, 2_000_000), Some(('Z', 'J', 'H'))); + assert_eq!(square_letters(true, 2_700_000, 2_000_000), None); + assert_eq!(square_letters(true, 1_299_999, 2_000_000), None); + // §11.11: AL then AP, BC then BF; rows A to Z (no I or O). + assert_eq!(square_letters(false, 800_000, 800_000), Some(('A', 'J', 'A'))); + assert_eq!(square_letters(false, 1_100_000, 2_000_000), Some(('A', 'P', 'N'))); + assert_eq!(square_letters(false, 2_000_000, 2_000_000), Some(('B', 'A', 'N'))); + assert_eq!(square_letters(false, 2_300_000, 3_199_999), Some(('B', 'F', 'Z'))); + assert_eq!(square_letters(false, 3_199_999, 799_999), None); + assert_eq!(square_letters(false, 3_200_000, 2_000_000), None); + for north in [true, false] { + let span = if north { 13..27 } else { 8..32 }; + for col in span.clone() { + for row in span.clone() { + let (h, cl, rw) = square_letters(north, col * 100_000, row * 100_000).unwrap(); + assert_eq!(square_origin(h, cl, rw), Ok((north, col as f64 * SQUARE, row as f64 * SQUARE))); + } + } + } + assert_eq!(square_origin('Y', 'A', 'A'), Err(GridError::Square)); + assert_eq!(square_origin('Z', 'D', 'A'), Err(GridError::Square)); + assert_eq!(square_origin('B', 'A', 'I'), Err(GridError::Square)); + assert_eq!(square_origin('C', 'A', 'A'), Err(GridError::Band)); + } + + #[test] + fn corner_squares_lie_outside_the_zone() { + // YRA, the north lettering's south-west corner, is wholly south of 84° N. + assert!(!cell_reaches_zone(true, 1_300_000.0, 1_300_000.0, SQUARE, 0.0)); + assert!(cell_reaches_zone(true, 2_000_000.0, 2_000_000.0, SQUARE, 0.0)); + assert!(cell_reaches_zone(false, 2_000_000.0, 2_000_000.0, SQUARE, 0.0)); + assert!(!cell_reaches_zone(false, 800_000.0, 800_000.0, SQUARE, 0.0)); + } +} diff --git a/crates/geom/src/utm.rs b/crates/geom/src/utm.rs index 98936f3e24..5441ffd406 100644 --- a/crates/geom/src/utm.rs +++ b/crates/geom/src/utm.rs @@ -18,9 +18,10 @@ //! writes the zone with two digits (`04QFJ`), so references line up and sort; one digit is read //! as well. //! -//! Only the UTM latitudes, 80° S to 84° N, are covered: the polar areas use the Universal Polar -//! Stereographic (UPS) grid, which isn't implemented. There the functions return `None`, and a -//! typed polar reference is refused with [`GridError::Polar`]. +//! The UTM functions cover the UTM latitudes, 80° S up to 84° N. North of 84° N and south of +//! 80° S, the polar areas use the Universal Polar Stereographic grid ([`crate::ups`]): there +//! [`format_utm`] writes UPS (`north 2392768 1607232`), [`to_mgrs`] gives the polar MGRS reference +//! (`Z FD 92767 07232`, no zone number), and [`parse_utm`] and [`parse_mgrs`] read both grids. use std::fmt; use std::sync::LazyLock; @@ -33,7 +34,7 @@ pub const UTM_MIN_LAT: f64 = -80.0; pub const UTM_MAX_LAT: f64 = 84.0; /// WGS 84 semi-major axis (metres) and flattening. -const WGS84_A: f64 = 6_378_137.0; +pub(crate) const WGS84_A: f64 = 6_378_137.0; const WGS84_F: f64 = 1.0 / 298.257_223_563; /// UTM's scale on the central meridian, false easting and the southern false northing. const K0: f64 = 0.9996; @@ -49,7 +50,7 @@ const ROW_CYCLE: f64 = 2_000_000.0; const EDGE_SLOP_DEG: f64 = 0.5; /// How far (degrees) a place, or the nearest part of a cell, may lie outside its band, or past the /// UTM limits, for rounding: about a metre, the precision a UTM position is written to. -const ROUNDING_DEG: f64 = 1.0 / M_PER_DEG; +pub(crate) const ROUNDING_DEG: f64 = 1.0 / M_PER_DEG; /// Metres per degree of latitude, roughly, for turning a cell's size into degrees. const M_PER_DEG: f64 = 111_000.0; @@ -100,8 +101,13 @@ static SERIES: LazyLock = LazyLock::new(|| { } }); +/// The WGS 84 first eccentricity, for [`crate::ups`]. +pub(crate) fn eccentricity() -> f64 { + SERIES.e +} + /// tan of the conformal latitude from tan of the latitude, τ′(τ) (Karney 2011, eqs. 7–9). -fn conformal_tan(tau: f64) -> f64 { +pub(crate) fn conformal_tan(tau: f64) -> f64 { let e = SERIES.e; let sigma = (e * (e * tau / tau.hypot(1.0)).atanh()).sinh(); tau * sigma.hypot(1.0) - sigma * tau.hypot(1.0) @@ -109,7 +115,7 @@ fn conformal_tan(tau: f64) -> f64 { /// tan of the latitude from tan of the conformal latitude, by Newton's method (Karney 2011, /// eqs. 19–21). -fn geographic_tan(taup: f64) -> Option { +pub(crate) fn geographic_tan(taup: f64) -> Option { let e2m = 1.0 - SERIES.e * SERIES.e; let mut tau = taup / e2m; for _ in 0..10 { @@ -158,7 +164,7 @@ fn tm_inverse(x: f64, y: f64) -> Option<(f64, f64)> { } /// A longitude within [-180, 180). -fn wrap(lon: f64) -> f64 { +pub(crate) fn wrap(lon: f64) -> f64 { let l = (lon + 180.0).rem_euclid(360.0) - 180.0; if l >= 180.0 { l - 360.0 } else { l } } @@ -301,14 +307,20 @@ pub fn from_utm(zone: u8, north: bool, easting: f64, northing: f64) -> Option Option { - to_utm(c).map(|u| u.to_string()) + to_utm(c).map(|u| u.to_string()).or_else(|| crate::ups::format_ups(c)) } /// An MGRS reference: zone, band, the 100 km square's column and row letters, and the easting -/// and northing within the square truncated to `digits` digits each (0–5: 100 km to 1 m). +/// and northing within the square truncated to `digits` digits each (0–5: 100 km to 1 m). In the +/// polar areas (UPS) the zone is 0, as MGRS writes no zone number there (and as GeographicLib's +/// UTMUPS numbers UPS), and the band is the half's letter: Y or Z north of 84° N, A or B south of +/// 80° S; [`Mgrs::polar`] tells them apart. Zone 0 is never a UTM zone, so code that turns a zone +/// into an EPSG code (326zz, 327zz) must check [`Mgrs::polar`] first; [`Mgrs::centre`] refuses a +/// polar letter with a UTM zone and a UTM band with zone 0. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Mgrs { pub zone: u8, @@ -326,9 +338,29 @@ impl Mgrs { 10f64.powi(5 - i32::from(self.digits.min(5))) } - /// Without spaces: `33UVP1234523456`, `04QFJ12345678`. + /// Whether the reference is in a polar area (UPS), which MGRS writes without a zone number. + pub fn polar(&self) -> bool { + self.zone == 0 + } + + /// Writes the zone and band as MGRS writes them: `33U`, `04Q`, or the polar half's letter alone + /// (`Z`), without building a string of its own. + fn write_designator(&self, f: &mut impl fmt::Write) -> fmt::Result { + if self.polar() { write!(f, "{}", self.band) } else { write!(f, "{:02}{}", self.zone, self.band) } + } + + /// Without spaces: `33UVP1234523456`, `04QFJ12345678`, `ZFD9276707232`; [`parse_mgrs`] reads it + /// back. pub fn compact(&self) -> String { - format!("{:02}{}{}{}{}", self.zone, self.band, self.column, self.row, self.digit_groups().concat()) + let mut out = String::with_capacity(15); + // Writing to a String can't fail. + let _ = self.write_designator(&mut out); + out.push(self.column); + out.push(self.row); + for group in self.digit_groups() { + out.push_str(&group); + } + out } /// The easting and northing digits, zero-padded to the precision (empty for 100 km). @@ -347,9 +379,11 @@ impl Mgrs { } impl fmt::Display for Mgrs { - /// `33U VP 12345 23456` (the readout's form; `33U VP` at 100 km; `04Q FJ …` in zones 1–9). + /// `33U VP 12345 23456` (the readout's form; `33U VP` at 100 km; `04Q FJ …` in zones 1–9; + /// `Z FD 92767 07232` in the polar areas). fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{:02}{} {}{}", self.zone, self.band, self.column, self.row)?; + self.write_designator(f)?; + write!(f, " {}{}", self.column, self.row)?; let [e, n] = self.digit_groups(); if !e.is_empty() { write!(f, " {e} {n}")?; @@ -359,10 +393,11 @@ impl fmt::Display for Mgrs { } /// A place's MGRS reference to `digits` digits per axis (clamped to 0–5: 100 km to 1 m), -/// truncated as MGRS requires; `None` outside 80° S to 84° N (the UPS areas). +/// truncated as MGRS requires (NGA.SIG.0012 §12.3); in the polar areas the UPS reference +/// (`Z FD 92767 07232`). `None` for a non-finite place or a latitude past ±90°. pub fn to_mgrs(c: Coord, digits: u8) -> Option { let digits = digits.min(5); - let u = to_utm(c)?; + let Some(u) = to_utm(c) else { return polar_mgrs(c, digits) }; // Whole metres first, truncated, so the square letters and the digits agree at an edge. Just // south of the equator the northing can round up to the full 10,000 km false northing, which // is the equator itself and row A of band N: it is kept a metre short, in row V of band M. @@ -387,6 +422,24 @@ pub fn to_mgrs(c: Coord, digits: u8) -> Option { }) } +/// A polar place's MGRS reference (NGA.SIG.0012 §§11.9–11.12): the UPS easting and northing in +/// whole meters, truncated, so the square letters and the digits agree at an edge. +fn polar_mgrs(c: Coord, digits: u8) -> Option { + let p = crate::ups::to_ups(c)?; + let (e, n) = (p.easting.floor() as i64, p.northing.floor() as i64); + let (band, column, row) = crate::ups::square_letters(p.north, e, n)?; + let scale = 10i64.pow(5 - u32::from(digits)); + Some(Mgrs { + zone: 0, + band, + column, + row, + easting: u32::try_from(e.rem_euclid(100_000) / scale).ok()?, + northing: u32::try_from(n.rem_euclid(100_000) / scale).ok()?, + digits, + }) +} + /// The column and row letters of the 100 km square holding easting `e` and northing `n` (metres, /// the southern hemisphere's with its 10,000 km false northing) in UTM zone `zone`: `('M', 'B')` /// for Baghdad's 444,140 m E 3,684,706 m N in zone 38 (`38S MB`). @@ -404,7 +457,8 @@ pub fn square_letters(zone: u8, e: f64, n: f64) -> Option<(char, char)> { Some((column, row)) } -/// A place as `33U VP 12345 23456` (1 m); `None` outside 80° S to 84° N. +/// A place as `33U VP 12345 23456` (1 m), or `Z FD 92767 07232` in the polar areas; `None` for +/// a non-finite place or a latitude past ±90°. pub fn format_mgrs(c: Coord) -> Option { to_mgrs(c, 5).map(|m| m.to_string()) } @@ -418,7 +472,8 @@ pub enum GridError { Zone, /// A letter that isn't a latitude band. Band, - /// A polar (UPS) reference: bands A, B, Y and Z. + /// A polar letter (A, B, Y or Z) after a zone number, or a UTM position north of 84° N or + /// south of 80° S: the polar areas are UPS, which has no zone number. Polar, /// 100 km square letters that the zone doesn't use. Square, @@ -438,7 +493,9 @@ impl fmt::Display for GridError { GridError::Syntax => "not a UTM or MGRS grid reference", GridError::Zone => "the UTM zone must be 1 to 60", GridError::Band => "the latitude band must be a letter from C to X (not I or O)", - GridError::Polar => "polar (UPS) grid references, north of 84° N or south of 80° S, aren't supported", + GridError::Polar => { + "north of 84° N and south of 80° S the grid is UPS, which has no zone number: write north 2000000 2444268, south 2000000 1555732, or polar MGRS such as Z AM 00000 44268" + } GridError::Square => "the 100 km square letters aren't used in this zone", GridError::Digits => "the grid digits must be an even count of 0 to 10, half for the easting and half for the northing", GridError::BandMismatch => "the northing doesn't fall in the latitude band given", @@ -491,10 +548,14 @@ fn cell_latitudes(zone: u8, north: bool, e0: f64, n0: f64, cell: f64) -> Option< /// The centre of the cell an MGRS reference names: the 2,000 km row cycle is settled by the band, /// which the cell must reach into. fn locate(m: &Mgrs) -> Result { + // Zone 0 with a polar half's letter is UPS; with any other letter it is a bad UTM zone. + if m.polar() && crate::ups::is_polar_half(m.band) { + return locate_polar(m); + } if !(1..=60).contains(&m.zone) { return Err(GridError::Zone); } - if matches!(m.band, 'A' | 'B' | 'Y' | 'Z') { + if crate::ups::is_polar_half(m.band) { return Err(GridError::Polar); } if m.digits > 5 { @@ -531,8 +592,42 @@ fn locate(m: &Mgrs) -> Result { found.ok_or(GridError::BandMismatch) } +/// The center of the cell a polar MGRS reference names (NGA.SIG.0012 §11.13): the square's +/// south-west corner from its letters, plus the digits. The cell must reach into its UPS zone: +/// the squares at the corners of the lettering lie wholly in the UTM latitudes. +fn locate_polar(m: &Mgrs) -> Result { + if m.digits > 5 { + return Err(GridError::Digits); + } + let (north, e0, n0) = crate::ups::square_origin(m.band, m.column, m.row)?; + let cell = m.precision_m(); + if f64::from(m.easting) * cell >= SQUARE || f64::from(m.northing) * cell >= SQUARE { + return Err(GridError::Digits); + } + let e0 = e0 + f64::from(m.easting) * cell; + let n0 = n0 + f64::from(m.northing) * cell; + if !crate::ups::cell_reaches_zone(north, e0, n0, cell, ROUNDING_DEG) { + return Err(GridError::OutsideZone); + } + crate::ups::from_ups(north, e0 + cell / 2.0, n0 + cell / 2.0).ok_or(GridError::OutsideZone) +} + /// Most characters a typed grid reference may have. -const MAX_REF_CHARS: usize = 64; +pub(crate) const MAX_REF_CHARS: usize = 64; + +/// An easting and a northing in meters, separated by spaces or commas: plain decimals only (no +/// signs, exponents or `inf`). +pub(crate) fn easting_and_northing(text: &str) -> Result<(f64, f64), GridError> { + let nums: Vec<&str> = text.split(|c: char| c.is_whitespace() || c == ',').filter(|s| !s.is_empty()).collect(); + let [es, ns] = nums.as_slice() else { return Err(GridError::Syntax) }; + let number = |s: &str| { + if !s.chars().all(|c| c.is_ascii_digit() || c == '.') { + return Err(GridError::Syntax); + } + s.parse::().ok().filter(|v| v.is_finite()).ok_or(GridError::Syntax) + }; + Ok((number(es)?, number(ns)?)) +} /// Reads a zone number (one or two digits) and the letter after it, skipping spaces. The zone /// isn't checked to be 1–60 here (the caller does, once the rest reads as a reference): until @@ -554,7 +649,7 @@ fn zone_and_letter(chars: &mut std::iter::Peekable>) -> Resu /// Checks a band letter, telling the polar letters apart. fn band_letter(letter: char) -> Result { - if matches!(letter, 'A' | 'B' | 'Y' | 'Z') { + if crate::ups::is_polar_half(letter) { return Err(GridError::Polar); } band_latitudes(letter).map(|_| letter).ok_or(GridError::Band) @@ -564,15 +659,32 @@ fn band_letter(letter: char) -> Result { /// `33U VP 12345 23456`, `33UVP 1234 2345`, `4QFJ` (100 km). The digits are an even count of 0 /// to 10, as one run or as two groups of the same length. The square letters are checked against /// the zone, and the northing against the band, so a reference that doesn't exist is refused -/// rather than placed somewhere else. Polar (UPS) references are refused with -/// [`GridError::Polar`]. +/// rather than placed somewhere else. +/// +/// In the polar areas MGRS writes no zone number (NGA.SIG.0012 §§11.9 and 11.13): the half's +/// letter (Y or Z north, A or B south), the square's letters, then the digits, as +/// `ZFD9276707232`, `Z FD 92767 07232` or `ZAH` (100 km), in any case and at any precision, as +/// NGA allows. Text that starts with a letter other than A, B, Y or Z isn't a reference, and a +/// polar letter after a zone number (`38ZMB`) is refused with [`GridError::Polar`]. Telling a +/// reference from a word that happens to read as one (`ATL`, `Bay 12`) is up to the caller that +/// takes free text: search's `read_grid_reference` does. pub fn parse_mgrs(text: &str) -> Result { let text = text.trim(); if text.chars().count() > MAX_REF_CHARS { return Err(GridError::Syntax); } let mut chars = text.chars().peekable(); - let (zone, band) = zone_and_letter(&mut chars)?; + let polar = chars.peek().is_some_and(char::is_ascii_alphabetic); + let (zone, band) = if polar { + // Only the polar halves' letters start a reference: `Elm 123` or `Main` is text. + let half = chars.next().map(|c| c.to_ascii_uppercase()).ok_or(GridError::Syntax)?; + if !crate::ups::is_polar_half(half) { + return Err(GridError::Syntax); + } + (0, half) + } else { + zone_and_letter(&mut chars)? + }; let mut letters = [' '; 2]; for l in letters.iter_mut() { while chars.next_if(|c| c.is_whitespace()).is_some() {} @@ -599,11 +711,15 @@ pub fn parse_mgrs(text: &str) -> Result { } _ => return Err(GridError::Digits), }; - // The zone first, as `parse_utm` does: `0AAA` names a bad zone, not a polar reference. - if !(1..=60).contains(&zone) { - return Err(GridError::Zone); - } - let band = band_letter(band)?; + let band = if polar { + band + } else { + // The zone first, as `parse_utm` does: `0AAA` names a bad zone, not a polar reference. + if !(1..=60).contains(&zone) { + return Err(GridError::Zone); + } + band_letter(band)? + }; let [column, row] = letters; let digit = |s: &str| if s.is_empty() { Ok(0) } else { s.parse::().map_err(|_| GridError::Digits) }; let m = Mgrs { @@ -631,12 +747,17 @@ pub fn parse_mgrs(text: &str) -> Result { /// /// `S` after the zone is band S (32° N to 40° N). A northing outside band S may mean the /// southern hemisphere, so it is refused as [`GridError::Ambiguous`] rather than guessed. -/// Polar (UPS) references are refused. +/// +/// North of 84° N and south of 80° S the grid is UPS, read by [`crate::ups::parse_ups`]'s forms +/// (`north 2392768 1607232`); a UTM zone's position there is refused as [`GridError::Polar`]. pub fn parse_utm(text: &str) -> Result { let text = text.trim(); if text.chars().count() > MAX_REF_CHARS { return Err(GridError::Syntax); } + if text.starts_with(|c: char| c.is_ascii_alphabetic()) { + return crate::ups::parse_ups(text); + } let mut chars = text.chars().peekable(); let (zone, letter) = zone_and_letter(&mut chars)?; let mut word = String::from(letter); @@ -647,16 +768,7 @@ pub fn parse_utm(text: &str) -> Result { return Err(GridError::Syntax); } let rest: String = chars.collect(); - let nums: Vec<&str> = rest.split(|c: char| c.is_whitespace() || c == ',').filter(|s| !s.is_empty()).collect(); - let [es, ns] = nums.as_slice() else { return Err(GridError::Syntax) }; - let number = |s: &str| { - // Plain decimals only: no signs, exponents or "inf". - if s.is_empty() || !s.chars().all(|c| c.is_ascii_digit() || c == '.') { - return Err(GridError::Syntax); - } - s.parse::().ok().filter(|v| v.is_finite()).ok_or(GridError::Syntax) - }; - let (easting, northing) = (number(es)?, number(ns)?); + let (easting, northing) = easting_and_northing(&rest)?; if !(1..=60).contains(&zone) { return Err(GridError::Zone); } @@ -945,8 +1057,11 @@ mod tests { assert_eq!(to_mgrs(p, 9).unwrap().digits, 5); // The UTM readout rounds instead. assert_eq!(from_utm(38, true, 444_140.6, 3_684_706.4).map(format_utm), Some(Some("38north 444141 3684706".into()))); - assert!(to_mgrs(c(0.0, 84.0), 5).is_none()); - assert!(format_mgrs(c(0.0, -85.0)).is_none()); + // In the polar areas, UPS's MGRS (GeographicLib's `GeoConvert -m -p 0`), truncated too. + assert_eq!(to_mgrs(c(0.0, 84.0), 5).map(|m| m.compact()).as_deref(), Some("ZAA0000033272")); + assert_eq!(format_mgrs(c(170.0, -85.0)).as_deref(), Some("B AG 96454 52981")); + assert_eq!(to_mgrs(c(-0.0001, -88.0), 5).map(|m| m.compact()).as_deref(), Some("AZQ9999922069")); + assert_eq!(to_mgrs(c(170.0, -85.0), 2).map(|m| m.compact()).as_deref(), Some("BAG9652")); } #[test] @@ -1173,10 +1288,17 @@ mod tests { let zone_end = text.find(|ch: char| !ch.is_ascii_digit()).unwrap(); assert!(text[zone_end..].starts_with("north ") || text[zone_end..].starts_with("south "), "{text}"); } - // Where UTM has no zone the readout still writes nothing, and the hemisphere form of a - // polar position is refused. - for p in [c(0.0, 84.0), c(0.0, -80.000_1), c(0.0, 90.0)] { - assert!(format_utm(p).is_none(), "{p:?}"); + // Where UTM has no zone the readout writes UPS (GeographicLib's `GeoConvert -u -l`), which + // reads back; a UTM zone's position there is refused. + for (p, want) in [ + (c(0.0, 84.0), "north 2000000 1333272"), + (c(0.0001, -80.000_1), "south 2000002 3112940"), + (c(0.0, 90.0), "north 2000000 2000000"), + ] { + let text = format_utm(p).unwrap(); + assert_eq!(text, want, "{p:?}"); + let back = parse_utm(&text).unwrap(); + assert!((back.y - p.y).abs() < 1e-5, "{p:?} {back:?}"); } let (e, n) = to_utm_in_zone(c(15.0, 84.05), 33, true).unwrap(); assert_eq!(parse_utm(&format!("33north {} {}", e.round(), n.round())), Err(GridError::Polar)); @@ -1376,7 +1498,15 @@ mod tests { #[test] fn outside_utm_is_said_not_guessed() { - for p in [c(0.0, 84.0), c(10.0, 89.9), c(0.0, 90.0), c(-60.0, -80.5), c(0.0, -90.0), c(f64::NAN, 1.0)] { + // UTM has no zone in the polar areas; the readouts give UPS there instead. + for p in [c(0.0, 84.0), c(10.0, 89.9), c(0.0, 90.0), c(-60.0, -80.5), c(0.0, -90.0)] { + assert!(to_utm(p).is_none(), "{p:?}"); + let utm = format_utm(p).unwrap(); + assert!(utm.starts_with(if p.y > 0.0 { "north " } else { "south " }), "{p:?} {utm}"); + let mgrs = to_mgrs(p, 5).unwrap(); + assert!(mgrs.polar() && "ABYZ".contains(mgrs.band), "{p:?} {mgrs}"); + } + for p in [c(f64::NAN, 1.0), c(0.0, 90.5), c(0.0, -91.0), c(f64::INFINITY, 85.0)] { assert!(to_utm(p).is_none(), "{p:?}"); assert!(format_utm(p).is_none(), "{p:?}"); assert!(format_mgrs(p).is_none(), "{p:?}"); @@ -1389,4 +1519,115 @@ mod tests { assert!(to_utm_in_zone(c(100.0, 0.0), 31, true).is_none()); assert!(to_utm_in_zone(c(3.0, 91.0), 31, true).is_none()); } + + /// Polar MGRS against GeographicLib's `GeoConvert -m -p 0`: written, then read back in both + /// forms to the same cell. + #[test] + fn polar_mgrs_matches_geoconvert_and_reads_back() { + let cases = [ + (0.0, 84.0, "ZAA0000033272"), + (-0.5, 84.5, "YZA9466788941"), + (45.0, 85.0, "ZFD9276707232"), + (-135.0, 87.5, "YYJ0370596294"), + (10.0, 89.999, "ZAG0001999890"), + (0.0, 90.0, "ZAH0000000000"), + (179.9, 86.0, "ZAM0077544267"), + (-179.9, 86.0, "YZM9922444267"), + (180.0, 84.0, "ZAP0000066727"), + (-180.0, 84.0, "ZAP0000066727"), + (-60.0, -80.5, "ALT8456628525"), + (170.0, -85.0, "BAG9645452981"), + (30.0, -89.9, "BAN0555109614"), + (0.0, -90.0, "BAN0000000000"), + (0.0001, -80.0001, "BAZ0000112939"), + (-0.0001, -88.0, "AZQ9999922069"), + ]; + for (lon, lat, want) in cases { + let m = to_mgrs(c(lon, lat), 5).unwrap(); + assert_eq!(m.compact(), want, "{lon} {lat}"); + assert_eq!(parse_mgrs(want), Ok(m), "{want}"); + assert_eq!(parse_mgrs(&m.to_string()), Ok(m), "{m}"); + assert_eq!(parse_mgrs(&want.to_lowercase()), Ok(m), "{want}"); + // Every precision reads back, compact or spaced. + for digits in 0..=5 { + let r = to_mgrs(c(lon, lat), digits).unwrap(); + assert_eq!(parse_mgrs(&r.compact()), Ok(r), "{want} at {digits} digits"); + assert_eq!(parse_mgrs(&r.to_string()), Ok(r), "{want} at {digits} digits"); + } + let p = m.centre().unwrap(); + assert!((p.y - lat).abs() < 1e-4, "{want}: {p:?}"); + } + // UTM still owns 80° S itself. + assert_eq!(to_mgrs(c(0.0, -80.0), 5).map(|m| m.compact()).as_deref(), Some("31CDM4186716915")); + // NGA.STND.0037 App. B-5f's worked example, 86°46′ N 132°30′ W: zone Y, square XK. + let m = to_mgrs(c(-132.5, 86.0 + 46.0 / 60.0), 2).unwrap(); + assert_eq!((m.band, m.column, m.row), ('Y', 'X', 'K')); + } + + #[test] + fn polar_references_that_name_no_place_are_refused() { + // Built by hand, zone 0 with a UTM band is a bad zone, not a bad band. + let m = Mgrs { zone: 0, band: 'U', column: 'V', row: 'P', easting: 0, northing: 0, digits: 0 }; + assert_eq!(m.centre(), Err(GridError::Zone)); + for (text, why) in [ + ("ZDA", GridError::Square), // Z skips D and E + ("Z DA", GridError::Square), // spaced, the same + ("YAA", GridError::Square), // Y starts at R + ("BAI", GridError::Square), // no I + ("YRA", GridError::OutsideZone), // the north lettering's corner lies south of 84° N + ("AJA", GridError::OutsideZone), // the south lettering's corner lies north of 80° S + ("ZAH123", GridError::Digits), + ("Z AH 123 45", GridError::Digits), + ("38ZMB", GridError::Polar), // a polar letter after a zone number + ] { + assert_eq!(parse_mgrs(text), Err(why), "{text}"); + } + // Text that starts with any other letter, or doesn't go on as letters and digits, isn't a + // reference. + for text in ["CAT", "Main", "Elm 123", "Berlin 12", "Z", "ZA", "zap road", "Z 12"] { + assert_eq!(parse_mgrs(text), Err(GridError::Syntax), "{text}"); + } + // Every form NGA allows reads, at any precision and in any case; telling a reference from + // a word that reads as one is search's job (`read_grid_reference`). + for text in ["ZAH", "Z AH", "z ah", "ZAH12", "ZAH1234", "BAG9652", "ZFD 9207", "ZAC 7714662481", "Z AH 12345 12345"] { + assert!(parse_mgrs(text).is_ok(), "{text}"); + } + } + + /// UPS positions: the readout's `north …`/`south …` and NGA.STND.0037 App. A-4's + /// `Y, 1735147, 2243078`, whose letter must match the side of the 2,000,000 m easting. + #[test] + fn ups_positions_read_both_forms() { + let p = parse_utm("north 2392768 1607232").unwrap(); + assert!((p.x - 45.0).abs() < 1e-4 && (p.y - 85.0).abs() < 1e-4, "{p:?}"); + assert_eq!(parse_utm("NORTH 2392768 1607232"), Ok(p)); + assert_eq!(parse_utm("Z 2392768 1607232"), Ok(p)); + // GeographicLib's short form (`GeoConvert -u`). + assert_eq!(parse_utm("n 2392768 1607232"), Ok(p)); + assert!(parse_utm("s 2096454 1452981").is_ok_and(|q| q.y < -80.0)); + let q = parse_utm("Y, 1735147, 2243078").unwrap(); + assert!(q.x < 0.0 && q.y > 84.0, "{q:?}"); + let s = parse_utm("south 2096454 1452981").unwrap(); + assert!((s.x - 170.0).abs() < 1e-4 && (s.y + 85.0).abs() < 1e-4, "{s:?}"); + assert_eq!(parse_utm("B 2096454 1452981"), Ok(s)); + for (text, why) in [ + ("Y 2392768 1607232", GridError::OutsideZone), // east of 2,000,000 m is Z + ("A 2096454 1452981", GridError::OutsideZone), // east of 2,000,000 m is B + ("north 2000000 1300000", GridError::OutsideZone), // lettered, but south of 84° N + ("south 2000000 3150000", GridError::OutsideZone), // lettered, but north of 80° S + ("north 2000000 100000", GridError::Syntax), // outside the lettered area + ("north 412345 5523456", GridError::Syntax), // a UTM position without its zone + ("n 2000000 100000", GridError::Syntax), + ("A 2000000 100000", GridError::Syntax), // outside the lettered area too + ("A 10 20", GridError::Syntax), + ("A1 12", GridError::Syntax), + ("B 12, 34", GridError::Syntax), + ("north 2000000", GridError::Syntax), + ("north -1 2000000", GridError::Syntax), + ("Q 2000000 2000000", GridError::Syntax), + ("north 1e300 2000000", GridError::Syntax), + ] { + assert_eq!(parse_utm(text), Err(why), "{text}"); + } + } } diff --git a/crates/ui-egui/src/coordreadout.rs b/crates/ui-egui/src/coordreadout.rs index 6953ee3647..80ecda3f28 100644 --- a/crates/ui-egui/src/coordreadout.rs +++ b/crates/ui-egui/src/coordreadout.rs @@ -69,9 +69,9 @@ impl CoordReadout { matches!(self, CoordReadout::Utm | CoordReadout::Mgrs) } - /// The place in this format; for UTM and MGRS `None` outside their latitudes (80° S to - /// 84° N) and on another body's map (`earth` false), and for every format `None` for a - /// non-finite place. + /// The place in this format; for UTM and MGRS, UPS in the polar areas (north of 84° N and + /// south of 80° S) and `None` on another body's map (`earth` false), and for every format + /// `None` for a non-finite place. pub fn format(self, c: Coord, earth: bool) -> Option { if !c.is_finite() || (self.earth_only() && !earth) { return None; @@ -84,10 +84,9 @@ impl CoordReadout { } } - /// The status bar's readout of the pointer: `—` off the map, and a short statement where UTM - /// and MGRS have no zone (the polar areas, which use UPS, and other bodies) rather than a - /// wrong grid reference; the [`hover`](Self::hover) text says why. It is no wider than a - /// reference, so the status bar keeps its room. + /// The status bar's readout of the pointer: `—` off the map, and a short statement on another + /// body's map, where the Earth's grids name no place, rather than a wrong grid reference. It is + /// no wider than a reference, so the status bar keeps its room. pub fn readout(self, c: Option, earth: bool) -> String { match c { None => "—".to_string(), @@ -96,11 +95,11 @@ impl CoordReadout { } } - /// The status bar readout's hover text: the current format, what a click does, and where - /// UTM and MGRS read. + /// The status bar readout's hover text: the current format, what a click does, and how UTM + /// and MGRS read near the poles. pub fn hover(self) -> String { i18n::fmt( - "Coordinates in {format}. Click to switch: decimal degrees, DMS, UTM, MGRS. UTM and MGRS cover the Earth from 80° S to 84° N.", + "Coordinates in {format}. Click to switch: decimal degrees, DMS, UTM, MGRS. UTM and MGRS are grids of the Earth, read in UPS north of 84° N and south of 80° S.", &[("format", self.label())], ) } @@ -150,15 +149,14 @@ mod tests { } #[test] - fn polar_places_say_they_are_outside_utm() { + fn polar_places_read_in_ups() { let pole = Coord::new(10.0, 86.0); + // GeographicLib's `GeoConvert -u -l` and `-m` for the same place. + assert_eq!(CoordReadout::Utm.readout(Some(pole), true), "north 2077146 1562481"); + assert_eq!(CoordReadout::Mgrs.readout(Some(pole), true), "Z AC 77146 62481"); for f in [CoordReadout::Utm, CoordReadout::Mgrs] { - assert_eq!(f.format(pole, true), None); - let r = f.readout(Some(pole), true); - assert_eq!(r, format!("No {} here", f.label())); - // No wider than the reference it stands for, in the status bar. - assert!(r.chars().count() <= f.readout(Some(Coord::new(44.4, 33.3)), true).chars().count(), "{r}"); - assert!(f.hover().contains("80° S to 84° N")); + assert_eq!(f.format(pole, true).as_deref(), Some(f.readout(Some(pole), true).as_str())); + assert!(f.hover().contains("UPS")); } // Decimal and DMS read there as anywhere. assert_eq!(CoordReadout::Dms.readout(Some(pole), true), "10°00′00.0″ E 86°00′00.0″ N"); @@ -170,7 +168,10 @@ mod tests { let p = Coord::new(44.4, 33.3); for f in [CoordReadout::Utm, CoordReadout::Mgrs] { assert_eq!(f.format(p, false), None); - assert_eq!(f.readout(Some(p), false), format!("No {} here", f.label())); + let r = f.readout(Some(p), false); + assert_eq!(r, format!("No {} here", f.label())); + // No wider than the reference it stands for, in the status bar. + assert!(r.chars().count() <= f.readout(Some(p), true).chars().count(), "{r}"); assert!(f.earth_only()); } for f in [CoordReadout::Decimal, CoordReadout::Dms] { diff --git a/crates/ui-egui/src/mapmenu.rs b/crates/ui-egui/src/mapmenu.rs index df7fceb130..f5a01341a3 100644 --- a/crates/ui-egui/src/mapmenu.rs +++ b/crates/ui-egui/src/mapmenu.rs @@ -52,9 +52,9 @@ fn lat_lon(c: Coord) -> String { } /// The coordinate row: the text it shows and copies, in the readout's format, and whether it fell -/// back from it. Decimal degrees are `lat, lon` ([`lat_lon`]); north of 84° N or south of 80° S, -/// and on another body's map (`earth` false), UTM and MGRS fall back to them (and the row's hover -/// text says why). +/// back from it. Decimal degrees are `lat, lon` ([`lat_lon`]); north of 84° N and south of 80° S +/// UTM and MGRS give UPS (`north …`, `Z …`); on another body's map (`earth` false) they fall back +/// to latitude and longitude (and the row's hover text says why). fn coordinate_row(c: Coord, f: CoordReadout, earth: bool) -> (String, bool) { match f { CoordReadout::Decimal => (lat_lon(c), false), @@ -129,11 +129,6 @@ pub fn show(app: &mut RustGisApp, ui: &mut Ui, c: Coord) { "Copy coordinates to the clipboard. {format} is a grid of the Earth, so latitude and longitude are copied", &[("format", format.label())], ) - } else if fell_back { - i18n::fmt( - "Copy coordinates to the clipboard. No {format} here: outside the UTM zones (80° S to 84° N), so latitude and longitude are copied", - &[("format", format.label())], - ) } else { tl!("Copy coordinates to the clipboard").to_string() }; @@ -306,11 +301,15 @@ mod tests { assert!((at.x - q.x).abs() < 1e-4 && (at.y - q.y).abs() < 1e-4, "{text} {at:?}"); } } - // Where UTM has no zone, the row falls back to latitude and longitude (and says so). + // Where UTM has no zone, the row gives UPS (`north …`, `Z …`), which reads back too. let pole = Coord::new(10.0, 86.0); for f in [CoordReadout::Utm, CoordReadout::Mgrs] { - assert_eq!(coordinate_row(pole, f, true), ("86.000000, 10.000000".into(), true), "{f:?}"); - // On another body's map as well: UTM and MGRS are the Earth's grids. + let (text, fell_back) = coordinate_row(pole, f, true); + assert!(!fell_back && (text.starts_with("north ") || text.starts_with("Z ")), "{f:?}: {text}"); + let at = rustgis_engine::cmd::search::read_grid_reference(&text).unwrap_or_else(|e| panic!("{text}: {e}")); + assert!((at.x - pole.x).abs() < 1e-3 && (at.y - pole.y).abs() < 1e-4, "{text} {at:?}"); + // On another body's map the row falls back to latitude and longitude (and says so): + // UTM, MGRS and UPS are the Earth's grids. assert_eq!(coordinate_row(p, f, false), ("33.300000, 44.400000".into(), true), "{f:?}"); } assert!(!coordinate_row(pole, CoordReadout::Dms, true).1); diff --git a/crates/ui-egui/src/searchbox.rs b/crates/ui-egui/src/searchbox.rs index 0033bf8c5b..5533c9dc68 100644 --- a/crates/ui-egui/src/searchbox.rs +++ b/crates/ui-egui/src/searchbox.rs @@ -106,8 +106,10 @@ pub fn had_focus(st: &State, pass: u64) -> bool { st.focus_pass.is_some_and(|p| p + 1 == pass) } +/// Whether the query reads as a coordinate and nothing else, so looking it up as a place is no +/// use. A polar reference may as well be a name or a code (`BAG123456`), so it isn't. fn is_coordinate(st: &State) -> bool { - matches!(st.results.hits.first(), Some(Hit::Coordinate { .. })) + matches!(st.results.hits.first(), Some(Hit::Coordinate { .. })) && !st.results.coordinate_may_be_text } /// The box, at the bottom of the left pane (`ui` is the pane). @@ -386,7 +388,9 @@ fn grid_error_text(e: rustgis_engine::geom::GridError) -> String { G::Syntax => tl_raw!("not a UTM or MGRS grid reference"), G::Zone => tl_raw!("the UTM zone must be 1 to 60"), G::Band => tl_raw!("the latitude band must be a letter from C to X (not I or O)"), - G::Polar => tl_raw!("polar (UPS) grid references, north of 84° N or south of 80° S, aren't supported"), + G::Polar => tl_raw!( + "north of 84° N and south of 80° S the grid is UPS, which has no zone number: write north 2000000 2444268, south 2000000 1555732, or polar MGRS such as Z AM 00000 44268" + ), G::Square => tl_raw!("the 100 km square letters aren't used in this zone"), G::Digits => tl_raw!("the grid digits must be an even count of 0 to 10, half for the easting and half for the northing"), G::BandMismatch => tl_raw!("the northing doesn't fall in the latitude band given"), diff --git a/crates/ui-egui/tests/coordinate_readout.rs b/crates/ui-egui/tests/coordinate_readout.rs index 00f6508c3f..c1aa8d6569 100644 --- a/crates/ui-egui/tests/coordinate_readout.rs +++ b/crates/ui-egui/tests/coordinate_readout.rs @@ -120,12 +120,15 @@ fn the_status_bar_reads_the_pointer_in_the_chosen_format_and_a_click_switches() h.get_by_label(&mgrs).click(); hover_map(&mut h); assert_eq!(h.state().map.coord_format, CoordReadout::Decimal); - // Where UTM has no zone the readout says so rather than showing a wrong reference. + // Where UTM has no zone the readout gives the polar grid, UPS (MGRS without a zone number). h.state_mut().run("ui.coordinateFormat", json!({"format": "mgrs"})).unwrap(); h.state_mut().run("map.goToXY", json!({"lon": 10.0, "lat": 84.5, "scale": 10000})).unwrap(); hover_map(&mut h); - assert!(h.state().map.pointer_lonlat.is_some_and(|c| c.y > 84.0)); - h.get_by_label("No MGRS here"); + let at = h.state().map.pointer_lonlat.unwrap(); + assert!(at.y > 84.0, "{at:?}"); + let polar = rustgis_engine::geom::format_mgrs(at).unwrap(); + assert!(polar.starts_with("Z "), "{polar}"); + h.get_by_label(&polar); // On another body's map UTM and MGRS, the Earth's grids, read nothing either. h.state_mut().run("map.body", json!({"name": "mars", "basemap": false})).unwrap(); h.state_mut().run("map.goToXY", json!({"lon": 44.4, "lat": 33.3, "scale": 10000})).unwrap(); diff --git a/docs/user-guide/maps.md b/docs/user-guide/maps.md index ebf747a632..8541e01813 100644 --- a/docs/user-guide/maps.md +++ b/docs/user-guide/maps.md @@ -130,9 +130,9 @@ rustgis-cli run --sample --cmd 'map.search={"query":"Tokyo","go":true}' **Right-click the map** for a menu about that place. Its first row shows the place in the status bar's coordinate format (latitude and longitude as `40.712800, -74.006000` for decimal degrees); -click it to copy it. North of 84° N and south of 80° S, where UTM and MGRS have no zone, and on -the map of another body than the Earth, it shows and copies the latitude and longitude, and its -hover text says why. Below it, **Copy As GeoJSON** +click it to copy it. North of 84° N and south of 80° S it gives the polar grid, UPS (see +[Coordinate readouts](#coordinate-readouts)). On the map of another body than the Earth it shows +and copies the latitude and longitude, and its hover text says why. Below it, **Copy As GeoJSON** copies the place as a point feature, **Center Map Here** and **Zoom In Here** move the view, and **Directions To Here** and **Directions From Here** open the [Directions](#directions) pane. **Quick Analysis** runs a tool at the place: a buffer of 500 m, 1 km or 5 km (¼, 1 or 5 miles when the Directions pane is set @@ -159,15 +159,21 @@ UTM states the hemisphere, as GeographicLib's `GeoConvert -u -l` writes it, not in plain UTM a letter after the zone is commonly read as the hemisphere, so `38S` (band S, 32° N to 40° N) would be taken for the southern hemisphere, 10,000 km away. Latitude bands are MGRS's. UTM and MGRS are on WGS 84, with the zone exceptions for southern Norway (32V) and Svalbard (31X, -33X, 35X and 37X), and cover 80° S to 84° N. Nearer the poles they would need the Universal Polar -Stereographic grid, which RustGIS doesn't have: there the readout shows *No UTM here* (or -*No MGRS here*) rather than a wrong reference, and so it does on the map of another body than -the Earth, where degrees still read. Scripts set the format with +33X, 35X and 37X), and cover 80° S up to 84° N. North of 84° N and south of 80° S the readouts +use the Universal Polar Stereographic grid (UPS), as NGA defines it (NGA.SIG.0012): the UTM +readout gives the zone spelled out and the easting and northing rounded to the meter, +`north 2077146 1562481`, as GeographicLib writes it, and the MGRS readout gives the polar +reference, which has no zone number: a letter for the half (Y for western longitudes and Z for +eastern ones in the north, A and B in the south, with the 0° and 180° meridians in Z and B), +the 100 km square and the digits, truncated, `Z AC 77146 62481`. 84° N itself is UPS, 80° S +itself is UTM. On the map of another body than the Earth the readout shows *No UTM here* +(or *No MGRS here*) rather than a wrong reference, and degrees still read. Scripts set the format with `ui.coordinateFormat={"format":"utm"}` (`decimal`, `dms`, `utm` or `mgrs`); without `format` it steps to the next one. A saved format this version doesn't know, say from a newer RustGIS, reads as decimal degrees with a notice, and stays saved until you pick a format. -The [search box](#navigating) takes the same grid references, in any case: +The [search box](#navigating) takes the same grid references, in any case (polar references have +their own rules, below): - **MGRS** with or without spaces: `33UWR2156621996`, `33U WR 21566 21996`, `33UWR 2156 2199`, or a 100 km square alone, `33UWR`; a zone below 10 with or without its leading zero (`04QFJ`, @@ -182,12 +188,33 @@ The [search box](#navigating) takes the same grid references, in any case: `S` after the zone is always band S (32° N to 40° N), as in `11S 384629 3768405` (Los Angeles); with a northing outside band S it could mean the southern hemisphere, so it finds nothing: write `south` instead. +- **UPS and polar MGRS**, north of 84° N and south of 80° S, which have no zone number: UPS as + the readout writes it, `north 2077146 1562481` or `south 2096454 1452981`, or with the half's + letter, `Z 2077146 1562481` or `Y, 1735147, 2243078`. Polar MGRS has no zone number, so three + letters and a few digits look like a word or a code (`ATL`, `Bay 12`, the flight `BAW1234`); + search reads one only as a reference is written: as the readout writes it, with a space after + the half's letter and the square in capitals, then no digits or two equal groups (`Z AC`, + `Z AC 77 62`, `Z AC 77146 62481`; `A ST 12` is an address), as + one word with at least six digits (`ZAC7714662481`, 100 m or finer), or in capitals before + two equal groups of at least three digits (`ZAC 771 624`, `ZAC 77146 62481`). A UPS position + (`north 2077146 1562481`, `Z 2077146 1562481`) and a reference written exactly as the readout + writes it (`Z AC 77146 62481`) are plainly places. Any + other polar text may also be a name or a code, so the attribute tables are still searched, + their hits come before the polar place, and **Search places** is still offered; with room + for one hit (`limit: 1`), a matching feature is the hit. A UTM zone's position past 84° N or + 80° S, or a polar letter after a zone number (`38ZMB`), finds nothing and the list says how UPS + is written. A reference that doesn't exist (square letters the zone doesn't use, a northing or a square outside the band, an odd number of digits, a place outside the zone) finds nothing rather than a -place somewhere else, and the list says why; `map.search` returns the reason as `gridError`. A -100 km square written with spaces, such as `5 Ave` or `4K TV`, is as likely ordinary text, so one -that names no square gives no reason; written as one word, `38TMJ`, it does. On the map of +place somewhere else, and the list says why; `map.search` returns the reason as `gridError`, and +adds `"coordinateMayBeText": true` when a polar place among its hits may as well be a name or a +code. A 100 km square written with spaces, such as `5 Ave`, `4K TV` or `A TO`, is as likely +ordinary text, so one that names no square gives no reason; written as one word, `38TMJ`, it does. Polar +MGRS written compactly (`ZDA1234512345`) may be a code too, so one that names no place gives no +reason either; written as the readout writes it (`Z DA 12345 12345`), it does. A UPS position +after `n` or `s` may be a State Plane pair (`N 1350000 1350000`), so it gives no reason; after +`north`, `south` or the half's letter (`Y 2392768 1607232`), it does. On the map of another body, grid references find nothing. ### Directions