From 0deb2e10de2e872a2589feb369f97beeff6df89a Mon Sep 17 00:00:00 2001 From: Marc Mintel Date: Fri, 13 Nov 2026 21:27:08 +0100 Subject: [PATCH] Gegnermodell: MDF-Fix, Strassen- und Linien-Reads, leichter 3-Bet, Leiter-Infrastruktur Bewiesen auf der gepaarten Leiter (19 Gegner, 95 %-CI, kein Profil verliert): - MDF-Floor/Veto-Fix: in der Sim bit-identisch, echte Haende Overfold 36 -> 7.5 bb. - Aggressions-Vertrauen, Strassen-Reads (Turn/River-Aggression, Fold-auf-Bet je Strasse, Bayes-geschrumpft zum Gesamt-Read), Zug-Logging der Gegnerprofile, Replay mit geloggten Profilen. - Leichter 3-Bet gegen 3-Bet-Folder (EV-Break-even risk/(pot+risk)): +6.62 +-5.23 bb/100 gegen den 3-Bet-Folder, sonst unveraendert. - Fold-auf-C-Bet preist die C-Bet: neutral. - Welt-Archetypen cbet-folder, 3bet-folder, check-raiser; ab_zelle (Zellen-Leiter, fortsetzbar), Warteschlange mit Thread-Budget, ab.py. Nicht drin: der Check-Raise-Abschlag (drei Varianten, keine sauber; wird durch ein Spielbaum-Modell ersetzt), der River-Showdown-Read bleibt aus (Verlierer -1.31). Ergebnisse: messung_engine/ERGEBNISSE.md. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 18 ++ entscheiden/replay.py | 35 ++++ lesen/handreview.py | 18 ++ lesen/profil.py | 35 +++- messung_engine/.gitignore | 8 + messung_engine/ERGEBNISSE.md | 22 +++ messung_engine/GRENZE.txt | 2 + messung_engine/ab.py | 71 ++++++++ messung_engine/pokerbench-engine-starter.ps1 | 83 ++++++++++ messung_engine/replay_aggrconf.txt | 19 +++ messung_engine/replay_jetzt_c03530a.kurz.txt | 13 ++ messung_engine/replay_jetzt_c03530a.txt | 19 +++ messung_engine/replay_mdf_fix.txt | 18 ++ messung_engine/warteschlange.txt | 16 ++ src/bin/ab_zelle.rs | 125 ++++++++++++++ src/engine/river_subgame.rs | 91 ++++++++++- src/exploit/fold_chance.rs | 18 +- src/exploit/mark.rs | 6 + src/exploit/mdf_floor.rs | 31 +++- src/exploit/profile.rs | 29 ++++ src/exploit/sample.rs | 44 +++++ src/exploit/table_fold.rs | 18 +- src/game/line.rs | 107 ++++++++++++ src/game/mod.rs | 1 + src/preflop/advise.rs | 58 ++++++- src/sim/memory.rs | 115 ++++++++++++- src/sim/table.rs | 5 +- src/sim/welt.rs | 163 ++++++++++++++++++- src/sim/welt_memory.rs | 44 +++++ src/wire/decode_villain.rs | 67 +++++++- tests/aggression_spec.py | 43 +++++ tests/handreview_spec.py | 19 +++ tests/line_reads.rs | 107 ++++++++++++ tests/wire_decode.rs | 55 +++++++ 34 files changed, 1497 insertions(+), 26 deletions(-) create mode 100644 messung_engine/.gitignore create mode 100644 messung_engine/ERGEBNISSE.md create mode 100644 messung_engine/GRENZE.txt create mode 100644 messung_engine/ab.py create mode 100644 messung_engine/pokerbench-engine-starter.ps1 create mode 100644 messung_engine/replay_aggrconf.txt create mode 100644 messung_engine/replay_jetzt_c03530a.kurz.txt create mode 100644 messung_engine/replay_jetzt_c03530a.txt create mode 100644 messung_engine/replay_mdf_fix.txt create mode 100644 messung_engine/warteschlange.txt create mode 100644 src/bin/ab_zelle.rs create mode 100644 src/game/line.rs create mode 100644 tests/line_reads.rs diff --git a/CLAUDE.md b/CLAUDE.md index c1c18fec..9e8a25c0 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -15,3 +15,21 @@ Dieser Baum ist der **Betrieb**: alles an einem Ort. Klon und App lassen sich abtrennen; sie liegen dann als eigener Baum daneben (`../pokersim`). Auftraege und aeltere Texte liegen in `docs/notizen/`, der Vertrag in `docs/VERTRAG.md`. + +## Messlaeufe (Leiter, Sims, Benches) + +Der Rechner ist auch der Spielrechner. Ein Messlauf darf ihn nie blockieren (13.11.: 30 parallele +Laeufe, 100 % CPU auf 32 Kernen, systemweit startete kein Prozess mehr). + +- **Hoechstens 28 Mess-Threads gleichzeitig (von 32 Kernen), alles in Priorität `Idle`**; `cargo` mit + `-j 4`. Laeuft der echte Client (Spielbetrieb), hoechstens 2. Lieber wenige Prozesse mit Thread-Pool + (`ab_zelle`, `POKERBENCH_THREADS`) als viele Einzelprozesse; nie dutzende Prozesse. Die Engine-Warteschlange + (`messung_engine/pokerbench-engine-starter.ps1`) haelt das Budget aus `messung_engine/GRENZE.txt` ein. +- **Erkennbare Namen.** Jede Kopie eines Bench-Binaries heisst `pokerbench--.exe` + (z. B. `pokerbench-turn-veto.exe`), nie `ab1.exe` o. ae. Wer im Task-Manager schaut, muss sehen, + dass es eine Poker-Messung ist und zu welchem Track sie gehoert. +- **Warteschlangen sichtbar und stoppbar.** Ein Starter, der Laeufe nachfuellt, heisst + `pokerbench--starter.ps1`, schreibt seine PID nach `/STARTER.pid` und wird + beim Anhalten ZUERST beendet, dann die Laeufe. Sonst startet er sofort neue. +- **Ergebnisse nicht nur im Scratchpad.** Fertige Messdateien gehoeren in den Worktree + (`messung_/`), das Scratchpad ist fluechtig. diff --git a/entscheiden/replay.py b/entscheiden/replay.py index a45ed402..89bc4173 100644 --- a/entscheiden/replay.py +++ b/entscheiden/replay.py @@ -112,6 +112,27 @@ def _seat_name(seats): return {v: k for k, v in seats.items()} +def geloggte_gegner(pfad=None): + """{(hand, street): {sitz: profil}} aus dem Zug-Log (archiv/lauf/zuege.jsonl, Feld `gegner`, ab + 13.11.): was der Kern live ueber die Gegner wusste. Fehlt es, bleibt das Export-Profil (nur VPIP).""" + pfad = pfad or os.environ.get("COINPOKER_ZUEGE") or os.path.join( + os.path.dirname(os.path.abspath(__file__)), "..", "archiv", "lauf", "zuege.jsonl") + out = {} + if not os.path.exists(pfad): + return out + for zeile in open(pfad, encoding="utf-8"): + try: + z = json.loads(zeile) + except ValueError: + continue + if z.get("hand") is not None and z.get("gegner"): + out[(str(z["hand"]), z.get("street"))] = z["gegner"] + return out + + +GELOGGT = None + + def reconstruct(hand): """Laeuft die HH-Aktionen durch, baut vor jeder Hero-Aktion den Wire-Spot und paart ihn mit der naechsten geloggten Entscheidung. Gibt Liste von (spot_dict, decision) zurueck.""" @@ -127,6 +148,8 @@ def reconstruct(hand): decisions = iter(hand["decisions"]) out = [] + req_quelle = QUELLE + def snapshot(dec): """Baut die Wire-Anfrage fuer die aktuelle Hero-Entscheidung.""" board = dec["board"] @@ -142,6 +165,12 @@ def reconstruct(hand): "folded": seat in folded} if name in hand["prof"]: v["profile"] = dict(hand["prof"][name]) + live = (GELOGGT or {}).get((str(hand["hid"]), dec["street"]), {}).get(str(seat)) + if live: + v["profile"] = {k: x for k, x in live.items() if k not in ("folded", "marke")} + if live.get("marke"): + v["marke"] = live["marke"] + req_quelle["live"] += 1 vils.append(v) req = {"variant": "NLHE", "bigBlind": bb, "seats": len(seats), "heroSeat": hero_seat, "heroCards": _wire_cards(" ".join(hand["hero_cards"])), @@ -206,7 +235,12 @@ def reconstruct(hand): # ---------------------------------------------------------------- Benчmark +QUELLE = Counter() + + def run(export_path): + global GELOGGT + GELOGGT = geloggte_gegner() md = open(export_path, encoding="utf-8").read() blocks = re.split(r'^### Hand ', md, flags=re.M)[1:] hands = [h for h in (parse_hand(b) for b in blocks) if h] @@ -307,6 +341,7 @@ def main(): r = run(path) print(f"=== Replay-Benchmark ({os.path.basename(path)}) ===") print(f"Haende {r['n_hands']} | Hero-Entscheidungen rekonstruiert {r['n_spots']} | davon gegen Bet {r['n_bet']}") + print(f"Gegnerprofile: {QUELLE['live']} aus dem Live-Zug-Log, sonst aus dem Export (nur VPIP)") print(f"TREUE (Re-Decision == Log): gesamt {100*r['treue']:.0f}% | gegen Bet {100*r['treue_bet']:.0f}%") print() print("FOLD gegen Bet je Street (Re-Decision der aktuellen Engine):") diff --git a/lesen/handreview.py b/lesen/handreview.py index a897a4ec..c06e1acb 100644 --- a/lesen/handreview.py +++ b/lesen/handreview.py @@ -59,9 +59,27 @@ def eintrag(anfrage, antwort, raum=None, zeit=None): "klasse": ans.get("category"), "equity": ans.get("equity"), "grund": ans.get("reason"), + # Was der Kern ueber die Gegner wusste (Profil je Sitz): ohne das kann kein Replay den Zug + # treu nachspielen (10.11.: der Export trug nur VPIP, live kam viel mehr an). + "gegner": _gegner(a.get("villains")), } +def _gegner(villains): + """{sitz: profil} der Gegner, nur Zahlen (keine gezeigten Karten - die stehen in der Hand).""" + out = {} + for v in villains or (): + if not isinstance(v, dict) or v.get("seat") is None: + continue + prof = v.get("profile") if isinstance(v.get("profile"), dict) else {} + zahlen = {k: x for k, x in prof.items() if isinstance(x, (int, float)) and not isinstance(x, bool)} + if v.get("marke"): + zahlen["marke"] = v["marke"] + if zahlen or v.get("folded"): + out[str(v["seat"])] = dict(zahlen, **({"folded": True} if v.get("folded") else {})) + return out or None + + def finde(zuege, hand=None, raum=None, klasse=None, aktion=None, letzte=None): """Zuege (Liste von Review-Zeilen) filtern. `raum` matcht als Teilstring (Pool-Namen tragen die Tischnummer), die anderen exakt. `letzte`: nur die letzten N nach dem Filter.""" diff --git a/lesen/profil.py b/lesen/profil.py index bc56ffb0..2bdd654d 100644 --- a/lesen/profil.py +++ b/lesen/profil.py @@ -160,6 +160,14 @@ AGGRESSIV = ("BET", "RAISE") # einsetzende Züge GEZAEHLT = ("BET", "RAISE", "CALL", "CHECK") # Nach-Flop-Züge, die zählen (Folden fällt raus) +def aggression_zuege(aktionen): + """Wie viele Nach-Flop-Züge die `aggression` trägt (Folden und Vorflop zählen nicht) - die + Stichprobe der Aggression. Der Kern gewichtet die Aggression damit (`aggressionActions`), nicht mit + den HUD-Händen: 500 HUD-Hände und 2 gesehene Züge sind ein dünner Bluff-Read.""" + return sum(1 for a in (aktionen or ()) + if a.get("street") in NACHFLOP and a.get("action") in GEZAEHLT) + + def aggression(aktionen): """Anteil der Nach-Flop-Züge, die Einsatz oder Erhöhung sind (0..1) - None ohne solchen Zug. @@ -174,6 +182,28 @@ def aggression(aktionen): return hart / len(nachflop) +def strassen(aktionen): + """Die Reads je Straße, so gezählt wie das Sitzungsgedächtnis der Sim (src/sim/memory.rs): + Aggression auf Turn/River = Einsatz/Erhöhung unter allen nicht-foldenden Zügen der Straße, + Fold auf eine Bet je Straße = Folds unter Folds+Calls (eine Erhöhung zählt nicht). Geliefert + werden Rohanteil UND Stichprobe; der Kern zieht beides zum Gesamt-Read (src/wire/decode_villain.rs), + ein einzelner River-Zug macht also kein 0/1. Straßen ohne Zug fehlen.""" + out = {} + zuege = [a for a in (aktionen or ()) if a.get("street") in NACHFLOP] + for strasse, name in (("TURN", "turn"), ("RIVER", "river")): + n = [a for a in zuege if a.get("street") == strasse and a.get("action") in GEZAEHLT] + if n: + out[f"{name}Aggression"] = sum(1 for a in n if a.get("action") in AGGRESSIV) / len(n) + out[f"{name}AggressionActions"] = len(n) + for strasse, name in (("FLOP", "flop"), ("TURN", "turn"), ("RIVER", "river")): + folds = sum(1 for a in zuege if a.get("street") == strasse and a.get("action") == "FOLD") + calls = sum(1 for a in zuege if a.get("street") == strasse and a.get("action") == "CALL") + if folds + calls: + out[f"{name}FoldToBet"] = folds / (folds + calls) + out[f"{name}FacingBet"] = folds + calls + return out + + def sitze(text): """{sitz: kennung} aus der Sitzliste.""" klar = _klar(text) @@ -217,7 +247,8 @@ def aus_sitzliste(liste, werte, basis=None, gesehen=None, aktionen=None): (main.6 - ein Profil für das ganze Log gab beiden Tischen dieselben Werte). Mit `basis` (stichproben) und `gesehen` ({kennung: Hände}) trägt jedes Profil `hands` = Grundwert + eigene gesehene Hände - der Kern vertraut dünnen Werten danach weniger. - Mit `aktionen` ({kennung: Nach-Flop-Züge}) trägt es `aggression`, sobald es solche Züge gibt.""" + Mit `aktionen` ({kennung: Nach-Flop-Züge}) trägt es `aggression` samt `aggressionActions` (die Zahl + der Züge, auf denen sie beruht), sobald es solche Züge gibt, dazu die Reads je Straße (`strassen`).""" profile = {} for sitz in liste or (): kennung = str(sitz.get("userId")) if isinstance(sitz, dict) else None @@ -230,6 +261,8 @@ def aus_sitzliste(liste, werte, basis=None, gesehen=None, aktionen=None): frei = aggression(aktionen.get(kennung)) if frei is not None: p["aggression"] = frei + p["aggressionActions"] = aggression_zuege(aktionen.get(kennung)) + p.update(strassen(aktionen.get(kennung))) profile[int(sitz["seatId"])] = p return profile diff --git a/messung_engine/.gitignore b/messung_engine/.gitignore new file mode 100644 index 00000000..9714b2db --- /dev/null +++ b/messung_engine/.gitignore @@ -0,0 +1,8 @@ +bin/ +*.err +STARTER.pid +STOP +arme/ +logs/ +starter.log +erledigt.txt diff --git a/messung_engine/ERGEBNISSE.md b/messung_engine/ERGEBNISSE.md new file mode 100644 index 00000000..056fa5e9 --- /dev/null +++ b/messung_engine/ERGEBNISSE.md @@ -0,0 +1,22 @@ +# Engine-Leiter, Ergebnisse 13.11.2026 + +Gepaart (gleiche Karten), Differenz B−A in bb/100 mit 95 %-Intervall, `python ab.py arme/A arme/B`. +19 Gegner: 8 klassische, 10 Welt-Archetypen, gto. Zellen liegen in `arme/` (nicht im Git, ~67 MB). + +| Arm | gegen | Ergebnis | Urteil | +|---|---|---|---| +| mdf-fix | basis | 0 geaenderte Deals; echte Haende: Overfold 36 → 7.5 bb | uebernommen | +| neu-aus (Aggressions-Vertrauen, Strassen-Reads, SD aus) | mdf-fix | identisch | uebernommen (wirkt live) | +| sd-an (River-Showdown-Bluffanteil) | neu-aus | −1.31 ±0.95, umgekehrt −8.38 | VERLIERER, aus | +| p2-bayes | basis | −10.76 ±1.20 (nemesis-2 −98.6) | VERLIERER | +| p3-br1 / p3-br2 | basis | −0.64 ±0.45 / −0.87 ±0.49 | VERLIERER | +| linie-3bet (leichter 3-Bet gegen 3-Bet-Folder) | linie-aus | 3bet-folder +6.62 ±5.23, GESAMT +0.35 ±0.28, sonst 0 | GEWINNER, uebernommen | +| linie-cbet (Fold-auf-C-Bet preist die C-Bet) | linie-aus | ueberall ≈0 (Flop-Fold-Read deckt es in der Sim ab) | neutral, uebernommen | +| linie-xr (Check-Raise-Abschlag, alle Nicht-Value-Raises) | linie-aus | check-raiser +14.96, nemesis-2 −7.59 ±6.36 | VERLIERER | +| linie-xr2 (nur Bluff/Semibluff) | linie-aus | check-raiser +12.68, nemesis-2 −4.29 ±5.87 | nicht uebernommen | +| linie-xr3 (+ nur Ueberschuss ueber 8 %) | linie-aus | check-raiser +9.73, nemesis-2 −1.81 ±3.44 | nicht uebernommen: Flickwerk | + +Check-Raise: der Abschlag ist ein Zusatzterm an einer EV-Formel, die keine Raises kennt; die drei +Varianten wurden an der Leiter nachgestellt. Ersetzt wird er durch ein konsistentes Modell (Antwort des +Gegners als gelernte Verteilung Fold/Call/Value-Raise/Bluff-Raise, Heros Antwort auf das Raise gerechnet) +mit Priors, die aus echten Haenden geschaetzt sind (Empirical Bayes), statt handgesetzter Anker. diff --git a/messung_engine/GRENZE.txt b/messung_engine/GRENZE.txt new file mode 100644 index 00000000..ffda9973 --- /dev/null +++ b/messung_engine/GRENZE.txt @@ -0,0 +1,2 @@ +threads=28 +je_lauf=7 diff --git a/messung_engine/ab.py b/messung_engine/ab.py new file mode 100644 index 00000000..1c589ff8 --- /dev/null +++ b/messung_engine/ab.py @@ -0,0 +1,71 @@ +"""Paired A/B of two measurement arms, deal by deal. + +Each arm is a folder of sample files (one luck-corrected bb value per line, one file per +opponent/individual, same file names in both arms = same deals). Prints per group (file-name +prefix before the first '.') the paired delta B - A in bb/100 with a 95 % CI, the groups pooled +as strata, and a verdict: GEWINNER (CI above 0), VERLIERER (CI below 0), offen. + + python messung_engine/ab.py [--min-delta 0] +""" + +import math +import os +import sys + +Z95 = 1.959964 + + +def lese(pfad): + with open(pfad, encoding="utf-8") as f: + return [float(x) for x in f.read().split()] + + +def gepaart(a, b): + n = min(len(a), len(b)) + if n != len(a) or n != len(b): + raise SystemExit(f"ungleiche Laenge {len(a)} vs {len(b)}") + d = [y - x for x, y in zip(a, b)] + m = sum(d) / n + v = sum((x - m) ** 2 for x in d) / max(n - 1, 1) + return 100 * m, 100 * math.sqrt(v / n), n, sum(1 for x in d if x != 0) + + +def urteil(m, ci): + if m - ci > 0: + return "GEWINNER" + if m + ci < 0: + return "VERLIERER" + return "offen" + + +def main(): + if len(sys.argv) < 3: + raise SystemExit(__doc__) + da, db = sys.argv[1], sys.argv[2] + namen = sorted(set(os.listdir(da)) & set(os.listdir(db))) + namen = [n for n in namen if n.endswith(".txt")] + gruppen = {} + for n in namen: + gruppen.setdefault(n.split(".")[0], []).append(n) + alle = [] + print(f"A = {da}\nB = {db}\n") + print(f"{'Gegner':<14} {'B-A bb/100':>11} {'±95%':>8} {'Deals':>7} {'geaendert':>9} Urteil") + for g, files in sorted(gruppen.items()): + teile = [gepaart(lese(os.path.join(da, f)), lese(os.path.join(db, f))) for f in files] + k = len(teile) + m = sum(t[0] for t in teile) / k + se = math.sqrt(sum(t[1] ** 2 for t in teile)) / k + n = sum(t[2] for t in teile) + ch = sum(t[3] for t in teile) + alle.append((m, se)) + print(f"{g:<14} {m:>+11.2f} {Z95 * se:>8.2f} {n:>7} {ch:>9} {urteil(m, Z95 * se)}") + if alle: + k = len(alle) + m = sum(x[0] for x in alle) / k + se = math.sqrt(sum(x[1] ** 2 for x in alle)) / k + print(f"{'GESAMT':<14} {m:>+11.2f} {Z95 * se:>8.2f} (Strata gleich gewichtet) {urteil(m, Z95 * se)}") + print(f"Kein Profil verliert: {'ja' if all(x[0] + Z95 * x[1] >= 0 for x in alle) else 'NEIN'}") + + +if __name__ == "__main__": + main() diff --git a/messung_engine/pokerbench-engine-starter.ps1 b/messung_engine/pokerbench-engine-starter.ps1 new file mode 100644 index 00000000..582b0383 --- /dev/null +++ b/messung_engine/pokerbench-engine-starter.ps1 @@ -0,0 +1,83 @@ +# Warteschlange der Engine-Messlaeufe (alle Tracks), siehe CLAUDE.md "Messlaeufe". +# +# Liest bei jedem Durchgang messung_engine/warteschlange.txt (Zeilen: id|exe|argumente|env|arbeitsordner, +# env als K=V;K=V, leere Felder erlaubt, '#' = Kommentar) und startet Laeufe parallel, solange das +# THREAD-BUDGET reicht. Budget in GRENZE.txt (jederzeit aenderbar, wirkt beim naechsten Start): +# threads=16 Summe der Mess-Threads aller laufenden Laeufe (2, wenn der Client spielt) +# je_lauf=8 Threads pro Lauf (POKERBENCH_THREADS) +# Prioritaet Idle. Fertige ids stehen in erledigt.txt, Ausgabe in logs/.log. +# Eigene PID steht in STARTER.pid. ANHALTEN: zuerst diesen Starter beenden, dann die Laeufe +# (Get-Process pokerbench-*). Datei STOP im Ordner = keine neuen Laeufe mehr starten, sauber auslaufen. +# Ein Neustart des Starters uebernimmt bereits laufende Laeufe (an ihrem Ausgabeordner erkannt). +$ErrorActionPreference = 'Continue' +$D = Split-Path -Parent $MyInvocation.MyCommand.Path +(Get-Process -Id $PID).PriorityClass = 'Idle' +$PID | Set-Content "$D\STARTER.pid" +New-Item -ItemType Directory -Force "$D\logs" | Out-Null +if (-not (Test-Path "$D\erledigt.txt")) { New-Item -ItemType File "$D\erledigt.txt" | Out-Null } + +function Grenze { + $g = @{ threads = 16; je_lauf = 8 } + if (Test-Path "$D\GRENZE.txt") { + Get-Content "$D\GRENZE.txt" | ForEach-Object { + if ($_ -match '^\s*(\w+)\s*=\s*(\d+)') { $g[$Matches[1]] = [int]$Matches[2] } + } + } + $g +} + +function Jobs { + if (-not (Test-Path "$D\warteschlange.txt")) { return @() } + @(Get-Content "$D\warteschlange.txt" | Where-Object { $_ -and -not $_.StartsWith('#') }) +} + +$laufend = @{} # id -> @{ p = Process; t = threads } +# Bereits laufende Laeufe uebernehmen (zaehlen mit vollem Budget, bis sie fertig sind). +$prozesse = Get-CimInstance Win32_Process -Filter "Name LIKE 'pokerbench-%'" +foreach ($j in Jobs) { + $f = $j -split '\|'; $out = ($f[2] -split ' ')[0] + $treffer = $prozesse | Where-Object { $_.CommandLine -and $_.CommandLine.Contains($out + ' ') } | Select-Object -First 1 + if ($treffer) { + $laufend[$f[0]] = @{ p = (Get-Process -Id $treffer.ProcessId); t = (Grenze).threads } + "$($f[0]) uebernommen pid=$($treffer.ProcessId) $(Get-Date -Format s)" | Add-Content "$D\starter.log" + } +} + +while ($true) { + foreach ($id in @($laufend.Keys)) { + $p = $laufend[$id].p + if ($p.HasExited) { + "$id exit=$($p.ExitCode) $(Get-Date -Format s)" | Add-Content "$D\erledigt.txt" + $laufend.Remove($id) + } + } + $fertig = @{} + Get-Content "$D\erledigt.txt" | ForEach-Object { $fertig[($_ -split ' ')[0]] = 1 } + $offen = @(Jobs | Where-Object { $i = ($_ -split '\|')[0]; -not $fertig.ContainsKey($i) -and -not $laufend.ContainsKey($i) }) + $g = Grenze + $belegt = 0; foreach ($l in $laufend.Values) { $belegt += $l.t } + $frei = $g.threads - $belegt + if ((Test-Path "$D\STOP") -or $offen.Count -eq 0) { + if ($laufend.Count -eq 0) { break } + } elseif ($frei -ge 1 -and ($frei -ge $g.je_lauf -or $laufend.Count -eq 0)) { + $t = [Math]::Max(1, [Math]::Min($g.je_lauf, $frei)) + $f = $offen[0] -split '\|' + $id = $f[0]; $exe = $f[1]; $args_ = $f[2]; $env_ = $f[3]; $wd = $f[4] + if (-not $wd) { $wd = $D } + $env:POKERBENCH_THREADS = "$t" + foreach ($kv in ($env_ -split ';' | Where-Object { $_ })) { + $k, $v = $kv -split '=', 2; Set-Item "Env:$k" $v + } + $p = Start-Process -FilePath $exe -ArgumentList $args_ -WorkingDirectory $wd -NoNewWindow -PassThru ` + -RedirectStandardOutput "$D\logs\$id.log" -RedirectStandardError "$D\logs\$id.err" + try { $p.PriorityClass = 'Idle' } catch {} + foreach ($kv in ($env_ -split ';' | Where-Object { $_ })) { Remove-Item "Env:$(($kv -split '=')[0])" -ErrorAction SilentlyContinue } + Remove-Item Env:POKERBENCH_THREADS -ErrorAction SilentlyContinue + $laufend[$id] = @{ p = $p; t = $t } + "$id gestartet pid=$($p.Id) threads=$t $(Get-Date -Format s)" | Add-Content "$D\starter.log" + continue + } + Start-Sleep -Seconds 10 +} +Remove-Item "$D\STARTER.pid" -ErrorAction SilentlyContinue +"leer $(Get-Date -Format s)" | Add-Content "$D\starter.log" diff --git a/messung_engine/replay_aggrconf.txt b/messung_engine/replay_aggrconf.txt new file mode 100644 index 00000000..e35c589e --- /dev/null +++ b/messung_engine/replay_aggrconf.txt @@ -0,0 +1,19 @@ +=== Replay-Benchmark (coinpoker_cash_2026-11-10_analyse.md) === +Haende 161 | Hero-Entscheidungen rekonstruiert 195 | davon gegen Bet 28 +Gegnerprofile: 0 aus dem Live-Zug-Log, sonst aus dem Export (nur VPIP) +TREUE (Re-Decision == Log): gesamt 85% | gegen Bet 68% + +FOLD gegen Bet je Street (Re-Decision der aktuellen Engine): + FLOP : fold 6, call 9 -> 40% Fold-to-bet + TURN : fold 3, call 3 -> 50% Fold-to-bet + RIVER: fold 2, call 5 -> 29% Fold-to-bet + +EQUITY-BIAS (Engine - wahr) ueber 14 Ground-Truth-Spots: -0.186 (negativ = unterschaetzt -> Overfold-Wurzel) +EV-VERLUST belegt: Overfold 7.5 bb | Overcall 3.1 bb + +Belegte Overfolds (Gegner gezeigt, wahre Equity machte den Call +EV): + #174898200297 FLOP [Ah 7d 2s ] pot 0.17 call 0.06 | wahr 0.82 vs be 0.26 | Engine 0.237 | Gegner Jd Kd | +EV weg 6.4 bb + #174898200332 FLOP [3h 9s As ] pot 0.16 call 0.04 | wahr 0.27 vs be 0.20 | Engine 0.141 | Gegner Qc 7c | +EV weg 0.7 bb + #174898200316 FLOP [2h 8c 3h ] pot 0.28 call 0.08 | wahr 0.24 vs be 0.22 | Engine 0.191 | Gegner Qs 9s | +EV weg 0.4 bb + +Baseline geschrieben: D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\benchmarks\replay_baseline.txt diff --git a/messung_engine/replay_jetzt_c03530a.kurz.txt b/messung_engine/replay_jetzt_c03530a.kurz.txt new file mode 100644 index 00000000..d350180f --- /dev/null +++ b/messung_engine/replay_jetzt_c03530a.kurz.txt @@ -0,0 +1,13 @@ +label c03530a+lokal +export coinpoker_cash_2026-11-10 +hands 161 +spots 195 +facing_bet 28 +faithfulness 0.872 +faithfulness_bet 0.821 +foldbet_flop 6 9 +foldbet_turn 3 3 +foldbet_river 6 1 +equity_bias -0.186 n=14 +overfold_bb 36.0 +overcall_bb 3.1 diff --git a/messung_engine/replay_jetzt_c03530a.txt b/messung_engine/replay_jetzt_c03530a.txt new file mode 100644 index 00000000..05eb901f --- /dev/null +++ b/messung_engine/replay_jetzt_c03530a.txt @@ -0,0 +1,19 @@ +=== Replay-Benchmark (coinpoker_cash_2026-11-10_analyse.md) === +Haende 161 | Hero-Entscheidungen rekonstruiert 195 | davon gegen Bet 28 +TREUE (Re-Decision == Log): gesamt 87% | gegen Bet 82% + +FOLD gegen Bet je Street (Re-Decision der aktuellen Engine): + FLOP : fold 6, call 9 -> 40% Fold-to-bet + TURN : fold 3, call 3 -> 50% Fold-to-bet + RIVER: fold 6, call 1 -> 86% Fold-to-bet + +EQUITY-BIAS (Engine - wahr) ueber 14 Ground-Truth-Spots: -0.186 (negativ = unterschaetzt -> Overfold-Wurzel) +EV-VERLUST belegt: Overfold 36.0 bb | Overcall 3.1 bb + +Belegte Overfolds (Gegner gezeigt, wahre Equity machte den Call +EV): + #174898200346 RIVER [9c Tc Kc Qd 2h] pot 0.57 call 0.26 | wahr 1.00 vs be 0.31 | Engine 0.226 | Gegner Ah Td | +EV weg 28.5 bb + #174898200297 FLOP [Ah 7d 2s ] pot 0.17 call 0.06 | wahr 0.82 vs be 0.26 | Engine 0.237 | Gegner Jd Kd | +EV weg 6.4 bb + #174898200332 FLOP [3h 9s As ] pot 0.16 call 0.04 | wahr 0.27 vs be 0.20 | Engine 0.141 | Gegner Qc 7c | +EV weg 0.7 bb + #174898200316 FLOP [2h 8c 3h ] pot 0.28 call 0.08 | wahr 0.24 vs be 0.22 | Engine 0.191 | Gegner Qs 9s | +EV weg 0.4 bb + +Baseline geschrieben: D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\benchmarks\replay_baseline.txt diff --git a/messung_engine/replay_mdf_fix.txt b/messung_engine/replay_mdf_fix.txt new file mode 100644 index 00000000..192906d5 --- /dev/null +++ b/messung_engine/replay_mdf_fix.txt @@ -0,0 +1,18 @@ +=== Replay-Benchmark (coinpoker_cash_2026-11-10_analyse.md) === +Haende 161 | Hero-Entscheidungen rekonstruiert 195 | davon gegen Bet 28 +TREUE (Re-Decision == Log): gesamt 85% | gegen Bet 68% + +FOLD gegen Bet je Street (Re-Decision der aktuellen Engine): + FLOP : fold 6, call 9 -> 40% Fold-to-bet + TURN : fold 3, call 3 -> 50% Fold-to-bet + RIVER: fold 2, call 5 -> 29% Fold-to-bet + +EQUITY-BIAS (Engine - wahr) ueber 14 Ground-Truth-Spots: -0.186 (negativ = unterschaetzt -> Overfold-Wurzel) +EV-VERLUST belegt: Overfold 7.5 bb | Overcall 3.1 bb + +Belegte Overfolds (Gegner gezeigt, wahre Equity machte den Call +EV): + #174898200297 FLOP [Ah 7d 2s ] pot 0.17 call 0.06 | wahr 0.82 vs be 0.26 | Engine 0.237 | Gegner Jd Kd | +EV weg 6.4 bb + #174898200332 FLOP [3h 9s As ] pot 0.16 call 0.04 | wahr 0.27 vs be 0.20 | Engine 0.141 | Gegner Qc 7c | +EV weg 0.7 bb + #174898200316 FLOP [2h 8c 3h ] pot 0.28 call 0.08 | wahr 0.24 vs be 0.22 | Engine 0.191 | Gegner Qs 9s | +EV weg 0.4 bb + +Baseline geschrieben: D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\benchmarks\replay_baseline.txt diff --git a/messung_engine/warteschlange.txt b/messung_engine/warteschlange.txt new file mode 100644 index 00000000..9b09d97b --- /dev/null +++ b/messung_engine/warteschlange.txt @@ -0,0 +1,16 @@ +# id|exe|argumente|env|arbeitsordner (Arm-Ergebnisse: arme//, Vergleich: python ab.py arme/basis arme/) +basis|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\bin\pokerbench-engine-basis.exe|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\arme\basis 2000 4000 4 all|| +id-turn|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\bin\pokerbench-engine-turn.exe|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\arme\id-turn 2000 4000 1 nemesis-1,nemesis-3,wert-sizer,textur-cbet|TURN_VETO=0| +id-p2|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\bin\pokerbench-engine-p2.exe|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\arme\id-p2 2000 4000 1 nemesis-1,nemesis-3,wert-sizer,textur-cbet|| +id-p3|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\bin\pokerbench-engine-p3.exe|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\arme\id-p3 2000 4000 1 nemesis-1,nemesis-3,wert-sizer,textur-cbet|| +mdf-fix|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\bin\pokerbench-engine-mdffix.exe|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\arme\mdf-fix 2000 4000 4 all|| +p2-bayes|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\bin\pokerbench-engine-p2.exe|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\arme\p2-bayes 2000 4000 4 all|BAYES=1| +p3-br1|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\bin\pokerbench-engine-p3.exe|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\arme\p3-br1 2000 4000 4 all|BR_PIECES=1| +p3-br2|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\bin\pokerbench-engine-p3.exe|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\arme\p3-br2 2000 4000 4 all|BR_PIECES=2| +linie-basis|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\bin\pokerbench-engine-linie.exe|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\arme\linie-aus 2000 4000 4 all|| +linie-cbet|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\bin\pokerbench-engine-linie.exe|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\arme\linie-cbet 2000 4000 4 all|READS=cbet| +linie-xr|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\bin\pokerbench-engine-linie.exe|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\arme\linie-xr 2000 4000 4 all|READS=xr| +linie-3bet|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\bin\pokerbench-engine-linie.exe|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\arme\linie-3bet 2000 4000 4 all|READS=3bet| +turn-draw-rest|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\bin\pokerbench-engine-turn.exe|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\arme\turn-draw 2000 4000 4 all|| +linie-xr2|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\bin\pokerbench-engine-linie2.exe|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\arme\linie-xr2 2000 4000 4 nemesis-2,check-raiser,cbet-folder,3bet-folder|READS=xr;POKERBENCH_THREADS=16| +linie-xr3|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\bin\pokerbench-engine-linie3.exe|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\arme\linie-xr3 2000 4000 4 nemesis-2,check-raiser,cbet-folder,3bet-folder|READS=xr;POKERBENCH_THREADS=16| diff --git a/src/bin/ab_zelle.rs b/src/bin/ab_zelle.rs new file mode 100644 index 00000000..54332b28 --- /dev/null +++ b/src/bin/ab_zelle.rs @@ -0,0 +1,125 @@ +//! One ARM of a paired A/B over the whole measurement gate: the world population (`sim::welt`, every +//! archetype + the gto control, `draws` individuals each) AND the classic profiles (station, fish, +//! reg, nit, maniac, nemesis-1..3, `draws` seeds each). Memory read. Each cell's +//! per-deal luck-corrected samples (bb) go to `/..txt`. Two arms (two processes, same +//! rows, same deals) are compared deal by deal with `python messung_engine/ab.py `. +//! +//! The arm is chosen by environment so independent processes stay paired: +//! - `TURN_VETO`, `TURN_BUCKET`, `TURN_PER_STREET`: read by the turn track itself, +//! - every other track adds its switch in `apply_arm` below (identity on the engine branch). +//! +//! Run: `ab_zelle [welt-deals=2000] [klassik-deals=4000] [draws=4] [rows=all|welt|klassik|a,b,..]` +//! Threads: `POKERBENCH_THREADS` (default 16). Every cell is independent and deterministic, so the +//! thread count never changes a number. Run at priority Idle (see CLAUDE.md "Messlaeufe"). + +use rechner::rng::Rng; +use rechner::sim::opponent::Opponent; +use rechner::sim::reader::{Rules, Style}; +use rechner::sim::session::{deal_samples, ReadMode, Setup}; +use rechner::sim::welt::{Persona, ARCHETYPES}; +use std::sync::atomic::{AtomicUsize, Ordering}; + +/// World rows: same seeds as `welt_leiter`, so individuals and deals match the ladder. +const WELT_SEED: u64 = 0x5EED_0A11; +const DRAW_SEED: u64 = 0xD2A9_0000; +/// Classic rows: seed of `br_ladder` / `turn_veto_ab` for k = 0. +const KLASSIK_SEED: u64 = 0x5EED_0001; +const STACK_BB: f64 = 100.0; + +const N1: Rules = Rules { call_margin: 0.215, raise_at: 0.587, bet_at: 0.548, open_at: 0.729, bluff: 0.068, size: 0.441 }; +const N2: Rules = Rules { call_margin: 0.173, raise_at: 0.579, bet_at: 0.748, open_at: 0.800, bluff: 0.229, size: 0.996 }; +const N3: Rules = Rules { call_margin: 0.396, raise_at: 0.769, bet_at: 0.615, open_at: 0.468, bluff: 0.261, size: 1.148 }; +const KLASSIK: [&str; 8] = ["station", "fish", "reg", "nit", "maniac", "nemesis-1", "nemesis-2", "nemesis-3"]; + +/// Track switches read from the environment. Identity on the engine branch. +fn apply_arm() { + // RIVER_SD=1: the river showdown read (world memory) into the session read (arm). + rechner::sim::memory::set_river_showdown(std::env::var("RIVER_SD").as_deref() == Ok("1")); + // READS=cbet,3bet,xr: the line-specific HUD reads (fold to c-bet / fold to 3-bet / check-raise). + use rechner::sim::memory::{set_line_reads, READ_CBET, READ_CHECK_RAISE, READ_THREE_BET}; + let reads = std::env::var("READS").unwrap_or_default(); + let mask = reads.split(',').fold(0u8, |m, r| match r.trim() { + "cbet" => m | READ_CBET, + "3bet" => m | READ_THREE_BET, + "xr" => m | READ_CHECK_RAISE, + _ => m, + }); + set_line_reads(mask); +} + +fn klassik(name: &str) -> Option { + Some(match name { + "station" => Opponent::CallingStation, + "fish" => Opponent::Reader(Style::Fish), + "reg" => Opponent::Reader(Style::Reg), + "nit" => Opponent::Reader(Style::Nit), + "maniac" => Opponent::Reader(Style::Maniac), + "nemesis-1" => Opponent::Styled(N1), + "nemesis-2" => Opponent::Styled(N2), + "nemesis-3" => Opponent::Styled(N3), + _ => return None, + }) +} + +/// (opponent, deals, seed) of row `name`, individual/seed `k`. +fn cell(name: &str, k: u64, welt_deals: u32, klassik_deals: u32) -> (Opponent, u32, u64) { + if let Some(i) = ARCHETYPES.iter().position(|a| *a == name) { + let opp = Opponent::Welt(Persona::draw(i, Rng::seeded(DRAW_SEED + 1000 * i as u64 + k)).0); + return (opp, welt_deals, WELT_SEED ^ (k + 1).wrapping_mul(0x9E37_79B9)); + } + if name == "gto" { + return (Opponent::Reader(Style::Gto), welt_deals, WELT_SEED ^ (k + 1).wrapping_mul(0x9E37_79B9)); + } + let opp = klassik(name).unwrap_or_else(|| panic!("unbekannte Zeile {name}")); + (opp, klassik_deals, KLASSIK_SEED ^ k.wrapping_mul(0x9E37_79B9_7F4A_7C15)) +} + +fn main() { + let a: Vec = std::env::args().collect(); + let out = a.get(1).expect("ab_zelle [welt-deals] [klassik-deals] [draws] [rows]").clone(); + let num = |i: usize, d: u32| a.get(i).and_then(|s| s.parse().ok()).unwrap_or(d); + let (welt_deals, klassik_deals, draws) = (num(2, 2000), num(3, 4000), num(4, 4) as u64); + let welt: Vec = ARCHETYPES.iter().map(|s| s.to_string()).chain(["gto".to_string()]).collect(); + let klass: Vec = KLASSIK.iter().map(|s| s.to_string()).collect(); + let rows: Vec = match a.get(5).map(String::as_str) { + None | Some("all") => welt.into_iter().chain(klass).collect(), + Some("welt") => welt, + Some("klassik") => klass, + Some(list) => list.split(',').map(str::to_string).collect(), + }; + let threads: usize = std::env::var("POKERBENCH_THREADS").ok().and_then(|s| s.parse().ok()).unwrap_or(16).max(1); + std::fs::create_dir_all(&out).expect("out dir"); + // Cells still to play, the long ones (more deals) first so the threads finish together. + let mut jobs: Vec<(String, u64, u32)> = rows + .iter() + .flat_map(|name| (0..draws).map(move |k| (name.clone(), k))) + .filter(|(name, k)| !std::path::Path::new(&format!("{out}/{name}.{k}.txt")).exists()) + .map(|(name, k)| { + let deals = cell(&name, k, welt_deals, klassik_deals).1; + (name, k, deals) + }) + .collect(); + jobs.sort_by(|a, b| b.2.cmp(&a.2)); + let next = AtomicUsize::new(0); + std::thread::scope(|s| { + for _ in 0..threads.min(jobs.len().max(1)) { + s.spawn(|| { + apply_arm(); // per thread: some switches are thread-local + loop { + let j = next.fetch_add(1, Ordering::Relaxed); + let Some((name, k, _)) = jobs.get(j) else { break }; + let (opponent, deals, seed) = cell(name, *k, welt_deals, klassik_deals); + let setup = Setup { players: 2, opponent, deals, stack_bb: STACK_BB, seed, read: ReadMode::Memory }; + let (samples, m) = deal_samples(&setup); + let body: Vec = samples.iter().map(|x| format!("{x}")).collect(); + let file = format!("{out}/{name}.{k}.txt"); + let tmp = format!("{file}.tmp"); + std::fs::write(&tmp, body.join(" +")).expect("write samples"); + std::fs::rename(&tmp, &file).expect("finish samples"); + println!("{name:<12} k={k} {:>+8.2} bb/100 +-{:>6.2}", m.bb_per_100, m.ci95); + } + }); + } + }); +} diff --git a/src/engine/river_subgame.rs b/src/engine/river_subgame.rs index 17d9b8ca..9f5fe625 100644 --- a/src/engine/river_subgame.rs +++ b/src/engine/river_subgame.rs @@ -216,6 +216,36 @@ pub(crate) fn believed_villain(tree: &Tree, n: usize, profile: Option<&Profile>, .unwrap_or(with_call) } +/// Shown river bets at which the showdown read and the aggression read weigh the same (the street +/// prior, `exploit::sample::STREET_PRIOR`). +const SHOWN_HALF: f64 = crate::exploit::sample::STREET_PRIOR; + +/// The aggression the river belief runs on. Without a showdown read: the river (else pooled) +/// aggression, as before. With one (`Profile::river_bluff_share` over `river_bluff_shown` river bets +/// seen at showdown): the aggression `believed_villain` would need to produce that air share — inverted +/// from its own model (bets = value above `VALUE_RANK` + `bluff_prob` of the range below `BLUFF_RANK`, +/// `bluff_prob = gto_bluff · a / DEFAULT_AGGRESSION`) — blended in by `n / (n + SHOWN_HALF)`. Direct +/// evidence beats the aggression proxy: a player who bets often with value (aggressive, not bluffy) or +/// rarely but always as air. +pub(crate) fn river_bluff_aggression(profile: Option<&Profile>, pot: f64, bet: f64) -> Option { + let p = profile?; + let a = p.river_aggression.or(p.aggression).filter(|x| !x.is_nan()); + let ok = |x: Option| x.filter(|v| !v.is_nan()); + let (Some(share), Some(n)) = (ok(p.river_bluff_share), ok(p.river_bluff_shown).filter(|n| *n > 0.0)) else { + return a; + }; + let gto_bluff = if pot + bet > 0.0 { bet / (pot + bet) } else { 0.0 }; + if gto_bluff <= 0.0 { + return a; + } + let s = share.clamp(0.0, 0.999); + let bluff_prob = (s * (1.0 - VALUE_RANK) / (BLUFF_RANK * (1.0 - s))).clamp(0.0, 1.0); + let shown = (bluff_prob * DEFAULT_AGGRESSION / gto_bluff).clamp(0.0, 1.0); + let base = a.unwrap_or(DEFAULT_AGGRESSION); + let w = n / (n + SHOWN_HALF); + Some(base + w * (shown - base)) +} + /// The KL trust radius from the read's confidence (payoff/chip units). `λ = LAMBDA_POT_SCALE · pot · /// (1−c)/c`: no confidence (`None`/0) → `∞` → `kl_best_response` returns exact GTO (the proven /// unexploitable baseline — it can never again balance against a fish it cannot read); confidence → 1 @@ -289,7 +319,9 @@ pub fn river_exploit_plan(spot: &Spot, villain_combos: &[Vec], profile: Op return None; } // Only exploit on a read strong enough to trust; otherwise the heuristic keeps the edge. - if profile.and_then(|p| p.confidence).filter(|c| !c.is_nan()).unwrap_or(0.0) < CONFIDENCE_FLOOR { + // The gearbox exploits a belief about BLUFFING: trust it only as far as the aggression read goes. + let confidence = profile.and_then(Profile::bluff_read_confidence); + if confidence.unwrap_or(0.0) < CONFIDENCE_FLOOR { return None; } let rules = spot.rules(); @@ -307,8 +339,8 @@ pub fn river_exploit_plan(spot: &Spot, villain_combos: &[Vec], profile: Op let game = subgame(spot, villain_combos, villain_combos, pot, bet)?; let n = game.ladder.len(); - let opponent = believed_villain(&game.tree, n, profile, pot, bet, profile.and_then(|p| p.river_aggression.or(p.aggression))); - let lambda = lambda_from_confidence(profile.and_then(|p| p.confidence), pot); + let opponent = believed_villain(&game.tree, n, profile, pot, bet, river_bluff_aggression(profile, pot, bet)); + let lambda = lambda_from_confidence(confidence, pot); let tilted = kl_best_response(&game.tree, &opponent, &game.solved.strategy, 0, lambda); let hb = game.bucket(hero_strength); @@ -346,6 +378,19 @@ pub fn fold_veto(spot: &Spot, base: Decision) -> Decision { if base.choice != Choice::Call { return base; } + // The veto answers a read that the bettor UNDER-bluffs. Without a postflop aggression read there + // is no bluff evidence at all (the belief would fall back to the balanced default and fold the + // bottom of a GTO range against a player nobody measured): stand down. Replay 10.11., hand + // 174898200346: vpip-only read, river top pair vetoed into a fold against a pair of tens. + let bluff_read = spot + .live_villains() + .next() + .and_then(|v| v.profile.as_ref()) + .and_then(|p| p.river_aggression.or(p.aggression)) + .is_some_and(|a| !a.is_nan()); + if !bluff_read { + return base; + } let Some(plan) = river_exploit_mix(spot) else { return base; }; @@ -638,4 +683,44 @@ mod tests { let check = Decision::new(Choice::Check, 0.7, "heuristic check"); assert_eq!(fold_veto(&spot, check.clone()), check, "a non-call base is never vetoed"); } + + /// The showdown read moves the river belief toward what was SHOWN: all-air river bets raise the + /// believed aggression, all-value ones lower it, a thin sample barely moves it, none leaves it. + #[test] + fn shown_river_bets_move_the_bluff_belief() { + let base = prof(0.4, 0.35, 0.9); + let (pot, bet) = (10.0, 7.5); + assert_eq!(river_bluff_aggression(Some(&base), pot, bet), Some(0.35)); + let shown = |share: f64, n: f64| Profile { river_bluff_share: Some(share), river_bluff_shown: Some(n), ..base }; + let honest = river_bluff_aggression(Some(&shown(0.0, 60.0)), pot, bet).unwrap(); + let bluffer = river_bluff_aggression(Some(&shown(0.45, 60.0)), pot, bet).unwrap(); + let thin = river_bluff_aggression(Some(&shown(0.0, 1.0)), pot, bet).unwrap(); + assert!(honest < 0.1, "never bluffed at showdown: {honest}"); + assert!(bluffer > 0.6, "mostly air at showdown: {bluffer}"); + assert!(thin > 0.3 && thin < 0.35, "one showdown barely moves it: {thin}"); + // The air share the model implies at the balanced aggression maps back onto it (round trip). + let gto_bluff = bet / (pot + bet); + let b = gto_bluff; // bluff_prob at a = DEFAULT_AGGRESSION + let s = BLUFF_RANK * b / (BLUFF_RANK * b + (1.0 - VALUE_RANK)); + let back = river_bluff_aggression(Some(&shown(s, 1e9)), pot, bet).unwrap(); + assert!((back - DEFAULT_AGGRESSION).abs() < 1e-6, "{back}"); + } + + /// No aggression read = no under-bluff evidence: the veto stands down even on a confident read + /// of other stats (replay 10.11., vpip-only HUD, river top pair vetoed into a fold). + #[test] + fn the_veto_needs_an_aggression_read() { + let board = Card::parse_list("Ah Kd 7c 2s 9h").unwrap(); + let no_aggr = Profile { aggression: None, vpip: Some(0.6), ..prof(0.30, 0.06, 0.85) }; + let spot = river_vs_bet(&board, "Jc Js", 6.0, 6.0, Some(no_aggr)); + let call = Decision::new(Choice::Call, 0.6, "heuristic call"); + assert_eq!(fold_veto(&spot, call.clone()), call, "no bluff read, no veto"); + // A strong HUD read (confidence 0.85) whose aggression rests on two seen moves: the gearbox + // trusts the bluff read only as far as the aggression goes -> below the floor, no plan. + let thin = Profile { aggression_confidence: Some(2.0 / 32.0), ..prof(0.30, 0.06, 0.85) }; + let spot = river_vs_bet(&board, "Jc Js", 6.0, 6.0, Some(thin)); + assert_eq!(fold_veto(&spot, call.clone()), call, "thin aggression read, no veto"); + let villain = sample_villain(); + assert!(river_exploit_plan(&spot, &villain, spot.live_villains().next().unwrap().profile.as_ref()).is_none()); + } } diff --git a/src/exploit/fold_chance.rs b/src/exploit/fold_chance.rs index a4c07e4e..a8420d8c 100644 --- a/src/exploit/fold_chance.rs +++ b/src/exploit/fold_chance.rs @@ -75,9 +75,25 @@ pub fn fold_chance(profile: Option<&Profile>, ratio: f64, facing_raise: bool) -> fold_chance_on(profile, ratio, facing_raise, None) } +/// Fold base against hero's continuation bet: the opponent's fold-to-c-bet read when it carries one +/// (a calling station's is trust-damped like its pooled read), else the flop read (`fold_base_on`). +/// A c-bet folder gives up the flop far more often than its pooled fold-to-bet says, and a sticky +/// flop caller far less. +pub fn fold_base_cbet(profile: Option<&Profile>) -> f64 { + match profile.and_then(|p| p.fold_to_cbet.filter(|f| !f.is_nan()).map(|f| (p, f.clamp(0.0, 1.0)))) { + Some((p, f)) if classify(p) == Style::CallingStation => DEFAULT_FOLD_TO_BET + station_trust(p) * (f - DEFAULT_FOLD_TO_BET), + Some((_, f)) => f, + None => fold_base_on(profile, Some(Street::Flop)), + } +} + /// `fold_chance` with the street's own fold read (`fold_base_on`). pub fn fold_chance_on(profile: Option<&Profile>, ratio: f64, facing_raise: bool, street: Option) -> f64 { - let f = fold_base_on(profile, street); + sized_fold(fold_base_on(profile, street), ratio, facing_raise) +} + +/// P(fold) to a bet of `ratio` pots from a fold base `f` (the reference-size fold rate). +pub fn sized_fold(f: f64, ratio: f64, facing_raise: bool) -> f64 { let ratio = if ratio.is_nan() { 0.0 } else { ratio.max(0.0) }; let sized = if f >= 1.0 { if ratio > 0.0 { 1.0 } else { 0.0 } diff --git a/src/exploit/mark.rs b/src/exploit/mark.rs index 195e445d..a0703ee7 100644 --- a/src/exploit/mark.rs +++ b/src/exploit/mark.rs @@ -25,6 +25,9 @@ const WEAK_PLAYER: Profile = Profile { wtsd: None, wsd: None, confidence: None, + aggression_confidence: None, + river_bluff_share: None, + river_bluff_shown: None, }; fn prior(mark: &str) -> Option { @@ -54,5 +57,8 @@ pub fn with_mark(measured: Option, mark: &str) -> Option { wtsd: known.wtsd.or(prior.wtsd), wsd: known.wsd.or(prior.wsd), confidence: known.confidence.or(prior.confidence), + aggression_confidence: known.aggression_confidence, + river_bluff_share: known.river_bluff_share, + river_bluff_shown: known.river_bluff_shown, }) } diff --git a/src/exploit/mdf_floor.rs b/src/exploit/mdf_floor.rs index 35995ce1..da30d1c5 100644 --- a/src/exploit/mdf_floor.rs +++ b/src/exploit/mdf_floor.rs @@ -81,9 +81,23 @@ fn over_bluffs(profile: &Profile) -> bool { fn range_may_bluff(spot: &Spot) -> bool { let mut live = spot.villains.iter().filter(|v| !v.folded).peekable(); live.peek().is_none() - || live.any(|v| v.profile.as_ref().is_none_or(over_bluffs)) + || live.any(|v| v.profile.as_ref().is_none_or(|p| bluff_unread(p) || over_bluffs(p))) } +/// A profile WITHOUT a postflop aggression read says nothing about bluffing (a live HUD often carries +/// only vpip/pfr): it is unread on the axis the floor needs, so it is defended exactly like an unread +/// villain. Only a measured aggression below the over-bluff line counts as evidence of a value-weighted +/// range. (Replay 10.11., hand 174898200346: vpip-only read, river top pair folded to a pair of tens, +/// 28.5 bb, because a missing aggression was read as "proven balanced".) +fn bluff_unread(profile: &Profile) -> bool { + profile.aggression.is_none_or(f64::is_nan) + || profile.aggression_confidence.is_some_and(|c| c.is_nan() || c < AGGRESSION_READ_MIN) +} + +/// An aggression read thinner than this (live: about 10 seen postflop moves at the 30-move half-life) +/// is no evidence either way: the same floor the river gearbox needs before it trusts a read. +const AGGRESSION_READ_MIN: f64 = 0.25; + /// True when hero must defend `made` against the bet he faces (never fold): on the river, with /// a bluff-catcher or better, whose strength puts it in the top `1 - alpha` of the range, and the /// bettor is not a confirmed under-bluffer. @@ -197,6 +211,21 @@ mod tests { assert!(defends(&spot, Made::MiddlePair)); } + #[test] + fn a_profile_without_an_aggression_read_is_defended_like_an_unread_one() { + // Live HUD with vpip only (replay 10.11., hand 174898200346): no bluff evidence either way, + // so the floor holds exactly as for an unread villain. + let vpip_only = Profile { vpip: Some(0.6), ..Profile::default() }; + let spot = Spot { villains: vec![villain(Some(vpip_only))], ..river(12.0, 6.0) }; + assert!(defends(&spot, Made::MiddlePair)); + let thin = Profile { aggression: Some(0.0), aggression_confidence: Some(2.0 / 32.0), ..Profile::default() }; + let spot = Spot { villains: vec![villain(Some(thin))], ..river(12.0, 6.0) }; + assert!(defends(&spot, Made::MiddlePair), "two seen moves are no under-bluff evidence"); + let nan = Profile { aggression: Some(f64::NAN), ..Profile::default() }; + let spot = Spot { villains: vec![villain(Some(nan))], ..river(12.0, 6.0) }; + assert!(defends(&spot, Made::MiddlePair)); + } + #[test] fn a_balanced_regular_is_not_floored() { // The near-GTO opponent (reads.rs oracle p(0.32, 0.22, 0.42, 0.40)): moderate aggression 0.40 diff --git a/src/exploit/profile.rs b/src/exploit/profile.rs index 0034fe2b..fa84d430 100644 --- a/src/exploit/profile.rs +++ b/src/exploit/profile.rs @@ -55,4 +55,33 @@ pub struct Profile { /// radius λ: strong read → exploit far, weak read → stay near GTO. `None` = no confidence signal /// (treated as 0 by the gearbox). No classify/gate rule reads it; it only scales exploitation. pub confidence: Option, + /// Confidence of the AGGRESSION read alone, in `[0, 1)`. Live the client HUD has no aggression: + /// it comes from the few postflop moves this session saw (`lesen/profil.py`), while `confidence` + /// comes from the HUD hand count, so the two can disagree by orders of magnitude (500 HUD hands, + /// 2 seen moves). `None` = the aggression read is as good as `confidence` (the session memory, + /// where both come from the same postflop sample). Read through `bluff_read_confidence`. + pub aggression_confidence: Option, + /// River showdown read: of the player's river bets/raises that were SHOWN DOWN, the share that was + /// air (equity below `AIR_STRENGTH` vs a random hand on the final board). Unbiased evidence of the + /// river betting range: whether hero calls depends on hero's cards, not the bettor's. The river + /// gearbox blends it into its bluff belief by `river_bluff_shown` (`engine::river_subgame`). + pub river_bluff_share: Option, + /// How many river bets/raises `river_bluff_share` rests on. + pub river_bluff_shown: Option, +} + +/// Equity vs a random hand on the river below which a shown river bet counts as air (a bluff): the +/// lower two strength bands (`sim::welt_memory::STRENGTH_BANDS`). +pub const AIR_STRENGTH: f64 = 0.4; + +impl Profile { + /// How far a read about this player's BLUFFING may be trusted: the weaker of the overall read + /// and the aggression read. `None` = no confidence signal (the gearbox treats it as 0). + pub fn bluff_read_confidence(&self) -> Option { + let ok = |x: Option| x.filter(|c| !c.is_nan()); + match (ok(self.confidence), ok(self.aggression_confidence)) { + (Some(c), Some(a)) => Some(c.min(a)), + (c, _) => c, + } + } } diff --git a/src/exploit/sample.rs b/src/exploit/sample.rs index 393fdc6b..5f782467 100644 --- a/src/exploit/sample.rs +++ b/src/exploit/sample.rs @@ -36,8 +36,16 @@ pub const PRIOR: Profile = Profile { wtsd: None, wsd: None, confidence: None, + aggression_confidence: None, + river_bluff_share: None, + river_bluff_shown: None, }; +/// 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; + /// Weight of the sample in `[0, 1)`. pub fn trust(hands: f64) -> f64 { if hands.is_nan() || hands <= 0.0 { @@ -76,5 +84,41 @@ pub fn shrink(profile: &Profile, hands: f64) -> Profile { // count earns the gearbox's trust exactly as a session-memory read does. Keep an explicit // confidence if one was already set. confidence: profile.confidence.or(Some(w)), + aggression_confidence: profile.aggression_confidence, + river_bluff_share: profile.river_bluff_share, + river_bluff_shown: profile.river_bluff_shown, } } + +/// The aggression read on its OWN sample: `raw` was measured over `actions` postflop moves (not over +/// the HUD's hands), so it is shrunk toward the population with that weight and carries it as +/// `aggression_confidence`. No usable count: the profile is returned unchanged. +pub fn shrink_aggression(profile: Profile, raw: Option, actions: f64) -> Profile { + if actions.is_nan() || actions < 0.0 { + return profile; + } + let w = actions / (actions + AGGRESSION_HALF); + Profile { aggression: pull(raw, PRIOR.aggression, w), aggression_confidence: Some(w), ..profile } +} + +/// 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; +pub const CHECK_RAISE_ANCHOR: f64 = 0.08; + +/// 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 +/// 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 { + let raw = raw.filter(|x| !x.is_nan())?; + let pooled = pooled.filter(|x| !x.is_nan())?; + if n.is_nan() || n <= 0.0 { + return None; + } + Some((raw * n + STREET_PRIOR * pooled) / (n + STREET_PRIOR)) +} diff --git a/src/exploit/table_fold.rs b/src/exploit/table_fold.rs index 3be02319..fee11447 100644 --- a/src/exploit/table_fold.rs +++ b/src/exploit/table_fold.rs @@ -1,5 +1,5 @@ -use super::fold_chance::{fold_chance_on, MAX_FOLD}; -use crate::game::Spot; +use super::fold_chance::{fold_base_cbet, fold_chance_on, sized_fold, MAX_FOLD}; +use crate::game::{line, Spot}; /// Pressure of a raise to `to`: the chips beyond a call, `to - to_call`, over the pot /// after calling, `pot + to_call`. A plain bet (`to_call = 0`) is `to / pot`. @@ -21,6 +21,16 @@ pub fn table_fold(spot: &Spot, to: f64, scale: f64) -> f64 { if live.peek().is_none() { return 0.0; } - live.map(|v| (fold_chance_on(v.profile.as_ref(), ratio, facing_raise, Some(spot.street)) * scale).clamp(0.0, MAX_FOLD)) - .product() + // Hero's continuation bet is priced by the fold-to-c-bet read (`fold_base_cbet`). + let cbet = line::cbet_spot(&spot.history, spot.hero_seat, spot.street); + live.map(|v| { + let p = v.profile.as_ref(); + let f = if cbet { + sized_fold(fold_base_cbet(p), ratio, facing_raise) + } else { + fold_chance_on(p, ratio, facing_raise, Some(spot.street)) + }; + (f * scale).clamp(0.0, MAX_FOLD) + }) + .product() } diff --git a/src/game/line.rs b/src/game/line.rs new file mode 100644 index 00000000..3dee9b7f --- /dev/null +++ b/src/game/line.rs @@ -0,0 +1,107 @@ +//! The betting line so far, read off an action history: who raised preflop, whether a flop bet is a +//! continuation bet, whether a player faces a 3-bet after opening, whether a player checked on this +//! street. One reading for the sim opponents (`sim::table`), the session memory that counts the HUD +//! stats from it (`sim::memory`) and the engine that prices hero's bets against those stats. +//! +//! Pure functions over `&[ActionRecord]` in table order; blinds and antes are not aggression. + +use super::{ActionRecord, SeenAction, Street}; + +fn aggressive_on(history: &[ActionRecord], street: Street) -> impl Iterator { + history.iter().filter(move |r| r.street == street && r.action.is_aggressive()) +} + +/// Seat of the last preflop bettor/raiser (the preflop aggressor), if anyone raised. +pub fn preflop_aggressor(history: &[ActionRecord]) -> Option { + aggressive_on(history, Street::Preflop).last().map(|r| r.seat) +} + +/// Seat of the first preflop raiser (the opener), if anyone raised. +pub fn opener(history: &[ActionRecord]) -> Option { + aggressive_on(history, Street::Preflop).next().map(|r| r.seat) +} + +/// The flop's only aggressive action so far is the preflop aggressor's bet: `seat` (someone else) +/// faces a continuation bet. +pub fn facing_cbet(history: &[ActionRecord], seat: u8) -> bool { + let Some(pfa) = preflop_aggressor(history) else { return false }; + let mut flop = aggressive_on(history, Street::Flop); + match (flop.next(), flop.next()) { + (Some(bet), None) => bet.seat == pfa && pfa != seat, + _ => false, + } +} + +/// Preflop, `seat` opened and exactly one re-raise by someone else followed: it faces a 3-bet. +pub fn facing_three_bet(history: &[ActionRecord], seat: u8) -> bool { + let mut pre = aggressive_on(history, Street::Preflop); + match (pre.next(), pre.next(), pre.next()) { + (Some(open), Some(three), None) => open.seat == seat && three.seat != seat, + _ => false, + } +} + +/// `seat` checked on `street` and exactly one bet followed: the spot to check-raise. +pub fn check_raise_chance(history: &[ActionRecord], seat: u8, street: Street) -> bool { + let Some(check) = history.iter().position(|r| r.street == street && r.seat == seat && r.action == SeenAction::Check) + else { + return false; + }; + aggressive_on(history, street).count() == 1 && aggressive_on(&history[check..], street).count() == 1 +} + +/// `seat` checked on `street` and nobody has bet there since: a bet now is a bet into its check. +pub fn checked_to(history: &[ActionRecord], seat: u8, street: Street) -> bool { + history.iter().any(|r| r.street == street && r.seat == seat && r.action == SeenAction::Check) + && aggressive_on(history, street).next().is_none() +} + +/// Hero would bet the flop as the preflop aggressor with no flop bet yet: a continuation bet. +pub fn cbet_spot(history: &[ActionRecord], hero: u8, street: Street) -> bool { + street == Street::Flop && preflop_aggressor(history) == Some(hero) && aggressive_on(history, Street::Flop).next().is_none() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn r(street: Street, seat: u8, action: SeenAction) -> ActionRecord { + ActionRecord { street, seat, action, amount: None } + } + use SeenAction::*; + use Street::*; + + #[test] + fn continuation_bet_and_its_response() { + let h = vec![r(Preflop, 1, PostSmallBlind), r(Preflop, 2, PostBigBlind), r(Preflop, 1, Raise), r(Preflop, 2, Call)]; + assert_eq!(preflop_aggressor(&h), Some(1)); + assert!(cbet_spot(&h, 1, Flop)); + assert!(!cbet_spot(&h, 2, Flop)); + let mut f = h.clone(); + f.push(r(Flop, 2, Check)); + assert!(checked_to(&f, 2, Flop)); + f.push(r(Flop, 1, Bet)); + assert!(facing_cbet(&f, 2)); + assert!(!facing_cbet(&f, 1)); + assert!(check_raise_chance(&f, 2, Flop)); + f.push(r(Flop, 2, Raise)); + assert!(!facing_cbet(&f, 2), "after the raise it is no longer a c-bet spot"); + // A donk bet is no c-bet. + let mut d = h.clone(); + d.push(r(Flop, 2, Bet)); + assert!(!facing_cbet(&d, 1)); + } + + #[test] + fn three_bet_after_opening() { + let h = vec![r(Preflop, 1, PostSmallBlind), r(Preflop, 2, PostBigBlind), r(Preflop, 1, Raise), r(Preflop, 2, Raise)]; + assert_eq!(opener(&h), Some(1)); + assert!(facing_three_bet(&h, 1)); + assert!(!facing_three_bet(&h, 2)); + let mut four = h.clone(); + four.push(r(Preflop, 1, Raise)); + assert!(!facing_three_bet(&four, 2), "a 4-bet is not a 3-bet"); + let blinds_only = vec![r(Preflop, 1, PostSmallBlind), r(Preflop, 2, PostBigBlind)]; + assert!(!facing_three_bet(&blinds_only, 1)); + } +} diff --git a/src/game/mod.rs b/src/game/mod.rs index 994fe075..f9121b98 100644 --- a/src/game/mod.rs +++ b/src/game/mod.rs @@ -3,6 +3,7 @@ pub mod action_record; pub mod choice; pub mod confidence; pub mod decision; +pub mod line; pub mod seen_action; pub mod spot; pub mod street; diff --git a/src/preflop/advise.rs b/src/preflop/advise.rs index 91396bf9..074852c7 100644 --- a/src/preflop/advise.rs +++ b/src/preflop/advise.rs @@ -18,7 +18,7 @@ use super::situation_of::situation_of; use super::width_factor::width_factor; use crate::exploit::steal_width::steal_width; use crate::exploit::thresholds::Thresholds; -use crate::game::{SeenAction, Spot}; +use crate::game::{line, SeenAction, Spot, Street}; use crate::variant::ActionShape; /// At or below this effective stack (bb) raising ranges become jamming ranges. @@ -159,6 +159,62 @@ pub fn advise(spot: &Spot, thresholds: &Thresholds) -> PreflopPlan { /// `advise` with an ICM open-jam widening factor (`>= 1`, `1.0` = neutral). The tournament entry /// (`engine::decide`) passes the bubble factor (`icm::risk::jam_width_factor`); cash passes `1.0`. pub fn advise_widened(spot: &Spot, thresholds: &Thresholds, jam_widen: f64) -> PreflopPlan { + let situation = situation_of(spot); + light_three_bet(spot, situation, advise_chart(spot, thresholds, jam_widen)) +} + +/// A light 3-bet re-raises to this multiple of the open. +const LIGHT_THREE_BET_MULT: f64 = 3.0; +/// The fold-to-3-bet read must clear the pure bluff's break-even by this much. +const LIGHT_THREE_BET_EDGE: f64 = 0.05; +/// Folding hands 3-bet light only from the top of the deck (some equity when called); the bottom +/// stays a fold. +const LIGHT_THREE_BET_BAND: f64 = 0.85; + +/// Against an opener who folds to 3-bets more than a pure bluff needs, a hand the chart calls or +/// (inside `LIGHT_THREE_BET_BAND`) folds re-raises instead: the pure bluff already wins +/// `P(fold) · pot > (1 − P(fold)) · risk`, i.e. the read clears `risk / (pot + risk)` +/// (+ `LIGHT_THREE_BET_EDGE`) for a 3-bet to `LIGHT_THREE_BET_MULT`× the open, and a called 3-bet +/// still has the hand's equity — against a folder that beats flatting. Only heads-up against the +/// lone opener with a fold-to-3-bet read, full-shape games. Everything else stays as the chart says. +fn light_three_bet(spot: &Spot, situation: Situation, plan: PreflopPlan) -> PreflopPlan { + let candidate = match plan.action { + ChartAction::Call => true, + ChartAction::Fold => plan.percentile <= LIGHT_THREE_BET_BAND, + _ => false, + }; + if situation != Situation::FacingOpen || !candidate || !matches!(spot.rules().shape, ActionShape::Full) { + return plan; + } + let mut live = spot.live_villains(); + let (Some(v), None) = (live.next(), live.next()) else { return plan }; + if line::opener(&spot.history) != Some(v.seat) { + return plan; + } + let Some(f3) = v.profile.and_then(|p| p.fold_to_three_bet).filter(|f| !f.is_nan()) else { return plan }; + let hero_in = spot + .history + .iter() + .filter(|r| r.street == Street::Preflop && r.seat == spot.hero_seat) + .filter_map(|r| r.amount) + .fold(0.0, f64::max); + let to = LIGHT_THREE_BET_MULT * (spot.to_call + hero_in); + let risk = to - hero_in; + if !(risk > 0.0 && spot.pot > 0.0) { + return plan; + } + let need = risk / (spot.pot + risk); + if f3 < need + LIGHT_THREE_BET_EDGE { + return plan; + } + PreflopPlan { + action: ChartAction::Raise, + reason: format!("{} | light 3-bet: fold to 3-bet {f3:.2} > {need:.2} needed", plan.reason), + ..plan + } +} + +fn advise_chart(spot: &Spot, thresholds: &Thresholds, jam_widen: f64) -> PreflopPlan { let hand = percentile(spot.variant, &spot.hero_cards); let pos = seat_position(spot, spot.hero_seat); let situation = situation_of(spot); diff --git a/src/sim/memory.rs b/src/sim/memory.rs index d9965fa7..7bf056b9 100644 --- a/src/sim/memory.rs +++ b/src/sim/memory.rs @@ -10,7 +10,7 @@ //! archetype, so their counts pool into one read. use crate::exploit::profile::Profile; -use crate::game::{ActionRecord, SeenAction, Street}; +use crate::game::{line, ActionRecord, SeenAction, Street}; pub use super::welt_memory::{ strength_band, Cell, Move, Pos, Reveal, SizeBucket, Showdown, Texture, Tank, WorldEvent, WorldHand, @@ -48,6 +48,14 @@ struct Counts { // 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 { @@ -60,7 +68,7 @@ fn street_index(street: Street) -> Option { } /// 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 = 15.0; +pub const STREET_FOLD_PRIOR: f64 = crate::exploit::sample::STREET_PRIOR; static STREET_FOLD: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true); @@ -73,6 +81,37 @@ 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, 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 { @@ -108,7 +147,28 @@ impl SessionMemory { } } + /// 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; + } + } + } + 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) { @@ -208,8 +268,25 @@ impl SessionMemory { } } } + 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 = + shrunk(self.c.xr_made, self.c.xr_chances, Some(CHECK_RAISE_PRIOR)).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), @@ -231,6 +308,40 @@ mod tests { 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). diff --git a/src/sim/table.rs b/src/sim/table.rs index 37690520..9c2d7178 100644 --- a/src/sim/table.rs +++ b/src/sim/table.rs @@ -14,7 +14,7 @@ use crate::card::{deck, Card}; use crate::engine::decide::decide_with; use crate::exploit::profile::Profile; use crate::icm::lage::Turnierlage; -use crate::game::{ActionKind, ActionRecord, Choice, SeenAction, Spot, Street, Villain}; +use crate::game::{line, ActionKind, ActionRecord, Choice, SeenAction, Spot, Street, Villain}; use crate::guard::validate::check; use crate::hand::showdown::best; use crate::rake::{split_over_pots, uncalled, HandEnd, RakeRule, MEASURED_ANTE_BB}; @@ -350,6 +350,9 @@ impl Table<'_> { street: self.street, texture: Texture::of(&self.setup.deal.board[..self.street.board_len()]), pos: if self.in_position(i) { Pos::Ip } else { Pos::Oop }, + facing_cbet: line::facing_cbet(&self.history, i as u8 + 1), + facing_three_bet: line::facing_three_bet(&self.history, i as u8 + 1), + checked_here: line::check_raise_chance(&self.history, i as u8 + 1, self.street), }; let (act, rng) = welt::act(&p, view, &ctx, self.rng); let (tank, rng) = p.tank_factor(reading.strength, rng); diff --git a/src/sim/welt.rs b/src/sim/welt.rs index b6530980..d2d5b65c 100644 --- a/src/sim/welt.rs +++ b/src/sim/welt.rs @@ -88,21 +88,42 @@ pub struct Persona { /// ln pace = `tank_slope` * (strength - 0.5) + `tank_noise` * z. pub tank_slope: f64, pub tank_noise: f64, + /// Added to the call margin facing a flop continuation bet (the preflop raiser's first flop bet); + /// positive folds more. 0 = treats a c-bet like any bet. + pub cbet_call: f64, + /// Preflop, after opening and facing a re-raise: continue only from this strength, fold the rest. + /// 0 = plays its base thresholds. + pub three_bet_continue: f64, + /// Check-raise tendency: the chance to check (trap) a hand it would bet when first to act out of + /// position before the river, raising a bet after its check from `bet_at` (not `raise_at`), and + /// half that chance to check-raise air. 0 = never. + pub check_raise: f64, /// The cliche HUD of the archetype (vpip, pfr, fold-to-bet, aggression), measured by `welt_leiter kalib` /// (memory read after 150 deals x 3 individuals): what `ReadMode::Oracle` /// hands the engine. It is the archetype's, not this individual's. pub oracle: [f64; 4], } -/// Labels of the archetypes, in `Persona::mean` order. -pub const ARCHETYPES: [&str; 7] = - ["wert-sizer", "polar", "umgekehrt", "textur-cbet", "position", "tanker", "balanciert"]; +/// Labels of the archetypes, in `Persona::mean` order. The last three deviate on exactly one HUD axis +/// the pooled reads do not see (fold to c-bet, fold to 3-bet, check-raise): the gate for those reads. +pub const ARCHETYPES: [&str; 10] = [ + "wert-sizer", + "polar", + "umgekehrt", + "textur-cbet", + "position", + "tanker", + "balanciert", + "cbet-folder", + "3bet-folder", + "check-raiser", +]; /// Index of the control archetype. pub const BALANCED: usize = 6; /// Share of the field per archetype (`Persona::sample`). -const WEIGHTS: [f64; 7] = [0.18, 0.14, 0.16, 0.14, 0.14, 0.12, 0.12]; +const WEIGHTS: [f64; 10] = [0.18, 0.14, 0.16, 0.14, 0.14, 0.12, 0.12, 0.10, 0.10, 0.10]; const REG: Rules = Rules { call_margin: 0.22, raise_at: 0.82, bet_at: 0.64, open_at: 0.62, bluff: 0.10, size: 2.0 / 3.0 }; @@ -122,6 +143,9 @@ impl Persona { ip: Shift::NONE, tank_slope: 0.0, tank_noise: 0.30, + cbet_call: 0.0, + three_bet_continue: 0.0, + check_raise: 0.0, oracle: [0.31, 0.13, 0.55, 0.30], }; match i { @@ -190,7 +214,35 @@ impl Persona { ..base }, // Control: size independent of strength, no texture or position effect, no pace tell. - _ => Persona { tell: Tell::Mixed, lo: 0.33, hi: 1.0, noise: 0.10, oracle: [0.61, 0.09, 0.42, 0.32], ..base }, + 6 => Persona { tell: Tell::Mixed, lo: 0.33, hi: 1.0, noise: 0.10, oracle: [0.61, 0.09, 0.42, 0.32], ..base }, + // Gives up on the flop to a c-bet, sticky everywhere else (turn/river call down light): a + // pooled fold-to-bet averages the two and misprices both. Oracle not calibrated (Memory reads). + 7 => Persona { + rules: Rules { call_margin: 0.12, ..REG }, + tell: Tell::Mixed, + noise: 0.10, + cbet_call: 0.24, + oracle: [0.31, 0.13, 0.50, 0.30], + ..base + }, + // Opens wide, folds to a 3-bet unless strong: a light 3-bet prints against it. + 8 => Persona { + rules: Rules { open_at: 0.50, ..REG }, + tell: Tell::Mixed, + noise: 0.10, + three_bet_continue: 0.80, + oracle: [0.45, 0.30, 0.55, 0.30], + ..base + }, + // Traps out of position and check-raises, strong and air: betting into its check is + // riskier than its fold-to-bet says, thin value and stabs lose. + _ => Persona { + tell: Tell::Mixed, + noise: 0.10, + check_raise: 0.55, + oracle: [0.31, 0.13, 0.50, 0.35], + ..base + }, } } @@ -221,6 +273,20 @@ impl Persona { ..m }; let mut rng = rng; + // The single-axis tendencies (only the archetypes that have one draw them, so every older + // archetype's draw sequence is untouched). + if p.cbet_call > 0.0 { + let (v, r) = jitter(p.cbet_call, 0.04, 0.05, 0.45, rng); + (p.cbet_call, rng) = (v, r); + } + if p.three_bet_continue > 0.0 { + let (v, r) = jitter(p.three_bet_continue, 0.04, 0.65, 0.95, rng); + (p.three_bet_continue, rng) = (v, r); + } + if p.check_raise > 0.0 { + let (v, r) = jitter(p.check_raise, 0.08, 0.2, 0.9, rng); + (p.check_raise, rng) = (v, r); + } if !control { for s in p.tex.iter_mut().chain([&mut p.oop, &mut p.ip]) { let (a, r1) = jitter(s.bet_at, 0.025, -0.3, 0.3, rng); @@ -295,12 +361,21 @@ pub struct Ctx { pub street: Street, pub texture: Texture, pub pos: Pos, + /// Facing the preflop raiser's first flop bet (a continuation bet). + pub facing_cbet: bool, + /// Preflop, it opened and now faces a re-raise. + pub facing_three_bet: bool, + /// It already checked on this street (a bet now faces it after its check). + pub checked_here: bool, } /// The persona's action. Preflop it plays its base thresholds (`reader::act_with`); postflop the /// thresholds are shifted by the board texture and its position, and bets are sized by its tell. pub fn act(p: &Persona, view: View, ctx: &Ctx, rng: Rng) -> (Act, Rng) { if ctx.street == Street::Preflop { + if ctx.facing_three_bet && p.three_bet_continue > 0.0 && view.to_call > 0.0 && ctx.reading.strength < p.three_bet_continue { + return (Act::Fold, rng); + } return act_with(p.rules, view, ctx.reading, rng); } let s = ctx.reading.strength; @@ -309,7 +384,8 @@ pub fn act(p: &Persona, view: View, ctx: &Ctx, rng: Rng) -> (Act, Rng) { let ps = if ctx.pos == Pos::Ip { p.ip } else { p.oop }; let bet_at = p.rules.bet_at + t.bet_at + ps.bet_at; let raise_at = p.rules.raise_at + t.raise_at + ps.raise_at; - let margin = (p.rules.call_margin + t.call + ps.call).max(0.0); + let cbet = if ctx.facing_cbet { p.cbet_call } else { 0.0 }; + let margin = (p.rules.call_margin + t.call + ps.call + cbet).max(0.0); let bluff = (p.rules.bluff * t.bluff_mult * ps.bluff_mult).clamp(0.0, 0.9); let can_raise = view.min_raise_to.is_some(); let sized = |bluff_hand: bool, rng: Rng| { @@ -320,10 +396,30 @@ pub fn act(p: &Persona, view: View, ctx: &Ctx, rng: Rng) -> (Act, Rng) { if can_raise && s >= raise_at { return sized(false, rng); } + let mut rng = rng; + if p.check_raise > 0.0 && can_raise && ctx.checked_here { + if s >= bet_at { + return sized(false, rng); // the trapped hand springs + } + if s < BLUFF_BELOW { + let (u, r) = rng.unit(); + rng = r; + if u < p.check_raise / 2.0 { + return sized(true, rng); + } + } + } let price = to_call / (ctx.reading.pot + to_call); return (if s >= price + margin { Act::Call } else { Act::Fold }, rng); } if can_raise && s >= bet_at { + if p.check_raise > 0.0 && ctx.pos == Pos::Oop && ctx.street != Street::River { + let (u, rng) = rng.unit(); + if u < p.check_raise { + return (Act::Check, rng); // trap: check to raise + } + return sized(false, rng); + } return sized(false, rng); } if can_raise && s < BLUFF_BELOW { @@ -442,6 +538,9 @@ mod tests { street: Street::Flop, texture, pos, + facing_cbet: false, + facing_three_bet: false, + checked_here: false, }; let view = View { to_call: 0.0, min_raise_to: Some(1.0), max_raise_to: Some(100.0) }; let (a, r2) = act(p, view, &ctx, r); @@ -464,6 +563,56 @@ mod tests { assert!((a - b).abs() < 0.03, "{a} vs {b}"); } + /// The three single-axis archetypes deviate exactly where their HUD stat says. + #[test] + fn the_line_archetypes_play_their_line() { + let ctx = |strength: f64, street: Street, pos: Pos, cbet: bool, three: bool, checked: bool| Ctx { + reading: Reading { strength, pot: 4.0, own_bet: 0.0, preflop: street == Street::Preflop }, + street, + texture: Texture::Dry, + pos, + facing_cbet: cbet, + facing_three_bet: three, + checked_here: checked, + }; + let facing = View { to_call: 2.0, min_raise_to: Some(4.0), max_raise_to: Some(100.0) }; + let open = View { to_call: 0.0, min_raise_to: Some(1.0), max_raise_to: Some(100.0) }; + let rate = |p: &Persona, view: View, c: &dyn Fn(f64) -> Ctx, pick: fn(&Act) -> bool| { + let mut rng = Rng::seeded(31); + let mut hits = 0; + for _ in 0..3000 { + let (s, r) = rng.unit(); + let (a, r2) = act(p, view, &c(s), r); + rng = r2; + hits += pick(&a) as u32; + } + hits as f64 / 3000.0 + }; + let fold = |a: &Act| matches!(a, Act::Fold); + let raise = |a: &Act| matches!(a, Act::RaiseTo(_)); + let check = |a: &Act| matches!(a, Act::Check); + + let cf = arch(7, 1); + let vs_cbet = rate(&cf, facing, &|s| ctx(s, Street::Flop, Pos::Oop, true, false, false), fold); + let vs_bet = rate(&cf, facing, &|s| ctx(s, Street::Flop, Pos::Oop, false, false, false), fold); + println!("cbet-folder folds c-bet {vs_cbet:.2}, other bet {vs_bet:.2}"); + assert!(vs_cbet > vs_bet + 0.15); + + let tf = arch(8, 2); + let vs_three = rate(&tf, facing, &|s| ctx(s, Street::Preflop, Pos::Ip, false, true, false), fold); + let vs_open = rate(&tf, facing, &|s| ctx(s, Street::Preflop, Pos::Ip, false, false, false), fold); + println!("3bet-folder folds 3-bet {vs_three:.2}, other raise {vs_open:.2}"); + assert!(vs_three > vs_open + 0.15); + + let xr = arch(9, 3); + let traps = rate(&xr, open, &|s| ctx(s, Street::Flop, Pos::Oop, false, false, false), check); + let reg_checks = rate(&arch(BALANCED, 3), open, &|s| ctx(s, Street::Flop, Pos::Oop, false, false, false), check); + let springs = rate(&xr, facing, &|s| ctx(s, Street::Flop, Pos::Oop, false, false, true), raise); + let reg_raises = rate(&arch(BALANCED, 3), facing, &|s| ctx(s, Street::Flop, Pos::Oop, false, false, true), raise); + println!("check-raiser checks {traps:.2} (control {reg_checks:.2}), raises after check {springs:.2} (control {reg_raises:.2})"); + assert!(traps > reg_checks + 0.05 && springs > reg_raises + 0.1); + } + #[test] fn the_tanker_slows_down_with_strength() { let p = arch(5, 11); @@ -553,7 +702,7 @@ mod tests { #[test] fn the_field_draws_every_archetype() { let mut rng = Rng::seeded(77); - let mut seen = [0u32; 7]; + let mut seen = [0u32; ARCHETYPES.len()]; for _ in 0..3000 { let (p, r) = Persona::sample(rng); rng = r; diff --git a/src/sim/welt_memory.rs b/src/sim/welt_memory.rs index 985f8020..1f734fce 100644 --- a/src/sim/welt_memory.rs +++ b/src/sim/welt_memory.rs @@ -331,6 +331,9 @@ pub struct WorldMemory { showdowns: Vec, hands: u32, revealed_hands: u32, + /// River bets/raises of revealed hands, and how many of them were air (`profile::AIR_STRENGTH`). + river_bets_shown: u32, + river_air_shown: u32, } fn street_ix(street: Street) -> Option { @@ -409,6 +412,10 @@ impl WorldMemory { if let (Move::Bet | Move::Raise, Some(f)) = (ev.mv, ev.size_frac) { self.observe_size_strength(f, st); aggressive += 1; + if ev.street == Street::River { + self.river_bets_shown += 1; + self.river_air_shown += (st < crate::exploit::profile::AIR_STRENGTH) as u32; + } } if let Some(t) = ev.tank { self.observe_tank_strength(t, st); @@ -454,6 +461,8 @@ impl WorldMemory { self.showdowns.drain(..over); self.hands += other.hands; self.revealed_hands += other.revealed_hands; + self.river_bets_shown += other.river_bets_shown; + self.river_air_shown += other.river_air_shown; } // ---- queries ---- @@ -533,6 +542,13 @@ impl WorldMemory { } /// The most recent showdowns (up to `SHOWDOWN_CAP`), oldest first. + /// River showdown read: `(air share, shown river bets)` over the river bets/raises of revealed + /// hands, `None` before the first one. + pub fn river_bluff(&self) -> Option<(f64, u32)> { + (self.river_bets_shown > 0) + .then(|| (self.river_air_shown as f64 / self.river_bets_shown as f64, self.river_bets_shown)) + } + pub fn showdowns(&self) -> &[Showdown] { &self.showdowns } @@ -656,6 +672,34 @@ mod tests { assert_eq!(m2.size_pairs(), 0); } + #[test] + fn shown_river_bets_split_into_air_and_value() { + let board = cards("Ks 7d 2c 9h 3s"); + let river_bet = |seat| WorldEvent { + seat, + street: Street::River, + texture: Texture::Dry, + pos: Pos::Ip, + mv: Move::Bet, + size_frac: Some(0.75), + tank: None, + }; + let hand = |hole: &str| WorldHand { + events: vec![river_bet(2)], + reveals: vec![Reveal { seat: 2, hole: [Card::parse_short(&hole[..2]).unwrap(), Card::parse_short(&hole[2..]).unwrap()], board: board.clone() }], + }; + let mut m = WorldMemory::new(); + assert_eq!(m.river_bluff(), None); + m.observe_world_hand(&hand("AhAd")); // overpair: value + m.observe_world_hand(&hand("5h4h")); // missed draw, 5-high: air + m.observe_world_hand(&WorldHand { events: vec![river_bet(2)], reveals: vec![] }); // not shown: no evidence + assert_eq!(m.river_bluff(), Some((0.5, 2))); + let mut sum = WorldMemory::new(); + sum.merge(&m); + sum.merge(&m); + assert_eq!(sum.river_bluff(), Some((0.5, 4))); + } + #[test] fn merge_sums_the_counts() { let mut a = WorldMemory::new(); diff --git a/src/wire/decode_villain.rs b/src/wire/decode_villain.rs index 25bd175d..f4cd3c11 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; +use crate::exploit::sample::{shrink, shrink_aggression, shrink_street, CHECK_RAISE_ANCHOR, FOLD_TO_THREE_BET_ANCHOR}; use crate::fault::Fault; use crate::game::Villain; use crate::json::field::{at, join, optional, text}; @@ -17,8 +17,8 @@ fn profile(villain: &Value, path: &str) -> Result, Fault> { pfr: opt_number_member(object, &at_profile, "pfr")?, fold_to_bet: opt_number_member(object, &at_profile, "foldToBet")?, aggression: opt_number_member(object, &at_profile, "aggression")?, - // Per-street aggression is not on the wire yet (the opponent memory derives it); keep it None - // so the engine falls back to the pooled read until the client delivers it. + // Per-street reads come as raw rate + sample (`streets` below) and are shrunk toward the pooled + // read there; nothing unshrunk lands here. turn_aggression: None, river_aggression: None, street_fold_to_bet: [None; 3], @@ -33,12 +33,69 @@ fn profile(villain: &Value, path: &str) -> Result, Fault> { wsd: opt_number_member(object, &at_profile, "wsd")?, // Not on the wire: confidence is derived from `hands` by `shrink` below (half-life PRIOR_HANDS). confidence: None, + aggression_confidence: None, + river_bluff_share: None, + river_bluff_shown: None, }; // `hands` (extension, exploit::sample): with it, few hands count little - Ok(Some(match opt_number_member(object, &at_profile, "hands")? { + let shrunk = match opt_number_member(object, &at_profile, "hands")? { Some(hands) => shrink(&raw, hands), None => raw, - })) + }; + // `aggressionActions` (extension, lesen/profil.py): the postflop moves the aggression was measured + // over. Aggression then trusts its OWN sample, not the HUD hand count. + let pooled = match opt_number_member(object, &at_profile, "aggressionActions")? { + Some(actions) => shrink_aggression(shrunk, raw.aggression, actions), + None => shrunk, + }; + 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. +fn streets(object: &Value, path: &str, pooled: Profile) -> Result { + let read = |rate: &str, count: &str, anchor: Option| -> Result, Fault> { + Ok(match opt_number_member(object, path, count)? { + Some(n) => shrink_street(opt_number_member(object, path, rate)?, n, anchor), + None => 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 = [ + read("flopFoldToBet", "flopFacingBet", pooled.fold_to_bet)?, + read("turnFoldToBet", "turnFacingBet", pooled.fold_to_bet)?, + read("riverFoldToBet", "riverFacingBet", pooled.fold_to_bet)?, + ]; + Ok(Profile { + fold_to_cbet, + fold_to_three_bet, + check_raise, + turn_aggression: turn_aggression.or(pooled.turn_aggression), + river_aggression: river_aggression.or(pooled.river_aggression), + street_fold_to_bet, + ..pooled + }) } /// `marke` (extension, exploit::mark): the client's label fills what the profile does not know. diff --git a/tests/aggression_spec.py b/tests/aggression_spec.py index 392eac18..7bba96a5 100644 --- a/tests/aggression_spec.py +++ b/tests/aggression_spec.py @@ -77,11 +77,20 @@ class ImProfil(unittest.TestCase): self.assertAlmostEqual(p[2]["vpip"], 0.29, places=6) self.assertAlmostEqual(p[2]["foldToBet"], 0.65, places=6) + def test_profil_traegt_die_stichprobe_der_aggression(self): + # Der Kern gewichtet die Aggression mit IHRER Stichprobe, nicht mit den HUD-Haenden. + werte = {"1662615": {"vpip": 0.29, "pfr": 0.20, "foldToBet": 0.65}} + aktionen = {"1662615": [{"street": "FLOP", "action": "BET"}, {"street": "TURN", "action": "CHECK"}, + {"street": "TURN", "action": "FOLD"}, {"street": "PREFLOP", "action": "RAISE"}]} + p = profil.aus_sitzliste(self.SITZE, werte, aktionen=aktionen) + self.assertEqual(p[2]["aggressionActions"], 2) + def test_ohne_nachflop_zug_fehlt_das_feld(self): werte = {"1662615": {"vpip": 0.29, "pfr": 0.20, "foldToBet": 0.65}} aktionen = {"1662615": [{"street": "PREFLOP", "action": "RAISE"}]} p = profil.aus_sitzliste(self.SITZE, werte, aktionen=aktionen) self.assertNotIn("aggression", p[2]) + self.assertNotIn("aggressionActions", p[2]) def test_ohne_aktionen_bleibt_das_profil_wie_bisher(self): werte = {"1662615": {"vpip": 0.29, "pfr": 0.20, "foldToBet": 0.65}} @@ -89,5 +98,39 @@ class ImProfil(unittest.TestCase): self.assertNotIn("aggression", p[2]) +class Strassen(unittest.TestCase): + """Reads je Strasse - gezaehlt wie das Sitzungsgedaechtnis der Sim (src/sim/memory.rs), geliefert + als Rohanteil plus Stichprobe; der Kern zieht sie zum Gesamt-Read.""" + + def test_aggression_je_strasse_mit_stichprobe(self): + r = profil.strassen([zug("FLOP", "BET"), zug("TURN", "BET"), zug("TURN", "CHECK"), + zug("RIVER", "CALL"), zug("RIVER", "FOLD")]) + self.assertAlmostEqual(r["turnAggression"], 0.5) + self.assertEqual(r["turnAggressionActions"], 2) + self.assertEqual(r["riverAggression"], 0.0) # der Fold zaehlt nicht mit + self.assertEqual(r["riverAggressionActions"], 1) + self.assertNotIn("flopAggression", r) # der Flop steckt im Gesamt-Read + + def test_fold_auf_bet_je_strasse(self): + r = profil.strassen([zug("FLOP", "CALL"), zug("FLOP", "FOLD"), zug("FLOP", "RAISE"), + zug("TURN", "FOLD"), zug("PREFLOP", "FOLD")]) + self.assertAlmostEqual(r["flopFoldToBet"], 0.5) # die Erhoehung zaehlt nicht + self.assertEqual(r["flopFacingBet"], 2) + self.assertEqual(r["turnFoldToBet"], 1.0) + self.assertEqual(r["turnFacingBet"], 1) + self.assertNotIn("riverFoldToBet", r) + + def test_ohne_zuege_leer(self): + self.assertEqual(profil.strassen(None), {}) + self.assertEqual(profil.strassen([zug("PREFLOP", "RAISE")]), {}) + + def test_im_profil(self): + sitze = [{"seatId": 2, "userName": "SneS77", "userId": 1662615}] + werte = {"1662615": {"vpip": 0.29, "foldToBet": 0.65}} + p = profil.aus_sitzliste(sitze, werte, aktionen={"1662615": [zug("RIVER", "BET")]}) + self.assertEqual(p[2]["riverAggression"], 1.0) + self.assertEqual(p[2]["riverAggressionActions"], 1) + + if __name__ == "__main__": unittest.main(verbosity=2) diff --git a/tests/handreview_spec.py b/tests/handreview_spec.py index 05ccfc79..8e831f2c 100644 --- a/tests/handreview_spec.py +++ b/tests/handreview_spec.py @@ -57,6 +57,25 @@ class Eintrag(unittest.TestCase): self.assertEqual(e["aktion"], "FOLD") +class Gegner(unittest.TestCase): + """Was der Kern ueber die Gegner wusste, steht am Zug (fuer treue Replays).""" + + def test_profile_je_sitz_nur_zahlen(self): + anfrage = {**ANFRAGE, "villains": [ + {"seat": 3, "stack": 1.6, "folded": False, + "profile": {"vpip": 0.6, "hands": 26, "aggression": 0.4, "aggressionActions": 5, + "gezeigt": [["Ah", "Td"]]}}, + {"seat": 4, "stack": 2.0, "folded": True}, + {"seat": 5, "stack": 2.0, "folded": False}]} + g = handreview.eintrag(anfrage, ANTWORT)["gegner"] + self.assertEqual(g["3"], {"vpip": 0.6, "hands": 26, "aggression": 0.4, "aggressionActions": 5}) + self.assertEqual(g["4"], {"folded": True}) + self.assertNotIn("5", g) + + def test_ohne_gegner_none(self): + self.assertIsNone(handreview.eintrag(ANFRAGE, ANTWORT)["gegner"]) + + class Finde(unittest.TestCase): def setUp(self): self.zuege = [ diff --git a/tests/line_reads.rs b/tests/line_reads.rs new file mode 100644 index 00000000..9aae230b --- /dev/null +++ b/tests/line_reads.rs @@ -0,0 +1,107 @@ +//! The line-specific HUD reads reach hero's decisions: a light 3-bet against a 3-bet folder, the +//! fold-to-c-bet read pricing hero's c-bet. +use rechner::card::Card; +use rechner::exploit::profile::Profile; +use rechner::exploit::table_fold::table_fold; +use rechner::exploit::thresholds::Thresholds; +use rechner::game::{ActionKind, ActionRecord, SeenAction, Spot, Street, Villain}; +use rechner::preflop::advise::advise; +use rechner::preflop::plan::ChartAction; +use rechner::variant::Variant; + +fn rec(street: Street, seat: u8, action: SeenAction, amount: Option) -> ActionRecord { + ActionRecord { street, seat, action, amount } +} + +/// Heads-up, hero big blind (seat 2), the button/small blind (seat 1) opened to 2.5. +fn bb_vs_open(hole: &str, profile: Option) -> Spot { + Spot { + variant: Variant::Nlhe, + big_blind: 1.0, + seats: 2, + hero_seat: 2, + button_seat: Some(1), + hero_cards: Card::parse_list(hole).expect("cards"), + board: vec![], + street: Street::Preflop, + pot: 3.5, + to_call: 1.5, + hero_stack: 99.0, + min_raise_to: Some(4.0), + max_raise_to: Some(100.0), + legal: vec![ActionKind::Fold, ActionKind::Call, ActionKind::Raise], + allowed_sizes: None, + villains: vec![Villain { seat: 1, stack: 97.5, folded: false, profile }], + seed: 1, + history: vec![ + rec(Street::Preflop, 1, SeenAction::PostSmallBlind, Some(0.5)), + rec(Street::Preflop, 2, SeenAction::PostBigBlind, Some(1.0)), + rec(Street::Preflop, 1, SeenAction::Raise, Some(2.5)), + ], + } +} + +#[test] +fn a_three_bet_folder_gets_three_bet_light() { + // Find a hand the chart folds, inside the light band. + let folds = ["Q2o", "J3o", "T4o", "K2o", "94s", "Q4o", "J5o", "T6o", "K3o", "85s", "72o", "83o", "92o", "T2o", "J2o", "64o", "53o", "T3o"]; + let to_cards = |h: &str| { + let b = h.as_bytes(); + let (r1, r2) = (b[0] as char, b[1] as char); + if b[2] == b's' { format!("{r1}h {r2}h") } else { format!("{r1}h {r2}d") } + }; + let folder = Profile { fold_to_three_bet: Some(0.9), ..Profile::default() }; + let sticky = Profile { fold_to_three_bet: Some(0.3), ..Profile::default() }; + let mut tried = 0; + for h in folds { + let blind = advise(&bb_vs_open(&to_cards(h), None), &Thresholds::BASE); + if blind.action == ChartAction::Raise || (blind.action == ChartAction::Fold && blind.percentile > 0.85) { + continue; + } + tried += 1; + let vs = advise(&bb_vs_open(&to_cards(h), Some(folder)), &Thresholds::BASE); + assert_eq!(vs.action, ChartAction::Raise, "{h}: {}", vs.reason); + assert!(vs.reason.contains("light 3-bet")); + assert_eq!(advise(&bb_vs_open(&to_cards(h), Some(sticky)), &Thresholds::BASE).action, blind.action); + } + assert!(tried > 0, "no folding hand in the band found"); +} + +/// Heads-up flop, hero (seat 1) raised preflop, the villain (seat 2) checked to hero. +fn flop_checked_to_hero(profile: Profile) -> Spot { + Spot { + variant: Variant::Nlhe, + big_blind: 1.0, + seats: 2, + hero_seat: 1, + button_seat: Some(1), + hero_cards: Card::parse_list("7h 6h").expect("cards"), + board: Card::parse_list("Ks 9d 2c").expect("board"), + street: Street::Flop, + pot: 5.0, + to_call: 0.0, + hero_stack: 97.5, + min_raise_to: Some(1.0), + max_raise_to: Some(97.5), + legal: vec![ActionKind::Check, ActionKind::Raise], + allowed_sizes: None, + villains: vec![Villain { seat: 2, stack: 97.5, folded: false, profile: Some(profile) }], + seed: 1, + history: vec![ + rec(Street::Preflop, 1, SeenAction::PostSmallBlind, Some(0.5)), + rec(Street::Preflop, 2, SeenAction::PostBigBlind, Some(1.0)), + rec(Street::Preflop, 1, SeenAction::Raise, Some(2.5)), + rec(Street::Preflop, 2, SeenAction::Call, Some(2.5)), + rec(Street::Flop, 2, SeenAction::Check, None), + ], + } +} + +#[test] +fn the_cbet_is_priced_by_fold_to_cbet() { + let base = Profile { vpip: Some(0.3), fold_to_bet: Some(0.4), ..Profile::default() }; + let pooled = table_fold(&flop_checked_to_hero(base), 3.0, 1.0); + let folder = table_fold(&flop_checked_to_hero(Profile { fold_to_cbet: Some(0.8), ..base }), 3.0, 1.0); + let sticky = table_fold(&flop_checked_to_hero(Profile { fold_to_cbet: Some(0.2), ..base }), 3.0, 1.0); + assert!(folder > pooled + 0.2 && sticky < pooled - 0.1, "{sticky} {pooled} {folder}"); +} diff --git a/tests/wire_decode.rs b/tests/wire_decode.rs index be05a6f3..3da33737 100644 --- a/tests/wire_decode.rs +++ b/tests/wire_decode.rs @@ -274,3 +274,58 @@ fn decoding_does_not_check_consistency() { // Hero seat beyond the table: structurally fine, guard::validate rejects it later. assert!(run(&with(r#""heroSeat":0"#, r#""heroSeat":9"#)).is_ok()); } + +/// `aggressionActions`: the aggression read is weighed on its OWN sample (postflop moves seen), not +/// on the HUD hand count, and carries that weight as `aggression_confidence`; the overall confidence +/// still comes from `hands`. Without the count nothing changes. +#[test] +fn aggression_trusts_its_own_sample() { + let thin = r#""villains":[{"seat":1,"stack":50,"folded":false,"profile":{ + "vpip":0.6,"hands":500,"aggression":0.0,"aggressionActions":2}}]"#; + let p = run(&plus(thin)).unwrap().villains[0].profile.unwrap(); + let w = 2.0 / (2.0 + 30.0); + assert!((p.aggression_confidence.unwrap() - w).abs() < 1e-12); + assert!((p.aggression.unwrap() - 0.35 * (1.0 - w)).abs() < 1e-12, "pulled to the population, not 0"); + assert!(p.confidence.unwrap() > 0.9, "the HUD read itself is strong"); + assert!((p.bluff_read_confidence().unwrap() - w).abs() < 1e-12, "a bluff read is only as good as its aggression"); + + let old = r#""villains":[{"seat":1,"stack":50,"folded":false,"profile":{"vpip":0.6,"hands":500,"aggression":0.0}}]"#; + let q = run(&plus(old)).unwrap().villains[0].profile.unwrap(); + assert_eq!(q.aggression_confidence, None); + assert_eq!(q.bluff_read_confidence(), q.confidence); +} + +#[test] +fn street_reads_are_pulled_to_the_pooled_read() { + // One river bet seen: the river belief moves only 1/16 of the way off the pooled aggression. + let one = r#""villains":[{"seat":1,"stack":50,"folded":false,"profile":{ + "vpip":0.3,"foldToBet":0.5,"aggression":0.2, + "riverAggression":1.0,"riverAggressionActions":1, + "turnFoldToBet":1.0,"turnFacingBet":5}}]"#; + let p = run(&plus(one)).unwrap().villains[0].profile.unwrap(); + assert!((p.river_aggression.unwrap() - (1.0 + 15.0 * 0.2) / 16.0).abs() < 1e-12); + assert!((p.street_fold_to_bet[1].unwrap() - (5.0 + 15.0 * 0.5) / 20.0).abs() < 1e-12); + assert_eq!(p.turn_aggression, None, "no turn sample: falls back to the pooled read"); + assert_eq!(p.street_fold_to_bet[0], None); + + // A rate without its sample, or without a pooled read to anchor on, is not trusted at all. + let bare = r#""villains":[{"seat":1,"stack":50,"folded":false,"profile":{ + "vpip":0.3,"riverAggression":1.0,"riverAggressionActions":3,"riverFoldToBet":0.0}}]"#; + let q = run(&plus(bare)).unwrap().villains[0].profile.unwrap(); + assert_eq!(q.river_aggression, None); + assert_eq!(q.street_fold_to_bet[2], None); +} + +#[test] +fn hud_line_stats_rest_on_their_spots_not_on_all_hands() { + // 100 HUD hands are ~15 c-bets faced: the 0.9 fold-to-c-bet is pulled halfway to the 0.4 pool. + let p = r#""villains":[{"seat":1,"stack":50,"folded":false,"profile":{ + "foldToBet":0.4,"foldToCbet":0.9,"foldToThreeBet":0.9,"checkRaise":0.3,"hands":100}}]"#; + let q = run(&plus(p)).unwrap().villains[0].profile.unwrap(); + let fb = q.fold_to_bet.unwrap(); // already hand-shrunk + let n = 100.0 * 0.15; + assert!((q.fold_to_cbet.unwrap() - (0.9 * n + 15.0 * fb) / (n + 15.0)).abs() < 1e-12); + let n3 = 100.0 * 0.04; + assert!((q.fold_to_three_bet.unwrap() - (0.9 * n3 + 15.0 * 0.55) / (n3 + 15.0)).abs() < 1e-12); + assert!(q.check_raise.unwrap() < 0.2, "10 chances barely move it off 0.08"); +}