SPB Git

Repository Public

test_moteur.py 15.6 KB 343 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Valo-Plex9# File             : moteur/tests/test_moteur.py10# Module           : moteur11# Repository       : https://git.spboucher.ai/valo-plex12# Project Website  : https://www.valo-plex.com13# Created          : 2026-12-0114# Last Modified    : 2026-12-0315#16# =============================================================================17# AUTHOR & PROFESSIONAL AFFILIATION18# =============================================================================19#20# Author           : Simon-Pierre Boucher21# Position         : Professor of Finance22# Institution      : Université du Québec en Outaouais (UQO)23# Department       : Département des sciences administratives24# Organization     : SP Boucher25#26# Website          : https://spboucher.ai27# Git              : https://git.spboucher.ai28#29# =============================================================================30# OFFICIAL CONTACT DIRECTORY31# =============================================================================32#33# General          : info@spboucher.ai34# Professional     : contact@spboucher.ai35# Direct           : simon@spboucher.ai36# Research         : research@spboucher.ai37# Development      : dev@spboucher.ai38# Support          : support@spboucher.ai39# Security/Admin   : admin@spboucher.ai40# Notifications    : notifications@spboucher.ai41#42# Preferred Contact: contact@spboucher.ai43#44# =============================================================================45# COPYRIGHT & INTELLECTUAL PROPERTY46# =============================================================================47#48# Copyright (c) 202649# Simon-Pierre Boucher50#51# All rights reserved where applicable.52#53# This file is governed by the applicable project license,54# copyright notices, institutional agreements and relevant law.55#56# Unless expressly authorized by the applicable license or57# rights holder, copying, redistribution, sublicensing,58# publication and commercial exploitation are not permitted.59#60# Existing third-party rights and notices remain unaffected.61#62# =============================================================================63# CONFIDENTIALITY & SECURITY64# =============================================================================65#66# Classification   : Public67# Distribution     : Public repository; use is governed by the project license68# Security Contact : admin@spboucher.ai69#70# Access to this source does not independently grant permission71# to redistribute or disclose confidential materials.72#73# Do not embed credentials, private keys, access tokens,74# certificates or confidential personal information.75#76# =============================================================================77# LICENSE & MAINTENANCE78# =============================================================================79#80# License          : None specified (no license file in this repository)81# Maintainer       : Simon-Pierre Boucher82# Technical Contact: dev@spboucher.ai83#84# =============================================================================85# END OF SP BOUCHER SOURCE HEADER86# =============================================================================8788import numpy as np89import pandas as pd9091from plexmoteur import socle92from plexmoteur import variables as V939495def test_nombre():96    assert socle.nombre("163 596,00 $") == 163596.097    assert socle.nombre("2 283 600 $ (2026)") == 2283600.098    assert socle.nombre("sur demande") is None99    assert socle.nombre(None) is None100101102def test_details_revenus_et_logements():103    d = socle.lire_details('{"Revenus annuels": "17 940,00 $", "1 1/2": "1", "3 1/2": "1", "6 1/2 et plus": "1", '104                           '"Taxes municipales": "2 400 $", "Taux d\'occupation": "100"}')105    assert d["revenu"] == 17940.0106    assert d["mix"] == {1: 1, 3: 1, 6: 1}107    assert d["taxe_mun"] == 2400.0108    assert socle.lire_details("pas du json") == {}109110111def test_classes_et_groupes():112    assert [socle.classe(n) for n in (2, 3, 4, 5, 6, 11, 12, 23, 24, 300)] == [113        "duplex", "triplex", "quadruplex", "quintuplex", "6-11", "6-11", "12-23", "12-23", "24+", "24+"]114    assert list(V.groupe([2, 3, 4, 5, 6, 11, 12, 80])) == [0, 1, 2, 2, 3, 3, 4, 4]115116117def test_dates():118    assert V.iso_de(V.jour_de("2026-11-18")) == "2026-11-18"119120121def _histoire():122    rng = np.random.default_rng(1)123    n = 400124    return pd.DataFrame({125        "jour": rng.integers(1000, 1300, n), "code_mun": np.where(np.arange(n) < 300, "A", "B"),126        "region": 6, "ref": 2024, "lr": np.where(np.arange(n) < 300, 0.10, 0.50) + rng.normal(0, 0.01, n)})127128129def test_repere_lisse_vers_la_region():130    H = _histoire()131    T = V.table_ratios(H, know=1300)132    C = pd.DataFrame({"code_mun": ["A", "B", "Z"], "region": [6, 6, 6], "ref": [2024, 2024, 2024]})133    r = V.repere(C, T)134    # une municipalité bien fournie garde son ratio ; une inconnue reçoit celui de la région135    assert abs(r["l_ratio"][0] - 0.10) < 0.02136    assert abs(r["l_ratio"][1] - 0.50) < 0.06137    assert r["ratio_n"][2] == 0 and 0.09 < r["l_ratio"][2] < 0.2138139140def test_repere_ignore_le_futur():141    H = _histoire()142    T = V.table_ratios(H, know=900)          # aucune vente connue à cette date143    C = pd.DataFrame({"code_mun": ["A"], "region": [6], "ref": [2024]})144    assert np.isnan(V.repere(C, T)["l_ratio"][0])145146147def test_un_millesime_de_role_sans_ventes_n_a_pas_de_repere():148    H = _histoire()149    T = V.table_ratios(H, know=1300)150    C = pd.DataFrame({"code_mun": ["A"], "region": [6], "ref": [2030]})151    assert np.isnan(V.repere(C, T)["l_ratio"][0])152153154# --- départage des ventes voisines à distance égale ------------------------------------------------155156def _ventes_ex_aequo(n_meme_point=9, graine=0):157    """Des ventes dont plusieurs au MÊME point (logements d'un même immeuble), plus quelques autres."""158    rng = np.random.default_rng(graine)159    x = np.r_[np.zeros(n_meme_point), rng.uniform(0.5, 3.0, 12)]160    y = np.r_[np.zeros(n_meme_point), rng.uniform(0.5, 3.0, 12)]161    n = len(x)162    return pd.DataFrame({"sale_id": [f"s{i:03d}" for i in range(n)], "id": [f"b{i % 5}" for i in range(n)],163                         "jour": 1000 + np.arange(n), "x": x, "y": y})164165166def _proches(w, k=4, rayon=4.0, cx=(0.1,), cy=(0.0,)):167    d, j = V.plus_proches(w["x"].to_numpy(), w["y"].to_numpy(), V.rang_stable(w),168                          np.asarray(cx, float), np.asarray(cy, float), k, rayon)169    return d, [[w["sale_id"].iloc[i] if i < len(w) else None for i in ligne] for ligne in j]170171172def test_ex_aequo_departages_par_identifiant_de_vente():173    w = _ventes_ex_aequo()174    d, ids = _proches(w, k=4)175    # neuf ventes à la même distance : les quatre retenues sont les quatre plus petits identifiants176    assert ids[0] == ["s000", "s001", "s002", "s003"]177    assert np.allclose(d[0], 0.1)178179180def test_resultat_independant_de_l_ordre_des_lignes():181    w = _ventes_ex_aequo()182    reference = _proches(w, k=6)[1]183    for graine in range(25):184        melange = w.sample(frac=1.0, random_state=graine).reset_index(drop=True)185        assert _proches(melange, k=6)[1] == reference186187188def test_groupe_d_ex_aequo_plus_grand_que_k_et_que_la_marge():189    # trente ventes au même point, k = 3 : la coupe tombe au milieu du groupe, tout le groupe est repris190    w = _ventes_ex_aequo(n_meme_point=30)191    for graine in range(10):192        melange = w.sample(frac=1.0, random_state=graine).reset_index(drop=True)193        assert _proches(melange, k=3)[1][0] == ["s000", "s001", "s002"]194195196def test_sans_ex_aequo_meme_resultat_que_l_arbre():197    from scipy.spatial import cKDTree198    rng = np.random.default_rng(7)199    w = pd.DataFrame({"sale_id": [f"s{i:04d}" for i in range(500)], "id": "b", "jour": 1,200                      "x": rng.uniform(0, 10, 500), "y": rng.uniform(0, 10, 500)})201    cx, cy = rng.uniform(0, 10, 60), rng.uniform(0, 10, 60)202    d, j = V.plus_proches(w["x"].to_numpy(), w["y"].to_numpy(), V.rang_stable(w), cx, cy, 8, 1.5)203    d0, j0 = cKDTree(np.c_[w["x"], w["y"]]).query(np.c_[cx, cy], k=8, distance_upper_bound=1.5)204    assert (j == j0).all()205    assert np.allclose(d[np.isfinite(d)], d0[np.isfinite(d0)], rtol=1e-12)206    assert (np.isfinite(d) == np.isfinite(d0)).all()207208209def test_rayon_et_places_vides():210    w = _ventes_ex_aequo(n_meme_point=2)211    d, j = V.plus_proches(w["x"].to_numpy(), w["y"].to_numpy(), V.rang_stable(w), np.array([0.0]), np.array([0.0]), 5, 0.2)212    assert np.isfinite(d[0]).sum() == 2 and (j[0, 2:] == len(w)).all()213    # plus de places demandées que de ventes214    d, j = V.plus_proches(w["x"].to_numpy()[:3], w["y"].to_numpy()[:3], V.rang_stable(w.iloc[:3]),215                          np.array([0.0]), np.array([0.0]), 8, 9.0)216    assert d.shape == (1, 8) and np.isfinite(d[0]).sum() == 3217218219def test_rang_stable_sans_identifiant_de_vente():220    w = _ventes_ex_aequo().drop(columns=["sale_id"])221    r1 = V.rang_stable(w)222    melange = w.sample(frac=1.0, random_state=3)223    r2 = pd.Series(V.rang_stable(melange.reset_index(drop=True)), index=melange.index).sort_index().to_numpy()224    assert (r1 == r2).all()225226227def test_derniere_vente_le_meme_jour_departagee_par_identifiant():228    w = pd.DataFrame({"sale_id": ["s2", "s9", "s1", "s5"], "id": ["a", "a", "a", "b"],229                      "jour": [10, 20, 20, 7], "e": [0.1, 0.2, 0.3, 0.4]})230    for graine in range(20):231        melange = w.sample(frac=1.0, random_state=graine).reset_index(drop=True)232        d = V.derniere_vente(melange)233        # immeuble « a » : deux ventes le jour 20, la plus grande clé (s9) reste, quel que soit l'ordre des lignes234        assert d.loc["a", "sale_id"] == "s9" and d.loc["a", "e"] == 0.2235        assert d.loc["b", "sale_id"] == "s5"236237238def test_matrice_insensible_au_dernier_bit():239    cols = ("l_aire", "x", "region")240    a = pd.DataFrame({"l_aire": [5.43197375136071, np.nan], "x": [12.5, -3.25], "region": [6.0, np.nan]})241    b = a.copy()242    b.loc[0, "l_aire"] = np.nextafter(5.43197375136071, 10.0)       # le même log, calculé par une autre machine243    Xa, Xb = V.matrice(a, cols), V.matrice(b, cols)244    assert a.loc[0, "l_aire"] != b.loc[0, "l_aire"]245    assert np.array_equal(Xa, Xb, equal_nan=True)246    assert np.isnan(Xa[1, 0]) and Xa[1, 2] == 30.0                 # manquant gardé ; catégorie manquante codée247248249# --- typologie, comparables, réconciliation (marché commercial et trois approches) -------------------250251from plexmoteur import reconcilier, revenu, typologie252253254def test_typologie_cubf():255    c = typologie.categorie_cubf256    assert c(5010) == "commerce" and c(5002) == "centre-commercial" and c(6000) == "bureau"257    assert c(5831) == "hebergement" and c(5811) == "restauration" and c(5533) == "automobile"258    assert c(3280) == "industriel" and c(5020) == "entrepot" and c(6376) == "entrepot"259    assert c(1511) == "habitation-collective" and c(1543) == "habitation-collective"260    # hors champ : résidence de tourisme, rue, école, église, ferme, terrain vacant, logement261    for code in (5834, 4550, 6812, 6911, 8199, 9100, 1000, None):262        assert c(code) is None263    # chaque catégorie commerciale a un indice de groupe distinct, après les cinq tailles résidentielles264    idx = typologie.indice_commercial(typologie.COMMERCIALES)265    assert sorted(idx) == list(range(5, 5 + len(typologie.COMMERCIALES)))266    assert typologie.GROUPES[idx[0]] == typologie.COMMERCIALES[0]267268269def test_preparer_commercial_taille_en_metres_carres():270    df = pd.DataFrame({"lat": [45.5, 45.5], "lng": [-73.6, -73.6], "logements": [0, 2], "aire_m2": [500.0, None],271                       "categorie": ["bureau", "commerce"], "region_code": ["06", "06"]})272    p = V.preparer(df, typologie.COMMERCIAL)273    assert p["taille"][0] == 500.0 and np.isnan(p["taille"][1])274    assert list(p["groupe"]) == [typologie.INDICE_COMMERCIAL["bureau"], typologie.INDICE_COMMERCIAL["commerce"]]275276277def _ventes_comparables():278    n = 12279    return pd.DataFrame({"sale_id": [f"s{i}" for i in range(n)], "id": [f"b{i}" for i in range(n)],280                         "jour": 1000 + np.arange(n), "x": np.linspace(0, 1, n), "y": np.zeros(n),281                         "e": np.r_[np.full(6, 0.10), np.full(6, 0.30)], "taille": 3.0, "groupe": 1})282283284def test_comparables_mediane_ponderee_et_exclusions():285    H = _ventes_comparables()286    profil = V.PROFILS[typologie.RESIDENTIEL]287    C = pd.DataFrame({"id": ["b0", "z"], "x": [0.0, 0.0], "y": [0.0, 0.0], "taille": [3.0, 3.0], "groupe": [1, 1]})288    r = V.comparables(C, H, know=1100, profil=profil)289    assert r["c_n"][1] == V.COMP_K and 0.10 <= r["c_e"][1] <= 0.30290    # une cible ne se compare jamais à sa propre vente291    j = V.plus_proches(H["x"].to_numpy(), H["y"].to_numpy(), V.rang_stable(H), np.array([0.0]), np.array([0.0]), 12, 3.0)[1]292    assert H["id"].to_numpy()[j[0][0]] == "b0"293    seul = V.comparables(C.iloc[[0]], H.iloc[:3], know=1100, profil=profil)       # b0 exclu : deux comparables294    assert np.isnan(seul["c_e"][0]) and seul["c_n"][0] == 2295    # rien n'est connu avant la première vente296    assert np.isnan(V.comparables(C, H, know=900, profil=profil)["c_e"]).all()297298299def test_reconciliation_apprend_des_poids_utiles():300    rng = np.random.default_rng(3)301    n = 1500302    y = rng.normal(13, 0.5, n)303    L = np.c_[y + rng.normal(0, 0.10, n), y + 0.05 + rng.normal(0, 0.12, n), y + rng.normal(0, 0.60, n)]304    L[rng.random(n) < 0.2, 1] = np.nan305    g = np.zeros(n, dtype=int)306    R = reconcilier.apprendre(y, L, g, [0, 1])307    p = R["groupes"][0]["poids"]308    assert abs(sum(p) - 1) < 1e-9 and p[0] > 0.3 and p[1] > 0.1 and p[2] <= 0.1309    assert abs(R["groupes"][0]["biais"][1] - 0.05) < 0.02310    assert R["groupes"][1]["propre"] is False                 # groupe vide : règles de l'ensemble311    rec, P, disp = reconcilier.appliquer(L, g, R)312    assert np.abs(rec - y).mean() < np.abs(L[:, 0] - y).mean()   # mieux que l'hédonique seule313    assert np.allclose(np.nansum(P, axis=1), 1.0)314    # sans approche hédonique, aucune valeur ; sans comparables, leur poids passe aux autres315    rec2, P2, _ = reconcilier.appliquer(np.array([[np.nan, 13.0, 13.0], [13.0, np.nan, 13.2]]), np.array([0, 0]), R)316    assert np.isnan(rec2[0]) and P2[1][1] == 0 and abs(P2[1].sum() - 1) < 1e-9317318319def test_revenu_commercial_selon_les_loyers_publies():320    B = pd.DataFrame({"categorie": ["bureau", "hebergement", "bureau"], "aire_m2": [1000.0, 1000.0, None],321                      "region": [6, 6, 6]})322    R = revenu.calculer_commercial(B)323    assert R["rne"][0] > 0 and R["loyer_net_pi2"][0] == 19.50324    assert np.isnan(R["rne"][1]) and np.isnan(R["rne"][2])       # ni loyer publié, ni aire : rien325    assert list(revenu.zone([6, 3, 8])) == ["montreal", "quebec", "ailleurs"]326327328def test_tranches_et_marches_actifs(monkeypatch):329    assert list(typologie.tranche([2, 3, 5, 6, 11, 12, 23, 24, 49, 50, 300])) == [330        "duplex", "triplex", "4-5", "6-11", "6-11", "12-23", "12-23", "24-49", "24-49", "50+", "50+"]331    monkeypatch.delenv("VX_MARCHES", raising=False)332    assert typologie.marches_actifs() == ("residentiel",)        # le commercial n'est pas servi par défaut333    monkeypatch.setenv("VX_MARCHES", "commercial,residentiel")334    assert typologie.marches_actifs() == ("residentiel", "commercial")335336337def test_comparables_detail_poids_de_somme_un():338    H = _ventes_comparables()339    C = pd.DataFrame({"id": ["z"], "x": [0.0], "y": [0.0], "taille": [3.0], "groupe": [1]})340    r = V.comparables(C, H, know=1100, profil=V.PROFILS[typologie.RESIDENTIEL], detail=True)341    assert abs(r["_poids"][0].sum() - 1) < 1e-9 and r["_sale"].shape == (1, V.COMP_K)342    assert (np.diff(r["_poids"][0]) <= 1e-12).all()             # par poids décroissant343
Files main
Menu

Theme