From ec800a1672d3d56174b5bc69136cdefd1cecfe4c Mon Sep 17 00:00:00 2001 From: Marc Mintel Date: Wed, 28 Oct 2026 12:00:21 +0100 Subject: [PATCH] Preflop charts and exploitation layer Hand percentiles (169-class equity ranking, Omaha-5 structural score with empirical CDF), position/situation inference, position x situation charts, all-in-or-fold charts, pot-odds all-in calls, advise(); exploit style classification, threshold adjustment and villain range guess. Co-Authored-By: Claude Opus 5.5 --- src/exploit/adjust.rs | 54 ++++- src/exploit/fold_equity_scale.rs | 13 + src/exploit/mod.rs | 4 + src/exploit/range_guess.rs | 23 +- src/exploit/range_narrowing.rs | 44 ++++ src/exploit/style.rs | 62 +++++ src/exploit/style_shift.rs | 51 ++++ src/preflop/advise.rs | 75 +++++- src/preflop/allin_call_cutoff.rs | 20 ++ src/preflop/certainty.rs | 12 + src/preflop/chart_decision.rs | 18 ++ src/preflop/chart_row.rs | 33 +++ src/preflop/effective_stack.rs | 28 +++ src/preflop/full_chart.rs | 81 +++++++ src/preflop/hand_percentile.rs | 12 +- src/preflop/holdem_percentile.rs | 68 ++++++ src/preflop/holdem_ranking.rs | 22 ++ src/preflop/mod.rs | 19 ++ src/preflop/plo5_pair_bonus.rs | 19 ++ src/preflop/plo5_percentile.rs | 14 ++ src/preflop/plo5_rundown.rs | 43 ++++ src/preflop/plo5_score.rs | 41 ++++ src/preflop/plo5_score_table.rs | 32 +++ src/preflop/plo5_suits.rs | 18 ++ src/preflop/position.rs | 72 ++++++ src/preflop/push_chart.rs | 55 +++++ src/preflop/reason.rs | 26 ++ src/preflop/situation.rs | 84 +++++++ src/preflop/width_factor.rs | 19 ++ tests/exploit_adjust.rs | 141 +++++++++++ tests/exploit_range_guess.rs | 162 +++++++++++++ tests/exploit_style.rs | 70 ++++++ tests/preflop_advise.rs | 397 +++++++++++++++++++++++++++++++ tests/preflop_percentile.rs | 111 +++++++++ tests/preflop_plo5.rs | 106 +++++++++ tests/preflop_position.rs | 95 ++++++++ tests/preflop_situation.rs | 59 +++++ 37 files changed, 2194 insertions(+), 9 deletions(-) create mode 100644 src/exploit/fold_equity_scale.rs create mode 100644 src/exploit/range_narrowing.rs create mode 100644 src/exploit/style.rs create mode 100644 src/exploit/style_shift.rs create mode 100644 src/preflop/allin_call_cutoff.rs create mode 100644 src/preflop/certainty.rs create mode 100644 src/preflop/chart_decision.rs create mode 100644 src/preflop/chart_row.rs create mode 100644 src/preflop/effective_stack.rs create mode 100644 src/preflop/full_chart.rs create mode 100644 src/preflop/holdem_percentile.rs create mode 100644 src/preflop/holdem_ranking.rs create mode 100644 src/preflop/plo5_pair_bonus.rs create mode 100644 src/preflop/plo5_percentile.rs create mode 100644 src/preflop/plo5_rundown.rs create mode 100644 src/preflop/plo5_score.rs create mode 100644 src/preflop/plo5_score_table.rs create mode 100644 src/preflop/plo5_suits.rs create mode 100644 src/preflop/position.rs create mode 100644 src/preflop/push_chart.rs create mode 100644 src/preflop/reason.rs create mode 100644 src/preflop/situation.rs create mode 100644 src/preflop/width_factor.rs create mode 100644 tests/exploit_adjust.rs create mode 100644 tests/exploit_range_guess.rs create mode 100644 tests/exploit_style.rs create mode 100644 tests/preflop_advise.rs create mode 100644 tests/preflop_percentile.rs create mode 100644 tests/preflop_plo5.rs create mode 100644 tests/preflop_position.rs create mode 100644 tests/preflop_situation.rs diff --git a/src/exploit/adjust.rs b/src/exploit/adjust.rs index b8950e10..ae555efd 100644 --- a/src/exploit/adjust.rs +++ b/src/exploit/adjust.rs @@ -1,8 +1,58 @@ +use super::fold_equity_scale::{fold_equity_scale, MAX_SCALE, MIN_SCALE}; use super::profile::Profile; +use super::style::classify; +use super::style_shift::shift_for; use super::thresholds::Thresholds; +/// Output ranges: whatever the inputs, the engine never sees thresholds outside these. +const CALL_MARGIN: (f64, f64) = (0.0, 0.15); +const VALUE_RAISE: (f64, f64) = (0.52, 0.85); +const ABSTAIN_BAND: (f64, f64) = (0.0, 0.05); +const RANGE_WIDTH: (f64, f64) = (0.6, 1.4); + +fn bounded(x: f64, (low, high): (f64, f64)) -> f64 { + if x.is_nan() { + low + } else { + x.clamp(low, high) + } +} + +/// `base` as seen against one profile; `None` when the profile says nothing. +fn against(base: Thresholds, profile: &Profile) -> Option { + shift_for(classify(profile)).map(|shift| Thresholds { + call_margin: bounded(base.call_margin + shift.call_margin, CALL_MARGIN), + value_raise: bounded(base.value_raise + shift.value_raise, VALUE_RAISE), + abstain_band: bounded(base.abstain_band, ABSTAIN_BAND), + fold_equity_scale: (base.fold_equity_scale + * fold_equity_scale(profile.fold_to_bet, shift.fold_equity_default)) + .clamp(MIN_SCALE, MAX_SCALE), + range_width_scale: bounded(base.range_width_scale * shift.range_width, RANGE_WIDTH), + }) +} + +/// Conservative merge of two opponents: keep the harder-to-continue value of each +/// threshold (higher margins, lower fold equity, narrower ranges). +fn conservative(a: Thresholds, b: Thresholds) -> Thresholds { + Thresholds { + call_margin: a.call_margin.max(b.call_margin), + value_raise: a.value_raise.max(b.value_raise), + abstain_band: a.abstain_band.max(b.abstain_band), + fold_equity_scale: a.fold_equity_scale.min(b.fold_equity_scale), + range_width_scale: a.range_width_scale.min(b.range_width_scale), + } +} + /// Shift thresholds for the given live opponents' profiles. No profiles → `base` unchanged. +/// +/// Each profile is classified (`style::classify`) and moves `base` by its style +/// (`style_shift`); foldToBet, when given, sets `fold_equity_scale` continuously. +/// Profiles with no usable numbers are ignored; with several informative ones the +/// results are merged conservatively. Outputs are clamped to sane ranges. pub fn adjust(base: Thresholds, profiles: &[Profile]) -> Thresholds { - let _ = (base, profiles); - todo!("exploit::adjust") + profiles + .iter() + .filter_map(|p| against(base, p)) + .reduce(conservative) + .unwrap_or(base) } diff --git a/src/exploit/fold_equity_scale.rs b/src/exploit/fold_equity_scale.rs new file mode 100644 index 00000000..919d558d --- /dev/null +++ b/src/exploit/fold_equity_scale.rs @@ -0,0 +1,13 @@ +//! Fold-equity multiplier from an opponent's foldToBet. + +pub const MIN_SCALE: f64 = 0.3; +pub const MAX_SCALE: f64 = 1.6; + +/// `0.35 + 1.3 * foldToBet` clamped to `[0.3, 1.6]` (a 50 % folder is neutral, 1.0). +/// Continuous and increasing in `fold_to_bet`; without a figure, `fallback`. +pub fn fold_equity_scale(fold_to_bet: Option, fallback: f64) -> f64 { + fold_to_bet + .filter(|b| !b.is_nan()) + .map_or(fallback, |b| 0.35 + 1.3 * b.clamp(0.0, 1.0)) + .clamp(MIN_SCALE, MAX_SCALE) +} diff --git a/src/exploit/mod.rs b/src/exploit/mod.rs index 38ca4eeb..4fb7d847 100644 --- a/src/exploit/mod.rs +++ b/src/exploit/mod.rs @@ -1,6 +1,10 @@ //! Exploitation layer: reads opponent profiles, moves thresholds and range guesses. pub mod adjust; +pub mod fold_equity_scale; pub mod profile; pub mod range_guess; +pub mod range_narrowing; +pub mod style; +pub mod style_shift; pub mod thresholds; diff --git a/src/exploit/range_guess.rs b/src/exploit/range_guess.rs index f39af6d1..fe44cb92 100644 --- a/src/exploit/range_guess.rs +++ b/src/exploit/range_guess.rs @@ -1,8 +1,27 @@ +use super::range_narrowing::{bet_factor, multiway_factor, stickiness_factor, street_factor}; use crate::game::{Spot, Villain}; +/// Baseline when the villain has no vpip figure (typical full-ring/six-max regular). +pub const DEFAULT_VPIP: f64 = 0.30; +const MIN_FRACTION: f64 = 0.05; + /// Estimated fraction of starting hands (best first) this villain still holds here, /// in `(0, 1]`. Used as `VillainRange::Top` for the equity estimate. +/// +/// `vpip` (default 0.30) x street (1, .8, .62, .5) x bet size (`to_call / pot`, narrower) +/// x multiway-passive bonus x stickiness (foldToBet), clamped to `[0.05, 1]`. pub fn top_fraction(spot: &Spot, villain: &Villain) -> f64 { - let _ = (spot, villain); - todo!("exploit::range_guess") + let profile = villain.profile.unwrap_or_default(); + let vpip = profile + .vpip + .filter(|v| !v.is_nan()) + .map_or(DEFAULT_VPIP, |v| v.clamp(0.02, 1.0)); + let someone_bet = spot.to_call > 0.0; + let live = spot.live_villains().count(); + (vpip + * street_factor(spot.street) + * bet_factor(spot.to_call, spot.pot) + * multiway_factor(live, someone_bet) + * stickiness_factor(profile.fold_to_bet)) + .clamp(MIN_FRACTION, 1.0) } diff --git a/src/exploit/range_narrowing.rs b/src/exploit/range_narrowing.rs new file mode 100644 index 00000000..8aed6602 --- /dev/null +++ b/src/exploit/range_narrowing.rs @@ -0,0 +1,44 @@ +//! Multipliers that narrow or widen a guessed opponent range. + +use crate::game::Street; + +/// Later streets: players who are still in hold stronger hands. +const BY_STREET: [f64; 4] = [1.0, 0.8, 0.62, 0.5]; + +pub fn street_factor(street: Street) -> f64 { + BY_STREET[street as usize] +} + +/// A bet of `to_call / pot` (capped at 1.5 pots) narrows the range: `1 / (1 + 1.2 r)`. +/// No bet gives 1.0; a pot-sized bet about 0.45. Unusable numbers count as a big bet +/// if there is something to call, else no bet. +pub fn bet_factor(to_call: f64, pot: f64) -> f64 { + let ratio = if to_call.is_nan() || to_call <= 0.0 { + 0.0 + } else if pot.is_nan() || pot <= 0.0 { + MAX_BET_RATIO + } else { + (to_call / pot).min(MAX_BET_RATIO) + }; + 1.0 / (1.0 + 1.2 * ratio) +} + +const MAX_BET_RATIO: f64 = 1.5; + +/// Passive multiway pots (nobody has bet) leave wider ranges: +10 % per extra live player, +/// at most three extra. Once somebody bets the bonus is gone. +pub fn multiway_factor(live_players: usize, someone_bet: bool) -> f64 { + if someone_bet { + 1.0 + } else { + 1.0 + 0.1 * live_players.saturating_sub(1).min(3) as f64 + } +} + +/// Sticky players (low foldToBet) continue with more hands, foldy ones with fewer: +/// `1 + 0.4 * (0.5 - foldToBet)`, so 0.84 to 1.2. Unknown or NaN gives 1.0. +pub fn stickiness_factor(fold_to_bet: Option) -> f64 { + fold_to_bet + .filter(|b| !b.is_nan()) + .map_or(1.0, |b| 1.0 + 0.4 * (0.5 - b.clamp(0.0, 1.0))) +} diff --git a/src/exploit/style.rs b/src/exploit/style.rs new file mode 100644 index 00000000..0cbc84c1 --- /dev/null +++ b/src/exploit/style.rs @@ -0,0 +1,62 @@ +//! Classifies an opponent profile into a playing style. + +use super::profile::Profile; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Style { + /// No usable numbers at all. + Unknown, + /// Plays very few hands and folds to pressure. + Nit, + /// Plays many hands and raises a lot. + LooseAggressive, + /// Plays many hands passively, or almost never folds to a bet. + CallingStation, + /// Everything in between. + Regular, +} + +const LOOSE_VPIP: f64 = 0.35; +const AGGRESSIVE_PFR: f64 = 0.20; +const NIT_VPIP: f64 = 0.15; +const NIT_FOLD_TO_BET: f64 = 0.65; +/// Fold-to-bet claims about a "nit" only count if the player is not clearly loose. +const NIT_MAX_VPIP_WITH_FOLDS: f64 = 0.25; +const STATION_FOLD_TO_BET: f64 = 0.30; +const STATION_MIN_VPIP: f64 = 0.28; + +/// A frequency in `[0, 1]`; NaN means "not known". +fn frequency(x: Option) -> Option { + x.filter(|v| !v.is_nan()).map(|v| v.clamp(0.0, 1.0)) +} + +/// Thresholds (vpip/pfr/foldToBet are all clamped to `[0, 1]` first, NaN counts as missing): +/// - all missing: `Unknown` +/// - vpip >= 35 % and pfr >= 20 %: `LooseAggressive` +/// - vpip >= 35 % otherwise, or foldToBet <= 30 % with vpip >= 28 % (or unknown): `CallingStation` +/// - vpip <= 15 %, or foldToBet >= 65 % with vpip <= 25 % (or unknown): `Nit` +/// - else `Regular` +pub fn classify(profile: &Profile) -> Style { + let (vpip, pfr, fold) = ( + frequency(profile.vpip), + frequency(profile.pfr), + frequency(profile.fold_to_bet), + ); + let loose = vpip.is_some_and(|v| v >= LOOSE_VPIP); + let sticky = fold.is_some_and(|b| b <= STATION_FOLD_TO_BET) + && vpip.map_or(true, |v| v >= STATION_MIN_VPIP); + let tight = vpip.is_some_and(|v| v <= NIT_VPIP) + || (fold.is_some_and(|b| b >= NIT_FOLD_TO_BET) + && vpip.map_or(true, |v| v <= NIT_MAX_VPIP_WITH_FOLDS)); + if vpip.is_none() && pfr.is_none() && fold.is_none() { + Style::Unknown + } else if loose && pfr.is_some_and(|f| f >= AGGRESSIVE_PFR) { + Style::LooseAggressive + } else if loose || sticky { + Style::CallingStation + } else if tight { + Style::Nit + } else { + Style::Regular + } +} diff --git a/src/exploit/style_shift.rs b/src/exploit/style_shift.rs new file mode 100644 index 00000000..f880585b --- /dev/null +++ b/src/exploit/style_shift.rs @@ -0,0 +1,51 @@ +//! How each style moves the thresholds, as data. + +use super::style::Style; + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Shift { + /// Added to `call_margin`. + pub call_margin: f64, + /// Added to `value_raise`. + pub value_raise: f64, + /// Multiplies `range_width_scale`. + pub range_width: f64, + /// `fold_equity_scale` to use when the profile has no foldToBet figure. + pub fold_equity_default: f64, +} + +const NONE: Shift = Shift { + call_margin: 0.0, + value_raise: 0.0, + range_width: 1.0, + fold_equity_default: 1.0, +}; + +/// `None` for `Unknown`: nothing is learned from an empty profile. +pub fn shift_for(style: Style) -> Option { + match style { + Style::Unknown => None, + Style::Regular => Some(NONE), + // Their bets are strong, they fold to ours, we defend less. + Style::Nit => Some(Shift { + call_margin: 0.04, + value_raise: 0.02, + range_width: 0.85, + fold_equity_default: 1.25, + }), + // They call too much: value-bet thinner, never bluff. + Style::CallingStation => Some(Shift { + call_margin: 0.0, + value_raise: -0.04, + range_width: 1.0, + fold_equity_default: 0.5, + }), + // They bluff and raise light: call wider, defend wider. + Style::LooseAggressive => Some(Shift { + call_margin: -0.015, + value_raise: -0.01, + range_width: 1.15, + fold_equity_default: 0.9, + }), + } +} diff --git a/src/preflop/advise.rs b/src/preflop/advise.rs index d25026c1..1c7616c3 100644 --- a/src/preflop/advise.rs +++ b/src/preflop/advise.rs @@ -1,9 +1,80 @@ +use super::allin_call_cutoff::call_cutoff; +use super::certainty::certainty; +use super::chart_decision::decide; +use super::chart_row::ChartRow; +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::push_chart::push_cutoff; +use super::reason::describe; +use super::situation::{classify, Situation}; +use super::width_factor::width_factor; use crate::exploit::thresholds::Thresholds; use crate::game::Spot; +use crate::variant::ActionShape; + +/// At or below this effective stack (bb) raising ranges become jamming ranges. +const SHORT_STACK_BB: f64 = 15.0; + +/// A non-finite or non-positive width scale is ignored (treated as neutral). +fn sane_scale(scale: f64) -> f64 { + if scale.is_finite() && scale > 0.0 { + scale + } else { + 1.0 + } +} + +/// 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 width = width_factor(spot.seats, rules.hole_usage) * scale; + match (situation, rules.shape) { + (Situation::FacingAllIn, ActionShape::Full) => { + ChartRow::new(0.0, call_cutoff(spot.to_call, spot.pot), 0.0).scaled(scale) + } + (Situation::FacingAllIn, ActionShape::Binary) => { + ChartRow::new(0.0, 0.0, call_cutoff(spot.to_call, spot.pot)).scaled(scale) + } + (_, ActionShape::Binary) => { + ChartRow::new(0.0, 0.0, push_cutoff(pos, situation, effective_bb)).scaled(scale) + } + (_, ActionShape::Full) => { + let row = full_row(pos, situation) + .unwrap_or(ChartRow::new(0.0, 0.0, 0.0)) + .scaled(width); + if effective_bb <= SHORT_STACK_BB { + row.raises_become_jams() + } else { + row + } + } + } +} /// Chart lookup for a preflop spot. `thresholds.range_width_scale` widens/narrows ranges. +/// +/// Position (`position`), situation (`classify`) and the variant's rules pick a chart row; +/// the row is scaled by table size, game and `range_width_scale`; the hand's percentile +/// then selects jam / raise / call / fold. Binary-shape games only ever answer Jam or Fold. pub fn advise(spot: &Spot, thresholds: &Thresholds) -> PreflopPlan { - let _ = (spot, thresholds); - todo!("preflop::advise") + let hand = percentile(spot.variant, &spot.hero_cards); + let pos = position(spot.seats, spot.hero_seat, spot.button_seat); + let situation = classify(spot.to_call, spot.big_blind, spot.pot, spot.hero_stack); + let row = cutoffs( + spot, + situation, + effective_stack_bb(spot), + sane_scale(thresholds.range_width_scale), + ); + let action = decide(hand, &row); + PreflopPlan { + action, + percentile: hand, + certainty: certainty(hand, &[row.raise, row.call, row.jam]), + reason: describe(pos, situation, action, &row), + } } diff --git a/src/preflop/allin_call_cutoff.rs b/src/preflop/allin_call_cutoff.rs new file mode 100644 index 00000000..16dcc186 --- /dev/null +++ b/src/preflop/allin_call_cutoff.rs @@ -0,0 +1,20 @@ +//! Calling an all-in: how good must the hand be, given the price? + +const MIN_CUTOFF: f64 = 0.005; +const MAX_CUTOFF: f64 = 0.6; + +/// Hand-percentile cut-off for calling `to_call` into a pot of `pot` (which already +/// contains the all-in bet). +/// +/// Required equity `r = to_call / (pot + to_call)`. A shover's range is stronger than a +/// random hand, so the required percentile falls steeply with `r`: +/// `cutoff = 0.8 * (1 - r)^3`, kept in `[0.005, 0.6]` (r = 0.2 gives top 41 %, 0.33 gives +/// 24 %, 0.5 gives 10 %, 0.7 gives 2 %). Garbage prices give the tightest cut-off. +pub fn call_cutoff(to_call: f64, pot: f64) -> f64 { + let required = to_call / (pot + to_call); + if required.is_finite() && (0.0..=1.0).contains(&required) { + (0.8 * (1.0 - required).powi(3)).clamp(MIN_CUTOFF, MAX_CUTOFF) + } else { + MIN_CUTOFF + } +} diff --git a/src/preflop/certainty.rs b/src/preflop/certainty.rs new file mode 100644 index 00000000..ceb8b70a --- /dev/null +++ b/src/preflop/certainty.rs @@ -0,0 +1,12 @@ +//! How firmly a chart holds for one hand. + +/// Distance from `percentile` to the nearest cut-off that actually separates hands +/// (`0 < c < 1`), measured against `max(0.3 * c, 0.01)` and clamped to `[0, 1]`. +/// 1.0 deep inside or outside every range, near 0 right at a border. +pub fn certainty(percentile: f64, cutoffs: &[f64]) -> f64 { + cutoffs + .iter() + .filter(|c| **c > 0.0 && **c < 1.0) + .map(|c| ((percentile - c).abs() / (0.3 * c).max(0.01)).clamp(0.0, 1.0)) + .fold(1.0, f64::min) +} diff --git a/src/preflop/chart_decision.rs b/src/preflop/chart_decision.rs new file mode 100644 index 00000000..a583ac7a --- /dev/null +++ b/src/preflop/chart_decision.rs @@ -0,0 +1,18 @@ +//! Picks the chart action for a hand percentile. + +use super::chart_row::ChartRow; +use super::plan::ChartAction; + +/// Jam beats raise beats call; a hand continues only when strictly inside a cut-off, +/// so a zero cut-off switches that column off. +pub fn decide(percentile: f64, row: &ChartRow) -> ChartAction { + if percentile < row.jam { + ChartAction::Jam + } else if percentile < row.raise { + ChartAction::Raise + } else if percentile < row.call { + ChartAction::Call + } else { + ChartAction::Fold + } +} diff --git a/src/preflop/chart_row.rs b/src/preflop/chart_row.rs new file mode 100644 index 00000000..1674a6db --- /dev/null +++ b/src/preflop/chart_row.rs @@ -0,0 +1,33 @@ +//! One chart line: percentile cut-offs (a hand continues if its percentile is *below* the cut-off). + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ChartRow { + /// Hands better than this raise (open, isolate, 3-bet, 4-bet). + pub raise: f64, + /// Hands better than this, but outside the raise range, call/limp/check. Includes `raise`. + pub call: f64, + /// Hands better than this go all-in (takes precedence over `raise`). + pub jam: f64, +} + +impl ChartRow { + pub const fn new(raise: f64, call: f64, jam: f64) -> ChartRow { + ChartRow { raise, call, jam } + } + + /// Every cut-off multiplied by `factor` and kept inside `[0, 1]`. + pub fn scaled(self, factor: f64) -> ChartRow { + let apply = |c: f64| (c * factor).clamp(0.0, 1.0); + ChartRow::new(apply(self.raise), apply(self.call), apply(self.jam)) + } + + /// Short stacks turn their raising range into a jamming range. + pub fn raises_become_jams(self) -> ChartRow { + ChartRow::new(0.0, self.call, self.jam.max(self.raise)) + } + + /// The widest continuing cut-off. + pub fn widest(self) -> f64 { + self.raise.max(self.call).max(self.jam) + } +} diff --git a/src/preflop/effective_stack.rs b/src/preflop/effective_stack.rs new file mode 100644 index 00000000..92fff3c5 --- /dev/null +++ b/src/preflop/effective_stack.rs @@ -0,0 +1,28 @@ +//! Effective stack in big blinds. + +use crate::game::Spot; + +/// Used when the numbers cannot be trusted: deep enough not to trigger any short-stack rule. +pub const UNKNOWN_DEEP_BB: f64 = 100.0; + +fn usable(x: f64) -> bool { + x.is_finite() && x > 0.0 +} + +/// `min(hero stack, largest live villain stack)` in big blinds; hero's stack alone when +/// no live villain with a usable stack is known. Unusable numbers give `UNKNOWN_DEEP_BB`. +pub fn effective_stack_bb(spot: &Spot) -> f64 { + let largest_villain = spot + .live_villains() + .map(|v| v.stack) + .filter(|s| usable(*s)) + .fold(None, |best: Option, s| { + Some(best.map_or(s, |b| b.max(s))) + }); + let chips = largest_villain.map_or(spot.hero_stack, |v| v.min(spot.hero_stack)); + if usable(chips) && usable(spot.big_blind) { + chips / spot.big_blind + } else { + UNKNOWN_DEEP_BB + } +} diff --git a/src/preflop/full_chart.rs b/src/preflop/full_chart.rs new file mode 100644 index 00000000..0a9b064c --- /dev/null +++ b/src/preflop/full_chart.rs @@ -0,0 +1,81 @@ +//! Raise / call / jam cut-offs for full-action games (six-max reference), as data. +//! +//! Rows by position, columns by situation (`Unopened`, `FacingLimp`, `FacingOpen`, +//! `FacingThreeBetPlus`). `FacingAllIn` is priced, not charted (`allin_call_cutoff`). +//! The percentiles are shares of all starting hands, best first. + +use super::chart_row::ChartRow; +use super::position::Position; +use super::situation::Situation; + +const fn row(raise: f64, call: f64, jam: f64) -> ChartRow { + ChartRow::new(raise, call, jam) +} + +const EARLY: [ChartRow; 4] = [ + row(0.15, 0.15, 0.0), + row(0.10, 0.22, 0.0), + row(0.04, 0.08, 0.0), + row(0.025, 0.045, 0.0), +]; +const MIDDLE: [ChartRow; 4] = [ + row(0.19, 0.19, 0.0), + row(0.13, 0.27, 0.0), + row(0.05, 0.10, 0.0), + row(0.03, 0.05, 0.0), +]; +const CUTOFF: [ChartRow; 4] = [ + row(0.27, 0.27, 0.0), + row(0.18, 0.34, 0.0), + row(0.07, 0.15, 0.0), + row(0.035, 0.06, 0.0), +]; +const BUTTON: [ChartRow; 4] = [ + row(0.42, 0.42, 0.0), + row(0.28, 0.45, 0.0), + row(0.09, 0.24, 0.0), + row(0.04, 0.08, 0.0), +]; +const SMALL_BLIND: [ChartRow; 4] = [ + row(0.38, 0.45, 0.0), + row(0.20, 0.40, 0.0), + row(0.09, 0.15, 0.0), + row(0.04, 0.07, 0.0), +]; +const BIG_BLIND: [ChartRow; 4] = [ + row(0.15, 1.0, 0.0), + row(0.18, 1.0, 0.0), + row(0.08, 0.35, 0.0), + row(0.04, 0.09, 0.0), +]; +const HEADS_UP_BUTTON: [ChartRow; 4] = [ + row(0.75, 0.90, 0.0), + row(0.40, 1.0, 0.0), + row(0.15, 0.55, 0.0), + row(0.05, 0.14, 0.0), +]; + +/// Unknown position is charted like early position (the tightest, hence the safest). +fn rows_for(position: Position) -> &'static [ChartRow; 4] { + match position { + Position::Early | Position::Unknown => &EARLY, + Position::Middle => &MIDDLE, + Position::Cutoff => &CUTOFF, + Position::Button => &BUTTON, + Position::SmallBlind => &SMALL_BLIND, + Position::BigBlind => &BIG_BLIND, + Position::HeadsUpButton => &HEADS_UP_BUTTON, + } +} + +/// `None` for `FacingAllIn`, which has no fixed chart. +pub fn full_row(position: Position, situation: Situation) -> Option { + let column = match situation { + Situation::Unopened => 0, + Situation::FacingLimp => 1, + Situation::FacingOpen => 2, + Situation::FacingThreeBetPlus => 3, + Situation::FacingAllIn => return None, + }; + Some(rows_for(position)[column]) +} diff --git a/src/preflop/hand_percentile.rs b/src/preflop/hand_percentile.rs index cf18837c..4ac1dfe0 100644 --- a/src/preflop/hand_percentile.rs +++ b/src/preflop/hand_percentile.rs @@ -1,9 +1,15 @@ +use super::holdem_percentile::holdem_percentile; +use super::plo5_percentile::plo5_percentile; use crate::card::Card; -use crate::variant::Variant; +use crate::variant::{rules, Variant}; /// Strength percentile of a starting hand: 0.0 = best possible, 1.0 = worst. /// Hold'em-family hands use a 169-class ranking table; PLO5 uses a structural score. +/// Anything that is not a valid hand for the variant is `1.0`. pub fn percentile(variant: Variant, hole: &[Card]) -> f64 { - let _ = (variant, hole); - todo!("preflop::hand_percentile") + match rules(variant).hole_cards { + 2 => holdem_percentile(hole), + 5 => plo5_percentile(hole), + _ => 1.0, + } } diff --git a/src/preflop/holdem_percentile.rs b/src/preflop/holdem_percentile.rs new file mode 100644 index 00000000..aa8e4bcd --- /dev/null +++ b/src/preflop/holdem_percentile.rs @@ -0,0 +1,68 @@ +//! Percentile of a two-card hand from the 169-class ranking. + +use super::holdem_ranking::RANKING; +use crate::card::Card; + +const TOTAL_COMBOS: u32 = 1326; + +/// `[row][col]`: pairs on the diagonal, suited above it (`[high][low]`), +/// offsuit below it (`[low][high]`). Each cell holds the share of combos that +/// rank strictly better plus half the class's own combos, so 0.5 is the mean. +static TABLE: [[f64; 13]; 13] = build_table(); + +const fn rank_index(symbol: u8) -> usize { + match symbol { + b'2' => 0, + b'3' => 1, + b'4' => 2, + b'5' => 3, + b'6' => 4, + b'7' => 5, + b'8' => 6, + b'9' => 7, + b'T' => 8, + b'J' => 9, + b'Q' => 10, + b'K' => 11, + _ => 12, + } +} + +const fn build_table() -> [[f64; 13]; 13] { + let mut table = [[1.0; 13]; 13]; + let mut before = 0u32; + let mut i = 0; + while i < RANKING.len() { + let class = RANKING[i].as_bytes(); + let (high, low) = (rank_index(class[0]), rank_index(class[1])); + let (weight, row, col) = if high == low { + (6, high, high) + } else if class[2] == b's' { + (4, high, low) + } else { + (12, low, high) + }; + table[row][col] = (before as f64 + weight as f64 / 2.0) / TOTAL_COMBOS as f64; + before += weight; + i += 1; + } + table +} + +/// `1.0` unless `hole` is exactly two distinct cards. +pub fn holdem_percentile(hole: &[Card]) -> f64 { + match hole { + [a, b] if a != b => { + let (high, low) = if a.rank >= b.rank { (a, b) } else { (b, a) }; + let (h, l) = (high.rank as usize, low.rank as usize); + if h == l { + TABLE[h][h] + } else if high.suit == low.suit { + TABLE[h][l] + } else { + TABLE[l][h] + } + } + _ => 1.0, + } +} diff --git a/src/preflop/holdem_ranking.rs b/src/preflop/holdem_ranking.rs new file mode 100644 index 00000000..eda8a623 --- /dev/null +++ b/src/preflop/holdem_ranking.rs @@ -0,0 +1,22 @@ +//! The 169 starting-hand classes of Hold'em, best first. +//! +//! Source: all-in equity of each class against one uniformly random hand +//! (heads-up, five-card board run out), measured by Monte-Carlo with 700 000 +//! deals per class; AA 85.2 % down to 32o 32.3 %. Notation: `AKs` suited, +//! `AKo` offsuit, `AA` pair; the higher rank comes first. + +pub const RANKING: [&str; 169] = [ + "AA", "KK", "QQ", "JJ", "TT", "99", "88", "AKs", "AQs", "77", "AKo", "AJs", "ATs", "AQo", + "AJo", "66", "KQs", "A9s", "ATo", "KJs", "A8s", "KTs", "KQo", "A7s", "A9o", "KJo", "55", "QJs", + "K9s", "A5s", "A8o", "A6s", "KTo", "QTs", "A4s", "A7o", "K8s", "A3s", "QJo", "K9o", "A5o", + "Q9s", "K7s", "A6o", "JTs", "A2s", "QTo", "44", "A4o", "K6s", "K8o", "Q8s", "A3o", "K5s", + "J9s", "Q9o", "K7o", "JTo", "A2o", "K4s", "Q7s", "K6o", "J8s", "K3s", "T9s", "33", "Q6s", + "Q8o", "K5o", "J9o", "K2s", "Q5s", "K4o", "T8s", "J7s", "Q4s", "Q7o", "T9o", "J8o", "K3o", + "Q3s", "Q6o", "98s", "T7s", "J6s", "K2o", "22", "Q5o", "Q2s", "J5s", "T8o", "J7o", "Q4o", + "97s", "J4s", "T6s", "Q3o", "J3s", "98o", "T7o", "87s", "J6o", "96s", "J2s", "T5s", "Q2o", + "J5o", "T4s", "86s", "97o", "J4o", "T6o", "T3s", "95s", "76s", "J3o", "87o", "T2s", "85s", + "96o", "J2o", "T5o", "94s", "75s", "T4o", "86o", "65s", "93s", "84s", "T3o", "95o", "76o", + "92s", "74s", "T2o", "85o", "54s", "64s", "83s", "94o", "75o", "82s", "73s", "93o", "65o", + "53s", "63s", "84o", "92o", "43s", "74o", "54o", "72s", "64o", "52s", "62s", "83o", "42s", + "82o", "73o", "53o", "63o", "32s", "43o", "72o", "52o", "62o", "42o", "32o", +]; diff --git a/src/preflop/mod.rs b/src/preflop/mod.rs index db71e18c..55cd7954 100644 --- a/src/preflop/mod.rs +++ b/src/preflop/mod.rs @@ -1,5 +1,24 @@ //! Preflop: chart lookup by position and action sequence. pub mod advise; +pub mod allin_call_cutoff; +pub mod certainty; +pub mod chart_decision; +pub mod chart_row; +pub mod effective_stack; +pub mod full_chart; pub mod hand_percentile; +pub mod holdem_percentile; +pub mod holdem_ranking; pub mod plan; +pub mod plo5_pair_bonus; +pub mod plo5_percentile; +pub mod plo5_rundown; +pub mod plo5_score; +pub mod plo5_score_table; +pub mod plo5_suits; +pub mod position; +pub mod push_chart; +pub mod reason; +pub mod situation; +pub mod width_factor; diff --git a/src/preflop/plo5_pair_bonus.rs b/src/preflop/plo5_pair_bonus.rs new file mode 100644 index 00000000..318c8cb1 --- /dev/null +++ b/src/preflop/plo5_pair_bonus.rs @@ -0,0 +1,19 @@ +//! Score value of a pair, indexed by rank value (2..=14); 0 and 1 unused. + +pub const PAIR_BONUS: [i32; 15] = [0, 0, 2, 3, 4, 6, 8, 10, 13, 16, 20, 24, 28, 34, 40]; + +/// Points per card for being a high card, indexed by rank value. +pub const HIGH_CARD: [i32; 15] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 6, 8, 10]; + +pub const TRIPS_PENALTY: i32 = 25; +pub const QUADS_PENALTY: i32 = 60; + +/// Points a rank group adds: pairs earn their bonus, trips/quads are penalised. +pub fn group_points(rank_value: usize, copies: u8) -> i32 { + match copies { + 2 => PAIR_BONUS[rank_value], + 3 => PAIR_BONUS[rank_value] / 2 - TRIPS_PENALTY, + 4 => -QUADS_PENALTY, + _ => 0, + } +} diff --git a/src/preflop/plo5_percentile.rs b/src/preflop/plo5_percentile.rs new file mode 100644 index 00000000..79063c4d --- /dev/null +++ b/src/preflop/plo5_percentile.rs @@ -0,0 +1,14 @@ +//! Maps an Omaha-5 structural score to a percentile via the empirical score distribution. + +use super::plo5_score::score; +use super::plo5_score_table::{PERCENTILE_BY_SCORE, SCORE_MIN}; +use crate::card::Card; + +/// `1.0` unless `hole` is exactly five distinct cards. Monotone: a higher score never +/// gives a larger percentile. +pub fn plo5_percentile(hole: &[Card]) -> f64 { + score(hole).map_or(1.0, |s| { + let index = (s - SCORE_MIN).clamp(0, PERCENTILE_BY_SCORE.len() as i32 - 1); + PERCENTILE_BY_SCORE[index as usize] + }) +} diff --git a/src/preflop/plo5_rundown.rs b/src/preflop/plo5_rundown.rs new file mode 100644 index 00000000..d4112cef --- /dev/null +++ b/src/preflop/plo5_rundown.rs @@ -0,0 +1,43 @@ +//! Connectedness and dangling-card points for a five-card Omaha hand. + +/// Best points for `k` distinct ranks inside one window of five rank values. +const BY_WINDOW_FILL: [i32; 6] = [0, 0, 0, 4, 12, 22]; +const DANGLER_PENALTY: i32 = 7; + +/// Rank `value` (2..=14) is present; the ace also counts as value 1. +fn present(counts: &[u8; 15], value: usize) -> bool { + if value == 1 { + counts[14] > 0 + } else { + counts[value] > 0 + } +} + +/// Most distinct ranks in any window of five consecutive values (wheel included). +fn best_window_fill(counts: &[u8; 15]) -> usize { + (1..=10) + .map(|low| (low..low + 5).filter(|v| present(counts, *v)).count()) + .max() + .unwrap_or(0) +} + +/// Points for how well the distinct ranks hang together. +pub fn connectedness_points(counts: &[u8; 15]) -> i32 { + BY_WINDOW_FILL[best_window_fill(counts).min(5)] +} + +/// A single card is dangling if it is unpaired, shares no suit, and sits more +/// than four rank values from every other rank. +pub fn dangler_points(counts: &[u8; 15], lone_suit_ranks: impl Iterator) -> i32 { + let isolated = |rank: u8| { + let near = |other: usize| { + let r = rank as usize; + let distance = |a: usize, b: usize| a.max(b) - a.min(b); + other != r + && counts[other] > 0 + && (distance(other, r) <= 4 || (r == 14 && other <= 5) || (other == 14 && r <= 5)) + }; + counts[rank as usize] == 1 && !(2..=14).any(near) + }; + -DANGLER_PENALTY * lone_suit_ranks.filter(|r| isolated(*r)).count() as i32 +} diff --git a/src/preflop/plo5_score.rs b/src/preflop/plo5_score.rs new file mode 100644 index 00000000..f90771f0 --- /dev/null +++ b/src/preflop/plo5_score.rs @@ -0,0 +1,41 @@ +//! Structural strength score of a five-card Omaha starting hand (higher = better). +//! +//! Components: pairs (trips/quads penalised), high cards, suitedness +//! (double-suited bonus, nut-suit bonus), best rundown window, dangling cards. + +use super::plo5_pair_bonus::{group_points, HIGH_CARD}; +use super::plo5_rundown::{connectedness_points, dangler_points}; +use super::plo5_suits::suit_points; +use crate::card::Card; + +/// `None` unless `hole` is exactly five distinct cards. +pub fn score(hole: &[Card]) -> Option { + let distinct = hole.iter().enumerate().all(|(i, c)| !hole[..i].contains(c)); + (hole.len() == 5 && distinct).then(|| score_of_valid(hole)) +} + +fn score_of_valid(hole: &[Card]) -> i32 { + let mut counts = [0u8; 15]; + let mut sizes = [0u8; 4]; + let mut tops = [0u8; 4]; + for card in hole { + let (value, suit) = (card.rank.value(), card.suit as usize); + counts[value as usize] += 1; + sizes[suit] += 1; + tops[suit] = tops[suit].max(value); + } + let groups: i32 = (2..=14).map(|v| group_points(v, counts[v])).sum(); + let high: i32 = hole + .iter() + .map(|c| HIGH_CARD[c.rank.value() as usize]) + .sum(); + let lone = hole + .iter() + .filter(|c| sizes[c.suit as usize] == 1) + .map(|c| c.rank.value()); + groups + + high + + suit_points(&sizes, &tops) + + connectedness_points(&counts) + + dangler_points(&counts, lone) +} diff --git a/src/preflop/plo5_score_table.rs b/src/preflop/plo5_score_table.rs new file mode 100644 index 00000000..b93d0feb --- /dev/null +++ b/src/preflop/plo5_score_table.rs @@ -0,0 +1,32 @@ +//! Empirical percentile of every Omaha-5 structural score (see `plo5_score::score`). +//! +//! Generated by enumerating all 2 598 960 five-card hands: entry `score - SCORE_MIN` is +//! (hands with a higher score + half the hands with this score) / all hands. +//! Regenerate whenever the weights in the `plo5_*` files change. + +pub const SCORE_MIN: i32 = -50; +pub const PERCENTILE_BY_SCORE: [f64; 225] = [ + 0.99996, 0.99991, 0.99991, 0.99990, 0.99990, 0.99990, 0.99990, 0.99989, 0.99988, 0.99987, + 0.99986, 0.99986, 0.99986, 0.99986, 0.99985, 0.99985, 0.99985, 0.99985, 0.99984, 0.99984, + 0.99983, 0.99982, 0.99982, 0.99982, 0.99982, 0.99982, 0.99982, 0.99981, 0.99981, 0.99979, + 0.99977, 0.99975, 0.99973, 0.99969, 0.99965, 0.99960, 0.99940, 0.99914, 0.99886, 0.99855, + 0.99819, 0.99775, 0.99726, 0.99668, 0.99616, 0.99566, 0.99521, 0.99481, 0.99445, 0.99411, + 0.99378, 0.99337, 0.99295, 0.99263, 0.99232, 0.99201, 0.99174, 0.99149, 0.99113, 0.99063, + 0.98990, 0.98890, 0.98739, 0.98546, 0.98269, 0.97915, 0.97239, 0.96527, 0.95637, 0.94681, + 0.93620, 0.92548, 0.91148, 0.89575, 0.87821, 0.85969, 0.84310, 0.82537, 0.80892, 0.79118, + 0.77384, 0.75756, 0.74199, 0.72573, 0.71093, 0.69633, 0.68055, 0.66573, 0.64699, 0.62954, + 0.61349, 0.59864, 0.58179, 0.56494, 0.54469, 0.52169, 0.50182, 0.48085, 0.46359, 0.44462, + 0.42700, 0.40869, 0.39143, 0.37533, 0.35999, 0.34430, 0.32846, 0.31366, 0.29635, 0.28139, + 0.26659, 0.25320, 0.24003, 0.22852, 0.21677, 0.20301, 0.19188, 0.18150, 0.17264, 0.16218, + 0.15219, 0.14314, 0.13503, 0.12803, 0.12186, 0.11593, 0.11043, 0.10617, 0.10207, 0.09779, + 0.09317, 0.08923, 0.08514, 0.08135, 0.07749, 0.07354, 0.06933, 0.06534, 0.06165, 0.05825, + 0.05549, 0.05279, 0.05010, 0.04756, 0.04522, 0.04297, 0.04032, 0.03783, 0.03585, 0.03396, + 0.03271, 0.03155, 0.03014, 0.02874, 0.02762, 0.02672, 0.02553, 0.02394, 0.02259, 0.02144, + 0.02066, 0.01983, 0.01877, 0.01785, 0.01687, 0.01559, 0.01389, 0.01248, 0.01108, 0.00976, + 0.00862, 0.00758, 0.00681, 0.00603, 0.00535, 0.00465, 0.00401, 0.00349, 0.00310, 0.00274, + 0.00241, 0.00209, 0.00191, 0.00173, 0.00166, 0.00159, 0.00142, 0.00127, 0.00118, 0.00111, + 0.00106, 0.00102, 0.00099, 0.00094, 0.00086, 0.00075, 0.00068, 0.00064, 0.00063, 0.00062, + 0.00061, 0.00058, 0.00051, 0.00045, 0.00042, 0.00039, 0.00037, 0.00032, 0.00028, 0.00026, + 0.00025, 0.00024, 0.00019, 0.00013, 0.00010, 0.00007, 0.00007, 0.00006, 0.00005, 0.00004, + 0.00003, 0.00002, 0.00001, 0.00000, 0.00000, +]; diff --git a/src/preflop/plo5_suits.rs b/src/preflop/plo5_suits.rs new file mode 100644 index 00000000..ad2f04df --- /dev/null +++ b/src/preflop/plo5_suits.rs @@ -0,0 +1,18 @@ +//! Suitedness points for a five-card Omaha hand. + +/// Bonus by number of cards in one suit (index 0..=5). +const BY_SUIT_SIZE: [i32; 6] = [0, 0, 10, 12, 6, -8]; +/// Bonus for the highest card of a suit that has at least two cards, by rank value. +const BY_TOP_CARD: [i32; 15] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 5, 10]; +/// Bonus when two different suits are both shared (double suited or better). +const DOUBLE_SUITED: i32 = 12; + +/// `sizes[s]` = cards in suit `s`; `tops[s]` = highest rank value in suit `s`. +pub fn suit_points(sizes: &[u8; 4], tops: &[u8; 4]) -> i32 { + let per_suit: i32 = (0..4) + .filter(|s| sizes[*s] >= 2) + .map(|s| BY_SUIT_SIZE[sizes[s] as usize] + BY_TOP_CARD[tops[s] as usize]) + .sum(); + let shared = sizes.iter().filter(|n| **n >= 2).count(); + per_suit + if shared >= 2 { DOUBLE_SUITED } else { 0 } +} diff --git a/src/preflop/position.rs b/src/preflop/position.rs new file mode 100644 index 00000000..db75983a --- /dev/null +++ b/src/preflop/position.rs @@ -0,0 +1,72 @@ +//! Seat position relative to the button. + +/// Where hero sits. Offsets clockwise from the button: 0 = button, 1 = small blind, +/// 2 = big blind, then under-the-gun onwards; the last seat before the button is the cutoff. +/// Heads-up the button *is* the small blind and acts first preflop (`HeadsUpButton`). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Position { + Early, + Middle, + Cutoff, + Button, + SmallBlind, + BigBlind, + HeadsUpButton, + Unknown, +} + +impl Position { + pub fn label(self) -> &'static str { + match self { + Position::Early => "EP", + Position::Middle => "MP", + Position::Cutoff => "CO", + Position::Button => "BTN", + Position::SmallBlind => "SB", + Position::BigBlind => "BB", + Position::HeadsUpButton => "BTN/SB", + Position::Unknown => "pos?", + } + } +} + +const MIN_SEATS: u8 = 2; +const MAX_SEATS: u8 = 10; + +/// 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`. +pub fn position(seats: u8, hero_seat: u8, button_seat: Option) -> Position { + match button_seat { + Some(button) + if (MIN_SEATS..=MAX_SEATS).contains(&seats) + && hero_seat <= seats + && button <= seats => + { + let offset = (hero_seat as i32 - button as i32).rem_euclid(seats as i32) as u8; + from_offset(seats, offset) + } + _ => Position::Unknown, + } +} + +fn from_offset(seats: u8, offset: u8) -> Position { + match (seats, offset) { + (2, 0) => Position::HeadsUpButton, + (2, _) => Position::BigBlind, + (_, 0) => Position::Button, + (_, 1) => Position::SmallBlind, + (_, 2) => Position::BigBlind, + (_, o) if o == seats - 1 => Position::Cutoff, + (_, o) => { + // Seats between the big blind and the cutoff: the later half is "middle". + let before_cutoff = seats - 4; + let middle = before_cutoff / 2; + if o - 3 < before_cutoff - middle { + Position::Early + } else { + Position::Middle + } + } + } +} diff --git a/src/preflop/push_chart.rs b/src/preflop/push_chart.rs new file mode 100644 index 00000000..8e86a1b2 --- /dev/null +++ b/src/preflop/push_chart.rs @@ -0,0 +1,55 @@ +//! All-in-or-fold charts (binary action shape), as data. +//! +//! Cut-off = position base (at 10 bb) x situation factor x stack factor, kept in `[0, 1]`. +//! Shorter stacks push wider; unknown position uses the early row. + +use super::position::Position; +use super::situation::Situation; + +/// Share of hands pushed at 10 bb effective, unopened. +fn base(position: Position) -> f64 { + match position { + Position::Early | Position::Unknown => 0.30, + Position::Middle => 0.38, + Position::Cutoff => 0.48, + Position::Button => 0.62, + Position::SmallBlind => 0.70, + Position::BigBlind => 0.25, + Position::HeadsUpButton => 0.85, + } +} + +/// Behind other action, the pushing range tightens (jamming over a raise is the tightest). +fn situation_factor(situation: Situation) -> f64 { + match situation { + Situation::Unopened => 1.0, + Situation::FacingLimp => 1.1, + Situation::FacingOpen => 0.4, + Situation::FacingThreeBetPlus => 0.15, + Situation::FacingAllIn => 1.0, + } +} + +/// `(max effective stack in bb, factor)`; anything deeper than the last entry gets `DEEP`. +const STACK_FACTORS: [(f64, f64); 7] = [ + (3.0, 2.0), + (5.0, 1.6), + (7.0, 1.3), + (10.0, 1.0), + (15.0, 0.8), + (20.0, 0.6), + (30.0, 0.4), +]; +const DEEP: f64 = 0.25; + +fn stack_factor(effective_bb: f64) -> f64 { + STACK_FACTORS + .iter() + .find(|(limit, _)| effective_bb <= *limit) + .map_or(DEEP, |(_, factor)| *factor) +} + +/// Push cut-off (percentile) for a non-all-in situation. +pub fn push_cutoff(position: Position, situation: Situation, effective_bb: f64) -> f64 { + (base(position) * situation_factor(situation) * stack_factor(effective_bb)).clamp(0.0, 1.0) +} diff --git a/src/preflop/reason.rs b/src/preflop/reason.rs new file mode 100644 index 00000000..d362ab9a --- /dev/null +++ b/src/preflop/reason.rs @@ -0,0 +1,26 @@ +//! Short human-readable explanation of a chart decision. + +use super::chart_row::ChartRow; +use super::plan::ChartAction; +use super::position::Position; +use super::situation::Situation; + +fn percent(cutoff: f64) -> u32 { + (cutoff * 100.0).round().clamp(0.0, 100.0) as u32 +} + +/// e.g. `"BTN open, top 38%"`, `"BB vs open, call top 30%"`, `"EP open, fold outside top 15%"`. +pub fn describe( + position: Position, + situation: Situation, + action: ChartAction, + row: &ChartRow, +) -> String { + let head = format!("{} {}", position.label(), situation.label()); + match action { + ChartAction::Raise => format!("{head}, top {}%", percent(row.raise)), + ChartAction::Call => format!("{head}, call top {}%", percent(row.call)), + ChartAction::Jam => format!("{head}, jam top {}%", percent(row.jam)), + ChartAction::Fold => format!("{head}, fold outside top {}%", percent(row.widest())), + } +} diff --git a/src/preflop/situation.rs b/src/preflop/situation.rs new file mode 100644 index 00000000..d9c67fe5 --- /dev/null +++ b/src/preflop/situation.rs @@ -0,0 +1,84 @@ +//! What has happened in front of hero, inferred from the chip counts alone. + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Situation { + /// Nobody has put in more than the blinds. + Unopened, + /// One or more limpers. + FacingLimp, + /// A single raise. + FacingOpen, + /// A re-raise or worse. + FacingThreeBetPlus, + /// Calling would put hero's whole stack in. + FacingAllIn, +} + +impl Situation { + pub fn label(self) -> &'static str { + match self { + Situation::Unopened => "open", + Situation::FacingLimp => "vs limp", + Situation::FacingOpen => "vs open", + Situation::FacingThreeBetPlus => "vs 3-bet+", + Situation::FacingAllIn => "vs all-in", + } + } +} + +/// Pot of blinds only (1.5 bb) plus slack for antes/straddle dust. +const UNOPENED_POT_BB: f64 = 2.25; +/// A call this big (in bb) can only be a re-raise: opens are 2-5 bb. +const THREE_BET_CALL_BB: f64 = 5.0; +/// Pot (bb) from which a call above `SMALL_THREE_BET_CALL_BB` is a re-raise too. +const BLOATED_POT_BB: f64 = 11.0; +const SMALL_THREE_BET_CALL_BB: f64 = 3.5; +/// A call of up to one big blind (plus rounding) is not a raise. +const NOT_A_RAISE_BB: f64 = 1.0001; + +fn non_negative(x: f64) -> f64 { + if x.is_nan() || x < 0.0 { + 0.0 + } else { + x + } +} + +/// Heuristics, all in big blinds: +/// 1. `to_call >= hero_stack` (and `to_call > 0`) is all-in; +/// 2. `to_call > 5` or (`pot >= 11` and `to_call > 3.5`) is a 3-bet or more; +/// 3. `to_call > 1` is a single raise; +/// 4. otherwise `pot <= 2.25` is unopened (blinds only), else limped. +/// +/// Known blind spot: a big blind facing a min-raise (call of 1 bb into a 3.5 bb pot) +/// looks like a limp. Nonsense numbers degrade to `Unopened`/`FacingOpen`, never panic. +pub fn classify(to_call: f64, big_blind: f64, pot: f64, hero_stack: f64) -> Situation { + let (to_call, pot, stack) = ( + non_negative(to_call), + non_negative(pot), + non_negative(hero_stack), + ); + let blind_known = big_blind.is_finite() && big_blind > 0.0; + if to_call > 0.0 && to_call >= stack { + Situation::FacingAllIn + } else if !blind_known { + if to_call > 0.0 { + Situation::FacingOpen + } else { + Situation::Unopened + } + } else { + let (call_bb, pot_bb) = (to_call / big_blind, pot / big_blind); + if call_bb > THREE_BET_CALL_BB + || (pot_bb >= BLOATED_POT_BB && call_bb > SMALL_THREE_BET_CALL_BB) + { + Situation::FacingThreeBetPlus + } else if call_bb > NOT_A_RAISE_BB { + Situation::FacingOpen + } else if pot_bb <= UNOPENED_POT_BB { + Situation::Unopened + } else { + Situation::FacingLimp + } + } +} diff --git a/src/preflop/width_factor.rs b/src/preflop/width_factor.rs new file mode 100644 index 00000000..0f1b1e08 --- /dev/null +++ b/src/preflop/width_factor.rs @@ -0,0 +1,19 @@ +//! Chart width multipliers that depend on the table and the game, not on the position. + +use crate::variant::HoleUsage; + +/// By number of seats (index = seats). Shorthanded tables play wider, full ring tighter; +/// the six-max charts are the reference (1.0). +const BY_SEATS: [f64; 11] = [1.0, 1.0, 1.5, 1.25, 1.1, 1.05, 1.0, 0.97, 0.93, 0.9, 0.9]; + +/// Omaha hands run closer in equity, so the same percentile share is played a bit wider. +fn by_hole_usage(usage: HoleUsage) -> f64 { + match usage { + HoleUsage::BestFiveOfAll => 1.0, + HoleUsage::ExactlyTwoHole => 1.1, + } +} + +pub fn width_factor(seats: u8, usage: HoleUsage) -> f64 { + BY_SEATS.get(seats as usize).copied().unwrap_or(0.9) * by_hole_usage(usage) +} diff --git a/tests/exploit_adjust.rs b/tests/exploit_adjust.rs new file mode 100644 index 00000000..06d1c583 --- /dev/null +++ b/tests/exploit_adjust.rs @@ -0,0 +1,141 @@ +use pokerfreak::exploit::adjust::adjust; +use pokerfreak::exploit::profile::Profile; +use pokerfreak::exploit::thresholds::Thresholds; + +const BASE: Thresholds = Thresholds::BASE; + +fn profile(vpip: Option, pfr: Option, fold_to_bet: Option) -> Profile { + Profile { + vpip, + pfr, + fold_to_bet, + } +} + +fn station() -> Profile { + profile(Some(0.50), Some(0.05), Some(0.20)) +} + +fn nit() -> Profile { + profile(Some(0.10), Some(0.07), Some(0.75)) +} + +fn maniac() -> Profile { + profile(Some(0.60), Some(0.40), Some(0.40)) +} + +#[test] +fn no_information_changes_nothing() { + assert_eq!(adjust(BASE, &[]), BASE); + assert_eq!(adjust(BASE, &[Profile::default()]), BASE); + assert_eq!( + adjust(BASE, &[Profile::default(), Profile::default()]), + BASE + ); +} + +#[test] +fn calling_stations_are_value_bet_thinner_and_not_bluffed() { + let t = adjust(BASE, &[station()]); + assert!(t.fold_equity_scale < 0.7 * BASE.fold_equity_scale, "{t:?}"); + assert!(t.value_raise < BASE.value_raise); +} + +#[test] +fn nits_fold_more_and_bet_strong() { + let t = adjust(BASE, &[nit()]); + assert!(t.fold_equity_scale > BASE.fold_equity_scale); + assert!(t.call_margin > BASE.call_margin); + assert!(t.range_width_scale < BASE.range_width_scale); +} + +#[test] +fn aggressive_players_are_called_wider() { + let t = adjust(BASE, &[maniac()]); + assert!(t.call_margin < BASE.call_margin); + assert!(t.range_width_scale > BASE.range_width_scale); +} + +#[test] +fn more_fold_to_bet_never_lowers_fold_equity_scale() { + for (vpip, pfr) in [(0.30, 0.10), (0.15, 0.10), (0.55, 0.40), (0.50, 0.05)] { + let scales: Vec = (0..=20) + .map(|i| { + adjust( + BASE, + &[profile(Some(vpip), Some(pfr), Some(i as f64 / 20.0))], + ) + .fold_equity_scale + }) + .collect(); + assert!( + scales.windows(2).all(|w| w[0] <= w[1]), + "vpip {vpip}: {scales:?}" + ); + assert!(scales[20] > scales[0]); + } +} + +#[test] +fn several_profiles_combine_conservatively() { + let (s, n) = (adjust(BASE, &[station()]), adjust(BASE, &[nit()])); + let both = adjust(BASE, &[station(), nit()]); + assert_eq!(both.call_margin, s.call_margin.max(n.call_margin)); + assert_eq!( + both.fold_equity_scale, + s.fold_equity_scale.min(n.fold_equity_scale) + ); + assert_eq!(both.value_raise, s.value_raise.max(n.value_raise)); + assert_eq!( + both.range_width_scale, + s.range_width_scale.min(n.range_width_scale) + ); + // order does not matter, unknowns are ignored + assert_eq!(adjust(BASE, &[nit(), Profile::default(), station()]), both); +} + +#[test] +fn outputs_stay_in_sane_ranges_for_any_input() { + let grid = [ + None, + Some(-1.0), + Some(0.0), + Some(0.3), + Some(1.0), + Some(9.0), + Some(f64::NAN), + Some(f64::INFINITY), + ]; + for vpip in grid { + for pfr in grid { + for ftb in grid { + let t = adjust(BASE, &[profile(vpip, pfr, ftb)]); + assert!((0.0..=0.15).contains(&t.call_margin), "{t:?}"); + assert!((0.52..=0.85).contains(&t.value_raise), "{t:?}"); + assert!((0.0..=0.05).contains(&t.abstain_band), "{t:?}"); + assert!((0.3..=1.6).contains(&t.fold_equity_scale), "{t:?}"); + assert!((0.6..=1.4).contains(&t.range_width_scale), "{t:?}"); + } + } + } +} + +#[test] +fn adjust_is_pure() { + let ps = [station(), maniac()]; + assert_eq!(adjust(BASE, &ps), adjust(BASE, &ps)); +} + +#[test] +fn adjustments_compose_with_a_non_default_base() { + let tight = Thresholds { + fold_equity_scale: 0.8, + ..BASE + }; + let t = adjust(tight, &[nit()]); + assert!(t.fold_equity_scale > 0.8); + assert!( + adjust(tight, &[station()]).fold_equity_scale + < adjust(BASE, &[station()]).fold_equity_scale + ); +} diff --git a/tests/exploit_range_guess.rs b/tests/exploit_range_guess.rs new file mode 100644 index 00000000..fe0a605b --- /dev/null +++ b/tests/exploit_range_guess.rs @@ -0,0 +1,162 @@ +use pokerfreak::exploit::profile::Profile; +use pokerfreak::exploit::range_guess::top_fraction; +use pokerfreak::game::{ActionKind, Spot, Street, Villain}; +use pokerfreak::variant::Variant; + +fn villain(profile: Option) -> Villain { + Villain { + seat: 1, + stack: 100.0, + folded: false, + profile, + } +} + +fn vpip(value: f64) -> Option { + Some(Profile { + vpip: Some(value), + ..Profile::default() + }) +} + +fn spot(street: Street, pot: f64, to_call: f64, villains: Vec) -> Spot { + Spot { + variant: Variant::Nlhe, + big_blind: 1.0, + seats: 6, + hero_seat: 0, + button_seat: Some(3), + hero_cards: vec![], + board: vec![], + street, + pot, + to_call, + hero_stack: 100.0, + min_raise_to: None, + max_raise_to: None, + legal: vec![ActionKind::Fold, ActionKind::Call, ActionKind::Raise], + allowed_sizes: None, + villains, + seed: 1, + } +} + +fn guess(street: Street, pot: f64, to_call: f64, profile: Option) -> f64 { + let v = villain(profile); + top_fraction(&spot(street, pot, to_call, vec![v.clone()]), &v) +} + +#[test] +fn always_in_the_half_open_unit_interval() { + let profiles = [ + None, + vpip(0.0), + vpip(1.0), + vpip(f64::NAN), + vpip(5.0), + vpip(-2.0), + ]; + for street in Street::ALL { + for (pot, to_call) in [ + (0.0, 0.0), + (10.0, 0.0), + (10.0, 10.0), + (1.0, 50.0), + (f64::NAN, 3.0), + (-4.0, -1.0), + ] { + for p in profiles { + let f = guess(street, pot, to_call, p); + assert!(f > 0.0 && f <= 1.0, "{street:?} {pot} {to_call}: {f}"); + } + } + } +} + +#[test] +fn unknown_profile_uses_a_documented_default() { + let f = guess(Street::Preflop, 1.5, 0.0, None); + assert!((f - 0.30).abs() < 1e-9, "{f}"); +} + +#[test] +fn looser_players_hold_wider_ranges() { + let fractions: Vec = (1..=10) + .map(|i| guess(Street::Flop, 10.0, 0.0, vpip(i as f64 / 10.0))) + .collect(); + assert!(fractions.windows(2).all(|w| w[0] <= w[1]), "{fractions:?}"); + assert!(fractions[9] > fractions[0]); +} + +#[test] +fn bigger_bets_mean_narrower_ranges() { + let fractions: Vec = [0.0, 2.5, 5.0, 10.0, 20.0] + .iter() + .map(|c| guess(Street::Flop, 10.0, *c, vpip(0.4))) + .collect(); + assert!(fractions.windows(2).all(|w| w[0] > w[1]), "{fractions:?}"); +} + +#[test] +fn later_streets_mean_narrower_ranges() { + let fractions: Vec = Street::ALL + .iter() + .map(|s| guess(*s, 10.0, 5.0, vpip(0.4))) + .collect(); + assert!(fractions.windows(2).all(|w| w[0] > w[1]), "{fractions:?}"); +} + +#[test] +fn passive_multiway_pots_are_wider_than_heads_up() { + let v = villain(vpip(0.3)); + let heads_up = top_fraction(&spot(Street::Flop, 10.0, 0.0, vec![v.clone()]), &v); + let three_way = top_fraction( + &spot( + Street::Flop, + 10.0, + 0.0, + vec![v.clone(), villain(None), villain(None)], + ), + &v, + ); + assert!(three_way > heads_up); + // once somebody bets, the multiway bonus is gone. + let bet_hu = top_fraction(&spot(Street::Flop, 10.0, 5.0, vec![v.clone()]), &v); + let bet_mw = top_fraction( + &spot( + Street::Flop, + 10.0, + 5.0, + vec![v.clone(), villain(None), villain(None)], + ), + &v, + ); + assert_eq!(bet_hu, bet_mw); +} + +#[test] +fn folded_villains_do_not_count_as_multiway() { + let v = villain(vpip(0.3)); + let folded = Villain { + folded: true, + ..villain(None) + }; + let a = top_fraction(&spot(Street::Flop, 10.0, 0.0, vec![v.clone()]), &v); + let b = top_fraction(&spot(Street::Flop, 10.0, 0.0, vec![v.clone(), folded]), &v); + assert_eq!(a, b); +} + +#[test] +fn sticky_players_hold_wider_ranges_than_foldy_ones() { + let with_ftb = |ftb: f64| { + Some(Profile { + vpip: Some(0.3), + pfr: None, + fold_to_bet: Some(ftb), + }) + }; + assert!( + guess(Street::Turn, 10.0, 5.0, with_ftb(0.1)) + > guess(Street::Turn, 10.0, 5.0, with_ftb(0.9)) + ); +} diff --git a/tests/exploit_style.rs b/tests/exploit_style.rs new file mode 100644 index 00000000..ec566a37 --- /dev/null +++ b/tests/exploit_style.rs @@ -0,0 +1,70 @@ +use pokerfreak::exploit::profile::Profile; +use pokerfreak::exploit::style::{classify, Style}; + +fn profile(vpip: Option, pfr: Option, fold_to_bet: Option) -> Profile { + Profile { + vpip, + pfr, + fold_to_bet, + } +} + +#[test] +fn nothing_known_is_unknown() { + assert_eq!(classify(&Profile::default()), Style::Unknown); + assert_eq!( + classify(&profile(Some(f64::NAN), None, Some(f64::NAN))), + Style::Unknown + ); +} + +#[test] +fn tight_players_are_nits() { + assert_eq!(classify(&profile(Some(0.10), Some(0.08), None)), Style::Nit); + assert_eq!(classify(&profile(None, None, Some(0.80))), Style::Nit); +} + +#[test] +fn loose_and_raising_is_loose_aggressive() { + assert_eq!( + classify(&profile(Some(0.55), Some(0.35), None)), + Style::LooseAggressive + ); + assert_eq!( + classify(&profile(Some(0.45), Some(0.30), Some(0.5))), + Style::LooseAggressive + ); +} + +#[test] +fn loose_and_passive_or_sticky_is_a_calling_station() { + assert_eq!( + classify(&profile(Some(0.50), Some(0.05), Some(0.2))), + Style::CallingStation + ); + assert_eq!( + classify(&profile(Some(0.45), None, None)), + Style::CallingStation + ); + assert_eq!( + classify(&profile(None, None, Some(0.15))), + Style::CallingStation + ); +} + +#[test] +fn ordinary_numbers_are_regular() { + assert_eq!( + classify(&profile(Some(0.22), Some(0.18), Some(0.5))), + Style::Regular + ); +} + +#[test] +fn out_of_range_values_are_clamped_not_trusted() { + assert_eq!( + classify(&profile(Some(7.0), Some(5.0), None)), + Style::LooseAggressive + ); + assert_eq!(classify(&profile(Some(-3.0), None, None)), Style::Nit); +} diff --git a/tests/preflop_advise.rs b/tests/preflop_advise.rs new file mode 100644 index 00000000..2d7c6a36 --- /dev/null +++ b/tests/preflop_advise.rs @@ -0,0 +1,397 @@ +use pokerfreak::card::Card; +use pokerfreak::exploit::thresholds::Thresholds; +use pokerfreak::game::Spot; +use pokerfreak::game::{ActionKind, Street, Villain}; +use pokerfreak::preflop::advise::advise; +use pokerfreak::preflop::hand_percentile::percentile; +use pokerfreak::preflop::plan::{ChartAction, PreflopPlan}; +use pokerfreak::variant::Variant; + +const EARLY: u8 = 0; +const MIDDLE: u8 = 1; +const CUTOFF: u8 = 2; +const BUTTON: u8 = 3; +const SMALL_BLIND: u8 = 4; +const BIG_BLIND: u8 = 5; + +fn cards(text: &str) -> Vec { + Card::parse_list(text).expect("valid cards") +} + +fn villain(stack: f64) -> Villain { + Villain { + seat: 0, + stack, + folded: false, + profile: None, + } +} + +/// Six-max, button on seat 3, big blind = 1.0. +fn spot_with( + variant: Variant, + hole: Vec, + hero_seat: u8, + pot: f64, + to_call: f64, + stack: f64, +) -> Spot { + Spot { + variant, + big_blind: 1.0, + seats: 6, + hero_seat, + button_seat: Some(3), + hero_cards: hole, + board: vec![], + street: Street::Preflop, + pot, + to_call, + hero_stack: stack, + min_raise_to: Some(2.0), + max_raise_to: Some(stack), + legal: vec![ActionKind::Fold, ActionKind::Call, ActionKind::Raise], + allowed_sizes: None, + villains: vec![villain(100.0)], + seed: 1, + } +} + +fn spot(hole: &str, hero_seat: u8, pot: f64, to_call: f64) -> Spot { + spot_with(Variant::Nlhe, cards(hole), hero_seat, pot, to_call, 100.0) +} + +fn plan(hole: &str, hero_seat: u8, pot: f64, to_call: f64) -> PreflopPlan { + advise(&spot(hole, hero_seat, pot, to_call), &Thresholds::BASE) +} + +fn all_combos() -> Vec> { + (0..52u8) + .flat_map(|i| (i + 1..52u8).map(move |j| (i, j))) + .filter_map(|(i, j)| Some(vec![Card::from_index(i)?, Card::from_index(j)?])) + .collect() +} + +/// Share of the 1326 combos for which the chart answers `wanted`. +fn share(base: &Spot, thresholds: &Thresholds, wanted: ChartAction) -> f64 { + let hits = all_combos() + .into_iter() + .filter(|hole| { + let s = Spot { + hero_cards: hole.clone(), + ..base.clone() + }; + advise(&s, thresholds).action == wanted + }) + .count(); + hits as f64 / 1326.0 +} + +fn open_share(hero_seat: u8, thresholds: &Thresholds) -> f64 { + let to_call = if hero_seat == SMALL_BLIND { 0.5 } else { 1.0 }; + let base = spot("Ah Ad", hero_seat, 1.5, to_call); + share(&base, thresholds, ChartAction::Raise) +} + +#[test] +fn premium_hands_open_everywhere_and_trash_never_does() { + for seat in [EARLY, MIDDLE, CUTOFF, BUTTON, SMALL_BLIND] { + let to_call = if seat == SMALL_BLIND { 0.5 } else { 1.0 }; + assert_eq!(plan("Ah Ad", seat, 1.5, to_call).action, ChartAction::Raise); + assert_eq!(plan("7c 2d", seat, 1.5, to_call).action, ChartAction::Fold); + } +} + +#[test] +fn opening_range_widens_towards_the_button() { + let neutral = Thresholds::BASE; + let (e, m, c, b) = ( + open_share(EARLY, &neutral), + open_share(MIDDLE, &neutral), + open_share(CUTOFF, &neutral), + open_share(BUTTON, &neutral), + ); + assert!(e < m && m < c && c < b, "{e} {m} {c} {b}"); + assert!((0.10..0.20).contains(&e), "early {e}"); + assert!((0.33..0.50).contains(&b), "button {b}"); +} + +#[test] +fn unknown_position_uses_the_early_chart() { + let neutral = Thresholds::BASE; + let known = Spot { + button_seat: Some(3), + ..spot("Ah Ad", EARLY, 1.5, 1.0) + }; + let unknown = Spot { + button_seat: None, + hero_seat: BUTTON, + ..known.clone() + }; + let early = share(&known, &neutral, ChartAction::Raise); + assert_eq!(share(&unknown, &neutral, ChartAction::Raise), early); +} + +#[test] +fn range_width_scale_widens_and_narrows() { + let base = Thresholds::BASE; + let wide = Thresholds { + range_width_scale: 1.3, + ..base + }; + let narrow = Thresholds { + range_width_scale: 0.7, + ..base + }; + let (n, b, w) = ( + open_share(BUTTON, &narrow), + open_share(BUTTON, &base), + open_share(BUTTON, &wide), + ); + assert!(n < b && b < w, "{n} {b} {w}"); + let broken = Thresholds { + range_width_scale: f64::NAN, + ..base + }; + assert_eq!(open_share(BUTTON, &broken), b); +} + +#[test] +fn heads_up_button_opens_most_hands() { + let mut s = spot("Ah Ad", BUTTON, 1.5, 0.5); + s.seats = 2; + s.hero_seat = 0; + s.button_seat = Some(0); + assert!(share(&s, &Thresholds::BASE, ChartAction::Raise) > 0.6); +} + +#[test] +fn big_blind_checks_its_option_with_anything() { + let p = plan("7c 2d", BIG_BLIND, 2.5, 0.0); + assert_eq!(p.action, ChartAction::Call); +} + +#[test] +fn facing_a_limp_isolates_with_strong_hands() { + assert_eq!(plan("Ah Ad", BUTTON, 2.5, 1.0).action, ChartAction::Raise); + assert_eq!(plan("7c 2d", BUTTON, 2.5, 1.0).action, ChartAction::Fold); +} + +#[test] +fn facing_an_open_three_bets_calls_or_folds() { + assert_eq!(plan("Ah Ad", BUTTON, 4.5, 3.0).action, ChartAction::Raise); + assert_eq!(plan("Ah Kd", BUTTON, 4.5, 3.0).action, ChartAction::Raise); + assert_eq!(plan("Jh Th", BUTTON, 4.5, 3.0).action, ChartAction::Call); + assert_eq!(plan("7c 2d", BUTTON, 4.5, 3.0).action, ChartAction::Fold); + // big blind defends wider than an early seat against the same price. + let bb_calls = share( + &spot("Ah Ad", BIG_BLIND, 4.5, 2.0), + &Thresholds::BASE, + ChartAction::Call, + ); + let ep_calls = share( + &spot("Ah Ad", EARLY, 4.5, 3.0), + &Thresholds::BASE, + ChartAction::Call, + ); + assert!(bb_calls > ep_calls); +} + +#[test] +fn facing_a_three_bet_continues_only_with_the_top() { + assert_eq!(plan("Ah Ad", BUTTON, 13.5, 9.0).action, ChartAction::Raise); + assert_eq!(plan("Kh Jd", BUTTON, 13.5, 9.0).action, ChartAction::Fold); + let continuing = 1.0 + - share( + &spot("Ah Ad", BUTTON, 13.5, 9.0), + &Thresholds::BASE, + ChartAction::Fold, + ); + assert!(continuing < 0.12, "continue share {continuing}"); +} + +#[test] +fn short_stacks_turn_raises_into_jams() { + let short = spot_with(Variant::Nlhe, cards("Ah Ad"), BUTTON, 4.5, 3.0, 15.0); + assert_eq!(advise(&short, &Thresholds::BASE).action, ChartAction::Jam); + let deep = spot_with(Variant::Nlhe, cards("Ah Ad"), BUTTON, 4.5, 3.0, 100.0); + assert_eq!(advise(&deep, &Thresholds::BASE).action, ChartAction::Raise); +} + +#[test] +fn facing_an_all_in_depends_on_the_price() { + let call_share = |pot: f64| { + let s = spot_with(Variant::Nlhe, cards("Ah Ad"), BUTTON, pot, 100.0, 100.0); + share(&s, &Thresholds::BASE, ChartAction::Call) + }; + let cheap = call_share(300.0); + let dear = call_share(100.0); + assert!(cheap > dear, "{cheap} {dear}"); + assert!(dear < 0.11); + let aces = spot_with(Variant::Nlhe, cards("Ah Ad"), BUTTON, 150.0, 100.0, 100.0); + assert_eq!(advise(&aces, &Thresholds::BASE).action, ChartAction::Call); + let trash = spot_with(Variant::Nlhe, cards("7c 2d"), BUTTON, 150.0, 100.0, 100.0); + assert_eq!(advise(&trash, &Thresholds::BASE).action, ChartAction::Fold); +} + +#[test] +fn all_in_or_fold_only_ever_jams_or_folds() { + let stacks = [3.0, 5.0, 10.0, 20.0, 40.0]; + for stack in stacks { + for seat in [EARLY, CUTOFF, BUTTON, SMALL_BLIND, BIG_BLIND] { + for (pot, to_call) in [(1.5, 1.0), (2.5, 1.0), (4.5, 3.0), (stack + 1.5, stack)] { + let base = spot_with(Variant::Aof, cards("Ah Ad"), seat, pot, to_call, stack); + for hole in all_combos().into_iter().step_by(37) { + let s = Spot { + hero_cards: hole, + ..base.clone() + }; + let action = advise(&s, &Thresholds::BASE).action; + assert!( + matches!(action, ChartAction::Jam | ChartAction::Fold), + "{action:?}" + ); + } + } + } + } +} + +#[test] +fn all_in_or_fold_gets_wider_when_shorter() { + let jam_share = |stack: f64| { + let base = spot_with(Variant::Aof, cards("Ah Ad"), BUTTON, 1.5, 1.0, stack); + share(&base, &Thresholds::BASE, ChartAction::Jam) + }; + let (s5, s10, s20, s40) = ( + jam_share(5.0), + jam_share(10.0), + jam_share(20.0), + jam_share(40.0), + ); + assert!(s5 > s10 && s10 > s20 && s20 > s40, "{s5} {s10} {s20} {s40}"); + let deep_aces = spot_with(Variant::Aof, cards("Ah Ad"), EARLY, 1.5, 1.0, 40.0); + assert_eq!( + advise(&deep_aces, &Thresholds::BASE).action, + ChartAction::Jam + ); + let deep_trash = spot_with(Variant::Aof, cards("7c 2d"), EARLY, 1.5, 1.0, 40.0); + assert_eq!( + advise(&deep_trash, &Thresholds::BASE).action, + ChartAction::Fold + ); +} + +#[test] +fn all_in_or_fold_uses_the_effective_stack() { + let mut covered = spot_with(Variant::Aof, cards("9h 8h"), BUTTON, 1.5, 1.0, 40.0); + covered.villains = vec![villain(6.0)]; + let mut covering = covered.clone(); + covering.villains = vec![villain(80.0)]; + let jam = |s: &Spot| share(s, &Thresholds::BASE, ChartAction::Jam); + assert!(jam(&covered) > jam(&covering)); +} + +#[test] +fn plan_carries_percentile_certainty_and_reason() { + let aces = plan("Ah Ad", BUTTON, 1.5, 1.0); + assert_eq!(aces.percentile, percentile(Variant::Nlhe, &cards("Ah Ad"))); + assert!((0.0..=1.0).contains(&aces.certainty)); + assert!(aces.certainty > 0.9); + assert!( + aces.reason.contains("BTN") && aces.reason.contains("open"), + "{}", + aces.reason + ); + assert!( + aces.reason.contains("top") && aces.reason.contains('%'), + "{}", + aces.reason + ); + + let all_certainties_ok = all_combos().into_iter().step_by(11).all(|hole| { + let s = Spot { + hero_cards: hole, + ..spot("Ah Ad", BUTTON, 1.5, 1.0) + }; + let p = advise(&s, &Thresholds::BASE); + (0.0..=1.0).contains(&p.certainty) && !p.reason.is_empty() + }); + assert!(all_certainties_ok); +} + +#[test] +fn borderline_hands_are_less_certain_than_clear_ones() { + let base = spot("Ah Ad", BUTTON, 1.5, 1.0); + let by_certainty: Vec = all_combos() + .into_iter() + .map(|hole| { + advise( + &Spot { + hero_cards: hole, + ..base.clone() + }, + &Thresholds::BASE, + ) + .certainty + }) + .collect(); + assert!(by_certainty.iter().any(|c| *c < 0.2)); + assert!(by_certainty.iter().any(|c| *c > 0.95)); +} + +#[test] +fn omaha_five_cards_use_the_same_charts() { + let strong = spot_with( + Variant::Plo5, + cards("Ah Ad Kh Kd Jc"), + BUTTON, + 1.5, + 1.0, + 100.0, + ); + let junk = spot_with( + Variant::Plo5, + cards("2c 7d 4h 9s 3c"), + BUTTON, + 1.5, + 1.0, + 100.0, + ); + assert_eq!( + advise(&strong, &Thresholds::BASE).action, + ChartAction::Raise + ); + assert_eq!(advise(&junk, &Thresholds::BASE).action, ChartAction::Fold); +} + +#[test] +fn invalid_hole_cards_fold_without_panicking() { + let one = spot_with(Variant::Nlhe, cards("Ah"), BUTTON, 1.5, 1.0, 100.0); + let plan = advise(&one, &Thresholds::BASE); + assert_eq!(plan.action, ChartAction::Fold); + assert_eq!(plan.percentile, 1.0); + let none = spot_with(Variant::Aof, vec![], BUTTON, 1.5, 1.0, 10.0); + assert_eq!(advise(&none, &Thresholds::BASE).action, ChartAction::Fold); +} + +#[test] +fn degenerate_numbers_do_not_panic() { + let weird = [ + (f64::NAN, f64::NAN, f64::NAN), + (0.0, 0.0, 0.0), + (-1.0, -1.0, -1.0), + ]; + for (pot, to_call, stack) in weird { + for variant in Variant::ALL { + let hole = if variant == Variant::Plo5 { + "Ah Ad Kh Kd Jc" + } else { + "Ah Ad" + }; + let s = spot_with(variant, cards(hole), BUTTON, pot, to_call, stack); + let p = advise(&s, &Thresholds::BASE); + assert!((0.0..=1.0).contains(&p.certainty)); + } + } +} diff --git a/tests/preflop_percentile.rs b/tests/preflop_percentile.rs new file mode 100644 index 00000000..98b09fbb --- /dev/null +++ b/tests/preflop_percentile.rs @@ -0,0 +1,111 @@ +use pokerfreak::card::Card; +use pokerfreak::preflop::hand_percentile::percentile; +use pokerfreak::preflop::holdem_ranking::RANKING; +use pokerfreak::variant::Variant; + +fn hand(text: &str) -> Vec { + Card::parse_list(text).expect("valid cards") +} + +fn pct(text: &str) -> f64 { + percentile(Variant::Nlhe, &hand(text)) +} + +fn all_combos() -> Vec> { + (0..52u8) + .flat_map(|i| (i + 1..52u8).map(move |j| (i, j))) + .filter_map(|(i, j)| Some(vec![Card::from_index(i)?, Card::from_index(j)?])) + .collect() +} + +#[test] +fn ranking_table_has_169_distinct_classes() { + assert_eq!(RANKING.len(), 169); + let mut sorted: Vec<&str> = RANKING.to_vec(); + sorted.sort_unstable(); + sorted.dedup(); + assert_eq!(sorted.len(), 169); +} + +#[test] +fn aces_are_best_and_seven_deuce_is_near_worst() { + assert!(pct("Ah Ad") < 0.01); + assert!(pct("7c 2d") > 0.93); + assert!(pct("3c 2d") > pct("7c 2d")); +} + +#[test] +fn pairs_descend() { + assert!(pct("Ah Ad") < pct("Kh Kd")); + assert!(pct("Kh Kd") < pct("Qh Qd")); + assert!(pct("Qh Qd") < pct("2h 2d")); +} + +#[test] +fn well_known_orderings_hold() { + assert!(pct("Ah Kh") < pct("Ah Kd")); + assert!(pct("Ah Kh") < pct("Ah Qh")); + assert!(pct("Ah Kd") < pct("Ah Qd")); + assert!(pct("Kh Kd") < pct("Ah Kh")); + assert!(pct("Jh Th") < pct("Jh 2h")); + assert!(pct("2h 2d") < pct("7c 3d")); +} + +#[test] +fn suited_beats_offsuit_for_every_unpaired_class() { + let ranks = "23456789TJQKA"; + for (i, hi) in ranks.chars().enumerate().skip(1) { + for lo in ranks.chars().take(i) { + let suited = pct(&format!("{hi}h {lo}h")); + let offsuit = pct(&format!("{hi}h {lo}d")); + assert!(suited < offsuit, "{hi}{lo}s vs {hi}{lo}o"); + } + } +} + +#[test] +fn every_combo_maps_into_unit_interval_and_averages_one_half() { + let combos = all_combos(); + assert_eq!(combos.len(), 1326); + let values: Vec = combos + .iter() + .map(|c| percentile(Variant::Nlhe, c)) + .collect(); + assert!(values.iter().all(|p| (0.0..=1.0).contains(p))); + let mean = values.iter().sum::() / values.len() as f64; + assert!((mean - 0.5).abs() < 0.001, "mean {mean}"); +} + +#[test] +fn suit_and_card_order_do_not_matter() { + assert_eq!(pct("Ah 5h"), pct("5s As")); + assert_eq!(pct("Ah 5d"), pct("5c Ad")); + assert_ne!(pct("Ah 5h"), pct("Ah 5d")); +} + +#[test] +fn hold_em_family_shares_one_table() { + let h = hand("Qh Jd"); + let base = percentile(Variant::Nlhe, &h); + assert_eq!(percentile(Variant::KPoker, &h), base); + assert_eq!(percentile(Variant::Aof, &h), base); +} + +#[test] +fn invalid_hands_are_worst_not_panics() { + assert_eq!(percentile(Variant::Nlhe, &[]), 1.0); + assert_eq!(percentile(Variant::Nlhe, &hand("Ah")), 1.0); + assert_eq!(percentile(Variant::Nlhe, &hand("Ah Kd Qc")), 1.0); + assert_eq!(percentile(Variant::Nlhe, &hand("Ah Ah")), 1.0); + assert_eq!(percentile(Variant::Plo5, &hand("Ah Kd")), 1.0); + assert_eq!(percentile(Variant::Plo5, &hand("Ah Kd Qc Js Th 9h")), 1.0); + assert_eq!(percentile(Variant::Plo5, &hand("Ah Ah Qc Js Th")), 1.0); +} + +#[test] +fn many_calls_are_cheap_and_deterministic() { + let h = hand("9h 8h"); + let first = percentile(Variant::Nlhe, &h); + let sum: f64 = (0..300_000).map(|_| percentile(Variant::Nlhe, &h)).sum(); + assert!((sum / 300_000.0 - first).abs() < 1e-9); +} diff --git a/tests/preflop_plo5.rs b/tests/preflop_plo5.rs new file mode 100644 index 00000000..97cb25c4 --- /dev/null +++ b/tests/preflop_plo5.rs @@ -0,0 +1,106 @@ +use pokerfreak::card::Card; +use pokerfreak::preflop::hand_percentile::percentile; +use pokerfreak::preflop::plo5_score::score; +use pokerfreak::variant::Variant; + +fn hand(text: &str) -> Vec { + Card::parse_list(text).expect("valid cards") +} + +fn pct(text: &str) -> f64 { + percentile(Variant::Plo5, &hand(text)) +} + +/// Deterministic pseudo-random 5-card hands (LCG), independent of the crate's Rng. +fn sample_hands(count: usize) -> Vec> { + let mut state: u64 = 0x2545_F491_4F6C_DD1D; + let mut next = move || { + state = state + .wrapping_mul(6364136223846793005) + .wrapping_add(1442695040888963407); + (state >> 33) as u8 + }; + (0..count) + .map(|_| { + let mut picked: Vec = Vec::new(); + while picked.len() < 5 { + let c = next() % 52; + if !picked.contains(&c) { + picked.push(c); + } + } + picked.into_iter().filter_map(Card::from_index).collect() + }) + .collect() +} + +#[test] +fn double_suited_big_pairs_beat_rainbow_junk() { + let strong = pct("Ah Ad Kh Kd Jc"); + let junk = pct("2c 7d 4h 9s 3c"); + assert!(strong < 0.05, "strong {strong}"); + assert!(junk > 0.8, "junk {junk}"); + assert!(strong < junk); +} + +#[test] +fn double_suited_beats_single_suited_with_same_ranks() { + assert!(pct("Ah Kh Qd Jd Tc") < pct("Ah Kd Qc Js Ts")); +} + +#[test] +fn trips_and_quads_are_penalised() { + assert!(pct("Ah Ad Kh Kd Qc") < pct("Ah Ad Ac Kh Qd")); + assert!(pct("Ah Ad Ac Kh Qd") < pct("Ah Ad Ac As Kd")); +} + +#[test] +fn connected_rundowns_beat_scattered_cards_of_same_top() { + assert!(pct("Jh Td 9c 8s 2h") < pct("Jh 8d 5c 3s 2h")); +} + +#[test] +fn bigger_pairs_beat_smaller_pairs() { + assert!(pct("Ah Ad Kc Qs Jh") < pct("7h 7d Kc Qs Jh")); +} + +#[test] +fn suit_permutation_does_not_change_the_value() { + assert_eq!(pct("Ah Ad Kh Kd Jc"), pct("As Ac Ks Kc Jd")); + assert_eq!(pct("Ah Ad Kh Kd Jc"), pct("Jc Kd Kh Ad Ah")); +} + +#[test] +fn percentile_is_monotone_in_score() { + let hands = sample_hands(1500); + for a in &hands { + for b in hands.iter().take(40) { + let (sa, sb) = (score(a).expect("score"), score(b).expect("score")); + let (pa, pb) = (percentile(Variant::Plo5, a), percentile(Variant::Plo5, b)); + if sa > sb { + assert!(pa <= pb); + } + if sa == sb { + assert_eq!(pa, pb); + } + } + } +} + +#[test] +fn random_hands_spread_evenly_over_the_unit_interval() { + let hands = sample_hands(20_000); + let values: Vec = hands.iter().map(|h| percentile(Variant::Plo5, h)).collect(); + assert!(values.iter().all(|p| (0.0..=1.0).contains(p))); + let mean = values.iter().sum::() / values.len() as f64; + assert!((mean - 0.5).abs() < 0.02, "mean {mean}"); + let top_decile = values.iter().filter(|p| **p < 0.1).count() as f64 / values.len() as f64; + assert!((top_decile - 0.1).abs() < 0.03, "top decile {top_decile}"); +} + +#[test] +fn score_rejects_wrong_card_counts() { + assert_eq!(score(&hand("Ah Kd")), None); + assert_eq!(score(&hand("Ah Kd Qc Js Th 9h")), None); + assert_eq!(score(&hand("Ah Ah Qc Js Th")), None); +} diff --git a/tests/preflop_position.rs b/tests/preflop_position.rs new file mode 100644 index 00000000..4e9dc988 --- /dev/null +++ b/tests/preflop_position.rs @@ -0,0 +1,95 @@ +use pokerfreak::preflop::position::{position, Position}; + +#[test] +fn six_max_zero_based() { + let at = |hero| position(6, hero, Some(3)); + assert_eq!(at(3), Position::Button); + assert_eq!(at(4), Position::SmallBlind); + assert_eq!(at(5), Position::BigBlind); + assert_eq!(at(0), Position::Early); + assert_eq!(at(1), Position::Middle); + assert_eq!(at(2), Position::Cutoff); +} + +#[test] +fn six_max_one_based() { + let at = |hero| position(6, hero, Some(6)); + assert_eq!(at(6), Position::Button); + assert_eq!(at(1), Position::SmallBlind); + assert_eq!(at(2), Position::BigBlind); + assert_eq!(at(3), Position::Early); + assert_eq!(at(4), Position::Middle); + assert_eq!(at(5), Position::Cutoff); +} + +#[test] +fn heads_up_button_is_small_blind() { + assert_eq!(position(2, 0, Some(0)), Position::HeadsUpButton); + assert_eq!(position(2, 1, Some(0)), Position::BigBlind); + assert_eq!(position(2, 2, Some(1)), Position::BigBlind); + assert_eq!(position(2, 1, Some(1)), Position::HeadsUpButton); +} + +#[test] +fn three_and_four_handed() { + assert_eq!(position(3, 0, Some(0)), Position::Button); + assert_eq!(position(3, 1, Some(0)), Position::SmallBlind); + assert_eq!(position(3, 2, Some(0)), Position::BigBlind); + assert_eq!(position(4, 0, Some(1)), Position::Cutoff); + assert_eq!(position(4, 1, Some(1)), Position::Button); +} + +#[test] +fn five_handed_has_one_early_seat() { + assert_eq!(position(5, 4, Some(1)), Position::Early); + assert_eq!(position(5, 0, Some(1)), Position::Cutoff); +} + +#[test] +fn nine_and_ten_handed_split_early_and_middle() { + let nine: Vec = (3..9).map(|o| position(9, o, Some(0))).collect(); + assert_eq!( + nine, + vec![ + Position::Early, + Position::Early, + Position::Early, + Position::Middle, + Position::Middle, + Position::Cutoff + ] + ); + let ten: Vec = (3..10).map(|o| position(10, o, Some(0))).collect(); + assert_eq!(ten.iter().filter(|p| **p == Position::Early).count(), 3); + assert_eq!(ten.iter().filter(|p| **p == Position::Middle).count(), 3); + assert_eq!(ten[6], Position::Cutoff); +} + +#[test] +fn unknown_when_button_missing_or_input_absurd() { + assert_eq!(position(6, 2, None), Position::Unknown); + assert_eq!(position(1, 0, Some(0)), Position::Unknown); + assert_eq!(position(0, 0, Some(0)), Position::Unknown); + assert_eq!(position(11, 0, Some(0)), Position::Unknown); + assert_eq!(position(6, 9, Some(0)), Position::Unknown); + assert_eq!(position(6, 0, Some(9)), Position::Unknown); +} + +#[test] +fn labels_are_short_and_distinct() { + let all = [ + Position::Early, + Position::Middle, + Position::Cutoff, + Position::Button, + Position::SmallBlind, + Position::BigBlind, + Position::HeadsUpButton, + Position::Unknown, + ]; + let mut labels: Vec<&str> = all.iter().map(|p| p.label()).collect(); + labels.sort_unstable(); + labels.dedup(); + assert_eq!(labels.len(), all.len()); + assert_eq!(Position::Button.label(), "BTN"); +} diff --git a/tests/preflop_situation.rs b/tests/preflop_situation.rs new file mode 100644 index 00000000..7fa6355d --- /dev/null +++ b/tests/preflop_situation.rs @@ -0,0 +1,59 @@ +use pokerfreak::preflop::situation::{classify, Situation}; + +// classify(to_call, big_blind, pot, hero_stack); everything in big blinds (bb = 1.0). + +#[test] +fn unopened_pots() { + assert_eq!(classify(0.5, 1.0, 1.5, 100.0), Situation::Unopened); // small blind + assert_eq!(classify(1.0, 1.0, 1.5, 100.0), Situation::Unopened); // button, blinds only + assert_eq!(classify(0.0, 1.0, 1.5, 100.0), Situation::Unopened); +} + +#[test] +fn limped_pots() { + assert_eq!(classify(1.0, 1.0, 2.5, 100.0), Situation::FacingLimp); + assert_eq!(classify(0.5, 1.0, 3.0, 100.0), Situation::FacingLimp); + assert_eq!(classify(0.0, 1.0, 2.5, 100.0), Situation::FacingLimp); // big blind option +} + +#[test] +fn single_raise() { + assert_eq!(classify(3.0, 1.0, 4.5, 100.0), Situation::FacingOpen); + assert_eq!(classify(2.0, 1.0, 4.5, 100.0), Situation::FacingOpen); // big blind vs 3x + assert_eq!(classify(4.5, 1.0, 6.0, 100.0), Situation::FacingOpen); +} + +#[test] +fn re_raises() { + assert_eq!( + classify(9.0, 1.0, 13.5, 100.0), + Situation::FacingThreeBetPlus + ); + assert_eq!( + classify(6.0, 1.0, 13.5, 100.0), + Situation::FacingThreeBetPlus + ); // opener vs 3-bet + assert_eq!( + classify(20.0, 1.0, 30.0, 100.0), + Situation::FacingThreeBetPlus + ); +} + +#[test] +fn all_in_when_the_call_takes_the_stack() { + assert_eq!(classify(20.0, 1.0, 30.0, 20.0), Situation::FacingAllIn); + assert_eq!(classify(25.0, 1.0, 30.0, 20.0), Situation::FacingAllIn); + assert_eq!(classify(100.0, 1.0, 150.0, 100.0), Situation::FacingAllIn); + assert_ne!(classify(0.0, 1.0, 1.5, 0.0), Situation::FacingAllIn); +} + +#[test] +fn bad_numbers_never_panic() { + assert_eq!(classify(0.0, 0.0, 0.0, 0.0), Situation::Unopened); + let nan = f64::NAN; + let _ = classify(nan, 1.0, 1.5, 10.0); + let _ = classify(1.0, nan, 1.5, 10.0); + let _ = classify(1.0, 1.0, nan, nan); + let _ = classify(f64::INFINITY, 1.0, f64::INFINITY, f64::INFINITY); + let _ = classify(-1.0, -1.0, -1.0, -1.0); +}