- engine::audit_turn: Turn-Entscheidungen im Turn+River-Spiel (E3-Löser) nachgerechnet, EV je Aktion fuer die echte Hand (TrSolver::hand_action_values), Gegner-Range entlang der Linie - engine::audit_allin: Preflop gegen All-in (Equity gegen Nash-Push-Range vs Preis), Push/Fold first-in <= 25 bb (Nash-Spiel der Charts), Flop gegen All-in (exakte Equity vs Preis) - bin/audit: Feld method/note, --turn-iters/--turn-combos/--turn-cards - lesen/audit_lauf.py: exakte Spots aus dem Schatten-Log, Cache je Lauf, Bericht je Lauf (Street, Messlatte, Engine-Teil, Top 10), Wochensumme, Fixture-Vorschlaege - sicht/audit_seite.py + Route: /audit, /api/audit, /api/audit/laeufe, /api/audit/woche - betrieb/audit_haken.py + docs/notizen/D4-audit-haken.patch (runner.py, 3 Zeilen) - tests/audit_lauf_spec.py 12/12; cargo test engine::audit 14/14 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
273 lines
12 KiB
Rust
273 lines
12 KiB
Rust
//! Decision audit (plan D4) on the turn: re-solve a real heads-up turn decision with the turn+river
|
|
//! game over real combos (`cfr::turn_river_game`, the E3 solver) and price the action taken.
|
|
//!
|
|
//! Same definitions as the river audit (`engine::audit`): the EV of an action is hero's expected
|
|
//! chips after taking it at the node and playing the solved strategy afterwards, against the solved
|
|
//! villain, whose range is conditioned on the observed turn line; the loss is `EV(best) - EV(taken)`.
|
|
//! The scale is the game's: chips from the start of the turn, each player counted as having put
|
|
//! `pot / 2` in. Only differences between actions mean anything.
|
|
//!
|
|
//! Ranges as on the river: the blueprint where it knows the spot (`$GRUNDSTRATEGIE`, scenario S1),
|
|
//! else the engine's range model for both players. Hero's real hand is always in the game (added at
|
|
//! the mean weight when the model would not have played it, flagged `hero_in_range = false`).
|
|
//!
|
|
//! Named approximations (all in `Opts`): at most `turn_combos` combos per player (the heaviest; equal
|
|
//! weights are thinned by a fixed hash, not by card order, so the sample is not biased towards a
|
|
//! suit or rank); `turn_cards` river cards evenly strided, each standing for its share; the bet menu
|
|
//! of `TrBets::standard` plus the size played; `turn_iters` CFR+ iterations; no river raise.
|
|
|
|
use crate::card::Card;
|
|
use crate::cfr::river_game::Act;
|
|
use crate::cfr::turn_river_game::{build, Hands, TNode, TrBets, TrSolver};
|
|
use crate::engine::audit::{ranges, ActEv, Audit, Opts, Skip, Taken};
|
|
use crate::engine::turn_game::turn_line;
|
|
use crate::game::{Spot, Street};
|
|
use crate::hand::fast7;
|
|
|
|
/// A deterministic shuffle key: ties in weight are broken by this, not by the card mask.
|
|
fn mix(m: u64) -> u64 {
|
|
let mut x = m.wrapping_mul(0x9E37_79B9_7F4A_7C15);
|
|
x ^= x >> 31;
|
|
x.wrapping_mul(0xBF58_476D_1CE4_E5B9)
|
|
}
|
|
|
|
/// Masks and weights of a combo list: off the board, deduplicated, the `max` heaviest (ties by a fixed
|
|
/// hash), `keep` always in.
|
|
pub(crate) fn thin(list: &[(Vec<Card>, f64)], board: u64, max: usize, keep: Option<u64>) -> Hands {
|
|
let mut v: Vec<(u64, f64)> = list
|
|
.iter()
|
|
.filter(|(c, w)| c.len() == 2 && *w > 0.0 && w.is_finite())
|
|
.map(|(c, w)| (fast7::mask(c), *w))
|
|
.filter(|(m, _)| m & board == 0 && m.count_ones() == 2)
|
|
.collect();
|
|
v.sort_by_key(|x| x.0);
|
|
v.dedup_by_key(|x| x.0);
|
|
v.sort_by(|a, b| b.1.total_cmp(&a.1).then(mix(a.0).cmp(&mix(b.0))));
|
|
let kept = keep.and_then(|k| v.iter().find(|x| x.0 == k).map(|x| x.1));
|
|
v.truncate(max.max(1));
|
|
if let Some(k) = keep {
|
|
if !v.iter().any(|x| x.0 == k) {
|
|
let mean = v.iter().map(|x| x.1).sum::<f64>() / v.len().max(1) as f64;
|
|
v.push((k, kept.unwrap_or(mean).max(1e-9)));
|
|
}
|
|
}
|
|
Hands { masks: v.iter().map(|x| x.0).collect(), weights: v.iter().map(|x| x.1).collect() }
|
|
}
|
|
|
|
/// Audit one heads-up turn decision.
|
|
pub fn audit_turn(spot: &Spot, taken: Taken, opts: Opts) -> Result<Audit, Skip> {
|
|
if spot.street != Street::Turn || spot.board.len() != 4 {
|
|
return Err(Skip::Street(spot.street));
|
|
}
|
|
let gated = crate::engine::read_gate::gate_reads(spot);
|
|
let spot = &gated;
|
|
if spot.live_villains().count() != 1 {
|
|
return Err(Skip::Multiway);
|
|
}
|
|
if spot.hero_cards.len() != 2 {
|
|
return Err(Skip::NoRange("not a two-card hand"));
|
|
}
|
|
let villain = spot.live_villains().next().ok_or(Skip::Multiway)?;
|
|
let (mut hero_list, villain_list, source) = ranges(spot, villain).ok_or(Skip::NoRange("range lists"))?;
|
|
let held = |c: &Vec<Card>| c.len() == 2 && c.iter().all(|x| spot.hero_cards.contains(x));
|
|
let hero_in_range = hero_list.iter().any(|(c, _)| held(c));
|
|
if !hero_in_range {
|
|
let mean = hero_list.iter().map(|(_, w)| w).sum::<f64>() / hero_list.len().max(1) as f64;
|
|
hero_list.push((spot.hero_cards.clone(), mean.max(1e-9)));
|
|
}
|
|
let (first, line, c) = turn_line(spot, villain);
|
|
let pot = spot.pot - c[0] - c[1];
|
|
if pot <= 0.0 {
|
|
return Err(Skip::NoRange("pot at street start"));
|
|
}
|
|
let stack = (spot.hero_stack + c[0]).min(villain.stack + c[1]);
|
|
if stack <= c[0].max(c[1]) + 1e-9 && spot.to_call <= 0.0 {
|
|
return Err(Skip::NoRange("no stack behind"));
|
|
}
|
|
let aggressed = line.iter().any(|a| matches!(a, Act::Bet(_) | Act::Raise(_)));
|
|
let act = match taken {
|
|
Taken::Fold if spot.to_call > 0.0 => Act::Fold,
|
|
Taken::Fold => return Err(Skip::Illegal("fold with nothing to call")),
|
|
Taken::Check if spot.to_call == 0.0 => Act::Check,
|
|
Taken::Check => return Err(Skip::Illegal("check facing a bet")),
|
|
Taken::Call if spot.to_call > 0.0 => Act::Call,
|
|
Taken::Call => return Err(Skip::Illegal("call with nothing to call")),
|
|
Taken::Aggress(to) if aggressed => Act::Raise(to.min(stack)),
|
|
Taken::Aggress(to) => Act::Bet(to.min(stack)),
|
|
};
|
|
let aggressive = matches!(act, Act::Bet(_) | Act::Raise(_));
|
|
let mut forced = line.clone();
|
|
if aggressive {
|
|
forced.push(act);
|
|
}
|
|
let board = fast7::mask(&spot.board);
|
|
let hero_mask = fast7::mask(&spot.hero_cards);
|
|
if hero_mask & board != 0 {
|
|
return Err(Skip::NoRange("hero cards on the board"));
|
|
}
|
|
let hands = [thin(&hero_list, board, opts.turn_combos, Some(hero_mask)), thin(&villain_list, board, opts.turn_combos, None)];
|
|
if hands[1].masks.is_empty() {
|
|
return Err(Skip::NoRange("villain range empty"));
|
|
}
|
|
let hand = hands[0].masks.iter().position(|m| *m == hero_mask).ok_or(Skip::NoRange("hero hand"))?;
|
|
let combos = [hands[0].masks.len(), hands[1].masks.len()];
|
|
let mut bets = TrBets::standard(pot, stack, first);
|
|
bets.river.max_raises = 0;
|
|
let game = build(&bets, &forced);
|
|
let at = game.at.ok_or(Skip::LineLeftTree)?;
|
|
let hero_node = if aggressive {
|
|
(0..game.nodes.len())
|
|
.find(|&i| matches!(&game.nodes[i], TNode::Dec { kids, .. } if kids.contains(&at)))
|
|
.ok_or(Skip::LineLeftTree)?
|
|
} else {
|
|
at
|
|
};
|
|
if !matches!(game.nodes.get(hero_node), Some(TNode::Dec { player: 0, street: 0, .. })) {
|
|
return Err(Skip::LineLeftTree);
|
|
}
|
|
let acts = game.acts[hero_node].clone();
|
|
let nodes = game.nodes.len();
|
|
let mut solver = TrSolver::new(game, hands, board, Some(opts.turn_cards.max(1)));
|
|
solver.run(opts.turn_iters.max(1));
|
|
let strategy = solver.strategy();
|
|
let exploit = solver.exploitability(&strategy).total;
|
|
let (values, off_line) = solver.hand_action_values(&strategy, hero_node, hand).ok_or(Skip::NoRange("hero class has no deals"))?;
|
|
let mix_row = strategy.row(hero_node, 0, hand).to_vec();
|
|
let list: Vec<ActEv> = acts
|
|
.iter()
|
|
.zip(&values)
|
|
.enumerate()
|
|
.map(|(k, (a, ev))| ActEv { act: *a, prob: mix_row.get(k).copied().unwrap_or(0.0), ev: *ev })
|
|
.collect();
|
|
let mut taken_ix = None;
|
|
let mut size_gap = 0.0;
|
|
for (k, ae) in list.iter().enumerate() {
|
|
match (ae.act, act) {
|
|
(Act::Bet(x), Act::Bet(y)) | (Act::Raise(x), Act::Raise(y)) => {
|
|
let gap = (x - y).abs() / x.max(y).max(1e-9);
|
|
if taken_ix.is_none() || gap < size_gap {
|
|
taken_ix = Some(k);
|
|
size_gap = gap;
|
|
}
|
|
}
|
|
(a, t) if a == t => {
|
|
taken_ix = Some(k);
|
|
size_gap = 0.0;
|
|
break;
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
let taken_ix = taken_ix.ok_or(Skip::LineLeftTree)?;
|
|
let ev_best = list.iter().map(|a| a.ev).fold(f64::NEG_INFINITY, f64::max);
|
|
let ev_mix: f64 = list.iter().map(|a| a.prob * a.ev).sum();
|
|
let ev_taken = list[taken_ix].ev;
|
|
Ok(Audit {
|
|
source,
|
|
class: hand,
|
|
classes: combos[0],
|
|
nodes,
|
|
first,
|
|
acts: list,
|
|
taken: taken_ix,
|
|
size_gap,
|
|
ev_best,
|
|
ev_mix,
|
|
ev_taken,
|
|
loss: (ev_best - ev_taken).max(0.0),
|
|
off_line,
|
|
hero_in_range,
|
|
exploitability: exploit,
|
|
method: "turn_river_game",
|
|
note: format!("{}x{} combos, {} river cards, {} iterations", combos[0], combos[1], opts.turn_cards, opts.turn_iters),
|
|
})
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use crate::game::{ActionKind, Villain};
|
|
use crate::variant::Variant;
|
|
|
|
fn turn_spot(board: &str, hero: &str, pot: f64, to_call: f64, stack: f64) -> Spot {
|
|
Spot {
|
|
variant: Variant::Nlhe,
|
|
big_blind: 1.0,
|
|
seats: 2,
|
|
hero_seat: 1,
|
|
button_seat: Some(1),
|
|
hero_cards: Card::parse_list(hero).unwrap(),
|
|
board: Card::parse_list(board).unwrap(),
|
|
street: Street::Turn,
|
|
pot,
|
|
to_call,
|
|
hero_stack: stack,
|
|
min_raise_to: Some((2.0 * to_call).max(1.0).min(stack)),
|
|
max_raise_to: Some(stack),
|
|
legal: if to_call > 0.0 {
|
|
vec![ActionKind::Fold, ActionKind::Call, ActionKind::Raise]
|
|
} else {
|
|
vec![ActionKind::Check, ActionKind::Raise]
|
|
},
|
|
allowed_sizes: None,
|
|
villains: vec![Villain { seat: 2, stack, folded: false, profile: None }],
|
|
seed: 7,
|
|
history: Vec::new(),
|
|
}
|
|
}
|
|
|
|
fn quick() -> Opts {
|
|
Opts { turn_iters: 60, turn_combos: 60, turn_cards: 6, ..Opts::default() }
|
|
}
|
|
|
|
#[test]
|
|
fn folding_the_nut_flush_to_a_turn_bet_loses_calling_does_not() {
|
|
// Hero holds the nut flush; the villain bets the pot (20 into 20: the pot shows 40).
|
|
let mut spot = turn_spot("Kh 7h 2h 9c", "Ah Qh", 40.0, 20.0, 100.0);
|
|
spot.history = vec![crate::game::ActionRecord { street: Street::Turn, seat: 2, action: crate::game::SeenAction::Bet, amount: Some(20.0) }];
|
|
let fold = audit_turn(&spot, Taken::Fold, quick()).expect("auditable");
|
|
let call = audit_turn(&spot, Taken::Call, quick()).expect("auditable");
|
|
assert_eq!(fold.method, "turn_river_game");
|
|
assert!(fold.loss > 5.0, "folding the nuts must cost real EV, got {}", fold.loss);
|
|
assert!(call.loss < fold.loss, "calling loses less than folding ({} vs {})", call.loss, fold.loss);
|
|
assert_eq!(fold.acts[fold.taken].act, Act::Fold);
|
|
}
|
|
|
|
#[test]
|
|
fn the_played_bet_size_is_priced_exactly() {
|
|
let spot = turn_spot("Kh 7h 2h 9c", "Ah Qh", 20.0, 0.0, 100.0);
|
|
let bet = audit_turn(&spot, Taken::Aggress(13.0), quick()).expect("auditable");
|
|
assert!(bet.size_gap < 1e-9, "size in the tree, gap {}", bet.size_gap);
|
|
assert!(matches!(bet.acts[bet.taken].act, Act::Bet(x) if (x - 13.0).abs() < 1e-9));
|
|
}
|
|
|
|
#[test]
|
|
fn thinning_keeps_the_hero_hand_and_does_not_follow_card_order() {
|
|
let all: Vec<(Vec<Card>, f64)> = ["As Ks", "Ad Kd", "Ac Kc", "Ah Kh", "2c 2d", "3c 3d", "4c 4d", "5c 5d"]
|
|
.iter()
|
|
.map(|s| (Card::parse_list(s).unwrap(), 1.0))
|
|
.collect();
|
|
let keep = fast7::mask(&Card::parse_list("5c 5d").unwrap());
|
|
for max in 1..4 {
|
|
let h = thin(&all, 0, max, Some(keep));
|
|
assert!(h.masks.contains(&keep), "hero hand kept at max {max}");
|
|
assert!(h.masks.len() == max || h.masks.len() == max + 1);
|
|
}
|
|
let h2 = thin(&all, 0, 3, None);
|
|
let sorted: Vec<u64> = {
|
|
let mut v: Vec<u64> = all.iter().map(|(c, _)| fast7::mask(c)).collect();
|
|
v.sort();
|
|
v.truncate(3);
|
|
v
|
|
};
|
|
assert_ne!(h2.masks, sorted, "equal weights are thinned by hash, not by mask order");
|
|
}
|
|
|
|
#[test]
|
|
fn multiway_and_river_are_not_audited_here() {
|
|
let mut spot = turn_spot("Kh 7h 2h 9c", "Ah Qh", 20.0, 20.0, 100.0);
|
|
spot.villains.push(Villain { seat: 3, stack: 100.0, folded: false, profile: None });
|
|
assert_eq!(audit_turn(&spot, Taken::Call, quick()), Err(Skip::Multiway));
|
|
}
|
|
}
|