Identite Fuel Advisor, assets locaux et audit economique corrige
Renommage Fuel Advisor (titre, header, favicon SVG/PNG, apple-touch-icon, logo SVG servis localement). Oracle: contrainte de penalty corrigee (portee inversee), quantites non entieres ecartees avant rejeu, double comptage de penalite supprime. Audit economique regenerer: plafonds omniscients coherents et positifs; deux lignes non resolues conservees telles quelles.
This commit is contained in:
214
research/economic_audit/build_audit_report.py
Normal file
214
research/economic_audit/build_audit_report.py
Normal file
@@ -0,0 +1,214 @@
|
||||
"""Rapport construit à partir des seuls résultats réellement exécutés."""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).parent
|
||||
ORDER = [
|
||||
"local",
|
||||
"forced_12",
|
||||
"forced_50",
|
||||
"oracle_no_extra",
|
||||
"oracle_penalized",
|
||||
"oracle_full_bound",
|
||||
"lp_optimistic_ceiling",
|
||||
]
|
||||
LABELS = {
|
||||
"local": "modèle local (anticipation sur hausse)",
|
||||
"forced_12": "contrôle forcé 12 c€/L",
|
||||
"forced_50": "contrôle forcé 50 c€/L",
|
||||
"oracle_no_extra": "oracle J+14 sans passage supplémentaire",
|
||||
"oracle_penalized": "oracle J+14 avec passages supplémentaires pénalisés",
|
||||
"oracle_full_bound": "plafond omniscient (toute la période)",
|
||||
"lp_optimistic_ceiling": "majorant optimiste par relaxation linéaire",
|
||||
}
|
||||
|
||||
|
||||
def money(value):
|
||||
return f"{value:+.2f} €"
|
||||
|
||||
|
||||
def strategy_line(name, entry, days):
|
||||
if "error" in entry:
|
||||
return f"- {LABELS[name]} : **non concluant — {entry['error']}**"
|
||||
if "optimistic_saving" in entry:
|
||||
return (
|
||||
f"- {LABELS[name]} : majorant {money(entry['optimistic_saving'])} "
|
||||
f"({entry['optimistic_saving'] * 365.25 / days:+.2f} €/an) ; "
|
||||
f"{entry['total_visits']:.2f} visites équivalentes dont "
|
||||
f"{entry['fractional_visits']} fractionnaires ; {entry['note']}"
|
||||
)
|
||||
summary, raw = entry["summary"], entry["raw"]
|
||||
line = (
|
||||
f"- {LABELS[name]} : brut {money(summary['gross'])} ; net {money(summary['net'])} ; "
|
||||
f"{summary['eur_per_year']:+.2f} €/an ; prix payé {summary['price_paid']:.4f} €/L ; "
|
||||
f"{summary['passages']} passages ({summary['extra_passages']:+d}) ; "
|
||||
f"volume déplacé {summary['litres_moved']:.2f} L ; détour {summary['detour_km']:.2f} km ; "
|
||||
f"réserve {summary['reserve_ok']} ; confort {summary['comfort_ok']} ; "
|
||||
f"conservation {summary['conservation_error']:.2g} L ; stock final {summary['stock_final']:.4f} L."
|
||||
)
|
||||
if "optimizer_max_gap" in raw:
|
||||
line += (
|
||||
f"\n - solveur : gap maximal {raw['optimizer_max_gap']:.2g}, "
|
||||
f"certifié {raw['optimizer_certified']}, information {raw['information']}."
|
||||
)
|
||||
if raw.get("certificate_note"):
|
||||
line += f" {raw['certificate_note']}."
|
||||
return line
|
||||
|
||||
|
||||
def run():
|
||||
audit = json.loads((ROOT / "signal-audit.json").read_text())
|
||||
economics = json.loads((ROOT / "economic-audit-results.json").read_text())
|
||||
stations = json.loads((ROOT / "station-audit-results.json").read_text())
|
||||
lines = [
|
||||
"# Audit économique — signal, stock, confort, timing et lieu d'achat",
|
||||
"",
|
||||
"Rapport régénéré depuis les seuls fichiers de résultats. Aucun chiffre saisi à la main.",
|
||||
"Aucun score n'est branché au conseil réel. Les rapports `vehicle-simulation.*` antérieurs",
|
||||
"sont supersédés (compteur de signaux hors fenêtre, amplitudes non mûres, confort non imposé,",
|
||||
"carburant des détours absent du stock).",
|
||||
"",
|
||||
"**2024 est diagnostique** : cette année a servi à des validations antérieures.",
|
||||
"Le résultat principal porte sur **2025-01-01 → 2026-08-30**, avec seuil, régime local et",
|
||||
"amplitude gelés avant le 1er janvier 2025. Ce rejeu est rétroactif : ces journées ayant",
|
||||
"déjà été consultées, il ne s'agit pas d'un holdout vierge.",
|
||||
"",
|
||||
"## 1. Couverture réelle du q90 glissant",
|
||||
"",
|
||||
"Le q90 utilise les 730 scores **strictement antérieurs** (minimum 180 scores).",
|
||||
"L'ancien compteur affichait les signaux de tout l'historique, pas ceux de la fenêtre simulée.",
|
||||
"",
|
||||
]
|
||||
for fuel, years in audit.items():
|
||||
lines.append(f"### {fuel}")
|
||||
for year in ("2024", "2025", "2026"):
|
||||
p = years[year]
|
||||
lines.append(
|
||||
f"- **{year}** : {p['signals']} jours signalés sur {p['evaluable']} évaluables "
|
||||
f"= **{100 * p['coverage']:.2f} %** ; score médian {p['score_median']:.6f} ; "
|
||||
f"q90 médian {p['q90_median']:.6f}, min {p['q90_min']:.6f}, "
|
||||
f"max {p['q90_max']:.6f}."
|
||||
)
|
||||
lines.append("")
|
||||
lines.append("Dates encadrant les changements brusques de couverture (score / seuil / signal) :")
|
||||
for transition in years["transitions"]:
|
||||
lines.append(f"- autour du {transition['date']} :")
|
||||
for p in transition["surrounding"]:
|
||||
lines.append(f" - {p['t']} : {p['score']:.6f} / {p['threshold']:.6f} / {p['fired']}")
|
||||
lines.append("")
|
||||
lines += [
|
||||
"## 2. Amplitudes : nomenclature et gel",
|
||||
"",
|
||||
"- `expected_amplitude_all_signals` : moyenne des maxima de hausse des 730 signaux antérieurs,",
|
||||
" **succès et échecs inclus**, uniquement parmi les cibles déjà mûres (`available_at < t`).",
|
||||
"- `median_amplitude_all_signals` : médiane du même ensemble, utilisée dans le rapport",
|
||||
" `vehicle-simulation`.",
|
||||
"- `amplitude_when_event_occurs` : moyenne conditionnelle aux succès, **diagnostique seulement**.",
|
||||
"",
|
||||
"L'affirmation « moyenne optimiste ~12 c€/L » est retirée : ce nombre conditionné au succès",
|
||||
"n'est pas exploitable par un moteur de décision, et l'utiliser aurait surévalué le gain",
|
||||
"d'un facteur trois à quatre. Le maximum futur n'est lui-même pas une économie garantie.",
|
||||
"",
|
||||
]
|
||||
for entry in economics["results"]:
|
||||
if entry["period"] != "frozen_2025_2026":
|
||||
continue
|
||||
freeze = entry["freeze"]
|
||||
lines.append(
|
||||
f"- {entry['profile']} : seuil gelé {freeze['threshold']:.6f} ; amplitude attendue "
|
||||
f"tous signaux {freeze['expected_amplitude_all_signals']:.4f} c€/L ; "
|
||||
f"{freeze['signal_history']} antécédents ; dernier label mûr utilisé "
|
||||
f"{freeze['training_available_at_max']} ; dernier score du seuil "
|
||||
f"{freeze['threshold_source_max']}."
|
||||
)
|
||||
lines += [
|
||||
"",
|
||||
"**Limite reconnue** : c'est la première cause du « zéro anticipation » des rapports",
|
||||
"précédents. Un estimateur plus généreux du gain ne peut venir que d'une meilleure",
|
||||
"prévision, jamais d'une statistique conditionnée au succès.",
|
||||
"",
|
||||
"## 3. Timing : contraintes réelles et garanties comptables",
|
||||
"",
|
||||
"Contraintes appliquées à **tous** les bras : consommation identique, réservoir nominal plein",
|
||||
"au départ, réserve par profil, capacité vérifiée au remplissage, minimum 3 jours entre",
|
||||
"visites, maximum 8 visites par mois calendaire, achat minimum 10 L, carburant des détours",
|
||||
"réellement consommé. Une contrainte infaisable lève une erreur : rien n'est contourné en",
|
||||
"silence. **Le plein est limité à la capacité nominale** (l'ancien banc utilisait 80 % du",
|
||||
"réservoir) — changement commun à tous les bras, sans quoi la comparaison était biaisée.",
|
||||
"",
|
||||
"Conservation vérifiée à 1e-7 L : `achats = consommation normale + détours + stock final − stock initial`.",
|
||||
"Coût comparable = achats + (stock initial − stock final) valorisé au **même prix de début**",
|
||||
"pour les deux bras. Le minimum d'achat peut laisser davantage de stock terminal : ce n'est",
|
||||
"ni une économie ni une dépense perdue. Pénalité = 3 € × passages au-delà de la référence,",
|
||||
"en plus du carburant des détours. Le local ne peut qu'**anticiper une hausse**, jamais",
|
||||
"différer un achat sur une baisse annoncée.",
|
||||
"",
|
||||
]
|
||||
for entry in economics["results"]:
|
||||
baseline = entry["baseline"]
|
||||
lines.append(f"### {entry['period']} — {entry['profile']} ({entry['days']} jours)")
|
||||
lines.append(
|
||||
f"- référence : achats {baseline['cash']:.2f} € ; coût ajusté du stock "
|
||||
f"{baseline['stock_adjusted_cost']:.2f} € ; prix payé {baseline['price_paid']:.4f} €/L ; "
|
||||
f"{baseline['passages']} passages ; {baseline['litres']:.2f} L achetés ; "
|
||||
f"{baseline['consumed']:.2f} L consommés ; stock {baseline['stock_initial']:.4f} → "
|
||||
f"{baseline['stock_final']:.4f} L."
|
||||
)
|
||||
for name in ORDER:
|
||||
if name in entry["strategies"]:
|
||||
lines.append(strategy_line(name, entry["strategies"][name], entry["days"]))
|
||||
lines.append("")
|
||||
lines += [
|
||||
"### Comment lire ces oracles",
|
||||
"",
|
||||
"- L'**oracle J+14** ne connaît que les prix de J à J+14 et garde le planning ainsi que le",
|
||||
" stock terminal de la référence hors de la fenêtre : c'est un gain **réalisable mais",
|
||||
" restreint**, jamais un plafond global.",
|
||||
"- Le **plafond omniscient** connaît toute la période et conserve le stock final de la",
|
||||
" référence. Il ne vaut comme borne que si le solveur certifie l'optimalité ; la note de",
|
||||
" certification est écrite à côté de chaque ligne.",
|
||||
"- Le **majorant optimiste** autorise des visites fractionnaires : c'est une borne supérieure",
|
||||
" du gain, pas un gain atteignable.",
|
||||
"",
|
||||
"## 4. Valeur du lieu d'achat (vrais prix par station)",
|
||||
"",
|
||||
"Origine `fav:1` (Villenave-d'Ornon). Deux politiques, calendrier et autonomie identiques :",
|
||||
"station **la plus proche disponible ce jour** contre station **la moins chère nette du",
|
||||
"carburant du détour**, parmi les stations disposant d'une route OSRM réelle (≤ 20 km A/R).",
|
||||
"Les distances sont celles du cache actuel appliquées rétrospectivement : réseau routier",
|
||||
"supposé stable, aller-retour approximé à deux fois l'aller, sans trafic. Ce n'est ni un",
|
||||
"détour sur trajet habituel, ni une recherche exhaustive, ni un plafond universel.",
|
||||
"",
|
||||
]
|
||||
for entry in stations["results"]:
|
||||
summary, base, best = entry["summary"], entry["baseline"], entry["best"]
|
||||
lines.append(
|
||||
f"- {entry['profile']} : net {money(summary['net'])} "
|
||||
f"({summary['eur_per_year']:+.2f} €/an) ; prix payé {base['price_paid']:.4f} → "
|
||||
f"{best['price_paid']:.4f} €/L ; passages {base['passages']} → {best['passages']} ; "
|
||||
f"routes {base['detour_km']:.2f} → {best['detour_km']:.2f} km ; réserve/confort "
|
||||
f"{best['reserve_ok']}/{best['comfort_ok']} ; conservation "
|
||||
f"{best['conservation_error']:.2g} L."
|
||||
)
|
||||
lines += [
|
||||
"",
|
||||
"## 5. Portée et limites",
|
||||
"",
|
||||
"- Gains de **lieu** et de **timing** mesurés séparément : ils ne s'additionnent pas.",
|
||||
"- Un oracle **restreint** qui rapporte peu ne prouve pas que le problème vaut peu :",
|
||||
" il prouve seulement que cette politique-là ne capte pas grand-chose.",
|
||||
"- Le plafond omniscient borne le timing **sous ces profils et ces contraintes**, pas pour",
|
||||
" tous les usages possibles.",
|
||||
"- Aucune de ces valeurs n'est une validation de production, ni un conseil d'achat : le",
|
||||
" conseil réel reste autonomie, réserve et prix local, sans prévision.",
|
||||
"",
|
||||
]
|
||||
(ROOT / "ECONOMIC_AUDIT_REPORT.md").write_text("\n".join(lines) + "\n")
|
||||
print(
|
||||
"rapport écrit", len(economics["results"]), "profils/périodes ;", len(economics["failures"]), "échecs"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run()
|
||||
134
research/economic_audit/economic_engine.py
Normal file
134
research/economic_audit/economic_engine.py
Normal file
@@ -0,0 +1,134 @@
|
||||
"""Audit offline : stock commun, optimisation MILP avec futur limité à J+14.
|
||||
Dépendances recherche uniquement : scipy/numpy. Jamais importé par l'application.
|
||||
"""
|
||||
|
||||
from collections import Counter
|
||||
|
||||
import numpy as np
|
||||
|
||||
MIN_INTERVAL = 3
|
||||
MONTH_CAP = 8
|
||||
PENALTY = 3.0
|
||||
|
||||
|
||||
def demand(vehicle, days):
|
||||
return (
|
||||
np.array(
|
||||
[
|
||||
(vehicle.get("trip_km", 400) if i % vehicle.get("trip_interval_days", 15) == 0 else 0)
|
||||
if vehicle.get("usage") == "occasional"
|
||||
else vehicle["monthly_km"] / 30.4375
|
||||
for i in range(len(days))
|
||||
]
|
||||
)
|
||||
* vehicle["consumption"]
|
||||
/ 100
|
||||
)
|
||||
|
||||
|
||||
def simulate(days, prices, vehicle, mode="baseline", forecasts=None, detour_km=4.0, budget=None):
|
||||
use = demand(vehicle, days)
|
||||
cap = vehicle["tank_liters"]
|
||||
reserve = vehicle["min_range_km"] * vehicle["consumption"] / 100
|
||||
detour_l = detour_km * vehicle["consumption"] / 100
|
||||
initial = cap
|
||||
stock = initial
|
||||
visits = []
|
||||
purchases = []
|
||||
levels = []
|
||||
consumed = 0.0
|
||||
cash = 0.0
|
||||
for i, day in enumerate(days):
|
||||
remaining = float(sum(use[i:]))
|
||||
allowed = (not visits or i - visits[-1] >= MIN_INTERVAL) and sum(
|
||||
days[j][:7] == day[:7] for j in visits
|
||||
) < MONTH_CAP
|
||||
# Besoin préventif si la prochaine occasion autorisée serait trop tardive.
|
||||
need = stock < reserve + use[i] + detour_l / 2 + 1e-9 and stock < reserve + remaining - 1e-7
|
||||
q = 0.0
|
||||
if mode == "scheduled":
|
||||
q = (forecasts or {}).get(day, 0)
|
||||
else:
|
||||
signal = (forecasts or {}).get(day, 0)
|
||||
addable = cap - stock + detour_l
|
||||
advance = (
|
||||
signal > 0
|
||||
and addable * signal / 100
|
||||
>= vehicle.get("min_gain_eur", 1.5) + PENALTY + detour_l * prices[i]
|
||||
)
|
||||
if allowed and (need or advance):
|
||||
q = max(0, min(cap - stock + detour_l / 2, max(10, remaining + reserve - stock + detour_l)))
|
||||
if q < 10 - 1e-7:
|
||||
q = 0
|
||||
if q > 1e-6:
|
||||
if not allowed:
|
||||
raise ValueError("Confort violé")
|
||||
# L'aller est consommé avant remplissage, le retour ensuite.
|
||||
if stock - detour_l / 2 < reserve - 1e-6:
|
||||
raise ValueError("Réserve sur aller station")
|
||||
if stock + q - detour_l / 2 > cap + 1e-6:
|
||||
raise ValueError("Capacité au remplissage")
|
||||
stock += q - detour_l
|
||||
cash += q * prices[i]
|
||||
consumed += detour_l
|
||||
visits.append(i)
|
||||
purchases.append(dict(day=day, litres=q, price=prices[i]))
|
||||
stock -= use[i]
|
||||
consumed += use[i]
|
||||
levels.append(stock)
|
||||
if stock < reserve - 1e-6:
|
||||
raise ValueError("Réserve violée")
|
||||
bought = sum(p["litres"] for p in purchases)
|
||||
error = bought - consumed - stock + initial
|
||||
assert abs(error) < 1e-7
|
||||
return dict(
|
||||
cash=cash,
|
||||
stock_adjusted_cost=cash + (initial - stock) * prices[0],
|
||||
litres=bought,
|
||||
consumed=consumed,
|
||||
stock_initial=initial,
|
||||
stock_final=stock,
|
||||
conservation_error=error,
|
||||
price_paid=cash / bought if bought else None,
|
||||
passages=len(visits),
|
||||
visits=visits,
|
||||
purchases=purchases,
|
||||
levels=levels,
|
||||
detour_km=len(visits) * detour_km,
|
||||
reserve_ok=bool(min(levels) >= reserve - 1e-6),
|
||||
comfort_ok=all(b - a >= MIN_INTERVAL for a, b in zip(visits, visits[1:], strict=False))
|
||||
and max(Counter(days[j][:7] for j in visits).values(), default=0) <= MONTH_CAP,
|
||||
)
|
||||
|
||||
|
||||
def compare(base, run, days, penalty_included=False):
|
||||
"""`penalty_included=True` pour les plans d'oracle : leur objectif a déjà facturé
|
||||
les passages supplémentaires, la repayer ici compterait la pénalité deux fois."""
|
||||
extra = run["passages"] - base["passages"]
|
||||
gross = base["stock_adjusted_cost"] - run["stock_adjusted_cost"]
|
||||
net = gross if penalty_included else gross - max(0, extra) * PENALTY
|
||||
b = {p["day"]: p["litres"] for p in base["purchases"]}
|
||||
r = {p["day"]: p["litres"] for p in run["purchases"]}
|
||||
# Volume réaffecté entre dates ; exclut l'écart de volume total acheté.
|
||||
moved = (
|
||||
sum(abs(b.get(d, 0) - r.get(d, 0)) for d in set(b) | set(r)) - abs(base["litres"] - run["litres"])
|
||||
) / 2
|
||||
return dict(
|
||||
gross=gross,
|
||||
net=net,
|
||||
eur_per_year=net * 365.25 / len(days),
|
||||
extra_passages=extra,
|
||||
litres_moved=max(0, moved),
|
||||
**{
|
||||
k: run[k]
|
||||
for k in (
|
||||
"price_paid",
|
||||
"passages",
|
||||
"stock_final",
|
||||
"conservation_error",
|
||||
"reserve_ok",
|
||||
"comfort_ok",
|
||||
"detour_km",
|
||||
)
|
||||
},
|
||||
)
|
||||
41
research/economic_audit/export_economic.py
Normal file
41
research/economic_audit/export_economic.py
Normal file
@@ -0,0 +1,41 @@
|
||||
"""Export prix et routage observés pour audit offline, aucun secret."""
|
||||
|
||||
import json
|
||||
import sqlite3
|
||||
from pathlib import Path
|
||||
|
||||
from clean_backtest import states_for
|
||||
from validation import VEHICLE_PROFILES
|
||||
|
||||
c = sqlite3.connect("/var/lib/fuel-advisor/fuel.sqlite3")
|
||||
c.row_factory = sqlite3.Row
|
||||
routes = [
|
||||
dict(r)
|
||||
for r in c.execute(
|
||||
"SELECT * FROM route_cache WHERE origin_lat=? AND origin_lon=? AND provider=?",
|
||||
(44.7737872, -0.5595029, "osrm"),
|
||||
)
|
||||
]
|
||||
stations = [dict(r) for r in c.execute("SELECT id,lat,lon FROM stations")]
|
||||
by_id = {}
|
||||
for s in stations:
|
||||
if s["lat"] is None:
|
||||
continue
|
||||
candidates = [
|
||||
r
|
||||
for r in routes
|
||||
if abs(r["target_lat"] - s["lat"]) < 0.0001 and abs(r["target_lon"] - s["lon"]) < 0.0001
|
||||
]
|
||||
if candidates:
|
||||
r = max(candidates, key=lambda r: r["computed_at"])
|
||||
by_id[s["id"]] = dict(roundtrip_km=2 * r["distance_m"] / 1000, computed_at=r["computed_at"])
|
||||
out = dict(profiles=VEHICLE_PROFILES, routes=by_id, origin="fav:1", fuels={})
|
||||
for fuel in ("Gazole", "SP95"):
|
||||
states = states_for(fuel)
|
||||
out["fuels"][fuel] = [
|
||||
dict(day=k, prices=v["prices"])
|
||||
for k, v in sorted(states.items())
|
||||
if "2024-01-01" <= k <= "2026-09-13"
|
||||
]
|
||||
Path("reports/economic-inputs.json").write_text(json.dumps(out))
|
||||
print("routes", len(by_id), "days", {f: len(v) for f, v in out["fuels"].items()})
|
||||
46
research/economic_audit/repair_failed.py
Normal file
46
research/economic_audit/repair_failed.py
Normal file
@@ -0,0 +1,46 @@
|
||||
"""Rejoue uniquement les deux lignes échouées, sans retoucher les autres résultats."""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from economic_engine import compare, simulate
|
||||
from timing_oracle import oracle
|
||||
|
||||
ROOT = Path(__file__).parent
|
||||
TARGETS = [
|
||||
("petit_reservoir", "oracle_penalized", dict(noextra=False)),
|
||||
("van_occasionnel", "oracle_full_bound", dict(full=True, limit=600)),
|
||||
]
|
||||
|
||||
|
||||
def run():
|
||||
data = json.loads((ROOT / "economic-inputs.json").read_text())
|
||||
report = json.loads((ROOT / "economic-audit-results.json").read_text())
|
||||
for profile, name, kwargs in TARGETS:
|
||||
vehicle = data["profiles"][profile]
|
||||
points = [p for p in data["fuels"][vehicle["fuel"]] if "2025-01-01" <= p["day"] <= "2026-08-30"]
|
||||
days = [p["day"] for p in points]
|
||||
prices = [sorted(p["prices"].values())[len(p["prices"]) // 2] for p in points]
|
||||
base = simulate(days, prices, vehicle)
|
||||
entry = next(
|
||||
e for e in report["results"] if e["profile"] == profile and e["period"] == "frozen_2025_2026"
|
||||
)
|
||||
try:
|
||||
result = oracle(days, prices, vehicle, base, **kwargs)
|
||||
entry["strategies"][name] = {
|
||||
"summary": compare(base, result, days, penalty_included=True),
|
||||
"raw": result,
|
||||
"penalty_included": True,
|
||||
}
|
||||
print(profile, name, entry["strategies"][name]["summary"], flush=True)
|
||||
except ValueError as exc:
|
||||
entry["strategies"][name] = {"error": str(exc)}
|
||||
print("FAILED", profile, name, exc, flush=True)
|
||||
report["failures"] = [f for f in report["failures"] if not (f[1] == profile and f[2] == name)]
|
||||
if "error" in entry["strategies"][name]:
|
||||
report["failures"].append(["frozen_2025_2026", profile, name, entry["strategies"][name]["error"]])
|
||||
(ROOT / "economic-audit-results.json").write_text(json.dumps(report, indent=1))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run()
|
||||
4
research/economic_audit/requirements-research.txt
Normal file
4
research/economic_audit/requirements-research.txt
Normal file
@@ -0,0 +1,4 @@
|
||||
numpy==2.5.3
|
||||
scipy==1.18.1
|
||||
pytest==9.1.1
|
||||
ruff==0.16.7
|
||||
119
research/economic_audit/run_economic_audit.py
Normal file
119
research/economic_audit/run_economic_audit.py
Normal file
@@ -0,0 +1,119 @@
|
||||
"""Campagne d'audit économique. Règles et modes écrits avant lecture des nouveaux résultats."""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from statistics import fmean
|
||||
|
||||
from economic_engine import compare, simulate
|
||||
from timing_oracle import lp_ceiling, oracle
|
||||
|
||||
from signal_audit import quantile
|
||||
|
||||
ROOT = Path(__file__).parent
|
||||
PERIODS = [("2024-01-01", "2024-12-31", "diagnostic_2024"), ("2025-01-01", "2026-08-30", "frozen_2025_2026")]
|
||||
FORCED = [("forced_12", 12.0), ("forced_50", 50.0)]
|
||||
|
||||
|
||||
def frozen_forecasts(fuel, cutoff):
|
||||
"""Paramètres gelés avant `cutoff` : q90, régime local et amplitude attendue."""
|
||||
rows = json.loads((ROOT / f"audit-rows-{fuel}.json").read_text())
|
||||
points = json.loads((ROOT / f"audit-signals-{fuel}.json").read_text())
|
||||
past = [p for p in points if p["t"] < cutoff][-730:]
|
||||
threshold = quantile([p["score"] for p in past])
|
||||
mature = [r for r in rows if r["target"]["available_at"] < cutoff]
|
||||
fired = {p["t"] for p in points if p["t"] < cutoff and p["fired"]}
|
||||
amplitudes = [r["target"]["future_max_delta"] for r in mature if r["t"] in fired][-730:]
|
||||
expected = fmean(amplitudes)
|
||||
base = (sum(r["target"]["events"]["up_3"]["hit"] for r in mature) + 1) / (len(mature) + 2)
|
||||
|
||||
def local(group):
|
||||
group_rows = [r for r in mature if r["regime"] == group]
|
||||
return (sum(r["target"]["events"]["up_3"]["hit"] for r in group_rows) + 30 * base) / (
|
||||
len(group_rows) + 30
|
||||
)
|
||||
|
||||
scores = {tuple(r["regime"]): local(r["regime"]) for r in mature}
|
||||
out = {
|
||||
r["t"]: expected if scores.get(tuple(r["regime"]), 0) >= threshold else 0
|
||||
for r in rows
|
||||
if r["t"] >= cutoff
|
||||
}
|
||||
freeze = dict(
|
||||
cutoff=cutoff,
|
||||
threshold=threshold,
|
||||
expected_amplitude_all_signals=expected,
|
||||
signal_history=len(amplitudes),
|
||||
training_available_at_max=max(r["target"]["available_at"] for r in mature),
|
||||
threshold_source_max=past[-1]["t"],
|
||||
note="paramètres gelés avant la période évaluée, features as-of",
|
||||
)
|
||||
return out, freeze
|
||||
|
||||
|
||||
def run():
|
||||
data = json.loads((ROOT / "economic-inputs.json").read_text())
|
||||
report = {"status": "offline_audit", "results": [], "failures": []}
|
||||
for start, end, label in PERIODS:
|
||||
for key, vehicle in data["profiles"].items():
|
||||
points = [p for p in data["fuels"][vehicle["fuel"]] if start <= p["day"] <= end]
|
||||
days = [p["day"] for p in points]
|
||||
prices = [sorted(p["prices"].values())[len(p["prices"]) // 2] for p in points]
|
||||
forecasts, freeze = frozen_forecasts(vehicle["fuel"], start)
|
||||
base = simulate(days, prices, vehicle)
|
||||
entry = {
|
||||
"profile": key,
|
||||
"period": label,
|
||||
"days": len(days),
|
||||
"freeze": freeze,
|
||||
"baseline": base,
|
||||
"strategies": {},
|
||||
}
|
||||
modes = [
|
||||
("local", forecasts, False),
|
||||
*[(name, {d: c for d in days}, False) for name, c in FORCED],
|
||||
("oracle_no_extra", None, True),
|
||||
("oracle_penalized", None, True),
|
||||
]
|
||||
for name, signals, is_oracle in modes:
|
||||
try:
|
||||
if is_oracle:
|
||||
result = oracle(days, prices, vehicle, base, noextra=name == "oracle_no_extra")
|
||||
else:
|
||||
result = simulate(days, prices, vehicle, "local", signals)
|
||||
entry["strategies"][name] = {
|
||||
"summary": compare(base, result, days, penalty_included=is_oracle),
|
||||
"raw": result,
|
||||
"penalty_included": is_oracle,
|
||||
}
|
||||
print(label, key, name, entry["strategies"][name]["summary"], flush=True)
|
||||
except ValueError as exc:
|
||||
entry["strategies"][name] = {"error": str(exc)}
|
||||
report["failures"].append([label, key, name, str(exc)])
|
||||
print("FAILED", label, key, name, exc, flush=True)
|
||||
if label == "frozen_2025_2026":
|
||||
for name, kwargs in (
|
||||
("oracle_full_bound", {"full": True, "limit": 240}),
|
||||
("lp_optimistic_ceiling", None),
|
||||
):
|
||||
try:
|
||||
if kwargs:
|
||||
result = oracle(days, prices, vehicle, base, **kwargs)
|
||||
entry["strategies"][name] = {
|
||||
"summary": compare(base, result, days, penalty_included=True),
|
||||
"raw": result,
|
||||
"penalty_included": True,
|
||||
}
|
||||
else:
|
||||
entry["strategies"][name] = lp_ceiling(days, prices, vehicle, base)
|
||||
print(label, key, name, entry["strategies"][name], flush=True)
|
||||
except ValueError as exc:
|
||||
entry["strategies"][name] = {"error": str(exc)}
|
||||
report["failures"].append([label, key, name, str(exc)])
|
||||
print("FAILED", label, key, name, exc, flush=True)
|
||||
report["results"].append(entry)
|
||||
(ROOT / "economic-audit-results.json").write_text(json.dumps(report, indent=1))
|
||||
(ROOT / "economic-audit-results.json").write_text(json.dumps(report, indent=1))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run()
|
||||
97
research/economic_audit/signal_audit.py
Normal file
97
research/economic_audit/signal_audit.py
Normal file
@@ -0,0 +1,97 @@
|
||||
"""Audit offline : seuil strictement passé et amplitudes de cibles mûres seulement."""
|
||||
|
||||
import json
|
||||
import math
|
||||
from collections import deque
|
||||
from pathlib import Path
|
||||
from statistics import fmean, median
|
||||
|
||||
|
||||
def quantile(values):
|
||||
ordered = sorted(values)
|
||||
return ordered[min(len(ordered) - 1, math.ceil(0.9 * (len(ordered) - 1)))]
|
||||
|
||||
|
||||
def audit_rows(rows, key="up_3", minimum=180, window=730):
|
||||
history, pending, matured, out = [], deque(), [], []
|
||||
for row in rows:
|
||||
t = row["t"]
|
||||
while pending and pending[0]["target"]["available_at"] < t:
|
||||
matured.append(pending.popleft())
|
||||
score = row["score"][key]
|
||||
if len(history) >= minimum:
|
||||
past = history[-window:]
|
||||
assert past[-1][0] < t
|
||||
threshold = quantile([v for _, v in past])
|
||||
fired = score >= threshold
|
||||
recent = matured[-window:]
|
||||
all_values = [r["target"]["future_max_delta"] for r in recent]
|
||||
hits = [r["target"]["future_max_delta"] for r in recent if r["target"]["events"][key]["hit"]]
|
||||
out.append(
|
||||
dict(
|
||||
t=t,
|
||||
score=score,
|
||||
threshold=threshold,
|
||||
fired=fired,
|
||||
threshold_source_max=past[-1][0],
|
||||
expected_amplitude_all_signals=fmean(all_values) if len(recent) >= 20 else None,
|
||||
median_amplitude_all_signals=median(all_values) if len(recent) >= 20 else None,
|
||||
amplitude_when_event_occurs=fmean(hits) if hits else None,
|
||||
amplitude_source_max=max((r["target"]["available_at"] for r in recent), default=None),
|
||||
amplitude_sample=len(recent),
|
||||
)
|
||||
)
|
||||
if fired:
|
||||
pending.append(row)
|
||||
history.append((t, score))
|
||||
return out
|
||||
|
||||
|
||||
def summarize(points):
|
||||
result = {}
|
||||
for year in ("2024", "2025", "2026"):
|
||||
group = [p for p in points if p["t"].startswith(year) and p["t"] <= "2026-08-30"]
|
||||
thresholds = [p["threshold"] for p in group]
|
||||
result[year] = dict(
|
||||
evaluable=len(group),
|
||||
signals=sum(p["fired"] for p in group),
|
||||
coverage=fmean(p["fired"] for p in group),
|
||||
score_median=median(p["score"] for p in group),
|
||||
q90_median=median(thresholds),
|
||||
q90_min=min(thresholds),
|
||||
q90_max=max(thresholds),
|
||||
)
|
||||
changes = []
|
||||
for i in range(28, len(points) - 28):
|
||||
p = points[i]
|
||||
if not "2024-01-01" <= p["t"] <= "2026-08-02":
|
||||
continue
|
||||
before = fmean(x["fired"] for x in points[i - 28 : i])
|
||||
after = fmean(x["fired"] for x in points[i : i + 28])
|
||||
changes.append((abs(after - before), i, before, after))
|
||||
selected = []
|
||||
for _delta, i, _before, _after in sorted(changes, reverse=True):
|
||||
if all(abs(i - j) >= 56 for j in selected):
|
||||
selected.append(i)
|
||||
if len(selected) == 3:
|
||||
break
|
||||
result["transitions"] = [dict(date=points[i]["t"], surrounding=points[i - 2 : i + 3]) for i in selected]
|
||||
return result
|
||||
|
||||
|
||||
def run():
|
||||
from enrich_campaign import local_rows
|
||||
|
||||
out = {}
|
||||
for fuel in ("Gazole", "SP95", "E10"):
|
||||
rows = local_rows(fuel, 14)
|
||||
points = audit_rows(rows)
|
||||
Path(f"reports/audit-rows-{fuel}.json").write_text(json.dumps(rows))
|
||||
Path(f"reports/audit-signals-{fuel}.json").write_text(json.dumps(points))
|
||||
out[fuel] = summarize(points)
|
||||
print(fuel, json.dumps(out[fuel], ensure_ascii=False), flush=True)
|
||||
Path("reports/signal-audit.json").write_text(json.dumps(out, ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run()
|
||||
110
research/economic_audit/station_audit.py
Normal file
110
research/economic_audit/station_audit.py
Normal file
@@ -0,0 +1,110 @@
|
||||
"""Valeur du lieu d'achat : vrais prix et routes OSRM existantes, aucun prix futur."""
|
||||
|
||||
import json
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
|
||||
from economic_engine import compare, demand
|
||||
|
||||
ROOT = Path(__file__).parent
|
||||
|
||||
|
||||
def station_run(points, vehicle, routes, best=False):
|
||||
days = [p["day"] for p in points]
|
||||
use = demand(vehicle, days)
|
||||
cap = vehicle["tank_liters"]
|
||||
reserve = vehicle["min_range_km"] * vehicle["consumption"] / 100
|
||||
nearby = {s: r for s, r in routes.items() if r["roundtrip_km"] <= 20}
|
||||
maxdetour = max(r["roundtrip_km"] for r in nearby.values()) * vehicle["consumption"] / 100
|
||||
target = cap - maxdetour / 2
|
||||
stock = cap
|
||||
cash = 0.0
|
||||
consumed = 0.0
|
||||
detours = 0.0
|
||||
visits = []
|
||||
purchases = []
|
||||
levels = []
|
||||
for i, p in enumerate(points):
|
||||
remaining = float(sum(use[i:]))
|
||||
need = stock < reserve + use[i] + maxdetour / 2 + 1e-9 and stock < reserve + remaining - 1e-7
|
||||
if need:
|
||||
if visits and i - visits[-1] < 3:
|
||||
raise ValueError("Confort intervalle")
|
||||
if sum(days[j][:7] == days[i][:7] for j in visits) >= 8:
|
||||
raise ValueError("Confort mensuel")
|
||||
candidates = []
|
||||
for sid, price in p["prices"].items():
|
||||
if sid not in nearby:
|
||||
continue
|
||||
km = nearby[sid]["roundtrip_km"]
|
||||
dl = km * vehicle["consumption"] / 100
|
||||
q = max(10, min(target, remaining + reserve) - stock + dl)
|
||||
if stock - dl / 2 < reserve - 1e-7 or stock + q - dl / 2 > cap + 1e-7:
|
||||
continue
|
||||
candidates.append((q * price, km, sid, q, price, dl))
|
||||
if not candidates:
|
||||
raise ValueError("Aucune station routée accessible à " + days[i])
|
||||
cost, km, sid, q, price, dl = min(candidates, key=(lambda x: x[0]) if best else (lambda x: x[1]))
|
||||
if q > 1e-6:
|
||||
stock += q - dl
|
||||
consumed += dl
|
||||
cash += cost
|
||||
detours += km
|
||||
purchases.append(dict(day=days[i], litres=q, price=price, station_id=sid, route_km=km))
|
||||
visits.append(i)
|
||||
stock -= use[i]
|
||||
consumed += use[i]
|
||||
levels.append(stock)
|
||||
if stock < reserve - 1e-7:
|
||||
raise ValueError("Réserve")
|
||||
bought = sum(p["litres"] for p in purchases)
|
||||
error = bought - consumed - stock + cap
|
||||
assert abs(error) < 1e-7
|
||||
# Même valorisation terminale pour les deux bras : prix de la plus proche au début.
|
||||
first = points[0]["prices"]
|
||||
closest = min((s for s in nearby if s in first), key=lambda s: nearby[s]["roundtrip_km"])
|
||||
return dict(
|
||||
cash=cash,
|
||||
stock_adjusted_cost=cash + (cap - stock) * first[closest],
|
||||
stock_initial=cap,
|
||||
stock_final=stock,
|
||||
litres=bought,
|
||||
consumed=consumed,
|
||||
conservation_error=error,
|
||||
price_paid=cash / bought,
|
||||
passages=len(visits),
|
||||
visits=visits,
|
||||
purchases=purchases,
|
||||
levels=levels,
|
||||
detour_km=detours,
|
||||
reserve_ok=bool(min(levels) >= reserve - 1e-7),
|
||||
comfort_ok=all(b - a >= 3 for a, b in zip(visits, visits[1:], strict=False))
|
||||
and max(Counter(days[i][:7] for i in visits).values(), default=0) <= 8,
|
||||
)
|
||||
|
||||
|
||||
def run():
|
||||
data = json.loads((ROOT / "economic-inputs.json").read_text())
|
||||
result = []
|
||||
for key, v in data["profiles"].items():
|
||||
points = [p for p in data["fuels"][v["fuel"]] if "2025-01-01" <= p["day"] <= "2026-08-30"]
|
||||
base = station_run(points, v, data["routes"])
|
||||
best = station_run(points, v, data["routes"], True)
|
||||
summary = compare(base, best, [p["day"] for p in points])
|
||||
result.append(dict(profile=key, baseline=base, best=best, summary=summary))
|
||||
print(key, summary, flush=True)
|
||||
(ROOT / "station-audit-results.json").write_text(
|
||||
json.dumps(
|
||||
dict(
|
||||
origin="fav:1",
|
||||
max_roundtrip_km=20,
|
||||
routes="OSRM actuelles appliquées rétrospectivement, hypothèse réseau routier stable ; aller-retour = 2 × aller, pas trafic",
|
||||
results=result,
|
||||
),
|
||||
indent=1,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run()
|
||||
50
research/economic_audit/test_economic_audit.py
Normal file
50
research/economic_audit/test_economic_audit.py
Normal file
@@ -0,0 +1,50 @@
|
||||
from datetime import date, timedelta
|
||||
|
||||
import pytest
|
||||
from economic_engine import simulate
|
||||
|
||||
from signal_audit import audit_rows
|
||||
|
||||
|
||||
def test_maturation_and_strict_threshold():
|
||||
rows = [
|
||||
dict(
|
||||
t=(date(2020, 1, 1) + timedelta(days=i)).isoformat(),
|
||||
score={"up_3": 0.2},
|
||||
target=dict(
|
||||
available_at=(date(2020, 1, 1) + timedelta(days=i + 15)).isoformat(),
|
||||
future_max_delta=100 + i,
|
||||
events={"up_3": {"hit": True}},
|
||||
),
|
||||
)
|
||||
for i in range(60)
|
||||
]
|
||||
a = audit_rows(rows, minimum=2)
|
||||
for p in a:
|
||||
assert p["threshold_source_max"] < p["t"]
|
||||
assert p["amplitude_source_max"] is None or p["amplitude_source_max"] < p["t"]
|
||||
before = [p for p in a if p["t"] <= "2020-02-01"]
|
||||
for r in rows:
|
||||
if r["target"]["available_at"] >= "2020-02-01":
|
||||
r["target"]["future_max_delta"] = 999999
|
||||
assert before == [p for p in audit_rows(rows, minimum=2) if p["t"] <= "2020-02-01"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mode", ["baseline", "local"])
|
||||
def test_stock_and_comfort(mode):
|
||||
days = [(date(2025, 1, 1) + timedelta(days=i)).isoformat() for i in range(35)]
|
||||
v = dict(tank_liters=40, consumption=6, min_range_km=50, monthly_km=1500, min_gain_eur=1)
|
||||
prices = [1.8 + i * 0.003 for i in range(35)]
|
||||
b = simulate(days, prices, v)
|
||||
r = simulate(
|
||||
days,
|
||||
prices,
|
||||
v,
|
||||
mode,
|
||||
{d: 50 for d in days},
|
||||
budget=b["passages"] if mode == "oracle_no_extra" else None,
|
||||
)
|
||||
assert r["conservation_error"] == pytest.approx(0, abs=1e-7)
|
||||
assert r["reserve_ok"] and r["comfort_ok"]
|
||||
if mode == "oracle_no_extra":
|
||||
assert r["passages"] <= b["passages"]
|
||||
45
research/economic_audit/test_signal_maturity.py
Normal file
45
research/economic_audit/test_signal_maturity.py
Normal file
@@ -0,0 +1,45 @@
|
||||
from datetime import date, timedelta
|
||||
|
||||
from signal_audit import audit_rows
|
||||
|
||||
|
||||
def test_q90_uses_only_strictly_previous_scores():
|
||||
rows = []
|
||||
for i in range(80):
|
||||
rows.append(
|
||||
dict(
|
||||
t=(date(2020, 1, 1) + timedelta(days=i)).isoformat(),
|
||||
score={"up_3": float(i)},
|
||||
target=dict(
|
||||
available_at=(date(2020, 1, 1) + timedelta(days=i + 15)).isoformat(),
|
||||
future_max_delta=i,
|
||||
events={"up_3": {"hit": i >= 3}},
|
||||
),
|
||||
)
|
||||
)
|
||||
result = audit_rows(rows, minimum=2)
|
||||
assert all(p["threshold_source_max"] < p["t"] for p in result)
|
||||
assert all(p["threshold"] < p["score"] for p in result)
|
||||
|
||||
|
||||
def test_immature_future_amplitudes_do_not_affect_past_decisions():
|
||||
rows = []
|
||||
for i in range(80):
|
||||
rows.append(
|
||||
dict(
|
||||
t=(date(2020, 1, 1) + timedelta(days=i)).isoformat(),
|
||||
score={"up_3": 0.2},
|
||||
target=dict(
|
||||
available_at=(date(2020, 1, 1) + timedelta(days=i + 15)).isoformat(),
|
||||
future_max_delta=i,
|
||||
events={"up_3": {"hit": i >= 3}},
|
||||
),
|
||||
)
|
||||
)
|
||||
before = [p for p in audit_rows(rows, minimum=2) if p["t"] <= "2020-02-15"]
|
||||
for r in rows:
|
||||
if r["target"]["available_at"] >= "2020-02-15":
|
||||
r["target"]["future_max_delta"] = 999999
|
||||
after = [p for p in audit_rows(rows, minimum=2) if p["t"] <= "2020-02-15"]
|
||||
assert before == after
|
||||
assert all(p["amplitude_source_max"] is None or p["amplitude_source_max"] < p["t"] for p in after)
|
||||
78
research/economic_audit/test_timing_oracle.py
Normal file
78
research/economic_audit/test_timing_oracle.py
Normal file
@@ -0,0 +1,78 @@
|
||||
from datetime import date, timedelta
|
||||
|
||||
import pytest
|
||||
from economic_engine import compare, simulate
|
||||
from timing_oracle import lp_ceiling, optimize_window, oracle
|
||||
|
||||
|
||||
def fixture():
|
||||
days = [(date(2025, 1, 1) + timedelta(days=i)).isoformat() for i in range(45)]
|
||||
v = dict(tank_liters=40, consumption=6, min_range_km=50, monthly_km=1500, min_gain_eur=1)
|
||||
prices = [1.8 + i * 0.003 for i in range(45)]
|
||||
return days, v, prices
|
||||
|
||||
|
||||
@pytest.mark.parametrize("extra", [False, True])
|
||||
def test_feasible_oracle(extra):
|
||||
d, v, p = fixture()
|
||||
b = simulate(d, p, v)
|
||||
r = oracle(d, p, v, b, noextra=not extra)
|
||||
assert r["stock_final"] == pytest.approx(b["stock_final"])
|
||||
assert r["reserve_ok"] and r["comfort_ok"]
|
||||
assert abs(r["conservation_error"]) < 1e-7
|
||||
net_cost = r["stock_adjusted_cost"] + 3 * max(0, r["passages"] - b["passages"])
|
||||
assert net_cost <= b["stock_adjusted_cost"] + 1e-5
|
||||
if not extra:
|
||||
assert r["passages"] <= b["passages"]
|
||||
|
||||
|
||||
def test_oracle_does_not_read_prices_beyond_horizon():
|
||||
d, v, p = fixture()
|
||||
b = simulate(d, p, v)
|
||||
q = [0.0] * len(d)
|
||||
for i, x in zip(b["visits"], b["purchases"], strict=True):
|
||||
q[i] = x["litres"]
|
||||
a, _ = optimize_window(d, p, v, q, 0, 15, b["passages"], False)
|
||||
changed = p[:15] + [1000.0] * 30
|
||||
other, _ = optimize_window(d, changed, v, q, 0, 15, b["passages"], False)
|
||||
assert a == pytest.approx(other)
|
||||
|
||||
|
||||
def test_lp_ceiling_is_optimistic_not_realizable():
|
||||
d, v, p = fixture()
|
||||
b = simulate(d, p, v)
|
||||
ceiling = lp_ceiling(d, p, v, b)
|
||||
assert ceiling["certified"] is True
|
||||
assert ceiling["optimistic_saving"] >= -1e-6
|
||||
assert ceiling["total_visits"] <= b["passages"] + 1e-9
|
||||
|
||||
|
||||
def test_anticipation_uses_same_stock_and_delays_next_need():
|
||||
d, v, p = fixture()
|
||||
b = simulate(d, p, v)
|
||||
i = b["visits"][0] - 2
|
||||
r = simulate(d, p, v, "local", {d[i]: 100})
|
||||
assert i in r["visits"]
|
||||
assert b["visits"][0] not in r["visits"]
|
||||
assert r["stock_final"] == pytest.approx(b["stock_final"])
|
||||
|
||||
|
||||
def test_omniscient_bound_cannot_be_worse_than_reference():
|
||||
"""Le plan de référence est réalisable : un plafond négatif est un bug, pas un résultat."""
|
||||
d, v, p = fixture()
|
||||
b = simulate(d, p, v)
|
||||
ceiling = oracle(d, p, v, b, noextra=True, full=True)
|
||||
saving = b["stock_adjusted_cost"] - ceiling["stock_adjusted_cost"]
|
||||
assert saving >= -1e-5, f"plafond omniscient négatif : {saving}"
|
||||
assert ceiling["passages"] <= b["passages"]
|
||||
assert abs(ceiling["conservation_error"]) < 1e-7
|
||||
|
||||
|
||||
def test_penalty_is_charged_once_for_oracle_plans():
|
||||
"""Les plans d'oracle facturent déjà la pénalité : `compare` ne doit pas la repayer."""
|
||||
d, v, p = fixture()
|
||||
b = simulate(d, p, v)
|
||||
plan = oracle(d, p, v, b, noextra=False)
|
||||
once = compare(b, plan, d, penalty_included=True)
|
||||
twice = compare(b, plan, d)
|
||||
assert once["net"] >= twice["net"] - 1e-9
|
||||
183
research/economic_audit/timing_oracle.py
Normal file
183
research/economic_audit/timing_oracle.py
Normal file
@@ -0,0 +1,183 @@
|
||||
"""Oracles de timing : information J+14 et plafond optimiste.
|
||||
|
||||
Trois objets distincts, jamais confondus :
|
||||
|
||||
- ``oracle(..., full=False)`` : réoptimise chaque fenêtre J…J+14. Le planning et le
|
||||
stock hors segment restent ceux de la référence. C'est un gain **réalisable**
|
||||
mais restreint, pas un plafond.
|
||||
- ``oracle(..., full=True)`` : programme entier mixte sur toute la période, stock
|
||||
final égal à celui de la référence. Plafond uniquement si le solveur certifie
|
||||
l'optimalité ; sinon la note le dit.
|
||||
- ``lp_ceiling`` : relaxation linéaire du même modèle (visites fractionnaires).
|
||||
Toujours certifiée, mais **optimiste** : les visites fractionnaires sont
|
||||
irréalistes, elle majore donc le gain atteignable.
|
||||
"""
|
||||
|
||||
import numpy as np
|
||||
from economic_engine import demand, simulate
|
||||
from scipy.optimize import Bounds, LinearConstraint, milp
|
||||
|
||||
NOEXTRA, PENALIZED = "no_extra_passage", "extra_passages_penalized"
|
||||
|
||||
|
||||
def _model(days, prices, v, q, start, end, base_count, noextra, integral=True, terminal="fixed"):
|
||||
"""Construit le programme d'une fenêtre. `terminal='fixed'` épingle le stock final."""
|
||||
n = end - start
|
||||
cap = v["tank_liters"]
|
||||
reserve = v["min_range_km"] * v["consumption"] / 100
|
||||
use = demand(v, days)
|
||||
dl = 4 * v["consumption"] / 100
|
||||
stock = cap
|
||||
levels = []
|
||||
for i, x in enumerate(q):
|
||||
stock += x - (dl if x > 1e-6 else 0) - use[i]
|
||||
levels.append(stock)
|
||||
initial = cap if start == 0 else levels[start - 1]
|
||||
outside = [i for i, x in enumerate(q) if x > 1e-6 and not start <= i < end]
|
||||
n_visits = 3 * n + 1
|
||||
cost = np.zeros(n_visits)
|
||||
cost[:n] = prices[start:end]
|
||||
cost[-1] = 3.0
|
||||
low = np.zeros(n_visits)
|
||||
high = np.full(n_visits, np.inf)
|
||||
low[n : 2 * n] = reserve
|
||||
high[n : 2 * n] = cap
|
||||
high[2 * n : 3 * n] = 1
|
||||
if terminal == "fixed":
|
||||
low[2 * n - 1] = high[2 * n - 1] = levels[end - 1]
|
||||
rows, lower, upper = [], [], []
|
||||
|
||||
def add(items, low_bound, high_bound):
|
||||
row = np.zeros(n_visits)
|
||||
for j, value in items:
|
||||
row[j] += value
|
||||
rows.append(row)
|
||||
lower.append(low_bound)
|
||||
upper.append(high_bound)
|
||||
|
||||
for j in range(n):
|
||||
index = start + j
|
||||
terms = [(n + j, 1), (j, -1), (2 * n + j, dl)]
|
||||
if j:
|
||||
terms.append((n + j - 1, -1))
|
||||
value = -use[index] + (initial if j == 0 else 0)
|
||||
add(terms, value, value)
|
||||
add([(j, 1), (2 * n + j, -cap)], -np.inf, 0)
|
||||
add([(j, 1), (2 * n + j, -10)], 0, np.inf)
|
||||
add([(n + j, 1), (2 * n + j, dl / 2)], -np.inf, cap - use[index])
|
||||
if j:
|
||||
add([(n + j - 1, 1), (2 * n + j, -dl / 2)], reserve, np.inf)
|
||||
elif initial < reserve + dl / 2 - 1e-7:
|
||||
high[2 * n + j] = 0
|
||||
if any(abs(index - i) < 3 for i in outside):
|
||||
high[2 * n + j] = 0
|
||||
add([(2 * n + k, 1) for k in range(max(0, j - 2), j + 1)], -np.inf, 1)
|
||||
for month in {d[:7] for d in days[start:end]}:
|
||||
add(
|
||||
[(2 * n + j, 1) for j in range(n) if days[start + j][:7] == month],
|
||||
-np.inf,
|
||||
8 - sum(days[i][:7] == month for i in outside),
|
||||
)
|
||||
if noextra:
|
||||
add([(2 * n + j, 1) for j in range(n)], -np.inf, base_count - len(outside))
|
||||
# e >= visites_dans_la_fenetre - passages_restants : seule la pénalité des passages
|
||||
# supplémentaires est facturée, les passages de référence restent gratuits.
|
||||
add([(n_visits - 1, 1)] + [(2 * n + j, -1) for j in range(n)], len(outside) - base_count, np.inf)
|
||||
integrality = np.r_[np.zeros(2 * n), np.ones(n), 0] if integral else np.zeros(n_visits)
|
||||
return cost, Bounds(low, high), LinearConstraint(np.array(rows), lower, upper), integrality, n
|
||||
|
||||
|
||||
def _solve(cost, bounds, constraint, integrality, n, limit):
|
||||
return milp(
|
||||
cost,
|
||||
integrality=integrality,
|
||||
bounds=bounds,
|
||||
constraints=constraint,
|
||||
options={"time_limit": limit, "mip_rel_gap": 1e-7},
|
||||
)
|
||||
|
||||
|
||||
def optimize_window(days, prices, v, q, start, end, base_count, noextra, limit=20):
|
||||
cost, bounds, constraint, integrality, n = _model(days, prices, v, q, start, end, base_count, noextra)
|
||||
result = _solve(cost, bounds, constraint, integrality, n, limit)
|
||||
if not result.success and result.x is None:
|
||||
raise ValueError(f"{days[start]} : {result.message}")
|
||||
quantities = np.maximum(0.0, result.x[:n])
|
||||
visits = result.x[2 * n : 3 * n]
|
||||
# Un plan n'est rejouable que s'il est entier : une visite fractionnaire laissée par un
|
||||
# solveur interrompu créerait deux passages rapprochés au rejeu. On ne garde que les
|
||||
# passages francs et on signale ceux qui ont été écartés.
|
||||
dropped = int(np.sum((visits >= 0.5) != (visits > 1e-6)))
|
||||
quantities[visits < 0.5] = 0
|
||||
quantities[quantities < 1e-6] = 0
|
||||
# Tolérance numérique : un achat de 10 L rendu à 9,999999 ne doit pas être supprimé,
|
||||
# sinon le stock suivant tombe sous la réserve.
|
||||
quantities[quantities < 10.0 - 1e-6] = 0
|
||||
return quantities, dict(
|
||||
gap=float(result.mip_gap),
|
||||
objective=float(result.fun),
|
||||
certified=bool(result.success),
|
||||
fractional_dropped=dropped,
|
||||
message=None if result.success else result.message,
|
||||
)
|
||||
|
||||
|
||||
def oracle(days, prices, v, base, noextra=False, full=False, limit=900):
|
||||
"""J+14 par défaut ; `full=True` tente le plafond omniscient sur toute la période."""
|
||||
quantities = np.zeros(len(days))
|
||||
for index, purchase in zip(base["visits"], base["purchases"], strict=True):
|
||||
quantities[index] = purchase["litres"]
|
||||
starts = [0] if full else range(len(days))
|
||||
certificates = []
|
||||
for start in starts:
|
||||
end = len(days) if full else min(len(days), start + 15)
|
||||
quantities[start:end], certificate = optimize_window(
|
||||
days, prices, v, quantities, start, end, base["passages"], noextra, limit
|
||||
)
|
||||
certificates.append(certificate)
|
||||
result = simulate(
|
||||
days,
|
||||
prices,
|
||||
v,
|
||||
mode="scheduled",
|
||||
forecasts={d: float(x) for d, x in zip(days, quantities, strict=True)},
|
||||
)
|
||||
result["optimizer_max_gap"] = max(c["gap"] for c in certificates)
|
||||
result["optimizer_certified"] = all(c["certified"] for c in certificates)
|
||||
result["optimizer_messages"] = sorted({c["message"] for c in certificates if c["message"]})
|
||||
result["information"] = (
|
||||
"whole_period_perfect_hindsight" if full else "J_to_J_plus_14_fixed_terminal_segment"
|
||||
)
|
||||
if not full and not result["optimizer_certified"]:
|
||||
result["certificate_note"] = (
|
||||
"chaque fenêtre J+14 n'est qu'une réoptimisation locale à planning extérieur figé : "
|
||||
"gain réalisable, ni borne supérieure ni borne inférieure globale"
|
||||
)
|
||||
if full and not result["optimizer_certified"]:
|
||||
result["certificate_note"] = (
|
||||
"solveur interrompu : seule une solution réalisable est rapportée, jamais un plafond prouvé"
|
||||
)
|
||||
if noextra:
|
||||
assert result["passages"] <= base["passages"]
|
||||
return result
|
||||
|
||||
|
||||
def lp_ceiling(days, prices, v, base, noextra=True):
|
||||
"""Relaxation linéaire du modèle plein horizon : majorant **optimiste** du gain."""
|
||||
quantities = np.zeros(len(days))
|
||||
for index, purchase in zip(base["visits"], base["purchases"], strict=True):
|
||||
quantities[index] = purchase["litres"]
|
||||
cost, bounds, constraint, _, n = _model(
|
||||
days, prices, v, quantities, 0, len(days), base["passages"], noextra
|
||||
)
|
||||
result = _solve(cost, bounds, constraint, np.zeros(len(cost)), n, 60)
|
||||
if result.x is None:
|
||||
raise ValueError(f"relaxation non résolue : {result.message}")
|
||||
fractional = int(np.sum((result.x[2 * n : 3 * n] > 1e-6) & (result.x[2 * n : 3 * n] < 1 - 1e-6)))
|
||||
return dict(
|
||||
optimistic_saving=float(base["stock_adjusted_cost"] - result.fun),
|
||||
fractional_visits=fractional,
|
||||
total_visits=float(np.sum(result.x[2 * n : 3 * n])),
|
||||
certified=True,
|
||||
note="visites fractionnaires autorisées : borne supérieure du gain, pas un gain réalisable",
|
||||
)
|
||||
Reference in New Issue
Block a user