Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * PROJECT METADATA8 * -----------------------------------------------------------------------------9 * Project : Vrai-Prix Android10 * File : app/src/test/kotlin/com/spboucher/vraiprix/MapLayersTest.kt11 * Description : la carte KA Maps sur des réponses réelles (production du12 * 2026-12-01, préproduction pour les agrégats) : trois13 * natures qui ne se confondent pas (forme, nature du moteur,14 * genre de pastille), politique de densité des étiquettes,15 * points confondus, couches d'analyse et leurs règles de16 * publication.17 * Module : test18 * Repository : https://git.spboucher.ai/vrai-prix-android19 * Project Website : https://www.vrai-prix.com20 * Created : 2026-12-0121 * Last Modified : 2026-12-0122 *23 * =============================================================================24 * AUTHOR & PROFESSIONAL AFFILIATION25 * =============================================================================26 *27 * Author : Simon-Pierre Boucher28 * Position : Professor of Finance29 * Institution : Université du Québec en Outaouais (UQO)30 * Department : Département des sciences administratives31 * Organization : SP Boucher32 *33 * Website : https://spboucher.ai34 * Git : https://git.spboucher.ai35 *36 * =============================================================================37 * OFFICIAL CONTACT DIRECTORY38 * =============================================================================39 *40 * General : info@spboucher.ai41 * Professional : contact@spboucher.ai42 * Direct : simon@spboucher.ai43 * Research : research@spboucher.ai44 * Development : dev@spboucher.ai45 * Support : support@spboucher.ai46 * Security/Admin : admin@spboucher.ai47 * Notifications : notifications@spboucher.ai48 *49 * Preferred Contact: dev@spboucher.ai50 *51 * =============================================================================52 * COPYRIGHT & INTELLECTUAL PROPERTY53 * =============================================================================54 *55 * Copyright (c) 202656 * Simon-Pierre Boucher57 *58 * All rights reserved where applicable.59 *60 * This file is governed by the applicable project license,61 * copyright notices, institutional agreements and relevant law.62 *63 * Unless expressly authorized by the applicable license or64 * rights holder, copying, redistribution, sublicensing,65 * publication and commercial exploitation are not permitted.66 *67 * Existing third-party rights and notices remain unaffected.68 *69 * =============================================================================70 * CONFIDENTIALITY & SECURITY71 * =============================================================================72 *73 * Classification : Public74 * Distribution : Public repository; use is governed by the project license75 * Security Contact : admin@spboucher.ai76 *77 * Access to this source does not independently grant permission78 * to redistribute or disclose confidential materials.79 *80 * Do not embed credentials, private keys, access tokens,81 * certificates or confidential personal information.82 *83 * =============================================================================84 * LICENSE & MAINTENANCE85 * =============================================================================86 *87 * License : None specified (no license file in this repository)88 * Maintainer : Simon-Pierre Boucher89 * Technical Contact: dev@spboucher.ai90 *91 * =============================================================================92 * END OF SP BOUCHER SOURCE HEADER93 * =============================================================================94 */9596package com.spboucher.vraiprix9798import ai.spboucher.kamaps.KaLayer99import ai.spboucher.kamaps.KaLayerData100import ai.spboucher.kamaps.KaLayerType101import com.spboucher.vraiprix.core.model.CellGrid102import com.spboucher.vraiprix.core.model.ListingsPage103import com.spboucher.vraiprix.core.model.MeasureNature104import com.spboucher.vraiprix.core.model.PricePosition105import com.spboucher.vraiprix.core.model.PropertyPoints106import com.spboucher.vraiprix.core.model.SalesGrid107import com.spboucher.vraiprix.core.model.SalesPage108import com.spboucher.vraiprix.core.model.TerritoryMap109import com.spboucher.vraiprix.core.model.ValueGrid110import com.spboucher.vraiprix.core.model.ValueStatus111import com.spboucher.vraiprix.core.net.CarteApi112import com.spboucher.vraiprix.core.net.CarteCapabilities113import com.spboucher.vraiprix.core.net.MapBounds114import com.spboucher.vraiprix.core.util.Fmt115import com.spboucher.vraiprix.core.util.ValueFmt116import com.spboucher.vraiprix.design.MapStyle117import com.spboucher.vraiprix.features.map.Analysis118import com.spboucher.vraiprix.features.map.DotShape119import com.spboucher.vraiprix.features.map.ScreenBox120import com.spboucher.vraiprix.features.map.PlumbStyle121import com.spboucher.vraiprix.features.map.MapFilters122import com.spboucher.vraiprix.features.map.MapLayer123import com.spboucher.vraiprix.features.map.MapLayers124import com.spboucher.vraiprix.features.map.MapPalette125import com.spboucher.vraiprix.features.map.MapPoint126import com.spboucher.vraiprix.features.map.MapRules127import com.spboucher.vraiprix.features.map.MapViewport128import com.spboucher.vraiprix.features.map.containsBounds129import com.spboucher.vraiprix.features.map.padded130import com.spboucher.vraiprix.features.map.samePlace131import kotlinx.serialization.json.JsonArray132import kotlinx.serialization.json.JsonObject133import kotlinx.serialization.json.JsonPrimitive134import kotlinx.serialization.json.jsonArray135import kotlinx.serialization.json.jsonObject136import kotlinx.serialization.json.jsonPrimitive137import org.junit.Assert.assertEquals138import org.junit.Assert.assertFalse139import org.junit.Assert.assertNotNull140import org.junit.Assert.assertNull141import org.junit.Assert.assertTrue142import org.junit.Test143144class MapLayersTest {145 private val light = MapPalette(dark = false)146 private val units = PropertyPoints.from(Fixtures.json("carte-proprietes")).items.map { MapPoint.of(it) }147 private val sales = SalesPage.from(Fixtures.json("carte-ventes")).items.mapNotNull { MapPoint.of(it) }148 private val listings = ListingsPage.from(Fixtures.json("carte-inscriptions")).items.mapNotNull { MapPoint.of(it) }149 private val describe: (MapPoint) -> String = { it.id }150151 private fun data(l: KaLayer): JsonArray = ((l.data as KaLayerData.Json).element as JsonArray)152 private fun features(l: KaLayer): JsonArray = ((l.data as KaLayerData.Json).element as JsonObject)["features"]!!.jsonArray153 private fun str(o: JsonObject, k: String): String? = (o[k] as? JsonPrimitive)?.content154155 // --- Trois natures ---------------------------------------------------------------------------------156157 @Test158 fun realResponsesCarryTheThreeNatures() {159 assertEquals(160, units.size)160 assertTrue(units.count { it.value?.isFirm == true } > 50)161 assertTrue(units.any { it.value?.status == ValueStatus.ORDRE } && units.any { it.amount == null })162 assertTrue(sales.any { it.sale?.deMarche == true } && sales.any { it.sale?.deMarche == false })163 assertTrue(listings.any { it.listing?.position?.position != null } && listings.any { it.listing?.position?.position == null })164 }165166 @Test167 fun eachNatureHasItsOwnShapeNeverSharedWithAnother() {168 val unitShapes = units.map { MapLayers.shape(it) }.toSet()169 val saleShapes = sales.map { MapLayers.shape(it) }.toSet()170 val listingShapes = (listings.map { MapLayers.shape(it) } + listings.map { MapLayers.shape(it, Analysis.GAP) }).toSet()171 assertEquals(setOf(DotShape.DOT, DotShape.RING), unitShapes)172 assertEquals(setOf(DotShape.SQUARE, DotShape.RING_STRUCK), saleShapes)173 assertEquals(setOf(DotShape.DIAMOND_RING, DotShape.DIAMOND), listingShapes)174 // rond = estimation, carré ou anneau barré = vente réelle, losange = prix demandé : aucune forme commune175 assertTrue((unitShapes intersect saleShapes).isEmpty() && (unitShapes intersect listingShapes).isEmpty() && (saleShapes intersect listingShapes).isEmpty())176 // une vente hors marché est barrée, jamais un carré plein177 assertTrue(sales.filter { it.sale?.deMarche != true }.all { MapLayers.shape(it) == DotShape.RING_STRUCK })178 }179180 @Test181 fun anEstimatedValueIsNeverDrawnAsAnObservedPrice() {182 // nature du moteur : `estime` (cernée) ou `hypothese` (tiretée) pour une valeur ; `observe` pour un prix réel183 assertTrue(units.none { MapLayers.nature(it).id == "observe" })184 assertTrue(units.filter { it.value?.isFirm == true }.all { MapLayers.nature(it).id == "estime" })185 assertTrue(units.filter { it.value?.status == ValueStatus.ORDRE }.all { MapLayers.nature(it).id == "hypothese" })186 assertTrue((sales + listings).all { MapLayers.nature(it).id == "observe" })187 // genres de la marque : aucun pour une valeur (outremer cerné), `sale` au charbon, `listing` ocre188 assertTrue(units.all { MapLayers.kind(it) == null })189 assertTrue(sales.all { MapLayers.kind(it) == "sale" } && listings.all { MapLayers.kind(it) == "listing" })190 }191192 @Test193 fun labelsSayTheRegime() {194 val firm = units.first { it.value?.isFirm == true }195 val order = units.first { it.value?.status == ValueStatus.ORDRE }196 val none = units.first { it.amount == null }197 assertFalse(MapLayers.label(firm)!!.startsWith("≈"))198 assertTrue(MapLayers.label(order)!!.startsWith("≈ "))199 assertNull(MapLayers.label(none))200 // aucune espace insécable dans une étiquette dessinée par le moteur201 assertTrue((units + sales + listings).mapNotNull { MapLayers.label(it) }.none { it.contains(' ') })202 // couche « écart » : la position se lit par un signe, pas par la couleur seule203 val gap = listings.filter { it.listing?.position?.position != null }.map { MapLayers.label(it, Analysis.GAP)!! }204 assertTrue(gap.isNotEmpty() && gap.all { it.startsWith("↓ ") || it.startsWith("= ") || it.startsWith("↑ ") })205 assertTrue(listings.filter { it.listing?.position?.position == null }.all { l -> MapLayers.label(l, Analysis.GAP)!!.first().isDigit() })206 }207208 @Test209 fun dotsLayersKeepNaturesApart() {210 val layers = MapLayers.dots(units, Analysis.UNITS_POINTS, light, 15.0)211 assertEquals(listOf(MapStyle.Layers.DOTS_FIRM, MapStyle.Layers.DOTS_ORDER, MapStyle.Layers.DOTS_NONE), layers.map { it.id })212 assertTrue(layers.all { it.type == KaLayerType.POINTS })213 assertEquals(units.size, layers.sumOf { data(it).size })214 assertEquals(listOf("dot", "ring", "ring"), layers.map { str(it.options, "shape") })215 // les valeurs fermes sont teintées par l'une des cinq classes outremer ; jamais par la rampe des prix payés216 val firmColors = data(layers[0]).map { str(it.jsonObject, "color")!! }.toSet()217 assertTrue(firmColors.isNotEmpty() && light.valueRamp.containsAll(firmColors))218 assertTrue((firmColors intersect light.salesRamp.toSet()).isEmpty())219 // une propriété sans valeur ne porte aucun montant220 assertTrue(data(layers[2]).none { it.jsonObject.containsKey("value") })221222 val saleLayers = MapLayers.dots(sales, Analysis.SALES_POINTS, light, 15.0)223 assertEquals(listOf(MapStyle.Layers.DOTS_SALES, MapStyle.Layers.DOTS_OFF_MARKET), saleLayers.map { it.id })224 assertEquals(listOf("square", "ring-struck"), saleLayers.map { str(it.options, "shape") })225 assertEquals(20, data(saleLayers[1]).size)226227 val gapLayers = MapLayers.dots(listings, Analysis.GAP, light, 15.0)228 assertEquals(listOf(MapStyle.Layers.DOTS_LISTINGS), gapLayers.map { it.id })229 val shapes = data(gapLayers[0]).map { str(it.jsonObject, "shape") ?: str(gapLayers[0].options, "shape") }230 assertEquals(listings.count { it.listing?.position?.position != null }, shapes.count { it == "diamond" })231 assertEquals(listings.count { it.listing?.position?.position == null }, shapes.count { it == "diamond-ring" })232 assertTrue(MapLayers.dots(emptyList(), Analysis.SALES_POINTS, light, 15.0).isEmpty())233 }234235 @Test236 fun uncertaintyTintsFirmValuesByTheWidthOfTheirInterval() {237 val layer = MapLayers.dots(units, Analysis.UNCERTAINTY, light, 15.0).first { it.id == MapStyle.Layers.DOTS_FIRM }238 val colors = data(layer).map { str(it.jsonObject, "color")!! }.toSet()239 assertTrue(light.widthRamp.containsAll(colors))240 val classes = light.classes(Analysis.UNCERTAINTY)!!241 assertEquals(0, classes.index(0.10)); assertEquals(1, classes.index(0.15)); assertEquals(4, classes.index(0.30))242 }243244 @Test245 fun valueClassesAreTheFiveFixedClassesOfTheSite() {246 val c = light.classes(Analysis.UNITS_POINTS)!!247 assertEquals(MeasureNature.ESTIMATION, c.nature)248 assertEquals(listOf(0, 1, 2, 3, 4), listOf(299_999.0, 300_000.0, 450_000.0, 650_000.0, 1_000_000.0).map(c::index))249 assertEquals("#2540a6", c.color(2_000_000.0))250 // les prix payés ont leur rampe, distincte de l'outremer des valeurs251 assertEquals(MeasureNature.SALE, light.classes(Analysis.PRICE_TERRITORIES)!!.nature)252 assertTrue((light.classes(Analysis.PRICE_TERRITORIES)!!.colors intersect c.colors.toSet()).isEmpty())253 assertEquals(5, MapPalette(dark = true).classes(Analysis.TREND)!!.colors.size)254 }255256 // --- Densité, regroupements, points confondus ----------------------------------------------------------257258 private val view = MapViewport(MapBounds(-73.59, 45.52, -73.57, 45.53), widthDp = 411.0, heightDp = 560.0, zoom = 15.2)259260 @Test261 fun labelPolicyBoundsTheCountAndNeverOverlaps() {262 val picked = MapRules.pickLabels(units, view, null) { MapLayers.label(it) }263 val budget = (411.0 * 560.0 / MapRules.LABEL_AREA).toInt()264 assertTrue(picked.isNotEmpty() && picked.size <= budget)265 // jamais une propriété sans valeur, jamais deux étiquettes qui se recouvrent, rien hors de la zone dégagée266 assertTrue(picked.all { MapLayers.label(it) != null })267 val boxes = picked.map { p ->268 val (x, y) = MapRules.screen(view, p.lat, p.lng)269 val (w, h) = MapRules.pillSize(MapLayers.label(p)!!, 1.0)270 doubleArrayOf(x - w / 2, y - h, x + w / 2, y)271 }272 for (b in boxes) assertTrue(b[0] >= 0 && b[1] >= 0 && b[2] <= 411.0 && b[3] <= 560.0)273 for (i in boxes.indices) for (j in i + 1 until boxes.size) {274 val (a, b) = boxes[i] to boxes[j]275 assertFalse(a[0] < b[2] && a[2] > b[0] && a[1] < b[3] && a[3] > b[1])276 }277 // les valeurs fermes passent avant les ordres de grandeur ; la même vue donne les mêmes étiquettes278 assertTrue(picked.first().value?.isFirm == true)279 assertEquals(picked.map { it.id }, MapRules.pickLabels(units, view, null) { MapLayers.label(it) }.map { it.id })280 }281282 @Test283 fun theSelectionAlwaysHasItsLabelEvenWithoutValue() {284 val none = units.first { it.amount == null && view.bounds.contains(it.lat, it.lng) }285 val picked = MapRules.pickLabels(units, view, none.id) { MapLayers.label(it) ?: if (it.id == none.id) "Sans valeur" else null }286 assertEquals(none.id, picked.first().id)287 val layer = MapLayers.labels(picked, Analysis.UNITS_POINTS, light, none.id, "Sans valeur", describe)288 val m = data(layer).first().jsonObject289 assertEquals("Sans valeur", str(m, "label")); assertEquals("selected", str(m, "state")); assertEquals("hypothese", str(m, "nature"))290 // l'app a déjà écarté les recouvrements : le désencombrement du moteur est coupé291 assertEquals("false", str(layer.options, "declutter"))292 }293294 @Test295 fun anAskingPriceLabelIsLightWithAnOchreRuleNeverASalePill() {296 val picked = listings.filter { it.amount != null }.take(12)297 val layer = MapLayers.labels(picked, Analysis.LISTINGS_POINTS, light, null, "Sans valeur", describe)298 for (m in data(layer).map { it.jsonObject }) {299 assertEquals("listing", str(m, "kind")); assertEquals("observe", str(m, "nature"))300 assertEquals(light.paper, str(m, "color")); assertEquals(light.listing, str(m, "strokeColor")); assertEquals(light.ink, str(m, "textColor"))301 }302 // le jour comme la nuit : une vente est une étiquette pleine (charbon, ivoire la nuit), une valeur estimée une303 // étiquette cernée d'outremer sur fond de papier, jamais pleine304 for (dark in listOf(false, true)) {305 val p = MapPalette(dark)306 val sale = data(MapLayers.labels(sales.take(5), Analysis.SALES_POINTS, p, null, "Sans valeur", describe)).first().jsonObject307 assertEquals("sale", str(sale, "kind")); assertEquals(p.sale, str(sale, "color")); assertEquals(p.paper, str(sale, "textColor"))308 val unit = data(MapLayers.labels(units.filter { it.value?.isFirm == true }.take(5), Analysis.UNITS_POINTS, p, null, "Sans valeur", describe)).first().jsonObject309 assertNull(unit["kind"]); assertEquals("estime", str(unit, "nature"))310 assertEquals(p.paper, str(unit, "color")); assertEquals(p.brand, str(unit, "strokeColor")); assertEquals(p.brand, str(unit, "textColor"))311 assertFalse(str(sale, "color") == str(unit, "color"))312 }313 // couche « écart » : le filet prend la teinte de la position, la flèche la dit aussi314 val gap = data(MapLayers.labels(listings.filter { it.listing?.position?.position == PricePosition.DANS }.take(1), Analysis.GAP, light, null, "Sans valeur", describe)).first().jsonObject315 assertEquals(light.inside, str(gap, "strokeColor")); assertTrue(str(gap, "label")!!.startsWith("= "))316 }317318 @Test319 fun groupPlatesNeverBorrowTheUltramarineOfEstimates() {320 for (dark in listOf(false, true)) {321 val p = MapPalette(dark)322 val s = MapLayers.groups(sales, MapLayer.SALES, Analysis.SALES_POINTS, p, null, "Sans valeur", describe).options["cluster"]!!.jsonObject323 assertEquals(p.sale, str(s, "color")); assertEquals(p.paper, str(s, "textColor"))324 val l = MapLayers.groups(listings, MapLayer.LISTINGS, Analysis.LISTINGS_POINTS, p, null, "Sans valeur", describe).options["cluster"]!!.jsonObject325 assertEquals(p.paper, str(l, "color")); assertEquals(p.listing, str(l, "strokeColor"))326 assertFalse(p.brand in listOf(str(s, "color"), str(s, "strokeColor"), str(l, "color"), str(l, "strokeColor"), str(l, "textColor")))327 // les valeurs estimées gardent l'outremer, en filet et en texte : une plaque cernée, jamais pleine328 val u = MapLayers.groups(units, MapLayer.UNITS, Analysis.UNITS_POINTS, p, null, "Sans valeur", describe).options["cluster"]!!.jsonObject329 assertEquals(p.brand, str(u, "strokeColor")); assertEquals(p.paper, str(u, "color"))330 }331 }332333 @Test334 fun noLabelUnderTheInterfaceLaidOverTheMap() {335 val free = MapRules.pickLabels(sales, view, null) { MapLayers.label(it) }336 assertTrue(free.isNotEmpty())337 // un bouton posé là où une étiquette tenait : elle n'y est plus, et aucune autre ne s'y pose338 val (x, y) = MapRules.screen(view, free.first().lat, free.first().lng)339 val button = ScreenBox(x - 30, y - 40, x + 30, y + 8)340 val picked = MapRules.pickLabels(sales, view.copy(blocked = listOf(button)), null) { MapLayers.label(it) }341 for (p in picked) {342 val (px, py) = MapRules.screen(view, p.lat, p.lng)343 val (w, h) = MapRules.pillSize(MapLayers.label(p)!!, 1.0)344 assertFalse(px - w / 2 < button.right && px + w / 2 > button.left && py - h < button.bottom && py > button.top)345 }346 // le point choisi garde la sienne, où qu'il soit347 val sel = free.first().id348 assertEquals(sel, MapRules.pickLabels(sales, view.copy(blocked = listOf(button)), sel) { MapLayers.label(it) }.first().id)349 }350351 @Test352 fun theChosenPointKeepsItsNatureInItsPlumbLabel() {353 val firm = units.first { it.value?.isFirm == true }354 val order = units.first { it.amount != null && it.value?.isFirm != true }355 val none = units.first { it.amount == null }356 val market = sales.first { it.sale?.deMarche == true }357 val asking = listings.first { it.amount != null }358 val f = PlumbStyle.of(firm, Analysis.UNITS_POINTS, light)359 // une valeur estimée : cernée d'outremer sur fond clair, jamais pleine360 assertEquals(light.paper, f.fill); assertEquals(light.brand, f.stroke); assertFalse(f.dashed); assertFalse(f.hollowTip)361 val o = PlumbStyle.of(order, Analysis.UNITS_POINTS, light)362 assertTrue(o.dashed && o.hollowTip); assertEquals(light.paper, o.fill)363 assertEquals(light.muted, PlumbStyle.of(none, Analysis.UNITS_POINTS, light).stroke)364 // une vente réelle : pleine au charbon ; un prix demandé : claire à filet ocre365 val s = PlumbStyle.of(market, Analysis.SALES_POINTS, light)366 assertEquals(light.sale, s.fill); assertEquals(light.paper, s.text)367 val a = PlumbStyle.of(asking, Analysis.LISTINGS_POINTS, light)368 assertEquals(light.paper, a.fill); assertEquals(light.listing, a.stroke)369 assertEquals(3, setOf(f.fill to f.stroke, s.fill to s.stroke, a.fill to a.stroke).size)370 // le moteur ne dessine pas une seconde étiquette sous la vue ancrée371 val layer = MapLayers.labels(listOf(firm, order), Analysis.UNITS_POINTS, light, firm.id, "Sans valeur", describe, annotated = true)372 assertEquals(listOf(order.id), data(layer).map { str(it.jsonObject, "id") })373 }374375 @Test376 fun aDenseZoneIsReadInQuartersOrShownAsSectorsNeverTruncated() {377 val area = MapBounds(-73.60, 45.50, -73.56, 45.54)378 assertEquals(listOf(area), MapRules.readingParts(area, 850, 850))379 val q = MapRules.readingParts(area, 851, 850)380 assertEquals(4, q.size)381 // les quatre quarts couvrent la zone, sans trou ni débord382 assertEquals(area.west, q.minOf { it.west }, 0.0); assertEquals(area.east, q.maxOf { it.east }, 0.0)383 assertEquals(area.south, q.minOf { it.south }, 0.0); assertEquals(area.north, q.maxOf { it.north }, 0.0)384 assertEquals(area.lngSpan * area.latSpan, q.sumOf { it.lngSpan * it.latSpan }, 1e-12)385 assertTrue(MapRules.readingParts(area, 3401, 850).isEmpty())386 }387388 @Test389 fun aTiltedViewHandsItsLabelsToTheEngineAtTheSameDensity() {390 val tilted = view.copy(flat = false)391 val c = MapRules.labelCandidates(sales, tilted, null)392 val budget = (view.widthDp * view.heightDp / MapRules.LABEL_AREA).toInt()393 assertTrue(c.isNotEmpty() && c.size <= budget * 2)394 // les ventes de marché d'abord, comme à plat395 assertTrue(c.first().sale?.deMarche == true)396 val layer = MapLayers.labels(c, Analysis.SALES_POINTS, light, null, "Sans valeur", describe, annotated = true, byEngine = true)397 // le moteur désencombre : aucune étiquette en recouvrement, aucune sous l'interface déclarée398 assertEquals("true", str(layer.options, "declutter"))399 }400401 @Test402 fun aFirmValueReadsTheSameOnItsLabelAndInItsPreview() {403 for (p in units.filter { it.value?.isFirm == true }) {404 val a = p.value!!.amounts!!405 assertEquals(Fmt.compact(ValueFmt.rounded(a.value, a.low, a.high)).replace('\u00A0', ' '), MapLayers.label(p))406 }407 }408409 @Test410 fun largerFontMeansFewerLabels() {411 val normal = MapRules.pickLabels(sales, view, null, 1.0) { MapLayers.label(it) }412 val large = MapRules.pickLabels(sales, view, null, 1.3) { MapLayers.label(it) }413 assertTrue(large.size <= normal.size && large.isNotEmpty())414 assertTrue(MapRules.pillSize("512 k$", 1.3).first > MapRules.pillSize("512 k$", 1.0).first)415 // au-delà de 1,3 la pastille ne grossit plus (la carte reste lisible)416 assertEquals(MapRules.pillSize("512 k$", 1.3), MapRules.pillSize("512 k$", 2.0))417 }418419 @Test420 fun groupsLayerClustersByMedianForPricesAndByCountForEstimates() {421 val s = MapLayers.groups(sales, MapLayer.SALES, Analysis.SALES_POINTS, light, null, "Sans valeur", describe)422 assertEquals(MapStyle.Layers.GROUPS, s.id)423 assertEquals(sales.size, data(s).size)424 val c = s.options["cluster"]!!.jsonObject425 assertEquals("median", str(c, "aggregate")); assertEquals("{count} ventes · {value}", str(c, "labelTemplate")); assertEquals("true", str(c, "keepSelected"))426 assertEquals(MapRules.CLUSTER_MAX_ZOOM.toString(), str(c, "maxZoom"))427 // des valeurs fermes et des ordres de grandeur mêlés n'ont pas de médiane qui veuille dire quelque chose428 val u = MapLayers.groups(units, MapLayer.UNITS, Analysis.UNITS_POINTS, light, null, "Sans valeur", describe)429 assertEquals("count", str(u.options["cluster"]!!.jsonObject, "aggregate"))430 assertEquals("{count}", str(u.options["cluster"]!!.jsonObject, "labelTemplate"))431 // une propriété sans valeur compte dans son groupe, sans étiquette432 assertEquals(units.size, data(u).size)433 assertEquals(units.count { it.amount == null }, data(u).count { !it.jsonObject.containsKey("label") })434 // les ventes de marché d'abord (ordre des données = priorité du moteur)435 assertEquals("s" + sales.first { it.sale?.deMarche == true }.sale!!.id, str(data(s).first().jsonObject, "id"))436 }437438 @Test439 fun pointsAtTheSameAddressAreOfferedAsAList() {440 val byPlace = units.groupBy { Math.round(it.lat * 1e5) to Math.round(it.lng * 1e5) }441 val shared = byPlace.values.firstOrNull { it.size > 1 }442 if (shared != null) assertEquals(shared.map { it.id }.toSet(), samePlace(units, shared.first()).map { it.id }.toSet())443 val a = units.first()444 val twin = a.copy(id = "jumeau")445 assertEquals(setOf(a.id, "jumeau"), samePlace(units + twin, a).filter { it.id == a.id || it.id == "jumeau" }.map { it.id }.toSet())446 val far = a.copy(id = "loin", lat = a.lat + 0.01)447 assertEquals(listOf("loin"), samePlace(listOf(far), far).map { it.id })448 }449450 @Test451 fun filtersAndBounds() {452 val f = MapFilters(type = "condo", min = 300_000.0)453 assertTrue(sales.filter(f::keeps).all { it.type == "condo" && (it.amount ?: 0.0) >= 300_000.0 })454 assertEquals(0, MapFilters().activeCount); assertEquals(2, f.activeCount)455 val b = MapBounds(-73.5912, 45.5203, -73.5701, 45.5309)456 val snapped = MapRules.snapped(b.padded(0.2), 0.02, 0.48)457 assertTrue(snapped.containsBounds(b))458 // la même emprise pour deux vues voisines : la réponse gardée est relue (304, hors ligne)459 assertEquals(snapped.bbox, MapRules.snapped(MapBounds(-73.5905, 45.5210, -73.5710, 45.5300).padded(0.2), 0.02, 0.48).bbox)460 assertTrue(MapRules.snapped(MapBounds(-74.6, 45.0, -73.0, 46.4), 0.02, 0.48).let { it.lngSpan <= 0.4801 && it.latSpan <= 0.4801 })461 }462463 // --- Analyses ------------------------------------------------------------------------------------------464465 @Test466 fun analysesBelongToOneNatureAndHideWithoutTheirRoute() {467 val none = CarteCapabilities.NONE468 val all = CarteCapabilities(territories = true, salesGrid = true)469 // production d'aujourd'hui (routes absentes) : seules les couches qui n'en dépendent pas s'offrent470 assertEquals(listOf(Analysis.UNITS_POINTS, Analysis.UNCERTAINTY, Analysis.VALUE_CELLS), Analysis.offered(MapLayer.UNITS, none))471 assertEquals(listOf(Analysis.SALES_POINTS), Analysis.offered(MapLayer.SALES, none))472 assertEquals(listOf(Analysis.LISTINGS_POINTS, Analysis.GAP), Analysis.offered(MapLayer.LISTINGS, none))473 assertEquals(Analysis.offered(MapLayer.SALES, none), Analysis.offered(MapLayer.SALES, null))474 assertEquals(5, Analysis.offered(MapLayer.SALES, all).size)475 assertEquals(Analysis.entries.size, MapLayer.entries.sumOf { Analysis.offered(it, all).size })476 // chaque analyse a la nature de sa couche : la rampe ne ment pas477 for (a in Analysis.entries) light.classes(a)?.let { c ->478 assertEquals(when (a.layer) { MapLayer.UNITS -> MeasureNature.ESTIMATION; MapLayer.SALES -> MeasureNature.SALE; MapLayer.LISTINGS -> MeasureNature.ASKING }, c.nature)479 }480 assertEquals("region", MapRules.level(5.0)); assertEquals("mrc", MapRules.level(7.0)); assertEquals("municipalite", MapRules.level(10.0)); assertEquals("local", MapRules.level(12.0))481 assertEquals(12 to 9, MapRules.gridSize(768.0, 576.0)); assertEquals(4 to 40, MapRules.gridSize(100.0, 9000.0))482 }483484 @Test485 fun territoriesDecodeWithTheirRuleAndDates() {486 val m = TerritoryMap.from(Fixtures.json("carte-territoires-valeur"))487 assertEquals("valeur", m.mesure.code); assertEquals(MeasureNature.ESTIMATION, m.mesure.nature); assertEquals(30, m.mesure.seuil)488 assertEquals(34, m.items.size); assertEquals(33, m.publies); assertEquals(1, m.sousLeSeuil)489 val montreal = m.items.first { it.slug == "montreal" }490 assertEquals("municipalite/66023", montreal.limite); assertEquals(654_200.0, montreal.valeur!!, 0.5); assertTrue(montreal.publie)491 val hidden = m.items.first { !it.publie }492 assertNull(hidden.valeur)493 val v = TerritoryMap.from(Fixtures.json("carte-territoires-ventes"))494 assertEquals(MeasureNature.SALE, v.mesure.nature); assertTrue(v.mesure.periodique)495 assertEquals("provisoire", v.periode!!.etat); assertTrue(v.periodesOffertes.containsAll(listOf("12-mois", "2025")))496 val t = TerritoryMap.from(Fixtures.json("carte-territoires-tendance"))497 assertEquals("tendance", t.mesure.code); assertEquals(52, t.sousLeSeuil); assertNull(t.periode)498 assertEquals("2026-T3", t.items.first { it.publie }.periode)499 }500501 @Test502 fun choroplethTintsOnlyPublishedTerritoriesAndStaysBelowWater() {503 val m = TerritoryMap.from(Fixtures.json("carte-territoires-tendance"))504 val shape = CarteApi.geometryOf(Fixtures.text("geo-limite-arrondissement"))!!505 assertEquals("MultiPolygon", str(shape, "type"))506 val published = m.items.first { it.publie }507 val hidden = m.items.first { !it.publie && it.limite != null }508 val shapes = mapOf(published.limite!! to shape, hidden.limite!! to shape)509 val classes = light.classes(Analysis.TREND)!!510 val layers = MapLayers.territories(m.items, shapes, classes, light, picked = hidden.id)511 assertEquals(listOf(MapStyle.Layers.TERRITORIES, MapStyle.Layers.TERRITORIES_NA, MapStyle.Layers.TERRITORY_PICK), layers.map { it.id })512 // sous l'eau du fond : un fleuve n'est jamais teinté513 assertEquals("below-water", str(layers[0].options, "slot"))514 val f = features(layers[0]).single().jsonObject515 assertEquals(published.id, str(f, "id"))516 assertEquals(classes.color(published.valeur!!), str(f["properties"]!!.jsonObject, "color"))517 // sous le seuil : contour tireté (nature « hypothèse »), opacité nulle, aucune couleur ni valeur518 val na = features(layers[1]).single().jsonObject["properties"]!!.jsonObject519 assertFalse(na.containsKey("color")); assertFalse(na.containsKey("value"))520 assertEquals("hypothese", str(layers[1].options, "nature")); assertEquals(0.0, layers[1].options["fillOpacity"]!!.jsonPrimitive.content.toDouble(), 0.0)521 assertEquals(KaLayerType.LINES, layers[2].type)522 // un territoire sans limite reçue n'est pas dessiné523 assertTrue(MapLayers.territories(m.items, emptyMap(), classes, light, null).isEmpty())524 assertNull(CarteApi.geometryOf("{\"error\":{\"code\":\"introuvable\"}}")); assertNull(CarteApi.geometryOf("<html>"))525 }526527 @Test528 fun salesGridPublishesMediansOnlyAboveItsThresholdAndNeverFillsHoles() {529 val g = SalesGrid.from(Fixtures.json("carte-ventes-grille"))530 assertTrue(g.disponible); assertEquals(12, g.grid.cols); assertEquals(10, g.grid.rows); assertEquals(120, g.grid.values.size)531 assertEquals(10, g.seuilCase); assertEquals(50, g.seuilEmprise); assertEquals(12_592, g.retenues); assertEquals(1_966, g.horsMarche)532 assertEquals(99, g.grid.published)533 // une case sous le seuil reste nulle, et la couche à plat n'a un rectangle que par case publiée534 for (i in g.grid.values.indices) if (g.grid.counts[i] < g.seuilCase) assertNull(g.grid.values[i])535 val classes = light.classes(Analysis.PRICE_CELLS)!!536 val cells = MapLayers.cells(g.grid, classes, zoom = 12.0)!!537 assertEquals(99, features(cells).size)538 assertEquals("below-water", str(cells.options, "slot"))539 // de près : par-dessus les empreintes (`above: buildings` est l'écriture que tous les moteurs comprennent)540 assertEquals("buildings", str(MapLayers.cells(g.grid, classes, zoom = 14.5)!!.options, "above"))541 val first = features(cells).first().jsonObject["properties"]!!.jsonObject542 assertEquals(classes.color(476.5), str(first, "color")); assertEquals("46", str(first, "n"))543 // la case sous un point : celle du nord-ouest544 assertEquals(0 to 0, g.grid.at(45.5599, -73.6499)); assertNull(g.grid.at(46.0, -73.6))545 val c = g.grid.cell(0, 0)546 assertEquals(-73.65, c.west, 1e-9); assertEquals(45.56, c.north, 1e-9)547 // en relief : une valeur par nœud, emprise rentrée d'une demi-case, trous gardés548 val surface = MapLayers.surface(g.grid, classes, 420.0)!!549 val s = (surface.data as KaLayerData.Json).element.jsonObject550 assertEquals(-73.65 + (0.13 / 12) / 2, s["o"]!!.jsonPrimitive.content.toDouble(), 1e-9)551 assertEquals(120, s["values"]!!.jsonArray.size)552 assertEquals(21, s["values"]!!.jsonArray.count { it is kotlinx.serialization.json.JsonNull })553 // chaleur : un point par case où il y a des ventes, pesé par leur nombre ; elle ne porte aucun prix554 val heat = MapLayers.heat(g.grid, light)!!555 assertEquals(KaLayerType.HEAT, heat.type)556 assertEquals(g.grid.counts.count { it > 0 } * 3, (heat.data as KaLayerData.Triplets).values.size)557 }558559 @Test560 fun aGridBelowTheZoneThresholdDrawsNothing() {561 val g = SalesGrid.from(Fixtures.json("carte-ventes-grille-vide"))562 if (!g.disponible) {563 assertNotNull(g.motif)564 } else {565 assertTrue(g.retenues >= g.seuilEmprise && g.grid.published >= g.casesMin)566 }567 val empty = CellGrid(MapBounds(0.0, 0.0, 1.0, 1.0), 2, 2, listOf(null, null, null, null), listOf(3, 0, 1, 2))568 assertNull(MapLayers.cells(empty, light.classes(Analysis.PRICE_CELLS)!!, 12.0))569 assertNull(MapLayers.surface(empty, light.classes(Analysis.PRICE_CELLS)!!, 400.0))570 assertNull(MapLayers.heat(CellGrid(MapBounds(0.0, 0.0, 1.0, 1.0), 1, 1, listOf(null), listOf(0)), light))571 }572573 @Test574 fun valueGridKeepsEachCellInItsPlaceAndItsThreshold() {575 val b = MapBounds(-73.6, 45.5, -73.56, 45.54)576 val g = ValueGrid.from(Fixtures.json("carte-valeurs-grille"), b, 6, 8)577 assertEquals(30, g.seuil); assertEquals(40_000, g.unitesMax); assertEquals(48, g.grid.values.size)578 assertTrue(g.disponible && g.grid.published >= ValueGrid.MIN_CELLS)579 // une case sans médiane (moins de 30 valeurs fermes) reste vide580 for (i in g.grid.values.indices) if (g.grid.counts[i] < g.seuil) assertNull(g.grid.values[i])581 assertTrue(g.grid.values.filterNotNull().all { it > 50_000 })582 // au-delà de 40 000 propriétés le service ne publie rien : rien n'est tracé, le motif est dit583 val big = ValueGrid.from(Fixtures.json("v3-grille"), MapBounds(-73.65, 45.48, -73.52, 45.56), 14, 9)584 if (!big.disponible) assertTrue(big.grid.published < ValueGrid.MIN_CELLS || big.motif != null)585 }586587 @Test588 fun analyticBuildingsCarryFirmValuesOnlyAndNeverAHeight() {589 val layer = MapLayers.buildings(units, Analysis.UNITS_POINTS, light)!!590 assertEquals(KaLayerType.BUILDINGS, layer.type)591 assertEquals(units.count { it.value?.isFirm == true }, data(layer).size)592 // la hauteur d'un volume reste celle du fond de carte593 assertEquals("false", str(layer.options, "heights"))594 assertTrue(data(layer).all { !it.jsonObject.containsKey("height") && str(it.jsonObject, "nature") == "estime" })595 // un ordre de grandeur ne teinte aucun bâtiment596 val firmIds = units.filter { it.value?.isFirm == true }.map { it.id }.toSet()597 assertTrue(data(layer).all { str(it.jsonObject, "id") in firmIds })598 // ventes et prix demandés : le bâtiment marque le lieu, à la teinte de sa nature, jamais à l'outremer des valeurs599 val s = MapLayers.buildings(sales, Analysis.SALES_POINTS, light)!!600 assertEquals(sales.count { it.sale?.deMarche == true }, data(s).size)601 assertTrue(data(s).all { str(it.jsonObject, "nature") == "observe" && str(it.jsonObject, "color") == light.sale && !it.jsonObject.containsKey("height") })602 val l = MapLayers.buildings(listings, Analysis.LISTINGS_POINTS, light)!!603 assertTrue(data(l).all { str(it.jsonObject, "nature") == "observe" && str(it.jsonObject, "color") == light.listing })604 assertEquals("false", str(s.options, "heights"))605 }606}607