Repository Public BSD-3-Clause
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Maps9// File : Infrastructure/geocoder-builder/Sources/orix-geocoder-bench/main.swift10// Module : orix-geocoder-bench11// 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 ORIXSearch9192// orix-geocoder-bench --index <search.sqlite> [--index <other.sqlite>] <command>93// query <text> [--focus lat,lon] [--suggest] [--limit N] print the results of one query94// reverse <lat,lon> [--max metres] reverse-geocode one coordinate95// sanity the fixed list of sanity queries of the README96// bench [--rounds N] latency of the fixed query list (p50 / p95)97func fail(_ message: String) -> Never {98 FileHandle.standardError.write(Data((message + "\n").utf8))99 exit(2)100}101102func parseCoordinate(_ text: String) -> Coordinate? {103 let v = text.split(separator: ",").compactMap { Double($0) }104 guard v.count == 2 else { return nil }105 let c = Coordinate(latitude: v[0], longitude: v[1])106 return c.isValid ? c : nil107}108109func describe(_ r: SearchResult) -> String {110 var tags: [String] = [r.kind.rawValue]111 if let c = r.category { tags.append(c.rawValue) }112 if let p = r.placeType { tags.append(p.rawValue) }113 if let s = r.streetClass { tags.append(s.rawValue) }114 if let m = r.addressMatch { tags.append("address:" + m.rawValue) }115 if r.isTypoCorrected { tags.append("typo-corrected") }116 if r.cityIsApproximate { tags.append("city≈") }117 if let ref = r.roadRef { tags.append("ref " + ref) }118 let distance = r.distance.map { String(format: " %.0f m", $0) } ?? ""119 let osm = r.osm.map { " \(["n", "w", "r"][$0.type.rawValue])\($0.id)" } ?? ""120 let name = r.name.isEmpty ? "(unnamed)" : r.name121 return String(format: "%.3f %@ — %@ [%@]%@ %.5f,%.5f%@", r.score, name, r.secondaryLine, tags.joined(separator: ", "), distance,122 r.coordinate.latitude, r.coordinate.longitude, osm)123}124125func percentile(_ sorted: [Double], _ p: Double) -> Double {126 guard !sorted.isEmpty else { return 0 }127 let rank = Int((p * Double(sorted.count)).rounded(.up)) - 1128 return sorted[min(sorted.count - 1, max(0, rank))]129}130131let montreal = Coordinate(latitude: 45.5088, longitude: -73.5878)132let quebec = Coordinate(latitude: 46.8131, longitude: -71.2075)133134struct BenchQuery {135 var text: String136 var focus: Coordinate?137}138139// Submitted queries: names, addresses with and without a house number, categories near a point, typos.140let fullQueries: [BenchQuery] = [141 .init(text: "Stade olympique", focus: montreal), .init(text: "Château Frontenac", focus: quebec), .init(text: "Montréal", focus: nil),142 .init(text: "Sherbrooke", focus: montreal), .init(text: "Université Laval", focus: quebec), .init(text: "aéroport", focus: montreal),143 .init(text: "1000 rue Sherbrooke Ouest", focus: montreal), .init(text: "1234 Sherbrooke O, Montréal", focus: nil),144 .init(text: "845 rue Sherbrooke Ouest Montréal", focus: nil), .init(text: "1 rue des Carrières, Québec", focus: nil),145 .init(text: "2325 rue de l'Université", focus: quebec), .init(text: "99999 rue Sherbrooke Ouest", focus: montreal),146 .init(text: "rue Saint-Denis", focus: montreal), .init(text: "boul René-Lévesque", focus: quebec), .init(text: "chemin Sainte-Foy", focus: quebec),147 .init(text: "av du Parc", focus: montreal), .init(text: "A-40", focus: montreal), .init(text: "Autoroute 20", focus: quebec),148 .init(text: "route 132", focus: nil), .init(text: "café", focus: montreal), .init(text: "pharmacie", focus: quebec),149 .init(text: "essence", focus: montreal), .init(text: "dépanneur", focus: quebec), .init(text: "borne de recharge", focus: montreal),150 .init(text: "restaurant", focus: quebec), .init(text: "toilettes", focus: montreal), .init(text: "épicerie Laval", focus: nil),151 .init(text: "SAQ", focus: montreal), .init(text: "Tim Hortons", focus: quebec), .init(text: "Jean Coutu Trois-Rivières", focus: nil),152 .init(text: "sherbroke", focus: montreal), .init(text: "montreel", focus: nil), .init(text: "chateau frontenax", focus: quebec),153 .init(text: "rue saint deniz", focus: montreal), .init(text: "parc lafontaine", focus: montreal), .init(text: "Mont-Tremblant", focus: nil),154 .init(text: "lac saint-jean", focus: nil), .init(text: "Gare du Palais", focus: quebec), .init(text: "hôpital", focus: quebec),155 .init(text: "45.5017, -73.5673", focus: nil), .init(text: "Rimouski", focus: nil), .init(text: "rue principale", focus: quebec),156 .init(text: "3 brasseurs", focus: montreal), .init(text: "métro Berri-UQAM", focus: montreal),157]158159// Type-ahead: short prefixes and partially typed queries.160let suggestQueries: [BenchQuery] = [161 "mo", "mon", "sh", "she", "ru", "rue", "st", "sai", "ca", "caf", "ph", "pha", "bo", "bou", "ch", "che", "la", "lac", "pa", "par",162 "qu", "que", "ti", "tim", "mc", "mcd", "12", "123", "a-4", "1000 r", "1000 rue sh", "1000 rue sherbrooke o", "rue sa", "rue saint-d",163 "stade ol", "château fr", "univ", "université la", "pharmacie j", "tr", "tro", "trois-r", "sherb", "gati", "ess", "dép", "av du p", "boul rené",164].enumerated().map { BenchQuery(text: $0.element, focus: $0.offset % 3 == 0 ? quebec : montreal) }165166let reversePoints: [Coordinate] = [167 Coordinate(latitude: 45.5017, longitude: -73.5673), Coordinate(latitude: 45.5088, longitude: -73.5878), Coordinate(latitude: 46.8131, longitude: -71.2075),168 Coordinate(latitude: 46.8119, longitude: -71.2052), Coordinate(latitude: 45.4042, longitude: -71.8929), Coordinate(latitude: 48.4284, longitude: -71.0685),169 Coordinate(latitude: 46.3432, longitude: -72.5477), Coordinate(latitude: 45.4765, longitude: -75.7013), Coordinate(latitude: 48.4490, longitude: -68.5230),170 Coordinate(latitude: 45.5576, longitude: -73.5516), Coordinate(latitude: 52.0000, longitude: -72.0000), Coordinate(latitude: 46.1185, longitude: -74.5962),171]172173var arguments = Array(CommandLine.arguments.dropFirst())174var indexPaths: [String] = []175while arguments.first == "--index" {176 arguments.removeFirst()177 guard !arguments.isEmpty else { fail("--index needs a path") }178 indexPaths.append(arguments.removeFirst())179}180guard !arguments.isEmpty else { fail("usage: orix-geocoder-bench --index <search.sqlite> [--index …] query <text> [--focus lat,lon] [--suggest] [--limit N] | reverse <lat,lon> [--max m] | sanity | bench [--rounds N]") }181let command = arguments.removeFirst()182@MainActor func option(_ name: String) -> String? {183 guard let i = arguments.firstIndex(of: name), i + 1 < arguments.count else { return nil }184 let v = arguments[i + 1]185 arguments.removeSubrange(i...(i + 1))186 return v187}188@MainActor func flag(_ name: String) -> Bool {189 guard let i = arguments.firstIndex(of: name) else { return false }190 arguments.remove(at: i)191 return true192}193194let engine = SearchEngine()195do {196 try SQLiteCapabilities.verify()197 for path in indexPaths {198 let info = try await engine.openIndex(at: URL(fileURLWithPath: path))199 let date = info.dataDate.map { ISO8601DateFormatter().string(from: $0) } ?? "unknown"200 print("index \(info.regionID): schema \(info.schemaMajor).\(info.schemaMinor), data \(date), places \(info.placeCount), pois \(info.poiCount), streets \(info.streetCount), addresses \(info.addressCount), interpolation ranges \(info.interpolationCount)")201 }202203 func runQuery(_ text: String, focus: Coordinate?, suggest: Bool, limit: Int) async throws {204 let start = DispatchTime.now().uptimeNanoseconds205 let response = try await engine.search(SearchQuery(text: text, mode: suggest ? .suggest : .full, focus: focus, limit: limit))206 let ms = Double(DispatchTime.now().uptimeNanoseconds - start) / 1e6207 var notes: [String] = []208 if let c = response.matchedCategory { notes.append("category \(c.rawValue)") }209 for c in response.corrections { notes.append("corrected \(c.original) → \(c.replacements.joined(separator: "|"))") }210 if let n = response.parsed.houseNumber { notes.append("house number \(n)") }211 if !response.parsed.cityTokens.isEmpty { notes.append("locality \(response.parsed.cityTokens.joined(separator: " "))") }212 let focusText = focus.map { String(format: " near %.4f,%.4f", $0.latitude, $0.longitude) } ?? ""213 print("\n\"\(text)\"\(focusText)\(suggest ? " (suggest)" : "") \(String(format: "%.1f ms", ms)) \(notes.joined(separator: "; "))")214 for r in response.results { print(" " + describe(r)) }215 if response.results.isEmpty { print(" (no result)") }216 }217218 func runReverse(_ c: Coordinate, max: Double) async throws {219 let start = DispatchTime.now().uptimeNanoseconds220 let outcome = try await engine.reverseGeocode(c, maxDistance: max)221 let ms = Double(DispatchTime.now().uptimeNanoseconds - start) / 1e6222 print("\nreverse \(c.latitude),\(c.longitude) within \(Int(max)) m \(String(format: "%.1f ms", ms))")223 switch outcome {224 case .nothingWithin(let m): print(" nothing within \(Int(m)) m")225 case .found(let r):226 for (label, m) in [("address", r.address), ("street", r.street), ("place", r.place)] {227 if let m { print(" \(label): " + describe(m.result)) } else { print(" \(label): none within \(Int(r.maxDistance)) m") }228 }229 }230 }231232 switch command {233 case "query":234 let focus = option("--focus").flatMap(parseCoordinate)235 let limit = option("--limit").flatMap { Int($0) } ?? 8236 let suggest = flag("--suggest")237 guard let text = arguments.first else { fail("query needs a text") }238 try await runQuery(text, focus: focus, suggest: suggest, limit: limit)239 case "reverse":240 let max = option("--max").flatMap { Double($0) } ?? 150241 guard let c = arguments.first.flatMap(parseCoordinate) else { fail("reverse needs lat,lon") }242 try await runReverse(c, max: max)243 case "sanity":244 try await runQuery("1000 rue Sherbrooke Ouest", focus: montreal, suggest: false, limit: 5)245 try await runQuery("99999 rue Sherbrooke Ouest", focus: montreal, suggest: false, limit: 3)246 try await runQuery("1234 Sherbrooke O, Montréal", focus: nil, suggest: false, limit: 3)247 try await runQuery("Stade olympique", focus: nil, suggest: false, limit: 5)248 try await runQuery("Château Frontenac", focus: nil, suggest: false, limit: 5)249 try await runQuery("café", focus: montreal, suggest: false, limit: 6)250 try await runQuery("pharmacie", focus: quebec, suggest: false, limit: 6)251 try await runQuery("essence", focus: quebec, suggest: false, limit: 4)252 try await runQuery("SAQ", focus: montreal, suggest: false, limit: 4)253 try await runQuery("A-40", focus: montreal, suggest: false, limit: 5)254 try await runQuery("sherbroke", focus: montreal, suggest: false, limit: 5)255 try await runQuery("montreel", focus: nil, suggest: false, limit: 3)256 try await runQuery("45.5017, -73.5673", focus: nil, suggest: false, limit: 3)257 try await runQuery("mon", focus: montreal, suggest: true, limit: 6)258 try await runQuery("rue saint-d", focus: quebec, suggest: true, limit: 6)259 try await runReverse(Coordinate(latitude: 45.5017, longitude: -73.5673), max: 150)260 try await runReverse(Coordinate(latitude: 46.8119, longitude: -71.2052), max: 150)261 try await runReverse(Coordinate(latitude: 52.0, longitude: -72.0), max: 150)262 case "bench":263 let rounds = option("--rounds").flatMap { Int($0) } ?? 5264 func measure(_ label: String, _ count: Int, _ body: (Int) async throws -> Void) async throws {265 var first: [Double] = [], warm: [Double] = []266 var worst: (Double, Int) = (0, 0)267 for round in 0...rounds {268 for i in 0..<count {269 let start = DispatchTime.now().uptimeNanoseconds270 try await body(i)271 let ms = Double(DispatchTime.now().uptimeNanoseconds - start) / 1e6272 if round == 0 { first.append(ms) } else { warm.append(ms); if ms > worst.0 { worst = (ms, i) } }273 }274 }275 first.sort(); warm.sort()276 print(String(format: "%@: %d queries × %d rounds — warm p50 %.2f ms, p95 %.2f ms, max %.2f ms (query #%d); first pass p50 %.2f ms, p95 %.2f ms, max %.2f ms",277 label, count, rounds, percentile(warm, 0.5), percentile(warm, 0.95), warm.last ?? 0, worst.1, percentile(first, 0.5), percentile(first, 0.95), first.last ?? 0))278 }279 try await measure("full search", fullQueries.count) { i in280 _ = try await engine.search(SearchQuery(text: fullQueries[i].text, mode: .full, focus: fullQueries[i].focus, limit: 20))281 }282 try await measure("suggestions", suggestQueries.count) { i in283 _ = try await engine.suggest(suggestQueries[i].text, focus: suggestQueries[i].focus, limit: 8)284 }285 try await measure("reverse geocoding", reversePoints.count) { i in286 _ = try await engine.reverseGeocode(reversePoints[i], maxDistance: 150)287 }288 if flag("--details") {289 print("\nper query (one warm run):")290 for q in fullQueries {291 let start = DispatchTime.now().uptimeNanoseconds292 let r = try await engine.search(SearchQuery(text: q.text, mode: .full, focus: q.focus, limit: 20))293 print(String(format: " full %7.2f ms %3d results %@", Double(DispatchTime.now().uptimeNanoseconds - start) / 1e6, r.results.count, q.text))294 }295 for q in suggestQueries {296 let start = DispatchTime.now().uptimeNanoseconds297 let r = try await engine.suggest(q.text, focus: q.focus, limit: 8)298 print(String(format: " suggest %7.2f ms %3d results %@", Double(DispatchTime.now().uptimeNanoseconds - start) / 1e6, r.results.count, q.text))299 }300 }301 default:302 fail("unknown command \(command)")303 }304} catch {305 FileHandle.standardError.write(Data("error: \(error)\n".utf8))306 exit(1)307}308