Protocole amont apparie : IC diagnostiques, familles as-of, placebo et PR-AUC

This commit is contained in:
root
2026-09-13 09:36:57 +02:00
parent 3bee9a40d9
commit d9bb03fd5f
4 changed files with 939 additions and 9 deletions

View File

@@ -0,0 +1,119 @@
"""Le protocole amont tient-il : appariement, disponibilité réelle, placebo, IC diagnostiqués."""
import sqlite3
import pytest
import upstream_features as up
from enrich_campaign import fit_logistic, predict_logistic, quantile_thresholds, verdict
from risk_report import MIN_USABLE_BLOCKS, bootstrap_ci, paired_block_bootstrap
def make_db(tmp_path):
path = tmp_path / "synthetic.sqlite3"
conn = sqlite3.connect(path)
conn.execute("create table upstream_series (series text, day text, value real, unit text,"
" source text, fetched_at text, observed_at text, published_at text)")
conn.execute("create table chokepoint_daily (chokepoint text, day text, transit_tankers real,"
" transit_total real, capacity_tankers real, capacity_total real, source text,"
" fetched_at text)")
for index in range(0, 40):
day = f"2024-01-{index + 1:02d}" if index < 31 else f"2024-02-{index - 30:02d}"
conn.execute("insert into upstream_series values (?,?,?,?,?,?,?,?)",
("usd_per_eur", day, 1.10 + index / 1000, "usd", "BCE", None, day, None))
conn.execute("insert into chokepoint_daily values (?,?,?,?,?,?,?,?)",
("Strait of Hormuz", day, 50 + index, 90, 10, 20, "IMF PortWatch", None))
conn.commit()
conn.close()
return path
def test_publication_lag_hides_a_value_that_is_not_published_yet(tmp_path):
path = make_db(tmp_path)
points = up.load_family("portwatch", path)["portwatch_tankers"]
observed = points[0]["day"]
assert points[0]["lag_days"] == 10, "PortWatch décrit un jour mais publie plus tard"
daily = up.asof_daily(points, observed, points[0]["available_at"])
assert daily[observed] is None, "aucune ligne ne doit être visible avant sa publication"
assert daily[points[0]["available_at"]] is not None, "elle devient visible à sa date de publication"
def test_forward_fill_starts_only_after_publication(tmp_path):
path = make_db(tmp_path)
points = up.load_family("portwatch", path)["portwatch_tankers"]
start, end = points[0]["day"], points[-1]["available_at"]
daily = up.asof_daily(points, start, end)
published = points[0]["available_at"]
assert daily[published] == points[0]["value"]
assert daily[start] is None
assert all(value is not None for day, value in daily.items() if day > published)
def test_external_features_never_change_when_a_future_value_changes(tmp_path):
path = make_db(tmp_path)
before = up.family_features("fx", "2024-01-01", "2024-02-10", path)
snapshots = {day: dict(values) for day, (values, _) in before.items()}
conn = sqlite3.connect(path)
conn.execute("update upstream_series set value = value * 3 where day = '2024-02-09'")
conn.commit()
conn.close()
after = up.family_features("fx", "2024-01-01", "2024-02-10", path)
for day in ("2024-01-05", "2024-01-20", "2024-02-01"):
assert after[day][0] == snapshots[day], "une valeur plus récente ne réécrit pas le passé"
def test_placebo_keeps_the_distribution_and_breaks_the_order(tmp_path):
rows = [(index, index * 2.0) for index in range(200)]
shuffled = up.permute_blocks(rows, block=30, seed=5)
assert sorted(shuffled) == sorted(rows), "la distribution marginale est conservée"
assert shuffled != rows, "l'ordre temporel est bien cassé"
shifted = up.shift_rows(rows, shift=90)
assert shifted[-1] == rows[89], "décalage temporel non causal explicite"
def test_paired_bootstrap_detects_a_systematic_difference():
good = [0.1] * 600
bad = [0.3] * 600
same = paired_block_bootstrap(good, good)
assert same["mean_difference"] == 0 and not same["significant"]
worse = paired_block_bootstrap(bad, good)
assert worse["mean_difference"] > 0 and worse["significant"], "dégradation systématique détectée"
better = paired_block_bootstrap(good, bad)
assert better["mean_difference"] < 0 and better["high"] < 0
def test_ci_exposes_block_diagnostics_and_refuses_a_thin_effectif():
flags = [True] * 12 + [False] * 588
thin = bootstrap_ci([1] * 12 + [None] * 588, flags=flags)
assert thin["n_blocks_total"] == 22
assert thin["n_blocks_with_signal"] == 1 and thin["n_effective_signals"] == 1
assert thin["usable"] is False
assert "non exploitable" in thin["note"]
wide = [True] * 300 + [False] * 300
usable = bootstrap_ci([1, 0] * 150 + [None] * 300, flags=wide)
assert usable["n_blocks_with_signal"] >= MIN_USABLE_BLOCKS and usable["usable"] is True
def test_verdicts_are_pre_declared_and_placebo_aware():
real = dict(usable=True, low=-0.02, high=-0.004, mean_difference=-0.01)
assert verdict(real, 0.03, 0.20, 0.25) == "apporte une information reproductible"
assert verdict(real, 0.03, 0.30, 0.20) == "aucun apport démontré — le placebo fait aussi bien ou mieux"
assert verdict(dict(usable=True, low=0.002, high=0.03), -0.01, 0.30, 0.35) == "dégrade le modèle"
assert verdict(dict(usable=False, low=-0.02, high=0.004), 0.01, 0.20, 0.25) == "aucun apport démontré"
def test_thresholds_follow_the_frozen_rule_on_their_own_validation():
scores = [0.1] * 95 + [0.5] * 5
table = quantile_thresholds(scores, "2023-01-01", "2024-12-31")
assert table["q95"]["value"] == pytest.approx(0.5)
assert table["q90"]["value"] == pytest.approx(0.1)
assert table["score>=0.25"]["value"] == 0.25
assert table["q95"]["source_from"] == "2023-01-01"
def test_logistic_is_deterministic_and_responds_to_its_feature():
matrix = [[0.0], [0.1], [0.9], [1.0]] * 50
labels = [0.0, 0.0, 1.0, 1.0] * 50
first = fit_logistic(matrix, labels)
second = fit_logistic(matrix, labels)
assert first["weights"] == second["weights"], "aucun aléa dans l'ajustement"
assert predict_logistic(first, [1.0]) > predict_logistic(first, [0.0])