diff --git a/src/blueprint/engine_gegner.rs b/src/blueprint/engine_gegner.rs new file mode 100644 index 00000000..9503df6b --- /dev/null +++ b/src/blueprint/engine_gegner.rs @@ -0,0 +1,196 @@ +//! The live engine as the opponent of LBR on scenario S1 (plan M4): the engine's exploitability +//! on flop, turn and river with the same yardstick as the blueprint's. +//! +//! At an S1 node the engine is asked (`engine::decide`) with a spot built from the tree: six seats as +//! in the simulator (button 1, small blind 2, big blind 3, the rest folded preflop), the preflop +//! line, the postflop line up to the node as `history`, the real pot including the folded small +//! blind. Its choice is mapped back onto the node's children (sizes pseudo-harmonically, as for real +//! hands in `ranges`). The engine is deterministic per spot seed, so the row is pure. +//! +//! Named approximations: the engine sees no read on LBR (profile `None`), so this is the engine's +//! default play; its own size menu is mapped onto the tree's (an off-tree size is rounded to a tree +//! size, which LBR then exploits as if the engine had used it). + +use super::lbr::Gegner; +use super::mccfr::Knoten; +use super::ranges::harmonisch; +use super::s1::{Aktion, OPEN, S1, STACK}; +use crate::card::Card; +use crate::engine::decide::decide; +use crate::game::{ActionKind, ActionRecord, Choice, SeenAction, Spot, Street, Villain}; +use crate::hand::fast7; +use crate::variant::Variant; + +/// Seats of the S1 players in the built spot: player 0 = big blind, player 1 = button. +const SITZ: [u8; 2] = [3, 1]; +const SB_TOT: f64 = 0.5; + +pub struct EngineGegner { + deck: Vec, +} + +impl Default for EngineGegner { + fn default() -> Self { + EngineGegner { + 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").unwrap(), + } + } +} + +const STRASSEN: [Street; 3] = [Street::Flop, Street::Turn, Street::River]; + +impl EngineGegner { + fn karten(&self, m: u64) -> Vec { + self.deck.iter().copied().filter(|c| fast7::bit(*c) & m != 0).collect() + } + + /// The spot of S1 node `k` for the acting player holding `hand`; also the contributions at the + /// start of the node's street. + pub fn spot(&self, s: &S1, k: usize, hand: u64, board: u64) -> Option<(Spot, f64)> { + let Knoten::Zug { spieler: p, strasse, kinder } = &s.baum.baum.knoten[k] else { return None }; + let (p, strasse) = (*p, *strasse); + // Path root -> k. + let mut pfad = vec![k]; + while let Some(&e) = pfad.last().map(|x| &s.baum.eltern[*x]) { + if e == usize::MAX { + break; + } + pfad.push(e); + } + pfad.reverse(); + let rec = |street, seat, action, amount| ActionRecord { street, seat, action, amount }; + let mut history = vec![ + rec(Street::Preflop, 2, SeenAction::PostSmallBlind, Some(SB_TOT)), + rec(Street::Preflop, 3, SeenAction::PostBigBlind, Some(1.0)), + rec(Street::Preflop, 4, SeenAction::Fold, None), + rec(Street::Preflop, 5, SeenAction::Fold, None), + rec(Street::Preflop, 6, SeenAction::Fold, None), + rec(Street::Preflop, 1, SeenAction::Raise, Some(OPEN)), + rec(Street::Preflop, 2, SeenAction::Fold, None), + rec(Street::Preflop, 3, SeenAction::Call, Some(OPEN)), + ]; + let mut start = OPEN; + let mut start_strasse = 0; + for w in pfad.windows(2) { + let (q, child) = (w[0], w[1]); + let Knoten::Zug { spieler: a, strasse: st, .. } = &s.baum.baum.knoten[q] else { return None }; + if *st != start_strasse { + start_strasse = *st; + start = s.baum.beitrag[q][0]; + } + let street_total = s.baum.beitrag[child][*a] - start; + let (action, amount) = match s.baum.aktion[child]? { + Aktion::Check => (SeenAction::Check, None), + Aktion::Call => (SeenAction::Call, Some(street_total)), + Aktion::Bet(_) => (SeenAction::Bet, Some(street_total)), + Aktion::Raise(_) => (SeenAction::Raise, Some(street_total)), + Aktion::Fold => (SeenAction::Fold, None), + }; + history.push(rec(STRASSEN[*st], SITZ[*a], action, amount)); + } + if strasse != start_strasse { + start = s.baum.beitrag[k][0]; + } + let c = s.baum.beitrag[k]; + let o = 1 - p; + let to_call = c[o] - c[p]; + let raises = kinder.iter().any(|x| matches!(s.baum.aktion[*x], Some(Aktion::Bet(_) | Aktion::Raise(_)))); + let mut legal = if to_call > 0.0 { vec![ActionKind::Fold, ActionKind::Call] } else { vec![ActionKind::Check] }; + if raises { + legal.push(ActionKind::Raise); + } + let (mine_street, theirs_street) = (c[p] - start, c[o] - start); + let min_raise_to = theirs_street + to_call.max(1.0); + let max_raise_to = mine_street + (STACK - c[p]); + let villains = (1..=6u8) + .filter(|x| *x != SITZ[p]) + .map(|x| Villain { seat: x, stack: if x == SITZ[o] { STACK - c[o] } else { STACK }, folded: x != SITZ[o], profile: None }) + .collect(); + let spot = Spot { + variant: Variant::Nlhe, + big_blind: 1.0, + seats: 6, + hero_seat: SITZ[p], + button_seat: Some(1), + hero_cards: self.karten(hand), + board: self.karten(board), + street: STRASSEN[strasse], + pot: c[0] + c[1] + SB_TOT, + to_call, + hero_stack: STACK - c[p], + min_raise_to: raises.then_some(min_raise_to.min(max_raise_to)), + max_raise_to: raises.then_some(max_raise_to), + legal, + allowed_sizes: None, + villains, + seed: crate::rng::split_mix::Rng::seeded(hand ^ (k as u64) << 52).next_u64().0, + history, + }; + Some((spot, start)) + } + + /// The child of node `k` the engine's choice maps to. + fn kind(&self, s: &S1, k: usize, choice: Choice, start: f64) -> Option { + let Knoten::Zug { spieler: p, kinder, .. } = &s.baum.baum.knoten[k] else { return None }; + let finde = |a: Aktion| kinder.iter().copied().find(|c| s.baum.aktion[*c] == Some(a)); + let c = s.baum.beitrag[k]; + let passiv = finde(Aktion::Check).or_else(|| finde(Aktion::Call)); + match choice { + Choice::Fold => finde(Aktion::Fold).or(passiv), + Choice::Check | Choice::Call | Choice::Abstain => passiv, + Choice::Raise { to } => { + let pot = c[0] + c[1]; + let all_in = start + to >= STACK - 1e-6; + let kand: Vec<(f64, usize)> = kinder + .iter() + .filter_map(|x| match s.baum.aktion[*x] { + Some(Aktion::Bet(t) | Aktion::Raise(t)) => Some((t, *x)), + _ => None, + }) + .collect(); + if all_in { + if let Some((_, x)) = kand.iter().find(|(t, _)| *t >= STACK - 1e-9) { + return Some(*x); + } + } + let frac: Vec<(f64, usize)> = kand.iter().map(|(t, x)| ((t - c[*p]) / pot, *x)).collect(); + // The real pot carries the dead small blind; the fraction is taken against it. + harmonisch((start + to - c[*p]) / (pot + SB_TOT), &frac).or(passiv) + } + } + } +} + +impl Gegner for EngineGegner { + fn zeile(&self, s: &S1, k: usize, hand: u64, board: u64, _: usize) -> Vec { + let Knoten::Zug { kinder, .. } = &s.baum.baum.knoten[k] else { return Vec::new() }; + let mut row = vec![0.0; kinder.len()]; + let pick = self.spot(s, k, hand, board).and_then(|(spot, start)| self.kind(s, k, decide(&spot).choice, start)); + let i = pick.and_then(|c| kinder.iter().position(|x| *x == c)).unwrap_or(0); + row[i] = 1.0; + row + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::blueprint::abstraktion::river_cuts; + use crate::blueprint::lbr::lbr_gegen; + use crate::blueprint::s1::Abstraktion; + + #[test] + fn the_engine_answers_on_s1_nodes_and_lbr_runs_against_it() { + let s = S1::neu(Abstraktion { flop: None, turn: None, river: river_cuts(50, 1) }); + let g = EngineGegner::default(); + let m = |t: &str| fast7::mask(&Card::parse_list(t).unwrap()); + // Root: big blind first on the flop. + let (spot, _) = g.spot(&s, s.baum.baum.wurzel, m("As Ad"), m("Ah 7d 2c")).unwrap(); + assert_eq!((spot.hero_seat, spot.pot, spot.to_call), (3, 5.5, 0.0)); + let row = g.zeile(&s, s.baum.baum.wurzel, m("As Ad"), m("Ah 7d 2c"), 0); + assert_eq!(row.iter().sum::(), 1.0); + let t = std::time::Instant::now(); + let e = lbr_gegen(&s, &g, 20, 1, 5); + eprintln!("LBR vs engine (20 hands, no tables): {:+.0} bb/100, {:?} per hand", e.bb100, t.elapsed() / 20); + } +} diff --git a/src/blueprint/lbr.rs b/src/blueprint/lbr.rs index cedacc39..7d79ff6b 100644 --- a/src/blueprint/lbr.rs +++ b/src/blueprint/lbr.rs @@ -75,8 +75,33 @@ fn gegen(eq: &[f32], w: &[f64]) -> f64 { if b > 0.0 { a / b } else { 0.5 } } -/// One hand with LBR in seat `l`; returns LBR's result in bb. -fn hand(s: &S1, tab: &Tabellen, l: usize, rng: &mut Zufall) -> f64 { +/// The player LBR exploits: its action probabilities at an S1 decision node. +pub trait Gegner: Sync { + /// Row over the node's children for `hand` (combo index `combo`) on the street's `board`; + /// `klasse` is the hand's blueprint class there. + fn zeile(&self, s: &S1, k: usize, hand: u64, board: u64, klasse: usize) -> Vec; +} + +/// The blueprint's average strategy as the opponent. +pub struct Blaupause<'a>(pub &'a Tabellen); + +impl Gegner for Blaupause<'_> { + fn zeile(&self, s: &S1, k: usize, _: u64, _: u64, klasse: usize) -> Vec { + let n = match &s.baum.baum.knoten[k] { + Knoten::Zug { kinder, .. } => kinder.len(), + Knoten::Ende(_) => 0, + }; + self.0.durchschnitt(k, klasse, n) + } +} + +/// One hand with LBR in seat `l`; returns LBR's result in bb. Rows are cached per hand (the +/// engine opponent is expensive to ask). +fn hand(s: &S1, g: &G, l: usize, rng: &mut Zufall) -> f64 { + let mut cache: std::collections::HashMap<(usize, usize), Vec> = std::collections::HashMap::new(); + let mut zeile = |k: usize, i: usize, board: u64, klasse: usize| -> Vec { + cache.entry((k, i)).or_insert_with(|| g.zeile(s, k, s.alle[i], board, klasse)).clone() + }; let o = 1 - l; let d = s.ziehen(rng); let baum = &s.baum; @@ -105,7 +130,7 @@ fn hand(s: &S1, tab: &Tabellen, l: usize, rng: &mut Zufall) -> f64 { } let n = kinder.len(); if spieler == o { - let sigma = tab.durchschnitt(k, s.klasse_von(d.hand[o], board, strasse, &ehs_river), n); + let sigma = zeile(k, super::abstraktion::combo_index(d.hand[o]), board, s.klasse_von(d.hand[o], board, strasse, &ehs_river)); let mut x = rng.unit(); let mut a = 0; while a + 1 < n && x >= sigma[a] { @@ -114,7 +139,7 @@ fn hand(s: &S1, tab: &Tabellen, l: usize, rng: &mut Zufall) -> f64 { } for i in 0..w.len() { if w[i] > 0.0 { - w[i] *= tab.durchschnitt(k, klassen[i], n)[a]; + w[i] *= zeile(k, i, board, klassen[i])[a]; } } k = kinder[a]; @@ -135,11 +160,10 @@ fn hand(s: &S1, tab: &Tabellen, l: usize, rng: &mut Zufall) -> f64 { // The opponent's fold probability per combo at the child node (fold = child 0). let (mut fold, mut all) = (0.0, 0.0); let mut call_w = vec![0f64; w.len()]; - if let Knoten::Zug { kinder: ck, .. } = &baum.baum.knoten[kind] { - let m = ck.len(); + if let Knoten::Zug { .. } = &baum.baum.knoten[kind] { for i in 0..w.len() { if w[i] > 0.0 { - let pf = tab.durchschnitt(kind, klassen[i], m)[0]; + let pf = zeile(kind, i, board, klassen[i])[0]; fold += w[i] * pf; all += w[i]; call_w[i] = w[i] * (1.0 - pf); @@ -159,8 +183,13 @@ fn hand(s: &S1, tab: &Tabellen, l: usize, rng: &mut Zufall) -> f64 { } } -/// LBR over `haende` hands (alternating seats) on `threads` threads. +/// LBR against the blueprint over `haende` hands (alternating seats) on `threads` threads. pub fn lbr(s: &S1, tab: &Tabellen, haende: usize, threads: usize, seed: u64) -> Ergebnis { + lbr_gegen(s, &Blaupause(tab), haende, threads, seed) +} + +/// LBR against any opponent over `haende` hands (alternating seats) on `threads` threads. +pub fn lbr_gegen(s: &S1, g: &G, haende: usize, threads: usize, seed: u64) -> Ergebnis { let je = haende.div_ceil(threads.max(1)); let teile: Vec<[(f64, f64, usize); 2]> = std::thread::scope(|sc| { let hs: Vec<_> = (0..threads.max(1) as u64) @@ -170,7 +199,7 @@ pub fn lbr(s: &S1, tab: &Tabellen, haende: usize, threads: usize, seed: u64) -> let mut acc = [(0.0, 0.0, 0usize); 2]; for i in 0..je { let l = i % 2; - let v = hand(s, tab, l, &mut rng); + let v = hand(s, g, l, &mut rng); acc[l].0 += v; acc[l].1 += v * v; acc[l].2 += 1; diff --git a/src/blueprint/mod.rs b/src/blueprint/mod.rs index f60eaf41..a8d99291 100644 --- a/src/blueprint/mod.rs +++ b/src/blueprint/mod.rs @@ -1,6 +1,7 @@ //! Offline-Grundstrategie (Plan E2): Abstraktion und Loeser. pub mod abstraktion; +pub mod engine_gegner; pub mod iso; pub mod lbr; pub mod mccfr; diff --git a/src/blueprint/ranges.rs b/src/blueprint/ranges.rs index 2bd72112..dc4bfbdb 100644 --- a/src/blueprint/ranges.rs +++ b/src/blueprint/ranges.rs @@ -1,347 +1,347 @@ -//! Ranges of both players from the blueprint (plan E2e): the input the river game was missing. -//! -//! A real spot is mapped onto scenario S1 when it is one: button opened, small blind folded, big -//! blind called, heads-up from the flop on, about 100 bb deep. The played postflop line is walked -//! through the S1 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, S1, STACK}; -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, - /// S1 player of the hero (0 = big blind, 1 = button). - pub hero_spieler: usize, - /// The S1 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. -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 S1 seats of a spot: (big blind seat, button seat), if the preflop was exactly S1. -fn s1_sitze(spot: &Spot) -> Option<(u8, u8)> { - if spot.variant != crate::variant::Variant::Nlhe || spot.seats < 3 { - return None; - } - let button = spot.button_seat?; - let bb = spot.history.iter().find(|r| r.action == SeenAction::PostBigBlind)?.seat; - let mut raised = false; - let mut called = 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 != button && r.seat != bb => {} - SeenAction::Raise | SeenAction::Bet if r.seat == button && !raised => { - let to = r.amount? / spot.big_blind; - if !(2.0..=3.0).contains(&to) { - return None; - } - raised = true; - } - SeenAction::Call if r.seat == bb && raised && !called => called = true, - _ => return None, - } - } - (raised && called).then_some((bb, button)) -} - -fn karten_maske(cards: &[Card]) -> u64 { - fast7::mask(cards) -} - -static GRUND: std::sync::OnceLock> = std::sync::OnceLock::new(); - -/// The S1 blueprint, loaded once from `$GRUNDSTRATEGIE/abstraktion/` and -/// `$GRUNDSTRATEGIE/grundstrategie/s1.ckpt`; `None` without the variable or the files. -pub fn grundstrategie() -> Option<&'static (S1, Tabellen)> { - GRUND - .get_or_init(|| { - let dir = std::path::PathBuf::from(std::env::var_os("GRUNDSTRATEGIE")?); - let s = S1::neu(super::s1::Abstraktion::laden(&dir.join("abstraktion")).ok()?); - let mut tab = Tabellen::neu(&s); - tab.datei_lesen(&dir.join("grundstrategie").join("s1.ckpt")).then_some((s, tab)) - }) - .as_ref() -} - -/// Weighted combo lists (hero, villain) for the river game from the blueprint, if the spot is S1. -pub fn gewichtete_listen(spot: &Spot) -> Option<(Vec<(Vec, f64)>, Vec<(Vec, f64)>)> { - let (s, tab) = grundstrategie()?; - 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 S1 or the line leaves it. -pub fn ranges(s: &S1, tab: &Tabellen, spot: &Spot) -> Option { - let (bb, btn) = s1_sitze(spot)?; - let hero_spieler = if spot.hero_seat == bb { 0 } else if spot.hero_seat == btn { 1 } else { return None }; - let villain_seat = if hero_spieler == 0 { btn } else { bb }; - 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 == bb { 0 } else if r.seat == btn { 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 >= STACK { (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; - 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"); - } - - #[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 scenario S1 when it is one: button opened, small blind folded, big +//! blind called, heads-up from the flop on, about 100 bb deep. The played postflop line is walked +//! through the S1 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, S1, STACK}; +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, + /// S1 player of the hero (0 = big blind, 1 = button). + pub hero_spieler: usize, + /// The S1 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 S1 seats of a spot: (big blind seat, button seat), if the preflop was exactly S1. +fn s1_sitze(spot: &Spot) -> Option<(u8, u8)> { + if spot.variant != crate::variant::Variant::Nlhe || spot.seats < 3 { + return None; + } + let button = spot.button_seat?; + let bb = spot.history.iter().find(|r| r.action == SeenAction::PostBigBlind)?.seat; + let mut raised = false; + let mut called = 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 != button && r.seat != bb => {} + SeenAction::Raise | SeenAction::Bet if r.seat == button && !raised => { + let to = r.amount? / spot.big_blind; + if !(2.0..=3.0).contains(&to) { + return None; + } + raised = true; + } + SeenAction::Call if r.seat == bb && raised && !called => called = true, + _ => return None, + } + } + (raised && called).then_some((bb, button)) +} + +fn karten_maske(cards: &[Card]) -> u64 { + fast7::mask(cards) +} + +static GRUND: std::sync::OnceLock> = std::sync::OnceLock::new(); + +/// The S1 blueprint, loaded once from `$GRUNDSTRATEGIE/abstraktion/` and +/// `$GRUNDSTRATEGIE/grundstrategie/s1.ckpt`; `None` without the variable or the files. +pub fn grundstrategie() -> Option<&'static (S1, Tabellen)> { + GRUND + .get_or_init(|| { + let dir = std::path::PathBuf::from(std::env::var_os("GRUNDSTRATEGIE")?); + let s = S1::neu(super::s1::Abstraktion::laden(&dir.join("abstraktion")).ok()?); + let mut tab = Tabellen::neu(&s); + tab.datei_lesen(&dir.join("grundstrategie").join("s1.ckpt")).then_some((s, tab)) + }) + .as_ref() +} + +/// Weighted combo lists (hero, villain) for the river game from the blueprint, if the spot is S1. +pub fn gewichtete_listen(spot: &Spot) -> Option<(Vec<(Vec, f64)>, Vec<(Vec, f64)>)> { + let (s, tab) = grundstrategie()?; + 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 S1 or the line leaves it. +pub fn ranges(s: &S1, tab: &Tabellen, spot: &Spot) -> Option { + let (bb, btn) = s1_sitze(spot)?; + let hero_spieler = if spot.hero_seat == bb { 0 } else if spot.hero_seat == btn { 1 } else { return None }; + let villain_seat = if hero_spieler == 0 { btn } else { bb }; + 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 == bb { 0 } else if r.seat == btn { 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 >= STACK { (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; + 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"); + } + + #[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/blueprint/s1.rs b/src/blueprint/s1.rs index 3f1fdd3d..b5db5038 100644 --- a/src/blueprint/s1.rs +++ b/src/blueprint/s1.rs @@ -49,6 +49,8 @@ pub struct Einsatzbaum { pub aktion: Vec>, /// Contributions of both players (preflop included) when the node is reached. pub beitrag: Vec<[f64; 2]>, + /// Parent of every node (`usize::MAX` for the root). + pub eltern: Vec, } struct Bauer { @@ -126,7 +128,13 @@ impl Einsatzbaum { pub fn s1() -> Einsatzbaum { let mut b = Bauer { knoten: Vec::new(), enden: Vec::new(), aktion: Vec::new(), beitrag: Vec::new() }; let wurzel = b.zug(0, [OPEN, OPEN], 0, 0, false, None); - Einsatzbaum { baum: Baum { knoten: b.knoten, wurzel }, enden: b.enden, aktion: b.aktion, beitrag: b.beitrag } + let mut eltern = vec![usize::MAX; b.knoten.len()]; + for (i, k) in b.knoten.iter().enumerate() { + if let Knoten::Zug { kinder, .. } = k { + kinder.iter().for_each(|c| eltern[*c] = i); + } + } + Einsatzbaum { baum: Baum { knoten: b.knoten, wurzel }, enden: b.enden, aktion: b.aktion, beitrag: b.beitrag, eltern } } }