From 1229ded0b974b3e420d025ee02e1d4d720f74d34 Mon Sep 17 00:00:00 2001 From: Marc Mintel Date: Sun, 15 Nov 2026 12:44:04 +0100 Subject: [PATCH] PokerIntel je Feld gewichtet hinter POKERINTEL (aus = bitgleich), Sim-Lesemodus @hud Schaetzer (lesen/pokerintel.py): vpip/pfr tragen ~60 Motorhaende, foldToBet ~8 statt pauschal 20. hud_profile teilt Draht und Sim; ReadMode::Hud zieht verrauschte PokerIntel-Zahlen (Beta, gemessenes m) aus einer Vorsession und liest sie wie der Draht. Co-Authored-By: Claude Opus 5.5 --- entscheiden/decide.py | 2 +- lesen/roentgen.py | 1382 ++++++++++++++++++------------------ src/bin/ab_zelle.rs | 1 + src/exploit/sample.rs | 133 +++- src/sim/hud.rs | 109 +++ src/sim/memory.rs | 1110 +++++++++++++++-------------- src/sim/mod.rs | 1 + src/sim/sechsmax.rs | 2 +- src/sim/session.rs | 12 +- src/wire/decode_villain.rs | 29 +- 10 files changed, 1529 insertions(+), 1252 deletions(-) create mode 100644 src/sim/hud.rs diff --git a/entscheiden/decide.py b/entscheiden/decide.py index 86e90b58..5f9fc9b5 100644 --- a/entscheiden/decide.py +++ b/entscheiden/decide.py @@ -37,7 +37,7 @@ QUELLE = os.environ.get("COINPOKER_KERN_QUELLE", os.path.join(BASE, "..")) SCHALTER_DATEI = os.path.join(BASE, "..", "betrieb", "kern_schalter.txt") BEKANNTE_SCHALTER = ("MDF_UNREAD", "RAISE_DRAWS", "RAISE_PRIOR", "TURN_SPIEL", "GRUNDSTRATEGIE", "OPEN_JAM", "SOLVER_RIVER", "SOLVER_TURN", "SOLVER_FLOP", "SOLVER_RIVER3", "SOLVER_TURN3", "SOLVER_FLOP3", - "RAKE_LIVE") + "RAKE_LIVE", "POKERINTEL") # Pfade gehoeren nicht in die Arm-Marke. OHNE_MARKE = ("GRUNDSTRATEGIE",) diff --git a/lesen/roentgen.py b/lesen/roentgen.py index 4ce27628..3b56407c 100644 --- a/lesen/roentgen.py +++ b/lesen/roentgen.py @@ -1,691 +1,691 @@ -#!/usr/bin/env python3 -"""Engine-Röntgen: was hat in diesem Live-Lauf wirklich entschieden - und wirkt der Gegner-Read? - -Je Lauf (Läufer-PID, aus dem Schatten-Log) in klaren Zahlen: - 1. Ergebnis: Hände, netto BB, bb/100 mit 95-%-Intervall, dasselbe je A/B-Arm (`arm`). - 2. Wer entschied: Anteil je Street, aus dem Grund-Text des Zugs (`grund`): - Preflop-CFR / Range-Regeln, Turn-Solver E3 (`turn game`), Turn-/River-Veto, MDF-Boden, - Enthaltung (`setzt aus`), Postflop-Heuristik (der Rest). - 3. Read-Wirkung: jede Anfrage des Laufs (`anfrage` im Schatten-Log) geht zweimal durch den Live-Kern - - einmal wie gespielt, einmal ohne `profile` bei allen Gegnern. Gezählt wird je Street, wie viele - Entscheidungen sich ändern (Aktion; Größe getrennt). Das zeigt, ob Ausbeutung überhaupt greift. - 4. Read-Stichprobe: wie viele Hände stehen hinter den Gegnerprofilen (`hands`). - 5. Läufer-Gesundheit: Klicks, veraltete/verworfene Züge, kleinste Restuhr, abgelaufene Uhren. - -Quellen (alle unter --wurzel, Vorgabe: dieser Baum oder ROENTGEN_WURZEL): - archiv/lauf/zuege.jsonl, archiv/lauf/haende.jsonl, betrieb/scratch/shadow*.jsonl, - betrieb/kern_schalter.txt (Engine-Schalter), target/release/rechner(.exe) (Live-Kern). - -Das Nachspielen läuft in EINEM Kernprozess in Priorität Idle, gegen eine KOPIE des Kerns -(`archiv/roentgen/kern/pokerbench-roentgen-nachspiel.exe`) - der Live-Kern wird nie gesperrt oder -gebaut. Antworten werden je Anfrage zwischengespeichert (archiv/roentgen/cache/), ein zweiter Blick -auf denselben Lauf spielt nur Neues nach. - - python3 lesen/roentgen.py letzter Lauf - python3 lesen/roentgen.py --start "2026-11-14 18:57" - python3 lesen/roentgen.py --pid 43432 --json - python3 lesen/roentgen.py --liste alle Läufe im Schatten-Log - python3 lesen/roentgen.py --ohne-nachspiel ohne Read-Wirkung (schnell) - -Spezifikation: tests/roentgen_spec.py. Reine Funktionen bis auf das Laden und `kern_aufruf`. -""" -import argparse -import ast -import calendar -import collections -import glob -import hashlib -import json -import os -import shutil -import subprocess -import sys -import time - -_HIER = os.path.dirname(os.path.abspath(__file__)) -if _HIER not in sys.path: - sys.path.insert(0, _HIER) -import liveabgleich # noqa: E402 bb_pro_100: dieselbe Winrate-Rechnung wie das A/B - -BAUM = os.path.dirname(_HIER) -STREETS = ("PREFLOP", "FLOP", "TURN", "RIVER") - -# Wer entschied - Reihenfolge = Spaltenreihenfolge im Bericht. -KLASSEN = ("cfr", "regeln", "e3", "solver", "turn_veto", "river_veto", "mdf", "heuristik", "enthaltung") -KLASSEN_NAME = { - "cfr": "Preflop-CFR", "regeln": "Range-Regeln", "e3": "Turn-Solver E3", - "solver": "Solver überall (A/B/C)", - "turn_veto": "Turn-Veto", "river_veto": "River-Veto", "mdf": "MDF-Boden", - "heuristik": "Heuristik", "enthaltung": "Enthaltung", -} -# Gleiche Liste wie entscheiden/decide.py: nur Messschalter, keine beliebige Umgebung. -BEKANNTE_SCHALTER = ("MDF_UNREAD", "RAISE_DRAWS", "RAISE_PRIOR", "TURN_SPIEL", "GRUNDSTRATEGIE", "SOLVER_RIVER", "SOLVER_TURN", "SOLVER_FLOP", "SOLVER_RIVER3", "SOLVER_TURN3", "SOLVER_FLOP3") -OHNE_MARKE = ("GRUNDSTRATEGIE",) -IDLE_PRIORITY_CLASS = 0x00000040 -KERN_KOPIE = "pokerbench-roentgen-nachspiel" + (".exe" if sys.platform == "win32" else "") - - -# ---------------------------------------------------------------- Zeit - -def _lokal_epoche(s): - """'2026-11-14 18:57:07' (Ortszeit, wie zuege/shadow) -> Epoche.""" - return time.mktime(time.strptime(s[:19], "%Y-%m-%d %H:%M:%S")) - - -def _utc_epoche(s): - """'2026-11-14T19:13:02Z' (UTC, wie haende) -> Epoche.""" - return calendar.timegm(time.strptime(s[:19], "%Y-%m-%dT%H:%M:%S")) - - -# ---------------------------------------------------------------- Einlesen - -def jsonl(pfad): - """Zeilen einer jsonl-Datei als dicts; kaputte Zeilen (abgeschnittenes Ende) fallen weg.""" - aus = [] - try: - with open(pfad, encoding="utf-8", errors="replace") as f: - for zeile in f: - zeile = zeile.strip() - if not zeile: - continue - try: - d = json.loads(zeile) - except ValueError: - continue - if isinstance(d, dict): - aus.append(d) - except OSError: - pass - return aus - - -def schatten_dateien(wurzel): - """Alle Schatten-Logs, älteste zuerst (rotierte tragen das Datum im Namen, shadow.jsonl ist das jüngste).""" - ps = glob.glob(os.path.join(wurzel, "betrieb", "scratch", "shadow*.jsonl")) - return sorted(ps, key=lambda p: (os.path.basename(p) == "shadow.jsonl", os.path.basename(p))) - - -def _als_dict(x): - if isinstance(x, dict): - return x - if isinstance(x, str): - for lade in (json.loads, ast.literal_eval): - try: - d = lade(x) - if isinstance(d, dict): - return d - except (ValueError, SyntaxError): - pass - return None - - -# ---------------------------------------------------------------- Läufe - -def laeufe(schatten): - """Läufe = Läufer-PIDs im Schatten-Log: [{pid, von, bis, entscheidungen}] nach Startzeit.""" - je = collections.OrderedDict() - for e in schatten: - pid, z = e.get("pid"), e.get("zeit") - if pid is None or not isinstance(z, str): - continue - r = je.setdefault(pid, {"pid": pid, "von": z, "bis": z, "entscheidungen": 0}) - r["von"] = min(r["von"], z) - r["bis"] = max(r["bis"], z) - if "anfrage" in e: - r["entscheidungen"] += 1 - return sorted(je.values(), key=lambda r: r["von"]) - - -def waehle(liste, pid=None, start=None): - """Den Lauf zur PID; sonst den, der `start` (Ortszeit) enthält oder als erster danach beginnt; - sonst den letzten Lauf mit Entscheidungen. None, wenn nichts passt.""" - if pid is not None: - return next((r for r in liste if str(r["pid"]) == str(pid)), None) - mit = [r for r in liste if r["entscheidungen"] > 0] - if start: - for r in mit: - if r["von"] <= start <= r["bis"]: - return r - return next((r for r in mit if r["von"] >= start), None) - return mit[-1] if mit else None - - -def im_fenster(zeilen, von, bis): - """zuege-Zeilen (Ortszeit) zwischen von und bis (beide eingeschlossen).""" - return [z for z in zeilen if isinstance(z.get("zeit"), str) and von <= z["zeit"][:19] <= bis] - - -def haende_im_fenster(haende, von, bis): - """haende (UTC) im Lauf-Fenster (Ortszeit).""" - a, b = _lokal_epoche(von), _lokal_epoche(bis) - aus = [] - for h in haende: - try: - t = _utc_epoche(h["zeit"]) - except (KeyError, TypeError, ValueError): - continue - if a <= t <= b: - aus.append(h) - return aus - - -# ---------------------------------------------------------------- 1. Ergebnis - -def ergebnis(haende): - """{gesamt: bb_pro_100, arme: {arm: bb_pro_100}} aus den Händen des Laufs.""" - werte, je_arm = [], collections.defaultdict(list) - for h in haende: - v = liveabgleich.netto_bb(h) - if v is None: - continue - werte.append(v) - je_arm[h.get("arm") or "-"].append(v) - return {"gesamt": liveabgleich.bb_pro_100(werte), - "arme": {a: liveabgleich.bb_pro_100(w) for a, w in sorted(je_arm.items())}} - - -# ---------------------------------------------------------------- 2. Wer entschied - -def klasse(street, grund): - """Welcher Engine-Teil hat entschieden - aus dem Grund-Text.""" - g = grund or "" - if "setzt aus" in g: - return "enthaltung" - if "turn veto" in g: - return "turn_veto" - if "defensive veto" in g: - return "river_veto" - if "river solver" in g or "river3 solver" in g or "solver turn" in g or "solver flop" in g: - return "solver" - if "turn game" in g: - return "e3" - if "MDF-Boden" in g: - return "mdf" - if street == "PREFLOP": - return "cfr" if "CFR" in g else "regeln" - return "heuristik" - - -def wer_entschied(zuege): - """{street: {zuege, kern_zuege, klassen: {klasse: n}}} in Street-Reihenfolge, plus 'GESAMT'. - kern_zuege = Züge ohne Enthaltung: die Basis der Anteile der Engine-Teile.""" - aus = collections.OrderedDict() - for s in STREETS + ("GESAMT",): - aus[s] = {"zuege": 0, "kern_zuege": 0, "klassen": {k: 0 for k in KLASSEN}} - for z in zuege: - s = z.get("street") - if s not in STREETS: - continue - k = klasse(s, z.get("grund")) - for t in (s, "GESAMT"): - aus[t]["zuege"] += 1 - aus[t]["kern_zuege"] += k != "enthaltung" - aus[t]["klassen"][k] += 1 - return aus - - -# ---------------------------------------------------------------- 4. Read-Stichprobe - -STUFEN = ((0, 0, "ohne Profil"), (1, 9, "1-9"), (10, 29, "10-29"), (30, 99, "30-99"), (100, None, "100+")) - - -def _stufe(n): - for lo, hi, name in STUFEN: - if n >= lo and (hi is None or n <= hi): - return name - return STUFEN[0][2] - - -def lesestichprobe(zuege): - """Wie viele Hände stehen hinter den Reads? - je_gegner: Verteilung über die Gegner (Raum+Sitz, höchster `hands`-Stand im Lauf) - je_zug: Verteilung über alle Gegner-Einträge aller Züge (was die Engine tatsächlich sah) - zuege_mit_read: Züge, in denen mindestens ein Gegner ein Profil trug.""" - gegner, je_zug, mit, median_quelle = {}, collections.Counter(), 0, [] - for z in zuege: - g = z.get("gegner") - if not isinstance(g, dict) or not g: - continue - mit += 1 - for sitz, p in g.items(): - n = p.get("hands", 0) if isinstance(p, dict) else 0 - n = n if isinstance(n, (int, float)) else 0 - je_zug[_stufe(n)] += 1 - median_quelle.append(n) - schl = (z.get("raum"), str(sitz)) - gegner[schl] = max(gegner.get(schl, 0), n) - je_gegner = collections.Counter(_stufe(n) for n in gegner.values()) - ordnung = [s[2] for s in STUFEN] - median_quelle.sort() - return { - "gegner": len(gegner), - "je_gegner": {s: je_gegner.get(s, 0) for s in ordnung}, - "je_zug": {s: je_zug.get(s, 0) for s in ordnung}, - "zuege_mit_read": mit, "zuege": len(zuege), - "median_hands": median_quelle[len(median_quelle) // 2] if median_quelle else None, - } - - -# ---------------------------------------------------------------- 5. Gesundheit - -def gesundheit(schatten_lauf): - """Läufer-Gesundheit aus den Schatten-Einträgen EINES Laufs.""" - entsch = [e for e in schatten_lauf if "anfrage" in e] - geklickt = [e for e in entsch if e.get("geklickt")] - ohne_echo = [e for e in geklickt if "ohne Echo" in str(e.get("geklickt"))] - hinweise = collections.Counter(str(e.get("hinweis") or "") for e in entsch) - veraltet = sum(n for h, n in hinweise.items() if h.startswith("veraltet")) - ohne_fenster = sum(n for h, n in hinweise.items() if h.startswith("Raum ohne Fenster")) - fristen = [e["frist_rest_s"] for e in entsch if isinstance(e.get("frist_rest_s"), (int, float))] - ereig = collections.Counter(e.get("ereignis") for e in schatten_lauf if e.get("ereignis")) - enthalt = 0 - for e in entsch: - a = _als_dict(e.get("anfrage")) or {} - if a.get("legalActions") == [] and a.get("_unklar"): - enthalt += 1 - return { - "entscheidungen": len(entsch), - "enthaltungen": enthalt, - "geklickt": len(geklickt), - "ohne_echo": len(ohne_echo), - "nicht_geklickt": len(entsch) - len(geklickt), - "veraltet": veraltet, - "ohne_fenster": ohne_fenster, - "frist_min_s": min(fristen) if fristen else None, - "frist_unter_5s": sum(1 for f in fristen if f < 5.0), - "uhr_abgelaufen": sum(1 for f in fristen if f <= 0.0), - "sitout": ereig.get("sitout", 0), - "kanal_ohne_antwort": sum(1 for e in schatten_lauf - if e.get("ereignis") == "aktion_kanal" and e.get("echo") is False), - } - - -# ---------------------------------------------------------------- 3. Read-Wirkung - -def ohne_read(anfrage): - """Dieselbe Anfrage, nur ohne `profile` bei allen Gegnern.""" - a = dict(anfrage) - a["villains"] = [{k: v for k, v in g.items() if k != "profile"} if isinstance(g, dict) else g - for g in anfrage.get("villains") or []] - return a - - -def hat_read(anfrage): - return any(isinstance(g, dict) and g.get("profile") for g in anfrage.get("villains") or []) - - -def nachspielbar(schatten_lauf): - """[(eintrag, anfrage)] - nur echte Kern-Anfragen (Enthaltungen der Übersetzung gehen nie zum Kern).""" - aus = [] - for e in schatten_lauf: - if "anfrage" not in e: - continue - a = _als_dict(e["anfrage"]) - if not a or (a.get("legalActions") == [] and a.get("_unklar")): - continue - aus.append((e, a)) - return aus - - -def _schluessel(anfrage, env): - roh = json.dumps(anfrage, sort_keys=True, ensure_ascii=False) + "|" + json.dumps(env, sort_keys=True) - return hashlib.sha1(roh.encode("utf-8")).hexdigest() - - -def _gleiche_groesse(a, b): - if a is None or b is None: - return a is None and b is None - try: - return abs(float(a) - float(b)) < 1e-6 - except (TypeError, ValueError): - return a == b - - -def _zug_text(antwort): - g = antwort.get("size") - return f"{antwort.get('action')} {g:.3g}" if isinstance(g, (int, float)) else str(antwort.get("action")) - - -def lese_wirkung(paare, kern, envs=None, cache=None, beispiele=12): - """Spielt jede Anfrage zweimal durch `kern(anfragen, env) -> antworten`: wie gespielt und ohne Read. - - paare: [(schatten_eintrag, anfrage)]; envs: je Paar die Kern-Umgebung (Vorgabe {}). - cache: dict schluessel -> antwort (wird ergänzt), damit ein Lauf nur einmal gerechnet wird. - Liefert je Street: entscheidungen, mit_read, aktion_anders, groesse_anders, treu (Nachspiel == - live geklickte Kern-Antwort), plus Beispiele der geänderten Züge.""" - cache = {} if cache is None else cache - envs = envs or [{}] * len(paare) - # Fehlende Antworten je Umgebung gebündelt rechnen (ein Kernprozess je Umgebung und Durchgang). - offen = collections.OrderedDict() - schl = [] - for (e, a), env in zip(paare, envs): - k_mit, k_ohne = _schluessel(a, env), _schluessel(ohne_read(a), env) - schl.append((k_mit, k_ohne)) - for k, anf in ((k_mit, a), (k_ohne, ohne_read(a))): - if k not in cache: - envk = json.dumps(env, sort_keys=True) - offen.setdefault(envk, collections.OrderedDict())[k] = anf - for envk, auftraege in offen.items(): - antworten = kern(list(auftraege.values()), json.loads(envk)) - if len(antworten) != len(auftraege): - raise RuntimeError(f"Kern gab {len(antworten)} Antworten auf {len(auftraege)} Anfragen") - for k, ant in zip(auftraege.keys(), antworten): - cache[k] = ant - aus = collections.OrderedDict() - for s in STREETS + ("GESAMT",): - aus[s] = {"entscheidungen": 0, "mit_read": 0, "aktion_anders": 0, "groesse_anders": 0, "treu": 0} - bsp = [] - for (e, a), (k_mit, k_ohne) in zip(paare, schl): - s = a.get("street") - if s not in STREETS: - continue - mit, ohne = cache[k_mit] or {}, cache[k_ohne] or {} - live = _als_dict(e.get("antwort")) or {} - akt = mit.get("action") != ohne.get("action") - gr = not akt and not _gleiche_groesse(mit.get("size"), ohne.get("size")) - treu = live.get("action") == mit.get("action") - for t in (s, "GESAMT"): - r = aus[t] - r["entscheidungen"] += 1 - r["mit_read"] += hat_read(a) - r["aktion_anders"] += akt - r["groesse_anders"] += gr - r["treu"] += treu - if akt and len(bsp) < beispiele: - bsp.append({"zeit": e.get("zeit"), "raum": e.get("raum"), "street": s, - "mit": _zug_text(mit), "ohne": _zug_text(ohne), - "grund_mit": mit.get("reason"), "grund_ohne": ohne.get("reason")}) - return {"streets": aus, "beispiele": bsp} - - -# ---------------------------------------------------------------- Kern - -def lies_schalter(pfad): - """betrieb/kern_schalter.txt -> {K: V} (nur bekannte Schalter), wie entscheiden/decide.py.""" - schalter = {} - try: - with open(pfad, encoding="utf-8") as f: - for zeile in f: - zeile = zeile.split("#", 1)[0].strip() - if "=" not in zeile: - continue - k, v = (t.strip() for t in zeile.split("=", 1)) - if k in BEKANNTE_SCHALTER and v: - schalter[k] = v - except OSError: - pass - return schalter - - -def env_fuer_arm(arm, datei_schalter): - """Kern-Umgebung, mit der ein Arm gespielt wurde. Ein Arm 'schalter:K=V,...' sagt genau, welche - Schalter galten (die Datei kann sich seither geändert haben); Pfade (GRUNDSTRATEGIE) stehen nie in - der Marke und kommen aus der Datei. Ohne Schalter-Marke gilt die Datei.""" - if isinstance(arm, str) and arm.startswith("schalter:"): - env = {} - for teil in arm[len("schalter:"):].split(","): - if "=" in teil: - k, v = (t.strip() for t in teil.split("=", 1)) - if k in BEKANNTE_SCHALTER: - env[k] = v - for k in OHNE_MARKE: - if k in datei_schalter: - env[k] = datei_schalter[k] - return env - return dict(datei_schalter) - - -def arm_je_zug(zuege): - """(raum, hand, street) -> arm aus den zuege-Zeilen.""" - return {(z.get("raum"), str(z.get("hand")), z.get("street")): z.get("arm") for z in zuege} - - -def kern_kopie(quelle, ziel_ordner): - """Kopiert den Live-Kern nach ziel_ordner/pokerbench-roentgen-nachspiel(.exe), wenn er sich - geändert hat - so sperrt das Nachspielen nie das Live-Binary (Windows) und baut nichts.""" - os.makedirs(ziel_ordner, exist_ok=True) - ziel = os.path.join(ziel_ordner, KERN_KOPIE) - q = os.stat(quelle) - try: - z = os.stat(ziel) - if z.st_size == q.st_size and abs(z.st_mtime - q.st_mtime) < 1: - return ziel - except OSError: - pass - shutil.copy2(quelle, ziel) - return ziel - - -def kern_aufruf(binary, timeout_je=5.0): - """kern(anfragen, env) -> antworten: ein Prozess je Bündel, Priorität Idle.""" - def kern(anfragen, env): - if not anfragen: - return [] - umgebung = {k: v for k, v in os.environ.items() if k not in BEKANNTE_SCHALTER} - umgebung.update(env) - extra = {} - if sys.platform == "win32": - extra["creationflags"] = IDLE_PRIORITY_CLASS - else: - extra["preexec_fn"] = lambda: os.nice(19) - r = subprocess.run([binary], input="\n".join(json.dumps(a) for a in anfragen) + "\n", - capture_output=True, text=True, encoding="utf-8", env=umgebung, - timeout=60 + timeout_je * len(anfragen), **extra) - if r.returncode != 0: - raise RuntimeError(f"der Kern scheiterte: {r.stderr.strip()[:300]}") - aus = [] - for zeile in r.stdout.split("\n"): - if not zeile.strip(): - continue - try: - aus.append(json.loads(zeile)) - except ValueError: - aus.append({"action": "UNLESBAR"}) - return aus - return kern - - -def kern_pfad(wurzel): - return os.path.join(wurzel, "target", "release", "rechner.exe" if sys.platform == "win32" else "rechner") - - -# ---------------------------------------------------------------- Bericht - -def cache_pfad(cache_ordner, pid, kern_id=""): - """Ein Cache je Lauf und Kern-Stand: ein neu gebauter Kern rechnet neu.""" - return os.path.join(cache_ordner, f"nachspiel-{pid}{'-' + kern_id if kern_id else ''}.json") - - -def _cache_laden(pfad): - try: - with open(pfad, encoding="utf-8") as f: - d = json.load(f) - return d if isinstance(d, dict) else {} - except (OSError, ValueError): - return {} - - -def _cache_schreiben(pfad, d): - os.makedirs(os.path.dirname(pfad), exist_ok=True) - tmp = pfad + ".tmp" - with open(tmp, "w", encoding="utf-8") as f: - json.dump(d, f, ensure_ascii=False) - os.replace(tmp, pfad) - - -def daten(wurzel): - """Alles, was der Bericht von der Platte braucht.""" - lauf = os.path.join(wurzel, "archiv", "lauf") - schatten = [] - for p in schatten_dateien(wurzel): - schatten.extend(jsonl(p)) - return {"zuege": jsonl(os.path.join(lauf, "zuege.jsonl")), - "haende": jsonl(os.path.join(lauf, "haende.jsonl")), - "schatten": schatten} - - -def bericht(d, pid=None, start=None, bis=None, kern=None, kern_info=None, datei_schalter=None, - cache=None): - """Der ganze Bericht als dict. `kern` None = ohne Read-Wirkung (kein Nachspielen).""" - liste = laeufe(d["schatten"]) - lauf = waehle(liste, pid=pid, start=start) - if lauf is None: - if not start: - return {"fehler": "kein Lauf im Schatten-Log gefunden", "laeufe": liste} - # Ohne Schatten-Log: nur das Zeitfenster aus zuege (keine Gesundheit, kein Nachspiel). - lauf = {"pid": None, "von": start, "bis": bis or "9999", "entscheidungen": 0} - von, ende = lauf["von"], min(lauf["bis"], bis) if bis else lauf["bis"] - schatten_lauf = [e for e in d["schatten"] if e.get("pid") == lauf["pid"] - and isinstance(e.get("zeit"), str) and von <= e["zeit"] <= ende] - zuege = im_fenster(d["zuege"], von, ende) - haende = haende_im_fenster(d["haende"], von, ende if ende != "9999" else "9999-12-31 23:59:59") - aus = { - "lauf": {"pid": lauf["pid"], "von": von, "bis": ende}, - "ergebnis": ergebnis(haende), - "wer": wer_entschied(zuege), - "stichprobe": lesestichprobe(zuege), - "gesundheit": gesundheit(schatten_lauf), - "wirkung": None, - } - if kern is not None: - paare = nachspielbar(schatten_lauf) - arme = arm_je_zug(zuege) - haupt = collections.Counter(z.get("arm") for z in zuege).most_common(1) - haupt = haupt[0][0] if haupt else None - envs = [] - for e, a in paare: - teile = str(e.get("zug") or "").split("|") - arm = arme.get((e.get("raum"), teile[1] if len(teile) > 1 else None, a.get("street")), haupt) - envs.append(env_fuer_arm(arm, datei_schalter or {})) - aus["wirkung"] = lese_wirkung(paare, kern, envs, cache) - aus["wirkung"]["kern"] = kern_info - aus["wirkung"]["umgebungen"] = sorted({json.dumps(x, sort_keys=True) for x in envs}) - return aus - - -def rechnen(wurzel, pid=None, start=None, bis=None, nachspiel=True, cache_ordner=None, kern_quelle=None): - """Bericht mit Platte: liest, kopiert den Kern, spielt nach (mit Plattencache).""" - d = daten(wurzel) - if not nachspiel: - return bericht(d, pid, start, bis) - cache_ordner = cache_ordner or os.environ.get("ROENTGEN_CACHE") or os.path.join(BAUM, "archiv", "roentgen") - quelle = kern_quelle or kern_pfad(wurzel) - if not os.path.exists(quelle): - r = bericht(d, pid, start, bis) - r["wirkung"] = {"fehler": f"kein Kern unter {quelle}"} - return r - binary = kern_kopie(quelle, os.path.join(cache_ordner, "kern")) - info = {"quelle": quelle, "gebaut": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(os.path.getmtime(quelle)))} - schalter = lies_schalter(os.path.join(wurzel, "betrieb", "kern_schalter.txt")) - vorab = waehle(laeufe(d["schatten"]), pid=pid, start=start) - st = os.stat(quelle) - kern_id = hashlib.sha1(f"{st.st_size}|{int(st.st_mtime)}".encode()).hexdigest()[:8] - cpfad = cache_pfad(os.path.join(cache_ordner, "cache"), vorab["pid"] if vorab else "fenster", kern_id) - cache = _cache_laden(cpfad) - vorher = len(cache) - r = bericht(d, pid, start, bis, kern_aufruf(binary), info, schalter, cache) - if len(cache) != vorher: - _cache_schreiben(cpfad, cache) - return r - - -# ---------------------------------------------------------------- Text - -def _pz(n, gesamt): - return f"{100.0 * n / gesamt:5.1f}%" if gesamt else " -" - - -def _bb(b): - if not b or b["n"] == 0: - return "keine Hände" - s = f"{b['n']} Hände, netto {b['netto_bb']:+.1f} BB, {b['bb100']:+.1f} bb/100" - if b["halb95"] is not None: - s += f" (95 %: {b['tief']:+.0f} bis {b['hoch']:+.0f})" - return s - - -def text(r): - if "fehler" in r: - return r["fehler"] - L = r["lauf"] - z = [f"ENGINE-RÖNTGEN Lauf pid {L['pid']} {L['von']} bis {L['bis']}", ""] - z.append("1. ERGEBNIS") - z.append(" gesamt: " + _bb(r["ergebnis"]["gesamt"])) - for arm, b in r["ergebnis"]["arme"].items(): - z.append(f" Arm {arm}: " + _bb(b)) - z.append("") - z.append("2. WER ENTSCHIED (Anteil an den Kern-Zügen je Street; Enthaltung: Anteil an allen Zügen)") - kopf = f" {'Street':<8}{'Züge':>6}" + "".join(f"{KLASSEN_NAME[k]:>16}" for k in KLASSEN) - z.append(kopf) - for s, w in r["wer"].items(): - n = w["zuege"] - zeile = f" {s:<8}{n:>6}" + "".join( - f"{(str(w['klassen'][k]) + ' ' + _pz(w['klassen'][k], n if k == 'enthaltung' else w['kern_zuege']).strip()) if w['klassen'][k] else '-':>16}" - for k in KLASSEN) - z.append(zeile) - z.append("") - z.append("3. READ-WIRKUNG (jede Anfrage nochmal durch den Kern, einmal ohne Gegnerprofile)") - w = r.get("wirkung") - if not w: - z.append(" nicht gerechnet (--ohne-nachspiel, oder das Nachspielen läuft noch)") - elif "fehler" in w: - z.append(" " + w["fehler"]) - else: - z.append(f" {'Street':<8}{'Entsch.':>8}{'mit Read':>10}{'Aktion anders':>16}{'nur Größe anders':>18}{'Nachspiel=live':>16}") - for s, x in w["streets"].items(): - n = x["entscheidungen"] - z.append(f" {s:<8}{n:>8}{x['mit_read']:>10}{(str(x['aktion_anders']) + ' ' + _pz(x['aktion_anders'], n).strip()):>16}" - f"{(str(x['groesse_anders']) + ' ' + _pz(x['groesse_anders'], n).strip()):>18}{_pz(x['treu'], n):>16}") - g = w["streets"]["GESAMT"] - z.append(f" => der Gegner-Read ändert {g['aktion_anders']} von {g['entscheidungen']} Entscheidungen " - f"({_pz(g['aktion_anders'], g['entscheidungen']).strip()}).") - if w.get("kern"): - z.append(f" Kern: {w['kern']['quelle']} (gebaut {w['kern']['gebaut']}); Schalter: " - + "; ".join(w.get("umgebungen") or [])) - for b in w["beispiele"]: - z.append(f" - {b['zeit']} {b['street']}: mit Read {b['mit']}, ohne {b['ohne']} [{(b['grund_mit'] or '')[:70]}]") - z.append("") - st = r["stichprobe"] - z.append("4. READ-STICHPROBE (Hände hinter den Gegnerprofilen)") - z.append(f" Züge mit Profil: {st['zuege_mit_read']} von {st['zuege']}; Median hands je Gegner-Eintrag: {st['median_hands']}") - z.append(f" je Gegner ({st['gegner']}): " + " ".join(f"{k}: {v}" for k, v in st["je_gegner"].items())) - z.append(" je Gegner-Eintrag im Zug: " + " ".join(f"{k}: {v}" for k, v in st["je_zug"].items())) - z.append("") - g = r["gesundheit"] - z.append("5. LÄUFER") - z.append(f" Entscheidungen {g['entscheidungen']} (davon Enthaltungen {g['enthaltungen']}), geklickt {g['geklickt']}" - f" (ohne Echo {g['ohne_echo']}), nicht geklickt {g['nicht_geklickt']}") - z.append(f" veraltet/verworfen {g['veraltet']}, Raum ohne Fenster {g['ohne_fenster']}, Kanal ohne Antwort {g['kanal_ohne_antwort']}") - fm = "-" if g["frist_min_s"] is None else f"{g['frist_min_s']:.1f} s" - z.append(f" kleinste Restuhr {fm}, unter 5 s: {g['frist_unter_5s']}, Uhr abgelaufen: {g['uhr_abgelaufen']}, Sitout-Ereignisse: {g['sitout']}") - return "\n".join(z) - - -def main(argv=None): - a = argparse.ArgumentParser(description="Engine-Röntgen je Live-Lauf") - a.add_argument("--wurzel", default=os.environ.get("ROENTGEN_WURZEL", BAUM), - help="Baum mit archiv/lauf, betrieb/scratch, target/release (Vorgabe: dieser)") - a.add_argument("--pid", help="Läufer-PID") - a.add_argument("--start", help="Startzeit (Ortszeit) 'JJJJ-MM-TT HH:MM' - der Lauf, der sie enthält") - a.add_argument("--bis", help="nur bis zu dieser Ortszeit") - a.add_argument("--kern", help="Kern-Binary (Vorgabe: /target/release/rechner)") - a.add_argument("--ohne-nachspiel", action="store_true", help="Read-Wirkung nicht rechnen") - a.add_argument("--json", action="store_true") - a.add_argument("--liste", action="store_true", help="Läufe im Schatten-Log zeigen") - x = a.parse_args(argv) - if x.liste: - for r in laeufe(daten(x.wurzel)["schatten"]): - print(f"pid {r['pid']:>7} {r['von']} bis {r['bis']} {r['entscheidungen']} Entscheidungen") - return 0 - r = rechnen(x.wurzel, pid=x.pid, start=x.start, bis=x.bis, nachspiel=not x.ohne_nachspiel, - kern_quelle=x.kern) - if x.json: - print(json.dumps(r, ensure_ascii=False, indent=1, default=str)) - else: - sys.stdout.reconfigure(encoding="utf-8", errors="replace") if hasattr(sys.stdout, "reconfigure") else None - print(text(r)) - return 0 if "fehler" not in r else 1 - - -if __name__ == "__main__": - sys.exit(main()) +#!/usr/bin/env python3 +"""Engine-Röntgen: was hat in diesem Live-Lauf wirklich entschieden - und wirkt der Gegner-Read? + +Je Lauf (Läufer-PID, aus dem Schatten-Log) in klaren Zahlen: + 1. Ergebnis: Hände, netto BB, bb/100 mit 95-%-Intervall, dasselbe je A/B-Arm (`arm`). + 2. Wer entschied: Anteil je Street, aus dem Grund-Text des Zugs (`grund`): + Preflop-CFR / Range-Regeln, Turn-Solver E3 (`turn game`), Turn-/River-Veto, MDF-Boden, + Enthaltung (`setzt aus`), Postflop-Heuristik (der Rest). + 3. Read-Wirkung: jede Anfrage des Laufs (`anfrage` im Schatten-Log) geht zweimal durch den Live-Kern - + einmal wie gespielt, einmal ohne `profile` bei allen Gegnern. Gezählt wird je Street, wie viele + Entscheidungen sich ändern (Aktion; Größe getrennt). Das zeigt, ob Ausbeutung überhaupt greift. + 4. Read-Stichprobe: wie viele Hände stehen hinter den Gegnerprofilen (`hands`). + 5. Läufer-Gesundheit: Klicks, veraltete/verworfene Züge, kleinste Restuhr, abgelaufene Uhren. + +Quellen (alle unter --wurzel, Vorgabe: dieser Baum oder ROENTGEN_WURZEL): + archiv/lauf/zuege.jsonl, archiv/lauf/haende.jsonl, betrieb/scratch/shadow*.jsonl, + betrieb/kern_schalter.txt (Engine-Schalter), target/release/rechner(.exe) (Live-Kern). + +Das Nachspielen läuft in EINEM Kernprozess in Priorität Idle, gegen eine KOPIE des Kerns +(`archiv/roentgen/kern/pokerbench-roentgen-nachspiel.exe`) - der Live-Kern wird nie gesperrt oder +gebaut. Antworten werden je Anfrage zwischengespeichert (archiv/roentgen/cache/), ein zweiter Blick +auf denselben Lauf spielt nur Neues nach. + + python3 lesen/roentgen.py letzter Lauf + python3 lesen/roentgen.py --start "2026-11-14 18:57" + python3 lesen/roentgen.py --pid 43432 --json + python3 lesen/roentgen.py --liste alle Läufe im Schatten-Log + python3 lesen/roentgen.py --ohne-nachspiel ohne Read-Wirkung (schnell) + +Spezifikation: tests/roentgen_spec.py. Reine Funktionen bis auf das Laden und `kern_aufruf`. +""" +import argparse +import ast +import calendar +import collections +import glob +import hashlib +import json +import os +import shutil +import subprocess +import sys +import time + +_HIER = os.path.dirname(os.path.abspath(__file__)) +if _HIER not in sys.path: + sys.path.insert(0, _HIER) +import liveabgleich # noqa: E402 bb_pro_100: dieselbe Winrate-Rechnung wie das A/B + +BAUM = os.path.dirname(_HIER) +STREETS = ("PREFLOP", "FLOP", "TURN", "RIVER") + +# Wer entschied - Reihenfolge = Spaltenreihenfolge im Bericht. +KLASSEN = ("cfr", "regeln", "e3", "solver", "turn_veto", "river_veto", "mdf", "heuristik", "enthaltung") +KLASSEN_NAME = { + "cfr": "Preflop-CFR", "regeln": "Range-Regeln", "e3": "Turn-Solver E3", + "solver": "Solver überall (A/B/C)", + "turn_veto": "Turn-Veto", "river_veto": "River-Veto", "mdf": "MDF-Boden", + "heuristik": "Heuristik", "enthaltung": "Enthaltung", +} +# Gleiche Liste wie entscheiden/decide.py: nur Messschalter, keine beliebige Umgebung. +BEKANNTE_SCHALTER = ("MDF_UNREAD", "RAISE_DRAWS", "RAISE_PRIOR", "TURN_SPIEL", "GRUNDSTRATEGIE", "SOLVER_RIVER", "SOLVER_TURN", "SOLVER_FLOP", "SOLVER_RIVER3", "SOLVER_TURN3", "SOLVER_FLOP3", "POKERINTEL") +OHNE_MARKE = ("GRUNDSTRATEGIE",) +IDLE_PRIORITY_CLASS = 0x00000040 +KERN_KOPIE = "pokerbench-roentgen-nachspiel" + (".exe" if sys.platform == "win32" else "") + + +# ---------------------------------------------------------------- Zeit + +def _lokal_epoche(s): + """'2026-11-14 18:57:07' (Ortszeit, wie zuege/shadow) -> Epoche.""" + return time.mktime(time.strptime(s[:19], "%Y-%m-%d %H:%M:%S")) + + +def _utc_epoche(s): + """'2026-11-14T19:13:02Z' (UTC, wie haende) -> Epoche.""" + return calendar.timegm(time.strptime(s[:19], "%Y-%m-%dT%H:%M:%S")) + + +# ---------------------------------------------------------------- Einlesen + +def jsonl(pfad): + """Zeilen einer jsonl-Datei als dicts; kaputte Zeilen (abgeschnittenes Ende) fallen weg.""" + aus = [] + try: + with open(pfad, encoding="utf-8", errors="replace") as f: + for zeile in f: + zeile = zeile.strip() + if not zeile: + continue + try: + d = json.loads(zeile) + except ValueError: + continue + if isinstance(d, dict): + aus.append(d) + except OSError: + pass + return aus + + +def schatten_dateien(wurzel): + """Alle Schatten-Logs, älteste zuerst (rotierte tragen das Datum im Namen, shadow.jsonl ist das jüngste).""" + ps = glob.glob(os.path.join(wurzel, "betrieb", "scratch", "shadow*.jsonl")) + return sorted(ps, key=lambda p: (os.path.basename(p) == "shadow.jsonl", os.path.basename(p))) + + +def _als_dict(x): + if isinstance(x, dict): + return x + if isinstance(x, str): + for lade in (json.loads, ast.literal_eval): + try: + d = lade(x) + if isinstance(d, dict): + return d + except (ValueError, SyntaxError): + pass + return None + + +# ---------------------------------------------------------------- Läufe + +def laeufe(schatten): + """Läufe = Läufer-PIDs im Schatten-Log: [{pid, von, bis, entscheidungen}] nach Startzeit.""" + je = collections.OrderedDict() + for e in schatten: + pid, z = e.get("pid"), e.get("zeit") + if pid is None or not isinstance(z, str): + continue + r = je.setdefault(pid, {"pid": pid, "von": z, "bis": z, "entscheidungen": 0}) + r["von"] = min(r["von"], z) + r["bis"] = max(r["bis"], z) + if "anfrage" in e: + r["entscheidungen"] += 1 + return sorted(je.values(), key=lambda r: r["von"]) + + +def waehle(liste, pid=None, start=None): + """Den Lauf zur PID; sonst den, der `start` (Ortszeit) enthält oder als erster danach beginnt; + sonst den letzten Lauf mit Entscheidungen. None, wenn nichts passt.""" + if pid is not None: + return next((r for r in liste if str(r["pid"]) == str(pid)), None) + mit = [r for r in liste if r["entscheidungen"] > 0] + if start: + for r in mit: + if r["von"] <= start <= r["bis"]: + return r + return next((r for r in mit if r["von"] >= start), None) + return mit[-1] if mit else None + + +def im_fenster(zeilen, von, bis): + """zuege-Zeilen (Ortszeit) zwischen von und bis (beide eingeschlossen).""" + return [z for z in zeilen if isinstance(z.get("zeit"), str) and von <= z["zeit"][:19] <= bis] + + +def haende_im_fenster(haende, von, bis): + """haende (UTC) im Lauf-Fenster (Ortszeit).""" + a, b = _lokal_epoche(von), _lokal_epoche(bis) + aus = [] + for h in haende: + try: + t = _utc_epoche(h["zeit"]) + except (KeyError, TypeError, ValueError): + continue + if a <= t <= b: + aus.append(h) + return aus + + +# ---------------------------------------------------------------- 1. Ergebnis + +def ergebnis(haende): + """{gesamt: bb_pro_100, arme: {arm: bb_pro_100}} aus den Händen des Laufs.""" + werte, je_arm = [], collections.defaultdict(list) + for h in haende: + v = liveabgleich.netto_bb(h) + if v is None: + continue + werte.append(v) + je_arm[h.get("arm") or "-"].append(v) + return {"gesamt": liveabgleich.bb_pro_100(werte), + "arme": {a: liveabgleich.bb_pro_100(w) for a, w in sorted(je_arm.items())}} + + +# ---------------------------------------------------------------- 2. Wer entschied + +def klasse(street, grund): + """Welcher Engine-Teil hat entschieden - aus dem Grund-Text.""" + g = grund or "" + if "setzt aus" in g: + return "enthaltung" + if "turn veto" in g: + return "turn_veto" + if "defensive veto" in g: + return "river_veto" + if "river solver" in g or "river3 solver" in g or "solver turn" in g or "solver flop" in g: + return "solver" + if "turn game" in g: + return "e3" + if "MDF-Boden" in g: + return "mdf" + if street == "PREFLOP": + return "cfr" if "CFR" in g else "regeln" + return "heuristik" + + +def wer_entschied(zuege): + """{street: {zuege, kern_zuege, klassen: {klasse: n}}} in Street-Reihenfolge, plus 'GESAMT'. + kern_zuege = Züge ohne Enthaltung: die Basis der Anteile der Engine-Teile.""" + aus = collections.OrderedDict() + for s in STREETS + ("GESAMT",): + aus[s] = {"zuege": 0, "kern_zuege": 0, "klassen": {k: 0 for k in KLASSEN}} + for z in zuege: + s = z.get("street") + if s not in STREETS: + continue + k = klasse(s, z.get("grund")) + for t in (s, "GESAMT"): + aus[t]["zuege"] += 1 + aus[t]["kern_zuege"] += k != "enthaltung" + aus[t]["klassen"][k] += 1 + return aus + + +# ---------------------------------------------------------------- 4. Read-Stichprobe + +STUFEN = ((0, 0, "ohne Profil"), (1, 9, "1-9"), (10, 29, "10-29"), (30, 99, "30-99"), (100, None, "100+")) + + +def _stufe(n): + for lo, hi, name in STUFEN: + if n >= lo and (hi is None or n <= hi): + return name + return STUFEN[0][2] + + +def lesestichprobe(zuege): + """Wie viele Hände stehen hinter den Reads? + je_gegner: Verteilung über die Gegner (Raum+Sitz, höchster `hands`-Stand im Lauf) + je_zug: Verteilung über alle Gegner-Einträge aller Züge (was die Engine tatsächlich sah) + zuege_mit_read: Züge, in denen mindestens ein Gegner ein Profil trug.""" + gegner, je_zug, mit, median_quelle = {}, collections.Counter(), 0, [] + for z in zuege: + g = z.get("gegner") + if not isinstance(g, dict) or not g: + continue + mit += 1 + for sitz, p in g.items(): + n = p.get("hands", 0) if isinstance(p, dict) else 0 + n = n if isinstance(n, (int, float)) else 0 + je_zug[_stufe(n)] += 1 + median_quelle.append(n) + schl = (z.get("raum"), str(sitz)) + gegner[schl] = max(gegner.get(schl, 0), n) + je_gegner = collections.Counter(_stufe(n) for n in gegner.values()) + ordnung = [s[2] for s in STUFEN] + median_quelle.sort() + return { + "gegner": len(gegner), + "je_gegner": {s: je_gegner.get(s, 0) for s in ordnung}, + "je_zug": {s: je_zug.get(s, 0) for s in ordnung}, + "zuege_mit_read": mit, "zuege": len(zuege), + "median_hands": median_quelle[len(median_quelle) // 2] if median_quelle else None, + } + + +# ---------------------------------------------------------------- 5. Gesundheit + +def gesundheit(schatten_lauf): + """Läufer-Gesundheit aus den Schatten-Einträgen EINES Laufs.""" + entsch = [e for e in schatten_lauf if "anfrage" in e] + geklickt = [e for e in entsch if e.get("geklickt")] + ohne_echo = [e for e in geklickt if "ohne Echo" in str(e.get("geklickt"))] + hinweise = collections.Counter(str(e.get("hinweis") or "") for e in entsch) + veraltet = sum(n for h, n in hinweise.items() if h.startswith("veraltet")) + ohne_fenster = sum(n for h, n in hinweise.items() if h.startswith("Raum ohne Fenster")) + fristen = [e["frist_rest_s"] for e in entsch if isinstance(e.get("frist_rest_s"), (int, float))] + ereig = collections.Counter(e.get("ereignis") for e in schatten_lauf if e.get("ereignis")) + enthalt = 0 + for e in entsch: + a = _als_dict(e.get("anfrage")) or {} + if a.get("legalActions") == [] and a.get("_unklar"): + enthalt += 1 + return { + "entscheidungen": len(entsch), + "enthaltungen": enthalt, + "geklickt": len(geklickt), + "ohne_echo": len(ohne_echo), + "nicht_geklickt": len(entsch) - len(geklickt), + "veraltet": veraltet, + "ohne_fenster": ohne_fenster, + "frist_min_s": min(fristen) if fristen else None, + "frist_unter_5s": sum(1 for f in fristen if f < 5.0), + "uhr_abgelaufen": sum(1 for f in fristen if f <= 0.0), + "sitout": ereig.get("sitout", 0), + "kanal_ohne_antwort": sum(1 for e in schatten_lauf + if e.get("ereignis") == "aktion_kanal" and e.get("echo") is False), + } + + +# ---------------------------------------------------------------- 3. Read-Wirkung + +def ohne_read(anfrage): + """Dieselbe Anfrage, nur ohne `profile` bei allen Gegnern.""" + a = dict(anfrage) + a["villains"] = [{k: v for k, v in g.items() if k != "profile"} if isinstance(g, dict) else g + for g in anfrage.get("villains") or []] + return a + + +def hat_read(anfrage): + return any(isinstance(g, dict) and g.get("profile") for g in anfrage.get("villains") or []) + + +def nachspielbar(schatten_lauf): + """[(eintrag, anfrage)] - nur echte Kern-Anfragen (Enthaltungen der Übersetzung gehen nie zum Kern).""" + aus = [] + for e in schatten_lauf: + if "anfrage" not in e: + continue + a = _als_dict(e["anfrage"]) + if not a or (a.get("legalActions") == [] and a.get("_unklar")): + continue + aus.append((e, a)) + return aus + + +def _schluessel(anfrage, env): + roh = json.dumps(anfrage, sort_keys=True, ensure_ascii=False) + "|" + json.dumps(env, sort_keys=True) + return hashlib.sha1(roh.encode("utf-8")).hexdigest() + + +def _gleiche_groesse(a, b): + if a is None or b is None: + return a is None and b is None + try: + return abs(float(a) - float(b)) < 1e-6 + except (TypeError, ValueError): + return a == b + + +def _zug_text(antwort): + g = antwort.get("size") + return f"{antwort.get('action')} {g:.3g}" if isinstance(g, (int, float)) else str(antwort.get("action")) + + +def lese_wirkung(paare, kern, envs=None, cache=None, beispiele=12): + """Spielt jede Anfrage zweimal durch `kern(anfragen, env) -> antworten`: wie gespielt und ohne Read. + + paare: [(schatten_eintrag, anfrage)]; envs: je Paar die Kern-Umgebung (Vorgabe {}). + cache: dict schluessel -> antwort (wird ergänzt), damit ein Lauf nur einmal gerechnet wird. + Liefert je Street: entscheidungen, mit_read, aktion_anders, groesse_anders, treu (Nachspiel == + live geklickte Kern-Antwort), plus Beispiele der geänderten Züge.""" + cache = {} if cache is None else cache + envs = envs or [{}] * len(paare) + # Fehlende Antworten je Umgebung gebündelt rechnen (ein Kernprozess je Umgebung und Durchgang). + offen = collections.OrderedDict() + schl = [] + for (e, a), env in zip(paare, envs): + k_mit, k_ohne = _schluessel(a, env), _schluessel(ohne_read(a), env) + schl.append((k_mit, k_ohne)) + for k, anf in ((k_mit, a), (k_ohne, ohne_read(a))): + if k not in cache: + envk = json.dumps(env, sort_keys=True) + offen.setdefault(envk, collections.OrderedDict())[k] = anf + for envk, auftraege in offen.items(): + antworten = kern(list(auftraege.values()), json.loads(envk)) + if len(antworten) != len(auftraege): + raise RuntimeError(f"Kern gab {len(antworten)} Antworten auf {len(auftraege)} Anfragen") + for k, ant in zip(auftraege.keys(), antworten): + cache[k] = ant + aus = collections.OrderedDict() + for s in STREETS + ("GESAMT",): + aus[s] = {"entscheidungen": 0, "mit_read": 0, "aktion_anders": 0, "groesse_anders": 0, "treu": 0} + bsp = [] + for (e, a), (k_mit, k_ohne) in zip(paare, schl): + s = a.get("street") + if s not in STREETS: + continue + mit, ohne = cache[k_mit] or {}, cache[k_ohne] or {} + live = _als_dict(e.get("antwort")) or {} + akt = mit.get("action") != ohne.get("action") + gr = not akt and not _gleiche_groesse(mit.get("size"), ohne.get("size")) + treu = live.get("action") == mit.get("action") + for t in (s, "GESAMT"): + r = aus[t] + r["entscheidungen"] += 1 + r["mit_read"] += hat_read(a) + r["aktion_anders"] += akt + r["groesse_anders"] += gr + r["treu"] += treu + if akt and len(bsp) < beispiele: + bsp.append({"zeit": e.get("zeit"), "raum": e.get("raum"), "street": s, + "mit": _zug_text(mit), "ohne": _zug_text(ohne), + "grund_mit": mit.get("reason"), "grund_ohne": ohne.get("reason")}) + return {"streets": aus, "beispiele": bsp} + + +# ---------------------------------------------------------------- Kern + +def lies_schalter(pfad): + """betrieb/kern_schalter.txt -> {K: V} (nur bekannte Schalter), wie entscheiden/decide.py.""" + schalter = {} + try: + with open(pfad, encoding="utf-8") as f: + for zeile in f: + zeile = zeile.split("#", 1)[0].strip() + if "=" not in zeile: + continue + k, v = (t.strip() for t in zeile.split("=", 1)) + if k in BEKANNTE_SCHALTER and v: + schalter[k] = v + except OSError: + pass + return schalter + + +def env_fuer_arm(arm, datei_schalter): + """Kern-Umgebung, mit der ein Arm gespielt wurde. Ein Arm 'schalter:K=V,...' sagt genau, welche + Schalter galten (die Datei kann sich seither geändert haben); Pfade (GRUNDSTRATEGIE) stehen nie in + der Marke und kommen aus der Datei. Ohne Schalter-Marke gilt die Datei.""" + if isinstance(arm, str) and arm.startswith("schalter:"): + env = {} + for teil in arm[len("schalter:"):].split(","): + if "=" in teil: + k, v = (t.strip() for t in teil.split("=", 1)) + if k in BEKANNTE_SCHALTER: + env[k] = v + for k in OHNE_MARKE: + if k in datei_schalter: + env[k] = datei_schalter[k] + return env + return dict(datei_schalter) + + +def arm_je_zug(zuege): + """(raum, hand, street) -> arm aus den zuege-Zeilen.""" + return {(z.get("raum"), str(z.get("hand")), z.get("street")): z.get("arm") for z in zuege} + + +def kern_kopie(quelle, ziel_ordner): + """Kopiert den Live-Kern nach ziel_ordner/pokerbench-roentgen-nachspiel(.exe), wenn er sich + geändert hat - so sperrt das Nachspielen nie das Live-Binary (Windows) und baut nichts.""" + os.makedirs(ziel_ordner, exist_ok=True) + ziel = os.path.join(ziel_ordner, KERN_KOPIE) + q = os.stat(quelle) + try: + z = os.stat(ziel) + if z.st_size == q.st_size and abs(z.st_mtime - q.st_mtime) < 1: + return ziel + except OSError: + pass + shutil.copy2(quelle, ziel) + return ziel + + +def kern_aufruf(binary, timeout_je=5.0): + """kern(anfragen, env) -> antworten: ein Prozess je Bündel, Priorität Idle.""" + def kern(anfragen, env): + if not anfragen: + return [] + umgebung = {k: v for k, v in os.environ.items() if k not in BEKANNTE_SCHALTER} + umgebung.update(env) + extra = {} + if sys.platform == "win32": + extra["creationflags"] = IDLE_PRIORITY_CLASS + else: + extra["preexec_fn"] = lambda: os.nice(19) + r = subprocess.run([binary], input="\n".join(json.dumps(a) for a in anfragen) + "\n", + capture_output=True, text=True, encoding="utf-8", env=umgebung, + timeout=60 + timeout_je * len(anfragen), **extra) + if r.returncode != 0: + raise RuntimeError(f"der Kern scheiterte: {r.stderr.strip()[:300]}") + aus = [] + for zeile in r.stdout.split("\n"): + if not zeile.strip(): + continue + try: + aus.append(json.loads(zeile)) + except ValueError: + aus.append({"action": "UNLESBAR"}) + return aus + return kern + + +def kern_pfad(wurzel): + return os.path.join(wurzel, "target", "release", "rechner.exe" if sys.platform == "win32" else "rechner") + + +# ---------------------------------------------------------------- Bericht + +def cache_pfad(cache_ordner, pid, kern_id=""): + """Ein Cache je Lauf und Kern-Stand: ein neu gebauter Kern rechnet neu.""" + return os.path.join(cache_ordner, f"nachspiel-{pid}{'-' + kern_id if kern_id else ''}.json") + + +def _cache_laden(pfad): + try: + with open(pfad, encoding="utf-8") as f: + d = json.load(f) + return d if isinstance(d, dict) else {} + except (OSError, ValueError): + return {} + + +def _cache_schreiben(pfad, d): + os.makedirs(os.path.dirname(pfad), exist_ok=True) + tmp = pfad + ".tmp" + with open(tmp, "w", encoding="utf-8") as f: + json.dump(d, f, ensure_ascii=False) + os.replace(tmp, pfad) + + +def daten(wurzel): + """Alles, was der Bericht von der Platte braucht.""" + lauf = os.path.join(wurzel, "archiv", "lauf") + schatten = [] + for p in schatten_dateien(wurzel): + schatten.extend(jsonl(p)) + return {"zuege": jsonl(os.path.join(lauf, "zuege.jsonl")), + "haende": jsonl(os.path.join(lauf, "haende.jsonl")), + "schatten": schatten} + + +def bericht(d, pid=None, start=None, bis=None, kern=None, kern_info=None, datei_schalter=None, + cache=None): + """Der ganze Bericht als dict. `kern` None = ohne Read-Wirkung (kein Nachspielen).""" + liste = laeufe(d["schatten"]) + lauf = waehle(liste, pid=pid, start=start) + if lauf is None: + if not start: + return {"fehler": "kein Lauf im Schatten-Log gefunden", "laeufe": liste} + # Ohne Schatten-Log: nur das Zeitfenster aus zuege (keine Gesundheit, kein Nachspiel). + lauf = {"pid": None, "von": start, "bis": bis or "9999", "entscheidungen": 0} + von, ende = lauf["von"], min(lauf["bis"], bis) if bis else lauf["bis"] + schatten_lauf = [e for e in d["schatten"] if e.get("pid") == lauf["pid"] + and isinstance(e.get("zeit"), str) and von <= e["zeit"] <= ende] + zuege = im_fenster(d["zuege"], von, ende) + haende = haende_im_fenster(d["haende"], von, ende if ende != "9999" else "9999-12-31 23:59:59") + aus = { + "lauf": {"pid": lauf["pid"], "von": von, "bis": ende}, + "ergebnis": ergebnis(haende), + "wer": wer_entschied(zuege), + "stichprobe": lesestichprobe(zuege), + "gesundheit": gesundheit(schatten_lauf), + "wirkung": None, + } + if kern is not None: + paare = nachspielbar(schatten_lauf) + arme = arm_je_zug(zuege) + haupt = collections.Counter(z.get("arm") for z in zuege).most_common(1) + haupt = haupt[0][0] if haupt else None + envs = [] + for e, a in paare: + teile = str(e.get("zug") or "").split("|") + arm = arme.get((e.get("raum"), teile[1] if len(teile) > 1 else None, a.get("street")), haupt) + envs.append(env_fuer_arm(arm, datei_schalter or {})) + aus["wirkung"] = lese_wirkung(paare, kern, envs, cache) + aus["wirkung"]["kern"] = kern_info + aus["wirkung"]["umgebungen"] = sorted({json.dumps(x, sort_keys=True) for x in envs}) + return aus + + +def rechnen(wurzel, pid=None, start=None, bis=None, nachspiel=True, cache_ordner=None, kern_quelle=None): + """Bericht mit Platte: liest, kopiert den Kern, spielt nach (mit Plattencache).""" + d = daten(wurzel) + if not nachspiel: + return bericht(d, pid, start, bis) + cache_ordner = cache_ordner or os.environ.get("ROENTGEN_CACHE") or os.path.join(BAUM, "archiv", "roentgen") + quelle = kern_quelle or kern_pfad(wurzel) + if not os.path.exists(quelle): + r = bericht(d, pid, start, bis) + r["wirkung"] = {"fehler": f"kein Kern unter {quelle}"} + return r + binary = kern_kopie(quelle, os.path.join(cache_ordner, "kern")) + info = {"quelle": quelle, "gebaut": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(os.path.getmtime(quelle)))} + schalter = lies_schalter(os.path.join(wurzel, "betrieb", "kern_schalter.txt")) + vorab = waehle(laeufe(d["schatten"]), pid=pid, start=start) + st = os.stat(quelle) + kern_id = hashlib.sha1(f"{st.st_size}|{int(st.st_mtime)}".encode()).hexdigest()[:8] + cpfad = cache_pfad(os.path.join(cache_ordner, "cache"), vorab["pid"] if vorab else "fenster", kern_id) + cache = _cache_laden(cpfad) + vorher = len(cache) + r = bericht(d, pid, start, bis, kern_aufruf(binary), info, schalter, cache) + if len(cache) != vorher: + _cache_schreiben(cpfad, cache) + return r + + +# ---------------------------------------------------------------- Text + +def _pz(n, gesamt): + return f"{100.0 * n / gesamt:5.1f}%" if gesamt else " -" + + +def _bb(b): + if not b or b["n"] == 0: + return "keine Hände" + s = f"{b['n']} Hände, netto {b['netto_bb']:+.1f} BB, {b['bb100']:+.1f} bb/100" + if b["halb95"] is not None: + s += f" (95 %: {b['tief']:+.0f} bis {b['hoch']:+.0f})" + return s + + +def text(r): + if "fehler" in r: + return r["fehler"] + L = r["lauf"] + z = [f"ENGINE-RÖNTGEN Lauf pid {L['pid']} {L['von']} bis {L['bis']}", ""] + z.append("1. ERGEBNIS") + z.append(" gesamt: " + _bb(r["ergebnis"]["gesamt"])) + for arm, b in r["ergebnis"]["arme"].items(): + z.append(f" Arm {arm}: " + _bb(b)) + z.append("") + z.append("2. WER ENTSCHIED (Anteil an den Kern-Zügen je Street; Enthaltung: Anteil an allen Zügen)") + kopf = f" {'Street':<8}{'Züge':>6}" + "".join(f"{KLASSEN_NAME[k]:>16}" for k in KLASSEN) + z.append(kopf) + for s, w in r["wer"].items(): + n = w["zuege"] + zeile = f" {s:<8}{n:>6}" + "".join( + f"{(str(w['klassen'][k]) + ' ' + _pz(w['klassen'][k], n if k == 'enthaltung' else w['kern_zuege']).strip()) if w['klassen'][k] else '-':>16}" + for k in KLASSEN) + z.append(zeile) + z.append("") + z.append("3. READ-WIRKUNG (jede Anfrage nochmal durch den Kern, einmal ohne Gegnerprofile)") + w = r.get("wirkung") + if not w: + z.append(" nicht gerechnet (--ohne-nachspiel, oder das Nachspielen läuft noch)") + elif "fehler" in w: + z.append(" " + w["fehler"]) + else: + z.append(f" {'Street':<8}{'Entsch.':>8}{'mit Read':>10}{'Aktion anders':>16}{'nur Größe anders':>18}{'Nachspiel=live':>16}") + for s, x in w["streets"].items(): + n = x["entscheidungen"] + z.append(f" {s:<8}{n:>8}{x['mit_read']:>10}{(str(x['aktion_anders']) + ' ' + _pz(x['aktion_anders'], n).strip()):>16}" + f"{(str(x['groesse_anders']) + ' ' + _pz(x['groesse_anders'], n).strip()):>18}{_pz(x['treu'], n):>16}") + g = w["streets"]["GESAMT"] + z.append(f" => der Gegner-Read ändert {g['aktion_anders']} von {g['entscheidungen']} Entscheidungen " + f"({_pz(g['aktion_anders'], g['entscheidungen']).strip()}).") + if w.get("kern"): + z.append(f" Kern: {w['kern']['quelle']} (gebaut {w['kern']['gebaut']}); Schalter: " + + "; ".join(w.get("umgebungen") or [])) + for b in w["beispiele"]: + z.append(f" - {b['zeit']} {b['street']}: mit Read {b['mit']}, ohne {b['ohne']} [{(b['grund_mit'] or '')[:70]}]") + z.append("") + st = r["stichprobe"] + z.append("4. READ-STICHPROBE (Hände hinter den Gegnerprofilen)") + z.append(f" Züge mit Profil: {st['zuege_mit_read']} von {st['zuege']}; Median hands je Gegner-Eintrag: {st['median_hands']}") + z.append(f" je Gegner ({st['gegner']}): " + " ".join(f"{k}: {v}" for k, v in st["je_gegner"].items())) + z.append(" je Gegner-Eintrag im Zug: " + " ".join(f"{k}: {v}" for k, v in st["je_zug"].items())) + z.append("") + g = r["gesundheit"] + z.append("5. LÄUFER") + z.append(f" Entscheidungen {g['entscheidungen']} (davon Enthaltungen {g['enthaltungen']}), geklickt {g['geklickt']}" + f" (ohne Echo {g['ohne_echo']}), nicht geklickt {g['nicht_geklickt']}") + z.append(f" veraltet/verworfen {g['veraltet']}, Raum ohne Fenster {g['ohne_fenster']}, Kanal ohne Antwort {g['kanal_ohne_antwort']}") + fm = "-" if g["frist_min_s"] is None else f"{g['frist_min_s']:.1f} s" + z.append(f" kleinste Restuhr {fm}, unter 5 s: {g['frist_unter_5s']}, Uhr abgelaufen: {g['uhr_abgelaufen']}, Sitout-Ereignisse: {g['sitout']}") + return "\n".join(z) + + +def main(argv=None): + a = argparse.ArgumentParser(description="Engine-Röntgen je Live-Lauf") + a.add_argument("--wurzel", default=os.environ.get("ROENTGEN_WURZEL", BAUM), + help="Baum mit archiv/lauf, betrieb/scratch, target/release (Vorgabe: dieser)") + a.add_argument("--pid", help="Läufer-PID") + a.add_argument("--start", help="Startzeit (Ortszeit) 'JJJJ-MM-TT HH:MM' - der Lauf, der sie enthält") + a.add_argument("--bis", help="nur bis zu dieser Ortszeit") + a.add_argument("--kern", help="Kern-Binary (Vorgabe: /target/release/rechner)") + a.add_argument("--ohne-nachspiel", action="store_true", help="Read-Wirkung nicht rechnen") + a.add_argument("--json", action="store_true") + a.add_argument("--liste", action="store_true", help="Läufe im Schatten-Log zeigen") + x = a.parse_args(argv) + if x.liste: + for r in laeufe(daten(x.wurzel)["schatten"]): + print(f"pid {r['pid']:>7} {r['von']} bis {r['bis']} {r['entscheidungen']} Entscheidungen") + return 0 + r = rechnen(x.wurzel, pid=x.pid, start=x.start, bis=x.bis, nachspiel=not x.ohne_nachspiel, + kern_quelle=x.kern) + if x.json: + print(json.dumps(r, ensure_ascii=False, indent=1, default=str)) + else: + sys.stdout.reconfigure(encoding="utf-8", errors="replace") if hasattr(sys.stdout, "reconfigure") else None + print(text(r)) + return 0 if "fehler" not in r else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/bin/ab_zelle.rs b/src/bin/ab_zelle.rs index 4e0b8b1c..7e642959 100644 --- a/src/bin/ab_zelle.rs +++ b/src/bin/ab_zelle.rs @@ -161,6 +161,7 @@ fn read_of(name: &str) -> (&str, ReadMode) { match name.split_once('@') { Some((base, "blind")) => (base, ReadMode::Blind), Some((base, "oracle")) => (base, ReadMode::Oracle), + Some((base, "hud")) => (base, ReadMode::Hud), Some((_, other)) => panic!("unbekannter Lesemodus @{other}"), None => (name, ReadMode::Memory), } diff --git a/src/exploit/sample.rs b/src/exploit/sample.rs index 53d965de..49eae463 100644 --- a/src/exploit/sample.rs +++ b/src/exploit/sample.rs @@ -1,4 +1,4 @@ -//! How much a profile is worth: its sample. Opponent statistics come without a hand count, so +//! How much a profile is worth: its sample. Opponent statistics come without a hand count, so //! the caller sends one (`villains[].profile.hands`, extension, not in VERTRAG.md). Few hands //! mean the numbers are mostly noise; they are pulled toward the population before anything //! reads them. @@ -41,7 +41,7 @@ pub const PRIOR: Profile = Profile { river_bluff_shown: None, }; -/// Postflop moves at which an aggression read and the population weigh the same — the session +/// Postflop moves at which an aggression read and the population weigh the same — the session /// memory's half-life (`sim::memory::CONFIDENCE_HALF`), so a live read earns trust as fast as a /// simulated one. pub const AGGRESSION_HALF: f64 = 30.0; @@ -101,6 +101,74 @@ pub fn shrink_aggression(profile: Profile, raw: Option, actions: f64) -> Pr Profile { aggression: pull(raw, PRIOR.aggression, w), aggression_confidence: Some(w), ..profile } } +/// Share of a HUD's hands in which the player faces a c-bet / a 3-bet after opening / a bet after +/// checking (rough 6-max frequencies): the effective sample of each line stat. +pub const CBET_SPOT_SHARE: f64 = 0.15; +pub const THREE_BET_SPOT_SHARE: f64 = 0.04; +pub const CHECK_RAISE_SPOT_SHARE: f64 = 0.10; + +/// The base sample `lesen/profil.py` gives a believable client HUD (`GLAUBHAFT`): the wire's `hands` is +/// this plus the hands we saw ourselves. +pub const GLAUBHAFT: f64 = 20.0; + +/// Measured worth of the PokerIntel numbers in engine hands (`lesen/pokerintel.py`, STAND §16): the +/// hand count that gives the engine's trust `h/(h+30)` the weight the data earn against the population. +/// vpip/pfr are worth far more than the flat 20 (fitted weight 0.76–0.88, lower 95 % bound >= 0.57 → +/// 60 hands = weight 0.67), the fold-to-bet number far less (weight 0.07–0.22 → 8 hands = 0.21). The +/// other fields stay at the flat base: their intervals reach 0 and 1, the data do not carry a change. +pub const PI_HANDS_VPIP: f64 = 60.0; +pub const PI_HANDS_PFR: f64 = 60.0; +pub const PI_HANDS_FOLD: f64 = 8.0; + +/// Switch `POKERINTEL=1` (read once): the HUD fields get their measured weights (`hud_profile`). +/// Off (default): the flat `GLAUBHAFT` base for every field, bit-identical to before. +pub fn pokerintel_on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("POKERINTEL").as_deref() == Ok("1")) +} + +/// The sample one field rests on when the client base `GLAUBHAFT` is worth `base` hands for it: our own +/// hands on top count as they are; a thin profile (below the base, `lesen/profil.py DUENN`) is scaled. +pub fn field_hands(hands: f64, base: f64) -> f64 { + if hands.is_nan() || hands <= 0.0 { + return hands; + } + if hands >= GLAUBHAFT { + hands - GLAUBHAFT + base + } else { + hands * base / GLAUBHAFT + } +} + +/// A client HUD with a hand count, as the engine believes it: `shrink` over `hands`, then the line stats +/// (foldToCbet, foldToThreeBet, checkRaise) over the fraction of hands their spot arises in, toward their +/// anchors (as the sim memory does), so 40 HUD hands are not 40 c-bets. With `POKERINTEL=1` +/// (`hud_profile_weighted`) vpip, pfr and fold-to-bet carry their measured worth instead of the flat +/// base, and the fold/range read's `confidence` is the fold-to-bet trust. +pub fn hud_profile(raw: &Profile, hands: f64) -> Profile { + hud_profile_with(raw, hands, pokerintel_on()) +} + +pub fn hud_profile_with(raw: &Profile, hands: f64, weighted: bool) -> Profile { + let mut p = shrink(raw, hands); + if weighted { + let w = |base: f64| trust(field_hands(hands, base)); + let w_fold = w(PI_HANDS_FOLD); + p.vpip = pull(raw.vpip, PRIOR.vpip, w(PI_HANDS_VPIP)); + p.pfr = pull(raw.pfr, PRIOR.pfr, w(PI_HANDS_PFR)); + p.fold_to_bet = pull(raw.fold_to_bet, PRIOR.fold_to_bet, w_fold); + p.confidence = raw.confidence.or(Some(w_fold)); + } + let line = |x: Option, share: f64, anchor: Option| shrink_street(x, hands * share, anchor); + let cbet_anchor = p.fold_to_bet.or(Some(crate::exploit::fold_chance::DEFAULT_FOLD_TO_BET)); + Profile { + fold_to_cbet: line(p.fold_to_cbet, CBET_SPOT_SHARE, cbet_anchor), + fold_to_three_bet: line(p.fold_to_three_bet, THREE_BET_SPOT_SHARE, Some(FOLD_TO_THREE_BET_ANCHOR)), + check_raise: line(p.check_raise, CHECK_RAISE_SPOT_SHARE, Some(CHECK_RAISE_ANCHOR)), + ..p + } +} + /// Anchors of the line reads that have no pooled read to shrink toward (a regular's HUD): fold to /// 3-bet and check-raise. Shared by the sim memory and the wire. pub const FOLD_TO_THREE_BET_ANCHOR: f64 = 0.55; @@ -108,12 +176,12 @@ pub const CHECK_RAISE_ANCHOR: f64 = 0.08; /// Prior strength of the check-raise read in pseudo-chances (Beta(mu*kappa, (1-mu)*kappa)). pub const CHECK_RAISE_KAPPA: f64 = 15.0; -/// Street samples at which one street's own read and the pooled read weigh the same — the session +/// Street samples at which one street's own read and the pooled read weigh the same — the session /// memory's `sim::memory::STREET_FOLD_PRIOR`, so a live street read earns trust as a simulated one. pub const STREET_PRIOR: f64 = 15.0; /// One street's read (`raw`, measured over `n` moves on that street) pulled toward the `pooled` read of -/// all streets: `(raw·n + STREET_PRIOR·pooled) / (n + STREET_PRIOR)`. A few river moves barely move +/// all streets: `(raw·n + STREET_PRIOR·pooled) / (n + STREET_PRIOR)`. A few river moves barely move /// the river belief off the pooled one. No street sample, a broken count or no pooled read to anchor /// on: `None`, so the engine falls back to the pooled read (never a raw 0/1 from one move). pub fn shrink_street(raw: Option, n: f64, pooled: Option) -> Option { @@ -124,3 +192,60 @@ pub fn shrink_street(raw: Option, n: f64, pooled: Option) -> Option Profile { + Profile { + vpip: Some(0.45), + pfr: Some(0.08), + fold_to_bet: Some(0.70), + aggression: Some(0.2), + fold_to_cbet: Some(0.8), + fold_to_three_bet: Some(0.3), + check_raise: Some(0.2), + ..Profile::default() + } + } + + /// Switch off: exactly the old wire (shrink over `hands`, line stats over their spot share). + #[test] + fn off_is_the_old_wire() { + for hands in [0.0, 5.0, 20.0, 44.0, 300.0, f64::NAN] { + let raw = hud(); + let p = shrink(&raw, hands); + let anchor = p.fold_to_bet.or(Some(crate::exploit::fold_chance::DEFAULT_FOLD_TO_BET)); + let old = Profile { + fold_to_cbet: shrink_street(p.fold_to_cbet, hands * CBET_SPOT_SHARE, anchor), + fold_to_three_bet: shrink_street(p.fold_to_three_bet, hands * THREE_BET_SPOT_SHARE, Some(FOLD_TO_THREE_BET_ANCHOR)), + check_raise: shrink_street(p.check_raise, hands * CHECK_RAISE_SPOT_SHARE, Some(CHECK_RAISE_ANCHOR)), + ..p + }; + let new = hud_profile_with(&raw, hands, false); + assert_eq!(format!("{old:?}"), format!("{new:?}"), "hands {hands}"); + } + } + + /// Switch on: vpip/pfr believed more, fold-to-bet less, by the measured effective samples. + #[test] + fn on_reweights_by_field() { + let raw = hud(); + let (off, on) = (hud_profile_with(&raw, 24.0, false), hud_profile_with(&raw, 24.0, true)); + let d = |x: Option, p: f64| (x.unwrap() - p).abs(); + assert!(d(on.vpip, 0.28) > d(off.vpip, 0.28)); + assert!(d(on.pfr, 0.18) > d(off.pfr, 0.18)); + assert!(d(on.fold_to_bet, 0.45) < d(off.fold_to_bet, 0.45)); + assert!(on.confidence.unwrap() < off.confidence.unwrap()); + assert_eq!(on.aggression, off.aggression); + } + + #[test] + fn field_hands_maps_the_default_and_counts_own_hands_fully() { + assert_eq!(field_hands(GLAUBHAFT, 60.0), 60.0); + assert_eq!(field_hands(GLAUBHAFT + 10.0, 8.0), 18.0); + assert_eq!(field_hands(10.0, 60.0), 30.0); + assert_eq!(field_hands(0.0, 60.0), 0.0); + } +} diff --git a/src/sim/hud.rs b/src/sim/hud.rs new file mode 100644 index 00000000..726006c0 --- /dev/null +++ b/src/sim/hud.rs @@ -0,0 +1,109 @@ +//! The client HUD a live seat carries (PokerIntel), for the `ReadMode::Hud` ladder rows. +//! +//! Live, 95 % of seats arrive with PokerIntel numbers whose effective sample is far below the hands +//! they claim (`lesen/pokerintel.py`, STAND §16: vpip ~12 chances, fold ~4). The sim reproduces that: +//! a pre-session on its own seed measures the opponent's true rates (`SessionMemory::raw_profile`), +//! then each field is drawn from Beta(m·θ, m·(1−θ)) with the measured m. The engine then reads that +//! HUD exactly like the live wire (`SessionMemory::hud_read` → `sample::hud_profile`). + +use super::memory::SessionMemory; +use super::population::normal; +use crate::exploit::profile::Profile; +use crate::rng::Rng; + +/// Deals of the truth pre-session. +pub const HUD_VOR: u32 = 800; +/// Effective chances per field (`messung_gedaechtnis/pokerintel.json`, fit with fixed mean). +pub const M_VPIP: f64 = 12.1; +pub const M_PFR: f64 = 10.0; +pub const M_FOLD: f64 = 4.0; +pub const M_FOLD_TO_CBET: f64 = 3.1; +pub const M_FOLD_TO_THREE_BET: f64 = 30.0; +pub const M_CHECK_RAISE: f64 = 12.5; + +/// Gamma(shape, 1) by Marsaglia–Tsang (shape < 1 via the boost u^(1/shape)). +fn gamma(shape: f64, rng: Rng) -> (f64, Rng) { + if shape < 1.0 { + let (g, rng) = gamma(shape + 1.0, rng); + let (u, rng) = rng.unit(); + return (g * u.max(1e-300).powf(1.0 / shape), rng); + } + let d = shape - 1.0 / 3.0; + let c = 1.0 / (9.0 * d).sqrt(); + let mut rng = rng; + loop { + let (z, r) = normal(rng); + let (u, r) = r.unit(); + rng = r; + let v = (1.0 + c * z).powi(3); + if v > 0.0 && u.max(1e-300).ln() < 0.5 * z * z + d - d * v + d * v.ln() { + return (d * v, rng); + } + } +} + +/// One draw of a rate measured over `m` chances whose truth is `theta`. +pub fn noisy(theta: f64, m: f64, rng: Rng) -> (f64, Rng) { + let t = theta.clamp(0.005, 0.995); + let (a, rng) = gamma(m * t, rng); + let (b, rng) = gamma(m * (1.0 - t), rng); + (a / (a + b), rng) +} + +/// The HUD a seat shows: every known truth field drawn noisily, unknown fields stay `None`. +pub fn draw(truth: &Profile, rng: Rng) -> Profile { + let mut rng = rng; + let mut f = |x: Option, m: f64| { + x.map(|t| { + let (v, r) = noisy(t, m, rng); + rng = r; + v + }) + }; + Profile { + vpip: f(truth.vpip, M_VPIP), + pfr: f(truth.pfr, M_PFR), + fold_to_bet: f(truth.fold_to_bet, M_FOLD), + fold_to_cbet: f(truth.fold_to_cbet, M_FOLD_TO_CBET), + fold_to_three_bet: f(truth.fold_to_three_bet, M_FOLD_TO_THREE_BET), + check_raise: f(truth.check_raise, M_CHECK_RAISE), + ..Profile::default() + } +} + +/// The truth of a pre-session memory, as the HUD source. +pub fn truth(memory: &SessionMemory) -> Profile { + memory.raw_profile() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn noisy_has_the_right_mean_and_spread() { + let (n, theta, m) = (20000, 0.3, 10.0); + let mut rng = Rng::seeded(7); + let mut xs = Vec::with_capacity(n); + for _ in 0..n { + let (x, r) = noisy(theta, m, rng); + rng = r; + xs.push(x); + } + let mean = xs.iter().sum::() / n as f64; + let var = xs.iter().map(|x| (x - mean).powi(2)).sum::() / n as f64; + assert!((mean - theta).abs() < 0.01, "mean {mean}"); + let want = theta * (1.0 - theta) / (m + 1.0); + assert!((var / want - 1.0).abs() < 0.08, "var {var} want {want}"); + } + + #[test] + fn small_shapes_stay_in_range() { + let mut rng = Rng::seeded(3); + for _ in 0..2000 { + let (x, r) = noisy(0.02, 3.0, rng); + rng = r; + assert!((0.0..=1.0).contains(&x)); + } + } +} diff --git a/src/sim/memory.rs b/src/sim/memory.rs index f3495e05..9577a990 100644 --- a/src/sim/memory.rs +++ b/src/sim/memory.rs @@ -1,529 +1,581 @@ -//! Session memory (Stage 1): the engine builds its read from the opponent's OBSERVED actions over -//! the hands of a session, instead of being handed the converged HUD read (`sim::reads`) or playing -//! blind. A HUD that only counts - per opponent seat, preflop voluntary money and raises, postflop -//! folds-to-a-bet and aggression - turned into a `Profile` once a warmup of hands is seen, so the -//! first hands play blind and the read converges to the truth over the session. -//! -//! The gap blind -> read-given that `benchmarks/baseline.txt` / `tests/sim_blind` measure is exactly -//! what this must recapture: a `... (memory)` scenario lands between the blind and the read-given -//! twin, the share of the prize that observation alone earns. Every opponent seat is the same fixed -//! archetype, so their counts pool into one read. - -use crate::exploit::profile::Profile; -use crate::game::{line, ActionRecord, SeenAction, Street}; - -pub use super::welt_memory::{ - strength_band, Cell, Move, Pos, Reveal, SizeBucket, Showdown, Texture, Tank, WorldEvent, WorldHand, - WorldMemory, STRENGTH_BANDS, -}; - -/// Hands to observe before the read is trusted; until then `read` is `None` (the engine plays -/// blind). Keeps an early, noisy sample from steering worse than no read at all. -pub const WARMUP_HANDS: u32 = 25; - -/// Postflop actions at which the read's confidence reaches 0.5 (half-life). Matches the Bayesian -/// posterior's `VERTRAUEN_HALB` so the counts HUD and `exploit::posterior` agree on how fast a read -/// earns trust. The river gearbox turns this confidence into the KL trust radius. -pub const CONFIDENCE_HALF: f64 = 30.0; - -/// Running tallies over the opponent archetype. Preflop opportunities (`hands`) and the voluntary / -/// raise counts drive vpip and pfr; the postflop tallies drive fold-to-bet and aggression. -#[derive(Clone, Copy, Debug, Default, PartialEq)] -struct Counts { - hands: u32, - vpip: u32, - pfr: u32, - folded_to_bet: u32, - passive_call: u32, - passive_check: u32, - aggressive: u32, - // Per-street aggression split (turn and river only — the streets the subgame gearboxes solve). - // `*_passive` is calls plus checks on that street (the aggression denominator, matching the pooled - // one which counts checks); folds are excluded, as in the pooled aggression. - turn_aggressive: u32, - turn_passive: u32, - river_aggressive: u32, - river_passive: u32, - // Facing-a-bet outcomes per street (flop, turn, river): folds and calls, for the per-street - // fold-to-bet read. - street_fold: [u32; 3], - street_call: [u32; 3], - // Line-specific HUD stats (`game::line`): responses facing a c-bet / a 3-bet after opening / - // a bet after own check, and how many of them folded / folded / raised. - cbet_faced: u32, - cbet_folded: u32, - three_bet_faced: u32, - three_bet_folded: u32, - xr_chances: u32, - xr_made: u32, -} - -fn street_index(street: Street) -> Option { - match street { - Street::Flop => Some(0), - Street::Turn => Some(1), - Street::River => Some(2), - Street::Preflop => None, - } -} - -/// Facing-a-bet samples that weigh as much as the pooled read when shrinking a street's fold rate. -pub const STREET_FOLD_PRIOR: f64 = crate::exploit::sample::STREET_PRIOR; - -static STREET_FOLD: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true); - -/// Switch the per-street fold read on or off (A/B arm for the ladder). Default on. -pub fn set_street_fold(on: bool) { - STREET_FOLD.store(on, std::sync::atomic::Ordering::Relaxed); -} - -fn street_fold_on() -> bool { - STREET_FOLD.load(std::sync::atomic::Ordering::Relaxed) -} - -/// Line-specific HUD reads switched into `read()`: bit 1 fold to c-bet, 2 fold to 3-bet, 4 check-raise. -static LINE_READS: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0); - -/// Line reads in `read()` (A/B arm): `READ_CBET | READ_THREE_BET | READ_CHECK_RAISE`. Default none. -pub fn set_line_reads(mask: u8) { - LINE_READS.store(mask, std::sync::atomic::Ordering::Relaxed); -} -pub const READ_CBET: u8 = 1; -pub const READ_THREE_BET: u8 = 2; -pub const READ_CHECK_RAISE: u8 = 4; - -fn line_read_on(bit: u8) -> bool { - LINE_READS.load(std::sync::atomic::Ordering::Relaxed) & bit != 0 -} - -/// Population anchors the line reads shrink toward over `STREET_FOLD_PRIOR` samples (a regular's -/// HUD): fold to 3-bet and check-raise have no pooled read to anchor on. -use crate::exploit::sample::{ - CHECK_RAISE_ANCHOR as CHECK_RAISE_PRIOR, CHECK_RAISE_KAPPA, FOLD_TO_THREE_BET_ANCHOR as FOLD_TO_THREE_BET_PRIOR, -}; - -static RIVER_SHOWDOWN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); - -/// Switch the river showdown read (`Profile::river_bluff_share`, from the world memory's revealed river -/// bets) into `read()` (A/B arm for the ladder). Default off until the ladder proves it. -pub fn set_river_showdown(on: bool) { - RIVER_SHOWDOWN.store(on, std::sync::atomic::Ordering::Relaxed); -} - -fn river_showdown_on() -> bool { - RIVER_SHOWDOWN.load(std::sync::atomic::Ordering::Relaxed) -} - -/// The read a HUD accumulates from watching one fixed opponent archetype play a session. -#[derive(Clone, Debug, Default, PartialEq)] -pub struct SessionMemory { - c: Counts, - /// The richer dimensions (sizing x strength, texture x position cells, showdown reveals, timing), - /// see `sim::welt_memory`. Filled only by `observe_world_hand`; `read()` ignores it, so the classic - /// HUD read (and every existing ladder number) is unchanged by it. - world: WorldMemory, -} - -impl SessionMemory { - pub fn new() -> Self { - Self::default() - } - - /// The world-dimension observations (sizing, texture/position cells, showdowns, timing). - pub fn world(&self) -> &WorldMemory { - &self.world - } - - /// Fold one finished hand's world observations (see `WorldHand`) into the world memory. - /// The raw (chances, hits) per read, for the empirical-Bayes fit of the population priors - /// (`lesen/eichung.py`), named like `lesen/zaehler.py`. - pub fn line_counts(&self) -> Vec<(&'static str, u32, u32)> { - let c = &self.c; - vec![ - ("vpip", c.hands, c.vpip), - ("pfr", c.hands, c.pfr), - ("aggression", c.aggressive + c.passive_call + c.passive_check, c.aggressive), - ("flopFoldToBet", c.street_fold[0] + c.street_call[0], c.street_fold[0]), - ("turnFoldToBet", c.street_fold[1] + c.street_call[1], c.street_fold[1]), - ("riverFoldToBet", c.street_fold[2] + c.street_call[2], c.street_fold[2]), - ("foldToCbet", c.cbet_faced, c.cbet_folded), - ("foldToThreeBet", c.three_bet_faced, c.three_bet_folded), - ("checkRaise", c.xr_chances, c.xr_made), - ] - } - - pub fn observe_world_hand(&mut self, hand: &WorldHand) { - self.world.observe_world_hand(hand); - } - - /// Fold every opponent seat's actions of one finished hand into the counts. `hero` is the - /// 0-based hero seat; every other of the `players` seats is an opponent of the same archetype. - pub fn observe_hand(&mut self, history: &[ActionRecord], hero: usize, players: usize) { - for seat in 1..=players as u8 { - if seat as usize - 1 != hero { - self.observe_seat(history, seat); - } - } - } - - /// The line-specific responses of `seat`: each of its actions judged against the line before it. - fn observe_lines(&mut self, history: &[ActionRecord], seat: u8) { - for (k, r) in history.iter().enumerate().filter(|(_, r)| r.seat == seat) { - let before = &history[..k]; - let folded = r.action == SeenAction::Fold; - if r.street == Street::Flop && line::facing_cbet(before, seat) { - self.c.cbet_faced += 1; - self.c.cbet_folded += folded as u32; - } - if r.street == Street::Preflop && line::facing_three_bet(before, seat) { - self.c.three_bet_faced += 1; - self.c.three_bet_folded += folded as u32; - } - if r.street != Street::Preflop && line::check_raise_chance(before, seat, r.street) { - self.c.xr_chances += 1; - self.c.xr_made += r.action.is_aggressive() as u32; - } - } - } - - /// One seat's actions of a finished hand (a per-opponent memory at a mixed table, `sim::sechsmax`). - pub fn observe_seat(&mut self, history: &[ActionRecord], seat: u8) { - self.observe_lines(history, seat); - self.c.hands += 1; - let (mut voluntary, mut raised) = (false, false); - for r in history.iter().filter(|r| r.seat == seat) { - if r.street == Street::Preflop { - // Blinds are forced (PostSmallBlind / PostBigBlind); a check is free. Only a call or - // an aggressive action puts money in by choice. - match r.action { - SeenAction::Call | SeenAction::Bet | SeenAction::Raise | SeenAction::AllIn => { - voluntary = true; - } - _ => {} - } - raised |= r.action.is_aggressive(); - } else { - // Postflop a fold or a call only happens facing a bet; a check faces nothing. The - // check still counts as a passive action for aggression (matching how the oracle - // reads are measured, `tests/sim_opponent_stats`): leaving checks out of the - // denominator makes a passive, check-heavy opponent look far more aggressive than it - // is, and `bluff_share` reads aggression directly. - match r.action { - SeenAction::Fold => { - self.c.folded_to_bet += 1; - if let Some(i) = street_index(r.street) { - self.c.street_fold[i] += 1; - } - } - SeenAction::Call => { - if let Some(i) = street_index(r.street) { - self.c.street_call[i] += 1; - } - self.c.passive_call += 1; - self.bump_passive(r.street); - } - SeenAction::Check => { - self.c.passive_check += 1; - self.bump_passive(r.street); - } - a if a.is_aggressive() => { - self.c.aggressive += 1; - self.bump_aggressive(r.street); - } - _ => {} - } - } - } - self.c.vpip += voluntary as u32; - self.c.pfr += raised as u32; - } - - /// A passive postflop action (call or check) on the turn/river, for the per-street aggression - /// denominator. Flop and preflop are not split. - fn bump_passive(&mut self, street: Street) { - match street { - Street::Turn => self.c.turn_passive += 1, - Street::River => self.c.river_passive += 1, - _ => {} - } - } - - /// An aggressive postflop action (bet or raise) on the turn/river, for the per-street numerator. - fn bump_aggressive(&mut self, street: Street) { - match street { - Street::Turn => self.c.turn_aggressive += 1, - Street::River => self.c.river_aggressive += 1, - _ => {} - } - } - - /// The read so far, or `None` during the warmup. vpip / pfr are over hands; fold-to-bet is folds - /// over folds-plus-calls facing a bet; aggression is bets-and-raises over bets-raises-and-calls. - pub fn read(&self) -> Option { - if self.c.hands < WARMUP_HANDS { - return None; - } - let ratio = |num: u32, den: u32| (den > 0).then(|| num as f64 / den as f64); - let facing_bet = self.c.folded_to_bet + self.c.passive_call; - // Aggression frequency: bets and raises over every non-folding postflop action, checks - // included (see `observe_seat`). - let postflop_actions = self.c.aggressive + self.c.passive_call + self.c.passive_check; - // Confidence for the gearbox: the read is only as trustworthy as its weaker postflop sample — - // the facing-a-bet count (drives fold_to_bet / the defense belief) and the total postflop - // count (drives aggression / the betting-polarization belief). Half at CONFIDENCE_HALF. - let conf = |n: u32| n as f64 / (n as f64 + CONFIDENCE_HALF); - let confidence = conf(facing_bet.min(postflop_actions)); - // Per-street aggression: bets/raises over bets-raises-plus-passive on that street (same shape - // as the pooled frequency). `None` until the street has an action, so `believed_villain` falls - // back to the pooled read. - let street_aggr = |aggr: u32, passive: u32| ratio(aggr, aggr + passive); - let pooled_fold = ratio(self.c.folded_to_bet, facing_bet); - let mut street_fold_to_bet = [None; 3]; - if let (true, Some(pooled)) = (street_fold_on(), pooled_fold) { - for i in 0..3 { - let n = (self.c.street_fold[i] + self.c.street_call[i]) as f64; - if n > 0.0 { - street_fold_to_bet[i] = - Some((self.c.street_fold[i] as f64 + STREET_FOLD_PRIOR * pooled) / (n + STREET_FOLD_PRIOR)); - } - } - } - let river_bluff = self.world.river_bluff().filter(|_| river_showdown_on()); - // Line reads, shrunk like the street reads: c-bet folds toward the flop fold read (else the - // pooled one), the others toward a regular's number. - let shrunk = |num: u32, den: u32, anchor: Option| { - anchor.filter(|_| den > 0).map(|a| (num as f64 + STREET_FOLD_PRIOR * a) / (den as f64 + STREET_FOLD_PRIOR)) - }; - let flop_anchor = street_fold_to_bet[0].or(pooled_fold); - let fold_to_cbet = shrunk(self.c.cbet_folded, self.c.cbet_faced, flop_anchor).filter(|_| line_read_on(READ_CBET)); - let fold_to_three_bet = shrunk(self.c.three_bet_folded, self.c.three_bet_faced, Some(FOLD_TO_THREE_BET_PRIOR)) - .filter(|_| line_read_on(READ_THREE_BET)); - let check_raise = (self.c.xr_chances > 0) - .then(|| (self.c.xr_made as f64 + CHECK_RAISE_KAPPA * CHECK_RAISE_PRIOR) / (self.c.xr_chances as f64 + CHECK_RAISE_KAPPA)) - .filter(|_| line_read_on(READ_CHECK_RAISE)); - Some(Profile { - street_fold_to_bet, - fold_to_cbet, - fold_to_three_bet, - check_raise, - river_bluff_share: river_bluff.map(|(s, _)| s), - river_bluff_shown: river_bluff.map(|(_, n)| n as f64), - vpip: ratio(self.c.vpip, self.c.hands), - pfr: ratio(self.c.pfr, self.c.hands), - fold_to_bet: ratio(self.c.folded_to_bet, facing_bet), - aggression: ratio(self.c.aggressive, postflop_actions), - turn_aggression: street_aggr(self.c.turn_aggressive, self.c.turn_passive), - river_aggression: street_aggr(self.c.river_aggressive, self.c.river_passive), - confidence: Some(confidence), - ..Profile::default() - }) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::exploit::style::{classify, Style}; - - fn rec(street: Street, seat: u8, action: SeenAction) -> ActionRecord { - ActionRecord { street, seat, action, amount: None } - } - - /// The line reads count only the responses to their own line, shrink toward their anchors, and - /// stay out of the read until switched on (so the ladder stays bit-identical by default). - #[test] - fn line_reads_count_their_own_spots() { - use SeenAction::*; - let mut m = SessionMemory::new(); - // Hero (seat 1) opens and c-bets, the opponent (seat 2) folds the flop: a c-bet fold. - let cbet_fold = [ - rec(Street::Preflop, 1, PostSmallBlind), rec(Street::Preflop, 2, PostBigBlind), - rec(Street::Preflop, 1, Raise), rec(Street::Preflop, 2, Call), - rec(Street::Flop, 2, Check), rec(Street::Flop, 1, Bet), rec(Street::Flop, 2, Fold), - ]; - // The opponent opens, hero 3-bets, the opponent folds. - let three_fold = [ - rec(Street::Preflop, 2, PostSmallBlind), rec(Street::Preflop, 1, PostBigBlind), - rec(Street::Preflop, 2, Raise), rec(Street::Preflop, 1, Raise), rec(Street::Preflop, 2, Fold), - ]; - for _ in 0..30 { - m.observe_hand(&cbet_fold, 0, 2); - m.observe_hand(&three_fold, 0, 2); - } - assert_eq!((m.c.cbet_faced, m.c.cbet_folded), (30, 30)); - assert_eq!((m.c.three_bet_faced, m.c.three_bet_folded), (30, 30)); - assert_eq!((m.c.xr_chances, m.c.xr_made), (30, 0), "checked, faced the bet, folded: no check-raise"); - let off = m.read().expect("read"); - assert_eq!((off.fold_to_cbet, off.fold_to_three_bet, off.check_raise), (None, None, None)); - set_line_reads(READ_CBET | READ_THREE_BET | READ_CHECK_RAISE); - let on = m.read().expect("read"); - set_line_reads(0); - assert!(on.fold_to_cbet.unwrap() > 0.9); - assert!((on.fold_to_three_bet.unwrap() - (30.0 + 15.0 * 0.55) / 45.0).abs() < 1e-12); - assert!((on.check_raise.unwrap() - 15.0 * 0.08 / 45.0).abs() < 1e-12); - } - - /// One heads-up hand (hero seat 0 = seat 1, opponent seat 2): the opponent calls hero's preflop - /// raise (voluntary, not a raise), then calls a flop bet and folds the turn (passive, folds to a - /// bet, never aggressive). - fn loose_passive_hand() -> Vec { - vec![ - rec(Street::Preflop, 1, SeenAction::PostSmallBlind), - rec(Street::Preflop, 2, SeenAction::PostBigBlind), - rec(Street::Preflop, 1, SeenAction::Raise), - rec(Street::Preflop, 2, SeenAction::Call), - rec(Street::Flop, 1, SeenAction::Bet), - rec(Street::Flop, 2, SeenAction::Call), - rec(Street::Turn, 1, SeenAction::Bet), - rec(Street::Turn, 2, SeenAction::Fold), - ] - } - - #[test] - fn no_read_before_the_warmup() { - let mut m = SessionMemory::new(); - let h = loose_passive_hand(); - for _ in 0..WARMUP_HANDS - 1 { - m.observe_hand(&h, 0, 2); - } - assert_eq!(m.read(), None); - m.observe_hand(&h, 0, 2); - assert!(m.read().is_some()); - } - - #[test] - fn a_seat_that_only_posts_a_blind_is_not_vpip() { - // Hero seat 0; the opponent (seat 2) is the big blind and checks its option: no voluntary - // money, no raise. - let hand = vec![ - rec(Street::Preflop, 1, SeenAction::PostSmallBlind), - rec(Street::Preflop, 2, SeenAction::PostBigBlind), - rec(Street::Preflop, 1, SeenAction::Call), - rec(Street::Preflop, 2, SeenAction::Check), - ]; - let mut m = SessionMemory::new(); - for _ in 0..WARMUP_HANDS { - m.observe_hand(&hand, 0, 2); - } - let p = m.read().expect("read after warmup"); - assert_eq!(p.vpip, Some(0.0)); - assert_eq!(p.pfr, Some(0.0)); - } - - #[test] - fn the_loose_passive_opponent_reads_as_a_calling_station() { - let mut m = SessionMemory::new(); - let h = loose_passive_hand(); - for _ in 0..40 { - m.observe_hand(&h, 0, 2); - } - let p = m.read().expect("read"); - assert_eq!(p.vpip, Some(1.0)); // calls every preflop - assert_eq!(p.pfr, Some(0.0)); - assert_eq!(p.fold_to_bet, Some(0.5)); // one call, one fold facing a bet - assert_eq!(p.aggression, Some(0.0)); // never bets or raises postflop - assert_eq!(classify(&p), Style::CallingStation); - } - - #[test] - fn checks_count_toward_aggression_so_a_passive_opponent_reads_passive() { - // Seat 2 bets once but checks the flop in every other hand. Aggression must be 1 / (1 bet + - // many checks), near zero - not 1 / 1 from leaving the checks out of the denominator. - let bet = vec![ - rec(Street::Preflop, 1, SeenAction::PostSmallBlind), - rec(Street::Preflop, 2, SeenAction::PostBigBlind), - rec(Street::Preflop, 1, SeenAction::Call), - rec(Street::Preflop, 2, SeenAction::Check), - rec(Street::Flop, 2, SeenAction::Bet), - ]; - let check = vec![ - rec(Street::Preflop, 1, SeenAction::PostSmallBlind), - rec(Street::Preflop, 2, SeenAction::PostBigBlind), - rec(Street::Preflop, 1, SeenAction::Call), - rec(Street::Preflop, 2, SeenAction::Check), - rec(Street::Flop, 2, SeenAction::Check), - ]; - let mut m = SessionMemory::new(); - m.observe_hand(&bet, 0, 2); - for _ in 0..29 { - m.observe_hand(&check, 0, 2); - } - let p = m.read().expect("read"); - assert_eq!(p.aggression, Some(1.0 / 30.0)); // 1 bet, 29 checks - } - - #[test] - fn per_street_aggression_splits_the_turn_from_the_pooled_read() { - // Seat 2 checks the flop (passive) but bets the turn (aggressive), no river action. The pooled - // aggression is 1 bet / (1 bet + 1 check) = 0.5, but the TURN aggression is 1/1 = 1.0, and the - // river stays None. This is exactly the barreler the pooled read under-sells. - let hand = vec![ - rec(Street::Preflop, 1, SeenAction::PostSmallBlind), - rec(Street::Preflop, 2, SeenAction::PostBigBlind), - rec(Street::Preflop, 1, SeenAction::Raise), - rec(Street::Preflop, 2, SeenAction::Call), - rec(Street::Flop, 1, SeenAction::Check), - rec(Street::Flop, 2, SeenAction::Check), - rec(Street::Turn, 1, SeenAction::Check), - rec(Street::Turn, 2, SeenAction::Bet), - ]; - let mut m = SessionMemory::new(); - for _ in 0..40 { - m.observe_hand(&hand, 0, 2); - } - let p = m.read().expect("read"); - assert_eq!(p.aggression, Some(0.5)); // 1 bet, 1 flop check pooled - assert_eq!(p.turn_aggression, Some(1.0)); // bets every turn, never passive on the turn - assert_eq!(p.river_aggression, None); // no river action seen - } - - #[test] - fn street_fold_is_shrunk_toward_the_pooled_read() { - // Folds every flop bet, calls every turn bet: pooled fold 0.5; the flop (n=40 folds) moves - // well above it, the turn well below it, the river (no data) stays None. - let hand = vec![ - rec(Street::Preflop, 1, SeenAction::PostSmallBlind), - rec(Street::Preflop, 2, SeenAction::PostBigBlind), - rec(Street::Preflop, 1, SeenAction::Raise), - rec(Street::Preflop, 2, SeenAction::Call), - rec(Street::Flop, 1, SeenAction::Bet), - rec(Street::Flop, 2, SeenAction::Fold), - ]; - let call = vec![ - rec(Street::Preflop, 1, SeenAction::Raise), - rec(Street::Preflop, 2, SeenAction::Call), - rec(Street::Turn, 1, SeenAction::Bet), - rec(Street::Turn, 2, SeenAction::Call), - ]; - let mut m = SessionMemory::new(); - for _ in 0..20 { - m.observe_hand(&hand, 0, 2); - m.observe_hand(&call, 0, 2); - } - let p = m.read().expect("read"); - assert_eq!(p.fold_to_bet, Some(0.5)); - let flop = p.street_fold_to_bet[0].expect("flop"); - let turn = p.street_fold_to_bet[1].expect("turn"); - assert!(flop > 0.7 && flop < 1.0, "{flop}"); - assert!(turn < 0.3 && turn > 0.0, "{turn}"); - assert_eq!(p.street_fold_to_bet[2], None); - } - - #[test] - fn a_tight_folding_opponent_reads_as_a_nit() { - // Seat 2 folds preflop every hand: no voluntary money, and (vpip 0) classifies as a nit. - let hand = vec![ - rec(Street::Preflop, 1, SeenAction::PostSmallBlind), - rec(Street::Preflop, 2, SeenAction::PostBigBlind), - rec(Street::Preflop, 1, SeenAction::Raise), - rec(Street::Preflop, 2, SeenAction::Fold), - ]; - let mut m = SessionMemory::new(); - for _ in 0..40 { - m.observe_hand(&hand, 0, 2); - } - let p = m.read().expect("read"); - assert_eq!(p.vpip, Some(0.0)); - assert_eq!(classify(&p), Style::Nit); - } -} +//! Session memory (Stage 1): the engine builds its read from the opponent's OBSERVED actions over +//! the hands of a session, instead of being handed the converged HUD read (`sim::reads`) or playing +//! blind. A HUD that only counts - per opponent seat, preflop voluntary money and raises, postflop +//! folds-to-a-bet and aggression - turned into a `Profile` once a warmup of hands is seen, so the +//! first hands play blind and the read converges to the truth over the session. +//! +//! The gap blind -> read-given that `benchmarks/baseline.txt` / `tests/sim_blind` measure is exactly +//! what this must recapture: a `... (memory)` scenario lands between the blind and the read-given +//! twin, the share of the prize that observation alone earns. Every opponent seat is the same fixed +//! archetype, so their counts pool into one read. + +use crate::exploit::profile::Profile; +use crate::exploit::sample::shrink_aggression; +use crate::game::{line, ActionRecord, SeenAction, Street}; + +pub use super::welt_memory::{ + strength_band, Cell, Move, Pos, Reveal, SizeBucket, Showdown, Texture, Tank, WorldEvent, WorldHand, + WorldMemory, STRENGTH_BANDS, +}; + +/// Hands to observe before the read is trusted; until then `read` is `None` (the engine plays +/// blind). Keeps an early, noisy sample from steering worse than no read at all. +pub const WARMUP_HANDS: u32 = 25; + +/// Postflop actions at which the read's confidence reaches 0.5 (half-life). Matches the Bayesian +/// posterior's `VERTRAUEN_HALB` so the counts HUD and `exploit::posterior` agree on how fast a read +/// earns trust. The river gearbox turns this confidence into the KL trust radius. +pub const CONFIDENCE_HALF: f64 = 30.0; + +/// Running tallies over the opponent archetype. Preflop opportunities (`hands`) and the voluntary / +/// raise counts drive vpip and pfr; the postflop tallies drive fold-to-bet and aggression. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +struct Counts { + hands: u32, + vpip: u32, + pfr: u32, + folded_to_bet: u32, + passive_call: u32, + passive_check: u32, + aggressive: u32, + // Per-street aggression split (turn and river only — the streets the subgame gearboxes solve). + // `*_passive` is calls plus checks on that street (the aggression denominator, matching the pooled + // one which counts checks); folds are excluded, as in the pooled aggression. + turn_aggressive: u32, + turn_passive: u32, + river_aggressive: u32, + river_passive: u32, + // Facing-a-bet outcomes per street (flop, turn, river): folds and calls, for the per-street + // fold-to-bet read. + street_fold: [u32; 3], + street_call: [u32; 3], + // Line-specific HUD stats (`game::line`): responses facing a c-bet / a 3-bet after opening / + // a bet after own check, and how many of them folded / folded / raised. + cbet_faced: u32, + cbet_folded: u32, + three_bet_faced: u32, + three_bet_folded: u32, + xr_chances: u32, + xr_made: u32, +} + +fn street_index(street: Street) -> Option { + match street { + Street::Flop => Some(0), + Street::Turn => Some(1), + Street::River => Some(2), + Street::Preflop => None, + } +} + +/// Facing-a-bet samples that weigh as much as the pooled read when shrinking a street's fold rate. +pub const STREET_FOLD_PRIOR: f64 = crate::exploit::sample::STREET_PRIOR; + +static STREET_FOLD: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true); + +/// Switch the per-street fold read on or off (A/B arm for the ladder). Default on. +pub fn set_street_fold(on: bool) { + STREET_FOLD.store(on, std::sync::atomic::Ordering::Relaxed); +} + +fn street_fold_on() -> bool { + STREET_FOLD.load(std::sync::atomic::Ordering::Relaxed) +} + +/// Line-specific HUD reads switched into `read()`: bit 1 fold to c-bet, 2 fold to 3-bet, 4 check-raise. +static LINE_READS: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0); + +/// Line reads in `read()` (A/B arm): `READ_CBET | READ_THREE_BET | READ_CHECK_RAISE`. Default none. +pub fn set_line_reads(mask: u8) { + LINE_READS.store(mask, std::sync::atomic::Ordering::Relaxed); +} +pub const READ_CBET: u8 = 1; +pub const READ_THREE_BET: u8 = 2; +pub const READ_CHECK_RAISE: u8 = 4; + +fn line_read_on(bit: u8) -> bool { + LINE_READS.load(std::sync::atomic::Ordering::Relaxed) & bit != 0 +} + +/// Population anchors the line reads shrink toward over `STREET_FOLD_PRIOR` samples (a regular's +/// HUD): fold to 3-bet and check-raise have no pooled read to anchor on. +use crate::exploit::sample::{ + CHECK_RAISE_ANCHOR as CHECK_RAISE_PRIOR, CHECK_RAISE_KAPPA, FOLD_TO_THREE_BET_ANCHOR as FOLD_TO_THREE_BET_PRIOR, +}; + +static RIVER_SHOWDOWN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// Switch the river showdown read (`Profile::river_bluff_share`, from the world memory's revealed river +/// bets) into `read()` (A/B arm for the ladder). Default off until the ladder proves it. +pub fn set_river_showdown(on: bool) { + RIVER_SHOWDOWN.store(on, std::sync::atomic::Ordering::Relaxed); +} + +fn river_showdown_on() -> bool { + RIVER_SHOWDOWN.load(std::sync::atomic::Ordering::Relaxed) +} + +/// The read a HUD accumulates from watching one fixed opponent archetype play a session. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct SessionMemory { + c: Counts, + /// The richer dimensions (sizing x strength, texture x position cells, showdown reveals, timing), + /// see `sim::welt_memory`. Filled only by `observe_world_hand`; `read()` ignores it, so the classic + /// HUD read (and every existing ladder number) is unchanged by it. + world: WorldMemory, +} + +impl SessionMemory { + pub fn new() -> Self { + Self::default() + } + + /// The world-dimension observations (sizing, texture/position cells, showdowns, timing). + pub fn world(&self) -> &WorldMemory { + &self.world + } + + /// Fold one finished hand's world observations (see `WorldHand`) into the world memory. + /// The raw (chances, hits) per read, for the empirical-Bayes fit of the population priors + /// (`lesen/eichung.py`), named like `lesen/zaehler.py`. + pub fn line_counts(&self) -> Vec<(&'static str, u32, u32)> { + let c = &self.c; + vec![ + ("vpip", c.hands, c.vpip), + ("pfr", c.hands, c.pfr), + ("aggression", c.aggressive + c.passive_call + c.passive_check, c.aggressive), + ("flopFoldToBet", c.street_fold[0] + c.street_call[0], c.street_fold[0]), + ("turnFoldToBet", c.street_fold[1] + c.street_call[1], c.street_fold[1]), + ("riverFoldToBet", c.street_fold[2] + c.street_call[2], c.street_fold[2]), + ("foldToCbet", c.cbet_faced, c.cbet_folded), + ("foldToThreeBet", c.three_bet_faced, c.three_bet_folded), + ("checkRaise", c.xr_chances, c.xr_made), + ] + } + + pub fn observe_world_hand(&mut self, hand: &WorldHand) { + self.world.observe_world_hand(hand); + } + + /// Fold every opponent seat's actions of one finished hand into the counts. `hero` is the + /// 0-based hero seat; every other of the `players` seats is an opponent of the same archetype. + pub fn observe_hand(&mut self, history: &[ActionRecord], hero: usize, players: usize) { + for seat in 1..=players as u8 { + if seat as usize - 1 != hero { + self.observe_seat(history, seat); + } + } + } + + /// The line-specific responses of `seat`: each of its actions judged against the line before it. + fn observe_lines(&mut self, history: &[ActionRecord], seat: u8) { + for (k, r) in history.iter().enumerate().filter(|(_, r)| r.seat == seat) { + let before = &history[..k]; + let folded = r.action == SeenAction::Fold; + if r.street == Street::Flop && line::facing_cbet(before, seat) { + self.c.cbet_faced += 1; + self.c.cbet_folded += folded as u32; + } + if r.street == Street::Preflop && line::facing_three_bet(before, seat) { + self.c.three_bet_faced += 1; + self.c.three_bet_folded += folded as u32; + } + if r.street != Street::Preflop && line::check_raise_chance(before, seat, r.street) { + self.c.xr_chances += 1; + self.c.xr_made += r.action.is_aggressive() as u32; + } + } + } + + /// One seat's actions of a finished hand (a per-opponent memory at a mixed table, `sim::sechsmax`). + pub fn observe_seat(&mut self, history: &[ActionRecord], seat: u8) { + self.observe_lines(history, seat); + self.c.hands += 1; + let (mut voluntary, mut raised) = (false, false); + for r in history.iter().filter(|r| r.seat == seat) { + if r.street == Street::Preflop { + // Blinds are forced (PostSmallBlind / PostBigBlind); a check is free. Only a call or + // an aggressive action puts money in by choice. + match r.action { + SeenAction::Call | SeenAction::Bet | SeenAction::Raise | SeenAction::AllIn => { + voluntary = true; + } + _ => {} + } + raised |= r.action.is_aggressive(); + } else { + // Postflop a fold or a call only happens facing a bet; a check faces nothing. The + // check still counts as a passive action for aggression (matching how the oracle + // reads are measured, `tests/sim_opponent_stats`): leaving checks out of the + // denominator makes a passive, check-heavy opponent look far more aggressive than it + // is, and `bluff_share` reads aggression directly. + match r.action { + SeenAction::Fold => { + self.c.folded_to_bet += 1; + if let Some(i) = street_index(r.street) { + self.c.street_fold[i] += 1; + } + } + SeenAction::Call => { + if let Some(i) = street_index(r.street) { + self.c.street_call[i] += 1; + } + self.c.passive_call += 1; + self.bump_passive(r.street); + } + SeenAction::Check => { + self.c.passive_check += 1; + self.bump_passive(r.street); + } + a if a.is_aggressive() => { + self.c.aggressive += 1; + self.bump_aggressive(r.street); + } + _ => {} + } + } + } + self.c.vpip += voluntary as u32; + self.c.pfr += raised as u32; + } + + /// A passive postflop action (call or check) on the turn/river, for the per-street aggression + /// denominator. Flop and preflop are not split. + fn bump_passive(&mut self, street: Street) { + match street { + Street::Turn => self.c.turn_passive += 1, + Street::River => self.c.river_passive += 1, + _ => {} + } + } + + /// An aggressive postflop action (bet or raise) on the turn/river, for the per-street numerator. + fn bump_aggressive(&mut self, street: Street) { + match street { + Street::Turn => self.c.turn_aggressive += 1, + Street::River => self.c.river_aggressive += 1, + _ => {} + } + } + + /// The read so far, or `None` during the warmup. vpip / pfr are over hands; fold-to-bet is folds + /// over folds-plus-calls facing a bet; aggression is bets-and-raises over bets-raises-and-calls. + pub fn read(&self) -> Option { + if self.c.hands < WARMUP_HANDS { + return None; + } + let ratio = |num: u32, den: u32| (den > 0).then(|| num as f64 / den as f64); + let facing_bet = self.c.folded_to_bet + self.c.passive_call; + // Aggression frequency: bets and raises over every non-folding postflop action, checks + // included (see `observe_seat`). + let postflop_actions = self.c.aggressive + self.c.passive_call + self.c.passive_check; + // Confidence for the gearbox: the read is only as trustworthy as its weaker postflop sample — + // the facing-a-bet count (drives fold_to_bet / the defense belief) and the total postflop + // count (drives aggression / the betting-polarization belief). Half at CONFIDENCE_HALF. + let conf = |n: u32| n as f64 / (n as f64 + CONFIDENCE_HALF); + let confidence = conf(facing_bet.min(postflop_actions)); + // Per-street aggression: bets/raises over bets-raises-plus-passive on that street (same shape + // as the pooled frequency). `None` until the street has an action, so `believed_villain` falls + // back to the pooled read. + let street_aggr = |aggr: u32, passive: u32| ratio(aggr, aggr + passive); + let pooled_fold = ratio(self.c.folded_to_bet, facing_bet); + let mut street_fold_to_bet = [None; 3]; + if let (true, Some(pooled)) = (street_fold_on(), pooled_fold) { + for i in 0..3 { + let n = (self.c.street_fold[i] + self.c.street_call[i]) as f64; + if n > 0.0 { + street_fold_to_bet[i] = + Some((self.c.street_fold[i] as f64 + STREET_FOLD_PRIOR * pooled) / (n + STREET_FOLD_PRIOR)); + } + } + } + let river_bluff = self.world.river_bluff().filter(|_| river_showdown_on()); + // Line reads, shrunk like the street reads: c-bet folds toward the flop fold read (else the + // pooled one), the others toward a regular's number. + let shrunk = |num: u32, den: u32, anchor: Option| { + anchor.filter(|_| den > 0).map(|a| (num as f64 + STREET_FOLD_PRIOR * a) / (den as f64 + STREET_FOLD_PRIOR)) + }; + let flop_anchor = street_fold_to_bet[0].or(pooled_fold); + let fold_to_cbet = shrunk(self.c.cbet_folded, self.c.cbet_faced, flop_anchor).filter(|_| line_read_on(READ_CBET)); + let fold_to_three_bet = shrunk(self.c.three_bet_folded, self.c.three_bet_faced, Some(FOLD_TO_THREE_BET_PRIOR)) + .filter(|_| line_read_on(READ_THREE_BET)); + let check_raise = (self.c.xr_chances > 0) + .then(|| (self.c.xr_made as f64 + CHECK_RAISE_KAPPA * CHECK_RAISE_PRIOR) / (self.c.xr_chances as f64 + CHECK_RAISE_KAPPA)) + .filter(|_| line_read_on(READ_CHECK_RAISE)); + Some(Profile { + street_fold_to_bet, + fold_to_cbet, + fold_to_three_bet, + check_raise, + river_bluff_share: river_bluff.map(|(s, _)| s), + river_bluff_shown: river_bluff.map(|(_, n)| n as f64), + vpip: ratio(self.c.vpip, self.c.hands), + pfr: ratio(self.c.pfr, self.c.hands), + fold_to_bet: ratio(self.c.folded_to_bet, facing_bet), + aggression: ratio(self.c.aggressive, postflop_actions), + turn_aggression: street_aggr(self.c.turn_aggressive, self.c.turn_passive), + river_aggression: street_aggr(self.c.river_aggressive, self.c.river_passive), + confidence: Some(confidence), + ..Profile::default() + }) + } +} + +impl SessionMemory { + /// The raw rates counted so far (no warmup, no shrinking): the "truth" a long pre-session measures, + /// from which the HUD mode draws its noisy PokerIntel numbers (`sim::hud`). + pub fn raw_profile(&self) -> Profile { + let ratio = |num: u32, den: u32| (den > 0).then(|| num as f64 / den as f64); + Profile { + vpip: ratio(self.c.vpip, self.c.hands), + pfr: ratio(self.c.pfr, self.c.hands), + fold_to_bet: ratio(self.c.folded_to_bet, self.c.folded_to_bet + self.c.passive_call), + aggression: ratio(self.c.aggressive, self.c.aggressive + self.c.passive_call + self.c.passive_check), + fold_to_cbet: ratio(self.c.cbet_folded, self.c.cbet_faced), + fold_to_three_bet: ratio(self.c.three_bet_folded, self.c.three_bet_faced), + check_raise: ratio(self.c.xr_made, self.c.xr_chances), + ..Profile::default() + } + } + + /// The read a live table gives (`wire::decode_villain`): the client HUD `hud` (raw PokerIntel + /// numbers) believed over `GLAUBHAFT` + the hands seen so far (`sample::hud_profile`), the + /// aggression on its own counted moves, the street reads counted here toward the HUD-pooled ones. + pub fn hud_read(&self, hud: &Profile) -> Option { + let hands = crate::exploit::sample::GLAUBHAFT + self.c.hands as f64; + let base = crate::exploit::sample::hud_profile(hud, hands); + let ratio = |num: u32, den: u32| (den > 0).then(|| num as f64 / den as f64); + let actions = self.c.aggressive + self.c.passive_call + self.c.passive_check; + let p = if actions > 0 { + shrink_aggression(base, ratio(self.c.aggressive, actions), actions as f64) + } else { + base + }; + let street = |aggr: u32, passive: u32, anchor: Option| { + crate::exploit::sample::shrink_street(ratio(aggr, aggr + passive), (aggr + passive) as f64, anchor) + }; + let mut street_fold_to_bet = [None; 3]; + if street_fold_on() { + for (i, s) in street_fold_to_bet.iter_mut().enumerate() { + *s = street(self.c.street_fold[i], self.c.street_call[i], p.fold_to_bet); + } + } + let river_bluff = self.world.river_bluff().filter(|_| river_showdown_on()); + Some(Profile { + turn_aggression: street(self.c.turn_aggressive, self.c.turn_passive, p.aggression).or(p.turn_aggression), + river_aggression: street(self.c.river_aggressive, self.c.river_passive, p.aggression).or(p.river_aggression), + street_fold_to_bet, + river_bluff_share: river_bluff.map(|(s, _)| s), + river_bluff_shown: river_bluff.map(|(_, n)| n as f64), + ..p + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::exploit::style::{classify, Style}; + + fn rec(street: Street, seat: u8, action: SeenAction) -> ActionRecord { + ActionRecord { street, seat, action, amount: None } + } + + /// The line reads count only the responses to their own line, shrink toward their anchors, and + /// stay out of the read until switched on (so the ladder stays bit-identical by default). + #[test] + fn line_reads_count_their_own_spots() { + use SeenAction::*; + let mut m = SessionMemory::new(); + // Hero (seat 1) opens and c-bets, the opponent (seat 2) folds the flop: a c-bet fold. + let cbet_fold = [ + rec(Street::Preflop, 1, PostSmallBlind), rec(Street::Preflop, 2, PostBigBlind), + rec(Street::Preflop, 1, Raise), rec(Street::Preflop, 2, Call), + rec(Street::Flop, 2, Check), rec(Street::Flop, 1, Bet), rec(Street::Flop, 2, Fold), + ]; + // The opponent opens, hero 3-bets, the opponent folds. + let three_fold = [ + rec(Street::Preflop, 2, PostSmallBlind), rec(Street::Preflop, 1, PostBigBlind), + rec(Street::Preflop, 2, Raise), rec(Street::Preflop, 1, Raise), rec(Street::Preflop, 2, Fold), + ]; + for _ in 0..30 { + m.observe_hand(&cbet_fold, 0, 2); + m.observe_hand(&three_fold, 0, 2); + } + assert_eq!((m.c.cbet_faced, m.c.cbet_folded), (30, 30)); + assert_eq!((m.c.three_bet_faced, m.c.three_bet_folded), (30, 30)); + assert_eq!((m.c.xr_chances, m.c.xr_made), (30, 0), "checked, faced the bet, folded: no check-raise"); + let off = m.read().expect("read"); + assert_eq!((off.fold_to_cbet, off.fold_to_three_bet, off.check_raise), (None, None, None)); + set_line_reads(READ_CBET | READ_THREE_BET | READ_CHECK_RAISE); + let on = m.read().expect("read"); + set_line_reads(0); + assert!(on.fold_to_cbet.unwrap() > 0.9); + assert!((on.fold_to_three_bet.unwrap() - (30.0 + 15.0 * 0.55) / 45.0).abs() < 1e-12); + assert!((on.check_raise.unwrap() - 15.0 * 0.08 / 45.0).abs() < 1e-12); + } + + /// One heads-up hand (hero seat 0 = seat 1, opponent seat 2): the opponent calls hero's preflop + /// raise (voluntary, not a raise), then calls a flop bet and folds the turn (passive, folds to a + /// bet, never aggressive). + fn loose_passive_hand() -> Vec { + vec![ + rec(Street::Preflop, 1, SeenAction::PostSmallBlind), + rec(Street::Preflop, 2, SeenAction::PostBigBlind), + rec(Street::Preflop, 1, SeenAction::Raise), + rec(Street::Preflop, 2, SeenAction::Call), + rec(Street::Flop, 1, SeenAction::Bet), + rec(Street::Flop, 2, SeenAction::Call), + rec(Street::Turn, 1, SeenAction::Bet), + rec(Street::Turn, 2, SeenAction::Fold), + ] + } + + #[test] + fn no_read_before_the_warmup() { + let mut m = SessionMemory::new(); + let h = loose_passive_hand(); + for _ in 0..WARMUP_HANDS - 1 { + m.observe_hand(&h, 0, 2); + } + assert_eq!(m.read(), None); + m.observe_hand(&h, 0, 2); + assert!(m.read().is_some()); + } + + #[test] + fn a_seat_that_only_posts_a_blind_is_not_vpip() { + // Hero seat 0; the opponent (seat 2) is the big blind and checks its option: no voluntary + // money, no raise. + let hand = vec![ + rec(Street::Preflop, 1, SeenAction::PostSmallBlind), + rec(Street::Preflop, 2, SeenAction::PostBigBlind), + rec(Street::Preflop, 1, SeenAction::Call), + rec(Street::Preflop, 2, SeenAction::Check), + ]; + let mut m = SessionMemory::new(); + for _ in 0..WARMUP_HANDS { + m.observe_hand(&hand, 0, 2); + } + let p = m.read().expect("read after warmup"); + assert_eq!(p.vpip, Some(0.0)); + assert_eq!(p.pfr, Some(0.0)); + } + + #[test] + fn the_loose_passive_opponent_reads_as_a_calling_station() { + let mut m = SessionMemory::new(); + let h = loose_passive_hand(); + for _ in 0..40 { + m.observe_hand(&h, 0, 2); + } + let p = m.read().expect("read"); + assert_eq!(p.vpip, Some(1.0)); // calls every preflop + assert_eq!(p.pfr, Some(0.0)); + assert_eq!(p.fold_to_bet, Some(0.5)); // one call, one fold facing a bet + assert_eq!(p.aggression, Some(0.0)); // never bets or raises postflop + assert_eq!(classify(&p), Style::CallingStation); + } + + #[test] + fn checks_count_toward_aggression_so_a_passive_opponent_reads_passive() { + // Seat 2 bets once but checks the flop in every other hand. Aggression must be 1 / (1 bet + + // many checks), near zero - not 1 / 1 from leaving the checks out of the denominator. + let bet = vec![ + rec(Street::Preflop, 1, SeenAction::PostSmallBlind), + rec(Street::Preflop, 2, SeenAction::PostBigBlind), + rec(Street::Preflop, 1, SeenAction::Call), + rec(Street::Preflop, 2, SeenAction::Check), + rec(Street::Flop, 2, SeenAction::Bet), + ]; + let check = vec![ + rec(Street::Preflop, 1, SeenAction::PostSmallBlind), + rec(Street::Preflop, 2, SeenAction::PostBigBlind), + rec(Street::Preflop, 1, SeenAction::Call), + rec(Street::Preflop, 2, SeenAction::Check), + rec(Street::Flop, 2, SeenAction::Check), + ]; + let mut m = SessionMemory::new(); + m.observe_hand(&bet, 0, 2); + for _ in 0..29 { + m.observe_hand(&check, 0, 2); + } + let p = m.read().expect("read"); + assert_eq!(p.aggression, Some(1.0 / 30.0)); // 1 bet, 29 checks + } + + #[test] + fn per_street_aggression_splits_the_turn_from_the_pooled_read() { + // Seat 2 checks the flop (passive) but bets the turn (aggressive), no river action. The pooled + // aggression is 1 bet / (1 bet + 1 check) = 0.5, but the TURN aggression is 1/1 = 1.0, and the + // river stays None. This is exactly the barreler the pooled read under-sells. + let hand = vec![ + rec(Street::Preflop, 1, SeenAction::PostSmallBlind), + rec(Street::Preflop, 2, SeenAction::PostBigBlind), + rec(Street::Preflop, 1, SeenAction::Raise), + rec(Street::Preflop, 2, SeenAction::Call), + rec(Street::Flop, 1, SeenAction::Check), + rec(Street::Flop, 2, SeenAction::Check), + rec(Street::Turn, 1, SeenAction::Check), + rec(Street::Turn, 2, SeenAction::Bet), + ]; + let mut m = SessionMemory::new(); + for _ in 0..40 { + m.observe_hand(&hand, 0, 2); + } + let p = m.read().expect("read"); + assert_eq!(p.aggression, Some(0.5)); // 1 bet, 1 flop check pooled + assert_eq!(p.turn_aggression, Some(1.0)); // bets every turn, never passive on the turn + assert_eq!(p.river_aggression, None); // no river action seen + } + + #[test] + fn street_fold_is_shrunk_toward_the_pooled_read() { + // Folds every flop bet, calls every turn bet: pooled fold 0.5; the flop (n=40 folds) moves + // well above it, the turn well below it, the river (no data) stays None. + let hand = vec![ + rec(Street::Preflop, 1, SeenAction::PostSmallBlind), + rec(Street::Preflop, 2, SeenAction::PostBigBlind), + rec(Street::Preflop, 1, SeenAction::Raise), + rec(Street::Preflop, 2, SeenAction::Call), + rec(Street::Flop, 1, SeenAction::Bet), + rec(Street::Flop, 2, SeenAction::Fold), + ]; + let call = vec![ + rec(Street::Preflop, 1, SeenAction::Raise), + rec(Street::Preflop, 2, SeenAction::Call), + rec(Street::Turn, 1, SeenAction::Bet), + rec(Street::Turn, 2, SeenAction::Call), + ]; + let mut m = SessionMemory::new(); + for _ in 0..20 { + m.observe_hand(&hand, 0, 2); + m.observe_hand(&call, 0, 2); + } + let p = m.read().expect("read"); + assert_eq!(p.fold_to_bet, Some(0.5)); + let flop = p.street_fold_to_bet[0].expect("flop"); + let turn = p.street_fold_to_bet[1].expect("turn"); + assert!(flop > 0.7 && flop < 1.0, "{flop}"); + assert!(turn < 0.3 && turn > 0.0, "{turn}"); + assert_eq!(p.street_fold_to_bet[2], None); + } + + #[test] + fn a_tight_folding_opponent_reads_as_a_nit() { + // Seat 2 folds preflop every hand: no voluntary money, and (vpip 0) classifies as a nit. + let hand = vec![ + rec(Street::Preflop, 1, SeenAction::PostSmallBlind), + rec(Street::Preflop, 2, SeenAction::PostBigBlind), + rec(Street::Preflop, 1, SeenAction::Raise), + rec(Street::Preflop, 2, SeenAction::Fold), + ]; + let mut m = SessionMemory::new(); + for _ in 0..40 { + m.observe_hand(&hand, 0, 2); + } + let p = m.read().expect("read"); + assert_eq!(p.vpip, Some(0.0)); + assert_eq!(classify(&p), Style::Nit); + } +} diff --git a/src/sim/mod.rs b/src/sim/mod.rs index 5bcc68a6..54a4a5fb 100644 --- a/src/sim/mod.rs +++ b/src/sim/mod.rs @@ -8,6 +8,7 @@ pub mod benchmark; pub mod exploit_pop; pub mod exploit_river; pub mod gto; +pub mod hud; pub mod league; pub mod luck; pub mod memory; diff --git a/src/sim/sechsmax.rs b/src/sim/sechsmax.rs index 6a3e430f..43d683de 100644 --- a/src/sim/sechsmax.rs +++ b/src/sim/sechsmax.rs @@ -356,7 +356,7 @@ pub fn play_block(setup: &Setup6, b: u32) -> Vec { reads[s] = match setup.read { ReadMode::Oracle => opponent_profile(*o), ReadMode::Blind => None, - ReadMode::Memory => memory[m].read(), + ReadMode::Memory | ReadMode::Hud => memory[m].read(), }; } let hand = HandSetup { diff --git a/src/sim/session.rs b/src/sim/session.rs index 956dc7f0..5ed3c5e9 100644 --- a/src/sim/session.rs +++ b/src/sim/session.rs @@ -17,6 +17,9 @@ pub enum ReadMode { /// Build the read from the opponent's observed actions over the session (`sim::memory`): starts /// blind, converges toward the oracle. Lands between `Blind` and `Oracle` on the ladder. Memory, + /// Live-like: the seat carries a noisy client HUD (`sim::hud`, PokerIntel's measured effective + /// sample) and the memory counts on top of it, read like the live wire (`SessionMemory::hud_read`). + Hud, } #[derive(Clone, Copy, Debug, PartialEq)] @@ -144,6 +147,12 @@ fn deal_samples_at(setup: &Setup, cost: TableCost) -> (Vec, Vec, Measu let mut rake = 0.0; // The memory accumulates across every hand of the session, in order; unused in the other modes. let mut memory = SessionMemory::new(); + // Hud: the truth from a pre-session on its own seed, then one noisy HUD for the whole session. + let hud = (setup.read == ReadMode::Hud).then(|| { + let pre = Setup { read: ReadMode::Memory, deals: super::hud::HUD_VOR, seed: setup.seed ^ 0x4855_4400_0000_0001, ..*setup }; + let (_, _, _, seen) = deal_samples_at(&pre, cost); + super::hud::draw(&super::hud::truth(&seen), Rng::seeded(mix(setup.seed, 0x4855_4402))) + }); for d in 0..setup.deals { let (cards, _) = deal(players as usize, Rng::seeded(mix(setup.seed, d as u64))); let (mut sum, mut raw) = (0.0, 0.0); @@ -153,6 +162,7 @@ fn deal_samples_at(setup: &Setup, cost: TableCost) -> (Vec, Vec, Measu ReadMode::Oracle => HandRead::Oracle, ReadMode::Blind => HandRead::Given(None), ReadMode::Memory => HandRead::Given(memory.read()), + ReadMode::Hud => HandRead::Given(memory.hud_read(hud.as_ref().expect("hud"))), }; let hand = HandSetup { deal: &cards, @@ -163,7 +173,7 @@ fn deal_samples_at(setup: &Setup, cost: TableCost) -> (Vec, Vec, Measu read, }; // Only the memory mode feeds the hand back into the accumulator afterwards. - let track = (setup.read == ReadMode::Memory).then_some(&mut memory); + let track = matches!(setup.read, ReadMode::Memory | ReadMode::Hud).then_some(&mut memory); let r = play_hand_tracked(&hand, cost, track); rake += r.rake; sum += r.hero_net - r.luck; diff --git a/src/wire/decode_villain.rs b/src/wire/decode_villain.rs index f4cd3c11..1d79c9be 100644 --- a/src/wire/decode_villain.rs +++ b/src/wire/decode_villain.rs @@ -1,6 +1,6 @@ use crate::exploit::mark::with_mark; use crate::exploit::profile::Profile; -use crate::exploit::sample::{shrink, shrink_aggression, shrink_street, CHECK_RAISE_ANCHOR, FOLD_TO_THREE_BET_ANCHOR}; +use crate::exploit::sample::{hud_profile, shrink_aggression, shrink_street}; use crate::fault::Fault; use crate::game::Villain; use crate::json::field::{at, join, optional, text}; @@ -37,9 +37,10 @@ fn profile(villain: &Value, path: &str) -> Result, Fault> { river_bluff_share: None, river_bluff_shown: None, }; - // `hands` (extension, exploit::sample): with it, few hands count little + // `hands` (extension, exploit::sample): with it, few hands count little; the line stats rest on + // the fraction of hands their spot arises in (`hud_profile`, shared with the sim's HUD mode). let shrunk = match opt_number_member(object, &at_profile, "hands")? { - Some(hands) => shrink(&raw, hands), + Some(hands) => hud_profile(&raw, hands), None => raw, }; // `aggressionActions` (extension, lesen/profil.py): the postflop moves the aggression was measured @@ -51,12 +52,6 @@ fn profile(villain: &Value, path: &str) -> Result, Fault> { streets(object, &at_profile, pooled).map(Some) } -/// Share of a HUD's hands in which the player faces a c-bet / a 3-bet after opening / a bet after -/// checking (rough 6-max frequencies): the effective sample of each line stat. -const CBET_SPOT_SHARE: f64 = 0.15; -const THREE_BET_SPOT_SHARE: f64 = 0.04; -const CHECK_RAISE_SPOT_SHARE: f64 = 0.10; - /// Per-street reads (extension, lesen/profil.py `strassen`): the rate seen on one street and the moves /// it rests on, each pulled toward the pooled (already shrunk) read by `shrink_street`. The engine /// already plays them (turn/river subgame, fold_chance); the session memory fills them in the sim. @@ -67,19 +62,6 @@ fn streets(object: &Value, path: &str, pooled: Profile) -> Result None, }) }; - // The HUD's line stats (foldToCbet, foldToThreeBet, checkRaise) come with the hand count only. Each - // rests on a fraction of those hands (the spot must arise): shrink them over that effective sample - // toward their anchor, as the sim memory does (`sim::memory`), so 40 HUD hands are not 40 c-bets. - let hands = opt_number_member(object, path, "hands")?; - // Without a hand count the profile is used as given (as `shrink` does). - let line = |x: Option, share: f64, anchor: Option| match hands { - Some(h) => shrink_street(x, h * share, anchor), - None => x, - }; - let cbet_anchor = pooled.fold_to_bet.or(Some(crate::exploit::fold_chance::DEFAULT_FOLD_TO_BET)); - let fold_to_cbet = line(pooled.fold_to_cbet, CBET_SPOT_SHARE, cbet_anchor); - let fold_to_three_bet = line(pooled.fold_to_three_bet, THREE_BET_SPOT_SHARE, Some(FOLD_TO_THREE_BET_ANCHOR)); - let check_raise = line(pooled.check_raise, CHECK_RAISE_SPOT_SHARE, Some(CHECK_RAISE_ANCHOR)); let turn_aggression = read("turnAggression", "turnAggressionActions", pooled.aggression)?; let river_aggression = read("riverAggression", "riverAggressionActions", pooled.aggression)?; let street_fold_to_bet = [ @@ -88,9 +70,6 @@ fn streets(object: &Value, path: &str, pooled: Profile) -> Result