diff --git a/docs/notizen/PLAN-weltklasse.md b/docs/notizen/PLAN-weltklasse.md index de56e1f9..c0543092 100644 --- a/docs/notizen/PLAN-weltklasse.md +++ b/docs/notizen/PLAN-weltklasse.md @@ -109,7 +109,7 @@ und Stufe L2 −2500 BB sind scharf (`betrieb/bankroll_regel.json`, Merge 91a873 | D1d | Lesen breit: Ausbeutung auch gegen Nit, Maniac, Folder, passive Fische über begrenzte Kanäle (`engine::read_exploit`, Schalter `GEGNER_BREIT`, aus; C-Bet-Druck, Bluff-Veto, River-Bluff-Catch und Dünnwert über `river_br`, Light-3-Bet), jeder Read in einer KL-Vertrauensregion um den Blind-Wert | Messregel 1a: Gewinn gegen den Lese-Typ > 0, LBR-Anstieg ≤ 5 bb/100, Leiter ohne Verlierer | gebaut; Replay echter Züge: Lesen ändert 0,74 % (vorher 0,67 %), mit Gedächtnis-Draht (`profile.reads`) 1,04 %; Diagnose: limitiert NICHT durch Menge oder Schranke, sondern durch fehlende Kanäle (Steal 32 %, 3-Bet mit Spielern dahinter 16 %) und multiway (24 %); Micro-Pool (`GEGNER_POOL`) gebaut, ändert 0 Züge; Leiter- und LBR-Arme eingereiht | | D1e | Neue Lese-Kanäle, wo die Diagnose die Züge findet: (1) Steal gegen die Blinds über foldToSteal (Einzel + Pool), (2) Light-3-Bet mit Spielern dahinter (Opener allein im Topf, Rest noch nicht gehandelt), (3) Flop/Turn gegen Einsatz (Bluff-Catch über Aggression), (4) multiway nur defensiv. Je Kanal in der KL-Region, Pool als Anker bei dünner Stichprobe | Messregel 1a je Kanal; Replay-Anteil + Audit-Wert | läuft (15.11.): Blockade-Tabelle mit bb fertig; (1) Steal `s` gebaut, Replay 1,04 → 1,71 %, Leiter+LBR eingereiht; (2) `m` gebaut, 0 Züge, verworfen; nächster Hebel nach Geld: postflop Check ohne C-Bet-Lage / gegen Einsatz Turn | | D1f | Decke je Gegnertyp: Best Response gegen jeden festen Leiter-Bot (LBR auf S1 mit dem Bot als Gegner, `blueprint::welt_gegner`, `src/bin/decke.rs`), Engine dagegen, Anteil ausgeschöpft; dann größte Lücken (Lücke × Micro-Häufigkeit) schließen, Read-gewichtet. Priorität 1: cbet-folder −31 | Tabelle Engine / Decke / % je Zeile; je Fix Leiter ohne Verlierer, LBR nicht schlechter | läuft (15.11.): cbet-folder-Leck gefunden (Erhöhungskriege ≈ −58 bb/100), Fix `RERAISE_TIEFE` + Read `raise_to_bet`, Pilot (Schwelle) +6,16 ±3,12 kein Verlierer (cbet-folder +19,7); 03:15 auf stetige Bayes-Verengung r^(k−1) umgebaut, Tor eingereiht (Leiter all + micro + pool-nl2, LBR erzwungen + blind); Draht fertig, Zähler bei D2/D3 a3f79fc; S1-Decke fertig: Mittel 46 % ausgeschöpft (HUD 46 %), größte Lücken cbet-folder +320, micro-passiv +305, umgekehrt +293, wert-sizer nur 20 %; micro-passiv-Diagnose: Read wirkt fast nur in der Verteidigung → `ANGRIFF_FOLD` (c118034, Tor eingereiht); r^(k−1)-Tor: Mittel +11,95 ±1,90, aber nemesis-1 −11,40 ±9,05 → r jetzt bedingter Read `reraise_to_raise` (a347c6c), Tor neu eingereiht; 15.11.: RERAISE_BLUFF=erst volles Tor gruen (Leiter +6,72, Micro +6,90, lerner +8,22, LBR nicht signifikant schlechter) → Schalter-Vorschlag; ANGRIFF_FOLD verworfen (nemesis-1 −330, LBR +369) | -| D2 | Priors aus echten Händen eichen (`lesen/eichung.py`), ab 200 Gegnern mit je ≥ 30 Chancen | κ-Intervalle endlich; ersetzt die gesetzten Anker | **15.11. Eichschleife gebaut** (`lesen/pool.py`, Haken nach jedem Lauf, STAND §15): Priors je Stufe und Format getrennt, Vergessen 28 Tage, versioniert, live nur über `befoerdern` nach Vorwärts-CV + Replay + Leiter (inkl. `pool-`) + LBR. **15.11. statistisches Tor (Bootstrap über Gegner, Holm): foldToBet bestanden** (+0,0167 [+0,0071; +0,0267] gegen den Kern-Anker, 118 Micro-Gegner; Eichschleife bestätigt +0,0127), alle anderen Reads offen (STAND §14). Schalter-Vorschlag nur foldToBet-Prior: Replay 3 von 1345 Zügen anders, Leiter/LBR in der Warteschlange, pool-nl2 +1,34 ±1,44 (kein Verlierer). **15.11. PokerIntel (STAND §16):** effektive Stichprobe gemessen (vpip/pfr ≈ 60+ Hände, foldToBet ≈ 8 statt pauschal 20); Neugewichtung hinter `POKERINTEL`, aus bitgleich, Leiter `@hud`/pool-nl2/LBR eingereiht; wtsd/wsd/steal/threeBet tragen nicht. PokerIntel im Gedächtnis (datiert, getrennt). **Vorher: Tor 14.11. nicht bestanden, nur an der Menge** (Zweig `claude/gedaechtnis-voll-1f97d3`): hierarchische Priors schlagen die Anker auf zurückgehaltenen Händen (Micro foldToCbet +0,57, cbet +0,31, 3-Bet +0,034 Log-Loss), κ endlich für 5 Reads; aber erst 118 von 200 Gegnern (vpip), es fehlen ~8400 Micro-Hände. Anker bleiben live. Log rotiert alle ~7 min: Sicherungs-Haken gebaut (`betrieb/sicherung_haken.py`, alle 120 s + Lauf-Ende) und **im Live-Stand** (Owner 14.11.), scharf ab dem nächsten Läuferstart | +| D2 | Priors aus echten Händen eichen (`lesen/eichung.py`), ab 200 Gegnern mit je ≥ 30 Chancen | κ-Intervalle endlich; ersetzt die gesetzten Anker | **15.11. Eichschleife gebaut** (`lesen/pool.py`, Haken nach jedem Lauf, STAND §15): Priors je Stufe und Format getrennt, Vergessen 28 Tage, versioniert, live nur über `befoerdern` nach Vorwärts-CV + Replay + Leiter (inkl. `pool-`) + LBR. **15.11. statistisches Tor (Bootstrap über Gegner, Holm): foldToBet bestanden** (+0,0167 [+0,0071; +0,0267] gegen den Kern-Anker, 118 Micro-Gegner; Eichschleife bestätigt +0,0127), alle anderen Reads offen (STAND §14). Schalter-Vorschlag nur foldToBet-Prior: Replay 3 von 1345 Zügen anders, Leiter/LBR in der Warteschlange, pool-nl2 +1,34 ±1,44 (kein Verlierer). **15.11. abends Tor GEGNER_ZAEHLUNG=1 (+POKERINTEL) gegen Live-Stand a1bc217 eingereiht, Zeile 4 (STAND §17).** **15.11. PokerIntel (STAND §16):** effektive Stichprobe gemessen (vpip/pfr ≈ 60+ Hände, foldToBet ≈ 8 statt pauschal 20); Neugewichtung hinter `POKERINTEL`, aus bitgleich, Leiter `@hud`/pool-nl2/LBR eingereiht; wtsd/wsd/steal/threeBet tragen nicht. PokerIntel im Gedächtnis (datiert, getrennt). **Vorher: Tor 14.11. nicht bestanden, nur an der Menge** (Zweig `claude/gedaechtnis-voll-1f97d3`): hierarchische Priors schlagen die Anker auf zurückgehaltenen Händen (Micro foldToCbet +0,57, cbet +0,31, 3-Bet +0,034 Log-Loss), κ endlich für 5 Reads; aber erst 118 von 200 Gegnern (vpip), es fehlen ~8400 Micro-Hände. Anker bleiben live. Log rotiert alle ~7 min: Sicherungs-Haken gebaut (`betrieb/sicherung_haken.py`, alle 120 s + Lauf-Ende) und **im Live-Stand** (Owner 14.11.), scharf ab dem nächsten Läuferstart | | D3 | Gezeigte Hände verengen die Range-Annahme je Gegner | Vorhersage auf zurückgehaltenen Händen besser (Log-Loss) | **je Linie bestanden 14.11.** (Micro +0,549 [+0,29, +0,81], n = 119 Testhände; Übung +0,110, n = 925); je Spieler noch offen (~160 Showdowns fehlen). Schalter `GEGNER_GEDAECHTNIS` (aus) | | D4 | Entscheidungs-Audit: jede echte River- und Turn-Entscheidung wird nachgerechnet, EV-Verlust je Entscheidung | Bericht je Woche; zeigt das größte Leck in echten Spots | **fertig gebaut** (fa7fce9 + Probe, Zweig `claude/audit-auto-9d812b`): `lesen/audit_lauf.py` rechnet je Lauf alle HU-Turn- (E3-Spiel) und River-Entscheidungen nach, Preflop gegen Jams und Push/Fold ≤ 25 bb, Flop gegen All-in; Bericht je Lauf + Woche, Cockpit `/audit`, Fixture-Vorschläge ab 3 bb. Probe 14.11. (6 Läufe, 2707 Hände): **590,6 bb = 21,8 bb/100** Entscheidungsverlust, davon River 312,5, Turn 230,9, Preflop 47,3. **Im Live-Stand** (Merge b308df8, Owner 14.11.), Haken im Läufer, scharf ab dem nächsten Läuferstart | diff --git a/docs/notizen/STAND-weltklasse.md b/docs/notizen/STAND-weltklasse.md index a55e6fd1..cb6f88dd 100644 --- a/docs/notizen/STAND-weltklasse.md +++ b/docs/notizen/STAND-weltklasse.md @@ -406,3 +406,12 @@ Zweig `claude/gedaechtnis-pokerintel` (Worktree gedaechtnis-voll), nicht im Live | Sim-Lesemodus `@hud` | Der Sitz trägt ein verrauschtes PokerIntel wie live. Die Wahrheit kommt aus einer Vorsession (800 Deals, eigener Seed), jedes Feld wird aus Beta(m·θ, m·(1−θ)) mit dem gemessenen m gezogen. Darüber liegen die eigenen Zählungen, gelesen wie der Draht (`SessionMemory::hud_read`) | 1229ded | | Gedächtnis | Feld `pokerintel` je Gegner: Stand + Zeit + Historie (nur Änderungen, höchstens 12), getrennt von den eigenen Zählungen. Gefüllt nach jedem Pool-Lauf (`pool.py` → `pokerintel.gedaechtnis_fuellen`, Sperre wie zeit_tells, `POKERINTEL_MERKEN=0` schaltet ab). Übergabe bitgleich mit und ohne Feld (Spec `Bitgleich`) | 4801555 | | Eingereiht (P5, nach D2) | `gedaechtnis-pi-{nl2,leiter}-{aus,an}` (Zeilen `@hud`, an-Arm mit FRUEHSTOPP), `gedaechtnis-pi-lbr-{typ,duenn,folder}-{aus,an}`. Auswertung: `python messung_gedaechtnis/auswerten_pokerintel.py` | – | + +## 17. Nachtrag 15.11. abends: Tor GEGNER_ZAEHLUNG=1 (+ POKERINTEL) gegen den vollen Live-Stand (Auftrag Orchestrator, höchste Priorität) + +| Was | Ergebnis | Commit | +|---|---|---| +| Befund | Gezählte Reads gehen live nur mit `GEGNER_ZAEHLUNG=1` an den Kern, und das ist aus. `RERAISE_TIEFE`/`RERAISE_BLUFF` und `TURN_RAISE_NUR=rtb:0.30` laufen live deshalb auf dem Anker 0,30, die Leiter hat sie aber mit echten Reads gemessen | – | +| Stand | Live-Zweig a1bc217 gemergt. In `zaehler.py` bleibt die Zählung von nemesis3-river (raiseToBet + reraiseToRaise), Specs grün. ReadMode::Hud deckt jetzt auch lerner/Diagnose ab (dort wie Memory) | cd68663 | +| Sim-Arm „wie live heute“ | Neu: `LESEN_DRAHT=live` = HUD-Stichprobe wie `hud`, aber **ohne** gezählte raiseToBet/reraiseToRaise, wie live ohne Zählung. Das alte `hud` gab sie mit und maß damit nicht, was live läuft. `hud`/`gezaehlt` bleiben unverändert | – | +| Eingereiht (Zeile 4) | Alle Live-Schalter, Micro-Rake. Leiter 21 Zeilen (inkl. micro-passiv, lerner) × 4, pool-nl2 × 8, LBR typ. Drei Arme: `live`, `gez` (`LESEN_DRAHT=gezaehlt`, LBR mit reads), `pi` (gez + `POKERINTEL=1`, Zeilen `@hud`), gez/pi mit FRÜHSTOPP gegen live. Auswertung `python messung_gedaechtnis/auswerten_zaehlung.py` | – | diff --git a/messung_gedaechtnis/auswerten_zaehlung.py b/messung_gedaechtnis/auswerten_zaehlung.py new file mode 100644 index 00000000..593e77d4 --- /dev/null +++ b/messung_gedaechtnis/auswerten_zaehlung.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python3 +"""Tor GEGNER_ZAEHLUNG=1 (gez) und GEGNER_ZAEHLUNG=1 + POKERINTEL=1 (pi) gegen den Live-Stand (live). + +Gepaart Deal fuer Deal (gleiche Seeds); die pi-Zellen heissen @hud und werden mit gepaart. +Tor: Leiter (21 Zeilen inkl. micro-passiv, lerner) und pool-nl2 ohne Verlierer, LBR typ nicht schlechter. + + python messung_gedaechtnis/auswerten_zaehlung.py [--engine ] +""" +import argparse +import math +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import auswerten as a # noqa: E402 + +HIER = a.HIER + + +def paare(da, db): + """Je Gegner (Mittel, ±95, Deals) B - A; B-Dateien duerfen @hud tragen.""" + if not (os.path.isdir(da) and os.path.isdir(db)): + return {} + na = {n for n in os.listdir(da) if n.endswith(".txt")} + gruppen = {} + for n in sorted(os.listdir(db)): + if not n.endswith(".txt"): + continue + basis = n.replace("@hud", "") + if basis not in na: + continue + x, y = a.zahlen(os.path.join(da, basis)), a.zahlen(os.path.join(db, n)) + if len(x) != len(y) or not x: + continue + gruppen.setdefault(basis.split(".")[0], []).append([q - p for p, q in zip(x, y)]) + out = {} + for g, zellen in gruppen.items(): + teile = [a.mittel(d) for d in zellen] + k = len(teile) + out[g] = (sum(t[0] for t in teile) / k, math.sqrt(sum(t[1] ** 2 for t in teile)) / k, sum(t[2] for t in teile)) + return out + + +def main(argv): + ap = argparse.ArgumentParser() + ap.add_argument("--engine", default=a.ENGINE) + o = ap.parse_args(argv) + fertig = a.erledigt(o.engine) + for arm in ("gez", "pi"): + ok, alles = True, True + print(f"==== {arm} gegen live") + for teil in ("leiter", "nl2"): + ida, idb = f"gedaechtnis-z-{teil}-live", f"gedaechtnis-z-{teil}-{arm}" + alles &= ida in fertig and idb in fertig + if "fruehstopp-VERLIERER" in fertig.get(idb, ""): + ok = False + r = paare(os.path.join(HIER, "arme", f"z-{teil}-live"), os.path.join(HIER, "arme", f"z-{teil}-{arm}")) + print(f" -- {teil} (live {fertig.get(ida, 'offen')}, {arm} {fertig.get(idb, 'offen')})") + ges = [] + for g, (m, ci, n) in sorted(r.items()): + verl = m + ci < 0 + ok &= not verl + ges.append((m, ci)) + print(f" {g:<14} {m:+8.2f} ±{ci:6.2f} n={n:>6}{' VERLIERER' if verl else ''}") + if ges: + m = sum(x[0] for x in ges) / len(ges) + ci = math.sqrt(sum(x[1] ** 2 for x in ges)) / len(ges) + print(f" {'GESAMT':<14} {m:+8.2f} ±{ci:6.2f}") + ida, idb = "gedaechtnis-z-lbr-typ-live", f"gedaechtnis-z-lbr-typ-{arm}" + alles &= ida in fertig and idb in fertig + fa, fb = (os.path.join(HIER, "lbr", f"z-typ-{x}.txt") for x in ("live", arm)) + r = a.lbr_ab(fa, fb) if os.path.exists(fa) and os.path.exists(fb) else None + if r is None: + print(" -- LBR typ: noch keine Haende") + else: + m, ci, n = r + lok = m <= a.LBR_TOL and m - ci <= 0 + ok &= lok + print(f" -- LBR typ (+ = mehr ausbeutbar) {m:+8.2f} ±{ci:6.2f} n={n:>5} {'ok' if lok else 'SCHLECHTER'}") + print(f" URTEIL {arm}: " + ("kein Verlierer" if ok else "VERLIERER/SCHLECHTER") + ("" if alles else " (Zwischenstand)")) + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/src/bin/ab_zelle.rs b/src/bin/ab_zelle.rs index befc1f8a..1418f0df 100644 --- a/src/bin/ab_zelle.rs +++ b/src/bin/ab_zelle.rs @@ -71,10 +71,11 @@ fn apply_arm() { { use rechner::sim::memory::{set_wire_read, WireRead}; set_wire_read(match std::env::var("LESEN_DRAHT").as_deref() { - Ok("hud") => WireRead::Hud, + Ok("hud") | Ok("live") => WireRead::Hud, Ok("gezaehlt") => WireRead::Counted, _ => WireRead::Off, }); + rechner::sim::memory::set_wire_without_counted(std::env::var("LESEN_DRAHT").as_deref() == Ok("live")); } // GEDAECHTNIS_FOLD=a,b: foldToBet as the memory handover decodes it (plan D2), only with LESEN_DRAHT=gezaehlt. rechner::sim::memory::set_fold_prior(std::env::var("GEDAECHTNIS_FOLD").ok().and_then(|v| { diff --git a/src/sim/memory.rs b/src/sim/memory.rs index e1bcd993..f0af9af8 100644 --- a/src/sim/memory.rs +++ b/src/sim/memory.rs @@ -1,776 +1,790 @@ -//! Session memory (Stage 1): the engine builds its read from the opponent's OBSERVED actions over -//! the hands of a session, instead of being handed the converged HUD read (`sim::reads`) or playing -//! blind. A HUD that only counts - per opponent seat, preflop voluntary money and raises, postflop -//! folds-to-a-bet and aggression - turned into a `Profile` once a warmup of hands is seen, so the -//! first hands play blind and the read converges to the truth over the session. -//! -//! The gap blind -> read-given that `benchmarks/baseline.txt` / `tests/sim_blind` measure is exactly -//! what this must recapture: a `... (memory)` scenario lands between the blind and the read-given -//! twin, the share of the prize that observation alone earns. Every opponent seat is the same fixed -//! archetype, so their counts pool into one read. - -use crate::exploit::profile::Profile; -use crate::exploit::sample::shrink_aggression; -use crate::game::{line, ActionRecord, SeenAction, Street}; - -pub use super::welt_memory::{ - strength_band, Cell, Move, Pos, Reveal, SizeBucket, Showdown, Texture, Tank, WorldEvent, WorldHand, - WorldMemory, STRENGTH_BANDS, -}; - -/// Hands to observe before the read is trusted; until then `read` is `None` (the engine plays -/// blind). Keeps an early, noisy sample from steering worse than no read at all. -pub const WARMUP_HANDS: u32 = 25; - -/// Postflop actions at which the read's confidence reaches 0.5 (half-life). Matches the Bayesian -/// posterior's `VERTRAUEN_HALB` so the counts HUD and `exploit::posterior` agree on how fast a read -/// earns trust. The river gearbox turns this confidence into the KL trust radius. -pub const CONFIDENCE_HALF: f64 = 30.0; - -/// Running tallies over the opponent archetype. Preflop opportunities (`hands`) and the voluntary / -/// raise counts drive vpip and pfr; the postflop tallies drive fold-to-bet and aggression. -#[derive(Clone, Copy, Debug, Default, PartialEq)] -struct Counts { - hands: u32, - vpip: u32, - pfr: u32, - folded_to_bet: u32, - passive_call: u32, - passive_check: u32, - aggressive: u32, - // Per-street aggression split (turn and river only — the streets the subgame gearboxes solve). - // `*_passive` is calls plus checks on that street (the aggression denominator, matching the pooled - // one which counts checks); folds are excluded, as in the pooled aggression. - turn_aggressive: u32, - turn_passive: u32, - river_aggressive: u32, - river_passive: u32, - // Facing-a-bet outcomes per street (flop, turn, river): folds and calls, for the per-street - // fold-to-bet read. - street_fold: [u32; 3], - street_call: [u32; 3], - // Line-specific HUD stats (`game::line`): responses facing a c-bet / a 3-bet after opening / - // a bet after own check, and how many of them folded / folded / raised. - cbet_faced: u32, - cbet_folded: u32, - three_bet_faced: u32, - three_bet_folded: u32, - xr_chances: u32, - xr_made: u32, - // Postflop raises facing a bet (Raise, or an all-in over someone else's bet on that street). - raised_vs_bet: u32, - // Postflop actions facing aggression after the seat's own bet/raise on that street, and how many - // of them re-raised (`Profile::reraise_to_raise`). - reraise_seen: u32, - reraise_made: u32, -} - -fn street_index(street: Street) -> Option { - match street { - Street::Flop => Some(0), - Street::Turn => Some(1), - Street::River => Some(2), - Street::Preflop => None, - } -} - -/// Facing-a-bet samples that weigh as much as the pooled read when shrinking a street's fold rate. -pub const STREET_FOLD_PRIOR: f64 = crate::exploit::sample::STREET_PRIOR; - -static STREET_FOLD: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true); - -/// Switch the per-street fold read on or off (A/B arm for the ladder). Default on. -pub fn set_street_fold(on: bool) { - STREET_FOLD.store(on, std::sync::atomic::Ordering::Relaxed); -} - -fn street_fold_on() -> bool { - STREET_FOLD.load(std::sync::atomic::Ordering::Relaxed) -} - -/// Line-specific HUD reads switched into `read()`: bit 1 fold to c-bet, 2 fold to 3-bet, 4 check-raise. -static LINE_READS: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0); - -/// Line reads in `read()` (A/B arm): `READ_CBET | READ_THREE_BET | READ_CHECK_RAISE`. Default none. -pub fn set_line_reads(mask: u8) { - LINE_READS.store(mask, std::sync::atomic::Ordering::Relaxed); -} -pub const READ_CBET: u8 = 1; -pub const READ_THREE_BET: u8 = 2; -pub const READ_CHECK_RAISE: u8 = 4; - -fn line_read_on(bit: u8) -> bool { - LINE_READS.load(std::sync::atomic::Ordering::Relaxed) & bit != 0 -} - -/// Population anchors the line reads shrink toward over `STREET_FOLD_PRIOR` samples (a regular's -/// HUD): fold to 3-bet and check-raise have no pooled read to anchor on. -use crate::exploit::sample::{ - CHECK_RAISE_ANCHOR as CHECK_RAISE_PRIOR, CHECK_RAISE_KAPPA, FOLD_TO_THREE_BET_ANCHOR as FOLD_TO_THREE_BET_PRIOR, -}; - -static RIVER_SHOWDOWN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); - -/// Switch the river showdown read (`Profile::river_bluff_share`, from the world memory's revealed river -/// bets) into `read()` (A/B arm for the ladder). Default off until the ladder proves it. -pub fn set_river_showdown(on: bool) { - RIVER_SHOWDOWN.store(on, std::sync::atomic::Ordering::Relaxed); -} - -fn river_showdown_on() -> bool { - RIVER_SHOWDOWN.load(std::sync::atomic::Ordering::Relaxed) -} - -/// How the session read reaches the engine (A/B arm for the ladder, plan D1b "Zaehlung an den Kern"). -/// `Off` (default): the raw rates with the memory's own confidence, as always. The two wire modes pass -/// the read through exactly the shrink the live wire applies (`wire::decode_villain`: `sample::shrink` -/// over `hands`, `shrink_aggression` over the postflop moves, `shrink_street` per street), so the ladder -/// sees what a live profile would make of the same counts: -/// - `Hud`: the samples live had before 14.11. — `hands` capped at [`HUD_HANDS`] (the client HUD's -/// guessed count, live median 23), aggression at [`HUD_MOVES`] (moves in the log window, median 2), -/// each street at [`HUD_STREET`]; -/// - `Counted`: the true counts (`lesen/zaehler.py` fed into the profile, `lesen/profil.py mit_zaehlung`). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum WireRead { - Off, - Hud, - Counted, -} - -/// Live samples before counted reads (14.11., 1910 villain profiles on 1763 postflop requests). -pub const HUD_HANDS: u32 = 23; -pub const HUD_MOVES: u32 = 2; -pub const HUD_STREET: u32 = 1; - -static WIRE_READ: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0); - -/// Switch the wire mode of `read()` (see [`WireRead`]). Default `Off`. -pub fn set_wire_read(mode: WireRead) { - let v = match mode { - WireRead::Off => 0, - WireRead::Hud => 1, - WireRead::Counted => 2, - }; - WIRE_READ.store(v, std::sync::atomic::Ordering::Relaxed); -} - -fn wire_read() -> WireRead { - match WIRE_READ.load(std::sync::atomic::Ordering::Relaxed) { - 1 => WireRead::Hud, - 2 => WireRead::Counted, - _ => WireRead::Off, - } -} - -/// Memory handover foldToBet (plan D2, gedaechtnis-voll): with `Counted`, the pooled fold-to-bet is the -/// posterior `(k + a) / (n + a + b)` over the true facing-bet counts, exactly as `wire::decode_villain` -/// decodes `profile.reads.foldToBet {n, k, prior: [a, b]}`. Without a delivered prior live decodes the -/// core's anchor at 30 chances (a = 0.45 * 30, b = 0.55 * 30): that is the A arm, the D2 stake prior the -/// B arm. Unset (both 0): the `shrink` path as before (bit-identical). -static FOLD_PRIOR_A: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); -static FOLD_PRIOR_B: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); - -/// Set (`Some((a, b))`, both > 0) or clear the memory-handover foldToBet prior (see above). -pub fn set_fold_prior(prior: Option<(f64, f64)>) { - let (a, b) = prior.filter(|(a, b)| *a > 0.0 && *b > 0.0).unwrap_or((0.0, 0.0)); - FOLD_PRIOR_A.store(a.to_bits(), std::sync::atomic::Ordering::Relaxed); - FOLD_PRIOR_B.store(b.to_bits(), std::sync::atomic::Ordering::Relaxed); -} - -fn fold_prior() -> Option<(f64, f64)> { - let a = f64::from_bits(FOLD_PRIOR_A.load(std::sync::atomic::Ordering::Relaxed)); - let b = f64::from_bits(FOLD_PRIOR_B.load(std::sync::atomic::Ordering::Relaxed)); - (a > 0.0 && b > 0.0).then_some((a, b)) -} - -/// The read a HUD accumulates from watching one fixed opponent archetype play a session. -#[derive(Clone, Debug, Default, PartialEq)] -pub struct SessionMemory { - c: Counts, - /// The richer dimensions (sizing x strength, texture x position cells, showdown reveals, timing), - /// see `sim::welt_memory`. Filled only by `observe_world_hand`; `read()` ignores it, so the classic - /// HUD read (and every existing ladder number) is unchanged by it. - world: WorldMemory, -} - -impl SessionMemory { - pub fn new() -> Self { - Self::default() - } - - /// The world-dimension observations (sizing, texture/position cells, showdowns, timing). - pub fn world(&self) -> &WorldMemory { - &self.world - } - - /// Fold one finished hand's world observations (see `WorldHand`) into the world memory. - /// The raw (chances, hits) per read, for the empirical-Bayes fit of the population priors - /// (`lesen/eichung.py`), named like `lesen/zaehler.py`. - pub fn line_counts(&self) -> Vec<(&'static str, u32, u32)> { - let c = &self.c; - vec![ - ("vpip", c.hands, c.vpip), - ("pfr", c.hands, c.pfr), - ("aggression", c.aggressive + c.passive_call + c.passive_check, c.aggressive), - ("flopFoldToBet", c.street_fold[0] + c.street_call[0], c.street_fold[0]), - ("turnFoldToBet", c.street_fold[1] + c.street_call[1], c.street_fold[1]), - ("riverFoldToBet", c.street_fold[2] + c.street_call[2], c.street_fold[2]), - ("foldToCbet", c.cbet_faced, c.cbet_folded), - ("foldToThreeBet", c.three_bet_faced, c.three_bet_folded), - ("checkRaise", c.xr_chances, c.xr_made), - ] - } - - pub fn observe_world_hand(&mut self, hand: &WorldHand) { - self.world.observe_world_hand(hand); - } - - /// Fold every opponent seat's actions of one finished hand into the counts. `hero` is the - /// 0-based hero seat; every other of the `players` seats is an opponent of the same archetype. - pub fn observe_hand(&mut self, history: &[ActionRecord], hero: usize, players: usize) { - for seat in 1..=players as u8 { - if seat as usize - 1 != hero { - self.observe_seat(history, seat); - } - } - } - - /// The line-specific responses of `seat`: each of its actions judged against the line before it. - fn observe_lines(&mut self, history: &[ActionRecord], seat: u8) { - for (k, r) in history.iter().enumerate().filter(|(_, r)| r.seat == seat) { - let before = &history[..k]; - let folded = r.action == SeenAction::Fold; - if r.street == Street::Flop && line::facing_cbet(before, seat) { - self.c.cbet_faced += 1; - self.c.cbet_folded += folded as u32; - } - if r.street == Street::Preflop && line::facing_three_bet(before, seat) { - self.c.three_bet_faced += 1; - self.c.three_bet_folded += folded as u32; - } - if r.street != Street::Preflop && line::check_raise_chance(before, seat, r.street) { - self.c.xr_chances += 1; - self.c.xr_made += r.action.is_aggressive() as u32; - } - } - } - - /// One seat's actions of a finished hand (a per-opponent memory at a mixed table, `sim::sechsmax`). - pub fn observe_seat(&mut self, history: &[ActionRecord], seat: u8) { - self.observe_lines(history, seat); - self.c.hands += 1; - let (mut voluntary, mut raised) = (false, false); - for (i, r) in history.iter().enumerate().filter(|(_, r)| r.seat == seat) { - if r.street == Street::Preflop { - // Blinds are forced (PostSmallBlind / PostBigBlind); a check is free. Only a call or - // an aggressive action puts money in by choice. - match r.action { - SeenAction::Call | SeenAction::Bet | SeenAction::Raise | SeenAction::AllIn => { - voluntary = true; - } - _ => {} - } - raised |= r.action.is_aggressive(); - } else { - // Postflop a fold or a call only happens facing a bet; a check faces nothing. The - // check still counts as a passive action for aggression (matching how the oracle - // reads are measured, `tests/sim_opponent_stats`): leaving checks out of the - // denominator makes a passive, check-heavy opponent look far more aggressive than it - // is, and `bluff_share` reads aggression directly. - // Facing aggression after an own bet/raise on this street: the re-raise spot. - let own = history[..i].iter().rposition(|b| b.street == r.street && b.seat == seat && b.action.is_aggressive()); - if let Some(j) = own { - if matches!(r.action, SeenAction::Fold | SeenAction::Call) || r.action.is_aggressive() { - if history[j + 1..i].iter().any(|b| b.street == r.street && b.seat != seat && b.action.is_aggressive()) { - self.c.reraise_seen += 1; - self.c.reraise_made += r.action.is_aggressive() as u32; - } - } - } - match r.action { - SeenAction::Fold => { - self.c.folded_to_bet += 1; - if let Some(i) = street_index(r.street) { - self.c.street_fold[i] += 1; - } - } - SeenAction::Call => { - if let Some(i) = street_index(r.street) { - self.c.street_call[i] += 1; - } - self.c.passive_call += 1; - self.bump_passive(r.street); - } - SeenAction::Check => { - self.c.passive_check += 1; - self.bump_passive(r.street); - } - a if a.is_aggressive() => { - self.c.aggressive += 1; - self.bump_aggressive(r.street); - let facing = a == SeenAction::Raise - || history[..i].iter().any(|b| b.street == r.street && b.seat != seat && b.action.is_aggressive()); - self.c.raised_vs_bet += facing as u32; - } - _ => {} - } - } - } - self.c.vpip += voluntary as u32; - self.c.pfr += raised as u32; - } - - /// A passive postflop action (call or check) on the turn/river, for the per-street aggression - /// denominator. Flop and preflop are not split. - fn bump_passive(&mut self, street: Street) { - match street { - Street::Turn => self.c.turn_passive += 1, - Street::River => self.c.river_passive += 1, - _ => {} - } - } - - /// An aggressive postflop action (bet or raise) on the turn/river, for the per-street numerator. - fn bump_aggressive(&mut self, street: Street) { - match street { - Street::Turn => self.c.turn_aggressive += 1, - Street::River => self.c.river_aggressive += 1, - _ => {} - } - } - - /// The read so far, or `None` during the warmup. vpip / pfr are over hands; fold-to-bet is folds - /// over folds-plus-calls facing a bet; aggression is bets-and-raises over bets-raises-and-calls. - pub fn read(&self) -> Option { - if self.c.hands < WARMUP_HANDS { - return None; - } - let ratio = |num: u32, den: u32| (den > 0).then(|| num as f64 / den as f64); - let facing_bet = self.c.folded_to_bet + self.c.passive_call; - // Aggression frequency: bets and raises over every non-folding postflop action, checks - // included (see `observe_seat`). - let postflop_actions = self.c.aggressive + self.c.passive_call + self.c.passive_check; - // Confidence for the gearbox: the read is only as trustworthy as its weaker postflop sample — - // the facing-a-bet count (drives fold_to_bet / the defense belief) and the total postflop - // count (drives aggression / the betting-polarization belief). Half at CONFIDENCE_HALF. - let conf = |n: u32| n as f64 / (n as f64 + CONFIDENCE_HALF); - let confidence = conf(facing_bet.min(postflop_actions)); - // Per-street aggression: bets/raises over bets-raises-plus-passive on that street (same shape - // as the pooled frequency). `None` until the street has an action, so `believed_villain` falls - // back to the pooled read. - let street_aggr = |aggr: u32, passive: u32| ratio(aggr, aggr + passive); - let pooled_fold = ratio(self.c.folded_to_bet, facing_bet); - let mut street_fold_to_bet = [None; 3]; - if let (true, Some(pooled)) = (street_fold_on(), pooled_fold) { - for i in 0..3 { - let n = (self.c.street_fold[i] + self.c.street_call[i]) as f64; - if n > 0.0 { - street_fold_to_bet[i] = - Some((self.c.street_fold[i] as f64 + STREET_FOLD_PRIOR * pooled) / (n + STREET_FOLD_PRIOR)); - } - } - } - let river_bluff = self.world.river_bluff().filter(|_| river_showdown_on()); - // Line reads, shrunk like the street reads: c-bet folds toward the flop fold read (else the - // pooled one), the others toward a regular's number. - let shrunk = |num: u32, den: u32, anchor: Option| { - anchor.filter(|_| den > 0).map(|a| (num as f64 + STREET_FOLD_PRIOR * a) / (den as f64 + STREET_FOLD_PRIOR)) - }; - let flop_anchor = street_fold_to_bet[0].or(pooled_fold); - let fold_to_cbet = shrunk(self.c.cbet_folded, self.c.cbet_faced, flop_anchor).filter(|_| line_read_on(READ_CBET)); - let fold_to_three_bet = shrunk(self.c.three_bet_folded, self.c.three_bet_faced, Some(FOLD_TO_THREE_BET_PRIOR)) - .filter(|_| line_read_on(READ_THREE_BET)); - let check_raise = (self.c.xr_chances > 0) - .then(|| (self.c.xr_made as f64 + CHECK_RAISE_KAPPA * CHECK_RAISE_PRIOR) / (self.c.xr_chances as f64 + CHECK_RAISE_KAPPA)) - .filter(|_| line_read_on(READ_CHECK_RAISE)); - let raw = Profile { - street_fold_to_bet, - fold_to_cbet, - fold_to_three_bet, - check_raise, - river_bluff_share: river_bluff.map(|(s, _)| s), - river_bluff_shown: river_bluff.map(|(_, n)| n as f64), - flop_aggression: None, - fold_to_steal: None, - fold_to_raise: None, - // Shrunk toward 0.30 (the middle of the `RERAISE_TIEFE` gate) with 10 pseudo-samples. - raise_to_bet: Some((self.c.raised_vs_bet as f64 + 10.0 * 0.30) / ((facing_bet + self.c.raised_vs_bet) as f64 + 10.0)), - // Same shrinkage, conditional on having bet/raised the street before facing the raise. - size_gain: size_gain(self.world.size_strength_corr(), self.world.size_pairs()), - reraise_to_raise: Some((self.c.reraise_made as f64 + 10.0 * 0.30) / (self.c.reraise_seen as f64 + 10.0)), - 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() - }; - Some(match wire_read() { - WireRead::Off => raw, - mode => self.as_wire(raw, mode, postflop_actions), - }) - } - - /// `raw` as the live wire would decode it from these counts (`wire::decode_villain`), with the - /// samples of `mode` (see [`WireRead`]). - fn as_wire(&self, raw: Profile, mode: WireRead, postflop_actions: u32) -> Profile { - use crate::exploit::sample::{shrink, shrink_aggression, shrink_street}; - let cap = |n: u32, c: u32| (if mode == WireRead::Hud { n.min(c) } else { n }) as f64; - let base = Profile { - turn_aggression: None, - river_aggression: None, - street_fold_to_bet: [None; 3], - confidence: None, - ..raw - }; - let pooled = shrink(&base, cap(self.c.hands, HUD_HANDS)); - let mut pooled = shrink_aggression(pooled, raw.aggression, cap(postflop_actions, HUD_MOVES)); - if let (WireRead::Counted, Some((a, b))) = (mode, fold_prior()) { - let n = (self.c.folded_to_bet + self.c.passive_call) as f64; - if n > 0.0 { - pooled.fold_to_bet = Some(((self.c.folded_to_bet as f64 + a) / (n + a + b)).clamp(0.0, 1.0)); - } - } - let rate = |k: u32, n: u32| (n > 0).then(|| k as f64 / n as f64); - let street = |k: u32, n: u32, anchor: Option| shrink_street(rate(k, n), cap(n, HUD_STREET), anchor); - let (ta, tn) = (self.c.turn_aggressive, self.c.turn_aggressive + self.c.turn_passive); - let (ra, rn) = (self.c.river_aggressive, self.c.river_aggressive + self.c.river_passive); - let mut street_fold_to_bet = [None; 3]; - if street_fold_on() { - for (i, slot) in street_fold_to_bet.iter_mut().enumerate() { - let n = self.c.street_fold[i] + self.c.street_call[i]; - *slot = street(self.c.street_fold[i], n, pooled.fold_to_bet); - } - } - Profile { - turn_aggression: street(ta, tn, pooled.aggression), - river_aggression: street(ra, rn, pooled.aggression), - street_fold_to_bet, - ..pooled - } - } -} - -/// Size-strength correlation that counts as the population's tell (gain 1 on `size_notch`). -const SIZE_CORR_POP: f64 = 0.4; -/// Pseudo-pairs of the gain prior (gain 1). -const SIZE_GAIN_PRIOR: f64 = 20.0; - -/// `Profile::size_gain` from the shown (size, strength) correlation over `n` pairs: corr / 0.4, -/// shrunk toward 1 with 20 pseudo-pairs, clamped to [-2, 2.5]; 1 without pairs. -pub fn size_gain(corr: Option, n: u32) -> Option { - let raw = corr.filter(|c| c.is_finite()).map_or(1.0, |c| c / SIZE_CORR_POP); - let n = n as f64; - Some(((n * raw + SIZE_GAIN_PRIOR) / (n + SIZE_GAIN_PRIOR)).clamp(-2.0, 2.5)) -} - -impl SessionMemory { - /// The raw rates counted so far (no warmup, no shrinking): the "truth" a long pre-session measures, - /// from which the HUD mode draws its noisy PokerIntel numbers (`sim::hud`). - pub fn raw_profile(&self) -> Profile { - let ratio = |num: u32, den: u32| (den > 0).then(|| num as f64 / den as f64); - Profile { - vpip: ratio(self.c.vpip, self.c.hands), - pfr: ratio(self.c.pfr, self.c.hands), - fold_to_bet: ratio(self.c.folded_to_bet, self.c.folded_to_bet + self.c.passive_call), - aggression: ratio(self.c.aggressive, self.c.aggressive + self.c.passive_call + self.c.passive_check), - fold_to_cbet: ratio(self.c.cbet_folded, self.c.cbet_faced), - fold_to_three_bet: ratio(self.c.three_bet_folded, self.c.three_bet_faced), - check_raise: ratio(self.c.xr_made, self.c.xr_chances), - ..Profile::default() - } - } - - /// The read a live table gives (`wire::decode_villain`): the client HUD `hud` (raw PokerIntel - /// numbers) believed over `GLAUBHAFT` + the hands seen so far (`sample::hud_profile`), the - /// aggression on its own counted moves, the street reads counted here toward the HUD-pooled ones. - pub fn hud_read(&self, hud: &Profile) -> Option { - let hands = crate::exploit::sample::GLAUBHAFT + self.c.hands as f64; - let base = crate::exploit::sample::hud_profile(hud, hands); - let ratio = |num: u32, den: u32| (den > 0).then(|| num as f64 / den as f64); - let actions = self.c.aggressive + self.c.passive_call + self.c.passive_check; - let p = if actions > 0 { - shrink_aggression(base, ratio(self.c.aggressive, actions), actions as f64) - } else { - base - }; - let street = |aggr: u32, passive: u32, anchor: Option| { - crate::exploit::sample::shrink_street(ratio(aggr, aggr + passive), (aggr + passive) as f64, anchor) - }; - let mut street_fold_to_bet = [None; 3]; - if street_fold_on() { - for (i, s) in street_fold_to_bet.iter_mut().enumerate() { - *s = street(self.c.street_fold[i], self.c.street_call[i], p.fold_to_bet); - } - } - let river_bluff = self.world.river_bluff().filter(|_| river_showdown_on()); - Some(Profile { - turn_aggression: street(self.c.turn_aggressive, self.c.turn_passive, p.aggression).or(p.turn_aggression), - river_aggression: street(self.c.river_aggressive, self.c.river_passive, p.aggression).or(p.river_aggression), - street_fold_to_bet, - river_bluff_share: river_bluff.map(|(s, _)| s), - river_bluff_shown: river_bluff.map(|(_, n)| n as f64), - // The counted line reads (`RERAISE_TIEFE`/`RERAISE_BLUFF`), as `read` gives them. - raise_to_bet: Some((self.c.raised_vs_bet as f64 + 10.0 * 0.30) / ((self.c.folded_to_bet + self.c.passive_call + self.c.raised_vs_bet) as f64 + 10.0)), - reraise_to_raise: Some((self.c.reraise_made as f64 + 10.0 * 0.30) / (self.c.reraise_seen as f64 + 10.0)), - size_gain: size_gain(self.world.size_strength_corr(), self.world.size_pairs()), - ..p - }) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::exploit::style::{classify, Style}; - - fn rec(street: Street, seat: u8, action: SeenAction) -> ActionRecord { - ActionRecord { street, seat, action, amount: None } - } - - /// The line reads count only the responses to their own line, shrink toward their anchors, and - /// stay out of the read until switched on (so the ladder stays bit-identical by default). - #[test] - fn line_reads_count_their_own_spots() { - use SeenAction::*; - let mut m = SessionMemory::new(); - // Hero (seat 1) opens and c-bets, the opponent (seat 2) folds the flop: a c-bet fold. - let cbet_fold = [ - rec(Street::Preflop, 1, PostSmallBlind), rec(Street::Preflop, 2, PostBigBlind), - rec(Street::Preflop, 1, Raise), rec(Street::Preflop, 2, Call), - rec(Street::Flop, 2, Check), rec(Street::Flop, 1, Bet), rec(Street::Flop, 2, Fold), - ]; - // The opponent opens, hero 3-bets, the opponent folds. - let three_fold = [ - rec(Street::Preflop, 2, PostSmallBlind), rec(Street::Preflop, 1, PostBigBlind), - rec(Street::Preflop, 2, Raise), rec(Street::Preflop, 1, Raise), rec(Street::Preflop, 2, Fold), - ]; - for _ in 0..30 { - m.observe_hand(&cbet_fold, 0, 2); - m.observe_hand(&three_fold, 0, 2); - } - assert_eq!((m.c.cbet_faced, m.c.cbet_folded), (30, 30)); - assert_eq!((m.c.three_bet_faced, m.c.three_bet_folded), (30, 30)); - assert_eq!((m.c.xr_chances, m.c.xr_made), (30, 0), "checked, faced the bet, folded: no check-raise"); - let off = m.read().expect("read"); - assert_eq!((off.fold_to_cbet, off.fold_to_three_bet, off.check_raise), (None, None, None)); - set_line_reads(READ_CBET | READ_THREE_BET | READ_CHECK_RAISE); - let on = m.read().expect("read"); - set_line_reads(0); - assert!(on.fold_to_cbet.unwrap() > 0.9); - assert!((on.fold_to_three_bet.unwrap() - (30.0 + 15.0 * 0.55) / 45.0).abs() < 1e-12); - assert!((on.check_raise.unwrap() - 15.0 * 0.08 / 45.0).abs() < 1e-12); - } - - /// The conditional re-raise read counts only answers to a raise after an own bet/raise on the street: - /// the opponent bets, hero raises, the opponent re-raises (hit) or calls (miss); a call of hero's - /// first bet is not that spot. - #[test] - fn reraise_read_counts_raises_after_own_aggression() { - use SeenAction::*; - let pre = [rec(Street::Preflop, 1, PostSmallBlind), rec(Street::Preflop, 2, PostBigBlind), - rec(Street::Preflop, 1, Call), rec(Street::Preflop, 2, Check)]; - let line = |answer| { - let mut h = pre.to_vec(); - h.extend([rec(Street::Flop, 2, Bet), rec(Street::Flop, 1, Raise), rec(Street::Flop, 2, answer), - rec(Street::Turn, 1, Bet), rec(Street::Turn, 2, Call)]); - h - }; - let mut m = SessionMemory::new(); - for i in 0..40 { - m.observe_hand(&line(if i % 4 == 0 { Raise } else { Call }), 0, 2); - } - assert_eq!((m.c.reraise_seen, m.c.reraise_made), (40, 10)); - let r = m.read().expect("read").reraise_to_raise.unwrap(); - assert!((r - (10.0 + 3.0) / 50.0).abs() < 1e-12); - } - - /// One heads-up hand (hero seat 0 = seat 1, opponent seat 2): the opponent calls hero's preflop - /// raise (voluntary, not a raise), then calls a flop bet and folds the turn (passive, folds to a - /// bet, never aggressive). - fn loose_passive_hand() -> Vec { - vec![ - rec(Street::Preflop, 1, SeenAction::PostSmallBlind), - rec(Street::Preflop, 2, SeenAction::PostBigBlind), - rec(Street::Preflop, 1, SeenAction::Raise), - rec(Street::Preflop, 2, SeenAction::Call), - rec(Street::Flop, 1, SeenAction::Bet), - rec(Street::Flop, 2, SeenAction::Call), - rec(Street::Turn, 1, SeenAction::Bet), - rec(Street::Turn, 2, SeenAction::Fold), - ] - } - - /// Plan D1b: the wire modes shrink like `wire::decode_villain`. `Hud` trusts the live HUD's guessed - /// sample (23 hands, 2 aggression moves) however much was seen; `Counted` trusts the true counts. - #[test] - fn wire_modes_trust_the_live_or_the_counted_sample() { - use crate::exploit::sample::trust; - let mut m = SessionMemory::new(); - let h = loose_passive_hand(); - for _ in 0..300 { - m.observe_hand(&h, 0, 2); - } - let raw = m.read().expect("read after warmup"); - let postflop = m.c.aggressive + m.c.passive_call + m.c.passive_check; - let hud = m.as_wire(raw, WireRead::Hud, postflop); - let counted = m.as_wire(raw, WireRead::Counted, postflop); - assert_eq!(hud.confidence, Some(trust(HUD_HANDS as f64))); - assert_eq!(counted.confidence, Some(trust(m.c.hands as f64))); - assert_eq!(hud.aggression_confidence, Some(HUD_MOVES as f64 / (HUD_MOVES as f64 + 30.0))); - // The counted read sits nearer the raw rate than the HUD-trusted one. - let gap = |p: &Profile| (p.vpip.unwrap() - raw.vpip.unwrap()).abs(); - assert!(gap(&counted) < gap(&hud)); - assert_eq!(wire_read(), WireRead::Off); - } - - #[test] - fn no_read_before_the_warmup() { - let mut m = SessionMemory::new(); - let h = loose_passive_hand(); - for _ in 0..WARMUP_HANDS - 1 { - m.observe_hand(&h, 0, 2); - } - assert_eq!(m.read(), None); - m.observe_hand(&h, 0, 2); - assert!(m.read().is_some()); - } - - #[test] - fn a_seat_that_only_posts_a_blind_is_not_vpip() { - // Hero seat 0; the opponent (seat 2) is the big blind and checks its option: no voluntary - // money, no raise. - let hand = vec![ - rec(Street::Preflop, 1, SeenAction::PostSmallBlind), - rec(Street::Preflop, 2, SeenAction::PostBigBlind), - rec(Street::Preflop, 1, SeenAction::Call), - rec(Street::Preflop, 2, SeenAction::Check), - ]; - let mut m = SessionMemory::new(); - for _ in 0..WARMUP_HANDS { - m.observe_hand(&hand, 0, 2); - } - let p = m.read().expect("read after warmup"); - assert_eq!(p.vpip, Some(0.0)); - assert_eq!(p.pfr, Some(0.0)); - } - - #[test] - fn the_loose_passive_opponent_reads_as_a_calling_station() { - let mut m = SessionMemory::new(); - let h = loose_passive_hand(); - for _ in 0..40 { - m.observe_hand(&h, 0, 2); - } - let p = m.read().expect("read"); - assert_eq!(p.vpip, Some(1.0)); // calls every preflop - assert_eq!(p.pfr, Some(0.0)); - assert_eq!(p.fold_to_bet, Some(0.5)); // one call, one fold facing a bet - assert_eq!(p.aggression, Some(0.0)); // never bets or raises postflop - assert_eq!(classify(&p), Style::CallingStation); - } - - #[test] - fn checks_count_toward_aggression_so_a_passive_opponent_reads_passive() { - // Seat 2 bets once but checks the flop in every other hand. Aggression must be 1 / (1 bet + - // many checks), near zero - not 1 / 1 from leaving the checks out of the denominator. - let bet = vec![ - rec(Street::Preflop, 1, SeenAction::PostSmallBlind), - rec(Street::Preflop, 2, SeenAction::PostBigBlind), - rec(Street::Preflop, 1, SeenAction::Call), - rec(Street::Preflop, 2, SeenAction::Check), - rec(Street::Flop, 2, SeenAction::Bet), - ]; - let check = vec![ - rec(Street::Preflop, 1, SeenAction::PostSmallBlind), - rec(Street::Preflop, 2, SeenAction::PostBigBlind), - rec(Street::Preflop, 1, SeenAction::Call), - rec(Street::Preflop, 2, SeenAction::Check), - rec(Street::Flop, 2, SeenAction::Check), - ]; - let mut m = SessionMemory::new(); - m.observe_hand(&bet, 0, 2); - for _ in 0..29 { - m.observe_hand(&check, 0, 2); - } - let p = m.read().expect("read"); - assert_eq!(p.aggression, Some(1.0 / 30.0)); // 1 bet, 29 checks - } - - #[test] - fn per_street_aggression_splits_the_turn_from_the_pooled_read() { - // Seat 2 checks the flop (passive) but bets the turn (aggressive), no river action. The pooled - // aggression is 1 bet / (1 bet + 1 check) = 0.5, but the TURN aggression is 1/1 = 1.0, and the - // river stays None. This is exactly the barreler the pooled read under-sells. - let hand = vec![ - rec(Street::Preflop, 1, SeenAction::PostSmallBlind), - rec(Street::Preflop, 2, SeenAction::PostBigBlind), - rec(Street::Preflop, 1, SeenAction::Raise), - rec(Street::Preflop, 2, SeenAction::Call), - rec(Street::Flop, 1, SeenAction::Check), - rec(Street::Flop, 2, SeenAction::Check), - rec(Street::Turn, 1, SeenAction::Check), - rec(Street::Turn, 2, SeenAction::Bet), - ]; - let mut m = SessionMemory::new(); - for _ in 0..40 { - m.observe_hand(&hand, 0, 2); - } - let p = m.read().expect("read"); - assert_eq!(p.aggression, Some(0.5)); // 1 bet, 1 flop check pooled - assert_eq!(p.turn_aggression, Some(1.0)); // bets every turn, never passive on the turn - assert_eq!(p.river_aggression, None); // no river action seen - } - - #[test] - fn street_fold_is_shrunk_toward_the_pooled_read() { - // Folds every flop bet, calls every turn bet: pooled fold 0.5; the flop (n=40 folds) moves - // well above it, the turn well below it, the river (no data) stays None. - let hand = vec![ - rec(Street::Preflop, 1, SeenAction::PostSmallBlind), - rec(Street::Preflop, 2, SeenAction::PostBigBlind), - rec(Street::Preflop, 1, SeenAction::Raise), - rec(Street::Preflop, 2, SeenAction::Call), - rec(Street::Flop, 1, SeenAction::Bet), - rec(Street::Flop, 2, SeenAction::Fold), - ]; - let call = vec![ - rec(Street::Preflop, 1, SeenAction::Raise), - rec(Street::Preflop, 2, SeenAction::Call), - rec(Street::Turn, 1, SeenAction::Bet), - rec(Street::Turn, 2, SeenAction::Call), - ]; - let mut m = SessionMemory::new(); - for _ in 0..20 { - m.observe_hand(&hand, 0, 2); - m.observe_hand(&call, 0, 2); - } - let p = m.read().expect("read"); - assert_eq!(p.fold_to_bet, Some(0.5)); - let flop = p.street_fold_to_bet[0].expect("flop"); - let turn = p.street_fold_to_bet[1].expect("turn"); - assert!(flop > 0.7 && flop < 1.0, "{flop}"); - assert!(turn < 0.3 && turn > 0.0, "{turn}"); - assert_eq!(p.street_fold_to_bet[2], None); - } - - #[test] - fn a_tight_folding_opponent_reads_as_a_nit() { - // Seat 2 folds preflop every hand: no voluntary money, and (vpip 0) classifies as a nit. - let hand = vec![ - rec(Street::Preflop, 1, SeenAction::PostSmallBlind), - rec(Street::Preflop, 2, SeenAction::PostBigBlind), - rec(Street::Preflop, 1, SeenAction::Raise), - rec(Street::Preflop, 2, SeenAction::Fold), - ]; - let mut m = SessionMemory::new(); - for _ in 0..40 { - m.observe_hand(&hand, 0, 2); - } - let p = m.read().expect("read"); - assert_eq!(p.vpip, Some(0.0)); - assert_eq!(classify(&p), Style::Nit); - } -} +//! Session memory (Stage 1): the engine builds its read from the opponent's OBSERVED actions over +//! the hands of a session, instead of being handed the converged HUD read (`sim::reads`) or playing +//! blind. A HUD that only counts - per opponent seat, preflop voluntary money and raises, postflop +//! folds-to-a-bet and aggression - turned into a `Profile` once a warmup of hands is seen, so the +//! first hands play blind and the read converges to the truth over the session. +//! +//! The gap blind -> read-given that `benchmarks/baseline.txt` / `tests/sim_blind` measure is exactly +//! what this must recapture: a `... (memory)` scenario lands between the blind and the read-given +//! twin, the share of the prize that observation alone earns. Every opponent seat is the same fixed +//! archetype, so their counts pool into one read. + +use crate::exploit::profile::Profile; +use crate::exploit::sample::shrink_aggression; +use crate::game::{line, ActionRecord, SeenAction, Street}; + +pub use super::welt_memory::{ + strength_band, Cell, Move, Pos, Reveal, SizeBucket, Showdown, Texture, Tank, WorldEvent, WorldHand, + WorldMemory, STRENGTH_BANDS, +}; + +/// Hands to observe before the read is trusted; until then `read` is `None` (the engine plays +/// blind). Keeps an early, noisy sample from steering worse than no read at all. +pub const WARMUP_HANDS: u32 = 25; + +/// Postflop actions at which the read's confidence reaches 0.5 (half-life). Matches the Bayesian +/// posterior's `VERTRAUEN_HALB` so the counts HUD and `exploit::posterior` agree on how fast a read +/// earns trust. The river gearbox turns this confidence into the KL trust radius. +pub const CONFIDENCE_HALF: f64 = 30.0; + +/// Running tallies over the opponent archetype. Preflop opportunities (`hands`) and the voluntary / +/// raise counts drive vpip and pfr; the postflop tallies drive fold-to-bet and aggression. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +struct Counts { + hands: u32, + vpip: u32, + pfr: u32, + folded_to_bet: u32, + passive_call: u32, + passive_check: u32, + aggressive: u32, + // Per-street aggression split (turn and river only — the streets the subgame gearboxes solve). + // `*_passive` is calls plus checks on that street (the aggression denominator, matching the pooled + // one which counts checks); folds are excluded, as in the pooled aggression. + turn_aggressive: u32, + turn_passive: u32, + river_aggressive: u32, + river_passive: u32, + // Facing-a-bet outcomes per street (flop, turn, river): folds and calls, for the per-street + // fold-to-bet read. + street_fold: [u32; 3], + street_call: [u32; 3], + // Line-specific HUD stats (`game::line`): responses facing a c-bet / a 3-bet after opening / + // a bet after own check, and how many of them folded / folded / raised. + cbet_faced: u32, + cbet_folded: u32, + three_bet_faced: u32, + three_bet_folded: u32, + xr_chances: u32, + xr_made: u32, + // Postflop raises facing a bet (Raise, or an all-in over someone else's bet on that street). + raised_vs_bet: u32, + // Postflop actions facing aggression after the seat's own bet/raise on that street, and how many + // of them re-raised (`Profile::reraise_to_raise`). + reraise_seen: u32, + reraise_made: u32, +} + +fn street_index(street: Street) -> Option { + match street { + Street::Flop => Some(0), + Street::Turn => Some(1), + Street::River => Some(2), + Street::Preflop => None, + } +} + +/// Facing-a-bet samples that weigh as much as the pooled read when shrinking a street's fold rate. +pub const STREET_FOLD_PRIOR: f64 = crate::exploit::sample::STREET_PRIOR; + +static STREET_FOLD: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true); + +/// Switch the per-street fold read on or off (A/B arm for the ladder). Default on. +pub fn set_street_fold(on: bool) { + STREET_FOLD.store(on, std::sync::atomic::Ordering::Relaxed); +} + +fn street_fold_on() -> bool { + STREET_FOLD.load(std::sync::atomic::Ordering::Relaxed) +} + +/// Line-specific HUD reads switched into `read()`: bit 1 fold to c-bet, 2 fold to 3-bet, 4 check-raise. +static LINE_READS: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0); + +/// Line reads in `read()` (A/B arm): `READ_CBET | READ_THREE_BET | READ_CHECK_RAISE`. Default none. +pub fn set_line_reads(mask: u8) { + LINE_READS.store(mask, std::sync::atomic::Ordering::Relaxed); +} +pub const READ_CBET: u8 = 1; +pub const READ_THREE_BET: u8 = 2; +pub const READ_CHECK_RAISE: u8 = 4; + +fn line_read_on(bit: u8) -> bool { + LINE_READS.load(std::sync::atomic::Ordering::Relaxed) & bit != 0 +} + +/// Population anchors the line reads shrink toward over `STREET_FOLD_PRIOR` samples (a regular's +/// HUD): fold to 3-bet and check-raise have no pooled read to anchor on. +use crate::exploit::sample::{ + CHECK_RAISE_ANCHOR as CHECK_RAISE_PRIOR, CHECK_RAISE_KAPPA, FOLD_TO_THREE_BET_ANCHOR as FOLD_TO_THREE_BET_PRIOR, +}; + +static RIVER_SHOWDOWN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// Switch the river showdown read (`Profile::river_bluff_share`, from the world memory's revealed river +/// bets) into `read()` (A/B arm for the ladder). Default off until the ladder proves it. +pub fn set_river_showdown(on: bool) { + RIVER_SHOWDOWN.store(on, std::sync::atomic::Ordering::Relaxed); +} + +fn river_showdown_on() -> bool { + RIVER_SHOWDOWN.load(std::sync::atomic::Ordering::Relaxed) +} + +/// How the session read reaches the engine (A/B arm for the ladder, plan D1b "Zaehlung an den Kern"). +/// `Off` (default): the raw rates with the memory's own confidence, as always. The two wire modes pass +/// the read through exactly the shrink the live wire applies (`wire::decode_villain`: `sample::shrink` +/// over `hands`, `shrink_aggression` over the postflop moves, `shrink_street` per street), so the ladder +/// sees what a live profile would make of the same counts: +/// - `Hud`: the samples live had before 14.11. — `hands` capped at [`HUD_HANDS`] (the client HUD's +/// guessed count, live median 23), aggression at [`HUD_MOVES`] (moves in the log window, median 2), +/// each street at [`HUD_STREET`]; +/// - `Counted`: the true counts (`lesen/zaehler.py` fed into the profile, `lesen/profil.py mit_zaehlung`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum WireRead { + Off, + Hud, + Counted, +} + +/// Live samples before counted reads (14.11., 1910 villain profiles on 1763 postflop requests). +pub const HUD_HANDS: u32 = 23; +pub const HUD_MOVES: u32 = 2; +pub const HUD_STREET: u32 = 1; + +static WIRE_READ: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0); + +/// Switch the wire mode of `read()` (see [`WireRead`]). Default `Off`. +pub fn set_wire_read(mode: WireRead) { + let v = match mode { + WireRead::Off => 0, + WireRead::Hud => 1, + WireRead::Counted => 2, + }; + WIRE_READ.store(v, std::sync::atomic::Ordering::Relaxed); +} + +/// `LESEN_DRAHT=live`: the `Hud` wire as live runs WITHOUT `GEGNER_ZAEHLUNG` — the counted-only line +/// reads (`raiseToBet`, `reraiseToRaise`) never reach the core, so `RERAISE_*` / `TURN_RAISE_NUR` sit on +/// their pool anchor. The plain `Hud` mode keeps them (as measured before 15.11.). +static WIRE_WITHOUT_COUNTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +pub fn set_wire_without_counted(on: bool) { + WIRE_WITHOUT_COUNTED.store(on, std::sync::atomic::Ordering::Relaxed); +} + +fn wire_read() -> WireRead { + match WIRE_READ.load(std::sync::atomic::Ordering::Relaxed) { + 1 => WireRead::Hud, + 2 => WireRead::Counted, + _ => WireRead::Off, + } +} + +/// Memory handover foldToBet (plan D2, gedaechtnis-voll): with `Counted`, the pooled fold-to-bet is the +/// posterior `(k + a) / (n + a + b)` over the true facing-bet counts, exactly as `wire::decode_villain` +/// decodes `profile.reads.foldToBet {n, k, prior: [a, b]}`. Without a delivered prior live decodes the +/// core's anchor at 30 chances (a = 0.45 * 30, b = 0.55 * 30): that is the A arm, the D2 stake prior the +/// B arm. Unset (both 0): the `shrink` path as before (bit-identical). +static FOLD_PRIOR_A: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); +static FOLD_PRIOR_B: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// Set (`Some((a, b))`, both > 0) or clear the memory-handover foldToBet prior (see above). +pub fn set_fold_prior(prior: Option<(f64, f64)>) { + let (a, b) = prior.filter(|(a, b)| *a > 0.0 && *b > 0.0).unwrap_or((0.0, 0.0)); + FOLD_PRIOR_A.store(a.to_bits(), std::sync::atomic::Ordering::Relaxed); + FOLD_PRIOR_B.store(b.to_bits(), std::sync::atomic::Ordering::Relaxed); +} + +fn fold_prior() -> Option<(f64, f64)> { + let a = f64::from_bits(FOLD_PRIOR_A.load(std::sync::atomic::Ordering::Relaxed)); + let b = f64::from_bits(FOLD_PRIOR_B.load(std::sync::atomic::Ordering::Relaxed)); + (a > 0.0 && b > 0.0).then_some((a, b)) +} + +/// The read a HUD accumulates from watching one fixed opponent archetype play a session. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct SessionMemory { + c: Counts, + /// The richer dimensions (sizing x strength, texture x position cells, showdown reveals, timing), + /// see `sim::welt_memory`. Filled only by `observe_world_hand`; `read()` ignores it, so the classic + /// HUD read (and every existing ladder number) is unchanged by it. + world: WorldMemory, +} + +impl SessionMemory { + pub fn new() -> Self { + Self::default() + } + + /// The world-dimension observations (sizing, texture/position cells, showdowns, timing). + pub fn world(&self) -> &WorldMemory { + &self.world + } + + /// Fold one finished hand's world observations (see `WorldHand`) into the world memory. + /// The raw (chances, hits) per read, for the empirical-Bayes fit of the population priors + /// (`lesen/eichung.py`), named like `lesen/zaehler.py`. + pub fn line_counts(&self) -> Vec<(&'static str, u32, u32)> { + let c = &self.c; + vec![ + ("vpip", c.hands, c.vpip), + ("pfr", c.hands, c.pfr), + ("aggression", c.aggressive + c.passive_call + c.passive_check, c.aggressive), + ("flopFoldToBet", c.street_fold[0] + c.street_call[0], c.street_fold[0]), + ("turnFoldToBet", c.street_fold[1] + c.street_call[1], c.street_fold[1]), + ("riverFoldToBet", c.street_fold[2] + c.street_call[2], c.street_fold[2]), + ("foldToCbet", c.cbet_faced, c.cbet_folded), + ("foldToThreeBet", c.three_bet_faced, c.three_bet_folded), + ("checkRaise", c.xr_chances, c.xr_made), + ] + } + + pub fn observe_world_hand(&mut self, hand: &WorldHand) { + self.world.observe_world_hand(hand); + } + + /// Fold every opponent seat's actions of one finished hand into the counts. `hero` is the + /// 0-based hero seat; every other of the `players` seats is an opponent of the same archetype. + pub fn observe_hand(&mut self, history: &[ActionRecord], hero: usize, players: usize) { + for seat in 1..=players as u8 { + if seat as usize - 1 != hero { + self.observe_seat(history, seat); + } + } + } + + /// The line-specific responses of `seat`: each of its actions judged against the line before it. + fn observe_lines(&mut self, history: &[ActionRecord], seat: u8) { + for (k, r) in history.iter().enumerate().filter(|(_, r)| r.seat == seat) { + let before = &history[..k]; + let folded = r.action == SeenAction::Fold; + if r.street == Street::Flop && line::facing_cbet(before, seat) { + self.c.cbet_faced += 1; + self.c.cbet_folded += folded as u32; + } + if r.street == Street::Preflop && line::facing_three_bet(before, seat) { + self.c.three_bet_faced += 1; + self.c.three_bet_folded += folded as u32; + } + if r.street != Street::Preflop && line::check_raise_chance(before, seat, r.street) { + self.c.xr_chances += 1; + self.c.xr_made += r.action.is_aggressive() as u32; + } + } + } + + /// One seat's actions of a finished hand (a per-opponent memory at a mixed table, `sim::sechsmax`). + pub fn observe_seat(&mut self, history: &[ActionRecord], seat: u8) { + self.observe_lines(history, seat); + self.c.hands += 1; + let (mut voluntary, mut raised) = (false, false); + for (i, r) in history.iter().enumerate().filter(|(_, r)| r.seat == seat) { + if r.street == Street::Preflop { + // Blinds are forced (PostSmallBlind / PostBigBlind); a check is free. Only a call or + // an aggressive action puts money in by choice. + match r.action { + SeenAction::Call | SeenAction::Bet | SeenAction::Raise | SeenAction::AllIn => { + voluntary = true; + } + _ => {} + } + raised |= r.action.is_aggressive(); + } else { + // Postflop a fold or a call only happens facing a bet; a check faces nothing. The + // check still counts as a passive action for aggression (matching how the oracle + // reads are measured, `tests/sim_opponent_stats`): leaving checks out of the + // denominator makes a passive, check-heavy opponent look far more aggressive than it + // is, and `bluff_share` reads aggression directly. + // Facing aggression after an own bet/raise on this street: the re-raise spot. + let own = history[..i].iter().rposition(|b| b.street == r.street && b.seat == seat && b.action.is_aggressive()); + if let Some(j) = own { + if matches!(r.action, SeenAction::Fold | SeenAction::Call) || r.action.is_aggressive() { + if history[j + 1..i].iter().any(|b| b.street == r.street && b.seat != seat && b.action.is_aggressive()) { + self.c.reraise_seen += 1; + self.c.reraise_made += r.action.is_aggressive() as u32; + } + } + } + match r.action { + SeenAction::Fold => { + self.c.folded_to_bet += 1; + if let Some(i) = street_index(r.street) { + self.c.street_fold[i] += 1; + } + } + SeenAction::Call => { + if let Some(i) = street_index(r.street) { + self.c.street_call[i] += 1; + } + self.c.passive_call += 1; + self.bump_passive(r.street); + } + SeenAction::Check => { + self.c.passive_check += 1; + self.bump_passive(r.street); + } + a if a.is_aggressive() => { + self.c.aggressive += 1; + self.bump_aggressive(r.street); + let facing = a == SeenAction::Raise + || history[..i].iter().any(|b| b.street == r.street && b.seat != seat && b.action.is_aggressive()); + self.c.raised_vs_bet += facing as u32; + } + _ => {} + } + } + } + self.c.vpip += voluntary as u32; + self.c.pfr += raised as u32; + } + + /// A passive postflop action (call or check) on the turn/river, for the per-street aggression + /// denominator. Flop and preflop are not split. + fn bump_passive(&mut self, street: Street) { + match street { + Street::Turn => self.c.turn_passive += 1, + Street::River => self.c.river_passive += 1, + _ => {} + } + } + + /// An aggressive postflop action (bet or raise) on the turn/river, for the per-street numerator. + fn bump_aggressive(&mut self, street: Street) { + match street { + Street::Turn => self.c.turn_aggressive += 1, + Street::River => self.c.river_aggressive += 1, + _ => {} + } + } + + /// The read so far, or `None` during the warmup. vpip / pfr are over hands; fold-to-bet is folds + /// over folds-plus-calls facing a bet; aggression is bets-and-raises over bets-raises-and-calls. + pub fn read(&self) -> Option { + if self.c.hands < WARMUP_HANDS { + return None; + } + let ratio = |num: u32, den: u32| (den > 0).then(|| num as f64 / den as f64); + let facing_bet = self.c.folded_to_bet + self.c.passive_call; + // Aggression frequency: bets and raises over every non-folding postflop action, checks + // included (see `observe_seat`). + let postflop_actions = self.c.aggressive + self.c.passive_call + self.c.passive_check; + // Confidence for the gearbox: the read is only as trustworthy as its weaker postflop sample — + // the facing-a-bet count (drives fold_to_bet / the defense belief) and the total postflop + // count (drives aggression / the betting-polarization belief). Half at CONFIDENCE_HALF. + let conf = |n: u32| n as f64 / (n as f64 + CONFIDENCE_HALF); + let confidence = conf(facing_bet.min(postflop_actions)); + // Per-street aggression: bets/raises over bets-raises-plus-passive on that street (same shape + // as the pooled frequency). `None` until the street has an action, so `believed_villain` falls + // back to the pooled read. + let street_aggr = |aggr: u32, passive: u32| ratio(aggr, aggr + passive); + let pooled_fold = ratio(self.c.folded_to_bet, facing_bet); + let mut street_fold_to_bet = [None; 3]; + if let (true, Some(pooled)) = (street_fold_on(), pooled_fold) { + for i in 0..3 { + let n = (self.c.street_fold[i] + self.c.street_call[i]) as f64; + if n > 0.0 { + street_fold_to_bet[i] = + Some((self.c.street_fold[i] as f64 + STREET_FOLD_PRIOR * pooled) / (n + STREET_FOLD_PRIOR)); + } + } + } + let river_bluff = self.world.river_bluff().filter(|_| river_showdown_on()); + // Line reads, shrunk like the street reads: c-bet folds toward the flop fold read (else the + // pooled one), the others toward a regular's number. + let shrunk = |num: u32, den: u32, anchor: Option| { + anchor.filter(|_| den > 0).map(|a| (num as f64 + STREET_FOLD_PRIOR * a) / (den as f64 + STREET_FOLD_PRIOR)) + }; + let flop_anchor = street_fold_to_bet[0].or(pooled_fold); + let fold_to_cbet = shrunk(self.c.cbet_folded, self.c.cbet_faced, flop_anchor).filter(|_| line_read_on(READ_CBET)); + let fold_to_three_bet = shrunk(self.c.three_bet_folded, self.c.three_bet_faced, Some(FOLD_TO_THREE_BET_PRIOR)) + .filter(|_| line_read_on(READ_THREE_BET)); + let check_raise = (self.c.xr_chances > 0) + .then(|| (self.c.xr_made as f64 + CHECK_RAISE_KAPPA * CHECK_RAISE_PRIOR) / (self.c.xr_chances as f64 + CHECK_RAISE_KAPPA)) + .filter(|_| line_read_on(READ_CHECK_RAISE)); + let raw = Profile { + street_fold_to_bet, + fold_to_cbet, + fold_to_three_bet, + check_raise, + river_bluff_share: river_bluff.map(|(s, _)| s), + river_bluff_shown: river_bluff.map(|(_, n)| n as f64), + flop_aggression: None, + fold_to_steal: None, + fold_to_raise: None, + // Shrunk toward 0.30 (the middle of the `RERAISE_TIEFE` gate) with 10 pseudo-samples. + raise_to_bet: Some((self.c.raised_vs_bet as f64 + 10.0 * 0.30) / ((facing_bet + self.c.raised_vs_bet) as f64 + 10.0)), + // Same shrinkage, conditional on having bet/raised the street before facing the raise. + size_gain: size_gain(self.world.size_strength_corr(), self.world.size_pairs()), + reraise_to_raise: Some((self.c.reraise_made as f64 + 10.0 * 0.30) / (self.c.reraise_seen as f64 + 10.0)), + 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() + }; + Some(match wire_read() { + WireRead::Off => raw, + WireRead::Hud if WIRE_WITHOUT_COUNTED.load(std::sync::atomic::Ordering::Relaxed) => Profile { + raise_to_bet: None, + reraise_to_raise: None, + ..self.as_wire(raw, WireRead::Hud, postflop_actions) + }, + mode => self.as_wire(raw, mode, postflop_actions), + }) + } + + /// `raw` as the live wire would decode it from these counts (`wire::decode_villain`), with the + /// samples of `mode` (see [`WireRead`]). + fn as_wire(&self, raw: Profile, mode: WireRead, postflop_actions: u32) -> Profile { + use crate::exploit::sample::{shrink, shrink_aggression, shrink_street}; + let cap = |n: u32, c: u32| (if mode == WireRead::Hud { n.min(c) } else { n }) as f64; + let base = Profile { + turn_aggression: None, + river_aggression: None, + street_fold_to_bet: [None; 3], + confidence: None, + ..raw + }; + let pooled = shrink(&base, cap(self.c.hands, HUD_HANDS)); + let mut pooled = shrink_aggression(pooled, raw.aggression, cap(postflop_actions, HUD_MOVES)); + if let (WireRead::Counted, Some((a, b))) = (mode, fold_prior()) { + let n = (self.c.folded_to_bet + self.c.passive_call) as f64; + if n > 0.0 { + pooled.fold_to_bet = Some(((self.c.folded_to_bet as f64 + a) / (n + a + b)).clamp(0.0, 1.0)); + } + } + let rate = |k: u32, n: u32| (n > 0).then(|| k as f64 / n as f64); + let street = |k: u32, n: u32, anchor: Option| shrink_street(rate(k, n), cap(n, HUD_STREET), anchor); + let (ta, tn) = (self.c.turn_aggressive, self.c.turn_aggressive + self.c.turn_passive); + let (ra, rn) = (self.c.river_aggressive, self.c.river_aggressive + self.c.river_passive); + let mut street_fold_to_bet = [None; 3]; + if street_fold_on() { + for (i, slot) in street_fold_to_bet.iter_mut().enumerate() { + let n = self.c.street_fold[i] + self.c.street_call[i]; + *slot = street(self.c.street_fold[i], n, pooled.fold_to_bet); + } + } + Profile { + turn_aggression: street(ta, tn, pooled.aggression), + river_aggression: street(ra, rn, pooled.aggression), + street_fold_to_bet, + ..pooled + } + } +} + +/// Size-strength correlation that counts as the population's tell (gain 1 on `size_notch`). +const SIZE_CORR_POP: f64 = 0.4; +/// Pseudo-pairs of the gain prior (gain 1). +const SIZE_GAIN_PRIOR: f64 = 20.0; + +/// `Profile::size_gain` from the shown (size, strength) correlation over `n` pairs: corr / 0.4, +/// shrunk toward 1 with 20 pseudo-pairs, clamped to [-2, 2.5]; 1 without pairs. +pub fn size_gain(corr: Option, n: u32) -> Option { + let raw = corr.filter(|c| c.is_finite()).map_or(1.0, |c| c / SIZE_CORR_POP); + let n = n as f64; + Some(((n * raw + SIZE_GAIN_PRIOR) / (n + SIZE_GAIN_PRIOR)).clamp(-2.0, 2.5)) +} + +impl SessionMemory { + /// The raw rates counted so far (no warmup, no shrinking): the "truth" a long pre-session measures, + /// from which the HUD mode draws its noisy PokerIntel numbers (`sim::hud`). + pub fn raw_profile(&self) -> Profile { + let ratio = |num: u32, den: u32| (den > 0).then(|| num as f64 / den as f64); + Profile { + vpip: ratio(self.c.vpip, self.c.hands), + pfr: ratio(self.c.pfr, self.c.hands), + fold_to_bet: ratio(self.c.folded_to_bet, self.c.folded_to_bet + self.c.passive_call), + aggression: ratio(self.c.aggressive, self.c.aggressive + self.c.passive_call + self.c.passive_check), + fold_to_cbet: ratio(self.c.cbet_folded, self.c.cbet_faced), + fold_to_three_bet: ratio(self.c.three_bet_folded, self.c.three_bet_faced), + check_raise: ratio(self.c.xr_made, self.c.xr_chances), + ..Profile::default() + } + } + + /// The read a live table gives (`wire::decode_villain`): the client HUD `hud` (raw PokerIntel + /// numbers) believed over `GLAUBHAFT` + the hands seen so far (`sample::hud_profile`), the + /// aggression on its own counted moves, the street reads counted here toward the HUD-pooled ones. + pub fn hud_read(&self, hud: &Profile) -> Option { + let hands = crate::exploit::sample::GLAUBHAFT + self.c.hands as f64; + let base = crate::exploit::sample::hud_profile(hud, hands); + let ratio = |num: u32, den: u32| (den > 0).then(|| num as f64 / den as f64); + let actions = self.c.aggressive + self.c.passive_call + self.c.passive_check; + let p = if actions > 0 { + shrink_aggression(base, ratio(self.c.aggressive, actions), actions as f64) + } else { + base + }; + let street = |aggr: u32, passive: u32, anchor: Option| { + crate::exploit::sample::shrink_street(ratio(aggr, aggr + passive), (aggr + passive) as f64, anchor) + }; + let mut street_fold_to_bet = [None; 3]; + if street_fold_on() { + for (i, s) in street_fold_to_bet.iter_mut().enumerate() { + *s = street(self.c.street_fold[i], self.c.street_call[i], p.fold_to_bet); + } + } + let river_bluff = self.world.river_bluff().filter(|_| river_showdown_on()); + Some(Profile { + turn_aggression: street(self.c.turn_aggressive, self.c.turn_passive, p.aggression).or(p.turn_aggression), + river_aggression: street(self.c.river_aggressive, self.c.river_passive, p.aggression).or(p.river_aggression), + street_fold_to_bet, + river_bluff_share: river_bluff.map(|(s, _)| s), + river_bluff_shown: river_bluff.map(|(_, n)| n as f64), + // The counted line reads (`RERAISE_TIEFE`/`RERAISE_BLUFF`), as `read` gives them. + raise_to_bet: Some((self.c.raised_vs_bet as f64 + 10.0 * 0.30) / ((self.c.folded_to_bet + self.c.passive_call + self.c.raised_vs_bet) as f64 + 10.0)), + reraise_to_raise: Some((self.c.reraise_made as f64 + 10.0 * 0.30) / (self.c.reraise_seen as f64 + 10.0)), + size_gain: size_gain(self.world.size_strength_corr(), self.world.size_pairs()), + ..p + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::exploit::style::{classify, Style}; + + fn rec(street: Street, seat: u8, action: SeenAction) -> ActionRecord { + ActionRecord { street, seat, action, amount: None } + } + + /// The line reads count only the responses to their own line, shrink toward their anchors, and + /// stay out of the read until switched on (so the ladder stays bit-identical by default). + #[test] + fn line_reads_count_their_own_spots() { + use SeenAction::*; + let mut m = SessionMemory::new(); + // Hero (seat 1) opens and c-bets, the opponent (seat 2) folds the flop: a c-bet fold. + let cbet_fold = [ + rec(Street::Preflop, 1, PostSmallBlind), rec(Street::Preflop, 2, PostBigBlind), + rec(Street::Preflop, 1, Raise), rec(Street::Preflop, 2, Call), + rec(Street::Flop, 2, Check), rec(Street::Flop, 1, Bet), rec(Street::Flop, 2, Fold), + ]; + // The opponent opens, hero 3-bets, the opponent folds. + let three_fold = [ + rec(Street::Preflop, 2, PostSmallBlind), rec(Street::Preflop, 1, PostBigBlind), + rec(Street::Preflop, 2, Raise), rec(Street::Preflop, 1, Raise), rec(Street::Preflop, 2, Fold), + ]; + for _ in 0..30 { + m.observe_hand(&cbet_fold, 0, 2); + m.observe_hand(&three_fold, 0, 2); + } + assert_eq!((m.c.cbet_faced, m.c.cbet_folded), (30, 30)); + assert_eq!((m.c.three_bet_faced, m.c.three_bet_folded), (30, 30)); + assert_eq!((m.c.xr_chances, m.c.xr_made), (30, 0), "checked, faced the bet, folded: no check-raise"); + let off = m.read().expect("read"); + assert_eq!((off.fold_to_cbet, off.fold_to_three_bet, off.check_raise), (None, None, None)); + set_line_reads(READ_CBET | READ_THREE_BET | READ_CHECK_RAISE); + let on = m.read().expect("read"); + set_line_reads(0); + assert!(on.fold_to_cbet.unwrap() > 0.9); + assert!((on.fold_to_three_bet.unwrap() - (30.0 + 15.0 * 0.55) / 45.0).abs() < 1e-12); + assert!((on.check_raise.unwrap() - 15.0 * 0.08 / 45.0).abs() < 1e-12); + } + + /// The conditional re-raise read counts only answers to a raise after an own bet/raise on the street: + /// the opponent bets, hero raises, the opponent re-raises (hit) or calls (miss); a call of hero's + /// first bet is not that spot. + #[test] + fn reraise_read_counts_raises_after_own_aggression() { + use SeenAction::*; + let pre = [rec(Street::Preflop, 1, PostSmallBlind), rec(Street::Preflop, 2, PostBigBlind), + rec(Street::Preflop, 1, Call), rec(Street::Preflop, 2, Check)]; + let line = |answer| { + let mut h = pre.to_vec(); + h.extend([rec(Street::Flop, 2, Bet), rec(Street::Flop, 1, Raise), rec(Street::Flop, 2, answer), + rec(Street::Turn, 1, Bet), rec(Street::Turn, 2, Call)]); + h + }; + let mut m = SessionMemory::new(); + for i in 0..40 { + m.observe_hand(&line(if i % 4 == 0 { Raise } else { Call }), 0, 2); + } + assert_eq!((m.c.reraise_seen, m.c.reraise_made), (40, 10)); + let r = m.read().expect("read").reraise_to_raise.unwrap(); + assert!((r - (10.0 + 3.0) / 50.0).abs() < 1e-12); + } + + /// One heads-up hand (hero seat 0 = seat 1, opponent seat 2): the opponent calls hero's preflop + /// raise (voluntary, not a raise), then calls a flop bet and folds the turn (passive, folds to a + /// bet, never aggressive). + fn loose_passive_hand() -> Vec { + vec![ + rec(Street::Preflop, 1, SeenAction::PostSmallBlind), + rec(Street::Preflop, 2, SeenAction::PostBigBlind), + rec(Street::Preflop, 1, SeenAction::Raise), + rec(Street::Preflop, 2, SeenAction::Call), + rec(Street::Flop, 1, SeenAction::Bet), + rec(Street::Flop, 2, SeenAction::Call), + rec(Street::Turn, 1, SeenAction::Bet), + rec(Street::Turn, 2, SeenAction::Fold), + ] + } + + /// Plan D1b: the wire modes shrink like `wire::decode_villain`. `Hud` trusts the live HUD's guessed + /// sample (23 hands, 2 aggression moves) however much was seen; `Counted` trusts the true counts. + #[test] + fn wire_modes_trust_the_live_or_the_counted_sample() { + use crate::exploit::sample::trust; + let mut m = SessionMemory::new(); + let h = loose_passive_hand(); + for _ in 0..300 { + m.observe_hand(&h, 0, 2); + } + let raw = m.read().expect("read after warmup"); + let postflop = m.c.aggressive + m.c.passive_call + m.c.passive_check; + let hud = m.as_wire(raw, WireRead::Hud, postflop); + let counted = m.as_wire(raw, WireRead::Counted, postflop); + assert_eq!(hud.confidence, Some(trust(HUD_HANDS as f64))); + assert_eq!(counted.confidence, Some(trust(m.c.hands as f64))); + assert_eq!(hud.aggression_confidence, Some(HUD_MOVES as f64 / (HUD_MOVES as f64 + 30.0))); + // The counted read sits nearer the raw rate than the HUD-trusted one. + let gap = |p: &Profile| (p.vpip.unwrap() - raw.vpip.unwrap()).abs(); + assert!(gap(&counted) < gap(&hud)); + assert_eq!(wire_read(), WireRead::Off); + } + + #[test] + fn no_read_before_the_warmup() { + let mut m = SessionMemory::new(); + let h = loose_passive_hand(); + for _ in 0..WARMUP_HANDS - 1 { + m.observe_hand(&h, 0, 2); + } + assert_eq!(m.read(), None); + m.observe_hand(&h, 0, 2); + assert!(m.read().is_some()); + } + + #[test] + fn a_seat_that_only_posts_a_blind_is_not_vpip() { + // Hero seat 0; the opponent (seat 2) is the big blind and checks its option: no voluntary + // money, no raise. + let hand = vec![ + rec(Street::Preflop, 1, SeenAction::PostSmallBlind), + rec(Street::Preflop, 2, SeenAction::PostBigBlind), + rec(Street::Preflop, 1, SeenAction::Call), + rec(Street::Preflop, 2, SeenAction::Check), + ]; + let mut m = SessionMemory::new(); + for _ in 0..WARMUP_HANDS { + m.observe_hand(&hand, 0, 2); + } + let p = m.read().expect("read after warmup"); + assert_eq!(p.vpip, Some(0.0)); + assert_eq!(p.pfr, Some(0.0)); + } + + #[test] + fn the_loose_passive_opponent_reads_as_a_calling_station() { + let mut m = SessionMemory::new(); + let h = loose_passive_hand(); + for _ in 0..40 { + m.observe_hand(&h, 0, 2); + } + let p = m.read().expect("read"); + assert_eq!(p.vpip, Some(1.0)); // calls every preflop + assert_eq!(p.pfr, Some(0.0)); + assert_eq!(p.fold_to_bet, Some(0.5)); // one call, one fold facing a bet + assert_eq!(p.aggression, Some(0.0)); // never bets or raises postflop + assert_eq!(classify(&p), Style::CallingStation); + } + + #[test] + fn checks_count_toward_aggression_so_a_passive_opponent_reads_passive() { + // Seat 2 bets once but checks the flop in every other hand. Aggression must be 1 / (1 bet + + // many checks), near zero - not 1 / 1 from leaving the checks out of the denominator. + let bet = vec![ + rec(Street::Preflop, 1, SeenAction::PostSmallBlind), + rec(Street::Preflop, 2, SeenAction::PostBigBlind), + rec(Street::Preflop, 1, SeenAction::Call), + rec(Street::Preflop, 2, SeenAction::Check), + rec(Street::Flop, 2, SeenAction::Bet), + ]; + let check = vec![ + rec(Street::Preflop, 1, SeenAction::PostSmallBlind), + rec(Street::Preflop, 2, SeenAction::PostBigBlind), + rec(Street::Preflop, 1, SeenAction::Call), + rec(Street::Preflop, 2, SeenAction::Check), + rec(Street::Flop, 2, SeenAction::Check), + ]; + let mut m = SessionMemory::new(); + m.observe_hand(&bet, 0, 2); + for _ in 0..29 { + m.observe_hand(&check, 0, 2); + } + let p = m.read().expect("read"); + assert_eq!(p.aggression, Some(1.0 / 30.0)); // 1 bet, 29 checks + } + + #[test] + fn per_street_aggression_splits_the_turn_from_the_pooled_read() { + // Seat 2 checks the flop (passive) but bets the turn (aggressive), no river action. The pooled + // aggression is 1 bet / (1 bet + 1 check) = 0.5, but the TURN aggression is 1/1 = 1.0, and the + // river stays None. This is exactly the barreler the pooled read under-sells. + let hand = vec![ + rec(Street::Preflop, 1, SeenAction::PostSmallBlind), + rec(Street::Preflop, 2, SeenAction::PostBigBlind), + rec(Street::Preflop, 1, SeenAction::Raise), + rec(Street::Preflop, 2, SeenAction::Call), + rec(Street::Flop, 1, SeenAction::Check), + rec(Street::Flop, 2, SeenAction::Check), + rec(Street::Turn, 1, SeenAction::Check), + rec(Street::Turn, 2, SeenAction::Bet), + ]; + let mut m = SessionMemory::new(); + for _ in 0..40 { + m.observe_hand(&hand, 0, 2); + } + let p = m.read().expect("read"); + assert_eq!(p.aggression, Some(0.5)); // 1 bet, 1 flop check pooled + assert_eq!(p.turn_aggression, Some(1.0)); // bets every turn, never passive on the turn + assert_eq!(p.river_aggression, None); // no river action seen + } + + #[test] + fn street_fold_is_shrunk_toward_the_pooled_read() { + // Folds every flop bet, calls every turn bet: pooled fold 0.5; the flop (n=40 folds) moves + // well above it, the turn well below it, the river (no data) stays None. + let hand = vec![ + rec(Street::Preflop, 1, SeenAction::PostSmallBlind), + rec(Street::Preflop, 2, SeenAction::PostBigBlind), + rec(Street::Preflop, 1, SeenAction::Raise), + rec(Street::Preflop, 2, SeenAction::Call), + rec(Street::Flop, 1, SeenAction::Bet), + rec(Street::Flop, 2, SeenAction::Fold), + ]; + let call = vec![ + rec(Street::Preflop, 1, SeenAction::Raise), + rec(Street::Preflop, 2, SeenAction::Call), + rec(Street::Turn, 1, SeenAction::Bet), + rec(Street::Turn, 2, SeenAction::Call), + ]; + let mut m = SessionMemory::new(); + for _ in 0..20 { + m.observe_hand(&hand, 0, 2); + m.observe_hand(&call, 0, 2); + } + let p = m.read().expect("read"); + assert_eq!(p.fold_to_bet, Some(0.5)); + let flop = p.street_fold_to_bet[0].expect("flop"); + let turn = p.street_fold_to_bet[1].expect("turn"); + assert!(flop > 0.7 && flop < 1.0, "{flop}"); + assert!(turn < 0.3 && turn > 0.0, "{turn}"); + assert_eq!(p.street_fold_to_bet[2], None); + } + + #[test] + fn a_tight_folding_opponent_reads_as_a_nit() { + // Seat 2 folds preflop every hand: no voluntary money, and (vpip 0) classifies as a nit. + let hand = vec![ + rec(Street::Preflop, 1, SeenAction::PostSmallBlind), + rec(Street::Preflop, 2, SeenAction::PostBigBlind), + rec(Street::Preflop, 1, SeenAction::Raise), + rec(Street::Preflop, 2, SeenAction::Fold), + ]; + let mut m = SessionMemory::new(); + for _ in 0..40 { + m.observe_hand(&hand, 0, 2); + } + let p = m.read().expect("read"); + assert_eq!(p.vpip, Some(0.0)); + assert_eq!(classify(&p), Style::Nit); + } +}