From aaec262a13bcd1299efd5486816fc8d14d526f4a Mon Sep 17 00:00:00 2001 From: Marc Mintel Date: Sat, 5 Dec 2026 00:06:34 +0100 Subject: [PATCH] vorflop_selbst: archive measurement scaffold for the preflop self-consistency correction (21,390 preflop decisions counted by line); waits for the sidecar Co-Authored-By: Claude Opus 5.5 --- messung/innovation/vorflop_selbst/KARTE.md | 29 +++ messung/innovation/vorflop_selbst/linien.py | 71 +++++++ messung/innovation/vorflop_selbst/sidecar.py | 43 ++++ .../vorflop_selbst/vorflop_selbst.py | 193 ++++++++++++++++++ messung/innovation/vorflop_selbst/wert.py | 86 ++++++++ .../innovation/vorflop_selbst/zaehlung.json | 63 ++++++ tests/innovation_vorflop_selbst_spec.py | 142 +++++++++++++ 7 files changed, 627 insertions(+) create mode 100644 messung/innovation/vorflop_selbst/KARTE.md create mode 100644 messung/innovation/vorflop_selbst/linien.py create mode 100644 messung/innovation/vorflop_selbst/sidecar.py create mode 100644 messung/innovation/vorflop_selbst/vorflop_selbst.py create mode 100644 messung/innovation/vorflop_selbst/wert.py create mode 100644 messung/innovation/vorflop_selbst/zaehlung.json create mode 100644 tests/innovation_vorflop_selbst_spec.py diff --git a/messung/innovation/vorflop_selbst/KARTE.md b/messung/innovation/vorflop_selbst/KARTE.md new file mode 100644 index 00000000..4e7cb25d --- /dev/null +++ b/messung/innovation/vorflop_selbst/KARTE.md @@ -0,0 +1,29 @@ +--- +titel: Vorflop-selbst ueber alle Preflop-Entscheidungen des Archivs +strang: motor +plan: innovation, Nachspiel MOTOR_VORFLOP_SELBST +frage: Welche der 21.390 echten Preflop-Entscheidungen (01.-04.12.) aendert MOTOR_VORFLOP_SELBST, mit welchem Wert ohne Wuerfel (bb, Intervall), und bleibt der Dienst mit Schalter AUS bitgleich? +tor: info + Liste fuer die Hauptsession (AENDERUNGEN.md); Aus-Pruefung 0 Abweichungen auf 500 echten Anfragen +decke: Summe der Werte je 100 Haende laut Seitendatei; die Liste ist exakt (kein Sim-Lauf), Aufloesung = Intervall aus dem Seitendatei-Kovarianz +abbruch: kein Lauf tiefer als die 21.390 Anfragen; Abbruch, wenn die Seitendatei fehlt oder Aus-Pruefung Abweichungen zeigt +quelle: pruefstand/basis-rein (ein.jsonl, ref.jsonl) +status: geplant +ergebnis: Zaehlung fertig (21.390 Preflop-Entscheidungen, 20.358 Haende); Werte warten auf die Seitendatei +entscheidung: offen +punkt: – +erwartet: – +richter: ungeprueft +schalter: MOTOR_VORFLOP_SELBST +buendel: a +stand: 2026-12-05 +bericht: AENDERUNGEN.md +starter: – +nachfolger: – +eichung: – +stackoff: – +--- + +Skript `vorflop_selbst.py` (zaehlen, lauf, aus, bericht), reine Teile `linien.py`, `wert.py`, Leser `sidecar.py` +(STUB-Format, bis der Zweig claude/vorflop-selbst-2 das echte dokumentiert). Spec: `tests/innovation_vorflop_selbst_spec.py`. +Grosse Zwischendateien: /Volumes/Alpha SSD/pokerfreak-daten/innovation/vorflop_selbst/. +Offen: echter Knotenschluessel/Klasse aus der CLI des Motors (heute Platzhalter aus Linie, Position, Klasse im Grundtext). diff --git a/messung/innovation/vorflop_selbst/linien.py b/messung/innovation/vorflop_selbst/linien.py new file mode 100644 index 00000000..8a0988b5 --- /dev/null +++ b/messung/innovation/vorflop_selbst/linien.py @@ -0,0 +1,71 @@ +"""Preflop line classification from a request (pure, no I/O). Output carries no player or hand IDs.""" + +POSTS = ("POST_SB", "POST_BB", "POST_ANTE") +LINIEN = ("open", "bb_option", "vs_limp", "iso_limp", "vs_open", "vs_3bet", "vs_4bet", "vs_5bet_plus") +_POS_NACH_SPIELERN = { + 2: ("SB", "BB"), + 3: ("SB", "BB", "BTN"), + 4: ("SB", "BB", "CO", "BTN"), + 5: ("SB", "BB", "HJ", "CO", "BTN"), + 6: ("SB", "BB", "UTG", "HJ", "CO", "BTN"), +} + + +def position(q): + """Seat name relative to the button; SB posts first, seats run in action order from the SB.""" + n = q["seats"] + sb = next((h["seat"] for h in q["history"] if h["action"] == "POST_SB"), None) + namen = _POS_NACH_SPIELERN.get(n) + if sb is None or namen is None: + return "?" + return namen[(q["heroSeat"] - sb) % n] + + +def vorgeschichte(history): + """(raises, limps, level, extra_blinds) of the preflop history before the hero acts. + ALL_IN counts as a raise only if it exceeds the current bet level; RAISE amounts are raise-to totals.""" + stufe, raises, limps, extra_bb = 0.0, 0, 0, 0 + for h in history: + if h["street"] != "PREFLOP": + continue + a, x = h["action"], h.get("amount") or 0.0 + if a == "POST_BB": + extra_bb += 1 + stufe = max(stufe, x) + elif a == "POST_SB": + stufe = max(stufe, x) + elif a == "RAISE" or (a == "ALL_IN" and x > stufe + 1e-9): + raises += 1 + stufe = max(stufe, x) + elif a == "CALL" and raises == 0: + limps += 1 + return raises, limps, stufe, max(extra_bb - 1, 0) + + +def linie(q): + """One of LINIEN, from raises/limps before the hero; BB without a raise and no limp is the check option.""" + raises, limps, _, _ = vorgeschichte(q["history"]) + pos = position(q) + if raises == 0: + if limps > 0: + return "vs_limp" if pos in ("SB", "BB") else "iso_limp" + return "bb_option" if pos == "BB" else "open" + return {1: "vs_open", 2: "vs_3bet", 3: "vs_4bet"}.get(raises, "vs_5bet_plus") + + +def sonderform(q): + """Tags that change the table: splash pot, straddle (second big blind), ante.""" + _, _, _, extra = vorgeschichte(q["history"]) + tags = [] + if q.get("_splash"): + tags.append("splash") + if extra: + tags.append("straddle") + if any(h["action"] == "POST_ANTE" for h in q["history"]): + tags.append("ante") + return tags + + +def beschreibe(q): + """Compact, ID-free description of the decision.""" + return {"pos": position(q), "linie": linie(q), "spieler": q["seats"], "sonder": sonderform(q)} diff --git a/messung/innovation/vorflop_selbst/sidecar.py b/messung/innovation/vorflop_selbst/sidecar.py new file mode 100644 index 00000000..7dac802d --- /dev/null +++ b/messung/innovation/vorflop_selbst/sidecar.py @@ -0,0 +1,43 @@ +"""Reader for the MOTOR_VORFLOP_SELBST sidecar and for the reason mark - ISOLATED because the real format is still unknown. + +STUB FORMAT (replace `lade`/`parse_marke` once the other branch (claude/vorflop-selbst) documents the real one): + sidecar JSON: {"format": "stub-1", "eintraege": [{"key": str, "klasse": int, "pi": {a: p}, "pi_neu": {a: p}, + "R": float, "R_se": float, "w": float, "V": {a: bb}, "se_V": {a: bb}, "cov": {a: {b: c}} | null}]} + reason mark : "[Vorflop-selbst -> R w ]" inside the answer's `reason`. +""" +import json +import re + +MARKE = re.compile(r"\[Vorflop-selbst\s+(?P[^\]]*?)->(?P[^\]]*?)\s+R\s+(?P\S+)\s+w\s+(?P\S+?)\]") +KLASSE = re.compile(r"Klasse (\d+)") +ANTEIL = re.compile(r"([\w.\-]+)\s+(\d+(?:\.\d+)?)%") + + +def parse_marke(reason): + """Reason mark -> {alt, neu, R, w} (strings as logged) or None.""" + m = MARKE.search(reason or "") + return m.groupdict() if m else None + + +def parse_klasse(reason): + m = KLASSE.search(reason or "") + return int(m.group(1)) if m else None + + +def parse_mischung(text): + """'fold 0%, call 5%, 0.75x 95%' -> {'fold': 0.0, 'call': 0.05, '0.75x': 0.95} (whole percent, only a fallback).""" + return {a: float(p) / 100.0 for a, p in ANTEIL.findall(text or "")} + + +def knoten_schluessel(q_beschreibung, antwort): + """Node key of a request. STUB: line type + position + players + class; the real key comes from the motor CLI.""" + k = parse_klasse(antwort.get("reason")) + return "%s|%s|%d|%s" % (q_beschreibung["linie"], q_beschreibung["pos"], q_beschreibung["spieler"], k), k + + +def lade(pfad): + with open(pfad) as f: + d = json.load(f) + if d.get("format") != "stub-1": + raise ValueError("unknown sidecar format %r - update sidecar.py" % d.get("format")) + return {(e["key"], e["klasse"]): e for e in d["eintraege"]} diff --git a/messung/innovation/vorflop_selbst/vorflop_selbst.py b/messung/innovation/vorflop_selbst/vorflop_selbst.py new file mode 100644 index 00000000..1db057f4 --- /dev/null +++ b/messung/innovation/vorflop_selbst/vorflop_selbst.py @@ -0,0 +1,193 @@ +#!/usr/bin/env python3 +"""Measurement over ALL preflop decisions of the archive (basis-rein): which would MOTOR_VORFLOP_SELBST change, worth what? + + python3 messung/innovation/vorflop_selbst/vorflop_selbst.py zaehlen + python3 .../vorflop_selbst.py lauf sidecar= [env=K=V ...] (switch ON and OFF through the service, parses the mark) + python3 .../vorflop_selbst.py aus [n=500] [saat=1] (switch OFF: bit-identical on real requests) + python3 .../vorflop_selbst.py bericht (AENDERUNGEN.md + aenderungen.jsonl from lauf.jsonl) + +Source (read only): /ein.jsonl (one request per line), ref.jsonl (logged live answers, same line order). +Every exe run goes through werkzeuge/motorplatz.py --plaetze 2, nice 10. Outputs carry no player or hand IDs. +""" +import collections +import json +import os +import random +import subprocess +import sys + +HIER = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HIER) +import linien as L # noqa: E402 +import sidecar as S # noqa: E402 +import wert as W # noqa: E402 + +WURZEL = "/Users/marcmintel/Projects/pokerfreak" +ARCHIV = "/Volumes/Alpha SSD/pokerfreak-daten/pruefstand/basis-rein" +DATEN = "/Volumes/Alpha SSD/pokerfreak-daten/grundstrategie-mitzaehler" +STRATEGIE = DATEN + "/sechs100-v2.bin" +GROSS = "/Volumes/Alpha SSD/pokerfreak-daten/innovation/vorflop_selbst" +SCHALTER = "MOTOR_VORFLOP_SELBST" +BATCH = 500 +TOP = 50 + + +def lies(pfad): + with open(pfad) as f: + for z in f: + yield json.loads(z) + + +def preflop_entscheidungen(): + """Yields (line index, request, description, logged class) for every PREFLOP request; hands = distinct hand ids in ref.""" + ref = lies(ARCHIV + "/ref.jsonl") + for i, (q, r) in enumerate(zip(lies(ARCHIV + "/ein.jsonl"), ref)): + if q["street"] == "PREFLOP": + yield i, q, L.beschreibe(q), S.parse_klasse((r.get("motor") or {}).get("reason")), r.get("hand") + + +def zaehlen(): + os.makedirs(GROSS, exist_ok=True) + je = collections.Counter() + hände, n = set(), 0 + zeilen = [] + for i, q, b, k, hand in preflop_entscheidungen(): + n += 1 + je[(b["linie"], b["pos"])] += 1 + zeilen.append(dict(b, i=i, klasse=k)) + for r in lies(ARCHIV + "/ref.jsonl"): + hände.add(r.get("hand")) + tmp = GROSS + "/entscheidungen.jsonl.tmp" + with open(tmp, "w") as f: + for z in zeilen: + f.write(json.dumps(z) + "\n") + os.replace(tmp, GROSS + "/entscheidungen.jsonl") + linie = collections.Counter() + for (l, _), c in je.items(): + linie[l] += c + sonder = collections.Counter(t for z in zeilen for t in z["sonder"]) + out = {"entscheidungen": n, "haende": len(hände), "je_linie": dict(linie), "je_linie_position": {"%s|%s" % k: c for k, c in sorted(je.items())}, + "sonderformen": dict(sonder), "je_spielerzahl": dict(collections.Counter(z["spieler"] for z in zeilen))} + with open(HIER + "/zaehlung.json", "w") as f: + json.dump(out, f, indent=1) + print(json.dumps(out, indent=1)) + + +def dienst(exe, qs, env_zusatz): + argv = [sys.executable, os.path.join(WURZEL, "werkzeuge/motorplatz.py"), "--plaetze", "2", "--", "nice", "-n", "10", + exe, "dienst", "sechs100", DATEN, "2000-600-400", "200", STRATEGIE] + out = [] + for a in range(0, len(qs), BATCH): + teil = qs[a:a + BATCH] + r = subprocess.run(argv, input="".join(json.dumps(q) + "\n" for q in teil), capture_output=True, text=True, + env=dict(os.environ, MOTOR_FLACH="1", **env_zusatz)) + zeilen = [z for z in r.stdout.splitlines() if z.strip()] + if len(zeilen) != len(teil): + raise SystemExit("%d answers for %d requests; stderr: %s" % (len(zeilen), len(teil), r.stderr[-500:])) + out += [json.loads(z) for z in zeilen] + return out + + +def lauf(exe, opt): + """Runs the preflop requests with the switch ON; keeps the lines whose answer carries the mark.""" + sc = S.lade(opt["sidecar"]) + extra = dict(x.split("=", 1) for x in opt.get("env", "").split(",") if x) + es = list(preflop_entscheidungen()) + qs = [q for _, q, _, _, _ in es] + an = dienst(exe, qs, dict(extra, **{SCHALTER: "1"})) + ohne = dienst(exe, qs, {SCHALTER: "0"}) + zeilen = {} + for (i, q, b, k, _), a, o in zip(es, an, ohne): + marke = S.parse_marke(a.get("reason")) + key, klasse = S.knoten_schluessel(b, a) + e = sc.get((key, klasse)) + z = zeilen.setdefault((key, klasse), dict(b, key=key, klasse=klasse, n=0, markiert=marke is not None, e=e)) + z["n"] += 1 + rows = [] + for z in zeilen.values(): + e = z.pop("e") + if e is None or not z["markiert"]: + continue + r = W.zeile({"pi_alt": e["pi"], "pi_neu": e["pi_neu"], "V": e["V"], "cov": e.get("cov"), "se_V": e.get("se_V"), + "n": z["n"], "key": z["key"], "klasse": z["klasse"], "linie": z["linie"], "pos": z["pos"], + "spieler": z["spieler"], "sonder": z["sonder"], "R": e["R"], "R_se": e["R_se"], "w": e["w"]}) + if r: + rows.append(r) + with open(GROSS + "/lauf.jsonl.tmp", "w") as f: + for r in W.sortiert(rows): + f.write(json.dumps(r) + "\n") + os.replace(GROSS + "/lauf.jsonl.tmp", GROSS + "/lauf.jsonl") + print("rows changed:", len(rows), "of", len(zeilen), "unique decisions") + + +def aus(exe_a, exe_b, opt): + """Switch OFF: both exes answer identically on preflop + other streets (turn/river included) of the archive.""" + n, saat = int(opt.get("n", 500)), int(opt.get("saat", 1)) + alle = collections.defaultdict(list) + for q in lies(ARCHIV + "/ein.jsonl"): + alle[q["street"]].append(q) + r = random.Random(saat) + plan = {"PREFLOP": n // 2, "FLOP": n // 6, "TURN": n // 6} + plan["RIVER"] = n - sum(plan.values()) + qs = [r.choice(alle[s]) for s, c in plan.items() for _ in range(c)] + a, b = dienst(exe_a, qs, {}), dienst(exe_b, qs, {}) + je, abw = collections.defaultdict(lambda: [0, 0]), [] + for q, x, y in zip(qs, a, b): + ka = tuple(x.get(k) for k in ("action", "size", "reason")) + kb = tuple(y.get(k) for k in ("action", "size", "reason")) + je[q["street"]][0 if ka == kb else 1] += 1 + if ka != kb: + abw.append({"strasse": q["street"], "a": ka, "b": kb}) + erg = {"exe_a": exe_a, "exe_b": exe_b, "n": len(qs), "je_strasse_gleich_anders": je, "anders": sum(v[1] for v in je.values()), "abweichungen": abw[:50]} + with open(HIER + "/aus_pruefung.json", "w") as f: + json.dump(erg, f, indent=1) + print(json.dumps({k: erg[k] for k in ("n", "je_strasse_gleich_anders", "anders")})) + + +def erklaerung(z): + d = W.differenz(z["pi_alt"], z["pi_neu"]) + ab = max(d, key=lambda a: -d[a]) + auf = max(d, key=lambda a: d[a]) + return ("%s, %s, %d Spieler, Klasse %s: %.0f %% weniger %s, %.0f %% mehr %s (Tafel behaelt Gewicht w=%.2f, der Rest geht auf die selbstkonsistente Antwort); Wert %+.3f bb je Vorkommen " + "[%+.3f; %+.3f], kommt %dx im Archiv vor." % (z["linie"], z["pos"], z["spieler"], z["klasse"], -100 * d[ab], ab, 100 * d[auf], auf, + z["w"], z["wert"], z["wert_lo"], z["wert_hi"], z["n"])) + + +def bericht(): + z = json.load(open(HIER + "/zaehlung.json")) + rows = list(lies(GROSS + "/lauf.jsonl")) + s = W.summen(rows, z["entscheidungen"], z["haende"]) + je = W.summen_je(rows, "linie", z["je_linie"], z["haende"]) + with open(HIER + "/aenderungen.jsonl", "w") as f: + for r in rows: + f.write(json.dumps({k: r[k] for k in ("key", "linie", "pos", "spieler", "klasse", "n", "pi_alt", "pi_neu", "R", "R_se", "w", "wert", "wert_se", "wert_lo", "wert_hi")}) + "\n") + t = ["# Vorflop-selbst: Aenderungen an allen Preflop-Entscheidungen des Archivs", "", + "Entscheidungen: %d, davon geaendert (eindeutig): %d (%d Vorkommen). Wert ohne Wuerfel: %+.2f bb/100 [%+.2f; %+.2f]." % ( + s["entscheidungen"], s["geaendert_eindeutig"], s["geaendert_vorkommen"], s["wert_bb_pro_100"], s["lo_bb_pro_100"], s["hi_bb_pro_100"]), + "", "| Linie | Entscheidungen | geaendert | bb/100 [95 %] |", "|---|---|---|---|"] + for l, v in je.items(): + t.append("| %s | %d | %d | %+.2f [%+.2f; %+.2f] |" % (l, v["entscheidungen"], v["geaendert_eindeutig"], v["wert_bb_pro_100"], v["lo_bb_pro_100"], v["hi_bb_pro_100"])) + t += ["", "## Top %d nach |Wert|" % TOP, ""] + ["%d. %s" % (i + 1, erklaerung(r)) for i, r in enumerate(rows[:TOP])] + with open(HIER + "/AENDERUNGEN.md", "w") as f: + f.write("\n".join(t) + "\n") + print("\n".join(t[:12])) + + +def main(argv): + cmd, rest = argv[0], argv[1:] + pos = [x for x in rest if "=" not in x] + opt = dict(x.split("=", 1) for x in rest if "=" in x) + if cmd == "zaehlen": + zaehlen() + elif cmd == "lauf": + lauf(pos[0], opt) + elif cmd == "aus": + aus(pos[0], pos[1], opt) + elif cmd == "bericht": + bericht() + else: + raise SystemExit(__doc__) + + +if __name__ == "__main__": + main(sys.argv[1:]) diff --git a/messung/innovation/vorflop_selbst/wert.py b/messung/innovation/vorflop_selbst/wert.py new file mode 100644 index 00000000..a0991aaa --- /dev/null +++ b/messung/innovation/vorflop_selbst/wert.py @@ -0,0 +1,86 @@ +"""Value without dice, sorting and totals for the preflop self-consistency list (pure, no I/O). + +A row is one unique decision (node + class) with archive frequency n: + pi_old, pi_neu : {action: probability} + V : {action: value in bb} from the sidecar + cov : {a: {b: covariance}} of the V estimates, or None (then se_V is used as a diagonal) + se_V : {action: standard error} +The value of a change is dW = sum_a (pi'(a) - pi(a)) * V(a): no card luck, only the decision. 1.96 sigma intervals. +""" +import math + +Z95 = 1.96 +VERAENDERT_AB = 1e-9 + + +def aktionen(*mischungen): + return sorted({a for m in mischungen for a in m}) + + +def differenz(pi_alt, pi_neu): + return {a: pi_neu.get(a, 0.0) - pi_alt.get(a, 0.0) for a in aktionen(pi_alt, pi_neu)} + + +def veraendert(pi_alt, pi_neu): + return any(abs(d) > VERAENDERT_AB for d in differenz(pi_alt, pi_neu).values()) + + +def wert_ohne_wurf(pi_alt, pi_neu, V): + """Sum_a (pi'(a) - pi(a)) V(a); an action without a V estimate and with a changed probability is an error.""" + s = 0.0 + for a, d in differenz(pi_alt, pi_neu).items(): + if abs(d) <= VERAENDERT_AB: + continue + if a not in V: + raise KeyError("no value for changed action %r" % a) + s += d * V[a] + return s + + +def wert_se(pi_alt, pi_neu, cov=None, se_V=None): + """Standard error of the value: sqrt(d' S d) with the full covariance, else independent estimates.""" + d = {a: x for a, x in differenz(pi_alt, pi_neu).items() if abs(x) > VERAENDERT_AB} + if cov is not None: + v = sum(d[a] * d[b] * cov.get(a, {}).get(b, 0.0) for a in d for b in d) + elif se_V is not None: + v = sum((d[a] * se_V[a]) ** 2 for a in d) + else: + raise ValueError("neither cov nor se_V given") + return math.sqrt(max(v, 0.0)) + + +def zeile(r): + """Row with value, standard error and 95 % interval; None if the decision is unchanged.""" + if not veraendert(r["pi_alt"], r["pi_neu"]): + return None + w = wert_ohne_wurf(r["pi_alt"], r["pi_neu"], r["V"]) + se = wert_se(r["pi_alt"], r["pi_neu"], r.get("cov"), r.get("se_V")) + return dict(r, wert=w, wert_se=se, wert_lo=w - Z95 * se, wert_hi=w + Z95 * se) + + +def sortiert(zeilen): + """By |value| descending; ties broken by frequency, then key, so the order is deterministic.""" + return sorted(zeilen, key=lambda z: (-abs(z["wert"]), -z["n"], str(z.get("key")))) + + +def summen(zeilen, entscheidungen, haende): + """Totals: decisions seen, unique rows changed, value per 100 hands with interval. + Frequency-weighted; the same row shares one estimate (fully correlated across occurrences), different rows are + independent: se_total = sqrt(sum_k (n_k se_k)^2).""" + if haende <= 0: + raise ValueError("hands must be positive") + gesamt = sum(z["n"] * z["wert"] for z in zeilen) + se = math.sqrt(sum((z["n"] * z["wert_se"]) ** 2 for z in zeilen)) + f = 100.0 / haende + return {"entscheidungen": entscheidungen, "geaendert_eindeutig": len(zeilen), + "geaendert_vorkommen": sum(z["n"] for z in zeilen), + "wert_bb_pro_100": gesamt * f, "se_bb_pro_100": se * f, + "lo_bb_pro_100": (gesamt - Z95 * se) * f, "hi_bb_pro_100": (gesamt + Z95 * se) * f} + + +def summen_je(zeilen, schluessel, entscheidungen_je, haende): + """Totals per group (e.g. line type); entscheidungen_je maps group -> number of decisions seen.""" + gruppen = {} + for z in zeilen: + gruppen.setdefault(z[schluessel], []).append(z) + return {g: summen(gruppen.get(g, []), entscheidungen_je[g], haende) for g in sorted(entscheidungen_je)} diff --git a/messung/innovation/vorflop_selbst/zaehlung.json b/messung/innovation/vorflop_selbst/zaehlung.json new file mode 100644 index 00000000..55e46e9d --- /dev/null +++ b/messung/innovation/vorflop_selbst/zaehlung.json @@ -0,0 +1,63 @@ +{ + "entscheidungen": 21390, + "haende": 20358, + "je_linie": { + "open": 10908, + "vs_open": 7810, + "iso_limp": 480, + "vs_limp": 546, + "vs_3bet": 1514, + "vs_4bet": 85, + "bb_option": 19, + "vs_5bet_plus": 28 + }, + "je_linie_position": { + "bb_option|BB": 19, + "iso_limp|BTN": 233, + "iso_limp|CO": 178, + "iso_limp|HJ": 69, + "open|BTN": 2030, + "open|CO": 2537, + "open|HJ": 2708, + "open|SB": 1685, + "open|UTG": 1948, + "vs_3bet|BB": 390, + "vs_3bet|BTN": 279, + "vs_3bet|CO": 212, + "vs_3bet|HJ": 192, + "vs_3bet|SB": 328, + "vs_3bet|UTG": 113, + "vs_4bet|BB": 21, + "vs_4bet|BTN": 16, + "vs_4bet|CO": 10, + "vs_4bet|HJ": 14, + "vs_4bet|SB": 17, + "vs_4bet|UTG": 7, + "vs_5bet_plus|BB": 1, + "vs_5bet_plus|BTN": 7, + "vs_5bet_plus|CO": 6, + "vs_5bet_plus|HJ": 5, + "vs_5bet_plus|SB": 5, + "vs_5bet_plus|UTG": 4, + "vs_limp|BB": 325, + "vs_limp|SB": 221, + "vs_open|BB": 2715, + "vs_open|BTN": 1542, + "vs_open|CO": 878, + "vs_open|HJ": 372, + "vs_open|SB": 2293, + "vs_open|UTG": 10 + }, + "sonderformen": { + "straddle": 397, + "splash": 201, + "ante": 201 + }, + "je_spielerzahl": { + "2": 809, + "3": 690, + "5": 6028, + "6": 11995, + "4": 1868 + } +} \ No newline at end of file diff --git a/tests/innovation_vorflop_selbst_spec.py b/tests/innovation_vorflop_selbst_spec.py new file mode 100644 index 00000000..ee270a16 --- /dev/null +++ b/tests/innovation_vorflop_selbst_spec.py @@ -0,0 +1,142 @@ +#!/usr/bin/env python3 +"""Specification messung/innovation/vorflop_selbst/{linien,wert}.py (line classification, value without dice, sorting, totals). + python3 tests/innovation_vorflop_selbst_spec.py -v""" +import math +import os +import sys +import unittest + +_w = os.path.dirname(os.path.abspath(__file__)) +while _w != "/" and not os.path.isdir(os.path.join(_w, "messung")): + _w = os.path.dirname(_w) +sys.path.insert(0, os.path.join(_w, "messung", "innovation", "vorflop_selbst")) +import linien as L # noqa: E402 +import wert as W # noqa: E402 + + +def h(seat, a, amt=None): + d = {"street": "PREFLOP", "seat": seat, "action": a} + if amt is not None: + d["amount"] = amt + return d + + +def q(seats, hero, hist, **kw): + return dict({"seats": seats, "heroSeat": hero, "history": hist}, **kw) + + +# six-handed: seat 5 = SB, 6 = BB, then UTG = 1, HJ = 2, CO = 3, BTN = 4 +BLINDS6 = [h(5, "POST_SB", 0.01), h(6, "POST_BB", 0.02)] + + +class Linien(unittest.TestCase): + def test_positionen_sechser(self): + namen = [L.position(q(6, s, BLINDS6)) for s in (5, 6, 1, 2, 3, 4)] + self.assertEqual(namen, ["SB", "BB", "UTG", "HJ", "CO", "BTN"]) + + def test_heads_up(self): + hist = [h(2, "POST_SB", 0.01), h(1, "POST_BB", 0.02)] + self.assertEqual((L.position(q(2, 2, hist)), L.position(q(2, 1, hist))), ("SB", "BB")) + + def test_open_ohne_vorgeschichte(self): + self.assertEqual(L.linie(q(6, 1, BLINDS6)), "open") + self.assertEqual(L.linie(q(6, 4, BLINDS6 + [h(1, "FOLD"), h(2, "FOLD"), h(3, "FOLD")])), "open") + + def test_bb_option_nach_limps_ist_vs_limp_nicht_bb_option(self): + self.assertEqual(L.linie(q(6, 6, BLINDS6 + [h(1, "FOLD"), h(2, "CALL", 0.02), h(3, "FOLD"), h(4, "FOLD"), h(5, "CALL", 0.02)])), "vs_limp") + + def test_bb_check_option_ohne_limper(self): + self.assertEqual(L.linie(q(6, 6, BLINDS6 + [h(i, "FOLD") for i in (1, 2, 3, 4, 5)])), "bb_option") + + def test_iso_hinter_limper(self): + self.assertEqual(L.linie(q(6, 3, BLINDS6 + [h(1, "FOLD"), h(2, "CALL", 0.02)])), "iso_limp") + + def test_raises_zaehlen(self): + o = BLINDS6 + [h(1, "RAISE", 0.05)] + self.assertEqual(L.linie(q(6, 2, o)), "vs_open") + self.assertEqual(L.linie(q(6, 1, o + [h(2, "RAISE", 0.15)])), "vs_3bet") + self.assertEqual(L.linie(q(6, 2, o + [h(2, "RAISE", 0.15), h(3, "RAISE", 0.4)])), "vs_4bet") + self.assertEqual(L.linie(q(6, 1, o + [h(2, "RAISE", 0.15), h(3, "RAISE", 0.4), h(4, "RAISE", 1.0)])), "vs_5bet_plus") + + def test_allin_ist_nur_ein_raise_ueber_dem_niveau(self): + kurz = BLINDS6 + [h(1, "RAISE", 0.05), h(2, "ALL_IN", 0.03)] # short all-in below the level: a call + self.assertEqual(L.vorgeschichte(kurz)[0], 1) + gross = BLINDS6 + [h(1, "RAISE", 0.05), h(2, "ALL_IN", 0.8)] + self.assertEqual(L.vorgeschichte(gross)[0], 2) + + def test_straddle_ist_zweiter_big_blind_und_kein_raise(self): + hist = [h(1, "POST_SB", 0.01), h(2, "POST_BB", 0.02), h(4, "POST_BB", 0.02), h(3, "FOLD")] + self.assertEqual(L.sonderform(q(5, 5, hist)), ["straddle"]) + self.assertEqual(L.vorgeschichte(hist)[0], 0) + + def test_splash_und_ante(self): + self.assertEqual(L.sonderform(q(4, 1, BLINDS6 + [h(2, "POST_ANTE", 0.5)], _splash=5)), ["splash", "ante"]) + self.assertEqual(L.sonderform(q(6, 1, BLINDS6)), []) + + def test_beschreibung_enthaelt_keine_kennungen(self): + b = L.beschreibe(q(6, 1, BLINDS6, kennung="1", seed=5)) + self.assertEqual(sorted(b), ["linie", "pos", "sonder", "spieler"]) + + +ALT = {"fold": 0.5, "call": 0.5} +NEU = {"fold": 0.3, "call": 0.5, "raise": 0.2} +V = {"fold": 0.0, "call": 0.4, "raise": 1.0} + + +class Wert(unittest.TestCase): + def test_wert_ist_summe_der_aenderungen_mal_V(self): + self.assertAlmostEqual(W.wert_ohne_wurf(ALT, NEU, V), -0.2 * 0.0 + 0.2 * 1.0) + self.assertAlmostEqual(W.wert_ohne_wurf({"a": 1.0}, {"b": 1.0}, {"a": 2.0, "b": 3.0}), 1.0) + + def test_unveraenderte_aktion_braucht_kein_V(self): + self.assertAlmostEqual(W.wert_ohne_wurf({"a": 0.5, "x": 0.5}, {"a": 0.7, "x": 0.3}, {"a": 1.0, "x": 0.0}), 0.2) + + def test_fehlendes_V_bei_geaenderter_aktion_ist_fehler(self): + with self.assertRaises(KeyError): + W.wert_ohne_wurf(ALT, NEU, {"fold": 0.0, "call": 0.4}) + + def test_se_diagonal_und_kovarianz(self): + d = {"fold": -0.2, "raise": 0.2} + se = W.wert_se(ALT, NEU, se_V={"fold": 0.5, "call": 9.0, "raise": 0.5}) + self.assertAlmostEqual(se, math.sqrt((0.2 * 0.5) ** 2 * 2)) + cov = {"fold": {"fold": 0.25, "raise": 0.25}, "raise": {"fold": 0.25, "raise": 0.25}} + # perfectly correlated, d = (-0.2, +0.2): variance of the difference cancels to 0 + self.assertAlmostEqual(W.wert_se(ALT, NEU, cov=cov), 0.0, places=9) + self.assertEqual(sorted(k for k, x in d.items() if x), ["fold", "raise"]) + + def test_se_ohne_angaben_ist_fehler(self): + with self.assertRaises(ValueError): + W.wert_se(ALT, NEU) + + def test_unveraenderte_entscheidung_gibt_keine_zeile(self): + self.assertIsNone(W.zeile({"pi_alt": ALT, "pi_neu": dict(ALT), "V": V, "se_V": {}})) + + def test_zeile_intervall(self): + z = W.zeile({"pi_alt": ALT, "pi_neu": NEU, "V": V, "se_V": {"fold": 0.1, "call": 0.1, "raise": 0.1}, "n": 3}) + self.assertAlmostEqual(z["wert_hi"] - z["wert"], W.Z95 * z["wert_se"]) + self.assertAlmostEqual(z["wert"] - z["wert_lo"], W.Z95 * z["wert_se"]) + + def test_sortierung_nach_betrag_absteigend_stabil(self): + zs = [{"wert": 0.1, "n": 1, "key": "a"}, {"wert": -0.5, "n": 1, "key": "b"}, {"wert": 0.5, "n": 4, "key": "c"}] + self.assertEqual([z["key"] for z in W.sortiert(zs)], ["c", "b", "a"]) + + def test_summen_gewichtet_mit_haeufigkeit(self): + zs = [{"wert": 0.2, "wert_se": 0.1, "n": 10}, {"wert": -0.1, "wert_se": 0.0, "n": 5}] + s = W.summen(zs, entscheidungen=100, haende=50) + self.assertAlmostEqual(s["wert_bb_pro_100"], (2.0 - 0.5) * 2) + self.assertAlmostEqual(s["se_bb_pro_100"], 1.0 * 2) # same row fully correlated: n * se + self.assertEqual((s["geaendert_eindeutig"], s["geaendert_vorkommen"], s["entscheidungen"]), (2, 15, 100)) + + def test_summen_je_gruppe_zeigt_auch_leere_gruppen(self): + zs = [{"wert": 1.0, "wert_se": 0.0, "n": 1, "linie": "open"}] + r = W.summen_je(zs, "linie", {"open": 4, "vs_open": 6}, haende=10) + self.assertAlmostEqual(r["open"]["wert_bb_pro_100"], 10.0) + self.assertEqual(r["vs_open"]["geaendert_eindeutig"], 0) + + def test_null_haende_ist_fehler(self): + with self.assertRaises(ValueError): + W.summen([], 0, 0) + + +if __name__ == "__main__": + unittest.main()