SPB Git

Repository Public

environment.py 10.3 KB 272 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/environment.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-1813# Last Modified    : 2026-08-1814#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: contact@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# =============================================================================8687# -----------------------------------------------------------------------------88# Lou-Ka — Agrégateur de logements à louer (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# environment.py : données d'environnement OpenStreetMap par tuile (Overpass)91#   pour le calcul des KA Scores (kascores.py). Même stratégie « par tuiles »92#   que poi.py (0,5° + marge) mais avec un inventaire élargi :93#     · routes majeures (autoroutes/artères) et voies ferrées AVEC géométrie94#       (nœuds) — distances aux sources de bruit du KA Calme Score ;95#     · aéroports/héliports, zones industrielles, bars/boîtes de nuit ;96#     · pistes cyclables (géométrie) — densité du KA Bike Score ;97#     · TOUS les points d'intérêt des catégories poi.py — plus proches ET98#       comptages par rayon (KA Walk/Services Scores).99#   Cache permanent en base (table env_tiles), rafraîchi aux ~3 mois.100#   Attribution : données © contributeurs OpenStreetMap (ODbL).101# -----------------------------------------------------------------------------102from __future__ import annotations103104import json105import math106import time107108from . import db109from .poi import (110    CATEGORIES, OVERPASS_URLS, PoiClient, TILE, TILE_MARGIN, _match_category,111    _tile_of,112)113114REFRESH_AFTER = 90 * 86400   # l'environnement bâti bouge peu115116# Classes linéaires (bruit / vélo) : (clé, sélecteur Overpass)117_LINEAR = [118    ("autoroute", '["highway"~"^(motorway|motorway_link|trunk)$"]'),119    ("artere",    '["highway"~"^(primary|secondary)$"]'),120    ("rail",      '["railway"~"^(rail|light_rail)$"]["service"!~"."]'),121    ("cyclable",  '["highway"="cycleway"]'),122    ("cyclable2", '["cycleway"~"^(lane|track|opposite_lane|opposite_track)$"]'),123]124125# Classes ponctuelles additionnelles (bruit / vie nocturne)126_POINTS = [127    ("aeroport",   '["aeroway"~"^(aerodrome|heliport)$"]'),128    ("industriel", '["landuse"="industrial"]'),129    ("bar",        '["amenity"~"^(bar|nightclub|pub)$"]'),130]131132133def _tile_bbox(ty: int, tx: int) -> str:134    s = ty * TILE - TILE_MARGIN135    n = (ty + 1) * TILE + TILE_MARGIN136    w = tx * TILE - TILE_MARGIN137    e = (tx + 1) * TILE + TILE_MARGIN138    return f"{s:.4f},{w:.4f},{n:.4f},{e:.4f}"139140141def _linear_query(ty: int, tx: int) -> str:142    bbox = _tile_bbox(ty, tx)143    parts = [f"way{sel}({bbox});" for _k, sel in _LINEAR]144    return f'[out:json][timeout:240];({"".join(parts)});out geom;'145146147def _points_query(ty: int, tx: int) -> str:148    bbox = _tile_bbox(ty, tx)149    parts = [f"nwr{sel}({bbox});" for _k, sel in _POINTS]150    parts += [f"nwr{sel}({bbox});" for _c, _l, sel, _r in CATEGORIES]151    return f'[out:json][timeout:240];({"".join(parts)});out center tags;'152153154def _match_linear(tags: dict) -> str | None:155    hw = tags.get("highway")156    if hw in ("motorway", "motorway_link", "trunk"):157        return "autoroute"158    if hw in ("primary", "secondary"):159        return "artere"160    if tags.get("railway") in ("rail", "light_rail"):161        return "rail"162    if hw == "cycleway" or tags.get("cycleway") in (163            "lane", "track", "opposite_lane", "opposite_track"):164        return "cyclable"165    return None166167168def _match_point(tags: dict) -> str | None:169    if tags.get("aeroway") in ("aerodrome", "heliport"):170        return "aeroport"171    if tags.get("landuse") == "industrial":172        return "industriel"173    if tags.get("amenity") in ("bar", "nightclub", "pub"):174        return "bar"175    return None176177178def fetch_tile(client: PoiClient, ty: int, tx: int) -> dict | None:179    """Inventaire environnemental d'une tuile.180181    Format : {"lines": {classe: [[[lat,lng],…] par voie]},182              "points": {classe: [[lat,lng],…]},183              "pois":   {cat: [[lat,lng],…]}}184    """185    lines_raw = client._post(_linear_query(ty, tx))186    if lines_raw is None:187        return None188    points_raw = client._post(_points_query(ty, tx))189    if points_raw is None:190        return None191192    lines: dict[str, list] = {}193    for el in lines_raw:194        tags = el.get("tags") or {}195        cls = _match_linear(tags)196        geom = el.get("geometry") or []197        if cls is None or len(geom) < 2:198            continue199        # nœuds arrondis à 5 décimales (~1 m) — suffisant pour des distances200        lines.setdefault(cls, []).append(201            [[round(g["lat"], 5), round(g["lon"], 5)] for g in geom])202203    points: dict[str, list] = {}204    pois: dict[str, list] = {}205    for el in points_raw:206        tags = el.get("tags") or {}207        lat = el.get("lat") or (el.get("center") or {}).get("lat")208        lng = el.get("lon") or (el.get("center") or {}).get("lon")209        if lat is None or lng is None:210            continue211        pt = [round(lat, 5), round(lng, 5)]212        cls = _match_point(tags)213        if cls is not None:214            points.setdefault(cls, []).append(pt)215        cat = _match_category(tags)216        if cat is not None:217            pois.setdefault(cat, []).append(pt)218219    return {"lines": lines, "points": points, "pois": pois}220221222def needed_tiles(con) -> list[tuple[int, int]]:223    """Tuiles couvrant les immeubles géolocalisés du parc actif."""224    rows = con.execute(225        """SELECT DISTINCT ROUND(lat,4) la, ROUND(lng,4) ln FROM listings226           WHERE active=1 AND lat IS NOT NULL AND lng IS NOT NULL""").fetchall()227    return sorted({_tile_of(r["la"], r["ln"]) for r in rows})228229230def run(limit: int | None = None) -> dict:231    """Remplit/rafraîchit env_tiles pour toutes les tuiles du parc.232233    `limit` borne le nombre de tuiles téléchargées cette fois-ci (2 requêtes234    Overpass par tuile ; les tuiles fraîches ne coûtent rien).235    """236    con = db.connect()237    client = PoiClient()238    tiles = needed_tiles(con)239    now = time.time()240    done = fetched = failed = 0241    for ty, tx in tiles:242        key = f"{ty},{tx}"243        row = con.execute("SELECT fetched_at FROM env_tiles WHERE tile_key=?",244                          (key,)).fetchone()245        if row is not None and now - row["fetched_at"] < REFRESH_AFTER:246            done += 1247            continue248        if limit is not None and fetched >= limit:249            continue250        data = fetch_tile(client, ty, tx)251        if data is None:252            failed += 1253            print(f"  ✗ tuile {key} : Overpass indisponible")254            continue255        con.execute(256            "INSERT OR REPLACE INTO env_tiles(tile_key, data, fetched_at)"257            " VALUES (?,?,?)", (key, json.dumps(data), time.time()))258        con.commit()259        fetched += 1260        n_lines = sum(len(v) for v in data["lines"].values())261        n_pois = sum(len(v) for v in data["pois"].values())262        print(f"  ✓ tuile {key} : {n_lines} voies, {n_pois} POI")263    con.close()264    return {"tuiles": len(tiles), "fraiches": done, "telechargees": fetched,265            "echecs": failed}266267268def load_tile(con, ty: int, tx: int) -> dict | None:269    row = con.execute("SELECT data FROM env_tiles WHERE tile_key=?",270                      (f"{ty},{tx}",)).fetchone()271    return json.loads(row["data"]) if row else None272
Files main
Menu

Theme