Compare forecast methods against matched naive events
#1
by emberian - opened
Files changed (2)
- agent.py+42-21
- test_decision_contract.pyAdded+37
411 unmodified lines4124134144154164174184194204214224234244254264274284294304314324334344354367 unmodified lines444445446447448449450121 unmodified lines5725735745755765775782 unmodified lines58158258358458558658728 unmodified lines616617618619620621622411 unmodified linesdef gate(c):acc = {}for s, h, m, e in c.execute("SELECT signal, target-made, method, ABS(value-actual) FROM forecast WHERE scored=1").fetchall():acc.setdefault((kind_of(s), int(h)), {}).setdefault(m, []).append(e)out = {}for k, ms in acc.items():nv = ms.get("naive", [])if not nv:continuemn = sum(nv) / len(nv)rec = {"n_naive": len(nv), "mae_naive": round(mn, 4), "methods": {}, "admitted": None}for m in METHODS:tr = ms.get(m, [])if tr:mt = sum(tr) / len(tr)ok = len(tr) >= 30 and mt <= 0.9 * mnrec["methods"][m] = {"n": len(tr), "mae": round(mt, 4), "admitted": ok}if ok and (rec["admitted"] is None or mt < rec["methods"][rec["admitted"]]["mae"]):rec["admitted"] = mout["%s@%dh" % (k[0], k[1] // 3600)] = recreturn out7 unmodified linesdef plan_actions(c, now):"""CHECKED OPERATIONS proposed from the current facts; dry-run results attached; nothing executes here"""t = c.execute("SELECT MAX(ts) FROM fact").fetchone()[0]if not t:return []_, rows = latest_values(c)rows = [(e, s, v) for e, s, v, _, _ in rows]121 unmodified linesdef latest_values(c):"""the newest value of every (entity, signal) in the last 15 minutes (slow sensors run every 5)"""t = c.execute("SELECT MAX(ts) FROM fact").fetchone()[0]if not t:return None, []rows = c.execute("SELECT f.entity, f.signal, f.value, f.source, f.ts FROM fact f JOIN (SELECT entity, signal, MAX(ts) m FROM fact ""WHERE ts>=? GROUP BY entity, signal) x ON f.entity=x.entity AND f.signal=x.signal AND f.ts=x.m", (t - 900,)).fetchall()2 unmodified linesdef status(c):t, rows = latest_values(c)if not t:return {"facts": 0}crit, warn = [], []for e, s, v, src, ts in rows:28 unmodified linesdef why(c, entity):t, _ = latest_values(c)if not t:return []out = []for e, s in c.execute("SELECT DISTINCT entity, signal FROM fact WHERE ts>=?", (t - 3600,)).fetchall():411 unmodified lines4124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564577 unmodified lines465466467468469470471121 unmodified lines5935945955965975985992 unmodified lines60260360460560660760828 unmodified lines637638639640641642643411 unmodified linesdef gate(c):"""Compare a method with the baseline on exactly the same forecast events.Duplicate method/event rows are ambiguous, not independent evidence.Mismatched actual observations cannot form a baseline comparison."""events = {}for made, target, entity, signal, method, value, actual in c.execute("SELECT made, target, entity, signal, method, value, actual FROM forecast WHERE scored=1").fetchall():key = (kind_of(signal), int(target - made), made, target, entity)methods = events.setdefault(key, {})methods.setdefault(method, []).append((value, actual))acc = {}for key, methods in events.items():base = methods.get("naive", [])if len(base) != 1:continuevalue, actual = base[0]rec = acc.setdefault(key[:2], {"naive": [], "pairs": {}})baseline_error = abs(value - actual)rec["naive"].append(baseline_error)for method in METHODS:rows = methods.get(method, [])if len(rows) == 1 and rows[0][1] == actual:rec["pairs"].setdefault(method, []).append((abs(rows[0][0] - actual), baseline_error))out = {}for (signal, horizon), samples in acc.items():naive = samples["naive"]rec = {"n_naive": len(naive), "mae_naive": round(sum(naive) / len(naive), 4),"methods": {}, "admitted": None}best = Nonefor method, pairs in samples["pairs"].items():mt = sum(a for a, _ in pairs) / len(pairs)mn = sum(b for _, b in pairs) / len(pairs)ok = len(pairs) >= 30 and mt < mn and mt <= 0.9 * mnrec["methods"][method] = {"n": len(pairs), "mae": round(mt, 4),"mae_naive_paired": round(mn, 4), "admitted": ok}if ok and (best is None or mt < best):rec["admitted"], best = method, mtduration = "%dh" % (horizon // 3600) if horizon % 3600 == 0 else "%ds" % horizonout["%s@%s" % (signal, duration)] = recreturn out7 unmodified linesdef plan_actions(c, now):"""CHECKED OPERATIONS proposed from the current facts; dry-run results attached; nothing executes here"""t = c.execute("SELECT MAX(ts) FROM fact").fetchone()[0]if t is None:return []_, rows = latest_values(c)rows = [(e, s, v) for e, s, v, _, _ in rows]121 unmodified linesdef latest_values(c):"""the newest value of every (entity, signal) in the last 15 minutes (slow sensors run every 5)"""t = c.execute("SELECT MAX(ts) FROM fact").fetchone()[0]if t is None:return None, []rows = c.execute("SELECT f.entity, f.signal, f.value, f.source, f.ts FROM fact f JOIN (SELECT entity, signal, MAX(ts) m FROM fact ""WHERE ts>=? GROUP BY entity, signal) x ON f.entity=x.entity AND f.signal=x.signal AND f.ts=x.m", (t - 900,)).fetchall()2 unmodified linesdef status(c):t, rows = latest_values(c)if t is None:return {"facts": 0}crit, warn = [], []for e, s, v, src, ts in rows:28 unmodified linesdef why(c, entity):t, _ = latest_values(c)if t is None:return []out = []for e, s in c.execute("SELECT DISTINCT entity, signal FROM fact WHERE ts>=?", (t - 3600,)).fetchall():
12345678910111213141516171819202122232425262728293031323334353637import sqlite3import unittestfrom contextlib import closingfrom agent import gate, latest_values
class ForecastContract(unittest.TestCase): def results(self, method, entity, value): return [(i, i+3600, entity, "used_pct", method, value, 1, 0) for i in range(30)]
def check_gate(self, rows): with closing(sqlite3.connect(":memory:")) as db: db.execute("CREATE TABLE forecast(made,target,entity,signal,method,value,scored,actual)") db.executemany("INSERT INTO forecast VALUES(?,?,?,?,?,?,?,?)", rows) return gate(db)["used_pct@1h"]
def test_unpaired_baseline_is_not_evidence(self): self.assertIsNone(self.check_gate(self.results("naive", "a", 100) + self.results("trend6h", "b", 1))["admitted"])
def test_matching_improvement_and_duplicate_refusal(self): baseline = self.results("naive", "a", 100) method = self.results("trend6h", "a", 1) self.assertEqual(self.check_gate(baseline + method)["admitted"], "trend6h") self.assertIsNone(self.check_gate(baseline + method + [method[0]])["admitted"])
def test_equal_perfect_forecasts_did_not_beat_baseline(self): self.assertIsNone(self.check_gate(self.results("naive", "a", 0) + self.results("trend6h", "a", 0))["admitted"])
def test_epoch_zero_is_a_real_timestamp(self): with closing(sqlite3.connect(":memory:")) as db: db.execute("CREATE TABLE fact(ts,entity,signal,value,source)") db.execute("INSERT INTO fact VALUES(0,'disk:a','used_pct',98,'supplied')") stamp, rows = latest_values(db) self.assertEqual(stamp, 0) self.assertEqual(len(rows), 1)
if __name__ == "__main__": unittest.main()agent.py+42-21
test_decision_contract.pyAdded+37