diff --git a/src/bin/read_diff.rs b/src/bin/read_diff.rs index 58deb514..44a880ea 100644 --- a/src/bin/read_diff.rs +++ b/src/bin/read_diff.rs @@ -1,33 +1,59 @@ -//! Paired A/B of the memory read channels: `read_diff [deals]` plays the same deals with -//! the per-street fold read off (A) and on (B) and prints the per-deal paired difference B - A in -//! bb/100 with its 95 % CI (luck-corrected samples, same seed). - -use rechner::sim::memory::set_street_fold; -use rechner::sim::opponent::Opponent; -use rechner::sim::reader::{Rules, Style}; -use rechner::sim::session::{deal_samples, ReadMode, Setup}; - -fn main() { - let a: Vec = std::env::args().collect(); - let deals: u32 = a.get(2).and_then(|s| s.parse().ok()).unwrap_or(4000); - let opp = match a[1].as_str() { - "fish" => Opponent::Reader(Style::Fish), - "reg" => Opponent::Reader(Style::Reg), - "nit" => Opponent::Reader(Style::Nit), - "maniac" => Opponent::Reader(Style::Maniac), - "nem1" => Opponent::Styled(Rules { call_margin: 0.215, raise_at: 0.587, bet_at: 0.548, open_at: 0.729, bluff: 0.068, size: 0.441 }), - "nem2" => Opponent::Styled(Rules { call_margin: 0.173, raise_at: 0.579, bet_at: 0.748, open_at: 0.800, bluff: 0.229, size: 0.996 }), - "nem3" => Opponent::Styled(Rules { call_margin: 0.396, raise_at: 0.769, bet_at: 0.615, open_at: 0.468, bluff: 0.261, size: 1.148 }), - o => panic!("profil? {o}"), - }; - let setup = Setup { players: 2, opponent: opp, deals, stack_bb: 100.0, seed: std::env::var("SEED").ok().and_then(|s| s.parse().ok()).unwrap_or(0x5EED_0001), read: ReadMode::Memory }; - set_street_fold(false); - let (xa, ma) = deal_samples(&setup); - set_street_fold(true); - let (xb, mb) = deal_samples(&setup); - let d: Vec = xa.iter().zip(&xb).map(|(p, q)| q - p).collect(); - let n = d.len() as f64; - let mean = d.iter().sum::() / n; - let var = d.iter().map(|x| (x - mean).powi(2)).sum::() / (n - 1.0); - println!("{} A {:+.2} B {:+.2} diff {:+.2} +-{:.2}", a[1], ma.bb_per_100, mb.bb_per_100, 100.0 * mean, 100.0 * 1.96 * (var / n).sqrt()); -} +//! Paired A/B of the memory read channels: `read_diff [deals]` plays the same deals with +//! the per-street fold read off (A) and on (B) and prints the per-deal paired difference B - A in +//! bb/100 with its 95 % CI (luck-corrected samples, same seed). + +use rechner::exploit::bayes::{set_lcb_z, set_strengths}; +use rechner::sim::memory::{set_bayes, set_street_fold}; +use rechner::sim::opponent::Opponent; +use rechner::sim::reader::{Rules, Style}; +use rechner::sim::session::{deal_samples, ReadMode, Setup}; + +fn main() { + let a: Vec = std::env::args().collect(); + let deals: u32 = a.get(2).and_then(|s| s.parse().ok()).unwrap_or(4000); + let opp = match a[1].as_str() { + "fish" => Opponent::Reader(Style::Fish), + "reg" => Opponent::Reader(Style::Reg), + "nit" => Opponent::Reader(Style::Nit), + "maniac" => Opponent::Reader(Style::Maniac), + "nem1" => Opponent::Styled(Rules { call_margin: 0.215, raise_at: 0.587, bet_at: 0.548, open_at: 0.729, bluff: 0.068, size: 0.441 }), + "nem2" => Opponent::Styled(Rules { call_margin: 0.173, raise_at: 0.579, bet_at: 0.748, open_at: 0.800, bluff: 0.229, size: 0.996 }), + "nem3" => Opponent::Styled(Rules { call_margin: 0.396, raise_at: 0.769, bet_at: 0.615, open_at: 0.468, bluff: 0.261, size: 1.148 }), + o => panic!("profil? {o}"), + }; + let setup = Setup { players: 2, opponent: opp, deals, stack_bb: 100.0, seed: std::env::var("SEED").ok().and_then(|s| s.parse().ok()).unwrap_or(0x5EED_0001), read: ReadMode::Memory }; + // Arms (args 3..): street = per-street fold read (0d4c3a4), bayes = hierarchical model, + // bayesz = model with z posterior sds taken off the fold rate, off = pooled only. + // The first arm is the reference; every other arm is reported as a paired difference to it. + let arms: Vec = if a.len() > 3 { a[3..].to_vec() } else { vec!["street".into(), "bayes".into()] }; + let mut runs: Vec<(String, Vec, f64)> = Vec::new(); + for arm in &arms { + // bayes[:z=][:s=,,] + let mut parts = arm.split(':'); + let kind = parts.next().unwrap_or(""); + let (mut z, mut st) = (0.0, (15.0, 12.0, 10.0)); + for part in parts { + if let Some(v) = part.strip_prefix("z=") { + z = v.parse().unwrap(); + } else if let Some(v) = part.strip_prefix("s=") { + let n: Vec = v.split(',').map(|x| x.parse().unwrap()).collect(); + st = (n[0], n[1], n[2]); + } + } + set_street_fold(kind == "street"); + set_bayes(kind == "bayes"); + set_lcb_z(z); + set_strengths(st.0, st.1, st.2); + let (x, m) = deal_samples(&setup); + runs.push((arm.clone(), x, m.bb_per_100)); + } + let (_, base, mb0) = &runs[0]; + println!("{} ref {} {:+.2}", a[1], runs[0].0, mb0); + for (name, x, m) in &runs[1..] { + let d: Vec = base.iter().zip(x).map(|(p, q)| q - p).collect(); + let n = d.len() as f64; + let mean = d.iter().sum::() / n; + let var = d.iter().map(|x| (x - mean).powi(2)).sum::() / (n - 1.0); + println!("{} {} {:+.2} diff {:+.2} +-{:.2}", a[1], name, m, 100.0 * mean, 100.0 * 1.96 * (var / n).sqrt()); + } +} diff --git a/src/exploit/bayes.rs b/src/exploit/bayes.rs new file mode 100644 index 00000000..3e08214d --- /dev/null +++ b/src/exploit/bayes.rs @@ -0,0 +1,585 @@ +//! Hierarchical Bayes opponent model: population -> archetype cluster -> individual. +//! +//! The memory (`sim::memory`) feeds every observed action of one opponent in as a count in a +//! conjugate cell (Dirichlet over {fold, call, raise} facing a bet; Beta over bet/passive for +//! aggression), keyed by the dimensions the observer could see: street, bet-size bucket, facing a +//! raise, preflop-aggressor role, position, board texture. A dimension the observer cannot supply is +//! `None`; the observation then counts on the coarser levels only. So when the observer starts +//! delivering a new dimension (a richer population, showdown texture cells) nothing here changes: the +//! cells fill and the deeper levels start to carry data. +//! +//! Shrinkage by data: a cell's posterior is `counts + strength * parent_mean`, the parent being the +//! next coarser cell (pooled -> street -> size -> raise-state -> role -> position -> texture). A thin +//! cell stays at its parent, a well-observed one moves to its own rate. The pooled level's parent is +//! the CLUSTER prior: the mean of five archetypes weighted by soft responsibilities learned from the +//! observed pooled frequencies (vpip, pfr, aggression, fold-to-bet), never a hard label. The prior's +//! strength is the Beta-equivalent of the mixture's variance: archetypes that disagree, or aggressive +//! archetypes with wide spread, give a weak prior, so aggressive extremes are not pulled to a median +//! (the lesson of the uniform population prior, `mem-prior-loser`). +//! +//! The snapshot (`ReadModel`) hands the engine posterior mean AND standard deviation per cell, so +//! downstream exploits can scale their strength by the confidence. + +use super::fold_chance::{RAISE_RESISTANCE, REFERENCE_RATIO}; +use std::collections::BTreeMap; + +pub const MAX_DIMS: usize = 6; +const WILD: u8 = u8::MAX; +/// Dimension slots, in hierarchy order (coarse to fine). +pub const D_STREET: usize = 0; +pub const D_SIZE: usize = 1; +pub const D_RAISE: usize = 2; +pub const D_ROLE: usize = 3; +pub const D_POSITION: usize = 4; +pub const D_TEXTURE: usize = 5; + +pub const SIZE_BUCKETS: usize = 3; +/// Pressure ratio each size bucket stands for when its cell is converted back to a reference-size +/// fold read (`REFERENCE_RATIO` = 0.66 is the middle one). +pub const SIZE_REP: [f64; SIZE_BUCKETS] = [0.33, 0.66, 1.1]; + +static LCB_Z_BITS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// How many posterior standard deviations are taken off the fold read (uncertainty-scaled +/// exploitation). 0 = posterior mean. Process-wide knob so the ladder can A/B it. +pub fn lcb_z() -> f64 { + f64::from_bits(LCB_Z_BITS.load(std::sync::atomic::Ordering::Relaxed)) +} + +pub fn set_lcb_z(z: f64) { + LCB_Z_BITS.store(z.to_bits(), std::sync::atomic::Ordering::Relaxed); +} + +static STRENGTH_BITS: [std::sync::atomic::AtomicU64; 3] = [ + std::sync::atomic::AtomicU64::new(0x402E_0000_0000_0000), // 15.0 + std::sync::atomic::AtomicU64::new(0x4028_0000_0000_0000), // 12.0 + std::sync::atomic::AtomicU64::new(0x4024_0000_0000_0000), // 10.0 +]; + +/// Pseudo-count weights of the street / size / raise-state levels (ladder A/B knob). +pub fn set_strengths(street: f64, size: f64, raise: f64) { + for (b, v) in STRENGTH_BITS.iter().zip([street, size, raise]) { + b.store(v.to_bits(), std::sync::atomic::Ordering::Relaxed); + } +} + +fn strengths() -> [f64; MAX_DIMS] { + let g = |i: usize| f64::from_bits(STRENGTH_BITS[i].load(std::sync::atomic::Ordering::Relaxed)); + [g(0), g(1), g(2), FINE_STRENGTH, FINE_STRENGTH, FINE_STRENGTH] +} + +pub type Dims = [Option; MAX_DIMS]; +pub const NO_DIMS: Dims = [None; MAX_DIMS]; + +/// Size bucket of a pressure ratio (chips beyond a call over the pot after calling). +pub fn size_bucket(ratio: f64) -> usize { + if ratio < 0.45 { + 0 + } else if ratio < 0.85 { + 1 + } else { + 2 + } +} + +/// Outcome facing a bet. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Facing { + Fold = 0, + Call = 1, + Raise = 2, +} + +/// Posterior mean and standard deviation of a frequency. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Est { + pub mean: f64, + pub sd: f64, +} + +impl Est { + fn beta(a: f64, b: f64) -> Est { + let n = a + b; + Est { mean: a / n, sd: (a * b / (n * n * (n + 1.0))).sqrt() } + } +} + +/// Counts by dimension prefix: key `[v0, v1, .., WILD..]` holds every observation whose first +/// dimensions equal the prefix (and which had those dimensions at all). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Cells { + map: BTreeMap<[u8; MAX_DIMS], [f64; K]>, +} + +impl Cells { + pub fn observe(&mut self, dims: &Dims, cat: usize) { + let mut key = [WILD; MAX_DIMS]; + self.map.entry(key).or_insert([0.0; K])[cat] += 1.0; + for (i, d) in dims.iter().enumerate() { + let Some(v) = d else { break }; + key[i] = *v; + self.map.entry(key).or_insert([0.0; K])[cat] += 1.0; + } + } + + /// Counts of the cell identified by the first `depth` dimensions. + pub fn counts(&self, dims: &Dims, depth: usize) -> [f64; K] { + let mut key = [WILD; MAX_DIMS]; + for i in 0..depth.min(MAX_DIMS) { + match dims[i] { + Some(v) => key[i] = v, + None => return [0.0; K], + } + } + self.map.get(&key).copied().unwrap_or([0.0; K]) + } + + pub fn total(&self) -> f64 { + self.counts(&NO_DIMS, 0).iter().sum() + } + + /// Hierarchical posterior alphas of the cell `dims` down to `depth` levels. `prior` is the + /// cluster-level alpha; `strength[l]` is the pseudo-count weight the parent mean carries into + /// level `l` (0 = pooled uses the prior itself); `adjust(l, v, parent_mean)` maps the parent's + /// mean to the child prior mean (a size law, a raise-resistance factor, or the identity). + pub fn posterior( + &self, + prior: [f64; K], + dims: &Dims, + depth: usize, + strength: &[f64; MAX_DIMS], + adjust: &dyn Fn(usize, u8, [f64; K]) -> [f64; K], + ) -> [f64; K] { + let mut alpha = prior; + let pooled = self.counts(dims, 0); + for k in 0..K { + alpha[k] += pooled[k]; + } + for l in 0..depth.min(MAX_DIMS) { + let Some(v) = dims[l] else { break }; + let sum: f64 = alpha.iter().sum(); + let mut mean = [0.0; K]; + for k in 0..K { + mean[k] = alpha[k] / sum; + } + let child_mean = adjust(l, v, mean); + let counts = self.counts(dims, l + 1); + for k in 0..K { + alpha[k] = counts[k] + strength[l] * child_mean[k]; + } + } + alpha + } +} + +// --------------------------------------------------------------------------------------------- +// Archetype clusters (the population level) +// --------------------------------------------------------------------------------------------- + +pub const N_CLUSTER: usize = 5; + +/// One archetype: mean pooled frequencies and how tightly the population clusters around them +/// (Beta concentration; small = wide = the extremes keep their spread). +#[derive(Clone, Copy, Debug)] +pub struct Cluster { + pub name: &'static str, + pub vpip: f64, + pub pfr: f64, + pub aggression: f64, + pub fold: f64, + /// Fraction of facing-a-bet actions that are raises. + pub raise: f64, + /// Concentration for vpip / pfr / aggression / fold-to-bet. + pub conc: [f64; 4], +} + +pub const CLUSTERS: [Cluster; N_CLUSTER] = [ + Cluster { name: "nit", vpip: 0.12, pfr: 0.09, aggression: 0.28, fold: 0.62, raise: 0.04, conc: [30.0, 30.0, 20.0, 20.0] }, + Cluster { name: "reg", vpip: 0.25, pfr: 0.19, aggression: 0.36, fold: 0.45, raise: 0.08, conc: [25.0, 25.0, 20.0, 20.0] }, + Cluster { name: "lag", vpip: 0.38, pfr: 0.28, aggression: 0.50, fold: 0.40, raise: 0.12, conc: [10.0, 10.0, 8.0, 10.0] }, + Cluster { name: "station", vpip: 0.50, pfr: 0.08, aggression: 0.12, fold: 0.22, raise: 0.04, conc: [25.0, 25.0, 20.0, 20.0] }, + Cluster { name: "maniac", vpip: 0.65, pfr: 0.40, aggression: 0.62, fold: 0.30, raise: 0.15, conc: [8.0, 8.0, 6.0, 8.0] }, +]; + +/// Evidence tempering: the four pooled frequencies are correlated, so their likelihoods are not +/// multiplied at full weight. +const TEMPER: f64 = 0.5; +/// Beta-equivalent strength limits of the cluster-mixture prior on a pooled frequency. +const PRIOR_MIN: f64 = 4.0; +const PRIOR_MAX: f64 = 24.0; +/// Pseudo-count weight of the street level above the pooled one (the proven per-street channel). +const STREET_STRENGTH: f64 = 15.0; +const SIZE_STRENGTH: f64 = 12.0; +const RAISE_STRENGTH: f64 = 10.0; +const FINE_STRENGTH: f64 = 10.0; + +/// Pooled opportunity counts for the cluster responsibilities. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Pooled { + pub hands: f64, + pub vpip: f64, + pub pfr: f64, + pub postflop: f64, + pub aggressive: f64, + pub facing: f64, + pub folded: f64, +} + +fn ln_gamma(x: f64) -> f64 { + // Lanczos (g = 7, n = 9). + const C: [f64; 9] = [ + 0.999_999_999_999_809_9, + 676.520_368_121_885_1, + -1_259.139_216_722_402_8, + 771.323_428_777_653_1, + -176.615_029_162_140_6, + 12.507_343_278_686_905, + -0.138_571_095_265_720_12, + 9.984_369_578_019_572e-6, + 1.505_632_735_149_311_6e-7, + ]; + if x < 0.5 { + return (std::f64::consts::PI / (std::f64::consts::PI * x).sin()).ln() - ln_gamma(1.0 - x); + } + let x = x - 1.0; + let mut a = C[0]; + let t = x + 7.5; + for (i, c) in C.iter().enumerate().skip(1) { + a += c / (x + i as f64); + } + 0.5 * (2.0 * std::f64::consts::PI).ln() + (x + 0.5) * t.ln() - t + a.ln() +} + +fn ln_beta(a: f64, b: f64) -> f64 { + ln_gamma(a) + ln_gamma(b) - ln_gamma(a + b) +} + +/// Beta-binomial log likelihood up to the binomial coefficient (identical across clusters). +fn bb_ll(k: f64, n: f64, mean: f64, conc: f64) -> f64 { + if n <= 0.0 { + return 0.0; + } + let (a, b) = (mean * conc, (1.0 - mean) * conc); + ln_beta(k + a, n - k + b) - ln_beta(a, b) +} + +/// Soft cluster responsibilities from the pooled frequencies (equal prior weights). +pub fn responsibilities(p: &Pooled) -> [f64; N_CLUSTER] { + let mut ll = [0.0; N_CLUSTER]; + for (i, c) in CLUSTERS.iter().enumerate() { + ll[i] = TEMPER + * (bb_ll(p.vpip, p.hands, c.vpip, c.conc[0]) + + bb_ll(p.pfr, p.hands, c.pfr, c.conc[1]) + + bb_ll(p.aggressive, p.postflop, c.aggression, c.conc[2]) + + bb_ll(p.folded, p.facing, c.fold, c.conc[3])); + } + let max = ll.iter().cloned().fold(f64::NEG_INFINITY, f64::max); + let mut w = [0.0; N_CLUSTER]; + let mut sum = 0.0; + for i in 0..N_CLUSTER { + w[i] = (ll[i] - max).exp(); + sum += w[i]; + } + for x in w.iter_mut() { + *x /= sum; + } + w +} + +/// Mixture mean and Beta-equivalent strength of one cluster frequency under the responsibilities. +fn mixture(resp: &[f64; N_CLUSTER], mean: impl Fn(&Cluster) -> f64, conc: impl Fn(&Cluster) -> f64) -> (f64, f64) { + let m: f64 = CLUSTERS.iter().zip(resp).map(|(c, r)| r * mean(c)).sum(); + let var: f64 = CLUSTERS + .iter() + .zip(resp) + .map(|(c, r)| { + let mu = mean(c); + r * (mu * (1.0 - mu) / (conc(c) + 1.0) + (mu - m) * (mu - m)) + }) + .sum(); + let s = if var > 1e-9 { m * (1.0 - m) / var - 1.0 } else { PRIOR_MAX }; + (m, s.clamp(PRIOR_MIN, PRIOR_MAX)) +} + +// --------------------------------------------------------------------------------------------- +// The model +// --------------------------------------------------------------------------------------------- + +/// Everything the engine reads from the model for one opponent. Plain data, `Copy`. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ReadModel { + /// Fold vs call facing a bet, by street x size bucket x facing-a-raise (0 = first bet, 1 = + /// raised). Mean is the fold probability AT the bucket's representative size and raise state. + pub fold: [[[Est; 2]; SIZE_BUCKETS]; 3], + /// Fold vs call by street (all sizes pooled). + pub street_fold: [Est; 3], + pub fold_pooled: Est, + pub aggression: Est, + pub vpip: Est, + pub pfr: Est, + /// Soft archetype responsibilities (nit, reg, lag, station, maniac). + pub cluster: [f64; N_CLUSTER], +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct OpponentModel { + fold: Cells<3>, + aggr: Cells<2>, + pool: Pooled, +} + +fn fold_adjust(level: usize, value: u8, parent: [f64; 3]) -> [f64; 3] { + let non_raise = (parent[0] + parent[1]).max(1e-12); + let q = parent[0] / non_raise; + let q = match level { + D_SIZE => 1.0 - (1.0 - q).powf(SIZE_REP[(value as usize).min(SIZE_BUCKETS - 1)] / REFERENCE_RATIO), + D_RAISE if value == 1 => q * RAISE_RESISTANCE, + _ => q, + }; + [non_raise * q, non_raise * (1.0 - q), parent[2]] +} + +impl OpponentModel { + pub fn new() -> Self { + Self::default() + } + + /// One preflop hand of this opponent. + pub fn observe_preflop(&mut self, voluntary: bool, raised: bool) { + self.pool.hands += 1.0; + self.pool.vpip += voluntary as u8 as f64; + self.pool.pfr += raised as u8 as f64; + } + + /// A postflop action that was not a fold (check, call, bet, raise): the aggression opportunity. + pub fn observe_aggression(&mut self, dims: &Dims, aggressive: bool) { + self.pool.postflop += 1.0; + self.pool.aggressive += aggressive as u8 as f64; + self.aggr.observe(dims, aggressive as usize); + } + + /// The opponent faced a bet and folded, called or raised. + pub fn observe_facing(&mut self, dims: &Dims, outcome: Facing) { + if outcome != Facing::Raise { + self.pool.facing += 1.0; + self.pool.folded += (outcome == Facing::Fold) as u8 as f64; + } + self.fold.observe(dims, outcome as usize); + } + + fn fold_prior(&self, resp: &[f64; N_CLUSTER]) -> [f64; 3] { + let (q, s) = mixture(resp, |c| c.fold, |c| c.conc[3]); + let r: f64 = CLUSTERS.iter().zip(resp).map(|(c, w)| w * c.raise).sum(); + [s * q * (1.0 - r), s * (1.0 - q) * (1.0 - r), s * r] + } + + /// Hierarchical fold/call posterior of one cell: depth = how many dimensions to use. + pub fn fold_est(&self, dims: &Dims, depth: usize) -> Est { + let resp = responsibilities(&self.pool); + self.fold_est_with(&resp, dims, depth) + } + + fn fold_est_with(&self, resp: &[f64; N_CLUSTER], dims: &Dims, depth: usize) -> Est { + let a = self.fold.posterior(self.fold_prior(resp), dims, depth, &strengths(), &fold_adjust); + Est::beta(a[0], a[1]) + } + + /// Hierarchical posterior of the pooled/by-street aggression. + pub fn aggression_est(&self, dims: &Dims, depth: usize) -> Est { + let resp = responsibilities(&self.pool); + let (m, s) = mixture(&resp, |c| c.aggression, |c| c.conc[2]); + // Categories: 0 passive, 1 aggressive. + let prior = [s * (1.0 - m), s * m]; + let strength = [STREET_STRENGTH, FINE_STRENGTH, FINE_STRENGTH, FINE_STRENGTH, FINE_STRENGTH, FINE_STRENGTH]; + let a = self.aggr.posterior(prior, dims, depth, &strength, &|_, _, m| m); + Est::beta(a[1], a[0]) + } + + /// The full read for the engine. + pub fn snapshot(&self) -> ReadModel { + let resp = responsibilities(&self.pool); + let mut fold = [[[Est { mean: 0.0, sd: 0.0 }; 2]; SIZE_BUCKETS]; 3]; + let mut street_fold = [Est { mean: 0.0, sd: 0.0 }; 3]; + for s in 0..3 { + let mut d = NO_DIMS; + d[D_STREET] = Some(s as u8); + street_fold[s] = self.fold_est_with(&resp, &d, 1); + for b in 0..SIZE_BUCKETS { + d[D_SIZE] = Some(b as u8); + for r in 0..2 { + d[D_RAISE] = Some(r as u8); + fold[s][b][r] = self.fold_est_with(&resp, &d, 3); + } + } + } + let (vm, vs) = mixture(&resp, |c| c.vpip, |c| c.conc[0]); + let (pm, ps) = mixture(&resp, |c| c.pfr, |c| c.conc[1]); + let hands = self.pool.hands; + ReadModel { + fold, + street_fold, + fold_pooled: self.fold_est_with(&resp, &NO_DIMS, 0), + aggression: self.aggression_est(&NO_DIMS, 0), + vpip: Est::beta(self.pool.vpip + vs * vm, hands - self.pool.vpip + vs * (1.0 - vm)), + pfr: Est::beta(self.pool.pfr + ps * pm, hands - self.pool.pfr + ps * (1.0 - pm)), + cluster: resp, + } + } + + /// Debug dump of the raw (street, size, raise) fold/call/raise counts. + pub fn debug_counts(&self) -> String { + let mut out = String::new(); + for st in 0..3u8 { + for b in 0..3u8 { + for r in 0..2u8 { + let mut d = NO_DIMS; + d[D_STREET] = Some(st); + d[D_SIZE] = Some(b); + d[D_RAISE] = Some(r); + let c = self.fold.counts(&d, 3); + if c.iter().sum::() > 0.0 { + out += &format!(" cnt s{st} b{b} r{r}: fold {} call {} raise {} +", c[0], c[1], c[2]); + } + } + } + } + out + } + + pub fn pooled(&self) -> &Pooled { + &self.pool + } + + /// Facing-a-bet samples seen. + pub fn facing_samples(&self) -> f64 { + self.fold.total() + } +} + +impl ReadModel { + /// Fold probability at the reference size (`REFERENCE_RATIO`, no raise) implied by the cell that + /// `ratio` / `facing_raise` fall in on `street` (0 flop, 1 turn, 2 river): the cell's rate at its + /// representative size, converted back through the size law, so `fold_chance` composes with its + /// own sizing and raise-resistance unchanged. Also the cell's sd, in the same reference units. + pub fn fold_at_reference(&self, street: usize, ratio: f64, facing_raise: bool) -> (f64, f64) { + let b = size_bucket(ratio); + let est = self.fold[street.min(2)][b][facing_raise as usize]; + let (mut p, mut sd) = (est.mean, est.sd); + if facing_raise { + p = (p / RAISE_RESISTANCE).min(0.99); + sd /= RAISE_RESISTANCE; + } + let k = REFERENCE_RATIO / SIZE_REP[b]; + let f = 1.0 - (1.0 - p.clamp(0.0, 0.999)).powf(k); + // d f / d p at p: k (1-p)^(k-1) + let slope = k * (1.0 - p.clamp(0.0, 0.999)).powf(k - 1.0); + (f.clamp(0.0, 1.0), sd * slope) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn dims(street: u8, size: u8, raise: u8) -> Dims { + let mut d = NO_DIMS; + d[D_STREET] = Some(street); + d[D_SIZE] = Some(size); + d[D_RAISE] = Some(raise); + d + } + + #[test] + fn prefix_counts_nest_and_unknown_dimensions_stop_at_the_coarser_level() { + let mut c: Cells<2> = Cells::default(); + c.observe(&dims(0, 1, 0), 0); + let mut partial = NO_DIMS; + partial[D_STREET] = Some(0); + c.observe(&partial, 1); // size unknown: counts on pooled + street only + assert_eq!(c.counts(&NO_DIMS, 0), [1.0, 1.0]); + assert_eq!(c.counts(&dims(0, 1, 0), 1), [1.0, 1.0]); + assert_eq!(c.counts(&dims(0, 1, 0), 2), [1.0, 0.0]); + } + + #[test] + fn a_thin_cell_stays_at_its_parent_and_a_full_one_moves() { + let mut m = OpponentModel::new(); + for _ in 0..200 { + m.observe_facing(&dims(1, 1, 0), Facing::Call); + m.observe_facing(&dims(0, 1, 0), Facing::Fold); + } + // One flop-size-0 sample does not move that cell away from the street level much. + m.observe_facing(&dims(0, 0, 0), Facing::Call); + let street = m.fold_est(&dims(0, 1, 0), 1); + let cell = m.fold_est(&dims(0, 0, 0), 3); + assert!(street.mean > 0.8, "street {:?}", street); + assert!(cell.mean > 0.6, "thin cell should stay near its parent: {:?}", cell); + // The turn is its own, well observed cell: it moved to the call rate. + assert!(m.fold_est(&dims(1, 1, 0), 3).mean < 0.2); + } + + #[test] + fn soft_responsibilities_follow_the_observed_style() { + let mut station = OpponentModel::new(); + let mut maniac = OpponentModel::new(); + for i in 0..300 { + station.observe_preflop(i % 2 == 0, i % 12 == 0); + station.observe_aggression(&NO_DIMS, i % 9 == 0); + station.observe_facing(&dims(0, 1, 0), if i % 5 == 0 { Facing::Fold } else { Facing::Call }); + maniac.observe_preflop(i % 3 != 0, i % 5 < 2); + maniac.observe_aggression(&NO_DIMS, i % 5 < 3); + maniac.observe_facing(&dims(0, 1, 0), if i % 3 == 0 { Facing::Fold } else { Facing::Call }); + } + let rs = station.snapshot().cluster; + let rm = maniac.snapshot().cluster; + assert!(rs[3] > 0.6, "station responsibilities {:?}", rs); + assert!(rm[4] > 0.4, "maniac responsibilities {:?}", rm); + assert!((rs.iter().sum::() - 1.0).abs() < 1e-9); + } + + #[test] + fn without_data_the_cell_posterior_is_the_cluster_prior_and_uncertain() { + let m = OpponentModel::new(); + let e = m.fold_est(&dims(0, 1, 0), 3); + assert!(e.mean > 0.3 && e.mean < 0.55, "{:?}", e); + assert!(e.sd > 0.05, "no data must leave real uncertainty: {:?}", e); + } + + #[test] + fn size_law_prior_makes_small_bets_fold_less_without_data() { + let m = OpponentModel::new(); + let small = m.fold_est(&dims(0, 0, 0), 3).mean; + let mid = m.fold_est(&dims(0, 1, 0), 3).mean; + let big = m.fold_est(&dims(0, 2, 0), 3).mean; + assert!(small < mid && mid < big, "{small} {mid} {big}"); + // Raised state folds less than the first bet. + assert!(m.fold_est(&dims(0, 1, 1), 3).mean < mid); + } + + #[test] + fn reference_conversion_round_trips_the_prior() { + // With no data in any cell the converted reference fold equals the pooled prior mean. + let m = OpponentModel::new(); + let rm = m.snapshot(); + let pooled = rm.fold_pooled.mean; + for b in 0..SIZE_BUCKETS { + for r in [false, true] { + let (f, _) = rm.fold_at_reference(0, SIZE_REP[b], r); + assert!((f - pooled).abs() < 0.03, "bucket {b} raise {r}: {f} vs {pooled}"); + } + } + } + + #[test] + fn more_data_shrinks_the_uncertainty() { + let mut m = OpponentModel::new(); + let before = m.fold_est(&dims(0, 1, 0), 3).sd; + for i in 0..400 { + m.observe_facing(&dims(0, 1, 0), if i % 2 == 0 { Facing::Fold } else { Facing::Call }); + } + let after = m.fold_est(&dims(0, 1, 0), 3); + assert!(after.sd < before / 2.0); + assert!((after.mean - 0.5).abs() < 0.05); + } +} diff --git a/src/exploit/fold_chance.rs b/src/exploit/fold_chance.rs index a4c07e4e..617f71fc 100644 --- a/src/exploit/fold_chance.rs +++ b/src/exploit/fold_chance.rs @@ -70,6 +70,29 @@ pub fn fold_base_on(profile: Option<&Profile>, street: Option) -> f64 { } } +/// The reference-size fold read from the hierarchical Bayes model (`exploit::bayes`) for the cell +/// this bet falls in: street x size bucket x raise state, shrunk through the archetype clusters. +/// `None` without a model on the profile or off the postflop streets (the legacy path then runs). +/// The posterior sd scales the read's strength: `bayes::lcb_z()` standard deviations are taken off +/// the fold rate (0 = posterior mean). Station trust applies on top, as for the pooled read. +pub fn fold_base_model(profile: Option<&Profile>, street: Option, ratio: f64, facing_raise: bool) -> Option { + let p = profile?; + let model = p.fold_model.as_ref()?; + let i = match street? { + Street::Flop => 0, + Street::Turn => 1, + Street::River => 2, + Street::Preflop => return None, + }; + let (f, sd) = model.fold_at_reference(i, ratio, facing_raise); + let raw = (f - super::bayes::lcb_z() * sd).clamp(0.0, 1.0); + Some(if classify(p) == Style::CallingStation { + DEFAULT_FOLD_TO_BET + station_trust(p) * (raw - DEFAULT_FOLD_TO_BET) + } else { + raw + }) +} + /// P(this opponent folds) to a bet of `ratio` pots. Total: any input gives `[0, MAX_FOLD]`. pub fn fold_chance(profile: Option<&Profile>, ratio: f64, facing_raise: bool) -> f64 { fold_chance_on(profile, ratio, facing_raise, None) @@ -77,7 +100,8 @@ pub fn fold_chance(profile: Option<&Profile>, ratio: f64, facing_raise: bool) -> /// `fold_chance` with the street's own fold read (`fold_base_on`). pub fn fold_chance_on(profile: Option<&Profile>, ratio: f64, facing_raise: bool, street: Option) -> f64 { - let f = fold_base_on(profile, street); + let ratio_in = if ratio.is_nan() { 0.0 } else { ratio.max(0.0) }; + let f = fold_base_model(profile, street, ratio_in, facing_raise).unwrap_or_else(|| fold_base_on(profile, street)); let ratio = if ratio.is_nan() { 0.0 } else { ratio.max(0.0) }; let sized = if f >= 1.0 { if ratio > 0.0 { 1.0 } else { 0.0 } diff --git a/src/exploit/mark.rs b/src/exploit/mark.rs index 195e445d..17f55324 100644 --- a/src/exploit/mark.rs +++ b/src/exploit/mark.rs @@ -16,6 +16,7 @@ const WEAK_PLAYER: Profile = Profile { turn_aggression: None, river_aggression: None, street_fold_to_bet: [None; 3], + fold_model: None, cbet: None, fold_to_cbet: None, three_bet: None, @@ -45,6 +46,7 @@ pub fn with_mark(measured: Option, mark: &str) -> Option { turn_aggression: known.turn_aggression.or(prior.turn_aggression), river_aggression: known.river_aggression.or(prior.river_aggression), street_fold_to_bet: known.street_fold_to_bet, + fold_model: known.fold_model, cbet: known.cbet.or(prior.cbet), fold_to_cbet: known.fold_to_cbet.or(prior.fold_to_cbet), three_bet: known.three_bet.or(prior.three_bet), diff --git a/src/exploit/mod.rs b/src/exploit/mod.rs index a1066f17..098f8f58 100644 --- a/src/exploit/mod.rs +++ b/src/exploit/mod.rs @@ -2,6 +2,7 @@ pub mod adjust; pub mod band_bounds; +pub mod bayes; pub mod band_stretch; pub mod bet_ratio; pub mod bluff_share; diff --git a/src/exploit/profile.rs b/src/exploit/profile.rs index 0034fe2b..476c00bf 100644 --- a/src/exploit/profile.rs +++ b/src/exploit/profile.rs @@ -1,3 +1,5 @@ +use super::bayes::ReadModel; + /// Observed opponent tendencies, all frequencies in `[0, 1]`. Every field optional. /// Wire shape (extension): /// `"profile": {"vpip": 0.45, "pfr": 0.08, "foldToBet": 0.3, "aggression": 0.4}`. @@ -32,6 +34,10 @@ pub struct Profile { /// pooled read and a well-sampled one moves to its own rate. `None` per street = no data. Read /// only by `fold_chance::fold_chance_on` (hero's fold equity on that street). pub street_fold_to_bet: [Option; 3], + /// Hierarchical Bayes read (`exploit::bayes`): fold-vs-call posterior mean AND sd per street x + /// size bucket x raise state, shrunk through archetype clusters. Memory-only; `None` for the + /// oracle, blind and the wire. When present it replaces `street_fold_to_bet` in `fold_chance_on`. + pub fold_model: Option, /// How often the player continuation-bets the flop as the preflop aggressor. pub cbet: Option, /// How often the player folds to a continuation bet. diff --git a/src/exploit/sample.rs b/src/exploit/sample.rs index 393fdc6b..ff3d304d 100644 --- a/src/exploit/sample.rs +++ b/src/exploit/sample.rs @@ -27,6 +27,7 @@ pub const PRIOR: Profile = Profile { turn_aggression: None, river_aggression: None, street_fold_to_bet: [None; 3], + fold_model: None, cbet: None, fold_to_cbet: None, three_bet: None, @@ -64,6 +65,7 @@ pub fn shrink(profile: &Profile, hands: f64) -> Profile { turn_aggression: pull(profile.turn_aggression, PRIOR.turn_aggression, w), river_aggression: pull(profile.river_aggression, PRIOR.river_aggression, w), street_fold_to_bet: profile.street_fold_to_bet, + fold_model: profile.fold_model, cbet: pull(profile.cbet, PRIOR.cbet, w), fold_to_cbet: pull(profile.fold_to_cbet, PRIOR.fold_to_cbet, w), three_bet: pull(profile.three_bet, PRIOR.three_bet, w), diff --git a/src/sim/memory.rs b/src/sim/memory.rs index d9965fa7..c93a4e5f 100644 --- a/src/sim/memory.rs +++ b/src/sim/memory.rs @@ -9,6 +9,8 @@ //! twin, the share of the prize that observation alone earns. Every opponent seat is the same fixed //! archetype, so their counts pool into one read. +use crate::exploit::bayes::{size_bucket, Dims, Facing, OpponentModel, D_POSITION, D_RAISE, D_ROLE, D_SIZE, D_STREET, NO_DIMS}; +use crate::exploit::pot_trace::{contribution, pot_before}; use crate::exploit::profile::Profile; use crate::game::{ActionRecord, SeenAction, Street}; @@ -73,6 +75,71 @@ fn street_fold_on() -> bool { STREET_FOLD.load(std::sync::atomic::Ordering::Relaxed) } +static BAYES: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// Switch the hierarchical Bayes read (`exploit::bayes`) on or off (A/B arm for the ladder). When on +/// it replaces the per-street fold read; when off the memory behaves exactly as before. +pub fn set_bayes(on: bool) { + BAYES.store(on, std::sync::atomic::Ordering::Relaxed); +} + +fn bayes_on() -> bool { + BAYES.load(std::sync::atomic::Ordering::Relaxed) +} + +/// What a villain decision faced: the pressure ratio of the bet (if the pot is traceable) and +/// whether the villain had already bet this street (so it faces a raise). +#[derive(Clone, Copy)] +struct Faced { + ratio: Option, + raised: bool, +} + +/// Pressure of the aggressive record `i`, in the same units hero's fold equity uses +/// (`table_fold::pressure_ratio`): chips beyond a call over the pot after calling. +fn pressure_of(history: &[ActionRecord], pots: &[Option], i: usize) -> Option { + let r = &history[i]; + let pot = (*pots.get(i)?)?; + let put = contribution(history, i)?; + let street = || history[..i].iter().rev().take_while(|x| x.street == r.street); + let prev_to = street().filter(|x| x.action != SeenAction::PostAnte).filter_map(|x| x.amount).fold(0.0, f64::max); + let own = street() + .filter(|x| x.seat == r.seat && x.action != SeenAction::PostAnte) + .find_map(|x| x.amount.filter(|a| a.is_finite())) + .unwrap_or(0.0); + let to_call = (prev_to - own).max(0.0); + let base = pot + to_call; + let ratio = (put - to_call).max(0.0) / base; + (base > 0.0 && ratio.is_finite()).then_some(ratio) +} + +/// For every record of `seat` postflop that answers a bet: what it faced. +fn faced_by(history: &[ActionRecord], seat: u8) -> Vec> { + let pots = pot_before(history); + let mut out = vec![None; history.len()]; + let mut street = None; + let mut outstanding: Option> = None; + let mut own_bet = false; + for (i, r) in history.iter().enumerate() { + if street != Some(r.street) { + street = Some(r.street); + outstanding = None; + own_bet = false; + } + if r.street == Street::Preflop { + continue; + } + if r.seat == seat { + out[i] = outstanding.map(|ratio| Faced { ratio, raised: own_bet }); + outstanding = None; + own_bet |= r.action.is_aggressive(); + } else if r.action.is_aggressive() { + outstanding = Some(pressure_of(history, &pots, i)); + } + } + out +} + /// The read a HUD accumulates from watching one fixed opponent archetype play a session. #[derive(Clone, Debug, Default, PartialEq)] pub struct SessionMemory { @@ -81,6 +148,7 @@ pub struct SessionMemory { /// see `sim::welt_memory`. Filled only by `observe_world_hand`; `read()` ignores it, so the classic /// HUD read (and every existing ladder number) is unchanged by it. world: WorldMemory, + model: OpponentModel, } impl SessionMemory { @@ -103,15 +171,24 @@ impl SessionMemory { pub fn observe_hand(&mut self, history: &[ActionRecord], hero: usize, players: usize) { for seat in 1..=players as u8 { if seat as usize - 1 != hero { - self.observe_seat(history, seat); + self.observe_seat(history, seat, players); } } } - fn observe_seat(&mut self, history: &[ActionRecord], seat: u8) { + fn observe_seat(&mut self, history: &[ActionRecord], seat: u8, players: usize) { self.c.hands += 1; let (mut voluntary, mut raised) = (false, false); - for r in history.iter().filter(|r| r.seat == seat) { + let faced = faced_by(history, seat); + // Preflop-aggressor role (1 = this seat made the last preflop raise, 0 = another seat did) + // and heads-up position (1 = button, in position postflop): extra cells for the model. + let role = history + .iter() + .rev() + .find(|r| r.street == Street::Preflop && r.action.is_aggressive()) + .map(|r| (r.seat == seat) as u8); + let position = (players == 2).then_some((seat == 1) as u8); + for (i, r) in history.iter().enumerate().filter(|(_, r)| r.seat == seat) { if r.street == Street::Preflop { // Blinds are forced (PostSmallBlind / PostBigBlind); a check is free. Only a call or // an aggressive action puts money in by choice. @@ -123,6 +200,37 @@ impl SessionMemory { } raised |= r.action.is_aggressive(); } else { + let street_i = street_index(r.street).map(|i| i as u8); + let mut dims: Dims = NO_DIMS; + dims[D_STREET] = street_i; + if let Some(f) = faced[i] { + dims[D_SIZE] = f.ratio.map(|x| size_bucket(x) as u8); + if dims[D_SIZE].is_some() { + dims[D_RAISE] = Some(f.raised as u8); + dims[D_ROLE] = role; + dims[D_POSITION] = position; + } + } + match r.action { + SeenAction::Fold => self.model.observe_facing(&dims, Facing::Fold), + SeenAction::Call => self.model.observe_facing(&dims, Facing::Call), + a if a.is_aggressive() && faced[i].is_some() => { + self.model.observe_facing(&dims, Facing::Raise) + } + _ => {} + } + if r.action != SeenAction::Fold { + // Aggression cells use their own layout: street, role, position. + let mut ad: Dims = NO_DIMS; + ad[0] = street_i; + if street_i.is_some() { + ad[1] = role; + if role.is_some() { + ad[2] = position; + } + } + self.model.observe_aggression(&ad, r.action.is_aggressive()); + } // Postflop a fold or a call only happens facing a bet; a check faces nothing. The // check still counts as a passive action for aggression (matching how the oracle // reads are measured, `tests/sim_opponent_stats`): leaving checks out of the @@ -156,6 +264,7 @@ impl SessionMemory { } self.c.vpip += voluntary as u32; self.c.pfr += raised as u32; + self.model.observe_preflop(voluntary, raised); } /// A passive postflop action (call or check) on the turn/river, for the per-street aggression @@ -199,7 +308,8 @@ impl SessionMemory { let street_aggr = |aggr: u32, passive: u32| ratio(aggr, aggr + passive); let pooled_fold = ratio(self.c.folded_to_bet, facing_bet); let mut street_fold_to_bet = [None; 3]; - if let (true, Some(pooled)) = (street_fold_on(), pooled_fold) { + let bayes = bayes_on(); + if let (true, false, Some(pooled)) = (street_fold_on(), bayes, pooled_fold) { for i in 0..3 { let n = (self.c.street_fold[i] + self.c.street_call[i]) as f64; if n > 0.0 { @@ -208,8 +318,19 @@ impl SessionMemory { } } } + if bayes && self.c.hands % 4000 == 0 && std::env::var("BAYES_DEBUG").is_ok() { + let m = self.model.snapshot(); + eprintln!("hands {} pooled {:?} cluster {:?}", self.c.hands, m.fold_pooled, m.cluster); + for st in 0..3 { + for b in 0..3 { + eprintln!(" s{} b{} first {:.3}+-{:.3} raised {:.3}+-{:.3}", st, b, m.fold[st][b][0].mean, m.fold[st][b][0].sd, m.fold[st][b][1].mean, m.fold[st][b][1].sd); + } + } + eprintln!("{}", self.model.debug_counts()); + } Some(Profile { street_fold_to_bet, + fold_model: bayes.then(|| self.model.snapshot()), vpip: ratio(self.c.vpip, self.c.hands), pfr: ratio(self.c.pfr, self.c.hands), fold_to_bet: ratio(self.c.folded_to_bet, facing_bet), diff --git a/src/wire/decode_villain.rs b/src/wire/decode_villain.rs index 25bd175d..2a016ca6 100644 --- a/src/wire/decode_villain.rs +++ b/src/wire/decode_villain.rs @@ -22,6 +22,7 @@ fn profile(villain: &Value, path: &str) -> Result, Fault> { turn_aggression: None, river_aggression: None, street_fold_to_bet: [None; 3], + fold_model: None, // HUD extras (lesen/profil.py DURCHGEREICHT): same client names on the wire. cbet: opt_number_member(object, &at_profile, "cbet")?, fold_to_cbet: opt_number_member(object, &at_profile, "foldToCbet")?,