Repository Public BSD-3-Clause
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Maps9// File : Packages/ORIXAtlas/Tests/ORIXAtlasTests/Support.swift10// Module : ORIXAtlasTests11// 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 CoreGraphics89import Foundation90import ImageIO91import ORIXAtlas92import ORIXGeoCore93import ORIXMapStyle94import ORIXTileStore95import UniformTypeIdentifiers9697enum TestData {98 static let packageRoot = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()99 static let repositoryRoot = packageRoot.deletingLastPathComponent().deletingLastPathComponent()100 static let worldURL = repositoryRoot.appendingPathComponent("Apps/ORIXMaps/Resources/BaseMap/world-base.pmtiles")101 static let montrealURL = repositoryRoot.appendingPathComponent("data/build/montreal.pmtiles")102 static let artifacts = packageRoot.appendingPathComponent("Artifacts")103104 static var hasMontreal: Bool { FileManager.default.fileExists(atPath: montrealURL.path) }105 static var benchmarksEnabled: Bool { ProcessInfo.processInfo.environment["ORIX_ATLAS_BENCH"] == "1" }106107 static func world() throws -> PMTilesArchive { try PMTilesArchive(url: worldURL) }108 static func montreal() throws -> PMTilesArchive { try PMTilesArchive(url: montrealURL) }109110 /// Fixed set of Montréal tiles for measurements: the tiles of each zoom 12...15 covering a box around downtown,111 /// Mount Royal and the river (45.47...45.56 N, 73.66...73.50 W), in row-major order.112 static func benchmarkTiles() -> [TileID] {113 let box = BoundingBox(minLat: 45.47, minLon: -73.66, maxLat: 45.56, maxLon: -73.50)114 var out: [TileID] = []115 for z in UInt8(12)...15 {116 let all = WebMercator.tiles(covering: box, zoom: z, limit: 100_000) ?? []117 // At most 64 tiles per zoom, evenly spaced, so that every zoom weighs the same.118 let step = max(1, all.count / 64)119 out += stride(from: 0, to: all.count, by: step).prefix(64).map { all[$0] }120 }121 return out122 }123124 @discardableResult125 static func writePNG(_ bitmap: AtlasBitmap, _ name: String) throws -> URL {126 try FileManager.default.createDirectory(at: artifacts, withIntermediateDirectories: true)127 let url = artifacts.appendingPathComponent(name)128 guard let image = bitmap.makeImage(), let dest = CGImageDestinationCreateWithURL(url as CFURL, UTType.png.identifier as CFString, 1, nil) else {129 throw CocoaError(.fileWriteUnknown)130 }131 CGImageDestinationAddImage(dest, image, nil)132 guard CGImageDestinationFinalize(dest) else { throw CocoaError(.fileWriteUnknown) }133 return url134 }135}136137func distance(_ c: (red: UInt8, green: UInt8, blue: UInt8), _ h: HexColor) -> Double {138 let dr = Double(c.red) - Double(h.red), dg = Double(c.green) - Double(h.green), db = Double(c.blue) - Double(h.blue)139 return (dr * dr + dg * dg + db * db).squareRoot()140}141142func percentile(_ values: [Double], _ p: Double) -> Double {143 guard !values.isEmpty else { return .nan }144 let sorted = values.sorted()145 let rank = Int((p / 100 * Double(sorted.count)).rounded(.up))146 return sorted[min(sorted.count - 1, max(0, rank - 1))]147}148149func milliseconds(_ body: () throws -> Void) rethrows -> Double {150 let start = ContinuousClock.now151 try body()152 let d = ContinuousClock.now - start153 return Double(d.components.seconds) * 1000 + Double(d.components.attoseconds) / 1e15154}155156/// Minimal Mapbox Vector Tile writer for synthetic test tiles (string attributes only).157enum MVT {158 struct Feature {159 var type: VectorTile.GeometryType160 /// Rings without their closing point, or lines.161 var parts: [[(Int32, Int32)]]162 var attributes: [(String, String)] = []163 }164165 static func varint(_ value: UInt64) -> [UInt8] {166 var v = value, out: [UInt8] = []167 repeat { var b = UInt8(v & 0x7f); v >>= 7; if v != 0 { b |= 0x80 }; out.append(b) } while v != 0168 return out169 }170 static func field(_ number: Int, varint v: UInt64) -> [UInt8] { varint(UInt64(number << 3)) + varint(v) }171 static func field(_ number: Int, bytes: [UInt8]) -> [UInt8] { varint(UInt64(number << 3 | 2)) + varint(UInt64(bytes.count)) + bytes }172 static func zigzag(_ v: Int32) -> UInt64 { UInt64(UInt32(bitPattern: (v << 1) ^ (v >> 31))) }173174 static func layer(_ name: String, extent: UInt32 = 4096, _ features: [Feature]) -> [UInt8] {175 var keys: [String] = [], values: [String] = []176 var body = field(15, varint: 2) + field(1, bytes: Array(name.utf8))177 for f in features {178 var tags: [UInt8] = []179 for (k, v) in f.attributes {180 if !keys.contains(k) { keys.append(k) }181 if !values.contains(v) { values.append(v) }182 tags += varint(UInt64(keys.firstIndex(of: k)!)) + varint(UInt64(values.firstIndex(of: v)!))183 }184 var geometry: [UInt8] = []185 var cx: Int32 = 0, cy: Int32 = 0186 for part in f.parts where !part.isEmpty {187 geometry += varint(UInt64(1 << 3 | 1)) + varint(zigzag(part[0].0 - cx)) + varint(zigzag(part[0].1 - cy))188 cx = part[0].0; cy = part[0].1189 if part.count > 1 {190 geometry += varint(UInt64((part.count - 1) << 3 | 2))191 for p in part.dropFirst() { geometry += varint(zigzag(p.0 - cx)) + varint(zigzag(p.1 - cy)); cx = p.0; cy = p.1 }192 }193 if f.type == .polygon { geometry += varint(15) }194 }195 body += field(2, bytes: field(2, bytes: tags) + field(3, varint: UInt64(f.type.rawValue)) + field(4, bytes: geometry))196 }197 for k in keys { body += field(3, bytes: Array(k.utf8)) }198 for v in values { body += field(4, bytes: field(1, bytes: Array(v.utf8))) }199 body += field(5, varint: UInt64(extent))200 return field(3, bytes: body)201 }202203 static func tile(_ layers: [[UInt8]]) throws -> VectorTile { try VectorTile(data: Data(layers.flatMap { $0 })) }204}205206/// Deterministic generator (SplitMix64) so that fuzz tests are reproducible.207struct SeededGenerator: RandomNumberGenerator {208 var state: UInt64209 init(seed: UInt64) { state = seed }210 mutating func next() -> UInt64 {211 state &+= 0x9E37_79B9_7F4A_7C15212 var z = state213 z = (z ^ (z >> 30)) &* 0xBF58_476D_1CE4_E5B9214 z = (z ^ (z >> 27)) &* 0x94D0_49BB_1331_11EB215 return z ^ (z >> 31)216 }217}218219/// Minimal PMTiles v3 writer for synthetic archives (no compression, root directory only).220enum SyntheticArchive {221 static func make(_ tiles: [(TileID, [UInt8])]) throws -> PMTilesArchive {222 let sorted = tiles.sorted { PMTilesArchive.tileID($0.0) < PMTilesArchive.tileID($1.0) }223 var directory = MVT.varint(UInt64(sorted.count))224 var last: UInt64 = 0225 for (id, _) in sorted { let v = PMTilesArchive.tileID(id); directory += MVT.varint(v - last); last = v }226 for _ in sorted { directory += MVT.varint(1) }227 for (_, bytes) in sorted { directory += MVT.varint(UInt64(bytes.count)) }228 var offset: UInt64 = 0229 for (_, bytes) in sorted { directory += MVT.varint(offset + 1); offset += UInt64(bytes.count) }230 let metadata = Array("{}".utf8)231 var header = [UInt8](repeating: 0, count: 127)232 header.replaceSubrange(0..<7, with: Array("PMTiles".utf8))233 header[7] = 3234 func put(_ v: UInt64, _ at: Int) { for i in 0..<8 { header[at + i] = UInt8(v >> UInt64(8 * i) & 0xff) } }235 func put32(_ v: Int32, _ at: Int) { let u = UInt32(bitPattern: v); for i in 0..<4 { header[at + i] = UInt8(u >> UInt32(8 * i) & 0xff) } }236 let rootOffset: UInt64 = 127, metaOffset = rootOffset + UInt64(directory.count), dataOffset = metaOffset + UInt64(metadata.count)237 put(rootOffset, 8); put(UInt64(directory.count), 16); put(metaOffset, 24); put(UInt64(metadata.count), 32)238 put(dataOffset, 40); put(0, 48); put(dataOffset, 56); put(offset, 64)239 put(UInt64(sorted.count), 72); put(UInt64(sorted.count), 80); put(UInt64(sorted.count), 88)240 header[96] = 1; header[97] = 1; header[98] = 1; header[99] = 1241 header[100] = sorted.map(\.0.z).min() ?? 0; header[101] = sorted.map(\.0.z).max() ?? 0242 put32(-1_800_000_000, 102); put32(-850_000_000, 106); put32(1_800_000_000, 110); put32(850_000_000, 114)243 return try PMTilesArchive(data: Data(header + directory + metadata + sorted.flatMap(\.1)))244 }245}246