diff --git a/src/bin/sechsmax.rs b/src/bin/sechsmax.rs new file mode 100644 index 00000000..d170c76d --- /dev/null +++ b/src/bin/sechsmax.rs @@ -0,0 +1,200 @@ +//! The 6-max ladder (plan O3, `sim::sechsmax`): one ARM, blocks of deals spread over threads, one +//! file per block, so a run resumes and two arms (same seed, other switches) pair deal by deal. +//! +//! Run: +//! `sechsmax lauf [deals=1200] [block=25] [population=micro] [read=memory] [seed=6] [stacks=gemischt]` +//! `sechsmax bericht ` win rate per column (total, position, street, decider) +//! `sechsmax vergleich ` paired difference per column (new minus base) +//! `sechsmax lbr [deals=600] [block=30] [population=micro] [seed=6] [particles=32] [stacks=gemischt]` +//! `sechsmax lbr-bericht ` / `sechsmax lbr-vergleich ` (multiway LBR) +//! Queue form: `sechsmax ...` (= `lauf`; `SECHSMAX_MODUS=lbr` = `lbr`), so the engine queue +//! recognises a running job by its first argument. +//! Threads: `POKERBENCH_THREADS` (default 2). Arms by environment (read once by the engine): +//! `MDF_UNREAD=0`, `OPEN_JAM=1`, and every switch `ab_zelle` knows. Run at priority Idle and copy the +//! binary as `pokerbench-sechsmax-.exe` (CLAUDE.md "Messlaeufe"). + +use rechner::sim::paired::compare; +use rechner::sim::sechsmax::{ + compare_rows, lbr_block, lbr_line, lbr_parse, lbr_report, play_block, report, LbrConfig, LbrHand, LbrSetup, Population, Row, + Setup6, Stacks, LBR_COLUMNS, +}; +use rechner::sim::session::ReadMode; +use rechner::sim::table::TableCost; +use std::sync::atomic::{AtomicUsize, Ordering}; + +fn read_dir(dir: &str) -> Vec { + let mut files: Vec<(u32, std::path::PathBuf)> = std::fs::read_dir(dir) + .unwrap_or_else(|e| panic!("{dir}: {e}")) + .filter_map(|e| e.ok()) + .filter_map(|e| { + let n = e.file_name().to_string_lossy().to_string(); + let b = n.strip_prefix("block.")?.strip_suffix(".txt")?.parse().ok()?; + Some((b, e.path())) + }) + .collect(); + files.sort(); + files + .iter() + .flat_map(|(_, p)| std::fs::read_to_string(p).expect("block file").lines().filter_map(Row::parse).collect::>()) + .collect() +} + +fn lauf(a: &[String]) { + let out = a.get(2).expect("sechsmax lauf [deals] [block] [population] [read] [seed]").clone(); + let num = |i: usize, d: u64| a.get(i).and_then(|s| s.parse().ok()).unwrap_or(d); + let read = match a.get(6).map(String::as_str).unwrap_or("memory") { + "oracle" => ReadMode::Oracle, + "blind" => ReadMode::Blind, + "memory" => ReadMode::Memory, + x => panic!("read {x}: oracle|blind|memory"), + }; + let setup = Setup6 { + population: Population::named(a.get(5).map(String::as_str).unwrap_or("micro")), + deals: num(3, 1200) as u32, + block: num(4, 25) as u32, + stack_bb: 100.0, + seed: num(7, 6), + read, + cost: TableCost::FREE, + stacks: Stacks::named(a.get(8).map(String::as_str).unwrap_or("gemischt")), + }; + std::fs::create_dir_all(&out).expect("out dir"); + let threads: usize = std::env::var("POKERBENCH_THREADS").ok().and_then(|s| s.parse().ok()).unwrap_or(2).max(1); + let todo: Vec = (0..setup.blocks()).filter(|b| !std::path::Path::new(&format!("{out}/block.{b}.txt")).exists()).collect(); + eprintln!("{} Bloecke offen von {}, {threads} Threads", todo.len(), setup.blocks()); + let next = AtomicUsize::new(0); + let t0 = std::time::Instant::now(); + std::thread::scope(|s| { + for _ in 0..threads.min(todo.len().max(1)) { + s.spawn(|| loop { + let j = next.fetch_add(1, Ordering::Relaxed); + let Some(&b) = todo.get(j) else { break }; + let rows = play_block(&setup, b); + let body: Vec = rows.iter().map(Row::line).collect(); + let file = format!("{out}/block.{b}.txt"); + std::fs::write(format!("{file}.tmp"), body.join("\n")).expect("write block"); + std::fs::rename(format!("{file}.tmp"), &file).expect("finish block"); + let bad: u32 = rows.iter().map(|r| r.invalid).sum(); + eprintln!("block {b} fertig ({} Deals, {bad} ungueltig), {:.0} s", rows.len(), t0.elapsed().as_secs_f64()); + }); + } + }); + if rechner::preflop::open_jam::open_jam_on() { + let n = rechner::preflop::open_jam::taken(); + println!("open-jam decisions: {n}"); + std::fs::write(format!("{out}/open_jam_taken.{}.txt", std::process::id()), n.to_string()).expect("write open-jam count"); + } + bericht(&out); +} + +fn bericht(dir: &str) { + let rows = read_dir(dir); + let dec: u32 = rows.iter().map(|r| r.decisions).sum(); + let bad: u32 = rows.iter().map(|r| r.invalid).sum(); + let lost: f64 = rows.iter().map(|r| r.chips_lost).sum(); + println!("{dir}: {} Deals = {} Haende, {dec} Entscheidungen, {bad} ungueltig, Chipfehler {lost:.2e}", rows.len(), 6 * rows.len()); + for (name, m, ci) in report(&rows) { + println!(" {name:<18} {m:>+9.2} bb/100 +-{ci:>7.2}"); + } +} + +fn vergleich(a: &str, b: &str) { + let (x, y) = (read_dir(a), read_dir(b)); + let n = x.len().min(y.len()); + println!("{b} minus {a}: {n} gemeinsame Deals (gepaart)"); + for (name, c) in compare_rows(&x[..n], &y[..n]).expect("compare") { + println!(" {name:<18} {:>+9.2} bb/100 +-{:>7.2} {:?} ({} Deals bewegt)", c.delta_bb_per_100, c.ci95, c.verdict, c.changed_deals); + } +} + +fn main() { + let mut a: Vec = std::env::args().collect(); + // Queue form (`messung_engine/warteschlange.txt` finds a run by its FIRST argument, the out dir): + // `sechsmax ...` = `sechsmax lauf ...`, or the LBR with `SECHSMAX_MODUS=lbr`. + const MODES: [&str; 6] = ["lauf", "bericht", "vergleich", "lbr", "lbr-bericht", "lbr-vergleich"]; + if a.len() > 1 && !MODES.contains(&a[1].as_str()) { + let mode = if std::env::var("SECHSMAX_MODUS").as_deref() == Ok("lbr") { "lbr" } else { "lauf" }; + a.insert(1, mode.to_string()); + } + match a.get(1).map(String::as_str) { + Some("lauf") => lauf(&a), + Some("bericht") => bericht(a.get(2).expect("sechsmax bericht ")), + Some("lbr") => lbr(&a), + Some("lbr-bericht") => lbr_bericht(a.get(2).expect("sechsmax lbr-bericht ")), + Some("lbr-vergleich") => lbr_vergleich(a.get(2).expect("base dir"), a.get(3).expect("new dir")), + Some("vergleich") => vergleich(a.get(2).expect("base dir"), a.get(3).expect("new dir")), + _ => eprintln!("sechsmax lauf|bericht|vergleich|lbr|lbr-bericht|lbr-vergleich ..."), + } +} + +fn lbr_read(dir: &str) -> Vec { + let mut files: Vec<(u32, std::path::PathBuf)> = std::fs::read_dir(dir) + .unwrap_or_else(|e| panic!("{dir}: {e}")) + .filter_map(|e| e.ok()) + .filter_map(|e| { + let n = e.file_name().to_string_lossy().to_string(); + let b = n.strip_prefix("lbr.")?.strip_suffix(".txt")?.parse().ok()?; + Some((b, e.path())) + }) + .collect(); + files.sort(); + files.iter().flat_map(|(_, p)| std::fs::read_to_string(p).expect("lbr file").lines().filter_map(lbr_parse).collect::>()).collect() +} + +fn lbr(a: &[String]) { + let out = a.get(2).expect("sechsmax lbr [deals] [block] [population] [seed] [particles]").clone(); + let num = |i: usize, d: u64| a.get(i).and_then(|s| s.parse().ok()).unwrap_or(d); + let setup = LbrSetup { + population: Population::named(a.get(5).map(String::as_str).unwrap_or("micro")), + deals: num(3, 600) as u32, + block: num(4, 30) as u32, + stack_bb: 100.0, + seed: num(6, 6), + cfg: LbrConfig { particles: num(7, 32) as usize, ..LbrConfig::DEFAULT }, + stacks: Stacks::named(a.get(8).map(String::as_str).unwrap_or("gemischt")), + }; + std::fs::create_dir_all(&out).expect("out dir"); + let threads: usize = std::env::var("POKERBENCH_THREADS").ok().and_then(|s| s.parse().ok()).unwrap_or(2).max(1); + let todo: Vec = (0..setup.blocks()).filter(|b| !std::path::Path::new(&format!("{out}/lbr.{b}.txt")).exists()).collect(); + eprintln!("{} LBR-Bloecke offen von {}, {threads} Threads", todo.len(), setup.blocks()); + let next = AtomicUsize::new(0); + let t0 = std::time::Instant::now(); + std::thread::scope(|s| { + for _ in 0..threads.min(todo.len().max(1)) { + s.spawn(|| loop { + let j = next.fetch_add(1, Ordering::Relaxed); + let Some(&b) = todo.get(j) else { break }; + let hands = lbr_block(&setup, b); + let body: Vec = hands.iter().map(lbr_line).collect(); + let file = format!("{out}/lbr.{b}.txt"); + std::fs::write(format!("{file}.tmp"), body.join("\n")).expect("write block"); + std::fs::rename(format!("{file}.tmp"), &file).expect("finish block"); + eprintln!("lbr block {b} fertig ({} Haende), {:.0} s", hands.len(), t0.elapsed().as_secs_f64()); + }); + } + }); + lbr_bericht(&out); +} + +fn lbr_bericht(dir: &str) { + let h = lbr_read(dir); + let q: u64 = h.iter().map(|x| x.queries).sum(); + let d: u32 = h.iter().map(|x| x.br_decisions).sum(); + let bad: u32 = h.iter().map(|x| x.invalid).sum(); + println!("{dir}: {} Haende, {d} LBR-Entscheidungen, {q} Abfragen, {bad} ungueltig", h.len()); + for (name, m, ci) in lbr_report(&h) { + println!(" {name:<16} {m:>+9.2} bb/100 +-{ci:>7.2}"); + } +} + +fn lbr_vergleich(a: &str, b: &str) { + let (x, y) = (lbr_read(a), lbr_read(b)); + let n = x.len().min(y.len()); + println!("{b} minus {a}: {n} gemeinsame Haende (gepaart)"); + for (name, f) in LBR_COLUMNS { + let xs: Vec = x[..n].iter().map(f).collect(); + let ys: Vec = y[..n].iter().map(f).collect(); + let c = compare(&xs, &ys).expect("compare"); + println!(" {name:<16} {:>+9.2} bb/100 +-{:>7.2} {:?} ({} Haende bewegt)", c.delta_bb_per_100, c.ci95, c.verdict, c.changed_deals); + } +} diff --git a/src/sim/lbr6.rs b/src/sim/lbr6.rs new file mode 100644 index 00000000..8e3a5b0b --- /dev/null +++ b/src/sim/lbr6.rs @@ -0,0 +1,390 @@ +//! Multiway local best response (plan O3): at a six-seat table ONE seat plays a local best response +//! (LBR, Lisy & Bowling 2017) against everybody, the engine sits on another seat, the other four are +//! fixed population opponents. The usual multiway stand-in for exploitability: not an equilibrium +//! distance (there is none to measure multiway), but how much a cheap, greedy counter-player wins +//! and how much MORE the engine loses when such a player sits at its table. +//! +//! **The best-responder.** It knows every player's policy but no hidden card. Per opponent it keeps +//! `particles` hole-card hypotheses (drawn at the start of the hand, uniform without its own cards), +//! weighted by how well each explains that opponent's actions so far: before an opponent acts the +//! table state is copied, the opponent's policy is replayed on every hypothesis with the SAME +//! randomness, and a hypothesis whose action class (fold / check-call / raise) differs keeps only +//! `eps` of its weight (soft, so one surprising action cannot kill the whole set). Hypotheses that +//! collide with its own cards or the board drop out. +//! +//! At its own turn it values, from the current pot and with fold = 0: +//! * check / call: equity against all live ranges times the pot after the call, minus the call; +//! * each raise size (preflop 3x and all-in, postflop half pot, pot and all-in): every live +//! opponent's answer to the raise is replayed on each of its hypotheses (each as if it faced the +//! raise first; independent answers), then joint draws: if everybody folds it takes the pot, +//! otherwise the callers' cards are fixed and one board is rolled out. +//! +//! and plays the best (check / call on a tie). After a raise it assumes the others only call +//! (the LBR simplification); when they re-raise it simply decides again. +//! +//! **Cost.** Each opponent action costs `particles` policy queries; each best-responder decision +//! about `sizes x live x particles` more. Engine queries are full `decide` calls. +//! +//! **Bias, stated.** Sampled ranges (a few dozen hypotheses) are noisy; the HU S1 study measured +//! subsampled LBR biased (`blueprint::lbr`). Independent answers ignore that later players see +//! earlier answers. Both make the counter-player weaker than a true best response, so the number +//! is a LOWER bound on exploitability, best used paired (arm against arm on the same deals). + +use super::{Act, HandSetup, Table, View}; +use crate::card::{deck, Card}; +use crate::hand::fast7::{bit, score}; +use crate::rng::Rng; +use crate::exploit::profile::Profile; +use crate::game::Street; +use crate::sim::opponent::Opponent; + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Config { + /// Hole-card hypotheses per opponent. + pub particles: usize, + /// Joint draws for the equity of check / call. + pub equity_samples: usize, + /// Joint draws per raise size. + pub joint_samples: usize, + /// Weight a hypothesis keeps when its action class does not match. + pub eps: f64, +} + +impl Config { + pub const DEFAULT: Config = Config { particles: 32, equity_samples: 240, joint_samples: 96, eps: 0.02 }; +} + +pub struct State { + pub(super) seat: usize, + cfg: Config, + /// Per seat: hypotheses and their weights (empty for the best-responder's own seat). + parts: Vec>, + w: Vec>, + rng: Rng, + decisions: u32, + queries: u64, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Kind { + Fold, + Passive, + Raise, +} + +fn kind(a: Act, view: View) -> Kind { + match a { + Act::Fold if view.to_call > 0.0 => Kind::Fold, + Act::RaiseTo(_) if view.min_raise_to.is_some() => Kind::Raise, + _ => Kind::Passive, + } +} + +fn hole_mask(h: &[Card; 2]) -> u64 { + bit(h[0]) | bit(h[1]) +} + +impl State { + fn new(t: &Table, seat: usize, cfg: Config, rng: Rng) -> State { + let own = t.setup.deal.holes[seat]; + let pool = deck::without(&own); + let mut rng = rng; + let n = t.players(); + let mut parts = vec![Vec::new(); n]; + for (j, p) in parts.iter_mut().enumerate() { + if j == seat { + continue; + } + for _ in 0..cfg.particles { + let (c, r) = deck::draw(&pool, 2, rng).expect("two cards"); + rng = r; + p.push([c[0], c[1]]); + } + } + let w = parts.iter().map(|p| vec![1.0; p.len()]).collect(); + State { seat, cfg, parts, w, rng, decisions: 0, queries: 0 } + } +} + +/// `seat`'s action at the copy `before` if it held `hole` (same randomness as the real table). +fn replay(before: &Table, seat: usize, hole: [Card; 2], view: Option) -> (Act, View) { + let mut deal = before.setup.deal.clone(); + deal.holes[seat] = hole; + let s = before.setup; + let setup = HandSetup { deal: &deal, hero_seat: s.hero_seat, opponent: s.opponent, stack_bb: s.stack_bb, seed: s.seed, read: s.read }; + let mut q = before.with_setup(&setup); + let view = view.unwrap_or_else(|| q.view(seat)); + (q.choose(seat, view), view) +} + +/// Weighs seat `i`'s hypotheses by the action `act` it just chose at `before`. +pub(super) fn observe(t: &mut Table, before: &Table, i: usize, view: View, act: Act) { + let Some(mut st) = t.br.take() else { return }; + let real = kind(act, view); + let board = t.setup.deal.board[..t.street.board_len()].iter().fold(0u64, |m, c| m | bit(*c)); + for k in 0..st.parts[i].len() { + if st.w[i][k] <= 0.0 { + continue; + } + let h = st.parts[i][k]; + if hole_mask(&h) & board != 0 { + st.w[i][k] = 0.0; + continue; + } + let (a, _) = replay(before, i, h, Some(view)); + st.queries += 1; + if kind(a, view) != real { + st.w[i][k] *= st.cfg.eps; + } + } + t.br = Some(st); +} + +/// Weighted pick among the hypotheses of one seat that avoid `used`. +fn pick(parts: &[[Card; 2]], cum: &[f64], used: u64, rng: Rng) -> (Option, Rng) { + let total = *cum.last().unwrap_or(&0.0); + let mut rng = rng; + if total <= 0.0 { + return (None, rng); + } + for _ in 0..12 { + let (u, r) = rng.unit(); + rng = r; + let x = u * total; + let k = cum.partition_point(|c| *c <= x).min(cum.len() - 1); + if hole_mask(&parts[k]) & used == 0 { + return (Some(k), rng); + } + } + (None, rng) +} + +/// Rolls out the board once and returns `hole`'s share of the pot against `others`. +fn showdown_share(hole: u64, board: &[Card], others: &[u64], used: u64, rng: Rng) -> (f64, Rng) { + let mut rng = rng; + let mut b = board.iter().fold(0u64, |m, c| m | bit(*c)); + let mut used = used; + let mut missing = 5 - board.len(); + while missing > 0 { + let (x, r) = rng.below(52); + rng = r; + let c = 1u64 << (16 * (x / 13) + x % 13); + if c & used == 0 { + used |= c; + b |= c; + missing -= 1; + } + } + let me = score(hole | b); + let mut ties = 1.0; + for o in others { + let s = score(o | b); + if s > me { + return (0.0, rng); + } + if s == me { + ties += 1.0; + } + } + (1.0 / ties, rng) +} + +/// The best-responder's action at seat `i`. +pub(super) fn decide(t: &mut Table, i: usize, view: View) -> Act { + let mut st = t.br.take().expect("LBR state"); + st.decisions += 1; + let hole = hole_mask(&t.setup.deal.holes[i]); + let board_cards: Vec = t.setup.deal.board[..t.street.board_len()].to_vec(); + let board = board_cards.iter().fold(0u64, |m, c| m | bit(*c)); + let live: Vec = (0..t.players()).filter(|j| *j != i && !t.folded[*j]).collect(); + // Cumulative weights per live seat, hypotheses on the board or on own cards removed. + let mut cums: Vec> = Vec::new(); + for &j in &live { + let mut acc = 0.0; + let mut cum: Vec = st.parts[j] + .iter() + .zip(&st.w[j]) + .map(|(h, w)| { + acc += if hole_mask(h) & (board | hole) == 0 { *w } else { 0.0 }; + acc + }) + .collect(); + if acc <= 0.0 { + // Every hypothesis ruled out: fall back to the unweighted set (no information). + acc = 0.0; + cum = st.parts[j] + .iter() + .map(|h| { + acc += if hole_mask(h) & (board | hole) == 0 { 1.0 } else { 0.0 }; + acc + }) + .collect(); + } + cums.push(cum); + } + let pot: f64 = t.total.iter().sum(); + let mut rng = st.rng; + + // Equity against every live range. + let (mut eq, mut n) = (0.0, 0usize); + for _ in 0..st.cfg.equity_samples { + let mut used = hole | board; + let mut others = Vec::with_capacity(live.len()); + let mut ok = true; + for (x, &j) in live.iter().enumerate() { + let (k, r) = pick(&st.parts[j], &cums[x], used, rng); + rng = r; + let Some(k) = k else { + ok = false; + break; + }; + let m = hole_mask(&st.parts[j][k]); + used |= m; + others.push(m); + } + if !ok { + continue; + } + let (s, r) = showdown_share(hole, &board_cards, &others, used, rng); + rng = r; + eq += s; + n += 1; + } + let eq = if n > 0 { eq / n as f64 } else { 1.0 / (live.len() + 1) as f64 }; + + let (mut best_act, mut best_v) = if view.to_call > 0.0 { + let call = eq * (pot + view.to_call) - view.to_call; + if call > 0.0 { (Act::Call, call) } else { (Act::Fold, 0.0) } + } else { + (Act::Check, eq * pot) + }; + + if let Some((min, max)) = view.min_raise_to.zip(view.max_raise_to) { + let mut sizes: Vec = if t.street == Street::Preflop { + vec![3.0 * t.max_bet.max(1.0), max] + } else { + let base = t.bet[i] + view.to_call; + vec![base + 0.5 * (pot + view.to_call), base + (pot + view.to_call), max] + }; + for s in sizes.iter_mut() { + *s = s.clamp(min, max); + } + sizes.dedup_by(|a, b| (*a - *b).abs() < 1e-9); + for to in sizes { + let mut tr = t.snapshot(); + tr.apply(i, view, Act::RaiseTo(to)); + let added = tr.bet[i] - t.bet[i]; + let pot_after: f64 = tr.total.iter().sum(); + // Per live seat and hypothesis: continues facing the raise? + let mut goes_on: Vec> = Vec::with_capacity(live.len()); + for (x, &j) in live.iter().enumerate() { + let can = tr.can_act(j) && tr.max_bet - tr.bet[j] > 1e-9; + let mut row = vec![true; st.parts[j].len()]; + if can { + for k in 0..row.len() { + let w = cums[x][k] - if k > 0 { cums[x][k - 1] } else { 0.0 }; + if w <= 0.0 { + continue; + } + let (a, v) = replay(&tr, j, st.parts[j][k], None); + st.queries += 1; + row[k] = kind(a, v) != Kind::Fold; + } + } + goes_on.push(row); + } + let (mut value, mut m) = (0.0, 0usize); + for _ in 0..st.cfg.joint_samples { + let mut used = hole | board; + let mut callers: Vec<(usize, u64)> = Vec::new(); + let mut ok = true; + for (x, &j) in live.iter().enumerate() { + let (k, r) = pick(&st.parts[j], &cums[x], used, rng); + rng = r; + let Some(k) = k else { + ok = false; + break; + }; + let mk = hole_mask(&st.parts[j][k]); + used |= mk; + if goes_on[x][k] { + callers.push((j, mk)); + } + } + if !ok { + continue; + } + m += 1; + if callers.is_empty() { + value += pot; + continue; + } + let calls: f64 = callers.iter().map(|(j, _)| (tr.max_bet - tr.bet[*j]).clamp(0.0, tr.stack[*j])).sum(); + let others: Vec = callers.iter().map(|c| c.1).collect(); + let (s, r) = showdown_share(hole, &board_cards, &others, used, rng); + rng = r; + value += s * (pot_after + calls) - added; + } + if m > 0 && value / m as f64 > best_v + 1e-9 { + best_v = value / m as f64; + best_act = Act::RaiseTo(to); + } + } + } + st.rng = rng; + t.br = Some(st); + best_act +} + +/// One deal at a mixed six-seat table, twice: with the best-responder on `br_seat` and, for the +/// pairing, with `baseline` there instead. Values in big blinds. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct LbrHand { + /// The engine's result with the best-responder at the table, luck-corrected. + pub engine: f64, + /// The engine's result with the baseline opponent on that seat (same deal), luck-corrected. + pub engine_base: f64, + /// The best-responder's result (raw). + pub br: f64, + /// The baseline opponent's result on the same seat (raw). + pub br_base: f64, + pub br_decisions: u32, + pub queries: u64, + pub invalid: u32, +} + +/// Plays `setup` (hero = the engine) with `opponents` / `reads` per seat; `br_seat` is the +/// best-responder in the first game and `opponents[br_seat]` in the baseline game. +pub fn play_pair( + setup: &HandSetup, + opponents: &[Opponent], + reads: &[Option], + start: Option<&[f64]>, + br_seat: usize, + cfg: Config, +) -> LbrHand { + assert_ne!(br_seat, setup.hero_seat as usize - 1, "the best-responder is not the engine"); + let cost = super::TableCost::FREE; + let mut base = Table::new(setup, cost, None, None, start.map(<[f64]>::to_vec)); + base.opps = opponents.to_vec(); + base.seat_reads = Some(reads.to_vec()); + base.field_strength = true; + base.run(); + let mut t = Table::new(setup, cost, None, None, start.map(<[f64]>::to_vec)); + t.opps = opponents.to_vec(); + t.seat_reads = Some(reads.to_vec()); + t.field_strength = true; + let rng = Rng::seeded(setup.seed ^ 0x1B12_0000_0000_0006); + t.br = Some(Box::new(State::new(&t, br_seat, cfg, rng))); + t.run(); + let st = t.br.take().expect("LBR state"); + LbrHand { + engine: t.result.hero_net - t.result.luck, + engine_base: base.result.hero_net - base.result.luck, + br: t.nets[br_seat], + br_base: base.nets[br_seat], + br_decisions: st.decisions, + queries: st.queries, + invalid: t.result.invalid + base.result.invalid, + } +} diff --git a/src/sim/memory.rs b/src/sim/memory.rs index 0fccdd9b..f3495e05 100644 --- a/src/sim/memory.rs +++ b/src/sim/memory.rs @@ -186,7 +186,8 @@ impl SessionMemory { } } - fn observe_seat(&mut self, history: &[ActionRecord], seat: u8) { + /// One seat's actions of a finished hand (a per-opponent memory at a mixed table, `sim::sechsmax`). + pub fn observe_seat(&mut self, history: &[ActionRecord], seat: u8) { self.observe_lines(history, seat); self.c.hands += 1; let (mut voluntary, mut raised) = (false, false); diff --git a/src/sim/mod.rs b/src/sim/mod.rs index a493820c..5bcc68a6 100644 --- a/src/sim/mod.rs +++ b/src/sim/mod.rs @@ -17,6 +17,7 @@ pub mod paired; pub mod population; pub mod reader; pub mod reads; +pub mod sechsmax; pub mod sequential; pub mod session; pub mod simreal; diff --git a/src/sim/reader.rs b/src/sim/reader.rs index 6f78878d..919f4de4 100644 --- a/src/sim/reader.rs +++ b/src/sim/reader.rs @@ -1,148 +1,184 @@ -//! Opponents that look at their cards: fixed rules on equity against a random hand. Not a model -//! of real players, but they punish what card-blind opponents cannot, such as paying off strong -//! hands or bluffing into a caller. - -use super::opponent::{Act, View}; -use crate::card::{deck, Card}; -use crate::hand::showdown::best; -use crate::rng::Rng; -use crate::variant::HoleUsage; - -/// Boards drawn per strength estimate. -const STRENGTH_SAMPLES: usize = 200; -/// Up to this price (bb) a preflop raise is an open, above it a re-raise. -const OPEN_PRICE: f64 = 1.0; -/// Only hands below this strength bluff. -const BLUFF_BELOW: f64 = 0.45; - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Style { - Reg, - Nit, - Maniac, - Fish, - /// Near-GTO range player; its real play lives in `sim::gto` (needs the table context). - Gto, - /// A second balanced range player: small-ball, half-pot, value-leaning (`sim::gto`, `Shape::SMALL`). - /// An independent balanced target so a defensive fix must generalise, not overfit the one `Gto`. - GtoSmall, -} - -/// What the table tells a reading opponent besides the `View`. -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct Reading { - /// Equity against one random hand, 0 to 1. - pub strength: f64, - pub pot: f64, - /// Already in front of it on this street. - pub own_bet: f64, - pub preflop: bool, -} - -/// The six thresholds that define a reading opponent's whole play. A named `Style` is one point in -/// this space; the synthetic population (`sim::population`) draws arbitrary points around the style -/// means, so one ruleset = one individual opponent. All fields public so the population can build them. -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct Rules { - /// Equity it wants above the pot odds to call. - pub call_margin: f64, - /// Raises a bet from here. - pub raise_at: f64, - /// Bets when checked to from here. - pub bet_at: f64, - /// Opens preflop from here. - pub open_at: f64, - /// How often it bluffs a weak hand when checked to. - pub bluff: f64, - /// Bet size as a share of the pot after calling. - pub size: f64, -} - -impl Style { - pub const ALL: [Style; 4] = [Style::Reg, Style::Nit, Style::Maniac, Style::Fish]; - - pub fn name(self) -> &'static str { - match self { - Style::Reg => "reg", - Style::Nit => "nit", - Style::Maniac => "maniac", - Style::Fish => "fish", - Style::Gto => "gto", - Style::GtoSmall => "gto-small", - } - } - - /// The betting shape for the two balanced range players, `None` for the threshold styles. - pub fn gto_shape(self) -> Option { - match self { - Style::Gto => Some(super::gto::Shape::BALANCED), - Style::GtoSmall => Some(super::gto::Shape::SMALL), - _ => None, - } - } - - pub fn rules(self) -> Rules { - match self { - Style::Reg => Rules { call_margin: 0.22, raise_at: 0.82, bet_at: 0.68, open_at: 0.62, bluff: 0.08, size: 2.0 / 3.0 }, - Style::Nit => Rules { call_margin: 0.32, raise_at: 0.90, bet_at: 0.78, open_at: 0.70, bluff: 0.0, size: 0.5 }, - Style::Maniac => Rules { call_margin: 0.08, raise_at: 0.70, bet_at: 0.55, open_at: 0.52, bluff: 0.35, size: 1.0 }, - // Stand-in only: the table plays `Gto`/`GtoSmall` through `sim::gto`, not these thresholds. - Style::Gto | Style::GtoSmall => Rules { call_margin: 0.22, raise_at: 0.82, bet_at: 0.68, open_at: 0.62, bluff: 0.08, size: 2.0 / 3.0 }, - Style::Fish => Rules { call_margin: 0.02, raise_at: 0.92, bet_at: 0.80, open_at: 0.78, bluff: 0.02, size: 0.4 }, - } - } - - pub fn act(self, view: View, reading: Reading, rng: Rng) -> (Act, Rng) { - act_with(self.rules(), view, reading, rng) - } -} - -/// Play an explicit ruleset (the behaviour of any drawn opponent, not only a named `Style`). Same -/// threshold logic `Style::act` used; lifted out so the population can drive arbitrary `Rules`. -pub fn act_with(rules: Rules, view: View, reading: Reading, rng: Rng) -> (Act, Rng) { - let s = reading.strength; - let to_call = view.to_call; - let raise_from = match (reading.preflop && to_call <= OPEN_PRICE, to_call > 0.0) { - (true, _) => rules.open_at, - (false, true) => rules.raise_at, - (false, false) => rules.bet_at, - }; - let raise = Act::RaiseTo(reading.own_bet + to_call + rules.size * (reading.pot + to_call)); - let can_raise = view.min_raise_to.is_some(); - if can_raise && s >= raise_from { - return (raise, rng); - } - if to_call > 0.0 { - let price = to_call / (reading.pot + to_call); - return (if s >= price + rules.call_margin { Act::Call } else { Act::Fold }, rng); - } - if can_raise && !reading.preflop && s < BLUFF_BELOW { - let (u, rng) = rng.unit(); - return (if u < rules.bluff { raise } else { Act::Check }, rng); - } - (Act::Check, rng) -} - -/// Equity of `hole` against one random hand, ties counting half; seed-fixed Monte Carlo. -pub fn strength(hole: &[Card], board: &[Card], rng: Rng) -> f64 { - let mut known = hole.to_vec(); - known.extend_from_slice(board); - let pool = deck::without(&known); - let missing = 5 - board.len(); - let mut rng = rng; - let mut won = 0.0; - for _ in 0..STRENGTH_SAMPLES { - let (cards, next) = deck::draw(&pool, 2 + missing, rng).expect("enough cards"); - rng = next; - let mut full = board.to_vec(); - full.extend_from_slice(&cards[2..]); - let mine = best(HoleUsage::BestFiveOfAll, hole, &full).expect("valid cards"); - let theirs = best(HoleUsage::BestFiveOfAll, &cards[..2], &full).expect("valid cards"); - won += match mine.cmp(&theirs) { - std::cmp::Ordering::Greater => 1.0, - std::cmp::Ordering::Equal => 0.5, - std::cmp::Ordering::Less => 0.0, - }; - } - won / STRENGTH_SAMPLES as f64 -} +//! Opponents that look at their cards: fixed rules on equity against a random hand. Not a model +//! of real players, but they punish what card-blind opponents cannot, such as paying off strong +//! hands or bluffing into a caller. + +use super::opponent::{Act, View}; +use crate::card::{deck, Card}; +use crate::hand::fast7::{mask, score}; +use crate::rng::Rng; + +/// Boards drawn per strength estimate. +const STRENGTH_SAMPLES: usize = 200; +/// Up to this price (bb) a preflop raise is an open, above it a re-raise. +const OPEN_PRICE: f64 = 1.0; +/// Only hands below this strength bluff. +const BLUFF_BELOW: f64 = 0.45; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Style { + Reg, + Nit, + Maniac, + Fish, + /// Near-GTO range player; its real play lives in `sim::gto` (needs the table context). + Gto, + /// A second balanced range player: small-ball, half-pot, value-leaning (`sim::gto`, `Shape::SMALL`). + /// An independent balanced target so a defensive fix must generalise, not overfit the one `Gto`. + GtoSmall, +} + +/// What the table tells a reading opponent besides the `View`. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Reading { + /// Equity against one random hand, 0 to 1. + pub strength: f64, + pub pot: f64, + /// Already in front of it on this street. + pub own_bet: f64, + pub preflop: bool, +} + +/// The six thresholds that define a reading opponent's whole play. A named `Style` is one point in +/// this space; the synthetic population (`sim::population`) draws arbitrary points around the style +/// means, so one ruleset = one individual opponent. All fields public so the population can build them. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Rules { + /// Equity it wants above the pot odds to call. + pub call_margin: f64, + /// Raises a bet from here. + pub raise_at: f64, + /// Bets when checked to from here. + pub bet_at: f64, + /// Opens preflop from here. + pub open_at: f64, + /// How often it bluffs a weak hand when checked to. + pub bluff: f64, + /// Bet size as a share of the pot after calling. + pub size: f64, +} + +impl Style { + pub const ALL: [Style; 4] = [Style::Reg, Style::Nit, Style::Maniac, Style::Fish]; + + pub fn name(self) -> &'static str { + match self { + Style::Reg => "reg", + Style::Nit => "nit", + Style::Maniac => "maniac", + Style::Fish => "fish", + Style::Gto => "gto", + Style::GtoSmall => "gto-small", + } + } + + /// The betting shape for the two balanced range players, `None` for the threshold styles. + pub fn gto_shape(self) -> Option { + match self { + Style::Gto => Some(super::gto::Shape::BALANCED), + Style::GtoSmall => Some(super::gto::Shape::SMALL), + _ => None, + } + } + + pub fn rules(self) -> Rules { + match self { + Style::Reg => Rules { call_margin: 0.22, raise_at: 0.82, bet_at: 0.68, open_at: 0.62, bluff: 0.08, size: 2.0 / 3.0 }, + Style::Nit => Rules { call_margin: 0.32, raise_at: 0.90, bet_at: 0.78, open_at: 0.70, bluff: 0.0, size: 0.5 }, + Style::Maniac => Rules { call_margin: 0.08, raise_at: 0.70, bet_at: 0.55, open_at: 0.52, bluff: 0.35, size: 1.0 }, + // Stand-in only: the table plays `Gto`/`GtoSmall` through `sim::gto`, not these thresholds. + Style::Gto | Style::GtoSmall => Rules { call_margin: 0.22, raise_at: 0.82, bet_at: 0.68, open_at: 0.62, bluff: 0.08, size: 2.0 / 3.0 }, + Style::Fish => Rules { call_margin: 0.02, raise_at: 0.92, bet_at: 0.80, open_at: 0.78, bluff: 0.02, size: 0.4 }, + } + } + + pub fn act(self, view: View, reading: Reading, rng: Rng) -> (Act, Rng) { + act_with(self.rules(), view, reading, rng) + } +} + +/// Play an explicit ruleset (the behaviour of any drawn opponent, not only a named `Style`). Same +/// threshold logic `Style::act` used; lifted out so the population can drive arbitrary `Rules`. +pub fn act_with(rules: Rules, view: View, reading: Reading, rng: Rng) -> (Act, Rng) { + let s = reading.strength; + let to_call = view.to_call; + let raise_from = match (reading.preflop && to_call <= OPEN_PRICE, to_call > 0.0) { + (true, _) => rules.open_at, + (false, true) => rules.raise_at, + (false, false) => rules.bet_at, + }; + let raise = Act::RaiseTo(reading.own_bet + to_call + rules.size * (reading.pot + to_call)); + let can_raise = view.min_raise_to.is_some(); + if can_raise && s >= raise_from { + return (raise, rng); + } + if to_call > 0.0 { + let price = to_call / (reading.pot + to_call); + return (if s >= price + rules.call_margin { Act::Call } else { Act::Fold }, rng); + } + if can_raise && !reading.preflop && s < BLUFF_BELOW { + let (u, rng) = rng.unit(); + return (if u < rules.bluff { raise } else { Act::Check }, rng); + } + (Act::Check, rng) +} + +/// Equity of `hole` against one random hand, ties counting half; seed-fixed Monte Carlo. +pub fn strength(hole: &[Card], board: &[Card], rng: Rng) -> f64 { + let mut known = hole.to_vec(); + known.extend_from_slice(board); + let pool = deck::without(&known); + let missing = 5 - board.len(); + let mut rng = rng; + let mut won = 0.0; + for _ in 0..STRENGTH_SAMPLES { + let (cards, next) = deck::draw(&pool, 2 + missing, rng).expect("enough cards"); + rng = next; + let mut full = board.to_vec(); + full.extend_from_slice(&cards[2..]); + // `fast7::score` orders hands exactly like `best` (its spec), so the result is bit-identical. + let b = mask(&full); + let (mine, theirs) = (score(mask(hole) | b), score(mask(&cards[..2]) | b)); + won += match mine.cmp(&theirs) { + std::cmp::Ordering::Greater => 1.0, + std::cmp::Ordering::Equal => 0.5, + std::cmp::Ordering::Less => 0.0, + }; + } + won / STRENGTH_SAMPLES as f64 +} + +/// Equity of `hole` against `others` random hands at once (ties split), seed-fixed Monte Carlo: the +/// multiway generalisation of `strength`, so a threshold keeps its meaning ("a favourite against the +/// FIELD") in a pot with several players. Used by the mixed 6-max table postflop (`sim::sechsmax`). +pub fn strength_field(hole: &[Card], board: &[Card], others: usize, rng: Rng) -> f64 { + let mut known = hole.to_vec(); + known.extend_from_slice(board); + let pool = deck::without(&known); + let missing = 5 - board.len(); + let mut rng = rng; + let mut won = 0.0; + for _ in 0..STRENGTH_SAMPLES { + let (cards, next) = deck::draw(&pool, 2 * others + missing, rng).expect("enough cards"); + rng = next; + let mut full = board.to_vec(); + full.extend_from_slice(&cards[2 * others..]); + let b = mask(&full); + let mine = score(mask(hole) | b); + let mut ties = 1.0; + let mut lost = false; + for o in 0..others { + let theirs = score(mask(&cards[2 * o..2 * o + 2]) | b); + if theirs > mine { + lost = true; + break; + } + if theirs == mine { + ties += 1.0; + } + } + if !lost { + won += 1.0 / ties; + } + } + won / STRENGTH_SAMPLES as f64 +} diff --git a/src/sim/sechsmax.rs b/src/sim/sechsmax.rs new file mode 100644 index 00000000..30c357a9 --- /dev/null +++ b/src/sim/sechsmax.rs @@ -0,0 +1,538 @@ +//! 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:` 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; 11] = + ["walk", "cfr", "regeln", "open_jam", "mdf", "heuristik", "turn_veto", "river_veto", "e3", "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:`. + 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:)"), + }, + }; + 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 { + 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 { + 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 { + 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 { + 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 = 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 { + let f: Vec = line.split_whitespace().map(|x| x.parse().ok()).collect::>()?; + 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 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 { + 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 = (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> = 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 => 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 { + (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::() / n; + let var = x.iter().map(|s| (s - mean).powi(2)).sum::() / (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> = rows.iter().map(Row::columns).collect(); + Row::column_names() + .into_iter() + .enumerate() + .map(|(k, name)| { + let x: Vec = 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, String> { + let (a, b): (Vec>, Vec>) = (base.iter().map(Row::columns).collect(), new.iter().map(Row::columns).collect()); + Row::column_names() + .into_iter() + .enumerate() + .map(|(k, name)| { + let x: Vec = a.iter().map(|c| c[k]).collect(); + let y: Vec = 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 { + 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> = 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 { + let f: Vec = line.split_whitespace().map(|x| x.parse().ok()).collect::>()?; + (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::>()); + (*name, m, ci) + }) + .collect() +} diff --git a/src/sim/table.rs b/src/sim/table.rs index 9c2d7178..4cf71a50 100644 --- a/src/sim/table.rs +++ b/src/sim/table.rs @@ -100,6 +100,9 @@ pub struct Dec { pub equity: Option, } +#[path = "lbr6.rs"] +pub mod lbr6; + struct Table<'a> { setup: &'a HandSetup<'a>, cost: TableCost, @@ -128,6 +131,23 @@ struct Table<'a> { world: Vec, /// The pace of the world opponent's action in progress. welt_tank: Option, + /// The opponent on each seat (hero's entry unused). `vec![setup.opponent; n]` everywhere except + /// the mixed table (`play_hand_mixed`, the 6-max ladder `sim::sechsmax`). + opps: Vec, + /// Per-seat reads (hero's entry unused); `Some` only on the mixed table, where it overrides + /// `setup.read` seat by seat. + seat_reads: Option>>, + /// Street and reason text of hero's last decision; kept only on the mixed table. + last: Option<(Street, String)>, + keep_last: bool, + /// The multiway LBR's state (`lbr6`); `None` on every other table. + br: Option>, + /// Every seat's result after `run` (big blinds). + nets: Vec, + /// Postflop with more than two players live, a reading opponent's strength is its equity + /// against the whole field (`reader::strength_field`), not against one random hand. Only the + /// mixed table sets it; heads-up it changes nothing. + field_strength: bool, } impl Table<'_> { @@ -216,12 +236,16 @@ impl Table<'_> { // measures the exploit brain instead of playing it blind - unless the scenario hands a // different read (blind = no profile, or the memory's snapshot). let read = match self.setup.read { - HandRead::Oracle => super::reads::opponent_profile(self.setup.opponent), + HandRead::Oracle if self.seat_reads.is_none() => super::reads::opponent_profile(self.setup.opponent), + HandRead::Oracle => None, HandRead::Given(p) => p, }; let villains = (0..self.players()) .filter(|j| *j != i) - .map(|j| Villain { seat: j as u8 + 1, stack: self.stack[j], folded: self.folded[j], profile: read }) + .map(|j| { + let profile = self.seat_reads.as_ref().map_or(read, |r| r[j]); + Villain { seat: j as u8 + 1, stack: self.stack[j], folded: self.folded[j], profile } + }) .collect(); let decision_seed = self.setup.seed ^ (self.result.hero_decisions as u64 + 1).wrapping_mul(0x9E37_79B9_7F4A_7C15); Spot { @@ -260,10 +284,16 @@ impl Table<'_> { equity: decision.equity, }); } + if self.keep_last { + self.last = Some((spot.street, decision.reason)); + } decision.choice } Err(_) => { self.result.invalid += 1; + if self.keep_last { + self.last = Some((self.street, String::from("invalid"))); + } Choice::Abstain } }; @@ -283,8 +313,15 @@ impl Table<'_> { fn reading(&self, i: usize) -> Reading { let board = &self.setup.deal.board[..self.street.board_len()]; let seed = self.setup.seed ^ ((i as u64 + 1) << 32) ^ (self.street.board_len() as u64 + 1).wrapping_mul(0x51_7CC1); + let hole = &self.setup.deal.holes[i]; + let live = self.live(); + let strength = if self.field_strength && self.street != Street::Preflop && live > 2 { + super::reader::strength_field(hole, board, live - 1, Rng::seeded(seed)) + } else { + strength(hole, board, Rng::seeded(seed)) + }; Reading { - strength: strength(&self.setup.deal.holes[i], board, Rng::seeded(seed)), + strength, pot: self.total.iter().sum(), own_bet: self.bet[i], preflop: self.street == Street::Preflop, @@ -301,7 +338,7 @@ impl Table<'_> { /// One action of seat `i`. For a world opponent (`Opponent::Welt`) the postflop action is also /// logged as a `WorldEvent` (what an observer sees: street, texture, position, move, size, pace). fn act(&mut self, i: usize) -> bool { - let welt = matches!(self.setup.opponent, Opponent::Welt(_)) && i != self.hero && self.street != Street::Preflop; + let welt = matches!(self.opps[i], Opponent::Welt(_)) && i != self.hero && self.street != Street::Preflop; if !welt { return self.act_inner(i); } @@ -339,10 +376,26 @@ impl Table<'_> { fn act_inner(&mut self, i: usize) -> bool { let view = self.view(i); - let act = if i == self.hero { + // Multiway LBR (`lbr6`): the best-responder's seat plays its own policy; before any other + // seat acts, the state is kept so its particles can be weighed by what it actually does. + if self.br.as_ref().is_some_and(|b| b.seat == i) { + let act = lbr6::decide(self, i, view); + return self.apply(i, view, act); + } + let before = self.br.is_some().then(|| self.snapshot()); + let act = self.choose(i, view); + if let Some(before) = before { + lbr6::observe(self, &before, i, view, act); + } + self.apply(i, view, act) + } + + /// What seat `i` (hero or a fixed opponent) plays facing `view`; advances the table's rng. + fn choose(&mut self, i: usize, view: View) -> Act { + if i == self.hero { self.hero_act(view) } else { - let (act, rng) = match self.setup.opponent { + let (act, rng) = match self.opps[i] { Opponent::Welt(p) => { let reading = self.reading(i); let ctx = welt::Ctx { @@ -391,7 +444,11 @@ impl Table<'_> { }; self.rng = rng; act - }; + } + } + + /// Carries out `act` of seat `i`; true when it raised. + fn apply(&mut self, i: usize, view: View, act: Act) -> bool { match act { Act::Fold => { self.folded[i] = true; @@ -547,6 +604,53 @@ impl<'a> Table<'a> { trace, world: Vec::new(), welt_tank: None, + opps: vec![setup.opponent; n], + seat_reads: None, + last: None, + keep_last: false, + br: None, + nets: Vec::new(), + field_strength: false, + } + } + + /// A copy of the state for a what-if query (`lbr6`): no trace, no LBR state. + fn snapshot(&self) -> Table<'a> { + self.with_setup(self.setup) + } + + /// The same state at a table whose deal differs (another hole for one seat): the copy plays + /// the seat's policy on those cards with the SAME randomness the table had at this point. + fn with_setup<'b>(&self, setup: &'b HandSetup<'b>) -> Table<'b> + where + 'a: 'b, + { + Table { + setup, + cost: self.cost, + lage: self.lage, + hero: self.hero, + stack: self.stack.clone(), + start: self.start.clone(), + bet: self.bet.clone(), + total: self.total.clone(), + folded: self.folded.clone(), + street: self.street, + max_bet: self.max_bet, + last_raise: self.last_raise, + history: self.history.clone(), + rng: self.rng, + result: self.result, + trace: None, + world: Vec::new(), + welt_tank: None, + opps: self.opps.clone(), + seat_reads: self.seat_reads.clone(), + last: None, + keep_last: false, + br: None, + nets: Vec::new(), + field_strength: self.field_strength, } } @@ -575,6 +679,7 @@ impl<'a> Table<'a> { self.result.hero_net = nets[self.hero]; self.result.rake = rake; self.result.chips_lost = nets.iter().sum::() + rake; + self.nets = nets; } } @@ -632,3 +737,27 @@ pub fn play_hand_history(setup: &HandSetup, cost: TableCost) -> (HandResult, Vec t.run(); (t.result, t.history) } + +/// One hand at a MIXED table: `opponents[seat - 1]` plays each seat (hero's entry is ignored) and +/// `reads[seat - 1]` is the profile the engine sees on that seat (`setup.opponent` and `setup.read` +/// are then unused). Returns hero's result, the action history (for per-opponent memories) and the +/// street and reason text of hero's LAST decision (`start`: per-seat stacks, `None` = all `stack_bb`) (`None`: hero never had to act, e.g. a walk in the +/// big blind). The 6-max ladder (`sim::sechsmax`) and the multiway LBR are built on it. Reading +/// opponents judge their hand against the whole field postflop (`reader::strength_field`). +pub fn play_hand_mixed( + setup: &HandSetup, + cost: TableCost, + opponents: &[Opponent], + reads: &[Option], + start: Option<&[f64]>, +) -> (HandResult, Vec, Option<(Street, String)>) { + assert_eq!(opponents.len(), setup.deal.holes.len(), "one opponent per seat"); + assert_eq!(reads.len(), setup.deal.holes.len(), "one read per seat"); + let mut t = Table::new(setup, cost, None, None, start.map(<[f64]>::to_vec)); + t.opps = opponents.to_vec(); + t.seat_reads = Some(reads.to_vec()); + t.keep_last = true; + t.field_strength = true; + t.run(); + (t.result, t.history, t.last) +} diff --git a/tests/sim_sechsmax.rs b/tests/sim_sechsmax.rs new file mode 100644 index 00000000..e3ac6262 --- /dev/null +++ b/tests/sim_sechsmax.rs @@ -0,0 +1,222 @@ +//! The 6-max ladder and the multiway LBR (plan O3, `sim::sechsmax`, `sim::table::lbr6`). + +use rechner::card::deck; +use rechner::hand::showdown::best; +use rechner::rng::Rng; +use rechner::sim::opponent::Opponent; +use rechner::sim::reader::{strength, strength_field, Style}; +use rechner::sim::reads::opponent_profile; +use rechner::sim::sechsmax::{ + decider, lbr_block, lbr_report, lbr_seats, play_block, report, run, seat_of, LbrConfig, LbrSetup, Population, Setup6, Stacks, + DECIDERS, SEATS, +}; +use rechner::sim::session::ReadMode; +use rechner::sim::table::{deal, play_hand_at, play_hand_mixed, HandRead, HandSetup, TableCost}; +use rechner::variant::HoleUsage; + +fn setup(pop: &str, deals: u32, block: u32, read: ReadMode) -> Setup6 { + Setup6 { population: Population::named(pop), deals, block, stack_bb: 100.0, seed: 11, read, cost: TableCost::FREE, stacks: Stacks::Gemischt } +} + +/// The old `reader::strength` with the general evaluator: the fast one must give the same number. +fn strength_slow(hole: &[rechner::card::Card], board: &[rechner::card::Card], rng: Rng) -> f64 { + let mut known = hole.to_vec(); + known.extend_from_slice(board); + let pool = deck::without(&known); + let missing = 5 - board.len(); + let mut rng = rng; + let mut won = 0.0; + for _ in 0..200 { + let (cards, next) = deck::draw(&pool, 2 + missing, rng).unwrap(); + rng = next; + let mut full = board.to_vec(); + full.extend_from_slice(&cards[2..]); + let mine = best(HoleUsage::BestFiveOfAll, hole, &full).unwrap(); + let theirs = best(HoleUsage::BestFiveOfAll, &cards[..2], &full).unwrap(); + won += match mine.cmp(&theirs) { + std::cmp::Ordering::Greater => 1.0, + std::cmp::Ordering::Equal => 0.5, + std::cmp::Ordering::Less => 0.0, + }; + } + won / 200.0 +} + +#[test] +fn strength_on_the_fast_evaluator_is_bit_identical() { + let mut rng = Rng::seeded(99); + for k in 0..120 { + let n = [0, 3, 4, 5][k % 4]; + let (cards, r) = deck::draw(&deck::full(), 2 + n, rng).unwrap(); + rng = r; + let seed = Rng::seeded(k as u64); + assert_eq!(strength(&cards[..2], &cards[2..], seed), strength_slow(&cards[..2], &cards[2..], seed)); + } +} + +#[test] +fn field_strength_against_one_hand_is_strength() { + let mut rng = Rng::seeded(7); + for k in 0..60 { + let n = [3, 4, 5][k % 3]; + let (cards, r) = deck::draw(&deck::full(), 2 + n, rng).unwrap(); + rng = r; + let seed = Rng::seeded(k as u64 + 500); + assert_eq!(strength_field(&cards[..2], &cards[2..], 1, seed), strength(&cards[..2], &cards[2..], seed)); + // Against more hands the same holding is never a bigger favourite (Monte Carlo, loose bound). + let one = strength(&cards[..2], &cards[2..], seed); + let four = strength_field(&cards[..2], &cards[2..], 4, seed); + assert!(four <= one + 0.08, "{one} vs four {four}"); + } + // Aces on a dry flop are a big favourite against one hand, much less against four. + let aa = rechner::card::Card::parse_list("As Ah").unwrap(); + let flop = rechner::card::Card::parse_list("7c 2d 9h").unwrap(); + let (one, four) = (strength(&aa, &flop, Rng::seeded(1)), strength_field(&aa, &flop, 4, Rng::seeded(1))); + assert!(one > 0.85 && four < one - 0.1 && four > 0.5, "{one} {four}"); +} + +#[test] +fn a_mixed_table_of_one_type_plays_exactly_the_old_table() { + // Same opponent on every seat and its oracle read per seat = the old table with `HandRead::Oracle`. + // Heads-up for every type; six-handed only for a card-blind type (the mixed table's reading + // opponents judge their hand against the whole field postflop, the old table against one hand). + for players in [2usize, 6] { + let types = if players == 2 { + vec![Opponent::Reader(Style::Reg), Opponent::Reader(Style::Gto), Opponent::CallingStation] + } else { + vec![Opponent::CallingStation, Opponent::RandomLegal] + }; + for (k, opp) in types.into_iter().enumerate() { + for d in 0..6u64 { + let (cards, _) = deal(players, Rng::seeded(1000 * k as u64 + d)); + let hero_seat = (d as usize % players) as u8 + 1; + let hand = HandSetup { deal: &cards, hero_seat, opponent: opp, stack_bb: 100.0, seed: d, read: HandRead::Oracle }; + let old = play_hand_at(&hand, TableCost::FREE); + let (new, history, last) = play_hand_mixed(&hand, TableCost::FREE, &vec![opp; players], &vec![opponent_profile(opp); players], None); + assert_eq!(old, new, "{players} Sitze, {opp:?}, Deal {d}"); + assert!(!history.is_empty()); + assert_eq!(last.is_some(), new.hero_decisions > 0); + } + } + } +} + +#[test] +fn the_ladder_is_deterministic_and_its_columns_add_up() { + let s = setup("misch", 8, 4, ReadMode::Memory); + let rows = run(&s); + assert_eq!(rows.len(), 8); + assert_eq!(rows, run(&s), "same seed, same rows"); + // Blocks are independent: block 1 alone equals rows 4..8. + assert_eq!(play_block(&s, 1), rows[4..].to_vec()); + for r in &rows { + assert_eq!(r.invalid, 0); + assert!(r.chips_lost < 1e-6, "chips {}", r.chips_lost); + assert!(r.decisions > 0); + let pos: f64 = r.pos.iter().sum::() / SEATS as f64; + assert!((pos - r.total).abs() < 1e-9); + assert!((r.street.iter().sum::() - r.total).abs() < 1e-9); + assert!((r.decider.iter().sum::() - r.total).abs() < 1e-9); + } + let rep = report(&rows); + assert_eq!(rep.len(), 2 + SEATS + 4 + DECIDERS.len()); + assert!(rep.iter().all(|(_, m, ci)| m.is_finite() && ci.is_finite())); +} + +#[test] +fn a_parsed_row_is_the_row() { + let rows = run(&setup("micro", 2, 2, ReadMode::Oracle)); + for r in rows { + let mut back = rechner::sim::sechsmax::Row::parse(&r.line()).expect("parses"); + back.chips_lost = r.chips_lost; + assert_eq!(back, r); + } +} + +#[test] +fn lineups_follow_the_population() { + let p = Population::named("nur:jammer"); + let l = p.lineup(3, 0); + assert_eq!(l.len(), SEATS - 1); + assert!(l.iter().all(|(n, o)| *n == "jammer" && matches!(o, Opponent::Styled(_)))); + let m = Population::named("misch"); + assert_eq!(m.lineup(3, 7), m.lineup(3, 7)); + assert_ne!(m.lineup(3, 7), m.lineup(3, 8)); + // Seating: the five members fill the five seats around hero. + for h in 0..SEATS { + let mut seats: Vec = (0..SEATS - 1).map(|m| seat_of(h, m)).collect(); + seats.push(h); + seats.sort(); + assert_eq!(seats, (0..SEATS).collect::>()); + } +} + +#[test] +fn deciders_follow_the_reason_text() { + use rechner::game::Street; + let idx = |n: &str| DECIDERS.iter().position(|d| *d == n).unwrap(); + assert_eq!(decider(None), idx("walk")); + assert_eq!(decider(Some(&(Street::River, "MDF-Boden: Made-Hand verteidigt".into()))), idx("mdf")); + assert_eq!(decider(Some(&(Street::Preflop, "BTN vs open-jam 90bb from CO: equity".into()))), idx("open_jam")); + assert_eq!(decider(Some(&(Street::Preflop, "BTN vs open, CFR x".into()))), idx("cfr")); + assert_eq!(decider(Some(&(Street::Preflop, "rules".into()))), idx("regeln")); + assert_eq!(decider(Some(&(Street::River, "defensive veto: x".into()))), idx("river_veto")); + assert_eq!(decider(Some(&(Street::Turn, "defensive turn veto: x".into()))), idx("turn_veto")); + assert_eq!(decider(Some(&(Street::Flop, "value bet".into()))), idx("heuristik")); +} + +#[test] +fn the_jammer_opens_all_in() { + // A jammer seat with a premium hand, first to act: its open is all-in. + let opp = Opponent::Styled(rechner::sim::sechsmax::JAMMER); + let mut seen = 0; + for d in 0..200u64 { + let (cards, _) = deal(6, Rng::seeded(d)); + let hand = HandSetup { deal: &cards, hero_seat: 1, opponent: opp, stack_bb: 100.0, seed: d, read: HandRead::Given(None) }; + let (_, history, _) = play_hand_mixed(&hand, TableCost::FREE, &[opp; 6], &[None; 6], None); + use rechner::game::{SeenAction, Street}; + let first_raise = history.iter().find(|r| r.street == Street::Preflop && r.action.is_aggressive() && r.action != SeenAction::PostBigBlind && r.action != SeenAction::PostSmallBlind); + if let Some(r) = first_raise { + if r.seat != 1 { + assert_eq!(r.action, SeenAction::AllIn, "deal {d}: {r:?}"); + seen += 1; + } + } + } + assert!(seen > 10, "{seen} jams"); +} + +#[test] +fn lbr_seats_cover_every_pair() { + let mut pairs = std::collections::BTreeSet::new(); + for d in 0..30 { + let (h, b) = lbr_seats(d); + assert_ne!(h, b); + pairs.insert((h, b)); + } + assert_eq!(pairs.len(), 30); +} + +#[test] +fn the_multiway_lbr_is_deterministic_valid_and_beats_a_station_seat() { + let s = LbrSetup { + population: Population::named("nur:station"), + deals: 60, + block: 60, + stack_bb: 100.0, + seed: 5, + cfg: LbrConfig { particles: 12, equity_samples: 120, joint_samples: 48, ..LbrConfig::DEFAULT }, + stacks: Stacks::Gemischt, + }; + let a = lbr_block(&s, 0); + assert_eq!(a.len(), 60); + assert!(a.iter().all(|h| h.invalid == 0)); + assert!(a.iter().any(|h| h.br_decisions > 0)); + let b = lbr_block(&s, 0); + assert_eq!(a, b, "same seed, same hands"); + // Against four calling stations the best-responder value-bets and never bluffs: it must win + // more on its seat than the calling station it replaces. + let rep = lbr_report(&a); + let gain = rep.iter().find(|r| r.0 == "lbr-gewinn").unwrap().1; + assert!(gain > 0.0, "LBR gain over a station seat {gain:+.1} bb/100"); +}