Merge sechsmax-messung: 6-max-Leiter und Multiway-LBR (Owner-OK 15.11.)

Bit-Identitaet vom Branch belegt: 815/815 Spots byte-gleich (Schalter aus).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-15 00:48:57 +01:00
co-authored by Claude Opus 5.5
858 changed files with 28917 additions and 1320 deletions
+30 -2
View File
@@ -102,9 +102,36 @@ fn postflop(spot: &Spot, thresholds: &Thresholds, raw: &Spot, premium: f64) -> D
if let Some(d) = super::river_subgame::dbr_decision(raw) {
return d.with_equity(equity.share);
}
// Stage A, solver everywhere (off by default, SOLVER_RIVER): the heads-up river decided
// by an equilibrium solve over real combos, ranges from the line (`engine::river_spieler`).
if let Some(d) = super::river_spieler::river_spieler_decision(raw) {
return d.with_equity(equity.share);
}
// Multiway river (off by default, SOLVER_RIVER3): 3- and 4-handed rivers decided by
// Monte-Carlo CFR over real combos (`engine::river3_spieler`).
if let Some(d) = super::river3_spieler::river3_decision(raw) {
return d.with_equity(equity.share);
}
// Arm (off by default, TURN_SPIEL=grund): the turn+river game with ranges from the
// blueprint (`engine::turn_game`); `None` while the switch is off.
if let Some(d) = super::turn_game::turn_game_decision(raw) {
// blueprint (`engine::turn_game`); `None` while the switch is off. Stage B supersedes it
// when on (same game, blueprint ranges where recognised, hero's hand always kept, inside
// the turn deadline): E3 first would spend the deadline and then hand pruned hands to the
// heuristic.
let e3 = if super::turn_game::turn_ueberall() { None } else { super::turn_game::turn_game_decision(raw) };
if let Some(d) = e3 {
return d.with_equity(equity.share);
}
// Stage B, solver everywhere (off by default, SOLVER_TURN): every heads-up turn.
if let Some(d) = super::turn_game::turn_solver_decision(raw) {
return d.with_equity(equity.share);
}
// Multiway turn and flop (off by default, SOLVER_TURN3 / SOLVER_FLOP3): 3- and 4-handed
// spots decided by Monte-Carlo CFR over the remaining streets (`engine::multi3_spieler`).
if let Some(d) = super::multi3_spieler::multi3_decision(raw) {
return d.with_equity(equity.share);
}
// Stage C, solver everywhere (off by default, SOLVER_FLOP): every heads-up flop.
if let Some(d) = super::flop_spieler::flop_spieler_decision(raw) {
return d.with_equity(equity.share);
}
return super::river_subgame::fold_veto(raw, floored);
@@ -203,6 +230,7 @@ pub fn decide_with(spot: &Spot, lage: Option<&Turnierlage>) -> Decision {
// Chip-lineares Geld (der Sieger nimmt alles, alle Verbliebenen gleich bezahlt, p1 > p2 = ... = pn):
// ICM IST Chip-EV, also genau der Cash-Pfad. Eine unbepreisbare Lage bleibt ein Aussetzen.
let lage = lage.filter(|l| !(l.is_usable() && l.is_chip_linear()));
super::frist::begin();
// Only act on reads we are proven to beat blind play with (`read_gate`); competent and
// aggressive opponents are played blind until the exploit logic earns them on the ladder.
let gated = super::read_gate::gate_reads(spot);
+243
View File
@@ -0,0 +1,243 @@
//! 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;
+131
View File
@@ -0,0 +1,131 @@
use super::*;
use crate::card::Card;
use crate::cfr::turn_river_game::Hands;
use crate::game::{ActionKind, ActionRecord, Choice, SeenAction, Spot, Street, Villain};
use crate::variant::Variant;
static MODE_LOCK: Mutex<()> = Mutex::new(());
fn rec(street: Street, seat: u8, action: SeenAction, amount: Option<f64>) -> ActionRecord {
ActionRecord { street, seat, action, amount }
}
/// Button (seat 4) opens 2.5, big blind (seat 0) calls; `flop` is the flop line so far; hero = button.
fn flop_spot(flop: &[ActionRecord], hero: &str, to_call: 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)),
];
h.extend_from_slice(flop);
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").unwrap(),
street: Street::Flop,
pot: 5.5 + to_call,
to_call,
hero_stack: 97.5,
min_raise_to: Some(if to_call > 0.0 { 2.0 * to_call } else { 1.0 }),
max_raise_to: Some(97.5),
legal,
allowed_sizes: None,
villains: vec![Villain { seat: 0, stack: 97.5 - to_call, folded: false, profile: None }],
seed: 11,
history: h,
}
}
fn checked_to(hero: &str) -> Spot {
flop_spot(&[rec(Street::Flop, 0, SeenAction::Check, None)], hero, 0.0)
}
fn facing_bet(hero: &str) -> Spot {
flop_spot(&[rec(Street::Flop, 0, SeenAction::Bet, Some(4.0))], hero, 4.0)
}
#[test]
#[ignore]
fn timing() {
for hero in ["Ac As", "Td 9c"] {
for spot in [facing_bet(hero), checked_to(hero)] {
let (h, v) = crate::engine::river_spieler::model_lists(&spot).unwrap();
let cfg = FlopConfig { budget_ms: 1e9, ..FlopConfig::STANDARD };
let s = solve_flop(&spot, &h, &v, &cfg, Some(fast7::mask(&spot.hero_cards)), "modell").unwrap();
eprintln!("{}x{} combos {} nodes {} iters {:.0} ms", s.combos[0], s.combos[1], s.nodes, s.iterations, s.millis);
}
}
}
#[test]
fn off_decides_nothing_and_on_decides_heads_up_flops() {
let _g = MODE_LOCK.lock().unwrap();
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);
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 = 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);
}
/// The equity showdown is exact: AA vs KK on Q72 rainbow after a blank turn loses only to a river king
/// (two kings left among 44 river cards).
#[test]
fn the_river_equity_table_is_exact() {
let board = fast7::mask(&Card::parse_list("Qh 7d 2c").unwrap());
let aa = fast7::mask(&Card::parse_list("As Ad").unwrap());
let kk = fast7::mask(&Card::parse_list("Ks Kd").unwrap());
let game = build(&flop_bets(5.5, 97.5, 1), &[]);
let hands = [Hands { masks: vec![aa], weights: vec![1.0] }, Hands { masks: vec![kk], weights: vec![1.0] }];
let turn = fast7::bit(Card::parse_list("3s").unwrap()[0]);
let s = TrSolver::with_cards(game, hands, board, vec![turn], 1.0).with_river_equity(board);
let eq = s.eq.as_ref().unwrap()[0][0];
// 44 river cards left (52 - 3 board - turn - 4 hole); KK wins with Kh or Kc only.
assert!((eq - 42.0 / 44.0).abs() < 1e-5, "eq {eq}");
}
/// Facing a pot bet with total air the solver folds mostly; with top set it never folds.
#[test]
fn sets_continue_air_folds() {
let cfg = FlopConfig::STANDARD;
let row = |hero: &str| {
let spot = facing_bet(hero);
let (h, v) = crate::engine::river_spieler::model_lists(&spot).unwrap();
let m = fast7::mask(&spot.hero_cards);
let s = solve_flop(&spot, &h, &v, &cfg, Some(m), "modell").unwrap();
let i = s.hero_masks.iter().position(|x| *x == m).unwrap();
let a = s.acts.len();
(s.rows[i * a..(i + 1) * a].to_vec(), s.acts.clone())
};
let (r, acts) = row("Ac As");
let fold = |r: &[f64], acts: &[Act]| r.iter().zip(acts).filter(|(_, a)| **a == Act::Fold).map(|(p, _)| p).sum::<f64>();
assert!(fold(&r, &acts) < 0.01, "top set folds {r:?}");
let (r, acts) = row("5s 4s");
let _ = (r, acts); // a gutshot with a backdoor: no assertion on frequency, only that it solves
let (r, acts) = row("Td 9c");
assert!(fold(&r, &acts) > 0.5, "ten-high air calls {r:?} {acts:?}");
}
+50
View File
@@ -0,0 +1,50 @@
//! The decision deadline of the postflop solvers ("Solver ueberall"): `decide_with` marks the start of
//! each decision on its thread, and a solver gets what is left of its street's total before it starts.
//! Totals per decision (live table): river and flop 2 s, turn 1.25 s, each minus `MARGIN_MS` for the
//! work after the solve. Without a mark (tests, tools calling a solver directly) the full total is left.
use std::cell::Cell;
use std::time::Instant;
thread_local! {
static START: Cell<Option<Instant>> = const { Cell::new(None) };
}
/// Total wall time of one decision per street, in ms.
pub const RIVER_MS: f64 = 2000.0;
pub const TURN_MS: f64 = 1250.0;
pub const FLOP_MS: f64 = 2000.0;
/// Kept free after the solve (strategy readout, sampling, the answer).
pub const MARGIN_MS: f64 = 150.0;
/// Mark the start of a decision on this thread.
pub fn begin() {
START.with(|s| s.set(Some(Instant::now())));
}
/// Milliseconds since the mark (0 without one).
pub fn elapsed_ms() -> f64 {
START.with(|s| s.get().map_or(0.0, |t| t.elapsed().as_secs_f64() * 1e3))
}
/// What a solver may still spend of `total_ms` (may be ≤ 0: then it must not start).
pub fn left_ms(total_ms: f64) -> f64 {
total_ms - MARGIN_MS - elapsed_ms()
}
/// Measurement switch `SOLVER_ZEIT=fest`: solvers ignore wall time and always run their full iteration
/// count, so ladder and LBR results do not depend on machine load (read once).
pub fn fixed() -> bool {
static FIXED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*FIXED.get_or_init(|| std::env::var("SOLVER_ZEIT").as_deref() == Ok("fest"))
}
/// The budget a solve gets: `cap_ms` (its own limit), cut to what is left of the street's total;
/// infinite under `SOLVER_ZEIT=fest`.
pub fn budget_ms(cap_ms: f64, total_ms: f64) -> f64 {
if fixed() {
f64::INFINITY
} else {
cap_ms.min(left_ms(total_ms))
}
}
+5
View File
@@ -9,6 +9,8 @@ pub mod called_equity;
pub mod decide;
pub mod double_board;
pub mod effective;
pub mod flop_spieler;
pub mod frist;
pub mod from_plan;
pub mod multiway;
pub mod omaha_combos;
@@ -19,6 +21,9 @@ pub mod read_gate;
pub mod range_combos;
pub mod range_filter;
pub mod read_label;
pub mod multi3_spieler;
pub mod river3_spieler;
pub mod river_spieler;
pub mod river_subgame;
pub mod run_twice;
pub mod semibluff;
+186
View File
@@ -0,0 +1,186 @@
//! "Solver everywhere", the MULTIWAY turn and flop: 3- and 4-handed spots decided by Monte-Carlo CFR
//! over real combos across the remaining streets (`cfr::multi3`), the sibling of the multiway river
//! (`engine::river3_spieler`, same ranges, line replay and approximations). Switches `SOLVER_TURN3`
//! and `SOLVER_FLOP3` (default off: no decision, the engine is bit-identical).
//!
//! - **Turn game:** turn betting (33/75 % pot, all-in, one raise ×3), `TURN_SLOTS` river cards, river
//! betting (75 % pot, all-in, one raise), showdown.
//! - **Flop game:** flop betting (as the turn above), `FLOP_SLOTS` turn cards, turn betting (75 %,
//! all-in, one raise), the river dealt and checked down (as stage C, no river betting).
//! - **Ranges** per player from the range model of the line (gated reads), at most `MAX_COMBOS`.
//! - **Time:** `frist::TURN_MS` / `frist::FLOP_MS` per decision, own caps `TURN_BUDGET_MS` /
//! `FLOP_BUDGET_MS`; under `MIN_ITERS` iterations the heuristic decides.
//!
//! Named approximations: no equilibrium guarantee with three players; stacks capped at the smallest
//! live stack (no side pots); the next street's card from a few slots; one size on later streets.
use crate::cfr::multi3::{GameM, NodeM, SolverM};
use crate::cfr::river3::Menu3;
use crate::cfr::river_game::Act;
use crate::engine::river3_spieler::{acting_order, model_hands, street_line3};
use crate::engine::river_subgame::legal_choice;
use crate::game::{Decision, Spot, Street, Villain};
use crate::hand::fast7;
use crate::rng::Rng;
use std::sync::atomic::{AtomicBool, Ordering};
static TURN3: AtomicBool = AtomicBool::new(false);
static FLOP3: AtomicBool = AtomicBool::new(false);
pub fn set_turn3(on: bool) {
TURN3.store(on, Ordering::Relaxed);
}
pub fn set_flop3(on: bool) {
FLOP3.store(on, Ordering::Relaxed);
}
pub fn turn3() -> bool {
TURN3.load(Ordering::Relaxed)
}
pub fn flop3() -> bool {
FLOP3.load(Ordering::Relaxed)
}
fn on(key: &str) -> bool {
matches!(std::env::var(key).as_deref(), Ok("1") | Ok("an"))
}
/// `SOLVER_TURN3=1`, `SOLVER_FLOP3=1`.
pub fn from_env() -> (bool, bool) {
(on("SOLVER_TURN3"), on("SOLVER_FLOP3"))
}
/// Iteration cap (and the count under `SOLVER_ZEIT=fest`).
pub const ITERS: u32 = 12_000;
/// Fewest iterations a decision may rest on.
pub const MIN_ITERS: u32 = 1_000;
/// Own caps of one solve, inside the street's decision total.
pub const TURN_BUDGET_MS: f64 = 1050.0;
pub const FLOP_BUDGET_MS: f64 = 1700.0;
/// Most combos per player.
pub const MAX_COMBOS: usize = 200;
pub const TURN_SLOTS: usize = 8;
pub const FLOP_SLOTS: usize = 6;
fn later() -> Menu3 {
Menu3 { fracs: vec![0.75], raise_mult: 3.0, max_raises: 1, allin: true }
}
pub struct SolvedM {
pub row: Vec<f64>,
pub acts: Vec<Act>,
pub iterations: u64,
pub millis: f64,
pub players: usize,
pub nodes: usize,
pub combos: Vec<usize>,
}
/// Solve this 3- or 4-handed turn or flop (gated spot) and return hero's average strategy at its node.
pub fn solve_multi3(spot: &Spot) -> Option<SolvedM> {
let villains = spot.live_villains().count();
let (cards, cap_ms, total, slots) = match spot.street {
Street::Turn => (4, TURN_BUDGET_MS, crate::engine::frist::TURN_MS, TURN_SLOTS),
Street::Flop => (3, FLOP_BUDGET_MS, crate::engine::frist::FLOP_MS, FLOP_SLOTS),
_ => return None,
};
if spot.board.len() != cards || spot.hero_cards.len() != 2 || !(2..=3).contains(&villains) {
return None;
}
let budget = crate::engine::frist::budget_ms(cap_ms, total);
if budget <= 0.0 {
return None;
}
let started = std::time::Instant::now();
let order = acting_order(spot)?;
let (line, c) = street_line3(spot, &order, spot.street)?;
let me = order.iter().position(|s| *s == spot.hero_seat)?;
let stack_of = |seat: u8| -> f64 {
if seat == spot.hero_seat {
spot.hero_stack
} else {
spot.live_villains().find(|v| v.seat == seat).map_or(0.0, |v| v.stack)
}
};
let cap = order.iter().enumerate().map(|(i, s)| stack_of(*s) + c[i]).fold(f64::INFINITY, f64::min);
let pot = spot.pot - c.iter().sum::<f64>();
if pot <= 0.0 || !cap.is_finite() || cap <= c.iter().copied().fold(0.0, f64::max) {
return None;
}
let board = fast7::mask(&spot.board);
let hero_mask = fast7::mask(&spot.hero_cards);
let mut hands = Vec::with_capacity(order.len());
for seat in &order {
let h = if *seat == spot.hero_seat {
model_hands(spot, &Villain { seat: *seat, stack: spot.hero_stack, folded: false, profile: None }, board, Some(hero_mask), MAX_COMBOS)?
} else {
let v = spot.live_villains().find(|v| v.seat == *seat)?;
model_hands(spot, v, board, None, MAX_COMBOS)?
};
hands.push(h);
}
let game = GameM::build(order.len(), pot, cap, &[Menu3::standard(), later()], slots);
let at = game.follow(&line)?;
let NodeM::Dec { player, acts, .. } = &game.nodes[at] else { return None };
if *player != me {
return None;
}
let acts = acts.clone();
let nodes = game.nodes.len();
let combos: Vec<usize> = hands.iter().map(|h| h.masks.len()).collect();
let hero_index = hands[me].masks.iter().position(|m| *m == hero_mask)?;
let mut solver = SolverM::new(game, hands, board, spot.seed ^ 0x9e37_79b9_7f4a_7c15);
let mut done = 0u32;
while done < ITERS {
solver.iterate();
done += 1;
if done % 50 == 0 && started.elapsed().as_secs_f64() * 1e3 > budget {
break;
}
}
if done < MIN_ITERS {
return None;
}
let row = solver.row(at, hero_index);
Some(SolvedM { row, acts, iterations: solver.iterations(), millis: started.elapsed().as_secs_f64() * 1e3, players: order.len(), nodes, combos })
}
/// The live multiway turn/flop decision, or `None` and the heuristic keeps it.
pub fn multi3_decision(raw: &Spot) -> Option<Decision> {
let on = match raw.street {
Street::Turn => turn3(),
Street::Flop => flop3(),
_ => false,
};
if !on || raw.hero_cards.len() != 2 || raw.live_villains().count() < 2 {
return None;
}
let gated = crate::engine::read_gate::gate_reads(raw);
let s = solve_multi3(&gated)?;
let (draw, _) = Rng::seeded(gated.seed).unit();
let mut acc = 0.0;
let mut pick = s.acts.len() - 1;
for (k, p) in s.row.iter().enumerate() {
acc += p;
if draw < acc {
pick = k;
break;
}
}
let act = s.acts[pick];
let p = s.row[pick];
let street = if gated.street == Street::Turn { "turn3" } else { "flop3" };
Some(Decision::new(
legal_choice(&gated, act),
p.clamp(0.0, 1.0),
format!(
"solver {street} ({} players): {:?} combos, {} nodes, {} iters, {act:?} p {p:.2}, {:.0} ms",
s.players, s.combos, s.nodes, s.iterations, s.millis
),
))
}
#[cfg(test)]
mod tests;
+108
View File
@@ -0,0 +1,108 @@
use super::*;
use crate::card::Card;
use crate::game::{ActionKind, ActionRecord, Choice, SeenAction, Spot, Street, Villain};
use crate::variant::Variant;
use std::sync::Mutex;
static LOCK: Mutex<()> = Mutex::new(());
fn rec(street: Street, seat: u8, action: SeenAction, amount: Option<f64>) -> ActionRecord {
ActionRecord { street, seat, action, amount }
}
/// Six-max, three-way: button (hero, seat 4) opens 2.5, SB (5) and BB (0) call (pot 7.5). On the flop
/// SB checks, BB bets 3.75, hero to act. On the turn (flop bet called by all, pot 18.75) SB checks, BB
/// bets 6, hero to act.
fn three_way(street: Street, hero: &str) -> Spot {
use SeenAction::*;
use Street::*;
let mut history = 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, Call, Some(2.5)),
rec(Preflop, 0, Call, Some(2.5)),
rec(Flop, 5, Check, None),
rec(Flop, 0, Bet, Some(3.75)),
];
let (board, pot, to_call, stack) = if street == Flop {
("Ah 7d 2c", 11.25, 3.75, 97.5)
} else {
history.extend([rec(Flop, 4, Call, Some(3.75)), rec(Flop, 5, Call, Some(3.75)), rec(Turn, 5, Check, None), rec(Turn, 0, Bet, Some(6.0))]);
("Ah 7d 2c Ks", 24.75, 6.0, 93.75)
};
Spot {
variant: Variant::Nlhe,
big_blind: 1.0,
seats: 6,
hero_seat: 4,
button_seat: None,
hero_cards: Card::parse_list(hero).unwrap(),
board: Card::parse_list(board).unwrap(),
street,
pot,
to_call,
hero_stack: stack,
min_raise_to: Some(2.0 * to_call),
max_raise_to: Some(stack),
legal: vec![ActionKind::Fold, ActionKind::Call, ActionKind::Raise],
allowed_sizes: None,
villains: vec![
Villain { seat: 5, stack, folded: false, profile: None },
Villain { seat: 0, stack: stack - to_call, folded: false, profile: None },
],
seed: 9,
history,
}
}
fn fold(s: &SolvedM) -> f64 {
s.row.iter().zip(&s.acts).filter(|(_, a)| **a == Act::Fold).map(|(p, _)| p).sum()
}
#[test]
fn off_decides_nothing_and_heads_up_is_not_in_the_slice() {
let _g = LOCK.lock().unwrap();
set_turn3(false);
set_flop3(false);
assert!(multi3_decision(&three_way(Street::Turn, "As Ad")).is_none());
assert!(multi3_decision(&three_way(Street::Flop, "As Ad")).is_none());
set_turn3(true);
set_flop3(true);
let mut hu = three_way(Street::Turn, "As Ad");
hu.villains.pop();
assert!(multi3_decision(&hu).is_none());
set_turn3(false);
set_flop3(false);
}
#[test]
fn on_decides_three_way_turns_and_flops_legally_and_in_time() {
let _g = LOCK.lock().unwrap();
set_turn3(true);
set_flop3(true);
for (street, limit, tag) in [(Street::Turn, 1.25, "solver turn3 (3 players)"), (Street::Flop, 2.0, "solver flop3 (3 players)")] {
for hero in ["As Ad", "6s 5d", "Kc Qc"] {
let t = std::time::Instant::now();
let d = multi3_decision(&three_way(street, hero)).expect("3-way spot is in the slice");
assert!(t.elapsed().as_secs_f64() < limit, "{street:?} {:?}", t.elapsed());
assert!(d.reason.contains(tag), "{}", d.reason);
assert!(matches!(d.choice, Choice::Fold | Choice::Call | Choice::Raise { .. }), "{:?}", d.choice);
}
}
set_turn3(false);
set_flop3(false);
}
#[test]
fn top_set_continues_and_air_folds_three_way() {
for street in [Street::Turn, Street::Flop] {
let s = solve_multi3(&three_way(street, "As Ad")).unwrap();
assert!(fold(&s) < 0.05, "{street:?} {:?} {:?}", s.row, s.acts);
}
let s = solve_multi3(&three_way(Street::Turn, "6s 5d")).unwrap();
assert!(fold(&s) > 0.6, "{:?} {:?}", s.row, s.acts);
}
+230
View File
@@ -0,0 +1,230 @@
//! "Solver everywhere", the MULTIWAY river: 3- and 4-handed river spots decided by Monte-Carlo CFR over
//! real combos (`cfr::river3`), as Pluribus solves multiway subgames. Switch `SOLVER_RIVER3` (default
//! off: no decision, the engine is bit-identical).
//!
//! - **Players** in post-flop acting order (small blind first, from the blinds in the history), hero
//! among them; ranges per player from the range model of the action history (`range_spec`: hero's
//! own line without a read, each villain's with its gated read), weight 1 per combo, hero's real hand
//! added at a token weight if the model range does not hold it.
//! - **The observed river line** is replayed into the tree (nearest size); a river line the tree
//! cannot hold (a folded player's bet, an inconsistent price) leaves the spot to the heuristic.
//! - **Named approximations:** no equilibrium guarantee with three players; stacks capped at the
//! smallest live stack (no side pots); two bet sizes, one raise; Monte-Carlo noise (the average
//! strategy of hero's hand after `ITERS` or the time budget).
//! - **Time:** `frist::RIVER_MS` per decision; under `MIN_ITERS` iterations the heuristic decides.
use crate::card::Card;
use crate::cfr::river3::{Game3, Hands3, Menu3, Node3, Solver3};
use crate::cfr::river_game::Act;
use crate::engine::river_subgame::legal_choice;
use crate::game::{Decision, SeenAction, Spot, Street, Villain};
use crate::hand::fast7;
use crate::rng::Rng;
use std::sync::atomic::{AtomicBool, Ordering};
static ON: AtomicBool = AtomicBool::new(false);
pub fn set_river3(on: bool) {
ON.store(on, Ordering::Relaxed);
}
pub fn river3() -> bool {
ON.load(Ordering::Relaxed)
}
/// `SOLVER_RIVER3=1`.
pub fn from_env() -> bool {
matches!(std::env::var("SOLVER_RIVER3").as_deref(), Ok("1") | Ok("an"))
}
/// Iteration cap (and the count under `SOLVER_ZEIT=fest`).
pub const ITERS: u32 = 40_000;
/// Fewest iterations a decision may rest on.
pub const MIN_ITERS: u32 = 3_000;
/// Own cap of one solve, inside the river's decision total.
pub const BUDGET_MS: f64 = 1500.0;
/// Most combos per player (heaviest first, model weights are equal: the first in the model's order).
pub const MAX_COMBOS: usize = 300;
const TOKEN: f64 = 1e-6;
/// The live seats (hero and the villains still in) in post-flop acting order, from the blinds:
/// the small blind acts first, then clockwise. `None` without blinds in the history.
pub fn acting_order(spot: &Spot) -> Option<Vec<u8>> {
let n = spot.seats.max(2) as i32;
let sb = spot.history.iter().find(|r| r.street == Street::Preflop && r.action == SeenAction::PostSmallBlind).map(|r| r.seat as i32);
let bb = spot.history.iter().find(|r| r.street == Street::Preflop && r.action == SeenAction::PostBigBlind).map(|r| r.seat as i32);
let first = match (sb, bb) {
(Some(s), _) => s,
(None, Some(b)) => b - 1,
_ => return None,
};
let mut seats: Vec<u8> = std::iter::once(spot.hero_seat).chain(spot.live_villains().map(|v| v.seat)).collect();
seats.sort_by_key(|s| (*s as i32 - first).rem_euclid(n));
Some(seats)
}
/// The observed line of `street` among the live players: `(index in order, act)` and the street
/// contributions per player; `None` if it is not consistent with hero's price.
pub(crate) fn street_line3(spot: &Spot, order: &[u8], street: Street) -> Option<(Vec<(usize, Act)>, Vec<f64>)> {
let mut c = vec![0.0; order.len()];
let mut line = Vec::new();
let mut aggressed = false;
for r in spot.history.iter().filter(|r| r.street == street) {
let Some(who) = order.iter().position(|s| *s == r.seat) else {
// A player no longer in: a check or fold is harmless, money in is not representable.
if matches!(r.action, SeenAction::Bet | SeenAction::Raise | SeenAction::AllIn | SeenAction::Call) {
return None;
}
continue;
};
let top = c.iter().copied().fold(0.0, f64::max);
let amount = r.amount.unwrap_or(c[who]);
match r.action {
SeenAction::Check => line.push((who, Act::Check)),
SeenAction::Bet | SeenAction::Raise | SeenAction::AllIn if amount > top => {
line.push((who, if aggressed { Act::Raise(amount) } else { Act::Bet(amount) }));
aggressed = true;
c[who] = amount;
}
SeenAction::Call | SeenAction::AllIn => {
line.push((who, Act::Call));
c[who] = top;
}
SeenAction::Fold => return None,
_ => {}
}
}
let me = order.iter().position(|s| *s == spot.hero_seat)?;
let top = c.iter().copied().fold(0.0, f64::max);
((top - c[me] - spot.to_call).abs() < 1e-6 * spot.pot.max(1.0)).then_some((line, c))
}
/// The model range of `who`'s line, as card masks off the board (weight 1 each), heaviest-first order
/// of the model, at most `MAX_COMBOS`; `keep` joins at a token weight if missing.
pub(crate) fn model_hands(spot: &Spot, who: &Villain, board: u64, keep: Option<u64>, max: usize) -> Option<Hands3> {
let rules = spot.rules();
let filter = crate::engine::range_filter::range_filter(&crate::exploit::range_model::range_spec(spot, who), rules, spot.variant, &spot.board);
let list: Vec<Vec<Card>> = crate::engine::range_combos::combos(&rules, &filter, &spot.board)?;
let mut masks: Vec<u64> = list.iter().filter(|c| c.len() == 2).map(|c| fast7::mask(c)).filter(|m| m & board == 0 && m.count_ones() == 2).collect();
masks.sort_unstable();
masks.dedup();
if masks.len() > max {
// Evenly strided, so the kept range keeps its shape (the model gives no weights to rank by).
let step = masks.len() as f64 / max as f64;
masks = (0..max).map(|k| masks[(k as f64 * step) as usize]).collect();
}
let mut weights = vec![1.0; masks.len()];
if let Some(k) = keep {
if !masks.contains(&k) {
masks.push(k);
weights.push(TOKEN);
}
}
(!masks.is_empty()).then_some(Hands3 { masks, weights })
}
pub struct Solved3 {
pub row: Vec<f64>,
pub acts: Vec<Act>,
pub iterations: u64,
pub millis: f64,
pub players: usize,
pub nodes: usize,
pub combos: Vec<usize>,
}
/// Solve this 3- or 4-handed river (gated spot) and return hero's average strategy at its node.
pub fn solve_river3(spot: &Spot) -> Option<Solved3> {
let villains = spot.live_villains().count();
if spot.street != Street::River || spot.board.len() != 5 || spot.hero_cards.len() != 2 || !(2..=3).contains(&villains) {
return None;
}
let budget = crate::engine::frist::budget_ms(BUDGET_MS, crate::engine::frist::RIVER_MS);
if budget <= 0.0 {
return None;
}
let started = std::time::Instant::now();
let order = acting_order(spot)?;
let (line, c) = street_line3(spot, &order, Street::River)?;
let me = order.iter().position(|s| *s == spot.hero_seat)?;
let stack_of = |seat: u8| -> f64 {
if seat == spot.hero_seat {
spot.hero_stack
} else {
spot.live_villains().find(|v| v.seat == seat).map_or(0.0, |v| v.stack)
}
};
let cap = order.iter().enumerate().map(|(i, s)| stack_of(*s) + c[i]).fold(f64::INFINITY, f64::min);
let pot = spot.pot - c.iter().sum::<f64>();
if pot <= 0.0 || !cap.is_finite() || cap <= c.iter().copied().fold(0.0, f64::max) {
return None;
}
let board = fast7::mask(&spot.board);
let hero_mask = fast7::mask(&spot.hero_cards);
let mut hands = Vec::with_capacity(order.len());
for seat in &order {
let h = if *seat == spot.hero_seat {
model_hands(spot, &Villain { seat: *seat, stack: spot.hero_stack, folded: false, profile: None }, board, Some(hero_mask), MAX_COMBOS)?
} else {
let v = spot.live_villains().find(|v| v.seat == *seat)?;
model_hands(spot, v, board, None, MAX_COMBOS)?
};
hands.push(h);
}
let game = Game3::build(order.len(), pot, cap, &Menu3::standard());
let at = game.follow(&line)?;
let Node3::Dec { player, acts, .. } = &game.nodes[at] else { return None };
if *player != me {
return None;
}
let acts = acts.clone();
let nodes = game.nodes.len();
let combos: Vec<usize> = hands.iter().map(|h| h.masks.len()).collect();
let hero_index = hands[me].masks.iter().position(|m| *m == hero_mask)?;
let mut solver = Solver3::new(game, hands, board, spot.seed ^ 0x9e37_79b9_7f4a_7c15);
let mut done = 0u32;
while done < ITERS {
solver.iterate();
done += 1;
if done % 200 == 0 && started.elapsed().as_secs_f64() * 1e3 > budget {
break;
}
}
if done < MIN_ITERS {
return None;
}
let row = solver.row(at, hero_index);
Some(Solved3 { row, acts, iterations: solver.iterations(), millis: started.elapsed().as_secs_f64() * 1e3, players: order.len(), nodes, combos })
}
/// The live multiway-river decision, or `None` and the heuristic keeps it.
pub fn river3_decision(raw: &Spot) -> Option<Decision> {
if !river3() || raw.street != Street::River || raw.hero_cards.len() != 2 || raw.board.len() != 5 {
return None;
}
let gated = crate::engine::read_gate::gate_reads(raw);
let s = solve_river3(&gated)?;
let (draw, _) = Rng::seeded(gated.seed).unit();
let mut acc = 0.0;
let mut pick = s.acts.len() - 1;
for (k, p) in s.row.iter().enumerate() {
acc += p;
if draw < acc {
pick = k;
break;
}
}
let act = s.acts[pick];
let p = s.row[pick];
Some(Decision::new(
legal_choice(&gated, act),
p.clamp(0.0, 1.0),
format!(
"river3 solver ({} players): {:?} combos, {} nodes, {} iters, {act:?} p {p:.2}, {:.0} ms",
s.players, s.combos, s.nodes, s.iterations, s.millis
),
))
}
#[cfg(test)]
mod tests;
+102
View File
@@ -0,0 +1,102 @@
use super::*;
use crate::game::{ActionKind, ActionRecord, Choice, SeenAction, Spot, Street, Villain};
use crate::variant::Variant;
use std::sync::Mutex;
static LOCK: Mutex<()> = Mutex::new(());
fn rec(street: Street, seat: u8, action: SeenAction, amount: Option<f64>) -> ActionRecord {
ActionRecord { street, seat, action, amount }
}
/// Six-max, three-way to the river: button (hero, seat 4) opens 2.5, small blind (5) and big blind
/// (0) call; flop SB check, BB check, BTN bets 3.75, both call; turn checked through; river SB check,
/// BB bets 10, hero to act. Pot before the river 18.75.
fn three_way(hero: &str) -> Spot {
use SeenAction::*;
use Street::*;
let history = 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, Call, Some(2.5)),
rec(Preflop, 0, Call, Some(2.5)),
rec(Flop, 5, Check, None),
rec(Flop, 0, Check, None),
rec(Flop, 4, Bet, Some(3.75)),
rec(Flop, 5, Call, Some(3.75)),
rec(Flop, 0, Call, Some(3.75)),
rec(Turn, 5, Check, None),
rec(Turn, 0, Check, None),
rec(Turn, 4, Check, None),
rec(River, 5, Check, None),
rec(River, 0, Bet, Some(10.0)),
];
Spot {
variant: Variant::Nlhe,
big_blind: 1.0,
seats: 6,
hero_seat: 4,
button_seat: None,
hero_cards: Card::parse_list(hero).unwrap(),
board: Card::parse_list("Ah 7d 2c Ks 3h").unwrap(),
street: Street::River,
pot: 28.75,
to_call: 10.0,
hero_stack: 93.75,
min_raise_to: Some(20.0),
max_raise_to: Some(93.75),
legal: vec![ActionKind::Fold, ActionKind::Call, ActionKind::Raise],
allowed_sizes: None,
villains: vec![
Villain { seat: 5, stack: 93.75, folded: false, profile: None },
Villain { seat: 0, stack: 83.75, folded: false, profile: None },
],
seed: 5,
history,
}
}
#[test]
fn acting_order_starts_at_the_small_blind() {
assert_eq!(acting_order(&three_way("Qc Jc")), Some(vec![5, 0, 4]));
}
#[test]
fn off_decides_nothing_and_heads_up_is_not_in_the_slice() {
let _g = LOCK.lock().unwrap();
set_river3(false);
assert!(river3_decision(&three_way("As Ad")).is_none());
set_river3(true);
let mut hu = three_way("As Ad");
hu.villains.pop();
assert!(river3_decision(&hu).is_none());
set_river3(false);
}
#[test]
fn on_decides_three_way_rivers_legally_and_in_time() {
let _g = LOCK.lock().unwrap();
set_river3(true);
for hero in ["As Ad", "6s 5d", "Kc Qc"] {
let spot = three_way(hero);
let t = std::time::Instant::now();
let d = river3_decision(&spot).expect("3-way river is in the slice");
assert!(t.elapsed().as_secs_f64() < 2.0);
assert!(d.reason.contains("river3 solver (3 players)"), "{}", d.reason);
assert!(matches!(d.choice, Choice::Fold | Choice::Call | Choice::Raise { .. }), "{:?}", d.choice);
}
set_river3(false);
}
#[test]
fn top_set_continues_and_air_folds_three_way() {
let s = solve_river3(&three_way("As Ad")).unwrap();
let fold = |s: &Solved3| s.row.iter().zip(&s.acts).filter(|(_, a)| **a == Act::Fold).map(|(p, _)| p).sum::<f64>();
assert!(fold(&s) < 0.05, "{:?} {:?}", s.row, s.acts);
let s = solve_river3(&three_way("6s 5d")).unwrap();
assert!(fold(&s) > 0.7, "{:?} {:?}", s.row, s.acts);
}
+398
View File
@@ -0,0 +1,398 @@
//! Stage A of "solver everywhere": the heads-up RIVER decided by an equilibrium solve over real combos,
//! as the primary decision maker (not a veto). Switch `SOLVER_RIVER` (default off).
//!
//! - **Game:** `cfr::turn_river_game::build_river` - the river alone, with the observed river line
//! inside the tree (exact sizes), position, three bet sizes plus all-in, raises. Solved with the
//! vectorised CFR+ of `TrSolver` over real combos: card removal and showdowns are exact per combo
//! (no strength buckets, blockers count).
//! - **Ranges** come from the hand's action history: where the blueprint recognises the spot (scenario
//! family of `blueprint::ranges`, loaded via `GRUNDSTRATEGIE`) both ranges are the blueprint's along
//! the line played; everywhere else both come from the engine's range model
//! (`exploit::range_model::range_spec` -> `range_filter`): the villain's with its (gated) read, hero's
//! own as the same model sees hero's line, without a read. `SOLVER_RIVER=modell` forces the range
//! model also in blueprint spots (a measurement arm: it shows the model path on the LBR scenario).
//! - **One solve per public state.** The ranges do not depend on hero's cards (the game deals card
//! removal itself), so a solve serves every hero hand at the node; solves are cached by public state.
//! Every hero hand outside the modelled range joins the solve at a token weight, so it gets a
//! strategy without moving the equilibrium.
//! - **Time budget:** CFR+ runs at most `ITERS` iterations and stops at `BUDGET_MS` wall time; under
//! `MIN_ITERS` finished iterations the heuristic keeps the decision (`None`).
//!
//! Not in the slice (the heuristic plays): multiway rivers, tournaments (the caller only asks for cash),
//! Omaha and other variants (hole cards != 2), spots whose line leaves the tree.
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;
use crate::rng::Rng;
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::sync::atomic::{AtomicU8, Ordering};
use std::sync::{Arc, Mutex};
/// Who plays the heads-up river.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RiverSpieler {
/// The heuristic (default).
Aus,
/// The solver; blueprint ranges where the spot is a blueprint scenario, else the range model.
An,
/// The solver with range-model ranges everywhere (measurement arm).
Modell,
}
static MODE: AtomicU8 = AtomicU8::new(0);
pub fn set_river_spieler(mode: RiverSpieler) {
MODE.store(
match mode {
RiverSpieler::Aus => 0,
RiverSpieler::An => 1,
RiverSpieler::Modell => 2,
},
Ordering::Relaxed,
);
}
pub fn river_spieler() -> RiverSpieler {
match MODE.load(Ordering::Relaxed) {
1 => RiverSpieler::An,
2 => RiverSpieler::Modell,
_ => RiverSpieler::Aus,
}
}
/// `SOLVER_RIVER`: `1`/`an` -> `An`, `modell` -> `Modell`, else `Aus`.
pub fn from_env() -> RiverSpieler {
match std::env::var("SOLVER_RIVER").as_deref() {
Ok("1") | Ok("an") => RiverSpieler::An,
Ok("modell") => RiverSpieler::Modell,
_ => RiverSpieler::Aus,
}
}
/// CFR+ iterations at most.
pub const ITERS: u32 = 600;
/// Fewer finished iterations than this (time budget hit): the heuristic decides.
pub const MIN_ITERS: u32 = 100;
/// Wall-time budget of one solve.
pub const BUDGET_MS: f64 = 1500.0;
/// The river bet menu: 33 %, 75 %, 125 % pot and all-in; raises to 3x or all-in, two raises.
fn river_menu() -> Menu {
Menu { fracs: vec![0.33, 0.75, 1.25], raise_mult: vec![3.0], max_raises: 2, allin: true }
}
/// One solved river node: what every hero hand at this public state shares.
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,
}
/// Masks and weights of a combo list off the `dead` cards. `fill`: every other two-card combo joins at a
/// token weight, so each possible hero hand has a strategy in the one solve (CFR's regrets of a hand do
/// not depend on its own reach, so a token-weight hand plays its counterfactual best line without moving
/// the equilibrium).
fn hands_of(list: &[(Vec<Card>, f64)], dead: u64, fill: bool) -> Hands {
let mut w: HashMap<u64, f64> = HashMap::new();
for (c, x) in list {
if c.len() == 2 && *x > 0.0 && x.is_finite() {
let m = fast7::mask(c);
if m & dead == 0 && m.count_ones() == 2 {
let e = w.entry(m).or_insert(0.0);
*e = e.max(*x);
}
}
}
let top = w.values().copied().fold(0.0f64, f64::max).max(1e-12);
if fill {
let bits: Vec<u64> = (0..4u32).flat_map(|s| (0..13u32).map(move |r| 1u64 << (16 * s + r))).filter(|b| b & dead == 0).collect();
for i in 0..bits.len() {
for j in i + 1..bits.len() {
w.entry(bits[i] | bits[j]).or_insert(top * TOKEN);
}
}
}
let mut v: Vec<(u64, f64)> = w.into_iter().collect();
v.sort_by(|a, b| a.0.cmp(&b.0));
Hands { masks: v.iter().map(|x| x.0).collect(), weights: v.iter().map(|x| x.1).collect() }
}
/// Relative weight of a hero hand outside the modelled range.
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<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 {
return None;
}
let villain = spot.live_villains().next()?;
let (first, forced, c) = river_line(spot, villain);
let pot = spot.pot - c[0] - c[1];
let stack = (spot.hero_stack + c[0]).min(villain.stack + c[1]);
if pot <= 0.0 || stack <= 0.0 {
return None;
}
let budget = crate::engine::frist::budget_ms(BUDGET_MS, crate::engine::frist::RIVER_MS);
if budget <= 0.0 {
return None;
}
let started = std::time::Instant::now();
let turn = fast7::mask(&spot.board[..4]);
let river = fast7::bit(spot.board[4]);
let dead = turn | river;
let hands = [hands_of(hero, dead, true), hands_of(villain_list, dead, false)];
if hands[0].masks.is_empty() || hands[1].masks.is_empty() {
return None;
}
let bets = TrBets { pot, stack, first, turn: river_menu(), river: river_menu() };
let game = build_river(&bets, &forced);
let at = game.at?;
if !matches!(game.nodes.get(at), Some(TNode::Dec { player: 0, street: 1, .. })) {
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 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();
done += 1;
if done % 10 == 0 && started.elapsed().as_secs_f64() * 1e3 > budget {
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 })
}
/// Hero's action for the real hand from a solved node: the equilibrium mix, realised from the spot seed.
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 choice = legal_choice(spot, act);
let p = row.get(pick).copied().unwrap_or(0.0);
Some(Decision::new(
choice,
p.clamp(0.0, 1.0),
format!(
"river solver ({}): {}x{} combos, {} nodes, {} iters, {act:?} p {p:.2}, {:.0} ms",
solved.source, solved.combos[0], solved.combos[1], solved.nodes, solved.iterations, solved.millis
),
))
}
/// Both ranges from the range model (the action history): hero's as the model reads hero's own line
/// (no read), the villain's with its gated read. Board cards only are dead (not hero's).
pub fn model_lists(spot: &Spot) -> Option<(Vec<(Vec<Card>, f64)>, Vec<(Vec<Card>, f64)>)> {
let villain = spot.live_villains().next()?;
let rules = spot.rules();
let list = |who: &Villain| {
let filter = crate::engine::range_filter::range_filter(&crate::exploit::range_model::range_spec(spot, who), rules, spot.variant, &spot.board);
crate::engine::range_combos::combos(&rules, &filter, &spot.board)
};
let me = Villain { seat: spot.hero_seat, stack: spot.hero_stack, folded: false, profile: None };
let eins = |l: Vec<Vec<Card>>| l.into_iter().map(|c| (c, 1.0)).collect::<Vec<_>>();
Some((eins(list(&me)?), eins(list(villain)?)))
}
/// 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<RangeRead> {
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<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))
}
/// Lock the villain's river decisions toward the read (restricted Nash response, `TrSolver::lock`):
/// the believed row per combo is `RangeRead::believed_row` (one source of truth with the read layer).
/// Facing an opening bet the weight is the fold read's trust, where it may bet the bluff read's trust;
/// facing a raise the node stays free (the read says nothing about raises). Nodes the read has no
/// opinion on stay pure CFR.
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 facing = acts.contains(&Act::Fold);
if facing && !matches!(incoming[node], Some(Act::Bet(_))) {
continue;
}
let rows: Option<Vec<f64>> = pct.iter().map(|p| read.believed_row(2, &acts, pot, *p)).collect::<Option<Vec<Vec<f64>>>>().map(|r| r.concat());
if let Some(rows) = rows {
solver.lock(node, rows, read.trust(!facing, 2));
}
}
}
static CACHE: Mutex<Option<HashMap<u64, Arc<Solved>>>> = Mutex::new(None);
const CACHE_MAX: usize = 4096;
/// Identity of the public state, the villain's read and the mode (not hero's cards).
fn public_key(spot: &Spot, mode: RiverSpieler) -> 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, MODE.load(Ordering::Relaxed), mode as u8, ITERS).hash(&mut h);
h.finish()
}
/// The live decision: the river solved to equilibrium for hero's real hand, or `None` (switch off, not
/// a heads-up Hold'em river, off the tree, budget) and the heuristic keeps the decision. `spot` carries
/// the ungated reads; the villain range uses the gated ones, as the heuristic's does.
pub fn river_spieler_decision(raw: &Spot) -> Option<Decision> {
let mode = river_spieler();
if mode == RiverSpieler::Aus || raw.street != Street::River || raw.hero_cards.len() != 2 || raw.board.len() != 5 {
return None;
}
let gated = crate::engine::read_gate::gate_reads(raw);
let spot = &gated;
if spot.live_villains().count() != 1 {
return None;
}
let hero_mask = fast7::mask(&spot.hero_cards);
if hero_mask & fast7::mask(&spot.board) != 0 {
return None;
}
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) = 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 {
map.clear();
}
map.insert(key, solved.clone());
}
solved
}
};
decide_from(spot, &solved, hero_mask)
}
#[cfg(test)]
mod tests;
+191
View File
@@ -0,0 +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<f64>) -> 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<f64>, Vec<Act>) {
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<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}");
}
+112 -4
View File
@@ -68,10 +68,22 @@ 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 own cap on one solve; the decision total is `frist::TURN_MS`.
pub const STAGE_B_BUDGET_MS: f64 = 1700.0;
/// Stage B's game size: 120 combos per player, 8 river cards (measured: same exploitability inside the
/// game as 160 × 10 at 200 iterations, 1.34 % of the pot, in 62 % of the time).
pub const STAGE_B_COMBOS: usize = 120;
pub const STAGE_B_RIVER_CARDS: usize = 8;
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 +95,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,
}
}
}
@@ -121,11 +134,16 @@ pub struct TurnSolved {
/// The turn line so far for hero and `villain`: who acted first (0 = hero), the forced actions and the
/// street contributions. Falls back to "villain bet `to_call`" / "hero first" without a history.
pub(crate) fn turn_line(spot: &Spot, villain: &Villain) -> (usize, Vec<Act>, [f64; 2]) {
street_line(spot, villain, Street::Turn)
}
/// The line of `street` so far (as `turn_line`).
pub(crate) fn street_line(spot: &Spot, villain: &Villain, street: Street) -> (usize, Vec<Act>, [f64; 2]) {
let mut first = None;
let mut acts = Vec::new();
let mut c = [0.0f64, 0.0];
let mut aggressed = false;
for r in spot.history.iter().filter(|r| r.street == Street::Turn) {
for r in spot.history.iter().filter(|r| r.street == street) {
let who = if r.seat == spot.hero_seat {
0
} else if r.seat == villain.seat {
@@ -158,7 +176,7 @@ pub(crate) fn turn_line(spot: &Spot, villain: &Villain) -> (usize, Vec<Act>, [f6
}
/// Masks and weights of a combo list: off the board, the `max` heaviest, `keep` (hero's hand) always in.
fn prune(list: &[(Vec<Card>, f64)], board: u64, cfg: &TurnConfig, keep: Option<u64>) -> Hands {
pub(crate) fn prune(list: &[(Vec<Card>, f64)], board: u64, cfg: &TurnConfig, keep: Option<u64>) -> Hands {
let mut v: Vec<(u64, f64)> = list
.iter()
.filter(|(c, w)| c.len() == 2 && *w > 0.0 && w.is_finite())
@@ -221,7 +239,21 @@ fn solve_core(spot: &Spot, hero: &[(Vec<Card>, f64)], villain_list: &[(Vec<Card>
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 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<f64> = (0..combos[0]).flat_map(|i| strategy.row(at, 0, i).to_vec()).collect();
@@ -318,5 +350,81 @@ pub fn turn_game_decision(spot: &Spot) -> Option<Decision> {
decide_from(spot, solved, hero_mask).map(|d| d.decision)
}
// --- Stage B of "solver everywhere" (switch SOLVER_TURN, default off) ---
static UEBERALL: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
/// Stage B: the turn game decides every heads-up Hold'em turn, not only blueprint scenarios. Ranges
/// from the blueprint where it recognises the spot, else from the range model of the action history
/// (`river_spieler::model_lists`: hero's line without a read, the villain's with its gated read).
pub fn set_turn_ueberall(on: bool) {
UEBERALL.store(on, std::sync::atomic::Ordering::Relaxed);
}
pub fn turn_ueberall() -> bool {
UEBERALL.load(std::sync::atomic::Ordering::Relaxed)
}
/// `SOLVER_TURN=1`.
pub fn turn_ueberall_from_env() -> bool {
matches!(std::env::var("SOLVER_TURN").as_deref(), Ok("1") | Ok("an"))
}
/// The stage-B decision for `raw` (ungated reads; the villain range uses the gated ones), or `None`
/// (switch off, not a heads-up Hold'em turn, off the tree) and the heuristic keeps the decision. A hero
/// hand outside the pruned range gets an uncached solve with the hand in it (live asks once per
/// decision, so this is the normal live cost).
pub fn turn_solver_decision(raw: &Spot) -> Option<Decision> {
if !turn_ueberall() || raw.street != Street::Turn || raw.hero_cards.len() != 2 || raw.board.len() != 4 {
return None;
}
let gated = crate::engine::read_gate::gate_reads(raw);
let spot = &gated;
if spot.live_villains().count() != 1 {
return None;
}
let cfg = TurnConfig { max_combos: STAGE_B_COMBOS, river_cards: STAGE_B_RIVER_CARDS, 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 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 tag = |mut d: Decision, src: &str| {
d.reason = format!("solver turn ({src}) {}", d.reason);
d
};
let cached = CACHE.lock().ok().and_then(|m| m.as_ref().and_then(|m| m.get(&key).cloned()));
if let Some(t) = cached.and_then(|s| decide_from(spot, s, hero_mask)) {
return Some(tag(t.decision, "cache"));
}
// One solve per decision, inside what is left of the turn'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, src) = lists()?;
let budget = crate::engine::frist::budget_ms(cfg.budget_ms, crate::engine::frist::TURN_MS);
if budget <= 0.0 {
return None;
}
let cfg = TurnConfig { budget_ms: budget, ..cfg };
if prune(&hero, fast7::mask(&spot.board), &cfg, None).masks.contains(&hero_mask) {
let solved = Arc::new(solve_core(spot, &hero, &villain, &cfg, None)?);
if let Ok(mut m) = CACHE.lock() {
let map = m.get_or_insert_with(HashMap::new);
if map.len() >= CACHE_MAX {
map.clear();
}
map.insert(key, solved.clone());
}
return decide_from(spot, solved, hero_mask).map(|t| tag(t.decision, src));
}
solve_turn(spot, &hero, &villain, &cfg).map(|t| tag(t.decision, src))
}
#[cfg(test)]
mod tests;
+265 -242
View File
@@ -1,242 +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<f64>) -> 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<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 board = Card::parse_list("Ah 7d 2c Ks").unwrap();
let cards: Vec<Card> = 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<Card>, 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<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());
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()
);
}
}
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<f64>) -> 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<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 board = Card::parse_list("Ah 7d 2c Ks").unwrap();
let cards: Vec<Card> = 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<Card>, 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<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());
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);
}