Files
pokerfreak/src/sim/welt_memory.rs
T

803 lines
30 KiB
Rust

//! World memory: the observation API for the dimensions the classic HUD counts (`sim::memory`) do not
//! see. It is a pure data layer - a clean, documented set of "observe" calls and read-only queries -
//! that a hierarchical Bayes model (or any other consumer) can read. The engine itself reads NONE of
//! this yet; `SessionMemory::read()` is untouched, so the existing ladder is bit-identical.
//!
//! The dimensions:
//!
//! - **Sizing x strength.** A bet or raise is recorded as a pot fraction (`SizeBucket`). The strength
//! of the hand behind it is only known when it is SHOWN, so pairs (bucket, strength band) fill from
//! showdown reveals only (`observe_world_hand`, or `observe_size_strength` by hand). Un-revealed
//! bets still land in the plain per-bucket histogram (`size_hist`). Strength is the hand's equity
//! against one random hand on the street of the bet (`sim::reader::strength`), i.e. what a human
//! could infer from the revealed cards and the board at that moment.
//! - **Texture x position cells.** For each street (flop/turn/river) x board `Texture` x `Pos`, the
//! counts of the opponent's bet / check (when checked to) and fold / call / raise (facing a bet).
//! - **Showdown reveals.** The shown hand and the final board, with its strength.
//! - **Timing.** A tank factor per action (1.0 = the opponent's usual pace; > 1 slower), bucketed as
//! `Tank`, paired with strength the same way sizing is.
//!
//! Everything is count-based and order-free (apart from the capped showdown list), so merging two
//! memories or feeding a hierarchical prior is a sum.
use super::reader::strength;
use crate::card::Card;
use crate::game::Street;
use crate::rng::Rng;
/// Equity bands of the strength axis: `[0,.2) [.2,.4) [.4,.6) [.6,.8) [.8,1]`.
pub const STRENGTH_BANDS: usize = 5;
/// Most recent showdowns kept verbatim (the counts have no cap).
pub const SHOWDOWN_CAP: usize = 512;
/// Strength (equity vs a random hand, 0..1) to its band index `0..STRENGTH_BANDS`.
pub fn strength_band(s: f64) -> usize {
((s.clamp(0.0, 1.0) * STRENGTH_BANDS as f64) as usize).min(STRENGTH_BANDS - 1)
}
/// Board texture. Classified on the cards shown so far (flop, turn or river board).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Texture {
/// Unpaired, rainbow-ish, disconnected: little to draw to.
Dry,
/// Unpaired and drawy: a flush draw or a connected (straight-draw) board.
Wet,
/// At least one pair on the board (and not flush-dominant).
Paired,
/// Flush-dominant: flop all one suit; turn >= 3, river >= 4 of one suit.
Monotone,
}
impl Texture {
pub const ALL: [Texture; 4] = [Texture::Dry, Texture::Wet, Texture::Paired, Texture::Monotone];
pub fn index(self) -> usize {
self as usize
}
pub fn name(self) -> &'static str {
["dry", "wet", "paired", "mono"][self as usize]
}
/// Classify a 3-5 card board (fewer cards, i.e. preflop, reads `Dry`).
pub fn of(board: &[Card]) -> Texture {
let n = board.len();
if n < 3 {
return Texture::Dry;
}
let mut suits = [0u8; 4];
let mut ranks = [0u8; 15];
for c in board {
suits[c.suit as usize] += 1;
ranks[c.rank.value() as usize] += 1;
}
ranks[1] = ranks[14]; // the ace plays low as well
let max_suit = *suits.iter().max().expect("four suits");
if max_suit >= [3u8, 3, 4][(n - 3).min(2)] {
return Texture::Monotone;
}
if ranks[2..=14].iter().any(|r| *r >= 2) {
return Texture::Paired;
}
// Connected: enough distinct ranks inside one five-rank window (straight possible / drawing).
let need = if n == 5 { 4 } else { 3 };
let connected = (1..=10usize).any(|lo| (lo..lo + 5).filter(|v| ranks[*v] > 0).count() >= need);
// Flush draw present: two of a suit on the flop, three on the turn/river.
let flushy = max_suit as usize >= if n == 3 { 2 } else { 3 };
if connected && flushy || (connected && n == 3 && tight(&ranks)) {
Texture::Wet
} else {
Texture::Dry
}
}
}
/// Three flop ranks within a four-rank span (a very connected flop even when rainbow).
fn tight(ranks: &[u8; 15]) -> bool {
(1..=11usize).any(|lo| (lo..lo + 4).filter(|v| ranks[*v] > 0).count() >= 3)
}
/// Position of the acting opponent: acts last among the live players after the flop, or not.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Pos {
Oop,
Ip,
}
impl Pos {
pub const ALL: [Pos; 2] = [Pos::Oop, Pos::Ip];
pub fn index(self) -> usize {
self as usize
}
}
/// A bet or raise size as a fraction of the pot it was made into (the raise counted on top of the
/// call: raise-by / (pot + to_call)).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SizeBucket {
/// Under 0.40 pot.
Small,
/// 0.40 to under 0.75.
Medium,
/// 0.75 to under 1.10.
Large,
/// 1.10 and up.
Overbet,
}
impl SizeBucket {
pub const COUNT: usize = 4;
pub const ALL: [SizeBucket; 4] = [SizeBucket::Small, SizeBucket::Medium, SizeBucket::Large, SizeBucket::Overbet];
pub fn of(frac: f64) -> SizeBucket {
if frac < 0.40 {
SizeBucket::Small
} else if frac < 0.75 {
SizeBucket::Medium
} else if frac < 1.10 {
SizeBucket::Large
} else {
SizeBucket::Overbet
}
}
pub fn index(self) -> usize {
self as usize
}
pub fn name(self) -> &'static str {
["small", "medium", "large", "overbet"][self as usize]
}
}
/// How long the opponent took, relative to its own usual pace.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Tank {
/// Factor under 0.8.
Fast,
Normal,
/// Factor 1.25 and up.
Slow,
}
impl Tank {
pub const COUNT: usize = 3;
pub fn of(factor: f64) -> Tank {
if factor < 0.8 {
Tank::Fast
} else if factor < 1.25 {
Tank::Normal
} else {
Tank::Slow
}
}
pub fn index(self) -> usize {
self as usize
}
}
/// What the opponent did (blinds and antes are not events).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Move {
/// Opened the betting (nothing to call).
Bet,
/// Raised a bet (all-in over a bet included).
Raise,
Call,
/// Checked (nothing to call).
Check,
Fold,
}
/// One postflop opponent action with its context. `size_frac` is set for `Bet`/`Raise`, `tank` when a
/// pace was observed. `seat` is the 1-based table seat.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct WorldEvent {
pub seat: u8,
pub street: Street,
pub texture: Texture,
pub pos: Pos,
pub mv: Move,
pub size_frac: Option<f64>,
pub tank: Option<f64>,
}
/// A hand shown at showdown, with the full board it was shown on.
#[derive(Clone, Debug, PartialEq)]
pub struct Reveal {
pub seat: u8,
pub hole: [Card; 2],
pub board: Vec<Card>,
}
/// Everything observable about one finished hand beyond the plain action history: the opponents'
/// postflop events and the hands that were shown (empty when the hand ended without showdown).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct WorldHand {
pub events: Vec<WorldEvent>,
pub reveals: Vec<Reveal>,
}
/// Counts of one (street, texture, position) cell.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Cell {
pub bet: u32,
pub check: u32,
pub fold: u32,
pub call: u32,
pub raise: u32,
}
impl Cell {
/// Times it was checked to (bet or check).
pub fn open_spots(&self) -> u32 {
self.bet + self.check
}
/// Times it faced a bet (fold, call or raise).
pub fn facing_spots(&self) -> u32 {
self.fold + self.call + self.raise
}
pub fn bet_rate(&self) -> Option<f64> {
(self.open_spots() > 0).then(|| self.bet as f64 / self.open_spots() as f64)
}
pub fn fold_rate(&self) -> Option<f64> {
(self.facing_spots() > 0).then(|| self.fold as f64 / self.facing_spots() as f64)
}
pub fn raise_rate(&self) -> Option<f64> {
(self.facing_spots() > 0).then(|| self.raise as f64 / self.facing_spots() as f64)
}
fn add(&mut self, mv: Move) {
match mv {
Move::Bet => self.bet += 1,
Move::Check => self.check += 1,
Move::Fold => self.fold += 1,
Move::Call => self.call += 1,
Move::Raise => self.raise += 1,
}
}
fn merge(&mut self, o: &Cell) {
self.bet += o.bet;
self.check += o.check;
self.fold += o.fold;
self.call += o.call;
self.raise += o.raise;
}
}
/// A hand shown at showdown, kept verbatim.
#[derive(Clone, Debug, PartialEq)]
pub struct Showdown {
pub hole: [Card; 2],
pub board: Vec<Card>,
/// Equity vs a random hand on the full board.
pub strength: f64,
/// The opponent's bets and raises in the hand (how hard it pushed before showing).
pub aggressive_actions: u32,
}
/// Running first and second moments of (x, y) pairs, for a correlation without storing the pairs.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
struct Moments {
n: f64,
sx: f64,
sy: f64,
sxx: f64,
syy: f64,
sxy: f64,
}
impl Moments {
fn add(&mut self, x: f64, y: f64) {
self.n += 1.0;
self.sx += x;
self.sy += y;
self.sxx += x * x;
self.syy += y * y;
self.sxy += x * y;
}
fn corr(&self) -> Option<f64> {
if self.n < 3.0 {
return None;
}
let cov = self.sxy - self.sx * self.sy / self.n;
let vx = self.sxx - self.sx * self.sx / self.n;
let vy = self.syy - self.sy * self.sy / self.n;
(vx > 1e-12 && vy > 1e-12).then(|| cov / (vx * vy).sqrt())
}
}
/// The world observations of one opponent (or one pooled archetype). See the module docs.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct WorldMemory {
/// `[street flop/turn/river][texture][pos]`.
cells: [[[Cell; 2]; 4]; 3],
size_hist: [u32; SizeBucket::COUNT],
size_strength: [[u32; STRENGTH_BANDS]; SizeBucket::COUNT],
tank_hist: [u32; Tank::COUNT],
tank_strength: [[u32; STRENGTH_BANDS]; Tank::COUNT],
size_moments: Moments,
tank_moments: Moments,
showdowns: Vec<Showdown>,
hands: u32,
revealed_hands: u32,
/// River bets/raises of revealed hands, and how many of them were air (`profile::AIR_STRENGTH`).
river_bets_shown: u32,
river_air_shown: u32,
/// Preflop classes (`range_spec::chen_class`) of the revealed hands, all lines (plan D3).
shown_class: [u32; CLASSES],
}
use crate::exploit::range_spec::{chen_class, CLASSES};
/// Shown-hand classes of the real NL0.01-0.02 pool per line (`lesen/uebergabe.Quelle.linien_population`,
/// 16.11., aggregate counts only): the line prior of the hierarchical shown-hand read. Order: the
/// river lines first ("river-aggr", "river-passiv"), then every other line, which only feed the pooled
/// class distribution.
pub const NL2_LINES: [[u32; CLASSES]; 9] = [
[5, 10, 34, 31, 13], // river-aggr
[14, 41, 69, 82, 52], // river-passiv
[13, 17, 13, 9, 4], // preflop-aggr
[7, 10, 3, 12, 8], // turn-aggr
[3, 10, 8, 8, 3], // flop-aggr
[0, 1, 2, 1, 6], // ohne
[0, 0, 1, 1, 0], // preflop-passiv
[0, 0, 1, 1, 0], // turn-passiv
[0, 1, 0, 0, 0], // flop-passiv
];
/// Pseudo-count of the pooled distribution in a line's prior (= `lesen/zeigt_eval.LAMBDA_KONTEXT`).
pub const SHOWN_LAMBDA: f64 = 5.0;
/// Prior strength of the player's own shown hands (= `lesen/uebergabe.D3_KAPPA`).
pub const SHOWN_KAPPA: f64 = 50.0;
/// The hierarchical shown-hand read on the two river lines (= `lesen/uebergabe._klassen_feld`): the
/// line distribution, shrunk toward the pooled one by `SHOWN_LAMBDA`, tilted by the player's own shown
/// classes `own` (all lines), which pull with weight n / (n + `SHOWN_KAPPA`). No shown hands = the line
/// prior itself. -> [river-aggr, river-passiv].
pub fn shown_river_read(lines: &[[u32; CLASSES]], own: &[u32; CLASSES]) -> [[f64; CLASSES]; 2] {
let mut all = [0.0; CLASSES];
for l in lines {
for c in 0..CLASSES {
all[c] += l[c] as f64;
}
}
let n_all: f64 = all.iter().sum();
let pop: Vec<f64> = (0..CLASSES).map(|c| (all[c] + 1.0) / (n_all + CLASSES as f64)).collect();
let n_own: f64 = own.iter().map(|x| *x as f64).sum();
let mut out = [[0.0; CLASSES]; 2];
for (i, o) in out.iter_mut().enumerate() {
let zl = lines.get(i).copied().unwrap_or([0; CLASSES]);
let n: f64 = zl.iter().map(|x| *x as f64).sum();
let mut q = [0.0; CLASSES];
for c in 0..CLASSES {
let base = (zl[c] as f64 + SHOWN_LAMBDA * pop[c]) / (n + SHOWN_LAMBDA);
q[c] = if n_own > 0.0 { base * ((own[c] as f64 + SHOWN_KAPPA * pop[c]) / (n_own + SHOWN_KAPPA)) / pop[c] } else { base };
}
let s: f64 = q.iter().sum();
*o = q.map(|x| x / s);
}
out
}
fn street_ix(street: Street) -> Option<usize> {
match street {
Street::Preflop => None,
Street::Flop => Some(0),
Street::Turn => Some(1),
Street::River => Some(2),
}
}
/// A fixed seed per (hole, board length): the strength estimate of a shown hand is reproducible.
fn reveal_seed(hole: &[Card; 2], len: usize) -> u64 {
0x5EED_5EED ^ ((hole[0].index() as u64) << 8) ^ ((hole[1].index() as u64) << 16) ^ ((len as u64) << 24)
}
impl WorldMemory {
pub fn new() -> Self {
Self::default()
}
// ---- observation API ----
/// One postflop action: bumps its (street, texture, position) cell, the size histogram when it is
/// a sized bet/raise, and the pace histogram when a pace was observed. Preflop events are ignored.
pub fn observe_action(&mut self, ev: &WorldEvent) {
let Some(s) = street_ix(ev.street) else { return };
self.cells[s][ev.texture.index()][ev.pos.index()].add(ev.mv);
if let (Move::Bet | Move::Raise, Some(f)) = (ev.mv, ev.size_frac) {
self.size_hist[SizeBucket::of(f).index()] += 1;
}
if let Some(t) = ev.tank {
self.tank_hist[Tank::of(t).index()] += 1;
}
}
/// A bet/raise of `size_frac` (pot fraction) made with a hand now known to be of `strength`
/// (equity vs a random hand, 0..1). Call this when a hand is revealed.
pub fn observe_size_strength(&mut self, size_frac: f64, strength: f64) {
self.size_strength[SizeBucket::of(size_frac).index()][strength_band(strength)] += 1;
self.size_moments.add(size_frac, strength);
}
/// An action taken at pace `tank` (1.0 = usual) with a hand now known to be of `strength`.
pub fn observe_tank_strength(&mut self, tank: f64, strength: f64) {
self.tank_strength[Tank::of(tank).index()][strength_band(strength)] += 1;
self.tank_moments.add(tank.max(1e-6).ln(), strength);
}
/// A showdown reveal on its own (hand and full board), kept in the capped list.
pub fn observe_showdown(&mut self, hole: [Card; 2], board: &[Card], aggressive_actions: u32) {
let s = strength(&hole, board, Rng::seeded(reveal_seed(&hole, board.len())));
if self.showdowns.len() == SHOWDOWN_CAP {
self.showdowns.remove(0);
}
self.showdowns.push(Showdown { hole, board: board.to_vec(), strength: s, aggressive_actions });
self.revealed_hands += 1;
}
/// A whole finished hand: every event (cells, histograms), and for each revealed seat the
/// strength of its hand on the street of each of its sized bets and paced actions, so the
/// (size, strength) and (tank, strength) pairs fill, plus the showdown record itself.
pub fn observe_world_hand(&mut self, hand: &WorldHand) {
self.hands += 1;
for ev in &hand.events {
self.observe_action(ev);
}
for rv in &hand.reveals {
let mut by_street: [Option<f64>; 3] = [None; 3];
let mut aggressive = 0;
for ev in hand.events.iter().filter(|e| e.seat == rv.seat) {
let Some(s) = street_ix(ev.street) else { continue };
let len = ev.street.board_len().min(rv.board.len());
let st = *by_street[s]
.get_or_insert_with(|| strength(&rv.hole, &rv.board[..len], Rng::seeded(reveal_seed(&rv.hole, len))));
if let (Move::Bet | Move::Raise, Some(f)) = (ev.mv, ev.size_frac) {
self.observe_size_strength(f, st);
aggressive += 1;
if ev.street == Street::River {
self.river_bets_shown += 1;
self.river_air_shown += (st < crate::exploit::profile::AIR_STRENGTH) as u32;
}
}
if let Some(t) = ev.tank {
self.observe_tank_strength(t, st);
}
}
self.observe_showdown(rv.hole, &rv.board, aggressive);
self.shown_class[chen_class(&rv.hole)] += 1;
}
}
/// Add every count of `other` into `self` (pooling seats or sessions).
pub fn merge(&mut self, other: &WorldMemory) {
for s in 0..3 {
for t in 0..4 {
for p in 0..2 {
self.cells[s][t][p].merge(&other.cells[s][t][p]);
}
}
}
for b in 0..SizeBucket::COUNT {
self.size_hist[b] += other.size_hist[b];
for k in 0..STRENGTH_BANDS {
self.size_strength[b][k] += other.size_strength[b][k];
}
}
for b in 0..Tank::COUNT {
self.tank_hist[b] += other.tank_hist[b];
for k in 0..STRENGTH_BANDS {
self.tank_strength[b][k] += other.tank_strength[b][k];
}
}
let add = |a: &mut Moments, o: &Moments| {
a.n += o.n;
a.sx += o.sx;
a.sy += o.sy;
a.sxx += o.sxx;
a.syy += o.syy;
a.sxy += o.sxy;
};
add(&mut self.size_moments, &other.size_moments);
add(&mut self.tank_moments, &other.tank_moments);
self.showdowns.extend(other.showdowns.iter().cloned());
let over = self.showdowns.len().saturating_sub(SHOWDOWN_CAP);
self.showdowns.drain(..over);
self.hands += other.hands;
self.revealed_hands += other.revealed_hands;
self.river_bets_shown += other.river_bets_shown;
self.river_air_shown += other.river_air_shown;
for c in 0..CLASSES {
self.shown_class[c] += other.shown_class[c];
}
}
/// Preflop classes of all revealed hands (plan D3).
pub fn shown_classes(&self) -> [u32; CLASSES] {
self.shown_class
}
// ---- queries ----
/// Hands folded in through `observe_world_hand`.
pub fn hands(&self) -> u32 {
self.hands
}
/// Showdown reveals seen (counts past the cap).
pub fn revealed_hands(&self) -> u32 {
self.revealed_hands
}
/// The (texture, position) cell of one postflop street (`None` for preflop).
pub fn cell(&self, street: Street, texture: Texture, pos: Pos) -> Option<Cell> {
street_ix(street).map(|s| self.cells[s][texture.index()][pos.index()])
}
/// The (texture, position) cell summed over flop, turn and river.
pub fn cell_all_streets(&self, texture: Texture, pos: Pos) -> Cell {
let mut c = Cell::default();
for s in 0..3 {
c.merge(&self.cells[s][texture.index()][pos.index()]);
}
c
}
/// All bets/raises by size bucket, revealed or not.
pub fn size_hist(&self) -> [u32; SizeBucket::COUNT] {
self.size_hist
}
/// Revealed pairs: `[size bucket][strength band]` counts.
pub fn size_strength(&self) -> [[u32; STRENGTH_BANDS]; SizeBucket::COUNT] {
self.size_strength
}
/// Mean revealed strength behind each size bucket (`None` where no pair was seen).
pub fn mean_strength_by_size(&self) -> [Option<f64>; SizeBucket::COUNT] {
let mut out = [None; SizeBucket::COUNT];
for b in 0..SizeBucket::COUNT {
let n: u32 = self.size_strength[b].iter().sum();
if n > 0 {
let mid = |k: usize| (k as f64 + 0.5) / STRENGTH_BANDS as f64;
let sum: f64 = (0..STRENGTH_BANDS).map(|k| self.size_strength[b][k] as f64 * mid(k)).sum();
out[b] = Some(sum / n as f64);
}
}
out
}
/// Number of revealed (size, strength) pairs.
pub fn size_pairs(&self) -> u32 {
self.size_moments.n as u32
}
/// Pearson correlation of bet size (pot fraction) with the strength of the hand behind it, over
/// revealed pairs. Positive: sizes up with strength; negative: reverse tell; near 0: no tell.
pub fn size_strength_corr(&self) -> Option<f64> {
self.size_moments.corr()
}
/// Pace histogram `[fast, normal, slow]`.
pub fn tank_hist(&self) -> [u32; Tank::COUNT] {
self.tank_hist
}
/// Revealed pairs `[tank bucket][strength band]`.
pub fn tank_strength(&self) -> [[u32; STRENGTH_BANDS]; Tank::COUNT] {
self.tank_strength
}
/// Pearson correlation of ln(tank factor) with strength over revealed pairs.
pub fn tank_strength_corr(&self) -> Option<f64> {
self.tank_moments.corr()
}
/// River showdown read for a table without world events (`sim::table`, `RIVER_SD=1` on the HU
/// ladder): a revealed hand that bet or raised `river_bets` times on the river, counted as
/// `observe_world_hand` counts it (strength at the full board, air below `AIR_STRENGTH`). Touches
/// nothing but the river showdown counts.
pub fn observe_river_reveal(&mut self, hole: &[Card; 2], board: &[Card], river_bets: u32) {
if river_bets == 0 || board.len() < 5 {
return;
}
let st = strength(hole, &board[..5], Rng::seeded(reveal_seed(hole, 5)));
self.river_bets_shown += river_bets;
self.river_air_shown += river_bets * (st < crate::exploit::profile::AIR_STRENGTH) as u32;
}
/// The most recent showdowns (up to `SHOWDOWN_CAP`), oldest first.
/// River showdown read: `(air share, shown river bets)` over the river bets/raises of revealed
/// hands, `None` before the first one.
pub fn river_bluff(&self) -> Option<(f64, u32)> {
(self.river_bets_shown > 0)
.then(|| (self.river_air_shown as f64 / self.river_bets_shown as f64, self.river_bets_shown))
}
pub fn showdowns(&self) -> &[Showdown] {
&self.showdowns
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn shown_river_read_is_the_handover_formula() {
// lesen/uebergabe._klassen_feld on the same counts, ten shown premium hands
let mut own = [0; CLASSES];
own[0] = 10;
let q = shown_river_read(&NL2_LINES, &own)[0];
for (a, b) in q.iter().zip([0.1631, 0.0987, 0.3194, 0.2935, 0.1254]) {
assert!((a - b).abs() < 1e-4, "{q:?}");
}
// nothing shown: the line prior, a distribution
let p = shown_river_read(&NL2_LINES, &[0; CLASSES]);
assert!((p[1].iter().sum::<f64>() - 1.0).abs() < 1e-12 && p[0][2] > p[0][0]);
}
fn cards(s: &str) -> Vec<Card> {
Card::parse_list(s).expect("cards")
}
#[test]
fn textures_classify() {
assert_eq!(Texture::of(&cards("Ks 7d 2c")), Texture::Dry);
assert_eq!(Texture::of(&cards("Ks Kd 2c")), Texture::Paired);
assert_eq!(Texture::of(&cards("Ks 9s 2s")), Texture::Monotone);
assert_eq!(Texture::of(&cards("9s 8s 6d")), Texture::Wet);
assert_eq!(Texture::of(&cards("9h 8c 7d")), Texture::Wet);
assert_eq!(Texture::of(&cards("Ks 7d 2c 3h")), Texture::Dry);
assert_eq!(Texture::of(&cards("Ks 7s 2s 3h")), Texture::Monotone);
assert_eq!(Texture::of(&cards("Ks 7s 2s 3h Jd")), Texture::Dry);
}
#[test]
fn texture_shares_are_usable() {
// Every cell must be populated often enough to be learnable on random flops.
let mut rng = Rng::seeded(99);
let mut count = [0u32; 4];
let n = 6000;
for _ in 0..n {
let (d, next) = crate::card::deck::draw(&crate::card::deck::full(), 3, rng).expect("deal");
rng = next;
count[Texture::of(&d).index()] += 1;
}
for t in Texture::ALL {
let share = count[t.index()] as f64 / n as f64;
println!("{}: {share:.3}", t.name());
assert!(share > 0.03, "{} share {share:.3}", t.name());
}
}
#[test]
fn buckets_and_bands() {
assert_eq!(SizeBucket::of(0.33), SizeBucket::Small);
assert_eq!(SizeBucket::of(0.5), SizeBucket::Medium);
assert_eq!(SizeBucket::of(1.0), SizeBucket::Large);
assert_eq!(SizeBucket::of(1.5), SizeBucket::Overbet);
assert_eq!(Tank::of(0.5), Tank::Fast);
assert_eq!(Tank::of(1.0), Tank::Normal);
assert_eq!(Tank::of(2.0), Tank::Slow);
assert_eq!(strength_band(0.0), 0);
assert_eq!(strength_band(0.55), 2);
assert_eq!(strength_band(1.0), STRENGTH_BANDS - 1);
}
#[test]
fn cells_count_by_street_texture_position() {
let mut m = WorldMemory::new();
let ev = |street, texture, pos, mv, f: Option<f64>| WorldEvent { seat: 2, street, texture, pos, mv, size_frac: f, tank: None };
m.observe_action(&ev(Street::Flop, Texture::Dry, Pos::Ip, Move::Bet, Some(0.5)));
m.observe_action(&ev(Street::Flop, Texture::Dry, Pos::Ip, Move::Check, None));
m.observe_action(&ev(Street::Flop, Texture::Dry, Pos::Ip, Move::Check, None));
m.observe_action(&ev(Street::Turn, Texture::Wet, Pos::Oop, Move::Fold, None));
m.observe_action(&ev(Street::Preflop, Texture::Dry, Pos::Ip, Move::Bet, Some(0.5)));
let c = m.cell(Street::Flop, Texture::Dry, Pos::Ip).expect("flop cell");
assert_eq!((c.bet, c.check), (1, 2));
assert!((c.bet_rate().expect("rate") - 1.0 / 3.0).abs() < 1e-12);
assert_eq!(m.cell(Street::Turn, Texture::Wet, Pos::Oop).expect("cell").fold, 1);
assert_eq!(m.cell(Street::Preflop, Texture::Dry, Pos::Ip), None);
assert_eq!(m.cell_all_streets(Texture::Dry, Pos::Ip).bet, 1);
assert_eq!(m.size_hist()[SizeBucket::Medium.index()], 1);
}
#[test]
fn size_strength_pairs_and_correlation() {
let mut m = WorldMemory::new();
// A clean "sizes up with strength" pattern.
for i in 0..40 {
let s = 0.3 + 0.6 * (i as f64 / 39.0);
m.observe_size_strength(0.25 + 0.9 * (s - 0.3) / 0.6, s);
}
assert!(m.size_strength_corr().expect("corr") > 0.99);
let mean = m.mean_strength_by_size();
assert!(mean[0].expect("small") < mean[3].expect("overbet"));
// No pairs: no correlation.
assert_eq!(WorldMemory::new().size_strength_corr(), None);
}
#[test]
fn a_shown_hand_pairs_its_bets_with_its_strength() {
// Seat 2 bets big on the flop and shows the nuts-ish AA on a dry board: one big pair, strong.
let board = cards("Ks 7d 2c 9h 3s");
let hole = [Card::parse_short("Ah").expect("c"), Card::parse_short("Ad").expect("c")];
let hand = WorldHand {
events: vec![WorldEvent {
seat: 2,
street: Street::Flop,
texture: Texture::Dry,
pos: Pos::Ip,
mv: Move::Bet,
size_frac: Some(0.9),
tank: Some(1.6),
}],
reveals: vec![Reveal { seat: 2, hole, board: board.clone() }],
};
let mut m = WorldMemory::new();
m.observe_world_hand(&hand);
assert_eq!(m.hands(), 1);
assert_eq!(m.revealed_hands(), 1);
assert_eq!(m.size_pairs(), 1);
assert_eq!(m.size_strength()[SizeBucket::Large.index()][STRENGTH_BANDS - 1], 1);
assert_eq!(m.tank_strength()[Tank::Slow.index()][STRENGTH_BANDS - 1], 1);
assert_eq!(m.showdowns().len(), 1);
assert_eq!(m.showdowns()[0].aggressive_actions, 1);
// Without a reveal the bet is counted but never paired.
let mut m2 = WorldMemory::new();
m2.observe_world_hand(&WorldHand { events: hand.events.clone(), reveals: vec![] });
assert_eq!(m2.size_hist()[SizeBucket::Large.index()], 1);
assert_eq!(m2.size_pairs(), 0);
}
#[test]
fn shown_river_bets_split_into_air_and_value() {
let board = cards("Ks 7d 2c 9h 3s");
let river_bet = |seat| WorldEvent {
seat,
street: Street::River,
texture: Texture::Dry,
pos: Pos::Ip,
mv: Move::Bet,
size_frac: Some(0.75),
tank: None,
};
let hand = |hole: &str| WorldHand {
events: vec![river_bet(2)],
reveals: vec![Reveal { seat: 2, hole: [Card::parse_short(&hole[..2]).unwrap(), Card::parse_short(&hole[2..]).unwrap()], board: board.clone() }],
};
let mut m = WorldMemory::new();
assert_eq!(m.river_bluff(), None);
m.observe_world_hand(&hand("AhAd")); // overpair: value
m.observe_world_hand(&hand("5h4h")); // missed draw, 5-high: air
m.observe_world_hand(&WorldHand { events: vec![river_bet(2)], reveals: vec![] }); // not shown: no evidence
assert_eq!(m.river_bluff(), Some((0.5, 2)));
let mut sum = WorldMemory::new();
sum.merge(&m);
sum.merge(&m);
assert_eq!(sum.river_bluff(), Some((0.5, 4)));
}
#[test]
fn merge_sums_the_counts() {
let mut a = WorldMemory::new();
let mut b = WorldMemory::new();
a.observe_size_strength(0.5, 0.5);
b.observe_size_strength(0.5, 0.9);
b.observe_size_strength(1.0, 0.9);
a.merge(&b);
assert_eq!(a.size_pairs(), 3);
}
}