Files
pokerfreak/tests/short_deck_charts.rs
T
mmintel 04d5251acf Welt ohne fremden Namen: Pruefordner vollstaendig mitkopieren, Engine nur im eigenen Baum
Die Welt nannte 'pokerfreak' nur noch in zwei Harness-Zeilen - der Rest waren veraltete
Rust-Pruefungen im Pruefordner, die der Aufbau nie auffrischte.
2026-11-01 23:37:11 +01:00

404 lines
18 KiB
Rust

//! Short deck charts (`preflop::generated_charts_short`): complete, and right by an independent
//! measure.
//!
//! **Completeness.** Every seat (EP, MP, CO, BTN, SB) at every depth of the plan appears exactly
//! once in both tables. Every one of the 81 classes of the 36-card deck has a well-formed row in
//! every node its seat can reach -- including the edge of the deck: the sixes (66, A6s, A6o, 76s,
//! 76o,...) are dealt and present, the classes with a card below six (65s, A5o, 22) are not in the
//! deck and stay exactly 0. Nodes a seat cannot reach (small-blind rows when the small blind is
//! the first actor) are all 0; reachable nodes are not.
//!
//! **Independent measure.** The CFR tables are solved over a class-vs-class equity matrix (60 000
//! Monte Carlo samples per class pair) with pairwise card-removal approximations. Every all-in
//! decision in them can instead be judged directly with real cards: deal the hero's class combo,
//! deal the opponent a combo from the chart's own range (weighted by its permille, disjoint from
//! the hero's cards), deal a random five-card board and compare with `hand::showdown::judge` under
//! short deck rules. None of the equity matrix, the chance tables or the solver is used. Checked:
//!
//! - big blind versus a jam (push / fold, every seat): call iff
//! `(2s + dead) * equity - s > -1`, dead = 0.5 when the small blind folded in front;
//! - small blind jam (push / fold, small blind first): `EV(push) = (1 - C) * 1 + C * (2s * equity
//! against the calling range - s)` against `EV(fold) = -0.5`, `C` = calling share of the big
//! blind's combos disjoint from the hero's;
//! - versus the jam over a 3-bet (open tables): the big blind (and the small blind over its own
//! 3-bet) calls iff `(2s + dead) * equity - s > -three_bet`, the jam range being
//! `open x jam frequency`.
//!
//! A chart row is "wrong" when its mix loses more than `3 x standard error + TOLERANCE` (in equity
//! units: the abstraction's own equity noise plus the card removal of the players who folded,
//! which the direct check ignores) against the better of the two actions. Only classes that reach
//! the node count, weighted by how often they do (`vs_jam` is reached by the 3-bet share of
//! `defend`): a class that never 3-bets has no `vs_jam` decision, and the solver leaves its row at
//! the untouched default (often 500). The default run checks
//! a few spots with `TRIALS` showdowns per class; the full sweep over every spot is
//!
//! ```text
//! cargo test --release --test short_deck_charts -- --ignored --nocapture
//! ```
//!
//! which prints per spot the wrong decisions and the combo-weighted mean EV loss of the chart
//! against the direct best response (bb per hand dealt to that seat).
//!
//! Observed in the full sweep (40 000 showdowns per class, 23 min): 0 wrong decisions in 69
//! checked nodes (35 push / fold spots, the small blind's with its jam as a second node, and the
//! jam calls of 15 open spots). Mean EV loss of the chart against the direct best response: at
//! most 0.0027 bb in push / fold (CO 15 bb); in the open tables 0.000-0.016 bb at 20 and 40 bb and
//! 0.10-0.18 bb at 100 bb (EP), where the pot is 200 bb: 0.09 equity points, inside the noise of
//! the narrow jam ranges. 65-143 rows per open spot are unreached `vs_jam` defaults.
//!
//! **Edge hands.** Fourteen classes are never jammed or called in any push / fold spot (66, 76o,
//! 86o, 96o, T6o, J6o, Q6o, 76s, 87o, J7o, Q7o, 86s, T6s, J6s): without antes the bottom of a
//! 36-card deck has too little equity against the calling ranges, and the direct check of the
//! small blind's 5 bb jam agrees.
use rechner::card::{deck, Card};
use rechner::cfr::frozen_spot::{OpenSpot, PushFoldSpot};
use rechner::cfr::hand_class::{class_combos, class_exists, class_name, class_parse, CLASS_COUNT};
use rechner::cfr::seat::Seat;
use rechner::cfr::spot_params::{SMALL_BLIND_THREE_BET_SIZE, THREE_BET_SIZE};
use rechner::hand::showdown::judge;
use rechner::preflop::generated_charts_short::{OPEN, OPEN_DEPTHS, PUSH_FOLD, PUSH_FOLD_DEPTHS};
use rechner::rng::Rng;
use rechner::variant::{rules, DeckRule, Rules, Variant};
const TRIALS: u32 = 4_000;
const FULL_TRIALS: u32 = 40_000;
/// Equity slack of the abstraction (equity table noise, folded players' card removal).
const TOLERANCE: f64 = 0.02;
/// Classes the push / fold tables never jam or call (observed; checked against direct showdowns).
const NEVER_PLAYED: [&str; 14] =
["66", "76o", "86o", "96o", "T6o", "J6o", "Q6o", "76s", "87o", "J7o", "Q7o", "86s", "T6s", "J6s"];
fn short() -> Rules {
rules(Variant::ShortDeck)
}
fn deck_classes() -> Vec<usize> {
(0..CLASS_COUNT).filter(|c| class_exists(DeckRule::SHORT, *c)).collect()
}
fn id(name: &str) -> usize {
class_parse(name).unwrap_or_else(|| panic!("class {name}"))
}
// ---------------------------------------------------------------------------------------------
// Completeness
#[test]
fn every_seat_and_depth_appears_exactly_once() {
for seat in Seat::ALL {
for depth in PUSH_FOLD_DEPTHS {
assert_eq!(PUSH_FOLD.iter().filter(|s| s.seat == seat && s.depth_bb == depth).count(), 1, "push {seat:?} {depth}");
}
for depth in OPEN_DEPTHS {
assert_eq!(OPEN.iter().filter(|s| s.seat == seat && s.depth_bb == depth).count(), 1, "open {seat:?} {depth}");
}
}
assert_eq!(PUSH_FOLD.len(), Seat::ALL.len() * PUSH_FOLD_DEPTHS.len());
assert_eq!(OPEN.len(), Seat::ALL.len() * OPEN_DEPTHS.len());
}
#[test]
fn the_deck_edge_is_exact_sixes_are_dealt_fives_are_not() {
let classes = deck_classes();
assert_eq!(classes.len(), 81);
for name in ["66", "A6s", "A6o", "76s", "76o", "K6o", "T6s"] {
assert!(classes.contains(&id(name)), "{name} is a short deck class");
}
for name in ["55", "65s", "A5o", "22", "32o", "K2s"] {
assert!(!classes.contains(&id(name)), "{name} is not");
}
// Every combo of the deck falls into one of the 81 classes: 9 x 6 + 36 x 4 + 36 x 12 = 630.
let combos: usize = classes.iter().map(|c| class_combos(*c).len()).sum();
assert_eq!(combos, 630);
}
fn binary_rows(s: &PushFoldSpot) -> [(&'static str, &[u16; CLASS_COUNT]); 4] {
[("push", &s.push), ("call", &s.call), ("sb_call", &s.sb_call), ("bb_overcall", &s.bb_overcall)]
}
fn open_binary(s: &OpenSpot) -> [(&'static str, &[u16; CLASS_COUNT]); 4] {
[("open", &s.open), ("vs_jam", &s.vs_jam), ("bb_overcall", &s.bb_overcall), ("sb_vs_jam", &s.sb_vs_jam)]
}
fn open_ternary(s: &OpenSpot) -> [(&'static str, &[[u16; 2]; CLASS_COUNT]); 4] {
[("defend", &s.defend), ("vs_three_bet", &s.vs_three_bet), ("sb_defend", &s.sb_defend), ("vs_sb_three_bet", &s.vs_sb_three_bet)]
}
/// Nodes only the three-player games (EP to BTN) have.
fn small_blind_node(name: &str) -> bool {
matches!(name, "sb_call" | "bb_overcall" | "sb_defend" | "sb_vs_jam" | "vs_sb_three_bet")
}
#[test]
fn every_deck_class_has_a_row_in_every_reachable_node_and_nothing_else_does() {
let classes = deck_classes();
let outside: Vec<usize> = (0..CLASS_COUNT).filter(|c| !classes.contains(c)).collect();
for s in PUSH_FOLD.iter() {
for (name, row) in binary_rows(s) {
let label = format!("push {:?} {} {name}", s.seat, s.depth_bb);
assert!(row.iter().all(|v| *v <= 1000), "{label}");
assert!(outside.iter().all(|c| row[*c] == 0), "{label}: class outside the deck");
let used = classes.iter().any(|c| row[*c] > 0);
let reachable = s.seat != Seat::SmallBlind || !small_blind_node(name);
assert_eq!(used, reachable, "{label}: reachable {reachable}, used {used}");
}
}
for s in OPEN.iter() {
for (name, row) in open_binary(s) {
let label = format!("open {:?} {} {name}", s.seat, s.depth_bb);
assert!(row.iter().all(|v| *v <= 1000), "{label}");
assert!(outside.iter().all(|c| row[*c] == 0), "{label}: class outside the deck");
let reachable = s.seat != Seat::SmallBlind || !small_blind_node(name);
assert_eq!(classes.iter().any(|c| row[*c] > 0), reachable, "{label}");
}
for (name, row) in open_ternary(s) {
let label = format!("open {:?} {} {name}", s.seat, s.depth_bb);
assert!(row.iter().all(|[a, b]| a + b <= 1000), "{label}");
assert!(outside.iter().all(|c| row[*c] == [0, 0]), "{label}: class outside the deck");
let reachable = s.seat != Seat::SmallBlind || !small_blind_node(name);
assert_eq!(classes.iter().any(|c| row[*c] != [0, 0]), reachable, "{label}");
}
}
}
#[test]
fn edge_hands_get_edge_decisions() {
let (aa, worst) = (id("AA"), id("76o"));
for s in PUSH_FOLD.iter() {
assert_eq!(s.push[aa], 1000, "{:?} {}", s.seat, s.depth_bb);
assert_eq!(s.call[aa], 1000);
}
for s in OPEN.iter() {
assert_eq!(s.open[aa], 1000);
if s.seat == Seat::Early {
assert_eq!(s.open[worst], 0, "76o opens from EP at {} bb", s.depth_bb);
}
}
// Without antes the weakest classes are never played: jammed or called in no push / fold spot
// at all. That is a finding, not a gap -- their rows exist (all 0) and the direct showdowns
// below agree: even the small blind at 5 bb loses by jamming them.
let never: Vec<usize> = deck_classes()
.into_iter()
.filter(|c| PUSH_FOLD.iter().all(|s| s.push[*c] == 0 && s.call[*c] == 0 && s.sb_call[*c] == 0))
.collect();
let names: Vec<String> = never.iter().map(|c| class_name(*c).unwrap_or_default()).collect();
assert_eq!(names, NEVER_PLAYED, "classes never played");
let verdict = check_push_fold(push_spot(Seat::SmallBlind, 5), TRIALS);
assert!(verdict.wrong.is_empty(), "{:#?}", verdict.wrong);
}
// ---------------------------------------------------------------------------------------------
// Independent measure: all-in decisions judged with real cards
type Range = Vec<([Card; 2], f64)>;
fn range(weight: impl Fn(usize) -> f64) -> Range {
deck_classes()
.into_iter()
.flat_map(|c| class_combos(c).into_iter().map(move |h| (h, c)))
.map(|(h, c)| (h, weight(c)))
.filter(|(_, w)| *w > 0.0)
.collect()
}
fn disjoint(a: &[Card; 2], b: &[Card; 2]) -> bool {
!a.iter().any(|c| b.contains(c))
}
/// Hero's showdown share against a weighted range, the hero's combos taken in turn; also the
/// standard error.
fn equity(class: usize, villain: &Range, trials: u32, seed: u64) -> (f64, f64) {
let rules = short();
let heroes = class_combos(class);
let mut rng = Rng::seeded(seed ^ (class as u64).wrapping_mul(0x9E37_79B9));
let (mut sum, mut sq, mut n) = (0.0, 0.0, 0u32);
for t in 0..trials {
let hero = heroes[t as usize % heroes.len()];
let options: Vec<&([Card; 2], f64)> = villain.iter().filter(|(h, _)| disjoint(h, &hero)).collect();
let total: f64 = options.iter().map(|(_, w)| w).sum();
if total <= 0.0 {
return (0.5, 0.0);
}
let (u, next) = rng.unit();
rng = next;
let mut left = u * total;
let pick = options.iter().find(|(_, w)| {
left -= w;
left < 0.0
});
let other = pick.map_or(options[options.len() - 1].0, |(h, _)| *h);
let dead: Vec<Card> = hero.iter().chain(other.iter()).copied().collect();
let pool = deck::without_in(rules.deck, &dead);
let Some((board, next)) = deck::draw(&pool, 5, rng) else { return (0.5, 0.0) };
rng = next;
let (Ok(a), Ok(b)) = (judge(&rules, &hero, &board), judge(&rules, &other, &board)) else { continue };
let x = if a > b { 1.0 } else if a == b { 0.5 } else { 0.0 };
sum += x;
sq += x * x;
n += 1;
}
let mean = sum / n.max(1) as f64;
let var = (sq / n.max(1) as f64 - mean * mean).max(0.0);
(mean, (var / n.max(1) as f64).sqrt())
}
/// One all-in decision of a class: value of the second action minus the first (bb), its
/// standard error, and how much one equity point is worth here (to scale `TOLERANCE`).
struct Edge {
gain: f64,
error: f64,
per_equity: f64,
}
#[derive(Default)]
struct Verdict {
wrong: Vec<String>,
/// Classes that never reach the node (their row is the solver's untouched default).
unreached: usize,
loss: f64,
weight: f64,
}
impl Verdict {
/// `reach`: how often the class arrives at the node (0: never, the row is not played).
fn judge(&mut self, label: &str, class: usize, frequency: u16, reach: f64, edge: Edge) {
if reach <= 0.0 {
self.unreached += 1;
return;
}
let f = frequency as f64 / 1000.0;
let combos = class_combos(class).len() as f64 * reach;
let loss = edge.gain.max(0.0) - f * edge.gain;
self.loss += combos * loss;
self.weight += combos;
let slack = 3.0 * edge.error + TOLERANCE * edge.per_equity;
if loss > slack {
self.wrong.push(format!(
"{label} {}: chart {frequency} permille, direct edge {:+.3} bb (slack {:.3})",
class_name(class).unwrap_or_default(),
edge.gain,
slack
));
}
}
fn mean_loss(&self) -> f64 {
if self.weight > 0.0 { self.loss / self.weight } else { 0.0 }
}
}
/// A caller facing a jam of `s` with `pot = 2s + dead`, having put in `in_already`.
fn call_edge(class: usize, jammers: &Range, s: f64, dead: f64, in_already: f64, trials: u32) -> Edge {
let (eq, se) = equity(class, jammers, trials, 0x5348_4F52);
let pot = 2.0 * s + dead;
Edge { gain: pot * eq - s + in_already, error: pot * se, per_equity: pot }
}
fn check_push_fold(spot: &PushFoldSpot, trials: u32) -> Verdict {
let s = spot.depth_bb as f64;
let mut verdict = Verdict::default();
let label = format!("push {:?} {}", spot.seat, spot.depth_bb);
let pushers = range(|c| spot.push[c] as f64 / 1000.0);
let dead = if spot.seat == Seat::SmallBlind { 0.0 } else { 0.5 };
for class in deck_classes() {
verdict.judge(&format!("{label} BB call"), class, spot.call[class], 1.0, call_edge(class, &pushers, s, dead, 1.0, trials));
}
if spot.seat == Seat::SmallBlind {
let callers = range(|c| spot.call[c] as f64 / 1000.0);
for class in deck_classes() {
let hero = class_combos(class);
let calling: f64 = hero
.iter()
.map(|h| {
let all: Vec<_> = deck_classes()
.into_iter()
.flat_map(class_combos)
.filter(|b| disjoint(b, h))
.map(|b| spot.call[rechner::cfr::hand_class::class_of(b[0], b[1]).unwrap_or(0)] as f64 / 1000.0)
.collect();
all.iter().sum::<f64>() / all.len() as f64
})
.sum::<f64>()
/ hero.len() as f64;
let (eq, se) = equity(class, &callers, trials, 0x5055_5348);
let push = (1.0 - calling) * 1.0 + calling * (2.0 * s * eq - s);
let edge = Edge { gain: push + 0.5, error: calling * 2.0 * s * se, per_equity: calling * 2.0 * s };
verdict.judge(&format!("{label} SB push"), class, spot.push[class], 1.0, edge);
}
}
verdict
}
fn check_open_jams(spot: &OpenSpot, trials: u32) -> Verdict {
let s = spot.depth_bb as f64;
let mut verdict = Verdict::default();
let label = format!("open {:?} {}", spot.seat, spot.depth_bb);
let jams = range(|c| spot.open[c] as f64 / 1000.0 * spot.vs_three_bet[c][1] as f64 / 1000.0);
let dead = if spot.seat == Seat::SmallBlind { 0.0 } else { 0.5 };
if !jams.is_empty() {
for class in deck_classes() {
let edge = call_edge(class, &jams, s, dead, THREE_BET_SIZE, trials);
let reach = spot.defend[class][1] as f64 / 1000.0;
verdict.judge(&format!("{label} BB vs jam"), class, spot.vs_jam[class], reach, edge);
}
}
if spot.seat != Seat::SmallBlind {
let jams = range(|c| spot.open[c] as f64 / 1000.0 * spot.vs_sb_three_bet[c][1] as f64 / 1000.0);
if !jams.is_empty() {
for class in deck_classes() {
let edge = call_edge(class, &jams, s, 1.0, SMALL_BLIND_THREE_BET_SIZE, trials);
let reach = spot.sb_defend[class][1] as f64 / 1000.0;
verdict.judge(&format!("{label} SB vs jam"), class, spot.sb_vs_jam[class], reach, edge);
}
}
}
verdict
}
fn push_spot(seat: Seat, depth: u8) -> &'static PushFoldSpot {
PUSH_FOLD.iter().find(|s| s.seat == seat && s.depth_bb == depth).expect("push spot")
}
fn open_spot(seat: Seat, depth: u8) -> &'static OpenSpot {
OPEN.iter().find(|s| s.seat == seat && s.depth_bb == depth).expect("open spot")
}
#[test]
fn all_in_decisions_agree_with_direct_card_showdowns_on_sample_spots() {
let verdicts = [
check_push_fold(push_spot(Seat::SmallBlind, 10), TRIALS),
check_push_fold(push_spot(Seat::Early, 15), TRIALS),
check_open_jams(open_spot(Seat::Button, 20), TRIALS),
];
for v in &verdicts {
assert!(v.wrong.is_empty(), "{:#?}", v.wrong);
assert!(v.mean_loss() < 0.02, "mean loss {}", v.mean_loss());
}
}
#[test]
#[ignore = "full sweep, minutes in release: cargo test --release --test short_deck_charts -- --ignored --nocapture"]
fn every_all_in_decision_agrees_with_direct_card_showdowns() {
let mut wrong = Vec::new();
let mut nodes = 0;
let mut worst = (0.0, String::new());
let mut report = |label: String, v: Verdict, count: usize| {
println!("{label:<16} wrong {:>2} mean EV loss {:.4} bb unreached rows {}", v.wrong.len(), v.mean_loss(), v.unreached);
nodes += count;
if v.mean_loss() > worst.0 {
worst = (v.mean_loss(), label.clone());
}
wrong.extend(v.wrong);
};
for spot in PUSH_FOLD.iter() {
let count = if spot.seat == Seat::SmallBlind { 2 } else { 1 };
report(format!("push {} {}", spot.seat.label(), spot.depth_bb), check_push_fold(spot, FULL_TRIALS), count);
}
for spot in OPEN.iter() {
let count = if spot.seat == Seat::SmallBlind { 1 } else { 2 };
report(format!("open {} {}", spot.seat.label(), spot.depth_bb), check_open_jams(spot, FULL_TRIALS), count);
}
println!("{nodes} nodes checked, worst mean loss {:.4} bb ({})", worst.0, worst.1);
assert!(wrong.is_empty(), "{:#?}", wrong);
}