//! Session memory (Stage 1): the engine builds its read from the opponent's OBSERVED actions over //! the hands of a session, instead of being handed the converged HUD read (`sim::reads`) or playing //! blind. A HUD that only counts - per opponent seat, preflop voluntary money and raises, postflop //! folds-to-a-bet and aggression - turned into a `Profile` once a warmup of hands is seen, so the //! first hands play blind and the read converges to the truth over the session. //! //! The gap blind -> read-given that `benchmarks/baseline.txt` / `tests/sim_blind` measure is exactly //! what this must recapture: a `... (memory)` scenario lands between the blind and the read-given //! 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}; pub use super::welt_memory::{ strength_band, Cell, Move, Pos, Reveal, SizeBucket, Showdown, Texture, Tank, WorldEvent, WorldHand, WorldMemory, STRENGTH_BANDS, }; /// Hands to observe before the read is trusted; until then `read` is `None` (the engine plays /// blind). Keeps an early, noisy sample from steering worse than no read at all. pub const WARMUP_HANDS: u32 = 25; /// Postflop actions at which the read's confidence reaches 0.5 (half-life). Matches the Bayesian /// posterior's `VERTRAUEN_HALB` so the counts HUD and `exploit::posterior` agree on how fast a read /// earns trust. The river gearbox turns this confidence into the KL trust radius. pub const CONFIDENCE_HALF: f64 = 30.0; /// Running tallies over the opponent archetype. Preflop opportunities (`hands`) and the voluntary / /// raise counts drive vpip and pfr; the postflop tallies drive fold-to-bet and aggression. #[derive(Clone, Copy, Debug, Default, PartialEq)] struct Counts { hands: u32, vpip: u32, pfr: u32, folded_to_bet: u32, passive_call: u32, passive_check: u32, aggressive: u32, // Per-street aggression split (turn and river only — the streets the subgame gearboxes solve). // `*_passive` is calls plus checks on that street (the aggression denominator, matching the pooled // one which counts checks); folds are excluded, as in the pooled aggression. turn_aggressive: u32, turn_passive: u32, river_aggressive: u32, river_passive: u32, // Facing-a-bet outcomes per street (flop, turn, river): folds and calls, for the per-street // fold-to-bet read. street_fold: [u32; 3], street_call: [u32; 3], } fn street_index(street: Street) -> Option { match street { Street::Flop => Some(0), Street::Turn => Some(1), Street::River => Some(2), Street::Preflop => None, } } /// Facing-a-bet samples that weigh as much as the pooled read when shrinking a street's fold rate. pub const STREET_FOLD_PRIOR: f64 = 15.0; static STREET_FOLD: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true); /// Switch the per-street fold read on or off (A/B arm for the ladder). Default on. pub fn set_street_fold(on: bool) { STREET_FOLD.store(on, std::sync::atomic::Ordering::Relaxed); } 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 { c: Counts, /// The richer dimensions (sizing x strength, texture x position cells, showdown reveals, timing), /// 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 { pub fn new() -> Self { Self::default() } /// The world-dimension observations (sizing, texture/position cells, showdowns, timing). pub fn world(&self) -> &WorldMemory { &self.world } /// Fold one finished hand's world observations (see `WorldHand`) into the world memory. pub fn observe_world_hand(&mut self, hand: &WorldHand) { self.world.observe_world_hand(hand); } /// Fold every opponent seat's actions of one finished hand into the counts. `hero` is the /// 0-based hero seat; every other of the `players` seats is an opponent of the same archetype. 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, players); } } } fn observe_seat(&mut self, history: &[ActionRecord], seat: u8, players: usize) { self.c.hands += 1; let (mut voluntary, mut raised) = (false, false); 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. match r.action { SeenAction::Call | SeenAction::Bet | SeenAction::Raise | SeenAction::AllIn => { voluntary = true; } _ => {} } 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 // denominator makes a passive, check-heavy opponent look far more aggressive than it // is, and `bluff_share` reads aggression directly. match r.action { SeenAction::Fold => { self.c.folded_to_bet += 1; if let Some(i) = street_index(r.street) { self.c.street_fold[i] += 1; } } SeenAction::Call => { if let Some(i) = street_index(r.street) { self.c.street_call[i] += 1; } self.c.passive_call += 1; self.bump_passive(r.street); } SeenAction::Check => { self.c.passive_check += 1; self.bump_passive(r.street); } a if a.is_aggressive() => { self.c.aggressive += 1; self.bump_aggressive(r.street); } _ => {} } } } 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 /// denominator. Flop and preflop are not split. fn bump_passive(&mut self, street: Street) { match street { Street::Turn => self.c.turn_passive += 1, Street::River => self.c.river_passive += 1, _ => {} } } /// An aggressive postflop action (bet or raise) on the turn/river, for the per-street numerator. fn bump_aggressive(&mut self, street: Street) { match street { Street::Turn => self.c.turn_aggressive += 1, Street::River => self.c.river_aggressive += 1, _ => {} } } /// The read so far, or `None` during the warmup. vpip / pfr are over hands; fold-to-bet is folds /// over folds-plus-calls facing a bet; aggression is bets-and-raises over bets-raises-and-calls. pub fn read(&self) -> Option { if self.c.hands < WARMUP_HANDS { return None; } let ratio = |num: u32, den: u32| (den > 0).then(|| num as f64 / den as f64); let facing_bet = self.c.folded_to_bet + self.c.passive_call; // Aggression frequency: bets and raises over every non-folding postflop action, checks // included (see `observe_seat`). let postflop_actions = self.c.aggressive + self.c.passive_call + self.c.passive_check; // Confidence for the gearbox: the read is only as trustworthy as its weaker postflop sample — // the facing-a-bet count (drives fold_to_bet / the defense belief) and the total postflop // count (drives aggression / the betting-polarization belief). Half at CONFIDENCE_HALF. let conf = |n: u32| n as f64 / (n as f64 + CONFIDENCE_HALF); let confidence = conf(facing_bet.min(postflop_actions)); // Per-street aggression: bets/raises over bets-raises-plus-passive on that street (same shape // as the pooled frequency). `None` until the street has an action, so `believed_villain` falls // back to the pooled read. 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]; 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 { street_fold_to_bet[i] = Some((self.c.street_fold[i] as f64 + STREET_FOLD_PRIOR * pooled) / (n + STREET_FOLD_PRIOR)); } } } 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), aggression: ratio(self.c.aggressive, postflop_actions), turn_aggression: street_aggr(self.c.turn_aggressive, self.c.turn_passive), river_aggression: street_aggr(self.c.river_aggressive, self.c.river_passive), confidence: Some(confidence), ..Profile::default() }) } } #[cfg(test)] mod tests { use super::*; use crate::exploit::style::{classify, Style}; fn rec(street: Street, seat: u8, action: SeenAction) -> ActionRecord { ActionRecord { street, seat, action, amount: None } } /// One heads-up hand (hero seat 0 = seat 1, opponent seat 2): the opponent calls hero's preflop /// raise (voluntary, not a raise), then calls a flop bet and folds the turn (passive, folds to a /// bet, never aggressive). fn loose_passive_hand() -> Vec { vec![ rec(Street::Preflop, 1, SeenAction::PostSmallBlind), rec(Street::Preflop, 2, SeenAction::PostBigBlind), rec(Street::Preflop, 1, SeenAction::Raise), rec(Street::Preflop, 2, SeenAction::Call), rec(Street::Flop, 1, SeenAction::Bet), rec(Street::Flop, 2, SeenAction::Call), rec(Street::Turn, 1, SeenAction::Bet), rec(Street::Turn, 2, SeenAction::Fold), ] } #[test] fn no_read_before_the_warmup() { let mut m = SessionMemory::new(); let h = loose_passive_hand(); for _ in 0..WARMUP_HANDS - 1 { m.observe_hand(&h, 0, 2); } assert_eq!(m.read(), None); m.observe_hand(&h, 0, 2); assert!(m.read().is_some()); } #[test] fn a_seat_that_only_posts_a_blind_is_not_vpip() { // Hero seat 0; the opponent (seat 2) is the big blind and checks its option: no voluntary // money, no raise. let hand = vec![ rec(Street::Preflop, 1, SeenAction::PostSmallBlind), rec(Street::Preflop, 2, SeenAction::PostBigBlind), rec(Street::Preflop, 1, SeenAction::Call), rec(Street::Preflop, 2, SeenAction::Check), ]; let mut m = SessionMemory::new(); for _ in 0..WARMUP_HANDS { m.observe_hand(&hand, 0, 2); } let p = m.read().expect("read after warmup"); assert_eq!(p.vpip, Some(0.0)); assert_eq!(p.pfr, Some(0.0)); } #[test] fn the_loose_passive_opponent_reads_as_a_calling_station() { let mut m = SessionMemory::new(); let h = loose_passive_hand(); for _ in 0..40 { m.observe_hand(&h, 0, 2); } let p = m.read().expect("read"); assert_eq!(p.vpip, Some(1.0)); // calls every preflop assert_eq!(p.pfr, Some(0.0)); assert_eq!(p.fold_to_bet, Some(0.5)); // one call, one fold facing a bet assert_eq!(p.aggression, Some(0.0)); // never bets or raises postflop assert_eq!(classify(&p), Style::CallingStation); } #[test] fn checks_count_toward_aggression_so_a_passive_opponent_reads_passive() { // Seat 2 bets once but checks the flop in every other hand. Aggression must be 1 / (1 bet + // many checks), near zero - not 1 / 1 from leaving the checks out of the denominator. let bet = vec![ rec(Street::Preflop, 1, SeenAction::PostSmallBlind), rec(Street::Preflop, 2, SeenAction::PostBigBlind), rec(Street::Preflop, 1, SeenAction::Call), rec(Street::Preflop, 2, SeenAction::Check), rec(Street::Flop, 2, SeenAction::Bet), ]; let check = vec![ rec(Street::Preflop, 1, SeenAction::PostSmallBlind), rec(Street::Preflop, 2, SeenAction::PostBigBlind), rec(Street::Preflop, 1, SeenAction::Call), rec(Street::Preflop, 2, SeenAction::Check), rec(Street::Flop, 2, SeenAction::Check), ]; let mut m = SessionMemory::new(); m.observe_hand(&bet, 0, 2); for _ in 0..29 { m.observe_hand(&check, 0, 2); } let p = m.read().expect("read"); assert_eq!(p.aggression, Some(1.0 / 30.0)); // 1 bet, 29 checks } #[test] fn per_street_aggression_splits_the_turn_from_the_pooled_read() { // Seat 2 checks the flop (passive) but bets the turn (aggressive), no river action. The pooled // aggression is 1 bet / (1 bet + 1 check) = 0.5, but the TURN aggression is 1/1 = 1.0, and the // river stays None. This is exactly the barreler the pooled read under-sells. let hand = vec![ rec(Street::Preflop, 1, SeenAction::PostSmallBlind), rec(Street::Preflop, 2, SeenAction::PostBigBlind), rec(Street::Preflop, 1, SeenAction::Raise), rec(Street::Preflop, 2, SeenAction::Call), rec(Street::Flop, 1, SeenAction::Check), rec(Street::Flop, 2, SeenAction::Check), rec(Street::Turn, 1, SeenAction::Check), rec(Street::Turn, 2, SeenAction::Bet), ]; let mut m = SessionMemory::new(); for _ in 0..40 { m.observe_hand(&hand, 0, 2); } let p = m.read().expect("read"); assert_eq!(p.aggression, Some(0.5)); // 1 bet, 1 flop check pooled assert_eq!(p.turn_aggression, Some(1.0)); // bets every turn, never passive on the turn assert_eq!(p.river_aggression, None); // no river action seen } #[test] fn street_fold_is_shrunk_toward_the_pooled_read() { // Folds every flop bet, calls every turn bet: pooled fold 0.5; the flop (n=40 folds) moves // well above it, the turn well below it, the river (no data) stays None. let hand = vec![ rec(Street::Preflop, 1, SeenAction::PostSmallBlind), rec(Street::Preflop, 2, SeenAction::PostBigBlind), rec(Street::Preflop, 1, SeenAction::Raise), rec(Street::Preflop, 2, SeenAction::Call), rec(Street::Flop, 1, SeenAction::Bet), rec(Street::Flop, 2, SeenAction::Fold), ]; let call = vec![ rec(Street::Preflop, 1, SeenAction::Raise), rec(Street::Preflop, 2, SeenAction::Call), rec(Street::Turn, 1, SeenAction::Bet), rec(Street::Turn, 2, SeenAction::Call), ]; let mut m = SessionMemory::new(); for _ in 0..20 { m.observe_hand(&hand, 0, 2); m.observe_hand(&call, 0, 2); } let p = m.read().expect("read"); assert_eq!(p.fold_to_bet, Some(0.5)); let flop = p.street_fold_to_bet[0].expect("flop"); let turn = p.street_fold_to_bet[1].expect("turn"); assert!(flop > 0.7 && flop < 1.0, "{flop}"); assert!(turn < 0.3 && turn > 0.0, "{turn}"); assert_eq!(p.street_fold_to_bet[2], None); } #[test] fn a_tight_folding_opponent_reads_as_a_nit() { // Seat 2 folds preflop every hand: no voluntary money, and (vpip 0) classifies as a nit. let hand = vec![ rec(Street::Preflop, 1, SeenAction::PostSmallBlind), rec(Street::Preflop, 2, SeenAction::PostBigBlind), rec(Street::Preflop, 1, SeenAction::Raise), rec(Street::Preflop, 2, SeenAction::Fold), ]; let mut m = SessionMemory::new(); for _ in 0..40 { m.observe_hand(&hand, 0, 2); } let p = m.read().expect("read"); assert_eq!(p.vpip, Some(0.0)); assert_eq!(classify(&p), Style::Nit); } }