Add odds, sizing, guard and engine glue with tests

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-28 11:51:24 +01:00
co-authored by Claude Opus 5.5
parent 7e0ee9199e
commit 62db6df752
36 changed files with 1846 additions and 9 deletions
+70 -4
View File
@@ -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<f64> = 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<Box<dyn Fn(&[Card]) -> bool>> = fractions
.into_iter()
.map(|fraction| {
Box::new(move |hand: &[Card]| percentile(variant, hand) <= fraction)
as Box<dyn Fn(&[Card]) -> bool>
})
.collect();
let ranges: Vec<VillainRange> =
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<Profile> = 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))
}
+48
View File
@@ -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<f64>) -> Option<Choice> {
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<Choice> {
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()),
),
}
}
+4
View File
@@ -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;
+50
View File
@@ -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<Scored> {
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()
}
+23
View File
@@ -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<Choice> {
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<Choice> {
if spot.is_legal(ActionKind::Check) {
Some(Choice::Check)
} else if spot.is_legal(ActionKind::Fold) {
Some(Choice::Fold)
} else {
None
}
}
+92
View File
@@ -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<Scored> {
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<f64>, 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"),
},
}
}