// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! A reference ellipsoid: distances, bearings and destinations measured on //! it, and the spheres that stand in for it. //! //! Every datum is drawn on some ellipsoid: WGS 84 on its own, NAD83 and //! ETRS89 on GRS 80, NAD27 on Clarke 1866, OSGB36 on Airy 1830. `epsg` has //! every one the EPSG dataset knows. //! //! `distance`, `initialBearing` and `destination` work on the ellipsoid //! itself, along its geodesics, by Karney's algorithm in `Geodesic`: exact //! to about 15 nanometres. The same three on a `Sphere` are an //! approximation that is off by up to 0.56 per cent, and quicker. `sphere` //! makes one, from whichever of the ellipsoid's radii is to be kept true. //! //! **This does not convert between datums.** A datum is an ellipsoid *and* //! where it sits against the Earth, and the same place has coordinates //! differing by up to a hundred metres or so between NAD27 and NAD83, which //! no choice of radius does anything about. What it does is measure in the //! frame the coordinates were given in. The mean spheres of the EPSG //! ellipsoids differ by at most 2 040 metres of radius, between Zach 1812 and //! International 1924 -- one part in three thousand; those of WGS 84 and //! GRS 80 by less than a tenth of a millimetre. const std = @import("std"); const Geodesic = @import("Geodesic.zig"); const Position = @import("root.zig").Position; const spherical = @import("sphere.zig"); const Sphere = spherical.Sphere; const Ellipsoid = @This(); /// The equatorial radius, a, in metres. semi_major: f64, /// The polar radius, b, in metres. Kept rather than the flattening because /// some ellipsoids -- Clarke 1866 -- are defined by their two axes, and the /// rest are exact enough through `fromFlattening`. semi_minor: f64, /// The ellipsoid with equatorial radius `a` and flattening 1 / /// `inverse_flattening`, which is how most are defined. pub fn fromFlattening(a: f64, inverse_flattening: f64) Ellipsoid { return .{ .semi_major = a, .semi_minor = a - a / inverse_flattening }; } /// Every Earth ellipsoid in the EPSG Geodetic Parameter Dataset, generated /// from PROJ's copy of it by `tools/epsg_ellipsoids.py`: `epsg.clarke_1866`, /// `epsg.international_1924`, `epsg.airy_1830` and forty-seven more, and /// `epsg.all` to look through. pub const epsg = @import("epsg_ellipsoids.zig"); /// WGS 84, EPSG 7030: the ellipsoid of GPS and of GeoJSON, and so the one to /// use when nothing says otherwise. pub const wgs84 = epsg.wgs_84; /// GRS 80, EPSG 7019: NAD83, ETRS89, GDA2020, NZGD2000, the ITRF /// realizations, and some two hundred and fifty datums in all. It differs /// from WGS 84 by a tenth of a millimetre in the polar radius. pub const grs80 = epsg.grs_1980; /// The ellipsoid EPSG knows by `code` -- 7030 for WGS 84, 7008 for Clarke /// 1866 -- or null if it is not one of `epsg.all`. pub fn fromEpsg(code: u16) ?Ellipsoid { for (epsg.all) |entry| { if (entry.code == code) return entry.ellipsoid; } return null; } /// Every ellipsoid in `epsg.all` by its EPSG name, ignoring ASCII case: /// `"Clarke 1866"`, `"clarke 1866"` and `"CLARKE 1866"` are the same one. pub const by_name: std.StaticStringMapWithEql( Ellipsoid, std.static_string_map.eqlAsciiIgnoreCase, ) = .initComptime(kvs: { var kvs: [epsg.all.len]struct { []const u8, Ellipsoid } = undefined; for (&kvs, epsg.all) |*kv, entry| kv.* = .{ entry.name, entry.ellipsoid }; break :kvs kvs; }); /// The ellipsoid EPSG calls `name`, in any case -- `"WGS 84"`, /// `"international 1924"` -- or null if it is not one of `epsg.all`. pub fn fromName(name: []const u8) ?Ellipsoid { return by_name.get(name); } /// The flattening, (a − b) / a. pub fn flattening(ellipsoid: Ellipsoid) f64 { return (ellipsoid.semi_major - ellipsoid.semi_minor) / ellipsoid.semi_major; } /// The square of the first eccentricity, (a² − b²) / a². pub fn eccentricitySquared(ellipsoid: Ellipsoid) f64 { const f = ellipsoid.flattening(); return f * (2 - f); } /// R₁, the mean of the three semi-axes, (2a + b) / 3. The usual choice, and /// the one that is closest to right for a distance in no particular /// direction. pub fn meanRadius(ellipsoid: Ellipsoid) f64 { return (2 * ellipsoid.semi_major + ellipsoid.semi_minor) / 3; } /// R₂, the radius of the sphere with the same surface area as the /// ellipsoid: R₂² = a²/2 · (1 + (1 − e²) · atanh(e) / e). pub fn authalicRadius(ellipsoid: Ellipsoid) f64 { const a = ellipsoid.semi_major; const e2 = ellipsoid.eccentricitySquared(); // atanh(e) / e tends to one as e does; a sphere has no eccentricity to // divide by. if (e2 == 0) return a; const e = @sqrt(e2); return a * @sqrt((1 + (1 - e2) * std.math.atanh(e) / e) / 2); } /// R₃, the radius of the sphere with the same volume as the ellipsoid, /// ∛(a²b). pub fn volumetricRadius(ellipsoid: Ellipsoid) f64 { return std.math.cbrt(ellipsoid.semi_major * ellipsoid.semi_major * ellipsoid.semi_minor); } /// The ellipsoid's geodesics, for `Geodesic.inverse` and `Geodesic.direct` /// in terms of bare latitudes and longitudes, and the arrival azimuth and /// arc length the functions below leave out. /// /// The flattening comes from the two axes, so for an ellipsoid defined by /// a and 1/f it has been rounded twice. That moves a distance by about a /// nanometre in twenty thousand kilometres. pub fn geodesic(ellipsoid: Ellipsoid) Geodesic { return .init(ellipsoid.semi_major, ellipsoid.flattening()); } /// The length of the shortest path between two positions along the /// ellipsoid, in metres. /// /// Solved exactly, to rounding, for any two positions, antipodal ones /// included; see `Geodesic`. pub fn distance(ellipsoid: Ellipsoid, a: Position, b: Position) f64 { return ellipsoid.geodesic().inverse(a.latitude, a.longitude, b.latitude, b.longitude).distance; } /// The direction to set off in from `from` to reach `to` along the shortest /// path on the ellipsoid: degrees clockwise from true north, 0 to 360. /// /// Between two positions that are the same, or between antipodal ones where /// more than one path is shortest, there is no one direction, and the answer /// is one of them. pub fn initialBearing(ellipsoid: Ellipsoid, from: Position, to: Position) f64 { const azimuth = ellipsoid.geodesic().inverse(from.latitude, from.longitude, to.latitude, to.longitude).azimuth1; return spherical.normalizeBearing(azimuth); } /// Where one arrives setting off from `from` on `bearing` degrees and /// following the geodesic for `metres`. /// /// The result's longitude is normalized to [-180, 180) and its altitude is /// `from`'s. pub fn destination(ellipsoid: Ellipsoid, from: Position, bearing: f64, metres: f64) Position { const arrived = ellipsoid.geodesic().direct(from.latitude, from.longitude, bearing, metres); return .{ .longitude = spherical.normalizeLongitude(arrived.longitude), .latitude = arrived.latitude, .altitude = from.altitude, }; } /// Which of an ellipsoid's radii to make a sphere of. pub const Radius = enum { /// R₁, `meanRadius`. mean, /// R₂, `authalicRadius`: the same surface area. authalic, /// R₃, `volumetricRadius`: the same volume. volumetric, /// a, the largest: distances along the equator come out right. equatorial, /// b, the smallest. polar, }; /// A sphere of one of the ellipsoid's radii, to measure on. /// /// Between them the choices move a distance by a third of a per cent at /// most, from `polar` to `equatorial`; `mean`, `authalic` and `volumetric` /// agree to within about eight metres, a millionth. pub fn sphere(ellipsoid: Ellipsoid, radius: Radius) Sphere { return .{ .radius = switch (radius) { .mean => ellipsoid.meanRadius(), .authalic => ellipsoid.authalicRadius(), .volumetric => ellipsoid.volumetricRadius(), .equatorial => ellipsoid.semi_major, .polar => ellipsoid.semi_minor, } }; } const testing = std.testing; test "GRS 80's radii are Moritz's" { // Moritz gives them to a tenth of a millimetre. try testing.expectApproxEqAbs(6_356_752.3141, grs80.semi_minor, 1e-4); try testing.expectApproxEqAbs(0.00669438002290, grs80.eccentricitySquared(), 1e-14); try testing.expectApproxEqAbs(6_371_008.7714, grs80.meanRadius(), 1e-4); // Except this one, which Moritz gives as 6 371 007.1810: a tenth of a // millimetre high, as a truncated series would be. Worked to fifty // digits the closed form is 6 371 007.180 883 5. try testing.expectApproxEqAbs(6_371_007.1808835, grs80.authalicRadius(), 1e-6); try testing.expectApproxEqAbs(6_371_000.7900, grs80.volumetricRadius(), 1e-4); } test "GRS 80's mean sphere is the one sphere measures on" { try testing.expectApproxEqAbs(@import("sphere.zig").earth_mean_radius, grs80.sphere(.mean).radius, 1e-4); } test "WGS 84 and GRS 80 differ by a tenth of a millimetre" { try testing.expectEqual(wgs84.semi_major, grs80.semi_major); // WGS 84 is the rounder of the two, by a flattening that differs in the // eleventh digit. const polar = wgs84.semi_minor - grs80.semi_minor; try testing.expect(polar > 0.00005 and polar < 0.0002); try testing.expectApproxEqAbs(grs80.meanRadius(), wgs84.meanRadius(), 1e-4); } test "a sphere's radii are all its radius" { const round: Ellipsoid = .{ .semi_major = 6_371_000, .semi_minor = 6_371_000 }; inline for (@typeInfo(Radius).@"enum".field_names) |name| { try testing.expectEqual(@as(f64, 6_371_000), round.sphere(@field(Radius, name)).radius); } } test "the radii fall in order" { for (epsg.all) |entry| { const e = entry.ellipsoid; errdefer std.debug.print("{s}, EPSG {d}\n", .{ entry.name, entry.code }); if (e.semi_minor == e.semi_major) { // One of EPSG's authalic spheres, whose radii are all the same. try testing.expectEqual(e.semi_major, e.authalicRadius()); continue; } try testing.expect(e.semi_minor < e.volumetricRadius()); try testing.expect(e.volumetricRadius() < e.authalicRadius()); try testing.expect(e.authalicRadius() < e.meanRadius()); try testing.expect(e.meanRadius() < e.semi_major); } } test "every EPSG ellipsoid is the Earth's size" { // A unit wrongly converted, or not converted at all, is a factor of // three: nothing in the dataset is more than a few kilometres from the // mean. for (epsg.all) |entry| { errdefer std.debug.print("{s}, EPSG {d}\n", .{ entry.name, entry.code }); try testing.expectApproxEqAbs(@as(f64, 6_371_000), entry.ellipsoid.meanRadius(), 5_000); } } test "EPSG codes find their ellipsoids" { try testing.expectEqual(wgs84, fromEpsg(7030).?); try testing.expectEqual(grs80, fromEpsg(7019).?); try testing.expectEqual(epsg.clarke_1866, fromEpsg(7008).?); try testing.expectEqual(@as(?Ellipsoid, null), fromEpsg(4326)); } test "names find their ellipsoids, in any case" { try testing.expectEqual(wgs84, fromName("WGS 84").?); try testing.expectEqual(wgs84, fromName("wgs 84").?); try testing.expectEqual(epsg.clarke_1880_rgs, fromName("CLARKE 1880 (RGS)").?); try testing.expectEqual(@as(?Ellipsoid, null), fromName("WGS84")); try testing.expectEqual(@as(?Ellipsoid, null), fromName("")); } test "every EPSG name finds its own ellipsoid" { for (epsg.all, 0..) |entry, i| { errdefer std.debug.print("{s}, EPSG {d}\n", .{ entry.name, entry.code }); try testing.expectEqual(entry.ellipsoid, fromName(entry.name).?); // Two names the same but for case would make one of them // unreachable, whichever the map happened to keep. for (epsg.all[i + 1 ..]) |other| { try testing.expect(!std.ascii.eqlIgnoreCase(entry.name, other.name)); } } } test "distances on WGS 84 are Karney's" { // GeodSolve0 of Karney's tests: JFK to CDG, 5 853 226 m on WGS 84. const jfk: Position = .{ .longitude = -73.8, .latitude = 40.6 }; const cdg: Position = .{ .longitude = 2.55, .latitude = 49.01666667 }; try testing.expectApproxEqAbs(5_853_226, wgs84.distance(jfk, cdg), 0.5); try testing.expectApproxEqAbs(53.47022, wgs84.initialBearing(jfk, cdg), 0.5e-5); // And the flattening from the two axes costs nothing that shows. const exact: Geodesic = .init(6_378_137, 1.0 / 298.257223563); try testing.expectApproxEqAbs(exact.inverse(40.6, -73.8, 49.01666667, 2.55).distance, wgs84.distance(jfk, cdg), 1e-8); } test "the mean sphere is within 0.56 per cent of the ellipsoid" { const places = [_]Position{ .{ .longitude = -93.625, .latitude = 41.5868 }, .{ .longitude = 151.2, .latitude = -33.9 }, .{ .longitude = 0, .latitude = 89 }, .{ .longitude = 100, .latitude = 0 }, .{ .longitude = -60, .latitude = -70 }, }; const mean = wgs84.sphere(.mean); for (places) |a| for (places) |b| { const on_ellipsoid = wgs84.distance(a, b); const on_sphere = mean.distance(a, b); try testing.expect(@abs(on_sphere - on_ellipsoid) <= 0.0057 * on_ellipsoid + 1e-6); }; } test "the ellipsoid's destination undoes its distance and bearing" { const here: Position = .{ .longitude = -93.625, .latitude = 41.5868, .altitude = 290 }; const there: Position = .{ .longitude = 151.2, .latitude = -33.9 }; for ([_]Ellipsoid{ wgs84, epsg.clarke_1866, epsg.airy_1830 }) |e| { const arrived = e.destination(here, e.initialBearing(here, there), e.distance(here, there)); try testing.expectApproxEqAbs(@as(f64, 0), e.distance(arrived, there), 1e-6); try testing.expectEqual(here.altitude, arrived.altitude); } } test "nearly antipodal points, where Vincenty fails, have a distance" { // GeodSolve9: Vincenty's iteration does not converge here. const a: Position = .{ .longitude = 0, .latitude = 56.320923501171 }; const b: Position = .{ .longitude = 179.664747671772880215, .latitude = -56.320923501171 }; try testing.expectApproxEqAbs(19_993_558.287, wgs84.distance(a, b), 0.5e-3); } test "Clarke 1866's flattening is the one it is known by" { // Defined by its axes; the flattening that follows is 1 / 294.978698. try testing.expectApproxEqAbs(294.978698, 1 / epsg.clarke_1866.flattening(), 1e-6); } test "Clarke 1858, in Clarke's feet, is in metres" { // 20 926 348 and 20 855 233 Clarke's feet, at 0.3047972654 m to the foot. try testing.expectApproxEqAbs(6_378_293.645, epsg.clarke_1858.semi_major, 1e-3); try testing.expectApproxEqAbs(6_356_617.988, epsg.clarke_1858.semi_minor, 1e-3); }