Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Valo-Plex iOS9// File : ValoPlex/Core/Appariement.swift10// Description : rattache chaque plex à l'empreinte réelle de son bâtiment11// (couche « building » du fond de carte), pour que ce soient12// les vrais bâtiments qui prennent la couleur de la valeur.13// Même règle que le site (src/lib/cartegl.ts, fonction14// apparier). Calcul pur, sans carte : vérifiable par des15// tests.16// Module : ValoPlex17// Repository : https://git.spboucher.ai/valo-plex-ios18// Project Website : https://www.valo-plex.com19// Created : 2026-12-0120// Last Modified : 2026-12-0121//22// =============================================================================23// AUTHOR & PROFESSIONAL AFFILIATION24// =============================================================================25//26// Author : Simon-Pierre Boucher27// Position : Professor of Finance28// Institution : Université du Québec en Outaouais (UQO)29// Department : Département des sciences administratives30// Organization : SP Boucher31//32// Website : https://spboucher.ai33// Git : https://git.spboucher.ai34//35// =============================================================================36// OFFICIAL CONTACT DIRECTORY37// =============================================================================38//39// General : info@spboucher.ai40// Professional : contact@spboucher.ai41// Direct : simon@spboucher.ai42// Research : research@spboucher.ai43// Development : dev@spboucher.ai44// Support : support@spboucher.ai45// Security/Admin : admin@spboucher.ai46// Notifications : notifications@spboucher.ai47//48// Preferred Contact: support@spboucher.ai49//50// =============================================================================51// COPYRIGHT & INTELLECTUAL PROPERTY52// =============================================================================53//54// Copyright (c) 202655// Simon-Pierre Boucher56//57// All rights reserved where applicable.58//59// This file is governed by the applicable project license,60// copyright notices, institutional agreements and relevant law.61//62// Unless expressly authorized by the applicable license or63// rights holder, copying, redistribution, sublicensing,64// publication and commercial exploitation are not permitted.65//66// Existing third-party rights and notices remain unaffected.67//68// =============================================================================69// CONFIDENTIALITY & SECURITY70// =============================================================================71//72// Classification : Public73// Distribution : Public repository; use is governed by the project license74// Security Contact : admin@spboucher.ai75//76// Access to this source does not independently grant permission77// to redistribute or disclose confidential materials.78//79// Do not embed credentials, private keys, access tokens,80// certificates or confidential personal information.81//82// =============================================================================83// LICENSE & MAINTENANCE84// =============================================================================85//86// License : None specified (no license file in this repository)87// Maintainer : Simon-Pierre Boucher88// Technical Contact: dev@spboucher.ai89//90// =============================================================================91// END OF SP BOUCHER SOURCE HEADER92// =============================================================================9394import CoreLocation95import Foundation9697/// Un immeuble à placer sur la carte.98struct PlexGeo: Hashable, Sendable {99 let cle: String100 let lat: Double101 let lng: Double102 /// Valeur par porte ; nulle si le service s'abstient.103 let pp: Double?104 let vendre: Bool105 let logements: Int106 /// 0 : plex du parc ; 1 : immeuble de la fiche ; 2 : vente comparable.107 var role = 0108}109110/// Empreinte d'un bâtiment du fond de carte : anneau extérieur puis anneaux intérieurs, en (longitude, latitude).111struct Bati: Sendable {112 let anneaux: [[CLLocationCoordinate2D]]113 let ouest: Double114 let sud: Double115 let est: Double116 let nord: Double117 /// Hauteur du fond de carte (render_height), quatre mètres au moins ; sept par défaut.118 let hauteur: Double119120 init?(anneaux: [[CLLocationCoordinate2D]], hauteurRendue: Double?) {121 guard let ext = anneaux.first, ext.count >= 4 else { return nil }122 self.anneaux = anneaux123 ouest = ext.map(\.longitude).min()!124 est = ext.map(\.longitude).max()!125 sud = ext.map(\.latitude).min()!126 nord = ext.map(\.latitude).max()!127 hauteur = max(4, (hauteurRendue ?? 0) > 0 ? hauteurRendue! : 7)128 }129130 /// Les tuiles voisines livrent deux fois le même bâtiment : cette clé les confond.131 var cle: String { String(format: "%.6f,%.6f,%.6f,%.6f,%d", ouest, sud, est, nord, anneaux[0].count) }132133 func contient(lat: Double, lng: Double) -> Bool {134 guard lng >= ouest, lng <= est, lat >= sud, lat <= nord else { return false }135 let a = anneaux[0]136 var dedans = false137 var j = a.count - 1138 for i in 0..<a.count {139 let xi = a[i].longitude, yi = a[i].latitude, xj = a[j].longitude, yj = a[j].latitude140 if (yi > lat) != (yj > lat), lng < (xj - xi) * (lat - yi) / (yj - yi) + xi { dedans.toggle() }141 j = i142 }143 return dedans144 }145146 /// Distance en mètres du point au sommet le plus proche de l'anneau extérieur.147 func distance(lat: Double, lng: Double) -> Double {148 let cosl = cos(lat * .pi / 180)149 var d = Double.infinity150 for s in anneaux[0] {151 d = min(d, hypot((s.longitude - lng) * 111_320 * cosl, (s.latitude - lat) * 111_320))152 }153 return d154 }155}156157/// Un bâtiment à dessiner : coloré s'il abrite des plex (`groupe` ≥ 0), en volume clair sinon.158struct BatiDessine: Sendable {159 let anneaux: [[CLLocationCoordinate2D]]160 /// Indice dans `Appariement.groupes`, ou −1 pour un bâtiment sans plex.161 let groupe: Int162 /// Médiane de la valeur par porte des plex abrités.163 let pp: Double?164 let vendre: Bool165 let hauteur: Double166 let role: Int167}168169struct Appariement: Sendable {170 let batis: [BatiDessine]171 /// Plex abrités par chaque bâtiment coloré.172 let groupes: [[PlexGeo]]173 /// Plex sans empreinte connue du fond de carte : ils reçoivent un petit volume de remplacement.174 let sansEmpreinte: Int175176 static let pas = 0.0006177 /// Le point du rôle est parfois dans la cour ou sur le trottoir : bâtiment le plus proche, à 16 m au plus.178 static let portee = 16.0179180 static func mediane(_ v: [Double]) -> Double? {181 let t = v.sorted()182 return t.isEmpty ? nil : t[t.count / 2]183 }184185 /// Hauteur d'un bâtiment coloré : celle du fond de carte, jamais moins que ce qu'exigent les logements du plus186 /// grand plex abrité (OpenStreetMap donne souvent cinq mètres par défaut à un triplex de trois étages).187 static func hauteur(fond: Double, logements: Int) -> Double {188 max(fond, 3.2 * Double(min(4, max(1, logements))) + 1)189 }190191 /// Rayon d'une pastille de la vue d'ensemble, en points : suit la racine du nombre d'immeubles de la case.192 static func rayonCase(n: Int, max: Int) -> Double { 5 + 19 * (Double(n) / Double(Swift.max(1, max))).squareRoot() }193194 static func carre(lat: Double, lng: Double, demi: Double) -> [CLLocationCoordinate2D] {195 let dy = demi / 111_320196 let dx = demi / (111_320 * cos(lat * .pi / 180))197 return [198 .init(latitude: lat - dy, longitude: lng - dx), .init(latitude: lat - dy, longitude: lng + dx),199 .init(latitude: lat + dy, longitude: lng + dx), .init(latitude: lat + dy, longitude: lng - dx),200 .init(latitude: lat - dy, longitude: lng - dx),201 ]202 }203204 private struct Cellule: Hashable {205 let x: Int206 let y: Int207 }208209 init(batiments brut: [Bati], plex: [PlexGeo]) {210 // sans doublons de tuile211 var vus = Set<String>()212 let B = brut.filter { vus.insert($0.cle).inserted }213 var grille: [Cellule: [Int]] = [:]214 for (k, b) in B.enumerated() {215 for gx in Int((b.ouest / Self.pas).rounded(.down))...Int((b.est / Self.pas).rounded(.down)) {216 for gy in Int((b.sud / Self.pas).rounded(.down))...Int((b.nord / Self.pas).rounded(.down)) {217 grille[Cellule(x: gx, y: gy), default: []].append(k)218 }219 }220 }221 var dans: [Int: [PlexGeo]] = [:]222 var ordre: [Int] = []223 var orphelins: [PlexGeo] = []224 for p in plex {225 let gx = Int((p.lng / Self.pas).rounded(.down)), gy = Int((p.lat / Self.pas).rounded(.down))226 var trouve = (grille[Cellule(x: gx, y: gy)] ?? []).first { B[$0].contient(lat: p.lat, lng: p.lng) } ?? -1227 if trouve < 0 {228 var mieux = Self.portee229 for dx in -1...1 {230 for dy in -1...1 {231 for k in grille[Cellule(x: gx + dx, y: gy + dy)] ?? [] {232 let d = B[k].distance(lat: p.lat, lng: p.lng)233 if d < mieux {234 mieux = d235 trouve = k236 }237 }238 }239 }240 }241 if trouve < 0 {242 orphelins.append(p)243 } else {244 if dans[trouve] == nil { ordre.append(trouve) }245 dans[trouve, default: []].append(p)246 }247 }248 var groupes: [[PlexGeo]] = []249 var sortie: [BatiDessine] = []250 // le rôle d'un bâtiment : celui de la fiche l'emporte sur une vente comparable, qui l'emporte sur le parc251 let roleDe = { (l: [PlexGeo]) in l.contains { $0.role == 1 } ? 1 : (l.contains { $0.role == 2 } ? 2 : 0) }252 for k in ordre {253 let l = dans[k]!, b = B[k]254 sortie.append(BatiDessine(anneaux: b.anneaux, groupe: groupes.count, pp: Self.mediane(l.compactMap(\.pp)), vendre: l.contains(where: \.vendre),255 hauteur: Self.hauteur(fond: b.hauteur, logements: l.map(\.logements).max() ?? 1), role: roleDe(l)))256 groupes.append(l)257 }258 // Les bâtiments sans plex passent par la même couche, en clair : deux extrusions superposées sur les mêmes259 // murs se disputeraient chaque pixel.260 for (k, b) in B.enumerated() where dans[k] == nil {261 sortie.append(BatiDessine(anneaux: b.anneaux, groupe: -1, pp: nil, vendre: false, hauteur: b.hauteur, role: 0))262 }263 for p in orphelins {264 sortie.append(BatiDessine(anneaux: [Self.carre(lat: p.lat, lng: p.lng, demi: 5)], groupe: groupes.count, pp: p.pp, vendre: p.vendre,265 hauteur: 3.2 * Double(min(4, max(1, p.logements))) + 1, role: p.role))266 groupes.append([p])267 }268 batis = sortie269 self.groupes = groupes270 sansEmpreinte = orphelins.count271 }272}273