SPB Git

Repository Public BSD-3-Clause

TerrainTests.swift 9.9 KB 195 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Maps9// File             : Packages/ORIXTerrain/Tests/ORIXTerrainTests/TerrainTests.swift10// Module           : ORIXTerrainTests11// Repository       : https://git.spboucher.ai/orix-maps12// Created          : 2026-11-2513// Last Modified    : 2026-11-2514//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author           : Simon-Pierre Boucher20// Position         : Professor of Finance21// Institution      : Université du Québec en Outaouais (UQO)22// Department       : Département des sciences administratives23// Organization     : SP Boucher24//25// Website          : https://spboucher.ai26// Git              : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General          : info@spboucher.ai33// Professional     : contact@spboucher.ai34// Direct           : simon@spboucher.ai35// Research         : research@spboucher.ai36// Development      : dev@spboucher.ai37// Support          : support@spboucher.ai38// Security/Admin   : admin@spboucher.ai39// Notifications    : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification   : Public66// Distribution     : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License          : Proprietary, all rights reserved (see license file)80// License File     : LICENSE81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import Foundation89import ORIXGeoCore90import Testing91@testable import ORIXTerrain9293/// A 3-arc-second tile whose elevation is a plane: 100 m at the south edge rising 1 000 m to the north edge, plus94/// 500 m from west to east, with an optional void square.95private func planeTile(lat: Int = 45, lon: Int = -74, voidRows: ClosedRange<Int>? = nil) throws -> HGTTile {96    let n = 120197    var bytes = [UInt8](repeating: 0, count: n * n * 2)98    for row in 0..<n {99        for col in 0..<n {100            var v = Int16((100 + 1_000 * Double(n - 1 - row) / Double(n - 1) + 500 * Double(col) / Double(n - 1)).rounded())101            if let r = voidRows, r.contains(row), r.contains(col) { v = HGTTile.void }102            let u = UInt16(bitPattern: v)103            bytes[(row * n + col) * 2] = UInt8(u >> 8); bytes[(row * n + col) * 2 + 1] = UInt8(u & 0xff)104        }105    }106    return try HGTTile(data: Data(bytes), southWestLatitude: lat, southWestLongitude: lon, datasetName: "Synthetic plane")107}108109@Suite struct HGTTests {110    @Test func cornersEdgesAndInterpolation() throws {111        let t = try planeTile()112        #expect(t.samplesPerSide == 1201)113        #expect(t.elevation(at: Coordinate(latitude: 45, longitude: -74)) == 100)114        #expect(t.elevation(at: Coordinate(latitude: 46, longitude: -74)) == 1_100)115        #expect(t.elevation(at: Coordinate(latitude: 45, longitude: -73)) == 600)116        #expect(t.elevation(at: Coordinate(latitude: 46, longitude: -73)) == 1_600)117        let mid = try #require(t.elevation(at: Coordinate(latitude: 45.5, longitude: -73.5)))118        #expect(abs(mid - 850) < 1)119        let between = try #require(t.elevation(at: Coordinate(latitude: 45.123_456, longitude: -73.987_654)))120        #expect(abs(between - (100 + 123.456 + 500 * 0.012_346)) < 1.5)121        #expect(t.elevation(at: Coordinate(latitude: 46.001, longitude: -73.5)) == nil)122        #expect(t.elevation(at: Coordinate(latitude: 45.5, longitude: -74.001)) == nil)123        #expect(abs(t.resolutionMeters(atLatitude: 45) - 92.7) < 0.5)124    }125126    @Test func voidsAreUnknownNotZero() throws {127        let t = try planeTile(voidRows: 590...610)128        #expect(t.elevation(at: Coordinate(latitude: 45.5, longitude: -73.5)) == nil)129        #expect(t.elevation(at: Coordinate(latitude: 45.9, longitude: -73.1)) != nil)130    }131132    @Test func rejectsWrongSizesAndNames() throws {133        #expect(throws: TerrainError.invalidSize(1000)) { _ = try HGTTile(data: Data(count: 1000), southWestLatitude: 45, southWestLongitude: -74) }134        #expect(throws: TerrainError.self) { _ = try HGTTile(data: Data(count: 1201 * 1201 * 2), southWestLatitude: 90, southWestLongitude: 0) }135        #expect(try HGTTile.corner(fromName: "N45W074.hgt") == (45, -74))136        #expect(try HGTTile.corner(fromName: "s33e151") == (-33, 151))137        for bad in ["", "N45W74", "X45W074", "N4AW074", "N95W074", "N45W181", "N45W0745"] {138            #expect(throws: TerrainError.self) { _ = try HGTTile.corner(fromName: bad) }139        }140    }141142    @Test func mosaicPicksTheRightTileAndReportsGaps() throws {143        let m = ElevationMosaic(tiles: [try planeTile(lat: 45, lon: -74), try planeTile(lat: 46, lon: -74)], datasetName: "Two tiles")144        #expect(m.elevation(at: Coordinate(latitude: 45.5, longitude: -73.5)) != nil)145        #expect(m.elevation(at: Coordinate(latitude: 46.5, longitude: -73.5)) != nil)146        #expect(m.elevation(at: Coordinate(latitude: 47.5, longitude: -73.5)) == nil)147        #expect(m.elevation(at: Coordinate(latitude: 45.5, longitude: -72.5)) == nil)148        #expect(ElevationMosaic(tiles: [], datasetName: "none").resolutionMeters(atLatitude: 0) == .infinity)149    }150}151152@Suite struct ProfileTests {153    @Test func profileAlongAClimbHasTheRightTotals() throws {154        let t = try planeTile()155        // Due north along the west edge: 0.5° of latitude = 500 m of climb over about 55.6 km.156        let line = [Coordinate(latitude: 45.2, longitude: -74), Coordinate(latitude: 45.7, longitude: -74)]157        let p = ElevationProfile(line: line, source: t, spacing: 30)158        #expect(p.coverage == 1 && p.datasetName == "Synthetic plane" && abs(p.resolutionMeters - 92.7) < 0.5)159        #expect(abs(p.samples.last!.distance - Geodesy.length(of: line)) < 1)160        // Sampling never goes finer than the data resolution.161        #expect(p.samples.count < Int(Geodesy.length(of: line) / 90) + 3)162        let totals = try #require(p.ascentAndDescent())163        #expect(abs(totals.ascent - 500) < 6 && totals.descent == 0)164        #expect(abs(p.minElevation! - 300) < 1 && abs(p.maxElevation! - 800) < 1)165        let grade = try #require(p.maxGrade(window: 500))166        #expect(abs(grade - 500 / Geodesy.length(of: line)) < 0.002)167        let down = ElevationProfile(line: line.reversed(), source: t)168        #expect(abs(down.ascentAndDescent()!.descent - 500) < 6 && down.ascentAndDescent()!.ascent == 0)169    }170171    @Test func missingDataStaysMissing() throws {172        let t = try planeTile(voidRows: 590...610)173        // A line crossing the void and then leaving the tile.174        let line = [Coordinate(latitude: 45.5, longitude: -73.9), Coordinate(latitude: 45.5, longitude: -72.8)]175        let p = ElevationProfile(line: line, source: t, spacing: 200)176        #expect(p.coverage > 0.5 && p.coverage < 0.95)177        #expect(p.samples.last?.elevation == nil)178        #expect(p.samples.contains { $0.elevation == nil && $0.coordinate.longitude < -73.45 && $0.coordinate.longitude > -73.52 })179        // The climb is not counted across the gap as if the ground were continuous.180        let totals = try #require(p.ascentAndDescent(threshold: 1))181        #expect(totals.ascent < 500 * 1.0 && totals.descent == 0)182        let nothing = ElevationProfile(line: [Coordinate(latitude: 10, longitude: 10), Coordinate(latitude: 10.1, longitude: 10)], source: t)183        #expect(nothing.coverage == 0 && nothing.ascentAndDescent() == nil && nothing.minElevation == nil && nothing.maxGrade() == nil)184    }185186    @Test func degenerateLinesAndSampleCap() throws {187        let t = try planeTile()188        #expect(ElevationProfile(line: [], source: t).samples.isEmpty)189        #expect(ElevationProfile(line: [Coordinate(latitude: 45.5, longitude: -73.5)], source: t).samples.count == 1)190        let long = [Coordinate(latitude: 45.01, longitude: -73.99), Coordinate(latitude: 45.99, longitude: -73.01)]191        let capped = ElevationProfile(line: long, source: t, spacing: 1, maxSamples: 200)192        #expect(capped.samples.count <= 203)193    }194}195
Files main
Menu

Theme