Files
pokerfreak/src/engine/flop_spieler.rs
T

244 lines
10 KiB
Rust

//! 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<f64>,
acts: Vec<Act>,
hero_masks: Vec<u64>,
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<Card>, f64)], villain_list: &[(Vec<Card>, f64)], cfg: &FlopConfig, keep: Option<u64>, source: &'static str) -> Option<Solved> {
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 started.elapsed().as_secs_f64() * 1e3 > cfg.budget_ms {
break;
}
}
if done < MIN_ITERS {
return None;
}
let strategy = solver.strategy();
let rows: Vec<f64> = (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<Decision> {
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<Option<HashMap<u64, Arc<Solved>>>> = 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<Decision> {
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 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()));
if let Some(d) = cached.and_then(|s| decide_from(spot, &s, hero_mask)) {
return Some(d);
}
// One solve per decision, inside what is left of the flop's total: the shared public-state solve
// (cached) when hero's hand survives the pruning, else a solve with hero's hand kept (not cached).
let (hero, villain, source) = lists()?;
let budget = crate::engine::frist::budget_ms(cfg.budget_ms, crate::engine::frist::FLOP_MS);
if budget <= 0.0 {
return None;
}
let cfg = FlopConfig { budget_ms: budget, ..cfg };
let pc = TurnConfig { max_combos: cfg.max_combos, cover: 0.95, ..TurnConfig::STANDARD };
if prune(&hero, fast7::mask(&spot.board), &pc, None).masks.contains(&hero_mask) {
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());
}
return decide_from(spot, &solved, hero_mask);
}
let own = solve_flop(spot, &hero, &villain, &cfg, Some(hero_mask), source)?;
decide_from(spot, &own, hero_mask)
}
#[cfg(test)]
mod tests;