Add CFR preflop chart generator, frozen charts and lookup

Pure CFR+ core over a 169-class abstraction, push/fold and open/call/3-bet games,
Nash/Kuhn/plausibility/lookup tests, chartgen binary, frozen equity and charts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-28 13:05:07 +01:00
co-authored by Claude Opus 5.5
parent 30aaee6e1b
commit a7b32cf425
46 changed files with 5994 additions and 2 deletions
+125
View File
@@ -0,0 +1,125 @@
//! 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);
}
}
}