From 4c7fecebb06236e478bc2d294556a986a03ed3cf Mon Sep 17 00:00:00 2001 From: Marc Mintel Date: Wed, 28 Oct 2026 12:33:52 +0100 Subject: [PATCH] Engine: texture-aware thresholds, semibluffs with fold equity, multiway, uncertainty band, range filter glue Co-Authored-By: Claude Opus 5.5 --- src/engine/decide.rs | 35 ++- src/engine/effective.rs | 37 +++ src/engine/mod.rs | 7 + src/engine/multiway.rs | 39 +++ src/engine/options.rs | 56 +++- src/engine/postflop.rs | 115 ++++++-- src/engine/range_filter.rs | 30 ++ src/engine/read_label.rs | 58 ++++ src/engine/semibluff.rs | 14 + src/engine/texture_stance.rs | 63 ++++ src/engine/uncertainty.rs | 15 + src/odds/ev.rs | 10 +- tests/engine_choose_postflop.rs | 279 +++++++++--------- tests/engine_multiway.rs | 112 +++++++ tests/engine_property.rs | 502 ++++++++++++++++++-------------- tests/engine_range_filter.rs | 63 ++++ tests/engine_read_label.rs | 70 +++++ tests/engine_semibluff.rs | 96 ++++++ tests/engine_texture_stance.rs | 125 ++++++++ tests/engine_uncertainty.rs | 92 ++++++ tests/spot_fixture/mod.rs | 190 +++++++----- 21 files changed, 1516 insertions(+), 492 deletions(-) create mode 100644 src/engine/effective.rs create mode 100644 src/engine/multiway.rs create mode 100644 src/engine/range_filter.rs create mode 100644 src/engine/read_label.rs create mode 100644 src/engine/semibluff.rs create mode 100644 src/engine/texture_stance.rs create mode 100644 src/engine/uncertainty.rs create mode 100644 tests/engine_multiway.rs create mode 100644 tests/engine_range_filter.rs create mode 100644 tests/engine_read_label.rs create mode 100644 tests/engine_semibluff.rs create mode 100644 tests/engine_texture_stance.rs create mode 100644 tests/engine_uncertainty.rs diff --git a/src/engine/decide.rs b/src/engine/decide.rs index a439abf1..b5bfdb10 100644 --- a/src/engine/decide.rs +++ b/src/engine/decide.rs @@ -1,23 +1,20 @@ use super::from_plan::from_plan; use super::passive::cheapest_continue; use super::postflop::choose_postflop; -use crate::card::Card; +use super::range_filter::{range_filter, HandFilter}; use crate::equity::monte_carlo::estimate; use crate::equity::query::Query; use crate::equity::villain_range::VillainRange; use crate::exploit::adjust::adjust; use crate::exploit::profile::Profile; -use crate::exploit::range_guess::top_fraction; +use crate::exploit::range_model::range_spec; use crate::exploit::thresholds::Thresholds; use crate::game::{Decision, Spot, Street}; use crate::guard::enforce::enforce; use crate::preflop::advise::advise; -use crate::preflop::hand_percentile::percentile; +use crate::read::hand_read::read; use crate::rng::Rng; -/// A villain's range as an owned predicate over hole cards. -type HandFilter = Box bool>; - const TRIALS_TWO_CARD: u32 = 3000; const TRIALS_FIVE_CARD: u32 = 1500; @@ -29,32 +26,34 @@ fn trials(spot: &Spot) -> u32 { } } +/// Postflop: read the hand, model each live villain's range, simulate, choose. fn postflop(spot: &Spot, thresholds: &Thresholds) -> Decision { - let fractions: Vec = spot.live_villains().map(|v| top_fraction(spot, v)).collect(); - if fractions.is_empty() { + let rules = spot.rules(); + let hand_read = match read(&rules, &spot.hero_cards, &spot.board) { + Ok(r) => r, + Err(fault) => return Decision::abstain(format!("hand read unavailable: {fault}")), + }; + let filters: Vec = spot + .live_villains() + .map(|v| range_filter(&range_spec(spot, v), rules, spot.variant, &spot.board)) + .collect(); + if filters.is_empty() { return cheapest_continue(spot).map_or_else( || Decision::abstain("no live opponent and nothing to continue with"), |choice| Decision::new(choice, 0.5, "no live opponents: cheapest continuing action"), ); } - let variant = spot.variant; - let filters: Vec = fractions - .into_iter() - .map(|fraction| { - Box::new(move |hand: &[Card]| percentile(variant, hand) <= fraction) as HandFilter - }) - .collect(); let ranges: Vec = filters.iter().map(|f| VillainRange::Filter(f.as_ref())).collect(); let query = Query { - rules: spot.rules(), + rules, hero: &spot.hero_cards, board: &spot.board, villains: &ranges, trials: trials(spot), }; match estimate(&query, Rng::seeded(spot.seed)) { - Ok((equity, _)) => choose_postflop(spot, &equity, thresholds), + Ok((equity, _)) => choose_postflop(spot, &equity, thresholds, &hand_read), Err(fault) => Decision::abstain(format!("equity unavailable: {fault}")), } } @@ -68,7 +67,7 @@ fn think(spot: &Spot) -> Decision { } } -/// Full decision for a validated spot (preflop chart or postflop equity/EV), +/// Full decision for a validated spot (preflop chart or postflop read/equity/EV), /// always passed through `guard::enforce::enforce`. pub fn decide(spot: &Spot) -> Decision { enforce(spot, think(spot)) diff --git a/src/engine/effective.rs b/src/engine/effective.rs new file mode 100644 index 00000000..2ced106c --- /dev/null +++ b/src/engine/effective.rs @@ -0,0 +1,37 @@ +use super::multiway::{extra_call_margin, extra_value_raise, realized_share, semibluff_allowed}; +use super::texture_stance::texture_stance; +use crate::exploit::thresholds::Thresholds; +use crate::game::{ActionKind, Spot}; +use crate::read::hand_read::HandRead; + +/// Everything the choice needs, after texture and multiway adjustments. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Effective { + /// Live villains, at least 1. + pub villains: usize, + /// Equity share after the multiway realisation discount. + pub share: f64, + pub call_margin: f64, + pub value_raise: f64, + pub value_ok: bool, + pub raise_ok: bool, + pub semibluff_ok: bool, +} + +/// `thresholds` seen through the hand read (`texture_stance`) and the number of live +/// villains (`multiway`). Pure; heads-up with a monster is the identity. +pub fn effective(spot: &Spot, share: f64, thresholds: &Thresholds, read: &HandRead) -> Effective { + let live = spot.live_villains().count(); + let villains = live.max(1); + let facing_bet = spot.to_call > 0.0 && spot.is_legal(ActionKind::Call); + let stance = texture_stance(thresholds, read, facing_bet); + Effective { + villains, + share: realized_share(share, villains), + call_margin: stance.call_margin + extra_call_margin(villains), + value_raise: (stance.value_raise + extra_value_raise(villains)).min(0.95), + value_ok: stance.value_ok, + raise_ok: stance.raise_ok, + semibluff_ok: semibluff_allowed(villains), + } +} diff --git a/src/engine/mod.rs b/src/engine/mod.rs index 540cf0b5..c8db2262 100644 --- a/src/engine/mod.rs +++ b/src/engine/mod.rs @@ -1,7 +1,14 @@ //! Engine: composes assessment and choice into a decision. pub mod decide; +pub mod effective; pub mod from_plan; +pub mod multiway; pub mod options; pub mod passive; pub mod postflop; +pub mod range_filter; +pub mod read_label; +pub mod semibluff; +pub mod texture_stance; +pub mod uncertainty; diff --git a/src/engine/multiway.rs b/src/engine/multiway.rs new file mode 100644 index 00000000..c5f9e9d9 --- /dev/null +++ b/src/engine/multiway.rs @@ -0,0 +1,39 @@ +//! How the number of live villains `n` moves the postflop bars. Heads-up (`n <= 1`) +//! is the identity; every extra villain (`e = n - 1`) adds: +//! +//! | quantity | rule | why | +//! |------------------|----------------------------------------|--------------------------------------------------| +//! | equity realised | `share * 0.97^e` | multiway pots are contested, equity is realised less | +//! | call margin | `+ 0.01 * e` | someone else is likelier to hold the better hand | +//! | value threshold | `+ 0.05 * e` | a raise must beat several ranges; the absolute bar rises while the fair share `1/(n+1)` falls, so the bar is kept above the heads-up one | +//! | semibluffs | only while `n <= 2` | fold equity compounds to near zero against 3+ | + +/// Per extra villain: factor on the equity share. +pub const REALIZATION_PER_EXTRA: f64 = 0.97; +/// Per extra villain: added to the call margin. +pub const MARGIN_PER_EXTRA: f64 = 0.01; +/// Per extra villain: added to the value-raise threshold. +pub const VALUE_PER_EXTRA: f64 = 0.05; +/// Most villains a semibluff may face. +pub const SEMIBLUFF_MAX_VILLAINS: usize = 2; + +fn extras(villains: usize) -> i32 { + villains.saturating_sub(1).min(64) as i32 +} + +/// Equity share after the multiway realisation discount. +pub fn realized_share(share: f64, villains: usize) -> f64 { + share * REALIZATION_PER_EXTRA.powi(extras(villains)) +} + +pub fn extra_call_margin(villains: usize) -> f64 { + MARGIN_PER_EXTRA * f64::from(extras(villains)) +} + +pub fn extra_value_raise(villains: usize) -> f64 { + VALUE_PER_EXTRA * f64::from(extras(villains)) +} + +pub fn semibluff_allowed(villains: usize) -> bool { + villains <= SEMIBLUFF_MAX_VILLAINS +} diff --git a/src/engine/options.rs b/src/engine/options.rs index b0160872..c4cb0d92 100644 --- a/src/engine/options.rs +++ b/src/engine/options.rs @@ -1,7 +1,9 @@ -use crate::equity::estimate::Estimate; +use super::effective::Effective; +use super::semibluff::has_real_draw; use crate::exploit::thresholds::Thresholds; use crate::game::{ActionKind, Choice, Spot}; use crate::odds::{break_even::break_even, ev, fold_equity::fold_equity}; +use crate::read::hand_read::HandRead; use crate::sizing::candidates::candidates; /// A legal choice with its expected value in chips (relative to folding now). @@ -11,32 +13,62 @@ pub struct Scored { pub ev: f64, } -/// Every action the breakpoint rule lets hero consider, in preference order -/// (passive first, so ties keep the cheaper line): +/// EV of the best non-raising line, ignoring the call margin: check when free, the raw +/// call EV, folding (0) when check is not available. `None` when none is legal. +pub fn passive_ev(spot: &Spot, share: f64) -> Option { + let free = spot.is_legal(ActionKind::Check); + let check = free.then(|| ev::check(share, spot.pot)); + let call = spot.is_legal(ActionKind::Call).then(|| ev::call(share, spot.pot, spot.to_call)); + let fold = (spot.is_legal(ActionKind::Fold) && !free).then(ev::fold); + [check, call, fold].into_iter().flatten().filter(|x| x.is_finite()).reduce(f64::max) +} + +/// A raise is a value raise when the read allows it and the realised share clears the +/// effective value threshold. +pub fn is_value_raise(eff: &Effective) -> bool { + eff.raise_ok && eff.value_ok && eff.share >= eff.value_raise +} + +/// Every action the rule lets hero consider, in preference order (passive first, so +/// ties keep the cheaper line). With `eff` the effective (texture and multiway +/// adjusted) numbers and `share = eff.share`: /// * check, when legal; -/// * call, when legal and `share >= break_even + call_margin`; +/// * call, when legal and `share >= break_even + eff.call_margin`; /// * fold, when legal and check is not; -/// * each sizing candidate as a raise, when legal and `share >= value_raise`. +/// * each sizing candidate as a raise, when legal and either +/// - it is a value raise (`is_value_raise`), or +/// - it is a semibluff: raising is allowed, at most two villains, a real draw +/// (`semibluff::has_real_draw`), and the raise EV is strictly above `passive_ev`. /// -/// Raises are value raises only: the fold-equity term shapes which size is best, it -/// does not license raising a hand below the value threshold. -pub fn scored(spot: &Spot, estimate: &Estimate, thresholds: &Thresholds) -> Vec { - let share = estimate.share; +/// The raise EV uses `fold_equity(pot, to, fold_equity_scale, live villains)`, i.e. +/// `fe * pot + (1 - fe) * (share * final_pot - added)`. Pure bluffs never qualify. +pub fn scored(spot: &Spot, eff: &Effective, thresholds: &Thresholds, read: &HandRead) -> Vec { + let share = eff.share; let free = spot.is_legal(ActionKind::Check); let be = break_even(spot.pot, spot.to_call); let live = spot.live_villains().count(); let check = free.then(|| Scored { choice: Choice::Check, ev: ev::check(share, spot.pot) }); - let call = (spot.is_legal(ActionKind::Call) && share >= be + thresholds.call_margin) + let call = (spot.is_legal(ActionKind::Call) && share >= be + eff.call_margin) .then(|| Scored { choice: Choice::Call, ev: ev::call(share, spot.pot, spot.to_call) }); let fold = (spot.is_legal(ActionKind::Fold) && !free) .then(|| Scored { choice: Choice::Fold, ev: ev::fold() }); - let raises = if spot.is_legal(ActionKind::Raise) && share >= thresholds.value_raise { candidates(spot) } else { Default::default() } + + let value = is_value_raise(eff); + let semi = eff.raise_ok && eff.semibluff_ok && has_real_draw(read, spot.street); + let floor = passive_ev(spot, share).unwrap_or(f64::NEG_INFINITY); + let sizes = if spot.is_legal(ActionKind::Raise) && (value || semi) { + candidates(spot) + } else { + Vec::new() + }; + let raises = sizes .into_iter() .map(|to| { let fe = fold_equity(spot.pot, to, thresholds.fold_equity_scale, live); Scored { choice: Choice::Raise { to }, ev: ev::raise(share, spot.pot, spot.to_call, to, fe) } - }); + }) + .filter(move |s| value || s.ev > floor); check .into_iter() diff --git a/src/engine/postflop.rs b/src/engine/postflop.rs index 95dcb5a2..87855056 100644 --- a/src/engine/postflop.rs +++ b/src/engine/postflop.rs @@ -1,12 +1,17 @@ -use super::options::{scored, Scored}; +use super::effective::{effective, Effective}; +use super::options::{is_value_raise, passive_ev, scored, Scored}; use super::passive::cheapest_continue; +use super::read_label::describe; +use super::uncertainty::abstain_confidence; use crate::equity::estimate::Estimate; use crate::exploit::thresholds::Thresholds; use crate::game::{ActionKind, Choice, Decision, Spot}; use crate::odds::{break_even::break_even, ev}; +use crate::read::hand_read::HandRead; -fn label(choice: Choice) -> String { +fn label(choice: Choice, semibluff: bool) -> String { match choice { + Choice::Raise { to } if semibluff => format!("semibluff raise to {to:.2}"), Choice::Raise { to } => format!("raise to {to:.2}"), other => other.name().to_lowercase(), } @@ -32,7 +37,9 @@ fn lead(spot: &Spot, share: f64, options: &[Scored], winner: Scored) -> f64 { (winner.choice == Choice::Fold && spot.is_legal(ActionKind::Call)) .then(|| ev::call(share, spot.pot, spot.to_call)), ); - rivals.fold(None, |m: Option, x| Some(m.map_or(x, |m| m.max(x)))).map_or(winner.ev.abs(), |r| winner.ev - r) + rivals + .fold(None, |m: Option, x| Some(m.map_or(x, |m| m.max(x)))) + .map_or(winner.ev.abs(), |r| winner.ev - r) } fn confidence(spot: &Spot, gap: f64) -> f64 { @@ -40,51 +47,105 @@ fn confidence(spot: &Spot, gap: f64) -> f64 { 0.5 + 0.5 * (4.0 * gap.max(0.0) / scale).tanh() } -/// The breakpoint rule for a postflop spot, given an equity estimate. +/// Opening of every reason: the read, plus the player count when multiway. +fn headline(read: &HandRead, eff: &Effective) -> String { + if eff.villains > 1 { + format!("{} ({}-way)", describe(read), eff.villains) + } else { + describe(read) + } +} + +/// `(lead, error)` when a raise leads the best passive line by less than its own EV +/// standard error, `std_error * final pot` (the money at stake). A negative lead +/// (the passive line is worth more) counts as inside the error. +fn marginal_raise( + spot: &Spot, + eff: &Effective, + estimate: &Estimate, + to: f64, + raise_ev: f64, +) -> Option<(f64, f64)> { + let passive = passive_ev(spot, eff.share)?; + let gap = raise_ev - passive; + let error = estimate.std_error.max(0.0) * ev::final_pot(spot.pot, spot.to_call, to); + (gap < error).then_some((gap, error)) +} + +/// The rule for a postflop spot, given an equity estimate and the hand read. /// -/// 1. Uncertain equity, or `|share - break-even| < abstain_band + 2 * std_error` while -/// facing a real fold/call choice: ABSTAIN. -/// 2. Otherwise score check / call / fold / value raises (see `options::scored`) and -/// take the maximum EV. Never folds when check is legal. -/// 3. `confidence` rises with the EV lead over the runner-up, relative to the pot. -pub fn choose_postflop(spot: &Spot, estimate: &Estimate, thresholds: &Thresholds) -> Decision { - let share = estimate.share; - if !(share.is_finite() && (0.0..=1.0).contains(&share)) { +/// 1. Invalid equity: ABSTAIN with confidence 0. +/// 2. `effective` (texture stance x multiway) gives the realised share, call margin, +/// value threshold and which raises are allowed. +/// 3. Score check / call / fold / value raises / semibluffs (`options::scored`) and take +/// the maximum EV. Never folds when check is legal. +/// 4. Uncertainty: facing fold-or-call with `|share - (break-even + call margin)| < +/// abstain_band + 2 * std_error`, or a winning raise whose EV lead over the best +/// passive line is below `std_error * final pot`: ABSTAIN with a small confidence +/// (0.05..0.30, `uncertainty::abstain_confidence`). +/// 5. Otherwise `confidence` rises with the EV lead over the runner-up, relative to the pot. +pub fn choose_postflop( + spot: &Spot, + estimate: &Estimate, + thresholds: &Thresholds, + read: &HandRead, +) -> Decision { + let raw = estimate.share; + if !(raw.is_finite() && (0.0..=1.0).contains(&raw)) { return Decision::abstain("equity unavailable"); } + let eff = effective(spot, raw, thresholds, read); + let share = eff.share; let be = break_even(spot.pot, spot.to_call); + let breakpoint = be + eff.call_margin; let band = thresholds.abstain_band + 2.0 * estimate.std_error.max(0.0); let facing_choice = spot.is_legal(ActionKind::Fold) && spot.is_legal(ActionKind::Call) && !spot.is_legal(ActionKind::Check); - if facing_choice && (share - be).abs() < band { - return Decision::abstain(format!( - "equity {share:.2} vs break-even {be:.2}: inside uncertainty band {band:.3}" - )); + let head = headline(read, &eff); + let options = scored(spot, &eff, thresholds, read); + let winner = best(&options); + + if let Some(Scored { choice: Choice::Raise { to }, ev: raise_ev }) = winner { + if let Some((gap, error)) = marginal_raise(spot, &eff, estimate, to, raise_ev) { + return Decision::new( + Choice::Abstain, + abstain_confidence(gap, error), + format!("{head}: raise EV lead {gap:+.2} inside its error {error:.2}"), + ); + } + } else if facing_choice && (share - breakpoint).abs() < band { + return Decision::new( + Choice::Abstain, + abstain_confidence((share - breakpoint).abs(), band), + format!( + "{head}: equity {raw:.2} (realised {share:.2}) vs break-even {be:.2} + margin {:.2}: inside uncertainty band {band:.3}", + eff.call_margin + ), + ); } - let options = scored(spot, estimate, thresholds); - match best(&options) { - Some(winner) => { - let shown = match winner.choice { + match winner { + Some(w) => { + let shown = match w.choice { Choice::Fold => ev::call(share, spot.pot, spot.to_call), - _ => winner.ev, + _ => w.ev, }; - let name = match winner.choice { + let name = match w.choice { Choice::Fold => "call".to_string(), - other => label(other), + other => label(other, !is_value_raise(&eff)), }; Decision::new( - winner.choice, - confidence(spot, lead(spot, share, &options, winner)), - format!("equity {share:.2} vs break-even {be:.2}, EV {name} {shown:+.2}"), + w.choice, + confidence(spot, lead(spot, share, &options, w)), + format!("{head}: equity {raw:.2} vs break-even {be:.2}, EV {name} {shown:+.2}"), ) } None => match cheapest_continue(spot) { Some(choice) => Decision::new( choice, 0.5, - format!("equity {share:.2} vs break-even {be:.2}, only continuing action available"), + format!("{head}: equity {raw:.2} vs break-even {be:.2}, only continuing action available"), ), None => Decision::abstain("no actionable option"), }, diff --git a/src/engine/range_filter.rs b/src/engine/range_filter.rs new file mode 100644 index 00000000..a15177f7 --- /dev/null +++ b/src/engine/range_filter.rs @@ -0,0 +1,30 @@ +use crate::card::Card; +use crate::exploit::range_spec::RangeSpec; +use crate::preflop::hand_percentile::percentile; +use crate::read::draw::Draw; +use crate::read::glance::glance; +use crate::variant::{Rules, Variant}; + +/// A villain's range as an owned predicate over hole cards. +pub type HandFilter = Box bool>; + +/// Turns a `RangeSpec` into the predicate Monte Carlo samples from: a hand is in when +/// its preflop percentile lies in `[lo, hi]` and, for every continuation, its made +/// hand on the first `board_len` board cards is at least `min_made` — or it holds at +/// least a gutshot when the continuation lets draws continue. A hand `glance` cannot +/// read is out. A `board_len` beyond the board is clamped to the whole board. +pub fn range_filter(spec: &RangeSpec, rules: Rules, variant: Variant, board: &[Card]) -> HandFilter { + let spec = spec.clone(); + let board = board.to_vec(); + Box::new(move |hand: &[Card]| { + let p = percentile(variant, hand); + p >= spec.lo + && p <= spec.hi + && spec.continues.iter().all(|c| { + match glance(&rules, hand, &board[..c.board_len.min(board.len())]) { + Ok((made, draw)) => made >= c.min_made || (c.draws_continue && draw >= Draw::Gutshot), + Err(_) => false, + } + }) + }) +} diff --git a/src/engine/read_label.rs b/src/engine/read_label.rs new file mode 100644 index 00000000..1462ec41 --- /dev/null +++ b/src/engine/read_label.rs @@ -0,0 +1,58 @@ +use crate::read::draw::Draw; +use crate::read::hand_read::HandRead; +use crate::read::made::Made; +use crate::read::suit_pattern::SuitPattern; + +/// Wetness from which a board is called wet, and up to which it is called dry. +const WET: f64 = 0.6; +const DRY: f64 = 0.3; + +fn made_name(made: Made) -> &'static str { + match made { + Made::Air => "air", + Made::BoardOnly => "board only", + Made::Underpair => "underpair", + Made::BottomPair => "bottom pair", + Made::MiddlePair => "middle pair", + Made::TopPairWeakKicker => "top pair weak kicker", + Made::TopPairGoodKicker => "top pair good kicker", + Made::Overpair => "overpair", + Made::TwoPair => "two pair", + Made::Set => "set", + Made::Trips => "trips", + Made::Straight => "straight", + Made::Flush => "flush", + Made::FullHouse => "full house", + Made::Quads => "quads", + Made::StraightFlush => "straight flush", + } +} + +fn draw_suffix(draw: Draw) -> &'static str { + match draw { + Draw::None | Draw::Backdoor => "", + Draw::Gutshot => " with gutshot", + Draw::OpenEnded => " with open-ended draw", + Draw::Flush => " with flush draw", + Draw::Combo => " with combo draw", + } +} + +fn board_name(read: &HandRead) -> &'static str { + let wetness = read.texture.wetness; + if read.texture.suits == SuitPattern::FourFlush { + "four-flush" + } else if wetness >= WET { + "wet" + } else if wetness <= DRY { + "dry" + } else { + "medium" + } +} + +/// The read in words, e.g. "top pair good kicker on wet board" or +/// "air with flush draw on dry board". Used in decision reasons. +pub fn describe(read: &HandRead) -> String { + format!("{}{} on {} board", made_name(read.made), draw_suffix(read.draw), board_name(read)) +} diff --git a/src/engine/semibluff.rs b/src/engine/semibluff.rs new file mode 100644 index 00000000..a0f82ae8 --- /dev/null +++ b/src/engine/semibluff.rs @@ -0,0 +1,14 @@ +use crate::game::Street; +use crate::read::draw::Draw; +use crate::read::hand_read::HandRead; + +/// Outs that make a draw "real" regardless of its class. +pub const REAL_DRAW_OUTS: u8 = 8; + +/// Hero holds a draw worth raising with: open-ended, flush or combo, or at least +/// [`REAL_DRAW_OUTS`] outs. Never on the river (no cards to come). +pub fn has_real_draw(read: &HandRead, street: Street) -> bool { + street != Street::River + && (matches!(read.draw, Draw::OpenEnded | Draw::Flush | Draw::Combo) + || read.outs >= REAL_DRAW_OUTS) +} diff --git a/src/engine/texture_stance.rs b/src/engine/texture_stance.rs new file mode 100644 index 00000000..22ac384c --- /dev/null +++ b/src/engine/texture_stance.rs @@ -0,0 +1,63 @@ +use crate::exploit::thresholds::Thresholds; +use crate::read::draw::Draw; +use crate::read::hand_read::HandRead; +use crate::read::made::Made; +use crate::read::suit_pattern::SuitPattern; +use crate::read::tier::{tier, Tier}; + +/// Thresholds as seen by one specific hand on one specific board (heads-up basis). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Stance { + /// Equity above break-even needed to continue. + pub call_margin: f64, + /// Equity needed for a value raise. + pub value_raise: f64, + /// A value raise is allowed at all (pot control off). + pub value_ok: bool, + /// Any raise is allowed (`BoardOnly` never raises). + pub raise_ok: bool, +} + +const CALL_MARGIN: (f64, f64) = (0.0, 0.2); +const VALUE_RAISE: (f64, f64) = (0.5, 0.95); +/// Wetness at or above this is a "wet" board (no thin value raise for one pair). +const WET: f64 = 0.6; +/// Wetness at or below this is "dry"; the strong-hand discount fades out by 0.3. +const DRY: f64 = 0.3; + +/// Shifts `(call_margin, value_raise)` for the hand's tier and the board, `w` = wetness. +/// +/// | tier | call margin | value raise | value raise allowed | +/// |---------|----------------------------------|-------------------------------------|------------------------------| +/// | Weak | +0.03 facing a bet without a draw| +0.10 | yes | +/// | Medium | +0.01 + 0.04w (+0.03 four-flush) | +0.06 + 0.12w | no if w >= 0.6 or four-flush | +/// | Strong | +0.02w (+0.03 four-flush) | -0.04 dry (fades to 0 at w=0.3) + 0.05w (+0.08 four-flush) | yes | +/// | Monster | 0 | 0 | yes | +/// +/// `Made::BoardOnly` may not raise at all. Results are clamped to +/// `call_margin` in [0, 0.2] and `value_raise` in [0.5, 0.95]. Unknown wetness counts as 0.5. +pub fn texture_stance(base: &Thresholds, read: &HandRead, facing_bet: bool) -> Stance { + let w = if read.texture.wetness.is_nan() { 0.5 } else { read.texture.wetness.clamp(0.0, 1.0) }; + let four = read.texture.suits == SuitPattern::FourFlush; + let four_margin = if four { 0.03 } else { 0.0 }; + let drawing = read.draw >= Draw::Gutshot; + let dry = (1.0 - w / DRY).clamp(0.0, 1.0); + + let (margin, value, value_ok) = match tier(read.made) { + Tier::Weak => (if facing_bet && !drawing { 0.03 } else { 0.0 }, 0.10, true), + Tier::Medium => (0.01 + 0.04 * w + four_margin, 0.06 + 0.12 * w, !(w >= WET || four)), + Tier::Strong => ( + 0.02 * w + four_margin, + -0.04 * dry + 0.05 * w + if four { 0.08 } else { 0.0 }, + true, + ), + Tier::Monster => (0.0, 0.0, true), + }; + let raise_ok = read.made != Made::BoardOnly; + Stance { + call_margin: (base.call_margin + margin).clamp(CALL_MARGIN.0, CALL_MARGIN.1), + value_raise: (base.value_raise + value).clamp(VALUE_RAISE.0, VALUE_RAISE.1), + value_ok: value_ok && raise_ok, + raise_ok, + } +} diff --git a/src/engine/uncertainty.rs b/src/engine/uncertainty.rs new file mode 100644 index 00000000..a8a2f3aa --- /dev/null +++ b/src/engine/uncertainty.rs @@ -0,0 +1,15 @@ +/// Confidence floor of an ABSTAIN caused by uncertainty (right at the edge). +pub const MIN_UNCERTAIN_CONFIDENCE: f64 = 0.05; +/// Ceiling (at the rim of the band). An uncertainty ABSTAIN never exceeds this. +pub const MAX_UNCERTAIN_CONFIDENCE: f64 = 0.30; + +/// Confidence of an uncertainty ABSTAIN: `0.05 + 0.25 * distance / width`, where +/// `distance` is how far the evidence is from the edge being decided (break-even, +/// or the EV tie) and `width` the uncertainty band. On the edge the engine is least +/// sure (0.05); at the rim of the band it is most sure (0.30). Total: NaN, negative or +/// zero-width input gives the floor or the ceiling, never anything outside the range. +pub fn abstain_confidence(distance: f64, width: f64) -> f64 { + let ratio = if width > 0.0 { (distance / width).clamp(0.0, 1.0) } else { 1.0 }; + let ratio = if ratio.is_nan() { 0.0 } else { ratio }; + MIN_UNCERTAIN_CONFIDENCE + (MAX_UNCERTAIN_CONFIDENCE - MIN_UNCERTAIN_CONFIDENCE) * ratio +} diff --git a/src/odds/ev.rs b/src/odds/ev.rs index 00b20cc6..e11af4c1 100644 --- a/src/odds/ev.rs +++ b/src/odds/ev.rs @@ -21,10 +21,16 @@ pub fn call(share: f64, pot: f64, to_call: f64) -> f64 { share * (pot + to_call) - to_call } +/// Pot after a raise adding `added` chips that one villain calls: +/// `pot + added + max(added - to_call, 0)`. Also the money at stake in the raise, +/// used to scale its EV standard error. +pub fn final_pot(pot: f64, to_call: f64, added: f64) -> f64 { + pot + added + (added - to_call).max(0.0) +} + /// Raise adding `added` chips, with fold probability `fe`: /// `fe * pot + (1 - fe) * (share * final_pot - added)` where /// `final_pot = pot + added + max(added - to_call, 0)`. pub fn raise(share: f64, pot: f64, to_call: f64, added: f64, fe: f64) -> f64 { - let final_pot = pot + added + (added - to_call).max(0.0); - fe * pot + (1.0 - fe) * (share * final_pot - added) + fe * pot + (1.0 - fe) * (share * final_pot(pot, to_call, added) - added) } diff --git a/tests/engine_choose_postflop.rs b/tests/engine_choose_postflop.rs index 6663e8a8..8b91aab6 100644 --- a/tests/engine_choose_postflop.rs +++ b/tests/engine_choose_postflop.rs @@ -1,139 +1,140 @@ -mod spot_fixture; - -use pokerfreak::engine::postflop::choose_postflop; -use pokerfreak::exploit::thresholds::Thresholds; -use pokerfreak::game::{ActionKind, Choice, Spot}; -use pokerfreak::sizing::candidates::candidates; -use spot_fixture::*; - -const BASE: Thresholds = Thresholds::BASE; - -// round_flop: pot 10, 5 to call -> break-even exactly 1/3. - -#[test] -fn clear_call_when_equity_beats_the_price() { - let d = choose_postflop(&round_flop(), &estimate(0.45, 0.005), &BASE); - assert_eq!(d.choice, Choice::Call); - assert!(d.reason.contains("equity 0.45"), "{}", d.reason); - assert!(d.reason.contains("break-even 0.33"), "{}", d.reason); - assert!(d.reason.contains("EV"), "{}", d.reason); -} - -#[test] -fn clear_fold_when_equity_is_far_below_the_price() { - let d = choose_postflop(&round_flop(), &estimate(0.15, 0.005), &BASE); - assert_eq!(d.choice, Choice::Fold); -} - -#[test] -fn abstains_near_the_breakpoint() { - let d = choose_postflop(&round_flop(), &estimate(0.34, 0.005), &BASE); - assert_eq!(d.choice, Choice::Abstain); - assert_eq!(d.confidence.value(), 0.0); -} - -#[test] -fn abstain_band_widens_with_the_standard_error() { - let noisy = choose_postflop(&round_flop(), &estimate(0.36, 0.02), &BASE); - assert_eq!(noisy.choice, Choice::Abstain); - let tight = choose_postflop(&round_flop(), &estimate(0.36, 0.001), &BASE); - assert_eq!(tight.choice, Choice::Call); -} - -#[test] -fn call_margin_is_required_above_break_even() { - let thresholds = Thresholds { abstain_band: 0.0, call_margin: 0.05, ..BASE }; - // 0.36 is above break-even (0.333) but below break-even + margin (0.383) - let d = choose_postflop(&round_flop(), &estimate(0.36, 0.0), &thresholds); - assert_eq!(d.choice, Choice::Fold); -} - -#[test] -fn value_raise_when_equity_is_high() { - let spot = round_flop(); - let d = choose_postflop(&spot, &estimate(0.80, 0.005), &BASE); - match d.choice { - Choice::Raise { to } => assert!(candidates(&spot).contains(&to), "{to}"), - other => panic!("expected a raise, got {other:?}"), - } -} - -#[test] -fn no_raise_below_the_value_threshold() { - let d = choose_postflop(&round_flop(), &estimate(0.50, 0.005), &BASE); - assert_eq!(d.choice, Choice::Call); -} - -#[test] -fn value_threshold_comes_from_the_thresholds() { - let eager = Thresholds { value_raise: 0.45, ..BASE }; - let d = choose_postflop(&round_flop(), &estimate(0.50, 0.005), &eager); - assert!(matches!(d.choice, Choice::Raise { .. }), "{d:?}"); -} - -#[test] -fn checks_when_free_and_weak() { - let spot = Spot { to_call: 0.0, legal: vec![ActionKind::Check, ActionKind::Raise], ..round_flop() }; - let d = choose_postflop(&spot, &estimate(0.30, 0.005), &BASE); - assert_eq!(d.choice, Choice::Check); -} - -#[test] -fn raises_when_free_and_strong() { - let spot = Spot { to_call: 0.0, legal: vec![ActionKind::Check, ActionKind::Raise], ..round_flop() }; - let d = choose_postflop(&spot, &estimate(0.90, 0.005), &BASE); - assert!(matches!(d.choice, Choice::Raise { .. }), "{d:?}"); -} - -#[test] -fn never_folds_when_check_is_legal() { - let spot = Spot { - to_call: 0.0, - legal: vec![ActionKind::Fold, ActionKind::Check], - ..round_flop() - }; - for share in [0.0, 0.05, 0.3, 0.9] { - let d = choose_postflop(&spot, &estimate(share, 0.005), &BASE); - assert_eq!(d.choice, Choice::Check, "share {share}"); - } -} - -#[test] -fn call_when_fold_and_check_are_not_available() { - let spot = Spot { legal: vec![ActionKind::Call], ..round_flop() }; - let d = choose_postflop(&spot, &estimate(0.10, 0.005), &BASE); - assert_eq!(d.choice, Choice::Call); -} - -#[test] -fn raises_come_from_allowed_sizes_verbatim() { - let spot = Spot { allowed_sizes: Some(vec![20.0, 40.0]), ..round_flop() }; - let d = choose_postflop(&spot, &estimate(0.85, 0.005), &BASE); - match d.choice { - Choice::Raise { to } => assert!(to == 20.0 || to == 40.0, "{to}"), - other => panic!("expected a raise, got {other:?}"), - } -} - -#[test] -fn raise_without_candidates_falls_back_to_the_passive_line() { - let spot = Spot { allowed_sizes: Some(vec![500.0]), ..round_flop() }; - let d = choose_postflop(&spot, &estimate(0.85, 0.005), &BASE); - assert_eq!(d.choice, Choice::Call); -} - -#[test] -fn non_finite_equity_abstains() { - let d = choose_postflop(&round_flop(), &estimate(f64::NAN, 0.0), &BASE); - assert_eq!(d.choice, Choice::Abstain); -} - -#[test] -fn confidence_grows_with_distance_from_the_breakpoint() { - let near = choose_postflop(&round_flop(), &estimate(0.40, 0.001), &BASE); - let far = choose_postflop(&round_flop(), &estimate(0.55, 0.001), &BASE); - assert_eq!(near.choice, Choice::Call); - assert_eq!(far.choice, Choice::Call); - assert!(far.confidence > near.confidence); - assert!(far.confidence.value() <= 1.0 && near.confidence.value() > 0.0); -} +mod spot_fixture; + +use pokerfreak::engine::postflop::choose_postflop; +use pokerfreak::exploit::thresholds::Thresholds; +use pokerfreak::game::{ActionKind, Choice, Spot}; +use pokerfreak::sizing::candidates::candidates; +use spot_fixture::*; + +const BASE: Thresholds = Thresholds::BASE; + +// round_flop: pot 10, 5 to call -> break-even exactly 1/3. + +#[test] +fn clear_call_when_equity_beats_the_price() { + let d = choose_postflop(&round_flop(), &estimate(0.45, 0.005), &BASE, &neutral_read()); + assert_eq!(d.choice, Choice::Call); + assert!(d.reason.contains("equity 0.45"), "{}", d.reason); + assert!(d.reason.contains("break-even 0.33"), "{}", d.reason); + assert!(d.reason.contains("EV"), "{}", d.reason); +} + +#[test] +fn clear_fold_when_equity_is_far_below_the_price() { + let d = choose_postflop(&round_flop(), &estimate(0.15, 0.005), &BASE, &neutral_read()); + assert_eq!(d.choice, Choice::Fold); +} + +#[test] +fn abstains_near_the_breakpoint() { + let d = choose_postflop(&round_flop(), &estimate(0.34, 0.005), &BASE, &neutral_read()); + assert_eq!(d.choice, Choice::Abstain); + assert!(d.confidence.value() > 0.0 && d.confidence.value() <= 0.3, "{d:?}"); +} + +#[test] +fn abstain_band_widens_with_the_standard_error() { + // call breakpoint = 1/3 + call_margin 0.02 = 0.3533 + let noisy = choose_postflop(&round_flop(), &estimate(0.38, 0.02), &BASE, &neutral_read()); + assert_eq!(noisy.choice, Choice::Abstain); + let tight = choose_postflop(&round_flop(), &estimate(0.38, 0.001), &BASE, &neutral_read()); + assert_eq!(tight.choice, Choice::Call); +} + +#[test] +fn call_margin_is_required_above_break_even() { + let thresholds = Thresholds { abstain_band: 0.0, call_margin: 0.05, ..BASE }; + // 0.36 is above break-even (0.333) but below break-even + margin (0.383) + let d = choose_postflop(&round_flop(), &estimate(0.36, 0.0), &thresholds, &neutral_read()); + assert_eq!(d.choice, Choice::Fold); +} + +#[test] +fn value_raise_when_equity_is_high() { + let spot = round_flop(); + let d = choose_postflop(&spot, &estimate(0.80, 0.005), &BASE, &neutral_read()); + match d.choice { + Choice::Raise { to } => assert!(candidates(&spot).contains(&to), "{to}"), + other => panic!("expected a raise, got {other:?}"), + } +} + +#[test] +fn no_raise_below_the_value_threshold() { + let d = choose_postflop(&round_flop(), &estimate(0.50, 0.005), &BASE, &neutral_read()); + assert_eq!(d.choice, Choice::Call); +} + +#[test] +fn value_threshold_comes_from_the_thresholds() { + let eager = Thresholds { value_raise: 0.45, ..BASE }; + let d = choose_postflop(&round_flop(), &estimate(0.50, 0.005), &eager, &neutral_read()); + assert!(matches!(d.choice, Choice::Raise { .. }), "{d:?}"); +} + +#[test] +fn checks_when_free_and_weak() { + let spot = Spot { to_call: 0.0, legal: vec![ActionKind::Check, ActionKind::Raise], ..round_flop() }; + let d = choose_postflop(&spot, &estimate(0.30, 0.005), &BASE, &neutral_read()); + assert_eq!(d.choice, Choice::Check); +} + +#[test] +fn raises_when_free_and_strong() { + let spot = Spot { to_call: 0.0, legal: vec![ActionKind::Check, ActionKind::Raise], ..round_flop() }; + let d = choose_postflop(&spot, &estimate(0.90, 0.005), &BASE, &neutral_read()); + assert!(matches!(d.choice, Choice::Raise { .. }), "{d:?}"); +} + +#[test] +fn never_folds_when_check_is_legal() { + let spot = Spot { + to_call: 0.0, + legal: vec![ActionKind::Fold, ActionKind::Check], + ..round_flop() + }; + for share in [0.0, 0.05, 0.3, 0.9] { + let d = choose_postflop(&spot, &estimate(share, 0.005), &BASE, &neutral_read()); + assert_eq!(d.choice, Choice::Check, "share {share}"); + } +} + +#[test] +fn call_when_fold_and_check_are_not_available() { + let spot = Spot { legal: vec![ActionKind::Call], ..round_flop() }; + let d = choose_postflop(&spot, &estimate(0.10, 0.005), &BASE, &neutral_read()); + assert_eq!(d.choice, Choice::Call); +} + +#[test] +fn raises_come_from_allowed_sizes_verbatim() { + let spot = Spot { allowed_sizes: Some(vec![20.0, 40.0]), ..round_flop() }; + let d = choose_postflop(&spot, &estimate(0.85, 0.005), &BASE, &neutral_read()); + match d.choice { + Choice::Raise { to } => assert!(to == 20.0 || to == 40.0, "{to}"), + other => panic!("expected a raise, got {other:?}"), + } +} + +#[test] +fn raise_without_candidates_falls_back_to_the_passive_line() { + let spot = Spot { allowed_sizes: Some(vec![500.0]), ..round_flop() }; + let d = choose_postflop(&spot, &estimate(0.85, 0.005), &BASE, &neutral_read()); + assert_eq!(d.choice, Choice::Call); +} + +#[test] +fn non_finite_equity_abstains() { + let d = choose_postflop(&round_flop(), &estimate(f64::NAN, 0.0), &BASE, &neutral_read()); + assert_eq!(d.choice, Choice::Abstain); +} + +#[test] +fn confidence_grows_with_distance_from_the_breakpoint() { + let near = choose_postflop(&round_flop(), &estimate(0.40, 0.001), &BASE, &neutral_read()); + let far = choose_postflop(&round_flop(), &estimate(0.55, 0.001), &BASE, &neutral_read()); + assert_eq!(near.choice, Choice::Call); + assert_eq!(far.choice, Choice::Call); + assert!(far.confidence > near.confidence); + assert!(far.confidence.value() <= 1.0 && near.confidence.value() > 0.0); +} diff --git a/tests/engine_multiway.rs b/tests/engine_multiway.rs new file mode 100644 index 00000000..44d63845 --- /dev/null +++ b/tests/engine_multiway.rs @@ -0,0 +1,112 @@ +mod spot_fixture; + +use pokerfreak::engine::effective::effective; +use pokerfreak::engine::multiway::{ + extra_call_margin, extra_value_raise, realized_share, semibluff_allowed, +}; +use pokerfreak::engine::postflop::choose_postflop; +use pokerfreak::exploit::thresholds::Thresholds; +use pokerfreak::game::Choice; +use pokerfreak::read::draw::Draw; +use pokerfreak::read::made::Made; +use pokerfreak::read::suit_pattern::SuitPattern; +use spot_fixture::*; + +const BASE: Thresholds = Thresholds::BASE; + +fn close(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-9 +} + +#[test] +fn heads_up_changes_nothing() { + assert_eq!(realized_share(0.5, 1), 0.5); + assert_eq!(extra_call_margin(1), 0.0); + assert_eq!(extra_value_raise(1), 0.0); + assert_eq!(realized_share(0.5, 0), 0.5); +} + +#[test] +fn each_extra_villain_discounts_equity_and_raises_the_bars() { + assert!(close(realized_share(0.5, 4), 0.5 * 0.97f64.powi(3))); + assert!(close(extra_call_margin(3), 0.02)); + assert!(close(extra_value_raise(3), 0.10)); + assert!(realized_share(0.5, 5) < realized_share(0.5, 4)); + assert!(extra_value_raise(5) > extra_value_raise(4)); +} + +#[test] +fn semibluffs_need_at_most_two_villains() { + assert!(semibluff_allowed(0) && semibluff_allowed(1) && semibluff_allowed(2)); + assert!(!semibluff_allowed(3) && !semibluff_allowed(5)); +} + +#[test] +fn effective_thresholds_combine_texture_and_player_count() { + // Medium hand, dry board (wetness 0.1): texture gives margin 0.034, value 0.692. + let read = read_of(Made::MiddlePair, Draw::None, 0, SuitPattern::Rainbow, 0.1); + let spot = with_villains(round_flop(), 3); + let e = effective(&spot, 0.5, &BASE, &read); + assert_eq!(e.villains, 3); + assert!(close(e.share, 0.5 * 0.97 * 0.97), "{e:?}"); + assert!(close(e.call_margin, 0.034 + 0.02), "{e:?}"); + assert!(close(e.value_raise, 0.692 + 0.10), "{e:?}"); + assert!(e.value_ok && e.raise_ok && !e.semibluff_ok); +} + +#[test] +fn folded_villains_do_not_count() { + let mut spot = with_villains(round_flop(), 4); + spot.villains[0].folded = true; + spot.villains[1].folded = true; + let e = effective(&spot, 0.5, &BASE, &neutral_read()); + assert_eq!(e.villains, 2); + assert!(e.semibluff_ok); +} + +#[test] +fn no_live_villain_counts_as_one() { + let e = effective(&with_villains(round_flop(), 0), 0.5, &BASE, &neutral_read()); + assert_eq!(e.villains, 1); + assert_eq!(e.share, 0.5); +} + +// round_flop: pot 10, 5 to call, break-even 1/3. + +#[test] +fn a_share_that_calls_heads_up_folds_four_way() { + let share = estimate(0.38, 0.002); + let heads_up = choose_postflop(&with_villains(round_flop(), 1), &share, &BASE, &neutral_read()); + assert_eq!(heads_up.choice, Choice::Call, "{heads_up:?}"); + let four_way = choose_postflop(&with_villains(round_flop(), 4), &share, &BASE, &neutral_read()); + assert_eq!(four_way.choice, Choice::Fold, "{four_way:?}"); +} + +#[test] +fn a_share_that_value_raises_heads_up_only_calls_three_way() { + let share = estimate(0.70, 0.002); + let heads_up = choose_postflop(&with_villains(round_flop(), 1), &share, &BASE, &neutral_read()); + assert!(matches!(heads_up.choice, Choice::Raise { .. }), "{heads_up:?}"); + let three_way = choose_postflop(&with_villains(round_flop(), 3), &share, &BASE, &neutral_read()); + assert_eq!(three_way.choice, Choice::Call, "{three_way:?}"); +} + +#[test] +fn semibluff_works_two_way_but_not_three_way() { + let share = estimate(0.45, 0.005); + let two = choose_postflop(&with_villains(round_flop(), 2), &share, &BASE, &flush_draw_read()); + assert!(matches!(two.choice, Choice::Raise { .. }), "{two:?}"); + let three = choose_postflop(&with_villains(round_flop(), 3), &share, &BASE, &flush_draw_read()); + assert_eq!(three.choice, Choice::Call, "{three:?}"); +} + +#[test] +fn the_reason_names_the_player_count_when_multiway() { + let d = choose_postflop( + &with_villains(round_flop(), 3), + &estimate(0.45, 0.002), + &BASE, + &neutral_read(), + ); + assert!(d.reason.contains("3-way"), "{}", d.reason); +} diff --git a/tests/engine_property.rs b/tests/engine_property.rs index b73d67de..e6c64792 100644 --- a/tests/engine_property.rs +++ b/tests/engine_property.rs @@ -1,215 +1,287 @@ -mod spot_fixture; - -use pokerfreak::card::deck; -use pokerfreak::engine::from_plan::from_plan; -use pokerfreak::engine::postflop::choose_postflop; -use pokerfreak::equity::estimate::Estimate; -use pokerfreak::exploit::thresholds::Thresholds; -use pokerfreak::game::{ActionKind, Choice, Decision, Spot, Street, Villain}; -use pokerfreak::guard::enforce::enforce; -use pokerfreak::guard::settle::settle; -use pokerfreak::preflop::plan::{ChartAction, PreflopPlan}; -use pokerfreak::rng::Rng; -use pokerfreak::variant::{ActionShape, Variant}; - -const CASES: usize = 3000; - -/// Tiny generator monad over the seeded Rng: each draw returns the value and the next Rng. -fn unit(rng: Rng) -> (f64, Rng) { - rng.unit() -} - -fn below(rng: Rng, bound: u64) -> (u64, Rng) { - rng.below(bound) -} - -fn chips(rng: Rng, scale: f64) -> (f64, Rng) { - let (kind, rng) = below(rng, 12); - let (x, rng) = unit(rng); - let value = match kind { - 0 => 0.0, - 1 => 0.01 * x, - _ => (x * scale * 100.0).round() / 100.0, - }; - (value, rng) -} - -fn subset_of_legal(rng: Rng) -> (Vec, Rng) { - let (mask, rng) = below(rng, 15); - let kinds: Vec = ActionKind::ALL - .iter() - .enumerate() - .filter(|(i, _)| (mask + 1) >> i & 1 == 1) - .map(|(_, k)| *k) - .collect(); - (kinds, rng) -} - -fn allowed_list(rng: Rng) -> (Option>, Rng) { - let (on, rng) = below(rng, 2); - if on == 0 { - return (None, rng); - } - let (n, rng) = below(rng, 5); - let (values, rng) = (0..n).fold((vec![], rng), |(mut acc, rng), _| { - let (v, rng) = chips(rng, 6.0); - acc.push(v); - (acc, rng) - }); - (Some(values), rng) -} - -fn random_spot(rng: Rng) -> (Spot, Rng) { - let (v, rng) = below(rng, 4); - let variant = Variant::ALL[v as usize]; - let (s, rng) = below(rng, 4); - let street = Street::ALL[s as usize]; - let (hole, rng) = (spot_fixture::cards("Ah 5h"), rng); - let (pot, rng) = chips(rng, 20.0); - let (to_call, rng) = chips(rng, 5.0); - let (stack, rng) = chips(rng, 10.0); - let (min_on, rng) = below(rng, 2); - let (min, rng) = chips(rng, 2.0); - let (max_on, rng) = below(rng, 2); - let (max, rng) = chips(rng, 15.0); - let (legal, rng) = subset_of_legal(rng); - let (allowed, rng) = allowed_list(rng); - let (nv, rng) = below(rng, 4); - let spot = Spot { - variant, - street, - board: deck::full().into_iter().skip(10).take(street.board_len()).collect(), - hero_cards: hole, - pot, - to_call, - hero_stack: stack, - min_raise_to: (min_on == 1).then_some(min), - max_raise_to: (max_on == 1).then_some(max), - legal, - allowed_sizes: allowed, - villains: (0..nv).map(|i| Villain { seat: i as u8, ..spot_fixture::villain(0) }).collect(), - ..spot_fixture::flop() - }; - (spot, rng) -} - -fn random_estimate(rng: Rng) -> (Estimate, Rng) { - let (share, rng) = unit(rng); - let (se, rng) = unit(rng); - (spot_fixture::estimate(share, se * 0.05), rng) -} - -fn random_plan(rng: Rng) -> (PreflopPlan, Rng) { - let (a, rng) = below(rng, 4); - let (certainty, rng) = unit(rng); - let action = [ChartAction::Fold, ChartAction::Call, ChartAction::Raise, ChartAction::Jam][a as usize]; - (spot_fixture::plan(action, certainty), rng) -} - -fn random_thresholds(rng: Rng) -> (Thresholds, Rng) { - let (a, rng) = unit(rng); - let (b, rng) = unit(rng); - let (c, rng) = unit(rng); - let (d, rng) = unit(rng); - ( - Thresholds { - call_margin: a * 0.1, - value_raise: 0.4 + b * 0.5, - abstain_band: c * 0.05, - fold_equity_scale: d * 2.0, - range_width_scale: 1.0, - }, - rng, - ) -} - -fn assert_sound(spot: &Spot, decision: &Decision, label: &str) { - let ctx = format!("{label}: {spot:?} -> {decision:?}"); - if let Some(kind) = decision.choice.kind() { - assert!(spot.is_legal(kind), "illegal kind. {ctx}"); - if kind == ActionKind::Fold { - assert!(!spot.is_legal(ActionKind::Check), "fold with check legal. {ctx}"); - } - } - assert!((0.0..=1.0).contains(&decision.confidence.value()), "{ctx}"); - if let Choice::Raise { to } = decision.choice { - assert!(to.is_finite() && to > 0.0, "{ctx}"); - assert!(to <= spot.hero_stack, "unaffordable. {ctx}"); - if let Some(allowed) = &spot.allowed_sizes { - assert!(allowed.contains(&to), "not from allowedSizes. {ctx}"); - } - if let Some(min) = spot.min_raise_to { - assert!(to >= min || to == spot.hero_stack, "below min and not all-in. {ctx}"); - } - if let Some(max) = spot.max_raise_to { - assert!(to <= max, "above max. {ctx}"); - } - if spot.rules().shape == ActionShape::Binary { - assert!(to == spot.hero_stack || Some(to) == spot.max_raise_to || spot.allowed_sizes.is_some(), "{ctx}"); - } - } - let after = settle(spot, decision.choice); - assert!(after.stack >= 0.0, "negative stack. {ctx}"); - assert!( - (after.stack + after.pot - (spot.hero_stack + spot.pot)).abs() < 1e-9, - "chips not conserved. {ctx}" - ); -} - -#[test] -fn postflop_choices_survive_enforcement_on_random_spots() { - let rng = Rng::seeded(0xD1CE); - let _ = (0..CASES).fold(rng, |rng, _| { - let (spot, rng) = random_spot(rng); - let (est, rng) = random_estimate(rng); - let (th, rng) = random_thresholds(rng); - let raw = choose_postflop(&spot, &est, &th); - assert_sound(&spot, &enforce(&spot, raw), "postflop"); - rng - }); -} - -#[test] -fn preflop_plans_survive_enforcement_on_random_spots() { - let rng = Rng::seeded(0xBEEF); - let _ = (0..CASES).fold(rng, |rng, _| { - let (spot, rng) = random_spot(rng); - let (plan, rng) = random_plan(rng); - let raw = from_plan(&spot, &plan); - assert_sound(&spot, &enforce(&spot, raw), "from_plan"); - rng - }); -} - -#[test] -fn enforce_is_sound_for_arbitrary_decisions() { - let rng = Rng::seeded(0xFACE); - let _ = (0..CASES).fold(rng, |rng, _| { - let (spot, rng) = random_spot(rng); - let (k, rng) = below(rng, 6); - let (size, rng) = chips(rng, 30.0); - let choice = match k { - 0 => Choice::Fold, - 1 => Choice::Check, - 2 => Choice::Call, - 3 => Choice::Raise { to: size }, - 4 => Choice::Raise { to: f64::NAN }, - _ => Choice::Abstain, - }; - assert_sound(&spot, &enforce(&spot, Decision::new(choice, 0.5, "arbitrary")), "enforce"); - rng - }); -} - -#[test] -fn enforce_is_idempotent() { - let rng = Rng::seeded(0xABCD); - let _ = (0..CASES).fold(rng, |rng, _| { - let (spot, rng) = random_spot(rng); - let (est, rng) = random_estimate(rng); - let once = enforce(&spot, choose_postflop(&spot, &est, &Thresholds::BASE)); - let twice = enforce(&spot, once.clone()); - assert_eq!(once.choice, twice.choice, "{spot:?}"); - rng - }); -} +mod spot_fixture; + +use pokerfreak::card::deck; +use pokerfreak::engine::from_plan::from_plan; +use pokerfreak::engine::postflop::choose_postflop; +use pokerfreak::equity::estimate::Estimate; +use pokerfreak::exploit::thresholds::Thresholds; +use pokerfreak::game::{ActionKind, Choice, Decision, Spot, Street, Villain}; +use pokerfreak::guard::enforce::enforce; +use pokerfreak::guard::settle::settle; +use pokerfreak::preflop::plan::{ChartAction, PreflopPlan}; +use pokerfreak::read::draw::Draw; +use pokerfreak::read::hand_read::HandRead; +use pokerfreak::read::made::Made; +use pokerfreak::read::suit_pattern::SuitPattern; +use pokerfreak::rng::Rng; +use pokerfreak::variant::{ActionShape, Variant}; + +const CASES: usize = 3000; +const POSTFLOP_CASES: usize = 4000; + +/// Tiny generator monad over the seeded Rng: each draw returns the value and the next Rng. +fn unit(rng: Rng) -> (f64, Rng) { + rng.unit() +} + +fn below(rng: Rng, bound: u64) -> (u64, Rng) { + rng.below(bound) +} + +fn chips(rng: Rng, scale: f64) -> (f64, Rng) { + let (kind, rng) = below(rng, 12); + let (x, rng) = unit(rng); + let value = match kind { + 0 => 0.0, + 1 => 0.01 * x, + _ => (x * scale * 100.0).round() / 100.0, + }; + (value, rng) +} + +fn subset_of_legal(rng: Rng) -> (Vec, Rng) { + let (mask, rng) = below(rng, 15); + let kinds: Vec = ActionKind::ALL + .iter() + .enumerate() + .filter(|(i, _)| (mask + 1) >> i & 1 == 1) + .map(|(_, k)| *k) + .collect(); + (kinds, rng) +} + +fn allowed_list(rng: Rng) -> (Option>, Rng) { + let (on, rng) = below(rng, 2); + if on == 0 { + return (None, rng); + } + let (n, rng) = below(rng, 5); + let (values, rng) = (0..n).fold((vec![], rng), |(mut acc, rng), _| { + let (v, rng) = chips(rng, 6.0); + acc.push(v); + (acc, rng) + }); + (Some(values), rng) +} + +fn random_spot(rng: Rng) -> (Spot, Rng) { + let (v, rng) = below(rng, Variant::ALL.len() as u64); + let variant = Variant::ALL[v as usize]; + let (s, rng) = below(rng, 4); + let street = Street::ALL[s as usize]; + let (hole, rng) = (spot_fixture::cards("Ah 5h"), rng); + let (pot, rng) = chips(rng, 20.0); + let (to_call, rng) = chips(rng, 5.0); + let (stack, rng) = chips(rng, 10.0); + let (min_on, rng) = below(rng, 2); + let (min, rng) = chips(rng, 2.0); + let (max_on, rng) = below(rng, 2); + let (max, rng) = chips(rng, 15.0); + let (legal, rng) = subset_of_legal(rng); + let (allowed, rng) = allowed_list(rng); + let (nv, rng) = below(rng, 6); + let (folded_mask, rng) = below(rng, 64); + let spot = Spot { + variant, + street, + board: deck::full().into_iter().skip(10).take(street.board_len()).collect(), + hero_cards: hole, + pot, + to_call, + hero_stack: stack, + min_raise_to: (min_on == 1).then_some(min), + max_raise_to: (max_on == 1).then_some(max), + legal, + allowed_sizes: allowed, + villains: (0..nv) + .map(|i| Villain { seat: i as u8, folded: i < 5 && folded_mask >> i & 1 == 1 && folded_mask % 3 == 0, ..spot_fixture::villain(0) }) + .collect(), + ..spot_fixture::flop() + }; + (spot, rng) +} + +fn random_estimate(rng: Rng) -> (Estimate, Rng) { + let (share, rng) = unit(rng); + let (se, rng) = unit(rng); + (spot_fixture::estimate(share, se * 0.05), rng) +} + +const MADES: [Made; 16] = [ + Made::Air, Made::BoardOnly, Made::Underpair, Made::BottomPair, Made::MiddlePair, + Made::TopPairWeakKicker, Made::TopPairGoodKicker, Made::Overpair, Made::TwoPair, Made::Set, + Made::Trips, Made::Straight, Made::Flush, Made::FullHouse, Made::Quads, Made::StraightFlush, +]; +const DRAWS: [Draw; 6] = [Draw::None, Draw::Backdoor, Draw::Gutshot, Draw::OpenEnded, Draw::Flush, Draw::Combo]; +const SUITS: [SuitPattern; 4] = + [SuitPattern::Rainbow, SuitPattern::TwoTone, SuitPattern::Monotone, SuitPattern::FourFlush]; + +fn random_read(rng: Rng) -> (HandRead, Rng) { + let (m, rng) = below(rng, MADES.len() as u64); + let (d, rng) = below(rng, DRAWS.len() as u64); + let (outs, rng) = below(rng, 16); + let (s, rng) = below(rng, SUITS.len() as u64); + let (wet, rng) = unit(rng); + let (odd, rng) = below(rng, 20); + let wetness = if odd == 0 { f64::NAN } else { wet }; + ( + spot_fixture::read_of(MADES[m as usize], DRAWS[d as usize], outs as u8, SUITS[s as usize], wetness), + rng, + ) +} + +fn random_plan(rng: Rng) -> (PreflopPlan, Rng) { + let (a, rng) = below(rng, 4); + let (certainty, rng) = unit(rng); + let action = [ChartAction::Fold, ChartAction::Call, ChartAction::Raise, ChartAction::Jam][a as usize]; + (spot_fixture::plan(action, certainty), rng) +} + +fn random_thresholds(rng: Rng) -> (Thresholds, Rng) { + let (a, rng) = unit(rng); + let (b, rng) = unit(rng); + let (c, rng) = unit(rng); + let (d, rng) = unit(rng); + ( + Thresholds { + call_margin: a * 0.1, + value_raise: 0.4 + b * 0.5, + abstain_band: c * 0.05, + fold_equity_scale: d * 2.0, + range_width_scale: 1.0, + }, + rng, + ) +} + +fn assert_sound(spot: &Spot, decision: &Decision, label: &str) { + let ctx = format!("{label}: {spot:?} -> {decision:?}"); + if let Some(kind) = decision.choice.kind() { + assert!(spot.is_legal(kind), "illegal kind. {ctx}"); + if kind == ActionKind::Fold { + assert!(!spot.is_legal(ActionKind::Check), "fold with check legal. {ctx}"); + } + } + assert!((0.0..=1.0).contains(&decision.confidence.value()), "{ctx}"); + if let Choice::Raise { to } = decision.choice { + assert!(to.is_finite() && to > 0.0, "{ctx}"); + assert!(to <= spot.hero_stack, "unaffordable. {ctx}"); + if let Some(allowed) = &spot.allowed_sizes { + assert!(allowed.contains(&to), "not from allowedSizes. {ctx}"); + } + if let Some(min) = spot.min_raise_to { + assert!(to >= min || to == spot.hero_stack, "below min and not all-in. {ctx}"); + } + if let Some(max) = spot.max_raise_to { + assert!(to <= max, "above max. {ctx}"); + } + if spot.rules().shape == ActionShape::Binary { + assert!(to == spot.hero_stack || Some(to) == spot.max_raise_to || spot.allowed_sizes.is_some(), "{ctx}"); + } + } + let after = settle(spot, decision.choice); + assert!(after.stack >= 0.0, "negative stack. {ctx}"); + assert!( + (after.stack + after.pot - (spot.hero_stack + spot.pot)).abs() < 1e-9, + "chips not conserved. {ctx}" + ); +} + +#[test] +fn postflop_choices_survive_enforcement_on_random_spots() { + let rng = Rng::seeded(0xD1CE); + let _ = (0..POSTFLOP_CASES).fold(rng, |rng, _| { + let (spot, rng) = random_spot(rng); + let (est, rng) = random_estimate(rng); + let (th, rng) = random_thresholds(rng); + let (read, rng) = random_read(rng); + let raw = choose_postflop(&spot, &est, &th, &read); + let enforced = enforce(&spot, raw); + assert_sound(&spot, &enforced, "postflop"); + if enforced.choice == Choice::Abstain { + assert!(enforced.confidence.value() <= 0.3, "abstain too confident: {enforced:?}"); + } + rng + }); +} + +#[test] +fn preflop_plans_survive_enforcement_on_random_spots() { + let rng = Rng::seeded(0xBEEF); + let _ = (0..CASES).fold(rng, |rng, _| { + let (spot, rng) = random_spot(rng); + let (plan, rng) = random_plan(rng); + let raw = from_plan(&spot, &plan); + assert_sound(&spot, &enforce(&spot, raw), "from_plan"); + rng + }); +} + +#[test] +fn enforce_is_sound_for_arbitrary_decisions() { + let rng = Rng::seeded(0xFACE); + let _ = (0..CASES).fold(rng, |rng, _| { + let (spot, rng) = random_spot(rng); + let (k, rng) = below(rng, 6); + let (size, rng) = chips(rng, 30.0); + let choice = match k { + 0 => Choice::Fold, + 1 => Choice::Check, + 2 => Choice::Call, + 3 => Choice::Raise { to: size }, + 4 => Choice::Raise { to: f64::NAN }, + _ => Choice::Abstain, + }; + assert_sound(&spot, &enforce(&spot, Decision::new(choice, 0.5, "arbitrary")), "enforce"); + rng + }); +} + +#[test] +fn enforce_is_idempotent() { + let rng = Rng::seeded(0xABCD); + let _ = (0..CASES).fold(rng, |rng, _| { + let (spot, rng) = random_spot(rng); + let (est, rng) = random_estimate(rng); + let (read, rng) = random_read(rng); + let once = enforce(&spot, choose_postflop(&spot, &est, &Thresholds::BASE, &read)); + let twice = enforce(&spot, once.clone()); + assert_eq!(once.choice, twice.choice, "{spot:?}"); + rng + }); +} + +#[test] +fn postflop_raise_sizes_come_from_the_menu_and_confidence_is_bounded_before_enforcement() { + let rng = Rng::seeded(0x5EED); + let _ = (0..POSTFLOP_CASES).fold(rng, |rng, _| { + let (spot, rng) = random_spot(rng); + let (est, rng) = random_estimate(rng); + let (th, rng) = random_thresholds(rng); + let (read, rng) = random_read(rng); + let raw = choose_postflop(&spot, &est, &th, &read); + assert!((0.0..=1.0).contains(&raw.confidence.value()), "{raw:?}"); + if raw.choice == Choice::Abstain { + assert!(raw.confidence.value() <= 0.3, "{raw:?}"); + } + if let (Choice::Raise { to }, Some(menu)) = (raw.choice, &spot.allowed_sizes) { + assert!(menu.contains(&to), "raw raise {to} not in {menu:?}"); + } + rng + }); +} + +#[test] +fn nothing_beats_nothing_never_raises_on_the_board_alone() { + let rng = Rng::seeded(0xB0A2D); + let _ = (0..CASES).fold(rng, |rng, _| { + let (spot, rng) = random_spot(rng); + let (est, rng) = random_estimate(rng); + let (th, rng) = random_thresholds(rng); + let (read, rng) = random_read(rng); + let read = HandRead { made: Made::BoardOnly, ..read }; + let raw = choose_postflop(&spot, &est, &th, &read); + assert!(!matches!(raw.choice, Choice::Raise { .. }), "{spot:?} {raw:?}"); + rng + }); +} diff --git a/tests/engine_range_filter.rs b/tests/engine_range_filter.rs new file mode 100644 index 00000000..b7222384 --- /dev/null +++ b/tests/engine_range_filter.rs @@ -0,0 +1,63 @@ +mod spot_fixture; + +use pokerfreak::engine::range_filter::range_filter; +use pokerfreak::exploit::range_spec::RangeSpec; +use pokerfreak::preflop::hand_percentile::percentile; +use pokerfreak::variant::{rules, Variant}; +use spot_fixture::cards; + +// Only specs without continuations are tested here: continuations call `read::glance`, +// which is implemented on another branch. + +const HANDS: [&str; 6] = ["Ah Ad", "Kh Qh", "9s 8s", "7d 2c", "Td 5c", "Qs Js"]; + +fn keeps(spec: &RangeSpec, hand: &str) -> bool { + let board = cards("Ac 7d 2s"); + range_filter(spec, rules(Variant::Nlhe), Variant::Nlhe, &board)(&cards(hand)) +} + +#[test] +fn keeps_exactly_the_hands_inside_the_percentile_band() { + let spec = RangeSpec { lo: 0.05, hi: 0.30, continues: Vec::new() }; + for hand in HANDS { + let p = percentile(Variant::Nlhe, &cards(hand)); + assert_eq!(keeps(&spec, hand), (0.05..=0.30).contains(&p), "{hand} at {p}"); + } +} + +#[test] +fn top_spec_keeps_the_best_hands_only() { + let spec = RangeSpec::top(0.10); + assert!(keeps(&spec, "Ah Ad")); + assert!(!keeps(&spec, "7d 2c")); +} + +#[test] +fn the_lower_bound_cuts_off_the_very_best_hands() { + let spec = RangeSpec { lo: 0.2, hi: 1.0, continues: Vec::new() }; + assert!(!keeps(&spec, "Ah Ad")); + assert!(keeps(&spec, "7d 2c")); +} + +#[test] +fn the_full_range_keeps_every_valid_hand() { + let spec = RangeSpec::top(1.0); + assert!(HANDS.iter().all(|h| keeps(&spec, h))); +} + +#[test] +fn nonsense_hands_are_judged_by_their_percentile_and_never_panic() { + let spec = RangeSpec::top(0.5); + let board = cards("Ac 7d 2s"); + let f = range_filter(&spec, rules(Variant::Nlhe), Variant::Nlhe, &board); + assert!(!f(&[])); + assert!(!f(&cards("Ah"))); +} + +#[test] +fn works_for_five_card_hands() { + let spec = RangeSpec::top(1.0); + let board = cards("Ac 7d 2s"); + let f = range_filter(&spec, rules(Variant::Plo5), Variant::Plo5, &board); + assert!(f(&cards("Ah Kh Qd Jc 9s"))); +} diff --git a/tests/engine_read_label.rs b/tests/engine_read_label.rs new file mode 100644 index 00000000..be667932 --- /dev/null +++ b/tests/engine_read_label.rs @@ -0,0 +1,70 @@ +mod spot_fixture; + +use pokerfreak::engine::postflop::choose_postflop; +use pokerfreak::engine::read_label::describe; +use pokerfreak::exploit::thresholds::Thresholds; +use pokerfreak::read::draw::Draw; +use pokerfreak::read::made::Made; +use pokerfreak::read::suit_pattern::SuitPattern; +use spot_fixture::*; + +#[test] +fn names_the_made_hand_and_the_board() { + let wet = read_of(Made::TopPairGoodKicker, Draw::None, 0, SuitPattern::TwoTone, 0.8); + assert_eq!(describe(&wet), "top pair good kicker on wet board"); + let dry = read_of(Made::Overpair, Draw::None, 0, SuitPattern::Rainbow, 0.1); + assert_eq!(describe(&dry), "overpair on dry board"); + let mid = read_of(Made::MiddlePair, Draw::None, 0, SuitPattern::TwoTone, 0.45); + assert_eq!(describe(&mid), "middle pair on medium board"); +} + +#[test] +fn a_four_flush_board_is_named_before_its_wetness() { + let r = read_of(Made::TwoPair, Draw::None, 0, SuitPattern::FourFlush, 0.9); + assert_eq!(describe(&r), "two pair on four-flush board"); +} + +#[test] +fn draws_are_named() { + let r = read_of(Made::Air, Draw::Flush, 9, SuitPattern::TwoTone, 0.8); + assert_eq!(describe(&r), "air with flush draw on wet board"); + let r = read_of(Made::Air, Draw::OpenEnded, 8, SuitPattern::Rainbow, 0.2); + assert_eq!(describe(&r), "air with open-ended draw on dry board"); + let r = read_of(Made::Underpair, Draw::Combo, 12, SuitPattern::Rainbow, 0.2); + assert_eq!(describe(&r), "underpair with combo draw on dry board"); + let r = read_of(Made::Air, Draw::Gutshot, 4, SuitPattern::Rainbow, 0.2); + assert_eq!(describe(&r), "air with gutshot on dry board"); +} + +#[test] +fn no_draw_text_for_nothing_or_backdoor() { + for draw in [Draw::None, Draw::Backdoor] { + let r = read_of(Made::Set, draw, 0, SuitPattern::Rainbow, 0.2); + assert_eq!(describe(&r), "set on dry board"); + } +} + +#[test] +fn every_made_class_has_a_distinct_nonempty_name() { + let all = [ + Made::Air, Made::BoardOnly, Made::Underpair, Made::BottomPair, Made::MiddlePair, + Made::TopPairWeakKicker, Made::TopPairGoodKicker, Made::Overpair, Made::TwoPair, Made::Set, + Made::Trips, Made::Straight, Made::Flush, Made::FullHouse, Made::Quads, Made::StraightFlush, + ]; + let names: Vec = all + .iter() + .map(|m| describe(&read_of(*m, Draw::None, 0, SuitPattern::Rainbow, 0.2))) + .collect(); + let mut sorted = names.clone(); + sorted.sort(); + sorted.dedup(); + assert_eq!(sorted.len(), all.len(), "{names:?}"); +} + +#[test] +fn the_decision_reason_names_the_read() { + let r = read_of(Made::TopPairGoodKicker, Draw::None, 0, SuitPattern::TwoTone, 0.8); + let d = choose_postflop(&round_flop(), &estimate(0.55, 0.002), &Thresholds::BASE, &r); + assert!(d.reason.contains("top pair good kicker on wet board"), "{}", d.reason); + assert!(d.reason.contains("equity 0.55"), "{}", d.reason); +} diff --git a/tests/engine_semibluff.rs b/tests/engine_semibluff.rs new file mode 100644 index 00000000..2e961a95 --- /dev/null +++ b/tests/engine_semibluff.rs @@ -0,0 +1,96 @@ +mod spot_fixture; + +use pokerfreak::engine::postflop::choose_postflop; +use pokerfreak::engine::semibluff::has_real_draw; +use pokerfreak::exploit::thresholds::Thresholds; +use pokerfreak::game::{Choice, Spot, Street}; +use pokerfreak::read::draw::Draw; +use pokerfreak::read::made::Made; +use pokerfreak::read::suit_pattern::SuitPattern; +use spot_fixture::*; + +const BASE: Thresholds = Thresholds::BASE; + +// round_flop: pot 10, 5 to call, stack 100, candidates [10, 15, 20] (1/3, 2/3, pot). +// Share 0.40, heads-up, so realized share is 0.40 and the call needs 1/3 + 0.02. +// call EV = 0.40 * 15 - 5 = 1.0 +// raise to 20, fe = 2/3*s : fe*10 + (1-fe) * (0.40 * 45 - 20) [final pot 45] +// raise to 15, fe = 0.6*s : fe*10 + (1-fe) * (0.40 * 35 - 15) [final pot 35] +// raise to 10, fe = 0.5*s : fe*10 + (1-fe) * (0.40 * 25 - 10) [final pot 25] +// scale 1.0: raise to 20 = 6.667 - 0.667 = 6.0 (beats the call by 5.0) +// scale 0.15: 10 -> 0.75, 15 -> -0.01, 20 -> -0.80, all below the call's 1.0. + +#[test] +fn flush_draw_with_good_fold_equity_raises() { + let d = choose_postflop(&round_flop(), &estimate(0.40, 0.005), &BASE, &flush_draw_read()); + assert_eq!(d.choice, Choice::Raise { to: 20.0 }, "{d:?}"); + assert!(d.reason.contains("semibluff"), "{}", d.reason); + assert!(d.reason.contains("flush draw"), "{}", d.reason); +} + +#[test] +fn the_same_draw_only_calls_against_a_calling_station() { + let station = Thresholds { fold_equity_scale: 0.15, ..BASE }; + let d = choose_postflop(&round_flop(), &estimate(0.40, 0.005), &station, &flush_draw_read()); + assert_eq!(d.choice, Choice::Call, "{d:?}"); +} + +#[test] +fn no_semibluff_on_the_river() { + let river = Spot { street: Street::River, ..round_flop() }; + let d = choose_postflop(&river, &estimate(0.40, 0.005), &BASE, &flush_draw_read()); + assert_eq!(d.choice, Choice::Call, "{d:?}"); +} + +#[test] +fn pure_bluffs_without_equity_stay_off() { + let air = read_of(Made::Air, Draw::None, 0, SuitPattern::Rainbow, 0.2); + let th = Thresholds { abstain_band: 0.0, ..BASE }; + let d = choose_postflop(&round_flop(), &estimate(0.40, 0.0), &th, &air); + assert_eq!(d.choice, Choice::Call, "{d:?}"); + // Even a hopeless hand never turns into a bluff raise. + let d = choose_postflop(&round_flop(), &estimate(0.10, 0.0), &th, &air); + assert_eq!(d.choice, Choice::Fold, "{d:?}"); +} + +#[test] +fn eight_outs_count_as_a_real_draw_even_for_a_gutshot_class() { + let eight = read_of(Made::Air, Draw::Gutshot, 8, SuitPattern::Rainbow, 0.2); + let seven = read_of(Made::Air, Draw::Gutshot, 7, SuitPattern::Rainbow, 0.2); + let d8 = choose_postflop(&round_flop(), &estimate(0.40, 0.005), &BASE, &eight); + let d7 = choose_postflop(&round_flop(), &estimate(0.40, 0.005), &BASE, &seven); + assert!(matches!(d8.choice, Choice::Raise { .. }), "{d8:?}"); + assert_eq!(d7.choice, Choice::Call, "{d7:?}"); +} + +#[test] +fn which_reads_are_real_draws() { + let r = |draw, outs| read_of(Made::Air, draw, outs, SuitPattern::Rainbow, 0.2); + for draw in [Draw::OpenEnded, Draw::Flush, Draw::Combo] { + assert!(has_real_draw(&r(draw, 0), Street::Flop), "{draw:?}"); + assert!(!has_real_draw(&r(draw, 9), Street::River), "{draw:?}"); + } + assert!(has_real_draw(&r(Draw::None, 8), Street::Turn)); + assert!(!has_real_draw(&r(Draw::None, 7), Street::Turn)); + assert!(!has_real_draw(&r(Draw::Backdoor, 3), Street::Flop)); + assert!(!has_real_draw(&r(Draw::Gutshot, 4), Street::Flop)); +} + +#[test] +fn a_semibluff_is_also_possible_when_the_raise_is_the_only_way_to_continue_cheaply() { + // Free to act: check is the passive option (EV share * pot = 4.0 at 0.40). + let spot = Spot { + to_call: 0.0, + legal: vec![pokerfreak::game::ActionKind::Check, pokerfreak::game::ActionKind::Raise], + ..round_flop() + }; + let d = choose_postflop(&spot, &estimate(0.40, 0.005), &BASE, &flush_draw_read()); + assert!(matches!(d.choice, Choice::Raise { .. }), "{d:?}"); +} + +#[test] +fn board_only_never_raises_even_with_a_huge_share() { + let board = read_of(Made::BoardOnly, Draw::None, 0, SuitPattern::Rainbow, 0.0); + let d = choose_postflop(&round_flop(), &estimate(0.95, 0.002), &BASE, &board); + assert_eq!(d.choice, Choice::Call, "{d:?}"); +} diff --git a/tests/engine_texture_stance.rs b/tests/engine_texture_stance.rs new file mode 100644 index 00000000..01724983 --- /dev/null +++ b/tests/engine_texture_stance.rs @@ -0,0 +1,125 @@ +mod spot_fixture; + +use pokerfreak::engine::texture_stance::texture_stance; +use pokerfreak::exploit::thresholds::Thresholds; +use pokerfreak::read::draw::Draw; +use pokerfreak::read::made::Made; +use pokerfreak::read::suit_pattern::SuitPattern; +use spot_fixture::read_of; + +const BASE: Thresholds = Thresholds::BASE; // call_margin 0.02, value_raise 0.62 + +fn close(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-9 +} + +#[test] +fn medium_hand_on_a_wet_board_loses_the_thin_value_raise_and_pays_more() { + let read = read_of(Made::MiddlePair, Draw::None, 0, SuitPattern::TwoTone, 0.8); + let s = texture_stance(&BASE, &read, true); + assert!(!s.value_ok); + assert!(s.raise_ok); + assert!(close(s.call_margin, 0.02 + 0.01 + 0.04 * 0.8), "{s:?}"); + assert!(close(s.value_raise, 0.62 + 0.06 + 0.12 * 0.8), "{s:?}"); +} + +#[test] +fn medium_hand_on_a_dry_board_may_still_value_raise_but_needs_more() { + let read = read_of(Made::TopPairWeakKicker, Draw::None, 0, SuitPattern::Rainbow, 0.1); + let s = texture_stance(&BASE, &read, true); + assert!(s.value_ok); + assert!(close(s.call_margin, 0.02 + 0.01 + 0.004), "{s:?}"); + assert!(close(s.value_raise, 0.62 + 0.06 + 0.012), "{s:?}"); +} + +#[test] +fn medium_hand_on_a_four_flush_board_never_value_raises() { + let read = read_of(Made::MiddlePair, Draw::None, 0, SuitPattern::FourFlush, 0.3); + let s = texture_stance(&BASE, &read, true); + assert!(!s.value_ok); + assert!(close(s.call_margin, 0.02 + 0.01 + 0.012 + 0.03), "{s:?}"); +} + +#[test] +fn strong_hand_on_a_dry_board_raises_slightly_below_the_value_threshold() { + let read = read_of(Made::TopPairGoodKicker, Draw::None, 0, SuitPattern::Rainbow, 0.0); + let s = texture_stance(&BASE, &read, true); + assert!(s.value_ok); + assert!(close(s.value_raise, 0.58), "{s:?}"); + assert!(close(s.call_margin, 0.02), "{s:?}"); +} + +#[test] +fn strong_hand_on_a_wet_board_wants_more_equity_to_raise() { + let read = read_of(Made::Overpair, Draw::None, 0, SuitPattern::TwoTone, 1.0); + let s = texture_stance(&BASE, &read, true); + assert!(close(s.value_raise, 0.62 + 0.05), "{s:?}"); + assert!(close(s.call_margin, 0.02 + 0.02), "{s:?}"); +} + +#[test] +fn strong_hand_on_a_four_flush_board_is_more_careful_still() { + let read = read_of(Made::TwoPair, Draw::None, 0, SuitPattern::FourFlush, 0.5); + let s = texture_stance(&BASE, &read, true); + assert!(close(s.value_raise, 0.62 + 0.08 + 0.025), "{s:?}"); + assert!(close(s.call_margin, 0.02 + 0.01 + 0.03), "{s:?}"); +} + +#[test] +fn weak_hand_without_draw_facing_a_bet_is_stricter() { + let read = read_of(Made::BottomPair, Draw::None, 0, SuitPattern::Rainbow, 0.2); + let s = texture_stance(&BASE, &read, true); + assert!(close(s.call_margin, 0.05), "{s:?}"); + assert!(close(s.value_raise, 0.72), "{s:?}"); +} + +#[test] +fn weak_hand_with_a_draw_keeps_the_plain_call_margin() { + let read = read_of(Made::Air, Draw::Gutshot, 4, SuitPattern::Rainbow, 0.2); + assert!(close(texture_stance(&BASE, &read, true).call_margin, 0.02)); +} + +#[test] +fn weak_hand_not_facing_a_bet_keeps_the_plain_call_margin() { + let read = read_of(Made::Air, Draw::None, 0, SuitPattern::Rainbow, 0.2); + assert!(close(texture_stance(&BASE, &read, false).call_margin, 0.02)); +} + +#[test] +fn board_only_never_raises() { + let read = read_of(Made::BoardOnly, Draw::None, 0, SuitPattern::Rainbow, 0.0); + let s = texture_stance(&BASE, &read, false); + assert!(!s.raise_ok); + assert!(!s.value_ok); +} + +#[test] +fn monsters_are_never_moved() { + for suits in [SuitPattern::Rainbow, SuitPattern::Monotone, SuitPattern::FourFlush] { + for wet in [0.0, 0.5, 1.0] { + let read = read_of(Made::FullHouse, Draw::None, 0, suits, wet); + let s = texture_stance(&BASE, &read, true); + assert!(close(s.call_margin, 0.02) && close(s.value_raise, 0.62), "{s:?}"); + assert!(s.value_ok && s.raise_ok); + } + } +} + +#[test] +fn outputs_stay_inside_their_ranges() { + let high = Thresholds { value_raise: 0.9, call_margin: 0.19, ..BASE }; + let weak = read_of(Made::Air, Draw::None, 0, SuitPattern::Rainbow, 0.0); + let s = texture_stance(&high, &weak, true); + assert!(close(s.value_raise, 0.95), "{s:?}"); + assert!(close(s.call_margin, 0.2), "{s:?}"); + let low = Thresholds { value_raise: 0.5, ..BASE }; + let strong = read_of(Made::Overpair, Draw::None, 0, SuitPattern::Rainbow, 0.0); + assert!(close(texture_stance(&low, &strong, true).value_raise, 0.5)); +} + +#[test] +fn unknown_wetness_is_treated_as_medium() { + let nan = read_of(Made::MiddlePair, Draw::None, 0, SuitPattern::TwoTone, f64::NAN); + let mid = read_of(Made::MiddlePair, Draw::None, 0, SuitPattern::TwoTone, 0.5); + assert_eq!(texture_stance(&BASE, &nan, true), texture_stance(&BASE, &mid, true)); +} diff --git a/tests/engine_uncertainty.rs b/tests/engine_uncertainty.rs new file mode 100644 index 00000000..b95820b7 --- /dev/null +++ b/tests/engine_uncertainty.rs @@ -0,0 +1,92 @@ +mod spot_fixture; + +use pokerfreak::engine::postflop::choose_postflop; +use pokerfreak::engine::uncertainty::{abstain_confidence, MAX_UNCERTAIN_CONFIDENCE, MIN_UNCERTAIN_CONFIDENCE}; +use pokerfreak::exploit::thresholds::Thresholds; +use pokerfreak::game::Choice; +use pokerfreak::read::draw::Draw; +use pokerfreak::read::made::Made; +use pokerfreak::read::suit_pattern::SuitPattern; +use spot_fixture::*; + +const BASE: Thresholds = Thresholds::BASE; + +fn close(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-9 +} + +#[test] +fn confidence_rises_linearly_from_the_edge_to_the_rim_of_the_band() { + assert!(close(abstain_confidence(0.0, 0.04), 0.05)); + assert!(close(abstain_confidence(0.02, 0.04), 0.175)); + assert!(close(abstain_confidence(0.04, 0.04), 0.30)); + assert_eq!(MIN_UNCERTAIN_CONFIDENCE, 0.05); + assert_eq!(MAX_UNCERTAIN_CONFIDENCE, 0.30); +} + +#[test] +fn confidence_never_leaves_its_range() { + for (d, w) in [(1.0, 0.04), (-1.0, 0.04), (0.01, 0.0), (f64::NAN, 0.1), (0.1, f64::NAN), (f64::INFINITY, 1.0)] { + let c = abstain_confidence(d, w); + assert!((0.05..=0.30).contains(&c), "{d} {w} -> {c}"); + } +} + +// round_flop: break-even 1/3, plain call margin 0.02 -> call breakpoint 0.3533. + +#[test] +fn abstain_near_the_effective_breakpoint_carries_small_confidence() { + let d = choose_postflop(&round_flop(), &estimate(0.34, 0.005), &BASE, &neutral_read()); + assert_eq!(d.choice, Choice::Abstain); + let c = d.confidence.value(); + assert!((0.05..=0.30).contains(&c), "{c}"); +} + +#[test] +fn closer_to_the_edge_means_less_confidence() { + let near = choose_postflop(&round_flop(), &estimate(0.352, 0.005), &BASE, &neutral_read()); + let rim = choose_postflop(&round_flop(), &estimate(0.335, 0.005), &BASE, &neutral_read()); + assert_eq!((near.choice, rim.choice), (Choice::Abstain, Choice::Abstain)); + assert!(near.confidence < rim.confidence, "{near:?} {rim:?}"); +} + +#[test] +fn the_band_applies_to_the_texture_adjusted_breakpoint() { + // Medium pair on a dry board: margin 0.02 + 0.01 + 0.004 = 0.034 -> breakpoint 0.3673. + // Share 0.38 is outside the band around the plain 0.3533 but inside the one around 0.3673. + let medium = read_of(Made::MiddlePair, Draw::None, 0, SuitPattern::Rainbow, 0.1); + let plain = choose_postflop(&round_flop(), &estimate(0.38, 0.001), &BASE, &neutral_read()); + let shifted = choose_postflop(&round_flop(), &estimate(0.38, 0.001), &BASE, &medium); + assert_eq!(plain.choice, Choice::Call); + assert_eq!(shifted.choice, Choice::Abstain, "{shifted:?}"); +} + +#[test] +fn the_band_applies_to_the_multiway_adjusted_breakpoint() { + // Three-way: realized 0.38 * 0.9409 = 0.3575, breakpoint 0.3333 + 0.04 = 0.3733. + let spot = with_villains(round_flop(), 3); + let d = choose_postflop(&spot, &estimate(0.38, 0.001), &BASE, &neutral_read()); + assert_eq!(d.choice, Choice::Abstain, "{d:?}"); +} + +#[test] +fn marginal_raise_versus_call_abstains_with_small_confidence() { + // Flush draw, share 0.40, fold-equity scale 0.4: the best raise (to 10) is worth 2.0 + // against the call's 1.0. EV standard error = std_error * final pot (25). + let th = Thresholds { fold_equity_scale: 0.4, ..BASE }; + let noisy = choose_postflop(&round_flop(), &estimate(0.40, 0.05), &th, &flush_draw_read()); + assert_eq!(noisy.choice, Choice::Abstain, "{noisy:?}"); + let c = noisy.confidence.value(); + assert!((0.05..=0.30).contains(&c), "{c}"); + let tight = choose_postflop(&round_flop(), &estimate(0.40, 0.02), &th, &flush_draw_read()); + assert!(matches!(tight.choice, Choice::Raise { .. }), "{tight:?}"); +} + +#[test] +fn invalid_equity_stays_at_zero_confidence() { + for share in [f64::NAN, -0.1, 1.5] { + let d = choose_postflop(&round_flop(), &estimate(share, 0.01), &BASE, &neutral_read()); + assert_eq!(d.choice, Choice::Abstain); + assert_eq!(d.confidence.value(), 0.0); + } +} diff --git a/tests/spot_fixture/mod.rs b/tests/spot_fixture/mod.rs index e74b58d9..67bada60 100644 --- a/tests/spot_fixture/mod.rs +++ b/tests/spot_fixture/mod.rs @@ -1,79 +1,111 @@ -#![allow(dead_code)] -//! Shared builders for spots, estimates and plans used by the engine-side tests. - -use pokerfreak::card::Card; -use pokerfreak::equity::estimate::Estimate; -use pokerfreak::game::{ActionKind, Spot, Street, Villain}; -use pokerfreak::preflop::plan::{ChartAction, PreflopPlan}; -use pokerfreak::variant::Variant; - -pub fn cards(text: &str) -> Vec { - Card::parse_list(text).expect("fixture cards") -} - -pub fn villain(seat: u8) -> Villain { - Villain { seat, stack: 10.0, folded: false, profile: None } -} - -/// NLHE flop, hero Ah5h on Ac7d2s, pot 1.25, 0.2 to call, stack 2.4. -pub fn flop() -> Spot { - Spot { - variant: Variant::Nlhe, - big_blind: 0.1, - seats: 6, - hero_seat: 5, - button_seat: None, - hero_cards: cards("Ah 5h"), - board: cards("Ac 7d 2s"), - street: Street::Flop, - pot: 1.25, - to_call: 0.2, - hero_stack: 2.4, - min_raise_to: Some(0.5), - max_raise_to: Some(20.0), - legal: vec![ActionKind::Fold, ActionKind::Call, ActionKind::Raise], - allowed_sizes: None, - villains: vec![villain(2)], - seed: 1, - history: Vec::new(), - } -} - -/// Round numbers: pot 10, 5 to call, deep stack. Break-even is exactly 1/3. -pub fn round_flop() -> Spot { - Spot { - pot: 10.0, - to_call: 5.0, - hero_stack: 100.0, - min_raise_to: Some(10.0), - max_raise_to: Some(100.0), - ..flop() - } -} - -/// Preflop NLHE, hero SB-ish: pot 0.15, 0.1 to call, stack 10. -pub fn preflop() -> Spot { - Spot { - board: vec![], - street: Street::Preflop, - pot: 0.15, - to_call: 0.1, - hero_stack: 10.0, - min_raise_to: Some(0.2), - max_raise_to: Some(10.0), - ..flop() - } -} - -pub fn with_variant(spot: Spot, variant: Variant) -> Spot { - let hole = if variant == Variant::Plo5 { "Ah 5h Kd Qc 9s" } else { "Ah 5h" }; - Spot { variant, hero_cards: cards(hole), ..spot } -} - -pub fn estimate(share: f64, std_error: f64) -> Estimate { - Estimate { win: share, tie: 0.0, share, trials: 3000, std_error } -} - -pub fn plan(action: ChartAction, certainty: f64) -> PreflopPlan { - PreflopPlan { action, percentile: 0.1, certainty, reason: "chart".to_string() } -} +#![allow(dead_code)] +//! Shared builders for spots, estimates and plans used by the engine-side tests. + +use pokerfreak::card::Card; +use pokerfreak::equity::estimate::Estimate; +use pokerfreak::game::{ActionKind, Spot, Street, Villain}; +use pokerfreak::preflop::plan::{ChartAction, PreflopPlan}; +use pokerfreak::read::draw::Draw; +use pokerfreak::read::hand_read::HandRead; +use pokerfreak::read::made::Made; +use pokerfreak::read::pairing::Pairing; +use pokerfreak::read::suit_pattern::SuitPattern; +use pokerfreak::read::texture::Texture; +use pokerfreak::variant::Variant; + +pub fn cards(text: &str) -> Vec { + Card::parse_list(text).expect("fixture cards") +} + +pub fn villain(seat: u8) -> Villain { + Villain { seat, stack: 10.0, folded: false, profile: None } +} + +/// NLHE flop, hero Ah5h on Ac7d2s, pot 1.25, 0.2 to call, stack 2.4. +pub fn flop() -> Spot { + Spot { + variant: Variant::Nlhe, + big_blind: 0.1, + seats: 6, + hero_seat: 5, + button_seat: None, + hero_cards: cards("Ah 5h"), + board: cards("Ac 7d 2s"), + street: Street::Flop, + pot: 1.25, + to_call: 0.2, + hero_stack: 2.4, + min_raise_to: Some(0.5), + max_raise_to: Some(20.0), + legal: vec![ActionKind::Fold, ActionKind::Call, ActionKind::Raise], + allowed_sizes: None, + villains: vec![villain(2)], + seed: 1, + history: Vec::new(), + } +} + +/// Round numbers: pot 10, 5 to call, deep stack. Break-even is exactly 1/3. +pub fn round_flop() -> Spot { + Spot { + pot: 10.0, + to_call: 5.0, + hero_stack: 100.0, + min_raise_to: Some(10.0), + max_raise_to: Some(100.0), + ..flop() + } +} + +/// Preflop NLHE, hero SB-ish: pot 0.15, 0.1 to call, stack 10. +pub fn preflop() -> Spot { + Spot { + board: vec![], + street: Street::Preflop, + pot: 0.15, + to_call: 0.1, + hero_stack: 10.0, + min_raise_to: Some(0.2), + max_raise_to: Some(10.0), + ..flop() + } +} + +pub fn with_variant(spot: Spot, variant: Variant) -> Spot { + let hole = if variant == Variant::Plo5 { "Ah 5h Kd Qc 9s" } else { "Ah 5h" }; + Spot { variant, hero_cards: cards(hole), ..spot } +} + +pub fn estimate(share: f64, std_error: f64) -> Estimate { + Estimate { win: share, tie: 0.0, share, trials: 3000, std_error } +} + +pub fn plan(action: ChartAction, certainty: f64) -> PreflopPlan { + PreflopPlan { action, percentile: 0.1, certainty, reason: "chart".to_string() } +} + +/// A hand read built from parts (no board analysis involved). +pub fn read_of(made: Made, draw: Draw, outs: u8, suits: SuitPattern, wetness: f64) -> HandRead { + HandRead { + made, + draw, + outs, + nut_draw: false, + texture: Texture { suits, pairing: Pairing::Unpaired, connectivity: 2, high: None, wetness }, + } +} + +/// A monster on a medium board: no texture rule moves any threshold for it. +pub fn neutral_read() -> HandRead { + read_of(Made::Straight, Draw::None, 0, SuitPattern::TwoTone, 0.5) +} + +/// Air with a flush draw (9 outs) on a two-tone flop. +pub fn flush_draw_read() -> HandRead { + read_of(Made::Air, Draw::Flush, 9, SuitPattern::TwoTone, 0.5) +} + +/// `n` live villains on seats 1..=n. +pub fn with_villains(spot: Spot, n: u8) -> Spot { + Spot { villains: (1..=n).map(villain).collect(), ..spot } +}