E3: Turn+River nachrechnen am Tisch mit Ranges aus der Grundstrategie (Weiche TURN_SPIEL=grund, Standard aus)

Aus worktree-agent-a0615d59d349d0c73 (2bd387d), auf die Szenariofamilie uebertragen (ranges_mit, gewichtete_listen_offen ueber erkennen). Tests turn/blueprint/river/decide: 84 ok.
Befund: die HU-Leiter (ab_zelle, 2 Sitze) erreicht nie Grundstrategie-Ranges; river-grund/turn-grund dort messen nichts. Messung ueber engine_lbr (6 Sitze).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-14 02:32:16 +01:00
co-authored by Claude Opus 5.5
parent 20da294c5a
commit 207a9ad1f1
13 changed files with 2160 additions and 504 deletions
+11
View File
@@ -222,3 +222,14 @@ das E1-Tor erneut.
| M4 Engine-LBR | LBR gegen die Live-Engine gebaut, exakt ~25 s/Hand, fortsetzbar (`pokerbench-engine-lbr`, 20 000 Hände in der Warteschlange) | 9f59e1a, e00dc74 |
| M4 Stichprobe | Range-Stichprobe statt aller Combos, gepaart gegen exakt auf der echten Grundstrategie (4000 Hände): k=24 −155, k=48 −112, k=96 −35, k=192 −14 ±46 bb/100. **Verworfen**: spart nur mit großer Verzerrung nach unten | e00dc74 |
| Übung, Fehlerscan | 1741 Züge: 0 Folds bei freiem Check, 0 verpasste Monster-Werte; Luft-Bluffs 1 von 314; offen: MDF-Boden-Calls am River (15, bis ~100 bb), Prüfung wartet auf Hand-ID im Zug-Log | af3013a |
## 8. Nachtrag 14.11.: E3 Turn+River nachrechnen (gebaut, ungemessen)
| Baustein | Stand |
|---|---|
| `cfr::turn_river_game` | Turn+River als ein Spiel ueber echte Combos: Turn-Setzen (50 %, 100 %, All-in, ein Raise, beobachtete Groesse exakt im Baum), Zufallsknoten ueber die River-Karten, River-Setzen; CFR+ voll in der Breite, Showdown in O(Haende) je Karte; exakter Best Response je Spieler (Ausnutzbarkeit) |
| `engine::turn_game` | Weiche `TurnPlayer::Grund` (Standard Aus; `ab_zelle`/`engine_lbr`: `TURN_SPIEL=grund`, braucht `GRUNDSTRATEGIE`). Ranges aus `ranges` am Turn-Knoten, Villain-Range ohne Blocker der echten Hand, damit ein Solve fuer alle Haende am Knoten reicht (Cache nach oeffentlichem Zustand). Haende ausserhalb der beschnittenen Range spielt die Heuristik |
| Abnahme | Tests: Vektorwerte = skalare Aufzaehlung, Nullsumme, Best Response = Brute Force ueber alle reinen Strategien, Turn durchgecheckt = `river_game` (Wert und Ausnutzbarkeit), nur legale Choices, Aus = unveraendert |
| Naeherungen | Range auf 95 % Masse / 160 Combos, 10 von 48 River-Karten (gleichmaessig gestreift, je 1/K), kein River-Raise (Schalter `TURN_RIVER_RAISES=1`), feste 200 Iterationen; ~1,3 s je Entscheidung auf einem Faden |
| Offen | Messung (LBR gegen die Live-Engine mit `TURN_SPIEL=grund`; die HU-Leiter `ab_zelle` sieht wegen `seats = 2` nie Blueprint-Ranges, die Arme `river-grund`/`turn-grund` dort sind Identitaet) |
+9 -2
View File
@@ -6,6 +6,7 @@
//!
//! The arm is chosen by environment so independent processes stay paired:
//! - `TURN_VETO`, `TURN_BUCKET`, `TURN_PER_STREET`: read by the turn track itself,
//! - `TURN_SPIEL=grund` (with `GRUNDSTRATEGIE`): the turn+river game with blueprint ranges (plan E3),
//! - every other track adds its switch in `apply_arm` below (identity on the engine branch).
//!
//! Run: `ab_zelle <out-dir> [welt-deals=2000] [klassik-deals=4000] [draws=4] [rows=all|welt|klassik|a,b,..]`
@@ -62,10 +63,16 @@ fn apply_arm() {
Ok("grund") => RiverPlayer::Grund,
_ => RiverPlayer::Off,
});
// TURN_SPIEL=grund: the turn+river game with both ranges from the blueprint (plan E3,
// `engine::turn_game`), only where the blueprint recognises the spot. Needs GRUNDSTRATEGIE like
// RIVER_DBR=grund. Size/budget: TURN_COMBOS, TURN_CARDS, TURN_ITERS (defaults in `TurnConfig`).
use rechner::engine::turn_game::{set_turn_player, TurnPlayer};
let turn_grund = std::env::var("TURN_SPIEL").as_deref() == Ok("grund");
set_turn_player(if turn_grund { TurnPlayer::Grund } else { TurnPlayer::Off });
// The blueprint arm waits until the blueprint run has finished (its FERTIG marker), so a
// queued arm never reads a half-trained checkpoint; then loads it once.
if std::env::var("RIVER_DBR").as_deref() == Ok("grund") {
let dir = std::path::PathBuf::from(std::env::var_os("GRUNDSTRATEGIE").expect("RIVER_DBR=grund needs GRUNDSTRATEGIE"));
if turn_grund || std::env::var("RIVER_DBR").as_deref() == Ok("grund") {
let dir = std::path::PathBuf::from(std::env::var_os("GRUNDSTRATEGIE").expect("RIVER_DBR=grund / TURN_SPIEL=grund needs GRUNDSTRATEGIE"));
while !dir.join("grundstrategie").join("FERTIG").exists() {
std::thread::sleep(std::time::Duration::from_secs(60));
}
+7 -1
View File
@@ -7,7 +7,7 @@
//! file as `i value_bb` at once, and a restart computes only the missing hands.
//!
//! Run: `engine_lbr <out-file> <hands> [seed]`, threads from `POKERBENCH_THREADS` (default 1).
//! The engine runs with its default switches (no env arms).
//! The engine runs with its default switches; the one env arm is `TURN_SPIEL=grund` (turn game, E3).
use rechner::blueprint::abstraktion::river_cuts;
use rechner::blueprint::engine_gegner::EngineGegner;
@@ -27,6 +27,12 @@ fn main() {
let haende: u64 = args[2].parse().expect("hands");
let seed: u64 = args.get(3).map(|x| x.parse().expect("seed")).unwrap_or(7);
let threads: usize = std::env::var("POKERBENCH_THREADS").ok().and_then(|x| x.parse().ok()).unwrap_or(1).max(1);
// TURN_SPIEL=grund (plan E3): the turn+river game with blueprint ranges plays the engine's turn
// where the blueprint recognises the spot (needs GRUNDSTRATEGIE: tables and checkpoint).
if std::env::var("TURN_SPIEL").as_deref() == Ok("grund") {
rechner::engine::turn_game::set_turn_player(rechner::engine::turn_game::TurnPlayer::Grund);
assert!(rechner::blueprint::ranges::grundstrategie().is_some(), "TURN_SPIEL=grund needs GRUNDSTRATEGIE with tables and checkpoint");
}
let mut fertig = vec![None; haende as usize];
if let Ok(t) = std::fs::read_to_string(&out) {
+514 -498
View File
File diff suppressed because it is too large Load Diff
+1
View File
@@ -111,6 +111,7 @@ pub mod tree3;
pub mod tree;
pub mod turn;
pub mod turn_river;
pub mod turn_river_game;
pub mod value_walk;
pub mod wake_range;
pub mod walk3;
+2 -2
View File
@@ -88,7 +88,7 @@ fn showdown(n: usize, q: f64) -> Payoff {
}
/// Add `x` to `sizes` (sorted), dropping abstract sizes within `SAME_SIZE` of it.
fn with_exact(mut sizes: Vec<f64>, x: f64) -> Vec<f64> {
pub(crate) fn with_exact(mut sizes: Vec<f64>, x: f64) -> Vec<f64> {
sizes.retain(|s| (s - x).abs() > SAME_SIZE * s.max(x));
sizes.push(x);
sizes.sort_by(f64::total_cmp);
@@ -96,7 +96,7 @@ fn with_exact(mut sizes: Vec<f64>, x: f64) -> Vec<f64> {
}
/// Distinct sizes in `(lo, cap]`, all-in (`cap`) always last; near-duplicates of all-in dropped.
fn sized(raw: impl Iterator<Item = f64>, lo: f64, cap: f64) -> Vec<f64> {
pub(crate) fn sized(raw: impl Iterator<Item = f64>, lo: f64, cap: f64) -> Vec<f64> {
let mut out: Vec<f64> = raw.filter(|s| s.is_finite() && *s > lo && *s < cap * (1.0 - SAME_SIZE)).collect();
out.sort_by(f64::total_cmp);
out.dedup_by(|a, b| (*a - *b).abs() <= SAME_SIZE * a.max(*b));
+664
View File
@@ -0,0 +1,664 @@
//! The heads-up TURN + RIVER as one game over real hands (plan E3, layer 2 of the target engine).
//!
//! `cfr::turn_river` (stage B) solves one turn betting round and values the river with an
//! equilibrium *number*, over strength buckets. This module keeps the river inside the game:
//!
//! - **Hands** are real combos with a weight each (both ranges come from the blueprint, see
//! `blueprint::ranges`). The information set of a player is (combo, public line) on the turn and
//! (combo, river card, public line) on the river, so hands change strength with the river card
//! exactly. Card removal is exact: a pair of overlapping combos is never dealt, and a river card
//! a combo holds is not dealt to it.
//! - **Tree:** turn betting (menu `TrBets::turn`), then a chance node over the river cards, then
//! river betting (menu `TrBets::river`). The player `first` acts first on both streets. The
//! observed turn actions (`forced`) are inside the tree with their exact sizes, so hero's real
//! decision is a node (`TrGame::at`).
//! - **Payoffs** are hero's (player 0) net chips from the start of the turn, each player counted
//! as having put `pot / 2` in, as in `river_game`. Zero-sum.
//! - **Solver:** CFR+ (regrets floored at zero, alternating updates, linearly weighted average),
//! full width over the hands, vectorised like `cfr::iterate`. A showdown is evaluated in
//! `O(hands)` per river card with prefix sums and card-removal inclusion-exclusion, not `O(hands^2)`.
//! - **Exploitability:** `TrSolver::exploitability` is the exact best response of each player in
//! this game against the average strategy (sum of both gains, chips per deal).
//!
//! # Named approximations
//!
//! `TrSolver::new` can be given a subset of the river cards (`river_cards`): then each sampled card
//! stands for `1/K` of all cards (the deal weight is rescaled by `48 / (44 K)`, exact for all 48).
//! The caller can also prune the ranges. Both are chosen by the bridge in `engine::turn_game`.
use super::river_game::{sized, with_exact, Act};
use crate::hand::fast7;
/// Bet menu of one street.
#[derive(Clone, Debug, PartialEq)]
pub struct Menu {
/// Opening bets as fractions of the pot (all-in is always added).
pub fracs: Vec<f64>,
/// Raises to `mult` x the bet faced (all-in is always added).
pub raise_mult: Vec<f64>,
/// Raises allowed after the opening bet.
pub max_raises: usize,
/// Whether the all-in is a bet / raise size of its own (an observed all-in is always in the tree).
pub allin: bool,
}
/// The betting abstraction of the two streets.
#[derive(Clone, Debug, PartialEq)]
pub struct TrBets {
/// Pot at the start of the turn.
pub pot: f64,
/// Effective stack at the start of the turn.
pub stack: f64,
/// Who acts first on both streets: 0 = hero, 1 = villain.
pub first: usize,
pub turn: Menu,
pub river: Menu,
}
impl TrBets {
/// Turn: 50 %, 100 % pot, all-in, one raise (3x); river: 70 % pot, all-in, one raise (3x).
pub fn standard(pot: f64, stack: f64, first: usize) -> TrBets {
TrBets {
pot,
stack,
first,
turn: Menu { fracs: vec![0.5, 1.0], raise_mult: vec![3.0], max_raises: 1, allin: true },
river: Menu { fracs: vec![0.7], raise_mult: vec![3.0], max_raises: 1, allin: true },
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum TNode {
/// `street`: 0 = turn, 1 = river.
Dec { player: usize, street: u8, kids: Vec<usize> },
/// `folder` loses `amt` (its contribution counting `pot / 2` of the start pot), the other wins it.
Fold { folder: usize, amt: f64 },
/// Showdown on the river card: the better hand wins `half`, the worse loses it.
Show { half: f64 },
/// The river card is dealt; `child` is the river betting (or a showdown).
Chance { child: usize },
}
/// A built turn+river game.
pub struct TrGame {
pub nodes: Vec<TNode>,
/// `acts[node][k]` = the action of child `k` of decision `node`.
pub acts: Vec<Vec<Act>>,
pub root: usize,
/// The node reached by the forced (observed) turn line.
pub at: Option<usize>,
}
struct Builder<'a> {
b: &'a TrBets,
forced: &'a [Act],
nodes: Vec<TNode>,
acts: Vec<Vec<Act>>,
at: Option<usize>,
}
impl Builder<'_> {
fn push(&mut self, node: TNode, acts: Vec<Act>) -> usize {
self.nodes.push(node);
self.acts.push(acts);
self.nodes.len() - 1
}
/// After the turn closes with both players matched at `total` each: the river card, then the
/// river betting; an all-in goes straight to the showdown.
fn to_river(&mut self, total: f64) -> usize {
let b = self.b;
let child = if total >= b.stack - 1e-9 {
self.push(TNode::Show { half: b.pot / 2.0 + total }, Vec::new())
} else {
self.street(1, b.first, total, [0.0, 0.0], false, 0, None)
};
self.push(TNode::Chance { child }, Vec::new())
}
/// `base`: chips each player put in on earlier streets; `c`: street contributions.
#[allow(clippy::too_many_arguments)]
fn street(&mut self, street: u8, to_act: usize, base: f64, c: [f64; 2], checked: bool, raises: usize, depth: Option<usize>) -> usize {
let b = self.b;
let menu = if street == 0 { &b.turn } else { &b.river };
let other = 1 - to_act;
let facing = c[other] > c[to_act];
let cap = b.stack - base;
let pot_now = b.pot + 2.0 * base + c[0] + c[1];
let forced = if street == 0 { depth.and_then(|d| self.forced.get(d).copied()) } else { None };
let mut acts: Vec<Act> = if facing {
let mut a = vec![Act::Fold, Act::Call];
if raises < menu.max_raises && c[other] < cap {
let mut sizes = sized(menu.raise_mult.iter().map(|m| m * c[other]), c[other], cap);
if !menu.allin {
sizes.retain(|s| *s < cap - 1e-9);
}
if let Some(Act::Raise(x)) = forced {
sizes = with_exact(sizes, x.min(cap));
}
a.extend(sizes.into_iter().map(Act::Raise));
} else if let Some(Act::Raise(x)) = forced {
a.push(Act::Raise(x.min(cap)));
}
a
} else {
let mut sizes = sized(menu.fracs.iter().map(|f| f * pot_now), 0.0, cap);
if !menu.allin {
sizes.retain(|s| *s < cap - 1e-9);
}
if let Some(Act::Bet(x)) = forced {
sizes = with_exact(sizes, x.min(cap));
}
std::iter::once(Act::Check).chain(sizes.into_iter().map(Act::Bet)).collect()
};
acts.dedup();
let follow = forced.and_then(|f| {
acts.iter().position(|a| match (a, f) {
(Act::Bet(x), Act::Bet(y)) | (Act::Raise(x), Act::Raise(y)) => (x - y.min(cap)).abs() < 1e-9,
_ => *a == f,
})
});
if street == 0 && depth == Some(self.forced.len()) {
self.at = Some(self.nodes.len());
}
let me = self.push(TNode::Dec { player: to_act, street, kids: Vec::new() }, acts.clone());
let mut kids = Vec::with_capacity(acts.len());
for (k, a) in acts.iter().enumerate() {
let next_depth = match (depth, follow) {
(Some(d), Some(f)) if f == k => Some(d + 1),
_ => None,
};
let kid = match *a {
Act::Fold => self.push(TNode::Fold { folder: to_act, amt: b.pot / 2.0 + base + c[to_act] }, Vec::new()),
Act::Check if checked || to_act != b.first => {
if street == 0 {
self.to_river(base)
} else {
self.push(TNode::Show { half: b.pot / 2.0 + base }, Vec::new())
}
}
Act::Check => self.street(street, other, base, c, true, raises, next_depth),
Act::Call => {
let total = base + c[other];
if street == 0 {
self.to_river(total)
} else {
self.push(TNode::Show { half: b.pot / 2.0 + total }, Vec::new())
}
}
Act::Bet(to) | Act::Raise(to) => {
let mut nc = c;
nc[to_act] = to;
let r = if matches!(a, Act::Raise(_)) { raises + 1 } else { raises };
self.street(street, other, base, nc, false, r, next_depth)
}
};
kids.push(kid);
}
if let TNode::Dec { kids: k, .. } = &mut self.nodes[me] {
*k = kids;
}
me
}
}
/// Build the game for the observed turn line `forced` (from the start of the turn).
pub fn build(bets: &TrBets, forced: &[Act]) -> TrGame {
let mut b = Builder { b: bets, forced, nodes: Vec::new(), acts: Vec::new(), at: None };
let root = b.street(0, bets.first.min(1), 0.0, [0.0, 0.0], false, 0, Some(0));
TrGame { nodes: b.nodes, acts: b.acts, root, at: b.at }
}
const NO_CARD: usize = usize::MAX;
/// Hands of one player: card masks (`fast7` layout) and range weights.
#[derive(Clone, Debug)]
pub struct Hands {
pub masks: Vec<u64>,
pub weights: Vec<f64>,
}
struct RiverCard {
bit: u64,
/// 1.0 if the combo does not hold the card, else 0.0.
free: [Vec<f64>; 2],
/// `fast7` score of each combo with board and this card.
rank: [Vec<u32>; 2],
/// Combo indices by ascending score.
order: [Vec<u32>; 2],
}
fn pos(mask: u64) -> (usize, usize) {
(mask.trailing_zeros() as usize, (mask & (mask - 1)).trailing_zeros() as usize)
}
/// The solver state; see the module doc.
pub struct TrSolver {
pub game: std::sync::Arc<TrGame>,
n: [usize; 2],
cards: [Vec<(usize, usize)>; 2],
#[allow(dead_code)]
masks: [Vec<u64>; 2],
same: [Vec<Option<usize>>; 2],
weights: [Vec<f64>; 2],
rc: Vec<RiverCard>,
/// Deal weight of one sampled river card.
wr: f64,
regret: Vec<Vec<f64>>,
sums: Vec<Vec<f64>>,
pub iterations: u32,
}
/// The average strategy: per decision node, per copy (1 on the turn, one per river card on the
/// river), per hand, the action probabilities.
#[derive(Clone, Debug)]
pub struct TrStrategy {
probs: Vec<Vec<f64>>,
actions: Vec<usize>,
n: [usize; 2],
players: Vec<usize>,
}
impl TrStrategy {
/// Action probabilities of `hand` at `node` (`card` = river card index; ignored on the turn).
pub fn row(&self, node: usize, card: usize, hand: usize) -> &[f64] {
let a = self.actions[node];
let n = self.n[self.players[node]];
let copies = self.probs[node].len() / (n * a).max(1);
let c = if copies == 1 { 0 } else { card };
let off = (c * n + hand) * a;
&self.probs[node][off..off + a]
}
}
/// Best-response result: gain of each player and their sum, in chips per deal.
#[derive(Clone, Copy, Debug)]
pub struct Exploit {
pub gain: [f64; 2],
pub total: f64,
}
fn matched(regret: &[f64], a: usize, out: &mut [f64]) {
for (r, o) in regret.chunks(a).zip(out.chunks_mut(a)) {
let s: f64 = r.iter().sum();
if s > 0.0 {
for (x, y) in r.iter().zip(o.iter_mut()) {
*y = x / s;
}
} else {
o.iter_mut().for_each(|y| *y = 1.0 / a as f64);
}
}
}
impl TrSolver {
/// `board`: the four turn cards as a mask; `river`: the river cards to enumerate (`None` = all 48 not
/// on the board, `Some(k)` = `k` of them, evenly strided). Combos must not touch the board.
pub fn new(game: TrGame, hands: [Hands; 2], board: u64, river: Option<usize>) -> TrSolver {
let mut all: Vec<u64> = (0..4u32)
.flat_map(|s| (0..13u32).map(move |r| 1u64 << (16 * s + r)))
.filter(|b| b & board == 0)
.collect();
let candidates = all.len();
if let Some(k) = river {
let k = k.clamp(1, candidates);
all = (0..k).map(|i| all[(((i as f64 + 0.5) * candidates as f64 / k as f64) as usize).min(candidates - 1)]).collect();
}
// Every valid (pair, card) triple has weight 1/44 when all 48 are enumerated.
let wr = candidates as f64 / (all.len() as f64 * (candidates as f64 - 4.0));
TrSolver::with_cards(game, hands, board, all, wr)
}
/// As `new`, with explicit river cards (single-bit masks) and the deal weight of each.
pub fn with_cards(game: TrGame, hands: [Hands; 2], board: u64, all: Vec<u64>, wr: f64) -> TrSolver {
let n = [hands[0].masks.len(), hands[1].masks.len()];
let cards = [hands[0].masks.iter().map(|m| pos(*m)).collect::<Vec<_>>(), hands[1].masks.iter().map(|m| pos(*m)).collect::<Vec<_>>()];
let same = [0, 1].map(|p| {
hands[p].masks.iter().map(|m| hands[1 - p].masks.iter().position(|o| o == m)).collect::<Vec<_>>()
});
let total = |p: usize| hands[p].weights.iter().sum::<f64>().max(1e-300);
let weights = [0, 1].map(|p| hands[p].weights.iter().map(|w| w / total(p)).collect::<Vec<f64>>());
let k = all.len();
let rc: Vec<RiverCard> = all
.iter()
.map(|bit| {
let free = [0, 1].map(|p| hands[p].masks.iter().map(|m| if m & bit == 0 { 1.0 } else { 0.0 }).collect::<Vec<f64>>());
let rank = [0, 1].map(|p| hands[p].masks.iter().map(|m| fast7::score(m | board | bit)).collect::<Vec<u32>>());
let order = [0, 1].map(|p| {
let mut o: Vec<u32> = (0..n[p] as u32).collect();
o.sort_by_key(|i| rank[p][*i as usize]);
o
});
RiverCard { bit: *bit, free, rank, order }
})
.collect();
let mut regret = Vec::with_capacity(game.nodes.len());
for node in &game.nodes {
regret.push(match node {
TNode::Dec { player, street, kids } => {
let copies = if *street == 0 { 1 } else { k };
vec![0.0; copies * n[*player] * kids.len()]
}
_ => Vec::new(),
});
}
let sums = regret.clone();
let masks = [hands[0].masks.clone(), hands[1].masks.clone()];
TrSolver { game: std::sync::Arc::new(game), n, cards, masks, same, weights, rc, wr, regret, sums, iterations: 0 }
}
pub fn hands(&self, player: usize) -> usize {
self.n[player]
}
pub fn river_cards(&self) -> usize {
self.rc.len()
}
/// One CFR+ iteration (both players, alternating).
pub fn iterate(&mut self) {
self.iterations += 1;
for p in 0..2 {
let own = vec![1.0; self.n[p]];
let opp = self.weights[1 - p].clone();
let weight = self.iterations as f64;
self.walk(self.game.root, p, &own, &opp, NO_CARD, weight);
}
}
pub fn run(&mut self, iterations: u32) {
for _ in 0..iterations {
self.iterate();
}
}
/// `out[i]` = sum of `opp[j]` over the opponent combos `j` that share no card with own combo `i`.
fn disjoint(&self, p: usize, opp: &[f64]) -> Vec<f64> {
let mut c = [0.0f64; 64];
let mut t = 0.0;
for (j, w) in opp.iter().enumerate() {
let (a, b) = self.cards[1 - p][j];
c[a] += w;
c[b] += w;
t += w;
}
(0..self.n[p])
.map(|i| {
let (a, b) = self.cards[p][i];
t - c[a] - c[b] + self.same[p][i].map_or(0.0, |j| opp[j])
})
.collect()
}
/// Showdown values of player `p`'s combos on river card `r`: `half` x (win mass - lose mass).
fn show(&self, p: usize, r: usize, opp: &[f64], half: f64) -> Vec<f64> {
let rc = &self.rc[r];
let (n_own, n_opp) = (self.n[p], self.n[1 - p]);
let (own_o, own_r) = (&rc.order[p], &rc.rank[p]);
let (opp_o, opp_r) = (&rc.order[1 - p], &rc.rank[1 - p]);
let mut c = [0.0f64; 64];
let mut t = 0.0;
for (j, w) in opp.iter().enumerate() {
let (a, b) = self.cards[1 - p][j];
c[a] += w;
c[b] += w;
t += w;
}
let (mut less_t, mut less_c) = (0.0f64, [0.0f64; 64]);
let mut eq_c = [0.0f64; 64];
let mut ptr = 0;
let mut out = vec![0.0; n_own];
let mut k = 0;
while k < n_own {
let s = own_r[own_o[k] as usize];
let mut e = k;
while e < n_own && own_r[own_o[e] as usize] == s {
e += 1;
}
while ptr < n_opp && opp_r[opp_o[ptr] as usize] < s {
let j = opp_o[ptr] as usize;
let (a, b) = self.cards[1 - p][j];
less_t += opp[j];
less_c[a] += opp[j];
less_c[b] += opp[j];
ptr += 1;
}
let (mut eq_t, mut q) = (0.0f64, ptr);
while q < n_opp && opp_r[opp_o[q] as usize] == s {
let j = opp_o[q] as usize;
let (a, b) = self.cards[1 - p][j];
eq_t += opp[j];
eq_c[a] += opp[j];
eq_c[b] += opp[j];
q += 1;
}
for idx in k..e {
let i = own_o[idx] as usize;
let (a, b) = self.cards[p][i];
let sm = self.same[p][i].map_or(0.0, |j| opp[j]);
let disj = t - c[a] - c[b] + sm;
let less = less_t - less_c[a] - less_c[b];
let eq = eq_t - eq_c[a] - eq_c[b] + sm;
out[i] = half * (2.0 * less + eq - disj);
}
for &j in &opp_o[ptr..q] {
let (a, b) = self.cards[1 - p][j as usize];
eq_c[a] = 0.0;
eq_c[b] = 0.0;
}
k = e;
}
out
}
fn mask_by_card(&self, v: &[f64], p: usize, r: usize) -> Vec<f64> {
v.iter().zip(&self.rc[r].free[p]).map(|(x, f)| x * f).collect()
}
/// Counterfactual values of the traversing player `p`, one per own combo.
fn walk(&mut self, node: usize, p: usize, own: &[f64], opp: &[f64], r: usize, weight: f64) -> Vec<f64> {
let game = std::sync::Arc::clone(&self.game);
match game.nodes[node] {
TNode::Fold { folder, amt } => {
let v = if folder == p { -amt } else { amt };
self.disjoint(p, opp).into_iter().map(|x| x * v).collect()
}
TNode::Show { half } => self.show(p, r, opp, half),
TNode::Chance { child } => {
let mut total = vec![0.0; self.n[p]];
for ri in 0..self.rc.len() {
let o = self.mask_by_card(own, p, ri);
let q = self.mask_by_card(opp, 1 - p, ri);
let v = self.walk(child, p, &o, &q, ri, weight);
let free = &self.rc[ri].free[p];
for i in 0..total.len() {
total[i] += self.wr * v[i] * free[i];
}
}
total
}
TNode::Dec { player, street, ref kids } => {
let a = kids.len();
let n = self.n[player];
let off = if street == 0 { 0 } else { r * n * a };
let mut sigma = vec![0.0; n * a];
matched(&self.regret[node][off..off + n * a], a, &mut sigma);
if player == p {
let values: Vec<Vec<f64>> = kids
.iter()
.enumerate()
.map(|(k, kid)| {
let reach: Vec<f64> = (0..n).map(|i| own[i] * sigma[i * a + k]).collect();
self.walk(*kid, p, &reach, opp, r, weight)
})
.collect();
let mut node_value = vec![0.0; n];
for i in 0..n {
node_value[i] = (0..a).map(|k| sigma[i * a + k] * values[k][i]).sum();
for k in 0..a {
let reg = &mut self.regret[node][off + i * a + k];
*reg = (*reg + values[k][i] - node_value[i]).max(0.0);
self.sums[node][off + i * a + k] += weight * own[i] * sigma[i * a + k];
}
}
node_value
} else {
let mut total = vec![0.0; self.n[p]];
for (k, kid) in kids.iter().enumerate() {
let reach: Vec<f64> = (0..n).map(|j| opp[j] * sigma[j * a + k]).collect();
let v = self.walk(*kid, p, own, &reach, r, weight);
total.iter_mut().zip(&v).for_each(|(t, x)| *t += x);
}
total
}
}
}
}
/// The average strategy so far (uniform where a hand was never reached).
pub fn strategy(&self) -> TrStrategy {
let mut actions = Vec::new();
let mut players = Vec::new();
let probs = self
.game
.nodes
.iter()
.enumerate()
.map(|(i, node)| match node {
TNode::Dec { player, kids, .. } => {
let a = kids.len();
actions.push(a);
players.push(*player);
let mut out = vec![0.0; self.sums[i].len()];
for (s, o) in self.sums[i].chunks(a).zip(out.chunks_mut(a)) {
let t: f64 = s.iter().sum();
for (x, y) in s.iter().zip(o.iter_mut()) {
*y = if t > 0.0 { x / t } else { 1.0 / a as f64 };
}
}
out
}
_ => {
actions.push(0);
players.push(0);
Vec::new()
}
})
.collect();
TrStrategy { probs, actions, n: self.n, players }
}
/// Best-response values of player `p` (per own combo) against `strategy`.
fn br(&self, strategy: &TrStrategy, node: usize, p: usize, opp: &[f64], r: usize) -> Vec<f64> {
match &self.game.nodes[node] {
TNode::Fold { folder, amt } => {
let v = if *folder == p { -amt } else { *amt };
self.disjoint(p, opp).into_iter().map(|x| x * v).collect()
}
TNode::Show { half } => self.show(p, r, opp, *half),
TNode::Chance { child } => {
let mut total = vec![0.0; self.n[p]];
for ri in 0..self.rc.len() {
let q = self.mask_by_card(opp, 1 - p, ri);
let v = self.br(strategy, *child, p, &q, ri);
let free = &self.rc[ri].free[p];
for i in 0..total.len() {
total[i] += self.wr * v[i] * free[i];
}
}
total
}
TNode::Dec { player, kids, .. } => {
if *player == p {
let mut best = vec![f64::NEG_INFINITY; self.n[p]];
for kid in kids {
let v = self.br(strategy, *kid, p, opp, r);
best.iter_mut().zip(&v).for_each(|(b, x)| *b = b.max(*x));
}
best
} else {
let mut total = vec![0.0; self.n[p]];
for (k, kid) in kids.iter().enumerate() {
let reach: Vec<f64> = (0..opp.len()).map(|j| opp[j] * strategy.row(node, r, j)[k]).collect();
let v = self.br(strategy, *kid, p, &reach, r);
total.iter_mut().zip(&v).for_each(|(t, x)| *t += x);
}
total
}
}
}
}
/// Normaliser: total deal weight of the disjoint pairs.
fn pair_mass(&self) -> f64 {
let d = self.disjoint(0, &self.weights[1]);
d.iter().zip(&self.weights[0]).map(|(x, w)| x * w).sum()
}
/// Best-response value of player `p` against `strategy`, chips per deal, in `p`'s own net.
pub fn best_response_value(&self, strategy: &TrStrategy, p: usize) -> f64 {
let v = self.br(strategy, self.game.root, p, &self.weights[1 - p], NO_CARD);
v.iter().zip(&self.weights[p]).map(|(x, w)| x * w).sum::<f64>() / self.pair_mass()
}
/// Exploitability of `strategy`: both best-response gains. Zero exactly at an equilibrium.
pub fn exploitability(&self, strategy: &TrStrategy) -> Exploit {
// Zero-sum: the value of the profile for player p is the negative of the other's, so the
// gains sum to BR_0 + BR_1.
let g0 = self.best_response_value(strategy, 0);
let g1 = self.best_response_value(strategy, 1);
Exploit { gain: [g0, g1], total: g0 + g1 }
}
/// Expected net of hero (player 0) when both follow `strategy`, chips per deal.
pub fn value(&self, strategy: &TrStrategy) -> f64 {
let v = self.follow(strategy, self.game.root, 0, &self.weights[1], NO_CARD, &vec![1.0; self.n[0]]);
v.iter().zip(&self.weights[0]).map(|(x, w)| x * w).sum::<f64>() / self.pair_mass()
}
fn follow(&self, strategy: &TrStrategy, node: usize, p: usize, opp: &[f64], r: usize, own: &[f64]) -> Vec<f64> {
match &self.game.nodes[node] {
TNode::Fold { folder, amt } => {
let v = if *folder == p { -amt } else { *amt };
self.disjoint(p, opp).into_iter().map(|x| x * v).collect()
}
TNode::Show { half } => self.show(p, r, opp, *half),
TNode::Chance { child } => {
let mut total = vec![0.0; self.n[p]];
for ri in 0..self.rc.len() {
let q = self.mask_by_card(opp, 1 - p, ri);
let v = self.follow(strategy, *child, p, &q, ri, own);
let free = &self.rc[ri].free[p];
for i in 0..total.len() {
total[i] += self.wr * v[i] * free[i];
}
}
total
}
TNode::Dec { player, kids, .. } => {
let mut total = vec![0.0; self.n[p]];
for (k, kid) in kids.iter().enumerate() {
if *player == p {
let v = self.follow(strategy, *kid, p, opp, r, own);
for i in 0..total.len() {
total[i] += strategy.row(node, r, i)[k] * v[i];
}
} else {
let reach: Vec<f64> = (0..opp.len()).map(|j| opp[j] * strategy.row(node, r, j)[k]).collect();
let v = self.follow(strategy, *kid, p, &reach, r, own);
total.iter_mut().zip(&v).for_each(|(t, x)| *t += x);
}
}
total
}
}
}
/// The river card with this bit (index into the enumerated cards), if enumerated.
pub fn card_index(&self, bit: u64) -> Option<usize> {
self.rc.iter().position(|c| c.bit == bit)
}
}
#[cfg(test)]
mod tests;
+381
View File
@@ -0,0 +1,381 @@
use super::*;
use crate::card::Card;
use crate::cfr::river_game;
use crate::rng::Rng;
const BOARD: &str = "Ah 7d 2c Ks";
fn board() -> u64 {
fast7::mask(&Card::parse_list(BOARD).unwrap())
}
/// All two-card combos off the board and off `avoid`.
fn pool(avoid: u64) -> Vec<u64> {
let bits: Vec<u64> = (0..4u32).flat_map(|s| (0..13u32).map(move |r| 1u64 << (16 * s + r))).filter(|b| b & (board() | avoid) == 0).collect();
let mut v = Vec::new();
for i in 0..bits.len() {
for j in i + 1..bits.len() {
v.push(bits[i] | bits[j]);
}
}
v
}
fn lcg(x: &mut u64) -> u64 {
*x = x.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
*x >> 33
}
/// `n` random distinct combos with random weights.
fn random_hands(n: usize, seed: u64, avoid: u64) -> Hands {
let p = pool(avoid);
let mut x = seed;
let mut masks: Vec<u64> = Vec::new();
while masks.len() < n {
let m = p[(lcg(&mut x) as usize) % p.len()];
if !masks.contains(&m) {
masks.push(m);
}
}
let weights = (0..n).map(|_| 0.2 + (lcg(&mut x) % 1000) as f64 / 1000.0).collect();
Hands { masks, weights }
}
fn only_all_in() -> Menu {
Menu { fracs: vec![], raise_mult: vec![], max_raises: 0, allin: true }
}
// --- an independent scalar evaluator: one deal at a time, payoffs from the chips actually put in ---
type Probs<'a> = &'a dyn Fn(usize, usize, usize) -> Vec<f64>; // (node, card copy, hand of the deciding player)
struct Walk<'a> {
s: &'a TrSolver,
probs: Probs<'a>,
masks: [u64; 2],
hands: [usize; 2],
}
impl Walk<'_> {
fn go(&self, node: usize, chips: [f64; 2], c: [f64; 2], r: usize) -> [f64; 2] {
match &self.s.game.nodes[node] {
TNode::Fold { folder, .. } => {
let mut out = [0.0; 2];
out[*folder] = -chips[*folder];
out[1 - *folder] = chips[*folder];
out
}
TNode::Show { .. } => {
assert_eq!(chips[0], chips[1], "a showdown is matched");
let b = self.s.rc[r].bit;
let bd = board();
let sc = [fast7::score(self.masks[0] | bd | b), fast7::score(self.masks[1] | bd | b)];
match sc[0].cmp(&sc[1]) {
std::cmp::Ordering::Greater => [chips[1], -chips[1]],
std::cmp::Ordering::Less => [-chips[0], chips[0]],
std::cmp::Ordering::Equal => [0.0, 0.0],
}
}
TNode::Chance { child } => {
assert_eq!(chips[0], chips[1], "a street ends matched");
let mut out = [0.0; 2];
for card in 0..self.s.rc.len() {
if (self.masks[0] | self.masks[1]) & self.s.rc[card].bit != 0 {
continue;
}
let v = self.go(*child, chips, [0.0, 0.0], card);
out[0] += self.s.wr * v[0];
out[1] += self.s.wr * v[1];
}
out
}
TNode::Dec { player, kids, .. } => {
let p = (self.probs)(node, r, self.hands[*player]);
let mut out = [0.0; 2];
for (k, kid) in kids.iter().enumerate() {
let (mut ch, mut cc) = (chips, c);
match self.s.game.acts[node][k] {
Act::Bet(to) | Act::Raise(to) => {
ch[*player] += to - cc[*player];
cc[*player] = to;
}
Act::Call => {
ch[*player] += cc[1 - *player] - cc[*player];
cc[*player] = cc[1 - *player];
}
_ => {}
}
let v = self.go(*kid, ch, cc, r);
out[0] += p[k] * v[0];
out[1] += p[k] * v[1];
}
out
}
}
}
}
/// Expected net of both players over all valid deals, normalised like the solver.
fn scalar_values(s: &TrSolver, pot: f64, probs: Probs) -> [f64; 2] {
let (mut tot, mut mass) = ([0.0; 2], 0.0);
for i in 0..s.n[0] {
for j in 0..s.n[1] {
if s.masks[0][i] & s.masks[1][j] != 0 {
continue;
}
mass += s.weights[0][i] * s.weights[1][j];
let w = Walk { s, probs, masks: [s.masks[0][i], s.masks[1][j]], hands: [i, j] };
let v = w.go(s.game.root, [pot / 2.0, pot / 2.0], [0.0, 0.0], NO_CARD);
for p in 0..2 {
tot[p] += s.weights[0][i] * s.weights[1][j] * v[p];
}
}
}
[tot[0] / mass, tot[1] / mass]
}
fn tiny(hero: usize, villain: usize, first: usize, seed: u64) -> (TrSolver, f64) {
let pot = 4.0;
let bets = TrBets { pot, stack: 8.0, first, turn: only_all_in(), river: only_all_in() };
let game = build(&bets, &[]);
let hands = [random_hands(hero, seed, 0), random_hands(villain, seed ^ 0x9E37, 0)];
let cards = vec![fast7::mask(&Card::parse_list("3s").unwrap()), fast7::mask(&Card::parse_list("Jh").unwrap())];
// Two river cards, each standing for half of the deals.
let wr = 0.5 * 48.0 / 44.0;
(TrSolver::with_cards(game, hands, board(), cards, wr), pot)
}
#[test]
fn the_vector_values_equal_the_scalar_enumeration_and_the_game_is_zero_sum() {
for first in 0..2 {
let (mut s, pot) = tiny(3, 2, first, 11 + first as u64);
s.run(300);
let strat = s.strategy();
let f = |node: usize, r: usize, h: usize| strat.row(node, r, h).to_vec();
let [v0, v1] = scalar_values(&s, pot, &f);
assert!((v0 + v1).abs() < 1e-9, "zero-sum: {v0} {v1}");
let vec_value = s.value(&strat);
assert!((vec_value - v0).abs() < 1e-9, "vector {vec_value} vs scalar {v0}");
}
}
/// The best response by brute force: every pure strategy of the player against the other's fixed one.
fn brute_best_response(s: &TrSolver, pot: f64, strat: &TrStrategy, p: usize) -> f64 {
let k = s.rc.len();
let mut sets: Vec<(usize, usize, usize, usize)> = Vec::new(); // node, copy, hand, actions
for (node, n) in s.game.nodes.iter().enumerate() {
if let TNode::Dec { player, street, kids } = n {
if *player == p {
for copy in 0..(if *street == 0 { 1 } else { k }) {
for h in 0..s.n[p] {
sets.push((node, copy, h, kids.len()));
}
}
}
}
}
let total: u64 = sets.iter().map(|x| x.3 as u64).product();
assert!(total <= 1 << 20, "{total} pure strategies is too many for a brute force");
let mut best = f64::NEG_INFINITY;
for code in 0..total {
let mut c = code;
let mut choice = std::collections::HashMap::new();
for (node, copy, h, a) in &sets {
choice.insert((*node, *copy, *h), (c % *a as u64) as usize);
c /= *a as u64;
}
let f = |node: usize, r: usize, h: usize| -> Vec<f64> {
if let TNode::Dec { player, street, kids } = &s.game.nodes[node] {
if *player == p {
let copy = if *street == 0 { 0 } else { r };
let mut v = vec![0.0; kids.len()];
v[choice[&(node, copy, h)]] = 1.0;
return v;
}
}
strat.row(node, r, h).to_vec()
};
best = best.max(scalar_values(s, pot, &f)[p]);
}
best
}
#[test]
fn the_best_response_equals_a_brute_force_over_all_pure_strategies() {
let (mut s, pot) = tiny(3, 2, 0, 5);
let uniform = s.strategy();
s.run(200);
let solved = s.strategy();
for (name, strat) in [("uniform", &uniform), ("solved", &solved)] {
for p in 0..2 {
let brute = brute_best_response(&s, pot, strat, p);
let fast = s.best_response_value(strat, p);
assert!((brute - fast).abs() < 1e-9, "{name} player {p}: brute {brute} vs vector {fast}");
}
}
let e = s.exploitability(&solved);
let u = s.exploitability(&uniform);
eprintln!("tiny game: solved exploitability {:.5}, uniform {:.5}", e.total, u.total);
assert!(e.total < 0.05, "solved exploitability {}", e.total);
assert!(u.total > 5.0 * e.total.max(1e-3), "a uniform strategy is much more exploitable ({} vs {})", u.total, e.total);
}
#[test]
fn the_solver_converges_on_a_real_sized_game() {
let bets = TrBets::standard(20.0, 80.0, 0);
let game = build(&bets, &[]);
let hands = [random_hands(14, 3, 0), random_hands(14, 4, 0)];
let mut s = TrSolver::new(game, hands, board(), Some(10));
let mut seen = Vec::new();
for _ in 0..4 {
s.run(100);
seen.push(s.exploitability(&s.strategy()).total);
}
eprintln!("exploitability after 100/200/300/400 iterations: {seen:?} (pot 20)");
assert!(seen[3] < seen[0], "{seen:?}");
assert!(seen[3] < 0.5, "exploitability {} chips on a 20-chip pot", seen[3]);
}
#[test]
fn a_checked_through_turn_is_exactly_the_river_game() {
let river_card = fast7::mask(&Card::parse_list("3s").unwrap());
// Hands with pairwise distinct strengths on this runout, so classes are strength ranks.
let bd = board();
let mut x = 99u64;
let p = pool(river_card);
let mut used = std::collections::HashSet::new();
let mut pick = |n: usize| {
let mut v = Vec::new();
while v.len() < n {
let m = p[(lcg(&mut x) as usize) % p.len()];
if used.insert(fast7::score(m | bd | river_card)) {
v.push(m);
}
}
v
};
let (hm, vm) = (pick(5), pick(5));
let hands = [Hands { masks: hm.clone(), weights: vec![1.0, 2.0, 1.0, 3.0, 1.0] }, Hands { masks: vm.clone(), weights: vec![2.0, 1.0, 1.0, 1.0, 2.0] }];
let (pot, stack, first) = (10.0, 40.0, 1);
let rmenu = Menu { fracs: vec![0.5, 1.0], raise_mult: vec![3.0], max_raises: 1, allin: true };
let bets = TrBets { pot, stack, first, turn: Menu { fracs: vec![], raise_mult: vec![], max_raises: 0, allin: false }, river: rmenu };
let game = build(&bets, &[]);
let mut mine = TrSolver::with_cards(game, hands.clone(), bd, vec![river_card], 1.0);
mine.run(1500);
let strat = mine.strategy();
let e_mine = mine.exploitability(&strat).total;
let v_mine = mine.value(&strat);
// The river game over the same hands as classes.
let score = |m: u64| fast7::score(m | bd | river_card);
let mut ladder: Vec<u32> = hm.iter().chain(&vm).map(|m| score(*m)).collect();
ladder.sort();
ladder.dedup();
let class = |m: u64| ladder.iter().position(|l| *l == score(m)).unwrap();
let n = ladder.len();
let mut chance = vec![0.0; n * n];
for (i, a) in hm.iter().enumerate() {
for (j, b) in vm.iter().enumerate() {
if a & b == 0 {
chance[class(*a) * n + class(*b)] += hands[0].weights[i] * hands[1].weights[j];
}
}
}
let z: f64 = chance.iter().sum();
chance.iter_mut().for_each(|c| *c /= z);
let rb = river_game::Bets { pot, stack, first, bet_fracs: vec![0.5, 1.0], raise_mult: vec![3.0], max_raises: 1 };
let rg = river_game::build(n, chance, &rb, &[]);
let solved = crate::cfr::solve::solve(&rg.tree, 3000, Rng::seeded(1));
let e_rg = crate::cfr::exploitability::exploitability(&rg.tree, &solved.strategy);
let v_rg = crate::cfr::exploitability::game_value(&rg.tree, &solved.strategy);
// The river game's strategy, carried into this game node by node, is judged by this module's best response.
let mut at = mine.game.root;
while !matches!(mine.game.nodes[at], TNode::Chance { .. }) {
let TNode::Dec { kids, .. } = &mine.game.nodes[at] else { panic!() };
at = kids[0];
}
let TNode::Chance { child } = &mine.game.nodes[at] else { unreachable!() };
let r0 = *child;
assert!(r0 + rg.tree.nodes.len() < mine.game.nodes.len());
let mut carried = mine.strategy();
for k in 0..rg.tree.nodes.len() {
if let Node::Decision { player, .. } = &rg.tree.nodes[k] {
let a = carried.actions[r0 + k];
assert_eq!(a, rg.tree.action_count(k).unwrap(), "same actions at the same node");
let ms = if *player == 0 { &hm } else { &vm };
for (h, m) in ms.iter().enumerate() {
let row = solved.strategy.row(k, class(*m)).to_vec();
carried.probs[r0 + k][h * a..(h + 1) * a].copy_from_slice(&row);
}
}
}
let e_carried = mine.exploitability(&carried).total;
let v_carried = mine.value(&carried);
eprintln!("mine: value {v_mine:.4} expl {e_mine:.4}; river_game: value {v_rg:.4} expl {e_rg:.4}; carried: value {v_carried:.4} expl {e_carried:.4}");
assert!(e_mine < 0.05 && e_rg < 0.05, "{e_mine} {e_rg}");
assert!((v_mine - v_rg).abs() < 0.05, "game values differ: {v_mine} vs {v_rg}");
assert!(e_carried < 0.05, "the river game's equilibrium is an equilibrium here too: {e_carried}");
assert!((v_carried - v_rg).abs() < 0.05, "same payoffs: {v_carried} vs {v_rg}");
}
use crate::cfr::tree::Node;
#[test]
fn an_observed_turn_bet_is_a_node_and_hero_faces_it() {
let bets = TrBets::standard(20.0, 80.0, 1);
let g = build(&bets, &[Act::Bet(13.0)]);
let at = g.at.expect("hero faces the bet");
let TNode::Dec { player, street, .. } = &g.nodes[at] else { panic!() };
assert_eq!((*player, *street), (0, 0));
assert_eq!(g.acts[at][0], Act::Fold);
assert_eq!(g.acts[at][1], Act::Call);
assert!(g.acts[at].iter().any(|a| matches!(a, Act::Raise(_))));
assert!(g.acts[g.root].contains(&Act::Bet(13.0)), "exact size in the tree");
let g2 = build(&bets, &[Act::Check]);
let at2 = g2.at.expect("hero acts after villain checks");
assert!(matches!(&g2.nodes[at2], TNode::Dec { player: 0, street: 0, .. }));
let g3 = build(&TrBets::standard(20.0, 80.0, 0), &[]);
assert_eq!(g3.at, Some(g3.root));
}
/// Convergence probe: exploitability (percent of the pot) against iterations and time.
#[test]
#[ignore = "timing probe"]
fn convergence_probe() {
for (n, k) in [(200usize, 16usize), (200, 48)] {
let bets = TrBets::standard(20.0, 80.0, 0);
let game = build(&bets, &[]);
let hands = [random_hands(n, 3, 0), random_hands(n, 4, 0)];
let mut s = TrSolver::new(game, hands, board(), Some(k));
let t = std::time::Instant::now();
let mut done = 0;
for target in [25u32, 50, 100, 200, 400] {
s.run(target - done);
done = target;
let ms = t.elapsed().as_secs_f64() * 1e3;
let e = s.exploitability(&s.strategy()).total;
eprintln!("combos {n} cards {k}: {target} iterations ({ms:.0} ms): exploitability {:.2} % of the pot", e / 20.0 * 100.0);
let t2 = std::time::Instant::now();
let _ = t2;
}
}
}
/// Timing probe (run with `--ignored --nocapture`): iterations per second at table-sized ranges.
#[test]
#[ignore = "timing probe"]
fn timing_probe() {
for (n, k) in [(150usize, 48usize), (150, 16), (150, 8), (300, 16), (300, 8)] {
for river_fracs in [vec![0.7], vec![]] {
let mut bets = TrBets::standard(20.0, 80.0, 0);
bets.river.fracs = river_fracs.clone();
let game = build(&bets, &[]);
let nodes = game.nodes.len();
let hands = [random_hands(n, 3, 0), random_hands(n, 4, 0)];
let mut s = TrSolver::new(game, hands, board(), Some(k));
let t = std::time::Instant::now();
s.run(10);
let per = t.elapsed().as_secs_f64() / 10.0;
eprintln!("combos {n} river cards {k} river sizes {river_fracs:?}: {nodes} nodes, {:.1} ms/iteration", per * 1e3);
}
}
}
+5
View File
@@ -97,6 +97,11 @@ 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);
}
// 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) {
return d.with_equity(equity.share);
}
return super::river_subgame::fold_veto(raw, floored);
}
floored
+1
View File
@@ -22,5 +22,6 @@ pub mod semibluff;
pub mod size_policy;
pub mod texture_stance;
pub mod thin_value;
pub mod turn_game;
pub mod turn_subgame;
pub mod uncertainty;
+1 -1
View File
@@ -754,7 +754,7 @@ fn deal_classes(spot: &Spot, hero_combos: &[(Vec<Card>, f64)], villain_combos: &
}
/// The legal choice nearest to a game action.
fn legal_choice(spot: &Spot, act: Act) -> Choice {
pub(crate) fn legal_choice(spot: &Spot, act: Act) -> Choice {
let passive = if spot.to_call > 0.0 { Choice::Call } else { Choice::Check };
match act {
Act::Fold if spot.to_call > 0.0 => Choice::Fold,
+322
View File
@@ -0,0 +1,322 @@
//! The turn re-solved at the table over real hands (plan E3, layer 2): both ranges from the
//! blueprint (`blueprint::ranges`, carried along the line actually played), the turn betting and
//! the river inside one game (`cfr::turn_river_game`), hero's equilibrium action at the real node.
//!
//! Switch: `TurnPlayer::Grund` (default `Off`; `ab_zelle` / `engine_lbr`: `TURN_SPIEL=grund`). Off,
//! `turn_game_decision` returns `None` before it looks at anything, so the engine's output is
//! unchanged. On, it plays only where the blueprint recognises the spot (S1: button open, big blind
//! call, about 100 bb, heads-up on the turn, hero at a decision); everywhere else the heuristic plays.
//!
//! The solve depends on the public state only (board, line, pot, stacks): the villain's range is NOT
//! conditioned on hero's real cards (`gewichtete_listen_offen`; the game deals card removal itself),
//! so one solve serves every hero hand at the same node. Solves are cached by public state (a
//! measurement that asks the engine for every hand of a range, as LBR does, pays one solve per node).
//!
//! Approximations (named, each a knob of `TurnConfig`): ranges are pruned to the `max_combos`
//! heaviest combos per player; the river is enumerated over `river_cards` evenly strided cards, each
//! standing for its share (`cfr::turn_river_game`); the bet menu is `TrBets::standard` plus the
//! observed size; the solve is a fixed `iterations` of CFR+. Hero's real hand, if pruned away or
//! outside the blueprint range, is put back with its weight (or a token weight) in an uncached solve.
use crate::card::Card;
use crate::cfr::river_game::Act;
use crate::cfr::turn_river_game::{build, Exploit, Hands, TNode, TrBets, TrSolver};
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::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::sync::{Arc, Mutex};
static MODE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
/// Who plays the heads-up turn.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TurnPlayer {
/// The heuristic (default).
Off,
/// The turn+river game with both ranges from the blueprint; only where the spot is a blueprint
/// scenario, else the heuristic plays.
Grund,
}
pub fn set_turn_player(mode: TurnPlayer) {
MODE.store(u8::from(mode == TurnPlayer::Grund), std::sync::atomic::Ordering::Relaxed);
}
pub fn turn_player() -> TurnPlayer {
if MODE.load(std::sync::atomic::Ordering::Relaxed) == 1 {
TurnPlayer::Grund
} else {
TurnPlayer::Off
}
}
/// Size and budget of the solve.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct TurnConfig {
/// Most combos per player (heaviest by weight).
pub max_combos: usize,
/// Stop adding combos once this share of the range mass is in (before `max_combos`).
pub cover: f64,
/// River cards enumerated (of 48).
pub river_cards: usize,
/// CFR+ iterations.
pub iterations: u32,
/// Also compute the best-response exploitability of the result (about two more iterations).
pub measure: bool,
/// Raises allowed after a river bet (0 or 1).
pub river_raises: usize,
}
impl TurnConfig {
pub const STANDARD: TurnConfig = TurnConfig { max_combos: 160, cover: 0.95, river_cards: 10, iterations: 200, measure: false, river_raises: 0 };
/// `STANDARD` with `TURN_COMBOS`, `TURN_CARDS`, `TURN_ITERS`, `TURN_EXPLOIT=1` from the environment.
pub fn from_env() -> TurnConfig {
let num = |k: &str, d: usize| std::env::var(k).ok().and_then(|s| s.parse().ok()).filter(|n| *n > 0).unwrap_or(d);
TurnConfig {
max_combos: num("TURN_COMBOS", Self::STANDARD.max_combos),
cover: num("TURN_COVER", 95) as f64 / 100.0,
river_cards: num("TURN_CARDS", Self::STANDARD.river_cards),
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)),
}
}
}
/// One solved node of the game: what every hero hand at this public state shares.
pub struct Solved {
/// Hero's turn-node action probabilities, `hero_masks.len()` rows of `acts.len()`.
rows: Vec<f64>,
acts: Vec<Act>,
hero_masks: Vec<u64>,
pub millis: f64,
pub combos: [usize; 2],
pub nodes: usize,
/// Best-response exploitability of the solved game, chips per deal (when `measure`).
pub exploit: Option<Exploit>,
pub big_blind: f64,
pub pot: f64,
}
impl Solved {
/// Exploitability in bb per 100 decisions of this kind (what the plan's gate counts).
pub fn exploit_bb_per_100(&self) -> Option<f64> {
self.exploit.map(|e| e.total / self.big_blind * 100.0)
}
}
/// The result of deciding one hand from a `Solved`.
pub struct TurnSolved {
pub decision: Decision,
/// Hero's action probabilities for the real hand at the real node, and the actions they stand for.
pub row: Vec<f64>,
pub acts: Vec<Act>,
pub solved: Arc<Solved>,
}
/// 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.
fn turn_line(spot: &Spot, villain: &Villain) -> (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) {
let who = if r.seat == spot.hero_seat {
0
} else if r.seat == villain.seat {
1
} else {
continue;
};
first.get_or_insert(who);
let amount = r.amount.unwrap_or(c[who]);
match r.action {
SeenAction::Check => acts.push(Act::Check),
SeenAction::Bet | SeenAction::Raise | SeenAction::AllIn if amount > c[1 - who] => {
acts.push(if aggressed { Act::Raise(amount) } else { Act::Bet(amount) });
aggressed = true;
c[who] = amount;
}
SeenAction::Call | SeenAction::AllIn => {
acts.push(Act::Call);
c[who] = c[1 - who];
}
_ => {}
}
}
let consistent = (c[1] - c[0] - spot.to_call).abs() < 1e-6 * spot.pot.max(1.0);
match first {
Some(f) if consistent => (f, acts, c),
_ if spot.to_call > 0.0 => (1, vec![Act::Bet(spot.to_call)], [0.0, spot.to_call]),
_ => (0, Vec::new(), [0.0, 0.0]),
}
}
/// 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 {
let mut v: Vec<(u64, f64)> = list
.iter()
.filter(|(c, w)| c.len() == 2 && *w > 0.0 && w.is_finite())
.map(|(c, w)| (fast7::mask(c), *w))
.filter(|(m, _)| m & board == 0 && m.count_ones() == 2)
.collect();
v.sort_by(|a, b| b.1.total_cmp(&a.1).then(a.0.cmp(&b.0)));
v.dedup_by_key(|x| x.0);
let top = v.first().map_or(1.0, |x| x.1);
let kept = keep.and_then(|k| v.iter().position(|x| x.0 == k).map(|i| v[i].1));
let total: f64 = v.iter().map(|x| x.1).sum();
let mut acc = 0.0;
let enough = v
.iter()
.position(|x| {
acc += x.1;
acc >= cfg.cover * total
})
.map_or(v.len(), |i| i + 1);
v.truncate(enough.min(cfg.max_combos).max(1));
if let Some(k) = keep {
if !v.iter().any(|x| x.0 == k) {
// Pruned away, or not in the blueprint range at all: stays in with the weight it had, else
// a token weight, so the game has a strategy for it without moving the equilibrium.
v.push((k, kept.unwrap_or(top * 1e-6)));
}
}
Hands { masks: v.iter().map(|x| x.0).collect(), weights: v.iter().map(|x| x.1).collect() }
}
/// Solve the game of `spot`'s public state with these weighted ranges. `keep`: a hero hand that must
/// be in the game whatever the pruning. `None` outside a heads-up turn decision or when the line
/// leaves the tree.
fn solve_core(spot: &Spot, hero: &[(Vec<Card>, f64)], villain_list: &[(Vec<Card>, f64)], cfg: &TurnConfig, keep: Option<u64>) -> Option<Solved> {
if spot.street != Street::Turn || spot.board.len() != 4 || spot.live_villains().count() != 1 {
return None;
}
let villain = spot.live_villains().next()?;
let (first, forced, c) = turn_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 <= c[0].max(c[1]) {
return None;
}
let started = std::time::Instant::now();
let board = fast7::mask(&spot.board);
let hands = [prune(hero, board, cfg, keep), prune(villain_list, board, cfg, None)];
if hands[0].masks.is_empty() || hands[1].masks.is_empty() {
return None;
}
let mut bets = TrBets::standard(pot, stack, first);
bets.river.max_raises = cfg.river_raises;
let game = build(&bets, &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.river_cards));
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();
let millis = started.elapsed().as_secs_f64() * 1e3;
Some(Solved { rows, acts, hero_masks, millis, combos, nodes, exploit, big_blind: spot.big_blind, pot })
}
/// Hero's decision for the real hand from a solved node.
fn decide_from(spot: &Spot, solved: Arc<Solved>, hero_mask: u64) -> Option<TurnSolved> {
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].to_vec();
let (draw, _) = Rng::seeded(spot.seed).unit();
let mut acc = 0.0;
let mut pick = row.len().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);
let decision = Decision::new(
choice,
p.clamp(0.0, 1.0),
format!("turn game: {}x{} combos, {} nodes, {act:?} p {p:.2}, solved in {:.0} ms", solved.combos[0], solved.combos[1], solved.nodes, solved.millis),
);
let acts = solved.acts.clone();
Some(TurnSolved { decision, row, acts, solved })
}
/// Solve the turn for `spot` with these weighted ranges (`hero`, `villain`, as `gewichtete_listen`
/// gives them) and decide; no cache. `None` outside a heads-up turn decision or off the tree.
pub fn solve_turn(spot: &Spot, hero: &[(Vec<Card>, f64)], villain_list: &[(Vec<Card>, f64)], cfg: &TurnConfig) -> Option<TurnSolved> {
if spot.hero_cards.len() != 2 {
return None;
}
let hero_mask = fast7::mask(&spot.hero_cards);
if hero_mask & fast7::mask(&spot.board) != 0 {
return None;
}
let solved = solve_core(spot, hero, villain_list, cfg, Some(hero_mask))?;
decide_from(spot, Arc::new(solved), hero_mask)
}
static CACHE: Mutex<Option<HashMap<u64, Arc<Solved>>>> = Mutex::new(None);
/// An entry is a few kilobytes (one row of probabilities per hero combo).
const CACHE_MAX: usize = 4096;
/// Identity of the public state and the solve budget (not hero's cards).
fn public_key(spot: &Spot, cfg: &TurnConfig) -> 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));
(spot.hero_seat, cfg.max_combos, cfg.cover.to_bits(), cfg.river_cards, cfg.iterations, cfg.measure, cfg.river_raises).hash(&mut h);
h.finish()
}
/// The live decision: the turn game with ranges from the blueprint, or `None` (switch off, not a
/// blueprint spot, ...) and the heuristic keeps the decision.
pub fn turn_game_decision(spot: &Spot) -> Option<Decision> {
if turn_player() == TurnPlayer::Off || spot.street != Street::Turn || spot.hero_cards.len() != 2 {
return None;
}
let cfg = TurnConfig::from_env();
let hero_mask = fast7::mask(&spot.hero_cards);
if hero_mask & fast7::mask(&spot.board) != 0 {
return None;
}
let key = public_key(spot, &cfg);
let cached = CACHE.lock().ok()?.as_ref().and_then(|m| m.get(&key).cloned());
let solved = match cached {
Some(s) => s,
None => {
let (hero, villain) = crate::blueprint::ranges::gewichtete_listen_offen(spot)?;
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());
}
solved
}
};
// A hero hand outside the pruned range (low weight at this node, or not in the blueprint range at
// all) is not in the game: `None`, the heuristic plays it.
decide_from(spot, solved, hero_mask).map(|d| d.decision)
}
#[cfg(test)]
mod tests;
+242
View File
@@ -0,0 +1,242 @@
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()
);
}
}