Merge origin/main: Engine-Stand (River-Solver, Synthetik-Labor, Live-A/B) in den Windows-Port

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-11-12 21:40:01 +01:00
co-authored by Claude Opus 4.8
129 changed files with 16062 additions and 848 deletions
+17
View File
@@ -0,0 +1,17 @@
{
"n_players": 10,
"weights": {
"fish": 0.0,
"reg": 1.0,
"nit": 0.0,
"maniac": 0.0
},
"spread_hud": {
"reg": {
"vpip": 0.04294699575575042,
"pfr": 0.026749870196985173,
"foldToBet": 0.08887569346502389
}
},
"quelle": "rec-log.log"
}
+62 -17
View File
File diff suppressed because one or more lines are too long
+13
View File
@@ -0,0 +1,13 @@
label 5f68c71+lokal
export coinpoker_cash_2026-11-10
hands 161
spots 195
facing_bet 28
faithfulness 0.851
faithfulness_bet 0.679
foldbet_flop 6 9
foldbet_turn 3 3
foldbet_river 2 5
equity_bias -0.186 n=14
overfold_bb 7.5
overcall_bb 3.1
+13
View File
@@ -0,0 +1,13 @@
label 5f68c71+lokal
export coinpoker_cash_2026-11-10
hands 161
spots 195
facing_bet 28
faithfulness 0.882
faithfulness_bet 0.893
foldbet_flop 8 7
foldbet_turn 3 3
foldbet_river 6 1
equity_bias -0.221 n=14
overfold_bb 40.6
overcall_bb 3.1
+22 -1
View File
@@ -101,6 +101,7 @@ import tischregeln
import tischzahlen
import dialog
import ergebnis
import allin_ev
import statistik
import strom
import tara_ereignisse
@@ -140,6 +141,7 @@ ZUSTAND = os.path.join(SCRATCH, "zustand.json") # Wiederaufnahme nach Abstur
TAKT_MARKE = os.path.join(SCRATCH, "laeufer_takt") # Herzschlag je Takt (Wache)
TISCHARTEN = os.path.join(SCRATCH, "tisch_arten.json") # Gedaechtnis der Tisch-Spielart (betrieb/tischarten.py)
SPIELPLAN = os.path.join(SCRATCH, "spielplan.json") # Übung oder Cash und Tischzahl - setzt das Cockpit (betrieb/spielplan.py)
AB_ARM = os.environ.get("COINPOKER_ARM") or None # A/B-Arm-Marke je Hand; leer = inert. Auswertung: lesen/liveabgleich.ab_aus_log(feld="arm")
# Du hast Maus/Tastatur benutzt: das Cockpit (mac/) legt die Datei an - nur bei Eingaben, nie
# bei Klicks eines Programms (macOS nennt den Absender). Du hast Vorrang, der Läufer wartet.
# Deine Eingaben meldet das Cockpit. Kette/Chaos (SCRATCH) haben ihren eigenen Ordner -
@@ -571,7 +573,22 @@ def ergebnisse(text, sitzer=None):
return 0
neu = 0
aufgedeckt = ergebnis.aufgedeckt(text) # gezeigte Haende (auch der Gegner) fuer Taras Showdown-Reaktion
rechnung = {}
try: # volle Rechnung je Hand fuer die All-in-EV (Board/Reveal)
rechnung = {(r["raum"], r["hand"]): r["daten"] for r in ergebnis.rechnungen(text)}
except Exception:
rechnung = {}
for h in ergebnis.haende(text):
if AB_ARM:
h["arm"] = AB_ARM # A/B-Marke dieses Laufs (COINPOKER_ARM); persistiert in haende.jsonl
d = rechnung.get((h["raum"], h["hand"])) # All-in-EV: varianzreduziertes netto_bb_ev (nur Flop/Turn,
if d is not None: # Preflop-Enumeration zu teuer live -> dort roh). Fehler = roh.
try:
ev = allin_ev.aus_daten(d, h["spieler"])
if ev.get("qualifiziert"):
h["netto_bb_ev"] = ev["netto_ev_bb"]
except Exception:
pass
if not BUCH.eintragen([h]):
continue
neu += 1
@@ -580,6 +597,7 @@ def ergebnisse(text, sitzer=None):
schreiben({"zeit": time.strftime("%Y-%m-%d %H:%M:%S"), "ergebnis": h["hand"],
"raum": h["raum"], "netto": h["netto"], "bb": h["bb"],
"netto_bb": round(h["netto"] / h["bb"], 2) if h.get("bb") else None,
"netto_bb_ev": h.get("netto_bb_ev"), # All-in-EV, falls Flop/Turn-All-in; sonst None
"gewonnen": h["gewonnen"], "showdown": h["showdown"], "spielart": h["spielart"]})
wie = "gewonnen" if h["netto"] > 0 else "verloren" if h["netto"] < 0 else "plus minus null"
print(f"{time.strftime('%H:%M:%S')} ERGEBNIS {h['raum']} {h['hand']}: {wie} "
@@ -607,7 +625,10 @@ def buchen(zeile, kurz, antwort, geklickt=None, hinweis="", gedenkzeit=0.0, bele
# damit jede Hand spaeter nachlesbar ist (Owner 7.11.). Das Schattenlog rotiert/ist ephemer.
if BUCH is not None:
try:
BUCH.zug(handreview.eintrag(eintrag["anfrage"], antwort, raum))
z = handreview.eintrag(eintrag["anfrage"], antwort, raum)
if AB_ARM:
z["arm"] = AB_ARM # A/B-Marke auch am Zug: Insights je Arm teilbar (lesen/einblick)
BUCH.zug(z)
except Exception:
pass
marke = antwort.get("action", "?")
+26 -3
View File
@@ -71,10 +71,13 @@ def _runde(x, stellen=2):
def _gruppe(liste):
n = len(liste)
sd = [h for h in liste if h.get("showdown")]
unten, oben = spanne_bb_pro_100(liste)
return {
"haende": n,
"netto_bb": _runde(sum(h["netto"] / h["bb"] for h in liste if h.get("bb")) if n else None),
"bb_pro_100": _runde(bb_pro_100_aus(liste)),
"unten": unten, # 95-%-Spanne um bb/100 (None unter zwei Haenden)
"oben": oben,
"gewonnen": rate(sum(1 for h in liste if h.get("gewonnen")), n),
"showdown": rate(len(sd), n),
"showdown_gewonnen": rate(sum(1 for h in sd if h.get("gewonnen")), len(sd)),
@@ -106,11 +109,20 @@ def je_format(haende):
je[h.get("format") or UNBEKANNT].append(h)
out = []
for fmt, liste in sorted(je.items()):
unten, oben = spanne_bb_pro_100(liste)
out.append(dict(format=fmt, unten=unten, oben=oben, **_gruppe(liste)))
out.append(dict(format=fmt, **_gruppe(liste))) # unten/oben kommen aus _gruppe
return out
def je_arm(haende):
"""Kennzahlen je A/B-Arm (Feld "arm", im Lauf per COINPOKER_ARM gesetzt); Hände ohne Arm als
"unbekannt". Dies ist die deskriptive Tabelle; den signifikanz-geprüften Vergleich (Welch-Zwei-
Stichproben) liefert lesen/liveabgleich.ab_aus_log(feld="arm")."""
je = collections.defaultdict(list)
for h in haende:
je[h.get("arm") or UNBEKANNT].append(h)
return [dict(arm=a, **_gruppe(liste)) for a, liste in sorted(je.items())]
def bestes_format(gruppen):
"""Das Format, dessen 95-%-Spanne ganz über allen anderen liegt - sonst keines, mit Grund.
Ein Urteil aus überlappenden Spannen wäre Zufall, nicht Können."""
@@ -180,7 +192,7 @@ def kennzahlen_aus(haende, ereignisse=()):
"haende": gesamt["haende"], "von": zeiten[0] if zeiten else None,
"bis": zeiten[-1] if zeiten else None,
"gesamt": gesamt, "je_stake": je_stake, "je_format": formate,
"bestes_format": bestes_format(formate),
"bestes_format": bestes_format(formate), "je_arm": je_arm(haende),
"aktionen": {"anzahl": dict(akt), "anteil": {k: rate(v, summe) for k, v in akt.items()}},
"sitzungen": sitzungen(ereignisse), "auszeiten": auszeiten(ereignisse),
"ereignisse": dict(collections.Counter(e.get("art") for e in ereignisse)),
@@ -209,6 +221,8 @@ def md_aus(kz, titel="Statistik"):
f"Haende: {kz['haende']}" + (f" ({kz['von']} bis {kz['bis']})" if kz["von"] else ""),
"", "| Kennzahl | Wert |", "|---|---|",
f"| bb/100 | {_zahl(g['bb_pro_100'])} |",
f"| bb/100 95-%-Spanne | "
+ (f"{_zahl(g['unten'])} bis {_zahl(g['oben'])}" if g.get("unten") is not None else "-") + " |",
f"| Netto (bb) | {_zahl(g['netto_bb'])} |",
f"| gewonnene Haende | {_prozent(g['gewonnen'])} |",
f"| VPIP | {_prozent(g['vpip'])} |",
@@ -231,6 +245,15 @@ def md_aus(kz, titel="Statistik"):
z.append(f"| {r['format']} | {r['haende']} | {_zahl(r['bb_pro_100'])} | {spanne} | "
f"{_zahl(r['netto_bb'])} | {_prozent(r['vpip'])} | {_prozent(r['pfr'])} |")
z += ["", f"Am besten: {b['format'] if b['format'] else 'noch kein Urteil'} - {b['grund']}", ""]
arme = kz.get("je_arm") or []
if len(arme) > 1 or any(r["arm"] != UNBEKANNT for r in arme):
z += ["### A/B je Arm", "",
"| Arm | Haende | bb/100 | 95-%-Spanne | Netto (bb) | VPIP | PFR |", "|---|---|---|---|---|---|---|"]
for r in arme:
spanne = f"{_zahl(r['unten'])} bis {_zahl(r['oben'])}" if r["unten"] is not None else "-"
z.append(f"| {r['arm']} | {r['haende']} | {_zahl(r['bb_pro_100'])} | {spanne} | "
f"{_zahl(r['netto_bb'])} | {_prozent(r['vpip'])} | {_prozent(r['pfr'])} |")
z += ["", "Signifikanz (Welch): `python3 lesen/liveabgleich.py --ab-log <haende.jsonl> arm`", ""]
a = kz["aktionen"]
if a["anzahl"]:
z += ["### Aktionsverteilung", "", "| Aktion | Anzahl | Anteil |", "|---|---|---|"]
+179
View File
@@ -0,0 +1,179 @@
#!/usr/bin/env python3
"""Stufe-0-Bericht (Übung): schlägt die Engine live die Null, spielt sie sane, läuft der Loop sauber?
Liest den Statistik-Speicher einer Übungs-Sitzung (betrieb/statistik.py: haende.jsonl +
ereignisse.jsonl) und - wenn angegeben - das Schattenlog des Läufers (runner: shadow*.jsonl) für
die Loop-Gesundheit. Das Urteil sagt NUR, was die Stichprobe hergibt:
* live bb/100 mit 95-%-Spanne (statistik.spanne_bb_pro_100): ist die Untergrenze > 0, schlägt die
Engine die Null MIT 95 % Sicherheit. Überlappt die Spanne die Null, ist es Zufall, kein Beweis
(dieselbe Regel wie statistik.bestes_format).
* Spielstil (VPIP/PFR/Showdown): eine degenerierte Engine (VPIP 2 % oder 95 %, PFR > VPIP) fällt
auf, bevor man Micro-Geld riskiert.
* Loop-Gesundheit: Abbrüche (Invariantenbruch), Timeouts (Uhr abgelaufen -> Server-Sitout),
Abstains (der Kern gab keine Aktion). Null Abbrüche und null Timeouts = der Loop trägt.
python3 betrieb/stufe0.py # STATS_DIR / archiv/lauf
python3 betrieb/stufe0.py --pfad DIR --shadow shadow.jsonl
python3 betrieb/stufe0.py --erwartung 80 300 --json # Sim-to-Real-Band vergleichen
VARIANZ (ehrlich): live kann KEINE Karten paaren wie die Synthetik-Leiter - jede Hand wird einmal
ausgeteilt, die volle Varianz (σ ≈ 90 bb/100) bleibt. Übung löst darum nur GROBE Dinge auf:
gewinnt es überhaupt, läuft der Loop, ist der Stil sane. Feine A/B-Deltas (1-9 bb/100) brauchen
>100k Hände je Arm und gehören nach Stufe 2 (mit All-in-EV/AIVAT-Varianzreduktion), nicht hierher.
"""
import os as _os, sys as _sys
_w = _os.path.dirname(_os.path.abspath(__file__))
while _w != "/" and not _os.path.isdir(_os.path.join(_w, "betrieb")):
_w = _os.path.dirname(_w)
WURZEL = _w
for _u in ("lesen", "betrieb"):
_q = _os.path.join(_w, _u)
if _os.path.isdir(_q) and _q not in _sys.path:
_sys.path.insert(0, _q)
import argparse
import json
import statistik
# Stil-Band: ausserhalb ist eine Engine degeneriert (nicht spielbar), nicht nur ausbeutbar.
VPIP_MIN, VPIP_MAX = 0.05, 0.90
SHOWDOWN_MIN = 0.02
def _urteil_null(unten, oben, n):
"""Schlägt die Engine die Null? Nur mit der 95-%-Spanne - Überlappung heisst Zufall."""
if n < 2 or unten is None or oben is None:
return "zu wenig Hände für ein Urteil"
if unten > 0:
return "gewinnt mit 95 % Sicherheit"
if oben < 0:
return "verliert mit 95 % Sicherheit"
return "noch Zufall (die 95-%-Spanne überlappt die Null)"
def _stil(gesamt):
"""VPIP/PFR/Showdown und ob sie in einem spielbaren Band liegen (PFR <= VPIP, kein Extrem)."""
vpip, pfr, sd = gesamt.get("vpip"), gesamt.get("pfr"), gesamt.get("showdown")
hinweise = []
if vpip is None:
hinweise.append("keine Hände")
else:
if not (VPIP_MIN <= vpip <= VPIP_MAX):
hinweise.append(f"VPIP {vpip*100:.0f} % ausserhalb {VPIP_MIN*100:.0f}-{VPIP_MAX*100:.0f} %")
if pfr is not None and pfr > vpip + 1e-9:
hinweise.append(f"PFR {pfr*100:.0f} % > VPIP {vpip*100:.0f} % (unmöglich - Lesefehler)")
if sd is not None and sd < SHOWDOWN_MIN:
hinweise.append(f"Showdown {sd*100:.1f} % sehr niedrig")
return {"vpip": vpip, "pfr": pfr, "showdown": sd, "sane": not hinweise,
"hinweise": hinweise}
def _loop(ereignisse, shadow):
"""Loop-Gesundheit: Abbrüche/Timeouts/Abstains/Sitouts. Abbruch oder Timeout = der Loop hakt."""
abbruch = sum(1 for e in shadow if e.get("ereignis") == "abbruch")
abstain = sum(1 for e in shadow
if isinstance(e.get("antwort"), dict)
and (e["antwort"].get("action") or "").upper() == "ABSTAIN")
timeouts = (sum(1 for e in ereignisse if e.get("grund") == "timeout")
+ sum(1 for e in shadow if e.get("ereignis") == "timeout"
or (e.get("grund") == "timeout")))
sitouts = sum(1 for e in ereignisse if e.get("art") in statistik.AUSZEIT_ARTEN)
return {"abbruch": abbruch, "timeouts": timeouts, "abstains": abstain, "sitouts": sitouts,
"sauber": abbruch == 0 and timeouts == 0}
def _sim_to_real(unten, oben, erwartung):
"""Live-Spanne gegen ein erwartetes Band (lo, hi) aus der Synthetik - Überlappung = im Rahmen."""
if erwartung is None:
return None
lo_e, hi_e = erwartung
if unten is None or oben is None:
urteil = "zu wenig Hände"
elif unten > hi_e:
urteil = "besser als erwartet (live-Spanne über dem Band)"
elif oben < lo_e:
urteil = "schlechter als erwartet (live-Spanne unter dem Band)"
else:
urteil = "im erwarteten Bereich (Spannen überlappen)"
return {"erwartet_unten": lo_e, "erwartet_oben": hi_e, "urteil": urteil}
def bericht(haende, ereignisse=(), shadow=(), erwartung=None):
"""Der ganze Stufe-0-Bericht als reines dict (JSON-fähig). `erwartung`: (lo, hi) bb/100-Band
aus der Synthetik für den Sim-to-Real-Vergleich, oder None."""
haende = list(haende)
kz = statistik.kennzahlen_aus(haende, list(ereignisse))
g = kz["gesamt"]
n = g["haende"]
unten, oben = g.get("unten"), g.get("oben")
return {
"haende": n,
"von": kz["von"], "bis": kz["bis"],
"bb_pro_100": g["bb_pro_100"], "unten": unten, "oben": oben,
"schlaegt_null": bool(unten is not None and unten > 0),
"urteil": _urteil_null(unten, oben, n),
"stil": _stil(g),
"loop": _loop(list(ereignisse), list(shadow)),
"sim_to_real": _sim_to_real(unten, oben, erwartung),
}
def _spanne_text(unten, oben):
return f"{unten:.1f} bis {oben:.1f}" if unten is not None else "- (zu wenig Hände)"
def text(b):
"""Der Bericht als kompakter Text fürs Terminal."""
z = ["=== Stufe-0-Bericht (Übung) ===",
f"Hände: {b['haende']}" + (f" ({b['von']} bis {b['bis']})" if b["von"] else "")]
bb = "-" if b["bb_pro_100"] is None else f"{b['bb_pro_100']:+.1f}"
z.append(f"bb/100: {bb} 95-%-Spanne: {_spanne_text(b['unten'], b['oben'])}")
z.append(f" -> {b['urteil']}")
s = b["stil"]
def _p(x):
return "-" if x is None else f"{x*100:.0f} %"
z.append(f"Stil: VPIP {_p(s['vpip'])} PFR {_p(s['pfr'])} Showdown {_p(s['showdown'])}"
+ (" [sane]" if s["sane"] else " [PROBLEM: " + "; ".join(s["hinweise"]) + "]"))
lp = b["loop"]
z.append(f"Loop: Abbrüche {lp['abbruch']} Timeouts {lp['timeouts']} Abstains {lp['abstains']}"
f" Sitouts {lp['sitouts']} -> " + ("sauber" if lp["sauber"] else "HAKT (Abbruch/Timeout)"))
if b["sim_to_real"]:
st = b["sim_to_real"]
z.append(f"Sim-to-Real: erwartet {st['erwartet_unten']:.0f} bis {st['erwartet_oben']:.0f} bb/100"
f" -> {st['urteil']}")
return "\n".join(z)
def _shadow_lesen(pfad):
if not pfad or not _os.path.exists(pfad):
return []
out = []
with open(pfad, encoding="utf-8") as f:
for zeile in f:
try:
d = json.loads(zeile)
except ValueError:
continue
if isinstance(d, dict):
out.append(d)
return out
def main(argv=None):
p = argparse.ArgumentParser(description="Stufe-0-Bericht (Übung): schlägt es die Null, Loop sauber?")
p.add_argument("--pfad", help="Statistik-Ordner (Vorgabe: STATS_DIR oder archiv/lauf)")
p.add_argument("--shadow", help="Schattenlog des Läufers (shadow*.jsonl) für die Loop-Gesundheit")
p.add_argument("--erwartung", nargs=2, type=float, metavar=("UNTEN", "OBEN"),
help="erwartetes bb/100-Band aus der Synthetik (Sim-to-Real)")
p.add_argument("--json", action="store_true", help="als JSON statt Text")
a = p.parse_args(argv)
st = statistik.Statistik(a.pfad)
b = bericht(st.haende(), st.ereignisse(), _shadow_lesen(a.shadow),
tuple(a.erwartung) if a.erwartung else None)
print(json.dumps(b, indent=1, ensure_ascii=False) if a.json else text(b))
return 0
if __name__ == "__main__":
_sys.exit(main())
+134
View File
@@ -0,0 +1,134 @@
# Architektur: das synthetische Gegner-Labor (kalibrierte Population + Liga + EGTA)
Ziel: Exploitation und Mindgames **synthetisch** messen — tausende Datensätze auf einmal, schnell,
risikolos — statt im langsamen Live-Farm. Der Live-Lauf schrumpft auf seine eine unverzichtbare Rolle:
den finalen Sim-to-Real-Abgleich.
## Warum die heutige Leiter das nicht kann
Die Leiter sind **5 feste Karikatur-Bots** (`sim::reader::Style`). Zwei Dinge fehlen, und beide sind
der Grund, warum Exploitation dort unsichtbar ist (und warum der Stage-A-Solver −43 „verlor"):
1. **Kein verdeckter Typ.** Die Engine bekommt den konvergierten Read schon schlüsselfertig geschenkt
(`sim::reads::opponent_profile` → `ReadMode::Oracle`). Es gibt nichts zu *erschließen* → der
Exploitation-Teil der Engine (`exploit::posterior`) läuft leer.
2. **Keine Reaktion.** Die Bots adaptieren nicht. Image-Aufbau und Sequencing haben nichts zum Beißen
→ Mindgames sind nicht messbar.
## Die Kernidee: Grundwahrheit vs. Beobachtung
Schon heute gibt es die zwei Ebenen, nur fest verdrahtet:
- **Grundwahrheit** = `reader::Rules` — 6 Parameter `{call_margin, raise_at, bet_at, open_at, bluff, size}`
(`src/sim/reader.rs:42-55`). Die 5 Styles sind 5 *Punkte* in diesem Raum (`reader.rs:80-89`).
- **Beobachtung** = `exploit::profile::Profile` — 12 HUD-Zahlen (`src/exploit/profile.rs`), die eine
gegebene `Rules` über viele Hände *induziert*.
**Exploitation-EV = der Abstand zwischen „Engine kennt die Grundwahrheit" und „Engine muss sie aus
Beobachtung erschließen".** Genau diesen Abstand verschenkt die Leiter, indem sie den Oracle-Read
reicht. Das Labor macht ihn sichtbar: Grundwahrheit `θ` aus einer Verteilung ziehen, der Engine nur
den *wachsenden, verrauschten* Read aus beobachteten Aktionen geben (`exploit::posterior`), und messen.
## Die vier Schichten
### Schicht 1 — Die Population `P(θ)`
Nicht 5 feste `Rules`, sondern eine **Verteilung** über `θ` = (`Rules` + Leaks + verdeckte Klasse):
- `reader::Rules` von festen Konstanten zu einem **gezogenen** Satz machen (neuer Typ `Population`
neben `Style`; `Style::rules()` bleibt als die 5 Anker-Mittelwerte).
- `θ` zieht aus einer **Mischverteilung**: Archetyp-Cluster (Reg/Nit/Maniac/Fish/Reg-balanced) als
Mittelwerte, plus Kovarianz → tausende *individuelle* Gegner, nicht 5 Klone.
- Erweiterte Leak-Achsen, die die 6 Basis-Parameter nicht fassen: Sizing-Tells (Bet-Size korreliert mit
Stärke), Timing-Tells, Street-spezifische Aggression, Position-Blindheit, Tilt-Neigung.
- **Verdeckte Klasse:** jeder gezogene Gegner trägt ein Label, das die Engine NICHT sieht — nur aus
Aktionen erschließbar. Das ist die Schraube, an der Exploitation greift.
Dateien: Ausbau `src/sim/reader.rs` (+ `population.rs`), gezogen mit `rng::Rng` (deterministisch, Seed).
### Schicht 2 — Die adaptive Liga (macht Mindgames messbar)
Statische Population testet Exploitation; **adaptive** Gegner testen Mindgames. Gegner, die ein Modell
des Helden führen und reagieren, in Stufen:
- **L0 statisch** — die Population aus Schicht 1 (kein Gedächtnis).
- **L1 reaktiv** — passt Schwellen an die beobachtete Hero-Aggression an (einfacher Frequenz-Konter).
- **L2 modellierend** — führt selbst einen Posterior über den Helden, kontert dessen geschätzte Range.
- **L3 Liga** — ein Pool aus Exploitern, früheren Hero-Versionen und L1/L2-Gegnern (AlphaStar/Pluribus-
Muster). Der Held wird gegen die ganze Liga bewertet → Robustheit, kein Overfit auf einen Gegner.
Bei L1–L3 beißt Image-Aufbau: Variante B baut ein Bild, der Gegner reagiert, B nutzt die Reaktion —
alles synthetisch. Zuteilung **pro Gegner kohärent** (nie pro Hand — das zerstörte den Effekt).
### Schicht 3 — Der EGTA-Harness (die rigorose Messung)
*Empirical Game-Theoretic Analysis*: eine Meta-Payoff-Matrix Strategie×Strategie, gefüllt durch
tausende simulierte Matches, dann Best-Response/empirisches Gleichgewicht **über die Population**.
- **Payoff-Schätzung** je Zelle: varianzreduziert mit `sim::aivat` (bewiesen) + gepaart/gespiegelt.
- **Früh-Stopp/Allokation:** `sim::sequential` (Anytime-CI, bewiesen) als Promote/Kill-Regel;
`exploit::thompson` (bewiesen) teilt Rechenzeit der aussichtsreichsten Variante zu → Dateneffizienz.
- **Exploitability-Wächter:** `sim::exploit_river` → Population-Best-Response; ein Feature darf
Population-EV heben, aber die Exploitability-Schranke nicht reißen (kein Bot-Overfit, kein
Gegen-Exploit). Das ist das Zwillings-Tor, das die alte bb/100-Leiter ersetzt:
**Population-EV hoch UND Exploitability gedeckelt.**
### Schicht 4 — Kalibrierung an echte Daten (gegen den Sim-to-Real-Gap)
Synthetik ist nur so gut wie `P(θ)`. Die Daten dafür existieren schon, pro `userId`:
- die 12 HUD-Zahlen (`lesen/profil.py`, `profil.DURCHGEREICHT`) — dieselben Felder wie `Profile`.
- Sizing-/Timing-Eimer + gezeigte Hände (`lesen/gedaechtnis.py`: `sizing`, `timing`, `gezeigt`).
**Kalibrierung = fitte `P(θ)` so, dass die von ihr *induzierten* HUD+Sizing/Timing-Verteilungen die
*empirische* Verteilung echter Spieler treffen** (Momentenmethode/MLE auf dem 12-dim-HUD-Vektor plus
Sizing/Timing-Histogrammen). Der Link Grundwahrheit→Beobachtung ist heute schon hand-geeicht
(`sim::reads::opponent_profile`, aus `tests/sim_opponent_stats` gemessen) — das verallgemeinern wir von
„5 Punkte" auf „die gezogene Verteilung". Dazu: **Held-out-Spieler** (nie auf denselben eichen und
testen) und **Worst-Case** über eine Bandbreite von Populationen, nicht nur das Mittel.
## Der Messpfeiler (was neu sichtbar wird)
Die eine Änderung, die alles freischaltet: **den Oracle-Read abschalten.** Statt
`ReadMode::Oracle`/`reads::opponent_profile` bekommt die Engine nur den aus Beobachtung wachsenden
Read (`ReadMode::Memory` verallgemeinert auf die Population + `exploit::posterior`).
```
Exploitation-Lücke = EV(Engine erschließt+adaptiert | Population)
− EV(Engine spielt GTO/blind | Population)
```
Positiv und wachsend mit der Read-Konfidenz = die Engine nutzt wirklich aus. Diese Zahl war auf der
Leiter strukturell 0 (Oracle geschenkt) — deshalb „brachte alles nichts". Im Labor ist sie das
Hauptmaß.
## Sim-to-Real & die Grenze
Adaptive synthetische Gegner sind ein *Modell* menschlicher Adaption, kein Mensch. Also: alles
offline messen, was offline messbar ist; der Live-Farm prüft nur den Schluss-Gap. Andockpunkte stehen
(Live-Map): Entscheidung `betrieb/runner.py:3391`, Ergebnis `runner.py:553-562`, Join über
`(raum, hand)`, echte Gegner-ID in `anfrage["_sitze"]` — genug, um reale `(Typ, Aktion, Ausgang)`-
Tupel für die Kalibrierung zu ernten und das finale A/B (grober Schalter: `COINPOKER_KERN`-Binary) zu
fahren.
**Gebaut + gefahren (Stand jetzt):** Der Outcome-Abgleich steht (`lesen/liveabgleich.py`): er liest
`archiv/lauf/haende.jsonl` und hält das reale bb/100 (−266.75 über 190 Hände, 95% −560…+27) gegen die
Sim-Vorhersage (+43.95). Ergebnis: **KLAFFT, Gap −311** — die behauptete Kante kommt am Tisch nicht an.
Der Gap enthält Population-/Rake-/Betriebs-Confounds; sie trennt erst der kontrollierte An/Aus-Split,
der nur noch Hände unter beiden Armen braucht, keinen neuen Code. `BEFUND-liveabgleich-stufe4-live`.
## Reihenfolge nach echtem Signalgewinn
| Stufe | Bau | Erster messbarer Gewinn |
|---|---|---|
| **0 ✓** | Population-Draw (`reader::Rules`→gezogen) **+ Oracle aus, Read via Memory/`posterior`** (`sim::population`, `sim::exploit_pop`, `bin/exploit_gap`) | **GEMESSEN: +18.98 bb/100 ±7.14, signifikant** (fish +46, nit +9, maniac +4, reg −2.5). `BEFUND-exploitation-luecke-population` |
| **1** | Kalibrierung an `profil.py`/`gedaechtnis` | realistische Population; Sim-to-Real auf der statischen Seite geschlossen |
| **2 ✓** | EGTA-Harness + Exploitability-Wächter (`sim::twin_gate`, `bin/twin_gate`) | **GEBAUT, drei Achsen, VOLLBUDGET gemessen:** Offense +43.95 (Lücke +18.98, = Stufe 0), Boden **gto −36.25** (Engine verliert gegen Balancierte — zeigt die Wurzel, die die Oracle-Leiter verbarg), River-Exploitability Mittel 77/Max 146. Budget-robust (CIs ±12–37). `Gate::passes` ersetzt die bb/100-Leiter. `BEFUND-zwillings-tor-stufe2` |
| **3 ✓ (L0–L3)** | Adaptive Liga komplett: L1 reaktiv (`sim::adaptive`), L2 modellierend (`Adapt::Model`, Beta-Posterior + LCB-Gate), L3 Liga (`sim::league`, `bin/league`) | **GEMESSEN:** L1 Tighten −0.59 (n.s.), Loosen +20.03; L2 konfidenz-gegatet (milder, +26 in der Liga); **L3-Liga: Mittel +27.55, Boden Nemesis −258** (stehendes Härte-Mitglied). `BEFUND-adaptive-liga-mindgame-steuer`, `BEFUND-liga-l2-l3` |
| **4 ✓ (beide Hälften gebaut + gefahren)** | HUD-Gap (`sim::simreal`, `bin/simreal`) **+ Outcome-Abgleich** (`lesen/liveabgleich.py`, `tests/liveabgleich_spec.py`) | **HUD:** within-reg-Streuung synth vs real vpip 0.126/0.043, pfr 0.093/0.027, foldToBet 0.056/0.089 — modest, gerichtet (`BEFUND-simreal-stufe4`). **OUTCOME (190 echte Hände):** real **−266.75 bb/100** (95% −560 bis +27) gegen Sim-Vorhersage **+43.95** ⇒ **Gap −310.70, KLAFFT** (Sim-Kante über dem realen Intervall — die behauptete Kante kommt am Tisch nicht an; Confounds: Population/Rake/Betrieb). `BEFUND-liveabgleich-stufe4-live`. **A/B-Test + Pipeline fertig** (`ab_vergleich`/`--ab`, `ab_aus_log`/`--ab-log`, 21 Tests grün). Die Arme trennen sich über die vorhandene Umgebung (`COINPOKER_KERN`-Binary + `STATS_DIR`-Ordner) — **heute lauffähig ohne neuen Code**, genaue Befehlsfolge in `RUNBOOK-liveabgleich-ab.md`. **Offen bleibt nur, den Live-Farm unter beiden Armen zu fahren** — ein geldechter Betriebs-Schritt am Tisch über Zeit. Das Werkzeug wartet auf die Daten. |
| **5 ✓** | Optimizer (Diagonal-CMA-ES, parallel; `sim::optimize`, `bin/nemesis`) | **GEBAUT + validiert** (Sphäre/Rosenbrock/Rauschen). `worst_case_opponent` VOLLBUDGET (1000×14): **Nemesis −414.81 bb/100** gegen einen klebrigen Low-Bluff-Caller (die Engine barrelt in die Station); der 300×8-Lauf fand −642.96 gegen einen loose-aggro Reraiser — zwei Budgets, zwei Klippen ⇒ breites Worst-Case-Tal, kein Artefakt. Der +44-Durchschnitt verbarg beide. Bereit für Engine-Hyperparameter, sobald als Vektor exponiert. `BEFUND-optimizer-nemesis-stufe5` |
Eiserne Gesetze bleiben, nur das Tor ändert sich: **nie einen Verlierer ausliefern** heißt jetzt
„verliert Population-EV oder reißt die Exploitability-Schranke"; **zuerst messen** heißt „gegen die
kalibrierte Population, nicht gegen 5 Dummies". Stufe 0 ist der Punkt, an dem aus „brachte nichts" zum
ersten Mal eine echte Exploitation-Zahl wird.
@@ -0,0 +1,63 @@
# Befund: die Engine ist gegen Adaption robust — keine Mindgame-Steuer, und ein +20er Geschenk
Stufe 3 des synthetischen Labors steht: Gegner, die den Helden beobachten und ihr Regelwerk pro Hand
an seine Nach-Flop-Aggression anpassen. Das ist die erste Messung, die Mindgames überhaupt berühren
kann — die feste Leiter und selbst die statische Population (Stufe 0) können es strukturell nicht, weil
dort nichts reagiert.
## Aufbau
- `sim::adaptive`: ein `HeroModel` zählt die beobachtete Nach-Flop-Aggression des Helden; `adapt()`
leitet daraus pro Hand ein frisches `Rules` ab, gespielt über den `Opponent::Styled`-Seam aus
Stufe 0 (keine `table.rs`-Änderung nötig). Zwei Reaktionen klammern das realistische Verhalten ein:
- **Tighten** — gibt dem Aggressor kein Spiel: hebt `call_margin` (faltet mehr), senkt `bluff`.
- **Loosen** — der Hero-Caller: senkt `call_margin` (ruft leichter mit, wittert Bluffs).
- Gemessen **gepaart**: derselbe gezogene Gegner, dieselben Austeilungen, einmal statisch
(= die Stufe-0-Memory-Baseline), einmal adaptierend. Der Held erschließt den Gegner die ganze Zeit
aus seinem eigenen Session-Memory (der echte Exploitation-Pfad), er bekommt die Adaption NICHT
geschenkt. Delta = `adaptiv − statisch`, bb/100.
## Ergebnis (`adaptive_gap`, 48 Gegner × 400 Austeilungen)
```
statisch adaptiv DELTA paired anytime
tighten +43.95 +43.36 -0.59 bb/100 ±5.81 ±11.91 n.s.
loosen +43.95 +63.98 +20.03 bb/100 ±5.91 ±12.12 SIGNIFIKANT
```
## Was das heißt (ehrlich)
1. **Der Harness ist exakt validiert.** Die statische Spalte reproduziert die Stufe-0-Memory-Zahl
(+43.95) **auf den Cent**. `Adapt::Static` spielt also bit-genau denselben Pfad wie `exploit_pop`
im Memory-Modus — die gepaarte Kontrolle stimmt, das Delta misst wirklich nur die Adaption.
2. **Keine Mindgame-Steuer.** Gegen einen Gegner, der auf Aggression hin stark zumacht (bis an die
Nit-Grenze, `call_margin` 0.22→0.57), verliert die Engine **nichts** Messbares (−0.59, n.s.). Ihr
stationärer Read wird von der Reaktion nicht ausgehebelt — das ist die beruhigende Nachricht.
3. **Loosen ist ein Geschenk, kein Angriff.** Ruft der Gegner als Reaktion leichter mit (Hero-Caller),
wird die Engine **reicher**, nicht ärmer: +44 → +64, +20 bb/100 signifikant. Ein loser Gegner ist
leichter auszubeuten, und die Engine zieht den Wert (dünnere Value-Bets, mehr bezahlt). Exploitation
funktioniert also auch gegen ein *bewegliches* Ziel, nicht nur gegen die fixe Population.
4. **Die eigentliche Front ist Tighten = 0, nicht Tighten < 0.** Ein *Weltklasse*-Spieler verwandelt
das Zumachen des Gegners in Profit: faltet er zu viel, muss die Blufffrequenz **hoch**. Die Engine
hält den Wert (kein Leck), schöpft das Überfalten aber nicht ab — Delta ≈ 0 statt Delta > 0. Das ist
kein Verlust, sondern liegengelassenes Geld: der nächste Hebel ist aktives Über-Bluffen gegen einen
gemessen überfaltenden Read, genau die Richtung der Krone (λ aus Konfidenz, Frequenz-Exploitation).
## Grenzen
- Zwei Reaktionsstile (Tighten/Loosen) bracketen, sind aber kein Modell echter Adaption — das ist L1
der Liga (reaktiver Frequenz-Konter). L2 (der Gegner führt selbst einen Posterior über den Helden)
und L3 (Liga aus Exploitern + früheren Hero-Versionen, Robustheit) stehen noch aus; erst L2/L3 testen
Sequencing und Gegen-Exploit scharf.
- 48 Gegner, gepoolt über ~19 200 gepaarte Austeilungen je Stil — die Deltas sind belastbar.
- Adaption ist frequenzbasiert (Nach-Flop-Aggression); Sizing-/Timing-getriebene Reaktionen fehlen noch.
## Einordnung
Zusammen mit Stufe 0 (+18.98 Exploitation-Lücke) ist das Bild konsistent und ehrlich: die Engine ist
ein solider, nicht ausbeutbarer Exploiter — sie gewinnt gegen die Population und gegen zwei
Adaptionsmoden, ohne sich kontern zu lassen. Der Weltklasse-Rest ist nicht „einen Verlust reparieren",
sondern „das neutrale Tighten-Delta in Profit drehen". Siehe `ARCHITEKTUR-synthetik-labor.md`, Stufe 3.
+87
View File
@@ -0,0 +1,87 @@
# Befund: All-in-EV — varianzreduzierte Hand-Bewertung fürs Live-A/B
**Datum:** 2026-11-12
**Zweck:** Das Live-A/B (temporal, ein Prozess — siehe `BEFUND-live-ab-einblick.md`) ist durch die
Varianz der All-in-Pötte stark gebremst. Die All-in-EV ersetzt bei einem All-in vor dem River das
realisierte Board-Ergebnis durch seinen Erwartungswert (Equity gegen die aufgedeckten Gegnerkarten).
**Mittelwerttreu:** der Erwartungswert bleibt, nur die Streuung fällt → das A/B wird schneller
signifikant (Tracker-„all-in adjusted winnings"; grob ~60 % weniger Hände für dieselbe Schranke).
## Was gebaut wurde
- **`lesen/allin_ev.py`** — Kern + Extraktor.
- `equity(hero, board_bis_allin, [vil])` → exakte Enumeration via `entscheiden/eval7.equity_vs`.
- `ev_netto_bb(eq, sieg, pleite)` = `eq*sieg + (1-eq)*pleite` — die **zwei Beine sind beobachtet**
(Sieger-Netto post-Rake, Verlierer-Netto), also rake-exakt und unverzerrt.
- `aus_daten(daten, held, preflop_ok=False)` — eine Hand aus der vollen Rechnung
(`ergebnis.rechnungen`). **Gated** auf den eindeutigen Fall: Kopf-an-Kopf, EIN Brett (kein
RIT/Doppelbrett/EV-Chop/Bombpot), beide aufgedeckt, All-in vor dem River, gleiche Einsätze (kein
Seiten-Pott). Sonst `qualifiziert=False` + Grund, und `netto_ev_bb` = roh `netto_bb`.
- `aus_text(text, held)` — alle fertigen Hände eines Logtexts (nur Weiterverarbeitung).
- **Live-Verdrahtung (`betrieb/runner.py::ergebnisse`)**: je fertige Hero-Hand wird über
`ergebnis.rechnungen(text)` die volle Rechnung geholt und `aus_daten` berechnet; qualifiziert →
`h["netto_bb_ev"]` gesetzt (persistiert in `haende.jsonl` **und** im Schattenlog). Defensiv
(try/except → roh bei jedem Fehler).
- **Auswertung (`lesen/liveabgleich.py`)**: `netto_bb(hand, ev=False)` und
`ab_aus_log(..., ev=False)` nehmen bei `ev=True` den `netto_bb_ev` statt des realisierten. CLI:
`python3 lesen/liveabgleich.py --ab-log <log.jsonl> arm --ev`. **Roh bleibt Vorgabe** — die EV ist
eine Rausch-Linse fürs A/B, nicht die Buchhaltung.
## Korrektheit — bewiesen, nicht geglaubt (`tests/allin_ev_spec.py`, 22 Tests)
- **Mittelwerttreue (Kern-Spezifikation):** 40 000 Sims, `|mean(EV) − mean(realisiert)| < 1.0` und
`var(EV) < 0.5·var(realisiert)`. Ein nicht mittelwerttreuer EV wäre ein **stiller Verlierer** —
darum ist das die Kern-Prüfung.
- **Extraktor deterministisch:** konstruierte `daten`-Dicts (exakt die Parser-Form) mit echten
Equity-Zahlen (AA vs KQ auf K72 = 0.8162; Rolle getauscht = 0.1838; Turn schneidet Board korrekt).
Gating geprüft: EV-Chop/RIT, 3-hand, nicht beide aufgedeckt, River-All-in, Seiten-Pott, kein All-in.
## Warum NICHT an den Archiv-Rohlogs validiert
Erster Validierungsversuch gegen `ergebnis.bestand_text()`: 1276 Hände, **0 qualifiziert**, 1273 davon
„kein Held". Grund: die Client-Rohlogs **rotieren in Minuten** (genau darum gibt es die persistenten
`haende.jsonl`/`zuege.jsonl`). Das Rohfenster trug nur 3 Hero-Hände, keine HU-All-in-Hand. Der
Rohtext der historischen All-ins ist weg; `haende.jsonl` trägt kein Board/Reveal. → Validierung über
konstruierte `daten` (dauerhaft, deterministisch, schnell) statt über flüchtige Rohlogs. Der Extraktor
läuft **live** korrekt, weil der Runner am Hand-Ende den frischen Text hat.
## Preflop-Pfad: seed-deterministischer Monte-Carlo (jetzt live bepreist)
Preflop-All-ins sind gerade bei Short-Stack/Turnier häufig; die exakte Equity wäre C(48,5) = 1,7M
Runouts (Minuten in reinem Python) — in der heißen Schleife verboten. Lösung:
- **`entscheiden/eval7.equity_mc(hero, board, vils, laeufe=6000, seed)`** — schätzt dieselbe Equity über
`laeufe` ZUFÄLLIGE (seed-deterministische) Runouts statt aller. **Unverzerrt:** jeder Runout ist eine
gleichverteilte Ziehung aus demselben Raum, den `equity_vs` vollständig mittelt → `E[Schätzung] =
wahre Equity`, nur MC-Rauschen ~0,5/√laeufe (bei 6000: ~0,6 % 1σ). Ein unverzerrter Equity-Schätzer
gibt eine mittelwerttreue EV — die Kern-Eigenschaft bleibt erhalten.
- **`eval7.score7`** — direkter 7-Karten-Wert (ohne die 21-Kombinationen-Schleife von `best7`), nur für
den MC-Pfad; der Ground-Truth `best7`/`score5` bleibt unangetastet. **Bewiesen gleichwertig:**
`score7 == best7` über 60 000 Zufallshände, 0 Abweichungen (`tests/eval7_mc_spec.py`). Mit `score7` +
GC-aus ist der MC linear: **~43 ms/2000, ~100 ms/6000 Läufe** (vorher mit `best7` super-linear,
3000 Läufe = 1,5 s durch GC-Thrashing).
- **`lesen/allin_ev.equity`** routet Preflop (0 Board-Karten) auf `equity_mc` mit Seed AUS DEN KARTEN
(crc32, prozess-stabil) — dasselbe Matchup → dieselbe Schätzung, auch über A/B-Arme. Flop (990) und
Turn (44) bleiben exakt. Der `preflop_ok`-Guard ist weg; Preflop qualifiziert sich jetzt und wird
live für ~100 ms bepreist (seltenes Ereignis, in der Ergebnis-Schleife tragbar).
**Nebenbefund (wichtig):** Beim Prüfen kam AA vs KQ preflop als 0,87 heraus — kurz als Evaluator-Bug
verdächtigt (Erinnerung „AA vs KQ ~0,72" war falsch). **Drei unabhängige Evaluatoren** (score7,
best7-Enumeration, ein von Hand geschriebener unabhängiger 5-Karten-Rang) geben übereinstimmend 0,871,
0 Abweichungen. 0,87 ist korrekt: KQo ist schwächer als KK, gewinnt also weniger als dessen 18 %. Der
Ground-Truth-Evaluator ist bestätigt sauber — kein Bug.
## Status
Alle betroffenen Specs grün (allin_ev 23, eval7_mc 6, liveabgleich 23, ab_arm 8, einblick 12,
ergebnis 31, statistik 21, handreview 7). Die roten Specs im Gesamtlauf sind vorbestehende Windows/
macOS-Portabilitätsfehler (AF_UNIX, SIGHUP, 0o600-chmod, /tmp- und Library-Pfade, fehlendes `mcp`),
keiner im Änderungs-Set. **Nicht committet.** Keine Engine-Verhaltensänderung — reine Mess-
Infrastruktur (die Hand-Zeile bekommt ein zusätzliches Feld; roh bleibt Vorgabe überall).
**Offene Kante (klein):** 6000 MC-Läufe ~100 ms liegen in der Ergebnis-Schleife; bei einem seltenen
Preflop-All-in unkritisch, aber ein Schwung vieler gleichzeitig fertig werdender Preflop-All-ins (etwa
nach einem Reconnect) summiert sich. Wenn das je stört: vorberechnete 2v2-Equity-Tabelle (O(1)) oder
die MC in einen Worker schieben. Heute nicht nötig.
@@ -0,0 +1,54 @@
# Befund: die Glückskorrektur des Benchmarks ist schon nahezu optimal — β-Tuning ist ein toter Hebel
Frage (Marc): *„ist auch dein Bench absolute mathematische Weltklasse?"* — Teilantwort, gemessen.
Der Benchmark speichert je Austeilung `net − luck`: eine Kontrollvariate mit **fest β = 1**
(`sim::session`). Weil der Glücks-Term Erwartungswert ~0 hat, ist `net − β·luck` für **jedes** β
erwartungstreu, und das varianzminimale β\* = Cov(net, luck)/Var(luck) ist nicht zwingend 1. Die
naheliegende „Weltklasse"-Vermutung: AIVAT (`sim::aivat`) lernt β\* kreuzangepasst und schlägt den
festen Bench. **Gemessen (`src/bin/aivat_bench.rs`, echte Sim-Daten) ist das falsch.**
## Die Zahlen
```
Szenario β* Varianzfaktor CI aivat vs Bench
bench/raw aivat/raw aivat/bench
heads-up gto 1.21 1.65x 1.68x 1.01x +0.7 %
heads-up gto-small 1.08 1.50x 1.47x 0.98x -1.0 %
heads-up fish 1.21 1.32x 1.23x 0.94x -3.3 %
heads-up station 1.99 1.25x 1.36x 1.08x +3.8 %
heads-up reg 0.84 1.41x 1.36x 0.97x -1.6 %
```
(Alle drei Schätzer — roh β=0, Bench β=1, AIVAT β\* — stimmen je Szenario innerhalb jeder CI überein:
erwartungstreu bestätigt, wie `E[luck]=0` es verlangt.)
## Was die Zahlen sagen
1. **Die *vorhandene* Glückskorrektur ist der echte Gewinn.** `bench/raw` = 1.25–1.65× Varianz: die
feste β=1-Korrektur drückt die Varianz um 25–65 %. Das ist schon ausgeliefert und solide.
2. **Das β-Tuning ist ein Nicht-Gewinn.** `aivat/bench` = 0.94–1.08× — ein Wash, auf drei von fünf
Szenarien sogar minimal schlechter (Kreuzanpassungs-Rauschen bei diesem n).
3. **Warum, obwohl β\* teils weit von 1 liegt (Station β\*=1.99!):** `Var(net − β·luck)` ist quadratisch
in β und **flach am Minimum**. Nur ein grob falsches β (etwa β=0, keine Korrektur) kostet — und das
vermeidet der Bench bereits. Um das Optimum herum ist der Verlust zweiter Ordnung ≈ 0.
## Konsequenz: NICHT ausliefern
Kein Einhängen von kreuzangepasstem β in den Bench — es ist eine kosmetische Änderung ohne messbaren
Nutzen, gelegentlich ein kleiner Schaden. Der Diagnose-Binär `aivat_bench` bleibt als dokumentiertes
Audit-Werkzeug (wie `exploit_scan`), `session::deal_net_and_luck` als seine API.
## Was den Maßstab WIRKLICH Weltklasse machen würde (evidenzbasiert)
Die Varianzreduktion einer Kontrollvariate ist durch **1 − ρ²** gedeckelt, ρ = corr(net, luck). Der
tote Hebel ist β; der lebende Hebel ist ein **stärkeres Kontrollsignal** (höheres ρ):
- **Volle AIVAT-Korrektur**, nicht nur All-in-Glück: eine Baseline an **jedem Chance- und Gegnerknoten**
des Baums (per-Street-Equity statt nur Showdown-Glück). Genau das nennt `sim::aivat` selbst als „nicht
umgesetzt". Höheres ρ² → engere CI — *dort* liegt die Weltklasse, nicht im Koeffizienten.
- **Zeituniformer Früh-Stopp** (`sim::sequential`, gebaut + bewiesen): nach jeder Austeilung peeken und
stoppen, sobald entschieden, ohne Optional-Stopping-Verzerrung.
- **Exploitability über River hinaus** + realistische Ranges + **Gegner-Holdout** gegen In-Sample-Overfit.
Siehe `docs/notizen/ROADMAP-mathematik.md`, Abschnitt Messschicht.
@@ -0,0 +1,73 @@
# Befund: die konditionierte Fold-Equity (Stage B, live) verliert gegen balancierte Gegner
Erster Versuch, einen Solver-Baustein (`cfr::turn`, Stage B) in den **lebenden** Entscheidungspfad zu
heben, statt ihn nur als Toy-Test zu beweisen. Ergebnis: ein gemessener **Verlierer** auf genau den
Szenarien, die er heilen sollte. Komplett revertiert.
## Die Idee (theoretisch sauber)
`cfr::turn` beweist auf abstrakten Buckets: Ein Barrel gegen eine Range, die **vorher schon gecallt
hat**, bucht die *globale* Fold-to-Bet-Quote (`exploit::table_fold`) als Phantom-Gewinn — die Hände,
die gecallt haben, sind die starke committete Fortsetzungs-Range und folden höchstens die
Mindestverteidigungsfrequenz (alpha) auf einen weiteren Einsatz. Gebucht > realisiert, der Barrel
blutet (BEFUND-nit-read-leck).
Gebaut: `engine::conditioned_fold` — sobald ein lebender Villain **postflop gecallt** hat, wird die
Fold-Equity eines Bluffs/Halbbluffs auf die GTO-Decke `alpha = r/(1+r)` (`r = pressure_ratio`)
gekappt. Erste Einsätze und alle Value-Linien unberührt (Steal/Value-Farming bleibt unangetastet).
Eingehängt an `options.rs:134`. 6 Unit-Tests + 41 Lib-Tests grün.
## Gemessen (gepaart, 3000-Deal-Leiter, gegen Basislinie 24549fb+lokal)
```
heads-up gto -3.76 ± 1.99 bb/100 30 geändert SCHLECHTER (-28.92 -> -32.68)
heads-up gto-small -3.29 ± 1.87 bb/100 31 geändert SCHLECHTER (-17.24 -> -20.54)
heads-up gto (blind) -3.76 ± 1.99 30 geändert SCHLECHTER
heads-up gto-small (blind) -3.29 ± 1.87 31 geändert SCHLECHTER
heads-up fish (blind) +4.45 ± 2.79 27 geändert BESSER
heads-up calling station (blind) +8.34 ± 3.52 40 geändert BESSER
GESAMT -0.14 ± 0.42 234 geändert nicht unterscheidbar
```
Alle Farm-Bots (reg/nit/maniac/fish/station, read-given) **gleich oder nicht unterscheidbar** — die
Gates schützen sie wie gebaut. Der Netto-Effekt ist null. Aber die **balancierten Zielszenarien
verlieren signifikant** (Intervall schließt 0 aus).
## Warum es verliert — die Kernkorrektur
Der `cfr::turn`-Beweis gilt gegen einen **Über-Folder** (Nit, globale Quote 0.82 ≫ alpha): dort ist
die gebuchte Fold-Equity auf der verengten Range tatsächlich Phantom. Gegen einen **genuin
balancierten** Gegner (gto, foldToBet 0.42 ≈ alpha) ist die Fold-Equity **kein Phantom** — der gto
foldet real auf der Mindestverteidigungsfrequenz, die Barrels waren **+EV** (deckt sich mit Stage 5:
„jeder Aggression-Eimer ist +EV gegen gto"). Die Decke kappt genau diese realen, profitablen Barrels
(und wirft über die `PURE_BLUFF_MIN_FOLD`-Schwelle einige ganz weg) → der Gewinn geht verloren.
**Also:** Das Over-Barrel-Leck ist **Nit-spezifisch** (Über-Folder, mehrstraßig), kein allgemeines
Leck gegen committete Ranges. Und die Leiter belohnt seine Behebung nicht: Die Engine **farmt Nits
ohnehin** (+38 bb/100), das mehrstraßige Phantom kostet dort real so wenig, dass es im Rauschen liegt,
während dieselbe Kappung die +EV-Barrels gegen den balancierten Gegner wegnimmt.
## Folge für die Vision (engine-math-vision)
Die Vision-Annahme „**Stage B = hier stirbt das Over-Barrel-Leck**, der Barrel sieht endlich die
River-Konsequenz" ist gegen **balancierte** Gegner **falsch**: Der Barrel ist dort schon richtig
bepreist. Stage B als pauschale konditionierte Fold-Equity ist kein Leiter-Gewinn.
Was die Messung dieser Session kumulativ zeigt:
- **Defense gegen gto** (Over-Call): Rest ist Cooler-Varianz, nicht foldbar (Over-Call-Decke inert).
- **Offense gegen gto** (Barrel): konditionierte Fold-Equity verliert — die Barrels sind schon +EV.
- Gegen die **fixen balancierten Bots ist die Heuristik nahe an ihrem erreichbaren EV**; der
−24/−17-Rest ist überwiegend irreduzible Varianz + die strukturelle Realisierungslücke, kein
heuristisch schließbares Leck.
**Konsequenz:** Der echte Gewinn der Vision (sichere Ausnutzung) zeigt sich **nicht** in bb/100 gegen
diese fixen Near-GTO-Bots — dort ist das Signal cooler-/varianzdominiert. Er zeigt sich gegen
**ausnutzbare** Gegner (die Farm-Bots, schon +100..+350) und, als Unausnutzbarkeits-Beweis, in der
**Postflop-Exploitability gegen eine Best Response** — das eine Maß, das MODULES.md ausdrücklich als
fehlend nennt („Postflop-Exploitability gegen eine Best Response fehlt noch"). Der nächste echte
Schritt ist dieses Maß zu bauen, nicht ein weiterer bb/100-Patch gegen gto.
## Status
Revertiert: `engine::conditioned_fold` gelöscht, `options.rs`/`engine/mod.rs` unverändert, `cfr::turn`
bleibt als bewiesener Toy-Baustein liegen. 41 Lib-Tests grün. Kein Fix ausgeliefert.
@@ -0,0 +1,59 @@
# Befund: +19 bb/100 Exploitation-Lücke gegen eine gezogene Population — das Labor zeigt, was die Leiter verbarg
Stufe 0 des synthetischen Labors steht und liefert die erste **positive, signifikante** Exploitation-
Zahl dieser Arbeit. Gemessen gegen eine gezogene Gegner-Population mit **abgeschaltetem Oracle-Read**:
die Engine muss den Gegner aus beobachteten Aktionen erschließen (`sim::memory` → die 4 HUD-Zahlen),
statt ihn geschenkt zu bekommen.
## Aufbau
- `sim::population`: Verteilung über `reader::Rules` (6 Schwellen), Archetyp-Mischung (fish/reg/nit/
maniac) mit Streuung → tausende *individuelle* Gegner, jeder mit verdecktem Label.
- `sim::exploit_pop`: zieht N Gegner (`Opponent::Styled`, kein Oracle-Profil → `reads` gibt `None`),
spielt die Engine heads-up gegen jeden **einmal blind, einmal mit Session-Memory**, über dieselben
Austeilungen (Kartenglück hebt sich paarweise auf). Lücke = `memory − blind`, bb/100.
- CI gepaart (`sim::paired`) **und** anytime (`sim::sequential`) — Letzteres zum ersten Mal auf echten
schwer-tailed Pokerdaten statt synthetischem Gauß.
## Ergebnis (`exploit_gap`, 48 Gegner × 400 Austeilungen)
```
blind (kein Read) +24.96 bb/100
memory (erschlossen) +43.95 bb/100
EXPLOITATION-LÜCKE +18.98 bb/100 paired ±7.14, anytime ±14.64 SIGNIFIKANT POSITIV
nach verdecktem Archetyp (mittlere Lücke je Gegner):
fish +45.93 (18) <- hier liegt das Geld
nit +8.94 (10)
maniac +4.00 ( 7)
reg -2.53 (13) <- Überadjust gegen Balancierte (richtungsweisend, kleine Stichprobe)
```
Selbst die konservative Anytime-CI schließt die 0 aus (18.98 − 14.64 = +4.3 > 0).
## Was das heißt
1. **Die These stimmt.** Gegen eine *varied* Population, Oracle aus, verdient das Erschließen des Reads
~+19 bb/100 über blindes Spiel — fast eine Verdopplung der Winrate (+25 → +44).
2. **Die Leiter verbarg das strukturell.** Dort bekommt die Engine den konvergierten Oracle-Read
(`sim::reads::opponent_profile`) geschenkt → nichts zu erschließen, keine Exploitation messbar. Das
ist der Grund, warum frühere Live-Integrationen auf der Leiter „nichts brachten": das Maß war blind
für genau die Fähigkeit, die zählt.
3. **Der eine negative Wert ist Signal, kein Rauschen allein.** `reg −2.53`: gegen balancierte Gegner
überadjustiert die Engine. Das ist exakt die Motivation der Krone (KL-Vertrauensregion, λ aus
Konfidenz): bei balanciert aussehendem Read nahe GTO bleiben. Nächster Hebel, nicht Zufall.
4. **Die Konfidenzfolge hält auf echten Daten.** Breiter als die feste CI (richtig so — gültig unter
Peeking), konsistent. Die frühere „nur auf Gauß geprüft"-Lücke ist damit geschlossen.
## Grenzen (ehrlich)
- 48 Gegner ist eine moderate Stichprobe; die **gepoolte** Lücke (±7.14 über ~19 200 gepaarte
Austeilungen) ist belastbar, die **Pro-Archetyp**-Zahlen (7–18 Gegner) sind richtungsweisend.
- Die Population ist noch der ungeeichte `micro`-Prior. Stufe 1 fittet sie an echte Daten
(`lesen/profil.py`, `gedaechtnis`), erst dann ist die absolute Zahl real; die *Methode* steht.
## Nächste Stufen
Stufe 1 Kalibrierung (Population an echte HUD/Sizing-Daten), Stufe 2 EGTA-Harness + Exploitability-
Wächter (Zwillings-Tor; adressiert `reg`), Stufe 3 adaptive Liga (Mindgames). Siehe
`docs/notizen/ARCHITEKTUR-synthetik-labor.md`.
@@ -0,0 +1,161 @@
# Befund: das nächste Leck (River-Über-Call gegen Value) sitzt in der falschen Schicht
Nach dem MDF-Boden-Fix (BEFUND-gto-ueberdefense, −38.44 → −24.83 bb/100) habe ich den nächsten
Leak gesucht. Ergebnis: ein echter, aber **kleiner und variance-behafteter** Rest, der sich mit der
jetzigen Architektur und Messung **nicht sauber beweisen** lässt. Kein Fix ausgeliefert.
## Zwei klare Zwischenbefunde
**1. Es gibt KEIN Fold-Disziplin-Leck.** Über-Fold-Test (`diag_gto`, pro Straße bei gefasstem Bet:
foldet der Hero mit Equity ≥ Break-even?):
```
street faced folds folds w/ odds fold%
preflop 1944 244 0 12.6%
flop 335 138 0 41.2%
turn 216 101 0 46.8%
river 167 129 0 77.2%
```
**Null Folds mit Odds auf jeder Straße.** Jeder Fold ist modell-korrekt (Equity < Break-even). Die
Fold-Eimer (river −24, preflop −22, turn −12, flop −10 bb/100) sind **Sunk-Cost** aus früherer
Investition, kein Over-Fold. Folden-wir-zu-viel ist widerlegt.
**2. Der Rest-Leak ist ein Über-Call marginaler Made-Hands gegen Value.** Der River-Call-Eimer
(−25.58 bb/100, 32 Hände) liegt im Band **eq 0.35–0.55** (27 Hände, −12 bis −28 bb/Hand). Beispiele,
womit der Hero callt und verliert:
```
Qd 4c board 7h 4h Jc Js 9s eq 0.35 net -25.9 (Zweitpaar / Board-Paar)
8d 8s board 4d Tc Kd Th 3c eq 0.44 net -28.7 (Unterpaar zu TT/K)
Jc Jd board 4c Kd 6s Ts 6d eq 0.45 net -18.3 (Unterpaar zu K)
8s 9s board Jd Th 3c 9h Jc eq 0.43 net -53.7 (schwaches Zweitpaar)
4h 5d board 9h 4d 9c 4s 6s eq 0.48 net -65.4 (Fours-full vs Nines-full = Cooler)
Qc Qd board Th Ah 9c Jc Tc eq 0.52 net -75.6 (Cooler)
```
Muster: **schwache Zweitpaare / Unterpaare** bluffcatchen River-Value-Bets. Das Modell bewertet sie
mit 0.35–0.55, weil sein River-Bet-Range-Boden **Top Pair Good Kicker** ist (`BET_RUNG`) — also „über"
dem Single-Pair-Boden der modellierten Betting-Range. Ein balancierter Gegner **bettet aber keine
mittleren Hände** (er checkt sie, gto.rs: „medium hands check"); seine Value-Bets sind stärker. Der
Boden ist zu niedrig → Equity überschätzt → marginaler Call → Verlust. Dazu: mehrere der 27 Hände sind
**Cooler/Varianz** (Fours-full, QQ), nicht systematisch.
## Warum der naheliegende Fix in der falschen Schicht sitzt
Der naheliegende Griff — den River-Value-Boden für einen balancierten Regular um eine Sprosse heben
(`street_continuation::river_value_bump`) — habe ich gebaut und gemessen: **exakt null Wirkung**
(−24.83 → −24.83, River-Band bit-identisch).
Grund: `engine::read_gate::gate_reads` **streicht das Profil** für jeden Stil mit `earned_trust == 0`
— darunter `Regular` (der gto). Das Range-Modell (`range_spec` → `street_continuation`) sieht den gto
also **blind** (`profile: None`), der Bump feuert nie. Das ist **Absicht**: `read_gate` (Zeile 38–44)
schreibt das Gesetz fest — **defensive** Read-Anpassungen („fold more thin value / bluff catchers into
a proven non-bluffer") gehören in den **ungegateten** MDF-Boden-Pfad (`mdf_floor::floor` auf dem
`raw`-Spot), **offensive** werden gegatet. Mein River-Über-Call-Fix ist eine *defensive* Anpassung —
also gehört er NICHT ins (gegatete) Range-Modell, sondern in den ungegateten Defense-Pfad.
## Der richtige Fix (noch nicht gebaut): eine „Over-Call-Decke" neben dem MDF-Boden
Spiegelbild des MDF-Bodens, gleiche Bauart (ungegateter Read, nur River, auf Heros Made-Hand):
- **Boden** (existiert): macht gegen einen bewiesenen **Over-Bluffer** aus einem Fold einen MDF-Call.
- **Decke** (fehlt): macht gegen einen bewiesenen **Value-Better / Nicht-Over-Bluffer** aus einem
marginalen Modell-Call einen Fold — denn gegen eine wertlastige Betting-Range schlägt der dünne
Bluffcatcher nur die (zu wenigen) Bluffs.
Genau die Kronengleichung, defensive Seite: λ = belastbares Read, nur gegen einen *bewiesen*
balancierten/engen Better schärfer folden; Fische/Stations/ungelesen unberührt (dort ist weites
Callen korrekt und bezahlt).
## Warum jetzt nicht gebaut: die Messung trägt es nicht
Der Rest-Leak ist **−12 bis −22 bb/100 auf ~27 Händen**, das gto-Szenario hat **±10 bb/100 CI** (1000
Deals) und enthält sichtbare Cooler. Ein Fix, der die Hälfte zurückholt, landet **im Rauschen** — nicht
beweisbar. Nach der Arbeitsleiste („measure first; never ship a loser; prove on the ladder") ist der
nächste Schritt **nicht** ein blinder Patch, sondern:
1. **Messung schärfen:** gto-Deals hochdrehen (z. B. 1000 → 5000) und/oder einen zweiten balancierten
Gegner (andere Size/Bluff-Mischung) aufnehmen, damit ein ~10-bb/100-Defense-Fix signifikant wird.
2. **Dann** die Over-Call-Decke bauen und gepaart beweisen; sonst reverten + Befund.
## Messung geschärft (erledigt — Vorarbeit für die Over-Call-Decke)
Damit ein ~6–8-bb/100-Defense-Fix überhaupt beweisbar wird:
- **Deals hoch:** die balancierten Heads-up-Szenarien laufen jetzt mit `BALANCED_DEALS = 3000` statt
1000 (CI ~1.7× enger). Die Leiter braucht dafür 244 s statt 180 s — vertretbar für eine
Beweis-Leiter.
- **Zweiter balancierter Gegner:** `Style::GtoSmall` (`sim::gto::Shape::SMALL`, Half-Pot, 0.3 Bluffs
pro Value) — ein unabhängiges, wertlastigeres Ziel, damit die Decke generalisieren muss, nicht den
einen `Gto` überanpasst. `sim::gto` ist dazu auf `Shape { bet_size, bluff_per_value }`
parametrisiert; `Gto` = `Shape::BALANCED` ist byte-identisch zu vorher (die −24.83-Messung bleibt
unberührt).
- **Validiert balanciert:** der Engine verliert auch gegen `gto-small` (**−17.24 bb/100** read-given,
−23.46 blind) — ein echter balancierter Gegner, kein schwacher Bot (den der Engine mit +100
zerlegen würde).
**Wichtig — warum die Schärfung nötig war:** bei 3000 Deals steht `heads-up gto` auf **−28.92 bb/100**,
auf den 1000 Deals des `diag` dagegen −24.83. Eine ~4-bb/100-Stichprobenschwankung, **größer als der
erwartete Fix-Effekt** — ein auf 1000 Deals „bewiesener" kleiner Fix wäre Rauschen gewesen.
Neue Basislinie (`benchmarks/baseline.txt`, 19 Szenarien, MDF-Fix drin, noch keine Decke) gespeichert.
`diag_gto` nimmt jetzt Deal-Zahl + Gegner als Argumente (`diag_gto 5000 gto-small`), für schnelle
deterministische In-Sample-Iteration der Decke.
## Over-Call-Decke gebaut, gemessen, widerlegt, revertiert
Die Decke wurde **genau wie geplant** gebaut (ungegateter Overlay in `mdf_floor`, nur River,
Spiegelbild des Bodens):
- `proven_value_bettor(profile)` = `classify ∈ {Regular, Nit}` ∧ `aggression < 0.60` (Spiegel von
`over_bluffs`), `range_is_value_heavy` = **alle** lebenden Villains gelesen und value-heavy.
- `only_beats_bluffs(made)` = `beats_bluffs ∧ made < TopPairWeakKicker` (Underpair/BottomPair/MiddlePair).
- `ceiling(...)`: aus einem Modell-**Call** eines reinen Bluffcatchers gegen einen bewiesenen
Value-Better wird ein **Fold**. 10 Unit-Tests grün, Prädikat verifiziert (`vh=true` auf gto und
gto-small, Boden/Decke schließen sich gegenseitig aus).
**Gemessen (gepaart, in-sample via `diag_gto`): exakt null Wirkung.**
```
vor Decke nach Decke
gto -24.83 -24.83 (byte-identisch, 0 Flips)
gto-small -11.25 -11.25 (byte-identisch, 0 Flips)
```
**Warum null:** die Decke feuert nie, weil das Leck, das sie treffen soll, **nicht existiert**. Eine
Instrumentierung aller River-Calls-facing-a-bet (CEIL_DEBUG) zeigt die wahre Verteilung der 32 Hände
im River-Call-Eimer:
```
gto (1000 Deals, 32 River-Calls): 30× TwoPair, 1× TopPairWeakKicker, 1× FullHouse
gto-small (400 Deals, 13): 12× TwoPair, 1× FullHouse
```
**Kein einziger Underpair / BottomPair / MiddlePair.** Die schwachen Bluffcatcher, die der obige
Equity-0.35–0.55-Dump suggerierte, **foldet der Engine bereits korrekt** (Modell-Fold, 0 Over-Folds —
siehe oben). Die 0.35–0.55-Equity im Dump war die **Modell**-Equity, nicht die Handklasse: ein
kontrafeited TwoPair oder ein Cooler steht beim Modell bei 0.4, ist aber in Wahrheit `TwoPair`.
**Der Rest-Leak ist also ein Cooler-Leck, kein Over-Call-Leck.** Die verlierenden River-Calls sind
**starke Made-Hands (TwoPair+), die auf gepaarten Boards zweitbest sind** (Villain hat das bessere
Zweitpaar / Trips / Full House). Die kann man gegen eine balancierte Value+Bluff-Range **nicht
profitabel folden**: TwoPair schlägt alle Bluffs und einen Teil des dünnen Values; „alle TwoPair
folden" wäre ein katastrophaler Over-Fold (man foldet das gewinnende Zweitpaar viel öfter als das
verlierende). Der Dump zeigte nur die **Verlierer** des Eimers; über 32 Hände mit ±CI-Rauschen ist der
negative Netto-Saldo nicht als systematisches Leck belegbar.
**Fazit (Arbeitsleiste: never ship a loser):** kein Fix ausgeliefert, Decke komplett revertiert
(`mdf_floor` trägt wieder nur den bewiesenen MDF-Boden, `decide` unverändert, 41 Lib-Tests grün). Der
−24.83/−11.25-Rest gegen balancierte Gegner ist **primär Cooler-Varianz auf starken Händen + Preflop-
Sunk-Cost**, kein foldbarer River-Over-Call.
**Die geschärfte Messung hat sich bezahlt gemacht** — nicht durch einen Fix, sondern indem sie die
wahre River-Call-Verteilung (32 Hände, alle TwoPair+) klar zeigte und die plausibel klingende
Over-Call-Hypothese **tötete, bevor** ein inerter Patch ausgeliefert wurde, der dem Prosa-Muster des
Befunds entsprach, aber den Daten nicht.
## Werkzeug
`src/bin/diag_gto.rs` erweitert: Über-Fold-Test (facing-a-bet fold-vs-odds pro Straße), Dump der
verlierenden River-Calls (Heros Bluffcatcher mit Board + Modell-Equity), und Argumente für Deal-Zahl
und Gegner. Bleibt als Diagnose. (Die CEIL_DEBUG-Instrumentierung wurde mit der Decke revertiert.)
@@ -0,0 +1,125 @@
# Befund: der GTO-Boden unter dem realistischen Read — Über-Defense durch Breite-als-Bluff-Fehlsignal
Der Boden des Zwillings-Tors stand bei **gto −36.25 bb/100** (`twin_gate`, Memory-Read — der realistisch
eingesetzte Read, nicht das geschenkte Oracle). Die beiden früheren GTO-Befunde arbeiteten mit dem
**Oracle**-Read (`diag_gto`, −24.83) und schlossen daraus, der Rest sei Cooler-Varianz + Preflop-Sunk-Cost,
kein foldbarer River-Leak (`BEFUND-gto-restleck-river-overcall`). Das stimmt — **für den Oracle-Read**.
Unter dem realistischen Session-Read liegt darunter aber noch ein echtes, lesegetriebenes Leck.
## Die entscheidende Messung: Oracle ≠ Memory
Für einen `Regular`/`Gto` ist `earned_trust == 0` (`engine::read_gate`), das Range-Modell spielt ihn also in
**jedem** Lese-Modus blind. Der einzige Hebel, der den gto berührt, ist der **ungegatete MDF-Boden**
(`exploit::mdf_floor`). Eine Sonde (`floor_read`, gto, 800 Austeilungen) zeigt den Lese-Effekt isoliert:
```
gto Oracle -27.60 bb/100 (Boden feuert NICHT)
gto Blind -40.04 bb/100 (Boden feuert -> Over-Call)
gto Memory -40.04 bb/100 (Boden feuert -> Over-Call, = Blind!)
```
Memory == Blind, obwohl der Read nach 25 Hand Warmup voll steht. Das heißt: der Boden feuert auch **mit**
dem Session-Read. Warum? Weil er den Read als Over-Bluffer liest.
## Die Wurzel: `over_bluffs` feuerte auf Preflop-**Breite**, nicht auf Bluff-Frequenz
`mdf_floor::over_bluffs` feuerte bei `classify(profile) == LooseAggressive`. `classify` stuft als
LooseAggressive ein bei **vpip ≥ 0.35 ∧ pfr ≥ 0.20** — also reiner **Range-Breite**. Heads-up spielt ein
korrekt balancierter Gegner eine weite Range (Button opent ~80 %, BB verteidigt ~70 %). Sein **gemessener**
Session-Read ist deshalb breit, obwohl seine Postflop-Aggression maßvoll ist. Direkt gemessen
(`gto_read_probe`, Memory-Read-Endstand):
```
Archetyp vpip pfr fold2bet aggr classify over_bluffs(alt)
gto 0.70 0.46 0.50 0.35 LooseAggressive true <- FEHLSIGNAL
maniac 0.93 0.21 0.34 0.49 LooseAggressive true (korrekt)
fish 0.87 0.00 0.21 0.11 CallingStation false
reg 0.49 0.06 0.47 0.31 CallingStation false
```
Der balancierte gto (Aggression **0.35**) und der echte Over-Bluffer-Maniac (Aggression **0.49**) sind über
vpip/pfr **nicht unterscheidbar** — beide „LooseAggressive". Das einzige trennende Merkmal ist die
**Postflop-Aggression**. Das Oracle-Read des gto entkam dem nur, weil es per Hand auf ein schmales vpip 0.32
(< 0.35) gesetzt ist; der Session-Read misst die echten 0.70 und fällt ins Fehlsignal. So kam der
−52-bb/100-Over-Call aus `BEFUND-gto-ueberdefense` unter dem realistischen Read zurück — der dortige Fix
(`under_bluffs` → `over_bluffs`) deckte nur den Oracle-Wert, nicht die Breite-Falle.
Range-**Breite** ≠ Bluff-**Frequenz**. Wer breit spielt, blufft nicht automatisch zu viel.
## Der Fix: trust-aware, auf dem direkten Bluff-Signal
`over_bluffs` feuert jetzt **nur** auf gemessene Postflop-Über-Aggression, der Breite-Term fällt weg:
```rust
const OVER_BLUFF_AGGRESSION: f64 = 0.45; // war 0.60, jetzt das alleinige Signal
fn over_bluffs(profile: &Profile) -> bool {
profile.aggression.is_some_and(|a| a >= OVER_BLUFF_AGGRESSION)
}
```
0.45 liegt zwischen balanciert (gto 0.35/0.40, gto-small darunter) und echtem Over-Bluffer (maniac 0.49/0.50):
der Maniac trippt weiter, der Balancierte nicht mehr. Das ist die Kronengleichung auf der Defensiv-Seite
(λ = belastbares Read): nur ein Read, der „dieser Gegner blufft zu viel" sagt, übersteuert den Modell-Fold —
und „zu viel bluffen" misst man an der Aggression, nicht an der Preflop-Breite.
## Beweis (gepaart, 95 %-CI)
**Boden-Achse** (`floor_read`, paired legacy vs neu, Memory, 4000 Austeilungen):
```
gto legacy -33.59 -> neu -26.75 | NEU-LEGACY +6.84 ± 6.74 Better (219 geänd.)
gto-small legacy -20.24 -> neu -14.10 | NEU-LEGACY +6.15 ± 4.50 Better (213 geänd.)
maniac legacy +82.57 -> neu +82.57 | NEU-LEGACY +0.00 ± 0.00 Identisch (0 geänd.)
```
Beide balancierten Ziele steigen signifikant (Intervall über 0); der Maniac ist **bit-identisch** — die
Über-Bluffer-Verteidigung, von der die Offense lebt, wird **nicht** zurückgegeben.
**Read-Lücke geschlossen** (`floor_read`, geshippter Code, Oracle/Blind/Memory, 2000 Austeilungen):
nach dem Fix steht Memory wieder bei Oracle statt bei Blind — der Boden feuert nicht mehr fälschlich.
```
Oracle Blind Memory
gto -17.80 -26.08 -18.26 (vor dem Fix: Memory = Blind = -40)
gto-small -2.63 -8.21 -2.88
```
(Absolut-Niveau ≠ Zwillings-Tor-Boden −23.93: andere Austeilungen — 2000/SEED hier vs 4000/seed^5 im
Tor, ±23-CI. Die Richtung zählt: Memory ≈ Oracle, der lesegetriebene Over-Call ist weg.)
**Zwillings-Tor** (`twin_gate`, Vollbudget, Baseline vs Kandidat) — die Accept-Regel:
```
Achse Baseline Kandidat Tor-Regel
OFFENSE (pop-EV) +43.95 +44.16 haelt (+0.21) OK
BODEN gto -36.25 -23.93 hoch um +12.32 OK
gto-small -25.93 -21.58 hoch um +4.35
reg/nit/fish -17.66/+42.92/+126.85 identisch unberuehrt
EXPLOITABILITY 77.03 77.03 identisch OK
```
`Gate::passes` = **true**: Population-EV hält, der Boden steigt, Exploitability steigt nicht. Die
Exploitability ist **konstruktiv** unverändert — die River-Batterie läuft mit `villain_profile: None`, und
der Fix berührt nur den Read-Profil-Zweig von `over_bluffs` (ungelesene Gegner feuern weiter über
`is_none_or`).
## Einordnung und was bleibt
Der Boden gegen den schlechtesten Balancierten (gto) steigt von −36.25 auf −23.93 bb/100 (Zwillings-Tor)
bzw. gepaart +6.84 ± 6.74 — **signifikant angehoben, ohne Offense oder Exploitability zu brechen**. Das war
der lesegetriebene Anteil, den die Oracle-Diagnose der früheren Befunde strukturell nicht sehen konnte.
Was **nicht** gelöst ist: der verbleibende Boden (gto −23.93) ist der Oracle-Rest — verteilte GTO-Distanz
(Aggression +97 / Defense −121 im `diag_gto`-Bucket), primär Cooler-Varianz auf starken Händen + Preflop-
Sunk-Cost gegen eine balancierte Range (`BEFUND-gto-restleck-river-overcall`). Den hebt kein Defense-Tweak;
er braucht den opponent-aware, trust-gegateten River-Subgame-Solver (`engine::decide` Kommentar, Stage A→live).
Der **Blind**-Zweig (`range_may_bluff` feuert bei ungelesenem Gegner, −40 vs Balancierte) ist bewusst
unangetastet: er trägt die Offense gegen die ungelesene Mikro-Population und wird vom Zwillings-Tor bewacht;
ihn anzufassen riskiert die +44 Population-EV und gehört in eine eigene, gepaart bewiesene Änderung.
## Werkzeug
- `src/bin/gto_read_probe.rs` — zeigt den Memory-Read je Archetyp + `classify` (das Fehlsignal sichtbar).
- `src/bin/floor_read.rs`, `src/bin/offense_proof.rs` — gepaarte legacy-vs-neu-Beweise (Boden- und
Offense-Achse) über einen temporären Mess-Schalter. (Schalter + Beweis-Bins nach Abnahme entfernt;
Reproduktion git-basiert wie die übrigen Befunde.)
+129
View File
@@ -0,0 +1,129 @@
# Befund: die −38 bb/100 heads-up gegen GTO sind ein Über-Call-Leck, kein Over-Barrel
**Messung** (`cargo run --release --bin diag_gto`, Szenario `heads-up gto`, 2000 Hände, deal-genau
wie die Leiter, luck-korrigiert). Gesamt **−38.44 bb/100** (≈ **−$77 / 100 Hände** bei $1/$2) —
exakt die Leiterzahl, der Nachbau ist treu.
## Die Aufschlüsselung nach Straße × letzter Hero-Aktion
Jede Hand wird ihrer **terminalen** Hero-Entscheidung zugeschlagen (Straße + Aktion). Die
bb/100-Beiträge summieren sich auf die −38.44.
```
bucket bb/100 hands bb/hand share%
river call -52.29 92 -11.37 4.6% <-- DAS LECK
preflop fold -21.73 244 -1.78 12.2%
turn fold -12.17 101 -2.41 5.0%
river fold -10.88 69 -3.15 3.5%
flop fold -10.28 138 -1.49 6.9%
river check -4.28 294 -0.29 14.7%
...
flop raise/bet +5.64 90 +1.25 4.5%
turn raise/bet +23.78 155 +3.07 7.8%
river raise/bet +31.21 153 +4.08 7.7%
preflop raise/bet +36.40 431 +1.69 21.6%
```
**Jeder Aggressions-Bucket ist positiv.** Preflop, Flop, Turn, River — wenn der Hero bettet oder
raist, verdient er (zusammen **+97 bb/100**). Das **widerlegt die Over-Barrel-Hypothese für diesen
Gegner**: die Engine barrelt nicht zu viel in genutzte Ranges, ihre Bets machen Geld. Der Verlust
sitzt vollständig auf der **passiven/defensiven** Seite.
## Die Wurzel: der River-Call
**−52.29 bb/100 aus nur 92 Händen (−11.37 bb/Hand).** Nach der vom Hero **selbst geschätzten
Equity** beim Call:
```
equity band bb/100 hands bb/hand
eq <0.35 -28.33 64 -8.85 <-- die Masse
eq 0.35-0.45 -11.86 20 -11.86
eq 0.45-0.55 -9.92 7 -28.34
eq >=0.55 -2.18 1 -43.60
```
**84 von 92 River-Calls macht die Engine mit unter 45 % Equity — nach ihrer eigenen Schätzung
hinten — und verliert in jedem Band.** Sie callt River-Bets, von denen sie weiß, dass sie geschlagen
ist.
## Mechanismus: der MDF-Boden feuert gegen einen ausbalancierten Gegner
`exploit::mdf_floor::floor` verwandelt auf dem River einen **modellgetriebenen Fold** einer
verteidigungswürdigen Made-Hand in einen MDF-Call — **es sei denn**, jeder lebende Gegner ist ein
*bestätigter Unter-Bluffer* (`under_bluffs`: Aggression < 0.25 **oder** Nit).
Das Oracle-Read des GTO-Gegners ist `p(vpip 0.32, pfr 0.22, fold_to_bet 0.42, aggression 0.40)`.
Aggression **0.40 ≥ 0.25**, und `classify` liest ihn als *plain regular*, nicht Nit. Also:
`under_bluffs = false` → `range_may_bluff = true` → **der Boden feuert**. Er überstimmt den korrekten
Modell-Fold und callt mit Unterpaar/Bottom-Pair gegen eine **ausbalancierte, wertlastige
River-Betting-Range**, die den Bluffcatcher schlägt.
Der Boden ist **auf die Mikro-Over-Folder kalibriert**, gegen die er gebaut wurde (Kommentar im
Modul: "mean equity bias ~−0.22, river fold-to-bet ~86 %" — das ist die Fish/Station-Leiter). Gegen
die verliert Über-Defense nicht, weil die wirklich zu viel bluffen/zu viel folden. Gegen einen
balancierten Werte-Better **zahlt dieselbe Über-Defense Value ab** → −11 bb pro Call.
## Position
```
seat 1 button/SB -12.48 bb/100
seat 2 BB -25.95 bb/100 <-- out of position blutet doppelt
```
Schlimmste Einzelzelle: **BB river call −33.45 bb/100**. Out of position, wo der GTO-Gegner mehr
bettet, über-verteidigt der Boden am meisten.
## Schlussfolgerung — beantwortet die Methoden-Weiche
1. **Stage B ist nicht der Fix für die −38.** Stage B (konditionierte Fold-Equity) zähmt das
*Barreln* — die Bet/Raise-Seite, die hier schon **+97 bb/100 Gewinn** macht. Es würde das Leck
nicht berühren und riskiert, die profitable Aggression zu beschneiden. Der Kern bleibt richtig
gebaut und bewiesen (`src/cfr/turn.rs`) für den Gegner, bei dem die Myopie *wirklich* der Leak ist
(Nit/Station, BEFUND-nit-read-leck) — nur nicht für diesen.
2. **Der Fix liegt auf der Defense-Seite und ist trust-aware** — genau die Kronengleichung
(`max E_belief[EV] − λ·KL`): λ = belastbares Read. Gegen einen **bewiesenen Over-Folder** (Fish/
Station) hart verteidigen; gegen einen **balancierten/wertlastigen** Better dem Modell-Fold
**trauen**. Konkret: `under_bluffs` / `range_may_bluff` so schärfen, dass ein balancierter Regular
(Aggression ~0.4, fold_to_bet ~0.42, pfr/vpip nah beieinander) den MDF-Boden **nicht** auslöst —
der Boden ist eine Antwort auf *gemessenes* Über-Folden, kein pauschaler Riegel gegen jeden, der
nicht Nit ist.
## Fix gebaut und gemessen
Der MDF-Boden feuert jetzt nur noch bei **positivem Over-Bluff-Beleg** (`over_bluffs`:
`classify == LooseAggressive` oder Aggression ≥ 0.60) oder gegen einen **ungelesenen** Gegner — statt
"gegen jeden, der nicht Nit ist". Ein balancierter/enger Regular (gto, reg) löst den Boden nicht mehr
aus; sein Fold wird dem Range-Modell überlassen (λ = belastbares Read). `src/exploit/mdf_floor.rs`:
`under_bluffs` → `over_bluffs`, `range_may_bluff` entsprechend geflippt. +2 Unit-Tests
(balancierter Regular nicht gefloort, Maniac weiter gefloort).
**Diagnose nach dem Fix** (`diag_gto`): heads-up gto **−38.44 → −24.83 bb/100**. Der River-Call-Eimer
**−52.29 → −25.58 bb/100** (92 → 32 Hände) — die dünnen Bluffcatcher unter 45 % Equity werden jetzt
gefoldet statt zwangsweise gecallt.
**Gepaarte Leiter** (nur dieser Fix isoliert, 17 Szenarien, PRE-FIX vs POST-FIX):
```
heads-up gto +13.61 ± 10.25 bb/100 60 geändert BESSER
6-max gto +7.38 ± 13.43 7 geändert nicht unterscheidbar
heads-up reg +9.20 ± 26.58 73 geändert nicht unterscheidbar
nit/maniac/fish/calling station/alle blind+memory +0.00 gleich (identisch)
GESAMT +0.78 ± 3.03 nicht unterscheidbar
```
**Kein Regress.** Die einzige signifikante Änderung ist heads-up gto BESSER (≈ +$27/100 bei $1/$2);
Nit/Maniac/Fish/Station/blind/memory sind bit-genau identisch — der Fix ist chirurgisch. `cargo test
--lib`: 41 grün.
## Was bleibt
Die anderen Defense-Lecks sind unberührt und das nächste Arbeitsfeld: **preflop fold** −21.73
(investieren und dann zum 3-Bet folden), **turn/flop fold** −12 / −10 (Barrel-Fold), und der
River-Check-Eimer. Der dominante Einzel-Leak (River-Über-Call) ist erledigt.
## Werkzeug
`src/bin/diag_gto.rs` — spielt das Leiter-Szenario auf dem Trace-Pfad nach und schlüsselt die
bb/100 nach Straße × terminaler Aktion, Position und (für den River-Call) nach eigener Equity auf.
Reproduziert die Leiterzahl deal-genau. Bleibt als Diagnose-Werkzeug.
+84
View File
@@ -0,0 +1,84 @@
# Befund: die Liga steht (L2 + L3) — Robustheit gegen einen ganzen Pool, und der Mittelwert verbirgt den Boden
Die adaptive Liga ist über L1 hinaus vollständig: **L2** (ein modellierender Gegner mit Posterior) und
**L3** (die Liga-Bewertung gegen einen ganzen Pool). Damit ist die synthetische Mess-Methodik komplett;
nur Stufe 4 (der Live-Abgleich) bleibt per Konstruktion dem Live-Farm vorbehalten.
## L2 — der modellierende Gegner (`Adapt::Model`)
L1 reagiert auf die rohe Hero-Aggressionsfrequenz — sofort, auch auf Rauschen. L2 führt einen **Beta-
Posterior** über die Bluffrate des Helden (`Beta(1+aggressiv, 1+passiv)`) und kontert nur nach Maßgabe
der **unteren Ein-Sigma-Konfidenzschranke**: `call_margin -= Gain · max(0, LCB − Referenz)`. Ein breiter
Posterior (dünne Stichprobe oder balancierter Held) zieht die Schranke zum Prior, also **keine
Überreaktion**; erst eine *sicher* hohe Bluffrate lockert die Calling-Schwelle.
Das ist der Gegner-seitige Spiegel genau des Prinzips, das der Engine selbst fehlt (die Krone: λ aus
Read-Konfidenz, KL-Vertrauensregion). Der Test `l2_model_waits_for_confidence_before_it_counters`
beweist es: bei gleicher 70-%-Frequenz kontert L2 die *dicke* Stichprobe strikt stärker als die *dünne*,
während L1 auf beide gleich reagiert.
Gegen die Population (`adaptive_gap`, 48 Gegner × 400 Austeilungen) gemessen, neben L1:
```
tighten Delta -0.59 ±5.81 (n.s.)
loosen Delta +20.03 ±5.91 (signifikant)
model Delta +14.89 ±5.00 (signifikant) <- L2, milder als der naive Loosen
```
L2 liegt erwartungsgemäß zwischen Tighten und Loosen: der konfidenz-gegatete Konter lockert weniger als
der rohe Loosen, also schöpft die Engine +14.89 statt +20.03 ab — die Engine beutet auch den
vorsichtigen Gegner aus, nur weniger stark, weil er ihr weniger Angriffsfläche gibt.
## L3 — die Liga (`sim::league`, `bin/league`)
Der Held wird gegen einen **Pool** bewertet: Populationszieher (statisch), die L1-Gegner (tighten/
loosen), der L2-Gegner und — fest verankert — der **Nemesis** aus Stufe 5. Das schlechteste Mitglied ist
der Boden; ein Change darf den Mittelwert heben, aber nicht gegen eine Schicht einbrechen (die
AlphaStar/Pluribus-Lehre: gegen eine Population von Antworten bewerten, nie gegen einen Einzelgegner, dann
überfittet nichts).
### Ergebnis (`league`, 12 Zieher + L1/L1/L2 + Nemesis, je 400 Austeilungen)
```
exploiter:nemesis -258.22 ±134.09 <- BODEN
L1:reg-loosen -44.08 ±87.61
pop:reg#3 -17.49 ±83.72
L1:reg-tighten +8.67 ±64.29
L2:reg-model +26.29 ±84.79
...
pop:fish#2 +119.78 ±67.55
Liga-Mittel : +27.55 bb/100
Liga-Boden : nemesis -258.22 bb/100
```
## Was das zeigt (ehrlich)
1. **Der Mittelwert verbirgt den Boden.** +27.55 im Mittel, aber −258 gegen den Nemesis. Genau der
Zweck der Liga: ein Change, der die Durchschnitts-EV hebt und dabei den Nemesis-Boden tiefer treibt,
ist **nicht** robust — und nur die Liga (nicht die bb/100-Leiter, nicht der Populationsschnitt) sieht
das.
2. **Der Nemesis als stehendes Mitglied.** Er reproduziert seine Klippe bei frischem Seed/Budget (hier
−258 statt −643, breite CI, aber mit Abstand das schlechteste Mitglied). Damit wird **jeder künftige
Change automatisch gegen das schärfste bekannte Leck geprüft** — kein Regress, der dort unbemerkt bleibt.
3. **Die balancierten Mitglieder clustern tief.** L1-loosen −44, pop:reg −17, L1-tighten +9 — dieselbe
GTO-Überdefense-Wurzel wie im Zwillings-Tor, jetzt auch in der Liga sichtbar.
4. **L2 ist milder als ein naiver Konter.** +26.29: der konfidenz-gegatete Gegner lässt der Engine mehr
als ein überreagierender L1, weil er gegen den (teils balanciert wirkenden) Engine-Helden nicht
überadjustiert — die LCB-Schranke wirkt wie beabsichtigt.
## Grenzen (ehrlich)
- 400 Austeilungen je Mitglied, einzeln (keine gepaarte Spiegelung über die Stile), daher breite CIs
(±33…±134). Die *Richtung* (Nemesis-Boden, balancierter Cluster tief, ausbeutbares Feld hoch) ist
robust, die Magnituden verrauscht. Ein Produktionslauf hebt die Deal-Zahl und nutzt die AIVAT-
Varianzreduktion.
- L2 modelliert über einen Postflop-Aggregat-Posterior; eine straßen-konditionierte Variante (flop/turn/
river getrennt) wäre der nächste Verfeinerungsschritt, braucht aber einen straßen-bewussten Gegner-Seam.
## Einordnung
Mit L2 + L3 ist die Liga (L0→L3) vollständig und die synthetische Lab-Methodik geschlossen: Population (0),
Kalibrierung (1), Zwillings-Tor (2), Liga L0–L3 (3), Optimizer (5). Die Liga macht „nie einen Verlierer
ausliefern" endgültig robust: **der Liga-Boden hält**, mit dem Nemesis als fest verankertem Härtetest.
Siehe `ARCHITEKTUR-synthetik-labor.md`.
+80
View File
@@ -0,0 +1,80 @@
# Befund: Live-A/B-Rückgrat + Insight-Aggregator (Stufe 1/2-Werkzeuge)
**Datum:** 2026-11-12
**Anlass:** Owner — „hast du schon das A/B testing vorbereitet? dass wir z.B. 12 Tische micro stakes
laufen lassen und extrem viele insights rausziehen können". Antwort: das Mess-Rückgrat (bb/100 +
95-%-CI, Nicht-Überlappung, Stufe-0-Bericht) stand; die A/B-Arm-Verdrahtung und die Insight-
Extraktion fehlten. Beide hier gebaut, pure-Python, auf Archiv bewiesen, **0 Regressionen**.
## Architektur-Befund (entscheidet die Form des A/B)
Die Engine wird **in einem Prozess** gerufen: `betrieb/runner.py` → `hand/entscheidung.hole` →
`entscheiden/decide.entscheide` shellt zum `rechner`-Binary (`COINPOKER_KERN`, `decide.py:22`). Ein
Läufer bedient **alle** Tische in **einem** Prozess; die Engine-Toggles (`MEM_PRIOR`, `SIZE_MIX`)
liest der Kern aus der Prozess-Umgebung und friert sie per `OnceLock` **einmalig** ein.
Folge: **zwei Arme können nicht gleichzeitig laufen** (ein Binary, eine eingefrorene Config). Das ist
kein Verlust — der statistisch **korrekte** Live-A/B ist ohnehin der **zeitliche**: alle Tische einen
Block auf Arm A, dann einen Block auf Arm B, abwechselnd. Gleiche Population über die Zeit, kein
Tisch-/Sitz-Confound. Gleichzeitig-pro-Tisch wäre schlechter (Tischwahl verzerrt). „12 Tische + viele
Insights" bleibt voll erhalten — nur eben zeitlich gearmt.
## Gebaut
### 1. A/B-Arm-Rückgrat (die Marke je Hand)
- `betrieb/runner.py`: `AB_ARM = os.environ.get("COINPOKER_ARM")` (leer = inert). In `ergebnisse`
trägt jede Hand `h["arm"]`; in der Zug-Protokollierung trägt jeder Zug `z["arm"]`. Persistiert
automatisch (`statistik.eintragen` schreibt das ganze Dict; `zuege.jsonl` ebenso).
- `betrieb/statistik.py`: `je_arm(haende)` — deskriptive bb/100-Tabelle je Arm (mit 95-%-Spanne),
in `kennzahlen_aus` und in `md_aus` (A/B-Abschnitt nur wenn ein Arm da ist).
- **Das Verdikt** liefert das schon spec-geprüfte `lesen/liveabgleich.ab_aus_log(haende, feld="arm")`
— der **Welch-Zwei-Stichproben-Test** auf bb/100 (ungepaart, korrekt). CLI:
`python3 lesen/liveabgleich.py --ab-log <haende.jsonl> arm`.
- Spec: `tests/ab_arm_spec.py` (8 grün), inkl. End-zu-End Arm→Welch. **Ändert die Engine-Spielweise
nicht** (reines Tagging/Reporting) — kann kein „Verlierer" sein, kein Leiter-Lauf nötig.
- Trockenlauf: 362 echte Archiv-Hände künstlich A/B gesplittet → Welch „kein signifikanter
Unterschied" (korrekt: Zufallssplit gleicher Population, 362 Hände ±200 bb/100). Beweist Pipeline
**und** Varianzrealität.
### 2. Insight-Aggregator `lesen/einblick.py` (der statistische Leak-Finder)
Aus den schon geloggten Zügen (`zuege.jsonl`: je Zug Lochkarten, Board, Aktion, Handklasse, Equity,
Engine-Grund — `lesen/handreview`). Anders als `betrieb/review.py` (Filter-Sucher) **aggregiert** es:
- `aktionen_je_street` — je Street Aktionsverteilung, Aggressiv-Anteil (BET+RAISE), Fold-Anteil.
- `vorflop_je_position` — Position aus dem Grund geparst ("MP open"→MP), je Position Aggressiv/Fold.
- `klassen_postflop` — je Handklasse (HighCard/Pair/TwoPair/…) die Aktionsverteilung (z. B. Anteil
gecheckter Drillinge).
- `grund_tags` — die Begründungs-Taxonomie des Kerns gefaltet (welche Regel wie oft feuert).
- `bericht(zuege, arm=…)` — mit `arm` nur die Züge **eines A/B-Arms** → Insights je Arm vergleichbar.
- CLI: `python3 lesen/einblick.py [zuege.jsonl] [--arm A] [--tags 20]`. Spec: `tests/einblick_spec.py`
(12 grün).
Trockenlauf auf 265 echten Zügen hob sofort Auffälligkeiten (im dünnen, alten Cash-Sample —
**kein** Strategie-Urteil): FLOP 0 % vs TURN 60 % aggressiv; RIVER 0 % aggressiv / 47 % Fold;
MP 133 Spots 100 % Fold. Das Werkzeug zieht die Leaks sauber heraus; ob sie echt sind, sagt erst ein
sauberer Micro-Lauf mit Volumen.
## Runbook — zeitlicher Live-A/B auf Micro
```bash
# Arm A (z. B. Prior an): einen Block fahren
COINPOKER_ARM=A MEM_PRIOR=1 python3 betrieb/runner.py --act
# Arm B (Baseline): einen Block fahren
COINPOKER_ARM=B MEM_PRIOR=0 python3 betrieb/runner.py --act
# Verdikt (Welch) + Insights je Arm
python3 lesen/liveabgleich.py --ab-log archiv/lauf/haende.jsonl arm
python3 lesen/einblick.py archiv/lauf/zuege.jsonl --arm A
python3 lesen/einblick.py archiv/lauf/zuege.jsonl --arm B
```
## Varianz (die ehrliche Grenze, gilt weiter)
Live keine Kartenpaarung → σ≈90 bb/100; A/B löst nur Δ≳20 bb/100 (Δ=5 bräuchte ~250k/Arm). Die
feinen Synthetik-Deltas sind live **nicht** auflösbar — Live-A/B nur für **grobe strukturelle** Hebel
und Sim-to-Real. Der nächste Hebel, der die A/B-Zahlen schneller signifikant macht: **All-in-EV je
Hand** (~−60 % Varianz). Die Infra ist halb da (`ev_chop`/`rit` je Hand, `equity`-Slot je Zug,
`lesen/evchop.py`), braucht aber Gegner-Showdown-Karten + All-in-Board je Hand zum Equity-Rückrechnen.
## Offen
- **All-in-EV** je Hand (Varianzreduktion) — nächster Baustein.
- `MEM_PRIOR` (Prior-Verdrahtung in `sim/memory.rs`, uncommitted): Leiter-Verdikt noch ausstehend.
- Alles hier **uncommitted** (Owner entscheidet Commit).
@@ -0,0 +1,91 @@
# Befund: Stufe 4, live-Hälfte — der Abgleich steht, und er feuert sofort: die Sim-Kante kommt am Tisch nicht an
Die live-Hälfte von Stufe 4 ist gebaut und gefahren: der **Sim-to-Real-OUTCOME-Abgleich**
(`lesen/liveabgleich.py`, Spezifikation `tests/liveabgleich_spec.py`). Er ist der Test, den die
Architektur „den einen unverzichtbaren Live-Test" nennt — und anders als die HUD-Hälfte (die den
Gegner-Fingerabdruck prüft) prüft er das Einzige, das zählt: **ob die vorhergesagte Kante echtes Geld wird.**
## Aufbau
Das Labor behauptet eine Kante: das Zwillings-Tor misst Offense **+43.95 bb/100** (die Engine beutet die
gezogene Population aus, Memory-Read). Der Abgleich liest, was der Live-Lauf tatsächlich verdient hat
(`archiv/lauf/haende.jsonl` — je eigener Hand `netto` in Chips, `bb` als Blindgröße, also `netto/bb`
stakes-normiert und addierbar), rechnet bb/100 mit 95-%-Winrate-Intervall und hält die Sim-Vorhersage
dagegen. Reine Funktionen wie die übrigen `lesen/`-Module; 13 Spezifikations-Tests grün.
## Ergebnis (`liveabgleich`, 190 echte Hände, 2026-10-29 bis 11-05)
```
REAL — was der Live-Lauf verdient hat:
gesamt n=190 bb/100 -266.75 95%: -560.44 bis +26.94
SIM — Vorhersage des Labors (Offense gegen die gezogene Population): +43.95 bb/100
GAP (real - sim): -310.70 bb/100
Urteil: KLAFFT — die Sim-Kante liegt ÜBER dem realen 95-%-Intervall.
```
## Was das zeigt (ehrlich)
1. **Der Test feuert — genau dafür ist er da.** Die obere Grenze des realen Intervalls (+26.94) liegt
**unter** der Sim-Vorhersage (+43.95). Das heißt: selbst bei der dicken Streuung von nur 190 Händen
überlebt die behauptete +44-Kante nicht bis zum Tisch; der reale Lauf verliert −267 bb/100. Das ist das
wichtigste einzelne Ergebnis des ganzen Labors: die Leiter sagte jahrelang „alles super" (Oracle-Read),
der Live-Abgleich sagt „die Kante kommt nicht an". Der Labor-Zweck — Selbsttäuschung aufdecken — ist erfüllt.
2. **Der Gap ist eine obere Schranke auf „Strategie", nicht reiner Strategiefehler.** Der Live-Lauf lief
NICHT unter Laborbedingungen. In den −267 stecken, untrennbar ohne den An/Aus-Split:
- **Andere Population.** Die echten Gegner sind nicht das synthetische Feld. Die Engine kann das
synthetische Feld schlagen und am echten trotzdem verlieren.
- **Betrieb.** Verstrichene Züge, AFK/Sitout (79 Auszeiten im Log), Client-Neustarts, AoF-Push/Fold,
Tischregeln, Rake — operative Verluste, keine EV der Entscheidung. Die Stake-Aufschlüsselung in
`archiv/lauf/STATS.md` zeigt das Muster: +372 bb/100 bei 50/100, aber −736 bei 1000/2000 und −402 bei
250/500. Die großen Minusse sitzen bei den hohen Stakes und wenigen Händen — nach Varianz und
Betrieb riechend, nicht nach einem flachen Strategie-Leck.
- **Varianz.** 190 Hände, Intervall fast 600 bb/100 breit. Das **Vorzeichen** des Gaps (Sim positiv,
real negativ, Sim über dem Intervall) ist belastbar; die **Magnitude** −311 ist grob.
3. **Die Richtung deckt sich mit den schon gefundenen Lecks.** Dass die Sim-Kante nicht ankommt, ist kein
Widerspruch zum Rest des Labors — es ist dieselbe Geschichte von der Geldseite: das Zwillings-Tor zeigt
den balancierten GTO-Boden (−36), der Nemesis die −415-Klippe (Barrel in die Station). Eine Engine, die
gegen Balancierte und gegen einen klebrigen Caller blutet, verdient an einem echten Feld voller solcher
Gegner ihr +44 nicht. Der Live-Abgleich ist die Außenmessung derselben Wurzel.
## Der A/B-Test ist fertig gerechnet — er wartet auf Hände, nicht auf Code
Den Gap in seine Teile zu zerlegen — wie viel Population, wie viel Betrieb, wie viel echte Strategie —
kann nur der **kontrollierte COINPOKER_KERN-An/Aus-Split**: derselbe Farm, dieselben Stakes, abwechselnd
mit und ohne Engine-Kern, und man zählt NUR die bb/100-Differenz der beiden Arme. Das paart die Confounds
weg.
Die **Rechnung dafür steht fertig und spezifiziert**: `liveabgleich.ab_vergleich(an, aus)` (CLI
`python3 lesen/liveabgleich.py --ab kern-an.jsonl kern-aus.jsonl`) nimmt die zwei Arm-Logs und liefert
die signifikanz-geprüfte bb/100-Differenz (Zwei-Stichproben-Welch-Intervall, Urteil schlägt/verliert/
unentschieden). An synthetischen Armen verifiziert (18 Tests grün); Demo:
```
Kern AN n=5 bb/100 +42.00 95%: -18.85..+102.85
Kern AUS n=5 bb/100 -126.00 95%: -180.95..-71.05
Differenz (an - aus): +168.00 bb/100 -> schlägt die Baseline signifikant (95% +86..+250)
```
Was fehlt, ist **allein das Laufen des Live-Farms unter beiden Armen** — eine reale, geldechte
Spiel-Session über Zeit, gegen echte Menschen auf CoinPoker. Das entsteht am Tisch, nicht in der
Werkbank: kein Code-Bauteil, sondern ein operativer Schritt, den nur der Betrieb (mit echtem Geld und
echten Gegnern über Stunden) ausführt.
**Und es braucht dafür keinen neuen Code — die Pipeline steht heute.** Der Schalter ist die Umgebung:
`COINPOKER_KERN` wählt das Engine-Binary (`entscheiden/decide.py:22`), `STATS_DIR` den Ausgabeordner
(`betrieb/statistik.py:258`). Zwei Läufe — Kern-Binary vs Baseline-Binary, je eigener `STATS_DIR` —
erzeugen zwei getrennte `haende.jsonl`, und `--ab arm_an/haende.jsonl arm_aus/haende.jsonl` druckt das
Urteil. Für ein EIN-Log mit Arm-Label gibt es `--ab-log` (Feld `kern`). Die genaue Befehlsfolge steht in
`RUNBOOK-liveabgleich-ab.md`. Das Werkzeug wartet auf die Daten, nicht die Daten auf das Werkzeug.
## Einordnung
Stufe 4 ist damit beidseitig gebaut und gefahren: die HUD-Hälfte (`BEFUND-simreal-stufe4`, der
Fingerabdruck-Gap, modest) und die Outcome-Hälfte (hier, der Geld-Gap, −311 und signifikant über dem
Intervall). Was offen bleibt, ist kein Modul, sondern ein kontrolliertes Live-Experiment, das nur Zeit und
Hände braucht. Der Abgleich ist jetzt der scharfe Außenspiegel des Labors — und sein erster Blick sagt
unmissverständlich: die Innen-EV ist noch nicht die Außen-EV. Genau diese Zahl zu schließen ist die Arbeit,
die die Mathematik-Roadmap meint. Siehe `ARCHITEKTUR-synthetik-labor.md`, Stufe 4.
+67
View File
@@ -0,0 +1,67 @@
# Befund: Populations-Prior in sim::memory — gemessener Verlierer, revertet
**Datum:** 2026-11-12
**Anlass:** Owner — „pokerintel muss genutzt werden und vor allem unser gedächtnis, wir müssen den
gegner extrem schnell kennen lernen". Idee: den schon gebauten, getesteten, aber unverdrahteten
Bayes-Populations-Prior (`exploit::posterior`, Beta-Bernoulli, PRIOR_STAERKE=10) in
`sim::memory::SessionMemory` einhängen, damit die Engine **ab Hand 1** liest statt 25 Hände blind
(`WARMUP_HANDS=25`). Verdrahtung hinter `MEM_PRIOR`-Schalter (Default an), `read_prior` neben
`read_raw`. Lib kompilierte, 10 sim::memory-Tests grün.
## Messung (gepaart, arch_read/nemesis_read, D=4000, SEED fix)
Sanity hält: der **Blind**-Arm ist zwischen `MEM_PRIOR=0` und `=1` bit-identisch (ARCH
+74.07/−13.67/+43.05/+83.03; Nemesis Oracle=Blind unverändert). Der Prior fasst nur den Memory-Arm an.
**ARCH — gap = Memory − Blind (alt → Prior):**
| Stil | gap alt | gap Prior | Δ | oracle-classify |
|--------|---------|-----------|----------|-----------------|
| fish | +58.51 | +59.85 | +1.34 | CallingStation |
| reg | +20.66 | +26.27 | **+5.61**| Regular |
| nit | +7.31 | +5.49 | −1.82 | Nit |
| maniac | −13.32 | **−45.46**| **−32.14** | LooseAggressive |
**NEMESIS — Memory-Arm bb/100 (alt → Prior), Blind zum Vergleich:**
| Nemesis | Blind | Memory alt | Memory Prior | Δ |
|-----------|---------|------------|--------------|----------|
| nemesis-1 | +80.04 | +77.16 | +67.73 | −9.43 |
| nemesis-2 | +114.16 | +79.25 | **+129.59** | **+50.34** |
| nemesis-3 | −26.41 | +0.29 | −1.46 | −1.75 |
## Urteil: REVERT
Kein sauberer Sieg. Große Gewinne (reg +5.61, nemesis-2 +50.34) stehen großen Verlusten gegenüber
(**maniac −32.14**, nemesis-1 −9.43). Der Maniac-Einbruch allein ist disqualifizierend nach dem
eisernen Gesetz „nie einen Verlierer ausliefern". `src/sim/memory.rs` auf HEAD revertet; die
Verdrahtung ist als Patch gesichert (`scratchpad/memory-prior-wip.patch`, 34 KB) für den verfeinerten
zweiten Anlauf.
## Wurzel (warum hilft er manchen, zerstört er andere?)
Der **uniforme** Populations-Prior zieht JEDE Lesung zur Median-Mitte (vpip 0.30, pfr 0.18,
fold_to_bet 0.45, **aggr 0.35**). Das ist gut für Gegner, deren wahres Bild nahe der Mitte liegt oder
die der rohe 25-Hand-Warmup früh fehlliest (nemesis-2: roh +79.25 unter Blind +114.16 = −35
Lese-Leck; der Prior kalibriert schneller → +129.59). Es ist **tödlich für aggressive Extreme**: beim
Maniac/LooseAggressive und nemesis-1 (aggr 0.62) schrumpft der Prior die Aggressions-Lesung Richtung
0.35 — die Engine liest „durchschnittlich", wo in Wahrheit extreme Aggression steht, und unter-
adjustiert in die Ausbeutung hinein. Die Aggressions-Achse ist genau die, wo ein Median-Prior am
meisten schadet, weil die exploitbaren Extreme dort am weitesten von der Mitte weg liegen.
Zusatz: der rohe Memory-Arm schadet dem Maniac schon ohne Prior (gap −13.32) — ein vorbestehendes
Loch (Memory-Lesung mis-exploitet den Maniac). Der Prior verstärkt es nur.
## Verfeinerter zweiter Anlauf (Wurzel angreifen, nicht Symptom)
1. **Prior nur auf die langsam konvergierenden passiven Achsen** (vpip/fold_to_bet), **nicht** auf
aggression — die Aggression roh/unverschoben lassen, damit Extreme sichtbar bleiben.
2. **Varianz des Priors auf der Aggressions-Achse weiten** (kleinere PRIOR_STAERKE nur dort), sodass
wenige aggressive Beobachtungen die Lesung schnell aus der Mitte ziehen.
3. **Stil-/Konfidenz-gated**: den Prior nur einsetzen, solange die rohe Beobachtung dünn ist UND die
frühe Lesung nicht schon ein Extrem andeutet (vgl. [[nemesis-station-mislabel]], confidence-ramp).
4. Erst dann wieder auf der Leiter messen — der Maniac-Arm ist der Gatekeeper.
## Offen
- Das vorbestehende Maniac-Loch im rohen Memory-Arm (gap −13.32) ist unabhängig vom Prior und bleibt.
- Live-A/B-Rückgrat + Insight-Aggregator stehen separat (`BEFUND-live-ab-einblick.md`), unberührt.
+171
View File
@@ -0,0 +1,171 @@
# Befund: Konfidenz-gewichtetes Stations-Trust — der Rest-Nemesis an der Klassengrenze
Nachsuche zu [[BEFUND-nemesis-station-fehllabel]]: der 0.45-Tor-Fix kippte den groben Fehllabel
(−409.86 → +80.73 bb/100), aber die CMA-ES gegen die reparierte Engine fand **Nemesis-2** — denselben
lesegetriebenen Leck-Typ, nur mit einer Aggression **knapp unter** dem Tor:
```
Nemesis-2 call_margin 0.173 raise_at 0.579 bet_at 0.748 open_at 0.800 bluff 0.229 size 0.996
Blind +114.01 bb/100
Memory -87.63 bb/100 konvergierter Read: vpip 0.65 pfr 0.15 fold2bet 0.56 aggr 0.41 -> CallingStation
```
Aggr 0.41 < 0.45 → er rutscht zurück in die **voll getrustete** Station und kassiert denselben Exploit.
## Warum kein tieferes Tor
Das Tor von 0.45 auf 0.40 zu senken, um aggr 0.41 zu fangen, quetscht den Reg-Archetyp (gemessene
Aggression 0.31 — nur 0.09 Luft, Memory-Rauschen überlappt), und die CMA-ES findet dann ein Nemesis-3
bei aggr ~0.33. Das ist Whack-a-Mole. Die Wurzel ist **nicht** die Lage des Tors, sondern seine
**Binärheit**: `earned_trust` gibt 1.0 für CallingStation und 0.0 sonst — ein Gegner direkt an der
Grenze bekommt den vollen Station-Exploit oder gar keinen. `read_gate` nennt das selbst als nächsten
Schritt: „The value is an f64, not a bool, to leave room for a partial, confidence-weighted trust later
without changing this seam."
## Der Fix: Trust als Konfidenz, nicht als Schalter
`exploit::style::station_trust(profile) -> f64` — eine Rampe statt eines Sprungs:
```rust
const STATION_MAX_AGGRESSION: f64 = 0.45; // oberhalb: keine Station (unverändert)
const STATION_FULL_TRUST_AGGRESSION: f64 = 0.20; // unterhalb: echte Station, volles Trust
pub fn station_trust(profile: &Profile) -> f64 {
if frequency(profile.fold_to_bet).is_some_and(|b| b <= STATION_FOLD_TO_BET) {
return 1.0; // ein echter Nicht-Folder: Nicht-Folden ist das Signal
}
match frequency(profile.aggression) {
None => 1.0, // kein Postflop-Sample: altes Verhalten, nichts regressiert
Some(a) => ((STATION_MAX_AGGRESSION - a)
/ (STATION_MAX_AGGRESSION - STATION_FULL_TRUST_AGGRESSION)).clamp(0.0, 1.0),
}
}
```
Eine echte passive Station (aggr ≤ 0.20, oder ein Nicht-Folder) bekommt `c = 1.0` und ist
**bit-identisch** zum alten binären Trust. Ein Grenzfall-Gegner bekommt eine Teil-Konfidenz: Nemesis-2
(aggr 0.41) nur `c = (0.45−0.41)/(0.45−0.20) = 0.16`.
### Jeder Kanal, der das Stations-Profil liest, wird mit `c` zur Blind-Grundlinie gezogen
`toward_blind(blind, x, c) = blind + c·(x − blind)` — voller Read bei `c=1`, reine Blind-Decke bei
`c=0`. Die Messung (nicht die Theorie) zeigte **vier** Kanäle, die das getrustete Profil lesen; jeder
einzeln skaliert, jeder bit-identisch bei `c=1`:
1. **`adjust.rs`** — die Stations-Schwellen-Shifts (`call_margin`, `value_raise`, `range_width`) skalieren
mit `c`: `base + shift·c`.
2. **`style_rung.rs`** — die Made-Hand-Boden-Sprosse: `-(round(c) as i32)` statt fix `-1`.
3. **`range_model.rs`** — der Preflop-Band-Stretch und das `unknown_role_band`-vpip werden per
`toward_blind` zur Blind-Breite gezogen (eine breite vpip-Lesung widert die modellierte Range nur so
weit, wie der Read getrustet ist).
4. **`fold_chance.rs`** — `fold_base` wird zur `DEFAULT_FOLD_TO_BET` (0.45) gezogen: ein fehlgelesenes
aggressives „Station"-fold_to_bet 0.56 trustet hero nur partiell, also **über-barrelt er nicht** in
eine leicht-raisende Range, deren Mehr-Straßen-Kosten die Einzel-Straßen-Bluff-EV nie modelliert.
## Beweis: die Wiederherstellung
`bin/nemesis_read` (Memory, 4000 Austeilungen), progressiv je Kanal-Gruppe:
```
binäres Trust (nur 0.45-Tor) -87.63 bb/100
+ soft-trust auf adjust / rung / range -54.34 bb/100
+ soft-trust auf fold_chance (Fold-Equity) +83.72 bb/100 (Blind-Decke +114.01)
```
Der dominante Kanal war die **Fold-Equity**: hero barrelte Flop/Turn in die vermeintlich foldende
Station und landete auf schlechten Rivern. Von −87.63 auf **+83.72** — hero schlägt den CMA-ES-
Extrempunkt jetzt deutlich auch unter dem realistischen Memory-Read.
**Der Boden ist unberührt** (`bin/arch_read`, 4000 Austeilungen, gap = Memory − Blind):
```
style blind memory gap
fish +74.58 +129.38 +54.81 (echte Station, aggr 0.11 -> c=1.0, bit-identisch)
reg -13.40 +4.00 +17.40
nit +43.05 +47.75 +4.70
maniac +82.57 +82.57 +0.00 (bit-identisch)
```
Kein Archetyp regressiert — jeder gap ≥ 0. Fish (die echte Station) behält volles Trust und ist
bit-identisch; Maniac ist unberührt.
## Der Rest: Mehr-Straßen-Kosten, nicht noch ein Schwellen-Tweak
Die verbleibende Lücke zur Blind-Decke (−30 bb/100) ist im `diag_nemesis which=2` lokalisiert:
```
bucket mem blind DELTA mem# blind#
river fold -74.96 -9.61 -65.34 578 336
turn call -33.45 +6.82 -40.27 210 156
...
river call +11.92 -23.00 +34.92 75 362
```
Der Rest ist **River-Fold-Übersteuerung**: hero erreicht den River deutlich öfter (578 vs 336) und
foldet — er floatet/barrelt die Vorstraßen noch etwas zu leicht und zahlt es auf dem River. Das ist
**keine** Trust-Kalibrierung mehr, sondern die bekannte Struktur-Grenze: die Einzel-Straßen-Bluff-EV
bucht fold × pot als Gewinn, ignoriert aber die Mehr-Straßen-Kosten der weiterspielenden (leicht-
raisenden, value-lastigen) Range. Das gehört in den opponent-aware, trust-gegateten River-Subgame-
Solver ([[engine-math-vision]] Stage A→live), nicht in einen weiteren Margin-Tweak. Nemesis-2 ist mit
+83.72 bb/100 kein Katastrophen-Leck mehr — gegen den Extrempunkt des Regelraums, nicht einen typischen
Gegner.
## Zwillings-Tor (Vollbudget, SEED 0x5EED_0001) — `Gate::passes` = true
```
Achse Baseline (efcff2b) soft-trust Tor-Regel
OFFENSE (pop-EV) +44.86 +50.58 haelt (+5.72) OK
BODEN (gto) -23.93 -23.93 bit-identisch OK
gto-small -21.58 -21.58 identisch
nit/maniac/fish +42.92/+45.58/+126.85 identisch unberuehrt
reg -17.66 -10.21 verbessert (nicht Boden)
EXPLOITABILITY 77.03 77.03 bit-identisch OK
```
Genau die vorhergesagte Signatur: jeder LooseAggressive/Nit/Maniac/Fish-Boden-Archetyp ist
bit-identisch (keiner klassifiziert als Grenzfall-Station), nur **reg** (der einzige Boden-Archetyp,
dessen Memory-Read an der Grenze als Station liest) und die **Offense** bewegen sich — beide nach oben.
Die Exploitability-Batterie läuft mit `villain_profile: None`, `classify` sieht nie ein echtes Profil →
bit-identisch, wie bei Leck 1. `Gate::passes`: Population hält (+5.72), Boden hält, Exploitability
steigt nicht.
## CMA-ES-Nachsuche: das lesegetriebene Loch ist zu — der Rest ist read-invariant
Die CMA-ES (`bin/nemesis`, Fast-Scan 1000×14) gegen die soft-trust-Engine findet ein **Nemesis-3**:
```
call_margin 0.396 raise_at 0.769 bet_at 0.615 open_at 0.468 bluff 0.261 size 1.148
Fast-Scan-EV −52.65 bb/100 (selektions-verzerrt nach unten, wie bei Nemesis-2: Scan fand −173, sauber −87)
```
Sauber nachgemessen (`bin/nemesis_read`, 4000) ist es ein **grundlegend anderer Befund**:
```
nemesis-3 Oracle −26.59 = Blind −26.59 = Memory −26.59 bb/100 (alle drei identisch)
konvergierter Read: vpip 0.31 pfr 0.30 fold2bet 0.79 aggr 0.47 -> classify Regular
```
**Blind ≈ Memory (exakt gleich) = ein echtes Loch, read-invariant** — das Gegenteil der lesegetriebenen
Familie (−414/−87), die dieser Fix schloss. Drei Dinge entscheiden es:
1. Nemesis-3 klassifiziert **Regular** → er wird ohnehin auf blind gegatet → die soft-trust-Änderung
(die nur CallingStation-Profile berührt) kann ihn **nicht** anfassen. Seine −26.59 sind bit-identisch
auf der pre-soft-trust- UND der pre-classify-Engine. Die CMA-ES brachte ihn nur ans Licht, weil die
lesegetriebenen Katastrophen jetzt zu sind — der Worst-Case wandert auf diesen vorbestehenden Punkt.
2. Die saubere EV ist **−26.59**, nicht −52.65 (Fast-Scan-Verzerrung, wie vorhergesagt).
3. Der Leck-Bucket (identisch in Blind und Memory): **river call −50.74** (117 Hände) gegen einen
tight-aggressiven Overbetter (vpip 0.31 ≈ pfr 0.30, size 1.148×Pot, blufft 0.261). Das ist eine
**Basis-Defense-Schwäche gegen River-Overbets**, keine Trust-Kalibrierung.
Das Loch-Schrumpfen (−414 → −87 → read-invariante −26.59) ist damit so weit, wie Trust-Kalibrierung es
bringen kann: der Rest ist die exakt vorhergesagte Struktur-Grenze — River-Defense gegen Overbets,
Domäne des opponent-aware River-Subgame-Solvers ([[engine-math-vision]] Stage A→live), **nicht** ein
weiterer Schwellen- oder Trust-Tweak. Das Zwillings-Tor schützt das Geshippte; nemesis-3 ist kein von
diesem Fix erzeugtes oder berührtes Leck.
## Werkzeug
- `src/exploit/style.rs::station_trust` — die Trust-Rampe + 4 Regressionstests.
- `src/bin/nemesis_read.rs` — EV je Lese-Modus; zeigt die Wiederherstellung zur Blind-Decke.
- `src/bin/arch_read.rs` — Boden-Archetypen Blind vs Memory; zeigt die Nicht-Regression.
- `src/bin/diag_nemesis.rs which=2` — Memory-vs-Blind-Bucket-Delta; lokalisiert den Rest-Kanal.
@@ -0,0 +1,183 @@
# Befund: der Nemesis — ein aggressiver Vielfalter, als Calling Station fehlklassifiziert
Das zweite Leck des synthetischen Labors: der CMA-ES-Nemesis (`sim::optimize::worst_case_opponent`,
`bin/nemesis`) fand den Gegner, gegen den die Engine am schlechtesten spielt — **−414 bb/100**
(Vollbudget-Lauf; mein Reproduktions-Read misst **−409.86 bb/100**). Der Brief nannte ihn einen
„klebrigen Low-Bluff-Caller, in den die Engine barrelt". Die Messung zeigt das Gegenteil: es ist kein
Over-Barrel und keine klebrige Station, sondern dieselbe Wurzel-Familie wie Leck 1 — **Preflop-Breite
übersteuert einen Read**, hier die gesamte Calling-Station-Klassifikation.
## Das Nemesis-Regelwerk (festes `Rules`)
```
call_margin 0.215 raise_at 0.587 bet_at 0.548 open_at 0.729 bluff 0.068 size 0.441
```
`call_margin` ist die Equity ÜBER den Pot-Odds, die der Gegner zum Callen verlangt (`reader.rs:47`) —
0.215 ≈ Reg (0.22), also **foldet Luft wie ein Reg**, keine Station (Fish 0.02). Zugleich **bettet er
viel** (bet_at 0.548, nahe Maniac 0.55) und **raist leicht** (raise_at 0.587 → raist ~41 % zurück, wenn
man bettet), **blufft aber fast nie** (0.068 ≈ Reg). Ein aggressiver, value-lastiger Vielfalter.
## Die entscheidende Messung: der Read ist das Gift, nicht die Hand
`bin/nemesis_read` misst die Engine-EV gegen dieses feste Regelwerk je Lese-Modus (4000 Austeilungen):
```
Oracle +81.41 bb/100 (Styled -> kein Oracle-Profil = blind)
Blind +81.41 bb/100 (kein Profil)
Memory -409.86 bb/100 (der Session-Read steht -> Katastrophe)
```
**Blind schlägt der Motor den Nemesis um +81.** Erst der aufgebaute Memory-Read kippt ihn auf −410 —
eine Spanne von **491 bb/100**, komplett lesegetrieben. (Coolers sind read-invariant; das hier ist es
nicht.)
## Die Wurzel: `classify` liest „Station" aus Preflop-Breite, gegen jeden Postflop-Befund
Der konvergierte Memory-Read des Nemesis (`bin/diag_nemesis`, 2000 Austeilungen):
```
vpip 0.53 pfr 0.14 fold2bet 0.65 aggr 0.62 -> classify CallingStation
```
`classify` stuft als CallingStation ein über den `loose`-Pfad (`vpip ≥ 0.35`), sobald der Gegner nicht
`LooseAggressive` ist (`pfr < 0.20`) — **egal, was fold_to_bet und aggression sagen**. Der Nemesis ist
breit preflop (vpip 0.53), aber er **foldet 65 %** und ist **hyper-aggressiv (0.62)** — das genaue
Gegenteil einer Station (passiv, foldet nie). Er erreicht „CallingStation" allein über die Breite.
Damit bekommt er **`earned_trust == 1.0`** (`read_gate`) — das Profil wird NICHT auf blind gegatet,
sondern voll ausgebeutet. Zwei Exploits feuern gegen den falschen Gegner:
1. **Station-Shift** (`style_shift`, CallingStation: `value_raise −0.04`, „value-bet thinner"): die
Engine value-bettet DÜNNER — in einen Gegner, der leicht zurückraist. Resultat: dünne Value-Bets
werden geraist, die Engine foldet investierte Chips (Terminal-Buckets `turn fold −152`,
`flop fold −153` im Baseline-`diag_nemesis`).
2. **Aggression-getriebener Bluff-Anteil** (`bluff_share::style_factor`): bei vorhandener aggression
gilt `aggression / 0.45`, hier `0.62 / 0.45 = 1.38×` — die Engine modelliert die value-lastige
Betting-Range des Nemesis als **über-durchschnittlich bluffig** und bluff-catcht sie ab. Der Nemesis
blufft 0.068 → die Calls verlieren (`turn call −163`, `river call −40`).
Beides ist dieselbe Verwechslung wie Leck 1: **Breite ≠ Bluff-Frequenz, und Breite ≠ Station.** Wer
breit spielt, ist nicht automatisch passiv. Nur die Postflop-Aggression trennt eine echte Station
(passiv) von einem aggressiven Vielfalter.
## Der Fix: eine Station ist loose UND passiv
`exploit::style::classify` — der `loose → CallingStation`-Pfad bekommt ein Aggressions-Tor:
```rust
const STATION_MAX_AGGRESSION: f64 = 0.45; // zwischen Reg (gemessen 0.31) und Maniac (~0.49)
let passive = aggr.is_none_or(|a| a < STATION_MAX_AGGRESSION);
...
} else if (loose && passive) || sticky {
Style::CallingStation
```
Der Nemesis (aggr 0.62) fällt aus dem `loose`-Pfad, ist nicht `sticky` (fold 0.65 > 0.30), nicht
`tight`, nicht `LooseAggressive` (pfr 0.14) → **Regular**. Regular hat `earned_trust 0` → `read_gate`
gatet ihn auf **blind**, die bewiesen sichere Grundlinie. Beide Fehl-Exploits schalten sich ab: das
Profil wird `None`, der Station-Shift entfällt, und `bluff_share` sieht `None` statt aggression 0.62.
`STATION_MAX_AGGRESSION = 0.45` liegt bewusst **über** der gemessenen Reg-Aggression (0.31) und der
echten Stations (Fish 0.11, Loose-Passiv-Test 0.0), aber **unter** dem Nemesis (0.62): die echten
Stationen bleiben Stationen, nur der aggressive Vielfalter kippt. Der `sticky`-Pfad (fold ≤ 0.30, ein
echter Nicht-Folder) bleibt aggressions-unabhängig eine Station — Nicht-Folden ist selbst das Signal.
Unbekannte aggression (`None`, noch kein Postflop-Sample) behält das alte breite Stations-Verhalten
(`is_none_or`), nichts regressiert für Profile ohne Postflop-Stichprobe.
## Beweis
**Leck geschlossen** (`bin/nemesis_read`, Memory, 4000 Austeilungen):
```
vorher nachher
Memory -409.86 -> +80.73 bb/100 (+490.59, = Blind-Decke +81.41)
classify CallingStation -> Regular
```
Die EV springt auf praktisch die Blind-Decke zurück (+80.73 vs. +81.41 blind, Rest −0.68 = Rausch:
der ungegatete MDF-Boden sieht per `raw` weiter aggression 0.62). Im `diag_nemesis` fällt die
Flop-Bet-Frequenz von 61.5 % auf 26.3 % — die Engine hört auf, dünn in die „Station" zu value-betten,
und spielt solides Blind-Poker.
**Keine Kollateralschäden an den Lese-Tests** (strukturell und gemessen):
- `tests/sim_reads.rs`: alle Oracle-Profile unverändert — CallingStation (aggr 0.02) und Fish (0.08)
bleiben Station, Maniac (pfr 0.42) bleibt LooseAggressive, Reg/Nit unverändert.
- Memory-Reads der Boden-Archetypen unverändert: Reg (aggr 0.31 < 0.45) bleibt Station, Fish (0.11)
bleibt Station, Maniac (pfr 0.21) bleibt LA, gto/gto-small (LA), Nit (tight) — **kein** Boden-Archetyp
kippt.
- 97 Lib-Tests grün (+4 neue `style`-Regressionstests), `exploit_style` 6 grün.
**Zwillings-Tor** (`twin_gate`, Vollbudget, SEED 0x5EED_0001; Baseline = efcff2b, deterministisch):
```
Achse Baseline (efcff2b) Kandidat Tor-Regel
OFFENSE (pop-EV) +44.16 +44.86 haelt (+0.70) OK
BODEN (worst) gto -23.93 gto -23.93 bit-identisch OK
gto-small -21.58 -21.58 identisch
reg/nit/maniac/fish -17.66/+42.92/+45.58/+126.85 identisch unberuehrt
EXPLOITABILITY 77.03 77.03 bit-identisch OK
```
`Gate::passes` = **true**: Population-EV hält (sogar +0.70), der Boden ist bit-identisch, die
Exploitability ist bit-identisch. Jeder Boden-Archetyp exakt wie die Baseline — wie strukturell
vorhergesagt: die Exploitability-Batterie läuft mit `villain_profile: None` → `classify` sieht nie ein
echtes Profil → **konstruktiv unverändert** (wie bei Leck 1); die Boden-Archetypen behalten ihre
Memory-Klassifikation → **unverändert**. Nur die Population-EV bewegte sich, und zwar nach oben: der
Fix kippt allein die loose + low-pfr + aggressive Draws (die Leck-Ecke) von Station auf Regular, genau
die Blutung — darum steigt die Offense leicht, statt zu fallen.
## Einordnung und was bleibt
Von −409.86 auf +80.73 bb/100 gegen den schlechtesten realistischen Gegner, den die CMA-ES finden
konnte — die Blind-Decke zurückgewonnen, ohne einen Boden- oder Exploitability-Beweis zu brechen. Es
war, wie bei Leck 1, ein lesegetriebenes Breite-als-Signal-Leck, das die Oracle-Diagnose nicht sehen
konnte (Oracle = blind für einen Styled-Gegner).
Was der Fix NICHT anfasst: der ungegatete MDF-Boden liest per `raw` weiter die rohe aggression 0.62 →
`over_bluffs` (aggression ≥ 0.45, Leck 1) feuert auf dem River, kostet aber nur den ~0.68-bb-Rest
gegen die Blind-Decke — innerhalb des Rauschens, kein eigenes Leck. Die Spannung „aggression hilft vs.
Maniac, schadet vs. aggressivem Value-Better" lebt im River-MDF-Boden und gehört, falls je relevant, in
den opponent-aware, trust-gegateten River-Subgame-Solver ([[engine-math-vision]] Stage A→live), nicht
in einen weiteren Schwellen-Tweak.
**Leck 3 (Live-Gap −311)** bleibt unberührt: es braucht operative Live-Farm-Daten, keinen
Code-Fix, den das Labor schließen kann.
## Robustheits-Nachsuche: das Loch schrumpft, der Rest ist die Trust-Struktur
Der Fix patcht nicht einen Punkt — die CMA-ES (`bin/nemesis`, jetzt mit `[deals] [generations]`
argv) gegen die REPARIERTE Engine neu laufen lassen zeigt, wie weit die kontinuierliche Robustheits-
Lücke zugeht:
```
vor dem Fix Nemesis-1 -414 bb/100 (Vollbudget) / -409.86 (Memory, 4000)
nach dem Fix Nemesis-2 -87.63 bb/100 (Memory, 4000; Schnellscan 400x8 fand -173, selektions-
verzerrt nach unten)
```
Nemesis-2 (`call_margin 0.173, raise_at 0.579, bet_at 0.748, open_at 0.800, bluff 0.229, size 0.996`)
ist **dasselbe lesegetriebene Leck**: Blind **+114.01**, Memory **−87.63** (`bin/nemesis_read`). Sein
konvergierter Read `vpip 0.65 pfr 0.15 fold2bet 0.56 aggr 0.41` → **classify CallingStation** — die
Aggression 0.41 liegt **knapp unter** dem 0.45-Tor, also rutscht er zurück in die getrustete Station.
Buckets wie bei Nemesis-1 (turn call −109, river/flop fold).
**Warum kein weiterer Schwellen-Tweak:** das Tor tiefer zu legen (z. B. 0.40), um aggr 0.41 zu fangen,
quetscht den Reg-Archetyp (gemessene Aggression 0.31 — nur 0.10 entfernt, Memory-Rauschen überlappt)
und die CMA-ES findet dann ein Nemesis-3 bei aggr 0.33. Die Wurzel ist das **binäre `earned_trust`**
(1.0 für CallingStation, 0.0 sonst): ein Gegner direkt an der Klassengrenze bekommt den vollen
Station-Exploit oder gar keinen. `read_gate` nennt das selbst als nächsten Schritt — „The value is an
f64, not a bool, to leave room for a partial, confidence-weighted trust later without changing this
seam." Das ist die saubere Lösung: Trust als Konfidenz, die den Exploit skaliert (Grenzfall → partiell),
plus der opponent-aware Range-Posterior, der die value-lastige Betting-Range direkt misst statt sie aus
`aggression/0.45` zu schätzen ([[engine-math-vision]]). Ein 0.01-Margin-Tweak ist das nicht wert — das
Zwillings-Tor schützt das Geshippte, und Nemesis-2 (−87, gegen den EXTREMPUNKT des Regelraums, kein
typischer Gegner) ist kein Katastrophen-Leck mehr, sondern die Struktur-Grenze der Heuristik.
## Werkzeug
- `src/bin/diag_nemesis.rs` — konvergierter Memory-Read + classify, Terminal-Bucket-Attribution
(aggressive vs. passive Seite) gegen das feste Nemesis-Regelwerk.
- `src/bin/nemesis_read.rs` — Nemesis-EV je Lese-Modus (Oracle/Blind/Memory): zeigt die Read-Lücke
und die Wiederherstellung auf die Blind-Decke.
+71
View File
@@ -0,0 +1,71 @@
# Befund: das Nit-Voll-Read-Leck ist Ueber-Barreln, nicht Unter-Barreln (Stage 5)
## Frage
Stage 3/4 liessen eine offene Wurzel: warum verliert selbst der KONSISTENTE volle Nit-Read gegen
blind (nit −50 bb/100), statt mindestens blind zu erreichen? Ein EV-Maximierer mit genauerer Info
sollte nie schlechter sein. Der Verdacht im BEFUND-offensiver-read war die Continue-Range-Schaetzung
(`call_floor`, Perzentil-Abbildung) sei fuer enge Ranges mis-kalibriert.
## Werkzeug
Ein Entscheidungs-Trace (`sim::table`: `Dec`, `Table::new/run`, `play_hand_traced`) und eine
Diagnose (`tests/sim_blind.rs::diagnose_nit_full_read_leak`): jede Austeilung heads-up gegen den Nit
einmal blind, einmal mit vollem Oracle-Read, gleiche Karten und gleicher Seed, so dass nur HEROs
read-getriebene Linien abweichen und sich das Kartenglueck exakt aufhebt
(`delta = oracle.hero_net − blind.hero_net`). Lokalisiert nach der ERSTEN abweichenden Entscheidung
(Strasse + Zug-Wechsel).
**Wichtig:** `decide()` gated intern (`read_gate::gate_reads`), also musste der Nit fuer die Messung
voruebergehend auf `earned_trust = 1.0` gesetzt werden, damit der volle Read den Riegel ueberlebt.
Danach zurueckgesetzt. (Ohne Promotion misst die Diagnose nur den defensiven MDF-Boden auf dem
rohen Spot: +1.3 bb/100 — der ausgelieferte, gegatete Zustand ist bereits leicht positiv.)
## Messung (voller Read, un-gated, 2×1000 Haende, FREE)
Gesamt ≈ −596 bb ueber 2000 Haende ≈ **−30 bb/100** (dieselbe Richtung wie die −50 der Leiter,
anderer Seed/ohne Rake). Nach Zug-Wechsel, schlechteste zuerst:
| Zug-Wechsel (erste Abweichung) | Haende | bb gesamt |
|---|---:|---:|
| flop: blind check → read **raise** | 140 | **−436.2** |
| flop: blind call → read raise | 9 | −146.7 |
| turn: blind raise → read fold | 1 | −115.0 |
| flop: blind raise → read check | 6 | −104.2 |
| ... (Rest klein) | | |
| flop: blind raise → read **call** (Pot-Control) | 3 | +157.3 |
| turn: blind abstain → read raise | 3 | +80.0 |
| river: blind call → read **fold** | 3 | +64.8 |
| flop: blind call → read fold | 13 | +53.5 |
| preflop: blind call → read fold | 8 | +20.3 |
Ein einziger Eimer traegt 73 % des Verlusts: **flop check → read raise**.
## Wurzel (korrigiert die bisherige Erzaehlung)
Der Riegel-Doc behauptete, der Read lasse die Engine "aufhoeren zu barreln und Fold-Equity liegen".
Die Daten zeigen das GEGENTEIL: der Read laesst die Engine **mehr barreln**. Er verwandelt
Flop-CHECKS in Bluff-RAISES, weil `table_fold` jetzt die wahre Nit-Fold-Rate 0.82 sieht und die
EINSTRASSIGE Bluff-EV `fold·Topf + (1−fold)·(called_share·Endtopf − Einsatz)` den Fold-Zweig
`0.82·Topf` als nahezu reinen Gewinn verbucht. Die 18 %, die weiterspielen, halten eine genuttete
Range und bluten ueber Turn und River weiter — ein MEHRSTRASSIGER Preis, den der einstrassige
Called-Zweig nie erfasst.
Also ist es **nicht** die Continue-Range-Kalibrierung (`call_floor`/Perzentil) — die DEFENSIVE Seite
desselben Reads gewinnt durchweg (mehr folden gegen den bewiesenen Nicht-Bluffer: +53.5, +64.8,
+20.3; Pot-Control statt Raise: +157.3). Nur die OFFENSIVE Seite blutet, und zwar an genau einer
Stelle: einstrassige Fold-Equity treibt Flop-Bluff-Raises, deren Called-Zweig mehrstrassig verliert.
Das deckt sich mit Stage 4: offensiven Trust auf 1.0 zu zwingen war noch SCHLECHTER (−88), weil das
genau diesen Ueber-Barrel-Hebel voll aufdreht.
## Schluss
- Der Riegel (Nit → blind fuer die Offense) bleibt gemessen richtig; der Doc-Grund war invertiert und
ist korrigiert.
- Der ausgelieferte, gegatete Zustand gegen den Nit ist leicht positiv (+1.3 bb/100), getragen allein
vom defensiven MDF-Boden.
- Kein Engine-Verhalten geaendert. Geliefert: das Trace-Werkzeug, die Diagnose, der korrigierte Doc.
## Echter naechster Schritt (zu messen, nicht blind zu bauen)
Der Defekt ist die EINSTRASSIGE Bluff-EV, nicht eine Konstante. Ein sicherer offensiver Read braucht,
dass der Called-Zweig eines Bluff-Barrels auf Flop/Turn den mehrstrassigen Preis sieht, wenn die
Continue-Range eng und stark ist (Nit: hoher Floor, niedriger `continue_share`). Hypothese zum Test:
eine Fortsetzungs-Strafe auf den Called-Zweig von Nicht-River-Bluffs, skaliert mit Enge/Staerke der
Continue-Range. Erfolgskriterium: bringt den vollen Nit-Read auf der Leiter auf ≥ blind, OHNE die
verdienten Stile (Station/Fisch) zu kosten. Sonst: Befund festhalten, Riegel behalten.
+50
View File
@@ -0,0 +1,50 @@
# Befund: der offensive Read laesst sich nicht abspalten (Stage 4)
## Idee
Stage 3 zeigte: den vollen Read eines starken Spielers zu behalten kostet (nit −50, reg −176
bb/100 heads-up), weil das Range-Modell seine Continue-Range ueberschaetzt. Vermutung: der WERT
steckt im OFFENSIVEN Teil — ein Nit foldet ~82 % zu Bets (gegen 0.45 blind), also liess die Engine
Fold-Equity liegen. Plan: nur den offensiven Pfad (`table_fold`, `steal_width`) die wahre Fold-Rate
sehen lassen, das Range-Modell blind halten. Die EV-Mathe schien das abzusichern:
`fe*Topf + (1-fe)*(Called-Zweig)`, nur `fe` hoch, der Called-Zweig unveraendert -> scheinbar strikt
mehr +EV-Bluffs.
## Messung
Offensiver Trust fuer alle Stile auf 1.0, Leiter gegen die blinde Basislinie:
| Szenario | offensiv-nur gegen blind | Urteil |
|-----------------|-------------------------:|------------|
| heads-up reg | −204.41 | SCHLECHTER |
| heads-up nit | −87.69 | SCHLECHTER |
| heads-up maniac | −78.09 | SCHLECHTER |
| 6-max reg | −72.94 | SCHLECHTER |
| 6-max nit | −35.14 | SCHLECHTER |
Noch SCHLECHTER als der volle Read (nit −50 in Stage 3). Die Abspaltung schadet aktiv.
## Wurzel
Fold-Rate und Continue-Range sind ZWEI SEITEN EINER MUENZE. Ein Nit foldet 82 %, WEIL er nur mit
starken Haenden weiterspielt. Nimmt man die hohe Fold-Rate (Offense), muss man die starke, enge
Continue-Range (Defense) mitnehmen. Entkoppelt (hohe Fold-Rate + blinde, weite Continue-Range) baut
man ein INKONSISTENTES, zu optimistisches Modell: die Engine bettet mehr, und die ~18 % der Bets,
die gecallt werden, laufen in eine viel staerkere Range als modelliert — der Called-Zweig verliert
gross, der Fold-Zweig gewinnt nur den Topf. Netto Minus.
Blind spielt gegen starke Spieler eine MODERATE Aggression, die nahezu optimal ist: ohne die
Fold-Rate zu kennen, bettet sie massvoll, und Upside (Folds) und Downside (starke Continues) heben
sich auf. Es gibt kein freies offensives Mittagessen gegen starke Spieler.
## Schluss
Zurueckgebaut; kein Code geliefert. Der Riegel (station-only, sonst blind) bleibt gemessen richtig.
Beide naheliegenden Hebel sind nun widerlegt: der volle Read (Stage 3) UND der offensiv abgespaltene
Read (Stage 4) verlieren gegen starke Spieler. Der Exploit hat nur gegen Ueberzahler positiven Rand,
wo die Continues schwach und weit sind.
## Was bleibt (echter naechster Schritt)
Ein besseres Gegnermodell, nicht ein weiterer Riegel-Hebel. Zwei Richtungen:
1. Pruefen, warum selbst der KONSISTENTE volle Read (hohe Fold-Rate + enge Continues) gegen den Nit
verliert statt mindestens blind zu erreichen — ein EV-maximierendes Modell mit genauerer Info
sollte nie schlechter sein. Verdacht: die Continue-Range-Schaetzung (Perzentil-Abbildung,
`call_floor`) ist fuer enge Ranges mis-kalibriert, die Exploit-Fehler ueberwiegen die Info.
2. Oder die Sitzungsschleife (Stage 1/2) nutzen, um nur dort zu exploiten, wo die Beobachtung einen
klaren, gegen blind gemessenen Rand zeigt — statt eines pauschalen Stil-Reads.
@@ -0,0 +1,89 @@
# Befund: der Optimizer steht — und findet sofort eine Klippe: ein realistischer Gegner, gegen den die Engine −643 bb/100 verliert
Stufe 5 des synthetischen Labors ist gebaut: ein ableitungsfreier **Optimizer** über die Objektiven des
Labors (`sim::optimize`, `bin/nemesis`). Er ist eine Diagonal-Kovarianz-CMA-Evolutionsstrategie (der
separable-CMA-ES-Kern, Ros & Hansen 2008; Konstanten aus Hansens Tutorial 2016, Kovarianz diagonal → kein
Eigenwertzerfall, keine Abhängigkeiten).
## Validierung (analytisch, deterministisch)
- Sphäre (4-dim) → f < 1e-6. ✓
- Rosenbrock → erreicht das Becken des Optimums (f < 2e-2 bei (≈1, ≈1)); die diagonale Variante grindet
das gekrümmte Tal langsam entlang (bekannte sep-CMA-ES-Grenze, ehrlich im Test dokumentiert). ✓
- Verrauschtes Objektiv → findet die Optimumsregion trotz Wobble. ✓
Die λ Kandidaten je Generation sind unabhängig und werden **parallel** ausgewertet (`f: Fn + Sync`);
das Sampling bleibt sequentiell, also ist das Ergebnis trotz Threads deterministisch im Seed. Das war
nötig: das Winrate-Objektiv ist einzel-threadig je Gegner, und die Parallelisierung holt die Kerne
zurück, die die Populationsläufe nutzen (eine einzel-threadige Suche lief >70 min, multi-core ein
Bruchteil).
## Erste Anwendung: der Nemesis (`nemesis`, 300 Austeilungen × 8 Generationen)
Statt „schlechtester von sechs Archetypen" (der Boden des Zwillings-Tors) sucht der Optimizer den
schlechtesten Gegner im **ganzen kontinuierlichen 6-dim-Regelraum** — eine empirische beste Antwort in
Gegner-Raum, die tightste Robustheitsprobe. Gefunden:
```
Nemesis-Regelwerk:
call_margin 0.147 raise_at 0.597 bet_at 0.616
open_at 0.817 bluff 0.396 size 0.270
Engine-EV gegen den Nemesis: -642.96 bb/100
```
## Was das heißt (ehrlich)
1. **Es gibt eine Klippe.** Dieselbe Engine, die die ganze Population mit +32 schlägt und Fisch/Maniac mit
+120 zerlegt, **verliert katastrophal** gegen eine bestimmte realistische Konfiguration: einen
loose-aggressiven Small-Ball-Dauer-Reraiser (niedriges `call_margin`, `raise_at` 0.597 fast am
Aggressions-Boden, hoher `bluff` 0.396, kleines `size` 0.270). Er re-raist unablässig klein mit weiter
Range und blufft viel. Der Durchschnitt (+32) verbarg diesen Abgrund völlig — genau der Grund, warum
Worst-Case-Suche nötig ist und der Mittelwert allein trügt.
2. **Richtung sicher, Magnitude verrauscht.** 300 Austeilungen sind wenige, −643 ist aber weit jenseits
jedes Rauschens: die *Existenz* des Lecks ist belastbar, die genaue Zahl nicht. Die Konfiguration
zeigt, wo zu graben ist: die Reaktion der Engine auf relentless kleine Aggression (vermutlich
Überfolden gegen die kleinen Reraises, oder eine Fehlklassifikation des Reads, die den Hebel
invertiert). Das ist der nächste echte Engine-Fix — vom Labor aufgedeckt, nicht erraten.
3. **Der Optimizer ist das Werkzeug, nicht nur für Gegner.** Dieselbe Maschine tunt die Engine-eigenen
Hyperparameter gegen die Population, sobald sie als Vektor exponiert sind — der „Feinschliff, zuletzt"
der Architektur. Sie ist fertig; es fehlt nur dieser Hook.
## Nachtrag: Vollbudget-Lauf (`nemesis`, 1000 Austeilungen × 14 Generationen)
Der Demo-Lauf oben (300×8) könnte die Klippe über- oder unterzeichnen. Deshalb nachgefahren bei vollem
Budget — mehr Austeilungen je Auswertung (strafferes EV), mehr Generationen (tiefere CMA-Konvergenz):
```
Nemesis-Regelwerk:
call_margin 0.215 raise_at 0.587 bet_at 0.548
open_at 0.729 bluff 0.068 size 0.441
Engine-EV gegen den Nemesis: -414.81 bb/100
```
**Die Klippe ist bestätigt — und das Vollbudget findet eine *andere* Wurzel.** Statt des loose-aggressiven
Reraisers (300×8) konvergiert die tiefere Suche auf einen **klebrigen Low-Bluff-Caller**: hohes
`call_margin` 0.215 (zahlt weit ab), `bluff` 0.068 (fast nie), mittleres `size` 0.441. Die Engine blutet
also **in die Calling-Station hinein** — sie barrelt/blufft gegen einen Gegner, der nie foldet und nie
selbst blufft. Das ist dieselbe Over-Barrel-/Over-Defense-Wurzel, die `BEFUND-gto-restleck-river-overcall`
und das Zwillings-Tor (Boden = balancierter gto) zeigen, hier aus der entgegengesetzten Richtung getroffen.
Dass zwei Budgets zwei verschiedene −400…−640-Klippen finden, heißt: es ist kein 300-Hand-Artefakt,
sondern ein breites Worst-Case-Tal. Die *Existenz und Größenordnung* (mehrere hundert bb/100) ist damit
budget-robust belegt; die genaue Zahl und der genaue Nemesis-Punkt wandern mit Budget/Seed.
## Grenzen (ehrlich)
- Das Winrate-Objektiv kostet ~Zehn-ms je Hand; eine Suche mit vielen Austeilungen je Auswertung ist
teuer. Eine Produktionssuche braucht die bewiesene AIVAT-Varianzreduktion (`sim::aivat`), um bei
gleicher Präzision mit weniger Austeilungen je Auswertung auszukommen — der in der Architektur genannte
Hebel. Der Demo-Lauf ist bewusst klein gehalten.
- Der Nemesis ist ein einzelner Punkt; eine robuste Härtung mittelt über mehrere Seeds und prüft, dass
ein Fix die Klippe schließt, ohne die +32-Population-EV oder den Zwillings-Tor-Boden zu brechen.
## Einordnung
Stufe 5 schließt das Labor: Population (0), Kalibrierung (1), Zwillings-Tor (2), adaptive Liga L1 (3),
Optimizer (5). Der erste Lauf liefert sofort den schärfsten offenen Engine-Befund dieser Arbeit — eine
realistische Klippe von −643 bb/100 —, den weder die Leiter noch der Populationsdurchschnitt je zeigten.
Siehe `ARCHITEKTUR-synthetik-labor.md`.
@@ -0,0 +1,62 @@
# Befund: das fehlende Maß ist gebaut — und die Engine ist am River massiv ausnutzbar
MODULES.md nennt es ausdrücklich als Lücke: *„Postflop-Exploitability gegen eine Best Response fehlt
noch."* Diese Runde ist sie gebaut — und liefert sofort die erste quantitative Zahl dafür, wie weit
die Heuristik vom Gleichgewicht entfernt ist.
## Was gebaut wurde
`sim::exploit_river` (Harness) + `src/bin/exploit_scan.rs` (Abtastung). Für ein **River**-Subgame
(die einzige Straße, die exakt ist: Board komplett, Showdown exakt, keine Zukunft):
1. **Card-exakte Buckets:** jede Combo beider Ranges nach exakter Showdown-Stärke auf dem Board
(`hand::showdown::best`) in eine gemeinsame Stärkeleiter einsortiert; Card Removal zwischen den
Ranges steckt in der gemeinsamen Austeilungstabelle `chance[i·n+j]`.
2. **Gleichgewichtswert v\*:** mit dem geteilten CFR+-Kern gelöst (`cfr::river::tree_with_chance`, neu
freigelegt).
3. **Engine als Held:** an jedem Held-Knoten und Bucket wird die **lebende** Engine befragt
(`engine::decide`, Repräsentant je Bucket) → reine Aktion je Bucket.
4. **Villain antwortet mit Best Response** auf diese feste Politik über die wahren Ranges.
`exploitability = v* − Wert(Engine | Villain antwortet optimal) ≥ 0`, in bb/100. Validiert durch drei
Tests: eine Nash-Strategie meldet ~0 (Pipeline korrekt), „alles folden" ist ausnutzbar, die lebende
Engine läuft und liefert eine endliche, nicht-negative Zahl.
## Erste Abtastung (volle OOP-Range gegen volle Range, Topf 6 / Bet 4, 60k Iter)
```
Board Belief v* Engine Exploitability
dry ace-high unread -19.4 -94.6 75.2 bb/100
paired unread -19.5 -51.6 32.1
wet connected unread -19.9 -63.0 43.0
monotone unread -20.3 -75.5 55.2
low dry unread -19.1 -83.5 64.4
broadway unread -20.2 -98.4 78.3
dry ace-high gto -19.4 -127.9 108.5
broadway gto -20.2 -103.2 83.1
```
- **v\* ≈ −19..−20 bb/100**, stabil über alle Texturen und **belief-unabhängig** (korrekt: v* ist das
Gleichgewicht des Baums, nicht der Engine-Glaube) — der Positions-Tax des OOP-Erstaktiven.
- **Die Engine gegen Best Response verliert 32–108 bb/100 mehr als v\***. Der River wird also
**massiv ausgenutzt**, sobald der Gegner optimal antwortet — genau das Leck, das die bb/100-Leiter
gegen die fixen Bots **komplett verdeckt** (die antworten nie optimal).
## Bedeutung
Das ist der quantitative Beweis der Vision-These: Die Single-Street-Heuristik ist am Postflop
ausnutzbar, ein echter Solver ist nötig — jetzt mit **Zahl**, nicht Bauchgefühl. Und es ist das Maß,
gegen das sich jede Solver-Stufe ab jetzt beweist (Exploitability runter), unabhängig vom
Cooler-Rauschen der Leiter.
**Caveat (ehrlich):** Das Subgame „volle Range, OOP, erster Zug" ist härter als ein realistischer,
durch vorheriges Setzen **verengter** Spot — die Zahlen sind eher eine obere Schranke. Nächste
Schritte: (a) verengte Ranges messen (realistische River-Spots), (b) eine echte River-Strategie
(Stage A, lebend) einsetzen und zeigen, dass die Exploitability **sinkt** — zum ersten Mal ein
belegbarer Solver-Gewinn, den die Leiter nicht zeigen konnte.
## Status
`src/cfr/river.rs` (Builder freigelegt), `src/sim/exploit_river.rs`, `src/bin/exploit_scan.rs`,
`src/sim/mod.rs`. 44 Lib-Tests grün. Reine Mess-Infrastruktur — ändert keine Spielentscheidung, kann
also nicht „verlieren". Nichts committed.
@@ -0,0 +1,40 @@
# Befund: der Read-Riegel als Earned-Trust-Tabelle (Stage 3)
## Frage
Der Riegel (`engine::read_gate`) liess bisher nur die Calling Station durch und spielte jeden
anderen Stil blind. War das zu vorsichtig? Welche Stile haben ihren Read auf der Leiter verdient?
## Messung
Earned-Trust-Tabelle gebaut (`earned_trust: Style -> f64`), der Riegel ist jetzt `> 0.0` statt ein
fester Fall. Im Experiment jeder Nicht-Ueberzahler auf volle 1.0 gesetzt und die Leiter gegen die
blinde Basislinie (`benchmarks/baseline.txt`, df915b1) gefahren:
| Szenario | Read gegen blind | Urteil |
|--------------------|-----------------:|-------------------|
| heads-up reg | −176.02 | SCHLECHTER |
| heads-up maniac | −147.57 | SCHLECHTER |
| heads-up nit | −50.44 | SCHLECHTER |
| 6-max reg | −61.79 | SCHLECHTER |
| 6-max nit | −22.39 | nicht unterscheidbar |
| 6-max maniac | +72.54 | nicht unterscheidbar |
Der Nit macht aus einem blinden +37.73-Gewinner einen Verlierer. Kein starker Stil wird irgendwo
sauber BESSER.
## Wurzel
Den Profil-Read eines starken Spielers zu behalten laesst das Range-Modell seine Continue-Range
ueberschaetzen -> die Engine hoert auf zu barrelen und verliert ihre Fold-Equity. Der DEFENSIVE
Wert eines starken Reads (duenne Value nicht in einen bewiesenen Nicht-Bluffer zahlen) wird ohnehin
schon vom ungegateten MDF-Boden geerntet (`mdf_floor::floor` auf dem rohen Spot in `engine::decide`).
Der Riegel steuert nur die OFFENSIVEN Anpassungen, und die zahlen sich allein gegen Ueberzahler aus.
## Schluss
Die Tabelle bleibt beim Ueberzahler (1.0), alle anderen 0.0 — verhalten identisch zur alten
`matches!(CallingStation)`, aber jetzt datengetrieben und je Stil mit Messung belegt. Der konservative
Riegel ist nicht bloss vorsichtig, sondern gemessen richtig.
## Naechster Schritt
Ein SICHERER offensiver Read gegen starke Spieler: nicht das ganze Profil ins Range-Modell geben,
sondern nur die Teile, die die Leiter als +EV beweist (z. B. Steal-Frequenz gegen den Nit, der 82 %
zu Bets foldet, ohne die Continue-Range zu ueberschaetzen). Dann verdient sich der Nit seinen Platz
in der Tabelle mit einem Wert > 0.
@@ -0,0 +1,102 @@
# Befund: der River-Solver geht live — als defensives Veto, nicht als Ersatz
Der höchste Hebel der Mathematik-Landkarte ([[ROADMAP-mathematik]], Zeile 1): den bewiesenen, aber
stillgelegten River-Subgame-Solver *sicher* in den Live-Pfad bringen. Stage A bewies ihn unausnutzbar
(0.0 bb/100 gegen korrekte Überzeugung), aber naiv verdrahtet kostete er **−43 bb/100** — er spielte
ausbalanciertes GTO gegen Gegner, die man ausnutzen muss ([[BEFUND-river-solver-balanced-vs-exploitable]]).
Dieser Befund baute zuerst das volle Getriebe (Belief + Vertrauen), **maß es, verwarf es, und engte es
auf seinen einen bewiesenen Vorteil ein.** Das ist die Eiserne Regel in Aktion: nie einen Verlierer
shippen — erst messen, dann die Form dem Beweis anpassen.
## Schritt 1 — das volle Getriebe (Belief + Vertrauen): gemessen, verworfen
Die Idee: statt der Heuristik den **KL-gebundenen Best Response gegen den geglaubten Gegner** über das
kartengenaue River-Subgame spielen — λ aus der Read-Konfidenz, sodass ein starker Read ausnutzt und ein
schwacher zu bewiesenem GTO zusammenfällt. Primitive alle vorhanden (`cfr::kl_br`, `believed_villain`,
`lambda_from_confidence`); 6 Unit-Tests grün; sauber verdrahtet.
**Die Leiter sagte Nein.** Das volle Getriebe ersetzte Heros ganze River-Entscheidung (Bet/Check **und**
Call/Fold) und verlor genau dort, wo die Heuristik schon gewinnt — die Ausnutzung lockerer Gegner:
| Nemesis | Blind | Memory (volles Getriebe) | Δ vs Soft-Trust-Boden |
|---|---|---|---|
| nemesis-1 | +81.41 | +71.84 | ≈ −10 |
| nemesis-2 | +114.01 | **+35.21** | **−48** (Boden war +83.72) |
Die KL-um-GTO-Politik ist **schwächer als die Heuristik** im Angriff: sie kann GTOs Support nur
umgewichten, nie die dünnen Value-Bets und leichten Calls spielen, mit denen die Heuristik+Memory einen
Fisch für +83 ausnimmt. Ein Ersatz dieser Offense durch eine Near-GTO-Linie **blutet** — das −43-Muster,
schlimmer. → Verworfen.
## Schritt 2 — die Einengung: nur das defensive Veto
Der **einzige** Ort, an dem das Getriebe ein bewiesener Vorteil ist, ist die **Verteidigung**: die
Single-Street-Heuristik **über-callt unter-gebluffte River-Overbets** (nemesis-3), weil ihr Range-Modell
den GTO-Bluffanteil `s/(P+s)` trägt, den ein tighter Bettor nicht hat. Also lässt der Befund die Offense
der Heuristik unangetastet und fügt genau eine Regel hinzu:
> **`fold_veto` (nur Cash):** foldet einen heuristischen **Call** gegen eine River-Wette, wenn ein
> **konfidenter** Read sagt, der Gegner **unter-blufft** (der KL-Best-Response gegen den geglaubten
> Gegner callt Heros Bucket an Knoten 4 seltener als `VETO_CALL_FLOOR`=0.5). Nie ein Bet/Check/Raise,
> nie bei dünnem Read, nie bei Turnier-Prämie (`premium > 0` → ICM bleibt in der Heuristik).
Konstruktiv sicher gegen den −43/−48-Regress: das Veto **kann Heros Offense nicht ändern**, nur einen
vom Read als verlierend bepreisten Call ablehnen. Gegen einen echten Bluffer (hohe `aggression`) glaubt
`believed_villain` eine bluffreiche Wettrange → Veto feuert nicht → die leichten Calls der Heuristik
bleiben. Gegen Stations/Fische (betten ihre ganze Range) feuert es ebenfalls nicht.
## Beweis (Leiter, gepaart, glückskorrigiert, SEED 0x5EED_0001, 4000 Austeilungen)
Die Veto-Leiter (`bt9ovdznj`) sagte **Ja.** Das Over-Call-Loch schließt sich, und keine Offense-Kante
regressiert — genau die konstruktive Erwartung:
| Nemesis | Blind | Memory (Veto) | Ziel | Befund |
|---|---|---|---|---|
| nemesis-1 | +81.41 | +78.34 ±28.0 | ≈ Blind (Offense unberührt) | ✓ Blind−Memory = 3 ≪ CI |
| nemesis-2 | +114.01 | +80.90 ±33.3 | ≈ +83 (Soft-Trust-Boden) | ✓ auf dem Boden |
| nemesis-3 | −26.59 | **+0.62 ±18.4** | > −26.59 (Over-Call-Loch) | ✓ **+27**, Loch zu |
Archetypen (`arch_read 4000`), Gap = Memory − Blind, kein Regress:
| Archetyp | Blind | Memory | Gap |
|---|---|---|---|
| fish | +74.58 | +132.37 | **+57.79** (Station-Exploit voll da) |
| reg | −13.40 | +7.52 | +20.92 |
| nit | +43.05 | +49.89 | +6.84 |
Das Veto berührt **keine** Angriffskante (nemesis-1 −3 innerhalb ±28; nemesis-2 am Soft-Trust-Boden;
alle Archetyp-Gaps positiv) und schließt genau das defensive Loch, für das es gebaut wurde
(nemesis-3 −26.59 → +0.62). Die Eiserne Regel ist erfüllt: **kein Verlierer, bewiesen auf der Leiter.**
Nächster Schritt: Zwillings-Tor, dann (auf ausdrückliche Freigabe) Commit.
## Was bleibt (nächste Stufen)
- **Belief-Kalibrierung** (falls die Leiter es verlangt — zwei bestätigte Defekte, Recon
2026-11-11): (a) **Combo-Masse statt Distinct-Rang** — `believed_villain`'s `rank = c/(n-1)`
(river_subgame.rs:192) ist die Position auf der **deduplizierten** Stärkeleiter (sort+dedup,
river_subgame.rs:148-151), nicht die kumulierte Combo-Masse; die `chance`-Tabelle trägt die
Combo-Zahlen, ist aber vom Fold/Bluff-Schwellwert strukturell getrennt. Auf gepaarten Boards foldet
`fold_to_bet`=0.45 also ~45 % der **Stärke-Ebenen**, nicht der Combos. Fix: Villain-Marginale der
`chance`-Tabelle als Masse-Quantil (`q[vb] = kum_unter + masse/2`). (b) **Doppelte Konditionierung**
— bei Facing-Bet ist die Eingabe-Range schon die *Wett*-Range (`continuations` setzt bei Villain-Bet
einen Value-Boden + `bluff_share`, street_continuation.rs:101-110); `believed_villain`'s `v_check`
filtert sie ein zweites Mal auf Top-40 %-Value. **Für das Veto ist das kein reiner Bug:** der
Zweitfilter entfernt genau die GTO-Bluffs, die `range_spec` einem Under-Bluffer fälschlich lässt
(die Over-Call-Wurzel), und ist per `aggression` selbstkorrigierend (ein echter Bluffer behält seine
Bluffs). Nur die **Höhe** ist unkalibriert — relevant erst, wenn das Veto fehl-feuert (Archetyp-
Regress). Beides wird nur angefasst, wenn die Leiter es verlangt; sonst bleibt v1.
- **Offense-Ausnutzung mathematisch heben**: die KL-um-GTO-Grenze (kann GTOs Nullmengen nicht
erreichen) heißt, dünner Value gegen Stations braucht ein anderes Primitiv (BR mit Support-Boden)
als `kl_best_response`. Die Heuristik hält diese Kante heute; ein mathematischer Ersatz ist ein
eigener, gemessener Schritt — nicht dieser.
- **Stage B** (`cfr::turn`, Turn+River-Subgame): sobald das River-Veto bewiesen live ist.
- **Die λ-Abbildung herleiten** statt `LAMBDA_POT_SCALE`/`CONFIDENCE_FLOOR` zu setzen —
informationstheoretisch ([[ROADMAP-mathematik]] §5), der Optimizer zuletzt.
## Werkzeug
- `src/engine/river_subgame.rs` — `believed_villain`, `lambda_from_confidence`, `river_exploit_plan`,
`fold_veto` (+ Unit-Tests inkl. `a_confident_underbluff_read_folds_a_bluff_catcher_facing_a_bet`).
- `src/exploit/profile.rs` / `src/sim/memory.rs` / `src/exploit/sample.rs` — `Profile.confidence`.
- `src/engine/decide.rs` — `fold_veto` nach `mdf_floor::floor` im River-Zweig von `postflop`, cash-gated.
+48
View File
@@ -0,0 +1,48 @@
# Befund Stage A: reines River-GTO schlägt die Exploit-Heuristik nicht
**Messung** (volle Leiter gegen Basislinie `201a115+lokal`, River-Subgame-Solver für den
Heads-up-River-am-Zug-Slice in `engine::decide` eingespeist):
```
GESAMT -73.95 ± 5.25 bb/100 2856 geändert SCHLECHTER
heads-up calling station -240.99 ±24.57 566 geändert SCHLECHTER
heads-up fish -114.94 ±21.51 290 geändert SCHLECHTER
heads-up reg / nit / maniac ~0 (im Rauschen) nicht unterscheidbar
6-max reg / nit / maniac / fish ~0 nicht unterscheidbar
```
Der Verlust sitzt **ausschließlich bei den Over-Callern** (Station callt 98 %, Fish 93 %). Gegen
Gegner, die man nicht ausbeuten kann (Reg, Nit), ist reines GTO neutral.
## Mechanismus
Reines GTO ist **unausbeutbar, aber nicht ausbeuterisch**. Der River-Solver löst das Gleichgewicht:
beide Seiten optimieren. Gegen einen Station, der nie foldet, ist das falsch an beiden Enden —
- GTO blufft einen ausbalancierten Luft-Anteil hinein, der immer gecallt wird (verbranntes Geld),
- GTO checkt mittlere Hände zurück statt thin zu valuebetten (liegengelassenes Geld).
Die **ausgelieferte Heuristik beutet genau das aus** (valuebettet thin, blufft Nicht-Folder nie) und
gewinnt gegen Station/Fish zweistellig bis dreistellig. GTO macht diesen Vorsprung kaputt.
## Schlussfolgerung (bestätigt die Vision)
1. **Pure GTO ≠ stompen.** Das ist der empirische Beweis für den Kern von [[engine-math-vision]]:
gebraucht wird **Best-Response gegen den _modellierten_ Gegner**, nicht das Gleichgewicht
(Kronengleichung `max E_belief[EV(σ)] − λ·KL(σ‖σ_GTO)`, λ→0 bei belastbarem Read).
2. **Stage A kann die Leiter auch mit Best-Response nicht gewinnen.** Eine Einzelstraßen-Best-Response
auf dem River ≈ das, was die Heuristik schon rechnet (EV jeder Aktion gegen die modellierte
Fold/Call-Frequenz). Der River ist die Straße, auf der die Einzelstraßen-Heuristik am wenigsten
falsch liegt. Der Gewinn liegt **mehrstraßig** (Stage B: Turn+River), wo die Myopie der Heuristik
der eigentliche Leak ist — der Over-Barrel in genutzte Ranges (siehe BEFUND-nit-read-leck).
## Was bleibt / was als Nächstes
- **Reverted:** die `decide`-Einspeisung ist raus; die ausgelieferte Engine ist unverändert
(kein Loser wird ausgeliefert).
- **Behalten als Fundament:** `src/cfr/river.rs` (gegen Lehrbuch-GTO bewiesen: Bluff-Verhältnis
`s/(P+s)`, MDF `P/(P+s)`) und `src/engine/river_subgame.rs` (die Bucketing-Brücke Combos→Stärke
via `judge`). Stage B wiederverwendet beides.
- **Nächster Schritt — Stage B:** Turn+River-Baum mit River-Chance-Knoten, gelöst als Best-Response
gegen die modellierte Gegner-Continuation, damit die Barrel-Entscheidung die River-Konsequenz
sieht. Dort stirbt der Over-Barrel-Leak.
@@ -0,0 +1,72 @@
# Befund: der River-Solver live verdrahtet kostet −43 bb/100 — Gleichgewicht gegen Fische ist falsch
Stage A hat einen card-exakten River-Subgame-Solver gebaut und in `sim::exploit_river` **bewiesen**:
gegen eine korrekte GTO-Überzeugung ist seine Politik exakt unausnutzbar (0.0 bb/100, Engine-Wert =
v\* auf die Nachkommastelle, alle Boards). Dieser Befund hält das Gegenstück fest: **derselbe Solver
in den Live-Pfad (`engine::decide`) gehängt ist ein −43-bb/100-Verlierer** — und warum.
## Der Versuch
In `decide::postflop` auf dem Heads-up-River vor der Heuristik-EV-Linie: statt der Einzelstraßen-
Heuristik die card-exakte Subgame-Gleichgewichtsmischung spielen (`river_plan` → `realize`, aus dem
Spot-Seed realisiert). Nur die aufzählbare Heads-up-River-Scheibe greift; alles andere fällt durch.
## Das Ergebnis (Leiter, integrierter Baum gegen Basislinie `24549fb+lokal`, 1115 s)
```
GESAMT -42.97 ± 5.93 bb/100 SCHLECHTER
heads-up calling station -126.79 ± 18.24 SCHLECHTER (+359 → +232)
heads-up maniac -125.10 ± 62.26 SCHLECHTER
heads-up fish -80.07 ± 29.37 SCHLECHTER
calling station (blind) -125.67 ± 19.77 SCHLECHTER
calling station (memory) -127.36 ± 18.30 SCHLECHTER
fish (blind) -59.25 ± 31.78 SCHLECHTER
fish (memory) -63.57 ± 26.77 SCHLECHTER
6-max gto -27.63 ± 24.72 SCHLECHTER
heads-up gto +1.26 ± 10.33 nicht unterscheidbar
heads-up gto-small -3.80 ± 11.14 nicht unterscheidbar
heads-up gto (blind) +11.43 ± 11.71 nicht unterscheidbar
heads-up gto-small (blind) +2.41 ± 11.66 nicht unterscheidbar
```
## Die Wurzel: ein symmetrischer Prior spielt ausbalanciert gegen Gegner, die man ausnutzen muss
Der Schaden teilt sich sauber:
- **Gegen die balancierten Gegner (gto, gto-small): nicht unterscheidbar.** Dort ist die symmetrische
Gleichgewichtsmischung ungefähr richtig — beide Seiten spielen nahe GTO, der Solver trifft es.
- **Gegen die ausnutzbaren Gegner (calling station, fish, maniac): katastrophal.** `river_plan` setzt
`hero_combos = villain_combos` (symmetrischer Prior) und löst auf das **Gleichgewicht**. Gegen eine
Calling Station ist Gleichgewicht grob falsch: man darf nicht ausbalancieren, sondern setzt jeden
dünnen Value-Bet durch und blufft nie. Der Solver checkt/unterbettet statt maximal Value zu holen —
−127 bb/100. Die Live-Verdrahtung **streift zusätzlich den Read ab**, von dem die ganze Leiter ihre
Kante bezieht.
Das ist die engine-math-vision-Warnung wörtlich eingetreten: ein GTO-Subgame-Solver ohne gegner-
bewusste Überzeugung spielt ausbalanciertes Poker gegen Spieler, die man schlachten sollte.
## Die Konsequenz: NIE EINEN VERLIERER AUSLIEFERN → zurückgebaut
Die Live-Verdrahtung in `decide.rs` ist entfernt (nur ein Kommentar und der Moduleintrag bleiben).
Der Solver bleibt als **bewiesenes Harness-Primitiv** (`sim::exploit_river`, 0.0 vs korrekte
Überzeugung) — er hat im Live-Pfad nichts verloren, bis zwei Dinge stehen:
1. **Gegnerbewusste Überzeugung** — Posterior (`exploit::posterior`, Beta/Bayes) → Range-Belief, statt
`hero = villain`. Der Solver muss gegen die *vermutete* Gegnerrange lösen, nicht gegen sich selbst.
2. **Vertrauens-Riegel (die Krone)** — `cfr::kl_br`: die ausgespielte Politik in einer KL-Kugel um GTO
halten, Radius λ aus der Read-Konfidenz (`posterior::confidence`). Starker Read → weit ausnutzen;
schwacher Read → nahe GTO. So kann der Solver nie wieder gegen einen Fisch ausbalancieren *und* nie
gegen einen unbekannten Gegner überausnutzen.
Bis dahin trägt die Heuristik-EV-Linie die Exploit-Kante, die die Leiter misst.
## Bestätigung (gemessen)
Nach dem Rückbau neu gemessen (`b3lgn7rq2`, 229 s): **GESAMT +0.00 ± 0.00 bb/100, 0 geändert,
jedes Szenario „gleich"** — die Stichproben sind bit-für-bit identisch zur Basislinie, der Rückbau ist
also vollständig und die Basislinie war sauber (calling station zurück auf +359.20, fish +152.44).
Der Benchmark-Gate ist grün (Exit 0, kein Regress). Nebenbefund: der Live-Solver war auch **5× langsamer**
(1115 s gegen 229 s) — eine 12k-Iterationen-CFR-Lösung je River-Entscheidung ist für den Live-Pfad ohnehin
zu teuer; er gehört in die Offline-/Harness-Schicht, nicht in `decide`.
+56
View File
@@ -0,0 +1,56 @@
# Befund: Stufe 4 offline — der Sim-to-Real-Gap ist messbar und modest; der Rest ist unausweichlich live
Die offline messbare Hälfte von Stufe 4 steht: der **Sim-to-Real-Gap im HUD-Raum** (`sim::simreal`,
`bin/simreal`). Die Frage, die sie beantwortet, ist die Lebensversicherung des ganzen Labors: *Sieht
unser synthetisches Feld durch ein HUD überhaupt aus wie echte Spieler?* Wenn nicht, ist keine In-Lab-EV
vertrauenswürdig — und das muss man wissen, bevor eine einzige Live-Hand läuft.
## Aufbau
Die Wahrheit→Beobachtung-Verknüpfung (`sim::reads`, an `tests/sim_opponent_stats` von den 5 Styles
geeicht) ist hier auf **beliebige gezogene `Rules`** verallgemeinert: `induced_hud(rules, n, seed)` misst
die vier HUD-Zahlen, die ein Regelwerk über viele Zufallshände an denselben kanonischen Spots induziert.
`population_induced_hud` fährt das über eine ganze gezogene Population und berichtet Mittel + Streuung je
Achse — der Fingerabdruck des synthetischen Feldes im beobachtbaren Raum.
## Ergebnis (`simreal`, 120 Zieher × 2000 Hände)
```
Ganzes synthetisches FELD (alle Archetypen):
vpip 0.529 (sd 0.343) pfr 0.110 (sd 0.146) foldToBet 0.613 (sd 0.178) aggression 0.196 (sd 0.138)
Innerhalb des reg-Clusters — synth. vs real STREUUNG (der faire Vergleich):
Achse synth. real Gap
vpip 0.126 0.043 +0.083
pfr 0.093 0.027 +0.066
foldToBet 0.056 0.089 -0.033
```
## Was das zeigt (ehrlich)
1. **Der faire Vergleich ist der within-Cluster.** Die Feld-Streuung (sd vpip 0.343) ist riesig, weil sie
**über** fish/reg/nit/maniac misst — das ist kein Realismus-Defekt, sondern die gewollte Heterogenität.
Vergleichbar mit den realen Daten (eine Tisch-Momentaufnahme, fast nur regs) ist nur die Streuung
**innerhalb** des reg-Clusters.
2. **Der Gap ist modest, aber real und gerichtet.** Innerhalb reg streut die synthetische Population auf
den Preflop-Achsen **~2–3× zu breit** (vpip +0.083, pfr +0.066) und auf foldToBet **zu schmal**
(−0.033). Heißt: `Spread::DEFAULT` gibt den synthetischen regs mehr Preflop-Varianz und weniger
Fold-to-Bet-Varianz, als der echte Tisch zeigt. Das ist ein konkreter Kalibrier-Hebel (Preflop-sd
runter, die foldToBet-treibenden Parameter streuen lassen) — aber erst mit mehr Daten zu ziehen.
3. **Die Methode steht, die Daten sind dünn.** 10 Spieler, ein Tisch, ein Cluster. Die anderen Archetypen
und echte Mittelwerte je Cluster brauchen mehr Mitschriebe (`lesen/kalibrierung.py a.log b.log …`).
Der Gap-Messer ist bereit; er wird mit jedem Logfile schärfer.
## Die Grenze, die bleibt (und warum)
Der **Live-Outcome-Abgleich** — die Engine gegen echte Menschen laufen lassen und Sim-EV gegen
Real-Ergebnis halten (das `COINPOKER_KERN`-A/B über `betrieb/runner.py`: Entscheidung `runner.py:3391`,
Ergebnis `runner.py:553-562`, Join über `(raum, hand)`, Gegner-ID in `anfrage["_sitze"]`) — ist **nicht
offline baubar**. Er braucht den Live-Farm, echte Gegner und echtes Geld über Zeit. Das ist keine
übersprungene Aufgabe, sondern eine Ressourcen-/Infrastruktur-Grenze; die Andockpunkte stehen, der
Schalter liegt beim Live-Betrieb. Alles, was ohne ihn messbar ist, ist jetzt gebaut und gemessen.
## Einordnung
Stufe 4 ist damit so weit umgesetzt, wie es synthetisch/offline geht: der HUD-Gap wird gemessen (modest,
gerichtet, datenbegrenzt), nur der unausweichlich-live Teil bleibt. Siehe `ARCHITEKTUR-synthetik-labor.md`.
@@ -0,0 +1,73 @@
# Befund: EV-neutrales Size-Mix (gegen den lesbaren Pur-Argmax)
## Problem
Das Postflop-Sizing war **vollständig deterministisch**: `engine::postflop::best` nimmt den reinen
EV-Argmax über die drei diskreten Sizes (`FRACTIONS = [1/3, 2/3, 1]` + All-in), bei Gleichstand die
erste (passive-first). Gleicher Spot → immer exakt dieselbe Size. Zwei Kosten:
1. **Ausnutzbarkeit (der Mathe-Punkt):** Ein Gleichgewicht *mischt* seine Sizes. Ein Pur-Argmax ist im
Prinzip lesbar — ein denkender Gegner clustert „große Size = Value" auf die Hero-Range.
2. **Online-Fingerabdruck:** konstante Size ist ein Muster (das Timing liegt getrennt im `hand/`-Layer).
Der einzige Zufall in der Engine war die *seeded* Equity-Monte-Carlo (`Rng::seeded(spot.seed)`,
reproduzierbar) — strategisch war nichts randomisiert.
## Lösung: mischen, aber nur unter EV-gleichwertigen Sizes
`engine::postflop::mix_size` / `pick_mixed`: nachdem das Abstain-Gate entschieden hat, *ob* geraist wird,
wird die **Size** unter den Raises gewürfelt, deren EV innerhalb eines Bandes des besten liegt:
```
error = MIX_BAND * estimate.std_error * final_pot(to)
tied = { raises s : winner.ev - s.ev <= error }
pick = tied[ Rng::seeded(spot.seed ^ MIX_SALT).below(tied.len()) ]
```
Eigenschaften, by design:
- **Nur Raise-Sizes mischen.** check/call/fold bleiben der deterministische Argmax (kein Aktions-Mix —
das wäre eine größere GTO-Änderung mit echtem Risiko).
- **EV-indifferent.** Das Band ist an den Standardfehler der Equity-Schätzung gekoppelt: zwei Sizes
innerhalb sind unter dem Modell nicht unterscheidbar. Darum **EV-neutral by construction** — es kann
gegen die nicht-adaptierenden Fish/Stations (unser EV-Fundament) nichts kosten und auf der Ladder kein
Minus werden. Der Gewinn entsteht nur gegen Gegner, die sonst eine feste Size lesen.
- **Seeded off `spot.seed`** (via `MIX_SALT` dekorreliert von der Equity-MC): reproduzierbar für gepaarte
Messung, aber variabel über Hände/Boards. Nur die gemischten Spots weichen vom deterministischen Lauf ab
— exakt das saubere Paarungssignal (wie bei `TURN_VETO`).
- **Mess-/Sweep-Schalter:** `SIZE_MIX=0` deaktiviert, `SIZE_MIX_BAND=<σ>` regelt die Bandbreite (read-once
OnceLock, Projektstil wie `TURN_LEAF_ITERS`).
4 Unit-Tests (`size_mix_tests`): mischt nur unter EV-gleichwertigen Sizes, No-op ohne Gleichstand, rührt
einen Nicht-Raise-Gewinner nie an, error=0 ist deterministisch. 128/128 Lib grün.
## Messung (gepaart vs. deterministische Baseline 24549fb+lokal, luck-korrigiert)
| Band | GESAMT | ±95% CI | Spots gemischt | Verdikt |
|---|---|---|---|---|
| 1.0σ | −0.56 | ±0.95 | 227 | nicht unterscheidbar |
| **0.5σ** | **−0.23** | **±0.59** | **112** | nicht unterscheidbar |
**Jede einzelne Zeile** (reg/nit/maniac/fish/station/gto/gto-small, HU + 6-max, blind/memory) ist „nicht
unterscheidbar". Die saubersten High-N-Zeilen — gto / gto-small, genau wo Unlesbarkeit zählt — sind tot
flach (0.5σ: +1.19 ±2.56 / +0.11 ±1.22, je 15 Spots gemischt).
**Der Punktschätzer ist konstruktionsbedingt leicht negativ**, kein echtes Leck: das Mix weicht nur je
*weg* vom Argmax (nie zu einer höher bewerteten Size), also senkt es den Modell-Erwartungswert um einen
Hauch. Beweis, dass es Band-getrieben ist (nicht Gegner-Signal): das Band zu halbieren halbiert **beides**
— Bias (−0.56→−0.23) und CI (±0.95→±0.59) und Spot-Zahl (227→112). Ein Gegner-spezifisches Leck würde
sich so nicht skalieren.
## Verdikt: 0.5σ als Default, live
Besteht den Projekt-Maßstab („nie ein gemessenes Minus shippen"): das luck-korrigierte 95%-CI schließt
Null in jeder Zeile und gesamt ein. 0.5σ ist der Default — der sauberere ≥0-Beweis, der trotzdem in 112
Spots echt mischt. `MIX_BAND = 0.5` in `engine::postflop`.
## Grenze / nächste Verfeinerung (optional)
Der Hart-Band-Uniform-Zug verschenkt per Konstruktion einen Hauch (nie zu einer besseren Size). Die
elegantere Form wäre ein **EV-gewichteter Zug** (Soft-Argmax / QRE-Temperatur über die Sizes): Masse
konzentriert auf die beste, aber auf echte Gleichstände verteilt → Bias → exakt 0, bei gleicher
Unlesbarkeit. Nicht nötig für den Beweis (0.5σ ist bereits ununterscheidbar von 0), aber der natürliche
nächste Schliff, wenn das Size-Grid ohnehin verfeinert wird (Overbet/Block-Bet aus dem Audit).
@@ -0,0 +1,168 @@
# Befund: Stage B — der Turn+River-Subgame-Solver steht (Live-Veto zurückgenommen)
Stage A brachte den River-Subgame-Solver (`cfr::river`), bewiesen unausnutzbar, live als defensives
Veto ([[BEFUND-river-gearbox-belief-trust.md]]). Stage B hebt denselben Bau **eine Straße tiefer**: ein
tiefenbegrenzter **Turn+River**-Solver, der den River-Gleichgewichtswert als Blatt einrechnet. Der
CFR-Kern blieb **unverändert** — er ist straßen-agnostisch, `Node::Chance` ist nativ, `Payoff::Pair`
ist eine freie Matrix. Die ganze Arbeit liegt in einem neuen Builder + einem Blatt-Vorrechner.
## Konstruktion (Option B: tiefenbegrenzter Turn, River-Gleichgewichtswert als Blatt)
Der Turn ist nicht die letzte Straße — ein Turn-Showdown ist nicht exakt, sein Wert hängt davon ab,
wie der River dann spielt. Also:
1. **Turn-Baum** = dieselbe 9-Knoten-Form wie der River (`cfr::turn_river::tree_with_leaf`), aber die
drei „erreiche den River"-Terminals tragen eine **Blatt-Wert-Matrix** `V[i][j]` statt eines
statischen Showdowns: Heros erwartete Chips über den *ganzen* River, gegeben die Turn-Buckets (i,j).
2. **Blatt-Wert** `V`: für jede der ~44 River-Karten (`deck::without_in` über das 4-Karten-Turn-Board)
das Heads-up-River-Subgame (`cfr::river`) an den zwei möglichen River-Start-Pots lösen (Turn
durchgecheckt; gecallter Turn-Bet) und seinen **Gleichgewichtswert je River-Bucket-Paar** lesen
(`cfr::turn_river::pair_values`), dann mit Card-Removal auf die **Turn**-Buckets zurückfalten. Zwei
Matrizen: `V_check` (River via Check-Check, Pot p) und `V_bet` (via gecalltem Bet, Pot p+2s).
3. **Turn lösen** (`tree_with_leaf`) und Heros gemischte Aktion für den Bucket seiner echten Turn-Hand
lesen.
Das ist die DeepStack/Endgame-Konstruktion, eine Straße tiefer als der bewiesene River-Bau. Wenn das
River-Blatt zum reinen Showdown entartet, ist der Turn-Baum **knotengetreu identisch** mit dem
River-Baum (Test `showdown_leaf_reproduces_the_river_tree_exactly`) — der tiefenbegrenzte Solve
degradiert also sauber zum Ein-Straßen-Solve.
**Die Kern-Invariante (bewiesen im Test):** `pair_values`, mit der `chance`-Tabelle des Baums
gewichtet, reproduziert exakt `value_walk::root_values(Follow, hero)` — der Blatt-Wert stimmt mit dem
eigenen Wert des Solvers überein. Das ist die Korrektheitsgarantie, dass die Eltern-Straße dem Blatt
vertrauen darf.
## Was gebaut wurde
- **`src/cfr/turn_river.rs`** (neu): `tree_with_leaf` (Turn-Baum mit Blatt-Matrizen), `pair_values`
(Hero-Wert je Klassenpaar unter einer Strategie, Vorwärts-Walk), `solve_turn`, `TurnSolve`.
3 Unit-Tests: Showdown-Blatt == River-Baum, pair_values liest das erzwungene Blatt, pair_values ×
chance == root_values.
- **`src/engine/turn_subgame.rs`** (neu): `turn_plan`/`turn_mix` (GTO-Baseline-Mix, Mess-Eintritt),
`build_turn` (Ranges → 44-Runout-River-Blätter → Turn-Solve), `turn_exploit_plan`/`turn_exploit_mix`
(opponent-aware Gearbox: `believed_villain` + `kl_best_response`, λ aus Konfidenz — alles aus dem
River wiederverwendet, da die Turn-Knoten `v_bet`/`v_check` dieselbe Bedeutung tragen), und
`turn_fold_veto` (cash-only defensiver Veto). 5 Unit-Tests (Wiring-Guards; die EV beweist die Leiter).
- **`src/engine/river_subgame.rs`**: `believed_villain` + `lambda_from_confidence` auf `pub(crate)`
gehoben (straßen-agnostisch wiederverwendet).
- **`src/engine/decide.rs`**: `turn_fold_veto` nach dem River-Veto eingehängt, cash-gegated
(`premium <= 0`). Jeder Veto ist off-street ein No-op.
- **Mess-Schalter**: `TURN_VETO=0` deaktiviert den Live-Veto ohne Rebuild (gepaarte Messung an/aus).
123/123 Lib-Tests grün (war 115, +8), keine Regression.
## Ehrliche Erwartung (Offense-Grenze geerbt)
Wie beim River kann der KL-um-GTO-Best-Response GTOs Nullmengen nicht erreichen — die dünnen
Value-Bets/leichten Calls, mit denen die Heuristik Fische ausnimmt, bleiben der Heuristik. Darum ist
der erste *live* Edge wieder **defensiv** (`turn_fold_veto`), und der Solver-Kern (`cfr::turn_river` +
`engine::turn_subgame`) ist der eigentliche Stage-B-Gewinn — getestete Infrastruktur, bereit für
Stage C / einen besseren Trigger / eine reichere Belief, **unabhängig davon, ob der Veto live bleibt.**
## Messung (b8uwhrmvd, 2500 Deals, gepaart Veto an/aus, Memory-Modus)
| Gegner | Veto ON | Veto OFF | ON−OFF |
|---|---|---|---|
| nemesis-1 | +80.40 | +88.17 | **−7.77** |
| nemesis-2 | +97.73 | +102.99 | **−5.26** |
| nemesis-3 | +18.86 | +3.12 | **+15.74** |
| fish | +138.73 | +137.31 | +1.42 |
| reg | +23.47 | +14.91 | +8.56 |
| nit | +50.56 | +48.93 | +1.63 |
| maniac | +90.91 | +71.42 | **+19.49** |
Oracle- und Blind-Zeilen sind ON==OFF bit-identisch (der Veto wirkt nur über den Memory-Read) — die
Paarung ist sauber. Netto **+33 bb/100** über alle sieben, auf der realistischen Archetyp-Population
(fish/reg/nit/maniac) sogar **Pareto-positiv** (alle vier besser), größter Einzelgewinn genau dort, wo
der Read-getriebene Over-Call blutet (maniac +19.49, reg +8.56) plus das nemesis-3-Loch (+15.74).
## Verdikt: Verdrahtung ZURÜCK, Infrastruktur BLEIBT
Trotz des positiven Mittels **regressiert der Veto die zwei härtesten Nemeses** (−7.77 / −5.26).
Wurzel (im Code lokalisiert): der Veto feuert auf einen konfidenten Under-Bluff-Read, aber
`believed_villain` liest nur `fold_to_bet` + `aggression` (eine *gepoolte* Postflop-Aggression). Bei
nemesis-1/-2 unterschätzt der Memory-Read ihre **Turn**-Aggression → die geglaubte Villain wirkt wie
ein Under-Bluffer → der Veto foldet einen *guten* Call. Das ist exakt die Belief-Lücke aus
[[DESIGN-reichere-belief-gearbox.md]] (keine Per-Street-Aggression, kein Sizing-Signal).
Eisernes Gesetz, Präzedenz: der River-Veto (Stage A) ging **nur** live, weil er **keine** Nemesis
regressierte („seine eine Kante ohne Kosten"). Dieser Turn-Veto hat Kosten auf den zwei Gegnern, deren
Robustheit am teuersten erkämpft wurde ([[nemesis-station-mislabel]]: −414 → +83). Ein
Populations-Mittelgewinn rechtfertigt keine Nemesis-Regression. Darum:
- **`decide.rs`-Verdrahtung zurückgenommen** (River-Veto-only wie vor Stage B; die zwei Turn-Zeilen
raus, Kommentar erklärt warum).
- **`cfr::turn_river` + `engine::turn_subgame` bleiben** — getestet (8 Unit-Tests, 123/123 Lib grün),
`pub`, bereit zur Wieder-Verdrahtung. Das ist der eigentliche Stage-B-Gewinn.
## Was den Live-Turn-Veto freischaltet
Der Veto wird live, sobald die Belief seinen Misfire auf nemesis-1/-2 verliert — d.h. wenn
`believed_villain` **Turn/River-spezifische Aggression** trägt statt der einen gepoolten (der billigste
erste Schritt aus [[DESIGN-reichere-belief-gearbox.md]]: `river_aggression`/`turn_aggression` als
Profile-Feld, auf dem Memory-Pfad gefüllt). Dann liest der Veto die aggressiven Nemeses korrekt als
Bluffer und foldet ihren Call nicht mehr — die maniac/reg/nemesis-3-Gewinne (+19/+8/+16) sollten
bleiben, die −7/−5-Kosten verschwinden. Das ist die nächste disziplinierte Rung, nicht ein Hack am
Trigger.
## Nachtrag (2026-11-12): Per-Street-Aggression gebaut, Turn-Veto wieder verdrahtet
Die freischaltende Rung ist umgesetzt. Die Belief trägt jetzt street-spezifische Aggression:
- **`Profile`**: zwei neue Felder `turn_aggression` / `river_aggression` (`Option<f64>`, Default `None`).
- **`believed_villain`**: Signatur nimmt die effektive Aggression als Parameter statt die gepoolte
`profile.aggression` intern zu lesen. Der Turn-Aufrufer (`turn_subgame`) übergibt
`turn_aggression.or(aggression)`, der River-Aufrufer (`river_subgame`) `river_aggression.or(aggression)`.
`None` → GTO-Default. `fold_to_bet` bleibt gepoolt (ein Signal nach dem anderen).
- **`sim::memory`**: Per-Street-Zähler für Turn/River (aggressiv vs. passiv=call+check, Folds raus wie
beim gepoolten Nenner); `read()` füllt die zwei Felder (`None` bis die Straße eine Aktion sah → der
Fallback greift). Neuer Test `per_street_aggression_splits_the_turn_from_the_pooled_read`: ein
Flop-Checker/Turn-Barreler liest gepoolt 0.5, aber turn_aggression 1.0.
- **Nicht-brechende Pflege**: vier volle `Profile`-Literale ergänzt (`decode_villain` → None, nicht auf
dem Wire; `sample.rs` PRIOR None + `shrink` zieht sie durch; `mark.rs` WEAK_PLAYER None + `with_mark`).
- **`decide.rs`**: Turn-Veto wieder hinter dem River-Veto verdrahtet, cash-only.
**Hypothese (zu beweisen):** die Per-Street-Aggression liest nemesis-1/-2 als Turn-Barreler → höhere
`bluff_prob` → die geglaubte Villain-Bet-Range wirkt bluffig → hero callt → der Veto foldet den guten
Call *nicht* mehr. Die maniac/reg/nemesis-3-Gewinne sollten bleiben (ihre Over-Call-Blutung ist
read-getrieben, unabhängig vom Aggression-Split). **Achtung Nebenwirkung:** der River-Veto nutzt jetzt
auch `river_aggression` statt der gepoolten — die Messung muss bestätigen, dass nemesis-3 (das
River-Loch) dadurch nicht beschädigt wird.
### Verdikt (bdl3scmw1, 600 Deals, gepaart Veto an/aus, Memory-Modus)
Die Hypothese ist **falsifiziert**. Per-Street-Aggression hat den nemesis-1-Misfire **nicht** geheilt —
sie hat ihn verschlimmert:
| Gegner | ON−OFF (gepoolt, b8uwhrmvd) | ON−OFF (per-street, bdl3scmw1) |
|---|---|---|
| nemesis-1 | −7.77 | **−25.93** (schlechter) |
| nemesis-2 | −5.26 | +2.33 (geheilt) |
| nemesis-3 | +15.74 | +28.62 |
Per-Street-Aggression heilt **nemesis-2** (der aggressive Turn-Barreler wird jetzt korrekt als Bluffer
gelesen, der Veto foldet seinen Call nicht mehr), aber **nemesis-1 regressiert tiefer**. nemesis-1 ist
*value-heavy* (bluff 0.068, call_margin 0.215): kein Turn-Barreler, sondern ein Gegner, dessen Turn-Bets
echt sind. Dort ist die **Wurzel nicht die Belief-Granularität**, sondern der **draw-BLINDE Turn-Bucket**:
der Veto foldet Bluff-Catcher, deren *River*-Equity die aktuelle-Stärke-Bucketleiter unterschätzt. Ein
defensiver Turn-Fold verwirkt realisierte Equity, die der River-Veto nie verwirkt (der River ist final —
da gibt es keine verworfene Draw-Equity mehr). Das braucht **draw-aware Turn-Bucketing** oder die
Offline-/Value-Function-Form, keinen Live-Fold-Veto.
### Entscheidung
- **Turn-Veto-Verdrahtung in `decide.rs` zurückgenommen** (River-Veto-only; Kommentar dokumentiert beide
Messungen und die Draw-Blind-Bucket-Wurzel). Eisernes Gesetz: zwei Messungen sind sich einig, dass
nemesis-1 regressiert → kein Live-Shipping.
- **Per-Street-Belief-Code BLEIBT** (Profile-Felder, `sim::memory`-Zähler, `believed_villain`-Signatur,
`TURN_LEAF_ITERS`-Knopf). Er ist auf der breiten Ladder **bewiesen neutral** (Benchmark busqe4obv:
GESAMT **+0.06 ±0.12 bb/100**, nur 8 Fish-Memory-Entscheidungen angestupst — bit-identisch sonst), also
live-inert ohne den Turn-Veto und schadet dem River-Veto nicht. Er ist getestete Belief-Infrastruktur
für Stage C / die draw-aware Turn-Form.
- **`cfr::turn_river` + `engine::turn_subgame` BLEIBEN** wie zuvor — getestete Stage-B-Infrastruktur.
**Lehre:** Der Turn-Veto-Misfire hat *zwei* Wurzeln, nicht eine. Die Belief-Granularität (nemesis-2) war
nur die halbe Geschichte; die andere Hälfte (nemesis-1) ist die Nicht-Finalität des Turns + draw-blinde
Buckets. Ein Live-Fold-Veto kann die zweite prinzipiell nicht lösen — nur ein Value-Function-Blatt, das
die verworfene Draw-Equity einpreist, kann das. Darum ist die nächste Turn-Rung Stage C (draw-aware
Bucketing + gesampelte Runouts), nicht ein weiterer Belief-Patch.
+99
View File
@@ -0,0 +1,99 @@
# Befund: Stufe 0 — Live-Test auf Übung (Pivot weg von Nur-Synthetik)
**Datum:** 2026-11-12
**Anlass:** Owner-Pivot — „vllt hören wir mal auf synthetisch zu testen sondern machen live a/b
tests pro tisch! erstmal übung dann micro stakes?". Die Synthetik-Leiter hat Grenznutzen erreicht
(die letzten drei Änderungen — Size-Mix neutral, Turn-Veto Verlierer, Bluff-Veto neutral), und
fixe Archetypen messen weder die Sim-to-Real-Lücke noch Anti-Exploitation gegen echte Menschen.
## Kernbefund: der Übung-Loop existiert schon komplett
Stufe 0 war **kein Bau von Null** — der ganze Live-Loop ist da und spielgeld-sicher:
- `betrieb/spielplan.py`: `scratch/spielplan.json {"modus":"uebung"}` lässt den Läufer selbst
**Practice-Games**-Tische öffnen (`REITER = {uebung:"Practice Games", cash:"Cash Games"}`), bis
zur Tischzahl auffüllen, und **nie** einen Cash-Tisch mischen (`modus_passt`).
- Harte Spielgeld-Sperre: `spielplan.erzwinge_uebung` + `umgebung.nur_uebung()` zwingen den
wirksamen Modus auf Übung, selbst wenn der Plan auf Cash steht (Vorfall 6.11.).
- `betrieb/runner.py`: liest Zustand → entscheidet über den Rust-Kern (`hand/entscheidung.py` →
`decide`) → protokolliert jeden Zug/jede Hand ins Schattenlog → optional klicken (`--act`); ohne
`--act` läuft er im **Schatten** (sagt an, du klickst). Not-Aus: `scratch/stop`.
- `betrieb/statistik.py`: jede fertige Hand mit `netto_bb` in `haende.jsonl`; bb/100, Raten,
Sitzungen, **95-%-Spannen je Format** (`spanne_bb_pro_100`), und `bestes_format` deklariert einen
Sieger nur, wenn eine 95-%-Spanne ganz über den anderen liegt (Überlappung = Zufall).
- **A/B-Haken für Stufe 2 existiert:** `je_format` gruppiert Hände nach `h["format"]` und vergleicht
die Gruppen mit dem Nicht-Überlappungs-Test. Zwei Arme = zwei `format`-Tags, mehr braucht es für
den Vergleich nicht.
## Was fehlte und jetzt gebaut ist
1. **Gesamt-bb/100 mit 95-%-Konfidenzband** (`betrieb/statistik.py`): die Spanne gab es nur je
Format, nicht auf der Kopfzahl „gewinnt die Engine?". `_gruppe` liefert jetzt `unten`/`oben`
(aus `spanne_bb_pro_100`), `md_aus` zeigt die Gesamt-Spanne. Spec: `tests/statistik_spec.py`
(21 grün, Regression ok).
2. **`betrieb/stufe0.py` — der Übung-Bericht**: liest den Statistik-Speicher (+ optional das
Schattenlog) und urteilt nur, was die Stichprobe hergibt:
- **Schlägt es die Null?** bb/100 mit 95-%-Spanne; `unten > 0` = gewinnt mit 95 %. Überlappt die
Spanne 0, ist es Zufall (dieselbe Regel wie `bestes_format`).
- **Spielstil sane?** VPIP/PFR/Showdown im Band; `PFR > VPIP` oder VPIP-Extrem = degeneriert.
- **Loop-Gesundheit:** Abbrüche (Invariantenbruch), Timeouts (Uhr abgelaufen → Server-Sitout),
Abstains (Kern ohne Aktion). 0 Abbrüche + 0 Timeouts = der Loop trägt.
- **Sim-to-Real** (optional `--erwartung LO HI`): live-Spanne gegen ein Synthetik-Band.
Spec: `tests/stufe0_spec.py` (16 grün).
## Trockenlauf gegen 190 Archiv-Hände (`archiv/lauf`, Cash)
```
Hände: 190 bb/100: -266.8 95-%-Spanne: -560.5 bis +26.9 -> noch Zufall (überlappt 0)
Stil: VPIP 31 % PFR 24 % Showdown 16 % -> sane
Loop: Abbrüche 0 Timeouts 0 Abstains 0 Sitouts 79 -> sauber
Sim-to-Real (80..300): schlechter als erwartet (live-Spanne unter dem Band)
```
Lehren: (a) der Bericht funktioniert gegen echte Daten; (b) **190 Hände beweisen nichts** — die
Spanne ist ±290 bb/100; (c) der Stil ist sane (vernünftiger TAG), der Loop sauber. Der
Sim-to-Real-Minus ist hier NICHT belastbar: es sind Cash-Archivhände (kein sauberer Übung-Lauf)
und viel zu wenige.
## Runbook — so läuft Stufe 0
```bash
# 1. Übung-Plan setzen (Spielgeld, 1 Tisch zum Anfang)
echo '{"modus":"uebung","tische":1}' > betrieb/scratch/spielplan.json
# 2. Läufer starten. Erst im Schatten (sagt an, du klickst), dann mit --act (klickt selbst).
python3 betrieb/runner.py # Schatten
python3 betrieb/runner.py --act # klickt selbst; scratch/stop hält das Klicken an
# 3. Bericht lesen (jederzeit, auch während des Laufs)
python3 betrieb/stufe0.py --shadow betrieb/scratch/shadow.jsonl
```
**Bestanden** = Loop sauber (0 Abbrüche/Timeouts) UND Stil sane. Die bb/100 ist auf Übung
zweitrangig (Spielgeld-Gegner ≠ Micro-Population); sie zählt erst ab Stufe 1 (Micro).
## Varianz — die ehrliche Grenze (gilt für Stufe 1/2)
Live kann **keine Karten paaren** wie die Synthetik-Leiter — die volle Varianz (σ ≈ 90 bb/100)
bleibt. Zum Auflösen einer A/B-Differenz Δ auf 95 % (gepaart nicht möglich):
| Δ bb/100 | Hände je Arm | mit All-in-EV + AIVAT (~−60 %) |
|---|---|---|
| 5 | ~250 000 | ~90 000 |
| 20 | ~15 000 | ~5 500 |
| 50 | ~2 500 | ~900 |
Folge: die 1–9-bb/100-Deltas der Synthetik sind live **nicht** auflösbar. Stufe 2 (A/B) nur für
**grobe strukturelle** Hebel (Δ≳20), und davor die **All-in-EV/AIVAT-Varianzreduktion** bauen
(die Hand trägt heute nur `netto`, keine All-in-Equity — das ist der nächste Infra-Schritt).
## Offen / nächste Schritte
- **Stufe 1 (Micro):** `micro_only` kappt Stakes auf BB 0.10; dann ist die live bb/100 die eigentlich
wertvolle Zahl (gewinnt es echt + Sim-to-Real gegen die Micro-Population).
- **All-in-EV/AIVAT live:** `game.poker_odds`/`lesen/evchop.py` haben die Equity; sie noch nicht in
die Hand-Zeile. Das ist die Varianzreduktion für Stufe 2.
- **A/B-Arm-Verdrahtung:** zwei Engine-Configs pro Tischprozess + `format`-Tag je Hand; der
Vergleich steht schon (`je_format` + Nicht-Überlappung).
- Noch offen aus der Synthetik: `bluff_veto` (neutral, uncommitted in `src/engine/`) → reverten.
@@ -0,0 +1,76 @@
# Befund: die Turnier-Pipeline steht schon — end-to-end, grün, gemessen
Auftrag war „Turnier-Pipeline angehen" (nach `AUFTRAG-modi.md`, der sagt *„Code kann beides noch
nicht"*). **Die Prämisse ist überholt.** Zwei Recon-Durchläufe (Rust + Python) und die vorhandenen
Turnier-Spezifikationen zeigen: die Pipeline ist über die ganze Kette gebaut und läuft grün. Nicht
neu bauen — belegen und die echten Restlücken benennen.
## Die Kette steht (mit Beleg)
| Glied | Ort | Stand |
|---|---|---|
| Log → Turnierlage lesen (Level/Blinds/Ante/Payout/Feld/Bubble/Late-Reg/Stack) | `lesen/turnier.py:141-222` | **gebaut** |
| `tournament`-Feld der Anfrage bauen | `lesen/turnier.py:260-292` (`kern_feld`) + `lesen/spot_from_log.py:512-513,573` | **gebaut** |
| Wire-Decode → `Turnierlage` | `src/wire/decode_tournament.rs:35-47` | **gebaut** |
| Live-Routing zu ICM | `src/wire/respond.rs:23` (`decide_with(spot, Some(lage))`) | **gebaut** |
| ICM-Engine (Harville, Risikoprämie, Bubble-Verengung) | `src/icm/{lage,harville,risk}.rs` | **gebaut + getestet** |
| Decide-Brücke reicht Feld unverändert durch | `entscheiden/decide.py:90-91` | **gebaut** |
| Klon-Turniermodus (Level/Ante/Late-Reg/Bust/Payout/Bubble/Pause) | `mock/turnier.py` | **gebaut** |
| UI: Modus sichtbar (Level/Blinds/Feld/Bezahlt/Bubble) | `sicht/ansicht.py:85-100` | **gebaut** |
| An-/Abmeldung, Verwaltung, Zeitplan | `lesen/turnier_*.py`, `betrieb/turnierzyklus.py`, `betrieb/turnierplan.py` | **gebaut** |
## Beleg: die Spezifikationen laufen grün (2026-11-11)
Rust: `tests/pipeline_tournament.rs`, `tests/icm_bubble.rs` (Bubble enger als Cash, null=Cash
bitgleich, kaputt→invalid, unbepreisbar→ABSTAIN, Feld > Harville-Grenze gesampelt).
Python (direkt gefahren):
```
turnier_anfrage_spec 14 OK (1 skip) turnier_anmeldung_spec 65 OK
turnier_spec 33 OK turnier_verwaltung_spec 13 OK
turnier_cash_only_spec 6 OK turnierliste_spec 7 OK
turnier_info_spec 11 OK turnierplan_spec 20 OK
turnier_phantom_spec 4 OK turnierzyklus_spec 20 OK
turnier_registering_spec 7 OK turniertisch_spec 12 OK
```
Nur zwei Dateien nicht grün — **beide aus demselben reinen Windows-Grund**, nicht aus Turnier-Logik:
`turnier_e2e_spec` (12) und `turnier_zug_buehne_spec` (5) brechen an
`AttributeError: module 'socket' has no attribute 'AF_UNIX'` — die Bühnen-Brücke nutzt Unix-Domain-
Sockets, die es unter Windows nicht gibt. Auf Linux (dem Hof) laufen sie.
Der Brief wird im Code selbst messgestützt widerlegt: `lesen/turnier.py:13-28` zeigt, dass es **kein**
Feld `isTournament` gibt (die 629 Treffer sind `isTournamentPrizePoolOverlay`), die echten Felder
kommen aus `dynamic_lobby_data`/`prize_list`/`rank_list`.
## Die echten Restlücken (nicht die Pipeline)
1. **K-Poker-Aktionsausführung** — der **eine** echte offene Bolzen. Die Übersetzung steigt bei einem
Live-K-Poker-Zug ohne gemessenes Menü aus (`lesen/spot_from_log.py:493-496`, „Tastentabelle nicht
gemessen"); `kpokerActions` ist im Bestand immer null. `hand/kpoker.py` hat die Slot-Tabelle aus der
Client-IL abgeleitet (`KPokerBetKeys`/`KPokerActionPanel`, Fold/Check/Call/AllIn/Bet-Slots) und
**korrigiert den Brief**: das Menü bedient man per **Maus-Klick auf Panel-Slots**, nicht per Taste.
Aber die Tabelle ist **nicht in `hand/act.py` verdrahtet** (`ZU_TAT` kennt nur FOLD/CHECK/CALL/RAISE).
Buildbar ist das Scaffold (Slots verdrahten + Übersetzung ein Menü erzeugen lassen); **messen** muss
man die Menü-Struktur an einem echten K-Poker-Tisch, bevor es echtes Geld anfasst (10-s-Uhr).
2. **Turnier-Tischdynamik** (Tischwechsel, Sitzwechsel, `tournamentCurrentStage`) — im Klon nur als
**Annahme** modelliert (`mock/turnier.py:19-24`); kein echter Mitschrieb zum Gegenprüfen.
3. **`spieler_tisch`** (Spieler am eigenen Tisch) aus dem Bestand unauflösbar → immer `None`
(`lesen/turnier.py:40,200`). Klein.
## Die eigentliche Frontier für „beste Turnier-Engine"
Nicht die Pipeline — die **Stärke-Messung fehlt.** Cash hat die Nemesis/Archetyp-Leiter; Turnier hat
nur **Korrektheits**-Tests (Bubble enger als Cash), **keine EV-Leiter**, die beweist, dass die ICM-Linie
*gewinnt*. Es gibt kein Rust-Turnier-Sim-Binary (`src/bin/` ist cash/exploit). `entscheiden/turnier_
benchmark.py` kalibriert die Prämie, misst aber keine Turnier-bb/100 gegen ein Feld. Das ist der
Measure-First-Grundstein, den „Weltklasse im Turnier" braucht — das Gegenstück zur Cash-Leiter.
## Einordnung
Für Turniere ist die Engine **operativ bereit** (Standard-NLHE-Turniere: Log→ICM→Entscheidung→Klon→UI
→Anmeldung, grün). Offen sind: K-Poker-Ausführung (ein gemessener Bolzen), Tischdynamik-Gegenprobe
(operativer Mitschrieb) und — am wichtigsten — eine **Turnier-Stärke-Leiter**, ohne die man die
ICM-Linie weder beweisen noch verbessern kann. Der Cash-Live-Gap (−311, [[BEFUND-liveabgleich-stufe4-
live]]) gilt für Turniere genauso: Innen-EV ist noch nicht Außen-EV.
@@ -0,0 +1,174 @@
# Befund: die Turnier-Stärke-Leiter steht — die ICM-Linie GEWINNT in Geld
Cash hat die Nemesis/Archetyp-Leiter, die jede Live-Änderung in bb/100 beweist. Turnier hatte bisher
nur **Korrektheits**-Tests (Bubble enger als Cash) und keine **EV-Leiter**
([[BEFUND-turnier-pipeline-steht]], „die eigentliche Frontier"). Dieser Befund baut sie und fährt die
ersten Zahlen: **die ICM-Linie schlägt die Chip-EV-Linie in 10 von 11 Spots (bewiesen, gepaart) — und
die Leiter findet sofort das eine LECK**, einen vorbestehenden Kalibrierfehler der Open-Jam-Weitung
(`cover-short` −12.5 ICM$/100), unabhängig vom ICM-Nash-Solver des Repos bestätigt. Genau dafür ist
eine Stärke-Leiter da: beweisen, was gewinnt, und messgenau zeigen, was nicht.
## Das Instrument (`sim::turnier_leiter`, `bin/turnier_leiter`)
Turniere werden um **Preise** gespielt, nicht um Chips, und Chips werden **nicht-linear** in
Preis-Equity umgerechnet (Harville/ICM). Eine Linie, die Chips gewinnt, kann an der Bubble Geld
verlieren. Also muss die Messung in **ICM-Geld** werten, nicht in Chips:
- Ein **Szenario** ist ein Heads-up-Pot (Hero + ein Gegner, beide auf `stack_bb`) eingebettet in ein
Feld fester Fremdstacks unter einer Preisstruktur (Pool = 100).
- Jede Hand wird **zweimal** gespielt, auf denselben Karten und Sitzen: die **ICM-Linie**
(`decide_with(spot, Some(lage))`) und die **Cash-Linie** (Chip-EV, `decide`). Die Chips bewegen sich
nur am Tisch (am Free-Table erhalten); das Feld bepreist die Bewegung per Harville.
- Kennzahl: die **gepaarte Kante** ICM$(an) − ICM$(aus) je 100 Hände. Dieselben Karten für beide
Linien → das Board-Glück hebt sich in der Differenz auf, übrig bleibt die reine Entscheidungs-Kante.
- Urteil pro Szenario: ✓ **gewinnt** (95-%-Intervall ganz > 0), · **neutral** (|Kante| ≤ CI, das
Anker-Ziel), ✗ **Leck** (Intervall ganz < 0 → Eiserne Regel: zurückrollen + Befund).
**Kein Mischen von Wissen.** Der Chip-Pfad und der ICM-Pfad teilen EINEN Mathe-Kern; nur die
`Turnierlage` schaltet die Preis-Bewertung dazu. Die Cash-Leiter ist bit-identisch unberührt
(`decide_with(spot, None)` == `decide(spot)` — die `lage` hängt nur am privaten `Table`, nicht am
weit konstruierten `HandSetup`).
## Beweis (SEED 0x5EED_0001, 4000 Austeilungen/Szenario, Pool = 100)
2500 Austeilungen/Szenario (die Intervalle sind jetzt scharf):
```
szenario typ kante ±ci an aus urteil
wta A +0.000 0.000 -1.744 -1.744 · neutral (Anker exakt)
deep-flat A +13.745 4.926 -32.752 -46.497 ✓ gewinnt
soft-bubble B +31.035 7.982 -49.739 -80.774 ✓ gewinnt
hard-bubble B +38.883 11.375 -78.623 -117.506 ✓ gewinnt
hard-bubble-reg B +14.900 5.191 -11.334 -26.234 ✓ gewinnt
final-table B +12.984 4.653 +5.802 -7.182 ✓ gewinnt
jam-vs-nit J +24.030 3.428 +47.878 +23.847 ✓ gewinnt
jam-vs-folder J +20.353 1.497 +63.536 +43.183 ✓ gewinnt
covered-maniac K +32.192 8.182 -100.373 -132.566 ✓ gewinnt (klassischer ICM-Spot)
covered-reg K +12.611 4.367 -3.024 -15.635 ✓ gewinnt
cover-short K -12.468 3.486 -10.350 +2.118 ✗ LECK (Open-Jam-Über-Weitung)
```
**Bilanz:** 10 von 11 Szenarien ✓ gewinnen signifikant (die Maniac-Bubbles jetzt klar, `hard-bubble`
+38.9, `soft-bubble` +31.0), der Anker `wta` exakt 0. Die ICM-Linie gewinnt also überall, wo sie soll
— **mit genau einer Ausnahme:** `cover-short` ist ein echtes **LECK** (−12.5 ±3.5, Intervall ganz unter
0). Das ist der Deckel-Fall (Hero deckt als Big Stack, `jam_width_factor` weitet den Open-Jam), und es
ist **kein Zufall** — der ICM-Nash-Solver des Repos zeigt genau dort die Über-Weitung (Jam 68 % vs Nash
65 %, s. u.). Die Leiter tut also, wofür sie gebaut ist: sie hat als Erstes einen realen, vorbestehenden
Kalibrierfehler der Open-Jam-Weitung gefunden und beziffert.
## Nachtrag (2026-11-12): das Leck ist geschlossen — Tiefen-Gatung
Schritt #1 unten umgesetzt und auf der Leiter bewiesen. `jam_depth_gate` (risk.rs): volle Open-Jam-
Weitung ≤ `JAM_DEPTH_FULL`=12bb, null ≥ `JAM_DEPTH_NONE`=22bb, linear dazwischen; angewandt auf den
**Überschuss** `1 + (w−1)·gate` in decide.rs. Der Hebel hängt an **Heros effektiver Tiefe**, nicht an
der Prämie — ein tiefer Deckler weitet nicht mehr, ein Kurzstack-Jammer voll. 2500 Austeilungen:
```
szenario typ kante ±ci an aus urteil
cover-short K +0.179 0.367 +2.297 +2.118 · neutral (war -12.5 LECK)
cover-6bb K +0.089 0.336 +1.848 +1.758 · neutral
cover-12bb K +0.329 0.407 +1.560 +1.231 · neutral
jam-vs-nit J +24.030 3.428 +47.878 +23.847 ✓ gewinnt (unberührt)
jam-vs-folder J +20.353 1.497 +63.536 +43.183 ✓ gewinnt (unberührt)
covered-maniac K +32.192 8.182 -100.373 -132.566 ✓ gewinnt
covered-reg K +12.611 4.367 -3.024 -15.635 ✓ gewinnt
covered-12bb K +36.383 9.685 -97.064 -133.447 ✓ gewinnt
```
- **`cover-short` −12.5 → +0.18 ±0.37 (neutral)**: Leck zu. Auch `cover-6bb`/`cover-12bb` neutral.
- **Keine Regression**: Kurzstack-Jams (`jam-vs-nit/folder`) und gedeckte Kurzstacks (`covered-*`)
bleiben grün — das Gate greift nur an Heros Tiefe, nicht an der Gegenseite.
- **10bb-Nash bit-identisch**: `jam_depth_gate(10)=1.0` per Konstruktion; `turnier_benchmark`-Call-
Verengung 8bb −13, 10/12/15bb ±0 unverändert; Jam ±1.
- **115 Lib-Tests grün** (inkl. `jam_depth_gate_full_when_short_zero_when_deep_and_monotone`).
Die Leiter hat ihren ersten Leck **gefunden UND dessen Schließung bewiesen** — der volle Mess-Zyklus,
wurzelrichtig und kalibrier-erhaltend. Nichts committed (Freigabe ausstehend).
## Lesart
- **Anker halten.** `wta` (winner-take-all): Kante **+0.000 ± 0.000** — ICM-Equity IST der Chip-Anteil,
also berechnet die Engine dort exakt **null** Prämie und weicht nicht ab. Der sauberste Beweis, dass
das Getriebe cash-neutral bleibt, wo es neutral sein muss.
- **Bubble/Final-Table gewinnen.** Wo die Prämie beißen soll, gewinnt sie: gegen einen ausbalancierten
Reg (`hard-bubble-reg`, `final-table`) ist die Kante signifikant > 0 — das ist die **Prämie selbst**,
nicht der Exploit. Die Engine foldet marginale Spots, die Chip-EV callt, und bewahrt Preis-Equity.
- **Jam-Druck gewinnt.** `jam-vs-nit`/`jam-vs-folder`: die Open-Jam-Weitung (`jam_pressure`) stiehlt
breiter, wenn der Deckel an der Bubble enger callen muss — signifikant > 0.
- **Maniac-Bubbles brauchen Masse.** Gegen einen All-in-Maniac ist die Varianz hoch (±30 bei 300); erst
mit 4000 Austeilungen trennt sich das Intervall von der Null. Die Kante zeigt positiv, das CI
bestätigt (oder nicht) — siehe Tabelle.
## Unabhängige Bestätigung: der ICM-Nash-Solver des Repos
Es gibt bereits einen **echten ICM-Nash-Push/Fold-Solver** im Baum (`entscheiden/turnier_referenz.py:131-170`,
`nash_icm_push`: fiktives Spiel über 169 Handklassen, in Harville-Geld bewertet; HU 10bb/10bb, Payout
50/30/20, dritter Stack 2/5/9bb). `entscheiden/turnier_benchmark.py` fährt die Engine dagegen. Die
Schwellen stimmen schon **auf ~3pp** überein:
| dritter Stack | Jam % (Nash / Engine) | BB-Call % (Nash / Engine) |
|---|---|---|
| 2bb | 97 / 99 | 14 / 13 |
| 5bb | 79 / 77 | 18 / 18 |
| 9bb | 65 / **68** | 22 / 22 |
Das ist die **unabhängige** Bestätigung der neuen Leiter: ein zweites, andersartiges Instrument (ein
Nash-Solver, kein gepaarter EV-Vergleich) sagt dasselbe — die ICM-Linie liegt richtig. **Und beide
zeigen auf dieselbe schwächste Stelle:** bei 9bb jammt die Engine 68 % gegen Nash 65 % — **3pp zu
breit**. Genau das ist das `cover-short`-Szenario der Leiter (Hero deckt als Big Stack, `jam_pressure`
weitet den Open-Jam), das als einziges ein **LECK** ist (−12.5 ±3.5 bei 2500). Zwei Instrumente
treffen dieselbe Diagnose: die **Open-Jam-Weitung (`jam_width_factor`) ist der schwächste Punkt der
ICM-Kalibrierung** — der erste konkrete, messgestützte Angriffspunkt, den die Leiter liefert. (Recon:
`side-session-notes/.../RECON-icm-nash-anker.md`.)
## Was das (noch) NICHT misst — die ehrlichen Grenzen
1. **Symmetrische Tischstacks.** Hero und Tischgegner starten beide auf `stack_bb`; die ICM-Spannung
kommt aus dem **Feld**. Echte ICM-Spots leben oft von **asymmetrischen** Tischstacks (Decker vs.
Gedeckter). Das braucht per-Sitz-Stacks im `Table` (heute ein `stack_bb` für alle) — der nächste
Ausbau der Leiter.
2. **Heads-up am Tisch.** Zwei Spieler am Tisch halten die Chip-Erhaltung sauber (hero_net = −opp_net).
Mehrweg-Tische (3+) bewegen mehrere Stacks und brauchen alle Netto-Ergebnisse aus `run()`.
3. **Keine ICM-Glückskorrektur.** Die gepaarte Differenz auf denselben Karten hebt das Board-Glück
schon fast auf; eine AIVAT-artige ICM-Kontrolle (wie `sim::luck` fürs Chip-bb/100) ist der
Varianz-Feinschliff, nicht gebaut.
4. **Innen-EV, nicht Außen-EV.** Wie beim Cash-Live-Gap (−311, [[BEFUND-liveabgleich-stufe4-live]])
misst die Leiter die Engine gegen ihr eigenes Gegner-Modell. Der Beweis ist „die ICM-Linie schlägt
die Chip-Linie im Modell", nicht „am echten CoinPoker-Tisch".
## Nächste Schritte (messgestützt, priorisiert)
1. **✓ ERLEDIGT (s. Nachtrag oben): Open-Jam-Weitung nachkalibriert — die #1-Baustelle, −12.5 → neutral.**
Wurzel-Hypothese: `jam_width_factor` (risk.rs:138) hängt NUR an der ICM-Prämie, **nicht an Heros
absoluter Tiefe**. Im `cover-short`-Spot deckt Hero mit 40bb und riskiert (über `jam_pressure`s
Caller-Logik) ~30bb — wird aber so breit geweitet wie ein 10bb-Jammer. Eine Weitung, die 30bb
riskiert, wird gecallt und bestraft → −12.5 ICM$/100. Der Nash-Abgleich sieht dieselbe Über-Weitung
bei kurzen Stacks (68 vs 65 @ 9bb), ist aber bei 10bb noch sauber. **Darum ist die Tiefen-Gatung die
wurzelrichtige UND kalibrier-erhaltende Lösung:** die Weitung auf kurze effektive Stacks (≤ ~15bb)
begrenzen, sodass die 10bb-Nash-Kalibrierung unberührt bleibt und nur der tiefe Deckler aufhört,
Müll zu jammen. Prüfstand: die Leiter (`cover-short` → ≥ 0, `jam-vs-nit/folder`/`covered-*` bleiben
grün) UND `entscheiden/turnier_benchmark.py` (Jam-% bleibt auf Nash). Ein **eigener, gemessener
Zyklus** auf `src/icm/risk.rs` — nicht in diesem Befund, der das Instrument und den Befund liefert.
Der Tiefen-Sweep (`cover-6/8/12bb`) in der Batterie lokalisiert, ab welcher Tiefe die Gatung greifen
muss.
2. **Den Nash-Solver als Rust-Anker einziehen.** `nash_icm_push` (`entscheiden/turnier_referenz.py`)
liefert eingefrorene Gold-Standard-Schwellen (Jam 97/79/65, Call 14/18/22, ±3pp) für HU 10bb/10bb,
50/30/20. Ein Rust-Test, der die Engine diese reproduzieren lässt, macht die Kalibrierung
regressionsfest — das Gegenstück zu `tests/cfr_nash.rs` (Chip-Nash) für ICM.
3. **Asymmetrie breiter fahren.** `covered-maniac`/`covered-reg` gewinnen klar; die Deck-Richtung
(`cover-short`) ist die Baustelle. Mehr Decker/Gedeckter-Tiefen (6/12/20bb) kartieren, wo ICM hilft.
## Einordnung
Die Turnier-Pipeline war **operativ** fertig ([[BEFUND-turnier-pipeline-steht]]); jetzt ist sie auch
**messbar stark**. Zum ersten Mal gibt es eine Zahl, die beweist, dass die ICM-Linie gewinnt — das
Measure-First-Fundament, ohne das „Weltklasse im Turnier" nur eine Behauptung ist. Die Leiter ist das
Werkzeug, mit dem jede künftige ICM-Änderung (asymmetrische Stacks, Mehrweg, Future-Game, Push/Fold-
Nash) bewiesen wird — wie die Nemesis-Leiter fürs Cash-Spiel.
## Werkzeug
- `src/sim/turnier_leiter.rs` — `Szenario`, `TurnierMessung`, `messen`, `lage_of`, `icm_score`
(+ 5 Unit-Tests: Pool-Erhaltung, Bust ~0, ICM-Konkavität, WTA-Anker, Determinismus).
- `src/sim/table.rs` — `play_hand_icm` + `lage` am privaten `Table` (cash-neutral).
- `src/bin/turnier_leiter.rs` — die Szenario-Batterie (Anker / Bubble / Jam-Druck).
+104
View File
@@ -0,0 +1,104 @@
# Befund: das Zwillings-Tor steht — und zeigt sofort, was die Leiter verbarg: die Engine verliert gegen Balancierte
Stufe 2 des synthetischen Labors ist gebaut: das **Zwillings-Tor** (`sim::twin_gate`, `bin/twin_gate`),
die Accept/Reject-Regel, die die bb/100-Leiter ersetzt. Ein Kandidat darf nur ausliefern, wenn er auf
**drei Achsen gleichzeitig** nicht verliert.
## Die drei Achsen
1. **OFFENSE — Population-EV.** Die Memory-Winrate gegen die gezogene Population (`sim::exploit_pop`):
die Engine muss ein *variiertes* Feld weiter ausbeuten.
2. **ROBUSTHEIT — der Boden (ein kleines EGTA).** Ein Populations-Gegner antwortet mit seiner besten
Antwort = er wählt den einen Archetyp, gegen den die Engine am schlechtesten läuft (linear ⇒ das
Minimum über die Archetypen ist die schlechteste Mischung). Die EV gegen diesen Archetyp ist der
Boden; kein Change darf ihn senken. Das ist die Achse, die einen Fix fängt, der Fische zerlegt, aber
gegen Balancierte blutet.
3. **DEFENSE — River-Exploitability.** Ein exakter Best-Response-Abstand auf einer festen Batterie von
River-Subgames (`sim::exploit_river`); kein Change darf ihn heben. Die Achse, die einen Change fängt,
der EV kauft, indem er unbalanciert/ausbeutbar spielt.
`Gate::passes` ist der reine Vergleicher zwischen Baseline und Kandidat, mit Toleranzen in Rauschgröße.
Damit wird „nie einen Verlierer ausliefern" rigoros und mehrachsig.
## Erste Messung (`twin_gate`, Population 40×300, Archetypen 1500, River 8000 Iter.)
```
OFFENSE Population-EV (Memory) +32.24 bb/100 (Exploitation-Lücke +17.16)
ROBUSTHEIT EV je Archetyp (Memory):
reg -8.44 ±39.50
nit +51.06 ±18.06
maniac +114.27 ±63.26
fish +123.32 ±34.50
gto -22.80 ±28.47
gto-small -35.25 ±30.80 <- BODEN
DEFENSE River-Exploitability (5 Spots): Mittel 77.03, Max 145.83 bb/100
```
## Was das zeigt (ehrlich)
1. **Das Tor findet sofort die wahre Schwäche.** In ihrem *realistischen* Modus (Read erschlossen, nicht
Oracle geschenkt) ist die Engine gegen alle drei balancierten/soliden Gegner **im Minus**: reg −8,
gto −23, gto-small −35. Sie verdient ihr Geld bei Fisch/Maniac/Nit (+51 bis +123) und **verliert es
an die Balancierten zurück**. Das ist exakt die dokumentierte Wurzel (`gto-overdefense-root`,
`BEFUND-gto-ueberdefense`, der reg −2.53 aus Stufe 0) — jetzt als harte Bodenachse, nicht als Fußnote.
2. **Die Leiter verbarg genau das.** Dort laufen die GTO-Szenarien mit **Oracle-Read**
(`benchmark.rs`: `balanced(..., ReadMode::Oracle)`). Mit geschenktem perfektem Read spielt die Engine
gegen Balancierte näher an GTO und das Minus verschwindet. Das Tor nimmt den Oracle weg und macht den
realen Verlust sichtbar: die bb/100-Leiter konnte den gefährlichsten Change — einen, der gegen
Balancierte überadjustiert — gar nicht als Verlierer erkennen.
3. **Defense ist ein relativer Riegel, keine Absolutzahl.** 77 bb/100 mittlere Exploitability klingt
hoch, ist aber ein Artefakt der absichtlich polaren Batterie mit winzigen 4-Combo-Ranges (ein falscher
Bucket = großer Swing). Der Zweck ist der Vergleich Baseline↔Kandidat auf **derselben** Batterie, nicht
die Behauptung „die Engine ist 77 bb ausbeutbar". Gegen die balancierte GTO-Schwäche ist zu erwarten,
dass ein guter Defensiv-Fix diese Zahl **senkt**.
## Nachtrag: Vollbudget-Lauf (`TwinBudget::default()` — Population 48×400, Archetypen 4000, River 12000)
Die erste Messung lief bewusst mager. Nachgefahren bei vollem Produktionsbudget, um den „Rauschen"-
Vorbehalt zu schließen:
```
OFFENSE Population-EV (Memory) +43.95 bb/100 (Exploitation-Lücke +18.98)
ROBUSTHEIT EV je Archetyp (Memory):
reg -17.66 ±23.58
nit +42.92 ±11.71
maniac +45.31 ±36.50
fish +126.85 ±20.67
gto -36.25 ±19.19 <- BODEN
gto-small -25.93 ±17.55
DEFENSE River-Exploitability (5 Spots): Mittel 77.03, Max 145.83 bb/100
```
**Die Schlussfolgerungen sind budget-robust — nicht Artefakte der mageren Erstmessung.** Offense +43.95
trifft den Stufe-0-Wert (+18.98 Lücke) auf die Kommastelle. Die CIs sind enger (±12–37 statt ±18–63), und
die *Richtung* hält unverändert: alle drei Balancierten im Minus (reg −18, gto −36, gto-small −26),
Fisch/Maniac/Nit stark positiv. Der Boden wandert nur innerhalb des Rauschens von gto-small auf **gto
−36.25** — es bleibt ein balancierter GTO-Spieler, die dokumentierte Over-Defense-Wurzel. Die
River-Exploitability (exakte Best Response, deterministisch) ist bitidentisch (77.03/145.83), wie erwartet,
da nur die Iterzahl stieg und die Batterie fix ist. Der „nimm TwinBudget::default()"-Vorbehalt ist damit
eingelöst: das volle Budget bestätigt das Leck, statt es zu widerlegen.
## Grenzen (ehrlich)
- **Rauschen.** Bei 1500 Austeilungen waren die Boden-CIs breit (±28–63); bei vollem Budget (oben)
schrumpfen sie auf ±12–37. Die *Richtung* (balanciert = negativ, ausbeutbar = stark positiv) war schon
mager robust und ist es voll erst recht; die *Magnituden* sind jetzt belastbar.
- **Varianzreduktion fehlt noch.** Das Tor misst heute *absolute* EV je Build; ein regressionsfester
Boden sollte die *Differenz* Kandidat−Baseline mit gemeinsamen Zufallszahlen (common random numbers,
gleicher Seed) messen, damit das Rauschen paart und die Toleranz unter die CI fällt. Nächster Ausbau
der Messachse (das `sim::aivat`-Werkzeug ist dafür bereits bewiesen).
- Die GTO-Archetypen sind solver-getrieben und dominieren die Laufzeit; darum die magere Deal-Zahl.
## Einordnung
Das Tor ersetzt die Leiter nicht nur formal — es hätte genau die Fehlmessung verhindert, die diese
Arbeit lange blockierte: ein Change, der auf der Leiter „gewinnt", weil er Dummies überfittet oder weil
der Oracle-Read das Balanciert-Leck zudeckt. „Nie einen Verlierer ausliefern" heißt ab jetzt: **Boden
hält, Exploitability steigt nicht, Population-EV hält** — alle drei. Siehe
`ARCHITEKTUR-synthetik-labor.md`, Stufe 2.
+92
View File
@@ -0,0 +1,92 @@
# Mathematik-Landkarte: Arsenal, Getriebe, Tiefe, Messschicht
Der Anspruch: beste Engine der Welt für Cash **und** Turnier, durch Forschungs-Mathematik, nicht durch
Heuristik-Schrauben. Diese Karte trennt ehrlich, was **bewiesen** ist, was **verdrahtet** ist und was
**fehlt**. Sie ist der rote Faden; jede Zeile nennt ihren Beweis-Status.
## Eiserne Gesetze (gelten über allem)
1. **Nie einen Verlierer ausliefern.** Ein gemessenes Minus → Rückbau + Befund. (Stage A live: −43 →
zurückgebaut, `BEFUND-river-solver-balanced-vs-exploitable`.)
2. **Jede Live-Änderung auf der Leiter beweisen** — gepaart, 95 %, glückskorrigiert.
3. **An der Wurzel angreifen**, nicht am Symptom.
4. **Cash- und Turnierwissen trennen** (ICM/Bubble vs Rake/Deepstack) über einem Mathe-Kern.
## 1. Das Arsenal — die Primitive (alle als Primitiv bewiesen, `--lib` grün)
| Primitiv | Modul | Was | Beweis |
|---|---|---|---|
| Bayes-Posterior | `exploit::posterior` | Beta-Posterior je Gegner-Tendenz, Konfidenz | Tests grün |
| Value of Information | `exploit::thompson` | Thompson/Bandit, Gamma-Sampling | Tests grün |
| MaxEnt-Ranges | `exploit::maxent` | Jaynes: unvoreingenommenste Range unter Momenten | Entropie-Maximum-Test |
| QRE / Temperatur | `cfr::qre` | Logit-Gleichgewicht, Temperatur aus Beobachtung | interpoliert uniform↔Nash |
| Krone: KL-Best-Response | `cfr::kl_br` | σ\* ∝ σ_GTO·exp(Q/λ), sichere Ausnutzung | λ-Sweep-Test |
| Kelly-Sizing | `sizing::kelly` | log-Wachstum, fraktioniert | Wachstums-Tests |
| AIVAT-Varianzreduktion | `sim::aivat` | Kontrollvariate, kreuzangepasstes β | 17× auf Testdaten |
| River-Subgame-Solver | `engine::river_subgame` | card-exakt, CFR+ | **0.0 Exploitability** vs korrekte Überzeugung |
| Anytime-Konfidenzfolge | `sim::sequential` | zeituniforme CI, Früh-Stopp | Miscoverage 0.008 ≤ 0.050 unter Peeking |
**Das Arsenal ist vollständig auf Forschungsniveau.** Was fehlt, ist nicht ein weiteres Primitiv —
sondern das Getriebe, das sie zu **einer** Engine koppelt.
## 2. Das Getriebe — die Kopplungen (der eigentliche Rückstand)
Jede Zeile ist eine geschlossene Schleife, die ein Primitiv an den Live-Pfad hängt. **Fast keine ist
verdrahtet** — hier liegt die ganze offene Arbeit.
| Schleife | von → nach | Zweck | Status |
|---|---|---|---|
| **Belief** | `posterior` → Range-Belief → `river_subgame` | Solver gegen *vermutete* Gegnerrange statt symmetrisch | **fehlt** — die Wurzel des −43-Befunds |
| **Vertrauen (Krone)** | `posterior::confidence` → λ → `kl_br` | starker Read → weit ausnutzen, schwacher → nahe GTO | **fehlt** |
| **Temperatur** | beobachtete Reads → `qre::fit_temperature` → Gegnermodell | Rationalität des Gegners schätzen | **fehlt** |
| **Modus** | Cash/Turnier → Terminalwert-Karte (Rake vs ICM) + `kelly`↔ICM | modusgerechte Endwerte | teilweise (Terminalwerte ja, ICM-Kopplung nein) |
| **Messung: AIVAT (β)** | `aivat` → Live-Benchmark | optimaler Kontrollvariaten-Koeffizient | **gemessen: toter Hebel** — β=1 schon nahe-optimal, β\* ein Wash (`BEFUND-bench-kontrollvariate-beta`) |
| **Messung: AIVAT (Signal)** | per-Node-Baseline → Benchmark | stärkeres ρ, nicht besseres β | **fehlt** — der echte Hebel (volle AIVAT-Korrektur) |
| **Messung: Früh-Stopp** | `sequential` → Benchmark | peeken + stoppen ohne Verzerrung | Primitiv bewiesen; Einhängen offen |
**Die Belief- und Vertrauens-Schleife ist der höchste Hebel:** sie verwandelt den bewiesenen, aber
stillgelegten River-Solver in echte Live-EV — *sicher*, weil der KL-Riegel ihn nie wieder gegen einen
Fisch ausbalancieren und nie gegen einen Unbekannten überausnutzen lässt.
## 3. Die Tiefe — gelöste Spielbäume
| Straße | Status |
|---|---|
| Preflop | **steht**: voll-breiter CFR+ (`cfr::mod`), Push/Fold + Open/3-Bet, 1–4 Defender, Multiway-Abtastung |
| River (Stage A) | **gelöst + bewiesen** (0.0), aber *nicht live* (Belief fehlt) |
| Turn+River (Stage B) | fehlt — card-exaktes Turn→River-Subgame |
| Flop→ (Stage C) | fehlt — volle Postflop-Tiefe mit Abstraktion |
| Multiway postflop | fehlt (preflop gibt es, postflop heads-up-only) |
## 4. Die Messschicht — ist der Maßstab selbst Weltklasse?
Heute: gepaarte/antithetische Stichproben + Glückskorrektur (β=1) + 95 %-CI + Regressions-Gate.
**Solide, aber nicht Weltklasse.** Die Weltklasse-Teile sind gebaut, teils noch nicht eingehängt:
- **AIVAT-β im Gate — gemessen erledigt, toter Hebel.** β=1 ist schon nahe-optimal; kreuzangepasstes
β\* ist ein Wash (±1–4 %, teils schlechter), weil `Var(net−β·luck)` am Minimum flach ist
(`BEFUND-bench-kontrollvariate-beta`). NICHT eingehängt. Der lebende Hebel ist nicht β, sondern ρ:
ein **stärkeres Kontrollsignal** — die volle AIVAT-Baseline an jedem Chance-/Gegnerknoten statt nur
All-in-Glück. Das hebt die Deckelung 1−ρ² und ist noch ungebaut.
- **Zeituniformer Früh-Stopp** — `sim::sequential` steht und ist bewiesen; einhängen heißt: nach jeder
Austeilung peeken, stoppen sobald entschieden → Gate-Zeit drastisch runter bei gültiger Fehlerrate.
- **Exploitability über River hinaus** — heute River-only mit harter Vollrange; fehlen: Turn/Multiway
und realistische (verengte) Ranges, damit die zweite Hälfte der Weltklasse-Bewertung vollständig ist.
- **Gegner-Holdout** — alles gegen feste Bots = in-sample; ein Holdout-Pool gegen Overfit fehlt.
## 5. Der Optimizer — die späte Schicht
Für Hyperparameter (Form der λ-Konfidenz-Abbildung, ρ der Konfidenzfolge, Sizing-Gitter): **Bayesian
Optimization / CMA-ES, nicht Genetik.** AIVAT-betrieben (billige, rauscharme Zielfunktion),
exploitability-bewacht (kein Bot-Overfit). Aber: die λ-Abbildung wird **hergeleitet** (Informations-
theorie), nicht gesucht — der Optimizer ist Feinschliff, kein Ersatz für die Herleitung. **Zuletzt.**
## Reihenfolge nach gemessenem Hebel
1. **Belief + Vertrauens-Getriebe** (`posterior`→Range→`river_subgame`, `confidence`→λ→`kl_br`): macht
den bewiesenen River-Solver *sicher live*. Der eine Umbau, der −43 in echtes Plus dreht. Höchster Hebel.
2. **Messschicht auf Weltklasse**: `sequential` einhängen (Früh-Stopp) + **volles AIVAT-Signal** (per-Node-
Baseline, nicht β-Tuning — das ist gemessen tot) → schnellerer, engerer Maßstab für alles danach.
3. **Stage B** (Turn+River), sobald Belief/Vertrauen am River bewiesen sind.
4. **Exploitability-Ausbau** (Turn/Multiway/realistische Ranges) + Holdout-Pool.
5. **Optimizer** (BO/CMA-ES) ganz zuletzt.
+64
View File
@@ -0,0 +1,64 @@
# Runbook: das kontrollierte Live-A/B (COINPOKER_KERN an/aus) fahren
Dies ist der eine noch offene Schritt von Stufe 4. **Es fehlt kein Code** — Harness, Arm-Trennung und
Signifikanz-Test stehen und sind getestet. Was fehlt, sind **Hände unter beiden Armen**: eine geldechte
Live-Session gegen echte Gegner, die nur der Betrieb am Tisch erzeugt. Dieses Runbook ist die genaue
Befehlsfolge dafür — danach rechnet das Werkzeug das Urteil in einer Zeile.
## Das Prinzip
Zwei Arme, sonst alles gleich (derselbe Farm, dieselben Stakes, dieselbe echte Population, abwechselnd):
- **AN** — mit dem Engine-Kern: `COINPOKER_KERN` zeigt auf `target/release/rechner(.exe)`.
- **AUS** — die Baseline ohne die zu prüfende Änderung: `COINPOKER_KERN` zeigt auf das Baseline-Binary
(z. B. ein Build des Kerns ohne den neuen Read / die neue Stufe, oder der vorige getaggte Kern).
Jeder Arm schreibt seine Hände in einen EIGENEN Statistik-Ordner über `STATS_DIR` (die Trennung ist
schon da, `betrieb/statistik.py:258`). So entstehen zwei saubere `haende.jsonl`.
## Die Befehle
Arm AN (eine Session am Tisch laufen lassen):
```bash
COINPOKER_KERN="$PWD/target/release/rechner.exe" \
STATS_DIR="$PWD/archiv/ab/arm_an" \
python3 betrieb/runner.py # normaler Lauf; so lange spielen, bis genug Hände zusammen sind
```
Arm AUS (eigene Session, Baseline-Binary, eigener Ordner):
```bash
COINPOKER_KERN="$PWD/target/release/rechner_baseline.exe" \
STATS_DIR="$PWD/archiv/ab/arm_aus" \
python3 betrieb/runner.py
```
Auswerten (sobald beide Arme Hände haben):
```bash
python3 lesen/liveabgleich.py --ab archiv/ab/arm_an/haende.jsonl archiv/ab/arm_aus/haende.jsonl
```
Das druckt bb/100 je Arm mit 95-%-Intervall, die Differenz und das Urteil
(schlägt/verliert/unentschieden, `ab_vergleich`).
Alternativ, falls beide Arme in EIN Log schreiben und die Hände ein Feld `kern` ("an"/"aus") tragen:
```bash
python3 lesen/liveabgleich.py --ab-log archiv/ab/haende.jsonl kern
```
## Wie viele Hände?
Die Winrate-Streuung ist groß. Für ein belastbares Urteil bei einer Kante von ~30–50 bb/100 braucht es
grob **einige Tausend Hände je Arm** (das 95-%-Intervall der Differenz schrumpft mit 1/√n). Der reale
190-Hand-Schnappschuss (`archiv/lauf/`) hat allein ein Intervall von fast 600 bb/100 — zu wenig für den
A/B. Das Werkzeug sagt „kein signifikanter Unterschied", bis die Arme dick genug sind; es überzeichnet nie.
## Warum das hier endet
Alles bis zu diesem Punkt ist gebaut, getestet und (auf vorhandenen Daten) gefahren. Der letzte Schritt
ist kein Programmier-, sondern ein Betriebsschritt: echtes Geld, echte Gegner, Zeit am Tisch. Den löst der
Mensch im Betrieb aus, nicht die Werkbank. Siehe `BEFUND-liveabgleich-stufe4-live`,
`ARCHITEKTUR-synthetik-labor.md` (Stufe 4).
+61
View File
@@ -0,0 +1,61 @@
# Stand & Fahrplan: der Weg zum echten Game
Stand 2026-11-12. Dieser Zettel fasst zusammen, was steht, und den kürzesten sicheren Weg vom jetzigen
Punkt zu Echtgeld am Tisch. Einzelbefunde liegen daneben in `docs/notizen/BEFUND-*.md`.
## Wo wir stehen
**Die Maschine läuft live.** Der mechanische Pfad (sitzen → lesen → entscheiden → klicken) ist auf
Windows bewiesen: Hero saß, spielte, gewann **+1320** in einem Live-Lauf. Die Sitz-Reserve-Race (30 s
TTL) ist gefixt und live bestätigt; der Läufer ist von 35–53 s/Loop auf ~Millisekunden runter (nativer
Toolhelp+PEB-Prozessleser statt WMI, echo=False fire-and-forget).
→ `BEFUND`e: Seating-TTL, Winproc-Speedup.
**Die Engine ist mathematisch dicht.** Die großen Lecks sind gefixt und auf der Synthetik-Leiter
bewiesen (gepaart, 95 %-CI, luck-korrigiert, nie ein Verlierer geshippt):
- GTO-Überverteidigung (MDF-Boden über-defendete gegen Balancierte) — trust-aware über Postflop-
Aggression statt Preflop-Breite.
- Nemesis-Station-Fehllesung (−414 bb/100) — Klassifikation auf Aggression gated + konfidenz-
gewichtetes Stations-Trust.
- River-Overbet-Defense-Loch — River-Subgame-Solver als Cash-only Fold-Veto (nemesis-3 −26,6 → +0,6).
- Dazu: ICM-Turnier-Linie (schlägt Chip-EV), EV-neutrales Size-Mix, Stage-A River-Solver.
**Das Messwerkzeug ist fertig (dieser Lauf).** Um live schnell zu lernen, nicht zu raten:
- **Live-A/B** temporal (ein-Prozess-Engine verbietet simultan): `COINPOKER_ARM` markiert Hand+Zug,
`statistik.je_arm` + `liveabgleich.ab_aus_log(feld="arm")` geben das Welch-Urteil je Arm.
- **Insights**: `lesen/einblick.py` aggregiert `zuege.jsonl` nach Street/Position/Klasse/Grund, je Arm.
- **All-in-EV** (`lesen/allin_ev.py`): ersetzt bei All-in vor dem River den Board-Wurf durch die
equity-gewichtete EV — mittelwerttreu, Varianz runter, A/B ~60 % schneller signifikant. Preflop über
seed-deterministischen Monte-Carlo (`eval7.equity_mc`/`score7`, bewiesen gleichwertig zum Ground-
Truth). Linse `netto_bb(ev=True)` / CLI `--ev`; roh bleibt überall Vorgabe.
→ `BEFUND-allin-ev.md`, `BEFUND-live-ab-einblick.md`.
**Was fehlt:** der *nachhaltige* 12-Tisch-Live-Lauf. Alles ist einzeln bewiesen, aber noch nie als
Ganzes stundenlang live gelaufen. Das ist der nächste Schritt — kein weiterer Bau.
## Fahrplan — 3 Stufen zum echten Game
**Stufe 1 — Übung (Spielgeld), das Gate.** 12 Tische, `TEMPO=schnell`, ein paar Stunden. Zweck: beweisen,
dass der Loop als Ganzes trägt, bevor Geld im Spiel ist. `betrieb/scratch/spielplan.json`:
`{"modus":"uebung","tische":12,...}`, dann `python3 betrieb/runner.py --act`. Urteil:
`python3 betrieb/stufe0.py --shadow archiv/lauf/shadow.jsonl`. **Grün = 0 Abbrüche, 0 Timeouts**, saner
Stil (VPIP/PFR plausibel). Das ist der einzige harte Riegel vor Echtgeld.
**Stufe 2 — Micro-Echtgeld, gedeckelt.** `spielplan.json`: `modus:"cash"`, `micro_only:true` (kappt die
Stakes auf `MICRO_MAX_BB`), kleines `budget` + Verlustdeckel. Derselbe Runner. `micro_only` ist genau der
„schnell testen ohne Risiko"-Schalter.
**Stufe 3 — iterieren mit dem Werkzeug.** Live bb/100 mit 95 %-CI verfolgen; `einblick.py` je Arm lesen;
eine Engine-Stellschraube temporal A/B-en (`COINPOKER_ARM`), die All-in-EV (`--ev`) dämpft das Rauschen.
Größtes Leck finden → auf der Leiter beweisen → nur Gewinner shippen.
## Ehrlich zu Risiko & Tempo
- **Varianz bei Micro ist brutal.** Live paart keine Karten wie die Synthetik-Leiter; A/B braucht
realistisch Δ≳20 bb/100. Die All-in-EV hilft, ersetzt aber keine Stichprobe → Tage, nicht Stunden,
für belastbare Live-Zahlen.
- **Das Timing-Modell ist nur synthetisch validiert** — VOLL=12 ist die „ruhige Decke", TEMPO=schnell
der Durchsatz-Hebel; der echte 12-Tisch-Lauf ist der erste Realtest.
- **Branch-Lage:** Dieser Zweig ist jetzt `main`. Der Live-Betrieb des Owners läuft aus dem Haupt-
Checkout (`engine/stage0-blind-ladder`, bereits vollständig in diesem Zweig enthalten); um das neue
Werkzeug dort live zu fahren, `main` in diesen Checkout ziehen.
+231
View File
@@ -0,0 +1,231 @@
#!/usr/bin/env python3
"""Unabhaengiger 7-Karten-Evaluator und River/Runout-Equity - der GROUND TRUTH des Replay-Benchmarks.
Bewusst NICHT die Engine (src/hand): der Benchmark benotet die Engine, also darf der Massstab nicht
aus derselben Quelle stammen. Klein, offensichtlich korrekt, mit Selbsttest (`_selftest`).
from eval7 import equity_vs, best7, karten
"""
import gc
import itertools
import random
from collections import Counter
RANG = {r: i for i, r in enumerate("23456789TJQKA", 2)}
FARBEN = "shdc"
VOLLDECK = [(r, s) for r in range(2, 15) for s in FARBEN]
def karte(t):
"""'As' -> (14, 's'); robust gegen 10/Zehn-Schreibweisen."""
t = t.strip()
return (RANG[t[0]], t[1])
def karten(s):
"""'As Kd' oder Liste -> [(14,'s'),(13,'d')]."""
if isinstance(s, (list, tuple)):
return [karte(x) for x in s]
return [karte(x) for x in s.split()]
def score5(cards):
"""Vergleichbarer Wert einer 5-Karten-Hand: (Kategorie, Kicker-Liste). Groesser = besser."""
rks = sorted((c[0] for c in cards), reverse=True)
suits = [c[1] for c in cards]
cnt = Counter(rks)
flush = len(set(suits)) == 1
dist = sorted(set(rks), reverse=True)
sh = None
if len(dist) == 5:
if dist[0] - dist[4] == 4:
sh = dist[0]
elif dist == [14, 5, 4, 3, 2]: # Wheel A-2-3-4-5
sh = 5
# Raenge nach (Anzahl, Rang) ordnen -> Kicker fuer Paare/Drillinge/Full House
seen = []
for r in sorted(rks, key=lambda r: (cnt[r], r), reverse=True):
if r not in seen:
seen.append(r)
pat = sorted(cnt.values(), reverse=True)
if sh and flush:
return (8, [sh])
if pat == [4, 1]:
return (7, seen)
if pat == [3, 2]:
return (6, seen)
if flush:
return (5, rks)
if sh:
return (4, [sh])
if pat == [3, 1, 1]:
return (3, seen)
if pat == [2, 2, 1]:
return (2, seen)
if pat == [2, 1, 1, 1]:
return (1, seen)
return (0, rks)
def best7(cards7):
"""Beste 5 aus 7 (oder aus 5/6) Karten."""
if len(cards7) <= 5:
return score5(list(cards7))
return max(score5(list(c)) for c in itertools.combinations(cards7, 5))
def equity_vs(hero, board, vils):
"""Exakte Equity von `hero` (2 Karten) auf `board` (3-5) gegen bekannte Gegnerhaende `vils`.
Enumeriert ALLE Runouts (kein Monte Carlo): am River exakt der Showdown, am Flop/Turn der
Mittelwert ueber alle Boardvervollstaendigungen. Ties zaehlen anteilig."""
hero = karten(hero) if not isinstance(hero[0], tuple) else hero
board = karten(board) if board and not isinstance(board[0], tuple) else list(board)
vils = [karten(v) if not isinstance(v[0], tuple) else v for v in vils]
bekannt = set(hero) | set(board)
for v in vils:
bekannt |= set(v)
deck = [c for c in VOLLDECK if c not in bekannt]
miss = 5 - len(board)
won = 0.0
n = 0
for extra in itertools.combinations(deck, miss):
full = board + list(extra)
hs = best7(hero + full)
vstr = [best7(v + full) for v in vils]
mx = max(vstr)
if hs > mx:
won += 1.0
elif hs == mx:
won += 1.0 / (1 + sum(1 for x in vstr if x == hs))
n += 1
return won / n if n else 0.0
def _strasse_hoch(vorhanden):
"""Hoechste Karte einer Strasse in der Rangmenge `vorhanden` (Set), oder None. Ass zaehlt auch
tief (Wheel A-2-3-4-5 -> 5)."""
if not vorhanden:
return None
r = set(vorhanden)
if 14 in r:
r.add(1)
for hi in range(14, 4, -1):
if hi in r and hi - 1 in r and hi - 2 in r and hi - 3 in r and hi - 4 in r:
return hi
return None
def score7(cards7):
"""Direkter 7-Karten-Wert - DASSELBE vergleichbare (Kategorie, Kicker)-Tupel wie best7, nur ohne
die 21-Kombinationen-Schleife (fuer equity_mc). Gleichwertig zu best7 (Differenztest _selftest /
tests/eval7_mc_spec), aber ~5x schneller und allokationsarm."""
cnt = [0] * 15
farbe = {"s": [], "h": [], "d": [], "c": []}
for r, s in cards7:
cnt[r] += 1
farbe[s].append(r)
fs = None
for s in farbe:
if len(farbe[s]) >= 5:
fs = s
break
if fs is not None:
sf = _strasse_hoch(set(farbe[fs]))
if sf:
return (8, [sf])
vier = drei = None
paare = []
for r in range(14, 1, -1):
c = cnt[r]
if c == 4 and vier is None:
vier = r
elif c == 3:
if drei is None:
drei = r
else:
paare.append(r) # ein zweiter Drilling zaehlt als Paar fuers Full House
elif c == 2:
paare.append(r)
if vier is not None:
kick = max(r for r in range(14, 1, -1) if cnt[r] and r != vier)
return (7, [vier, kick])
if drei is not None and paare:
return (6, [drei, paare[0]])
if fs is not None:
return (5, sorted(farbe[fs], reverse=True)[:5])
sh = _strasse_hoch([r for r in range(2, 15) if cnt[r]])
if sh:
return (4, [sh])
if drei is not None:
ks = [r for r in range(14, 1, -1) if cnt[r] and r != drei][:2]
return (3, [drei] + ks)
if len(paare) >= 2:
hp, lp = paare[0], paare[1]
kick = max(r for r in range(14, 1, -1) if cnt[r] and r != hp and r != lp)
return (2, [hp, lp, kick])
if paare:
p = paare[0]
ks = [r for r in range(14, 1, -1) if cnt[r] and r != p][:3]
return (1, [p] + ks)
return (0, [r for r in range(14, 1, -1) if cnt[r]][:5])
def equity_mc(hero, board, vils, laeufe=6000, seed=0):
"""Monte-Carlo-Schaetzung derselben Equity wie equity_vs, aber ueber `laeufe` ZUFAELLIGE
Boardvervollstaendigungen (seed-deterministisch) statt aller. Fuer den Preflop-All-in, wo die
exakte Enumeration C(48,5)=1,7M Runouts (Minuten) zu teuer ist.
UNVERZERRT: jeder Runout ist eine gleichverteilte Ziehung aus demselben Raum, den equity_vs
vollstaendig mittelt -> E[Schaetzung] = wahre Equity, nur MC-Rauschen ~0.5/sqrt(laeufe) (bei
6000: ~0.6 % 1-Sigma). Das erhaelt die Mittelwerttreue der All-in-EV (lesen/allin_ev): ein
unverzerrter Equity-Schaetzer gibt einen unverzerrten EV. `seed` macht es je Matchup reproduzierbar
(gleiche Karten -> gleiche Schaetzung, auch ueber A/B-Arme hinweg)."""
hero = karten(hero) if not isinstance(hero[0], tuple) else hero
board = karten(board) if board and not isinstance(board[0], tuple) else list(board)
vils = [karten(v) if not isinstance(v[0], tuple) else v for v in vils]
bekannt = set(hero) | set(board)
for v in vils:
bekannt |= set(v)
deck = [c for c in VOLLDECK if c not in bekannt]
miss = 5 - len(board)
if miss <= 0:
return equity_vs(hero, board, vils) # Board schon komplett -> exakt (ein Showdown)
rng = random.Random(seed)
stich = rng.sample # lokale Namen -> weniger Attributzugriffe je Runout
bewerte = score7
won = 0.0
gc.disable() # ohne GC bleibt die Schleife linear (sonst super-linear)
try:
for _ in range(laeufe):
full = board + stich(deck, miss)
hs = bewerte(hero + full)
vstr = [bewerte(v + full) for v in vils]
mx = max(vstr)
if hs > mx:
won += 1.0
elif hs == mx:
won += 1.0 / (1 + sum(1 for x in vstr if x == hs))
finally:
gc.enable()
return won / laeufe
def _selftest():
b = karten("Ts Th 5d Tc 8c")
assert best7(b + karten("As 6h")) > best7(b + karten("Ks 4h")) # TTT+A schlaegt TTT+K
assert score5(karten("Ah Kh Qh Jh 9h"))[0] == 5 # Flush
assert score5(karten("Ah Kd Qh Jh Th"))[0] == 4 # Strasse
assert score5(karten("Ah 2d 3h 4h 5h"))[0] == 4 # Wheel
assert score5(karten("Ah Ad Ac Ks Kd"))[0] == 6 # Full House
assert score5(karten("Ah Ad Ac As Kd"))[0] == 7 # Quads
assert equity_vs("Ac Ad", "Kc 7h 2s", ["Kh Qd"]) > 0.78 # AA schlaegt Top Pair KQ klar
assert equity_vs("Kc 7s", karten("Qc 2h Kd 6d 8d"), ["Ad Qh"]) == 1.0 # River: top pair K schlaegt QQ
assert equity_vs("Ac Ad", "2h 3h 4h 5h 9s", ["6h 7h"]) == 0.0 # River: fertiger Flush schlaegt AA
_selftest()
if __name__ == "__main__":
_selftest()
print("eval7 Selbsttest ok")
+335
View File
@@ -0,0 +1,335 @@
#!/usr/bin/env python3
"""Replay-Benchmark: der EHRLICHE Postflop-Massstab aus echten Hand-Histories.
Statt bb/100 gegen selbstgeschriebene Bots (die nur messen, ob wir die EIGENEN Fische schlagen)
treibt dieser Benchmark die ECHTE, AKTUELLE Engine ueber jede Hero-Entscheidung einer realen Session
und benotet sie gegen einen UNABHAENGIGEN Evaluator (`eval7`) auf den tatsaechlich gezeigten
Gegnerkarten. Jeder Hero-Spot wird aus der Hand-History als Wire-Anfrage rekonstruiert (board, pot,
toCall, Stacks, history, Profile) und neu entschieden - so misst der Benchmark FIXES, nicht nur die
alte Session.
Vier Masse:
* TREUE: reproduziert die Re-Decision die geloggte Linie? (Rekonstruktion korrekt?)
* EV-VERLUST: wo der Gegner zeigt - foldet die Engine +EV-Calls weg / callt sie -EV-Spots? (bb)
* EQUITY-BIAS: Engine-Equity minus WAHRE Equity (negativ = unterschaetzt -> Overfold-Wurzel)
* FOLD/MDF: Fold-gegen-Bet je Street gegen die Minimum-Defense-Frequency
COINPOKER_EXPORT=/pfad/zur/session.md python3 entscheiden/replay.py
COINPOKER_KERN=.../target/release/rechner.exe # Engine-Binary (Default: target/release/rechner)
"""
import json
import os
import re
import sys
from collections import Counter
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import decide
from eval7 import equity_vs, karten
HERO = "mmintel"
RANG = {"A": "ACE", "K": "KING", "Q": "QUEEN", "J": "JACK", "T": "TEN", "9": "NINE", "8": "EIGHT",
"7": "SEVEN", "6": "SIX", "5": "FIVE", "4": "FOUR", "3": "THREE", "2": "TWO"}
FARBE = {"s": "SPADES", "h": "HEARTS", "d": "DIAMONDS", "c": "CLUBS"}
STREETS = ["PREFLOP", "FLOP", "TURN", "RIVER"]
def _wire_card(t):
return {"rank": RANG[t[0]], "suit": FARBE[t[1]]}
def _wire_cards(txt):
return [_wire_card(x) for x in txt.split()]
def _board_dict(board_cards):
"""5-Karten-Board (Textliste) -> Wire-Board-Dict bis zur erreichten Street."""
d = {}
if len(board_cards) >= 3:
d["FLOP"] = [_wire_card(c) for c in board_cards[:3]]
if len(board_cards) >= 4:
d["TURN"] = [_wire_card(board_cards[3])]
if len(board_cards) >= 5:
d["RIVER"] = [_wire_card(board_cards[4])]
return d
# ---------------------------------------------------------------- HH-Parser
ACT_RE = re.compile(r'^(\S+): (posts small blind|posts big blind|posts the ante|folds|checks|'
r'bets|calls|raises)(?: \$?([0-9.]+))?(?: to \$?([0-9.]+))?', re.M)
def parse_hand(block):
"""MD-Handblock -> dict mit allem fuer die Rekonstruktion, oder None wenn unbrauchbar."""
hid = block.split(" ", 1)[0].lstrip("#")
mhole = re.search(r'Hero Hole Cards:\*\* `([^`]+)`', block)
mhh = re.search(r'```text\n(.*?)```', block, re.S)
if not mhole or not mhh:
return None
hero_cards = mhole.group(1).split()
hh = mhh.group(1)
# Engine-Entscheidungen (Street, board, pot, toCall, action) in Dokumentreihenfolge
dec_re = re.compile(r'`(PREFLOP|FLOP|TURN|RIVER)` \| board=`([^`]*)` \| '
r'pot=\$([0-9.]+) toCall=\$([0-9.]+) \| \*\*([A-Z]+)\*\* \| '
r'eq=([0-9.]+|None) \| (.*)')
decisions = [{"street": m.group(1), "board": m.group(2).split(), "pot": float(m.group(3)),
"to_call": float(m.group(4)), "action": m.group(5),
"eq": None if m.group(6) == "None" else float(m.group(6)), "reason": m.group(7)}
for m in dec_re.finditer(block)]
if not decisions:
return None
# VPIP/Hands je Name aus der Players-Zeile
prof = {}
for mm in re.finditer(r'S\d+ (\S+) \(\$[0-9.]+, VPIP (\d+)%/(\d+)h\)', block):
prof[mm.group(1)] = {"vpip": int(mm.group(2)) / 100.0, "hands": int(mm.group(3))}
# Sitze, Stacks, Button, Blinds, Showdown-Karten aus der HH
seats = {} # name -> seat
stacks = {} # name -> start stack
for mm in re.finditer(r'^Seat (\d+): (\S+) \(\$([0-9.]+) in chips\)', hh, re.M):
seats[mm.group(2)] = int(mm.group(1))
stacks[mm.group(2)] = float(mm.group(3))
mb = re.search(r'Seat #(\d+) is the button', hh)
button = int(mb.group(1)) if mb else None
mbb = re.search(r'\(\$([0-9.]+)/\$([0-9.]+)', hh)
sb, bb = (float(mbb.group(1)), float(mbb.group(2))) if mbb else (0.01, 0.02)
shown = {}
for mm in re.finditer(r'^(\S+): shows \[([^\]]+)\]', hh, re.M):
shown[mm.group(1)] = mm.group(2).split()
for mm in re.finditer(r'^Seat \d+: (\S+) showed \[([^\]]+)\]', hh, re.M):
shown.setdefault(mm.group(1), mm.group(2).split())
if HERO not in seats:
return None
return {"hid": hid, "hero_cards": hero_cards, "hh": hh, "decisions": decisions,
"prof": prof, "seats": seats, "stacks": stacks, "button": button,
"sb": sb, "bb": bb, "shown": shown}
def _seat_name(seats):
return {v: k for k, v in seats.items()}
def reconstruct(hand):
"""Laeuft die HH-Aktionen durch, baut vor jeder Hero-Aktion den Wire-Spot und paart ihn
mit der naechsten geloggten Entscheidung. Gibt Liste von (spot_dict, decision) zurueck."""
seats, stacks = hand["seats"], hand["stacks"]
bb = hand["bb"]
hero_seat = seats[HERO]
lines = hand["hh"].splitlines()
street = "PREFLOP"
street_contrib = Counter()
cum = Counter()
folded = set()
history = []
decisions = iter(hand["decisions"])
out = []
def snapshot(dec):
"""Baut die Wire-Anfrage fuer die aktuelle Hero-Entscheidung."""
board = dec["board"]
to_call = dec["to_call"]
hero_stack = round(stacks[HERO] - cum[HERO], 4)
legal = (["FOLD", "CALL"] + (["RAISE"] if hero_stack > to_call else [])) if to_call > 0 \
else ["CHECK"] + (["RAISE"] if hero_stack > 0 else [])
vils = []
for name, seat in seats.items():
if name == HERO:
continue
v = {"seat": seat, "stack": round(stacks[name] - cum[name], 4),
"folded": seat in folded}
if name in hand["prof"]:
v["profile"] = dict(hand["prof"][name])
vils.append(v)
req = {"variant": "NLHE", "bigBlind": bb, "seats": len(seats), "heroSeat": hero_seat,
"heroCards": _wire_cards(" ".join(hand["hero_cards"])),
"board": _board_dict(board), "street": dec["street"],
"pot": dec["pot"], "toCall": to_call, "heroStack": max(hero_stack, 0.0),
"legalActions": legal, "allowedSizes": [],
"villains": vils, "history": list(history),
"seed": (int(hand["hid"]) + STREETS.index(dec["street"]) * 7 + len(out)) & 0xFFFFFFFF}
if hand["button"]:
req["buttonSeat"] = hand["button"]
return req
for ln in lines:
if ln.startswith("*** FLOP"):
street = "FLOP"; street_contrib = Counter()
elif ln.startswith("*** TURN"):
street = "TURN"; street_contrib = Counter()
elif ln.startswith("*** RIVER"):
street = "RIVER"; street_contrib = Counter()
elif ln.startswith("*** SHOW DOWN") or ln.startswith("*** SUMMARY"):
break
m = ACT_RE.match(ln)
if not m:
continue
name, verb, amt, raise_to = m.group(1), m.group(2), m.group(3), m.group(4)
if name not in seats:
continue
seat = seats[name]
# Vor Heros Aktion: Spot bauen und mit der naechsten Entscheidung paaren
if name == HERO and verb in ("folds", "checks", "calls"):
dec = next(decisions, None)
if dec is not None and dec["street"] == street:
out.append((snapshot(dec), dec))
# Aktion auf den Zustand anwenden + history fortschreiben
if verb == "posts small blind":
street_contrib[seat] = float(amt); cum[seat] += float(amt)
history.append({"street": "PREFLOP", "seat": seat, "action": "POST_SB", "amount": float(amt)})
elif verb == "posts big blind":
street_contrib[seat] = float(amt); cum[seat] += float(amt)
history.append({"street": "PREFLOP", "seat": seat, "action": "POST_BB", "amount": float(amt)})
elif verb == "posts the ante":
cum[seat] += float(amt)
history.append({"street": "PREFLOP", "seat": seat, "action": "POST_ANTE", "amount": float(amt)})
elif verb == "folds":
folded.add(seat)
history.append({"street": street, "seat": seat, "action": "FOLD"})
elif verb == "checks":
history.append({"street": street, "seat": seat, "action": "CHECK"})
elif verb == "bets":
street_contrib[seat] = float(amt); cum[seat] += float(amt)
history.append({"street": street, "seat": seat, "action": "BET", "amount": float(amt)})
elif verb == "calls":
street_contrib[seat] += float(amt); cum[seat] += float(amt)
history.append({"street": street, "seat": seat, "action": "CALL", "amount": round(street_contrib[seat], 4)})
elif verb == "raises":
add = float(raise_to) - street_contrib[seat]
street_contrib[seat] = float(raise_to); cum[seat] += add
history.append({"street": street, "seat": seat, "action": "RAISE", "amount": float(raise_to)})
return out
# ---------------------------------------------------------------- Benчmark
def run(export_path):
md = open(export_path, encoding="utf-8").read()
blocks = re.split(r'^### Hand ', md, flags=re.M)[1:]
hands = [h for h in (parse_hand(b) for b in blocks) if h]
spots = [] # (hand, spot_dict, logged_decision)
for h in hands:
for spot, dec in reconstruct(h):
spots.append((h, spot, dec))
requests = [json.dumps(s[1]) for s in spots]
answers = decide.entscheide(requests)
# --- Masse sammeln ---
treue = 0; treue_bet = 0; n_bet = 0
foldbet = Counter(); callbet = Counter()
mdf_rows = []
bias = []
overfold_loss = 0.0; overcall_loss = 0.0
overfolds = []
for (h, spot, dec), ans in zip(spots, answers):
re_act = ans.get("action", "ABSTAIN")
re_eq = ans.get("equity")
logged = dec["action"]
# ABSTAIN zaehlt fuer die Treue als die Linie, die live gespielt wurde (Aussetzen -> Log)
if re_act == logged:
treue += 1
facing = dec["street"] != "PREFLOP" and dec["to_call"] > 0
if facing:
n_bet += 1
if re_act == logged:
treue_bet += 1
if re_act == "FOLD":
foldbet[dec["street"]] += 1
elif re_act == "CALL":
callbet[dec["street"]] += 1
# Ground Truth: lebende Gegner, die ihre Karten zeigen
board = dec["board"]
live_shown = []
sn = _seat_name(h["seats"])
for name, cs in h["shown"].items():
if name == HERO:
continue
cc = karten(cs)
if all(c not in karten(board) and c not in karten(" ".join(h["hero_cards"])) for c in cc):
live_shown.append(cs)
if live_shown:
te = equity_vs(" ".join(h["hero_cards"]), board, live_shown)
be = dec["to_call"] / (dec["pot"] + dec["to_call"])
ev_call = te * (dec["pot"] + dec["to_call"]) - dec["to_call"]
if re_eq is not None:
bias.append(re_eq - te)
if re_act == "FOLD" and ev_call > 1e-9:
overfold_loss += ev_call
overfolds.append((h["hid"], dec["street"], " ".join(board), dec["pot"],
dec["to_call"], round(te, 3), round(be, 3), re_eq,
" / ".join(" ".join(cs) for cs in live_shown), ev_call))
elif re_act == "CALL" and ev_call < -1e-9:
overcall_loss += -ev_call
mdf_rows.append((dec["street"], dec["to_call"] / (dec["pot"] + dec["to_call"])))
bb = hands[0]["bb"] if hands else 0.02
import statistics
return {
"n_hands": len(hands), "n_spots": len(spots), "n_bet": n_bet,
"treue": treue / len(spots) if spots else 0,
"treue_bet": treue_bet / n_bet if n_bet else 0,
"foldbet": dict(foldbet), "callbet": dict(callbet),
"bias_mean": statistics.mean(bias) if bias else 0.0,
"bias_n": len(bias),
"overfold_bb": overfold_loss / bb, "overcall_bb": overcall_loss / bb,
"overfolds": sorted(overfolds, key=lambda x: -x[9]),
"bb": bb,
}
def write_baseline(r, path, export_name):
import subprocess
try:
sha = subprocess.run(["git", "rev-parse", "--short", "HEAD"], cwd=os.path.dirname(path) or ".",
capture_output=True, text=True).stdout.strip() or "?"
except Exception:
sha = "?"
lines = [f"label {sha}+lokal", f"export {export_name}",
f"hands {r['n_hands']}", f"spots {r['n_spots']}", f"facing_bet {r['n_bet']}",
f"faithfulness {r['treue']:.3f}", f"faithfulness_bet {r['treue_bet']:.3f}"]
for s in ["FLOP", "TURN", "RIVER"]:
lines.append(f"foldbet_{s.lower()} {r['foldbet'].get(s,0)} {r['callbet'].get(s,0)}")
lines += [f"equity_bias {r['bias_mean']:.3f} n={r['bias_n']}",
f"overfold_bb {r['overfold_bb']:.1f}", f"overcall_bb {r['overcall_bb']:.1f}"]
open(path, "w", encoding="utf-8").write("\n".join(lines) + "\n")
def main():
path = os.environ.get("COINPOKER_EXPORT") or (sys.argv[1] if len(sys.argv) > 1 else None)
if not path or not os.path.exists(path):
print(f"Export nicht gefunden: {path}\nSetze COINPOKER_EXPORT=/pfad/zur/session.md (oder als Argument)")
sys.exit(2)
r = run(path)
print(f"=== Replay-Benchmark ({os.path.basename(path)}) ===")
print(f"Haende {r['n_hands']} | Hero-Entscheidungen rekonstruiert {r['n_spots']} | davon gegen Bet {r['n_bet']}")
print(f"TREUE (Re-Decision == Log): gesamt {100*r['treue']:.0f}% | gegen Bet {100*r['treue_bet']:.0f}%")
print()
print("FOLD gegen Bet je Street (Re-Decision der aktuellen Engine):")
for s in ["FLOP", "TURN", "RIVER"]:
f, c = r["foldbet"].get(s, 0), r["callbet"].get(s, 0)
if f + c:
print(f" {s:5}: fold {f}, call {c} -> {100*f/(f+c):.0f}% Fold-to-bet")
print()
print(f"EQUITY-BIAS (Engine - wahr) ueber {r['bias_n']} Ground-Truth-Spots: {r['bias_mean']:+.3f}"
f" (negativ = unterschaetzt -> Overfold-Wurzel)")
print(f"EV-VERLUST belegt: Overfold {r['overfold_bb']:.1f} bb | Overcall {r['overcall_bb']:.1f} bb")
print()
print("Belegte Overfolds (Gegner gezeigt, wahre Equity machte den Call +EV):")
for o in r["overfolds"][:12]:
hid, st, bd, pot, tc, te, be, eq, vil, ev = o
print(f" #{hid} {st:5} [{bd:14}] pot {pot:.2f} call {tc:.2f} | wahr {te:.2f} vs be {be:.2f} "
f"| Engine {eq} | Gegner {vil} | +EV weg {ev/r['bb']:.1f} bb")
base = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "benchmarks", "replay_baseline.txt")
ename = re.sub(r'_analyse\.md$|\.md$', '', os.path.basename(path))
write_baseline(r, base, ename)
print(f"\nBaseline geschrieben: {os.path.normpath(base)}")
return r
if __name__ == "__main__":
main()
+93
View File
@@ -0,0 +1,93 @@
//! Diagnose: woher kommt der Equity-Bias? Fuer jeden Wire-Spot von stdin wird die MODELLIERTE
//! Gegner-Range gedumpt und Heros Equity dagegen gemessen - einmal wie die Engine sie baut und
//! dann mit hochgedrehtem `bluff_share` je Continuation. Die Kurve zeigt, wie viel des Overfolds
//! an der (zu GTO-balancierten) Bluff-Annahme haengt.
//!
//! cat spots.ndjson | cargo run --release --example diag_bluff
use std::io::Read;
use rechner::card::Card;
use rechner::engine::range_combos::{as_ranges, combos};
use rechner::engine::range_filter::{range_filter, HandFilter};
use rechner::equity::monte_carlo::estimate;
use rechner::equity::query::Query;
use rechner::exploit::range_model::range_spec;
use rechner::exploit::range_spec::RangeSpec;
use rechner::game::Spot;
use rechner::rng::Rng;
const TRIALS: u32 = 40_000; // hohe Trials -> Standardfehler ~0.0025, der Bias ist sichtbar
fn specs(spot: &Spot, bluff: Option<f64>) -> Vec<RangeSpec> {
spot.live_villains()
.map(|v| {
let mut s = range_spec(spot, v);
if let Some(b) = bluff {
for c in s.continues.iter_mut() {
c.bluff_share = b;
}
}
s
})
.collect()
}
fn hero_share(spot: &Spot, bluff: Option<f64>) -> f64 {
let rules = spot.rules();
let specs = specs(spot, bluff);
let filters: Vec<HandFilter> = specs
.iter()
.map(|s| range_filter(s, rules, spot.variant, &spot.board))
.collect();
if filters.is_empty() {
return f64::NAN;
}
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();
let ranges = as_ranges(&filters, &lists);
let query = Query { rules, hero: &spot.hero_cards, board: &spot.board, villains: &ranges, trials: TRIALS };
estimate(&query, Rng::seeded(spot.seed)).map(|(e, _)| e.share).unwrap_or(f64::NAN)
}
fn fmt_cards(cs: &[Card]) -> String {
cs.iter().map(|c| format!("{c:?}")).collect::<Vec<_>>().join(" ")
}
fn diagnose(spot: &Spot) {
println!(
"--- {:?} [{}] | hero [{}] | pot {:.2} call {:.2} ---",
spot.street,
fmt_cards(&spot.board),
fmt_cards(&spot.hero_cards),
spot.pot,
spot.to_call
);
for v in spot.live_villains() {
let s = range_spec(spot, v);
let conts: Vec<String> = s
.continues
.iter()
.map(|c| format!("len{} >={:?} draws={} bluff={:.2}", c.board_len, c.min_made, c.draws_continue, c.bluff_share))
.collect();
println!(" villain seat {}: band [{:.2}..{:.2}] {}", v.seat, s.lo, s.hi, conts.join(" | "));
}
let base = hero_share(spot, None);
println!(" hero equity (Modell wie gebaut): {base:.3}");
print!(" bei bluff_share =");
for b in [0.15, 0.30, 0.45, 0.60, 0.75, 0.90] {
print!(" {:.2}->{:.3}", b, hero_share(spot, Some(b)));
}
println!();
}
fn main() {
let mut input = String::new();
std::io::stdin().read_to_string(&mut input).expect("stdin");
for line in input.lines().map(str::trim).filter(|l| !l.is_empty()) {
match rechner::json::parse(line).and_then(|v| rechner::wire::decode::decode(&v)) {
Ok(spot) => diagnose(&spot),
Err(e) => eprintln!("decode failed: {e} on: {}", &line[..line.len().min(80)]),
}
}
}
+161
View File
@@ -0,0 +1,161 @@
#!/usr/bin/env python3
"""All-in-EV: varianzreduzierte Hand-Bewertung. Ist im All-in vor dem River alles Geld drin, haengt
das Ergebnis nur noch am Board-Wurf. Die All-in-EV ersetzt diesen Wurf durch seinen Erwartungswert
(Equity gegen die aufgedeckten Gegnerkarten) - MITTELWERTTREU: der Erwartungswert bleibt, nur die
Varianz faellt. Das ist die klassische "all-in adjusted winnings" der Tracker, die Stufe-2-A/B etwa
60 % schneller signifikant macht (docs/notizen/BEFUND-stufe0-uebung.md: ~15k -> ~5,5k Haende/Arm).
Dieses Modul ist der KERN (reine Arithmetik + exakte Equity aus entscheiden/eval7). Die Extraktion
der Zutaten aus dem Hand-Text (Board zum All-in, Gegnerkarten, Einsaetze) steht getrennt in
`aus_text` - gated auf den eindeutigen Fall (Kopf-an-Kopf, ein Brett, All-in bis Showdown).
equity(hero, board_bis_allin, [villain]) -> Hero-Equity zum All-in-Zeitpunkt
ev_netto_bb(eq, netto_bei_sieg_bb, netto_bei_pleite_bb) -> der EV-Netto statt des realisierten
MITTELWERTTREUE (der Korrektheits-Beweis, tests/allin_ev_spec.py):
Die zwei Beine kommen aus BEOBACHTETEN Netto - `netto_bei_sieg` = was der Sieger real mitnahm
(post-Rake), `netto_bei_pleite` = was der Verlierer real verlor. Realisiert ist genau eines der
beiden; EV = eq*sieg + (1-eq)*pleite = E[realisiert | eq]. Ueber viele Haende ist der Mittelwert des
EV gleich dem des Realisierten (eq ist die wahre Gewinnwahrscheinlichkeit), mit kleinerer Varianz.
Ein nicht mittelwerttreuer EV waere ein STILLER VERLIERER - deshalb ist das die Kern-Spezifikation.
"""
import os
import sys
import zlib
_HIER = os.path.dirname(os.path.abspath(__file__))
_WURZEL = os.path.dirname(_HIER)
for _u in ("entscheiden",):
_q = os.path.join(_WURZEL, _u)
if os.path.isdir(_q) and _q not in sys.path:
sys.path.insert(0, _q)
import eval7
MC_LAEUFE = 6000 # Preflop-Monte-Carlo-Laeufe: ~100 ms, ~0,6 % 1-Sigma (eval7.score7, gc-aus)
def _seed(hero, villains):
"""Seed deterministisch AUS DEN KARTEN (crc32, prozess-stabil - nicht Pythons randomisiertes
hash()): dasselbe Matchup gibt dieselbe MC-Schaetzung, auch ueber A/B-Arme hinweg."""
teile = [str(c) for grp in (hero, *villains) for c in grp]
return zlib.crc32("|".join(teile).encode()) & 0xFFFFFFFF
def equity(hero, board_bis_allin, villains, laeufe=MC_LAEUFE):
"""Hero-Equity (2 Karten) auf dem Board ZUM ALL-IN-ZEITPUNKT gegen die bekannten Gegnerkarten.
3/4 Board-Karten -> exakte Enumeration der Runouts (990/44, Millisekunden). PREFLOP (0 Karten) ->
exakt waeren 1,7M Runouts, darum seed-deterministischer Monte-Carlo (eval7.equity_mc, unverzerrt,
~100 ms). 5 Karten -> deterministisch (Wurf schon gefallen). `villains`: Liste von je 2 Karten."""
if not hero or not villains:
return None
b = board_bis_allin or []
if len(b) == 0:
return eval7.equity_mc(hero, b, list(villains), laeufe=laeufe, seed=_seed(hero, villains))
return eval7.equity_vs(hero, b, list(villains))
def ev_netto_bb(eq, netto_bei_sieg_bb, netto_bei_pleite_bb):
"""Der mittelwerttreue EV-Netto in bb: eq*Sieg + (1-eq)*Pleite. Die beiden Netto sind beobachtet
(Sieger-Netto, Verlierer-Netto), also rake-exakt. `eq` in [0,1]."""
return eq * netto_bei_sieg_bb + (1.0 - eq) * netto_bei_pleite_bb
# Karten-Teilung des Boards: wie viele liegen je Street.
_STREET_KARTEN = {"PREFLOP": 0, "FLOP": 3, "TURN": 4, "RIVER": 5}
def board_bis(board, street):
"""Die ersten Karten des (End-)Boards, die zum All-in-Zeitpunkt (`street`) schon lagen.
board = flache Liste ['Tc','7h',...]; street in PREFLOP/FLOP/TURN/RIVER."""
n = _STREET_KARTEN.get(street, 0)
return list(board or [])[:n]
# ------------------------------------------------------- Extraktor aus der Hand-Rechnung
_STREET_NAME = ["PREFLOP", "FLOP", "TURN", "RIVER"]
def _allin_street(aktionen):
"""Street-Nummer (0..3) des All-in-Zugs in einer Aktionsliste [{street, aktion, betrag}], oder
None. Der frueheste All-in zaehlt (ab da laeuft das Brett nur noch aus)."""
s = None
for a in aktionen or []:
if isinstance(a, dict) and (a.get("aktion") or "").upper() in ("ALL_IN", "ALLIN"):
idx = _STREET_KARTEN_IDX.get(a.get("street"))
if idx is not None:
s = idx if s is None else min(s, idx)
return s
_STREET_KARTEN_IDX = {"PREFLOP": 0, "FLOP": 1, "TURN": 2, "RIVER": 3}
def aus_daten(daten, held):
"""All-in-EV EINER Hand aus der vollen Rechnung (ergebnis.rechnungen). GATED auf den eindeutigen
Fall - Kopf-an-Kopf, EIN Brett (kein RIT/Doppelbrett/EV-Chop/Bombpot), beide aufgedeckt, All-in
VOR dem River, kein Seiten-Pott. Sonst qualifiziert=False mit Grund (dann gilt netto_bb roh).
Preflop/Flop/Turn werden alle bepreist: Flop (990) und Turn (44) exakt, Preflop ueber seed-
deterministischen Monte-Carlo (~100 ms, eval7.equity_mc) statt der 1,7M-Runout-Enumeration.
-> {qualifiziert, grund, street, equity, netto_bb, netto_ev_bb, hero, villain, board_allin}.
netto_ev_bb ist mittelwerttreu: eq*Sieger-Netto + (1-eq)*Verlierer-Netto (beide beobachtet)."""
aus = {"qualifiziert": False, "grund": None, "street": None, "equity": None,
"netto_bb": None, "netto_ev_bb": None}
pl = daten.get("plaetze") or {}
bb = daten.get("bb")
if held not in pl or not bb:
aus["grund"] = "kein Held/kein bb"
return aus
hero = pl[held]
aus["netto_bb"] = round(hero["netto"] / bb, 4)
aus["netto_ev_bb"] = aus["netto_bb"] # Vorgabe: roh, bis eine Hand qualifiziert
m = daten.get("merker") or {}
if any(m.get(k) for k in ("rit", "doppelbrett", "ev_chop", "bomb_pot")):
aus["grund"] = "Sonderfall (rit/doppelbrett/evchop/bombpot)"
return aus
if len(pl) != 2:
aus["grund"] = "nicht heads-up"
return aus
villain = pl[next(n for n in pl if n != held)]
reveal = daten.get("reveal") or {}
hero_k = reveal.get(hero["sitz"]) or daten.get("hole")
vill_k = reveal.get(villain["sitz"])
if not hero_k or not vill_k or len(hero_k) != 2 or len(vill_k) != 2:
aus["grund"] = "nicht beide aufgedeckt"
return aus
paare = [x for x in (_allin_street(hero.get("aktionen")), _allin_street(villain.get("aktionen")))
if x is not None]
if not paare:
aus["grund"] = "kein All-in"
return aus
s = min(paare)
if s >= 3:
aus["grund"] = "All-in erst am River (keine Varianz)"
return aus
if abs(hero["einsatz"] - villain["einsatz"]) > 0.5 * bb:
aus["grund"] = "ungleiche Einsaetze (Seiten-Pott)"
return aus
board_s = board_bis(daten.get("board") or [], _STREET_NAME[s])
eq = equity(hero_k, board_s, [vill_k])
if eq is None:
aus["grund"] = "Equity nicht berechenbar"
return aus
sieger = max(hero["netto"], villain["netto"])
verlierer = min(hero["netto"], villain["netto"])
aus.update(qualifiziert=True, street=_STREET_NAME[s], equity=round(eq, 4),
netto_ev_bb=round(ev_netto_bb(eq, sieger, verlierer) / bb, 4),
hero=hero_k, villain=vill_k, board_allin=board_s)
return aus
def aus_text(text, held):
"""Alle fertigen Haende eines Logtexts, je Hand das aus_daten-Ergebnis (mit raum/hand). Nutzt
ergebnis.rechnungen - Platte nur dort, hier reine Weiterverarbeitung."""
import ergebnis
out = []
for r in ergebnis.rechnungen(text):
res = aus_daten(r["daten"], held)
res["raum"], res["hand"] = r["raum"], r["hand"]
out.append(res)
return out
+200
View File
@@ -0,0 +1,200 @@
#!/usr/bin/env python3
"""Einblick: aus den dauerhaft geloggten eigenen Zuegen (archiv/lauf/zuege.jsonl) die Spielweise der
Engine in Zahlen - je Street, je Vorflop-Position, je Postflop-Handklasse, und die Begruendungs-
Taxonomie des Kerns. Rein aus dem, was schon geloggt ist (lesen/handreview): kein neues Logging.
Anders als betrieb/review.py (Filter-Sucher, listet einzelne Haende) aggregiert dies - der
statistische Leak-Finder: "wie oft checkt die Engine welchen Drilling", "wie aggressiv am River",
"welche Vorflop-Position spielt zu breit". Mit `arm=` nur die Zuege eines A/B-Arms (Feld "arm",
im Lauf per COINPOKER_ARM gesetzt) - so lassen sich die Insights je Arm vergleichen.
Reine Funktionen (Platte nur in `laden`/`main`); Spezifikation: tests/einblick_spec.py.
python3 lesen/einblick.py [zuege.jsonl] [--arm A] [--tags 20]
"""
import collections
import json
import os
import sys
STREETS = ("PREFLOP", "FLOP", "TURN", "RIVER")
# Positionen, wie der Vorflop-Grund des Kerns sie nennt ("MP open", "SB vs limp", "BTN open").
POSITIONEN = {"UTG", "UTG1", "UTG2", "UTG3", "LJ", "HJ", "MP", "MP1", "MP2", "CO", "BTN", "SB", "BB"}
AGGRESSIV = {"BET", "RAISE"}
def nur_arm(zuege, arm):
"""Zuege eines A/B-Arms (Feld "arm"). `arm=None` -> alle; sonst exakt dieser Arm."""
if arm is None:
return list(zuege)
return [z for z in zuege if isinstance(z, dict) and z.get("arm") == arm]
def _quote(zaehler, aktionen):
n = sum(zaehler.values())
return (sum(zaehler.get(a, 0) for a in aktionen) / n) if n else 0.0
def aktionen_je_street(zuege):
"""Je Street: Zahl der Zuege, Aktionsverteilung, Aggressiv-Anteil (BET+RAISE), Fold-Anteil."""
je = {s: collections.Counter() for s in STREETS}
for z in zuege:
if not isinstance(z, dict):
continue
st, ak = z.get("street"), z.get("aktion")
if st in je and ak:
je[st][ak] += 1
out = []
for s in STREETS:
c = je[s]
n = sum(c.values())
if not n:
continue
out.append({"street": s, "zuege": n, "aktionen": dict(c),
"aggressiv": _quote(c, AGGRESSIV), "fold": _quote(c, {"FOLD"})})
return out
def position(grund):
"""Die Vorflop-Position aus dem Grund des Kerns (erstes Token), oder None. "MP open" -> "MP"."""
if not grund:
return None
teile = str(grund).strip().split()
return teile[0] if teile and teile[0] in POSITIONEN else None
def vorflop_je_position(zuege):
"""Vorflop je Position (aus dem Grund): Zuege, Aktionsverteilung, Aggressiv-/Fold-Anteil.
Die Zuege ohne erkennbare Position fallen weg (kein Rate-Spiel)."""
je = collections.defaultdict(collections.Counter)
for z in zuege:
if not isinstance(z, dict) or z.get("street") != "PREFLOP":
continue
p = position(z.get("grund"))
if p is None or not z.get("aktion"):
continue
je[p][z["aktion"]] += 1
out = []
for p in sorted(je):
c = je[p]
out.append({"position": p, "zuege": sum(c.values()), "aktionen": dict(c),
"aggressiv": _quote(c, AGGRESSIV), "fold": _quote(c, {"FOLD"})})
return out
def klassen_postflop(zuege):
"""Postflop je Handklasse (Feld "klasse": HighCard/Pair/TwoPair/...): Aktionsverteilung und
Aggressiv-Anteil. Das ist der Leak-Finder als Statistik - z. B. der Anteil gecheckter Drillinge."""
je = collections.defaultdict(collections.Counter)
for z in zuege:
if not isinstance(z, dict) or z.get("street") == "PREFLOP":
continue
k = z.get("klasse")
if not k or not z.get("aktion"):
continue
je[k][z["aktion"]] += 1
out = []
for k in sorted(je):
c = je[k]
out.append({"klasse": k, "zuege": sum(c.values()), "aktionen": dict(c),
"aggressiv": _quote(c, AGGRESSIV)})
return out
def _tag(grund):
"""Der Begruendungs-Kopf (vor '->', ',' oder ':'): "middle pair on wet board: equity .." -> die
Regel ohne die Zahlen. So faltet sich die Taxonomie des Kerns zu zaehlbaren Tags."""
if not grund:
return "(leer)"
kopf = str(grund).split("->")[0].split(",")[0].split(":")[0].strip()
return kopf[:48] if kopf else "(leer)"
def grund_tags(zuege, n=15):
"""Die haeufigsten Begruendungs-Koepfe des Kerns (welche Regel wie oft feuert)."""
c = collections.Counter(_tag(z.get("grund")) for z in zuege if isinstance(z, dict))
return [{"tag": t, "n": k} for t, k in c.most_common(n)]
def bericht(zuege, arm=None, tags=15):
"""Der ganze Einblick als JSON-faehiges Dict. Mit `arm` nur die Zuege dieses A/B-Arms."""
zuege = nur_arm(zuege, arm)
return {"arm": arm, "zuege": len(zuege),
"je_street": aktionen_je_street(zuege),
"je_position": vorflop_je_position(zuege),
"je_klasse": klassen_postflop(zuege),
"grund_tags": grund_tags(zuege, tags)}
def _p(x):
return f"{x * 100:4.0f} %"
def text(b):
"""Der Einblick als lesbarer Bericht."""
kopf = "=== Einblick: Spielweise aus den Zuegen ==="
if b["arm"] is not None:
kopf += f" (Arm {b['arm']})"
z = [kopf, f"Zuege: {b['zuege']}", ""]
z.append("je Street Zuege aggressiv fold")
for r in b["je_street"]:
z.append(f" {r['street']:<12} {r['zuege']:>5} {_p(r['aggressiv'])} {_p(r['fold'])}")
if b["je_position"]:
z += ["", "Vorflop je Position Zuege aggressiv fold"]
for r in b["je_position"]:
z.append(f" {r['position']:<17} {r['zuege']:>5} {_p(r['aggressiv'])} {_p(r['fold'])}")
if b["je_klasse"]:
z += ["", "Postflop je Handklasse Zuege aggressiv (Aktionen)"]
for r in b["je_klasse"]:
akt = " ".join(f"{k}:{v}" for k, v in sorted(r["aktionen"].items()))
z.append(f" {r['klasse']:<19} {r['zuege']:>5} {_p(r['aggressiv'])} {akt}")
z += ["", "haeufigste Begruendungen des Kerns:"]
for r in b["grund_tags"]:
z.append(f" {r['n']:>4} {r['tag']}")
return "\n".join(z) + "\n"
def laden(pfad):
"""Zug-Dicts aus einer jsonl-Datei; fehlende/kaputte Datei oder Zeile -> faellt weg."""
out = []
try:
with open(pfad, "r", 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):
out.append(d)
except OSError:
return []
return out
def main(argv):
pfad = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
"archiv", "lauf", "zuege.jsonl")
arm, tags = None, 15
i = 0
while i < len(argv):
if argv[i] == "--arm" and i + 1 < len(argv):
arm = argv[i + 1]
i += 2
elif argv[i] == "--tags" and i + 1 < len(argv):
try:
tags = int(argv[i + 1])
except ValueError:
pass
i += 2
else:
pfad = argv[i]
i += 1
print(text(bericht(laden(pfad), arm=arm, tags=tags)))
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
+21 -1
View File
@@ -188,6 +188,7 @@ def _rechnung(ereignisse):
zeit = None
hole = None
reveal = {}
brett = [] # flaches Hauptbrett ['Tc','7h',...] (nicht RIT/Doppelbrett) - fuer All-in-EV
gewinn = {}
zurueck = {}
erste_zeile = {} # name -> (chips, betAmout, caption) der ersten Sitzzeile
@@ -231,6 +232,12 @@ def _rechnung(ereignisse):
# Auch RIT-/Doppelbrett-Bretter zaehlen die Strasse mit, damit keine Zeile verloren geht.
for feld in ("dealerCards", "dealerCardsRit", "dealerCardsDoubleBoard"):
strasse = max(strasse, _strasse(d.get(feld)))
haupt = d.get("dealerCards")
if isinstance(haupt, dict): # das flache Hauptbrett, fuellstes Vorkommen gewinnt
flach = [k for s in ("FLOP", "TURN", "RIVER")
for k in (karte(c) for c in (haupt.get(s) or [])) if k]
if len(flach) >= len(brett):
brett = flach
if _gefuellt(d.get("dealerCardsRit")):
merker["rit"] = True
if _gefuellt(d.get("dealerCardsDoubleBoard")):
@@ -355,7 +362,7 @@ def _rechnung(ereignisse):
p["pruefung"] = "stapel"
p["abweichung"] = min(abw, key=abs)
return {"bb": bb, "sb": sb, "ante": ante or 0.0, "plaetze": plaetze, "reveal": reveal,
"hole": hole, "zeit": zeit, "merker": merker}, None
"hole": hole, "zeit": zeit, "merker": merker, "board": brett}, None
def _marke(x):
@@ -422,6 +429,19 @@ def haende_aller(text, uebersprungen=None):
return _eintraege(text, None, uebersprungen)
def rechnungen(text):
"""Die volle Rechnung je fertiger Hand (fuer lesen/allin_ev): Liste von {raum, hand, daten} mit
daten = {bb, sb, ante, plaetze, reveal, hole, board, merker, zeit}. Unfertige/unlesbare Haende
fallen weg. Anders als `haende` (fertige Hero-Zeilen) traegt dies Board, Reveal und alle Sitze."""
alle, _ = _gelesen(text)
out = []
for (raum, hand), ev in alle.items():
daten, _grund = _rechnung(ev)
if daten is not None:
out.append({"raum": raum, "hand": hand, "daten": daten})
return out
def aufgedeckt(text):
"""Siehe `lesen/aufdeckung.py` - dort definiert, hier weitergereicht (Zirkel vermieden)."""
return aufdeckung.aufgedeckt(text)
+135
View File
@@ -0,0 +1,135 @@
#!/usr/bin/env python3
"""Gegnersignal - aus dem persistenten Datensatz (lesen/gedaechtnis.py) ein kalibriertes Ausnutz-Signal.
PRODUZENT-Haelfte: rein-funktional, ohne Platte, ohne Rust. Liest NUR, was das Gedaechtnis hat und
der Client nicht liefert (`gezeigt`, `sizing`); die HUD-Zahlen (vpip/pfr/...) fasst es nie an.
Signal (alle Felder immer da, Zahlen sind float, Zaehler int):
n_gezeigt int Anzahl auswertbarer gezeigter Haende (Stichprobe)
n_sizing int Summe der Sizing-Eimer
konfidenz float 0..1, n/(n+K_GEZEIGT) - wie sehr das Handsignal zaehlt
konfidenz_sizing float 0..1, min(Sizing-Konfidenz, konfidenz) - sizing_tell braucht BEIDES
range_tightness float 0..1, 0.5 = zufaellige Haende; hoeher = staerkere Showdown-Haende.
Mittel der Handstaerke-Perzentile, zum Prior 0.5 hin geschrumpft
tightness_roh float ungeschrumpftes Mittel (None ohne Haende)
showdown_bluff_rate float 0..1 Anteil "Luft"-Haende (Perzentil < LUFT_GRENZE) unter den gezeigten,
zum Prior PRIOR_LUFT hin geschrumpft
sizing_tell float -1..1; >0: grosse Einsaetze = stark (Value-lastig), <0: grosse Einsaetze
= Bluff/Luft (Gegner over-bluffed mit Groesse). Konfidenz-geschrumpft
Handstaerke: Vorflop-Heuristik nach Chen (Hoechstkarte, Paar, gleiche Farbe, Luecke), die Punkte
je Kombination (alle 1326) in ein Perzentil gegen eine zufaellige Hand umgerechnet. Brett kennt das
Gedaechtnis nicht - "Luft" heisst daher: Vorflop-Handstaerke unter Zufallsmitte (schwach gehalten
bis zum Showdown). Das ist eine Naeherung, kein Equity-Wert.
Kalibrierung: Bayes-artige Schrumpfung w = n/(n+K). Ein Wert aus 2 Haenden zaehlt K/(2+K) weniger
als aus 10 (der Gedaechtnis-Deckel). `sizing_tell` ist eine Naeherung: Sizing-Eimer sind nicht
je Hand an `gezeigt` gebunden, also = Gross-minus-Klein-Anteil x Polaritaet der gezeigten Haende.
Spezifikation: tests/gegnersignal_spec.py.
"""
import itertools
K_GEZEIGT = 6.0 # Pseudo-Stichprobe: 6 Haende = halbes Vertrauen
K_SIZING = 8.0 # dito fuer Sizing-Zaehler
PRIOR_STRAFFHEIT = 0.5 # Zufall
PRIOR_LUFT = 0.30
LUFT_GRENZE = 0.35 # Perzentil darunter = Luft
KLEIN = ("mini",)
GROSS = ("pot", "over") # "halb" bleibt neutral
_RANG = {"2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, "T": 10, "J": 11,
"Q": 12, "K": 13, "A": 14}
_PUNKTE = {14: 10.0, 13: 8.0, 12: 7.0, 11: 6.0}
def _karte(k):
"""(rang, farbe) oder None. Nimmt 'Ah', 'Td', auch '10h'."""
s = str(k or "").strip()
if s.startswith("10"):
s = "T" + s[2:]
if len(s) != 2 or s[0].upper() not in _RANG:
return None
return _RANG[s[0].upper()], s[1].lower()
def _chen(a, b):
"""Chen-Punkte zweier (rang, farbe)-Karten."""
(r1, f1), (r2, f2) = sorted((a, b), key=lambda c: -c[0])
p = _PUNKTE.get(r1, r1 / 2.0)
if r1 == r2:
return max(5.0, 2 * p)
if f1 == f2:
p += 2
luecke = r1 - r2 - 1
p -= (0, 1, 2, 4)[luecke] if luecke < 4 else 5
if luecke <= 1 and r1 < 12:
p += 1
return p
_TABELLE = None
def _punkte_alle():
global _TABELLE
if _TABELLE is None:
deck = [(r, f) for r in range(2, 15) for f in "shdc"]
_TABELLE = sorted(_chen(a, b) for a, b in itertools.combinations(deck, 2))
return _TABELLE
def staerke(hand):
"""Perzentil 0..1 der Hand gegen eine zufaellige Hand (0.5 = Median); None bei ungueltiger Hand."""
if not isinstance(hand, (list, tuple)) or len(hand) != 2:
return None
a, b = _karte(hand[0]), _karte(hand[1])
if a is None or b is None or a == b:
return None
p = _chen(a, b)
alle = _punkte_alle()
unter = sum(1 for x in alle if x < p)
gleich = sum(1 for x in alle if x == p)
return (unter + 0.5 * gleich) / len(alle)
def _geschrumpft(wert, n, prior, k):
return (n * wert + k * prior) / (n + k)
def signal(eintrag):
"""Das Ausnutz-Signal (Dict, Felder s. Modulkopf) zu einem Gedaechtnis-Datensatz.
Leerer/None-Datensatz -> neutrale Werte (Prior), Konfidenz 0."""
eintrag = eintrag or {}
st = [s for s in (staerke(h) for h in eintrag.get("gezeigt") or []) if s is not None]
n = len(st)
konf = n / (n + K_GEZEIGT)
roh = sum(st) / n if n else None
tight = _geschrumpft(roh, n, PRIOR_STRAFFHEIT, K_GEZEIGT) if n else PRIOR_STRAFFHEIT
luft = sum(1 for s in st if s < LUFT_GRENZE)
bluff = _geschrumpft(luft / n, n, PRIOR_LUFT, K_GEZEIGT) if n else PRIOR_LUFT
z = {k: int(v) for k, v in (eintrag.get("sizing") or {}).items() if isinstance(v, (int, float)) and v > 0}
ns = sum(z.values())
tell, konf_s = 0.0, 0.0
if ns and n:
konf_s = min(ns / (ns + K_SIZING), konf)
schief = (sum(z.get(b, 0) for b in GROSS) - sum(z.get(b, 0) for b in KLEIN)) / ns
polar = 2.0 * (roh - 0.5)
tell = max(-1.0, min(1.0, schief * polar * konf_s))
return {"n_gezeigt": n, "n_sizing": ns, "konfidenz": konf, "konfidenz_sizing": konf_s,
"range_tightness": tight, "tightness_roh": roh,
"showdown_bluff_rate": bluff, "sizing_tell": tell}
def signale(speicher):
"""{kennung: signal} fuer ein ganzes Gedaechtnis (dict von gedaechtnis.laden)."""
return {str(k): signal(v) for k, v in (speicher or {}).items()}
if __name__ == "__main__":
import json
import sys
import gedaechtnis
print(json.dumps(signale(gedaechtnis.laden(sys.argv[1] if len(sys.argv) > 1 else "")), indent=1))
+224
View File
@@ -0,0 +1,224 @@
#!/usr/bin/env python3
"""Stufe 1 des synthetischen Gegner-Labors: die Gegner-POPULATION an echte Spielerdaten eichen.
Das Labor zieht seine Gegner aus vier Archetypen {fish, reg, nit, maniac}. Je Archetyp gilt der
"eingeschwungene HUD-Read" (src/sim/reads.rs, hier als ARCHETYPEN gespiegelt). Die Feldmischung
im Labor (fish 0.35 / reg 0.30 / nit 0.20 / maniac 0.15, src/sim/population.rs) ist ein
UNGEEICHTER Vorgabewert. Dieses Modul schaetzt die echte Mischung:
1. Je echtem Spieler der HUD-Vektor (vpip, pfr, foldToBet, aggression), alle 0..1.
2. Zuordnung zum naechsten Archetyp (euklidischer Abstand im HUD-Raum).
3. Zaehlen -> Gewichte (Summe 1); je Haufen Mittel und Streuung (Standardabweichung).
Fehlende Achsen: `aggression` liefert der Client NICHT (hud_stats kennt sie nicht, sie entsteht
erst aus Nach-Flop-Zuegen, profil.aggression). Fehlt eine Achse, zaehlt der Abstand nur ueber die
vorhandenen - der Vergleich bleibt fair, weil alle Archetypen dieselben Achsen verlieren.
Duenne Profile (profil.stichproben == DUENN, d. h. nach einer Handvoll Haende) fallen heraus.
Rein-funktional wie lesen/gedaechtnis.py; nur laden/speichern fassen die Platte an.
WOHER DIE ECHTEN DATEN KOMMEN (Stand: archiv/ hat KEINE fertige Spielerablage - kein
gedaechtnis.json, kein Stats-Verzeichnis je Gegner; das Gedaechtnis speichert HUD-Zahlen
ohnehin bewusst nicht). Echt vorhanden sind nur die hud_stats-Antworten in Mitschrieben, z. B.
archiv/rec-log.log (11 Spieler). Zwei Wege hierher:
* Log/Mitschrieb: python3 lesen/kalibrierung.py archiv/rec-log.log [weitere.log ...]
* JSON-Datei mit {kennung: {"vpip":..,"pfr":..,"foldToBet":..,"aggression":..}} (0..1):
python3 lesen/kalibrierung.py spieler.json
Schreibt archiv/population.json (mit -o anderer Pfad). Mehr Logs/Sitzungen -> bessere Eichung;
derselbe Spieler (Kennung) in mehreren Quellen zaehlt einmal, die spaetere Angabe gewinnt.
Spezifikation: tests/kalibrierung_spec.py.
"""
import json
import math
import os
import sys
_w = os.path.dirname(os.path.abspath(__file__))
if _w not in sys.path:
sys.path.insert(0, _w)
import profil
ACHSEN = ("vpip", "pfr", "foldToBet", "aggression")
# Gespiegelt aus src/sim/reads.rs - bei Aenderung dort hier nachziehen.
ARCHETYPEN = {
"fish": {"vpip": 0.93, "pfr": 0.01, "foldToBet": 0.40, "aggression": 0.08},
"reg": {"vpip": 0.31, "pfr": 0.13, "foldToBet": 0.72, "aggression": 0.25},
"nit": {"vpip": 0.06, "pfr": 0.03, "foldToBet": 0.82, "aggression": 0.12},
"maniac": {"vpip": 0.76, "pfr": 0.42, "foldToBet": 0.50, "aggression": 0.50},
}
NAMEN = tuple(ARCHETYPEN) # feste Reihenfolge; bei Gleichstand gewinnt der frühere
VORGABE_PFAD = os.path.join(os.path.dirname(_w), "archiv", "population.json")
def abstand(hud, archetyp):
"""Euklidischer Abstand von `hud` zum Archetyp, nur ueber die Achsen, die `hud` hat.
None, wenn gar keine Achse vorhanden ist."""
quadrate = [(float(hud[a]) - ARCHETYPEN[archetyp][a]) ** 2
for a in ACHSEN if hud.get(a) is not None]
return math.sqrt(sum(quadrate)) if quadrate else None
def klassifizieren(hud):
"""Name des naechsten Archetyps - None, wenn `hud` keine einzige Achse traegt."""
if not isinstance(hud, dict):
return None
beste = None
for name in NAMEN:
d = abstand(hud, name)
if d is None:
return None
if beste is None or d < beste[0]:
beste = (d, name)
return beste[1]
def _mittel_streuung(werte):
"""(Mittel, Standardabweichung) - Stichproben-Std (n-1); None bei weniger als 2 Werten."""
if len(werte) < 2:
return None
m = sum(werte) / len(werte)
return m, math.sqrt(sum((x - m) ** 2 for x in werte) / (len(werte) - 1))
def kalibrieren(spieler, quelle="unbekannt"):
"""Populationsspezifikation aus `spieler` = {kennung: HUD-Dict}. None ohne brauchbaren Spieler.
Schema (das die Rust-Seite liest):
{"n_players": int, "weights": {archetyp: anteil}, "spread_hud": {archetyp: {achse: std}},
"quelle": str}
`spread_hud` nur fuer Haufen mit mindestens 2 Spielern je Achse, fehlt ganz ohne solche Daten.
Das Mittel je Haufen steht bewusst nicht im Schema (es bleibt knapp); `haufen()` liefert es."""
zugeordnet = {n: [] for n in NAMEN}
for hud in (spieler or {}).values():
name = klassifizieren(hud)
if name is not None:
zugeordnet[name].append(hud)
n = sum(len(v) for v in zugeordnet.values())
if n == 0:
return None
spec = {"n_players": n,
"weights": {name: len(zugeordnet[name]) / n for name in NAMEN}}
spread = {}
for name in NAMEN:
je_achse = {}
for a in ACHSEN:
ms = _mittel_streuung([float(h[a]) for h in zugeordnet[name] if h.get(a) is not None])
if ms is not None:
je_achse[a] = ms[1]
if je_achse:
spread[name] = je_achse
if spread:
spec["spread_hud"] = spread
spec["quelle"] = quelle
return spec
def haufen(spieler):
"""{archetyp: {"n": int, "mittel": {achse: m}}} - beobachteter HUD-Mittelwert je Haufen."""
ergebnis = {n: {"n": 0, "mittel": {}} for n in NAMEN}
summen = {n: {} for n in NAMEN}
for hud in (spieler or {}).values():
name = klassifizieren(hud)
if name is None:
continue
ergebnis[name]["n"] += 1
for a in ACHSEN:
if hud.get(a) is not None:
s = summen[name].setdefault(a, [])
s.append(float(hud[a]))
for name in NAMEN:
ergebnis[name]["mittel"] = {a: sum(v) / len(v) for a, v in summen[name].items()}
return ergebnis
def aus_log(text):
"""{kennung: HUD} aus einem Mitschrieb mit hud_stats-Antworten (ueber lesen/profil.py).
Duenne Profile (nach einer Handvoll Haende, profil.stichproben == DUENN) bleiben draussen.
Nur die Achsen vpip/pfr/foldToBet; aggression fehlt (der Client liefert sie nicht)."""
dicke = profil.stichproben(text)
ergebnis = {}
for kennung, werte in profil.statistiken(text).items():
if dicke.get(kennung, profil.GLAUBHAFT) <= profil.DUENN:
continue
hud = {a: werte[a] for a in ACHSEN if a in werte}
if hud:
ergebnis[kennung] = hud
return ergebnis
def aus_json(daten):
"""{kennung: HUD} aus einer geladenen JSON-Struktur {kennung: {achse: wert}}; Muell faellt weg."""
ergebnis = {}
if not isinstance(daten, dict):
return ergebnis
for kennung, eintrag in daten.items():
if not isinstance(eintrag, dict):
continue
hud = {}
for a in ACHSEN:
try:
if eintrag.get(a) is not None:
hud[a] = min(max(float(eintrag[a]), 0.0), 1.0)
except (TypeError, ValueError):
pass
if hud:
ergebnis[str(kennung)] = hud
return ergebnis
def laden(pfad):
"""{kennung: HUD} aus einer Quelle - .json als Spielerablage, sonst als Mitschrieb.
Fehlende/kaputte Datei -> {}, nie eine Ausnahme."""
try:
if pfad.lower().endswith(".json"):
with open(pfad, "r", encoding="utf-8") as f:
return aus_json(json.load(f))
with open(pfad, "r", encoding="utf-8", errors="replace") as f:
return aus_log(f.read())
except (OSError, ValueError):
return {}
def speichern(pfad, spec):
"""Die Populationsspezifikation atomar schreiben (erst .tmp, dann os.replace)."""
os.makedirs(os.path.dirname(pfad) or ".", exist_ok=True)
tmp = pfad + ".tmp"
with open(tmp, "w", encoding="utf-8") as f:
json.dump(spec, f, ensure_ascii=False, indent=1)
os.replace(tmp, pfad)
def main(argv):
ziel = VORGABE_PFAD
quellen = []
i = 0
while i < len(argv):
if argv[i] == "-o" and i + 1 < len(argv):
ziel = argv[i + 1]
i += 2
else:
quellen.append(argv[i])
i += 1
if not quellen:
print(__doc__)
return 1
spieler = {}
for q in quellen:
spieler.update(laden(q))
spec = kalibrieren(spieler, quelle=", ".join(os.path.basename(q) for q in quellen))
if spec is None:
print("keine brauchbaren Spieler in den Quellen - nichts geschrieben")
return 1
speichern(ziel, spec)
print(json.dumps(spec, ensure_ascii=False, indent=1))
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
+292
View File
@@ -0,0 +1,292 @@
#!/usr/bin/env python3
"""Stufe 4 des synthetischen Gegner-Labors (die live-Hälfte): der Sim-to-Real-OUTCOME-Abgleich.
Das Labor sagt eine Kante voraus (Offense-EV des Zwillings-Tors, `src/sim/twin_gate.rs`: die Engine
beutet die GEZOGENE Population mit +43.95 bb/100 aus). Die Frage, die nur der Tisch beantwortet:
**Kommt diese Kante am echten Geld an?** Dieses Modul liest das, was der Live-Lauf tatsächlich
verdient hat (`archiv/lauf/haende.jsonl`, je eigener Hand `netto` in Chips und `bb` als Blindgröße),
rechnet daraus bb/100 mit 95-%-Intervall und hält es gegen die Sim-Vorhersage. Die Differenz ist der
Sim-to-Real-OUTCOME-Gap - die Zahl, die die Architektur „der eine unverzichtbare Live-Test" nennt.
Reine Funktionen (Platte nur in `main`/`laden`), wie `lesen/kalibrierung.py` und `lesen/gegnersignal.py`.
EHRLICHE GRENZE (warum der Gap kein reiner Strategiefehler ist):
Der Live-Lauf lief NICHT unter Laborbedingungen. Er enthält AoF-Push/Fold, Tischregeln, Klick-/UI-
Ausfälle (verstrichene Züge, AFK, Client-Neustarts), Rake, gemischte Stakes und vor allem die ECHTE
Population - nicht die synthetische. Der Gap misst also, wie viel der Sim-Kante bis zur Realität
überlebt, mit all diesen Confounds drin. Sie sauber zu trennen braucht den EINEN noch-live Rest: den
kontrollierten COINPOKER_KERN-An/Aus-Split (`betrieb/runner.py`, grober Schalter), bei dem derselbe
Farm mit und ohne Engine-Kern läuft und NUR die bb/100-Differenz zählt. Dafür fehlen Hände unter
beiden Bedingungen, nicht Code: der Abgleich hier ist gebaut und gefahren, er schärft sich mit Volumen.
Der A/B-Test selbst ist fertig gerechnet (`ab_vergleich`, CLI `--ab an.jsonl aus.jsonl`): er nimmt die
zwei Arm-Logs und liefert die signifikanz-geprüfte bb/100-Differenz. Was fehlt, ist allein das Laufen
des Live-Farms unter beiden Armen - eine reale, geldechte Spiel-Session über Zeit, die NICHT in dieser
Werkbank entsteht, sondern am Tisch. Das Werkzeug wartet darauf, nicht umgekehrt.
Spezifikation: tests/liveabgleich_spec.py.
"""
import json
import math
import os
import sys
# Gespiegelt aus dem Zwillings-Tor-Befund (src/sim/twin_gate.rs, Offense-Achse, Memory-Read gegen die
# gezogene Population). Bei Neumessung dort hier nachziehen. Das ist die Kante, die das Labor behauptet.
SIM_OFFENSE_BB100 = 43.95
_w = os.path.dirname(os.path.abspath(__file__))
VORGABE_PFAD = os.path.join(os.path.dirname(_w), "archiv", "lauf", "haende.jsonl")
Z = 1.959964 # 95-%-Quantil der Normalverteilung (zweiseitig)
def netto_bb(hand, ev=False):
"""Nettoergebnis einer Hand in Big Blinds, oder None wenn die Hand die Felder nicht trägt.
`netto` ist in Chips, `bb` die Blindgröße derselben Hand - netto/bb ist stakes-normiert, also
über verschiedene Stakes hinweg addierbar. Ein `netto_bb`-Feld im Log gewinnt, wenn vorhanden.
`ev=True`: wenn die Hand ein `netto_bb_ev` trägt (All-in-EV, lesen/allin_ev - varianzreduziert,
mittelwerttreu), gilt dieser statt des realisierten. Nur fürs A/B-Rauschdämpfen, nicht als
Buchhaltung. Ohne das Feld (keine qualifizierte All-in-Hand) fällt es auf netto_bb zurück."""
if not isinstance(hand, dict):
return None
if ev and isinstance(hand.get("netto_bb_ev"), (int, float)):
return float(hand["netto_bb_ev"])
if isinstance(hand.get("netto_bb"), (int, float)):
return float(hand["netto_bb"])
netto, bb = hand.get("netto"), hand.get("bb")
if isinstance(netto, (int, float)) and isinstance(bb, (int, float)) and bb:
return netto / bb
return None
def haende_lesen(text):
"""Liste der netto_bb-Werte aus einem jsonl-Mitschrieb; kaputte/unvollständige Zeilen fallen weg."""
werte = []
for zeile in text.splitlines():
zeile = zeile.strip()
if not zeile:
continue
try:
hand = json.loads(zeile)
except ValueError:
continue
v = netto_bb(hand)
if v is not None:
werte.append(v)
return werte
def bb_pro_100(werte):
"""{n, bb100, halb95, tief, hoch, netto_bb} aus netto_bb je Hand.
bb100 = Mittel je Hand * 100. Das 95-%-Intervall ist das der Winrate (Standardfehler des
Mittels * 100 * z), nicht das der einzelnen Hand - also „wie sicher ist die Kante", nicht „wie
streut eine Hand". Bei weniger als 2 Händen fehlt das Intervall (halb95/tief/hoch = None)."""
n = len(werte)
if n == 0:
return {"n": 0, "bb100": None, "halb95": None, "tief": None, "hoch": None, "netto_bb": 0.0}
summe = sum(werte)
mittel = summe / n
bb100 = mittel * 100.0
out = {"n": n, "bb100": bb100, "netto_bb": summe, "halb95": None, "tief": None, "hoch": None}
if n >= 2:
var = sum((x - mittel) ** 2 for x in werte) / (n - 1)
halb = Z * math.sqrt(var / n) * 100.0 # Halbbreite des 95-%-Intervalls in bb/100
out.update({"halb95": halb, "tief": bb100 - halb, "hoch": bb100 + halb})
return out
def abgleich(real, sim_bb100=SIM_OFFENSE_BB100):
"""Sim-Vorhersage gegen das reale Ergebnis `real` (aus bb_pro_100).
Liefert {sim, real, gap, deckt, urteil}:
gap = real.bb100 - sim_bb100 (negativ = die Kante kommt nicht an)
deckt = ob die Sim-Vorhersage im 95-%-Intervall des realen Ergebnisses liegt (None ohne Intervall)
urteil = kurzer Text. „zu dünn" wenn gar keine Hände; sonst passt/klafft je nach `deckt`."""
if real["n"] == 0:
return {"sim": sim_bb100, "real": None, "gap": None, "deckt": None,
"urteil": "zu dünn - keine Hände"}
gap = real["bb100"] - sim_bb100
deckt = None
if real["tief"] is not None:
deckt = real["tief"] <= sim_bb100 <= real["hoch"]
if deckt is None:
urteil = "eine Hand - kein Intervall, kein Urteil"
elif deckt:
urteil = "Sim-Vorhersage liegt im realen 95-%-Intervall - kein Widerspruch (bei dieser Streuung)"
else:
lage = "über" if gap < 0 else "unter"
urteil = (f"KLAFFT: die Sim-Kante liegt {lage} dem realen Intervall - "
f"{abs(gap):.0f} bb/100 Differenz kommen am Tisch nicht an")
return {"sim": sim_bb100, "real": real["bb100"], "gap": gap, "deckt": deckt, "urteil": urteil}
def ab_vergleich(an, aus):
"""Das kontrollierte A/B: Engine-Kern AN vs AUS (COINPOKER_KERN-Split). `an`/`aus` = netto_bb je
Hand des jeweiligen Arms (verschiedene Hände, also ZWEI-Stichproben, nicht gepaart).
Liefert {an, aus, diff, halb95, tief, hoch, signifikant, urteil}:
diff = an.bb100 - aus.bb100 (positiv = der Engine-Kern verdient mehr als die Baseline)
Intervall der Differenz: Welch-Standardfehler sqrt(se_an² + se_aus²), je se = halb95/z.
signifikant = ob 0 AUSSERHALB des 95-%-Intervalls der Differenz liegt (None ohne Intervall).
DAS ist der Test, der die Confounds wegpaart: beide Arme sehen denselben Farm, dieselben Stakes,
dieselbe echte Population - nur der Kern wechselt. Was bleibt, ist die reine Kern-Kante. Er braucht
nur Hände unter BEIDEN Armen; die Rechnung steht hier fertig und ist spezifiziert."""
a = bb_pro_100(an)
b = bb_pro_100(aus)
out = {"an": a, "aus": b, "diff": None, "halb95": None, "tief": None, "hoch": None,
"signifikant": None, "urteil": "zu dünn - beide Arme brauchen je ≥2 Hände"}
if a["n"] < 2 or b["n"] < 2:
return out
diff = a["bb100"] - b["bb100"]
se_an = a["halb95"] / Z # halb95 = z * se * 100 -> se (in bb/100) = halb95 / z
se_aus = b["halb95"] / Z
halb = Z * math.sqrt(se_an ** 2 + se_aus ** 2)
tief, hoch = diff - halb, diff + halb
sig = not (tief <= 0.0 <= hoch)
if not sig:
urteil = "kein signifikanter Unterschied - noch zu wenig Hände (das Intervall umfasst 0)"
elif diff > 0:
urteil = f"der Engine-Kern SCHLÄGT die Baseline signifikant: +{diff:.1f} bb/100 (95% {tief:+.1f}..{hoch:+.1f})"
else:
urteil = f"der Engine-Kern VERLIERT signifikant gegen die Baseline: {diff:.1f} bb/100 (95% {tief:+.1f}..{hoch:+.1f})"
out.update({"diff": diff, "halb95": halb, "tief": tief, "hoch": hoch,
"signifikant": sig, "urteil": urteil})
return out
def ab_aus_log(haende, feld="kern", an_wert=None, aus_wert=None, ev=False):
"""A/B aus EINEM gemischten Hand-Log, getrennt am Label `feld` (z. B. je Hand "kern":"an"/"aus").
`haende` = Liste von Hand-Dicts (nicht netto_bb-Werte - hier brauchen wir noch das Label). Ohne
gesetzte an_wert/aus_wert werden die zwei häufigsten Werte des Feldes als Arme genommen. So lässt
sich auch ein einziges haende.jsonl auswerten, wenn der Lauf die Hände je Arm markiert hat (sonst
trennt man die Arme über getrennte STATS_DIR-Ordner und nutzt `ab_vergleich` mit zwei Dateien).
`ev=True`: nutzt den varianzreduzierten All-in-EV (netto_bb_ev) statt des realisierten netto_bb -
gleicher Mittelwert, kleinere Streuung, also schneller signifikant (lesen/allin_ev)."""
marken = {}
for h in haende:
if isinstance(h, dict) and feld in h and netto_bb(h, ev) is not None:
marken.setdefault(h[feld], []).append(netto_bb(h, ev))
if an_wert is None or aus_wert is None:
haeufig = sorted(marken, key=lambda k: -len(marken[k]))
if len(haeufig) < 2:
return {"an": bb_pro_100([]), "aus": bb_pro_100([]), "diff": None, "halb95": None,
"tief": None, "hoch": None, "signifikant": None,
"urteil": f"nur ein Arm im Feld '{feld}' - getrennte Läufe/STATS_DIR nötig"}
an_wert = an_wert if an_wert is not None else haeufig[0]
aus_wert = aus_wert if aus_wert is not None else haeufig[1]
return ab_vergleich(marken.get(an_wert, []), marken.get(aus_wert, []))
def laden_haende(pfad):
"""Rohe Hand-Dicts aus einer jsonl-Datei (für `ab_aus_log`); kaputte Datei -> []."""
out = []
try:
with open(pfad, "r", 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):
out.append(d)
except OSError:
return []
return out
def laden(pfad):
"""netto_bb-Werte aus einer jsonl-Datei; fehlende/kaputte Datei -> [], nie eine Ausnahme."""
try:
with open(pfad, "r", encoding="utf-8", errors="replace") as f:
return haende_lesen(f.read())
except OSError:
return []
def _zeile(label, b):
iv = "" if b["halb95"] is None else f" 95%: {b['tief']:+.2f} bis {b['hoch']:+.2f}"
wr = "-" if b["bb100"] is None else f"{b['bb100']:+.2f}"
return f" {label:<10} n={b['n']:<4} bb/100 {wr}{iv}"
def _ab_main(an_pfad, aus_pfad):
"""CLI: das kontrollierte A/B aus zwei Arm-Logs (Kern an / Kern aus)."""
erg = ab_vergleich(laden(an_pfad), laden(aus_pfad))
print("=== Stufe 4: kontrolliertes A/B (COINPOKER_KERN an vs aus) ===")
print(f"AN : {an_pfad}")
print(f"AUS: {aus_pfad}\n")
print(_zeile("Kern AN", erg["an"]))
print(_zeile("Kern AUS", erg["aus"]))
if erg["diff"] is not None:
print(f"\nDifferenz (an - aus): {erg['diff']:+.2f} bb/100")
print(f"Urteil: {erg['urteil']}")
return 0
def main(argv):
if argv and argv[0] == "--ab":
if len(argv) < 3:
print("Nutzung: liveabgleich.py --ab <kern-an.jsonl> <kern-aus.jsonl>")
return 1
return _ab_main(argv[1], argv[2])
if argv and argv[0] == "--ab-log":
if len(argv) < 2:
print("Nutzung: liveabgleich.py --ab-log <gemischt.jsonl> [feld] [--ev]")
return 1
ev = "--ev" in argv[2:] # All-in-EV (varianzreduziert) statt realisiert
rest = [a for a in argv[2:] if a != "--ev"]
feld = rest[0] if rest else "kern"
erg = ab_aus_log(laden_haende(argv[1]), feld=feld, ev=ev)
print("=== Stufe 4: A/B aus einem markierten Log ===")
print(f"Quelle: {argv[1]} (Feld '{feld}'{', All-in-EV' if ev else ''})\n")
print(_zeile("Kern AN", erg["an"]))
print(_zeile("Kern AUS", erg["aus"]))
if erg["diff"] is not None:
print(f"\nDifferenz (an - aus): {erg['diff']:+.2f} bb/100")
print(f"Urteil: {erg['urteil']}")
return 0
pfad = VORGABE_PFAD
sim = SIM_OFFENSE_BB100
i = 0
while i < len(argv):
if argv[i] == "--sim" and i + 1 < len(argv):
try:
sim = float(argv[i + 1])
except ValueError:
pass
i += 2
else:
pfad = argv[i]
i += 1
werte = laden(pfad)
real = bb_pro_100(werte)
erg = abgleich(real, sim)
print("=== Stufe 4 (live-Hälfte): Sim-to-Real-OUTCOME-Abgleich ===")
print(f"Quelle: {pfad}\n")
print("REAL - was der Live-Lauf verdient hat:")
print(_zeile("gesamt", real))
print(f"\nSIM - was das Labor vorhersagt (Offense gegen die gezogene Population): {sim:+.2f} bb/100")
if erg["gap"] is not None:
print(f"\nGAP (real - sim): {erg['gap']:+.2f} bb/100")
print(f"Urteil: {erg['urteil']}")
print("\n(Der Gap enthält Population-, Rake- und Betriebs-Confounds; sie trennt erst der")
print(" kontrollierte COINPOKER_KERN-An/Aus-Split - der eine noch-live Rest. Mehr Hände schärfen.)")
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
+41
View File
@@ -0,0 +1,41 @@
//! Stufe 3 of the synthetic lab: how much does an ADAPTING opponent change the engine's edge?
//!
//! For each drawn opponent, play the engine heads-up (inferring the opponent from session memory, its
//! real exploitation path) over the SAME deals twice: once with the opponent held static (the Stufe-0
//! memory baseline), once with the opponent adapting its ruleset to the hero's observed aggression.
//! The paired per-deal difference is the bb/100 the engine's *stationary* read is worth against a
//! *moving* target — the first measurement of mind-game pressure in this work.
//!
//! Run: `cargo run --release --bin adaptive_gap`.
use rechner::sim::adaptive::{adaptive_effect, Adapt, AdaptReport};
use rechner::sim::population::Population;
const SEED: u64 = 0x5EED_0001;
const OPPONENTS: usize = 48;
const DEALS: u32 = 400;
fn line(r: &AdaptReport) {
let decisive = r.delta_bb_per_100.abs() - r.ci95 > 0.0;
println!(
" {:8} static {:+7.2} adaptiv {:+7.2} -> DELTA {:+7.2} bb/100 (paired +-{:.2}, anytime +-{:.2}) {}",
r.style,
r.static_bb_per_100,
r.adaptive_bb_per_100,
r.delta_bb_per_100,
r.ci95,
r.anytime_ci95,
if decisive { "SIGNIFIKANT" } else { "n.s." },
);
}
fn main() {
let pop = Population::micro();
println!("=== Stufe 3: adaptive Gegner — was kostet der stationaere Read gegen ein bewegliches Ziel? ===");
println!("{OPPONENTS} Gegner x {DEALS} Austeilungen, heads-up, Engine erschliesst via Memory.");
println!("DELTA = adaptiv - statisch (negativ = die Engine blutet gegen die Reaktion).\n");
line(&adaptive_effect(&pop, OPPONENTS, DEALS, SEED, Adapt::Tighten));
line(&adaptive_effect(&pop, OPPONENTS, DEALS, SEED, Adapt::Loosen));
line(&adaptive_effect(&pop, OPPONENTS, DEALS, SEED, Adapt::Model));
}
+72
View File
@@ -0,0 +1,72 @@
//! Is the benchmark's variance reduction world-class, or just a fixed beta=1 guess?
//!
//! The ladder stores, per deal, hero's net result corrected by a luck control signal: `net - luck`
//! (`sim::session`). That is a control variate with coefficient FIXED at beta = 1. Because the luck
//! signal has expectation ~0, `net - beta*luck` is unbiased for EVERY beta, and the
//! variance-minimising coefficient is beta* = Cov(net, luck) / Var(luck) -- not necessarily 1.
//! AIVAT learns beta* by cross-fitting (`sim::aivat`), so it never beats the raw estimator by less
//! and, when beta* != 1, beats the hard-coded beta = 1 too.
//!
//! This binary MEASURES the gap on real sim data, for the high-variance scenarios the ladder cares
//! about, before any estimator change. Same mean across all three estimators = unbiased; the CI
//! ratios say how much, if anything, cross-fitting buys over the current bench.
//!
//! Run: `cargo run --release --bin aivat_bench`.
use rechner::sim::aivat::{control_variate, raw};
use rechner::sim::opponent::Opponent;
use rechner::sim::reader::Style;
use rechner::sim::session::{deal_net_and_luck, ReadMode, Setup};
const SEED: u64 = 0x5EED_0001;
const STACK_BB: f64 = 100.0;
const FOLDS: usize = 10;
fn setup(players: u8, opponent: Opponent, deals: u32, read: ReadMode) -> Setup {
Setup { players, opponent, deals, stack_bb: STACK_BB, seed: SEED, read }
}
/// A single-run win-rate estimate three ways. `beta = 0` is the raw mean; `beta = 1` is the ladder's
/// current luck-corrected sample; `beta*` is the cross-fitted AIVAT control variate. Units: bb/100.
fn report(name: &str, s: &Setup) {
let (net, luck) = deal_net_and_luck(s);
let n = net.len();
// beta = 0: raw net, no correction.
let (m0, h0) = raw(&net);
// beta = 1: the current ladder sample net - luck.
let corrected: Vec<f64> = net.iter().zip(&luck).map(|(y, c)| y - c).collect();
let (m1, h1) = raw(&corrected);
// beta*: cross-fitted optimal coefficient (AIVAT). mu_c = 0 (luck is mean-zero by construction).
let (ms, hs) = control_variate(&net, &luck, 0.0, FOLDS).unwrap();
// Empirical beta* on the whole sample, for the record.
let mc = luck.iter().sum::<f64>() / n as f64;
let my = net.iter().sum::<f64>() / n as f64;
let cov = net.iter().zip(&luck).map(|(y, c)| (y - my) * (c - mc)).sum::<f64>() / n as f64;
let varc = luck.iter().map(|c| (c - mc).powi(2)).sum::<f64>() / n as f64;
let beta_star = if varc > 1e-12 { cov / varc } else { 0.0 };
println!("\n{name} ({n} deals)");
println!(" mean bb/100 raw(b=0) {:+7.2} bench(b=1) {:+7.2} aivat(b*) {:+7.2}", 100.0 * m0, 100.0 * m1, 100.0 * ms);
println!(" ci95 bb/100 raw(b=0) {:7.2} bench(b=1) {:7.2} aivat(b*) {:7.2}", 100.0 * h0, 100.0 * h1, 100.0 * hs);
println!(" beta* = {beta_star:.3} (bench assumes 1.000)");
println!(
" variance factor aivat/raw {:.2}x aivat/bench {:.2}x bench/raw {:.2}x",
(h0 / hs).powi(2),
(h1 / hs).powi(2),
(h0 / h1).powi(2)
);
let drop = 100.0 * (1.0 - hs / h1);
println!(" AIVAT over current bench: CI {drop:+.1} % (positive = narrower)");
}
fn main() {
println!("=== Benchmark estimator audit: fixed beta=1 vs cross-fitted beta* (AIVAT) ===");
println!("Unbiased iff the three means agree within a CI. Narrower aivat CI = world-class upgrade.");
report("heads-up gto", &setup(2, Opponent::Reader(Style::Gto), 3000, ReadMode::Oracle));
report("heads-up gto-small", &setup(2, Opponent::Reader(Style::GtoSmall), 3000, ReadMode::Oracle));
report("heads-up fish", &setup(2, Opponent::Reader(Style::Fish), 1000, ReadMode::Oracle));
report("heads-up calling station", &setup(2, Opponent::CallingStation, 1000, ReadMode::Oracle));
report("heads-up reg", &setup(2, Opponent::Reader(Style::Reg), 1000, ReadMode::Oracle));
}
+38
View File
@@ -0,0 +1,38 @@
//! Per-archetype Blind vs Memory EV: does acting on the (station) read HELP or HURT each archetype?
//! This decides whether softening the binary CallingStation trust is safe. If Memory ≥ Blind the read
//! is a net gain (keep trust high); if Memory < Blind the station exploit is already costing and
//! softening helps. Prints the gap = Memory − Blind.
//!
//! Run: `cargo run --release --bin arch_read [deals]` (default 4000; fast threshold styles only —
//! gto/gto-small run a per-decision solver and are covered by the twin gate).
use rechner::exploit::style::classify;
use rechner::sim::opponent::Opponent;
use rechner::sim::reader::Style;
use rechner::sim::reads::opponent_profile;
use rechner::sim::session::{measure, ReadMode, Setup};
const SEED: u64 = 0x5EED_0001;
const STACK_BB: f64 = 100.0;
fn ev(style: Style, read: ReadMode, deals: u32) -> f64 {
let setup =
Setup { players: 2, opponent: Opponent::Reader(style), deals, stack_bb: STACK_BB, seed: SEED, read };
measure(&setup).bb_per_100
}
fn main() {
let deals: u32 = std::env::args().nth(1).and_then(|s| s.parse().ok()).unwrap_or(4000);
println!("=== Archetyp Blind vs Memory, {deals} Austeilungen ===");
println!("gap = Memory - Blind (>0: Read nuetzt, <0: Station-Exploit kostet schon)\n");
println!(" {:<8} {:>9} {:>9} {:>9} {}", "style", "blind", "memory", "gap", "oracle-classify");
for style in [Style::Fish, Style::Reg, Style::Nit, Style::Maniac] {
let blind = ev(style, ReadMode::Blind, deals);
let memory = ev(style, ReadMode::Memory, deals);
let oc = opponent_profile(Opponent::Reader(style)).map(|p| format!("{:?}", classify(&p)));
println!(
" {:<8} {:>+9.2} {:>+9.2} {:>+9.2} {}",
style.name(), blind, memory, memory - blind, oc.unwrap_or_else(|| "-".into())
);
}
}
+270
View File
@@ -0,0 +1,270 @@
//! Diagnose WHERE the engine bleeds against the near-GTO opponent (`sim::gto`) heads-up.
//!
//! Replays the `heads-up gto` benchmark scenario deal for deal (same seed mixing, deal, hand seed,
//! oracle read, luck correction) but on the traced table path, so every hand carries a `Dec` per
//! hero decision. Attributes each hand's luck-corrected net to the street of hero's terminal
//! decision, the terminal action, and hero's position. The per-bucket contributions sum to the
//! scenario's bb/100 (−38 territory), so the table reads as "this many bb/100 come from here".
//!
//! Run: `cargo run --release --bin diag_gto`.
use rechner::game::{Choice, Street};
use rechner::rng::Rng;
use rechner::sim::opponent::Opponent;
use rechner::sim::reader::Style;
use rechner::sim::table::{deal, play_hand_traced, HandRead, HandSetup, TableCost};
use std::collections::BTreeMap;
const SEED: u64 = 0x5EED_0001;
const STACK_BB: f64 = 100.0;
const PLAYERS: usize = 2;
/// Deal count (argv 1, default 1000) and opponent (argv 2: "gto" default, or "gto-small").
fn config() -> (u32, Opponent, &'static str) {
let args: Vec<String> = std::env::args().collect();
let deals = args.get(1).and_then(|s| s.parse().ok()).unwrap_or(1000);
let (opponent, name) = match args.get(2).map(String::as_str) {
Some("gto-small") => (Opponent::Reader(Style::GtoSmall), "gto-small"),
_ => (Opponent::Reader(Style::Gto), "gto"),
};
(deals, opponent, name)
}
/// `session::mix`, reproduced (it is private there).
fn mix(seed: u64, n: u64) -> u64 {
Rng::seeded(seed ^ n.wrapping_mul(0xD1B5_4A32_D192_ED03)).next_u64().0
}
fn street_name(s: Street) -> &'static str {
match s {
Street::Preflop => "preflop",
Street::Flop => "flop",
Street::Turn => "turn",
Street::River => "river",
}
}
/// The action kind of a terminal hero decision, folded over its size.
fn choice_name(c: Choice) -> &'static str {
match c {
Choice::Fold => "fold",
Choice::Check => "check",
Choice::Call => "call",
Choice::Raise { .. } => "raise/bet",
Choice::Abstain => "abstain",
}
}
#[derive(Default, Clone, Copy)]
struct Agg {
hands: u32,
net: f64, // sum of luck-corrected net, bb
}
impl Agg {
fn add(&mut self, net: f64) {
self.hands += 1;
self.net += net;
}
}
/// bb/100 contribution of a bucket: `100 * sum(net) / total_hands`. These sum to the scenario rate.
fn contrib(net: f64, total_hands: u32) -> f64 {
100.0 * net / total_hands.max(1) as f64
}
fn main() {
let (deals, opponent, opp_name) = config();
let mut total = Agg::default();
// Attribution buckets.
let mut by_terminal: BTreeMap<(Street, &'static str), Agg> = BTreeMap::new();
let mut by_position: BTreeMap<u8, Agg> = BTreeMap::new();
let mut by_street_reached: BTreeMap<Street, Agg> = BTreeMap::new();
// Per-street action frequency over ALL hero decisions (not just terminal).
let mut action_counts: BTreeMap<(Street, &'static str), u32> = BTreeMap::new();
// Per-street: hands whose terminal decision is on that street, split value won vs lost.
let mut pos_terminal: BTreeMap<(u8, Street, &'static str), Agg> = BTreeMap::new();
// Drill into the dominant leak: river calls bucketed by the equity the engine stated for the call.
let mut eq_bands: BTreeMap<&'static str, Agg> = BTreeMap::new();
// Over-fold test: when hero FACES a bet (to_call>0), does it fold despite the odds to continue?
// break_even be = to_call/pot (pot already includes the bet). A fold with equity >= be is an
// over-fold by the model's own equity. Slots: [faced, folds, folds_with_odds, folds_eq_unknown].
let mut facing: BTreeMap<Street, [u32; 4]> = BTreeMap::new();
// Net of terminal-fold hands that faced a bet, split by whether hero had the odds (eq>=be).
let mut overfold_net: BTreeMap<(Street, &'static str), Agg> = BTreeMap::new();
// Example losing river calls (what is hero actually bluff-catching with?).
let mut river_call_examples: Vec<String> = Vec::new();
for d in 0..deals {
let (cards, _) = deal(PLAYERS, Rng::seeded(mix(SEED, d as u64)));
for hero_seat in 1..=PLAYERS as u8 {
let hand = HandSetup {
deal: &cards,
hero_seat,
opponent,
stack_bb: STACK_BB,
seed: mix(SEED ^ 0xA5A5, (d as u64) << 8 | hero_seat as u64),
read: HandRead::Oracle,
};
let (res, trace) = play_hand_traced(&hand, TableCost::FREE);
let net = res.hero_net - res.luck; // luck-corrected, matches the ladder
total.add(net);
by_position.entry(hero_seat).or_default().add(net);
// Every hero decision's action, by street (aggression distribution) + fold discipline
// when facing a bet.
for dec in &trace {
*action_counts.entry((dec.street, choice_name(dec.choice))).or_default() += 1;
if dec.to_call > 0.0 && dec.pot > 0.0 {
let be = dec.to_call / dec.pot;
let slot = facing.entry(dec.street).or_insert([0; 4]);
slot[0] += 1;
if matches!(dec.choice, Choice::Fold) {
slot[1] += 1;
match dec.equity {
Some(e) if e >= be => slot[2] += 1,
Some(_) => {}
None => slot[3] += 1,
}
}
}
}
// Deepest street hero reached (acted on at all).
let reached = trace.iter().map(|d| d.street).max().unwrap_or(Street::Preflop);
by_street_reached.entry(reached).or_default().add(net);
// Terminal decision: the last Dec of the hand.
if let Some(last) = trace.last() {
let key = (last.street, choice_name(last.choice));
by_terminal.entry(key).or_default().add(net);
pos_terminal.entry((hero_seat, last.street, choice_name(last.choice))).or_default().add(net);
if last.street == Street::River && matches!(last.choice, Choice::Call) {
let band = match last.equity {
Some(e) if e < 0.35 => "eq <0.35",
Some(e) if e < 0.45 => "eq 0.35-0.45",
Some(e) if e < 0.55 => "eq 0.45-0.55",
Some(_) => "eq >=0.55",
None => "eq n/a",
};
eq_bands.entry(band).or_default().add(net);
// Dump a handful of losing marginal river calls to see the bluff-catcher.
if net < -2.0 && river_call_examples.len() < 16 {
let hole = cards.holes[hero_seat as usize - 1];
let holes = format!("{} {}", hole[0].short(), hole[1].short());
let board: Vec<String> = cards.board.iter().map(|c| c.short()).collect();
river_call_examples.push(format!(
" {:<7} board {:<17} pot {:>5.1} call {:>4.1} eq {:>5.2} net {:>+6.1}",
holes, board.join(" "), last.pot, last.to_call,
last.equity.unwrap_or(f64::NAN), net
));
}
}
if matches!(last.choice, Choice::Fold) && last.to_call > 0.0 && last.pot > 0.0 {
let be = last.to_call / last.pot;
let tag = match last.equity {
Some(e) if e >= be => "had odds (eq>=be)",
Some(_) => "no odds (eq<be)",
None => "eq n/a (preflop chart)",
};
overfold_net.entry((last.street, tag)).or_default().add(net);
}
}
}
}
let h = total.hands;
println!("=== heads-up {} diagnosis: {} hands, overall {:+.2} bb/100 ===\n", opp_name, h, contrib(total.net, h));
println!("-- by hero position (seat 1 = button/SB, seat 2 = BB) --");
for (seat, a) in &by_position {
let role = if *seat == 1 { "button/SB" } else { "BB" };
println!(
" seat {} {:<10} {:+8.2} bb/100 {:>5} hands {:+7.3} bb/hand",
seat, role, contrib(a.net, h), a.hands, a.net / a.hands.max(1) as f64
);
}
println!("\n-- by deepest street hero reached --");
for (s, a) in &by_street_reached {
println!(
" {:<8} {:+8.2} bb/100 {:>5} hands {:+7.3} bb/hand",
street_name(*s), contrib(a.net, h), a.hands, a.net / a.hands.max(1) as f64
);
}
println!("\n-- by terminal decision (street x action of hero's LAST choice) --");
println!(" {:<18} {:>10} {:>6} {:>10} {:>10}", "bucket", "bb/100", "hands", "bb/hand", "share%");
let mut rows: Vec<_> = by_terminal.iter().collect();
rows.sort_by(|a, b| a.1.net.partial_cmp(&b.1.net).unwrap());
for ((s, act), a) in rows {
println!(
" {:<18} {:>+10.2} {:>6} {:>+10.3} {:>9.1}%",
format!("{} {}", street_name(*s), act),
contrib(a.net, h), a.hands, a.net / a.hands.max(1) as f64,
100.0 * a.hands as f64 / h as f64
);
}
println!("\n-- terminal decision split by position --");
println!(" {:<28} {:>10} {:>6} {:>10}", "pos / bucket", "bb/100", "hands", "bb/hand");
let mut prows: Vec<_> = pos_terminal.iter().collect();
prows.sort_by(|a, b| a.1.net.partial_cmp(&b.1.net).unwrap());
for ((seat, s, act), a) in prows.iter().take(12) {
let role = if *seat == 1 { "BTN" } else { "BB" };
println!(
" {:<28} {:>+10.2} {:>6} {:>+10.3}",
format!("{} {} {}", role, street_name(*s), act),
contrib(a.net, h), a.hands, a.net / a.hands.max(1) as f64
);
}
// Drill: the dominant leak. River calls bucketed by the equity the engine stated for the call.
println!("\n-- river CALL leak: by engine-stated equity at the call --");
println!(" {:<14} {:>10} {:>6} {:>10}", "equity band", "bb/100", "hands", "bb/hand");
for (band, a) in &eq_bands {
println!(
" {:<14} {:>+10.2} {:>6} {:>+10.3}",
band, contrib(a.net, h), a.hands, a.net / a.hands.max(1) as f64
);
}
println!("\n-- example losing river calls (hero's bluff-catcher) --");
for line in &river_call_examples {
println!("{line}");
}
println!("\n-- facing a bet: fold discipline per street (be = to_call/pot) --");
println!(" {:<8} {:>7} {:>7} {:>16} {:>10}", "street", "faced", "folds", "folds w/ odds", "fold%");
for (s, c) in &facing {
println!(
" {:<8} {:>7} {:>7} {:>16} {:>9.1}%",
street_name(*s), c[0], c[1], c[2], 100.0 * c[1] as f64 / c[0].max(1) as f64
);
}
println!("\n-- terminal folds that faced a bet: net by whether hero had the odds --");
println!(" {:<30} {:>10} {:>6} {:>10}", "street / odds", "bb/100", "hands", "bb/hand");
let mut ofrows: Vec<_> = overfold_net.iter().collect();
ofrows.sort_by(|a, b| a.1.net.partial_cmp(&b.1.net).unwrap());
for ((s, tag), a) in ofrows {
println!(
" {:<30} {:>+10.2} {:>6} {:>+10.3}",
format!("{} {}", street_name(*s), tag), contrib(a.net, h), a.hands, a.net / a.hands.max(1) as f64
);
}
println!("\n-- hero action frequency per street (all decisions) --");
let mut street_totals: BTreeMap<Street, u32> = BTreeMap::new();
for ((s, _), c) in &action_counts {
*street_totals.entry(*s).or_default() += c;
}
for ((s, act), c) in &action_counts {
let tot = street_totals[s].max(1);
println!(
" {:<8} {:<10} {:>6} {:>5.1}%",
street_name(*s), act, c, 100.0 * *c as f64 / tot as f64
);
}
}
+195
View File
@@ -0,0 +1,195 @@
//! Diagnose WHERE the engine bleeds against its NEMESIS — the sticky low-bluff calling station the
//! CMA-ES found (`sim::optimize::worst_case_opponent`, −414 bb/100). The nemesis ruleset is a fixed
//! `Rules`: call_margin 0.215 (calls very wide), bluff 0.068 (almost never bluffs), size 0.441. It
//! rarely folds and rarely bluffs, so barreling into it has no fold equity — the engine should check
//! back / give up, not bluff.
//!
//! Mirrors `diag_gto`'s traced attribution, but (a) the opponent is the explicit nemesis `Rules`,
//! (b) the read is the realistic converged Memory snapshot (the lab measures the nemesis under Memory),
//! and (c) the drill is on the AGGRESSIVE side (hero bet/raise buckets, bluff-into-station), because
//! this is the over-barrel mirror of the GTO over-defense leak.
//!
//! Run: `cargo run --release --bin diag_nemesis [deals]`.
use rechner::exploit::style::classify;
use rechner::game::{Choice, Street};
use rechner::rng::Rng;
use rechner::sim::memory::SessionMemory;
use rechner::sim::opponent::Opponent;
use rechner::sim::reader::Rules;
use rechner::sim::table::{deal, play_hand_tracked, play_hand_traced, HandRead, HandSetup, TableCost};
use std::collections::BTreeMap;
const SEED: u64 = 0x5EED_0001;
const STACK_BB: f64 = 100.0;
const PLAYERS: usize = 2;
/// The original nemesis ruleset (full-budget run vs the pre-fix engine).
const NEMESIS: Rules = Rules {
call_margin: 0.215,
raise_at: 0.587,
bet_at: 0.548,
open_at: 0.729,
bluff: 0.068,
size: 0.441,
};
/// The new worst case the CMA-ES finds against the FIXED engine (fast scan). Also read-driven
/// (Blind +114, Memory −87).
const NEMESIS2: Rules = Rules {
call_margin: 0.173,
raise_at: 0.579,
bet_at: 0.748,
open_at: 0.800,
bluff: 0.229,
size: 0.996,
};
/// The worst case the CMA-ES finds against the SOFT-TRUST engine (fast scan, −52.65 bb/100): folds air
/// hard (call_margin 0.396), opens very wide (0.468), rarely raises, overbets (size 1.148).
const NEMESIS3: Rules = Rules {
call_margin: 0.396,
raise_at: 0.769,
bet_at: 0.615,
open_at: 0.468,
bluff: 0.261,
size: 1.148,
};
fn mix(seed: u64, n: u64) -> u64 {
Rng::seeded(seed ^ n.wrapping_mul(0xD1B5_4A32_D192_ED03)).next_u64().0
}
fn street_name(s: Street) -> &'static str {
match s {
Street::Preflop => "preflop",
Street::Flop => "flop",
Street::Turn => "turn",
Street::River => "river",
}
}
fn choice_name(c: Choice) -> &'static str {
match c {
Choice::Fold => "fold",
Choice::Check => "check",
Choice::Call => "call",
Choice::Raise { .. } => "raise/bet",
Choice::Abstain => "abstain",
}
}
#[derive(Default, Clone, Copy)]
struct Agg {
hands: u32,
net: f64,
}
impl Agg {
fn add(&mut self, net: f64) {
self.hands += 1;
self.net += net;
}
}
fn contrib(net: f64, total_hands: u32) -> f64 {
100.0 * net / total_hands.max(1) as f64
}
/// Trace all deals under one fixed read; return (total, terminal buckets by (street, action)).
fn run(opponent: Opponent, deals: u32, read: Option<rechner::exploit::profile::Profile>)
-> (Agg, BTreeMap<(Street, &'static str), Agg>) {
let mut total = Agg::default();
let mut by_terminal: BTreeMap<(Street, &'static str), Agg> = BTreeMap::new();
for d in 0..deals {
let (cards, _) = deal(PLAYERS, Rng::seeded(mix(SEED, d as u64)));
for hero_seat in 1..=PLAYERS as u8 {
let hand = HandSetup {
deal: &cards,
hero_seat,
opponent,
stack_bb: STACK_BB,
seed: mix(SEED ^ 0xA5A5, (d as u64) << 8 | hero_seat as u64),
read: HandRead::Given(read),
};
let (res, trace) = play_hand_traced(&hand, TableCost::FREE);
let net = res.hero_net - res.luck; // luck-corrected
total.add(net);
if let Some(last) = trace.last() {
by_terminal.entry((last.street, choice_name(last.choice))).or_default().add(net);
}
}
}
(total, by_terminal)
}
fn main() {
let deals: u32 = std::env::args().nth(1).and_then(|s| s.parse().ok()).unwrap_or(2000);
let which: u32 = std::env::args().nth(2).and_then(|s| s.parse().ok()).unwrap_or(1);
let opponent = Opponent::Styled(match which {
3 => NEMESIS3,
2 => NEMESIS2,
_ => NEMESIS,
});
// --- Pass 1: converge the Memory read exactly as session::deal_samples does. ---
let mut memory = SessionMemory::new();
for d in 0..deals {
let (cards, _) = deal(PLAYERS, Rng::seeded(mix(SEED, d as u64)));
for hero_seat in 1..=PLAYERS as u8 {
let hand = HandSetup {
deal: &cards,
hero_seat,
opponent,
stack_bb: STACK_BB,
seed: mix(SEED ^ 0xA5A5, (d as u64) << 8 | hero_seat as u64),
read: HandRead::Given(memory.read()),
};
play_hand_tracked(&hand, TableCost::FREE, Some(&mut memory));
}
}
let read = memory.read();
println!("=== Nemesis-Diagnose (Memory vs Blind): {deals} Austeilungen ===\n");
print!("-- konvergierter Read des Nemesis: ");
match read {
None => println!("kein Read"),
Some(p) => println!(
"vpip {:.2} pfr {:.2} fold2bet {:.2} aggr {:.2} -> classify {:?}",
p.vpip.unwrap_or(f64::NAN), p.pfr.unwrap_or(f64::NAN),
p.fold_to_bet.unwrap_or(f64::NAN), p.aggression.unwrap_or(f64::NAN), classify(&p),
),
}
// --- Pass 2+3: same deals under the converged Memory read and under blind (None). ---
let (mem_total, mem_buckets) = run(opponent, deals, read);
let (blind_total, blind_buckets) = run(opponent, deals, None);
let h = mem_total.hands;
println!(
"\n-- gesamt: Memory {:+.2} vs Blind {:+.2} bb/100 (Delta {:+.2}, {} Haende) --",
contrib(mem_total.net, h), contrib(blind_total.net, h),
contrib(mem_total.net - blind_total.net, h), h
);
// Per terminal bucket: Memory, Blind, and the Memory−Blind delta (the leak per bucket), sorted by
// the delta (most-costly read-driven bucket first).
let mut keys: std::collections::BTreeSet<(Street, &'static str)> = std::collections::BTreeSet::new();
keys.extend(mem_buckets.keys().copied());
keys.extend(blind_buckets.keys().copied());
let get = |m: &BTreeMap<(Street, &'static str), Agg>, k: &(Street, &'static str)| {
m.get(k).copied().unwrap_or_default()
};
let mut rows: Vec<_> = keys.into_iter().map(|k| {
let (m, b) = (get(&mem_buckets, &k), get(&blind_buckets, &k));
(k, contrib(m.net, h), contrib(b.net, h), contrib(m.net - b.net, h), m.hands, b.hands)
}).collect();
rows.sort_by(|a, b| a.3.partial_cmp(&b.3).unwrap());
println!("\n-- nach terminaler Entscheidung: Memory vs Blind (Delta = Leck je Bucket) --");
println!(" {:<18} {:>10} {:>10} {:>10} {:>8} {:>8}", "bucket", "mem", "blind", "DELTA", "mem#", "blind#");
for ((s, act), m, b, delta, mh, bh) in rows {
println!(
" {:<18} {:>+10.2} {:>+10.2} {:>+10.2} {:>8} {:>8}",
format!("{} {}", street_name(s), act), m, b, delta, mh, bh
);
}
}
+39
View File
@@ -0,0 +1,39 @@
//! Stufe 0 of the synthetic lab: print the exploitation gap over a drawn opponent population.
//!
//! Draws a micro-stakes field, plays the live engine heads-up against each opponent with NO oracle
//! read — once blind, once inferring from session memory — and reports `memory - blind` in bb/100,
//! pooled and per hidden archetype. This is the exploitation number the fixed-bot ladder hides.
//!
//! Run: `cargo run --release --bin exploit_gap`.
use rechner::sim::exploit_pop::exploitation_gap;
use rechner::sim::population::Population;
const SEED: u64 = 0x5EED_0001;
const OPPONENTS: usize = 48;
const DEALS: u32 = 400;
fn main() {
let pop = Population::micro();
println!("=== Stufe 0: Exploitation-Lücke gegen eine gezogene Population ===");
println!("{OPPONENTS} Gegner x {DEALS} Austeilungen, heads-up, KEIN Oracle-Read (Engine muss erschließen).\n");
let r = exploitation_gap(&pop, OPPONENTS, DEALS, SEED);
println!("blind (kein Read) {:+8.2} bb/100", r.blind_bb_per_100);
println!("memory (erschlossen) {:+8.2} bb/100", r.memory_bb_per_100);
println!(
"\nEXPLOITATION-LÜCKE {:+8.2} bb/100 (paired +-{:.2}, anytime +-{:.2})",
r.gap_bb_per_100, r.ci95, r.anytime_ci95
);
let decisive = r.gap_bb_per_100 - r.ci95 > 0.0;
println!(
" {} bei 95 %\n",
if decisive { "SIGNIFIKANT POSITIV" } else { "noch nicht von 0 trennbar" }
);
println!("nach verdecktem Archetyp (mittlere Lücke je Gegner):");
for (label, (sum, n)) in &r.by_label {
println!(" {label:8} {:+7.2} bb/100 ({n} Gegner)", sum / *n as f64);
}
}
+85
View File
@@ -0,0 +1,85 @@
//! Scan the LIVE engine's heads-up river exploitability across board textures.
//!
//! The first postflop-exploitability number for this engine (the measure MODULES.md names as missing).
//! For each board, hero and villain hold the FULL remaining range (every unblocked two-card combo);
//! the harness (`sim::exploit_river`) buckets them by exact showdown strength, solves the river
//! subgame for the equilibrium value, plays the engine's real policy as hero, and lets the villain
//! best-respond. Exploitability = v* - value(engine | villain best-responds), in bb/100, always >= 0.
//!
//! Run: `cargo run --release --bin exploit_scan`. Pot and bet default to 6 and 4 bb (two-thirds pot).
use rechner::card::Card;
use rechner::exploit::profile::Profile;
use rechner::sim::exploit_river::{exploitability_river, RiverSpec};
const ITERS: u32 = 60_000;
const SEED: u64 = 0x5EED_0001;
const POT: f64 = 6.0;
const BET: f64 = 4.0;
/// The 52-card deck minus the board.
fn remaining(board: &[Card]) -> Vec<Card> {
(0..52)
.filter_map(Card::from_index)
.filter(|c| !board.contains(c))
.collect()
}
/// Every two-card combo from a card list.
fn combos(cards: &[Card]) -> Vec<Vec<Card>> {
let mut out = Vec::new();
for i in 0..cards.len() {
for j in (i + 1)..cards.len() {
out.push(vec![cards[i], cards[j]]);
}
}
out
}
fn scan(label: &str, board_text: &str, profile: Option<Profile>, profile_label: &str) {
let board = Card::parse_list(board_text).expect("valid board");
let deck = remaining(&board);
let range = combos(&deck);
let spec = RiverSpec {
board: &board,
hero_range: &range,
villain_range: &range,
villain_profile: profile,
pot: POT,
bet: BET,
};
match exploitability_river(&spec, ITERS, SEED) {
Some(r) => println!(
"{label:<22} {board_text:<17} {profile_label:<8} buckets {:>3} v* {:>8.1} engine {:>8.1} exploitability {:>7.1} bb/100",
r.buckets, r.gto_value, r.engine_value_vs_br, r.exploitability
),
None => println!("{label:<22} {board_text:<17} degenerate subgame"),
}
}
fn main() {
// A representative near-GTO villain belief (reads.rs gto), and the unread default.
let gto = Profile {
vpip: Some(0.32),
pfr: Some(0.22),
fold_to_bet: Some(0.42),
aggression: Some(0.40),
..Profile::default()
};
println!("heads-up river exploitability, pot {POT} bet {BET} (two-thirds), {ITERS} solver iters\n");
let boards = [
("dry ace-high", "Ah Kd 7c 2s 9h"),
("paired board", "Kh Kd 7c 2s 9h"),
("wet connected", "9h 8h 7c 6s 2h"),
("monotone", "Ah Jh 8h 3h 2c"),
("low dry", "7c 4d 2s 9h Js"),
("broadway", "Ah Ks Qd Jc 2h"),
];
for (label, board) in boards {
scan(label, board, None, "unread");
}
println!();
for (label, board) in boards {
scan(label, board, Some(gto), "gto");
}
}
+41
View File
@@ -0,0 +1,41 @@
//! The read-driven slice of the GTO robustness floor: gto / gto-small per read mode.
//!
//! For a `Regular`/`Gto` the range model is gated to blind in every read mode (`earned_trust == 0`), so
//! the only lever that touches it is the ungated MDF floor. Before the `over_bluffs` fix the session
//! (Memory) read tagged the balanced heads-up opponent LooseAggressive on preflop width alone, firing
//! the floor to force-call its value bets — so Memory sat with Blind, ~12 bb/100 below Oracle
//! (BEFUND-gto-ueberdefense-read). After the fix the floor keys on measured postflop aggression, which
//! the balanced opponent does not trip, so Memory recovers toward Oracle (the read-gap closes).
//!
//! Run: `cargo run --release --bin floor_read [deals]` (default 4000, twin_gate's archetype budget).
use rechner::sim::opponent::Opponent;
use rechner::sim::reader::Style;
use rechner::sim::session::{measure, ReadMode, Setup};
const SEED: u64 = 0x5EED_0001;
const STACK_BB: f64 = 100.0;
fn row(style: Style, read: ReadMode, deals: u32) {
let setup = Setup { players: 2, opponent: Opponent::Reader(style), deals, stack_bb: STACK_BB, seed: SEED, read };
let m = measure(&setup);
println!(
" {:<9} {:<7} {:>+8.2} bb/100 ±{:>5.2}",
style.name(),
format!("{read:?}"),
m.bb_per_100,
m.ci95,
);
}
fn main() {
let deals: u32 = std::env::args().nth(1).and_then(|s| s.parse().ok()).unwrap_or(4000);
println!("=== Floor-Read: gto/gto-small je Lese-Modus, {deals} Austeilungen ===");
println!("Nach dem Fix sollte Memory ~= Oracle sein (Read-Luecke geschlossen), nicht mehr = Blind.\n");
for style in [Style::Gto, Style::GtoSmall] {
for read in [ReadMode::Oracle, ReadMode::Blind, ReadMode::Memory] {
row(style, read, deals);
}
println!();
}
}
+74
View File
@@ -0,0 +1,74 @@
//! Does the session (Memory) read misclassify the balanced heads-up gto as LooseAggressive, tripping
//! the MDF floor's `over_bluffs`? Accumulates `SessionMemory` over a session against the gto exactly as
//! `session::deal_samples` does, and prints the evolving read + `classify` at checkpoints.
//!
//! Run: `cargo run --release --bin gto_read_probe [deals]`.
use rechner::exploit::style::classify;
use rechner::rng::Rng;
use rechner::sim::memory::SessionMemory;
use rechner::sim::opponent::Opponent;
use rechner::sim::reader::Style;
use rechner::sim::table::{deal, play_hand_tracked, HandRead, HandSetup, TableCost};
const SEED: u64 = 0x5EED_0001;
const STACK_BB: f64 = 100.0;
const PLAYERS: usize = 2;
fn mix(seed: u64, n: u64) -> u64 {
Rng::seeded(seed ^ n.wrapping_mul(0xD1B5_4A32_D192_ED03)).next_u64().0
}
/// The shipped `over_bluffs` predicate (mdf_floor): measured postflop aggression ≥ 0.45, NOT preflop
/// width. The old rule (`classify == LooseAggressive || aggr >= 0.60`) misfired on the balanced wide
/// heads-up read; this probe shows why (classify still says LooseAggressive, but aggr stays ~0.35).
fn over_bluffs_now(p: &rechner::exploit::profile::Profile) -> bool {
p.aggression.is_some_and(|a| a >= 0.45)
}
fn final_read(style: Style, deals: u32) {
let mut memory = SessionMemory::new();
for d in 0..deals {
let (cards, _) = deal(PLAYERS, Rng::seeded(mix(SEED, d as u64)));
for hero_seat in 1..=PLAYERS as u8 {
let hand = HandSetup {
deal: &cards,
hero_seat,
opponent: Opponent::Reader(style),
stack_bb: STACK_BB,
seed: mix(SEED ^ 0xA5A5, (d as u64) << 8 | hero_seat as u64),
read: HandRead::Given(memory.read()),
};
play_hand_tracked(&hand, TableCost::FREE, Some(&mut memory));
}
}
match memory.read() {
None => println!(" {:<10} kein Read", style.name()),
Some(p) => println!(
" {:<10} vpip {:>4.2} pfr {:>4.2} fold2bet {:>4.2} aggr {:>4.2} -> {:<16} over_bluffs={}",
style.name(),
p.vpip.unwrap_or(f64::NAN),
p.pfr.unwrap_or(f64::NAN),
p.fold_to_bet.unwrap_or(f64::NAN),
p.aggression.unwrap_or(f64::NAN),
format!("{:?}", classify(&p)),
over_bluffs_now(&p),
),
}
}
fn main() {
let deals: u32 = std::env::args().nth(1).and_then(|s| s.parse().ok()).unwrap_or(3000);
println!("=== Memory-Read je Archetyp (Endstand), {deals} Austeilungen ===");
println!("over_bluffs (geshippt) = aggression>=0.45 => MDF-Boden feuert (NICHT mehr Preflop-Breite).");
println!("Balanciert (gto/gto-small) sollte over_bluffs=false sein, Maniac=true.\n");
// Fast archetypes only here (no solver). `GTO_TOO=1` also runs gto/gto-small (slow solver).
let mut styles = vec![Style::Maniac, Style::Fish, Style::Reg, Style::Nit];
if std::env::var("GTO_TOO").is_ok() {
styles.push(Style::Gto);
styles.push(Style::GtoSmall);
}
for style in styles {
final_read(style, deals);
}
}
+33
View File
@@ -0,0 +1,33 @@
//! Stufe 3 / L3 of the synthetic lab: score the engine across the whole LEAGUE.
//!
//! Static field draws + the L1 reactive opponents + the L2 modelling opponent + the Stufe-5 nemesis,
//! all at once. The league mean says how the engine does on average; the WORST member is the
//! robustness floor — the one a change must never cave against. A richer-pool sibling of the twin
//! gate's six-archetype floor.
//!
//! Run: `cargo run --release --bin league`.
use rechner::sim::league::evaluate;
use rechner::sim::population::Population;
const SEED: u64 = 0x5EED_0001;
const POP_MEMBERS: usize = 12;
const DEALS: u32 = 400;
fn main() {
let pop = Population::micro();
println!("=== Stufe 3 / L3: die Liga — Robustheit gegen einen Pool, kein Overfit ===");
println!("{POP_MEMBERS} Populationszieher + L1 (tighten/loosen) + L2 (model) + Nemesis, je {DEALS} Austeilungen.\n");
let r = evaluate(&pop, POP_MEMBERS, DEALS, SEED);
let mut members = r.members.clone();
members.sort_by(|a, b| a.ev_bb_per_100.partial_cmp(&b.ev_bb_per_100).unwrap());
for m in &members {
let mark = if m.name == r.worst_name { " <- BODEN" } else { "" };
println!(" {:22} {:+9.2} bb/100 ±{:.2}{}", m.name, m.ev_bb_per_100, m.ci95, mark);
}
println!("\nLiga-Mittel : {:+.2} bb/100", r.mean_bb_per_100);
println!("Liga-Boden : {} {:+.2} bb/100 ±{:.2}", r.worst_name, r.worst_bb_per_100, r.worst_ci95);
println!("\nRobust heisst: der Boden haelt. Der Mittelwert allein genuegt nicht.");
}
+33
View File
@@ -0,0 +1,33 @@
//! Stufe 5 of the synthetic lab: find the engine's NEMESIS — the worst-case individual opponent.
//!
//! Runs the diagonal CMA-ES (`sim::optimize`) over the 6-dim ruleset space to find the realistic
//! opponent the engine does worst against, an empirical best response in opponent-space. This is a
//! tighter robustness probe than the twin gate's "worst of six archetypes" floor: it searches the
//! whole continuous neighbourhood. The same optimizer tunes the engine's own hyperparameters once they
//! are exposed as a vector — that is the "polish, last" step the architecture names.
//!
//! Run: `cargo run --release --bin nemesis`.
use rechner::sim::optimize::worst_case_opponent;
const SEED: u64 = 0x5EED_0001;
// Higher budget now that the λ-evaluations run in parallel: more deals per evaluation tightens the
// nemesis EV, more generations let the CMA-ES converge further into the worst-case region. Overridable
// from argv (`nemesis [deals] [generations]`) for a fast scan before the full-budget confirmation.
const DEALS: u32 = 1000;
const GENERATIONS: u32 = 14;
fn main() {
let deals: u32 = std::env::args().nth(1).and_then(|s| s.parse().ok()).unwrap_or(DEALS);
let generations: u32 = std::env::args().nth(2).and_then(|s| s.parse().ok()).unwrap_or(GENERATIONS);
println!("=== Stufe 5: der Nemesis — schlechtester Gegner der Engine (CMA-ES ueber den Regelraum) ===");
println!("{deals} Austeilungen je Auswertung, {generations} Generationen, Memory-Read.\n");
let (r, ev) = worst_case_opponent(deals, generations, SEED);
println!("Nemesis-Regelwerk (realistische Schranken):");
println!(" call_margin {:.3} raise_at {:.3} bet_at {:.3}", r.call_margin, r.raise_at, r.bet_at);
println!(" open_at {:.3} bluff {:.3} size {:.3}", r.open_at, r.bluff, r.size);
println!("\nEngine-EV gegen den Nemesis: {ev:+.2} bb/100");
println!("(> 0 = die Engine schlaegt selbst ihren schlechtesten realistischen Gegner.)");
}
+80
View File
@@ -0,0 +1,80 @@
//! Is the nemesis leak read-driven? Measure the engine's EV vs the fixed nemesis ruleset under each
//! read mode. If Blind >> Memory, the catastrophe is the TRUSTED CallingStation read (vpip 0.53 trips
//! the `loose -> CallingStation` path, earned_trust 1.0), and gating the nemesis to blind — by making
//! `classify` require a station to be postflop-passive, so this aggressive frequent-folder reads
//! Regular — recovers it toward the Blind ceiling.
//!
//! Run: `cargo run --release --bin nemesis_read [deals]`.
use rechner::exploit::style::classify;
use rechner::sim::opponent::Opponent;
use rechner::sim::reader::Rules;
use rechner::sim::session::{measure, ReadMode, Setup};
const SEED: u64 = 0x5EED_0001;
const STACK_BB: f64 = 100.0;
/// The original CMA-ES nemesis (full-budget, vs the pre-fix engine): a reg-tight low-bluff caller
/// that bet a lot and raised light. Fixed via the station-aggression gate (classify reads it Regular).
const NEMESIS: Rules = Rules {
call_margin: 0.215,
raise_at: 0.587,
bet_at: 0.548,
open_at: 0.729,
bluff: 0.068,
size: 0.441,
};
/// The NEW worst case the CMA-ES finds against the FIXED engine (fast scan 400x8, −173 bb/100): bets
/// tighter (0.748) but big (size ~pot), raises light (0.579), and actually bluffs (0.229).
const NEMESIS2: Rules = Rules {
call_margin: 0.173,
raise_at: 0.579,
bet_at: 0.748,
open_at: 0.800,
bluff: 0.229,
size: 0.996,
};
/// The worst case the CMA-ES finds against the SOFT-TRUST engine (fast scan 1000x14, −52.65 bb/100):
/// a different shape — folds air hard (call_margin 0.396), opens very wide (0.468), rarely raises
/// (0.769), overbets (size 1.148). Probe: is it the same read-driven family or a genuine hole?
const NEMESIS3: Rules = Rules {
call_margin: 0.396,
raise_at: 0.769,
bet_at: 0.615,
open_at: 0.468,
bluff: 0.261,
size: 1.148,
};
fn main() {
let deals: u32 = std::env::args().nth(1).and_then(|s| s.parse().ok()).unwrap_or(4000);
println!("=== Nemesis je Lese-Modus, {deals} Austeilungen ===");
println!("Blind >> Memory => lesegetriebenes Leck (Fehlklassifikation). Blind ~= Memory => echtes Loch.\n");
for (name, rules) in [("nemesis-1", NEMESIS), ("nemesis-2", NEMESIS2), ("nemesis-3", NEMESIS3)] {
println!("-- {name}: call_margin {:.3} raise_at {:.3} bet_at {:.3} open_at {:.3} bluff {:.3} size {:.3}",
rules.call_margin, rules.raise_at, rules.bet_at, rules.open_at, rules.bluff, rules.size);
for read in [ReadMode::Oracle, ReadMode::Blind, ReadMode::Memory] {
let setup = Setup {
players: 2,
opponent: Opponent::Styled(rules),
deals,
stack_bb: STACK_BB,
seed: SEED,
read,
};
let m = measure(&setup);
println!(" {:<7} {:>+9.2} bb/100 ±{:>5.2}", format!("{read:?}"), m.bb_per_100, m.ci95);
}
println!();
}
let p = rechner::exploit::profile::Profile {
vpip: Some(0.53),
pfr: Some(0.14),
fold_to_bet: Some(0.65),
aggression: Some(0.62),
..Default::default()
};
println!(" classify(nemesis-1-read vpip0.53 pfr0.14 fold0.65 aggr0.62) = {:?}", classify(&p));
}
+50
View File
@@ -0,0 +1,50 @@
//! Stufe 4 (offline half): the sim-to-real HUD gap.
//!
//! Prints the HUD distribution the synthetic population INDUCES (vpip/pfr/fold-to-bet/aggression, mean
//! and spread) so it can be held against the real players' HUD. The real spread below is read from the
//! Stufe-1 calibration (`archiv/population.json`, `lesen/kalibrierung.py`), which today is a single
//! ten-player table snapshot (mostly regs), so only the reg axis has a real comparison — the method is
//! what stands; more logs sharpen it. The remaining gap (live outcomes vs sim) needs the live farm.
//!
//! Run: `cargo run --release --bin simreal`.
use rechner::sim::population::{Archetype, Population, Spread};
use rechner::sim::reader::Style;
use rechner::sim::simreal::population_induced_hud;
const SEED: u64 = 0x5EED_0001;
const DRAWS: usize = 120;
const HANDS_EACH: usize = 2000;
fn main() {
let pop = Population::micro();
let field = population_induced_hud(&pop, DRAWS, HANDS_EACH, SEED);
println!("=== Stufe 4 (offline): Sim-to-Real-Gap im HUD-Raum ===");
println!("{DRAWS} Zieher x {HANDS_EACH} Haende.\n");
println!("Induzierte HUD des ganzen synthetischen FELDES (alle Archetypen):");
println!(" Achse Mittel Streuung (ueber Archetypen)");
println!(" vpip {:>7.3} {:>7.3}", field.mean.vpip, field.sd.vpip);
println!(" pfr {:>7.3} {:>7.3}", field.mean.pfr, field.sd.pfr);
println!(" foldToBet {:>7.3} {:>7.3}", field.mean.fold_to_bet, field.sd.fold_to_bet);
println!(" aggression {:>7.3} {:>7.3}", field.mean.aggression, field.sd.aggression);
// The FAIR comparison: synthetic WITHIN-reg spread vs the real within-reg spread. The real snapshot
// is one table of (mostly) regs, so only this cluster has a real target. Draw reg-only opponents.
let reg_only = Population {
archetypes: vec![Archetype { label: "reg", mean: Style::Reg.rules(), weight: 1.0 }],
spread: Spread::DEFAULT,
};
let reg = population_induced_hud(&reg_only, DRAWS, HANDS_EACH, SEED ^ 0x8EED);
let (real_vpip_sd, real_pfr_sd, real_ftb_sd) = (0.043, 0.027, 0.089);
println!("\nInnerhalb des reg-Clusters — synth. vs real STREUUNG (der faire Vergleich):");
println!(" Achse synth. real Gap");
println!(" vpip {:>7.3} {:>7.3} {:>+7.3}", reg.sd.vpip, real_vpip_sd, reg.sd.vpip - real_vpip_sd);
println!(" pfr {:>7.3} {:>7.3} {:>+7.3}", reg.sd.pfr, real_pfr_sd, reg.sd.pfr - real_pfr_sd);
println!(" foldToBet {:>7.3} {:>7.3} {:>+7.3}", reg.sd.fold_to_bet, real_ftb_sd, reg.sd.fold_to_bet - real_ftb_sd);
println!("\n(Echte Mittel je Archetyp und die anderen Cluster brauchen mehr Mitschriebe als die");
println!(" eine Tisch-Momentaufnahme. Der Live-Outcome-Abgleich bleibt dem Live-Farm vorbehalten.)");
}
+116
View File
@@ -0,0 +1,116 @@
//! Turnier-Stärke-Leiter: beweist (oder widerlegt), dass die ICM-Linie in GELD gewinnt.
//!
//! Das Turnier-Gegenstück zur Nemesis/Archetyp-Leiter. Jedes Szenario ist ein Heads-up-Pot im
//! Feld unter einer Preisstruktur; jede Hand wird in ICM-GELD gewertet (Harville), die ICM-Linie
//! (`decide_with(spot, Some(lage))`) gepaart gegen die Cash-Linie (Chip-EV) auf denselben
//! Austeilungen. Kennzahl: die gepaarte Kante ICM$(an) − ICM$(aus) je 100 Hände, Pool = 100.
//!
//! Anker (WTA, tief & flach): ICM MUSS ~ Cash sein, Kante ~ 0. Bubble/Final-Table: die ICM-Linie
//! soll GEWINNEN (Kante > 0). Eine Kante, deren 95-%-Intervall GANZ unter 0 liegt, ist ein Leck
//! (Eiserne Regel: nie einen Verlierer shippen) — dann zurückrollen und Befund.
//!
//! Run: `cargo run --release --bin turnier_leiter [deals]` (default 2000).
use rechner::sim::opponent::Opponent;
use rechner::sim::reader::Style;
use rechner::sim::turnier_leiter::{messen, Szenario, TurnierMessung};
const SEED: u64 = 0x5EED_0001;
/// `an` = Reader-style aggressor (bets/jams → hero DEFENDS, call-premium bites);
/// `nit`/`folder` let hero open-jam (jam-pressure widening). Asymmetric scenarios (type K) put
/// hero and the opponent on DIFFERENT stacks — covering vs covered, where ICM bites hardest.
fn szenarien(deals: u32) -> Vec<(Szenario, char)> {
let sym = |name, payouts: &[f64], field: &[f64], opp, stack: f64, level| Szenario {
name,
payouts: payouts.to_vec(),
hero_stack: stack,
opp_stack: stack,
field: field.to_vec(),
opponent: opp,
deals,
seed: SEED,
level,
};
let asym = |name, payouts: &[f64], hero_stack, opp_stack, field: &[f64], opp, level| Szenario {
name,
payouts: payouts.to_vec(),
hero_stack,
opp_stack,
field: field.to_vec(),
opponent: opp,
deals,
seed: SEED,
level,
};
vec![
// --- Anker: ICM muss ~ Cash sein (Kante ~ 0) ---
// Winner-take-all: ICM-Equity IST der Chip-Anteil, keine Prämie.
(sym("wta", &[100.0], &[30.0, 30.0], Opponent::Reader(Style::Maniac), 25.0, 3), 'A'),
// Tief & flach: 120bb, nahezu lineare Payouts → Prämie verschwindet.
(sym("deep-flat", &[30.0, 26.0, 24.0, 20.0], &[120.0, 120.0, 120.0], Opponent::Reader(Style::Maniac), 120.0, 2), 'A'),
// --- Bubble (symmetrisch): die ICM-Linie soll gewinnen (Kante > 0) ---
(sym("soft-bubble", &[34.0, 26.0, 22.0, 18.0], &[18.0, 15.0, 40.0, 12.0], Opponent::Reader(Style::Maniac), 20.0, 6), 'B'),
(sym("hard-bubble", &[50.0, 30.0, 20.0], &[7.0, 5.0, 35.0], Opponent::Reader(Style::Maniac), 18.0, 8), 'B'),
(sym("hard-bubble-reg", &[50.0, 30.0, 20.0], &[7.0, 5.0, 35.0], Opponent::Reader(Style::Reg), 18.0, 8), 'B'),
(sym("final-table", &[60.0, 25.0, 15.0], &[12.0, 45.0], Opponent::Reader(Style::Reg), 15.0, 9), 'B'),
// --- Jam-Druck: Hero first-in, Gegner muss an der Bubble enger callen ---
(sym("jam-vs-nit", &[50.0, 30.0, 20.0], &[6.0, 5.0, 30.0], Opponent::Reader(Style::Nit), 12.0, 8), 'J'),
(sym("jam-vs-folder", &[50.0, 30.0, 20.0], &[6.0, 5.0, 30.0], Opponent::Folder, 12.0, 8), 'J'),
// --- Asymmetrisch (K): Decker vs. Gedeckter, wo ICM am härtesten beißt ---
// Hero GEDECKT (short) gegen großen Aggressor: Call-Prämie hoch (Bust = raus), muss enger
// callen als Chip-EV → bewahrt Equity.
(asym("covered-maniac", &[50.0, 30.0, 20.0], 8.0, 40.0, &[6.0, 30.0], Opponent::Reader(Style::Maniac), 8), 'K'),
(asym("covered-reg", &[50.0, 30.0, 20.0], 10.0, 40.0, &[6.0, 30.0], Opponent::Reader(Style::Reg), 8), 'K'),
// Hero DECKT (big stack) einen Short: kann nicht busten (Prämie ~0), aber der Short muss
// enger callen → Open-Jam-Weitung stiehlt breiter.
(asym("cover-short", &[50.0, 30.0, 20.0], 40.0, 8.0, &[6.0, 30.0], Opponent::Reader(Style::Nit), 8), 'K'),
// --- Tiefen-Sweep um die Deck-Richtung: wo weitet `jam_width_factor` zu breit? ---
// Der Nash-Abgleich (RECON-icm-nash-anker) zeigt die Über-Weitung am größten bei ~9bb
// (Jam 68 vs Nash 65). 6/8/12bb klammern die schwache Stelle ein.
(asym("cover-6bb", &[50.0, 30.0, 20.0], 40.0, 6.0, &[6.0, 30.0], Opponent::Reader(Style::Nit), 8), 'K'),
(asym("cover-12bb", &[50.0, 30.0, 20.0], 40.0, 12.0, &[6.0, 30.0], Opponent::Reader(Style::Nit), 8), 'K'),
// Gedeckte Seite tiefer (12bb): gewinnt der ICM-Vorteil auch, wenn Hero weniger kurz ist?
(asym("covered-12bb", &[50.0, 30.0, 20.0], 12.0, 40.0, &[6.0, 30.0], Opponent::Reader(Style::Maniac), 8), 'K'),
]
}
/// Verdict symbol: ✓ ICM proven to win (whole interval > 0); · neutral (|edge| ≤ CI, the anchor
/// target); ✗ LECK — the interval is wholly below 0 (iron law: revert + Befund).
fn mark(m: &TurnierMessung) -> &'static str {
if m.wins() {
"✓ gewinnt"
} else if m.edge_per100 + m.ci95 < 0.0 {
"✗ LECK"
} else {
"· neutral"
}
}
fn main() {
let deals: u32 = std::env::args().nth(1).and_then(|s| s.parse().ok()).unwrap_or(2000);
println!("=== Turnier-Stärke-Leiter, {deals} Austeilungen/Szenario (Pool = 100) ===");
println!("Kante = ICM$(an) - ICM$(aus) je 100 Hände, gepaart, 95-%-Intervall.");
println!("A=Anker (Ziel ~0) B=Bubble/FT (Ziel >0) J=Jam-Druck\n");
println!(" {:<17} {:>3} {:>9} {:>8} {:>9} {:>9} {}", "szenario", "typ", "kante", "±ci", "an", "aus", "urteil");
let mut leck = false;
for (sz, typ) in szenarien(deals) {
let m = messen(&sz);
if m.invalid > 0 {
println!(" !! {} INVALID {}", sz.name, m.invalid);
}
if m.edge_per100 + m.ci95 < 0.0 {
leck = true;
}
println!(
" {:<17} {:>3} {:>+9.3} {:>8.3} {:>+9.3} {:>+9.3} {}",
sz.name, typ, m.edge_per100, m.ci95, m.icm_on_per100, m.icm_off_per100, mark(&m),
);
}
println!();
if leck {
println!(">> LECK gefunden: mindestens ein Szenario verliert ICM-Geld. Zurückrollen + Befund.");
} else {
println!(">> Kein Leck: keine ICM-Linie verliert. Bubble-Kanten > 0 beweisen den ICM-Vorteil.");
}
}
+43
View File
@@ -0,0 +1,43 @@
//! Stufe 2 of the synthetic lab: the TWIN GATE — print the three axes that replace the bb/100 ladder.
//!
//! One engine build, scored on: population EV (does it still exploit a varied field), the robustness
//! floor (its EV against the single worst archetype — the balanced players are the overfit catcher),
//! and river exploitability (an exact best-response distance on a fixed battery). "Never ship a loser"
//! becomes: lose no axis. Use `Gate::passes` in a regression harness to compare two builds.
//!
//! Run: `cargo run --release --bin twin_gate`.
use rechner::sim::population::Population;
use rechner::sim::twin_gate::{evaluate, TwinBudget};
const SEED: u64 = 0x5EED_0001;
fn main() {
let pop = Population::micro();
// Full budget: tightens the floor CIs the lean run left wide. The two balanced archetypes run a
// solver per decision, so this is the slow run (~1 h) — but it is the production-scale measurement.
let budget = TwinBudget::default();
println!("=== Stufe 2: das Zwillings-Tor (ersetzt die bb/100-Leiter) ===");
println!(
"Population {}x{} Austeilungen, Archetypen {} Austeilungen, River-Batterie {} Iter.\n",
budget.pop_opponents, budget.pop_deals, budget.archetype_deals, budget.river_iters
);
let r = evaluate(&pop, budget, SEED);
println!("OFFENSE — Population-EV (Memory, erschlossen)");
println!(" {:+.2} bb/100 (Exploitation-Luecke {:+.2})\n", r.population_ev_bb_per_100, r.exploitation_gap_bb_per_100);
println!("ROBUSTHEIT — EV je Archetyp (Memory), Boden = schlechtester:");
for (name, ev, ci) in &r.archetypes {
let mark = if *name == r.worst_archetype { " <- BODEN" } else { "" };
println!(" {name:10} {ev:+8.2} bb/100 +-{ci:.2}{mark}");
}
println!(" Boden: {} {:+.2} bb/100 +-{:.2}\n", r.worst_archetype, r.worst_ev_bb_per_100, r.worst_ci95);
println!("DEFENSE — River-Exploitability (exakte Best Response, {} Spots)", r.subgames);
println!(" Mittel {:.2} bb/100, Max {:.2} bb/100 (0 = unausbeutbar)\n", r.mean_exploitability_bb_per_100, r.max_exploitability_bb_per_100);
println!("Tor-Regel fuer einen Kandidaten: Population-EV haelt UND Boden haelt UND Exploitability steigt nicht.");
}
+199
View File
@@ -0,0 +1,199 @@
//! KL-Trust-Region-Best-Response: sigma* = argmax E[EV vs fester Gegner] - lambda * KL(sigma || gto).
//!
//! Je Infoset (Knoten x Klasse) ist die Loesung der Softmax-Tilt der GTO-Zeile mit den bedingten
//! Aktionswerten: `sigma*(a) ~ gto(a) * exp(Q(a) / lambda)`. Q haengt von sigma* weiter unten ab,
//! darum wird von den Blaettern zur Wurzel gearbeitet (tiefste eigene Knoten zuerst); jeder Knoten
//! sieht dann die schon getiltete Strategie unterhalb, die Rekursion ist damit exakt.
//!
//! `lambda = inf` liefert `gto` unveraendert, `lambda -> 0` den Best Response auf dem Traeger von
//! `gto` (Aktionen mit gto-Wahrscheinlichkeit 0 bleiben 0 - KL ist dort unendlich).
//!
//! Q ist der kontrafaktische Wert aus `value_walk` geteilt durch die Masse (Chance x Gegner-Reach)
//! des Infosets, also der Erwartungswert in Chips gegeben, dass der Infoset erreicht ist; so ist
//! `lambda` in denselben Einheiten wie die Auszahlungen und unabhaengig von der Reichweite.
use super::strategy::Strategy;
use super::tree::{Node, Tree};
use super::value_walk::{root_values, Responder};
/// Eigene Entscheidungsknoten samt Tiefe, tiefste zuerst.
fn hero_nodes_deepest_first(tree: &Tree, hero: usize) -> Vec<(usize, &'static str)> {
let mut found: Vec<(usize, usize, &'static str)> = Vec::new();
let mut stack = vec![(tree.root, 0usize)];
while let Some((node, depth)) = stack.pop() {
match tree.nodes.get(node) {
Some(Node::Decision { player, name, children }) => {
if *player == hero {
found.push((depth, node, name));
}
stack.extend(children.iter().map(|c| (*c, depth + 1)));
}
Some(Node::Chance(branches)) => stack.extend(branches.iter().map(|(_, c)| (*c, depth + 1))),
_ => {}
}
}
found.sort_by(|a, b| b.0.cmp(&a.0));
found.into_iter().map(|(_, node, name)| (node, name)).collect()
}
/// Softmax-Tilt einer Zeile: `base * exp((q - max q) / lambda)`, normalisiert.
fn tilt(base: &[f64], q: &[f64], lambda: f64) -> Vec<f64> {
let top = base
.iter()
.zip(q)
.filter(|(b, _)| **b > 0.0)
.map(|(_, q)| *q)
.fold(f64::NEG_INFINITY, f64::max);
if !top.is_finite() {
return base.to_vec();
}
let weights: Vec<f64> =
base.iter().zip(q).map(|(b, q)| if *b > 0.0 { b * ((q - top) / lambda).exp() } else { 0.0 }).collect();
let total: f64 = weights.iter().sum();
if total > 0.0 && total.is_finite() {
weights.iter().map(|w| w / total).collect()
} else {
base.to_vec()
}
}
/// Heros KL-Trust-Region-Strategie gegen die feste Strategie des Gegners (in `opponent`) um `gto`.
/// Nur die Gegnerzeilen von `opponent` zaehlen; Rueckgabe = `gto` mit getilteten Heldenzeilen.
pub fn kl_best_response(tree: &Tree, opponent: &Strategy, gto: &Strategy, hero_player: usize, lambda: f64) -> Strategy {
if !(lambda < f64::INFINITY) || lambda.is_nan() || !tree.is_playable() {
return gto.clone();
}
let lambda = lambda.max(1e-12);
let n = tree.classes;
let hero = hero_player.min(1);
// Start: Heldenzeilen aus gto, Gegnerzeilen aus `opponent` (nur zum Bewerten).
let mut current = gto.clone();
for (i, node) in tree.nodes.iter().enumerate() {
if let Node::Decision { player, name, .. } = node {
if *player != hero {
current = current.with_rows(tree, name, |c| opponent.row(i, c).to_vec()).unwrap_or(current);
}
}
}
for (node, name) in hero_nodes_deepest_first(tree, hero) {
// Werte unter `current` (unterhalb schon getiltet, oberhalb egal: Q haengt nicht davon ab).
let mut q: Vec<Vec<f64>> = Vec::new();
let mut mass = vec![0.0; n];
root_values(tree, &current, Responder::Follow, hero, &mut |v| {
if v.node == node {
q = v.action_values.to_vec();
for c in 0..n {
mass[c] = (0..n)
.map(|o| if hero == 0 { tree.chance[c * n + o] } else { tree.chance[o * n + c] } * v.opp[o])
.sum();
}
}
});
if q.is_empty() {
continue;
}
let rows: Vec<Vec<f64>> = (0..n)
.map(|c| {
let base = gto.row(node, c);
if mass[c] <= 1e-15 {
return base.to_vec();
}
let cond: Vec<f64> = q.iter().map(|a| a[c] / mass[c]).collect();
tilt(base, &cond, lambda)
})
.collect();
current = current.with_rows(tree, name, |c| rows[c].clone()).unwrap_or(current);
}
// Rueckgabe: Heldenzeilen getiltet, Gegnerzeilen wieder wie gto.
for (i, node) in tree.nodes.iter().enumerate() {
if let Node::Decision { player, name, .. } = node {
if *player != hero {
current = current.with_rows(tree, name, |c| gto.row(i, c).to_vec()).unwrap_or(current);
}
}
}
current
}
#[cfg(test)]
mod tests {
use super::*;
use crate::cfr::exploitability::game_value;
use crate::cfr::river::tree_with_chance;
use crate::cfr::solve::solve;
use crate::rng::Rng;
/// Polarisierter Fluss: Held Air+Nuts, Gegner reiner Bluffcatcher; Pot 2, Bet 1.
fn setup() -> (Tree, Strategy) {
let n = 3;
let mut chance = vec![0.0; n * n];
chance[0 * n + 1] = 0.5;
chance[2 * n + 1] = 0.5;
let tree = tree_with_chance(n, chance, 2.0, 1.0);
let gto = solve(&tree, 20_000, Rng::seeded(0x5EED_21AA)).strategy;
(tree, gto)
}
/// Wert des Gegners gegen Heldenstrategie bei bestem Gegner.
fn villain_br(tree: &Tree, s: &Strategy) -> f64 {
root_values(tree, s, Responder::Best, 1, &mut |_| {}).iter().sum()
}
fn belief_ev(tree: &Tree, s: &Strategy) -> f64 {
game_value(tree, s)
}
#[test]
fn lambda_sweep_traces_safety_exploit_tradeoff() {
let (tree, gto) = setup();
let base_br = villain_br(&tree, &gto);
let gto_ev = game_value(&tree, &gto);
// Der feste Gegner: gto, aber in der Realitaet ein Overfolder (belief) waere interessanter;
// hier der geloeste Gegner, der Held hat also nur Rauschen zu gewinnen. Zusaetzlich ein
// exploitierbarer Gegner: ruft nur 40 % (Overfold) statt 2/3.
let weak = gto.with_rows(&tree, "v_bet", |_| vec![0.6, 0.4]).unwrap();
let mut prev: Option<(f64, f64)> = None;
println!("lambda, belief_EV(vs overfolder), exploitability");
for lambda in [1e9, 100.0, 10.0, 1.0, 0.1, 0.01] {
let s = kl_best_response(&tree, &weak, &gto, 0, lambda);
let ev = belief_ev(&tree, &s.clone_with_villain(&tree, &weak));
let expl = villain_br(&tree, &s) - base_br;
println!("{lambda:>8} -> EV {ev:+.5} expl {expl:+.5}");
if lambda == 1e9 {
let ev_gto = belief_ev(&tree, &gto.clone_with_villain(&tree, &weak));
assert!((ev - ev_gto).abs() < 1e-6, "1e9 != gto: {ev} vs {ev_gto}");
assert!(expl.abs() < 1e-6, "gto exploitierbar: {expl}");
assert!((game_value(&tree, &s) - gto_ev).abs() < 1e-6);
}
if let Some((pe, px)) = prev {
assert!(ev >= pe - 1e-9, "EV sinkt bei lambda {lambda}: {pe} -> {ev}");
assert!(expl >= px - 1e-9, "Exploitability sinkt bei lambda {lambda}: {px} -> {expl}");
}
prev = Some((ev, expl));
}
let (ev_end, expl_end) = prev.unwrap();
let ev_gto = belief_ev(&tree, &gto.clone_with_villain(&tree, &weak));
assert!(ev_end > ev_gto + 0.05, "Exploit gewinnt nichts: {ev_end} vs {ev_gto}");
assert!(expl_end > 0.01, "Exploit ohne Preis? {expl_end}");
// lambda = inf exakt gto
assert_eq!(kl_best_response(&tree, &weak, &gto, 0, f64::INFINITY), gto);
}
/// Hilfe: Heldenzeilen aus `self`, Gegnerzeilen aus `villain` (alle Knoten von Spieler 1).
trait CloneWith {
fn clone_with_villain(&self, tree: &Tree, villain: &Strategy) -> Strategy;
}
impl CloneWith for Strategy {
fn clone_with_villain(&self, tree: &Tree, villain: &Strategy) -> Strategy {
let mut out = self.clone();
for (i, node) in tree.nodes.iter().enumerate() {
if let Node::Decision { player: 1, name, .. } = node {
out = out.with_rows(tree, name, |c| villain.row(i, c).to_vec()).unwrap();
}
}
out
}
}
}
+5
View File
@@ -77,6 +77,8 @@ pub mod generated_equity;
pub mod generated_equity_short;
pub mod hand_class;
pub mod iterate;
pub mod kl_br;
pub mod qre;
pub mod leaf_value3;
pub mod multi_shares;
pub mod multi_solve;
@@ -92,6 +94,7 @@ pub mod push_fold_game;
pub mod regret_matching;
pub mod render_charts;
pub mod render_equity;
pub mod river;
pub mod render_multi;
pub mod run_plan;
pub mod seat;
@@ -104,6 +107,8 @@ pub mod terminal_value;
pub mod three_way;
pub mod tree3;
pub mod tree;
pub mod turn;
pub mod turn_river;
pub mod value_walk;
pub mod wake_range;
pub mod walk3;
+286
View File
@@ -0,0 +1,286 @@
//! Logit quantal response equilibrium (QRE): Nash at finite temperature.
//!
//! Every player plays a softmax response to the expected payoffs of its own actions,
//! `sigma(a) ~ exp(beta * Q(a))`, per decision node and hand class, where `Q` is the expected
//! payoff given the class and reaching the node (the counterfactual value divided by the
//! opponent's reach mass). Both players do so against each other: the QRE is the fixed point.
//!
//! - `beta -> inf` (T -> 0): the best response, i.e. a Nash equilibrium of the zero-sum game.
//! - `beta -> 0` (T -> inf): uniform play.
//! - A humans-play-QRE read: fish = small beta, nit / solver = large beta (`fit_temperature`).
//!
//! Solver: the logit flow `d sigma = softmax(beta Q(sigma)) - sigma` integrated with RK4 (plain
//! damped iteration `sigma <- (1-eta) sigma + eta softmax(..)` spirals out at large beta, see
//! `settle`), with beta annealed from 1 up to the target (doubling) so every stage starts at the
//! previous solution (path-following). Step size follows the response gain. Deterministic.
use super::strategy::Strategy;
use super::tree::Tree;
use super::value_walk::{root_values, Responder, Visit};
const TOLERANCE: f64 = 1e-12;
const ETA_MAX: f64 = 0.5;
const ETA_MIN: f64 = 1e-7;
/// Logit-QRE profile at inverse temperature `beta` (T = 1/beta). `iters` is the iteration cap
/// per annealing stage.
pub fn qre(tree: &Tree, beta: f64, iters: u32) -> Strategy {
let start = Strategy::uniform(tree);
if !tree.is_playable() {
return start;
}
let beta = if beta.is_finite() { beta.max(0.0) } else { 1e6 };
stages(beta).into_iter().fold(start, |s, b| settle(tree, s, b, iters))
}
/// Annealing schedule: `[beta]` up to 1, else 1 and then doublings (geometric) up to `beta`.
fn stages(beta: f64) -> Vec<f64> {
if beta <= 1.0 {
return vec![beta];
}
let n = beta.log2().ceil().max(1.0) as i32;
std::iter::once(1.0).chain((1..=n).map(|k| beta.powf(k as f64 / n as f64))).collect()
}
type Field = Vec<(usize, Vec<Vec<f64>>)>;
/// The logit flow `f(sigma) = softmax(beta Q(sigma)) - sigma`, its residual `max|f|` and the
/// gain scale `spread` (largest `beta * (max Q - min Q)`).
fn flow(tree: &Tree, s: &Strategy, beta: f64) -> (Field, f64, f64) {
let (mut field, spread) = logit_targets(tree, s, beta);
let mut residual = 0.0f64;
for (node, rows) in field.iter_mut() {
for (c, row) in rows.iter_mut().enumerate() {
for (t, o) in row.iter_mut().zip(s.row(*node, c)) {
*t -= o;
residual = residual.max(t.abs());
}
}
}
(field, residual, spread)
}
/// `s + sum_k w_k * field_k`, clamped at 0 and renormalised per row.
fn moved(s: &Strategy, fields: &[(&Field, f64)]) -> Strategy {
let nodes = &fields[0].0;
(0..nodes.len()).fold(s.clone(), |acc, i| {
let node = nodes[i].0;
acc.with_node(node, |c| {
let mut row: Vec<f64> = s
.row(node, c)
.iter()
.enumerate()
.map(|(a, o)| (o + fields.iter().map(|(f, w)| w * f[i].1[c][a]).sum::<f64>()).max(0.0))
.collect();
let sum: f64 = row.iter().sum();
row.iter_mut().for_each(|x| *x /= sum);
row
})
})
}
/// Integrate the logit flow at a fixed beta with classic RK4 until the residual is below
/// tolerance (or `iters` steps). Why not plain damping: the flow's linearisation in a zero-sum
/// game is a spiral (real part about -1, imaginary part about beta x payoff scale), where explicit
/// Euler needs a step ~ 1/beta^2 but RK4 is stable up to ~ 1/beta. Step `h = 2 / (1 + spread / 2)`
/// clamped to `[ETA_MIN, ETA_MAX]`; `spread` follows the current gain, so large beta takes small steps.
fn settle(tree: &Tree, start: Strategy, beta: f64, iters: u32) -> Strategy {
let mut s = start;
for _ in 0..iters {
let (k1, residual, spread) = flow(tree, &s, beta);
if residual < TOLERANCE {
break;
}
let h = (1.5 / (1.0 + 0.5 * spread)).clamp(ETA_MIN, ETA_MAX);
let (k2, _, _) = flow(tree, &moved(&s, &[(&k1, h / 2.0)]), beta);
let (k3, _, _) = flow(tree, &moved(&s, &[(&k2, h / 2.0)]), beta);
let (k4, _, _) = flow(tree, &moved(&s, &[(&k3, h)]), beta);
s = moved(&s, &[(&k1, h / 6.0), (&k2, h / 3.0), (&k3, h / 3.0), (&k4, h / 6.0)]);
}
s
}
/// Softmax(beta Q) for every decision node of both players against the profile `s`:
/// `(node, row per class)`. A class that cannot reach the node keeps its current row.
fn logit_targets(tree: &Tree, s: &Strategy, beta: f64) -> (Vec<(usize, Vec<Vec<f64>>)>, f64) {
let n = tree.classes;
let mut out = Vec::new();
let mut spread = 0.0f64;
for player in 0..2 {
root_values(tree, s, Responder::Follow, player, &mut |v: &Visit| {
let rows = (0..n)
.map(|c| {
let mass: f64 = (0..n)
.map(|o| v.opp[o] * if player == 0 { tree.chance[c * n + o] } else { tree.chance[o * n + c] })
.sum();
if mass <= 1e-300 {
return s.row(v.node, c).to_vec();
}
let q: Vec<f64> = v.action_values.iter().map(|a| beta * a[c] / mass).collect();
let top = q.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
let low = q.iter().cloned().fold(f64::INFINITY, f64::min);
spread = spread.max(top - low);
softmax(&q)
})
.collect();
out.push((v.node, rows));
});
}
(out, spread)
}
fn softmax(x: &[f64]) -> Vec<f64> {
let top = x.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
let e: Vec<f64> = x.iter().map(|v| (v - top).exp()).collect();
let sum: f64 = e.iter().sum();
e.iter().map(|v| v / sum).collect()
}
/// Observed action counts of one class at one decision node.
#[derive(Clone, Debug, PartialEq)]
pub struct Observed {
pub node: usize,
pub class: usize,
/// One count (or frequency weight) per action.
pub counts: Vec<f64>,
}
/// Maximum-likelihood inverse temperature for observed actions: log-grid over
/// `[0.01, 1000]`, then golden-section refinement around the best cell. Likelihood need not be
/// unimodal in general; the grid guards against a poor local pick.
pub fn fit_temperature(observed: &[Observed], tree: &Tree) -> f64 {
let loglik = |beta: f64| -> f64 {
let s = qre(tree, beta, 4000);
observed
.iter()
.map(|o| {
let row = s.row(o.node, o.class);
o.counts.iter().zip(row).map(|(k, p)| k * p.max(1e-12).ln()).sum::<f64>()
})
.sum()
};
let (lo, hi, steps) = (0.01f64.ln(), 1000f64.ln(), 40);
let grid: Vec<f64> = (0..=steps).map(|k| lo + (hi - lo) * k as f64 / steps as f64).collect();
let scores: Vec<f64> = grid.iter().map(|x| loglik(x.exp())).collect();
let best = (0..grid.len()).fold(0, |b, k| if scores[k] > scores[b] { k } else { b });
let mut a = grid[best.saturating_sub(1)];
let mut b = grid[(best + 1).min(grid.len() - 1)];
let phi = (5f64.sqrt() - 1.0) / 2.0;
for _ in 0..40 {
let (c, d) = (b - phi * (b - a), a + phi * (b - a));
if loglik(c.exp()) > loglik(d.exp()) {
b = d;
} else {
a = c;
}
}
((a + b) / 2.0).exp()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::cfr::exploitability::{exploitability, game_value};
use crate::cfr::solve::solve;
use crate::cfr::tree::{Node, Payoff};
use crate::rng::Rng;
/// Polarised river: hero holds air or the nuts ([0.5, 0, 0.5]), villain a bluff-catcher
/// ([0, 1, 0]); pot 2, bet 1. Classes: 0 air, 1 bluff-catcher, 2 nuts. Payoffs for hero.
fn river() -> Tree {
let n = 3;
let mut chance = vec![0.0; n * n];
chance[0 * n + 1] = 0.5;
chance[2 * n + 1] = 0.5;
let showdown = |win: f64| Payoff::Pair((0..n * n).map(|k| if k / n == 2 { win } else { -win }).collect());
let nodes = vec![
Node::Decision { player: 0, name: "hero", children: vec![1, 2] },
Node::Terminal(showdown(1.0)), // check: pot 2 split by showdown, +-1
Node::Decision { player: 1, name: "villain", children: vec![3, 4] },
Node::Terminal(Payoff::Flat(1.0)), // villain folds
Node::Terminal(showdown(2.0)), // villain calls: +-2
];
Tree { classes: n, chance, nodes, root: 0 }
}
fn freqs(s: &Strategy, t: &Tree) -> (f64, f64, f64) {
let (h, v) = (t.find("hero").unwrap(), t.find("villain").unwrap());
(s.probability(h, 0, 1), s.probability(h, 2, 1), s.probability(v, 1, 1))
}
#[test]
fn qre_interpolates_between_uniform_and_nash() {
let t = river();
let nash = solve(&t, 20000, Rng::seeded(1));
let (nb, nn, nc) = freqs(&nash.strategy, &t);
println!("Nash (CFR+): bluff {nb:.4} nuts-bet {nn:.4} call {nc:.4}");
assert!((nb - 1.0 / 3.0).abs() < 0.02 && (nc - 2.0 / 3.0).abs() < 0.02);
let betas = [0.01, 0.1, 0.3, 0.5, 1.0, 2.0, 3.0, 5.0, 10.0, 30.0, 100.0, 300.0, 1000.0];
println!(" beta bluff(air) bet(nuts) call(BC) exploit value");
let rows: Vec<(f64, f64, f64, f64)> = betas
.iter()
.map(|&b| {
let s = qre(&t, b, 20000);
let (bl, nu, ca) = freqs(&s, &t);
println!(
"{b:7.2} {bl:.4} {nu:.4} {ca:.4} {:.4} {:.4}",
exploitability(&t, &s),
game_value(&t, &s)
);
(b, bl, nu, ca)
})
.collect();
// beta -> 0: uniform
let (_, bl, nu, ca) = rows[0];
assert!((bl - 0.5).abs() < 0.01 && (nu - 0.5).abs() < 0.01 && (ca - 0.5).abs() < 0.01);
// beta -> inf: Nash frequencies
let (_, bl, nu, ca) = *rows.last().unwrap();
assert!((bl - nb).abs() < 0.03, "bluff {bl} vs nash {nb}");
assert!((ca - nc).abs() < 0.03, "call {ca} vs nash {nc}");
assert!(nu > 0.97);
// Monotone approach. Not monotone from beta = 0: a uniform villain over-folds (call 1/2 <
// 2/3), so air profits from betting and the bluff first RISES above 1/2 (peak ~0.52 near
// beta 0.4) before falling to 1/3; the call frequency likewise overshoots 2/3 (peak ~0.70
// near beta 2) before settling. After the peak both fall monotonically onto Nash.
for w in rows.windows(2) {
assert!(w[1].2 >= w[0].2 - 1e-9, "nuts bet not monotone at beta {}", w[1].0);
if w[0].0 >= 0.5 {
assert!(w[1].1 <= w[0].1 + 1e-9, "bluff not monotone at beta {}", w[1].0);
}
if w[0].0 >= 2.0 {
assert!(w[1].3 <= w[0].3 + 1e-9, "call not monotone at beta {}", w[1].0);
}
if w[0].0 >= 0.3 {
assert!(w[1].0 > 0.0 && (w[1].1 - nb).abs() <= (w[0].1 - nb).abs() + 1e-9);
}
}
assert!(rows.iter().all(|r| r.1 > nb - 1e-3 && r.1 < 0.53));
}
#[test]
fn qre_is_a_fixed_point_and_deterministic() {
let t = river();
let a = qre(&t, 3.0, 20000);
assert_eq!(a, qre(&t, 3.0, 20000));
let again = settle(&t, a.clone(), 3.0, 1);
let (h, v) = (t.find("hero").unwrap(), t.find("villain").unwrap());
assert!((again.probability(h, 0, 1) - a.probability(h, 0, 1)).abs() < 1e-9);
assert!((again.probability(v, 1, 1) - a.probability(v, 1, 1)).abs() < 1e-9);
}
#[test]
fn fit_recovers_temperature() {
let t = river();
let s = qre(&t, 3.0, 20000);
let (h, v) = (t.find("hero").unwrap(), t.find("villain").unwrap());
let obs: Vec<Observed> = [(h, 0), (h, 2), (v, 1)]
.iter()
.map(|&(node, class)| Observed { node, class, counts: s.row(node, class).iter().map(|p| p * 10000.0).collect() })
.collect();
let fit = fit_temperature(&obs, &t);
println!("fit beta = {fit:.3} (true 3)");
assert!((fit - 3.0).abs() < 0.15);
}
}
+161
View File
@@ -0,0 +1,161 @@
//! A heads-up river subgame as a `Tree`, solved by the shared CFR+ core (`solve`).
//!
//! The river is terminal: the board is complete, so there are no chance nodes and a showdown is
//! exact. Hands are abstract **strength buckets**, 0 = weakest, `buckets - 1` = strongest, with a
//! monotone showdown (higher bucket wins, equal buckets split). Both players draw from the same
//! bucket set; `chance[i * buckets + j]` is the joint probability that hero (player 0) holds bucket
//! `i` and villain (player 1) holds bucket `j` (independent product of the two range vectors in this
//! first version; card removal between the ranges is a later refinement).
//!
//! Betting (v1): hero acts first, one bet size `s` (chips), no raises. Hero checks or bets; after a
//! check villain checks (showdown) or bets and hero folds or calls; after a bet villain folds or
//! calls. Enough to reproduce the textbook river results (`tests`): with pot `P` and bet `s`, the
//! polarised bettor's bluff-to-value ratio is `s / (P + s)` and the bluff-catcher defends `P / (P + s)`
//! (minimum defence frequency). Sizes and raises come in later versions.
//!
//! Payoffs are hero's net in chips from the river onward, zero-sum (each player is treated as having
//! put `P/2` into the pot). A showdown for total pot `Q` pays hero `+Q/2` when his bucket is higher,
//! `-Q/2` when lower, `0` on a tie. An uncalled bet returns, so a fold just moves the dead pot `±P/2`.
use super::solve::{solve, Solved};
use super::tree::{Node, Payoff, Tree};
use crate::rng::Rng;
/// A solved heads-up river subgame and the bucket count it was built over.
pub struct RiverSolve {
pub solved: Solved,
pub buckets: usize,
}
impl RiverSolve {
/// Hero's action probabilities at the root (index 0 = check, 1 = bet) for a hand in `bucket`.
pub fn hero_root(&self, bucket: usize) -> Vec<f64> {
self.solved.strategy.row(0, bucket).to_vec()
}
/// Hero's action probabilities facing a bet after checking (node "hero_vs_bet", index 4:
/// 0 = fold, 1 = call) for a hand in `bucket`.
pub fn hero_vs_bet(&self, bucket: usize) -> Vec<f64> {
self.solved.strategy.row(4, bucket).to_vec()
}
}
/// The monotone showdown payoff for a total pot `q`: `+q/2` when hero's bucket beats villain's,
/// `-q/2` when it loses, `0` on a tie.
fn showdown(buckets: usize, q: f64) -> Payoff {
let mut pair = vec![0.0; buckets * buckets];
for i in 0..buckets {
for j in 0..buckets {
pair[i * buckets + j] = match i.cmp(&j) {
std::cmp::Ordering::Greater => q / 2.0,
std::cmp::Ordering::Less => -q / 2.0,
std::cmp::Ordering::Equal => 0.0,
};
}
}
Payoff::Pair(pair)
}
/// The joint deal table `chance[i * buckets + j] = hero[i] * villain[j]`, normalised to sum 1.
/// Independent product (card removal between the two ranges is a later refinement). Falls back to a
/// uniform table when a range is empty or non-finite, so the tree stays playable.
fn chance(hero: &[f64], villain: &[f64]) -> Vec<f64> {
let buckets = hero.len();
let mut table = vec![0.0; buckets * buckets];
let mut total = 0.0;
for i in 0..buckets {
for j in 0..buckets {
let w = (hero[i].max(0.0)) * (villain[j].max(0.0));
let w = if w.is_finite() { w } else { 0.0 };
table[i * buckets + j] = w;
total += w;
}
}
if total > 0.0 {
table.iter_mut().for_each(|x| *x /= total);
} else {
table.iter_mut().for_each(|x| *x = 1.0 / (buckets * buckets) as f64);
}
table
}
/// Build the heads-up river tree over `buckets` strength buckets with an explicit joint deal table
/// `chance[i * buckets + j] = P(hero bucket i, villain bucket j)` (card removal already inside), one
/// bet size `s` (chips) into pot `p`, no raises. Node 0 is hero's root decision (check, bet). This is
/// the card-exact entry point: `sim::exploit_river` builds `chance` from real combos on a real board.
pub fn tree_with_chance(buckets: usize, chance: Vec<f64>, p: f64, s: f64) -> Tree {
let pot_called = p + 2.0 * s;
// Node indices are wired by hand; see the module doc for the shape.
let nodes = vec![
Node::Decision { player: 0, name: "hero", children: vec![1, 2] }, // 0: check -> 1, bet -> 2
Node::Decision { player: 1, name: "v_check", children: vec![3, 4] }, // 1: v check -> 3, v bet -> 4
Node::Decision { player: 1, name: "v_bet", children: vec![5, 6] }, // 2: v fold -> 5, v call -> 6
Node::Terminal(showdown(buckets, p)), // 3: check-check showdown
Node::Decision { player: 0, name: "hero_vs_bet", children: vec![7, 8] }, // 4: hero fold -> 7, call -> 8
Node::Terminal(Payoff::Flat(p / 2.0)), // 5: hero bet, villain folds
Node::Terminal(showdown(buckets, pot_called)), // 6: hero bet, villain calls
Node::Terminal(Payoff::Flat(-p / 2.0)), // 7: hero checks, bets, hero folds
Node::Terminal(showdown(buckets, pot_called)), // 8: hero checks, bets, hero calls
];
Tree { classes: buckets, chance, nodes, root: 0 }
}
/// Build the v1 heads-up river tree: hero first to act, one bet size `s` (chips) into pot `p`,
/// no raises, with the independent-product deal table. Node 0 is hero's root decision (check, bet).
fn tree(hero: &[f64], villain: &[f64], p: f64, s: f64) -> Tree {
tree_with_chance(hero.len(), chance(hero, villain), p, s)
}
/// Solve the v1 heads-up river subgame: hero (player 0) first to act, one bet size `s` chips into
/// pot `p`, no raises. `hero` / `villain` are strength-bucket weight vectors of equal length
/// (0 = weakest). Runs `iterations` of CFR+.
pub fn solve_river(hero: &[f64], villain: &[f64], p: f64, s: f64, iterations: u32, seed: u64) -> RiverSolve {
let t = tree(hero, villain, p, s);
RiverSolve { solved: solve(&t, iterations, Rng::seeded(seed)), buckets: hero.len() }
}
#[cfg(test)]
mod tests {
use super::*;
/// Convergence budget for the toy trees (tiny, so this is plenty).
const ITERS: u32 = 20_000;
const SEED: u64 = 0x5EED_21AA;
/// Polarised river: hero holds only air (bucket 0) and nuts (bucket 2) in equal weight;
/// villain holds only a bluff-catcher (bucket 1). Pot 2, half-pot bet 1. Textbook GTO:
/// - hero value-bets the nuts ~100 %,
/// - hero bluffs the air at the frequency making bluff-to-value = s/(P+s) = 1/3, i.e. since
/// value = all nuts, the air bets ~1/3 of the time,
/// - the bluff-catcher calls at MDF = P/(P+s) = 2/3.
#[test]
fn polarised_river_matches_textbook_gto() {
let hero = [0.5, 0.0, 0.5]; // air, (unused mid), nuts
let villain = [0.0, 1.0, 0.0]; // pure bluff-catcher
let (p, s) = (2.0, 1.0);
let r = solve_river(&hero, &villain, p, s, ITERS, SEED);
let nuts_bet = r.hero_root(2)[1];
let air_bet = r.hero_root(0)[1];
// Villain calling the bluff-catcher facing hero's bet: node "v_bet" (index 2), action 1 = call.
let villain_call = r.solved.strategy.probability(2, 1, 1);
assert!(nuts_bet > 0.95, "nuts should value-bet ~always, got {nuts_bet:.3}");
assert!((air_bet - 1.0 / 3.0).abs() < 0.06, "air bluff freq ~1/3, got {air_bet:.3}");
assert!((villain_call - 2.0 / 3.0).abs() < 0.06, "bluff-catcher calls ~2/3 (MDF), got {villain_call:.3}");
}
/// Quarter-pot bet changes the numbers the same way theory says: bluff-to-value = s/(P+s) and
/// MDF = P/(P+s). Pot 2, bet 0.5: air bluffs ~ (0.5/2.5)=1/5 of the time, villain calls ~ 2/2.5 = 4/5.
#[test]
fn smaller_bet_shifts_frequencies_as_theory_says() {
let hero = [0.5, 0.0, 0.5];
let villain = [0.0, 1.0, 0.0];
let (p, s) = (2.0, 0.5);
let r = solve_river(&hero, &villain, p, s, ITERS, SEED);
let air_bet = r.hero_root(0)[1];
let villain_call = r.solved.strategy.probability(2, 1, 1);
assert!((air_bet - 0.2).abs() < 0.06, "air bluff freq ~1/5, got {air_bet:.3}");
assert!((villain_call - 0.8).abs() < 0.06, "bluff-catcher calls ~4/5, got {villain_call:.3}");
}
}
+5
View File
@@ -59,6 +59,11 @@ impl Strategy {
Ok(self.replaced(index, |class| rows[class].clone()))
}
/// Copy with one node replaced by `row(class)` per class (for solvers outside this module).
pub(crate) fn with_node(&self, index: usize, row: impl Fn(usize) -> Vec<f64>) -> Strategy {
self.replaced(index, row)
}
fn replaced(&self, index: usize, row: impl Fn(usize) -> Vec<f64>) -> Strategy {
let mut probs = self.probs.clone();
probs[index] = (0..self.classes).flat_map(row).collect();
+175
View File
@@ -0,0 +1,175 @@
//! Two-street (turn → river) best-response barrel value over abstract strength buckets.
//!
//! The single-street `engine::bluff::branches` values a bet as `P(fold)·pot + (1−P(fold))·
//! (called_share·final_pot − to)`, and the engine draws `P(fold)` from the villain's *global*
//! profile stat (`exploit::table_fold`, a HUD fold-to-bet). That is the over-barrel leak
//! (BEFUND-nit-read-leck): after the villain has already called a bet, the range that reaches the
//! next street is the strong, *continuing* subset — it folds far less than the global rate. Booking
//! the global fold equity on the river bluff books phantom profit; the narrowed range calls and the
//! barrel bleeds.
//!
//! The fix is to condition the fold equity on *reaching* the street: the river fold probability is
//! what the **narrowed** range actually folds (minimum-defence against the price), not the global
//! stat. Against that, a double-barrel with air is −EV, so best-response checks instead. This module
//! computes that conditioned value and demonstrates the leak as a test.
//!
//! Buckets are abstract strength ranks (higher = stronger) with a monotone showdown. Strength is
//! **static** across the river card in this v1 (no draws completing / board reshuffle); real board
//! runouts are a later refinement. The point proven here — conditioned vs global fold equity — does
//! not depend on reshuffle, because the leak is range *selection*, not the card.
/// A villain range as strength-bucket weights (mass still in play); index 0 = weakest.
pub type Range = Vec<f64>;
/// Total probability mass of a range.
fn mass(r: &[f64]) -> f64 {
r.iter().sum()
}
/// Hero's showdown share against `r`: mass strictly weaker than hero, plus half the ties, over the
/// total. Air (low bucket) against a strong range is ~0; the nuts ~1. Empty range splits (0.5).
fn showdown_share(hero: usize, r: &[f64]) -> f64 {
let total = mass(r);
if total <= 0.0 {
return 0.5;
}
let below: f64 = r.iter().take(hero).sum();
let tie = r.get(hero).copied().unwrap_or(0.0);
(below + 0.5 * tie) / total
}
/// Minimum-defence continue fraction against a bet of `bet` into `pot`: GTO defends `pot/(pot+bet)`
/// of the range (folds `alpha = bet/(pot+bet)`). `lean` scales it — a calling station over-defends
/// (`lean > 1`), a nit over-folds (`lean < 1`); `lean = 1` is the GTO defender. Clamped to [0, 1].
pub fn continue_fraction(bet: f64, pot: f64, lean: f64) -> f64 {
if bet <= 0.0 || pot < 0.0 {
return 1.0;
}
(lean * pot / (pot + bet)).clamp(0.0, 1.0)
}
/// The range that continues against the bet: the villain keeps its strongest hands up to
/// `continue_fraction` of its mass and folds the weak tail. Returns the narrowed weights (same
/// length), so a later street sees only the hands that actually called.
pub fn narrowed(r: &[f64], bet: f64, pot: f64, lean: f64) -> Range {
let keep = continue_fraction(bet, pot, lean) * mass(r);
let mut out = vec![0.0; r.len()];
let mut budget = keep;
// Fill from the strong end down; the last bucket may be partially kept.
for i in (0..r.len()).rev() {
if budget <= 0.0 {
break;
}
let take = r[i].min(budget);
out[i] = take;
budget -= take;
}
out
}
/// Hero's expected chips from the pot if the river checks through to showdown: `share · pot`.
fn check_value(hero: usize, r: &[f64], pot: f64) -> f64 {
showdown_share(hero, r) * pot
}
/// Hero's expected chips from betting `bet` into pot `pot` on the river, **given** the villain folds
/// with probability `fold_prob` and, when called, holds the narrowed continuing range. Matches the
/// `branches` convention: `fold_prob·pot + (1−fold_prob)·(share·final − bet)`, final pot = `pot+2bet`.
///
/// Pass `fold_prob` = the conditioned fold (`1 − continue_fraction` of the *current* range) for the
/// true value; pass a global stat to see the booked (phantom) value the single-street heuristic uses.
pub fn river_bet_value(hero: usize, r: &[f64], pot: f64, bet: f64, fold_prob: f64, lean: f64) -> f64 {
let called = narrowed(r, bet, pot, lean);
let share = showdown_share(hero, &called);
fold_prob * pot + (1.0 - fold_prob) * (share * (pot + 2.0 * bet) - bet)
}
/// Best-response river value for hero: the better of checking and a correctly-priced bet, where the
/// bet's fold equity is **conditioned** on the range that reached the river (minimum defence), not a
/// global stat. This is the value the two-street turn decision should see in its called branch.
pub fn river_best_response(hero: usize, r: &[f64], pot: f64, bet: f64, lean: f64) -> f64 {
let check = check_value(hero, r, pot);
let true_fold = 1.0 - continue_fraction(bet, pot, lean);
let bet_ev = river_bet_value(hero, r, pot, bet, true_fold, lean);
check.max(bet_ev)
}
/// Best-response value of barrelling the turn (vs folding now), river best-responded: the villain
/// folds the turn at the conditioned rate; when called, the pot grows and hero best-responds on the
/// river against the narrowed range (so an air hand checks rather than booking phantom fold equity).
pub fn turn_barrel_value(hero: usize, r: &[f64], pot: f64, turn_bet: f64, river_bet: f64, lean: f64) -> f64 {
let fold = 1.0 - continue_fraction(turn_bet, pot, lean);
let called_range = narrowed(r, turn_bet, pot, lean);
let pot_river = pot + 2.0 * turn_bet;
let river = river_best_response(hero, &called_range, pot_river, river_bet, lean);
fold * pot + (1.0 - fold) * (river - turn_bet)
}
#[cfg(test)]
mod tests {
use super::*;
/// A villain range that is uniform over 10 buckets before any betting.
fn uniform(buckets: usize) -> Range {
vec![1.0 / buckets as f64; buckets]
}
/// Conditioned fold equity fixes the over-barrel: hero holds air (bucket 0); after a turn-sized
/// river bet the continuing range is strong and folds little, so best-response CHECKS — the river
/// bet is −EV against the hands that got there.
#[test]
fn best_response_checks_air_on_the_river() {
let r = uniform(10);
let pot = 6.0; // a pot already swollen by earlier streets
let bet = 4.0; // two-thirds pot
let lean = 1.0; // GTO defender
let check = check_value(0, &r, pot);
let true_fold = 1.0 - continue_fraction(bet, pot, lean);
let bet_ev = river_bet_value(0, &r, pot, bet, true_fold, lean);
assert!(bet_ev < check, "air river bet {bet_ev:.3} must be worse than checking {check:.3}");
// Best-response takes the check.
assert!((river_best_response(0, &r, pot, bet, lean) - check).abs() < 1e-9);
}
/// The leak, reproduced: with the GLOBAL fold stat (a nit's 0.82) the river bluff BOOKS a profit
/// above checking, so the single-street heuristic barrels — but the REALIZED value, using the
/// true conditioned fold of the narrowed range, is below checking. Booked > check > realized.
#[test]
fn global_fold_stat_books_phantom_barrel_profit() {
let r = uniform(10);
let pot = 6.0;
let bet = 4.0;
let lean = 1.0;
let global_fold = 0.82; // the nit's unconditional fold-to-bet (BEFUND-nit-read-leck)
let check = check_value(0, &r, pot);
let booked = river_bet_value(0, &r, pot, bet, global_fold, lean);
let realized = river_bet_value(0, &r, pot, bet, 1.0 - continue_fraction(bet, pot, lean), lean);
assert!(booked > check, "the global stat must book a barrel (booked {booked:.3} > check {check:.3})");
assert!(realized < check, "but the realized barrel loses (realized {realized:.3} < check {check:.3})");
}
/// A value hand does the opposite: the nuts (top bucket) best-responds by betting, because the
/// narrowed calling range still pays off.
#[test]
fn best_response_value_bets_the_nuts() {
let r = uniform(10);
let pot = 6.0;
let bet = 4.0;
let lean = 1.2; // a slightly loose caller, so value gets paid
let check = check_value(9, &r, pot);
let br = river_best_response(9, &r, pot, bet, lean);
assert!(br > check + 1e-9, "the nuts should bet for value: br {br:.3} > check {check:.3}");
}
/// Narrowing keeps the strong end and conserves the kept mass.
#[test]
fn narrowing_keeps_the_strong_tail() {
let r = uniform(10);
let pot = 4.0;
let bet = 4.0; // alpha = 1/2, GTO defends half
let n = narrowed(&r, bet, pot, 1.0);
assert!((mass(&n) - 0.5).abs() < 1e-9, "half the mass continues, got {:.3}", mass(&n));
assert_eq!(n[0], 0.0, "the weakest bucket folds");
assert!(n[9] > 0.0, "the strongest bucket continues");
}
}
+217
View File
@@ -0,0 +1,217 @@
//! A heads-up TURN subgame as a `Tree`, depth-limited to one betting round with the value of the
//! river folded into the leaves. The betting shape is identical to the river tree (`cfr::river`):
//! hero acts first, one bet size, no raises. The difference is the terminal that would be a river
//! showdown: here the turn is NOT the last street, so the three "reach the river" terminals carry a
//! **leaf value matrix** `V[i * buckets + j]` = hero's expected chips over the whole river *given*
//! the turn buckets `(i, j)`, instead of a static showdown.
//!
//! This is the DeepStack/endgame construction: solve only the turn decisions, and evaluate each
//! river-reaching leaf by the equilibrium value of the river subgame it leads to (precomputed by the
//! caller, averaged over the runout, via the existing `cfr::river` solver). Because the CFR core
//! (`solve`, `terminal_value`, `kl_br`, `exploitability`) is street-agnostic and `terminal_value`
//! reads an arbitrary `Payoff::Pair`, no core change is needed — only this builder and the leaf
//! precompute. When the leaf is set to a plain monotone showdown, this tree is byte-identical to
//! `cfr::river::tree_with_chance` (see tests), so the turn solve degrades gracefully to the river one.
//!
//! Buckets are TURN strength classes (0 = weakest), `chance[i * buckets + j]` the joint turn deal
//! table with card removal already inside. Payoffs are hero's (player 0) net in chips, zero-sum, each
//! player treated as having put `p / 2` into the turn pot: a turn fold moves the dead pot `±p/2`; a
//! river-reaching leaf pays the precomputed `V`, which itself nets the river play to hero's chips.
use super::solve::{solve, Solved};
use super::strategy::Strategy;
use super::tree::{Node, Payoff, Tree};
use crate::rng::Rng;
/// A solved heads-up turn subgame and the turn-bucket count it was built over.
pub struct TurnSolve {
pub solved: Solved,
pub buckets: usize,
}
impl TurnSolve {
/// Hero's action probabilities at the root (0 = check, 1 = bet) for a hand in turn `bucket`.
pub fn hero_root(&self, bucket: usize) -> Vec<f64> {
self.solved.strategy.row(0, bucket).to_vec()
}
/// Hero's action probabilities facing a turn bet after checking (node "hero_vs_bet", index 4:
/// 0 = fold, 1 = call) for a hand in turn `bucket`.
pub fn hero_vs_bet(&self, bucket: usize) -> Vec<f64> {
self.solved.strategy.row(4, bucket).to_vec()
}
}
/// Build the heads-up turn tree over `buckets` turn-strength buckets with an explicit joint deal
/// table `chance[i * buckets + j] = P(hero turn-bucket i, villain turn-bucket j)` (card removal
/// inside), turn pot `p`, and two river leaf-value matrices (each `buckets * buckets`, hero's net
/// chips over the river):
/// - `leaf_check`: the river reached via a turn CHECK-CHECK (river starts at pot `p`),
/// - `leaf_bet`: the river reached via a CALLED turn bet (river starts at the larger pot).
///
/// Node 0 is hero's root decision (check, bet). Shape mirrors `cfr::river::tree_with_chance`; the
/// bet size enters only through the leaf matrices the caller computed, so it is not a parameter here.
pub fn tree_with_leaf(buckets: usize, chance: Vec<f64>, p: f64, leaf_check: Vec<f64>, leaf_bet: Vec<f64>) -> Tree {
debug_assert_eq!(chance.len(), buckets * buckets, "chance table must be buckets^2");
debug_assert_eq!(leaf_check.len(), buckets * buckets, "leaf_check must be buckets^2");
debug_assert_eq!(leaf_bet.len(), buckets * buckets, "leaf_bet must be buckets^2");
let nodes = vec![
Node::Decision { player: 0, name: "hero", children: vec![1, 2] }, // 0: check -> 1, bet -> 2
Node::Decision { player: 1, name: "v_check", children: vec![3, 4] }, // 1: v check -> 3, v bet -> 4
Node::Decision { player: 1, name: "v_bet", children: vec![5, 6] }, // 2: v fold -> 5, v call -> 6
Node::Terminal(Payoff::Pair(leaf_check)), // 3: turn check-check -> river
Node::Decision { player: 0, name: "hero_vs_bet", children: vec![7, 8] }, // 4: hero fold -> 7, call -> 8
Node::Terminal(Payoff::Flat(p / 2.0)), // 5: hero bet, villain folds (uncalled)
Node::Terminal(Payoff::Pair(leaf_bet.clone())), // 6: hero bet, villain calls -> river
Node::Terminal(Payoff::Flat(-p / 2.0)), // 7: hero checks, villain bets, hero folds
Node::Terminal(Payoff::Pair(leaf_bet)), // 8: hero checks, villain bets, hero calls -> river
];
Tree { classes: buckets, chance, nodes, root: 0 }
}
/// Hero's (player 0) payoff at a terminal for a fixed class pair `(i, j)` — the raw per-deal result,
/// before the chance/opponent-reach weighting the solver applies.
fn hero_payoff(payoff: &Payoff, n: usize, i: usize, j: usize) -> f64 {
match payoff {
Payoff::Flat(c) => *c,
Payoff::Own(v) => v.get(i).copied().unwrap_or(0.0),
Payoff::Pair(m) => m.get(i * n + j).copied().unwrap_or(0.0),
Payoff::Raked { pair, .. } => pair.get(i * n + j).copied().unwrap_or(0.0),
}
}
/// Hero's expected net chips for every class pair `(i, j)` under a fixed `strategy`:
/// `out[i * classes + j] = E[hero payoff | hero class i, villain class j, both follow `strategy`]`.
///
/// A forward walk conditioned on the pair (no chance/reach weighting — that is applied outside, by
/// the parent tree's own `chance` table). This is exactly the matrix a depth-limited parent street
/// needs as a `Payoff::Pair` leaf: solve the river subgame, then `pair_values` reads the equilibrium
/// value per river-bucket pair. Invariant (checked in tests): weighting `out` by the tree's `chance`
/// reproduces `value_walk::root_values(Follow, 0)`.
pub fn pair_values(tree: &Tree, strategy: &Strategy) -> Vec<f64> {
let n = tree.classes;
let mut out = vec![0.0; n * n];
for i in 0..n {
for j in 0..n {
out[i * n + j] = eval_pair(tree, strategy, tree.root, i, j);
}
}
out
}
/// Expected hero payoff from `node` for the fixed class pair `(i, j)` under `strategy`.
fn eval_pair(tree: &Tree, strategy: &Strategy, node: usize, i: usize, j: usize) -> f64 {
match &tree.nodes[node] {
Node::Terminal(payoff) => hero_payoff(payoff, tree.classes, i, j),
Node::Chance(branches) => branches.iter().map(|(p, child)| p * eval_pair(tree, strategy, *child, i, j)).sum(),
Node::Decision { player, children, .. } => {
let class = if *player == 0 { i } else { j };
children
.iter()
.enumerate()
.map(|(a, child)| strategy.probability(node, class, a) * eval_pair(tree, strategy, *child, i, j))
.sum()
}
}
}
/// Solve a heads-up turn subgame built by `tree_with_leaf`. Runs `iterations` of the shared CFR+ core.
pub fn solve_turn(buckets: usize, chance: Vec<f64>, p: f64, leaf_check: Vec<f64>, leaf_bet: Vec<f64>, iterations: u32, seed: u64) -> TurnSolve {
let t = tree_with_leaf(buckets, chance, p, leaf_check, leaf_bet);
TurnSolve { solved: solve(&t, iterations, Rng::seeded(seed)), buckets }
}
#[cfg(test)]
mod tests {
use super::*;
use crate::cfr::river::tree_with_chance;
use crate::cfr::value_walk::{root_values, Responder};
const ITERS: u32 = 20_000;
const SEED: u64 = 0x5EED_7117;
/// A monotone showdown matrix for total pot `q` (the river builder's private `showdown`, inlined).
fn showdown_vec(buckets: usize, q: f64) -> Vec<f64> {
let mut pair = vec![0.0; buckets * buckets];
for i in 0..buckets {
for j in 0..buckets {
pair[i * buckets + j] = match i.cmp(&j) {
std::cmp::Ordering::Greater => q / 2.0,
std::cmp::Ordering::Less => -q / 2.0,
std::cmp::Ordering::Equal => 0.0,
};
}
}
pair
}
/// Normalised joint deal table `hero[i] * villain[j]` (the river builder's private `chance`).
fn joint(hero: &[f64], villain: &[f64]) -> Vec<f64> {
let n = hero.len();
let mut t = vec![0.0; n * n];
let mut total = 0.0;
for i in 0..n {
for j in 0..n {
let w = hero[i].max(0.0) * villain[j].max(0.0);
t[i * n + j] = w;
total += w;
}
}
if total > 0.0 {
t.iter_mut().for_each(|x| *x /= total);
} else {
t.iter_mut().for_each(|x| *x = 1.0 / (n * n) as f64);
}
t
}
/// With the river folded in as a plain showdown (no river betting), the turn tree is byte-identical
/// to the river tree — `tree_with_leaf` is a faithful generalisation, so the depth-limited solve
/// degrades exactly to the one-street solve.
#[test]
fn showdown_leaf_reproduces_the_river_tree_exactly() {
let buckets = 3;
let (p, s) = (2.0, 1.0);
let chance = joint(&[0.5, 0.0, 0.5], &[0.0, 1.0, 0.0]);
let turn = tree_with_leaf(buckets, chance.clone(), p, showdown_vec(buckets, p), showdown_vec(buckets, p + 2.0 * s));
let river = tree_with_chance(buckets, chance, p, s);
assert_eq!(turn, river, "a showdown leaf must reproduce the river tree node-for-node");
}
/// `pair_values` reads back the exact leaf the pure strategy forces: hero always checks, villain
/// always checks → the check-check leaf, for every pair.
#[test]
fn pair_values_reads_back_the_forced_leaf() {
let buckets = 3;
let p = 2.0;
let leaf_check: Vec<f64> = (0..buckets * buckets).map(|k| k as f64 + 1.0).collect(); // arbitrary, distinct
let leaf_bet = vec![-9.0; buckets * buckets];
let tree = tree_with_leaf(buckets, joint(&[1.0, 1.0, 1.0], &[1.0, 1.0, 1.0]), p, leaf_check.clone(), leaf_bet);
// Pure: hero checks (action 0 at "hero"), villain checks (action 0 at "v_check").
let pure = Strategy::pure(&tree, |_, _| 0); // every node's action 0: hero check, villain check
let got = pair_values(&tree, &pure);
assert_eq!(got, leaf_check, "check-check must land on the check-check leaf for every pair");
}
/// The core invariant tying `pair_values` to the solver's own value: weighting the per-pair matrix
/// by the tree's `chance` reproduces `root_values(Follow, hero)` exactly. This is what lets a parent
/// street trust `pair_values` as its leaf.
#[test]
fn pair_values_weighted_by_chance_equals_root_values() {
let buckets = 3;
let (p, s) = (2.0, 1.0);
let chance = joint(&[0.4, 0.2, 0.4], &[0.1, 0.6, 0.3]);
let turn = tree_with_leaf(buckets, chance.clone(), p, showdown_vec(buckets, p), showdown_vec(buckets, p + 2.0 * s));
let solved = solve(&turn, ITERS, Rng::seeded(SEED));
let pv = pair_values(&turn, &solved.strategy);
let rv = root_values(&turn, &solved.strategy, Responder::Follow, 0, &mut |_| {});
for i in 0..buckets {
let weighted: f64 = (0..buckets).map(|j| chance[i * buckets + j] * pv[i * buckets + j]).sum();
assert!(
(weighted - rv[i]).abs() < 1e-9,
"class {i}: chance-weighted pair_values {weighted} != root_values {}",
rv[i]
);
}
}
}
+46 -8
View File
@@ -15,7 +15,7 @@ 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_pressure, jam_width_factor, width_factor};
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;
@@ -34,7 +34,7 @@ fn trials(spot: &Spot) -> u32 {
/// 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) -> Decision {
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,
@@ -52,6 +52,13 @@ fn postflop(spot: &Spot, thresholds: &Thresholds) -> Decision {
}
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,
@@ -62,8 +69,32 @@ fn postflop(spot: &Spot, thresholds: &Thresholds) -> Decision {
};
match estimate(&query, Rng::seeded(spot.seed)) {
Ok((equity, _)) => {
choose_postflop_with(spot, &equity, &called_equity(spot), thresholds, &hand_read)
.with_equity(equity.share)
// 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 {
return super::river_subgame::fold_veto(raw, floored);
}
floored
}
Err(fault) => Decision::abstain(format!("equity unavailable: {fault}")),
}
@@ -82,7 +113,7 @@ fn with_premium(thresholds: Thresholds, premium: f64) -> Thresholds {
}
}
fn think(spot: &Spot, premium: f64, jam_widen: f64) -> Decision {
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 {
@@ -93,7 +124,7 @@ fn think(spot: &Spot, premium: f64, jam_widen: f64) -> Decision {
let certainty = plan.certainty.max(MIN_CERTAINTY);
from_plan(spot, &PreflopPlan { certainty, ..plan })
}
Street::Flop | Street::Turn | Street::River => postflop(spot, &thresholds),
Street::Flop | Street::Turn | Street::River => postflop(spot, &thresholds, raw, premium),
}
}
@@ -110,6 +141,7 @@ 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,
@@ -118,8 +150,14 @@ pub fn decide_with(spot: &Spot, lage: Option<&Turnierlage>) -> Decision {
};
// 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.
let jam_widen = lage.and_then(|l| jam_pressure(spot, l)).map(jam_width_factor).unwrap_or(1.0);
let decision = enforce(spot, think(spot, premium, jam_widen));
// 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,
+2
View File
@@ -16,9 +16,11 @@ 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_subgame;
pub mod uncertainty;
+128
View File
@@ -10,6 +10,7 @@ use crate::exploit::thresholds::Thresholds;
use crate::game::{ActionKind, Choice, Decision, Spot};
use crate::odds::{break_even::break_even, ev};
use crate::read::hand_read::HandRead;
use crate::rng::Rng;
fn label(choice: Choice, kind: Option<RaiseKind>) -> String {
match (choice, kind) {
@@ -29,6 +30,79 @@ fn best(options: &[Scored]) -> Option<Scored> {
})
}
/// EV-indifference band for size mixing: raise sizes within `MIX_BAND` standard errors (in
/// chips) of the best are treated as tied. Half a standard error is a conservative tie — well
/// inside what the equity estimate can resolve. Overridable via `SIZE_MIX_BAND` (read once) for
/// a width sweep. The mix only ever deviates from the argmax (never to a higher-EV size), so a
/// wider band trades a larger by-construction point-estimate bias for more unpredictability:
/// paired ladder (vs the deterministic baseline) measured 1.0σ at −0.56 ±0.95 bb/100 / 227 spots
/// and 0.5σ at −0.23 ±0.59 / 112 spots — both indistinguishable from zero; 0.5σ is the default
/// as the cleaner ≥0 proof that still mixes where sizes are genuinely tied. See
/// BEFUND-size-mix-ev-neutral.md.
const MIX_BAND: f64 = 0.5;
fn mix_band() -> f64 {
use std::sync::OnceLock;
static BAND: OnceLock<f64> = OnceLock::new();
*BAND.get_or_init(|| {
std::env::var("SIZE_MIX_BAND")
.ok()
.and_then(|v| v.parse::<f64>().ok())
.filter(|&b| b.is_finite() && b >= 0.0)
.unwrap_or(MIX_BAND)
})
}
/// Decorrelates the size-mix draw from the equity Monte-Carlo stream, which seeds off
/// `spot.seed` directly. Any fixed non-zero salt works.
const MIX_SALT: u64 = 0x5F3B_C1D2_7A49_E6B5;
/// Measurement toggle (read once): `SIZE_MIX=0` disables size mixing so one run can measure the
/// engine with mixing on vs off on the same deals (paired). Default on.
fn size_mix_enabled() -> bool {
use std::sync::OnceLock;
static ON: OnceLock<bool> = OnceLock::new();
*ON.get_or_init(|| std::env::var("SIZE_MIX").as_deref() != Ok("0"))
}
/// Among the raise sizes within `error` chips of the winning raise (EV-indistinguishable under
/// the equity estimate), a seeded draw picks one. Pure: the winner is returned unchanged unless
/// it is a raise with two or more tied raise sizes. EV-neutral by construction — it only ever
/// swaps between statistically tied sizes.
fn pick_mixed(options: &[Scored], winner: Scored, error: f64, seed: u64) -> Scored {
if !matches!(winner.choice, Choice::Raise { .. }) || error <= 0.0 {
return winner;
}
let tied: Vec<Scored> = options
.iter()
.copied()
.filter(|s| matches!(s.choice, Choice::Raise { .. }) && winner.ev - s.ev <= error)
.collect();
if tied.len() <= 1 {
return winner;
}
let (idx, _) = Rng::seeded(seed).below(tied.len() as u64);
tied[idx as usize]
}
/// Equilibrium play mixes its bet sizes; a pure argmax over sizes is in principle readable (a
/// thinking villain clusters "big size => value"). Where two or more raise sizes are EV-tied
/// (within one standard error of the equity estimate), hero cannot tell them apart, so it draws
/// one — seeded off `spot.seed`, so paired runs stay reproducible and only the mixed spots
/// differ from the deterministic line. Only raise sizes mix; check/call/fold never do. Because
/// it only swaps between statistically tied sizes it is EV-neutral by construction: safe against
/// the non-adjusting fish/stations the ladder's edge rests on, and it can never be a measured
/// loser. The gain is only against villains who would otherwise read a fixed size.
fn mix_size(spot: &Spot, estimate: &Estimate, options: &[Scored], winner: Scored) -> Scored {
if !size_mix_enabled() {
return winner;
}
let Choice::Raise { to } = winner.choice else {
return winner;
};
let error = mix_band() * estimate.std_error.max(0.0) * ev::final_pot(spot.pot, spot.to_call, to);
pick_mixed(options, winner, error, spot.seed ^ MIX_SALT)
}
/// EV lead of the winner over the next-best alternative, counting folding (0) and the
/// call it passed up.
fn lead(spot: &Spot, share: f64, options: &[Scored], winner: Scored) -> f64 {
@@ -141,6 +215,9 @@ pub fn choose_postflop_with(
}
}
// The abstain gate above decided WHETHER to raise on the best size; once committed, mix the
// SIZE among EV-tied raises so the line is not a readable pure argmax (EV-neutral, seeded).
let winner = winner.map(|w| mix_size(spot, estimate, &options, w));
priced(match winner {
Some(w) => {
let shown = match w.choice {
@@ -167,3 +244,54 @@ pub fn choose_postflop_with(
},
})
}
#[cfg(test)]
mod size_mix_tests {
use super::*;
fn raise(to: f64, ev: f64) -> Scored {
Scored { choice: Choice::Raise { to }, ev, kind: Some(RaiseKind::Value) }
}
#[test]
fn mix_only_swaps_between_ev_tied_sizes() {
// Top raise 10.0; 9.8 is within the 0.5 band (gap 0.2), 5.0 is well outside.
let options = vec![raise(2.0, 10.0), raise(3.0, 9.8), raise(4.0, 5.0)];
let winner = raise(2.0, 10.0);
let mut seen: std::collections::BTreeSet<u64> = Default::default();
for seed in 0..64u64 {
let picked = pick_mixed(&options, winner, 0.5, seed);
match picked.choice {
Choice::Raise { to } => {
assert!(to == 2.0 || to == 3.0, "mixed into a non-tied size {to}");
seen.insert(to.to_bits());
}
other => panic!("mix changed the action to {other:?}"),
}
}
assert_eq!(seen.len(), 2, "did not draw across both tied sizes");
}
#[test]
fn mix_is_a_no_op_without_a_tie() {
let options = vec![raise(2.0, 10.0), raise(3.0, 5.0)];
let winner = raise(2.0, 10.0);
for seed in 0..16u64 {
assert_eq!(pick_mixed(&options, winner, 0.5, seed).choice, winner.choice);
}
}
#[test]
fn mix_never_touches_a_non_raise_winner() {
let call = Scored { choice: Choice::Call, ev: 1.0, kind: None };
let options = vec![call, raise(2.0, 10.0)];
assert_eq!(pick_mixed(&options, call, 5.0, 7).choice, Choice::Call);
}
#[test]
fn zero_error_is_deterministic() {
let options = vec![raise(2.0, 10.0), raise(3.0, 10.0)];
let winner = raise(2.0, 10.0);
assert_eq!(pick_mixed(&options, winner, 0.0, 3).choice, winner.choice);
}
}
+50 -12
View File
@@ -1,26 +1,64 @@
//! "Never worse than blind." Measured on the ladder, the exploit logic only beats solid blind play
//! against clearly-weak, over-calling opponents (calling stations / fish). Acting on a read of a
//! competent or aggressive opponent (reg / nit / maniac) makes the engine play WORSE than blind - it
//! bleeds to a heads-up reg (−102 bb/100 with a truthful read). Until the exploit logic earns the
//! right to adjust against them (proven on the ladder, fed by real strong-player data), the engine
//! keeps a read ONLY for the proven-profitable weak class and plays everyone else blind.
//! against opponents whose read it has EARNED. Acting on a read of a competent or aggressive
//! opponent (reg / maniac) makes the engine play WORSE than blind - it bleeds to a heads-up reg
//! (−102 bb/100 with a truthful read). Until a style's read is proven on the ladder (fed by real
//! data), the engine keeps a read ONLY for the earned styles and plays everyone else blind.
//!
//! This can never make a read harmful: it only ever acts where acting is known to help, and falls
//! back to the solid baseline everywhere else. Same spirit as the price/commitment floor - a read,
//! like a loose table, may never tip us into a worse decision.
//! The gate is a per-style table (`earned_trust`), not a single hard-coded class: each style is
//! turned on only once its `... (blind)` twin in `sim::benchmark` proves the read never costs. This
//! can never make a read harmful: it only ever acts where acting is known to help, and falls back to
//! the solid baseline everywhere else. Same spirit as the price/commitment floor - a read, like a
//! loose table, may never tip us into a worse decision.
use crate::exploit::style::{classify, Style};
use crate::game::{Spot, Villain};
/// A read is acted on only when it marks a clearly-weak, over-calling opponent - the one class the
/// exploit logic is measured to beat blind play against. Every other style falls back to blind.
/// How much of a read's adjustment each opponent style has EARNED on the ladder — the measured right
/// to deviate from blind play. `1.0` = exploit in full, `0.0` = keep playing blind (the read is
/// dropped at the gate). This generalizes the old CallingStation-only gate into a per-style table,
/// so a style is turned on only once its read is proven never worse than blind (the `... (blind)`
/// twins in `sim::benchmark` / `benchmarks/baseline.txt`).
///
/// Only `> 0.0` is consumed today (keep-or-drop at the gate); the shift shapes themselves live in
/// `exploit::style_shift` and apply in full to whatever survives the gate. The value is an `f64`,
/// not a bool, to leave room for a partial, confidence-weighted trust later without changing this
/// seam.
pub fn earned_trust(style: Style) -> f64 {
match style {
// Over-callers (fish, station): value-bet thinner, never bluff. Earned since Stage 0 — the
// `heads-up ... (blind)` twins show a large recaptured prize.
Style::CallingStation => 1.0,
// Measured on the ladder (Stage 3, every non-style run at full trust against the blind
// baseline): acting on a strong-player read only ever COSTS. Heads-up, a truthful read is
// worse than blind by reg −176, maniac −148, nit −50 bb/100 — the nit turns a +38 blind
// winner into a loser. The decision-trace diagnostic (Stage 5, `sim_blind::
// diagnose_nit_full_read_leak`) localized the nit leak: it is not under-barrelling but the
// OPPOSITE — the read turns flop CHECKS into bluff-RAISES (140 hands, −436 of −596 bb total),
// because `table_fold` now sees the nit's true 0.82 fold rate and the single-street bluff-EV
// books `0.82 × pot` as near-pure profit. The 18 % that continue hold a nutted range and
// bleed across turn and river, a multi-street cost the single-street called branch never
// models. The DEFENSIVE adjustments of the same read all GAIN (fold more thin value / bluff
// catchers into a proven non-bluffer) and are already harvested by the ungated MDF floor
// (`mdf_floor::floor` on the raw spot in `engine::decide`); this gate governs only the
// OFFENSIVE adjustments, which over-fire into strong ranges. So every non-over-caller stays
// blind until the bluff-EV models the multi-street cost of a called barrel (BEFUND-nit-read-leck).
Style::Regular => 0.0,
Style::Nit => 0.0,
Style::LooseAggressive => 0.0,
// No usable read.
Style::Unknown => 0.0,
}
}
/// A read is acted on only when its style has earned trust on the ladder - the classes the exploit
/// logic is measured to beat blind play against. Every other style falls back to blind.
pub fn exploit_worthy(style: Style) -> bool {
matches!(style, Style::CallingStation)
earned_trust(style) > 0.0
}
/// The spot with every opponent read the engine is not (yet) proven to use profitably dropped to
/// `None`, so the decision plays blind against competent and aggressive opponents and only exploits
/// the weak.
/// the earned styles.
pub fn gate_reads(spot: &Spot) -> Spot {
let villains = spot
.villains
+641
View File
@@ -0,0 +1,641 @@
//! Engine bridge from a live river spot to the pure CFR river solver (`cfr::river`).
//!
//! This is the Stage-A wiring: it turns the engine's own belief (the villain range model, as built
//! in `engine::decide::postflop`) into strength buckets, solves the heads-up river subgame to
//! equilibrium, and reads back hero's **mixed** action for the bucket its real hand sits in. All
//! poker-specific sourcing lives here; the solver stays a pure game over abstract buckets.
//!
//! # What changed from the first slice (and why it matters for exploitability)
//!
//! The first version solved with hero as a revealed **point mass** (one known hand) and then
//! collapsed the equilibrium mix to its majority action. Both make the line maximally exploitable:
//! a point-mass hero lets the solved villain best-respond to hero's exact strength (no need to
//! balance), and a pure readback cannot bluff or defend at the right frequency. Against a villain
//! that best-responds over hero's TRUE range, that bleeds — which the postflop-exploitability
//! harness (`sim::exploit_river`) measured at 32–108 bb/100.
//!
//! This version models hero with the **same strength distribution as the villain** (a symmetric
//! river prior — both players reach the river with strength spread over the board's quantiles) and
//! returns the equilibrium **mix** for hero's bucket. That is a balanced RANGE strategy: value
//! buckets bet, a calibrated fraction of air bluffs (bluff-to-value `s/(P+s)`), bluff-catchers
//! defend at MDF `P/(P+s)`. Live play realises the mix from the spot seed; the harness reads the
//! frequency directly.
//!
//! # Slice (v1)
//!
//! **Heads-up river**, both hero nodes of the solver's tree:
//! - hero first to act (`to_call == 0`) → check / bet,
//! - hero facing a bet (`to_call > 0`, the pre-bet pot `pot - to_call`, bet `to_call`) → fold / call.
//!
//! Multiway, or a villain range the engine cannot enumerate, returns `None` so the caller keeps the
//! heuristic. The solver equilibrium is the unexploitable baseline; whether wiring it into live play
//! also holds the bb/100 ladder is a measured question, not an assumption.
//!
//! # Named approximations
//!
//! - Hero's river range is modelled as the villain's strength distribution, not hero's true line-
//! consistent range. The closer the two, the lower the residual exploitability.
//! - The villain range is cut into `BUCKETS` equal-count (quantile) buckets, so a higher bucket index
//! always wins the showdown; the quantile cut makes the modelled distribution uniform over buckets.
//! - The solver's action abstraction is one bet size, no raises (`cfr::river` v1).
use crate::card::Card;
use crate::cfr::kl_br::kl_best_response;
use crate::cfr::river::tree_with_chance;
use crate::cfr::solve::{solve, Solved};
use crate::cfr::strategy::Strategy;
use crate::cfr::tree::Tree;
use crate::exploit::fold_chance::DEFAULT_FOLD_TO_BET;
use crate::exploit::posterior::DEFAULT_AGGRESSION;
use crate::exploit::profile::Profile;
use crate::game::{Choice, Decision, Spot, Street};
use crate::hand::showdown::judge;
use crate::hand::strength::Strength;
use crate::rng::Rng;
use crate::sizing::candidates::candidates;
/// CFR+ iterations per live solve. Enough for the tiny tree (9 nodes) to converge; an
/// under-converged solve is itself exploitable, so this is not shaved.
const ITERS: u32 = 12_000;
/// Target bet size as a fraction of the pot; the nearest legal candidate is used.
const TARGET_BET_FRACTION: f64 = 0.66;
// --- Belief + trust gearbox (the crown): turn the read into a believed villain strategy and a KL
// trust radius, so the solver EXPLOITS a known opponent instead of balancing against it, bounded by
// how much the read is trusted. λ = ∞ (no read) returns the proven-unexploitable GTO mix. ---
/// Normalised ladder rank at/above which the believed villain value-bets when checked to (top buckets).
const VALUE_RANK: f64 = 0.60;
/// Normalised ladder rank at/below which the believed villain may bluff when checked to (bottom buckets).
const BLUFF_RANK: f64 = 0.30;
/// Chip-scale of the KL radius at confidence 0.5 (as a fraction of the subgame pot). λ is in payoff
/// (chip) units; tying it to the pot keeps the trust radius scale-free across spot sizes. The map is
/// `λ = LAMBDA_POT_SCALE · pot · (1−c)/c`: c→0 ⇒ λ→∞ (pure GTO), c→1 ⇒ λ→0 (full best response).
const LAMBDA_POT_SCALE: f64 = 1.0;
/// Below this read confidence the gearbox stands down (returns `None`) and the proven heuristic keeps
/// the blind/exploit edge. Rationale: at a weak read λ is huge and the tilt collapses to near-GTO,
/// and GTO river play is itself worse than the heuristic against an unread exploitable field (the −43
/// revert). So the solver only takes over once the read is strong enough to EXPLOIT, never to balance.
const CONFIDENCE_FLOOR: f64 = 0.25;
/// Hero's equilibrium mix at the river node the spot sits on.
pub struct RiverPlan {
/// `true` = hero is facing a bet (`mix` is `[fold, call]`); `false` = hero acts first
/// (`mix` is `[check, bet]`).
pub facing: bool,
/// The two action probabilities for hero's bucket, in the order above.
pub mix: [f64; 2],
/// The bet-to total when acting first (the raise size); `0` facing a bet.
pub bet_to: f64,
/// Human reason for the decision log.
pub reason: String,
}
impl RiverPlan {
/// Probability of the aggressive action (bet, or call facing a bet).
fn forward(&self) -> f64 {
self.mix[1]
}
}
/// The legal bet-to total nearest `TARGET_BET_FRACTION * pot`, or `None` if nothing is bettable.
fn bet_to(spot: &Spot) -> Option<f64> {
let target = TARGET_BET_FRACTION * spot.pot;
candidates(spot)
.into_iter()
.filter(|to| *to > 0.0 && *to <= spot.hero_stack)
.min_by(|a, b| (a - target).abs().total_cmp(&(b - target).abs()))
}
/// Two hole-card hands can be dealt together only if they share no card.
fn disjoint(a: &[Card], b: &[Card]) -> bool {
a.iter().all(|c| !b.contains(c))
}
/// A solved card-exact river subgame plus the shared strength ladder, so hero's real hand can be
/// placed on the same buckets the solve used. The `tree` is kept so the belief/trust gearbox can
/// best-respond to a believed villain (`kl_best_response`) over the same game the GTO solve used.
struct Subgame {
tree: Tree,
solved: Solved,
ladder: Vec<Strength>,
}
impl Subgame {
/// The bucket a strength sits in on the shared ladder (its ascending rank, clamped to the top).
fn bucket(&self, s: Strength) -> usize {
self.ladder.partition_point(|d| *d < s).min(self.ladder.len() - 1)
}
}
/// Build and solve the card-exact heads-up river subgame the engine believes it is in. Hero's range
/// is modelled as the villain's believed range (`hero_combos == villain_combos`, a symmetric river
/// prior); both are bucketed by **exact showdown strength** on one shared ascending ladder, and the
/// joint deal table carries **card removal** between the two ranges — the same construction the
/// exploitability harness uses for the true game. This faithfulness is what lets the equilibrium it
/// plays actually be unexploitable; the coarse symmetric-uniform first cut was not, and measured
/// worse than the heuristic. `None` for fewer than two distinct strengths.
fn subgame(spot: &Spot, hero_combos: &[Vec<Card>], villain_combos: &[Vec<Card>], pot: f64, bet: f64) -> Option<Subgame> {
let rules = spot.rules();
let judged = |combos: &[Vec<Card>]| -> Vec<(Vec<Card>, Strength)> {
combos.iter().filter_map(|c| judge(&rules, c, &spot.board).ok().map(|s| (c.clone(), s))).collect()
};
let hero = judged(hero_combos);
let villain = judged(villain_combos);
if hero.is_empty() || villain.is_empty() {
return None;
}
let mut ladder: Vec<Strength> = hero.iter().chain(&villain).map(|(_, s)| *s).collect();
ladder.sort();
ladder.dedup();
let n = ladder.len();
if n < 2 {
return None;
}
let bucket = |s: Strength| ladder.partition_point(|d| *d < s).min(n - 1);
let mut chance = vec![0.0; n * n];
for (hc, hs) in &hero {
let hb = bucket(*hs);
for (vc, vs) in &villain {
if disjoint(hc, vc) {
chance[hb * n + bucket(*vs)] += 1.0;
}
}
}
let total: f64 = chance.iter().sum();
if total <= 0.0 {
return None;
}
chance.iter_mut().for_each(|x| *x /= total);
let tree = tree_with_chance(n, chance, pot, bet);
let solved = solve(&tree, ITERS, Rng::seeded(spot.seed));
Some(Subgame { tree, solved, ladder })
}
/// The believed villain strategy over the river tree, read off the opponent's `Profile`: how this
/// specific opponent plays the two villain nodes, as opposed to the balanced GTO villain the
/// symmetric solve assumes. `kl_best_response` best-responds hero toward this belief, bounded by λ.
///
/// - **`v_bet` `[fold, call]`** (villain facing hero's bet): folds the weakest `fold_to_bet` fraction
/// of the ladder by rank, calls the rest. A calling station (low fold-to-bet) calls almost
/// everything → hero value-bets thin and never bluffs; an over-folder folds more → hero bluffs.
/// - **`v_check` `[check, bet]`** (villain checked to): value-bets the top buckets, bluffs the bottom
/// buckets at a frequency scaled from the read's `aggression` around the GTO bluff ratio
/// `s/(P+s)`. A tight under-bluffer bets a value-heavy range → hero folds its bluff-catchers (the
/// river-overbet-defense fix); a maniac over-bluffs → hero calls down.
///
/// `aggression` is passed in by the caller so it can be STREET-SPECIFIC (the turn gearbox feeds turn
/// aggression, the river gearbox river aggression, each falling back to the pooled read). A single
/// pooled aggression under-sells a turn-barreler's turn bluffing and made the defensive veto fold a
/// good call against aggressive opponents; the per-street value fixes that misfire. `None` → the GTO
/// default. Only the two villain rows matter to `kl_best_response` (it keeps hero's GTO rows); the
/// base is a uniform strategy over the same tree, so the node widths line up.
pub(crate) fn believed_villain(tree: &Tree, n: usize, profile: Option<&Profile>, pot: f64, bet: f64, aggression: Option<f64>) -> Strategy {
let f = profile.and_then(|p| p.fold_to_bet).filter(|x| !x.is_nan()).unwrap_or(DEFAULT_FOLD_TO_BET).clamp(0.0, 1.0);
let a = aggression.filter(|x| !x.is_nan()).unwrap_or(DEFAULT_AGGRESSION).clamp(0.0, 1.0);
let rank = |c: usize| if n <= 1 { 1.0 } else { c as f64 / (n - 1) as f64 };
let gto_bluff = if pot + bet > 0.0 { bet / (pot + bet) } else { 0.0 };
let bluff_prob = if DEFAULT_AGGRESSION > 0.0 { (gto_bluff * a / DEFAULT_AGGRESSION).clamp(0.0, 1.0) } else { 0.0 };
let base = Strategy::uniform(tree);
let with_call = base
.with_rows(tree, "v_bet", |c| if rank(c) >= f { vec![0.0, 1.0] } else { vec![1.0, 0.0] })
.unwrap_or(base);
with_call
.with_rows(tree, "v_check", |c| {
let r = rank(c);
let bet_p = if r >= VALUE_RANK {
1.0
} else if r <= BLUFF_RANK {
bluff_prob
} else {
0.0
};
vec![1.0 - bet_p, bet_p]
})
.unwrap_or(with_call)
}
/// The KL trust radius from the read's confidence (payoff/chip units). `λ = LAMBDA_POT_SCALE · pot ·
/// (1−c)/c`: no confidence (`None`/0) → `∞` → `kl_best_response` returns exact GTO (the proven
/// unexploitable baseline — it can never again balance against a fish it cannot read); confidence → 1
/// → `λ → 0` → full best response to the believed villain. Monotone decreasing in `c`.
pub(crate) fn lambda_from_confidence(confidence: Option<f64>, pot: f64) -> f64 {
let c = confidence.filter(|x| !x.is_nan()).unwrap_or(0.0).clamp(0.0, 0.999);
if c <= 0.0 {
return f64::INFINITY;
}
LAMBDA_POT_SCALE * pot.max(0.0) * (1.0 - c) / c
}
/// Solve the heads-up river subgame from the engine's belief (`villain_combos`) and return hero's
/// equilibrium mix at the node the spot sits on, or `None` when the v1 slice does not apply (the
/// caller then keeps the heuristic).
pub fn river_plan(spot: &Spot, villain_combos: &[Vec<Card>]) -> Option<RiverPlan> {
if spot.street != Street::River {
return None;
}
if spot.live_villains().count() != 1 || villain_combos.is_empty() {
return None;
}
let rules = spot.rules();
let hero_strength = judge(&rules, &spot.hero_cards, &spot.board).ok()?;
if spot.to_call == 0.0 {
let bet = bet_to(spot)?;
let game = subgame(spot, villain_combos, villain_combos, spot.pot, bet)?;
let hb = game.bucket(hero_strength);
let probs = game.solved.strategy.row(0, hb).to_vec(); // [check, bet]
let bet_p = probs.get(1).copied().unwrap_or(0.0);
Some(RiverPlan {
facing: false,
mix: [probs.first().copied().unwrap_or(1.0 - bet_p), bet_p],
bet_to: bet,
reason: format!("river subgame: bucket {hb}/{}, p(bet) {bet_p:.2}", game.ladder.len()),
})
} else {
// Facing a bet: the solver's pre-bet pot is `pot - to_call`, the bet is `to_call`.
let p = spot.pot - spot.to_call;
let bet = spot.to_call;
if p <= 0.0 || bet <= 0.0 {
return None;
}
let game = subgame(spot, villain_combos, villain_combos, p, bet)?;
let hb = game.bucket(hero_strength);
let row = game.solved.strategy.row(4, hb).to_vec(); // [fold, call]
let call_p = row.get(1).copied().unwrap_or(0.0);
Some(RiverPlan {
facing: true,
mix: [row.first().copied().unwrap_or(1.0 - call_p), call_p],
bet_to: 0.0,
reason: format!("river subgame: bucket {hb}/{} facing bet, p(call) {call_p:.2}", game.ladder.len()),
})
}
}
/// The belief + trust version of `river_plan`: solve the subgame for GTO, then tilt hero's strategy
/// toward best-responding to the **believed** villain (`believed_villain`, from `profile`) inside a
/// KL ball of radius λ (`lambda_from_confidence`, from the read's confidence). Returns hero's tilted
/// mix at the node the spot sits on.
///
/// This is the fix for the −43 "balanced vs a fish" revert: a strong read exploits (value-bets thin,
/// folds under-bluffed overbets), a weak or absent read collapses to the proven-unexploitable GTO
/// mix (λ → ∞). `None` outside the v1 slice, so the caller keeps the heuristic.
pub fn river_exploit_plan(spot: &Spot, villain_combos: &[Vec<Card>], profile: Option<&Profile>) -> Option<RiverPlan> {
if spot.street != Street::River {
return None;
}
if spot.live_villains().count() != 1 || villain_combos.is_empty() {
return None;
}
// Only exploit on a read strong enough to trust; otherwise the heuristic keeps the edge.
if profile.and_then(|p| p.confidence).filter(|c| !c.is_nan()).unwrap_or(0.0) < CONFIDENCE_FLOOR {
return None;
}
let rules = spot.rules();
let hero_strength = judge(&rules, &spot.hero_cards, &spot.board).ok()?;
let (pot, bet, facing) = if spot.to_call == 0.0 {
(spot.pot, bet_to(spot)?, false)
} else {
let p = spot.pot - spot.to_call;
if p <= 0.0 || spot.to_call <= 0.0 {
return None;
}
(p, spot.to_call, true)
};
let game = subgame(spot, villain_combos, villain_combos, pot, bet)?;
let n = game.ladder.len();
let opponent = believed_villain(&game.tree, n, profile, pot, bet, profile.and_then(|p| p.river_aggression.or(p.aggression)));
let lambda = lambda_from_confidence(profile.and_then(|p| p.confidence), pot);
let tilted = kl_best_response(&game.tree, &opponent, &game.solved.strategy, 0, lambda);
let hb = game.bucket(hero_strength);
// Node 0 "hero" [check, bet] when first to act; node 4 "hero_vs_bet" [fold, call] facing a bet.
let node = if facing { 4 } else { 0 };
let row = tilted.row(node, hb).to_vec();
let forward = row.get(1).copied().unwrap_or(0.0);
Some(RiverPlan {
facing,
mix: [row.first().copied().unwrap_or(1.0 - forward), forward],
bet_to: if facing { 0.0 } else { bet },
reason: format!(
"river gearbox: bucket {hb}/{n}{}, λ {:.2}, p(fwd) {forward:.2}",
if facing { " facing bet" } else { "" },
lambda
),
})
}
/// Below this believed call frequency the defensive veto folds: when the KL-bounded best response to
/// the believed villain calls hero's bucket less than half the time, the believed bet is value-heavy
/// enough that the heuristic's call is −EV. A full 0.5 keeps the veto to clear under-bluff reads.
const VETO_CALL_FLOOR: f64 = 0.5;
/// Defensive river veto: on a confident read that the villain UNDER-bluffs its bet, fold a heuristic
/// CALL that the belief+trust gearbox would not make. This is the gearbox's one proven edge — the
/// single-street heuristic over-calls under-bluffed river overbets (nemesis-3) because its range model
/// carries the GTO bluff share a tight bettor does not have. Everything else is left to the heuristic:
/// the veto only ever turns a call into a fold facing a bet, never touches a bet/check/raise, and
/// stands down on a thin read (confidence floor) or off the heads-up river slice.
///
/// Safe by construction against the −43/−48 "balanced vs a fish" regression: it cannot change hero's
/// OFFENSE, only decline a call the read prices as losing. The caller gates it to cash (no ICM premium).
pub fn fold_veto(spot: &Spot, base: Decision) -> Decision {
if base.choice != Choice::Call {
return base;
}
let Some(plan) = river_exploit_mix(spot) else {
return base;
};
if !plan.facing || plan.mix[1] >= VETO_CALL_FLOOR {
return base;
}
Decision {
choice: Choice::Fold,
reason: format!("defensive veto: {} (heuristic would call)", plan.reason),
..base
}
}
/// Realise a `RiverPlan` into a concrete decision, mixing from the spot seed (deterministic per spot,
/// correct frequency across the range of deals). Confidence rises as the mix leaves 50/50.
pub fn realize(spot: &Spot, plan: &RiverPlan) -> Decision {
let (draw, _) = Rng::seeded(spot.seed).unit();
let aggressive = draw < plan.forward();
let choice = match (plan.facing, aggressive) {
(false, true) => Choice::Raise { to: plan.bet_to },
(false, false) => Choice::Check,
(true, true) => Choice::Call,
(true, false) => Choice::Fold,
};
let confidence = 0.5 + (plan.forward() - 0.5).abs();
Decision::new(choice, confidence, plan.reason.clone())
}
/// Build the villain belief combos the way `decide::postflop` does (gated reads, enumerated range)
/// and return hero's river mix — the measurement entry point for `sim::exploit_river`, faithful to
/// what the live engine would play. `None` when the slice does not apply.
pub fn river_mix(spot: &Spot) -> Option<RiverPlan> {
if spot.street != Street::River {
return None;
}
let gated = crate::engine::read_gate::gate_reads(spot);
let spot = &gated;
if spot.live_villains().count() != 1 {
return None;
}
let villain = spot.live_villains().next()?;
let rules = spot.rules();
let filter = crate::engine::range_filter::range_filter(
&crate::exploit::range_model::range_spec(spot, villain),
rules,
spot.variant,
&spot.board,
);
let dead: Vec<Card> = spot.hero_cards.iter().chain(&spot.board).copied().collect();
let list = crate::engine::range_combos::combos(&rules, &filter, &dead)?;
river_plan(spot, &list)
}
/// Live entry for the belief + trust gearbox: source the villain belief range from the **raw**
/// (ungated) read and hand the solver the opponent's real `Profile` (tendencies + confidence). The
/// gate that blinds the heuristic is not applied here — the KL trust radius (λ from confidence) is
/// the gearbox's own safety, so it reads the true opponent and the floor keeps it from acting on a
/// thin read. `None` outside the v1 slice or below the confidence floor, so the caller keeps the
/// heuristic.
pub fn river_exploit_mix(spot: &Spot) -> Option<RiverPlan> {
if spot.street != Street::River {
return None;
}
if spot.live_villains().count() != 1 {
return None;
}
let villain = spot.live_villains().next()?;
let profile = villain.profile.as_ref();
let rules = spot.rules();
let filter = crate::engine::range_filter::range_filter(
&crate::exploit::range_model::range_spec(spot, villain),
rules,
spot.variant,
&spot.board,
);
let dead: Vec<Card> = spot.hero_cards.iter().chain(&spot.board).copied().collect();
let list = crate::engine::range_combos::combos(&rules, &filter, &dead)?;
river_exploit_plan(spot, &list, profile)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::game::{ActionKind, Villain};
use crate::variant::Variant;
/// A heads-up river spot where hero is first to act into `pot` with check or a two-thirds bet.
fn river_to_act(board: &[Card], hero: &str, pot: f64) -> Spot {
Spot {
variant: Variant::Nlhe,
big_blind: 1.0,
seats: 2,
hero_seat: 1,
button_seat: Some(1),
hero_cards: Card::parse_list(hero).unwrap(),
board: board.to_vec(),
street: Street::River,
pot,
to_call: 0.0,
hero_stack: pot * 4.0,
min_raise_to: Some(pot * 0.66),
max_raise_to: Some(pot * 4.0),
legal: vec![ActionKind::Check, ActionKind::Raise],
allowed_sizes: Some(vec![pot * 0.66]),
villains: vec![Villain { seat: 2, stack: pot * 4.0, folded: false, profile: None }],
seed: 0x5EED_B17E,
history: Vec::new(),
}
}
/// A river spot the slice accepts (heads-up, hero to act) returns a mix, and a strong made hand
/// leans to betting. Guards the wiring, not the exact frequency.
#[test]
fn a_made_hand_to_act_gets_a_river_mix_that_leans_to_bet() {
let board = Card::parse_list("Ah Kd 7c 2s 9h").unwrap();
let villain: Vec<Vec<Card>> = ["Ad Jc", "Qh Qd", "Jd Jh", "8c 8d", "6h 6d", "5c 4c", "Td 9c", "Kc Qc"]
.iter()
.map(|c| Card::parse_list(c).unwrap())
.collect();
let spot = river_to_act(&board, "Ac As", 6.0); // overpair-strength: top two on this board
let plan = river_plan(&spot, &villain).expect("heads-up river to-act is in slice");
assert!(!plan.facing);
assert!(plan.bet_to > 0.0);
assert!(
plan.forward() > 0.5,
"a strong made hand should lean to betting, got p(bet) {:.2}",
plan.forward()
);
}
// --- belief + trust gearbox ---
use crate::cfr::river::tree_with_chance;
fn prof(fold_to_bet: f64, aggression: f64, confidence: f64) -> Profile {
Profile {
fold_to_bet: Some(fold_to_bet),
aggression: Some(aggression),
confidence: Some(confidence),
..Default::default()
}
}
fn uniform_tree(n: usize, pot: f64, bet: f64) -> Tree {
tree_with_chance(n, vec![1.0 / (n * n) as f64; n * n], pot, bet)
}
/// λ is ∞ without a read (⇒ kl_br returns exact GTO), finite with one, and falls as the read
/// strengthens; at confidence 0.5 it is exactly `LAMBDA_POT_SCALE · pot`.
#[test]
fn lambda_falls_as_confidence_rises_and_is_infinite_without_a_read() {
assert!(lambda_from_confidence(None, 6.0).is_infinite());
assert!(lambda_from_confidence(Some(0.0), 6.0).is_infinite());
let mid = lambda_from_confidence(Some(0.5), 6.0);
let high = lambda_from_confidence(Some(0.9), 6.0);
assert!(mid.is_finite() && high.is_finite());
assert!(high < mid, "λ must fall as confidence rises: {high} !< {mid}");
assert!((mid - LAMBDA_POT_SCALE * 6.0).abs() < 1e-9, "c=0.5 ⇒ λ = pot·scale");
}
/// The believed villain facing a bet calls a wider slice of the ladder when it is a low-fold
/// station than when it is a high-fold over-folder.
#[test]
fn a_believed_station_calls_wider_than_a_believed_overfolder() {
let n = 6;
let tree = uniform_tree(n, 2.0, 1.0);
let station = believed_villain(&tree, n, Some(&prof(0.10, 0.35, 0.8)), 2.0, 1.0, Some(0.35));
let overfolder = believed_villain(&tree, n, Some(&prof(0.80, 0.35, 0.8)), 2.0, 1.0, Some(0.35));
// node 2 "v_bet", action 1 = call.
let calls = |s: &Strategy| (0..n).filter(|&c| s.probability(2, c, 1) > 0.5).count();
assert!(
calls(&station) > calls(&overfolder),
"station calls wider: {} vs {}",
calls(&station),
calls(&overfolder)
);
}
/// The believed villain bluffs its air (bottom bucket) more when checked to the more aggressive
/// the read — a passive under-bluffer bets a value-heavy range.
#[test]
fn a_believed_aggressive_villain_bluffs_more_when_checked_to() {
let n = 10;
let tree = uniform_tree(n, 2.0, 1.0);
let passive = believed_villain(&tree, n, Some(&prof(0.45, 0.10, 0.8)), 2.0, 1.0, Some(0.10));
let maniac = believed_villain(&tree, n, Some(&prof(0.45, 0.80, 0.8)), 2.0, 1.0, Some(0.80));
// node 1 "v_check", bucket 0 = air, action 1 = bet.
assert!(
maniac.probability(1, 0, 1) > passive.probability(1, 0, 1),
"a maniac bluffs its air more: {} !> {}",
maniac.probability(1, 0, 1),
passive.probability(1, 0, 1)
);
}
fn river_to_act_vs(board: &[Card], hero: &str, pot: f64, profile: Option<Profile>) -> Spot {
Spot {
villains: vec![Villain { seat: 2, stack: pot * 4.0, folded: false, profile }],
..river_to_act(board, hero, pot)
}
}
fn sample_villain() -> Vec<Vec<Card>> {
["Ad Jc", "Qh Qd", "Jd Jh", "8c 8d", "6h 6d", "5c 4c", "Td 9c", "Kc Qc"]
.iter()
.map(|c| Card::parse_list(c).unwrap())
.collect()
}
/// Below the confidence floor the gearbox stands down (`None`) so the heuristic keeps the edge.
#[test]
fn the_gearbox_stands_down_below_the_confidence_floor() {
let board = Card::parse_list("Ah Kd 7c 2s 9h").unwrap();
let villain = sample_villain();
let thin = river_to_act_vs(&board, "Ac As", 6.0, Some(prof(0.2, 0.3, 0.10)));
assert!(
river_exploit_plan(&thin, &villain, thin.live_villains().next().unwrap().profile.as_ref()).is_none(),
"confidence 0.10 < floor ⇒ no plan"
);
let confident = river_to_act_vs(&board, "Ac As", 6.0, Some(prof(0.2, 0.3, 0.80)));
assert!(
river_exploit_plan(&confident, &villain, confident.live_villains().next().unwrap().profile.as_ref()).is_some(),
"confidence 0.80 ≥ floor ⇒ a plan"
);
}
/// A confident calling-station read makes hero value-bet a strong made hand (exploit, not balance).
#[test]
fn a_confident_station_read_value_bets_a_strong_hand() {
let board = Card::parse_list("Ah Kd 7c 2s 9h").unwrap();
let villain = sample_villain();
let spot = river_to_act_vs(&board, "Ac As", 6.0, Some(prof(0.08, 0.15, 0.85)));
let plan = river_exploit_plan(&spot, &villain, spot.live_villains().next().unwrap().profile.as_ref())
.expect("confident heads-up river to-act is in slice");
assert!(!plan.facing);
assert!(plan.forward() > 0.5, "value-bet a strong hand into a station, got p(bet) {:.2}", plan.forward());
}
/// A heads-up river spot where hero faces a `bet` into the pre-bet pot `pot`, with fold or call.
fn river_vs_bet(board: &[Card], hero: &str, pot: f64, bet: f64, profile: Option<Profile>) -> Spot {
Spot {
variant: Variant::Nlhe,
big_blind: 1.0,
seats: 2,
hero_seat: 1,
button_seat: Some(1),
hero_cards: Card::parse_list(hero).unwrap(),
board: board.to_vec(),
street: Street::River,
pot: pot + bet,
to_call: bet,
hero_stack: pot * 4.0,
min_raise_to: None,
max_raise_to: None,
legal: vec![ActionKind::Fold, ActionKind::Call],
allowed_sizes: None,
villains: vec![Villain { seat: 2, stack: pot * 4.0, folded: false, profile }],
seed: 0x5EED_B17E,
history: Vec::new(),
}
}
/// The core nemesis-3 mechanism the defensive veto rides on: a confident read that the villain
/// UNDER-bluffs its river bet (tight, passive) best-responds hero's bluff-catcher toward a FOLD
/// (believed call frequency below the veto floor), where the single-street heuristic would call.
#[test]
fn a_confident_underbluff_read_folds_a_bluff_catcher_facing_a_bet() {
let board = Card::parse_list("Ah Kd 7c 2s 9h").unwrap();
let villain = sample_villain();
// Jc Js: a genuine bluff-catcher on this A-K-high board — it loses to the villain's value
// (AJ=aces, KQ=kings, QQ) and beats only the bottom (99, 88, 66, 54). Vs a believed
// UNDER-bluffer the bet is value-heavy, so calling is −EV and the gearbox folds.
let spot = river_vs_bet(&board, "Jc Js", 6.0, 6.0, Some(prof(0.30, 0.06, 0.85)));
let plan = river_exploit_plan(&spot, &villain, spot.live_villains().next().unwrap().profile.as_ref())
.expect("confident heads-up river vs-bet is in slice");
assert!(plan.facing, "facing a bet");
assert!(
plan.mix[1] < VETO_CALL_FLOOR,
"a bluff-catcher vs a believed under-bluffer should fold (p(call) {:.2} < {VETO_CALL_FLOOR})",
plan.mix[1]
);
}
/// The veto never touches hero's offense: a base that is not a call is returned unchanged even
/// though a plan exists (guards against the −43/−48 full-replacement regression returning).
#[test]
fn the_veto_leaves_a_non_call_decision_untouched() {
let board = Card::parse_list("Ah Kd 7c 2s 9h").unwrap();
let spot = river_vs_bet(&board, "Qc Qd", 6.0, 6.0, Some(prof(0.30, 0.06, 0.85)));
let check = Decision::new(Choice::Check, 0.7, "heuristic check");
assert_eq!(fold_veto(&spot, check.clone()), check, "a non-call base is never vetoed");
}
}
+596
View File
@@ -0,0 +1,596 @@
//! Engine bridge from a live TURN spot to the depth-limited turn+river CFR solver
//! (`cfr::turn_river`). The turn-street analogue of `engine::river_subgame`, one street deeper.
//!
//! # Construction (Option B: depth-limited turn, river-equilibrium leaf)
//!
//! The turn is NOT the last street, so a turn showdown is not exact — what a turn line is worth
//! depends on how the river then plays. This bridge solves only the turn betting round and evaluates
//! each "reach the river" leaf by the **equilibrium value of the river subgame** it leads to,
//! averaged over the runout:
//!
//! 1. Source the villain belief range (gated reads → `range_spec` → `range_filter` → `combos`), the
//! same pipeline as the river. Hero is modelled with the same range (symmetric prior), as on the
//! river. Bucket both by **turn** strength (`judge` on the 4-card board) into one shared ladder.
//! 2. For every river card (`deck::without_in` over the turn board), solve the heads-up river subgame
//! (`cfr::river`) at the two possible river-start pots (turn checked through, and a called turn
//! bet), and read its equilibrium value per river-bucket pair (`cfr::turn_river::pair_values`).
//! Fold those values back onto the **turn** buckets, weighted by card removal, to get two leaf
//! matrices `V_check[i][j]` and `V_bet[i][j]` (hero's expected river chips given the turn buckets).
//! 3. Build the turn tree (`cfr::turn_river::tree_with_leaf`) with those leaves and solve it. Read
//! hero's mixed action for the bucket its real turn hand sits in.
//!
//! This is the proven river construction lifted one street: the CFR core is unchanged, the leaf is a
//! real equilibrium value (not an equity guess), and when the river leaf degenerates to a showdown
//! the turn tree is identical to the river tree (`cfr::turn_river` tests). Multiway, or a range the
//! engine cannot enumerate, returns `None` and the caller keeps the heuristic.
//!
//! # Named approximations (beyond the river's own)
//!
//! - Hero's turn range is the villain's believed range (symmetric prior), as on the river.
//! - Turn and river buckets are equal-strength quantile cuts; a higher bucket wins the showdown on
//! that street. The leaf averages the river value over runouts at the combo level (card removal of
//! the river card is exact per pair), then aggregates to turn buckets.
//! - River sub-solves use one bet size (`cfr::river` v1) at `TARGET_BET_FRACTION` of the pot; the turn
//! likewise. Raises and multiple sizes are later versions.
use crate::card::{deck, Card};
use crate::cfr::kl_br::kl_best_response;
use crate::cfr::river::tree_with_chance;
use crate::cfr::solve::solve;
use crate::cfr::tree::Tree;
use crate::cfr::turn_river::{pair_values, tree_with_leaf};
use crate::engine::river_subgame::{believed_villain, lambda_from_confidence};
use crate::exploit::profile::Profile;
use crate::game::{Choice, Decision, Spot, Street};
use crate::hand::showdown::judge;
use crate::hand::strength::Strength;
use crate::rng::Rng;
use crate::sizing::candidates::candidates;
/// CFR+ iterations for the turn solve (tiny 9-node tree).
const TURN_SOLVE_ITERS: u32 = 6_000;
/// CFR+ iterations for each river sub-solve that feeds a leaf value. These feed an averaged value, not
/// a live decision, so a lighter budget than the live river solver (12k) is enough.
const RIVER_LEAF_ITERS: u32 = 3_000;
/// Target bet size as a fraction of the pot; the nearest legal candidate is used (turn), the exact
/// fraction is used for the river sub-solves.
const TARGET_BET_FRACTION: f64 = 0.66;
/// Below this read confidence the turn gearbox stands down (the heuristic keeps the edge). Mirrors the
/// river gearbox: at a weak read λ is huge and the tilt collapses to near-GTO, and a balanced turn line
/// is worse than the heuristic against an unread exploitable field.
const CONFIDENCE_FLOOR: f64 = 0.25;
/// Below this believed call frequency the defensive veto folds a heuristic turn call: the believed
/// (KL-bounded) best response calls hero's bucket less than half the time, so the believed turn bet is
/// value-heavy enough that the call is −EV. The turn analogue of the proven river `VETO_CALL_FLOOR`.
const VETO_CALL_FLOOR: f64 = 0.5;
/// Measurement toggle (read once): `TURN_VETO=0` disables the live turn veto so a single run can
/// measure the engine with the veto on vs off on the same deals (paired). Default on. Not read on the
/// hot path beyond the first call.
fn veto_enabled() -> bool {
use std::sync::OnceLock;
static ON: OnceLock<bool> = OnceLock::new();
*ON.get_or_init(|| std::env::var("TURN_VETO").as_deref() != Ok("0"))
}
/// CFR+ iterations per river leaf solve, overridable via `TURN_LEAF_ITERS` (read once) for a
/// speed/accuracy sweep — the dominant cost is `~44` of these per turn build. The default
/// `RIVER_LEAF_ITERS` leaves behaviour bit-identical; a lower value trades leaf-value precision for
/// speed. A non-numeric or zero value falls back to the default.
fn river_leaf_iters() -> u32 {
use std::sync::OnceLock;
static ITERS: OnceLock<u32> = OnceLock::new();
*ITERS.get_or_init(|| {
std::env::var("TURN_LEAF_ITERS")
.ok()
.and_then(|v| v.parse::<u32>().ok())
.filter(|&n| n > 0)
.unwrap_or(RIVER_LEAF_ITERS)
})
}
/// Hero's equilibrium mix at the turn node the spot sits on.
pub struct TurnPlan {
/// `true` = hero faces a turn bet (`mix` is `[fold, call]`); `false` = hero acts first
/// (`mix` is `[check, bet]`).
pub facing: bool,
/// The two action probabilities for hero's bucket, in the order above.
pub mix: [f64; 2],
/// The bet-to total when acting first; `0` facing a bet.
pub bet_to: f64,
/// Human reason for the decision log.
pub reason: String,
}
impl TurnPlan {
/// Probability of the aggressive action (bet, or call facing a bet).
pub fn forward(&self) -> f64 {
self.mix[1]
}
}
/// The legal bet-to total nearest `TARGET_BET_FRACTION * pot`, or `None` if nothing is bettable.
fn bet_to(spot: &Spot) -> Option<f64> {
let target = TARGET_BET_FRACTION * spot.pot;
candidates(spot)
.into_iter()
.filter(|to| *to > 0.0 && *to <= spot.hero_stack)
.min_by(|a, b| (a - target).abs().total_cmp(&(b - target).abs()))
}
/// Two hole-card hands can be dealt together only if they share no card.
fn disjoint(a: &[Card], b: &[Card]) -> bool {
a.iter().all(|c| !b.contains(c))
}
/// A solved turn subgame plus the shared turn-strength ladder, so hero's real hand can be placed on
/// the same buckets the solve used.
struct TurnGame {
tree: Tree,
solved: crate::cfr::solve::Solved,
ladder: Vec<Strength>,
}
impl TurnGame {
fn bucket(&self, s: Strength) -> usize {
self.ladder.partition_point(|d| *d < s).min(self.ladder.len() - 1)
}
}
/// Build the two river leaf-value matrices (`V_check`, `V_bet`) over the turn buckets by solving the
/// river subgame for every runout at both river-start pots and folding the equilibrium values back
/// onto the turn buckets with exact card removal. `turn_n` is the turn-bucket count, `turn_bucket`
/// maps a combo's turn strength to its bucket, `p`/`s` the turn pot and bet.
fn river_leaves(
spot: &Spot,
hero: &[(Vec<Card>, usize)], // (combo, turn bucket)
villain: &[(Vec<Card>, usize)],
turn_n: usize,
p: f64,
s: f64,
) -> Option<(Vec<f64>, Vec<f64>)> {
let rules = spot.rules();
let (pot_check, s_check) = (p, TARGET_BET_FRACTION * p);
let pot_bet = p + 2.0 * s;
let s_bet = TARGET_BET_FRACTION * pot_bet;
let mut leaf_check = vec![0.0; turn_n * turn_n];
let mut leaf_bet = vec![0.0; turn_n * turn_n];
let mut counts = vec![0.0; turn_n * turn_n];
let rivers = deck::without_in(rules.deck, &spot.board);
for r in &rivers {
let mut board5 = spot.board.clone();
board5.push(*r);
// River strengths of the combos that can still be dealt with this river out.
let judged = |src: &[(Vec<Card>, usize)]| -> Vec<(Vec<Card>, usize, Strength)> {
src.iter()
.filter(|(c, _)| !c.contains(r))
.filter_map(|(c, tb)| judge(&rules, c, &board5).ok().map(|st| (c.clone(), *tb, st)))
.collect()
};
let rh = judged(hero);
let rv = judged(villain);
if rh.is_empty() || rv.is_empty() {
continue;
}
// Shared river ladder (ascending, deduped) over both ranges on this runout.
let mut rladder: Vec<Strength> = rh.iter().chain(&rv).map(|(_, _, st)| *st).collect();
rladder.sort();
rladder.dedup();
let m = rladder.len();
let rbucket = |st: Strength| rladder.partition_point(|d| *d < st).min(m.saturating_sub(1));
// A degenerate river (one strength level): the showdown is always a split, river value 0
// around either pot. Still counts toward the average, contributing 0.
if m < 2 {
for (hc, tbh, _) in &rh {
for (vc, tbv, _) in &rv {
if disjoint(hc, vc) {
counts[tbh * turn_n + tbv] += 1.0;
}
}
}
continue;
}
// River joint deal table over river buckets, card removal between the two ranges (the river
// card is already removed by construction).
let mut rchance = vec![0.0; m * m];
for (hc, _, hst) in &rh {
let hb = rbucket(*hst);
for (vc, _, vst) in &rv {
if disjoint(hc, vc) {
rchance[hb * m + rbucket(*vst)] += 1.0;
}
}
}
let total: f64 = rchance.iter().sum();
if total <= 0.0 {
continue;
}
rchance.iter_mut().for_each(|x| *x /= total);
// Equilibrium river value per river-bucket pair, at each river-start pot.
let seed = spot.seed ^ u64::from(r.index());
let tree_check = tree_with_chance(m, rchance.clone(), pot_check, s_check);
let w_check = pair_values(&tree_check, &solve(&tree_check, river_leaf_iters(), Rng::seeded(seed)).strategy);
let tree_bet = tree_with_chance(m, rchance, pot_bet, s_bet);
let w_bet = pair_values(&tree_bet, &solve(&tree_bet, river_leaf_iters(), Rng::seeded(seed)).strategy);
// Fold the river values onto the turn buckets.
for (hc, tbh, hst) in &rh {
let rbh = rbucket(*hst);
for (vc, tbv, vst) in &rv {
if disjoint(hc, vc) {
let rbv = rbucket(*vst);
let k = tbh * turn_n + tbv;
leaf_check[k] += w_check[rbh * m + rbv];
leaf_bet[k] += w_bet[rbh * m + rbv];
counts[k] += 1.0;
}
}
}
}
// Average per turn-bucket pair. Pairs that never co-occur keep 0 (they carry no chance weight).
for k in 0..turn_n * turn_n {
if counts[k] > 0.0 {
leaf_check[k] /= counts[k];
leaf_bet[k] /= counts[k];
}
}
Some((leaf_check, leaf_bet))
}
/// Build and solve the turn subgame the engine believes it is in, with the river folded into the
/// leaves. `p`/`s` are the turn pot and bet. `None` when it cannot be built (fewer than two distinct
/// turn strengths, empty ranges).
fn build_turn(spot: &Spot, hero_combos: &[Vec<Card>], villain_combos: &[Vec<Card>], p: f64, s: f64) -> Option<TurnGame> {
let rules = spot.rules();
let judged = |combos: &[Vec<Card>]| -> Vec<(Vec<Card>, Strength)> {
combos.iter().filter_map(|c| judge(&rules, c, &spot.board).ok().map(|st| (c.clone(), st))).collect()
};
let hero = judged(hero_combos);
let villain = judged(villain_combos);
if hero.is_empty() || villain.is_empty() {
return None;
}
let mut ladder: Vec<Strength> = hero.iter().chain(&villain).map(|(_, st)| *st).collect();
ladder.sort();
ladder.dedup();
let n = ladder.len();
if n < 2 {
return None;
}
let tb = |st: Strength| ladder.partition_point(|d| *d < st).min(n - 1);
let hero_b: Vec<(Vec<Card>, usize)> = hero.iter().map(|(c, st)| (c.clone(), tb(*st))).collect();
let villain_b: Vec<(Vec<Card>, usize)> = villain.iter().map(|(c, st)| (c.clone(), tb(*st))).collect();
// Turn joint deal table over turn buckets (card removal between the two ranges).
let mut chance = vec![0.0; n * n];
for (hc, hb) in &hero_b {
for (vc, vb) in &villain_b {
if disjoint(hc, vc) {
chance[hb * n + vb] += 1.0;
}
}
}
let total: f64 = chance.iter().sum();
if total <= 0.0 {
return None;
}
chance.iter_mut().for_each(|x| *x /= total);
let (leaf_check, leaf_bet) = river_leaves(spot, &hero_b, &villain_b, n, p, s)?;
let tree = tree_with_leaf(n, chance, p, leaf_check, leaf_bet);
let solved = solve(&tree, TURN_SOLVE_ITERS, Rng::seeded(spot.seed));
Some(TurnGame { tree, solved, ladder })
}
/// Solve the heads-up turn subgame from the engine's belief and return hero's equilibrium mix at the
/// node the spot sits on, or `None` when the v1 slice does not apply (the caller keeps the heuristic).
pub fn turn_plan(spot: &Spot, villain_combos: &[Vec<Card>]) -> Option<TurnPlan> {
if spot.street != Street::Turn {
return None;
}
if spot.live_villains().count() != 1 || villain_combos.is_empty() {
return None;
}
let rules = spot.rules();
let hero_strength = judge(&rules, &spot.hero_cards, &spot.board).ok()?;
if spot.to_call == 0.0 {
let s = bet_to(spot)?;
let game = build_turn(spot, villain_combos, villain_combos, spot.pot, s)?;
let hb = game.bucket(hero_strength);
let probs = game.solved.strategy.row(0, hb).to_vec(); // [check, bet]
let bet_p = probs.get(1).copied().unwrap_or(0.0);
Some(TurnPlan {
facing: false,
mix: [probs.first().copied().unwrap_or(1.0 - bet_p), bet_p],
bet_to: s,
reason: format!("turn subgame: bucket {hb}/{}, p(bet) {bet_p:.2}", game.ladder.len()),
})
} else {
// Facing a turn bet: the pre-bet pot is `pot - to_call`, the bet is `to_call`.
let p = spot.pot - spot.to_call;
let s = spot.to_call;
if p <= 0.0 || s <= 0.0 {
return None;
}
let game = build_turn(spot, villain_combos, villain_combos, p, s)?;
let hb = game.bucket(hero_strength);
let row = game.solved.strategy.row(4, hb).to_vec(); // [fold, call]
let call_p = row.get(1).copied().unwrap_or(0.0);
Some(TurnPlan {
facing: true,
mix: [row.first().copied().unwrap_or(1.0 - call_p), call_p],
bet_to: 0.0,
reason: format!("turn subgame: bucket {hb}/{} facing bet, p(call) {call_p:.2}", game.ladder.len()),
})
}
}
/// Build the villain belief combos the way `decide::postflop` does (gated reads, enumerated range)
/// and return hero's turn mix — the measurement entry point, faithful to what the live engine would
/// play. `None` when the slice does not apply.
pub fn turn_mix(spot: &Spot) -> Option<TurnPlan> {
if spot.street != Street::Turn {
return None;
}
let gated = crate::engine::read_gate::gate_reads(spot);
let spot = &gated;
if spot.live_villains().count() != 1 {
return None;
}
let villain = spot.live_villains().next()?;
let rules = spot.rules();
let filter = crate::engine::range_filter::range_filter(
&crate::exploit::range_model::range_spec(spot, villain),
rules,
spot.variant,
&spot.board,
);
let dead: Vec<Card> = spot.hero_cards.iter().chain(&spot.board).copied().collect();
let list = crate::engine::range_combos::combos(&rules, &filter, &dead)?;
turn_plan(spot, &list)
}
/// The belief + trust version of `turn_plan`: solve the turn subgame for GTO, then tilt hero toward
/// best-responding to the **believed** villain (`believed_villain`, reused from the river — the turn
/// tree's `v_bet`/`v_check` nodes carry the same meaning) inside a KL ball of radius λ
/// (`lambda_from_confidence`). A strong read exploits; a weak/absent read collapses to the proven
/// GTO mix (λ → ∞). `None` outside the slice or below the confidence floor.
pub fn turn_exploit_plan(spot: &Spot, villain_combos: &[Vec<Card>], profile: Option<&Profile>) -> Option<TurnPlan> {
if spot.street != Street::Turn {
return None;
}
if spot.live_villains().count() != 1 || villain_combos.is_empty() {
return None;
}
if profile.and_then(|p| p.confidence).filter(|c| !c.is_nan()).unwrap_or(0.0) < CONFIDENCE_FLOOR {
return None;
}
let rules = spot.rules();
let hero_strength = judge(&rules, &spot.hero_cards, &spot.board).ok()?;
let (p, s, facing) = if spot.to_call == 0.0 {
(spot.pot, bet_to(spot)?, false)
} else {
let p = spot.pot - spot.to_call;
if p <= 0.0 || spot.to_call <= 0.0 {
return None;
}
(p, spot.to_call, true)
};
let game = build_turn(spot, villain_combos, villain_combos, p, s)?;
let n = game.ladder.len();
let opponent = believed_villain(&game.tree, n, profile, p, s, profile.and_then(|pr| pr.turn_aggression.or(pr.aggression)));
let lambda = lambda_from_confidence(profile.and_then(|p| p.confidence), p);
let tilted = kl_best_response(&game.tree, &opponent, &game.solved.strategy, 0, lambda);
let hb = game.bucket(hero_strength);
let node = if facing { 4 } else { 0 };
let row = tilted.row(node, hb).to_vec();
let forward = row.get(1).copied().unwrap_or(0.0);
Some(TurnPlan {
facing,
mix: [row.first().copied().unwrap_or(1.0 - forward), forward],
bet_to: if facing { 0.0 } else { s },
reason: format!(
"turn gearbox: bucket {hb}/{n}{}, λ {:.2}, p(fwd) {forward:.2}",
if facing { " facing bet" } else { "" },
lambda
),
})
}
/// Live entry for the turn belief + trust gearbox: source the villain belief from the **raw** read and
/// hand the solver the opponent's real `Profile`. Like the river gearbox, the KL trust radius is its
/// own safety, so it reads the true opponent and the confidence floor keeps it off thin reads.
pub fn turn_exploit_mix(spot: &Spot) -> Option<TurnPlan> {
if spot.street != Street::Turn {
return None;
}
if spot.live_villains().count() != 1 {
return None;
}
let villain = spot.live_villains().next()?;
let profile = villain.profile.as_ref();
let rules = spot.rules();
let filter = crate::engine::range_filter::range_filter(
&crate::exploit::range_model::range_spec(spot, villain),
rules,
spot.variant,
&spot.board,
);
let dead: Vec<Card> = spot.hero_cards.iter().chain(&spot.board).copied().collect();
let list = crate::engine::range_combos::combos(&rules, &filter, &dead)?;
turn_exploit_plan(spot, &list, profile)
}
/// Defensive turn veto: on a confident read that the villain UNDER-bluffs its turn bet, fold a heuristic
/// CALL the belief+trust gearbox would not make — the turn analogue of `river_subgame::fold_veto`. It
/// only ever turns a call into a fold facing a bet, never touches a bet/check/raise, and stands down on
/// a thin read or off the heads-up turn slice. The caller gates it to cash (no ICM premium). Builds the
/// (expensive) subgame only when the base is already a Call and the read clears the confidence floor.
pub fn turn_fold_veto(spot: &Spot, base: Decision) -> Decision {
if !veto_enabled() {
return base;
}
if base.choice != Choice::Call {
return base;
}
let Some(plan) = turn_exploit_mix(spot) else {
return base;
};
if !plan.facing || plan.mix[1] >= VETO_CALL_FLOOR {
return base;
}
Decision {
choice: Choice::Fold,
reason: format!("defensive turn veto: {} (heuristic would call)", plan.reason),
..base
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::game::{ActionKind, Villain};
use crate::variant::Variant;
/// A heads-up turn spot where hero is first to act into `pot` with check or a two-thirds bet.
fn turn_to_act(board: &[Card], hero: &str, pot: f64) -> Spot {
Spot {
variant: Variant::Nlhe,
big_blind: 1.0,
seats: 2,
hero_seat: 1,
button_seat: Some(1),
hero_cards: Card::parse_list(hero).unwrap(),
board: board.to_vec(),
street: Street::Turn,
pot,
to_call: 0.0,
hero_stack: pot * 4.0,
min_raise_to: Some(pot * 0.66),
max_raise_to: Some(pot * 4.0),
legal: vec![ActionKind::Check, ActionKind::Raise],
allowed_sizes: Some(vec![pot * 0.66]),
villains: vec![Villain { seat: 2, stack: pot * 4.0, folded: false, profile: None }],
seed: 0x5EED_B17E,
history: Vec::new(),
}
}
fn sample_villain() -> Vec<Vec<Card>> {
["Ad Jc", "Qh Qd", "Jd Jh", "8c 8d", "6h 6d", "5c 4c", "Td 9c", "Kc Qc"]
.iter()
.map(|c| Card::parse_list(c).unwrap())
.collect()
}
/// A heads-up turn spot in the slice returns a mix, and a strong made hand leans to betting.
/// Guards the wiring (range → runout leaves → turn solve → readback), not the exact frequency.
#[test]
fn a_made_hand_to_act_gets_a_turn_mix_that_leans_to_bet() {
let board = Card::parse_list("Ah Kd 7c 2s").unwrap(); // turn: 4 cards
let villain = sample_villain();
let spot = turn_to_act(&board, "Ac As", 6.0); // top set on this board
let plan = turn_plan(&spot, &villain).expect("heads-up turn to-act is in slice");
assert!(!plan.facing);
assert!(plan.bet_to > 0.0);
assert!(plan.forward() > 0.5, "a strong made hand should lean to betting, got p(bet) {:.2}", plan.forward());
}
/// Off the turn (river) the slice declines, so the caller keeps the heuristic.
#[test]
fn the_slice_declines_off_the_turn() {
let river = Card::parse_list("Ah Kd 7c 2s 9h").unwrap(); // 5 cards = river
let mut spot = turn_to_act(&river[..4], "Ac As", 6.0);
spot.board = river;
spot.street = Street::River;
assert!(turn_plan(&spot, &sample_villain()).is_none(), "river is not the turn slice");
}
// --- belief + trust gearbox (L4) ---
fn prof(fold_to_bet: f64, aggression: f64, confidence: f64) -> Profile {
Profile {
fold_to_bet: Some(fold_to_bet),
aggression: Some(aggression),
confidence: Some(confidence),
..Default::default()
}
}
fn turn_to_act_vs(board: &[Card], hero: &str, pot: f64, profile: Option<Profile>) -> Spot {
Spot { villains: vec![Villain { seat: 2, stack: pot * 4.0, folded: false, profile }], ..turn_to_act(board, hero, pot) }
}
fn turn_vs_bet(board: &[Card], hero: &str, pot: f64, bet: f64, profile: Option<Profile>) -> Spot {
Spot {
variant: Variant::Nlhe,
big_blind: 1.0,
seats: 2,
hero_seat: 1,
button_seat: Some(1),
hero_cards: Card::parse_list(hero).unwrap(),
board: board.to_vec(),
street: Street::Turn,
pot: pot + bet,
to_call: bet,
hero_stack: pot * 4.0,
min_raise_to: None,
max_raise_to: None,
legal: vec![ActionKind::Fold, ActionKind::Call],
allowed_sizes: None,
villains: vec![Villain { seat: 2, stack: pot * 4.0, folded: false, profile }],
seed: 0x5EED_B17E,
history: Vec::new(),
}
}
/// Below the confidence floor the turn gearbox stands down (`None`), so the heuristic keeps the edge.
#[test]
fn the_turn_gearbox_stands_down_below_the_confidence_floor() {
let board = Card::parse_list("Ah Kd 7c 2s").unwrap();
let villain = sample_villain();
let thin = turn_to_act_vs(&board, "Ac As", 6.0, Some(prof(0.2, 0.3, 0.10)));
assert!(
turn_exploit_plan(&thin, &villain, thin.live_villains().next().unwrap().profile.as_ref()).is_none(),
"confidence 0.10 < floor ⇒ no plan"
);
let confident = turn_to_act_vs(&board, "Ac As", 6.0, Some(prof(0.2, 0.3, 0.80)));
assert!(
turn_exploit_plan(&confident, &villain, confident.live_villains().next().unwrap().profile.as_ref()).is_some(),
"confidence 0.80 ≥ floor ⇒ a plan"
);
}
/// A confident calling-station read makes hero value-bet a strong made hand on the turn (exploit,
/// not balance) — the offense direction of the gearbox.
#[test]
fn a_confident_station_read_value_bets_a_strong_turn_hand() {
let board = Card::parse_list("Ah Kd 7c 2s").unwrap();
let villain = sample_villain();
let spot = turn_to_act_vs(&board, "Ac As", 6.0, Some(prof(0.08, 0.15, 0.85)));
let plan = turn_exploit_plan(&spot, &villain, spot.live_villains().next().unwrap().profile.as_ref())
.expect("confident heads-up turn to-act is in slice");
assert!(!plan.facing);
assert!(plan.forward() > 0.5, "value-bet a strong hand into a station, got p(bet) {:.2}", plan.forward());
}
/// The veto never touches hero's offense: a base that is not a call is returned unchanged even
/// though a plan exists (guards against a full-replacement regression, as on the river).
#[test]
fn the_turn_veto_leaves_a_non_call_decision_untouched() {
let board = Card::parse_list("Ah Kd 7c 2s").unwrap();
let spot = turn_vs_bet(&board, "Qc Qd", 6.0, 6.0, Some(prof(0.30, 0.06, 0.85)));
let check = Decision::new(Choice::Check, 0.7, "heuristic check");
assert_eq!(turn_fold_veto(&spot, check.clone()), check, "a non-call base is never vetoed");
}
}
+11 -5
View File
@@ -1,6 +1,6 @@
use super::fold_equity_scale::{MAX_SCALE, MIN_SCALE};
use super::profile::Profile;
use super::style::classify;
use super::style::{classify, station_trust, Style};
use super::style_shift::shift_for;
use super::thresholds::Thresholds;
@@ -19,13 +19,19 @@ fn bounded(x: f64, (low, high): (f64, f64)) -> f64 {
}
/// `base` as seen against one profile; `None` when the profile says nothing.
///
/// A `CallingStation` shift is scaled by `station_trust`: a misclassified aggressive "station"
/// (loose width but postflop-aggressive — nemesis-2) gets a fraction of the value-bet-thinner shift,
/// not all of it. Every other style, and a genuine station (trust 1.0), is bit-identical to before.
fn against(base: Thresholds, profile: &Profile) -> Option<Thresholds> {
shift_for(classify(profile)).map(|shift| Thresholds {
call_margin: bounded(base.call_margin + shift.call_margin, CALL_MARGIN),
value_raise: bounded(base.value_raise + shift.value_raise, VALUE_RAISE),
let style = classify(profile);
let c = if style == Style::CallingStation { station_trust(profile) } else { 1.0 };
shift_for(style).map(|shift| Thresholds {
call_margin: bounded(base.call_margin + shift.call_margin * c, CALL_MARGIN),
value_raise: bounded(base.value_raise + shift.value_raise * c, VALUE_RAISE),
abstain_band: bounded(base.abstain_band, ABSTAIN_BAND),
fold_equity_scale: base.fold_equity_scale.clamp(MIN_SCALE, MAX_SCALE),
range_width_scale: bounded(base.range_width_scale * shift.range_width, RANGE_WIDTH),
range_width_scale: bounded(base.range_width_scale * (1.0 + (shift.range_width - 1.0) * c), RANGE_WIDTH),
})
}
+20
View File
@@ -17,6 +17,12 @@ pub const MAX_BLUFF_SHARE: f64 = 0.6;
const AVERAGE_AGGRESSION: f64 = 0.45;
const MAX_FACTOR: f64 = 2.0;
/// Populations-Ueber-Bluff-Prior gegen einen UNGELESENEN Gegner: der Micro-Pool c-bettet/barrelt
/// weit ueber GTO-Balance, also bekommt eine unbekannte (auch auf blind gegatete) Range auf
/// Flop/Turn mindestens diesen Bluff-Anteil. River bleibt dem MDF-Boden ueberlassen.
/// Micro-Prior; spaeter stake-skaliert.
const POP_BLUFF_PRIOR: [f64; 4] = [0.0, 0.40, 0.35, 0.0]; // preflop, flop, turn, river
fn street_factor(street: Street) -> f64 {
match street {
Street::Preflop => 0.0,
@@ -45,3 +51,17 @@ pub fn bluff_share(profile: Option<&Profile>, ratio: Option<f64>, street: Street
let balanced = s / (1.0 + 2.0 * s);
(balanced * street_factor(street) * style_factor(profile)).clamp(0.0, MAX_BLUFF_SHARE)
}
/// Lift the population over-bluff prior onto a base bluff share. It applies ONLY to an UNREAD
/// villain (`profile` None - including a read gated to blind) on a FIRST barrel: a sustained
/// multi-street line (`sustained`, the villain already bet/raised an earlier street) is
/// value-weighted even in the micro pool, so it gets no bump. River and preflop carry no prior
/// (the river is the MDF floor's job). Never exceeds `MAX_BLUFF_SHARE`.
pub fn with_pop_prior(profile: Option<&Profile>, street: Street, sustained: bool, base: f64) -> f64 {
let prior = if profile.is_none() && !sustained {
POP_BLUFF_PRIOR[street as usize]
} else {
0.0
};
base.max(prior).min(MAX_BLUFF_SHARE)
}
+17 -5
View File
@@ -11,7 +11,7 @@
//! (`table_fold::pressure_ratio`).
use super::profile::Profile;
use super::style::{classify, Style};
use super::style::{classify, station_trust, Style};
/// Bet size (pot fraction) at which foldToBet is taken to be measured.
pub const REFERENCE_RATIO: f64 = 0.66;
@@ -32,13 +32,25 @@ fn style_default(style: Style) -> f64 {
}
/// The opponent's fold-to-bet at the reference size.
///
/// A `CallingStation` read is trust-weighted (`station_trust`): a misclassified aggressive "station"
/// (nemesis-2, fold-to-bet 0.56 read, aggr 0.41) only partly trusts its high fold frequency, so hero
/// does not over-barrel into a light-raising range whose multi-street cost the single-street bluff-EV
/// never models. A genuine station (trust 1.0) is bit-identical to the raw read.
pub fn fold_base(profile: Option<&Profile>) -> f64 {
match profile {
None => DEFAULT_FOLD_TO_BET,
Some(p) => match p.fold_to_bet.filter(|f| !f.is_nan()) {
Some(f) => f.clamp(0.0, 1.0),
None => style_default(classify(p)),
},
Some(p) => {
let raw = match p.fold_to_bet.filter(|f| !f.is_nan()) {
Some(f) => f.clamp(0.0, 1.0),
None => style_default(classify(p)),
};
if classify(p) == Style::CallingStation {
DEFAULT_FOLD_TO_BET + station_trust(p) * (raw - DEFAULT_FOLD_TO_BET)
} else {
raw
}
}
}
}
+6
View File
@@ -13,6 +13,8 @@ const WEAK_PLAYER: Profile = Profile {
pfr: Some(0.10),
fold_to_bet: Some(0.25),
aggression: Some(0.20),
turn_aggression: None,
river_aggression: None,
cbet: None,
fold_to_cbet: None,
three_bet: None,
@@ -21,6 +23,7 @@ const WEAK_PLAYER: Profile = Profile {
check_raise: None,
wtsd: None,
wsd: None,
confidence: None,
};
fn prior(mark: &str) -> Option<Profile> {
@@ -38,6 +41,8 @@ pub fn with_mark(measured: Option<Profile>, mark: &str) -> Option<Profile> {
pfr: known.pfr.or(prior.pfr),
fold_to_bet: known.fold_to_bet.or(prior.fold_to_bet),
aggression: known.aggression.or(prior.aggression),
turn_aggression: known.turn_aggression.or(prior.turn_aggression),
river_aggression: known.river_aggression.or(prior.river_aggression),
cbet: known.cbet.or(prior.cbet),
fold_to_cbet: known.fold_to_cbet.or(prior.fold_to_cbet),
three_bet: known.three_bet.or(prior.three_bet),
@@ -46,5 +51,6 @@ pub fn with_mark(measured: Option<Profile>, mark: &str) -> Option<Profile> {
check_raise: known.check_raise.or(prior.check_raise),
wtsd: known.wtsd.or(prior.wtsd),
wsd: known.wsd.or(prior.wsd),
confidence: known.confidence.or(prior.confidence),
})
}
+245
View File
@@ -0,0 +1,245 @@
//! Maximum-Entropy-Verteilung (Jaynes): die am wenigsten annehmende Verteilung ueber
//! einen diskreten Traeger (Staerke-Buckets) unter linearen Momentbedingungen
//! Σ p_i·f_k(i) = c_k. Loesung: p_i ∝ exp(Σ_k λ_k·f_k(i)); die λ minimieren das
//! duale, glatte, konvexe g(λ) = ln Z(λ) − λ·c. Newton mit Backtracking, deterministisch.
const MAX_ITER: usize = 200;
const TOL: f64 = 1e-12;
/// Ergebnis mit Diagnose.
#[derive(Debug, Clone)]
pub struct MaxEnt {
pub p: Vec<f64>,
pub lambda: Vec<f64>,
pub iterations: usize,
/// Betrag des Gradienten (max. Momentenabweichung) am Ende.
pub residual: f64,
}
/// Shannon-Entropie in nats.
pub fn entropy(p: &[f64]) -> f64 {
p.iter().filter(|&&x| x > 0.0).map(|&x| -x * x.ln()).sum()
}
fn scores(features: &[Vec<f64>], lambda: &[f64], n: usize) -> Vec<f64> {
(0..n)
.map(|i| features.iter().zip(lambda).map(|(f, l)| l * f[i]).sum())
.collect()
}
/// Gibbs-Verteilung zu λ (numerisch stabil, Maximum abgezogen).
fn gibbs(features: &[Vec<f64>], lambda: &[f64], n: usize) -> Vec<f64> {
let s = scores(features, lambda, n);
let m = s.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
let w: Vec<f64> = s.iter().map(|x| (x - m).exp()).collect();
let z: f64 = w.iter().sum();
w.into_iter().map(|x| x / z).collect()
}
/// Duale Zielfunktion ln Z − λ·c (stabil).
fn dual(features: &[Vec<f64>], targets: &[f64], lambda: &[f64], n: usize) -> f64 {
let s = scores(features, lambda, n);
let m = s.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
let lz = m + s.iter().map(|x| (x - m).exp()).sum::<f64>().ln();
lz - lambda.iter().zip(targets).map(|(l, c)| l * c).sum::<f64>()
}
/// Loest ein lineares System (Gauss mit Teilpivot); None bei Singularitaet.
fn solve(mut a: Vec<Vec<f64>>, mut b: Vec<f64>) -> Option<Vec<f64>> {
let k = b.len();
for c in 0..k {
let piv = (c..k).max_by(|&x, &y| a[x][c].abs().total_cmp(&a[y][c].abs()))?;
if a[piv][c].abs() < 1e-300 {
return None;
}
a.swap(c, piv);
b.swap(c, piv);
for r in c + 1..k {
let f = a[r][c] / a[c][c];
for j in c..k {
a[r][j] -= f * a[c][j];
}
b[r] -= f * b[c];
}
}
let mut x = vec![0.0; k];
for r in (0..k).rev() {
let s: f64 = (r + 1..k).map(|j| a[r][j] * x[j]).sum();
x[r] = (b[r] - s) / a[r][r];
}
Some(x)
}
/// MaxEnt unter mehreren Momentbedingungen: `features[k][i]` = f_k(i), `targets[k]` = c_k.
/// Ohne Bedingungen: uniform. Ziele muessen im Inneren der konvexen Huelle liegen;
/// sonst bricht Newton nach MAX_ITER ab (siehe `residual`).
pub fn max_entropy_multi(features: &[Vec<f64>], targets: &[f64]) -> MaxEnt {
let n = features.first().map_or(0, |f| f.len());
assert!(features.len() == targets.len() && features.iter().all(|f| f.len() == n));
let k = features.len();
let mut lambda = vec![0.0; k];
let mut it = 0;
let mut res = 0.0;
if n == 0 {
return MaxEnt { p: vec![], lambda, iterations: 0, residual: 0.0 };
}
while it < MAX_ITER {
let p = gibbs(features, &lambda, n);
let mean: Vec<f64> =
features.iter().map(|f| f.iter().zip(&p).map(|(a, b)| a * b).sum()).collect();
let g: Vec<f64> = mean.iter().zip(targets).map(|(m, c)| m - c).collect();
res = g.iter().fold(0.0, |a: f64, x| a.max(x.abs()));
if res < TOL {
break;
}
// Hesse = Kovarianz der Merkmale unter p (+ kleiner Ridge gegen Singularitaet).
let mut h = vec![vec![0.0; k]; k];
for a in 0..k {
for b in 0..k {
let e: f64 = (0..n).map(|i| p[i] * features[a][i] * features[b][i]).sum();
h[a][b] = e - mean[a] * mean[b] + if a == b { 1e-14 } else { 0.0 };
}
}
let Some(step) = solve(h, g.clone()) else { break };
// Backtracking auf der dualen Zielfunktion (Armijo).
let f0 = dual(features, targets, &lambda, n);
let slope: f64 = g.iter().zip(&step).map(|(a, b)| a * b).sum();
let mut t = 1.0;
let mut accepted = false;
for _ in 0..60 {
let cand: Vec<f64> = lambda.iter().zip(&step).map(|(l, s)| l - t * s).collect();
if dual(features, targets, &cand, n) <= f0 - 1e-4 * t * slope {
lambda = cand;
accepted = true;
break;
}
t *= 0.5;
}
it += 1;
if !accepted {
break; // Dual am Rundungsboden; residual meldet die Restabweichung
}
}
let p = gibbs(features, &lambda, n);
let mean: Vec<f64> =
features.iter().map(|f| f.iter().zip(&p).map(|(a, b)| a * b).sum()).collect();
res = mean.iter().zip(targets).fold(res * 0.0, |a, (m, c)| a.max((m - c).abs()));
MaxEnt { p, lambda, iterations: it, residual: res }
}
/// MaxEnt fuer EINE Mittelwertbedingung Σ p_i·f_i = target. Liegt target (fast) am Rand
/// oder ausserhalb [min f, max f], wird ins Innere geklemmt (1e-9 relativ); die
/// Verteilung ist dann sehr spitz. target == Gleichverteilungsmittel -> uniform.
pub fn max_entropy(support_features: &[f64], target_mean: f64) -> Vec<f64> {
let n = support_features.len();
if n == 0 {
return vec![];
}
let lo = support_features.iter().cloned().fold(f64::INFINITY, f64::min);
let hi = support_features.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
if hi - lo <= 0.0 {
return vec![1.0 / n as f64; n];
}
let eps = (hi - lo) * 1e-9;
let c = target_mean.clamp(lo + eps, hi - eps);
max_entropy_multi(&[support_features.to_vec()], &[c]).p
}
#[cfg(test)]
mod tests {
use super::*;
fn mean(f: &[f64], p: &[f64]) -> f64 {
f.iter().zip(p).map(|(a, b)| a * b).sum()
}
fn feats(n: usize) -> Vec<f64> {
(0..n).map(|i| i as f64).collect()
}
#[test]
fn ohne_bedingung_uniform() {
let r = max_entropy_multi(&[], &[]);
assert!(r.p.is_empty());
let f = feats(10);
// Zielmittel = unbeschraenktes Mittel -> uniform
let p = max_entropy(&f, 4.5);
for x in &p {
assert!((x - 0.1).abs() < 1e-9, "{x}");
}
assert!((entropy(&p) - 10f64.ln()).abs() < 1e-9);
println!("uniform H={:.6} (ln10={:.6})", entropy(&p), 10f64.ln());
}
#[test]
fn mittelwert_und_entropiemaximum() {
let f = feats(10);
for &t in &[2.0, 4.5, 6.5, 8.0] {
let r = max_entropy_multi(&[f.clone()], &[t]);
let p = &r.p;
assert!((p.iter().sum::<f64>() - 1.0).abs() < 1e-12);
assert!((mean(&f, p) - t).abs() < 1e-9);
println!(
"target={t} lambda={:.6} iter={} res={:.1e} H={:.6}\n p={:?}",
r.lambda[0],
r.iterations,
r.residual,
entropy(p),
p.iter().map(|x| (x * 1e4).round() / 1e4).collect::<Vec<_>>()
);
// Richtung d ⟂ 1 und ⟂ f (erhaelt die Bedingungen); Entropie muss in beide Richtungen fallen.
let n = f.len() as f64;
let q: Vec<f64> = f.iter().map(|x| x * x).collect();
let (mf, mq) = (f.iter().sum::<f64>() / n, q.iter().sum::<f64>() / n);
let fc: Vec<f64> = f.iter().map(|x| x - mf).collect();
let qc: Vec<f64> = q.iter().map(|x| x - mq).collect();
let a = qc.iter().zip(&fc).map(|(x, y)| x * y).sum::<f64>()
/ fc.iter().map(|x| x * x).sum::<f64>();
let d: Vec<f64> = qc.iter().zip(&fc).map(|(x, y)| x - a * y).collect();
let h0 = entropy(p);
let pmin = p.iter().cloned().fold(f64::INFINITY, f64::min);
let dmax = d.iter().fold(0.0f64, |a, x| a.max(x.abs()));
for &e in &[0.5, -0.5, 0.1, -0.1] {
// Schritt relativ zum kleinsten p, damit alles positiv bleibt
let pq: Vec<f64> =
p.iter().zip(&d).map(|(a, b)| a + e * pmin * b / dmax).collect();
assert!(pq.iter().all(|&x| x > 0.0));
assert!((mean(&f, &pq) - t).abs() < 1e-9, "Bedingung erhalten");
assert!(entropy(&pq) < h0, "Entropie muss sinken (e={e})");
}
}
}
#[test]
fn neigung_monoton() {
let f = feats(8);
let hoch = max_entropy(&f, 5.5);
let tief = max_entropy(&f, 1.5);
assert!(hoch.windows(2).all(|w| w[1] > w[0]), "hoch: steigend");
assert!(tief.windows(2).all(|w| w[1] < w[0]), "tief: fallend");
assert!(hoch[7] > 1.0 / 8.0 && tief[0] > 1.0 / 8.0);
println!("hoch={:?} H={:.4}", hoch, entropy(&hoch));
println!("tief={:?} H={:.4}", tief, entropy(&tief));
// staerkere Neigung -> weniger Entropie
assert!(entropy(&max_entropy(&f, 6.5)) < entropy(&hoch));
}
#[test]
fn zwei_bedingungen() {
let f1 = feats(12);
let f2: Vec<f64> = f1.iter().map(|x| x * x).collect();
let (c1, c2) = (7.0, 60.0);
let r = max_entropy_multi(&[f1.clone(), f2.clone()], &[c1, c2]);
assert!((mean(&f1, &r.p) - c1).abs() < 1e-9);
assert!((mean(&f2, &r.p) - c2).abs() < 1e-9);
println!("2 Bed.: iter={} H={:.6}", r.iterations, entropy(&r.p));
}
#[test]
fn rand_und_deterministisch() {
let f = feats(6);
let p = max_entropy(&f, 5.0); // Rand -> geklemmt, spitz
assert!(p[5] > 0.99 && (p.iter().sum::<f64>() - 1.0).abs() < 1e-9);
assert_eq!(max_entropy(&f, 3.3), max_entropy(&f, 3.3));
}
}
+251
View File
@@ -0,0 +1,251 @@
//! Minimum-defence-frequency floor: on the river, a made hand in the top `1 - alpha` of a
//! defensible range is never folded to a bet, whatever the opponent range model says.
//!
//! This is the GTO floor UNDER the exploit deviation. Facing a bet of break-even `alpha`
//! (`to_call / (pot + to_call)`), a defender who folds more than `1 - alpha` of the hands that
//! beat a bluff lets the bettor print with any air (MDF). The engine's villain range model is
//! measured to be too value-heavy (replay benchmark: mean equity bias ~-0.22, river fold-to-bet
//! ~86 %), so equity-against-the-model folds bluff-catchers that MDF says must defend. This floor
//! reads HERO's own made hand - not the (untrusted) villain range - so it can never be moved by a
//! miscalibrated read: it only ever turns a model-driven fold into the call MDF requires.
//!
//! River only: there the bet is terminal and MDF is exact (no draws, no future streets, realisation
//! 1.0). Flop and turn defence couples with realisation and is left to the equity line.
use crate::exploit::profile::Profile;
use crate::game::{ActionKind, Choice, Decision, Spot, Street};
use crate::odds::break_even::break_even;
use crate::read::made::Made;
/// At or above this observed postflop aggression the bettor bets and raises more than a value range
/// supports, so MDF defence of a bluff-catcher is owed. Set BETWEEN a balanced range player's
/// measured aggression and a genuine over-bluffer's: the near-GTO opponents read ~0.35-0.40
/// (gto Memory 0.35, Oracle 0.40; gto-small lower), a maniac reads ~0.49-0.50 (Memory 0.49, Oracle
/// 0.50). A threshold of 0.45 trips the maniac and spares the balanced player.
const OVER_BLUFF_AGGRESSION: f64 = 0.45;
/// Fraction of random hands hero's made class beats by showdown - the MDF yardstick (rough,
/// monotone in `Made`). Not an equity: only its order and rough level matter, to place the hand
/// in hero's range (`strength >= alpha` ⇔ top `1 - alpha`).
fn strength(made: Made) -> f64 {
match made {
Made::Air => 0.15,
Made::BoardOnly => 0.18,
Made::Underpair => 0.42,
Made::BottomPair => 0.50,
Made::MiddlePair => 0.60,
Made::TopPairWeakKicker => 0.70,
Made::TopPairGoodKicker => 0.80,
Made::Overpair => 0.85,
Made::TwoPair => 0.90,
Made::Set | Made::Trips => 0.95,
Made::Straight => 0.97,
Made::Flush => 0.98,
Made::FullHouse => 0.99,
Made::Quads => 0.995,
Made::StraightFlush => 1.0,
}
}
/// A hand with real showdown value: at least a pair, so it beats a pure bluff. `BoardOnly`
/// (hero plays the board, chops at best) and `Air` are not bluff-catchers and are excluded -
/// their MDF defence, if any, is a raise, never a call.
fn beats_bluffs(made: Made) -> bool {
made >= Made::Underpair
}
/// Positive, directly observed evidence that this bettor OVER-bluffs, so the range model's fold of a
/// bluff-catcher is wrong and MDF defence is owed: an observed postflop aggression frequency above
/// what a value range supports. This is the DIRECT bluff signal — bets and raises per postflop action
/// — not preflop range WIDTH.
///
/// Why width is excluded: an earlier version also fired on `classify == LooseAggressive`, which keys on
/// vpip ≥ 0.35 ∧ pfr ≥ 0.20 — preflop range width. Heads-up, a correctly balanced opponent plays a wide
/// range (button opens ~80 %, big blind defends ~70 %), so its MEASURED vpip/pfr read loose-aggressive
/// (gto session read vpip 0.70, pfr 0.46) even though its postflop aggression is only ~0.35 and its
/// bets are value-balanced. That width clause force-called the balanced opponent's value bets — the
/// −52 bb/100 over-call BEFUND-gto-ueberdefense first saw under the oracle read, resurfacing under the
/// realistic session read because the oracle vpip was hand-set to a narrow 0.32 but the session read
/// measures the true 0.70 (BEFUND-gto-ueberdefense-read). Range width ≠ bluff frequency; only measured
/// over-aggression earns the defence. The crown equation's trust region, defensive side: only a read
/// that says "this bettor bluffs too much" overrides the model's fold.
fn over_bluffs(profile: &Profile) -> bool {
profile.aggression.is_some_and(|a| a >= OVER_BLUFF_AGGRESSION)
}
/// Could the bet be bluff-heavy enough that MDF requires defending our bluff-catcher? Only against an
/// unread villain (the unread micro population bluffs) or a positively-identified over-bluffer. A
/// balanced / tight regular's bets are value-weighted, so the floor defers to the range model's fold
/// instead of force-calling - the floor is a response to *measured* over-bluffing, not a blanket
/// riegel against everyone who is not a nit.
fn range_may_bluff(spot: &Spot) -> bool {
let mut live = spot.villains.iter().filter(|v| !v.folded).peekable();
live.peek().is_none()
|| live.any(|v| v.profile.as_ref().is_none_or(over_bluffs))
}
/// True when hero must defend `made` against the bet he faces (never fold): on the river, with
/// a bluff-catcher or better, whose strength puts it in the top `1 - alpha` of the range, and the
/// bettor is not a confirmed under-bluffer.
pub fn defends(spot: &Spot, made: Made) -> bool {
spot.street == Street::River
&& spot.to_call > 0.0
&& beats_bluffs(made)
&& strength(made) >= break_even(spot.pot, spot.to_call)
&& range_may_bluff(spot)
}
/// Overlay the floor on a finished postflop decision: a model-driven river fold of a defensible
/// made hand becomes the call MDF requires. `spot` must carry the UNGATED villain reads - the
/// floor's defensive use of a read (fold more against a confirmed non-bluffer, never fold a
/// bluff-catcher the model mis-prices) is always safe, unlike the range model that `read_gate`
/// keeps blind. The base decision's EV annotations are kept; anything but a floorable river fold
/// is returned unchanged.
pub fn floor(spot: &Spot, made: Made, decision: Decision) -> Decision {
if decision.choice == Choice::Fold && spot.is_legal(ActionKind::Call) && defends(spot, made) {
let be = break_even(spot.pot, spot.to_call);
return Decision::new(
Choice::Call,
0.5,
format!("MDF-Boden: Made-Hand verteidigt - Modell-Fold uebersteuert (break-even {be:.2})"),
)
.with_evs(decision.evs);
}
decision
}
#[cfg(test)]
mod tests {
use super::*;
fn river(pot: f64, to_call: f64) -> Spot {
Spot {
variant: crate::variant::Variant::Nlhe,
big_blind: 0.1,
seats: 2,
hero_seat: 1,
button_seat: None,
hero_cards: crate::card::Card::parse_list("Kd 7d").unwrap(),
board: crate::card::Card::parse_list("9c Tc Kc Qd 2h").unwrap(),
street: Street::River,
pot,
to_call,
hero_stack: 100.0,
min_raise_to: None,
max_raise_to: None,
legal: vec![],
allowed_sizes: None,
villains: vec![],
seed: 1,
history: Vec::new(),
}
}
#[test]
fn top_pair_defends_a_half_pot_river_bet() {
// alpha = 0.26 / 0.83 = 0.31; top pair weak kicker strength 0.70 >= 0.31 -> defend
assert!(defends(&river(0.57, 0.26), Made::TopPairWeakKicker));
}
#[test]
fn weak_pair_folds_to_an_overbet() {
// alpha = 15 / 25 = 0.60; underpair strength 0.42 < 0.60 -> no floor
assert!(!defends(&river(10.0, 15.0), Made::Underpair));
}
#[test]
fn air_is_never_floored() {
assert!(!defends(&river(10.0, 3.0), Made::Air));
assert!(!defends(&river(10.0, 3.0), Made::BoardOnly));
}
#[test]
fn only_on_the_river() {
let flop = Spot { street: Street::Flop, ..river(10.0, 3.0) };
assert!(!defends(&flop, Made::TopPairGoodKicker));
}
#[test]
fn no_floor_without_a_bet() {
assert!(!defends(&river(10.0, 0.0), Made::Overpair));
}
fn villain(profile: Option<Profile>) -> crate::game::Villain {
crate::game::Villain { seat: 1, stack: 100.0, folded: false, profile }
}
fn prof(aggression: f64, vpip: f64, fold_to_bet: f64) -> Profile {
Profile {
aggression: Some(aggression),
vpip: Some(vpip),
fold_to_bet: Some(fold_to_bet),
..Profile::default()
}
}
#[test]
fn an_aggressive_bettor_is_defended() {
// alpha 0.33, middle pair 0.60 >= 0.33, and the maniac bets bluffs -> defend.
let spot = Spot { villains: vec![villain(Some(prof(0.8, 0.55, 0.35)))], ..river(12.0, 6.0) };
assert!(defends(&spot, Made::MiddlePair));
}
#[test]
fn an_unread_bettor_is_defended() {
// No profile: the unread micro population bluffs, so the floor still holds.
let spot = Spot { villains: vec![villain(None)], ..river(12.0, 6.0) };
assert!(defends(&spot, Made::MiddlePair));
}
#[test]
fn a_balanced_regular_is_not_floored() {
// The near-GTO opponent (reads.rs oracle p(0.32, 0.22, 0.42, 0.40)): moderate aggression 0.40
// < 0.45 -> no over-bluff evidence, so the model's fold is trusted and a bluff-catcher is NOT
// force-called (BEFUND-gto-ueberdefense: this is the −52 bb/100 river-call leak).
let gto = Profile { pfr: Some(0.22), ..prof(0.40, 0.32, 0.42) };
let spot = Spot { villains: vec![villain(Some(gto))], ..river(12.0, 6.0) };
assert!(!defends(&spot, Made::MiddlePair));
}
#[test]
fn a_wide_but_balanced_headsup_opponent_is_not_floored() {
// The regression this fix buys: the gto's realistic SESSION read, vpip 0.70 / pfr 0.46 /
// aggression 0.35 (measured heads-up, not the hand-set oracle). classify -> LooseAggressive on
// preflop WIDTH alone, which the old `over_bluffs` fired on and force-called into a balanced
// value range (BEFUND-gto-ueberdefense-read). Aggression 0.35 < 0.45 -> no over-bluff evidence,
// so the floor now stays off and trusts the model's fold.
let wide = Profile { pfr: Some(0.46), ..prof(0.35, 0.70, 0.50) };
use crate::exploit::style::{classify, Style};
assert_eq!(classify(&wide), Style::LooseAggressive);
let spot = Spot { villains: vec![villain(Some(wide))], ..river(12.0, 6.0) };
assert!(!defends(&spot, Made::MiddlePair));
}
#[test]
fn a_loose_aggressive_bettor_is_still_floored() {
// The maniac (reads.rs oracle p(0.76, 0.42, 0.50, 0.50); session read aggression ~0.49): its
// measured postflop aggression 0.50 >= 0.45 bets far more than a value range supports, so MDF
// defence against its bluffs is owed and the floor holds — on the direct aggression signal, not
// preflop width (which it shares with the balanced wide opponent above).
let maniac = Profile { pfr: Some(0.42), ..prof(0.50, 0.76, 0.50) };
let spot = Spot { villains: vec![villain(Some(maniac))], ..river(12.0, 6.0) };
assert!(defends(&spot, Made::MiddlePair));
}
#[test]
fn a_confirmed_under_bluffer_is_not_floored() {
// Low observed aggression (0.0) and a nit: no bluffs to catch, the fold stands.
let honest = Spot { villains: vec![villain(Some(prof(0.0, 0.25, 0.5)))], ..river(12.0, 6.0) };
assert!(!defends(&honest, Made::MiddlePair));
let nit = Spot { villains: vec![villain(Some(prof(0.15, 0.11, 0.8)))], ..river(12.0, 6.0) };
assert!(!defends(&nit, Made::MiddlePair));
}
#[test]
fn a_folded_under_bluffer_does_not_suppress_the_live_bettor() {
// The nit folded; the live bettor is unread -> still defended.
let nit = crate::game::Villain { folded: true, ..villain(Some(prof(0.15, 0.11, 0.8))) };
let spot = Spot { villains: vec![nit, villain(None)], ..river(12.0, 6.0) };
assert!(defends(&spot, Made::MiddlePair));
}
}
+4
View File
@@ -10,6 +10,8 @@ pub mod fold_chance;
pub mod fold_equity_scale;
pub mod made_ladder;
pub mod mark;
pub mod mdf_floor;
pub mod posterior;
pub mod pot_trace;
pub mod preflop_role;
pub mod profile;
@@ -28,3 +30,5 @@ pub mod style_rung;
pub mod style_shift;
pub mod table_fold;
pub mod thresholds;
pub mod maxent;
pub mod thompson;
+251
View File
@@ -0,0 +1,251 @@
//! Bayes-Posterior ueber das Gegnerverhalten: Beta-Bernoulli je Parameter, Update pro Beobachtung.
//! Mittel = Punktschaetzung (fuellt `Profile`), Konzentration = Vertrauen (spaeter fuer das KL-lambda).
//! Eigenstaendig, nicht in die Live-Pipeline verdrahtet.
use super::band_stretch::DEFAULT_PFR;
use super::fold_chance::DEFAULT_FOLD_TO_BET;
use super::profile::Profile;
use super::range_guess::DEFAULT_VPIP;
use crate::game::{ActionRecord, SeenAction, Street};
/// Prior-Mittel der Aggressionsfrequenz (postflop Bet/Raise-Anteil).
pub const DEFAULT_AGGRESSION: f64 = 0.35;
/// Pseudo-Beobachtungen des Priors: so viele Haende braucht es, um ihn zu uebersteuern.
pub const PRIOR_STAERKE: f64 = 10.0;
/// Echte Beobachtungen, bei denen das Vertrauen 0.5 erreicht.
pub const VERTRAUEN_HALB: f64 = 30.0;
/// Ein Parameter: Beta(alpha, beta) ueber eine Frequenz.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Beta {
pub alpha: f64,
pub beta: f64,
}
impl Beta {
/// Prior mit Mittel `mean` und Staerke `strength` (= alpha + beta).
pub fn prior(mean: f64, strength: f64) -> Beta {
Beta { alpha: mean * strength, beta: (1.0 - mean) * strength }
}
pub fn mean(&self) -> f64 {
self.alpha / (self.alpha + self.beta)
}
pub fn variance(&self) -> f64 {
let n = self.alpha + self.beta;
self.alpha * self.beta / (n * n * (n + 1.0))
}
/// Echte Beobachtungen (Prior abgezogen).
pub fn beobachtet(&self) -> f64 {
(self.alpha + self.beta - PRIOR_STAERKE).max(0.0)
}
/// 0 ohne Daten, -> 1 mit wachsender Datenmenge.
pub fn vertrauen(&self) -> f64 {
let n = self.beobachtet();
n / (n + VERTRAUEN_HALB)
}
fn sehe(&mut self, erfolg: bool) {
if erfolg {
self.alpha += 1.0;
} else {
self.beta += 1.0;
}
}
}
/// Eine Beobachtung; `true` = der Gegner hat die Handlung gewaehlt.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Beobachtung {
/// Stand vor einer Wette: Fold (true) oder nicht (false).
FoldGegenWette(bool),
/// Hatte postflop die Option: Bet/Raise (true) oder nicht.
Aggression(bool),
/// Preflop freiwillig Geld im Pot (true) oder nicht.
Vpip(bool),
/// Preflop geraist (true) oder nicht.
Pfr(bool),
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Posterior {
pub fold_to_bet: Beta,
pub aggression: Beta,
pub vpip: Beta,
pub pfr: Beta,
}
impl Default for Posterior {
fn default() -> Self {
Posterior::new()
}
}
impl Posterior {
/// Prior = heutige Default-Annahmen; ohne Daten ist `profile()` ~ heutiges Verhalten.
pub fn new() -> Posterior {
Posterior {
fold_to_bet: Beta::prior(DEFAULT_FOLD_TO_BET, PRIOR_STAERKE),
aggression: Beta::prior(DEFAULT_AGGRESSION, PRIOR_STAERKE),
vpip: Beta::prior(DEFAULT_VPIP, PRIOR_STAERKE),
pfr: Beta::prior(DEFAULT_PFR, PRIOR_STAERKE),
}
}
/// Konjugates Update: Erfolg bumpt alpha, Misserfolg beta.
pub fn update(&mut self, obs: Beobachtung) {
match obs {
Beobachtung::FoldGegenWette(x) => self.fold_to_bet.sehe(x),
Beobachtung::Aggression(x) => self.aggression.sehe(x),
Beobachtung::Vpip(x) => self.vpip.sehe(x),
Beobachtung::Pfr(x) => self.pfr.sehe(x),
}
}
/// Liest die Handlungen eines Sitzes aus dem Verlauf, in Reihenfolge.
/// Postflop: "steht vor Wette" = ein anderer Sitz hat auf dieser Strasse gewettet/geraist, seit
/// dieser Sitz zuletzt gehandelt hat. Dann zaehlt Fold fuer fold_to_bet, Raise/AllIn fuer Aggression.
/// Preflop zaehlt je Hand nur die erste freiwillige Handlung (Blinds/Ante ausgenommen) fuer vpip/pfr.
/// Gibt die Zahl der verbuchten Beobachtungen zurueck.
pub fn beobachte_verlauf(&mut self, seat: u8, verlauf: &[ActionRecord]) -> usize {
let mut n = 0;
let mut strasse = None;
let mut vor_wette = false;
let mut preflop_gesehen = false;
for r in verlauf {
if strasse != Some(r.street) {
strasse = Some(r.street);
vor_wette = false;
}
let aggressiv = matches!(r.action, SeenAction::Bet | SeenAction::Raise | SeenAction::AllIn);
if r.seat != seat {
if aggressiv {
vor_wette = true;
}
continue;
}
if matches!(r.action, SeenAction::PostSmallBlind | SeenAction::PostBigBlind | SeenAction::PostAnte) {
continue;
}
if r.street == Street::Preflop {
if !preflop_gesehen {
preflop_gesehen = true;
let freiwillig = matches!(r.action, SeenAction::Call) || aggressiv;
self.update(Beobachtung::Vpip(freiwillig));
self.update(Beobachtung::Pfr(aggressiv));
n += 2;
}
} else {
if vor_wette {
self.update(Beobachtung::FoldGegenWette(r.action == SeenAction::Fold));
n += 1;
}
// Check/Fold/Call/Bet/Raise: Option zu wetten bestand (Fold/Call ohne Wette entfaellt).
if vor_wette || matches!(r.action, SeenAction::Check | SeenAction::Bet) {
self.update(Beobachtung::Aggression(aggressiv));
n += 1;
}
}
vor_wette = false;
}
n
}
/// Posterior-Mittel als `Profile` (Felder darunter bleiben `None`).
pub fn profile(&self) -> Profile {
Profile {
vpip: Some(self.vpip.mean()),
pfr: Some(self.pfr.mean()),
fold_to_bet: Some(self.fold_to_bet.mean()),
aggression: Some(self.aggression.mean()),
..Profile::default()
}
}
/// Gesamtvertrauen in [0, 1): Mittel der Einzelvertrauen (0 ohne Daten).
pub fn confidence(&self) -> f64 {
(self.fold_to_bet.vertrauen() + self.aggression.vertrauen() + self.vpip.vertrauen() + self.pfr.vertrauen())
/ 4.0
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Kleiner deterministischer LCG, kein RNG-Crate.
struct Lcg(u64);
impl Lcg {
fn next(&mut self) -> f64 {
self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
(self.0 >> 11) as f64 / (1u64 << 53) as f64
}
}
#[test]
fn prior_ohne_daten_ist_der_default() {
let p = Posterior::new();
let prof = p.profile();
assert!((prof.vpip.unwrap() - DEFAULT_VPIP).abs() < 1e-12);
assert!((prof.pfr.unwrap() - DEFAULT_PFR).abs() < 1e-12);
assert!((prof.fold_to_bet.unwrap() - DEFAULT_FOLD_TO_BET).abs() < 1e-12);
assert!((prof.aggression.unwrap() - DEFAULT_AGGRESSION).abs() < 1e-12);
assert_eq!(p.confidence(), 0.0);
}
#[test]
fn konvergiert_gegen_wahren_wert_und_vertrauen_steigt() {
let (wahr_fold, wahr_aggr) = (0.7, 0.2);
let mut rng = Lcg(42);
let mut p = Posterior::new();
let mut letzte_konf = p.confidence();
let mut letzte_var = p.fold_to_bet.variance();
println!("n, fold_mean, aggr_mean, confidence, fold_var");
for n in 1..=400 {
p.update(Beobachtung::FoldGegenWette(rng.next() < wahr_fold));
p.update(Beobachtung::Aggression(rng.next() < wahr_aggr));
let konf = p.confidence();
if matches!(n, 1 | 5 | 10 | 25 | 50 | 100 | 200 | 400) {
println!(
"{n:4} {:.4} {:.4} {:.4} {:.6}",
p.fold_to_bet.mean(),
p.aggression.mean(),
konf,
p.fold_to_bet.variance()
);
}
assert!(konf >= letzte_konf, "Vertrauen faellt bei n={n}");
letzte_konf = konf;
if n % 50 == 0 {
assert!(p.fold_to_bet.variance() < letzte_var, "Varianz sinkt nicht bei n={n}");
letzte_var = p.fold_to_bet.variance();
}
if n == 200 {
assert!((p.fold_to_bet.mean() - wahr_fold).abs() < 0.05);
assert!((p.aggression.mean() - wahr_aggr).abs() < 0.05);
}
}
assert!((p.fold_to_bet.mean() - wahr_fold).abs() < 0.05);
assert!(p.confidence() > 0.4);
}
#[test]
fn verlauf_wird_je_sitz_zugeordnet() {
let r = |street, seat, action| ActionRecord { street, seat, action, amount: None };
let verlauf = [
r(Street::Preflop, 0, SeenAction::PostSmallBlind),
r(Street::Preflop, 1, SeenAction::PostBigBlind),
r(Street::Preflop, 0, SeenAction::Raise),
r(Street::Preflop, 1, SeenAction::Call),
r(Street::Flop, 1, SeenAction::Check),
r(Street::Flop, 0, SeenAction::Bet),
r(Street::Flop, 1, SeenAction::Fold),
];
let mut p = Posterior::new();
let n = p.beobachte_verlauf(1, &verlauf);
// vpip+pfr (2), Flop-Check (aggr), Flop-Fold vor Wette (fold + aggr) = 5
assert_eq!(n, 5);
assert_eq!(p.fold_to_bet.beobachtet(), 1.0);
assert!(p.fold_to_bet.mean() > DEFAULT_FOLD_TO_BET);
assert!(p.vpip.mean() > DEFAULT_VPIP);
assert!(p.pfr.mean() < DEFAULT_PFR);
}
}
+15
View File
@@ -18,6 +18,15 @@ pub struct Profile {
/// Share of the player's postflop actions that are bets or raises (aggression
/// frequency). Steers how much of their betting range is a bluff (`bluff_share`).
pub aggression: Option<f64>,
/// Aggression frequency on the TURN only (bets+raises over the player's turn actions). `None`
/// until the memory/HUD has turn data. The turn gearbox (`engine::turn_subgame`) prefers it over
/// the pooled `aggression`: a player who barrels turns but checks flops reads as a turn bluffer
/// here, so the defensive veto does not fold a good call against them.
pub turn_aggression: Option<f64>,
/// Aggression frequency on the RIVER only. `None` until the memory/HUD has river data. The river
/// gearbox (`engine::river_subgame`) prefers it over the pooled `aggression`, since river bluffing
/// tendency differs from flop/turn barreling.
pub river_aggression: Option<f64>,
/// How often the player continuation-bets the flop as the preflop aggressor.
pub cbet: Option<f64>,
/// How often the player folds to a continuation bet.
@@ -35,4 +44,10 @@ pub struct Profile {
pub wtsd: Option<f64>,
/// Won at showdown: how often the player wins once at showdown.
pub wsd: Option<f64>,
/// Confidence in this read, in `[0, 1)`: 0 without data, rising with the observed postflop
/// sample (half at `sim::memory::CONFIDENCE_HALF` actions). Not a tendency — it says how far the
/// read may be trusted. The river gearbox (`engine::river_subgame`) turns it into the KL trust
/// radius λ: strong read → exploit far, weak read → stay near GTO. `None` = no confidence signal
/// (treated as 0 by the gearbox). No classify/gate rule reads it; it only scales exploitation.
pub confidence: Option<f64>,
}
+27 -3
View File
@@ -5,24 +5,48 @@ use super::range_spec::RangeSpec;
use super::role_band::role_band;
use super::role_from_history::role_of;
use super::street_continuation::continuations;
use super::style::{classify, station_trust, Style};
use crate::game::{Spot, Villain};
use crate::preflop::seat_position::seat_position;
/// Without a readable preflop role the band is the plain vpip share.
/// Confidence weight for how much this villain's read may widen the modeled range: `1.0` for every
/// non-station and every genuine station (bit-identical to the binary gate), a fraction for a
/// misclassified aggressive "station" (loose width but postflop-aggressive — the CMA-ES nemesis-2,
/// aggr 0.41 → 0.16). A wide `vpip` read only widens the modeled betting range as far as the read is
/// trusted, so a wide-preflop-but-TIGHT-betting opponent is no longer modeled as an over-weak range
/// the engine then over-calls. See `station_trust` and BEFUND-nemesis-soft-trust.
fn range_trust(villain: &Villain) -> f64 {
match villain.profile.as_ref() {
Some(p) if classify(p) == Style::CallingStation => station_trust(p),
_ => 1.0,
}
}
/// Pull a read-driven value `x` toward its blind baseline by trust `c`: full read at `c = 1`, pure
/// blind at `c = 0`.
fn toward_blind(blind: f64, x: f64, c: f64) -> f64 {
blind + c * (x - blind)
}
/// Without a readable preflop role the band is the plain vpip share — trust-blended toward the
/// default (blind) vpip so a low-trust station does not over-widen the band.
fn unknown_role_band(villain: &Villain) -> (f64, f64) {
let vpip = villain
.profile
.and_then(|p| p.vpip)
.filter(|v| !v.is_nan())
.map_or(DEFAULT_VPIP, |v| v.clamp(0.02, 1.0));
(0.0, vpip)
(0.0, toward_blind(DEFAULT_VPIP, vpip, range_trust(villain)))
}
fn preflop_band(spot: &Spot, villain: &Villain) -> (f64, f64) {
match role_of(&spot.history, villain.seat) {
Some(role) => {
let (lo, hi) = role_band(spot, role, seat_position(spot, villain.seat));
stretched(lo, hi, stretch(role, villain.profile))
// The read stretches the band by the villain's looseness; blind stretch is 1.0. Trust
// scales how far the band is stretched, so a misread station's wide vpip barely widens it.
let factor = toward_blind(1.0, stretch(role, villain.profile), range_trust(villain));
stretched(lo, hi, factor)
}
None => unknown_role_band(villain),
}
+11
View File
@@ -22,6 +22,10 @@ pub const PRIOR: Profile = Profile {
pfr: Some(0.18),
fold_to_bet: Some(0.45),
aggression: Some(0.35),
// No population prior for per-street aggression: a missing one lets `shrink` pass the measured
// value through unshrunk.
turn_aggression: None,
river_aggression: None,
cbet: None,
fold_to_cbet: None,
three_bet: None,
@@ -30,6 +34,7 @@ pub const PRIOR: Profile = Profile {
check_raise: None,
wtsd: None,
wsd: None,
confidence: None,
};
/// Weight of the sample in `[0, 1)`.
@@ -55,6 +60,8 @@ pub fn shrink(profile: &Profile, hands: f64) -> Profile {
pfr: pull(profile.pfr, PRIOR.pfr, w),
fold_to_bet: pull(profile.fold_to_bet, PRIOR.fold_to_bet, w),
aggression: pull(profile.aggression, PRIOR.aggression, w),
turn_aggression: pull(profile.turn_aggression, PRIOR.turn_aggression, w),
river_aggression: pull(profile.river_aggression, PRIOR.river_aggression, w),
cbet: pull(profile.cbet, PRIOR.cbet, w),
fold_to_cbet: pull(profile.fold_to_cbet, PRIOR.fold_to_cbet, w),
three_bet: pull(profile.three_bet, PRIOR.three_bet, w),
@@ -63,5 +70,9 @@ pub fn shrink(profile: &Profile, hands: f64) -> Profile {
check_raise: pull(profile.check_raise, PRIOR.check_raise, w),
wtsd: pull(profile.wtsd, PRIOR.wtsd, w),
wsd: pull(profile.wsd, PRIOR.wsd, w),
// The sample weight IS the read confidence (same half-life): a client profile with a hand
// count earns the gearbox's trust exactly as a session-memory read does. Keep an explicit
// confidence if one was already set.
confidence: profile.confidence.or(Some(w)),
}
}
+15 -2
View File
@@ -1,5 +1,5 @@
use super::bet_ratio::bet_ratios;
use super::bluff_share::bluff_share;
use super::bluff_share::{bluff_share, with_pop_prior};
use super::made_ladder::rung;
use super::range_spec::Continuation;
use super::size_notch::size_notch;
@@ -78,6 +78,17 @@ fn merge(a: Option<Floor>, b: Option<Floor>) -> Option<Floor> {
}
}
/// Did the villain already bet or raise on an earlier postflop street? Such a line is a sustained
/// barrel - value-weighted even in the micro pool - so it earns no population over-bluff prior.
fn aggressed_earlier(history: &[ActionRecord], street: Street, seat: u8) -> bool {
history.iter().any(|r| {
r.seat == seat
&& r.street != Street::Preflop
&& (r.street as usize) < (street as usize)
&& r.action.is_aggressive()
})
}
/// One continuation for the villain on `street`, if their actions there say anything.
fn on_street(
spot: &Spot,
@@ -86,13 +97,15 @@ fn on_street(
street: Street,
) -> Option<Continuation> {
let slot = street as usize - 1;
let sustained = aggressed_earlier(&spot.history, street, villain.seat);
let made_bet =
own_aggression(&spot.history, ratios, street, villain.seat).map(|(lvl, ratio)| {
let base = [BET_RUNG, RAISE_RUNG][lvl][slot];
let bluff = bluff_share(villain.profile.as_ref(), ratio, street);
(
rung(base, size_notch(ratio) + style_rung(villain)),
DRAWS[slot],
bluff_share(villain.profile.as_ref(), ratio, street),
with_pop_prior(villain.profile.as_ref(), street, sustained, bluff),
)
});
let made_call = called_big_bet(&spot.history, ratios, street, villain.seat).then(|| {
+137 -4
View File
@@ -24,25 +24,47 @@ const NIT_FOLD_TO_BET: f64 = 0.65;
const NIT_MAX_VPIP_WITH_FOLDS: f64 = 0.25;
const STATION_FOLD_TO_BET: f64 = 0.30;
const STATION_MIN_VPIP: f64 = 0.28;
/// A calling station is loose AND postflop-passive. Above this postflop aggression frequency a
/// loose-but-not-raising player is not a station — it only looks loose preflop. Sits between the
/// reg archetype's measured 0.31 and the maniac's ~0.49; the CMA-ES nemesis measures 0.62. See the
/// `an_aggressive_loose_folder_is_not_a_station` regression test and BEFUND-nemesis-station-fehllabel.
const STATION_MAX_AGGRESSION: f64 = 0.45;
/// At or below this postflop aggression a loose-path station is trusted in FULL (`station_trust`
/// 1.0). Between here and `STATION_MAX_AGGRESSION` the station exploit is scaled down linearly — a
/// confidence ramp, not a cliff. Set above the real stations (fish 0.11, oracle 0.02) so they stay
/// bit-identical, and below the reg archetype (0.31) so a misread aggressive "station" (nemesis-2
/// aggr 0.41 → trust 0.16) barely exploits. See `station_trust` and BEFUND-nemesis-soft-trust.
const STATION_FULL_TRUST_AGGRESSION: f64 = 0.20;
/// A frequency in `[0, 1]`; NaN means "not known".
fn frequency(x: Option<f64>) -> Option<f64> {
x.filter(|v| !v.is_nan()).map(|v| v.clamp(0.0, 1.0))
}
/// Thresholds (vpip/pfr/foldToBet are all clamped to `[0, 1]` first, NaN counts as missing):
/// Thresholds (vpip/pfr/foldToBet/aggression are all clamped to `[0, 1]` first, NaN counts as missing):
/// - all missing: `Unknown`
/// - vpip >= 35 % and pfr >= 20 %: `LooseAggressive`
/// - vpip >= 35 % otherwise, or foldToBet <= 30 % with vpip >= 28 % (or unknown): `CallingStation`
/// - (vpip >= 35 % AND aggression < 45 % or unknown), or foldToBet <= 30 % with vpip >= 28 % (or
/// unknown): `CallingStation`
/// - vpip <= 15 %, or foldToBet >= 65 % with vpip <= 25 % (or unknown): `Nit`
/// - else `Regular`
///
/// A station is loose AND passive: the `loose` → `CallingStation` path is gated on postflop
/// aggression (`STATION_MAX_AGGRESSION`) so a loose-preflop but aggression-heavy frequent-folder
/// (the CMA-ES nemesis: vpip 0.53, pfr 0.14, foldToBet 0.65, aggression 0.62) reads `Regular` — gated
/// to blind by `read_gate`, the proven-safe baseline — instead of being handed `earned_trust 1.0`
/// and the station exploit it then bled −448 bb/100 to. The `sticky` path (fold ≤ 30 %) is a real
/// non-folder and stays a station regardless of aggression.
pub fn classify(profile: &Profile) -> Style {
let (vpip, pfr, fold) = (
let (vpip, pfr, fold, aggr) = (
frequency(profile.vpip),
frequency(profile.pfr),
frequency(profile.fold_to_bet),
frequency(profile.aggression),
);
let loose = vpip.is_some_and(|v| v >= LOOSE_VPIP);
// Postflop-passive: a station does not fire back. Unknown aggression keeps the old behaviour.
let passive = aggr.is_none_or(|a| a < STATION_MAX_AGGRESSION);
let sticky = fold.is_some_and(|b| b <= STATION_FOLD_TO_BET)
&& vpip.is_none_or(|v| v >= STATION_MIN_VPIP);
let tight = vpip.is_some_and(|v| v <= NIT_VPIP)
@@ -52,7 +74,7 @@ pub fn classify(profile: &Profile) -> Style {
Style::Unknown
} else if loose && pfr.is_some_and(|f| f >= AGGRESSIVE_PFR) {
Style::LooseAggressive
} else if loose || sticky {
} else if (loose && passive) || sticky {
Style::CallingStation
} else if tight {
Style::Nit
@@ -60,3 +82,114 @@ pub fn classify(profile: &Profile) -> Style {
Style::Regular
}
}
/// How much to trust a `CallingStation` read, in `[0, 1]` — the confidence-weighted generalization
/// of the binary `earned_trust` gate (`engine::read_gate` keeps a station's profile or drops it; this
/// says HOW MUCH of the station exploit to apply to what it keeps). Only meaningful for a profile
/// that already classifies `CallingStation`; the station-exploit channels (`adjust`'s value shift,
/// `style_rung`'s made-floor rung) scale their deviation from blind by this weight.
///
/// A station earns full trust on either signal: it does not fold (sticky, `fold_to_bet` ≤ 30 %) —
/// value-betting it thin is always right — OR it is postflop-passive (low `aggression`). The
/// aggression ramp governs only the loose-WIDTH path, where a high `vpip` alone made the old binary
/// gate hand full trust to aggressive frequent-folders (the CMA-ES nemesis-2, aggr 0.41, folds 56 %)
/// that then bled to the over-call. Unknown aggression keeps the old full trust (no postflop sample
/// to doubt). A genuine station (fish, oracle) returns exactly `1.0` → bit-identical to the old gate.
pub fn station_trust(profile: &Profile) -> f64 {
// A real non-folder is a station on the strongest signal; aggression does not weaken that.
if frequency(profile.fold_to_bet).is_some_and(|b| b <= STATION_FOLD_TO_BET) {
return 1.0;
}
match frequency(profile.aggression) {
None => 1.0,
Some(a) => ((STATION_MAX_AGGRESSION - a)
/ (STATION_MAX_AGGRESSION - STATION_FULL_TRUST_AGGRESSION))
.clamp(0.0, 1.0),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn profile(vpip: f64, pfr: f64, fold: f64, aggr: f64) -> Profile {
Profile {
vpip: Some(vpip),
pfr: Some(pfr),
fold_to_bet: Some(fold),
aggression: Some(aggr),
..Profile::default()
}
}
/// The CMA-ES nemesis read: loose preflop (vpip 0.53) but a hyper-aggressive frequent-folder
/// (aggression 0.62, foldToBet 0.65). Width alone made the old `loose` path label it a station,
/// handing it earned_trust and the station exploit it bled −448 bb/100 to. It must read `Regular`
/// (gated to blind), not `CallingStation`.
#[test]
fn an_aggressive_loose_folder_is_not_a_station() {
let p = profile(0.53, 0.14, 0.65, 0.62);
assert_eq!(classify(&p), Style::Regular);
}
/// A genuinely loose-passive opponent (low aggression) is still a `CallingStation` — the fix
/// gates on aggression, not on preflop width, so the real station is untouched.
#[test]
fn a_loose_passive_opponent_is_still_a_station() {
let p = profile(0.70, 0.05, 0.25, 0.10);
assert_eq!(classify(&p), Style::CallingStation);
}
/// A sticky non-folder (foldToBet ≤ 30 %) stays a station regardless of aggression — not folding
/// is itself the station signal; the aggression gate applies only to the `loose` path.
#[test]
fn a_sticky_non_folder_stays_a_station_even_if_aggressive() {
let p = profile(0.40, 0.10, 0.20, 0.60);
assert_eq!(classify(&p), Style::CallingStation);
}
/// Aggression unknown (not yet measured) keeps the old width-based station read, so nothing
/// regresses for profiles without a postflop sample.
#[test]
fn unknown_aggression_keeps_the_width_based_station() {
let p = Profile { vpip: Some(0.50), pfr: Some(0.10), fold_to_bet: Some(0.45), ..Profile::default() };
assert_eq!(classify(&p), Style::CallingStation);
}
/// A genuine passive station (fish: aggr 0.11) and a non-folder earn FULL trust — the soft gate
/// is bit-identical to the old binary gate for the stations that were always right to exploit.
#[test]
fn a_passive_station_earns_full_trust() {
let fish = profile(0.55, 0.08, 0.40, 0.11); // loose path (folds 40 %), very passive
assert_eq!(station_trust(&fish), 1.0);
let non_folder = profile(0.40, 0.10, 0.20, 0.60); // sticky: never folds → full trust despite aggression
assert_eq!(station_trust(&non_folder), 1.0);
}
/// A misclassified aggressive loose "station" (nemesis-2: loose width, folds 56 %, aggr 0.41)
/// earns only a sliver of trust, so the station exploit barely fires on it.
#[test]
fn a_misread_aggressive_station_earns_little_trust() {
let nemesis2 = profile(0.65, 0.15, 0.56, 0.41);
let c = station_trust(&nemesis2);
assert!(c > 0.0 && c < 0.25, "expected a small trust, got {c}");
}
/// Trust falls monotonically as the loose-path station gets more aggressive, reaching 0 at the
/// classify boundary — a smooth handoff to `Regular` (gated blind), no cliff.
#[test]
fn loose_station_trust_ramps_down_with_aggression() {
let at = |a: f64| station_trust(&profile(0.55, 0.10, 0.50, a));
assert_eq!(at(0.20), 1.0);
assert!((at(0.325) - 0.5).abs() < 1e-9);
assert_eq!(at(0.45), 0.0);
assert!(at(0.25) > at(0.35));
}
/// Unknown aggression keeps full trust: no postflop sample is no reason to doubt the read.
#[test]
fn unknown_aggression_keeps_full_station_trust() {
let p = Profile { vpip: Some(0.50), pfr: Some(0.10), fold_to_bet: Some(0.45), ..Profile::default() };
assert_eq!(station_trust(&p), 1.0);
}
}
+11 -4
View File
@@ -1,12 +1,19 @@
use super::style::{classify, Style};
use super::style::{classify, station_trust, Style};
use crate::game::Villain;
/// How a villain's style moves a made-hand floor on `made_ladder`: looser styles
/// (calling station, loose-aggressive) one rung down, the nit one up.
///
/// The station's `-1` rung (model its bets one rung weaker → bluff-catch wider) is confidence-gated:
/// it fires only for a genuinely passive station (`station_trust` ≥ 0.5). A misclassified aggressive
/// "station" (nemesis-2, aggr 0.41 → trust 0.16) keeps the blind made-floor and is not over-called.
/// A genuine passive station / non-folder (trust 1.0) rounds to `-1`, bit-identical to before.
pub fn style_rung(villain: &Villain) -> i32 {
match villain.profile.map(|p| classify(&p)) {
Some(Style::CallingStation | Style::LooseAggressive) => -1,
Some(Style::Nit) => 1,
let Some(profile) = villain.profile.as_ref() else { return 0 };
match classify(profile) {
Style::CallingStation => -(station_trust(profile).round() as i32),
Style::LooseAggressive => -1,
Style::Nit => 1,
_ => 0,
}
}
+227
View File
@@ -0,0 +1,227 @@
//! Thompson-Sampling: jeder Arm haelt ein Beta(a,b) ueber seine Erfolgsquote.
//! Waehlen = je Arm ziehen, Argmax nehmen; danach konjugiert nachziehen.
//! Eine Aktion hat zwei Renditen: Chips und das, was sie verraet (Explorationswert).
use crate::rng::split_mix::Rng;
/// Beta-Glaube; Start Beta(1,1) = gleichverteilt.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Posterior {
pub alpha: f64,
pub beta: f64,
}
impl Posterior {
pub const fn uniform() -> Posterior {
Posterior { alpha: 1.0, beta: 1.0 }
}
pub const fn new(alpha: f64, beta: f64) -> Posterior {
Posterior { alpha, beta }
}
pub fn mean(&self) -> f64 {
self.alpha / (self.alpha + self.beta)
}
/// Konjugiertes Update; `reward` in [0,1] (Bernoulli 0/1 oder Bruchteil).
pub fn update(&mut self, reward: f64) {
let r = reward.clamp(0.0, 1.0);
self.alpha += r;
self.beta += 1.0 - r;
}
/// Eine Ziehung aus Beta(a,b) ueber Gamma-Verhaeltnis.
pub fn sample(&self, rng: &mut Rng) -> f64 {
let x = gamma(self.alpha, rng);
let y = gamma(self.beta, rng);
let s = x + y;
if s > 0.0 { x / s } else { self.mean() }
}
}
fn unit_open(rng: &mut Rng) -> f64 {
let (u, next) = rng.unit();
*rng = next;
u.max(f64::MIN_POSITIVE)
}
fn normal(rng: &mut Rng) -> f64 {
let u1 = unit_open(rng);
let u2 = unit_open(rng);
(-2.0 * u1.ln()).sqrt() * (std::f64::consts::TAU * u2).cos()
}
/// Gamma(shape, 1) nach Marsaglia-Tsang; shape < 1 per Boost u^(1/shape).
fn gamma(shape: f64, rng: &mut Rng) -> f64 {
if shape < 1.0 {
let g = gamma(shape + 1.0, rng);
return g * unit_open(rng).powf(1.0 / shape);
}
let d = shape - 1.0 / 3.0;
let c = 1.0 / (9.0 * d).sqrt();
loop {
let x = normal(rng);
let v = 1.0 + c * x;
if v <= 0.0 {
continue;
}
let v = v * v * v;
let u = unit_open(rng);
if u.ln() < 0.5 * x * x + d - d * v + d * v.ln() {
return d * v;
}
}
}
/// k Arme mit je einem Posterior.
#[derive(Clone, Debug)]
pub struct Bandit {
pub arms: Vec<Posterior>,
}
impl Bandit {
pub fn new(k: usize) -> Bandit {
Bandit { arms: vec![Posterior::uniform(); k] }
}
/// Thompson-Zug: je Arm ziehen, Argmax (erster bei Gleichstand).
pub fn choose(&mut self, rng: &mut Rng) -> usize {
let mut best = 0;
let mut best_v = f64::NEG_INFINITY;
for (i, p) in self.arms.iter().enumerate() {
let v = p.sample(rng);
if v > best_v {
best_v = v;
best = i;
}
}
best
}
pub fn update(&mut self, arm: usize, reward: f64) {
self.arms[arm].update(reward);
}
}
#[cfg(test)]
mod tests {
use super::*;
const MEANS: [f64; 3] = [0.3, 0.5, 0.8];
const T: usize = 2000;
fn pull(mean: f64, rng: &mut Rng) -> f64 {
let (u, n) = rng.unit();
*rng = n;
if u < mean { 1.0 } else { 0.0 }
}
/// (kumulatives Bedauern, Zuege je Arm, Zuege je Arm in der letzten Haelfte)
fn run_thompson(seed: u64) -> (f64, [usize; 3], [usize; 3]) {
let mut rng = Rng::seeded(seed);
let mut b = Bandit::new(3);
let (mut regret, mut n, mut late) = (0.0, [0; 3], [0; 3]);
for t in 0..T {
let a = b.choose(&mut rng);
b.update(a, pull(MEANS[a], &mut rng));
regret += 0.8 - MEANS[a];
n[a] += 1;
if t >= T / 2 {
late[a] += 1;
}
}
(regret, n, late)
}
/// Basislinie: eps-greedy auf Empirie (eps = 0.1), erst jeden Arm einmal.
fn run_eps_greedy(seed: u64, eps: f64) -> (f64, [usize; 3]) {
let mut rng = Rng::seeded(seed);
let (mut regret, mut n, mut sum) = (0.0, [0usize; 3], [0.0f64; 3]);
for t in 0..T {
let (u, nx) = rng.unit();
rng = nx;
let a = if t < 3 {
t
} else if u < eps {
let (r, nx) = rng.below(3);
rng = nx;
r as usize
} else {
(0..3)
.max_by(|&i, &j| (sum[i] / n[i] as f64).total_cmp(&(sum[j] / n[j] as f64)))
.unwrap()
};
sum[a] += pull(MEANS[a], &mut rng);
n[a] += 1;
regret += 0.8 - MEANS[a];
}
(regret, n)
}
#[test]
fn beta_sampler_matches_moments() {
let mut rng = Rng::seeded(7);
for &(a, b) in &[(1.0, 1.0), (2.0, 5.0), (0.5, 0.5), (30.0, 10.0)] {
let p = Posterior::new(a, b);
let n = 20000;
let xs: Vec<f64> = (0..n).map(|_| p.sample(&mut rng)).collect();
let m = xs.iter().sum::<f64>() / n as f64;
let v = xs.iter().map(|x| (x - m) * (x - m)).sum::<f64>() / n as f64;
let tv = a * b / ((a + b) * (a + b) * (a + b + 1.0));
assert!((m - p.mean()).abs() < 0.01, "mean {a},{b}: {m}");
assert!((v - tv).abs() < 0.1 * tv + 1e-4, "var {a},{b}: {v} vs {tv}");
assert!(xs.iter().all(|x| (0.0..=1.0).contains(x)));
}
}
#[test]
fn update_is_conjugate() {
let mut p = Posterior::uniform();
p.update(1.0);
p.update(0.0);
p.update(1.0);
assert_eq!((p.alpha, p.beta), (3.0, 2.0));
}
#[test]
fn deterministic() {
assert_eq!(run_thompson(5), run_thompson(5));
}
#[test]
fn thompson_beats_baseline_regret() {
let seeds = 20u64;
let (mut rt, mut re, mut rg) = (0.0, 0.0, 0.0);
let (mut nt, mut ne) = ([0usize; 3], [0usize; 3]);
let mut late = [0usize; 3];
for s in 0..seeds {
let (r, n, l) = run_thompson(1000 + s);
rt += r;
for i in 0..3 {
nt[i] += n[i];
late[i] += l[i];
}
let (r, n) = run_eps_greedy(1000 + s, 0.1);
re += r;
for i in 0..3 {
ne[i] += n[i];
}
rg += run_eps_greedy(1000 + s, 0.0).0;
}
let k = seeds as f64;
println!("Regret ueber T={T}, Mittel aus {seeds} Seeds:");
println!(" Thompson {:.1}", rt / k);
println!(" eps-greedy {:.1} (eps=0.1)", re / k);
println!(" greedy {:.1} (eps=0)", rg / k);
println!("Zuege je Arm (Mittel) Thompson {:?}", nt.map(|x| x / seeds as usize));
println!("Zuege je Arm (Mittel) eps-greedy {:?}", ne.map(|x| x / seeds as usize));
let half = (T / 2) as f64 * k;
let share = late[2] as f64 / half;
println!("Thompson Anteil bester Arm, 2. Haelfte: {share:.3}");
assert!(rt < 0.6 * re, "Thompson {rt} vs eps-greedy {re}");
assert!(rt < rg, "Thompson {rt} vs greedy {rg}");
assert!(share > 0.9, "konzentriert nicht: {share}");
assert!(nt[2] > nt[1] && nt[1] > nt[0]);
}
}
+38
View File
@@ -139,3 +139,41 @@ pub fn jam_width_factor(pressure: f64) -> f64 {
let severity = (pressure / MAX_PREMIUM).clamp(0.0, 1.0);
1.0 + JAM_WIDEN_SPAN * severity.powi(JAM_CONVEXITY)
}
/// Effective depth (big blinds) below which the open-jam widening applies in FULL, and above which
/// it fades to nothing. The ICM open-jam widening is a SHORT-stack lever (push/fold territory): a
/// deep hero that merely COVERS a short should not widen its opening range, or it opens junk from
/// depth that gets called and punished. Measured: the `cover-short` LECK (−12.5 ICM$/100 on the
/// strength ladder, `sim::turnier_leiter`), corroborated by the repo's ICM-Nash solver over-jamming
/// at short stacks. The 10bb push/fold calibration (`entscheiden/turnier_benchmark`) sits BELOW
/// `JAM_DEPTH_FULL`, so the gate leaves it bit-untouched; it only quiets the deep coverer.
pub const JAM_DEPTH_FULL: f64 = 12.0;
pub const JAM_DEPTH_NONE: f64 = 22.0;
/// Taper in `[0, 1]` on the open-jam widening by hero's effective depth: 1 at/below
/// `JAM_DEPTH_FULL`, 0 at/above `JAM_DEPTH_NONE`, linear between. Apply to the EXCESS of
/// `jam_width_factor` over 1 (`1 + (w - 1) * gate`), so a short jammer widens fully and a deep
/// coverer not at all.
pub fn jam_depth_gate(depth_bb: f64) -> f64 {
((JAM_DEPTH_NONE - depth_bb) / (JAM_DEPTH_NONE - JAM_DEPTH_FULL)).clamp(0.0, 1.0)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn jam_depth_gate_full_when_short_zero_when_deep_and_monotone() {
// Short stack (push/fold territory incl. the 10bb Nash spot): full widening, unchanged.
assert_eq!(jam_depth_gate(5.0), 1.0);
assert_eq!(jam_depth_gate(10.0), 1.0, "the 10bb Nash calibration stays untouched");
assert_eq!(jam_depth_gate(JAM_DEPTH_FULL), 1.0);
// Deep coverer (the cover-short LECK): no widening.
assert_eq!(jam_depth_gate(JAM_DEPTH_NONE), 0.0);
assert_eq!(jam_depth_gate(40.0), 0.0);
// Linear, monotone non-increasing between.
let mid = jam_depth_gate(17.0);
assert!(mid > 0.0 && mid < 1.0, "tapers in between: {mid}");
assert!(jam_depth_gate(13.0) >= jam_depth_gate(18.0));
}
}
+360
View File
@@ -0,0 +1,360 @@
//! Stufe 3 of the synthetic lab: ADAPTIVE opponents — the mind-game frontier.
//!
//! The static population (`sim::population`, Stufe 0) measures exploitation: the engine infers a
//! *fixed* hidden type and attacks it. But a real opponent is a moving target — they watch the hero
//! and shift. That is where image, sequencing and mind-games live, and the fixed-bot ladder (and even
//! the static population) cannot touch it.
//!
//! Here the opponent carries a running model of the hero (`HeroModel`: the hero's observed postflop
//! aggression) and re-derives its own ruleset every hand (`adapt`), played through the
//! `Opponent::Styled(Rules)` seam built in Stufe 0 — so NO table change is needed, the opponent is
//! just handed a fresh `Rules` each hand. Two reaction styles bracket the realistic human responses to
//! an aggressor:
//!
//! - `Tighten`: gives the aggressor no action — needs a stronger hand to call, bluffs less. A good
//! engine should *increase* its bluffing against this (they fold too much).
//! - `Loosen`: the hero-caller — suspects bluffs and calls down lighter. A good engine should bluff
//! *less* and value-bet thinner against this.
//!
//! The measurement is paired: the SAME drawn opponent and the SAME deals are played once with the
//! opponent `Static` (the Stufe-0 memory baseline) and once `adapt`ing. The per-deal difference,
//! pooled over the field, is the bb/100 the opponent's adaptation costs (or, if negative for the
//! opponent, earns) the engine — i.e. how much the engine's *stationary* read is worth against a
//! *moving* target. A negative delta is the mind-game tax the engine pays for not tracking the shift;
//! a positive delta means the opponent's reaction opens a leak the engine already exploits.
use super::memory::SessionMemory;
use super::opponent::Opponent;
use super::paired::compare;
use super::population::Population;
use super::reader::Rules;
use super::sequential::ConfSeq;
use super::table::{deal, play_hand_history, HandRead, HandSetup, TableCost};
use crate::game::Street;
use crate::rng::Rng;
use std::thread;
const STACK_BB: f64 = 100.0;
const PLAYERS: u8 = 2;
/// Hands the opponent watches before it starts adapting: an early, noisy read of the hero would
/// swing the ruleset on nothing. Matches the spirit of the engine's own `memory::WARMUP_HANDS`.
const ADAPT_WARMUP: u32 = 20;
/// The hero aggression the base ruleset is tuned for; the opponent reacts to the deviation from it.
const REF_AGGRESSION: f64 = 0.30;
/// How hard the opponent swings its calling threshold per unit of excess hero aggression.
const ADAPT_GAIN: f64 = 0.7;
/// How a league opponent reacts to the hero it observes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Adapt {
/// Ignores the hero entirely — the Stufe-0 behaviour, the paired control (league L0).
Static,
/// L1 reactive: tightens against an aggressive hero on the raw frequency — raises its calling bar,
/// bluffs less ("he's a maniac, give him nothing").
Tighten,
/// L1 reactive: loosens against an aggressive hero on the raw frequency — calls down lighter to
/// catch bluffs ("he bluffs too much").
Loosen,
/// L2 modelling: keeps a Beta posterior over the hero's bluff rate and counters only by how much a
/// one-sigma LOWER confidence bound exceeds the reference. Against a balanced or thinly-sampled hero
/// the posterior is wide, the lower bound stays near the reference, and it does not overadjust —
/// the Bayesian answer to L1's twitchiness, and the opponent-side mirror of the engine's own
/// confidence-gated exploitation.
Model,
}
impl Adapt {
pub fn name(self) -> &'static str {
match self {
Adapt::Static => "static",
Adapt::Tighten => "tighten",
Adapt::Loosen => "loosen",
Adapt::Model => "model",
}
}
}
/// The opponent's running model of the hero: postflop aggressive vs passive action counts.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct HeroModel {
aggressive: u32,
passive: u32,
}
impl HeroModel {
pub fn new() -> Self {
Self::default()
}
/// Fold the hero's postflop actions of one finished hand into the model. `hero_seat` is 1-based,
/// matching `ActionRecord::seat`.
pub fn observe(&mut self, history: &[crate::game::ActionRecord], hero_seat: u8) {
for r in history.iter().filter(|r| r.seat == hero_seat && r.street != Street::Preflop) {
if r.action.is_aggressive() {
self.aggressive += 1;
} else if matches!(r.action, crate::game::SeenAction::Call | crate::game::SeenAction::Check)
{
self.passive += 1;
}
}
}
/// Observed postflop aggression frequency, or the neutral reference before any postflop action.
pub fn aggression(&self) -> f64 {
let n = self.aggressive + self.passive;
if n == 0 {
REF_AGGRESSION
} else {
self.aggressive as f64 / n as f64
}
}
/// One-sigma LOWER confidence bound on the hero's bluff (aggression) rate under a Beta(1+aggr,
/// 1+passive) posterior: mean − sqrt(variance). Wide (thin or balanced) posteriors pull this toward
/// the prior, so a counter gated on it does not overreact to noise. Used by `Adapt::Model` (L2).
pub fn bluff_lcb(&self) -> f64 {
let a = 1.0 + self.aggressive as f64;
let b = 1.0 + self.passive as f64;
let s = a + b;
let mean = a / s;
let var = a * b / (s * s * (s + 1.0));
(mean - var.sqrt()).max(0.0)
}
pub fn actions_seen(&self) -> u32 {
self.aggressive + self.passive
}
}
/// Re-derive the opponent's ruleset for the next hand from its model of the hero. `Static` and the
/// warmup both return `base` unchanged, so a `Static` run reproduces the Stufe-0 memory baseline
/// exactly. Only *excess* aggression (above the reference) moves the thresholds — a passive hero gets
/// the base ruleset either way.
pub fn adapt(base: Rules, model: &HeroModel, style: Adapt) -> Rules {
if style == Adapt::Static || model.actions_seen() < ADAPT_WARMUP {
return base;
}
let excess = (model.aggression() - REF_AGGRESSION).max(0.0);
let mut r = base;
match style {
Adapt::Static => {}
Adapt::Tighten => {
r.call_margin = (base.call_margin + ADAPT_GAIN * excess).clamp(0.0, 0.6);
r.bluff = (base.bluff - 0.5 * ADAPT_GAIN * excess).clamp(0.0, 1.0);
}
Adapt::Loosen => {
r.call_margin = (base.call_margin - ADAPT_GAIN * excess).clamp(0.0, 0.6);
}
Adapt::Model => {
// Beta(1+aggr, 1+passive) posterior over the hero's bluff rate; counter by the one-sigma
// LOWER bound's excess over the reference, so uncertainty (a wide posterior) yields no
// move and only a confidently-high bluff rate loosens the calling bar.
let lcb_excess = (model.bluff_lcb() - REF_AGGRESSION).max(0.0);
r.call_margin = (base.call_margin - ADAPT_GAIN * lcb_excess).clamp(0.0, 0.6);
}
}
r
}
fn mix(seed: u64, n: u64) -> u64 {
Rng::seeded(seed ^ n.wrapping_mul(0xD1B5_4A32_D192_ED03)).next_u64().0
}
/// Play one heads-up session against ONE drawn opponent, threading the hero's read (`SessionMemory`,
/// the real inference path) and the opponent's model of the hero across every hand, duplicating each
/// deal over both seats so position and card luck cancel within a sample. Returns the per-deal
/// luck-corrected hero result in bb. With `Adapt::Static` this is exactly the Stufe-0 memory run.
pub fn session_samples(base: Rules, deals: u32, seed: u64, style: Adapt) -> Vec<f64> {
let mut hero_mem = SessionMemory::new();
let mut hero_model = HeroModel::new();
let mut samples = Vec::with_capacity(deals as usize);
for d in 0..deals {
let (cards, _) = deal(PLAYERS as usize, Rng::seeded(mix(seed, d as u64)));
let mut sum = 0.0;
for hero_seat in 1..=PLAYERS {
let rules = adapt(base, &hero_model, style);
let hand = HandSetup {
deal: &cards,
hero_seat,
opponent: Opponent::Styled(rules),
stack_bb: STACK_BB,
// The hero infers the opponent from its own observed actions, same as memory mode.
read: HandRead::Given(hero_mem.read()),
seed: mix(seed ^ 0xA5A5, (d as u64) << 8 | hero_seat as u64),
};
let (r, history) = play_hand_history(&hand, TableCost::FREE);
sum += r.hero_net - r.luck;
hero_mem.observe_hand(&history, hero_seat as usize - 1, PLAYERS as usize);
hero_model.observe(&history, hero_seat);
}
samples.push(sum / PLAYERS as f64);
}
samples
}
#[derive(Clone, Debug)]
pub struct AdaptReport {
pub style: &'static str,
pub opponents: usize,
pub deals_each: u32,
/// Engine win rate against the field with the opponent static (the Stufe-0 memory baseline).
pub static_bb_per_100: f64,
/// Engine win rate against the field with the opponent adapting to the hero.
pub adaptive_bb_per_100: f64,
/// adaptive - static, pooled and paired over the SAME deals (card luck cancels). The mind-game
/// effect on the engine's edge: negative = the engine's stationary read bleeds against the shift.
pub delta_bb_per_100: f64,
/// Paired 95 % half width of the delta (`sim::paired`).
pub ci95: f64,
/// Anytime 95 % half width of the delta (`sim::sequential`) — valid under peeking.
pub anytime_ci95: f64,
}
struct One {
stat: Vec<f64>,
adap: Vec<f64>,
}
fn run_one(pop: &Population, k: usize, deals: u32, seed: u64, style: Adapt) -> One {
let (draw, _) = pop.sample(Rng::seeded(seed ^ (k as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15)));
let base = draw.rules;
let hand_seed = seed ^ (k as u64).wrapping_mul(0xD1B5_4A32_D192_ED03);
One {
stat: session_samples(base, deals, hand_seed, Adapt::Static),
adap: session_samples(base, deals, hand_seed, style),
}
}
/// Measure how much an `adapt`ing field changes the engine's edge versus the same field held static.
/// Deterministic in `seed`; threaded over opponents.
pub fn adaptive_effect(
pop: &Population,
opponents: usize,
deals: u32,
seed: u64,
style: Adapt,
) -> AdaptReport {
let results: Vec<One> = thread::scope(|scope| {
let handles: Vec<_> = (0..opponents)
.map(|k| scope.spawn(move || run_one(pop, k, deals, seed, style)))
.collect();
handles.into_iter().map(|h| h.join().expect("an opponent panicked")).collect()
});
let mut stat_all = Vec::new();
let mut adap_all = Vec::new();
let mut cs = ConfSeq::new(0.05, (opponents as u64 * deals as u64).max(1));
for one in &results {
for (s, a) in one.stat.iter().zip(&one.adap) {
stat_all.push(*s);
adap_all.push(*a);
cs.push(a - s);
}
}
let cmp = compare(&stat_all, &adap_all).expect("non-empty paired diffs");
let mean = |v: &[f64]| 100.0 * v.iter().sum::<f64>() / v.len().max(1) as f64;
AdaptReport {
style: style.name(),
opponents,
deals_each: deals,
static_bb_per_100: mean(&stat_all),
adaptive_bb_per_100: mean(&adap_all),
delta_bb_per_100: cmp.delta_bb_per_100,
ci95: cmp.ci95,
anytime_ci95: 100.0 * cs.radius(),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn hero_model_counts_postflop_aggression() {
use crate::game::{ActionRecord, SeenAction};
let h = |street, seat, action| ActionRecord { street, seat, action, amount: None };
let history = vec![
h(Street::Preflop, 1, SeenAction::Raise), // preflop ignored
h(Street::Flop, 1, SeenAction::Bet), // aggressive
h(Street::Turn, 1, SeenAction::Check), // passive
h(Street::River, 1, SeenAction::Bet), // aggressive
h(Street::Flop, 2, SeenAction::Call), // other seat, ignored for hero_seat 1
];
let mut m = HeroModel::new();
m.observe(&history, 1);
assert_eq!(m.actions_seen(), 3);
assert!((m.aggression() - 2.0 / 3.0).abs() < 1e-9);
}
#[test]
fn adapt_is_identity_when_static_or_in_warmup() {
let base = crate::sim::reader::Style::Reg.rules();
let mut model = HeroModel::new();
model.aggressive = 100;
model.passive = 0; // hyper-aggressive, but...
// static always returns base
assert_eq!(adapt(base, &model, Adapt::Static), base);
// a fresh model is in warmup -> base even under Tighten
let fresh = HeroModel::new();
assert_eq!(adapt(base, &fresh, Adapt::Tighten), base);
}
#[test]
fn tighten_raises_the_calling_bar_against_an_aggressor() {
let base = crate::sim::reader::Style::Reg.rules();
let mut model = HeroModel::new();
model.aggressive = 80;
model.passive = 20; // 0.8 aggression, well above the 0.30 reference
let t = adapt(base, &model, Adapt::Tighten);
assert!(t.call_margin > base.call_margin, "tighten should fold more");
assert!(t.bluff <= base.bluff, "tighten should bluff no more");
let l = adapt(base, &model, Adapt::Loosen);
assert!(l.call_margin < base.call_margin, "loosen should call lighter");
}
#[test]
fn a_passive_hero_leaves_the_ruleset_at_base() {
let base = crate::sim::reader::Style::Reg.rules();
let mut model = HeroModel::new();
model.aggressive = 5;
model.passive = 95; // below the reference -> no excess -> no change
assert_eq!(adapt(base, &model, Adapt::Tighten), base);
}
#[test]
fn l2_model_waits_for_confidence_before_it_counters() {
// Same 70 % bluff FREQUENCY, two sample sizes. L1 (Tighten/Loosen) reacts to the frequency
// regardless; L2 (Model) gates on the posterior's lower bound, so the thin sample must not move
// the ruleset while the thick one does.
let base = crate::sim::reader::Style::Reg.rules();
let mut thin = HeroModel::new();
thin.aggressive = 21; // past the warmup, but a wide posterior
thin.passive = 9;
let mut thick = HeroModel::new();
thick.aggressive = 210; // same 0.70 mean, a tight posterior
thick.passive = 90;
assert!((thin.aggression() - thick.aggression()).abs() < 1e-9, "same frequency");
// L1 loosens on both (frequency-driven).
assert!(adapt(base, &thin, Adapt::Loosen).call_margin < base.call_margin);
assert!(adapt(base, &thick, Adapt::Loosen).call_margin < base.call_margin);
// L2 counters harder when confident: the thick sample loosens strictly more than the thin one.
let thin_cm = adapt(base, &thin, Adapt::Model).call_margin;
let thick_cm = adapt(base, &thick, Adapt::Model).call_margin;
assert!(thick_cm < thin_cm, "confident over-bluff must loosen more: thin={thin_cm:.3} thick={thick_cm:.3}");
assert!(thick_cm < base.call_margin, "confident over-bluff must loosen below base");
}
#[test]
fn effect_runs_and_is_finite() {
let pop = Population::micro();
let r = adaptive_effect(&pop, 4, 25, 0x5EED_0001, Adapt::Tighten);
println!(
"static {:+.1} adaptive {:+.1} delta {:+.2} +-{:.2} (anytime +-{:.2})",
r.static_bb_per_100, r.adaptive_bb_per_100, r.delta_bb_per_100, r.ci95, r.anytime_ci95
);
assert!(r.delta_bb_per_100.is_finite() && r.ci95.is_finite());
}
}
+110
View File
@@ -0,0 +1,110 @@
//! AIVAT-artige Varianzreduktion: Kontrollvariate mit BEKANNTEM Erwartungswert (Glueck-Term,
//! z. B. realisierte minus erwartete Equity je Hand). Schaetzer y - beta*(c - mu_c) bleibt
//! erwartungstreu; beta wird per Kreuzanpassung (Faltung) aus den uebrigen Haenden gelernt,
//! damit beta nicht mit der eigenen Hand korreliert (sonst O(1/n)-Verzerrung).
//! Umgesetzt: Kontrollvariate je Hand (Chance-/Showdown-Glueck, Entscheidungs-Baseline).
//! Nicht umgesetzt: volle AIVAT-Korrektur jedes Chance- und Gegnerknotens im Baum.
//! Annahme: c korreliert mit dem Rauschen von y; Reduktion ~ 1 - rho^2. Ohne Korrelation
//! kein Gewinn, aber auch keine Verzerrung.
const Z95: f64 = 1.96;
/// (Mittel, 95-%-Halbbreite), beides in den Einheiten der Eingabe.
pub fn raw(y: &[f64]) -> (f64, f64) {
let n = y.len() as f64;
if y.len() < 2 {
return (y.first().copied().unwrap_or(0.0), f64::INFINITY);
}
let m = y.iter().sum::<f64>() / n;
let v = y.iter().map(|x| (x - m).powi(2)).sum::<f64>() / (n - 1.0);
(m, Z95 * (v / n).sqrt())
}
/// Kontrollvariate `c` mit bekanntem Erwartungswert `mu_c`; `folds` >= 2 Kreuzanpassung.
pub fn control_variate(y: &[f64], c: &[f64], mu_c: f64, folds: usize) -> Result<(f64, f64), String> {
let n = y.len();
if n != c.len() || n < 4 || folds < 2 || folds > n {
return Err(format!("{} Ergebnisse, {} Kontrollwerte, {} Faltungen", n, c.len(), folds));
}
let mut adj = Vec::with_capacity(n);
for k in 0..folds {
let (mut sy, mut sc, mut syc, mut scc, mut m) = (0.0, 0.0, 0.0, 0.0, 0.0);
for i in (0..n).filter(|i| i % folds != k) {
sy += y[i];
sc += c[i];
syc += y[i] * c[i];
scc += c[i] * c[i];
m += 1.0;
}
let var_c = scc / m - (sc / m).powi(2);
let beta = if var_c > 1e-12 { (syc / m - sy / m * sc / m) / var_c } else { 0.0 };
adj.extend((0..n).filter(|i| i % folds == k).map(|i| y[i] - beta * (c[i] - mu_c)));
}
Ok(raw(&adj))
}
#[cfg(test)]
mod tests {
use super::*;
struct Lcg(u64);
impl Lcg {
fn unif(&mut self) -> f64 {
self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
((self.0 >> 11) as f64 + 0.5) / (1u64 << 53) as f64
}
fn normal(&mut self) -> f64 {
(-2.0 * self.unif().ln()).sqrt() * (6.2831853 * self.unif()).cos()
}
}
/// Ergebnis = Signal + Glueck (EV-gegen-Realisierung) + Restrauschen; c = Glueck, Mittel 0.
fn daten(n: usize, seed: u64) -> (Vec<f64>, Vec<f64>) {
let mut r = Lcg(seed);
let (mut y, mut c) = (Vec::new(), Vec::new());
for _ in 0..n {
let luck = 8.0 * r.normal();
let rest = 2.0 * r.normal();
y.push(5.0 + luck + rest); // Signal 5 bb pro Hand
c.push(luck + 0.5 * r.normal()); // verrauschtes, aber korreliertes Glueckmass
}
(y, c)
}
#[test]
fn kontrollvariate_gleicher_mittelwert_engeres_ci() {
let (y, c) = daten(5000, 42);
let (m0, h0) = raw(&y);
let (m1, h1) = control_variate(&y, &c, 0.0, 10).unwrap();
println!("roh: mean {:.3} ci95 +-{:.3}", m0, h0);
println!("aivat: mean {:.3} ci95 +-{:.3}", m1, h1);
println!("Varianzfaktor {:.2}x, CI {:.0} % schmaler", (h0 / h1).powi(2), 100.0 * (1.0 - h1 / h0));
assert!((m1 - m0).abs() < h0, "Mittel verschoben");
assert!(h1 < 0.7 * h0, "CI nicht >= 30 % schmaler");
}
#[test]
fn erwartungstreu_ueber_viele_laeufe() {
// Kleines n, viele Wiederholungen: Mittel der Schaetzer muss das Signal treffen.
let (mut s_raw, mut s_cv, reps) = (0.0, 0.0, 400);
for k in 0..reps {
let (y, c) = daten(40, 1000 + k);
s_raw += raw(&y).0;
s_cv += control_variate(&y, &c, 0.0, 5).unwrap().0;
}
let (a, b) = (s_raw / reps as f64, s_cv / reps as f64);
println!("Signal 5.000 roh {:.3} aivat {:.3}", a, b);
assert!((b - 5.0).abs() < 0.15, "Verzerrung: {}", b);
}
#[test]
fn unkorreliert_keine_verzerrung_kein_schaden() {
let mut r = Lcg(7);
let y: Vec<f64> = (0..3000).map(|_| 1.0 + 5.0 * r.normal()).collect();
let c: Vec<f64> = (0..3000).map(|_| r.normal()).collect();
let (m0, h0) = raw(&y);
let (m1, h1) = control_variate(&y, &c, 0.0, 10).unwrap();
println!("unkorreliert roh {:.3}+-{:.3} aivat {:.3}+-{:.3}", m0, h0, m1, h1);
assert!(h1 < 1.05 * h0);
}
}
+221 -180
View File
@@ -1,180 +1,221 @@
//! The benchmark: a fixed set of scenarios, run the same way for every version of the engine, so
//! that two runs can be compared deal by deal (`sim::paired`). The runs in text files; the
//! pure parts are here, the file and clock work in `src/bin/benchmark.rs`.
use super::opponent::Opponent;
use super::paired::{compare, Comparison, Verdict};
use super::reader::Style;
use super::session::{deal_samples, Setup};
use std::thread;
const SEED: u64 = 0x5EED_0001;
const STACK_BB: f64 = 100.0;
const HEADS_UP_DEALS: u32 = 1000;
const SIX_MAX_DEALS: u32 = 150;
pub struct Scenario {
pub name: &'static str,
pub setup: Setup,
}
const fn scenario(name: &'static str, players: u8, opponent: Opponent) -> Scenario {
let deals = if players == 2 { HEADS_UP_DEALS } else { SIX_MAX_DEALS };
Scenario { name, setup: Setup { players, opponent, deals, stack_bb: STACK_BB, seed: SEED } }
}
/// Folder and random opponent are left out: the first is saturated at +75, the second's variance
/// would drown the total. `tests/sim_strength.rs` keeps watching both.
pub const SCENARIOS: [Scenario; 10] = [
scenario("heads-up reg", 2, Opponent::Reader(Style::Reg)),
scenario("heads-up nit", 2, Opponent::Reader(Style::Nit)),
scenario("heads-up maniac", 2, Opponent::Reader(Style::Maniac)),
scenario("heads-up fish", 2, Opponent::Reader(Style::Fish)),
scenario("heads-up calling station", 2, Opponent::CallingStation),
scenario("6-max reg", 6, Opponent::Reader(Style::Reg)),
scenario("6-max nit", 6, Opponent::Reader(Style::Nit)),
scenario("6-max maniac", 6, Opponent::Reader(Style::Maniac)),
scenario("6-max fish", 6, Opponent::Reader(Style::Fish)),
scenario("6-max calling station", 6, Opponent::CallingStation),
];
#[derive(Clone, Debug, PartialEq)]
pub struct ScenarioRun {
pub name: String,
pub deals: u32,
pub seed: u64,
pub decisions: u32,
pub abstains: u32,
/// Requests the guard refused: a simulator bug, must stay 0.
pub invalid: u32,
/// Hero's luck-corrected result per deal, bb.
pub samples: Vec<f64>,
}
impl ScenarioRun {
pub fn bb_per_100(&self) -> f64 {
100.0 * self.samples.iter().sum::<f64>() / self.samples.len().max(1) as f64
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Run {
/// Which version this is.
pub label: String,
pub scenarios: Vec<ScenarioRun>,
}
/// Plays every scenario, one thread each. The result does not depend on the threads.
pub fn run_all(label: &str) -> Run {
let scenarios = thread::scope(|scope| {
let running: Vec<_> = SCENARIOS
.iter()
.map(|s| {
scope.spawn(move || {
let (samples, m) = deal_samples(&s.setup);
ScenarioRun {
name: s.name.to_string(),
deals: s.setup.deals,
seed: s.setup.seed,
decisions: m.decisions,
abstains: m.abstains,
invalid: m.invalid,
samples,
}
})
})
.collect();
running.into_iter().map(|r| r.join().expect("a scenario panicked")).collect()
});
Run { label: label.to_string(), scenarios }
}
pub struct Report {
pub scenarios: Vec<(String, Comparison)>,
pub overall: Comparison,
pub invalid: u32,
}
impl Report {
/// Worse anywhere, even if the total hides it, or a request the guard refused.
pub fn has_regression(&self) -> bool {
self.invalid > 0
|| self.overall.verdict == Verdict::Worse
|| self.scenarios.iter().any(|(_, c)| c.verdict == Verdict::Worse)
}
}
/// The mean of independent scenarios, each counting the same; their variances add.
pub fn overall(comparisons: &[Comparison]) -> Comparison {
let k = comparisons.len().max(1) as f64;
let delta = comparisons.iter().map(|c| c.delta_bb_per_100).sum::<f64>() / k;
let ci95 = comparisons.iter().map(|c| c.ci95.powi(2)).sum::<f64>().sqrt() / k;
let identical = comparisons.iter().all(|c| c.verdict == Verdict::Identical);
Comparison {
delta_bb_per_100: delta,
ci95,
changed_deals: comparisons.iter().map(|c| c.changed_deals).sum(),
verdict: if identical { Verdict::Identical } else { Verdict::of(delta, ci95) },
}
}
/// Compares two runs. Runs under other conditions say nothing about the engine: refused.
pub fn verdict_of_run(base: &Run, new: &Run) -> Result<Report, String> {
if base.scenarios.len() != new.scenarios.len() {
return Err(format!("{} gegen {} Szenarien: Basislinie neu messen", base.scenarios.len(), new.scenarios.len()));
}
let mut scenarios = Vec::with_capacity(base.scenarios.len());
for (b, n) in base.scenarios.iter().zip(&new.scenarios) {
if b.name != n.name || b.deals != n.deals || b.seed != n.seed {
return Err(format!("andere Bedingungen: „{}“ gegen „{}“: Basislinie neu messen", b.name, n.name));
}
scenarios.push((b.name.clone(), compare(&b.samples, &n.samples)?));
}
let all: Vec<Comparison> = scenarios.iter().map(|(_, c)| *c).collect();
Ok(Report { overall: overall(&all), invalid: new.scenarios.iter().map(|s| s.invalid).sum(), scenarios })
}
/// The run as text. Floats are written so that they read back bit for bit.
pub fn render(run: &Run) -> String {
let mut text = format!("label {}\n", run.label);
for s in &run.scenarios {
let samples: Vec<String> = s.samples.iter().map(f64::to_string).collect();
text += &format!(
"scenario {}\ndeals {}\nseed {}\ncounts {} {} {}\nsamples {}\n",
s.name, s.deals, s.seed, s.decisions, s.abstains, s.invalid, samples.join(" ")
);
}
text
}
fn field<'a>(lines: &mut std::str::Lines<'a>, key: &str) -> Result<&'a str, String> {
let line = lines.next().ok_or_else(|| format!("„{key}“ fehlt"))?;
line.strip_prefix(key)
.and_then(|rest| rest.strip_prefix(' '))
.ok_or_else(|| format!("„{key}“ erwartet, „{line}“ gelesen"))
}
fn number<T: std::str::FromStr>(text: &str) -> Result<T, String> {
text.parse().map_err(|_| format!("keine Zahl: „{text}“"))
}
pub fn parse(text: &str) -> Result<Run, String> {
let mut lines = text.lines();
let label = field(&mut lines, "label")?.to_string();
let mut scenarios = Vec::new();
while lines.clone().next().is_some() {
let name = field(&mut lines, "scenario")?.to_string();
let deals: u32 = number(field(&mut lines, "deals")?)?;
let seed: u64 = number(field(&mut lines, "seed")?)?;
let counts = field(&mut lines, "counts")?.split(' ').map(number).collect::<Result<Vec<u32>, _>>()?;
let [decisions, abstains, invalid] = counts[..] else {
return Err(format!("„counts“ von „{name}“ hat {} Werte", counts.len()));
};
let samples = field(&mut lines, "samples")?.split(' ').map(number).collect::<Result<Vec<f64>, _>>()?;
if samples.len() != deals as usize {
return Err(format!("„{name}“: {deals} Austeilungen, {} Werte", samples.len()));
}
scenarios.push(ScenarioRun { name, deals, seed, decisions, abstains, invalid, samples });
}
Ok(Run { label, scenarios })
}
//! The benchmark: a fixed set of scenarios, run the same way for every version of the engine, so
//! that two runs can be compared deal by deal (`sim::paired`). The runs in text files; the
//! pure parts are here, the file and clock work in `src/bin/benchmark.rs`.
use super::opponent::Opponent;
use super::paired::{compare, Comparison, Verdict};
use super::reader::Style;
use super::session::{deal_samples, ReadMode, Setup};
use std::thread;
const SEED: u64 = 0x5EED_0001;
const STACK_BB: f64 = 100.0;
const HEADS_UP_DEALS: u32 = 1000;
const SIX_MAX_DEALS: u32 = 150;
/// The balanced opponents (gto, gto-small) run more deals: their leaks are small and concentrated in
/// a few high-variance river pots, so the paired interval must be narrow enough to prove a defensive
/// fix worth a handful of bb/100 (BEFUND-gto-restleck-river-overcall).
const BALANCED_DEALS: u32 = 3000;
pub struct Scenario {
pub name: &'static str,
pub setup: Setup,
}
const fn with_read(name: &'static str, players: u8, opponent: Opponent, read: ReadMode) -> Scenario {
let deals = if players == 2 { HEADS_UP_DEALS } else { SIX_MAX_DEALS };
Scenario { name, setup: Setup { players, opponent, deals, stack_bb: STACK_BB, seed: SEED, read } }
}
/// Read-given: the engine sees the opponent's converged HUD read (the exploit brain).
const fn scenario(name: &'static str, players: u8, opponent: Opponent) -> Scenario {
with_read(name, players, opponent, ReadMode::Oracle)
}
/// A heads-up balanced opponent (gto family) at the higher `BALANCED_DEALS` count, in any read mode.
const fn balanced(name: &'static str, opponent: Opponent, read: ReadMode) -> Scenario {
Scenario { name, setup: Setup { players: 2, opponent, deals: BALANCED_DEALS, stack_bb: STACK_BB, seed: SEED, read } }
}
/// Blind: the read is withheld, the no-read baseline a memory / probe must improve on. The gap to
/// the matching read-given scenario is the measured session payoff of a read (`tests/sim_blind`).
const fn blind(name: &'static str, players: u8, opponent: Opponent) -> Scenario {
with_read(name, players, opponent, ReadMode::Blind)
}
/// Memory: no handed read; the engine builds one from observed actions over the session
/// (`sim::memory`). Lands between the blind and read-given twins - the share of the prize that
/// observation alone recaptures.
const fn memory(name: &'static str, players: u8, opponent: Opponent) -> Scenario {
with_read(name, players, opponent, ReadMode::Memory)
}
/// Folder and random opponent are left out: the first is saturated at +75, the second's variance
/// would drown the total. `tests/sim_strength.rs` keeps watching both.
///
/// The last four are the two opponents the engine can actually exploit today (the calling station
/// and the fish, the classes `exploit::read_gate` lets through), each blind and memory: blind is the
/// no-read baseline, memory is the read built from observation. The ladder thus tracks both the
/// prize of a read and how much of it the session memory earns back.
pub const SCENARIOS: [Scenario; 19] = [
scenario("heads-up reg", 2, Opponent::Reader(Style::Reg)),
scenario("heads-up nit", 2, Opponent::Reader(Style::Nit)),
scenario("heads-up maniac", 2, Opponent::Reader(Style::Maniac)),
scenario("heads-up fish", 2, Opponent::Reader(Style::Fish)),
scenario("heads-up calling station", 2, Opponent::CallingStation),
balanced("heads-up gto", Opponent::Reader(Style::Gto), ReadMode::Oracle),
balanced("heads-up gto-small", Opponent::Reader(Style::GtoSmall), ReadMode::Oracle),
scenario("6-max reg", 6, Opponent::Reader(Style::Reg)),
scenario("6-max nit", 6, Opponent::Reader(Style::Nit)),
scenario("6-max maniac", 6, Opponent::Reader(Style::Maniac)),
scenario("6-max fish", 6, Opponent::Reader(Style::Fish)),
scenario("6-max calling station", 6, Opponent::CallingStation),
scenario("6-max gto", 6, Opponent::Reader(Style::Gto)),
balanced("heads-up gto (blind)", Opponent::Reader(Style::Gto), ReadMode::Blind),
balanced("heads-up gto-small (blind)", Opponent::Reader(Style::GtoSmall), ReadMode::Blind),
blind("heads-up fish (blind)", 2, Opponent::Reader(Style::Fish)),
blind("heads-up calling station (blind)", 2, Opponent::CallingStation),
memory("heads-up fish (memory)", 2, Opponent::Reader(Style::Fish)),
memory("heads-up calling station (memory)", 2, Opponent::CallingStation),
];
#[derive(Clone, Debug, PartialEq)]
pub struct ScenarioRun {
pub name: String,
pub deals: u32,
pub seed: u64,
pub decisions: u32,
pub abstains: u32,
/// Requests the guard refused: a simulator bug, must stay 0.
pub invalid: u32,
/// Hero's luck-corrected result per deal, bb.
pub samples: Vec<f64>,
}
impl ScenarioRun {
pub fn bb_per_100(&self) -> f64 {
100.0 * self.samples.iter().sum::<f64>() / self.samples.len().max(1) as f64
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Run {
/// Which version this is.
pub label: String,
pub scenarios: Vec<ScenarioRun>,
}
/// Plays every scenario, one thread each. The result does not depend on the threads.
pub fn run_all(label: &str) -> Run {
let scenarios = thread::scope(|scope| {
let running: Vec<_> = SCENARIOS
.iter()
.map(|s| {
scope.spawn(move || {
let (samples, m) = deal_samples(&s.setup);
ScenarioRun {
name: s.name.to_string(),
deals: s.setup.deals,
seed: s.setup.seed,
decisions: m.decisions,
abstains: m.abstains,
invalid: m.invalid,
samples,
}
})
})
.collect();
running.into_iter().map(|r| r.join().expect("a scenario panicked")).collect()
});
Run { label: label.to_string(), scenarios }
}
pub struct Report {
pub scenarios: Vec<(String, Comparison)>,
pub overall: Comparison,
pub invalid: u32,
}
impl Report {
/// Worse anywhere, even if the total hides it, or a request the guard refused.
pub fn has_regression(&self) -> bool {
self.invalid > 0
|| self.overall.verdict == Verdict::Worse
|| self.scenarios.iter().any(|(_, c)| c.verdict == Verdict::Worse)
}
}
/// The mean of independent scenarios, each counting the same; their variances add.
pub fn overall(comparisons: &[Comparison]) -> Comparison {
let k = comparisons.len().max(1) as f64;
let delta = comparisons.iter().map(|c| c.delta_bb_per_100).sum::<f64>() / k;
let ci95 = comparisons.iter().map(|c| c.ci95.powi(2)).sum::<f64>().sqrt() / k;
let identical = comparisons.iter().all(|c| c.verdict == Verdict::Identical);
Comparison {
delta_bb_per_100: delta,
ci95,
changed_deals: comparisons.iter().map(|c| c.changed_deals).sum(),
verdict: if identical { Verdict::Identical } else { Verdict::of(delta, ci95) },
}
}
/// Compares two runs. Runs under other conditions say nothing about the engine: refused.
pub fn verdict_of_run(base: &Run, new: &Run) -> Result<Report, String> {
if base.scenarios.len() != new.scenarios.len() {
return Err(format!("{} gegen {} Szenarien: Basislinie neu messen", base.scenarios.len(), new.scenarios.len()));
}
let mut scenarios = Vec::with_capacity(base.scenarios.len());
for (b, n) in base.scenarios.iter().zip(&new.scenarios) {
if b.name != n.name || b.deals != n.deals || b.seed != n.seed {
return Err(format!("andere Bedingungen: „{}“ gegen „{}“: Basislinie neu messen", b.name, n.name));
}
scenarios.push((b.name.clone(), compare(&b.samples, &n.samples)?));
}
let all: Vec<Comparison> = scenarios.iter().map(|(_, c)| *c).collect();
Ok(Report { overall: overall(&all), invalid: new.scenarios.iter().map(|s| s.invalid).sum(), scenarios })
}
/// The run as text. Floats are written so that they read back bit for bit.
pub fn render(run: &Run) -> String {
let mut text = format!("label {}\n", run.label);
for s in &run.scenarios {
let samples: Vec<String> = s.samples.iter().map(f64::to_string).collect();
text += &format!(
"scenario {}\ndeals {}\nseed {}\ncounts {} {} {}\nsamples {}\n",
s.name, s.deals, s.seed, s.decisions, s.abstains, s.invalid, samples.join(" ")
);
}
text
}
fn field<'a>(lines: &mut std::str::Lines<'a>, key: &str) -> Result<&'a str, String> {
let line = lines.next().ok_or_else(|| format!("„{key}“ fehlt"))?;
line.strip_prefix(key)
.and_then(|rest| rest.strip_prefix(' '))
.ok_or_else(|| format!("„{key}“ erwartet, „{line}“ gelesen"))
}
fn number<T: std::str::FromStr>(text: &str) -> Result<T, String> {
text.parse().map_err(|_| format!("keine Zahl: „{text}“"))
}
pub fn parse(text: &str) -> Result<Run, String> {
let mut lines = text.lines();
let label = field(&mut lines, "label")?.to_string();
let mut scenarios = Vec::new();
while lines.clone().next().is_some() {
let name = field(&mut lines, "scenario")?.to_string();
let deals: u32 = number(field(&mut lines, "deals")?)?;
let seed: u64 = number(field(&mut lines, "seed")?)?;
let counts = field(&mut lines, "counts")?.split(' ').map(number).collect::<Result<Vec<u32>, _>>()?;
let [decisions, abstains, invalid] = counts[..] else {
return Err(format!("„counts“ von „{name}“ hat {} Werte", counts.len()));
};
let samples = field(&mut lines, "samples")?.split(' ').map(number).collect::<Result<Vec<f64>, _>>()?;
if samples.len() != deals as usize {
return Err(format!("„{name}“: {deals} Austeilungen, {} Werte", samples.len()));
}
scenarios.push(ScenarioRun { name, deals, seed, decisions, abstains, invalid, samples });
}
Ok(Run { label, scenarios })
}
+122
View File
@@ -0,0 +1,122 @@
//! Stufe 0 of the synthetic lab: the EXPLOITATION GAP.
//!
//! Draw opponents from a `Population`, play the engine heads-up against each with NO oracle read
//! (`Opponent::Styled` has no authored profile), once blind and once with session memory. In memory
//! mode the engine must INFER the opponent from its observed actions (`sim::memory` →
//! `exploit::posterior`); blind mode is the same engine with nothing to read. The per-deal paired
//! difference `memory - blind`, over the SAME deals (card luck cancels) and pooled over the whole
//! field, is the bb/100 the engine's inference earns against a realistic population.
//!
//! On the fixed-bot ladder this number is structurally hidden: there the engine is handed the
//! converged oracle read (`sim::reads`), so there is nothing to infer and no exploitation to show.
//! Here the oracle is withheld by construction, so the gap is the real exploitation signal.
//!
//! The pooled paired CI reuses `sim::paired::compare`; an anytime CI from `sim::sequential` is
//! reported alongside — the first run of that confidence sequence on real (heavy-tailed) poker
//! samples instead of synthetic Gaussian ones.
use super::paired::compare;
use super::population::Population;
use super::sequential::ConfSeq;
use super::session::{deal_samples, ReadMode, Setup};
use crate::rng::Rng;
use std::collections::BTreeMap;
use std::thread;
const STACK_BB: f64 = 100.0;
const PLAYERS: u8 = 2;
#[derive(Clone, Debug)]
pub struct GapReport {
pub opponents: usize,
pub deals_each: u32,
/// Engine win rate against the field with no read.
pub blind_bb_per_100: f64,
/// Engine win rate against the field inferring from session memory.
pub memory_bb_per_100: f64,
/// memory - blind, pooled over all (opponent, deal) pairs.
pub gap_bb_per_100: f64,
/// Paired 95 % half width of the gap (`sim::paired`).
pub ci95: f64,
/// Anytime 95 % half width of the gap (`sim::sequential`) — valid under peeking; sanity cross-check.
pub anytime_ci95: f64,
/// Per hidden archetype: mean per-opponent gap and how many opponents.
pub by_label: BTreeMap<String, (f64, usize)>,
}
struct One {
label: &'static str,
blind: Vec<f64>,
memory: Vec<f64>,
}
fn run_one(pop: &Population, k: usize, deals: u32, seed: u64) -> One {
let (draw, _) = pop.sample(Rng::seeded(seed ^ (k as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15)));
let hand_seed = seed ^ (k as u64).wrapping_mul(0xD1B5_4A32_D192_ED03);
let blind = Setup {
players: PLAYERS,
opponent: draw.opponent(),
deals,
stack_bb: STACK_BB,
seed: hand_seed,
read: ReadMode::Blind,
};
let memory = Setup { read: ReadMode::Memory, ..blind };
One { label: draw.label, blind: deal_samples(&blind).0, memory: deal_samples(&memory).0 }
}
/// Measure the exploitation gap over `opponents` draws, `deals` deals each. Deterministic in `seed`.
pub fn exploitation_gap(pop: &Population, opponents: usize, deals: u32, seed: u64) -> GapReport {
let results: Vec<One> = thread::scope(|scope| {
let handles: Vec<_> =
(0..opponents).map(|k| scope.spawn(move || run_one(pop, k, deals, seed))).collect();
handles.into_iter().map(|h| h.join().expect("an opponent panicked")).collect()
});
let mut blind_all = Vec::new();
let mut mem_all = Vec::new();
let mut cs = ConfSeq::new(0.05, (opponents as u64 * deals as u64).max(1));
let mut by_label: BTreeMap<String, (f64, usize)> = BTreeMap::new();
for one in &results {
let g = 100.0 * (one.memory.iter().sum::<f64>() - one.blind.iter().sum::<f64>())
/ deals.max(1) as f64;
let e = by_label.entry(one.label.to_string()).or_insert((0.0, 0));
e.0 += g;
e.1 += 1;
for (b, m) in one.blind.iter().zip(&one.memory) {
blind_all.push(*b);
mem_all.push(*m);
cs.push(m - b);
}
}
let cmp = compare(&blind_all, &mem_all).expect("non-empty paired diffs");
let mean = |v: &[f64]| 100.0 * v.iter().sum::<f64>() / v.len().max(1) as f64;
GapReport {
opponents,
deals_each: deals,
blind_bb_per_100: mean(&blind_all),
memory_bb_per_100: mean(&mem_all),
gap_bb_per_100: cmp.delta_bb_per_100,
ci95: cmp.ci95,
anytime_ci95: 100.0 * cs.radius(),
by_label,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn gap_runs_and_is_finite() {
// Tiny: this exercises the full engine decision path, so keep it small for `cargo test`.
let pop = Population::micro();
let r = exploitation_gap(&pop, 4, 25, 0x5EED_0001);
println!(
"blind {:+.1} memory {:+.1} gap {:+.2} +-{:.2} (anytime +-{:.2}) by {:?}",
r.blind_bb_per_100, r.memory_bb_per_100, r.gap_bb_per_100, r.ci95, r.anytime_ci95, r.by_label
);
assert!(r.gap_bb_per_100.is_finite() && r.ci95.is_finite());
assert_eq!(r.by_label.values().map(|(_, n)| n).sum::<usize>(), 4);
}
}
+324
View File
@@ -0,0 +1,324 @@
//! Postflop exploitability of the LIVE engine on a heads-up river subgame.
//!
//! The ladder (`sim::benchmark`) measures bb/100 against fixed card-blind bots; it cannot say how far
//! the engine is from a Nash equilibrium, and against near-GTO bots its signal is cooler-dominated
//! (BEFUND-conditioned-fold-barrel, BEFUND-gto-restleck-river-overcall). MODULES.md names the missing
//! measure outright: "Postflop-Exploitability gegen eine Best Response fehlt noch". This module builds
//! it for the river - the one street where the subgame is exact (board complete, showdown exact, no
//! future chance).
//!
//! # What is measured
//!
//! A heads-up river subgame over real cards: a board, hero's range and villain's range as combo lists.
//! Hands are bucketed by their EXACT showdown strength on the board (`hand::showdown::best`), card
//! removal between the two ranges is baked into the joint deal table, and the betting tree is
//! `cfr::river` (hero first, one bet size, no raises).
//!
//! Hero plays the ENGINE's real policy: at each hero node and bucket the engine is queried
//! (`engine::decide`) for a representative hand of that bucket, giving a pure action per bucket. The
//! villain then BEST-RESPONDS to that fixed policy over the true ranges. Hero's exploitability is
//!
//! ```text
//! exploitability = v* - value(hero | villain best-responds to the engine)
//! ```
//!
//! where `v*` is hero's value at the solved equilibrium of the same subgame. It is `>= 0` and `0`
//! exactly when the engine already plays the river unexploitably. Units: bb per 100 deals (the pot and
//! bet are given in big blinds, `big_blind = 1`).
//!
//! # Approximations (named)
//!
//! - One representative hand per bucket drives the engine query; hands of equal showdown strength but
//! different blockers can in principle play differently, which this collapses.
//! - The betting tree is the `cfr::river` v1 (one bet size, no raises). A richer action abstraction
//! only grows the villain's best-response power, so this is a LOWER bound on exploitability.
//! - The engine models the villain from the spot's profile, not from the tree's true range; that is
//! the point - the best response knows the engine's policy and the true range, the engine plays its
//! own beliefs.
use crate::card::Card;
use crate::cfr::exploitability::game_value;
use crate::cfr::river::tree_with_chance;
use crate::cfr::solve::solve;
use crate::cfr::strategy::Strategy;
use crate::cfr::tree::Tree;
use crate::cfr::value_walk::{root_values, Responder};
use crate::engine::decide::decide;
use crate::engine::river_subgame;
use crate::exploit::profile::Profile;
use crate::game::{ActionKind, Choice, Spot, Street, Villain};
use crate::hand::showdown::best;
use crate::rng::Rng;
use crate::variant::{rules, Variant};
/// A heads-up river subgame over real cards. Pot and bet are in big blinds.
pub struct RiverSpec<'a> {
pub board: &'a [Card],
pub hero_range: &'a [Vec<Card>],
pub villain_range: &'a [Vec<Card>],
/// The profile the engine sees for the villain (its belief); the best response ignores it.
pub villain_profile: Option<Profile>,
pub pot: f64,
pub bet: f64,
}
/// The exploitability of the engine's river play on one subgame, all in bb/100.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ExploitReport {
pub buckets: usize,
/// Hero's value at the solved equilibrium of the subgame.
pub gto_value: f64,
/// Hero's value when the villain best-responds to the engine's fixed policy.
pub engine_value_vs_br: f64,
/// `gto_value - engine_value_vs_br`, `>= 0`.
pub exploitability: f64,
}
/// Strength bucket of each combo on the board, 0 = weakest, plus the shared bucket count. Both ranges
/// share one ascending set of distinct showdown strengths, so a higher bucket always wins the showdown.
struct Buckets {
count: usize,
hero_bucket: Vec<usize>,
villain_bucket: Vec<usize>,
}
fn bucketize(board: &[Card], hero: &[Vec<Card>], villain: &[Vec<Card>]) -> Option<Buckets> {
let usage = rules(Variant::Nlhe).hole_usage;
let strength = |combo: &[Card]| best(usage, combo, board).ok();
let hero_s: Vec<_> = hero.iter().map(|c| strength(c)).collect();
let villain_s: Vec<_> = villain.iter().map(|c| strength(c)).collect();
// One ascending ladder of distinct strengths across both ranges.
let mut distinct: Vec<_> = hero_s.iter().chain(&villain_s).filter_map(|s| *s).collect();
distinct.sort();
distinct.dedup();
if distinct.len() < 2 {
return None;
}
let rank = |s: Option<_>| s.and_then(|v| distinct.iter().position(|d| *d == v));
let hero_bucket: Vec<usize> = hero_s.iter().map(|s| rank(*s).unwrap_or(0)).collect();
let villain_bucket: Vec<usize> = villain_s.iter().map(|s| rank(*s).unwrap_or(0)).collect();
Some(Buckets { count: distinct.len(), hero_bucket, villain_bucket })
}
/// Two hole-card hands can be dealt together only if they share no card.
fn disjoint(a: &[Card], b: &[Card]) -> bool {
a.iter().all(|c| !b.contains(c))
}
/// The joint deal table `chance[i * n + j] = P(hero bucket i, villain bucket j)`: uniform over every
/// disjoint (hero combo, villain combo) pair, so card removal between the two ranges is exact.
fn joint_chance(spec: &RiverSpec, b: &Buckets) -> Vec<f64> {
let n = b.count;
let mut chance = vec![0.0; n * n];
for (hi, hcombo) in spec.hero_range.iter().enumerate() {
for (vi, vcombo) in spec.villain_range.iter().enumerate() {
if disjoint(hcombo, vcombo) {
chance[b.hero_bucket[hi] * n + b.villain_bucket[vi]] += 1.0;
}
}
}
let total: f64 = chance.iter().sum();
if total > 0.0 {
chance.iter_mut().for_each(|x| *x /= total);
}
chance
}
/// First hero combo in each bucket, to drive the engine query. `None` for a bucket hero never holds.
fn hero_reps<'a>(spec: &'a RiverSpec, b: &Buckets) -> Vec<Option<&'a [Card]>> {
let mut reps: Vec<Option<&[Card]>> = vec![None; b.count];
for (i, combo) in spec.hero_range.iter().enumerate() {
let bucket = b.hero_bucket[i];
if reps[bucket].is_none() {
reps[bucket] = Some(combo);
}
}
reps
}
/// Build the river spot the engine faces at a hero node: at the root (`facing_bet = false`) hero is
/// first to act into `pot` with check or a bet to `bet`; facing a bet hero calls `bet` into the pot the
/// villain already grew.
fn hero_spot(spec: &RiverSpec, hand: &[Card], facing_bet: bool) -> Spot {
let (pot, to_call, legal, allowed, min_raise, max_raise) = if facing_bet {
(spec.pot + spec.bet, spec.bet, vec![ActionKind::Fold, ActionKind::Call], None, None, None)
} else {
(
spec.pot,
0.0,
vec![ActionKind::Check, ActionKind::Raise],
Some(vec![spec.bet]),
Some(spec.bet),
Some(spec.bet.max(spec.pot) * 4.0),
)
};
Spot {
variant: Variant::Nlhe,
big_blind: 1.0,
seats: 2,
hero_seat: 1,
button_seat: Some(1),
hero_cards: hand.to_vec(),
board: spec.board.to_vec(),
street: Street::River,
pot,
to_call,
hero_stack: spec.bet.max(spec.pot) * 4.0,
min_raise_to: min_raise,
max_raise_to: max_raise,
legal,
allowed_sizes: allowed,
villains: vec![Villain { seat: 2, stack: spec.pot * 4.0, folded: false, profile: spec.villain_profile }],
seed: 0x5EED_B17E,
history: Vec::new(),
}
}
/// The engine's action row at a hero node for a bucket's representative hand, as a probability per
/// action: `[check, bet]` at node "hero", `[fold, call]` at "hero_vs_bet". Where the river solver
/// applies (`river_subgame::river_mix`) the engine MIXES, so the row is its equilibrium frequency —
/// the whole point of Stage A, and the only way a balanced strategy can show as unexploitable. Where
/// the solver declines, the heuristic (`decide`) gives a pure row. A bucket hero never holds maps to
/// the passive action, which its zero chance makes irrelevant.
fn engine_row(spec: &RiverSpec, reps: &[Option<&[Card]>], name: &str, bucket: usize) -> Vec<f64> {
let facing = match name {
"hero" => false,
"hero_vs_bet" => true,
_ => return vec![1.0, 0.0],
};
let Some(hand) = reps.get(bucket).copied().flatten() else { return vec![1.0, 0.0] };
let spot = hero_spot(spec, hand, facing);
if let Some(plan) = river_subgame::river_mix(&spot) {
if plan.facing == facing {
return vec![plan.mix[0], plan.mix[1]];
}
}
// Solver declined for this node: fall back to the heuristic's pure action.
let aggressive = match facing {
false => matches!(decide(&spot).choice, Choice::Raise { .. }),
true => matches!(decide(&spot).choice, Choice::Call),
};
if aggressive {
vec![0.0, 1.0]
} else {
vec![1.0, 0.0]
}
}
/// Hero's exploitability on the subgame: `v* - value(hero | villain best-responds)`, in bb/100.
/// `iterations` solves the equilibrium reference; `seed` seeds the solver (the engine query is
/// deterministic). Returns `None` for a degenerate subgame (fewer than two buckets, empty ranges).
pub fn exploitability_river(spec: &RiverSpec, iterations: u32, seed: u64) -> Option<ExploitReport> {
let b = bucketize(spec.board, spec.hero_range, spec.villain_range)?;
let chance = joint_chance(spec, &b);
if chance.iter().sum::<f64>() <= 0.0 {
return None;
}
let tree = tree_with_chance(b.count, chance, spec.pot, spec.bet);
let reps = hero_reps(spec, &b);
// The engine's real per-bucket river policy as a (possibly mixed) behaviour strategy at both hero
// nodes; every other node keeps the uniform base (villain nodes are best-responded, not read).
let engine = Strategy::uniform(&tree)
.with_rows(&tree, "hero", |bucket| engine_row(spec, &reps, "hero", bucket))
.and_then(|s| s.with_rows(&tree, "hero_vs_bet", |bucket| engine_row(spec, &reps, "hero_vs_bet", bucket)))
.unwrap_or_else(|_| Strategy::uniform(&tree));
Some(report(&tree, &engine, iterations, seed, b.count))
}
/// Assemble the report from a built tree and a fixed hero strategy (shared by the engine path and the
/// tests). `v*` is the equilibrium value; the villain best-responds to `hero` for the exploited value.
fn report(tree: &Tree, hero: &Strategy, iterations: u32, seed: u64, buckets: usize) -> ExploitReport {
let solved = solve(tree, iterations, Rng::seeded(seed));
let gto_value = game_value(tree, &solved.strategy);
// Player 1 best-responds while player 0 follows `hero`; the summed value is the villain's, so hero
// gets its negation (zero-sum). Counterfactual values are per deal; x100 for bb/100.
let villain_br: f64 = root_values(tree, hero, Responder::Best, 1, &mut |_| {}).iter().sum();
let engine_value_vs_br = -villain_br;
ExploitReport {
buckets,
gto_value: gto_value * 100.0,
engine_value_vs_br: engine_value_vs_br * 100.0,
exploitability: (gto_value - engine_value_vs_br) * 100.0,
}
}
#[cfg(test)]
mod tests {
use super::*;
const ITERS: u32 = 20_000;
const SEED: u64 = 0x5EED_E0F1;
/// A polarised river over abstract buckets built by hand (hero: air + nuts, villain: bluff-catcher)
/// — the same shape `cfr::river` proves against textbook GTO. Feeding the SOLVED strategy as hero's
/// own play must report ~0 exploitability: a Nash strategy is unexploitable, so the harness math
/// (v* + villain best response) cancels. This validates the pipeline independent of the engine.
fn polarised_tree() -> Tree {
// buckets: 0 = air, 1 = bluff-catcher, 2 = nuts. chance = independent product of the ranges.
let hero = [0.5, 0.0, 0.5];
let villain = [0.0, 1.0, 0.0];
let n = 3;
let mut chance = vec![0.0; n * n];
let mut total = 0.0;
for i in 0..n {
for j in 0..n {
let w = hero[i] * villain[j];
chance[i * n + j] = w;
total += w;
}
}
chance.iter_mut().for_each(|x| *x /= total);
tree_with_chance(n, chance, 2.0, 1.0)
}
#[test]
fn a_nash_strategy_reports_zero_exploitability() {
let tree = polarised_tree();
let solved = solve(&tree, ITERS, Rng::seeded(SEED));
let r = report(&tree, &solved.strategy, ITERS, SEED, 3);
assert!(r.exploitability.abs() < 1.5, "GTO must be ~unexploitable, got {:.3} bb/100", r.exploitability);
}
#[test]
fn a_fold_everything_strategy_is_exploitable() {
// Hero folds to every bet and never bets: the villain best-responds by always betting, printing
// the pot with any hand. That is strictly worse than the equilibrium, so exploitability > 0.
let tree = polarised_tree();
let hero = Strategy::pure(&tree, |name, _| match name {
"hero_vs_bet" => 0, // fold
"hero" => 0, // check
_ => 0,
});
let r = report(&tree, &hero, ITERS, SEED, 3);
assert!(r.exploitability > 5.0, "folding everything must be exploitable, got {:.3}", r.exploitability);
assert!(r.exploitability >= -1e-9, "exploitability is non-negative, got {:.3}", r.exploitability);
}
#[test]
fn the_live_engine_runs_and_reports_a_finite_number() {
// A real board, a small two-hand range each: the harness must bucketize real cards, query the
// engine and return a finite, non-negative exploitability. (Correctness of the number is the
// math tests above; this guards the live wiring.)
let board = Card::parse_list("Ah Kd 7c 2s 9h").unwrap();
let hero = [
Card::parse_list("Ac Qc").unwrap(), // top pair
Card::parse_list("5d 4d").unwrap(), // air
];
let villain = [
Card::parse_list("Ad Jc").unwrap(), // top pair worse kicker
Card::parse_list("6h 6d").unwrap(), // underpair / bluff-catcher
];
let spec = RiverSpec {
board: &board,
hero_range: &hero,
villain_range: &villain,
villain_profile: None,
pot: 6.0,
bet: 4.0,
};
let r = exploitability_river(&spec, 4_000, SEED).expect("non-degenerate subgame");
assert!(r.exploitability.is_finite());
assert!(r.exploitability >= -1e-6, "exploitability non-negative, got {:.3}", r.exploitability);
assert!(r.buckets >= 2);
}
}
+380
View File
@@ -0,0 +1,380 @@
//! A near-GTO scripted opponent: the strong measurement target the weak styles cannot be. It plays
//! RANGES, not hand-strength thresholds: every decision first ranks its hand inside its own range
//! (`range_pct`, 0 = best), then plays that rank by balanced frequencies.
//!
//! - Preflop: position charts (open / call / 3-bet value + bluff / 4-bet / jam) on the 169-class
//! percentile; heads-up the button opens ~80 %, the big blind defends ~70 %.
//! - Betting: value from the top of the range, bluffs from the draw / air band at the ratio the bet
//! size asks for (bet 2/3 pot: 0.4 bluff per value, so the caller is indifferent). Medium hands
//! check (showdown value, protected by checking back), the nuts sometimes trap.
//! - Facing a bet: defends the minimum-defence share `pot / (pot + bet)` of its range, no more, no
//! less, narrowed by each earlier street it already paid; raises the very top plus a thin bluff
//! band. Against a big bet it folds more, against a small one it calls more - price decides.
//! - In position it bets thinner than out of position; the preflop aggressor c-bets more than the
//! caller leads; multiway it tightens and stops bluffing.
//!
//! It is not a solver: ranks come from equity against a random hand (draws included), the ranges
//! are fixed charts. But it has no single-street leak a heuristic can farm: it neither over-folds
//! nor over-calls, and its bluffs are as frequent as its value bets allow.
use super::opponent::{Act, View};
use crate::card::{deck, Card};
use crate::game::{ActionRecord, SeenAction, Street};
use crate::hand::showdown::best;
use crate::preflop::holdem_percentile::holdem_percentile;
use crate::rng::Rng;
use crate::variant::HoleUsage;
/// Range hands the own hand is ranked against.
const RANGE_SAMPLES: usize = 36;
/// Runouts per range hand when the board is not complete.
const RUNOUTS: usize = 20;
/// Chance a street's call is carried by the narrower range on the next street.
const STREET_REACH: f64 = 0.62;
/// The betting shape of a balanced opponent: its bet size (pot fraction) and how many bluffs it mixes
/// in per value bet. Several shapes give the ladder independent balanced targets (so a defensive fix
/// must generalise, not overfit one sizing). All shapes stay balanced - the bluff ratio matches the
/// size's minimum-defence indifference - so none has a single-street leak a heuristic can farm.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Shape {
pub bet_size: f64,
pub bluff_per_value: f64,
}
impl Shape {
/// Two-thirds-pot bettor, 0.4 bluffs per value (the original `Gto`). Byte-identical to the
/// constants it replaces, so the existing `heads-up gto` measurement is unchanged.
pub const BALANCED: Shape = Shape { bet_size: 2.0 / 3.0, bluff_per_value: 0.4 };
/// Small-ball half-pot bettor, value-leaning (0.3 bluffs per value): a tighter, more
/// value-weighted river betting range - the hardest case for a hero that over-calls marginal
/// made hands, and an independent balanced target.
pub const SMALL: Shape = Shape { bet_size: 0.5, bluff_per_value: 0.3 };
}
pub struct Ctx<'a> {
pub hole: &'a [Card],
pub board: &'a [Card],
/// Equity against one random hand (the shared `Reading` signal).
pub strength: f64,
/// Whole pot, bets of this street included.
pub pot: f64,
pub own_bet: f64,
pub stack: f64,
/// 0-based seat; 0 is the button.
pub seat: usize,
pub players: usize,
pub live: usize,
/// Acts last among the live players after the flop.
pub in_position: bool,
pub history: &'a [ActionRecord],
pub seed: u64,
/// Bet size and bluff mix of this balanced opponent.
pub shape: Shape,
}
struct Pre {
/// Raises made before this action (blinds are not raises).
level: usize,
last_raiser: Option<u8>,
limpers: usize,
max_bet: f64,
}
fn preflop_facts(history: &[ActionRecord]) -> Pre {
let mut pre = Pre { level: 0, last_raiser: None, limpers: 0, max_bet: 0.0 };
for r in history.iter().filter(|r| r.street == Street::Preflop) {
let amount = r.amount.unwrap_or(0.0);
match r.action {
SeenAction::PostAnte => {}
SeenAction::PostSmallBlind | SeenAction::PostBigBlind => pre.max_bet = pre.max_bet.max(amount),
SeenAction::Call if amount <= 1.0 + 1e-9 => pre.limpers += 1,
_ if amount > pre.max_bet + 1e-9 => {
pre.level += 1;
pre.last_raiser = Some(r.seat);
pre.max_bet = amount;
}
_ => {}
}
}
pre
}
/// Distance behind the button: 0 button, 1 small blind, 2 big blind, then early to late.
fn open_share(ctx: &Ctx) -> f64 {
let n = ctx.players;
let seat = ctx.seat;
if n == 2 {
return if seat == 0 { 0.80 } else { 1.0 };
}
match seat {
0 => 0.45,
1 => 0.40,
2 => 1.0,
s => match n - s {
1 => 0.27,
2 => 0.21,
_ => 0.16,
},
}
}
/// Share of hands called against one open, by seat.
fn call_share(ctx: &Ctx) -> f64 {
let n = ctx.players;
match (n, ctx.seat) {
(2, 1) => 0.70,
(_, 2) => 0.50,
(_, 0) => 0.12,
(_, 1) => 0.05,
(_, s) if n - s == 1 => 0.10,
_ => 0.08,
}
}
fn raise_to(ctx: &Ctx, to: f64) -> Act {
Act::RaiseTo(to.min(ctx.stack + ctx.own_bet))
}
fn preflop(view: View, ctx: &Ctx, pre: &Pre, rng: Rng) -> (Act, Rng) {
let q = holdem_percentile(ctx.hole);
let (u, rng) = rng.unit();
let can_raise = view.min_raise_to.is_some();
let hu = ctx.players == 2;
let act = match pre.level {
0 => {
let share = open_share(ctx);
let free = view.to_call <= 0.0;
if free {
// Big blind with the option: iso-raise the top, else check.
if can_raise && pre.limpers > 0 && q <= 0.14 { raise_to(ctx, 3.5 + pre.limpers as f64) } else { Act::Check }
} else if can_raise && pre.limpers > 0 && q <= share * 0.8 {
raise_to(ctx, 3.5 + pre.limpers as f64)
} else if can_raise && pre.limpers == 0 && q <= share {
raise_to(ctx, if ctx.seat == 1 && !hu { 3.0 } else { 2.5 })
} else if q <= share * 0.5 && view.to_call <= 0.5 + 1e-9 {
Act::Call
} else {
Act::Fold
}
}
1 => {
let x = pre.max_bet;
let scale = (2.5 / x).clamp(0.3, 1.2);
let value = if hu { 0.09 } else { 0.035 };
let (lo, hi, p) = if hu { (0.30, 0.50, 0.30) } else { (0.28, 0.42, 0.28) };
let call = call_share(ctx) * scale;
let three_bet = (if ctx.in_position_preflop() { 3.0 } else { 3.6 }) * x;
if can_raise && q <= value {
raise_to(ctx, three_bet)
} else if can_raise && q >= lo && q <= hi && u < p * scale {
raise_to(ctx, three_bet)
} else if q <= call {
Act::Call
} else {
Act::Fold
}
}
2 => {
let x = pre.max_bet;
let scale = (8.0 / x).clamp(0.3, 1.3);
let (value, call) = if hu { (0.035, 0.20) } else { (0.02, 0.12) };
if can_raise && q <= value {
raise_to(ctx, 2.3 * x)
} else if can_raise && q >= 0.15 && q <= 0.30 && u < 0.12 * scale {
raise_to(ctx, 2.3 * x)
} else if q <= call * scale {
Act::Call
} else {
Act::Fold
}
}
_ => {
if q <= 0.02 {
if can_raise && pre.max_bet < ctx.stack * 0.5 { raise_to(ctx, ctx.stack + ctx.own_bet) } else { Act::Call }
} else {
Act::Fold
}
}
};
(act, rng)
}
impl Ctx<'_> {
/// Preflop, "in position" over the opener: the button, or a seat after the raiser. Coarse.
fn in_position_preflop(&self) -> bool {
self.seat == 0 || (self.players > 2 && self.seat >= 3 && self.seat + 1 == self.players)
}
}
/// How often this seat has already paid a postflop bet.
fn prior_calls(ctx: &Ctx, street: Street) -> i32 {
ctx.history
.iter()
.filter(|r| r.street >= Street::Flop && r.street < street && r.seat as usize == ctx.seat + 1 && r.action == SeenAction::Call)
.count() as i32
}
/// Share of all hands this seat still holds after its own preflop actions (its range).
fn range_share(ctx: &Ctx, pre: &Pre) -> f64 {
let mine = ctx.seat as u8 + 1;
let last = ctx.history.iter().rev().find(|r| r.street == Street::Preflop && r.seat == mine && !matches!(r.action, SeenAction::PostAnte | SeenAction::PostSmallBlind | SeenAction::PostBigBlind));
match last.map(|r| r.action) {
Some(SeenAction::Raise | SeenAction::Bet | SeenAction::AllIn) if pre.last_raiser == Some(mine) => {
if pre.level <= 1 { open_share(ctx).min(0.8) } else { 0.07 }
}
Some(SeenAction::Call) => {
if pre.level <= 1 { call_share(ctx).max(0.10) } else { 0.10 }
}
_ => 0.9,
}
}
fn candidate_equity(cand: &[Card], board: &[Card], rng: Rng) -> (f64, Rng) {
let mut known = cand.to_vec();
known.extend_from_slice(board);
let pool = deck::without(&known);
let missing = 5 - board.len();
let mut rng = rng;
let mut won = 0.0;
for _ in 0..RUNOUTS {
let (cards, next) = deck::draw(&pool, 2 + missing, rng).expect("enough cards");
rng = next;
let mut full = board.to_vec();
full.extend_from_slice(&cards[2..]);
let mine = best(HoleUsage::BestFiveOfAll, cand, &full).expect("valid cards");
let theirs = best(HoleUsage::BestFiveOfAll, &cards[..2], &full).expect("valid cards");
won += match mine.cmp(&theirs) {
std::cmp::Ordering::Greater => 1.0,
std::cmp::Ordering::Equal => 0.5,
std::cmp::Ordering::Less => 0.0,
};
}
(won / RUNOUTS as f64, rng)
}
/// Share of the own range (preflop-chart hands) that beats this hand on the current board:
/// 0 is the nuts, 1 the worst. River: exact showdown ranks; earlier streets: equity against a random
/// hand, which counts draws.
fn range_pct(ctx: &Ctx, share: f64, rng: Rng) -> (f64, Rng) {
let mut known = ctx.hole.to_vec();
known.extend_from_slice(ctx.board);
let pool = deck::without(&known);
let river = ctx.board.len() == 5;
let mine_showdown = river.then(|| best(HoleUsage::BestFiveOfAll, ctx.hole, ctx.board).expect("valid cards"));
let mut rng = rng;
let (mut beaten_by, mut seen) = (0.0, 0usize);
let mut attempts = 0;
while seen < RANGE_SAMPLES && attempts < 600 {
attempts += 1;
let (i, r) = rng.below(pool.len() as u64);
let (mut j, r) = r.below(pool.len() as u64 - 1);
rng = r;
if j >= i {
j += 1;
}
let cand = [pool[i as usize], pool[j as usize]];
if holdem_percentile(&cand) > share {
continue;
}
seen += 1;
beaten_by += match &mine_showdown {
Some(mine) => {
let theirs = best(HoleUsage::BestFiveOfAll, &cand, ctx.board).expect("valid cards");
match theirs.cmp(mine) {
std::cmp::Ordering::Greater => 1.0,
std::cmp::Ordering::Equal => 0.5,
std::cmp::Ordering::Less => 0.0,
}
}
None => {
let (eq, r) = candidate_equity(&cand, ctx.board, rng);
rng = r;
if eq > ctx.strength { 1.0 } else if eq == ctx.strength { 0.5 } else { 0.0 }
}
};
}
((if seen == 0 { 0.5 } else { beaten_by / seen as f64 }), rng)
}
fn postflop(view: View, ctx: &Ctx, pre: &Pre, rng: Rng) -> (Act, Rng) {
let street = match ctx.board.len() {
3 => Street::Flop,
4 => Street::Turn,
_ => Street::River,
};
let river = street == Street::River;
let (p, rng) = range_pct(ctx, range_share(ctx, pre), rng);
let (u, rng) = rng.unit();
let (u2, rng) = rng.unit();
let can_raise = view.min_raise_to.is_some();
let multi = ctx.live > 2;
let bet_to = |frac: f64| raise_to(ctx, ctx.own_bet + view.to_call + frac * (ctx.pot + view.to_call));
let (pool_lo, pool_hi) = if river { (0.72, 1.0) } else { (0.55, 0.92) };
if view.to_call <= 0.0 {
if !can_raise {
return (Act::Check, rng);
}
let aggressor = pre.last_raiser == Some(ctx.seat as u8 + 1);
let mut value = match (aggressor, ctx.in_position) {
(true, false) => 0.28,
(true, true) => 0.33,
(false, true) => 0.30,
(false, false) => 0.16,
};
let mut bluffs = ctx.shape.bluff_per_value * value;
if multi {
value *= 0.6;
bluffs = ctx.shape.bluff_per_value * value * 0.3;
}
let bluff_prob = bluffs / (pool_hi - pool_lo);
let act = if p <= 0.03 && !river && u < 0.25 {
Act::Check
} else if p <= value || (p >= pool_lo && p <= pool_hi && u2 < bluff_prob) {
bet_to(ctx.shape.bet_size)
} else {
Act::Check
};
return (act, rng);
}
// Facing a bet or raise: defend the minimum-defence share of the range.
let before = (ctx.pot - view.to_call).max(1e-9);
let mdf = before / ctx.pot;
let reach = STREET_REACH.powi(prior_calls(ctx, street));
let defend = mdf * reach * if multi { 0.85 } else { 1.0 };
let faced_raise = ctx.own_bet > 0.0;
let raise_value = if faced_raise { 0.03 } else if river { 0.06 } else { 0.05 };
let all_in_price = view.to_call >= ctx.stack - 1e-9;
let act = if can_raise && !all_in_price && p <= raise_value && u < 0.9 {
raise_to(ctx, 3.0 * (ctx.own_bet + view.to_call))
} else if can_raise
&& !all_in_price
&& !faced_raise
&& !multi
&& p > defend
&& p >= (if river { 0.85 } else { 0.55 })
&& p <= (if river { 1.0 } else { 0.92 })
&& u < 0.07
{
raise_to(ctx, 3.0 * (ctx.own_bet + view.to_call))
} else if p <= defend {
Act::Call
} else {
Act::Fold
};
(act, rng)
}
pub fn act(view: View, ctx: &Ctx, rng: Rng) -> (Act, Rng) {
let pre = preflop_facts(ctx.history);
if ctx.board.is_empty() {
preflop(view, ctx, &pre, rng)
} else {
// The ranking has its own stream so that it does not depend on the hand's other randomness.
let (act, _) = postflop(view, ctx, &pre, Rng::seeded(ctx.seed));
let (_, rng) = rng.next_u64();
(act, rng)
}
}
+142
View File
@@ -0,0 +1,142 @@
//! Stufe 3, tier L3 of the synthetic lab: the LEAGUE.
//!
//! A static population measures exploitation; a single adaptive opponent measures one mind-game. The
//! league measures ROBUSTNESS: the hero is scored against a whole POOL at once — static field draws,
//! the L1 reactive opponents (`Adapt::Tighten`/`Loosen`), the L2 modelling opponent (`Adapt::Model`),
//! and the exploiter the Stufe-5 optimizer dug up (the nemesis ruleset). The pool's *worst* member is
//! the floor that matters: a change may lift the league mean, but if it caves against one tier it is
//! not robust (the AlphaStar / Pluribus lesson — evaluate against a population of responses, never a
//! single opponent, so nothing overfits).
//!
//! This is the richer-pool sibling of the twin gate's six-archetype floor (`sim::twin_gate`): same
//! idea (worst-case over a roster), but the roster now spans the adaptive tiers and the known
//! exploiter, not just the static archetypes.
use super::adaptive::{session_samples, Adapt};
use super::population::Population;
use super::reader::{Rules, Style};
use crate::rng::Rng;
use std::thread;
/// 95 % two-sided normal quantile.
const Z95: f64 = 1.959_964;
/// The worst-case individual opponent the Stufe-5 CMA-ES found (`bin/nemesis`): a loose-aggressive
/// small-ball re-raiser the engine bled −643 bb/100 against. Pinned here as a standing league member so
/// every future change is checked against the sharpest known hole.
pub const NEMESIS: Rules = Rules {
call_margin: 0.147,
raise_at: 0.597,
bet_at: 0.616,
open_at: 0.817,
bluff: 0.396,
size: 0.270,
};
#[derive(Clone, Debug)]
pub struct MemberResult {
pub name: String,
pub ev_bb_per_100: f64,
pub ci95: f64,
}
#[derive(Clone, Debug)]
pub struct LeagueReport {
pub members: Vec<MemberResult>,
/// Mean of the members' EVs — the league average.
pub mean_bb_per_100: f64,
pub worst_name: String,
pub worst_bb_per_100: f64,
pub worst_ci95: f64,
}
struct Member {
name: String,
base: Rules,
style: Adapt,
}
fn rate(samples: &[f64]) -> (f64, f64) {
let n = samples.len().max(1) as f64;
let mean = samples.iter().sum::<f64>() / n;
let var = samples.iter().map(|s| (s - mean).powi(2)).sum::<f64>() / (n - 1.0).max(1.0);
(100.0 * mean, 100.0 * Z95 * (var / n).sqrt())
}
/// Assemble the roster: `pop_members` static draws from the field, the three adaptive tiers on a reg
/// base (L1 tighten, L1 loosen, L2 model), and the pinned nemesis.
fn roster(pop: &Population, pop_members: usize, seed: u64) -> Vec<Member> {
let mut members = Vec::new();
let mut rng = Rng::seeded(seed ^ 0x1EA6_0E11);
for k in 0..pop_members {
let (draw, next) = pop.sample(rng);
rng = next;
members.push(Member {
name: format!("pop:{}#{k}", draw.label),
base: draw.rules,
style: Adapt::Static,
});
}
let reg = Style::Reg.rules();
members.push(Member { name: "L1:reg-tighten".into(), base: reg, style: Adapt::Tighten });
members.push(Member { name: "L1:reg-loosen".into(), base: reg, style: Adapt::Loosen });
members.push(Member { name: "L2:reg-model".into(), base: reg, style: Adapt::Model });
members.push(Member { name: "exploiter:nemesis".into(), base: NEMESIS, style: Adapt::Static });
members
}
/// Score the hero across the whole league, `deals` deals per member. Deterministic in `seed`; threaded
/// over members.
pub fn evaluate(pop: &Population, pop_members: usize, deals: u32, seed: u64) -> LeagueReport {
let members = roster(pop, pop_members, seed);
let results: Vec<MemberResult> = thread::scope(|scope| {
let handles: Vec<_> = members
.iter()
.enumerate()
.map(|(i, m)| {
let seed_m = seed ^ (i as u64 + 1).wrapping_mul(0x9E37_79B9_7F4A_7C15);
scope.spawn(move || {
let samples = session_samples(m.base, deals, seed_m, m.style);
let (ev, ci) = rate(&samples);
MemberResult { name: m.name.clone(), ev_bb_per_100: ev, ci95: ci }
})
})
.collect();
handles.into_iter().map(|h| h.join().expect("a league member panicked")).collect()
});
let mean = results.iter().map(|r| r.ev_bb_per_100).sum::<f64>() / results.len().max(1) as f64;
let worst = results
.iter()
.min_by(|a, b| a.ev_bb_per_100.partial_cmp(&b.ev_bb_per_100).unwrap())
.expect("non-empty league");
LeagueReport {
worst_name: worst.name.clone(),
worst_bb_per_100: worst.ev_bb_per_100,
worst_ci95: worst.ci95,
mean_bb_per_100: mean,
members: results,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn league_scores_every_tier_and_finds_a_floor() {
// Tiny budget: drives the full engine per member, keep small for `cargo test`.
let pop = Population::micro();
let r = evaluate(&pop, 3, 25, 0x5EED_0001);
println!("league mean {:+.1}, worst {} {:+.1}", r.mean_bb_per_100, r.worst_name, r.worst_bb_per_100);
for m in &r.members {
println!(" {:20} {:+8.1} ±{:.1}", m.name, m.ev_bb_per_100, m.ci95);
}
// 3 population draws + tighten + loosen + model + nemesis = 7 members.
assert_eq!(r.members.len(), 7);
assert!(r.members.iter().any(|m| m.name == "exploiter:nemesis"));
assert!(r.members.iter().any(|m| m.name == "L2:reg-model"));
assert!(r.mean_bb_per_100.is_finite());
assert!(r.worst_bb_per_100 <= r.mean_bb_per_100 + 1e-9, "worst must not exceed the mean");
}
}

Some files were not shown because too many files have changed in this diff Show More