Repository Public License
1// ORIX Convert — Packages/EngineGeo/Tests/EngineGeoTests/CRSTests.swift2// Description: Reference systems: control coordinates for every supported EPSG code, identification of .prj3// definitions, reprojection through the engine, refusal of systems that cannot be transformed, the4// missing-.prj rules, and axis order per format.5// Author: Simon-Pierre Boucher — contact@spboucher.ai6import Foundation7import Testing8import ConvertCore9@testable import EngineGeo1011@Suite struct CRSTests {12 @Test func everySupportedCodeHasControlPoints() {13 let tested = Set(ControlPoints.projected.map(\.0)).union([4326, 4269, 4617])14 #expect(tested == Set(CRSRegistry.supportedCodes))15 #expect(CRSRegistry.supportedCodes.count == 179)16 for code in CRSRegistry.supportedCodes {17 #expect(CRSRegistry.definition(epsg: code)?.name == ControlPoints.names[code], "name of EPSG:\(code)")18 }19 #expect(CRSRegistry.definition(epsg: 32198) == nil)20 }2122 @Test func forwardAndInverseMatchControlPoints() throws {23 for (code, lon, lat, x, y) in ControlPoints.projected {24 let def = try #require(CRSRegistry.definition(epsg: code))25 let geographic = try #require(CRSRegistry.definition(epsg: def.datum.geographicEPSG))26 let forward = try CRSTransformer(from: geographic, to: def).apply(Coordinate(lon, lat, z: 12, m: 3))27 // 0.1 mm against PROJ.28 #expect(abs(forward.x - x) < 1e-4 && abs(forward.y - y) < 1e-4, "EPSG:\(code) forward: \(forward.x), \(forward.y) vs \(x), \(y)")29 #expect(forward.z == 12 && forward.m == 3)30 let inverse = try CRSTransformer(from: def, to: geographic).apply(Coordinate(x, y))31 #expect(abs(inverse.x - lon) < 1e-9 && abs(inverse.y - lat) < 1e-9, "EPSG:\(code) inverse: \(inverse.x), \(inverse.y)")32 }33 }3435 @Test func knownReferencePoints() throws {36 // Web Mercator: the equator / antimeridian corner is ±π·R = ±20037508.342789244.37 let wgs = try #require(CRSRegistry.definition(epsg: 4326)), merc = try #require(CRSRegistry.definition(epsg: 3857))38 let corner = try CRSTransformer(from: wgs, to: merc).apply(Coordinate(180, 0))39 #expect(abs(corner.x - 20_037_508.342789244) < 1e-6 && abs(corner.y) < 1e-9)40 // UTM: a point on the central meridian at the equator is (500000, 0); in the south (500000, 10000000).41 let north = try CRSTransformer(from: wgs, to: try #require(CRSRegistry.definition(epsg: 32631))).apply(Coordinate(3, 0))42 #expect(abs(north.x - 500_000) < 1e-6 && abs(north.y) < 1e-6)43 let south = try CRSTransformer(from: wgs, to: try #require(CRSRegistry.definition(epsg: 32731))).apply(Coordinate(3, 0))44 #expect(abs(south.x - 500_000) < 1e-6 && abs(south.y - 10_000_000) < 1e-6)45 // MTM zone 8: central meridian 73°30′ W maps to the false easting 304800.46 let mtm = try CRSTransformer(from: try #require(CRSRegistry.definition(epsg: 4617)), to: try #require(CRSRegistry.definition(epsg: 2950))).apply(Coordinate(-73.5, 45.5))47 #expect(abs(mtm.x - 304_800) < 1e-6)48 // Meridian arc on WGS 84 from the equator to the pole ≈ 10 001 965.729 m; UTM scales it by 0.9996.49 let pole = try CRSTransformer(from: wgs, to: try #require(CRSRegistry.definition(epsg: 32631))).apply(Coordinate(3, 90))50 #expect(abs(pole.y - 10_001_965.729 * 0.9996) < 1e-3)51 }5253 @Test func transformerFlagsDatumChanges() throws {54 let nadUTM = try #require(CRSRegistry.definition(epsg: 26918)), wgs = try #require(CRSRegistry.definition(epsg: 4326))55 let t = CRSTransformer(from: nadUTM, to: wgs)56 #expect(t.crossesDatum && !t.isNumericNoOp)57 #expect(t.summary.contains("treated as coincident"))58 let same = CRSTransformer(from: try #require(CRSRegistry.definition(epsg: 4269)), to: wgs)59 #expect(same.crossesDatum && same.isNumericNoOp)60 #expect(try same.apply(Coordinate(-73.1, 45.2)) == Coordinate(-73.1, 45.2))61 #expect(!CRSTransformer(from: try #require(CRSRegistry.definition(epsg: 32618)), to: wgs).crossesDatum)62 #expect(throws: ConversionError.self) { _ = try CRSTransformer(from: wgs, to: nadUTM).apply(Coordinate(10, 95)) }63 #expect(throws: ConversionError.self) { _ = try CRSTransformer(from: wgs, to: nadUTM).apply(Coordinate(40, 45)) }64 #expect(throws: ConversionError.self) { _ = try CRSTransformer(from: wgs, to: try #require(CRSRegistry.definition(epsg: 3857))).apply(Coordinate(0, 90)) }65 }6667 @Test func identifiesDefinitions() throws {68 #expect(CRS.from(wkt: Cities.wgs84ESRI).epsg == 4326)69 #expect(CRS.from(wkt: Samples.utm18NAD83ESRI).epsg == 26918)70 #expect(CRS.from(wkt: Samples.mtm8ESRI).epsg == 2950)71 #expect(CRS.from(wkt: Samples.webMercatorESRI).epsg == 3857)72 #expect(CRS.from(wkt: Samples.utm18WGS84OGC).epsg == 32618)73 let lambert = CRS.from(wkt: Samples.quebecLambertESRI)74 #expect(lambert.epsg == nil && lambert.definition == nil)75 #expect(lambert.name == "NAD_1983_Quebec_Lambert" && lambert.wkt == Samples.quebecLambertESRI)76 #expect(lambert.summary.contains("NAD_1983_Quebec_Lambert"))77 // A code outside the registry is kept as declared.78 let other = CRS.from(wkt: "PROJCS[\"RGF93 / Lambert-93\",GEOGCS[\"RGF93\",DATUM[\"Reseau_Geodesique_Francais_1993\",SPHEROID[\"GRS 1980\",6378137,298.257222101]],PRIMEM[\"Greenwich\",0],UNIT[\"degree\",0.0174532925199433]],PROJECTION[\"Lambert_Conformal_Conic_2SP\"],UNIT[\"metre\",1],AUTHORITY[\"EPSG\",\"2154\"]]")79 #expect(other.epsg == 2154 && other.definition == nil)80 // A different datum with UTM parameters must not be mistaken for a supported zone.81 #expect(CRS.from(wkt: Samples.utm18NAD83ESRI.replacingOccurrences(of: "D_North_American_1983", with: "D_North_American_1927")).epsg == nil)82 #expect(CRS.from(wkt: Samples.utm18NAD83ESRI.replacingOccurrences(of: "UNIT[\"Meter\",1.0]", with: "UNIT[\"Foot_US\",0.3048006096012192]")).epsg == nil)83 #expect(CRS.from(wkt: "not wkt at all").epsg == nil)84 #expect(CRS.from(wkt: String(repeating: "A[", count: 100)).epsg == nil)85 // Every definition the engine writes is recognised again, in both flavours.86 for code in CRSRegistry.supportedCodes {87 let crs = CRS(epsg: code)88 #expect(CRS.from(wkt: try #require(crs.ogcWKT)).epsg == code)89 let esri = try #require(crs.esriWKT)90 #expect(!esri.contains("AUTHORITY"))91 #expect(CRS.from(wkt: esri).epsg == code, "Esri text of EPSG:\(code)")92 }93 #expect(try CRS.parse(userInput: "epsg:26918").epsg == 26918)94 #expect(try CRS.parse(userInput: " 3857 ").epsg == 3857)95 #expect(try CRS.parse(userInput: "WGS84").epsg == 4326)96 #expect(throws: ConversionError.self) { _ = try CRS.parse(userInput: "Lambert") }97 }9899 /// The three cities in NAD83 / UTM zone 18N (EPSG:26918), from PROJ.100 static let citiesUTM18: [(Double, Double)] = [(611_928.7121664289, 5_039_683.6301076), (789_260.0040504602, 5_191_467.724107624), (445_454.3719848061, 5_030_011.834307104)]101102 static func utmShapefile(in temp: TempDir, prj: String?) -> URL {103 let dir = temp.sub("utm")104 let shp = dir.appendingPathComponent("towns.shp")105 try? ShapefileBytes.shp(type: 1, shapes: citiesUTM18.map { .point(x: $0.0, y: $0.1) }).write(to: shp)106 try? ShapefileBytes.dbf(columns: [.init(name: "name", type: "C", length: 12)], rows: Cities.names.map { [Array($0.utf8)] }).write(to: dir.appendingPathComponent("towns.dbf"))107 try? Data("UTF-8".utf8).write(to: dir.appendingPathComponent("towns.cpg"))108 if let prj { try? Data(prj.utf8).write(to: dir.appendingPathComponent("TOWNS.PRJ")) }109 return shp110 }111112 @Test(arguments: [FormatID.geojson, .kml, .gpx]) func reprojectsToWGS84(_ destination: FormatID) async throws {113 let temp = TempDir()114 let r = try await convert(Self.utmShapefile(in: temp, prj: Samples.utm18NAD83ESRI), .shapefile, to: destination, in: temp)115 for (i, f) in r.features.enumerated() {116 guard case .point(let c)? = f.geometry else { Issue.record("not a point"); continue }117 // 1e-8° ≈ 1 mm.118 #expect(abs(c.x - Cities.xyz[i].0) < 1e-8 && abs(c.y - Cities.xyz[i].1) < 1e-8, "\(c.x), \(c.y)")119 }120 #expect(r.output.facts["geo.source-crs"] == "EPSG:26918 (NAD83 / UTM zone 18N)")121 #expect(r.output.facts["geo.destination-crs"] == "EPSG:4326 (WGS 84)")122 #expect(r.output.facts["geo.transformation"] == "EPSG:26918 → EPSG:4326, NAD83 and WGS 84 treated as coincident (up to about 1–2 m)")123 #expect(r.warnings.first("crs-reprojected") != nil)124 #expect(r.warnings.first("crs-datum-coincident")?.severity == .caution)125 }126127 @Test func carriesProjectedCoordinatesUnchanged() async throws {128 let temp = TempDir()129 let shp = Self.utmShapefile(in: temp, prj: Samples.utm18NAD83ESRI)130 let gpkg = try await convert(shp, .shapefile, to: .geopackage, in: temp)131 #expect(gpkg.layers[0].crs.epsg == 26918)132 for (i, f) in gpkg.features.enumerated() { #expect(coordinates(f.geometry).first == Coordinate(Self.citiesUTM18[i].0, Self.citiesUTM18[i].1)) }133 #expect(gpkg.output.facts["geo.transformation"] == "none")134 #expect(gpkg.warnings.first("crs-reprojected") == nil)135 // And back to a shapefile: the .prj is regenerated and recognised.136 let back = try await convert(gpkg.output.files[0], .geopackage, to: .shapefile, in: temp)137 #expect(back.layers[0].crs.epsg == 26918)138 #expect(coordinates(back.features[2].geometry).first == Coordinate(Self.citiesUTM18[2].0, Self.citiesUTM18[2].1))139 // CSV keeps the numbers and says it cannot record the system.140 let csv = try await convert(shp, .shapefile, to: .csv, in: temp)141 #expect(csv.warnings.first("csv-crs-not-recorded")?.message.contains("EPSG:26918") == true)142 #expect(try String(contentsOf: csv.output.files[0], encoding: .utf8).hasPrefix("x,y,name\r\n611928.7121664289,5039683.6301076,Montréal\r\n"))143 }144145 @Test func explicitTargetReprojects() async throws {146 let temp = TempDir()147 let source = Cities.source(.geojson, in: temp)148 let r = try await convert(source, .geojson, to: .geopackage, in: temp, options: ["crs.target": .string("EPSG:32618")])149 #expect(r.layers[0].crs.epsg == 32618)150 // WGS 84 / UTM 18N of Montréal (PROJ).151 let c = try #require(coordinates(r.features[0].geometry).first)152 #expect(abs(c.x - 611_928.7121654929) < 1e-4 && abs(c.y - 5_039_683.630227742) < 1e-4)153 #expect(c.z == 36.5)154 #expect(r.output.facts["geo.transformation"] == "EPSG:4326 → EPSG:32618")155 // Web Mercator target, then back to WGS 84 through KML.156 let merc = try await convert(source, .geojson, to: .shapefile, in: temp, options: ["crs.target": .string("3857")])157 #expect(merc.layers[0].crs.epsg == 3857)158 let m = try #require(coordinates(merc.features[0].geometry).first)159 #expect(abs(m.x - -8_189_474.375035995) < 1e-6 && abs(m.y - 5_700_852.733103192) < 1e-6)160 let back = try await convert(merc.output.files[0].appendingPathComponent("cities.shp"), .shapefile, to: .kml, in: temp)161 let b = try #require(coordinates(back.features[0].geometry).first)162 #expect(abs(b.x - -73.5673) < 1e-9 && abs(b.y - 45.5017) < 1e-9)163 await #expect(throws: ConversionError.self) { _ = try await convert(source, .geojson, to: .geopackage, in: temp, options: ["crs.target": .string("EPSG:2154")]) }164 }165166 @Test func refusesUnknownSystemForWGS84Formats() async throws {167 let temp = TempDir()168 let shp = Self.utmShapefile(in: temp, prj: Samples.quebecLambertESRI)169 for destination in [FormatID.geojson, .kml, .gpx] {170 do {171 _ = try await convert(shp, .shapefile, to: destination, in: temp)172 Issue.record("\(destination) accepted an unknown reference system")173 } catch let error as ConversionError {174 guard case .invalidOption(let message) = error else { Issue.record("wrong error \(error)"); continue }175 #expect(message.contains("NAD_1983_Quebec_Lambert"), "\(message)")176 }177 }178 // Explicit opt-in: unchanged coordinates and a data-loss warning.179 let forced = try await convert(shp, .shapefile, to: .geojson, in: temp, options: ["crs.unsafe-passthrough": .bool(true)])180 #expect(forced.warnings.first("crs-unsafe-passthrough")?.severity == .dataLoss)181 #expect(coordinates(forced.features[0].geometry).first == Coordinate(Self.citiesUTM18[0].0, Self.citiesUTM18[0].1))182 #expect(forced.output.facts["geo.transformation"]?.contains("not WGS 84") == true)183 // Formats that carry a definition keep it verbatim.184 let gpkg = try await convert(shp, .shapefile, to: .geopackage, in: temp)185 #expect(gpkg.layers[0].crs.wkt == Samples.quebecLambertESRI && gpkg.layers[0].crs.epsg == nil)186 #expect(coordinates(gpkg.features[1].geometry).first == Coordinate(Self.citiesUTM18[1].0, Self.citiesUTM18[1].1))187 let again = try await convert(gpkg.output.files[0], .geopackage, to: .shapefile, in: temp)188 #expect(try String(contentsOf: again.output.files[0].appendingPathComponent("towns.prj"), encoding: .utf8) == Samples.quebecLambertESRI)189 }190191 @Test func missingPRJMustBeStated() async throws {192 let temp = TempDir()193 // Projected numbers without .prj: refused until the user states the system.194 let shp = Self.utmShapefile(in: temp, prj: nil)195 do {196 _ = try await convert(shp, .shapefile, to: .geojson, in: temp)197 Issue.record("accepted projected coordinates without a reference system")198 } catch let error as ConversionError {199 guard case .invalidOption(let m) = error else { Issue.record("wrong error \(error)"); return }200 #expect(m.contains("does not say which reference system"))201 }202 let stated = try await convert(shp, .shapefile, to: .geojson, in: temp, options: ["crs.source": .string("EPSG:26918")])203 let c = try #require(coordinates(stated.features[0].geometry).first)204 #expect(abs(c.x - -73.5673) < 1e-8 && abs(c.y - 45.5017) < 1e-8)205 // Degrees without .prj: assumed WGS 84, with a visible warning.206 let degrees = Cities.writeShapefile(in: temp.sub("noprj"), prj: nil)207 let assumed = try await convert(degrees, .shapefile, to: .geojson, in: temp)208 #expect(assumed.warnings.first("crs-assumed-wgs84")?.severity == .caution)209 #expect(assumed.output.facts["geo.source-crs"] == "EPSG:4326 (WGS 84)")210 // A stated system that contradicts the file wins and is reported.211 let overridden = try await convert(Self.utmShapefile(in: temp, prj: Samples.utm18NAD83ESRI), .shapefile, to: .geopackage, in: temp, options: ["crs.source": .string("EPSG:32618")])212 #expect(overridden.warnings.first("crs-overridden")?.message.contains("EPSG:26918") == true)213 #expect(overridden.layers[0].crs.epsg == 32618)214 }215216 @Test func axisOrderPerFormat() async throws {217 let temp = TempDir()218 // One point, longitude −73.5 (x), latitude 45.25 (y), written in each format's own order.219 let geojson = temp.write("a.geojson", "{\"type\":\"Point\",\"coordinates\":[-73.5,45.25]}")220 let kml = temp.write("a.kml", "<kml xmlns=\"http://www.opengis.net/kml/2.2\"><Placemark><Point><coordinates>-73.5,45.25</coordinates></Point></Placemark></kml>")221 let gpx = temp.write("a.gpx", "<gpx version=\"1.1\" xmlns=\"http://www.topografix.com/GPX/1/1\"><wpt lon=\"-73.5\" lat=\"45.25\"/></gpx>")222 let csvLatFirst = temp.write("a.csv", "lat,lon\n45.25,-73.5\n")223 let csvWKT = temp.write("b.csv", "id,wkt\n1,POINT (-73.5 45.25)\n")224 let expected = Coordinate(-73.5, 45.25)225 for (url, format) in [(geojson, FormatID.geojson), (kml, .kml), (gpx, .gpx), (csvLatFirst, .csv), (csvWKT, .csv)] {226 let layers = try GeoReader.read(url, format: format, options: GeoReadOptions(), check: {}).layers227 #expect(coordinates(layers[0].features[0].geometry) == [expected], "\(url.lastPathComponent)")228 }229 // Writers: the text carries the format's order.230 let toGPX = try await convert(geojson, .geojson, to: .gpx, in: temp)231 #expect(try String(contentsOf: toGPX.output.files[0], encoding: .utf8).contains("<wpt lat=\"45.25\" lon=\"-73.5\">"))232 let toKML = try await convert(gpx, .gpx, to: .kml, in: temp)233 #expect(try String(contentsOf: toKML.output.files[0], encoding: .utf8).contains("<coordinates>-73.5,45.25</coordinates>"))234 let toGeoJSON = try await convert(csvLatFirst, .csv, to: .geojson, in: temp)235 #expect(try String(contentsOf: toGeoJSON.output.files[0], encoding: .utf8).contains("\"coordinates\":[-73.5,45.25]"))236 let toCSV = try await convert(kml, .kml, to: .csv, in: temp)237 #expect(try String(contentsOf: toCSV.output.files[0], encoding: .utf8) == "longitude,latitude\r\n-73.5,45.25\r\n")238 // Swapped columns are caught by the value ranges instead of being accepted silently.239 let swapped = temp.write("swapped.csv", "lat,lon\n151.2093,-33.8688\n")240 #expect(throws: ConversionError.self) { _ = try GeoReader.read(swapped, format: .csv, options: GeoReadOptions(), check: {}) }241 // Legacy GeoJSON "crs": honoured, flagged, and x / y order kept.242 let legacy = temp.write("legacy.geojson", "{\"type\":\"FeatureCollection\",\"crs\":{\"type\":\"name\",\"properties\":{\"name\":\"urn:ogc:def:crs:EPSG::26918\"}},\"features\":[{\"type\":\"Feature\",\"properties\":{},\"geometry\":{\"type\":\"Point\",\"coordinates\":[611928.7121664289,5039683.6301076]}}]}")243 let l = try await convert(legacy, .geojson, to: .kml, in: temp)244 #expect(l.warnings.first("geojson-legacy-crs")?.severity == .caution)245 let p = try #require(coordinates(l.features[0].geometry).first)246 #expect(abs(p.x - -73.5673) < 1e-8 && abs(p.y - 45.5017) < 1e-8)247 let crs84 = temp.write("crs84.geojson", "{\"type\":\"FeatureCollection\",\"crs\":{\"type\":\"name\",\"properties\":{\"name\":\"urn:ogc:def:crs:OGC:1.3:CRS84\"}},\"features\":[]}")248 let d = try GeoReader.read(crs84, format: .geojson, options: GeoReadOptions(), check: {})249 #expect(d.layers[0].crs.epsg == 4326 && d.warnings.contains { $0.code == "geojson-legacy-crs" && $0.severity == .info })250 }251}252