Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : KA Maps Engine9// File : sdk/ios/Example/App/Scenarios5.swift10// Module : sdk11// Repository : https://git.spboucher.ai/ka-maps-engine12// Created : 2026-12-0113// Last Modified : 2026-12-0114//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 : None specified (no license file in this repository)80// Maintainer : Simon-Pierre Boucher81// Technical Contact: dev@spboucher.ai82//83// =============================================================================84// END OF SP BOUCHER SOURCE HEADER85// =============================================================================8687import CoreLocation88import KAMaps89import UIKit9091/// SDK 0.4.0 : moteur des phases 11 et 12 — plaques entières ou absentes (bord de la vue compris), texte des92/// plaques, bâtiment mis en évidence par sa donnée, bâtiments teintés pour VoiceOver, état de chargement de la vue,93/// source des lots, écart du corps d'une pastille, genre des étiquettes, adresses de tuiles versionnées.94extension ScenarioRunner {95 static var round5: [String] { ["engine12"] }9697 func engine12() async throws {98 try await reset(.montreal, zoom: 13.4)99 guard let v = map.mapView else { throw ScenarioFailure("vue absente") }100 let c = DemoPlace.montreal.coordinate101 func errors(since m: Int) -> [String] {102 model.log[m...].compactMap { e -> String? in if case .error(let s) = e.event { return s } else { return nil } }103 }104105 // 1. Plaques : entières dans la vue ou absentes, à plusieurs positions ; texte rendu ; options nouvelles.106 var pts = DemoData.markers(around: c, count: 420, brand: .louka, spread: 0.05, seed: 21)107 for i in pts.indices { pts[i].kind = i % 3 == 0 ? "good" : "high" }108 var m = mark109 try await settle { map.addLayer(.markers(id: "plaques", pts, cluster: KAClusterOptions(radius: 46, maxZoom: 17, aggregate: .median, label: .value, labelTemplate: "{value}\n{count} logements", shares: ["good"], maxShift: 60, fullCounts: true))) }110 try check(errors(since: m).isEmpty, "options de grappe refusées : \(errors(since: m))")111 var cut = 0, seen = 0, labelled = 0112 for (k, d) in [(0.0, 0.0), (0.0031, 0.3), (-0.0047, 0.6), (0.0013, -0.4)].enumerated() {113 if k > 0 { try await settle { map.jumpTo(KACamera(center: CLLocationCoordinate2D(latitude: c.latitude + d.0 * 0.7, longitude: c.longitude + d.0), zoom: 13.4 + d.1)) } }114 await sleep(0.4)115 for r in try map.renderedMarkers(layer: "plaques") where r.feature.kind == .cluster {116 seen += 1117 if !v.bounds.insetBy(dx: -0.5, dy: -0.5).contains(r.rect) { cut += 1 }118 if r.isPill, let t = r.feature.label, t.contains("logements"), t.contains("\n") { labelled += 1 }119 }120 if k == 0 { await checkpoint("engine12-plaques") }121 }122 fact("plaques", ["vues": .number(Double(seen)), "coupees": .number(Double(cut)), "avecTexte": .number(Double(labelled))])123 try check(seen >= 30 && cut == 0, "\(cut) signes de grappe coupés par le bord de la vue sur \(seen)")124 try check(labelled >= 20, "le texte des plaques doit être rendu par renderedMarkers : \(labelled) sur \(seen)")125 // Grappe sans valeur : gabarit de repli.126 try await settle { map.jumpTo(KACamera(center: c, zoom: 12.2)) }127 let bare = DemoData.markers(around: c, count: 200, brand: .louka).map { KAMarker(id: $0.id, coordinate: $0.coordinate, label: $0.label) }128 m = mark129 try await settle { map.addLayer(.markers(id: "plaques", bare, cluster: KAClusterOptions(aggregate: .median, label: .value, labelTemplate: "{value} · {count}", labelTemplateEmpty: "{count} logements"))) }130 await sleep(0.3)131 let texts = try map.renderedMarkers(layer: "plaques").filter { $0.feature.kind == .cluster && $0.isPill }.compactMap(\.feature.label)132 fact("labelTemplateEmpty", .array(texts.prefix(3).map(KAJSON.string)))133 try check(!texts.isEmpty && texts.allSatisfy { $0.hasSuffix(" logements") && !$0.contains("·") }, "gabarit de repli attendu : \(texts.prefix(4))")134 map.removeLayer("plaques")135136 // 2. Écart du corps d'une pastille ; priorité des étiquettes de zone (acceptée).137 try await settle { map.jumpTo(KACamera(center: c, zoom: 15)) }138 let a = CLLocationCoordinate2D(latitude: c.latitude, longitude: c.longitude - 0.003), b = CLLocationCoordinate2D(latitude: c.latitude, longitude: c.longitude + 0.003)139 m = mark140 try await settle {141 map.addLayer(.markers(id: "ecart", [KAMarker(id: "a", coordinate: a, label: "Sans écart"), KAMarker(id: "b", coordinate: b, label: "Cet immeuble", offset: CGSize(width: 0, height: -24))], cluster: nil, density: .off))142 map.addLayer(.polygons(id: "zones", geoJSON: ["type": "FeatureCollection", "features": [["type": "Feature", "properties": ["id": "z1", "nom": "Zone d'essai", "population": 10], "geometry": ["type": "Polygon", "coordinates": [.array(DemoData.zone(around: c, radius: 0.01).map { [.number($0.longitude), .number($0.latitude)] })]]]]], fillColor: "#b5452c", fillOpacity: 0.15, labelProperty: "nom", labelPriorityProperty: "population"))143 }144 try check(errors(since: m).isEmpty, "offset ou labelPriority refusés : \(errors(since: m))")145 await sleep(0.3)146 let rm = try map.renderedMarkers(layer: "ecart")147 guard let ra = rm.first(where: { $0.feature.id == "a" }), let rb = rm.first(where: { $0.feature.id == "b" }), let pa = map.project(a), let pb = map.project(b) else { throw ScenarioFailure("pastilles d'essai absentes") }148 let lift = Double((pa.y - ra.rect.midY) - (pb.y - rb.rect.midY))149 fact("offset.lift", .number((lift * 10).rounded() / 10))150 try check(abs(lift + 24) < 1.5, "le corps de la pastille doit monter de 24 points : \(lift)")151 await checkpoint("engine12-offset")152 map.removeLayer("ecart")153 map.removeLayer("zones")154155 // 3. État de chargement de la vue ; genre des étiquettes du fond.156 m = mark157 map.jumpTo(KACamera(center: DemoPlace.quebec.coordinate, zoom: 14.6))158 let busy = try map.viewState()159 let st = await map.whenIdle(timeout: 40)160 fact("viewState", ["avant.idle": .bool(busy.isIdle), "idle": .bool(st.isIdle), "complete": .bool(st.isComplete), "wanted": .number(Double(st.tilesWanted)), "ready": .number(Double(st.tilesReady)), "failed": .number(Double(st.tilesFailed))])161 try check(st.isIdle && st.isComplete && st.tilesWanted > 0 && st.tilesReady == st.tilesWanted && st.tilesFailed == 0, "état au repos inattendu : \(st)")162 try check(map.isIdle && map.lastIdleState?.isComplete == true, "isIdle et lastIdleState doivent suivre l'événement idle")163 let at = try map.viewState(at: CGPoint(x: v.bounds.midX, y: v.bounds.midY)).point164 try check(at?.isLoaded == true && at?.isDrawn == true && at?.hasFailed == false && (at?.layers.contains("road") ?? false), "tuile sous le centre : \(String(describing: at))")165 fact("viewState.at", ["tile": .string(at?.tile ?? ""), "layers": .array((at?.layers ?? []).map(KAJSON.string)), "parcel": .string(at?.parcel ?? "")])166 var kinds = Set<String>()167 for y in stride(from: 80.0, through: Double(v.bounds.height) - 80, by: 14) {168 for x in stride(from: 20.0, through: Double(v.bounds.width) - 20, by: 24) {169 for f in try map.queryRendered(at: CGPoint(x: x, y: y), layers: ["base"]) where f.kind == .label {170 if let k = f.featureKind { kinds.insert(k) }171 }172 }173 }174 fact("labelKinds", .array(kinds.sorted().map(KAJSON.string)))175 try check(!kinds.isEmpty, "aucune étiquette du fond ne rend son genre")176177 // 4. Source des lots.178 m = mark179 map.setParcelSource(.auto)180 await sleep(0.3)181 try check(errors(since: m).isEmpty && map.parcelSource == .auto, "setParcelSource refusé : \(errors(since: m))")182 let parcel = try map.viewState(at: CGPoint(x: v.bounds.midX, y: v.bounds.midY)).point?.parcel183 fact("parcel.auto", .string(parcel ?? "nil"))184 try check(parcel != nil && parcel != "off", "en mode auto l'état des lots ne doit pas être « off » : \(String(describing: parcel))")185 _ = await map.whenIdle(timeout: 20)186 map.setParcelSource(.base)187188 // 5. Bâtiment mis en évidence par sa donnée ; bâtiments teintés rendus, éléments VoiceOver.189 try await settle { map.jumpTo(KACamera(center: c, zoom: 16.4)) }190 await sleep(0.5)191 var site: CLLocationCoordinate2D?192 search: for dy in stride(from: -120.0, through: 120.0, by: 40) {193 for dx in stride(from: -120.0, through: 120.0, by: 40) {194 let p = CGPoint(x: v.bounds.midX + dx, y: v.bounds.midY + dy)195 if let f = try map.queryRendered(at: p, layers: ["base:building"]).first, f.building != nil, let ll = map.unproject(p) {196 site = ll197 break search198 }199 }200 }201 guard let site else { throw ScenarioFailure("aucun bâtiment sous la vue pour l'essai") }202 let data = [KAPoint(id: "u1", coordinate: site, value: 1, label: "Immeuble d'essai, 3 logements"), KAPoint(id: "u2", coordinate: site, value: 5), KAPoint(id: "u3", coordinate: site, value: 9)]203 m = mark204 map.addLayer(.buildings(id: "plex", data, scale: KAScale(.linear, stops: [(0, "#2f6f8f"), (10, "#b5452c")]), aggregate: .median))205 _ = try await wait("buildings:match", since: m, timeout: 30) { if case .buildingsMatch(let b) = $0 { return b.layer == "plex" && b.isFinal } else { return false } }206 _ = await map.whenIdle(timeout: 20)207 let rb2 = try map.renderedBuildings(layer: "plex")208 fact("renderedBuildings", .number(Double(rb2.count)))209 try check(rb2.count == 1 && rb2[0].feature.id == "u1" && Set(rb2[0].feature.buildingMembers) == ["u1", "u2", "u3"] && rb2[0].rect.width > 8 && rb2[0].feature.label == "Immeuble d'essai, 3 logements", "bâtiment teinté rendu : \(rb2.map { "\($0.feature.raw)" })")210 try check(try map.renderedMarkers(layer: "plex").isEmpty, "renderedMarkers ne doit pas rendre les bâtiments")211 m = mark212 try await settle { map.highlightBuilding(layer: "plex", id: "u2", color: "#103050") }213 try check(errors(since: m).isEmpty, "highlightBuilding(layer:id:) refusé : \(errors(since: m))")214 await checkpoint("engine12-batiment-cerne")215 try check(map.clearHighlight(), "un cerne devait être posé par highlightBuilding(layer:id:)")216 m = mark217 map.highlightBuilding(layer: "plex", id: "absente")218 await sleep(0.4)219 try check(!errors(since: m).isEmpty, "une donnée inconnue doit donner un événement d'erreur")220 v.setNeedsLayout()221 v.layoutIfNeeded()222 let ids = (v.accessibilityElements ?? []).compactMap { ($0 as? UIAccessibilityElement)?.accessibilityIdentifier }223 let el = (v.accessibilityElements ?? []).compactMap { $0 as? UIAccessibilityElement }.first { $0.accessibilityIdentifier == "KAMapBuilding-plex-u1" }224 fact("a11y.building", ["label": .string(el?.accessibilityLabel ?? ""), "value": .string(el?.accessibilityValue ?? "")])225 try check(el?.accessibilityLabel == "Immeuble d'essai, 3 logements" && (el?.accessibilityValue ?? "").contains("3"), "élément VoiceOver du bâtiment teinté absent ou mal libellé : \(ids)")226 map.removeLayer("plex")227228 // 6. Adresses de tuiles versionnées ; le stock (clé sans paramètre) sert la même vue réseau coupé.229 let far = CLLocationCoordinate2D(latitude: 48.4490 + Double(Int(Date().timeIntervalSince1970) % 50) * 0.0004, longitude: -68.5230)230 let n0 = map.networkStats231 try await settle(timeout: 40) { map.jumpTo(KACamera(center: far, zoom: 13.7)) }232 let n1 = map.networkStats233 fact("tiles", ["demandes": .number(Double(n1.completed - n0.completed)), "versionnees": .number(Double(n1.versioned - n0.versioned)), "version": .string(n1.dataVersion ?? "")])234 try check(n1.dataVersion?.isEmpty == false, "version des données inconnue")235 if n1.completed > n0.completed { try check(n1.versioned > n0.versioned, "les tuiles demandées doivent porter ?v= (\(n1.completed - n0.completed) demandes, \(n1.versioned - n0.versioned) versionnées)") }236 let tri = try map.perf().triangles237 v.networkPolicy = .offlineOnly238 try await settle { map.jumpTo(KACamera(center: c, zoom: 9)) }239 let n2 = map.networkStats240 try await settle { map.jumpTo(KACamera(center: far, zoom: 13.7)) }241 let (tri2, n3) = (try map.perf().triangles, map.networkStats)242 v.networkPolicy = .default243 fact("stock", ["triangles": .number(Double(tri)), "horsReseau": .number(Double(tri2)), "requetes": .number(Double(n3.completed - n2.completed))])244 try check(tri2 > 0 && abs(tri2 - tri) <= tri / 20 && n3.completed == n2.completed, "réseau coupé, la vue doit venir du stock : \(tri) puis \(tri2) triangles")245 try await settle { map.jumpTo(KACamera(center: c, zoom: 12)) }246 }247}248