Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Vrai-Prix iOS9// File : VraiPrix/Core/Map/Clusterer.swift10// Description : regroupement des points de carte par grille selon le zoom11// — pur, testable, hors du fil principal.12// Module : VraiPrix13// Repository : https://git.spboucher.ai/vrai-prix-ios-v314// Project Website : https://www.vrai-prix.com15// Created : 2026-11-2616// Last Modified : 2026-11-2617//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 point isolé ou un regroupement.94struct MapItem: Sendable, Hashable, Identifiable {95 enum Kind: Sendable, Hashable {96 case single(MapPoint)97 /// effectif et montant médian du regroupement98 case cluster(count: Int, median: Double?)99 }100 var id: String101 var lat: Double102 var lng: Double103 var kind: Kind104 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) }120 var width: Double { east - west }121 var height: Double { north - south }122123 func contains(lat: Double, lng: Double) -> Bool { lat >= south && lat <= north && lng >= west && lng <= east }124 func contains(_ other: MapBounds) -> Bool { other.west >= west && other.east <= east && other.south >= south && other.north <= north }125126 func padded(_ f: Double) -> MapBounds {127 let dx = width * f, dy = height * f128 return MapBounds(west: west - dx, south: south - dy, east: east + dx, north: north + dy)129 }130131 /// Même centre, côtés bornés (le service refuse plus de 0,5° de côté).132 func clamped(maxSide: Double) -> MapBounds {133 let cx = (west + east) / 2, cy = (south + north) / 2134 let w = min(width, maxSide) / 2, h = min(height, maxSide) / 2135 return MapBounds(west: cx - w, south: cy - h, east: cx + w, north: cy + h)136 }137}138139enum Clusterer {140 /// Regroupe les points visibles en cellules ; sous `singleThreshold` points visibles, ils restent individuels.141 /// Le point épinglé (sélection) est toujours affiché seul.142 static func cluster(_ points: [MapPoint], in bounds: MapBounds, columns: Int = 6, aspect: Double = 1.6,143 singleThreshold: Int = 44, maxItems: Int = 120, pinned: String? = nil) -> [MapItem] {144 if let pinned, let p = points.first(where: { $0.id == pinned }) {145 let rest = cluster(points.filter { $0.id != pinned }, in: bounds, columns: columns, aspect: aspect,146 singleThreshold: singleThreshold, maxItems: maxItems - 1)147 return rest + [MapItem(id: p.id, lat: p.lat, lng: p.lng, kind: .single(p))]148 }149 let area = bounds.padded(0.1)150 let w = max(area.width, 1e-9), h = max(area.height, 1e-9)151 let visible = points.filter { area.contains(lat: $0.lat, lng: $0.lng) }152 guard !visible.isEmpty else { return [] }153 if visible.count <= singleThreshold { return mergeCoincident(visible) }154155 let cols = max(2, columns)156 let rows = max(2, Int((Double(cols) * aspect).rounded()))157 // grille ancrée sur des multiples de la taille de cellule : les regroupements ne sautent pas quand la carte glisse158 let cw = w / Double(cols), ch = h / Double(rows)159 struct Acc { var n = 0; var sumLat = 0.0; var sumLng = 0.0; var amounts: [Double] = []; var first: MapPoint? }160 var cells: [Int64: Acc] = [:]161 for p in visible {162 let cx = Int64((p.lng / cw).rounded(.down)), cy = Int64((p.lat / ch).rounded(.down))163 let key = cx &* 1_000_003 &+ cy164 var a = cells[key] ?? Acc()165 a.n += 1; a.sumLat += p.lat; a.sumLng += p.lng166 if let m = p.amount, m > 0 { a.amounts.append(m) }167 if a.first == nil { a.first = p }168 cells[key] = a169 }170 // fusion des cellules dont les centres sont trop proches : les plaques ne se chevauchent pas171 var accs = cells.values.sorted { ($0.n, $0.sumLat) > ($1.n, $1.sumLat) }172 var merged: [Acc] = []173 let minDist = 0.8174 while !accs.isEmpty {175 var a = accs.removeFirst()176 var again = true177 while again {178 again = false179 let cLat = a.sumLat / Double(a.n), cLng = a.sumLng / Double(a.n)180 var rest: [Acc] = []181 for b in accs {182 let dx = (b.sumLng / Double(b.n) - cLng) / cw, dy = (b.sumLat / Double(b.n) - cLat) / ch183 if dx * dx + dy * dy < minDist * minDist {184 a.n += b.n; a.sumLat += b.sumLat; a.sumLng += b.sumLng; a.amounts += b.amounts185 again = true186 } else { rest.append(b) }187 }188 accs = rest189 }190 merged.append(a)191 }192 var out: [MapItem] = merged.map { a in193 let lat = a.sumLat / Double(a.n), lng = a.sumLng / Double(a.n)194 if a.n == 1, let p = a.first { return MapItem(id: p.id, lat: p.lat, lng: p.lng, kind: .single(p)) }195 let key = "\(Int64((lng / cw).rounded(.down)))_\(Int64((lat / ch).rounded(.down)))"196 return MapItem(id: "c\(key)-\(a.n)", lat: lat, lng: lng, kind: .cluster(count: a.n, median: median(a.amounts)))197 }198 if out.count > maxItems {199 out.sort { $0.count > $1.count }200 out = Array(out.prefix(maxItems))201 }202 return out203 }204205 static func median(_ v: [Double]) -> Double? {206 guard !v.isEmpty else { return nil }207 let s = v.sorted()208 return s.count % 2 == 1 ? s[s.count / 2] : (s[s.count / 2 - 1] + s[s.count / 2]) / 2209 }210211 /// Plusieurs points à la même adresse (même immeuble) : un seul marqueur regroupé.212 private static func mergeCoincident(_ pts: [MapPoint]) -> [MapItem] {213 var groups: [String: [MapPoint]] = [:]214 var order: [String] = []215 for p in pts {216 let k = String(format: "%.4f,%.4f", p.lat, p.lng)217 if groups[k] == nil { order.append(k) }218 groups[k, default: []].append(p)219 }220 return order.compactMap { k in221 guard let g = groups[k], let f = g.first else { return nil }222 if g.count == 1 { return MapItem(id: f.id, lat: f.lat, lng: f.lng, kind: .single(f)) }223 return MapItem(id: "b\(k)-\(g.count)", lat: f.lat, lng: f.lng,224 kind: .cluster(count: g.count, median: median(g.compactMap(\.amount))))225 }226 }227}228