Files
pokerfreak/tests/cfr_three_way.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

176 lines
8.1 KiB
Rust

//! The three-player abstraction: deal weights, three-way pot shares and the game trees.
//!
//! Three-way shares come from the pairwise class equities (`cfr::three_way`): each hand's share is
//! the weaker of its two pairwise equities, normalised. Reference: Monte Carlo with the engine's
//! own evaluator over 200 000 boards for fixed combos (standard error about 0.1 %). The
//! approximation is coarse. Observed (approx / sampled):
//!
//! | hands | approximation | Monte Carlo |
//! |---|---|---|
//! | AA, KK, QQ | 0.696 / 0.154 / 0.150 | 0.665 / 0.168 / 0.167 |
//! | AKo, QQ, 72o | 0.386 / 0.508 / 0.106 | 0.396 / 0.494 / 0.110 |
//! | AKs, AQo, KQo | 0.607 / 0.197 / 0.197 | 0.743 / 0.181 / 0.076 |
//! | 22, AKo, T9s | 0.348 / 0.349 / 0.303 | 0.283 / 0.370 / 0.347 |
//! | JTs, 99, AQo | 0.297 / 0.376 / 0.326 | 0.323 / 0.305 / 0.373 |
//!
//! Largest error 0.136 (dominated hands: AKs over AQo and KQo), root mean square 0.058. The
//! product of the pairwise equities (0.129 / 0.068) and other means were not better. The
//! favourite is kept where it is clear (a lead of 0.1 or more); near-even triples may swap.
use rechner::card::Card;
use rechner::cfr::environment::Environment;
use rechner::cfr::hand_class::{class_of, CLASS_COUNT};
use rechner::cfr::open3_game::open3_tree;
use rechner::cfr::push_fold3_game::push_fold3_tree;
use rechner::cfr::seat::Seat;
use rechner::cfr::strategy::Strategy;
use rechner::cfr::three_way::three_way_shares;
use rechner::cfr::tree3::Node3;
use rechner::cfr::walk3::{exploitability3, game_value3};
use rechner::equity::monte_carlo::estimate;
use rechner::equity::query::Query;
use rechner::equity::villain_range::VillainRange;
use rechner::rng::Rng;
use rechner::variant::{rules, Variant};
const SHARE_TOLERANCE: f64 = 0.14;
fn cs(text: &str) -> Vec<Card> {
Card::parse_list(text).expect("cards")
}
fn class(text: &str) -> usize {
let c = cs(text);
class_of(c[0], c[1]).expect("class")
}
/// Monte-Carlo share of the first hand against the other two.
fn sampled(hands: [&str; 3]) -> f64 {
let villains = [VillainRange::Exact(cs(hands[1])), VillainRange::Exact(cs(hands[2]))];
let hero = cs(hands[0]);
let query = Query { rules: rules(Variant::Nlhe), hero: &hero, board: &[], villains: &villains, trials: 200_000 };
estimate(&query, Rng::seeded(77)).expect("estimate").0.share
}
fn approximated(env: &Environment, hands: [&str; 3]) -> [f64; 3] {
let c = hands.map(class);
let e = |x: usize, y: usize| if x == y { 0.5 } else { env.equity.get(c[x], c[y]) };
three_way_shares([[e(0, 0), e(0, 1), e(0, 2)], [e(1, 0), e(1, 1), e(1, 2)], [e(2, 0), e(2, 1), e(2, 2)]], [1.0; 3], 1.0)
}
#[test]
fn three_way_shares_track_monte_carlo_and_keep_the_order() {
let env = Environment::frozen();
let matchups = [
["Ah As", "Kh Ks", "Qd Qc"],
["Ah Kd", "Qc Qs", "7h 2c"],
["Ah Kh", "Ad Qc", "Kc Qd"],
["2h 2d", "Ac Ks", "Th 9h"],
["Js Ts", "9c 9d", "Ad Qh"],
];
for hands in matchups {
let approx = approximated(&env, hands);
let exact = [0, 1, 2].map(|k| sampled([hands[k], hands[(k + 1) % 3], hands[(k + 2) % 3]]));
println!("{hands:?}: approx {approx:.3?}, sampled {exact:.3?}");
for k in 0..3 {
assert!(
(approx[k] - exact[k]).abs() < SHARE_TOLERANCE,
"{hands:?} hand {k}: approx {:.3}, sampled {:.3}",
approx[k],
exact[k]
);
}
let best = |v: [f64; 3]| (0..3).fold(0, |b, k| if v[k] > v[b] { k } else { b });
let mut sorted = exact;
sorted.sort_by(|a, b| b.total_cmp(a));
if sorted[0] - sorted[1] >= 0.1 {
assert_eq!(best(approx), best(exact), "{hands:?}: favourite");
}
}
}
#[test]
fn shares_sum_to_one_and_are_symmetric() {
let eq = [[0.5, 0.7, 0.6], [0.3, 0.5, 0.55], [0.4, 0.45, 0.5]];
for (weights, spread) in [([1.0; 3], 1.0), ([1.0, 0.85, 0.85], 1.3)] {
let s = three_way_shares(eq, weights, spread);
assert!((s.iter().sum::<f64>() - 1.0).abs() < 1e-12);
assert!(s.iter().all(|x| (0.0..=1.0).contains(x)));
}
// Swapping two players swaps their shares.
let swapped = [[0.5, 0.4, 0.45], [0.6, 0.5, 0.7], [0.55, 0.3, 0.5]];
let (a, b) = (three_way_shares(eq, [1.0; 3], 1.0), three_way_shares(swapped, [1.0; 3], 1.0));
assert!((a[0] - b[1]).abs() < 1e-12 && (a[1] - b[2]).abs() < 1e-12 && (a[2] - b[0]).abs() < 1e-12);
// Equal hands split evenly; position weight moves chips to the player in position.
let even = [[0.5; 3]; 3];
assert!(three_way_shares(even, [1.0; 3], 1.3).iter().all(|x| (x - 1.0 / 3.0).abs() < 1e-12));
let positional = three_way_shares(even, [1.0, 0.85, 0.85], 1.3);
assert!(positional[0] > 1.0 / 3.0 && positional[1] < 1.0 / 3.0);
}
#[test]
fn triple_deal_weights_are_a_symmetric_distribution_close_to_the_pairwise_one() {
let env = Environment::frozen();
let tree = push_fold3_tree(&env, Seat::Button, 10.0).expect("tree");
let n = CLASS_COUNT;
let (aa, kk, ak, t9) = (class("Ah As"), class("Kh Ks"), class("Ah Kd"), class("Th 9h"));
assert!((tree.weight(aa, kk, ak) - tree.weight(ak, aa, kk)).abs() < 1e-18);
// Three pairs of aces cannot be dealt; the pairwise product only makes it rare (a known limit
// of the approximation: 0.7 % of the weight of AA, KK, T9s, which needs no shared card).
assert!(tree.weight(aa, aa, aa) < 0.01 * tree.weight(aa, kk, t9));
let total: f64 = (0..n).map(|i| (0..n).map(|j| (0..n).map(|k| tree.weight(i, j, k)).sum::<f64>()).sum::<f64>()).sum();
assert!((total - 1.0).abs() < 1e-9, "total {total}");
// The two-player marginal stays within a few percent of the exact pairwise weight.
for (i, j) in [(aa, kk), (aa, ak), (ak, t9), (kk, kk)] {
let marginal: f64 = (0..n).map(|k| tree.weight(i, j, k)).sum();
let exact = env.chance.probability(i, j);
assert!((marginal / exact - 1.0).abs() < 0.05, "({i}, {j}): marginal {marginal}, exact {exact}");
}
}
fn pure(tree: &rechner::cfr::tree3::Tree3, aggressive: bool) -> Strategy {
Strategy::pure(tree, |_, _| if aggressive { 1 } else { 0 })
}
#[test]
fn push_fold_identities() {
let env = Environment::frozen_free_table();
// Button: nobody between the button and the small blind.
let tree = push_fold3_tree(&env, Seat::Button, 10.0).expect("tree");
// Everybody folds: the button's fold is worth 0.
assert!(game_value3(&tree, &pure(&tree, false), 0).abs() < 1e-12);
// The button always jams, both blinds always fold: +1.5 / -0.5 / -1.
let steal = Strategy::pure(&tree, |name, _| usize::from(name == "push"));
let values = [0, 1, 2].map(|p| game_value3(&tree, &steal, p));
assert!((values[0] - 1.5).abs() < 1e-9 && (values[1] + 0.5).abs() < 1e-9 && (values[2] + 1.0).abs() < 1e-9, "{values:?}");
// Everybody jams and calls: a symmetric three-way all-in, every player breaks even.
let all_in = pure(&tree, true);
for p in 0..3 {
assert!(game_value3(&tree, &all_in, p).abs() < 1e-9, "player {p}");
}
// Calling everything is exploitable, the frozen-style check can fail.
assert!(exploitability3(&tree, &all_in) > 0.1);
}
#[test]
fn the_trees_have_the_documented_decisions_and_refuse_bad_input() {
let env = Environment::frozen();
let names = |nodes: &[Node3]| -> Vec<&'static str> {
nodes.iter().filter_map(|n| match n {
Node3::Decision { name, .. } => Some(*name),
_ => None,
}).collect()
};
let push = push_fold3_tree(&env, Seat::Early, 12.0).expect("tree");
let mut found = names(&push.nodes);
found.sort();
assert_eq!(found, vec!["bb_overcall", "call", "push", "sb_call"]);
let open = open3_tree(&env, Seat::Cutoff, 40.0).expect("tree");
let mut found = names(&open.nodes);
found.sort();
assert_eq!(found, vec!["bb_overcall", "defend", "open", "sb_defend", "sb_vs_jam", "vs_jam", "vs_sb_three_bet", "vs_three_bet"]);
assert!(push_fold3_tree(&env, Seat::SmallBlind, 10.0).is_err());
assert!(open3_tree(&env, Seat::SmallBlind, 40.0).is_err());
assert!(open3_tree(&env, Seat::Button, 10.0).is_err());
assert!(push_fold3_tree(&env, Seat::Button, f64::NAN).is_err());
}