From 62db6df752dfa07a2fa1e493873a3f633847fa58 Mon Sep 17 00:00:00 2001 From: Marc Mintel Date: Wed, 28 Oct 2026 11:51:24 +0100 Subject: [PATCH] Add odds, sizing, guard and engine glue with tests Co-Authored-By: Claude Opus 5.5 --- src/engine/decide.rs | 74 ++++++++++- src/engine/from_plan.rs | 48 +++++++ src/engine/mod.rs | 4 + src/engine/options.rs | 50 ++++++++ src/engine/passive.rs | 23 ++++ src/engine/postflop.rs | 92 ++++++++++++++ src/guard/enforce.rs | 16 ++- src/guard/ledger.rs | 15 +++ src/guard/mod.rs | 3 + src/guard/repair.rs | 54 ++++++++ src/guard/settle.rs | 15 +++ src/guard/validate.rs | 97 +++++++++++++- src/odds/bluff.rs | 10 ++ src/odds/break_even.rs | 10 ++ src/odds/ev.rs | 30 +++++ src/odds/fold_equity.rs | 20 +++ src/odds/mod.rs | 8 ++ src/sizing/all_in.rs | 14 +++ src/sizing/allowed.rs | 23 ++++ src/sizing/bounds.rs | 27 ++++ src/sizing/candidates.rs | 26 ++++ src/sizing/fit.rs | 25 ++++ src/sizing/mod.rs | 8 ++ src/sizing/pot_fractions.rs | 10 ++ src/sizing/preflop.rs | 22 ++++ tests/engine_choose_postflop.rs | 139 +++++++++++++++++++++ tests/engine_from_plan.rs | 89 +++++++++++++ tests/engine_property.rs | 215 ++++++++++++++++++++++++++++++++ tests/guard_enforce.rs | 109 ++++++++++++++++ tests/guard_settle.rs | 73 +++++++++++ tests/guard_validate.rs | 145 +++++++++++++++++++++ tests/odds_break_even.rs | 37 ++++++ tests/odds_ev.rs | 72 +++++++++++ tests/sizing_candidates.rs | 130 +++++++++++++++++++ tests/sizing_preflop.rs | 44 +++++++ tests/spot_fixture/mod.rs | 78 ++++++++++++ 36 files changed, 1846 insertions(+), 9 deletions(-) create mode 100644 src/engine/from_plan.rs create mode 100644 src/engine/options.rs create mode 100644 src/engine/passive.rs create mode 100644 src/engine/postflop.rs create mode 100644 src/guard/ledger.rs create mode 100644 src/guard/repair.rs create mode 100644 src/guard/settle.rs create mode 100644 src/odds/bluff.rs create mode 100644 src/odds/break_even.rs create mode 100644 src/odds/ev.rs create mode 100644 src/odds/fold_equity.rs create mode 100644 src/sizing/all_in.rs create mode 100644 src/sizing/allowed.rs create mode 100644 src/sizing/bounds.rs create mode 100644 src/sizing/candidates.rs create mode 100644 src/sizing/fit.rs create mode 100644 src/sizing/pot_fractions.rs create mode 100644 src/sizing/preflop.rs create mode 100644 tests/engine_choose_postflop.rs create mode 100644 tests/engine_from_plan.rs create mode 100644 tests/engine_property.rs create mode 100644 tests/guard_enforce.rs create mode 100644 tests/guard_settle.rs create mode 100644 tests/guard_validate.rs create mode 100644 tests/odds_break_even.rs create mode 100644 tests/odds_ev.rs create mode 100644 tests/sizing_candidates.rs create mode 100644 tests/sizing_preflop.rs create mode 100644 tests/spot_fixture/mod.rs diff --git a/src/engine/decide.rs b/src/engine/decide.rs index c02aa4ed..3853113d 100644 --- a/src/engine/decide.rs +++ b/src/engine/decide.rs @@ -1,7 +1,73 @@ -use crate::game::{Decision, Spot}; +use super::from_plan::from_plan; +use super::passive::cheapest_continue; +use super::postflop::choose_postflop; +use crate::card::Card; +use crate::equity::monte_carlo::estimate; +use crate::equity::query::Query; +use crate::equity::villain_range::VillainRange; +use crate::exploit::adjust::adjust; +use crate::exploit::profile::Profile; +use crate::exploit::range_guess::top_fraction; +use crate::exploit::thresholds::Thresholds; +use crate::game::{Decision, Spot, Street}; +use crate::guard::enforce::enforce; +use crate::preflop::advise::advise; +use crate::preflop::hand_percentile::percentile; +use crate::rng::Rng; -/// Full decision for a validated spot (preflop chart or postflop equity/EV). +const TRIALS_TWO_CARD: u32 = 3000; +const TRIALS_FIVE_CARD: u32 = 1500; + +fn trials(spot: &Spot) -> u32 { + if spot.rules().hole_cards >= 5 { + TRIALS_FIVE_CARD + } else { + TRIALS_TWO_CARD + } +} + +fn postflop(spot: &Spot, thresholds: &Thresholds) -> Decision { + let fractions: Vec = spot.live_villains().map(|v| top_fraction(spot, v)).collect(); + if fractions.is_empty() { + return cheapest_continue(spot).map_or_else( + || Decision::abstain("no live opponent and nothing to continue with"), + |choice| Decision::new(choice, 0.5, "no live opponents: cheapest continuing action"), + ); + } + let variant = spot.variant; + let filters: Vec bool>> = fractions + .into_iter() + .map(|fraction| { + Box::new(move |hand: &[Card]| percentile(variant, hand) <= fraction) + as Box bool> + }) + .collect(); + let ranges: Vec = + filters.iter().map(|f| VillainRange::Filter(f.as_ref())).collect(); + let query = Query { + rules: spot.rules(), + hero: &spot.hero_cards, + board: &spot.board, + villains: &ranges, + trials: trials(spot), + }; + match estimate(&query, Rng::seeded(spot.seed)) { + Ok((equity, _)) => choose_postflop(spot, &equity, thresholds), + Err(fault) => Decision::abstain(format!("equity unavailable: {fault}")), + } +} + +fn think(spot: &Spot) -> Decision { + let profiles: Vec = spot.live_villains().filter_map(|v| v.profile).collect(); + let thresholds = adjust(Thresholds::BASE, &profiles); + match spot.street { + Street::Preflop => from_plan(spot, &advise(spot, &thresholds)), + Street::Flop | Street::Turn | Street::River => postflop(spot, &thresholds), + } +} + +/// Full decision for a validated spot (preflop chart or postflop equity/EV), +/// always passed through `guard::enforce::enforce`. pub fn decide(spot: &Spot) -> Decision { - let _ = spot; - todo!("engine::decide") + enforce(spot, think(spot)) } diff --git a/src/engine/from_plan.rs b/src/engine/from_plan.rs new file mode 100644 index 00000000..b6687796 --- /dev/null +++ b/src/engine/from_plan.rs @@ -0,0 +1,48 @@ +use super::passive::{cheapest_continue, give_up}; +use crate::game::{ActionKind, Choice, Decision, Spot}; +use crate::preflop::plan::{ChartAction, PreflopPlan}; +use crate::sizing::{all_in::all_in, preflop::raise_size}; + +/// Below this chart certainty, a plan that would put chips in is not trusted. +pub const MIN_CERTAINTY: f64 = 0.15; + +fn aggressive(spot: &Spot, size: Option) -> Option { + spot.is_legal(ActionKind::Raise) + .then_some(size) + .flatten() + .map(|to| Choice::Raise { to }) + .or_else(|| cheapest_continue(spot)) + .or_else(|| give_up(spot)) +} + +fn wanted(spot: &Spot, action: ChartAction) -> Option { + match action { + ChartAction::Jam => aggressive(spot, all_in(spot)), + ChartAction::Raise => aggressive(spot, raise_size(spot)), + ChartAction::Call => cheapest_continue(spot).or_else(|| give_up(spot)), + ChartAction::Fold => give_up(spot), + } +} + +/// Maps a chart action through sizing and legality. +/// Jam is all-in, Raise the standard preflop size (both fall back to calling when a +/// raise is impossible), Call calls or checks when free, Fold folds or checks when +/// free. A certainty under [`MIN_CERTAINTY`] turns chip-committing plans into ABSTAIN. +pub fn from_plan(spot: &Spot, plan: &PreflopPlan) -> Decision { + match wanted(spot, plan.action) { + None => Decision::abstain(format!("{}: no legal way to follow the chart", plan.reason)), + Some(choice @ (Choice::Call | Choice::Raise { .. })) if plan.certainty < MIN_CERTAINTY => { + Decision::abstain(format!( + "{}: certainty {:.2} too low to {}", + plan.reason, + plan.certainty, + choice.name().to_lowercase() + )) + } + Some(choice) => Decision::new( + choice, + plan.certainty, + format!("{} -> {}", plan.reason, choice.name().to_lowercase()), + ), + } +} diff --git a/src/engine/mod.rs b/src/engine/mod.rs index 1948d6f1..540cf0b5 100644 --- a/src/engine/mod.rs +++ b/src/engine/mod.rs @@ -1,3 +1,7 @@ //! Engine: composes assessment and choice into a decision. pub mod decide; +pub mod from_plan; +pub mod options; +pub mod passive; +pub mod postflop; diff --git a/src/engine/options.rs b/src/engine/options.rs new file mode 100644 index 00000000..902dbc62 --- /dev/null +++ b/src/engine/options.rs @@ -0,0 +1,50 @@ +use crate::equity::estimate::Estimate; +use crate::exploit::thresholds::Thresholds; +use crate::game::{ActionKind, Choice, Spot}; +use crate::odds::{break_even::break_even, ev, fold_equity::fold_equity}; +use crate::sizing::candidates::candidates; + +/// A legal choice with its expected value in chips (relative to folding now). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Scored { + pub choice: Choice, + pub ev: f64, +} + +/// Every action the breakpoint rule lets hero consider, in preference order +/// (passive first, so ties keep the cheaper line): +/// * check, when legal; +/// * call, when legal and `share >= break_even + call_margin`; +/// * fold, when legal and check is not; +/// * each sizing candidate as a raise, when legal and `share >= value_raise`. +/// +/// Raises are value raises only: the fold-equity term shapes which size is best, it +/// does not license raising a hand below the value threshold. +pub fn scored(spot: &Spot, estimate: &Estimate, thresholds: &Thresholds) -> Vec { + let share = estimate.share; + let free = spot.is_legal(ActionKind::Check); + let be = break_even(spot.pot, spot.to_call); + let live = spot.live_villains().count(); + + let check = free.then(|| Scored { choice: Choice::Check, ev: ev::check(share, spot.pot) }); + let call = (spot.is_legal(ActionKind::Call) && share >= be + thresholds.call_margin) + .then(|| Scored { choice: Choice::Call, ev: ev::call(share, spot.pot, spot.to_call) }); + let fold = (spot.is_legal(ActionKind::Fold) && !free) + .then(|| Scored { choice: Choice::Fold, ev: ev::fold() }); + let raises = (spot.is_legal(ActionKind::Raise) && share >= thresholds.value_raise) + .then(|| candidates(spot)) + .unwrap_or_default() + .into_iter() + .map(|to| { + let fe = fold_equity(spot.pot, to, thresholds.fold_equity_scale, live); + Scored { choice: Choice::Raise { to }, ev: ev::raise(share, spot.pot, spot.to_call, to, fe) } + }); + + check + .into_iter() + .chain(call) + .chain(fold) + .chain(raises) + .filter(|s| s.ev.is_finite()) + .collect() +} diff --git a/src/engine/passive.rs b/src/engine/passive.rs new file mode 100644 index 00000000..d7532e57 --- /dev/null +++ b/src/engine/passive.rs @@ -0,0 +1,23 @@ +use crate::game::{ActionKind, Choice, Spot}; + +/// The cheapest way to stay in the hand: check when free, else call. +pub fn cheapest_continue(spot: &Spot) -> Option { + if spot.is_legal(ActionKind::Check) { + Some(Choice::Check) + } else if spot.is_legal(ActionKind::Call) { + Some(Choice::Call) + } else { + None + } +} + +/// The way to give up: check when that is free, else fold. +pub fn give_up(spot: &Spot) -> Option { + if spot.is_legal(ActionKind::Check) { + Some(Choice::Check) + } else if spot.is_legal(ActionKind::Fold) { + Some(Choice::Fold) + } else { + None + } +} diff --git a/src/engine/postflop.rs b/src/engine/postflop.rs new file mode 100644 index 00000000..95dcb5a2 --- /dev/null +++ b/src/engine/postflop.rs @@ -0,0 +1,92 @@ +use super::options::{scored, Scored}; +use super::passive::cheapest_continue; +use crate::equity::estimate::Estimate; +use crate::exploit::thresholds::Thresholds; +use crate::game::{ActionKind, Choice, Decision, Spot}; +use crate::odds::{break_even::break_even, ev}; + +fn label(choice: Choice) -> String { + match choice { + Choice::Raise { to } => format!("raise to {to:.2}"), + other => other.name().to_lowercase(), + } +} + +/// Highest EV wins; the first of equals wins (options are ordered passive first). +fn best(options: &[Scored]) -> Option { + options.iter().copied().fold(None, |acc, s| match acc { + Some(b) if b.ev >= s.ev => Some(b), + _ => Some(s), + }) +} + +/// EV lead of the winner over the next-best alternative, counting folding (0) and the +/// call it passed up. +fn lead(spot: &Spot, share: f64, options: &[Scored], winner: Scored) -> f64 { + let rivals = options + .iter() + .filter(|s| s.choice != winner.choice) + .map(|s| s.ev) + .chain((winner.choice != Choice::Fold).then(ev::fold)) + .chain( + (winner.choice == Choice::Fold && spot.is_legal(ActionKind::Call)) + .then(|| ev::call(share, spot.pot, spot.to_call)), + ); + rivals.fold(None, |m: Option, x| Some(m.map_or(x, |m| m.max(x)))).map_or(winner.ev.abs(), |r| winner.ev - r) +} + +fn confidence(spot: &Spot, gap: f64) -> f64 { + let scale = (spot.pot + spot.to_call).max(spot.big_blind).max(f64::MIN_POSITIVE); + 0.5 + 0.5 * (4.0 * gap.max(0.0) / scale).tanh() +} + +/// The breakpoint rule for a postflop spot, given an equity estimate. +/// +/// 1. Uncertain equity, or `|share - break-even| < abstain_band + 2 * std_error` while +/// facing a real fold/call choice: ABSTAIN. +/// 2. Otherwise score check / call / fold / value raises (see `options::scored`) and +/// take the maximum EV. Never folds when check is legal. +/// 3. `confidence` rises with the EV lead over the runner-up, relative to the pot. +pub fn choose_postflop(spot: &Spot, estimate: &Estimate, thresholds: &Thresholds) -> Decision { + let share = estimate.share; + if !(share.is_finite() && (0.0..=1.0).contains(&share)) { + return Decision::abstain("equity unavailable"); + } + let be = break_even(spot.pot, spot.to_call); + let band = thresholds.abstain_band + 2.0 * estimate.std_error.max(0.0); + let facing_choice = spot.is_legal(ActionKind::Fold) + && spot.is_legal(ActionKind::Call) + && !spot.is_legal(ActionKind::Check); + if facing_choice && (share - be).abs() < band { + return Decision::abstain(format!( + "equity {share:.2} vs break-even {be:.2}: inside uncertainty band {band:.3}" + )); + } + + let options = scored(spot, estimate, thresholds); + match best(&options) { + Some(winner) => { + let shown = match winner.choice { + Choice::Fold => ev::call(share, spot.pot, spot.to_call), + _ => winner.ev, + }; + let name = match winner.choice { + Choice::Fold => "call".to_string(), + other => label(other), + }; + Decision::new( + winner.choice, + confidence(spot, lead(spot, share, &options, winner)), + format!("equity {share:.2} vs break-even {be:.2}, EV {name} {shown:+.2}"), + ) + } + None => match cheapest_continue(spot) { + Some(choice) => Decision::new( + choice, + 0.5, + format!("equity {share:.2} vs break-even {be:.2}, only continuing action available"), + ), + None => Decision::abstain("no actionable option"), + }, + } +} diff --git a/src/guard/enforce.rs b/src/guard/enforce.rs index 56a4fdd2..49137173 100644 --- a/src/guard/enforce.rs +++ b/src/guard/enforce.rs @@ -1,7 +1,19 @@ +use super::repair::{repair, Repair}; use crate::game::{Decision, Spot}; /// Last line of defence: the returned decision is legal for `spot` or it is ABSTAIN. +/// Repairs (fold to check, raise size snapped or clamped) are noted in the reason; +/// anything unrepairable becomes ABSTAIN with zero confidence. pub fn enforce(spot: &Spot, decision: Decision) -> Decision { - let _ = (spot, decision); - todo!("guard::enforce") + match repair(spot, decision.choice) { + Repair::Kept(choice) => Decision { choice, ..decision }, + Repair::Changed(choice, note) => Decision { + choice, + reason: format!("{} [enforced: {note}]", decision.reason), + ..decision + }, + Repair::Refused(why) => { + Decision::abstain(format!("{} [enforced: {why}]", decision.reason)) + } + } } diff --git a/src/guard/ledger.rs b/src/guard/ledger.rs new file mode 100644 index 00000000..3297fcfc --- /dev/null +++ b/src/guard/ledger.rs @@ -0,0 +1,15 @@ +/// Hero's stack and the pot after an action. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Ledger { + pub stack: f64, + pub pot: f64, +} + +impl Ledger { + /// Moves `amount` from the stack into the pot, never more than the stack holds and + /// never anything for a non-finite or non-positive amount. + pub fn pay(self, amount: f64) -> Ledger { + let paid = if amount.is_finite() { amount.max(0.0).min(self.stack.max(0.0)) } else { 0.0 }; + Ledger { stack: self.stack - paid, pot: self.pot + paid } + } +} diff --git a/src/guard/mod.rs b/src/guard/mod.rs index 5d6450ab..f2773ade 100644 --- a/src/guard/mod.rs +++ b/src/guard/mod.rs @@ -1,4 +1,7 @@ //! Guards: validate requests before thinking, enforce legality after thinking. pub mod enforce; +pub mod ledger; +pub mod repair; +pub mod settle; pub mod validate; diff --git a/src/guard/repair.rs b/src/guard/repair.rs new file mode 100644 index 00000000..eeaacb5b --- /dev/null +++ b/src/guard/repair.rs @@ -0,0 +1,54 @@ +use crate::game::{ActionKind, Choice, Spot}; +use crate::sizing::fit::fit; +use crate::variant::ActionShape; + +/// What became of a choice: kept as is, changed (with a note), or unsalvageable. +#[derive(Clone, Debug, PartialEq)] +pub enum Repair { + Kept(Choice), + Changed(Choice, String), + Refused(String), +} + +fn raise(spot: &Spot, to: f64) -> Repair { + if spot.hero_stack <= 0.0 { + return Repair::Refused("RAISE impossible: no chips behind".to_string()); + } + match fit(spot, to) { + Some(size) if size == to => Repair::Kept(Choice::Raise { to }), + Some(size) => Repair::Changed( + Choice::Raise { to: size }, + format!("raise size {to} adjusted to {size}"), + ), + None => Repair::Refused(format!("RAISE size {to} cannot be made legal")), + } +} + +fn binary_call(spot: &Spot) -> Repair { + if spot.to_call >= spot.hero_stack { + Repair::Kept(Choice::Call) + } else { + Repair::Refused("CALL is neither give-up nor all-in in a binary game".to_string()) + } +} + +/// Brings a choice into legal shape for `spot`, or refuses it. +pub fn repair(spot: &Spot, choice: Choice) -> Repair { + let check_free = spot.is_legal(ActionKind::Check); + match choice { + Choice::Abstain => Repair::Kept(Choice::Abstain), + Choice::Fold if check_free => { + Repair::Changed(Choice::Check, "FOLD replaced by free CHECK".to_string()) + } + other => match other.kind() { + Some(kind) if !spot.is_legal(kind) => { + Repair::Refused(format!("{} is not in legalActions", kind.name())) + } + _ => match other { + Choice::Raise { to } => raise(spot, to), + Choice::Call if spot.rules().shape == ActionShape::Binary => binary_call(spot), + kept => Repair::Kept(kept), + }, + }, + } +} diff --git a/src/guard/settle.rs b/src/guard/settle.rs new file mode 100644 index 00000000..998d78dd --- /dev/null +++ b/src/guard/settle.rs @@ -0,0 +1,15 @@ +use super::ledger::Ledger; +use crate::game::{Choice, Spot}; + +/// Applies a choice to hero's stack and the pot. Chips are conserved +/// (`stack + pot` is unchanged) and the stack never goes negative. +/// Nothing is committed beforehand, so a raise to X moves X chips, a call moves +/// `to_call`; both are capped by the stack (an all-in at most). +pub fn settle(spot: &Spot, choice: Choice) -> Ledger { + let before = Ledger { stack: spot.hero_stack.max(0.0), pot: spot.pot }; + match choice { + Choice::Call => before.pay(spot.to_call), + Choice::Raise { to } => before.pay(to), + Choice::Fold | Choice::Check | Choice::Abstain => before, + } +} diff --git a/src/guard/validate.rs b/src/guard/validate.rs index 198b210e..932e288a 100644 --- a/src/guard/validate.rs +++ b/src/guard/validate.rs @@ -1,8 +1,99 @@ use crate::fault::Fault; -use crate::game::Spot; +use crate::game::{ActionKind, Spot}; + +fn invalid(field: &str, detail: &str) -> Fault { + Fault::Invalid { field: field.to_string(), detail: detail.to_string() } +} + +fn chip(field: &str, value: f64) -> Result<(), Fault> { + if value.is_finite() && value >= 0.0 { + Ok(()) + } else { + Err(invalid(field, "must be a finite, non-negative amount")) + } +} + +fn optional_chip(field: &str, value: Option) -> Result<(), Fault> { + value.map_or(Ok(()), |v| chip(field, v)) +} + +fn has_duplicates(items: &[T]) -> bool { + items.iter().enumerate().any(|(i, a)| items[..i].contains(a)) +} + +fn cards(spot: &Spot) -> Result<(), Fault> { + let hole = spot.rules().hole_cards; + if spot.hero_cards.len() != hole { + return Err(invalid( + "heroCards", + &format!("expected {hole} cards for {}, got {}", spot.variant.name(), spot.hero_cards.len()), + )); + } + let board = spot.street.board_len(); + if spot.board.len() != board { + return Err(invalid( + "board", + &format!("expected {board} cards on {}, got {}", spot.street.name(), spot.board.len()), + )); + } + let all: Vec<_> = spot.hero_cards.iter().chain(spot.board.iter()).collect(); + if has_duplicates(&all) { + return Err(invalid("cards", "duplicate card across heroCards and board")); + } + Ok(()) +} + +fn chips(spot: &Spot) -> Result<(), Fault> { + if !(spot.big_blind.is_finite() && spot.big_blind > 0.0) { + return Err(invalid("bigBlind", "must be a finite, positive amount")); + } + chip("pot", spot.pot)?; + chip("toCall", spot.to_call)?; + chip("heroStack", spot.hero_stack)?; + optional_chip("minRaiseTo", spot.min_raise_to)?; + optional_chip("maxRaiseTo", spot.max_raise_to)?; + if let (Some(min), Some(max)) = (spot.min_raise_to, spot.max_raise_to) { + if min > max { + return Err(invalid("minRaiseTo", "exceeds maxRaiseTo")); + } + } + if let Some(sizes) = &spot.allowed_sizes { + if sizes.iter().any(|s| !(s.is_finite() && *s > 0.0)) { + return Err(invalid("allowedSizes", "every size must be finite and positive")); + } + } + spot.villains.iter().try_for_each(|v| chip("villains.stack", v.stack)) +} + +fn actions(spot: &Spot) -> Result<(), Fault> { + if spot.legal.is_empty() { + return Err(invalid("legalActions", "empty")); + } + if has_duplicates(&spot.legal) { + return Err(invalid("legalActions", "duplicate entry")); + } + if !(2..=10).contains(&spot.seats) { + return Err(invalid("seats", "must be between 2 and 10")); + } + if spot.is_legal(ActionKind::Check) && spot.to_call > 0.0 { + return Err(Fault::Inconsistent("CHECK legal while toCall > 0".to_string())); + } + let sizeable = spot.allowed_sizes.as_ref().map_or(false, |s| !s.is_empty()) + || spot.min_raise_to.is_some() + || spot.max_raise_to.is_some() + || spot.hero_stack > 0.0; + if spot.is_legal(ActionKind::Raise) && !sizeable { + return Err(Fault::Inconsistent( + "RAISE legal but no way to size it (no allowedSizes, no bounds, no stack)".to_string(), + )); + } + Ok(()) +} /// Consistency check of a decoded spot (cards, counts, chips, sizes, legal actions). pub fn check(spot: Spot) -> Result { - let _ = spot; - todo!("guard::validate") + cards(&spot)?; + chips(&spot)?; + actions(&spot)?; + Ok(spot) } diff --git a/src/odds/bluff.rs b/src/odds/bluff.rs new file mode 100644 index 00000000..9f1c00a0 --- /dev/null +++ b/src/odds/bluff.rs @@ -0,0 +1,10 @@ +/// Fold frequency a pure bluff needs to break even when risking `added` into `pot`: +/// `added / (pot + added)`. Total: degenerate input yields 0. +pub fn bluff_break_even(pot: f64, added: f64) -> f64 { + let total = pot + added; + if pot.is_finite() && added.is_finite() && added > 0.0 && total > 0.0 { + added / total + } else { + 0.0 + } +} diff --git a/src/odds/break_even.rs b/src/odds/break_even.rs new file mode 100644 index 00000000..dfebb1f2 --- /dev/null +++ b/src/odds/break_even.rs @@ -0,0 +1,10 @@ +/// Equity share needed for a call to break even: `to_call / (pot + to_call)`. +/// Total: degenerate input (non-finite, negative, empty denominator) yields 0. +pub fn break_even(pot: f64, to_call: f64) -> f64 { + let total = pot + to_call; + if pot.is_finite() && to_call.is_finite() && to_call > 0.0 && total > 0.0 { + to_call / total + } else { + 0.0 + } +} diff --git a/src/odds/ev.rs b/src/odds/ev.rs new file mode 100644 index 00000000..00b20cc6 --- /dev/null +++ b/src/odds/ev.rs @@ -0,0 +1,30 @@ +//! Expected value per action, in chips, relative to folding now (fold = 0). +//! +//! Approximations (documented, deliberate): +//! * Hero has nothing committed on this street, so a raise "to X" adds X chips. +//! * If a raise is called, exactly one villain calls and adds `X - to_call` +//! (the existing bet is already in the pot); the rest fold. +//! * `share` (equity) is realised in full; no later-street betting is modelled. + +/// Folding is the reference point. +pub fn fold() -> f64 { + 0.0 +} + +/// Free check: hero keeps `share` of the current pot. +pub fn check(share: f64, pot: f64) -> f64 { + share * pot +} + +/// Call: `share * (pot + to_call) - to_call`. +pub fn call(share: f64, pot: f64, to_call: f64) -> f64 { + share * (pot + to_call) - to_call +} + +/// Raise adding `added` chips, with fold probability `fe`: +/// `fe * pot + (1 - fe) * (share * final_pot - added)` where +/// `final_pot = pot + added + max(added - to_call, 0)`. +pub fn raise(share: f64, pot: f64, to_call: f64, added: f64, fe: f64) -> f64 { + let final_pot = pot + added + (added - to_call).max(0.0); + fe * pot + (1.0 - fe) * (share * final_pot - added) +} diff --git a/src/odds/fold_equity.rs b/src/odds/fold_equity.rs new file mode 100644 index 00000000..14300736 --- /dev/null +++ b/src/odds/fold_equity.rs @@ -0,0 +1,20 @@ +use super::bluff::bluff_break_even; + +/// Largest fold probability the model ever assumes for a single opponent. +pub const PER_VILLAIN_CAP: f64 = 0.95; + +/// Estimated probability that every live villain folds to a raise that adds `added` +/// chips to `pot`. +/// +/// One villain folds with `added / (pot + added)` (the bet as a pot fraction, i.e. +/// the bluff break-even), times `scale` (`Thresholds::fold_equity_scale`), capped at +/// [`PER_VILLAIN_CAP`]. Villains are treated as independent, so the probabilities +/// multiply. No live villain (or non-finite input) means no model: 0. +pub fn fold_equity(pot: f64, added: f64, scale: f64, villains: usize) -> f64 { + let single = (bluff_break_even(pot, added) * scale).clamp(0.0, PER_VILLAIN_CAP); + if villains == 0 || !single.is_finite() { + 0.0 + } else { + single.powi(villains.min(i32::MAX as usize) as i32) + } +} diff --git a/src/odds/mod.rs b/src/odds/mod.rs index 3a2f36d5..330878c3 100644 --- a/src/odds/mod.rs +++ b/src/odds/mod.rs @@ -1 +1,9 @@ //! Pot odds, break-even points and expected value per action. +//! +//! Convention (see `game::spot`): `pot` already contains the villains' bets, +//! `to_call` is what hero must add. All EVs are measured relative to folding now. + +pub mod bluff; +pub mod break_even; +pub mod ev; +pub mod fold_equity; diff --git a/src/sizing/all_in.rs b/src/sizing/all_in.rs new file mode 100644 index 00000000..29f02e54 --- /dev/null +++ b/src/sizing/all_in.rs @@ -0,0 +1,14 @@ +use super::allowed::valid_allowed; +use super::bounds::bounds; +use crate::game::Spot; + +/// The jam size: with `allowed_sizes`, the largest usable entry; otherwise +/// `min(max_raise_to, hero_stack)` (the stack when no max). `None` when that is not +/// a legal raise size (no chips, or below `min_raise_to`). For pot-limit variants +/// the "jam" is the pot-sized raise when that is smaller than the stack. +pub fn all_in(spot: &Spot) -> Option { + match valid_allowed(spot) { + Some(sizes) => sizes.last().copied(), + None => bounds(spot).map(|b| b.hi), + } +} diff --git a/src/sizing/allowed.rs b/src/sizing/allowed.rs new file mode 100644 index 00000000..8a09dde9 --- /dev/null +++ b/src/sizing/allowed.rs @@ -0,0 +1,23 @@ +use crate::game::Spot; + +/// The entries of `allowed_sizes` hero may actually use, verbatim and ascending: +/// finite, positive, affordable, inside `[min_raise_to, max_raise_to]` when given. +/// `None` when the spot has no `allowed_sizes` at all. +pub fn valid_allowed(spot: &Spot) -> Option> { + spot.allowed_sizes.as_ref().map(|sizes| { + let mut usable: Vec = sizes + .iter() + .copied() + .filter(|s| { + s.is_finite() + && *s > 0.0 + && *s <= spot.hero_stack + && spot.min_raise_to.map_or(true, |min| *s >= min) + && spot.max_raise_to.map_or(true, |max| *s <= max) + }) + .collect(); + usable.sort_by(f64::total_cmp); + usable.dedup(); + usable + }) +} diff --git a/src/sizing/bounds.rs b/src/sizing/bounds.rs new file mode 100644 index 00000000..27343806 --- /dev/null +++ b/src/sizing/bounds.rs @@ -0,0 +1,27 @@ +use crate::game::Spot; +use crate::variant::SizingRule; + +/// Inclusive range a free-form raise-to size may take. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Bounds { + pub lo: f64, + pub hi: f64, +} + +impl Bounds { + pub fn clamp(self, x: f64) -> f64 { + x.max(self.lo).min(self.hi) + } +} + +/// `[min_raise_to, min(max_raise_to, hero_stack)]`; pot-limit rules also cap at a +/// pot-sized raise (`pot + 2 * to_call`). `None` when no positive size fits. +pub fn bounds(spot: &Spot) -> Option { + let lo = spot.min_raise_to.unwrap_or(0.0).max(0.0); + let capped = spot.max_raise_to.unwrap_or(f64::INFINITY).min(spot.hero_stack); + let hi = match spot.rules().sizing { + SizingRule::PotLimit => capped.min(spot.pot + 2.0 * spot.to_call), + _ => capped, + }; + (lo.is_finite() && hi > 0.0 && lo <= hi).then_some(Bounds { lo, hi }) +} diff --git a/src/sizing/candidates.rs b/src/sizing/candidates.rs new file mode 100644 index 00000000..b4a99a08 --- /dev/null +++ b/src/sizing/candidates.rs @@ -0,0 +1,26 @@ +use super::all_in::all_in; +use super::allowed::valid_allowed; +use super::bounds::bounds; +use super::pot_fractions::{raise_to, FRACTIONS}; +use crate::game::Spot; +use crate::variant::SizingRule; + +/// Raise-to sizes worth evaluating, ascending and distinct. Driven by +/// `spot.rules().sizing`; `allowed_sizes`, when present, is the only source. +pub fn candidates(spot: &Spot) -> Vec { + if let Some(sizes) = valid_allowed(spot) { + return sizes; + } + match spot.rules().sizing { + SizingRule::AllInOnly => all_in(spot).into_iter().collect(), + SizingRule::NoLimit | SizingRule::PotLimit | SizingRule::Menu => { + let mut sizes: Vec = bounds(spot) + .map(|b| FRACTIONS.iter().map(|f| b.clamp(raise_to(spot, *f))).collect()) + .unwrap_or_default(); + sizes.retain(|s| s.is_finite() && *s > 0.0); + sizes.sort_by(f64::total_cmp); + sizes.dedup_by(|a, b| (*a - *b).abs() < 1e-12); + sizes + } + } +} diff --git a/src/sizing/fit.rs b/src/sizing/fit.rs new file mode 100644 index 00000000..f65cc7bd --- /dev/null +++ b/src/sizing/fit.rs @@ -0,0 +1,25 @@ +use super::all_in::all_in; +use super::allowed::valid_allowed; +use super::bounds::bounds; +use crate::game::Spot; +use crate::variant::{ActionShape, SizingRule}; + +/// Turns a wished raise-to size into one hero may legally play, or `None`. +/// * `allowed_sizes`: the nearest usable entry, verbatim (the lower one on ties). +/// * binary / all-in-only rules: the jam. +/// * otherwise: the target clamped into the bounds. +pub fn fit(spot: &Spot, target: f64) -> Option { + if !target.is_finite() { + return None; + } + if let Some(sizes) = valid_allowed(spot) { + return sizes + .into_iter() + .min_by(|a, b| (a - target).abs().total_cmp(&(b - target).abs())); + } + let rules = spot.rules(); + if rules.shape == ActionShape::Binary || rules.sizing == SizingRule::AllInOnly { + return all_in(spot); + } + bounds(spot).map(|b| b.clamp(target)).filter(|s| *s > 0.0) +} diff --git a/src/sizing/mod.rs b/src/sizing/mod.rs index 93c52a73..cbf81def 100644 --- a/src/sizing/mod.rs +++ b/src/sizing/mod.rs @@ -1 +1,9 @@ //! Raise-size candidates per sizing rule; `allowedSizes` always wins. + +pub mod all_in; +pub mod allowed; +pub mod bounds; +pub mod candidates; +pub mod fit; +pub mod pot_fractions; +pub mod preflop; diff --git a/src/sizing/pot_fractions.rs b/src/sizing/pot_fractions.rs new file mode 100644 index 00000000..baac014e --- /dev/null +++ b/src/sizing/pot_fractions.rs @@ -0,0 +1,10 @@ +use crate::game::Spot; + +/// Pot fractions offered for free-form sizing. +pub const FRACTIONS: [f64; 3] = [1.0 / 3.0, 2.0 / 3.0, 1.0]; + +/// Raise-to for a bet of `fraction` of the pot after hero calls: +/// `to_call + fraction * (pot + to_call)`. +pub fn raise_to(spot: &Spot, fraction: f64) -> f64 { + spot.to_call + fraction * (spot.pot + spot.to_call) +} diff --git a/src/sizing/preflop.rs b/src/sizing/preflop.rs new file mode 100644 index 00000000..de730929 --- /dev/null +++ b/src/sizing/preflop.rs @@ -0,0 +1,22 @@ +use super::fit::fit; +use crate::game::Spot; + +/// Open size in big blinds when nobody has raised yet. +pub const OPEN_BB: f64 = 2.5; +/// Multiplier on the bet faced for a re-raise. +pub const RERAISE_FACTOR: f64 = 3.0; + +/// Wished preflop raise-to: `2.5 bb` when only blinds/limps are faced +/// (`to_call <= big_blind`), else `3 x` the amount to call. +pub fn raise_target(spot: &Spot) -> f64 { + if spot.to_call <= spot.big_blind { + OPEN_BB * spot.big_blind + } else { + RERAISE_FACTOR * spot.to_call + } +} + +/// The chart `Raise` as a legal size (bounds / allowed sizes applied). +pub fn raise_size(spot: &Spot) -> Option { + fit(spot, raise_target(spot)) +} diff --git a/tests/engine_choose_postflop.rs b/tests/engine_choose_postflop.rs new file mode 100644 index 00000000..6663e8a8 --- /dev/null +++ b/tests/engine_choose_postflop.rs @@ -0,0 +1,139 @@ +mod spot_fixture; + +use pokerfreak::engine::postflop::choose_postflop; +use pokerfreak::exploit::thresholds::Thresholds; +use pokerfreak::game::{ActionKind, Choice, Spot}; +use pokerfreak::sizing::candidates::candidates; +use spot_fixture::*; + +const BASE: Thresholds = Thresholds::BASE; + +// round_flop: pot 10, 5 to call -> break-even exactly 1/3. + +#[test] +fn clear_call_when_equity_beats_the_price() { + let d = choose_postflop(&round_flop(), &estimate(0.45, 0.005), &BASE); + assert_eq!(d.choice, Choice::Call); + assert!(d.reason.contains("equity 0.45"), "{}", d.reason); + assert!(d.reason.contains("break-even 0.33"), "{}", d.reason); + assert!(d.reason.contains("EV"), "{}", d.reason); +} + +#[test] +fn clear_fold_when_equity_is_far_below_the_price() { + let d = choose_postflop(&round_flop(), &estimate(0.15, 0.005), &BASE); + assert_eq!(d.choice, Choice::Fold); +} + +#[test] +fn abstains_near_the_breakpoint() { + let d = choose_postflop(&round_flop(), &estimate(0.34, 0.005), &BASE); + assert_eq!(d.choice, Choice::Abstain); + assert_eq!(d.confidence.value(), 0.0); +} + +#[test] +fn abstain_band_widens_with_the_standard_error() { + let noisy = choose_postflop(&round_flop(), &estimate(0.36, 0.02), &BASE); + assert_eq!(noisy.choice, Choice::Abstain); + let tight = choose_postflop(&round_flop(), &estimate(0.36, 0.001), &BASE); + assert_eq!(tight.choice, Choice::Call); +} + +#[test] +fn call_margin_is_required_above_break_even() { + let thresholds = Thresholds { abstain_band: 0.0, call_margin: 0.05, ..BASE }; + // 0.36 is above break-even (0.333) but below break-even + margin (0.383) + let d = choose_postflop(&round_flop(), &estimate(0.36, 0.0), &thresholds); + assert_eq!(d.choice, Choice::Fold); +} + +#[test] +fn value_raise_when_equity_is_high() { + let spot = round_flop(); + let d = choose_postflop(&spot, &estimate(0.80, 0.005), &BASE); + match d.choice { + Choice::Raise { to } => assert!(candidates(&spot).contains(&to), "{to}"), + other => panic!("expected a raise, got {other:?}"), + } +} + +#[test] +fn no_raise_below_the_value_threshold() { + let d = choose_postflop(&round_flop(), &estimate(0.50, 0.005), &BASE); + assert_eq!(d.choice, Choice::Call); +} + +#[test] +fn value_threshold_comes_from_the_thresholds() { + let eager = Thresholds { value_raise: 0.45, ..BASE }; + let d = choose_postflop(&round_flop(), &estimate(0.50, 0.005), &eager); + assert!(matches!(d.choice, Choice::Raise { .. }), "{d:?}"); +} + +#[test] +fn checks_when_free_and_weak() { + let spot = Spot { to_call: 0.0, legal: vec![ActionKind::Check, ActionKind::Raise], ..round_flop() }; + let d = choose_postflop(&spot, &estimate(0.30, 0.005), &BASE); + assert_eq!(d.choice, Choice::Check); +} + +#[test] +fn raises_when_free_and_strong() { + let spot = Spot { to_call: 0.0, legal: vec![ActionKind::Check, ActionKind::Raise], ..round_flop() }; + let d = choose_postflop(&spot, &estimate(0.90, 0.005), &BASE); + assert!(matches!(d.choice, Choice::Raise { .. }), "{d:?}"); +} + +#[test] +fn never_folds_when_check_is_legal() { + let spot = Spot { + to_call: 0.0, + legal: vec![ActionKind::Fold, ActionKind::Check], + ..round_flop() + }; + for share in [0.0, 0.05, 0.3, 0.9] { + let d = choose_postflop(&spot, &estimate(share, 0.005), &BASE); + assert_eq!(d.choice, Choice::Check, "share {share}"); + } +} + +#[test] +fn call_when_fold_and_check_are_not_available() { + let spot = Spot { legal: vec![ActionKind::Call], ..round_flop() }; + let d = choose_postflop(&spot, &estimate(0.10, 0.005), &BASE); + assert_eq!(d.choice, Choice::Call); +} + +#[test] +fn raises_come_from_allowed_sizes_verbatim() { + let spot = Spot { allowed_sizes: Some(vec![20.0, 40.0]), ..round_flop() }; + let d = choose_postflop(&spot, &estimate(0.85, 0.005), &BASE); + match d.choice { + Choice::Raise { to } => assert!(to == 20.0 || to == 40.0, "{to}"), + other => panic!("expected a raise, got {other:?}"), + } +} + +#[test] +fn raise_without_candidates_falls_back_to_the_passive_line() { + let spot = Spot { allowed_sizes: Some(vec![500.0]), ..round_flop() }; + let d = choose_postflop(&spot, &estimate(0.85, 0.005), &BASE); + assert_eq!(d.choice, Choice::Call); +} + +#[test] +fn non_finite_equity_abstains() { + let d = choose_postflop(&round_flop(), &estimate(f64::NAN, 0.0), &BASE); + assert_eq!(d.choice, Choice::Abstain); +} + +#[test] +fn confidence_grows_with_distance_from_the_breakpoint() { + let near = choose_postflop(&round_flop(), &estimate(0.40, 0.001), &BASE); + let far = choose_postflop(&round_flop(), &estimate(0.55, 0.001), &BASE); + assert_eq!(near.choice, Choice::Call); + assert_eq!(far.choice, Choice::Call); + assert!(far.confidence > near.confidence); + assert!(far.confidence.value() <= 1.0 && near.confidence.value() > 0.0); +} diff --git a/tests/engine_from_plan.rs b/tests/engine_from_plan.rs new file mode 100644 index 00000000..03f27bbe --- /dev/null +++ b/tests/engine_from_plan.rs @@ -0,0 +1,89 @@ +mod spot_fixture; + +use pokerfreak::engine::from_plan::from_plan; +use pokerfreak::game::{ActionKind, Choice, Spot}; +use pokerfreak::preflop::plan::ChartAction; +use spot_fixture::*; + +fn free_spot() -> Spot { + Spot { + to_call: 0.0, + legal: vec![ActionKind::Check, ActionKind::Raise], + ..preflop() + } +} + +fn choice(spot: &Spot, action: ChartAction, certainty: f64) -> Choice { + from_plan(spot, &plan(action, certainty)).choice +} + +#[test] +fn jam_is_all_in() { + assert_eq!(choice(&preflop(), ChartAction::Jam, 1.0), Choice::Raise { to: 10.0 }); +} + +#[test] +fn raise_uses_the_preflop_size() { + match choice(&preflop(), ChartAction::Raise, 1.0) { + Choice::Raise { to } => assert!((to - 0.25).abs() < 1e-9), + other => panic!("{other:?}"), + } +} + +#[test] +fn raise_snaps_to_allowed_sizes() { + let spot = Spot { allowed_sizes: Some(vec![0.2, 0.5, 1.0]), ..preflop() }; + assert_eq!(choice(&spot, ChartAction::Raise, 1.0), Choice::Raise { to: 0.2 }); +} + +#[test] +fn call_calls_or_checks_when_free() { + assert_eq!(choice(&preflop(), ChartAction::Call, 1.0), Choice::Call); + assert_eq!(choice(&free_spot(), ChartAction::Call, 1.0), Choice::Check); +} + +#[test] +fn fold_folds_or_checks_when_free() { + assert_eq!(choice(&preflop(), ChartAction::Fold, 1.0), Choice::Fold); + assert_eq!(choice(&free_spot(), ChartAction::Fold, 1.0), Choice::Check); +} + +#[test] +fn jam_without_raise_falls_back_to_a_call() { + let spot = Spot { legal: vec![ActionKind::Fold, ActionKind::Call], ..preflop() }; + assert_eq!(choice(&spot, ChartAction::Jam, 1.0), Choice::Call); + assert_eq!(choice(&spot, ChartAction::Raise, 1.0), Choice::Call); +} + +#[test] +fn unsizeable_raise_falls_back_to_passive() { + let spot = Spot { hero_stack: 0.15, ..preflop() }; + assert_eq!(choice(&spot, ChartAction::Raise, 1.0), Choice::Call); +} + +#[test] +fn low_certainty_abstains_when_chips_would_go_in() { + assert_eq!(choice(&preflop(), ChartAction::Raise, 0.05), Choice::Abstain); + assert_eq!(choice(&preflop(), ChartAction::Call, 0.05), Choice::Abstain); + assert_eq!(choice(&preflop(), ChartAction::Jam, 0.05), Choice::Abstain); +} + +#[test] +fn low_certainty_never_blocks_a_free_check_or_a_fold() { + assert_eq!(choice(&free_spot(), ChartAction::Call, 0.0), Choice::Check); + assert_eq!(choice(&preflop(), ChartAction::Fold, 0.0), Choice::Fold); +} + +#[test] +fn reason_mentions_the_chart_and_confidence_follows_certainty() { + let sure = from_plan(&preflop(), &plan(ChartAction::Raise, 1.0)); + let unsure = from_plan(&preflop(), &plan(ChartAction::Raise, 0.4)); + assert!(sure.reason.contains("chart"), "{}", sure.reason); + assert!(sure.confidence > unsure.confidence); +} + +#[test] +fn nothing_legal_to_do_abstains() { + let spot = Spot { legal: vec![ActionKind::Raise], hero_stack: 0.0, ..preflop() }; + assert_eq!(choice(&spot, ChartAction::Call, 1.0), Choice::Abstain); +} diff --git a/tests/engine_property.rs b/tests/engine_property.rs new file mode 100644 index 00000000..bf80f3f5 --- /dev/null +++ b/tests/engine_property.rs @@ -0,0 +1,215 @@ +mod spot_fixture; + +use pokerfreak::card::deck; +use pokerfreak::engine::from_plan::from_plan; +use pokerfreak::engine::postflop::choose_postflop; +use pokerfreak::equity::estimate::Estimate; +use pokerfreak::exploit::thresholds::Thresholds; +use pokerfreak::game::{ActionKind, Choice, Decision, Spot, Street, Villain}; +use pokerfreak::guard::enforce::enforce; +use pokerfreak::guard::settle::settle; +use pokerfreak::preflop::plan::{ChartAction, PreflopPlan}; +use pokerfreak::rng::Rng; +use pokerfreak::variant::{ActionShape, Variant}; + +const CASES: usize = 3000; + +/// Tiny generator monad over the seeded Rng: each draw returns the value and the next Rng. +fn unit(rng: Rng) -> (f64, Rng) { + rng.unit() +} + +fn below(rng: Rng, bound: u64) -> (u64, Rng) { + rng.below(bound) +} + +fn chips(rng: Rng, scale: f64) -> (f64, Rng) { + let (kind, rng) = below(rng, 12); + let (x, rng) = unit(rng); + let value = match kind { + 0 => 0.0, + 1 => 0.01 * x, + _ => (x * scale * 100.0).round() / 100.0, + }; + (value, rng) +} + +fn subset_of_legal(rng: Rng) -> (Vec, Rng) { + let (mask, rng) = below(rng, 15); + let kinds: Vec = ActionKind::ALL + .iter() + .enumerate() + .filter(|(i, _)| (mask + 1) >> i & 1 == 1) + .map(|(_, k)| *k) + .collect(); + (kinds, rng) +} + +fn allowed_list(rng: Rng) -> (Option>, Rng) { + let (on, rng) = below(rng, 2); + if on == 0 { + return (None, rng); + } + let (n, rng) = below(rng, 5); + let (values, rng) = (0..n).fold((vec![], rng), |(mut acc, rng), _| { + let (v, rng) = chips(rng, 6.0); + acc.push(v); + (acc, rng) + }); + (Some(values), rng) +} + +fn random_spot(rng: Rng) -> (Spot, Rng) { + let (v, rng) = below(rng, 4); + let variant = Variant::ALL[v as usize]; + let (s, rng) = below(rng, 4); + let street = Street::ALL[s as usize]; + let (hole, rng) = (spot_fixture::cards("Ah 5h"), rng); + let (pot, rng) = chips(rng, 20.0); + let (to_call, rng) = chips(rng, 5.0); + let (stack, rng) = chips(rng, 10.0); + let (min_on, rng) = below(rng, 2); + let (min, rng) = chips(rng, 2.0); + let (max_on, rng) = below(rng, 2); + let (max, rng) = chips(rng, 15.0); + let (legal, rng) = subset_of_legal(rng); + let (allowed, rng) = allowed_list(rng); + let (nv, rng) = below(rng, 4); + let spot = Spot { + variant, + street, + board: deck::full().into_iter().skip(10).take(street.board_len()).collect(), + hero_cards: hole, + pot, + to_call, + hero_stack: stack, + min_raise_to: (min_on == 1).then_some(min), + max_raise_to: (max_on == 1).then_some(max), + legal, + allowed_sizes: allowed, + villains: (0..nv).map(|i| Villain { seat: i as u8, ..spot_fixture::villain(0) }).collect(), + ..spot_fixture::flop() + }; + (spot, rng) +} + +fn random_estimate(rng: Rng) -> (Estimate, Rng) { + let (share, rng) = unit(rng); + let (se, rng) = unit(rng); + (spot_fixture::estimate(share, se * 0.05), rng) +} + +fn random_plan(rng: Rng) -> (PreflopPlan, Rng) { + let (a, rng) = below(rng, 4); + let (certainty, rng) = unit(rng); + let action = [ChartAction::Fold, ChartAction::Call, ChartAction::Raise, ChartAction::Jam][a as usize]; + (spot_fixture::plan(action, certainty), rng) +} + +fn random_thresholds(rng: Rng) -> (Thresholds, Rng) { + let (a, rng) = unit(rng); + let (b, rng) = unit(rng); + let (c, rng) = unit(rng); + let (d, rng) = unit(rng); + ( + Thresholds { + call_margin: a * 0.1, + value_raise: 0.4 + b * 0.5, + abstain_band: c * 0.05, + fold_equity_scale: d * 2.0, + range_width_scale: 1.0, + }, + rng, + ) +} + +fn assert_sound(spot: &Spot, decision: &Decision, label: &str) { + let ctx = format!("{label}: {spot:?} -> {decision:?}"); + if let Some(kind) = decision.choice.kind() { + assert!(spot.is_legal(kind), "illegal kind. {ctx}"); + if kind == ActionKind::Fold { + assert!(!spot.is_legal(ActionKind::Check), "fold with check legal. {ctx}"); + } + } + assert!((0.0..=1.0).contains(&decision.confidence.value()), "{ctx}"); + if let Choice::Raise { to } = decision.choice { + assert!(to.is_finite() && to > 0.0, "{ctx}"); + assert!(to <= spot.hero_stack, "unaffordable. {ctx}"); + if let Some(allowed) = &spot.allowed_sizes { + assert!(allowed.iter().any(|a| *a == to), "not from allowedSizes. {ctx}"); + } + if let Some(min) = spot.min_raise_to { + assert!(to >= min, "below min. {ctx}"); + } + if let Some(max) = spot.max_raise_to { + assert!(to <= max, "above max. {ctx}"); + } + if spot.rules().shape == ActionShape::Binary { + assert!(to == spot.hero_stack || Some(to) == spot.max_raise_to || spot.allowed_sizes.is_some(), "{ctx}"); + } + } + let after = settle(spot, decision.choice); + assert!(after.stack >= 0.0, "negative stack. {ctx}"); + assert!( + (after.stack + after.pot - (spot.hero_stack + spot.pot)).abs() < 1e-9, + "chips not conserved. {ctx}" + ); +} + +#[test] +fn postflop_choices_survive_enforcement_on_random_spots() { + let rng = Rng::seeded(0xD1CE); + let _ = (0..CASES).fold(rng, |rng, _| { + let (spot, rng) = random_spot(rng); + let (est, rng) = random_estimate(rng); + let (th, rng) = random_thresholds(rng); + let raw = choose_postflop(&spot, &est, &th); + assert_sound(&spot, &enforce(&spot, raw), "postflop"); + rng + }); +} + +#[test] +fn preflop_plans_survive_enforcement_on_random_spots() { + let rng = Rng::seeded(0xBEEF); + let _ = (0..CASES).fold(rng, |rng, _| { + let (spot, rng) = random_spot(rng); + let (plan, rng) = random_plan(rng); + let raw = from_plan(&spot, &plan); + assert_sound(&spot, &enforce(&spot, raw), "from_plan"); + rng + }); +} + +#[test] +fn enforce_is_sound_for_arbitrary_decisions() { + let rng = Rng::seeded(0xFACE); + let _ = (0..CASES).fold(rng, |rng, _| { + let (spot, rng) = random_spot(rng); + let (k, rng) = below(rng, 6); + let (size, rng) = chips(rng, 30.0); + let choice = match k { + 0 => Choice::Fold, + 1 => Choice::Check, + 2 => Choice::Call, + 3 => Choice::Raise { to: size }, + 4 => Choice::Raise { to: f64::NAN }, + _ => Choice::Abstain, + }; + assert_sound(&spot, &enforce(&spot, Decision::new(choice, 0.5, "arbitrary")), "enforce"); + rng + }); +} + +#[test] +fn enforce_is_idempotent() { + let rng = Rng::seeded(0xABCD); + let _ = (0..CASES).fold(rng, |rng, _| { + let (spot, rng) = random_spot(rng); + let (est, rng) = random_estimate(rng); + let once = enforce(&spot, choose_postflop(&spot, &est, &Thresholds::BASE)); + let twice = enforce(&spot, once.clone()); + assert_eq!(once.choice, twice.choice, "{spot:?}"); + rng + }); +} diff --git a/tests/guard_enforce.rs b/tests/guard_enforce.rs new file mode 100644 index 00000000..3e3be185 --- /dev/null +++ b/tests/guard_enforce.rs @@ -0,0 +1,109 @@ +mod spot_fixture; + +use pokerfreak::game::{ActionKind, Choice, Decision, Spot}; +use pokerfreak::guard::enforce::enforce; +use pokerfreak::variant::Variant; +use spot_fixture::*; + +fn choose(spot: &Spot, choice: Choice) -> Choice { + enforce(spot, Decision::new(choice, 0.9, "test")).choice +} + +#[test] +fn legal_choices_pass_through() { + let spot = flop(); + assert_eq!(choose(&spot, Choice::Fold), Choice::Fold); + assert_eq!(choose(&spot, Choice::Call), Choice::Call); + assert_eq!(choose(&spot, Choice::Raise { to: 1.0 }), Choice::Raise { to: 1.0 }); +} + +#[test] +fn abstain_stays_abstain() { + let out = enforce(&flop(), Decision::abstain("unsure")); + assert_eq!(out.choice, Choice::Abstain); + assert_eq!(out.reason, "unsure"); +} + +#[test] +fn illegal_kinds_become_abstain_with_a_reason() { + let spot = flop(); // no CHECK + let out = enforce(&spot, Decision::new(Choice::Check, 0.9, "x")); + assert_eq!(out.choice, Choice::Abstain); + assert!(out.reason.contains("CHECK"), "{}", out.reason); + assert_eq!(out.confidence.value(), 0.0); + + let no_raise = Spot { legal: vec![ActionKind::Fold, ActionKind::Call], ..flop() }; + assert_eq!(choose(&no_raise, Choice::Raise { to: 1.0 }), Choice::Abstain); +} + +#[test] +fn fold_is_turned_into_check_when_check_is_legal() { + let spot = Spot { + to_call: 0.0, + legal: vec![ActionKind::Fold, ActionKind::Check, ActionKind::Raise], + ..flop() + }; + assert_eq!(choose(&spot, Choice::Fold), Choice::Check); +} + +#[test] +fn raise_is_snapped_to_allowed_sizes_exactly() { + let spot = Spot { allowed_sizes: Some(vec![0.5, 1.15, 4.6]), ..flop() }; + assert_eq!(choose(&spot, Choice::Raise { to: 1.15 }), Choice::Raise { to: 1.15 }); + assert_eq!(choose(&spot, Choice::Raise { to: 4.6 }), Choice::Raise { to: 1.15 }); + assert_eq!(choose(&spot, Choice::Raise { to: 1.0 }), Choice::Raise { to: 1.15 }); + assert_eq!(choose(&spot, Choice::Raise { to: 0.1 }), Choice::Raise { to: 0.5 }); +} + +#[test] +fn raise_with_no_affordable_allowed_size_abstains() { + let spot = Spot { allowed_sizes: Some(vec![4.6, 5.0]), ..flop() }; + assert_eq!(choose(&spot, Choice::Raise { to: 4.6 }), Choice::Abstain); +} + +#[test] +fn free_raise_is_clamped_to_bounds_and_stack() { + let spot = flop(); + assert_eq!(choose(&spot, Choice::Raise { to: 100.0 }), Choice::Raise { to: 2.4 }); + assert_eq!(choose(&spot, Choice::Raise { to: 0.01 }), Choice::Raise { to: 0.5 }); + let capped = Spot { max_raise_to: Some(1.0), ..flop() }; + assert_eq!(choose(&capped, Choice::Raise { to: 2.0 }), Choice::Raise { to: 1.0 }); +} + +#[test] +fn raise_with_non_finite_size_or_no_stack_abstains() { + assert_eq!(choose(&flop(), Choice::Raise { to: f64::NAN }), Choice::Abstain); + let broke = Spot { hero_stack: 0.0, ..flop() }; + assert_eq!(choose(&broke, Choice::Raise { to: 1.0 }), Choice::Abstain); +} + +#[test] +fn binary_variants_allow_only_give_up_or_all_in() { + let aof = with_variant(flop(), Variant::Aof); + assert_eq!(choose(&aof, Choice::Fold), Choice::Fold); + assert_eq!(choose(&aof, Choice::Raise { to: 1.0 }), Choice::Raise { to: 2.4 }); + // a partial call is not an all-in + assert_eq!(choose(&aof, Choice::Call), Choice::Abstain); +} + +#[test] +fn binary_call_that_covers_the_stack_is_an_all_in() { + let aof = with_variant(Spot { to_call: 2.4, ..flop() }, Variant::Aof); + assert_eq!(choose(&aof, Choice::Call), Choice::Call); +} + +#[test] +fn binary_check_is_allowed() { + let aof = with_variant( + Spot { to_call: 0.0, legal: vec![ActionKind::Check, ActionKind::Raise], ..flop() }, + Variant::Aof, + ); + assert_eq!(choose(&aof, Choice::Check), Choice::Check); +} + +#[test] +fn repairs_are_mentioned_in_the_reason() { + let out = enforce(&flop(), Decision::new(Choice::Raise { to: 100.0 }, 0.8, "big")); + assert!(out.reason.starts_with("big"), "{}", out.reason); + assert!(out.reason.len() > "big".len()); +} diff --git a/tests/guard_settle.rs b/tests/guard_settle.rs new file mode 100644 index 00000000..34355121 --- /dev/null +++ b/tests/guard_settle.rs @@ -0,0 +1,73 @@ +mod spot_fixture; + +use pokerfreak::game::{Choice, Spot}; +use pokerfreak::guard::settle::settle; +use spot_fixture::*; + +fn close(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-9 +} + +#[test] +fn passive_choices_change_nothing() { + let spot = flop(); + for choice in [Choice::Fold, Choice::Check, Choice::Abstain] { + let after = settle(&spot, choice); + assert_eq!((after.stack, after.pot), (2.4, 1.25), "{choice:?}"); + } +} + +#[test] +fn call_moves_to_call_into_the_pot() { + let after = settle(&flop(), Choice::Call); + assert!(close(after.stack, 2.2)); + assert!(close(after.pot, 1.45)); +} + +#[test] +fn call_is_capped_by_the_stack() { + let spot = Spot { to_call: 5.0, ..flop() }; + let after = settle(&spot, Choice::Call); + assert!(close(after.stack, 0.0)); + assert!(close(after.pot, 3.65)); +} + +#[test] +fn raise_moves_the_full_size() { + let after = settle(&flop(), Choice::Raise { to: 1.0 }); + assert!(close(after.stack, 1.4)); + assert!(close(after.pot, 2.25)); +} + +#[test] +fn raise_beyond_the_stack_is_an_all_in_at_most() { + let after = settle(&flop(), Choice::Raise { to: 50.0 }); + assert!(close(after.stack, 0.0)); + assert!(close(after.pot, 3.65)); +} + +#[test] +fn garbage_sizes_move_nothing() { + for to in [f64::NAN, -3.0, f64::INFINITY] { + let after = settle(&flop(), Choice::Raise { to }); + assert!(close(after.stack + after.pot, 3.65), "{to}"); + assert!(after.stack >= 0.0); + } +} + +#[test] +fn chips_are_conserved_and_the_stack_never_negative() { + let choices = [ + Choice::Fold, + Choice::Check, + Choice::Call, + Choice::Raise { to: 0.7 }, + Choice::Raise { to: 1e9 }, + Choice::Abstain, + ]; + for choice in choices { + let after = settle(&flop(), choice); + assert!(close(after.stack + after.pot, 2.4 + 1.25), "{choice:?}"); + assert!(after.stack >= 0.0, "{choice:?}"); + } +} diff --git a/tests/guard_validate.rs b/tests/guard_validate.rs new file mode 100644 index 00000000..c1f161f0 --- /dev/null +++ b/tests/guard_validate.rs @@ -0,0 +1,145 @@ +mod spot_fixture; + +use pokerfreak::fault::Fault; +use pokerfreak::game::{ActionKind, Spot, Street}; +use pokerfreak::guard::validate::check; +use pokerfreak::variant::Variant; +use spot_fixture::*; + +fn fault_text(spot: Spot) -> String { + match check(spot) { + Ok(_) => "accepted".to_string(), + Err(fault) => fault.to_string(), + } +} + +fn rejects(spot: Spot, needle: &str) { + let text = fault_text(spot); + assert!(text.contains(needle), "expected a fault mentioning {needle:?}, got {text:?}"); +} + +#[test] +fn a_consistent_spot_passes_unchanged() { + assert_eq!(check(flop()), Ok(flop())); + assert_eq!(check(preflop()), Ok(preflop())); + assert!(check(with_variant(flop(), Variant::Plo5)).is_ok()); +} + +#[test] +fn faults_are_values_of_the_shared_type() { + let bad = Spot { hero_cards: cards("Ah"), ..flop() }; + assert!(matches!(check(bad), Err(Fault::Invalid { .. }) | Err(Fault::Inconsistent(_)))); +} + +#[test] +fn wrong_hole_card_count_is_rejected_per_variant() { + rejects(Spot { hero_cards: cards("Ah"), ..flop() }, "heroCards"); + rejects(Spot { hero_cards: cards("Ah 5h Kd"), ..flop() }, "heroCards"); + rejects(Spot { variant: Variant::Plo5, ..flop() }, "heroCards"); +} + +#[test] +fn wrong_board_length_for_the_street_is_rejected() { + rejects(Spot { board: cards("Ac 7d"), ..flop() }, "board"); + rejects(Spot { street: Street::Turn, ..flop() }, "board"); + rejects(Spot { street: Street::Preflop, ..flop() }, "board"); +} + +#[test] +fn duplicate_cards_are_rejected() { + rejects(Spot { board: cards("Ah 7d 2s"), ..flop() }, "duplicate"); + rejects(Spot { board: cards("Ac Ac 2s"), ..flop() }, "duplicate"); + rejects(Spot { hero_cards: cards("Ah Ah"), ..flop() }, "duplicate"); +} + +#[test] +fn non_finite_or_negative_chips_are_rejected() { + rejects(Spot { pot: f64::NAN, ..flop() }, "pot"); + rejects(Spot { pot: -1.0, ..flop() }, "pot"); + rejects(Spot { to_call: f64::INFINITY, ..flop() }, "toCall"); + rejects(Spot { to_call: -0.1, ..flop() }, "toCall"); + rejects(Spot { hero_stack: -2.0, ..flop() }, "heroStack"); + rejects(Spot { hero_stack: f64::NAN, ..flop() }, "heroStack"); + rejects(Spot { min_raise_to: Some(f64::NAN), ..flop() }, "minRaiseTo"); + rejects(Spot { max_raise_to: Some(-1.0), ..flop() }, "maxRaiseTo"); +} + +#[test] +fn big_blind_must_be_positive() { + rejects(Spot { big_blind: 0.0, ..flop() }, "bigBlind"); + rejects(Spot { big_blind: -0.1, ..flop() }, "bigBlind"); + rejects(Spot { big_blind: f64::NAN, ..flop() }, "bigBlind"); +} + +#[test] +fn legal_actions_must_be_non_empty_and_distinct() { + rejects(Spot { legal: vec![], ..flop() }, "legalActions"); + rejects( + Spot { legal: vec![ActionKind::Fold, ActionKind::Call, ActionKind::Fold], ..flop() }, + "legalActions", + ); +} + +#[test] +fn seats_must_be_between_two_and_ten() { + rejects(Spot { seats: 1, ..flop() }, "seats"); + rejects(Spot { seats: 11, ..flop() }, "seats"); + rejects(Spot { seats: 0, ..flop() }, "seats"); + assert!(check(Spot { seats: 2, ..flop() }).is_ok()); + assert!(check(Spot { seats: 10, ..flop() }).is_ok()); +} + +#[test] +fn min_raise_above_max_raise_is_rejected() { + rejects(Spot { min_raise_to: Some(5.0), max_raise_to: Some(1.0), ..flop() }, "minRaiseTo"); +} + +#[test] +fn allowed_sizes_must_be_positive_and_finite() { + rejects(Spot { allowed_sizes: Some(vec![0.5, 0.0]), ..flop() }, "allowedSizes"); + rejects(Spot { allowed_sizes: Some(vec![0.5, -1.0]), ..flop() }, "allowedSizes"); + rejects(Spot { allowed_sizes: Some(vec![f64::NAN]), ..flop() }, "allowedSizes"); + rejects(Spot { allowed_sizes: Some(vec![f64::INFINITY]), ..flop() }, "allowedSizes"); +} + +#[test] +fn check_while_facing_a_bet_is_inconsistent() { + let spot = Spot { legal: vec![ActionKind::Check, ActionKind::Raise], ..flop() }; + rejects(spot, "CHECK"); +} + +#[test] +fn check_is_fine_when_nothing_is_owed() { + let spot = Spot { to_call: 0.0, legal: vec![ActionKind::Check, ActionKind::Raise], ..flop() }; + assert!(check(spot).is_ok()); +} + +#[test] +fn raise_with_no_way_to_size_it_is_inconsistent() { + let spot = Spot { + min_raise_to: None, + max_raise_to: None, + allowed_sizes: None, + hero_stack: 0.0, + ..flop() + }; + rejects(spot, "RAISE"); +} + +#[test] +fn raise_without_bounds_is_fine_while_hero_has_chips() { + let spot = Spot { min_raise_to: None, max_raise_to: None, ..flop() }; + assert!(check(spot).is_ok()); +} + +#[test] +fn raise_sized_by_allowed_sizes_alone_is_fine() { + let spot = Spot { + min_raise_to: None, + max_raise_to: None, + hero_stack: 0.0, + allowed_sizes: Some(vec![0.5]), + ..flop() + }; + assert!(check(spot).is_ok()); +} diff --git a/tests/odds_break_even.rs b/tests/odds_break_even.rs new file mode 100644 index 00000000..2f6ffbb0 --- /dev/null +++ b/tests/odds_break_even.rs @@ -0,0 +1,37 @@ +use pokerfreak::odds::bluff::bluff_break_even; +use pokerfreak::odds::break_even::break_even; + +fn close(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-12 +} + +#[test] +fn call_break_even_is_call_over_final_pot() { + assert!(close(break_even(10.0, 5.0), 5.0 / 15.0)); + assert!(close(break_even(1.25, 0.25), 0.25 / 1.5)); +} + +#[test] +fn free_call_needs_no_equity() { + assert_eq!(break_even(10.0, 0.0), 0.0); +} + +#[test] +fn empty_pot_needs_all_equity() { + assert!(close(break_even(0.0, 1.0), 1.0)); +} + +#[test] +fn degenerate_input_yields_zero_not_nan() { + assert_eq!(break_even(0.0, 0.0), 0.0); + assert_eq!(break_even(f64::NAN, 1.0), 0.0); + assert_eq!(break_even(1.0, f64::INFINITY), 0.0); +} + +#[test] +fn bluff_break_even_is_risk_over_risk_plus_pot() { + assert!(close(bluff_break_even(10.0, 5.0), 5.0 / 15.0)); + assert!(close(bluff_break_even(10.0, 10.0), 0.5)); + assert_eq!(bluff_break_even(10.0, 0.0), 0.0); + assert_eq!(bluff_break_even(f64::NAN, 1.0), 0.0); +} diff --git a/tests/odds_ev.rs b/tests/odds_ev.rs new file mode 100644 index 00000000..3033228f --- /dev/null +++ b/tests/odds_ev.rs @@ -0,0 +1,72 @@ +use pokerfreak::odds::ev; +use pokerfreak::odds::fold_equity::fold_equity; + +fn close(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-9 +} + +#[test] +fn fold_is_zero() { + assert_eq!(ev::fold(), 0.0); +} + +#[test] +fn check_is_share_of_pot() { + assert!(close(ev::check(0.5, 10.0), 5.0)); + assert!(close(ev::check(0.0, 10.0), 0.0)); +} + +#[test] +fn call_is_share_of_final_pot_minus_price() { + assert!(close(ev::call(0.4, 10.0, 5.0), 0.4 * 15.0 - 5.0)); + // exactly at break-even the call is worth nothing + assert!(close(ev::call(1.0 / 3.0, 10.0, 5.0), 0.0)); +} + +#[test] +fn raise_mixes_fold_equity_and_called_outcome() { + // pot 10, free to act, bet 5, fe 0.4, share 0.5: + // final pot 20 -> called outcome 0.5*20-5 = 5; EV = 0.4*10 + 0.6*5 = 7 + assert!(close(ev::raise(0.5, 10.0, 0.0, 5.0, 0.4), 7.0)); +} + +#[test] +fn raise_over_a_bet_only_adds_the_difference_for_villain() { + // pot 10 incl. villain bet 5; raise to 15; villain adds 10 -> final 35. + assert!(close(ev::raise(0.5, 10.0, 5.0, 15.0, 0.0), 0.5 * 35.0 - 15.0)); +} + +#[test] +fn raise_with_full_fold_equity_wins_the_pot() { + assert!(close(ev::raise(0.0, 10.0, 0.0, 5.0, 1.0), 10.0)); +} + +#[test] +fn raise_with_no_fold_equity_and_no_equity_loses_the_bet() { + assert!(close(ev::raise(0.0, 10.0, 0.0, 5.0, 0.0), -5.0)); +} + +#[test] +fn default_fold_equity_is_bet_over_pot_plus_bet() { + assert!(close(fold_equity(10.0, 5.0, 1.0, 1), 5.0 / 15.0)); +} + +#[test] +fn fold_equity_scales_with_threshold_scale() { + assert!(close(fold_equity(10.0, 5.0, 0.5, 1), 5.0 / 15.0 * 0.5)); +} + +#[test] +fn fold_equity_compounds_across_villains() { + let one = 5.0 / 15.0; + assert!(close(fold_equity(10.0, 5.0, 1.0, 2), one * one)); + assert!(close(fold_equity(10.0, 5.0, 1.0, 3), one * one * one)); +} + +#[test] +fn fold_equity_is_capped_and_total() { + assert!(fold_equity(10.0, 5.0, 100.0, 1) <= 0.95); + assert_eq!(fold_equity(10.0, 5.0, 1.0, 0), 0.0); + assert_eq!(fold_equity(f64::NAN, 5.0, 1.0, 1), 0.0); + assert_eq!(fold_equity(10.0, 5.0, -1.0, 1), 0.0); +} diff --git a/tests/sizing_candidates.rs b/tests/sizing_candidates.rs new file mode 100644 index 00000000..b57c52f6 --- /dev/null +++ b/tests/sizing_candidates.rs @@ -0,0 +1,130 @@ +mod spot_fixture; + +use pokerfreak::game::Spot; +use pokerfreak::sizing::all_in::all_in; +use pokerfreak::sizing::candidates::candidates; +use pokerfreak::sizing::fit::fit; +use pokerfreak::variant::Variant; +use spot_fixture::*; + +fn within(spot: &Spot, sizes: &[f64]) -> bool { + sizes.iter().all(|s| { + *s >= spot.min_raise_to.unwrap_or(0.0) + && *s <= spot.max_raise_to.unwrap_or(f64::MAX) + && *s <= spot.hero_stack + }) +} + +#[test] +fn nolimit_offers_a_few_pot_fractions_inside_bounds() { + let spot = flop(); + let sizes = candidates(&spot); + assert!(sizes.len() >= 2, "{sizes:?}"); + assert!(within(&spot, &sizes), "{sizes:?}"); + assert!(sizes.windows(2).all(|w| w[0] < w[1]), "sorted and distinct: {sizes:?}"); +} + +#[test] +fn nolimit_fractions_are_measured_on_the_pot_after_calling() { + let spot = round_flop(); // pot 10, call 5 -> 5 + f * 15 + let sizes = candidates(&spot); + assert!(sizes.iter().any(|s| (s - 10.0).abs() < 1e-9), "1/3 pot: {sizes:?}"); + assert!(sizes.iter().any(|s| (s - 15.0).abs() < 1e-9), "2/3 pot: {sizes:?}"); + assert!(sizes.iter().any(|s| (s - 20.0).abs() < 1e-9), "pot: {sizes:?}"); +} + +#[test] +fn sizes_are_clamped_into_the_hero_stack() { + let spot = Spot { hero_stack: 1.0, ..flop() }; + let sizes = candidates(&spot); + assert!(!sizes.is_empty()); + assert!(sizes.iter().all(|s| *s <= 1.0 && *s >= 0.5), "{sizes:?}"); +} + +#[test] +fn stack_below_min_raise_gives_no_candidates() { + let spot = Spot { hero_stack: 0.3, ..flop() }; + assert!(candidates(&spot).is_empty()); +} + +#[test] +fn potlimit_never_exceeds_pot_sized_raise() { + let spot = with_variant( + Spot { pot: 2.0, to_call: 0.5, hero_stack: 100.0, max_raise_to: Some(100.0), ..flop() }, + Variant::Plo5, + ); + let sizes = candidates(&spot); + assert!(!sizes.is_empty()); + assert!(sizes.iter().all(|s| *s <= 3.0 + 1e-9), "pot raise = 2 + 2*0.5: {sizes:?}"); +} + +#[test] +fn menu_without_allowed_sizes_falls_back_to_free_sizes() { + let menu = with_variant(flop(), Variant::KPoker); + assert_eq!(candidates(&menu), candidates(&flop())); +} + +#[test] +fn all_in_only_offers_exactly_the_jam() { + let aof = with_variant(flop(), Variant::Aof); + assert_eq!(candidates(&aof), vec![2.4]); + let capped = Spot { max_raise_to: Some(1.0), ..aof.clone() }; + assert_eq!(candidates(&capped), vec![1.0]); + let unbounded = Spot { max_raise_to: None, ..aof }; + assert_eq!(candidates(&unbounded), vec![2.4]); +} + +#[test] +fn allowed_sizes_are_the_only_source_verbatim() { + let spot = Spot { allowed_sizes: Some(vec![0.5, 1.15, 4.6]), ..flop() }; + assert_eq!(candidates(&spot), vec![0.5, 1.15]); +} + +#[test] +fn allowed_sizes_win_for_every_variant() { + for variant in Variant::ALL { + let spot = + with_variant(Spot { allowed_sizes: Some(vec![0.5, 1.15, 4.6]), ..flop() }, variant); + assert_eq!(candidates(&spot), vec![0.5, 1.15], "{variant:?}"); + } +} + +#[test] +fn allowed_sizes_are_filtered_by_min_and_max() { + let base = Spot { allowed_sizes: Some(vec![0.5, 1.15, 4.6]), ..flop() }; + assert_eq!(candidates(&Spot { min_raise_to: Some(0.6), ..base.clone() }), vec![1.15]); + assert_eq!(candidates(&Spot { max_raise_to: Some(1.0), ..base.clone() }), vec![0.5]); + assert!(candidates(&Spot { hero_stack: 0.4, ..base }).is_empty()); +} + +#[test] +fn all_in_is_stack_or_max() { + assert_eq!(all_in(&flop()), Some(2.4)); + assert_eq!(all_in(&Spot { max_raise_to: Some(1.0), ..flop() }), Some(1.0)); + assert_eq!(all_in(&Spot { hero_stack: 0.0, ..flop() }), None); + assert_eq!(all_in(&Spot { min_raise_to: Some(3.0), ..flop() }), None); +} + +#[test] +fn all_in_with_allowed_sizes_is_the_largest_affordable_one() { + let spot = Spot { allowed_sizes: Some(vec![0.5, 1.15, 4.6]), ..flop() }; + assert_eq!(all_in(&spot), Some(1.15)); +} + +#[test] +fn fit_clamps_free_sizes_and_snaps_allowed_ones() { + assert_eq!(fit(&flop(), 100.0), Some(2.4)); + assert_eq!(fit(&flop(), 0.01), Some(0.5)); + assert_eq!(fit(&flop(), 1.0), Some(1.0)); + assert_eq!(fit(&flop(), f64::NAN), None); + let allowed = Spot { allowed_sizes: Some(vec![0.5, 1.15, 4.6]), ..flop() }; + assert_eq!(fit(&allowed, 1.0), Some(1.15)); + assert_eq!(fit(&allowed, 4.6), Some(1.15)); + assert_eq!(fit(&allowed, 0.1), Some(0.5)); +} + +#[test] +fn fit_on_binary_variants_is_the_jam() { + let aof = with_variant(flop(), Variant::Aof); + assert_eq!(fit(&aof, 1.0), Some(2.4)); +} diff --git a/tests/sizing_preflop.rs b/tests/sizing_preflop.rs new file mode 100644 index 00000000..50fe7448 --- /dev/null +++ b/tests/sizing_preflop.rs @@ -0,0 +1,44 @@ +mod spot_fixture; + +use pokerfreak::game::Spot; +use pokerfreak::sizing::preflop::{raise_size, raise_target}; +use spot_fixture::*; + +fn close(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-9 +} + +#[test] +fn unopened_pot_opens_two_and_a_half_big_blinds() { + assert!(close(raise_target(&preflop()), 0.25)); +} + +#[test] +fn facing_a_raise_makes_it_three_times() { + let spot = Spot { to_call: 0.3, ..preflop() }; + assert!(close(raise_target(&spot), 0.9)); +} + +#[test] +fn raise_size_uses_the_target_when_free() { + assert!(close(raise_size(&preflop()).unwrap(), 0.25)); + assert!(close(raise_size(&Spot { to_call: 0.3, ..preflop() }).unwrap(), 0.9)); +} + +#[test] +fn raise_size_is_clamped_to_the_bounds() { + let spot = Spot { to_call: 0.3, max_raise_to: Some(0.6), ..preflop() }; + assert!(close(raise_size(&spot).unwrap(), 0.6)); +} + +#[test] +fn raise_size_picks_the_nearest_allowed_size_verbatim() { + let spot = Spot { allowed_sizes: Some(vec![0.2, 0.5, 1.0]), ..preflop() }; + assert_eq!(raise_size(&spot), Some(0.2)); +} + +#[test] +fn unaffordable_min_raise_gives_nothing() { + let spot = Spot { hero_stack: 0.15, ..preflop() }; + assert_eq!(raise_size(&spot), None); +} diff --git a/tests/spot_fixture/mod.rs b/tests/spot_fixture/mod.rs new file mode 100644 index 00000000..aecbee8b --- /dev/null +++ b/tests/spot_fixture/mod.rs @@ -0,0 +1,78 @@ +#![allow(dead_code)] +//! Shared builders for spots, estimates and plans used by the engine-side tests. + +use pokerfreak::card::Card; +use pokerfreak::equity::estimate::Estimate; +use pokerfreak::game::{ActionKind, Spot, Street, Villain}; +use pokerfreak::preflop::plan::{ChartAction, PreflopPlan}; +use pokerfreak::variant::Variant; + +pub fn cards(text: &str) -> Vec { + Card::parse_list(text).expect("fixture cards") +} + +pub fn villain(seat: u8) -> Villain { + Villain { seat, stack: 10.0, folded: false, profile: None } +} + +/// NLHE flop, hero Ah5h on Ac7d2s, pot 1.25, 0.2 to call, stack 2.4. +pub fn flop() -> Spot { + Spot { + variant: Variant::Nlhe, + big_blind: 0.1, + seats: 6, + hero_seat: 5, + button_seat: None, + hero_cards: cards("Ah 5h"), + board: cards("Ac 7d 2s"), + street: Street::Flop, + pot: 1.25, + to_call: 0.2, + hero_stack: 2.4, + min_raise_to: Some(0.5), + max_raise_to: Some(20.0), + legal: vec![ActionKind::Fold, ActionKind::Call, ActionKind::Raise], + allowed_sizes: None, + villains: vec![villain(2)], + seed: 1, + } +} + +/// Round numbers: pot 10, 5 to call, deep stack. Break-even is exactly 1/3. +pub fn round_flop() -> Spot { + Spot { + pot: 10.0, + to_call: 5.0, + hero_stack: 100.0, + min_raise_to: Some(10.0), + max_raise_to: Some(100.0), + ..flop() + } +} + +/// Preflop NLHE, hero SB-ish: pot 0.15, 0.1 to call, stack 10. +pub fn preflop() -> Spot { + Spot { + board: vec![], + street: Street::Preflop, + pot: 0.15, + to_call: 0.1, + hero_stack: 10.0, + min_raise_to: Some(0.2), + max_raise_to: Some(10.0), + ..flop() + } +} + +pub fn with_variant(spot: Spot, variant: Variant) -> Spot { + let hole = if variant == Variant::Plo5 { "Ah 5h Kd Qc 9s" } else { "Ah 5h" }; + Spot { variant, hero_cards: cards(hole), ..spot } +} + +pub fn estimate(share: f64, std_error: f64) -> Estimate { + Estimate { win: share, tie: 0.0, share, trials: 3000, std_error } +} + +pub fn plan(action: ChartAction, certainty: f64) -> PreflopPlan { + PreflopPlan { action, percentile: 0.1, certainty, reason: "chart".to_string() } +}