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/FeatureExtraction.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/// What the builder keeps of the tags of one OSM element.94struct FeatureInfo: Sendable {95 var names: NameSet96 var place: PlaceType?97 var category: PlaceCategory?98 var houseNumber: String?99 var street: String?100 var addrCity: String?101 var population: Int?102 var hasWikidata: Bool103 var hasBrand: Bool104105 var isIndexedFeature: Bool { place != nil || category != nil }106 var isAddress: Bool { houseNumber != nil && street != nil }107}108109enum FeatureExtraction {110 private static let ignoredAmenities: Set<String> = [111 "bench", "waste_basket", "post_box", "parking_space", "parking_entrance", "loading_dock", "vending_machine", "telephone",112 "recycling", "hunting_stand", "lounger", "bicycle_repair_station", "public_bookcase", "waste_disposal", "bbq", "clock",113 "fountain", "grit_bin", "letter_box", "motorcycle_parking",114 ]115 private static let restrictedAccess: Set<String> = ["private", "no", "permit", "employees", "residents"]116117 static func split(_ value: String?) -> [String] {118 guard let value else { return [] }119 return value.split(separator: ";").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }120 }121122 /// Display name and searchable variants: name, name:fr, name:en, alt_name, old_name, short_name, official_name, loc_name, brand.123 static func names(_ tags: [OSMTag]) -> (names: NameSet, hasBrand: Bool) {124 var name: String?, fr: String?, en: String?, brand: String?125 var others: [String] = []126 for t in tags {127 switch t.key {128 case "name": name = t.value129 case "name:fr": fr = t.value130 case "name:en": en = t.value131 case "brand": brand = t.value132 case "alt_name", "old_name", "short_name", "official_name", "loc_name", "alt_name:fr", "alt_name:en", "official_name:fr", "official_name:en":133 others.append(contentsOf: split(t.value))134 default: break135 }136 }137 let primary = [name, fr, en, brand].compactMap { $0?.trimmingCharacters(in: .whitespaces) }.first { !$0.isEmpty }138 let variants = ([fr, en, brand].compactMap { $0 } + others).filter { $0.utf8.count <= 120 }139 return (NameSet(primary: primary.flatMap { $0.utf8.count <= 160 ? $0 : nil }, variants: Array(variants.prefix(8))), brand != nil)140 }141142 /// The place, point-of-interest and address content of an element; nil when it has none.143 static func feature(_ tags: [OSMTag]) -> FeatureInfo? {144 guard !tags.isEmpty else { return nil }145 var interesting = false146 for t in tags {147 switch t.key {148 case "name", "amenity", "shop", "tourism", "leisure", "place", "addr:housenumber", "highway", "railway", "aeroway", "natural",149 "historic", "healthcare", "public_transport", "waterway", "boundary", "office", "craft", "brand":150 interesting = true151 default: break152 }153 if interesting { break }154 }155 guard interesting else { return nil }156 let (nameSet, hasBrand) = names(tags)157 let named = nameSet.primary != nil158 var info = FeatureInfo(names: nameSet, place: nil, category: nil, houseNumber: nil, street: nil, addrCity: nil, population: nil,159 hasWikidata: tags["wikidata"] != nil, hasBrand: hasBrand)160 if named, let p = tags["place"], let type = PlaceType(osmValue: p) {161 info.place = type162 info.population = tags["population"].flatMap { Int($0.filter(\.isNumber)) }163 }164 if info.place == nil {165 var category = PlaceCategory.classify(tag: { tags[$0] })166 if category == nil, named {167 // A named feature of a kind outside the taxonomy is still something people search for.168 let amenity = tags["amenity"]169 if (amenity != nil && !ignoredAmenities.contains(amenity!)) || tags["office"] != nil || tags["craft"] != nil || tags["tourism"] != nil170 || tags["leisure"] != nil || tags["man_made"] != nil || tags["club"] != nil171 || (tags["building"] != nil && tags["building"] != "no") || tags["landuse"] != nil {172 category = .other173 }174 }175 if let c = category {176 let access = tags["access"]177 let restricted = access.map { restrictedAccess.contains($0) } ?? false178 if c == .parking, restricted { category = nil }179 else if !named, restricted { category = nil }180 else if !named, !c.isUsefulWithoutName { category = nil }181 else if tags["disused"] == "yes" || tags["abandoned"] == "yes" { category = nil }182 }183 info.category = category184 }185 if let hn = tags["addr:housenumber"]?.trimmingCharacters(in: .whitespaces), !hn.isEmpty, hn.utf8.count <= 40 {186 info.houseNumber = hn187 }188 info.street = tags["addr:street"]?.trimmingCharacters(in: .whitespaces).nonEmptyValue189 info.addrCity = tags["addr:city"]?.trimmingCharacters(in: .whitespaces).nonEmptyValue190 return (info.isIndexedFeature || info.houseNumber != nil) ? info : nil191 }192193 /// Centroid of a closed way (area-weighted), or the middle of its bounding box for degenerate shapes.194 static func representativePoint(_ points: [Coordinate]) -> Coordinate? {195 guard let box = BoundingBox(enclosing: points) else { return nil }196 guard points.count >= 4, points.first == points.last else { return points.count == 1 ? points[0] : box.center }197 var area = 0.0, cx = 0.0, cy = 0.0198 let ox = points[0].longitude, oy = points[0].latitude199 for i in 0..<(points.count - 1) {200 let x0 = points[i].longitude - ox, y0 = points[i].latitude - oy, x1 = points[i + 1].longitude - ox, y1 = points[i + 1].latitude - oy201 let cross = x0 * y1 - x1 * y0202 area += cross; cx += (x0 + x1) * cross; cy += (y0 + y1) * cross203 }204 guard abs(area) > 1e-14 else { return box.center }205 let c = Coordinate(latitude: oy + cy / (3 * area), longitude: ox + cx / (3 * area))206 return box.contains(c) ? c : box.center207 }208}209210extension String {211 var nonEmptyValue: String? { isEmpty ? nil : self }212}213