Files
pokerfreak/src/sim/session.rs
T
mmintelandClaude Opus 5.5 e13658faa6 Linien-Audit pool-nl2 gegen echte NL2-Haende, neue Leiter-Persona pool-nl2-echt (Plan §8)
lesen/linien.py: gleiche Linien-Zaehlung fuer Client-Log, Schattenlog und Sim (ab_zelle LINIEN=1),
Bootstrap ueber Spieler, 70/30-Teilung. Persona-Felder size_mix/call_size_exp/raise_bluff (0 = bitgleich).
pool-nl2: 21/40 Linien im Intervall; pool-nl2-echt: 32/40, Pruefteil 26/31. Rueck-Test All-in-Linie
nicht reproduziert (echt 3,0 je 1000, Sim 1,0). STAND §19.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 00:34:57 +01:00

301 lines
12 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
use super::memory::SessionMemory;
use super::opponent::Opponent;
use super::table::{deal, play_hand_tracked, play_hand_tracked_history, Deal, HandRead, HandSetup, TableCost};
use crate::game::{ActionRecord, SeenAction, Street};
use crate::rng::Rng;
use std::fmt;
thread_local! {
/// Diagnostics (`ab_zelle LINIEN=1`, `lesen/linien.py`): while `Some`, every hand of
/// `deal_samples_*` is also written as one JSON line (history, hero seat, cards at showdown).
static LINIEN: std::cell::RefCell<Option<Vec<String>>> = const { std::cell::RefCell::new(None) };
}
/// Start (`true`) or stop collecting hand lines on this thread; see `take_linien`.
pub fn set_linien(on: bool) {
LINIEN.with(|l| *l.borrow_mut() = on.then(Vec::new));
}
/// The hand lines collected on this thread since `set_linien(true)` (collection stays on).
pub fn take_linien() -> Vec<String> {
LINIEN.with(|l| l.borrow_mut().as_mut().map(std::mem::take).unwrap_or_default())
}
fn linien_an() -> bool {
LINIEN.with(|l| l.borrow().is_some())
}
fn street_name(s: Street) -> &'static str {
match s {
Street::Preflop => "PREFLOP",
Street::Flop => "FLOP",
Street::Turn => "TURN",
Street::River => "RIVER",
}
}
/// One hand as a `lesen/linien.py` line: the opponent seats carry the id `kennung`.
fn linie(history: &[ActionRecord], cards: &Deal, hero_seat: u8, players: u8, kennung: &str, netto: f64) -> String {
let v: Vec<String> = history
.iter()
.map(|r| match r.amount {
Some(a) => format!(r#"{{"street":"{}","seat":{},"action":"{}","amount":{:.4}}}"#, street_name(r.street), r.seat, r.action.name(), a),
None => format!(r#"{{"street":"{}","seat":{},"action":"{}"}}"#, street_name(r.street), r.seat, r.action.name()),
})
.collect();
let folded: Vec<u8> = history.iter().filter(|r| r.action == SeenAction::Fold).map(|r| r.seat).collect();
let live: Vec<u8> = (1..=players).filter(|s| !folded.contains(s)).collect();
let (shown, board) = if live.len() >= 2 {
let shown: Vec<String> = live
.iter()
.map(|s| {
let h = cards.holes[*s as usize - 1];
format!(r#""{}":["{}","{}"]"#, s, h[0].short(), h[1].short())
})
.collect();
let board: Vec<String> = cards.board.iter().map(|c| format!(r#""{}""#, c.short())).collect();
(shown.join(","), board.join(","))
} else {
(String::new(), String::new())
};
let ids: Vec<String> = (1..=players).filter(|s| *s != hero_seat).map(|s| format!(r#""{s}":"{kennung}""#)).collect();
format!(
r#"{{"held":{hero_seat},"netto_bb":{netto:.4},"verlauf":[{}],"aufgedeckt":{{{shown}}},"board":[{board}],"kennung":{{{}}}}}"#,
v.join(","),
ids.join(",")
)
}
/// 95 % two-sided normal quantile.
const Z95: f64 = 1.959_964;
/// How the engine gets its read on the opponent for a scenario.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ReadMode {
/// The converged HUD read (`sim::reads`): the exploit brain, the upper bound.
Oracle,
/// No read at all: the no-read baseline a memory / probe must improve on.
Blind,
/// Build the read from the opponent's observed actions over the session (`sim::memory`): starts
/// blind, converges toward the oracle. Lands between `Blind` and `Oracle` on the ladder.
Memory,
/// Live-like: the seat carries a noisy client HUD (`sim::hud`, PokerIntel's measured effective
/// sample) and the memory counts on top of it, read like the live wire (`SessionMemory::hud_read`).
Hud,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Setup {
pub players: u8,
pub opponent: Opponent,
/// Deals; each is played once per seat (duplicate), so hands = deals × players.
pub deals: u32,
pub stack_bb: f64,
pub seed: u64,
/// How the engine is read into the opponent (oracle / blind / memory). See `ReadMode`.
pub read: ReadMode,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Measurement {
pub hands: u32,
pub bb_per_100: f64,
/// Half width of the 95 % interval, bb/100.
pub ci95: f64,
/// The same without luck correction (`sim::luck`): same expectation, wider interval.
pub raw_bb_per_100: f64,
pub raw_ci95: f64,
pub decisions: u32,
pub abstains: u32,
pub invalid: u32,
/// Mean rake of the whole table per hand, bb/100 (0 at the free table).
pub rake_bb_per_100: f64,
}
impl Measurement {
/// Lower end of the 95 % interval, bb/100.
pub fn lower(&self) -> f64 {
self.bb_per_100 - self.ci95
}
}
impl fmt::Display for Measurement {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"{:+.1} bb/100 ± {:.1} (95 %, ohne Korrektur {:+.1} ± {:.1}), {} Hände, {} Entscheidungen, {} ABSTAIN",
self.bb_per_100,
self.ci95,
self.raw_bb_per_100,
self.raw_ci95,
self.hands,
self.decisions,
self.abstains
)
}
}
pub(crate) fn mix(seed: u64, n: u64) -> u64 {
Rng::seeded(seed ^ n.wrapping_mul(0xD1B5_4A32_D192_ED03)).next_u64().0
}
/// `measure_at` the free table: the gross win rate.
pub fn measure(setup: &Setup) -> Measurement {
measure_at(setup, TableCost::FREE)
}
/// Plays `deals` deals, each from every seat, and returns hero's win rate with its interval, net
/// of what `cost` takes. A sample is one deal's mean over the seats, so position and card luck
/// cancel within it.
pub fn measure_at(setup: &Setup, cost: TableCost) -> Measurement {
deal_samples_at(setup, cost).2
}
/// Hero's luck-corrected result per deal in bb at the free table, for paired comparisons, with
/// the measurement.
pub fn deal_samples(setup: &Setup) -> (Vec<f64>, Measurement) {
let (corrected, _, m, _) = deal_samples_at(setup, TableCost::FREE);
(corrected, m)
}
/// Table of the paired ladder (`ab_zelle`): the free table unless `set_ladder_rake(true)` (arm
/// `SIM_RAKE=mikro`) puts it on the live micro table (`TableCost::MICRO`), where the rake is real.
static LADDER_RAKE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
/// Put the paired ladder on the raked micro table (`true`) or the free table (`false`, default).
pub fn set_ladder_rake(on: bool) {
LADDER_RAKE.store(on, std::sync::atomic::Ordering::Relaxed);
}
fn ladder_cost() -> TableCost {
if LADDER_RAKE.load(std::sync::atomic::Ordering::Relaxed) {
TableCost::MICRO
} else {
TableCost::FREE
}
}
/// `deal_samples` plus the session memory at the end (its counts feed the population-prior fit), at
/// the ladder's table (`set_ladder_rake`; the free table by default).
pub fn deal_samples_memory(setup: &Setup) -> (Vec<f64>, Measurement, SessionMemory) {
let (corrected, _, m, memory) = deal_samples_at(setup, ladder_cost());
(corrected, m, memory)
}
/// Per-deal (net result `y`, luck control signal `c`) at the free table. `c` has expectation ~0,
/// so `y - beta*c` is unbiased for any beta; `y - c` (beta=1) is the sample the ladder stores.
/// For analysing the estimator itself (control-variate / AIVAT): see `src/bin/aivat_bench.rs`.
pub fn deal_net_and_luck(setup: &Setup) -> (Vec<f64>, Vec<f64>) {
let (corrected, raw, _, _) = deal_samples_at(setup, TableCost::FREE);
let luck = raw.iter().zip(&corrected).map(|(r, c)| r - c).collect();
(raw, luck)
}
fn deal_samples_at(setup: &Setup, cost: TableCost) -> (Vec<f64>, Vec<f64>, Measurement, SessionMemory) {
let players = setup.players;
let mut samples = Vec::with_capacity(setup.deals as usize);
let mut raw_samples = Vec::with_capacity(setup.deals as usize);
let mut m = Measurement {
hands: 0,
bb_per_100: 0.0,
ci95: 0.0,
raw_bb_per_100: 0.0,
raw_ci95: 0.0,
decisions: 0,
abstains: 0,
invalid: 0,
rake_bb_per_100: 0.0,
};
let mut rake = 0.0;
// The memory accumulates across every hand of the session, in order; unused in the other modes.
let mut memory = SessionMemory::new();
// Hud: the truth from a pre-session on its own seed, then one noisy HUD for the whole session.
let hud = (setup.read == ReadMode::Hud).then(|| {
let pre = Setup { read: ReadMode::Memory, deals: super::hud::HUD_VOR, seed: setup.seed ^ 0x4855_4400_0000_0001, ..*setup };
let (_, _, _, seen) = deal_samples_at(&pre, cost);
super::hud::draw(&super::hud::truth(&seen), Rng::seeded(mix(setup.seed, 0x4855_4402)))
});
for d in 0..setup.deals {
let (cards, _) = deal(players as usize, Rng::seeded(mix(setup.seed, d as u64)));
let (mut sum, mut raw) = (0.0, 0.0);
for hero_seat in 1..=players {
// The read for this hand: oracle, blind, or the memory's snapshot BEFORE the hand plays.
let read = match setup.read {
ReadMode::Oracle => HandRead::Oracle,
ReadMode::Blind => HandRead::Given(None),
ReadMode::Memory => HandRead::Given(memory.read()),
ReadMode::Hud => HandRead::Given(memory.hud_read(hud.as_ref().expect("hud"))),
};
let hand = HandSetup {
deal: &cards,
hero_seat,
opponent: setup.opponent,
stack_bb: setup.stack_bb,
seed: mix(setup.seed ^ 0xA5A5, (d as u64) << 8 | hero_seat as u64),
read,
};
// Only the memory mode feeds the hand back into the accumulator afterwards.
let track = matches!(setup.read, ReadMode::Memory | ReadMode::Hud).then_some(&mut memory);
let r = if linien_an() {
let (r, history) = play_hand_tracked_history(&hand, cost, track);
let id = format!("{:x}", setup.seed);
let l = linie(&history, &cards, hero_seat, players, &id, r.hero_net);
LINIEN.with(|x| x.borrow_mut().as_mut().map(|v| v.push(l)));
r
} else {
play_hand_tracked(&hand, cost, track)
};
rake += r.rake;
sum += r.hero_net - r.luck;
raw += r.hero_net;
m.hands += 1;
m.decisions += r.hero_decisions;
m.abstains += r.abstains;
m.invalid += r.invalid;
}
samples.push(sum / players as f64);
raw_samples.push(raw / players as f64);
}
m.rake_bb_per_100 = 100.0 * rake / m.hands.max(1) as f64;
(m.bb_per_100, m.ci95) = rate(&samples);
(m.raw_bb_per_100, m.raw_ci95) = rate(&raw_samples);
(samples, raw_samples, m, memory)
}
/// Diagnostics: the ladder's deals exactly as `deal_samples_memory` plays them (same seeds, same
/// memory, the ladder's table cost), each hand handed to `seen(deal, cards, hero_seat, result, trace)`.
pub fn deal_trace_memory(setup: &Setup, mut seen: impl FnMut(u32, &super::table::Deal, u8, &super::table::HandResult, &[super::table::Dec])) {
let cost = ladder_cost();
let players = setup.players;
let mut memory = SessionMemory::new();
for d in 0..setup.deals {
let (cards, _) = deal(players as usize, Rng::seeded(mix(setup.seed, d as u64)));
for hero_seat in 1..=players {
let read = match setup.read {
ReadMode::Oracle => HandRead::Oracle,
ReadMode::Blind => HandRead::Given(None),
ReadMode::Memory | ReadMode::Hud => HandRead::Given(memory.read()),
};
let hand = HandSetup {
deal: &cards,
hero_seat,
opponent: setup.opponent,
stack_bb: setup.stack_bb,
seed: mix(setup.seed ^ 0xA5A5, (d as u64) << 8 | hero_seat as u64),
read,
};
let track = (setup.read == ReadMode::Memory).then_some(&mut memory);
let (r, trace) = super::table::play_hand_tracked_traced(&hand, cost, track);
seen(d, &cards, hero_seat as u8, &r, &trace);
}
}
}
/// Mean and 95 % half width of per-deal results, both in bb/100.
pub(crate) fn rate(samples: &[f64]) -> (f64, f64) {
let n = samples.len().max(1) as f64;
let mean = samples.iter().sum::<f64>() / n;
let var = samples.iter().map(|s| (s - mean).powi(2)).sum::<f64>() / (n - 1.0).max(1.0);
(100.0 * mean, 100.0 * Z95 * (var / n).sqrt())
}