SPB Git

Repository Public

Scenarios3.swift 14.4 KB 250 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : KA Maps Engine9// File             : sdk/ios/Example/App/Scenarios3.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/// Ajouts du moteur des phases 7 et 8, typés par le SDK 0.2.0 : parts et écart des grappes, plaque à deux92/// lignes, obstacles de l'interface, couleurs par pastille, emplacement des couches (`slot`), formes de points,93/// étiquettes du fond par couche source, bornes géographiques — et leur reprise après une perte du périphérique.94extension ScenarioRunner {95    static var round3: [String] { ["engine8"] }9697    func engine8() async throws {98        try await reset(.montreal, zoom: 11.5)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. Grappes : part par genre, écart, plaque à deux lignes.106        var pts = DemoData.markers(around: c, count: 300, brand: .louka)107        for i in pts.indices { pts[i].kind = i % 3 == 0 ? "good" : (i % 3 == 1 ? "high" : nil) }108        var m = mark109        try await settle {110            map.addLayer(.markers(id: "parts", pts, cluster: KAClusterOptions(aggregate: .median, label: .value, labelTemplate: "{value}\n{count} annonces", gap: 8, shares: ["good", "high"])))111        }112        try check(errors(since: m).isEmpty, "options de grappe refusées : \(errors(since: m))")113        let clusters = try map.renderedMarkers(layer: "parts").filter { $0.feature.kind == .cluster }114        try check(clusters.count >= 3, "grappes attendues : \(clusters.count)")115        let withShares = clusters.filter { !$0.feature.shares.isEmpty }116        fact("clusters", .number(Double(clusters.count)))117        fact("clusters.withShares", .number(Double(withShares.count)))118        try check(withShares.count == clusters.count, "chaque grappe doit rendre ses parts : \(withShares.count) sur \(clusters.count)")119        for k in withShares {120            let g = k.feature.shares["good"] ?? -1, h = k.feature.shares["high"] ?? -1121            try check(g >= 0 && h >= 0 && g + h <= 1.0001, "parts incohérentes : \(k.feature.shares)")122        }123        // Le tiers des données est « good » : la part pondérée par l'effectif doit s'en approcher.124        let total = clusters.reduce(0.0) { $0 + Double($1.feature.clusterCount ?? 0) }125        let good = clusters.reduce(0.0) { $0 + Double($1.feature.clusterCount ?? 0) * ($1.feature.shares["good"] ?? 0) }126        fact("share.good", .number(total > 0 ? (good / total * 1000).rounded() / 1000 : 0))127        try check(total > 0 && abs(good / total - 1.0 / 3) < 0.08, "part « good » pondérée : \(good / max(total, 1))")128        var overlaps = 0129        for i in clusters.indices { for j in clusters.indices where j > i && clusters[i].rect.intersects(clusters[j].rect) { overlaps += 1 } }130        fact("clusters.overlaps", .number(Double(overlaps)))131        try check(overlaps == 0, "\(overlaps) paires de plaques se recouvrent")132        await checkpoint("engine8-grappes-parts")133        map.removeLayer("parts")134135        // 2. Obstacles de l'interface et couleurs par pastille.136        try await settle { map.jumpTo(KACamera(center: c, zoom: 13.6)) }137        var pills = DemoData.markers(around: c, count: 160, brand: .louka, spread: 0.03, seed: 5)138        for i in pills.indices where i % 4 == 0 {139            pills[i].color = "#1f4e79"140            pills[i].textColor = "#ffffff"141            pills[i].strokeColor = "#0b2239"142            pills[i].priority = 10143        }144        m = mark145        try await settle { map.addLayer(.markers(id: "pastilles", pills, cluster: nil)) }146        try check(errors(since: m).isEmpty, "couleurs par pastille refusées : \(errors(since: m))")147        let obstacle = CGRect(x: 0, y: v.bounds.midY - 110, width: v.bounds.width, height: 220)148        // `renderedMarkers` rend aussi les marqueurs réduits à leur point : une pastille est plus large que 24 points.149        func pillsIn(_ r: CGRect) throws -> Int {150            try map.renderedMarkers(layer: "pastilles").filter { $0.feature.kind == .marker && $0.rect.width > 24 && $0.rect.intersects(r) }.count151        }152        let before = try pillsIn(obstacle)153        try check(before > 0, "aucune pastille dans la bande d'essai avant de la déclarer")154        await checkpoint("engine8-pastilles-couleurs")155        try await settle { map.setObstacles([obstacle]) }156        await sleep(0.4)157        let after = try pillsIn(obstacle)158        fact("obstacle.before", .number(Double(before)))159        fact("obstacle.after", .number(Double(after)))160        try check(after == 0, "\(after) pastilles encore dessinées dans l'obstacle (avant : \(before))")161        // Sous l'obstacle, le marqueur n'est ni dessiné ni touchable (moteur de la 0.3.0 ; il restait un point en 0.2.0).162        let under = pills.first { p in map.project(p.coordinate).map { obstacle.insetBy(dx: 20, dy: 20).contains($0) } ?? false }163        if let under, let p = map.project(under.coordinate) {164            let hit = try map.queryRendered(at: p, layers: ["pastilles"])165            try check(hit.isEmpty, "le marqueur sous l'obstacle ne doit plus être interrogeable : \(hit.count)")166        }167        await checkpoint("engine8-obstacles")168        try await settle { map.setObstacles([]) }169        await sleep(0.4)170        let cleared = try pillsIn(obstacle)171        try check(cleared > 0, "obstacles retirés : les pastilles doivent revenir")172        map.removeLayer("pastilles")173174        // 3. Emplacement d'une couche : choroplèthe sous l'eau et les routes ; formes et étiquettes de points.175        let river = CLLocationCoordinate2D(latitude: 45.5075, longitude: -73.5370)176        try await settle { map.jumpTo(KACamera(center: river, zoom: 13.2)) }177        let ring = DemoData.zone(around: river, radius: 0.02)178        var shapes: [KAPoint] = []179        let all = KAPointShape.allCases180        for (i, s) in all.enumerated() {181            let pos = CLLocationCoordinate2D(latitude: river.latitude + 0.012, longitude: river.longitude - 0.018 + Double(i) * 0.006)182            shapes.append(KAPoint(id: "s\(i)", coordinate: pos, value: Double(i) / Double(all.count), radius: 9, label: s.rawValue, shape: s))183        }184        m = mark185        try await settle {186            map.addLayer(.polygon(id: "zone-eau", ring: ring, fillColor: "#b5452c", fillOpacity: 0.55, strokeColor: "#b5452c", strokeWidth: 2, slot: .belowWater))187            map.addLayer(.points(id: "formes", shapes, scale: DemoData.valueScale, strokeColor: "#ffffff", strokeWidth: 1, labelSize: 12))188        }189        try check(errors(since: m).isEmpty, "slot ou formes refusés : \(errors(since: m))")190        // Le polygone reste interrogeable sous l'eau comme par-dessus (sonde au centre de l'anneau).191        let probe = map.project(river) ?? .zero192        let hitBelow = try map.queryRendered(at: probe, layers: ["zone-eau"]).count193        fact("slot.hitBelowWater", .number(Double(hitBelow)))194        await checkpoint("engine8-slot-sous-eau")195        try await settle { map.addLayer(.polygon(id: "zone-eau", ring: ring, fillColor: "#b5452c", fillOpacity: 0.55, strokeColor: "#b5452c", strokeWidth: 2, slot: .top)) }196        let hitTop = try map.queryRendered(at: probe, layers: ["zone-eau"]).count197        fact("slot.hitTop", .number(Double(hitTop)))198        try check(hitBelow == 1 && hitTop == 1, "polygone interrogeable : sous l'eau \(hitBelow), dessus \(hitTop)")199        await checkpoint("engine8-slot-dessus")200        map.removeLayer("zone-eau")201        map.removeLayer("formes")202203        // 4. Étiquettes du fond par couche source.204        try await settle { map.jumpTo(KACamera(center: c, zoom: 15.2)) }205        await sleep(0.6)206        let labels0 = try map.perf().labels207        try check(labels0 > 5, "trop peu d'étiquettes pour l'essai : \(labels0)")208        await checkpoint("engine8-etiquettes-toutes")209        try await settle { map.setBaseLabels([.poi: .hidden, .transit: .hidden, .road: .hidden, .place: .hidden, .houseNumber: .hidden, .water: .hidden, .landuse: .hidden]) }210        await sleep(0.8)211        let labels1 = try map.perf().labels212        let hidden = try map.command("setBaseLabels", ["poi": false])["hidden"]?.arrayValue?.compactMap(\.stringValue) ?? []213        try check(Set(hidden).isSuperset(of: ["poi", "transit", "road", "place"]), "couches masquées rendues par le moteur : \(hidden)")214        await checkpoint("engine8-etiquettes-masquees")215        try await settle { map.setBaseLabels([.poi: .hiddenKinds(["restaurant", "cafe"]), .transit: .shown, .road: .shown, .place: .shown, .houseNumber: .shown, .water: .shown, .landuse: .shown]) }216        await sleep(0.8)217        let labels2 = try map.perf().labels218        fact("labels", [.number(Double(labels0)), .number(Double(labels1)), .number(Double(labels2))])219        try check(labels1 * 2 < labels0, "étiquettes masquées : \(labels0) → \(labels1)")220        try check(labels2 > labels1, "étiquettes rétablies : \(labels1) → \(labels2)")221        try check(map.baseLabels == [.poi: .hiddenKinds(["restaurant", "cafe"])], "règles gardées par le contrôleur : \(map.baseLabels)")222        try await settle { map.setBaseLabels([.poi: .shown]) }223224        // 5. Bornes géographiques, gardées après une perte du périphérique.225        let island = KABounds(west: -73.98, south: 45.40, east: -73.47, north: 45.71)226        map.setMaxBounds(island)227        map.setObstacles([CGRect(x: 0, y: 0, width: v.bounds.width, height: 120)])228        try await settle { map.jumpTo(KACamera(center: DemoPlace.quebec.coordinate, zoom: 13)) }229        var cam = map.camera230        fact("maxBounds.center", [.number((cam.center.longitude * 1000).rounded() / 1000), .number((cam.center.latitude * 1000).rounded() / 1000)])231        try check(island.contains(cam.center), "bornes : centre \(cam.center) hors de l'île")232        let vb = try map.visibleBounds()233        try check(vb.west >= island.west - 0.002 && vb.east <= island.east + 0.002 && vb.south >= island.south - 0.002 && vb.north <= island.north + 0.002, "bornes : la vue \(vb) dépasse \(island)")234        m = mark235        v.simulateDeviceLoss()236        _ = try await wait("renderer:restarted", since: m, timeout: 15) { if case .rendererRestarted = $0 { return true } else { return false } }237        try await waitIdle(since: m, timeout: 40)238        try await settle { map.jumpTo(KACamera(center: DemoPlace.quebec.coordinate, zoom: 13)) }239        cam = map.camera240        try check(island.contains(cam.center), "bornes perdues après la reprise du rendu : centre \(cam.center)")241        let count = try map.command("setObstacles", ["rects": [[0, 0, 10, 10]]])["count"]?.intValue242        try check(count == 1, "setObstacles doit rendre le nombre de rectangles : \(String(describing: count))")243        map.setObstacles([])244        map.setMaxBounds(nil)245        try await settle { map.jumpTo(KACamera(center: DemoPlace.quebec.coordinate, zoom: 13)) }246        try check(!island.contains(map.camera.center), "bornes retirées : la carte doit aller à Québec")247        try await settle { map.jumpTo(KACamera(center: c, zoom: 12)) }248    }249}250
Files main
Menu

Theme