Files
pokerfreak/src/engine/glaube.rs
T

344 lines
15 KiB
Rust

//! One belief about an opponent (`POSTERIOR`, off by default = bit-identical), PLAN §8.11 #4, 5, 8, 15, 16.
//!
//! Stage S1 (`POSTERIOR=fold`): P(fold) to a bet is the range mass below the continue boundary, the
//! same boundary and the same number that the called branch plays against (`exploit::call_floor`).
//! Today the fold chance is a formula without the board (`exploit::fold_chance`), and the call floor
//! takes its width from that formula without the street read (`table_fold` uses the street read),
//! so the fold branch and the called branch disagree.
//!
//! The read says HOW MUCH a villain folds (its average over boards), the board says WHERE: in logit,
//!
//! `logit P(fold) = logit f_read + w * (logit m_board - logit m_ref)`
//!
//! * `f_read`: the fold chance of the read at this pressure (`fold_chance_on` / the c-bet read), the
//! villain's average;
//! * `m_board`: the share of his preflop band (`range_model::range_spec` lo..hi, hero's cards and the
//! board removed) below the calling floor (`call_floor`: rung by street, size notch and style; draws
//! from a gutshot continue before the river) on THIS board;
//! * `m_ref`: the same share averaged over `REF_BOARDS` random boards of the same length, so the term
//! is zero on an average board and the read keeps its level;
//! * `w`: the board weight (`POSTERIOR=fold:<w>`, default 1).
//!
//! Only the preflop band enters `m_board`: the pool folds MORE on later streets (NL2 flop 0,51, turn
//! 0,55, river 0,63), so the narrowing of a calling range is not the dominant effect, and the read's
//! street level already carries it. Board texture is what the formula misses.
use crate::card::{deck, Card};
use super::glaube_linie::{self, Line};
use crate::exploit::bluff_share::MAX_BLUFF_SHARE;
use crate::exploit::call_floor::CALL_RUNG;
use crate::exploit::profile::Profile;
use crate::exploit::sample::STREET_PRIOR;
use crate::exploit::fold_chance::{fold_base_cbet, fold_chance_on, sized_fold, MAX_FOLD};
use crate::exploit::made_ladder::rung;
use crate::exploit::range_model::range_spec;
use crate::exploit::size_notch::size_notch;
use crate::exploit::style_rung::style_rung;
use crate::game::{line, Spot, Street, Villain};
use crate::preflop::hand_percentile::percentile;
use crate::read::draw::Draw;
use crate::read::glance::glance;
use crate::read::made::Made;
use crate::rng::Rng;
use crate::variant::{Rules, Variant};
use std::cell::RefCell;
use std::collections::HashMap;
/// Random boards per reference share.
pub const REF_BOARDS: usize = 48;
const REF_SEED: u64 = 0x6_1A0B_E000;
/// Band edges are rounded to this step for the reference cache.
const BAND_STEP: f64 = 0.05;
/// Shares are kept inside `[EPS, 1 - EPS]` before the logit.
const EPS: f64 = 0.01;
/// The switch: which stages are on and the board weight of S1.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Mode {
pub fold: bool,
pub board_weight: f64,
/// `nurfold`: the board term only in the fold branch, the called branch keeps `call_floor`.
pub fold_only_branch: bool,
/// `anteil`: the read is the fold RATE within the class (below / above the floor) instead of a
/// logit level, `P(fold) = m_board * f / m_ref` (see `class_fold`). Never above the mass below
/// the floor unless the read folds more than that mass on average.
pub class_rate: bool,
/// S2 `bluff`: the bluff share of a villain's bet is a Beta posterior, see `bluff`.
pub bluff: bool,
}
thread_local! {
static OVERRIDE: std::cell::Cell<Option<Option<Mode>>> = const { std::cell::Cell::new(None) };
static MASS: RefCell<HashMap<String, f64>> = RefCell::new(HashMap::new());
}
/// `POSTERIOR=fold` or `fold:<w>` (comma list of stages; unknown stages are ignored). Else off.
pub fn mode() -> Option<Mode> {
use std::sync::OnceLock;
static M: OnceLock<Option<Mode>> = OnceLock::new();
OVERRIDE.with(|o| o.get()).unwrap_or_else(|| *M.get_or_init(|| std::env::var("POSTERIOR").ok().and_then(|s| parse(&s))))
}
fn parse(s: &str) -> Option<Mode> {
let mut m = Mode { fold: false, board_weight: 1.0, fold_only_branch: false, class_rate: false, bluff: false };
for t in s.split(',').map(str::trim) {
if t == "fold" {
m.fold = true;
} else if t == "nurfold" {
m.fold_only_branch = true;
} else if t == "anteil" {
m.class_rate = true;
} else if t == "bluff" {
m.bluff = true;
} else if let Some(w) = t.strip_prefix("fold:").and_then(|w| w.parse::<f64>().ok()).filter(|w| w.is_finite()) {
m.fold = true;
m.board_weight = w;
}
}
(m.fold || m.bluff).then_some(m)
}
/// Force the switch for this thread (`Some(None)` = off), `None` = the environment. Tests.
pub fn set_override(mode: Option<Option<Mode>>) {
OVERRIDE.with(|o| o.set(mode));
}
/// Is S1 on?
pub fn fold_on() -> bool {
mode().is_some_and(|m| m.fold)
}
/// Does the called branch play against `1 - fold` (S1 without `nurfold`)?
pub fn called_on() -> bool {
mode().is_some_and(|m| m.fold && !m.fold_only_branch)
}
fn logit(p: f64) -> f64 {
let p = p.clamp(EPS, 1.0 - EPS);
(p / (1.0 - p)).ln()
}
fn sigmoid(x: f64) -> f64 {
1.0 / (1.0 + (-x).exp())
}
/// The calling floor of `villain` against pressure `ratio` on `street` (`call_floor::call_continuation`).
fn floor(villain: &Villain, street: Street, ratio: f64) -> (Made, bool) {
let slot = (street as usize).clamp(1, 3) - 1;
(rung(CALL_RUNG[slot], size_notch(Some(ratio)) + style_rung(villain)), street != Street::River)
}
/// Share of the two-card hands with preflop percentile in `[lo, hi]`, outside `dead`, that fall
/// below the floor on `board`. `None` for other hand sizes or an empty band.
fn below_share(rules: &Rules, variant: Variant, lo: f64, hi: f64, board: &[Card], dead: &[Card], made: Made, draws: bool) -> Option<f64> {
if rules.hole_cards != 2 {
return None;
}
let pool = deck::without_in(rules.deck, dead);
let (mut all, mut below) = (0usize, 0usize);
for i in 0..pool.len() {
for j in i + 1..pool.len() {
let hand = [pool[i], pool[j]];
let p = percentile(variant, &hand);
if p < lo || p > hi {
continue;
}
let Ok((m, d)) = glance(rules, &hand, board) else { continue };
all += 1;
if !(m >= made || (draws && d >= Draw::Gutshot)) {
below += 1;
}
}
}
(all > 0).then(|| below as f64 / all as f64)
}
fn cached(key: String, f: impl FnOnce() -> Option<f64>) -> Option<f64> {
if let Some(x) = MASS.with(|m| m.borrow().get(&key).copied()) {
return Some(x);
}
let x = f()?;
MASS.with(|m| {
let mut m = m.borrow_mut();
if m.len() >= 4096 {
m.clear();
}
m.insert(key, x);
});
Some(x)
}
/// The board-average share below the floor for this band and street (random boards, fixed seed).
fn reference(rules: &Rules, variant: Variant, lo: f64, hi: f64, board_len: usize, made: Made, draws: bool) -> Option<f64> {
let key = format!("ref|{variant:?}|{lo:.2}|{hi:.2}|{board_len}|{made:?}|{draws}");
cached(key, || {
let full = deck::without_in(rules.deck, &[]);
let mut rng = Rng::seeded(REF_SEED ^ board_len as u64);
let mut sum = 0.0;
let mut n = 0usize;
for _ in 0..REF_BOARDS {
let (board, next) = deck::draw(&full, board_len, rng)?;
rng = next;
if let Some(x) = below_share(rules, variant, lo, hi, &board, &board, made, draws) {
sum += x;
n += 1;
}
}
(n > 0).then(|| sum / n as f64)
})
}
/// P(`villain` folds) to pressure `ratio`, S1 (see the module text). Falls back to the read alone
/// preflop, without a usable band, or for other hand sizes.
pub fn fold(spot: &Spot, villain: &Villain, ratio: f64, facing_raise: bool, read_fold: f64) -> f64 {
let Some(m) = mode().filter(|m| m.fold) else { return read_fold };
if spot.street == Street::Preflop || spot.board.len() < 3 || !(0.0..1.0).contains(&read_fold) || read_fold <= 0.0 {
return read_fold;
}
if m.class_rate && passive_station(villain) {
// A non-folding over-caller folds for reasons other than strength: no board term (pilot
// 16.11.: station -15,21 with it).
return read_fold;
}
let rules = spot.rules();
let spec = range_spec(spot, villain);
let round = |x: f64| ((x / BAND_STEP).round() * BAND_STEP).clamp(0.0, 1.0);
let (lo, hi) = (round(spec.lo), round(spec.hi));
if hi <= lo {
return read_fold;
}
let (made, draws) = floor(villain, spot.street, ratio);
let dead: Vec<Card> = spot.hero_cards.iter().chain(&spot.board).copied().collect();
let key = format!("brett|{:?}|{lo:.2}|{hi:.2}|{:?}|{:?}|{made:?}|{draws}", spot.variant, spot.board, spot.hero_cards);
let board = cached(key, || below_share(&rules, spot.variant, lo, hi, &spot.board, &dead, made, draws));
let reference = reference(&rules, spot.variant, lo, hi, spot.board.len(), made, draws);
let _ = facing_raise;
match (board, reference) {
(Some(b), Some(r)) if m.class_rate => {
let b = r + m.board_weight * (b - r);
class_fold(read_fold, b.clamp(0.0, 1.0), r).clamp(0.0, MAX_FOLD)
}
(Some(b), Some(r)) => sigmoid(logit(read_fold) + m.board_weight * (logit(b) - logit(r))).clamp(0.0, MAX_FOLD),
_ => read_fold,
}
}
/// The same over-caller as `engine::fortsetzung`: `Style::CallingStation` with foldToBet at most
/// `STATION_FOLD_TO_BET`.
fn passive_station(villain: &Villain) -> bool {
use crate::exploit::style::{classify, Style, STATION_FOLD_TO_BET};
villain.profile.as_ref().is_some_and(|p| {
classify(p) == Style::CallingStation && p.fold_to_bet.is_some_and(|f| f.is_finite() && f <= STATION_FOLD_TO_BET)
})
}
/// The read as a rate within the classes: on the average board a share `m_ref` lies below the floor,
/// the villain folds `f` in all. If `f <= m_ref` he folds `f / m_ref` of his hands below the floor and
/// nothing above it; else all below and `(f - m_ref) / (1 - m_ref)` of those above. On this board
/// (`m_board` below) the same rates give the fold chance; `m_board = m_ref` returns `f`.
fn class_fold(f: f64, m_board: f64, m_ref: f64) -> f64 {
if m_ref <= 0.0 {
return f;
}
if f <= m_ref {
m_board * f / m_ref
} else if m_ref >= 1.0 {
f
} else {
m_board + (1.0 - m_board) * (f - m_ref) / (1.0 - m_ref)
}
}
/// S2: the bluff share of a villain's bet as a Beta posterior.
///
/// * Prior of an UNREAD villain (no profile or the pool baseline): the population's air share on
/// this betting `line` (`engine::glaube_linie`, real showdowns per street, pot, barrels, size,
/// kind), `(air + 0,5)/(n + 1)`. Without a line table: on the river the pool mean `POOL_RIVER_AIR`
/// (never above the heuristic), on flop and turn the heuristic.
/// * Prior of a READ villain: the heuristic from his aggression (`exploit::bluff_share`).
/// * Evidence: his shown river bets (`Profile::river_bluff_share` over `river_bluff_shown`), weight
/// of the prior `STREET_PRIOR` bets as in the solver's read; flop and turn have no per-street
/// showdown count yet.
///
/// Off: `prior` unchanged.
pub fn bluff(profile: Option<&Profile>, street: Street, line: Option<&Line>, prior: f64) -> f64 {
if !mode().is_some_and(|m| m.bluff) || street == Street::Preflop {
return prior;
}
let ok = |x: Option<f64>| x.filter(|v| v.is_finite());
let unread = profile.is_none_or(|p| p.pool_baseline);
let pool = line.and_then(glaube_linie::lookup).map(|(air, n)| (air + 0.5) / (n + 1.0));
let prior = match (unread, pool) {
(true, Some(m)) => m.min(MAX_BLUFF_SHARE),
(true, None) if street == Street::River => prior.min(POOL_RIVER_AIR),
_ => prior,
};
if street != Street::River {
return prior;
}
let Some(p) = profile else { return prior };
match (ok(p.river_bluff_share), ok(p.river_bluff_shown)) {
(Some(share), Some(n)) if n > 0.0 => beta_mean(prior, STREET_PRIOR, share.clamp(0.0, 1.0), n).min(MAX_BLUFF_SHARE),
_ => prior,
}
}
/// Pool air share of shown river bets/raises at NL2 (real hands 15./16.11., `lesen/linien.py`, air =
/// equity below 0,40 vs a random hand on the final board): 10 of 68 (0,15); multi-street lines 5 of 36,
/// river all-ins 0 of 7. The balanced share `s/(1+2s)` the heuristic uses is 0,25 for a half-pot bet.
pub const POOL_RIVER_AIR: f64 = 0.15;
/// Posterior mean of a Beta prior with mean `m0` worth `k0` observations after `n` observations
/// with mean `x`.
fn beta_mean(m0: f64, k0: f64, x: f64, n: f64) -> f64 {
(k0 * m0 + n * x) / (k0 + n)
}
/// The read's fold chance as `table_fold` prices it (street read, c-bet read on a c-bet), then S1.
pub fn table_fold_of(spot: &Spot, villain: &Villain, ratio: f64, facing_raise: bool) -> f64 {
let p = villain.profile.as_ref();
let read = if line::cbet_spot(&spot.history, spot.hero_seat, spot.street) {
sized_fold(fold_base_cbet(p), ratio, facing_raise)
} else {
fold_chance_on(p, ratio, facing_raise, Some(spot.street))
};
fold(spot, villain, ratio, facing_raise, read)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_the_stages() {
assert_eq!(parse("fold"), Some(Mode { fold: true, board_weight: 1.0, fold_only_branch: false, class_rate: false, bluff: false }));
assert_eq!(parse("fold:0.5,bluff"), Some(Mode { fold: true, board_weight: 0.5, fold_only_branch: false, class_rate: false, bluff: true }));
assert_eq!(parse("fold:0,nurfold"), Some(Mode { fold: true, board_weight: 0.0, fold_only_branch: true, class_rate: false, bluff: false }));
assert_eq!(parse("0"), None);
assert_eq!(parse(""), None);
}
#[test]
fn an_average_board_keeps_the_read() {
assert!((sigmoid(logit(0.45)) - 0.45).abs() < 1e-12);
assert!((class_fold(0.2, 0.55, 0.55) - 0.2).abs() < 1e-12);
assert!((class_fold(0.7, 0.55, 0.55) - 0.7).abs() < 1e-12);
}
#[test]
fn a_rarely_folding_villain_folds_little_on_a_dry_board() {
// Maniac: folds 0.20 on average, 0.55 below the floor on average, 0.80 on this board.
let f = class_fold(0.2, 0.8, 0.55);
assert!((f - 0.2 * 0.8 / 0.55).abs() < 1e-12);
assert!(f < sigmoid(logit(0.2) + logit(0.8) - logit(0.55)));
assert_eq!(parse("fold,anteil").map(|m| m.class_rate), Some(true));
}
#[test]
fn shown_river_bets_pull_the_bluff_share() {
assert!((beta_mean(0.3, 15.0, 0.0, 15.0) - 0.15).abs() < 1e-12);
assert!((beta_mean(0.3, 15.0, 0.9, 0.0) - 0.3).abs() < 1e-12);
assert_eq!(parse("bluff").map(|m| (m.fold, m.bluff)), Some((false, true)));
}
}