Blueprint-Szenariofamilie: s1, sb, co, btn3, co3 (Szenario, Grund::mit, erkennen, grundstrategie <szenario>)
- szenario.rs: Eroeffner, Groessen, 3-Bet, Stack, Einsatzmenue je Szenario (3-Bet-Pots: Flop 25/50 %, Jam ab 85 % Stack) - s1.rs: Einsatzbaum::neu(&Szenario), Grund::mit (Ranges aus den Engine-Charts), S1 = Alias, Baum und s1.ckpt unveraendert - ranges.rs: erkennen(spot) -> (Szenario, Sitze), grundstrategie_fuer(sz) laedt <id>.ckpt; 4-Bet/Multiway/Limp/andere Eroeffner -> None - bin/grundstrategie: 5. Argument Szenario, <id>.ckpt, LBR-<id>.txt (S1 unveraendert) - Tests je Szenario: Baum, Nullsumme, Ranges, Erkennung, LBR fallend Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+21
-12
@@ -1,13 +1,17 @@
|
||||
//! Computes the S1 blueprint (plan E2d) with checkpoints, so a run can stop any time (live first).
|
||||
//! Computes a blueprint scenario (plan E2d; S1 by default) with checkpoints, so a run can stop any
|
||||
//! time (live first).
|
||||
//!
|
||||
//! grundstrategie <abstraktion-dir> <out-dir> <runden> [periode] threads: POKERBENCH_THREADS
|
||||
//! grundstrategie <abstraktion-dir> <out-dir> <runden> [periode] [szenario] threads: POKERBENCH_THREADS
|
||||
//!
|
||||
//! Resumes from `<out-dir>/s1.ckpt` if present. After every round the checkpoint is rewritten
|
||||
//! `szenario` is one of s1 (default), sb, co, btn3, co3 (`blueprint::szenario`). Resumes from
|
||||
//! `<out-dir>/<szenario>.ckpt` if present; LBR lines go to `LBR.txt` (`LBR-<szenario>.txt` for
|
||||
//! the others), the marker to `FERTIG` (`FERTIG-<szenario>`). After every round the checkpoint is rewritten
|
||||
//! (atomically via a temp file). Bench copies: `pokerbench-engine-grundstrategie.exe`.
|
||||
|
||||
use rechner::blueprint::lbr::lbr;
|
||||
use rechner::blueprint::mccfr::{rechnen, Tabellen};
|
||||
use rechner::blueprint::s1::{Abstraktion, S1};
|
||||
use rechner::blueprint::s1::{Abstraktion, Grund};
|
||||
use rechner::blueprint::szenario::Szenario;
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
use std::time::Instant;
|
||||
@@ -15,10 +19,15 @@ use std::time::Instant;
|
||||
fn main() {
|
||||
let a: Vec<String> = std::env::args().collect();
|
||||
if a.len() < 4 {
|
||||
panic!("grundstrategie <abstraktion-dir> <out-dir> <runden> [periode]");
|
||||
panic!("grundstrategie <abstraktion-dir> <out-dir> <runden> [periode] [s1|sb|co|btn3|co3]");
|
||||
}
|
||||
let runden: u64 = a[3].parse().unwrap();
|
||||
let periode: u64 = a.get(4).and_then(|s| s.parse().ok()).unwrap_or(1_000_000);
|
||||
let name = a.get(5).map_or("s1", |s| s.as_str());
|
||||
let sz = Szenario::finde(name).unwrap_or_else(|| panic!("unknown scenario {name}"));
|
||||
// S1 keeps its original file names (a running job and its consumers use them).
|
||||
let suffix = if sz.id == "s1" { String::new() } else { format!("-{}", sz.id) };
|
||||
let sitze = if sz.id == "s1" { ["BB", "BTN"] } else { ["OOP", "IP"] };
|
||||
let threads: usize = std::env::var("POKERBENCH_THREADS").ok().and_then(|s| s.parse().ok()).unwrap_or(2).max(1);
|
||||
let out = Path::new(&a[2]);
|
||||
std::fs::create_dir_all(out).unwrap();
|
||||
@@ -26,13 +35,13 @@ fn main() {
|
||||
while !Path::new(&a[1]).join("BERICHT.txt").exists() {
|
||||
std::thread::sleep(std::time::Duration::from_secs(30));
|
||||
}
|
||||
let spiel = S1::neu(Abstraktion::laden(Path::new(&a[1])).expect("abstraction tables"));
|
||||
let spiel = Grund::mit(sz, Abstraktion::laden(Path::new(&a[1])).expect("abstraction tables"));
|
||||
let mut tab = Tabellen::neu(&spiel);
|
||||
let ckpt = out.join("s1.ckpt");
|
||||
let ckpt = out.join(format!("{}.ckpt", sz.id));
|
||||
if tab.datei_lesen(&ckpt) {
|
||||
println!("fortgesetzt bei Runde {}", tab.runden);
|
||||
}
|
||||
println!("S1: {} Eintraege, {threads} Threads, Periode {periode}", tab.eintraege());
|
||||
println!("{}: {} Eintraege, {threads} Threads, Periode {periode}", sz.id, tab.eintraege());
|
||||
while tab.runden < runden {
|
||||
let t = Instant::now();
|
||||
rechnen(&spiel, &mut tab, 1, periode, threads, 0xE2D_5EED);
|
||||
@@ -45,14 +54,14 @@ fn main() {
|
||||
let n = if tab.runden == runden { 400_000 } else { 20_000 };
|
||||
let e = lbr(&spiel, &tab, n, threads, 0x1B2 ^ tab.runden);
|
||||
let zeile = format!(
|
||||
"Runde {} LBR {:+.1} ±{:.1} bb/100 (BB {:+.1}, BTN {:+.1}), {} Haende, {:.0}s",
|
||||
tab.runden, e.bb100, e.ci95, e.je_sitz[0], e.je_sitz[1], e.haende, t.elapsed().as_secs_f64()
|
||||
"Runde {} LBR {:+.1} ±{:.1} bb/100 ({} {:+.1}, {} {:+.1}), {} Haende, {:.0}s",
|
||||
tab.runden, e.bb100, e.ci95, sitze[0], e.je_sitz[0], sitze[1], e.je_sitz[1], e.haende, t.elapsed().as_secs_f64()
|
||||
);
|
||||
println!("{zeile}");
|
||||
let mut f = std::fs::OpenOptions::new().create(true).append(true).open(out.join("LBR.txt")).unwrap();
|
||||
let mut f = std::fs::OpenOptions::new().create(true).append(true).open(out.join(format!("LBR{suffix}.txt"))).unwrap();
|
||||
writeln!(f, "{zeile}").unwrap();
|
||||
}
|
||||
}
|
||||
// Marker for queued consumers (the E2e ladder arm waits for it).
|
||||
std::fs::write(out.join("FERTIG"), format!("{} Runden\n", tab.runden)).unwrap();
|
||||
std::fs::write(out.join(format!("FERTIG{suffix}")), format!("{} Runden\n", tab.runden)).unwrap();
|
||||
}
|
||||
|
||||
@@ -47,6 +47,7 @@ impl EngineGegner {
|
||||
/// The spot of S1 node `k` for the acting player holding `hand`; also the contributions at the
|
||||
/// start of the node's street.
|
||||
pub fn spot(&self, s: &S1, k: usize, hand: u64, board: u64) -> Option<(Spot, f64)> {
|
||||
assert_eq!(s.sz.id, "s1", "the engine opponent is built for scenario S1 only");
|
||||
let Knoten::Zug { spieler: p, strasse, kinder } = &s.baum.baum.knoten[k] else { return None };
|
||||
let (p, strasse) = (*p, *strasse);
|
||||
// Path root -> k.
|
||||
|
||||
+357
-357
@@ -1,357 +1,357 @@
|
||||
//! Local Best Response (Lisý/Bowling 2017) against the blueprint: the gate of plan E2d.
|
||||
//!
|
||||
//! LBR plays real cards against the blueprint's average strategy. It tracks the opponent's range
|
||||
//! card by card (preflop chart weights times the blueprint's probability of every action taken,
|
||||
//! per combo through its class), and at each own decision picks the action with the best value
|
||||
//! under the assumption that afterwards both players only check or call:
|
||||
//!
|
||||
//! - fold: lose what is in; check / call: equity share of the pot after calling;
|
||||
//! - bet / raise: the opponent folds with the probability its range folds at that node, otherwise
|
||||
//! calls (a raise counts as a call), and LBR gets its equity against the calling part.
|
||||
//!
|
||||
//! The opponent then acts by its strategy for its real hand. LBR's average result over both seats is
|
||||
//! a lower bound on the blueprint's exploitability (bb per hand; the gate is < 0.3, i.e. 30 bb/100).
|
||||
|
||||
use super::abstraktion::river_ehs;
|
||||
use super::iso;
|
||||
use super::mccfr::{Knoten, Spiel, Tabellen, Zufall};
|
||||
use super::s1::{Aktion, S1};
|
||||
use crate::hand::fast7;
|
||||
use crate::rng::split_mix::Rng;
|
||||
|
||||
/// Flop equity: run-outs sampled per decision (turn and river enumerate exactly).
|
||||
const FLOP_RUNOUTS: usize = 64;
|
||||
|
||||
pub struct Ergebnis {
|
||||
/// LBR's mean result in bb/100, averaged over both seats, and its 95 % half-width.
|
||||
pub bb100: f64,
|
||||
pub ci95: f64,
|
||||
pub haende: usize,
|
||||
/// bb/100 as player 0 (big blind) and as player 1 (button).
|
||||
pub je_sitz: [f64; 2],
|
||||
}
|
||||
|
||||
/// LBR's equity (win + tie/2) against every combo given the street's board, by exact enumeration
|
||||
/// on turn and river and by `FLOP_RUNOUTS` sampled run-outs on the flop. Combos that touch the
|
||||
/// board or the hand get 0.
|
||||
fn equities(s: &S1, hand: u64, board: u64, rng: &mut Zufall) -> Vec<f32> {
|
||||
let deck = iso::deck();
|
||||
let tot = hand | board;
|
||||
let runouts: Vec<u64> = match board.count_ones() {
|
||||
5 => vec![0],
|
||||
4 => deck.iter().copied().filter(|c| c & tot == 0).collect(),
|
||||
_ => (0..FLOP_RUNOUTS)
|
||||
.map(|_| loop {
|
||||
let (a, b) = (deck[rng.below(52)], deck[rng.below(52)]);
|
||||
if a != b && (a | b) & tot == 0 {
|
||||
break a | b;
|
||||
}
|
||||
})
|
||||
.collect(),
|
||||
};
|
||||
let mut win = vec![0f32; s.alle.len()];
|
||||
let mut n = vec![0f32; s.alle.len()];
|
||||
for r in &runouts {
|
||||
let full = board | r;
|
||||
let me = fast7::score(full | hand);
|
||||
for (i, c) in s.alle.iter().enumerate() {
|
||||
if c & (full | hand) == 0 {
|
||||
let o = fast7::score(full | c);
|
||||
win[i] += if me > o { 1.0 } else if me == o { 0.5 } else { 0.0 };
|
||||
n[i] += 1.0;
|
||||
}
|
||||
}
|
||||
}
|
||||
win.iter().zip(&n).map(|(w, n)| if *n > 0.0 { w / n } else { 0.0 }).collect()
|
||||
}
|
||||
|
||||
/// Equity against a weighted range (0.5 if the range is empty).
|
||||
fn gegen(eq: &[f32], w: &[f64]) -> f64 {
|
||||
let (mut a, mut b) = (0.0, 0.0);
|
||||
for (e, x) in eq.iter().zip(w) {
|
||||
a += *e as f64 * x;
|
||||
b += x;
|
||||
}
|
||||
if b > 0.0 { a / b } else { 0.5 }
|
||||
}
|
||||
|
||||
/// The player LBR exploits: its action probabilities at an S1 decision node.
|
||||
pub trait Gegner: Sync {
|
||||
/// Row over the node's children for `hand` (combo index `combo`) on the street's `board`;
|
||||
/// `klasse` is the hand's blueprint class there.
|
||||
fn zeile(&self, s: &S1, k: usize, hand: u64, board: u64, klasse: usize) -> Vec<f64>;
|
||||
}
|
||||
|
||||
/// The blueprint's average strategy as the opponent.
|
||||
pub struct Blaupause<'a>(pub &'a Tabellen);
|
||||
|
||||
impl Gegner for Blaupause<'_> {
|
||||
fn zeile(&self, s: &S1, k: usize, _: u64, _: u64, klasse: usize) -> Vec<f64> {
|
||||
let n = match &s.baum.baum.knoten[k] {
|
||||
Knoten::Zug { kinder, .. } => kinder.len(),
|
||||
Knoten::Ende(_) => 0,
|
||||
};
|
||||
self.0.durchschnitt(k, klasse, n)
|
||||
}
|
||||
}
|
||||
|
||||
/// One hand with LBR in seat `l`; returns LBR's result in bb. Rows are cached per hand (the
|
||||
/// engine opponent is expensive to ask).
|
||||
///
|
||||
/// `stichprobe = Some(k)`: the opponent's range is not tracked over every combo but over a uniform
|
||||
/// random subset of its support (a fresh permutation per hand), extended at each LBR decision until
|
||||
/// `k` combos carry posterior weight (prior times the opponent's probability of every action taken).
|
||||
/// Fold probability and equity are then self-normalised estimates over that subset - consistent, with
|
||||
/// an error of order `1/sqrt(k)`. `None` tracks every combo (exact). The subset is drawn from its own
|
||||
/// stream (`mischen`), so exact and subsampled LBR play the same deal (paired comparison). Noise can
|
||||
/// only make LBR choose worse, so the subsampled value is still a lower bound on exploitability.
|
||||
fn hand<G: Gegner>(s: &S1, g: &G, l: usize, rng: &mut Zufall, mischen: &mut Zufall, stichprobe: Option<usize>) -> f64 {
|
||||
let mut cache: std::collections::HashMap<(usize, usize), Vec<f64>> = std::collections::HashMap::new();
|
||||
let mut zeile = |k: usize, i: usize, board: u64, klasse: usize| -> Vec<f64> {
|
||||
cache.entry((k, i)).or_insert_with(|| g.zeile(s, k, s.alle[i], board, klasse)).clone()
|
||||
};
|
||||
let o = 1 - l;
|
||||
let d = s.ziehen(rng);
|
||||
let baum = &s.baum;
|
||||
let w0: Vec<f64> = s.alle.iter().zip(&s.gewicht[o]).map(|(c, g)| if c & d.hand[l] == 0 { *g } else { 0.0 }).collect();
|
||||
let boards = [d.board[0] | d.board[1] | d.board[2], d.board[0] | d.board[1] | d.board[2] | d.board[3], d.board.iter().fold(0, |m, c| m | c)];
|
||||
let ehs_river = river_ehs(boards[2], &s.alle);
|
||||
// Subsampling: the support in random order; `m` of it is active, the rest weighs 0 until drawn.
|
||||
let mut reihe: Vec<usize> = Vec::new();
|
||||
let mut m = 0;
|
||||
let mut w = match stichprobe {
|
||||
None => w0.clone(),
|
||||
Some(_) => {
|
||||
reihe = (0..w0.len()).filter(|i| w0[*i] > 0.0).collect();
|
||||
for j in (1..reihe.len()).rev() {
|
||||
reihe.swap(j, mischen.below(j + 1));
|
||||
}
|
||||
vec![0.0; w0.len()]
|
||||
}
|
||||
};
|
||||
// The opponent's actions so far: (node, action, street).
|
||||
let mut verlauf: Vec<(usize, usize, usize)> = Vec::new();
|
||||
let mut strasse_da = usize::MAX;
|
||||
let mut klassen: Vec<usize> = Vec::new();
|
||||
let mut eq: Vec<f32> = Vec::new();
|
||||
let mut k = baum.baum.wurzel;
|
||||
loop {
|
||||
let (spieler, strasse, kinder) = match &baum.baum.knoten[k] {
|
||||
Knoten::Ende(e) => return s.wert(&d, *e)[l],
|
||||
Knoten::Zug { spieler, strasse, kinder } => (*spieler, *strasse, kinder),
|
||||
};
|
||||
let board = boards[strasse];
|
||||
if strasse != strasse_da {
|
||||
strasse_da = strasse;
|
||||
for (i, c) in s.alle.iter().enumerate() {
|
||||
if c & board != 0 {
|
||||
w[i] = 0.0;
|
||||
}
|
||||
}
|
||||
let lebt = |i: usize| if stichprobe.is_some() { w0[i] > 0.0 && s.alle[i] & board == 0 } else { w[i] > 0.0 };
|
||||
klassen = (0..s.alle.len()).map(|i| if lebt(i) { s.klasse_von(s.alle[i], board, strasse, &ehs_river) } else { 0 }).collect();
|
||||
eq = equities(s, d.hand[l], board, rng);
|
||||
}
|
||||
let n = kinder.len();
|
||||
if spieler == o {
|
||||
let sigma = zeile(k, super::abstraktion::combo_index(d.hand[o]), board, s.klasse_von(d.hand[o], board, strasse, &ehs_river));
|
||||
let mut x = rng.unit();
|
||||
let mut a = 0;
|
||||
while a + 1 < n && x >= sigma[a] {
|
||||
x -= sigma[a];
|
||||
a += 1;
|
||||
}
|
||||
for i in 0..w.len() {
|
||||
if w[i] > 0.0 {
|
||||
w[i] *= zeile(k, i, board, klassen[i])[a];
|
||||
}
|
||||
}
|
||||
verlauf.push((k, a, strasse));
|
||||
k = kinder[a];
|
||||
continue;
|
||||
}
|
||||
if let Some(ziel) = stichprobe {
|
||||
// Top up the subset until `ziel` combos are consistent with the line (or the support is spent).
|
||||
let mut lebend = w.iter().filter(|x| **x > 0.0).count();
|
||||
while lebend < ziel && m < reihe.len() {
|
||||
let i = reihe[m];
|
||||
m += 1;
|
||||
let c = s.alle[i];
|
||||
if c & board != 0 {
|
||||
continue;
|
||||
}
|
||||
let mut x = w0[i];
|
||||
for &(kv, av, sv) in &verlauf {
|
||||
if x <= 0.0 {
|
||||
break;
|
||||
}
|
||||
let kl = s.klasse_von(c, boards[sv], sv, &ehs_river);
|
||||
x *= zeile(kv, i, boards[sv], kl)[av];
|
||||
}
|
||||
w[i] = x;
|
||||
if x > 0.0 {
|
||||
lebend += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let c = baum.beitrag[k];
|
||||
let (pot, mine) = (c[0] + c[1], c[l]);
|
||||
let wp = gegen(&eq, &w);
|
||||
let mut best = (f64::NEG_INFINITY, kinder[0]);
|
||||
for &kind in kinder {
|
||||
let v = match baum.aktion[kind] {
|
||||
Some(Aktion::Fold) => -mine,
|
||||
Some(Aktion::Check) | Some(Aktion::Call) => {
|
||||
let after = baum.beitrag[kind][o].max(c[o]);
|
||||
wp * 2.0 * after - after
|
||||
}
|
||||
Some(Aktion::Bet(to)) | Some(Aktion::Raise(to)) => {
|
||||
// The opponent's fold probability per combo at the child node (fold = child 0).
|
||||
let (mut fold, mut all) = (0.0, 0.0);
|
||||
let mut call_w = vec![0f64; w.len()];
|
||||
if let Knoten::Zug { .. } = &baum.baum.knoten[kind] {
|
||||
for i in 0..w.len() {
|
||||
if w[i] > 0.0 {
|
||||
let pf = zeile(kind, i, board, klassen[i])[0];
|
||||
fold += w[i] * pf;
|
||||
all += w[i];
|
||||
call_w[i] = w[i] * (1.0 - pf);
|
||||
}
|
||||
}
|
||||
}
|
||||
let fp = if all > 0.0 { fold / all } else { 0.0 };
|
||||
fp * (pot - mine) + (1.0 - fp) * (gegen(&eq, &call_w) * 2.0 * to - to)
|
||||
}
|
||||
None => unreachable!("every child has an action"),
|
||||
};
|
||||
if v > best.0 {
|
||||
best = (v, kind);
|
||||
}
|
||||
}
|
||||
k = best.1;
|
||||
}
|
||||
}
|
||||
|
||||
/// LBR against the blueprint over `haende` hands (alternating seats) on `threads` threads.
|
||||
pub fn lbr(s: &S1, tab: &Tabellen, haende: usize, threads: usize, seed: u64) -> Ergebnis {
|
||||
lbr_gegen(s, &Blaupause(tab), haende, threads, seed)
|
||||
}
|
||||
|
||||
/// LBR against any opponent over `haende` hands (alternating seats) on `threads` threads.
|
||||
pub fn lbr_gegen<G: Gegner>(s: &S1, g: &G, haende: usize, threads: usize, seed: u64) -> Ergebnis {
|
||||
lbr_stichprobe(s, g, haende, threads, seed, None)
|
||||
}
|
||||
|
||||
/// `lbr_gegen` with the opponent range subsampled to `stichprobe` live combos per decision (see `hand`).
|
||||
pub fn lbr_stichprobe<G: Gegner>(s: &S1, g: &G, haende: usize, threads: usize, seed: u64, stichprobe: Option<usize>) -> Ergebnis {
|
||||
let mut t = [(0.0, 0.0, 0usize); 2];
|
||||
for (i, v) in lbr_werte(s, g, haende, threads, seed, stichprobe).into_iter().enumerate() {
|
||||
let l = i % 2;
|
||||
t[l].0 += v;
|
||||
t[l].1 += v * v;
|
||||
t[l].2 += 1;
|
||||
}
|
||||
let mean = |x: (f64, f64, usize)| x.0 / x.2.max(1) as f64;
|
||||
let var = |x: (f64, f64, usize)| (x.1 / x.2.max(1) as f64 - mean(x).powi(2)) / x.2.max(1) as f64;
|
||||
let m = 0.5 * (mean(t[0]) + mean(t[1]));
|
||||
let se = 0.5 * (var(t[0]) + var(t[1])).sqrt();
|
||||
Ergebnis { bb100: 100.0 * m, ci95: 196.0 * se, haende: t[0].2 + t[1].2, je_sitz: [100.0 * mean(t[0]), 100.0 * mean(t[1])] }
|
||||
}
|
||||
|
||||
/// The stream of hand `i`: hashed twice from the seed, so neighbouring hands do not share a stream.
|
||||
fn strom(seed: u64, i: u64, art: u64) -> Zufall {
|
||||
let a = Rng::seeded(seed ^ art.wrapping_mul(0xD1B5_4A32_D192_ED03)).next_u64().0;
|
||||
Zufall(Rng::seeded(Rng::seeded(a ^ i.wrapping_mul(0x9E37_79B9_7F4A_7C15)).next_u64().0))
|
||||
}
|
||||
|
||||
/// LBR's result in bb for hand `i` alone (seat `i % 2`): the same value `lbr_werte` gives for it, so a
|
||||
/// long run can be split into pieces and resumed.
|
||||
pub fn lbr_hand<G: Gegner>(s: &S1, g: &G, i: u64, seed: u64, stichprobe: Option<usize>) -> f64 {
|
||||
hand(s, g, (i % 2) as usize, &mut strom(seed, i, 0), &mut strom(seed, i, 1), stichprobe)
|
||||
}
|
||||
|
||||
/// LBR's result in bb for every hand `i` (seat `i % 2`), each hand on its own stream: the values do not
|
||||
/// depend on the thread count, and two calls with the same seed play the same deals (paired).
|
||||
pub fn lbr_werte<G: Gegner>(s: &S1, g: &G, haende: usize, threads: usize, seed: u64, stichprobe: Option<usize>) -> Vec<f64> {
|
||||
let threads = threads.max(1);
|
||||
let mut werte = vec![0.0; haende];
|
||||
std::thread::scope(|sc| {
|
||||
for (th, teil) in werte.chunks_mut(haende.div_ceil(threads).max(1)).enumerate() {
|
||||
let start = th * haende.div_ceil(threads).max(1);
|
||||
sc.spawn(move || {
|
||||
for (j, v) in teil.iter_mut().enumerate() {
|
||||
let i = (start + j) as u64;
|
||||
*v = lbr_hand(s, g, i, seed, stichprobe);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
werte
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::blueprint::abstraktion::river_cuts;
|
||||
use crate::blueprint::mccfr::rechnen;
|
||||
use crate::blueprint::s1::Abstraktion;
|
||||
|
||||
/// LBR crushes an untrained (uniform) blueprint and does less against a trained one.
|
||||
#[test]
|
||||
fn lbr_punishes_a_uniform_strategy_more_than_a_trained_one() {
|
||||
let s = S1::neu(Abstraktion { flop: None, turn: None, river: river_cuts(50, 1) });
|
||||
let mut tab = Tabellen::neu(&s);
|
||||
let roh = lbr(&s, &tab, 2000, 2, 11);
|
||||
eprintln!("uniform: {:+.1} ±{:.1} bb/100 (seats {:+.1} / {:+.1})", roh.bb100, roh.ci95, roh.je_sitz[0], roh.je_sitz[1]);
|
||||
assert!(roh.bb100 - roh.ci95 > 500.0, "uniform must be very exploitable");
|
||||
rechnen(&s, &mut tab, 20, 20_000, 2, 3);
|
||||
let trainiert = lbr(&s, &tab, 2000, 2, 11);
|
||||
eprintln!("trained: {:+.1} ±{:.1} bb/100 (seats {:+.1} / {:+.1})", trainiert.bb100, trainiert.ci95, trainiert.je_sitz[0], trainiert.je_sitz[1]);
|
||||
// Without tables flop and turn have one class (the strategy cannot see its cards there),
|
||||
// so the trained strategy stays very exploitable; it must still be clearly less so.
|
||||
assert!(trainiert.bb100 < roh.bb100, "{} vs {}", trainiert.bb100, roh.bb100);
|
||||
}
|
||||
|
||||
/// Mean and 95 % half-width of `b - a` per hand, in bb/100.
|
||||
fn gepaart(a: &[f64], b: &[f64]) -> (f64, f64) {
|
||||
let d: Vec<f64> = a.iter().zip(b).map(|(x, y)| y - x).collect();
|
||||
let n = d.len() as f64;
|
||||
let m = d.iter().sum::<f64>() / n;
|
||||
let v = d.iter().map(|x| (x - m).powi(2)).sum::<f64>() / (n - 1.0);
|
||||
(100.0 * m, 196.0 * (v / n).sqrt())
|
||||
}
|
||||
|
||||
/// The real blueprint (`$GRUNDSTRATEGIE`): how far subsampled LBR falls below the exact one, paired.
|
||||
/// `cargo test --release lbr::tests::bias_on_the_real_blueprint -- --ignored --nocapture`
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn bias_on_the_real_blueprint() {
|
||||
let (s, tab) = crate::blueprint::ranges::grundstrategie().expect("GRUNDSTRATEGIE");
|
||||
let g = Blaupause(tab);
|
||||
let n: usize = std::env::var("LBR_HAENDE").ok().and_then(|x| x.parse().ok()).unwrap_or(2000);
|
||||
let voll = lbr_werte(s, &g, n, 1, 31, None);
|
||||
let mean = |v: &[f64]| 100.0 * v.iter().sum::<f64>() / v.len() as f64;
|
||||
eprintln!("exact {:+.1} bb/100 over {n} hands", mean(&voll));
|
||||
for k in [24, 48, 96, 192] {
|
||||
let teil = lbr_werte(s, &g, n, 1, 31, Some(k));
|
||||
let (m, ci) = gepaart(&voll, &teil);
|
||||
eprintln!("k={k}: {:+.1} bb/100, minus exact {m:+.1} ±{ci:.1}", mean(&teil));
|
||||
}
|
||||
}
|
||||
|
||||
/// The subsampled range estimate lands where the exact one does (against a cheap opponent where
|
||||
/// both can run): same hands, same seed stream for the deals is not guaranteed, so compare within
|
||||
/// the joint interval.
|
||||
#[test]
|
||||
fn subsampled_lbr_agrees_with_the_exact_one() {
|
||||
let s = S1::neu(Abstraktion { flop: None, turn: None, river: river_cuts(50, 1) });
|
||||
let mut tab = Tabellen::neu(&s);
|
||||
rechnen(&s, &mut tab, 20, 20_000, 2, 3);
|
||||
let g = Blaupause(&tab);
|
||||
let voll = lbr_werte(&s, &g, 4000, 2, 21, None);
|
||||
let teil = lbr_werte(&s, &g, 4000, 2, 21, Some(48));
|
||||
let (m, ci) = gepaart(&voll, &teil);
|
||||
eprintln!("paired k=48 minus exact: {m:+.1} ±{ci:.1} bb/100");
|
||||
assert!(m.abs() < ci + 50.0, "{m} ±{ci}");
|
||||
}
|
||||
}
|
||||
//! Local Best Response (Lisý/Bowling 2017) against the blueprint: the gate of plan E2d.
|
||||
//!
|
||||
//! LBR plays real cards against the blueprint's average strategy. It tracks the opponent's range
|
||||
//! card by card (preflop chart weights times the blueprint's probability of every action taken,
|
||||
//! per combo through its class), and at each own decision picks the action with the best value
|
||||
//! under the assumption that afterwards both players only check or call:
|
||||
//!
|
||||
//! - fold: lose what is in; check / call: equity share of the pot after calling;
|
||||
//! - bet / raise: the opponent folds with the probability its range folds at that node, otherwise
|
||||
//! calls (a raise counts as a call), and LBR gets its equity against the calling part.
|
||||
//!
|
||||
//! The opponent then acts by its strategy for its real hand. LBR's average result over both seats is
|
||||
//! a lower bound on the blueprint's exploitability (bb per hand; the gate is < 0.3, i.e. 30 bb/100).
|
||||
|
||||
use super::abstraktion::river_ehs;
|
||||
use super::iso;
|
||||
use super::mccfr::{Knoten, Spiel, Tabellen, Zufall};
|
||||
use super::s1::{Aktion, S1};
|
||||
use crate::hand::fast7;
|
||||
use crate::rng::split_mix::Rng;
|
||||
|
||||
/// Flop equity: run-outs sampled per decision (turn and river enumerate exactly).
|
||||
const FLOP_RUNOUTS: usize = 64;
|
||||
|
||||
pub struct Ergebnis {
|
||||
/// LBR's mean result in bb/100, averaged over both seats, and its 95 % half-width.
|
||||
pub bb100: f64,
|
||||
pub ci95: f64,
|
||||
pub haende: usize,
|
||||
/// bb/100 as player 0 (out of position; S1: big blind) and as player 1 (in position; S1: button).
|
||||
pub je_sitz: [f64; 2],
|
||||
}
|
||||
|
||||
/// LBR's equity (win + tie/2) against every combo given the street's board, by exact enumeration
|
||||
/// on turn and river and by `FLOP_RUNOUTS` sampled run-outs on the flop. Combos that touch the
|
||||
/// board or the hand get 0.
|
||||
fn equities(s: &S1, hand: u64, board: u64, rng: &mut Zufall) -> Vec<f32> {
|
||||
let deck = iso::deck();
|
||||
let tot = hand | board;
|
||||
let runouts: Vec<u64> = match board.count_ones() {
|
||||
5 => vec![0],
|
||||
4 => deck.iter().copied().filter(|c| c & tot == 0).collect(),
|
||||
_ => (0..FLOP_RUNOUTS)
|
||||
.map(|_| loop {
|
||||
let (a, b) = (deck[rng.below(52)], deck[rng.below(52)]);
|
||||
if a != b && (a | b) & tot == 0 {
|
||||
break a | b;
|
||||
}
|
||||
})
|
||||
.collect(),
|
||||
};
|
||||
let mut win = vec![0f32; s.alle.len()];
|
||||
let mut n = vec![0f32; s.alle.len()];
|
||||
for r in &runouts {
|
||||
let full = board | r;
|
||||
let me = fast7::score(full | hand);
|
||||
for (i, c) in s.alle.iter().enumerate() {
|
||||
if c & (full | hand) == 0 {
|
||||
let o = fast7::score(full | c);
|
||||
win[i] += if me > o { 1.0 } else if me == o { 0.5 } else { 0.0 };
|
||||
n[i] += 1.0;
|
||||
}
|
||||
}
|
||||
}
|
||||
win.iter().zip(&n).map(|(w, n)| if *n > 0.0 { w / n } else { 0.0 }).collect()
|
||||
}
|
||||
|
||||
/// Equity against a weighted range (0.5 if the range is empty).
|
||||
fn gegen(eq: &[f32], w: &[f64]) -> f64 {
|
||||
let (mut a, mut b) = (0.0, 0.0);
|
||||
for (e, x) in eq.iter().zip(w) {
|
||||
a += *e as f64 * x;
|
||||
b += x;
|
||||
}
|
||||
if b > 0.0 { a / b } else { 0.5 }
|
||||
}
|
||||
|
||||
/// The player LBR exploits: its action probabilities at an S1 decision node.
|
||||
pub trait Gegner: Sync {
|
||||
/// Row over the node's children for `hand` (combo index `combo`) on the street's `board`;
|
||||
/// `klasse` is the hand's blueprint class there.
|
||||
fn zeile(&self, s: &S1, k: usize, hand: u64, board: u64, klasse: usize) -> Vec<f64>;
|
||||
}
|
||||
|
||||
/// The blueprint's average strategy as the opponent.
|
||||
pub struct Blaupause<'a>(pub &'a Tabellen);
|
||||
|
||||
impl Gegner for Blaupause<'_> {
|
||||
fn zeile(&self, s: &S1, k: usize, _: u64, _: u64, klasse: usize) -> Vec<f64> {
|
||||
let n = match &s.baum.baum.knoten[k] {
|
||||
Knoten::Zug { kinder, .. } => kinder.len(),
|
||||
Knoten::Ende(_) => 0,
|
||||
};
|
||||
self.0.durchschnitt(k, klasse, n)
|
||||
}
|
||||
}
|
||||
|
||||
/// One hand with LBR in seat `l`; returns LBR's result in bb. Rows are cached per hand (the
|
||||
/// engine opponent is expensive to ask).
|
||||
///
|
||||
/// `stichprobe = Some(k)`: the opponent's range is not tracked over every combo but over a uniform
|
||||
/// random subset of its support (a fresh permutation per hand), extended at each LBR decision until
|
||||
/// `k` combos carry posterior weight (prior times the opponent's probability of every action taken).
|
||||
/// Fold probability and equity are then self-normalised estimates over that subset - consistent, with
|
||||
/// an error of order `1/sqrt(k)`. `None` tracks every combo (exact). The subset is drawn from its own
|
||||
/// stream (`mischen`), so exact and subsampled LBR play the same deal (paired comparison). Noise can
|
||||
/// only make LBR choose worse, so the subsampled value is still a lower bound on exploitability.
|
||||
fn hand<G: Gegner>(s: &S1, g: &G, l: usize, rng: &mut Zufall, mischen: &mut Zufall, stichprobe: Option<usize>) -> f64 {
|
||||
let mut cache: std::collections::HashMap<(usize, usize), Vec<f64>> = std::collections::HashMap::new();
|
||||
let mut zeile = |k: usize, i: usize, board: u64, klasse: usize| -> Vec<f64> {
|
||||
cache.entry((k, i)).or_insert_with(|| g.zeile(s, k, s.alle[i], board, klasse)).clone()
|
||||
};
|
||||
let o = 1 - l;
|
||||
let d = s.ziehen(rng);
|
||||
let baum = &s.baum;
|
||||
let w0: Vec<f64> = s.alle.iter().zip(&s.gewicht[o]).map(|(c, g)| if c & d.hand[l] == 0 { *g } else { 0.0 }).collect();
|
||||
let boards = [d.board[0] | d.board[1] | d.board[2], d.board[0] | d.board[1] | d.board[2] | d.board[3], d.board.iter().fold(0, |m, c| m | c)];
|
||||
let ehs_river = river_ehs(boards[2], &s.alle);
|
||||
// Subsampling: the support in random order; `m` of it is active, the rest weighs 0 until drawn.
|
||||
let mut reihe: Vec<usize> = Vec::new();
|
||||
let mut m = 0;
|
||||
let mut w = match stichprobe {
|
||||
None => w0.clone(),
|
||||
Some(_) => {
|
||||
reihe = (0..w0.len()).filter(|i| w0[*i] > 0.0).collect();
|
||||
for j in (1..reihe.len()).rev() {
|
||||
reihe.swap(j, mischen.below(j + 1));
|
||||
}
|
||||
vec![0.0; w0.len()]
|
||||
}
|
||||
};
|
||||
// The opponent's actions so far: (node, action, street).
|
||||
let mut verlauf: Vec<(usize, usize, usize)> = Vec::new();
|
||||
let mut strasse_da = usize::MAX;
|
||||
let mut klassen: Vec<usize> = Vec::new();
|
||||
let mut eq: Vec<f32> = Vec::new();
|
||||
let mut k = baum.baum.wurzel;
|
||||
loop {
|
||||
let (spieler, strasse, kinder) = match &baum.baum.knoten[k] {
|
||||
Knoten::Ende(e) => return s.wert(&d, *e)[l],
|
||||
Knoten::Zug { spieler, strasse, kinder } => (*spieler, *strasse, kinder),
|
||||
};
|
||||
let board = boards[strasse];
|
||||
if strasse != strasse_da {
|
||||
strasse_da = strasse;
|
||||
for (i, c) in s.alle.iter().enumerate() {
|
||||
if c & board != 0 {
|
||||
w[i] = 0.0;
|
||||
}
|
||||
}
|
||||
let lebt = |i: usize| if stichprobe.is_some() { w0[i] > 0.0 && s.alle[i] & board == 0 } else { w[i] > 0.0 };
|
||||
klassen = (0..s.alle.len()).map(|i| if lebt(i) { s.klasse_von(s.alle[i], board, strasse, &ehs_river) } else { 0 }).collect();
|
||||
eq = equities(s, d.hand[l], board, rng);
|
||||
}
|
||||
let n = kinder.len();
|
||||
if spieler == o {
|
||||
let sigma = zeile(k, super::abstraktion::combo_index(d.hand[o]), board, s.klasse_von(d.hand[o], board, strasse, &ehs_river));
|
||||
let mut x = rng.unit();
|
||||
let mut a = 0;
|
||||
while a + 1 < n && x >= sigma[a] {
|
||||
x -= sigma[a];
|
||||
a += 1;
|
||||
}
|
||||
for i in 0..w.len() {
|
||||
if w[i] > 0.0 {
|
||||
w[i] *= zeile(k, i, board, klassen[i])[a];
|
||||
}
|
||||
}
|
||||
verlauf.push((k, a, strasse));
|
||||
k = kinder[a];
|
||||
continue;
|
||||
}
|
||||
if let Some(ziel) = stichprobe {
|
||||
// Top up the subset until `ziel` combos are consistent with the line (or the support is spent).
|
||||
let mut lebend = w.iter().filter(|x| **x > 0.0).count();
|
||||
while lebend < ziel && m < reihe.len() {
|
||||
let i = reihe[m];
|
||||
m += 1;
|
||||
let c = s.alle[i];
|
||||
if c & board != 0 {
|
||||
continue;
|
||||
}
|
||||
let mut x = w0[i];
|
||||
for &(kv, av, sv) in &verlauf {
|
||||
if x <= 0.0 {
|
||||
break;
|
||||
}
|
||||
let kl = s.klasse_von(c, boards[sv], sv, &ehs_river);
|
||||
x *= zeile(kv, i, boards[sv], kl)[av];
|
||||
}
|
||||
w[i] = x;
|
||||
if x > 0.0 {
|
||||
lebend += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let c = baum.beitrag[k];
|
||||
let (pot, mine) = (c[0] + c[1], c[l]);
|
||||
let wp = gegen(&eq, &w);
|
||||
let mut best = (f64::NEG_INFINITY, kinder[0]);
|
||||
for &kind in kinder {
|
||||
let v = match baum.aktion[kind] {
|
||||
Some(Aktion::Fold) => -mine,
|
||||
Some(Aktion::Check) | Some(Aktion::Call) => {
|
||||
let after = baum.beitrag[kind][o].max(c[o]);
|
||||
wp * 2.0 * after - after
|
||||
}
|
||||
Some(Aktion::Bet(to)) | Some(Aktion::Raise(to)) => {
|
||||
// The opponent's fold probability per combo at the child node (fold = child 0).
|
||||
let (mut fold, mut all) = (0.0, 0.0);
|
||||
let mut call_w = vec![0f64; w.len()];
|
||||
if let Knoten::Zug { .. } = &baum.baum.knoten[kind] {
|
||||
for i in 0..w.len() {
|
||||
if w[i] > 0.0 {
|
||||
let pf = zeile(kind, i, board, klassen[i])[0];
|
||||
fold += w[i] * pf;
|
||||
all += w[i];
|
||||
call_w[i] = w[i] * (1.0 - pf);
|
||||
}
|
||||
}
|
||||
}
|
||||
let fp = if all > 0.0 { fold / all } else { 0.0 };
|
||||
fp * (pot - mine) + (1.0 - fp) * (gegen(&eq, &call_w) * 2.0 * to - to)
|
||||
}
|
||||
None => unreachable!("every child has an action"),
|
||||
};
|
||||
if v > best.0 {
|
||||
best = (v, kind);
|
||||
}
|
||||
}
|
||||
k = best.1;
|
||||
}
|
||||
}
|
||||
|
||||
/// LBR against the blueprint over `haende` hands (alternating seats) on `threads` threads.
|
||||
pub fn lbr(s: &S1, tab: &Tabellen, haende: usize, threads: usize, seed: u64) -> Ergebnis {
|
||||
lbr_gegen(s, &Blaupause(tab), haende, threads, seed)
|
||||
}
|
||||
|
||||
/// LBR against any opponent over `haende` hands (alternating seats) on `threads` threads.
|
||||
pub fn lbr_gegen<G: Gegner>(s: &S1, g: &G, haende: usize, threads: usize, seed: u64) -> Ergebnis {
|
||||
lbr_stichprobe(s, g, haende, threads, seed, None)
|
||||
}
|
||||
|
||||
/// `lbr_gegen` with the opponent range subsampled to `stichprobe` live combos per decision (see `hand`).
|
||||
pub fn lbr_stichprobe<G: Gegner>(s: &S1, g: &G, haende: usize, threads: usize, seed: u64, stichprobe: Option<usize>) -> Ergebnis {
|
||||
let mut t = [(0.0, 0.0, 0usize); 2];
|
||||
for (i, v) in lbr_werte(s, g, haende, threads, seed, stichprobe).into_iter().enumerate() {
|
||||
let l = i % 2;
|
||||
t[l].0 += v;
|
||||
t[l].1 += v * v;
|
||||
t[l].2 += 1;
|
||||
}
|
||||
let mean = |x: (f64, f64, usize)| x.0 / x.2.max(1) as f64;
|
||||
let var = |x: (f64, f64, usize)| (x.1 / x.2.max(1) as f64 - mean(x).powi(2)) / x.2.max(1) as f64;
|
||||
let m = 0.5 * (mean(t[0]) + mean(t[1]));
|
||||
let se = 0.5 * (var(t[0]) + var(t[1])).sqrt();
|
||||
Ergebnis { bb100: 100.0 * m, ci95: 196.0 * se, haende: t[0].2 + t[1].2, je_sitz: [100.0 * mean(t[0]), 100.0 * mean(t[1])] }
|
||||
}
|
||||
|
||||
/// The stream of hand `i`: hashed twice from the seed, so neighbouring hands do not share a stream.
|
||||
fn strom(seed: u64, i: u64, art: u64) -> Zufall {
|
||||
let a = Rng::seeded(seed ^ art.wrapping_mul(0xD1B5_4A32_D192_ED03)).next_u64().0;
|
||||
Zufall(Rng::seeded(Rng::seeded(a ^ i.wrapping_mul(0x9E37_79B9_7F4A_7C15)).next_u64().0))
|
||||
}
|
||||
|
||||
/// LBR's result in bb for hand `i` alone (seat `i % 2`): the same value `lbr_werte` gives for it, so a
|
||||
/// long run can be split into pieces and resumed.
|
||||
pub fn lbr_hand<G: Gegner>(s: &S1, g: &G, i: u64, seed: u64, stichprobe: Option<usize>) -> f64 {
|
||||
hand(s, g, (i % 2) as usize, &mut strom(seed, i, 0), &mut strom(seed, i, 1), stichprobe)
|
||||
}
|
||||
|
||||
/// LBR's result in bb for every hand `i` (seat `i % 2`), each hand on its own stream: the values do not
|
||||
/// depend on the thread count, and two calls with the same seed play the same deals (paired).
|
||||
pub fn lbr_werte<G: Gegner>(s: &S1, g: &G, haende: usize, threads: usize, seed: u64, stichprobe: Option<usize>) -> Vec<f64> {
|
||||
let threads = threads.max(1);
|
||||
let mut werte = vec![0.0; haende];
|
||||
std::thread::scope(|sc| {
|
||||
for (th, teil) in werte.chunks_mut(haende.div_ceil(threads).max(1)).enumerate() {
|
||||
let start = th * haende.div_ceil(threads).max(1);
|
||||
sc.spawn(move || {
|
||||
for (j, v) in teil.iter_mut().enumerate() {
|
||||
let i = (start + j) as u64;
|
||||
*v = lbr_hand(s, g, i, seed, stichprobe);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
werte
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::blueprint::abstraktion::river_cuts;
|
||||
use crate::blueprint::mccfr::rechnen;
|
||||
use crate::blueprint::s1::Abstraktion;
|
||||
|
||||
/// LBR crushes an untrained (uniform) blueprint and does less against a trained one.
|
||||
#[test]
|
||||
fn lbr_punishes_a_uniform_strategy_more_than_a_trained_one() {
|
||||
let s = S1::neu(Abstraktion { flop: None, turn: None, river: river_cuts(50, 1) });
|
||||
let mut tab = Tabellen::neu(&s);
|
||||
let roh = lbr(&s, &tab, 2000, 2, 11);
|
||||
eprintln!("uniform: {:+.1} ±{:.1} bb/100 (seats {:+.1} / {:+.1})", roh.bb100, roh.ci95, roh.je_sitz[0], roh.je_sitz[1]);
|
||||
assert!(roh.bb100 - roh.ci95 > 500.0, "uniform must be very exploitable");
|
||||
rechnen(&s, &mut tab, 20, 20_000, 2, 3);
|
||||
let trainiert = lbr(&s, &tab, 2000, 2, 11);
|
||||
eprintln!("trained: {:+.1} ±{:.1} bb/100 (seats {:+.1} / {:+.1})", trainiert.bb100, trainiert.ci95, trainiert.je_sitz[0], trainiert.je_sitz[1]);
|
||||
// Without tables flop and turn have one class (the strategy cannot see its cards there),
|
||||
// so the trained strategy stays very exploitable; it must still be clearly less so.
|
||||
assert!(trainiert.bb100 < roh.bb100, "{} vs {}", trainiert.bb100, roh.bb100);
|
||||
}
|
||||
|
||||
/// Mean and 95 % half-width of `b - a` per hand, in bb/100.
|
||||
fn gepaart(a: &[f64], b: &[f64]) -> (f64, f64) {
|
||||
let d: Vec<f64> = a.iter().zip(b).map(|(x, y)| y - x).collect();
|
||||
let n = d.len() as f64;
|
||||
let m = d.iter().sum::<f64>() / n;
|
||||
let v = d.iter().map(|x| (x - m).powi(2)).sum::<f64>() / (n - 1.0);
|
||||
(100.0 * m, 196.0 * (v / n).sqrt())
|
||||
}
|
||||
|
||||
/// The real blueprint (`$GRUNDSTRATEGIE`): how far subsampled LBR falls below the exact one, paired.
|
||||
/// `cargo test --release lbr::tests::bias_on_the_real_blueprint -- --ignored --nocapture`
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn bias_on_the_real_blueprint() {
|
||||
let (s, tab) = crate::blueprint::ranges::grundstrategie().expect("GRUNDSTRATEGIE");
|
||||
let g = Blaupause(tab);
|
||||
let n: usize = std::env::var("LBR_HAENDE").ok().and_then(|x| x.parse().ok()).unwrap_or(2000);
|
||||
let voll = lbr_werte(s, &g, n, 1, 31, None);
|
||||
let mean = |v: &[f64]| 100.0 * v.iter().sum::<f64>() / v.len() as f64;
|
||||
eprintln!("exact {:+.1} bb/100 over {n} hands", mean(&voll));
|
||||
for k in [24, 48, 96, 192] {
|
||||
let teil = lbr_werte(s, &g, n, 1, 31, Some(k));
|
||||
let (m, ci) = gepaart(&voll, &teil);
|
||||
eprintln!("k={k}: {:+.1} bb/100, minus exact {m:+.1} ±{ci:.1}", mean(&teil));
|
||||
}
|
||||
}
|
||||
|
||||
/// The subsampled range estimate lands where the exact one does (against a cheap opponent where
|
||||
/// both can run): same hands, same seed stream for the deals is not guaranteed, so compare within
|
||||
/// the joint interval.
|
||||
#[test]
|
||||
fn subsampled_lbr_agrees_with_the_exact_one() {
|
||||
let s = S1::neu(Abstraktion { flop: None, turn: None, river: river_cuts(50, 1) });
|
||||
let mut tab = Tabellen::neu(&s);
|
||||
rechnen(&s, &mut tab, 20, 20_000, 2, 3);
|
||||
let g = Blaupause(&tab);
|
||||
let voll = lbr_werte(&s, &g, 4000, 2, 21, None);
|
||||
let teil = lbr_werte(&s, &g, 4000, 2, 21, Some(48));
|
||||
let (m, ci) = gepaart(&voll, &teil);
|
||||
eprintln!("paired k=48 minus exact: {m:+.1} ±{ci:.1} bb/100");
|
||||
assert!(m.abs() < ci + 50.0, "{m} ±{ci}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,3 +7,4 @@ pub mod lbr;
|
||||
pub mod mccfr;
|
||||
pub mod ranges;
|
||||
pub mod s1;
|
||||
pub mod szenario;
|
||||
|
||||
+188
-37
@@ -1,15 +1,21 @@
|
||||
//! Ranges of both players from the blueprint (plan E2e): the input the river game was missing.
|
||||
//!
|
||||
//! A real spot is mapped onto scenario S1 when it is one: button opened, small blind folded, big
|
||||
//! blind called, heads-up from the flop on, about 100 bb deep. The played postflop line is walked
|
||||
//! through the S1 tree, real sizes mapped onto the tree's sizes by the pseudo-harmonic rule
|
||||
//! A real spot is mapped onto a scenario of the family (`szenario::ALLE`) when it is one: S1 (button
|
||||
//! opened, small blind folded, big blind called), the cutoff or small blind opening against a
|
||||
//! calling big blind, or a 3-bet pot (button / cutoff opens, big blind 3-bets, opener calls); always
|
||||
//! heads-up from the flop on, about 100 bb deep. A 4-bet pot, a multiway pot, a limp or any other
|
||||
//! opener gives `None`. The played postflop line is walked
|
||||
//! through the scenario's tree, real sizes mapped onto the tree's sizes by the pseudo-harmonic rule
|
||||
//! (Ganzfried/Sandholm 2013, deterministic: the nearer side under that rule). Each player's range is
|
||||
//! the chart weight of every combo times the blueprint's probability of each action the player
|
||||
//! took, read through the combo's class on that street's board.
|
||||
|
||||
use super::abstraktion::river_ehs;
|
||||
use super::mccfr::{Knoten, Tabellen};
|
||||
use super::s1::{Aktion, S1, STACK};
|
||||
use super::s1::{Aktion, Grund};
|
||||
use super::szenario::{Szenario, ALLE};
|
||||
use crate::preflop::position::Position;
|
||||
use crate::preflop::seat_position::seat_position;
|
||||
use crate::card::Card;
|
||||
use crate::game::{SeenAction, Spot, Street};
|
||||
use crate::hand::fast7;
|
||||
@@ -18,9 +24,9 @@ use crate::hand::fast7;
|
||||
pub struct Ranges {
|
||||
pub hero: Vec<f64>,
|
||||
pub villain: Vec<f64>,
|
||||
/// S1 player of the hero (0 = big blind, 1 = button).
|
||||
/// Scenario player of the hero (0 = out of position, 1 = in position).
|
||||
pub hero_spieler: usize,
|
||||
/// The S1 node of the hero's decision.
|
||||
/// The scenario's node of the hero's decision.
|
||||
pub knoten: usize,
|
||||
}
|
||||
|
||||
@@ -43,55 +49,83 @@ pub(super) fn harmonisch(x: f64, kandidaten: &[(f64, usize)]) -> Option<usize> {
|
||||
k.last().map(|l| l.1)
|
||||
}
|
||||
|
||||
/// The S1 seats of a spot: (big blind seat, button seat), if the preflop was exactly S1.
|
||||
fn s1_sitze(spot: &Spot) -> Option<(u8, u8)> {
|
||||
/// The scenario a spot's preflop line is, with its seats `(out of position, in position)`: the
|
||||
/// first raise opens (from the button, cutoff or small blind), the big blind calls or 3-bets and the
|
||||
/// 3-bettor is called; everybody else folded. `None` for anything else (4-bet, multiway, limp, an
|
||||
/// open from another seat, sizes off the scenarios').
|
||||
pub fn erkennen(spot: &Spot) -> Option<(&'static Szenario, (u8, u8))> {
|
||||
if spot.variant != crate::variant::Variant::Nlhe || spot.seats < 3 {
|
||||
return None;
|
||||
}
|
||||
let button = spot.button_seat?;
|
||||
spot.button_seat?;
|
||||
let bb = spot.history.iter().find(|r| r.action == SeenAction::PostBigBlind)?.seat;
|
||||
let mut raised = false;
|
||||
let mut called = false;
|
||||
let mut opener: Option<(u8, f64)> = None;
|
||||
let mut dreibet: Option<f64> = None;
|
||||
let (mut called, mut opener_called) = (false, false);
|
||||
for r in spot.history.iter().filter(|r| r.street == Street::Preflop) {
|
||||
match r.action {
|
||||
SeenAction::PostSmallBlind | SeenAction::PostBigBlind | SeenAction::PostAnte => {}
|
||||
SeenAction::Fold if r.seat != button && r.seat != bb => {}
|
||||
SeenAction::Raise | SeenAction::Bet if r.seat == button && !raised => {
|
||||
let to = r.amount? / spot.big_blind;
|
||||
if !(2.0..=3.0).contains(&to) {
|
||||
return None;
|
||||
}
|
||||
raised = true;
|
||||
SeenAction::Fold if r.seat != bb && Some(r.seat) != opener.map(|o| o.0) => {}
|
||||
SeenAction::Raise | SeenAction::Bet if opener.is_none() && r.seat != bb => opener = Some((r.seat, r.amount? / spot.big_blind)),
|
||||
SeenAction::Raise | SeenAction::Bet if opener.is_some() && r.seat == bb && dreibet.is_none() && !called => {
|
||||
dreibet = Some(r.amount? / spot.big_blind)
|
||||
}
|
||||
SeenAction::Call if r.seat == bb && raised && !called => called = true,
|
||||
SeenAction::Call if opener.is_some() && r.seat == bb && dreibet.is_none() && !called => called = true,
|
||||
SeenAction::Call if dreibet.is_some() && Some(r.seat) == opener.map(|o| o.0) && !opener_called => opener_called = true,
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
(raised && called).then_some((bb, button))
|
||||
let (opener_seat, to) = opener?;
|
||||
if !(called || (dreibet.is_some() && opener_called)) {
|
||||
return None;
|
||||
}
|
||||
let chart_seat = match seat_position(spot, opener_seat) {
|
||||
Position::Button => crate::cfr::seat::Seat::Button,
|
||||
Position::Cutoff => crate::cfr::seat::Seat::Cutoff,
|
||||
Position::SmallBlind => crate::cfr::seat::Seat::SmallBlind,
|
||||
_ => return None,
|
||||
};
|
||||
let in_window = |x: f64, (lo, hi): (f64, f64)| x >= lo && x <= hi;
|
||||
let sz = ALLE.iter().find(|z| {
|
||||
z.eroeffner == chart_seat
|
||||
&& z.dreibet.is_some() == dreibet.is_some()
|
||||
&& in_window(to, z.erkennung_eroeffnung)
|
||||
&& dreibet.is_none_or(|d| in_window(d, z.erkennung_dreibet))
|
||||
})?;
|
||||
let sitze = if sz.eroeffner_spieler() == 0 { (opener_seat, bb) } else { (bb, opener_seat) };
|
||||
Some((sz, sitze))
|
||||
}
|
||||
|
||||
fn karten_maske(cards: &[Card]) -> u64 {
|
||||
fast7::mask(cards)
|
||||
}
|
||||
|
||||
static GRUND: std::sync::OnceLock<Option<(S1, Tabellen)>> = std::sync::OnceLock::new();
|
||||
static GRUND: [std::sync::OnceLock<Option<(Grund, Tabellen)>>; ALLE.len()] =
|
||||
[const { std::sync::OnceLock::new() }; ALLE.len()];
|
||||
|
||||
/// The S1 blueprint, loaded once from `$GRUNDSTRATEGIE/abstraktion/` and
|
||||
/// `$GRUNDSTRATEGIE/grundstrategie/s1.ckpt`; `None` without the variable or the files.
|
||||
pub fn grundstrategie() -> Option<&'static (S1, Tabellen)> {
|
||||
GRUND
|
||||
/// The blueprint of scenario `sz`, loaded once from `$GRUNDSTRATEGIE/abstraktion/` and
|
||||
/// `$GRUNDSTRATEGIE/grundstrategie/<id>.ckpt`; `None` without the variable or the files.
|
||||
pub fn grundstrategie_fuer(sz: &Szenario) -> Option<&'static (Grund, Tabellen)> {
|
||||
GRUND[sz.index()]
|
||||
.get_or_init(|| {
|
||||
let dir = std::path::PathBuf::from(std::env::var_os("GRUNDSTRATEGIE")?);
|
||||
let s = S1::neu(super::s1::Abstraktion::laden(&dir.join("abstraktion")).ok()?);
|
||||
let s = Grund::mit(ALLE.iter().find(|z| z.id == sz.id)?, super::s1::Abstraktion::laden(&dir.join("abstraktion")).ok()?);
|
||||
let mut tab = Tabellen::neu(&s);
|
||||
tab.datei_lesen(&dir.join("grundstrategie").join("s1.ckpt")).then_some((s, tab))
|
||||
tab.datei_lesen(&dir.join("grundstrategie").join(format!("{}.ckpt", sz.id))).then_some((s, tab))
|
||||
})
|
||||
.as_ref()
|
||||
}
|
||||
|
||||
/// Weighted combo lists (hero, villain) for the river game from the blueprint, if the spot is S1.
|
||||
/// The S1 blueprint (`grundstrategie_fuer` of S1).
|
||||
pub fn grundstrategie() -> Option<&'static (Grund, Tabellen)> {
|
||||
grundstrategie_fuer(Szenario::s1())
|
||||
}
|
||||
|
||||
/// Weighted combo lists (hero, villain) for the river game from the blueprint, if the spot is one
|
||||
/// of the scenarios and its blueprint is loaded.
|
||||
pub fn gewichtete_listen(spot: &Spot) -> Option<(Vec<(Vec<Card>, f64)>, Vec<(Vec<Card>, f64)>)> {
|
||||
let (s, tab) = grundstrategie()?;
|
||||
let (sz, _) = erkennen(spot)?;
|
||||
let (s, tab) = grundstrategie_fuer(sz)?;
|
||||
let r = ranges(s, tab, spot)?;
|
||||
let deck = 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")?;
|
||||
let karte = |bit: u64| deck.iter().copied().find(|c| fast7::bit(*c) == bit);
|
||||
@@ -107,11 +141,16 @@ pub fn gewichtete_listen(spot: &Spot) -> Option<(Vec<(Vec<Card>, f64)>, Vec<(Vec
|
||||
(!h.is_empty() && !v.is_empty()).then_some((h, v))
|
||||
}
|
||||
|
||||
/// Ranges for the hero's current decision, or `None` when the spot is not S1 or the line leaves it.
|
||||
pub fn ranges(s: &S1, tab: &Tabellen, spot: &Spot) -> Option<Ranges> {
|
||||
let (bb, btn) = s1_sitze(spot)?;
|
||||
let hero_spieler = if spot.hero_seat == bb { 0 } else if spot.hero_seat == btn { 1 } else { return None };
|
||||
let villain_seat = if hero_spieler == 0 { btn } else { bb };
|
||||
/// Ranges for the hero's current decision, or `None` when the spot is not scenario `s` or the line
|
||||
/// leaves its tree.
|
||||
pub fn ranges(s: &Grund, tab: &Tabellen, spot: &Spot) -> Option<Ranges> {
|
||||
let (sz, (oop, ip)) = erkennen(spot)?;
|
||||
if sz.id != s.sz.id {
|
||||
return None;
|
||||
}
|
||||
let stapel = sz.stapel;
|
||||
let hero_spieler = if spot.hero_seat == oop { 0 } else if spot.hero_seat == ip { 1 } else { return None };
|
||||
let villain_seat = if hero_spieler == 0 { ip } else { oop };
|
||||
let villain = spot.villains.iter().find(|v| v.seat == villain_seat && !v.folded)?;
|
||||
if spot.live_villains().count() != 1 || spot.board.len() < 3 {
|
||||
return None;
|
||||
@@ -153,7 +192,7 @@ pub fn ranges(s: &S1, tab: &Tabellen, spot: &Spot) -> Option<Ranges> {
|
||||
}
|
||||
let mut c_real = [0.0f64; 2];
|
||||
for r in spot.history.iter().filter(|r| r.street == *st) {
|
||||
let p = if r.seat == bb { 0 } else if r.seat == btn { 1 } else { continue };
|
||||
let p = if r.seat == oop { 0 } else if r.seat == ip { 1 } else { continue };
|
||||
let Knoten::Zug { spieler, strasse, kinder } = &s.baum.baum.knoten[k] else { return None };
|
||||
if *spieler != p || *strasse != si {
|
||||
return None;
|
||||
@@ -174,7 +213,7 @@ pub fn ranges(s: &S1, tab: &Tabellen, spot: &Spot) -> Option<Ranges> {
|
||||
Some(Aktion::Bet(t)) | Some(Aktion::Raise(t)) => Some(((t - c_s1[p]) / pot_s1, *c, t)),
|
||||
_ => None,
|
||||
})
|
||||
.map(|(f, c, t)| if all_in && t >= STACK { (f64::INFINITY, c) } else { (f, c) })
|
||||
.map(|(f, c, t)| if all_in && t >= stapel { (f64::INFINITY, c) } else { (f, c) })
|
||||
.collect();
|
||||
if kand.is_empty() {
|
||||
// Call-equivalent all-in against a bet the tree cannot raise any more.
|
||||
@@ -225,7 +264,7 @@ pub fn ranges(s: &S1, tab: &Tabellen, spot: &Spot) -> Option<Ranges> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::blueprint::abstraktion::river_cuts;
|
||||
use crate::blueprint::s1::Abstraktion;
|
||||
use crate::blueprint::s1::{Abstraktion, S1};
|
||||
use crate::game::{ActionKind, ActionRecord, Villain};
|
||||
use crate::variant::Variant;
|
||||
|
||||
@@ -311,6 +350,118 @@ mod tests {
|
||||
assert!(ranges(&s, &tab, &s1_river(true)).is_none(), "a 3-bet pot is not S1");
|
||||
}
|
||||
|
||||
/// 6-max seats: button 4, small blind 5, big blind 0, UTG 1, MP 2, cutoff 3.
|
||||
fn pre(opener: u8, to: f64, rest: &[(u8, SeenAction, f64)]) -> Vec<ActionRecord> {
|
||||
use SeenAction::*;
|
||||
let mut h = vec![rec(Street::Preflop, 5, PostSmallBlind, Some(0.5)), rec(Street::Preflop, 0, PostBigBlind, Some(1.0))];
|
||||
for seat in 1..opener.min(6) {
|
||||
h.push(rec(Street::Preflop, seat, Fold, None));
|
||||
}
|
||||
h.push(rec(Street::Preflop, opener, Raise, Some(to)));
|
||||
for (seat, a, amount) in rest {
|
||||
h.push(rec(Street::Preflop, *seat, *a, (*a != Fold).then_some(*amount)));
|
||||
}
|
||||
h
|
||||
}
|
||||
|
||||
/// River spot of a preflop line: flop check / bet / call, turn check-check, river bet of the
|
||||
/// out-of-position player, the hero (in position) decides.
|
||||
fn mit_flop(preflop: Vec<ActionRecord>, each: f64, oop: u8, ip: u8) -> Spot {
|
||||
use SeenAction::*;
|
||||
use Street::*;
|
||||
let (b, r) = (each * 0.7, each * 1.1);
|
||||
let mut h = preflop;
|
||||
h.extend([
|
||||
rec(Flop, oop, Check, None),
|
||||
rec(Flop, ip, Bet, Some(b)),
|
||||
rec(Flop, oop, Call, Some(b)),
|
||||
rec(Turn, oop, Check, None),
|
||||
rec(Turn, ip, Check, None),
|
||||
rec(River, oop, Bet, Some(r)),
|
||||
]);
|
||||
let mut spot = s1_river(false);
|
||||
spot.hero_seat = ip;
|
||||
spot.pot = 2.0 * each + 2.0 * b + r;
|
||||
spot.to_call = r;
|
||||
spot.hero_stack = 100.0 - each - b;
|
||||
spot.villains = vec![Villain { seat: oop, stack: 100.0 - each - b - r, folded: false, profile: None }];
|
||||
spot.history = h;
|
||||
spot
|
||||
}
|
||||
|
||||
use SeenAction::{Call as K, Raise as R};
|
||||
|
||||
#[test]
|
||||
fn every_scenario_is_recognised_and_gives_ranges() {
|
||||
let fold = SeenAction::Fold;
|
||||
// (scenario, preflop, contribution each, oop seat, ip seat)
|
||||
let faelle: Vec<(&str, Vec<ActionRecord>, f64, u8, u8)> = vec![
|
||||
("s1", pre(4, 2.5, &[(5, fold, 0.0), (0, K, 2.5)]), 2.5, 0, 4),
|
||||
("co", pre(3, 2.5, &[(4, fold, 0.0), (5, fold, 0.0), (0, K, 2.5)]), 2.5, 0, 3),
|
||||
("sb", pre(5, 3.0, &[(0, K, 3.0)]), 3.0, 5, 0),
|
||||
("btn3", pre(4, 2.5, &[(5, fold, 0.0), (0, R, 9.0), (4, K, 9.0)]), 9.0, 0, 4),
|
||||
("co3", pre(3, 2.5, &[(4, fold, 0.0), (5, fold, 0.0), (0, R, 9.0), (3, K, 9.0)]), 9.0, 0, 3),
|
||||
];
|
||||
for (id, preflop, each, oop, ip) in faelle {
|
||||
let spot = mit_flop(preflop, each, oop, ip);
|
||||
let (sz, sitze) = erkennen(&spot).unwrap_or_else(|| panic!("{id} not recognised"));
|
||||
assert_eq!((sz.id, sitze), (id, (oop, ip)));
|
||||
let s = Grund::mit(sz, Abstraktion { flop: None, turn: None, river: river_cuts(50, 1) });
|
||||
let tab = Tabellen::neu(&s);
|
||||
let r = ranges(&s, &tab, &spot).unwrap_or_else(|| panic!("{id}: no ranges"));
|
||||
assert_eq!(r.hero_spieler, 1);
|
||||
let Knoten::Zug { spieler, strasse, .. } = &s.baum.baum.knoten[r.knoten] else { panic!() };
|
||||
assert_eq!((*spieler, *strasse), (1, 2), "{id}");
|
||||
assert!(r.villain.iter().any(|x| *x > 0.0) && r.hero.iter().any(|x| *x > 0.0), "{id}");
|
||||
// Every other scenario's blueprint refuses the spot.
|
||||
for other in ALLE.iter().filter(|z| z.id != id) {
|
||||
let o = Grund::mit(other, Abstraktion { flop: None, turn: None, river: river_cuts(50, 1) });
|
||||
assert!(ranges(&o, &Tabellen::neu(&o), &spot).is_none(), "{id} must not map onto {}", other.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_outside_the_scenarios_give_none() {
|
||||
let fold = SeenAction::Fold;
|
||||
let nein: Vec<(&str, Vec<ActionRecord>, f64)> = vec![
|
||||
("4-bet pot", pre(4, 2.5, &[(5, fold, 0.0), (0, R, 9.0), (4, R, 22.0), (0, K, 22.0)]), 22.0),
|
||||
("cold call (multiway)", pre(3, 2.5, &[(4, K, 2.5), (5, fold, 0.0), (0, K, 2.5)]), 2.5),
|
||||
("small blind calls too", pre(4, 2.5, &[(5, K, 2.5), (0, K, 2.5)]), 2.5),
|
||||
("3-bet by the small blind", pre(4, 2.5, &[(5, R, 11.0), (0, fold, 0.0), (4, K, 11.0)]), 11.0),
|
||||
("under the gun opens", pre(1, 2.5, &[(0, K, 2.5)]), 2.5),
|
||||
("middle position opens", pre(2, 2.5, &[(0, K, 2.5)]), 2.5),
|
||||
("open far too big", pre(4, 8.0, &[(5, fold, 0.0), (0, K, 8.0)]), 8.0),
|
||||
("3-bet not called", pre(4, 2.5, &[(5, fold, 0.0), (0, R, 9.0), (4, fold, 0.0)]), 9.0),
|
||||
];
|
||||
for (name, preflop, each) in nein {
|
||||
let spot = mit_flop(preflop, each, 0, 4);
|
||||
assert!(erkennen(&spot).is_none(), "{name} must not be a scenario");
|
||||
}
|
||||
}
|
||||
|
||||
/// The scenarios' ranges are the engine charts: the defender's call range against the opener
|
||||
/// is wider than the 3-bet range, a cutoff opens less than the button, and the small blind
|
||||
/// opens a range of its own.
|
||||
#[test]
|
||||
fn scenario_ranges_follow_the_charts() {
|
||||
let mass = |id: &str| {
|
||||
let sz = Szenario::finde(id).unwrap();
|
||||
let s = Grund::mit(sz, Abstraktion { flop: None, turn: None, river: river_cuts(50, 1) });
|
||||
let a = |p: usize| s.gewicht[p].iter().sum::<f64>() / 1326.0;
|
||||
let w = (a(0), a(1));
|
||||
eprintln!("{id}: OOP {:.3}, IP {:.3}", w.0, w.1);
|
||||
w
|
||||
};
|
||||
let (s1, sb, co, b3, c3) = (mass("s1"), mass("sb"), mass("co"), mass("btn3"), mass("co3"));
|
||||
assert!(co.1 < s1.1, "cutoff open {} vs button open {}", co.1, s1.1);
|
||||
assert!(s1.1 > 0.3 && sb.1 > 0.1 && co.0 > 0.1);
|
||||
for (name, three, call) in [("btn3", b3, s1), ("co3", c3, co)] {
|
||||
assert!(three.0 > 0.0 && three.0 < call.0, "{name}: 3-bet range {} must be narrower than the call range {}", three.0, call.0);
|
||||
assert!(three.1 > 0.0 && three.1 < call.1, "{name}: the opener's call-the-3-bet range {} is narrower than its open range {}", three.1, call.1);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pseudo_harmonic_mapping() {
|
||||
let k = [(0.33, 1), (0.75, 2), (f64::INFINITY, 3)];
|
||||
|
||||
+174
-21
@@ -12,18 +12,16 @@
|
||||
use super::abstraktion::{combo_index, combos, river_class, river_ehs, CLASSES};
|
||||
use super::iso::{self, Street};
|
||||
use super::mccfr::{Baum, Knoten, Spiel, Zufall};
|
||||
use super::szenario::Szenario;
|
||||
use crate::card::Card;
|
||||
use crate::cfr::hand_class::class_of;
|
||||
use crate::cfr::seat::Seat;
|
||||
use crate::hand::fast7;
|
||||
use crate::preflop::generated_lookup::{open_frequency, vs_open};
|
||||
use crate::preflop::generated_lookup::{open_frequency, vs_open, vs_three_bet};
|
||||
use crate::variant::Variant;
|
||||
|
||||
pub const STACK: f64 = 100.0;
|
||||
pub const OPEN: f64 = 2.5;
|
||||
pub const MAX_EINSAETZE: usize = 3;
|
||||
const BETS: [&[f64]; 3] = [&[0.33, 0.75], &[0.5, 1.0], &[0.33, 0.75, 1.25]];
|
||||
const RAISE: f64 = 3.0;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum Aktion {
|
||||
@@ -54,6 +52,7 @@ pub struct Einsatzbaum {
|
||||
}
|
||||
|
||||
struct Bauer {
|
||||
sz: Szenario,
|
||||
knoten: Vec<Knoten>,
|
||||
enden: Vec<Ende>,
|
||||
aktion: Vec<Option<Aktion>>,
|
||||
@@ -61,6 +60,14 @@ struct Bauer {
|
||||
}
|
||||
|
||||
impl Bauer {
|
||||
/// A bet / raise to `to` that leaves (almost) nothing behind is the all-in (`Szenario::allin_ab`).
|
||||
fn rund(&self, to: f64) -> f64 {
|
||||
match self.sz.allin_ab {
|
||||
Some(f) if to >= f * self.sz.stapel => self.sz.stapel,
|
||||
_ => to,
|
||||
}
|
||||
}
|
||||
|
||||
fn ende(&mut self, e: Ende, a: Aktion) -> usize {
|
||||
self.enden.push(e);
|
||||
self.knoten.push(Knoten::Ende(self.enden.len() - 1));
|
||||
@@ -74,7 +81,7 @@ impl Bauer {
|
||||
|
||||
/// Street `s` is over with equal contributions `c`.
|
||||
fn strasse_zu(&mut self, s: usize, c: f64, a: Aktion) -> usize {
|
||||
if s == 2 || c >= STACK {
|
||||
if s == 2 || c >= self.sz.stapel {
|
||||
self.ende(Ende::Showdown { c }, a)
|
||||
} else {
|
||||
self.zug(s + 1, [c, c], 0, 0, false, Some(a))
|
||||
@@ -94,8 +101,9 @@ impl Bauer {
|
||||
let mut kinder = Vec::new();
|
||||
if facing <= 0.0 {
|
||||
kinder.push(if geprueft || p == 1 { self.strasse_zu(s, c[p], Aktion::Check) } else { self.zug(s, c, o, 0, true, Some(Aktion::Check)) });
|
||||
let mut sizes: Vec<f64> = BETS[s].iter().map(|f| (c[p] + f * pot).min(STACK)).collect();
|
||||
sizes.push(STACK);
|
||||
let stapel = self.sz.stapel;
|
||||
let mut sizes: Vec<f64> = self.sz.einsaetze[s].iter().map(|f| self.rund((c[p] + f * pot).min(stapel))).collect();
|
||||
sizes.push(stapel);
|
||||
sizes.dedup_by(|x, y| (*x - *y).abs() < 1e-9);
|
||||
for to in sizes {
|
||||
if to > c[p] {
|
||||
@@ -107,8 +115,9 @@ impl Bauer {
|
||||
} else {
|
||||
kinder.push(self.ende(Ende::Fold { verlierer: p, c }, Aktion::Fold));
|
||||
kinder.push(self.strasse_zu(s, c[o], Aktion::Call));
|
||||
if einsaetze < MAX_EINSAETZE && c[o] < STACK {
|
||||
let mut sizes = vec![(c[p] + RAISE * facing).min(STACK), STACK];
|
||||
if einsaetze < self.sz.max_einsaetze && c[o] < self.sz.stapel {
|
||||
let stapel = self.sz.stapel;
|
||||
let mut sizes = vec![self.rund((c[p] + self.sz.raise * facing).min(stapel)), stapel];
|
||||
sizes.dedup_by(|x, y| (*x - *y).abs() < 1e-9);
|
||||
for to in sizes {
|
||||
let mut n = c;
|
||||
@@ -126,8 +135,13 @@ impl Bauer {
|
||||
|
||||
impl Einsatzbaum {
|
||||
pub fn s1() -> Einsatzbaum {
|
||||
let mut b = Bauer { knoten: Vec::new(), enden: Vec::new(), aktion: Vec::new(), beitrag: Vec::new() };
|
||||
let wurzel = b.zug(0, [OPEN, OPEN], 0, 0, false, None);
|
||||
Einsatzbaum::neu(Szenario::s1())
|
||||
}
|
||||
|
||||
/// The betting tree of a scenario: player 0 (out of position) acts first on every street.
|
||||
pub fn neu(sz: &Szenario) -> Einsatzbaum {
|
||||
let mut b = Bauer { sz: *sz, knoten: Vec::new(), enden: Vec::new(), aktion: Vec::new(), beitrag: Vec::new() };
|
||||
let wurzel = b.zug(0, [sz.beitrag(), sz.beitrag()], 0, 0, false, None);
|
||||
let mut eltern = vec![usize::MAX; b.knoten.len()];
|
||||
for (i, k) in b.knoten.iter().enumerate() {
|
||||
if let Knoten::Zug { kinder, .. } = k {
|
||||
@@ -168,11 +182,16 @@ pub struct Deal {
|
||||
pub sieger: i8,
|
||||
}
|
||||
|
||||
pub struct S1 {
|
||||
/// The game of one scenario (`Szenario`); `S1` is its original name and the S1 scenario.
|
||||
pub type S1 = Grund;
|
||||
|
||||
pub struct Grund {
|
||||
pub sz: &'static Szenario,
|
||||
pub baum: Einsatzbaum,
|
||||
pub abstraktion: Abstraktion,
|
||||
pub alle: Vec<u64>,
|
||||
/// Preflop weight per combo: [big blind call, button open].
|
||||
/// Preflop weight per combo of each player (0 = out of position, 1 = in position); S1: [big
|
||||
/// blind call, button open].
|
||||
pub gewicht: [Vec<f64>; 2],
|
||||
}
|
||||
|
||||
@@ -183,13 +202,35 @@ fn gewichte(alle: &[u64], f: impl Fn(Card, Card) -> f64) -> Vec<f64> {
|
||||
alle.iter().map(|h| f(karte(h & h.wrapping_neg()), karte(h & (h - 1)))).collect()
|
||||
}
|
||||
|
||||
impl S1 {
|
||||
pub fn neu(abstraktion: Abstraktion) -> S1 {
|
||||
impl Grund {
|
||||
pub fn neu(abstraktion: Abstraktion) -> Grund {
|
||||
Grund::mit(Szenario::s1(), abstraktion)
|
||||
}
|
||||
|
||||
/// The game of scenario `sz` with ranges from the engine's preflop charts at its stack:
|
||||
/// the opener's open frequency (times its call frequency against the 3-bet in a 3-bet pot) and
|
||||
/// the big blind's call (3-bet) frequency against that open.
|
||||
pub fn mit(sz: &'static Szenario, abstraktion: Abstraktion) -> Grund {
|
||||
let alle = combos();
|
||||
let depth = STACK;
|
||||
let bb = gewichte(&alle, |a, b| vs_open(Variant::Nlhe, Seat::Button, depth, class_of(a, b).unwrap()).map_or(0.0, |f| f.call));
|
||||
let btn = gewichte(&alle, |a, b| open_frequency(Variant::Nlhe, Seat::Button, depth, class_of(a, b).unwrap()).map_or(0.0, |f| f.raise));
|
||||
S1 { baum: Einsatzbaum::s1(), abstraktion, alle, gewicht: [bb, btn] }
|
||||
let (depth, opener) = (sz.stapel, sz.eroeffner);
|
||||
let klasse = |a: Card, b: Card| class_of(a, b).unwrap();
|
||||
let (eroeffner, verteidiger) = match sz.dreibet {
|
||||
None => (
|
||||
gewichte(&alle, |a, b| open_frequency(Variant::Nlhe, opener, depth, klasse(a, b)).map_or(0.0, |f| f.raise)),
|
||||
gewichte(&alle, |a, b| vs_open(Variant::Nlhe, opener, depth, klasse(a, b)).map_or(0.0, |f| f.call)),
|
||||
),
|
||||
Some(_) => (
|
||||
gewichte(&alle, |a, b| {
|
||||
let o = open_frequency(Variant::Nlhe, opener, depth, klasse(a, b)).map_or(0.0, |f| f.raise);
|
||||
o * vs_three_bet(Variant::Nlhe, opener, depth, klasse(a, b)).map_or(0.0, |f| f.call)
|
||||
}),
|
||||
gewichte(&alle, |a, b| vs_open(Variant::Nlhe, opener, depth, klasse(a, b)).map_or(0.0, |f| f.raise)),
|
||||
),
|
||||
};
|
||||
let mut gewicht = [Vec::new(), Vec::new()];
|
||||
gewicht[sz.eroeffner_spieler()] = eroeffner;
|
||||
gewicht[sz.verteidiger_spieler()] = verteidiger;
|
||||
Grund { sz, baum: Einsatzbaum::neu(sz), abstraktion, alle, gewicht }
|
||||
}
|
||||
|
||||
fn hand_ziehen(&self, p: usize, tot: u64, rng: &mut Zufall) -> u64 {
|
||||
@@ -203,7 +244,7 @@ impl S1 {
|
||||
}
|
||||
}
|
||||
|
||||
impl S1 {
|
||||
impl Grund {
|
||||
/// Class of `hand` on `strasse` with the street's board `board` (3, 4 or 5 cards); on the river
|
||||
/// `ehs` must be `river_ehs(board)`.
|
||||
pub fn klasse_von(&self, hand: u64, board: u64, strasse: usize, ehs: &[f32]) -> usize {
|
||||
@@ -215,7 +256,7 @@ impl S1 {
|
||||
}
|
||||
}
|
||||
|
||||
impl Spiel for S1 {
|
||||
impl Spiel for Grund {
|
||||
type Deal = Deal;
|
||||
|
||||
fn baum(&self) -> &Baum {
|
||||
@@ -320,6 +361,118 @@ mod tests {
|
||||
assert!(bb > 0.15 && bb < 0.70, "big blind call {bb}");
|
||||
}
|
||||
|
||||
/// S1 through the scenario family is the S1 of old: same tree shape, same entries (the
|
||||
/// checkpoint `s1.ckpt` has `(regret + sum) = 2 * 8 * entries` bytes), same ranges.
|
||||
#[test]
|
||||
fn s1_through_the_family_is_unchanged() {
|
||||
let t = Einsatzbaum::s1();
|
||||
let n = t.baum.knoten.iter().map(|k| if let Knoten::Zug { kinder, .. } = k { CLASSES * kinder.len() } else { 0 }).sum::<usize>();
|
||||
let tab = Tabellen::neu(&S1::neu(Abstraktion { flop: None, turn: None, river: river_cuts(50, 1) }));
|
||||
assert_eq!(tab.eintraege(), n);
|
||||
eprintln!("S1: {} Knoten, {} Eintraege", t.baum.knoten.len(), n);
|
||||
// The real checkpoint, if `GRUNDSTRATEGIE` names a directory with it: it must still load.
|
||||
if let Some(dir) = std::env::var_os("GRUNDSTRATEGIE") {
|
||||
let ckpt = std::path::Path::new(&dir).join("grundstrategie").join("s1.ckpt");
|
||||
if ckpt.exists() {
|
||||
let mut tab = tab;
|
||||
assert!(tab.datei_lesen(&ckpt), "s1.ckpt does not match the S1 tree any more");
|
||||
eprintln!("s1.ckpt loads: {} rounds", tab.runden);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn ohne_tabellen(sz: &'static Szenario) -> Grund {
|
||||
Grund::mit(sz, Abstraktion { flop: None, turn: None, river: river_cuts(50, 1) })
|
||||
}
|
||||
|
||||
/// Every scenario: tree well-formed (only the player facing a bet folds, contributions within
|
||||
/// the stack, at most the scenario's bets a street, out of position acts first), values
|
||||
/// zero-sum on legal deals.
|
||||
#[test]
|
||||
fn every_scenario_tree_is_well_formed_and_zero_sum() {
|
||||
use crate::blueprint::szenario::ALLE;
|
||||
for sz in ALLE.iter() {
|
||||
let s = ohne_tabellen(sz);
|
||||
let t = &s.baum;
|
||||
let zuege = t.baum.knoten.iter().filter(|k| matches!(k, Knoten::Zug { .. })).count();
|
||||
let eintraege = t.baum.knoten.iter().map(|k| if let Knoten::Zug { kinder, .. } = k { CLASSES * kinder.len() } else { 0 }).sum::<usize>();
|
||||
eprintln!("{}: {} Knoten, {} Zuege, {} Enden, {} Eintraege = {:.0} MB (2 Tabellen, f64)", sz.id, t.baum.knoten.len(), zuege, t.enden.len(), eintraege, eintraege as f64 * 16.0 / 1e6);
|
||||
let Knoten::Zug { spieler, strasse, .. } = &t.baum.knoten[t.baum.wurzel] else { panic!() };
|
||||
assert_eq!((*spieler, *strasse), (0, 0), "out of position acts first");
|
||||
assert_eq!(t.beitrag[t.baum.wurzel], [sz.beitrag(); 2]);
|
||||
for e in &t.enden {
|
||||
match e {
|
||||
Ende::Fold { verlierer, c } => {
|
||||
assert!(c[*verlierer] < c[1 - verlierer], "{}: only the player facing a bet folds", sz.id);
|
||||
assert!(c.iter().all(|x| *x <= sz.stapel + 1e-9));
|
||||
}
|
||||
Ende::Showdown { c } => assert!(*c >= sz.beitrag() && *c <= sz.stapel + 1e-9),
|
||||
}
|
||||
}
|
||||
fn tiefe(t: &Einsatzbaum, k: usize, s: usize, n: usize, max: usize) {
|
||||
if let Knoten::Zug { strasse, kinder, .. } = &t.baum.knoten[k] {
|
||||
let n = if *strasse != s { 0 } else { n };
|
||||
for c in kinder {
|
||||
let m = n + matches!(t.aktion[*c], Some(Aktion::Bet(_) | Aktion::Raise(_))) as usize;
|
||||
assert!(m <= max);
|
||||
tiefe(t, *c, *strasse, m, max);
|
||||
}
|
||||
}
|
||||
}
|
||||
tiefe(t, t.baum.wurzel, 0, 0, sz.max_einsaetze);
|
||||
let mut rng = Zufall(Rng::seeded(5));
|
||||
for _ in 0..50 {
|
||||
let d = s.ziehen(&mut rng);
|
||||
assert_eq!((d.hand[0] | d.hand[1] | d.board.iter().fold(0, |m, c| m | c)).count_ones(), 9);
|
||||
for e in 0..t.enden.len() {
|
||||
let w = s.wert(&d, e);
|
||||
assert_eq!(w[0], -w[1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Per scenario a short run lowers LBR below the uniform strategy's (river-only abstraction,
|
||||
/// so flop / turn stay blind; the point is that positions, seats and ranges are consistent).
|
||||
fn lbr_faellt(id: &str) {
|
||||
use crate::blueprint::lbr::lbr;
|
||||
let s = ohne_tabellen(Szenario::finde(id).unwrap());
|
||||
let mut tab = Tabellen::neu(&s);
|
||||
let roh = lbr(&s, &tab, 1000, 2, 11);
|
||||
let t = std::time::Instant::now();
|
||||
let (runden, periode) = (10u64, 10_000u64);
|
||||
rechnen(&s, &mut tab, runden, periode, 2, 3);
|
||||
let sek = t.elapsed().as_secs_f64();
|
||||
let nachher = lbr(&s, &tab, 1000, 2, 11);
|
||||
eprintln!(
|
||||
"{id}: {} Eintraege; {:.0} Iterationen/s (2 Threads); LBR uniform {:+.0} ±{:.0} -> trained {:+.0} ±{:.0} bb/100 (OOP {:+.0} / IP {:+.0})",
|
||||
tab.eintraege(), (runden * periode) as f64 / sek, roh.bb100, roh.ci95, nachher.bb100, nachher.ci95, nachher.je_sitz[0], nachher.je_sitz[1]
|
||||
);
|
||||
assert!(roh.bb100 - roh.ci95 > 300.0, "{id}: uniform must be very exploitable ({:+.0})", roh.bb100);
|
||||
assert!(nachher.bb100 < roh.bb100, "{id}: {} vs {}", nachher.bb100, roh.bb100);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lbr_falls_s1() {
|
||||
lbr_faellt("s1");
|
||||
}
|
||||
#[test]
|
||||
fn lbr_falls_sb() {
|
||||
lbr_faellt("sb");
|
||||
}
|
||||
#[test]
|
||||
fn lbr_falls_co() {
|
||||
lbr_faellt("co");
|
||||
}
|
||||
#[test]
|
||||
fn lbr_falls_btn3() {
|
||||
lbr_faellt("btn3");
|
||||
}
|
||||
#[test]
|
||||
fn lbr_falls_co3() {
|
||||
lbr_faellt("co3");
|
||||
}
|
||||
|
||||
/// A short run on the real tree: deals are legal, values zero-sum, the tables move.
|
||||
#[test]
|
||||
fn s1_runs_and_stays_zero_sum() {
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
//! Scenario family of the blueprint (plan E2, "3-bet pots and the other position pairs").
|
||||
//!
|
||||
//! A scenario is one heads-up postflop spot: the preflop line that leads to it (who opens, to how
|
||||
//! much, whether the big blind 3-bets and the opener calls), the stack, and the bet menu. Player 0
|
||||
//! is always the player who acts first postflop (out of position), player 1 the one in position.
|
||||
//! The two preflop ranges are the engine's own charts at the scenario's stack
|
||||
//! (`Grund::mit`, see `s1.rs`).
|
||||
//!
|
||||
//! Dead money (the small blind's 0.5 when it folds) is not part of the tree: pots are the two
|
||||
//! contributions, as in S1 (a modelling choice, under 3 % of the pot).
|
||||
//!
|
||||
//! The scenarios:
|
||||
//!
|
||||
//! | id | line | OOP (0) | IP (1) | pot at the flop |
|
||||
//! |-------|----------------------------------------|---------|--------|-----------------|
|
||||
//! | `s1` | BTN opens 2.5, BB calls | BB | BTN | 5 |
|
||||
//! | `sb` | SB opens 3, BB calls | SB | BB | 6 |
|
||||
//! | `co` | CO opens 2.5, BB calls | BB | CO | 5 |
|
||||
//! | `btn3`| BTN opens 2.5, BB 3-bets 9, BTN calls | BB | BTN | 18 |
|
||||
//! | `co3` | CO opens 2.5, BB 3-bets 9, CO calls | BB | CO | 18 |
|
||||
//!
|
||||
//! Bet menu: S1's is the default (flop 33 / 75 %, turn 50 / 100 %, river 33 / 75 / 125 % of the
|
||||
//! pot, all-in always, raises to 3x, at most 3 bets a street). In a 3-bet pot the stack-to-pot
|
||||
//! ratio is 5 instead of 19.5 (91 behind in an 18 pot): a 75 % flop bet already commits more than a
|
||||
//! third of the stack and any raise is nearly all-in, so the flop menu is the smaller 25 / 50 %
|
||||
//! (the 3-bettor's range advantage bets small and often at low SPR; big flop bets leave no turn
|
||||
//! room), the turn and river keep S1's sizes, and a bet or raise that would leave under 15 % of the
|
||||
//! stack behind is a jam (a 1-2 bb remainder is never played as a separate size; it also keeps the
|
||||
//! tree small).
|
||||
|
||||
use crate::cfr::seat::Seat;
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Szenario {
|
||||
pub id: &'static str,
|
||||
/// Chart seat of the opener (Button, Cutoff or SmallBlind; the defender is always the big blind).
|
||||
pub eroeffner: Seat,
|
||||
/// Open raise-to in bb.
|
||||
pub eroeffnung: f64,
|
||||
/// `Some(to)`: the big blind 3-bets to `to` and the opener calls.
|
||||
pub dreibet: Option<f64>,
|
||||
pub stapel: f64,
|
||||
/// Bet sizes as pot fractions per street (flop, turn, river).
|
||||
pub einsaetze: [&'static [f64]; 3],
|
||||
/// Raise = this multiple of the bet faced.
|
||||
pub raise: f64,
|
||||
pub max_einsaetze: usize,
|
||||
/// A bet / raise to at least this fraction of the stack is an all-in (`None`: only exact).
|
||||
pub allin_ab: Option<f64>,
|
||||
/// Accepted real open sizes and 3-bet sizes (bb) when a real hand is mapped onto the scenario.
|
||||
pub erkennung_eroeffnung: (f64, f64),
|
||||
pub erkennung_dreibet: (f64, f64),
|
||||
}
|
||||
|
||||
const S1_MENU: [&[f64]; 3] = [&[0.33, 0.75], &[0.5, 1.0], &[0.33, 0.75, 1.25]];
|
||||
const DREIBET_MENU: [&[f64]; 3] = [&[0.25, 0.5], &[0.5, 1.0], &[0.33, 0.75, 1.25]];
|
||||
|
||||
const fn einfach(id: &'static str, eroeffner: Seat, eroeffnung: f64, bereich: (f64, f64)) -> Szenario {
|
||||
Szenario {
|
||||
id,
|
||||
eroeffner,
|
||||
eroeffnung,
|
||||
dreibet: None,
|
||||
stapel: 100.0,
|
||||
einsaetze: S1_MENU,
|
||||
raise: 3.0,
|
||||
max_einsaetze: 3,
|
||||
allin_ab: None,
|
||||
erkennung_eroeffnung: bereich,
|
||||
erkennung_dreibet: (0.0, 0.0),
|
||||
}
|
||||
}
|
||||
|
||||
const fn dreibet(id: &'static str, eroeffner: Seat) -> Szenario {
|
||||
Szenario {
|
||||
id,
|
||||
eroeffner,
|
||||
eroeffnung: 2.5,
|
||||
dreibet: Some(9.0),
|
||||
stapel: 100.0,
|
||||
einsaetze: DREIBET_MENU,
|
||||
raise: 3.0,
|
||||
max_einsaetze: 3,
|
||||
allin_ab: Some(0.85),
|
||||
erkennung_eroeffnung: (2.0, 3.0),
|
||||
erkennung_dreibet: (7.0, 12.0),
|
||||
}
|
||||
}
|
||||
|
||||
/// All scenarios; `ALLE[0]` is S1.
|
||||
pub static ALLE: [Szenario; 5] = [
|
||||
einfach("s1", Seat::Button, 2.5, (2.0, 3.0)),
|
||||
einfach("sb", Seat::SmallBlind, 3.0, (2.5, 4.0)),
|
||||
einfach("co", Seat::Cutoff, 2.5, (2.0, 3.0)),
|
||||
dreibet("btn3", Seat::Button),
|
||||
dreibet("co3", Seat::Cutoff),
|
||||
];
|
||||
|
||||
impl Szenario {
|
||||
pub fn s1() -> &'static Szenario {
|
||||
&ALLE[0]
|
||||
}
|
||||
|
||||
pub fn finde(id: &str) -> Option<&'static Szenario> {
|
||||
ALLE.iter().find(|s| s.id == id)
|
||||
}
|
||||
|
||||
pub fn index(&self) -> usize {
|
||||
ALLE.iter().position(|s| s.id == self.id).expect("scenario of the table")
|
||||
}
|
||||
|
||||
/// Each player's contribution when the flop is dealt.
|
||||
pub fn beitrag(&self) -> f64 {
|
||||
self.dreibet.unwrap_or(self.eroeffnung)
|
||||
}
|
||||
|
||||
/// The opener's player number: the small blind is out of position (0), every other opener
|
||||
/// is in position (1) against the big blind.
|
||||
pub fn eroeffner_spieler(&self) -> usize {
|
||||
if self.eroeffner == Seat::SmallBlind { 0 } else { 1 }
|
||||
}
|
||||
|
||||
/// The big blind's player number.
|
||||
pub fn verteidiger_spieler(&self) -> usize {
|
||||
1 - self.eroeffner_spieler()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user