diff --git a/src/exploit/band_bounds.rs b/src/exploit/band_bounds.rs new file mode 100644 index 00000000..8c650445 --- /dev/null +++ b/src/exploit/band_bounds.rs @@ -0,0 +1,19 @@ +/// Narrowest band the equity code can sample from. +pub const MIN_WIDTH: f64 = 0.03; + +/// Forces any pair into `0 <= lo`, `hi <= 1`, `hi - lo >= 0.03`. NaN counts as the widest +/// choice on that side (`lo = 0`, `hi = 1`). The upper edge is kept when possible, +/// the lower edge gives way. +pub fn bounded(lo: f64, hi: f64) -> (f64, f64) { + let hi = if hi.is_nan() { + 1.0 + } else { + hi.clamp(MIN_WIDTH, 1.0) + }; + let lo = if lo.is_nan() { + 0.0 + } else { + lo.clamp(0.0, hi - MIN_WIDTH) + }; + (lo, hi) +} diff --git a/src/exploit/band_stretch.rs b/src/exploit/band_stretch.rs new file mode 100644 index 00000000..3b12ca25 --- /dev/null +++ b/src/exploit/band_stretch.rs @@ -0,0 +1,37 @@ +use super::preflop_role::PreflopRole; +use super::profile::Profile; +use super::range_guess::DEFAULT_VPIP; + +/// A regular preflop raise frequency (six-max). +pub const DEFAULT_PFR: f64 = 0.18; +const MIN_STRETCH: f64 = 0.5; +const MAX_STRETCH: f64 = 1.8; + +fn frequency(x: Option) -> Option { + x.filter(|v| !v.is_nan()).map(|v| v.clamp(0.0, 1.0)) +} + +/// How much looser (> 1) or tighter (< 1) than the reference player this villain is, for +/// the kind of action the role is made of. Clamped to `[0.5, 1.8]`; 1.0 without data. +/// +/// - raising roles: `pfr / 0.18`; without pfr, `sqrt(vpip / 0.30)` (half-strength vpip) +/// - calling, limping and blind roles: `vpip / 0.30` +pub fn stretch(role: PreflopRole, profile: Option) -> f64 { + let profile = profile.unwrap_or_default(); + let (vpip, pfr) = (frequency(profile.vpip), frequency(profile.pfr)); + let raw = if role.is_raising() { + pfr.map(|f| f / DEFAULT_PFR) + .or_else(|| vpip.map(|v| (v / DEFAULT_VPIP).sqrt())) + } else { + vpip.map(|v| v / DEFAULT_VPIP) + }; + raw.unwrap_or(1.0).clamp(MIN_STRETCH, MAX_STRETCH) +} + +/// A band `[lo, hi]` for a player `factor` times as loose as the reference: the upper +/// edge moves out by `factor`, the lower edge in by `1 / factor` (looser players raise +/// less often with their best hands, so fewer hands are excluded at the top). +/// Width is non-decreasing in `factor`. +pub fn stretched(lo: f64, hi: f64, factor: f64) -> (f64, f64) { + (lo / factor, hi * factor) +} diff --git a/src/exploit/bet_ratio.rs b/src/exploit/bet_ratio.rs new file mode 100644 index 00000000..fe6da707 --- /dev/null +++ b/src/exploit/bet_ratio.rs @@ -0,0 +1,16 @@ +use super::pot_trace::{contribution, pot_before}; +use crate::game::ActionRecord; + +/// Per record: chips added divided by the pot before it. `None` if the amount or the pot +/// is unknown, or the pot is empty. Only meaningful for bets, raises and all-ins. +pub fn bet_ratios(history: &[ActionRecord]) -> Vec> { + pot_before(history) + .into_iter() + .enumerate() + .map(|(index, pot)| { + let pot = pot.filter(|p| *p > 0.0)?; + let ratio = contribution(history, index)? / pot; + Some(ratio).filter(|r| r.is_finite()) + }) + .collect() +} diff --git a/src/exploit/made_ladder.rs b/src/exploit/made_ladder.rs new file mode 100644 index 00000000..e1d71123 --- /dev/null +++ b/src/exploit/made_ladder.rs @@ -0,0 +1,25 @@ +use crate::read::made::Made; + +/// The rungs a continuation floor moves on, weakest first. +const LADDER: [Made; 9] = [ + Made::Air, + Made::BottomPair, + Made::MiddlePair, + Made::TopPairWeakKicker, + Made::TopPairGoodKicker, + Made::Overpair, + Made::TwoPair, + Made::Set, + Made::Straight, +]; + +/// A floor never goes below bottom pair (rung 1): "any made hand" is the loosest claim. +const LOWEST_RUNG: i32 = 1; + +/// Rung `base + shift`, clamped to the ladder. Positive shifts are stricter. +pub fn rung(base: i32, shift: i32) -> Made { + let index = base + .saturating_add(shift) + .clamp(LOWEST_RUNG, LADDER.len() as i32 - 1); + LADDER[index as usize] +} diff --git a/src/exploit/mod.rs b/src/exploit/mod.rs index 0dbc69e5..b8c78aa3 100644 --- a/src/exploit/mod.rs +++ b/src/exploit/mod.rs @@ -1,12 +1,22 @@ //! Exploitation layer: reads opponent profiles, moves thresholds and range guesses. pub mod adjust; +pub mod band_bounds; +pub mod band_stretch; +pub mod bet_ratio; pub mod fold_equity_scale; +pub mod made_ladder; +pub mod pot_trace; +pub mod preflop_role; pub mod profile; pub mod range_guess; pub mod range_model; pub mod range_spec; pub mod range_narrowing; +pub mod role_band; +pub mod role_from_history; +pub mod size_notch; +pub mod street_continuation; pub mod style; pub mod style_shift; pub mod thresholds; diff --git a/src/exploit/pot_trace.rs b/src/exploit/pot_trace.rs new file mode 100644 index 00000000..323c45ec --- /dev/null +++ b/src/exploit/pot_trace.rs @@ -0,0 +1,41 @@ +use crate::game::{ActionRecord, SeenAction}; + +/// What the seat had in on this street before `history[index]`: the last amount of an +/// earlier non-ante record of the same seat and street (0 if none). +fn already_in(history: &[ActionRecord], index: usize) -> f64 { + let record = &history[index]; + history[..index] + .iter() + .rev() + .filter(|r| { + r.seat == record.seat && r.street == record.street && r.action != SeenAction::PostAnte + }) + .find_map(|r| r.amount.filter(|a| a.is_finite())) + .unwrap_or(0.0) +} + +/// Chips `history[index]` added to the pot. `None` when it cannot be told: a paying action +/// without a (usable) amount. Folds and checks add 0. Out-of-range index gives `None`. +pub fn contribution(history: &[ActionRecord], index: usize) -> Option { + let record = history.get(index)?; + match record.action { + SeenAction::Fold | SeenAction::Check => Some(0.0), + SeenAction::PostAnte => record.amount.filter(|a| a.is_finite() && *a >= 0.0), + _ => record + .amount + .filter(|a| a.is_finite() && *a >= 0.0) + .map(|a| (a - already_in(history, index)).max(0.0)), + } +} + +/// The pot before each record, summed from the contributions. From the first record whose +/// contribution is unknown on, the pot is unknown (`None`). +pub fn pot_before(history: &[ActionRecord]) -> Vec> { + (0..history.len()) + .scan(Some(0.0), |pot, index| { + let before = *pot; + *pot = before.zip(contribution(history, index)).map(|(p, c)| p + c); + Some(before) + }) + .collect() +} diff --git a/src/exploit/preflop_role.rs b/src/exploit/preflop_role.rs new file mode 100644 index 00000000..c705e723 --- /dev/null +++ b/src/exploit/preflop_role.rs @@ -0,0 +1,38 @@ +/// What a villain's preflop actions say about the hands they hold. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum PreflopRole { + /// First raise of the hand. + Opener, + /// Re-raised an open. + ThreeBettor, + /// Re-raised a 3-bet or more. + FourBettorPlus, + /// Jammed into an unraised pot. + JamOpen, + /// Jammed over a raise. + JamOverRaise, + /// Called one raise (cold caller, or a blind defending). + CallsRaise, + /// Called a 3-bet or more (also the opener who calls a 3-bet). + CallsThreeBet, + /// Called the big blind in an unraised pot. + Limper, + /// Small blind completing in an unraised pot. + SmallBlindCompleter, + /// Big blind that only checked its option. + BigBlindCheck, +} + +impl PreflopRole { + /// Raising roles follow the player pfr, the others their vpip. + pub fn is_raising(self) -> bool { + matches!( + self, + PreflopRole::Opener + | PreflopRole::ThreeBettor + | PreflopRole::FourBettorPlus + | PreflopRole::JamOpen + | PreflopRole::JamOverRaise + ) + } +} diff --git a/src/exploit/range_model.rs b/src/exploit/range_model.rs index 92b6873a..2308b296 100644 --- a/src/exploit/range_model.rs +++ b/src/exploit/range_model.rs @@ -1,11 +1,52 @@ +use super::band_bounds::bounded; +use super::band_stretch::{stretch, stretched}; +use super::range_guess::{top_fraction, DEFAULT_VPIP}; use super::range_spec::RangeSpec; +use super::role_band::role_band; +use super::role_from_history::role_of; +use super::street_continuation::continuations; use crate::game::{Spot, Villain}; +use crate::preflop::seat_position::seat_position; + +/// Without a readable preflop role the band is the plain vpip share. +fn unknown_role_band(villain: &Villain) -> (f64, f64) { + let vpip = villain + .profile + .and_then(|p| p.vpip) + .filter(|v| !v.is_nan()) + .map_or(DEFAULT_VPIP, |v| v.clamp(0.02, 1.0)); + (0.0, vpip) +} + +fn preflop_band(spot: &Spot, villain: &Villain) -> (f64, f64) { + match role_of(&spot.history, villain.seat) { + Some(role) => { + let (lo, hi) = role_band(spot, role, seat_position(spot, villain.seat)); + stretched(lo, hi, stretch(role, villain.profile)) + } + None => unknown_role_band(villain), + } +} /// Estimated range of `villain`, narrowed by the observed action sequence -/// (`spot.history`): preflop role (raiser, caller, 3-bettor, blind) sets the band, -/// postflop bets/raises add continuations. Without history it falls back to -/// `range_guess::top_fraction`. +/// (`spot.history`). +/// +/// - **No record of this seat in the history** (including an empty history): exactly the old +/// `RangeSpec::top(range_guess::top_fraction(spot, villain))`. +/// - Otherwise the **preflop band** comes from the villain role (`role_from_history`, +/// table in `role_band`, position from `seat_position`), stretched by the profile +/// (`band_stretch`), forced well-formed (`band_bounds`); the **postflop continuations** +/// from their bets and raises (`street_continuation`). +/// +/// Output: `0 <= lo`, `hi <= 1`, `hi - lo >= 0.03`, continuations sorted, only for dealt +/// streets. Never panics, whatever the history looks like. pub fn range_spec(spot: &Spot, villain: &Villain) -> RangeSpec { - let _ = (spot, villain); - todo!("exploit::range_model") + if spot.history.iter().any(|r| r.seat == villain.seat) { + let (raw_lo, raw_hi) = preflop_band(spot, villain); + let (lo, hi) = bounded(raw_lo, raw_hi); + RangeSpec { lo, hi, continues: continuations(spot, villain) } + } else { + RangeSpec::top(top_fraction(spot, villain)) + } } + diff --git a/src/exploit/role_band.rs b/src/exploit/role_band.rs new file mode 100644 index 00000000..b9461dba --- /dev/null +++ b/src/exploit/role_band.rs @@ -0,0 +1,77 @@ +use super::preflop_role::PreflopRole; +use crate::game::Spot; +use crate::preflop::chart_row::ChartRow; +use crate::preflop::full_chart::full_row; +use crate::preflop::position::Position; +use crate::preflop::situation::Situation; +use crate::preflop::width_factor::width_factor; + +/// Share of hands that jam into an unraised pot. +const JAM_OPEN: f64 = 0.15; +/// Share of hands that jam over a raise. +const JAM_OVER_RAISE: f64 = 0.06; +/// Callers miss the top of the re-raising range, but half of it may still flat: the band +/// starts at this share of the raise cut-off. +const SLOWPLAY_SHARE: f64 = 0.5; +/// Limpers re-raise their best hands: the top 10 % is missing. +const LIMP_TOP_CAP: f64 = 0.10; +/// A limping range: 1.3 x the chart calling width plus 15 points. +const LIMP_WIDTH_MULTIPLE: f64 = 1.3; +const LIMP_WIDTH_BONUS: f64 = 0.15; +/// The small blind completes cheaply (half a bet) with most hands but not the best ones. +const SB_COMPLETE_TOP_CAP: f64 = 0.10; +const SB_COMPLETE_WIDTH: f64 = 0.75; + +/// Chart row for a villain in `position` (unknown counts as middle position), scaled +/// by table size and game like hero own chart. +fn chart(spot: &Spot, position: Position, situation: Situation) -> ChartRow { + let position = if position == Position::Unknown { + Position::Middle + } else { + position + }; + full_row(position, situation) + .unwrap_or(ChartRow::new(0.0, 0.0, 0.0)) + .scaled(width_factor(spot.seats, spot.rules().hole_usage)) +} + +/// Percentile band `(lo, hi)` (0 = best) before profile stretching and clamping: +/// +/// | role | band | +/// |---|---| +/// | opener | `[0, chart open]` of the villain position | +/// | 3-bettor | `[0, chart raise vs open]` | +/// | 4-bettor+ | `[0, chart raise vs 3-bet]` | +/// | jam | `[0, 0.15]` unraised, `[0, 0.06]` over a raise | +/// | calls a raise | `[0.5 x raise vs open, call vs open]` (blinds use their own rows) | +/// | calls a 3-bet+ | `[0.5 x raise vs 3-bet, call vs 3-bet]` | +/// | limper | `[0.10, 0.15 + 1.3 x chart open-call]` | +/// | small blind completes | `[0.10, 0.75]` | +/// | big blind checks | `[0.5 x BB raise vs limp, 1]` | +pub fn role_band(spot: &Spot, role: PreflopRole, position: Position) -> (f64, f64) { + let at = |situation| chart(spot, position, situation); + match role { + PreflopRole::Opener => (0.0, at(Situation::Unopened).raise), + PreflopRole::ThreeBettor => (0.0, at(Situation::FacingOpen).raise), + PreflopRole::FourBettorPlus => (0.0, at(Situation::FacingThreeBetPlus).raise), + PreflopRole::JamOpen => (0.0, JAM_OPEN), + PreflopRole::JamOverRaise => (0.0, JAM_OVER_RAISE), + PreflopRole::CallsRaise => { + let row = at(Situation::FacingOpen); + (SLOWPLAY_SHARE * row.raise, row.call) + } + PreflopRole::CallsThreeBet => { + let row = at(Situation::FacingThreeBetPlus); + (SLOWPLAY_SHARE * row.raise, row.call) + } + PreflopRole::Limper => ( + LIMP_TOP_CAP, + LIMP_WIDTH_BONUS + LIMP_WIDTH_MULTIPLE * at(Situation::Unopened).call, + ), + PreflopRole::SmallBlindCompleter => (SB_COMPLETE_TOP_CAP, SB_COMPLETE_WIDTH), + PreflopRole::BigBlindCheck => ( + SLOWPLAY_SHARE * chart(spot, Position::BigBlind, Situation::FacingLimp).raise, + 1.0, + ), + } +} diff --git a/src/exploit/role_from_history.rs b/src/exploit/role_from_history.rs new file mode 100644 index 00000000..3b61a9be --- /dev/null +++ b/src/exploit/role_from_history.rs @@ -0,0 +1,120 @@ +use super::preflop_role::PreflopRole; +use crate::game::{ActionRecord, SeenAction, Street}; + +/// The villain last voluntary preflop action and how many raises came before it. +#[derive(Clone, Copy)] +enum Last { + Aggression { raises_before: usize, all_in: bool }, + Call { raises_before: usize }, + Check, +} + +#[derive(Clone, Copy, Default)] +struct Facts { + raises: usize, + small_blind: bool, + big_blind: bool, + last: Option, +} + +fn own_action(facts: Facts, action: SeenAction) -> Facts { + match action { + SeenAction::PostSmallBlind => Facts { + small_blind: true, + ..facts + }, + SeenAction::PostBigBlind => Facts { + big_blind: true, + ..facts + }, + SeenAction::PostAnte | SeenAction::Fold => facts, + SeenAction::Check => Facts { + last: Some(Last::Check), + ..facts + }, + SeenAction::Call => Facts { + last: Some(Last::Call { + raises_before: facts.raises, + }), + ..facts + }, + SeenAction::Bet | SeenAction::Raise | SeenAction::AllIn => Facts { + last: Some(Last::Aggression { + raises_before: facts.raises, + all_in: action == SeenAction::AllIn, + }), + ..facts + }, + } +} + +fn step(facts: Facts, record: &ActionRecord, seat: u8) -> Facts { + let updated = if record.seat == seat { + own_action(facts, record.action) + } else { + facts + }; + Facts { + raises: updated.raises + usize::from(record.action.is_aggressive()), + ..updated + } +} + +fn by_raises_faced(raises: usize) -> PreflopRole { + match raises { + 0 => PreflopRole::Limper, + 1 => PreflopRole::CallsRaise, + _ => PreflopRole::CallsThreeBet, + } +} + +/// Role of `seat` from the preflop records, in order (other seats only count as context). +/// `None` if there is nothing to go on. +/// +/// - The last call-or-aggression decides. Aggression after no raise: `Opener`, after one: +/// `ThreeBettor`, after more: `FourBettorPlus`; an all-in is a jam instead. +/// A call after no raise is a limp (`SmallBlindCompleter` for the small blind, a check +/// for the big blind), after one raise `CallsRaise`, after more `CallsThreeBet`. +/// So an opener who then calls a 3-bet is `CallsThreeBet`. +/// - A big blind whose last act is a check is `BigBlindCheck`. +/// - A blind with no later action is assumed to have stayed in: no raise at all gives +/// `BigBlindCheck` / `SmallBlindCompleter`, one raise `CallsRaise`, more `CallsThreeBet`. +/// - Every all-in counts as a raise for the raises-faced count, even a short call. +/// - Folds and antes are ignored. +pub fn role_of(history: &[ActionRecord], seat: u8) -> Option { + let facts = history + .iter() + .filter(|r| r.street == Street::Preflop) + .fold(Facts::default(), |facts, record| step(facts, record, seat)); + match facts.last { + Some(Last::Aggression { + raises_before, + all_in: true, + }) => Some(if raises_before == 0 { + PreflopRole::JamOpen + } else { + PreflopRole::JamOverRaise + }), + Some(Last::Aggression { + raises_before, + all_in: false, + }) => Some(match raises_before { + 0 => PreflopRole::Opener, + 1 => PreflopRole::ThreeBettor, + _ => PreflopRole::FourBettorPlus, + }), + Some(Last::Call { raises_before: 0 }) if facts.big_blind => { + Some(PreflopRole::BigBlindCheck) + } + Some(Last::Call { raises_before: 0 }) if facts.small_blind => { + Some(PreflopRole::SmallBlindCompleter) + } + Some(Last::Call { raises_before }) => Some(by_raises_faced(raises_before)), + Some(Last::Check) if facts.big_blind => Some(PreflopRole::BigBlindCheck), + Some(Last::Check) => None, + None if facts.big_blind && facts.raises == 0 => Some(PreflopRole::BigBlindCheck), + None if facts.small_blind && facts.raises == 0 => Some(PreflopRole::SmallBlindCompleter), + None if facts.big_blind || facts.small_blind => Some(by_raises_faced(facts.raises)), + None => None, + } +} diff --git a/src/exploit/size_notch.rs b/src/exploit/size_notch.rs new file mode 100644 index 00000000..a309eaf9 --- /dev/null +++ b/src/exploit/size_notch.rs @@ -0,0 +1,19 @@ +/// Bet size (chips added / pot before) as a number of rungs: bigger bets are stricter. +/// +/// | ratio | rungs | +/// |---|---| +/// | below 0.4 pot | -1 | +/// | 0.4 up to 0.9 | 0 | +/// | 0.9 up to 1.8 | +1 | +/// | 1.8 and more | +2 | +/// +/// Unknown (or NaN) size: 0. +pub fn size_notch(ratio: Option) -> i32 { + match ratio { + Some(r) if r < 0.4 => -1, + Some(r) if r < 0.9 => 0, + Some(r) if r < 1.8 => 1, + Some(r) if r >= 1.8 => 2, + _ => 0, + } +} diff --git a/src/exploit/street_continuation.rs b/src/exploit/street_continuation.rs new file mode 100644 index 00000000..f431e849 --- /dev/null +++ b/src/exploit/street_continuation.rs @@ -0,0 +1,142 @@ +use super::bet_ratio::bet_ratios; +use super::made_ladder::rung; +use super::range_spec::Continuation; +use super::size_notch::size_notch; +use super::style::{classify, Style}; +use crate::game::{ActionRecord, SeenAction, Spot, Street, Villain}; +use crate::read::made::Made; + +/// A call of a bet at least this big (pot fractions) shows a hand with some showdown value. +const BIG_BET: f64 = 0.6; + +/// Floor rung of a bet / of a raise (or all-in) per street (flop, turn, river), see `LADDER` +/// in `made_ladder`: middle pair, top pair weak kicker, top pair good kicker for bets; +/// top pair good kicker, overpair, two pair for raises. +const BET_RUNG: [i32; 3] = [2, 3, 4]; +const RAISE_RUNG: [i32; 3] = [4, 5, 6]; +/// Draws are still in on flop and turn, not on the river. +const DRAWS: [bool; 3] = [true, true, false]; + +/// Looser styles lose one rung, the nit gains one. +fn style_shift(villain: &Villain) -> i32 { + match villain.profile.map(|p| classify(&p)) { + Some(Style::CallingStation | Style::LooseAggressive) => -1, + Some(Style::Nit) => 1, + _ => 0, + } +} + +/// Bet = 0, raise (RAISE or ALL_IN) = 1. +fn level(action: SeenAction) -> Option { + match action { + SeenAction::Bet => Some(0), + SeenAction::Raise | SeenAction::AllIn => Some(1), + _ => None, + } +} + +/// The strongest aggression of the villain on `street`: highest level, then biggest ratio. +fn own_aggression( + history: &[ActionRecord], + ratios: &[Option], + street: Street, + seat: u8, +) -> Option<(usize, Option)> { + history + .iter() + .zip(ratios) + .filter(|(r, _)| r.street == street && r.seat == seat) + .filter_map(|(r, ratio)| level(r.action).map(|l| (l, *ratio))) + .max_by(|a, b| { + a.0.cmp(&b.0).then( + a.1.unwrap_or(-1.0) + .partial_cmp(&b.1.unwrap_or(-1.0)) + .unwrap_or(std::cmp::Ordering::Equal), + ) + }) +} + +/// Did the villain call, on `street`, a bet or raise (by anyone) of at least `BIG_BET` pots? +fn called_big_bet( + history: &[ActionRecord], + ratios: &[Option], + street: Street, + seat: u8, +) -> bool { + history.iter().enumerate().any(|(i, r)| { + r.street == street + && r.seat == seat + && r.action == SeenAction::Call + && history[..i] + .iter() + .zip(&ratios[..i]) + .rev() + .find(|(b, _)| b.street == street && b.action.is_aggressive()) + .is_some_and(|(_, ratio)| ratio.is_some_and(|x| x >= BIG_BET)) + }) +} + +fn merge(a: Option<(Made, bool)>, b: Option<(Made, bool)>) -> Option<(Made, bool)> { + match (a, b) { + (Some((ma, da)), Some((mb, db))) => Some((ma.max(mb), da && db)), + (one, other) => one.or(other), + } +} + +/// One continuation for the villain on `street`, if their actions there say anything. +fn on_street( + spot: &Spot, + ratios: &[Option], + villain: &Villain, + street: Street, +) -> Option { + let slot = street as usize - 1; + let made_bet = + own_aggression(&spot.history, ratios, street, villain.seat).map(|(lvl, ratio)| { + let base = [BET_RUNG, RAISE_RUNG][lvl][slot]; + ( + rung(base, size_notch(ratio) + style_shift(villain)), + DRAWS[slot], + ) + }); + let made_call = called_big_bet(&spot.history, ratios, street, villain.seat).then(|| { + ( + if street == Street::River { + Made::MiddlePair + } else { + Made::BottomPair + }, + DRAWS[slot], + ) + }); + merge(made_bet, made_call).map(|(min_made, draws_continue)| Continuation { + board_len: street.board_len(), + min_made, + draws_continue, + }) +} + +/// Postflop narrowing from the villain own actions, one entry per dealt street +/// (`board_len <= spot.board.len()`), sorted by board length. +/// +/// - **Bet** keeps `[middle pair, top pair weak kicker, top pair good kicker]+` on +/// flop/turn/river; **raise or all-in** keeps `[top pair good kicker, overpair, two pair]+`. +/// Flop and turn bets keep draws, the river keeps made hands only. Several actions on +/// one street: the highest level (then the biggest) counts. +/// - The size (chips added / pot before, from the amounts in the history) moves the floor +/// by `size_notch` rungs: bigger is stricter. Unknown sizes or pots: no move. +/// - A calling station or loose-aggressive style (see `style::classify`) lowers the floor +/// one rung, a nit raises it one. The floor never drops below bottom pair. +/// - **Checks and calls add nothing**: the continuation only expresses a minimum strength, +/// and a check does not say the hand is weak (traps) nor does a call bound it from +/// below in a useful way. One exception, a mild floor: a call of a bet of at least 0.6 pot +/// keeps bottom pair or better (or a draw) on flop/turn, middle pair or better on the river. +/// Combined with the villain own bet on the same street the stricter floor wins. +pub fn continuations(spot: &Spot, villain: &Villain) -> Vec { + let ratios = bet_ratios(&spot.history); + [Street::Flop, Street::Turn, Street::River] + .into_iter() + .filter(|street| street.board_len() <= spot.board.len()) + .filter_map(|street| on_street(spot, &ratios, villain, street)) + .collect() +} diff --git a/src/preflop/advise.rs b/src/preflop/advise.rs index 1c7616c3..85a2ff99 100644 --- a/src/preflop/advise.rs +++ b/src/preflop/advise.rs @@ -6,7 +6,7 @@ use super::effective_stack::effective_stack_bb; use super::full_chart::full_row; use super::hand_percentile::percentile; use super::plan::PreflopPlan; -use super::position::position; +use super::seat_position::seat_position; use super::push_chart::push_cutoff; use super::reason::describe; use super::situation::{classify, Situation}; @@ -30,7 +30,7 @@ fn sane_scale(scale: f64) -> f64 { /// The cut-offs that apply here, before the hand is looked at. fn cutoffs(spot: &Spot, situation: Situation, effective_bb: f64, scale: f64) -> ChartRow { let rules = spot.rules(); - let pos = position(spot.seats, spot.hero_seat, spot.button_seat); + let pos = seat_position(spot, spot.hero_seat); let width = width_factor(spot.seats, rules.hole_usage) * scale; match (situation, rules.shape) { (Situation::FacingAllIn, ActionShape::Full) => { @@ -62,7 +62,7 @@ fn cutoffs(spot: &Spot, situation: Situation, effective_bb: f64, scale: f64) -> /// then selects jam / raise / call / fold. Binary-shape games only ever answer Jam or Fold. pub fn advise(spot: &Spot, thresholds: &Thresholds) -> PreflopPlan { let hand = percentile(spot.variant, &spot.hero_cards); - let pos = position(spot.seats, spot.hero_seat, spot.button_seat); + let pos = seat_position(spot, spot.hero_seat); let situation = classify(spot.to_call, spot.big_blind, spot.pot, spot.hero_stack); let row = cutoffs( spot, diff --git a/src/preflop/button.rs b/src/preflop/button.rs new file mode 100644 index 00000000..63060223 --- /dev/null +++ b/src/preflop/button.rs @@ -0,0 +1,75 @@ +//! The dealer button: given explicitly, or inferred from the posted blinds. + +use crate::game::{SeenAction, Spot, Street}; + +const MIN_SEATS: u8 = 2; +const MAX_SEATS: u8 = 10; + +/// Seat of the button. +/// +/// 1. An explicit `buttonSeat` always wins (even if the history disagrees). +/// 2. Otherwise the first preflop `POST_SB` in `history`: the button sits one seat before +/// the small blind; heads-up the small blind *is* the button. +/// 3. Otherwise the first preflop `POST_BB`: two seats before it; heads-up the other seat. +/// 4. Otherwise `None`. +/// +/// Seat numbers may start at 0 or at 1. The numbering is read off every seat that appears +/// (hero, villains, history): a seat `0` means 0-based, a seat `seats` means 1-based. If +/// both readings stay possible and they disagree (the answer wraps around the table), +/// the result is `None`. If every seat is out of range for both readings, `None` too. +/// Needs `2 <= seats <= 10`. +pub fn button_seat(spot: &Spot) -> Option { + spot.button_seat.or_else(|| inferred(spot)) +} + +fn first_post(spot: &Spot, kind: SeenAction) -> Option { + spot.history + .iter() + .find(|r| r.street == Street::Preflop && r.action == kind) + .map(|r| r.seat) +} + +/// Seats in play, as far as the request tells. +fn seats_seen(spot: &Spot) -> impl Iterator + '_ { + std::iter::once(spot.hero_seat) + .chain(spot.villains.iter().map(|v| v.seat)) + .chain(spot.history.iter().map(|r| r.seat)) +} + +/// Numbering bases (0 or 1) under which every seat in play is a valid seat number. +fn possible_bases(spot: &Spot) -> Vec { + [0u8, 1] + .into_iter() + .filter(|base| { + seats_seen(spot).all(|s| s >= *base && (s as u16) < *base as u16 + spot.seats as u16) + }) + .collect() +} + +/// `steps` seats counter-clockwise from `seat`, wrapping inside `base..base + seats`. +fn step_back(seat: u8, steps: u8, seats: u8, base: u8) -> u8 { + (seat - base + seats - steps) % seats + base +} + +fn inferred(spot: &Spot) -> Option { + if !(MIN_SEATS..=MAX_SEATS).contains(&spot.seats) { + return None; + } + let heads_up = spot.seats == 2; + let (anchor, steps) = match ( + first_post(spot, SeenAction::PostSmallBlind), + first_post(spot, SeenAction::PostBigBlind), + ) { + (Some(sb), _) => (sb, if heads_up { 0 } else { 1 }), + (None, Some(bb)) => (bb, if heads_up { 1 } else { 2 }), + (None, None) => return None, + }; + let answers: Vec = possible_bases(spot) + .into_iter() + .map(|base| step_back(anchor, steps, spot.seats, base)) + .collect(); + match answers.split_first() { + Some((first, rest)) if rest.iter().all(|a| a == first) => Some(*first), + _ => None, + } +} diff --git a/src/preflop/mod.rs b/src/preflop/mod.rs index 55cd7954..58e53bee 100644 --- a/src/preflop/mod.rs +++ b/src/preflop/mod.rs @@ -2,6 +2,7 @@ pub mod advise; pub mod allin_call_cutoff; +pub mod button; pub mod certainty; pub mod chart_decision; pub mod chart_row; @@ -20,5 +21,6 @@ pub mod plo5_suits; pub mod position; pub mod push_chart; pub mod reason; +pub mod seat_position; pub mod situation; pub mod width_factor; diff --git a/src/preflop/position.rs b/src/preflop/position.rs index db75983a..21bd046e 100644 --- a/src/preflop/position.rs +++ b/src/preflop/position.rs @@ -33,6 +33,10 @@ impl Position { const MIN_SEATS: u8 = 2; const MAX_SEATS: u8 = 10; +/// Early/Middle split: of the `seats - 4` seats between the big blind and the cutoff, the first +/// half (rounded up) is `Early`, the rest `Middle`. 5 seats: 1E; 6: 1E 1M; 7: 2E 1M; 8: 2E 2M; +/// 9: 3E 2M; 10: 3E 3M. Tables of 3 or 4 seats have no such seats. +/// /// Position of `hero_seat` with the button on `button_seat`. Seat numbers may be 0- or /// 1-based (only their difference matters); `Unknown` without a button, with fewer /// than 2 or more than 10 seats, or with a seat number above `seats`. diff --git a/src/preflop/seat_position.rs b/src/preflop/seat_position.rs new file mode 100644 index 00000000..0cdd0f9e --- /dev/null +++ b/src/preflop/seat_position.rs @@ -0,0 +1,11 @@ +//! Position of any seat, with the button taken from the request or inferred from the history. + +use super::button::button_seat; +use super::position::{position, Position}; +use crate::game::Spot; + +/// `position(spot.seats, seat, button_seat(spot))`: `Unknown` only if neither an explicit +/// `buttonSeat` nor the blinds in `history` locate the button. +pub fn seat_position(spot: &Spot, seat: u8) -> Position { + position(spot.seats, seat, button_seat(spot)) +} diff --git a/src/wire/decode.rs b/src/wire/decode.rs index d025f84b..d60b7726 100644 --- a/src/wire/decode.rs +++ b/src/wire/decode.rs @@ -1,5 +1,6 @@ use super::decode_board::board; use super::decode_card::cards; +use super::decode_history::history; use super::decode_legal::{allowed_sizes, legal_actions}; use super::decode_name::named; use super::decode_villain::villains; @@ -31,6 +32,6 @@ pub fn decode(root: &Value) -> Result { villains: villains(root)?, button_seat: opt_u8_member(root, "", "buttonSeat")?, seed: opt_u64_member(root, "", "seed")?.unwrap_or(DEFAULT_SEED), - history: Vec::new(), + history: history(root)?, }) } diff --git a/src/wire/decode_history.rs b/src/wire/decode_history.rs new file mode 100644 index 00000000..9313eedf --- /dev/null +++ b/src/wire/decode_history.rs @@ -0,0 +1,67 @@ +use crate::fault::Fault; +use crate::game::{ActionRecord, SeenAction, Street}; +use crate::json::field::{at, join, optional}; +use crate::json::member::{opt_items_member, opt_number_member, text_member, u8_member}; +use crate::json::Value; + +fn vocabulary( + entry: &Value, + path: &str, + key: &str, + parse: fn(&str) -> Option, +) -> Result { + let given = text_member(entry, path, key)?; + parse(given).ok_or_else(|| Fault::Invalid { + field: join(path, key), + detail: format!("unknown value {given:?}"), + }) +} + +fn amount(entry: &Value, path: &str) -> Result, Fault> { + let value = opt_number_member(entry, path, "amount")?; + match value { + Some(n) if n < 0.0 || n.is_nan() => Err(Fault::Invalid { + field: join(path, "amount"), + detail: format!("expected a non-negative number, found {n}"), + }), + other => Ok(other), + } +} + +fn record(entry: &Value, path: &str) -> Result { + // A non-object entry faults here, at the entry path (not at its first member). + optional(entry, path, "street")?; + Ok(ActionRecord { + street: vocabulary(entry, path, "street", Street::parse)?, + seat: u8_member(entry, path, "seat")?, + action: vocabulary(entry, path, "action", SeenAction::parse)?, + amount: amount(entry, path)?, + }) +} + +/// Extension field `history`: the observed actions of this hand so far, oldest first. +/// +/// ```text +/// "history": [ +/// {"street": "PREFLOP", "seat": 4, "action": "POST_SB", "amount": 0.5}, +/// {"street": "PREFLOP", "seat": 2, "action": "RAISE", "amount": 3.0}, +/// {"street": "FLOP", "seat": 5, "action": "CHECK"} +/// ] +/// ``` +/// +/// - `street`: `PREFLOP | FLOP | TURN | RIVER` +/// - `seat`: whole number, same numbering as `heroSeat` / `villains[].seat` +/// - `action`: `POST_SB | POST_BB | POST_ANTE | FOLD | CHECK | CALL | BET | RAISE | ALL_IN` +/// - `amount` (optional, `null` = unknown): the seat's total contribution on that street +/// after the action (raise-to semantics), a non-negative number. +/// +/// Absent or `null` means an empty history. Any malformed entry is a `Fault` whose path +/// names the entry, e.g. `history[2].action`. +pub fn history(root: &Value) -> Result, Fault> { + opt_items_member(root, "", "history")? + .unwrap_or(&[]) + .iter() + .enumerate() + .map(|(i, entry)| record(entry, &at("history", i))) + .collect() +} diff --git a/src/wire/mod.rs b/src/wire/mod.rs index 78d64dff..0eb6367a 100644 --- a/src/wire/mod.rs +++ b/src/wire/mod.rs @@ -3,6 +3,7 @@ pub mod decode; pub mod decode_board; pub mod decode_card; +pub mod decode_history; pub mod decode_legal; pub mod decode_name; pub mod decode_villain; diff --git a/tests/history_decode.rs b/tests/history_decode.rs new file mode 100644 index 00000000..8477f260 --- /dev/null +++ b/tests/history_decode.rs @@ -0,0 +1,153 @@ +use pokerfreak::fault::Fault; +use pokerfreak::game::{ActionRecord, SeenAction, Spot, Street}; +use pokerfreak::json::parse; +use pokerfreak::wire::decode::decode; + +const EXAMPLE: &str = r#"{ + "variant": "NLHE", + "bigBlind": 0.1, + "seats": 6, + "heroSeat": 5, + "heroCards": [{"rank": "A", "suit": "HEARTS"}, {"rank": "5", "suit": "HEARTS"}], + "board": {"FLOP": [{"rank": "A", "suit": "CLUBS"}], "TURN": null, "RIVER": null}, + "street": "FLOP", + "pot": 1.25, + "toCall": 0.2, + "heroStack": 2.4, + "minRaiseTo": 0.5, + "maxRaiseTo": 20.0, + "legalActions": ["FOLD", "CALL", "RAISE"], + "allowedSizes": [0.5, 1.15, 4.6], + "villains": [{"seat": 2, "stack": 10.4, "folded": false}] +}"#; + +fn base(extra: &str) -> String { + format!( + r#"{{"variant":"NLHE","bigBlind":1,"seats":6,"heroSeat":0, + "heroCards":[{{"rank":"ACE","suit":"SPADES"}},{{"rank":"KING","suit":"SPADES"}}], + "street":"PREFLOP","pot":1.5,"toCall":1,"heroStack":100,"legalActions":["FOLD","CALL"]{extra}}}"# + ) +} + +fn run(history: &str) -> Result { + decode(&parse(&base(&format!(r#","history":{history}"#))).expect("test json")) +} + +fn failing_path(history: &str) -> String { + match run(history).expect_err("must fail") { + Fault::Invalid { field, .. } => field, + Fault::Missing(field) => field, + other => panic!("unexpected fault {other:?}"), + } +} + +#[test] +fn contract_example_without_history_has_an_empty_history() { + let spot = decode(&parse(EXAMPLE).unwrap()).unwrap(); + assert!(spot.history.is_empty()); +} + +#[test] +fn null_and_empty_history_are_empty() { + assert!(run("null").unwrap().history.is_empty()); + assert!(run("[]").unwrap().history.is_empty()); +} + +#[test] +fn decodes_every_field_in_order() { + let spot = run( + r#"[{"street":"PREFLOP","seat":4,"action":"POST_SB","amount":0.5}, + {"street":"PREFLOP","seat":5,"action":"POST_BB","amount":1}, + {"street":"PREFLOP","seat":0,"action":"RAISE","amount":3}, + {"street":"PREFLOP","seat":1,"action":"FOLD"}, + {"street":"FLOP","seat":5,"action":"CHECK","amount":null}, + {"street":"TURN","seat":0,"action":"BET","amount":4.5}, + {"street":"RIVER","seat":0,"action":"ALL_IN","amount":40}]"#, + ) + .unwrap(); + let expected = vec![ + ActionRecord { street: Street::Preflop, seat: 4, action: SeenAction::PostSmallBlind, amount: Some(0.5) }, + ActionRecord { street: Street::Preflop, seat: 5, action: SeenAction::PostBigBlind, amount: Some(1.0) }, + ActionRecord { street: Street::Preflop, seat: 0, action: SeenAction::Raise, amount: Some(3.0) }, + ActionRecord { street: Street::Preflop, seat: 1, action: SeenAction::Fold, amount: None }, + ActionRecord { street: Street::Flop, seat: 5, action: SeenAction::Check, amount: None }, + ActionRecord { street: Street::Turn, seat: 0, action: SeenAction::Bet, amount: Some(4.5) }, + ActionRecord { street: Street::River, seat: 0, action: SeenAction::AllIn, amount: Some(40.0) }, + ]; + assert_eq!(spot.history, expected); +} + +#[test] +fn every_action_name_is_accepted() { + for action in SeenAction::ALL { + let text = format!(r#"[{{"street":"FLOP","seat":1,"action":"{}"}}]"#, action.name()); + assert_eq!(run(&text).unwrap().history[0].action, action); + } +} + +#[test] +fn history_must_be_an_array() { + assert_eq!(failing_path(r#"{"street":"FLOP"}"#), "history"); + assert_eq!(failing_path("\"x\""), "history"); +} + +#[test] +fn entry_must_be_an_object() { + assert_eq!(failing_path("[3]"), "history[0]"); +} + +#[test] +fn faults_carry_the_path_of_the_entry() { + let ok = r#"{"street":"FLOP","seat":1,"action":"CHECK"}"#; + assert_eq!( + failing_path(&format!(r#"[{ok},{ok},{{"street":"FLOP","seat":1,"action":"LIMP"}}]"#)), + "history[2].action" + ); + assert_eq!( + failing_path(&format!(r#"[{ok},{{"street":"BEACH","seat":1,"action":"CHECK"}}]"#)), + "history[1].street" + ); + assert_eq!(failing_path(r#"[{"street":"FLOP","action":"CHECK"}]"#), "history[0].seat"); + assert_eq!(failing_path(r#"[{"seat":1,"action":"CHECK"}]"#), "history[0].street"); + assert_eq!(failing_path(r#"[{"street":"FLOP","seat":1}]"#), "history[0].action"); +} + +#[test] +fn bad_types_are_faults() { + assert_eq!( + failing_path(r#"[{"street":"FLOP","seat":"one","action":"CHECK"}]"#), + "history[0].seat" + ); + assert_eq!( + failing_path(r#"[{"street":"FLOP","seat":1.5,"action":"CHECK"}]"#), + "history[0].seat" + ); + assert_eq!( + failing_path(r#"[{"street":"FLOP","seat":-1,"action":"CHECK"}]"#), + "history[0].seat" + ); + assert_eq!( + failing_path(r#"[{"street":"FLOP","seat":300,"action":"CHECK"}]"#), + "history[0].seat" + ); + assert_eq!( + failing_path(r#"[{"street":7,"seat":1,"action":"CHECK"}]"#), + "history[0].street" + ); + assert_eq!( + failing_path(r#"[{"street":"FLOP","seat":1,"action":null}]"#), + "history[0].action" + ); +} + +#[test] +fn amount_must_be_a_non_negative_number() { + assert_eq!( + failing_path(r#"[{"street":"FLOP","seat":1,"action":"BET","amount":"big"}]"#), + "history[0].amount" + ); + assert_eq!( + failing_path(r#"[{"street":"FLOP","seat":1,"action":"BET","amount":-2}]"#), + "history[0].amount" + ); +} diff --git a/tests/position_advise.rs b/tests/position_advise.rs new file mode 100644 index 00000000..e46c936d --- /dev/null +++ b/tests/position_advise.rs @@ -0,0 +1,65 @@ +mod position_fixture; + +use pokerfreak::exploit::thresholds::Thresholds; +use pokerfreak::game::{ActionRecord, Spot}; +use pokerfreak::preflop::advise::advise; +use pokerfreak::preflop::position::Position; +use pokerfreak::preflop::seat_position::seat_position; +use position_fixture::{post_bb, post_sb, spot}; + +fn unopened(hero: u8, villains: &[u8], button: Option, history: Vec) -> Spot { + Spot { button_seat: button, ..spot(6, hero, villains, history) } +} + +#[test] +fn seat_position_uses_the_explicit_button() { + let s = unopened(0, &[1], Some(3), vec![]); + assert_eq!(seat_position(&s, 0), Position::Early); + assert_eq!(seat_position(&s, 3), Position::Button); + assert_eq!(seat_position(&s, 5), Position::BigBlind); +} + +#[test] +fn seat_position_uses_the_inferred_button() { + let s = unopened(0, &[1], None, vec![post_sb(4), post_bb(5)]); + assert_eq!(seat_position(&s, 3), Position::Button); + assert_eq!(seat_position(&s, 4), Position::SmallBlind); + assert_eq!(seat_position(&s, 2), Position::Cutoff); +} + +#[test] +fn seat_position_stays_unknown_without_any_hint() { + let s = unopened(0, &[1], None, vec![]); + assert_eq!(seat_position(&s, 2), Position::Unknown); +} + +#[test] +fn advise_reasons_name_the_inferred_position() { + let inferred = unopened(3, &[0], None, vec![post_sb(4), post_bb(5)]); + let plan = advise(&inferred, &Thresholds::BASE); + assert!(plan.reason.starts_with("BTN "), "{}", plan.reason); +} + +#[test] +fn advise_with_an_inferred_button_equals_advise_with_the_explicit_one() { + for hero in 0..6u8 { + let hist = vec![post_sb(4), post_bb(5)]; + let a = unopened(hero, &[0, 5], None, hist.clone()); + let b = unopened(hero, &[0, 5], Some(3), hist); + assert_eq!(advise(&a, &Thresholds::BASE), advise(&b, &Thresholds::BASE)); + } +} + +#[test] +fn advise_without_button_or_history_keeps_the_unknown_label() { + let s = unopened(3, &[0], None, vec![]); + let plan = advise(&s, &Thresholds::BASE); + assert!(plan.reason.starts_with("pos? "), "{}", plan.reason); +} + +#[test] +fn explicit_button_beats_a_conflicting_history() { + let s = unopened(3, &[0], Some(1), vec![post_sb(4), post_bb(5)]); + let plan = advise(&s, &Thresholds::BASE); + assert!(!plan.reason.starts_with("BTN "), "{}", plan.reason); +} diff --git a/tests/position_button.rs b/tests/position_button.rs new file mode 100644 index 00000000..6bb735a5 --- /dev/null +++ b/tests/position_button.rs @@ -0,0 +1,143 @@ +mod position_fixture; + +use pokerfreak::game::{SeenAction, Spot, Street}; +use pokerfreak::preflop::button::button_seat; +use position_fixture::{post_bb, post_sb, rec, spot}; + +fn with_button(s: Spot, button: Option) -> Spot { + Spot { button_seat: button, ..s } +} + +#[test] +fn explicit_button_wins_over_history() { + let s = with_button(spot(6, 0, &[1, 2], vec![post_sb(4), post_bb(5)]), Some(2)); + assert_eq!(button_seat(&s), Some(2)); +} + +#[test] +fn nothing_to_infer_from_is_none() { + assert_eq!(button_seat(&spot(6, 0, &[1, 2], vec![])), None); + assert_eq!(button_seat(&spot(6, 0, &[1, 2], vec![rec(3, SeenAction::Raise)])), None); +} + +#[test] +fn button_is_one_before_the_small_blind() { + // 0-based, hero seat 0 pins the numbering. + assert_eq!(button_seat(&spot(6, 0, &[], vec![post_sb(4)])), Some(3)); + assert_eq!(button_seat(&spot(6, 0, &[], vec![post_sb(1)])), Some(0)); + // 1-based, seat 6 is present. + assert_eq!(button_seat(&spot(6, 6, &[], vec![post_sb(4)])), Some(3)); +} + +#[test] +fn small_blind_in_the_first_seat_wraps_to_the_last() { + assert_eq!(button_seat(&spot(6, 3, &[5], vec![post_sb(0)])), Some(5)); // 0-based + assert_eq!(button_seat(&spot(6, 3, &[6], vec![post_sb(1)])), Some(6)); // 1-based +} + +#[test] +fn numbering_base_comes_from_every_seat_in_play() { + // Seat 0 only appears as a villain. + assert_eq!(button_seat(&spot(6, 3, &[0], vec![post_sb(1)])), Some(0)); + // Seat 6 only appears in the history. + assert_eq!( + button_seat(&spot(6, 3, &[], vec![post_sb(1), rec(6, SeenAction::Fold)])), + Some(6) + ); +} + +#[test] +fn ambiguous_numbering_with_a_wrap_is_unknown() { + // Small blind on seat 1, nobody on seat 0 or 6: button is 0 (0-based) or 6 (1-based). + assert_eq!(button_seat(&spot(6, 3, &[2], vec![post_sb(1)])), None); +} + +#[test] +fn ambiguous_numbering_without_a_wrap_is_fine() { + assert_eq!(button_seat(&spot(6, 3, &[2], vec![post_sb(4)])), Some(3)); +} + +#[test] +fn heads_up_the_small_blind_is_the_button() { + assert_eq!(button_seat(&spot(2, 0, &[1], vec![post_sb(0), post_bb(1)])), Some(0)); + assert_eq!(button_seat(&spot(2, 1, &[2], vec![post_sb(1), post_bb(2)])), Some(1)); + assert_eq!(button_seat(&spot(2, 1, &[0], vec![post_sb(1)])), Some(1)); +} + +#[test] +fn only_the_big_blind_known_puts_the_button_two_before() { + assert_eq!(button_seat(&spot(6, 0, &[], vec![post_bb(5)])), Some(3)); + assert_eq!(button_seat(&spot(6, 0, &[], vec![post_bb(1)])), Some(5)); // wraps, 0-based + assert_eq!(button_seat(&spot(6, 6, &[], vec![post_bb(1)])), Some(5)); // wraps, 1-based + assert_eq!(button_seat(&spot(9, 0, &[], vec![post_bb(2)])), Some(0)); +} + +#[test] +fn heads_up_with_only_the_big_blind_the_other_seat_is_the_button() { + assert_eq!(button_seat(&spot(2, 0, &[1], vec![post_bb(1)])), Some(0)); + assert_eq!(button_seat(&spot(2, 0, &[1], vec![post_bb(0)])), Some(1)); + assert_eq!(button_seat(&spot(2, 1, &[2], vec![post_bb(1)])), Some(2)); + assert_eq!(button_seat(&spot(2, 1, &[2], vec![post_bb(2)])), Some(1)); +} + +#[test] +fn both_blinds_that_agree_give_the_same_button() { + assert_eq!(button_seat(&spot(6, 0, &[], vec![post_sb(4), post_bb(5)])), Some(3)); +} + +#[test] +fn conflicting_blinds_trust_the_small_blind() { + // Big blind two seats after the small blind: a dead seat between them. + assert_eq!(button_seat(&spot(6, 0, &[], vec![post_sb(2), post_bb(4)])), Some(1)); +} + +#[test] +fn only_preflop_posts_count() { + let mut late = post_sb(4); + late.street = Street::Flop; + assert_eq!(button_seat(&spot(6, 0, &[], vec![late])), None); +} + +#[test] +fn the_first_post_of_each_kind_counts() { + assert_eq!(button_seat(&spot(6, 0, &[], vec![post_sb(4), post_sb(2)])), Some(3)); +} + +#[test] +fn absurd_inputs_are_none() { + assert_eq!(button_seat(&spot(1, 0, &[], vec![post_sb(0)])), None); + assert_eq!(button_seat(&spot(11, 0, &[], vec![post_sb(4)])), None); + assert_eq!(button_seat(&spot(0, 0, &[], vec![post_sb(4)])), None); + assert_eq!(button_seat(&spot(6, 0, &[], vec![post_sb(9)])), None); // seat beyond table + assert_eq!(button_seat(&spot(6, 0, &[6], vec![post_sb(4)])), None); // both seat 0 and seat 6 + assert_eq!(button_seat(&spot(6, 200, &[], vec![post_sb(4)])), None); +} + +#[test] +fn inferred_button_agrees_with_every_explicit_layout() { + // Every table size and numbering, the button anywhere: derive the blinds, then check + // the inference returns the button. The edge seats are added as villains so that the + // numbering base is always visible. + for seats in 3u8..=10 { + for base in 0u8..=1 { + for button in base..base + seats { + let sb = base + (button - base + 1) % seats; + let bb = base + (button - base + 2) % seats; + let edges = [base, base + seats - 1]; + let s = spot(seats, button, &edges, vec![post_sb(sb), post_bb(bb)]); + assert_eq!(button_seat(&s), Some(button), "seats {seats} base {base} button {button}"); + let only_bb = spot(seats, button, &edges, vec![post_bb(bb)]); + assert_eq!(button_seat(&only_bb), Some(button), "bb only, seats {seats} base {base}"); + } + } + } + for base in 0u8..=1 { + for button in base..base + 2 { + let other = if button == base { base + 1 } else { base }; + let hu = spot(2, button, &[other], vec![post_sb(button), post_bb(other)]); + assert_eq!(button_seat(&hu), Some(button)); + let only_bb = spot(2, button, &[other], vec![post_bb(other)]); + assert_eq!(button_seat(&only_bb), Some(button)); + } + } +} diff --git a/tests/position_exhaustive.rs b/tests/position_exhaustive.rs new file mode 100644 index 00000000..2c7cbc81 --- /dev/null +++ b/tests/position_exhaustive.rs @@ -0,0 +1,100 @@ +//! Every table size 2..=10, both seat numberings, button and hero at every seat. + +use pokerfreak::preflop::position::{position, Position}; + +/// Independent statement of the rule: offsets clockwise from the button. +fn expected(seats: u8, offset: u8) -> Position { + if seats == 2 { + return if offset == 0 { Position::HeadsUpButton } else { Position::BigBlind }; + } + match offset { + 0 => Position::Button, + 1 => Position::SmallBlind, + 2 => Position::BigBlind, + o if o == seats - 1 => Position::Cutoff, + o => { + // seats 3.. up to the cutoff: the first ceil(n/2) of the (n-4) are early + let early = (seats - 3) / 2; + if o - 3 < early { + Position::Early + } else { + Position::Middle + } + } + } +} + +#[test] +fn every_seat_at_every_table_size_and_numbering() { + let mut checked = 0; + for seats in 2u8..=10 { + for base in 0u8..=1 { + for button in base..base + seats { + for hero in base..base + seats { + let offset = (hero + seats - button) % seats; + assert_eq!( + position(seats, hero, Some(button)), + expected(seats, offset), + "seats {seats} base {base} button {button} hero {hero}" + ); + checked += 1; + } + } + } + } + assert_eq!(checked, 2 * (4 + 9 + 16 + 25 + 36 + 49 + 64 + 81 + 100)); +} + +#[test] +fn numbering_base_does_not_matter() { + for seats in 2u8..=10 { + for button in 0..seats { + for hero in 0..seats { + assert_eq!( + position(seats, hero, Some(button)), + position(seats, hero + 1, Some(button + 1)), + "seats {seats} button {button} hero {hero}" + ); + } + } + } +} + +#[test] +fn heads_up_button_is_the_small_blind_and_the_other_the_big_blind() { + for base in 0u8..=1 { + for button in base..base + 2 { + let other = if button == base { base + 1 } else { base }; + assert_eq!(position(2, button, Some(button)), Position::HeadsUpButton); + assert_eq!(position(2, other, Some(button)), Position::BigBlind); + } + } +} + +#[test] +fn cutoff_is_the_seat_before_the_button_and_utg_the_first_after_the_big_blind() { + for seats in 5u8..=10 { + for button in 0..seats { + let cutoff = (button + seats - 1) % seats; + let utg = (button + 3) % seats; + assert_eq!(position(seats, cutoff, Some(button)), Position::Cutoff); + assert_eq!(position(seats, utg, Some(button)), Position::Early, "seats {seats}"); + } + } +} + +#[test] +fn early_middle_split_counts_for_every_table_size() { + // (seats, early, middle): the n-4 seats between big blind and cutoff, earlier half early. + let table = [(4u8, 0usize, 0usize), (5, 1, 0), (6, 1, 1), (7, 2, 1), (8, 2, 2), (9, 3, 2), (10, 3, 3)]; + for (seats, early, middle) in table { + let positions: Vec = (0..seats).map(|h| position(seats, h, Some(0))).collect(); + let count = |p: Position| positions.iter().filter(|x| **x == p).count(); + assert_eq!(count(Position::Early), early, "seats {seats}"); + assert_eq!(count(Position::Middle), middle, "seats {seats}"); + assert_eq!(count(Position::Button), 1); + assert_eq!(count(Position::SmallBlind), 1); + assert_eq!(count(Position::BigBlind), 1); + assert_eq!(count(Position::Cutoff), 1); + } +} diff --git a/tests/position_fixture/mod.rs b/tests/position_fixture/mod.rs new file mode 100644 index 00000000..fa86e46a --- /dev/null +++ b/tests/position_fixture/mod.rs @@ -0,0 +1,45 @@ +#![allow(dead_code)] +//! Builders for button-inference tests. + +use pokerfreak::card::Card; +use pokerfreak::game::{ActionKind, ActionRecord, SeenAction, Spot, Street, Villain}; +use pokerfreak::variant::Variant; + +pub fn post_sb(seat: u8) -> ActionRecord { + rec(seat, SeenAction::PostSmallBlind) +} + +pub fn post_bb(seat: u8) -> ActionRecord { + rec(seat, SeenAction::PostBigBlind) +} + +pub fn rec(seat: u8, action: SeenAction) -> ActionRecord { + ActionRecord { street: Street::Preflop, seat, action, amount: None } +} + +/// Preflop NLHE, big blind 1, pot 1.5, 1 to call; no button, no history. +pub fn spot(seats: u8, hero_seat: u8, villain_seats: &[u8], history: Vec) -> Spot { + Spot { + variant: Variant::Nlhe, + big_blind: 1.0, + seats, + hero_seat, + button_seat: None, + hero_cards: Card::parse_list("Ah Kh").unwrap(), + board: vec![], + street: Street::Preflop, + pot: 1.5, + to_call: 1.0, + hero_stack: 100.0, + min_raise_to: Some(2.0), + max_raise_to: Some(100.0), + legal: vec![ActionKind::Fold, ActionKind::Call, ActionKind::Raise], + allowed_sizes: None, + villains: villain_seats + .iter() + .map(|s| Villain { seat: *s, stack: 100.0, folded: false, profile: None }) + .collect(), + seed: 1, + history, + } +} diff --git a/tests/range_model_fixture/mod.rs b/tests/range_model_fixture/mod.rs new file mode 100644 index 00000000..4fe6b937 --- /dev/null +++ b/tests/range_model_fixture/mod.rs @@ -0,0 +1,114 @@ +#![allow(dead_code)] +//! Builders for range-model tests. Table: 6 seats, 0-based, button on seat 3: +//! seat 3 BTN, 4 SB, 5 BB, 0 UTG (early), 1 MP (middle), 2 CO. Hero sits on seat 0. + +use pokerfreak::card::Card; +use pokerfreak::exploit::profile::Profile; +use pokerfreak::exploit::range_spec::{Continuation, RangeSpec}; +use pokerfreak::game::{ActionKind, ActionRecord, SeenAction, Spot, Street, Villain}; +use pokerfreak::variant::Variant; + +pub const HERO: u8 = 0; +pub const MIDDLE: u8 = 1; +pub const CUTOFF: u8 = 2; +pub const BUTTON: u8 = 3; +pub const SMALL_BLIND: u8 = 4; +pub const BIG_BLIND: u8 = 5; + +pub fn at(street: Street, seat: u8, action: SeenAction, amount: Option) -> ActionRecord { + ActionRecord { street, seat, action, amount } +} + +pub fn pre(seat: u8, action: SeenAction) -> ActionRecord { + at(Street::Preflop, seat, action, None) +} + +pub fn pre_amt(seat: u8, action: SeenAction, amount: f64) -> ActionRecord { + at(Street::Preflop, seat, action, Some(amount)) +} + +pub fn post(street: Street, seat: u8, action: SeenAction) -> ActionRecord { + at(street, seat, action, None) +} + +pub fn blinds() -> Vec { + vec![pre_amt(4, SeenAction::PostSmallBlind, 0.5), pre_amt(5, SeenAction::PostBigBlind, 1.0)] +} + +/// Blinds followed by `rest`. +pub fn hand(rest: Vec) -> Vec { + [blinds(), rest].concat() +} + +pub fn villain(seat: u8, profile: Option) -> Villain { + Villain { seat, stack: 100.0, folded: false, profile } +} + +pub fn profile(vpip: Option, pfr: Option, fold: Option) -> Option { + Some(Profile { vpip, pfr, fold_to_bet: fold }) +} + +pub fn vpip(value: f64) -> Option { + profile(Some(value), None, None) +} + +pub fn board_of(len: usize) -> Vec { + Card::parse_list(&"Kc 7d 2s 9h 4c"[..len * 3 - usize::from(len > 0)]).unwrap() +} + +fn street_of(len: usize) -> Street { + match len { + 0 => Street::Preflop, + 3 => Street::Flop, + 4 => Street::Turn, + _ => Street::River, + } +} + +/// A spot on the street matching `board_len` with the given history; villains: all but hero. +pub fn spot(board_len: usize, history: Vec, profile: Option) -> Spot { + Spot { + variant: Variant::Nlhe, + big_blind: 1.0, + seats: 6, + hero_seat: HERO, + button_seat: Some(3), + hero_cards: Card::parse_list("Ah Qd").unwrap(), + board: if board_len == 0 { vec![] } else { board_of(board_len) }, + street: street_of(board_len), + pot: 10.0, + to_call: 0.0, + hero_stack: 100.0, + min_raise_to: None, + max_raise_to: None, + legal: vec![ActionKind::Check, ActionKind::Raise], + allowed_sizes: None, + villains: [1u8, 2, 3, 4, 5].iter().map(|s| villain(*s, profile)).collect(), + seed: 1, + history, + } +} + +pub fn spec(spot: &Spot, seat: u8) -> RangeSpec { + let v = spot.villains.iter().find(|v| v.seat == seat).cloned().unwrap_or(villain(seat, None)); + pokerfreak::exploit::range_model::range_spec(spot, &v) +} + +pub fn width(s: &RangeSpec) -> f64 { + s.hi - s.lo +} + +pub fn well_formed(s: &RangeSpec, board_len: usize) -> bool { + let sorted = s.continues.windows(2).all(|w| w[0].board_len < w[1].board_len); + s.lo.is_finite() + && s.hi.is_finite() + && s.lo >= 0.0 + && s.hi <= 1.0 + && s.hi - s.lo >= 0.03 - 1e-12 + && sorted + && s.continues.iter().all(|c: &Continuation| (3..=5).contains(&c.board_len) && c.board_len <= board_len) +} + +pub fn continuation(s: &RangeSpec, board_len: usize) -> Option { + s.continues.iter().find(|c| c.board_len == board_len).copied() +} diff --git a/tests/range_model_postflop.rs b/tests/range_model_postflop.rs new file mode 100644 index 00000000..3922dbea --- /dev/null +++ b/tests/range_model_postflop.rs @@ -0,0 +1,281 @@ +mod range_model_fixture; + +use pokerfreak::game::SeenAction::{AllIn, Bet, Call, Check, Fold, Raise}; +use pokerfreak::game::{ActionRecord, SeenAction, Street}; +use pokerfreak::read::made::Made; +use range_model_fixture::*; + +const FLOP: Street = Street::Flop; +const TURN: Street = Street::Turn; +const RIVER: Street = Street::River; + +/// Cutoff opens, everybody else folds except the big blind: no amounts, so no size effect. +fn preflop() -> Vec { + hand(vec![pre(CUTOFF, Raise), pre(BIG_BLIND, Call)]) +} + +fn with(rest: Vec) -> Vec { + [preflop(), rest].concat() +} + +fn only(board_len: usize, rest: Vec) -> pokerfreak::exploit::range_spec::RangeSpec { + let s = spot(board_len, with(rest), None); + let r = spec(&s, CUTOFF); + assert!(well_formed(&r, board_len), "{r:?}"); + r +} + +#[test] +fn checks_and_calls_add_no_continuation() { + let r = only( + 5, + vec![ + post(FLOP, CUTOFF, Check), + post(FLOP, CUTOFF, Call), + post(TURN, CUTOFF, Check), + post(RIVER, CUTOFF, Call), + post(RIVER, CUTOFF, Fold), + ], + ); + assert!(r.continues.is_empty(), "{r:?}"); +} + +#[test] +fn flop_bet_keeps_middle_pair_and_draws() { + let c = continuation(&only(3, vec![post(FLOP, CUTOFF, Bet)]), 3).unwrap(); + assert_eq!((c.min_made, c.draws_continue), (Made::MiddlePair, true)); +} + +#[test] +fn flop_raise_keeps_top_pair_good_kicker_and_draws() { + let c = continuation(&only(3, vec![post(FLOP, CUTOFF, Raise)]), 3).unwrap(); + assert_eq!((c.min_made, c.draws_continue), (Made::TopPairGoodKicker, true)); +} + +#[test] +fn turn_bet_and_raise() { + let bet = continuation(&only(4, vec![post(TURN, CUTOFF, Bet)]), 4).unwrap(); + assert_eq!((bet.min_made, bet.draws_continue), (Made::TopPairWeakKicker, true)); + let raise = continuation(&only(4, vec![post(TURN, CUTOFF, Raise)]), 4).unwrap(); + assert_eq!((raise.min_made, raise.draws_continue), (Made::Overpair, true)); +} + +#[test] +fn river_bet_and_raise_keep_only_made_hands() { + let bet = continuation(&only(5, vec![post(RIVER, CUTOFF, Bet)]), 5).unwrap(); + assert_eq!((bet.min_made, bet.draws_continue), (Made::TopPairGoodKicker, false)); + let raise = continuation(&only(5, vec![post(RIVER, CUTOFF, Raise)]), 5).unwrap(); + assert_eq!((raise.min_made, raise.draws_continue), (Made::TwoPair, false)); +} + +#[test] +fn all_in_counts_as_a_raise() { + for (len, street) in [(3, FLOP), (4, TURN), (5, RIVER)] { + let jam = continuation(&only(len, vec![post(street, CUTOFF, AllIn)]), len).unwrap(); + let raise = continuation(&only(len, vec![post(street, CUTOFF, Raise)]), len).unwrap(); + assert_eq!(jam, raise); + } +} + +#[test] +fn later_streets_are_stricter_for_the_same_action() { + for action in [Bet, Raise, AllIn] { + let mins: Vec = [(3, FLOP), (4, TURN), (5, RIVER)] + .iter() + .map(|(len, street)| { + continuation(&only(*len, vec![post(*street, CUTOFF, action)]), *len).unwrap().min_made + }) + .collect(); + assert!(mins[0] <= mins[1] && mins[1] <= mins[2] && mins[0] < mins[2], "{action:?} {mins:?}"); + } +} + +#[test] +fn a_raise_is_stricter_than_a_bet_on_every_street() { + for (len, street) in [(3, FLOP), (4, TURN), (5, RIVER)] { + let bet = continuation(&only(len, vec![post(street, CUTOFF, Bet)]), len).unwrap(); + let raise = continuation(&only(len, vec![post(street, CUTOFF, Raise)]), len).unwrap(); + assert!(raise.min_made > bet.min_made, "street {street:?}"); + } +} + +#[test] +fn every_street_the_villain_bet_gets_an_entry_sorted_by_board_length() { + let r = only( + 5, + vec![ + post(RIVER, CUTOFF, Bet), + post(FLOP, CUTOFF, Bet), + post(TURN, CUTOFF, Bet), + ], + ); + let lens: Vec = r.continues.iter().map(|c| c.board_len).collect(); + assert_eq!(lens, vec![3, 4, 5]); +} + +#[test] +fn streets_that_were_not_dealt_yet_are_dropped() { + let r = only(3, vec![post(FLOP, CUTOFF, Bet), post(TURN, CUTOFF, Bet), post(RIVER, CUTOFF, Bet)]); + assert_eq!(r.continues.len(), 1); + assert_eq!(r.continues[0].board_len, 3); +} + +#[test] +fn bet_followed_by_a_raise_on_the_same_street_counts_as_the_raise() { + let r = only(3, vec![post(FLOP, CUTOFF, Bet), post(FLOP, CUTOFF, Raise)]); + assert_eq!(r.continues.len(), 1); + assert_eq!(r.continues[0].min_made, Made::TopPairGoodKicker); +} + +#[test] +fn other_players_aggression_does_not_narrow_this_villain() { + let r = only(3, vec![post(FLOP, BIG_BLIND, Bet), post(FLOP, CUTOFF, Call)]); + assert!(r.continues.is_empty()); +} + +#[test] +fn preflop_spot_has_no_continuations_even_with_later_records() { + let s = spot(0, with(vec![post(FLOP, CUTOFF, Bet)]), None); + assert!(spec(&s, CUTOFF).continues.is_empty()); +} + +// --- bet size relative to the pot ------------------------------------------------- + +/// Posts 0.5 + 1, cutoff raises to 3, small blind folds, big blind calls: pot 6.5. +fn sized_preflop() -> Vec { + hand(vec![ + pre_amt(CUTOFF, Raise, 3.0), + pre(SMALL_BLIND, Fold), + pre_amt(BIG_BLIND, Call, 3.0), + ]) +} + +fn bet_of(amount: f64, action: SeenAction) -> Made { + let history = [sized_preflop(), vec![at(FLOP, CUTOFF, action, Some(amount))]].concat(); + let s = spot(3, history, None); + continuation(&spec(&s, CUTOFF), 3).unwrap().min_made +} + +#[test] +fn bigger_bets_are_stricter_and_smaller_ones_looser() { + let small = bet_of(2.0, Bet); // 0.31 pot + let normal = bet_of(4.5, Bet); // 0.69 pot + let pot = bet_of(6.5, Bet); // 1.0 pot + let overbet = bet_of(13.0, Bet); // 2.0 pots + assert_eq!(small, Made::BottomPair); + assert_eq!(normal, Made::MiddlePair); + assert_eq!(pot, Made::TopPairWeakKicker); + assert_eq!(overbet, Made::TopPairGoodKicker); +} + +#[test] +fn size_effect_is_monotone() { + for action in [Bet, Raise] { + let mins: Vec = [0.5, 1.0, 2.0, 3.25, 4.5, 6.5, 9.0, 13.0, 30.0, 300.0] + .iter() + .map(|a| bet_of(*a, action)) + .collect(); + assert!(mins.windows(2).all(|w| w[0] <= w[1]), "{action:?} {mins:?}"); + } +} + +#[test] +fn unknown_bet_amount_or_unknown_pot_means_no_size_effect() { + let base = continuation(&only(3, vec![post(FLOP, CUTOFF, Bet)]), 3).unwrap(); + assert_eq!(base.min_made, Made::MiddlePair); + // A preflop call without an amount makes the pot unknowable. + let history = hand(vec![ + pre_amt(CUTOFF, Raise, 3.0), + pre(BIG_BLIND, Call), + at(FLOP, CUTOFF, Bet, Some(13.0)), + ]); + let s = spot(3, history, None); + assert_eq!(continuation(&spec(&s, CUTOFF), 3).unwrap().min_made, Made::MiddlePair); +} + +#[test] +fn later_streets_use_the_pot_built_so_far() { + // Flop: bet 6.5 called (pot 6.5 -> 19.5). Turn bet 6.5 is a third of that pot: smaller. + let history = [ + sized_preflop(), + vec![ + at(FLOP, CUTOFF, Bet, Some(6.5)), + at(FLOP, BIG_BLIND, Call, Some(6.5)), + at(TURN, CUTOFF, Bet, Some(6.5)), + ], + ] + .concat(); + let s = spot(4, history, None); + let r = spec(&s, CUTOFF); + assert_eq!(continuation(&r, 3).unwrap().min_made, Made::TopPairWeakKicker); + assert_eq!(continuation(&r, 4).unwrap().min_made, Made::MiddlePair); +} + +// --- calling a big bet ----------------------------------------------------------- + +fn calling(bet: Option, call_street: Street, len: usize) -> pokerfreak::exploit::range_spec::RangeSpec { + let history = [ + sized_preflop(), + vec![ + at(call_street, BIG_BLIND, Bet, bet), + at(call_street, CUTOFF, Call, bet), + ], + ] + .concat(); + let s = spot(len, history, None); + spec(&s, CUTOFF) +} + +#[test] +fn calling_a_big_bet_leaves_a_mild_floor() { + let r = calling(Some(6.5), FLOP, 3); + let c = continuation(&r, 3).expect("floor"); + assert_eq!((c.min_made, c.draws_continue), (Made::BottomPair, true)); +} + +#[test] +fn calling_a_big_river_bet_wants_a_made_hand() { + let history = [ + sized_preflop(), + vec![ + at(FLOP, BIG_BLIND, Check, None), + at(FLOP, CUTOFF, Check, None), + at(RIVER, BIG_BLIND, Bet, Some(6.5)), + at(RIVER, CUTOFF, Call, Some(6.5)), + ], + ] + .concat(); + let s = spot(5, history, None); + let c = continuation(&spec(&s, CUTOFF), 5).expect("floor"); + assert_eq!((c.min_made, c.draws_continue), (Made::MiddlePair, false)); +} + +#[test] +fn calling_a_small_or_unsized_bet_adds_nothing() { + assert!(calling(Some(2.0), FLOP, 3).continues.is_empty()); + assert!(calling(None, FLOP, 3).continues.is_empty()); +} + +#[test] +fn the_call_floor_is_always_looser_than_the_bet_floor() { + let floor = continuation(&calling(Some(6.5), FLOP, 3), 3).unwrap().min_made; + let bet = continuation(&only(3, vec![post(FLOP, CUTOFF, Bet)]), 3).unwrap().min_made; + assert!(floor < bet); +} + +#[test] +fn bet_and_call_on_one_street_keep_the_stricter_floor() { + let history = [ + sized_preflop(), + vec![ + at(FLOP, CUTOFF, Bet, Some(6.5)), + at(FLOP, BIG_BLIND, Raise, Some(20.0)), + at(FLOP, CUTOFF, Call, Some(20.0)), + ], + ] + .concat(); + let s = spot(3, history, None); + let r = spec(&s, CUTOFF); + assert_eq!(r.continues.len(), 1); + assert_eq!(r.continues[0].min_made, Made::TopPairWeakKicker); +} diff --git a/tests/range_model_preflop.rs b/tests/range_model_preflop.rs new file mode 100644 index 00000000..f9990b94 --- /dev/null +++ b/tests/range_model_preflop.rs @@ -0,0 +1,176 @@ +mod range_model_fixture; + +use pokerfreak::exploit::range_guess::top_fraction; +use pokerfreak::exploit::range_spec::RangeSpec; +use pokerfreak::game::SeenAction::{AllIn, Call, Check, Raise}; +use pokerfreak::game::Spot; +use range_model_fixture::*; + +fn near(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-9 +} + +fn band(history: Vec, seat: u8) -> (f64, f64) { + let s = spot(0, hand(history), None); + let r = spec(&s, seat); + assert!(well_formed(&r, 0), "{r:?}"); + assert!(r.continues.is_empty()); + (r.lo, r.hi) +} + +#[test] +fn opener_band_is_the_opening_chart_of_its_position() { + let (lo, hi) = band(vec![pre(MIDDLE, Raise)], MIDDLE); + assert!(near(lo, 0.0) && near(hi, 0.19), "{lo} {hi}"); + let (lo, hi) = band(vec![pre(CUTOFF, Raise)], CUTOFF); + assert!(near(lo, 0.0) && near(hi, 0.27), "{lo} {hi}"); + let (_, hi) = band(vec![pre(BUTTON, Raise)], BUTTON); + assert!(near(hi, 0.42)); + let (_, hi) = band(vec![pre(SMALL_BLIND, Raise)], SMALL_BLIND); + assert!(near(hi, 0.38)); +} + +#[test] +fn later_positions_open_wider() { + let hi = |seat| band(vec![pre(seat, Raise)], seat).1; + assert!(hi(MIDDLE) < hi(CUTOFF) && hi(CUTOFF) < hi(BUTTON)); +} + +#[test] +fn opener_with_an_unknown_position_is_charted_as_middle() { + let mut s = spot(0, vec![pre(MIDDLE, Raise)], None); + s.button_seat = None; + let r = spec(&s, MIDDLE); + assert!(near(r.hi, 0.19), "{r:?}"); +} + +#[test] +fn three_bettor_has_a_narrow_top_band() { + let (lo, hi) = band(vec![pre(MIDDLE, Raise), pre(BUTTON, Raise)], BUTTON); + assert!(near(lo, 0.0) && near(hi, 0.09), "{lo} {hi}"); + let (_, open_hi) = band(vec![pre(BUTTON, Raise)], BUTTON); + assert!(hi < open_hi / 3.0); +} + +#[test] +fn four_bettor_is_narrower_than_a_three_bettor() { + let history = vec![pre(MIDDLE, Raise), pre(BUTTON, Raise), pre(MIDDLE, Raise)]; + let (lo, hi) = band(history, MIDDLE); + assert!(near(lo, 0.0) && near(hi, 0.03), "{lo} {hi}"); +} + +#[test] +fn cold_caller_is_condensed_without_the_very_top_and_the_bottom() { + let (lo, hi) = band(vec![pre(MIDDLE, Raise), pre(BUTTON, Call)], BUTTON); + assert!(near(lo, 0.045) && near(hi, 0.24), "{lo} {hi}"); + let (_, open_hi) = band(vec![pre(BUTTON, Raise)], BUTTON); + assert!(lo > 0.0 && hi < open_hi); +} + +#[test] +fn cold_caller_from_early_position_is_tighter_than_from_the_button() { + let early = band(vec![pre(CUTOFF, Raise), pre(MIDDLE, Call)], MIDDLE); + let late = band(vec![pre(MIDDLE, Raise), pre(BUTTON, Call)], BUTTON); + assert!(early.1 < late.1); +} + +#[test] +fn opener_who_calls_a_three_bet_is_capped() { + let (lo, hi) = band(vec![pre(MIDDLE, Raise), pre(BUTTON, Raise), pre(MIDDLE, Call)], MIDDLE); + assert!(near(lo, 0.015) && near(hi, 0.05), "{lo} {hi}"); +} + +#[test] +fn caller_of_a_three_bet_is_narrower_than_a_caller_of_an_open() { + let vs_open = band(vec![pre(MIDDLE, Raise), pre(BUTTON, Call)], BUTTON); + let vs_three = band(vec![pre(MIDDLE, Raise), pre(CUTOFF, Raise), pre(BUTTON, Call)], BUTTON); + assert!(vs_three.1 < vs_open.1); +} + +#[test] +fn limper_is_capped_in_the_middle() { + let (lo, hi) = band(vec![pre(MIDDLE, Call)], MIDDLE); + assert!(lo > 0.05 && hi > lo + 0.1, "{lo} {hi}"); + let (_, open_hi) = band(vec![pre(MIDDLE, Raise)], MIDDLE); + assert!(hi > open_hi, "a limping range is wider than the opening range"); +} + +#[test] +fn small_blind_completing_is_wide_without_the_raising_hands() { + let (lo, hi) = band(vec![pre(MIDDLE, Call), pre(SMALL_BLIND, Call)], SMALL_BLIND); + assert!(lo > 0.05 && hi >= 0.7, "{lo} {hi}"); +} + +#[test] +fn small_blind_that_only_posted_and_saw_no_raise_counts_as_completing() { + let implied = band(vec![pre(MIDDLE, Call)], SMALL_BLIND); + let explicit = band(vec![pre(MIDDLE, Call), pre(SMALL_BLIND, Call)], SMALL_BLIND); + assert_eq!(implied, explicit); +} + +#[test] +fn big_blind_check_is_wide_minus_the_strongest_raising_hands() { + let (lo, hi) = band(vec![pre(MIDDLE, Call), pre(BIG_BLIND, Check)], BIG_BLIND); + assert!(lo > 0.05 && near(hi, 1.0), "{lo} {hi}"); +} + +#[test] +fn big_blind_with_no_action_after_limps_counts_as_checking() { + let implied = band(vec![pre(MIDDLE, Call)], BIG_BLIND); + let explicit = band(vec![pre(MIDDLE, Call), pre(BIG_BLIND, Check)], BIG_BLIND); + assert_eq!(implied, explicit); +} + +#[test] +fn big_blind_that_stayed_in_against_a_raise_is_a_defender() { + let (lo, hi) = band(vec![pre(BUTTON, Raise)], BIG_BLIND); + assert!(near(lo, 0.04) && near(hi, 0.35), "{lo} {hi}"); + let explicit = band(vec![pre(BUTTON, Raise), pre(BIG_BLIND, Call)], BIG_BLIND); + assert_eq!((lo, hi), explicit); +} + +#[test] +fn preflop_all_in_is_a_narrow_top_band() { + let (lo, hi) = band(vec![pre(BUTTON, AllIn)], BUTTON); + assert!(near(lo, 0.0) && near(hi, 0.15), "{lo} {hi}"); + let (lo, hi) = band(vec![pre(MIDDLE, Raise), pre(BUTTON, AllIn)], BUTTON); + assert!(near(lo, 0.0) && near(hi, 0.06), "{lo} {hi}"); +} + +#[test] +fn no_records_for_this_villain_means_the_old_behaviour() { + let s = spot(3, hand(vec![pre(MIDDLE, Raise)]), None); + let v = s.villains.iter().find(|v| v.seat == BUTTON).unwrap(); + assert_eq!(pokerfreak::exploit::range_model::range_spec(&s, v), RangeSpec::top(top_fraction(&s, v))); +} + +#[test] +fn empty_history_is_exactly_the_old_behaviour_for_every_villain() { + for board in [0usize, 3, 4, 5] { + for p in [None, vpip(0.5), vpip(0.1), profile(Some(0.3), Some(0.2), Some(0.4))] { + let s = spot(board, vec![], p); + for v in &s.villains { + assert_eq!( + pokerfreak::exploit::range_model::range_spec(&s, v), + RangeSpec::top(top_fraction(&s, v)) + ); + } + } + } +} + +#[test] +fn only_postflop_records_use_the_plain_vpip_band() { + let s = spot(3, vec![post(pokerfreak::game::Street::Flop, BUTTON, Check)], None); + let r = spec(&s, BUTTON); + assert!(near(r.lo, 0.0) && near(r.hi, 0.30), "{r:?}"); + let s = spot(3, vec![post(pokerfreak::game::Street::Flop, BUTTON, Check)], vpip(0.5)); + assert!(near(spec(&s, BUTTON).hi, 0.5)); +} + +#[test] +fn other_seats_actions_do_not_change_this_villains_band() { + let a = band(vec![pre(MIDDLE, Raise), pre(BUTTON, Call)], BUTTON); + let b: Spot = spot(0, hand(vec![pre(MIDDLE, Raise), pre(BUTTON, Call)]), None); + assert_eq!(spec(&b, BUTTON).hi, a.1); +} diff --git a/tests/range_model_profile.rs b/tests/range_model_profile.rs new file mode 100644 index 00000000..86178960 --- /dev/null +++ b/tests/range_model_profile.rs @@ -0,0 +1,118 @@ +mod range_model_fixture; + +use pokerfreak::exploit::profile::Profile; +use pokerfreak::game::SeenAction::{Bet, Call, Raise}; +use pokerfreak::game::Street; +use range_model_fixture::*; + +fn preflop_width(history: Vec, seat: u8, p: Option) -> f64 { + let s = spot(0, hand(history), p); + let r = spec(&s, seat); + assert!(well_formed(&r, 0), "{r:?}"); + width(&r) +} + +const LOOSE_TO_TIGHT_VPIP: [f64; 6] = [0.9, 0.6, 0.45, 0.30, 0.18, 0.06]; + +#[test] +fn looser_vpip_widens_a_calling_band() { + let widths: Vec = LOOSE_TO_TIGHT_VPIP + .iter() + .map(|v| preflop_width(vec![pre(MIDDLE, Raise), pre(BUTTON, Call)], BUTTON, vpip(*v))) + .collect(); + assert!(widths.windows(2).all(|w| w[0] >= w[1]), "{widths:?}"); + assert!(widths[0] > widths[5] + 0.05, "{widths:?}"); +} + +#[test] +fn looser_vpip_widens_a_limping_band() { + let widths: Vec = LOOSE_TO_TIGHT_VPIP + .iter() + .map(|v| preflop_width(vec![pre(CUTOFF, Call)], CUTOFF, vpip(*v))) + .collect(); + assert!(widths.windows(2).all(|w| w[0] >= w[1]), "{widths:?}"); + assert!(widths[0] > widths[5], "{widths:?}"); +} + +#[test] +fn higher_pfr_widens_an_opening_band() { + let widths: Vec = [0.40, 0.28, 0.18, 0.10, 0.04] + .iter() + .map(|f| { + preflop_width(vec![pre(CUTOFF, Raise)], CUTOFF, profile(Some(0.3), Some(*f), None)) + }) + .collect(); + assert!(widths.windows(2).all(|w| w[0] >= w[1]), "{widths:?}"); + assert!(widths[0] > widths[4], "{widths:?}"); +} + +#[test] +fn opening_without_pfr_falls_back_on_vpip_at_half_strength() { + let wide = preflop_width(vec![pre(BUTTON, Raise)], BUTTON, vpip(0.6)); + let none = preflop_width(vec![pre(BUTTON, Raise)], BUTTON, None); + let tight = preflop_width(vec![pre(BUTTON, Raise)], BUTTON, vpip(0.1)); + assert!(wide > none && none > tight); +} + +#[test] +fn a_profile_without_numbers_is_neutral() { + for (seat, history) in [ + (CUTOFF, vec![pre(CUTOFF, Raise)]), + (BUTTON, vec![pre(MIDDLE, Raise), pre(BUTTON, Call)]), + ] { + let plain = preflop_width(history.clone(), seat, None); + let empty = preflop_width(history.clone(), seat, profile(None, None, None)); + let nan = preflop_width(history, seat, profile(Some(f64::NAN), Some(f64::NAN), Some(f64::NAN))); + assert_eq!(plain, empty); + assert_eq!(plain, nan); + } +} + +#[test] +fn extreme_numbers_stay_well_formed() { + for v in [-3.0, 0.0, 1.0, 7.5, f64::INFINITY, f64::NEG_INFINITY] { + for (seat, history) in [ + (CUTOFF, vec![pre(CUTOFF, Raise)]), + (BUTTON, vec![pre(MIDDLE, Raise), pre(BUTTON, Call)]), + (BUTTON, vec![pre(MIDDLE, Raise), pre(BUTTON, Raise), pre(MIDDLE, Raise)]), + ] { + preflop_width(history, seat, profile(Some(v), Some(v), Some(v))); + } + } +} + +fn flop_bet_min(p: Option) -> pokerfreak::read::made::Made { + let history = hand(vec![ + pre(CUTOFF, Raise), + post(Street::Flop, CUTOFF, Bet), + ]); + let s = spot(3, history, p); + continuation(&spec(&s, CUTOFF), 3).expect("bet continuation").min_made +} + +#[test] +fn looser_player_never_gets_a_higher_min_made() { + let mins: Vec<_> = LOOSE_TO_TIGHT_VPIP.iter().map(|v| flop_bet_min(vpip(*v))).collect(); + assert!(mins.windows(2).all(|w| w[0] <= w[1]), "{mins:?}"); + assert!(mins[0] < mins[5], "{mins:?}"); +} + +#[test] +fn calling_station_loosens_and_nit_tightens_the_postflop_floor() { + let regular = flop_bet_min(profile(Some(0.25), Some(0.15), Some(0.5))); + let station = flop_bet_min(profile(Some(0.45), Some(0.08), Some(0.2))); + let nit = flop_bet_min(profile(Some(0.10), Some(0.08), Some(0.7))); + assert!(station < regular && regular < nit, "{station:?} {regular:?} {nit:?}"); +} + +#[test] +fn low_fold_to_bet_alone_loosens() { + let sticky = flop_bet_min(profile(None, None, Some(0.1))); + let plain = flop_bet_min(None); + assert!(sticky < plain); +} + +#[test] +fn no_profile_matches_the_regular_floor() { + assert_eq!(flop_bet_min(None), flop_bet_min(profile(Some(0.25), Some(0.15), Some(0.5)))); +} diff --git a/tests/range_model_robust.rs b/tests/range_model_robust.rs new file mode 100644 index 00000000..8690056c --- /dev/null +++ b/tests/range_model_robust.rs @@ -0,0 +1,156 @@ +mod range_model_fixture; + +use pokerfreak::exploit::profile::Profile; +use pokerfreak::exploit::range_model::range_spec; +use pokerfreak::game::{ActionRecord, SeenAction, Street, Villain}; +use pokerfreak::rng::Rng; +use range_model_fixture::*; + +const FLOP: Street = Street::Flop; + +#[test] +fn unknown_seats_are_ignored() { + let s = spot( + 3, + hand(vec![pre(99, SeenAction::Raise), post(FLOP, 77, SeenAction::Bet)]), + None, + ); + for seat in [1u8, 2, 3, 99, 200] { + assert!(well_formed(&spec(&s, seat), 3)); + } +} + +#[test] +fn actions_out_of_order_stay_well_formed() { + let history = vec![ + post(FLOP, CUTOFF, SeenAction::Bet), + pre(CUTOFF, SeenAction::Raise), + post(Street::River, CUTOFF, SeenAction::Raise), + pre(CUTOFF, SeenAction::Fold), + pre(CUTOFF, SeenAction::PostBigBlind), + post(Street::Turn, CUTOFF, SeenAction::Call), + pre(CUTOFF, SeenAction::Check), + ]; + for len in [0usize, 3, 4, 5] { + let s = spot(len, history.clone(), None); + assert!(well_formed(&spec(&s, CUTOFF), len), "board {len}"); + } +} + +#[test] +fn board_and_street_that_disagree_stay_well_formed() { + let mut s = spot(3, hand(vec![post(FLOP, CUTOFF, SeenAction::Bet)]), None); + s.board.clear(); // flop street, no board cards + let r = spec(&s, CUTOFF); + assert!(well_formed(&r, 0)); + assert!(r.continues.is_empty()); +} + +#[test] +fn hero_and_duplicate_blinds_are_harmless() { + let history = vec![ + pre(HERO, SeenAction::PostBigBlind), + pre(HERO, SeenAction::PostSmallBlind), + pre(BIG_BLIND, SeenAction::PostBigBlind), + pre(BIG_BLIND, SeenAction::PostBigBlind), + ]; + let s = spot(0, history, None); + for seat in 0u8..8 { + assert!(well_formed(&spec(&s, seat), 0)); + } +} + +#[test] +fn nonsense_amounts_and_table_sizes_stay_well_formed() { + for amount in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -5.0, 0.0, 1e300] { + for seats in [0u8, 1, 2, 11, 255] { + let history = vec![ + at(Street::Preflop, CUTOFF, SeenAction::PostBigBlind, Some(amount)), + at(Street::Preflop, MIDDLE, SeenAction::Raise, Some(amount)), + at(Street::Preflop, CUTOFF, SeenAction::Call, Some(amount)), + at(FLOP, CUTOFF, SeenAction::Bet, Some(amount)), + at(FLOP, MIDDLE, SeenAction::Raise, Some(amount)), + at(FLOP, CUTOFF, SeenAction::Call, Some(amount)), + ]; + let mut s = spot(3, history, None); + s.seats = seats; + s.big_blind = amount; + s.pot = amount; + for seat in [MIDDLE, CUTOFF] { + assert!(well_formed(&spec(&s, seat), 3), "amount {amount} seats {seats}"); + } + } + } +} + +fn pick(rng: Rng, items: &[T]) -> (T, Rng) { + let (i, rng) = rng.below(items.len() as u64); + (items[i as usize], rng) +} + +fn random_record(rng: Rng) -> (ActionRecord, Rng) { + let (street, rng) = pick(rng, &Street::ALL); + let (seat, rng) = rng.below(12); + let (action, rng) = pick(rng, &SeenAction::ALL); + let (present, rng) = rng.below(4); + let (unit, rng) = rng.unit(); + let (odd, rng) = rng.below(20); + let amount = match (present, odd) { + (0, _) => None, + (_, 0) => Some(f64::NAN), + (_, 1) => Some(-unit), + _ => Some(unit * 60.0), + }; + (ActionRecord { street, seat: seat as u8, action, amount }, rng) +} + +fn random_frequency(rng: Rng) -> (Option, Rng) { + let (kind, rng) = rng.below(8); + let (unit, rng) = rng.unit(); + let value = match kind { + 0 | 1 => None, + 2 => Some(f64::NAN), + 3 => Some(unit * 3.0 - 1.0), + _ => Some(unit), + }; + (value, rng) +} + +#[test] +fn property_random_histories_always_give_a_well_formed_spec() { + let mut rng = Rng::seeded(0xBADC0FFEE); + for case in 0..4000 { + let (len, r) = rng.below(12); + rng = r; + let mut history = Vec::new(); + for _ in 0..len { + let (rec, r) = random_record(rng); + rng = r; + history.push(rec); + } + let (board, r) = pick(rng, &[0usize, 3, 4, 5]); + rng = r; + let (vpip, r) = random_frequency(rng); + let (pfr, r) = random_frequency(r); + let (fold, r) = random_frequency(r); + rng = r; + let (seats, r) = rng.below(13); + rng = r; + let (button, r) = rng.below(14); + rng = r; + let (seat, r) = rng.below(12); + rng = r; + let mut s = spot(board, history, Some(Profile { vpip, pfr, fold_to_bet: fold })); + s.seats = seats as u8; + s.button_seat = if button == 13 { None } else { Some(button as u8) }; + let v = Villain { seat: seat as u8, stack: 50.0, folded: false, profile: s.villains[0].profile }; + let r = range_spec(&s, &v); + assert!(well_formed(&r, board), "case {case}: {r:?} for {s:?}"); + } +} + +#[test] +fn property_spec_is_deterministic() { + let s = spot(4, hand(vec![pre(CUTOFF, SeenAction::Raise), post(Street::Turn, CUTOFF, SeenAction::Bet)]), None); + assert_eq!(spec(&s, CUTOFF), spec(&s, CUTOFF)); +}