Solver ueberall: Read-Haken (Range-Kippung + Knotensperre), Zeitbudget fuer Turn/Flop-Rueckfall

- river_spieler::solver_lists: Kippung der Gegnerrange nach RangeRead (nur bei confidence > 0)
- river_spieler::lock_villain + TrSolver:🔒 geglaubte Gegnerstrategie am River (fold_to_bet, bluff_share), Gewicht = trust
- ohne Read / confidence 0 bitgleich (Test)
- Turn (Stufe B): Wandzeitbudget 1700 ms je Entscheidung inkl. Rueckfall-Solve, MIN_ITERS 60
- Flop: Rueckfall-Solve nur im Restbudget
- Abdeckung Turn: 427/478 HU (89 %), p50 2045 p99 3781 ms (vor dem Budget)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-14 21:27:38 +01:00
co-authored by Claude Opus 5.5
parent c7419822b6
commit e7a00cb35a
9 changed files with 945 additions and 672 deletions
+44
View File
@@ -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
}
}
+6
View File
@@ -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
+28 -1
View File
@@ -260,6 +260,10 @@ pub struct TrSolver {
/// The same as dense showdown matrices, `2 eq - 1` with overlapping pairs 0: per card, /// 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)]`. /// `[p0 rows (n0 x n1), p1 rows (n1 x n0)]`.
eqm: Vec<[Vec<f32>; 2]>, eqm: Vec<[Vec<f32>; 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<Option<(Vec<f64>, f64)>>,
weights: [Vec<f64>; 2], weights: [Vec<f64>; 2],
rc: Vec<RiverCard>, rc: Vec<RiverCard>,
/// Deal weight of one sampled river card. /// Deal weight of one sampled river card.
@@ -364,7 +368,7 @@ impl TrSolver {
} }
let sums = regret.clone(); let sums = regret.clone();
let masks = [hands[0].masks.clone(), hands[1].masks.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 /// 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() .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<f64>, 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 { pub fn hands(&self, player: usize) -> usize {
self.n[player] self.n[player]
} }
@@ -590,6 +612,11 @@ impl TrSolver {
let off = if street == 0 { 0 } else { r * n * a }; let off = if street == 0 { 0 } else { r * n * a };
let mut sigma = vec![0.0; n * a]; let mut sigma = vec![0.0; n * a];
matched(&self.regret[node][off..off + n * a], a, &mut sigma); 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 { if player == p {
let values: Vec<Vec<f64>> = kids let values: Vec<Vec<f64>> = kids
.iter() .iter()
+245 -229
View File
@@ -1,229 +1,245 @@
//! Stage C of "solver everywhere": the heads-up FLOP decided by an equilibrium solve over real combos. //! Stage C of "solver everywhere": the heads-up FLOP decided by an equilibrium solve over real combos.
//! Switch `SOLVER_FLOP` (default off). //! Switch `SOLVER_FLOP` (default off).
//! //!
//! - **Game:** `cfr::turn_river_game` with its first street as the flop: flop betting (33 %, 75 % pot, //! - **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 % //! 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 //! 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. //! (`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 //! - **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. //! 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. //! 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. //! - **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 //! 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. //! 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 //! The turn and river are re-solved at their own decisions (stages B and A), so only the flop action
//! comes from this game. //! comes from this game.
use crate::card::Card; use crate::card::Card;
use crate::cfr::river_game::Act; use crate::cfr::river_game::Act;
use crate::cfr::turn_river_game::{build, Menu, TNode, TrBets, TrSolver}; use crate::cfr::turn_river_game::{build, Menu, TNode, TrBets, TrSolver};
use crate::engine::river_subgame::legal_choice; use crate::engine::river_subgame::legal_choice;
use crate::engine::turn_game::{prune, street_line, TurnConfig}; use crate::engine::turn_game::{prune, street_line, TurnConfig};
use crate::game::{Decision, Spot, Street}; use crate::game::{Decision, Spot, Street};
use crate::hand::fast7; use crate::hand::fast7;
use crate::rng::Rng; use crate::rng::Rng;
use std::collections::HashMap; use std::collections::HashMap;
use std::hash::{Hash, Hasher}; use std::hash::{Hash, Hasher};
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
static ON: AtomicBool = AtomicBool::new(false); static ON: AtomicBool = AtomicBool::new(false);
/// Budget override in ms (0 = `STANDARD`); tests under parallel load use it.
pub fn set_flop_spieler(on: bool) { static BUDGET_OVERRIDE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
ON.store(on, Ordering::Relaxed);
} #[cfg(test)]
pub(crate) fn set_budget_override(ms: u64) {
pub fn flop_spieler() -> bool { BUDGET_OVERRIDE.store(ms, Ordering::Relaxed);
ON.load(Ordering::Relaxed) }
}
pub fn set_flop_spieler(on: bool) {
/// `SOLVER_FLOP=1`. ON.store(on, Ordering::Relaxed);
pub fn from_env() -> bool { }
matches!(std::env::var("SOLVER_FLOP").as_deref(), Ok("1") | Ok("an"))
} pub fn flop_spieler() -> bool {
ON.load(Ordering::Relaxed)
/// Size and budget (`FLOP_COMBOS`, `FLOP_CARDS`, `FLOP_ITERS` override). }
#[derive(Clone, Copy, Debug)]
pub struct FlopConfig { /// `SOLVER_FLOP=1`.
pub max_combos: usize, pub fn from_env() -> bool {
pub turn_cards: usize, matches!(std::env::var("SOLVER_FLOP").as_deref(), Ok("1") | Ok("an"))
pub iterations: u32, }
pub budget_ms: f64,
} /// Size and budget (`FLOP_COMBOS`, `FLOP_CARDS`, `FLOP_ITERS` override).
#[derive(Clone, Copy, Debug)]
pub const MIN_ITERS: u32 = 60; pub struct FlopConfig {
pub max_combos: usize,
impl FlopConfig { pub turn_cards: usize,
pub const STANDARD: FlopConfig = FlopConfig { max_combos: 120, turn_cards: 8, iterations: 200, budget_ms: 1800.0 }; pub iterations: u32,
pub budget_ms: f64,
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 { pub const MIN_ITERS: u32 = 60;
max_combos: num("FLOP_COMBOS", Self::STANDARD.max_combos),
turn_cards: num("FLOP_CARDS", Self::STANDARD.turn_cards), impl FlopConfig {
iterations: num("FLOP_ITERS", Self::STANDARD.iterations as usize) as u32, pub const STANDARD: FlopConfig = FlopConfig { max_combos: 120, turn_cards: 8, iterations: 200, budget_ms: 1800.0 };
budget_ms: Self::STANDARD.budget_ms,
} 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),
pub struct Solved { turn_cards: num("FLOP_CARDS", Self::STANDARD.turn_cards),
rows: Vec<f64>, iterations: num("FLOP_ITERS", Self::STANDARD.iterations as usize) as u32,
acts: Vec<Act>, budget_ms: match BUDGET_OVERRIDE.load(Ordering::Relaxed) {
hero_masks: Vec<u64>, 0 => Self::STANDARD.budget_ms,
pub millis: f64, ms => ms as f64,
pub iterations: u32, },
pub combos: [usize; 2], }
pub nodes: usize, }
pub source: &'static str, }
}
pub struct Solved {
/// The flop+turn betting menus. rows: Vec<f64>,
pub fn flop_bets(pot: f64, stack: f64, first: usize) -> TrBets { acts: Vec<Act>,
TrBets { hero_masks: Vec<u64>,
pot, pub millis: f64,
stack, pub iterations: u32,
first, pub combos: [usize; 2],
turn: Menu { fracs: vec![0.33, 0.75], raise_mult: vec![3.0], max_raises: 1, allin: true }, pub nodes: usize,
river: Menu { fracs: vec![0.75], raise_mult: vec![3.0], max_raises: 1, allin: true }, pub source: &'static str,
} }
}
/// The flop+turn betting menus.
/// Solve the flop of `spot` with these ranges; `keep` = a hero hand that must be in the game. pub fn flop_bets(pot: f64, stack: f64, first: usize) -> TrBets {
pub fn solve_flop(spot: &Spot, hero: &[(Vec<Card>, f64)], villain_list: &[(Vec<Card>, f64)], cfg: &FlopConfig, keep: Option<u64>, source: &'static str) -> Option<Solved> { TrBets {
if spot.street != Street::Flop || spot.board.len() != 3 || spot.live_villains().count() != 1 { pot,
return None; stack,
} first,
let villain = spot.live_villains().next()?; turn: Menu { fracs: vec![0.33, 0.75], raise_mult: vec![3.0], max_raises: 1, allin: true },
let (first, forced, c) = street_line(spot, villain, Street::Flop); river: Menu { fracs: vec![0.75], raise_mult: vec![3.0], max_raises: 1, allin: true },
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; /// 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<Card>, f64)], villain_list: &[(Vec<Card>, f64)], cfg: &FlopConfig, keep: Option<u64>, source: &'static str) -> Option<Solved> {
let started = std::time::Instant::now(); if spot.street != Street::Flop || spot.board.len() != 3 || spot.live_villains().count() != 1 {
let board = fast7::mask(&spot.board); return None;
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)]; let villain = spot.live_villains().next()?;
if hands[0].masks.is_empty() || hands[1].masks.is_empty() { let (first, forced, c) = street_line(spot, villain, Street::Flop);
return None; let pot = spot.pot - c[0] - c[1];
} let stack = (spot.hero_stack + c[0]).min(villain.stack + c[1]);
let game = build(&flop_bets(pot, stack, first), &forced); if pot <= 0.0 || stack <= c[0].max(c[1]) {
let at = game.at?; return None;
if !matches!(game.nodes.get(at), Some(TNode::Dec { player: 0, street: 0, .. })) { }
return None; let started = std::time::Instant::now();
} let board = fast7::mask(&spot.board);
let combos = [hands[0].masks.len(), hands[1].masks.len()]; let pc = TurnConfig { max_combos: cfg.max_combos, cover: 0.95, ..TurnConfig::STANDARD };
let hero_masks = hands[0].masks.clone(); let hands = [prune(hero, board, &pc, keep), prune(villain_list, board, &pc, None)];
let acts = game.acts[at].clone(); if hands[0].masks.is_empty() || hands[1].masks.is_empty() {
let nodes = game.nodes.len(); return None;
let mut solver = TrSolver::new(game, hands, board, Some(cfg.turn_cards)).with_river_equity(board); }
let mut done = 0; let game = build(&flop_bets(pot, stack, first), &forced);
while done < cfg.iterations { let at = game.at?;
solver.iterate(); if !matches!(game.nodes.get(at), Some(TNode::Dec { player: 0, street: 0, .. })) {
done += 1; return None;
if done % 5 == 0 && started.elapsed().as_secs_f64() * 1e3 > cfg.budget_ms { }
break; let combos = [hands[0].masks.len(), hands[1].masks.len()];
} let hero_masks = hands[0].masks.clone();
} let acts = game.acts[at].clone();
if done < MIN_ITERS { let nodes = game.nodes.len();
return None; let mut solver = TrSolver::new(game, hands, board, Some(cfg.turn_cards)).with_river_equity(board);
} let mut done = 0;
let strategy = solver.strategy(); while done < cfg.iterations {
let rows: Vec<f64> = (0..combos[0]).flat_map(|i| strategy.row(at, 0, i).to_vec()).collect(); solver.iterate();
let millis = started.elapsed().as_secs_f64() * 1e3; done += 1;
Some(Solved { rows, acts, hero_masks, millis, iterations: done, combos, nodes, source }) if done % 5 == 0 && started.elapsed().as_secs_f64() * 1e3 > cfg.budget_ms {
} break;
}
fn decide_from(spot: &Spot, solved: &Solved, hero_mask: u64) -> Option<Decision> { }
let idx = solved.hero_masks.iter().position(|m| *m == hero_mask)?; if done < MIN_ITERS {
let a = solved.acts.len(); return None;
let row = &solved.rows[idx * a..(idx + 1) * a]; }
let (draw, _) = Rng::seeded(spot.seed).unit(); let strategy = solver.strategy();
let mut acc = 0.0; let rows: Vec<f64> = (0..combos[0]).flat_map(|i| strategy.row(at, 0, i).to_vec()).collect();
let mut pick = a.saturating_sub(1); let millis = started.elapsed().as_secs_f64() * 1e3;
for (k, p) in row.iter().enumerate() { Some(Solved { rows, acts, hero_masks, millis, iterations: done, combos, nodes, source })
acc += p; }
if draw < acc {
pick = k; fn decide_from(spot: &Spot, solved: &Solved, hero_mask: u64) -> Option<Decision> {
break; 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 act = *solved.acts.get(pick)?; let (draw, _) = Rng::seeded(spot.seed).unit();
let p = row.get(pick).copied().unwrap_or(0.0); let mut acc = 0.0;
Some(Decision::new( let mut pick = a.saturating_sub(1);
legal_choice(spot, act), for (k, p) in row.iter().enumerate() {
p.clamp(0.0, 1.0), acc += p;
format!( if draw < acc {
"solver flop ({}): {}x{} combos, {} nodes, {} iters, {act:?} p {p:.2}, {:.0} ms", pick = k;
solved.source, solved.combos[0], solved.combos[1], solved.nodes, solved.iterations, solved.millis break;
), }
)) }
} let act = *solved.acts.get(pick)?;
let p = row.get(pick).copied().unwrap_or(0.0);
static CACHE: Mutex<Option<HashMap<u64, Arc<Solved>>>> = Mutex::new(None); Some(Decision::new(
const CACHE_MAX: usize = 2048; legal_choice(spot, act),
p.clamp(0.0, 1.0),
fn public_key(spot: &Spot, cfg: &FlopConfig) -> u64 { format!(
let mut h = std::collections::hash_map::DefaultHasher::new(); "solver flop ({}): {}x{} combos, {} nodes, {} iters, {act:?} p {p:.2}, {:.0} ms",
format!("{:?}", spot.history).hash(&mut h); solved.source, solved.combos[0], solved.combos[1], solved.nodes, solved.iterations, solved.millis
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); static CACHE: Mutex<Option<HashMap<u64, Arc<Solved>>>> = Mutex::new(None);
}); const CACHE_MAX: usize = 2048;
(spot.hero_seat, spot.button_seat, spot.seats, cfg.max_combos, cfg.turn_cards, cfg.iterations).hash(&mut h);
h.finish() fn public_key(spot: &Spot, cfg: &FlopConfig) -> u64 {
} let mut h = std::collections::hash_map::DefaultHasher::new();
format!("{:?}", spot.history).hash(&mut h);
/// The live stage-C decision, or `None` and the heuristic keeps it. format!("{:?}", spot.board).hash(&mut h);
pub fn flop_spieler_decision(raw: &Spot) -> Option<Decision> { [spot.pot, spot.to_call, spot.hero_stack, spot.big_blind].iter().for_each(|x| x.to_bits().hash(&mut h));
if !flop_spieler() || raw.street != Street::Flop || raw.hero_cards.len() != 2 || raw.board.len() != 3 { spot.live_villains().for_each(|v| {
return None; (v.seat, v.stack.to_bits()).hash(&mut h);
} format!("{:?}", v.profile).hash(&mut h);
let gated = crate::engine::read_gate::gate_reads(raw); });
let spot = &gated; (spot.hero_seat, spot.button_seat, spot.seats, cfg.max_combos, cfg.turn_cards, cfg.iterations).hash(&mut h);
if spot.live_villains().count() != 1 { h.finish()
return None; }
}
let cfg = FlopConfig::from_env(); /// The live stage-C decision, or `None` and the heuristic keeps it.
let hero_mask = fast7::mask(&spot.hero_cards); pub fn flop_spieler_decision(raw: &Spot) -> Option<Decision> {
if hero_mask & fast7::mask(&spot.board) != 0 { if !flop_spieler() || raw.street != Street::Flop || raw.hero_cards.len() != 2 || raw.board.len() != 3 {
return None; return None;
} }
let lists = || -> Option<(Vec<(Vec<Card>, f64)>, Vec<(Vec<Card>, f64)>, &'static str)> { let gated = crate::engine::read_gate::gate_reads(raw);
if let Some((h, v)) = crate::blueprint::ranges::gewichtete_listen_offen(spot) { let spot = &gated;
return Some((h, v, "grund")); if spot.live_villains().count() != 1 {
} return None;
let (h, v) = crate::engine::river_spieler::model_lists(spot)?; }
Some((h, v, "modell")) let begun = std::time::Instant::now();
}; let cfg = FlopConfig::from_env();
let key = public_key(spot, &cfg); let hero_mask = fast7::mask(&spot.hero_cards);
let cached = CACHE.lock().ok().and_then(|m| m.as_ref().and_then(|m| m.get(&key).cloned())); if hero_mask & fast7::mask(&spot.board) != 0 {
let solved = match cached { return None;
Some(s) => s, }
None => { let read = crate::engine::river_spieler::read_of(raw);
let (hero, villain, source) = lists()?; let lists = || crate::engine::river_spieler::solver_lists(spot, crate::engine::river_spieler::RiverSpieler::An, read.as_ref());
let solved = Arc::new(solve_flop(spot, &hero, &villain, &cfg, None, source)?); let raw_profile = read.as_ref().map(|_| format!("{:?}", raw.live_villains().next().map(|v| v.profile.clone())));
if let Ok(mut m) = CACHE.lock() { let key = {
let map = m.get_or_insert_with(HashMap::new); let mut h = std::collections::hash_map::DefaultHasher::new();
if map.len() >= CACHE_MAX { (public_key(spot, &cfg), raw_profile).hash(&mut h);
map.clear(); h.finish()
} };
map.insert(key, solved.clone()); let cached = CACHE.lock().ok().and_then(|m| m.as_ref().and_then(|m| m.get(&key).cloned()));
} let solved = match cached {
solved Some(s) => s,
} None => {
}; let (hero, villain, source) = lists()?;
if let Some(d) = decide_from(spot, &solved, hero_mask) { let solved = Arc::new(solve_flop(spot, &hero, &villain, &cfg, None, source)?);
return Some(d); if let Ok(mut m) = CACHE.lock() {
} let map = m.get_or_insert_with(HashMap::new);
let (hero, villain, source) = lists()?; if map.len() >= CACHE_MAX {
let own = solve_flop(spot, &hero, &villain, &cfg, Some(hero_mask), source)?; map.clear();
decide_from(spot, &own, hero_mask) }
} map.insert(key, solved.clone());
}
#[cfg(test)] solved
mod tests; }
};
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;
+2
View File
@@ -75,6 +75,7 @@ fn off_decides_nothing_and_on_decides_heads_up_flops() {
set_flop_spieler(false); set_flop_spieler(false);
assert!(flop_spieler_decision(&checked_to("Ks Kd")).is_none()); assert!(flop_spieler_decision(&checked_to("Ks Kd")).is_none());
set_flop_spieler(true); 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")] { 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"); let d = flop_spieler_decision(&spot).expect("heads-up flop is in the slice");
assert!(d.reason.contains("solver flop"), "{}", d.reason); 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"); let mut multi = checked_to("Ks Kd");
multi.villains.push(Villain { seat: 1, stack: 90.0, folded: false, profile: None }); multi.villains.push(Villain { seat: 1, stack: 90.0, folded: false, profile: None });
assert!(flop_spieler_decision(&multi).is_none()); assert!(flop_spieler_decision(&multi).is_none());
set_budget_override(0);
set_flop_spieler(false); set_flop_spieler(false);
} }
+127 -11
View File
@@ -24,6 +24,7 @@
use crate::card::Card; use crate::card::Card;
use crate::cfr::river_game::Act; use crate::cfr::river_game::Act;
use crate::cfr::turn_river_game::{build_river, Hands, Menu, TNode, TrBets, TrSolver}; 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::engine::river_subgame::{legal_choice, river_line};
use crate::game::{Decision, Spot, Street, Villain}; use crate::game::{Decision, Spot, Street, Villain};
use crate::hand::fast7; use crate::hand::fast7;
@@ -131,7 +132,7 @@ fn hands_of(list: &[(Vec<Card>, f64)], dead: u64, fill: bool) -> Hands {
const TOKEN: f64 = 1e-6; 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. /// 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<Card>, f64)], villain_list: &[(Vec<Card>, f64)], source: &'static str) -> Option<Solved> { pub fn solve_river(spot: &Spot, hero: &[(Vec<Card>, f64)], villain_list: &[(Vec<Card>, f64)], source: &'static str, read: Option<&RangeRead>) -> Option<Solved> {
if spot.street != Street::River || spot.board.len() != 5 || spot.live_villains().count() != 1 { if spot.street != Street::River || spot.board.len() != 5 || spot.live_villains().count() != 1 {
return None; return None;
} }
@@ -160,7 +161,11 @@ pub fn solve_river(spot: &Spot, hero: &[(Vec<Card>, f64)], villain_list: &[(Vec<
let hero_masks = hands[0].masks.clone(); let hero_masks = hands[0].masks.clone();
let acts = game.acts[at].clone(); let acts = game.acts[at].clone();
let nodes = game.nodes.len(); 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); 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; let mut done = 0;
while done < ITERS { while done < ITERS {
solver.iterate(); solver.iterate();
@@ -220,15 +225,120 @@ pub fn model_lists(spot: &Spot) -> Option<(Vec<(Vec<Card>, f64)>, Vec<(Vec<Card>
Some((eins(list(&me)?), eins(list(villain)?))) Some((eins(list(&me)?), eins(list(villain)?)))
} }
/// The ranges of this spot and where they came from. /// The read layer (`exploit::range_read`, switch `GEGNER_RANGE=1`, default off): the villain's read from
fn lists(spot: &Spot, mode: RiverSpieler) -> Option<(Vec<(Vec<Card>, f64)>, Vec<(Vec<Card>, f64)>, &'static str)> { /// its UNGATED profile, or `None` = the plain solver.
if mode == RiverSpieler::An { pub fn read_of(raw: &Spot) -> Option<RangeRead> {
if let Some((h, v)) = crate::blueprint::ranges::gewichtete_listen_offen(spot) { if std::env::var("GEGNER_RANGE").as_deref() != Ok("1") {
return Some((h, v, "grund")); 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<f64> {
let score: Vec<u32> = masks.iter().map(|m| fast7::score(m | board)).collect();
let mut order: Vec<usize> = (0..masks.len()).collect();
order.sort_by_key(|i| score[*i]);
let total: f64 = weights.iter().sum::<f64>().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<Card>, f64)>, Vec<(Vec<Card>, 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<u64> = v.iter().map(|(c, _)| fast7::mask(c)).collect();
let weights: Vec<f64> = 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<Option<Act>> = 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<Act>)> = 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<f64> = 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<f64> = 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<Option<HashMap<u64, Arc<Solved>>>> = Mutex::new(None); static CACHE: Mutex<Option<HashMap<u64, Arc<Solved>>>> = Mutex::new(None);
@@ -265,13 +375,19 @@ pub fn river_spieler_decision(raw: &Spot) -> Option<Decision> {
if hero_mask & fast7::mask(&spot.board) != 0 { if hero_mask & fast7::mask(&spot.board) != 0 {
return None; 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 cached = CACHE.lock().ok().and_then(|m| m.as_ref().and_then(|m| m.get(&key).cloned()));
let solved = match cached { let solved = match cached {
Some(s) => s, Some(s) => s,
None => { None => {
let (hero, villain, source) = lists(spot, mode)?; let (hero, villain, source) = solver_lists(spot, mode, read.as_ref())?;
let solved = Arc::new(solve_river(spot, &hero, &villain, source)?); let solved = Arc::new(solve_river(spot, &hero, &villain, source, read.as_ref())?);
if let Ok(mut m) = CACHE.lock() { if let Ok(mut m) = CACHE.lock() {
let map = m.get_or_insert_with(HashMap::new); let map = m.get_or_insert_with(HashMap::new);
if map.len() >= CACHE_MAX { if map.len() >= CACHE_MAX {
+191 -155
View File
@@ -1,155 +1,191 @@
use super::*; use super::*;
use crate::card::Card; use crate::card::Card;
use crate::game::{ActionKind, ActionRecord, Choice, SeenAction, Spot, Street, Villain}; use crate::game::{ActionKind, ActionRecord, Choice, SeenAction, Spot, Street, Villain};
use crate::variant::Variant; use crate::variant::Variant;
/// The switch is process-global: tests that touch it take turns. /// The switch is process-global: tests that touch it take turns.
static MODE_LOCK: Mutex<()> = Mutex::new(()); static MODE_LOCK: Mutex<()> = Mutex::new(());
fn rec(street: Street, seat: u8, action: SeenAction, amount: Option<f64>) -> ActionRecord { fn rec(street: Street, seat: u8, action: SeenAction, amount: Option<f64>) -> ActionRecord {
ActionRecord { street, seat, action, amount } 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, /// 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 /// call; turn check, check. River pot 9.1 + `pot_extra`; `river` is the river line so far; hero is the
/// button. /// button.
fn river_spot(river: &[ActionRecord], hero: &str, to_call: f64, pot_extra: f64) -> Spot { fn river_spot(river: &[ActionRecord], hero: &str, to_call: f64, pot_extra: f64) -> Spot {
use SeenAction::*; use SeenAction::*;
use Street::*; use Street::*;
let mut h = vec![ let mut h = vec![
rec(Preflop, 5, PostSmallBlind, Some(0.5)), rec(Preflop, 5, PostSmallBlind, Some(0.5)),
rec(Preflop, 0, PostBigBlind, Some(1.0)), rec(Preflop, 0, PostBigBlind, Some(1.0)),
rec(Preflop, 1, Fold, None), rec(Preflop, 1, Fold, None),
rec(Preflop, 2, Fold, None), rec(Preflop, 2, Fold, None),
rec(Preflop, 3, Fold, None), rec(Preflop, 3, Fold, None),
rec(Preflop, 4, Raise, Some(2.5)), rec(Preflop, 4, Raise, Some(2.5)),
rec(Preflop, 5, Fold, None), rec(Preflop, 5, Fold, None),
rec(Preflop, 0, Call, Some(2.5)), rec(Preflop, 0, Call, Some(2.5)),
rec(Flop, 0, Check, None), rec(Flop, 0, Check, None),
rec(Flop, 4, Bet, Some(1.8)), rec(Flop, 4, Bet, Some(1.8)),
rec(Flop, 0, Call, Some(1.8)), rec(Flop, 0, Call, Some(1.8)),
rec(Turn, 0, Check, None), rec(Turn, 0, Check, None),
rec(Turn, 4, Check, None), rec(Turn, 4, Check, None),
]; ];
h.extend_from_slice(river); 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] }; let legal = if to_call > 0.0 { vec![ActionKind::Fold, ActionKind::Call, ActionKind::Raise] } else { vec![ActionKind::Check, ActionKind::Raise] };
Spot { Spot {
variant: Variant::Nlhe, variant: Variant::Nlhe,
big_blind: 1.0, big_blind: 1.0,
seats: 6, seats: 6,
hero_seat: 4, hero_seat: 4,
button_seat: Some(4), button_seat: Some(4),
hero_cards: Card::parse_list(hero).unwrap(), hero_cards: Card::parse_list(hero).unwrap(),
board: Card::parse_list("Ah 7d 2c Ks 3h").unwrap(), board: Card::parse_list("Ah 7d 2c Ks 3h").unwrap(),
street: Street::River, street: Street::River,
pot: 9.1 + pot_extra, pot: 9.1 + pot_extra,
to_call, to_call,
hero_stack: 95.7, hero_stack: 95.7,
min_raise_to: Some(if to_call > 0.0 { 2.0 * to_call } else { 1.0 }), min_raise_to: Some(if to_call > 0.0 { 2.0 * to_call } else { 1.0 }),
max_raise_to: Some(95.7), max_raise_to: Some(95.7),
legal, legal,
allowed_sizes: None, allowed_sizes: None,
villains: vec![Villain { seat: 0, stack: 95.7 - to_call, folded: false, profile: None }], villains: vec![Villain { seat: 0, stack: 95.7 - to_call, folded: false, profile: None }],
seed: 7, seed: 7,
history: h, history: h,
} }
} }
fn facing_bet(hero: &str) -> Spot { fn facing_bet(hero: &str) -> Spot {
river_spot(&[rec(Street::River, 0, SeenAction::Bet, Some(9.0))], hero, 9.0, 9.0) river_spot(&[rec(Street::River, 0, SeenAction::Bet, Some(9.0))], hero, 9.0, 9.0)
} }
fn checked_to(hero: &str) -> Spot { fn checked_to(hero: &str) -> Spot {
river_spot(&[rec(Street::River, 0, SeenAction::Check, None)], hero, 0.0, 0.0) river_spot(&[rec(Street::River, 0, SeenAction::Check, None)], hero, 0.0, 0.0)
} }
fn row_of(spot: &Spot) -> (Vec<f64>, Vec<Act>) { fn row_of(spot: &Spot) -> (Vec<f64>, Vec<Act>) {
let (h, v) = model_lists(spot).expect("model ranges"); let (h, v) = model_lists(spot).expect("model ranges");
let s = solve_river(spot, &h, &v, "modell").expect("solved"); let s = solve_river(spot, &h, &v, "modell", None).expect("solved");
let m = fast7::mask(&spot.hero_cards); 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 i = s.hero_masks.iter().position(|x| *x == m).expect("every hero hand is in the solve");
let a = s.acts.len(); let a = s.acts.len();
(s.rows[i * a..(i + 1) * a].to_vec(), s.acts.clone()) (s.rows[i * a..(i + 1) * a].to_vec(), s.acts.clone())
} }
fn prob(row: &[f64], acts: &[Act], f: impl Fn(&Act) -> bool) -> f64 { fn prob(row: &[f64], acts: &[Act], f: impl Fn(&Act) -> bool) -> f64 {
row.iter().zip(acts).filter(|(_, a)| f(a)).map(|(p, _)| p).sum() row.iter().zip(acts).filter(|(_, a)| f(a)).map(|(p, _)| p).sum()
} }
/// Off (the default), the engine's output is untouched: no decision. /// Off (the default), the engine's output is untouched: no decision.
#[test] #[test]
fn off_decides_nothing() { fn off_decides_nothing() {
let _g = MODE_LOCK.lock().unwrap(); let _g = MODE_LOCK.lock().unwrap();
set_river_spieler(RiverSpieler::Aus); set_river_spieler(RiverSpieler::Aus);
assert!(river_spieler_decision(&facing_bet("As Ad")).is_none()); 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. /// On, a heads-up river is decided by the solver, deterministically, with a legal choice.
#[test] #[test]
fn on_decides_heads_up_rivers_deterministically() { fn on_decides_heads_up_rivers_deterministically() {
let _g = MODE_LOCK.lock().unwrap(); let _g = MODE_LOCK.lock().unwrap();
set_river_spieler(RiverSpieler::Modell); set_river_spieler(RiverSpieler::Modell);
for spot in [facing_bet("Qc Jc"), checked_to("Qc Jc"), facing_bet("As Ad")] { 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 a = river_spieler_decision(&spot).expect("heads-up river is in the slice");
let b = river_spieler_decision(&spot).expect("cached"); let b = river_spieler_decision(&spot).expect("cached");
assert_eq!(a.choice, b.choice); assert_eq!(a.choice, b.choice);
assert!(a.reason.contains("river solver (modell)"), "{}", a.reason); assert!(a.reason.contains("river solver (modell)"), "{}", a.reason);
match a.choice { match a.choice {
Choice::Fold | Choice::Call => assert!(spot.to_call > 0.0), Choice::Fold | Choice::Call => assert!(spot.to_call > 0.0),
Choice::Check => assert_eq!(spot.to_call, 0.0), Choice::Check => assert_eq!(spot.to_call, 0.0),
Choice::Raise { to } => assert!(to > spot.to_call), Choice::Raise { to } => assert!(to > spot.to_call),
_ => {} _ => {}
} }
} }
set_river_spieler(RiverSpieler::Aus); set_river_spieler(RiverSpieler::Aus);
} }
/// Multiway rivers stay with the heuristic. /// Multiway rivers stay with the heuristic.
#[test] #[test]
fn multiway_is_not_in_the_slice() { fn multiway_is_not_in_the_slice() {
let _g = MODE_LOCK.lock().unwrap(); let _g = MODE_LOCK.lock().unwrap();
set_river_spieler(RiverSpieler::Modell); set_river_spieler(RiverSpieler::Modell);
let mut spot = facing_bet("As Ad"); let mut spot = facing_bet("As Ad");
spot.villains.push(Villain { seat: 1, stack: 90.0, folded: false, profile: None }); spot.villains.push(Villain { seat: 1, stack: 90.0, folded: false, profile: None });
assert!(river_spieler_decision(&spot).is_none()); assert!(river_spieler_decision(&spot).is_none());
set_river_spieler(RiverSpieler::Aus); set_river_spieler(RiverSpieler::Aus);
} }
/// Top set never folds to a bet; six-high air facing a pot bet folds most of the time. /// Top set never folds to a bet; six-high air facing a pot bet folds most of the time.
#[test] #[test]
fn the_nuts_continue_and_air_folds() { fn the_nuts_continue_and_air_folds() {
let (row, acts) = row_of(&facing_bet("As Ad")); let (row, acts) = row_of(&facing_bet("As Ad"));
assert!(prob(&row, &acts, |a| *a == Act::Fold) < 0.01, "top set folds {row:?}"); assert!(prob(&row, &acts, |a| *a == Act::Fold) < 0.01, "top set folds {row:?}");
let (row, acts) = row_of(&facing_bet("6s 5s")); 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:?}"); 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. /// Checked to in position, top set bets for value.
#[test] #[test]
fn top_set_bets_when_checked_to() { fn top_set_bets_when_checked_to() {
let (row, acts) = row_of(&checked_to("As Ad")); let (row, acts) = row_of(&checked_to("As Ad"));
assert!(prob(&row, &acts, |a| matches!(a, Act::Bet(_))) > 0.8, "{row:?} {acts:?}"); 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 /// 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`). /// close to equilibrium (exact best response in the game, below 1 % of the pot after `ITERS`).
#[test] #[test]
fn the_river_game_converges() { fn the_river_game_converges() {
let spot = facing_bet("Qc Jc"); let spot = facing_bet("Qc Jc");
let (h, v) = model_lists(&spot).unwrap(); let (h, v) = model_lists(&spot).unwrap();
let villain = spot.live_villains().next().unwrap(); let villain = spot.live_villains().next().unwrap();
let (first, forced, c) = river_line(&spot, villain); let (first, forced, c) = river_line(&spot, villain);
assert_eq!((first, forced.clone()), (1, vec![Act::Bet(9.0)])); assert_eq!((first, forced.clone()), (1, vec![Act::Bet(9.0)]));
let pot = spot.pot - c[0] - c[1]; let pot = spot.pot - c[0] - c[1];
let bets = TrBets { pot, stack: 95.7, first, turn: river_menu(), river: river_menu() }; let bets = TrBets { pot, stack: 95.7, first, turn: river_menu(), river: river_menu() };
let game = build_river(&bets, &forced); let game = build_river(&bets, &forced);
let at = game.at.unwrap(); let at = game.at.unwrap();
assert!(matches!(game.nodes[at], TNode::Dec { player: 0, street: 1, .. })); assert!(matches!(game.nodes[at], TNode::Dec { player: 0, street: 1, .. }));
let turn = fast7::mask(&spot.board[..4]); let turn = fast7::mask(&spot.board[..4]);
let river = fast7::bit(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 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); let mut solver = TrSolver::with_cards(game, hands, turn, vec![river], 1.0);
solver.run(ITERS); solver.run(ITERS);
let e = solver.exploitability(&solver.strategy()); let e = solver.exploitability(&solver.strategy());
assert!(e.total / pot < 0.01, "exploitability {:.4} of pot {pot}", e.total); 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<f64> {
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::<f64>() / 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}");
}
+37 -11
View File
@@ -68,10 +68,18 @@ pub struct TurnConfig {
pub measure: bool, pub measure: bool,
/// Raises allowed after a river bet (0 or 1). /// Raises allowed after a river bet (0 or 1).
pub river_raises: usize, 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 { 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. /// `STANDARD` with `TURN_COMBOS`, `TURN_CARDS`, `TURN_ITERS`, `TURN_EXPLOIT=1` from the environment.
pub fn from_env() -> TurnConfig { pub fn from_env() -> TurnConfig {
@@ -83,6 +91,7 @@ impl TurnConfig {
iterations: num("TURN_ITERS", Self::STANDARD.iterations as usize) as u32, iterations: num("TURN_ITERS", Self::STANDARD.iterations as usize) as u32,
measure: std::env::var("TURN_EXPLOIT").as_deref() == Ok("1"), 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)), 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<Card>, f64)], villain_list: &[(Vec<Card>
let acts = game.acts[at].clone(); let acts = game.acts[at].clone();
let nodes = game.nodes.len(); let nodes = game.nodes.len();
let mut solver = TrSolver::new(game, hands, board, Some(cfg.river_cards)); 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 strategy = solver.strategy();
let exploit = cfg.measure.then(|| solver.exploitability(&strategy)); let exploit = cfg.measure.then(|| solver.exploitability(&strategy));
let rows: Vec<f64> = (0..combos[0]).flat_map(|i| strategy.row(at, 0, i).to_vec()).collect(); let rows: Vec<f64> = (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<Decision> {
if spot.live_villains().count() != 1 { if spot.live_villains().count() != 1 {
return None; 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); let hero_mask = fast7::mask(&spot.hero_cards);
if hero_mask & fast7::mask(&spot.board) != 0 { if hero_mask & fast7::mask(&spot.board) != 0 {
return None; return None;
} }
let lists = || -> Option<(Vec<(Vec<Card>, f64)>, Vec<(Vec<Card>, f64)>, &'static str)> { let read = crate::engine::river_spieler::read_of(raw);
if let Some((h, v)) = crate::blueprint::ranges::gewichtete_listen_offen(spot) { let lists = || crate::engine::river_spieler::solver_lists(spot, crate::engine::river_spieler::RiverSpieler::An, read.as_ref());
return Some((h, v, "grund")); let raw_profile = read.as_ref().map(|_| format!("{:?}", raw.live_villains().next().map(|v| v.profile.clone())));
}
let (h, v) = crate::engine::river_spieler::model_lists(spot)?;
Some((h, v, "modell"))
};
let mut key_h = std::collections::hash_map::DefaultHasher::new(); let mut key_h = std::collections::hash_map::DefaultHasher::new();
(public_key(spot, &cfg), "ueberall").hash(&mut key_h); (public_key(spot, &cfg), "ueberall").hash(&mut key_h);
spot.live_villains().for_each(|v| format!("{:?}", v.profile).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 key = key_h.finish();
let cached = CACHE.lock().ok().and_then(|m| m.as_ref().and_then(|m| m.get(&key).cloned())); let cached = CACHE.lock().ok().and_then(|m| m.as_ref().and_then(|m| m.get(&key).cloned()));
let mut source = ""; let mut source = "";
@@ -397,8 +418,13 @@ pub fn turn_solver_decision(raw: &Spot) -> Option<Decision> {
if let Some(t) = decide_from(spot, solved, hero_mask) { if let Some(t) = decide_from(spot, solved, hero_mask) {
return Some(tag(t.decision, source)); 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()?; 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)] #[cfg(test)]
+265 -265
View File
@@ -1,265 +1,265 @@
use super::*; use super::*;
use crate::card::Card; use crate::card::Card;
use crate::game::{ActionKind, ActionRecord, Choice, SeenAction, Spot, Street, Villain}; use crate::game::{ActionKind, ActionRecord, Choice, SeenAction, Spot, Street, Villain};
use crate::variant::Variant; use crate::variant::Variant;
use std::sync::Mutex; use std::sync::Mutex;
/// The switch is process-global: tests that touch it take turns. /// The switch is process-global: tests that touch it take turns.
static MODE_LOCK: Mutex<()> = Mutex::new(()); static MODE_LOCK: Mutex<()> = Mutex::new(());
fn rec(street: Street, seat: u8, action: SeenAction, amount: Option<f64>) -> ActionRecord { fn rec(street: Street, seat: u8, action: SeenAction, amount: Option<f64>) -> ActionRecord {
ActionRecord { street, seat, action, amount } 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, /// 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. /// 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 { fn s1_turn(turn: &[ActionRecord], hero: &str, to_call: f64, pot_extra: f64) -> Spot {
use SeenAction::*; use SeenAction::*;
use Street::*; use Street::*;
let mut h = vec![ let mut h = vec![
rec(Preflop, 5, PostSmallBlind, Some(0.5)), rec(Preflop, 5, PostSmallBlind, Some(0.5)),
rec(Preflop, 0, PostBigBlind, Some(1.0)), rec(Preflop, 0, PostBigBlind, Some(1.0)),
rec(Preflop, 1, Fold, None), rec(Preflop, 1, Fold, None),
rec(Preflop, 2, Fold, None), rec(Preflop, 2, Fold, None),
rec(Preflop, 3, Fold, None), rec(Preflop, 3, Fold, None),
rec(Preflop, 4, Raise, Some(2.5)), rec(Preflop, 4, Raise, Some(2.5)),
rec(Preflop, 5, Fold, None), rec(Preflop, 5, Fold, None),
rec(Preflop, 0, Call, Some(2.5)), rec(Preflop, 0, Call, Some(2.5)),
rec(Flop, 0, Check, None), rec(Flop, 0, Check, None),
rec(Flop, 4, Bet, Some(1.8)), rec(Flop, 4, Bet, Some(1.8)),
rec(Flop, 0, Call, Some(1.8)), rec(Flop, 0, Call, Some(1.8)),
]; ];
h.extend_from_slice(turn); 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] }; let legal = if to_call > 0.0 { vec![ActionKind::Fold, ActionKind::Call, ActionKind::Raise] } else { vec![ActionKind::Check, ActionKind::Raise] };
Spot { Spot {
variant: Variant::Nlhe, variant: Variant::Nlhe,
big_blind: 1.0, big_blind: 1.0,
seats: 6, seats: 6,
hero_seat: 4, hero_seat: 4,
button_seat: Some(4), button_seat: Some(4),
hero_cards: Card::parse_list(hero).unwrap(), hero_cards: Card::parse_list(hero).unwrap(),
board: Card::parse_list("Ah 7d 2c Ks").unwrap(), board: Card::parse_list("Ah 7d 2c Ks").unwrap(),
street: Street::Turn, street: Street::Turn,
pot: 9.1 + pot_extra, pot: 9.1 + pot_extra,
to_call, to_call,
hero_stack: 95.7, hero_stack: 95.7,
min_raise_to: Some(if to_call > 0.0 { 2.0 * to_call } else { 1.0 }), min_raise_to: Some(if to_call > 0.0 { 2.0 * to_call } else { 1.0 }),
max_raise_to: Some(95.7), max_raise_to: Some(95.7),
legal, legal,
allowed_sizes: None, allowed_sizes: None,
villains: vec![Villain { seat: 0, stack: 95.7 - to_call, folded: false, profile: None }], villains: vec![Villain { seat: 0, stack: 95.7 - to_call, folded: false, profile: None }],
seed: 7, seed: 7,
history: h, history: h,
} }
} }
fn facing_bet(hero: &str) -> Spot { fn facing_bet(hero: &str) -> Spot {
s1_turn(&[rec(Street::Turn, 0, SeenAction::Bet, Some(6.0))], hero, 6.0, 6.0) s1_turn(&[rec(Street::Turn, 0, SeenAction::Bet, Some(6.0))], hero, 6.0, 6.0)
} }
fn hero_first(hero: &str) -> Spot { fn hero_first(hero: &str) -> Spot {
// Hero on the button would be last to act; here villain checks and hero decides. // 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) 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`. /// 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<Card>, f64)> { fn range(n: usize, seed: u64, must: &[&str]) -> Vec<(Vec<Card>, 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 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 board = Card::parse_list("Ah 7d 2c Ks").unwrap();
let cards: Vec<Card> = all.into_iter().filter(|c| !board.contains(c)).collect(); let cards: Vec<Card> = all.into_iter().filter(|c| !board.contains(c)).collect();
let mut x = seed; let mut x = seed;
let mut next = || { let mut next = || {
x = x.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); x = x.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
(x >> 33) as usize (x >> 33) as usize
}; };
let mut out: Vec<(Vec<Card>, f64)> = must.iter().map(|m| (Card::parse_list(m).unwrap(), 1.0)).collect(); let mut out: Vec<(Vec<Card>, f64)> = must.iter().map(|m| (Card::parse_list(m).unwrap(), 1.0)).collect();
while out.len() < n { while out.len() < n {
let (a, b) = (cards[next() % cards.len()], cards[next() % cards.len()]); let (a, b) = (cards[next() % cards.len()], cards[next() % cards.len()]);
if a != b && !out.iter().any(|(c, _)| c.contains(&a) && c.contains(&b)) { 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.push((vec![a, b], 0.2 + (next() % 1000) as f64 / 1000.0));
} }
} }
out out
} }
fn cfg(iterations: u32) -> TurnConfig { fn cfg(iterations: u32) -> TurnConfig {
TurnConfig { max_combos: 200, cover: 1.0, river_cards: 12, iterations, measure: true, river_raises: 1 } TurnConfig { max_combos: 200, cover: 1.0, river_cards: 12, iterations, measure: true, river_raises: 1, budget_ms: 0.0 }
} }
#[test] #[test]
fn the_decision_is_a_legal_choice_at_both_kinds_of_node() { fn the_decision_is_a_legal_choice_at_both_kinds_of_node() {
let hands = ["Ac Qd", "7h 7c", "3c 4d", "Kd Qs", "9h 8h"]; 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 (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 { for hero in hands {
let spot = spot_of(hero); let spot = spot_of(hero);
let villain = range(80, 5, &[]); let villain = range(80, 5, &[]);
let me = range(80, 6, &[hero]); let me = range(80, 6, &[hero]);
let s = solve_turn(&spot, &me, &villain, &cfg(60)).expect("heads-up turn decision is in scope"); let s = solve_turn(&spot, &me, &villain, &cfg(60)).expect("heads-up turn decision is in scope");
let sum: f64 = s.row.iter().sum(); let sum: f64 = s.row.iter().sum();
assert!((sum - 1.0).abs() < 1e-9, "{name} {hero}: row {:?}", s.row); assert!((sum - 1.0).abs() < 1e-9, "{name} {hero}: row {:?}", s.row);
match s.decision.choice { match s.decision.choice {
Choice::Fold => assert!(spot.to_call > 0.0, "{name}: fold only when facing a bet"), 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::Check => assert_eq!(spot.to_call, 0.0, "{name}"),
Choice::Call => assert!(spot.to_call > 0.0, "{name}"), Choice::Call => assert!(spot.to_call > 0.0, "{name}"),
Choice::Raise { to } => { Choice::Raise { to } => {
let (lo, hi) = (spot.min_raise_to.unwrap(), spot.max_raise_to.unwrap()); 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}]"); assert!(to >= lo - 1e-9 && to <= hi + 1e-9, "{name} {hero}: raise to {to} outside [{lo}, {hi}]");
} }
Choice::Abstain => panic!("{name} {hero}: abstained"), Choice::Abstain => panic!("{name} {hero}: abstained"),
} }
assert!(spot.is_legal(match s.decision.choice { assert!(spot.is_legal(match s.decision.choice {
Choice::Fold => ActionKind::Fold, Choice::Fold => ActionKind::Fold,
Choice::Check => ActionKind::Check, Choice::Check => ActionKind::Check,
Choice::Call => ActionKind::Call, Choice::Call => ActionKind::Call,
_ => ActionKind::Raise, _ => ActionKind::Raise,
})); }));
} }
} }
} }
#[test] #[test]
fn out_of_position_hero_acts_first_with_check_or_a_bet() { 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). // 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); let mut spot = s1_turn(&[], "Ac Qd", 0.0, 0.0);
spot.hero_seat = 0; spot.hero_seat = 0;
spot.villains = vec![Villain { seat: 4, stack: 95.7, folded: false, profile: None }]; 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 (me, villain) = (range(60, 51, &["Ac Qd"]), range(60, 52, &[]));
let s = solve_turn(&spot, &me, &villain, &cfg(80)).expect("hero first"); 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_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!(s.acts.iter().skip(1).all(|a| matches!(a, Act::Bet(_))));
assert!(matches!(s.decision.choice, Choice::Check | Choice::Raise { .. })); assert!(matches!(s.decision.choice, Choice::Check | Choice::Raise { .. }));
if let Choice::Raise { to } = s.decision.choice { 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); assert!(to >= spot.min_raise_to.unwrap() - 1e-9 && to <= spot.max_raise_to.unwrap() + 1e-9);
} }
} }
#[test] #[test]
fn strong_hands_do_not_fold_and_air_folds_more() { 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). // The villain's range: top pair or better only (aces, kings, pairs of 7 and 2).
let villain: Vec<(Vec<Card>, f64)> = range(400, 21, &[]).into_iter().filter(|(c, _)| c.iter().any(|x| x.rank as u8 >= 11) || c[0].rank == c[1].rank).collect(); let villain: Vec<(Vec<Card>, 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()); assert!(villain.len() > 30, "{}", villain.len());
let me = range(100, 22, &["7s 7c", "3c 4d"]); let me = range(100, 22, &["7s 7c", "3c 4d"]);
let spot_set = facing_bet("7s 7c"); let spot_set = facing_bet("7s 7c");
let spot_air = facing_bet("3c 4d"); let spot_air = facing_bet("3c 4d");
let set = solve_turn(&spot_set, &me, &villain, &cfg(150)).unwrap(); let set = solve_turn(&spot_set, &me, &villain, &cfg(150)).unwrap();
let air = solve_turn(&spot_air, &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); 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!(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); assert!(air.row[0] > set.row[0] + 0.3, "air folds clearly more: {:?} vs {:?}", air.row, set.row);
} }
#[test] #[test]
fn the_solve_is_deterministic_and_the_game_is_balanced_enough() { fn the_solve_is_deterministic_and_the_game_is_balanced_enough() {
let spot = facing_bet("Ac Qd"); let spot = facing_bet("Ac Qd");
let (me, villain) = (range(150, 31, &["Ac Qd"]), range(150, 32, &[])); let (me, villain) = (range(150, 31, &["Ac Qd"]), range(150, 32, &[]));
let a = solve_turn(&spot, &me, &villain, &cfg(200)).unwrap(); let a = solve_turn(&spot, &me, &villain, &cfg(200)).unwrap();
let b = 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.row, b.row);
assert_eq!(a.decision.choice, b.decision.choice, "same input, same answer"); assert_eq!(a.decision.choice, b.decision.choice, "same input, same answer");
let e = a.solved.exploit.expect("measured"); 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()); 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); assert!(e.total < 0.05 * a.solved.pot, "exploitability {} on a {} pot", e.total, a.solved.pot);
} }
#[test] #[test]
fn a_spot_outside_the_game_is_left_to_the_heuristic() { fn a_spot_outside_the_game_is_left_to_the_heuristic() {
let me = range(50, 1, &["Ac Qd"]); let me = range(50, 1, &["Ac Qd"]);
let villain = range(50, 2, &[]); let villain = range(50, 2, &[]);
let mut river = facing_bet("Ac Qd"); let mut river = facing_bet("Ac Qd");
river.street = Street::River; river.street = Street::River;
river.board = Card::parse_list("Ah 7d 2c Ks 9h").unwrap(); river.board = Card::parse_list("Ah 7d 2c Ks 9h").unwrap();
assert!(solve_turn(&river, &me, &villain, &cfg(10)).is_none()); assert!(solve_turn(&river, &me, &villain, &cfg(10)).is_none());
let mut multiway = facing_bet("Ac Qd"); let mut multiway = facing_bet("Ac Qd");
multiway.villains.push(Villain { seat: 1, stack: 90.0, folded: false, profile: None }); 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(&multiway, &me, &villain, &cfg(10)).is_none());
assert!(solve_turn(&facing_bet("Ac Qd"), &me, &[], &cfg(10)).is_none(), "no villain range"); assert!(solve_turn(&facing_bet("Ac Qd"), &me, &[], &cfg(10)).is_none(), "no villain range");
} }
#[test] #[test]
fn off_means_none_and_the_engine_is_unchanged() { fn off_means_none_and_the_engine_is_unchanged() {
let _g = MODE_LOCK.lock().unwrap_or_else(|e| e.into_inner()); let _g = MODE_LOCK.lock().unwrap_or_else(|e| e.into_inner());
set_turn_player(TurnPlayer::Off); set_turn_player(TurnPlayer::Off);
let spots = [facing_bet("Ac Qd"), facing_bet("7s 7c"), hero_first("3c 4d"), hero_first("Kd Qs")]; 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"); let mut flop = hero_first("Ac Qd");
flop.street = Street::Flop; flop.street = Street::Flop;
flop.board.truncate(3); flop.board.truncate(3);
let mut river = facing_bet("Ac Qd"); let mut river = facing_bet("Ac Qd");
river.street = Street::River; river.street = Street::River;
river.board = Card::parse_list("Ah 7d 2c Ks 9h").unwrap(); river.board = Card::parse_list("Ah 7d 2c Ks 9h").unwrap();
for spot in spots.iter().chain([&flop, &river]) { for spot in spots.iter().chain([&flop, &river]) {
assert!(turn_game_decision(spot).is_none(), "off: the hook says nothing"); 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 // 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. // answer is the same either way: compare whole decisions.
if std::env::var_os("GRUNDSTRATEGIE").is_none() { if std::env::var_os("GRUNDSTRATEGIE").is_none() {
let off: Vec<_> = spots.iter().chain([&flop, &river]).map(crate::engine::decide::decide).collect(); let off: Vec<_> = spots.iter().chain([&flop, &river]).map(crate::engine::decide::decide).collect();
set_turn_player(TurnPlayer::Grund); set_turn_player(TurnPlayer::Grund);
let on: Vec<_> = spots.iter().chain([&flop, &river]).map(crate::engine::decide::decide).collect(); let on: Vec<_> = spots.iter().chain([&flop, &river]).map(crate::engine::decide::decide).collect();
set_turn_player(TurnPlayer::Off); set_turn_player(TurnPlayer::Off);
assert_eq!(off, on, "no blueprint: the heuristic plays unchanged"); assert_eq!(off, on, "no blueprint: the heuristic plays unchanged");
} }
assert_eq!(turn_player(), TurnPlayer::Off); assert_eq!(turn_player(), TurnPlayer::Off);
} }
#[test] #[test]
fn the_public_key_ignores_hero_cards_but_not_the_line() { fn the_public_key_ignores_hero_cards_but_not_the_line() {
let c = TurnConfig::STANDARD; let c = TurnConfig::STANDARD;
assert_eq!(public_key(&facing_bet("Ac Qd"), &c), public_key(&facing_bet("7s 7c"), &c)); 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)); assert_ne!(public_key(&facing_bet("Ac Qd"), &c), public_key(&hero_first("Ac Qd"), &c));
} }
#[test] #[test]
#[ignore = "timing probe"] #[ignore = "timing probe"]
fn tree_sizes() { fn tree_sizes() {
use crate::cfr::turn_river_game::{build, TNode, TrBets}; 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)] { 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 g = build(&TrBets::standard(9.1, 95.0, first), &forced);
let chance = g.nodes.iter().filter(|n| matches!(n, TNode::Chance { .. })).count(); 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 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(); 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()); 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`). /// Solve time at table size (run with `--ignored --nocapture`).
#[test] #[test]
#[ignore = "timing probe"] #[ignore = "timing probe"]
fn solve_time_at_table_size() { 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)] { 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 spot = facing_bet("Ac Qd");
let (me, villain) = (range(n, 41, &["Ac Qd"]), range(n, 42, &[])); 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 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 s = solve_turn(&spot, &me, &villain, &c).unwrap();
let e = s.solved.exploit.unwrap(); let e = s.solved.exploit.unwrap();
eprintln!( eprintln!(
"{n} combos, {cards} river cards, {iters} iterations, river raises {rr}: {:.0} ms ({} nodes), exploitability {:.2} % of pot = {:.0} bb/100", "{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.millis,
s.solved.nodes, s.solved.nodes,
e.total / s.solved.pot * 100.0, e.total / s.solved.pot * 100.0,
s.solved.exploit_bb_per_100().unwrap() 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 /// 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. /// blueprint is loaded, for any hero hand (in or out of the pruned range), with a legal choice.
#[test] #[test]
fn stage_b_decides_every_heads_up_turn_from_the_range_model() { fn stage_b_decides_every_heads_up_turn_from_the_range_model() {
let _g = MODE_LOCK.lock().unwrap(); let _g = MODE_LOCK.lock().unwrap();
set_turn_ueberall(false); set_turn_ueberall(false);
assert!(turn_solver_decision(&facing_bet("Qc Jc")).is_none()); assert!(turn_solver_decision(&facing_bet("Qc Jc")).is_none());
set_turn_ueberall(true); set_turn_ueberall(true);
for spot in [facing_bet("Qc Jc"), facing_bet("3s 3d"), hero_first("Ac Kc"), facing_bet("9h 4h")] { 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"); let d = turn_solver_decision(&spot).expect("heads-up turn is in the stage-B slice");
assert!(d.reason.contains("solver turn"), "{}", d.reason); assert!(d.reason.contains("solver turn"), "{}", d.reason);
match d.choice { match d.choice {
Choice::Fold | Choice::Call => assert!(spot.to_call > 0.0), Choice::Fold | Choice::Call => assert!(spot.to_call > 0.0),
Choice::Check => assert_eq!(spot.to_call, 0.0), Choice::Check => assert_eq!(spot.to_call, 0.0),
_ => {} _ => {}
} }
} }
let mut multi = facing_bet("Qc Jc"); let mut multi = facing_bet("Qc Jc");
multi.villains.push(Villain { seat: 1, stack: 90.0, folded: false, profile: None }); multi.villains.push(Villain { seat: 1, stack: 90.0, folded: false, profile: None });
assert!(turn_solver_decision(&multi).is_none()); assert!(turn_solver_decision(&multi).is_none());
set_turn_ueberall(false); set_turn_ueberall(false);
} }