From ac1963208d4d025d52877c65e55c4d3f4002f614 Mon Sep 17 00:00:00 2001 From: Marc Mintel Date: Sat, 5 Dec 2026 22:52:18 +0100 Subject: [PATCH] vorflop-allin-tafel: precomputed preflop all-in table (VALLIN01 format, strict start-check reader, traegt helper, builder with node/class counting, coverage mapping of real requests by seat) Per all-in node and class with table jam mass: all-in minus best other move in bb with 95 % bounds, against the table continuation (seed A picks, seed B values) and against the best response of the opponents (seed C, exact ruft_bestantwort for the jam). Not wired into the probe (consumer does that). Co-Authored-By: Claude Opus 5.5 --- entscheiden/motor/src/main.rs | 55 +- entscheiden/motor/src/vorflop_allin_tafel.rs | 392 ++++++++++ .../motor/src/vorflop_allin_tafel_bauen.rs | 668 ++++++++++++++++++ .../motor/src/vorflop_selbst_br_nach.rs | 2 +- entscheiden/motor/src/vorflop_selbst_werte.rs | 14 +- 5 files changed, 1122 insertions(+), 9 deletions(-) create mode 100644 entscheiden/motor/src/vorflop_allin_tafel.rs create mode 100644 entscheiden/motor/src/vorflop_allin_tafel_bauen.rs diff --git a/entscheiden/motor/src/main.rs b/entscheiden/motor/src/main.rs index c4c93df3..3c848dbb 100644 --- a/entscheiden/motor/src/main.rs +++ b/entscheiden/motor/src/main.rs @@ -58,6 +58,8 @@ mod bedarf; mod exakt; mod river_wert; mod vorflop_allin; +mod vorflop_allin_tafel; +mod vorflop_allin_tafel_bauen; mod vorflop_jamprobe; mod vorflop_selbst; mod vorflop_selbst_archiv; @@ -229,7 +231,7 @@ fn main() { } } // vorflop-selbst-eichen|bauen|knoten|vergleich ... (Beschreibung: docs/vorflop_selbst.md) - w @ ("vorflop-selbst-eichen" | "vorflop-selbst-bauen" | "vorflop-selbst-knoten" | "vorflop-selbst-vergleich" | "vorflop-selbst-diagnose" | "vorflop-selbst-archiv" | "vorflop-selbst-lage" | "vorflop-selbst-fehler" | "vorflop-selbst-werte" | "vorflop-selbst-br-nach") => { + w @ ("vorflop-selbst-eichen" | "vorflop-selbst-bauen" | "vorflop-selbst-knoten" | "vorflop-selbst-vergleich" | "vorflop-selbst-diagnose" | "vorflop-selbst-archiv" | "vorflop-selbst-lage" | "vorflop-selbst-fehler" | "vorflop-selbst-werte" | "vorflop-selbst-br-nach" | "vorflop-allin-tafel-bauen" | "vorflop-allin-tafel-abdeckung") => { let kl = |k: &str| klassen::Klassen::lade(&format!("{}/klassen-{k}.bin", a[3])); let t = lernen::Tabellen { bretter: klassen::Bretter::neu(), kl: [kl(&a[4]), kl(&a[5])] }; // Der Vergleich ruft die Live-Suche des Dienstes: Motor mit "genau" (Flop/Turn/River exakt), Schalter wie im Livebetrieb ueber die Umgebung @@ -340,6 +342,57 @@ fn main() { let seeds = vorflop_selbst_br_nach::Seeds::derive(kvf(9, "saat", vorflop_selbst_rechnen::SAAT_B as f64) as u64); vorflop_selbst_br_nach::br_nach(&m, &a[7], &a[8], &prm, &seeds, mit_suche); } + // vorflop-allin-tafel-bauen ... [faeden=16] [n_max=4096] [saat_a=..] [saat_b=..] [saat_c=..] [modus=tafel] [rmin=0.02] [n_wahl=] [stand=] [grenze=] [nur_zaehlen=1] [rate=] + // (vorflop_allin_tafel_bauen.rs; Format und Leser: vorflop_allin_tafel.rs) + "vorflop-allin-tafel-bauen" => { + assert_eq!(kv(8, "modus").as_deref().unwrap_or("tafel"), "tafel", "only modus=tafel is built"); + let n_max = kvf(8, "n_max", 4096.0) as u32; + let p = vorflop_allin_tafel_bauen::Parameter { + faeden: kvf(8, "faeden", 16.0) as usize, + n_max, + n_wahl: kvf(8, "n_wahl", n_max as f64) as u32, + saat_a: kvf(8, "saat_a", 0x5E1B_A11u64 as f64) as u64, + saat_b: kvf(8, "saat_b", 0xA2C1_B22u64 as f64) as u64, + saat_c: kvf(8, "saat_c", 0xC0DE_C33u64 as f64) as u64, + rmin: kvf(8, "rmin", 0.02) as f32, + stand: kv(8, "stand").unwrap_or_else(|| "unbekannt".into()), + baum_sha256: vorflop_allin_tafel::baum_sha256_hex(&std::fs::read(&a[6]).unwrap_or_else(|e| panic!("{}: {e}", a[6]))), + grenze: kv(8, "grenze").map(|g| g.parse().expect("grenze: Zahl")), + }; + if kvf(8, "nur_zaehlen", 0.0) != 0.0 { + let mut k = vorflop_allin_tafel_bauen::jam_knoten(&r); + k.truncate(p.grenze.unwrap_or(usize::MAX)); + let zl = vorflop_allin_tafel_bauen::zaehle(&r, &k, &p); + print!("{}", vorflop_allin_tafel_bauen::zaehl_bericht(&zl, &p, p.faeden, kvf(8, "rate", vorflop_allin_tafel_bauen::RATE_STANDARD))); + } else { + vorflop_allin_tafel_bauen::bauen(&r, &a[7], &p); + } + } + // vorflop-allin-tafel-abdeckung ... ein=[,..] [tafel=]: echte Vorflop-Anfragen je Lage (Sitze) gegen die Zeilen der Tafel (oder den Plan) + "vorflop-allin-tafel-abdeckung" => { + use vorflop_allin_tafel_bauen as vb; + let knoten: std::collections::HashMap> = vorflop_selbst_rechnen::knoten_liste(&m.s).into_iter().collect(); + let jk = vb::jam_knoten(&r); + let karte = vb::jam_klassen_karte(&jk); + let abgedeckt: std::collections::HashSet<(u64, u16)> = match kv(8, "tafel") { + Some(f) => { + let bytes = std::fs::read(&a[6]).unwrap(); + let (t, meldung) = vorflop_allin_tafel::pruefe_start(&f, &bytes).unwrap_or_else(|e| panic!("{e}")); + println!("tafel: {meldung}"); + t.zeilen.iter().map(|z| (z.key, z.klasse)).collect() + } + None => jk.iter().flat_map(|k| k.klassen.iter().map(move |&c| (k.key, c as u16))).collect(), + }; + let mut md = format!("Abdeckung der Vorflop-All-in-Tafel durch echte Anfragen ({} All-in-Knoten, {} Paare Knoten x Klasse; {}).\n\n", jk.len(), jk.iter().map(|k| k.klassen.len()).sum::(), if kv(8, "tafel").is_some() { "Zeilen der Tafeldatei" } else { "Plan: alle Paare mit All-in-Masse" }); + for f in kv(8, "ein").expect("ein=[,] fehlt").split(',') { + let ab = vb::abdeckung(&m, f, &knoten, &karte, &abgedeckt); + println!("abdeckung {f}: {} Vorflop, {} treu, {} abgedeckt", ab.preflop, ab.treu, ab.summe.abgedeckt); + md.push_str(&vb::abdeckung_markdown(f, &ab)); + } + assert!(!std::path::Path::new(&a[7]).exists(), "{} existiert schon (nie ueberschreiben)", a[7]); + std::fs::write(format!("{}.neu", a[7]), md).unwrap(); + std::fs::rename(format!("{}.neu", a[7]), &a[7]).unwrap(); + } // diagnose ... [faeden=24] [knoten=6] [je=6] [m=40] [grenze=840] [klassen=..] [modus=suche|aa] (aa: Dienst antwortet mit dem Tafelzug) "vorflop-selbst-diagnose" => { let klassen: Vec = kv(9, "klassen").unwrap_or_else(|| "T6s,86s,AKs,22,J9s,KQo".into()).split(',').map(str::to_string).collect(); diff --git a/entscheiden/motor/src/vorflop_allin_tafel.rs b/entscheiden/motor/src/vorflop_allin_tafel.rs new file mode 100644 index 00000000..828beb3d --- /dev/null +++ b/entscheiden/motor/src/vorflop_allin_tafel.rs @@ -0,0 +1,392 @@ +//! Precomputed preflop all-in table (format VALLIN01): per (tree node, class) the value of our all-in minus the best other move, in bb, with two-sided 95 % bounds, +//! on two sides: `tafel` (opponents continue with the table) and `bestantwort` (opponents answer with their best response; `vorflop_selbst_br_nach.rs`). +//! Pure module: format, writer, strict reader with start check, lookup, decision helper `traegt`, TSV dump. No environment is read here; the builder is +//! `vorflop_allin_tafel_bauen.rs`. NOT wired into the all-in probe (the consuming session does that, switch name proposed: MOTOR_ALLIN_PROBE_VORFLOP=). +//! +//! Layout (little endian, like the sidecar `vorflop_selbst.rs`): +//! header: magic "VALLIN01" (8) | 5 strings (u8 length + UTF-8): format name, source commit(s), mode, game id, SHA256 hex of the tree strategy file +//! | u16 format version | u64 seed A (choice of the best other move, table side) | u64 seed B (valuation, table side) | u64 seed C (choice of the best +//! other move, best-response side) | u32 n_max (hands per sample) | u32 n_choice (hands per opponent node and class) | f32 rmin (reach cut) | u32 rows +//! row (32 bytes): u64 node key | u16 class (0..168) | u32 n (hands of the valuation) | u8 best other move (table side, menu code) | u8 best other move +//! (best-response side, menu code) | f32 tafel lower | f32 tafel upper | f32 bestantwort lower | f32 bestantwort upper +//! Rows are strictly increasing by (key, class), so the file length is exactly header + rows * 32 and lookup is a binary search. +use crate::karten::vorflop_name; +use crate::spiel::ALLIN; +use crate::vorflop_selbst_filter::{hex, sha256}; + +pub const MAGIE: &[u8; 8] = b"VALLIN01"; +pub const FORMAT_NAME: &str = "VALLIN"; +pub const FORMAT_VERSION: u16 = 1; +pub const ZEILE_BYTES: usize = 32; +const KLASSEN: u16 = 169; +/// Largest menu code of a real move (the all-in itself is excluded as "best other move"). +const CODE_MAX: u8 = ALLIN - 1; + +#[derive(Clone, Debug, PartialEq)] +pub struct Kopf { + pub format: String, + pub version: u16, + /// source commit(s) of the executable + pub stand: String, + pub modus: String, + pub spiel_id: String, + /// SHA256 (hex, 64 characters) of the tree strategy file the rows were computed against + pub baum_sha256: String, + pub saat_a: u64, + pub saat_b: u64, + pub saat_c: u64, + pub n_max: u32, + pub n_wahl: u32, + pub rmin: f32, + pub zeilen: u32, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Zeile { + pub key: u64, + pub klasse: u16, + pub n: u32, + pub bester_tafel: u8, + pub bester_br: u8, + pub tafel_unten: f32, + pub tafel_oben: f32, + pub br_unten: f32, + pub br_oben: f32, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Tafel { + pub kopf: Kopf, + pub zeilen: Vec, +} + +/// The all-in carries only if it beats the best other move against the table continuation AND against the best response (both lower bounds above 0). +pub fn traegt(e: &Zeile) -> bool { + e.tafel_unten > 0.0 && e.br_unten > 0.0 +} + +pub fn baum_sha256_hex(baum_bytes: &[u8]) -> String { + hex(&sha256(baum_bytes)) +} + +fn kopf_bytes(k: &Kopf) -> Vec { + let mut o = MAGIE.to_vec(); + for t in [&k.format, &k.stand, &k.modus, &k.spiel_id, &k.baum_sha256] { + assert!(t.len() <= 255, "header text too long: {t}"); + o.push(t.len() as u8); + o.extend_from_slice(t.as_bytes()); + } + o.extend_from_slice(&k.version.to_le_bytes()); + for s in [k.saat_a, k.saat_b, k.saat_c] { + o.extend_from_slice(&s.to_le_bytes()); + } + o.extend_from_slice(&k.n_max.to_le_bytes()); + o.extend_from_slice(&k.n_wahl.to_le_bytes()); + o.extend_from_slice(&k.rmin.to_le_bytes()); + o.extend_from_slice(&k.zeilen.to_le_bytes()); + o +} + +fn zeile_bytes(z: &Zeile) -> [u8; ZEILE_BYTES] { + let mut o = [0u8; ZEILE_BYTES]; + o[0..8].copy_from_slice(&z.key.to_le_bytes()); + o[8..10].copy_from_slice(&z.klasse.to_le_bytes()); + o[10..14].copy_from_slice(&z.n.to_le_bytes()); + o[14] = z.bester_tafel; + o[15] = z.bester_br; + for (i, x) in [z.tafel_unten, z.tafel_oben, z.br_unten, z.br_oben].iter().enumerate() { + o[16 + 4 * i..20 + 4 * i].copy_from_slice(&x.to_le_bytes()); + } + o +} + +/// Serialises the table. Panics if the rows are not strictly increasing by (key, class) or the row count in the header is wrong (programming errors of the builder). +pub fn schreibe(t: &Tafel) -> Vec { + assert_eq!(t.kopf.zeilen as usize, t.zeilen.len(), "row count in the header"); + assert!(t.zeilen.windows(2).all(|w| (w[0].key, w[0].klasse) < (w[1].key, w[1].klasse)), "rows must be strictly increasing by (key, class)"); + let mut o = kopf_bytes(&t.kopf); + for z in &t.zeilen { + o.extend_from_slice(&zeile_bytes(z)); + } + o +} + +struct Leser<'a> { + b: &'a [u8], + p: usize, +} + +impl<'a> Leser<'a> { + fn nimm(&mut self, n: usize) -> Result<&'a [u8], String> { + let s = self.b.get(self.p..self.p + n).ok_or_else(|| format!("header truncated at byte {}", self.p))?; + self.p += n; + Ok(s) + } + fn text(&mut self) -> Result { + let n = self.nimm(1)?[0] as usize; + String::from_utf8(self.nimm(n)?.to_vec()).map_err(|_| "header text is not UTF-8".to_string()) + } + fn u16(&mut self) -> Result { + Ok(u16::from_le_bytes(self.nimm(2)?.try_into().unwrap())) + } + fn u32(&mut self) -> Result { + Ok(u32::from_le_bytes(self.nimm(4)?.try_into().unwrap())) + } + fn u64(&mut self) -> Result { + Ok(u64::from_le_bytes(self.nimm(8)?.try_into().unwrap())) + } + fn f32(&mut self) -> Result { + Ok(f32::from_le_bytes(self.nimm(4)?.try_into().unwrap())) + } +} + +fn pruefe_zeile(z: &Zeile, i: usize) -> Result<(), String> { + let fehler = |was: &str| Err(format!("row {i} (key {:016x}, class {}): {was}", z.key, z.klasse)); + if z.klasse >= KLASSEN { + return fehler("class out of range"); + } + if z.n == 0 { + return fehler("n is 0"); + } + for (name, code) in [("best other move (table)", z.bester_tafel), ("best other move (best response)", z.bester_br)] { + if code > CODE_MAX { + return fehler(&format!("{name}: menu code {code} is not a move other than the all-in")); + } + } + for (name, u, o) in [("tafel", z.tafel_unten, z.tafel_oben), ("bestantwort", z.br_unten, z.br_oben)] { + if !u.is_finite() || !o.is_finite() { + return fehler(&format!("{name}: bound is not finite")); + } + if u > o { + return fehler(&format!("{name}: lower bound {u} above upper bound {o}")); + } + } + Ok(()) +} + +/// Strict reading for the start check: magic, format name and version, SHA256 of the tree file against `erwartete_baum_sha256`, exact length, every row well formed, +/// rows strictly increasing. Err with the reason otherwise. +pub fn lies_streng(b: &[u8], erwartete_baum_sha256: &str) -> Result { + if b.len() < 8 || &b[..8] != MAGIE { + return Err("bad magic: not a VALLIN01 file".into()); + } + let mut l = Leser { b, p: 8 }; + let (format, stand, modus, spiel_id, baum_sha256) = (l.text()?, l.text()?, l.text()?, l.text()?, l.text()?); + let version = l.u16()?; + let (saat_a, saat_b, saat_c) = (l.u64()?, l.u64()?, l.u64()?); + let (n_max, n_wahl, rmin, zeilen) = (l.u32()?, l.u32()?, l.f32()?, l.u32()?); + if format != FORMAT_NAME || version != FORMAT_VERSION { + return Err(format!("unknown format {format} v{version} (expected {FORMAT_NAME} v{FORMAT_VERSION})")); + } + if baum_sha256 != erwartete_baum_sha256 { + return Err(format!("tree SHA256 mismatch: table was computed against {baum_sha256}, loaded strategy is {erwartete_baum_sha256}")); + } + if saat_a == saat_b || saat_a == saat_c || saat_b == saat_c { + return Err("seeds A, B, C are not pairwise different (selection and valuation would not be independent)".into()); + } + let rest = b.len() - l.p; + let erwartet = zeilen as usize * ZEILE_BYTES; + if rest != erwartet { + return Err(format!("length mismatch: header says {zeilen} rows ({erwartet} bytes), file has {rest} bytes after the header{}", if rest < erwartet { " (truncated row or file)" } else { "" })); + } + let mut out = Vec::with_capacity(zeilen as usize); + for (i, c) in b[l.p..].chunks_exact(ZEILE_BYTES).enumerate() { + let f = |o: usize| f32::from_le_bytes(c[o..o + 4].try_into().unwrap()); + let z = Zeile { + key: u64::from_le_bytes(c[0..8].try_into().unwrap()), + klasse: u16::from_le_bytes(c[8..10].try_into().unwrap()), + n: u32::from_le_bytes(c[10..14].try_into().unwrap()), + bester_tafel: c[14], + bester_br: c[15], + tafel_unten: f(16), + tafel_oben: f(20), + br_unten: f(24), + br_oben: f(28), + }; + pruefe_zeile(&z, i)?; + if let Some(v) = out.last().map(|v: &Zeile| (v.key, v.klasse)) { + if v >= (z.key, z.klasse) { + return Err(format!("row {i}: rows are not strictly increasing by (key, class)")); + } + } + out.push(z); + } + Ok(Tafel { kopf: Kopf { format, version, stand, modus, spiel_id, baum_sha256, saat_a, saat_b, saat_c, n_max, n_wahl, rmin, zeilen }, zeilen: out }) +} + +/// Start check from a file: reads it, validates against the SHA256 of the loaded tree strategy file; the message names both SHA256 for the start log. +pub fn pruefe_start(pfad: &str, baum_bytes: &[u8]) -> Result<(Tafel, String), String> { + let b = std::fs::read(pfad).map_err(|e| format!("{pfad}: {e}"))?; + let baum = baum_sha256_hex(baum_bytes); + let t = lies_streng(&b, &baum).map_err(|e| format!("{pfad}: {e}"))?; + let meldung = format!("vallin_sha256={} baum_sha256={baum} zeilen={} stand={}", hex(&sha256(&b)), t.zeilen.len(), t.kopf.stand); + Ok((t, meldung)) +} + +impl Tafel { + pub fn eintrag(&self, key: u64, klasse: usize) -> Option<&Zeile> { + let k = (key, u16::try_from(klasse).ok()?); + self.zeilen.binary_search_by(|z| (z.key, z.klasse).cmp(&k)).ok().map(|i| &self.zeilen[i]) + } + + /// (tafel lower, tafel upper, best-response lower, best-response upper, best other move = menu code of the table side) + pub fn lookup(&self, key: u64, klasse: usize) -> Option<(f32, f32, f32, f32, u8)> { + self.eintrag(key, klasse).map(|z| (z.tafel_unten, z.tafel_oben, z.br_unten, z.br_oben, z.bester_tafel)) + } +} + +/// Readable dump, one line per row, header as `#` lines. +pub fn tsv(t: &Tafel) -> String { + let k = &t.kopf; + let mut o = format!( + "# {} v{} stand={} modus={} spiel={} baum_sha256={}\n# saat_a={:#x} saat_b={:#x} saat_c={:#x} n_max={} n_wahl={} rmin={} zeilen={}\n", + k.format, k.version, k.stand, k.modus, k.spiel_id, k.baum_sha256, k.saat_a, k.saat_b, k.saat_c, k.n_max, k.n_wahl, k.rmin, k.zeilen + ); + o.push_str("key\tklasse\tklasse_name\tn\tbester_tafel\tbester_br\ttafel_unten\ttafel_oben\tbr_unten\tbr_oben\ttraegt\n"); + for z in &t.zeilen { + o.push_str(&format!( + "{:016x}\t{}\t{}\t{}\t{}\t{}\t{:.4}\t{:.4}\t{:.4}\t{:.4}\t{}\n", + z.key, z.klasse, vorflop_name(z.klasse as usize), z.n, z.bester_tafel, z.bester_br, z.tafel_unten, z.tafel_oben, z.br_unten, z.br_oben, traegt(z) as u8 + )); + } + o +} + +#[cfg(test)] +mod spec { + use super::*; + + fn kopf(zeilen: u32, baum: &str) -> Kopf { + Kopf { format: FORMAT_NAME.into(), version: FORMAT_VERSION, stand: "abc123;def456".into(), modus: "tafel".into(), spiel_id: "NurVorflop-n6".into(), baum_sha256: baum.into(), saat_a: 1, saat_b: 2, saat_c: 3, n_max: 4096, n_wahl: 4096, rmin: 0.02, zeilen } + } + + fn zeile(key: u64, klasse: u16) -> Zeile { + Zeile { key, klasse, n: 4096, bester_tafel: 1, bester_br: 0, tafel_unten: 0.5, tafel_oben: 1.5, br_unten: -0.25, br_oben: 0.75 } + } + + fn tafel() -> (Tafel, String) { + let baum = baum_sha256_hex(b"tree bytes"); + let zeilen = vec![zeile(7, 0), zeile(7, 12), zeile(9, 3)]; + (Tafel { kopf: kopf(3, &baum), zeilen }, baum) + } + + #[test] + fn format_round_trip_keeps_header_and_rows() { + let (t, baum) = tafel(); + let b = schreibe(&t); + assert_eq!(&b[..8], MAGIE); + assert_eq!(lies_streng(&b, &baum).unwrap(), t); + } + + #[test] + fn lookup_finds_exact_rows_only() { + let (t, _) = tafel(); + assert_eq!(t.lookup(7, 12), Some((0.5, 1.5, -0.25, 0.75, 1))); + assert_eq!(t.lookup(7, 1), None); + assert_eq!(t.lookup(8, 0), None); + assert_eq!(t.lookup(7, 70000), None); + } + + #[test] + fn start_check_rejects_bad_magic() { + let (t, baum) = tafel(); + let mut b = schreibe(&t); + b[0] = b'X'; + assert!(lies_streng(&b, &baum).unwrap_err().contains("bad magic")); + assert!(lies_streng(b"VSELBS02....", &baum).unwrap_err().contains("bad magic")); + assert!(lies_streng(&[], &baum).unwrap_err().contains("bad magic")); + } + + #[test] + fn start_check_rejects_a_table_of_another_tree() { + let (t, _) = tafel(); + let e = lies_streng(&schreibe(&t), &baum_sha256_hex(b"another tree")).unwrap_err(); + assert!(e.contains("tree SHA256 mismatch"), "{e}"); + } + + #[test] + fn start_check_rejects_truncated_rows_and_headers() { + let (t, baum) = tafel(); + let b = schreibe(&t); + for cut in [1, ZEILE_BYTES / 2, ZEILE_BYTES] { + let e = lies_streng(&b[..b.len() - cut], &baum).unwrap_err(); + assert!(e.contains("length mismatch"), "{e}"); + } + let mut lang = b.clone(); + lang.push(0); + assert!(lies_streng(&lang, &baum).unwrap_err().contains("length mismatch")); + assert!(lies_streng(&b[..20], &baum).unwrap_err().contains("truncated")); + } + + #[test] + fn start_check_rejects_malformed_rows() { + let (t, baum) = tafel(); + let mit = |f: &dyn Fn(&mut Zeile)| { + let mut x = t.clone(); + f(&mut x.zeilen[1]); + lies_streng(&schreibe(&x), &baum) + }; + assert!(mit(&|z| z.klasse = 169).unwrap_err().contains("class out of range")); + assert!(mit(&|z| z.n = 0).unwrap_err().contains("n is 0")); + assert!(mit(&|z| z.bester_br = ALLIN).unwrap_err().contains("other than the all-in")); + assert!(mit(&|z| z.tafel_unten = 9.0).unwrap_err().contains("above upper")); + assert!(mit(&|z| z.br_oben = f32::NAN).unwrap_err().contains("not finite")); + // the writer refuses unsorted rows, so a duplicate (key, class) is forged in the bytes + let mut b = schreibe(&t); + let o = b.len() - 2 * ZEILE_BYTES + 8; + b[o..o + 2].copy_from_slice(&0u16.to_le_bytes()); + assert!(lies_streng(&b, &baum).unwrap_err().contains("strictly increasing"), "duplicate key/class"); + let mut gleiche_saat = t.clone(); + gleiche_saat.kopf.saat_c = gleiche_saat.kopf.saat_a; + assert!(lies_streng(&schreibe(&gleiche_saat), &baum).unwrap_err().contains("pairwise different")); + } + + #[test] + fn start_check_rejects_unknown_format_version() { + let (mut t, baum) = tafel(); + t.kopf.version = 2; + assert!(lies_streng(&schreibe(&t), &baum).unwrap_err().contains("unknown format")); + } + + #[test] + #[should_panic(expected = "strictly increasing")] + fn writer_refuses_unsorted_rows() { + let (mut t, _) = tafel(); + t.zeilen.swap(0, 2); + schreibe(&t); + } + + #[test] + fn traegt_needs_both_lower_bounds_above_zero() { + let z = |t: f32, b: f32| Zeile { tafel_unten: t, tafel_oben: t + 1.0, br_unten: b, br_oben: b + 1.0, ..zeile(1, 0) }; + assert!(traegt(&z(0.1, 0.1))); + assert!(!traegt(&z(0.1, -0.1))); + assert!(!traegt(&z(-0.1, 0.1))); + assert!(!traegt(&z(-0.1, -0.1))); + assert!(!traegt(&z(0.0, 0.5)), "a lower bound of exactly 0 does not carry"); + assert!(!traegt(&z(0.5, 0.0))); + } + + #[test] + fn tsv_dump_has_one_line_per_row() { + let (t, _) = tafel(); + let s = tsv(&t); + assert_eq!(s.lines().filter(|l| !l.starts_with('#')).count(), 1 + t.zeilen.len()); + assert!(s.contains("0000000000000007\t12\t")); + } + + #[test] + fn pruefe_start_reads_a_file_and_names_both_hashes() { + let (t, _) = tafel(); + let baum_bytes = b"tree bytes"; + let t = Tafel { kopf: Kopf { baum_sha256: baum_sha256_hex(baum_bytes), ..t.kopf.clone() }, ..t }; + let pfad = std::env::temp_dir().join(format!("vallin-spec-{}.vallin", std::process::id())); + std::fs::write(&pfad, schreibe(&t)).unwrap(); + let (gelesen, meldung) = pruefe_start(pfad.to_str().unwrap(), baum_bytes).unwrap(); + assert_eq!(gelesen, t); + assert!(meldung.contains("vallin_sha256=") && meldung.contains(&format!("baum_sha256={}", baum_sha256_hex(baum_bytes))), "{meldung}"); + assert!(pruefe_start(pfad.to_str().unwrap(), b"other").is_err()); + std::fs::remove_file(&pfad).unwrap(); + assert!(pruefe_start(pfad.to_str().unwrap(), baum_bytes).unwrap_err().contains("vallin-spec")); + } +} diff --git a/entscheiden/motor/src/vorflop_allin_tafel_bauen.rs b/entscheiden/motor/src/vorflop_allin_tafel_bauen.rs new file mode 100644 index 00000000..bec2baa0 --- /dev/null +++ b/entscheiden/motor/src/vorflop_allin_tafel_bauen.rs @@ -0,0 +1,668 @@ +//! Builder of the preflop all-in table (format and reader: `vorflop_allin_tafel.rs`). +//! +//! For every preflop tree node where the table puts all-in mass on at least one class (a menu move that sets the whole stack, `Rolle::Jam`, with positive table +//! probability for a class that reaches the node) and for every such class the two sides of "all-in minus best other move" are computed: +//! * tafel: opponents continue with the table. Two seeds: A picks the best other move, B values (`vorflop_selbst_werte`: `werte_klasse`, `allin_gegen_bester`), 95 % two-sided. +//! * bestantwort: opponents answer with their best response (`vorflop_selbst_br_nach::node_br`; exact `ruft_bestantwort` where they only fold or call after our jam). Seed C +//! feeds the three independent streams of that module (choice of the opponents' action, valuation, choice of the best other move); mean -+ z SE, 95 % two-sided. +//! Subcommands (arguments as `key=value` from position 8): +//! `vorflop-allin-tafel-bauen [faeden=16] [n_max=4096] [saat_a=..] [saat_b=..] [saat_c=..] [modus=tafel] [rmin=0.02] [n_wahl=] +//! [stand=] [grenze=] [nur_zaehlen=1] [rate=]` +//! `vorflop-allin-tafel-abdeckung ein=[,..] [tafel=]` (coverage of real requests by seat) +//! The target is never overwritten (temp file, rename); partial results are appended per node to `.teil-NNNN` (a new file per start, old ones are only read) and a +//! restart continues with the nodes that are complete there. +use crate::dienst::Motor; +#[cfg(test)] +use crate::karten::*; +use crate::spiel::*; +use crate::vorflop_allin_tafel::*; +use crate::vorflop_allin_tafel::Kopf; +use crate::vorflop_selbst::*; +use crate::vorflop_selbst_br_nach as br; +use crate::vorflop_selbst_rechnen::*; +use crate::vorflop_selbst_werte::{abbilden, allin_gegen_bester, grenzen95, werte_klasse}; +use serde_json::Value; +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::io::Write; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering::Relaxed}; + +/// Marker class of the closing row of a node block in a partial file. +const ENDE_KLASSE: u16 = u16::MAX; +/// Throughput assumed for the cost estimate when `rate=` is not given: measured rollouts per second and thread of the tafel/BR rollouts on the Mac (loaded, one thread, top-reach nodes; the estimate formula matched the counted rollouts exactly on 3 nodes), see the farm job text. +pub const RATE_STANDARD: f64 = 300_000.0; +/// Seat names of the six-handed tree (tree seat index 0..5). +pub const SITZ_NAMEN: [&str; 6] = ["SB", "BB", "UTG", "HJ", "CO", "BTN"]; + +/// A node that has an all-in move with table mass, and the classes to compute there. +#[derive(Clone, Debug)] +pub struct JamKnoten { + pub key: u64, + pub codes: Vec, + /// menu index of the all-in move + pub jam: usize, + pub sitz: usize, + pub erreich: f64, + pub klassen: Vec, +} + +/// All nodes with all-in mass for at least one class that reaches the node. Order: descending reach (like `bauen`). +pub fn jam_knoten(r: &Rechner) -> Vec { + let mut out: Vec = vec![]; + for (key, codes) in knoten_liste(r.s) { + let pfad = pfad_aus_codes(r.s, &codes); + let z = zustand_nach(r.s, &pfad); + let m = z.menue(r.s); + let Some(jam) = rollen(&z, &m).iter().position(|x| *x == Rolle::Jam) else { continue }; + let rw = r.reichweite(&pfad); + let p = z.dran as usize; + let klassen: Vec = (0..KLASSEN).filter(|&c| rw.w[p][c] > 0.0 && r.st.hole(key, c, m.n).is_some_and(|v| v[jam] > 0.0)).collect(); + if !klassen.is_empty() { + out.push(JamKnoten { key, codes, jam, sitz: p, erreich: rw.erreich, klassen }); + } + } + out.sort_by(|a, b| b.erreich.partial_cmp(&a.erreich).unwrap().then(a.key.cmp(&b.key))); + out +} + +#[derive(Clone, Debug)] +pub struct Parameter { + pub faeden: usize, + pub n_max: u32, + pub n_wahl: u32, + pub saat_a: u64, + pub saat_b: u64, + pub saat_c: u64, + pub rmin: f32, + pub stand: String, + pub baum_sha256: String, + pub grenze: Option, +} + +impl Parameter { + fn kopf(&self, r: &Rechner, zeilen: u32) -> Kopf { + Kopf { + format: FORMAT_NAME.into(), + version: FORMAT_VERSION, + stand: self.stand.clone(), + modus: "tafel".into(), + spiel_id: spiel_id(r.s), + baum_sha256: self.baum_sha256.clone(), + saat_a: self.saat_a, + saat_b: self.saat_b, + saat_c: self.saat_c, + n_max: self.n_max, + n_wahl: self.n_wahl, + rmin: self.rmin, + zeilen, + } + } + fn br_parameter(&self) -> br::Params { + br::Params { n_choice: self.n_wahl as u64, n_value: self.n_max as u64, reach_min: self.rmin as f64, threads: 1, exact_jam: true, diagnose: false, exact_n: 20_000 } + } + /// Seeds A, B, C must be pairwise different. + fn pruefe_saaten(&self) -> Result<(), String> { + if self.saat_a == self.saat_b || self.saat_a == self.saat_c || self.saat_b == self.saat_c { + return Err(format!("seeds A {:#x}, B {:#x}, C {:#x} are not pairwise different", self.saat_a, self.saat_b, self.saat_c)); + } + Ok(()) + } +} + +fn f32_grenzen(d: f64, se: f64) -> Option<(f32, f32)> { + if !d.is_finite() || !se.is_finite() { + return None; + } + let (u, o) = grenzen95(d, se); + Some((u as f32, o as f32)) +} + +/// Rows of one node (classes without values are left out). Returns the rows and the number of rollouts spent. +pub fn rechne_knoten(r: &Rechner, jk: &JamKnoten, p: &Parameter) -> (Vec, u64) { + let pfad = pfad_aus_codes(r.s, &jk.codes); + let z = zustand_nach(r.s, &pfad); + let mz = z.menue(r.s); + let seeds = br::Seeds::derive(p.saat_c); + let nr = br::node_br(r, &pfad, &jk.klassen, &p.br_parameter(), &seeds, None); + let mut rollouts = nr.choice_rollouts + nr.value_rollouts; + let mut rows = vec![]; + for c in &nr.classes { + let Some(ad) = c.allin_minus_best_other.as_ref() else { continue }; + let Some((bu, bo)) = f32_grenzen(ad.diff.mean, ad.diff.se) else { continue }; + let va = werte_klasse(r, jk.key, c.class, &pfad, &z, Modus::Tafel, p.n_max as u64, p.saat_a); + let vb = werte_klasse(r, jk.key, c.class, &pfad, &z, Modus::Tafel, p.n_max as u64, p.saat_b); + rollouts += 2 * p.n_max as u64 * mz.n as u64; + let (Some((va, _, _)), Some((vb, kb, nb))) = (va, vb) else { continue }; + let Some(a) = allin_gegen_bester(&va, &vb, &kb, jk.jam) else { continue }; + let Some((tu, to)) = f32_grenzen(a.diff, a.se) else { continue }; + rows.push(Zeile { + key: jk.key, + klasse: c.class as u16, + n: nb.clamp(1, u32::MAX as u64) as u32, + bester_tafel: mz.z[a.bester].code, + bester_br: nr.moves[ad.best_other].code, + tafel_unten: tu, + tafel_oben: to, + br_unten: bu, + br_oben: bo, + }); + } + rows.sort_by_key(|z| z.klasse); + (rows, rollouts) +} + +// --------------------------------------------------------------------------------------------------------------------------------------------------- +// counting and cost estimate (no rollouts) + +#[derive(Clone, Debug, Default)] +pub struct Zaehlung { + pub knoten: usize, + pub paare: usize, + /// nodes and (node, class) pairs per tree seat + pub je_sitz: BTreeMap, + /// rollouts of the table side (2 seeds), of the best-response valuation and of the opponents' choice + pub rollouts_tafel: f64, + pub rollouts_br_wert: f64, + pub rollouts_br_wahl: f64, + /// opponent decision nodes below all moves (the choice samples), and nodes whose all-in answer is exact (no sampling for the jam move) + pub gegner_knoten: usize, + pub exakt_jam_knoten: usize, +} + +impl Zaehlung { + pub fn rollouts(&self) -> f64 { + self.rollouts_tafel + self.rollouts_br_wert + self.rollouts_br_wahl + } +} + +/// Counts nodes, classes and the rollouts a full run would use (same formulas as the code: table side 2 x n_max x moves per class; best-response valuation n_max x moves, +/// doubled for moves with opponent decisions, plus n_max x (moves - 1) for the choice of the best other move; opponents' choice n_wahl x actions per (opponent node, class with reach)). +pub fn zaehle(r: &Rechner, knoten: &[JamKnoten], p: &Parameter) -> Zaehlung { + let mut zl = Zaehlung::default(); + let prm = p.br_parameter(); + for jk in knoten { + let pfad = pfad_aus_codes(r.s, &jk.codes); + let z = zustand_nach(r.s, &pfad); + let m = z.menue(r.s); + let k = jk.klassen.len() as f64; + zl.knoten += 1; + zl.paare += jk.klassen.len(); + let e = zl.je_sitz.entry(jk.sitz).or_default(); + e.0 += 1; + e.1 += jk.klassen.len(); + let n = p.n_max as f64; + let rl = rollen(&z, &m); + let rw0 = r.reichweite(&pfad); + zl.rollouts_tafel += 2.0 * n * m.n as f64 * k; + let mut wert_zuege = 0.0; + for a in 0..m.n { + let mut y = z; + y.zieh(m.z[a].code, m.z[a].ziel); + if !y.lebt(z.dran as usize) { + wert_zuege += 1.0; + continue; + } + let mut rw = rw0.clone(); + r.reichweite_schritt(&mut rw, &z, m.z[a].code); + let mut sub = br::Subtree::default(); + br::collect(r, z.dran as usize, &y, &rw, rw.erreich, 1, prm.reach_min, &mut sub); + // the jam move is answered exactly (no sampling) where every opponent node below it only has fold / call + let exakt = rl[a] == Rolle::Jam && sub.nodes.iter().all(|o| o.menu.liste().iter().all(|x| x.code < 2)); + if exakt { + zl.exakt_jam_knoten += 1; + } + if !exakt { + for o in &sub.nodes { + let kl = (0..KLASSEN).filter(|&c| o.rw.w[o.seat][c] > 0.0).count() as f64; + zl.rollouts_br_wahl += kl * p.n_wahl as f64 * o.menu.n as f64; + zl.gegner_knoten += 1; + } + } + // valuation: with the policy (and, where opponents decide, once more with the table) + wert_zuege += if sub.nodes.is_empty() { 1.0 } else { 2.0 }; + } + zl.rollouts_br_wert += n * k * (wert_zuege + (m.n as f64 - 1.0)); + } + zl +} + +pub fn zaehl_bericht(zl: &Zaehlung, p: &Parameter, faeden: usize, rate: f64) -> String { + let mut o = format!( + "all-in nodes: {} ({} (node, class) pairs, {:.1} classes per node)\nper tree seat: {}\n", + zl.knoten, + zl.paare, + zl.paare as f64 / zl.knoten.max(1) as f64, + zl.je_sitz.iter().map(|(s, (k, c))| format!("{} {k} nodes / {c} pairs", SITZ_NAMEN.get(*s).copied().unwrap_or("?"))).collect::>().join("; ") + ); + o.push_str(&format!("nodes with an exact all-in answer (opponents only fold/call): {}; opponent decision nodes sampled: {}\n", zl.exakt_jam_knoten, zl.gegner_knoten)); + o.push_str(&format!( + "rollouts (n_max {}, n_wahl {}, rmin {}): table side {:.3e}, best-response valuation {:.3e}, opponents' choice {:.3e}, total {:.3e}\n", + p.n_max, p.n_wahl, p.rmin, zl.rollouts_tafel, zl.rollouts_br_wert, zl.rollouts_br_wahl, zl.rollouts() + )); + let s = zl.rollouts() / (rate * faeden as f64); + o.push_str(&format!("estimate at {rate:.0} rollouts/s/thread x {faeden} threads: {:.1} h (assumption, not measured on the farm; see the rate probe)\n", s / 3600.0)); + o +} + +// --------------------------------------------------------------------------------------------------------------------------------------------------- +// build + +/// Rows of the finished node blocks in the partial files `.teil-*`; each partial file starts with the header (zeilen = 0) that must equal this run's header. +fn lies_teile(dir: &std::path::Path, praefix: &str, kopf_ohne_zeilen: &[u8]) -> Result<(Vec, HashSet, usize), String> { + let mut teile: Vec = std::fs::read_dir(dir).map_err(|e| e.to_string())?.filter_map(|e| e.ok()).map(|e| e.path()).filter(|p| p.file_name().is_some_and(|n| n.to_string_lossy().starts_with(praefix))).collect(); + teile.sort(); + let (mut rows, mut fertig) = (vec![], HashSet::new()); + for t in &teile { + let b = std::fs::read(t).map_err(|e| format!("{}: {e}", t.display()))?; + if b.len() < kopf_ohne_zeilen.len() || b[..kopf_ohne_zeilen.len()] != *kopf_ohne_zeilen { + return Err(format!("{} belongs to another computation (header differs); choose another target name, the partial file stays untouched", t.display())); + } + let mut block: Vec = vec![]; + for c in b[kopf_ohne_zeilen.len()..].chunks_exact(ZEILE_BYTES) { + let key = u64::from_le_bytes(c[0..8].try_into().unwrap()); + let klasse = u16::from_le_bytes(c[8..10].try_into().unwrap()); + if klasse == ENDE_KLASSE { + let n = u32::from_le_bytes(c[10..14].try_into().unwrap()) as usize; + if n == block.len() && block.iter().all(|z| z.key == key) && fertig.insert(key) { + rows.append(&mut block); + } + block.clear(); + } else { + // reuse the strict row parser of the format through a one-row table + let z = Zeile { + key, + klasse, + n: u32::from_le_bytes(c[10..14].try_into().unwrap()), + bester_tafel: c[14], + bester_br: c[15], + tafel_unten: f32::from_le_bytes(c[16..20].try_into().unwrap()), + tafel_oben: f32::from_le_bytes(c[20..24].try_into().unwrap()), + br_unten: f32::from_le_bytes(c[24..28].try_into().unwrap()), + br_oben: f32::from_le_bytes(c[28..32].try_into().unwrap()), + }; + block.push(z); + } + } + } + Ok((rows, fertig, teile.len())) +} + +fn zeile_roh(z: &Zeile) -> [u8; ZEILE_BYTES] { + let t = Tafel { kopf: Kopf { format: String::new(), version: 0, stand: String::new(), modus: String::new(), spiel_id: String::new(), baum_sha256: String::new(), saat_a: 0, saat_b: 0, saat_c: 0, n_max: 0, n_wahl: 0, rmin: 0.0, zeilen: 1 }, zeilen: vec![*z] }; + let b = schreibe(&t); + b[b.len() - ZEILE_BYTES..].try_into().unwrap() +} + +/// Builds the table. Returns the path of the finished file, None for a partial build (`grenze`) or when the target exists already. +pub fn bauen(r: &Rechner, ziel: &str, p: &Parameter) -> Option { + p.pruefe_saaten().unwrap_or_else(|e| panic!("{e}")); + if std::path::Path::new(ziel).exists() { + println!("bauen: {ziel} exists already, nothing to do (never overwritten)"); + return None; + } + let dir = std::path::Path::new(ziel).parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(std::path::Path::new(".")).to_path_buf(); + let name = std::path::Path::new(ziel).file_name().unwrap().to_string_lossy().into_owned(); + let praefix = format!("{name}.teil-"); + let kopf0 = schreibe(&Tafel { kopf: p.kopf(r, 0), zeilen: vec![] }); + let (mut rows, fertig, nteile) = lies_teile(&dir, &praefix, &kopf0).unwrap_or_else(|e| { + eprintln!("bauen: ABORT: {e}"); + std::process::exit(2); + }); + let alle = jam_knoten(r); + let gesamt = alle.len(); + let offen: Vec<&JamKnoten> = alle.iter().filter(|k| !fertig.contains(&k.key)).take(p.grenze.unwrap_or(usize::MAX)).collect(); + println!("bauen: {gesamt} all-in nodes, {} done, {} now; n_max {}, n_wahl {}, rmin {}, {} threads, stand {}", fertig.len(), offen.len(), p.n_max, p.n_wahl, p.rmin, p.faeden, p.stand); + let teil_pfad = dir.join(format!("{praefix}{nteile:04}")); + let mut f = std::fs::OpenOptions::new().create_new(true).append(true).open(&teil_pfad).unwrap_or_else(|e| panic!("{}: {e}", teil_pfad.display())); + f.write_all(&kopf0).unwrap(); + let datei = std::sync::Mutex::new((f, Vec::::new())); + let (zaehler, roll, start) = (AtomicUsize::new(0), AtomicU64::new(0), std::time::Instant::now()); + crate::klassen::parallel(offen.len(), p.faeden, |i| { + let jk = offen[i]; + let (zeilen, n_roll) = rechne_knoten(r, jk, p); + roll.fetch_add(n_roll, Relaxed); + let mut blk: Vec = zeilen.iter().flat_map(zeile_roh).collect(); + blk.extend_from_slice(&zeile_roh(&Zeile { key: jk.key, klasse: ENDE_KLASSE, n: zeilen.len() as u32, bester_tafel: 0, bester_br: 0, tafel_unten: 0.0, tafel_oben: 0.0, br_unten: 0.0, br_oben: 0.0 })); + { + let mut g = datei.lock().unwrap(); + g.0.write_all(&blk).unwrap(); + g.1.extend(zeilen); + } + let n = zaehler.fetch_add(1, Relaxed) + 1; + if n % 25 == 0 || n == offen.len() { + let s = start.elapsed().as_secs_f64(); + println!("bauen: {n}/{} nodes, {s:.0} s, {:.0} rollouts/s", offen.len(), roll.load(Relaxed) as f64 / s); + } + }); + let (mut f, neu) = datei.into_inner().unwrap(); + f.flush().unwrap(); + rows.extend(neu); + println!("bauen: {} rollouts in {:.0} s ({:.0} per second and thread)", roll.load(Relaxed), start.elapsed().as_secs_f64(), roll.load(Relaxed) as f64 / start.elapsed().as_secs_f64().max(1e-9) / p.faeden as f64); + if p.grenze.is_some() { + println!("bauen: partial build (grenze), no assembly"); + return None; + } + rows.sort_by_key(|z| (z.key, z.klasse)); + let t = Tafel { kopf: p.kopf(r, rows.len() as u32), zeilen: rows }; + let bytes = schreibe(&t); + // the strict reader must accept what was just written + lies_streng(&bytes, &p.baum_sha256).unwrap_or_else(|e| panic!("assembled table fails the start check: {e}")); + let schreibe_neu = |pfad: &str, inhalt: &[u8]| { + assert!(!std::path::Path::new(pfad).exists(), "{pfad} exists (never overwritten)"); + let tmp = format!("{pfad}.neu"); + std::fs::write(&tmp, inhalt).unwrap_or_else(|e| panic!("{tmp}: {e}")); + std::fs::rename(&tmp, pfad).unwrap(); + }; + schreibe_neu(ziel, &bytes); + let sha = crate::vorflop_selbst_filter::hex(&crate::vorflop_selbst_filter::sha256(&bytes)); + schreibe_neu(&format!("{ziel}.sha256"), format!("{sha} {name}\n").as_bytes()); + schreibe_neu(&format!("{ziel}.tsv"), tsv(&t).as_bytes()); + let tragen = t.zeilen.iter().filter(|z| traegt(z)).count(); + println!("bauen: {ziel}: {} rows, {tragen} carry (both lower bounds above 0), SHA256 {sha}", t.zeilen.len()); + Some(ziel.to_string()) +} + +// --------------------------------------------------------------------------------------------------------------------------------------------------- +// coverage of real requests by seat + +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub struct Schluessel { + pub linie: &'static str, + pub eroeffner: &'static str, + pub dreier: &'static str, + pub ich: &'static str, +} + +/// Line and seats from the tree path to the node: number of raises (all-in counts as raise) before the node gives the line; the seats of the first two raisers are the +/// opener and the 3-bettor; `ich` is the seat to act. +pub fn lage_schluessel(pfad: &[(Zustand, u8)], ich: usize) -> Schluessel { + let name = |s: usize| SITZ_NAMEN.get(s).copied().unwrap_or("?"); + let raiser: Vec = pfad.iter().filter(|(_, c)| *c >= 2).map(|(z, _)| z.dran as usize).collect(); + let linie = match raiser.len() { + 0 => "open", + 1 => "vs_open", + 2 => "vs_3bet", + 3 => "vs_4bet", + _ => "vs_5bet+", + }; + Schluessel { linie, eroeffner: raiser.first().map_or("-", |s| name(*s)), dreier: raiser.get(1).map_or("-", |s| name(*s)), ich: name(ich) } +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Zeilenzaehler { + pub treu: u64, + /// the node has an all-in move in its menu + pub jam_im_menue: u64, + /// ... and the class has table mass on it (a row is planned) + pub jam_masse: u64, + /// ... and the table (or the plan) has a row + pub abgedeckt: u64, + /// an earlier raise on the path is an all-in: we face a jam (fold/call node, outside the table by design) + pub gegen_allin: u64, +} + +#[derive(Default)] +pub struct Abdeckung { + pub preflop: u64, + pub treu: u64, + pub nicht_treu: BTreeMap, + pub je_lage: BTreeMap, + pub summe: Zeilenzaehler, +} + +fn grund_gruppe(g: &str) -> String { + let s: String = g.chars().map(|c| if c.is_ascii_digit() { '#' } else { c }).collect(); + s.chars().take(110).collect() +} + +/// Maps every preflop request of `ein` (fidelity rule of `vorflop-selbst-werte`) and counts it. `abgedeckt`: (node key, class) pairs of the table or of the plan. +pub fn abdeckung(m: &Motor, ein: &str, knoten: &HashMap>, jam_klassen: &HashMap)>, abgedeckt: &HashSet<(u64, u16)>) -> Abdeckung { + let mut a = Abdeckung::default(); + let text = std::fs::read_to_string(ein).unwrap_or_else(|e| panic!("{ein}: {e}")); + for zeile in text.lines().filter(|l| !l.trim().is_empty()) { + let Ok(v) = serde_json::from_str::(zeile) else { continue }; + let q = if v.get("q").is_some() { v["q"].clone() } else { v }; + if q["street"] != "PREFLOP" { + continue; + } + a.preflop += 1; + let ab = match abbilden(m, &q) { + Ok(x) => x, + Err(g) => { + *a.nicht_treu.entry(grund_gruppe(&g)).or_default() += 1; + continue; + } + }; + let Some(codes) = knoten.get(&ab.key) else { + *a.nicht_treu.entry("treu, but node not in the node list (only one move in the menu)".into()).or_default() += 1; + continue; + }; + a.treu += 1; + let pfad = pfad_aus_codes(&m.s, codes); + let z = zustand_nach(&m.s, &pfad); + let sk = lage_schluessel(&pfad, z.dran as usize); + let mut zz = Zeilenzaehler { treu: 1, ..Default::default() }; + if let Some((_, masse)) = jam_klassen.get(&ab.key) { + zz.jam_im_menue = 1; + if masse[ab.kl] { + zz.jam_masse = 1; + zz.abgedeckt = abgedeckt.contains(&(ab.key, ab.kl as u16)) as u64; + } + } else if z.menue(&m.s).liste().iter().any(|x| x.code >= 2 && x.ziel >= z.einsatz[z.dran as usize] + z.stack[z.dran as usize]) { + // all-in in the menu but no class of this node has table mass: counted as all-in in the menu without mass + zz.jam_im_menue = 1; + } + zz.gegen_allin = pfad.iter().any(|(y, c)| *c >= 2 && y.menue(&m.s).liste().iter().any(|x| x.code == *c && x.ziel >= y.einsatz[y.dran as usize] + y.stack[y.dran as usize])) as u64; + for t in [a.je_lage.entry(sk).or_default(), &mut a.summe] { + t.treu += zz.treu; + t.jam_im_menue += zz.jam_im_menue; + t.jam_masse += zz.jam_masse; + t.abgedeckt += zz.abgedeckt; + t.gegen_allin += zz.gegen_allin; + } + } + a +} + +pub fn abdeckung_markdown(name: &str, a: &Abdeckung) -> String { + let s = &a.summe; + let mut o = format!("### {name}\n\n| | Anzahl |\n|---|---:|\n| Vorflop-Anfragen | {} |\n| treu auf einen Baumknoten abgebildet | {} |\n| davon: All-in im Menue des Knotens | {} |\n| davon: Klasse mit All-in-Masse in der Tafel (Zeile geplant) | {} |\n| davon: durch eine Zeile abgedeckt | {} |\n| davon: gegen ein fruehere All-in (Fold/Call-Knoten, nicht Teil der Tafel) | {} |\n| nicht treu / nicht abgebildet | {} |\n\n", a.preflop, a.treu, s.jam_im_menue, s.jam_masse, s.abgedeckt, s.gegen_allin, a.preflop - a.treu); + if !a.nicht_treu.is_empty() { + o.push_str("Nicht treu, nach Grund:\n\n| Grund | Anzahl |\n|---|---:|\n"); + let mut v: Vec<_> = a.nicht_treu.iter().collect(); + v.sort_by(|x, y| y.1.cmp(x.1).then(x.0.cmp(y.0))); + for (g, n) in v { + o.push_str(&format!("| {} | {n} |\n", g.replace('|', "/"))); + } + o.push('\n'); + } + o.push_str("Treu abgebildete Anfragen nach Lage (Linie, Eroeffner, 3-Bettor, eigener Sitz):\n\n| Linie | Eroeffner | 3-Bettor | ich | treu | All-in im Menue | mit All-in-Masse | abgedeckt | gegen All-in |\n|---|---|---|---|---:|---:|---:|---:|---:|\n"); + for (k, z) in &a.je_lage { + o.push_str(&format!("| {} | {} | {} | {} | {} | {} | {} | {} | {} |\n", k.linie, k.eroeffner, k.dreier, k.ich, z.treu, z.jam_im_menue, z.jam_masse, z.abgedeckt, z.gegen_allin)); + } + o.push('\n'); + o +} + +/// Classes with all-in mass per node key (same rule as `jam_knoten`), as lookup for the coverage count. +pub fn jam_klassen_karte(knoten: &[JamKnoten]) -> HashMap)> { + knoten + .iter() + .map(|k| { + let mut m = vec![false; KLASSEN]; + k.klassen.iter().for_each(|&c| m[c] = true); + (k.key, (k.jam, m)) + }) + .collect() +} + +#[cfg(test)] +mod spec { + use super::*; + use crate::dienst::Strategie; + use crate::lernen::Tabellen; + + fn leere_tabellen() -> Tabellen { + let leer = || crate::klassen::Klassen { k: [169; 4], tab: [vec![], vec![], vec![]] }; + Tabellen { bretter: crate::klassen::Bretter([0; 3].map(|_| BrettIndex::neu(&[]))), kl: [leer(), leer()] } + } + + /// Strategy bytes: `mix(node index, class, number of moves)` as weights summing to 255. + fn tafel_bytes(s: &Spiel, mix: &dyn Fn(usize, usize, usize) -> Vec) -> Strategie { + let liste = knoten_liste(s); + let mut b = b"MOTOR001".to_vec(); + b.extend_from_slice(&(liste.len() as u64).to_le_bytes()); + for (ni, (key, codes)) in liste.iter().enumerate() { + let m = zustand_nach(s, &pfad_aus_codes(s, codes)).menue(s); + b.extend_from_slice(&key.to_le_bytes()); + b.extend_from_slice(&169u16.to_le_bytes()); + b.push(m.n as u8); + for c in 0..169 { + b.extend_from_slice(&mix(ni, c, m.n)); + } + } + Strategie::aus_bytes(b) + } + + fn rein(n: usize, i: usize) -> Vec { + let mut v = vec![0u8; n]; + v[i] = 255; + v + } + + fn klasse(name: &str) -> usize { + (0..KLASSEN).find(|&c| vorflop_name(c) == name).unwrap() + } + + fn parameter(n: u32) -> Parameter { + Parameter { faeden: 2, n_max: n, n_wahl: n, saat_a: 11, saat_b: 22, saat_c: 33, rmin: 1e-4, stand: "test".into(), baum_sha256: baum_sha256_hex(b"toy"), grenze: None } + } + + /// pushfold10: the SB jams with every class, the BB's table answer is "call always". + fn pushfold() -> (Spiel, Strategie) { + let s = Spiel::neu("pushfold10"); + let st = tafel_bytes(&s, &|_, _, n| rein(n, 1)); + (s, st) + } + + #[test] + fn nodes_are_only_those_with_all_in_mass() { + let (s, st) = pushfold(); + let t = leere_tabellen(); + let r = Rechner { s: &s, t: &t, st: &st }; + // the BB node (fold / call) has no all-in move, so only the root appears + let k = jam_knoten(&r); + assert_eq!(k.len(), 1); + assert_eq!((k[0].sitz, k[0].codes.len(), k[0].klassen.len()), (0, 0, KLASSEN)); + // a table that never jams has no node at all; a table that jams only AA has exactly that class + let nie = tafel_bytes(&s, &|_, _, n| rein(n, 0)); + assert!(jam_knoten(&Rechner { s: &s, t: &t, st: &nie }).is_empty()); + let nur_aa = tafel_bytes(&s, &|_, c, n| rein(n, (c == klasse("AA")) as usize)); + let k = jam_knoten(&Rechner { s: &s, t: &t, st: &nur_aa }); + assert_eq!(k.len(), 1); + assert_eq!(k[0].klassen, vec![klasse("AA")]); + } + + #[test] + fn counting_matches_the_node_list_and_estimates_rollouts() { + let (s, st) = pushfold(); + let t = leere_tabellen(); + let r = Rechner { s: &s, t: &t, st: &st }; + let k = jam_knoten(&r); + let p = parameter(100); + let zl = zaehle(&r, &k, &p); + assert_eq!((zl.knoten, zl.paare, zl.exakt_jam_knoten), (1, KLASSEN, 1)); + // table side: 2 seeds x 100 hands x 2 moves x 169 classes + assert_eq!(zl.rollouts_tafel, 2.0 * 100.0 * 2.0 * 169.0); + assert_eq!(zl.rollouts_br_wahl, 0.0, "the all-in is answered exactly: nothing sampled"); + assert!(zaehl_bericht(&zl, &p, 16, RATE_STANDARD).contains("169 (node, class) pairs")); + } + + #[test] + fn rows_exist_only_for_jam_classes_and_aa_carries_while_72o_does_not() { + let (s, st) = pushfold(); + let t = leere_tabellen(); + let r = Rechner { s: &s, t: &t, st: &st }; + let (aa, o72) = (klasse("AA"), klasse("72o")); + let mut k = jam_knoten(&r); + k[0].klassen = vec![aa, o72]; // two classes keep the toy run short + let (rows, n) = rechne_knoten(&r, &k[0], ¶meter(1500)); + assert!(n > 0); + assert_eq!(rows.len(), 2); + let z = |c: usize| rows.iter().find(|z| z.klasse as usize == c).unwrap(); + // AA: the jam beats the fold clearly against the table (BB calls always) and against the best response (BB calls AA-like hands only when the equity pays) + assert!(z(aa).tafel_unten > 0.0 && z(aa).br_unten > 0.0 && traegt(z(aa)), "{:?}", z(aa)); + // 72o: loses against both + assert!(z(o72).tafel_oben < 0.0 && z(o72).br_oben < 0.0 && !traegt(z(o72)), "{:?}", z(o72)); + // the only other move is the fold (menu code 0) + assert!(rows.iter().all(|z| z.bester_tafel == FOLD && z.bester_br == FOLD && z.n > 0 && z.tafel_unten <= z.tafel_oben && z.br_unten <= z.br_oben)); + } + + #[test] + fn build_writes_a_table_that_passes_the_start_check_and_never_overwrites() { + let (s, st) = pushfold(); + let t = leere_tabellen(); + let r = Rechner { s: &s, t: &t, st: &st }; + // restrict the toy to two classes: a table that jams only AA and 72o + let eng = tafel_bytes(&s, &|_, c, n| rein(n, (c == klasse("AA") || c == klasse("72o")) as usize)); + let r2 = Rechner { s: &s, t: &t, st: &eng }; + let _ = &r; + let dir = std::env::temp_dir().join(format!("vallin-bau-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let ziel = dir.join("toy.vallin"); + let ziel = ziel.to_str().unwrap(); + let p = parameter(600); + assert_eq!(bauen(&r2, ziel, &p).as_deref(), Some(ziel)); + let b = std::fs::read(ziel).unwrap(); + let tafel = lies_streng(&b, &p.baum_sha256).unwrap(); + assert_eq!(tafel.zeilen.len(), 2); + assert!(std::fs::read_to_string(format!("{ziel}.sha256")).unwrap().starts_with(&crate::vorflop_selbst_filter::hex(&crate::vorflop_selbst_filter::sha256(&b)))); + assert!(std::fs::read_to_string(format!("{ziel}.tsv")).unwrap().contains("AA")); + // existing target: untouched + assert_eq!(bauen(&r2, ziel, &p), None); + assert_eq!(std::fs::read(ziel).unwrap(), b); + // a restart with another target name continues from the partial file: nothing is recomputed, the result is the same table + let ziel2 = dir.join("toy2.vallin"); + let ziel2 = ziel2.to_str().unwrap(); + std::fs::copy(format!("{ziel}.teil-0000"), format!("{ziel2}.teil-0000")).unwrap(); + assert_eq!(bauen(&r2, ziel2, &p).as_deref(), Some(ziel2)); + assert_eq!(std::fs::read(ziel2).unwrap(), b, "same rows from the partial file"); + // a partial file of a different computation aborts the process, so check the reader directly + let mut anders = p.clone(); + anders.saat_c = 99; + let kopf_anders = schreibe(&Tafel { kopf: anders.kopf(&r2, 0), zeilen: vec![] }); + assert!(lies_teile(&dir, "toy.vallin.teil-", &kopf_anders).unwrap_err().contains("another computation")); + std::fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn equal_seeds_are_refused() { + let mut p = parameter(10); + p.saat_c = p.saat_a; + assert!(p.pruefe_saaten().is_err()); + assert!(parameter(10).pruefe_saaten().is_ok()); + } + + #[test] + fn line_and_seats_come_from_the_raises_on_the_path() { + let s = Spiel::neu("sechs100"); + let mut z = Zustand::start(&s); + assert_eq!(z.dran, 2, "UTG acts first"); + let mut pfad: Vec<(Zustand, u8)> = vec![]; + assert_eq!(lage_schluessel(&pfad, 2), Schluessel { linie: "open", eroeffner: "-", dreier: "-", ich: "UTG" }); + // UTG folds, HJ opens, CO 3-bets: BTN faces a 3-bet (line vs_3bet, opener HJ, 3-bettor CO) + for waehle in [FOLD, 2, 2] { + let m = z.menue(&s); + let x = *m.liste().iter().find(|x| x.code == waehle).unwrap(); + pfad.push((z, x.code)); + z.zieh(x.code, x.ziel); + } + assert_eq!(z.dran, 5); + assert_eq!(lage_schluessel(&pfad, 5), Schluessel { linie: "vs_3bet", eroeffner: "HJ", dreier: "CO", ich: "BTN" }); + assert_eq!(lage_schluessel(&pfad[..2], 4).linie, "vs_open"); + } + + #[test] + fn grouping_of_reasons_hides_numbers() { + assert_eq!(grund_gruppe("nicht treu: Baum 3 hat Erhoehung"), grund_gruppe("nicht treu: Baum 7 hat Erhoehung")); + } +} diff --git a/entscheiden/motor/src/vorflop_selbst_br_nach.rs b/entscheiden/motor/src/vorflop_selbst_br_nach.rs index 15ee6654..8d255e28 100644 --- a/entscheiden/motor/src/vorflop_selbst_br_nach.rs +++ b/entscheiden/motor/src/vorflop_selbst_br_nach.rs @@ -150,7 +150,7 @@ pub struct Subtree { } #[allow(clippy::too_many_arguments)] -fn collect(r: &Rechner, p: usize, z: &Zustand, rw: &Reichweite, base: f64, depth: usize, reach_min: f64, out: &mut Subtree) { +pub fn collect(r: &Rechner, p: usize, z: &Zustand, rw: &Reichweite, base: f64, depth: usize, reach_min: f64, out: &mut Subtree) { if z.ende || z.strasse != 0 { return; } diff --git a/entscheiden/motor/src/vorflop_selbst_werte.rs b/entscheiden/motor/src/vorflop_selbst_werte.rs index 6e133aa8..9dd1675f 100644 --- a/entscheiden/motor/src/vorflop_selbst_werte.rs +++ b/entscheiden/motor/src/vorflop_selbst_werte.rs @@ -76,7 +76,7 @@ pub fn allin_gegen_bester(mittel_a: &[f64], mittel_b: &[f64], kov_b: &[Vec] } /// Werte V und Kovarianz der Klasse `kl` am Knoten (eine Stichprobe mit Saat `saat`). -fn werte_klasse(r: &Rechner, key: u64, kl: usize, pfad: &[(Zustand, u8)], z: &Zustand, modus: Modus, n_max: u64, saat: u64) -> Option<(Vec, Vec>, u64)> { +pub(crate) fn werte_klasse(r: &Rechner, key: u64, kl: usize, pfad: &[(Zustand, u8)], z: &Zustand, modus: Modus, n_max: u64, saat: u64) -> Option<(Vec, Vec>, u64)> { let rw = r.reichweite(pfad); let roh = r.knoten_roh(z, &rw, 0.0, n_max, misch(key, saat), Some(&[kl]), 1); let m = z.menue(r.s); @@ -108,14 +108,14 @@ fn modus_text(modus: Modus) -> (&'static str, Value) { } /// Eine Eingabezeile, Abbildung auf den Knoten. Ok((Knoten, Klasse, echter Preis)) oder Err(Grund der Nicht-Treue). -struct Abbild { - key: u64, - kl: usize, - preis_real: f64, - preis_baum: f64, +pub(crate) struct Abbild { + pub(crate) key: u64, + pub(crate) kl: usize, + pub(crate) preis_real: f64, + pub(crate) preis_baum: f64, } -fn abbilden(m: &Motor, q: &Value) -> Result { +pub(crate) fn abbilden(m: &Motor, q: &Value) -> Result { let spieler = 1 + q["villains"].as_array().map_or(0, Vec::len); if Motor::zu_zweit(q) { return Err("uebersprungen: heads-up (hu100-Motor)".into());