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/GeocoderBuilder/GeocoderBuild.swift10// Module : GeocoderBuilder11// 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 ORIXOSM91import ORIXSearch9293/// Turns OpenStreetMap elements into one ORIX search index.94///95/// Feed it in three steps, in this order: every relation (`addRelation`), every way (`addWay`) then `finishWays()`,96/// every node (`addNode`); then call `write`. `GeocoderBuild.run` does this from a PBF file with three passes of the reader.97/// Not thread-safe.98public final class GeocoderBuild {99 public static let builderVersion = "orix-geocoder-build 1.0.0"100101 public struct Configuration: Sendable {102 public var regionID: String103 /// Keep only what lies inside this box (features by their position, streets by the middle of each way).104 public var boundingBox: BoundingBox?105 public var pageSize: Int106 public var source: String?107 public init(regionID: String, boundingBox: BoundingBox? = nil, pageSize: Int = 4096, source: String? = nil) {108 self.regionID = regionID; self.boundingBox = boundingBox; self.pageSize = pageSize; self.source = source109 }110 }111112 public struct Statistics: Sendable, Codable {113 public var adminRelations = 0114 public var adminPolygons = 0115 public var adminIncomplete = 0116 public var streetWays = 0117 public var streetEntries = 0118 public var addressOnlyStreets = 0119 public var addressObjects = 0120 public var addressesWithoutStreet = 0121 public var interpolationWays = 0122 public var interpolationRanges = 0123 public var interpolationSkippedAlphabetic = 0124 public var interpolationSkippedInvalid = 0125 public var interpolationSkippedNoStreet = 0126 public var neededNodes = 0127 public var missingNodes = 0128 public var localityFromPolygon = 0129 public var localityApproximate = 0130 public var localityUnknown = 0131 }132133 public struct Member: Sendable {134 public var type: OSMRelation.MemberType135 public var ref: Int64136 public var role: String137 public init(type: OSMRelation.MemberType, ref: Int64, role: String) { self.type = type; self.ref = ref; self.role = role }138 }139140 private struct AdminRelation { var id: Int64; var name: String; var level: Int; var members: [(way: Int64, inner: Bool)] }141 private struct AreaRelation { var id: Int64; var info: FeatureInfo; var ways: [Int64] }142 private struct StreetWay { var id: Int64; var key: String; var names: NameSet; var ref: String?; var cls: StreetClass; var nodes: [Int64] }143 private struct InterpolationWay { var id: Int64; var kind: String; var street: String?; var nodes: [Int64] }144 private struct FeatureWay { var id: Int64; var info: FeatureInfo; var nodes: [Int64] }145 private struct FeatureNode { var id: Int64; var coordinate: Coordinate; var info: FeatureInfo }146 private struct GroupKey: Hashable { var name: String; var area: Int32 }147 /// Locality of a point: polygon indexes, or the index of the nearest settlement (approximation), or -1.148 private struct Locality: Sendable { var city: Int32 = -1; var district: Int32 = -1; var nearest: Int32 = -1149 var areaCode: Int32 { city >= 0 ? city : (nearest >= 0 ? -(nearest + 2) : -1) }150 }151152 private let configuration: Configuration153 public private(set) var statistics = Statistics()154155 private var adminRelations: [AdminRelation] = []156 private var areaRelations: [AreaRelation] = []157 private var wantedWays = Set<Int64>()158 private var wayNodes: [Int64: [Int64]] = [:]159 private var streetWays: [StreetWay] = []160 private var interpolationWays: [InterpolationWay] = []161 private var featureWays: [FeatureWay] = []162 private var featureNodes: [FeatureNode] = []163 private var neededNodes: [Int64] = []164 private var interpolationNodeIDs = Set<Int64>()165 private var interpolationNodes: [Int64: (number: String, street: String?)] = [:]166 private var store = NodeStore(wanted: [])167168 public init(configuration: Configuration) {169 self.configuration = configuration170 }171172 // MARK: Pass 1 — relations173174 public func addRelation(id: Int64, tags: [OSMTag], members: [Member]) {175 let type = tags["type"]176 if tags["boundary"] == "administrative", type == "boundary" || type == "multipolygon",177 let level = tags["admin_level"].flatMap({ Int($0) }), (8...10).contains(level),178 let name = (tags["name"] ?? tags["name:fr"])?.trimmingCharacters(in: .whitespaces), !name.isEmpty {179 let ways = members.filter { $0.type == .way && $0.role != "admin_centre" && $0.role != "label" }.map { (way: $0.ref, inner: $0.role == "inner") }180 if !ways.isEmpty {181 adminRelations.append(AdminRelation(id: id, name: name, level: level, members: ways))182 for w in ways { wantedWays.insert(w.way) }183 statistics.adminRelations += 1184 }185 return186 }187 guard type == "multipolygon" || type == "boundary", let info = FeatureExtraction.feature(tags), info.isIndexedFeature else { return }188 let outer = members.filter { $0.type == .way && $0.role != "inner" }.map(\.ref)189 guard !outer.isEmpty, outer.count <= 5_000 else { return }190 areaRelations.append(AreaRelation(id: id, info: info, ways: outer))191 for w in outer { wantedWays.insert(w) }192 }193194 // MARK: Pass 2 — ways195196 public func addWay(id: Int64, nodeRefs: [Int64], tags: [OSMTag]) {197 guard nodeRefs.count >= 2 else { return }198 var needed = false199 if wantedWays.contains(id) { wayNodes[id] = nodeRefs; needed = true }200 if !tags.isEmpty {201 if let kind = tags["addr:interpolation"] {202 interpolationWays.append(InterpolationWay(id: id, kind: kind, street: tags["addr:street"]?.trimmingCharacters(in: .whitespaces).nonEmptyValue, nodes: nodeRefs))203 for n in nodeRefs { interpolationNodeIDs.insert(n) }204 statistics.interpolationWays += 1205 needed = true206 } else if let highway = tags["highway"], let cls = StreetClass(osmValue: highway), tags["area"] != "yes" {207 let (names, _) = FeatureExtraction.names(tags)208 let ref = tags["ref"]?.trimmingCharacters(in: .whitespaces).nonEmptyValue209 if let name = names.primary {210 streetWays.append(StreetWay(id: id, key: TextNormalizer.canonicalKey(name), names: names, ref: ref, cls: cls, nodes: nodeRefs))211 needed = true212 } else if let ref, cls.isRoad, ref.utf8.count <= 24 {213 streetWays.append(StreetWay(id: id, key: "\u{1}ref:" + ref, names: NameSet(primary: nil), ref: ref, cls: cls, nodes: nodeRefs))214 needed = true215 }216 } else if let info = FeatureExtraction.feature(tags), info.isIndexedFeature || info.isAddress {217 featureWays.append(FeatureWay(id: id, info: info, nodes: nodeRefs))218 needed = true219 } else if tags["addr:housenumber"] != nil {220 statistics.addressesWithoutStreet += 1221 }222 }223 if needed { neededNodes.append(contentsOf: nodeRefs) }224 }225226 /// Call after the last way: prepares the table of node coordinates to collect.227 public func finishWays() {228 store = NodeStore(wanted: neededNodes)229 neededNodes = []230 statistics.neededNodes = store.count231 statistics.streetWays = streetWays.count232 }233234 // MARK: Pass 3 — nodes235236 public func addNode(id: Int64, latitude: Double, longitude: Double, tags: [OSMTag]) {237 store.offer(id: id, latitude: latitude, longitude: longitude)238 guard !tags.isEmpty, let info = FeatureExtraction.feature(tags) else { return }239 if let number = info.houseNumber, interpolationNodeIDs.contains(id) { interpolationNodes[id] = (number, info.street) }240 guard info.isIndexedFeature || info.isAddress else {241 if info.houseNumber != nil, !interpolationNodeIDs.contains(id) { statistics.addressesWithoutStreet += 1 }242 return243 }244 let c = Coordinate(latitude: latitude, longitude: longitude)245 guard c.isValid, configuration.boundingBox?.contains(c) ?? true else { return }246 featureNodes.append(FeatureNode(id: id, coordinate: c, info: info))247 }248249 // MARK: Assembly250251 private func inBox(_ c: Coordinate) -> Bool { configuration.boundingBox?.contains(c) ?? true }252253 /// Assembles everything and writes the index.254 public func write(to url: URL, dataTimestamp: Date?, log: (String) -> Void = { _ in }) throws -> SearchIndexSummary {255 let store = self.store256 statistics.missingNodes = store.count - store.filled257 let writer = try SearchIndexWriter(url: url, regionID: configuration.regionID,258 options: .init(pageSize: configuration.pageSize, builderVersion: Self.builderVersion, source: configuration.source))259260 // 1. Administrative polygons.261 var polygons: [AdminPolygon] = []262 for r in adminRelations {263 var members: [RingAssembly.Member] = []264 var complete = true265 for m in r.members {266 guard let nodes = wayNodes[m.way] else { complete = false; break }267 members.append(.init(nodes: nodes, isInner: m.inner))268 }269 guard complete, let rings = RingAssembly.assemble(members) else { statistics.adminIncomplete += 1; continue }270 var coordinateRings: [[Coordinate]] = []271 for ring in rings {272 let coords = store.coordinates(ring)273 guard coords.count == ring.count else { complete = false; break }274 coordinateRings.append(Array(coords.dropLast()))275 }276 guard complete, let box = BoundingBox(enclosing: coordinateRings.joined()) else { statistics.adminIncomplete += 1; continue }277 polygons.append(AdminPolygon(relationID: r.id, name: r.name, level: r.level, rings: coordinateRings, bbox: box))278 }279 statistics.adminPolygons = polygons.count280 let admin = AdminIndex(polygons: polygons)281 log("admin polygons \(polygons.count) (incomplete \(statistics.adminIncomplete))")282283 // 2. Settlements, for the approximate fallback when no polygon contains a point.284 let settlements: [(coordinate: Coordinate, name: String, weight: Double)] = featureNodes.compactMap { n in285 guard let type = n.info.place, type.isSettlement, let name = n.info.names.primary else { return nil }286 let weight: Double = switch type { case .city: 4; case .town: 2.5; case .village: 1.5; default: 1 }287 return (n.coordinate, name, weight)288 }289 let settlementCell = 0.25290 var settlementGrid: [Int64: [Int32]] = [:]291 func gridKey(_ c: Coordinate) -> (Int, Int) { (Int(((c.longitude + 180) / settlementCell).rounded(.down)), Int(((c.latitude + 90) / settlementCell).rounded(.down))) }292 for (i, s) in settlements.enumerated() { let k = gridKey(s.coordinate); settlementGrid[Int64(k.1) << 32 | Int64(k.0), default: []].append(Int32(i)) }293 let grid = settlementGrid294 let settlementPoints = settlements.map(\.coordinate), settlementWeights = settlements.map(\.weight)295 let locate: @Sendable (Coordinate) -> Locality = { c in296 let l = admin.locality(of: c)297 var out = Locality(city: l.city.map(Int32.init) ?? -1, district: l.district.map(Int32.init) ?? -1, nearest: -1)298 if out.city < 0 {299 let kx = Int(((c.longitude + 180) / settlementCell).rounded(.down)), ky = Int(((c.latitude + 90) / settlementCell).rounded(.down))300 var best = Double.infinity301 for dy in -1...1 { for dx in -1...1 {302 for i in grid[Int64(ky + dy) << 32 | Int64(kx + dx)] ?? [] {303 let d = Geodesy.fastDistance(c, settlementPoints[Int(i)])304 // Within 25 km; a town counts as nearer than a hamlet at the same distance.305 if d <= 25_000, d / settlementWeights[Int(i)] < best { best = d / settlementWeights[Int(i)]; out.nearest = i }306 }307 } }308 }309 return out310 }311 var polygonAreas: [Int32: AreaID] = [:], settlementAreas: [Int32: AreaID] = [:]312 func context(_ l: Locality, taggedCity: String? = nil) -> LocalityContext {313 var ctx = LocalityContext()314 if l.district >= 0 {315 ctx.district = polygonAreas[l.district] ?? writer.addArea(name: polygons[Int(l.district)].name, level: .admin(polygons[Int(l.district)].level))316 polygonAreas[l.district] = ctx.district317 }318 if let taggedCity { ctx.city = writer.addArea(name: taggedCity, level: .tagged); return ctx }319 if l.city >= 0 {320 ctx.city = polygonAreas[l.city] ?? writer.addArea(name: polygons[Int(l.city)].name, level: .admin(8))321 polygonAreas[l.city] = ctx.city322 statistics.localityFromPolygon += 1323 } else if l.nearest >= 0 {324 ctx.city = settlementAreas[l.nearest] ?? writer.addArea(name: settlements[Int(l.nearest)].name, level: .nearestPlace)325 settlementAreas[l.nearest] = ctx.city326 ctx.cityIsApproximate = true327 statistics.localityApproximate += 1328 } else {329 statistics.localityUnknown += 1330 }331 return ctx332 }333334 // 3. Places and points of interest; addresses go to their street.335 var addressBuckets: [GroupKey: [AddressRecord]] = [:]336 func emit(osm: OSMElementRef, coordinate: Coordinate, box: BoundingBox?, info: FeatureInfo, locality: Locality) {337 if let type = info.place {338 writer.add(PlaceRecord(osm: osm, coordinate: coordinate, boundingBox: box, names: info.names, type: type, population: info.population,339 hasWikidata: info.hasWikidata, locality: context(locality)))340 } else if let category = info.category {341 writer.add(POIRecord(osm: osm, coordinate: coordinate, boundingBox: box, names: info.names, category: category,342 houseNumber: info.street != nil ? info.houseNumber : nil, street: info.street, hasWikidata: info.hasWikidata,343 hasBrand: info.hasBrand, locality: context(locality, taggedCity: info.addrCity)))344 }345 if let number = info.houseNumber, let street = info.street {346 addressBuckets[GroupKey(name: TextNormalizer.canonicalKey(street), area: locality.areaCode), default: []]347 .append(AddressRecord(osm: osm, houseNumber: number, coordinate: coordinate))348 addressStreetNames[TextNormalizer.canonicalKey(street)] = addressStreetNames[TextNormalizer.canonicalKey(street)] ?? street349 statistics.addressObjects += 1350 }351 }352 let nodes = featureNodes353 let nodeLocalities = parallelMap(nodes.count) { locate(nodes[$0].coordinate) }354 for (i, n) in nodes.enumerated() { emit(osm: .init(type: .node, id: n.id), coordinate: n.coordinate, box: nil, info: n.info, locality: nodeLocalities[i]) }355 featureNodes = []356 log("feature nodes \(nodes.count)")357358 let ways = featureWays359 let wayShapes: [(Coordinate, BoundingBox, Locality)?] = parallelMap(ways.count) { i in360 let points = store.coordinates(ways[i].nodes)361 guard let c = FeatureExtraction.representativePoint(points), let box = BoundingBox(enclosing: points) else { return nil }362 return (c, box, locate(c))363 }364 for (i, w) in ways.enumerated() {365 guard let (c, box, l) = wayShapes[i], inBox(c) else { continue }366 let large = Geodesy.fastDistance(Coordinate(latitude: box.minLat, longitude: box.minLon), Coordinate(latitude: box.maxLat, longitude: box.maxLon)) > 150367 emit(osm: .init(type: .way, id: w.id), coordinate: c, box: large ? box : nil, info: w.info, locality: l)368 }369 featureWays = []370 log("feature ways \(ways.count)")371372 for r in areaRelations {373 var box: BoundingBox?374 for w in r.ways {375 for c in store.coordinates(wayNodes[w] ?? []) { if box == nil { box = BoundingBox(minLat: c.latitude, minLon: c.longitude, maxLat: c.latitude, maxLon: c.longitude) } else { box!.extend(c) } }376 }377 guard let box, inBox(box.center) else { continue }378 emit(osm: .init(type: .relation, id: r.id), coordinate: box.center, box: box, info: r.info, locality: locate(box.center))379 }380 log("area relations \(areaRelations.count)")381 areaRelations = []382383 // 4. Interpolation ways (OSM `addr:interpolation`): numeric ranges between consecutive numbered nodes.384 var interpolationBuckets: [GroupKey: [InterpolationRecord]] = [:]385 var debug: [String: Int] = [:]386 var endpointAdded = Set<Int64>()387 for way in interpolationWays {388 let step: Int389 switch way.kind {390 case "all": step = 1391 case "even", "odd": step = 2392 case "alphabetic": statistics.interpolationSkippedAlphabetic += 1; continue393 default:394 guard let n = Int(way.kind), n >= 1, n <= 100 else { statistics.interpolationSkippedInvalid += 1; continue }395 step = n396 }397 let numbered = way.nodes.indices.filter { interpolationNodes[way.nodes[$0]] != nil }398 guard numbered.count >= 2 else { statistics.interpolationSkippedInvalid += 1; debug["fewer than two numbered nodes", default: 0] += 1; continue }399 for k in 0..<(numbered.count - 1) {400 let i = numbered[k], j = numbered[k + 1]401 let a = interpolationNodes[way.nodes[i]]!, b = interpolationNodes[way.nodes[j]]!402 guard let start = Int(a.number), let end = Int(b.number) else { statistics.interpolationSkippedInvalid += 1; debug["non-integer end number", default: 0] += 1; continue }403 if start == end {404 // Not a range: both ends carry the same number. The numbered nodes are still real addresses of the way's street.405 statistics.interpolationSkippedInvalid += 1; debug["equal end numbers", default: 0] += 1406 if let street = way.street, a.street == nil, let c = store.coordinate(way.nodes[i]), inBox(c), endpointAdded.insert(way.nodes[i]).inserted {407 let key = GroupKey(name: TextNormalizer.canonicalKey(street), area: locate(c).areaCode)408 addressStreetNames[key.name] = addressStreetNames[key.name] ?? street409 addressBuckets[key, default: []].append(AddressRecord(osm: .init(type: .node, id: way.nodes[i]), houseNumber: a.number, coordinate: c))410 statistics.addressObjects += 1411 }412 continue413 }414 guard start >= 0, end >= 0, abs(end - start) % step == 0, abs(end - start) <= 20_000 else { statistics.interpolationSkippedInvalid += 1; debug["span not a multiple of the step", default: 0] += 1; continue }415 if (way.kind == "even" && start % 2 != 0) || (way.kind == "odd" && start % 2 != 1) { statistics.interpolationSkippedInvalid += 1; debug["parity contradicts even/odd", default: 0] += 1; continue }416 guard let street = way.street ?? a.street ?? b.street else { statistics.interpolationSkippedNoStreet += 1; continue }417 let line = store.coordinates(Array(way.nodes[i...j]))418 guard line.count == j - i + 1, line.count >= 2 else { statistics.interpolationSkippedInvalid += 1; continue }419 let middle = Geodesy.interpolate(line[0], line[line.count - 1], t: 0.5)420 guard inBox(middle) else { continue }421 let key = GroupKey(name: TextNormalizer.canonicalKey(street), area: locate(middle).areaCode)422 addressStreetNames[key.name] = addressStreetNames[key.name] ?? street423 interpolationBuckets[key, default: []].append(InterpolationRecord(wayID: way.id, start: start, end: end, step: step, line: line))424 statistics.interpolationRanges += 1425 // The two numbered nodes are real addresses; when they carry no addr:street of their own, the way's applies.426 for (index, node) in [(i, a), (j, b)] where node.street == nil && endpointAdded.insert(way.nodes[index]).inserted {427 let c = index == i ? line[0] : line[line.count - 1]428 addressBuckets[key, default: []].append(AddressRecord(osm: .init(type: .node, id: way.nodes[index]), houseNumber: node.number, coordinate: c))429 statistics.addressObjects += 1430 }431 }432 }433 interpolationWays = []434 log("interpolation ranges \(statistics.interpolationRanges); skipped: \(debug.sorted { $0.key < $1.key }.map { "\($0.key) \($0.value)" }.joined(separator: ", "))")435436 // 5. Streets: the ways of one name in one locality, split into connected groups.437 let streetWays = self.streetWays438 self.streetWays = []439 let geometry: [([Coordinate], Locality)?] = parallelMap(streetWays.count) { i in440 let points = store.coordinates(streetWays[i].nodes)441 guard points.count >= 2 else { return nil }442 return (points, locate(points[points.count / 2]))443 }444 var groups: [GroupKey: [Int]] = [:]445 for i in streetWays.indices {446 guard let (points, l) = geometry[i], inBox(points[points.count / 2]) else { continue }447 groups[GroupKey(name: streetWays[i].key, area: l.areaCode), default: []].append(i)448 }449 log("street ways \(streetWays.count), groups \(groups.count)")450451 // addr:street values written without the street type join the only street of that core name in the locality.452 var coreIndex: [GroupKey: [String]] = [:]453 for key in groups.keys where !key.name.hasPrefix("\u{1}") {454 let display = streetWays[groups[key]![0]].names.primary ?? ""455 coreIndex[GroupKey(name: TextNormalizer.streetCoreKey(display), area: key.area), default: []].append(key.name)456 }457 func targetKey(_ key: GroupKey) -> GroupKey {458 if groups[key] != nil { return key }459 let display = addressStreetNames[key.name] ?? key.name460 if let options = coreIndex[GroupKey(name: TextNormalizer.streetCoreKey(display), area: key.area)], options.count == 1 {461 return GroupKey(name: options[0], area: key.area)462 }463 return key464 }465 var addressesByStreet: [GroupKey: [AddressRecord]] = [:]466 for (key, list) in addressBuckets { addressesByStreet[targetKey(key), default: []].append(contentsOf: list) }467 addressBuckets = [:]468 var rangesByStreet: [GroupKey: [InterpolationRecord]] = [:]469 for (key, list) in interpolationBuckets { rangesByStreet[targetKey(key), default: []].append(contentsOf: list) }470 interpolationBuckets = [:]471472 func localityContext(areaCode: Int32, sample: Coordinate) -> LocalityContext {473 var l = Locality()474 if areaCode >= 0 { l.city = areaCode } else if areaCode <= -2 { l.nearest = -(areaCode + 2) }475 return context(l)476 }477 let coarse = 0.01478 func coarseKey(_ c: Coordinate) -> (Int, Int) { (Int(((c.longitude + 180) / coarse).rounded(.down)), Int(((c.latitude + 90) / coarse).rounded(.down))) }479 func pack(_ x: Int, _ y: Int) -> Int64 { Int64(y) << 32 | Int64(x) }480481 for (key, members) in groups {482 var indexes = members483 if indexes.contains(where: { streetWays[$0].cls.isRoad }) { indexes.removeAll { !streetWays[$0].cls.isRoad } }484 // Connected groups: ways whose nodes fall in the same or neighbouring 0.01° cells belong together.485 var parent = Array(0..<indexes.count)486 func find(_ x: Int) -> Int { var r = x; while parent[r] != r { r = parent[r] }; var y = x; while parent[y] != r { let n = parent[y]; parent[y] = r; y = n }; return r }487 var owner: [Int64: Int] = [:]488 if indexes.count > 1 {489 for (local, wi) in indexes.enumerated() {490 var previous: Int64 = .min491 for c in geometry[wi]!.0 {492 let (x, y) = coarseKey(c)493 let k = pack(x, y)494 if k == previous { continue }495 previous = k496 for dy in -1...1 { for dx in -1...1 {497 if let o = owner[pack(x + dx, y + dy)] { let a = find(local), b = find(o); if a != b { parent[a] = b } }498 } }499 if owner[k] == nil { owner[k] = local }500 }501 }502 }503 var components: [Int: [Int]] = [:]504 for (local, wi) in indexes.enumerated() { components[find(local), default: []].append(wi) }505 let ordered = components.values.sorted { $0.count != $1.count ? $0.count > $1.count : $0[0] < $1[0] }506507 // Addresses and interpolation ranges go to the nearest connected group.508 var componentAddresses = [[AddressRecord]](repeating: [], count: ordered.count)509 var componentRanges = [[InterpolationRecord]](repeating: [], count: ordered.count)510 let addresses = addressesByStreet.removeValue(forKey: key) ?? [], ranges = rangesByStreet.removeValue(forKey: key) ?? []511 if ordered.count == 1 {512 componentAddresses[0] = addresses; componentRanges[0] = ranges513 } else if !addresses.isEmpty || !ranges.isEmpty {514 var cellComponent: [Int64: Int] = [:]515 var centres: [Coordinate] = []516 for (ci, ways) in ordered.enumerated() {517 var sumLat = 0.0, sumLon = 0.0, n = 0.0518 for wi in ways { for c in geometry[wi]!.0 { let (x, y) = coarseKey(c); cellComponent[pack(x, y)] = cellComponent[pack(x, y)] ?? ci; sumLat += c.latitude; sumLon += c.longitude; n += 1 } }519 centres.append(Coordinate(latitude: sumLat / n, longitude: sumLon / n))520 }521 func component(for c: Coordinate) -> Int {522 let (x, y) = coarseKey(c)523 for ring in 0...2 { for dy in -ring...ring { for dx in -ring...ring where max(abs(dx), abs(dy)) == ring {524 if let ci = cellComponent[pack(x + dx, y + dy)] { return ci }525 } } }526 return centres.indices.min { Geodesy.fastDistance(c, centres[$0]) < Geodesy.fastDistance(c, centres[$1]) } ?? 0527 }528 for a in addresses { componentAddresses[component(for: a.coordinate)].append(a) }529 for r in ranges { componentRanges[component(for: r.line[0])].append(r) }530 }531532 for (ci, ways) in ordered.enumerated() {533 let lines = ways.map { geometry[$0]!.0 }534 let middles = lines.map { $0[$0.count / 2] }535 let mean = Coordinate(latitude: middles.reduce(0) { $0 + $1.latitude } / Double(middles.count), longitude: middles.reduce(0) { $0 + $1.longitude } / Double(middles.count))536 let representative = middles.indices.min { Geodesy.fastDistance(mean, middles[$0]) < Geodesy.fastDistance(mean, middles[$1]) } ?? 0537 var variants: [String] = []538 var refs: [String: Int] = [:]539 var cls = streetWays[ways[0]].cls540 for wi in ways {541 let w = streetWays[wi]542 if variants.count < 8 { for v in w.names.variants where !variants.contains(v) { variants.append(v) } }543 if let r = w.ref { refs[r, default: 0] += 1 }544 if w.cls.code < cls.code { cls = w.cls }545 }546 let ref = refs.max { $0.value != $1.value ? $0.value < $1.value : $0.key > $1.key }?.key547 writer.add(StreetRecord(osm: .init(type: .way, id: streetWays[ways[representative]].id),548 names: NameSet(primary: streetWays[ways[0]].names.primary, variants: variants), ref: ref, streetClass: cls,549 geometry: lines, coordinate: middles[representative],550 locality: localityContext(areaCode: key.area, sample: middles[representative]),551 addresses: componentAddresses[ci], interpolations: componentRanges[ci]))552 statistics.streetEntries += 1553 }554 }555 // Streets known only from addr:street tags (no way of that name in the locality): a street entry without geometry.556 var leftovers = Set(addressesByStreet.keys)557 leftovers.formUnion(rangesByStreet.keys)558 for key in leftovers {559 let addresses = addressesByStreet[key] ?? [], ranges = rangesByStreet[key] ?? []560 guard let name = addressStreetNames[key.name] else { continue }561 let points = addresses.map(\.coordinate) + ranges.map { $0.line[0] }562 guard !points.isEmpty else { continue }563 let sortedLat = points.map(\.latitude).sorted(), sortedLon = points.map(\.longitude).sorted()564 let median = Coordinate(latitude: sortedLat[sortedLat.count / 2], longitude: sortedLon[sortedLon.count / 2])565 let nearest = points.min { Geodesy.fastDistance(median, $0) < Geodesy.fastDistance(median, $1) } ?? median566 let osm = addresses.first?.osm ?? OSMElementRef(type: .way, id: ranges[0].wayID)567 writer.add(StreetRecord(osm: osm, names: NameSet(primary: name), streetClass: .residential, geometry: [], coordinate: nearest,568 locality: localityContext(areaCode: key.area, sample: nearest), addresses: addresses, interpolations: ranges))569 statistics.streetEntries += 1570 statistics.addressOnlyStreets += 1571 }572 log("street entries \(statistics.streetEntries) (address-only \(statistics.addressOnlyStreets))")573574 let summary = try writer.finish(boundingBox: configuration.boundingBox ?? headerBox, dataTimestamp: dataTimestamp)575 return summary576 }577578 /// Display form of each `addr:street` key (first spelling met).579 private var addressStreetNames: [String: String] = [:]580 /// Bounding box announced by the extract, used for the index metadata when no box is configured.581 public var headerBox: BoundingBox?582583 // MARK: PBF driver584585 public struct Outcome: Sendable {586 public var summary: SearchIndexSummary587 public var statistics: Statistics588 public var dataTimestamp: Date?589 public var seconds: Double590 }591592 /// Builds an index from a PBF extract: three passes of the reader (relations, ways, nodes), then assembly.593 public static func run(pbf: URL, output: URL, configuration: Configuration, log: (String) -> Void = { _ in }) throws -> Outcome {594 let started = Date()595 func elapsed() -> String { String(format: "%6.1f s", Date().timeIntervalSince(started)) }596 let reader = try OSMPBFReader(url: pbf)597 let header = try reader.header()598 var configuration = configuration599 if configuration.source == nil { configuration.source = pbf.lastPathComponent }600 let build = GeocoderBuild(configuration: configuration)601 if let b = header.bbox {602 let box = BoundingBox(minLat: b.minLat, minLon: b.minLon, maxLat: b.maxLat, maxLon: b.maxLon)603 if box.isValid, box.latSpan > 0 { build.headerBox = box }604 }605 try reader.read(.relations) { block in606 for r in block.relations { build.addRelation(id: r.id, tags: r.tags, members: r.members.map { Member(type: $0.type, ref: $0.ref, role: $0.role) }) }607 }608 log("\(elapsed()) relations read")609 try reader.read(.ways) { block in610 for w in block.ways { build.addWay(id: w.id, nodeRefs: w.nodeRefs, tags: w.tags) }611 }612 build.finishWays()613 log("\(elapsed()) ways read, \(build.statistics.neededNodes) node coordinates to collect")614 try reader.read(.nodes) { block in615 for n in block.nodes { build.addNode(id: n.id, latitude: n.latitude, longitude: n.longitude, tags: n.tags) }616 }617 log("\(elapsed()) nodes read")618 let timestamp = header.replicationTimestamp.flatMap { $0 > 0 ? Date(timeIntervalSince1970: TimeInterval($0)) : nil }619 let summary = try build.write(to: output, dataTimestamp: timestamp) { log("\(elapsed()) \($0)") }620 log("\(elapsed()) index written")621 return Outcome(summary: summary, statistics: build.statistics, dataTimestamp: timestamp, seconds: Date().timeIntervalSince(started))622 }623}624