Welt v5 part (b): E-step in Rust (std only), strengths bit-equal to Python, kernel as flat-array function

Standalone crate messung/batterie/v2/welt_v5/estep with binary pokerbench-welt5-estep:
joint posterior over (type, combo) per player, forward-range midpoint quantiles, shown/muck
evidence, 20-bin smoothed histograms, vergleich tool, synthetic generator, gzip wrapper.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-02 17:11:59 +01:00
co-authored by Claude Opus 5.5
parent 1d71ad7496
commit ca766dbae3
19 changed files with 3252 additions and 0 deletions
@@ -0,0 +1 @@
target/
+7
View File
@@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "pokerbench-welt5-estep"
version = "0.1.0"
@@ -0,0 +1,25 @@
[package]
name = "pokerbench-welt5-estep"
version = "0.1.0"
edition = "2021"
description = "Welt v5 E-Schritt: Posterior ueber (Typ, Handkombi) je Spieler und Hand, std only"
[lib]
name = "estep"
path = "src/lib.rs"
[[bin]]
name = "pokerbench-welt5-estep"
path = "src/main.rs"
[dependencies]
# eigener Baum: haengt nicht am Wurzel-Workspace
[workspace]
[profile.dev]
opt-level = 2
[profile.release]
opt-level = 3
debug = false
@@ -0,0 +1,55 @@
# Welt v5 E-step with gzip in and out (the Rust binary reads/writes plain JSONL on stdin/stdout).
# python3 lauf_gz.py --haende in.jsonl.gz --params params.json --out out.jsonl.gz [--faeden 4] [--mischung 0] [--max-typen 3] [--max N] [--vorflop F]
# Output goes to <out>.tmp and is renamed when the E-step finished without a crash; an existing <out> is never overwritten.
# Data outputs belong under /Volumes/Alpha SSD/pokerfreak-daten/welt_v5/ (hands and player ids never go into git).
import sys; sys.dont_write_bytecode = True
import argparse, gzip, os, subprocess, threading
HIER = os.path.dirname(os.path.abspath(__file__))
EXE = os.path.join(HIER, "target", "release", "pokerbench-welt5-estep")
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--haende", required=True)
ap.add_argument("--params", required=True)
ap.add_argument("--out", required=True)
ap.add_argument("--faeden", default="4")
ap.add_argument("--mischung", default="0")
ap.add_argument("--max-typen", default="3")
ap.add_argument("--max", default=None)
ap.add_argument("--vorflop", default=None)
a = ap.parse_args()
if os.path.exists(a.out) or os.path.exists(a.out + ".tmp"):
sys.exit("refusing to overwrite " + a.out)
cmd = ["nice", "-n", "10", EXE, "estep", "--haende", "-", "--params", a.params, "--out", "-",
"--faeden", a.faeden, "--mischung", a.mischung, "--max-typen", a.max_typen, "--nice", "0"]
if a.max: cmd += ["--max", a.max]
if a.vorflop: cmd += ["--vorflop", a.vorflop]
opener = gzip.open if a.haende.endswith(".gz") else open
p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
def einspeisen():
try:
with opener(a.haende, "rb") as f:
for blk in iter(lambda: f.read(1 << 20), b""):
p.stdin.write(blk)
except BrokenPipeError:
pass # --max reached or the binary died; its exit code decides below
finally:
try: p.stdin.close()
except BrokenPipeError: pass
t = threading.Thread(target=einspeisen); t.start()
tmp = a.out + ".tmp"
with open(tmp, "xb") as raw, gzip.GzipFile(fileobj=raw, mode="wb", compresslevel=3) as g:
for blk in iter(lambda: p.stdout.read(1 << 20), b""):
g.write(blk)
t.join()
rc = p.wait()
if rc not in (0, 2): # 2 = some hands carried an error line ("fehler"), the file is still complete
sys.exit("estep failed with exit code %d, partial output stays in %s" % (rc, tmp))
os.rename(tmp, a.out)
print("ok" if rc == 0 else "ok, but some hands have a 'fehler' entry", a.out)
main()
@@ -0,0 +1,397 @@
//! One hand: parse the decision file line, run the kernel per player and type, build the output line.
//! Joint per player: type weight * (1 / N_live) * sum_h [ prod_d P(a_d | d, h, type) * evidence(h) ].
//! ll of the hand = sum over players of ln(joint total).
use crate::json::{self, J};
use crate::karten::{board_bits, board_maske, kombi_nr, score, tafeln, NC};
use crate::kern::{vorwaerts, KernAus, KernEin, NA, NQ, NS};
use crate::modell::Params;
use crate::staerke::{brett_staerke, ordnung, vorflop_staerke, Scratch};
pub const LIMIT_BASIS_BB: f64 = 0.02;
#[derive(Debug, Clone)]
pub struct Ent {
pub st: u8,
pub codes: [i64; 3],
pub erlaubt: [u8; NA],
pub o: [f64; NA],
pub zug: u8,
}
#[derive(Debug, Clone)]
pub struct Spieler {
pub platz: i64,
pub typen: Vec<(i32, f64)>,
pub gezeigt: Option<[u8; 2]>,
pub muck: Option<[u8; 2]>,
pub ents: Vec<Ent>,
}
#[derive(Debug, Clone)]
pub struct Hand {
pub id: String,
pub bb: f64,
pub brett: Vec<u8>,
pub spieler: Vec<Spieler>,
}
fn karte(j: &J) -> Result<u8, String> {
match j.i64() {
Some(c) if (0..52).contains(&c) => Ok(c as u8),
_ => Err("bad card".into()),
}
}
fn zwei(j: Option<&J>) -> Result<Option<[u8; 2]>, String> {
match j {
None | Some(J::Null) => Ok(None),
Some(x) => {
let a = x.arr().ok_or("cards: expected array")?;
if a.len() != 2 {
return Err("cards: expected 2".into());
}
let (c1, c2) = (karte(&a[0])?, karte(&a[1])?);
if c1 == c2 {
return Err("cards: duplicate".into());
}
Ok(Some([c1, c2]))
}
}
}
fn zahlen<const N: usize>(j: &J, what: &str) -> Result<[f64; N], String> {
let a = j.arr().ok_or_else(|| format!("{}: expected array", what))?;
if a.len() != N {
return Err(format!("{}: expected {} entries", what, N));
}
let mut out = [0.0; N];
for i in 0..N {
out[i] = a[i].f64().ok_or_else(|| format!("{}: not a number", what))?;
}
Ok(out)
}
impl Hand {
pub fn from_json(j: &J) -> Result<Hand, String> {
let id = match j.get("h") {
Some(J::Str(s)) => s.clone(),
Some(J::Num(x)) => format!("{}", x),
_ => return Err("missing h".into()),
};
let bb = j.get("bb").and_then(|x| x.f64()).unwrap_or(LIMIT_BASIS_BB);
let brett: Vec<u8> = j.get("brett").and_then(|x| x.arr()).ok_or("missing brett")?.iter().map(karte).collect::<Result<_, _>>()?;
if brett.len() > 5 || (brett.len() != 0 && brett.len() < 3) {
return Err(format!("brett has {} cards", brett.len()));
}
let mut spieler = Vec::new();
for (i, sp) in j.get("spieler").and_then(|x| x.arr()).ok_or("missing spieler")?.iter().enumerate() {
let platz = sp.get("platz").and_then(|x| x.i64()).unwrap_or(i as i64);
let mut typen = Vec::new();
for tw in sp.get("typen").and_then(|x| x.arr()).unwrap_or(&[]) {
let a = tw.arr().ok_or("typen: expected [t, w]")?;
if a.len() != 2 {
return Err("typen: expected [t, w]".into());
}
typen.push((a[0].i64().ok_or("typen: bad t")? as i32, a[1].f64().ok_or("typen: bad w")?));
}
let mut ents = Vec::new();
for e in sp.get("ents").and_then(|x| x.arr()).unwrap_or(&[]) {
let st = e.get("st").and_then(|x| x.i64()).ok_or("ent: missing st")?;
if !(0..NS as i64).contains(&st) {
return Err("ent: st out of range".into());
}
let c = e.get("codes").and_then(|x| x.arr()).ok_or("ent: missing codes")?;
if c.len() != 3 {
return Err("ent: codes need 3 entries".into());
}
let codes = [c[0].i64().ok_or("bad code")?, c[1].i64().ok_or("bad code")?, c[2].i64().ok_or("bad code")?];
let er = zahlen::<NA>(e.get("erlaubt").ok_or("ent: missing erlaubt")?, "erlaubt")?;
let o = match e.get("o") {
Some(x) => zahlen::<NA>(x, "o")?,
None => [0.0; NA],
};
let zug = e.get("zug").and_then(|x| x.i64()).ok_or("ent: missing zug")?;
if !(0..NA as i64).contains(&zug) {
return Err("ent: zug out of range".into());
}
let mut erlaubt = [0u8; NA];
for a in 0..NA {
erlaubt[a] = (er[a] != 0.0) as u8;
}
ents.push(Ent { st: st as u8, codes, erlaubt, o, zug: zug as u8 });
}
spieler.push(Spieler { platz, typen, gezeigt: zwei(sp.get("gezeigt"))?, muck: zwei(sp.get("muck"))?, ents });
}
Ok(Hand { id, bb, brett, spieler })
}
}
#[derive(Debug, Clone)]
pub struct EntAus {
pub platz: i64,
pub d: usize,
pub codes: [i64; 3],
pub typ: i32,
pub typ_post: f64,
pub zug: u8,
pub erlaubt: [u8; NA],
pub o: [f64; NA],
pub st: u8,
/// (weight, mean q) per bin; the weights of all entries of one decision sum to 1
pub bins: [(f64, f64); NQ],
}
#[derive(Debug, Clone)]
pub struct HandAus {
pub id: String,
/// None when some player has likelihood 0 (written as null)
pub ll: Option<f64>,
pub nullspieler: Vec<i64>,
pub ents: Vec<EntAus>,
}
pub struct Optionen {
pub mischung: f64,
pub max_typen: usize,
}
impl Default for Optionen {
fn default() -> Self {
Optionen { mischung: 0.0, max_typen: 3 }
}
}
/// At most `max` largest weights (stable), renormalised; no usable type -> the pseudo type -1 (pool only).
pub fn typen_vorbereiten(typen: &[(i32, f64)], max: usize) -> Vec<(i32, f64)> {
let mut v: Vec<(i32, f64)> = typen.iter().copied().filter(|&(_, w)| w > 0.0 && w.is_finite()).collect();
v.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());
v.truncate(max.max(1));
let s: f64 = v.iter().map(|x| x.1).sum();
if v.is_empty() || s <= 0.0 {
return vec![(-1, 1.0)];
}
v.iter().map(|&(t, w)| (t, w / s)).collect()
}
#[derive(Default)]
pub struct Werkzeug {
pub st: Scratch,
pub aus: KernAus,
}
impl Werkzeug {
pub fn new() -> Self {
Werkzeug { st: Scratch::new(), aus: KernAus::new() }
}
}
pub fn estep_hand(p: &Params, opt: &Optionen, hand: &Hand, wz: &mut Werkzeug) -> Result<HandAus, String> {
let t = tafeln();
let brett = &hand.brett;
let bm = board_maske(brett);
// strengths per street, only if some decision needs them; sorted order over all non-NaN combos
let mut ord_voll: [Option<Vec<u16>>; NS] = [None, None, None, None];
for sp in &hand.spieler {
for e in &sp.ents {
let s = e.st as usize;
if ord_voll[s].is_some() {
continue;
}
let st = if s == 0 {
let vf = p.vorflop.as_ref().ok_or("preflop decision but the parameter file has no 'vorflop' table")?;
vorflop_staerke(vf)
} else {
let n = 2 + s;
if brett.len() < n {
return Err(format!("decision on street {} but board has {} cards", s, brett.len()));
}
brett_staerke(&mut wz.st, &brett[..n])
};
ord_voll[s] = Some(ordnung(&st));
}
}
let lam_shift = if hand.bb > 0.0 { (hand.bb / LIMIT_BASIS_BB).log2() } else { 0.0 };
let mut aus = HandAus { id: hand.id.clone(), ll: Some(0.0), nullspieler: Vec::new(), ents: Vec::new() };
let mut live_flag = vec![false; NC];
let mut evid = vec![0.0f64; NC];
for (si, sp) in hand.spieler.iter().enumerate() {
// live combos: board and the SHOWN cards of the other players are out
let mut weg = bm;
for (sj, other) in hand.spieler.iter().enumerate() {
if sj != si {
if let Some(g) = other.gezeigt {
weg |= (1u64 << g[0]) | (1u64 << g[1]);
}
}
}
let live: Vec<u16> = (0..NC as u16).filter(|&h| t.maske[h as usize] & weg == 0).collect();
live_flag.iter_mut().for_each(|x| *x = false);
for &h in &live {
live_flag[h as usize] = true;
}
// showdown evidence
evid.iter_mut().for_each(|x| *x = 0.0);
if let Some(g) = sp.gezeigt {
evid[kombi_nr(g[0], g[1])] = 1.0;
} else if let (Some(m), true) = (sp.muck, brett.len() == 5) {
let bb5 = board_bits(brett);
let gegen = score(bb5 | crate::karten::bit(m[0]) | crate::karten::bit(m[1]));
for &h in &live {
if score(bb5 | t.bits[h as usize]) < gegen {
evid[h as usize] = 1.0;
}
}
} else {
for &h in &live {
evid[h as usize] = 1.0;
}
}
let n_live = live.len() as f64;
let typen = typen_vorbereiten(&sp.typen, opt.max_typen);
let nd = sp.ents.len();
let st: Vec<u8> = sp.ents.iter().map(|e| e.st).collect();
let zug: Vec<u8> = sp.ents.iter().map(|e| e.zug).collect();
let mut erl = Vec::with_capacity(nd * NA);
for e in &sp.ents {
erl.extend_from_slice(&e.erlaubt);
}
let ords: Vec<Vec<u16>> = (0..NS)
.map(|s| match &ord_voll[s] {
Some(o) if sp.ents.iter().any(|e| e.st as usize == s) => o.iter().copied().filter(|&h| live_flag[h as usize]).collect(),
_ => Vec::new(),
})
.collect();
// per type: kernel run
let mut je_typ: Vec<(f64, Vec<f64>, Vec<f64>)> = Vec::new(); // (total, bin_w, bin_qw)
for &(ty, _) in &typen {
let mut ufix = Vec::with_capacity(nd * NA);
for e in &sp.ents {
let al = p.alpha_fuer(ty, e.codes);
for a in 0..NA {
ufix.push(al[a] + e.o[a] + p.lambda[a] * lam_shift);
}
}
let ein = KernEin {
nd,
st: &st,
zug: &zug,
erlaubt: &erl,
ufix: &ufix,
beta: &p.beta,
live: &live,
ordnung: [&ords[0], &ords[1], &ords[2], &ords[3]],
evid: &evid,
mischung: opt.mischung,
};
vorwaerts(&ein, &mut wz.aus);
je_typ.push((wz.aus.gesamt, wz.aus.bin_w.clone(), wz.aus.bin_qw.clone()));
}
// joint = type weight * total / N
let joint: Vec<f64> = typen.iter().zip(&je_typ).map(|(&(_, w), x)| w * x.0 / n_live.max(1.0)).collect();
let grand: f64 = joint.iter().sum();
if !(grand > 0.0) {
aus.ll = None;
aus.nullspieler.push(sp.platz);
continue;
}
if let Some(l) = aus.ll.as_mut() {
*l += grand.ln();
}
for (d, e) in sp.ents.iter().enumerate() {
for (ti, &(ty, _)) in typen.iter().enumerate() {
if joint[ti] <= 0.0 {
continue;
}
let f = typen[ti].1 / n_live.max(1.0) / grand;
let mut bins = [(0.0, 0.0); NQ];
for b in 0..NQ {
let w = je_typ[ti].1[d * NQ + b];
let q = if w > 0.0 { je_typ[ti].2[d * NQ + b] / w } else { (b as f64 + 0.5) / NQ as f64 };
bins[b] = (w * f, q);
}
aus.ents.push(EntAus {
platz: sp.platz,
d,
codes: e.codes,
typ: ty,
typ_post: joint[ti] / grand,
zug: e.zug,
erlaubt: e.erlaubt,
o: e.o,
st: e.st,
bins,
});
}
}
}
Ok(aus)
}
impl HandAus {
pub fn to_json(&self) -> String {
let mut s = String::with_capacity(512 + self.ents.len() * 900);
s.push_str("{\"h\":");
json::string(&mut s, &self.id);
s.push_str(",\"ll\":");
match self.ll {
Some(x) => json::num(&mut s, x),
None => s.push_str("null"),
}
if !self.nullspieler.is_empty() {
s.push_str(",\"null_platz\":[");
for (i, p) in self.nullspieler.iter().enumerate() {
if i > 0 {
s.push(',');
}
s.push_str(&p.to_string());
}
s.push(']');
}
s.push_str(",\"ents\":[");
for (i, e) in self.ents.iter().enumerate() {
if i > 0 {
s.push(',');
}
s.push_str(&format!("{{\"platz\":{},\"d\":{},\"codes\":[{},{},{}],\"typen\":[[{},", e.platz, e.d, e.codes[0], e.codes[1], e.codes[2], e.typ));
json::num(&mut s, e.typ_post);
s.push_str(&format!("]],\"zug\":{},\"erlaubt\":[", e.zug));
for a in 0..NA {
if a > 0 {
s.push(',');
}
s.push(if e.erlaubt[a] != 0 { '1' } else { '0' });
}
s.push_str("],\"o\":[");
for a in 0..NA {
if a > 0 {
s.push(',');
}
json::num(&mut s, e.o[a]);
}
s.push_str(&format!("],\"st\":{},\"bins\":[", e.st));
for b in 0..NQ {
if b > 0 {
s.push(',');
}
s.push('[');
json::num(&mut s, e.bins[b].0);
s.push(',');
json::num(&mut s, e.bins[b].1);
s.push(']');
}
s.push_str("]}");
}
s.push_str("]}");
s
}
}
pub fn fehlerzeile(id: &str, msg: &str) -> String {
let mut s = String::from("{\"h\":");
json::string(&mut s, id);
s.push_str(",\"ll\":null,\"ents\":[],\"fehler\":");
json::string(&mut s, msg);
s.push('}');
s
}
@@ -0,0 +1,302 @@
//! Hand-level tests: the whole E-step against a naive reference with explicit loops.
use crate::hand::*;
use crate::json;
use crate::karten::{bit, kombi_nr, score, tafeln, tests::c, NC};
use crate::modell::Params;
use crate::staerke::tests::river_brute;
fn params() -> Params {
Params::aus_text(&crate::synth::params_text(7)).unwrap()
}
fn ent(st: u8, fein: i64, erl: [u8; 6], o: [f64; 6], zug: u8) -> Ent {
Ent { st, codes: [fein, 100 + fein / 4, 200 + fein / 15], erlaubt: erl, o, zug }
}
fn brett() -> Vec<u8> {
"2c 7d 9h Js Ac".split_whitespace().map(c).collect()
}
fn hole(a: &str, b: &str) -> [u8; 2] {
[c(a), c(b)]
}
/// Three players: 0 shows, 1 mucks against player 0's cards, 2 folds preflop and has no evidence.
fn drei_spieler() -> Hand {
let o = [0.0, 0.1, -0.1, 0.0, 0.2, 0.0];
let alle = [1, 1, 1, 1, 0, 1];
Hand {
id: "t1".into(),
bb: 0.02,
brett: brett(),
spieler: vec![
Spieler {
platz: 0,
typen: vec![(1, 0.7), (4, 0.2), (2, 0.1)],
gezeigt: Some(hole("Ah", "Kd")),
muck: None,
ents: vec![ent(0, 3, alle, o, 3), ent(3, 17, [1, 1, 1, 0, 0, 0], [0.0; 6], 2)],
},
Spieler {
platz: 1,
typen: vec![(0, 0.5), (3, 0.5)],
gezeigt: None,
muck: Some(hole("Ah", "Kd")),
ents: vec![ent(0, 5, alle, [0.0; 6], 1), ent(3, 9, [1, 1, 0, 0, 0, 0], o, 1)],
},
Spieler { platz: 2, typen: vec![(5, 1.0)], gezeigt: None, muck: None, ents: vec![ent(0, 30, alle, [0.0; 6], 0)] },
],
}
}
type NaivTyp = (i32, f64, Vec<[(f64, f64); 20]>);
/// Naive reference: explicit loops, shares only the evaluator and the brute-force strength with the implementation.
fn naiv(p: &Params, hand: &Hand, si: usize, opt: &Optionen) -> (f64, Vec<NaivTyp>) {
let t = tafeln();
let sp = &hand.spieler[si];
let mut weg: Vec<u8> = hand.brett.clone();
for (j, o) in hand.spieler.iter().enumerate() {
if j != si {
if let Some(g) = o.gezeigt {
weg.extend_from_slice(&g);
}
}
}
let live: Vec<bool> = t.paar.iter().map(|&(a, b)| !weg.contains(&a) && !weg.contains(&b)).collect();
let n_live = live.iter().filter(|&&x| x).count() as f64;
let bb: u64 = hand.brett.iter().map(|&x| bit(x)).fold(0, |a, b| a | b);
let evid: Vec<bool> = (0..NC)
.map(|h| {
if let Some(g) = sp.gezeigt {
return h == kombi_nr(g[0], g[1]);
}
if let Some(m) = sp.muck {
let (a, b) = t.paar[h];
return score(bb | bit(a) | bit(b)) < score(bb | bit(m[0]) | bit(m[1]));
}
true
})
.collect();
let vf = p.vorflop.as_ref().unwrap();
let streng = |st: u8| -> Vec<f64> {
match st {
0 => (0..NC).map(|h| vf[t.klasse[h] as usize]).collect(),
3 => river_brute(&hand.brett),
_ => unreachable!(),
}
};
let typen = typen_vorbereiten(&sp.typen, opt.max_typen);
let mut roh: Vec<(i32, f64, Vec<[(f64, f64); 20]>, f64)> = Vec::new();
for &(ty, tw) in &typen {
let mut w: Vec<f64> = live.iter().map(|&l| if l { 1.0 } else { 0.0 }).collect();
let mut qs: Vec<Vec<f64>> = Vec::new();
for e in &sp.ents {
let s = streng(e.st);
let mut idx: Vec<usize> = (0..NC).filter(|&h| live[h]).collect();
idx.sort_by(|&a, &b| s[a].partial_cmp(&s[b]).unwrap().then(a.cmp(&b)));
let tot: f64 = idx.iter().map(|&h| w[h]).sum();
let mut q = vec![0.0; NC];
let mut cum = 0.0;
for &h in &idx {
q[h] = (cum + w[h] / 2.0) / tot;
cum += w[h];
}
let al = p.alpha_fuer(ty, e.codes);
for &h in &idx {
let knots = [0.0, 0.25, 0.5, 0.75, 1.0];
let mut u = [f64::NEG_INFINITY; 6];
for a in 0..6 {
if e.erlaubt[a] == 0 {
continue;
}
let mut x = al[a] + e.o[a];
if a > 0 {
for k in 0..5 {
let b = (1.0 - (q[h] - knots[k]).abs() * 4.0).max(0.0);
x += p.beta[(e.st as usize * 6 + a) * 5 + k] * b;
}
}
u[a] = x;
}
let z: f64 = u.iter().filter(|x| x.is_finite()).map(|x| x.exp()).sum();
let pr = if e.erlaubt[e.zug as usize] == 0 { 0.0 } else { u[e.zug as usize].exp() / z };
w[h] *= pr;
}
qs.push(q);
}
let post: Vec<f64> = (0..NC).map(|h| if live[h] && evid[h] { w[h] } else { 0.0 }).collect();
let total: f64 = post.iter().sum();
let mut bins = vec![[(0.0, 0.0); 20]; sp.ents.len()];
for d in 0..sp.ents.len() {
for h in 0..NC {
if post[h] > 0.0 {
let b = ((qs[d][h] * 20.0).floor() as usize).min(19);
bins[d][b].0 += post[h];
bins[d][b].1 += post[h] * qs[d][h];
}
}
}
roh.push((ty, tw, bins, tw * total / n_live));
}
let grand: f64 = roh.iter().map(|x| x.3).sum();
let out = roh
.into_iter()
.map(|(ty, tw, bins, joint)| {
let b2 = bins
.iter()
.map(|bd| {
let mut o = [(0.0, 0.0); 20];
for b in 0..20 {
let (w, qw) = bd[b];
o[b] = (w * tw / n_live / grand, if w > 0.0 { qw / w } else { (b as f64 + 0.5) / 20.0 });
}
o
})
.collect();
(ty, joint / grand, b2)
})
.collect();
(grand.ln(), out)
}
#[test]
fn matches_naive_reference_incl_shown_and_muck() {
let p = params();
let hand = drei_spieler();
let opt = Optionen { mischung: 0.0, max_typen: 3 };
let aus = estep_hand(&p, &opt, &hand, &mut Werkzeug::new()).unwrap();
let mut ll = 0.0;
for si in 0..3 {
let (l, typen) = naiv(&p, &hand, si, &opt);
ll += l;
for (ty, post, bins) in typen {
for (d, bd) in bins.iter().enumerate() {
let e = aus.ents.iter().find(|e| e.platz == si as i64 && e.d == d && e.typ == ty).expect("entry");
assert!((e.typ_post - post).abs() < 1e-12);
for b in 0..20 {
assert!((e.bins[b].0 - bd[b].0).abs() < 1e-12, "p{} d{} t{} bin{}: {} vs {}", si, d, ty, b, e.bins[b].0, bd[b].0);
assert!((e.bins[b].1 - bd[b].1).abs() < 1e-12);
}
}
}
}
assert!((aus.ll.unwrap() - ll).abs() < 1e-11, "{} vs {}", aus.ll.unwrap(), ll);
}
#[test]
fn bins_sum_to_one_per_decision_over_all_types() {
let p = params();
let aus = estep_hand(&p, &Optionen::default(), &drei_spieler(), &mut Werkzeug::new()).unwrap();
for platz in 0..3i64 {
let nd = if platz == 2 { 1 } else { 2 };
for d in 0..nd {
let s: f64 = aus.ents.iter().filter(|e| e.platz == platz && e.d == d).flat_map(|e| e.bins.iter().map(|b| b.0)).sum();
assert!((s - 1.0).abs() < 1e-12, "platz {} d {}: {}", platz, d, s);
let tp: f64 = aus.ents.iter().filter(|e| e.platz == platz && e.d == d).map(|e| e.typ_post).sum();
assert!((tp - 1.0).abs() < 1e-12);
}
}
}
#[test]
fn shown_player_posterior_is_one_combo() {
let p = params();
let aus = estep_hand(&p, &Optionen::default(), &drei_spieler(), &mut Werkzeug::new()).unwrap();
for e in aus.ents.iter().filter(|e| e.platz == 0) {
assert_eq!(e.bins.iter().filter(|b| b.0 > 0.0).count(), 1);
}
}
#[test]
fn evidence_without_decisions_counts_live_combos() {
// no decisions: ll = ln(P(evidence)) = ln(#consistent combos / #live combos)
let p = params();
let brett = brett();
let sieger = hole("Ah", "Kd");
let mk = |gez: Option<[u8; 2]>, muck: Option<[u8; 2]>| Hand {
id: "e".into(),
bb: 0.02,
brett: brett.clone(),
spieler: vec![
Spieler { platz: 0, typen: vec![(0, 1.0)], gezeigt: Some(sieger), muck: None, ents: vec![] },
Spieler { platz: 1, typen: vec![(0, 1.0)], gezeigt: gez, muck, ents: vec![] },
],
};
// player 0 shows: his live set is C(47,2) = 1081 (board out), P = 1/1081. Player 1 without evidence adds 0.
let a = estep_hand(&p, &Optionen::default(), &mk(None, None), &mut Werkzeug::new()).unwrap();
assert!((a.ll.unwrap() + (1081.0f64).ln()).abs() < 1e-12);
// player 1 mucks against AhKd: his live set is C(45,2) = 990 (board and the shown cards out), consistent = those that lose
let bb: u64 = brett.iter().map(|&x| bit(x)).fold(0, |a, b| a | b);
let gegen = score(bb | bit(sieger[0]) | bit(sieger[1]));
let t = tafeln();
let verlierer = (0..NC)
.filter(|&h| {
let (x, y) = t.paar[h];
let w = [x, y, brett[0], brett[1], brett[2], brett[3], brett[4], sieger[0], sieger[1]];
let doppelt = (0..w.len()).any(|i| (i + 1..w.len()).any(|j| w[i] == w[j]));
!doppelt && score(bb | bit(x) | bit(y)) < gegen
})
.count() as f64;
assert!(verlierer > 100.0 && verlierer < 990.0);
let m = estep_hand(&p, &Optionen::default(), &mk(None, Some(sieger)), &mut Werkzeug::new()).unwrap();
assert!((m.ll.unwrap() - (-(1081.0f64).ln() + (verlierer / 990.0).ln())).abs() < 1e-12, "{} {}", m.ll.unwrap(), verlierer);
// a tie does not count as losing: the board is a royal flush, everybody ties with the shown hand
let mut h2 = mk(None, Some(hole("2c", "3c")));
h2.brett = "Ah Kh Qh Jh Th".split_whitespace().map(c).collect();
h2.spieler[0].gezeigt = Some(hole("2c", "3c"));
let z = estep_hand(&p, &Optionen::default(), &h2, &mut Werkzeug::new()).unwrap();
assert!(z.ll.is_none(), "nobody loses: likelihood 0");
assert_eq!(z.nullspieler, vec![1]);
}
#[test]
fn type_list_truncated_normalised_and_defaulted() {
let v = typen_vorbereiten(&[(1, 0.1), (2, 0.4), (3, 0.3), (4, 0.2)], 3);
assert_eq!(v.iter().map(|x| x.0).collect::<Vec<_>>(), vec![2, 3, 4]);
assert!((v.iter().map(|x| x.1).sum::<f64>() - 1.0).abs() < 1e-15);
assert!((v[0].1 - 0.4 / 0.9).abs() < 1e-15);
assert_eq!(typen_vorbereiten(&[], 3), vec![(-1, 1.0)]);
}
#[test]
fn preflop_without_table_is_an_error_not_a_guess() {
let mut p = params();
p.vorflop = None;
assert!(estep_hand(&p, &Optionen::default(), &drei_spieler(), &mut Werkzeug::new()).is_err());
}
#[test]
fn json_in_and_out_round_trip() {
let line = r#"{"h":"abc","tag":"2026-01-01","bb":0.02,"brett":[1,5,9,40,44],"spieler":[
{"platz":0,"typen":[[0,0.6],[3,0.4]],"gezeigt":null,"muck":null,"ents":[{"st":0,"codes":[3,100,200],"erlaubt":[1,1,1,0,0,0],"o":[0,0,0,0,0,0],"zug":1},{"st":3,"codes":[4,101,201],"erlaubt":[0,1,1,1,0,0],"o":[0,0.5,0,0,0,0],"zug":2}]},
{"platz":1,"typen":[],"gezeigt":[10,20],"muck":null,"ents":[]}]}"#;
let h = Hand::from_json(&json::parse(line).unwrap()).unwrap();
assert_eq!(h.spieler.len(), 2);
assert_eq!(h.spieler[1].gezeigt, Some([10, 20]));
let aus = estep_hand(&params(), &Optionen::default(), &h, &mut Werkzeug::new()).unwrap();
let back = json::parse(&aus.to_json()).unwrap();
assert_eq!(back.get("h").unwrap().str(), Some("abc"));
assert!(back.get("ll").unwrap().f64().unwrap().is_finite());
let e = back.get("ents").unwrap().arr().unwrap();
assert_eq!(e.len(), aus.ents.len());
assert_eq!(e[0].get("bins").unwrap().arr().unwrap().len(), 20);
}
#[test]
fn flop_and_turn_decisions_run() {
// street 1 and 2 need the board prefix: a decision on the turn with a 3-card board must fail loudly
let p = params();
let mut h = drei_spieler();
h.brett = "2c 7d 9h".split_whitespace().map(c).collect();
h.spieler[0].gezeigt = None;
h.spieler[1].muck = None;
for s in h.spieler.iter_mut() {
s.ents = vec![ent(0, 3, [1, 1, 1, 0, 0, 0], [0.0; 6], 1), ent(1, 4, [1, 1, 1, 0, 0, 0], [0.0; 6], 2)];
}
let a = estep_hand(&p, &Optionen::default(), &h, &mut Werkzeug::new()).unwrap();
assert!(a.ll.unwrap().is_finite());
h.spieler[0].ents.push(ent(2, 4, [1, 1, 1, 0, 0, 0], [0.0; 6], 1));
assert!(estep_hand(&p, &Optionen::default(), &h, &mut Werkzeug::new()).is_err());
}
@@ -0,0 +1,285 @@
//! Minimal JSON reader and writer (std only), enough for the formats in ENTWURF section 4.
use std::fmt::Write;
#[derive(Debug, Clone, PartialEq)]
pub enum J {
Null,
Bool(bool),
Num(f64),
Str(String),
Arr(Vec<J>),
Obj(Vec<(String, J)>),
}
impl J {
pub fn get(&self, key: &str) -> Option<&J> {
match self {
J::Obj(v) => v.iter().find(|(k, _)| k == key).map(|(_, x)| x),
_ => None,
}
}
pub fn f64(&self) -> Option<f64> {
match self {
J::Num(x) => Some(*x),
J::Bool(b) => Some(*b as u8 as f64),
_ => None,
}
}
pub fn i64(&self) -> Option<i64> {
self.f64().and_then(|x| if x.fract() == 0.0 && x.abs() < 9e15 { Some(x as i64) } else { None })
}
pub fn str(&self) -> Option<&str> {
match self {
J::Str(s) => Some(s),
_ => None,
}
}
pub fn arr(&self) -> Option<&[J]> {
match self {
J::Arr(v) => Some(v),
_ => None,
}
}
pub fn is_null(&self) -> bool {
matches!(self, J::Null)
}
}
pub fn parse(text: &str) -> Result<J, String> {
let mut p = Parser { s: text.as_bytes(), i: 0 };
p.ws();
let v = p.value()?;
p.ws();
if p.i != p.s.len() {
return Err(format!("trailing characters at byte {}", p.i));
}
Ok(v)
}
struct Parser<'a> {
s: &'a [u8],
i: usize,
}
impl<'a> Parser<'a> {
fn ws(&mut self) {
while self.i < self.s.len() && matches!(self.s[self.i], b' ' | b'\t' | b'\n' | b'\r') {
self.i += 1;
}
}
fn err<T>(&self, msg: &str) -> Result<T, String> {
Err(format!("{} at byte {}", msg, self.i))
}
fn lit(&mut self, word: &str, v: J) -> Result<J, String> {
if self.s[self.i..].starts_with(word.as_bytes()) {
self.i += word.len();
Ok(v)
} else {
self.err("bad literal")
}
}
fn value(&mut self) -> Result<J, String> {
if self.i >= self.s.len() {
return self.err("unexpected end");
}
match self.s[self.i] {
b'n' => self.lit("null", J::Null),
b't' => self.lit("true", J::Bool(true)),
b'f' => self.lit("false", J::Bool(false)),
b'"' => Ok(J::Str(self.string()?)),
b'[' => {
self.i += 1;
let mut v = Vec::new();
self.ws();
if self.i < self.s.len() && self.s[self.i] == b']' {
self.i += 1;
return Ok(J::Arr(v));
}
loop {
self.ws();
v.push(self.value()?);
self.ws();
match self.s.get(self.i) {
Some(b',') => self.i += 1,
Some(b']') => {
self.i += 1;
return Ok(J::Arr(v));
}
_ => return self.err("expected , or ]"),
}
}
}
b'{' => {
self.i += 1;
let mut v = Vec::new();
self.ws();
if self.i < self.s.len() && self.s[self.i] == b'}' {
self.i += 1;
return Ok(J::Obj(v));
}
loop {
self.ws();
if self.s.get(self.i) != Some(&b'"') {
return self.err("expected key");
}
let k = self.string()?;
self.ws();
if self.s.get(self.i) != Some(&b':') {
return self.err("expected :");
}
self.i += 1;
self.ws();
let x = self.value()?;
v.push((k, x));
self.ws();
match self.s.get(self.i) {
Some(b',') => self.i += 1,
Some(b'}') => {
self.i += 1;
return Ok(J::Obj(v));
}
_ => return self.err("expected , or }"),
}
}
}
_ => self.number(),
}
}
fn number(&mut self) -> Result<J, String> {
let st = self.i;
// Python's json module writes these for non-finite floats
for (w, x) in [("NaN", f64::NAN), ("Infinity", f64::INFINITY), ("-Infinity", f64::NEG_INFINITY)] {
if self.s[st..].starts_with(w.as_bytes()) {
self.i = st + w.len();
return Ok(J::Num(x));
}
}
while self.i < self.s.len() && matches!(self.s[self.i], b'-' | b'+' | b'.' | b'e' | b'E' | b'0'..=b'9') {
self.i += 1;
}
let t = std::str::from_utf8(&self.s[st..self.i]).map_err(|e| e.to_string())?;
match t.parse::<f64>() {
Ok(x) => Ok(J::Num(x)),
Err(_) => {
self.i = st;
self.err("bad number")
}
}
}
fn hex4(&mut self) -> Result<u32, String> {
if self.i + 4 > self.s.len() {
return self.err("short \\u escape");
}
let t = std::str::from_utf8(&self.s[self.i..self.i + 4]).map_err(|e| e.to_string())?;
let v = u32::from_str_radix(t, 16).map_err(|e| e.to_string())?;
self.i += 4;
Ok(v)
}
fn string(&mut self) -> Result<String, String> {
self.i += 1; // opening quote
let mut out: Vec<u8> = Vec::new();
loop {
let c = *self.s.get(self.i).ok_or_else(|| format!("unterminated string at byte {}", self.i))?;
self.i += 1;
match c {
b'"' => break,
b'\\' => {
let e = *self.s.get(self.i).ok_or("bad escape")?;
self.i += 1;
let ch = match e {
b'"' => '"',
b'\\' => '\\',
b'/' => '/',
b'b' => '\u{8}',
b'f' => '\u{c}',
b'n' => '\n',
b'r' => '\r',
b't' => '\t',
b'u' => {
let mut u = self.hex4()?;
if (0xD800..0xDC00).contains(&u) && self.s[self.i..].starts_with(b"\\u") {
self.i += 2;
let lo = self.hex4()?;
u = 0x10000 + ((u - 0xD800) << 10) + (lo.wrapping_sub(0xDC00) & 0x3FF);
}
char::from_u32(u).unwrap_or('\u{FFFD}')
}
_ => return self.err("bad escape"),
};
let mut b = [0u8; 4];
out.extend_from_slice(ch.encode_utf8(&mut b).as_bytes());
}
_ => out.push(c),
}
}
String::from_utf8(out).map_err(|e| e.to_string())
}
}
/// Writes a finite f64 so that it parses back to the same value; non-finite becomes `null`.
pub fn num(out: &mut String, x: f64) {
if x.is_finite() {
let _ = write!(out, "{:?}", x);
} else {
out.push_str("null");
}
}
pub fn string(out: &mut String, s: &str) {
out.push('"');
for c in s.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
c if (c as u32) < 0x20 => {
let _ = write!(out, "\\u{:04x}", c as u32);
}
c => out.push(c),
}
}
out.push('"');
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_nested_structures() {
let v = parse(r#" {"a":[1,2.5,-3e-2,null,true],"b":{"c":"x\nyé"},"d":[]} "#).unwrap();
assert_eq!(v.get("a").unwrap().arr().unwrap().len(), 5);
assert_eq!(v.get("a").unwrap().arr().unwrap()[2].f64(), Some(-0.03));
assert_eq!(v.get("b").unwrap().get("c").unwrap().str(), Some("x\nyé"));
assert!(v.get("d").unwrap().arr().unwrap().is_empty());
}
#[test]
fn rejects_garbage() {
assert!(parse("{\"a\":}").is_err());
assert!(parse("[1,2").is_err());
assert!(parse("1 2").is_err());
}
#[test]
fn numbers_round_trip() {
for x in [0.1, 1.0, -2.5e-300, 123456789.123456789, 1e22, 0.30000000000000004] {
let mut s = String::new();
num(&mut s, x);
assert_eq!(parse(&s).unwrap().f64(), Some(x), "{}", s);
}
let mut s = String::new();
num(&mut s, f64::NEG_INFINITY);
assert_eq!(s, "null");
}
#[test]
fn strings_round_trip() {
let mut s = String::new();
string(&mut s, "a\"b\\c\n\u{1}é");
assert_eq!(parse(&s).unwrap().str(), Some("a\"b\\c\n\u{1}é"));
}
}
@@ -0,0 +1,213 @@
//! Cards, the 1,326 hole-card combos, and the 7-card evaluator (copied from entscheiden/motor/src/wert.rs).
//! Card = rank * 4 + suit (ranks "23456789TJQKA", suits "cdhs"), as in welt_v4/staerke.py.
use std::sync::OnceLock;
pub const NC: usize = 1326;
pub const RAENGE: &[u8; 13] = b"23456789TJQKA";
pub struct Tafeln {
/// combo number -> (a, b) with a < b, ordered like the Python `KOMBI` list
pub paar: Vec<(u8, u8)>,
/// (a, b) -> combo number, both orders
pub nr: [[u16; 52]; 52],
/// evaluator lane bits of the two hole cards
pub bits: Vec<u64>,
/// bit per card id (1 << c), for overlap tests
pub maske: Vec<u64>,
/// preflop class index per combo (index into `klassen_namen`)
pub klasse: Vec<u8>,
pub klassen_namen: Vec<String>,
}
pub fn tafeln() -> &'static Tafeln {
static T: OnceLock<Tafeln> = OnceLock::new();
T.get_or_init(|| {
let mut paar = Vec::with_capacity(NC);
let mut nr = [[0u16; 52]; 52];
for a in 0..52u8 {
for b in a + 1..52 {
nr[a as usize][b as usize] = paar.len() as u16;
nr[b as usize][a as usize] = paar.len() as u16;
paar.push((a, b));
}
}
let bits = paar.iter().map(|&(a, b)| bit(a) | bit(b)).collect();
let maske = paar.iter().map(|&(a, b)| (1u64 << a) | (1u64 << b)).collect();
let mut namen: Vec<String> = Vec::new();
let klasse = paar
.iter()
.map(|&(a, b)| {
let n = klasse_name(a, b);
match namen.iter().position(|x| *x == n) {
Some(i) => i as u8,
None => {
namen.push(n);
(namen.len() - 1) as u8
}
}
})
.collect();
Tafeln { paar, nr, bits, maske, klasse, klassen_namen: namen }
})
}
pub fn kombi_nr(a: u8, b: u8) -> usize {
tafeln().nr[a as usize][b as usize] as usize
}
/// Starting-hand class such as "AKs", "T9o", "77" (as `klasse` in staerke.py).
pub fn klasse_name(a: u8, b: u8) -> String {
let (ra, rb) = (a >> 2, b >> 2);
let (hi, lo) = (ra.max(rb), ra.min(rb));
let mut s = String::new();
s.push(RAENGE[hi as usize] as char);
s.push(RAENGE[lo as usize] as char);
if hi != lo {
s.push(if (a & 3) == (b & 3) { 's' } else { 'o' });
}
s
}
#[inline]
pub fn bit(c: u8) -> u64 {
1u64 << (16 * (c & 3) as u32 + (c >> 2) as u32)
}
pub fn board_bits(board: &[u8]) -> u64 {
board.iter().fold(0, |m, &c| m | bit(c))
}
pub fn board_maske(board: &[u8]) -> u64 {
board.iter().fold(0, |m, &c| m | (1u64 << c))
}
const LANE: u64 = 0x1FFF;
/// The highest straight in a 13-bit rank set: index of its top rank (3 = five-high wheel), or `None`.
fn straight_top(ranks: u32) -> Option<u32> {
let b = (ranks << 1) | ((ranks >> 12) & 1);
let run = b & (b >> 1) & (b >> 2) & (b >> 3) & (b >> 4);
(run != 0).then(|| 31 - run.leading_zeros() + 4 - 1)
}
fn top(mut bits: u32, n: u32) -> u32 {
while bits.count_ones() > n {
bits &= bits - 1;
}
bits
}
fn high(bits: u32) -> u32 {
31 - bits.leading_zeros()
}
const fn cat(c: u32) -> u32 {
c << 24
}
/// Score of the best five of the 5-7 cards in lane-bit mask `m`; higher is better, equal is a split.
pub fn score(m: u64) -> u32 {
let s = [(m & LANE) as u32, ((m >> 16) & LANE) as u32, ((m >> 32) & LANE) as u32, ((m >> 48) & LANE) as u32];
for lane in s {
if lane.count_ones() >= 5 {
return match straight_top(lane) {
Some(t) => cat(8) | t,
None => cat(5) | top(lane, 5),
};
}
}
let ranks = s[0] | s[1] | s[2] | s[3];
let four = s[0] & s[1] & s[2] & s[3];
if four != 0 {
let q = high(four);
return cat(7) | (q << 13) | top(ranks & !(1 << q), 1);
}
let three = (s[0] & s[1] & s[2]) | (s[0] & s[1] & s[3]) | (s[0] & s[2] & s[3]) | (s[1] & s[2] & s[3]);
let two = (s[0] & s[1]) | (s[0] & s[2]) | (s[0] & s[3]) | (s[1] & s[2]) | (s[1] & s[3]) | (s[2] & s[3]);
if three != 0 {
let t = high(three);
let pair = two & !(1 << t);
if pair != 0 {
return cat(6) | (t << 13) | (1 << high(pair));
}
}
if let Some(t) = straight_top(ranks) {
return cat(4) | t;
}
if three != 0 {
let t = high(three);
return cat(3) | (t << 13) | top(ranks & !(1 << t), 2);
}
if two.count_ones() >= 2 {
let p = top(two, 2);
return cat(2) | (p_code(p) << 13) | top(ranks & !p, 1);
}
if two != 0 {
let p = high(two);
return cat(1) | (p << 13) | top(ranks & !(1 << p), 3);
}
top(ranks, 5)
}
fn p_code(p: u32) -> u32 {
let hi = high(p);
let lo = high(p & !(1 << hi));
hi * 13 + lo
}
#[cfg(test)]
pub mod tests {
use super::*;
pub fn c(s: &str) -> u8 {
let b = s.as_bytes();
(RAENGE.iter().position(|&r| r == b[0]).unwrap() * 4 + b"cdhs".iter().position(|&f| f == b[1]).unwrap()) as u8
}
fn sc(cards: &[&str]) -> u32 {
score(cards.iter().fold(0, |m, s| m | bit(c(s))))
}
#[test]
fn combo_numbering_matches_lexicographic_list() {
assert_eq!(tafeln().paar.len(), NC);
assert_eq!(kombi_nr(0, 1), 0);
assert_eq!(kombi_nr(1, 0), 0);
assert_eq!(kombi_nr(0, 51), 50);
assert_eq!(kombi_nr(1, 2), 51);
assert_eq!(kombi_nr(50, 51), NC - 1);
}
#[test]
fn class_names() {
assert_eq!(klasse_name(c("Ah"), c("Kh")), "AKs");
assert_eq!(klasse_name(c("Kd"), c("Ah")), "AKo");
assert_eq!(klasse_name(c("7d"), c("7s")), "77");
assert_eq!(tafeln().klassen_namen.len(), 169);
}
#[test]
fn categories_are_ordered() {
let high = sc(&["Ah", "Kd", "9c", "7s", "4h", "3d", "2c"]);
let pair = sc(&["2h", "2d", "9c", "7s", "4h", "3d", "Kc"]);
let two = sc(&["2h", "2d", "9c", "9s", "4h", "3d", "Kc"]);
let trips = sc(&["2h", "2d", "2c", "9s", "4h", "Jd", "Kc"]);
let straight = sc(&["Ah", "2d", "3c", "4s", "5h", "Jd", "Kc"]);
let flush = sc(&["2h", "9h", "3h", "4h", "Kh", "Jd", "Kc"]);
let full = sc(&["2h", "2d", "2c", "9s", "9h", "Jd", "Kc"]);
let quads = sc(&["2h", "2d", "2c", "2s", "9h", "Jd", "Kc"]);
let sflush = sc(&["5h", "6h", "7h", "8h", "9h", "Jd", "Kc"]);
let v = [high, pair, two, trips, straight, flush, full, quads, sflush];
for w in v.windows(2) {
assert!(w[0] < w[1], "{:?}", v);
}
}
#[test]
fn wheel_loses_to_six_high_and_board_plays_ties() {
assert!(sc(&["Ah", "2d", "3c", "4s", "5h", "Jd", "Kc"]) < sc(&["2h", "3d", "4c", "5s", "6h", "Jd", "Kc"]));
let a = sc(&["Ah", "Kd", "Qc", "Js", "9h", "2d", "3c"]);
let b = sc(&["Ah", "Kd", "Qc", "Js", "9h", "4d", "5c"]);
assert_eq!(a, b);
}
}
@@ -0,0 +1,314 @@
//! The inner kernel: ONE player, ONE type, ONE hand. A pure function over flat arrays (no allocation
//! inside, no I/O, no hash maps), so it can be ported to a GPU kernel one-to-one.
//!
//! Forward pass over the 1,326 combos (only the `live` ones carry mass):
//! w[h] = 1 for live h
//! for each decision d (in order):
//! q_d(h) = midpoint quantile of h in the forward range w, combos ordered by strength `ordnung[st_d]`
//! w[h] *= P(zug_d | d, h) with u_a = ufix[d][a] + sum_k beta[st_d][a][k] * B_k(q_d(h)) (a >= 1)
//! post[h] = w[h] * evid[h] (showdown evidence, 0/1, NOT part of the forward range)
//! gesamt = sum_h post[h] (likelihood of this player's observations under this type, prior mass 1 per live combo)
//! bins[d][b] = sum of post[h] and post[h]*q_d(h) over h with floor(20*q_d(h)) == b
//! The caller multiplies by the type weight and the prior 1/N and normalises across types.
pub const NC: usize = 1326;
pub const NA: usize = 6;
pub const NK: usize = 5;
pub const NQ: usize = 20;
pub const NS: usize = 4;
/// Inputs of the kernel. All slices are flat; `ufix` and `erlaubt` have `nd * NA` entries,
/// `beta` has `NS * NA * NK` (beta[s][0][k] must be 0, the kernel does not read it).
pub struct KernEin<'a> {
pub nd: usize,
pub st: &'a [u8],
pub zug: &'a [u8],
pub erlaubt: &'a [u8],
/// alpha + o + lambda shift per decision and action (everything that does not depend on the hand)
pub ufix: &'a [f64],
pub beta: &'a [f64],
/// live combos (sorted ascending), these carry prior mass 1
pub live: &'a [u16],
/// per street: the live combos sorted by (strength, combo number); only streets that occur in `st` are read
pub ordnung: [&'a [u16]; NS],
/// showdown evidence per combo (0 or 1)
pub evid: &'a [f64],
/// mixing weight eps of the node frequency (0 = off)
pub mischung: f64,
}
/// Scratch and output of the kernel; buffers are reused between calls.
pub struct KernAus {
pub gesamt: f64,
/// nd * NQ: sum of post
pub bin_w: Vec<f64>,
/// nd * NQ: sum of post * q
pub bin_qw: Vec<f64>,
/// forward weights, NC
pub w: Vec<f64>,
/// q per decision, nd * NC
pub q: Vec<f64>,
/// P(observed action) per combo, NC
pub p: Vec<f64>,
}
impl KernAus {
pub fn new() -> Self {
KernAus { gesamt: 0.0, bin_w: Vec::new(), bin_qw: Vec::new(), w: vec![0.0; NC], q: Vec::new(), p: vec![0.0; NC] }
}
}
impl Default for KernAus {
fn default() -> Self {
Self::new()
}
}
/// Hat basis on the knots 0, .25, .5, .75, 1: returns (first knot, weight of first, weight of next).
#[inline]
pub fn hut(q: f64) -> (usize, f64, f64) {
let x = q * 4.0;
let k = (x as usize).min(NK - 2);
let f = x - k as f64;
(k, 1.0 - f, f)
}
/// P(zug | d, h) for one combo: legal-masked softmax over the six actions. `beta_st` is beta[st] (NA*NK).
#[inline]
pub fn p_zug(ufix: &[f64], erlaubt: &[u8], zug: usize, beta_st: &[f64], q: f64) -> f64 {
if erlaubt[zug] == 0 {
return 0.0;
}
let (k, b0, b1) = hut(q);
let mut u = [0.0f64; NA];
let mut m = f64::NEG_INFINITY;
for a in 0..NA {
if erlaubt[a] == 0 {
continue;
}
let mut x = ufix[a];
if a > 0 {
let b = &beta_st[a * NK..a * NK + NK];
x += b[k] * b0 + b[k + 1] * b1;
}
u[a] = x;
if x > m {
m = x;
}
}
let mut z = 0.0;
for a in 0..NA {
if erlaubt[a] != 0 {
z += (u[a] - m).exp();
}
}
(u[zug] - m).exp() / z
}
pub fn vorwaerts(e: &KernEin, aus: &mut KernAus) {
let nd = e.nd;
aus.bin_w.clear();
aus.bin_w.resize(nd * NQ, 0.0);
aus.bin_qw.clear();
aus.bin_qw.resize(nd * NQ, 0.0);
aus.q.clear();
aus.q.resize(nd * NC, 0.0);
aus.w.iter_mut().for_each(|x| *x = 0.0);
for &h in e.live {
aus.w[h as usize] = 1.0;
}
for d in 0..nd {
let st = e.st[d] as usize;
let ord = e.ordnung[st];
let mut tot = 0.0;
for &h in ord {
tot += aus.w[h as usize];
}
let qd = &mut aus.q[d * NC..(d + 1) * NC];
let mut cum = 0.0;
for &h in ord {
let wh = aus.w[h as usize];
qd[h as usize] = if tot > 0.0 { (cum + 0.5 * wh) / tot } else { 0.5 };
cum += wh;
}
let uf = &e.ufix[d * NA..(d + 1) * NA];
let er = &e.erlaubt[d * NA..(d + 1) * NA];
let bs = &e.beta[st * NA * NK..(st + 1) * NA * NK];
let zug = e.zug[d] as usize;
for &h in e.live {
aus.p[h as usize] = p_zug(uf, er, zug, bs, qd[h as usize]);
}
if e.mischung > 0.0 {
let (mut sw, mut sp) = (0.0, 0.0);
for &h in e.live {
sw += aus.w[h as usize];
sp += aus.w[h as usize] * aus.p[h as usize];
}
let knoten = if sw > 0.0 { sp / sw } else { 0.0 };
for &h in e.live {
let x = (1.0 - e.mischung) * aus.p[h as usize] + e.mischung * knoten;
aus.w[h as usize] *= x;
}
} else {
for &h in e.live {
aus.w[h as usize] *= aus.p[h as usize];
}
}
}
let mut gesamt = 0.0;
for &h in e.live {
let post = aus.w[h as usize] * e.evid[h as usize];
if post == 0.0 {
continue;
}
gesamt += post;
for d in 0..nd {
let q = aus.q[d * NC + h as usize];
let b = ((q * NQ as f64) as usize).min(NQ - 1);
aus.bin_w[d * NQ + b] += post;
aus.bin_qw[d * NQ + b] += post * q;
}
}
aus.gesamt = gesamt;
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn hat_basis_partitions_unity_and_hits_knots() {
for (q, k, b0, b1) in [(0.0, 0, 1.0, 0.0), (0.25, 1, 1.0, 0.0), (0.125, 0, 0.5, 0.5), (1.0, 3, 0.0, 1.0), (0.9, 3, 0.4, 0.6)] {
let (kk, x0, x1) = hut(q);
assert_eq!(kk, k, "q={}", q);
assert!((x0 - b0).abs() < 1e-12 && (x1 - b1).abs() < 1e-12, "q={} {:?}", q, (kk, x0, x1));
assert!((x0 + x1 - 1.0).abs() < 1e-15);
}
}
#[test]
fn softmax_respects_the_legal_mask() {
let uf = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0];
let beta = vec![0.0; NA * NK];
// only fold and call legal
let er = [1u8, 1, 0, 0, 0, 0];
let p1 = p_zug(&uf, &er, 1, &beta, 0.3);
let p0 = p_zug(&uf, &er, 0, &beta, 0.3);
assert!((p1 - 1.0f64.exp() / (1.0 + 1.0f64.exp())).abs() < 1e-14);
assert!((p0 + p1 - 1.0).abs() < 1e-14);
assert_eq!(p_zug(&uf, &er, 3, &beta, 0.3), 0.0);
// all six legal: normalised
let er = [1u8; 6];
let s: f64 = (0..6).map(|a| p_zug(&uf, &er, a, &beta, 0.5)).sum();
assert!((s - 1.0).abs() < 1e-14);
}
#[test]
fn beta_shifts_the_logit_along_the_hat_basis() {
let uf = [0.0; 6];
let mut beta = vec![0.0; NA * NK];
beta[2 * NK + 4] = 6.0; // action 2, knot q=1
let er = [1u8; 6];
let lo = p_zug(&uf, &er, 2, &beta, 0.0);
let hi = p_zug(&uf, &er, 2, &beta, 1.0);
assert!((lo - 1.0 / 6.0).abs() < 1e-14);
assert!((hi - 6.0f64.exp() / (6.0f64.exp() + 5.0)).abs() < 1e-14);
}
/// Two combos with distinct strengths; one decision with a deterministic rule: Raise (action 2) is only legal
/// next to fold, and beta makes strong combos raise.
#[test]
fn midpoint_quantile_and_bins_on_a_toy_range() {
let live: Vec<u16> = vec![10, 20, 30, 40];
let ord: Vec<u16> = vec![30, 10, 40, 20]; // weak -> strong
let st = [1u8];
let zug = [2u8];
let er = [1u8, 0, 1, 0, 0, 0];
let uf = [0.0f64; 6];
let mut beta = vec![0.0; NS * NA * NK];
beta[1 * NA * NK + 2 * NK + 4] = 2.0;
let mut evid = vec![0.0; NC];
for &h in &live {
evid[h as usize] = 1.0;
}
let e = KernEin {
nd: 1,
st: &st,
zug: &zug,
erlaubt: &er,
ufix: &uf,
beta: &beta,
live: &live,
ordnung: [&[], &ord, &[], &[]],
evid: &evid,
mischung: 0.0,
};
let mut aus = KernAus::new();
vorwaerts(&e, &mut aus);
// equal forward mass 1 each: q = (i + 0.5) / 4 in strength order
for (i, &h) in ord.iter().enumerate() {
assert!((aus.q[h as usize] - (i as f64 + 0.5) / 4.0).abs() < 1e-15);
}
// likelihood = sum of P(raise | q); only knot 4 (q = 1) has a coefficient, its hat weight is max(0, 4q - 3)
let want: f64 = (0..4)
.map(|i| {
let q = (i as f64 + 0.5) / 4.0;
let u = 2.0 * (4.0 * q - 3.0).max(0.0);
u.exp() / (u.exp() + 1.0)
})
.sum();
assert!((aus.gesamt - want).abs() < 1e-14, "{} vs {}", aus.gesamt, want);
// bins: q = .125 .375 .625 .875 -> bins 2, 7, 12, 17; weights sum to gesamt
let nz: Vec<usize> = (0..NQ).filter(|&b| aus.bin_w[b] > 0.0).collect();
assert_eq!(nz, vec![2, 7, 12, 17]);
assert!((aus.bin_w.iter().sum::<f64>() - aus.gesamt).abs() < 1e-14);
assert!((aus.bin_qw[17] / aus.bin_w[17] - 0.875).abs() < 1e-14);
}
#[test]
fn second_decision_uses_the_forward_range_not_the_prior() {
// decision 1 (steep beta on the knots 0 and 4): P(raise) = ~0, .5, .5, ~1 for q = .125, .375, .625, .875.
// Decision 2 must see the narrowed range (masses ~0, .5, .5, 1; total 2), not the prior.
let live: Vec<u16> = vec![0, 1, 2, 3];
let ord: Vec<u16> = vec![0, 1, 2, 3];
let st = [1u8, 1];
let zug = [2u8, 2];
let er = [1u8, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0];
let uf = [0.0f64; 12];
let mut beta = vec![0.0; NS * NA * NK];
beta[1 * NA * NK + 2 * NK + 4] = 40.0; // raise nearly sure for q > ~0.9, nearly never below 0.75
beta[1 * NA * NK + 2 * NK] = -40.0;
let mut evid = vec![0.0; NC];
evid[..4].iter_mut().for_each(|x| *x = 1.0);
let e = KernEin { nd: 2, st: &st, zug: &zug, erlaubt: &er, ufix: &uf, beta: &beta, live: &live, ordnung: [&[], &ord, &[], &[]], evid: &evid, mischung: 0.0 };
let mut aus = KernAus::new();
vorwaerts(&e, &mut aus);
assert!((aus.q[3] - 0.875).abs() < 1e-12);
assert!((aus.q[NC + 3] - 0.75).abs() < 1e-8, "{}", aus.q[NC + 3]);
assert!((aus.q[NC + 1] - 0.125).abs() < 1e-8, "{}", aus.q[NC + 1]);
assert!((aus.q[NC + 2] - 0.375).abs() < 1e-8, "{}", aus.q[NC + 2]);
}
#[test]
fn mixing_keeps_zero_probability_actions_alive() {
// two combos, q = .25 and .75; the strong one raises (beta), the weak one practically never. Evidence only on the weak one.
let live: Vec<u16> = vec![0, 1];
let ord: Vec<u16> = vec![0, 1];
let st = [1u8];
let zug = [2u8];
let er = [1u8, 0, 1, 0, 0, 0];
let uf = [0.0f64; 6];
let mut beta = vec![0.0; NS * NA * NK];
beta[1 * NA * NK + 2 * NK + 1] = -60.0;
beta[1 * NA * NK + 2 * NK + 3] = 60.0;
let mut evid = vec![0.0; NC];
evid[0] = 1.0;
let mk = |eps| KernEin { nd: 1, st: &st, zug: &zug, erlaubt: &er, ufix: &uf, beta: &beta, live: &live, ordnung: [&[], &ord, &[], &[]], evid: &evid, mischung: eps };
let mut aus = KernAus::new();
vorwaerts(&mk(0.0), &mut aus);
assert!(aus.gesamt < 1e-20);
vorwaerts(&mk(0.01), &mut aus);
// node frequency of the raise in the range = (P0 + P1) / 2 ~ 0.5; mixed P0 = 0.99 * ~0 + 0.01 * 0.5
assert!((aus.gesamt - 0.005).abs() < 1e-9, "{}", aus.gesamt);
}
}
@@ -0,0 +1,191 @@
//! The run: read decision lines, E-step per hand on a few threads, write output lines in input order.
use crate::hand::{estep_hand, fehlerzeile, Hand, Optionen, Werkzeug};
use crate::json;
use crate::modell::{vorflop_tafel, Params};
use std::fs::{self, File, OpenOptions};
use std::io::{self, BufRead, BufReader, BufWriter, Write};
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::sync::Mutex;
use std::time::Instant;
pub struct LaufOpt {
pub haende: String,
pub params: String,
pub vorflop: Option<String>,
pub out: String,
pub faeden: usize,
pub nice: i32,
pub max: Option<usize>,
pub opt: Optionen,
}
#[derive(Debug, Default)]
pub struct Stat {
pub haende: usize,
pub fehler: usize,
pub cpu_ns: u64,
pub wall_s: f64,
}
#[repr(C)]
struct Zeitpunkt {
sek: i64,
nsek: i64,
}
extern "C" {
fn setpriority(which: i32, who: u32, prio: i32) -> i32;
fn clock_gettime(clk: i32, ts: *mut Zeitpunkt) -> i32;
}
#[cfg(target_os = "macos")]
const CLOCK_THREAD_CPUTIME_ID: i32 = 16;
#[cfg(not(target_os = "macos"))]
const CLOCK_THREAD_CPUTIME_ID: i32 = 3;
/// CPU time of the calling thread in ns (not wall time: a loaded machine does not distort it).
fn thread_cpu_ns() -> u64 {
let mut t = Zeitpunkt { sek: 0, nsek: 0 };
unsafe {
clock_gettime(CLOCK_THREAD_CPUTIME_ID, &mut t);
}
(t.sek as u64) * 1_000_000_000 + t.nsek as u64
}
/// Lower the priority of this process (PRIO_PROCESS = 0, who 0 = self).
pub fn nice(n: i32) {
if n > 0 {
unsafe {
setpriority(0, 0, n);
}
}
}
fn verarbeite(p: &Params, opt: &Optionen, zeile: &str, wz: &mut Werkzeug) -> (String, bool) {
let j = match json::parse(zeile) {
Ok(j) => j,
Err(e) => return (fehlerzeile("?", &format!("json: {}", e)), true),
};
let id = j.get("h").and_then(|x| x.str()).unwrap_or("?").to_string();
match Hand::from_json(&j).and_then(|h| estep_hand(p, opt, &h, wz)) {
Ok(a) => (a.to_json(), false),
Err(e) => (fehlerzeile(&id, &e), true),
}
}
/// Writer that refuses to overwrite: tmp file via create_new, renamed on finish.
pub enum Ziel {
Stdout(BufWriter<io::Stdout>),
Datei { w: BufWriter<File>, tmp: PathBuf, fin: PathBuf },
}
impl Ziel {
pub fn offnen(pfad: &str) -> Result<Ziel, String> {
if pfad == "-" {
return Ok(Ziel::Stdout(BufWriter::new(io::stdout())));
}
let fin = PathBuf::from(pfad);
if fin.exists() {
return Err(format!("refusing to overwrite existing {}", pfad));
}
let mut tmp = fin.clone().into_os_string();
tmp.push(".tmp");
let tmp = PathBuf::from(tmp);
let f = OpenOptions::new().write(true).create_new(true).open(&tmp).map_err(|e| format!("{}: {}", tmp.display(), e))?;
Ok(Ziel::Datei { w: BufWriter::new(f), tmp, fin })
}
pub fn schreibe(&mut self, s: &str) -> io::Result<()> {
let w: &mut dyn Write = match self {
Ziel::Stdout(w) => w,
Ziel::Datei { w, .. } => w,
};
w.write_all(s.as_bytes())?;
w.write_all(b"\n")
}
pub fn fertig(self) -> Result<(), String> {
match self {
Ziel::Stdout(mut w) => w.flush().map_err(|e| e.to_string()),
Ziel::Datei { mut w, tmp, fin } => {
w.flush().map_err(|e| e.to_string())?;
drop(w);
if fin.exists() {
return Err(format!("{} appeared during the run, result stays in {}", fin.display(), tmp.display()));
}
fs::rename(&tmp, &fin).map_err(|e| e.to_string())
}
}
}
}
pub fn lauf(o: &LaufOpt) -> Result<Stat, String> {
nice(o.nice);
let mut p = Params::aus_text(&fs::read_to_string(&o.params).map_err(|e| format!("{}: {}", o.params, e))?)?;
if let Some(vf) = &o.vorflop {
let j = json::parse(&fs::read_to_string(vf).map_err(|e| format!("{}: {}", vf, e))?)?;
p.vorflop = Some(vorflop_tafel(j.get("vorflop").unwrap_or(&j))?);
}
let eingabe: Box<dyn BufRead> = if o.haende == "-" {
Box::new(BufReader::with_capacity(1 << 20, io::stdin()))
} else {
Box::new(BufReader::with_capacity(1 << 20, File::open(&o.haende).map_err(|e| format!("{}: {}", o.haende, e))?))
};
let mut ziel = Ziel::offnen(&o.out)?;
let faeden = o.faeden.max(1);
let batch = faeden * 64;
let mut stat = Stat::default();
let cpu = AtomicU64::new(0);
let start = Instant::now();
let mut werkzeuge: Vec<Werkzeug> = (0..faeden).map(|_| Werkzeug::new()).collect();
let mut lines = eingabe.lines();
loop {
let mut zeilen: Vec<String> = Vec::with_capacity(batch);
while zeilen.len() < batch && o.max.map_or(true, |m| stat.haende + zeilen.len() < m) {
match lines.next() {
Some(l) => {
let l = l.map_err(|e| e.to_string())?;
if !l.trim().is_empty() {
zeilen.push(l);
}
}
None => break,
}
}
if zeilen.is_empty() {
break;
}
let aus: Vec<Mutex<(String, bool)>> = (0..zeilen.len()).map(|_| Mutex::new((String::new(), false))).collect();
let next = AtomicUsize::new(0);
std::thread::scope(|sc| {
for wz in werkzeuge.iter_mut() {
let (zeilen, aus, next, cpu, p, opt) = (&zeilen, &aus, &next, &cpu, &p, &o.opt);
sc.spawn(move || {
loop {
let i = next.fetch_add(1, Ordering::Relaxed);
if i >= zeilen.len() {
break;
}
let t0 = thread_cpu_ns();
let r = verarbeite(p, opt, &zeilen[i], wz);
cpu.fetch_add(thread_cpu_ns() - t0, Ordering::Relaxed);
*aus[i].lock().unwrap() = r;
}
});
}
});
for a in aus {
let (s, fehler) = a.into_inner().unwrap();
ziel.schreibe(&s).map_err(|e| e.to_string())?;
stat.haende += 1;
stat.fehler += fehler as usize;
}
if o.max.map_or(false, |m| stat.haende >= m) {
break;
}
}
ziel.fertig()?;
stat.cpu_ns = cpu.load(Ordering::Relaxed);
stat.wall_s = start.elapsed().as_secs_f64();
Ok(stat)
}
@@ -0,0 +1,12 @@
//! Welt v5 E-step (std only). See ../ENTWURF.md section 2 and 4.
pub mod hand;
#[cfg(test)]
mod hand_tests;
pub mod json;
pub mod karten;
pub mod kern;
pub mod lauf;
pub mod modell;
pub mod staerke;
pub mod synth;
pub mod vergleich;
@@ -0,0 +1,127 @@
//! pokerbench-welt5-estep: Welt v5 E-step.
//!
//! pokerbench-welt5-estep estep --haende IN.jsonl|- --params P.json --out OUT.jsonl|- [--faeden 4] [--mischung 0] [--max-typen 3]
//! [--vorflop F.json] [--nice 10] [--max N]
//! pokerbench-welt5-estep vergleich A.jsonl B.jsonl [--tol 1e-9]
//! pokerbench-welt5-estep erzeuge --n N --seed S --haende OUT.jsonl --params OUT.json (synthetic data, for timing and smoke tests)
//!
//! Plain JSONL only (no gzip in std): use `-` and pipe through gzip, see lauf_gz.py.
use estep::hand::Optionen;
use estep::lauf::{lauf, LaufOpt};
use estep::{synth, vergleich};
use std::collections::HashMap;
use std::fs::OpenOptions;
use std::io::Write;
use std::process::ExitCode;
fn argumente(args: &[String]) -> Result<(Vec<String>, HashMap<String, String>), String> {
let mut pos = Vec::new();
let mut opt = HashMap::new();
let mut i = 0;
while i < args.len() {
if let Some(k) = args[i].strip_prefix("--") {
let v = args.get(i + 1).ok_or_else(|| format!("--{} needs a value", k))?.clone();
opt.insert(k.to_string(), v);
i += 2;
} else {
pos.push(args[i].clone());
i += 1;
}
}
Ok((pos, opt))
}
fn schreibe_neu(pfad: &str, inhalt: &str) -> Result<(), String> {
let mut f = OpenOptions::new().write(true).create_new(true).open(pfad).map_err(|e| format!("{}: {} (refusing to overwrite)", pfad, e))?;
f.write_all(inhalt.as_bytes()).map_err(|e| e.to_string())
}
fn lauf_main(args: &[String]) -> Result<u8, String> {
let (_, o) = argumente(args)?;
let get = |k: &str| o.get(k).cloned();
let zahl = |k: &str, d: f64| -> Result<f64, String> { get(k).map_or(Ok(d), |v| v.parse::<f64>().map_err(|_| format!("--{}: not a number", k))) };
let lo = LaufOpt {
haende: get("haende").ok_or("--haende missing")?,
params: get("params").ok_or("--params missing")?,
vorflop: get("vorflop"),
out: get("out").ok_or("--out missing")?,
faeden: zahl("faeden", 4.0)? as usize,
nice: zahl("nice", 10.0)? as i32,
max: get("max").map(|v| v.parse::<usize>().map_err(|_| "--max: not a number".to_string())).transpose()?,
opt: Optionen { mischung: zahl("mischung", 0.0)?, max_typen: zahl("max-typen", 3.0)? as usize },
};
if !(0.0..1.0).contains(&lo.opt.mischung) {
return Err("--mischung must be in [0, 1)".into());
}
let s = lauf(&lo)?;
let n = s.haende.max(1) as f64;
eprintln!(
"estep: {} hands, {} errors, wall {:.2} s ({:.3} ms/hand wall), cpu {:.3} ms/hand, {} threads",
s.haende,
s.fehler,
s.wall_s,
s.wall_s * 1e3 / n,
s.cpu_ns as f64 / 1e6 / n,
lo.faeden
);
Ok(if s.fehler > 0 { 2 } else { 0 })
}
fn vergleich_main(args: &[String]) -> Result<u8, String> {
let (pos, o) = argumente(args)?;
if pos.len() != 2 {
return Err("usage: vergleich A.jsonl B.jsonl [--tol 1e-9]".into());
}
let tol: f64 = o.get("tol").map_or(Ok(1e-9), |v| v.parse().map_err(|_| "--tol".to_string()))?;
let e = vergleich::vergleiche(&pos[0], &pos[1], tol, 1e-15)?;
println!(
"compared {} hands: {} differ, {} only in A, {} only in B; max |d ll| {:e}, max |d bin weight| {:e}, max |d bin q| {:e} (tol {:e})",
e.haende, e.verschieden, e.nur_a, e.nur_b, e.max_ll, e.max_w, e.max_q, tol
);
for m in &e.meldungen {
println!(" {}", m);
}
let ok = e.verschieden == 0 && e.nur_a == 0 && e.nur_b == 0 && e.haende > 0;
println!("{}", if ok { "OK" } else { "FAIL" });
Ok(if ok { 0 } else { 1 })
}
fn erzeuge_main(args: &[String]) -> Result<u8, String> {
let (_, o) = argumente(args)?;
let n: usize = o.get("n").ok_or("--n missing")?.parse().map_err(|_| "--n".to_string())?;
let seed: u64 = o.get("seed").map_or(Ok(1), |v| v.parse().map_err(|_| "--seed".to_string()))?;
let mut r = synth::Rng::new(seed);
let mut text = String::new();
for i in 0..n {
text.push_str(&synth::hand_zeile(&mut r, i));
text.push('\n');
}
schreibe_neu(o.get("haende").ok_or("--haende missing")?, &text)?;
schreibe_neu(o.get("params").ok_or("--params missing")?, &synth::params_text(seed))?;
Ok(0)
}
fn main() -> ExitCode {
let args: Vec<String> = std::env::args().skip(1).collect();
let (cmd, rest) = match args.split_first() {
Some((c, r)) => (c.as_str(), r),
None => {
eprintln!("usage: pokerbench-welt5-estep estep|vergleich|erzeuge ... (see src/main.rs)");
return ExitCode::from(64);
}
};
let r = match cmd {
"estep" => lauf_main(rest),
"vergleich" => vergleich_main(rest),
"erzeuge" => erzeuge_main(rest),
_ => Err(format!("unknown command '{}'", cmd)),
};
match r {
Ok(c) => ExitCode::from(c),
Err(e) => {
eprintln!("error: {}", e);
ExitCode::from(1)
}
}
}
@@ -0,0 +1,188 @@
//! Parameter file (M-step -> E-step), ENTWURF section 4:
//! {"fassung": "5.0-rN", "typen": 48, "alpha": {"t<k>": {"<stufe>:<code>": [6]}, "pool": {...}},
//! "beta": [4][6][5], "lambda": [6], "tau": [3], "vorflop": {"AKs": 0.67, ...}}
//! stufe is 0 = fein, 1 = mittel, 2 = grob (also accepted as the words fein / mittel / grob).
//! `vorflop` (class -> equity, 169 entries) is an addition of this implementation: the preflop strength table of the world file.
use crate::json::{self, J};
use crate::karten::tafeln;
use crate::kern::{NA, NK, NS};
use std::collections::HashMap;
pub type AlphaTafel = HashMap<(u8, i64), [f64; NA]>;
pub struct Params {
pub fassung: String,
pub typen: usize,
pub alpha: Vec<AlphaTafel>,
pub pool: AlphaTafel,
/// NS * NA * NK, beta[s][0][k] forced to 0
pub beta: Vec<f64>,
pub lambda: [f64; NA],
/// preflop strength per class (index as `Tafeln::klassen_namen`), if the file has it
pub vorflop: Option<Vec<f64>>,
}
fn stufe(s: &str) -> Result<u8, String> {
match s {
"0" | "fein" | "f" => Ok(0),
"1" | "mittel" | "m" => Ok(1),
"2" | "grob" | "g" => Ok(2),
_ => Err(format!("unknown alpha stufe '{}'", s)),
}
}
fn six(v: &J, what: &str) -> Result<[f64; NA], String> {
let a = v.arr().ok_or_else(|| format!("{}: expected array of 6", what))?;
if a.len() != NA {
return Err(format!("{}: expected 6 numbers, got {}", what, a.len()));
}
let mut out = [0.0; NA];
for i in 0..NA {
out[i] = a[i].f64().ok_or_else(|| format!("{}: not a number", what))?;
}
Ok(out)
}
fn alpha_tafel(v: &J, what: &str) -> Result<AlphaTafel, String> {
let mut m = AlphaTafel::new();
match v {
J::Obj(items) => {
for (k, x) in items {
let (s, c) = k.split_once(':').ok_or_else(|| format!("{}: bad key '{}'", what, k))?;
let code: i64 = c.parse().map_err(|_| format!("{}: bad code in '{}'", what, k))?;
m.insert((stufe(s)?, code), six(x, &format!("{} {}", what, k))?);
}
Ok(m)
}
_ => Err(format!("{}: expected object", what)),
}
}
/// {"AKs": 0.67, ...} with all 169 classes -> strengths by class index.
pub fn vorflop_tafel(j: &J) -> Result<Vec<f64>, String> {
let namen = &tafeln().klassen_namen;
let mut v = vec![f64::NAN; namen.len()];
match j {
J::Obj(items) => {
for (k, x) in items {
let i = namen.iter().position(|n| n == k).ok_or_else(|| format!("vorflop: unknown class '{}'", k))?;
v[i] = x.f64().ok_or("vorflop: not a number")?;
}
}
_ => return Err("vorflop: expected object".into()),
}
if v.iter().any(|x| x.is_nan()) {
return Err("vorflop: classes missing (need all 169)".into());
}
Ok(v)
}
impl Params {
pub fn from_json(j: &J) -> Result<Params, String> {
let fassung = j.get("fassung").and_then(|x| x.str()).unwrap_or("").to_string();
let typen = j.get("typen").and_then(|x| x.i64()).unwrap_or(48) as usize;
let mut alpha: Vec<AlphaTafel> = (0..typen).map(|_| AlphaTafel::new()).collect();
let mut pool = AlphaTafel::new();
match j.get("alpha") {
Some(J::Obj(items)) => {
for (k, v) in items {
if k == "pool" {
pool = alpha_tafel(v, "alpha.pool")?;
} else if let Some(n) = k.strip_prefix('t').and_then(|n| n.parse::<usize>().ok()) {
if n >= alpha.len() {
alpha.resize_with(n + 1, AlphaTafel::new);
}
alpha[n] = alpha_tafel(v, &format!("alpha.{}", k))?;
} else {
return Err(format!("alpha: unknown key '{}'", k));
}
}
}
_ => return Err("alpha missing".into()),
}
let mut beta = vec![0.0; NS * NA * NK];
let b = j.get("beta").and_then(|x| x.arr()).ok_or("beta missing")?;
if b.len() != NS {
return Err(format!("beta: expected {} streets", NS));
}
for (s, bs) in b.iter().enumerate() {
let bs = bs.arr().ok_or("beta: expected [4][6][5]")?;
if bs.len() != NA {
return Err("beta: expected 6 actions".into());
}
for (a, ba) in bs.iter().enumerate() {
let ba = ba.arr().ok_or("beta: expected [4][6][5]")?;
if ba.len() != NK {
return Err("beta: expected 5 knots".into());
}
for (k, x) in ba.iter().enumerate() {
// Fold is the reference action: its coefficients are zero by definition
beta[(s * NA + a) * NK + k] = if a == 0 { 0.0 } else { x.f64().ok_or("beta: not a number")? };
}
}
}
let lambda = match j.get("lambda") {
Some(l) => six(l, "lambda")?,
None => [0.0; NA],
};
let vorflop = match j.get("vorflop") {
Some(v @ J::Obj(_)) => Some(vorflop_tafel(v)?),
_ => None,
};
Ok(Params { fassung, typen, alpha, pool, beta, lambda, vorflop })
}
pub fn aus_text(text: &str) -> Result<Params, String> {
Params::from_json(&json::parse(text)?)
}
/// alpha for type `t` (-1 = no type, pool only) at the decision's three code levels:
/// type fein -> type mittel -> type grob -> pool grob -> zeros.
pub fn alpha_fuer(&self, t: i32, codes: [i64; 3]) -> [f64; NA] {
if t >= 0 {
if let Some(tab) = self.alpha.get(t as usize) {
for s in 0..3u8 {
if let Some(a) = tab.get(&(s, codes[s as usize])) {
return *a;
}
}
}
}
self.pool.get(&(2, codes[2])).copied().unwrap_or([0.0; NA])
}
}
#[cfg(test)]
mod tests {
use super::*;
fn text() -> String {
let street = "[[9,9,9,9,9],[1,2,3,4,5],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]]";
let b4 = format!("[{0},{0},{0},{0}]", street);
format!(
r#"{{"fassung":"t","typen":3,"alpha":{{"t1":{{"0:7":[1,1,1,1,1,1],"1:3":[2,2,2,2,2,2],"2:1":[3,3,3,3,3,3]}},"pool":{{"2:1":[4,4,4,4,4,4],"2:9":[5,5,5,5,5,5]}}}},"beta":{},"lambda":[0,0,0,0,0,0]}}"#,
b4
)
}
#[test]
fn alpha_fallback_chain() {
let p = Params::aus_text(&text()).unwrap();
assert_eq!(p.alpha_fuer(1, [7, 3, 1])[0], 1.0); // fine hit
assert_eq!(p.alpha_fuer(1, [8, 3, 1])[0], 2.0); // fine miss -> mid
assert_eq!(p.alpha_fuer(1, [8, 4, 1])[0], 3.0); // -> coarse of the type
assert_eq!(p.alpha_fuer(1, [8, 4, 9])[0], 5.0); // -> pool coarse
assert_eq!(p.alpha_fuer(1, [8, 4, 2])[0], 0.0); // -> zero
assert_eq!(p.alpha_fuer(0, [7, 3, 1])[0], 4.0); // type without entries -> pool
assert_eq!(p.alpha_fuer(-1, [7, 3, 1])[0], 4.0); // no type -> pool
assert_eq!(p.alpha_fuer(2, [7, 3, 2])[0], 0.0);
}
#[test]
fn fold_beta_is_forced_to_zero() {
let p = Params::aus_text(&text()).unwrap();
assert!(p.beta[..NK].iter().all(|&x| x == 0.0));
assert_eq!(p.beta[NK + 2], 3.0); // street 0, action 1, knot 2
}
}
@@ -0,0 +1,328 @@
//! Hand strength s(h) for all 1,326 combos on a board (ENTWURF section 3), identical to
//! welt_v4/staerke.py: `_staerke_auslaeufe` for a river, mean over the 46 river cards for a turn,
//! and the deterministic flop rule of v5 (runs j = 0, 24, 48, ... of the 1,176 lexicographic
//! (turn < river) pairs of the 49 free cards, 49 runs). Preflop: class table.
//!
//! Strength of a combo = (opponents beaten + 0.5 * ties) / opponents, where opponents are all
//! combos not touching the board and sharing no card with the combo. Combos touching the board
//! are NaN. Floating point operations are done in the same order as the numpy reference.
use crate::karten::{board_bits, board_maske, score, tafeln, NC};
pub const FLOP_SCHRITT: usize = 24;
#[derive(Default)]
pub struct Scratch {
wert: Vec<u32>,
schl: Vec<u64>,
k0: Vec<u32>,
g0: Vec<u32>,
je_karte: Vec<Vec<u32>>,
st: Vec<f64>,
gueltig: Vec<bool>,
summe: Vec<f64>,
zahl: Vec<u32>,
}
impl Scratch {
pub fn new() -> Self {
Scratch {
wert: vec![0; NC],
schl: Vec::with_capacity(NC),
k0: vec![0; NC],
g0: vec![0; NC],
je_karte: vec![Vec::with_capacity(52); 52],
st: vec![f64::NAN; NC],
gueltig: vec![false; NC],
summe: vec![0.0; NC],
zahl: vec![0; NC],
}
}
}
fn zaehle(sortiert: &[u32], v: u32) -> (i64, i64) {
let kleiner = sortiert.partition_point(|&x| x < v);
let bis = sortiert.partition_point(|&x| x <= v);
(kleiner as i64, (bis - kleiner) as i64)
}
/// River strengths for a 5-card board into `st` (NaN where the combo touches the board) and `gueltig`.
fn river(sc: &mut Scratch, board: &[u8], st_out: &mut [f64], gueltig: &mut [bool]) {
let t = tafeln();
let bm = board_maske(board);
let bb = board_bits(board);
sc.schl.clear();
for v in sc.je_karte.iter_mut() {
v.clear();
}
for h in 0..NC {
if t.maske[h] & bm != 0 {
gueltig[h] = false;
continue;
}
gueltig[h] = true;
let v = score(bb | t.bits[h]);
sc.wert[h] = v;
sc.schl.push(((v as u64) << 16) | h as u64);
}
// one sort; the per-card lists come out sorted by construction, the global ranks by a run scan
sc.schl.sort_unstable();
let n = sc.schl.len();
let mut i = 0;
while i < n {
let v = sc.schl[i] >> 16;
let mut j = i;
while j < n && sc.schl[j] >> 16 == v {
j += 1;
}
for x in i..j {
let h = (sc.schl[x] & 0xFFFF) as usize;
sc.k0[h] = i as u32;
sc.g0[h] = (j - i) as u32;
let (a, b) = t.paar[h];
sc.je_karte[a as usize].push(v as u32);
sc.je_karte[b as usize].push(v as u32);
}
i = j;
}
let gesamt_alle = n as i64;
for h in 0..NC {
if !gueltig[h] {
st_out[h] = f64::NAN;
continue;
}
let v = sc.wert[h];
let (a, b) = t.paar[h];
let (ka, ga) = zaehle(&sc.je_karte[a as usize], v);
let (kb, gb) = zaehle(&sc.je_karte[b as usize], v);
let kleiner = sc.k0[h] as i64 - ka - kb;
let gleich = sc.g0[h] as i64 - ga - gb + 1;
let gesamt = gesamt_alle - sc.je_karte[a as usize].len() as i64 - sc.je_karte[b as usize].len() as i64 + 1;
st_out[h] = (kleiner as f64 + 0.5 * gleich as f64) / (gesamt.max(1) as f64);
}
}
/// Strengths of a 5-card board (river).
pub fn river_staerke(sc: &mut Scratch, board: &[u8]) -> Vec<f64> {
assert_eq!(board.len(), 5);
let mut st = vec![f64::NAN; NC];
let mut g = vec![false; NC];
river(sc, board, &mut st, &mut g);
st
}
fn mittel_ueber_laeufe<I: Iterator<Item = [u8; 5]>>(sc: &mut Scratch, prefix: &[u8], laeufe: I) -> Vec<f64> {
let t = tafeln();
for h in 0..NC {
sc.summe[h] = 0.0;
sc.zahl[h] = 0;
}
let mut st = std::mem::take(&mut sc.st);
let mut g = std::mem::take(&mut sc.gueltig);
for lauf in laeufe {
river(sc, &lauf, &mut st, &mut g);
for h in 0..NC {
if g[h] {
sc.summe[h] += st[h];
sc.zahl[h] += 1;
}
}
}
sc.st = st;
sc.gueltig = g;
let pm = board_maske(prefix);
(0..NC)
.map(|h| if t.maske[h] & pm != 0 || sc.zahl[h] == 0 { f64::NAN } else { sc.summe[h] / (sc.zahl[h].max(1) as f64) })
.collect()
}
fn freie_karten(board: &[u8]) -> Vec<u8> {
let m = board_maske(board);
(0..52u8).filter(|&c| m >> c & 1 == 0).collect()
}
/// Turn: mean over all river cards.
pub fn turn_staerke(sc: &mut Scratch, board: &[u8]) -> Vec<f64> {
assert_eq!(board.len(), 4);
let frei = freie_karten(board);
let b = [board[0], board[1], board[2], board[3]];
mittel_ueber_laeufe(sc, board, frei.iter().map(move |&c| [b[0], b[1], b[2], b[3], c]))
}
/// Flop (v5 rule): mean over runs j = 0, 24, 48, ... of the lexicographic pairs of free cards.
pub fn flop_staerke(sc: &mut Scratch, board: &[u8]) -> Vec<f64> {
assert_eq!(board.len(), 3);
let frei = freie_karten(board);
let b = [board[0], board[1], board[2]];
let mut laeufe = Vec::new();
let mut j = 0usize;
for i in 0..frei.len() {
for k in i + 1..frei.len() {
if j % FLOP_SCHRITT == 0 {
laeufe.push([b[0], b[1], b[2], frei[i], frei[k]]);
}
j += 1;
}
}
mittel_ueber_laeufe(sc, board, laeufe.into_iter())
}
/// Preflop strengths from a class table (class index as in `Tafeln::klassen_namen`).
pub fn vorflop_staerke(tafel: &[f64]) -> Vec<f64> {
let t = tafeln();
(0..NC).map(|h| tafel[t.klasse[h] as usize]).collect()
}
/// Strengths of all combos for a board prefix of 3, 4 or 5 cards.
pub fn brett_staerke(sc: &mut Scratch, board: &[u8]) -> Vec<f64> {
match board.len() {
3 => flop_staerke(sc, board),
4 => turn_staerke(sc, board),
5 => river_staerke(sc, board),
n => panic!("board of {} cards", n),
}
}
/// Combos sorted by (strength ascending, combo number), NaN dropped.
pub fn ordnung(st: &[f64]) -> Vec<u16> {
let mut v: Vec<u16> = (0..NC as u16).filter(|&h| !st[h as usize].is_nan()).collect();
v.sort_by(|&a, &b| st[a as usize].partial_cmp(&st[b as usize]).unwrap().then(a.cmp(&b)));
v
}
#[cfg(test)]
pub mod tests {
use super::*;
use crate::karten::tests::c;
/// O(n^2) reference for a river board.
pub fn river_brute(board: &[u8]) -> Vec<f64> {
let t = tafeln();
let bm = board_maske(board);
let bb = board_bits(board);
(0..NC)
.map(|h| {
if t.maske[h] & bm != 0 {
return f64::NAN;
}
let me = score(bb | t.bits[h]);
let (mut kl, mut gl, mut n) = (0i64, 0i64, 0i64);
for g in 0..NC {
if t.maske[g] & (bm | t.maske[h]) != 0 {
continue;
}
n += 1;
let o = score(bb | t.bits[g]);
if o < me {
kl += 1;
} else if o == me {
gl += 1;
}
}
(kl as f64 + 0.5 * gl as f64) / n as f64
})
.collect()
}
fn mittel_brute(prefix: &[u8], laeufe: &[Vec<u8>]) -> Vec<f64> {
let t = tafeln();
let je_lauf: Vec<Vec<f64>> = laeufe.iter().map(|l| river_brute(l)).collect();
(0..NC)
.map(|h| {
if t.maske[h] & board_maske(prefix) != 0 {
return f64::NAN;
}
let (mut s, mut n) = (0.0, 0u32);
for l in &je_lauf {
let st = l[h];
if !st.is_nan() {
s += st;
n += 1;
}
}
if n == 0 {
f64::NAN
} else {
s / n as f64
}
})
.collect()
}
fn gleich(a: &[f64], b: &[f64]) {
assert_eq!(a.len(), b.len());
for i in 0..a.len() {
assert!((a[i].is_nan() && b[i].is_nan()) || (a[i] - b[i]).abs() < 1e-12, "combo {}: {} vs {}", i, a[i], b[i]);
}
}
fn brett(s: &str) -> Vec<u8> {
s.split_whitespace().map(c).collect()
}
#[test]
fn river_matches_brute_force() {
let mut sc = Scratch::new();
for b in ["2c 7d 9h Js Ac", "Ah Kh Qh Jh Th", "2c 2d 2h 9s 9c", "3c 4d 5h 6s 7c"] {
let b = brett(b);
gleich(&river_staerke(&mut sc, &b), &river_brute(&b));
}
}
#[test]
fn river_values_are_sane() {
let mut sc = Scratch::new();
let b = brett("Ah Kh Qh Jh Th");
let st = river_staerke(&mut sc, &b);
// board is a royal flush: every playable combo ties with every other -> exactly 0.5
let t = tafeln();
for h in 0..NC {
if t.maske[h] & board_maske(&b) == 0 {
assert!((st[h] - 0.5).abs() < 1e-15);
} else {
assert!(st[h].is_nan());
}
}
}
#[test]
fn turn_is_mean_over_all_rivers() {
let mut sc = Scratch::new();
let b = brett("2c 7d 9h Js");
let laeufe: Vec<Vec<u8>> = freie_karten(&b).iter().map(|&x| [b.clone(), vec![x]].concat()).collect();
assert_eq!(laeufe.len(), 48);
gleich(&turn_staerke(&mut sc, &b), &mittel_brute(&b, &laeufe));
}
#[test]
fn flop_uses_every_24th_lexicographic_pair() {
let mut sc = Scratch::new();
let b = brett("2c 7d 9h");
let frei = freie_karten(&b);
assert_eq!(frei.len(), 49);
let mut paare = Vec::new();
for i in 0..frei.len() {
for k in i + 1..frei.len() {
paare.push((frei[i], frei[k]));
}
}
assert_eq!(paare.len(), 1176);
let laeufe: Vec<Vec<u8>> = (0..1176).step_by(24).map(|j| [b.clone(), vec![paare[j].0, paare[j].1]].concat()).collect();
assert_eq!(laeufe.len(), 49);
gleich(&flop_staerke(&mut sc, &b), &mittel_brute(&b, &laeufe));
}
#[test]
fn ordering_is_stable_by_combo_number() {
let st = vec![0.5; NC];
let o = ordnung(&st);
assert_eq!(o.len(), NC);
assert!(o.windows(2).all(|w| w[0] < w[1]));
let mut st2 = vec![0.0; NC];
st2[5] = 1.0;
st2[7] = f64::NAN;
let o2 = ordnung(&st2);
assert_eq!(o2.len(), NC - 1);
assert_eq!(*o2.last().unwrap(), 5);
}
}
@@ -0,0 +1,217 @@
//! Synthetic hands and parameters (random, NOT real data) for timing and smoke tests.
use crate::json;
use crate::karten::{bit, board_bits, score, tafeln, RAENGE};
pub struct Rng(u64);
impl Rng {
pub fn new(seed: u64) -> Self {
Rng(seed.wrapping_mul(0x9E3779B97F4A7C15) | 1)
}
pub fn next(&mut self) -> u64 {
let mut x = self.0;
x ^= x >> 12;
x ^= x << 25;
x ^= x >> 27;
self.0 = x;
x.wrapping_mul(0x2545F4914F6CDD1D)
}
pub fn unit(&mut self) -> f64 {
(self.next() >> 11) as f64 / (1u64 << 53) as f64
}
pub fn below(&mut self, n: usize) -> usize {
(self.next() % n as u64) as usize
}
pub fn zwischen(&mut self, lo: f64, hi: f64) -> f64 {
lo + (hi - lo) * self.unit()
}
}
fn zahlenliste(out: &mut String, v: &[f64]) {
out.push('[');
for (i, x) in v.iter().enumerate() {
if i > 0 {
out.push(',');
}
json::num(out, *x);
}
out.push(']');
}
/// A parameter file with random alpha/beta for types 0..6, pool coarse codes, and a rough preflop table.
pub fn params_text(seed: u64) -> String {
let mut r = Rng::new(seed);
let mut s = String::from("{\"fassung\":\"synth\",\"typen\":48,\"alpha\":{");
for t in 0..6 {
s.push_str(&format!("\"t{}\":{{", t));
let mut first = true;
for (stufe, anzahl, basis) in [(0, 40usize, 0i64), (1, 10, 100), (2, 3, 200)] {
for c in 0..anzahl {
if r.unit() < 0.6 {
continue;
}
if !first {
s.push(',');
}
first = false;
let v: Vec<f64> = (0..6).map(|a| if a == 0 { 0.0 } else { r.zwischen(-1.5, 1.0) }).collect();
s.push_str(&format!("\"{}:{}\":", stufe, basis + c as i64));
zahlenliste(&mut s, &v);
}
}
s.push('}');
s.push(',');
}
s.push_str("\"pool\":{");
for c in 0..3 {
if c > 0 {
s.push(',');
}
let v: Vec<f64> = (0..6).map(|a| if a == 0 { 0.0 } else { r.zwischen(-1.0, 0.5) }).collect();
s.push_str(&format!("\"2:{}\":", 200 + c));
zahlenliste(&mut s, &v);
}
s.push_str("}},\"beta\":[");
for st in 0..4 {
if st > 0 {
s.push(',');
}
s.push('[');
for a in 0..6 {
if a > 0 {
s.push(',');
}
let v: Vec<f64> = (0..5).map(|k| if a == 0 { 0.0 } else { r.zwischen(-1.0, 4.0) * (k as f64 / 4.0) }).collect();
zahlenliste(&mut s, &v);
}
s.push(']');
}
s.push_str("],\"lambda\":[0,0,0,0,0,0],\"tau\":[1,1,1],\"vorflop\":{");
for (i, n) in tafeln().klassen_namen.iter().enumerate() {
if i > 0 {
s.push(',');
}
let b = n.as_bytes();
let hi = RAENGE.iter().position(|&c| c == b[0]).unwrap() as f64;
let lo = RAENGE.iter().position(|&c| c == b[1]).unwrap() as f64;
let mut v = 0.30 + 0.025 * hi + 0.01 * lo;
if b.len() == 2 {
v += 0.15;
} else if b[2] == b's' {
v += 0.02;
}
s.push_str(&format!("\"{}\":{}", n, v.min(0.85)));
}
s.push_str("}}");
s
}
fn lauf_ent(r: &mut Rng, st: usize, mut s: String) -> String {
let fein = r.below(40) as i64;
let mittel = 100 + fein / 4;
let grob = 200 + fein / 15;
let mut erl = [0u8; 6];
erl[1] = 1;
erl[0] = (r.unit() < 0.8) as u8;
for a in 2..6 {
erl[a] = (r.unit() < 0.6) as u8;
}
let legal: Vec<usize> = (0..6).filter(|&a| erl[a] == 1).collect();
let zug = legal[r.below(legal.len())];
let o: Vec<f64> = (0..6).map(|_| if r.unit() < 0.5 { 0.0 } else { r.zwischen(-0.3, 0.3) }).collect();
s.push_str(&format!("{{\"st\":{},\"codes\":[{},{},{}],\"erlaubt\":[", st, fein, mittel, grob));
s.push_str(&erl.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(","));
s.push_str("],\"o\":");
zahlenliste(&mut s, &o);
s.push_str(&format!(",\"zug\":{}}}", zug));
s
}
/// One synthetic hand as a decision-file line.
pub fn hand_zeile(r: &mut Rng, nr: usize) -> String {
let mut deck: Vec<u8> = (0..52).collect();
for i in (1..52).rev() {
deck.swap(i, r.below(i + 1));
}
let n = 2 + r.below(5);
let u = r.unit();
let blen = if u < 0.15 { 0 } else if u < 0.35 { 3 } else if u < 0.5 { 4 } else { 5 };
let brett_full: Vec<u8> = deck[..5].to_vec();
let brett: Vec<u8> = brett_full[..blen].to_vec();
let holes: Vec<[u8; 2]> = (0..n).map(|i| [deck[5 + 2 * i], deck[6 + 2 * i]]).collect();
// showdown: with a full board, a random subset shows; the best shown hand beats the muckers
let mut gezeigt: Vec<Option<[u8; 2]>> = vec![None; n];
let mut muck: Vec<Option<[u8; 2]>> = vec![None; n];
if blen == 5 {
let bb = board_bits(&brett_full);
let wert = |h: &[u8; 2]| score(bb | bit(h[0]) | bit(h[1]));
let best = (0..n).max_by_key(|&i| wert(&holes[i])).unwrap();
if r.unit() < 0.5 {
gezeigt[best] = Some(holes[best]);
for i in 0..n {
if i == best {
continue;
}
let u = r.unit();
if u < 0.3 {
gezeigt[i] = Some(holes[i]);
} else if u < 0.6 && wert(&holes[i]) < wert(&holes[best]) {
muck[i] = Some(holes[best]);
}
}
}
}
let mut s = String::from("{\"h\":");
json::string(&mut s, &format!("synth{}", nr));
s.push_str(&format!(",\"tag\":\"2026-01-01\",\"bb\":0.02,\"brett\":[{}],\"spieler\":[", brett.iter().map(|c| c.to_string()).collect::<Vec<_>>().join(",")));
let strassen = match blen {
0 => 1,
3 => 2,
4 => 3,
_ => 4,
};
for i in 0..n {
if i > 0 {
s.push(',');
}
s.push_str(&format!("{{\"platz\":{},\"typen\":[", i));
let nt = 1 + r.below(3);
let mut rest = 1.0;
for k in 0..nt {
if k > 0 {
s.push(',');
}
let w = if k + 1 == nt { rest } else { rest * r.zwischen(0.3, 0.7) };
rest -= w;
s.push_str(&format!("[{},{}]", r.below(6), w));
}
s.push_str("],\"gezeigt\":");
match gezeigt[i] {
Some(h) => s.push_str(&format!("[{},{}]", h[0], h[1])),
None => s.push_str("null"),
}
s.push_str(",\"muck\":");
match muck[i] {
Some(h) => s.push_str(&format!("[{},{}]", h[0], h[1])),
None => s.push_str("null"),
}
s.push_str(",\"ents\":[");
let mut erste = true;
for st in 0..strassen {
if st > 0 && r.unit() < 0.3 {
break;
}
for _ in 0..(1 + (r.unit() < 0.3) as usize) {
if !erste {
s.push(',');
}
erste = false;
s = lauf_ent(r, st, s);
}
}
s.push_str("]}");
}
s.push_str("]}");
s
}
@@ -0,0 +1,139 @@
//! Compare two E-step output files (JSONL) by hand id: ll, and per entry zug, st, codes, type, bins (weight, q).
//! Entries are matched by position within the hand. Numbers match if |a - b| <= tol * max(1, |a|, |b|).
//! The mean q of a bin is only compared where the bin weight exceeds `q_min_w` (empty bins carry no q).
use crate::json::{self, J};
use std::collections::HashMap;
use std::fs;
pub struct Ergebnis {
pub haende: usize,
pub nur_a: usize,
pub nur_b: usize,
pub verschieden: usize,
pub max_ll: f64,
pub max_w: f64,
pub max_q: f64,
pub meldungen: Vec<String>,
}
fn nah(a: f64, b: f64, tol: f64) -> bool {
(a - b).abs() <= tol * 1f64.max(a.abs()).max(b.abs())
}
fn lade(pfad: &str) -> Result<Vec<(String, J)>, String> {
let text = fs::read_to_string(pfad).map_err(|e| format!("{}: {}", pfad, e))?;
let mut v = Vec::new();
for (i, l) in text.lines().enumerate() {
if l.trim().is_empty() {
continue;
}
let j = json::parse(l).map_err(|e| format!("{} line {}: {}", pfad, i + 1, e))?;
let h = j.get("h").and_then(|x| x.str()).ok_or_else(|| format!("{} line {}: no h", pfad, i + 1))?.to_string();
v.push((h, j));
}
Ok(v)
}
pub fn vergleiche(pfad_a: &str, pfad_b: &str, tol: f64, q_min_w: f64) -> Result<Ergebnis, String> {
let a = lade(pfad_a)?;
let b: HashMap<String, J> = lade(pfad_b)?.into_iter().collect();
let mut e = Ergebnis { haende: 0, nur_a: 0, nur_b: 0, verschieden: 0, max_ll: 0.0, max_w: 0.0, max_q: 0.0, meldungen: Vec::new() };
let mut gesehen = 0usize;
for (h, ja) in &a {
let jb = match b.get(h) {
Some(x) => x,
None => {
e.nur_a += 1;
continue;
}
};
gesehen += 1;
e.haende += 1;
let mut fehl: Vec<String> = Vec::new();
match (ja.get("ll"), jb.get("ll")) {
(Some(x), Some(y)) if x.is_null() && y.is_null() => {}
(Some(x), Some(y)) => match (x.f64(), y.f64()) {
(Some(x), Some(y)) => {
e.max_ll = e.max_ll.max((x - y).abs());
if !nah(x, y, tol) {
fehl.push(format!("ll {} vs {}", x, y));
}
}
_ => fehl.push("ll null vs number".into()),
},
_ => fehl.push("ll missing".into()),
}
let ea = ja.get("ents").and_then(|x| x.arr()).unwrap_or(&[]);
let eb = jb.get("ents").and_then(|x| x.arr()).unwrap_or(&[]);
if ea.len() != eb.len() {
fehl.push(format!("entries {} vs {}", ea.len(), eb.len()));
} else {
for (i, (x, y)) in ea.iter().zip(eb).enumerate() {
for k in ["zug", "st"] {
if x.get(k).and_then(|v| v.i64()) != y.get(k).and_then(|v| v.i64()) {
fehl.push(format!("ent {} {}", i, k));
}
}
let tx = x.get("typen").and_then(|v| v.arr()).and_then(|v| v.first()).and_then(|v| v.arr());
let ty = y.get("typen").and_then(|v| v.arr()).and_then(|v| v.first()).and_then(|v| v.arr());
if let (Some(tx), Some(ty)) = (tx, ty) {
if tx[0].i64() != ty[0].i64() {
fehl.push(format!("ent {} type {:?} vs {:?}", i, tx[0].i64(), ty[0].i64()));
}
let (wx, wy) = (tx[1].f64().unwrap_or(f64::NAN), ty[1].f64().unwrap_or(f64::NAN));
if !nah(wx, wy, tol) {
fehl.push(format!("ent {} type posterior {} vs {}", i, wx, wy));
}
} else {
fehl.push(format!("ent {} typen missing", i));
}
let (bx, by) = (x.get("bins").and_then(|v| v.arr()), y.get("bins").and_then(|v| v.arr()));
match (bx, by) {
(Some(bx), Some(by)) if bx.len() == by.len() => {
for (bi, (p, q)) in bx.iter().zip(by).enumerate() {
let (p, q) = (p.arr().unwrap_or(&[]), q.arr().unwrap_or(&[]));
if p.len() != 2 || q.len() != 2 {
fehl.push(format!("ent {} bin {} shape", i, bi));
continue;
}
let (w1, w2) = (p[0].f64().unwrap_or(f64::NAN), q[0].f64().unwrap_or(f64::NAN));
e.max_w = e.max_w.max((w1 - w2).abs());
if !nah(w1, w2, tol) {
fehl.push(format!("ent {} bin {} weight {} vs {}", i, bi, w1, w2));
}
if w1 > q_min_w || w2 > q_min_w {
let (q1, q2) = (p[1].f64().unwrap_or(f64::NAN), q[1].f64().unwrap_or(f64::NAN));
e.max_q = e.max_q.max((q1 - q2).abs());
if !nah(q1, q2, tol) {
fehl.push(format!("ent {} bin {} q {} vs {}", i, bi, q1, q2));
}
}
}
}
_ => fehl.push(format!("ent {} bins missing or different length", i)),
}
}
}
if !fehl.is_empty() {
e.verschieden += 1;
if e.meldungen.len() < 20 {
e.meldungen.push(format!("{}: {}", h, fehl.iter().take(3).cloned().collect::<Vec<_>>().join("; ")));
}
}
}
e.nur_b = b.len().saturating_sub(gesehen);
Ok(e)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn closeness_is_relative_for_large_and_absolute_for_small() {
assert!(nah(1e-12, 2e-12, 1e-9));
assert!(nah(1000.0, 1000.0 + 1e-7, 1e-9));
assert!(!nah(1000.0, 1000.0 + 1e-5, 1e-9));
}
}
@@ -0,0 +1,54 @@
# Writes tests/golden_staerke.txt: strengths from the Python reference (welt_v4/staerke.py, flop per ENTWURF 3) for a few boards,
# read by the Rust test `golden_matches_python_reference`. Synthetic boards only, no real hands.
# python3 -I tests/gen_golden.py (refuses to overwrite)
import os, sys
sys.dont_write_bytecode = True
HIER = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HIER, "..", "..", "..", "welt_v4"))
import numpy as np
import staerke as ST
BRETTER = {
"river": ["2c 7d 9h Js Ac", "Ah Kh Qh 3d 3c", "5c 6d 7h 8s 9c", "2c 2d 2h 2s 9c"],
"turn": ["2c 7d 9h Js", "Ah Kh Qh 3d", "4s 4h 5c 9d"],
"flop": ["2c 7d 9h", "Ah Kh Qh", "4s 4h 5c"],
}
def karten(s):
return [ST.karte(t) for t in s.split()]
def flop_v5(brett):
frei = [c for c in range(52) if c not in brett]
paare = [(a, b) for i, a in enumerate(frei) for b in frei[i + 1:]]
laeufe = [brett + list(paare[j]) for j in range(0, len(paare), 24)]
assert len(laeufe) == 49
st, gueltig = ST._staerke_auslaeufe(laeufe)
zahl = gueltig.sum(0)
summe = np.where(gueltig, st, 0.0).sum(0)
auf_brett = (ST.KOMBI[:, :, None] == np.array(brett)[None, None, :]).any(-1).any(-1)
return np.where(auf_brett | (zahl == 0), np.nan, summe / np.maximum(zahl, 1))
def main():
ziel = os.path.join(HIER, "golden_staerke.txt")
if os.path.exists(ziel):
sys.exit("refusing to overwrite " + ziel)
zeilen = []
for art, liste in BRETTER.items():
for b in liste:
brett = karten(b)
if art == "flop":
st = flop_v5(brett)
else:
st = ST.brett_staerke(brett)
for nr in range(0, 1326, 37):
v = st[nr]
zeilen.append("%s|%s|%d|%s" % (art, b, nr, "nan" if np.isnan(v) else repr(float(v))))
with open(ziel, "w") as f:
f.write("\n".join(zeilen) + "\n")
print(len(zeilen), "lines ->", ziel)
main()
@@ -0,0 +1,37 @@
//! Strengths against the Python reference (welt_v4/staerke.py; flop per ENTWURF 3), values from tests/gen_golden.py.
use estep::karten::RAENGE;
use estep::staerke::{brett_staerke, Scratch};
fn karte(t: &str) -> u8 {
let b = t.as_bytes();
(RAENGE.iter().position(|&r| r == b[0]).unwrap() * 4 + b"cdhs".iter().position(|&f| f == b[1]).unwrap()) as u8
}
#[test]
fn golden_matches_python_reference() {
let text = include_str!("golden_staerke.txt");
let mut sc = Scratch::new();
let mut cache: Vec<(String, Vec<f64>)> = Vec::new();
let (mut n, mut max_diff) = (0, 0.0f64);
for l in text.lines() {
let f: Vec<&str> = l.split('|').collect();
let (brett_s, nr, want) = (f[1], f[2].parse::<usize>().unwrap(), f[3]);
if !cache.iter().any(|(k, _)| k == brett_s) {
let b: Vec<u8> = brett_s.split_whitespace().map(karte).collect();
cache.push((brett_s.to_string(), brett_staerke(&mut sc, &b)));
}
let st = &cache.iter().find(|(k, _)| k == brett_s).unwrap().1;
if want == "nan" {
assert!(st[nr].is_nan(), "{} combo {}", brett_s, nr);
} else {
let w: f64 = want.parse().unwrap();
let d = (st[nr] - w).abs();
max_diff = max_diff.max(d);
assert!(d < 1e-12, "{} combo {}: {} vs {}", brett_s, nr, st[nr], w);
}
n += 1;
}
assert!(n > 300);
eprintln!("golden: {} values, max diff {:e}", n, max_diff);
}
@@ -0,0 +1,360 @@
river|2c 7d 9h Js Ac|0|nan
river|2c 7d 9h Js Ac|37|nan
river|2c 7d 9h Js Ac|74|0.4313131313131313
river|2c 7d 9h Js Ac|111|0.42727272727272725
river|2c 7d 9h Js Ac|148|0.9525252525252526
river|2c 7d 9h Js Ac|185|nan
river|2c 7d 9h Js Ac|222|0.6383838383838384
river|2c 7d 9h Js Ac|259|0.5424242424242425
river|2c 7d 9h Js Ac|296|0.022727272727272728
river|2c 7d 9h Js Ac|333|0.8444444444444444
river|2c 7d 9h Js Ac|370|0.2287878787878788
river|2c 7d 9h Js Ac|407|0.7383838383838384
river|2c 7d 9h Js Ac|444|0.6383838383838384
river|2c 7d 9h Js Ac|481|0.10757575757575757
river|2c 7d 9h Js Ac|518|0.10757575757575757
river|2c 7d 9h Js Ac|555|0.5424242424242425
river|2c 7d 9h Js Ac|592|nan
river|2c 7d 9h Js Ac|629|nan
river|2c 7d 9h Js Ac|666|0.5424242424242425
river|2c 7d 9h Js Ac|703|0.10757575757575757
river|2c 7d 9h Js Ac|740|0.10757575757575757
river|2c 7d 9h Js Ac|777|0.6383838383838384
river|2c 7d 9h Js Ac|814|0.7383838383838384
river|2c 7d 9h Js Ac|851|0.5777777777777777
river|2c 7d 9h Js Ac|888|nan
river|2c 7d 9h Js Ac|925|0.9191919191919192
river|2c 7d 9h Js Ac|962|nan
river|2c 7d 9h Js Ac|999|0.8686868686868687
river|2c 7d 9h Js Ac|1036|0.7626262626262627
river|2c 7d 9h Js Ac|1073|nan
river|2c 7d 9h Js Ac|1110|nan
river|2c 7d 9h Js Ac|1147|0.36818181818181817
river|2c 7d 9h Js Ac|1184|0.36818181818181817
river|2c 7d 9h Js Ac|1221|0.9808080808080808
river|2c 7d 9h Js Ac|1258|nan
river|2c 7d 9h Js Ac|1295|0.8808080808080808
river|Ah Kh Qh 3d 3c|0|0.46616161616161617
river|Ah Kh Qh 3d 3c|37|0.2388888888888889
river|Ah Kh Qh 3d 3c|74|0.23333333333333334
river|Ah Kh Qh 3d 3c|111|0.23737373737373738
river|Ah Kh Qh 3d 3c|148|nan
river|Ah Kh Qh 3d 3c|185|0.23535353535353534
river|Ah Kh Qh 3d 3c|222|nan
river|Ah Kh Qh 3d 3c|259|nan
river|Ah Kh Qh 3d 3c|296|0.9126262626262627
river|Ah Kh Qh 3d 3c|333|0.990909090909091
river|Ah Kh Qh 3d 3c|370|nan
river|Ah Kh Qh 3d 3c|407|0.23535353535353534
river|Ah Kh Qh 3d 3c|444|0.23333333333333334
river|Ah Kh Qh 3d 3c|481|0.23737373737373738
river|Ah Kh Qh 3d 3c|518|0.23333333333333334
river|Ah Kh Qh 3d 3c|555|0.23737373737373738
river|Ah Kh Qh 3d 3c|592|0.23333333333333334
river|Ah Kh Qh 3d 3c|629|0.23737373737373738
river|Ah Kh Qh 3d 3c|666|0.23737373737373738
river|Ah Kh Qh 3d 3c|703|0.23333333333333334
river|Ah Kh Qh 3d 3c|740|0.23333333333333334
river|Ah Kh Qh 3d 3c|777|0.23737373737373738
river|Ah Kh Qh 3d 3c|814|0.23535353535353534
river|Ah Kh Qh 3d 3c|851|nan
river|Ah Kh Qh 3d 3c|888|0.806060606060606
river|Ah Kh Qh 3d 3c|925|0.23333333333333334
river|Ah Kh Qh 3d 3c|962|0.23535353535353534
river|Ah Kh Qh 3d 3c|999|nan
river|Ah Kh Qh 3d 3c|1036|0.2388888888888889
river|Ah Kh Qh 3d 3c|1073|0.5106060606060606
river|Ah Kh Qh 3d 3c|1110|nan
river|Ah Kh Qh 3d 3c|1147|0.694949494949495
river|Ah Kh Qh 3d 3c|1184|nan
river|Ah Kh Qh 3d 3c|1221|0.5297979797979798
river|Ah Kh Qh 3d 3c|1258|nan
river|Ah Kh Qh 3d 3c|1295|0.8474747474747475
river|5c 6d 7h 8s 9c|0|0.41414141414141414
river|5c 6d 7h 8s 9c|37|0.41414141414141414
river|5c 6d 7h 8s 9c|74|0.41414141414141414
river|5c 6d 7h 8s 9c|111|0.41414141414141414
river|5c 6d 7h 8s 9c|148|0.41414141414141414
river|5c 6d 7h 8s 9c|185|0.41414141414141414
river|5c 6d 7h 8s 9c|222|0.41414141414141414
river|5c 6d 7h 8s 9c|259|0.41414141414141414
river|5c 6d 7h 8s 9c|296|nan
river|5c 6d 7h 8s 9c|333|0.41414141414141414
river|5c 6d 7h 8s 9c|370|0.41414141414141414
river|5c 6d 7h 8s 9c|407|0.41414141414141414
river|5c 6d 7h 8s 9c|444|0.41414141414141414
river|5c 6d 7h 8s 9c|481|nan
river|5c 6d 7h 8s 9c|518|0.41414141414141414
river|5c 6d 7h 8s 9c|555|nan
river|5c 6d 7h 8s 9c|592|0.41414141414141414
river|5c 6d 7h 8s 9c|629|0.41414141414141414
river|5c 6d 7h 8s 9c|666|nan
river|5c 6d 7h 8s 9c|703|0.41414141414141414
river|5c 6d 7h 8s 9c|740|nan
river|5c 6d 7h 8s 9c|777|0.41414141414141414
river|5c 6d 7h 8s 9c|814|0.41414141414141414
river|5c 6d 7h 8s 9c|851|0.41414141414141414
river|5c 6d 7h 8s 9c|888|0.41414141414141414
river|5c 6d 7h 8s 9c|925|0.41414141414141414
river|5c 6d 7h 8s 9c|962|0.41414141414141414
river|5c 6d 7h 8s 9c|999|0.41414141414141414
river|5c 6d 7h 8s 9c|1036|nan
river|5c 6d 7h 8s 9c|1073|0.41414141414141414
river|5c 6d 7h 8s 9c|1110|0.41414141414141414
river|5c 6d 7h 8s 9c|1147|0.9287878787878788
river|5c 6d 7h 8s 9c|1184|0.9287878787878788
river|5c 6d 7h 8s 9c|1221|0.41414141414141414
river|5c 6d 7h 8s 9c|1258|0.41414141414141414
river|5c 6d 7h 8s 9c|1295|0.41414141414141414
river|2c 2d 2h 2s 9c|0|nan
river|2c 2d 2h 2s 9c|37|nan
river|2c 2d 2h 2s 9c|74|nan
river|2c 2d 2h 2s 9c|111|nan
river|2c 2d 2h 2s 9c|148|nan
river|2c 2d 2h 2s 9c|185|nan
river|2c 2d 2h 2s 9c|222|0.15151515151515152
river|2c 2d 2h 2s 9c|259|0.15151515151515152
river|2c 2d 2h 2s 9c|296|0.15151515151515152
river|2c 2d 2h 2s 9c|333|0.9348484848484848
river|2c 2d 2h 2s 9c|370|0.6196969696969697
river|2c 2d 2h 2s 9c|407|0.4863636363636364
river|2c 2d 2h 2s 9c|444|0.15151515151515152
river|2c 2d 2h 2s 9c|481|0.15151515151515152
river|2c 2d 2h 2s 9c|518|0.15151515151515152
river|2c 2d 2h 2s 9c|555|0.15151515151515152
river|2c 2d 2h 2s 9c|592|0.15151515151515152
river|2c 2d 2h 2s 9c|629|0.15151515151515152
river|2c 2d 2h 2s 9c|666|0.15151515151515152
river|2c 2d 2h 2s 9c|703|0.15151515151515152
river|2c 2d 2h 2s 9c|740|0.15151515151515152
river|2c 2d 2h 2s 9c|777|0.15151515151515152
river|2c 2d 2h 2s 9c|814|0.4863636363636364
river|2c 2d 2h 2s 9c|851|0.6196969696969697
river|2c 2d 2h 2s 9c|888|0.9348484848484848
river|2c 2d 2h 2s 9c|925|0.15151515151515152
river|2c 2d 2h 2s 9c|962|0.4863636363636364
river|2c 2d 2h 2s 9c|999|0.9348484848484848
river|2c 2d 2h 2s 9c|1036|0.4863636363636364
river|2c 2d 2h 2s 9c|1073|0.15151515151515152
river|2c 2d 2h 2s 9c|1110|0.7691919191919192
river|2c 2d 2h 2s 9c|1147|0.7691919191919192
river|2c 2d 2h 2s 9c|1184|0.7691919191919192
river|2c 2d 2h 2s 9c|1221|0.5015151515151515
river|2c 2d 2h 2s 9c|1258|0.9348484848484848
river|2c 2d 2h 2s 9c|1295|0.9348484848484848
turn|2c 7d 9h Js|0|nan
turn|2c 7d 9h Js|37|nan
turn|2c 7d 9h Js|74|0.5386034255599472
turn|2c 7d 9h Js|111|0.479534475186649
turn|2c 7d 9h Js|148|0.5209705753184014
turn|2c 7d 9h Js|185|nan
turn|2c 7d 9h Js|222|0.6864295125164691
turn|2c 7d 9h Js|259|0.5975186649099689
turn|2c 7d 9h Js|296|0.08557312252964441
turn|2c 7d 9h Js|333|0.3757575757575758
turn|2c 7d 9h Js|370|0.240052700922266
turn|2c 7d 9h Js|407|0.7772068511198944
turn|2c 7d 9h Js|444|0.6864295125164691
turn|2c 7d 9h Js|481|0.21598594642072894
turn|2c 7d 9h Js|518|0.21598594642072894
turn|2c 7d 9h Js|555|0.5996267018006145
turn|2c 7d 9h Js|592|nan
turn|2c 7d 9h Js|629|nan
turn|2c 7d 9h Js|666|0.5996267018006145
turn|2c 7d 9h Js|703|0.301010101010101
turn|2c 7d 9h Js|740|0.301010101010101
turn|2c 7d 9h Js|777|0.6906455862977604
turn|2c 7d 9h Js|814|0.7814229249011856
turn|2c 7d 9h Js|851|0.6391084760649978
turn|2c 7d 9h Js|888|nan
turn|2c 7d 9h Js|925|0.8798638559508126
turn|2c 7d 9h Js|962|nan
turn|2c 7d 9h Js|999|0.46594202898550746
turn|2c 7d 9h Js|1036|0.8202459376372417
turn|2c 7d 9h Js|1073|nan
turn|2c 7d 9h Js|1110|nan
turn|2c 7d 9h Js|1147|0.4802810715854193
turn|2c 7d 9h Js|1184|0.4802810715854193
turn|2c 7d 9h Js|1221|0.9508783487044354
turn|2c 7d 9h Js|1258|nan
turn|2c 7d 9h Js|1295|0.4413043478260871
turn|Ah Kh Qh 3d|0|0.35591787439613537
turn|Ah Kh Qh 3d|37|0.5167105841018881
turn|Ah Kh Qh 3d|74|0.16058410188844977
turn|Ah Kh Qh 3d|111|0.2638010540184452
turn|Ah Kh Qh 3d|148|nan
turn|Ah Kh Qh 3d|185|0.360243741765481
turn|Ah Kh Qh 3d|222|0.4336956521739129
turn|Ah Kh Qh 3d|259|nan
turn|Ah Kh Qh 3d|296|0.5306543697848045
turn|Ah Kh Qh 3d|333|0.8467281510759769
turn|Ah Kh Qh 3d|370|nan
turn|Ah Kh Qh 3d|407|0.365316205533597
turn|Ah Kh Qh 3d|444|0.2108146684233641
turn|Ah Kh Qh 3d|481|0.2975406236275803
turn|Ah Kh Qh 3d|518|0.1656565656565657
turn|Ah Kh Qh 3d|555|0.2864075537988581
turn|Ah Kh Qh 3d|592|0.13057751427316636
turn|Ah Kh Qh 3d|629|0.2725625823451912
turn|Ah Kh Qh 3d|666|0.2864075537988581
turn|Ah Kh Qh 3d|703|0.16918093983311383
turn|Ah Kh Qh 3d|740|0.16918093983311383
turn|Ah Kh Qh 3d|777|0.3557751427316642
turn|Ah Kh Qh 3d|814|0.36884057971014506
turn|Ah Kh Qh 3d|851|nan
turn|Ah Kh Qh 3d|888|0.7314009661835751
turn|Ah Kh Qh 3d|925|0.218522178304787
turn|Ah Kh Qh 3d|962|0.3784914361001318
turn|Ah Kh Qh 3d|999|nan
turn|Ah Kh Qh 3d|1036|0.5328063241106716
turn|Ah Kh Qh 3d|1073|0.626932367149758
turn|Ah Kh Qh 3d|1110|nan
turn|Ah Kh Qh 3d|1147|0.7005819060166887
turn|Ah Kh Qh 3d|1184|nan
turn|Ah Kh Qh 3d|1221|0.6952459376372423
turn|Ah Kh Qh 3d|1258|nan
turn|Ah Kh Qh 3d|1295|0.8202678963548528
turn|4s 4h 5c 9d|0|0.46987263943785706
turn|4s 4h 5c 9d|37|0.2602547211242862
turn|4s 4h 5c 9d|74|0.14779314888010536
turn|4s 4h 5c 9d|111|0.6132850241545896
turn|4s 4h 5c 9d|148|0.543566095740009
turn|4s 4h 5c 9d|185|0.2602547211242862
turn|4s 4h 5c 9d|222|nan
turn|4s 4h 5c 9d|259|0.20018664909969275
turn|4s 4h 5c 9d|296|nan
turn|4s 4h 5c 9d|333|0.5450153711023278
turn|4s 4h 5c 9d|370|0.32911725955204213
turn|4s 4h 5c 9d|407|0.9440382081686424
turn|4s 4h 5c 9d|444|0.9852876592007018
turn|4s 4h 5c 9d|481|nan
turn|4s 4h 5c 9d|518|nan
turn|4s 4h 5c 9d|555|nan
turn|4s 4h 5c 9d|592|0.6307422046552479
turn|4s 4h 5c 9d|629|0.6307422046552479
turn|4s 4h 5c 9d|666|0.6307422046552479
turn|4s 4h 5c 9d|703|0.23932806324110664
turn|4s 4h 5c 9d|740|0.23932806324110664
turn|4s 4h 5c 9d|777|0.7615063680281071
turn|4s 4h 5c 9d|814|0.2727492314448835
turn|4s 4h 5c 9d|851|0.3426657883179622
turn|4s 4h 5c 9d|888|0.5094642072902944
turn|4s 4h 5c 9d|925|nan
turn|4s 4h 5c 9d|962|0.27933684672815096
turn|4s 4h 5c 9d|999|0.5135485287659202
turn|4s 4h 5c 9d|1036|0.27933684672815096
turn|4s 4h 5c 9d|1073|nan
turn|4s 4h 5c 9d|1110|0.8037329819938519
turn|4s 4h 5c 9d|1147|0.4512296881862101
turn|4s 4h 5c 9d|1184|0.4512296881862101
turn|4s 4h 5c 9d|1221|0.8342995169082121
turn|4s 4h 5c 9d|1258|0.548199385155907
turn|4s 4h 5c 9d|1295|0.5570267896354852
flop|2c 7d 9h|0|nan
flop|2c 7d 9h|37|nan
flop|2c 7d 9h|74|0.5819640852974186
flop|2c 7d 9h|111|0.5440852974186304
flop|2c 7d 9h|148|0.5702823691460055
flop|2c 7d 9h|185|0.5577216610549945
flop|2c 7d 9h|222|0.765590689503733
flop|2c 7d 9h|259|0.6670072821235614
flop|2c 7d 9h|296|0.1875573921028467
flop|2c 7d 9h|333|0.4259689922480621
flop|2c 7d 9h|370|0.3748441865463144
flop|2c 7d 9h|407|0.2964975845410627
flop|2c 7d 9h|444|0.7508838383838387
flop|2c 7d 9h|481|0.20654269972451791
flop|2c 7d 9h|518|0.2115151515151515
flop|2c 7d 9h|555|0.6695133149678604
flop|2c 7d 9h|592|nan
flop|2c 7d 9h|629|nan
flop|2c 7d 9h|666|0.681796223100571
flop|2c 7d 9h|703|0.4881930415263751
flop|2c 7d 9h|740|0.45664787408973473
flop|2c 7d 9h|777|0.7494490358126723
flop|2c 7d 9h|814|0.28368794326241137
flop|2c 7d 9h|851|0.7234738691260432
flop|2c 7d 9h|888|nan
flop|2c 7d 9h|925|0.919170427681066
flop|2c 7d 9h|962|0.4276094276094276
flop|2c 7d 9h|999|0.4894612794612796
flop|2c 7d 9h|1036|0.43168350168350167
flop|2c 7d 9h|1073|nan
flop|2c 7d 9h|1110|nan
flop|2c 7d 9h|1147|0.4803030303030301
flop|2c 7d 9h|1184|0.4332491582491582
flop|2c 7d 9h|1221|0.7995536762978621
flop|2c 7d 9h|1258|0.5013614404918751
flop|2c 7d 9h|1295|0.4838624338624339
flop|Ah Kh Qh|0|0.3845005611672277
flop|Ah Kh Qh|37|0.6049012855831036
flop|Ah Kh Qh|74|0.1999060371153395
flop|Ah Kh Qh|111|0.3385600187925768
flop|Ah Kh Qh|148|nan
flop|Ah Kh Qh|185|0.40133247367289926
flop|Ah Kh Qh|222|0.2658136924803592
flop|Ah Kh Qh|259|0.19955106621773283
flop|Ah Kh Qh|296|0.36265920070267893
flop|Ah Kh Qh|333|0.7539506172839507
flop|Ah Kh Qh|370|nan
flop|Ah Kh Qh|407|0.37973210364514715
flop|Ah Kh Qh|444|0.25534894398530766
flop|Ah Kh Qh|481|0.4064689447668171
flop|Ah Kh Qh|518|0.22405162738496073
flop|Ah Kh Qh|555|0.4279012345679011
flop|Ah Kh Qh|592|0.17280583613916942
flop|Ah Kh Qh|629|0.41001504405759714
flop|Ah Kh Qh|666|0.4279012345679011
flop|Ah Kh Qh|703|0.2271829405162739
flop|Ah Kh Qh|740|0.23657224418093983
flop|Ah Kh Qh|777|0.488080808080808
flop|Ah Kh Qh|814|0.3927048260381594
flop|Ah Kh Qh|851|nan
flop|Ah Kh Qh|888|0.6752854633289417
flop|Ah Kh Qh|925|0.2668313570487484
flop|Ah Kh Qh|962|0.39337121212121207
flop|Ah Kh Qh|999|nan
flop|Ah Kh Qh|1036|0.6111784511784509
flop|Ah Kh Qh|1073|0.7066301310982159
flop|Ah Kh Qh|1110|nan
flop|Ah Kh Qh|1147|0.6707185491276402
flop|Ah Kh Qh|1184|nan
flop|Ah Kh Qh|1221|0.7432581630256053
flop|Ah Kh Qh|1258|nan
flop|Ah Kh Qh|1295|0.7712121212121212
flop|4s 4h 5c|0|0.49994388327721667
flop|4s 4h 5c|37|0.35960693895476503
flop|4s 4h 5c|74|0.24388066713648116
flop|4s 4h 5c|111|0.6340852974186308
flop|4s 4h 5c|148|0.6100550964187328
flop|4s 4h 5c|185|0.37140974967061924
flop|4s 4h 5c|222|0.2868227731864094
flop|4s 4h 5c|259|0.27913580246913594
flop|4s 4h 5c|296|nan
flop|4s 4h 5c|333|0.5749885215794307
flop|4s 4h 5c|370|0.43212980872555334
flop|4s 4h 5c|407|0.9050505050505049
flop|4s 4h 5c|444|0.8974517906336087
flop|4s 4h 5c|481|nan
flop|4s 4h 5c|518|nan
flop|4s 4h 5c|555|nan
flop|4s 4h 5c|592|0.651278744895766
flop|4s 4h 5c|629|0.6368799102132433
flop|4s 4h 5c|666|0.6471829405162736
flop|4s 4h 5c|703|0.3988888888888891
flop|4s 4h 5c|740|0.3892757360842469
flop|4s 4h 5c|777|0.30991021324354645
flop|4s 4h 5c|814|0.38307519640852983
flop|4s 4h 5c|851|0.44848484848484854
flop|4s 4h 5c|888|0.5347681359044996
flop|4s 4h 5c|925|0.28080808080808084
flop|4s 4h 5c|962|0.3893939393939394
flop|4s 4h 5c|999|0.5598370064279157
flop|4s 4h 5c|1036|0.3882226520524394
flop|4s 4h 5c|1073|0.7404918752744839
flop|4s 4h 5c|1110|0.5265095398428733
flop|4s 4h 5c|1147|0.48873176206509533
flop|4s 4h 5c|1184|0.4780904280904282
flop|4s 4h 5c|1221|0.7526427061310781
flop|4s 4h 5c|1258|0.5707839262187087
flop|4s 4h 5c|1295|0.5630952380952381