diff --git a/docs/notizen/BEFUND-river-gearbox-belief-trust.md b/docs/notizen/BEFUND-river-gearbox-belief-trust.md new file mode 100644 index 00000000..ca483008 --- /dev/null +++ b/docs/notizen/BEFUND-river-gearbox-belief-trust.md @@ -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. diff --git a/docs/notizen/BEFUND-size-mix-ev-neutral.md b/docs/notizen/BEFUND-size-mix-ev-neutral.md new file mode 100644 index 00000000..396a497f --- /dev/null +++ b/docs/notizen/BEFUND-size-mix-ev-neutral.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). diff --git a/docs/notizen/BEFUND-stage-b-turn-river-solver.md b/docs/notizen/BEFUND-stage-b-turn-river-solver.md new file mode 100644 index 00000000..21c1d36f --- /dev/null +++ b/docs/notizen/BEFUND-stage-b-turn-river-solver.md @@ -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`, 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. diff --git a/docs/notizen/BEFUND-turnier-pipeline-steht.md b/docs/notizen/BEFUND-turnier-pipeline-steht.md new file mode 100644 index 00000000..b03c1762 --- /dev/null +++ b/docs/notizen/BEFUND-turnier-pipeline-steht.md @@ -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. diff --git a/docs/notizen/BEFUND-turnier-staerke-leiter.md b/docs/notizen/BEFUND-turnier-staerke-leiter.md new file mode 100644 index 00000000..e817a22b --- /dev/null +++ b/docs/notizen/BEFUND-turnier-staerke-leiter.md @@ -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). diff --git a/src/bin/turnier_leiter.rs b/src/bin/turnier_leiter.rs new file mode 100644 index 00000000..9e092d1a --- /dev/null +++ b/src/bin/turnier_leiter.rs @@ -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."); + } +} diff --git a/src/cfr/mod.rs b/src/cfr/mod.rs index 2f173088..736de7c0 100644 --- a/src/cfr/mod.rs +++ b/src/cfr/mod.rs @@ -108,6 +108,7 @@ 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; diff --git a/src/cfr/turn_river.rs b/src/cfr/turn_river.rs new file mode 100644 index 00000000..b3e940fa --- /dev/null +++ b/src/cfr/turn_river.rs @@ -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 { + 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 { + 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, p: f64, leaf_check: Vec, leaf_bet: Vec) -> 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 { + 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, p: f64, leaf_check: Vec, leaf_bet: Vec, 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 { + 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 { + 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 = (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] + ); + } + } +} diff --git a/src/engine/decide.rs b/src/engine/decide.rs index fccd301f..6b356b74 100644 --- a/src/engine/decide.rs +++ b/src/engine/decide.rs @@ -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, raw: &Spot) -> 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, @@ -74,7 +74,27 @@ fn postflop(spot: &Spot, thresholds: &Thresholds, raw: &Spot) -> Decision { // 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); - crate::exploit::mdf_floor::floor(raw, hand_read.made, base).with_equity(equity.share) + 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}")), } @@ -104,7 +124,7 @@ fn think(spot: &Spot, premium: f64, jam_widen: f64, raw: &Spot) -> Decision { let certainty = plan.certainty.max(MIN_CERTAINTY); from_plan(spot, &PreflopPlan { certainty, ..plan }) } - Street::Flop | Street::Turn | Street::River => postflop(spot, &thresholds, raw), + Street::Flop | Street::Turn | Street::River => postflop(spot, &thresholds, raw, premium), } } @@ -130,7 +150,13 @@ 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); + // 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), diff --git a/src/engine/mod.rs b/src/engine/mod.rs index 4d7e2dfe..b7f3d37b 100644 --- a/src/engine/mod.rs +++ b/src/engine/mod.rs @@ -22,4 +22,5 @@ pub mod semibluff; pub mod size_policy; pub mod texture_stance; pub mod thin_value; +pub mod turn_subgame; pub mod uncertainty; diff --git a/src/engine/postflop.rs b/src/engine/postflop.rs index 1e8ba3fe..c10f8156 100644 --- a/src/engine/postflop.rs +++ b/src/engine/postflop.rs @@ -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) -> String { match (choice, kind) { @@ -29,6 +30,79 @@ fn best(options: &[Scored]) -> Option { }) } +/// 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 = OnceLock::new(); + *BAND.get_or_init(|| { + std::env::var("SIZE_MIX_BAND") + .ok() + .and_then(|v| v.parse::().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 = 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 = 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 = 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); + } +} diff --git a/src/engine/river_subgame.rs b/src/engine/river_subgame.rs index 40b514cc..17d9b8ca 100644 --- a/src/engine/river_subgame.rs +++ b/src/engine/river_subgame.rs @@ -40,8 +40,14 @@ //! - 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; @@ -54,6 +60,24 @@ 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 @@ -89,8 +113,10 @@ fn disjoint(a: &[Card], b: &[Card]) -> bool { } /// 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. +/// 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, } @@ -142,7 +168,64 @@ fn subgame(spot: &Spot, hero_combos: &[Vec], villain_combos: &[Vec], } chance.iter_mut().for_each(|x| *x /= total); let tree = tree_with_chance(n, chance, pot, bet); - Some(Subgame { solved: solve(&tree, ITERS, Rng::seeded(spot.seed)), ladder }) + 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) -> 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, 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 @@ -190,6 +273,92 @@ pub fn river_plan(spot: &Spot, villain_combos: &[Vec]) -> Option], profile: Option<&Profile>) -> Option { + 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 { @@ -230,6 +399,33 @@ pub fn river_mix(spot: &Spot) -> Option { 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 { + 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 = 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::*; @@ -279,4 +475,167 @@ mod tests { 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) -> Spot { + Spot { + villains: vec![Villain { seat: 2, stack: pot * 4.0, folded: false, profile }], + ..river_to_act(board, hero, pot) + } + } + + fn sample_villain() -> Vec> { + ["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) -> 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"); + } } diff --git a/src/engine/turn_subgame.rs b/src/engine/turn_subgame.rs new file mode 100644 index 00000000..ff048957 --- /dev/null +++ b/src/engine/turn_subgame.rs @@ -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 = 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 = OnceLock::new(); + *ITERS.get_or_init(|| { + std::env::var("TURN_LEAF_ITERS") + .ok() + .and_then(|v| v.parse::().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 { + 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, +} + +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, usize)], // (combo, turn bucket) + villain: &[(Vec, usize)], + turn_n: usize, + p: f64, + s: f64, +) -> Option<(Vec, Vec)> { + 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, usize)]| -> Vec<(Vec, 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 = 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], villain_combos: &[Vec], p: f64, s: f64) -> Option { + let rules = spot.rules(); + let judged = |combos: &[Vec]| -> Vec<(Vec, 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 = 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, usize)> = hero.iter().map(|(c, st)| (c.clone(), tb(*st))).collect(); + let villain_b: Vec<(Vec, 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]) -> Option { + 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 { + 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 = 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], profile: Option<&Profile>) -> Option { + 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 { + 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 = 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> { + ["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) -> 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) -> 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"); + } +} diff --git a/src/exploit/mark.rs b/src/exploit/mark.rs index 37d183cf..296e19d1 100644 --- a/src/exploit/mark.rs +++ b/src/exploit/mark.rs @@ -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 { @@ -38,6 +41,8 @@ pub fn with_mark(measured: Option, mark: &str) -> Option { 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, mark: &str) -> Option { 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), }) } diff --git a/src/exploit/profile.rs b/src/exploit/profile.rs index c9e8e99c..f009e1f4 100644 --- a/src/exploit/profile.rs +++ b/src/exploit/profile.rs @@ -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, + /// 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, + /// 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, /// How often the player continuation-bets the flop as the preflop aggressor. pub cbet: Option, /// How often the player folds to a continuation bet. @@ -35,4 +44,10 @@ pub struct Profile { pub wtsd: Option, /// Won at showdown: how often the player wins once at showdown. pub wsd: Option, + /// 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, } diff --git a/src/exploit/sample.rs b/src/exploit/sample.rs index 79a6cf93..e0b2bc03 100644 --- a/src/exploit/sample.rs +++ b/src/exploit/sample.rs @@ -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)), } } diff --git a/src/icm/risk.rs b/src/icm/risk.rs index f46d84e7..f23a2538 100644 --- a/src/icm/risk.rs +++ b/src/icm/risk.rs @@ -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)); + } +} diff --git a/src/sim/memory.rs b/src/sim/memory.rs index 8f43368d..72427921 100644 --- a/src/sim/memory.rs +++ b/src/sim/memory.rs @@ -16,6 +16,11 @@ use crate::game::{ActionRecord, SeenAction, Street}; /// blind). Keeps an early, noisy sample from steering worse than no read at all. pub const WARMUP_HANDS: u32 = 25; +/// Postflop actions at which the read's confidence reaches 0.5 (half-life). Matches the Bayesian +/// posterior's `VERTRAUEN_HALB` so the counts HUD and `exploit::posterior` agree on how fast a read +/// earns trust. The river gearbox turns this confidence into the KL trust radius. +pub const CONFIDENCE_HALF: f64 = 30.0; + /// Running tallies over the opponent archetype. Preflop opportunities (`hands`) and the voluntary / /// raise counts drive vpip and pfr; the postflop tallies drive fold-to-bet and aggression. #[derive(Clone, Copy, Debug, Default, PartialEq)] @@ -27,6 +32,13 @@ struct Counts { passive_call: u32, passive_check: u32, aggressive: u32, + // Per-street aggression split (turn and river only — the streets the subgame gearboxes solve). + // `*_passive` is calls plus checks on that street (the aggression denominator, matching the pooled + // one which counts checks); folds are excluded, as in the pooled aggression. + turn_aggressive: u32, + turn_passive: u32, + river_aggressive: u32, + river_passive: u32, } /// The read a HUD accumulates from watching one fixed opponent archetype play a session. @@ -72,9 +84,18 @@ impl SessionMemory { // is, and `bluff_share` reads aggression directly. match r.action { SeenAction::Fold => self.c.folded_to_bet += 1, - SeenAction::Call => self.c.passive_call += 1, - SeenAction::Check => self.c.passive_check += 1, - a if a.is_aggressive() => self.c.aggressive += 1, + SeenAction::Call => { + self.c.passive_call += 1; + self.bump_passive(r.street); + } + SeenAction::Check => { + self.c.passive_check += 1; + self.bump_passive(r.street); + } + a if a.is_aggressive() => { + self.c.aggressive += 1; + self.bump_aggressive(r.street); + } _ => {} } } @@ -83,6 +104,25 @@ impl SessionMemory { self.c.pfr += raised as u32; } + /// A passive postflop action (call or check) on the turn/river, for the per-street aggression + /// denominator. Flop and preflop are not split. + fn bump_passive(&mut self, street: Street) { + match street { + Street::Turn => self.c.turn_passive += 1, + Street::River => self.c.river_passive += 1, + _ => {} + } + } + + /// An aggressive postflop action (bet or raise) on the turn/river, for the per-street numerator. + fn bump_aggressive(&mut self, street: Street) { + match street { + Street::Turn => self.c.turn_aggressive += 1, + Street::River => self.c.river_aggressive += 1, + _ => {} + } + } + /// The read so far, or `None` during the warmup. vpip / pfr are over hands; fold-to-bet is folds /// over folds-plus-calls facing a bet; aggression is bets-and-raises over bets-raises-and-calls. pub fn read(&self) -> Option { @@ -94,11 +134,23 @@ impl SessionMemory { // Aggression frequency: bets and raises over every non-folding postflop action, checks // included (see `observe_seat`). let postflop_actions = self.c.aggressive + self.c.passive_call + self.c.passive_check; + // Confidence for the gearbox: the read is only as trustworthy as its weaker postflop sample — + // the facing-a-bet count (drives fold_to_bet / the defense belief) and the total postflop + // count (drives aggression / the betting-polarization belief). Half at CONFIDENCE_HALF. + let conf = |n: u32| n as f64 / (n as f64 + CONFIDENCE_HALF); + let confidence = conf(facing_bet.min(postflop_actions)); + // Per-street aggression: bets/raises over bets-raises-plus-passive on that street (same shape + // as the pooled frequency). `None` until the street has an action, so `believed_villain` falls + // back to the pooled read. + let street_aggr = |aggr: u32, passive: u32| ratio(aggr, aggr + passive); Some(Profile { vpip: ratio(self.c.vpip, self.c.hands), pfr: ratio(self.c.pfr, self.c.hands), fold_to_bet: ratio(self.c.folded_to_bet, facing_bet), aggression: ratio(self.c.aggressive, postflop_actions), + turn_aggression: street_aggr(self.c.turn_aggressive, self.c.turn_passive), + river_aggression: street_aggr(self.c.river_aggressive, self.c.river_passive), + confidence: Some(confidence), ..Profile::default() }) } @@ -202,6 +254,31 @@ mod tests { assert_eq!(p.aggression, Some(1.0 / 30.0)); // 1 bet, 29 checks } + #[test] + fn per_street_aggression_splits_the_turn_from_the_pooled_read() { + // Seat 2 checks the flop (passive) but bets the turn (aggressive), no river action. The pooled + // aggression is 1 bet / (1 bet + 1 check) = 0.5, but the TURN aggression is 1/1 = 1.0, and the + // river stays None. This is exactly the barreler the pooled read under-sells. + let hand = vec![ + rec(Street::Preflop, 1, SeenAction::PostSmallBlind), + rec(Street::Preflop, 2, SeenAction::PostBigBlind), + rec(Street::Preflop, 1, SeenAction::Raise), + rec(Street::Preflop, 2, SeenAction::Call), + rec(Street::Flop, 1, SeenAction::Check), + rec(Street::Flop, 2, SeenAction::Check), + rec(Street::Turn, 1, SeenAction::Check), + rec(Street::Turn, 2, SeenAction::Bet), + ]; + let mut m = SessionMemory::new(); + for _ in 0..40 { + m.observe_hand(&hand, 0, 2); + } + let p = m.read().expect("read"); + assert_eq!(p.aggression, Some(0.5)); // 1 bet, 1 flop check pooled + assert_eq!(p.turn_aggression, Some(1.0)); // bets every turn, never passive on the turn + assert_eq!(p.river_aggression, None); // no river action seen + } + #[test] fn a_tight_folding_opponent_reads_as_a_nit() { // Seat 2 folds preflop every hand: no voluntary money, and (vpip 0) classifies as a nit. diff --git a/src/sim/mod.rs b/src/sim/mod.rs index 26df2725..182828a0 100644 --- a/src/sim/mod.rs +++ b/src/sim/mod.rs @@ -21,4 +21,5 @@ pub mod sequential; pub mod session; pub mod simreal; pub mod table; +pub mod turnier_leiter; pub mod twin_gate; diff --git a/src/sim/table.rs b/src/sim/table.rs index 5ce6e050..5f65a819 100644 --- a/src/sim/table.rs +++ b/src/sim/table.rs @@ -10,8 +10,9 @@ use super::opponent::{Act, Opponent, View}; use super::gto; use super::reader::{strength, Reading}; use crate::card::{deck, Card}; -use crate::engine::decide::decide; +use crate::engine::decide::decide_with; use crate::exploit::profile::Profile; +use crate::icm::lage::Turnierlage; use crate::game::{ActionKind, ActionRecord, Choice, SeenAction, Spot, Street, Villain}; use crate::guard::validate::check; use crate::hand::showdown::best; @@ -101,8 +102,16 @@ pub struct Dec { struct Table<'a> { setup: &'a HandSetup<'a>, cost: TableCost, + /// The tournament situation the engine is queried under (`decide_with`). `None` = cash + /// (`decide_with(spot, None)` is bit-identical to `decide(spot)`), so the whole cash/exploit + /// ladder is untouched; `Some` routes hero through the ICM line (`icm::risk` premium / jam). + lage: Option<&'a Turnierlage>, hero: usize, stack: Vec, + /// Per-seat starting stacks (big blinds), the baseline for each seat's net. Symmetric + /// (`vec![stack_bb; n]`) on the cash/exploit path; the ICM ladder seats asymmetric stacks + /// (covering vs covered) through `play_hand_seated`. + start: Vec, bet: Vec, total: Vec, folded: Vec, @@ -236,7 +245,7 @@ impl Table<'_> { self.result.hero_decisions += 1; let choice = match check(self.spot(view)) { Ok(spot) => { - let decision = decide(&spot); + let decision = decide_with(&spot, self.lage); if let Some(trace) = self.trace.as_mut() { trace.push(Dec { street: spot.street, @@ -443,13 +452,22 @@ impl Table<'_> { } impl<'a> Table<'a> { - fn new(setup: &'a HandSetup<'a>, cost: TableCost, trace: Option>) -> Table<'a> { + fn new( + setup: &'a HandSetup<'a>, + cost: TableCost, + trace: Option>, + lage: Option<&'a Turnierlage>, + start: Option>, + ) -> Table<'a> { let n = setup.deal.holes.len(); + let start = start.unwrap_or_else(|| vec![setup.stack_bb; n]); Table { setup, cost, + lage, hero: setup.hero_seat as usize - 1, - stack: vec![setup.stack_bb; n], + stack: start.clone(), + start, bet: vec![0.0; n], total: vec![0.0; n], folded: vec![false; n], @@ -484,7 +502,7 @@ impl<'a> Table<'a> { self.round(1 % n); } let (won, rake) = self.showdown(); - let nets: Vec = (0..n).map(|i| self.stack[i] + won[i] - self.setup.stack_bb).collect(); + let nets: Vec = (0..n).map(|i| self.stack[i] + won[i] - self.start[i]).collect(); self.result.hero_net = nets[self.hero]; self.result.rake = rake; self.result.chips_lost = nets.iter().sum::() + rake; @@ -504,7 +522,7 @@ pub fn play_hand_at(setup: &HandSetup, cost: TableCost) -> HandResult { /// Like `play_hand_at`, but when a `memory` is given the finished hand's opponent actions are folded /// into it (Stage 1 session memory). The read for THIS hand is already fixed in `setup.read`. pub fn play_hand_tracked(setup: &HandSetup, cost: TableCost, memory: Option<&mut SessionMemory>) -> HandResult { - let mut t = Table::new(setup, cost, None); + let mut t = Table::new(setup, cost, None, None, None); t.run(); if let Some(m) = memory { m.observe_hand(&t.history, t.hero, t.players()); @@ -512,11 +530,25 @@ pub fn play_hand_tracked(setup: &HandSetup, cost: TableCost, memory: Option<&mut t.result } +/// Plays one hand at the free table with explicit per-seat starting stacks and hero on the line +/// `lage` selects: `Some` queries the engine `decide_with(spot, Some(lage))` (the ICM line — risk +/// premium / open-jam widening), `None` the cash chip-EV line at the SAME stacks (a fair paired +/// control). `start[seat]` is the seat's stack in big blinds; its length must match the deal. +/// `lage.stacks` is the field in the same unit (hero at `lage.hero`, the table opponent next); the +/// chips move only at the table, the `Turnierlage` prices them. The strength ladder +/// (`sim::turnier_leiter`) pairs the two lines on identical deals and stacks and scores the chip +/// outcome back into ICM money. +pub fn play_hand_seated(setup: &HandSetup, start: &[f64], lage: Option<&Turnierlage>) -> HandResult { + let mut t = Table::new(setup, TableCost::FREE, None, lage, Some(start.to_vec())); + t.run(); + t.result +} + /// Diagnostics: plays one hand and returns hero's result together with a `Dec` for every hero /// decision. For localizing where a read helps or hurts (`tests/sim_blind` leak diagnosis); the /// benchmark never uses this path. pub fn play_hand_traced(setup: &HandSetup, cost: TableCost) -> (HandResult, Vec) { - let mut t = Table::new(setup, cost, Some(Vec::new())); + let mut t = Table::new(setup, cost, Some(Vec::new()), None, None); t.run(); (t.result, t.trace.unwrap_or_default()) } @@ -524,7 +556,7 @@ pub fn play_hand_traced(setup: &HandSetup, cost: TableCost) -> (HandResult, Vec< /// Plays one hand and returns hero's result together with the full action history, so a caller can /// update BOTH a hero-side read and an opponent-side model of the hero (`sim::adaptive`, Stufe 3). pub fn play_hand_history(setup: &HandSetup, cost: TableCost) -> (HandResult, Vec) { - let mut t = Table::new(setup, cost, None); + let mut t = Table::new(setup, cost, None, None, None); t.run(); (t.result, t.history) } diff --git a/src/sim/turnier_leiter.rs b/src/sim/turnier_leiter.rs new file mode 100644 index 00000000..5c2a98f6 --- /dev/null +++ b/src/sim/turnier_leiter.rs @@ -0,0 +1,303 @@ +//! Turnier-Stärke-Leiter: gewinnt die ICM-Linie in GELD? +//! +//! Die Cash-Leiter (`sim::session`) beweist das Exploit-Hirn in bb/100. Turniere werden aber nicht +//! um Chips gespielt, sondern um PREISE, und Chips werden nicht-linear in Preis-Equity umgerechnet +//! (`icm`). Eine Linie, die Chips gewinnt, kann an der Bubble Geld verlieren. Also wertet das +//! Turnier-Gegenstück jede Hand in ICM-GELD statt in Chips und vergleicht die ICM-Linie +//! (`decide_with(spot, Some(lage))`) gegen die Cash-Linie (Chip-EV, `decide`) auf DENSELBEN +//! Austeilungen. +//! +//! Ein Szenario ist ein Heads-up-Pot zwischen Hero und einem Gegner, beide auf `stack_bb`, +//! eingebettet in ein Feld fester Fremdstacks (`field`) unter einer Preisstruktur (`payouts`). Die +//! Hand bewegt nur die beiden Tischstacks (Chips bleiben am Free-Table erhalten); das Feld bepreist +//! die Bewegung per Harville. Die Kennzahl ist die GEPAARTE Differenz ICM\$(an) − ICM\$(aus): +//! dieselben Karten und Sitze für beide Linien, also hebt sich das Board-Glück in der Differenz auf +//! und übrig bleibt die Entscheidungs-Kante. +//! +//! 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)`). + +use super::opponent::Opponent; +use super::table::{deal, play_hand_seated, HandRead, HandSetup}; +use crate::icm::harville; +use crate::icm::lage::Turnierlage; +use crate::rng::Rng; +use std::fmt; + +/// 95 % two-sided normal quantile. +const Z95: f64 = 1.959_964; +/// A busted stack is clamped to this before Harville (a zero rate never finishes the race). The +/// ICM value of busting out before the money is ~0, which this reproduces. +const BUST_FLOOR: f64 = 1e-9; + +/// One ICM test situation: a heads-up pot (hero + one opponent) inside a fixed field under a pay +/// structure. Hero and the opponent may sit at DIFFERENT stacks (covering vs covered) — the stacks +/// where ICM bites hardest. +#[derive(Clone, Debug, PartialEq)] +pub struct Szenario { + pub name: &'static str, + /// Prize of place 1, 2, ... (paid places only). The battery uses a pool of 100, so the + /// ICM\$/100 reads as "% of pool per 100 hands". + pub payouts: Vec, + /// Hero's stack at the table, in big blinds. + pub hero_stack: f64, + /// The table opponent's stack, in big blinds (= `hero_stack` for a symmetric spot). + pub opp_stack: f64, + /// Other players' stacks (NOT at the table), in big blinds — the rest of the ICM field. + pub field: Vec, + pub opponent: Opponent, + /// Deals; each is played from both seats (duplicate), so hands = deals × 2 per line. + pub deals: u32, + pub seed: u64, + /// Blind level (informational, passed to the engine's `Turnierlage`). + pub level: u32, +} + +/// Result of running one scenario: the ICM money of each line and the paired edge of ICM over cash. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct TurnierMessung { + pub name: &'static str, + pub hands: u32, + /// ICM money won per 100 hands on the ICM line (pool = 100). + pub icm_on_per100: f64, + /// ... on the cash (chip-EV) line. + pub icm_off_per100: f64, + /// The paired edge of the ICM line: mean(ICM\$on − ICM\$off) per 100 hands. + pub edge_per100: f64, + /// Half width of the 95 % interval on the paired edge. + pub ci95: f64, + pub decisions: u32, + pub abstains: u32, + /// Requests the guard refused on either line: a simulator bug, must stay 0. + pub invalid: u32, +} + +impl TurnierMessung { + /// Lower end of the 95 % interval on the edge. + pub fn lower(&self) -> f64 { + self.edge_per100 - self.ci95 + } + + /// The ICM line is PROVEN to win when the whole interval is above zero. + pub fn wins(&self) -> bool { + self.lower() > 0.0 + } + + /// Proven NOT to lose: the interval does not reach below zero (a correctness anchor, e.g. + /// winner-take-all where ICM must equal cash — edge ~0). + pub fn safe(&self) -> bool { + self.lower() >= -self.ci95 + } +} + +impl fmt::Display for TurnierMessung { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!( + f, + "{:<16} Kante {:+.3} ±{:.3} ICM$/100 (an {:+.3}, aus {:+.3}), {} Hände{}", + self.name, + self.edge_per100, + self.ci95, + self.icm_on_per100, + self.icm_off_per100, + self.hands, + if self.invalid > 0 { format!(" !! {} INVALID", self.invalid) } else { String::new() }, + ) + } +} + +fn mix(seed: u64, n: u64) -> u64 { + Rng::seeded(seed ^ n.wrapping_mul(0xD1B5_4A32_D192_ED03)).next_u64().0 +} + +/// The engine's `Turnierlage` for a scenario: hero at index 0, the table opponent at index 1, +/// then the field. Stacks in the same unit as the table (big blinds). +pub fn lage_of(s: &Szenario) -> Turnierlage { + let mut stacks = vec![s.hero_stack, s.opp_stack]; + stacks.extend_from_slice(&s.field); + Turnierlage { payouts: s.payouts.clone(), stacks, hero: 0, ante: 0.0, level: s.level } +} + +/// Hero's Harville prize equity for a field (busted stacks clamped positive). +fn icm_equity(stacks: &[f64], payouts: &[f64], hero: usize) -> f64 { + let s: Vec = stacks.iter().map(|x| x.max(BUST_FLOOR)).collect(); + harville::equities(&s, payouts)[hero] +} + +/// The ICM money the hand earned hero: his prize equity after the chips moved minus before. +/// Heads-up table: hero (index 0) nets `hero_net`, the table opponent (index 1) the mirror +/// (chips conserved at the free table); the field is untouched. +fn icm_score(lage: &Turnierlage, hero_net: f64) -> f64 { + let before = icm_equity(&lage.stacks, &lage.payouts, lage.hero); + let mut after = lage.stacks.clone(); + after[0] += hero_net; + after[1] -= hero_net; + icm_equity(&after, &lage.payouts, lage.hero) - before +} + +/// Runs one scenario and returns its ICM-money measurement. The ICM line and the cash line see the +/// SAME deals and seats; the per-deal sample is the mean over both seats of ICM\$(on) − ICM\$(off). +pub fn messen(s: &Szenario) -> TurnierMessung { + let lage = lage_of(s); + let mut edge = Vec::with_capacity(s.deals as usize); + let (mut on_tot, mut off_tot) = (0.0, 0.0); + let (mut decisions, mut abstains, mut invalid, mut hands) = (0u32, 0u32, 0u32, 0u32); + for d in 0..s.deals { + let (cards, _) = deal(2, Rng::seeded(mix(s.seed, d as u64))); + let mut e = 0.0; + for hero_seat in 1..=2u8 { + let setup = HandSetup { + deal: &cards, + hero_seat, + opponent: s.opponent, + // Unused on the seated path (explicit `start` below); a sane value for the struct. + stack_bb: s.hero_stack, + seed: mix(s.seed ^ 0xA5A5, (d as u64) << 8 | hero_seat as u64), + // The full read for both lines, so the only thing that differs is the ICM pricing. + read: HandRead::Oracle, + }; + // Seat hero at `hero_stack`, the opponent at `opp_stack`, whichever seat hero drew. + let start = if hero_seat == 1 { [s.hero_stack, s.opp_stack] } else { [s.opp_stack, s.hero_stack] }; + let on = play_hand_seated(&setup, &start, Some(&lage)); + let off = play_hand_seated(&setup, &start, None); + let s_on = icm_score(&lage, on.hero_net); + let s_off = icm_score(&lage, off.hero_net); + e += s_on - s_off; + on_tot += s_on; + off_tot += s_off; + decisions += on.hero_decisions + off.hero_decisions; + abstains += on.abstains + off.abstains; + invalid += on.invalid + off.invalid; + // Per-line paired hands (the denominator of `*_per100`); both lines saw this deal. + hands += 1; + } + edge.push(e / 2.0); + } + let (edge_per100, ci95) = rate(&edge); + let n = f64::from(s.deals.max(1) * 2); + TurnierMessung { + name: s.name, + hands, + icm_on_per100: 100.0 * on_tot / n, + icm_off_per100: 100.0 * off_tot / n, + edge_per100, + ci95, + decisions, + abstains, + invalid, + } +} + +/// Mean and 95 % half width of per-deal samples, both scaled to "per 100 hands". +fn rate(samples: &[f64]) -> (f64, f64) { + let n = samples.len().max(1) as f64; + let mean = samples.iter().sum::() / n; + let var = samples.iter().map(|x| (x - mean).powi(2)).sum::() / (n - 1.0).max(1.0); + (100.0 * mean, 100.0 * Z95 * (var / n).sqrt()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::sim::reader::Style; + + fn bubble(opponent: Opponent, deals: u32) -> Szenario { + Szenario { + name: "bubble", + // 3 paid of 5 left, steep ladder; pool 100. + payouts: vec![50.0, 30.0, 20.0], + // hero + table-opp at 20bb each; two short stacks about to bust. + field: vec![6.0, 4.0, 10.0], + opponent, + hero_stack: 20.0, + opp_stack: 20.0, + deals, + seed: 0x5EED_0001, + level: 7, + } + } + + #[test] + fn harville_conserves_the_pool_and_prices_busts_near_zero() { + let payouts = vec![50.0, 30.0, 20.0]; + let stacks = vec![20.0, 20.0, 6.0, 4.0, 10.0]; + let eq = harville::equities(&stacks, &payouts); + let sum: f64 = eq.iter().sum(); + assert!((sum - 100.0).abs() < 1e-6, "ICM money conserves the prize pool: {sum}"); + // A busted hero is worth ~nothing. + let busted = icm_equity(&[BUST_FLOOR, 30.0, 6.0, 4.0, 10.0], &payouts, 0); + assert!(busted < 0.5, "busting before the money is worth ~0, got {busted}"); + } + + #[test] + fn icm_score_is_zero_for_a_flat_hand_and_signed_with_the_chips() { + let lage = lage_of(&bubble(Opponent::Folder, 1)); + assert!(icm_score(&lage, 0.0).abs() < 1e-12, "no chips moved, no ICM change"); + assert!(icm_score(&lage, 5.0) > 0.0, "winning chips raises ICM equity"); + assert!(icm_score(&lage, -5.0) < 0.0, "losing chips lowers ICM equity"); + // ICM is concave: losing the pot hurts more than winning it helps (risk aversion). + assert!( + icm_score(&lage, 5.0) < -icm_score(&lage, -5.0), + "at the bubble the downside outweighs the upside", + ); + } + + #[test] + fn winner_take_all_is_the_cash_anchor_no_icm_edge() { + // One prize: ICM equity is exactly the chip share, so the ICM line must NOT diverge from + // cash — the edge is ~0 and never a loss. (Scoring still runs the whole pipeline.) + let s = Szenario { + name: "wta", + payouts: vec![100.0], + field: vec![30.0, 30.0], + opponent: Opponent::Reader(Style::Maniac), + hero_stack: 25.0, + opp_stack: 25.0, + deals: 200, + seed: 0x5EED_0007, + level: 3, + }; + let m = messen(&s); + assert_eq!(m.invalid, 0, "no invalid requests"); + assert!(m.edge_per100.abs() <= m.ci95 + 1e-9, "WTA: ICM equals cash within noise: {m}"); + } + + #[test] + fn asymmetric_covered_short_is_well_formed_and_chips_conserve() { + // Hero is the SHORT stack, covered by a big opponent at a hard bubble: the call premium is + // high (busting = out of the money). Chips must still conserve (no invalid, finite edge). + let s = Szenario { + name: "covered", + payouts: vec![50.0, 30.0, 20.0], + hero_stack: 8.0, + opp_stack: 40.0, + field: vec![6.0, 30.0], + opponent: Opponent::Reader(Style::Maniac), + deals: 150, + seed: 0x5EED_00AA, + level: 8, + }; + let m = messen(&s); + assert_eq!(m.invalid, 0, "asymmetric stacks: no invalid requests"); + assert_eq!(m.hands, 300); + assert!(m.edge_per100.is_finite() && m.ci95 > 0.0); + // The ICM line must not LOSE money (its lower bound stays out of a clear loss). + assert!(m.edge_per100 + m.ci95 > 0.0 || m.edge_per100.abs() <= m.ci95, "no clear ICM loss: {m}"); + } + + #[test] + fn deterministic() { + let s = bubble(Opponent::Reader(Style::Maniac), 120); + assert_eq!(messen(&s), messen(&s), "same seed, same measurement"); + } + + #[test] + fn a_bubble_run_is_well_formed() { + let m = messen(&bubble(Opponent::Reader(Style::Maniac), 150)); + assert_eq!(m.invalid, 0); + assert_eq!(m.hands, 300); + assert!(m.ci95 > 0.0 && m.ci95.is_finite()); + assert!(m.edge_per100.is_finite()); + } +} diff --git a/src/wire/decode_villain.rs b/src/wire/decode_villain.rs index b7bf8884..a929b24a 100644 --- a/src/wire/decode_villain.rs +++ b/src/wire/decode_villain.rs @@ -17,6 +17,10 @@ fn profile(villain: &Value, path: &str) -> Result, Fault> { pfr: opt_number_member(object, &at_profile, "pfr")?, fold_to_bet: opt_number_member(object, &at_profile, "foldToBet")?, aggression: opt_number_member(object, &at_profile, "aggression")?, + // Per-street aggression is not on the wire yet (the opponent memory derives it); keep it None + // so the engine falls back to the pooled read until the client delivers it. + turn_aggression: None, + river_aggression: None, // HUD extras (lesen/profil.py DURCHGEREICHT): same client names on the wire. cbet: opt_number_member(object, &at_profile, "cbet")?, fold_to_cbet: opt_number_member(object, &at_profile, "foldToCbet")?, @@ -26,6 +30,8 @@ fn profile(villain: &Value, path: &str) -> Result, Fault> { check_raise: opt_number_member(object, &at_profile, "checkRaise")?, wtsd: opt_number_member(object, &at_profile, "wtsd")?, wsd: opt_number_member(object, &at_profile, "wsd")?, + // Not on the wire: confidence is derived from `hands` by `shrink` below (half-life PRIOR_HANDS). + confidence: None, }; // `hands` (extension, exploit::sample): with it, few hands count little Ok(Some(match opt_number_member(object, &at_profile, "hands")? { diff --git a/tests/sim_blind.rs b/tests/sim_blind.rs index 49571215..83f73a09 100644 --- a/tests/sim_blind.rs +++ b/tests/sim_blind.rs @@ -259,7 +259,10 @@ fn the_ladder_carries_blind_and_memory_scenarios() { let names = |mode: ReadMode| -> Vec<_> { SCENARIOS.iter().filter(move |s| s.setup.read == mode).map(|s| s.name).collect() }; - assert_eq!(names(ReadMode::Blind), ["heads-up fish (blind)", "heads-up calling station (blind)"]); + assert_eq!( + names(ReadMode::Blind), + ["heads-up gto (blind)", "heads-up gto-small (blind)", "heads-up fish (blind)", "heads-up calling station (blind)"] + ); assert_eq!(names(ReadMode::Memory), ["heads-up fish (memory)", "heads-up calling station (memory)"]); - assert_eq!(names(ReadMode::Oracle).len(), 10); + assert_eq!(names(ReadMode::Oracle).len(), 13); }