Files
pokerfreak/src/sim/sechsmax.rs
T

545 lines
22 KiB
Rust

//! The 6-max ladder (plan O3): six seats, the engine on a rotating position against a MIXED
//! population of the existing opponent types, win rate in bb/100 with a 95 % interval in total,
//! per position, per street and per deciding engine part.
//!
//! **Pairing.** Every deal is played six times (duplicate): the engine takes each seat's cards
//! once, the same five opponents sit around it in the same order relative to the engine, so the
//! six hands of a deal share cards and opponents and position luck cancels within the deal. On top
//! the board luck is removed per hand (`sim::luck`, the same control variate as the HU ladder). Two
//! arms (two processes with different switches, same seed) play the same deals, lineups and
//! opponent choices, so `compare` judges them deal by deal.
//!
//! **Population.** A lineup of five is drawn per block of `block` deals; inside the block the five
//! stay, so a `Memory` read (one `SessionMemory` per opponent, observed seat by seat) learns them
//! like a real session does, and is reset with the next lineup. `misch` weighs all types equally;
//! `micro` is the live 0.01/0.02 pool as far as it is known (loose-passive majority, some
//! stations/fish, a few aggressive types and open-jammers; the shares are an assumption, see
//! `Population::named`). `nur:<type>` seats one type five times (diagnosis).
//!
//! **Attribution.** A hand's luck-corrected result goes to hero's position, to the street of
//! hero's LAST decision in the hand and to the engine part that took that decision (from the reason
//! text, the classes of `lesen/roentgen.py` plus `open_jam`). The street and decider columns are
//! shares of the total (they add up to it); a position column is the win rate in that position.
//!
//! What it does not measure: a real player's adaptation to hero (the opponents are fixed rules),
//! rake (free table unless `cost` says otherwise), and opponents outside the listed types.
use super::memory::SessionMemory;
use super::opponent::Opponent;
use super::paired::{compare, Comparison};
use super::reader::{Rules, Style};
use super::reads::opponent_profile;
use super::session::ReadMode;
use super::table::{deal, play_hand_mixed, HandRead, HandSetup, TableCost};
use super::welt::Persona;
use crate::exploit::profile::Profile;
use crate::game::Street;
use crate::rng::Rng;
pub const SEATS: usize = 6;
/// Seat index 0 is the button (`sim::table`).
pub const POSITIONS: [&str; SEATS] = ["BTN", "SB", "BB", "UTG", "HJ", "CO"];
pub const STREETS: [&str; 4] = ["preflop", "flop", "turn", "river"];
/// Engine parts that can take hero's last decision. `walk` = hero never acted (folded to in the BB).
pub const DECIDERS: [&str; 13] = [
"walk", "cfr", "regeln", "open_jam", "mdf", "heuristik", "turn_veto", "river_veto", "e3", "solver", "solver3", "enthaltung",
"ungueltig",
];
/// Columns of one row: total, raw total, positions, streets, deciders.
pub const COLUMNS: usize = 2 + SEATS + 4 + DECIDERS.len();
/// The nemesis rule bots of the HU ladder (`ab_zelle`).
pub const N1: Rules = Rules { call_margin: 0.215, raise_at: 0.587, bet_at: 0.548, open_at: 0.729, bluff: 0.068, size: 0.441 };
pub const N2: Rules = Rules { call_margin: 0.173, raise_at: 0.579, bet_at: 0.748, open_at: 0.800, bluff: 0.229, size: 0.996 };
pub const N3: Rules = Rules { call_margin: 0.396, raise_at: 0.769, bet_at: 0.615, open_at: 0.468, bluff: 0.261, size: 1.148 };
/// The micro open-jammer (live 14.11., hand 177615800656: a 90 bb open-jam from the cutoff). Opens
/// only all-in (the size clamps to the stack), from strength 0.63 against a random hand (about the
/// top 9 %: 77+, A9s+, AJo+, KQs); re-jams strong hands, otherwise a tight caller. Postflop it shoves
/// its bets. Its range is an assumption: the live pool's jam range is not measured.
pub const JAMMER: Rules = Rules { call_margin: 0.20, raise_at: 0.78, bet_at: 0.70, open_at: 0.63, bluff: 0.05, size: 60.0 };
/// Every opponent type a population can hold.
pub const TYPES: [&str; 12] =
["gto", "reg", "station", "fish", "nit", "maniac", "nemesis-1", "nemesis-2", "nemesis-3", "welt", "micro-passiv", "jammer"];
/// One opponent of type `name`; the drawn types (`welt`, `micro-passiv`) draw an individual from `rng`.
pub fn opponent_of(name: &str, rng: Rng) -> (Opponent, Rng) {
let o = match name {
"gto" => Opponent::Reader(Style::Gto),
"reg" => Opponent::Reader(Style::Reg),
"station" => Opponent::CallingStation,
"fish" => Opponent::Reader(Style::Fish),
"nit" => Opponent::Reader(Style::Nit),
"maniac" => Opponent::Reader(Style::Maniac),
"nemesis-1" => Opponent::Styled(N1),
"nemesis-2" => Opponent::Styled(N2),
"nemesis-3" => Opponent::Styled(N3),
"jammer" => Opponent::Styled(JAMMER),
"welt" => {
let (p, rng) = Persona::sample(rng);
return (Opponent::Welt(p), rng);
}
"micro-passiv" => {
let (p, rng) = Persona::draw_micro(rng);
return (Opponent::Welt(p), rng);
}
_ => panic!("unbekannter Gegnertyp {name}"),
};
(o, rng)
}
/// Shares of the opponent types at the table.
#[derive(Clone, Debug, PartialEq)]
pub struct Population {
pub name: String,
pub members: Vec<(&'static str, f64)>,
}
impl Population {
/// `misch`, `micro`, or `nur:<type>`.
pub fn named(name: &str) -> Population {
let members: Vec<(&'static str, f64)> = match name {
"misch" => TYPES.iter().map(|t| (*t, 1.0)).collect(),
// The live micro pool (14.11., 996 hands 0.01/0.02): mostly loose-passive and value-heavy
// (`micro_passiv`), stations and fish, a few regs and nits, rare maniacs and open-jammers.
// The shares are an assumption from the run's HUD, not a measured census.
"micro" => vec![
("micro-passiv", 0.40),
("fish", 0.15),
("station", 0.08),
("reg", 0.12),
("nit", 0.08),
("maniac", 0.05),
("jammer", 0.06),
("welt", 0.06),
],
_ => match name.strip_prefix("nur:") {
Some(t) => {
let t = TYPES.iter().find(|x| **x == t).unwrap_or_else(|| panic!("unbekannter Gegnertyp {t}"));
vec![(*t, 1.0)]
}
None => panic!("unbekannte Population {name} (misch, micro, nur:<typ>)"),
},
};
Population { name: name.to_string(), members }
}
/// Five opponents for lineup `b` (deterministic in `seed` and `b`), with their type names.
pub fn lineup(&self, seed: u64, b: u32) -> Vec<(&'static str, Opponent)> {
let total: f64 = self.members.iter().map(|m| m.1).sum();
let mut rng = Rng::seeded(seed ^ 0x6A5E_A700_0000 ^ (b as u64 + 1).wrapping_mul(0x9E37_79B9_7F4A_7C15));
(0..SEATS - 1)
.map(|_| {
let (u, r) = rng.unit();
let mut acc = 0.0;
let mut pick = self.members[self.members.len() - 1].0;
for (name, w) in &self.members {
acc += w / total;
if u <= acc {
pick = name;
break;
}
}
let (o, r) = opponent_of(pick, r);
rng = r;
(pick, o)
})
.collect()
}
}
/// The stacks at the table. Hero always starts with `stack_bb`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Stacks {
/// Everybody `stack_bb` (the HU ladder's table).
Gleich,
/// Each lineup member draws its stack once per lineup, uniform in 40 %..150 % of `stack_bb`
/// (whole big blinds): hero covers some players and is covered by others, as at a real table.
/// Needed for every spot where hero covers an all-in (live 14.11.: a 90 bb open-jam into 99 bb).
Gemischt,
}
impl Stacks {
pub fn named(name: &str) -> Stacks {
match name {
"gleich" => Stacks::Gleich,
"gemischt" => Stacks::Gemischt,
_ => panic!("stacks {name}: gleich|gemischt"),
}
}
}
/// The five lineup members' stacks of lineup `b` (big blinds).
pub fn lineup_stacks(stacks: Stacks, stack_bb: f64, seed: u64, b: u32) -> Vec<f64> {
match stacks {
Stacks::Gleich => vec![stack_bb; SEATS - 1],
Stacks::Gemischt => {
let mut rng = Rng::seeded(seed ^ 0x57AC_0000_0000 ^ (b as u64 + 1).wrapping_mul(0xC2B2_AE3D_27D4_EB4F));
(0..SEATS - 1)
.map(|_| {
let (u, r) = rng.unit();
rng = r;
(stack_bb * (0.4 + 1.1 * u)).round().max(1.0)
})
.collect()
}
}
}
/// Per-seat starting stacks with hero on seat index `h`.
fn seat_stacks(member: &[f64], hero_stack: f64, h: usize) -> Vec<f64> {
let mut s = vec![hero_stack; SEATS];
for (m, x) in member.iter().enumerate() {
s[seat_of(h, m)] = *x;
}
s
}
#[derive(Clone, Debug, PartialEq)]
pub struct Setup6 {
pub population: Population,
/// Deals; each is played from all six seats.
pub deals: u32,
/// Deals per lineup (the memory's session length is `6 * block` hands).
pub block: u32,
pub stack_bb: f64,
pub seed: u64,
pub read: ReadMode,
pub cost: TableCost,
pub stacks: Stacks,
}
impl Setup6 {
pub fn blocks(&self) -> u32 {
self.deals.div_ceil(self.block.max(1))
}
}
/// One deal's six hands. All values in big blinds, luck-corrected except `raw`.
#[derive(Clone, Debug, PartialEq)]
pub struct Row {
/// Mean over the six seats.
pub total: f64,
pub raw: f64,
/// Hero's result in that position (one hand each).
pub pos: [f64; SEATS],
/// Share of `total` by the street of hero's last decision.
pub street: [f64; 4],
/// Share of `total` by the engine part of hero's last decision.
pub decider: [f64; DECIDERS.len()],
pub decisions: u32,
pub invalid: u32,
pub abstains: u32,
pub chips_lost: f64,
}
impl Row {
pub fn columns(&self) -> Vec<f64> {
let mut v = vec![self.total, self.raw];
v.extend_from_slice(&self.pos);
v.extend_from_slice(&self.street);
v.extend_from_slice(&self.decider);
v
}
pub fn column_names() -> Vec<String> {
let mut v = vec!["gesamt".to_string(), "roh".to_string()];
v.extend(POSITIONS.iter().map(|p| format!("pos:{p}")));
v.extend(STREETS.iter().map(|s| format!("street:{s}")));
v.extend(DECIDERS.iter().map(|d| format!("teil:{d}")));
v
}
/// One line of the sample file: the columns, then decisions, invalid, abstains.
pub fn line(&self) -> String {
let mut f: Vec<String> = self.columns().iter().map(|x| format!("{x}")).collect();
f.extend([self.decisions.to_string(), self.invalid.to_string(), self.abstains.to_string()]);
f.join(" ")
}
pub fn parse(line: &str) -> Option<Row> {
let f: Vec<f64> = line.split_whitespace().map(|x| x.parse().ok()).collect::<Option<_>>()?;
if f.len() != COLUMNS + 3 {
return None;
}
let mut r = Row::zero();
r.total = f[0];
r.raw = f[1];
r.pos.copy_from_slice(&f[2..2 + SEATS]);
r.street.copy_from_slice(&f[2 + SEATS..6 + SEATS]);
r.decider.copy_from_slice(&f[6 + SEATS..COLUMNS]);
(r.decisions, r.invalid, r.abstains) = (f[COLUMNS] as u32, f[COLUMNS + 1] as u32, f[COLUMNS + 2] as u32);
Some(r)
}
fn zero() -> Row {
Row {
total: 0.0,
raw: 0.0,
pos: [0.0; SEATS],
street: [0.0; 4],
decider: [0.0; DECIDERS.len()],
decisions: 0,
invalid: 0,
abstains: 0,
chips_lost: 0.0,
}
}
}
/// The engine part behind a decision, from its street and reason text (the classes of
/// `lesen/roentgen.py::klasse`, plus `open_jam` and `ungueltig`).
pub fn decider(last: Option<&(Street, String)>) -> usize {
let idx = |name: &str| DECIDERS.iter().position(|d| *d == name).expect("decider");
let Some((street, g)) = last else { return idx("walk") };
idx(if g == "invalid" {
"ungueltig"
} else if g.contains("setzt aus") || g.contains("ABSTAIN") {
"enthaltung"
} else if g.contains("turn veto") {
"turn_veto"
} else if g.contains("defensive veto") {
"river_veto"
} else if ["river3 solver", "solver turn3", "solver flop3"].iter().any(|t| g.strip_prefix("solver-kern ").unwrap_or(g).starts_with(t)) {
"solver3"
} else if g.starts_with("river solver") || g.starts_with("solver turn") || g.starts_with("solver flop") {
"solver"
} else if g.contains("turn game") {
"e3"
} else if g.contains("MDF-Boden") {
"mdf"
} else if g.contains("vs open-jam") {
"open_jam"
} else if *street == Street::Preflop {
if g.contains("CFR") { "cfr" } else { "regeln" }
} else {
"heuristik"
})
}
fn street_index(last: Option<&(Street, String)>) -> usize {
match last.map(|l| l.0) {
None | Some(Street::Preflop) => 0,
Some(Street::Flop) => 1,
Some(Street::Turn) => 2,
Some(Street::River) => 3,
}
}
fn mix(seed: u64, n: u64) -> u64 {
Rng::seeded(seed ^ n.wrapping_mul(0xD1B5_4A32_D192_ED03)).next_u64().0
}
/// The seat (index) of lineup member `m` when hero sits at seat index `h`: member 0 directly left of hero.
pub fn seat_of(h: usize, m: usize) -> usize {
(h + 1 + m) % SEATS
}
/// Plays block `b` (its lineup, its deals) and returns one row per deal. Blocks are independent
/// and deterministic, so a run can split them over threads in any order.
pub fn play_block(setup: &Setup6, b: u32) -> Vec<Row> {
let lineup = setup.population.lineup(setup.seed, b);
let member_stacks = lineup_stacks(setup.stacks, setup.stack_bb, setup.seed, b);
let mut memory: Vec<SessionMemory> = (0..SEATS - 1).map(|_| SessionMemory::new()).collect();
let first = b * setup.block;
let last = (first + setup.block).min(setup.deals);
let mut rows = Vec::with_capacity((last - first) as usize);
for d in first..last {
let (cards, _) = deal(SEATS, Rng::seeded(mix(setup.seed, d as u64)));
let mut row = Row::zero();
for h in 0..SEATS {
let mut opponents = vec![Opponent::Folder; SEATS];
let mut reads: Vec<Option<Profile>> = vec![None; SEATS];
for (m, (_, o)) in lineup.iter().enumerate() {
let s = seat_of(h, m);
opponents[s] = *o;
reads[s] = match setup.read {
ReadMode::Oracle => opponent_profile(*o),
ReadMode::Blind => None,
ReadMode::Memory | ReadMode::Hud => memory[m].read(),
};
}
let hand = HandSetup {
deal: &cards,
hero_seat: h as u8 + 1,
// Unused at the mixed table (`play_hand_mixed`): every seat has its own opponent and read.
opponent: Opponent::Folder,
stack_bb: setup.stack_bb,
seed: mix(setup.seed ^ 0xA5A5, (d as u64) << 8 | h as u64),
read: HandRead::Given(None),
};
let start = seat_stacks(&member_stacks, setup.stack_bb, h);
let (r, history, last) = play_hand_mixed(&hand, setup.cost, &opponents, &reads, Some(&start));
if setup.read == ReadMode::Memory {
for (m, mem) in memory.iter_mut().enumerate() {
mem.observe_seat(&history, seat_of(h, m) as u8 + 1);
}
}
let x = r.hero_net - r.luck;
row.pos[h] = x;
row.total += x / SEATS as f64;
row.raw += r.hero_net / SEATS as f64;
row.street[street_index(last.as_ref())] += x / SEATS as f64;
row.decider[decider(last.as_ref())] += x / SEATS as f64;
row.decisions += r.hero_decisions;
row.invalid += r.invalid;
row.abstains += r.abstains;
row.chips_lost += r.chips_lost.abs();
}
rows.push(row);
}
rows
}
/// All blocks in order, single-threaded (tests; the binary spreads blocks over threads).
pub fn run(setup: &Setup6) -> Vec<Row> {
(0..setup.blocks()).flat_map(|b| play_block(setup, b)).collect()
}
/// 95 % two-sided normal quantile.
const Z95: f64 = 1.959_964;
/// Mean and 95 % half width of a column, in bb/100.
pub fn rate(x: &[f64]) -> (f64, f64) {
let n = x.len().max(1) as f64;
let mean = x.iter().sum::<f64>() / n;
let var = x.iter().map(|s| (s - mean).powi(2)).sum::<f64>() / (n - 1.0).max(1.0);
(100.0 * mean, 100.0 * Z95 * (var / n).sqrt())
}
/// Every column as (name, bb/100, ±95 %).
pub fn report(rows: &[Row]) -> Vec<(String, f64, f64)> {
let cols: Vec<Vec<f64>> = rows.iter().map(Row::columns).collect();
Row::column_names()
.into_iter()
.enumerate()
.map(|(k, name)| {
let x: Vec<f64> = cols.iter().map(|c| c[k]).collect();
let (m, ci) = rate(&x);
(name, m, ci)
})
.collect()
}
/// Paired comparison, column by column (new minus base). The rows must be the same deals in order.
pub fn compare_rows(base: &[Row], new: &[Row]) -> Result<Vec<(String, Comparison)>, String> {
let (a, b): (Vec<Vec<f64>>, Vec<Vec<f64>>) = (base.iter().map(Row::columns).collect(), new.iter().map(Row::columns).collect());
Row::column_names()
.into_iter()
.enumerate()
.map(|(k, name)| {
let x: Vec<f64> = a.iter().map(|c| c[k]).collect();
let y: Vec<f64> = b.iter().map(|c| c[k]).collect();
compare(&x, &y).map(|c| (name, c))
})
.collect()
}
// ---------------------------------------------------------------- multiway LBR (`table::lbr6`)
pub use super::table::lbr6::{Config as LbrConfig, LbrHand};
#[derive(Clone, Debug, PartialEq)]
pub struct LbrSetup {
pub population: Population,
/// Hands (one per deal: the engine's seat rotates with the deal, the best-responder's offset
/// with every sixth deal, so 30 deals cover every pair of seats once).
pub deals: u32,
/// Deals per lineup.
pub block: u32,
pub stack_bb: f64,
pub seed: u64,
pub cfg: LbrConfig,
pub stacks: Stacks,
}
impl LbrSetup {
pub fn blocks(&self) -> u32 {
self.deals.div_ceil(self.block.max(1))
}
}
/// Engine seat and best-responder seat (indices) of deal `d`.
pub fn lbr_seats(d: u32) -> (usize, usize) {
let h = d as usize % SEATS;
let o = (d as usize / SEATS) % (SEATS - 1);
(h, seat_of(h, o))
}
/// Block `b` of the multiway LBR: one `LbrHand` per deal. The four fixed opponents carry their
/// converged read (`ReadMode::Oracle`); the best-responder's seat is unread (`None`) in both games,
/// the way an unknown player is at a real table. The baseline game seats the lineup member the
/// best-responder replaces.
pub fn lbr_block(setup: &LbrSetup, b: u32) -> Vec<LbrHand> {
let lineup = setup.population.lineup(setup.seed, b);
let member_stacks = lineup_stacks(setup.stacks, setup.stack_bb, setup.seed, b);
let first = b * setup.block;
let last = (first + setup.block).min(setup.deals);
(first..last)
.map(|d| {
let (cards, _) = deal(SEATS, Rng::seeded(mix(setup.seed, d as u64)));
let (h, br) = lbr_seats(d);
let mut opponents = vec![Opponent::Folder; SEATS];
let mut reads: Vec<Option<Profile>> = vec![None; SEATS];
for (m, (_, o)) in lineup.iter().enumerate() {
let s = seat_of(h, m);
opponents[s] = *o;
reads[s] = if s == br { None } else { opponent_profile(*o) };
}
let hand = HandSetup {
deal: &cards,
hero_seat: h as u8 + 1,
opponent: Opponent::Folder,
stack_bb: setup.stack_bb,
seed: mix(setup.seed ^ 0xA5A5, (d as u64) << 8 | h as u64),
read: HandRead::Given(None),
};
let start = seat_stacks(&member_stacks, setup.stack_bb, h);
super::table::lbr6::play_pair(&hand, &opponents, &reads, Some(&start), br, setup.cfg)
})
.collect()
}
/// One line of the LBR sample file.
pub fn lbr_line(h: &LbrHand) -> String {
format!("{} {} {} {} {} {} {}", h.engine, h.engine_base, h.br, h.br_base, h.br_decisions, h.queries, h.invalid)
}
pub fn lbr_parse(line: &str) -> Option<LbrHand> {
let f: Vec<f64> = line.split_whitespace().map(|x| x.parse().ok()).collect::<Option<_>>()?;
(f.len() == 7).then(|| LbrHand {
engine: f[0],
engine_base: f[1],
br: f[2],
br_base: f[3],
br_decisions: f[4] as u32,
queries: f[5] as u64,
invalid: f[6] as u32,
})
}
/// The LBR columns: (name, value of one hand in bb).
pub const LBR_COLUMNS: [(&str, fn(&LbrHand) -> f64); 6] = [
// The best-responder's win rate on its seat.
("lbr", |h| h.br),
// The baseline opponent's on the same seat and deal.
("lbr-basis", |h| h.br_base),
// What best-responding gains over the baseline.
("lbr-gewinn", |h| h.br - h.br_base),
// The engine's loss to the best-responder (paired): the exploitability proxy.
("engine-verlust", |h| h.engine_base - h.engine),
("engine-mit-lbr", |h| h.engine),
("engine-basis", |h| h.engine_base),
];
/// Every LBR column as (name, bb/100, ±95 %).
pub fn lbr_report(hands: &[LbrHand]) -> Vec<(&'static str, f64, f64)> {
LBR_COLUMNS
.iter()
.map(|(name, f)| {
let (m, ci) = rate(&hands.iter().map(f).collect::<Vec<_>>());
(*name, m, ci)
})
.collect()
}