//! Decision audit (plan D4): re-solve a real river decision with the full river game and price the //! action that was actually taken. //! //! The audit judges decisions, not results. For one logged decision it builds the same heads-up river //! game the live engine plays (`cfr::river_game`: position, several sizes, raises, the observed river //! line inside the tree), solves it to equilibrium, and then asks, for hero's actual hand class at //! hero's actual node: what is every action worth against the solved villain, and what does the //! taken action lose against the best one? //! //! # Definitions //! //! - **EV of an action** = hero's expected chips from the river on (same chip scale as the solver: //! each player counted as having put `pot/2` in), after taking that action at the node and playing //! the solved strategy afterwards, against the villain's solved strategy. The villain's range is //! conditioned on reaching the node (its own solved action probabilities along the observed line //! multiply its class weights). Only differences between actions are meaningful. //! - **Loss** = `ev(best action) - ev(taken action)`, `>= 0`. It is measured against the Nash villain, //! not against the real one: a "loss" against a solved opponent can be a profitable exploit against //! a real leak, which is why the report separates action types and shows the range source. //! //! # What the range comes from //! //! Blueprint ranges (`blueprint::ranges::gewichtete_listen`, needs `$GRUNDSTRATEGIE` and a spot that //! is blueprint scenario S1) where available, else the engine's own range model for both players //! (`RangeSource::Model`), exactly as `river_subgame::river_game_decision` builds them. //! //! # Other streets //! //! - **Turn** (`engine::audit_turn`): the turn+river game over real combos (`cfr::turn_river_game`, //! the E3 solver), same definitions, chips from the start of the turn. //! - **Preflop and flop** (`engine::audit_allin`): only where a price decides alone - facing an all-in //! (equity against the jammer's range against the price), and a first-in push/fold at short stacks //! (the Nash push/fold game the frozen charts come from). Everything else is skipped with a reason. use crate::card::Card; use crate::cfr::river_game::{build, Act, Bets}; use crate::cfr::solve::solve; use crate::cfr::strategy::Strategy; use crate::cfr::tree::{Node, Payoff, Tree}; use crate::engine::river_subgame::{deal_classes, river_line}; use crate::game::{Spot, Street, Villain}; use crate::hand::showdown::judge; use crate::rng::Rng; /// What hero did at the node, in the vocabulary of the wire (`amount` = street total for bets/raises). #[derive(Clone, Copy, Debug, PartialEq)] pub enum Taken { Fold, Check, Call, /// Bet or raise to this street total (an all-in is a bet/raise to the stack). Aggress(f64), } /// Where both ranges came from. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum RangeSource { /// The S1 blueprint (plan E2e). Blueprint, /// The engine's own range model (no history needed, no blueprint). Model, /// Ranges handed in directly (unit tests). Given, } impl RangeSource { pub fn name(self) -> &'static str { match self { RangeSource::Blueprint => "blueprint", RangeSource::Model => "modell", RangeSource::Given => "gegeben", } } } /// Why a decision cannot be audited. #[derive(Clone, Debug, PartialEq)] pub enum Skip { /// A street without a yardstick here. Street(Street), /// Preflop / flop spot that no price alone decides (no all-in, no short-stack push/fold). NotCovered(&'static str), Multiway, NoRange(&'static str), /// The taken action does not fit the node (e.g. a fold with nothing to call). Illegal(&'static str), /// The observed line is not in the river game. LineLeftTree, } impl Skip { pub fn text(&self) -> String { match self { Skip::Street(s) => format!("street {s:?} not audited"), Skip::NotCovered(w) => format!("not covered: {w}"), Skip::Multiway => "multiway".to_string(), Skip::NoRange(w) => format!("no range: {w}"), Skip::Illegal(w) => format!("illegal: {w}"), Skip::LineLeftTree => "line left tree".to_string(), } } } /// One action of the node with its solved probability for hero's class and its EV. #[derive(Clone, Debug, PartialEq)] pub struct ActEv { pub act: Act, pub prob: f64, pub ev: f64, } /// The result for one decision, in chips of the spot. #[derive(Clone, Debug, PartialEq)] pub struct Audit { pub source: RangeSource, pub class: usize, pub classes: usize, pub nodes: usize, /// 0 = hero acts first on the river, 1 = villain did. pub first: usize, pub acts: Vec, /// Index into `acts` of the taken action. pub taken: usize, /// Relative size difference between the taken size and the tree size it was priced as (0 = exact). pub size_gap: f64, pub ev_best: f64, pub ev_mix: f64, pub ev_taken: f64, /// `ev_best - ev_taken`. pub loss: f64, /// The villain's solved range never reaches this node (its class weights all vanish); the EVs /// then use the unconditioned villain range. pub off_line: bool, /// Hero's actual hand is part of his modelled range (else it was added to be priced). pub hero_in_range: bool, /// Exploitability of the solved game at the end of the run (payoff units), a convergence check. pub exploitability: f64, /// Which yardstick priced the decision: `river_game`, `turn_river_game`, `jam_preis`, /// `allin_equity`, `push_fold`. pub method: &'static str, /// What the yardstick assumed, in a few words (reference range, depth, equity vs price). pub note: String, } /// Options for one audit run. #[derive(Clone, Copy, Debug)] pub struct Opts { /// CFR+ iterations of the river game. pub iters: u32, /// CFR+ iterations of the turn+river game. pub turn_iters: u32, /// Most combos per player in the turn+river game. pub turn_combos: usize, /// River cards enumerated in the turn+river game (of 44-46). pub turn_cards: usize, } impl Default for Opts { fn default() -> Opts { Opts { iters: 10_000, turn_iters: 200, turn_combos: 200, turn_cards: 10 } } } /// Audit one decision. River: the full river game. Turn: the turn+river game. Preflop and flop: /// all-in prices and short-stack push/fold (`audit_allin`). pub fn audit(spot: &Spot, taken: Taken, opts: Opts) -> Result { // RAKE_LIVE: the audit prices the river game and the all-in prices net of the room's rake, as the // live decision does (`rake::live`). The turn+river game (`cfr::turn_river_game`) stays raw. let _rake = crate::rake::live::cash_scope_seats(spot.big_blind, spot.seats); match spot.street { Street::River => audit_river(spot, taken, opts), Street::Turn => audit_turn(spot, taken, opts), Street::Preflop => crate::engine::audit_allin::audit_preflop(spot, taken), Street::Flop => crate::engine::audit_allin::audit_flop(spot, taken), } } /// The turn: `engine::audit_turn` (turn+river game over real combos). pub fn audit_turn(spot: &Spot, taken: Taken, opts: Opts) -> Result { crate::engine::audit_turn::audit_turn(spot, taken, opts) } pub(crate) type Weighted = Vec<(Vec, f64)>; /// The two weighted range lists of the spot and where they came from. pub(crate) fn ranges(spot: &Spot, villain: &Villain) -> Option<(Weighted, Weighted, RangeSource)> { if crate::blueprint::ranges::grundstrategie().is_some() { if let Some((h, v)) = crate::blueprint::ranges::gewichtete_listen(spot) { return Some((h, v, RangeSource::Blueprint)); } } let rules = spot.rules(); let list = |who: &Villain| { let filter = crate::engine::range_filter::range_filter( &crate::exploit::range_model::range_spec(spot, who), rules, spot.variant, &spot.board, ); crate::engine::range_combos::combos(&rules, &filter, &spot.board) }; let me = Villain { seat: spot.hero_seat, stack: spot.hero_stack, folded: false, profile: None }; let eins = |l: Vec>| l.into_iter().map(|c| (c, 1.0)).collect::(); Some((eins(list(&me)?), eins(list(villain)?), RangeSource::Model)) } fn audit_river(spot: &Spot, taken: Taken, opts: Opts) -> Result { let gated = crate::engine::read_gate::gate_reads(spot); let spot = &gated; if spot.live_villains().count() != 1 { return Err(Skip::Multiway); } 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"))?; // Hero knows his hand: if the modelled hero range does not contain it (a hand the range model // would not have played), add it at the mean combo weight so its class has deals to be priced on. let held = |c: &Vec| c.len() == spot.hero_cards.len() && 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::() / hero_list.len().max(1) as f64; hero_list.push((spot.hero_cards.clone(), mean.max(1e-9))); } let (n, chance, ladder, class_of) = deal_classes(spot, &hero_list, &villain_list).ok_or(Skip::NoRange("deal classes"))?; let (first, line, c) = river_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]); let strength = judge(&spot.rules(), &spot.hero_cards, &spot.board).map_err(|_| Skip::NoRange("hero hand"))?; let class = class_of[ladder.partition_point(|d| *d < strength).min(ladder.len() - 1)]; let bets = Bets::standard(pot, stack, first); 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), Taken::Aggress(to) => Act::Bet(to), }; let mut a = audit_game(n, chance, &bets, &line, act, class, opts.iters, spot.seed)?; a.source = source; a.first = first; a.hero_in_range = hero_in_range; Ok(a) } /// The pure part: a game over `n` classes with joint deal table `chance`, the observed river line /// `line` up to hero's node, the action hero took there, and hero's class. Prices every action of the /// node against the solved villain. pub fn audit_game(n: usize, chance: Vec, bets: &Bets, line: &[Act], taken: Act, class: usize, iters: u32, seed: u64) -> Result { let aggressive = matches!(taken, Act::Bet(_) | Act::Raise(_)); let mut forced = line.to_vec(); if aggressive { forced.push(taken); } let game = build(n, chance, bets, &forced); let at = game.at.ok_or(Skip::LineLeftTree)?; // The node of hero's decision: the line's end, or (when the taken bet is part of the forced line) // its parent. let tree = &game.tree; let hero_node = if aggressive { (0..tree.nodes.len()) .find(|&i| matches!(&tree.nodes[i], Node::Decision { children, .. } if children.contains(&at))) .ok_or(Skip::LineLeftTree)? } else { at }; if !matches!(tree.nodes.get(hero_node), Some(Node::Decision { player: 0, .. })) { return Err(Skip::LineLeftTree); } let solved = solve(tree, iters, Rng::seeded(seed)); let sigma = &solved.strategy; // The villain's class weights at the node: the deal row of hero's class, times the villain's // solved probability of every observed action on the way. let mut path = Vec::new(); path_to(tree, tree.root, hero_node, &mut path); let row: Vec = (0..n).map(|j| tree.chance[class * n + j]).collect(); let mut w = row.clone(); for &(node, k) in &path { if matches!(tree.nodes[node], Node::Decision { player: 1, .. }) { for (j, wj) in w.iter_mut().enumerate() { *wj *= sigma.probability(node, j, k); } } } let mut off_line = false; if w.iter().sum::() < 1e-12 { off_line = true; w = row; } let mass: f64 = w.iter().sum(); if mass <= 0.0 { return Err(Skip::NoRange("hero class has no deals")); } let children = match &tree.nodes[hero_node] { Node::Decision { children, .. } => children.clone(), _ => return Err(Skip::LineLeftTree), }; let acts = &game.acts[hero_node]; let mix = sigma.row(hero_node, class); let mut list = Vec::with_capacity(children.len()); for (k, &child) in children.iter().enumerate() { let ev = value(tree, sigma, child, &w, class) / mass; list.push(ActEv { act: acts[k], prob: mix.get(k).copied().unwrap_or(0.0), ev }); } // The taken action's child: exact match, else the nearest size (flagged by `size_gap`). let mut taken_ix = None; let mut size_gap = 0.0; for (k, ae) in list.iter().enumerate() { match (ae.act, taken) { (Act::Bet(x), Act::Bet(y)) | (Act::Raise(x), Act::Raise(y)) => { let gap = (x - y.min(bets.stack)).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: RangeSource::Given, class, classes: n, nodes: tree.nodes.len(), first: bets.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: true, exploitability: solved.final_exploitability, method: "river_game", note: String::new(), }) } /// The `(node, child)` steps from `node` down to `target`. pub(crate) fn path_to(tree: &Tree, node: usize, target: usize, out: &mut Vec<(usize, usize)>) -> bool { if node == target { return true; } if let Node::Decision { children, .. } = &tree.nodes[node] { for (k, &c) in children.iter().enumerate() { out.push((node, k)); if path_to(tree, c, target, out) { return true; } out.pop(); } } false } /// Unnormalised value for hero (class `b`) of the subtree at `node`, summed over the villain's class /// weights `w`: hero plays `sigma` for class `b`, the villain's weights shrink by its probabilities. pub(crate) fn value(tree: &Tree, sigma: &Strategy, node: usize, w: &[f64], b: usize) -> f64 { let n = tree.classes; match &tree.nodes[node] { Node::Terminal(p) => w .iter() .enumerate() .map(|(j, wj)| { wj * match p { Payoff::Flat(v) => *v, Payoff::Own(v) => v[b], Payoff::Pair(v) => v[b * n + j], Payoff::Raked { pair, .. } => pair[b * n + j], } }) .sum(), Node::Chance(branches) => branches.iter().map(|(pr, c)| pr * value(tree, sigma, *c, w, b)).sum(), Node::Decision { player: 0, children, .. } => children .iter() .enumerate() .map(|(k, &c)| sigma.probability(node, b, k) * value(tree, sigma, c, w, b)) .sum(), Node::Decision { children, .. } => children .iter() .enumerate() .map(|(k, &c)| { let w2: Vec = w.iter().enumerate().map(|(j, wj)| wj * sigma.probability(node, j, k)).collect(); value(tree, sigma, c, &w2, b) }) .sum(), } } #[cfg(test)] mod tests { use super::*; use crate::game::{ActionKind, Villain}; use crate::variant::Variant; const ITERS: u32 = 20_000; const SEED: u64 = 0x5EED_A0D1; /// Joint deal table with only the listed `(hero, villain, weight)` cells. fn table(n: usize, cells: &[(usize, usize, f64)]) -> Vec { let mut t = vec![0.0; n * n]; for &(i, j, w) in cells { t[i * n + j] += w; } let s: f64 = t.iter().sum(); t.iter_mut().for_each(|x| *x /= s); t } fn pick(a: &Audit, act: Act) -> &ActEv { a.acts.iter().find(|x| x.act == act).expect("act in node") } /// Air facing a pot-sized bet from a range that never bluffs (all nuts): calling loses the bet, /// folding loses nothing. #[test] fn air_calling_a_never_bluffing_pot_bet_loses_the_bet() { let (pot, bet) = (10.0, 10.0); let bets = Bets::standard(pot, 100.0, 1); let line = [Act::Bet(bet)]; // hero class 0 (air) against villain class 2 (nuts); class 1 is empty. let chance = table(3, &[(0, 2, 1.0)]); let call = audit_game(3, chance.clone(), &bets, &line, Act::Call, 0, ITERS, SEED).unwrap(); assert!((call.loss - bet).abs() < 0.05, "calling air loses ~the bet, got {}", call.loss); assert_eq!(call.acts[call.taken].act, Act::Call); let fold = audit_game(3, chance, &bets, &line, Act::Fold, 0, ITERS, SEED).unwrap(); assert!(fold.loss < 0.05, "folding air loses nothing, got {}", fold.loss); assert!(!call.off_line); } /// The nuts facing a bet they cannot raise: calling loses nothing, folding gives up the call EV. #[test] fn the_nuts_facing_a_bet_never_lose_by_continuing() { let (pot, bet) = (10.0, 10.0); // The stack equals the bet: calling is all-in and there is nothing to raise, so the call is // the only way to continue. let bets = Bets::standard(pot, bet, 1); let line = [Act::Bet(bet)]; // hero nuts (class 2) against bluff-catchers (class 1) and air (class 0): the villain bets // both, so hero's call wins pot + bet every time. let chance = table(3, &[(2, 0, 1.0), (2, 1, 1.0)]); let call = audit_game(3, chance.clone(), &bets, &line, Act::Call, 2, ITERS, SEED).unwrap(); assert!(call.loss < 0.05, "calling the nuts loses nothing, got {}", call.loss); let fold = audit_game(3, chance, &bets, &line, Act::Fold, 2, ITERS, SEED).unwrap(); assert!(fold.loss > 5.0, "folding the nuts must cost real EV, got {}", fold.loss); assert!(pick(&fold, Act::Call).ev > pick(&fold, Act::Fold).ev); } /// Hero first to act with the nuts of a polarised range into a bluff-catcher range: checking loses against betting, and the /// bet that is priced is the exact size played (no size gap). #[test] fn checking_the_nuts_first_loses_to_a_bet_and_the_size_is_priced_exactly() { let bets = Bets::standard(10.0, 100.0, 0); // hero: nuts and air in equal weight (a polarised range); villain: bluff-catchers only. let chance = table(3, &[(2, 1, 1.0), (0, 1, 1.0)]); let check = audit_game(3, chance.clone(), &bets, &[], Act::Check, 2, ITERS, SEED).unwrap(); assert!(check.loss > 1.0, "checking the nuts into a calling range gives EV up, got {}", check.loss); let bet = audit_game(3, chance, &bets, &[], Act::Bet(6.0), 2, ITERS, SEED).unwrap(); assert!(bet.size_gap < 1e-9, "the played size sits in the tree, gap {}", bet.size_gap); assert!(matches!(bet.acts[bet.taken].act, Act::Bet(x) if (x - 6.0).abs() < 1e-9)); assert!(bet.loss < check.loss, "a bet with the nuts loses less than the check ({} vs {})", bet.loss, check.loss); } fn river_spot(board: &str, hero: &str, pot: f64, to_call: f64) -> Spot { // Hero's stack equals the call when facing a bet: no raise to confuse the pricing. let stack = if to_call > 0.0 { to_call } else { 100.0 }; 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::River, pot, to_call, hero_stack: stack, min_raise_to: if to_call > 0.0 { None } else { Some(2.0) }, max_raise_to: if to_call > 0.0 { None } else { Some(stack) }, // (facing a bet: all-in is the call) legal: if to_call > 0.0 { vec![ActionKind::Fold, ActionKind::Call] } else { vec![ActionKind::Check, ActionKind::Raise] }, allowed_sizes: None, villains: vec![Villain { seat: 2, stack: 100.0, folded: false, profile: None }], seed: SEED, history: Vec::new(), } } /// End to end through the engine's range model: top set facing a pot bet should never fold. #[test] fn a_set_facing_a_pot_bet_loses_by_folding_not_by_calling() { let spot = river_spot("Ah Kd 7c 2s 9h", "Ac Ad", 20.0, 10.0); let opts = Opts { iters: 6_000, ..Opts::default() }; let call = audit(&spot, Taken::Call, opts).expect("auditable"); let fold = audit(&spot, Taken::Fold, opts).expect("auditable"); assert_eq!(call.source, RangeSource::Model); assert!(call.loss < 0.2, "calling a set loses ~nothing, got {}", call.loss); assert!(fold.loss > 3.0, "folding a set loses a lot, got {}", fold.loss); } #[test] fn multiway_and_illegal_are_skipped_not_guessed() { let mut spot = river_spot("Ah Kd 7c 2s 9h", "Ac Ad", 20.0, 10.0); spot.villains.push(Villain { seat: 3, stack: 100.0, folded: false, profile: None }); assert_eq!(audit(&spot, Taken::Call, Opts::default()), Err(Skip::Multiway)); let illegal = river_spot("Ah Kd 7c 2s 9h", "Ac Ad", 20.0, 0.0); assert!(matches!(audit(&illegal, Taken::Fold, Opts::default()), Err(Skip::Illegal(_)))); } }