// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! `geo.Geodesic` against `geodesic.c`, the C it was ported from, on //! generated input. //! //! Every case is solved by both, on the same ellipsoid built from the same //! two doubles, and the answers have to agree: //! //! * a distance to `distance_tolerance`, which is a few ulps of the longest //! one; //! * an azimuth to `azimuth_tolerance` -- or, where they differ by more, the //! port's azimuth has to be confirmed by the C following it. At the start //! of a line it has to be *another* shortest path: that is the case for a //! line a few nanometres long, whose ends differ in the last bit of their //! coordinates, and for antipodal points, where more than one path is //! shortest. At the end of one it has to lead back to the start, which //! near a pole it can do while differing a good deal, since there the //! azimuth is measured from whichever meridian a nanometre lands on. //! Anywhere else a different azimuth is a wrong one, and following it //! misses by centimetres; //! * an arrival to `arrival_tolerance`, measured by the C as the distance //! between the two; //! * for input out of range, a NaN from both; for input in range, an answer //! from the port, always. geodesic.c v2.2 answers some valid inputs on a //! prolate ellipsoid with a NaN, which the port departs from it to avoid //! (see `Geodesic.inverse`), and there the port's answer has to be //! confirmed by the C following it. //! //! The two are not bit for bit the same, and cannot be: Zig's `sin`, `cos` //! and `atan2` round differently from the C library's in the last place. //! //! The input is weighted towards where geodesic algorithms go wrong -- //! nearly antipodal points, very short lines, the poles and the equator, //! whole degrees that take the exact-reduction paths, the regression cases //! from Karney's own tests nudged by an ulp or two, and coordinates out of //! range -- over every ellipsoid in the EPSG dataset, a sphere, and three //! that are far from the Earth's shape to make the series work harder. //! //! zig build run -- --iterations 1000000 //! zig build run -- --seconds 600 //! zig build run -- --seed 12345 # exactly again const std = @import("std"); const geo = @import("geo"); const c = @import("geodesic"); const Geodesic = geo.Geodesic; /// A few ulps of twenty thousand kilometres, whose ulp is 3.7 nm. const distance_tolerance = 2e-8; /// About a micrometre at the Earth's radius. const azimuth_tolerance = 1e-8; /// How far apart two answers to the direct problem may land, and how close /// the port's azimuth has to lead to count as another shortest path. const arrival_tolerance = 1e-7; /// An ellipsoid, as the two numbers both implementations are built from. const Model = struct { name: []const u8, a: f64, f: f64 }; const models = blk: { const Ellipsoid = geo.Ellipsoid; const extra = [_]Model{ .{ .name = "sphere", .a = 6.4e6, .f = 0 }, .{ .name = "prolate, f = -1/150", .a = 6.4e6, .f = -1.0 / 150.0 }, .{ .name = "oblate, f = 1/50", .a = 6.4e6, .f = 1.0 / 50.0 }, .{ .name = "oblate, f = 1/10", .a = 6.4e6, .f = 0.1 }, }; var all: [Ellipsoid.epsg.all.len + extra.len]Model = undefined; @setEvalBranchQuota(10_000); for (Ellipsoid.epsg.all, 0..) |entry, i| { all[i] = .{ .name = entry.name, .a = entry.ellipsoid.semi_major, .f = entry.ellipsoid.flattening() }; } for (extra, Ellipsoid.epsg.all.len..) |m, i| all[i] = m; break :blk all; }; /// Inverse problems that have broken geodesic code before: Karney's /// regression cases from geodtest.c, as lat1, lon1, lat2, lon2. const hard = [_][4]f64{ .{ 40.6, -73.8, 49.01666667, 2.55 }, .{ 36.493349428792, 0, 36.49334942879201, 0.0000008 }, .{ 88.202499451857, 0, -88.202499451857, 179.981022032992859592 }, .{ 89.262080389218, 0, -89.262080389218, 179.992207982775375662 }, .{ 89.333123580033, 0, -89.333123580032997687, 179.99295812360148422 }, .{ 56.320923501171, 0, -56.320923501171, 179.664747671772880215 }, .{ 52.784459512564, 0, -52.784459512563990912, 179.634407464943777557 }, .{ 48.522876735459, 0, -48.52287673545898293, 179.599720456223079643 }, .{ 0.07476, 0, -0.07476, 180 }, .{ 0.1, 0, -0.1, 180 }, .{ 0, 0, 0, 179 }, .{ 0, 0, 0, 179.5 }, .{ 0, 0, 0, 180 }, .{ 0, 0, 0.5, 180 }, .{ 0, 0, 1, 180 }, .{ 20.001, 0, 20.001, 0 }, .{ 90, 0, 90, 180 }, .{ 90, 0, -90, 0 }, .{ 0, 0, 0, 0 }, .{ -0.0, 0, 0, -0.0 }, .{ 0.01777745589997, 30, 90, 0 }, }; const Checker = struct { cases: u64 = 0, failures: u64 = 0, /// How many azimuths differed by more than `azimuth_tolerance` and were /// confirmed by following them: another shortest path, or an arrival /// azimuth that leads back to the start. confirmed: u64 = 0, /// How many times geodesic.c answered NaN for valid input and the /// port's answer was confirmed instead. upstream_nans: u64 = 0, worst_distance: f64 = 0, worst_azimuth: f64 = 0, worst_arrival: f64 = 0, /// Counts a failure, and prints the first twenty: what went in and /// what each side said, as named values. fn fail(checker: *Checker, comptime what: []const u8, model: Model, inputs: anytype, outputs: anytype) void { checker.failures += 1; if (checker.failures > 20) return; std.debug.print("FAIL " ++ what ++ " on {s} (a = {e}, f = {e}):\n", .{ model.name, model.a, model.f }); inline for (.{ inputs, outputs }) |values| { inline for (@typeInfo(@TypeOf(values)).@"struct".field_names) |name| { std.debug.print(" {s} = {e}\n", .{ name, @field(values, name) }); } } // The same case again, exactly: every input as the bits of its // double, since a decimal is one more thing to get wrong. std.debug.print(" again: zig build run -- --" ++ (if (std.mem.startsWith(u8, what, "inverse")) "inverse" else "direct") ++ " {d}", .{modelIndex(model)}); inline for (@typeInfo(@TypeOf(inputs)).@"struct".field_names) |name| { std.debug.print(" 0x{x}", .{@as(u64, @bitCast(@as(f64, @field(inputs, name))))}); } std.debug.print("\n", .{}); } fn inverse(checker: *Checker, model: Model, lat1: f64, lon1: f64, lat2: f64, lon2: f64) void { checker.cases += 1; var g: c.struct_geod_geodesic = undefined; c.geod_init(&g, model.a, model.f); const port: Geodesic = .init(model.a, model.f); var s12: f64 = undefined; var azi1: f64 = undefined; var azi2: f64 = undefined; c.geod_inverse(&g, lat1, lon1, lat2, lon2, &s12, &azi1, &azi2); const z = port.inverse(lat1, lon1, lat2, lon2); const inputs = .{ .lat1 = lat1, .lon1 = lon1, .lat2 = lat2, .lon2 = lon2 }; const valid = validLatitude(lat1) and validLatitude(lat2) and std.math.isFinite(lon1) and std.math.isFinite(lon2); if (!valid) { if (!(std.math.isNan(s12) and std.math.isNan(z.distance))) checker.fail("inverse: invalid input without a NaN on both sides", model, inputs, .{ .c_s12 = s12, .port_s12 = z.distance }); return; } if (!std.math.isFinite(z.distance) or !std.math.isFinite(z.azimuth1) or !std.math.isFinite(z.azimuth2)) { checker.fail("inverse: no answer for valid input", model, inputs, .{ .c_s12 = s12, .port_s12 = z.distance, .port_azi1 = z.azimuth1, .port_azi2 = z.azimuth2 }); return; } if (std.math.isNan(s12)) { // geodesic.c's own NaN for valid input, which the port departs // from it to avoid: see `Geodesic.inverse`. The port's answer // stands if the C, following the port's azimuth for the port's // distance, arrives. var lat: f64 = undefined; var lon: f64 = undefined; c.geod_direct(&g, lat1, lon1, z.azimuth1, z.distance, &lat, &lon, null); var miss: f64 = undefined; c.geod_inverse(&g, lat, lon, lat2, lon2, &miss, null, null); if (!(miss <= arrival_tolerance)) { checker.fail("inverse: where the C has no answer, the port's is wrong", model, inputs, .{ .port_s12 = z.distance, .port_azi1 = z.azimuth1, .port_misses_by = miss }); } else { checker.upstream_nans += 1; } return; } const ds = @abs(z.distance - s12); checker.worst_distance = @max(checker.worst_distance, ds); if (ds > distance_tolerance) checker.fail("inverse: distance", model, inputs, .{ .c_s12 = s12, .port_s12 = z.distance }); const da = @max(angleDiff(z.azimuth1, azi1), angleDiff(z.azimuth2, azi2)); if (da <= azimuth_tolerance) { checker.worst_azimuth = @max(checker.worst_azimuth, da); return; } // Another shortest path, or a wrong one: follow the port's azimuth // for the C's distance and see where it arrives. var lat: f64 = undefined; var lon: f64 = undefined; c.geod_direct(&g, lat1, lon1, z.azimuth1, s12, &lat, &lon, null); var miss: f64 = undefined; c.geod_inverse(&g, lat, lon, lat2, lon2, &miss, null, null); if (miss > arrival_tolerance) { checker.fail("inverse: azimuth", model, inputs, .{ .c_azi1 = azi1, .port_azi1 = z.azimuth1, .c_azi2 = azi2, .port_azi2 = z.azimuth2, .s12 = s12, .port_azimuth_misses_by = miss, }); } else { checker.confirmed += 1; } } fn direct(checker: *Checker, model: Model, lat1: f64, lon1: f64, azi1: f64, s12: f64) void { checker.cases += 1; var g: c.struct_geod_geodesic = undefined; c.geod_init(&g, model.a, model.f); const port: Geodesic = .init(model.a, model.f); var lat2: f64 = undefined; var lon2: f64 = undefined; var azi2: f64 = undefined; c.geod_direct(&g, lat1, lon1, azi1, s12, &lat2, &lon2, &azi2); const z = port.direct(lat1, lon1, azi1, s12); const inputs = .{ .lat1 = lat1, .lon1 = lon1, .azi1 = azi1, .s12 = s12 }; const port_nan = std.math.isNan(z.latitude) or std.math.isNan(z.longitude) or std.math.isNan(z.azimuth); const c_nan = std.math.isNan(lat2) or std.math.isNan(lon2) or std.math.isNan(azi2); if (port_nan or c_nan) { if (port_nan != c_nan) checker.fail("direct: a NaN on one side only", model, inputs, .{ .c_lat2 = lat2, .port_lat2 = z.latitude, .c_lon2 = lon2, .port_lon2 = z.longitude }); return; } var miss: f64 = undefined; c.geod_inverse(&g, z.latitude, z.longitude, lat2, lon2, &miss, null, null); checker.worst_arrival = @max(checker.worst_arrival, miss); if (!(miss <= arrival_tolerance)) checker.fail("direct: arrival", model, inputs, .{ .c_lat2 = lat2, .port_lat2 = z.latitude, .c_lon2 = lon2, .port_lon2 = z.longitude, .apart = miss }); const da = angleDiff(z.azimuth, azi2); if (da <= azimuth_tolerance) { checker.worst_azimuth = @max(checker.worst_azimuth, da); return; } // Near a pole the azimuth on arrival is measured from whichever // meridian the longitude names, so a nanometre moves it a long way. // It is right if turning round on it and going back the same // distance returns to the start; a wrong one, at these distances, // misses by centimetres. var back_lat: f64 = undefined; var back_lon: f64 = undefined; c.geod_direct(&g, z.latitude, z.longitude, z.azimuth + 180, s12, &back_lat, &back_lon, null); var home: f64 = undefined; c.geod_inverse(&g, back_lat, back_lon, lat1, lon1, &home, null, null); if (!(home <= arrival_tolerance)) { checker.fail("direct: azimuth", model, inputs, .{ .c_azi2 = azi2, .port_azi2 = z.azimuth, .going_back_misses_by = home }); } else { checker.confirmed += 1; } } }; fn validLatitude(lat: f64) bool { return @abs(lat) <= 90; } fn modelIndex(model: Model) usize { for (models, 0..) |m, i| if (m.a == model.a and m.f == model.f and std.mem.eql(u8, m.name, model.name)) return i; unreachable; } /// The difference between two angles in degrees, the short way round. fn angleDiff(x: f64, y: f64) f64 { const d = @mod(@abs(x - y), 360); return @min(d, 360 - d); } /// `x` moved by up to three ulps either way. fn nudge(r: std.Random, x: f64) f64 { var y = x; const steps = r.uintAtMost(u2, 3); const up = r.boolean(); for (0..steps) |_| y = std.math.nextAfter(f64, y, if (up) std.math.inf(f64) else -std.math.inf(f64)); return y; } fn uniform(r: std.Random, lo: f64, hi: f64) f64 { return lo + (hi - lo) * r.float(f64); } /// Up to `scale`, spread over `decades` orders of magnitude below it. fn small(r: std.Random, scale: f64, decades: f64) f64 { return (r.float(f64) - 0.5) * scale * std.math.pow(f64, 10, -decades * r.float(f64)); } /// One case of each problem on one ellipsoid. fn one(checker: *Checker, r: std.Random) void { const model = models[r.uintLessThan(usize, models.len)]; var lat1 = uniform(r, -90, 90); var lon1 = uniform(r, -180, 180); var lat2 = uniform(r, -90, 90); var lon2 = uniform(r, -180, 180); switch (r.uintLessThan(u8, 7)) { 0 => {}, // anywhere 1 => { // nearly antipodal lat2 = std.math.clamp(-lat1 + small(r, 1e-2, 10), -90, 90); lon2 = lon1 + 180 + small(r, 1e-1, 10); }, 2 => { // very short lat2 = std.math.clamp(lat1 + small(r, 1, 14), -90, 90); lon2 = lon1 + small(r, 1, 14); }, 3 => { // the poles and the equator const special = [_]f64{ 90, -90, 0, -0.0, 1e-300, -1e-300, 89.99999999999, 1e-14 }; lat2 = special[r.uintLessThan(usize, special.len)]; if (r.boolean()) lat1 = special[r.uintLessThan(usize, special.len)]; }, 4 => { // whole degrees, including longitudes out past +/-180 lat1 = @floatFromInt(r.intRangeAtMost(i32, -90, 90)); lon1 = @floatFromInt(r.intRangeAtMost(i32, -720, 720)); lat2 = @floatFromInt(r.intRangeAtMost(i32, -90, 90)); lon2 = @floatFromInt(r.intRangeAtMost(i32, -720, 720)); }, 5 => { // a regression case, nudged const h = hard[r.uintLessThan(usize, hard.len)]; lat1 = std.math.clamp(nudge(r, h[0]), -90, 90); lon1 = nudge(r, h[1]); lat2 = std.math.clamp(nudge(r, h[2]), -90, 90); lon2 = nudge(r, h[3]); }, else => { // out of range const bad = [_]f64{ 90.0000001, -91, 1e300, std.math.inf(f64), -std.math.inf(f64), std.math.nan(f64) }; const x = bad[r.uintLessThan(usize, bad.len)]; switch (r.uintLessThan(u8, 4)) { 0 => lat1 = x, 1 => lat2 = x, 2 => lon1 = x, else => lon2 = x, } }, } checker.inverse(model, lat1, lon1, lat2, lon2); const azimuths = [_]f64{ 0, 90, 180, -180, -90, 1e-300 }; const azi = if (r.uintLessThan(u8, 4) == 0) azimuths[r.uintLessThan(usize, azimuths.len)] else uniform(r, -540, 540); const s12 = switch (r.uintLessThan(u8, 3)) { 0 => small(r, 1, 12), 1 => uniform(r, -2.5e7, 4.5e7), else => uniform(r, 1.99e7, 2.01e7), // about half way round }; checker.direct(model, if (std.math.isFinite(lat1)) lat1 else 0, if (std.math.isFinite(lon1)) lon1 else 0, azi, s12); } /// Every hard case, both ways round, on every ellipsoid. fn hardCases(checker: *Checker) void { for (models) |model| for (hard) |h| { checker.inverse(model, h[0], h[1], h[2], h[3]); checker.inverse(model, h[2], h[3], h[0], h[1]); }; } pub fn main(init: std.process.Init) !void { const io = init.io; var seconds: ?u32 = null; var iterations: u64 = 1_000_000; var seed: u64 = @bitCast(@as(i64, @truncate(std.Io.Timestamp.now(io, .real).nanoseconds))); var args: std.process.Args.Iterator = .init(init.minimal.args); _ = args.skip(); var replay: ?enum { inverse, direct } = null; var replay_args: [5]u64 = undefined; while (args.next()) |arg| { if (std.mem.eql(u8, arg, "--inverse") or std.mem.eql(u8, arg, "--direct")) { replay = if (std.mem.eql(u8, arg, "--inverse")) .inverse else .direct; for (&replay_args) |*a| a.* = std.fmt.parseInt(u64, args.next() orelse "", 0) catch { std.debug.print("--{s} takes an ellipsoid's index and four doubles as bits, as a failure prints them\n", .{@tagName(replay.?)}); std.process.exit(2); }; continue; } if (std.mem.eql(u8, arg, "--seconds")) { seconds = std.fmt.parseInt(u32, args.next() orelse "", 10) catch null; } else if (std.mem.eql(u8, arg, "--iterations")) { iterations = std.fmt.parseInt(u64, args.next() orelse "", 10) catch iterations; } else if (std.mem.eql(u8, arg, "--seed")) { seed = std.fmt.parseInt(u64, args.next() orelse "", 10) catch seed; } else { std.debug.print( \\usage: geodesic-reference [--iterations N | --seconds N] [--seed S] \\ geodesic-reference --inverse|--direct ELLIPSOID A B C D \\ , .{}); std.process.exit(2); } } if (replay) |problem| { var checker: Checker = .{}; const model = models[@min(replay_args[0], models.len - 1)]; const x: [4]f64 = .{ @bitCast(replay_args[1]), @bitCast(replay_args[2]), @bitCast(replay_args[3]), @bitCast(replay_args[4]) }; switch (problem) { .inverse => checker.inverse(model, x[0], x[1], x[2], x[3]), .direct => checker.direct(model, x[0], x[1], x[2], x[3]), } std.debug.print("{s}\n", .{if (checker.failures == 0) "agrees" else "disagrees"}); std.process.exit(if (checker.failures == 0) 0 else 1); } std.debug.print("seed {d}\n", .{seed}); var prng: std.Random.DefaultPrng = .init(seed); const r = prng.random(); var checker: Checker = .{}; hardCases(&checker); const start = std.Io.Timestamp.now(io, .awake).nanoseconds; var runs: u64 = 0; while (true) : (runs += 1) { if (seconds) |s| { // The clock is not cheap enough to read every time. if (runs % 4096 == 0 and std.Io.Timestamp.now(io, .awake).nanoseconds - start >= @as(i96, s) * std.time.ns_per_s) break; } else if (runs >= iterations) break; one(&checker, r); } std.debug.print( \\{d} cases on {d} ellipsoids, {d} failed \\worst distance difference {e:.2} m (allowed {e}) \\worst azimuth difference {e:.2} deg (allowed {e}), and {d} that differed by more but were confirmed by following them \\worst arrival difference {e:.2} m (allowed {e}) \\{d} valid inputs geodesic.c answered NaN, where the port's answer was confirmed instead \\ , .{ checker.cases, models.len, checker.failures, checker.worst_distance, distance_tolerance, checker.worst_azimuth, azimuth_tolerance, checker.confirmed, checker.worst_arrival, arrival_tolerance, checker.upstream_nans, }); if (checker.failures > 0) std.process.exit(1); } test "the hard cases agree on every ellipsoid" { var checker: Checker = .{}; hardCases(&checker); try std.testing.expectEqual(@as(u64, 0), checker.failures); }