Messstand: exploit-live (D1b/D1c) + solver-ueberall e7a00cb zusammen, nur fuer Messarme

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-14 21:28:50 +01:00
co-authored by Claude Opus 5.5
26 changed files with 4032 additions and 1473 deletions
+3
View File
@@ -15,3 +15,6 @@ mac/build/
daten/abstraktion/*.u8
daten/abstraktion/*.f32
daten/grundstrategie/
# Engine-Roentgen: Kern-Kopie und Nachspiel-Cache (lesen/roentgen.py), aus dem Lauf reproduzierbar
archiv/roentgen/
+1
View File
@@ -116,6 +116,7 @@ bewertet und nicht Ergebnisse. Seit 14.11. ergänzt sie die Live-Fixture (Messre
| E3 | Turn+River am Tisch nachrechnen, Ranges aus E2 | Leiter: gegen gto ≥ 0; River-Exploitability < 10 | gebaut; LBR gepaart **−83 ±69** gegen die Live-Engine (2000 Hände, weniger ausbeutbar). **Live ab Wechselpunkt 1 (Owner, O1)**; auf 282 echten Turn-Spots greift es 22-mal, ≤ 1,25 s je Entscheidung |
| E4 | Ausnutzung (`dbr`) mit Gewichten aus den Zählungen | Messregel 1a | entfällt mit dem Stopp |
| E5 | Umschalten: neue Engine wird Live-Stand | Z2 und Z3 erfüllt | entfällt mit dem Stopp |
| ES | **Solver überall** (Auftrag Orchestrator 14.11. abends, Ausnahme von der Stopp-Regel wie O1): ein Spieltheorie-Solver entscheidet jede Heads-up-Postflop-Straße live statt der Heuristik. Stufe A River (`SOLVER_RIVER`), B Turn (`SOLVER_TURN`), C Flop (`SOLVER_FLOP`), je ein Schalter in `betrieb/kern_schalter.txt`, aus. Ranges: Grundstrategie wo erkannt, sonst Range-Modell der Aktionsfolge | je Stufe: LBR gepaart signifikant besser, Leiter ohne Absturz, ≤ 2 s je Entscheidung (p99 ≤ 4 s), Abdeckung auf echten Anfragen | gebaut (A, B, C), Messung läuft; Stand in `STAND-weltklasse.md` §11 |
Es bleibt bei Heuristik plus Vetos. Erlaubt sind weiter: Fixes für in echten Händen bewiesene Lecks
(Live-Fixture), gemessen nach Messregel 1a (Leiter ohne Absturz, LBR vorher/nachher).
+1
View File
@@ -276,6 +276,7 @@ das E1-Tor erneut.
| Betrieb: River-Züge verpasst (Lauf 4, 18:00) | 4 von 260 Turn-Händen am 14.11. bekamen am River keine Entscheidung, die Uhr lief ab, der Client checkte (z. B. 177540600835, A7h). Ursache: `game.hole_cards` kommt einmal am Handanfang, main.log wächst bei 12 Tischen ~2,6 MB je Minute, das Lesefenster (4 MB) reicht ~90 s zurück; ohne Karten verwarf `spots()` den Zug still. Behoben: Handkarten-Gedächtnis je Hand im Läufer (`runner.HANDKARTEN`, 2000 Hände). Nachgebaut: der River-Spot der Hand erscheint wieder. Spec `tests/handkarten_gedaechtnis_spec.py` 5/5. Greift ab dem nächsten Läuferstart | L2 |
| Micro-Lauf 4 (ab 18:57, Arm `schalter:MDF_UNREAD=0,TURN_SPIEL=grund`, mit Handkarten-Fix), Stand 20:02 | 1006 Hände an 16 Tischen, **−278,9 BB, −27,7 bb/100 [−97,8, +42,4]**. 31 Hände ≥ 20 BB = −326,5 BB, Rest +47,6 BB. VPIP 35,6 %, PFR 25,7 %. 0 MDF-Boden-Calls; E3 rechnete 17 Turn-Züge, Hände netto +145,5 BB (eine +115). Kein Timeout, Restzeit beim Klick min 10,1 s, keine Straße ohne Entscheid. Neues Leck: **A7o callt einen 90-BB-Open-Jam** als „BTN vs open, CFR call 99 %“ (−89,5 BB); der Preflop-Weg behandelt einen All-in-Open wie einen normalen Open. Arm über den Tag: alt −49,5 ±52,3 bb/100 (1357 Hände), neu −2,1 ±61,9 (1234) | L2, D4 |
| Regression durch den Handkarten-Fix (Lauf 4) | Mit dem Gedächtnis kamen alte, schon beantwortete Züge wieder heraus. Ihr Tischzustand lag vor dem Fenster, die Übersetzung baute sie als „PREFLOP, Platz/Knopf unbekannt“, der Läufer hielt sie für neu: **308 Enthaltungen, 233 geklickt** (fold/check ins Leere). Schaden erkennbar: 1 Hand, −2,5 BB. Behoben: Karten nur aus dem Gedächtnis zählen nur für einen Zug, nach dem am Tisch noch nicht gehandelt wurde. Nachspiel main.1 (gleitendes 4-MB-Fenster): alt 218 Züge / 0 Enthaltungen, neu 219 / 1 (ein River-Zug zurück). Spec 7/7. Greift ab dem nächsten Läuferstart | L2 |
| Engine-Röntgen (Transparenz je Lauf) | `lesen/roentgen.py` (CLI, `--json`), Cockpit-Seite `/roentgen` (sicht-Server, Nachspiel im Hintergrund, Cache je Lauf), Spec `tests/roentgen_spec.py` 11/11. Lauf 4 (pid 43432, 18:57–20:14, 1192 Hände, −12,9 bb/100 [−76, +51]): **Gegner-Read ändert 7 von 2060 Entscheidungen (0,3 %)**, Preflop-CFR 60,9 % der Preflop-Kern-Züge, E3 7,2 % der Turn-Züge, Turn-/River-Veto 0, MDF-Boden 0, Flop/River 100 % Heuristik; Read-Stichprobe Median 23 Hände, kein Gegner ≥ 100; Nachspiel = live 99,9 % | Transparenz, D2 |
| Strang E | gestoppt am Tor (Abschnitt 9); Plan nachgezogen, offene Owner-Entscheidungen O1–O4 in `PLAN-weltklasse.md` 4a | Tor E2 |
| D1b Befund: Profile live zu dünn | Live trug jedes Profil `hands` ≈ 23 (Median, max 40: Grundwert 20 + Hände im Lesefenster), die Aggression stand in 30 % der Profile, Median 2 Züge (Lesefenster ~90 s). Die Vertrauensrampen des Kerns blieben am ungelesenen Standard: mit/ohne Profil änderten sich 7 von 2060 Entscheidungen. Das HUD des Servers zählt unsere Hände mit (eigenes HUD vpip 0,34 / pfr 0,23, gezählt 0,34 / 0,24 über 2697 Hände): gezählte Hände sind eine Untergrenze der HUD-Stichprobe | D1b |
| D1b gebaut (Schalter aus) | `GEGNER_ZAEHLUNG=1`: HUD-Raten bleiben, `hands` = max(bisher, gezählt), Aggression und Reads je Straße aus der Zählung, wenn sie mehr Züge hat; kein Populations-Prior (Befund mem-prior). `GEGNER_SHOWDOWN=1`: zusätzlich `riverBluffShare/-Shown` aus gezeigten River-Einsätzen (Luft = Equity < 0,4), der Kern liest das Feld jetzt vom Draht. Specs: profil 21, zaehler 18, gegner 15, zaehlbuch 7 grün | D1b |
+1
View File
@@ -33,6 +33,7 @@ SCHALTER_DATEI = os.path.join(BASE, "..", "betrieb", "kern_schalter.txt")
# GEGNER_ZAEHLUNG=1 ist kein Kern-Schalter, sondern einer des Laeufers (betrieb/runner.py): die gezaehlten
# Reads je Gegner gehen in die Profile. Er steht hier, damit er in der Arm-Marke jeder Hand steht.
BEKANNTE_SCHALTER = ("MDF_UNREAD", "RAISE_DRAWS", "RAISE_PRIOR", "TURN_SPIEL", "GRUNDSTRATEGIE",
"SOLVER_RIVER", "SOLVER_TURN", "SOLVER_FLOP",
"GEGNER_ZAEHLUNG", "GEGNER_SHOWDOWN", "GEGNER_RANGE")
# Pfade gehoeren nicht in die Arm-Marke.
OHNE_MARKE = ("GRUNDSTRATEGIE",)
+691
View File
@@ -0,0 +1,691 @@
#!/usr/bin/env python3
"""Engine-Röntgen: was hat in diesem Live-Lauf wirklich entschieden - und wirkt der Gegner-Read?
Je Lauf (Läufer-PID, aus dem Schatten-Log) in klaren Zahlen:
1. Ergebnis: Hände, netto BB, bb/100 mit 95-%-Intervall, dasselbe je A/B-Arm (`arm`).
2. Wer entschied: Anteil je Street, aus dem Grund-Text des Zugs (`grund`):
Preflop-CFR / Range-Regeln, Turn-Solver E3 (`turn game`), Turn-/River-Veto, MDF-Boden,
Enthaltung (`setzt aus`), Postflop-Heuristik (der Rest).
3. Read-Wirkung: jede Anfrage des Laufs (`anfrage` im Schatten-Log) geht zweimal durch den Live-Kern -
einmal wie gespielt, einmal ohne `profile` bei allen Gegnern. Gezählt wird je Street, wie viele
Entscheidungen sich ändern (Aktion; Größe getrennt). Das zeigt, ob Ausbeutung überhaupt greift.
4. Read-Stichprobe: wie viele Hände stehen hinter den Gegnerprofilen (`hands`).
5. Läufer-Gesundheit: Klicks, veraltete/verworfene Züge, kleinste Restuhr, abgelaufene Uhren.
Quellen (alle unter --wurzel, Vorgabe: dieser Baum oder ROENTGEN_WURZEL):
archiv/lauf/zuege.jsonl, archiv/lauf/haende.jsonl, betrieb/scratch/shadow*.jsonl,
betrieb/kern_schalter.txt (Engine-Schalter), target/release/rechner(.exe) (Live-Kern).
Das Nachspielen läuft in EINEM Kernprozess in Priorität Idle, gegen eine KOPIE des Kerns
(`archiv/roentgen/kern/pokerbench-roentgen-nachspiel.exe`) - der Live-Kern wird nie gesperrt oder
gebaut. Antworten werden je Anfrage zwischengespeichert (archiv/roentgen/cache/), ein zweiter Blick
auf denselben Lauf spielt nur Neues nach.
python3 lesen/roentgen.py letzter Lauf
python3 lesen/roentgen.py --start "2026-11-14 18:57"
python3 lesen/roentgen.py --pid 43432 --json
python3 lesen/roentgen.py --liste alle Läufe im Schatten-Log
python3 lesen/roentgen.py --ohne-nachspiel ohne Read-Wirkung (schnell)
Spezifikation: tests/roentgen_spec.py. Reine Funktionen bis auf das Laden und `kern_aufruf`.
"""
import argparse
import ast
import calendar
import collections
import glob
import hashlib
import json
import os
import shutil
import subprocess
import sys
import time
_HIER = os.path.dirname(os.path.abspath(__file__))
if _HIER not in sys.path:
sys.path.insert(0, _HIER)
import liveabgleich # noqa: E402 bb_pro_100: dieselbe Winrate-Rechnung wie das A/B
BAUM = os.path.dirname(_HIER)
STREETS = ("PREFLOP", "FLOP", "TURN", "RIVER")
# Wer entschied - Reihenfolge = Spaltenreihenfolge im Bericht.
KLASSEN = ("cfr", "regeln", "e3", "solver", "turn_veto", "river_veto", "mdf", "heuristik", "enthaltung")
KLASSEN_NAME = {
"cfr": "Preflop-CFR", "regeln": "Range-Regeln", "e3": "Turn-Solver E3",
"solver": "Solver überall (A/B/C)",
"turn_veto": "Turn-Veto", "river_veto": "River-Veto", "mdf": "MDF-Boden",
"heuristik": "Heuristik", "enthaltung": "Enthaltung",
}
# Gleiche Liste wie entscheiden/decide.py: nur Messschalter, keine beliebige Umgebung.
BEKANNTE_SCHALTER = ("MDF_UNREAD", "RAISE_DRAWS", "RAISE_PRIOR", "TURN_SPIEL", "GRUNDSTRATEGIE", "SOLVER_RIVER", "SOLVER_TURN", "SOLVER_FLOP")
OHNE_MARKE = ("GRUNDSTRATEGIE",)
IDLE_PRIORITY_CLASS = 0x00000040
KERN_KOPIE = "pokerbench-roentgen-nachspiel" + (".exe" if sys.platform == "win32" else "")
# ---------------------------------------------------------------- Zeit
def _lokal_epoche(s):
"""'2026-11-14 18:57:07' (Ortszeit, wie zuege/shadow) -> Epoche."""
return time.mktime(time.strptime(s[:19], "%Y-%m-%d %H:%M:%S"))
def _utc_epoche(s):
"""'2026-11-14T19:13:02Z' (UTC, wie haende) -> Epoche."""
return calendar.timegm(time.strptime(s[:19], "%Y-%m-%dT%H:%M:%S"))
# ---------------------------------------------------------------- Einlesen
def jsonl(pfad):
"""Zeilen einer jsonl-Datei als dicts; kaputte Zeilen (abgeschnittenes Ende) fallen weg."""
aus = []
try:
with open(pfad, encoding="utf-8", errors="replace") as f:
for zeile in f:
zeile = zeile.strip()
if not zeile:
continue
try:
d = json.loads(zeile)
except ValueError:
continue
if isinstance(d, dict):
aus.append(d)
except OSError:
pass
return aus
def schatten_dateien(wurzel):
"""Alle Schatten-Logs, älteste zuerst (rotierte tragen das Datum im Namen, shadow.jsonl ist das jüngste)."""
ps = glob.glob(os.path.join(wurzel, "betrieb", "scratch", "shadow*.jsonl"))
return sorted(ps, key=lambda p: (os.path.basename(p) == "shadow.jsonl", os.path.basename(p)))
def _als_dict(x):
if isinstance(x, dict):
return x
if isinstance(x, str):
for lade in (json.loads, ast.literal_eval):
try:
d = lade(x)
if isinstance(d, dict):
return d
except (ValueError, SyntaxError):
pass
return None
# ---------------------------------------------------------------- Läufe
def laeufe(schatten):
"""Läufe = Läufer-PIDs im Schatten-Log: [{pid, von, bis, entscheidungen}] nach Startzeit."""
je = collections.OrderedDict()
for e in schatten:
pid, z = e.get("pid"), e.get("zeit")
if pid is None or not isinstance(z, str):
continue
r = je.setdefault(pid, {"pid": pid, "von": z, "bis": z, "entscheidungen": 0})
r["von"] = min(r["von"], z)
r["bis"] = max(r["bis"], z)
if "anfrage" in e:
r["entscheidungen"] += 1
return sorted(je.values(), key=lambda r: r["von"])
def waehle(liste, pid=None, start=None):
"""Den Lauf zur PID; sonst den, der `start` (Ortszeit) enthält oder als erster danach beginnt;
sonst den letzten Lauf mit Entscheidungen. None, wenn nichts passt."""
if pid is not None:
return next((r for r in liste if str(r["pid"]) == str(pid)), None)
mit = [r for r in liste if r["entscheidungen"] > 0]
if start:
for r in mit:
if r["von"] <= start <= r["bis"]:
return r
return next((r for r in mit if r["von"] >= start), None)
return mit[-1] if mit else None
def im_fenster(zeilen, von, bis):
"""zuege-Zeilen (Ortszeit) zwischen von und bis (beide eingeschlossen)."""
return [z for z in zeilen if isinstance(z.get("zeit"), str) and von <= z["zeit"][:19] <= bis]
def haende_im_fenster(haende, von, bis):
"""haende (UTC) im Lauf-Fenster (Ortszeit)."""
a, b = _lokal_epoche(von), _lokal_epoche(bis)
aus = []
for h in haende:
try:
t = _utc_epoche(h["zeit"])
except (KeyError, TypeError, ValueError):
continue
if a <= t <= b:
aus.append(h)
return aus
# ---------------------------------------------------------------- 1. Ergebnis
def ergebnis(haende):
"""{gesamt: bb_pro_100, arme: {arm: bb_pro_100}} aus den Händen des Laufs."""
werte, je_arm = [], collections.defaultdict(list)
for h in haende:
v = liveabgleich.netto_bb(h)
if v is None:
continue
werte.append(v)
je_arm[h.get("arm") or "-"].append(v)
return {"gesamt": liveabgleich.bb_pro_100(werte),
"arme": {a: liveabgleich.bb_pro_100(w) for a, w in sorted(je_arm.items())}}
# ---------------------------------------------------------------- 2. Wer entschied
def klasse(street, grund):
"""Welcher Engine-Teil hat entschieden - aus dem Grund-Text."""
g = grund or ""
if "setzt aus" in g:
return "enthaltung"
if "turn veto" in g:
return "turn_veto"
if "defensive veto" in g:
return "river_veto"
if "river solver" in g or "solver turn" in g or "solver flop" in g:
return "solver"
if "turn game" in g:
return "e3"
if "MDF-Boden" in g:
return "mdf"
if street == "PREFLOP":
return "cfr" if "CFR" in g else "regeln"
return "heuristik"
def wer_entschied(zuege):
"""{street: {zuege, kern_zuege, klassen: {klasse: n}}} in Street-Reihenfolge, plus 'GESAMT'.
kern_zuege = Züge ohne Enthaltung: die Basis der Anteile der Engine-Teile."""
aus = collections.OrderedDict()
for s in STREETS + ("GESAMT",):
aus[s] = {"zuege": 0, "kern_zuege": 0, "klassen": {k: 0 for k in KLASSEN}}
for z in zuege:
s = z.get("street")
if s not in STREETS:
continue
k = klasse(s, z.get("grund"))
for t in (s, "GESAMT"):
aus[t]["zuege"] += 1
aus[t]["kern_zuege"] += k != "enthaltung"
aus[t]["klassen"][k] += 1
return aus
# ---------------------------------------------------------------- 4. Read-Stichprobe
STUFEN = ((0, 0, "ohne Profil"), (1, 9, "1-9"), (10, 29, "10-29"), (30, 99, "30-99"), (100, None, "100+"))
def _stufe(n):
for lo, hi, name in STUFEN:
if n >= lo and (hi is None or n <= hi):
return name
return STUFEN[0][2]
def lesestichprobe(zuege):
"""Wie viele Hände stehen hinter den Reads?
je_gegner: Verteilung über die Gegner (Raum+Sitz, höchster `hands`-Stand im Lauf)
je_zug: Verteilung über alle Gegner-Einträge aller Züge (was die Engine tatsächlich sah)
zuege_mit_read: Züge, in denen mindestens ein Gegner ein Profil trug."""
gegner, je_zug, mit, median_quelle = {}, collections.Counter(), 0, []
for z in zuege:
g = z.get("gegner")
if not isinstance(g, dict) or not g:
continue
mit += 1
for sitz, p in g.items():
n = p.get("hands", 0) if isinstance(p, dict) else 0
n = n if isinstance(n, (int, float)) else 0
je_zug[_stufe(n)] += 1
median_quelle.append(n)
schl = (z.get("raum"), str(sitz))
gegner[schl] = max(gegner.get(schl, 0), n)
je_gegner = collections.Counter(_stufe(n) for n in gegner.values())
ordnung = [s[2] for s in STUFEN]
median_quelle.sort()
return {
"gegner": len(gegner),
"je_gegner": {s: je_gegner.get(s, 0) for s in ordnung},
"je_zug": {s: je_zug.get(s, 0) for s in ordnung},
"zuege_mit_read": mit, "zuege": len(zuege),
"median_hands": median_quelle[len(median_quelle) // 2] if median_quelle else None,
}
# ---------------------------------------------------------------- 5. Gesundheit
def gesundheit(schatten_lauf):
"""Läufer-Gesundheit aus den Schatten-Einträgen EINES Laufs."""
entsch = [e for e in schatten_lauf if "anfrage" in e]
geklickt = [e for e in entsch if e.get("geklickt")]
ohne_echo = [e for e in geklickt if "ohne Echo" in str(e.get("geklickt"))]
hinweise = collections.Counter(str(e.get("hinweis") or "") for e in entsch)
veraltet = sum(n for h, n in hinweise.items() if h.startswith("veraltet"))
ohne_fenster = sum(n for h, n in hinweise.items() if h.startswith("Raum ohne Fenster"))
fristen = [e["frist_rest_s"] for e in entsch if isinstance(e.get("frist_rest_s"), (int, float))]
ereig = collections.Counter(e.get("ereignis") for e in schatten_lauf if e.get("ereignis"))
enthalt = 0
for e in entsch:
a = _als_dict(e.get("anfrage")) or {}
if a.get("legalActions") == [] and a.get("_unklar"):
enthalt += 1
return {
"entscheidungen": len(entsch),
"enthaltungen": enthalt,
"geklickt": len(geklickt),
"ohne_echo": len(ohne_echo),
"nicht_geklickt": len(entsch) - len(geklickt),
"veraltet": veraltet,
"ohne_fenster": ohne_fenster,
"frist_min_s": min(fristen) if fristen else None,
"frist_unter_5s": sum(1 for f in fristen if f < 5.0),
"uhr_abgelaufen": sum(1 for f in fristen if f <= 0.0),
"sitout": ereig.get("sitout", 0),
"kanal_ohne_antwort": sum(1 for e in schatten_lauf
if e.get("ereignis") == "aktion_kanal" and e.get("echo") is False),
}
# ---------------------------------------------------------------- 3. Read-Wirkung
def ohne_read(anfrage):
"""Dieselbe Anfrage, nur ohne `profile` bei allen Gegnern."""
a = dict(anfrage)
a["villains"] = [{k: v for k, v in g.items() if k != "profile"} if isinstance(g, dict) else g
for g in anfrage.get("villains") or []]
return a
def hat_read(anfrage):
return any(isinstance(g, dict) and g.get("profile") for g in anfrage.get("villains") or [])
def nachspielbar(schatten_lauf):
"""[(eintrag, anfrage)] - nur echte Kern-Anfragen (Enthaltungen der Übersetzung gehen nie zum Kern)."""
aus = []
for e in schatten_lauf:
if "anfrage" not in e:
continue
a = _als_dict(e["anfrage"])
if not a or (a.get("legalActions") == [] and a.get("_unklar")):
continue
aus.append((e, a))
return aus
def _schluessel(anfrage, env):
roh = json.dumps(anfrage, sort_keys=True, ensure_ascii=False) + "|" + json.dumps(env, sort_keys=True)
return hashlib.sha1(roh.encode("utf-8")).hexdigest()
def _gleiche_groesse(a, b):
if a is None or b is None:
return a is None and b is None
try:
return abs(float(a) - float(b)) < 1e-6
except (TypeError, ValueError):
return a == b
def _zug_text(antwort):
g = antwort.get("size")
return f"{antwort.get('action')} {g:.3g}" if isinstance(g, (int, float)) else str(antwort.get("action"))
def lese_wirkung(paare, kern, envs=None, cache=None, beispiele=12):
"""Spielt jede Anfrage zweimal durch `kern(anfragen, env) -> antworten`: wie gespielt und ohne Read.
paare: [(schatten_eintrag, anfrage)]; envs: je Paar die Kern-Umgebung (Vorgabe {}).
cache: dict schluessel -> antwort (wird ergänzt), damit ein Lauf nur einmal gerechnet wird.
Liefert je Street: entscheidungen, mit_read, aktion_anders, groesse_anders, treu (Nachspiel ==
live geklickte Kern-Antwort), plus Beispiele der geänderten Züge."""
cache = {} if cache is None else cache
envs = envs or [{}] * len(paare)
# Fehlende Antworten je Umgebung gebündelt rechnen (ein Kernprozess je Umgebung und Durchgang).
offen = collections.OrderedDict()
schl = []
for (e, a), env in zip(paare, envs):
k_mit, k_ohne = _schluessel(a, env), _schluessel(ohne_read(a), env)
schl.append((k_mit, k_ohne))
for k, anf in ((k_mit, a), (k_ohne, ohne_read(a))):
if k not in cache:
envk = json.dumps(env, sort_keys=True)
offen.setdefault(envk, collections.OrderedDict())[k] = anf
for envk, auftraege in offen.items():
antworten = kern(list(auftraege.values()), json.loads(envk))
if len(antworten) != len(auftraege):
raise RuntimeError(f"Kern gab {len(antworten)} Antworten auf {len(auftraege)} Anfragen")
for k, ant in zip(auftraege.keys(), antworten):
cache[k] = ant
aus = collections.OrderedDict()
for s in STREETS + ("GESAMT",):
aus[s] = {"entscheidungen": 0, "mit_read": 0, "aktion_anders": 0, "groesse_anders": 0, "treu": 0}
bsp = []
for (e, a), (k_mit, k_ohne) in zip(paare, schl):
s = a.get("street")
if s not in STREETS:
continue
mit, ohne = cache[k_mit] or {}, cache[k_ohne] or {}
live = _als_dict(e.get("antwort")) or {}
akt = mit.get("action") != ohne.get("action")
gr = not akt and not _gleiche_groesse(mit.get("size"), ohne.get("size"))
treu = live.get("action") == mit.get("action")
for t in (s, "GESAMT"):
r = aus[t]
r["entscheidungen"] += 1
r["mit_read"] += hat_read(a)
r["aktion_anders"] += akt
r["groesse_anders"] += gr
r["treu"] += treu
if akt and len(bsp) < beispiele:
bsp.append({"zeit": e.get("zeit"), "raum": e.get("raum"), "street": s,
"mit": _zug_text(mit), "ohne": _zug_text(ohne),
"grund_mit": mit.get("reason"), "grund_ohne": ohne.get("reason")})
return {"streets": aus, "beispiele": bsp}
# ---------------------------------------------------------------- Kern
def lies_schalter(pfad):
"""betrieb/kern_schalter.txt -> {K: V} (nur bekannte Schalter), wie entscheiden/decide.py."""
schalter = {}
try:
with open(pfad, encoding="utf-8") as f:
for zeile in f:
zeile = zeile.split("#", 1)[0].strip()
if "=" not in zeile:
continue
k, v = (t.strip() for t in zeile.split("=", 1))
if k in BEKANNTE_SCHALTER and v:
schalter[k] = v
except OSError:
pass
return schalter
def env_fuer_arm(arm, datei_schalter):
"""Kern-Umgebung, mit der ein Arm gespielt wurde. Ein Arm 'schalter:K=V,...' sagt genau, welche
Schalter galten (die Datei kann sich seither geändert haben); Pfade (GRUNDSTRATEGIE) stehen nie in
der Marke und kommen aus der Datei. Ohne Schalter-Marke gilt die Datei."""
if isinstance(arm, str) and arm.startswith("schalter:"):
env = {}
for teil in arm[len("schalter:"):].split(","):
if "=" in teil:
k, v = (t.strip() for t in teil.split("=", 1))
if k in BEKANNTE_SCHALTER:
env[k] = v
for k in OHNE_MARKE:
if k in datei_schalter:
env[k] = datei_schalter[k]
return env
return dict(datei_schalter)
def arm_je_zug(zuege):
"""(raum, hand, street) -> arm aus den zuege-Zeilen."""
return {(z.get("raum"), str(z.get("hand")), z.get("street")): z.get("arm") for z in zuege}
def kern_kopie(quelle, ziel_ordner):
"""Kopiert den Live-Kern nach ziel_ordner/pokerbench-roentgen-nachspiel(.exe), wenn er sich
geändert hat - so sperrt das Nachspielen nie das Live-Binary (Windows) und baut nichts."""
os.makedirs(ziel_ordner, exist_ok=True)
ziel = os.path.join(ziel_ordner, KERN_KOPIE)
q = os.stat(quelle)
try:
z = os.stat(ziel)
if z.st_size == q.st_size and abs(z.st_mtime - q.st_mtime) < 1:
return ziel
except OSError:
pass
shutil.copy2(quelle, ziel)
return ziel
def kern_aufruf(binary, timeout_je=5.0):
"""kern(anfragen, env) -> antworten: ein Prozess je Bündel, Priorität Idle."""
def kern(anfragen, env):
if not anfragen:
return []
umgebung = {k: v for k, v in os.environ.items() if k not in BEKANNTE_SCHALTER}
umgebung.update(env)
extra = {}
if sys.platform == "win32":
extra["creationflags"] = IDLE_PRIORITY_CLASS
else:
extra["preexec_fn"] = lambda: os.nice(19)
r = subprocess.run([binary], input="\n".join(json.dumps(a) for a in anfragen) + "\n",
capture_output=True, text=True, encoding="utf-8", env=umgebung,
timeout=60 + timeout_je * len(anfragen), **extra)
if r.returncode != 0:
raise RuntimeError(f"der Kern scheiterte: {r.stderr.strip()[:300]}")
aus = []
for zeile in r.stdout.split("\n"):
if not zeile.strip():
continue
try:
aus.append(json.loads(zeile))
except ValueError:
aus.append({"action": "UNLESBAR"})
return aus
return kern
def kern_pfad(wurzel):
return os.path.join(wurzel, "target", "release", "rechner.exe" if sys.platform == "win32" else "rechner")
# ---------------------------------------------------------------- Bericht
def cache_pfad(cache_ordner, pid, kern_id=""):
"""Ein Cache je Lauf und Kern-Stand: ein neu gebauter Kern rechnet neu."""
return os.path.join(cache_ordner, f"nachspiel-{pid}{'-' + kern_id if kern_id else ''}.json")
def _cache_laden(pfad):
try:
with open(pfad, encoding="utf-8") as f:
d = json.load(f)
return d if isinstance(d, dict) else {}
except (OSError, ValueError):
return {}
def _cache_schreiben(pfad, d):
os.makedirs(os.path.dirname(pfad), exist_ok=True)
tmp = pfad + ".tmp"
with open(tmp, "w", encoding="utf-8") as f:
json.dump(d, f, ensure_ascii=False)
os.replace(tmp, pfad)
def daten(wurzel):
"""Alles, was der Bericht von der Platte braucht."""
lauf = os.path.join(wurzel, "archiv", "lauf")
schatten = []
for p in schatten_dateien(wurzel):
schatten.extend(jsonl(p))
return {"zuege": jsonl(os.path.join(lauf, "zuege.jsonl")),
"haende": jsonl(os.path.join(lauf, "haende.jsonl")),
"schatten": schatten}
def bericht(d, pid=None, start=None, bis=None, kern=None, kern_info=None, datei_schalter=None,
cache=None):
"""Der ganze Bericht als dict. `kern` None = ohne Read-Wirkung (kein Nachspielen)."""
liste = laeufe(d["schatten"])
lauf = waehle(liste, pid=pid, start=start)
if lauf is None:
if not start:
return {"fehler": "kein Lauf im Schatten-Log gefunden", "laeufe": liste}
# Ohne Schatten-Log: nur das Zeitfenster aus zuege (keine Gesundheit, kein Nachspiel).
lauf = {"pid": None, "von": start, "bis": bis or "9999", "entscheidungen": 0}
von, ende = lauf["von"], min(lauf["bis"], bis) if bis else lauf["bis"]
schatten_lauf = [e for e in d["schatten"] if e.get("pid") == lauf["pid"]
and isinstance(e.get("zeit"), str) and von <= e["zeit"] <= ende]
zuege = im_fenster(d["zuege"], von, ende)
haende = haende_im_fenster(d["haende"], von, ende if ende != "9999" else "9999-12-31 23:59:59")
aus = {
"lauf": {"pid": lauf["pid"], "von": von, "bis": ende},
"ergebnis": ergebnis(haende),
"wer": wer_entschied(zuege),
"stichprobe": lesestichprobe(zuege),
"gesundheit": gesundheit(schatten_lauf),
"wirkung": None,
}
if kern is not None:
paare = nachspielbar(schatten_lauf)
arme = arm_je_zug(zuege)
haupt = collections.Counter(z.get("arm") for z in zuege).most_common(1)
haupt = haupt[0][0] if haupt else None
envs = []
for e, a in paare:
teile = str(e.get("zug") or "").split("|")
arm = arme.get((e.get("raum"), teile[1] if len(teile) > 1 else None, a.get("street")), haupt)
envs.append(env_fuer_arm(arm, datei_schalter or {}))
aus["wirkung"] = lese_wirkung(paare, kern, envs, cache)
aus["wirkung"]["kern"] = kern_info
aus["wirkung"]["umgebungen"] = sorted({json.dumps(x, sort_keys=True) for x in envs})
return aus
def rechnen(wurzel, pid=None, start=None, bis=None, nachspiel=True, cache_ordner=None, kern_quelle=None):
"""Bericht mit Platte: liest, kopiert den Kern, spielt nach (mit Plattencache)."""
d = daten(wurzel)
if not nachspiel:
return bericht(d, pid, start, bis)
cache_ordner = cache_ordner or os.environ.get("ROENTGEN_CACHE") or os.path.join(BAUM, "archiv", "roentgen")
quelle = kern_quelle or kern_pfad(wurzel)
if not os.path.exists(quelle):
r = bericht(d, pid, start, bis)
r["wirkung"] = {"fehler": f"kein Kern unter {quelle}"}
return r
binary = kern_kopie(quelle, os.path.join(cache_ordner, "kern"))
info = {"quelle": quelle, "gebaut": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(os.path.getmtime(quelle)))}
schalter = lies_schalter(os.path.join(wurzel, "betrieb", "kern_schalter.txt"))
vorab = waehle(laeufe(d["schatten"]), pid=pid, start=start)
st = os.stat(quelle)
kern_id = hashlib.sha1(f"{st.st_size}|{int(st.st_mtime)}".encode()).hexdigest()[:8]
cpfad = cache_pfad(os.path.join(cache_ordner, "cache"), vorab["pid"] if vorab else "fenster", kern_id)
cache = _cache_laden(cpfad)
vorher = len(cache)
r = bericht(d, pid, start, bis, kern_aufruf(binary), info, schalter, cache)
if len(cache) != vorher:
_cache_schreiben(cpfad, cache)
return r
# ---------------------------------------------------------------- Text
def _pz(n, gesamt):
return f"{100.0 * n / gesamt:5.1f}%" if gesamt else " -"
def _bb(b):
if not b or b["n"] == 0:
return "keine Hände"
s = f"{b['n']} Hände, netto {b['netto_bb']:+.1f} BB, {b['bb100']:+.1f} bb/100"
if b["halb95"] is not None:
s += f" (95 %: {b['tief']:+.0f} bis {b['hoch']:+.0f})"
return s
def text(r):
if "fehler" in r:
return r["fehler"]
L = r["lauf"]
z = [f"ENGINE-RÖNTGEN Lauf pid {L['pid']} {L['von']} bis {L['bis']}", ""]
z.append("1. ERGEBNIS")
z.append(" gesamt: " + _bb(r["ergebnis"]["gesamt"]))
for arm, b in r["ergebnis"]["arme"].items():
z.append(f" Arm {arm}: " + _bb(b))
z.append("")
z.append("2. WER ENTSCHIED (Anteil an den Kern-Zügen je Street; Enthaltung: Anteil an allen Zügen)")
kopf = f" {'Street':<8}{'Züge':>6}" + "".join(f"{KLASSEN_NAME[k]:>16}" for k in KLASSEN)
z.append(kopf)
for s, w in r["wer"].items():
n = w["zuege"]
zeile = f" {s:<8}{n:>6}" + "".join(
f"{(str(w['klassen'][k]) + ' ' + _pz(w['klassen'][k], n if k == 'enthaltung' else w['kern_zuege']).strip()) if w['klassen'][k] else '-':>16}"
for k in KLASSEN)
z.append(zeile)
z.append("")
z.append("3. READ-WIRKUNG (jede Anfrage nochmal durch den Kern, einmal ohne Gegnerprofile)")
w = r.get("wirkung")
if not w:
z.append(" nicht gerechnet (--ohne-nachspiel, oder das Nachspielen läuft noch)")
elif "fehler" in w:
z.append(" " + w["fehler"])
else:
z.append(f" {'Street':<8}{'Entsch.':>8}{'mit Read':>10}{'Aktion anders':>16}{'nur Größe anders':>18}{'Nachspiel=live':>16}")
for s, x in w["streets"].items():
n = x["entscheidungen"]
z.append(f" {s:<8}{n:>8}{x['mit_read']:>10}{(str(x['aktion_anders']) + ' ' + _pz(x['aktion_anders'], n).strip()):>16}"
f"{(str(x['groesse_anders']) + ' ' + _pz(x['groesse_anders'], n).strip()):>18}{_pz(x['treu'], n):>16}")
g = w["streets"]["GESAMT"]
z.append(f" => der Gegner-Read ändert {g['aktion_anders']} von {g['entscheidungen']} Entscheidungen "
f"({_pz(g['aktion_anders'], g['entscheidungen']).strip()}).")
if w.get("kern"):
z.append(f" Kern: {w['kern']['quelle']} (gebaut {w['kern']['gebaut']}); Schalter: "
+ "; ".join(w.get("umgebungen") or []))
for b in w["beispiele"]:
z.append(f" - {b['zeit']} {b['street']}: mit Read {b['mit']}, ohne {b['ohne']} [{(b['grund_mit'] or '')[:70]}]")
z.append("")
st = r["stichprobe"]
z.append("4. READ-STICHPROBE (Hände hinter den Gegnerprofilen)")
z.append(f" Züge mit Profil: {st['zuege_mit_read']} von {st['zuege']}; Median hands je Gegner-Eintrag: {st['median_hands']}")
z.append(f" je Gegner ({st['gegner']}): " + " ".join(f"{k}: {v}" for k, v in st["je_gegner"].items()))
z.append(" je Gegner-Eintrag im Zug: " + " ".join(f"{k}: {v}" for k, v in st["je_zug"].items()))
z.append("")
g = r["gesundheit"]
z.append("5. LÄUFER")
z.append(f" Entscheidungen {g['entscheidungen']} (davon Enthaltungen {g['enthaltungen']}), geklickt {g['geklickt']}"
f" (ohne Echo {g['ohne_echo']}), nicht geklickt {g['nicht_geklickt']}")
z.append(f" veraltet/verworfen {g['veraltet']}, Raum ohne Fenster {g['ohne_fenster']}, Kanal ohne Antwort {g['kanal_ohne_antwort']}")
fm = "-" if g["frist_min_s"] is None else f"{g['frist_min_s']:.1f} s"
z.append(f" kleinste Restuhr {fm}, unter 5 s: {g['frist_unter_5s']}, Uhr abgelaufen: {g['uhr_abgelaufen']}, Sitout-Ereignisse: {g['sitout']}")
return "\n".join(z)
def main(argv=None):
a = argparse.ArgumentParser(description="Engine-Röntgen je Live-Lauf")
a.add_argument("--wurzel", default=os.environ.get("ROENTGEN_WURZEL", BAUM),
help="Baum mit archiv/lauf, betrieb/scratch, target/release (Vorgabe: dieser)")
a.add_argument("--pid", help="Läufer-PID")
a.add_argument("--start", help="Startzeit (Ortszeit) 'JJJJ-MM-TT HH:MM' - der Lauf, der sie enthält")
a.add_argument("--bis", help="nur bis zu dieser Ortszeit")
a.add_argument("--kern", help="Kern-Binary (Vorgabe: <wurzel>/target/release/rechner)")
a.add_argument("--ohne-nachspiel", action="store_true", help="Read-Wirkung nicht rechnen")
a.add_argument("--json", action="store_true")
a.add_argument("--liste", action="store_true", help="Läufe im Schatten-Log zeigen")
x = a.parse_args(argv)
if x.liste:
for r in laeufe(daten(x.wurzel)["schatten"]):
print(f"pid {r['pid']:>7} {r['von']} bis {r['bis']} {r['entscheidungen']} Entscheidungen")
return 0
r = rechnen(x.wurzel, pid=x.pid, start=x.start, bis=x.bis, nachspiel=not x.ohne_nachspiel,
kern_quelle=x.kern)
if x.json:
print(json.dumps(r, ensure_ascii=False, indent=1, default=str))
else:
sys.stdout.reconfigure(encoding="utf-8", errors="replace") if hasattr(sys.stdout, "reconfigure") else None
print(text(r))
return 0 if "fehler" not in r else 1
if __name__ == "__main__":
sys.exit(main())
+121
View File
@@ -0,0 +1,121 @@
#!/usr/bin/env python3
"""Solver überall: Abdeckung und Zeit auf echten Live-Anfragen.
Jede echte Kern-Anfrage aus den Schatten-Logs (`anfrage`) geht einzeln durch einen Kern mit den
gegebenen Schaltern. Je Street und Spielerzahl wird gezählt, wer entschied (Grund-Text, Klassen wie
`lesen/roentgen.py`), und die Wandzeit je Anfrage gemessen (p50, p99, max).
Der Kern ist eine KOPIE (`pokerbench-solver-abdeckung.exe`), läuft in Priorität Idle, ein Prozess.
python3 lesen/solver_abdeckung.py --kern messung_solver/bin/pokerbench-solver-abdeckung.exe \\
--schatten <live>/betrieb/scratch --env SOLVER_RIVER=1 --env GRUNDSTRATEGIE=<live>/daten \\
--street RIVER
"""
import argparse
import collections
import glob
import json
import os
import subprocess
import sys
import time
_HIER = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, _HIER)
import roentgen # noqa: E402 klasse(), _als_dict()
IDLE = 0x00000040
def anfragen(ordner, streets):
"""Eindeutige echte Anfragen (Reihenfolge der Logs)."""
gesehen, aus = set(), []
for pfad in sorted(glob.glob(os.path.join(ordner, "shadow*.jsonl"))):
with open(pfad, encoding="utf-8", errors="replace") as f:
for zeile in f:
if '"anfrage"' not in zeile:
continue
try:
e = json.loads(zeile)
except ValueError:
continue
a = roentgen._als_dict(e.get("anfrage"))
if not a or (a.get("legalActions") == [] and a.get("_unklar")):
continue
if streets and str(a.get("street", "")).upper() not in streets:
continue
k = json.dumps(a, sort_keys=True)
if k in gesehen:
continue
gesehen.add(k)
aus.append(a)
return aus
def spieler(a):
return sum(1 for v in a.get("villains") or [] if isinstance(v, dict) and not v.get("folded"))
def quantil(xs, q):
if not xs:
return 0.0
xs = sorted(xs)
return xs[min(len(xs) - 1, int(q * len(xs)))]
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--kern", required=True)
ap.add_argument("--schatten", required=True)
ap.add_argument("--env", action="append", default=[])
ap.add_argument("--street", action="append", default=[])
ap.add_argument("--json", help="Ergebnis auch als JSON hierhin")
args = ap.parse_args()
env = {k: v for k, v in os.environ.items() if k not in roentgen.BEKANNTE_SCHALTER}
for kv in args.env:
k, v = kv.split("=", 1)
env[k] = v
liste = anfragen(args.schatten, {s.upper() for s in args.street})
extra = {"creationflags": IDLE} if sys.platform == "win32" else {}
p = subprocess.Popen([args.kern], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True,
encoding="utf-8", env=env, bufsize=1, **extra)
zaehl = collections.defaultdict(collections.Counter)
zeiten = collections.defaultdict(list)
for a in liste:
t0 = time.perf_counter()
p.stdin.write(json.dumps(a) + "\n")
p.stdin.flush()
antwort = p.stdout.readline()
ms = (time.perf_counter() - t0) * 1e3
try:
d = json.loads(antwort)
except ValueError:
d = {}
st = str(a.get("street", "")).upper()
n = spieler(a)
k = roentgen.klasse(st, d.get("reason") or d.get("grund") or "")
zaehl[(st, n)][k] += 1
zeiten[(st, n, k)].append(ms)
zeiten[(st, "alle")].append(ms)
p.stdin.close()
p.wait()
ergebnis = {}
print(f"{len(liste)} eindeutige Anfragen, Schalter {args.env}")
for (st, n), c in sorted(zaehl.items()):
tot = sum(c.values())
s = c.get("solver", 0)
zs = zeiten.get((st, n, "solver"), [])
print(f"{st:6} {n}-Gegner: {tot:4} Solver {s:4} ({100 * s / tot:5.1f} %) "
f"Zeit Solver p50 {quantil(zs, .5):6.0f} p99 {quantil(zs, .99):6.0f} max {max(zs or [0]):6.0f} ms "
+ " ".join(f"{k}={v}" for k, v in c.most_common()))
ergebnis[f"{st}/{n}"] = {"anfragen": tot, "solver": s, "klassen": dict(c),
"p50_ms": quantil(zs, .5), "p99_ms": quantil(zs, .99), "max_ms": max(zs or [0])}
for (st, alle), zs in sorted((k, v) for k, v in zeiten.items() if k[1] == "alle"):
print(f"{st:6} alle Anfragen: p50 {quantil(zs, .5):.0f} p99 {quantil(zs, .99):.0f} max {max(zs):.0f} ms")
if args.json:
with open(args.json, "w", encoding="utf-8") as f:
json.dump(ergebnis, f, indent=1)
if __name__ == "__main__":
main()
+7
View File
@@ -0,0 +1,7 @@
bin/
logs/
pilot/
STARTER.pid
arme/
starter.log
*.err
+44
View File
@@ -0,0 +1,44 @@
{
"TURN/1": {
"anfragen": 478,
"solver": 427,
"klassen": {
"solver": 427,
"e3": 43,
"heuristik": 8
},
"p50_ms": 2045.4059000039706,
"p99_ms": 3780.8470000018133,
"max_ms": 4345.02930000599
},
"TURN/2": {
"anfragen": 88,
"solver": 0,
"klassen": {
"heuristik": 88
},
"p50_ms": 0.0,
"p99_ms": 0.0,
"max_ms": 0
},
"TURN/3": {
"anfragen": 7,
"solver": 0,
"klassen": {
"heuristik": 7
},
"p50_ms": 0.0,
"p99_ms": 0.0,
"max_ms": 0
},
"TURN/4": {
"anfragen": 2,
"solver": 0,
"klassen": {
"heuristik": 2
},
"p50_ms": 0.0,
"p99_ms": 0.0,
"max_ms": 0
}
}
+6
View File
@@ -0,0 +1,6 @@
575 eindeutige Anfragen, Schalter ['SOLVER_RIVER=1', 'SOLVER_TURN=1', 'GRUNDSTRATEGIE=D:\\Projects\\pokerfreak\\.claude\\worktrees\\engine-lecks-angreifen-de7b88\\daten', 'MDF_UNREAD=0', 'TURN_SPIEL=grund']
TURN 1-Gegner: 478 Solver 427 ( 89.3 %) Zeit Solver p50 2045 p99 3781 max 4345 ms solver=427 e3=43 heuristik=8
TURN 2-Gegner: 88 Solver 0 ( 0.0 %) Zeit Solver p50 0 p99 0 max 0 ms heuristik=88
TURN 3-Gegner: 7 Solver 0 ( 0.0 %) Zeit Solver p50 0 p99 0 max 0 ms heuristik=7
TURN 4-Gegner: 2 Solver 0 ( 0.0 %) Zeit Solver p50 0 p99 0 max 0 ms heuristik=2
TURN alle Anfragen: p50 1191 p99 3753 max 4345 ms
@@ -0,0 +1,32 @@
# Solver ueberall: die zwei Stufe-A-LBR-Arme ausserhalb der Engine-Warteschlange, auf den 8 Threads,
# die der Engine-Starter (je_lauf=9) nicht nutzt. GRENZE.txt der Engine-Warteschlange steht derweil
# auf threads=20 (Summe 28). ANHALTEN: zuerst diesen Starter (STARTER.pid), dann pokerbench-solver-lbr.
# Am Ende setzt er GRENZE.txt wieder auf threads=28.
$ErrorActionPreference = 'Continue'
$D = Split-Path -Parent $MyInvocation.MyCommand.Path
(Get-Process -Id $PID).PriorityClass = 'Idle'
$PID | Set-Content "$D\STARTER.pid"
$G = 'D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\daten'
$grenze = 'D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\GRENZE.txt'
New-Item -ItemType Directory -Force "$D\lbr", "$D\logs" | Out-Null
$arme = @(
@{ id = 'basis'; env = @{} },
@{ id = 'a'; env = @{ SOLVER_RIVER = '1' } }
)
$laeufe = @()
foreach ($a in $arme) {
$env:POKERBENCH_THREADS = '4'; $env:MDF_UNREAD = '0'; $env:TURN_SPIEL = 'grund'; $env:GRUNDSTRATEGIE = $G
foreach ($k in $a.env.Keys) { Set-Item "Env:$k" $a.env[$k] }
$p = Start-Process -FilePath "$D\bin\pokerbench-solver-lbr.exe" -ArgumentList "$D\lbr\$($a.id).txt 2000" -WorkingDirectory $D -NoNewWindow -PassThru `
-RedirectStandardOutput "$D\logs\solver-lbr-$($a.id).log" -RedirectStandardError "$D\logs\solver-lbr-$($a.id).err"
try { $p.PriorityClass = 'Idle' } catch {}
foreach ($k in $a.env.Keys) { Remove-Item "Env:$k" -ErrorAction SilentlyContinue }
$laeufe += $p
"solver-lbr-$($a.id) gestartet pid=$($p.Id) $(Get-Date -Format s)" | Add-Content "$D\starter.log"
}
$laeufe | Wait-Process
"fertig $(Get-Date -Format s)" | Add-Content "$D\starter.log"
$t = Get-Content $grenze -Raw
$t = $t -replace '(?m)^threads=20\s*$', 'threads=28'
Set-Content -Path $grenze -Value $t -NoNewline
Remove-Item "$D\STARTER.pid" -ErrorAction SilentlyContinue
+10
View File
@@ -0,0 +1,10 @@
# Solver ueberall (Stufen A/B/C, Branch claude/solver-ueberall-44ecc1): gepaarte Leiter (Regressionstest) und LBR (Richter), dasselbe Binary fuer Basis und Arme
solver-leiter-basis|D:\Projects\pokerfreak\.claude\worktrees\solver-ueberall-44ecc1\messung_solver\bin\pokerbench-solver-leiter.exe|D:\Projects\pokerfreak\.claude\worktrees\solver-ueberall-44ecc1\messung_solver\arme\leiter-basis 500 1000 2 wert-sizer,polar,umgekehrt,textur-cbet,position,tanker,balanciert,cbet-folder,3bet-folder,check-raiser,gto,station,fish,reg,nit,maniac,nemesis-1,nemesis-2,nemesis-3,micro-passiv,micro-passiv@blind|MDF_UNREAD=0|D:\Projects\pokerfreak\.claude\worktrees\solver-ueberall-44ecc1
solver-leiter-a|D:\Projects\pokerfreak\.claude\worktrees\solver-ueberall-44ecc1\messung_solver\bin\pokerbench-solver-leiter.exe|D:\Projects\pokerfreak\.claude\worktrees\solver-ueberall-44ecc1\messung_solver\arme\leiter-a 500 1000 2 wert-sizer,polar,umgekehrt,textur-cbet,position,tanker,balanciert,cbet-folder,3bet-folder,check-raiser,gto,station,fish,reg,nit,maniac,nemesis-1,nemesis-2,nemesis-3,micro-passiv,micro-passiv@blind|MDF_UNREAD=0;SOLVER_RIVER=1|D:\Projects\pokerfreak\.claude\worktrees\solver-ueberall-44ecc1
solver-leiter-ab|D:\Projects\pokerfreak\.claude\worktrees\solver-ueberall-44ecc1\messung_solver\bin\pokerbench-solver-leiter.exe|D:\Projects\pokerfreak\.claude\worktrees\solver-ueberall-44ecc1\messung_solver\arme\leiter-ab 500 1000 2 wert-sizer,polar,umgekehrt,textur-cbet,position,tanker,balanciert,cbet-folder,3bet-folder,check-raiser,gto,station,fish,reg,nit,maniac,nemesis-1,nemesis-2,nemesis-3,micro-passiv,micro-passiv@blind|MDF_UNREAD=0;SOLVER_RIVER=1;SOLVER_TURN=1|D:\Projects\pokerfreak\.claude\worktrees\solver-ueberall-44ecc1
solver-leiter-abc|D:\Projects\pokerfreak\.claude\worktrees\solver-ueberall-44ecc1\messung_solver\bin\pokerbench-solver-leiter.exe|D:\Projects\pokerfreak\.claude\worktrees\solver-ueberall-44ecc1\messung_solver\arme\leiter-abc 500 1000 2 wert-sizer,polar,umgekehrt,textur-cbet,position,tanker,balanciert,cbet-folder,3bet-folder,check-raiser,gto,station,fish,reg,nit,maniac,nemesis-1,nemesis-2,nemesis-3,micro-passiv,micro-passiv@blind|MDF_UNREAD=0;SOLVER_RIVER=1;SOLVER_TURN=1;SOLVER_FLOP=1|D:\Projects\pokerfreak\.claude\worktrees\solver-ueberall-44ecc1
solver-lbr-basis|D:\Projects\pokerfreak\.claude\worktrees\solver-ueberall-44ecc1\messung_solver\bin\pokerbench-solver-lbr.exe|D:\Projects\pokerfreak\.claude\worktrees\solver-ueberall-44ecc1\messung_solver\lbr$n.txt 2000|MDF_UNREAD=0;TURN_SPIEL=grund;GRUNDSTRATEGIE=D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\daten|D:\Projects\pokerfreak\.claude\worktrees\solver-ueberall-44ecc1
solver-lbr-a|D:\Projects\pokerfreak\.claude\worktrees\solver-ueberall-44ecc1\messung_solver\bin\pokerbench-solver-lbr.exe|D:\Projects\pokerfreak\.claude\worktrees\solver-ueberall-44ecc1\messung_solver\lbr$n.txt 2000|MDF_UNREAD=0;TURN_SPIEL=grund;GRUNDSTRATEGIE=D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\daten;SOLVER_RIVER=1|D:\Projects\pokerfreak\.claude\worktrees\solver-ueberall-44ecc1
solver-lbr-a-modell|D:\Projects\pokerfreak\.claude\worktrees\solver-ueberall-44ecc1\messung_solver\bin\pokerbench-solver-lbr.exe|D:\Projects\pokerfreak\.claude\worktrees\solver-ueberall-44ecc1\messung_solver\lbr$n.txt 2000|MDF_UNREAD=0;TURN_SPIEL=grund;GRUNDSTRATEGIE=D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\daten;SOLVER_RIVER=modell|D:\Projects\pokerfreak\.claude\worktrees\solver-ueberall-44ecc1
solver-lbr-ab|D:\Projects\pokerfreak\.claude\worktrees\solver-ueberall-44ecc1\messung_solver\bin\pokerbench-solver-lbr.exe|D:\Projects\pokerfreak\.claude\worktrees\solver-ueberall-44ecc1\messung_solver\lbr$n.txt 2000|MDF_UNREAD=0;TURN_SPIEL=grund;GRUNDSTRATEGIE=D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\daten;SOLVER_RIVER=1;SOLVER_TURN=1|D:\Projects\pokerfreak\.claude\worktrees\solver-ueberall-44ecc1
solver-lbr-abc|D:\Projects\pokerfreak\.claude\worktrees\solver-ueberall-44ecc1\messung_solver\bin\pokerbench-solver-lbr.exe|D:\Projects\pokerfreak\.claude\worktrees\solver-ueberall-44ecc1\messung_solver\lbr$n.txt 2000|MDF_UNREAD=0;TURN_SPIEL=grund;GRUNDSTRATEGIE=D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\daten;SOLVER_RIVER=1;SOLVER_TURN=1;SOLVER_FLOP=1|D:\Projects\pokerfreak\.claude\worktrees\solver-ueberall-44ecc1
+131
View File
@@ -0,0 +1,131 @@
"""Engine-Röntgen im Cockpit-Server (lesen/roentgen.py): eine Seite und ein JSON-Endpunkt.
/roentgen Seite: Lauf wählen, Bericht als Tabelle (pollt, solange gerechnet wird)
/api/roentgen?pid=..|start=.. {"status": "rechnet"|"fertig"|"fehler", "text", "bericht", "stand"}
/api/roentgen/laeufe [{pid, von, bis, entscheidungen}]
Das Nachspielen (zweimal jede Anfrage durch den Kern, Priorität Idle) läuft in EINEM Hintergrundfaden,
nie im Anfrage-Faden: die erste Antwort kommt sofort mit dem schnellen Teil (ohne Read-Wirkung),
die Read-Wirkung folgt. Je Lauf zwischengespeichert; ein späterer Blick rechnet nur neue Züge nach
(roentgen.py hält den Plattencache je Anfrage). Datenquelle: ROENTGEN_WURZEL, sonst dieser Baum.
"""
import json
import os
import sys
import threading
import time
from urllib.parse import parse_qs
_w = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
_l = os.path.join(_w, "lesen")
if _l not in sys.path:
sys.path.append(_l)
NEU_NACH_S = 120.0 # ein fertiger Bericht gilt so lange; danach rechnet der nächste Blick nach
_sperre = threading.Lock()
_stand = {} # schluessel -> {"status", "text", "bericht", "stand", "fehler"}
_faden = None
def _wurzel():
import roentgen
return os.environ.get("ROENTGEN_WURZEL") or roentgen.BAUM
def _rechnen(schluessel, pid, start):
import roentgen
try:
schnell = roentgen.rechnen(_wurzel(), pid=pid, start=start, nachspiel=False)
with _sperre:
_stand[schluessel] = {"status": "rechnet", "bericht": schnell, "text": roentgen.text(schnell),
"stand": time.time()}
voll = roentgen.rechnen(_wurzel(), pid=pid, start=start, nachspiel=True)
with _sperre:
_stand[schluessel] = {"status": "fertig", "bericht": voll, "text": roentgen.text(voll),
"stand": time.time()}
except Exception as e: # noqa: BLE001 - die Seite zeigt den Fehler, der Server bleibt stehen
with _sperre:
alt = _stand.get(schluessel) or {}
_stand[schluessel] = {**alt, "status": "fehler", "fehler": f"{type(e).__name__}: {e}",
"stand": time.time()}
def anfordern(pid=None, start=None):
"""Stand für einen Lauf; stößt das Rechnen an, wenn nichts da oder veraltet ist."""
global _faden
schluessel = f"{pid or ''}|{start or ''}"
with _sperre:
st = dict(_stand.get(schluessel) or {})
laeuft = _faden is not None and _faden.is_alive()
alt = not st or (st.get("status") != "rechnet" and time.time() - st.get("stand", 0) > NEU_NACH_S)
if alt and not laeuft:
_faden = threading.Thread(target=_rechnen, args=(schluessel, pid, start), daemon=True,
name="roentgen")
_faden.start()
if not st:
st = {"status": "rechnet", "text": "rechnet ...", "bericht": None, "stand": None}
else:
st["status"] = "rechnet"
elif alt and laeuft and not st:
st = {"status": "wartet", "text": "ein anderer Lauf wird gerade gerechnet ...", "bericht": None}
return st
def laeufe():
import roentgen
return roentgen.laeufe(roentgen.daten(_wurzel())["schatten"])
SEITE = """<!doctype html>
<html lang="de"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Engine-Röntgen</title>
<style>
:root{--bg:#fff;--fg:#1d1d1f;--mut:#6e6e73;--rand:#d2d2d7;--akzent:#0a62c9}
@media (prefers-color-scheme:dark){:root{--bg:#1c1c1e;--fg:#f2f2f7;--mut:#98989d;--rand:#3a3a3c;--akzent:#64a8ff}}
body{margin:0;padding:16px;background:var(--bg);color:var(--fg);font:14px/1.4 -apple-system,Segoe UI,sans-serif}
h1{font-size:18px;margin:0 0 12px}
select,button{font:inherit;padding:4px 8px;background:var(--bg);color:var(--fg);border:1px solid var(--rand);border-radius:6px}
#status{color:var(--mut);margin:8px 0}
pre{font:12px/1.45 ui-monospace,Consolas,monospace;overflow-x:auto;border-top:1px solid var(--rand);padding-top:12px}
</style></head><body>
<h1>Engine-Röntgen</h1>
<label>Lauf <select id="lauf"></select></label> <button id="neu">neu rechnen</button>
<div id="status"></div><pre id="text">lädt ...</pre>
<script>
const $=id=>document.getElementById(id);let uhr=null;
async function laeufe(){
const l=await (await fetch('/api/roentgen/laeufe')).json();
$('lauf').innerHTML=l.filter(r=>r.entscheidungen>0).reverse().map(r=>
`<option value="${r.pid}">pid ${r.pid} · ${r.von} – ${r.bis.slice(11)} · ${r.entscheidungen} Entsch.</option>`).join('');
}
async function holen(){
clearTimeout(uhr);
const pid=$('lauf').value;
try{
const r=await (await fetch('/api/roentgen'+(pid?'?pid='+encodeURIComponent(pid):''))).json();
$('text').textContent=r.text||'';
const t=r.stand?new Date(r.stand*1000).toLocaleTimeString():'';
$('status').textContent=r.status==='fertig'?`fertig (${t})`:r.status==='fehler'?`Fehler: ${r.fehler}`:
r.status==='rechnet'?'Read-Wirkung wird nachgespielt (Kern, Priorität Idle) ...':r.status;
if(r.status==='rechnet'||r.status==='wartet') uhr=setTimeout(holen,3000);
}catch(e){$('status').textContent='Server nicht erreichbar';uhr=setTimeout(holen,5000);}
}
$('lauf').onchange=holen;$('neu').onclick=holen;
laeufe().then(holen);
</script></body></html>"""
def antwort(pfad, query=""):
"""(code, daten, art) für unsere Pfade, sonst None."""
if pfad == "/roentgen":
return 200, SEITE.encode("utf-8"), "text/html; charset=utf-8"
if pfad == "/api/roentgen/laeufe":
return 200, json.dumps(laeufe(), ensure_ascii=False).encode("utf-8"), "application/json; charset=utf-8"
if pfad == "/api/roentgen":
q = parse_qs(query or "")
pid = (q.get("pid") or [None])[0]
start = (q.get("start") or [None])[0]
st = anfordern(pid, start)
return 200, json.dumps(st, ensure_ascii=False, default=str).encode("utf-8"), "application/json; charset=utf-8"
return None
+6
View File
@@ -5,6 +5,7 @@
/api/steuern POST {aktion, raum?} -> sicht/steuern.py, Antwort {"ok","text",...}
/foto/<name>.png Fotos aus sicht/scratch/
/sendung/<name>.html, /api/sendung die Seiten der Sendung fuer OBS (sicht/sendung_seiten.py)
/roentgen, /api/roentgen Engine-Roentgen je Lauf (sicht/roentgen_seite.py, lesen/roentgen.py)
Leitsatz: das Cockpit liest nur. Ein Hintergrundfaden ruft alle ~0.5 s quellen.lesen() und
ansicht.bauen() auf; wirft eines davon (oder fehlt das Modul), geht die leere Ansicht raus. Der
@@ -22,6 +23,7 @@ from urllib.parse import urlparse
HIER = os.path.dirname(os.path.abspath(__file__))
if HIER not in sys.path:
sys.path.insert(0, HIER)
import roentgen_seite
import sendung_seiten
import steuern
import ws
@@ -233,6 +235,10 @@ def _handler(cockpit):
except OSError:
return self._fehler(404, "Bild nicht da")
return self._senden(200, daten, "image/png")
if pfad == "/roentgen" or pfad.startswith("/api/roentgen"):
seite = roentgen_seite.antwort(pfad, urlparse(self.path).query)
if seite:
return self._senden(*seite)
with cockpit.sperre:
teile = dict(cockpit.teile)
seite = sendung_seiten.antwort(pfad, teile) # die Seiten der Sendung fuer OBS
+4
View File
@@ -79,6 +79,10 @@ fn apply_arm() {
// TURN_SPIEL=grund: the turn+river game with both ranges from the blueprint (plan E3,
// `engine::turn_game`), only where the blueprint recognises the spot. Needs GRUNDSTRATEGIE like
// RIVER_DBR=grund. Size/budget: TURN_COMBOS, TURN_CARDS, TURN_ITERS (defaults in `TurnConfig`).
// SOLVER_RIVER=1|modell (stage A, solver everywhere): `engine::river_spieler`.
rechner::engine::river_spieler::set_river_spieler(rechner::engine::river_spieler::from_env());
rechner::engine::turn_game::set_turn_ueberall(rechner::engine::turn_game::turn_ueberall_from_env());
rechner::engine::flop_spieler::set_flop_spieler(rechner::engine::flop_spieler::from_env());
use rechner::engine::turn_game::{set_turn_player, TurnPlayer};
let turn_grund = std::env::var("TURN_SPIEL").as_deref() == Ok("grund");
set_turn_player(if turn_grund { TurnPlayer::Grund } else { TurnPlayer::Off });
+7
View File
@@ -34,6 +34,13 @@ fn main() {
assert!(rechner::blueprint::ranges::grundstrategie().is_some(), "TURN_SPIEL=grund needs GRUNDSTRATEGIE with tables and checkpoint");
}
// SOLVER_RIVER=1|modell (stage A): the river solver plays the engine's heads-up river.
rechner::engine::river_spieler::set_river_spieler(rechner::engine::river_spieler::from_env());
rechner::engine::turn_game::set_turn_ueberall(rechner::engine::turn_game::turn_ueberall_from_env());
rechner::engine::flop_spieler::set_flop_spieler(rechner::engine::flop_spieler::from_env());
if rechner::engine::river_spieler::river_spieler() == rechner::engine::river_spieler::RiverSpieler::An {
assert!(rechner::blueprint::ranges::grundstrategie().is_some(), "SOLVER_RIVER=1 on LBR needs GRUNDSTRATEGIE (else it measures the model path)");
}
let mut fertig = vec![None; haende as usize];
if let Ok(t) = std::fs::read_to_string(&out) {
for z in t.lines() {
+798 -664
View File
File diff suppressed because it is too large Load Diff
+188 -175
View File
@@ -1,175 +1,188 @@
use super::called_equity::called_equity;
use super::from_plan::{from_plan, MIN_CERTAINTY};
use super::passive::cheapest_continue;
use super::postflop::choose_postflop_with;
use super::range_combos::{as_ranges, combos};
use super::range_filter::{range_filter, HandFilter};
use crate::card::Card;
use crate::equity::monte_carlo::estimate;
use crate::equity::query::Query;
use crate::equity::villain_range::VillainRange;
use crate::exploit::adjust::adjust;
use crate::exploit::profile::Profile;
use crate::exploit::range_model::range_spec;
use crate::exploit::thresholds::Thresholds;
use crate::game::{Decision, Spot, Street};
use crate::guard::enforce::enforce;
use crate::icm::lage::Turnierlage;
use crate::icm::risk::{call_premium, jam_depth_gate, jam_pressure, jam_width_factor, width_factor};
use crate::preflop::advise::advise_widened;
use crate::preflop::plan::PreflopPlan;
use crate::read::hand_read::read;
use crate::rng::Rng;
const TRIALS_TWO_CARD: u32 = 3000;
const TRIALS_OMAHA: u32 = 1500;
fn trials(spot: &Spot) -> u32 {
if spot.rules().hole_cards >= 4 {
TRIALS_OMAHA
} else {
TRIALS_TWO_CARD
}
}
/// Postflop: read the hand, model each villain's range, simulate against it and
/// against the hands that would call each raise, choose.
fn postflop(spot: &Spot, thresholds: &Thresholds, raw: &Spot, premium: f64) -> Decision {
let rules = spot.rules();
let hand_read = match read(&rules, &spot.hero_cards, &spot.board) {
Ok(r) => r,
Err(fault) => return Decision::abstain(format!("hand read unavailable: {fault}")),
};
let filters: Vec<HandFilter> = spot
.live_villains()
.map(|v| range_filter(&range_spec(spot, v), rules, spot.variant, &spot.board))
.collect();
if filters.is_empty() {
return cheapest_continue(spot).map_or_else(
|| Decision::abstain("no live opponent and nothing to continue with"),
|choice| Decision::new(choice, 0.5, "no live opponents: cheapest continuing action"),
);
}
let dead: Vec<Card> = spot.hero_cards.iter().chain(&spot.board).copied().collect();
let lists: Vec<_> = filters.iter().map(|f| combos(&rules, f, &dead)).collect();
// Stage A river-subgame solver is NOT wired here. Proven exactly unexploitable (0.0 bb/100) vs a
// correct GTO belief in `sim::exploit_river`, but with a SYMMETRIC prior it plays balanced poker
// against players who must be exploited: wiring it live cost -43 bb/100 GESAMT, concentrated on
// the calling station / fish / maniac (BEFUND-river-solver-balanced-vs-exploitable). It returns
// to the live path only once the belief is opponent-aware (posterior -> range) and trust-gated
// (crown: KL ball around GTO, lambda from read confidence). Until then the heuristic EV line below
// keeps the exploit edge the whole ladder depends on.
let ranges: Vec<VillainRange> = as_ranges(&filters, &lists);
let query = Query {
rules,
hero: &spot.hero_cards,
board: &spot.board,
villains: &ranges,
trials: trials(spot),
};
match estimate(&query, Rng::seeded(spot.seed)) {
Ok((equity, _)) => {
// GTO-Boden UEBER dem Modell, aber unter der Exploit-Range: ein modellgetriebener
// River-Fold einer verteidigungswuerdigen Made-Hand wird zum MDF-Call. `raw` traegt die
// UNGEGATETEN Reads - der Boden darf den Gegner-Bluffanteil defensiv lesen (gegen einen
// bewiesenen Nicht-Bluffer mehr folden), was `read_gate` dem Range-Modell verwehrt.
let base = choose_postflop_with(spot, &equity, &called_equity(spot), thresholds, &hand_read);
let floored = crate::exploit::mdf_floor::floor(raw, hand_read.made, base).with_equity(equity.share);
// Defensive river veto (the belief+trust gearbox, CASH ONLY): a confident read that the
// villain UNDER-bluffs its river bet turns a heuristic call into a fold. This is the one
// place the gearbox is a proven edge — the heuristic over-calls under-bluffed overbets
// (nemesis-3); its OFFENSE (thin value, light calls vs real bluffers) stays untouched,
// because replacing that with a KL-GTO line bled EV on the ladder. Never overrides an
// ICM-driven line (premium > 0): chip-EV must not override a tournament fold/call.
//
// The TURN veto (`turn_subgame::turn_fold_veto`, Stage B) stays OUT of the live path. Two
// measurements now agree it regresses the hardest value-heavy nemesis (nemesis-1, bluff
// 0.068): pooled belief -7.77, per-street-aggression belief -25.93 (worse). The root is NOT
// belief granularity — per-street aggression fixed nemesis-2 but made nemesis-1 worse. It is
// the draw-BLIND turn bucket: the veto folds bluff-catchers whose river equity the
// current-strength ladder undervalues, so a defensive turn fold forfeits realized equity the
// river veto never does (the river is final). Fixing it needs draw-aware turn bucketing or
// the offline/value-function form, not a live fold-veto. The turn solver + per-street belief
// stay as tested primitives. See BEFUND-stage-b-turn-river-solver.md.
if premium <= 0.0 {
// Arm (off by default, RIVER_DBR): the data-biased robust counter-strategy plays the
// heads-up river whenever the read is strong enough (`river_subgame::dbr_decision`).
if let Some(d) = super::river_subgame::dbr_decision(raw) {
return d.with_equity(equity.share);
}
// Arm (off by default, TURN_SPIEL=grund): the turn+river game with ranges from the
// blueprint (`engine::turn_game`); `None` while the switch is off.
if let Some(d) = super::turn_game::turn_game_decision(raw) {
return d.with_equity(equity.share);
}
return super::river_subgame::fold_veto(raw, floored);
}
floored
}
Err(fault) => Decision::abstain(format!("equity unavailable: {fault}")),
}
}
/// Thresholds with the tournament risk premium (`icm::risk`) added: calls need more equity,
/// the preflop width narrows. No premium: unchanged.
fn with_premium(thresholds: Thresholds, premium: f64) -> Thresholds {
if premium <= 0.0 {
return thresholds;
}
Thresholds {
call_margin: thresholds.call_margin + premium,
range_width_scale: thresholds.range_width_scale * width_factor(premium),
..thresholds
}
}
fn think(spot: &Spot, premium: f64, jam_widen: f64, raw: &Spot) -> Decision {
let profiles: Vec<Profile> = spot.live_villains().filter_map(|v| v.profile).collect();
let thresholds = with_premium(adjust(Thresholds::BASE, &profiles), premium);
match spot.street {
Street::Preflop => {
let plan = advise_widened(spot, &thresholds, jam_widen);
// Eine Grenzhand folgt ihrer Seite der Tabelle (Raise bleibt Raise, Call bleibt Call):
// nahe der Grenze ist jede Linie fast gleich viel wert, Aussetzen ist die schlechteste.
let certainty = plan.certainty.max(MIN_CERTAINTY);
from_plan(spot, &PreflopPlan { certainty, ..plan })
}
Street::Flop | Street::Turn | Street::River => postflop(spot, &thresholds, raw, premium),
}
}
/// Full decision for a validated spot (preflop chart or postflop read/equity/EV),
/// always passed through `guard::enforce::enforce`. Die Handkategorie wird nur
/// zur Nachprüfung angehängt.
pub fn decide(spot: &Spot) -> Decision {
decide_with(spot, None)
}
/// `decide` with an optional tournament situation (`icm`). Without one: cash. With one
/// that cannot be priced: ABSTAIN.
pub fn decide_with(spot: &Spot, lage: Option<&Turnierlage>) -> Decision {
// Only act on reads we are proven to beat blind play with (`read_gate`); competent and
// aggressive opponents are played blind until the exploit logic earns them on the ladder.
let gated = super::read_gate::gate_reads(spot);
let raw = spot; // ungated reads, used ONLY by the defensive MDF floor (mdf_floor::floor)
let spot = &gated;
let premium = match lage.map(|l| call_premium(spot, l)) {
None => 0.0,
Some(Some(p)) => p,
Some(None) => return Decision::abstain("tournament situation unusable: no money EV"),
};
// Open-Jam-Weitung an der Bubble (`icm::risk::jam_pressure`): nur bei Turnierlage, sonst neutral.
// Unpricebar -> 1.0 (keine Weitung), nie ein Abbruch - der Riegel liegt bei `premium`/Calls.
// Tiefen-gegated (`jam_depth_gate`): die Weitung ist ein Kurzstack-Hebel; ein tiefer Deckler
// weitet NICHT (sonst oeffnet er Muell aus der Tiefe - gemessen: cover-short -12.5 ICM$/100).
let jam_widen = lage
.and_then(|l| jam_pressure(spot, l))
.map(jam_width_factor)
.map(|w| 1.0 + (w - 1.0) * jam_depth_gate(spot.hero_stack / spot.big_blind))
.unwrap_or(1.0);
let decision = enforce(spot, think(spot, premium, jam_widen, raw));
match crate::hand::showdown::best(spot.rules().hole_usage, &spot.hero_cards, &spot.board) {
Ok(strength) => decision.with_category(strength.category),
Err(_) => decision,
}
}
use super::called_equity::called_equity;
use super::from_plan::{from_plan, MIN_CERTAINTY};
use super::passive::cheapest_continue;
use super::postflop::choose_postflop_with;
use super::range_combos::{as_ranges, combos};
use super::range_filter::{range_filter, HandFilter};
use crate::card::Card;
use crate::equity::monte_carlo::estimate;
use crate::equity::query::Query;
use crate::equity::villain_range::VillainRange;
use crate::exploit::adjust::adjust;
use crate::exploit::profile::Profile;
use crate::exploit::range_model::range_spec;
use crate::exploit::thresholds::Thresholds;
use crate::game::{Decision, Spot, Street};
use crate::guard::enforce::enforce;
use crate::icm::lage::Turnierlage;
use crate::icm::risk::{call_premium, jam_depth_gate, jam_pressure, jam_width_factor, width_factor};
use crate::preflop::advise::advise_widened;
use crate::preflop::plan::PreflopPlan;
use crate::read::hand_read::read;
use crate::rng::Rng;
const TRIALS_TWO_CARD: u32 = 3000;
const TRIALS_OMAHA: u32 = 1500;
fn trials(spot: &Spot) -> u32 {
if spot.rules().hole_cards >= 4 {
TRIALS_OMAHA
} else {
TRIALS_TWO_CARD
}
}
/// Postflop: read the hand, model each villain's range, simulate against it and
/// against the hands that would call each raise, choose.
fn postflop(spot: &Spot, thresholds: &Thresholds, raw: &Spot, premium: f64) -> Decision {
let rules = spot.rules();
let hand_read = match read(&rules, &spot.hero_cards, &spot.board) {
Ok(r) => r,
Err(fault) => return Decision::abstain(format!("hand read unavailable: {fault}")),
};
let filters: Vec<HandFilter> = spot
.live_villains()
.map(|v| range_filter(&range_spec(spot, v), rules, spot.variant, &spot.board))
.collect();
if filters.is_empty() {
return cheapest_continue(spot).map_or_else(
|| Decision::abstain("no live opponent and nothing to continue with"),
|choice| Decision::new(choice, 0.5, "no live opponents: cheapest continuing action"),
);
}
let dead: Vec<Card> = spot.hero_cards.iter().chain(&spot.board).copied().collect();
let lists: Vec<_> = filters.iter().map(|f| combos(&rules, f, &dead)).collect();
// Stage A river-subgame solver is NOT wired here. Proven exactly unexploitable (0.0 bb/100) vs a
// correct GTO belief in `sim::exploit_river`, but with a SYMMETRIC prior it plays balanced poker
// against players who must be exploited: wiring it live cost -43 bb/100 GESAMT, concentrated on
// the calling station / fish / maniac (BEFUND-river-solver-balanced-vs-exploitable). It returns
// to the live path only once the belief is opponent-aware (posterior -> range) and trust-gated
// (crown: KL ball around GTO, lambda from read confidence). Until then the heuristic EV line below
// keeps the exploit edge the whole ladder depends on.
let ranges: Vec<VillainRange> = as_ranges(&filters, &lists);
let query = Query {
rules,
hero: &spot.hero_cards,
board: &spot.board,
villains: &ranges,
trials: trials(spot),
};
match estimate(&query, Rng::seeded(spot.seed)) {
Ok((equity, _)) => {
// GTO-Boden UEBER dem Modell, aber unter der Exploit-Range: ein modellgetriebener
// River-Fold einer verteidigungswuerdigen Made-Hand wird zum MDF-Call. `raw` traegt die
// UNGEGATETEN Reads - der Boden darf den Gegner-Bluffanteil defensiv lesen (gegen einen
// bewiesenen Nicht-Bluffer mehr folden), was `read_gate` dem Range-Modell verwehrt.
let base = choose_postflop_with(spot, &equity, &called_equity(spot), thresholds, &hand_read);
let floored = crate::exploit::mdf_floor::floor(raw, hand_read.made, base).with_equity(equity.share);
// Defensive river veto (the belief+trust gearbox, CASH ONLY): a confident read that the
// villain UNDER-bluffs its river bet turns a heuristic call into a fold. This is the one
// place the gearbox is a proven edge — the heuristic over-calls under-bluffed overbets
// (nemesis-3); its OFFENSE (thin value, light calls vs real bluffers) stays untouched,
// because replacing that with a KL-GTO line bled EV on the ladder. Never overrides an
// ICM-driven line (premium > 0): chip-EV must not override a tournament fold/call.
//
// The TURN veto (`turn_subgame::turn_fold_veto`, Stage B) stays OUT of the live path. Two
// measurements now agree it regresses the hardest value-heavy nemesis (nemesis-1, bluff
// 0.068): pooled belief -7.77, per-street-aggression belief -25.93 (worse). The root is NOT
// belief granularity — per-street aggression fixed nemesis-2 but made nemesis-1 worse. It is
// the draw-BLIND turn bucket: the veto folds bluff-catchers whose river equity the
// current-strength ladder undervalues, so a defensive turn fold forfeits realized equity the
// river veto never does (the river is final). Fixing it needs draw-aware turn bucketing or
// the offline/value-function form, not a live fold-veto. The turn solver + per-street belief
// stay as tested primitives. See BEFUND-stage-b-turn-river-solver.md.
if premium <= 0.0 {
// Arm (off by default, RIVER_DBR): the data-biased robust counter-strategy plays the
// heads-up river whenever the read is strong enough (`river_subgame::dbr_decision`).
if let Some(d) = super::river_subgame::dbr_decision(raw) {
return d.with_equity(equity.share);
}
// Stage A, solver everywhere (off by default, SOLVER_RIVER): the heads-up river decided
// by an equilibrium solve over real combos, ranges from the line (`engine::river_spieler`).
if let Some(d) = super::river_spieler::river_spieler_decision(raw) {
return d.with_equity(equity.share);
}
// Arm (off by default, TURN_SPIEL=grund): the turn+river game with ranges from the
// blueprint (`engine::turn_game`); `None` while the switch is off.
if let Some(d) = super::turn_game::turn_game_decision(raw) {
return d.with_equity(equity.share);
}
// Stage B, solver everywhere (off by default, SOLVER_TURN): every heads-up turn.
if let Some(d) = super::turn_game::turn_solver_decision(raw) {
return d.with_equity(equity.share);
}
// Stage C, solver everywhere (off by default, SOLVER_FLOP): every heads-up flop.
if let Some(d) = super::flop_spieler::flop_spieler_decision(raw) {
return d.with_equity(equity.share);
}
return super::river_subgame::fold_veto(raw, floored);
}
floored
}
Err(fault) => Decision::abstain(format!("equity unavailable: {fault}")),
}
}
/// Thresholds with the tournament risk premium (`icm::risk`) added: calls need more equity,
/// the preflop width narrows. No premium: unchanged.
fn with_premium(thresholds: Thresholds, premium: f64) -> Thresholds {
if premium <= 0.0 {
return thresholds;
}
Thresholds {
call_margin: thresholds.call_margin + premium,
range_width_scale: thresholds.range_width_scale * width_factor(premium),
..thresholds
}
}
fn think(spot: &Spot, premium: f64, jam_widen: f64, raw: &Spot) -> Decision {
let profiles: Vec<Profile> = spot.live_villains().filter_map(|v| v.profile).collect();
let thresholds = with_premium(adjust(Thresholds::BASE, &profiles), premium);
match spot.street {
Street::Preflop => {
let plan = advise_widened(spot, &thresholds, jam_widen);
// Eine Grenzhand folgt ihrer Seite der Tabelle (Raise bleibt Raise, Call bleibt Call):
// nahe der Grenze ist jede Linie fast gleich viel wert, Aussetzen ist die schlechteste.
let certainty = plan.certainty.max(MIN_CERTAINTY);
from_plan(spot, &PreflopPlan { certainty, ..plan })
}
Street::Flop | Street::Turn | Street::River => postflop(spot, &thresholds, raw, premium),
}
}
/// Full decision for a validated spot (preflop chart or postflop read/equity/EV),
/// always passed through `guard::enforce::enforce`. Die Handkategorie wird nur
/// zur Nachprüfung angehängt.
pub fn decide(spot: &Spot) -> Decision {
decide_with(spot, None)
}
/// `decide` with an optional tournament situation (`icm`). Without one: cash. With one
/// that cannot be priced: ABSTAIN.
pub fn decide_with(spot: &Spot, lage: Option<&Turnierlage>) -> Decision {
// Only act on reads we are proven to beat blind play with (`read_gate`); competent and
// aggressive opponents are played blind until the exploit logic earns them on the ladder.
let gated = super::read_gate::gate_reads(spot);
let raw = spot; // ungated reads, used ONLY by the defensive MDF floor (mdf_floor::floor)
let spot = &gated;
let premium = match lage.map(|l| call_premium(spot, l)) {
None => 0.0,
Some(Some(p)) => p,
Some(None) => return Decision::abstain("tournament situation unusable: no money EV"),
};
// Open-Jam-Weitung an der Bubble (`icm::risk::jam_pressure`): nur bei Turnierlage, sonst neutral.
// Unpricebar -> 1.0 (keine Weitung), nie ein Abbruch - der Riegel liegt bei `premium`/Calls.
// Tiefen-gegated (`jam_depth_gate`): die Weitung ist ein Kurzstack-Hebel; ein tiefer Deckler
// weitet NICHT (sonst oeffnet er Muell aus der Tiefe - gemessen: cover-short -12.5 ICM$/100).
let jam_widen = lage
.and_then(|l| jam_pressure(spot, l))
.map(jam_width_factor)
.map(|w| 1.0 + (w - 1.0) * jam_depth_gate(spot.hero_stack / spot.big_blind))
.unwrap_or(1.0);
let decision = enforce(spot, think(spot, premium, jam_widen, raw));
match crate::hand::showdown::best(spot.rules().hole_usage, &spot.hero_cards, &spot.board) {
Ok(strength) => decision.with_category(strength.category),
Err(_) => decision,
}
}
+245
View File
@@ -0,0 +1,245 @@
//! Stage C of "solver everywhere": the heads-up FLOP decided by an equilibrium solve over real combos.
//! Switch `SOLVER_FLOP` (default off).
//!
//! - **Game:** `cfr::turn_river_game` with its first street as the flop: flop betting (33 %, 75 % pot,
//! all-in, one raise), a chance node over `turn_cards` evenly strided turn cards, turn betting (75 %
//! pot, all-in, one raise), then the showdown as the EXACT equity over every river card per combo pair
//! (`TrSolver::with_river_equity`, card removal included). The observed flop line is in the tree.
//! - **Ranges** as in stages A/B: blueprint where it recognises the spot, else the range model of the
//! action history (`river_spieler::model_lists`); pruned to the heaviest `max_combos` per player.
//! Hero's real hand, if pruned away, joins at its weight (or a token weight) in an uncached solve.
//! - **Time:** fixed iterations with a wall-time budget; under `MIN_ITERS` the heuristic decides.
//!
//! Named approximations: no river betting (the river is a check-down inside the flop game; the river
//! solver re-solves it when it comes), `turn_cards` of 49 turn cards, pruned ranges, two flop sizes.
//! The turn and river are re-solved at their own decisions (stages B and A), so only the flop action
//! comes from this game.
use crate::card::Card;
use crate::cfr::river_game::Act;
use crate::cfr::turn_river_game::{build, Menu, TNode, TrBets, TrSolver};
use crate::engine::river_subgame::legal_choice;
use crate::engine::turn_game::{prune, street_line, TurnConfig};
use crate::game::{Decision, Spot, Street};
use crate::hand::fast7;
use crate::rng::Rng;
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
static ON: AtomicBool = AtomicBool::new(false);
/// Budget override in ms (0 = `STANDARD`); tests under parallel load use it.
static BUDGET_OVERRIDE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
#[cfg(test)]
pub(crate) fn set_budget_override(ms: u64) {
BUDGET_OVERRIDE.store(ms, Ordering::Relaxed);
}
pub fn set_flop_spieler(on: bool) {
ON.store(on, Ordering::Relaxed);
}
pub fn flop_spieler() -> bool {
ON.load(Ordering::Relaxed)
}
/// `SOLVER_FLOP=1`.
pub fn from_env() -> bool {
matches!(std::env::var("SOLVER_FLOP").as_deref(), Ok("1") | Ok("an"))
}
/// Size and budget (`FLOP_COMBOS`, `FLOP_CARDS`, `FLOP_ITERS` override).
#[derive(Clone, Copy, Debug)]
pub struct FlopConfig {
pub max_combos: usize,
pub turn_cards: usize,
pub iterations: u32,
pub budget_ms: f64,
}
pub const MIN_ITERS: u32 = 60;
impl FlopConfig {
pub const STANDARD: FlopConfig = FlopConfig { max_combos: 120, turn_cards: 8, iterations: 200, budget_ms: 1800.0 };
pub fn from_env() -> FlopConfig {
let num = |k: &str, d: usize| std::env::var(k).ok().and_then(|s| s.parse().ok()).filter(|n| *n > 0).unwrap_or(d);
FlopConfig {
max_combos: num("FLOP_COMBOS", Self::STANDARD.max_combos),
turn_cards: num("FLOP_CARDS", Self::STANDARD.turn_cards),
iterations: num("FLOP_ITERS", Self::STANDARD.iterations as usize) as u32,
budget_ms: match BUDGET_OVERRIDE.load(Ordering::Relaxed) {
0 => Self::STANDARD.budget_ms,
ms => ms as f64,
},
}
}
}
pub struct Solved {
rows: Vec<f64>,
acts: Vec<Act>,
hero_masks: Vec<u64>,
pub millis: f64,
pub iterations: u32,
pub combos: [usize; 2],
pub nodes: usize,
pub source: &'static str,
}
/// The flop+turn betting menus.
pub fn flop_bets(pot: f64, stack: f64, first: usize) -> TrBets {
TrBets {
pot,
stack,
first,
turn: Menu { fracs: vec![0.33, 0.75], raise_mult: vec![3.0], max_raises: 1, allin: true },
river: Menu { fracs: vec![0.75], raise_mult: vec![3.0], max_raises: 1, allin: true },
}
}
/// Solve the flop of `spot` with these ranges; `keep` = a hero hand that must be in the game.
pub fn solve_flop(spot: &Spot, hero: &[(Vec<Card>, f64)], villain_list: &[(Vec<Card>, f64)], cfg: &FlopConfig, keep: Option<u64>, source: &'static str) -> Option<Solved> {
if spot.street != Street::Flop || spot.board.len() != 3 || spot.live_villains().count() != 1 {
return None;
}
let villain = spot.live_villains().next()?;
let (first, forced, c) = street_line(spot, villain, Street::Flop);
let pot = spot.pot - c[0] - c[1];
let stack = (spot.hero_stack + c[0]).min(villain.stack + c[1]);
if pot <= 0.0 || stack <= c[0].max(c[1]) {
return None;
}
let started = std::time::Instant::now();
let board = fast7::mask(&spot.board);
let pc = TurnConfig { max_combos: cfg.max_combos, cover: 0.95, ..TurnConfig::STANDARD };
let hands = [prune(hero, board, &pc, keep), prune(villain_list, board, &pc, None)];
if hands[0].masks.is_empty() || hands[1].masks.is_empty() {
return None;
}
let game = build(&flop_bets(pot, stack, first), &forced);
let at = game.at?;
if !matches!(game.nodes.get(at), Some(TNode::Dec { player: 0, street: 0, .. })) {
return None;
}
let combos = [hands[0].masks.len(), hands[1].masks.len()];
let hero_masks = hands[0].masks.clone();
let acts = game.acts[at].clone();
let nodes = game.nodes.len();
let mut solver = TrSolver::new(game, hands, board, Some(cfg.turn_cards)).with_river_equity(board);
let mut done = 0;
while done < cfg.iterations {
solver.iterate();
done += 1;
if done % 5 == 0 && started.elapsed().as_secs_f64() * 1e3 > cfg.budget_ms {
break;
}
}
if done < MIN_ITERS {
return None;
}
let strategy = solver.strategy();
let rows: Vec<f64> = (0..combos[0]).flat_map(|i| strategy.row(at, 0, i).to_vec()).collect();
let millis = started.elapsed().as_secs_f64() * 1e3;
Some(Solved { rows, acts, hero_masks, millis, iterations: done, combos, nodes, source })
}
fn decide_from(spot: &Spot, solved: &Solved, hero_mask: u64) -> Option<Decision> {
let idx = solved.hero_masks.iter().position(|m| *m == hero_mask)?;
let a = solved.acts.len();
let row = &solved.rows[idx * a..(idx + 1) * a];
let (draw, _) = Rng::seeded(spot.seed).unit();
let mut acc = 0.0;
let mut pick = a.saturating_sub(1);
for (k, p) in row.iter().enumerate() {
acc += p;
if draw < acc {
pick = k;
break;
}
}
let act = *solved.acts.get(pick)?;
let p = row.get(pick).copied().unwrap_or(0.0);
Some(Decision::new(
legal_choice(spot, act),
p.clamp(0.0, 1.0),
format!(
"solver flop ({}): {}x{} combos, {} nodes, {} iters, {act:?} p {p:.2}, {:.0} ms",
solved.source, solved.combos[0], solved.combos[1], solved.nodes, solved.iterations, solved.millis
),
))
}
static CACHE: Mutex<Option<HashMap<u64, Arc<Solved>>>> = Mutex::new(None);
const CACHE_MAX: usize = 2048;
fn public_key(spot: &Spot, cfg: &FlopConfig) -> u64 {
let mut h = std::collections::hash_map::DefaultHasher::new();
format!("{:?}", spot.history).hash(&mut h);
format!("{:?}", spot.board).hash(&mut h);
[spot.pot, spot.to_call, spot.hero_stack, spot.big_blind].iter().for_each(|x| x.to_bits().hash(&mut h));
spot.live_villains().for_each(|v| {
(v.seat, v.stack.to_bits()).hash(&mut h);
format!("{:?}", v.profile).hash(&mut h);
});
(spot.hero_seat, spot.button_seat, spot.seats, cfg.max_combos, cfg.turn_cards, cfg.iterations).hash(&mut h);
h.finish()
}
/// The live stage-C decision, or `None` and the heuristic keeps it.
pub fn flop_spieler_decision(raw: &Spot) -> Option<Decision> {
if !flop_spieler() || raw.street != Street::Flop || raw.hero_cards.len() != 2 || raw.board.len() != 3 {
return None;
}
let gated = crate::engine::read_gate::gate_reads(raw);
let spot = &gated;
if spot.live_villains().count() != 1 {
return None;
}
let begun = std::time::Instant::now();
let cfg = FlopConfig::from_env();
let hero_mask = fast7::mask(&spot.hero_cards);
if hero_mask & fast7::mask(&spot.board) != 0 {
return None;
}
let read = crate::engine::river_spieler::read_of(raw);
let lists = || crate::engine::river_spieler::solver_lists(spot, crate::engine::river_spieler::RiverSpieler::An, read.as_ref());
let raw_profile = read.as_ref().map(|_| format!("{:?}", raw.live_villains().next().map(|v| v.profile.clone())));
let key = {
let mut h = std::collections::hash_map::DefaultHasher::new();
(public_key(spot, &cfg), raw_profile).hash(&mut h);
h.finish()
};
let cached = CACHE.lock().ok().and_then(|m| m.as_ref().and_then(|m| m.get(&key).cloned()));
let solved = match cached {
Some(s) => s,
None => {
let (hero, villain, source) = lists()?;
let solved = Arc::new(solve_flop(spot, &hero, &villain, &cfg, None, source)?);
if let Ok(mut m) = CACHE.lock() {
let map = m.get_or_insert_with(HashMap::new);
if map.len() >= CACHE_MAX {
map.clear();
}
map.insert(key, solved.clone());
}
solved
}
};
if let Some(d) = decide_from(spot, &solved, hero_mask) {
return Some(d);
}
// Hero's hand was pruned away: one more solve with it kept, in what is left of the budget.
let left = cfg.budget_ms - begun.elapsed().as_secs_f64() * 1e3;
if left <= 0.0 {
return None;
}
let (hero, villain, source) = lists()?;
let own = solve_flop(spot, &hero, &villain, &FlopConfig { budget_ms: left, ..cfg }, Some(hero_mask), source)?;
decide_from(spot, &own, hero_mask)
}
#[cfg(test)]
mod tests;
+131
View File
@@ -0,0 +1,131 @@
use super::*;
use crate::card::Card;
use crate::cfr::turn_river_game::Hands;
use crate::game::{ActionKind, ActionRecord, Choice, SeenAction, Spot, Street, Villain};
use crate::variant::Variant;
static MODE_LOCK: Mutex<()> = Mutex::new(());
fn rec(street: Street, seat: u8, action: SeenAction, amount: Option<f64>) -> ActionRecord {
ActionRecord { street, seat, action, amount }
}
/// Button (seat 4) opens 2.5, big blind (seat 0) calls; `flop` is the flop line so far; hero = button.
fn flop_spot(flop: &[ActionRecord], hero: &str, to_call: f64) -> Spot {
use SeenAction::*;
use Street::*;
let mut h = vec![
rec(Preflop, 5, PostSmallBlind, Some(0.5)),
rec(Preflop, 0, PostBigBlind, Some(1.0)),
rec(Preflop, 1, Fold, None),
rec(Preflop, 2, Fold, None),
rec(Preflop, 3, Fold, None),
rec(Preflop, 4, Raise, Some(2.5)),
rec(Preflop, 5, Fold, None),
rec(Preflop, 0, Call, Some(2.5)),
];
h.extend_from_slice(flop);
let legal = if to_call > 0.0 { vec![ActionKind::Fold, ActionKind::Call, ActionKind::Raise] } else { vec![ActionKind::Check, ActionKind::Raise] };
Spot {
variant: Variant::Nlhe,
big_blind: 1.0,
seats: 6,
hero_seat: 4,
button_seat: Some(4),
hero_cards: Card::parse_list(hero).unwrap(),
board: Card::parse_list("Ah 7d 2c").unwrap(),
street: Street::Flop,
pot: 5.5 + to_call,
to_call,
hero_stack: 97.5,
min_raise_to: Some(if to_call > 0.0 { 2.0 * to_call } else { 1.0 }),
max_raise_to: Some(97.5),
legal,
allowed_sizes: None,
villains: vec![Villain { seat: 0, stack: 97.5 - to_call, folded: false, profile: None }],
seed: 11,
history: h,
}
}
fn checked_to(hero: &str) -> Spot {
flop_spot(&[rec(Street::Flop, 0, SeenAction::Check, None)], hero, 0.0)
}
fn facing_bet(hero: &str) -> Spot {
flop_spot(&[rec(Street::Flop, 0, SeenAction::Bet, Some(4.0))], hero, 4.0)
}
#[test]
#[ignore]
fn timing() {
for hero in ["Ac As", "Td 9c"] {
for spot in [facing_bet(hero), checked_to(hero)] {
let (h, v) = crate::engine::river_spieler::model_lists(&spot).unwrap();
let cfg = FlopConfig { budget_ms: 1e9, ..FlopConfig::STANDARD };
let s = solve_flop(&spot, &h, &v, &cfg, Some(fast7::mask(&spot.hero_cards)), "modell").unwrap();
eprintln!("{}x{} combos {} nodes {} iters {:.0} ms", s.combos[0], s.combos[1], s.nodes, s.iterations, s.millis);
}
}
}
#[test]
fn off_decides_nothing_and_on_decides_heads_up_flops() {
let _g = MODE_LOCK.lock().unwrap();
set_flop_spieler(false);
assert!(flop_spieler_decision(&checked_to("Ks Kd")).is_none());
set_flop_spieler(true);
set_budget_override(60_000);
for spot in [checked_to("Ks Kd"), facing_bet("Qc Jc"), facing_bet("9s 8s"), checked_to("4h 3h")] {
let d = flop_spieler_decision(&spot).expect("heads-up flop is in the slice");
assert!(d.reason.contains("solver flop"), "{}", d.reason);
match d.choice {
Choice::Fold | Choice::Call => assert!(spot.to_call > 0.0),
Choice::Check => assert_eq!(spot.to_call, 0.0),
_ => {}
}
}
let mut multi = checked_to("Ks Kd");
multi.villains.push(Villain { seat: 1, stack: 90.0, folded: false, profile: None });
assert!(flop_spieler_decision(&multi).is_none());
set_budget_override(0);
set_flop_spieler(false);
}
/// The equity showdown is exact: AA vs KK on Q72 rainbow after a blank turn loses only to a river king
/// (two kings left among 44 river cards).
#[test]
fn the_river_equity_table_is_exact() {
let board = fast7::mask(&Card::parse_list("Qh 7d 2c").unwrap());
let aa = fast7::mask(&Card::parse_list("As Ad").unwrap());
let kk = fast7::mask(&Card::parse_list("Ks Kd").unwrap());
let game = build(&flop_bets(5.5, 97.5, 1), &[]);
let hands = [Hands { masks: vec![aa], weights: vec![1.0] }, Hands { masks: vec![kk], weights: vec![1.0] }];
let turn = fast7::bit(Card::parse_list("3s").unwrap()[0]);
let s = TrSolver::with_cards(game, hands, board, vec![turn], 1.0).with_river_equity(board);
let eq = s.eq.as_ref().unwrap()[0][0];
// 44 river cards left (52 - 3 board - turn - 4 hole); KK wins with Kh or Kc only.
assert!((eq - 42.0 / 44.0).abs() < 1e-5, "eq {eq}");
}
/// Facing a pot bet with total air the solver folds mostly; with top set it never folds.
#[test]
fn sets_continue_air_folds() {
let cfg = FlopConfig::STANDARD;
let row = |hero: &str| {
let spot = facing_bet(hero);
let (h, v) = crate::engine::river_spieler::model_lists(&spot).unwrap();
let m = fast7::mask(&spot.hero_cards);
let s = solve_flop(&spot, &h, &v, &cfg, Some(m), "modell").unwrap();
let i = s.hero_masks.iter().position(|x| *x == m).unwrap();
let a = s.acts.len();
(s.rows[i * a..(i + 1) * a].to_vec(), s.acts.clone())
};
let (r, acts) = row("Ac As");
let fold = |r: &[f64], acts: &[Act]| r.iter().zip(acts).filter(|(_, a)| **a == Act::Fold).map(|(p, _)| p).sum::<f64>();
assert!(fold(&r, &acts) < 0.01, "top set folds {r:?}");
let (r, acts) = row("5s 4s");
let _ = (r, acts); // a gutshot with a backdoor: no assertion on frequency, only that it solves
let (r, acts) = row("Td 9c");
assert!(fold(&r, &acts) > 0.5, "ten-high air calls {r:?} {acts:?}");
}
+30 -28
View File
@@ -1,28 +1,30 @@
//! Engine: composes assessment and choice into a decision.
pub mod audit;
pub mod bluff;
pub mod called;
pub mod called_equity;
pub mod decide;
pub mod double_board;
pub mod effective;
pub mod from_plan;
pub mod multiway;
pub mod omaha_combos;
pub mod options;
pub mod passive;
pub mod postflop;
pub mod read_gate;
pub mod range_combos;
pub mod range_filter;
pub mod read_label;
pub mod river_subgame;
pub mod run_twice;
pub mod semibluff;
pub mod size_policy;
pub mod texture_stance;
pub mod thin_value;
pub mod turn_game;
pub mod turn_subgame;
pub mod uncertainty;
//! Engine: composes assessment and choice into a decision.
pub mod audit;
pub mod bluff;
pub mod called;
pub mod called_equity;
pub mod decide;
pub mod double_board;
pub mod effective;
pub mod flop_spieler;
pub mod from_plan;
pub mod multiway;
pub mod omaha_combos;
pub mod options;
pub mod passive;
pub mod postflop;
pub mod read_gate;
pub mod range_combos;
pub mod range_filter;
pub mod read_label;
pub mod river_spieler;
pub mod river_subgame;
pub mod run_twice;
pub mod semibluff;
pub mod size_policy;
pub mod texture_stance;
pub mod thin_value;
pub mod turn_game;
pub mod turn_subgame;
pub mod uncertainty;
+405
View File
@@ -0,0 +1,405 @@
//! Stage A of "solver everywhere": the heads-up RIVER decided by an equilibrium solve over real combos,
//! as the primary decision maker (not a veto). Switch `SOLVER_RIVER` (default off).
//!
//! - **Game:** `cfr::turn_river_game::build_river` - the river alone, with the observed river line
//! inside the tree (exact sizes), position, three bet sizes plus all-in, raises. Solved with the
//! vectorised CFR+ of `TrSolver` over real combos: card removal and showdowns are exact per combo
//! (no strength buckets, blockers count).
//! - **Ranges** come from the hand's action history: where the blueprint recognises the spot (scenario
//! family of `blueprint::ranges`, loaded via `GRUNDSTRATEGIE`) both ranges are the blueprint's along
//! the line played; everywhere else both come from the engine's range model
//! (`exploit::range_model::range_spec` -> `range_filter`): the villain's with its (gated) read, hero's
//! own as the same model sees hero's line, without a read. `SOLVER_RIVER=modell` forces the range
//! model also in blueprint spots (a measurement arm: it shows the model path on the LBR scenario).
//! - **One solve per public state.** The ranges do not depend on hero's cards (the game deals card
//! removal itself), so a solve serves every hero hand at the node; solves are cached by public state.
//! Every hero hand outside the modelled range joins the solve at a token weight, so it gets a
//! strategy without moving the equilibrium.
//! - **Time budget:** CFR+ runs at most `ITERS` iterations and stops at `BUDGET_MS` wall time; under
//! `MIN_ITERS` finished iterations the heuristic keeps the decision (`None`).
//!
//! Not in the slice (the heuristic plays): multiway rivers, tournaments (the caller only asks for cash),
//! Omaha and other variants (hole cards != 2), spots whose line leaves the tree.
use crate::card::Card;
use crate::cfr::river_game::Act;
use crate::cfr::turn_river_game::{build_river, Hands, Menu, TNode, TrBets, TrSolver};
use crate::exploit::range_read::RangeRead;
use crate::engine::river_subgame::{legal_choice, river_line};
use crate::game::{Decision, Spot, Street, Villain};
use crate::hand::fast7;
use crate::rng::Rng;
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::sync::atomic::{AtomicU8, Ordering};
use std::sync::{Arc, Mutex};
/// Who plays the heads-up river.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RiverSpieler {
/// The heuristic (default).
Aus,
/// The solver; blueprint ranges where the spot is a blueprint scenario, else the range model.
An,
/// The solver with range-model ranges everywhere (measurement arm).
Modell,
}
static MODE: AtomicU8 = AtomicU8::new(0);
pub fn set_river_spieler(mode: RiverSpieler) {
MODE.store(
match mode {
RiverSpieler::Aus => 0,
RiverSpieler::An => 1,
RiverSpieler::Modell => 2,
},
Ordering::Relaxed,
);
}
pub fn river_spieler() -> RiverSpieler {
match MODE.load(Ordering::Relaxed) {
1 => RiverSpieler::An,
2 => RiverSpieler::Modell,
_ => RiverSpieler::Aus,
}
}
/// `SOLVER_RIVER`: `1`/`an` -> `An`, `modell` -> `Modell`, else `Aus`.
pub fn from_env() -> RiverSpieler {
match std::env::var("SOLVER_RIVER").as_deref() {
Ok("1") | Ok("an") => RiverSpieler::An,
Ok("modell") => RiverSpieler::Modell,
_ => RiverSpieler::Aus,
}
}
/// CFR+ iterations at most.
pub const ITERS: u32 = 600;
/// Fewer finished iterations than this (time budget hit): the heuristic decides.
pub const MIN_ITERS: u32 = 100;
/// Wall-time budget of one solve.
pub const BUDGET_MS: f64 = 1500.0;
/// The river bet menu: 33 %, 75 %, 125 % pot and all-in; raises to 3x or all-in, two raises.
fn river_menu() -> Menu {
Menu { fracs: vec![0.33, 0.75, 1.25], raise_mult: vec![3.0], max_raises: 2, allin: true }
}
/// One solved river node: what every hero hand at this public state shares.
pub struct Solved {
rows: Vec<f64>,
acts: Vec<Act>,
hero_masks: Vec<u64>,
pub millis: f64,
pub iterations: u32,
pub combos: [usize; 2],
pub nodes: usize,
pub source: &'static str,
}
/// Masks and weights of a combo list off the `dead` cards. `fill`: every other two-card combo joins at a
/// token weight, so each possible hero hand has a strategy in the one solve (CFR's regrets of a hand do
/// not depend on its own reach, so a token-weight hand plays its counterfactual best line without moving
/// the equilibrium).
fn hands_of(list: &[(Vec<Card>, f64)], dead: u64, fill: bool) -> Hands {
let mut w: HashMap<u64, f64> = HashMap::new();
for (c, x) in list {
if c.len() == 2 && *x > 0.0 && x.is_finite() {
let m = fast7::mask(c);
if m & dead == 0 && m.count_ones() == 2 {
let e = w.entry(m).or_insert(0.0);
*e = e.max(*x);
}
}
}
let top = w.values().copied().fold(0.0f64, f64::max).max(1e-12);
if fill {
let bits: Vec<u64> = (0..4u32).flat_map(|s| (0..13u32).map(move |r| 1u64 << (16 * s + r))).filter(|b| b & dead == 0).collect();
for i in 0..bits.len() {
for j in i + 1..bits.len() {
w.entry(bits[i] | bits[j]).or_insert(top * TOKEN);
}
}
}
let mut v: Vec<(u64, f64)> = w.into_iter().collect();
v.sort_by(|a, b| a.0.cmp(&b.0));
Hands { masks: v.iter().map(|x| x.0).collect(), weights: v.iter().map(|x| x.1).collect() }
}
/// Relative weight of a hero hand outside the modelled range.
const TOKEN: f64 = 1e-6;
/// Solve the river of `spot`'s public state with these ranges; every hero hand gets a strategy. `None` off the heads-up river slice, off the tree, or when the budget left too few iterations.
pub fn solve_river(spot: &Spot, hero: &[(Vec<Card>, f64)], villain_list: &[(Vec<Card>, f64)], source: &'static str, read: Option<&RangeRead>) -> Option<Solved> {
if spot.street != Street::River || spot.board.len() != 5 || spot.live_villains().count() != 1 {
return None;
}
let villain = spot.live_villains().next()?;
let (first, forced, c) = river_line(spot, villain);
let pot = spot.pot - c[0] - c[1];
let stack = (spot.hero_stack + c[0]).min(villain.stack + c[1]);
if pot <= 0.0 || stack <= 0.0 {
return None;
}
let started = std::time::Instant::now();
let turn = fast7::mask(&spot.board[..4]);
let river = fast7::bit(spot.board[4]);
let dead = turn | river;
let hands = [hands_of(hero, dead, true), hands_of(villain_list, dead, false)];
if hands[0].masks.is_empty() || hands[1].masks.is_empty() {
return None;
}
let bets = TrBets { pot, stack, first, turn: river_menu(), river: river_menu() };
let game = build_river(&bets, &forced);
let at = game.at?;
if !matches!(game.nodes.get(at), Some(TNode::Dec { player: 0, street: 1, .. })) {
return None;
}
let combos = [hands[0].masks.len(), hands[1].masks.len()];
let hero_masks = hands[0].masks.clone();
let acts = game.acts[at].clone();
let nodes = game.nodes.len();
let villain_weights = hands[1].weights.clone();
let mut solver = TrSolver::with_cards(game, hands, turn, vec![river], 1.0);
if let Some(r) = read {
lock_villain(&mut solver, r, pot, dead, &villain_weights);
}
let mut done = 0;
while done < ITERS {
solver.iterate();
done += 1;
if done % 10 == 0 && started.elapsed().as_secs_f64() * 1e3 > BUDGET_MS {
break;
}
}
if done < MIN_ITERS {
return None;
}
let strategy = solver.strategy();
let rows: Vec<f64> = (0..combos[0]).flat_map(|i| strategy.row(at, 0, i).to_vec()).collect();
let millis = started.elapsed().as_secs_f64() * 1e3;
Some(Solved { rows, acts, hero_masks, millis, iterations: done, combos, nodes, source })
}
/// Hero's action for the real hand from a solved node: the equilibrium mix, realised from the spot seed.
fn decide_from(spot: &Spot, solved: &Solved, hero_mask: u64) -> Option<Decision> {
let idx = solved.hero_masks.iter().position(|m| *m == hero_mask)?;
let a = solved.acts.len();
let row = &solved.rows[idx * a..(idx + 1) * a];
let (draw, _) = Rng::seeded(spot.seed).unit();
let mut acc = 0.0;
let mut pick = a.saturating_sub(1);
for (k, p) in row.iter().enumerate() {
acc += p;
if draw < acc {
pick = k;
break;
}
}
let act = *solved.acts.get(pick)?;
let choice = legal_choice(spot, act);
let p = row.get(pick).copied().unwrap_or(0.0);
Some(Decision::new(
choice,
p.clamp(0.0, 1.0),
format!(
"river solver ({}): {}x{} combos, {} nodes, {} iters, {act:?} p {p:.2}, {:.0} ms",
solved.source, solved.combos[0], solved.combos[1], solved.nodes, solved.iterations, solved.millis
),
))
}
/// Both ranges from the range model (the action history): hero's as the model reads hero's own line
/// (no read), the villain's with its gated read. Board cards only are dead (not hero's).
pub fn model_lists(spot: &Spot) -> Option<(Vec<(Vec<Card>, f64)>, Vec<(Vec<Card>, f64)>)> {
let villain = spot.live_villains().next()?;
let rules = spot.rules();
let list = |who: &Villain| {
let filter = crate::engine::range_filter::range_filter(&crate::exploit::range_model::range_spec(spot, who), rules, spot.variant, &spot.board);
crate::engine::range_combos::combos(&rules, &filter, &spot.board)
};
let me = Villain { seat: spot.hero_seat, stack: spot.hero_stack, folded: false, profile: None };
let eins = |l: Vec<Vec<Card>>| l.into_iter().map(|c| (c, 1.0)).collect::<Vec<_>>();
Some((eins(list(&me)?), eins(list(villain)?)))
}
/// The read layer (`exploit::range_read`, switch `GEGNER_RANGE=1`, default off): the villain's read from
/// its UNGATED profile, or `None` = the plain solver.
pub fn read_of(raw: &Spot) -> Option<RangeRead> {
if std::env::var("GEGNER_RANGE").as_deref() != Ok("1") {
return None;
}
let villain = raw.live_villains().next()?;
RangeRead::from_profile(villain.profile.as_ref())
}
/// Weighted mid-rank percentile of each combo's current strength (`fast7` score with `board`) within
/// the list. Exact on the river; current strength only (draw-blind) on flop and turn.
pub fn percentiles(masks: &[u64], weights: &[f64], board: u64) -> Vec<f64> {
let score: Vec<u32> = masks.iter().map(|m| fast7::score(m | board)).collect();
let mut order: Vec<usize> = (0..masks.len()).collect();
order.sort_by_key(|i| score[*i]);
let total: f64 = weights.iter().sum::<f64>().max(1e-300);
let mut out = vec![0.5; masks.len()];
let mut below = 0.0;
let mut k = 0;
while k < order.len() {
let mut e = k;
let mut tie = 0.0;
while e < order.len() && score[order[e]] == score[order[k]] {
tie += weights[order[e]];
e += 1;
}
for &i in &order[k..e] {
out[i] = (below + tie / 2.0) / total;
}
below += tie;
k = e;
}
out
}
/// The ranges of this spot (hero, villain) and where they came from: the blueprint where it recognises
/// the spot (unless `mode` is `Modell`), else the range model of the action history. THE HOOK of the
/// read layer: with a read, the villain's final weights are tilted by strength percentile
/// (`RangeRead::reweigh`); `read = None` returns the lists unchanged. Used by stages A, B and C.
pub fn solver_lists(spot: &Spot, mode: RiverSpieler, read: Option<&RangeRead>) -> Option<(Vec<(Vec<Card>, f64)>, Vec<(Vec<Card>, f64)>, &'static str)> {
let (h, mut v, source) = match mode {
RiverSpieler::An => match crate::blueprint::ranges::gewichtete_listen_offen(spot) {
Some((h, v)) => (h, v, "grund"),
None => {
let (h, v) = model_lists(spot)?;
(h, v, "modell")
}
},
_ => {
let (h, v) = model_lists(spot)?;
(h, v, "modell")
}
};
if let Some(r) = read.filter(|r| r.confidence > 0.0) {
let board = fast7::mask(&spot.board);
let masks: Vec<u64> = v.iter().map(|(c, _)| fast7::mask(c)).collect();
let weights: Vec<f64> = v.iter().map(|(_, w)| *w).collect();
let pct = percentiles(&masks, &weights, board);
let pairs: Vec<(f64, f64)> = weights.iter().copied().zip(pct).collect();
for ((_, w), x) in v.iter_mut().zip(r.reweigh(&pairs)) {
*w = x;
}
}
Some((h, v, source))
}
/// Value hands bet from this strength percentile up when the believed villain is checked to
/// (as `river_subgame`'s VALUE_RANK).
const BELIEVED_VALUE_RANK: f64 = 0.60;
/// Lock the villain's river decisions toward the read (restricted Nash response): facing a bet it folds
/// the weakest `fold_to_bet` share of its range and calls the rest (weight = the fold read's trust);
/// checked to, it bets its top `1 - BELIEVED_VALUE_RANK` at the size nearest 75 % pot plus the weakest
/// hands as bluffs so that the air share of the bet is `bluff_share` (weight = the bluff read's trust).
/// Facing a raise it stays free.
fn lock_villain(solver: &mut TrSolver, read: &RangeRead, pot: f64, board: u64, villain_weights: &[f64]) {
let pct = percentiles(solver.masks(1), villain_weights, board);
// The action that led into each node (a raise faced vs an opening bet faced).
let mut incoming: Vec<Option<Act>> = vec![None; solver.game.nodes.len()];
for (k, n) in solver.game.nodes.iter().enumerate() {
if let TNode::Dec { kids, .. } = n {
for (c, kid) in kids.iter().enumerate() {
incoming[*kid] = solver.game.acts[k].get(c).copied();
}
}
}
let nodes: Vec<(usize, Vec<Act>)> = solver
.game
.nodes
.iter()
.enumerate()
.filter_map(|(k, n)| match n {
TNode::Dec { player: 1, .. } => Some((k, solver.game.acts[k].clone())),
_ => None,
})
.collect();
for (node, acts) in nodes {
let a = acts.len();
let facing_bet = acts.contains(&Act::Fold) && matches!(incoming[node], Some(Act::Bet(_)));
if facing_bet {
let Some(f) = read.fold_to_bet(2) else { continue };
let call = acts.iter().position(|x| *x == Act::Call).unwrap_or(1);
let rows: Vec<f64> = pct.iter().flat_map(|p| (0..a).map(move |k| if *p < f { f64::from(k == 0) } else { f64::from(k == call) })).collect();
solver.lock(node, rows, read.trust(false, 2));
} else if !acts.contains(&Act::Fold) && acts.first() == Some(&Act::Check) {
let Some((bet, to)) = acts.iter().enumerate().filter_map(|(k, x)| if let Act::Bet(t) = x { Some((k, *t)) } else { None }).min_by(|x, y| (x.1 / pot - 0.75).abs().total_cmp(&(y.1 / pot - 0.75).abs())) else { continue };
let bs = read.bluff_share(2, to / pot).clamp(0.0, 0.9);
let value = 1.0 - BELIEVED_VALUE_RANK;
let bluff = (value * bs / (1.0 - bs)).min(BELIEVED_VALUE_RANK);
let rows: Vec<f64> = pct.iter().flat_map(|p| (0..a).map(move |k| if *p >= BELIEVED_VALUE_RANK || *p < bluff { f64::from(k == bet) } else { f64::from(k == 0) })).collect();
solver.lock(node, rows, read.trust(true, 2));
}
}
}
static CACHE: Mutex<Option<HashMap<u64, Arc<Solved>>>> = Mutex::new(None);
const CACHE_MAX: usize = 4096;
/// Identity of the public state, the villain's read and the mode (not hero's cards).
fn public_key(spot: &Spot, mode: RiverSpieler) -> u64 {
let mut h = std::collections::hash_map::DefaultHasher::new();
format!("{:?}", spot.history).hash(&mut h);
format!("{:?}", spot.board).hash(&mut h);
[spot.pot, spot.to_call, spot.hero_stack, spot.big_blind].iter().for_each(|x| x.to_bits().hash(&mut h));
spot.live_villains().for_each(|v| {
(v.seat, v.stack.to_bits()).hash(&mut h);
format!("{:?}", v.profile).hash(&mut h);
});
(spot.hero_seat, spot.button_seat, spot.seats, MODE.load(Ordering::Relaxed), mode as u8, ITERS).hash(&mut h);
h.finish()
}
/// The live decision: the river solved to equilibrium for hero's real hand, or `None` (switch off, not
/// a heads-up Hold'em river, off the tree, budget) and the heuristic keeps the decision. `spot` carries
/// the ungated reads; the villain range uses the gated ones, as the heuristic's does.
pub fn river_spieler_decision(raw: &Spot) -> Option<Decision> {
let mode = river_spieler();
if mode == RiverSpieler::Aus || raw.street != Street::River || raw.hero_cards.len() != 2 || raw.board.len() != 5 {
return None;
}
let gated = crate::engine::read_gate::gate_reads(raw);
let spot = &gated;
if spot.live_villains().count() != 1 {
return None;
}
let hero_mask = fast7::mask(&spot.hero_cards);
if hero_mask & fast7::mask(&spot.board) != 0 {
return None;
}
let read = read_of(raw);
let mut key = public_key(spot, mode);
if read.is_some() {
let mut h = std::collections::hash_map::DefaultHasher::new();
(key, format!("{:?}", raw.live_villains().next().map(|v| v.profile.clone()))).hash(&mut h);
key = h.finish();
}
let cached = CACHE.lock().ok().and_then(|m| m.as_ref().and_then(|m| m.get(&key).cloned()));
let solved = match cached {
Some(s) => s,
None => {
let (hero, villain, source) = solver_lists(spot, mode, read.as_ref())?;
let solved = Arc::new(solve_river(spot, &hero, &villain, source, read.as_ref())?);
if let Ok(mut m) = CACHE.lock() {
let map = m.get_or_insert_with(HashMap::new);
if map.len() >= CACHE_MAX {
map.clear();
}
map.insert(key, solved.clone());
}
solved
}
};
decide_from(spot, &solved, hero_mask)
}
#[cfg(test)]
mod tests;
+191
View File
@@ -0,0 +1,191 @@
use super::*;
use crate::card::Card;
use crate::game::{ActionKind, ActionRecord, Choice, SeenAction, Spot, Street, Villain};
use crate::variant::Variant;
/// The switch is process-global: tests that touch it take turns.
static MODE_LOCK: Mutex<()> = Mutex::new(());
fn rec(street: Street, seat: u8, action: SeenAction, amount: Option<f64>) -> ActionRecord {
ActionRecord { street, seat, action, amount }
}
/// Six-max line to the river: button (seat 4) opens 2.5, big blind (seat 0) calls; flop check, bet 1.8,
/// call; turn check, check. River pot 9.1 + `pot_extra`; `river` is the river line so far; hero is the
/// button.
fn river_spot(river: &[ActionRecord], hero: &str, to_call: f64, pot_extra: f64) -> Spot {
use SeenAction::*;
use Street::*;
let mut h = vec![
rec(Preflop, 5, PostSmallBlind, Some(0.5)),
rec(Preflop, 0, PostBigBlind, Some(1.0)),
rec(Preflop, 1, Fold, None),
rec(Preflop, 2, Fold, None),
rec(Preflop, 3, Fold, None),
rec(Preflop, 4, Raise, Some(2.5)),
rec(Preflop, 5, Fold, None),
rec(Preflop, 0, Call, Some(2.5)),
rec(Flop, 0, Check, None),
rec(Flop, 4, Bet, Some(1.8)),
rec(Flop, 0, Call, Some(1.8)),
rec(Turn, 0, Check, None),
rec(Turn, 4, Check, None),
];
h.extend_from_slice(river);
let legal = if to_call > 0.0 { vec![ActionKind::Fold, ActionKind::Call, ActionKind::Raise] } else { vec![ActionKind::Check, ActionKind::Raise] };
Spot {
variant: Variant::Nlhe,
big_blind: 1.0,
seats: 6,
hero_seat: 4,
button_seat: Some(4),
hero_cards: Card::parse_list(hero).unwrap(),
board: Card::parse_list("Ah 7d 2c Ks 3h").unwrap(),
street: Street::River,
pot: 9.1 + pot_extra,
to_call,
hero_stack: 95.7,
min_raise_to: Some(if to_call > 0.0 { 2.0 * to_call } else { 1.0 }),
max_raise_to: Some(95.7),
legal,
allowed_sizes: None,
villains: vec![Villain { seat: 0, stack: 95.7 - to_call, folded: false, profile: None }],
seed: 7,
history: h,
}
}
fn facing_bet(hero: &str) -> Spot {
river_spot(&[rec(Street::River, 0, SeenAction::Bet, Some(9.0))], hero, 9.0, 9.0)
}
fn checked_to(hero: &str) -> Spot {
river_spot(&[rec(Street::River, 0, SeenAction::Check, None)], hero, 0.0, 0.0)
}
fn row_of(spot: &Spot) -> (Vec<f64>, Vec<Act>) {
let (h, v) = model_lists(spot).expect("model ranges");
let s = solve_river(spot, &h, &v, "modell", None).expect("solved");
let m = fast7::mask(&spot.hero_cards);
let i = s.hero_masks.iter().position(|x| *x == m).expect("every hero hand is in the solve");
let a = s.acts.len();
(s.rows[i * a..(i + 1) * a].to_vec(), s.acts.clone())
}
fn prob(row: &[f64], acts: &[Act], f: impl Fn(&Act) -> bool) -> f64 {
row.iter().zip(acts).filter(|(_, a)| f(a)).map(|(p, _)| p).sum()
}
/// Off (the default), the engine's output is untouched: no decision.
#[test]
fn off_decides_nothing() {
let _g = MODE_LOCK.lock().unwrap();
set_river_spieler(RiverSpieler::Aus);
assert!(river_spieler_decision(&facing_bet("As Ad")).is_none());
}
/// On, a heads-up river is decided by the solver, deterministically, with a legal choice.
#[test]
fn on_decides_heads_up_rivers_deterministically() {
let _g = MODE_LOCK.lock().unwrap();
set_river_spieler(RiverSpieler::Modell);
for spot in [facing_bet("Qc Jc"), checked_to("Qc Jc"), facing_bet("As Ad")] {
let a = river_spieler_decision(&spot).expect("heads-up river is in the slice");
let b = river_spieler_decision(&spot).expect("cached");
assert_eq!(a.choice, b.choice);
assert!(a.reason.contains("river solver (modell)"), "{}", a.reason);
match a.choice {
Choice::Fold | Choice::Call => assert!(spot.to_call > 0.0),
Choice::Check => assert_eq!(spot.to_call, 0.0),
Choice::Raise { to } => assert!(to > spot.to_call),
_ => {}
}
}
set_river_spieler(RiverSpieler::Aus);
}
/// Multiway rivers stay with the heuristic.
#[test]
fn multiway_is_not_in_the_slice() {
let _g = MODE_LOCK.lock().unwrap();
set_river_spieler(RiverSpieler::Modell);
let mut spot = facing_bet("As Ad");
spot.villains.push(Villain { seat: 1, stack: 90.0, folded: false, profile: None });
assert!(river_spieler_decision(&spot).is_none());
set_river_spieler(RiverSpieler::Aus);
}
/// Top set never folds to a bet; six-high air facing a pot bet folds most of the time.
#[test]
fn the_nuts_continue_and_air_folds() {
let (row, acts) = row_of(&facing_bet("As Ad"));
assert!(prob(&row, &acts, |a| *a == Act::Fold) < 0.01, "top set folds {row:?}");
let (row, acts) = row_of(&facing_bet("6s 5s"));
assert!(prob(&row, &acts, |a| *a == Act::Fold) > 0.5, "air calls a pot bet {row:?} {acts:?}");
}
/// Checked to in position, top set bets for value.
#[test]
fn top_set_bets_when_checked_to() {
let (row, acts) = row_of(&checked_to("As Ad"));
assert!(prob(&row, &acts, |a| matches!(a, Act::Bet(_))) > 0.8, "{row:?} {acts:?}");
}
/// The river-only game: the observed line puts hero at a hero decision on the river, and the solve is
/// close to equilibrium (exact best response in the game, below 1 % of the pot after `ITERS`).
#[test]
fn the_river_game_converges() {
let spot = facing_bet("Qc Jc");
let (h, v) = model_lists(&spot).unwrap();
let villain = spot.live_villains().next().unwrap();
let (first, forced, c) = river_line(&spot, villain);
assert_eq!((first, forced.clone()), (1, vec![Act::Bet(9.0)]));
let pot = spot.pot - c[0] - c[1];
let bets = TrBets { pot, stack: 95.7, first, turn: river_menu(), river: river_menu() };
let game = build_river(&bets, &forced);
let at = game.at.unwrap();
assert!(matches!(game.nodes[at], TNode::Dec { player: 0, street: 1, .. }));
let turn = fast7::mask(&spot.board[..4]);
let river = fast7::bit(spot.board[4]);
let hands = [hands_of(&h, turn | river, false), hands_of(&v, turn | river, false)];
let mut solver = TrSolver::with_cards(game, hands, turn, vec![river], 1.0);
solver.run(ITERS);
let e = solver.exploitability(&solver.strategy());
assert!(e.total / pot < 0.01, "exploitability {:.4} of pot {pot}", e.total);
}
fn read(confidence: f64, bluff_confidence: f64, fold: f64) -> RangeRead {
RangeRead { tilt: 0.8, aggression_ratio: [None, None, Some(1.0)], shown: None, fold: [None, None, Some(fold)], confidence, bluff_confidence }
}
fn rows_with(spot: &Spot, r: Option<&RangeRead>) -> Vec<f64> {
let (h, v, src) = solver_lists(spot, RiverSpieler::Modell, r).expect("lists");
solve_river(spot, &h, &v, src, r).expect("solved").rows.clone()
}
/// The read hook with no read, or a read without any confidence, is the plain solver bit for bit.
#[test]
fn a_read_without_confidence_is_bit_identical() {
for spot in [facing_bet("Qc Jc"), checked_to("6s 5s")] {
let plain = rows_with(&spot, None);
let zero = rows_with(&spot, Some(&read(0.0, 0.0, 0.9)));
assert_eq!(plain.len(), zero.len());
assert!(plain.iter().zip(&zero).all(|(a, b)| a.to_bits() == b.to_bits()));
}
}
/// A trusted read that the villain over-folds to bets makes hero's range bet more often when checked to.
#[test]
fn a_trusted_over_fold_read_bets_more() {
let spot = checked_to("6s 5s");
let bet_share = |r: Option<&RangeRead>| {
let (h, v, src) = solver_lists(&spot, RiverSpieler::Modell, r).unwrap();
let s = solve_river(&spot, &h, &v, src, r).unwrap();
let a = s.acts.len();
let n = s.hero_masks.len();
(0..n).map(|k| prob(&s.rows[k * a..(k + 1) * a], &s.acts, |x| matches!(x, Act::Bet(_)))).sum::<f64>() / n as f64
};
let plain = bet_share(None);
let exploit = bet_share(Some(&read(0.9, 0.0, 0.9)));
assert!(exploit > plain + 0.1, "plain {plain:.2} exploit {exploit:.2}");
}
+431 -322
View File
@@ -1,322 +1,431 @@
//! The turn re-solved at the table over real hands (plan E3, layer 2): both ranges from the
//! blueprint (`blueprint::ranges`, carried along the line actually played), the turn betting and
//! the river inside one game (`cfr::turn_river_game`), hero's equilibrium action at the real node.
//!
//! Switch: `TurnPlayer::Grund` (default `Off`; `ab_zelle` / `engine_lbr`: `TURN_SPIEL=grund`). Off,
//! `turn_game_decision` returns `None` before it looks at anything, so the engine's output is
//! unchanged. On, it plays only where the blueprint recognises the spot (S1: button open, big blind
//! call, about 100 bb, heads-up on the turn, hero at a decision); everywhere else the heuristic plays.
//!
//! The solve depends on the public state only (board, line, pot, stacks): the villain's range is NOT
//! conditioned on hero's real cards (`gewichtete_listen_offen`; the game deals card removal itself),
//! so one solve serves every hero hand at the same node. Solves are cached by public state (a
//! measurement that asks the engine for every hand of a range, as LBR does, pays one solve per node).
//!
//! Approximations (named, each a knob of `TurnConfig`): ranges are pruned to the `max_combos`
//! heaviest combos per player; the river is enumerated over `river_cards` evenly strided cards, each
//! standing for its share (`cfr::turn_river_game`); the bet menu is `TrBets::standard` plus the
//! observed size; the solve is a fixed `iterations` of CFR+. Hero's real hand, if pruned away or
//! outside the blueprint range, is put back with its weight (or a token weight) in an uncached solve.
use crate::card::Card;
use crate::cfr::river_game::Act;
use crate::cfr::turn_river_game::{build, Exploit, Hands, TNode, TrBets, TrSolver};
use crate::engine::river_subgame::legal_choice;
use crate::game::{Decision, SeenAction, Spot, Street, Villain};
use crate::hand::fast7;
use crate::rng::Rng;
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::sync::{Arc, Mutex};
static MODE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
/// Who plays the heads-up turn.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TurnPlayer {
/// The heuristic (default).
Off,
/// The turn+river game with both ranges from the blueprint; only where the spot is a blueprint
/// scenario, else the heuristic plays.
Grund,
}
pub fn set_turn_player(mode: TurnPlayer) {
MODE.store(u8::from(mode == TurnPlayer::Grund), std::sync::atomic::Ordering::Relaxed);
}
pub fn turn_player() -> TurnPlayer {
if MODE.load(std::sync::atomic::Ordering::Relaxed) == 1 {
TurnPlayer::Grund
} else {
TurnPlayer::Off
}
}
/// Size and budget of the solve.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct TurnConfig {
/// Most combos per player (heaviest by weight).
pub max_combos: usize,
/// Stop adding combos once this share of the range mass is in (before `max_combos`).
pub cover: f64,
/// River cards enumerated (of 48).
pub river_cards: usize,
/// CFR+ iterations.
pub iterations: u32,
/// Also compute the best-response exploitability of the result (about two more iterations).
pub measure: bool,
/// Raises allowed after a river bet (0 or 1).
pub river_raises: usize,
}
impl TurnConfig {
pub const STANDARD: TurnConfig = TurnConfig { max_combos: 160, cover: 0.95, river_cards: 10, iterations: 200, measure: false, river_raises: 0 };
/// `STANDARD` with `TURN_COMBOS`, `TURN_CARDS`, `TURN_ITERS`, `TURN_EXPLOIT=1` from the environment.
pub fn from_env() -> TurnConfig {
let num = |k: &str, d: usize| std::env::var(k).ok().and_then(|s| s.parse().ok()).filter(|n| *n > 0).unwrap_or(d);
TurnConfig {
max_combos: num("TURN_COMBOS", Self::STANDARD.max_combos),
cover: num("TURN_COVER", 95) as f64 / 100.0,
river_cards: num("TURN_CARDS", Self::STANDARD.river_cards),
iterations: num("TURN_ITERS", Self::STANDARD.iterations as usize) as u32,
measure: std::env::var("TURN_EXPLOIT").as_deref() == Ok("1"),
river_raises: std::env::var("TURN_RIVER_RAISES").ok().and_then(|s| s.parse().ok()).map_or(Self::STANDARD.river_raises, |n: usize| n.min(1)),
}
}
}
/// One solved node of the game: what every hero hand at this public state shares.
pub struct Solved {
/// Hero's turn-node action probabilities, `hero_masks.len()` rows of `acts.len()`.
rows: Vec<f64>,
acts: Vec<Act>,
hero_masks: Vec<u64>,
pub millis: f64,
pub combos: [usize; 2],
pub nodes: usize,
/// Best-response exploitability of the solved game, chips per deal (when `measure`).
pub exploit: Option<Exploit>,
pub big_blind: f64,
pub pot: f64,
}
impl Solved {
/// Exploitability in bb per 100 decisions of this kind (what the plan's gate counts).
pub fn exploit_bb_per_100(&self) -> Option<f64> {
self.exploit.map(|e| e.total / self.big_blind * 100.0)
}
}
/// The result of deciding one hand from a `Solved`.
pub struct TurnSolved {
pub decision: Decision,
/// Hero's action probabilities for the real hand at the real node, and the actions they stand for.
pub row: Vec<f64>,
pub acts: Vec<Act>,
pub solved: Arc<Solved>,
}
/// The turn line so far for hero and `villain`: who acted first (0 = hero), the forced actions and the
/// street contributions. Falls back to "villain bet `to_call`" / "hero first" without a history.
fn turn_line(spot: &Spot, villain: &Villain) -> (usize, Vec<Act>, [f64; 2]) {
let mut first = None;
let mut acts = Vec::new();
let mut c = [0.0f64, 0.0];
let mut aggressed = false;
for r in spot.history.iter().filter(|r| r.street == Street::Turn) {
let who = if r.seat == spot.hero_seat {
0
} else if r.seat == villain.seat {
1
} else {
continue;
};
first.get_or_insert(who);
let amount = r.amount.unwrap_or(c[who]);
match r.action {
SeenAction::Check => acts.push(Act::Check),
SeenAction::Bet | SeenAction::Raise | SeenAction::AllIn if amount > c[1 - who] => {
acts.push(if aggressed { Act::Raise(amount) } else { Act::Bet(amount) });
aggressed = true;
c[who] = amount;
}
SeenAction::Call | SeenAction::AllIn => {
acts.push(Act::Call);
c[who] = c[1 - who];
}
_ => {}
}
}
let consistent = (c[1] - c[0] - spot.to_call).abs() < 1e-6 * spot.pot.max(1.0);
match first {
Some(f) if consistent => (f, acts, c),
_ if spot.to_call > 0.0 => (1, vec![Act::Bet(spot.to_call)], [0.0, spot.to_call]),
_ => (0, Vec::new(), [0.0, 0.0]),
}
}
/// Masks and weights of a combo list: off the board, the `max` heaviest, `keep` (hero's hand) always in.
fn prune(list: &[(Vec<Card>, f64)], board: u64, cfg: &TurnConfig, keep: Option<u64>) -> Hands {
let mut v: Vec<(u64, f64)> = list
.iter()
.filter(|(c, w)| c.len() == 2 && *w > 0.0 && w.is_finite())
.map(|(c, w)| (fast7::mask(c), *w))
.filter(|(m, _)| m & board == 0 && m.count_ones() == 2)
.collect();
v.sort_by(|a, b| b.1.total_cmp(&a.1).then(a.0.cmp(&b.0)));
v.dedup_by_key(|x| x.0);
let top = v.first().map_or(1.0, |x| x.1);
let kept = keep.and_then(|k| v.iter().position(|x| x.0 == k).map(|i| v[i].1));
let total: f64 = v.iter().map(|x| x.1).sum();
let mut acc = 0.0;
let enough = v
.iter()
.position(|x| {
acc += x.1;
acc >= cfg.cover * total
})
.map_or(v.len(), |i| i + 1);
v.truncate(enough.min(cfg.max_combos).max(1));
if let Some(k) = keep {
if !v.iter().any(|x| x.0 == k) {
// Pruned away, or not in the blueprint range at all: stays in with the weight it had, else
// a token weight, so the game has a strategy for it without moving the equilibrium.
v.push((k, kept.unwrap_or(top * 1e-6)));
}
}
Hands { masks: v.iter().map(|x| x.0).collect(), weights: v.iter().map(|x| x.1).collect() }
}
/// Solve the game of `spot`'s public state with these weighted ranges. `keep`: a hero hand that must
/// be in the game whatever the pruning. `None` outside a heads-up turn decision or when the line
/// leaves the tree.
fn solve_core(spot: &Spot, hero: &[(Vec<Card>, f64)], villain_list: &[(Vec<Card>, f64)], cfg: &TurnConfig, keep: Option<u64>) -> Option<Solved> {
if spot.street != Street::Turn || spot.board.len() != 4 || spot.live_villains().count() != 1 {
return None;
}
let villain = spot.live_villains().next()?;
let (first, forced, c) = turn_line(spot, villain);
let pot = spot.pot - c[0] - c[1];
let stack = (spot.hero_stack + c[0]).min(villain.stack + c[1]);
if pot <= 0.0 || stack <= c[0].max(c[1]) {
return None;
}
let started = std::time::Instant::now();
let board = fast7::mask(&spot.board);
let hands = [prune(hero, board, cfg, keep), prune(villain_list, board, cfg, None)];
if hands[0].masks.is_empty() || hands[1].masks.is_empty() {
return None;
}
let mut bets = TrBets::standard(pot, stack, first);
bets.river.max_raises = cfg.river_raises;
let game = build(&bets, &forced);
let at = game.at?;
if !matches!(game.nodes.get(at), Some(TNode::Dec { player: 0, street: 0, .. })) {
return None;
}
let combos = [hands[0].masks.len(), hands[1].masks.len()];
let hero_masks = hands[0].masks.clone();
let acts = game.acts[at].clone();
let nodes = game.nodes.len();
let mut solver = TrSolver::new(game, hands, board, Some(cfg.river_cards));
solver.run(cfg.iterations);
let strategy = solver.strategy();
let exploit = cfg.measure.then(|| solver.exploitability(&strategy));
let rows: Vec<f64> = (0..combos[0]).flat_map(|i| strategy.row(at, 0, i).to_vec()).collect();
let millis = started.elapsed().as_secs_f64() * 1e3;
Some(Solved { rows, acts, hero_masks, millis, combos, nodes, exploit, big_blind: spot.big_blind, pot })
}
/// Hero's decision for the real hand from a solved node.
fn decide_from(spot: &Spot, solved: Arc<Solved>, hero_mask: u64) -> Option<TurnSolved> {
let idx = solved.hero_masks.iter().position(|m| *m == hero_mask)?;
let a = solved.acts.len();
let row = solved.rows[idx * a..(idx + 1) * a].to_vec();
let (draw, _) = Rng::seeded(spot.seed).unit();
let mut acc = 0.0;
let mut pick = row.len().saturating_sub(1);
for (k, p) in row.iter().enumerate() {
acc += p;
if draw < acc {
pick = k;
break;
}
}
let act = *solved.acts.get(pick)?;
let choice = legal_choice(spot, act);
let p = row.get(pick).copied().unwrap_or(0.0);
let decision = Decision::new(
choice,
p.clamp(0.0, 1.0),
format!("turn game: {}x{} combos, {} nodes, {act:?} p {p:.2}, solved in {:.0} ms", solved.combos[0], solved.combos[1], solved.nodes, solved.millis),
);
let acts = solved.acts.clone();
Some(TurnSolved { decision, row, acts, solved })
}
/// Solve the turn for `spot` with these weighted ranges (`hero`, `villain`, as `gewichtete_listen`
/// gives them) and decide; no cache. `None` outside a heads-up turn decision or off the tree.
pub fn solve_turn(spot: &Spot, hero: &[(Vec<Card>, f64)], villain_list: &[(Vec<Card>, f64)], cfg: &TurnConfig) -> Option<TurnSolved> {
if spot.hero_cards.len() != 2 {
return None;
}
let hero_mask = fast7::mask(&spot.hero_cards);
if hero_mask & fast7::mask(&spot.board) != 0 {
return None;
}
let solved = solve_core(spot, hero, villain_list, cfg, Some(hero_mask))?;
decide_from(spot, Arc::new(solved), hero_mask)
}
static CACHE: Mutex<Option<HashMap<u64, Arc<Solved>>>> = Mutex::new(None);
/// An entry is a few kilobytes (one row of probabilities per hero combo).
const CACHE_MAX: usize = 4096;
/// Identity of the public state and the solve budget (not hero's cards).
fn public_key(spot: &Spot, cfg: &TurnConfig) -> u64 {
let mut h = std::collections::hash_map::DefaultHasher::new();
format!("{:?}", spot.history).hash(&mut h);
format!("{:?}", spot.board).hash(&mut h);
[spot.pot, spot.to_call, spot.hero_stack, spot.big_blind].iter().for_each(|x| x.to_bits().hash(&mut h));
spot.live_villains().for_each(|v| (v.seat, v.stack.to_bits()).hash(&mut h));
(spot.hero_seat, cfg.max_combos, cfg.cover.to_bits(), cfg.river_cards, cfg.iterations, cfg.measure, cfg.river_raises).hash(&mut h);
h.finish()
}
/// The live decision: the turn game with ranges from the blueprint, or `None` (switch off, not a
/// blueprint spot, ...) and the heuristic keeps the decision.
pub fn turn_game_decision(spot: &Spot) -> Option<Decision> {
if turn_player() == TurnPlayer::Off || spot.street != Street::Turn || spot.hero_cards.len() != 2 {
return None;
}
let cfg = TurnConfig::from_env();
let hero_mask = fast7::mask(&spot.hero_cards);
if hero_mask & fast7::mask(&spot.board) != 0 {
return None;
}
let key = public_key(spot, &cfg);
let cached = CACHE.lock().ok()?.as_ref().and_then(|m| m.get(&key).cloned());
let solved = match cached {
Some(s) => s,
None => {
let (hero, villain) = crate::blueprint::ranges::gewichtete_listen_offen(spot)?;
let solved = Arc::new(solve_core(spot, &hero, &villain, &cfg, None)?);
if let Ok(mut m) = CACHE.lock() {
let map = m.get_or_insert_with(HashMap::new);
if map.len() >= CACHE_MAX {
map.clear();
}
map.insert(key, solved.clone());
}
solved
}
};
// A hero hand outside the pruned range (low weight at this node, or not in the blueprint range at
// all) is not in the game: `None`, the heuristic plays it.
decide_from(spot, solved, hero_mask).map(|d| d.decision)
}
#[cfg(test)]
mod tests;
//! The turn re-solved at the table over real hands (plan E3, layer 2): both ranges from the
//! blueprint (`blueprint::ranges`, carried along the line actually played), the turn betting and
//! the river inside one game (`cfr::turn_river_game`), hero's equilibrium action at the real node.
//!
//! Switch: `TurnPlayer::Grund` (default `Off`; `ab_zelle` / `engine_lbr`: `TURN_SPIEL=grund`). Off,
//! `turn_game_decision` returns `None` before it looks at anything, so the engine's output is
//! unchanged. On, it plays only where the blueprint recognises the spot (S1: button open, big blind
//! call, about 100 bb, heads-up on the turn, hero at a decision); everywhere else the heuristic plays.
//!
//! The solve depends on the public state only (board, line, pot, stacks): the villain's range is NOT
//! conditioned on hero's real cards (`gewichtete_listen_offen`; the game deals card removal itself),
//! so one solve serves every hero hand at the same node. Solves are cached by public state (a
//! measurement that asks the engine for every hand of a range, as LBR does, pays one solve per node).
//!
//! Approximations (named, each a knob of `TurnConfig`): ranges are pruned to the `max_combos`
//! heaviest combos per player; the river is enumerated over `river_cards` evenly strided cards, each
//! standing for its share (`cfr::turn_river_game`); the bet menu is `TrBets::standard` plus the
//! observed size; the solve is a fixed `iterations` of CFR+. Hero's real hand, if pruned away or
//! outside the blueprint range, is put back with its weight (or a token weight) in an uncached solve.
use crate::card::Card;
use crate::cfr::river_game::Act;
use crate::cfr::turn_river_game::{build, Exploit, Hands, TNode, TrBets, TrSolver};
use crate::engine::river_subgame::legal_choice;
use crate::game::{Decision, SeenAction, Spot, Street, Villain};
use crate::hand::fast7;
use crate::rng::Rng;
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::sync::{Arc, Mutex};
static MODE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
/// Who plays the heads-up turn.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TurnPlayer {
/// The heuristic (default).
Off,
/// The turn+river game with both ranges from the blueprint; only where the spot is a blueprint
/// scenario, else the heuristic plays.
Grund,
}
pub fn set_turn_player(mode: TurnPlayer) {
MODE.store(u8::from(mode == TurnPlayer::Grund), std::sync::atomic::Ordering::Relaxed);
}
pub fn turn_player() -> TurnPlayer {
if MODE.load(std::sync::atomic::Ordering::Relaxed) == 1 {
TurnPlayer::Grund
} else {
TurnPlayer::Off
}
}
/// Size and budget of the solve.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct TurnConfig {
/// Most combos per player (heaviest by weight).
pub max_combos: usize,
/// Stop adding combos once this share of the range mass is in (before `max_combos`).
pub cover: f64,
/// River cards enumerated (of 48).
pub river_cards: usize,
/// CFR+ iterations.
pub iterations: u32,
/// Also compute the best-response exploitability of the result (about two more iterations).
pub measure: bool,
/// Raises allowed after a river bet (0 or 1).
pub river_raises: usize,
/// Wall-time budget in ms (0 = none, run all `iterations`); a budgeted solve that stops under
/// `MIN_ITERS` returns `None` and the heuristic decides.
pub budget_ms: f64,
}
/// Fewest iterations a budgeted solve may decide with.
pub const MIN_ITERS: u32 = 60;
/// Stage B's per-decision budget (all solves of one decision together).
pub const STAGE_B_BUDGET_MS: f64 = 1700.0;
impl TurnConfig {
pub const STANDARD: TurnConfig = TurnConfig { max_combos: 160, cover: 0.95, river_cards: 10, iterations: 200, measure: false, river_raises: 0, budget_ms: 0.0 };
/// `STANDARD` with `TURN_COMBOS`, `TURN_CARDS`, `TURN_ITERS`, `TURN_EXPLOIT=1` from the environment.
pub fn from_env() -> TurnConfig {
let num = |k: &str, d: usize| std::env::var(k).ok().and_then(|s| s.parse().ok()).filter(|n| *n > 0).unwrap_or(d);
TurnConfig {
max_combos: num("TURN_COMBOS", Self::STANDARD.max_combos),
cover: num("TURN_COVER", 95) as f64 / 100.0,
river_cards: num("TURN_CARDS", Self::STANDARD.river_cards),
iterations: num("TURN_ITERS", Self::STANDARD.iterations as usize) as u32,
measure: std::env::var("TURN_EXPLOIT").as_deref() == Ok("1"),
river_raises: std::env::var("TURN_RIVER_RAISES").ok().and_then(|s| s.parse().ok()).map_or(Self::STANDARD.river_raises, |n: usize| n.min(1)),
budget_ms: Self::STANDARD.budget_ms,
}
}
}
/// One solved node of the game: what every hero hand at this public state shares.
pub struct Solved {
/// Hero's turn-node action probabilities, `hero_masks.len()` rows of `acts.len()`.
rows: Vec<f64>,
acts: Vec<Act>,
hero_masks: Vec<u64>,
pub millis: f64,
pub combos: [usize; 2],
pub nodes: usize,
/// Best-response exploitability of the solved game, chips per deal (when `measure`).
pub exploit: Option<Exploit>,
pub big_blind: f64,
pub pot: f64,
}
impl Solved {
/// Exploitability in bb per 100 decisions of this kind (what the plan's gate counts).
pub fn exploit_bb_per_100(&self) -> Option<f64> {
self.exploit.map(|e| e.total / self.big_blind * 100.0)
}
}
/// The result of deciding one hand from a `Solved`.
pub struct TurnSolved {
pub decision: Decision,
/// Hero's action probabilities for the real hand at the real node, and the actions they stand for.
pub row: Vec<f64>,
pub acts: Vec<Act>,
pub solved: Arc<Solved>,
}
/// The turn line so far for hero and `villain`: who acted first (0 = hero), the forced actions and the
/// street contributions. Falls back to "villain bet `to_call`" / "hero first" without a history.
pub(crate) fn turn_line(spot: &Spot, villain: &Villain) -> (usize, Vec<Act>, [f64; 2]) {
street_line(spot, villain, Street::Turn)
}
/// The line of `street` so far (as `turn_line`).
pub(crate) fn street_line(spot: &Spot, villain: &Villain, street: Street) -> (usize, Vec<Act>, [f64; 2]) {
let mut first = None;
let mut acts = Vec::new();
let mut c = [0.0f64, 0.0];
let mut aggressed = false;
for r in spot.history.iter().filter(|r| r.street == street) {
let who = if r.seat == spot.hero_seat {
0
} else if r.seat == villain.seat {
1
} else {
continue;
};
first.get_or_insert(who);
let amount = r.amount.unwrap_or(c[who]);
match r.action {
SeenAction::Check => acts.push(Act::Check),
SeenAction::Bet | SeenAction::Raise | SeenAction::AllIn if amount > c[1 - who] => {
acts.push(if aggressed { Act::Raise(amount) } else { Act::Bet(amount) });
aggressed = true;
c[who] = amount;
}
SeenAction::Call | SeenAction::AllIn => {
acts.push(Act::Call);
c[who] = c[1 - who];
}
_ => {}
}
}
let consistent = (c[1] - c[0] - spot.to_call).abs() < 1e-6 * spot.pot.max(1.0);
match first {
Some(f) if consistent => (f, acts, c),
_ if spot.to_call > 0.0 => (1, vec![Act::Bet(spot.to_call)], [0.0, spot.to_call]),
_ => (0, Vec::new(), [0.0, 0.0]),
}
}
/// Masks and weights of a combo list: off the board, the `max` heaviest, `keep` (hero's hand) always in.
pub(crate) fn prune(list: &[(Vec<Card>, f64)], board: u64, cfg: &TurnConfig, keep: Option<u64>) -> Hands {
let mut v: Vec<(u64, f64)> = list
.iter()
.filter(|(c, w)| c.len() == 2 && *w > 0.0 && w.is_finite())
.map(|(c, w)| (fast7::mask(c), *w))
.filter(|(m, _)| m & board == 0 && m.count_ones() == 2)
.collect();
v.sort_by(|a, b| b.1.total_cmp(&a.1).then(a.0.cmp(&b.0)));
v.dedup_by_key(|x| x.0);
let top = v.first().map_or(1.0, |x| x.1);
let kept = keep.and_then(|k| v.iter().position(|x| x.0 == k).map(|i| v[i].1));
let total: f64 = v.iter().map(|x| x.1).sum();
let mut acc = 0.0;
let enough = v
.iter()
.position(|x| {
acc += x.1;
acc >= cfg.cover * total
})
.map_or(v.len(), |i| i + 1);
v.truncate(enough.min(cfg.max_combos).max(1));
if let Some(k) = keep {
if !v.iter().any(|x| x.0 == k) {
// Pruned away, or not in the blueprint range at all: stays in with the weight it had, else
// a token weight, so the game has a strategy for it without moving the equilibrium.
v.push((k, kept.unwrap_or(top * 1e-6)));
}
}
Hands { masks: v.iter().map(|x| x.0).collect(), weights: v.iter().map(|x| x.1).collect() }
}
/// Solve the game of `spot`'s public state with these weighted ranges. `keep`: a hero hand that must
/// be in the game whatever the pruning. `None` outside a heads-up turn decision or when the line
/// leaves the tree.
fn solve_core(spot: &Spot, hero: &[(Vec<Card>, f64)], villain_list: &[(Vec<Card>, f64)], cfg: &TurnConfig, keep: Option<u64>) -> Option<Solved> {
if spot.street != Street::Turn || spot.board.len() != 4 || spot.live_villains().count() != 1 {
return None;
}
let villain = spot.live_villains().next()?;
let (first, forced, c) = turn_line(spot, villain);
let pot = spot.pot - c[0] - c[1];
let stack = (spot.hero_stack + c[0]).min(villain.stack + c[1]);
if pot <= 0.0 || stack <= c[0].max(c[1]) {
return None;
}
let started = std::time::Instant::now();
let board = fast7::mask(&spot.board);
let hands = [prune(hero, board, cfg, keep), prune(villain_list, board, cfg, None)];
if hands[0].masks.is_empty() || hands[1].masks.is_empty() {
return None;
}
let mut bets = TrBets::standard(pot, stack, first);
bets.river.max_raises = cfg.river_raises;
let game = build(&bets, &forced);
let at = game.at?;
if !matches!(game.nodes.get(at), Some(TNode::Dec { player: 0, street: 0, .. })) {
return None;
}
let combos = [hands[0].masks.len(), hands[1].masks.len()];
let hero_masks = hands[0].masks.clone();
let acts = game.acts[at].clone();
let nodes = game.nodes.len();
let mut solver = TrSolver::new(game, hands, board, Some(cfg.river_cards));
if cfg.budget_ms > 0.0 {
let mut done = 0;
while done < cfg.iterations {
solver.iterate();
done += 1;
if done % 5 == 0 && started.elapsed().as_secs_f64() * 1e3 > cfg.budget_ms {
break;
}
}
if done < MIN_ITERS {
return None;
}
} else {
solver.run(cfg.iterations);
}
let strategy = solver.strategy();
let exploit = cfg.measure.then(|| solver.exploitability(&strategy));
let rows: Vec<f64> = (0..combos[0]).flat_map(|i| strategy.row(at, 0, i).to_vec()).collect();
let millis = started.elapsed().as_secs_f64() * 1e3;
Some(Solved { rows, acts, hero_masks, millis, combos, nodes, exploit, big_blind: spot.big_blind, pot })
}
/// Hero's decision for the real hand from a solved node.
fn decide_from(spot: &Spot, solved: Arc<Solved>, hero_mask: u64) -> Option<TurnSolved> {
let idx = solved.hero_masks.iter().position(|m| *m == hero_mask)?;
let a = solved.acts.len();
let row = solved.rows[idx * a..(idx + 1) * a].to_vec();
let (draw, _) = Rng::seeded(spot.seed).unit();
let mut acc = 0.0;
let mut pick = row.len().saturating_sub(1);
for (k, p) in row.iter().enumerate() {
acc += p;
if draw < acc {
pick = k;
break;
}
}
let act = *solved.acts.get(pick)?;
let choice = legal_choice(spot, act);
let p = row.get(pick).copied().unwrap_or(0.0);
let decision = Decision::new(
choice,
p.clamp(0.0, 1.0),
format!("turn game: {}x{} combos, {} nodes, {act:?} p {p:.2}, solved in {:.0} ms", solved.combos[0], solved.combos[1], solved.nodes, solved.millis),
);
let acts = solved.acts.clone();
Some(TurnSolved { decision, row, acts, solved })
}
/// Solve the turn for `spot` with these weighted ranges (`hero`, `villain`, as `gewichtete_listen`
/// gives them) and decide; no cache. `None` outside a heads-up turn decision or off the tree.
pub fn solve_turn(spot: &Spot, hero: &[(Vec<Card>, f64)], villain_list: &[(Vec<Card>, f64)], cfg: &TurnConfig) -> Option<TurnSolved> {
if spot.hero_cards.len() != 2 {
return None;
}
let hero_mask = fast7::mask(&spot.hero_cards);
if hero_mask & fast7::mask(&spot.board) != 0 {
return None;
}
let solved = solve_core(spot, hero, villain_list, cfg, Some(hero_mask))?;
decide_from(spot, Arc::new(solved), hero_mask)
}
static CACHE: Mutex<Option<HashMap<u64, Arc<Solved>>>> = Mutex::new(None);
/// An entry is a few kilobytes (one row of probabilities per hero combo).
const CACHE_MAX: usize = 4096;
/// Identity of the public state and the solve budget (not hero's cards).
fn public_key(spot: &Spot, cfg: &TurnConfig) -> u64 {
let mut h = std::collections::hash_map::DefaultHasher::new();
format!("{:?}", spot.history).hash(&mut h);
format!("{:?}", spot.board).hash(&mut h);
[spot.pot, spot.to_call, spot.hero_stack, spot.big_blind].iter().for_each(|x| x.to_bits().hash(&mut h));
spot.live_villains().for_each(|v| (v.seat, v.stack.to_bits()).hash(&mut h));
(spot.hero_seat, cfg.max_combos, cfg.cover.to_bits(), cfg.river_cards, cfg.iterations, cfg.measure, cfg.river_raises).hash(&mut h);
h.finish()
}
/// The live decision: the turn game with ranges from the blueprint, or `None` (switch off, not a
/// blueprint spot, ...) and the heuristic keeps the decision.
pub fn turn_game_decision(spot: &Spot) -> Option<Decision> {
if turn_player() == TurnPlayer::Off || spot.street != Street::Turn || spot.hero_cards.len() != 2 {
return None;
}
let cfg = TurnConfig::from_env();
let hero_mask = fast7::mask(&spot.hero_cards);
if hero_mask & fast7::mask(&spot.board) != 0 {
return None;
}
let key = public_key(spot, &cfg);
let cached = CACHE.lock().ok()?.as_ref().and_then(|m| m.get(&key).cloned());
let solved = match cached {
Some(s) => s,
None => {
let (hero, villain) = crate::blueprint::ranges::gewichtete_listen_offen(spot)?;
let solved = Arc::new(solve_core(spot, &hero, &villain, &cfg, None)?);
if let Ok(mut m) = CACHE.lock() {
let map = m.get_or_insert_with(HashMap::new);
if map.len() >= CACHE_MAX {
map.clear();
}
map.insert(key, solved.clone());
}
solved
}
};
// A hero hand outside the pruned range (low weight at this node, or not in the blueprint range at
// all) is not in the game: `None`, the heuristic plays it.
decide_from(spot, solved, hero_mask).map(|d| d.decision)
}
// --- Stage B of "solver everywhere" (switch SOLVER_TURN, default off) ---
static UEBERALL: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
/// Stage B: the turn game decides every heads-up Hold'em turn, not only blueprint scenarios. Ranges
/// from the blueprint where it recognises the spot, else from the range model of the action history
/// (`river_spieler::model_lists`: hero's line without a read, the villain's with its gated read).
pub fn set_turn_ueberall(on: bool) {
UEBERALL.store(on, std::sync::atomic::Ordering::Relaxed);
}
pub fn turn_ueberall() -> bool {
UEBERALL.load(std::sync::atomic::Ordering::Relaxed)
}
/// `SOLVER_TURN=1`.
pub fn turn_ueberall_from_env() -> bool {
matches!(std::env::var("SOLVER_TURN").as_deref(), Ok("1") | Ok("an"))
}
/// The stage-B decision for `raw` (ungated reads; the villain range uses the gated ones), or `None`
/// (switch off, not a heads-up Hold'em turn, off the tree) and the heuristic keeps the decision. A hero
/// hand outside the pruned range gets an uncached solve with the hand in it (live asks once per
/// decision, so this is the normal live cost).
pub fn turn_solver_decision(raw: &Spot) -> Option<Decision> {
if !turn_ueberall() || raw.street != Street::Turn || raw.hero_cards.len() != 2 || raw.board.len() != 4 {
return None;
}
let gated = crate::engine::read_gate::gate_reads(raw);
let spot = &gated;
if spot.live_villains().count() != 1 {
return None;
}
let begun = std::time::Instant::now();
let cfg = TurnConfig { budget_ms: STAGE_B_BUDGET_MS, ..TurnConfig::from_env() };
let hero_mask = fast7::mask(&spot.hero_cards);
if hero_mask & fast7::mask(&spot.board) != 0 {
return None;
}
let read = crate::engine::river_spieler::read_of(raw);
let lists = || crate::engine::river_spieler::solver_lists(spot, crate::engine::river_spieler::RiverSpieler::An, read.as_ref());
let raw_profile = read.as_ref().map(|_| format!("{:?}", raw.live_villains().next().map(|v| v.profile.clone())));
let mut key_h = std::collections::hash_map::DefaultHasher::new();
(public_key(spot, &cfg), "ueberall").hash(&mut key_h);
spot.live_villains().for_each(|v| format!("{:?}", v.profile).hash(&mut key_h));
raw_profile.hash(&mut key_h);
let key = key_h.finish();
let cached = CACHE.lock().ok().and_then(|m| m.as_ref().and_then(|m| m.get(&key).cloned()));
let mut source = "";
let solved = match cached {
Some(s) => s,
None => {
let (hero, villain, src) = lists()?;
source = src;
let solved = Arc::new(solve_core(spot, &hero, &villain, &cfg, None)?);
if let Ok(mut m) = CACHE.lock() {
let map = m.get_or_insert_with(HashMap::new);
if map.len() >= CACHE_MAX {
map.clear();
}
map.insert(key, solved.clone());
}
solved
}
};
let tag = |mut d: Decision, src: &str| {
d.reason = format!("solver turn ({}) {}", if src.is_empty() { "cache" } else { src }, d.reason);
d
};
if let Some(t) = decide_from(spot, solved, hero_mask) {
return Some(tag(t.decision, source));
}
// Hero's hand was pruned away: one more solve with it kept, in what is left of the budget.
let left = STAGE_B_BUDGET_MS - begun.elapsed().as_secs_f64() * 1e3;
if left <= 0.0 {
return None;
}
let (hero, villain, src) = lists()?;
solve_turn(spot, &hero, &villain, &TurnConfig { budget_ms: left, ..cfg }).map(|t| tag(t.decision, src))
}
#[cfg(test)]
mod tests;
+265 -242
View File
@@ -1,242 +1,265 @@
use super::*;
use crate::card::Card;
use crate::game::{ActionKind, ActionRecord, Choice, SeenAction, Spot, Street, Villain};
use crate::variant::Variant;
use std::sync::Mutex;
/// The switch is process-global: tests that touch it take turns.
static MODE_LOCK: Mutex<()> = Mutex::new(());
fn rec(street: Street, seat: u8, action: SeenAction, amount: Option<f64>) -> ActionRecord {
ActionRecord { street, seat, action, amount }
}
/// Six-max S1 line to the turn: button (seat 4) opens 2.5, big blind (seat 0) calls; flop check, bet 1.8,
/// call. Turn pot 9.1. `turn` is the turn line so far; hero is the button.
fn s1_turn(turn: &[ActionRecord], hero: &str, to_call: f64, pot_extra: f64) -> Spot {
use SeenAction::*;
use Street::*;
let mut h = vec![
rec(Preflop, 5, PostSmallBlind, Some(0.5)),
rec(Preflop, 0, PostBigBlind, Some(1.0)),
rec(Preflop, 1, Fold, None),
rec(Preflop, 2, Fold, None),
rec(Preflop, 3, Fold, None),
rec(Preflop, 4, Raise, Some(2.5)),
rec(Preflop, 5, Fold, None),
rec(Preflop, 0, Call, Some(2.5)),
rec(Flop, 0, Check, None),
rec(Flop, 4, Bet, Some(1.8)),
rec(Flop, 0, Call, Some(1.8)),
];
h.extend_from_slice(turn);
let legal = if to_call > 0.0 { vec![ActionKind::Fold, ActionKind::Call, ActionKind::Raise] } else { vec![ActionKind::Check, ActionKind::Raise] };
Spot {
variant: Variant::Nlhe,
big_blind: 1.0,
seats: 6,
hero_seat: 4,
button_seat: Some(4),
hero_cards: Card::parse_list(hero).unwrap(),
board: Card::parse_list("Ah 7d 2c Ks").unwrap(),
street: Street::Turn,
pot: 9.1 + pot_extra,
to_call,
hero_stack: 95.7,
min_raise_to: Some(if to_call > 0.0 { 2.0 * to_call } else { 1.0 }),
max_raise_to: Some(95.7),
legal,
allowed_sizes: None,
villains: vec![Villain { seat: 0, stack: 95.7 - to_call, folded: false, profile: None }],
seed: 7,
history: h,
}
}
fn facing_bet(hero: &str) -> Spot {
s1_turn(&[rec(Street::Turn, 0, SeenAction::Bet, Some(6.0))], hero, 6.0, 6.0)
}
fn hero_first(hero: &str) -> Spot {
// Hero on the button would be last to act; here villain checks and hero decides.
s1_turn(&[rec(Street::Turn, 0, SeenAction::Check, None)], hero, 0.0, 0.0)
}
/// A range of `n` combos off the board (and `avoid`), pseudo-random, weights 0.2..1.2; always includes `must`.
fn range(n: usize, seed: u64, must: &[&str]) -> Vec<(Vec<Card>, f64)> {
let all = Card::parse_list("2c 3c 4c 5c 6c 7c 8c 9c Tc Jc Qc Kc Ac 2d 3d 4d 5d 6d 7d 8d 9d Td Jd Qd Kd Ad 2h 3h 4h 5h 6h 7h 8h 9h Th Jh Qh Kh Ah 2s 3s 4s 5s 6s 7s 8s 9s Ts Js Qs Ks As").unwrap();
let board = Card::parse_list("Ah 7d 2c Ks").unwrap();
let cards: Vec<Card> = all.into_iter().filter(|c| !board.contains(c)).collect();
let mut x = seed;
let mut next = || {
x = x.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
(x >> 33) as usize
};
let mut out: Vec<(Vec<Card>, f64)> = must.iter().map(|m| (Card::parse_list(m).unwrap(), 1.0)).collect();
while out.len() < n {
let (a, b) = (cards[next() % cards.len()], cards[next() % cards.len()]);
if a != b && !out.iter().any(|(c, _)| c.contains(&a) && c.contains(&b)) {
out.push((vec![a, b], 0.2 + (next() % 1000) as f64 / 1000.0));
}
}
out
}
fn cfg(iterations: u32) -> TurnConfig {
TurnConfig { max_combos: 200, cover: 1.0, river_cards: 12, iterations, measure: true, river_raises: 1 }
}
#[test]
fn the_decision_is_a_legal_choice_at_both_kinds_of_node() {
let hands = ["Ac Qd", "7h 7c", "3c 4d", "Kd Qs", "9h 8h"];
for (spot_of, name) in [(facing_bet as fn(&str) -> Spot, "facing a bet"), (hero_first as fn(&str) -> Spot, "first to act")] {
for hero in hands {
let spot = spot_of(hero);
let villain = range(80, 5, &[]);
let me = range(80, 6, &[hero]);
let s = solve_turn(&spot, &me, &villain, &cfg(60)).expect("heads-up turn decision is in scope");
let sum: f64 = s.row.iter().sum();
assert!((sum - 1.0).abs() < 1e-9, "{name} {hero}: row {:?}", s.row);
match s.decision.choice {
Choice::Fold => assert!(spot.to_call > 0.0, "{name}: fold only when facing a bet"),
Choice::Check => assert_eq!(spot.to_call, 0.0, "{name}"),
Choice::Call => assert!(spot.to_call > 0.0, "{name}"),
Choice::Raise { to } => {
let (lo, hi) = (spot.min_raise_to.unwrap(), spot.max_raise_to.unwrap());
assert!(to >= lo - 1e-9 && to <= hi + 1e-9, "{name} {hero}: raise to {to} outside [{lo}, {hi}]");
}
Choice::Abstain => panic!("{name} {hero}: abstained"),
}
assert!(spot.is_legal(match s.decision.choice {
Choice::Fold => ActionKind::Fold,
Choice::Check => ActionKind::Check,
Choice::Call => ActionKind::Call,
_ => ActionKind::Raise,
}));
}
}
}
#[test]
fn out_of_position_hero_acts_first_with_check_or_a_bet() {
// Hero is the big blind (seat 0) and acts first on the turn; the villain is the button (seat 4).
let mut spot = s1_turn(&[], "Ac Qd", 0.0, 0.0);
spot.hero_seat = 0;
spot.villains = vec![Villain { seat: 4, stack: 95.7, folded: false, profile: None }];
let (me, villain) = (range(60, 51, &["Ac Qd"]), range(60, 52, &[]));
let s = solve_turn(&spot, &me, &villain, &cfg(80)).expect("hero first");
assert_eq!(s.acts[0], Act::Check, "check is the first action at a free node: {:?}", s.acts);
assert!(s.acts.iter().skip(1).all(|a| matches!(a, Act::Bet(_))));
assert!(matches!(s.decision.choice, Choice::Check | Choice::Raise { .. }));
if let Choice::Raise { to } = s.decision.choice {
assert!(to >= spot.min_raise_to.unwrap() - 1e-9 && to <= spot.max_raise_to.unwrap() + 1e-9);
}
}
#[test]
fn strong_hands_do_not_fold_and_air_folds_more() {
// The villain's range: top pair or better only (aces, kings, pairs of 7 and 2).
let villain: Vec<(Vec<Card>, f64)> = range(400, 21, &[]).into_iter().filter(|(c, _)| c.iter().any(|x| x.rank as u8 >= 11) || c[0].rank == c[1].rank).collect();
assert!(villain.len() > 30, "{}", villain.len());
let me = range(100, 22, &["7s 7c", "3c 4d"]);
let spot_set = facing_bet("7s 7c");
let spot_air = facing_bet("3c 4d");
let set = solve_turn(&spot_set, &me, &villain, &cfg(150)).unwrap();
let air = solve_turn(&spot_air, &me, &villain, &cfg(150)).unwrap();
eprintln!("set row {:?}, air row {:?} ({:?})", set.row, air.row, set.acts);
assert!(set.row[0] < 0.05, "a set never folds to a half-pot bet here: {:?}", set.row);
assert!(air.row[0] > set.row[0] + 0.3, "air folds clearly more: {:?} vs {:?}", air.row, set.row);
}
#[test]
fn the_solve_is_deterministic_and_the_game_is_balanced_enough() {
let spot = facing_bet("Ac Qd");
let (me, villain) = (range(150, 31, &["Ac Qd"]), range(150, 32, &[]));
let a = solve_turn(&spot, &me, &villain, &cfg(200)).unwrap();
let b = solve_turn(&spot, &me, &villain, &cfg(200)).unwrap();
assert_eq!(a.row, b.row);
assert_eq!(a.decision.choice, b.decision.choice, "same input, same answer");
let e = a.solved.exploit.expect("measured");
eprintln!("150x150 combos, 12 river cards, 200 iterations: {:.0} ms, exploitability {:.3} chips = {:.1} % of the {:.1} pot = {:.0} bb/100 (hero at the real node)", a.solved.millis, e.total, e.total / a.solved.pot * 100.0, a.solved.pot, a.solved.exploit_bb_per_100().unwrap());
assert!(e.total < 0.05 * a.solved.pot, "exploitability {} on a {} pot", e.total, a.solved.pot);
}
#[test]
fn a_spot_outside_the_game_is_left_to_the_heuristic() {
let me = range(50, 1, &["Ac Qd"]);
let villain = range(50, 2, &[]);
let mut river = facing_bet("Ac Qd");
river.street = Street::River;
river.board = Card::parse_list("Ah 7d 2c Ks 9h").unwrap();
assert!(solve_turn(&river, &me, &villain, &cfg(10)).is_none());
let mut multiway = facing_bet("Ac Qd");
multiway.villains.push(Villain { seat: 1, stack: 90.0, folded: false, profile: None });
assert!(solve_turn(&multiway, &me, &villain, &cfg(10)).is_none());
assert!(solve_turn(&facing_bet("Ac Qd"), &me, &[], &cfg(10)).is_none(), "no villain range");
}
#[test]
fn off_means_none_and_the_engine_is_unchanged() {
let _g = MODE_LOCK.lock().unwrap_or_else(|e| e.into_inner());
set_turn_player(TurnPlayer::Off);
let spots = [facing_bet("Ac Qd"), facing_bet("7s 7c"), hero_first("3c 4d"), hero_first("Kd Qs")];
let mut flop = hero_first("Ac Qd");
flop.street = Street::Flop;
flop.board.truncate(3);
let mut river = facing_bet("Ac Qd");
river.street = Street::River;
river.board = Card::parse_list("Ah 7d 2c Ks 9h").unwrap();
for spot in spots.iter().chain([&flop, &river]) {
assert!(turn_game_decision(spot).is_none(), "off: the hook says nothing");
}
// Switched on without a blueprint (no GRUNDSTRATEGIE) the hook still says nothing, so the engine's
// answer is the same either way: compare whole decisions.
if std::env::var_os("GRUNDSTRATEGIE").is_none() {
let off: Vec<_> = spots.iter().chain([&flop, &river]).map(crate::engine::decide::decide).collect();
set_turn_player(TurnPlayer::Grund);
let on: Vec<_> = spots.iter().chain([&flop, &river]).map(crate::engine::decide::decide).collect();
set_turn_player(TurnPlayer::Off);
assert_eq!(off, on, "no blueprint: the heuristic plays unchanged");
}
assert_eq!(turn_player(), TurnPlayer::Off);
}
#[test]
fn the_public_key_ignores_hero_cards_but_not_the_line() {
let c = TurnConfig::STANDARD;
assert_eq!(public_key(&facing_bet("Ac Qd"), &c), public_key(&facing_bet("7s 7c"), &c));
assert_ne!(public_key(&facing_bet("Ac Qd"), &c), public_key(&hero_first("Ac Qd"), &c));
}
#[test]
#[ignore = "timing probe"]
fn tree_sizes() {
use crate::cfr::turn_river_game::{build, TNode, TrBets};
for (name, forced, first) in [("hero first", vec![], 0usize), ("facing bet", vec![Act::Bet(6.0)], 1), ("check-raise spot", vec![Act::Check, Act::Bet(6.0)], 0)] {
let g = build(&TrBets::standard(9.1, 95.0, first), &forced);
let chance = g.nodes.iter().filter(|n| matches!(n, TNode::Chance { .. })).count();
let river_dec = g.nodes.iter().filter(|n| matches!(n, TNode::Dec { street: 1, .. })).count();
let turn_dec = g.nodes.iter().filter(|n| matches!(n, TNode::Dec { street: 0, .. })).count();
eprintln!("{name}: {} nodes, {turn_dec} turn decisions, {chance} river chance nodes, {river_dec} river decisions", g.nodes.len());
}
}
/// Solve time at table size (run with `--ignored --nocapture`).
#[test]
#[ignore = "timing probe"]
fn solve_time_at_table_size() {
for (n, cards, iters, rr) in [(160usize, 10usize, 200u32, 0usize), (160, 10, 400, 0), (160, 10, 200, 1), (100, 10, 200, 0)] {
let spot = facing_bet("Ac Qd");
let (me, villain) = (range(n, 41, &["Ac Qd"]), range(n, 42, &[]));
let c = TurnConfig { max_combos: n, cover: 1.0, river_cards: cards, iterations: iters, measure: true, river_raises: rr };
let s = solve_turn(&spot, &me, &villain, &c).unwrap();
let e = s.solved.exploit.unwrap();
eprintln!(
"{n} combos, {cards} river cards, {iters} iterations, river raises {rr}: {:.0} ms ({} nodes), exploitability {:.2} % of pot = {:.0} bb/100",
s.solved.millis,
s.solved.nodes,
e.total / s.solved.pot * 100.0,
s.solved.exploit_bb_per_100().unwrap()
);
}
}
use super::*;
use crate::card::Card;
use crate::game::{ActionKind, ActionRecord, Choice, SeenAction, Spot, Street, Villain};
use crate::variant::Variant;
use std::sync::Mutex;
/// The switch is process-global: tests that touch it take turns.
static MODE_LOCK: Mutex<()> = Mutex::new(());
fn rec(street: Street, seat: u8, action: SeenAction, amount: Option<f64>) -> ActionRecord {
ActionRecord { street, seat, action, amount }
}
/// Six-max S1 line to the turn: button (seat 4) opens 2.5, big blind (seat 0) calls; flop check, bet 1.8,
/// call. Turn pot 9.1. `turn` is the turn line so far; hero is the button.
fn s1_turn(turn: &[ActionRecord], hero: &str, to_call: f64, pot_extra: f64) -> Spot {
use SeenAction::*;
use Street::*;
let mut h = vec![
rec(Preflop, 5, PostSmallBlind, Some(0.5)),
rec(Preflop, 0, PostBigBlind, Some(1.0)),
rec(Preflop, 1, Fold, None),
rec(Preflop, 2, Fold, None),
rec(Preflop, 3, Fold, None),
rec(Preflop, 4, Raise, Some(2.5)),
rec(Preflop, 5, Fold, None),
rec(Preflop, 0, Call, Some(2.5)),
rec(Flop, 0, Check, None),
rec(Flop, 4, Bet, Some(1.8)),
rec(Flop, 0, Call, Some(1.8)),
];
h.extend_from_slice(turn);
let legal = if to_call > 0.0 { vec![ActionKind::Fold, ActionKind::Call, ActionKind::Raise] } else { vec![ActionKind::Check, ActionKind::Raise] };
Spot {
variant: Variant::Nlhe,
big_blind: 1.0,
seats: 6,
hero_seat: 4,
button_seat: Some(4),
hero_cards: Card::parse_list(hero).unwrap(),
board: Card::parse_list("Ah 7d 2c Ks").unwrap(),
street: Street::Turn,
pot: 9.1 + pot_extra,
to_call,
hero_stack: 95.7,
min_raise_to: Some(if to_call > 0.0 { 2.0 * to_call } else { 1.0 }),
max_raise_to: Some(95.7),
legal,
allowed_sizes: None,
villains: vec![Villain { seat: 0, stack: 95.7 - to_call, folded: false, profile: None }],
seed: 7,
history: h,
}
}
fn facing_bet(hero: &str) -> Spot {
s1_turn(&[rec(Street::Turn, 0, SeenAction::Bet, Some(6.0))], hero, 6.0, 6.0)
}
fn hero_first(hero: &str) -> Spot {
// Hero on the button would be last to act; here villain checks and hero decides.
s1_turn(&[rec(Street::Turn, 0, SeenAction::Check, None)], hero, 0.0, 0.0)
}
/// A range of `n` combos off the board (and `avoid`), pseudo-random, weights 0.2..1.2; always includes `must`.
fn range(n: usize, seed: u64, must: &[&str]) -> Vec<(Vec<Card>, f64)> {
let all = Card::parse_list("2c 3c 4c 5c 6c 7c 8c 9c Tc Jc Qc Kc Ac 2d 3d 4d 5d 6d 7d 8d 9d Td Jd Qd Kd Ad 2h 3h 4h 5h 6h 7h 8h 9h Th Jh Qh Kh Ah 2s 3s 4s 5s 6s 7s 8s 9s Ts Js Qs Ks As").unwrap();
let board = Card::parse_list("Ah 7d 2c Ks").unwrap();
let cards: Vec<Card> = all.into_iter().filter(|c| !board.contains(c)).collect();
let mut x = seed;
let mut next = || {
x = x.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
(x >> 33) as usize
};
let mut out: Vec<(Vec<Card>, f64)> = must.iter().map(|m| (Card::parse_list(m).unwrap(), 1.0)).collect();
while out.len() < n {
let (a, b) = (cards[next() % cards.len()], cards[next() % cards.len()]);
if a != b && !out.iter().any(|(c, _)| c.contains(&a) && c.contains(&b)) {
out.push((vec![a, b], 0.2 + (next() % 1000) as f64 / 1000.0));
}
}
out
}
fn cfg(iterations: u32) -> TurnConfig {
TurnConfig { max_combos: 200, cover: 1.0, river_cards: 12, iterations, measure: true, river_raises: 1, budget_ms: 0.0 }
}
#[test]
fn the_decision_is_a_legal_choice_at_both_kinds_of_node() {
let hands = ["Ac Qd", "7h 7c", "3c 4d", "Kd Qs", "9h 8h"];
for (spot_of, name) in [(facing_bet as fn(&str) -> Spot, "facing a bet"), (hero_first as fn(&str) -> Spot, "first to act")] {
for hero in hands {
let spot = spot_of(hero);
let villain = range(80, 5, &[]);
let me = range(80, 6, &[hero]);
let s = solve_turn(&spot, &me, &villain, &cfg(60)).expect("heads-up turn decision is in scope");
let sum: f64 = s.row.iter().sum();
assert!((sum - 1.0).abs() < 1e-9, "{name} {hero}: row {:?}", s.row);
match s.decision.choice {
Choice::Fold => assert!(spot.to_call > 0.0, "{name}: fold only when facing a bet"),
Choice::Check => assert_eq!(spot.to_call, 0.0, "{name}"),
Choice::Call => assert!(spot.to_call > 0.0, "{name}"),
Choice::Raise { to } => {
let (lo, hi) = (spot.min_raise_to.unwrap(), spot.max_raise_to.unwrap());
assert!(to >= lo - 1e-9 && to <= hi + 1e-9, "{name} {hero}: raise to {to} outside [{lo}, {hi}]");
}
Choice::Abstain => panic!("{name} {hero}: abstained"),
}
assert!(spot.is_legal(match s.decision.choice {
Choice::Fold => ActionKind::Fold,
Choice::Check => ActionKind::Check,
Choice::Call => ActionKind::Call,
_ => ActionKind::Raise,
}));
}
}
}
#[test]
fn out_of_position_hero_acts_first_with_check_or_a_bet() {
// Hero is the big blind (seat 0) and acts first on the turn; the villain is the button (seat 4).
let mut spot = s1_turn(&[], "Ac Qd", 0.0, 0.0);
spot.hero_seat = 0;
spot.villains = vec![Villain { seat: 4, stack: 95.7, folded: false, profile: None }];
let (me, villain) = (range(60, 51, &["Ac Qd"]), range(60, 52, &[]));
let s = solve_turn(&spot, &me, &villain, &cfg(80)).expect("hero first");
assert_eq!(s.acts[0], Act::Check, "check is the first action at a free node: {:?}", s.acts);
assert!(s.acts.iter().skip(1).all(|a| matches!(a, Act::Bet(_))));
assert!(matches!(s.decision.choice, Choice::Check | Choice::Raise { .. }));
if let Choice::Raise { to } = s.decision.choice {
assert!(to >= spot.min_raise_to.unwrap() - 1e-9 && to <= spot.max_raise_to.unwrap() + 1e-9);
}
}
#[test]
fn strong_hands_do_not_fold_and_air_folds_more() {
// The villain's range: top pair or better only (aces, kings, pairs of 7 and 2).
let villain: Vec<(Vec<Card>, f64)> = range(400, 21, &[]).into_iter().filter(|(c, _)| c.iter().any(|x| x.rank as u8 >= 11) || c[0].rank == c[1].rank).collect();
assert!(villain.len() > 30, "{}", villain.len());
let me = range(100, 22, &["7s 7c", "3c 4d"]);
let spot_set = facing_bet("7s 7c");
let spot_air = facing_bet("3c 4d");
let set = solve_turn(&spot_set, &me, &villain, &cfg(150)).unwrap();
let air = solve_turn(&spot_air, &me, &villain, &cfg(150)).unwrap();
eprintln!("set row {:?}, air row {:?} ({:?})", set.row, air.row, set.acts);
assert!(set.row[0] < 0.05, "a set never folds to a half-pot bet here: {:?}", set.row);
assert!(air.row[0] > set.row[0] + 0.3, "air folds clearly more: {:?} vs {:?}", air.row, set.row);
}
#[test]
fn the_solve_is_deterministic_and_the_game_is_balanced_enough() {
let spot = facing_bet("Ac Qd");
let (me, villain) = (range(150, 31, &["Ac Qd"]), range(150, 32, &[]));
let a = solve_turn(&spot, &me, &villain, &cfg(200)).unwrap();
let b = solve_turn(&spot, &me, &villain, &cfg(200)).unwrap();
assert_eq!(a.row, b.row);
assert_eq!(a.decision.choice, b.decision.choice, "same input, same answer");
let e = a.solved.exploit.expect("measured");
eprintln!("150x150 combos, 12 river cards, 200 iterations: {:.0} ms, exploitability {:.3} chips = {:.1} % of the {:.1} pot = {:.0} bb/100 (hero at the real node)", a.solved.millis, e.total, e.total / a.solved.pot * 100.0, a.solved.pot, a.solved.exploit_bb_per_100().unwrap());
assert!(e.total < 0.05 * a.solved.pot, "exploitability {} on a {} pot", e.total, a.solved.pot);
}
#[test]
fn a_spot_outside_the_game_is_left_to_the_heuristic() {
let me = range(50, 1, &["Ac Qd"]);
let villain = range(50, 2, &[]);
let mut river = facing_bet("Ac Qd");
river.street = Street::River;
river.board = Card::parse_list("Ah 7d 2c Ks 9h").unwrap();
assert!(solve_turn(&river, &me, &villain, &cfg(10)).is_none());
let mut multiway = facing_bet("Ac Qd");
multiway.villains.push(Villain { seat: 1, stack: 90.0, folded: false, profile: None });
assert!(solve_turn(&multiway, &me, &villain, &cfg(10)).is_none());
assert!(solve_turn(&facing_bet("Ac Qd"), &me, &[], &cfg(10)).is_none(), "no villain range");
}
#[test]
fn off_means_none_and_the_engine_is_unchanged() {
let _g = MODE_LOCK.lock().unwrap_or_else(|e| e.into_inner());
set_turn_player(TurnPlayer::Off);
let spots = [facing_bet("Ac Qd"), facing_bet("7s 7c"), hero_first("3c 4d"), hero_first("Kd Qs")];
let mut flop = hero_first("Ac Qd");
flop.street = Street::Flop;
flop.board.truncate(3);
let mut river = facing_bet("Ac Qd");
river.street = Street::River;
river.board = Card::parse_list("Ah 7d 2c Ks 9h").unwrap();
for spot in spots.iter().chain([&flop, &river]) {
assert!(turn_game_decision(spot).is_none(), "off: the hook says nothing");
}
// Switched on without a blueprint (no GRUNDSTRATEGIE) the hook still says nothing, so the engine's
// answer is the same either way: compare whole decisions.
if std::env::var_os("GRUNDSTRATEGIE").is_none() {
let off: Vec<_> = spots.iter().chain([&flop, &river]).map(crate::engine::decide::decide).collect();
set_turn_player(TurnPlayer::Grund);
let on: Vec<_> = spots.iter().chain([&flop, &river]).map(crate::engine::decide::decide).collect();
set_turn_player(TurnPlayer::Off);
assert_eq!(off, on, "no blueprint: the heuristic plays unchanged");
}
assert_eq!(turn_player(), TurnPlayer::Off);
}
#[test]
fn the_public_key_ignores_hero_cards_but_not_the_line() {
let c = TurnConfig::STANDARD;
assert_eq!(public_key(&facing_bet("Ac Qd"), &c), public_key(&facing_bet("7s 7c"), &c));
assert_ne!(public_key(&facing_bet("Ac Qd"), &c), public_key(&hero_first("Ac Qd"), &c));
}
#[test]
#[ignore = "timing probe"]
fn tree_sizes() {
use crate::cfr::turn_river_game::{build, TNode, TrBets};
for (name, forced, first) in [("hero first", vec![], 0usize), ("facing bet", vec![Act::Bet(6.0)], 1), ("check-raise spot", vec![Act::Check, Act::Bet(6.0)], 0)] {
let g = build(&TrBets::standard(9.1, 95.0, first), &forced);
let chance = g.nodes.iter().filter(|n| matches!(n, TNode::Chance { .. })).count();
let river_dec = g.nodes.iter().filter(|n| matches!(n, TNode::Dec { street: 1, .. })).count();
let turn_dec = g.nodes.iter().filter(|n| matches!(n, TNode::Dec { street: 0, .. })).count();
eprintln!("{name}: {} nodes, {turn_dec} turn decisions, {chance} river chance nodes, {river_dec} river decisions", g.nodes.len());
}
}
/// Solve time at table size (run with `--ignored --nocapture`).
#[test]
#[ignore = "timing probe"]
fn solve_time_at_table_size() {
for (n, cards, iters, rr) in [(160usize, 10usize, 200u32, 0usize), (160, 10, 400, 0), (160, 10, 200, 1), (100, 10, 200, 0)] {
let spot = facing_bet("Ac Qd");
let (me, villain) = (range(n, 41, &["Ac Qd"]), range(n, 42, &[]));
let c = TurnConfig { max_combos: n, cover: 1.0, river_cards: cards, iterations: iters, measure: true, river_raises: rr, budget_ms: 0.0 };
let s = solve_turn(&spot, &me, &villain, &c).unwrap();
let e = s.solved.exploit.unwrap();
eprintln!(
"{n} combos, {cards} river cards, {iters} iterations, river raises {rr}: {:.0} ms ({} nodes), exploitability {:.2} % of pot = {:.0} bb/100",
s.solved.millis,
s.solved.nodes,
e.total / s.solved.pot * 100.0,
s.solved.exploit_bb_per_100().unwrap()
);
}
}
/// Stage B (SOLVER_TURN): off, nothing; on, a heads-up turn is decided from the range model when no
/// blueprint is loaded, for any hero hand (in or out of the pruned range), with a legal choice.
#[test]
fn stage_b_decides_every_heads_up_turn_from_the_range_model() {
let _g = MODE_LOCK.lock().unwrap();
set_turn_ueberall(false);
assert!(turn_solver_decision(&facing_bet("Qc Jc")).is_none());
set_turn_ueberall(true);
for spot in [facing_bet("Qc Jc"), facing_bet("3s 3d"), hero_first("Ac Kc"), facing_bet("9h 4h")] {
let d = turn_solver_decision(&spot).expect("heads-up turn is in the stage-B slice");
assert!(d.reason.contains("solver turn"), "{}", d.reason);
match d.choice {
Choice::Fold | Choice::Call => assert!(spot.to_call > 0.0),
Choice::Check => assert_eq!(spot.to_call, 0.0),
_ => {}
}
}
let mut multi = facing_bet("Qc Jc");
multi.villains.push(Villain { seat: 1, stack: 90.0, folded: false, profile: None });
assert!(turn_solver_decision(&multi).is_none());
set_turn_ueberall(false);
}
+49 -42
View File
@@ -1,42 +1,49 @@
//! The only impure part: read lines from stdin, write lines to stdout.
use rechner::game::Decision;
use rechner::wire::encode::encode;
use rechner::wire::respond::respond;
use std::io::{self, BufRead, Write};
use std::panic::{catch_unwind, set_hook, AssertUnwindSafe};
/// A panic anywhere in the core still yields a valid ABSTAIN line.
fn guarded(line: &str) -> String {
catch_unwind(AssertUnwindSafe(|| respond(line)))
.unwrap_or_else(|_| encode(&Decision::abstain("internal error")))
}
fn serve(input: impl BufRead, mut output: impl Write) -> io::Result<()> {
for line in input.lines() {
let line = line?;
if line.trim().is_empty() {
continue;
}
writeln!(output, "{}", guarded(&line))?;
output.flush()?;
}
Ok(())
}
fn main() {
set_hook(Box::new(|_| {}));
// TURN_SPIEL=grund (plan E3, Owner 14.11.): the turn+river game with blueprint ranges plays the
// turn where the blueprint recognises the spot (GRUNDSTRATEGIE = folder with tables and
// checkpoints). Without the files every turn falls back to the heuristic (`turn_game_decision`
// returns None), so a missing folder never breaks a decision.
if std::env::var("TURN_SPIEL").as_deref() == Ok("grund") {
rechner::engine::turn_game::set_turn_player(rechner::engine::turn_game::TurnPlayer::Grund);
}
let stdin = io::stdin();
let stdout = io::stdout();
if let Err(error) = serve(stdin.lock(), stdout.lock()) {
eprintln!("io error: {error}");
std::process::exit(1);
}
}
//! The only impure part: read lines from stdin, write lines to stdout.
use rechner::game::Decision;
use rechner::wire::encode::encode;
use rechner::wire::respond::respond;
use std::io::{self, BufRead, Write};
use std::panic::{catch_unwind, set_hook, AssertUnwindSafe};
/// A panic anywhere in the core still yields a valid ABSTAIN line.
fn guarded(line: &str) -> String {
catch_unwind(AssertUnwindSafe(|| respond(line)))
.unwrap_or_else(|_| encode(&Decision::abstain("internal error")))
}
fn serve(input: impl BufRead, mut output: impl Write) -> io::Result<()> {
for line in input.lines() {
let line = line?;
if line.trim().is_empty() {
continue;
}
writeln!(output, "{}", guarded(&line))?;
output.flush()?;
}
Ok(())
}
fn main() {
set_hook(Box::new(|_| {}));
// TURN_SPIEL=grund (plan E3, Owner 14.11.): the turn+river game with blueprint ranges plays the
// turn where the blueprint recognises the spot (GRUNDSTRATEGIE = folder with tables and
// checkpoints). Without the files every turn falls back to the heuristic (`turn_game_decision`
// returns None), so a missing folder never breaks a decision.
if std::env::var("TURN_SPIEL").as_deref() == Ok("grund") {
rechner::engine::turn_game::set_turn_player(rechner::engine::turn_game::TurnPlayer::Grund);
}
// SOLVER_RIVER (stage A, solver everywhere): the heads-up river decided by an equilibrium solve
// (`engine::river_spieler`); blueprint ranges where GRUNDSTRATEGIE recognises the spot, else the
// range model. Off by default.
rechner::engine::river_spieler::set_river_spieler(rechner::engine::river_spieler::from_env());
// SOLVER_TURN=1 (stage B): every heads-up turn by the turn+river game (`turn_game::turn_solver_decision`).
rechner::engine::turn_game::set_turn_ueberall(rechner::engine::turn_game::turn_ueberall_from_env());
rechner::engine::flop_spieler::set_flop_spieler(rechner::engine::flop_spieler::from_env());
let stdin = io::stdin();
let stdout = io::stdout();
if let Err(error) = serve(stdin.lock(), stdout.lock()) {
eprintln!("io error: {error}");
std::process::exit(1);
}
}
+234
View File
@@ -0,0 +1,234 @@
#!/usr/bin/env python3
"""Spezifikation lesen/roentgen.py - das Engine-Röntgen je Live-Lauf.
Kleine Fixtures, kein echter Kern: das Nachspielen bekommt einen Schein-Kern (Python-Funktion), der
nur dann anders entscheidet, wenn ein Gegner ein Profil trägt. Jede Zahl wird von Hand nachgerechnet.
python3 tests/roentgen_spec.py -v
"""
import json
import os
import shutil
import sys
import tempfile
import time
import unittest
_w = os.path.dirname(os.path.abspath(__file__))
while _w != "/" and not os.path.isdir(os.path.join(_w, "lesen")):
_w = os.path.dirname(_w)
sys.path.insert(0, os.path.join(_w, "lesen"))
import roentgen
def utc(lokal):
"""Ortszeit 'JJJJ-MM-TT HH:MM:SS' -> UTC-Zeitstempel wie in haende.jsonl."""
return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(time.mktime(time.strptime(lokal, "%Y-%m-%d %H:%M:%S"))))
def anfrage(street="FLOP", profil=False, legal=("FOLD", "CALL"), unklar=None):
v = {"seat": 2, "stack": 2.0, "folded": False}
if profil:
v["profile"] = {"vpip": 0.5, "hands": 40}
a = {"street": street, "legalActions": list(legal), "villains": [v]}
if unklar:
a.update({"legalActions": [], "_unklar": unklar})
return a
def entscheidung(zeit, a, pid=7, aktion="CALL", geklickt="kanal call", hinweis="", frist=20.0, hand="1"):
return {"zeit": zeit, "pid": pid, "raum": "R", "anfrage": a, "antwort": {"action": aktion},
"geklickt": geklickt, "hinweis": hinweis, "frist_rest_s": frist,
"zug": f"R|{hand}|{a.get('street')}|0.1|0.02|AsKs|()"}
def schein_kern(aufrufe):
"""Profil da -> FOLD, sonst CALL; Größe immer 1.0. Merkt sich jeden Aufruf."""
def kern(anfragen, env):
aufrufe.append((len(anfragen), env))
return [{"action": "FOLD" if roentgen.hat_read(a) else "CALL", "size": 1.0, "reason": "x"}
for a in anfragen]
return kern
class Klasse(unittest.TestCase):
def test_grund_texte(self):
k = roentgen.klasse
self.assertEqual(k("PREFLOP", "EP open, CFR open 100bb: fold 100% -> fold"), "cfr")
self.assertEqual(k("PREFLOP", "BB vs open, call top 30% -> call"), "regeln")
self.assertEqual(k("TURN", "turn game: 30x40 combos, 9 nodes, Check p 0.6, solved in 80 ms"), "e3")
self.assertEqual(k("RIVER", "river solver (modell): 300x200 combos, 21 nodes, 600 iters, Fold p 0.9, 40 ms"), "solver")
self.assertEqual(k("TURN", "defensive turn veto: x (heuristic would call)"), "turn_veto")
self.assertEqual(k("RIVER", "defensive veto: x (heuristic would call)"), "river_veto")
self.assertEqual(k("RIVER", "MDF-Boden: Made-Hand verteidigt"), "mdf")
self.assertEqual(k("FLOP", "air on dry board: equity 0.2"), "heuristik")
# Enthaltung gewinnt - auch mit kaputtem Umlaut aus dem Log
self.assertEqual(k("PREFLOP", "\u00c3\u0153bersetzung setzt aus: Knopf unbekannt"), "enthaltung")
def test_anteile_ohne_enthaltung(self):
zs = [{"street": "PREFLOP", "grund": "CFR open"}] * 3 + [{"street": "PREFLOP", "grund": "top 20%"}] \
+ [{"street": "PREFLOP", "grund": "setzt aus"}] * 2 + [{"street": "TURN", "grund": "turn game: 1"}]
w = roentgen.wer_entschied(zs)
self.assertEqual(w["PREFLOP"]["zuege"], 6)
self.assertEqual(w["PREFLOP"]["kern_zuege"], 4) # 6 - 2 Enthaltungen
self.assertEqual(w["PREFLOP"]["klassen"]["cfr"], 3) # 3/4 = 75 % der Kern-Züge
self.assertEqual(w["PREFLOP"]["klassen"]["regeln"], 1)
self.assertEqual(w["TURN"]["klassen"]["e3"], 1)
self.assertEqual(w["GESAMT"]["zuege"], 7)
self.assertEqual(w["FLOP"]["zuege"], 0)
class Laeufe(unittest.TestCase):
S = [{"pid": 1, "zeit": "2026-11-14 10:00:00", "anfrage": {}},
{"pid": 1, "zeit": "2026-11-14 11:00:00"},
{"pid": 2, "zeit": "2026-11-14 18:54:00"}, # Lauf ohne Entscheidung
{"pid": 3, "zeit": "2026-11-14 18:57:07", "anfrage": {}},
{"pid": 3, "zeit": "2026-11-14 20:14:38"}]
def test_laeufe_und_wahl(self):
l = roentgen.laeufe(self.S)
self.assertEqual([r["pid"] for r in l], [1, 2, 3])
self.assertEqual(l[2]["von"], "2026-11-14 18:57:07")
self.assertEqual(l[2]["bis"], "2026-11-14 20:14:38")
self.assertEqual(roentgen.waehle(l)["pid"], 3) # letzter mit Entscheidungen
self.assertEqual(roentgen.waehle(l, pid="1")["pid"], 1)
self.assertEqual(roentgen.waehle(l, start="2026-11-14 18:57")["pid"], 3) # erster danach, nicht pid 2
self.assertEqual(roentgen.waehle(l, start="2026-11-14 10:30")["pid"], 1) # enthält
self.assertIsNone(roentgen.waehle(l, pid=99))
class Ergebnis(unittest.TestCase):
def test_bb_je_arm_und_fenster(self):
hs = [{"zeit": utc("2026-11-14 19:00:00"), "netto": 0.04, "bb": 0.02, "arm": "a"},
{"zeit": utc("2026-11-14 19:01:00"), "netto": -0.02, "bb": 0.02, "arm": "b"},
{"zeit": utc("2026-11-14 21:00:00"), "netto": 9.0, "bb": 0.02, "arm": "a"}] # nach dem Lauf
drin = roentgen.haende_im_fenster(hs, "2026-11-14 18:57:07", "2026-11-14 20:14:38")
self.assertEqual(len(drin), 2)
e = roentgen.ergebnis(drin)
self.assertEqual(e["gesamt"]["n"], 2)
self.assertAlmostEqual(e["gesamt"]["netto_bb"], 1.0) # +2 BB -1 BB
self.assertAlmostEqual(e["gesamt"]["bb100"], 50.0)
self.assertAlmostEqual(e["arme"]["a"]["netto_bb"], 2.0)
self.assertAlmostEqual(e["arme"]["b"]["netto_bb"], -1.0)
class Stichprobe(unittest.TestCase):
def test_verteilung(self):
zs = [{"raum": "R", "gegner": {"1": {"hands": 5}, "2": {"hands": 40}}},
{"raum": "R", "gegner": {"1": {"hands": 12}}}, # derselbe Gegner, jetzt 12
{"raum": "R", "gegner": None}]
s = roentgen.lesestichprobe(zs)
self.assertEqual(s["gegner"], 2)
self.assertEqual(s["je_gegner"]["10-29"], 1) # Sitz 1: höchster Stand 12
self.assertEqual(s["je_gegner"]["30-99"], 1)
self.assertEqual(s["je_zug"]["1-9"], 1)
self.assertEqual(s["zuege_mit_read"], 2)
self.assertEqual(s["zuege"], 3)
class Gesundheit(unittest.TestCase):
def test_zaehlt(self):
s = [entscheidung("t", anfrage(), frist=12.5),
entscheidung("t", anfrage(), geklickt="kanal fold (ohne Echo)", frist=3.0),
entscheidung("t", anfrage(), geklickt=None, hinweis="veraltet: am Tisch wurde schon gehandelt"),
entscheidung("t", anfrage(unklar="Knopf unbekannt"), frist=-1.0),
{"zeit": "t", "pid": 7, "ereignis": "sitout"},
{"zeit": "t", "pid": 7, "ereignis": "aktion_kanal", "echo": False}]
g = roentgen.gesundheit(s)
self.assertEqual(g["entscheidungen"], 4)
self.assertEqual(g["enthaltungen"], 1)
self.assertEqual(g["geklickt"], 3)
self.assertEqual(g["ohne_echo"], 1)
self.assertEqual(g["veraltet"], 1)
self.assertEqual(g["frist_min_s"], -1.0)
self.assertEqual(g["frist_unter_5s"], 2)
self.assertEqual(g["uhr_abgelaufen"], 1)
self.assertEqual(g["sitout"], 1)
self.assertEqual(g["kanal_ohne_antwort"], 1)
class Wirkung(unittest.TestCase):
def test_read_wirkung_je_street_und_cache(self):
s = [entscheidung("a", anfrage("FLOP", profil=True), aktion="FOLD"), # Read kippt CALL->FOLD
entscheidung("b", anfrage("FLOP", profil=False)), # ohne Profil: gleich
entscheidung("c", anfrage("RIVER", profil=True), aktion="CALL"), # live CALL, Nachspiel FOLD
entscheidung("d", anfrage("PREFLOP", unklar="x"))] # Enthaltung: nie zum Kern
paare = roentgen.nachspielbar(s)
self.assertEqual(len(paare), 3)
aufrufe, cache = [], {}
w = roentgen.lese_wirkung(paare, schein_kern(aufrufe), cache=cache)
f, r, g = w["streets"]["FLOP"], w["streets"]["RIVER"], w["streets"]["GESAMT"]
self.assertEqual((f["entscheidungen"], f["mit_read"], f["aktion_anders"], f["treu"]), (2, 1, 1, 2))
self.assertEqual((r["entscheidungen"], r["aktion_anders"], r["treu"]), (1, 1, 0))
self.assertEqual((g["entscheidungen"], g["aktion_anders"], g["groesse_anders"]), (3, 2, 0))
self.assertEqual(len(w["beispiele"]), 2)
self.assertEqual(w["beispiele"][0]["mit"], "FOLD 1")
self.assertEqual(w["beispiele"][0]["ohne"], "CALL 1")
# ein Kernprozess (eine Umgebung), 4 verschiedene Anfragen: a, c, c ohne Read, und
# a ohne Read == b == b ohne Read (gleicher Inhalt, einmal gerechnet)
self.assertEqual(aufrufe, [(4, {})])
roentgen.lese_wirkung(paare, schein_kern(aufrufe), cache=cache)
self.assertEqual(len(aufrufe), 1) # zweiter Blick: alles aus dem Cache
def test_ohne_read_laesst_original(self):
a = anfrage(profil=True)
b = roentgen.ohne_read(a)
self.assertNotIn("profile", b["villains"][0])
self.assertIn("profile", a["villains"][0])
def test_env_fuer_arm(self):
datei = {"MDF_UNREAD": "0", "TURN_SPIEL": "grund", "GRUNDSTRATEGIE": "D:/daten"}
# Arm sagt, was galt: TURN_SPIEL war damals nicht an - die heutige Datei gilt nicht
self.assertEqual(roentgen.env_fuer_arm("schalter:MDF_UNREAD=0", datei),
{"MDF_UNREAD": "0", "GRUNDSTRATEGIE": "D:/daten"})
self.assertEqual(roentgen.env_fuer_arm(None, datei), datei)
class GanzerBericht(unittest.TestCase):
"""Ein kleiner Baum auf der Platte: Lauf wählen, alle Teile, Text ohne Fehler."""
def setUp(self):
self.w = tempfile.mkdtemp()
os.makedirs(os.path.join(self.w, "archiv", "lauf"))
os.makedirs(os.path.join(self.w, "betrieb", "scratch"))
arm = "schalter:MDF_UNREAD=0"
zuege = [{"zeit": "2026-11-14 19:00:00", "street": "PREFLOP", "grund": "CFR open", "arm": arm,
"raum": "R", "hand": "1", "gegner": {"2": {"hands": 40}}},
{"zeit": "2026-11-14 19:00:05", "street": "FLOP", "grund": "air", "arm": arm,
"raum": "R", "hand": "1", "gegner": {"2": {"hands": 40}}},
{"zeit": "2026-11-14 17:00:00", "street": "FLOP", "grund": "alter Lauf", "raum": "R"}]
haende = [{"zeit": utc("2026-11-14 19:00:03"), "netto": 0.1, "bb": 0.02, "arm": arm}]
schatten = [entscheidung("2026-11-14 19:00:00", anfrage("PREFLOP", True), aktion="FOLD"),
entscheidung("2026-11-14 19:00:05", anfrage("FLOP", False)),
"kaputte zeile {"]
for name, zeilen in (("archiv/lauf/zuege.jsonl", zuege), ("archiv/lauf/haende.jsonl", haende),
("betrieb/scratch/shadow.jsonl", schatten)):
with open(os.path.join(self.w, name), "w", encoding="utf-8") as f:
for z in zeilen:
f.write((z if isinstance(z, str) else json.dumps(z)) + "\n")
def tearDown(self):
shutil.rmtree(self.w, ignore_errors=True)
def test_bericht(self):
aufrufe = []
r = roentgen.bericht(roentgen.daten(self.w), kern=schein_kern(aufrufe),
datei_schalter={"MDF_UNREAD": "1", "TURN_SPIEL": "grund"})
self.assertEqual(r["lauf"]["pid"], 7)
self.assertEqual(r["ergebnis"]["gesamt"]["n"], 1)
self.assertAlmostEqual(r["ergebnis"]["gesamt"]["netto_bb"], 5.0)
self.assertEqual(r["wer"]["GESAMT"]["zuege"], 2) # der alte Lauf zählt nicht
self.assertEqual(r["wirkung"]["streets"]["GESAMT"]["aktion_anders"], 1)
self.assertEqual(aufrufe[0][1], {"MDF_UNREAD": "0"}) # Umgebung aus dem Arm, nicht der Datei
t = roentgen.text(r)
self.assertIn("ändert 1 von 2 Entscheidungen", t)
self.assertIn("Preflop-CFR", t)
json.dumps(r) # --json muss serialisierbar sein
def test_ohne_nachspiel(self):
r = roentgen.rechnen(self.w, nachspiel=False)
self.assertIsNone(r["wirkung"])
self.assertIn("nicht gerechnet", roentgen.text(r))
if __name__ == "__main__":
unittest.main()