Files
pokerfreak/src/icm/push_fold.rs
T
mmintelandClaude Opus 5.5 91fe71d37d Turnier: chip-lineares Geld spielt exakt den Cash-Pfad (WTA-Test wieder gruen)
tests/pipeline_tournament.rs winner_takes_all_is_cash_on_the_wire war rot (68 vs 88 Calls): der
Push/Fold-Solver lieferte beim WTA Chip-NASH statt des Cash-Pfads. Allgemein ist Geld affin in Chips,
wenn Platz 2..n gleich zahlen (unbezahlt = 0): Turnierlage::is_chip_linear. decide_with laesst eine
solche Lage fallen (der Solver prueft es zusaetzlich); unbepreisbar bleibt Aussetzen.
Zweiter Fall gefunden: alle Verbliebenen gleich bezahlt -> der alte Risiko-Pfad callte 0 von 169
(Praemie explodiert ohne Chip-Abhaengigkeit), jetzt 88 = Cash. Neuer Test chip_linear_money_is_cash_on_the_wire
(gleich bezahlt, 70/10/10/10, WTA-Liste laenger als das Feld, HU 65/35) + Einheitstests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 00:29:34 +01:00

517 lines
22 KiB
Rust

//! ICM push/fold: the short-stack all-in game solved in PRIZE money, antes included.
//!
//! Two preflop spots of a tournament table are the whole game at short depth:
//! * hero FIRST IN at or below `OPEN_JAM_MAX_BB` effective: jam or fold;
//! * hero FACING the lone jam of the first raiser (no caller in between) at or below
//! `CALL_JAM_MAX_BB`: call or fold.
//!
//! Both are one `JamGame`: a pusher, then the players behind it who may call, in acting order.
//! The game is solved by fictitious play over the 169 hand classes on the engine's own all-in
//! equity table (`cfr::generated_equity`), with every terminal valued by Malmuth-Harville
//! (`harville::equities`) over the WHOLE field under the pay structure:
//! * all fold: the pusher takes the pot (blinds AND antes - the dead money that makes short
//! stacks jam wide);
//! * caller `i` calls (the callers before it folded, the ones after fold too - no overcalls): a
//! heads-up all-in for `min(pusher, caller)` plus the dead money of everybody else;
//! * the pusher folds (hero first in): hero keeps what it has not posted, the big blind takes
//! the rest.
//!
//! The caller's fold value is the all-fold terminal. Card removal and overcalls are ignored (the
//! standard ICM push/fold approximation, as in `entscheiden/turnier_referenz.nash_icm_push`,
//! which this generalises from one bystander and heads-up to any field and table).
//!
//! The answer is the best response of HERO's actual class against the equilibrium of the other
//! side, plus the equilibrium width (share of combos that jam / call) - the base the exploit width
//! may move (`preflop::exploit_border`), exactly as the frozen chip tables do in cash.
//!
//! Only with a `Turnierlage`: cash never reaches this module (`engine::decide` calls it only
//! when the request carries `tournament`). Anything the game cannot model (limps, several
//! raises, a caller before hero, a field larger than `MAX_FIELD`, other variants) returns `None`
//! and the calibrated chip path with its ICM premium (`icm::risk`) stays in charge.
use super::harville::equities;
use super::lage::Turnierlage;
use crate::cfr::equity_matrix::EquityMatrix;
use crate::cfr::frozen_equity::frozen_equity;
use crate::cfr::hand_class::{class_combos, class_of, CLASS_COUNT};
use crate::game::{SeenAction, Spot, Street};
use crate::preflop::effective_stack::effective_stack_bb;
use crate::preflop::first_raiser::{preflop_callers, raise_count, sole_raiser};
use crate::variant::Variant;
use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
use std::sync::OnceLock;
/// Measurement switch (always on in play): the strength ladder turns the solver off for the
/// paired A/B against the calibrated chip path (`sim::turnier_leiter::messen_solver`).
static ENABLED: AtomicBool = AtomicBool::new(true);
/// Turns the solver on or off for this process (ladder A/B only).
pub fn set_enabled(on: bool) {
ENABLED.store(on, Ordering::Relaxed);
}
/// Which halves the solver answers (ladder diagnosis only; play keeps both): bit 1 = first-in
/// jam, bit 2 = call/fold against a lone jam.
static SIDES: AtomicU8 = AtomicU8::new(3);
/// Restricts the solver to `sides` (bit 1 jam, bit 2 call) for this process (ladder only).
pub fn set_sides(sides: u8) {
SIDES.store(sides, Ordering::Relaxed);
}
/// Hero first in at or below this effective depth (big blinds) is a push/fold spot.
pub const OPEN_JAM_MAX_BB: f64 = 15.0;
/// Hero facing a lone jam at or below this effective depth is solved as a call/fold spot
/// (the same depth the frozen chip tables use for calling jams).
pub const CALL_JAM_MAX_BB: f64 = 25.0;
/// Largest field the solver prices (each terminal is one Harville evaluation; above
/// `harville::MAX_PLAYERS` it is sampled, 20 000 orders x field).
pub const MAX_FIELD: usize = 200;
/// Fictitious-play rounds; the average strategy moves by `1 / (t + 2)`.
pub const ROUNDS: usize = 150;
/// A busted stack is priced at this (Harville needs a positive rate; it finishes last).
const BUST_FLOOR: f64 = 1e-9;
/// What hero should do, and how wide the equilibrium continues for hero's side.
#[derive(Clone, Debug, PartialEq)]
pub struct PushFoldAnswer {
/// Jam (first in) or call (facing a jam) is worth more prize money than folding.
pub continue_: bool,
/// Hero facing a jam (`true`) or first in (`false`).
pub facing_jam: bool,
/// Share of combos hero's side continues with at equilibrium (jam or call).
pub width: f64,
/// Prize money of continuing minus folding for hero's class (pool units of `payouts`).
pub edge: f64,
/// Effective depth in big blinds.
pub depth_bb: f64,
/// Number of modelled callers behind the pusher.
pub callers: usize,
}
struct Table {
eq: Vec<f64>,
weight: [f64; CLASS_COUNT],
}
fn table() -> &'static Table {
static T: OnceLock<Table> = OnceLock::new();
T.get_or_init(|| {
let m: EquityMatrix = frozen_equity();
let mut eq = vec![0.5; CLASS_COUNT * CLASS_COUNT];
for i in 0..CLASS_COUNT {
for j in 0..CLASS_COUNT {
eq[i * CLASS_COUNT + j] = m.get(i, j);
}
}
let mut weight = [0.0; CLASS_COUNT];
for (c, w) in weight.iter_mut().enumerate() {
*w = class_combos(c).len() as f64;
}
Table { eq, weight }
})
}
/// Prize values of the terminals, for the pusher and each caller.
#[derive(Clone, Debug, PartialEq)]
pub struct Terminals {
/// Pusher's money when everybody folds.
pub pusher_all_fold: f64,
/// Pusher's money when it folds itself (only meaningful when hero is the pusher).
pub pusher_fold: f64,
/// Per caller: (pusher wins, pusher loses) for the pusher.
pub pusher_vs: Vec<(f64, f64)>,
/// Per caller: (fold = all fold, call and win, call and lose) for the caller.
pub caller: Vec<(f64, f64, f64)>,
}
/// One modelled player of the hand: index into the priced stacks, chips at hand start, forced
/// chips posted (blinds and antes).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Seat {
pub index: usize,
pub start: f64,
pub posted: f64,
}
/// The terminals of the jam game. `stacks` is the field at hand start (table players' entries
/// already their hand-start chips), `forced` the forced pot (all blinds and antes), `bb_index`
/// the player that takes the pot when the pusher folds.
pub fn terminals(
stacks: &[f64],
payouts: &[f64],
pusher: Seat,
callers: &[Seat],
table_posts: &[Seat],
forced: f64,
bb_index: usize,
) -> Terminals {
// Everybody at the table loses what it posted; the field away from the table is untouched.
let base = || {
let mut s = stacks.to_vec();
for p in table_posts {
s[p.index] = p.start - p.posted;
}
s
};
let money = |s: &[f64]| {
let priced: Vec<f64> = s.iter().map(|x| x.max(BUST_FLOOR)).collect();
equities(&priced, payouts)
};
let mut all_fold = base();
all_fold[pusher.index] += forced;
let v_all = money(&all_fold);
let mut folded = base();
folded[bb_index] += forced;
let v_fold = money(&folded);
let mut pusher_vs = Vec::with_capacity(callers.len());
let mut caller = Vec::with_capacity(callers.len());
for c in callers {
let risk = pusher.start.min(c.start);
let dead = forced - pusher.posted - c.posted;
let mut win = base();
win[pusher.index] = pusher.start + risk + dead;
win[c.index] = c.start - risk;
let mut lose = base();
lose[pusher.index] = pusher.start - risk;
lose[c.index] = c.start + risk + dead;
let (w, l) = (money(&win), money(&lose));
pusher_vs.push((w[pusher.index], l[pusher.index]));
caller.push((v_all[c.index], l[c.index], w[c.index]));
}
Terminals { pusher_all_fold: v_all[pusher.index], pusher_fold: v_fold[pusher.index], pusher_vs, caller }
}
/// Equilibrium of the jam game: (push frequency per class, call frequency per class per caller).
pub fn solve(t: &Terminals) -> (Vec<f64>, Vec<Vec<f64>>) {
let tab = table();
let k = t.caller.len();
let mut push = vec![1.0; CLASS_COUNT];
let mut call = vec![vec![0.0; CLASS_COUNT]; k];
for round in 0..ROUNDS {
let step = 1.0 / (round as f64 + 2.0);
// Callers: best response to the average push range.
let push_mass: f64 = (0..CLASS_COUNT).map(|h| push[h] * tab.weight[h]).sum();
let mut call_br = vec![vec![0.0; CLASS_COUNT]; k];
if push_mass > 0.0 {
for c in 0..CLASS_COUNT {
let row = &tab.eq[c * CLASS_COUNT..(c + 1) * CLASS_COUNT];
let e: f64 = (0..CLASS_COUNT).map(|h| push[h] * tab.weight[h] * row[h]).sum::<f64>() / push_mass;
for (i, &(fold, win, lose)) in t.caller.iter().enumerate() {
if e * win + (1.0 - e) * lose > fold {
call_br[i][c] = 1.0;
}
}
}
}
// Pusher: best response to the average call ranges.
let push_br = pusher_best_response(t, &call, tab);
for c in 0..CLASS_COUNT {
push[c] += (push_br[c] - push[c]) * step;
for i in 0..k {
call[i][c] += (call_br[i][c] - call[i][c]) * step;
}
}
}
(push, call)
}
/// Prize money of jamming each class against the call ranges.
fn push_values(t: &Terminals, call: &[Vec<f64>], tab: &Table) -> Vec<f64> {
let total: f64 = tab.weight.iter().sum();
let mut value = vec![0.0; CLASS_COUNT];
let mut reach = 1.0;
for (i, range) in call.iter().enumerate() {
let mass: f64 = (0..CLASS_COUNT).map(|c| range[c] * tab.weight[c]).sum();
let q = mass / total;
let (win, lose) = t.pusher_vs[i];
for (h, v) in value.iter_mut().enumerate() {
let e = if mass > 0.0 {
let row = &tab.eq[h * CLASS_COUNT..(h + 1) * CLASS_COUNT];
(0..CLASS_COUNT).map(|c| range[c] * tab.weight[c] * row[c]).sum::<f64>() / mass
} else {
0.5
};
*v += reach * q * (e * win + (1.0 - e) * lose);
}
reach *= 1.0 - q;
}
for v in &mut value {
*v += reach * t.pusher_all_fold;
}
value
}
fn pusher_best_response(t: &Terminals, call: &[Vec<f64>], tab: &Table) -> Vec<f64> {
push_values(t, call, tab).iter().map(|v| if *v > t.pusher_fold { 1.0 } else { 0.0 }).collect()
}
fn share(range: &[f64], tab: &Table) -> f64 {
let total: f64 = tab.weight.iter().sum();
(0..CLASS_COUNT).map(|c| range[c].round() * tab.weight[c]).sum::<f64>() / total
}
/// Hero's chips at hand start: what the field lists for hero.
fn hand_start(lage: &Turnierlage) -> f64 {
lage.stacks[lage.hero]
}
/// Forced chips a seat posted this hand (blinds and antes).
fn posted(spot: &Spot, seat: u8) -> f64 {
let preflop = || spot.history.iter().filter(move |r| r.street == Street::Preflop && r.seat == seat);
let ante: f64 = preflop().filter(|r| r.action == SeenAction::PostAnte).filter_map(|r| r.amount).sum();
let blind = preflop()
.filter(|r| matches!(r.action, SeenAction::PostSmallBlind | SeenAction::PostBigBlind))
.filter_map(|r| r.amount)
.fold(0.0, f64::max);
ante + blind
}
/// Everything a seat put in this hand so far (antes plus its street total preflop).
fn committed(spot: &Spot, seat: u8) -> f64 {
let preflop = || spot.history.iter().filter(move |r| r.street == Street::Preflop && r.seat == seat);
let ante: f64 = preflop().filter(|r| r.action == SeenAction::PostAnte).filter_map(|r| r.amount).sum();
let street = preflop().filter(|r| r.action != SeenAction::PostAnte).filter_map(|r| r.amount).fold(0.0, f64::max);
ante + street
}
/// Who posted the big blind (takes the pot when the pusher folds).
fn big_blind_seat(spot: &Spot) -> Option<u8> {
spot.history
.iter()
.find(|r| r.street == Street::Preflop && r.action == SeenAction::PostBigBlind)
.map(|r| r.seat)
}
/// Acting order after `from` around the ring of `seats`.
fn after(seats: u8, from: u8, seat: u8) -> u8 {
let n = seats.max(1);
((seat + n - from) % n).max(1)
}
/// The field with each table villain's entry replaced by its hand-start chips: villains are
/// matched to the nearest unmatched field stack (the rank list lags the table a little); a
/// villain without a match is appended.
fn place_villains(lage: &Turnierlage, table: &[(u8, f64)]) -> (Vec<f64>, Vec<(u8, usize)>) {
let mut stacks = lage.stacks.clone();
let mut taken = vec![false; stacks.len()];
taken[lage.hero] = true;
let mut placed = Vec::with_capacity(table.len());
for &(seat, start) in table {
let best = (0..stacks.len())
.filter(|i| !taken[*i])
.min_by(|a, b| (lage.stacks[*a] - start).abs().total_cmp(&(lage.stacks[*b] - start).abs()));
let index = match best {
Some(i) => i,
None => {
stacks.push(start);
taken.push(false);
stacks.len() - 1
}
};
taken[index] = true;
stacks[index] = start;
placed.push((seat, index));
}
(stacks, placed)
}
/// The ICM push/fold answer for hero, or `None` when the spot is not a modelled jam game.
pub fn push_fold(spot: &Spot, lage: &Turnierlage) -> Option<PushFoldAnswer> {
if !ENABLED.load(Ordering::Relaxed) {
return None;
}
if !lage.is_usable() || lage.is_chip_linear() || lage.stacks.len() > MAX_FIELD || spot.street != Street::Preflop {
// Chip-linear money (winner takes all, everyone left paid alike): ICM IS chip-EV, the cash
// path plays it unchanged (tests/pipeline_tournament.rs winner_takes_all_is_cash_on_the_wire).
return None;
}
if !matches!(spot.variant, Variant::Nlhe | Variant::Aof) || spot.hero_cards.len() != 2 {
return None;
}
if !(spot.big_blind.is_finite() && spot.big_blind > 0.0) || !preflop_callers(spot).is_empty() {
return None;
}
let hero_class = class_of(spot.hero_cards[0], spot.hero_cards[1])?;
let big_blind = big_blind_seat(spot)?;
let hero_start = hand_start(lage);
// Every seat dealt in that the history or the villains name; folded villains still posted.
let mut seats: Vec<u8> = spot.villains.iter().map(|v| v.seat).collect();
for r in spot.history.iter().filter(|r| r.street == Street::Preflop) {
if r.seat != spot.hero_seat && !seats.contains(&r.seat) {
seats.push(r.seat);
}
}
let stack_of = |seat: u8| spot.villains.iter().find(|v| v.seat == seat).map(|v| v.stack);
let table_starts: Vec<(u8, f64)> =
seats.iter().filter_map(|s| stack_of(*s).map(|st| (*s, st + committed(spot, *s)))).collect();
let (mut stacks, placed) = place_villains(lage, &table_starts);
stacks[lage.hero] = hero_start;
let stacks = stacks;
let index_of = |seat: u8| -> Option<usize> {
if seat == spot.hero_seat {
Some(lage.hero)
} else {
placed.iter().find(|(s, _)| *s == seat).map(|(_, i)| *i)
}
};
let seat_of = |seat: u8| -> Option<Seat> {
let index = index_of(seat)?;
Some(Seat { index, start: stacks[index], posted: posted(spot, seat) })
};
let hero = Seat { index: lage.hero, start: hero_start, posted: posted(spot, spot.hero_seat) };
let table_posts: Vec<Seat> =
std::iter::once(hero).chain(seats.iter().filter_map(|s| seat_of(*s))).collect();
let forced: f64 = table_posts.iter().map(|p| p.posted).sum();
let bb_index = index_of(big_blind)?;
let folded_before = |seat: u8, jam_at: usize| {
spot.history.iter().take(jam_at).any(|r| r.seat == seat && r.action == SeenAction::Fold)
};
match raise_count(spot) {
0 if SIDES.load(Ordering::Relaxed) & 1 != 0 => {
// First in: hero pushes, every live villain may call, in acting order.
let depth = effective_stack_bb(spot);
if depth > OPEN_JAM_MAX_BB || !spot.history.iter().any(|r| r.action == SeenAction::PostBigBlind) {
return None;
}
if spot.to_call > spot.big_blind + 1e-9 || big_blind == spot.hero_seat {
return None; // a limp or hero's own option: not a first-in jam
}
let mut behind: Vec<&crate::game::Villain> = spot.live_villains().collect();
behind.sort_by_key(|v| after(spot.seats, spot.hero_seat, v.seat));
let callers: Vec<Seat> = behind.iter().filter_map(|v| seat_of(v.seat)).collect();
if callers.is_empty() || callers.len() != behind.len() {
return None;
}
let t = terminals(&stacks, &lage.payouts, hero, &callers, &table_posts, forced, bb_index);
let (_, call) = solve(&t);
let tab = table();
let values = push_values(&t, &call, tab);
let br: Vec<f64> = values.iter().map(|v| if *v > t.pusher_fold { 1.0 } else { 0.0 }).collect();
let edge = values[hero_class] - t.pusher_fold;
Some(PushFoldAnswer {
continue_: edge > 0.0,
facing_jam: false,
width: share(&br, tab),
edge,
depth_bb: depth,
callers: callers.len(),
})
}
1 if SIDES.load(Ordering::Relaxed) & 2 != 0 => {
// Facing the lone jam of the first raiser.
let jammer = sole_raiser(spot)?;
let jam_at = spot
.history
.iter()
.position(|r| r.street == Street::Preflop && r.seat == jammer && r.action.is_aggressive())?;
let jam = spot.history[jam_at];
let jammer_stack = stack_of(jammer)?;
let all_in = jam.action == SeenAction::AllIn || jammer_stack <= 1e-9;
if !all_in || spot.to_call <= 0.0 {
return None;
}
let pusher = seat_of(jammer)?;
let depth = pusher.start.min(hero_start) / spot.big_blind;
if depth > CALL_JAM_MAX_BB {
return None;
}
// The players behind the jammer when it jammed: hero first (it acts now), then the
// live villains still to act; who folded before the jam was not behind it.
let mut behind: Vec<u8> = seats
.iter()
.copied()
.filter(|s| *s != jammer && !folded_before(*s, jam_at))
.filter(|s| {
spot.villains.iter().any(|v| v.seat == *s && !v.folded)
|| spot.history.iter().skip(jam_at).any(|r| r.seat == *s && r.action == SeenAction::Fold)
})
.collect();
behind.sort_by_key(|s| after(spot.seats, jammer, *s));
let mut callers: Vec<Seat> = vec![hero];
callers.extend(behind.iter().filter(|s| **s != spot.hero_seat).filter_map(|s| seat_of(*s)));
callers.sort_by_key(|c| {
let seat = if c.index == hero.index {
spot.hero_seat
} else {
placed.iter().find(|(_, i)| *i == c.index).map_or(spot.hero_seat, |(s, _)| *s)
};
after(spot.seats, jammer, seat)
});
let me = callers.iter().position(|c| c.index == hero.index)?;
let t = terminals(&stacks, &lage.payouts, pusher, &callers, &table_posts, forced, bb_index);
let (push, call) = solve(&t);
let tab = table();
let mass: f64 = (0..CLASS_COUNT).map(|h| push[h] * tab.weight[h]).sum();
if mass <= 0.0 {
return None;
}
let row = &tab.eq[hero_class * CLASS_COUNT..(hero_class + 1) * CLASS_COUNT];
let e: f64 = (0..CLASS_COUNT).map(|h| push[h] * tab.weight[h] * row[h]).sum::<f64>() / mass;
let (fold, win, lose) = t.caller[me];
let edge = e * win + (1.0 - e) * lose - fold;
Some(PushFoldAnswer {
continue_: edge > 0.0,
facing_jam: true,
width: share(&call[me], tab),
edge,
depth_bb: depth,
callers: callers.len(),
})
}
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
fn hu(hero: f64, opp: f64, field: &[f64]) -> (Vec<f64>, Seat, Seat) {
let mut stacks = vec![hero, opp];
stacks.extend_from_slice(field);
(stacks, Seat { index: 0, start: hero, posted: 0.5 }, Seat { index: 1, start: opp, posted: 1.0 })
}
fn widths(payouts: &[f64], hero: f64, opp: f64, field: &[f64]) -> (f64, f64) {
let (stacks, p, c) = hu(hero, opp, field);
let t = terminals(&stacks, payouts, p, &[c], &[p, c], 1.5, 1);
let (push, call) = solve(&t);
let tab = table();
(share(&push, tab), share(&call[0], tab))
}
#[test]
fn winner_take_all_heads_up_is_the_chip_nash() {
// One prize, two players: ICM money IS the chip share - the solver is chip Nash. HU 10bb:
// jam ~60 %, call ~38 % (the frozen chip tables, `push_chart` and turnier_referenz).
let (jam, call) = widths(&[1.0], 10.0, 10.0, &[]);
assert!((jam - 0.60).abs() < 0.05, "chip-Nash jam ~60 %: {jam}");
assert!((call - 0.38).abs() < 0.05, "chip-Nash call ~38 %: {call}");
}
#[test]
fn bubble_with_a_short_bystander_matches_the_icm_nash_reference() {
// entscheiden/turnier_referenz.nash_icm_push, HU 10bb/10bb, 50/30/20, short bystander
// 2/5/9bb: ICM-Nash jam 97/79/65 %, call 14/18/22 %. Frozen anchor, +-5pp.
for (short, jam_ref, call_ref) in [(2.0, 0.97, 0.14), (5.0, 0.79, 0.18), (9.0, 0.65, 0.22)] {
let (jam, call) = widths(&[50.0, 30.0, 20.0], 10.0, 10.0, &[short]);
assert!((jam - jam_ref).abs() < 0.05, "short {short}: jam {jam} vs {jam_ref}");
assert!((call - call_ref).abs() < 0.05, "short {short}: call {call} vs {call_ref}");
}
}
#[test]
fn antes_widen_the_jam() {
// The same 10bb heads-up with 1.2bb of antes in the middle: more dead money, wider jam.
let (stacks, p, c) = hu(10.0, 10.0, &[]);
let plain = terminals(&stacks, &[1.0], p, &[c], &[p, c], 1.5, 1);
let p_a = Seat { posted: 0.5 + 0.6, ..p };
let c_a = Seat { posted: 1.0 + 0.6, ..c };
let ante = terminals(&stacks, &[1.0], p_a, &[c_a], &[p_a, c_a], 2.7, 1);
let tab = table();
let (a, b) = (share(&solve(&plain).0, tab), share(&solve(&ante).0, tab));
assert!(b > a + 0.05, "antes widen the jam: {a} -> {b}");
}
}