Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Immo-Ka iOS9// File : ImmoKa/Core/Map/Clusterer.swift10// Description : regroupement des points de carte par grille selon le zoom11// — pur, testable, hors du fil principal.12// Module : ImmoKa13// Repository : https://git.spboucher.ai/immo-ka-ios-v314// Project Website : https://www.immo-ka.com15// Created : 2026-11-2516// Last Modified : 2026-11-2817//18// =============================================================================19// AUTHOR & PROFESSIONAL AFFILIATION20// =============================================================================21//22// Author : Simon-Pierre Boucher23// Position : Professor of Finance24// Institution : Université du Québec en Outaouais (UQO)25// Department : Département des sciences administratives26// Organization : SP Boucher27//28// Website : https://spboucher.ai29// Git : https://git.spboucher.ai30//31// =============================================================================32// OFFICIAL CONTACT DIRECTORY33// =============================================================================34//35// General : info@spboucher.ai36// Professional : contact@spboucher.ai37// Direct : simon@spboucher.ai38// Research : research@spboucher.ai39// Development : dev@spboucher.ai40// Support : support@spboucher.ai41// Security/Admin : admin@spboucher.ai42// Notifications : notifications@spboucher.ai43//44// Preferred Contact: support@spboucher.ai45//46// =============================================================================47// COPYRIGHT & INTELLECTUAL PROPERTY48// =============================================================================49//50// Copyright (c) 202651// Simon-Pierre Boucher52//53// All rights reserved where applicable.54//55// This file is governed by the applicable project license,56// copyright notices, institutional agreements and relevant law.57//58// Unless expressly authorized by the applicable license or59// rights holder, copying, redistribution, sublicensing,60// publication and commercial exploitation are not permitted.61//62// Existing third-party rights and notices remain unaffected.63//64// =============================================================================65// CONFIDENTIALITY & SECURITY66// =============================================================================67//68// Classification : Public69// Distribution : Public repository; use is governed by the project license70// Security Contact : admin@spboucher.ai71//72// Access to this source does not independently grant permission73// to redistribute or disclose confidential materials.74//75// Do not embed credentials, private keys, access tokens,76// certificates or confidential personal information.77//78// =============================================================================79// LICENSE & MAINTENANCE80// =============================================================================81//82// License : None specified (no license file in this repository)83// Maintainer : Simon-Pierre Boucher84// Technical Contact: dev@spboucher.ai85//86// =============================================================================87// END OF SP BOUCHER SOURCE HEADER88// =============================================================================8990import CoreLocation91import Foundation9293/// Élément affiché sur la carte : un logement isolé ou un regroupement.94struct MapItem: Sendable, Hashable, Identifiable {95 enum Kind: Sendable, Hashable {96 case single(uid: String, price: Double?, verdict: Verdict?)97 case cluster(count: Int, good: Int, minPrice: Double?)98 }99 var id: String100 var lat: Double101 var lng: Double102 var kind: Kind103104 var coordinate: CLLocationCoordinate2D { .init(latitude: lat, longitude: lng) }105 var count: Int {106 if case .cluster(let c, _, _) = kind { return c }107 return 1108 }109}110111/// Zone visible de la carte (degrés).112struct MapBounds: Sendable, Hashable {113 var west: Double114 var south: Double115 var east: Double116 var north: Double117118 /// Paramètre `bbox` de l'API : ouest,sud,est,nord.119 var bbox: String { String(format: "%.5f,%.5f,%.5f,%.5f", west, south, east, north) }120121 func contains(lat: Double, lng: Double) -> Bool { lat >= south && lat <= north && lng >= west && lng <= east }122123 func padded(_ f: Double) -> MapBounds {124 let dx = (east - west) * f, dy = (north - south) * f125 return MapBounds(west: west - dx, south: south - dy, east: east + dx, north: north + dy)126 }127}128129enum Clusterer {130 /// Regroupe les points visibles en au plus `columns × rows` cellules ; sous `singleThreshold`131 /// points visibles (ou cellule à un seul point), les logements restent individuels.132 ///133 /// - Parameters:134 /// - points: tous les points correspondant aux filtres.135 /// - bounds: zone visible.136 /// - columns: nombre de cellules en largeur (la hauteur suit le rapport de la zone).137 /// - maxItems: borne dure du nombre d'éléments renvoyés.138 /// - pinned: logement sélectionné, toujours affiché seul (sa porte reste visible, jamais absorbée par un regroupement).139 static func cluster(_ points: [MapPoint], in bounds: MapBounds, columns: Int = 7,140 aspect: Double = 1.6, singleThreshold: Int = 70, maxItems: Int = 160, pinned: String? = nil) -> [MapItem] {141 if let pinned, let p = points.first(where: { $0.uid == pinned }) {142 let rest = cluster(points.filter { $0.uid != pinned }, in: bounds, columns: columns, aspect: aspect,143 singleThreshold: singleThreshold, maxItems: maxItems - 1)144 return rest + [MapItem(id: p.uid, lat: p.lat, lng: p.lng, kind: .single(uid: p.uid, price: p.price, verdict: p.verdict))]145 }146 let area = bounds.padded(0.12)147 let w = max(area.east - area.west, 1e-9)148 let h = max(area.north - area.south, 1e-9)149 let visible = points.filter { area.contains(lat: $0.lat, lng: $0.lng) }150 guard !visible.isEmpty else { return [] }151152 if visible.count <= singleThreshold {153 return mergeCoincident(visible)154 }155156 let cols = max(2, columns)157 let rows = max(2, Int((Double(cols) * aspect).rounded()))158 // la grille est ancrée sur des multiples de la taille de cellule : les regroupements159 // ne « sautent » pas quand la carte glisse160 let cw = w / Double(cols), ch = h / Double(rows)161162 struct Acc { var n = 0; var good = 0; var sumLat = 0.0; var sumLng = 0.0; var minPrice: Double?; var first: MapPoint? }163 var cells: [Int64: Acc] = [:]164 cells.reserveCapacity(cols * rows * 2)165 for p in visible {166 let cx = Int64((p.lng / cw).rounded(.down)), cy = Int64((p.lat / ch).rounded(.down))167 let key = cx &* 1_000_003 &+ cy168 var a = cells[key] ?? Acc()169 a.n += 1170 if p.verdict == .sous { a.good += 1 }171 a.sumLat += p.lat; a.sumLng += p.lng172 if Listing.priceIsPlausible(p.price), let pr = p.price { a.minPrice = min(a.minPrice ?? pr, pr) }173 if a.first == nil { a.first = p }174 cells[key] = a175 }176177 // fusion des cellules voisines dont les centres sont trop proches : les disques ne se178 // chevauchent pas à l'écran (les plus gros absorbent leurs voisins)179 var accs = cells.values.sorted { $0.n > $1.n }180 var merged: [Acc] = []181 merged.reserveCapacity(accs.count)182 let minDist = 0.82 // en unités de cellule183 while !accs.isEmpty {184 var a = accs.removeFirst()185 var again = true186 while again {187 again = false188 let cLat = a.sumLat / Double(a.n), cLng = a.sumLng / Double(a.n)189 var rest: [Acc] = []190 rest.reserveCapacity(accs.count)191 for b in accs {192 let dx = (b.sumLng / Double(b.n) - cLng) / cw, dy = (b.sumLat / Double(b.n) - cLat) / ch193 if dx * dx + dy * dy < minDist * minDist {194 a.n += b.n; a.good += b.good; a.sumLat += b.sumLat; a.sumLng += b.sumLng195 if let m = b.minPrice { a.minPrice = min(a.minPrice ?? m, m) }196 again = true197 } else {198 rest.append(b)199 }200 }201 accs = rest202 }203 merged.append(a)204 }205206 var out: [MapItem] = []207 out.reserveCapacity(merged.count)208 for a in merged {209 let lat = a.sumLat / Double(a.n), lng = a.sumLng / Double(a.n)210 if a.n == 1, let p = a.first {211 out.append(MapItem(id: p.uid, lat: p.lat, lng: p.lng, kind: .single(uid: p.uid, price: p.price, verdict: p.verdict)))212 } else {213 // identifiant stable : cellule du centre + effectif214 let key = "\(Int64((lng / cw).rounded(.down)))_\(Int64((lat / ch).rounded(.down)))"215 out.append(MapItem(id: "c\(key)-\(a.n)", lat: lat, lng: lng,216 kind: .cluster(count: a.n, good: a.good, minPrice: a.minPrice)))217 }218 }219 if out.count > maxItems {220 out.sort { $0.count > $1.count }221 out = Array(out.prefix(maxItems))222 }223 return out224 }225226 /// Plusieurs logements à la même adresse (même immeuble) : un seul marqueur regroupé.227 private static func mergeCoincident(_ pts: [MapPoint]) -> [MapItem] {228 var groups: [String: [MapPoint]] = [:]229 var order: [String] = []230 for p in pts {231 let k = String(format: "%.4f,%.4f", p.lat, p.lng)232 if groups[k] == nil { order.append(k) }233 groups[k, default: []].append(p)234 }235 return order.compactMap { k in236 guard let g = groups[k], let f = g.first else { return nil }237 if g.count == 1 {238 return MapItem(id: f.uid, lat: f.lat, lng: f.lng, kind: .single(uid: f.uid, price: f.price, verdict: f.verdict))239 }240 let prices = g.compactMap { Listing.priceIsPlausible($0.price) ? $0.price : nil }241 return MapItem(id: "b\(k)-\(g.count)", lat: f.lat, lng: f.lng,242 kind: .cluster(count: g.count, good: g.filter { $0.verdict == .sous }.count, minPrice: prices.min()))243 }244 }245246 /// Regroupements du serveur (v3) ramenés à ce que l'écran peut porter : même grille ancrée que `cluster`,247 /// effectifs additionnés, centre pondéré, prix minimal gardé. Aucune inscription n'est perdue ni inventée.248 static func merge(_ clusters: [ServerCluster], in bounds: MapBounds, columns: Int = 7, aspect: Double = 1.6,249 maxItems: Int = 160) -> [MapItem] {250 let area = bounds.padded(0.12)251 let w = max(area.east - area.west, 1e-9), h = max(area.north - area.south, 1e-9)252 let visible = clusters.filter { $0.count > 0 && area.contains(lat: $0.lat, lng: $0.lng) }253 guard !visible.isEmpty else { return [] }254 let cols = max(2, columns), rows = max(2, Int((Double(cols) * aspect).rounded()))255 let cw = w / Double(cols), ch = h / Double(rows)256 struct Acc { var n = 0; var sumLat = 0.0; var sumLng = 0.0; var minPrice: Double? }257 var cells: [Int64: Acc] = [:]258 for c in visible {259 let key = Int64((c.lng / cw).rounded(.down)) &* 1_000_003 &+ Int64((c.lat / ch).rounded(.down))260 var a = cells[key] ?? Acc()261 a.n += c.count262 a.sumLat += c.lat * Double(c.count); a.sumLng += c.lng * Double(c.count)263 if let p = c.minPrice, Listing.priceIsPlausible(p) { a.minPrice = min(a.minPrice ?? p, p) }264 cells[key] = a265 }266 var out: [MapItem] = cells.map { key, a in267 let lat = a.sumLat / Double(a.n), lng = a.sumLng / Double(a.n)268 return MapItem(id: "s\(key)-\(a.n)", lat: lat, lng: lng, kind: .cluster(count: a.n, good: 0, minPrice: a.minPrice))269 }270 out.sort { $0.count > $1.count }271 return Array(out.prefix(maxItems))272 }273274 /// Zone à cadrer pour une réponse de carte v3 (points ou regroupements pondérés par leur effectif).275 static func robustBounds(points: [MapPoint], clusters: [ServerCluster]) -> MapBounds? {276 if !points.isEmpty { return robustBounds(points) }277 let total = clusters.reduce(0) { $0 + $1.count }278 guard total > 0 else { return nil }279 // on écarte les regroupements périphériques qui pèsent ensemble moins de 2 % des inscriptions280 func cut(_ values: [(Double, Int)]) -> (Double, Double) {281 let sorted = values.sorted { $0.0 < $1.0 }282 let limit = Double(total) * 0.02283 var acc = 0.0, lo = sorted.first!.0, hi = sorted.last!.0284 for (v, n) in sorted { acc += Double(n); if acc > limit { lo = v; break } }285 acc = 0286 for (v, n) in sorted.reversed() { acc += Double(n); if acc > limit { hi = v; break } }287 return (lo, max(hi, lo))288 }289 let (w, e) = cut(clusters.map { ($0.lng, $0.count) })290 let (so, n) = cut(clusters.map { ($0.lat, $0.count) })291 return MapBounds(west: w, south: so, east: e, north: n)292 }293294 /// Zone englobante robuste : ignore les 2 % de points extrêmes (coordonnées erronées).295 static func robustBounds(_ points: [MapPoint]) -> MapBounds? {296 guard !points.isEmpty else { return nil }297 let lngs = points.map(\.lng).sorted(), lats = points.map(\.lat).sorted()298 let cut = points.count > 40 ? points.count * 2 / 100 : 0299 return MapBounds(west: lngs[cut], south: lats[cut], east: lngs[lngs.count - 1 - cut], north: lats[lats.count - 1 - cut])300 }301}302