CFR charts with both blinds as defenders, short deck tables

EP, MP, CO and BTN now play three-player games against small and big
blind (push/fold and open/call/3-bet trees, CFR+ for three players,
exploitability summed over all three best responses). Deal weights and
three-way shares are documented approximations. Short deck gets its own
equity table and charts from the same generator (--deck short).

Open width shrinks in EP/MP (e.g. EP 100bb 0.291 -> 0.249, MP 40bb
0.357 -> 0.293); frozen exploitability stays at 0-4 micro-bb (full) and
0-9 micro-bb (short). Lookup and advice cover SB vs open/jam, BB after
an SB call and the opener vs an SB 3-bet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-28 15:02:45 +01:00
co-authored by Claude Opus 5.5
parent 50b58832e5
commit 7f40fa49a0
40 changed files with 9864 additions and 2585 deletions
+132 -125
View File
@@ -1,125 +1,132 @@
//! Chart generator: the only place of the CFR work that touches the outside world.
//!
//! ```text
//! cargo run --release --bin chartgen -- equity > src/cfr/generated_equity.rs
//! cargo run --release --bin chartgen -- charts > src/preflop/generated_charts.rs
//! ```
//!
//! Options: `--threads N` (default: all cores; the result never depends on it),
//! `equity --samples N --seed S --deck full|short`, `charts --push-iterations N --open-iterations N`.
//! Source text goes to stdout, progress to stderr. `equity --deck short` prints the table for the
//! 36-card deck (81 classes; the rest of the 13 x 13 grid stays 0) once the evaluator is
//! deck-aware; pipe it into a new `generated_equity_short.rs` and solve with
//! `Environment::new(&rules(Variant::ShortDeck), ...)`.
use pokerfreak::cfr::environment::Environment;
use pokerfreak::cfr::equity_matrix::TRIANGLE_LEN;
use pokerfreak::cfr::equity_run::triangle_slice;
use pokerfreak::cfr::frozen_spot::{OpenSpot, PushFoldSpot};
use pokerfreak::cfr::render_charts::render_charts;
use pokerfreak::cfr::render_equity::render_equity;
use pokerfreak::cfr::run_plan::{
open_plan, push_fold_plan, EQUITY_SAMPLES, EQUITY_SEED, OPEN_ITERATIONS, PUSH_FOLD_ITERATIONS,
};
use pokerfreak::cfr::spot_solver::{solve_open_spot_for, solve_push_fold_spot_for};
use pokerfreak::fault::Fault;
use pokerfreak::variant::{rules, Variant};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Mutex;
use std::time::Instant;
/// `f(0..count)` on `threads` workers; the result order is the index order.
fn parallel_map<T: Send>(count: usize, threads: usize, f: impl Fn(usize) -> T + Sync) -> Vec<T> {
let next = AtomicUsize::new(0);
let slots: Mutex<Vec<Option<T>>> = Mutex::new((0..count).map(|_| None).collect());
std::thread::scope(|scope| {
for _ in 0..threads.max(1) {
scope.spawn(|| loop {
let index = next.fetch_add(1, Ordering::SeqCst);
if index >= count {
break;
}
let value = f(index);
if let Ok(mut guard) = slots.lock() {
guard[index] = Some(value);
}
});
}
});
slots.into_inner().unwrap_or_default().into_iter().flatten().collect()
}
fn option<T: std::str::FromStr>(args: &[String], name: &str) -> Option<T> {
args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).and_then(|v| v.parse().ok())
}
fn threads(args: &[String]) -> usize {
option(args, "--threads")
.unwrap_or_else(|| std::thread::available_parallelism().map_or(1, |n| n.get()))
}
fn equity(args: &[String]) -> Result<String, Fault> {
let variant = match option::<String>(args, "--deck").as_deref() {
Some("short") => Variant::ShortDeck,
_ => Variant::Nlhe,
};
let rules = rules(variant);
let seed: u64 = option(args, "--seed").unwrap_or(EQUITY_SEED);
let samples: u32 = option(args, "--samples").unwrap_or(EQUITY_SAMPLES);
let chunk = 64;
let chunks = TRIANGLE_LEN.div_ceil(chunk);
let started = Instant::now();
eprintln!("equity: {TRIANGLE_LEN} class pairs x {samples} samples on {} threads", threads(args));
let parts = parallel_map(chunks, threads(args), |k| {
triangle_slice(&rules, seed, samples, k * chunk..(k + 1) * chunk)
});
let triangle: Vec<u16> = parts.into_iter().collect::<Result<Vec<_>, _>>()?.concat();
eprintln!("equity: done in {:.1} s", started.elapsed().as_secs_f64());
Ok(render_equity(seed, samples, &triangle))
}
fn charts(args: &[String]) -> Result<String, Fault> {
let env = Environment::frozen();
let push_iterations: u32 = option(args, "--push-iterations").unwrap_or(PUSH_FOLD_ITERATIONS);
let open_iterations: u32 = option(args, "--open-iterations").unwrap_or(OPEN_ITERATIONS);
let (push_plan, open_plan) = (push_fold_plan(), open_plan());
let started = Instant::now();
eprintln!(
"charts: {} push/fold + {} open spots on {} threads",
push_plan.len(),
open_plan.len(),
threads(args)
);
let push: Vec<Result<PushFoldSpot, Fault>> = parallel_map(push_plan.len(), threads(args), |k| {
let (seat, depth) = push_plan[k];
solve_push_fold_spot_for(&env, seat, depth, push_iterations)
});
eprintln!("charts: push/fold done at {:.1} s", started.elapsed().as_secs_f64());
let open: Vec<Result<OpenSpot, Fault>> = parallel_map(open_plan.len(), threads(args), |k| {
let (seat, depth) = open_plan[k];
solve_open_spot_for(&env, seat, depth, open_iterations)
});
eprintln!("charts: all done in {:.1} s", started.elapsed().as_secs_f64());
let push = push.into_iter().collect::<Result<Vec<_>, _>>()?;
let open = open.into_iter().collect::<Result<Vec<_>, _>>()?;
Ok(render_charts(&push, &open))
}
fn main() {
let args: Vec<String> = std::env::args().skip(1).collect();
let result = match args.first().map(String::as_str) {
Some("equity") => equity(&args[1..]),
Some("charts") => charts(&args[1..]),
_ => {
eprintln!("usage: chartgen equity|charts [--threads N] [options] (source goes to stdout)");
std::process::exit(2);
}
};
match result {
Ok(source) => print!("{source}"),
Err(fault) => {
eprintln!("chartgen: {fault}");
std::process::exit(1);
}
}
}
//! Chart generator: the only place of the CFR work that touches the outside world.
//!
//! ```text
//! cargo run --release --bin chartgen -- equity > src/cfr/generated_equity.rs
//! cargo run --release --bin chartgen -- charts > src/preflop/generated_charts.rs
//! cargo run --release --bin chartgen -- equity --deck short > src/cfr/generated_equity_short.rs
//! cargo run --release --bin chartgen -- charts --deck short > src/preflop/generated_charts_short.rs
//! ```
//!
//! Options: `--threads N` (default: all cores; the result never depends on it), `--deck full|short`,
//! `equity --samples N --seed S`, `charts --push-iterations N --open-iterations N` (override the
//! plan of `cfr::run_plan` for every seat). Source text goes to stdout, progress to stderr.
//! `charts` reads the frozen equity table of its deck, so regenerate the equity first.
use pokerfreak::cfr::chart_deck::ChartDeck;
use pokerfreak::cfr::environment::Environment;
use pokerfreak::cfr::equity_matrix::TRIANGLE_LEN;
use pokerfreak::cfr::equity_run::triangle_slice;
use pokerfreak::cfr::frozen_spot::{OpenSpot, PushFoldSpot};
use pokerfreak::cfr::render_charts::render_charts;
use pokerfreak::cfr::render_equity::render_equity;
use pokerfreak::cfr::run_plan::{
open_iterations as open_iterations_for, open_plan, push_fold_iterations, push_fold_plan, EQUITY_SAMPLES,
EQUITY_SEED,
};
use pokerfreak::cfr::spot_solver::{solve_open_spot_for, solve_push_fold_spot_for};
use pokerfreak::fault::Fault;
use pokerfreak::variant::rules;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Mutex;
use std::time::Instant;
/// `f(0..count)` on `threads` workers; the result order is the index order.
fn parallel_map<T: Send>(count: usize, threads: usize, f: impl Fn(usize) -> T + Sync) -> Vec<T> {
let next = AtomicUsize::new(0);
let slots: Mutex<Vec<Option<T>>> = Mutex::new((0..count).map(|_| None).collect());
std::thread::scope(|scope| {
for _ in 0..threads.max(1) {
scope.spawn(|| loop {
let index = next.fetch_add(1, Ordering::SeqCst);
if index >= count {
break;
}
let value = f(index);
if let Ok(mut guard) = slots.lock() {
guard[index] = Some(value);
}
});
}
});
slots.into_inner().unwrap_or_default().into_iter().flatten().collect()
}
fn option<T: std::str::FromStr>(args: &[String], name: &str) -> Option<T> {
args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).and_then(|v| v.parse().ok())
}
fn threads(args: &[String]) -> usize {
option(args, "--threads")
.unwrap_or_else(|| std::thread::available_parallelism().map_or(1, |n| n.get()))
}
fn deck(args: &[String]) -> ChartDeck {
match option::<String>(args, "--deck").as_deref() {
Some("short") => ChartDeck::Short,
_ => ChartDeck::Full,
}
}
fn equity(args: &[String]) -> Result<String, Fault> {
let deck = deck(args);
let rules = rules(deck.variant());
let seed: u64 = option(args, "--seed").unwrap_or(EQUITY_SEED);
let samples: u32 = option(args, "--samples").unwrap_or(EQUITY_SAMPLES);
let chunk = 64;
let chunks = TRIANGLE_LEN.div_ceil(chunk);
let started = Instant::now();
eprintln!("equity: {TRIANGLE_LEN} class pairs x {samples} samples on {} threads", threads(args));
let parts = parallel_map(chunks, threads(args), |k| {
triangle_slice(&rules, seed, samples, k * chunk..(k + 1) * chunk)
});
let triangle: Vec<u16> = parts.into_iter().collect::<Result<Vec<_>, _>>()?.concat();
eprintln!("equity: done in {:.1} s", started.elapsed().as_secs_f64());
Ok(render_equity(deck, seed, samples, &triangle))
}
fn charts(args: &[String]) -> Result<String, Fault> {
let deck = deck(args);
let env = Environment::frozen_for(deck);
let push_iterations: Option<u32> = option(args, "--push-iterations");
let open_iterations: Option<u32> = option(args, "--open-iterations");
let (push_plan, open_plan) = (push_fold_plan(), open_plan());
let started = Instant::now();
eprintln!(
"charts: {} push/fold + {} open spots on {} threads",
push_plan.len(),
open_plan.len(),
threads(args)
);
let push: Vec<Result<PushFoldSpot, Fault>> = parallel_map(push_plan.len(), threads(args), |k| {
let (seat, depth) = push_plan[k];
solve_push_fold_spot_for(&env, seat, depth, push_iterations.unwrap_or(push_fold_iterations(seat)))
});
eprintln!("charts: push/fold done at {:.1} s", started.elapsed().as_secs_f64());
let open: Vec<Result<OpenSpot, Fault>> = parallel_map(open_plan.len(), threads(args), |k| {
let (seat, depth) = open_plan[k];
solve_open_spot_for(&env, seat, depth, open_iterations.unwrap_or(open_iterations_for(seat)))
});
eprintln!("charts: all done in {:.1} s", started.elapsed().as_secs_f64());
let push = push.into_iter().collect::<Result<Vec<_>, _>>()?;
let open = open.into_iter().collect::<Result<Vec<_>, _>>()?;
Ok(render_charts(deck, &push, &open))
}
fn main() {
let args: Vec<String> = std::env::args().skip(1).collect();
let result = match args.first().map(String::as_str) {
Some("equity") => equity(&args[1..]),
Some("charts") => charts(&args[1..]),
_ => {
eprintln!("usage: chartgen equity|charts [--threads N] [options] (source goes to stdout)");
std::process::exit(2);
}
};
match result {
Ok(source) => print!("{source}"),
Err(fault) => {
eprintln!("chartgen: {fault}");
std::process::exit(1);
}
}
}
+59
View File
@@ -0,0 +1,59 @@
//! The two decks the generator produces tables for, and where their frozen files live.
use crate::variant::Variant;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ChartDeck {
/// 52 cards, hold'em (NLHE and AOF share the tables).
Full,
/// 36 cards, short deck rules (flush over full house, A-6-7-8-9).
Short,
}
impl ChartDeck {
pub fn variant(self) -> Variant {
match self {
ChartDeck::Full => Variant::Nlhe,
ChartDeck::Short => Variant::ShortDeck,
}
}
/// The deck whose tables a variant uses; `None` for variants without CFR tables.
pub fn of(variant: Variant) -> Option<ChartDeck> {
match variant {
Variant::Nlhe | Variant::Aof => Some(ChartDeck::Full),
Variant::ShortDeck => Some(ChartDeck::Short),
_ => None,
}
}
/// Command-line value of `chartgen --deck`.
pub fn flag(self) -> &'static str {
match self {
ChartDeck::Full => "full",
ChartDeck::Short => "short",
}
}
pub fn equity_file(self) -> &'static str {
match self {
ChartDeck::Full => "src/cfr/generated_equity.rs",
ChartDeck::Short => "src/cfr/generated_equity_short.rs",
}
}
pub fn charts_file(self) -> &'static str {
match self {
ChartDeck::Full => "src/preflop/generated_charts.rs",
ChartDeck::Short => "src/preflop/generated_charts_short.rs",
}
}
/// `" --deck short"` for the short deck, empty for the default.
pub fn deck_argument(self) -> &'static str {
match self {
ChartDeck::Full => "",
ChartDeck::Short => " --deck short",
}
}
}
+72 -65
View File
@@ -1,65 +1,72 @@
//! Everything a game builder needs to know about the deck: rules, exact deal weights, the
//! equity matrix and the strength order of the classes.
use super::chance_table::{chance_table, ChanceTable};
use super::equity_matrix::EquityMatrix;
use super::frozen_equity::frozen_equity;
use super::hand_class::{classes_in, CLASS_COUNT};
use crate::fault::Fault;
use crate::variant::{rules, Rules, Variant};
#[derive(Clone, Debug)]
pub struct Environment {
pub rules: Rules,
pub equity: EquityMatrix,
pub chance: ChanceTable,
/// Classes of the deck, strongest first: by all-in equity against a uniformly random hand.
pub order: Vec<usize>,
}
impl Environment {
/// Two-card games only (the classes are two-card hands).
pub fn new(rules: &Rules, equity: EquityMatrix) -> Result<Environment, Fault> {
if rules.hole_cards != 2 {
return Err(Fault::Invalid {
field: "rules".into(),
detail: "hand classes need exactly two hole cards".into(),
});
}
let chance = chance_table(rules.deck);
let vs_random = |c: usize| -> f64 {
let (num, den) = (0..CLASS_COUNT).fold((0.0, 0.0), |(n, d), j| {
let p = chance.probability(c, j);
(n + p * equity.get(c, j), d + p)
});
if den > 0.0 {
num / den
} else {
0.0
}
};
let mut order = classes_in(rules.deck);
order.sort_by(|a, b| {
vs_random(*b).partial_cmp(&vs_random(*a)).unwrap_or(std::cmp::Ordering::Equal).then(a.cmp(b))
});
Ok(Environment { rules: *rules, equity, chance, order })
}
/// Full deck, hold'em rules, the frozen equity table.
pub fn frozen() -> Environment {
Environment::new(&rules(Variant::Nlhe), frozen_equity()).unwrap_or_else(|_| {
// Unreachable: the hold'em rule set has two hole cards. Kept total instead of panicking.
let r = rules(Variant::Nlhe);
Environment {
rules: r,
equity: EquityMatrix::neutral(),
chance: chance_table(r.deck),
order: classes_in(r.deck),
}
})
}
pub fn classes(&self) -> usize {
CLASS_COUNT
}
}
//! Everything a game builder needs to know about the deck: rules, exact deal weights, the
//! equity matrix and the strength order of the classes.
use super::chance_table::{chance_table, ChanceTable};
use super::chart_deck::ChartDeck;
use super::equity_matrix::EquityMatrix;
use super::frozen_equity::frozen_equity_for;
use super::hand_class::{classes_in, CLASS_COUNT};
use crate::fault::Fault;
use crate::variant::{rules, Rules};
#[derive(Clone, Debug)]
pub struct Environment {
pub rules: Rules,
pub equity: EquityMatrix,
pub chance: ChanceTable,
/// Classes of the deck, strongest first: by all-in equity against a uniformly random hand.
pub order: Vec<usize>,
}
impl Environment {
/// Two-card games only (the classes are two-card hands).
pub fn new(rules: &Rules, equity: EquityMatrix) -> Result<Environment, Fault> {
if rules.hole_cards != 2 {
return Err(Fault::Invalid {
field: "rules".into(),
detail: "hand classes need exactly two hole cards".into(),
});
}
let chance = chance_table(rules.deck);
let vs_random = |c: usize| -> f64 {
let (num, den) = (0..CLASS_COUNT).fold((0.0, 0.0), |(n, d), j| {
let p = chance.probability(c, j);
(n + p * equity.get(c, j), d + p)
});
if den > 0.0 {
num / den
} else {
0.0
}
};
let mut order = classes_in(rules.deck);
order.sort_by(|a, b| {
vs_random(*b).partial_cmp(&vs_random(*a)).unwrap_or(std::cmp::Ordering::Equal).then(a.cmp(b))
});
Ok(Environment { rules: *rules, equity, chance, order })
}
/// Full deck, hold'em rules, the frozen equity table.
pub fn frozen() -> Environment {
Environment::frozen_for(ChartDeck::Full)
}
/// The deck's rules and its frozen equity table.
pub fn frozen_for(deck: ChartDeck) -> Environment {
let variant = deck.variant();
Environment::new(&rules(variant), frozen_equity_for(deck)).unwrap_or_else(|_| {
// Unreachable: both rule sets have two hole cards. Kept total instead of panicking.
let r = rules(variant);
Environment {
rules: r,
equity: EquityMatrix::neutral(),
chance: chance_table(r.deck),
order: classes_in(r.deck),
}
})
}
pub fn classes(&self) -> usize {
CLASS_COUNT
}
}
+18 -9
View File
@@ -1,9 +1,18 @@
//! The frozen full-deck equity matrix (`generated_equity.rs`) as a value.
use super::equity_matrix::EquityMatrix;
use super::generated_equity::TRIANGLE;
/// Never fails: an unreadable table degrades to coin flips instead of a panic.
pub fn frozen_equity() -> EquityMatrix {
EquityMatrix::from_triangle(&TRIANGLE).unwrap_or_else(|_| EquityMatrix::neutral())
}
//! The frozen equity matrices (`generated_equity.rs`, `generated_equity_short.rs`) as values.
use super::chart_deck::ChartDeck;
use super::equity_matrix::EquityMatrix;
use super::{generated_equity, generated_equity_short};
/// The full-deck table. Never fails: an unreadable table degrades to coin flips instead of a panic.
pub fn frozen_equity() -> EquityMatrix {
frozen_equity_for(ChartDeck::Full)
}
pub fn frozen_equity_for(deck: ChartDeck) -> EquityMatrix {
let triangle: &[u16] = match deck {
ChartDeck::Full => &generated_equity::TRIANGLE,
ChartDeck::Short => &generated_equity_short::TRIANGLE,
};
EquityMatrix::from_triangle(triangle).unwrap_or_else(|_| EquityMatrix::neutral())
}
+66 -49
View File
@@ -1,49 +1,66 @@
//! The shapes of the frozen chart tables (`preflop/generated_charts.rs` is data in these types).
//!
//! All frequencies are permille (0..=1000) per hand class, indexed by `ClassId`
//! (the 13 x 13 grid of `hand_class`). Two-action nodes store the frequency of the second
//! action (push / call / raise); three-action nodes store `[call, raise]` and the fold
//! frequency is `1000 - call - raise`.
use super::hand_class::CLASS_COUNT;
use super::seat::Seat;
/// How the run that produced a spot converged.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SpotMeta {
/// CFR+ iterations run.
pub iterations: u32,
/// The argmax chart did not change after this iteration (sampled every `iterations / 200`).
pub stable_since: u32,
/// `(iteration, exploitability in micro-bb)` at N/100, N/20, N/5, N/2 and N, on the
/// unrounded average strategy; the last entry is of the frozen permille strategy.
pub checkpoints: [(u32, u32); 5],
/// Exploitability of the frozen permille strategy, micro-bb (1e-6 bb) per deal.
pub exploitability_micro_bb: u32,
}
/// Push / fold: the first actor's push frequency and the big blind's call frequency.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PushFoldSpot {
pub seat: Seat,
pub depth_bb: u8,
pub push: [u16; CLASS_COUNT],
pub call: [u16; CLASS_COUNT],
pub meta: SpotMeta,
}
/// Open / call / 3-bet.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct OpenSpot {
pub seat: Seat,
pub depth_bb: u8,
/// Opener: raise frequency (else fold).
pub open: [u16; CLASS_COUNT],
/// Big blind versus the open: `[call, 3-bet]`.
pub defend: [[u16; 2]; CLASS_COUNT],
/// Opener versus the 3-bet: `[call, jam]`.
pub vs_three_bet: [[u16; 2]; CLASS_COUNT],
/// Big blind versus the jam: call frequency (else fold).
pub vs_jam: [u16; CLASS_COUNT],
pub meta: SpotMeta,
}
//! The shapes of the frozen chart tables (`preflop/generated_charts.rs` is data in these types).
//!
//! All frequencies are permille (0..=1000) per hand class, indexed by `ClassId`
//! (the 13 x 13 grid of `hand_class`). Two-action nodes store the frequency of the second
//! action (push / call / raise); three-action nodes store `[call, raise]` and the fold
//! frequency is `1000 - call - raise`.
//!
//! The first actors EP, MP, CO and BTN face both blinds (three-player games); the small blind as
//! first actor faces only the big blind (two-player games), so its rows for small-blind
//! decisions and big-blind overcalls stay 0. Classes missing from the deck (short deck) are 0.
use super::hand_class::CLASS_COUNT;
use super::seat::Seat;
/// How the run that produced a spot converged.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SpotMeta {
/// CFR+ iterations run.
pub iterations: u32,
/// The argmax chart did not change after this iteration (sampled every `iterations / 200`).
pub stable_since: u32,
/// `(iteration, exploitability in micro-bb)` at N/100, N/20, N/5, N/2 and N, on the
/// unrounded average strategy; the last entry is of the frozen permille strategy.
pub checkpoints: [(u32, u32); 5],
/// Exploitability of the frozen permille strategy, micro-bb (1e-6 bb) per deal.
pub exploitability_micro_bb: u32,
}
/// Push / fold: the first actor's push frequency and the blinds' call frequencies.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PushFoldSpot {
pub seat: Seat,
pub depth_bb: u8,
pub push: [u16; CLASS_COUNT],
/// Big blind versus the jam after the small blind folded (or with no small blind behind).
pub call: [u16; CLASS_COUNT],
/// Small blind versus the jam, the big blind still to act.
pub sb_call: [u16; CLASS_COUNT],
/// Big blind versus the jam after the small blind called.
pub bb_overcall: [u16; CLASS_COUNT],
pub meta: SpotMeta,
}
/// Open / call / 3-bet.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct OpenSpot {
pub seat: Seat,
pub depth_bb: u8,
/// Opener: raise frequency (else fold).
pub open: [u16; CLASS_COUNT],
/// Big blind versus the open after the small blind folded: `[call, 3-bet]`.
pub defend: [[u16; 2]; CLASS_COUNT],
/// Opener versus the big blind's 3-bet: `[call, jam]`.
pub vs_three_bet: [[u16; 2]; CLASS_COUNT],
/// Big blind versus the jam: call frequency (else fold).
pub vs_jam: [u16; CLASS_COUNT],
/// Small blind versus the open, the big blind still to act: `[call, 3-bet]`.
pub sb_defend: [[u16; 2]; CLASS_COUNT],
/// Big blind versus the open and the small blind's call: call frequency (no squeeze).
pub bb_overcall: [u16; CLASS_COUNT],
/// Opener versus the small blind's 3-bet: `[call, jam]`.
pub vs_sb_three_bet: [[u16; 2]; CLASS_COUNT],
/// Small blind versus the jam over its 3-bet: call frequency.
pub sb_vs_jam: [u16; CLASS_COUNT],
pub meta: SpotMeta,
}
+31 -5
View File
@@ -1,10 +1,12 @@
//! Frozen permille tables <-> `Strategy` values over the matching game tree.
use super::frozen_spot::{OpenSpot, PushFoldSpot};
use super::game::Game;
use super::hand_class::CLASS_COUNT;
use super::permille::{from_permille, to_permille};
use super::strategy::Strategy;
use super::tree::Tree;
use super::tree3::Tree3;
use crate::fault::Fault;
fn binary(p: u16) -> Vec<f64> {
@@ -18,13 +20,23 @@ fn ternary(row: [u16; 2]) -> Vec<f64> {
from_permille(&[1000 - call - raise, call, raise])
}
/// Two-player push / fold (the small blind against the big blind).
pub fn push_fold_strategy(tree: &Tree, spot: &PushFoldSpot) -> Result<Strategy, Fault> {
Strategy::uniform(tree)
.with_rows(tree, "push", |c| binary(spot.push[c]))?
.with_rows(tree, "call", |c| binary(spot.call[c]))
}
pub fn open_strategy(tree: &Tree, spot: &OpenSpot) -> Result<Strategy, Fault> {
/// Three-player push / fold (both blinds behind).
pub fn push_fold3_strategy(tree: &Tree3, spot: &PushFoldSpot) -> Result<Strategy, Fault> {
Strategy::uniform(tree)
.with_rows(tree, "push", |c| binary(spot.push[c]))?
.with_rows(tree, "sb_call", |c| binary(spot.sb_call[c]))?
.with_rows(tree, "call", |c| binary(spot.call[c]))?
.with_rows(tree, "bb_overcall", |c| binary(spot.bb_overcall[c]))
}
fn big_blind_line<G: Game>(tree: &G, spot: &OpenSpot) -> Result<Strategy, Fault> {
Strategy::uniform(tree)
.with_rows(tree, "open", |c| binary(spot.open[c]))?
.with_rows(tree, "defend", |c| ternary(spot.defend[c]))?
@@ -32,12 +44,26 @@ pub fn open_strategy(tree: &Tree, spot: &OpenSpot) -> Result<Strategy, Fault> {
.with_rows(tree, "vs_jam", |c| binary(spot.vs_jam[c]))
}
fn node_of(tree: &Tree, name: &str) -> Result<usize, Fault> {
tree.find(name).ok_or_else(|| Fault::Missing(format!("decision node {name}")))
/// Two-player open / call / 3-bet (the small blind against the big blind).
pub fn open_strategy(tree: &Tree, spot: &OpenSpot) -> Result<Strategy, Fault> {
big_blind_line(tree, spot)
}
/// Three-player open / call / 3-bet (both blinds defend).
pub fn open3_strategy(tree: &Tree3, spot: &OpenSpot) -> Result<Strategy, Fault> {
big_blind_line(tree, spot)?
.with_rows(tree, "sb_defend", |c| ternary(spot.sb_defend[c]))?
.with_rows(tree, "bb_overcall", |c| binary(spot.bb_overcall[c]))?
.with_rows(tree, "vs_sb_three_bet", |c| ternary(spot.vs_sb_three_bet[c]))?
.with_rows(tree, "sb_vs_jam", |c| binary(spot.sb_vs_jam[c]))
}
fn node_of<G: Game>(tree: &G, name: &str) -> Result<usize, Fault> {
tree.decision(name).ok_or_else(|| Fault::Missing(format!("decision node {name}")))
}
/// Permille of the last action of a two-action node.
pub fn binary_row(tree: &Tree, strategy: &Strategy, name: &str) -> Result<[u16; CLASS_COUNT], Fault> {
pub fn binary_row<G: Game>(tree: &G, strategy: &Strategy, name: &str) -> Result<[u16; CLASS_COUNT], Fault> {
let node = node_of(tree, name)?;
let mut out = [0u16; CLASS_COUNT];
for (class, slot) in out.iter_mut().enumerate() {
@@ -47,7 +73,7 @@ pub fn binary_row(tree: &Tree, strategy: &Strategy, name: &str) -> Result<[u16;
}
/// Permille of `[call, raise]` of a three-action node.
pub fn ternary_row(tree: &Tree, strategy: &Strategy, name: &str) -> Result<[[u16; 2]; CLASS_COUNT], Fault> {
pub fn ternary_row<G: Game>(tree: &G, strategy: &Strategy, name: &str) -> Result<[[u16; 2]; CLASS_COUNT], Fault> {
let node = node_of(tree, name)?;
let mut out = [[0u16; 2]; CLASS_COUNT];
for (class, slot) in out.iter_mut().enumerate() {
+61
View File
@@ -0,0 +1,61 @@
//! What the solver needs from a game, whatever the number of players: the shape of the
//! decision nodes, one CFR+ step and the exploitability of a strategy.
//!
//! `Tree` (two players, zero-sum) and `Tree3` (three players) implement it, so `Strategy`,
//! `SolverState` and `solve` work on both.
use super::exploitability::exploitability;
use super::iterate::iterate;
use super::solver_state::SolverState;
use super::strategy::Strategy;
use super::tree::{Node, Tree};
use crate::rng::Rng;
pub trait Game {
/// Hand classes per player.
fn classes(&self) -> usize;
/// Actions per node, 0 for nodes that are not decisions.
fn action_counts(&self) -> Vec<usize>;
/// Name of a decision node, `None` for other nodes and unknown indices.
fn decision_name(&self, node: usize) -> Option<&'static str>;
/// One CFR+ iteration.
fn step(&self, state: SolverState, rng: Rng) -> (SolverState, Rng);
/// Sum of every player's best-response gain against the others' fixed strategy.
fn exploitability(&self, strategy: &Strategy) -> f64;
/// Index of the decision node with this name.
fn decision(&self, name: &str) -> Option<usize> {
(0..self.action_counts().len()).find(|n| self.decision_name(*n) == Some(name))
}
}
impl Game for Tree {
fn classes(&self) -> usize {
self.classes
}
fn action_counts(&self) -> Vec<usize> {
self.nodes
.iter()
.map(|n| match n {
Node::Decision { children, .. } => children.len(),
_ => 0,
})
.collect()
}
fn decision_name(&self, node: usize) -> Option<&'static str> {
match self.nodes.get(node) {
Some(Node::Decision { name, .. }) => Some(name),
_ => None,
}
}
fn step(&self, state: SolverState, rng: Rng) -> (SolverState, Rng) {
iterate(self, state, rng)
}
fn exploitability(&self, strategy: &Strategy) -> f64 {
exploitability(self, strategy)
}
}
+616
View File
@@ -0,0 +1,616 @@
//! GENERATED by `cargo run --release --bin chartgen -- equity --deck short > src/cfr/generated_equity_short.rs`.
//! Do not edit.
//!
//! Deck: 36 cards (six to ace), short deck hand order: flush over full house, A-6-7-8-9 is a
//! straight. Classes with a rank below six are not in the deck and stay 0.
//!
//! All-in preflop equity of hand class `i` against class `j` (`i <= j`, row-major over the
//! 13 x 13 class grid of `hand_class`) in 1/10 000, from 60000 seeded Monte-Carlo
//! board runouts per class pair with exact card removal, evaluated by `hand::showdown::judge`.
//! The diagonal is 5000 by symmetry; the lower triangle is `10000 - upper`.
//! Standard error per entry: at most 0.20 % (sqrt(0.25 / samples)).
pub const SEED: u64 = 5786926807299543621;
pub const SAMPLES: u32 = 60000;
pub static TRIANGLE: [u16; 14365] = [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 5000, 5057, 4857, 4670, 4748, 4952, 4991, 5032, 4897, 0, 0, 0, 0, 4840, 2670, 4098, 3992, 3976, 3970, 4271,
4225, 4166, 0, 0, 0, 0, 4653, 3967, 2506, 3833, 3816, 3820, 4135, 4247, 4046, 0, 0, 0, 0, 4467, 3856, 3712, 2325, 3671,
3673, 4010, 4132, 4095, 0, 0, 0, 0, 4551, 3842, 3678, 3552, 2378, 3339, 3677, 3779, 3955, 0, 0, 0, 0, 4729, 3823, 3696,
3559, 3245, 2383, 3627, 3723, 3845, 0, 0, 0, 0, 4768, 4115, 3984, 3875, 3574, 3508, 2569, 3885, 4060, 0, 0, 0, 0, 4800,
4073, 4100, 3997, 3662, 3606, 3747, 2593, 4156, 0, 0, 0, 0, 4680, 4018, 3906, 3943, 3829, 3719, 3921, 3996, 2463, 5000, 4407, 3893,
3915, 3879, 3771, 3879, 3436, 0, 0, 0, 0, 4801, 2256, 4070, 3644, 3507, 3306, 3585, 3540, 3125, 0, 0, 0, 0, 4242, 3942,
2069, 3294, 3511, 3566, 3787, 3983, 3648, 0, 0, 0, 0, 3781, 3553, 3181, 1952, 3350, 3398, 3633, 3838, 3639, 0, 0, 0, 0,
3786, 3397, 3393, 3256, 2355, 3069, 3322, 3617, 3864, 0, 0, 0, 0, 3716, 3191, 3449, 3289, 2964, 2460, 3170, 3615, 3644, 0, 0,
0, 0, 3617, 3459, 3648, 3511, 3206, 3045, 2631, 3777, 3765, 0, 0, 0, 0, 3726, 3401, 3842, 3710, 3488, 3475, 3637, 2773, 3976,
0, 0, 0, 0, 3314, 3021, 3513, 3523, 3734, 3527, 3625, 3809, 2387, 5000, 3962, 3980, 4092, 3992, 3868, 3596, 0, 0, 0, 0,
5389, 4053, 4335, 4009, 4148, 4263, 4489, 4350, 4307, 0, 0, 0, 0, 4808, 4170, 2226, 3538, 3454, 3268, 3572, 3542, 3158, 0, 0,
0, 0, 3836, 3860, 3439, 1999, 3413, 3559, 3813, 3836, 3796, 0, 0, 0, 0, 3831, 3996, 3343, 3307, 2432, 3330, 3608, 3677, 4006,
0, 0, 0, 0, 3930, 4113, 3162, 3452, 3224, 2654, 3532, 3620, 3858, 0, 0, 0, 0, 3830, 4319, 3440, 3690, 3483, 3404, 2793,
3748, 4004, 0, 0, 0, 0, 3707, 4192, 3411, 3704, 3555, 3476, 3589, 2804, 3988, 0, 0, 0, 0, 3459, 4142, 3049, 3666, 3861,
3721, 3854, 3828, 2566, 5000, 4083, 4199, 4083, 4088, 3607, 0, 0, 0, 0, 5877, 4241, 4888, 4329, 4263, 4394, 4603, 4578, 4300, 0,
0, 0, 0, 5817, 4710, 3865, 4076, 3962, 4160, 4334, 4580, 4186, 0, 0, 0, 0, 4801, 4174, 3940, 2213, 3365, 3218, 3499, 3469,
3165, 0, 0, 0, 0, 3934, 4123, 3819, 3262, 2478, 3434, 3693, 3845, 3981, 0, 0, 0, 0, 4034, 4229, 4014, 3112, 3325, 2718,
3709, 3894, 3904, 0, 0, 0, 0, 3918, 4429, 4180, 3378, 3561, 3568, 2886, 4052, 4021, 0, 0, 0, 0, 3914, 4417, 4408, 3345,
3694, 3739, 3887, 2952, 3991, 0, 0, 0, 0, 3468, 4142, 4039, 3064, 3836, 3759, 3863, 3842, 2585, 5000, 3891, 3764, 3798, 3824, 0,
0, 0, 0, 5841, 4371, 4859, 4779, 4293, 4136, 4388, 4310, 4286, 0, 0, 0, 0, 5771, 4680, 4016, 4476, 4026, 3894, 4073, 4295,
4138, 0, 0, 0, 0, 5694, 4602, 4309, 3705, 3632, 3587, 3803, 4068, 4155, 0, 0, 0, 0, 4798, 4130, 3879, 3509, 1724, 2697,
3034, 3057, 3055, 0, 0, 0, 0, 3750, 3983, 3751, 3466, 2622, 2301, 3396, 3562, 3780, 0, 0, 0, 0, 3622, 4220, 3927, 3681,
2936, 3274, 2432, 3737, 3893, 0, 0, 0, 0, 3653, 4147, 4141, 3911, 2954, 3414, 3590, 2549, 4000, 0, 0, 0, 0, 3662, 4121,
3975, 4005, 2945, 3628, 3731, 3837, 2727, 5000, 3436, 3482, 3377, 0, 0, 0, 0, 5878, 4343, 4836, 4690, 4888, 4273, 4107, 4101, 4051,
0, 0, 0, 0, 5678, 4657, 4018, 4364, 4551, 3961, 3816, 4102, 3917, 0, 0, 0, 0, 5582, 4520, 4199, 3643, 4235, 3545, 3619,
3828, 3893, 0, 0, 0, 0, 5879, 4692, 4381, 4083, 3338, 3079, 3343, 3534, 3782, 0, 0, 0, 0, 4798, 4104, 3813, 3405, 2982,
1369, 2809, 2826, 2647, 0, 0, 0, 0, 3311, 3951, 3670, 3495, 3223, 2724, 2068, 3415, 3515, 0, 0, 0, 0, 3347, 3930, 3937,
3679, 3409, 2736, 3286, 2266, 3636, 0, 0, 0, 0, 3231, 3889, 3772, 3748, 3640, 2560, 3390, 3497, 2257, 5000, 3374, 3313, 0, 0,
0, 0, 5961, 4526, 5071, 4866, 4965, 5068, 4461, 4235, 4166, 0, 0, 0, 0, 5783, 4874, 4167, 4513, 4622, 4751, 4204, 4196, 3987,
0, 0, 0, 0, 5686, 4674, 4346, 3753, 4302, 4433, 3698, 3902, 4013, 0, 0, 0, 0, 5989, 4783, 4451, 4152, 3508, 3916, 3278,
3615, 3849, 0, 0, 0, 0, 6302, 4873, 4575, 4270, 3771, 3420, 3143, 3597, 3752, 0, 0, 0, 0, 4807, 4282, 4038, 3565, 3163,
3025, 1384, 2895, 2769, 0, 0, 0, 0, 3251, 4081, 4018, 3757, 3481, 3463, 2798, 2279, 3612, 0, 0, 0, 0, 3176, 3991, 3837,
3859, 3701, 3613, 2684, 3465, 2261, 5000, 3145, 0, 0, 0, 0, 5891, 4368, 4948, 4733, 4857, 4938, 5307, 4388, 3957, 0, 0, 0,
0, 5894, 4742, 4228, 4604, 4638, 4754, 5129, 4315, 3953, 0, 0, 0, 0, 5678, 4553, 4427, 3825, 4349, 4406, 4784, 3837, 3883, 0,
0, 0, 0, 5954, 4667, 4468, 4193, 3552, 3900, 4316, 3353, 3767, 0, 0, 0, 0, 6257, 4735, 4574, 4248, 3759, 3468, 4287, 3166,
3672, 0, 0, 0, 0, 6343, 5098, 4904, 4592, 4153, 4116, 3616, 3192, 3895, 0, 0, 0, 0, 4803, 4210, 4141, 3688, 3223, 3045,
3066, 1310, 2705, 0, 0, 0, 0, 3023, 3800, 3797, 3745, 3627, 3530, 3740, 2611, 2063, 5000, 0, 0, 0, 0, 6301, 4336, 4944,
4891, 4784, 5095, 5462, 5448, 4446, 0, 0, 0, 0, 6149, 4752, 4084, 4640, 4596, 4878, 5196, 5407, 4240, 0, 0, 0, 0, 6133,
4695, 4473, 3927, 4378, 4614, 4984, 5181, 3994, 0, 0, 0, 0, 5941, 4611, 4426, 4226, 3674, 3886, 4335, 4559, 3635, 0, 0, 0,
0, 6354, 4901, 4677, 4448, 3746, 3774, 4447, 4725, 3479, 0, 0, 0, 0, 6403, 5235, 4988, 4788, 4171, 4266, 3916, 4881, 3441, 0,
0, 0, 0, 6570, 5222, 5184, 4981, 4370, 4528, 4690, 3961, 3375, 0, 0, 0, 0, 4803, 4271, 4075, 3843, 3489, 3331, 3297, 3220,
1490, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 5000, 2595, 4301, 3910, 3795, 3597, 3846, 3812, 3413, 0, 0, 0, 0, 4440, 4165, 2354, 3552, 3771, 3833, 4054, 4228,
3906, 0, 0, 0, 0, 4022, 3795, 3410, 2243, 3612, 3676, 3895, 4085, 3899, 0, 0, 0, 0, 4027, 3676, 3606, 3453, 2635, 3346,
3596, 3869, 4101, 0, 0, 0, 0, 3989, 3476, 3663, 3520, 3205, 2734, 3450, 3871, 3908, 0, 0, 0, 0, 3885, 3706, 3874, 3720,
3431, 3277, 2910, 4034, 4026, 0, 0, 0, 0, 3983, 3690, 4039, 3906, 3694, 3708, 3859, 3026, 4226, 0, 0, 0, 0, 3578, 3301,
3749, 3736, 3941, 3728, 3840, 4046, 2668, 5000, 4777, 4568, 4720, 4947, 5155, 5204, 5062, 0, 0, 0, 0, 5728, 4596, 2508, 4061, 4143,
4239, 4255, 4582, 4398, 0, 0, 0, 0, 5531, 4390, 3907, 2363, 4011, 4108, 4108, 4397, 4429, 0, 0, 0, 0, 5422, 4526, 4008,
3878, 2457, 3758, 3787, 4114, 4369, 0, 0, 0, 0, 5434, 4742, 4093, 3978, 3637, 2564, 3725, 4132, 4225, 0, 0, 0, 0, 5262,
4909, 4111, 3961, 3662, 3590, 2562, 4028, 4187, 0, 0, 0, 0, 5412, 4962, 4410, 4237, 3960, 3981, 3880, 2745, 4389, 0, 0, 0,
0, 5431, 4837, 4220, 4257, 4220, 4083, 4031, 4216, 2611, 5000, 4018, 4050, 4151, 4143, 4111, 3833, 0, 0, 0, 0, 5451, 4799, 2596,
3748, 3797, 3773, 3607, 3888, 3550, 0, 0, 0, 0, 4922, 3906, 3639, 2070, 3683, 3898, 3939, 4157, 4086, 0, 0, 0, 0, 4943,
3912, 3681, 3577, 2541, 3670, 3717, 4003, 4316, 0, 0, 0, 0, 4970, 4000, 3630, 3769, 3557, 2824, 3713, 3939, 4217, 0, 0, 0,
0, 4733, 3975, 3472, 3815, 3588, 3577, 2969, 3779, 4155, 0, 0, 0, 0, 4861, 3940, 3731, 4008, 3865, 3789, 3628, 3130, 4295, 0,
0, 0, 0, 4861, 3687, 3430, 3936, 4167, 4065, 4003, 4131, 2911, 5000, 4108, 4256, 4364, 4322, 3864, 0, 0, 0, 0, 5766, 5760,
4044, 4417, 4286, 4462, 4585, 4829, 4452, 0, 0, 0, 0, 5442, 4805, 4275, 2636, 3707, 3695, 3544, 3874, 3562, 0, 0, 0, 0,
5031, 3972, 4141, 3600, 2570, 3786, 3901, 4148, 4347, 0, 0, 0, 0, 5102, 4091, 4310, 3575, 3663, 2927, 3976, 4233, 4218, 0, 0,
0, 0, 4935, 4177, 4433, 3419, 3767, 3826, 3199, 4174, 4164, 0, 0, 0, 0, 5066, 4142, 4643, 3718, 3991, 4076, 4021, 3306, 4330,
0, 0, 0, 0, 4911, 3714, 4287, 3424, 4214, 4064, 4007, 4159, 2875, 5000, 3944, 4089, 4008, 4036, 0, 0, 0, 0, 5617, 5726,
4208, 4727, 4335, 4155, 4337, 4570, 4411, 0, 0, 0, 0, 5513, 5685, 4550, 3854, 3836, 3939, 4084, 4299, 4389, 0, 0, 0, 0,
5503, 4802, 4182, 3713, 2126, 3180, 3083, 3417, 3441, 0, 0, 0, 0, 4910, 3796, 4017, 3813, 3082, 2487, 3661, 3934, 4100, 0, 0,
0, 0, 4826, 3924, 4182, 3937, 2987, 3532, 2774, 3951, 4144, 0, 0, 0, 0, 4938, 3853, 4394, 4143, 3296, 3789, 3799, 2894, 4275,
0, 0, 0, 0, 4977, 3861, 4248, 4240, 3310, 3937, 3985, 4097, 3062, 5000, 3742, 3703, 3587, 0, 0, 0, 0, 5510, 5630, 4146,
4620, 4850, 4293, 4113, 4335, 4131, 0, 0, 0, 0, 5400, 5535, 4443, 3764, 4537, 3799, 3815, 4054, 4135, 0, 0, 0, 0, 5625,
5830, 4689, 4368, 3567, 3372, 3568, 3791, 4068, 0, 0, 0, 0, 5483, 4804, 4122, 3672, 3259, 1740, 2839, 3206, 3048, 0, 0, 0,
0, 4726, 3594, 3964, 3683, 3438, 2754, 2425, 3694, 3758, 0, 0, 0, 0, 4846, 3571, 4167, 3899, 3666, 3091, 3552, 2574, 3891, 0,
0, 0, 0, 4690, 3453, 3980, 3992, 3919, 2957, 3615, 3734, 2550, 5000, 3385, 3285, 0, 0, 0, 0, 5285, 5625, 4151, 4515, 4758,
4980, 4250, 4092, 3958, 0, 0, 0, 0, 5166, 5427, 4351, 3784, 4473, 4626, 3706, 3859, 3925, 0, 0, 0, 0, 5389, 5693, 4582,
4301, 3543, 4124, 3319, 3586, 3839, 0, 0, 0, 0, 5638, 5993, 4782, 4445, 3965, 3564, 3165, 3720, 3839, 0, 0, 0, 0, 5320,
4806, 4086, 3558, 3204, 3051, 1392, 2978, 2808, 0, 0, 0, 0, 4504, 3265, 3940, 3725, 3456, 3582, 2875, 2255, 3640, 0, 0, 0,
0, 4366, 3156, 3807, 3784, 3702, 3697, 2716, 3499, 2262, 5000, 3188, 0, 0, 0, 0, 5409, 5656, 4252, 4833, 4890, 5040, 5103, 4441,
4029, 0, 0, 0, 0, 5205, 5463, 4657, 3893, 4549, 4639, 4756, 3872, 4017, 0, 0, 0, 0, 5463, 5752, 4700, 4396, 3608, 4237,
4290, 3484, 3892, 0, 0, 0, 0, 5657, 6038, 4839, 4463, 4092, 3665, 4310, 3427, 3890, 0, 0, 0, 0, 5529, 6330, 4884, 4577,
4128, 4144, 3607, 3218, 3863, 0, 0, 0, 0, 5380, 4800, 4268, 3736, 3359, 3296, 3080, 1440, 2909, 0, 0, 0, 0, 4360, 3071,
3868, 3881, 3748, 3742, 3709, 2808, 2222, 5000, 0, 0, 0, 0, 5450, 5927, 4139, 4828, 4902, 5115, 5200, 5555, 4407, 0, 0, 0,
0, 5461, 5894, 4647, 4027, 4637, 4929, 4973, 5352, 4087, 0, 0, 0, 0, 5480, 5738, 4724, 4482, 3884, 4249, 4339, 4769, 3837, 0,
0, 0, 0, 5704, 6158, 4905, 4752, 4094, 3917, 4493, 4894, 3657, 0, 0, 0, 0, 5608, 6430, 5012, 4776, 4178, 4325, 3932, 4900,
3518, 0, 0, 0, 0, 5769, 6534, 5332, 5160, 4595, 4692, 4706, 4099, 3533, 0, 0, 0, 0, 5328, 4794, 4249, 3931, 3687, 3510,
3375, 3376, 1679, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 5000, 4394, 2562, 3790, 3724, 3562, 3834, 3804, 3435, 0, 0, 0, 0, 4079, 4050, 3684, 2299, 3682, 3822, 4063, 4094, 4048, 0,
0, 0, 0, 4098, 4176, 3612, 3527, 2709, 3603, 3850, 3929, 4243, 0, 0, 0, 0, 4164, 4300, 3452, 3660, 3436, 2910, 3789, 3887,
4107, 0, 0, 0, 0, 4080, 4510, 3698, 3882, 3690, 3640, 3064, 3996, 4254, 0, 0, 0, 0, 3961, 4389, 3663, 3915, 3752, 3692,
3825, 3063, 4244, 0, 0, 0, 0, 3726, 4355, 3313, 3868, 4057, 3930, 4069, 4048, 2838, 5000, 2896, 3995, 4038, 4026, 3883, 4139, 3804,
0, 0, 0, 0, 5081, 4115, 3887, 2360, 3932, 4150, 4196, 4390, 4309, 0, 0, 0, 0, 5102, 4132, 3897, 3783, 2808, 3918, 3976,
4252, 4549, 0, 0, 0, 0, 5128, 4218, 3881, 3972, 3750, 3074, 3970, 4195, 4467, 0, 0, 0, 0, 4910, 4206, 3745, 4013, 3791,
3797, 3223, 4033, 4390, 0, 0, 0, 0, 5035, 4179, 3985, 4202, 4058, 4008, 3865, 3377, 4510, 0, 0, 0, 0, 5045, 3927, 3676,
4135, 4371, 4273, 4190, 4312, 3171, 5000, 4538, 4658, 4928, 5176, 5384, 5181, 0, 0, 0, 0, 5879, 5711, 4366, 2376, 4302, 4434, 4518,
4543, 4707, 0, 0, 0, 0, 5762, 5586, 4466, 4145, 2527, 4085, 4165, 4192, 4700, 0, 0, 0, 0, 5749, 5619, 4723, 4254, 3934,
2631, 4135, 4194, 4576, 0, 0, 0, 0, 5622, 5624, 4940, 4351, 4013, 3973, 2790, 4193, 4572, 0, 0, 0, 0, 5554, 5520, 5132,
4360, 4050, 4048, 4044, 2786, 4504, 0, 0, 0, 0, 5683, 5623, 4947, 4526, 4524, 4398, 4398, 4322, 2748, 5000, 4185, 4320, 4411, 4460,
4105, 0, 0, 0, 0, 5711, 5402, 4800, 3001, 3952, 4022, 4060, 3917, 3942, 0, 0, 0, 0, 5318, 5091, 4049, 3840, 2655, 3994,
4201, 4264, 4674, 0, 0, 0, 0, 5423, 5171, 4162, 3889, 3863, 3047, 4323, 4388, 4544, 0, 0, 0, 0, 5266, 5289, 4225, 3916,
4058, 4169, 3372, 4309, 4501, 0, 0, 0, 0, 5176, 4968, 4262, 3756, 4110, 4219, 4148, 3467, 4328, 0, 0, 0, 0, 5145, 4972,
3944, 3793, 4505, 4379, 4332, 4156, 3240, 5000, 3987, 4101, 4325, 4287, 0, 0, 0, 0, 5805, 5496, 5603, 4007, 4063, 4162, 4366, 4546,
4651, 0, 0, 0, 0, 5729, 5464, 4813, 3932, 2525, 3498, 3592, 3462, 3846, 0, 0, 0, 0, 5233, 4967, 3860, 4022, 3392, 2572,
3987, 4152, 4390, 0, 0, 0, 0, 5169, 5044, 3951, 4216, 3484, 3844, 2934, 4203, 4452, 0, 0, 0, 0, 5148, 4908, 4140, 4404,
3340, 4003, 4043, 3198, 4508, 0, 0, 0, 0, 5180, 4901, 4096, 4478, 3697, 4231, 4277, 4311, 3393, 5000, 3786, 4017, 3807, 0, 0,
0, 0, 5604, 5319, 5481, 3959, 4840, 4002, 4127, 4303, 4381, 0, 0, 0, 0, 5868, 5636, 5786, 4659, 3734, 3650, 3844, 4068, 4290,
0, 0, 0, 0, 5795, 5476, 4805, 3865, 3532, 2128, 3366, 3262, 3406, 0, 0, 0, 0, 5017, 4833, 3646, 3986, 3715, 3252, 2630,
3929, 4103, 0, 0, 0, 0, 5019, 4742, 3842, 4149, 3926, 3156, 3778, 2901, 4167, 0, 0, 0, 0, 4902, 4692, 3655, 4227, 4136,
3276, 3945, 4003, 2900, 5000, 3687, 3524, 0, 0, 0, 0, 5433, 5197, 5385, 3932, 4750, 4913, 3947, 4110, 4192, 0, 0, 0, 0,
5687, 5431, 5669, 4571, 3691, 4437, 3603, 3820, 4094, 0, 0, 0, 0, 5923, 5660, 5972, 4734, 4276, 3762, 3491, 3949, 4120, 0, 0,
0, 0, 5573, 5515, 4800, 3805, 3478, 3374, 1809, 2999, 3218, 0, 0, 0, 0, 4660, 4704, 3549, 3965, 3685, 3800, 2887, 2594, 3901,
0, 0, 0, 0, 4604, 4586, 3392, 4041, 3950, 3959, 3103, 3734, 2597, 5000, 3211, 0, 0, 0, 0, 5204, 4974, 5328, 3919, 4591,
4801, 4969, 3932, 3907, 0, 0, 0, 0, 5481, 5218, 5471, 4425, 3613, 4335, 4518, 3516, 3825, 0, 0, 0, 0, 5667, 5419, 5740,
4619, 4178, 3708, 4549, 3453, 3857, 0, 0, 0, 0, 5546, 5662, 6051, 4779, 4346, 4364, 3802, 3275, 4024, 0, 0, 0, 0, 5454,
5345, 4798, 3790, 3393, 3321, 3139, 1474, 3001, 0, 0, 0, 0, 4409, 4266, 3082, 3767, 3689, 3710, 3874, 2894, 2221, 5000, 0, 0,
0, 0, 5573, 5321, 5678, 4089, 4864, 5127, 5264, 5360, 4194, 0, 0, 0, 0, 5624, 5375, 5499, 4688, 4003, 4497, 4657, 4750, 3962,
0, 0, 0, 0, 5829, 5636, 5951, 4928, 4336, 4053, 4798, 4881, 3796, 0, 0, 0, 0, 5768, 5787, 6226, 5071, 4494, 4618, 4091,
4873, 3726, 0, 0, 0, 0, 5779, 5723, 6503, 5149, 4569, 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0, 0, 4158, 4300, 4024, 3550, 2763, 3686, 3947, 4095, 4225, 0, 0, 0, 0,
4272, 4424, 4202, 3404, 3527, 2974, 3959, 4135, 4165, 0, 0, 0, 0, 4141, 4606, 4371, 3631, 3775, 3785, 3126, 4288, 4272, 0, 0,
0, 0, 4152, 4590, 4578, 3604, 3919, 3969, 4116, 3213, 4241, 0, 0, 0, 0, 3724, 4343, 4243, 3326, 4044, 3981, 4074, 4047, 2851,
5000, 4462, 2935, 3969, 3950, 3817, 4110, 3814, 0, 0, 0, 0, 5173, 4184, 4313, 3858, 2841, 4023, 4146, 4376, 4592, 0, 0, 0,
0, 5264, 4308, 4490, 3817, 3860, 3178, 4197, 4468, 4451, 0, 0, 0, 0, 5107, 4401, 4607, 3692, 3971, 4030, 3434, 4419, 4407, 0,
0, 0, 0, 5223, 4381, 4805, 3958, 4188, 4281, 4221, 3540, 4556, 0, 0, 0, 0, 5088, 3940, 4478, 3683, 4399, 4262, 4220, 4363,
3129, 5000, 3284, 4184, 4248, 4302, 4152, 4180, 0, 0, 0, 0, 5478, 5231, 4270, 4066, 2931, 4226, 4417, 4486, 4888, 0, 0, 0,
0, 5564, 5327, 4375, 4114, 4057, 3294, 4537, 4607, 4759, 0, 0, 0, 0, 5426, 5432, 4459, 4141, 4233, 4355, 3601, 4544, 4726, 0,
0, 0, 0, 5342, 5125, 4478, 3995, 4302, 4412, 4357, 3686, 4556, 0, 0, 0, 0, 5306, 5132, 4172, 4022, 4685, 4553, 4524, 4359,
3478, 5000, 4558, 4830, 5080, 5366, 5320, 0, 0, 0, 0, 6070, 5894, 5750, 4385, 2527, 4278, 4493, 4565, 4801, 0, 0, 0, 0,
6108, 5985, 5796, 4639, 4139, 2679, 4478, 4594, 4694, 0, 0, 0, 0, 6007, 5969, 5826, 4866, 4335, 4311, 2878, 4576, 4618, 0, 0,
0, 0, 5918, 5850, 5833, 5122, 4400, 4436, 4393, 2968, 4543, 0, 0, 0, 0, 5837, 5731, 5683, 5086, 4634, 4512, 4449, 4369, 2818,
5000, 4021, 4170, 4359, 4552, 0, 0, 0, 0, 6127, 5946, 5720, 4801, 2908, 3744, 3905, 3973, 3856, 0, 0, 0, 0, 5562, 5269,
4981, 3895, 3639, 2622, 4195, 4457, 4568, 0, 0, 0, 0, 5485, 5328, 5062, 4021, 3779, 4040, 3062, 4485, 4693, 0, 0, 0, 0,
5423, 5234, 5207, 4195, 3826, 4296, 4312, 3394, 4796, 0, 0, 0, 0, 5382, 5147, 4933, 4352, 3696, 4390, 4519, 4594, 3712, 5000, 3809,
4057, 4138, 0, 0, 0, 0, 6183, 5824, 5613, 5777, 3913, 3822, 4165, 4335, 4538, 0, 0, 0, 0, 6185, 5975, 5765, 4803, 3706,
2563, 3711, 3800, 3499, 0, 0, 0, 0, 5347, 5170, 4903, 3673, 4017, 3592, 2723, 4241, 4365, 0, 0, 0, 0, 5349, 5141, 5001,
3888, 4184, 3661, 4079, 3092, 4394, 0, 0, 0, 0, 5138, 4867, 4692, 3962, 4373, 3374, 4200, 4216, 3253, 5000, 3737, 3826, 0, 0,
0, 0, 5953, 5694, 5416, 5618, 3840, 4775, 3787, 4148, 4295, 0, 0, 0, 0, 6133, 5947, 5640, 5962, 4598, 3893, 3759, 4234, 4334,
0, 0, 0, 0, 6051, 6035, 5813, 4807, 3666, 3631, 2217, 3524, 3246, 0, 0, 0, 0, 5012, 5032, 4847, 3590, 3994, 4081, 3403,
2765, 4132, 0, 0, 0, 0, 4817, 4828, 4542, 3661, 4150, 4173, 3127, 3961, 2916, 5000, 3512, 0, 0, 0, 0, 5685, 5474, 5227,
5436, 3795, 4649, 4821, 3733, 4060, 0, 0, 0, 0, 5914, 5705, 5472, 5722, 4466, 3857, 4861, 3663, 4124, 0, 0, 0, 0, 5864,
5895, 5660, 6012, 4621, 4672, 3922, 3595, 4235, 0, 0, 0, 0, 5915, 5874, 5833, 4809, 3605, 3531, 3463, 1883, 3014, 0, 0, 0,
0, 4616, 4460, 4455, 3358, 3913, 3968, 4062, 2902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3742, 2092, 3009,
3340, 3360, 3356, 0, 0, 0, 0, 3989, 4173, 3949, 3664, 2931, 2568, 3652, 3822, 4029, 0, 0, 0, 0, 3857, 4403, 4123, 3865,
3233, 3497, 2706, 3985, 4140, 0, 0, 0, 0, 3890, 4335, 4324, 4130, 3245, 3648, 3795, 2821, 4244, 0, 0, 0, 0, 3882, 4304,
4182, 4197, 3245, 3856, 3962, 4049, 2991, 5000, 4402, 3943, 2465, 3469, 3378, 3696, 3721, 0, 0, 0, 0, 5088, 4031, 4196, 3982, 3371,
2769, 3903, 4180, 4340, 0, 0, 0, 0, 5009, 4165, 4358, 4142, 3270, 3741, 3025, 4203, 4381, 0, 0, 0, 0, 5107, 4075, 4582,
4330, 3581, 4000, 4015, 3145, 4497, 0, 0, 0, 0, 5147, 4072, 4439, 4413, 3583, 4144, 4190, 4300, 3320, 5000, 4162, 2831, 3747, 3861,
3741, 4105, 0, 0, 0, 0, 5390, 5120, 4097, 4221, 3647, 2829, 4203, 4393, 4605, 0, 0, 0, 0, 5335, 5208, 4182, 4402, 3730,
4040, 3196, 4429, 4670, 0, 0, 0, 0, 5288, 5070, 4354, 4584, 3601, 4198, 4240, 3437, 4716, 0, 0, 0, 0, 5332, 5067, 4327,
4658, 3945, 4414, 4471, 4510, 3607, 5000, 3177, 3986, 4139, 4210, 4108, 0, 0, 0, 0, 5683, 5412, 5133, 4094, 3871, 2880, 4418, 4678,
4772, 0, 0, 0, 0, 5622, 5467, 5232, 4246, 3995, 4226, 3318, 4702, 4900, 0, 0, 0, 0, 5576, 5384, 5362, 4386, 4072, 4486,
4502, 3609, 4987, 0, 0, 0, 0, 5567, 5308, 5090, 4555, 3943, 4575, 4692, 4773, 3919, 5000, 4655, 4933, 5214, 5460, 0, 0, 0,
0, 6386, 6177, 6021, 5856, 4482, 2514, 4780, 4955, 5121, 0, 0, 0, 0, 6233, 6206, 6066, 5907, 4733, 4577, 2675, 4911, 5115, 0,
0, 0, 0, 6188, 6135, 6125, 5957, 4987, 4748, 4724, 2880, 5103, 0, 0, 0, 0, 6062, 5880, 5755, 5815, 5217, 4914, 4907, 4900,
3060, 5000, 3801, 4088, 4241, 0, 0, 0, 0, 6654, 6373, 6101, 5939, 4804, 2912, 3780, 3967, 4176, 0, 0, 0, 0, 5835, 5667,
5348, 5017, 3690, 3669, 2637, 4450, 4752, 0, 0, 0, 0, 5842, 5528, 5448, 5156, 3940, 3852, 4294, 3049, 4813, 0, 0, 0, 0,
5846, 5514, 5272, 5201, 4069, 4016, 4576, 4619, 3463, 5000, 3726, 3901, 0, 0, 0, 0, 6392, 6189, 5907, 5598, 5964, 3992, 3848, 4508,
4725, 0, 0, 0, 0, 6443, 6406, 6137, 5987, 4806, 3732, 2598, 3751, 3958, 0, 0, 0, 0, 5451, 5473, 5273, 4983, 3597, 4348,
3633, 2741, 4535, 0, 0, 0, 0, 5416, 5419, 5139, 5045, 3754, 4551, 3800, 4353, 3112, 5000, 3633, 0, 0, 0, 0, 6190, 5960,
5695, 5436, 5690, 3968, 5310, 3794, 4495, 0, 0, 0, 0, 6134, 6162, 5922, 5609, 6051, 5105, 4058, 3693, 4576, 0, 0, 0, 0,
6374, 6262, 6207, 6012, 4815, 3667, 3557, 2266, 3681, 0, 0, 0, 0, 5223, 5021, 5040, 4906, 3489, 4314, 4401, 3548, 2832, 5000, 0,
0, 0, 0, 5966, 5683, 5474, 5236, 5549, 3890, 5126, 5342, 3714, 0, 0, 0, 0, 5895, 5908, 5675, 5463, 5861, 4925, 3992, 5336,
3628, 0, 0, 0, 0, 5980, 5862, 5922, 5704, 6124, 5116, 5116, 4109, 3663, 0, 0, 0, 0, 6108, 5914, 5801, 5766, 4809, 3584,
3495, 3514, 1982, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5000, 4335, 4046, 3685, 3259, 1758, 3114, 3135, 2963, 0, 0,
0, 0, 3575, 4149, 3898, 3715, 3452, 3028, 2349, 3676, 3773, 0, 0, 0, 0, 3613, 4138, 4148, 3891, 3635, 3028, 3498, 2533, 3898,
0, 0, 0, 0, 3503, 4092, 3966, 3955, 3855, 2877, 3614, 3724, 2543, 5000, 4342, 3923, 3525, 2094, 3141, 3506, 3354, 0, 0, 0,
0, 4899, 3839, 4167, 3880, 3652, 3047, 2693, 3940, 4003, 0, 0, 0, 0, 5017, 3829, 4360, 4122, 3869, 3397, 3749, 2837, 4128, 0,
0, 0, 0, 4872, 3689, 4186, 4185, 4132, 3256, 3828, 3946, 2802, 5000, 4103, 3767, 2474, 3640, 3555, 3673, 0, 0, 0, 0, 5202,
5005, 3886, 4185, 3907, 3530, 2888, 4158, 4355, 0, 0, 0, 0, 5189, 4922, 4098, 4346, 4138, 3442, 3980, 3150, 4392, 0, 0, 0,
0, 5084, 4894, 3897, 4412, 4330, 3546, 4166, 4203, 3160, 5000, 3926, 2863, 3967, 4048, 3775, 0, 0, 0, 0, 5493, 5343, 5079, 3908,
4197, 3837, 2981, 4463, 4585, 0, 0, 0, 0, 5514, 5308, 5168, 4126, 4369, 3906, 4274, 3323, 4596, 0, 0, 0, 0, 5340, 5039,
4860, 4192, 4547, 3655, 4394, 4388, 3471, 5000, 3186, 4023, 4205, 4402, 0, 0, 0, 0, 5985, 5822, 5483, 5180, 3916, 3906, 2899, 4669,
4954, 0, 0, 0, 0, 6015, 5678, 5597, 5308, 4140, 4066, 4466, 3282, 5008, 0, 0, 0, 0, 6002, 5672, 5446, 5369, 4297, 4231,
4733, 4791, 3683, 5000, 5019, 5278, 5450, 0, 0, 0, 0, 6331, 6188, 5992, 5872, 5772, 4816, 2515, 4858, 4910, 0, 0, 0, 0,
6270, 6087, 6056, 5892, 5811, 5035, 4660, 2703, 4943, 0, 0, 0, 0, 5979, 5847, 5718, 5722, 5863, 5195, 4722, 4724, 2809, 5000, 3659,
3841, 0, 0, 0, 0, 6581, 6551, 6247, 6000, 5934, 4804, 2450, 3623, 3782, 0, 0, 0, 0, 5499, 5449, 5255, 4936, 4515, 3543,
3502, 2571, 4360, 0, 0, 0, 0, 5311, 5285, 4985, 4891, 4694, 3698, 3640, 4186, 2971, 5000, 3512, 0, 0, 0, 0, 6145, 6024,
5807, 5533, 5264, 6098, 3907, 3579, 4376, 0, 0, 0, 0, 6563, 6311, 6282, 6095, 5972, 4808, 3451, 2102, 3560, 0, 0, 0, 0,
5060, 4893, 4908, 4735, 4483, 3378, 4208, 3435, 2630, 5000, 0, 0, 0, 0, 5976, 5912, 5642, 5430, 5061, 5930, 3975, 5377, 3558, 0,
0, 0, 0, 6074, 5864, 5887, 5633, 5288, 6217, 5160, 4113, 3594, 0, 0, 0, 0, 6252, 6091, 5970, 5889, 6037, 4805, 3425, 3462,
1912, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 5000, 4499, 4279, 3808, 3452, 3308, 1773, 3181, 3074, 0, 0, 0, 0, 3536, 4271, 4231, 3953,
3701, 3670, 3077, 2565, 3878, 0, 0, 0, 0, 3481, 4185, 4035, 4079, 3934, 3835, 2988, 3695, 2528, 5000, 4303, 3824, 3471, 3343, 1772,
3273, 3113, 0, 0, 0, 0, 4704, 3543, 4133, 3954, 3671, 3800, 3168, 2535, 3890, 0, 0, 0, 0, 4540, 3433, 4016, 3986, 3922,
3896, 3009, 3706, 2542, 5000, 4048, 3751, 3644, 2160, 3306, 3509, 0, 0, 0, 0, 4863, 4890, 3803, 4162, 3898, 3990, 3188, 2855, 4136,
0, 0, 0, 0, 4786, 4767, 3643, 4250, 4152, 4169, 3387, 3965, 2868, 5000, 3899, 3865, 2541, 3807, 3520, 0, 0, 0, 0, 5176,
5199, 5022, 3849, 4188, 4263, 3673, 3001, 4368, 0, 0, 0, 0, 5000, 4995, 4746, 3914, 4345, 4374, 3393, 4163, 3160, 5000, 3960, 2902,
3982, 4197, 0, 0, 0, 0, 5630, 5643, 5444, 5163, 3828, 4536, 3856, 2993, 4744, 0, 0, 0, 0, 5610, 5586, 5297, 5209, 3985,
4722, 4058, 4530, 3358, 5000, 2762, 3863, 4036, 0, 0, 0, 0, 5665, 5619, 5420, 5111, 4710, 3780, 3751, 2836, 4591, 0, 0, 0,
0, 5484, 5459, 5154, 5082, 4869, 3929, 3897, 4382, 3229, 5000, 5389, 5510, 0, 0, 0, 0, 6133, 6143, 5974, 5868, 5716, 5860, 5145,
2537, 4832, 0, 0, 0, 0, 5853, 5825, 5671, 5646, 5781, 5786, 5267, 4647, 2714, 5000, 3462, 0, 0, 0, 0, 6519, 6500, 6443,
6134, 6061, 6164, 4802, 1938, 3487, 0, 0, 0, 0, 4902, 4885, 4902, 4683, 4479, 4429, 3328, 3377, 2433, 5000, 0, 0, 0, 0,
5856, 5892, 5714, 5524, 5193, 5380, 6258, 3975, 3480, 0, 0, 0, 0, 6279, 6216, 6029, 5975, 6117, 6183, 4806, 3336, 1700, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
5000, 4437, 4366, 3934, 3498, 3333, 3368, 1699, 3021, 0, 0, 0, 0, 3307, 4014, 4017, 3950, 3857, 3774, 3969, 2928, 2383, 5000, 4475,
3980, 3629, 3563, 3369, 1824, 3215, 0, 0, 0, 0, 4562, 3337, 4069, 4091, 3974, 3964, 3925, 3116, 2508, 5000, 4044, 3669, 3594, 3425,
1863, 3298, 0, 0, 0, 0, 4597, 4456, 3366, 3990, 3905, 3933, 4084, 3204, 2506, 5000, 3851, 3781, 3717, 2237, 3325, 0, 0, 0,
0, 4791, 4662, 4648, 3635, 4114, 4174, 4241, 3214, 2832, 5000, 3910, 3805, 2591, 3948, 0, 0, 0, 0, 5395, 5206, 5199, 5076, 3742,
4498, 4580, 3804, 3088, 5000, 3707, 2437, 3826, 0, 0, 0, 0, 5245, 5068, 5082, 4899, 4676, 3650, 4407, 3696, 2894, 5000, 2288, 3766,
0, 0, 0, 0, 5101, 5076, 5091, 4875, 4674, 4625, 3620, 3630, 2722, 5000, 5610, 0, 0, 0, 0, 5787, 5677, 5644, 5522, 5661,
5671, 5794, 5357, 2555, 5000, 0, 0, 0, 0, 6374, 6204, 6146, 6115, 6080, 6161, 6253, 4805, 1527, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5000, 4490, 4319, 4087, 3778, 3630, 3569, 3513,
1867, 5000, 4476, 4180, 3950, 3754, 3648, 3655, 2057, 5000, 4267, 4056, 3907, 3847, 3703, 2233, 5000, 4085, 3964, 3861, 3740, 2212, 5000, 3821,
3753, 3787, 2330, 5000, 3696, 3712, 2260, 5000, 3605, 2069, 5000, 1891, 5000,
];
+121
View File
@@ -0,0 +1,121 @@
//! Counterfactual value of a three-player leaf for one traverser, given both opponents' reach.
//!
//! `value[x] = scale * sum_{y, z} P(x, y, z) * reach_q[y] * reach_r[z] * u_p(x, y, z)`, where `q`
//! and `r` are the two opponents and `P` the triple deal weight of `Tree3`. The traverser's own
//! reach is not part of the value. Opponent classes with zero reach are skipped; a leaf whose
//! payoff does not depend on the third player's class reduces the inner sum to a dot product.
use super::tree3::{Outcome, Tree3};
fn others(p: usize) -> (usize, usize) {
match p {
0 => (1, 2),
1 => (0, 2),
_ => (0, 1),
}
}
fn support(reach: &[f64]) -> Vec<usize> {
(0..reach.len()).filter(|k| reach[*k] != 0.0).collect()
}
/// `sum_{y, z} P(x, y, z) reach_o[y] reach_t[z] u(x, y)` for every `x`, times `scale`.
fn with_one(tree: &Tree3, reach_o: &[f64], reach_t: &[f64], scale: f64, u: impl Fn(usize, usize) -> f64) -> Vec<f64> {
let n = tree.classes;
let g = &tree.pair;
let ys = support(reach_o);
if ys.is_empty() || tree.norm <= 0.0 || reach_t.iter().all(|r| *r == 0.0) {
return vec![0.0; n];
}
let factor = scale / tree.norm;
let mut hx = vec![0.0; n];
(0..n)
.map(|x| {
let row_x = &g[x * n..(x + 1) * n];
hx.iter_mut().zip(row_x.iter().zip(reach_t)).for_each(|(h, (a, r))| *h = a * r);
let acc: f64 = ys
.iter()
.map(|y| {
let gxy = row_x[*y] * reach_o[*y];
if gxy == 0.0 {
return 0.0;
}
let row_y = &g[y * n..(y + 1) * n];
let d: f64 = hx.iter().zip(row_y).map(|(a, b)| a * b).sum();
gxy * d * u(x, *y)
})
.sum();
acc * factor
})
.collect()
}
/// Full triple sum for leaves whose payoff depends on all three classes.
fn with_both(tree: &Tree3, p: usize, outcome: &Outcome, reach: [&[f64]; 3], scale: f64) -> Vec<f64> {
let n = tree.classes;
let g = &tree.pair;
let (q, r) = others(p);
let (ys, zs) = (support(reach[q]), support(reach[r]));
if ys.is_empty() || zs.is_empty() || tree.norm <= 0.0 {
return vec![0.0; n];
}
let factor = scale / tree.norm;
(0..n)
.map(|x| {
let row_x = &g[x * n..(x + 1) * n];
let mut acc = 0.0;
for y in &ys {
let gxy = row_x[*y] * reach[q][*y];
if gxy == 0.0 {
continue;
}
let row_y = &g[y * n..(y + 1) * n];
for z in &zs {
let w = gxy * row_x[*z] * row_y[*z] * reach[r][*z];
if w == 0.0 {
continue;
}
let mut c = [0usize; 3];
c[p] = x;
c[q] = *y;
c[r] = *z;
acc += w * tree.payoff(outcome, c)[p];
}
}
acc * factor
})
.collect()
}
/// Probability mass of reaching the leaf with each own class: the value of a payoff of 1.
pub fn reach_mass(tree: &Tree3, p: usize, reach: [&[f64]; 3], scale: f64) -> Vec<f64> {
let (q, r) = others(p);
with_one(tree, reach[q], reach[r], scale, |_, _| 1.0)
}
pub fn leaf_value(tree: &Tree3, outcome: &Outcome, p: usize, reach: [&[f64]; 3], scale: f64) -> Vec<f64> {
let (q, r) = others(p);
let own_only = |u: &dyn Fn(usize) -> f64| with_one(tree, reach[q], reach[r], scale, |x, _| u(x));
match outcome {
Outcome::Flat(u) => own_only(&|_| u[p]),
Outcome::Own { player, values, rest } if *player == p => {
own_only(&|x| values.get(x).copied().unwrap_or(0.0))
}
Outcome::Own { rest, .. } => own_only(&|_| rest[p]),
Outcome::Heads { a, b, pot, invested, share } if *a == p || *b == p => {
let n = tree.classes;
let other = if *a == p { *b } else { *a };
let third = 3 - p - other;
let mine = |x: usize, y: usize| -> f64 {
if *a == p {
share.get(x * n + y).copied().unwrap_or(0.5)
} else {
1.0 - share.get(y * n + x).copied().unwrap_or(0.5)
}
};
with_one(tree, reach[other], reach[third], scale, |x, y| pot * mine(x, y) - invested[p])
}
Outcome::Heads { invested, .. } => own_only(&|_| -invested[p]),
Outcome::Three { .. } => with_both(tree, p, outcome, reach, scale),
}
}
+87 -78
View File
@@ -1,78 +1,87 @@
//! Offline preflop chart derivation: counterfactual regret minimisation over a small,
//! documented preflop abstraction. Pure; the only I/O lives in `src/bin/chartgen.rs`.
//!
//! # Abstraction (every assumption)
//!
//! **Hands.** The 169 hold'em classes (`hand_class`), dealt with exact combo weights:
//! a deal is an ordered pair of disjoint combos, all equally likely, so card removal between the
//! two players is exact (`chance_table`). Other players' cards are ignored (see multiway).
//!
//! **Equity.** `equity_matrix`: all-in preflop equity of every class against every class, from a
//! seeded Monte Carlo over disjoint combo pairs and uniformly random five-card boards, evaluated
//! with `hand::showdown::judge` (`equity_pair`). Frozen as integers in `generated_equity.rs`
//! (regenerate with `chartgen equity`). Noise: about 0.2 % per entry at 60 000 samples.
//!
//! **Games** (`push_fold_game`, `open_game`), blinds 0.5 / 1, 6-max seats `seat`:
//! - push / fold: the first actor jams the effective stack or folds; the big blind calls or folds.
//! - open / call / 3-bet: raise to a fixed size or fold; the big blind folds, calls or 3-bets to a
//! fixed size; versus the 3-bet the opener folds, calls or jams; the big blind calls or folds
//! the jam. Sizes: `spot_params`.
//!
//! **Multiway.** One opponent is modelled. The players behind the first actor each hold a hand
//! that continues with probability `WAKE_FRACTION` (the top 15 % of combos by random-hand
//! equity); if one does, the first actor is called by that range and the big blind takes no
//! decision. Players behind are independent, and their cards do not block the modelled hands.
//!
//! **Payoffs.** Net result in bb for the first actor, zero-sum. All-in lines use raw equity.
//! Lines that leave chips behind use `pot x realised share`: equity is stretched around 50 %
//! (the better hand realises more, `REALIZATION_SPREAD`), then the out-of-position player's side
//! counts `R` (0.85 in single-raised, 0.90 in 3-bet pots) against the in-position player's 1.0 and
//! the pot is split in proportion -- zero-sum, unlike a one-sided `pot x equity x R`.
//! The big blind is out of position against every seat but the small blind.
//!
//! **Variants.** `Environment::new(rules, equity)` is generic over the rules: any two-card game
//! whose deck rule yields the class set (`classes_in`). AOF (binary action shape) is exactly the
//! push / fold game. Short deck needs only one more run once `hand::showdown::judge` is
//! deck-aware: `chartgen equity --deck short` (equity for the 81 classes of the 36-card deck),
//! then solve the spots with that `Environment`.
//!
//! # Solver
//!
//! Full-width vectorised CFR+ (`iterate`): regrets floored at zero, alternating updates, average
//! strategy linearly weighted. One iteration is a pure fold step `(state, rng) -> (state, rng)`;
//! the generator is passed through because enumerating all deals needs no randomness.
//! `solve` records the convergence (`checkpoints`, `stable_since`), `exploitability` and
//! `deviation` implement the Nash test, `spot_solver` freezes a spot as permille tables.
pub mod chance_table;
pub mod chart_signature;
pub mod deviation;
pub mod environment;
pub mod equity_matrix;
pub mod equity_pair;
pub mod equity_run;
pub mod exploitability;
pub mod frozen_equity;
pub mod frozen_spot;
pub mod frozen_strategy;
pub mod generated_equity;
pub mod hand_class;
pub mod iterate;
pub mod open_game;
pub mod payoffs;
pub mod permille;
pub mod push_fold_game;
pub mod regret_matching;
pub mod render_charts;
pub mod render_equity;
pub mod run_plan;
pub mod seat;
pub mod solve;
pub mod solver_state;
pub mod spot_params;
pub mod spot_solver;
pub mod strategy;
pub mod terminal_value;
pub mod tree;
pub mod value_walk;
pub mod wake_range;
//! Offline preflop chart derivation: counterfactual regret minimisation over a small,
//! documented preflop abstraction. Pure; the only I/O lives in `src/bin/chartgen.rs`.
//!
//! # Abstraction (every assumption)
//!
//! **Hands.** The 169 hold'em classes (`hand_class`), dealt with exact combo weights:
//! a deal is an ordered pair of disjoint combos, all equally likely, so card removal between the
//! two players is exact (`chance_table`). Other players' cards are ignored (see multiway).
//!
//! **Equity.** `equity_matrix`: all-in preflop equity of every class against every class, from a
//! seeded Monte Carlo over disjoint combo pairs and uniformly random five-card boards, evaluated
//! with `hand::showdown::judge` (`equity_pair`). Frozen as integers in `generated_equity.rs`
//! (regenerate with `chartgen equity`). Noise: about 0.2 % per entry at 60 000 samples.
//!
//! **Games** (`push_fold_game`, `open_game`), blinds 0.5 / 1, 6-max seats `seat`:
//! - push / fold: the first actor jams the effective stack or folds; the big blind calls or folds.
//! - open / call / 3-bet: raise to a fixed size or fold; the big blind folds, calls or 3-bets to a
//! fixed size; versus the 3-bet the opener folds, calls or jams; the big blind calls or folds
//! the jam. Sizes: `spot_params`.
//!
//! **Multiway.** One opponent is modelled. The players behind the first actor each hold a hand
//! that continues with probability `WAKE_FRACTION` (the top 15 % of combos by random-hand
//! equity); if one does, the first actor is called by that range and the big blind takes no
//! decision. Players behind are independent, and their cards do not block the modelled hands.
//!
//! **Payoffs.** Net result in bb for the first actor, zero-sum. All-in lines use raw equity.
//! Lines that leave chips behind use `pot x realised share`: equity is stretched around 50 %
//! (the better hand realises more, `REALIZATION_SPREAD`), then the out-of-position player's side
//! counts `R` (0.85 in single-raised, 0.90 in 3-bet pots) against the in-position player's 1.0 and
//! the pot is split in proportion -- zero-sum, unlike a one-sided `pot x equity x R`.
//! The big blind is out of position against every seat but the small blind.
//!
//! **Variants.** `Environment::new(rules, equity)` is generic over the rules: any two-card game
//! whose deck rule yields the class set (`classes_in`). AOF (binary action shape) is exactly the
//! push / fold game. Short deck needs only one more run once `hand::showdown::judge` is
//! deck-aware: `chartgen equity --deck short` (equity for the 81 classes of the 36-card deck),
//! then solve the spots with that `Environment`.
//!
//! # Solver
//!
//! Full-width vectorised CFR+ (`iterate`): regrets floored at zero, alternating updates, average
//! strategy linearly weighted. One iteration is a pure fold step `(state, rng) -> (state, rng)`;
//! the generator is passed through because enumerating all deals needs no randomness.
//! `solve` records the convergence (`checkpoints`, `stable_since`), `exploitability` and
//! `deviation` implement the Nash test, `spot_solver` freezes a spot as permille tables.
pub mod chance_table;
pub mod chart_deck;
pub mod chart_signature;
pub mod deviation;
pub mod environment;
pub mod equity_matrix;
pub mod equity_pair;
pub mod equity_run;
pub mod exploitability;
pub mod frozen_equity;
pub mod frozen_spot;
pub mod frozen_strategy;
pub mod game;
pub mod generated_equity;
pub mod generated_equity_short;
pub mod hand_class;
pub mod iterate;
pub mod leaf_value3;
pub mod open3_game;
pub mod open_game;
pub mod payoffs;
pub mod permille;
pub mod push_fold3_game;
pub mod push_fold_game;
pub mod regret_matching;
pub mod render_charts;
pub mod render_equity;
pub mod run_plan;
pub mod seat;
pub mod solve;
pub mod solver_state;
pub mod spot_params;
pub mod spot_solver;
pub mod strategy;
pub mod terminal_value;
pub mod three_way;
pub mod tree3;
pub mod tree;
pub mod value_walk;
pub mod wake_range;
pub mod walk3;
+133
View File
@@ -0,0 +1,133 @@
//! Game (b3): open / call / 3-bet with both blinds as defenders (three players).
//!
//! Player 0 opens from `seat` (EP, MP, CO or BTN) to `OPEN_SIZE` or folds; player 1 is the small
//! blind, player 2 the big blind. The field between the opener and the small blind is the wake
//! model of `open_game` (one player fewer, the small blind decides itself). Then:
//!
//! - `sb_defend` (P1): fold / call / 3-bet to `SMALL_BLIND_THREE_BET_SIZE`.
//! - After the small blind folds: the two-player tree against the big blind with the small blind
//! dead -- `defend` (P2: fold / call / 3-bet to `THREE_BET_SIZE`), `vs_three_bet`
//! (P0: fold / call / jam), `vs_jam` (P2: fold / call).
//! - After the small blind calls: `bb_overcall` (P2: fold / call; no squeeze). A call plays the
//! pot three-way, the opener in position against both blinds.
//! - After the small blind 3-bets: the big blind always folds (no cold 4-bet, no cold call);
//! `vs_sb_three_bet` (P0: fold / call / jam), `sb_vs_jam` (P1: fold / call).
//!
//! Pots with chips behind pay pot x realised share (`payoffs::share`, three-way:
//! `three_way::three_way_shares`); jams pay raw equity. The opener is in position against both
//! blinds; the blinds count `REALIZATION_OOP_SINGLE_RAISED` (3-bet pots
//! `REALIZATION_OOP_THREE_BET`).
use super::environment::Environment;
use super::hand_class::CLASS_COUNT;
use super::open_game::open_size;
use super::payoffs::share;
use super::push_fold3_game::{all_in_share, needs_two_blinds};
use super::seat::Seat;
use super::spot_params::{
field_folds, BIG_BLIND, REALIZATION_OOP_SINGLE_RAISED, REALIZATION_OOP_THREE_BET, REALIZATION_SPREAD,
SMALL_BLIND, SMALL_BLIND_THREE_BET_SIZE, THREE_BET_SIZE, WAKE_FRACTION,
};
use super::tree3::{Node3, Outcome, Tree3};
use super::wake_range::{equity_against, top_membership};
use crate::fault::Fault;
/// Opener's postflop pot share against one blind, in position.
fn in_position_share(env: &Environment, realization: f64) -> Vec<f64> {
(0..CLASS_COUNT * CLASS_COUNT)
.map(|k| share(env.equity.get(k / CLASS_COUNT, k % CLASS_COUNT), true, realization))
.collect()
}
pub fn open3_tree(env: &Environment, seat: Seat, depth_bb: f64) -> Result<Tree3, Fault> {
needs_two_blinds(seat)?;
let (x, y, z) = (open_size(seat), THREE_BET_SIZE, SMALL_BLIND_THREE_BET_SIZE);
if !depth_bb.is_finite() || depth_bb <= y.max(z) {
return Err(Fault::Invalid {
field: "depth_bb".into(),
detail: "stack must exceed the 3-bet sizes".into(),
});
}
let s = depth_bb;
let (sb, bb) = (SMALL_BLIND, BIG_BLIND);
let r = field_folds(seat.players_before_blinds());
let wake = equity_against(env, &top_membership(env, WAKE_FRACTION));
let wake_ip = seat == Seat::Button;
let single = in_position_share(env, REALIZATION_OOP_SINGLE_RAISED);
let three_bet = in_position_share(env, REALIZATION_OOP_THREE_BET);
let jam = all_in_share(env);
let blinds_oop = [1.0, REALIZATION_OOP_SINGLE_RAISED, REALIZATION_OOP_SINGLE_RAISED];
let mut nodes: Vec<Node3> = Vec::new();
let mut add = |node: Node3| -> usize {
nodes.push(node);
nodes.len() - 1
};
let heads = |b: usize, pot: f64, invested: [f64; 3], share: &Vec<f64>| Node3::Terminal(Outcome::Heads {
a: 0,
b,
pot,
invested,
share: share.clone(),
});
// Small blind folds: the big blind's tree, the small blind dead.
let t_open_fold = add(Node3::Terminal(Outcome::Flat([0.0, 0.0, 0.0])));
let t_blinds_fold = add(Node3::Terminal(Outcome::Flat([sb + bb, -sb, -bb])));
let t_bb_calls = add(heads(2, 2.0 * x + sb, [x, sb, x], &single));
let t_opener_folds_bb = add(Node3::Terminal(Outcome::Flat([-x, -sb, x + sb])));
let t_bb_three_bet_called = add(heads(2, 2.0 * y + sb, [y, sb, y], &three_bet));
let t_bb_folds_jam = add(Node3::Terminal(Outcome::Flat([y + sb, -sb, -y])));
let t_bb_calls_jam = add(heads(2, 2.0 * s + sb, [s, sb, s], &jam));
let vs_jam = add(Node3::Decision { player: 2, name: "vs_jam", children: vec![t_bb_folds_jam, t_bb_calls_jam] });
let vs_three_bet = add(Node3::Decision {
player: 0,
name: "vs_three_bet",
children: vec![t_opener_folds_bb, t_bb_three_bet_called, vs_jam],
});
let defend =
add(Node3::Decision { player: 2, name: "defend", children: vec![t_blinds_fold, t_bb_calls, vs_three_bet] });
// Small blind calls: the big blind folds or makes it three-way.
let t_bb_folds_behind = add(heads(1, 2.0 * x + bb, [x, x, bb], &single));
let t_three_way = add(Node3::Terminal(Outcome::Three {
pot: 3.0 * x,
invested: [x, x, x],
weights: blinds_oop,
spread: REALIZATION_SPREAD,
}));
let overcall =
add(Node3::Decision { player: 2, name: "bb_overcall", children: vec![t_bb_folds_behind, t_three_way] });
// Small blind 3-bets: the big blind is out.
let t_opener_folds_sb = add(Node3::Terminal(Outcome::Flat([-x, x + bb, -bb])));
let t_sb_three_bet_called = add(heads(1, 2.0 * z + bb, [z, z, bb], &three_bet));
let t_sb_folds_jam = add(Node3::Terminal(Outcome::Flat([z + bb, -z, -bb])));
let t_sb_calls_jam = add(heads(1, 2.0 * s + bb, [s, s, bb], &jam));
let sb_vs_jam =
add(Node3::Decision { player: 1, name: "sb_vs_jam", children: vec![t_sb_folds_jam, t_sb_calls_jam] });
let vs_sb_three_bet = add(Node3::Decision {
player: 0,
name: "vs_sb_three_bet",
children: vec![t_opener_folds_sb, t_sb_three_bet_called, sb_vs_jam],
});
let sb_defend =
add(Node3::Decision { player: 1, name: "sb_defend", children: vec![defend, overcall, vs_sb_three_bet] });
let raised = if r < 1.0 {
let woken = Outcome::Own {
player: 0,
values: wake
.iter()
.map(|e| (2.0 * x + sb + bb) * share(*e, wake_ip, REALIZATION_OOP_SINGLE_RAISED) - x)
.collect(),
rest: [0.0, -sb, -bb],
};
let t_woken = add(Node3::Terminal(woken));
add(Node3::Chance(vec![(r, sb_defend), (1.0 - r, t_woken)]))
} else {
sb_defend
};
let root = add(Node3::Decision { player: 0, name: "open", children: vec![t_open_fold, raised] });
Ok(Tree3::new(env, nodes, root))
}
+81
View File
@@ -0,0 +1,81 @@
//! Game (a3): push / fold with both blinds as callers (three players).
//!
//! Player 0 is the first actor at `seat` (EP, MP, CO or BTN), player 1 the small blind, player 2
//! the big blind. Player 0 jams `depth_bb` or folds. If the players between him and the small
//! blind fold -- probability `field_folds(players_before_blinds)` -- the small blind calls or
//! folds, then the big blind calls or folds: after a small-blind fold at node `call`, after a
//! small-blind call at node `bb_overcall`. Otherwise a hand of the top `WAKE_FRACTION` range
//! calls and the blinds take no decision. Both calling means a three-way all-in.
//!
//! Decisions: `push` (P0: fold / push), `sb_call` (P1: fold / call), `call` and `bb_overcall`
//! (P2: fold / call). All-in pots pay raw (pairwise or three-way) equity.
use super::environment::Environment;
use super::hand_class::CLASS_COUNT;
use super::seat::Seat;
use super::spot_params::{field_folds, BIG_BLIND, SMALL_BLIND, WAKE_FRACTION};
use super::tree3::{Node3, Outcome, Tree3};
use super::wake_range::{equity_against, top_membership};
use crate::fault::Fault;
/// Smallest stack for which a jam is a raise at all.
const MIN_DEPTH: f64 = 1.5;
/// Player 0's all-in equity against player `b` for the `Heads` share table.
pub(crate) fn all_in_share(env: &Environment) -> Vec<f64> {
(0..CLASS_COUNT * CLASS_COUNT).map(|k| env.equity.get(k / CLASS_COUNT, k % CLASS_COUNT)).collect()
}
pub(crate) fn needs_two_blinds(seat: Seat) -> Result<(), Fault> {
if seat == Seat::SmallBlind {
Err(Fault::Invalid {
field: "seat".into(),
detail: "the small blind faces only the big blind: use the two-player game".into(),
})
} else {
Ok(())
}
}
pub fn push_fold3_tree(env: &Environment, seat: Seat, depth_bb: f64) -> Result<Tree3, Fault> {
needs_two_blinds(seat)?;
if !depth_bb.is_finite() || depth_bb < MIN_DEPTH {
return Err(Fault::Invalid { field: "depth_bb".into(), detail: "stack must be at least 1.5 bb".into() });
}
let s = depth_bb;
let (sb, bb) = (SMALL_BLIND, BIG_BLIND);
let wake = equity_against(env, &top_membership(env, WAKE_FRACTION));
let r = field_folds(seat.players_before_blinds());
let heads = all_in_share(env);
let mut nodes: Vec<Node3> = Vec::new();
let mut add = |node: Node3| -> usize {
nodes.push(node);
nodes.len() - 1
};
let t_fold = add(Node3::Terminal(Outcome::Flat([0.0, 0.0, 0.0])));
let t_blinds_fold = add(Node3::Terminal(Outcome::Flat([sb + bb, -sb, -bb])));
let t_big_blind_calls =
add(Node3::Terminal(Outcome::Heads { a: 0, b: 2, pot: 2.0 * s + sb, invested: [s, sb, s], share: heads.clone() }));
let t_small_blind_calls =
add(Node3::Terminal(Outcome::Heads { a: 0, b: 1, pot: 2.0 * s + bb, invested: [s, s, bb], share: heads }));
let t_three_way =
add(Node3::Terminal(Outcome::Three { pot: 3.0 * s, invested: [s, s, s], weights: [1.0; 3], spread: 1.0 }));
let call = add(Node3::Decision { player: 2, name: "call", children: vec![t_blinds_fold, t_big_blind_calls] });
let overcall =
add(Node3::Decision { player: 2, name: "bb_overcall", children: vec![t_small_blind_calls, t_three_way] });
let sb_call = add(Node3::Decision { player: 1, name: "sb_call", children: vec![call, overcall] });
let pushed = if r < 1.0 {
let woken = Outcome::Own {
player: 0,
values: wake.iter().map(|e| e * (2.0 * s + sb + bb) - s).collect(),
rest: [0.0, -sb, -bb],
};
let t_woken = add(Node3::Terminal(woken));
add(Node3::Chance(vec![(r, sb_call), (1.0 - r, t_woken)]))
} else {
sb_call
};
let root = add(Node3::Decision { player: 0, name: "push", children: vec![t_fold, pushed] });
Ok(Tree3::new(env, nodes, root))
}
+191 -152
View File
@@ -1,152 +1,191 @@
//! Rust source text of `preflop/generated_charts.rs`: header, convergence table, data.
use super::frozen_spot::{OpenSpot, PushFoldSpot, SpotMeta};
use super::generated_equity;
use super::render_equity::wrapped;
use super::run_plan::{CFR_SEED, OPEN_DEPTHS, PUSH_FOLD_DEPTHS};
use super::spot_params::{
OPEN_SIZE, REALIZATION_OOP_SINGLE_RAISED, REALIZATION_OOP_THREE_BET, REALIZATION_SPREAD,
SMALL_BLIND_OPEN_SIZE, THREE_BET_SIZE, WAKE_FRACTION,
};
fn header() -> String {
format!(
"\
//! GENERATED by `cargo run --release --bin chartgen -- charts > src/preflop/generated_charts.rs`.
//! Do not edit. Frozen output of `crate::cfr`; the equity table is `src/cfr/generated_equity.rs`
//! (`chartgen equity > src/cfr/generated_equity.rs`).
//!
//! Frequencies are permille (0..=1000) per hand class, indexed by `ClassId` of
//! `cfr::hand_class` (13 x 13 grid; pairs on the diagonal, suited above, offsuit below).
//! Layout and meaning of every field: `cfr::frozen_spot`.
//!
//! Abstraction (details in the `cfr` module docs; all numbers in `cfr::spot_params`):
//! - 169 hold'em classes, exact combo weights with card removal between the two players.
//! - Class-vs-class all-in equity: seeded Monte Carlo, `hand::showdown::judge`.
//! - Blinds 0.5 / 1, 6-max, one modelled opponent (the big blind) plus a multiway tax: every
//! player behind the first actor holds a continuing hand (top {wake:.0} % of combos) with
//! probability {wake_p:.2}; if one does, the first actor is simply called by that range.
//! - Push/fold: jam the effective stack or fold; the big blind calls or folds. AOF is the same
//! game (`AOF_PUSH_FOLD` aliases `PUSH_FOLD`; `tests/generated_charts_reproduce.rs` re-solves it
//! under the AOF rules).
//! - Open/call/3-bet: open to {open} bb ({sb_open} bb from the small blind), the big blind folds,
//! calls or 3-bets to {three_bet} bb, the opener folds, calls or jams, the big blind calls or folds
//! the jam. Lines that leave chips behind pay pot x realised share: equity stretched by
//! {spread} around 50 %, then split by position (out of position realises {oop} of its
//! equity against the in-position player, {oop3} in 3-bet pots); all-in lines pay raw equity.
//! - Solver: full-width CFR+ (regret floor 0, alternating players, average strategy weighted by
//! iteration). Exploitability is that of the permille strategy printed here, in micro-bb
//! (1e-6 bb): the sum of both players' best-response gains, as a share of every deal.
//! - Ranges come out wider than 6-max solver charts for EP / MP because only one defender is
//! modelled: read them as relative, abstraction-internal equilibria, not as solver output.
//!
//! Convergence per spot (`iterations`, `stable_since` = argmax chart final from that iteration,
//! exploitability in micro-bb at N/100, N/20, N/5, N/2, N):
//!
",
wake = WAKE_FRACTION * 100.0,
wake_p = WAKE_FRACTION,
open = OPEN_SIZE,
sb_open = SMALL_BLIND_OPEN_SIZE,
three_bet = THREE_BET_SIZE,
spread = REALIZATION_SPREAD,
oop = REALIZATION_OOP_SINGLE_RAISED,
oop3 = REALIZATION_OOP_THREE_BET,
)
}
fn meta_line(label: &str, meta: &SpotMeta) -> String {
let curve: Vec<String> = meta.checkpoints.iter().map(|(_, e)| e.to_string()).collect();
format!(
"//! {label:<10} iterations {:>6} stable_since {:>6} exploitability {}\n",
meta.iterations,
meta.stable_since,
curve.join(" / ")
)
}
fn meta_source(meta: &SpotMeta) -> String {
let points: Vec<String> = meta.checkpoints.iter().map(|(t, e)| format!("({t}, {e})")).collect();
format!(
"SpotMeta {{ iterations: {}, stable_since: {}, checkpoints: [{}], exploitability_micro_bb: {} }}",
meta.iterations,
meta.stable_since,
points.join(", "),
meta.exploitability_micro_bb
)
}
fn row(name: &str, values: &[u16]) -> String {
format!(" {name}: [\n{} ],\n", wrapped(values, 24).lines().map(|l| format!(" {l}\n")).collect::<String>())
}
fn pair_row(name: &str, values: &[[u16; 2]]) -> String {
let flat: Vec<u16> = values.iter().flat_map(|p| p.iter().copied()).collect();
let lines: String = flat
.chunks(24)
.map(|c| {
let items: Vec<String> = c.chunks(2).map(|p| format!("[{}, {}]", p[0], p[1])).collect();
format!(" {},\n", items.join(", "))
})
.collect();
format!(" {name}: [\n{lines} ],\n")
}
fn push_spot_source(s: &PushFoldSpot) -> String {
format!(
" PushFoldSpot {{\n seat: Seat::{:?},\n depth_bb: {},\n{}{} meta: {},\n }},\n",
s.seat,
s.depth_bb,
row("push", &s.push),
row("call", &s.call),
meta_source(&s.meta)
)
}
fn open_spot_source(s: &OpenSpot) -> String {
format!(
" OpenSpot {{\n seat: Seat::{:?},\n depth_bb: {},\n{}{}{}{} meta: {},\n }},\n",
s.seat,
s.depth_bb,
row("open", &s.open),
pair_row("defend", &s.defend),
pair_row("vs_three_bet", &s.vs_three_bet),
row("vs_jam", &s.vs_jam),
meta_source(&s.meta)
)
}
pub fn render_charts(push: &[PushFoldSpot], open: &[OpenSpot]) -> String {
let convergence: String = push
.iter()
.map(|s| meta_line(&format!("push {} {}", s.seat.label(), s.depth_bb), &s.meta))
.chain(open.iter().map(|s| meta_line(&format!("open {} {}", s.seat.label(), s.depth_bb), &s.meta)))
.collect();
let push_body: String = push.iter().map(push_spot_source).collect();
let open_body: String = open.iter().map(open_spot_source).collect();
format!(
"{header}{convergence}//!\n\
//! Equity table: seed {eq_seed}, {eq_samples} samples per class pair. CFR seed {cfr_seed}.\n\n\
use crate::cfr::frozen_spot::{{OpenSpot, PushFoldSpot, SpotMeta}};\n\
use crate::cfr::seat::Seat;\n\n\
pub const EQUITY_SEED: u64 = {eq_seed};\n\
pub const EQUITY_SAMPLES: u32 = {eq_samples};\n\
pub const CFR_SEED: u64 = {cfr_seed};\n\
pub const PUSH_FOLD_DEPTHS: [u8; {nd}] = {push_depths:?};\n\
pub const OPEN_DEPTHS: [u8; {nod}] = {open_depths:?};\n\n\
pub static PUSH_FOLD: [PushFoldSpot; {np}] = [\n{push_body}];\n\n\
pub static OPEN: [OpenSpot; {no}] = [\n{open_body}];\n\n\
/// All-in-or-fold has no other choice than push or fold: the same game, the same tables.\n\
pub static AOF_PUSH_FOLD: &[PushFoldSpot] = &PUSH_FOLD;\n",
header = header(),
eq_seed = generated_equity::SEED,
nd = PUSH_FOLD_DEPTHS.len(),
nod = OPEN_DEPTHS.len(),
push_depths = PUSH_FOLD_DEPTHS,
open_depths = OPEN_DEPTHS,
eq_samples = generated_equity::SAMPLES,
cfr_seed = CFR_SEED,
np = push.len(),
no = open.len(),
)
}
//! Rust source text of `preflop/generated_charts.rs` / `generated_charts_short.rs`: header,
//! convergence table, data.
use super::chart_deck::ChartDeck;
use super::frozen_spot::{OpenSpot, PushFoldSpot, SpotMeta};
use super::render_equity::wrapped;
use super::run_plan::{CFR_SEED, OPEN_DEPTHS, PUSH_FOLD_DEPTHS};
use super::spot_params::{
OPEN_SIZE, REALIZATION_OOP_SINGLE_RAISED, REALIZATION_OOP_THREE_BET, REALIZATION_SPREAD,
SMALL_BLIND_OPEN_SIZE, SMALL_BLIND_THREE_BET_SIZE, THREE_BET_SIZE, WAKE_FRACTION,
};
use super::{generated_equity, generated_equity_short};
fn deck_lines(deck: ChartDeck) -> &'static str {
match deck {
ChartDeck::Full => "//! - 169 hold'em classes of the 52-card deck.\n",
ChartDeck::Short => {
"//! - Short deck: 81 classes of the 36-card deck (six to ace), short deck hand order. The other\n\
//! cells of the 13 x 13 grid are not in the deck and stay 0.\n"
}
}
}
fn header(deck: ChartDeck) -> String {
format!(
"\
//! GENERATED by `cargo run --release --bin chartgen -- charts{arg} > {charts}`.
//! Do not edit. Frozen output of `crate::cfr`; the equity table is `{equity}`
//! (`chartgen equity{arg} > {equity}`).
//!
//! Frequencies are permille (0..=1000) per hand class, indexed by `ClassId` of
//! `cfr::hand_class` (13 x 13 grid; pairs on the diagonal, suited above, offsuit below).
//! Layout and meaning of every field: `cfr::frozen_spot`.
//!
//! Abstraction (details in the `cfr` module docs; all numbers in `cfr::spot_params`):
{deck}\
//! - Exact combo weights with card removal between two players; for three players the deal
//! weight is the product of the three pairwise compatibilities (`cfr::tree3`).
//! - Class-vs-class all-in equity: seeded Monte Carlo, `hand::showdown::judge`. Three-way pots
//! split by the weaker pairwise equity of each hand, normalised (`cfr::three_way`).
//! - Blinds 0.5 / 1, 6-max. EP, MP, CO and BTN face BOTH blinds as players (three-player games);
//! the small blind as first actor faces the big blind. Players between the first actor and the
//! small blind are a multiway tax: each holds a continuing hand (top {wake:.0} % of combos) with
//! probability {wake_p:.2}; if one does, the first actor is simply called by that range.
//! - Push/fold: jam the effective stack or fold; the small blind calls or folds, then the big
//! blind calls or folds (separately after a small-blind fold and call). AOF is the same game
//! (`AOF_PUSH_FOLD` aliases `PUSH_FOLD`).
//! - Open/call/3-bet: open to {open} bb ({sb_open} bb from the small blind). The small blind folds,
//! calls or 3-bets to {sb_three_bet} bb; after its fold the big blind folds, calls or 3-bets to
//! {three_bet} bb, the opener folds, calls or jams, the big blind calls or folds the jam. After
//! the small blind's call the big blind folds or calls (no squeeze); after its 3-bet the big
//! blind folds and the opener folds, calls or jams. Lines that leave chips behind pay pot x
//! realised share: equity stretched by {spread} around the even share, then split by position
//! (out of position realises {oop} of its equity, {oop3} in 3-bet pots); all-in lines pay raw
//! equity.
//! - Solver: full-width CFR+ (regret floor 0, alternating players, average strategy weighted by
//! iteration). Exploitability is that of the permille strategy printed here, in micro-bb
//! (1e-6 bb): the sum of every player's best-response gain, as a share of every deal.
//! - The field behind only calls, so EP / MP still open wider than 6-max solver charts: read the
//! tables as abstraction-internal equilibria, not as solver output.
//!
//! Convergence per spot (`iterations`, `stable_since` = argmax chart final from that iteration,
//! exploitability in micro-bb at N/100, N/20, N/5, N/2, N):
//!
",
arg = deck.deck_argument(),
charts = deck.charts_file(),
equity = deck.equity_file(),
deck = deck_lines(deck),
wake = WAKE_FRACTION * 100.0,
wake_p = WAKE_FRACTION,
open = OPEN_SIZE,
sb_open = SMALL_BLIND_OPEN_SIZE,
sb_three_bet = SMALL_BLIND_THREE_BET_SIZE,
three_bet = THREE_BET_SIZE,
spread = REALIZATION_SPREAD,
oop = REALIZATION_OOP_SINGLE_RAISED,
oop3 = REALIZATION_OOP_THREE_BET,
)
}
fn meta_line(label: &str, meta: &SpotMeta) -> String {
let curve: Vec<String> = meta.checkpoints.iter().map(|(_, e)| e.to_string()).collect();
format!(
"//! {label:<10} iterations {:>6} stable_since {:>6} exploitability {}\n",
meta.iterations,
meta.stable_since,
curve.join(" / ")
)
}
fn meta_source(meta: &SpotMeta) -> String {
let points: Vec<String> = meta.checkpoints.iter().map(|(t, e)| format!("({t}, {e})")).collect();
format!(
"SpotMeta {{ iterations: {}, stable_since: {}, checkpoints: [{}], exploitability_micro_bb: {} }}",
meta.iterations,
meta.stable_since,
points.join(", "),
meta.exploitability_micro_bb
)
}
fn row(name: &str, values: &[u16]) -> String {
format!(" {name}: [\n{} ],\n", wrapped(values, 24).lines().map(|l| format!(" {l}\n")).collect::<String>())
}
fn pair_row(name: &str, values: &[[u16; 2]]) -> String {
let flat: Vec<u16> = values.iter().flat_map(|p| p.iter().copied()).collect();
let lines: String = flat
.chunks(24)
.map(|c| {
let items: Vec<String> = c.chunks(2).map(|p| format!("[{}, {}]", p[0], p[1])).collect();
format!(" {},\n", items.join(", "))
})
.collect();
format!(" {name}: [\n{lines} ],\n")
}
fn push_spot_source(s: &PushFoldSpot) -> String {
format!(
" PushFoldSpot {{\n seat: Seat::{:?},\n depth_bb: {},\n{}{}{}{} meta: {},\n }},\n",
s.seat,
s.depth_bb,
row("push", &s.push),
row("call", &s.call),
row("sb_call", &s.sb_call),
row("bb_overcall", &s.bb_overcall),
meta_source(&s.meta)
)
}
fn open_spot_source(s: &OpenSpot) -> String {
format!(
" OpenSpot {{\n seat: Seat::{:?},\n depth_bb: {},\n{}{}{}{}{}{}{}{} meta: {},\n }},\n",
s.seat,
s.depth_bb,
row("open", &s.open),
pair_row("defend", &s.defend),
pair_row("vs_three_bet", &s.vs_three_bet),
row("vs_jam", &s.vs_jam),
pair_row("sb_defend", &s.sb_defend),
row("bb_overcall", &s.bb_overcall),
pair_row("vs_sb_three_bet", &s.vs_sb_three_bet),
row("sb_vs_jam", &s.sb_vs_jam),
meta_source(&s.meta)
)
}
fn equity_source(deck: ChartDeck) -> (u64, u32) {
match deck {
ChartDeck::Full => (generated_equity::SEED, generated_equity::SAMPLES),
ChartDeck::Short => (generated_equity_short::SEED, generated_equity_short::SAMPLES),
}
}
pub fn render_charts(deck: ChartDeck, push: &[PushFoldSpot], open: &[OpenSpot]) -> String {
let convergence: String = push
.iter()
.map(|s| meta_line(&format!("push {} {}", s.seat.label(), s.depth_bb), &s.meta))
.chain(open.iter().map(|s| meta_line(&format!("open {} {}", s.seat.label(), s.depth_bb), &s.meta)))
.collect();
let push_body: String = push.iter().map(push_spot_source).collect();
let open_body: String = open.iter().map(open_spot_source).collect();
let aof = match deck {
ChartDeck::Full => "\n/// All-in-or-fold has no other choice than push or fold: the same game, the same tables.\n\
pub static AOF_PUSH_FOLD: &[PushFoldSpot] = &PUSH_FOLD;\n",
ChartDeck::Short => "",
};
let (eq_seed, eq_samples) = equity_source(deck);
format!(
"{header}{convergence}//!\n\
//! Equity table: seed {eq_seed}, {eq_samples} samples per class pair. CFR seed {cfr_seed}.\n\n\
use crate::cfr::frozen_spot::{{OpenSpot, PushFoldSpot, SpotMeta}};\n\
use crate::cfr::seat::Seat;\n\n\
pub const EQUITY_SEED: u64 = {eq_seed};\n\
pub const EQUITY_SAMPLES: u32 = {eq_samples};\n\
pub const CFR_SEED: u64 = {cfr_seed};\n\
pub const PUSH_FOLD_DEPTHS: [u8; {nd}] = {push_depths:?};\n\
pub const OPEN_DEPTHS: [u8; {nod}] = {open_depths:?};\n\n\
pub static PUSH_FOLD: [PushFoldSpot; {np}] = [\n{push_body}];\n\n\
pub static OPEN: [OpenSpot; {no}] = [\n{open_body}];\n{aof}",
header = header(deck),
nd = PUSH_FOLD_DEPTHS.len(),
nod = OPEN_DEPTHS.len(),
push_depths = PUSH_FOLD_DEPTHS,
open_depths = OPEN_DEPTHS,
cfr_seed = CFR_SEED,
np = push.len(),
no = open.len(),
)
}
+17 -3
View File
@@ -1,5 +1,6 @@
//! Rust source text of `generated_equity.rs`.
//! Rust source text of `generated_equity.rs` / `generated_equity_short.rs`.
use super::chart_deck::ChartDeck;
use super::equity_matrix::TRIANGLE_LEN;
/// Lines of numbers, `per_line` per line, indented.
@@ -13,11 +14,21 @@ pub fn wrapped(numbers: &[u16], per_line: usize) -> String {
.collect()
}
pub fn render_equity(seed: u64, samples: u32, triangle: &[u16]) -> String {
fn deck_lines(deck: ChartDeck) -> &'static str {
match deck {
ChartDeck::Full => "",
ChartDeck::Short => "//! Deck: 36 cards (six to ace), short deck hand order: flush over full house, A-6-7-8-9 is a\n\
//! straight. Classes with a rank below six are not in the deck and stay 0.\n\
//!\n",
}
}
pub fn render_equity(deck: ChartDeck, seed: u64, samples: u32, triangle: &[u16]) -> String {
format!(
"//! GENERATED by `cargo run --release --bin chartgen -- equity > src/cfr/generated_equity.rs`.\n\
"//! GENERATED by `cargo run --release --bin chartgen -- equity{arg} > {file}`.\n\
//! Do not edit.\n\
//!\n\
{deck}\
//! All-in preflop equity of hand class `i` against class `j` (`i <= j`, row-major over the\n\
//! 13 x 13 class grid of `hand_class`) in 1/10 000, from {samples} seeded Monte-Carlo\n\
//! board runouts per class pair with exact card removal, evaluated by `hand::showdown::judge`.\n\
@@ -26,6 +37,9 @@ pub fn render_equity(seed: u64, samples: u32, triangle: &[u16]) -> String {
pub const SEED: u64 = {seed};\n\
pub const SAMPLES: u32 = {samples};\n\n\
pub static TRIANGLE: [u16; {len}] = [\n{body}];\n",
arg = deck.deck_argument(),
file = deck.equity_file(),
deck = deck_lines(deck),
err = (0.25 / samples.max(1) as f64).sqrt() * 100.0,
len = TRIANGLE_LEN,
body = wrapped(triangle, 24),
+21
View File
@@ -10,8 +10,29 @@ pub const EQUITY_SAMPLES: u32 = 60_000;
/// the result; it is recorded so a sampling variant stays reproducible.
pub const CFR_SEED: u64 = 0x4346_522B;
/// Two-player games (the small blind against the big blind).
pub const PUSH_FOLD_ITERATIONS: u32 = 8_000;
pub const OPEN_ITERATIONS: u32 = 20_000;
/// Three-player games (EP, MP, CO, BTN against both blinds). An iteration costs about 10 ms
/// (push / fold) and 45 ms (open) instead of well below 1 ms.
pub const PUSH_FOLD3_ITERATIONS: u32 = 4_000;
pub const OPEN3_ITERATIONS: u32 = 16_000;
pub fn push_fold_iterations(seat: Seat) -> u32 {
if seat == Seat::SmallBlind {
PUSH_FOLD_ITERATIONS
} else {
PUSH_FOLD3_ITERATIONS
}
}
pub fn open_iterations(seat: Seat) -> u32 {
if seat == Seat::SmallBlind {
OPEN_ITERATIONS
} else {
OPEN3_ITERATIONS
}
}
/// Effective stacks in bb.
pub const PUSH_FOLD_DEPTHS: [u8; 7] = [5, 8, 10, 12, 15, 20, 25];
+65 -59
View File
@@ -1,59 +1,65 @@
//! The five seats the charts distinguish in 6-max. The big blind is always the modelled
//! opponent (caller / defender), so it has no chart of its own as first actor.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Seat {
Early,
Middle,
Cutoff,
Button,
SmallBlind,
}
impl Seat {
pub const ALL: [Seat; 5] = [Seat::Early, Seat::Middle, Seat::Cutoff, Seat::Button, Seat::SmallBlind];
pub fn label(self) -> &'static str {
match self {
Seat::Early => "EP",
Seat::Middle => "MP",
Seat::Cutoff => "CO",
Seat::Button => "BTN",
Seat::SmallBlind => "SB",
}
}
/// Players who still act behind this seat before the big blind: the modelled "field".
pub fn players_behind(self) -> usize {
match self {
Seat::Early => 4,
Seat::Middle => 3,
Seat::Cutoff => 2,
Seat::Button => 1,
Seat::SmallBlind => 0,
}
}
/// Postflop the big blind acts before every seat except the small blind.
pub fn is_in_position_against_big_blind(self) -> bool {
self != Seat::SmallBlind
}
pub fn posted_blind(self) -> f64 {
if self == Seat::SmallBlind {
super::spot_params::SMALL_BLIND
} else {
0.0
}
}
/// Money in the pot from players that fold in the modelled line (the small blind when
/// somebody else is the first actor).
pub fn dead_money(self) -> f64 {
if self == Seat::SmallBlind {
0.0
} else {
super::spot_params::SMALL_BLIND
}
}
}
//! The five seats the charts distinguish in 6-max. The big blind is always the modelled
//! opponent (caller / defender), so it has no chart of its own as first actor.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Seat {
Early,
Middle,
Cutoff,
Button,
SmallBlind,
}
impl Seat {
pub const ALL: [Seat; 5] = [Seat::Early, Seat::Middle, Seat::Cutoff, Seat::Button, Seat::SmallBlind];
pub fn label(self) -> &'static str {
match self {
Seat::Early => "EP",
Seat::Middle => "MP",
Seat::Cutoff => "CO",
Seat::Button => "BTN",
Seat::SmallBlind => "SB",
}
}
/// Players who still act behind this seat before the big blind: the modelled "field".
pub fn players_behind(self) -> usize {
match self {
Seat::Early => 4,
Seat::Middle => 3,
Seat::Cutoff => 2,
Seat::Button => 1,
Seat::SmallBlind => 0,
}
}
/// Players between this seat and the small blind: the field of the three-player games, where
/// both blinds are modelled players.
pub fn players_before_blinds(self) -> usize {
self.players_behind().saturating_sub(1)
}
/// Postflop the big blind acts before every seat except the small blind.
pub fn is_in_position_against_big_blind(self) -> bool {
self != Seat::SmallBlind
}
pub fn posted_blind(self) -> f64 {
if self == Seat::SmallBlind {
super::spot_params::SMALL_BLIND
} else {
0.0
}
}
/// Money in the pot from players that fold in the modelled line (the small blind when
/// somebody else is the first actor).
pub fn dead_money(self) -> f64 {
if self == Seat::SmallBlind {
0.0
} else {
super::spot_params::SMALL_BLIND
}
}
}
+67 -69
View File
@@ -1,69 +1,67 @@
//! Run CFR+ for a fixed number of iterations and record how it converged.
//!
//! Two records, both about the average strategy:
//! - `checkpoints`: exploitability (in payoff units) at five iteration counts,
//! `N/100, N/20, N/5, N/2, N` (the last one is always `N`);
//! - `stable_since`: the argmax chart (`chart_signature`, permille-rounded) is sampled every
//! `N/200` iterations (at least every iteration); `stable_since` is the first sampled
//! iteration from which every later sample equals the final chart. A chart that only settles
//! at the very end reports `N`.
use super::chart_signature::signature;
use super::exploitability::exploitability;
use super::iterate::iterate;
use super::solver_state::SolverState;
use super::strategy::{average_strategy, Strategy};
use super::tree::Tree;
use crate::rng::Rng;
#[derive(Clone, Debug, PartialEq)]
pub struct Solved {
pub iterations: u32,
pub strategy: Strategy,
/// Five `(iteration, exploitability)` pairs.
pub checkpoints: Vec<(u32, f64)>,
pub stable_since: u32,
pub final_exploitability: f64,
}
fn checkpoint_iterations(n: u32) -> [u32; 5] {
[n / 100, n / 20, n / 5, n / 2, n].map(|k| k.max(1).min(n.max(1)))
}
pub fn solve(tree: &Tree, iterations: u32, rng: Rng) -> Solved {
let stride = (iterations / 200).max(1);
let marks = checkpoint_iterations(iterations);
let start = (SolverState::fresh(tree), rng, Vec::new(), Vec::new());
let (state, _, samples, curve) = (1..=iterations).fold(start, |(state, rng, mut samples, mut curve), t| {
let (state, rng) = iterate(tree, state, rng);
let sampled = t % stride == 0 || t == iterations;
let marked = marks.contains(&t);
if sampled || marked {
let average = average_strategy(tree, &state);
if sampled {
samples.push((t, signature(&average)));
}
if marked {
curve.push((t, exploitability(tree, &average)));
}
}
(state, rng, samples, curve)
});
let strategy = average_strategy(tree, &state);
let final_exploitability = exploitability(tree, &strategy);
let checkpoints: Vec<(u32, f64)> = marks
.iter()
.map(|m| curve.iter().find(|(t, _)| t == m).copied().unwrap_or((*m, final_exploitability)))
.collect();
let final_chart = samples.last().map(|(_, s): &(u32, Vec<u8>)| s.clone());
let stable_since = match final_chart {
Some(chart) => samples
.iter()
.rev()
.take_while(|(_, s)| *s == chart)
.last()
.map_or(iterations, |(t, _)| *t),
None => iterations,
};
Solved { iterations, strategy, checkpoints, stable_since, final_exploitability }
}
//! Run CFR+ for a fixed number of iterations and record how it converged.
//!
//! Two records, both about the average strategy:
//! - `checkpoints`: exploitability (in payoff units) at five iteration counts,
//! `N/100, N/20, N/5, N/2, N` (the last one is always `N`);
//! - `stable_since`: the argmax chart (`chart_signature`, permille-rounded) is sampled every
//! `N/200` iterations (at least every iteration); `stable_since` is the first sampled
//! iteration from which every later sample equals the final chart. A chart that only settles
//! at the very end reports `N`.
use super::chart_signature::signature;
use super::game::Game;
use super::solver_state::SolverState;
use super::strategy::{average_strategy, Strategy};
use crate::rng::Rng;
#[derive(Clone, Debug, PartialEq)]
pub struct Solved {
pub iterations: u32,
pub strategy: Strategy,
/// Five `(iteration, exploitability)` pairs.
pub checkpoints: Vec<(u32, f64)>,
pub stable_since: u32,
pub final_exploitability: f64,
}
fn checkpoint_iterations(n: u32) -> [u32; 5] {
[n / 100, n / 20, n / 5, n / 2, n].map(|k| k.max(1).min(n.max(1)))
}
pub fn solve<G: Game + ?Sized>(tree: &G, iterations: u32, rng: Rng) -> Solved {
let stride = (iterations / 200).max(1);
let marks = checkpoint_iterations(iterations);
let start = (SolverState::fresh(tree), rng, Vec::new(), Vec::new());
let (state, _, samples, curve) = (1..=iterations).fold(start, |(state, rng, mut samples, mut curve), t| {
let (state, rng) = tree.step(state, rng);
let sampled = t % stride == 0 || t == iterations;
let marked = marks.contains(&t);
if sampled || marked {
let average = average_strategy(tree, &state);
if sampled {
samples.push((t, signature(&average)));
}
if marked {
curve.push((t, tree.exploitability(&average)));
}
}
(state, rng, samples, curve)
});
let strategy = average_strategy(tree, &state);
let final_exploitability = tree.exploitability(&strategy);
let checkpoints: Vec<(u32, f64)> = marks
.iter()
.map(|m| curve.iter().find(|(t, _)| t == m).copied().unwrap_or((*m, final_exploitability)))
.collect();
let final_chart = samples.last().map(|(_, s): &(u32, Vec<u8>)| s.clone());
let stable_since = match final_chart {
Some(chart) => samples
.iter()
.rev()
.take_while(|(_, s)| *s == chart)
.last()
.map_or(iterations, |(t, _)| *t),
None => iterations,
};
Solved { iterations, strategy, checkpoints, stable_since, final_exploitability }
}
+42 -45
View File
@@ -1,45 +1,42 @@
//! Everything CFR+ remembers between iterations, as one value.
use super::tree::{Node, Tree};
#[derive(Clone, Debug, PartialEq)]
pub struct SolverState {
iteration: u32,
/// Per node `[class * actions + action]`; empty for non-decision nodes.
regret: Vec<Vec<f64>>,
strategy_sum: Vec<Vec<f64>>,
}
impl SolverState {
pub fn fresh(tree: &Tree) -> SolverState {
let zeros: Vec<Vec<f64>> = tree
.nodes
.iter()
.map(|n| match n {
Node::Decision { children, .. } => vec![0.0; tree.classes * children.len()],
_ => Vec::new(),
})
.collect();
SolverState { iteration: 0, regret: zeros.clone(), strategy_sum: zeros }
}
pub fn iteration(&self) -> u32 {
self.iteration
}
pub fn regret(&self, node: usize) -> &[f64] {
self.regret.get(node).map_or(&[], |r| r.as_slice())
}
pub fn strategy_sum(&self, node: usize) -> &[f64] {
self.strategy_sum.get(node).map_or(&[], |r| r.as_slice())
}
pub(crate) fn into_parts(self) -> (u32, Vec<Vec<f64>>, Vec<Vec<f64>>) {
(self.iteration, self.regret, self.strategy_sum)
}
pub(crate) fn from_parts(iteration: u32, regret: Vec<Vec<f64>>, strategy_sum: Vec<Vec<f64>>) -> SolverState {
SolverState { iteration, regret, strategy_sum }
}
}
//! Everything CFR+ remembers between iterations, as one value.
use super::game::Game;
#[derive(Clone, Debug, PartialEq)]
pub struct SolverState {
iteration: u32,
/// Per node `[class * actions + action]`; empty for non-decision nodes.
regret: Vec<Vec<f64>>,
strategy_sum: Vec<Vec<f64>>,
}
impl SolverState {
pub fn fresh<G: Game + ?Sized>(tree: &G) -> SolverState {
let zeros: Vec<Vec<f64>> = tree
.action_counts()
.iter()
.map(|a| vec![0.0; tree.classes() * a])
.collect();
SolverState { iteration: 0, regret: zeros.clone(), strategy_sum: zeros }
}
pub fn iteration(&self) -> u32 {
self.iteration
}
pub fn regret(&self, node: usize) -> &[f64] {
self.regret.get(node).map_or(&[], |r| r.as_slice())
}
pub fn strategy_sum(&self, node: usize) -> &[f64] {
self.strategy_sum.get(node).map_or(&[], |r| r.as_slice())
}
pub(crate) fn into_parts(self) -> (u32, Vec<Vec<f64>>, Vec<Vec<f64>>) {
(self.iteration, self.regret, self.strategy_sum)
}
pub(crate) fn from_parts(iteration: u32, regret: Vec<Vec<f64>>, strategy_sum: Vec<Vec<f64>>) -> SolverState {
SolverState { iteration, regret, strategy_sum }
}
}
+4
View File
@@ -13,6 +13,10 @@ pub const SMALL_BLIND_OPEN_SIZE: f64 = 3.0;
/// The big blind's 3-bet (raise-to, in bb) against every open.
pub const THREE_BET_SIZE: f64 = 9.0;
/// The small blind's 3-bet (raise-to, in bb) in the three-player games: bigger than the big
/// blind's because the small blind plays the pot out of position.
pub const SMALL_BLIND_THREE_BET_SIZE: f64 = 11.0;
/// Out-of-position realisation in single-raised pots (three streets left): the out-of-position
/// player's stretched equity (see `REALIZATION_SPREAD`) counts only 0.85 against the in-position
/// player's 1.0, and the pot is split in proportion -- `share_ip = e_ip / (e_ip + R * e_oop)` --
+95 -31
View File
@@ -1,13 +1,22 @@
//! Solve one spot end to end and freeze it: build the tree, run CFR+, round to permille, measure
//! the exploitability of the rounded strategy that is actually shipped.
//!
//! The small blind as first actor plays the two-player games against the big blind; every other
//! seat plays the three-player games against both blinds. Classes that do not exist in the deck
//! are frozen as 0 (they are never dealt, so this changes no value).
use super::environment::Environment;
use super::exploitability::exploitability;
use super::frozen_spot::{OpenSpot, PushFoldSpot, SpotMeta};
use super::frozen_strategy::{binary_row, open_strategy, push_fold_strategy, ternary_row};
use super::frozen_strategy::{
binary_row, open3_strategy, open_strategy, push_fold3_strategy, push_fold_strategy, ternary_row,
};
use super::game::Game;
use super::hand_class::{class_exists, CLASS_COUNT};
use super::open3_game::open3_tree;
use super::open_game::open_tree;
use super::push_fold3_game::push_fold3_tree;
use super::push_fold_game::push_fold_tree;
use super::run_plan::{CFR_SEED, OPEN_ITERATIONS, PUSH_FOLD_ITERATIONS};
use super::run_plan::{open_iterations, push_fold_iterations, CFR_SEED};
use super::seat::Seat;
use super::solve::{solve, Solved};
use crate::fault::Fault;
@@ -31,8 +40,61 @@ fn meta(solved: &Solved, frozen_exploitability: f64) -> SpotMeta {
}
}
/// Rows of a two-action node, or all zero when the game has no such node.
fn binary_or_zero<G: Game>(tree: &G, solved: &Solved, name: &str) -> Result<[u16; CLASS_COUNT], Fault> {
match tree.decision(name) {
Some(_) => binary_row(tree, &solved.strategy, name),
None => Ok([0; CLASS_COUNT]),
}
}
fn ternary_or_zero<G: Game>(tree: &G, solved: &Solved, name: &str) -> Result<[[u16; 2]; CLASS_COUNT], Fault> {
match tree.decision(name) {
Some(_) => ternary_row(tree, &solved.strategy, name),
None => Ok([[0; 2]; CLASS_COUNT]),
}
}
fn masked<T: Copy + Default>(env: &Environment, row: [T; CLASS_COUNT]) -> [T; CLASS_COUNT] {
let mut out = row;
for (class, slot) in out.iter_mut().enumerate() {
if !class_exists(env.rules.deck, class) {
*slot = T::default();
}
}
out
}
fn push_fold_rows<G: Game>(env: &Environment, tree: &G, solved: &Solved, seat: Seat, depth_bb: u8) -> Result<PushFoldSpot, Fault> {
Ok(PushFoldSpot {
seat,
depth_bb,
push: masked(env, binary_or_zero(tree, solved, "push")?),
call: masked(env, binary_or_zero(tree, solved, "call")?),
sb_call: masked(env, binary_or_zero(tree, solved, "sb_call")?),
bb_overcall: masked(env, binary_or_zero(tree, solved, "bb_overcall")?),
meta: meta(solved, 0.0),
})
}
fn open_rows<G: Game>(env: &Environment, tree: &G, solved: &Solved, seat: Seat, depth_bb: u8) -> Result<OpenSpot, Fault> {
Ok(OpenSpot {
seat,
depth_bb,
open: masked(env, binary_or_zero(tree, solved, "open")?),
defend: masked(env, ternary_or_zero(tree, solved, "defend")?),
vs_three_bet: masked(env, ternary_or_zero(tree, solved, "vs_three_bet")?),
vs_jam: masked(env, binary_or_zero(tree, solved, "vs_jam")?),
sb_defend: masked(env, ternary_or_zero(tree, solved, "sb_defend")?),
bb_overcall: masked(env, binary_or_zero(tree, solved, "bb_overcall")?),
vs_sb_three_bet: masked(env, ternary_or_zero(tree, solved, "vs_sb_three_bet")?),
sb_vs_jam: masked(env, binary_or_zero(tree, solved, "sb_vs_jam")?),
meta: meta(solved, 0.0),
})
}
pub fn solve_push_fold_spot(env: &Environment, seat: Seat, depth_bb: u8) -> Result<PushFoldSpot, Fault> {
solve_push_fold_spot_for(env, seat, depth_bb, PUSH_FOLD_ITERATIONS)
solve_push_fold_spot_for(env, seat, depth_bb, push_fold_iterations(seat))
}
pub fn solve_push_fold_spot_for(
@@ -41,22 +103,24 @@ pub fn solve_push_fold_spot_for(
depth_bb: u8,
iterations: u32,
) -> Result<PushFoldSpot, Fault> {
let tree = push_fold_tree(env, seat, depth_bb as f64)?;
let solved = solve(&tree, iterations, Rng::seeded(CFR_SEED));
let mut spot = PushFoldSpot {
seat,
depth_bb,
push: binary_row(&tree, &solved.strategy, "push")?,
call: binary_row(&tree, &solved.strategy, "call")?,
meta: meta(&solved, 0.0),
};
let frozen = exploitability(&tree, &push_fold_strategy(&tree, &spot)?);
spot.meta = meta(&solved, frozen);
Ok(spot)
let rng = Rng::seeded(CFR_SEED);
if seat == Seat::SmallBlind {
let tree = push_fold_tree(env, seat, depth_bb as f64)?;
let solved = solve(&tree, iterations, rng);
let mut spot = push_fold_rows(env, &tree, &solved, seat, depth_bb)?;
spot.meta = meta(&solved, tree.exploitability(&push_fold_strategy(&tree, &spot)?));
Ok(spot)
} else {
let tree = push_fold3_tree(env, seat, depth_bb as f64)?;
let solved = solve(&tree, iterations, rng);
let mut spot = push_fold_rows(env, &tree, &solved, seat, depth_bb)?;
spot.meta = meta(&solved, tree.exploitability(&push_fold3_strategy(&tree, &spot)?));
Ok(spot)
}
}
pub fn solve_open_spot(env: &Environment, seat: Seat, depth_bb: u8) -> Result<OpenSpot, Fault> {
solve_open_spot_for(env, seat, depth_bb, OPEN_ITERATIONS)
solve_open_spot_for(env, seat, depth_bb, open_iterations(seat))
}
pub fn solve_open_spot_for(
@@ -65,18 +129,18 @@ pub fn solve_open_spot_for(
depth_bb: u8,
iterations: u32,
) -> Result<OpenSpot, Fault> {
let tree = open_tree(env, seat, depth_bb as f64)?;
let solved = solve(&tree, iterations, Rng::seeded(CFR_SEED));
let mut spot = OpenSpot {
seat,
depth_bb,
open: binary_row(&tree, &solved.strategy, "open")?,
defend: ternary_row(&tree, &solved.strategy, "defend")?,
vs_three_bet: ternary_row(&tree, &solved.strategy, "vs_three_bet")?,
vs_jam: binary_row(&tree, &solved.strategy, "vs_jam")?,
meta: meta(&solved, 0.0),
};
let frozen = exploitability(&tree, &open_strategy(&tree, &spot)?);
spot.meta = meta(&solved, frozen);
Ok(spot)
let rng = Rng::seeded(CFR_SEED);
if seat == Seat::SmallBlind {
let tree = open_tree(env, seat, depth_bb as f64)?;
let solved = solve(&tree, iterations, rng);
let mut spot = open_rows(env, &tree, &solved, seat, depth_bb)?;
spot.meta = meta(&solved, tree.exploitability(&open_strategy(&tree, &spot)?));
Ok(spot)
} else {
let tree = open3_tree(env, seat, depth_bb as f64)?;
let solved = solve(&tree, iterations, rng);
let mut spot = open_rows(env, &tree, &solved, seat, depth_bb)?;
spot.meta = meta(&solved, tree.exploitability(&open3_strategy(&tree, &spot)?));
Ok(spot)
}
}
+139 -148
View File
@@ -1,148 +1,139 @@
//! A behaviour strategy: for every decision node and hand class a probability per action.
use super::regret_matching::matched;
use super::solver_state::SolverState;
use super::tree::{Node, Tree};
use crate::fault::Fault;
#[derive(Clone, Debug, PartialEq)]
pub struct Strategy {
classes: usize,
actions: Vec<usize>,
probs: Vec<Vec<f64>>,
}
fn actions_of(tree: &Tree) -> Vec<usize> {
tree.nodes
.iter()
.map(|n| match n {
Node::Decision { children, .. } => children.len(),
_ => 0,
})
.collect()
}
impl Strategy {
/// Every action equally likely everywhere.
pub fn uniform(tree: &Tree) -> Strategy {
let actions = actions_of(tree);
let probs = actions
.iter()
.map(|a| if *a == 0 { Vec::new() } else { vec![1.0 / *a as f64; tree.classes * *a] })
.collect();
Strategy { classes: tree.classes, actions, probs }
}
/// The same action for each class at every decision node: `choose(node name, class)`.
pub fn pure(tree: &Tree, choose: impl Fn(&str, usize) -> usize) -> Strategy {
let base = Strategy::uniform(tree);
tree.nodes.iter().enumerate().fold(base, |s, (index, node)| match node {
Node::Decision { name, .. } => s.replaced(index, |class| pure_row(s.actions[index], choose(name, class))),
_ => s,
})
}
/// Copy with the named node replaced by a pure choice per class (no-op if the name is unknown).
pub fn with_pure(&self, tree: &Tree, name: &str, choose: impl Fn(usize) -> usize) -> Strategy {
match tree.find(name) {
Some(index) => self.replaced(index, |class| pure_row(self.actions[index], choose(class))),
None => self.clone(),
}
}
/// Copy with the named node replaced by explicit rows (`row(class)` = one probability per action).
pub fn with_rows(
&self,
tree: &Tree,
name: &str,
row: impl Fn(usize) -> Vec<f64>,
) -> Result<Strategy, Fault> {
let index = tree
.find(name)
.ok_or_else(|| Fault::Missing(format!("decision node {name}")))?;
let width = self.actions.get(index).copied().unwrap_or(0);
let rows: Vec<Vec<f64>> = (0..self.classes).map(&row).collect();
if rows.iter().any(|r| r.len() != width) {
return Err(Fault::Invalid { field: name.into(), detail: "wrong number of actions".into() });
}
Ok(self.replaced(index, |class| rows[class].clone()))
}
fn replaced(&self, index: usize, row: impl Fn(usize) -> Vec<f64>) -> Strategy {
let mut probs = self.probs.clone();
probs[index] = (0..self.classes).flat_map(row).collect();
Strategy { classes: self.classes, actions: self.actions.clone(), probs }
}
pub fn classes(&self) -> usize {
self.classes
}
pub fn node_count(&self) -> usize {
self.actions.len()
}
pub fn action_count(&self, node: usize) -> usize {
self.actions.get(node).copied().unwrap_or(0)
}
/// Probabilities of one class at one node (empty when not a decision node).
pub fn row(&self, node: usize, class: usize) -> &[f64] {
let width = self.action_count(node);
self.probs
.get(node)
.and_then(|p| p.get(class * width..(class + 1) * width))
.unwrap_or(&[])
}
pub fn probability(&self, node: usize, class: usize, action: usize) -> f64 {
self.row(node, class).get(action).copied().unwrap_or(0.0)
}
}
fn pure_row(width: usize, action: usize) -> Vec<f64> {
(0..width).map(|a| if a == action.min(width.saturating_sub(1)) { 1.0 } else { 0.0 }).collect()
}
/// Current strategy by regret matching (the last iterate, not the average).
pub fn current_strategy(tree: &Tree, state: &SolverState) -> Strategy {
let actions = actions_of(tree);
let probs = actions
.iter()
.enumerate()
.map(|(node, a)| match state.regret(node) {
regrets if *a > 0 => matched(regrets, *a),
_ => Vec::new(),
})
.collect();
Strategy { classes: tree.classes, actions, probs }
}
/// The average strategy (weighted by iteration and own reach). A class that never reached a node
/// falls back to the current regret-matching strategy there.
pub fn average_strategy(tree: &Tree, state: &SolverState) -> Strategy {
let current = current_strategy(tree, state);
let probs = current
.actions
.iter()
.enumerate()
.map(|(node, a)| {
let sums = state.strategy_sum(node);
if *a == 0 {
return Vec::new();
}
(0..tree.classes)
.flat_map(|class| {
let row = sums.get(class * a..(class + 1) * a).unwrap_or(&[]);
let total: f64 = row.iter().sum();
if total > 0.0 {
row.iter().map(|x| x / total).collect::<Vec<f64>>()
} else {
current.row(node, class).to_vec()
}
})
.collect()
})
.collect();
Strategy { classes: tree.classes, actions: current.actions, probs }
}
//! A behaviour strategy: for every decision node and hand class a probability per action.
use super::game::Game;
use super::regret_matching::matched;
use super::solver_state::SolverState;
use crate::fault::Fault;
#[derive(Clone, Debug, PartialEq)]
pub struct Strategy {
classes: usize,
actions: Vec<usize>,
probs: Vec<Vec<f64>>,
}
impl Strategy {
/// Every action equally likely everywhere.
pub fn uniform<G: Game + ?Sized>(tree: &G) -> Strategy {
let actions = tree.action_counts();
let probs = actions
.iter()
.map(|a| if *a == 0 { Vec::new() } else { vec![1.0 / *a as f64; tree.classes() * *a] })
.collect();
Strategy { classes: tree.classes(), actions, probs }
}
/// The same action for each class at every decision node: `choose(node name, class)`.
pub fn pure<G: Game + ?Sized>(tree: &G, choose: impl Fn(&str, usize) -> usize) -> Strategy {
let base = Strategy::uniform(tree);
(0..base.actions.len()).fold(base, |s, index| match tree.decision_name(index) {
Some(name) => s.replaced(index, |class| pure_row(s.actions[index], choose(name, class))),
None => s,
})
}
/// Copy with the named node replaced by a pure choice per class (no-op if the name is unknown).
pub fn with_pure<G: Game + ?Sized>(&self, tree: &G, name: &str, choose: impl Fn(usize) -> usize) -> Strategy {
match tree.decision(name) {
Some(index) => self.replaced(index, |class| pure_row(self.actions[index], choose(class))),
None => self.clone(),
}
}
/// Copy with the named node replaced by explicit rows (`row(class)` = one probability per action).
pub fn with_rows<G: Game + ?Sized>(
&self,
tree: &G,
name: &str,
row: impl Fn(usize) -> Vec<f64>,
) -> Result<Strategy, Fault> {
let index = tree
.decision(name)
.ok_or_else(|| Fault::Missing(format!("decision node {name}")))?;
let width = self.actions.get(index).copied().unwrap_or(0);
let rows: Vec<Vec<f64>> = (0..self.classes).map(&row).collect();
if rows.iter().any(|r| r.len() != width) {
return Err(Fault::Invalid { field: name.into(), detail: "wrong number of actions".into() });
}
Ok(self.replaced(index, |class| rows[class].clone()))
}
fn replaced(&self, index: usize, row: impl Fn(usize) -> Vec<f64>) -> Strategy {
let mut probs = self.probs.clone();
probs[index] = (0..self.classes).flat_map(row).collect();
Strategy { classes: self.classes, actions: self.actions.clone(), probs }
}
pub fn classes(&self) -> usize {
self.classes
}
pub fn node_count(&self) -> usize {
self.actions.len()
}
pub fn action_count(&self, node: usize) -> usize {
self.actions.get(node).copied().unwrap_or(0)
}
/// Probabilities of one class at one node (empty when not a decision node).
pub fn row(&self, node: usize, class: usize) -> &[f64] {
let width = self.action_count(node);
self.probs
.get(node)
.and_then(|p| p.get(class * width..(class + 1) * width))
.unwrap_or(&[])
}
pub fn probability(&self, node: usize, class: usize, action: usize) -> f64 {
self.row(node, class).get(action).copied().unwrap_or(0.0)
}
}
fn pure_row(width: usize, action: usize) -> Vec<f64> {
(0..width).map(|a| if a == action.min(width.saturating_sub(1)) { 1.0 } else { 0.0 }).collect()
}
/// Current strategy by regret matching (the last iterate, not the average).
pub fn current_strategy<G: Game + ?Sized>(tree: &G, state: &SolverState) -> Strategy {
let actions = tree.action_counts();
let probs = actions
.iter()
.enumerate()
.map(|(node, a)| match state.regret(node) {
regrets if *a > 0 => matched(regrets, *a),
_ => Vec::new(),
})
.collect();
Strategy { classes: tree.classes(), actions, probs }
}
/// The average strategy (weighted by iteration and own reach). A class that never reached a node
/// falls back to the current regret-matching strategy there.
pub fn average_strategy<G: Game + ?Sized>(tree: &G, state: &SolverState) -> Strategy {
let current = current_strategy(tree, state);
let probs = current
.actions
.iter()
.enumerate()
.map(|(node, a)| {
let sums = state.strategy_sum(node);
if *a == 0 {
return Vec::new();
}
(0..tree.classes())
.flat_map(|class| {
let row = sums.get(class * a..(class + 1) * a).unwrap_or(&[]);
let total: f64 = row.iter().sum();
if total > 0.0 {
row.iter().map(|x| x / total).collect::<Vec<f64>>()
} else {
current.row(node, class).to_vec()
}
})
.collect()
})
.collect();
Strategy { classes: tree.classes(), actions: current.actions, probs }
}
+37
View File
@@ -0,0 +1,37 @@
//! Pot shares of a three-way showdown from the pairwise equities (no three-way table exists).
//!
//! 1. Raw share of each hand: the weaker of its two pairwise equities, then normalised. A hand
//! wins the pot only by beating its strongest rival, and the chances of beating both are
//! strongly correlated (QQ against AA and KK needs a queen either way), so the minimum is a
//! better estimate than the product. `tests/cfr_three_way.rs` measures the error against
//! Monte Carlo.
//! 2. Realisation (pots with chips behind): every share is stretched around 1/3 by `spread`,
//! clamped to `[0, 1]`, weighted by the player's position factor (1.0 in position,
//! `REALIZATION_OOP_SINGLE_RAISED` out of position) and normalised again. All-in pots use
//! `spread` 1 and equal weights, i.e. the raw shares.
//!
//! The shares always sum to 1, so the payoffs stay zero-sum.
/// `equity[x][y]` = all-in equity of player `x`'s hand against player `y`'s.
pub fn three_way_shares(equity: [[f64; 3]; 3], weights: [f64; 3], spread: f64) -> [f64; 3] {
let raw = [
equity[0][1].min(equity[0][2]).max(0.0),
equity[1][0].min(equity[1][2]).max(0.0),
equity[2][0].min(equity[2][1]).max(0.0),
];
let shares = normalised(raw);
let realised = [0, 1, 2].map(|x| {
let stretched = (1.0 / 3.0 + spread * (shares[x] - 1.0 / 3.0)).clamp(0.0, 1.0);
stretched * weights[x].max(0.0)
});
normalised(realised)
}
fn normalised(v: [f64; 3]) -> [f64; 3] {
let total: f64 = v.iter().sum();
if total > 0.0 && total.is_finite() {
v.map(|x| x / total)
} else {
[1.0 / 3.0; 3]
}
}
+128
View File
@@ -0,0 +1,128 @@
//! A three-player game as data: the same public tree as `tree` (decision nodes are played per
//! hand class), with a payoff for every player at each leaf and chance weights over class triples.
//!
//! **Deal weights.** `P(i, j, k) = g(i, j) * g(i, k) * g(j, k) / norm` with
//! `g(i, j) = disjoint combo pairs (i, j) / sqrt(combos(i) * combos(j))`. Card removal between any
//! two players is exact; an overlap of all three hands (AK, AQ, AJ share the ace) is approximated
//! by the product of the pairwise compatibilities. The weight is symmetric in the three classes.
//!
//! **Three-way showdowns** use the pairwise equity matrix (`three_way_shares`): no three-way
//! equity table is generated.
use super::environment::Environment;
use super::hand_class::CLASS_COUNT;
use super::three_way::three_way_shares;
#[derive(Clone, Debug, PartialEq)]
pub enum Outcome {
/// Every player's result is fixed.
Flat([f64; 3]),
/// `player`'s result depends on its own class (`values`), the others get `rest`.
Own { player: usize, values: Vec<f64>, rest: [f64; 3] },
/// Showdown between `a` and `b`: `a` receives `pot * share[i_a * classes + i_b]`, `b` the rest
/// of the pot; every player's own `invested` chips are subtracted (the third player folded).
Heads { a: usize, b: usize, pot: f64, invested: [f64; 3], share: Vec<f64> },
/// Three-way showdown: the pot is split by `three_way_shares` with the realisation `weights`
/// and `spread` (all-in: weights 1, spread 1).
Three { pot: f64, invested: [f64; 3], weights: [f64; 3], spread: f64 },
}
#[derive(Clone, Debug, PartialEq)]
pub enum Node3 {
Decision { player: usize, name: &'static str, children: Vec<usize> },
/// Branches `(probability, child)`; probabilities should sum to 1.
Chance(Vec<(f64, usize)>),
Terminal(Outcome),
}
#[derive(Clone, Debug, PartialEq)]
pub struct Tree3 {
pub classes: usize,
/// `g(i, j)`, row-major, symmetric.
pub pair: Vec<f64>,
/// Sum of `g(i, j) g(i, k) g(j, k)` over all triples.
pub norm: f64,
/// Pairwise all-in equity `e(i, j)`, row-major.
pub equity: Vec<f64>,
pub nodes: Vec<Node3>,
pub root: usize,
}
/// `g` and its normaliser for the deck of `env`.
pub fn triple_weights(env: &Environment) -> (Vec<f64>, f64) {
let n = CLASS_COUNT;
let combos: Vec<f64> = (0..n).map(|c| env.chance.combos(c) as f64).collect();
let pair: Vec<f64> = (0..n * n)
.map(|k| {
let (i, j) = (k / n, k % n);
let scale = (combos[i] * combos[j]).sqrt();
if scale > 0.0 {
env.chance.disjoint_combos(i, j) as f64 / scale
} else {
0.0
}
})
.collect();
let norm = (0..n)
.map(|i| {
let row_i = &pair[i * n..(i + 1) * n];
(0..n)
.map(|j| {
let row_j = &pair[j * n..(j + 1) * n];
row_i[j] * row_i.iter().zip(row_j).map(|(a, b)| a * b).sum::<f64>()
})
.sum::<f64>()
})
.sum();
(pair, norm)
}
impl Tree3 {
pub fn new(env: &Environment, nodes: Vec<Node3>, root: usize) -> Tree3 {
let (pair, norm) = triple_weights(env);
let n = CLASS_COUNT;
let equity = (0..n * n).map(|k| env.equity.get(k / n, k % n)).collect();
Tree3 { classes: n, pair, norm, equity, nodes, root }
}
/// Probability of the deal `(i, j, k)` (any order of the players).
pub fn weight(&self, i: usize, j: usize, k: usize) -> f64 {
let n = self.classes;
if i >= n || j >= n || k >= n || self.norm <= 0.0 {
return 0.0;
}
self.pair[i * n + j] * self.pair[i * n + k] * self.pair[j * n + k] / self.norm
}
/// Every player's result at a leaf for the classes `c` (indexed by player).
pub fn payoff(&self, outcome: &Outcome, c: [usize; 3]) -> [f64; 3] {
let n = self.classes;
match outcome {
Outcome::Flat(u) => *u,
Outcome::Own { player, values, rest } => {
let mut u = *rest;
if let Some(slot) = u.get_mut(*player) {
*slot = values.get(c[*player]).copied().unwrap_or(0.0);
}
u
}
Outcome::Heads { a, b, pot, invested, share } => {
let s = share.get(c[*a] * n + c[*b]).copied().unwrap_or(0.5);
let mut u = invested.map(|x| -x);
u[*a] += pot * s;
u[*b] += pot * (1.0 - s);
u
}
Outcome::Three { pot, invested, weights, spread } => {
let e = |x: usize, y: usize| self.equity[c[x] * n + c[y]];
let shares = three_way_shares([[0.5, e(0, 1), e(0, 2)], [e(1, 0), 0.5, e(1, 2)], [e(2, 0), e(2, 1), 0.5]], *weights, *spread);
[0, 1, 2].map(|p| pot * shares[p] - invested[p])
}
}
}
/// The tree can be traversed.
pub fn is_playable(&self) -> bool {
self.classes > 0 && self.pair.len() == self.classes * self.classes && self.root < self.nodes.len()
}
}
+259
View File
@@ -0,0 +1,259 @@
//! Traversals of a three-player tree: the CFR+ step, evaluation of a fixed strategy, best
//! response, exploitability and the Nash test's per-infoset action values.
//!
//! Same scheme as the two-player `iterate` / `value_walk`: vectorised over hand classes, values
//! counterfactual (summed over both opponents' holdings, weighted by deal probability and their
//! reach, without the traverser's own reach). Chance branches scale a common factor.
//!
//! CFR+ update: regrets floored at zero, players updated in turn (0, 1, 2), each against the
//! strategies already updated in this iteration, average strategy weighted by the iteration.
//! For three players CFR has no equilibrium guarantee; whether the result is one is measured
//! (`exploitability`, `deviations`), not assumed.
use super::deviation::Deviation;
use super::game::Game;
use super::leaf_value3::{leaf_value, reach_mass};
use super::regret_matching::matched;
use super::solver_state::SolverState;
use super::strategy::Strategy;
use super::tree3::{Node3, Tree3};
use crate::rng::Rng;
type Reach = [Vec<f64>; 3];
fn view(reach: &Reach) -> [&[f64]; 3] {
[&reach[0], &reach[1], &reach[2]]
}
fn add(total: &mut [f64], value: &[f64]) {
total.iter_mut().zip(value).for_each(|(t, v)| *t += v);
}
struct Learn<'a> {
tree: &'a Tree3,
player: usize,
weight: f64,
regret: &'a mut Vec<Vec<f64>>,
sums: &'a mut Vec<Vec<f64>>,
}
impl Learn<'_> {
fn walk(&mut self, node: usize, reach: &Reach, scale: f64) -> Vec<f64> {
let tree = self.tree;
let n = tree.classes;
match tree.nodes.get(node) {
None => vec![0.0; n],
Some(Node3::Terminal(outcome)) => leaf_value(tree, outcome, self.player, view(reach), scale),
Some(Node3::Chance(branches)) => branches.iter().fold(vec![0.0; n], |mut total, (p, child)| {
let value = self.walk(*child, reach, scale * p);
add(&mut total, &value);
total
}),
Some(Node3::Decision { player, children, .. }) => {
let actions = children.len();
if actions == 0 {
return vec![0.0; n];
}
let sigma = matched(&self.regret[node], actions);
let owner = *player;
let values: Vec<Vec<f64>> = children
.iter()
.enumerate()
.map(|(a, child)| {
let mut next = reach.clone();
next[owner].iter_mut().enumerate().for_each(|(c, r)| *r *= sigma[c * actions + a]);
self.walk(*child, &next, scale)
})
.collect();
if owner != self.player {
return values.iter().fold(vec![0.0; n], |mut total, v| {
add(&mut total, v);
total
});
}
let own = &reach[owner];
(0..n)
.map(|i| {
let node_value: f64 = (0..actions).map(|a| sigma[i * actions + a] * values[a][i]).sum();
for a in 0..actions {
let r = &mut self.regret[node][i * actions + a];
*r = (*r + values[a][i] - node_value).max(0.0);
self.sums[node][i * actions + a] += self.weight * own[i] * sigma[i * actions + a];
}
node_value
})
.collect()
}
}
}
}
/// One CFR+ iteration as a pure fold step; the generator passes through (full width).
pub fn iterate3(tree: &Tree3, state: SolverState, rng: Rng) -> (SolverState, Rng) {
let (iteration, mut regret, mut sums) = state.into_parts();
let next = iteration.saturating_add(1);
if tree.is_playable() && regret.len() == tree.nodes.len() {
let ones = vec![1.0; tree.classes];
let reach: Reach = [ones.clone(), ones.clone(), ones];
for player in 0..3 {
let mut pass = Learn { tree, player, weight: next as f64, regret: &mut regret, sums: &mut sums };
pass.walk(tree.root, &reach, 1.0);
}
}
(SolverState::from_parts(next, regret, sums), rng)
}
/// What a traverser's decision node looked like during an evaluation walk.
pub(crate) struct Visit3<'a> {
pub node: usize,
pub name: &'static str,
pub reach: &'a Reach,
pub scale: f64,
/// `[action][class]`
pub action_values: &'a [Vec<f64>],
}
struct Evaluate<'a> {
tree: &'a Tree3,
strategy: &'a Strategy,
player: usize,
best: bool,
}
impl Evaluate<'_> {
fn probability(&self, node: usize, class: usize, action: usize) -> f64 {
self.strategy.probability(node, class, action)
}
fn walk<F: FnMut(&Visit3)>(&self, node: usize, reach: &Reach, scale: f64, visit: &mut F) -> Vec<f64> {
let tree = self.tree;
let n = tree.classes;
match tree.nodes.get(node) {
None => vec![0.0; n],
Some(Node3::Terminal(outcome)) => leaf_value(tree, outcome, self.player, view(reach), scale),
Some(Node3::Chance(branches)) => branches.iter().fold(vec![0.0; n], |mut total, (p, child)| {
let value = self.walk(*child, reach, scale * p, visit);
add(&mut total, &value);
total
}),
Some(Node3::Decision { player, name, children }) => {
let owner = *player;
let mine = owner == self.player;
let values: Vec<Vec<f64>> = children
.iter()
.enumerate()
.map(|(a, child)| {
let mut next = reach.clone();
if !(mine && self.best) {
next[owner]
.iter_mut()
.enumerate()
.for_each(|(c, r)| *r *= self.probability(node, c, a));
}
self.walk(*child, &next, scale, visit)
})
.collect();
if !mine {
return values.iter().fold(vec![0.0; n], |mut total, v| {
add(&mut total, v);
total
});
}
visit(&Visit3 { node, name, reach, scale, action_values: &values });
(0..n)
.map(|i| {
let v = if self.best {
values.iter().map(|v| v[i]).fold(f64::NEG_INFINITY, f64::max)
} else {
(0..children.len()).map(|a| self.probability(node, i, a) * values[a][i]).sum()
};
if v.is_finite() { v } else { 0.0 }
})
.collect()
}
}
}
}
fn root_values3<F: FnMut(&Visit3)>(tree: &Tree3, strategy: &Strategy, player: usize, best: bool, visit: &mut F) -> Vec<f64> {
if !tree.is_playable() {
return vec![0.0; tree.classes];
}
let ones = vec![1.0; tree.classes];
let reach: Reach = [ones.clone(), ones.clone(), ones];
Evaluate { tree, strategy, player, best }.walk(tree.root, &reach, 1.0, visit)
}
/// Expected result of `player` when everybody follows `strategy`.
pub fn game_value3(tree: &Tree3, strategy: &Strategy, player: usize) -> f64 {
root_values3(tree, strategy, player.min(2), false, &mut |_| {}).iter().sum()
}
/// What `player` wins by best-responding while the other two keep `strategy`.
pub fn best_response_gain3(tree: &Tree3, strategy: &Strategy, player: usize) -> f64 {
let player = player.min(2);
let best: f64 = root_values3(tree, strategy, player, true, &mut |_| {}).iter().sum();
best - game_value3(tree, strategy, player)
}
/// Sum of the three best-response gains (0 exactly at a Nash equilibrium).
pub fn exploitability3(tree: &Tree3, strategy: &Strategy) -> f64 {
(0..3).map(|p| best_response_gain3(tree, strategy, p)).sum()
}
/// One entry per decision node, hand class and acting player that can be reached at all: the
/// conditional value of every action with everything else frozen (see `deviation`).
pub fn deviations3(tree: &Tree3, strategy: &Strategy) -> Vec<Deviation> {
let mut found = Vec::new();
for player in 0..3 {
let mut visit = |v: &Visit3| {
let mass = reach_mass(tree, player, view(v.reach), v.scale);
for (class, m) in mass.iter().enumerate() {
if *m <= 0.0 {
continue;
}
found.push(Deviation {
node: v.name,
player,
class,
weight: v.reach[player][class] * m,
frequency: strategy.row(v.node, class).to_vec(),
value: v.action_values.iter().map(|a| a[class] / m).collect(),
});
}
};
root_values3(tree, strategy, player, false, &mut visit);
}
found
}
impl Game for Tree3 {
fn classes(&self) -> usize {
self.classes
}
fn action_counts(&self) -> Vec<usize> {
self.nodes
.iter()
.map(|n| match n {
Node3::Decision { children, .. } => children.len(),
_ => 0,
})
.collect()
}
fn decision_name(&self, node: usize) -> Option<&'static str> {
match self.nodes.get(node) {
Some(Node3::Decision { name, .. }) => Some(name),
_ => None,
}
}
fn step(&self, state: SolverState, rng: Rng) -> (SolverState, Rng) {
iterate3(self, state, rng)
}
fn exploitability(&self, strategy: &Strategy) -> f64 {
exploitability3(self, strategy)
}
}
+77 -25
View File
@@ -5,28 +5,33 @@
//! |---|---|---|---|
//! | unopened, binary game or at most 15 bb | first to act | `push_frequency` | jam |
//! | unopened, deeper | first to act | `open_frequency` | raise |
//! | facing one open | big blind, opener known | `vs_open` | 3-bet |
//! | facing a 3-bet | the opener | `vs_three_bet` | jam |
//! | facing an all-in | big blind, the jam is the only raise, at most 25 bb | `call_vs_push` | — |
//! | facing one open, no caller | small blind | `sb_vs_open` | 3-bet |
//! | facing one open, no caller | big blind | `vs_open` | 3-bet |
//! | facing one open, the small blind called | big blind | `bb_vs_open_and_call` | — |
//! | facing a 3-bet from a blind | the opener | `vs_three_bet` / `vs_sb_three_bet` | jam |
//! | facing a jam (the only raise), no caller, at most 25 bb | small blind | `sb_call_vs_push` | — |
//! | facing a jam (the only raise), at most 25 bb | big blind | `call_vs_push` / `bb_overcall_vs_push` | — |
//!
//! Only for 6-max tables (the size the generator modelled). Everything else (other
//! variants and table sizes, multiway raises, unknown openers) has no answer here and
//! stays with the heuristic charts. The action is the most frequent one; ties keep the
//! Only for 6-max tables (the size the generator modelled) and the variants with tables (NLHE,
//! AOF, short deck). Everything else (other variants and table sizes, callers other than the
//! small blind, 4-bets, 3-bets from players that are not in the blinds, unknown openers) has no
//! answer here and stays with the heuristic charts. The action is the most frequent one; ties keep the
//! cheaper action. `width` is the combo-weighted share of hands the equilibrium
//! continues with at that node, the base for exploit deviations (`exploit_border`).
use super::first_raiser::{first_raiser, sole_raiser};
use super::first_raiser::{first_raiser, preflop_callers, raise_count, second_raiser, sole_raiser};
use super::generated_lookup::{
call_vs_push, has_charts, open_frequency, push_frequency, seat_of, vs_open, vs_three_bet, Frequencies,
bb_overcall_vs_push, bb_vs_open_and_call, call_vs_push, has_charts, open_frequency, push_frequency,
sb_call_vs_push, sb_vs_open, seat_of, vs_open, vs_sb_three_bet, vs_three_bet, Frequencies,
};
use super::plan::ChartAction;
use super::position::Position;
use super::seat_position::seat_position;
use super::situation::Situation;
use crate::cfr::hand_class::{class_combos, class_of, ClassId, CLASS_COUNT};
use crate::cfr::hand_class::{class_combos, class_exists, class_of, ClassId, CLASS_COUNT};
use crate::cfr::seat::Seat;
use crate::game::Spot;
use crate::variant::ActionShape;
use crate::variant::{ActionShape, DeckRule};
/// Unopened pots at or below this depth are push / fold spots.
const PUSH_FOLD_BB: f64 = 15.0;
@@ -63,9 +68,9 @@ fn seat_of_player(spot: &Spot, seat: u8) -> Option<Seat> {
seat_of(seat_position(spot, seat))
}
/// Combo-weighted share of all hands whose most frequent action is not a fold.
fn width(read: &dyn Fn(ClassId) -> Option<Frequencies>) -> f64 {
let (kept, all) = (0..CLASS_COUNT).fold((0.0, 0.0), |(kept, all), class| {
/// Combo-weighted share of the deck's hands whose most frequent action is not a fold.
fn width(deck: DeckRule, read: &dyn Fn(ClassId) -> Option<Frequencies>) -> f64 {
let (kept, all) = (0..CLASS_COUNT).filter(|c| class_exists(deck, *c)).fold((0.0, 0.0), |(kept, all), class| {
let combos = class_combos(class).len() as f64;
let plays = read(class).is_some_and(|f| pick(f, ChartAction::Raise) != ChartAction::Fold);
(kept + if plays { combos } else { 0.0 }, all + combos)
@@ -75,31 +80,78 @@ fn width(read: &dyn Fn(ClassId) -> Option<Frequencies>) -> f64 {
type Node = (Box<dyn Fn(ClassId) -> Option<Frequencies>>, ChartAction, &'static str, ChartAction);
/// Who called the open (or jam) before hero: nobody, only the small blind, or anybody else.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Callers {
None,
SmallBlind,
Other,
}
fn callers(spot: &Spot) -> Callers {
let seats = preflop_callers(spot);
if seats.is_empty() {
Callers::None
} else if seats.iter().all(|s| seat_position(spot, *s) == Position::SmallBlind) {
Callers::SmallBlind
} else {
Callers::Other
}
}
fn boxed(read: impl Fn(ClassId) -> Option<Frequencies> + 'static) -> Box<dyn Fn(ClassId) -> Option<Frequencies>> {
Box::new(read)
}
/// The table node for this spot: lookup per class, aggressive action, name, widen-to action.
fn node(spot: &Spot, situation: Situation, pos: Position, depth: f64) -> Option<Node> {
let variant = spot.variant;
let binary = spot.rules().shape == ActionShape::Binary;
let big_blind = pos == Position::BigBlind;
let (big_blind, small_blind) = (pos == Position::BigBlind, pos == Position::SmallBlind);
let called = callers(spot);
let first = || seat_of_player(spot, sole_raiser(spot)?);
match situation {
Situation::Unopened if binary || depth <= PUSH_FOLD_BB => {
let seat = seat_of(pos)?;
Some((Box::new(move |c| push_frequency(variant, seat, depth, c)), ChartAction::Jam, "push/fold", ChartAction::Jam))
Some((boxed(move |c| push_frequency(variant, seat, depth, c)), ChartAction::Jam, "push/fold", ChartAction::Jam))
}
Situation::Unopened => {
let seat = seat_of(pos)?;
Some((Box::new(move |c| open_frequency(seat, depth, c)), ChartAction::Raise, "open", ChartAction::Raise))
Some((boxed(move |c| open_frequency(variant, seat, depth, c)), ChartAction::Raise, "open", ChartAction::Raise))
}
Situation::FacingOpen if big_blind && !binary => {
let opener = seat_of_player(spot, sole_raiser(spot)?)?;
Some((Box::new(move |c| vs_open(opener, depth, c)), ChartAction::Raise, "vs open", ChartAction::Call))
Situation::FacingOpen if small_blind && !binary && called == Callers::None => {
let opener = first()?;
Some((boxed(move |c| sb_vs_open(variant, opener, depth, c)), ChartAction::Raise, "SB vs open", ChartAction::Call))
}
Situation::FacingThreeBetPlus if !binary && first_raiser(spot) == Some(spot.hero_seat) => {
Situation::FacingOpen if big_blind && !binary && called == Callers::None => {
let opener = first()?;
Some((boxed(move |c| vs_open(variant, opener, depth, c)), ChartAction::Raise, "vs open", ChartAction::Call))
}
Situation::FacingOpen if big_blind && !binary && called == Callers::SmallBlind => {
let opener = first()?;
Some((boxed(move |c| bb_vs_open_and_call(variant, opener, depth, c)), ChartAction::Raise, "vs open + SB call", ChartAction::Call))
}
Situation::FacingThreeBetPlus
if !binary && first_raiser(spot) == Some(spot.hero_seat) && raise_count(spot) == 2 =>
{
let seat = seat_of(pos)?;
Some((Box::new(move |c| vs_three_bet(seat, depth, c)), ChartAction::Jam, "vs 3-bet", ChartAction::Call))
match seat_position(spot, second_raiser(spot)?) {
Position::BigBlind => Some((boxed(move |c| vs_three_bet(variant, seat, depth, c)), ChartAction::Jam, "vs 3-bet", ChartAction::Call)),
Position::SmallBlind => Some((boxed(move |c| vs_sb_three_bet(variant, seat, depth, c)), ChartAction::Jam, "vs SB 3-bet", ChartAction::Call)),
_ => None,
}
}
Situation::FacingAllIn if big_blind && depth <= CALL_JAM_MAX_BB => {
let pusher = seat_of_player(spot, sole_raiser(spot)?)?;
Some((Box::new(move |c| call_vs_push(variant, pusher, depth, c)), ChartAction::Call, "vs jam", ChartAction::Call))
Situation::FacingAllIn if small_blind && depth <= CALL_JAM_MAX_BB && called == Callers::None => {
let pusher = first()?;
Some((boxed(move |c| sb_call_vs_push(variant, pusher, depth, c)), ChartAction::Call, "SB vs jam", ChartAction::Call))
}
Situation::FacingAllIn if big_blind && depth <= CALL_JAM_MAX_BB && called == Callers::None => {
let pusher = first()?;
Some((boxed(move |c| call_vs_push(variant, pusher, depth, c)), ChartAction::Call, "vs jam", ChartAction::Call))
}
Situation::FacingAllIn if big_blind && depth <= CALL_JAM_MAX_BB && called == Callers::SmallBlind => {
let pusher = first()?;
Some((boxed(move |c| bb_overcall_vs_push(variant, pusher, depth, c)), ChartAction::Call, "vs jam + SB call", ChartAction::Call))
}
_ => None,
}
@@ -119,7 +171,7 @@ pub fn cfr_advice(spot: &Spot, situation: Situation, pos: Position, depth: f64)
action: pick(frequencies, aggressive),
frequencies,
table,
width: width(&read),
width: width(spot.rules().deck, &read),
widen_to,
})
}
+40 -21
View File
@@ -1,21 +1,40 @@
use crate::game::{SeenAction, Spot, Street};
/// Seats that raised or went all-in preflop, in order.
fn raisers(spot: &Spot) -> impl Iterator<Item = u8> + '_ {
spot.history
.iter()
.filter(|r| r.street == Street::Preflop && matches!(r.action, SeenAction::Raise | SeenAction::AllIn))
.map(|r| r.seat)
}
/// The seat that opened the pot with a raise (or jam), when the history shows one.
pub fn first_raiser(spot: &Spot) -> Option<u8> {
raisers(spot).next()
}
/// The seat of the only preflop raise, `None` with no raise or with several.
pub fn sole_raiser(spot: &Spot) -> Option<u8> {
let mut all = raisers(spot);
let first = all.next()?;
all.next().is_none().then_some(first)
}
use crate::game::{SeenAction, Spot, Street};
/// Seats that raised or went all-in preflop, in order.
fn raisers(spot: &Spot) -> impl Iterator<Item = u8> + '_ {
spot.history
.iter()
.filter(|r| r.street == Street::Preflop && matches!(r.action, SeenAction::Raise | SeenAction::AllIn))
.map(|r| r.seat)
}
/// The seat that opened the pot with a raise (or jam), when the history shows one.
pub fn first_raiser(spot: &Spot) -> Option<u8> {
raisers(spot).next()
}
/// The seat of the only preflop raise, `None` with no raise or with several.
pub fn sole_raiser(spot: &Spot) -> Option<u8> {
let mut all = raisers(spot);
let first = all.next()?;
all.next().is_none().then_some(first)
}
/// The seat of the second preflop raise (the 3-bet), when the history shows one.
pub fn second_raiser(spot: &Spot) -> Option<u8> {
raisers(spot).nth(1)
}
/// Number of preflop raises and jams.
pub fn raise_count(spot: &Spot) -> usize {
raisers(spot).count()
}
/// Seats that called preflop (a big blind check is not a call), in order.
pub fn preflop_callers(spot: &Spot) -> Vec<u8> {
spot.history
.iter()
.filter(|r| r.street == Street::Preflop && r.action == SeenAction::Call)
.map(|r| r.seat)
.collect()
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+79 -19
View File
@@ -6,17 +6,29 @@
//! covered range). Non-finite or non-positive depths, unknown classes and variants without a
//! chart give `None`.
//!
//! Every function answers for the *seat that acts* in that situation:
//! Every function answers for the *seat that acts* in that situation (`seat` / `pusher` /
//! `opener` is always the first actor of the spot):
//! - `push_frequency`: the first actor jams (raise = jam) or folds.
//! - `call_vs_push`: the big blind facing that jam (`seat` = the pusher).
//! - `sb_call_vs_push`: the small blind facing that jam, the big blind still behind.
//! - `call_vs_push`: the big blind facing that jam after the small blind folded.
//! - `bb_overcall_vs_push`: the big blind facing that jam after the small blind called.
//! - `open_frequency`: the first actor raises or folds.
//! - `vs_open`: the big blind facing the open of `seat`: fold / call / 3-bet.
//! - `vs_three_bet`: the opener (`seat`) facing the big blind's 3-bet: fold / call / jam.
//! - `vs_jam`: the big blind facing the opener's jam: fold / call.
//! - `sb_vs_open`: the small blind facing the open: fold / call / 3-bet.
//! - `vs_open`: the big blind facing the open after the small blind folded: fold / call / 3-bet.
//! - `bb_vs_open_and_call`: the big blind facing the open and the small blind's call: fold / call.
//! - `vs_three_bet`: the opener facing the big blind's 3-bet: fold / call / jam.
//! - `vs_sb_three_bet`: the opener facing the small blind's 3-bet: fold / call / jam.
//! - `vs_jam`: the big blind facing the opener's jam over its 3-bet: fold / call.
//!
//! The small-blind and overcall tables exist only for first actors EP to BTN (the small blind as
//! first actor faces the big blind alone): for `SmallBlind` they answer `None`.
//! Tables: NLHE and AOF share the full-deck file, short deck has its own (`generated_charts_short`);
//! AOF has push / fold only.
//!
//! Class ids are those of `crate::cfr::hand_class` (`class_of(card, card)`).
use super::generated_charts::{AOF_PUSH_FOLD, OPEN, OPEN_DEPTHS, PUSH_FOLD, PUSH_FOLD_DEPTHS};
use super::generated_charts_short as short;
use super::position::Position;
use crate::cfr::frozen_spot::{OpenSpot, PushFoldSpot};
use crate::cfr::hand_class::{ClassId, CLASS_COUNT};
@@ -141,45 +153,93 @@ fn lookup<T: Placed>(
Some(read(lo, class).blend(read(hi, class), t))
}
fn non_empty<T>(spots: &'static [T]) -> Option<&'static [T]> {
(!spots.is_empty()).then_some(spots)
}
fn push_chart(variant: Variant) -> Option<&'static [PushFoldSpot]> {
match variant {
Variant::Nlhe => Some(&PUSH_FOLD),
Variant::Aof => Some(AOF_PUSH_FOLD),
Variant::Nlhe => non_empty(&PUSH_FOLD),
Variant::Aof => non_empty(AOF_PUSH_FOLD),
Variant::ShortDeck => non_empty(&short::PUSH_FOLD),
_ => None,
}
}
/// True when CFR charts exist for `variant` (NLHE and AOF).
fn open_chart(variant: Variant) -> Option<&'static [OpenSpot]> {
match variant {
Variant::Nlhe => non_empty(&OPEN),
Variant::ShortDeck => non_empty(&short::OPEN),
_ => None,
}
}
/// True when CFR charts exist for `variant` (NLHE, AOF, short deck).
pub fn has_charts(variant: Variant) -> bool {
push_chart(variant).is_some()
}
/// The small blind and the overcall are players only when somebody else acted first.
fn facing_both_blinds(first_actor: Seat) -> Option<()> {
(first_actor != Seat::SmallBlind).then_some(())
}
/// The first actor's jam frequency (`raise`) or fold.
pub fn push_frequency(variant: Variant, seat: Seat, depth_bb: f64, class: ClassId) -> Option<Frequencies> {
lookup(push_chart(variant)?, seat, depth_bb, class, |s, c| Frequencies::aggressive(s.push[c]))
}
/// The big blind's response to a jam from `pusher`.
/// The big blind's response to a jam from `pusher` after the small blind folded.
pub fn call_vs_push(variant: Variant, pusher: Seat, depth_bb: f64, class: ClassId) -> Option<Frequencies> {
lookup(push_chart(variant)?, pusher, depth_bb, class, |s, c| Frequencies::passive(s.call[c]))
}
/// The first actor's raise frequency or fold (NLHE only).
pub fn open_frequency(seat: Seat, depth_bb: f64, class: ClassId) -> Option<Frequencies> {
lookup(&OPEN, seat, depth_bb, class, |s, c| Frequencies::aggressive(s.open[c]))
/// The small blind's response to a jam from `pusher`, the big blind still to act.
pub fn sb_call_vs_push(variant: Variant, pusher: Seat, depth_bb: f64, class: ClassId) -> Option<Frequencies> {
facing_both_blinds(pusher)?;
lookup(push_chart(variant)?, pusher, depth_bb, class, |s, c| Frequencies::passive(s.sb_call[c]))
}
/// The big blind facing the open of `opener`: fold / call / 3-bet.
pub fn vs_open(opener: Seat, depth_bb: f64, class: ClassId) -> Option<Frequencies> {
lookup(&OPEN, opener, depth_bb, class, |s, c| Frequencies::split(s.defend[c]))
/// The big blind's response to a jam from `pusher` that the small blind called.
pub fn bb_overcall_vs_push(variant: Variant, pusher: Seat, depth_bb: f64, class: ClassId) -> Option<Frequencies> {
facing_both_blinds(pusher)?;
lookup(push_chart(variant)?, pusher, depth_bb, class, |s, c| Frequencies::passive(s.bb_overcall[c]))
}
/// The first actor's raise frequency or fold.
pub fn open_frequency(variant: Variant, seat: Seat, depth_bb: f64, class: ClassId) -> Option<Frequencies> {
lookup(open_chart(variant)?, seat, depth_bb, class, |s, c| Frequencies::aggressive(s.open[c]))
}
/// The small blind facing the open of `opener`: fold / call / 3-bet.
pub fn sb_vs_open(variant: Variant, opener: Seat, depth_bb: f64, class: ClassId) -> Option<Frequencies> {
facing_both_blinds(opener)?;
lookup(open_chart(variant)?, opener, depth_bb, class, |s, c| Frequencies::split(s.sb_defend[c]))
}
/// The big blind facing the open of `opener` (the small blind folded): fold / call / 3-bet.
pub fn vs_open(variant: Variant, opener: Seat, depth_bb: f64, class: ClassId) -> Option<Frequencies> {
lookup(open_chart(variant)?, opener, depth_bb, class, |s, c| Frequencies::split(s.defend[c]))
}
/// The big blind facing the open of `opener` and the small blind's call: fold / call.
pub fn bb_vs_open_and_call(variant: Variant, opener: Seat, depth_bb: f64, class: ClassId) -> Option<Frequencies> {
facing_both_blinds(opener)?;
lookup(open_chart(variant)?, opener, depth_bb, class, |s, c| Frequencies::passive(s.bb_overcall[c]))
}
/// The opener facing the big blind's 3-bet: fold / call / jam.
pub fn vs_three_bet(opener: Seat, depth_bb: f64, class: ClassId) -> Option<Frequencies> {
lookup(&OPEN, opener, depth_bb, class, |s, c| Frequencies::split(s.vs_three_bet[c]))
pub fn vs_three_bet(variant: Variant, opener: Seat, depth_bb: f64, class: ClassId) -> Option<Frequencies> {
lookup(open_chart(variant)?, opener, depth_bb, class, |s, c| Frequencies::split(s.vs_three_bet[c]))
}
/// The opener facing the small blind's 3-bet: fold / call / jam.
pub fn vs_sb_three_bet(variant: Variant, opener: Seat, depth_bb: f64, class: ClassId) -> Option<Frequencies> {
facing_both_blinds(opener)?;
lookup(open_chart(variant)?, opener, depth_bb, class, |s, c| Frequencies::split(s.vs_sb_three_bet[c]))
}
/// The big blind facing the opener's jam over the 3-bet: fold / call.
pub fn vs_jam(opener: Seat, depth_bb: f64, class: ClassId) -> Option<Frequencies> {
lookup(&OPEN, opener, depth_bb, class, |s, c| Frequencies::passive(s.vs_jam[c]))
pub fn vs_jam(variant: Variant, opener: Seat, depth_bb: f64, class: ClassId) -> Option<Frequencies> {
lookup(open_chart(variant)?, opener, depth_bb, class, |s, c| Frequencies::passive(s.vs_jam[c]))
}
+34 -33
View File
@@ -1,33 +1,34 @@
//! Preflop: chart lookup by position and action sequence.
pub mod advise;
pub mod allin_call_cutoff;
pub mod button;
pub mod certainty;
pub mod cfr_advice;
pub mod chart_decision;
pub mod chart_row;
pub mod effective_stack;
pub mod exploit_border;
pub mod first_raiser;
pub mod full_chart;
pub mod generated_charts;
pub mod generated_lookup;
pub mod hand_percentile;
pub mod holdem_percentile;
pub mod holdem_ranking;
pub mod plan;
pub mod plo5_pair_bonus;
pub mod plo5_percentile;
pub mod plo5_rundown;
pub mod plo5_score;
pub mod plo5_score_table;
pub mod plo5_suits;
pub mod position;
pub mod push_chart;
pub mod reason;
pub mod seat_position;
pub mod short_deck_percentile;
pub mod short_deck_ranking;
pub mod situation;
pub mod width_factor;
//! Preflop: chart lookup by position and action sequence.
pub mod advise;
pub mod allin_call_cutoff;
pub mod button;
pub mod certainty;
pub mod cfr_advice;
pub mod chart_decision;
pub mod chart_row;
pub mod effective_stack;
pub mod exploit_border;
pub mod first_raiser;
pub mod full_chart;
pub mod generated_charts;
pub mod generated_charts_short;
pub mod generated_lookup;
pub mod hand_percentile;
pub mod holdem_percentile;
pub mod holdem_ranking;
pub mod plan;
pub mod plo5_pair_bonus;
pub mod plo5_percentile;
pub mod plo5_rundown;
pub mod plo5_score;
pub mod plo5_score_table;
pub mod plo5_suits;
pub mod position;
pub mod push_chart;
pub mod reason;
pub mod seat_position;
pub mod short_deck_percentile;
pub mod short_deck_ranking;
pub mod situation;
pub mod width_factor;