diff --git a/docs/notizen/STAND-weltklasse.md b/docs/notizen/STAND-weltklasse.md index eb1b1691..0e7a1795 100644 --- a/docs/notizen/STAND-weltklasse.md +++ b/docs/notizen/STAND-weltklasse.md @@ -222,3 +222,14 @@ das E1-Tor erneut. | M4 Engine-LBR | LBR gegen die Live-Engine gebaut, exakt ~25 s/Hand, fortsetzbar (`pokerbench-engine-lbr`, 20 000 Hände in der Warteschlange) | 9f59e1a, e00dc74 | | M4 Stichprobe | Range-Stichprobe statt aller Combos, gepaart gegen exakt auf der echten Grundstrategie (4000 Hände): k=24 −155, k=48 −112, k=96 −35, k=192 −14 ±46 bb/100. **Verworfen**: spart nur mit großer Verzerrung nach unten | e00dc74 | | Übung, Fehlerscan | 1741 Züge: 0 Folds bei freiem Check, 0 verpasste Monster-Werte; Luft-Bluffs 1 von 314; offen: MDF-Boden-Calls am River (15, bis ~100 bb), Prüfung wartet auf Hand-ID im Zug-Log | af3013a | + + +## 8. Nachtrag 14.11.: E3 Turn+River nachrechnen (gebaut, ungemessen) + +| Baustein | Stand | +|---|---| +| `cfr::turn_river_game` | Turn+River als ein Spiel ueber echte Combos: Turn-Setzen (50 %, 100 %, All-in, ein Raise, beobachtete Groesse exakt im Baum), Zufallsknoten ueber die River-Karten, River-Setzen; CFR+ voll in der Breite, Showdown in O(Haende) je Karte; exakter Best Response je Spieler (Ausnutzbarkeit) | +| `engine::turn_game` | Weiche `TurnPlayer::Grund` (Standard Aus; `ab_zelle`/`engine_lbr`: `TURN_SPIEL=grund`, braucht `GRUNDSTRATEGIE`). Ranges aus `ranges` am Turn-Knoten, Villain-Range ohne Blocker der echten Hand, damit ein Solve fuer alle Haende am Knoten reicht (Cache nach oeffentlichem Zustand). Haende ausserhalb der beschnittenen Range spielt die Heuristik | +| Abnahme | Tests: Vektorwerte = skalare Aufzaehlung, Nullsumme, Best Response = Brute Force ueber alle reinen Strategien, Turn durchgecheckt = `river_game` (Wert und Ausnutzbarkeit), nur legale Choices, Aus = unveraendert | +| Naeherungen | Range auf 95 % Masse / 160 Combos, 10 von 48 River-Karten (gleichmaessig gestreift, je 1/K), kein River-Raise (Schalter `TURN_RIVER_RAISES=1`), feste 200 Iterationen; ~1,3 s je Entscheidung auf einem Faden | +| Offen | Messung (LBR gegen die Live-Engine mit `TURN_SPIEL=grund`; die HU-Leiter `ab_zelle` sieht wegen `seats = 2` nie Blueprint-Ranges, die Arme `river-grund`/`turn-grund` dort sind Identitaet) | diff --git a/src/bin/ab_zelle.rs b/src/bin/ab_zelle.rs index 599ed0c4..0ead8e5d 100644 --- a/src/bin/ab_zelle.rs +++ b/src/bin/ab_zelle.rs @@ -6,6 +6,7 @@ //! //! The arm is chosen by environment so independent processes stay paired: //! - `TURN_VETO`, `TURN_BUCKET`, `TURN_PER_STREET`: read by the turn track itself, +//! - `TURN_SPIEL=grund` (with `GRUNDSTRATEGIE`): the turn+river game with blueprint ranges (plan E3), //! - every other track adds its switch in `apply_arm` below (identity on the engine branch). //! //! Run: `ab_zelle [welt-deals=2000] [klassik-deals=4000] [draws=4] [rows=all|welt|klassik|a,b,..]` @@ -62,10 +63,16 @@ fn apply_arm() { Ok("grund") => RiverPlayer::Grund, _ => RiverPlayer::Off, }); + // TURN_SPIEL=grund: the turn+river game with both ranges from the blueprint (plan E3, + // `engine::turn_game`), only where the blueprint recognises the spot. Needs GRUNDSTRATEGIE like + // RIVER_DBR=grund. Size/budget: TURN_COMBOS, TURN_CARDS, TURN_ITERS (defaults in `TurnConfig`). + use rechner::engine::turn_game::{set_turn_player, TurnPlayer}; + let turn_grund = std::env::var("TURN_SPIEL").as_deref() == Ok("grund"); + set_turn_player(if turn_grund { TurnPlayer::Grund } else { TurnPlayer::Off }); // The blueprint arm waits until the blueprint run has finished (its FERTIG marker), so a // queued arm never reads a half-trained checkpoint; then loads it once. - if std::env::var("RIVER_DBR").as_deref() == Ok("grund") { - let dir = std::path::PathBuf::from(std::env::var_os("GRUNDSTRATEGIE").expect("RIVER_DBR=grund needs GRUNDSTRATEGIE")); + if turn_grund || std::env::var("RIVER_DBR").as_deref() == Ok("grund") { + let dir = std::path::PathBuf::from(std::env::var_os("GRUNDSTRATEGIE").expect("RIVER_DBR=grund / TURN_SPIEL=grund needs GRUNDSTRATEGIE")); while !dir.join("grundstrategie").join("FERTIG").exists() { std::thread::sleep(std::time::Duration::from_secs(60)); } diff --git a/src/bin/engine_lbr.rs b/src/bin/engine_lbr.rs index 46f3237f..91765000 100644 --- a/src/bin/engine_lbr.rs +++ b/src/bin/engine_lbr.rs @@ -7,7 +7,7 @@ //! file as `i value_bb` at once, and a restart computes only the missing hands. //! //! Run: `engine_lbr [seed]`, threads from `POKERBENCH_THREADS` (default 1). -//! The engine runs with its default switches (no env arms). +//! The engine runs with its default switches; the one env arm is `TURN_SPIEL=grund` (turn game, E3). use rechner::blueprint::abstraktion::river_cuts; use rechner::blueprint::engine_gegner::EngineGegner; @@ -27,6 +27,12 @@ fn main() { let haende: u64 = args[2].parse().expect("hands"); let seed: u64 = args.get(3).map(|x| x.parse().expect("seed")).unwrap_or(7); let threads: usize = std::env::var("POKERBENCH_THREADS").ok().and_then(|x| x.parse().ok()).unwrap_or(1).max(1); + // TURN_SPIEL=grund (plan E3): the turn+river game with blueprint ranges plays the engine's turn + // where the blueprint recognises the spot (needs GRUNDSTRATEGIE: tables and checkpoint). + if std::env::var("TURN_SPIEL").as_deref() == Ok("grund") { + rechner::engine::turn_game::set_turn_player(rechner::engine::turn_game::TurnPlayer::Grund); + assert!(rechner::blueprint::ranges::grundstrategie().is_some(), "TURN_SPIEL=grund needs GRUNDSTRATEGIE with tables and checkpoint"); + } let mut fertig = vec![None; haende as usize]; if let Ok(t) = std::fs::read_to_string(&out) { diff --git a/src/blueprint/ranges.rs b/src/blueprint/ranges.rs index 873a0367..22f439d3 100644 --- a/src/blueprint/ranges.rs +++ b/src/blueprint/ranges.rs @@ -1,498 +1,514 @@ -//! Ranges of both players from the blueprint (plan E2e): the input the river game was missing. -//! -//! A real spot is mapped onto a scenario of the family (`szenario::ALLE`) when it is one: S1 (button -//! opened, small blind folded, big blind called), the cutoff or small blind opening against a -//! calling big blind, or a 3-bet pot (button / cutoff opens, big blind 3-bets, opener calls); always -//! heads-up from the flop on, about 100 bb deep. A 4-bet pot, a multiway pot, a limp or any other -//! opener gives `None`. The played postflop line is walked -//! through the scenario's tree, real sizes mapped onto the tree's sizes by the pseudo-harmonic rule -//! (Ganzfried/Sandholm 2013, deterministic: the nearer side under that rule). Each player's range is -//! the chart weight of every combo times the blueprint's probability of each action the player -//! took, read through the combo's class on that street's board. - -use super::abstraktion::river_ehs; -use super::mccfr::{Knoten, Tabellen}; -use super::s1::{Aktion, Grund}; -use super::szenario::{Szenario, ALLE}; -use crate::preflop::position::Position; -use crate::preflop::seat_position::seat_position; -use crate::card::Card; -use crate::game::{SeenAction, Spot, Street}; -use crate::hand::fast7; - -/// Combos with weights, hero's and villain's (S1 index of the combo list `S1::alle`). -pub struct Ranges { - pub hero: Vec, - pub villain: Vec, - /// Scenario player of the hero (0 = out of position, 1 = in position). - pub hero_spieler: usize, - /// The scenario's node of the hero's decision. - pub knoten: usize, -} - -/// Pseudo-harmonic choice between the neighbouring abstract fractions `a < x < b`: the probability -/// of `a` is `(b - x)(1 + a) / ((b - a)(1 + x))`; the side with probability >= 1/2 is taken. -pub(super) fn harmonisch(x: f64, kandidaten: &[(f64, usize)]) -> Option { - let mut k: Vec<(f64, usize)> = kandidaten.to_vec(); - k.sort_by(|p, q| p.0.total_cmp(&q.0)); - let first = k.first()?; - if x <= first.0 { - return Some(first.1); - } - for w in k.windows(2) { - let ((a, ia), (b, ib)) = (w[0], w[1]); - if x <= b { - let pa = (b - x) * (1.0 + a) / ((b - a) * (1.0 + x)); - return Some(if pa >= 0.5 { ia } else { ib }); - } - } - k.last().map(|l| l.1) -} - -/// The scenario a spot's preflop line is, with its seats `(out of position, in position)`: the -/// first raise opens (from the button, cutoff or small blind), the big blind calls or 3-bets and the -/// 3-bettor is called; everybody else folded. `None` for anything else (4-bet, multiway, limp, an -/// open from another seat, sizes off the scenarios'). -pub fn erkennen(spot: &Spot) -> Option<(&'static Szenario, (u8, u8))> { - if spot.variant != crate::variant::Variant::Nlhe || spot.seats < 3 { - return None; - } - spot.button_seat?; - let bb = spot.history.iter().find(|r| r.action == SeenAction::PostBigBlind)?.seat; - let mut opener: Option<(u8, f64)> = None; - let mut dreibet: Option = None; - let (mut called, mut opener_called) = (false, false); - for r in spot.history.iter().filter(|r| r.street == Street::Preflop) { - match r.action { - SeenAction::PostSmallBlind | SeenAction::PostBigBlind | SeenAction::PostAnte => {} - SeenAction::Fold if r.seat != bb && Some(r.seat) != opener.map(|o| o.0) => {} - SeenAction::Raise | SeenAction::Bet if opener.is_none() && r.seat != bb => opener = Some((r.seat, r.amount? / spot.big_blind)), - SeenAction::Raise | SeenAction::Bet if opener.is_some() && r.seat == bb && dreibet.is_none() && !called => { - dreibet = Some(r.amount? / spot.big_blind) - } - SeenAction::Call if opener.is_some() && r.seat == bb && dreibet.is_none() && !called => called = true, - SeenAction::Call if dreibet.is_some() && Some(r.seat) == opener.map(|o| o.0) && !opener_called => opener_called = true, - _ => return None, - } - } - let (opener_seat, to) = opener?; - if !(called || (dreibet.is_some() && opener_called)) { - return None; - } - let chart_seat = match seat_position(spot, opener_seat) { - Position::Button => crate::cfr::seat::Seat::Button, - Position::Cutoff => crate::cfr::seat::Seat::Cutoff, - Position::SmallBlind => crate::cfr::seat::Seat::SmallBlind, - _ => return None, - }; - let in_window = |x: f64, (lo, hi): (f64, f64)| x >= lo && x <= hi; - let sz = ALLE.iter().find(|z| { - z.eroeffner == chart_seat - && z.dreibet.is_some() == dreibet.is_some() - && in_window(to, z.erkennung_eroeffnung) - && dreibet.is_none_or(|d| in_window(d, z.erkennung_dreibet)) - })?; - let sitze = if sz.eroeffner_spieler() == 0 { (opener_seat, bb) } else { (bb, opener_seat) }; - Some((sz, sitze)) -} - -fn karten_maske(cards: &[Card]) -> u64 { - fast7::mask(cards) -} - -static GRUND: [std::sync::OnceLock>; ALLE.len()] = - [const { std::sync::OnceLock::new() }; ALLE.len()]; - -/// The blueprint of scenario `sz`, loaded once from `$GRUNDSTRATEGIE/abstraktion/` and -/// `$GRUNDSTRATEGIE/grundstrategie/.ckpt`; `None` without the variable or the files. -pub fn grundstrategie_fuer(sz: &Szenario) -> Option<&'static (Grund, Tabellen)> { - GRUND[sz.index()] - .get_or_init(|| { - let dir = std::path::PathBuf::from(std::env::var_os("GRUNDSTRATEGIE")?); - let s = Grund::mit(ALLE.iter().find(|z| z.id == sz.id)?, super::s1::Abstraktion::laden(&dir.join("abstraktion")).ok()?); - let mut tab = Tabellen::neu(&s); - tab.datei_lesen(&dir.join("grundstrategie").join(format!("{}.ckpt", sz.id))).then_some((s, tab)) - }) - .as_ref() -} - -/// The S1 blueprint (`grundstrategie_fuer` of S1). -pub fn grundstrategie() -> Option<&'static (Grund, Tabellen)> { - grundstrategie_fuer(Szenario::s1()) -} - -/// Weighted combo lists (hero, villain) for the river game from the blueprint, if the spot is one -/// of the scenarios and its blueprint is loaded. -pub fn gewichtete_listen(spot: &Spot) -> Option<(Vec<(Vec, f64)>, Vec<(Vec, f64)>)> { - let (sz, _) = erkennen(spot)?; - let (s, tab) = grundstrategie_fuer(sz)?; - let r = ranges(s, tab, spot)?; - let deck = Card::parse_list("2c 3c 4c 5c 6c 7c 8c 9c Tc Jc Qc Kc Ac 2d 3d 4d 5d 6d 7d 8d 9d Td Jd Qd Kd Ad 2h 3h 4h 5h 6h 7h 8h 9h Th Jh Qh Kh Ah 2s 3s 4s 5s 6s 7s 8s 9s Ts Js Qs Ks As")?; - let karte = |bit: u64| deck.iter().copied().find(|c| fast7::bit(*c) == bit); - let liste = |w: &[f64]| -> Option, f64)>> { - s.alle - .iter() - .zip(w) - .filter(|(_, x)| **x > 1e-12) - .map(|(c, x)| Some((vec![karte(c & c.wrapping_neg())?, karte(c & (c - 1))?], *x))) - .collect() - }; - let (h, v) = (liste(&r.hero)?, liste(&r.villain)?); - (!h.is_empty() && !v.is_empty()).then_some((h, v)) -} - -/// Ranges for the hero's current decision, or `None` when the spot is not scenario `s` or the line -/// leaves its tree. -pub fn ranges(s: &Grund, tab: &Tabellen, spot: &Spot) -> Option { - let (sz, (oop, ip)) = erkennen(spot)?; - if sz.id != s.sz.id { - return None; - } - let stapel = sz.stapel; - let hero_spieler = if spot.hero_seat == oop { 0 } else if spot.hero_seat == ip { 1 } else { return None }; - let villain_seat = if hero_spieler == 0 { ip } else { oop }; - let villain = spot.villains.iter().find(|v| v.seat == villain_seat && !v.folded)?; - if spot.live_villains().count() != 1 || spot.board.len() < 3 { - return None; - } - // About 100 bb effective at the flop (S1 is computed for 100). - let eff = (spot.hero_stack.min(villain.stack) + spot.pot / 2.0) / spot.big_blind; - if !(70.0..=140.0).contains(&eff) { - return None; - } - let bbs = |x: f64| x / spot.big_blind; - let board_all = karten_maske(&spot.board); - let boards = [karten_maske(&spot.board[..3]), karten_maske(&spot.board[..spot.board.len().min(4)]), board_all]; - let ehs = if spot.board.len() == 5 { river_ehs(board_all, &s.alle) } else { Vec::new() }; - let mut w = [s.gewicht[0].clone(), s.gewicht[1].clone()]; - for (i, c) in s.alle.iter().enumerate() { - if c & board_all != 0 { - w[0][i] = 0.0; - w[1][i] = 0.0; - } - } - let hero_mask = karten_maske(&spot.hero_cards); - // Real contributions on the current street (bb) and the real pot at the street start. - let preflop_pot: f64 = { - let mut c: std::collections::HashMap = std::collections::HashMap::new(); - for r in spot.history.iter().filter(|r| r.street == Street::Preflop) { - if let Some(a) = r.amount { - let e = c.entry(r.seat).or_insert(0.0); - *e = if r.action == SeenAction::PostAnte { *e + a } else { e.max(a) }; - } - } - c.values().map(|x| bbs(*x)).sum() - }; - let mut real_pot = preflop_pot; - let mut k = s.baum.baum.wurzel; - let streets = [Street::Flop, Street::Turn, Street::River]; - for (si, st) in streets.iter().enumerate() { - if si >= spot.board.len() - 2 { - break; - } - let mut c_real = [0.0f64; 2]; - for r in spot.history.iter().filter(|r| r.street == *st) { - let p = if r.seat == oop { 0 } else if r.seat == ip { 1 } else { continue }; - let Knoten::Zug { spieler, strasse, kinder } = &s.baum.baum.knoten[k] else { return None }; - if *spieler != p || *strasse != si { - return None; - } - let pot_real = real_pot + c_real[0] + c_real[1]; - let child = match r.action { - SeenAction::Check => kinder.iter().copied().find(|c| s.baum.aktion[*c] == Some(Aktion::Check))?, - SeenAction::Call => kinder.iter().copied().find(|c| s.baum.aktion[*c] == Some(Aktion::Call))?, - SeenAction::Fold => return None, - SeenAction::Bet | SeenAction::Raise | SeenAction::AllIn => { - let to = bbs(r.amount?); - let all_in = r.action == SeenAction::AllIn; - let c_s1 = s.baum.beitrag[k]; - let pot_s1 = c_s1[0] + c_s1[1]; - let kand: Vec<(f64, usize)> = kinder - .iter() - .filter_map(|c| match s.baum.aktion[*c] { - Some(Aktion::Bet(t)) | Some(Aktion::Raise(t)) => Some(((t - c_s1[p]) / pot_s1, *c, t)), - _ => None, - }) - .map(|(f, c, t)| if all_in && t >= stapel { (f64::INFINITY, c) } else { (f, c) }) - .collect(); - if kand.is_empty() { - // Call-equivalent all-in against a bet the tree cannot raise any more. - kinder.iter().copied().find(|c| s.baum.aktion[*c] == Some(Aktion::Call))? - } else if all_in { - kand.iter().find(|x| x.0.is_infinite()).map(|x| x.1).or_else(|| harmonisch((to - c_real[p]) / pot_real, &kand))? - } else { - let kand: Vec<(f64, usize)> = kand.into_iter().filter(|x| x.0.is_finite()).collect(); - harmonisch((to - c_real[p]) / pot_real, &kand)? - } - } - _ => continue, - }; - // The actor's range: times the blueprint's probability of this action per combo class. - let a = kinder.iter().position(|c| *c == child)?; - let n = kinder.len(); - let board = boards[si]; - for (i, c) in s.alle.iter().enumerate() { - if w[p][i] > 0.0 { - let cls = s.klasse_von(*c, board, si, &ehs); - w[p][i] *= tab.durchschnitt(k, cls, n)[a]; - } - } - if let Some(a) = r.amount { - c_real[p] = bbs(a); - } - if r.action == SeenAction::Call { - c_real[p] = c_real[1 - p]; - } - k = child; - } - real_pot += c_real[0] + c_real[1]; - } - let Knoten::Zug { spieler, strasse, .. } = &s.baum.baum.knoten[k] else { return None }; - if *spieler != hero_spieler || *strasse + 3 != spot.board.len() { - return None; - } - let mut villain_w = w[1 - hero_spieler].clone(); - for (i, c) in s.alle.iter().enumerate() { - if c & hero_mask != 0 { - villain_w[i] = 0.0; - } - } - Some(Ranges { hero: w[hero_spieler].clone(), villain: villain_w, hero_spieler, knoten: k }) -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::blueprint::abstraktion::river_cuts; - use crate::blueprint::s1::{Abstraktion, S1}; - use crate::game::{ActionKind, ActionRecord, Villain}; - use crate::variant::Variant; - - fn rec(street: Street, seat: u8, action: SeenAction, amount: Option) -> ActionRecord { - ActionRecord { street, seat, action, amount } - } - - /// Six-max: button 4 opens 2.5, small blind 5 folds, big blind 0 calls; flop check, bet 1.8, - /// call; turn check-check; river big blind bets 6, the button (hero) decides. - pub(super) fn s1_river_spot() -> Spot { - s1_river(false) - } - - fn s1_river(three_bet: bool) -> Spot { - use SeenAction::*; - use Street::*; - let mut h = vec![ - rec(Preflop, 5, PostSmallBlind, Some(0.5)), - rec(Preflop, 0, PostBigBlind, Some(1.0)), - rec(Preflop, 1, Fold, None), - rec(Preflop, 2, Fold, None), - rec(Preflop, 3, Fold, None), - rec(Preflop, 4, Raise, Some(2.5)), - rec(Preflop, 5, Fold, None), - ]; - if three_bet { - h.push(rec(Preflop, 0, Raise, Some(9.0))); - h.push(rec(Preflop, 4, Call, Some(9.0))); - } else { - h.push(rec(Preflop, 0, Call, Some(2.5))); - } - h.extend([ - rec(Flop, 0, Check, None), - rec(Flop, 4, Bet, Some(1.8)), - rec(Flop, 0, Call, Some(1.8)), - rec(Turn, 0, Check, None), - rec(Turn, 4, Check, None), - rec(River, 0, Bet, Some(6.0)), - ]); - Spot { - variant: Variant::Nlhe, - big_blind: 1.0, - seats: 6, - hero_seat: 4, - button_seat: Some(4), - hero_cards: Card::parse_list("Ac Qd").unwrap(), - board: Card::parse_list("Ah 7d 2c Ks 9h").unwrap(), - street: Street::River, - pot: 15.1, - to_call: 6.0, - hero_stack: 93.7, - min_raise_to: Some(12.0), - max_raise_to: Some(93.7), - legal: vec![ActionKind::Fold, ActionKind::Call, ActionKind::Raise], - allowed_sizes: None, - villains: vec![Villain { seat: 0, stack: 89.7, folded: false, profile: None }], - seed: 1, - history: h, - } - } - - #[test] - fn an_s1_line_gives_ranges_at_the_heros_river_node() { - let s = S1::neu(Abstraktion { flop: None, turn: None, river: river_cuts(50, 1) }); - let tab = Tabellen::neu(&s); - let r = ranges(&s, &tab, &s1_river(false)).expect("the line is S1"); - assert_eq!(r.hero_spieler, 1); - let Knoten::Zug { spieler, strasse, .. } = &s.baum.baum.knoten[r.knoten] else { panic!() }; - assert_eq!((*spieler, *strasse), (1, 2)); - assert!(matches!(s.baum.aktion[r.knoten], Some(Aktion::Bet(_))), "river bet mapped to a tree bet"); - let board = karten_maske(&Card::parse_list("Ah 7d 2c Ks 9h").unwrap()); - let hero = karten_maske(&Card::parse_list("Ac Qd").unwrap()); - for (i, c) in s.alle.iter().enumerate() { - if c & board != 0 { - assert_eq!(r.hero[i], 0.0); - assert_eq!(r.villain[i], 0.0); - } - if c & hero != 0 { - assert_eq!(r.villain[i], 0.0, "the villain cannot hold the hero's cards"); - } - } - assert!(r.villain.iter().any(|x| *x > 0.0) && r.hero.iter().any(|x| *x > 0.0)); - assert!(ranges(&s, &tab, &s1_river(true)).is_none(), "a 3-bet pot is not S1"); - } - - /// 6-max seats: button 4, small blind 5, big blind 0, UTG 1, MP 2, cutoff 3. - fn pre(opener: u8, to: f64, rest: &[(u8, SeenAction, f64)]) -> Vec { - use SeenAction::*; - let mut h = vec![rec(Street::Preflop, 5, PostSmallBlind, Some(0.5)), rec(Street::Preflop, 0, PostBigBlind, Some(1.0))]; - for seat in 1..opener.min(6) { - h.push(rec(Street::Preflop, seat, Fold, None)); - } - h.push(rec(Street::Preflop, opener, Raise, Some(to))); - for (seat, a, amount) in rest { - h.push(rec(Street::Preflop, *seat, *a, (*a != Fold).then_some(*amount))); - } - h - } - - /// River spot of a preflop line: flop check / bet / call, turn check-check, river bet of the - /// out-of-position player, the hero (in position) decides. - fn mit_flop(preflop: Vec, each: f64, oop: u8, ip: u8) -> Spot { - use SeenAction::*; - use Street::*; - let (b, r) = (each * 0.7, each * 1.1); - let mut h = preflop; - h.extend([ - rec(Flop, oop, Check, None), - rec(Flop, ip, Bet, Some(b)), - rec(Flop, oop, Call, Some(b)), - rec(Turn, oop, Check, None), - rec(Turn, ip, Check, None), - rec(River, oop, Bet, Some(r)), - ]); - let mut spot = s1_river(false); - spot.hero_seat = ip; - spot.pot = 2.0 * each + 2.0 * b + r; - spot.to_call = r; - spot.hero_stack = 100.0 - each - b; - spot.villains = vec![Villain { seat: oop, stack: 100.0 - each - b - r, folded: false, profile: None }]; - spot.history = h; - spot - } - - use SeenAction::{Call as K, Raise as R}; - - #[test] - fn every_scenario_is_recognised_and_gives_ranges() { - let fold = SeenAction::Fold; - // (scenario, preflop, contribution each, oop seat, ip seat) - let faelle: Vec<(&str, Vec, f64, u8, u8)> = vec![ - ("s1", pre(4, 2.5, &[(5, fold, 0.0), (0, K, 2.5)]), 2.5, 0, 4), - ("co", pre(3, 2.5, &[(4, fold, 0.0), (5, fold, 0.0), (0, K, 2.5)]), 2.5, 0, 3), - ("sb", pre(5, 3.0, &[(0, K, 3.0)]), 3.0, 5, 0), - ("btn3", pre(4, 2.5, &[(5, fold, 0.0), (0, R, 9.0), (4, K, 9.0)]), 9.0, 0, 4), - ("co3", pre(3, 2.5, &[(4, fold, 0.0), (5, fold, 0.0), (0, R, 9.0), (3, K, 9.0)]), 9.0, 0, 3), - ]; - for (id, preflop, each, oop, ip) in faelle { - let spot = mit_flop(preflop, each, oop, ip); - let (sz, sitze) = erkennen(&spot).unwrap_or_else(|| panic!("{id} not recognised")); - assert_eq!((sz.id, sitze), (id, (oop, ip))); - let s = Grund::mit(sz, Abstraktion { flop: None, turn: None, river: river_cuts(50, 1) }); - let tab = Tabellen::neu(&s); - let r = ranges(&s, &tab, &spot).unwrap_or_else(|| panic!("{id}: no ranges")); - assert_eq!(r.hero_spieler, 1); - let Knoten::Zug { spieler, strasse, .. } = &s.baum.baum.knoten[r.knoten] else { panic!() }; - assert_eq!((*spieler, *strasse), (1, 2), "{id}"); - assert!(r.villain.iter().any(|x| *x > 0.0) && r.hero.iter().any(|x| *x > 0.0), "{id}"); - // Every other scenario's blueprint refuses the spot. - for other in ALLE.iter().filter(|z| z.id != id) { - let o = Grund::mit(other, Abstraktion { flop: None, turn: None, river: river_cuts(50, 1) }); - assert!(ranges(&o, &Tabellen::neu(&o), &spot).is_none(), "{id} must not map onto {}", other.id); - } - } - } - - #[test] - fn lines_outside_the_scenarios_give_none() { - let fold = SeenAction::Fold; - let nein: Vec<(&str, Vec, f64)> = vec![ - ("4-bet pot", pre(4, 2.5, &[(5, fold, 0.0), (0, R, 9.0), (4, R, 22.0), (0, K, 22.0)]), 22.0), - ("cold call (multiway)", pre(3, 2.5, &[(4, K, 2.5), (5, fold, 0.0), (0, K, 2.5)]), 2.5), - ("small blind calls too", pre(4, 2.5, &[(5, K, 2.5), (0, K, 2.5)]), 2.5), - ("3-bet by the small blind", pre(4, 2.5, &[(5, R, 11.0), (0, fold, 0.0), (4, K, 11.0)]), 11.0), - ("under the gun opens", pre(1, 2.5, &[(0, K, 2.5)]), 2.5), - ("middle position opens", pre(2, 2.5, &[(0, K, 2.5)]), 2.5), - ("open far too big", pre(4, 8.0, &[(5, fold, 0.0), (0, K, 8.0)]), 8.0), - ("3-bet not called", pre(4, 2.5, &[(5, fold, 0.0), (0, R, 9.0), (4, fold, 0.0)]), 9.0), - ]; - for (name, preflop, each) in nein { - let spot = mit_flop(preflop, each, 0, 4); - assert!(erkennen(&spot).is_none(), "{name} must not be a scenario"); - } - } - - /// The scenarios' ranges are the engine charts: the defender's call range against the opener - /// is wider than the 3-bet range, a cutoff opens less than the button, and the small blind - /// opens a range of its own. - #[test] - fn scenario_ranges_follow_the_charts() { - let mass = |id: &str| { - let sz = Szenario::finde(id).unwrap(); - let s = Grund::mit(sz, Abstraktion { flop: None, turn: None, river: river_cuts(50, 1) }); - let a = |p: usize| s.gewicht[p].iter().sum::() / 1326.0; - let w = (a(0), a(1)); - eprintln!("{id}: OOP {:.3}, IP {:.3}", w.0, w.1); - w - }; - let (s1, sb, co, b3, c3) = (mass("s1"), mass("sb"), mass("co"), mass("btn3"), mass("co3")); - assert!(co.1 < s1.1, "cutoff open {} vs button open {}", co.1, s1.1); - assert!(s1.1 > 0.3 && sb.1 > 0.1 && co.0 > 0.1); - for (name, three, call) in [("btn3", b3, s1), ("co3", c3, co)] { - assert!(three.0 > 0.0 && three.0 < call.0, "{name}: 3-bet range {} must be narrower than the call range {}", three.0, call.0); - assert!(three.1 > 0.0 && three.1 < call.1, "{name}: the opener's call-the-3-bet range {} is narrower than its open range {}", three.1, call.1); - } - } - - #[test] - fn pseudo_harmonic_mapping() { - let k = [(0.33, 1), (0.75, 2), (f64::INFINITY, 3)]; - assert_eq!(harmonisch(0.2, &k), Some(1)); - assert_eq!(harmonisch(0.4, &k), Some(1), "0.40 maps down: P(0.33) = 0.67"); - assert_eq!(harmonisch(0.6, &k), Some(2)); - assert_eq!(harmonisch(2.0, &[(0.33, 1), (0.75, 2)]), Some(2)); - } -} - -#[cfg(test)] -mod echt { - use super::*; - - /// With `GRUNDSTRATEGIE` set (real tables and checkpoint): the S1 river line gets ranges, and - /// the villain's river-betting range is not the chart range any more. - #[test] - #[ignore = "needs GRUNDSTRATEGIE with tables and a checkpoint"] - fn real_blueprint_ranges_for_an_s1_river() { - let spot = super::tests::s1_river_spot(); - let (h, v) = gewichtete_listen(&spot).expect("S1 river with the real blueprint"); - let (s, _) = grundstrategie().unwrap(); - let mass = |l: &[(Vec, f64)]| l.iter().map(|x| x.1).sum::(); - eprintln!("hero {} combos, mass {:.1}; villain {} combos, mass {:.1}; chart villain mass {:.1}", h.len(), mass(&h), v.len(), mass(&v), s.gewicht[0].iter().sum::()); - let mut top: Vec<_> = v.clone(); - top.sort_by(|a, b| b.1.total_cmp(&a.1)); - for (c, w) in top.iter().take(12) { - eprintln!(" {:?} {:.3}", c, w); - } - crate::engine::river_subgame::set_river_player(crate::engine::river_subgame::RiverPlayer::Grund); - let d = crate::engine::river_subgame::river_game_decision(&spot).expect("river game decides"); - eprintln!("{:?} {}", d.choice, d.reason); - } -} +//! Ranges of both players from the blueprint (plan E2e): the input the river game was missing. +//! +//! A real spot is mapped onto a scenario of the family (`szenario::ALLE`) when it is one: S1 (button +//! opened, small blind folded, big blind called), the cutoff or small blind opening against a +//! calling big blind, or a 3-bet pot (button / cutoff opens, big blind 3-bets, opener calls); always +//! heads-up from the flop on, about 100 bb deep. A 4-bet pot, a multiway pot, a limp or any other +//! opener gives `None`. The played postflop line is walked +//! through the scenario's tree, real sizes mapped onto the tree's sizes by the pseudo-harmonic rule +//! (Ganzfried/Sandholm 2013, deterministic: the nearer side under that rule). Each player's range is +//! the chart weight of every combo times the blueprint's probability of each action the player +//! took, read through the combo's class on that street's board. + +use super::abstraktion::river_ehs; +use super::mccfr::{Knoten, Tabellen}; +use super::s1::{Aktion, Grund}; +use super::szenario::{Szenario, ALLE}; +use crate::preflop::position::Position; +use crate::preflop::seat_position::seat_position; +use crate::card::Card; +use crate::game::{SeenAction, Spot, Street}; +use crate::hand::fast7; + +/// Combos with weights, hero's and villain's (S1 index of the combo list `S1::alle`). +pub struct Ranges { + pub hero: Vec, + pub villain: Vec, + /// Scenario player of the hero (0 = out of position, 1 = in position). + pub hero_spieler: usize, + /// The scenario's node of the hero's decision. + pub knoten: usize, +} + +/// Pseudo-harmonic choice between the neighbouring abstract fractions `a < x < b`: the probability +/// of `a` is `(b - x)(1 + a) / ((b - a)(1 + x))`; the side with probability >= 1/2 is taken. +pub(super) fn harmonisch(x: f64, kandidaten: &[(f64, usize)]) -> Option { + let mut k: Vec<(f64, usize)> = kandidaten.to_vec(); + k.sort_by(|p, q| p.0.total_cmp(&q.0)); + let first = k.first()?; + if x <= first.0 { + return Some(first.1); + } + for w in k.windows(2) { + let ((a, ia), (b, ib)) = (w[0], w[1]); + if x <= b { + let pa = (b - x) * (1.0 + a) / ((b - a) * (1.0 + x)); + return Some(if pa >= 0.5 { ia } else { ib }); + } + } + k.last().map(|l| l.1) +} + +/// The scenario a spot's preflop line is, with its seats `(out of position, in position)`: the +/// first raise opens (from the button, cutoff or small blind), the big blind calls or 3-bets and the +/// 3-bettor is called; everybody else folded. `None` for anything else (4-bet, multiway, limp, an +/// open from another seat, sizes off the scenarios'). +pub fn erkennen(spot: &Spot) -> Option<(&'static Szenario, (u8, u8))> { + if spot.variant != crate::variant::Variant::Nlhe || spot.seats < 3 { + return None; + } + spot.button_seat?; + let bb = spot.history.iter().find(|r| r.action == SeenAction::PostBigBlind)?.seat; + let mut opener: Option<(u8, f64)> = None; + let mut dreibet: Option = None; + let (mut called, mut opener_called) = (false, false); + for r in spot.history.iter().filter(|r| r.street == Street::Preflop) { + match r.action { + SeenAction::PostSmallBlind | SeenAction::PostBigBlind | SeenAction::PostAnte => {} + SeenAction::Fold if r.seat != bb && Some(r.seat) != opener.map(|o| o.0) => {} + SeenAction::Raise | SeenAction::Bet if opener.is_none() && r.seat != bb => opener = Some((r.seat, r.amount? / spot.big_blind)), + SeenAction::Raise | SeenAction::Bet if opener.is_some() && r.seat == bb && dreibet.is_none() && !called => { + dreibet = Some(r.amount? / spot.big_blind) + } + SeenAction::Call if opener.is_some() && r.seat == bb && dreibet.is_none() && !called => called = true, + SeenAction::Call if dreibet.is_some() && Some(r.seat) == opener.map(|o| o.0) && !opener_called => opener_called = true, + _ => return None, + } + } + let (opener_seat, to) = opener?; + if !(called || (dreibet.is_some() && opener_called)) { + return None; + } + let chart_seat = match seat_position(spot, opener_seat) { + Position::Button => crate::cfr::seat::Seat::Button, + Position::Cutoff => crate::cfr::seat::Seat::Cutoff, + Position::SmallBlind => crate::cfr::seat::Seat::SmallBlind, + _ => return None, + }; + let in_window = |x: f64, (lo, hi): (f64, f64)| x >= lo && x <= hi; + let sz = ALLE.iter().find(|z| { + z.eroeffner == chart_seat + && z.dreibet.is_some() == dreibet.is_some() + && in_window(to, z.erkennung_eroeffnung) + && dreibet.is_none_or(|d| in_window(d, z.erkennung_dreibet)) + })?; + let sitze = if sz.eroeffner_spieler() == 0 { (opener_seat, bb) } else { (bb, opener_seat) }; + Some((sz, sitze)) +} + +fn karten_maske(cards: &[Card]) -> u64 { + fast7::mask(cards) +} + +static GRUND: [std::sync::OnceLock>; ALLE.len()] = + [const { std::sync::OnceLock::new() }; ALLE.len()]; + +/// The blueprint of scenario `sz`, loaded once from `$GRUNDSTRATEGIE/abstraktion/` and +/// `$GRUNDSTRATEGIE/grundstrategie/.ckpt`; `None` without the variable or the files. +pub fn grundstrategie_fuer(sz: &Szenario) -> Option<&'static (Grund, Tabellen)> { + GRUND[sz.index()] + .get_or_init(|| { + let dir = std::path::PathBuf::from(std::env::var_os("GRUNDSTRATEGIE")?); + let s = Grund::mit(ALLE.iter().find(|z| z.id == sz.id)?, super::s1::Abstraktion::laden(&dir.join("abstraktion")).ok()?); + let mut tab = Tabellen::neu(&s); + tab.datei_lesen(&dir.join("grundstrategie").join(format!("{}.ckpt", sz.id))).then_some((s, tab)) + }) + .as_ref() +} + +/// The S1 blueprint (`grundstrategie_fuer` of S1). +pub fn grundstrategie() -> Option<&'static (Grund, Tabellen)> { + grundstrategie_fuer(Szenario::s1()) +} + +/// Weighted combo lists (hero, villain) for the river game from the blueprint, if the spot is one +/// of the scenarios and its blueprint is loaded. +pub fn gewichtete_listen(spot: &Spot) -> Option<(Vec<(Vec, f64)>, Vec<(Vec, f64)>)> { + gewichtete_listen_mit(spot, true) +} + +/// As `gewichtete_listen`, but the villain list is NOT conditioned on the hero's real cards: the +/// ranges of the public state, the input of a subgame that deals card removal itself (turn game). +pub fn gewichtete_listen_offen(spot: &Spot) -> Option<(Vec<(Vec, f64)>, Vec<(Vec, f64)>)> { + gewichtete_listen_mit(spot, false) +} + +fn gewichtete_listen_mit(spot: &Spot, blocker: bool) -> Option<(Vec<(Vec, f64)>, Vec<(Vec, f64)>)> { + let (sz, _) = erkennen(spot)?; + let (s, tab) = grundstrategie_fuer(sz)?; + let r = ranges_mit(s, tab, spot, blocker)?; + let deck = Card::parse_list("2c 3c 4c 5c 6c 7c 8c 9c Tc Jc Qc Kc Ac 2d 3d 4d 5d 6d 7d 8d 9d Td Jd Qd Kd Ad 2h 3h 4h 5h 6h 7h 8h 9h Th Jh Qh Kh Ah 2s 3s 4s 5s 6s 7s 8s 9s Ts Js Qs Ks As")?; + let karte = |bit: u64| deck.iter().copied().find(|c| fast7::bit(*c) == bit); + let liste = |w: &[f64]| -> Option, f64)>> { + s.alle + .iter() + .zip(w) + .filter(|(_, x)| **x > 1e-12) + .map(|(c, x)| Some((vec![karte(c & c.wrapping_neg())?, karte(c & (c - 1))?], *x))) + .collect() + }; + let (h, v) = (liste(&r.hero)?, liste(&r.villain)?); + (!h.is_empty() && !v.is_empty()).then_some((h, v)) +} + +/// Ranges for the hero's current decision, or `None` when the spot is not scenario `s` or the line +/// leaves its tree. +pub fn ranges(s: &Grund, tab: &Tabellen, spot: &Spot) -> Option { + ranges_mit(s, tab, spot, true) +} + +/// `ranges`; with `blocker == false` the villain's range keeps the combos that share a card with the +/// hero's real hand (the public-state range). +pub fn ranges_mit(s: &Grund, tab: &Tabellen, spot: &Spot, blocker: bool) -> Option { + let (sz, (oop, ip)) = erkennen(spot)?; + if sz.id != s.sz.id { + return None; + } + let stapel = sz.stapel; + let hero_spieler = if spot.hero_seat == oop { 0 } else if spot.hero_seat == ip { 1 } else { return None }; + let villain_seat = if hero_spieler == 0 { ip } else { oop }; + let villain = spot.villains.iter().find(|v| v.seat == villain_seat && !v.folded)?; + if spot.live_villains().count() != 1 || spot.board.len() < 3 { + return None; + } + // About 100 bb effective at the flop (S1 is computed for 100). + let eff = (spot.hero_stack.min(villain.stack) + spot.pot / 2.0) / spot.big_blind; + if !(70.0..=140.0).contains(&eff) { + return None; + } + let bbs = |x: f64| x / spot.big_blind; + let board_all = karten_maske(&spot.board); + let boards = [karten_maske(&spot.board[..3]), karten_maske(&spot.board[..spot.board.len().min(4)]), board_all]; + let ehs = if spot.board.len() == 5 { river_ehs(board_all, &s.alle) } else { Vec::new() }; + let mut w = [s.gewicht[0].clone(), s.gewicht[1].clone()]; + for (i, c) in s.alle.iter().enumerate() { + if c & board_all != 0 { + w[0][i] = 0.0; + w[1][i] = 0.0; + } + } + let hero_mask = karten_maske(&spot.hero_cards); + // Real contributions on the current street (bb) and the real pot at the street start. + let preflop_pot: f64 = { + let mut c: std::collections::HashMap = std::collections::HashMap::new(); + for r in spot.history.iter().filter(|r| r.street == Street::Preflop) { + if let Some(a) = r.amount { + let e = c.entry(r.seat).or_insert(0.0); + *e = if r.action == SeenAction::PostAnte { *e + a } else { e.max(a) }; + } + } + c.values().map(|x| bbs(*x)).sum() + }; + let mut real_pot = preflop_pot; + let mut k = s.baum.baum.wurzel; + let streets = [Street::Flop, Street::Turn, Street::River]; + for (si, st) in streets.iter().enumerate() { + if si >= spot.board.len() - 2 { + break; + } + let mut c_real = [0.0f64; 2]; + for r in spot.history.iter().filter(|r| r.street == *st) { + let p = if r.seat == oop { 0 } else if r.seat == ip { 1 } else { continue }; + let Knoten::Zug { spieler, strasse, kinder } = &s.baum.baum.knoten[k] else { return None }; + if *spieler != p || *strasse != si { + return None; + } + let pot_real = real_pot + c_real[0] + c_real[1]; + let child = match r.action { + SeenAction::Check => kinder.iter().copied().find(|c| s.baum.aktion[*c] == Some(Aktion::Check))?, + SeenAction::Call => kinder.iter().copied().find(|c| s.baum.aktion[*c] == Some(Aktion::Call))?, + SeenAction::Fold => return None, + SeenAction::Bet | SeenAction::Raise | SeenAction::AllIn => { + let to = bbs(r.amount?); + let all_in = r.action == SeenAction::AllIn; + let c_s1 = s.baum.beitrag[k]; + let pot_s1 = c_s1[0] + c_s1[1]; + let kand: Vec<(f64, usize)> = kinder + .iter() + .filter_map(|c| match s.baum.aktion[*c] { + Some(Aktion::Bet(t)) | Some(Aktion::Raise(t)) => Some(((t - c_s1[p]) / pot_s1, *c, t)), + _ => None, + }) + .map(|(f, c, t)| if all_in && t >= stapel { (f64::INFINITY, c) } else { (f, c) }) + .collect(); + if kand.is_empty() { + // Call-equivalent all-in against a bet the tree cannot raise any more. + kinder.iter().copied().find(|c| s.baum.aktion[*c] == Some(Aktion::Call))? + } else if all_in { + kand.iter().find(|x| x.0.is_infinite()).map(|x| x.1).or_else(|| harmonisch((to - c_real[p]) / pot_real, &kand))? + } else { + let kand: Vec<(f64, usize)> = kand.into_iter().filter(|x| x.0.is_finite()).collect(); + harmonisch((to - c_real[p]) / pot_real, &kand)? + } + } + _ => continue, + }; + // The actor's range: times the blueprint's probability of this action per combo class. + let a = kinder.iter().position(|c| *c == child)?; + let n = kinder.len(); + let board = boards[si]; + for (i, c) in s.alle.iter().enumerate() { + if w[p][i] > 0.0 { + let cls = s.klasse_von(*c, board, si, &ehs); + w[p][i] *= tab.durchschnitt(k, cls, n)[a]; + } + } + if let Some(a) = r.amount { + c_real[p] = bbs(a); + } + if r.action == SeenAction::Call { + c_real[p] = c_real[1 - p]; + } + k = child; + } + real_pot += c_real[0] + c_real[1]; + } + let Knoten::Zug { spieler, strasse, .. } = &s.baum.baum.knoten[k] else { return None }; + if *spieler != hero_spieler || *strasse + 3 != spot.board.len() { + return None; + } + let mut villain_w = w[1 - hero_spieler].clone(); + for (i, c) in s.alle.iter().enumerate() { + if blocker && c & hero_mask != 0 { + villain_w[i] = 0.0; + } + } + Some(Ranges { hero: w[hero_spieler].clone(), villain: villain_w, hero_spieler, knoten: k }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::blueprint::abstraktion::river_cuts; + use crate::blueprint::s1::{Abstraktion, S1}; + use crate::game::{ActionKind, ActionRecord, Villain}; + use crate::variant::Variant; + + fn rec(street: Street, seat: u8, action: SeenAction, amount: Option) -> ActionRecord { + ActionRecord { street, seat, action, amount } + } + + /// Six-max: button 4 opens 2.5, small blind 5 folds, big blind 0 calls; flop check, bet 1.8, + /// call; turn check-check; river big blind bets 6, the button (hero) decides. + pub(super) fn s1_river_spot() -> Spot { + s1_river(false) + } + + fn s1_river(three_bet: bool) -> Spot { + use SeenAction::*; + use Street::*; + let mut h = vec![ + rec(Preflop, 5, PostSmallBlind, Some(0.5)), + rec(Preflop, 0, PostBigBlind, Some(1.0)), + rec(Preflop, 1, Fold, None), + rec(Preflop, 2, Fold, None), + rec(Preflop, 3, Fold, None), + rec(Preflop, 4, Raise, Some(2.5)), + rec(Preflop, 5, Fold, None), + ]; + if three_bet { + h.push(rec(Preflop, 0, Raise, Some(9.0))); + h.push(rec(Preflop, 4, Call, Some(9.0))); + } else { + h.push(rec(Preflop, 0, Call, Some(2.5))); + } + h.extend([ + rec(Flop, 0, Check, None), + rec(Flop, 4, Bet, Some(1.8)), + rec(Flop, 0, Call, Some(1.8)), + rec(Turn, 0, Check, None), + rec(Turn, 4, Check, None), + rec(River, 0, Bet, Some(6.0)), + ]); + Spot { + variant: Variant::Nlhe, + big_blind: 1.0, + seats: 6, + hero_seat: 4, + button_seat: Some(4), + hero_cards: Card::parse_list("Ac Qd").unwrap(), + board: Card::parse_list("Ah 7d 2c Ks 9h").unwrap(), + street: Street::River, + pot: 15.1, + to_call: 6.0, + hero_stack: 93.7, + min_raise_to: Some(12.0), + max_raise_to: Some(93.7), + legal: vec![ActionKind::Fold, ActionKind::Call, ActionKind::Raise], + allowed_sizes: None, + villains: vec![Villain { seat: 0, stack: 89.7, folded: false, profile: None }], + seed: 1, + history: h, + } + } + + #[test] + fn an_s1_line_gives_ranges_at_the_heros_river_node() { + let s = S1::neu(Abstraktion { flop: None, turn: None, river: river_cuts(50, 1) }); + let tab = Tabellen::neu(&s); + let r = ranges(&s, &tab, &s1_river(false)).expect("the line is S1"); + assert_eq!(r.hero_spieler, 1); + let Knoten::Zug { spieler, strasse, .. } = &s.baum.baum.knoten[r.knoten] else { panic!() }; + assert_eq!((*spieler, *strasse), (1, 2)); + assert!(matches!(s.baum.aktion[r.knoten], Some(Aktion::Bet(_))), "river bet mapped to a tree bet"); + let board = karten_maske(&Card::parse_list("Ah 7d 2c Ks 9h").unwrap()); + let hero = karten_maske(&Card::parse_list("Ac Qd").unwrap()); + for (i, c) in s.alle.iter().enumerate() { + if c & board != 0 { + assert_eq!(r.hero[i], 0.0); + assert_eq!(r.villain[i], 0.0); + } + if c & hero != 0 { + assert_eq!(r.villain[i], 0.0, "the villain cannot hold the hero's cards"); + } + } + assert!(r.villain.iter().any(|x| *x > 0.0) && r.hero.iter().any(|x| *x > 0.0)); + assert!(ranges(&s, &tab, &s1_river(true)).is_none(), "a 3-bet pot is not S1"); + } + + /// 6-max seats: button 4, small blind 5, big blind 0, UTG 1, MP 2, cutoff 3. + fn pre(opener: u8, to: f64, rest: &[(u8, SeenAction, f64)]) -> Vec { + use SeenAction::*; + let mut h = vec![rec(Street::Preflop, 5, PostSmallBlind, Some(0.5)), rec(Street::Preflop, 0, PostBigBlind, Some(1.0))]; + for seat in 1..opener.min(6) { + h.push(rec(Street::Preflop, seat, Fold, None)); + } + h.push(rec(Street::Preflop, opener, Raise, Some(to))); + for (seat, a, amount) in rest { + h.push(rec(Street::Preflop, *seat, *a, (*a != Fold).then_some(*amount))); + } + h + } + + /// River spot of a preflop line: flop check / bet / call, turn check-check, river bet of the + /// out-of-position player, the hero (in position) decides. + fn mit_flop(preflop: Vec, each: f64, oop: u8, ip: u8) -> Spot { + use SeenAction::*; + use Street::*; + let (b, r) = (each * 0.7, each * 1.1); + let mut h = preflop; + h.extend([ + rec(Flop, oop, Check, None), + rec(Flop, ip, Bet, Some(b)), + rec(Flop, oop, Call, Some(b)), + rec(Turn, oop, Check, None), + rec(Turn, ip, Check, None), + rec(River, oop, Bet, Some(r)), + ]); + let mut spot = s1_river(false); + spot.hero_seat = ip; + spot.pot = 2.0 * each + 2.0 * b + r; + spot.to_call = r; + spot.hero_stack = 100.0 - each - b; + spot.villains = vec![Villain { seat: oop, stack: 100.0 - each - b - r, folded: false, profile: None }]; + spot.history = h; + spot + } + + use SeenAction::{Call as K, Raise as R}; + + #[test] + fn every_scenario_is_recognised_and_gives_ranges() { + let fold = SeenAction::Fold; + // (scenario, preflop, contribution each, oop seat, ip seat) + let faelle: Vec<(&str, Vec, f64, u8, u8)> = vec![ + ("s1", pre(4, 2.5, &[(5, fold, 0.0), (0, K, 2.5)]), 2.5, 0, 4), + ("co", pre(3, 2.5, &[(4, fold, 0.0), (5, fold, 0.0), (0, K, 2.5)]), 2.5, 0, 3), + ("sb", pre(5, 3.0, &[(0, K, 3.0)]), 3.0, 5, 0), + ("btn3", pre(4, 2.5, &[(5, fold, 0.0), (0, R, 9.0), (4, K, 9.0)]), 9.0, 0, 4), + ("co3", pre(3, 2.5, &[(4, fold, 0.0), (5, fold, 0.0), (0, R, 9.0), (3, K, 9.0)]), 9.0, 0, 3), + ]; + for (id, preflop, each, oop, ip) in faelle { + let spot = mit_flop(preflop, each, oop, ip); + let (sz, sitze) = erkennen(&spot).unwrap_or_else(|| panic!("{id} not recognised")); + assert_eq!((sz.id, sitze), (id, (oop, ip))); + let s = Grund::mit(sz, Abstraktion { flop: None, turn: None, river: river_cuts(50, 1) }); + let tab = Tabellen::neu(&s); + let r = ranges(&s, &tab, &spot).unwrap_or_else(|| panic!("{id}: no ranges")); + assert_eq!(r.hero_spieler, 1); + let Knoten::Zug { spieler, strasse, .. } = &s.baum.baum.knoten[r.knoten] else { panic!() }; + assert_eq!((*spieler, *strasse), (1, 2), "{id}"); + assert!(r.villain.iter().any(|x| *x > 0.0) && r.hero.iter().any(|x| *x > 0.0), "{id}"); + // Every other scenario's blueprint refuses the spot. + for other in ALLE.iter().filter(|z| z.id != id) { + let o = Grund::mit(other, Abstraktion { flop: None, turn: None, river: river_cuts(50, 1) }); + assert!(ranges(&o, &Tabellen::neu(&o), &spot).is_none(), "{id} must not map onto {}", other.id); + } + } + } + + #[test] + fn lines_outside_the_scenarios_give_none() { + let fold = SeenAction::Fold; + let nein: Vec<(&str, Vec, f64)> = vec![ + ("4-bet pot", pre(4, 2.5, &[(5, fold, 0.0), (0, R, 9.0), (4, R, 22.0), (0, K, 22.0)]), 22.0), + ("cold call (multiway)", pre(3, 2.5, &[(4, K, 2.5), (5, fold, 0.0), (0, K, 2.5)]), 2.5), + ("small blind calls too", pre(4, 2.5, &[(5, K, 2.5), (0, K, 2.5)]), 2.5), + ("3-bet by the small blind", pre(4, 2.5, &[(5, R, 11.0), (0, fold, 0.0), (4, K, 11.0)]), 11.0), + ("under the gun opens", pre(1, 2.5, &[(0, K, 2.5)]), 2.5), + ("middle position opens", pre(2, 2.5, &[(0, K, 2.5)]), 2.5), + ("open far too big", pre(4, 8.0, &[(5, fold, 0.0), (0, K, 8.0)]), 8.0), + ("3-bet not called", pre(4, 2.5, &[(5, fold, 0.0), (0, R, 9.0), (4, fold, 0.0)]), 9.0), + ]; + for (name, preflop, each) in nein { + let spot = mit_flop(preflop, each, 0, 4); + assert!(erkennen(&spot).is_none(), "{name} must not be a scenario"); + } + } + + /// The scenarios' ranges are the engine charts: the defender's call range against the opener + /// is wider than the 3-bet range, a cutoff opens less than the button, and the small blind + /// opens a range of its own. + #[test] + fn scenario_ranges_follow_the_charts() { + let mass = |id: &str| { + let sz = Szenario::finde(id).unwrap(); + let s = Grund::mit(sz, Abstraktion { flop: None, turn: None, river: river_cuts(50, 1) }); + let a = |p: usize| s.gewicht[p].iter().sum::() / 1326.0; + let w = (a(0), a(1)); + eprintln!("{id}: OOP {:.3}, IP {:.3}", w.0, w.1); + w + }; + let (s1, sb, co, b3, c3) = (mass("s1"), mass("sb"), mass("co"), mass("btn3"), mass("co3")); + assert!(co.1 < s1.1, "cutoff open {} vs button open {}", co.1, s1.1); + assert!(s1.1 > 0.3 && sb.1 > 0.1 && co.0 > 0.1); + for (name, three, call) in [("btn3", b3, s1), ("co3", c3, co)] { + assert!(three.0 > 0.0 && three.0 < call.0, "{name}: 3-bet range {} must be narrower than the call range {}", three.0, call.0); + assert!(three.1 > 0.0 && three.1 < call.1, "{name}: the opener's call-the-3-bet range {} is narrower than its open range {}", three.1, call.1); + } + } + + #[test] + fn pseudo_harmonic_mapping() { + let k = [(0.33, 1), (0.75, 2), (f64::INFINITY, 3)]; + assert_eq!(harmonisch(0.2, &k), Some(1)); + assert_eq!(harmonisch(0.4, &k), Some(1), "0.40 maps down: P(0.33) = 0.67"); + assert_eq!(harmonisch(0.6, &k), Some(2)); + assert_eq!(harmonisch(2.0, &[(0.33, 1), (0.75, 2)]), Some(2)); + } +} + +#[cfg(test)] +mod echt { + use super::*; + + /// With `GRUNDSTRATEGIE` set (real tables and checkpoint): the S1 river line gets ranges, and + /// the villain's river-betting range is not the chart range any more. + #[test] + #[ignore = "needs GRUNDSTRATEGIE with tables and a checkpoint"] + fn real_blueprint_ranges_for_an_s1_river() { + let spot = super::tests::s1_river_spot(); + let (h, v) = gewichtete_listen(&spot).expect("S1 river with the real blueprint"); + let (s, _) = grundstrategie().unwrap(); + let mass = |l: &[(Vec, f64)]| l.iter().map(|x| x.1).sum::(); + eprintln!("hero {} combos, mass {:.1}; villain {} combos, mass {:.1}; chart villain mass {:.1}", h.len(), mass(&h), v.len(), mass(&v), s.gewicht[0].iter().sum::()); + let mut top: Vec<_> = v.clone(); + top.sort_by(|a, b| b.1.total_cmp(&a.1)); + for (c, w) in top.iter().take(12) { + eprintln!(" {:?} {:.3}", c, w); + } + crate::engine::river_subgame::set_river_player(crate::engine::river_subgame::RiverPlayer::Grund); + let d = crate::engine::river_subgame::river_game_decision(&spot).expect("river game decides"); + eprintln!("{:?} {}", d.choice, d.reason); + } +} diff --git a/src/cfr/mod.rs b/src/cfr/mod.rs index ea06568f..dc85a6af 100644 --- a/src/cfr/mod.rs +++ b/src/cfr/mod.rs @@ -111,6 +111,7 @@ pub mod tree3; pub mod tree; pub mod turn; pub mod turn_river; +pub mod turn_river_game; pub mod value_walk; pub mod wake_range; pub mod walk3; diff --git a/src/cfr/river_game.rs b/src/cfr/river_game.rs index 73bc550f..763df427 100644 --- a/src/cfr/river_game.rs +++ b/src/cfr/river_game.rs @@ -88,7 +88,7 @@ fn showdown(n: usize, q: f64) -> Payoff { } /// Add `x` to `sizes` (sorted), dropping abstract sizes within `SAME_SIZE` of it. -fn with_exact(mut sizes: Vec, x: f64) -> Vec { +pub(crate) fn with_exact(mut sizes: Vec, x: f64) -> Vec { sizes.retain(|s| (s - x).abs() > SAME_SIZE * s.max(x)); sizes.push(x); sizes.sort_by(f64::total_cmp); @@ -96,7 +96,7 @@ fn with_exact(mut sizes: Vec, x: f64) -> Vec { } /// Distinct sizes in `(lo, cap]`, all-in (`cap`) always last; near-duplicates of all-in dropped. -fn sized(raw: impl Iterator, lo: f64, cap: f64) -> Vec { +pub(crate) fn sized(raw: impl Iterator, lo: f64, cap: f64) -> Vec { let mut out: Vec = raw.filter(|s| s.is_finite() && *s > lo && *s < cap * (1.0 - SAME_SIZE)).collect(); out.sort_by(f64::total_cmp); out.dedup_by(|a, b| (*a - *b).abs() <= SAME_SIZE * a.max(*b)); diff --git a/src/cfr/turn_river_game.rs b/src/cfr/turn_river_game.rs new file mode 100644 index 00000000..ad29a97b --- /dev/null +++ b/src/cfr/turn_river_game.rs @@ -0,0 +1,664 @@ +//! The heads-up TURN + RIVER as one game over real hands (plan E3, layer 2 of the target engine). +//! +//! `cfr::turn_river` (stage B) solves one turn betting round and values the river with an +//! equilibrium *number*, over strength buckets. This module keeps the river inside the game: +//! +//! - **Hands** are real combos with a weight each (both ranges come from the blueprint, see +//! `blueprint::ranges`). The information set of a player is (combo, public line) on the turn and +//! (combo, river card, public line) on the river, so hands change strength with the river card +//! exactly. Card removal is exact: a pair of overlapping combos is never dealt, and a river card +//! a combo holds is not dealt to it. +//! - **Tree:** turn betting (menu `TrBets::turn`), then a chance node over the river cards, then +//! river betting (menu `TrBets::river`). The player `first` acts first on both streets. The +//! observed turn actions (`forced`) are inside the tree with their exact sizes, so hero's real +//! decision is a node (`TrGame::at`). +//! - **Payoffs** are hero's (player 0) net chips from the start of the turn, each player counted +//! as having put `pot / 2` in, as in `river_game`. Zero-sum. +//! - **Solver:** CFR+ (regrets floored at zero, alternating updates, linearly weighted average), +//! full width over the hands, vectorised like `cfr::iterate`. A showdown is evaluated in +//! `O(hands)` per river card with prefix sums and card-removal inclusion-exclusion, not `O(hands^2)`. +//! - **Exploitability:** `TrSolver::exploitability` is the exact best response of each player in +//! this game against the average strategy (sum of both gains, chips per deal). +//! +//! # Named approximations +//! +//! `TrSolver::new` can be given a subset of the river cards (`river_cards`): then each sampled card +//! stands for `1/K` of all cards (the deal weight is rescaled by `48 / (44 K)`, exact for all 48). +//! The caller can also prune the ranges. Both are chosen by the bridge in `engine::turn_game`. + +use super::river_game::{sized, with_exact, Act}; +use crate::hand::fast7; + +/// Bet menu of one street. +#[derive(Clone, Debug, PartialEq)] +pub struct Menu { + /// Opening bets as fractions of the pot (all-in is always added). + pub fracs: Vec, + /// Raises to `mult` x the bet faced (all-in is always added). + pub raise_mult: Vec, + /// Raises allowed after the opening bet. + pub max_raises: usize, + /// Whether the all-in is a bet / raise size of its own (an observed all-in is always in the tree). + pub allin: bool, +} + +/// The betting abstraction of the two streets. +#[derive(Clone, Debug, PartialEq)] +pub struct TrBets { + /// Pot at the start of the turn. + pub pot: f64, + /// Effective stack at the start of the turn. + pub stack: f64, + /// Who acts first on both streets: 0 = hero, 1 = villain. + pub first: usize, + pub turn: Menu, + pub river: Menu, +} + +impl TrBets { + /// Turn: 50 %, 100 % pot, all-in, one raise (3x); river: 70 % pot, all-in, one raise (3x). + pub fn standard(pot: f64, stack: f64, first: usize) -> TrBets { + TrBets { + pot, + stack, + first, + turn: Menu { fracs: vec![0.5, 1.0], raise_mult: vec![3.0], max_raises: 1, allin: true }, + river: Menu { fracs: vec![0.7], raise_mult: vec![3.0], max_raises: 1, allin: true }, + } + } +} + +#[derive(Clone, Debug, PartialEq)] +pub enum TNode { + /// `street`: 0 = turn, 1 = river. + Dec { player: usize, street: u8, kids: Vec }, + /// `folder` loses `amt` (its contribution counting `pot / 2` of the start pot), the other wins it. + Fold { folder: usize, amt: f64 }, + /// Showdown on the river card: the better hand wins `half`, the worse loses it. + Show { half: f64 }, + /// The river card is dealt; `child` is the river betting (or a showdown). + Chance { child: usize }, +} + +/// A built turn+river game. +pub struct TrGame { + pub nodes: Vec, + /// `acts[node][k]` = the action of child `k` of decision `node`. + pub acts: Vec>, + pub root: usize, + /// The node reached by the forced (observed) turn line. + pub at: Option, +} + +struct Builder<'a> { + b: &'a TrBets, + forced: &'a [Act], + nodes: Vec, + acts: Vec>, + at: Option, +} + +impl Builder<'_> { + fn push(&mut self, node: TNode, acts: Vec) -> usize { + self.nodes.push(node); + self.acts.push(acts); + self.nodes.len() - 1 + } + + /// After the turn closes with both players matched at `total` each: the river card, then the + /// river betting; an all-in goes straight to the showdown. + fn to_river(&mut self, total: f64) -> usize { + let b = self.b; + let child = if total >= b.stack - 1e-9 { + self.push(TNode::Show { half: b.pot / 2.0 + total }, Vec::new()) + } else { + self.street(1, b.first, total, [0.0, 0.0], false, 0, None) + }; + self.push(TNode::Chance { child }, Vec::new()) + } + + /// `base`: chips each player put in on earlier streets; `c`: street contributions. + #[allow(clippy::too_many_arguments)] + fn street(&mut self, street: u8, to_act: usize, base: f64, c: [f64; 2], checked: bool, raises: usize, depth: Option) -> usize { + let b = self.b; + let menu = if street == 0 { &b.turn } else { &b.river }; + let other = 1 - to_act; + let facing = c[other] > c[to_act]; + let cap = b.stack - base; + let pot_now = b.pot + 2.0 * base + c[0] + c[1]; + let forced = if street == 0 { depth.and_then(|d| self.forced.get(d).copied()) } else { None }; + let mut acts: Vec = if facing { + let mut a = vec![Act::Fold, Act::Call]; + if raises < menu.max_raises && c[other] < cap { + let mut sizes = sized(menu.raise_mult.iter().map(|m| m * c[other]), c[other], cap); + if !menu.allin { + sizes.retain(|s| *s < cap - 1e-9); + } + if let Some(Act::Raise(x)) = forced { + sizes = with_exact(sizes, x.min(cap)); + } + a.extend(sizes.into_iter().map(Act::Raise)); + } else if let Some(Act::Raise(x)) = forced { + a.push(Act::Raise(x.min(cap))); + } + a + } else { + let mut sizes = sized(menu.fracs.iter().map(|f| f * pot_now), 0.0, cap); + if !menu.allin { + sizes.retain(|s| *s < cap - 1e-9); + } + if let Some(Act::Bet(x)) = forced { + sizes = with_exact(sizes, x.min(cap)); + } + std::iter::once(Act::Check).chain(sizes.into_iter().map(Act::Bet)).collect() + }; + acts.dedup(); + let follow = forced.and_then(|f| { + acts.iter().position(|a| match (a, f) { + (Act::Bet(x), Act::Bet(y)) | (Act::Raise(x), Act::Raise(y)) => (x - y.min(cap)).abs() < 1e-9, + _ => *a == f, + }) + }); + if street == 0 && depth == Some(self.forced.len()) { + self.at = Some(self.nodes.len()); + } + let me = self.push(TNode::Dec { player: to_act, street, kids: Vec::new() }, acts.clone()); + let mut kids = Vec::with_capacity(acts.len()); + for (k, a) in acts.iter().enumerate() { + let next_depth = match (depth, follow) { + (Some(d), Some(f)) if f == k => Some(d + 1), + _ => None, + }; + let kid = match *a { + Act::Fold => self.push(TNode::Fold { folder: to_act, amt: b.pot / 2.0 + base + c[to_act] }, Vec::new()), + Act::Check if checked || to_act != b.first => { + if street == 0 { + self.to_river(base) + } else { + self.push(TNode::Show { half: b.pot / 2.0 + base }, Vec::new()) + } + } + Act::Check => self.street(street, other, base, c, true, raises, next_depth), + Act::Call => { + let total = base + c[other]; + if street == 0 { + self.to_river(total) + } else { + self.push(TNode::Show { half: b.pot / 2.0 + total }, Vec::new()) + } + } + Act::Bet(to) | Act::Raise(to) => { + let mut nc = c; + nc[to_act] = to; + let r = if matches!(a, Act::Raise(_)) { raises + 1 } else { raises }; + self.street(street, other, base, nc, false, r, next_depth) + } + }; + kids.push(kid); + } + if let TNode::Dec { kids: k, .. } = &mut self.nodes[me] { + *k = kids; + } + me + } +} + +/// Build the game for the observed turn line `forced` (from the start of the turn). +pub fn build(bets: &TrBets, forced: &[Act]) -> TrGame { + let mut b = Builder { b: bets, forced, nodes: Vec::new(), acts: Vec::new(), at: None }; + let root = b.street(0, bets.first.min(1), 0.0, [0.0, 0.0], false, 0, Some(0)); + TrGame { nodes: b.nodes, acts: b.acts, root, at: b.at } +} + +const NO_CARD: usize = usize::MAX; +/// Hands of one player: card masks (`fast7` layout) and range weights. +#[derive(Clone, Debug)] +pub struct Hands { + pub masks: Vec, + pub weights: Vec, +} + +struct RiverCard { + bit: u64, + /// 1.0 if the combo does not hold the card, else 0.0. + free: [Vec; 2], + /// `fast7` score of each combo with board and this card. + rank: [Vec; 2], + /// Combo indices by ascending score. + order: [Vec; 2], +} + +fn pos(mask: u64) -> (usize, usize) { + (mask.trailing_zeros() as usize, (mask & (mask - 1)).trailing_zeros() as usize) +} + +/// The solver state; see the module doc. +pub struct TrSolver { + pub game: std::sync::Arc, + n: [usize; 2], + cards: [Vec<(usize, usize)>; 2], + #[allow(dead_code)] + masks: [Vec; 2], + same: [Vec>; 2], + weights: [Vec; 2], + rc: Vec, + /// Deal weight of one sampled river card. + wr: f64, + regret: Vec>, + sums: Vec>, + pub iterations: u32, +} + +/// The average strategy: per decision node, per copy (1 on the turn, one per river card on the +/// river), per hand, the action probabilities. +#[derive(Clone, Debug)] +pub struct TrStrategy { + probs: Vec>, + actions: Vec, + n: [usize; 2], + players: Vec, +} + +impl TrStrategy { + /// Action probabilities of `hand` at `node` (`card` = river card index; ignored on the turn). + pub fn row(&self, node: usize, card: usize, hand: usize) -> &[f64] { + let a = self.actions[node]; + let n = self.n[self.players[node]]; + let copies = self.probs[node].len() / (n * a).max(1); + let c = if copies == 1 { 0 } else { card }; + let off = (c * n + hand) * a; + &self.probs[node][off..off + a] + } +} + +/// Best-response result: gain of each player and their sum, in chips per deal. +#[derive(Clone, Copy, Debug)] +pub struct Exploit { + pub gain: [f64; 2], + pub total: f64, +} + +fn matched(regret: &[f64], a: usize, out: &mut [f64]) { + for (r, o) in regret.chunks(a).zip(out.chunks_mut(a)) { + let s: f64 = r.iter().sum(); + if s > 0.0 { + for (x, y) in r.iter().zip(o.iter_mut()) { + *y = x / s; + } + } else { + o.iter_mut().for_each(|y| *y = 1.0 / a as f64); + } + } +} + +impl TrSolver { + /// `board`: the four turn cards as a mask; `river`: the river cards to enumerate (`None` = all 48 not + /// on the board, `Some(k)` = `k` of them, evenly strided). Combos must not touch the board. + pub fn new(game: TrGame, hands: [Hands; 2], board: u64, river: Option) -> TrSolver { + let mut all: Vec = (0..4u32) + .flat_map(|s| (0..13u32).map(move |r| 1u64 << (16 * s + r))) + .filter(|b| b & board == 0) + .collect(); + let candidates = all.len(); + if let Some(k) = river { + let k = k.clamp(1, candidates); + all = (0..k).map(|i| all[(((i as f64 + 0.5) * candidates as f64 / k as f64) as usize).min(candidates - 1)]).collect(); + } + // Every valid (pair, card) triple has weight 1/44 when all 48 are enumerated. + let wr = candidates as f64 / (all.len() as f64 * (candidates as f64 - 4.0)); + TrSolver::with_cards(game, hands, board, all, wr) + } + + /// As `new`, with explicit river cards (single-bit masks) and the deal weight of each. + pub fn with_cards(game: TrGame, hands: [Hands; 2], board: u64, all: Vec, wr: f64) -> TrSolver { + let n = [hands[0].masks.len(), hands[1].masks.len()]; + let cards = [hands[0].masks.iter().map(|m| pos(*m)).collect::>(), hands[1].masks.iter().map(|m| pos(*m)).collect::>()]; + let same = [0, 1].map(|p| { + hands[p].masks.iter().map(|m| hands[1 - p].masks.iter().position(|o| o == m)).collect::>() + }); + let total = |p: usize| hands[p].weights.iter().sum::().max(1e-300); + let weights = [0, 1].map(|p| hands[p].weights.iter().map(|w| w / total(p)).collect::>()); + let k = all.len(); + let rc: Vec = all + .iter() + .map(|bit| { + let free = [0, 1].map(|p| hands[p].masks.iter().map(|m| if m & bit == 0 { 1.0 } else { 0.0 }).collect::>()); + let rank = [0, 1].map(|p| hands[p].masks.iter().map(|m| fast7::score(m | board | bit)).collect::>()); + let order = [0, 1].map(|p| { + let mut o: Vec = (0..n[p] as u32).collect(); + o.sort_by_key(|i| rank[p][*i as usize]); + o + }); + RiverCard { bit: *bit, free, rank, order } + }) + .collect(); + let mut regret = Vec::with_capacity(game.nodes.len()); + for node in &game.nodes { + regret.push(match node { + TNode::Dec { player, street, kids } => { + let copies = if *street == 0 { 1 } else { k }; + vec![0.0; copies * n[*player] * kids.len()] + } + _ => Vec::new(), + }); + } + let sums = regret.clone(); + let masks = [hands[0].masks.clone(), hands[1].masks.clone()]; + TrSolver { game: std::sync::Arc::new(game), n, cards, masks, same, weights, rc, wr, regret, sums, iterations: 0 } + } + + pub fn hands(&self, player: usize) -> usize { + self.n[player] + } + + pub fn river_cards(&self) -> usize { + self.rc.len() + } + + /// One CFR+ iteration (both players, alternating). + pub fn iterate(&mut self) { + self.iterations += 1; + for p in 0..2 { + let own = vec![1.0; self.n[p]]; + let opp = self.weights[1 - p].clone(); + let weight = self.iterations as f64; + self.walk(self.game.root, p, &own, &opp, NO_CARD, weight); + } + } + + pub fn run(&mut self, iterations: u32) { + for _ in 0..iterations { + self.iterate(); + } + } + + /// `out[i]` = sum of `opp[j]` over the opponent combos `j` that share no card with own combo `i`. + fn disjoint(&self, p: usize, opp: &[f64]) -> Vec { + let mut c = [0.0f64; 64]; + let mut t = 0.0; + for (j, w) in opp.iter().enumerate() { + let (a, b) = self.cards[1 - p][j]; + c[a] += w; + c[b] += w; + t += w; + } + (0..self.n[p]) + .map(|i| { + let (a, b) = self.cards[p][i]; + t - c[a] - c[b] + self.same[p][i].map_or(0.0, |j| opp[j]) + }) + .collect() + } + + /// Showdown values of player `p`'s combos on river card `r`: `half` x (win mass - lose mass). + fn show(&self, p: usize, r: usize, opp: &[f64], half: f64) -> Vec { + let rc = &self.rc[r]; + let (n_own, n_opp) = (self.n[p], self.n[1 - p]); + let (own_o, own_r) = (&rc.order[p], &rc.rank[p]); + let (opp_o, opp_r) = (&rc.order[1 - p], &rc.rank[1 - p]); + let mut c = [0.0f64; 64]; + let mut t = 0.0; + for (j, w) in opp.iter().enumerate() { + let (a, b) = self.cards[1 - p][j]; + c[a] += w; + c[b] += w; + t += w; + } + let (mut less_t, mut less_c) = (0.0f64, [0.0f64; 64]); + let mut eq_c = [0.0f64; 64]; + let mut ptr = 0; + let mut out = vec![0.0; n_own]; + let mut k = 0; + while k < n_own { + let s = own_r[own_o[k] as usize]; + let mut e = k; + while e < n_own && own_r[own_o[e] as usize] == s { + e += 1; + } + while ptr < n_opp && opp_r[opp_o[ptr] as usize] < s { + let j = opp_o[ptr] as usize; + let (a, b) = self.cards[1 - p][j]; + less_t += opp[j]; + less_c[a] += opp[j]; + less_c[b] += opp[j]; + ptr += 1; + } + let (mut eq_t, mut q) = (0.0f64, ptr); + while q < n_opp && opp_r[opp_o[q] as usize] == s { + let j = opp_o[q] as usize; + let (a, b) = self.cards[1 - p][j]; + eq_t += opp[j]; + eq_c[a] += opp[j]; + eq_c[b] += opp[j]; + q += 1; + } + for idx in k..e { + let i = own_o[idx] as usize; + let (a, b) = self.cards[p][i]; + let sm = self.same[p][i].map_or(0.0, |j| opp[j]); + let disj = t - c[a] - c[b] + sm; + let less = less_t - less_c[a] - less_c[b]; + let eq = eq_t - eq_c[a] - eq_c[b] + sm; + out[i] = half * (2.0 * less + eq - disj); + } + for &j in &opp_o[ptr..q] { + let (a, b) = self.cards[1 - p][j as usize]; + eq_c[a] = 0.0; + eq_c[b] = 0.0; + } + k = e; + } + out + } + + fn mask_by_card(&self, v: &[f64], p: usize, r: usize) -> Vec { + v.iter().zip(&self.rc[r].free[p]).map(|(x, f)| x * f).collect() + } + + /// Counterfactual values of the traversing player `p`, one per own combo. + fn walk(&mut self, node: usize, p: usize, own: &[f64], opp: &[f64], r: usize, weight: f64) -> Vec { + let game = std::sync::Arc::clone(&self.game); + match game.nodes[node] { + TNode::Fold { folder, amt } => { + let v = if folder == p { -amt } else { amt }; + self.disjoint(p, opp).into_iter().map(|x| x * v).collect() + } + TNode::Show { half } => self.show(p, r, opp, half), + TNode::Chance { child } => { + let mut total = vec![0.0; self.n[p]]; + for ri in 0..self.rc.len() { + let o = self.mask_by_card(own, p, ri); + let q = self.mask_by_card(opp, 1 - p, ri); + let v = self.walk(child, p, &o, &q, ri, weight); + let free = &self.rc[ri].free[p]; + for i in 0..total.len() { + total[i] += self.wr * v[i] * free[i]; + } + } + total + } + TNode::Dec { player, street, ref kids } => { + let a = kids.len(); + let n = self.n[player]; + let off = if street == 0 { 0 } else { r * n * a }; + let mut sigma = vec![0.0; n * a]; + matched(&self.regret[node][off..off + n * a], a, &mut sigma); + if player == p { + let values: Vec> = kids + .iter() + .enumerate() + .map(|(k, kid)| { + let reach: Vec = (0..n).map(|i| own[i] * sigma[i * a + k]).collect(); + self.walk(*kid, p, &reach, opp, r, weight) + }) + .collect(); + let mut node_value = vec![0.0; n]; + for i in 0..n { + node_value[i] = (0..a).map(|k| sigma[i * a + k] * values[k][i]).sum(); + for k in 0..a { + let reg = &mut self.regret[node][off + i * a + k]; + *reg = (*reg + values[k][i] - node_value[i]).max(0.0); + self.sums[node][off + i * a + k] += weight * own[i] * sigma[i * a + k]; + } + } + node_value + } else { + let mut total = vec![0.0; self.n[p]]; + for (k, kid) in kids.iter().enumerate() { + let reach: Vec = (0..n).map(|j| opp[j] * sigma[j * a + k]).collect(); + let v = self.walk(*kid, p, own, &reach, r, weight); + total.iter_mut().zip(&v).for_each(|(t, x)| *t += x); + } + total + } + } + } + } + + /// The average strategy so far (uniform where a hand was never reached). + pub fn strategy(&self) -> TrStrategy { + let mut actions = Vec::new(); + let mut players = Vec::new(); + let probs = self + .game + .nodes + .iter() + .enumerate() + .map(|(i, node)| match node { + TNode::Dec { player, kids, .. } => { + let a = kids.len(); + actions.push(a); + players.push(*player); + let mut out = vec![0.0; self.sums[i].len()]; + for (s, o) in self.sums[i].chunks(a).zip(out.chunks_mut(a)) { + let t: f64 = s.iter().sum(); + for (x, y) in s.iter().zip(o.iter_mut()) { + *y = if t > 0.0 { x / t } else { 1.0 / a as f64 }; + } + } + out + } + _ => { + actions.push(0); + players.push(0); + Vec::new() + } + }) + .collect(); + TrStrategy { probs, actions, n: self.n, players } + } + + /// Best-response values of player `p` (per own combo) against `strategy`. + fn br(&self, strategy: &TrStrategy, node: usize, p: usize, opp: &[f64], r: usize) -> Vec { + match &self.game.nodes[node] { + TNode::Fold { folder, amt } => { + let v = if *folder == p { -amt } else { *amt }; + self.disjoint(p, opp).into_iter().map(|x| x * v).collect() + } + TNode::Show { half } => self.show(p, r, opp, *half), + TNode::Chance { child } => { + let mut total = vec![0.0; self.n[p]]; + for ri in 0..self.rc.len() { + let q = self.mask_by_card(opp, 1 - p, ri); + let v = self.br(strategy, *child, p, &q, ri); + let free = &self.rc[ri].free[p]; + for i in 0..total.len() { + total[i] += self.wr * v[i] * free[i]; + } + } + total + } + TNode::Dec { player, kids, .. } => { + if *player == p { + let mut best = vec![f64::NEG_INFINITY; self.n[p]]; + for kid in kids { + let v = self.br(strategy, *kid, p, opp, r); + best.iter_mut().zip(&v).for_each(|(b, x)| *b = b.max(*x)); + } + best + } else { + let mut total = vec![0.0; self.n[p]]; + for (k, kid) in kids.iter().enumerate() { + let reach: Vec = (0..opp.len()).map(|j| opp[j] * strategy.row(node, r, j)[k]).collect(); + let v = self.br(strategy, *kid, p, &reach, r); + total.iter_mut().zip(&v).for_each(|(t, x)| *t += x); + } + total + } + } + } + } + + /// Normaliser: total deal weight of the disjoint pairs. + fn pair_mass(&self) -> f64 { + let d = self.disjoint(0, &self.weights[1]); + d.iter().zip(&self.weights[0]).map(|(x, w)| x * w).sum() + } + + /// Best-response value of player `p` against `strategy`, chips per deal, in `p`'s own net. + pub fn best_response_value(&self, strategy: &TrStrategy, p: usize) -> f64 { + let v = self.br(strategy, self.game.root, p, &self.weights[1 - p], NO_CARD); + v.iter().zip(&self.weights[p]).map(|(x, w)| x * w).sum::() / self.pair_mass() + } + + /// Exploitability of `strategy`: both best-response gains. Zero exactly at an equilibrium. + pub fn exploitability(&self, strategy: &TrStrategy) -> Exploit { + // Zero-sum: the value of the profile for player p is the negative of the other's, so the + // gains sum to BR_0 + BR_1. + let g0 = self.best_response_value(strategy, 0); + let g1 = self.best_response_value(strategy, 1); + Exploit { gain: [g0, g1], total: g0 + g1 } + } + + /// Expected net of hero (player 0) when both follow `strategy`, chips per deal. + pub fn value(&self, strategy: &TrStrategy) -> f64 { + let v = self.follow(strategy, self.game.root, 0, &self.weights[1], NO_CARD, &vec![1.0; self.n[0]]); + v.iter().zip(&self.weights[0]).map(|(x, w)| x * w).sum::() / self.pair_mass() + } + + fn follow(&self, strategy: &TrStrategy, node: usize, p: usize, opp: &[f64], r: usize, own: &[f64]) -> Vec { + match &self.game.nodes[node] { + TNode::Fold { folder, amt } => { + let v = if *folder == p { -amt } else { *amt }; + self.disjoint(p, opp).into_iter().map(|x| x * v).collect() + } + TNode::Show { half } => self.show(p, r, opp, *half), + TNode::Chance { child } => { + let mut total = vec![0.0; self.n[p]]; + for ri in 0..self.rc.len() { + let q = self.mask_by_card(opp, 1 - p, ri); + let v = self.follow(strategy, *child, p, &q, ri, own); + let free = &self.rc[ri].free[p]; + for i in 0..total.len() { + total[i] += self.wr * v[i] * free[i]; + } + } + total + } + TNode::Dec { player, kids, .. } => { + let mut total = vec![0.0; self.n[p]]; + for (k, kid) in kids.iter().enumerate() { + if *player == p { + let v = self.follow(strategy, *kid, p, opp, r, own); + for i in 0..total.len() { + total[i] += strategy.row(node, r, i)[k] * v[i]; + } + } else { + let reach: Vec = (0..opp.len()).map(|j| opp[j] * strategy.row(node, r, j)[k]).collect(); + let v = self.follow(strategy, *kid, p, &reach, r, own); + total.iter_mut().zip(&v).for_each(|(t, x)| *t += x); + } + } + total + } + } + } + + /// The river card with this bit (index into the enumerated cards), if enumerated. + pub fn card_index(&self, bit: u64) -> Option { + self.rc.iter().position(|c| c.bit == bit) + } +} + +#[cfg(test)] +mod tests; diff --git a/src/cfr/turn_river_game/tests.rs b/src/cfr/turn_river_game/tests.rs new file mode 100644 index 00000000..a0b4abf0 --- /dev/null +++ b/src/cfr/turn_river_game/tests.rs @@ -0,0 +1,381 @@ +use super::*; +use crate::card::Card; +use crate::cfr::river_game; +use crate::rng::Rng; + +const BOARD: &str = "Ah 7d 2c Ks"; + +fn board() -> u64 { + fast7::mask(&Card::parse_list(BOARD).unwrap()) +} + +/// All two-card combos off the board and off `avoid`. +fn pool(avoid: u64) -> Vec { + let bits: Vec = (0..4u32).flat_map(|s| (0..13u32).map(move |r| 1u64 << (16 * s + r))).filter(|b| b & (board() | avoid) == 0).collect(); + let mut v = Vec::new(); + for i in 0..bits.len() { + for j in i + 1..bits.len() { + v.push(bits[i] | bits[j]); + } + } + v +} + +fn lcg(x: &mut u64) -> u64 { + *x = x.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + *x >> 33 +} + +/// `n` random distinct combos with random weights. +fn random_hands(n: usize, seed: u64, avoid: u64) -> Hands { + let p = pool(avoid); + let mut x = seed; + let mut masks: Vec = Vec::new(); + while masks.len() < n { + let m = p[(lcg(&mut x) as usize) % p.len()]; + if !masks.contains(&m) { + masks.push(m); + } + } + let weights = (0..n).map(|_| 0.2 + (lcg(&mut x) % 1000) as f64 / 1000.0).collect(); + Hands { masks, weights } +} + +fn only_all_in() -> Menu { + Menu { fracs: vec![], raise_mult: vec![], max_raises: 0, allin: true } +} + +// --- an independent scalar evaluator: one deal at a time, payoffs from the chips actually put in --- + +type Probs<'a> = &'a dyn Fn(usize, usize, usize) -> Vec; // (node, card copy, hand of the deciding player) + +struct Walk<'a> { + s: &'a TrSolver, + probs: Probs<'a>, + masks: [u64; 2], + hands: [usize; 2], +} + +impl Walk<'_> { + fn go(&self, node: usize, chips: [f64; 2], c: [f64; 2], r: usize) -> [f64; 2] { + match &self.s.game.nodes[node] { + TNode::Fold { folder, .. } => { + let mut out = [0.0; 2]; + out[*folder] = -chips[*folder]; + out[1 - *folder] = chips[*folder]; + out + } + TNode::Show { .. } => { + assert_eq!(chips[0], chips[1], "a showdown is matched"); + let b = self.s.rc[r].bit; + let bd = board(); + let sc = [fast7::score(self.masks[0] | bd | b), fast7::score(self.masks[1] | bd | b)]; + match sc[0].cmp(&sc[1]) { + std::cmp::Ordering::Greater => [chips[1], -chips[1]], + std::cmp::Ordering::Less => [-chips[0], chips[0]], + std::cmp::Ordering::Equal => [0.0, 0.0], + } + } + TNode::Chance { child } => { + assert_eq!(chips[0], chips[1], "a street ends matched"); + let mut out = [0.0; 2]; + for card in 0..self.s.rc.len() { + if (self.masks[0] | self.masks[1]) & self.s.rc[card].bit != 0 { + continue; + } + let v = self.go(*child, chips, [0.0, 0.0], card); + out[0] += self.s.wr * v[0]; + out[1] += self.s.wr * v[1]; + } + out + } + TNode::Dec { player, kids, .. } => { + let p = (self.probs)(node, r, self.hands[*player]); + let mut out = [0.0; 2]; + for (k, kid) in kids.iter().enumerate() { + let (mut ch, mut cc) = (chips, c); + match self.s.game.acts[node][k] { + Act::Bet(to) | Act::Raise(to) => { + ch[*player] += to - cc[*player]; + cc[*player] = to; + } + Act::Call => { + ch[*player] += cc[1 - *player] - cc[*player]; + cc[*player] = cc[1 - *player]; + } + _ => {} + } + let v = self.go(*kid, ch, cc, r); + out[0] += p[k] * v[0]; + out[1] += p[k] * v[1]; + } + out + } + } + } +} + +/// Expected net of both players over all valid deals, normalised like the solver. +fn scalar_values(s: &TrSolver, pot: f64, probs: Probs) -> [f64; 2] { + let (mut tot, mut mass) = ([0.0; 2], 0.0); + for i in 0..s.n[0] { + for j in 0..s.n[1] { + if s.masks[0][i] & s.masks[1][j] != 0 { + continue; + } + mass += s.weights[0][i] * s.weights[1][j]; + let w = Walk { s, probs, masks: [s.masks[0][i], s.masks[1][j]], hands: [i, j] }; + let v = w.go(s.game.root, [pot / 2.0, pot / 2.0], [0.0, 0.0], NO_CARD); + for p in 0..2 { + tot[p] += s.weights[0][i] * s.weights[1][j] * v[p]; + } + } + } + [tot[0] / mass, tot[1] / mass] +} + +fn tiny(hero: usize, villain: usize, first: usize, seed: u64) -> (TrSolver, f64) { + let pot = 4.0; + let bets = TrBets { pot, stack: 8.0, first, turn: only_all_in(), river: only_all_in() }; + let game = build(&bets, &[]); + let hands = [random_hands(hero, seed, 0), random_hands(villain, seed ^ 0x9E37, 0)]; + let cards = vec![fast7::mask(&Card::parse_list("3s").unwrap()), fast7::mask(&Card::parse_list("Jh").unwrap())]; + // Two river cards, each standing for half of the deals. + let wr = 0.5 * 48.0 / 44.0; + (TrSolver::with_cards(game, hands, board(), cards, wr), pot) +} + +#[test] +fn the_vector_values_equal_the_scalar_enumeration_and_the_game_is_zero_sum() { + for first in 0..2 { + let (mut s, pot) = tiny(3, 2, first, 11 + first as u64); + s.run(300); + let strat = s.strategy(); + let f = |node: usize, r: usize, h: usize| strat.row(node, r, h).to_vec(); + let [v0, v1] = scalar_values(&s, pot, &f); + assert!((v0 + v1).abs() < 1e-9, "zero-sum: {v0} {v1}"); + let vec_value = s.value(&strat); + assert!((vec_value - v0).abs() < 1e-9, "vector {vec_value} vs scalar {v0}"); + } +} + +/// The best response by brute force: every pure strategy of the player against the other's fixed one. +fn brute_best_response(s: &TrSolver, pot: f64, strat: &TrStrategy, p: usize) -> f64 { + let k = s.rc.len(); + let mut sets: Vec<(usize, usize, usize, usize)> = Vec::new(); // node, copy, hand, actions + for (node, n) in s.game.nodes.iter().enumerate() { + if let TNode::Dec { player, street, kids } = n { + if *player == p { + for copy in 0..(if *street == 0 { 1 } else { k }) { + for h in 0..s.n[p] { + sets.push((node, copy, h, kids.len())); + } + } + } + } + } + let total: u64 = sets.iter().map(|x| x.3 as u64).product(); + assert!(total <= 1 << 20, "{total} pure strategies is too many for a brute force"); + let mut best = f64::NEG_INFINITY; + for code in 0..total { + let mut c = code; + let mut choice = std::collections::HashMap::new(); + for (node, copy, h, a) in &sets { + choice.insert((*node, *copy, *h), (c % *a as u64) as usize); + c /= *a as u64; + } + let f = |node: usize, r: usize, h: usize| -> Vec { + if let TNode::Dec { player, street, kids } = &s.game.nodes[node] { + if *player == p { + let copy = if *street == 0 { 0 } else { r }; + let mut v = vec![0.0; kids.len()]; + v[choice[&(node, copy, h)]] = 1.0; + return v; + } + } + strat.row(node, r, h).to_vec() + }; + best = best.max(scalar_values(s, pot, &f)[p]); + } + best +} + +#[test] +fn the_best_response_equals_a_brute_force_over_all_pure_strategies() { + let (mut s, pot) = tiny(3, 2, 0, 5); + let uniform = s.strategy(); + s.run(200); + let solved = s.strategy(); + for (name, strat) in [("uniform", &uniform), ("solved", &solved)] { + for p in 0..2 { + let brute = brute_best_response(&s, pot, strat, p); + let fast = s.best_response_value(strat, p); + assert!((brute - fast).abs() < 1e-9, "{name} player {p}: brute {brute} vs vector {fast}"); + } + } + let e = s.exploitability(&solved); + let u = s.exploitability(&uniform); + eprintln!("tiny game: solved exploitability {:.5}, uniform {:.5}", e.total, u.total); + assert!(e.total < 0.05, "solved exploitability {}", e.total); + assert!(u.total > 5.0 * e.total.max(1e-3), "a uniform strategy is much more exploitable ({} vs {})", u.total, e.total); +} + +#[test] +fn the_solver_converges_on_a_real_sized_game() { + let bets = TrBets::standard(20.0, 80.0, 0); + let game = build(&bets, &[]); + let hands = [random_hands(14, 3, 0), random_hands(14, 4, 0)]; + let mut s = TrSolver::new(game, hands, board(), Some(10)); + let mut seen = Vec::new(); + for _ in 0..4 { + s.run(100); + seen.push(s.exploitability(&s.strategy()).total); + } + eprintln!("exploitability after 100/200/300/400 iterations: {seen:?} (pot 20)"); + assert!(seen[3] < seen[0], "{seen:?}"); + assert!(seen[3] < 0.5, "exploitability {} chips on a 20-chip pot", seen[3]); +} + +#[test] +fn a_checked_through_turn_is_exactly_the_river_game() { + let river_card = fast7::mask(&Card::parse_list("3s").unwrap()); + // Hands with pairwise distinct strengths on this runout, so classes are strength ranks. + let bd = board(); + let mut x = 99u64; + let p = pool(river_card); + let mut used = std::collections::HashSet::new(); + let mut pick = |n: usize| { + let mut v = Vec::new(); + while v.len() < n { + let m = p[(lcg(&mut x) as usize) % p.len()]; + if used.insert(fast7::score(m | bd | river_card)) { + v.push(m); + } + } + v + }; + let (hm, vm) = (pick(5), pick(5)); + let hands = [Hands { masks: hm.clone(), weights: vec![1.0, 2.0, 1.0, 3.0, 1.0] }, Hands { masks: vm.clone(), weights: vec![2.0, 1.0, 1.0, 1.0, 2.0] }]; + let (pot, stack, first) = (10.0, 40.0, 1); + let rmenu = Menu { fracs: vec![0.5, 1.0], raise_mult: vec![3.0], max_raises: 1, allin: true }; + let bets = TrBets { pot, stack, first, turn: Menu { fracs: vec![], raise_mult: vec![], max_raises: 0, allin: false }, river: rmenu }; + let game = build(&bets, &[]); + let mut mine = TrSolver::with_cards(game, hands.clone(), bd, vec![river_card], 1.0); + mine.run(1500); + let strat = mine.strategy(); + let e_mine = mine.exploitability(&strat).total; + let v_mine = mine.value(&strat); + // The river game over the same hands as classes. + let score = |m: u64| fast7::score(m | bd | river_card); + let mut ladder: Vec = hm.iter().chain(&vm).map(|m| score(*m)).collect(); + ladder.sort(); + ladder.dedup(); + let class = |m: u64| ladder.iter().position(|l| *l == score(m)).unwrap(); + let n = ladder.len(); + let mut chance = vec![0.0; n * n]; + for (i, a) in hm.iter().enumerate() { + for (j, b) in vm.iter().enumerate() { + if a & b == 0 { + chance[class(*a) * n + class(*b)] += hands[0].weights[i] * hands[1].weights[j]; + } + } + } + let z: f64 = chance.iter().sum(); + chance.iter_mut().for_each(|c| *c /= z); + let rb = river_game::Bets { pot, stack, first, bet_fracs: vec![0.5, 1.0], raise_mult: vec![3.0], max_raises: 1 }; + let rg = river_game::build(n, chance, &rb, &[]); + let solved = crate::cfr::solve::solve(&rg.tree, 3000, Rng::seeded(1)); + let e_rg = crate::cfr::exploitability::exploitability(&rg.tree, &solved.strategy); + let v_rg = crate::cfr::exploitability::game_value(&rg.tree, &solved.strategy); + // The river game's strategy, carried into this game node by node, is judged by this module's best response. + let mut at = mine.game.root; + while !matches!(mine.game.nodes[at], TNode::Chance { .. }) { + let TNode::Dec { kids, .. } = &mine.game.nodes[at] else { panic!() }; + at = kids[0]; + } + let TNode::Chance { child } = &mine.game.nodes[at] else { unreachable!() }; + let r0 = *child; + assert!(r0 + rg.tree.nodes.len() < mine.game.nodes.len()); + let mut carried = mine.strategy(); + for k in 0..rg.tree.nodes.len() { + if let Node::Decision { player, .. } = &rg.tree.nodes[k] { + let a = carried.actions[r0 + k]; + assert_eq!(a, rg.tree.action_count(k).unwrap(), "same actions at the same node"); + let ms = if *player == 0 { &hm } else { &vm }; + for (h, m) in ms.iter().enumerate() { + let row = solved.strategy.row(k, class(*m)).to_vec(); + carried.probs[r0 + k][h * a..(h + 1) * a].copy_from_slice(&row); + } + } + } + let e_carried = mine.exploitability(&carried).total; + let v_carried = mine.value(&carried); + eprintln!("mine: value {v_mine:.4} expl {e_mine:.4}; river_game: value {v_rg:.4} expl {e_rg:.4}; carried: value {v_carried:.4} expl {e_carried:.4}"); + assert!(e_mine < 0.05 && e_rg < 0.05, "{e_mine} {e_rg}"); + assert!((v_mine - v_rg).abs() < 0.05, "game values differ: {v_mine} vs {v_rg}"); + assert!(e_carried < 0.05, "the river game's equilibrium is an equilibrium here too: {e_carried}"); + assert!((v_carried - v_rg).abs() < 0.05, "same payoffs: {v_carried} vs {v_rg}"); +} + +use crate::cfr::tree::Node; + +#[test] +fn an_observed_turn_bet_is_a_node_and_hero_faces_it() { + let bets = TrBets::standard(20.0, 80.0, 1); + let g = build(&bets, &[Act::Bet(13.0)]); + let at = g.at.expect("hero faces the bet"); + let TNode::Dec { player, street, .. } = &g.nodes[at] else { panic!() }; + assert_eq!((*player, *street), (0, 0)); + assert_eq!(g.acts[at][0], Act::Fold); + assert_eq!(g.acts[at][1], Act::Call); + assert!(g.acts[at].iter().any(|a| matches!(a, Act::Raise(_)))); + assert!(g.acts[g.root].contains(&Act::Bet(13.0)), "exact size in the tree"); + let g2 = build(&bets, &[Act::Check]); + let at2 = g2.at.expect("hero acts after villain checks"); + assert!(matches!(&g2.nodes[at2], TNode::Dec { player: 0, street: 0, .. })); + let g3 = build(&TrBets::standard(20.0, 80.0, 0), &[]); + assert_eq!(g3.at, Some(g3.root)); +} + +/// Convergence probe: exploitability (percent of the pot) against iterations and time. +#[test] +#[ignore = "timing probe"] +fn convergence_probe() { + for (n, k) in [(200usize, 16usize), (200, 48)] { + let bets = TrBets::standard(20.0, 80.0, 0); + let game = build(&bets, &[]); + let hands = [random_hands(n, 3, 0), random_hands(n, 4, 0)]; + let mut s = TrSolver::new(game, hands, board(), Some(k)); + let t = std::time::Instant::now(); + let mut done = 0; + for target in [25u32, 50, 100, 200, 400] { + s.run(target - done); + done = target; + let ms = t.elapsed().as_secs_f64() * 1e3; + let e = s.exploitability(&s.strategy()).total; + eprintln!("combos {n} cards {k}: {target} iterations ({ms:.0} ms): exploitability {:.2} % of the pot", e / 20.0 * 100.0); + let t2 = std::time::Instant::now(); + let _ = t2; + } + } +} + +/// Timing probe (run with `--ignored --nocapture`): iterations per second at table-sized ranges. +#[test] +#[ignore = "timing probe"] +fn timing_probe() { + for (n, k) in [(150usize, 48usize), (150, 16), (150, 8), (300, 16), (300, 8)] { + for river_fracs in [vec![0.7], vec![]] { + let mut bets = TrBets::standard(20.0, 80.0, 0); + bets.river.fracs = river_fracs.clone(); + let game = build(&bets, &[]); + let nodes = game.nodes.len(); + let hands = [random_hands(n, 3, 0), random_hands(n, 4, 0)]; + let mut s = TrSolver::new(game, hands, board(), Some(k)); + let t = std::time::Instant::now(); + s.run(10); + let per = t.elapsed().as_secs_f64() / 10.0; + eprintln!("combos {n} river cards {k} river sizes {river_fracs:?}: {nodes} nodes, {:.1} ms/iteration", per * 1e3); + } + } +} diff --git a/src/engine/decide.rs b/src/engine/decide.rs index 7a973b24..64cf3d18 100644 --- a/src/engine/decide.rs +++ b/src/engine/decide.rs @@ -97,6 +97,11 @@ fn postflop(spot: &Spot, thresholds: &Thresholds, raw: &Spot, premium: f64) -> D if let Some(d) = super::river_subgame::dbr_decision(raw) { return d.with_equity(equity.share); } + // Arm (off by default, TURN_SPIEL=grund): the turn+river game with ranges from the + // blueprint (`engine::turn_game`); `None` while the switch is off. + if let Some(d) = super::turn_game::turn_game_decision(raw) { + return d.with_equity(equity.share); + } return super::river_subgame::fold_veto(raw, floored); } floored diff --git a/src/engine/mod.rs b/src/engine/mod.rs index b7f3d37b..01b48e03 100644 --- a/src/engine/mod.rs +++ b/src/engine/mod.rs @@ -22,5 +22,6 @@ pub mod semibluff; pub mod size_policy; pub mod texture_stance; pub mod thin_value; +pub mod turn_game; pub mod turn_subgame; pub mod uncertainty; diff --git a/src/engine/river_subgame.rs b/src/engine/river_subgame.rs index 192ea0bf..ec3a2ec2 100644 --- a/src/engine/river_subgame.rs +++ b/src/engine/river_subgame.rs @@ -754,7 +754,7 @@ fn deal_classes(spot: &Spot, hero_combos: &[(Vec, f64)], villain_combos: & } /// The legal choice nearest to a game action. -fn legal_choice(spot: &Spot, act: Act) -> Choice { +pub(crate) fn legal_choice(spot: &Spot, act: Act) -> Choice { let passive = if spot.to_call > 0.0 { Choice::Call } else { Choice::Check }; match act { Act::Fold if spot.to_call > 0.0 => Choice::Fold, diff --git a/src/engine/turn_game.rs b/src/engine/turn_game.rs new file mode 100644 index 00000000..0e36290f --- /dev/null +++ b/src/engine/turn_game.rs @@ -0,0 +1,322 @@ +//! The turn re-solved at the table over real hands (plan E3, layer 2): both ranges from the +//! blueprint (`blueprint::ranges`, carried along the line actually played), the turn betting and +//! the river inside one game (`cfr::turn_river_game`), hero's equilibrium action at the real node. +//! +//! Switch: `TurnPlayer::Grund` (default `Off`; `ab_zelle` / `engine_lbr`: `TURN_SPIEL=grund`). Off, +//! `turn_game_decision` returns `None` before it looks at anything, so the engine's output is +//! unchanged. On, it plays only where the blueprint recognises the spot (S1: button open, big blind +//! call, about 100 bb, heads-up on the turn, hero at a decision); everywhere else the heuristic plays. +//! +//! The solve depends on the public state only (board, line, pot, stacks): the villain's range is NOT +//! conditioned on hero's real cards (`gewichtete_listen_offen`; the game deals card removal itself), +//! so one solve serves every hero hand at the same node. Solves are cached by public state (a +//! measurement that asks the engine for every hand of a range, as LBR does, pays one solve per node). +//! +//! Approximations (named, each a knob of `TurnConfig`): ranges are pruned to the `max_combos` +//! heaviest combos per player; the river is enumerated over `river_cards` evenly strided cards, each +//! standing for its share (`cfr::turn_river_game`); the bet menu is `TrBets::standard` plus the +//! observed size; the solve is a fixed `iterations` of CFR+. Hero's real hand, if pruned away or +//! outside the blueprint range, is put back with its weight (or a token weight) in an uncached solve. + +use crate::card::Card; +use crate::cfr::river_game::Act; +use crate::cfr::turn_river_game::{build, Exploit, Hands, TNode, TrBets, TrSolver}; +use crate::engine::river_subgame::legal_choice; +use crate::game::{Decision, SeenAction, Spot, Street, Villain}; +use crate::hand::fast7; +use crate::rng::Rng; +use std::collections::HashMap; +use std::hash::{Hash, Hasher}; +use std::sync::{Arc, Mutex}; + +static MODE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0); + +/// Who plays the heads-up turn. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TurnPlayer { + /// The heuristic (default). + Off, + /// The turn+river game with both ranges from the blueprint; only where the spot is a blueprint + /// scenario, else the heuristic plays. + Grund, +} + +pub fn set_turn_player(mode: TurnPlayer) { + MODE.store(u8::from(mode == TurnPlayer::Grund), std::sync::atomic::Ordering::Relaxed); +} + +pub fn turn_player() -> TurnPlayer { + if MODE.load(std::sync::atomic::Ordering::Relaxed) == 1 { + TurnPlayer::Grund + } else { + TurnPlayer::Off + } +} + +/// Size and budget of the solve. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct TurnConfig { + /// Most combos per player (heaviest by weight). + pub max_combos: usize, + /// Stop adding combos once this share of the range mass is in (before `max_combos`). + pub cover: f64, + /// River cards enumerated (of 48). + pub river_cards: usize, + /// CFR+ iterations. + pub iterations: u32, + /// Also compute the best-response exploitability of the result (about two more iterations). + pub measure: bool, + /// Raises allowed after a river bet (0 or 1). + pub river_raises: usize, +} + +impl TurnConfig { + pub const STANDARD: TurnConfig = TurnConfig { max_combos: 160, cover: 0.95, river_cards: 10, iterations: 200, measure: false, river_raises: 0 }; + + /// `STANDARD` with `TURN_COMBOS`, `TURN_CARDS`, `TURN_ITERS`, `TURN_EXPLOIT=1` from the environment. + pub fn from_env() -> TurnConfig { + let num = |k: &str, d: usize| std::env::var(k).ok().and_then(|s| s.parse().ok()).filter(|n| *n > 0).unwrap_or(d); + TurnConfig { + max_combos: num("TURN_COMBOS", Self::STANDARD.max_combos), + cover: num("TURN_COVER", 95) as f64 / 100.0, + river_cards: num("TURN_CARDS", Self::STANDARD.river_cards), + iterations: num("TURN_ITERS", Self::STANDARD.iterations as usize) as u32, + measure: std::env::var("TURN_EXPLOIT").as_deref() == Ok("1"), + river_raises: std::env::var("TURN_RIVER_RAISES").ok().and_then(|s| s.parse().ok()).map_or(Self::STANDARD.river_raises, |n: usize| n.min(1)), + } + } +} + +/// One solved node of the game: what every hero hand at this public state shares. +pub struct Solved { + /// Hero's turn-node action probabilities, `hero_masks.len()` rows of `acts.len()`. + rows: Vec, + acts: Vec, + hero_masks: Vec, + pub millis: f64, + pub combos: [usize; 2], + pub nodes: usize, + /// Best-response exploitability of the solved game, chips per deal (when `measure`). + pub exploit: Option, + pub big_blind: f64, + pub pot: f64, +} + +impl Solved { + /// Exploitability in bb per 100 decisions of this kind (what the plan's gate counts). + pub fn exploit_bb_per_100(&self) -> Option { + self.exploit.map(|e| e.total / self.big_blind * 100.0) + } +} + +/// The result of deciding one hand from a `Solved`. +pub struct TurnSolved { + pub decision: Decision, + /// Hero's action probabilities for the real hand at the real node, and the actions they stand for. + pub row: Vec, + pub acts: Vec, + pub solved: Arc, +} + +/// The turn line so far for hero and `villain`: who acted first (0 = hero), the forced actions and the +/// street contributions. Falls back to "villain bet `to_call`" / "hero first" without a history. +fn turn_line(spot: &Spot, villain: &Villain) -> (usize, Vec, [f64; 2]) { + let mut first = None; + let mut acts = Vec::new(); + let mut c = [0.0f64, 0.0]; + let mut aggressed = false; + for r in spot.history.iter().filter(|r| r.street == Street::Turn) { + let who = if r.seat == spot.hero_seat { + 0 + } else if r.seat == villain.seat { + 1 + } else { + continue; + }; + first.get_or_insert(who); + let amount = r.amount.unwrap_or(c[who]); + match r.action { + SeenAction::Check => acts.push(Act::Check), + SeenAction::Bet | SeenAction::Raise | SeenAction::AllIn if amount > c[1 - who] => { + acts.push(if aggressed { Act::Raise(amount) } else { Act::Bet(amount) }); + aggressed = true; + c[who] = amount; + } + SeenAction::Call | SeenAction::AllIn => { + acts.push(Act::Call); + c[who] = c[1 - who]; + } + _ => {} + } + } + let consistent = (c[1] - c[0] - spot.to_call).abs() < 1e-6 * spot.pot.max(1.0); + match first { + Some(f) if consistent => (f, acts, c), + _ if spot.to_call > 0.0 => (1, vec![Act::Bet(spot.to_call)], [0.0, spot.to_call]), + _ => (0, Vec::new(), [0.0, 0.0]), + } +} + +/// Masks and weights of a combo list: off the board, the `max` heaviest, `keep` (hero's hand) always in. +fn prune(list: &[(Vec, f64)], board: u64, cfg: &TurnConfig, keep: Option) -> Hands { + let mut v: Vec<(u64, f64)> = list + .iter() + .filter(|(c, w)| c.len() == 2 && *w > 0.0 && w.is_finite()) + .map(|(c, w)| (fast7::mask(c), *w)) + .filter(|(m, _)| m & board == 0 && m.count_ones() == 2) + .collect(); + v.sort_by(|a, b| b.1.total_cmp(&a.1).then(a.0.cmp(&b.0))); + v.dedup_by_key(|x| x.0); + let top = v.first().map_or(1.0, |x| x.1); + let kept = keep.and_then(|k| v.iter().position(|x| x.0 == k).map(|i| v[i].1)); + let total: f64 = v.iter().map(|x| x.1).sum(); + let mut acc = 0.0; + let enough = v + .iter() + .position(|x| { + acc += x.1; + acc >= cfg.cover * total + }) + .map_or(v.len(), |i| i + 1); + v.truncate(enough.min(cfg.max_combos).max(1)); + if let Some(k) = keep { + if !v.iter().any(|x| x.0 == k) { + // Pruned away, or not in the blueprint range at all: stays in with the weight it had, else + // a token weight, so the game has a strategy for it without moving the equilibrium. + v.push((k, kept.unwrap_or(top * 1e-6))); + } + } + Hands { masks: v.iter().map(|x| x.0).collect(), weights: v.iter().map(|x| x.1).collect() } +} + +/// Solve the game of `spot`'s public state with these weighted ranges. `keep`: a hero hand that must +/// be in the game whatever the pruning. `None` outside a heads-up turn decision or when the line +/// leaves the tree. +fn solve_core(spot: &Spot, hero: &[(Vec, f64)], villain_list: &[(Vec, f64)], cfg: &TurnConfig, keep: Option) -> Option { + if spot.street != Street::Turn || spot.board.len() != 4 || spot.live_villains().count() != 1 { + return None; + } + let villain = spot.live_villains().next()?; + let (first, forced, c) = turn_line(spot, villain); + let pot = spot.pot - c[0] - c[1]; + let stack = (spot.hero_stack + c[0]).min(villain.stack + c[1]); + if pot <= 0.0 || stack <= c[0].max(c[1]) { + return None; + } + let started = std::time::Instant::now(); + let board = fast7::mask(&spot.board); + let hands = [prune(hero, board, cfg, keep), prune(villain_list, board, cfg, None)]; + if hands[0].masks.is_empty() || hands[1].masks.is_empty() { + return None; + } + let mut bets = TrBets::standard(pot, stack, first); + bets.river.max_raises = cfg.river_raises; + let game = build(&bets, &forced); + let at = game.at?; + if !matches!(game.nodes.get(at), Some(TNode::Dec { player: 0, street: 0, .. })) { + return None; + } + let combos = [hands[0].masks.len(), hands[1].masks.len()]; + let hero_masks = hands[0].masks.clone(); + let acts = game.acts[at].clone(); + let nodes = game.nodes.len(); + let mut solver = TrSolver::new(game, hands, board, Some(cfg.river_cards)); + solver.run(cfg.iterations); + let strategy = solver.strategy(); + let exploit = cfg.measure.then(|| solver.exploitability(&strategy)); + let rows: Vec = (0..combos[0]).flat_map(|i| strategy.row(at, 0, i).to_vec()).collect(); + let millis = started.elapsed().as_secs_f64() * 1e3; + Some(Solved { rows, acts, hero_masks, millis, combos, nodes, exploit, big_blind: spot.big_blind, pot }) +} + +/// Hero's decision for the real hand from a solved node. +fn decide_from(spot: &Spot, solved: Arc, hero_mask: u64) -> Option { + let idx = solved.hero_masks.iter().position(|m| *m == hero_mask)?; + let a = solved.acts.len(); + let row = solved.rows[idx * a..(idx + 1) * a].to_vec(); + let (draw, _) = Rng::seeded(spot.seed).unit(); + let mut acc = 0.0; + let mut pick = row.len().saturating_sub(1); + for (k, p) in row.iter().enumerate() { + acc += p; + if draw < acc { + pick = k; + break; + } + } + let act = *solved.acts.get(pick)?; + let choice = legal_choice(spot, act); + let p = row.get(pick).copied().unwrap_or(0.0); + let decision = Decision::new( + choice, + p.clamp(0.0, 1.0), + format!("turn game: {}x{} combos, {} nodes, {act:?} p {p:.2}, solved in {:.0} ms", solved.combos[0], solved.combos[1], solved.nodes, solved.millis), + ); + let acts = solved.acts.clone(); + Some(TurnSolved { decision, row, acts, solved }) +} + +/// Solve the turn for `spot` with these weighted ranges (`hero`, `villain`, as `gewichtete_listen` +/// gives them) and decide; no cache. `None` outside a heads-up turn decision or off the tree. +pub fn solve_turn(spot: &Spot, hero: &[(Vec, f64)], villain_list: &[(Vec, f64)], cfg: &TurnConfig) -> Option { + if spot.hero_cards.len() != 2 { + return None; + } + let hero_mask = fast7::mask(&spot.hero_cards); + if hero_mask & fast7::mask(&spot.board) != 0 { + return None; + } + let solved = solve_core(spot, hero, villain_list, cfg, Some(hero_mask))?; + decide_from(spot, Arc::new(solved), hero_mask) +} + +static CACHE: Mutex>>> = Mutex::new(None); +/// An entry is a few kilobytes (one row of probabilities per hero combo). +const CACHE_MAX: usize = 4096; + +/// Identity of the public state and the solve budget (not hero's cards). +fn public_key(spot: &Spot, cfg: &TurnConfig) -> u64 { + let mut h = std::collections::hash_map::DefaultHasher::new(); + format!("{:?}", spot.history).hash(&mut h); + format!("{:?}", spot.board).hash(&mut h); + [spot.pot, spot.to_call, spot.hero_stack, spot.big_blind].iter().for_each(|x| x.to_bits().hash(&mut h)); + spot.live_villains().for_each(|v| (v.seat, v.stack.to_bits()).hash(&mut h)); + (spot.hero_seat, cfg.max_combos, cfg.cover.to_bits(), cfg.river_cards, cfg.iterations, cfg.measure, cfg.river_raises).hash(&mut h); + h.finish() +} + +/// The live decision: the turn game with ranges from the blueprint, or `None` (switch off, not a +/// blueprint spot, ...) and the heuristic keeps the decision. +pub fn turn_game_decision(spot: &Spot) -> Option { + if turn_player() == TurnPlayer::Off || spot.street != Street::Turn || spot.hero_cards.len() != 2 { + return None; + } + let cfg = TurnConfig::from_env(); + let hero_mask = fast7::mask(&spot.hero_cards); + if hero_mask & fast7::mask(&spot.board) != 0 { + return None; + } + let key = public_key(spot, &cfg); + let cached = CACHE.lock().ok()?.as_ref().and_then(|m| m.get(&key).cloned()); + let solved = match cached { + Some(s) => s, + None => { + let (hero, villain) = crate::blueprint::ranges::gewichtete_listen_offen(spot)?; + let solved = Arc::new(solve_core(spot, &hero, &villain, &cfg, None)?); + if let Ok(mut m) = CACHE.lock() { + let map = m.get_or_insert_with(HashMap::new); + if map.len() >= CACHE_MAX { + map.clear(); + } + map.insert(key, solved.clone()); + } + solved + } + }; + // A hero hand outside the pruned range (low weight at this node, or not in the blueprint range at + // all) is not in the game: `None`, the heuristic plays it. + decide_from(spot, solved, hero_mask).map(|d| d.decision) +} + +#[cfg(test)] +mod tests; diff --git a/src/engine/turn_game/tests.rs b/src/engine/turn_game/tests.rs new file mode 100644 index 00000000..3a13c626 --- /dev/null +++ b/src/engine/turn_game/tests.rs @@ -0,0 +1,242 @@ +use super::*; +use crate::card::Card; +use crate::game::{ActionKind, ActionRecord, Choice, SeenAction, Spot, Street, Villain}; +use crate::variant::Variant; +use std::sync::Mutex; + +/// The switch is process-global: tests that touch it take turns. +static MODE_LOCK: Mutex<()> = Mutex::new(()); + +fn rec(street: Street, seat: u8, action: SeenAction, amount: Option) -> ActionRecord { + ActionRecord { street, seat, action, amount } +} + +/// Six-max S1 line to the turn: button (seat 4) opens 2.5, big blind (seat 0) calls; flop check, bet 1.8, +/// call. Turn pot 9.1. `turn` is the turn line so far; hero is the button. +fn s1_turn(turn: &[ActionRecord], hero: &str, to_call: f64, pot_extra: f64) -> Spot { + use SeenAction::*; + use Street::*; + let mut h = vec![ + rec(Preflop, 5, PostSmallBlind, Some(0.5)), + rec(Preflop, 0, PostBigBlind, Some(1.0)), + rec(Preflop, 1, Fold, None), + rec(Preflop, 2, Fold, None), + rec(Preflop, 3, Fold, None), + rec(Preflop, 4, Raise, Some(2.5)), + rec(Preflop, 5, Fold, None), + rec(Preflop, 0, Call, Some(2.5)), + rec(Flop, 0, Check, None), + rec(Flop, 4, Bet, Some(1.8)), + rec(Flop, 0, Call, Some(1.8)), + ]; + h.extend_from_slice(turn); + let legal = if to_call > 0.0 { vec![ActionKind::Fold, ActionKind::Call, ActionKind::Raise] } else { vec![ActionKind::Check, ActionKind::Raise] }; + Spot { + variant: Variant::Nlhe, + big_blind: 1.0, + seats: 6, + hero_seat: 4, + button_seat: Some(4), + hero_cards: Card::parse_list(hero).unwrap(), + board: Card::parse_list("Ah 7d 2c Ks").unwrap(), + street: Street::Turn, + pot: 9.1 + pot_extra, + to_call, + hero_stack: 95.7, + min_raise_to: Some(if to_call > 0.0 { 2.0 * to_call } else { 1.0 }), + max_raise_to: Some(95.7), + legal, + allowed_sizes: None, + villains: vec![Villain { seat: 0, stack: 95.7 - to_call, folded: false, profile: None }], + seed: 7, + history: h, + } +} + +fn facing_bet(hero: &str) -> Spot { + s1_turn(&[rec(Street::Turn, 0, SeenAction::Bet, Some(6.0))], hero, 6.0, 6.0) +} + +fn hero_first(hero: &str) -> Spot { + // Hero on the button would be last to act; here villain checks and hero decides. + s1_turn(&[rec(Street::Turn, 0, SeenAction::Check, None)], hero, 0.0, 0.0) +} + +/// A range of `n` combos off the board (and `avoid`), pseudo-random, weights 0.2..1.2; always includes `must`. +fn range(n: usize, seed: u64, must: &[&str]) -> Vec<(Vec, f64)> { + let all = Card::parse_list("2c 3c 4c 5c 6c 7c 8c 9c Tc Jc Qc Kc Ac 2d 3d 4d 5d 6d 7d 8d 9d Td Jd Qd Kd Ad 2h 3h 4h 5h 6h 7h 8h 9h Th Jh Qh Kh Ah 2s 3s 4s 5s 6s 7s 8s 9s Ts Js Qs Ks As").unwrap(); + let board = Card::parse_list("Ah 7d 2c Ks").unwrap(); + let cards: Vec = all.into_iter().filter(|c| !board.contains(c)).collect(); + let mut x = seed; + let mut next = || { + x = x.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (x >> 33) as usize + }; + let mut out: Vec<(Vec, f64)> = must.iter().map(|m| (Card::parse_list(m).unwrap(), 1.0)).collect(); + while out.len() < n { + let (a, b) = (cards[next() % cards.len()], cards[next() % cards.len()]); + if a != b && !out.iter().any(|(c, _)| c.contains(&a) && c.contains(&b)) { + out.push((vec![a, b], 0.2 + (next() % 1000) as f64 / 1000.0)); + } + } + out +} + +fn cfg(iterations: u32) -> TurnConfig { + TurnConfig { max_combos: 200, cover: 1.0, river_cards: 12, iterations, measure: true, river_raises: 1 } +} + +#[test] +fn the_decision_is_a_legal_choice_at_both_kinds_of_node() { + let hands = ["Ac Qd", "7h 7c", "3c 4d", "Kd Qs", "9h 8h"]; + for (spot_of, name) in [(facing_bet as fn(&str) -> Spot, "facing a bet"), (hero_first as fn(&str) -> Spot, "first to act")] { + for hero in hands { + let spot = spot_of(hero); + let villain = range(80, 5, &[]); + let me = range(80, 6, &[hero]); + let s = solve_turn(&spot, &me, &villain, &cfg(60)).expect("heads-up turn decision is in scope"); + let sum: f64 = s.row.iter().sum(); + assert!((sum - 1.0).abs() < 1e-9, "{name} {hero}: row {:?}", s.row); + match s.decision.choice { + Choice::Fold => assert!(spot.to_call > 0.0, "{name}: fold only when facing a bet"), + Choice::Check => assert_eq!(spot.to_call, 0.0, "{name}"), + Choice::Call => assert!(spot.to_call > 0.0, "{name}"), + Choice::Raise { to } => { + let (lo, hi) = (spot.min_raise_to.unwrap(), spot.max_raise_to.unwrap()); + assert!(to >= lo - 1e-9 && to <= hi + 1e-9, "{name} {hero}: raise to {to} outside [{lo}, {hi}]"); + } + Choice::Abstain => panic!("{name} {hero}: abstained"), + } + assert!(spot.is_legal(match s.decision.choice { + Choice::Fold => ActionKind::Fold, + Choice::Check => ActionKind::Check, + Choice::Call => ActionKind::Call, + _ => ActionKind::Raise, + })); + } + } +} + +#[test] +fn out_of_position_hero_acts_first_with_check_or_a_bet() { + // Hero is the big blind (seat 0) and acts first on the turn; the villain is the button (seat 4). + let mut spot = s1_turn(&[], "Ac Qd", 0.0, 0.0); + spot.hero_seat = 0; + spot.villains = vec![Villain { seat: 4, stack: 95.7, folded: false, profile: None }]; + let (me, villain) = (range(60, 51, &["Ac Qd"]), range(60, 52, &[])); + let s = solve_turn(&spot, &me, &villain, &cfg(80)).expect("hero first"); + assert_eq!(s.acts[0], Act::Check, "check is the first action at a free node: {:?}", s.acts); + assert!(s.acts.iter().skip(1).all(|a| matches!(a, Act::Bet(_)))); + assert!(matches!(s.decision.choice, Choice::Check | Choice::Raise { .. })); + if let Choice::Raise { to } = s.decision.choice { + assert!(to >= spot.min_raise_to.unwrap() - 1e-9 && to <= spot.max_raise_to.unwrap() + 1e-9); + } +} + +#[test] +fn strong_hands_do_not_fold_and_air_folds_more() { + // The villain's range: top pair or better only (aces, kings, pairs of 7 and 2). + let villain: Vec<(Vec, f64)> = range(400, 21, &[]).into_iter().filter(|(c, _)| c.iter().any(|x| x.rank as u8 >= 11) || c[0].rank == c[1].rank).collect(); + assert!(villain.len() > 30, "{}", villain.len()); + let me = range(100, 22, &["7s 7c", "3c 4d"]); + let spot_set = facing_bet("7s 7c"); + let spot_air = facing_bet("3c 4d"); + let set = solve_turn(&spot_set, &me, &villain, &cfg(150)).unwrap(); + let air = solve_turn(&spot_air, &me, &villain, &cfg(150)).unwrap(); + eprintln!("set row {:?}, air row {:?} ({:?})", set.row, air.row, set.acts); + assert!(set.row[0] < 0.05, "a set never folds to a half-pot bet here: {:?}", set.row); + assert!(air.row[0] > set.row[0] + 0.3, "air folds clearly more: {:?} vs {:?}", air.row, set.row); +} + +#[test] +fn the_solve_is_deterministic_and_the_game_is_balanced_enough() { + let spot = facing_bet("Ac Qd"); + let (me, villain) = (range(150, 31, &["Ac Qd"]), range(150, 32, &[])); + let a = solve_turn(&spot, &me, &villain, &cfg(200)).unwrap(); + let b = solve_turn(&spot, &me, &villain, &cfg(200)).unwrap(); + assert_eq!(a.row, b.row); + assert_eq!(a.decision.choice, b.decision.choice, "same input, same answer"); + let e = a.solved.exploit.expect("measured"); + eprintln!("150x150 combos, 12 river cards, 200 iterations: {:.0} ms, exploitability {:.3} chips = {:.1} % of the {:.1} pot = {:.0} bb/100 (hero at the real node)", a.solved.millis, e.total, e.total / a.solved.pot * 100.0, a.solved.pot, a.solved.exploit_bb_per_100().unwrap()); + assert!(e.total < 0.05 * a.solved.pot, "exploitability {} on a {} pot", e.total, a.solved.pot); +} + +#[test] +fn a_spot_outside_the_game_is_left_to_the_heuristic() { + let me = range(50, 1, &["Ac Qd"]); + let villain = range(50, 2, &[]); + let mut river = facing_bet("Ac Qd"); + river.street = Street::River; + river.board = Card::parse_list("Ah 7d 2c Ks 9h").unwrap(); + assert!(solve_turn(&river, &me, &villain, &cfg(10)).is_none()); + let mut multiway = facing_bet("Ac Qd"); + multiway.villains.push(Villain { seat: 1, stack: 90.0, folded: false, profile: None }); + assert!(solve_turn(&multiway, &me, &villain, &cfg(10)).is_none()); + assert!(solve_turn(&facing_bet("Ac Qd"), &me, &[], &cfg(10)).is_none(), "no villain range"); +} + +#[test] +fn off_means_none_and_the_engine_is_unchanged() { + let _g = MODE_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + set_turn_player(TurnPlayer::Off); + let spots = [facing_bet("Ac Qd"), facing_bet("7s 7c"), hero_first("3c 4d"), hero_first("Kd Qs")]; + let mut flop = hero_first("Ac Qd"); + flop.street = Street::Flop; + flop.board.truncate(3); + let mut river = facing_bet("Ac Qd"); + river.street = Street::River; + river.board = Card::parse_list("Ah 7d 2c Ks 9h").unwrap(); + for spot in spots.iter().chain([&flop, &river]) { + assert!(turn_game_decision(spot).is_none(), "off: the hook says nothing"); + } + // Switched on without a blueprint (no GRUNDSTRATEGIE) the hook still says nothing, so the engine's + // answer is the same either way: compare whole decisions. + if std::env::var_os("GRUNDSTRATEGIE").is_none() { + let off: Vec<_> = spots.iter().chain([&flop, &river]).map(crate::engine::decide::decide).collect(); + set_turn_player(TurnPlayer::Grund); + let on: Vec<_> = spots.iter().chain([&flop, &river]).map(crate::engine::decide::decide).collect(); + set_turn_player(TurnPlayer::Off); + assert_eq!(off, on, "no blueprint: the heuristic plays unchanged"); + } + assert_eq!(turn_player(), TurnPlayer::Off); +} + +#[test] +fn the_public_key_ignores_hero_cards_but_not_the_line() { + let c = TurnConfig::STANDARD; + assert_eq!(public_key(&facing_bet("Ac Qd"), &c), public_key(&facing_bet("7s 7c"), &c)); + assert_ne!(public_key(&facing_bet("Ac Qd"), &c), public_key(&hero_first("Ac Qd"), &c)); +} + +#[test] +#[ignore = "timing probe"] +fn tree_sizes() { + use crate::cfr::turn_river_game::{build, TNode, TrBets}; + for (name, forced, first) in [("hero first", vec![], 0usize), ("facing bet", vec![Act::Bet(6.0)], 1), ("check-raise spot", vec![Act::Check, Act::Bet(6.0)], 0)] { + let g = build(&TrBets::standard(9.1, 95.0, first), &forced); + let chance = g.nodes.iter().filter(|n| matches!(n, TNode::Chance { .. })).count(); + let river_dec = g.nodes.iter().filter(|n| matches!(n, TNode::Dec { street: 1, .. })).count(); + let turn_dec = g.nodes.iter().filter(|n| matches!(n, TNode::Dec { street: 0, .. })).count(); + eprintln!("{name}: {} nodes, {turn_dec} turn decisions, {chance} river chance nodes, {river_dec} river decisions", g.nodes.len()); + } +} + +/// Solve time at table size (run with `--ignored --nocapture`). +#[test] +#[ignore = "timing probe"] +fn solve_time_at_table_size() { + for (n, cards, iters, rr) in [(160usize, 10usize, 200u32, 0usize), (160, 10, 400, 0), (160, 10, 200, 1), (100, 10, 200, 0)] { + let spot = facing_bet("Ac Qd"); + let (me, villain) = (range(n, 41, &["Ac Qd"]), range(n, 42, &[])); + let c = TurnConfig { max_combos: n, cover: 1.0, river_cards: cards, iterations: iters, measure: true, river_raises: rr }; + let s = solve_turn(&spot, &me, &villain, &c).unwrap(); + let e = s.solved.exploit.unwrap(); + eprintln!( + "{n} combos, {cards} river cards, {iters} iterations, river raises {rr}: {:.0} ms ({} nodes), exploitability {:.2} % of pot = {:.0} bb/100", + s.solved.millis, + s.solved.nodes, + e.total / s.solved.pot * 100.0, + s.solved.exploit_bb_per_100().unwrap() + ); + } +}