SPB Git

Repository Public BSD-3-Clause

AdminIndex.swift 10.9 KB 246 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Maps9// File             : Infrastructure/geocoder-builder/Sources/GeocoderBuilder/AdminIndex.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 ORIXGeoCore9091/// One administrative boundary assembled from the member ways of its relation.92public struct AdminPolygon: Sendable {93    public var relationID: Int6494    public var name: String95    public var level: Int96    /// Closed rings (outer and inner together); a point is inside when it is inside an odd number of them.97    public var rings: [[Coordinate]]98    public var bbox: BoundingBox99100    public func contains(_ c: Coordinate) -> Bool {101        guard bbox.contains(c) else { return false }102        var inside = false103        for ring in rings where Geodesy.contains(ring: ring, point: c) { inside.toggle() }104        return inside105    }106}107108public enum RingAssembly {109    public struct Member: Sendable {110        public var nodes: [Int64]111        public var isInner: Bool112        public init(nodes: [Int64], isInner: Bool) { self.nodes = nodes; self.isInner = isInner }113    }114115    /// Stitches member ways into closed rings of node identifiers by matching end nodes.116    /// Returns nil when a chain cannot be closed (the boundary is cut by the edge of the extract): a partial polygon117    /// would assign points to the wrong side, so the caller drops the boundary.118    public static func assemble(_ members: [Member]) -> [[Int64]]? {119        var rings: [[Int64]] = []120        var open: [[Int64]] = []121        for m in members where m.nodes.count >= 2 {122            if m.nodes.first == m.nodes.last { if m.nodes.count >= 4 { rings.append(m.nodes) } } else { open.append(m.nodes) }123        }124        var byEnd: [Int64: [Int]] = [:]125        for (i, w) in open.enumerated() { byEnd[w.first!, default: []].append(i); byEnd[w.last!, default: []].append(i) }126        var used = [Bool](repeating: false, count: open.count)127        for start in open.indices where !used[start] {128            used[start] = true129            var ring = open[start]130            while ring.first != ring.last {131                guard let next = byEnd[ring.last!]?.first(where: { !used[$0] }) else { return nil }132                used[next] = true133                let w = open[next]134                if w.first == ring.last { ring.append(contentsOf: w.dropFirst()) } else { ring.append(contentsOf: w.reversed().dropFirst()) }135            }136            if ring.count >= 4 { rings.append(ring) }137        }138        return rings.isEmpty ? nil : rings139    }140}141142/// Point-in-polygon lookup over many administrative boundaries, accelerated by a grid: every cell lists the polygons that143/// cover it entirely (answer without geometry) and those whose boundary crosses it (exact ray-casting test).144public struct AdminIndex: Sendable {145    public let polygons: [AdminPolygon]146    private let cellSize: Double147    private let table: [Int64: Range<Int>]148    /// Polygon index, negative-encoded (`~index`) when the cell is only partly covered.149    private let entries: [Int32]150151    public init(polygons: [AdminPolygon], cellSize: Double = 0.01) {152        self.polygons = polygons153        self.cellSize = cellSize154        let perPolygon: [[(Int64, Int32)]] = parallelMap(polygons.count) { p in155            Self.rasterize(polygons[p], index: Int32(p), cellSize: cellSize)156        }157        var all: [(Int64, Int32)] = []158        all.reserveCapacity(perPolygon.reduce(0) { $0 + $1.count })159        for list in perPolygon { all.append(contentsOf: list) }160        all.sort { $0.0 != $1.0 ? $0.0 < $1.0 : $0.1 < $1.1 }161        var table: [Int64: Range<Int>] = [:]162        var entries: [Int32] = []163        entries.reserveCapacity(all.count)164        var i = 0165        while i < all.count {166            var j = i167            while j < all.count, all[j].0 == all[i].0 { entries.append(all[j].1); j += 1 }168            table[all[i].0] = i..<j169            i = j170        }171        self.table = table172        self.entries = entries173    }174175    private static func key(_ ix: Int, _ iy: Int) -> Int64 { Int64(iy) << 32 | Int64(ix) }176    private static func cell(_ v: Double, _ offset: Double, _ size: Double) -> Int { Int(((v + offset) / size).rounded(.down)) }177178    private static func rasterize(_ polygon: AdminPolygon, index: Int32, cellSize: Double) -> [(Int64, Int32)] {179        // 1. Cells crossed by the boundary: conservative, by subdividing every edge until its box spans at most 2×2 cells.180        var boundary = Set<Int64>()181        func mark(_ a: Coordinate, _ b: Coordinate, depth: Int) {182            let x0 = cell(min(a.longitude, b.longitude), 180, cellSize), x1 = cell(max(a.longitude, b.longitude), 180, cellSize)183            let y0 = cell(min(a.latitude, b.latitude), 90, cellSize), y1 = cell(max(a.latitude, b.latitude), 90, cellSize)184            if (x1 - x0 <= 1 && y1 - y0 <= 1) || depth > 40 {185                for y in y0...y1 { for x in x0...x1 { boundary.insert(key(x, y)) } }186            } else {187                let m = Coordinate(latitude: (a.latitude + b.latitude) / 2, longitude: (a.longitude + b.longitude) / 2)188                mark(a, m, depth: depth + 1); mark(m, b, depth: depth + 1)189            }190        }191        for ring in polygon.rings {192            for i in 0..<ring.count { mark(ring[i], ring[(i + 1) % ring.count], depth: 0) }193        }194        var out: [(Int64, Int32)] = boundary.map { ($0, ~index) }195        // 2. Interior cells: scan-line fill on the latitude of the cell centres.196        let y0 = cell(polygon.bbox.minLat, 90, cellSize), y1 = cell(polygon.bbox.maxLat, 90, cellSize)197        for y in y0...y1 {198            let lat = (Double(y) + 0.5) * cellSize - 90199            var crossings: [Double] = []200            for ring in polygon.rings {201                var j = ring.count - 1202                for i in 0..<ring.count {203                    let a = ring[i], b = ring[j]204                    if (a.latitude > lat) != (b.latitude > lat) {205                        crossings.append((b.longitude - a.longitude) * (lat - a.latitude) / (b.latitude - a.latitude) + a.longitude)206                    }207                    j = i208                }209            }210            crossings.sort()211            var k = 0212            while k + 1 < crossings.count {213                // Cells whose centre lies between the two crossings.214                let first = Int(((crossings[k] + 180) / cellSize - 0.5).rounded(.up)), last = Int(((crossings[k + 1] + 180) / cellSize - 0.5).rounded(.down))215                if last >= first { for x in first...last where !boundary.contains(key(x, y)) { out.append((key(x, y), index)) } }216                k += 2217            }218        }219        return out220    }221222    /// Indexes of the polygons containing the coordinate.223    public func polygons(containing c: Coordinate) -> [Int] {224        guard let range = table[Self.key(Self.cell(c.longitude, 180, cellSize), Self.cell(c.latitude, 90, cellSize))] else { return [] }225        var out: [Int] = []226        for e in entries[range] {227            if e >= 0 { out.append(Int(e)) } else if polygons[Int(~e)].contains(c) { out.append(Int(~e)) }228        }229        return out230    }231232    /// The municipality (admin level 8) and the borough or district (level 9, else 10) containing the coordinate.233    public func locality(of c: Coordinate) -> (city: Int?, district: Int?) {234        var city: Int?, nine: Int?, ten: Int?235        for p in polygons(containing: c) {236            switch polygons[p].level {237            case 8: city = city ?? p238            case 9: nine = nine ?? p239            case 10: ten = ten ?? p240            default: break241            }242        }243        return (city, nine ?? ten)244    }245}246
Files main
Menu

Theme