diff --git a/messung_solver/abdeckung-turn.json b/messung_solver/abdeckung-turn.json new file mode 100644 index 00000000..993d3a8d --- /dev/null +++ b/messung_solver/abdeckung-turn.json @@ -0,0 +1,44 @@ +{ + "TURN/1": { + "anfragen": 478, + "solver": 427, + "klassen": { + "solver": 427, + "e3": 43, + "heuristik": 8 + }, + "p50_ms": 2045.4059000039706, + "p99_ms": 3780.8470000018133, + "max_ms": 4345.02930000599 + }, + "TURN/2": { + "anfragen": 88, + "solver": 0, + "klassen": { + "heuristik": 88 + }, + "p50_ms": 0.0, + "p99_ms": 0.0, + "max_ms": 0 + }, + "TURN/3": { + "anfragen": 7, + "solver": 0, + "klassen": { + "heuristik": 7 + }, + "p50_ms": 0.0, + "p99_ms": 0.0, + "max_ms": 0 + }, + "TURN/4": { + "anfragen": 2, + "solver": 0, + "klassen": { + "heuristik": 2 + }, + "p50_ms": 0.0, + "p99_ms": 0.0, + "max_ms": 0 + } +} \ No newline at end of file diff --git a/messung_solver/abdeckung-turn.txt b/messung_solver/abdeckung-turn.txt new file mode 100644 index 00000000..7fb894dc --- /dev/null +++ b/messung_solver/abdeckung-turn.txt @@ -0,0 +1,6 @@ +575 eindeutige Anfragen, Schalter ['SOLVER_RIVER=1', 'SOLVER_TURN=1', 'GRUNDSTRATEGIE=D:\\Projects\\pokerfreak\\.claude\\worktrees\\engine-lecks-angreifen-de7b88\\daten', 'MDF_UNREAD=0', 'TURN_SPIEL=grund'] +TURN 1-Gegner: 478 Solver 427 ( 89.3 %) Zeit Solver p50 2045 p99 3781 max 4345 ms solver=427 e3=43 heuristik=8 +TURN 2-Gegner: 88 Solver 0 ( 0.0 %) Zeit Solver p50 0 p99 0 max 0 ms heuristik=88 +TURN 3-Gegner: 7 Solver 0 ( 0.0 %) Zeit Solver p50 0 p99 0 max 0 ms heuristik=7 +TURN 4-Gegner: 2 Solver 0 ( 0.0 %) Zeit Solver p50 0 p99 0 max 0 ms heuristik=2 +TURN alle Anfragen: p50 1191 p99 3753 max 4345 ms diff --git a/src/cfr/turn_river_game.rs b/src/cfr/turn_river_game.rs index 746d8c79..6e40e616 100644 --- a/src/cfr/turn_river_game.rs +++ b/src/cfr/turn_river_game.rs @@ -260,6 +260,10 @@ pub struct TrSolver { /// The same as dense showdown matrices, `2 eq - 1` with overlapping pairs 0: per card, /// `[p0 rows (n0 x n1), p1 rows (n1 x n0)]`. eqm: Vec<[Vec; 2]>, + /// Node locks (read layer, restricted Nash response): at a locked decision node the player plays + /// `(1 - w) * sigma + w * believed`, `believed` = one row of `a` probabilities per own hand (the + /// same for every dealt card). `None` everywhere = the plain equilibrium solve. + lock: Vec, f64)>>, weights: [Vec; 2], rc: Vec, /// Deal weight of one sampled river card. @@ -364,7 +368,7 @@ impl TrSolver { } 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, eq: None, eqm: Vec::new(), weights, rc, wr, regret, sums, iterations: 0 } + TrSolver { game: std::sync::Arc::new(game), n, cards, masks, same, eq: None, eqm: Vec::new(), lock: Vec::new(), weights, rc, wr, regret, sums, iterations: 0 } } /// Stage C: the game's first street is the FLOP (`board` = three flop cards), the dealt card is the @@ -451,6 +455,24 @@ impl TrSolver { .collect() } + /// Lock decision `node` toward `believed` (one row of action probabilities per hand of the acting + /// player, `hands(player) * actions`) with weight `w` in (0, 1]. `w <= 0` changes nothing. + pub fn lock(&mut self, node: usize, believed: Vec, w: f64) { + let Some(TNode::Dec { player, kids, .. }) = self.game.nodes.get(node) else { return }; + if w <= 0.0 || believed.len() != self.n[*player] * kids.len() { + return; + } + if self.lock.len() < self.game.nodes.len() { + self.lock.resize(self.game.nodes.len(), None); + } + self.lock[node] = Some((believed, w.min(1.0))); + } + + /// Card masks of `player`'s hands, in solver order. + pub fn masks(&self, player: usize) -> &[u64] { + &self.masks[player] + } + pub fn hands(&self, player: usize) -> usize { self.n[player] } @@ -590,6 +612,11 @@ impl TrSolver { 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 let Some(Some((believed, w))) = self.lock.get(node) { + for (x, b) in sigma.iter_mut().zip(believed) { + *x = (1.0 - w) * *x + w * b; + } + } if player == p { let values: Vec> = kids .iter() diff --git a/src/engine/flop_spieler.rs b/src/engine/flop_spieler.rs index 7a83e70d..90c9cdff 100644 --- a/src/engine/flop_spieler.rs +++ b/src/engine/flop_spieler.rs @@ -1,229 +1,245 @@ -//! Stage C of "solver everywhere": the heads-up FLOP decided by an equilibrium solve over real combos. -//! Switch `SOLVER_FLOP` (default off). -//! -//! - **Game:** `cfr::turn_river_game` with its first street as the flop: flop betting (33 %, 75 % pot, -//! all-in, one raise), a chance node over `turn_cards` evenly strided turn cards, turn betting (75 % -//! pot, all-in, one raise), then the showdown as the EXACT equity over every river card per combo pair -//! (`TrSolver::with_river_equity`, card removal included). The observed flop line is in the tree. -//! - **Ranges** as in stages A/B: blueprint where it recognises the spot, else the range model of the -//! action history (`river_spieler::model_lists`); pruned to the heaviest `max_combos` per player. -//! Hero's real hand, if pruned away, joins at its weight (or a token weight) in an uncached solve. -//! - **Time:** fixed iterations with a wall-time budget; under `MIN_ITERS` the heuristic decides. -//! -//! Named approximations: no river betting (the river is a check-down inside the flop game; the river -//! solver re-solves it when it comes), `turn_cards` of 49 turn cards, pruned ranges, two flop sizes. -//! The turn and river are re-solved at their own decisions (stages B and A), so only the flop action -//! comes from this game. - -use crate::card::Card; -use crate::cfr::river_game::Act; -use crate::cfr::turn_river_game::{build, Menu, TNode, TrBets, TrSolver}; -use crate::engine::river_subgame::legal_choice; -use crate::engine::turn_game::{prune, street_line, TurnConfig}; -use crate::game::{Decision, Spot, Street}; -use crate::hand::fast7; -use crate::rng::Rng; -use std::collections::HashMap; -use std::hash::{Hash, Hasher}; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::{Arc, Mutex}; - -static ON: AtomicBool = AtomicBool::new(false); - -pub fn set_flop_spieler(on: bool) { - ON.store(on, Ordering::Relaxed); -} - -pub fn flop_spieler() -> bool { - ON.load(Ordering::Relaxed) -} - -/// `SOLVER_FLOP=1`. -pub fn from_env() -> bool { - matches!(std::env::var("SOLVER_FLOP").as_deref(), Ok("1") | Ok("an")) -} - -/// Size and budget (`FLOP_COMBOS`, `FLOP_CARDS`, `FLOP_ITERS` override). -#[derive(Clone, Copy, Debug)] -pub struct FlopConfig { - pub max_combos: usize, - pub turn_cards: usize, - pub iterations: u32, - pub budget_ms: f64, -} - -pub const MIN_ITERS: u32 = 60; - -impl FlopConfig { - pub const STANDARD: FlopConfig = FlopConfig { max_combos: 120, turn_cards: 8, iterations: 200, budget_ms: 1800.0 }; - - pub fn from_env() -> FlopConfig { - let num = |k: &str, d: usize| std::env::var(k).ok().and_then(|s| s.parse().ok()).filter(|n| *n > 0).unwrap_or(d); - FlopConfig { - max_combos: num("FLOP_COMBOS", Self::STANDARD.max_combos), - turn_cards: num("FLOP_CARDS", Self::STANDARD.turn_cards), - iterations: num("FLOP_ITERS", Self::STANDARD.iterations as usize) as u32, - budget_ms: Self::STANDARD.budget_ms, - } - } -} - -pub struct Solved { - rows: Vec, - acts: Vec, - hero_masks: Vec, - pub millis: f64, - pub iterations: u32, - pub combos: [usize; 2], - pub nodes: usize, - pub source: &'static str, -} - -/// The flop+turn betting menus. -pub fn flop_bets(pot: f64, stack: f64, first: usize) -> TrBets { - TrBets { - pot, - stack, - first, - turn: Menu { fracs: vec![0.33, 0.75], raise_mult: vec![3.0], max_raises: 1, allin: true }, - river: Menu { fracs: vec![0.75], raise_mult: vec![3.0], max_raises: 1, allin: true }, - } -} - -/// Solve the flop of `spot` with these ranges; `keep` = a hero hand that must be in the game. -pub fn solve_flop(spot: &Spot, hero: &[(Vec, f64)], villain_list: &[(Vec, f64)], cfg: &FlopConfig, keep: Option, source: &'static str) -> Option { - if spot.street != Street::Flop || spot.board.len() != 3 || spot.live_villains().count() != 1 { - return None; - } - let villain = spot.live_villains().next()?; - let (first, forced, c) = street_line(spot, villain, Street::Flop); - 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 pc = TurnConfig { max_combos: cfg.max_combos, cover: 0.95, ..TurnConfig::STANDARD }; - let hands = [prune(hero, board, &pc, keep), prune(villain_list, board, &pc, None)]; - if hands[0].masks.is_empty() || hands[1].masks.is_empty() { - return None; - } - let game = build(&flop_bets(pot, stack, first), &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.turn_cards)).with_river_equity(board); - let mut done = 0; - while done < cfg.iterations { - solver.iterate(); - done += 1; - if done % 5 == 0 && started.elapsed().as_secs_f64() * 1e3 > cfg.budget_ms { - break; - } - } - if done < MIN_ITERS { - return None; - } - let strategy = solver.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, iterations: done, combos, nodes, source }) -} - -fn decide_from(spot: &Spot, solved: &Solved, 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]; - let (draw, _) = Rng::seeded(spot.seed).unit(); - let mut acc = 0.0; - let mut pick = a.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 p = row.get(pick).copied().unwrap_or(0.0); - Some(Decision::new( - legal_choice(spot, act), - p.clamp(0.0, 1.0), - format!( - "solver flop ({}): {}x{} combos, {} nodes, {} iters, {act:?} p {p:.2}, {:.0} ms", - solved.source, solved.combos[0], solved.combos[1], solved.nodes, solved.iterations, solved.millis - ), - )) -} - -static CACHE: Mutex>>> = Mutex::new(None); -const CACHE_MAX: usize = 2048; - -fn public_key(spot: &Spot, cfg: &FlopConfig) -> 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); - format!("{:?}", v.profile).hash(&mut h); - }); - (spot.hero_seat, spot.button_seat, spot.seats, cfg.max_combos, cfg.turn_cards, cfg.iterations).hash(&mut h); - h.finish() -} - -/// The live stage-C decision, or `None` and the heuristic keeps it. -pub fn flop_spieler_decision(raw: &Spot) -> Option { - if !flop_spieler() || raw.street != Street::Flop || raw.hero_cards.len() != 2 || raw.board.len() != 3 { - return None; - } - let gated = crate::engine::read_gate::gate_reads(raw); - let spot = &gated; - if spot.live_villains().count() != 1 { - return None; - } - let cfg = FlopConfig::from_env(); - let hero_mask = fast7::mask(&spot.hero_cards); - if hero_mask & fast7::mask(&spot.board) != 0 { - return None; - } - let lists = || -> Option<(Vec<(Vec, f64)>, Vec<(Vec, f64)>, &'static str)> { - if let Some((h, v)) = crate::blueprint::ranges::gewichtete_listen_offen(spot) { - return Some((h, v, "grund")); - } - let (h, v) = crate::engine::river_spieler::model_lists(spot)?; - Some((h, v, "modell")) - }; - let key = public_key(spot, &cfg); - let cached = CACHE.lock().ok().and_then(|m| m.as_ref().and_then(|m| m.get(&key).cloned())); - let solved = match cached { - Some(s) => s, - None => { - let (hero, villain, source) = lists()?; - let solved = Arc::new(solve_flop(spot, &hero, &villain, &cfg, None, source)?); - 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 - } - }; - if let Some(d) = decide_from(spot, &solved, hero_mask) { - return Some(d); - } - let (hero, villain, source) = lists()?; - let own = solve_flop(spot, &hero, &villain, &cfg, Some(hero_mask), source)?; - decide_from(spot, &own, hero_mask) -} - -#[cfg(test)] -mod tests; +//! Stage C of "solver everywhere": the heads-up FLOP decided by an equilibrium solve over real combos. +//! Switch `SOLVER_FLOP` (default off). +//! +//! - **Game:** `cfr::turn_river_game` with its first street as the flop: flop betting (33 %, 75 % pot, +//! all-in, one raise), a chance node over `turn_cards` evenly strided turn cards, turn betting (75 % +//! pot, all-in, one raise), then the showdown as the EXACT equity over every river card per combo pair +//! (`TrSolver::with_river_equity`, card removal included). The observed flop line is in the tree. +//! - **Ranges** as in stages A/B: blueprint where it recognises the spot, else the range model of the +//! action history (`river_spieler::model_lists`); pruned to the heaviest `max_combos` per player. +//! Hero's real hand, if pruned away, joins at its weight (or a token weight) in an uncached solve. +//! - **Time:** fixed iterations with a wall-time budget; under `MIN_ITERS` the heuristic decides. +//! +//! Named approximations: no river betting (the river is a check-down inside the flop game; the river +//! solver re-solves it when it comes), `turn_cards` of 49 turn cards, pruned ranges, two flop sizes. +//! The turn and river are re-solved at their own decisions (stages B and A), so only the flop action +//! comes from this game. + +use crate::card::Card; +use crate::cfr::river_game::Act; +use crate::cfr::turn_river_game::{build, Menu, TNode, TrBets, TrSolver}; +use crate::engine::river_subgame::legal_choice; +use crate::engine::turn_game::{prune, street_line, TurnConfig}; +use crate::game::{Decision, Spot, Street}; +use crate::hand::fast7; +use crate::rng::Rng; +use std::collections::HashMap; +use std::hash::{Hash, Hasher}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; + +static ON: AtomicBool = AtomicBool::new(false); +/// Budget override in ms (0 = `STANDARD`); tests under parallel load use it. +static BUDGET_OVERRIDE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +#[cfg(test)] +pub(crate) fn set_budget_override(ms: u64) { + BUDGET_OVERRIDE.store(ms, Ordering::Relaxed); +} + +pub fn set_flop_spieler(on: bool) { + ON.store(on, Ordering::Relaxed); +} + +pub fn flop_spieler() -> bool { + ON.load(Ordering::Relaxed) +} + +/// `SOLVER_FLOP=1`. +pub fn from_env() -> bool { + matches!(std::env::var("SOLVER_FLOP").as_deref(), Ok("1") | Ok("an")) +} + +/// Size and budget (`FLOP_COMBOS`, `FLOP_CARDS`, `FLOP_ITERS` override). +#[derive(Clone, Copy, Debug)] +pub struct FlopConfig { + pub max_combos: usize, + pub turn_cards: usize, + pub iterations: u32, + pub budget_ms: f64, +} + +pub const MIN_ITERS: u32 = 60; + +impl FlopConfig { + pub const STANDARD: FlopConfig = FlopConfig { max_combos: 120, turn_cards: 8, iterations: 200, budget_ms: 1800.0 }; + + pub fn from_env() -> FlopConfig { + let num = |k: &str, d: usize| std::env::var(k).ok().and_then(|s| s.parse().ok()).filter(|n| *n > 0).unwrap_or(d); + FlopConfig { + max_combos: num("FLOP_COMBOS", Self::STANDARD.max_combos), + turn_cards: num("FLOP_CARDS", Self::STANDARD.turn_cards), + iterations: num("FLOP_ITERS", Self::STANDARD.iterations as usize) as u32, + budget_ms: match BUDGET_OVERRIDE.load(Ordering::Relaxed) { + 0 => Self::STANDARD.budget_ms, + ms => ms as f64, + }, + } + } +} + +pub struct Solved { + rows: Vec, + acts: Vec, + hero_masks: Vec, + pub millis: f64, + pub iterations: u32, + pub combos: [usize; 2], + pub nodes: usize, + pub source: &'static str, +} + +/// The flop+turn betting menus. +pub fn flop_bets(pot: f64, stack: f64, first: usize) -> TrBets { + TrBets { + pot, + stack, + first, + turn: Menu { fracs: vec![0.33, 0.75], raise_mult: vec![3.0], max_raises: 1, allin: true }, + river: Menu { fracs: vec![0.75], raise_mult: vec![3.0], max_raises: 1, allin: true }, + } +} + +/// Solve the flop of `spot` with these ranges; `keep` = a hero hand that must be in the game. +pub fn solve_flop(spot: &Spot, hero: &[(Vec, f64)], villain_list: &[(Vec, f64)], cfg: &FlopConfig, keep: Option, source: &'static str) -> Option { + if spot.street != Street::Flop || spot.board.len() != 3 || spot.live_villains().count() != 1 { + return None; + } + let villain = spot.live_villains().next()?; + let (first, forced, c) = street_line(spot, villain, Street::Flop); + 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 pc = TurnConfig { max_combos: cfg.max_combos, cover: 0.95, ..TurnConfig::STANDARD }; + let hands = [prune(hero, board, &pc, keep), prune(villain_list, board, &pc, None)]; + if hands[0].masks.is_empty() || hands[1].masks.is_empty() { + return None; + } + let game = build(&flop_bets(pot, stack, first), &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.turn_cards)).with_river_equity(board); + let mut done = 0; + while done < cfg.iterations { + solver.iterate(); + done += 1; + if done % 5 == 0 && started.elapsed().as_secs_f64() * 1e3 > cfg.budget_ms { + break; + } + } + if done < MIN_ITERS { + return None; + } + let strategy = solver.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, iterations: done, combos, nodes, source }) +} + +fn decide_from(spot: &Spot, solved: &Solved, 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]; + let (draw, _) = Rng::seeded(spot.seed).unit(); + let mut acc = 0.0; + let mut pick = a.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 p = row.get(pick).copied().unwrap_or(0.0); + Some(Decision::new( + legal_choice(spot, act), + p.clamp(0.0, 1.0), + format!( + "solver flop ({}): {}x{} combos, {} nodes, {} iters, {act:?} p {p:.2}, {:.0} ms", + solved.source, solved.combos[0], solved.combos[1], solved.nodes, solved.iterations, solved.millis + ), + )) +} + +static CACHE: Mutex>>> = Mutex::new(None); +const CACHE_MAX: usize = 2048; + +fn public_key(spot: &Spot, cfg: &FlopConfig) -> 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); + format!("{:?}", v.profile).hash(&mut h); + }); + (spot.hero_seat, spot.button_seat, spot.seats, cfg.max_combos, cfg.turn_cards, cfg.iterations).hash(&mut h); + h.finish() +} + +/// The live stage-C decision, or `None` and the heuristic keeps it. +pub fn flop_spieler_decision(raw: &Spot) -> Option { + if !flop_spieler() || raw.street != Street::Flop || raw.hero_cards.len() != 2 || raw.board.len() != 3 { + return None; + } + let gated = crate::engine::read_gate::gate_reads(raw); + let spot = &gated; + if spot.live_villains().count() != 1 { + return None; + } + let begun = std::time::Instant::now(); + let cfg = FlopConfig::from_env(); + let hero_mask = fast7::mask(&spot.hero_cards); + if hero_mask & fast7::mask(&spot.board) != 0 { + return None; + } + let read = crate::engine::river_spieler::read_of(raw); + let lists = || crate::engine::river_spieler::solver_lists(spot, crate::engine::river_spieler::RiverSpieler::An, read.as_ref()); + let raw_profile = read.as_ref().map(|_| format!("{:?}", raw.live_villains().next().map(|v| v.profile.clone()))); + let key = { + let mut h = std::collections::hash_map::DefaultHasher::new(); + (public_key(spot, &cfg), raw_profile).hash(&mut h); + h.finish() + }; + let cached = CACHE.lock().ok().and_then(|m| m.as_ref().and_then(|m| m.get(&key).cloned())); + let solved = match cached { + Some(s) => s, + None => { + let (hero, villain, source) = lists()?; + let solved = Arc::new(solve_flop(spot, &hero, &villain, &cfg, None, source)?); + 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 + } + }; + if let Some(d) = decide_from(spot, &solved, hero_mask) { + return Some(d); + } + // Hero's hand was pruned away: one more solve with it kept, in what is left of the budget. + let left = cfg.budget_ms - begun.elapsed().as_secs_f64() * 1e3; + if left <= 0.0 { + return None; + } + let (hero, villain, source) = lists()?; + let own = solve_flop(spot, &hero, &villain, &FlopConfig { budget_ms: left, ..cfg }, Some(hero_mask), source)?; + decide_from(spot, &own, hero_mask) +} + +#[cfg(test)] +mod tests; diff --git a/src/engine/flop_spieler/tests.rs b/src/engine/flop_spieler/tests.rs index a2826931..fd5e112d 100644 --- a/src/engine/flop_spieler/tests.rs +++ b/src/engine/flop_spieler/tests.rs @@ -75,6 +75,7 @@ fn off_decides_nothing_and_on_decides_heads_up_flops() { set_flop_spieler(false); assert!(flop_spieler_decision(&checked_to("Ks Kd")).is_none()); set_flop_spieler(true); + set_budget_override(60_000); for spot in [checked_to("Ks Kd"), facing_bet("Qc Jc"), facing_bet("9s 8s"), checked_to("4h 3h")] { let d = flop_spieler_decision(&spot).expect("heads-up flop is in the slice"); assert!(d.reason.contains("solver flop"), "{}", d.reason); @@ -87,6 +88,7 @@ fn off_decides_nothing_and_on_decides_heads_up_flops() { let mut multi = checked_to("Ks Kd"); multi.villains.push(Villain { seat: 1, stack: 90.0, folded: false, profile: None }); assert!(flop_spieler_decision(&multi).is_none()); + set_budget_override(0); set_flop_spieler(false); } diff --git a/src/engine/river_spieler.rs b/src/engine/river_spieler.rs index 91eec12a..74ac5478 100644 --- a/src/engine/river_spieler.rs +++ b/src/engine/river_spieler.rs @@ -24,6 +24,7 @@ use crate::card::Card; use crate::cfr::river_game::Act; use crate::cfr::turn_river_game::{build_river, Hands, Menu, TNode, TrBets, TrSolver}; +use crate::exploit::range_read::RangeRead; use crate::engine::river_subgame::{legal_choice, river_line}; use crate::game::{Decision, Spot, Street, Villain}; use crate::hand::fast7; @@ -131,7 +132,7 @@ fn hands_of(list: &[(Vec, f64)], dead: u64, fill: bool) -> Hands { const TOKEN: f64 = 1e-6; /// Solve the river of `spot`'s public state with these ranges; every hero hand gets a strategy. `None` off the heads-up river slice, off the tree, or when the budget left too few iterations. -pub fn solve_river(spot: &Spot, hero: &[(Vec, f64)], villain_list: &[(Vec, f64)], source: &'static str) -> Option { +pub fn solve_river(spot: &Spot, hero: &[(Vec, f64)], villain_list: &[(Vec, f64)], source: &'static str, read: Option<&RangeRead>) -> Option { if spot.street != Street::River || spot.board.len() != 5 || spot.live_villains().count() != 1 { return None; } @@ -160,7 +161,11 @@ pub fn solve_river(spot: &Spot, hero: &[(Vec, f64)], villain_list: &[(Vec< let hero_masks = hands[0].masks.clone(); let acts = game.acts[at].clone(); let nodes = game.nodes.len(); + let villain_weights = hands[1].weights.clone(); let mut solver = TrSolver::with_cards(game, hands, turn, vec![river], 1.0); + if let Some(r) = read { + lock_villain(&mut solver, r, pot, dead, &villain_weights); + } let mut done = 0; while done < ITERS { solver.iterate(); @@ -220,15 +225,120 @@ pub fn model_lists(spot: &Spot) -> Option<(Vec<(Vec, f64)>, Vec<(Vec Some((eins(list(&me)?), eins(list(villain)?))) } -/// The ranges of this spot and where they came from. -fn lists(spot: &Spot, mode: RiverSpieler) -> Option<(Vec<(Vec, f64)>, Vec<(Vec, f64)>, &'static str)> { - if mode == RiverSpieler::An { - if let Some((h, v)) = crate::blueprint::ranges::gewichtete_listen_offen(spot) { - return Some((h, v, "grund")); +/// The read layer (`exploit::range_read`, switch `GEGNER_RANGE=1`, default off): the villain's read from +/// its UNGATED profile, or `None` = the plain solver. +pub fn read_of(raw: &Spot) -> Option { + if std::env::var("GEGNER_RANGE").as_deref() != Ok("1") { + return None; + } + let villain = raw.live_villains().next()?; + RangeRead::from_profile(villain.profile.as_ref()) +} + +/// Weighted mid-rank percentile of each combo's current strength (`fast7` score with `board`) within +/// the list. Exact on the river; current strength only (draw-blind) on flop and turn. +pub fn percentiles(masks: &[u64], weights: &[f64], board: u64) -> Vec { + let score: Vec = masks.iter().map(|m| fast7::score(m | board)).collect(); + let mut order: Vec = (0..masks.len()).collect(); + order.sort_by_key(|i| score[*i]); + let total: f64 = weights.iter().sum::().max(1e-300); + let mut out = vec![0.5; masks.len()]; + let mut below = 0.0; + let mut k = 0; + while k < order.len() { + let mut e = k; + let mut tie = 0.0; + while e < order.len() && score[order[e]] == score[order[k]] { + tie += weights[order[e]]; + e += 1; + } + for &i in &order[k..e] { + out[i] = (below + tie / 2.0) / total; + } + below += tie; + k = e; + } + out +} + +/// The ranges of this spot (hero, villain) and where they came from: the blueprint where it recognises +/// the spot (unless `mode` is `Modell`), else the range model of the action history. THE HOOK of the +/// read layer: with a read, the villain's final weights are tilted by strength percentile +/// (`RangeRead::reweigh`); `read = None` returns the lists unchanged. Used by stages A, B and C. +pub fn solver_lists(spot: &Spot, mode: RiverSpieler, read: Option<&RangeRead>) -> Option<(Vec<(Vec, f64)>, Vec<(Vec, f64)>, &'static str)> { + let (h, mut v, source) = match mode { + RiverSpieler::An => match crate::blueprint::ranges::gewichtete_listen_offen(spot) { + Some((h, v)) => (h, v, "grund"), + None => { + let (h, v) = model_lists(spot)?; + (h, v, "modell") + } + }, + _ => { + let (h, v) = model_lists(spot)?; + (h, v, "modell") + } + }; + if let Some(r) = read.filter(|r| r.confidence > 0.0) { + let board = fast7::mask(&spot.board); + let masks: Vec = v.iter().map(|(c, _)| fast7::mask(c)).collect(); + let weights: Vec = v.iter().map(|(_, w)| *w).collect(); + let pct = percentiles(&masks, &weights, board); + let pairs: Vec<(f64, f64)> = weights.iter().copied().zip(pct).collect(); + for ((_, w), x) in v.iter_mut().zip(r.reweigh(&pairs)) { + *w = x; + } + } + Some((h, v, source)) +} + +/// Value hands bet from this strength percentile up when the believed villain is checked to +/// (as `river_subgame`'s VALUE_RANK). +const BELIEVED_VALUE_RANK: f64 = 0.60; + +/// Lock the villain's river decisions toward the read (restricted Nash response): facing a bet it folds +/// the weakest `fold_to_bet` share of its range and calls the rest (weight = the fold read's trust); +/// checked to, it bets its top `1 - BELIEVED_VALUE_RANK` at the size nearest 75 % pot plus the weakest +/// hands as bluffs so that the air share of the bet is `bluff_share` (weight = the bluff read's trust). +/// Facing a raise it stays free. +fn lock_villain(solver: &mut TrSolver, read: &RangeRead, pot: f64, board: u64, villain_weights: &[f64]) { + let pct = percentiles(solver.masks(1), villain_weights, board); + // The action that led into each node (a raise faced vs an opening bet faced). + let mut incoming: Vec> = vec![None; solver.game.nodes.len()]; + for (k, n) in solver.game.nodes.iter().enumerate() { + if let TNode::Dec { kids, .. } = n { + for (c, kid) in kids.iter().enumerate() { + incoming[*kid] = solver.game.acts[k].get(c).copied(); + } + } + } + let nodes: Vec<(usize, Vec)> = solver + .game + .nodes + .iter() + .enumerate() + .filter_map(|(k, n)| match n { + TNode::Dec { player: 1, .. } => Some((k, solver.game.acts[k].clone())), + _ => None, + }) + .collect(); + for (node, acts) in nodes { + let a = acts.len(); + let facing_bet = acts.contains(&Act::Fold) && matches!(incoming[node], Some(Act::Bet(_))); + if facing_bet { + let Some(f) = read.fold_to_bet(2) else { continue }; + let call = acts.iter().position(|x| *x == Act::Call).unwrap_or(1); + let rows: Vec = pct.iter().flat_map(|p| (0..a).map(move |k| if *p < f { f64::from(k == 0) } else { f64::from(k == call) })).collect(); + solver.lock(node, rows, read.trust(false, 2)); + } else if !acts.contains(&Act::Fold) && acts.first() == Some(&Act::Check) { + let Some((bet, to)) = acts.iter().enumerate().filter_map(|(k, x)| if let Act::Bet(t) = x { Some((k, *t)) } else { None }).min_by(|x, y| (x.1 / pot - 0.75).abs().total_cmp(&(y.1 / pot - 0.75).abs())) else { continue }; + let bs = read.bluff_share(2, to / pot).clamp(0.0, 0.9); + let value = 1.0 - BELIEVED_VALUE_RANK; + let bluff = (value * bs / (1.0 - bs)).min(BELIEVED_VALUE_RANK); + let rows: Vec = pct.iter().flat_map(|p| (0..a).map(move |k| if *p >= BELIEVED_VALUE_RANK || *p < bluff { f64::from(k == bet) } else { f64::from(k == 0) })).collect(); + solver.lock(node, rows, read.trust(true, 2)); } } - let (h, v) = model_lists(spot)?; - Some((h, v, "modell")) } static CACHE: Mutex>>> = Mutex::new(None); @@ -265,13 +375,19 @@ pub fn river_spieler_decision(raw: &Spot) -> Option { if hero_mask & fast7::mask(&spot.board) != 0 { return None; } - let key = public_key(spot, mode); + let read = read_of(raw); + let mut key = public_key(spot, mode); + if read.is_some() { + let mut h = std::collections::hash_map::DefaultHasher::new(); + (key, format!("{:?}", raw.live_villains().next().map(|v| v.profile.clone()))).hash(&mut h); + key = h.finish(); + } let cached = CACHE.lock().ok().and_then(|m| m.as_ref().and_then(|m| m.get(&key).cloned())); let solved = match cached { Some(s) => s, None => { - let (hero, villain, source) = lists(spot, mode)?; - let solved = Arc::new(solve_river(spot, &hero, &villain, source)?); + let (hero, villain, source) = solver_lists(spot, mode, read.as_ref())?; + let solved = Arc::new(solve_river(spot, &hero, &villain, source, read.as_ref())?); if let Ok(mut m) = CACHE.lock() { let map = m.get_or_insert_with(HashMap::new); if map.len() >= CACHE_MAX { diff --git a/src/engine/river_spieler/tests.rs b/src/engine/river_spieler/tests.rs index 9606b04a..4a1d3fcd 100644 --- a/src/engine/river_spieler/tests.rs +++ b/src/engine/river_spieler/tests.rs @@ -1,155 +1,191 @@ -use super::*; -use crate::card::Card; -use crate::game::{ActionKind, ActionRecord, Choice, SeenAction, Spot, Street, Villain}; -use crate::variant::Variant; - -/// 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 line to the river: button (seat 4) opens 2.5, big blind (seat 0) calls; flop check, bet 1.8, -/// call; turn check, check. River pot 9.1 + `pot_extra`; `river` is the river line so far; hero is the -/// button. -fn river_spot(river: &[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)), - rec(Turn, 0, Check, None), - rec(Turn, 4, Check, None), - ]; - h.extend_from_slice(river); - 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 3h").unwrap(), - street: Street::River, - 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 { - river_spot(&[rec(Street::River, 0, SeenAction::Bet, Some(9.0))], hero, 9.0, 9.0) -} - -fn checked_to(hero: &str) -> Spot { - river_spot(&[rec(Street::River, 0, SeenAction::Check, None)], hero, 0.0, 0.0) -} - -fn row_of(spot: &Spot) -> (Vec, Vec) { - let (h, v) = model_lists(spot).expect("model ranges"); - let s = solve_river(spot, &h, &v, "modell").expect("solved"); - let m = fast7::mask(&spot.hero_cards); - let i = s.hero_masks.iter().position(|x| *x == m).expect("every hero hand is in the solve"); - let a = s.acts.len(); - (s.rows[i * a..(i + 1) * a].to_vec(), s.acts.clone()) -} - -fn prob(row: &[f64], acts: &[Act], f: impl Fn(&Act) -> bool) -> f64 { - row.iter().zip(acts).filter(|(_, a)| f(a)).map(|(p, _)| p).sum() -} - -/// Off (the default), the engine's output is untouched: no decision. -#[test] -fn off_decides_nothing() { - let _g = MODE_LOCK.lock().unwrap(); - set_river_spieler(RiverSpieler::Aus); - assert!(river_spieler_decision(&facing_bet("As Ad")).is_none()); -} - -/// On, a heads-up river is decided by the solver, deterministically, with a legal choice. -#[test] -fn on_decides_heads_up_rivers_deterministically() { - let _g = MODE_LOCK.lock().unwrap(); - set_river_spieler(RiverSpieler::Modell); - for spot in [facing_bet("Qc Jc"), checked_to("Qc Jc"), facing_bet("As Ad")] { - let a = river_spieler_decision(&spot).expect("heads-up river is in the slice"); - let b = river_spieler_decision(&spot).expect("cached"); - assert_eq!(a.choice, b.choice); - assert!(a.reason.contains("river solver (modell)"), "{}", a.reason); - match a.choice { - Choice::Fold | Choice::Call => assert!(spot.to_call > 0.0), - Choice::Check => assert_eq!(spot.to_call, 0.0), - Choice::Raise { to } => assert!(to > spot.to_call), - _ => {} - } - } - set_river_spieler(RiverSpieler::Aus); -} - -/// Multiway rivers stay with the heuristic. -#[test] -fn multiway_is_not_in_the_slice() { - let _g = MODE_LOCK.lock().unwrap(); - set_river_spieler(RiverSpieler::Modell); - let mut spot = facing_bet("As Ad"); - spot.villains.push(Villain { seat: 1, stack: 90.0, folded: false, profile: None }); - assert!(river_spieler_decision(&spot).is_none()); - set_river_spieler(RiverSpieler::Aus); -} - -/// Top set never folds to a bet; six-high air facing a pot bet folds most of the time. -#[test] -fn the_nuts_continue_and_air_folds() { - let (row, acts) = row_of(&facing_bet("As Ad")); - assert!(prob(&row, &acts, |a| *a == Act::Fold) < 0.01, "top set folds {row:?}"); - let (row, acts) = row_of(&facing_bet("6s 5s")); - assert!(prob(&row, &acts, |a| *a == Act::Fold) > 0.5, "air calls a pot bet {row:?} {acts:?}"); -} - -/// Checked to in position, top set bets for value. -#[test] -fn top_set_bets_when_checked_to() { - let (row, acts) = row_of(&checked_to("As Ad")); - assert!(prob(&row, &acts, |a| matches!(a, Act::Bet(_))) > 0.8, "{row:?} {acts:?}"); -} - -/// The river-only game: the observed line puts hero at a hero decision on the river, and the solve is -/// close to equilibrium (exact best response in the game, below 1 % of the pot after `ITERS`). -#[test] -fn the_river_game_converges() { - let spot = facing_bet("Qc Jc"); - let (h, v) = model_lists(&spot).unwrap(); - let villain = spot.live_villains().next().unwrap(); - let (first, forced, c) = river_line(&spot, villain); - assert_eq!((first, forced.clone()), (1, vec![Act::Bet(9.0)])); - let pot = spot.pot - c[0] - c[1]; - let bets = TrBets { pot, stack: 95.7, first, turn: river_menu(), river: river_menu() }; - let game = build_river(&bets, &forced); - let at = game.at.unwrap(); - assert!(matches!(game.nodes[at], TNode::Dec { player: 0, street: 1, .. })); - let turn = fast7::mask(&spot.board[..4]); - let river = fast7::bit(spot.board[4]); - let hands = [hands_of(&h, turn | river, false), hands_of(&v, turn | river, false)]; - let mut solver = TrSolver::with_cards(game, hands, turn, vec![river], 1.0); - solver.run(ITERS); - let e = solver.exploitability(&solver.strategy()); - assert!(e.total / pot < 0.01, "exploitability {:.4} of pot {pot}", e.total); -} +use super::*; +use crate::card::Card; +use crate::game::{ActionKind, ActionRecord, Choice, SeenAction, Spot, Street, Villain}; +use crate::variant::Variant; + +/// 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 line to the river: button (seat 4) opens 2.5, big blind (seat 0) calls; flop check, bet 1.8, +/// call; turn check, check. River pot 9.1 + `pot_extra`; `river` is the river line so far; hero is the +/// button. +fn river_spot(river: &[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)), + rec(Turn, 0, Check, None), + rec(Turn, 4, Check, None), + ]; + h.extend_from_slice(river); + 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 3h").unwrap(), + street: Street::River, + 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 { + river_spot(&[rec(Street::River, 0, SeenAction::Bet, Some(9.0))], hero, 9.0, 9.0) +} + +fn checked_to(hero: &str) -> Spot { + river_spot(&[rec(Street::River, 0, SeenAction::Check, None)], hero, 0.0, 0.0) +} + +fn row_of(spot: &Spot) -> (Vec, Vec) { + let (h, v) = model_lists(spot).expect("model ranges"); + let s = solve_river(spot, &h, &v, "modell", None).expect("solved"); + let m = fast7::mask(&spot.hero_cards); + let i = s.hero_masks.iter().position(|x| *x == m).expect("every hero hand is in the solve"); + let a = s.acts.len(); + (s.rows[i * a..(i + 1) * a].to_vec(), s.acts.clone()) +} + +fn prob(row: &[f64], acts: &[Act], f: impl Fn(&Act) -> bool) -> f64 { + row.iter().zip(acts).filter(|(_, a)| f(a)).map(|(p, _)| p).sum() +} + +/// Off (the default), the engine's output is untouched: no decision. +#[test] +fn off_decides_nothing() { + let _g = MODE_LOCK.lock().unwrap(); + set_river_spieler(RiverSpieler::Aus); + assert!(river_spieler_decision(&facing_bet("As Ad")).is_none()); +} + +/// On, a heads-up river is decided by the solver, deterministically, with a legal choice. +#[test] +fn on_decides_heads_up_rivers_deterministically() { + let _g = MODE_LOCK.lock().unwrap(); + set_river_spieler(RiverSpieler::Modell); + for spot in [facing_bet("Qc Jc"), checked_to("Qc Jc"), facing_bet("As Ad")] { + let a = river_spieler_decision(&spot).expect("heads-up river is in the slice"); + let b = river_spieler_decision(&spot).expect("cached"); + assert_eq!(a.choice, b.choice); + assert!(a.reason.contains("river solver (modell)"), "{}", a.reason); + match a.choice { + Choice::Fold | Choice::Call => assert!(spot.to_call > 0.0), + Choice::Check => assert_eq!(spot.to_call, 0.0), + Choice::Raise { to } => assert!(to > spot.to_call), + _ => {} + } + } + set_river_spieler(RiverSpieler::Aus); +} + +/// Multiway rivers stay with the heuristic. +#[test] +fn multiway_is_not_in_the_slice() { + let _g = MODE_LOCK.lock().unwrap(); + set_river_spieler(RiverSpieler::Modell); + let mut spot = facing_bet("As Ad"); + spot.villains.push(Villain { seat: 1, stack: 90.0, folded: false, profile: None }); + assert!(river_spieler_decision(&spot).is_none()); + set_river_spieler(RiverSpieler::Aus); +} + +/// Top set never folds to a bet; six-high air facing a pot bet folds most of the time. +#[test] +fn the_nuts_continue_and_air_folds() { + let (row, acts) = row_of(&facing_bet("As Ad")); + assert!(prob(&row, &acts, |a| *a == Act::Fold) < 0.01, "top set folds {row:?}"); + let (row, acts) = row_of(&facing_bet("6s 5s")); + assert!(prob(&row, &acts, |a| *a == Act::Fold) > 0.5, "air calls a pot bet {row:?} {acts:?}"); +} + +/// Checked to in position, top set bets for value. +#[test] +fn top_set_bets_when_checked_to() { + let (row, acts) = row_of(&checked_to("As Ad")); + assert!(prob(&row, &acts, |a| matches!(a, Act::Bet(_))) > 0.8, "{row:?} {acts:?}"); +} + +/// The river-only game: the observed line puts hero at a hero decision on the river, and the solve is +/// close to equilibrium (exact best response in the game, below 1 % of the pot after `ITERS`). +#[test] +fn the_river_game_converges() { + let spot = facing_bet("Qc Jc"); + let (h, v) = model_lists(&spot).unwrap(); + let villain = spot.live_villains().next().unwrap(); + let (first, forced, c) = river_line(&spot, villain); + assert_eq!((first, forced.clone()), (1, vec![Act::Bet(9.0)])); + let pot = spot.pot - c[0] - c[1]; + let bets = TrBets { pot, stack: 95.7, first, turn: river_menu(), river: river_menu() }; + let game = build_river(&bets, &forced); + let at = game.at.unwrap(); + assert!(matches!(game.nodes[at], TNode::Dec { player: 0, street: 1, .. })); + let turn = fast7::mask(&spot.board[..4]); + let river = fast7::bit(spot.board[4]); + let hands = [hands_of(&h, turn | river, false), hands_of(&v, turn | river, false)]; + let mut solver = TrSolver::with_cards(game, hands, turn, vec![river], 1.0); + solver.run(ITERS); + let e = solver.exploitability(&solver.strategy()); + assert!(e.total / pot < 0.01, "exploitability {:.4} of pot {pot}", e.total); +} + +fn read(confidence: f64, bluff_confidence: f64, fold: f64) -> RangeRead { + RangeRead { tilt: 0.8, aggression_ratio: [None, None, Some(1.0)], shown: None, fold: [None, None, Some(fold)], confidence, bluff_confidence } +} + +fn rows_with(spot: &Spot, r: Option<&RangeRead>) -> Vec { + let (h, v, src) = solver_lists(spot, RiverSpieler::Modell, r).expect("lists"); + solve_river(spot, &h, &v, src, r).expect("solved").rows.clone() +} + +/// The read hook with no read, or a read without any confidence, is the plain solver bit for bit. +#[test] +fn a_read_without_confidence_is_bit_identical() { + for spot in [facing_bet("Qc Jc"), checked_to("6s 5s")] { + let plain = rows_with(&spot, None); + let zero = rows_with(&spot, Some(&read(0.0, 0.0, 0.9))); + assert_eq!(plain.len(), zero.len()); + assert!(plain.iter().zip(&zero).all(|(a, b)| a.to_bits() == b.to_bits())); + } +} + +/// A trusted read that the villain over-folds to bets makes hero's range bet more often when checked to. +#[test] +fn a_trusted_over_fold_read_bets_more() { + let spot = checked_to("6s 5s"); + let bet_share = |r: Option<&RangeRead>| { + let (h, v, src) = solver_lists(&spot, RiverSpieler::Modell, r).unwrap(); + let s = solve_river(&spot, &h, &v, src, r).unwrap(); + let a = s.acts.len(); + let n = s.hero_masks.len(); + (0..n).map(|k| prob(&s.rows[k * a..(k + 1) * a], &s.acts, |x| matches!(x, Act::Bet(_)))).sum::() / n as f64 + }; + let plain = bet_share(None); + let exploit = bet_share(Some(&read(0.9, 0.0, 0.9))); + assert!(exploit > plain + 0.1, "plain {plain:.2} exploit {exploit:.2}"); +} diff --git a/src/engine/turn_game.rs b/src/engine/turn_game.rs index d95b0f91..4f3b169e 100644 --- a/src/engine/turn_game.rs +++ b/src/engine/turn_game.rs @@ -68,10 +68,18 @@ pub struct TurnConfig { pub measure: bool, /// Raises allowed after a river bet (0 or 1). pub river_raises: usize, + /// Wall-time budget in ms (0 = none, run all `iterations`); a budgeted solve that stops under + /// `MIN_ITERS` returns `None` and the heuristic decides. + pub budget_ms: f64, } +/// Fewest iterations a budgeted solve may decide with. +pub const MIN_ITERS: u32 = 60; +/// Stage B's per-decision budget (all solves of one decision together). +pub const STAGE_B_BUDGET_MS: f64 = 1700.0; + impl TurnConfig { - pub const STANDARD: TurnConfig = TurnConfig { max_combos: 160, cover: 0.95, river_cards: 10, iterations: 200, measure: false, river_raises: 0 }; + pub const STANDARD: TurnConfig = TurnConfig { max_combos: 160, cover: 0.95, river_cards: 10, iterations: 200, measure: false, river_raises: 0, budget_ms: 0.0 }; /// `STANDARD` with `TURN_COMBOS`, `TURN_CARDS`, `TURN_ITERS`, `TURN_EXPLOIT=1` from the environment. pub fn from_env() -> TurnConfig { @@ -83,6 +91,7 @@ impl TurnConfig { 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)), + budget_ms: Self::STANDARD.budget_ms, } } } @@ -226,7 +235,21 @@ fn solve_core(spot: &Spot, hero: &[(Vec, f64)], villain_list: &[(Vec 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); + if cfg.budget_ms > 0.0 { + let mut done = 0; + while done < cfg.iterations { + solver.iterate(); + done += 1; + if done % 5 == 0 && started.elapsed().as_secs_f64() * 1e3 > cfg.budget_ms { + break; + } + } + if done < MIN_ITERS { + return None; + } + } else { + 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(); @@ -356,21 +379,19 @@ pub fn turn_solver_decision(raw: &Spot) -> Option { if spot.live_villains().count() != 1 { return None; } - let cfg = TurnConfig::from_env(); + let begun = std::time::Instant::now(); + let cfg = TurnConfig { budget_ms: STAGE_B_BUDGET_MS, ..TurnConfig::from_env() }; let hero_mask = fast7::mask(&spot.hero_cards); if hero_mask & fast7::mask(&spot.board) != 0 { return None; } - let lists = || -> Option<(Vec<(Vec, f64)>, Vec<(Vec, f64)>, &'static str)> { - if let Some((h, v)) = crate::blueprint::ranges::gewichtete_listen_offen(spot) { - return Some((h, v, "grund")); - } - let (h, v) = crate::engine::river_spieler::model_lists(spot)?; - Some((h, v, "modell")) - }; + let read = crate::engine::river_spieler::read_of(raw); + let lists = || crate::engine::river_spieler::solver_lists(spot, crate::engine::river_spieler::RiverSpieler::An, read.as_ref()); + let raw_profile = read.as_ref().map(|_| format!("{:?}", raw.live_villains().next().map(|v| v.profile.clone()))); let mut key_h = std::collections::hash_map::DefaultHasher::new(); (public_key(spot, &cfg), "ueberall").hash(&mut key_h); spot.live_villains().for_each(|v| format!("{:?}", v.profile).hash(&mut key_h)); + raw_profile.hash(&mut key_h); let key = key_h.finish(); let cached = CACHE.lock().ok().and_then(|m| m.as_ref().and_then(|m| m.get(&key).cloned())); let mut source = ""; @@ -397,8 +418,13 @@ pub fn turn_solver_decision(raw: &Spot) -> Option { if let Some(t) = decide_from(spot, solved, hero_mask) { return Some(tag(t.decision, source)); } + // Hero's hand was pruned away: one more solve with it kept, in what is left of the budget. + let left = STAGE_B_BUDGET_MS - begun.elapsed().as_secs_f64() * 1e3; + if left <= 0.0 { + return None; + } let (hero, villain, src) = lists()?; - solve_turn(spot, &hero, &villain, &cfg).map(|t| tag(t.decision, src)) + solve_turn(spot, &hero, &villain, &TurnConfig { budget_ms: left, ..cfg }).map(|t| tag(t.decision, src)) } #[cfg(test)] diff --git a/src/engine/turn_game/tests.rs b/src/engine/turn_game/tests.rs index c8f49acd..02af5c21 100644 --- a/src/engine/turn_game/tests.rs +++ b/src/engine/turn_game/tests.rs @@ -1,265 +1,265 @@ -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() - ); - } -} - -/// Stage B (SOLVER_TURN): off, nothing; on, a heads-up turn is decided from the range model when no -/// blueprint is loaded, for any hero hand (in or out of the pruned range), with a legal choice. -#[test] -fn stage_b_decides_every_heads_up_turn_from_the_range_model() { - let _g = MODE_LOCK.lock().unwrap(); - set_turn_ueberall(false); - assert!(turn_solver_decision(&facing_bet("Qc Jc")).is_none()); - set_turn_ueberall(true); - for spot in [facing_bet("Qc Jc"), facing_bet("3s 3d"), hero_first("Ac Kc"), facing_bet("9h 4h")] { - let d = turn_solver_decision(&spot).expect("heads-up turn is in the stage-B slice"); - assert!(d.reason.contains("solver turn"), "{}", d.reason); - match d.choice { - Choice::Fold | Choice::Call => assert!(spot.to_call > 0.0), - Choice::Check => assert_eq!(spot.to_call, 0.0), - _ => {} - } - } - let mut multi = facing_bet("Qc Jc"); - multi.villains.push(Villain { seat: 1, stack: 90.0, folded: false, profile: None }); - assert!(turn_solver_decision(&multi).is_none()); - set_turn_ueberall(false); -} +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, budget_ms: 0.0 } +} + +#[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, budget_ms: 0.0 }; + 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() + ); + } +} + +/// Stage B (SOLVER_TURN): off, nothing; on, a heads-up turn is decided from the range model when no +/// blueprint is loaded, for any hero hand (in or out of the pruned range), with a legal choice. +#[test] +fn stage_b_decides_every_heads_up_turn_from_the_range_model() { + let _g = MODE_LOCK.lock().unwrap(); + set_turn_ueberall(false); + assert!(turn_solver_decision(&facing_bet("Qc Jc")).is_none()); + set_turn_ueberall(true); + for spot in [facing_bet("Qc Jc"), facing_bet("3s 3d"), hero_first("Ac Kc"), facing_bet("9h 4h")] { + let d = turn_solver_decision(&spot).expect("heads-up turn is in the stage-B slice"); + assert!(d.reason.contains("solver turn"), "{}", d.reason); + match d.choice { + Choice::Fold | Choice::Call => assert!(spot.to_call > 0.0), + Choice::Check => assert_eq!(spot.to_call, 0.0), + _ => {} + } + } + let mut multi = facing_bet("Qc Jc"); + multi.villains.push(Villain { seat: 1, stack: 90.0, folded: false, profile: None }); + assert!(turn_solver_decision(&multi).is_none()); + set_turn_ueberall(false); +}