From 0fe188755e3234c8b8aa57db77803f14894973ab Mon Sep 17 00:00:00 2001 From: Marc Mintel Date: Sat, 5 Dec 2026 22:22:20 +0100 Subject: [PATCH] vorflop-selbst-br-nach: value of each preflop menu move against the best response of the opponents to exactly that move Sampled backward-induction best response (choice on sample 1, value on sample 2, best-other on sample 3, separate seeds), exact caller (vorflop_jamprobe) for the all-in where only fold/call follow, allin_minus_best_other_br with paired SE and one-sided bounds. Rechner gets reichweite_schritt (pure refactor of reichweite_mit) and spiele_aus_politik (fixed choice per node and class). Co-Authored-By: Claude Opus 5.5 --- entscheiden/motor/src/main.rs | 26 +- .../motor/src/vorflop_selbst_br_nach.rs | 1012 +++++++++++++++++ .../motor/src/vorflop_selbst_rechnen.rs | 51 +- 3 files changed, 1071 insertions(+), 18 deletions(-) create mode 100644 entscheiden/motor/src/vorflop_selbst_br_nach.rs diff --git a/entscheiden/motor/src/main.rs b/entscheiden/motor/src/main.rs index 519ae288..5de825b8 100644 --- a/entscheiden/motor/src/main.rs +++ b/entscheiden/motor/src/main.rs @@ -62,6 +62,7 @@ mod vorflop_jamprobe; mod vorflop_selbst; mod vorflop_selbst_archiv; mod vorflop_selbst_br; +mod vorflop_selbst_br_nach; mod vorflop_selbst_fehler; mod vorflop_selbst_filter; mod vorflop_selbst_lage; @@ -227,11 +228,11 @@ 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") => { + 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-br-nach") => { 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 - let m = dienst::Motor { s: Spiel::neu(&a[2]), t: std::sync::Arc::new(t), st: dienst::Strategie::lade(&a[6]), genau: w == "vorflop-selbst-vergleich" || (w == "vorflop-selbst-knoten" && a.iter().any(|v| v == "modus=suche")) || (w == "vorflop-selbst-lage" && a.iter().any(|v| v.starts_with("m=") && v != "m=0")) || (w == "vorflop-selbst-diagnose" && !a.iter().any(|v| v == "modus=aa")), merk: Default::default() }; + let m = dienst::Motor { s: Spiel::neu(&a[2]), t: std::sync::Arc::new(t), st: dienst::Strategie::lade(&a[6]), genau: w == "vorflop-selbst-vergleich" || (w == "vorflop-selbst-knoten" && a.iter().any(|v| v == "modus=suche")) || (w == "vorflop-selbst-lage" && a.iter().any(|v| v.starts_with("m=") && v != "m=0")) || (w == "vorflop-selbst-diagnose" && !a.iter().any(|v| v == "modus=aa")) || (w == "vorflop-selbst-br-nach" && a.iter().any(|v| v == "modus=suche")), merk: Default::default() }; let r = vorflop_selbst_rechnen::Rechner { s: &m.s, t: &m.t, st: &m.st }; let x = |i: usize, d: f64| a.get(i).map_or(d, |v| v.parse::().unwrap()); // Schluessel=Wert-Argumente ab Stelle `ab` @@ -303,6 +304,27 @@ fn main() { vorflop_selbst_archiv::sonstige(&m, &a[7], faeden, n_max, kvf(10, "top", 5.0) as usize, saat_b); } } + // br-nach ... [faeden=4] [n_max=256] [n_wahl=] [saat=] [modus=tafel|suche] [delta=..] [rmin=0.001] [exakt=1] [diag=0] [exakt_n=20000] + // (vorflop_selbst_br_nach.rs: Wert jedes eigenen Menuezugs gegen die beste Antwort der Gegner; delta wird nicht gebraucht, die Suche laeuft in jeder Stichprobe) + "vorflop-selbst-br-nach" => { + let mit_suche = match kv(9, "modus").as_deref().unwrap_or("tafel") { + "tafel" => false, + "suche" => true, + x => panic!("modus={x}?"), + }; + let n_max = kvf(9, "n_max", 256.0) as u64; + let prm = vorflop_selbst_br_nach::Params { + n_choice: kvf(9, "n_wahl", n_max as f64) as u64, + n_value: n_max, + reach_min: kvf(9, "rmin", vorflop_selbst_br_nach::REACH_MIN), + threads: kvf(9, "faeden", 4.0) as usize, + exact_jam: kvf(9, "exakt", 1.0) != 0.0, + diagnose: kvf(9, "diag", 0.0) != 0.0, + exact_n: kvf(9, "exakt_n", 20_000.0) as u32, + }; + 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); + } // 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_selbst_br_nach.rs b/entscheiden/motor/src/vorflop_selbst_br_nach.rs new file mode 100644 index 00000000..15ee6654 --- /dev/null +++ b/entscheiden/motor/src/vorflop_selbst_br_nach.rs @@ -0,0 +1,1012 @@ +//! Value of each of OUR preflop menu moves against the BEST RESPONSE of the opponents to exactly that move (part b of the two-sided check +//! "an all-in must carry against the measured/table answer AND against the best response"; part a is `vorflop_jamprobe.rs` / the table rollouts). +//! +//! Definition. Node I (we are seat p), our class h, menu move m. After m the opponents still to act decide at every one of THEIR preflop nodes X below m (until the +//! flop or the end of the hand). W_BR(m | h) is our value (bb, net of the hand, rake as in the tree) when +//! * every opponent seat j plays, at each of his nodes X and for each of his classes c, the action with the highest value for HIM +//! (V_j(a | X, c): he holds class c, the other hands come from the table reach to X, our range is the table range of the path including m and our later table moves), +//! where the continuation after his action is the table, except that deeper opponent nodes already play their best response (backward induction by depth); +//! * our own later preflop nodes play the table; the postflop continuation is the table (mode tafel) or the live search for OUR seat (mode suche); +//! * the ranges the opponents respond to are the table ranges (`reichweite`): our range for move m is table reach at I times the table share of m per class. They respond to +//! that RANGE, not to our class h (our class is what we value). If the table never plays m (empty range) they respond to our whole range at I (`range_source = node`). +//! +//! Statistics (same pattern as `vorflop_selbst_br.rs`). Three independent seed streams: (1) CHOICE: the best action per (X, c) is picked on sample 1; (2) VALUE: W_BR is valued on +//! sample 2 (paired over the moves, same deals and random numbers); (3) BEST: the best other move for `allin_minus_best_other_br` is picked on sample 3 and the difference +//! is formed on sample 2, paired per deal. SE from the spread of the per-deal values (paired differences where differences are formed); one-sided (1 - ALPHA) bounds. +//! `Seeds::new` refuses equal streams. Bias: choosing on sample 1 keeps the max bias out of the value; the noise of the choice itself makes the opponent play slightly +//! worse than his true best response, so W_BR is biased UPWARD (in our favour) by that noise; it shrinks with `n_choice` (the `diag` rows measure it). +//! +//! All-in move: if after our all-in every opponent node only has fold/call, the opponents' choice is the EXACT best response of `vorflop_jamprobe::ruft_bestantwort` against our +//! jam range (each opponent as if alone against us, the approximation of that module), class by class, no sampling and no max bias. The value is then still valued by the +//! paired rollouts (so differences to the other moves are paired); `jam_exact` additionally reports `vorflop_jamprobe::ev_jam` (independent exact evaluator) as a cross check. +//! If an opponent can still re-raise over our all-in (multiway with deeper stacks), the sampled best response is used (`source = sampled`). +//! +//! Multiway: each opponent best-responds in turn by backward induction using the table reach for the ranges at his node (ranges of earlier opponents are NOT re-derived from +//! their best-response actions). That equals the exact best response for one opponent still to act and is an approximation for several; valuation of our value uses the +//! real rollout from I (deals from the reach at I), so the opponents' actual deviations are included there. +//! Cost control: subtrees whose table reach (relative to the reach after m) is below `reach_min` play the table (their mass is reported as `pruned_mass`). +use crate::dienst::Motor; +use crate::karten::*; +use crate::lernen::Deal; +use crate::spiel::*; +use crate::vorflop_jamprobe as jp; +use crate::vorflop_selbst::*; +use crate::vorflop_selbst_rechnen::*; +use crate::vorflop_selbst_suche::{vzug, Sucher, Suche, VZug}; +use serde_json::{json, Value}; +use std::collections::{BTreeMap, HashMap}; +use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; + +/// Default relative reach below which a subtree plays the table. +pub const REACH_MIN: f64 = 1e-3; +/// Hard cap on opponent nodes per move (reported as `cap_hit`). +pub const NODE_CAP: usize = 20_000; +/// Rollout replicates of the exact jam evaluator (hands cycle through the class). +const EXACT_REPLICATES: u32 = 16; + +/// Three independent random streams: choice (sample 1), value (sample 2), best-other (sample 3). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Seeds { + pub choice: u64, + pub value: u64, + pub best: u64, +} + +impl Seeds { + /// Refuses streams that are not pairwise different (selection and valuation would not be independent). + pub fn new(choice: u64, value: u64, best: u64) -> Result { + if choice == value || choice == best || value == best { + return Err(format!("seed streams not pairwise different: choice {choice:#x}, value {value:#x}, best {best:#x}")); + } + Ok(Seeds { choice, value, best }) + } + + /// Three streams from one base seed; aborts if they came out equal. + pub fn derive(base: u64) -> Seeds { + Seeds::new(misch(base, 0xC401), misch(base, 0x7A1E), misch(base, 0xBE57)).unwrap_or_else(|e| panic!("{e}")) + } +} + +#[derive(Clone, Debug)] +pub struct Params { + /// hands per (opponent node, class) for the choice (sample 1) + pub n_choice: u64, + /// hands per (our class, move) for the value (samples 2 and 3) + pub n_value: u64, + pub reach_min: f64, + pub threads: usize, + /// use the exact caller for the all-in where it applies + pub exact_jam: bool, + /// also measure, per opponent node, the opponent's best-response value against his table value (second independent sample) + pub diagnose: bool, + /// total hands of the `ev_jam` cross check per class + pub exact_n: u32, +} + +impl Default for Params { + fn default() -> Self { + Params { n_choice: 256, n_value: 256, reach_min: REACH_MIN, threads: 4, exact_jam: true, diagnose: false, exact_n: 20_000 } + } +} + +/// Mean, standard error, one-sided (1 - ALPHA) bounds. +#[derive(Clone, Copy, Debug)] +pub struct Est { + pub mean: f64, + pub se: f64, + pub lower: f64, + pub upper: f64, + pub n: u64, +} + +#[derive(Clone, Copy, Default)] +struct Acc { + n: u64, + sum: f64, + sq: f64, +} + +impl Acc { + fn plus(&mut self, x: f64) { + self.n += 1; + self.sum += x; + self.sq += x * x; + } + fn est(&self) -> Est { + let n = self.n as f64; + let mean = if self.n > 0 { self.sum / n } else { f64::NAN }; + let se = if self.n > 1 { (((self.sq / n - mean * mean).max(0.0) * n / (n - 1.0)) / n).sqrt() } else { f64::INFINITY }; + let z = normal_quantil(1.0 - ALPHA); + Est { mean, se, lower: mean - z * se, upper: mean + z * se, n: self.n } + } +} + +fn est_json(e: &Est) -> Value { + json!({"mean": e.mean, "se": e.se, "lower": e.lower, "upper": e.upper, "n": e.n}) +} + +// --------------------------------------------------------------------------------------------------------------------------------------------------- +// opponent nodes below a move + +/// A decision node of an opponent below our move. +pub struct OppNode { + pub z: Zustand, + pub menu: Menue, + pub key: u64, + pub seat: usize, + pub depth: usize, + /// table reach to this node (path from the root including our move) + pub rw: Reichweite, + /// reach relative to the reach after our move + pub rel: f64, +} + +#[derive(Default)] +pub struct Subtree { + pub nodes: Vec, + /// summed relative reach of the pruned subtree roots (they play the table) + pub pruned_mass: f64, + pub cap_hit: bool, +} + +#[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) { + if z.ende || z.strasse != 0 { + return; + } + let rel = if base > 0.0 { rw.erreich / base } else { 1.0 }; + if rel < reach_min { + out.pruned_mass += rel; + return; + } + let m = z.menue(r.s); + if z.dran as usize != p && m.n >= 2 { + if out.nodes.len() >= NODE_CAP { + out.cap_hit = true; + return; + } + out.nodes.push(OppNode { z: *z, menu: m, key: z.schluessel(&m), seat: z.dran as usize, depth, rw: rw.clone(), rel }); + } + for x in m.liste() { + let mut y = *z; + y.zieh(x.code, x.ziel); + let mut rw2 = rw.clone(); + r.reichweite_schritt(&mut rw2, z, x.code); + collect(r, p, &y, &rw2, base, depth + 1, reach_min, out); + } +} + +// --------------------------------------------------------------------------------------------------------------------------------------------------- +// best response of the opponents (sampled, backward induction by depth) + +/// One chosen action with (when `diagnose`) its value against the table value on an independent sample. +#[derive(Clone, Debug)] +pub struct Choice { + pub key: u64, + pub seat: usize, + pub depth: usize, + pub class: usize, + pub action: u8, + /// class weight at the node (combos x reach of the seat) + pub weight: f64, + /// diagnose: opponent's value of the chosen action / of the table mixture, paired difference with SE, on the independent sample + pub v_br: f64, + pub v_table: f64, + pub se_gain: f64, + pub n: u64, +} + +/// Node-level gain of the best response over the table, weighted over the classes. +#[derive(Clone, Debug)] +pub struct NodeGain { + pub key: u64, + pub seat: usize, + pub depth: usize, + pub gain: f64, + pub se: f64, + pub classes: usize, +} + +/// Sampled best response at all given nodes (deepest first, nodes of one depth are independent). Chosen actions go into `pol`. +/// Returns the choices (value fields only filled with `diagnose`). +pub fn sampled_best_response(r: &Rechner, nodes: &[OppNode], seeds: &Seeds, prm: &Params, pol: &mut Politik, rollouts: &AtomicU64) -> Vec { + let alle = klassen_haende(); + let mut tiefen: Vec = nodes.iter().map(|n| n.depth).collect(); + tiefen.sort_unstable(); + tiefen.dedup(); + let mut out: Vec = vec![]; + for &tiefe in tiefen.iter().rev() { + let idx: Vec = (0..nodes.len()).filter(|&i| nodes[i].depth == tiefe).collect(); + let cums: Vec<[Option>; MAXN]> = idx.iter().map(|&i| r.cum_fuer(&nodes[i].z, &nodes[i].rw)).collect(); + // an opponent range of mass 0 cannot be drawn: that node plays the table + let ok: Vec = idx.iter().zip(&cums).map(|(_, c)| c.iter().flatten().all(|v| v[HAENDE - 1] > 0.0)).collect(); + let mut tasks: Vec<(usize, usize)> = vec![]; + for (k, &i) in idx.iter().enumerate() { + if ok[k] { + tasks.extend((0..KLASSEN).filter(|&c| nodes[i].rw.w[nodes[i].seat][c] > 0.0).map(|c| (k, c))); + } + } + let res = std::sync::Mutex::new(Vec::::new()); + let pol_ro: &Politik = pol; + crate::klassen::parallel(tasks.len(), prm.threads, |t| { + let (k, c) = tasks[t]; + let node = &nodes[idx[k]]; + let (j, na) = (node.seat, node.menu.n); + let values = |fam: u64, n: u64, act: &mut dyn FnMut(&[f64])| -> u64 { + let (mut got, mut ctr) = (0u64, 0u64); + while got < n && ctr < n * 20 { + ctr += 1; + let seed = misch(fam, ctr); + let Some(mut d) = r.deal_ziehen(j, &cums[k], &alle[c], seed) else { continue }; + let mut v = vec![0.0; na]; + for (a, va) in v.iter_mut().enumerate() { + let mut y = node.z; + y.zieh(node.menu.z[a].code, node.menu.z[a].ziel); + *va = r.spiele_aus_politik(y, &mut d, j, misch(seed, 0xAC), None, None, Some(pol_ro)).wert; + } + rollouts.fetch_add(na as u64, Relaxed); + act(&v); + got += 1; + } + got + }; + let fam1 = misch(misch(seeds.choice, node.key), c as u64 + 1); + let mut sum1 = vec![0.0; na]; + if values(fam1, prm.n_choice, &mut |v| v.iter().enumerate().for_each(|(a, x)| sum1[a] += x)) == 0 { + // no deal could be drawn (the ranges block each other): this class plays the table + return; + } + let best = (0..na).max_by(|&x, &y| sum1[x].partial_cmp(&sum1[y]).unwrap_or(std::cmp::Ordering::Equal).then(y.cmp(&x))).unwrap(); + let mut ch = Choice { key: node.key, seat: j, depth: node.depth, class: c, action: best as u8, weight: vorflop_kombos(c) as f64 * node.rw.w[j][c] as f64, v_br: 0.0, v_table: 0.0, se_gain: 0.0, n: 0 }; + if prm.diagnose { + let pi: Vec = r.st.hole(node.key, c, na).map_or_else(|| vec![1.0 / na as f64; na], |v| v[..na].iter().map(|x| *x as f64).collect()); + let fam2 = misch(misch(seeds.value, node.key), c as u64 + 1); + let (mut ab, mut at, mut ag) = (Acc::default(), Acc::default(), Acc::default()); + values(fam2, prm.n_choice, &mut |v| { + let tab: f64 = (0..na).map(|a| pi[a] * v[a]).sum(); + ab.plus(v[best]); + at.plus(tab); + ag.plus(v[best] - tab); + }); + (ch.v_br, ch.v_table, ch.se_gain, ch.n) = (ab.est().mean, at.est().mean, ag.est().se, ag.n); + } + res.lock().unwrap().push(ch); + }); + let mut level = res.into_inner().unwrap(); + level.sort_by_key(|c| (c.key, c.class)); + for c in &level { + pol.insert((c.key, c.class), c.action); + } + out.extend(level); + } + out +} + +/// Weighted gain of the best response over the table per node (diagnose rows only). +pub fn node_gains(choices: &[Choice]) -> Vec { + let mut by: BTreeMap> = BTreeMap::new(); + for c in choices.iter().filter(|c| c.n > 1) { + by.entry(c.key).or_default().push(c); + } + by.into_iter() + .map(|(key, cs)| { + let g: f64 = cs.iter().map(|c| c.weight).sum(); + let gain = cs.iter().map(|c| c.weight / g * (c.v_br - c.v_table)).sum(); + let se = cs.iter().map(|c| (c.weight / g * c.se_gain).powi(2)).sum::().sqrt(); + NodeGain { key, seat: cs[0].seat, depth: cs[0].depth, gain, se, classes: cs.len() } + }) + .collect() +} + +// --------------------------------------------------------------------------------------------------------------------------------------------------- +// exact best response against an all-in (vorflop_jamprobe) + +/// Everything the exact caller used for one all-in move. +pub struct JamExact { + pub tisch: jp::Tisch, + /// opponent seats in the order of `tisch.gegner` + pub seats: Vec, + /// `ruft[g][class]`: opponent g calls with the class (`ruft_bestantwort`) + pub ruft: Vec>, + pub rake: jp::RakeModell, + pub range_source: &'static str, + /// opponent ranges as weights per hand index (table reach at I) + pub ranges: Vec>, +} + +/// Exact best response of the opponents to our all-in `menu[a]` at `z`, written into `pol`. None if it does not apply: an opponent could still re-raise (a node below the all-in has a raise). +pub fn exact_jam_response(r: &Rechner, z: &Zustand, a: usize, rw0: &Reichweite, pol: &mut Politik) -> Option { + let p = z.dran as usize; + let menu = z.menue(r.s); + let mut y = *z; + y.zieh(menu.z[a].code, menu.z[a].ziel); + // nodes below the all-in: only fold / call allowed + fn below(r: &Rechner, z: &Zustand, out: &mut Vec<(Zustand, Menue)>) -> bool { + if z.ende || z.strasse != 0 { + return true; + } + let m = z.menue(r.s); + if m.n >= 2 { + if m.liste().iter().any(|x| x.code >= 2) { + return false; + } + out.push((*z, m)); + } + m.liste().iter().all(|x| { + let mut y = *z; + y.zieh(x.code, x.ziel); + below(r, &y, out) + }) + } + let mut nodes = vec![]; + if !below(r, &y, &mut nodes) { + return None; + } + let s = r.s; + let seats: Vec = (0..s.n).filter(|&j| j != p && z.lebt(j)).collect(); + let mein_drin = z.gesamt[p] as f64 / 100.0; + let ziel = (z.gesamt[p] + (menu.z[a].ziel - z.einsatz[p])) as f64 / 100.0; + let gegner: Vec = seats.iter().map(|&j| jp::Sitz { drin: z.gesamt[j] as f64 / 100.0, rest: z.stack[j] as f64 / 100.0 }).collect(); + let mut tisch = jp::Tisch { mein_drin, ziel, tot: 0.0, gegner }; + tisch.tot = (z.pot as f64 / 100.0 - tisch.topf()).max(0.0); + let rake = jp::RakeModell::Linear { satz: s.rake as f64, deckel: s.rake_kappe as f64 / 100.0 }; + // our jam range: table reach at I times the table share of the all-in per class (all-in moves of the menu); if the table never jams, our whole range at I + let anteil = |c: usize| -> f64 { + r.st.hole(z.schluessel(&menu), c, menu.n).map_or(1.0 / menu.n as f64, |v| v[a] as f64) + }; + let mut w169 = [0f32; KLASSEN]; + for (c, w) in w169.iter_mut().enumerate() { + *w = (vorflop_kombos(c) as f64 * rw0.w[p][c] as f64 * anteil(c)) as f32; + } + let mut range_source = "table"; + if w169.iter().sum::() <= 0.0 { + range_source = "node"; + for (c, w) in w169.iter_mut().enumerate() { + *w = vorflop_kombos(c) * rw0.w[p][c]; + } + if w169.iter().sum::() <= 0.0 { + return None; + } + } + let eq = jp::klassen_gegen(&w169, jp::BR_VERSUCHE); + let ruft: Vec> = (0..seats.len()).map(|g| eq.iter().map(|e| e.is_some_and(|e| jp::ruft_bestantwort(e as f64, &tisch, g, &rake))).collect()).collect(); + for (zn, mn) in &nodes { + let g = seats.iter().position(|&j| j == zn.dran as usize)?; + let key = zn.schluessel(mn); + let fold = mn.liste().iter().position(|x| x.code == FOLD); + let call = mn.liste().iter().position(|x| x.code == CALL)?; + for c in 0..KLASSEN { + let act = if ruft[g][c] { call } else { fold.unwrap_or(call) }; + pol.insert((key, c), act as u8); + } + } + let paare = alle_paare(); + let ranges: Vec> = seats.iter().map(|&j| paare.iter().map(|&(x, y)| rw0.w[j][vorflop(x, y)]).collect()).collect(); + Some(JamExact { tisch, seats, ruft, rake, range_source, ranges }) +} + +/// Cross check: `ev_jam` value (bb, net of the hand, i.e. minus what we already had in) of the class `h`, replicates over the hands of the class. +pub fn exact_jam_value(je: &JamExact, h: usize, total: u32, seed: u64) -> Option { + let paare = alle_paare(); + let haende = &klassen_haende()[h]; + let je_rep = (total / EXACT_REPLICATES).max(200); + let mut acc = Acc::default(); + for rep in 0..EXACT_REPLICATES { + let hand = haende[rep as usize % haende.len()]; + let ev = jp::ev_jam(hand, &je.tisch, &je.ranges, &|g, hh| je.ruft[g][vorflop(paare[hh].0, paare[hh].1)], &je.rake, je_rep, misch(seed, rep as u64 + 1))?; + acc.plus(ev - je.tisch.mein_drin); + } + Some(acc.est()) +} + +// --------------------------------------------------------------------------------------------------------------------------------------------------- +// values of our moves + +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Source { + /// no opponent decision below the move (fold, or the hand ends) + Fixed, + Sampled, + /// exact best response of `vorflop_jamprobe` + ExactJam, +} + +impl Source { + fn text(self) -> &'static str { + match self { + Source::Fixed => "fixed", + Source::Sampled => "sampled", + Source::ExactJam => "exact_jam", + } + } +} + +pub struct MoveInfo { + pub idx: usize, + pub code: u8, + pub ziel: i32, + pub name: String, + pub role: Rolle, + pub y: Zustand, + pub source: Source, + pub opp_nodes: usize, + pub pruned_mass: f64, + pub cap_hit: bool, + pub range_source: &'static str, +} + +pub struct MoveEst { + pub w_br: Est, + pub w_table: Est, + /// paired W_BR - W_table + pub br_minus_table: Est, +} + +pub struct AllinDiff { + /// W_BR(all-in) - W_BR(best other move), paired per deal + pub diff: Est, + /// best other move (picked on the independent sample 3) + pub best_other: usize, +} + +pub struct ClassResult { + pub class: usize, + pub moves: Vec, + pub allin_minus_best_other: Option, + /// `ev_jam` cross check of the all-in value (only with the exact caller) + pub jam_exact: Option, +} + +struct NodeCtx<'a> { + z: Zustand, + p: usize, + key: u64, + moves: &'a [MoveInfo], + jam: Option, + cum: [Option>; MAXN], + verlauf0: Vec, + je: Option<&'a JamExact>, +} + +#[allow(clippy::too_many_arguments)] +fn value_class(r: &Rechner, ctx: &NodeCtx, pol: &Politik, h: usize, seeds: &Seeds, prm: &Params, sucher: Option<&dyn Sucher>, rollouts: &AtomicU64) -> Option { + let nm = ctx.moves.len(); + let alle = klassen_haende(); + let play = |d: &mut Deal, mv: &MoveInfo, sd: u64, politik: Option<&Politik>| -> f64 { + rollouts.fetch_add(1, Relaxed); + match sucher { + None => r.spiele_aus_politik(mv.y, d, ctx.p, sd, None, None, politik).wert, + Some(s) => { + let mut v = ctx.verlauf0.clone(); + v.push(vzug(&ctx.z, mv.code, mv.ziel)); + r.spiele_aus_politik(mv.y, d, ctx.p, sd, Some((s, &mut v)), None, politik).wert + } + } + }; + let deals = |fam: u64, n: u64, f: &mut dyn FnMut(&mut Deal, u64)| { + let (mut got, mut ctr) = (0u64, 0u64); + while got < n && ctr < n * 20 { + ctr += 1; + let seed = misch(fam, ctr); + let Some(mut d) = r.deal_ziehen(ctx.p, &ctx.cum, &alle[h], seed) else { continue }; + f(&mut d, misch(seed, 0xAC)); + got += 1; + } + }; + // sample 2: values, paired over the moves + let fam2 = misch(misch(seeds.value, ctx.key), h as u64 + 1); + let (mut br, mut tab, mut gap) = (vec![Acc::default(); nm], vec![Acc::default(); nm], vec![Acc::default(); nm]); + let mut rows: Vec> = vec![]; + deals(fam2, prm.n_value, &mut |d, sd| { + let mut row = Vec::with_capacity(nm); + for (a, mv) in ctx.moves.iter().enumerate() { + let b = play(d, mv, sd, Some(pol)); + let t = if mv.source == Source::Fixed { b } else { play(d, mv, sd, None) }; + br[a].plus(b); + tab[a].plus(t); + gap[a].plus(b - t); + row.push(b); + } + rows.push(row); + }); + if rows.len() < 2 { + return None; + } + let moves: Vec = (0..nm).map(|a| MoveEst { w_br: br[a].est(), w_table: tab[a].est(), br_minus_table: gap[a].est() }).collect(); + // sample 3: the best other move, independent of the sample the difference is formed on + let allin = ctx.jam.and_then(|jam| { + let others: Vec = (0..nm).filter(|&a| a != jam).collect(); + if others.is_empty() { + return None; + } + let mut s3 = vec![Acc::default(); nm]; + let fam3 = misch(misch(seeds.best, ctx.key), h as u64 + 1); + deals(fam3, prm.n_value, &mut |d, sd| { + for &a in &others { + s3[a].plus(play(d, &ctx.moves[a], sd, Some(pol))); + } + }); + let best = others.iter().copied().max_by(|&x, &y| s3[x].est().mean.partial_cmp(&s3[y].est().mean).unwrap_or(std::cmp::Ordering::Equal).then(y.cmp(&x)))?; + let mut diff = Acc::default(); + rows.iter().for_each(|row| diff.plus(row[jam] - row[best])); + Some(AllinDiff { diff: diff.est(), best_other: best }) + }); + let jam_exact = ctx.je.and_then(|je| exact_jam_value(je, h, prm.exact_n, misch(seeds.value, 0xEA ^ ctx.key ^ h as u64))); + Some(ClassResult { class: h, moves, allin_minus_best_other: allin, jam_exact }) +} + +/// Result for one node: the moves, per requested class the values, and the cost. +pub struct NodeResult { + pub key: u64, + pub seat: usize, + pub moves: Vec, + pub classes: Vec, + pub choices: Vec, + pub choice_rollouts: u64, + pub value_rollouts: u64, + pub exact_jam_applied: bool, +} + +impl NodeResult { + /// Rollouts relative to the plain table rollout of the same classes (n_value hands per class and move). + pub fn cost_vs_table(&self, prm: &Params) -> f64 { + let plain = (self.classes.len().max(1) as u64 * prm.n_value * self.moves.len() as u64) as f64; + (self.choice_rollouts + self.value_rollouts) as f64 / plain + } +} + +/// W_BR of every move of the node at the end of `pfad` for the classes `hands`. `sucher`: Some = mode suche (our seat uses the search after the flop; sequential), +/// None = mode tafel. +pub fn node_br(r: &Rechner, pfad: &[(Zustand, u8)], hands: &[usize], prm: &Params, seeds: &Seeds, sucher: Option<&dyn Sucher>) -> NodeResult { + assert_ne!(seeds.choice, seeds.value, "choice and value samples must use different seeds"); + let z = zustand_nach(r.s, pfad); + let menu = z.menue(r.s); + let (p, key) = (z.dran as usize, z.schluessel(&menu)); + let rw0 = r.reichweite(pfad); + let rl = rollen(&z, &menu); + let mut pol = Politik::new(); + let mut moves: Vec = vec![]; + let mut sub_nodes: Vec = vec![]; + let mut exact_applied = false; + let mut exacts: Vec<(usize, JamExact)> = vec![]; + for a in 0..menu.n { + let mut y = z; + y.zieh(menu.z[a].code, menu.z[a].ziel); + let mut info = MoveInfo { idx: a, code: menu.z[a].code, ziel: menu.z[a].ziel, name: zugname(&menu, a), role: rl[a], y, source: Source::Fixed, opp_nodes: 0, pruned_mass: 0.0, cap_hit: false, range_source: "table" }; + if !y.lebt(p) { + // we are out of the hand: nothing the opponents do changes our value + moves.push(info); + continue; + } + if rl[a] == Rolle::Jam && prm.exact_jam { + if let Some(je) = exact_jam_response(r, &z, a, &rw0, &mut pol) { + info.source = Source::ExactJam; + info.range_source = je.range_source; + exact_applied = true; + exacts.push((a, je)); + moves.push(info); + continue; + } + } + // our range for the move: table reach at I times the table share of the move; empty -> our whole range at I + let mass: f64 = (0..KLASSEN).map(|c| vorflop_kombos(c) as f64 * rw0.w[p][c] as f64 * r.st.hole(key, c, menu.n).map_or(1.0 / menu.n as f64, |v| v[a] as f64)).sum(); + let mut rw = rw0.clone(); + if mass > 0.0 { + r.reichweite_schritt(&mut rw, &z, menu.z[a].code); + } else { + info.range_source = "node"; + } + let mut sub = Subtree::default(); + collect(r, p, &y, &rw, rw.erreich, 1, prm.reach_min, &mut sub); + info.opp_nodes = sub.nodes.len(); + info.pruned_mass = sub.pruned_mass; + info.cap_hit = sub.cap_hit; + if !sub.nodes.is_empty() { + info.source = Source::Sampled; + } + sub_nodes.append(&mut sub.nodes); + moves.push(info); + } + let choice_rollouts = AtomicU64::new(0); + let value_rollouts = AtomicU64::new(0); + let choices = sampled_best_response(r, &sub_nodes, seeds, prm, &mut pol, &choice_rollouts); + let jam = rl.iter().position(|x| *x == Rolle::Jam); + let je_main = jam.and_then(|a| exacts.iter().find(|(i, _)| *i == a).map(|(_, je)| je)); + let ctx = NodeCtx { z, p, key, moves: &moves, jam, cum: r.cum_fuer(&z, &rw0), verlauf0: verlauf_aus_pfad(r.s, pfad), je: je_main }; + let mut classes: Vec = vec![]; + if ctx.cum.iter().flatten().all(|v| v[HAENDE - 1] > 0.0) { + match sucher { + Some(s) => { + for &h in hands { + classes.extend(value_class(r, &ctx, &pol, h, seeds, prm, Some(s), &value_rollouts)); + } + } + None => { + let out = std::sync::Mutex::new(Vec::::new()); + crate::klassen::parallel(hands.len(), prm.threads, |i| { + if let Some(c) = value_class(r, &ctx, &pol, hands[i], seeds, prm, None, &value_rollouts) { + out.lock().unwrap().push(c); + } + }); + classes = out.into_inner().unwrap(); + classes.sort_by_key(|c| c.class); + } + } + } + NodeResult { key, seat: p, moves, classes, choices, choice_rollouts: choice_rollouts.load(Relaxed), value_rollouts: value_rollouts.load(Relaxed), exact_jam_applied: exact_applied } +} + +// --------------------------------------------------------------------------------------------------------------------------------------------------- +// the tool: real requests -> tree nodes (fidelity rule of the archive tool) -> one JSON line per request + +fn move_json(mv: &MoveInfo, e: &MoveEst) -> Value { + json!({ + "idx": mv.idx, "name": mv.name, "role": format!("{:?}", mv.role), "source": mv.source.text(), "range_source": mv.range_source, + "w_br": e.w_br.mean, "se": e.w_br.se, "lower": e.w_br.lower, "upper": e.w_br.upper, "n": e.w_br.n, + "w_table": e.w_table.mean, "w_table_se": e.w_table.se, + "br_minus_table": est_json(&e.br_minus_table), + "opp_nodes": mv.opp_nodes, "pruned_mass": mv.pruned_mass, "cap_hit": mv.cap_hit, + }) +} + +fn class_json(nr: &NodeResult, c: &ClassResult) -> Value { + let moves: Vec = nr.moves.iter().zip(&c.moves).map(|(m, e)| move_json(m, e)).collect(); + let allin = c.allin_minus_best_other.as_ref().map(|a| { + let mut v = est_json(&a.diff); + v["best_other"] = json!(nr.moves[a.best_other].name); + v["best_other_idx"] = json!(a.best_other); + v + }); + json!({"moves": moves, "allin_minus_best_other_br": allin, "jam_exact": c.jam_exact.as_ref().map(est_json)}) +} + +/// Reads the preflop requests of `ein`, maps each to its tree node (same rules as the archive tool) and writes one JSON line per input line to `aus`. +#[allow(clippy::too_many_arguments)] +pub fn br_nach(m: &Motor, ein: &str, aus: &str, prm: &Params, seeds: &Seeds, mit_suche: bool) { + let r = Rechner { s: &m.s, t: &m.t, st: &m.st }; + let knoten: HashMap> = knoten_liste(&m.s).into_iter().collect(); + let text = std::fs::read_to_string(ein).unwrap_or_else(|e| panic!("{ein}: {e}")); + struct Req { + i: usize, + key: u64, + kl: usize, + status: String, + } + let mut reqs: Vec = vec![]; + for (i, zeile) in text.lines().enumerate() { + if zeile.trim().is_empty() { + continue; + } + let q: Value = serde_json::from_str(zeile).unwrap_or(Value::Null); + let mut req = Req { i, key: 0, kl: 0, status: String::new() }; + let spieler = 1 + q["villains"].as_array().map_or(0, Vec::len); + req.status = if q["street"] != "PREFLOP" { + "skipped: not preflop".into() + } else if Motor::zu_zweit(&q) { + "skipped: heads-up (hu100 engine)".into() + } else if q["_splash"].as_f64().unwrap_or(0.0) > 0.0 { + "skipped: splash".into() + } else if spieler >= 4 && Motor::ist_straddle(&q) { + "skipped: straddle".into() + } else { + match m.vorflop_lage(&q) { + Err(e) => format!("skipped: situation unreadable ({e})"), + Ok((l, ich, hand)) => { + if l.fehler.is_some() { + "skipped: history does not fit the tree".into() + } else { + let z = l.z; + let mz = z.menue(&m.s); + match crate::vorflop_selbst_treue::treue_am_knoten(&m.s, &z, &l, ich as usize, &q) { + Err(g) => format!("skipped: not faithful ({g})"), + Ok(()) if !knoten.contains_key(&z.schluessel(&mz)) => "skipped: node not in the preflop tree list".into(), + Ok(()) => { + req.key = z.schluessel(&mz); + req.kl = vorflop(hand.0, hand.1); + "ok".into() + } + } + } + } + } + }; + reqs.push(req); + } + let mut nodes: BTreeMap> = BTreeMap::new(); + for q in reqs.iter().filter(|q| q.status == "ok") { + nodes.entry(q.key).or_default().push(q.kl); + } + println!("br_nach: {} lines, {} usable, {} distinct nodes; n_choice {} n_value {} reach_min {} seeds {:?}", reqs.len(), reqs.iter().filter(|q| q.status == "ok").count(), nodes.len(), prm.n_choice, prm.n_value, prm.reach_min, seeds); + let suche = Suche::neu(m); + let mut results: HashMap = HashMap::new(); + for (key, hands) in &mut nodes { + hands.sort_unstable(); + hands.dedup(); + let pfad = pfad_aus_codes(&m.s, &knoten[key]); + let nr = node_br(&r, &pfad, hands, prm, seeds, if mit_suche { Some(&suche as &dyn Sucher) } else { None }); + println!("br_nach: node {key:016x} seat {} moves {} classes {} choice_rollouts {} value_rollouts {} cost_vs_table {:.1}x exact_jam {}", nr.seat, nr.moves.len(), nr.classes.len(), nr.choice_rollouts, nr.value_rollouts, nr.cost_vs_table(prm), nr.exact_jam_applied); + results.insert(*key, nr); + } + let mut o = String::new(); + for q in &reqs { + let mut zeile = json!({"i": q.i, "status": q.status}); + if q.status == "ok" { + let nr = &results[&q.key]; + zeile["key"] = json!(format!("{:016x}", q.key)); + zeile["class"] = json!(q.kl); + zeile["class_name"] = json!(vorflop_name(q.kl)); + zeile["lage"] = json!(crate::vorflop_selbst_archiv::lage_text(&m.s, &pfad_aus_codes(&m.s, &knoten[&q.key]))); + zeile["n_choice"] = json!(prm.n_choice); + zeile["n_value"] = json!(prm.n_value); + zeile["mode"] = json!(if mit_suche { "suche" } else { "tafel" }); + zeile["seeds"] = json!({"choice": seeds.choice, "value": seeds.value, "best": seeds.best}); + zeile["cost_vs_table"] = json!(nr.cost_vs_table(prm)); + if prm.diagnose { + let g: Vec = node_gains(&nr.choices).iter().map(|g| json!({"key": format!("{:016x}", g.key), "seat": g.seat, "depth": g.depth, "gain": g.gain, "se": g.se, "classes": g.classes})).collect(); + zeile["diag_node_gains"] = json!(g); + } + match nr.classes.iter().find(|c| c.class == q.kl) { + Some(c) => zeile["result"] = class_json(nr, c), + None => zeile["status"] = json!("no values (ranges block each other or no hand drawn)"), + } + } + o.push_str(&zeile.to_string()); + o.push('\n'); + } + let tmp = format!("{aus}.neu"); + std::fs::write(&tmp, o).unwrap_or_else(|e| panic!("{tmp}: {e}")); + std::fs::rename(&tmp, aus).unwrap(); + println!("br_nach: {aus} written ({} lines)", reqs.len()); +} + +#[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 for the given nodes: `mix(node index, class, n actions)` 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 pfad = pfad_aus_codes(s, codes); + let m = zustand_nach(s, &pfad).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 { + let v = mix(ni, c, m.n); + assert_eq!(v.len(), m.n); + b.extend_from_slice(&v); + } + } + Strategie::aus_bytes(b) + } + + fn rein(n: usize, i: usize) -> Vec { + let mut v = vec![0u8; n]; + v[i] = 255; + v + } + + /// pushfold10: the SB jams always, the BB's table answer is "call always" (the best response is not). + fn pushfold() -> (Spiel, Strategie) { + let s = Spiel::neu("pushfold10"); + // root (SB: fold / all-in) and the BB node (fold / call): all-in and call + let st = tafel_bytes(&s, &|_, _, n| rein(n, 1)); + (s, st) + } + + fn params(n: u64) -> Params { + Params { n_choice: n, n_value: n, reach_min: 1e-4, threads: 2, exact_jam: true, diagnose: true, exact_n: 20_000 } + } + + fn klasse(name: &str) -> usize { + (0..KLASSEN).find(|&c| vorflop_name(c) == name).unwrap() + } + + /// The BB's node after the SB's all-in and its (fold, call) indices. + fn bb_knoten(s: &Spiel) -> (Zustand, usize, usize) { + let w = Zustand::start(s); + let mw = w.menue(s); + let mut y = w; + y.zieh(mw.z[1].code, mw.z[1].ziel); + let my = y.menue(s); + (y, my.liste().iter().position(|x| x.code == FOLD).unwrap(), my.liste().iter().position(|x| x.code == CALL).unwrap()) + } + + #[test] + fn spec1_toy_the_best_response_is_call_iff_the_equity_pays_the_price() { + // Hand-derived: the BB calls 9 into a pot of 11 + 9 = 20 -> breakeven equity 9/20 = 45 % against the SB's jam range (all hands). + // AA (about 85 % against a random hand) calls, value 20 x 0.85 - 10 = +7.0; 72o (about 35 %) folds, value -1 (the posted big blind). + let (s, st) = pushfold(); + let t = leere_tabellen(); + let r = Rechner { s: &s, t: &t, st: &st }; + let w = Zustand::start(&s); + let pfad = vec![(w, w.menue(&s).z[0].code)]; + // the root path: nodes below move index 1 (all-in); force the sampled path so the choice itself is tested + let mut prm = params(1500); + prm.exact_jam = false; + let nr = node_br(&r, &[], &[klasse("72o")], &prm, &Seeds::derive(5), None); + let _ = pfad; + let (_, fold, call) = bb_knoten(&s); + let bb = nr.choices.iter().filter(|c| c.seat == 1).collect::>(); + assert!(!bb.is_empty()); + let wahl = |name: &str| bb.iter().find(|c| c.class == klasse(name)).unwrap(); + assert_eq!(wahl("AA").action as usize, call); + assert_eq!(wahl("KK").action as usize, call); + assert_eq!(wahl("72o").action as usize, fold); + assert_eq!(wahl("32o").action as usize, fold); + // value of the choice (independent sample): AA about +7.0, 72o exactly -1 + assert!((wahl("AA").v_br - 7.0).abs() < 0.8, "{:?}", wahl("AA")); + assert!((wahl("72o").v_br + 1.0).abs() < 1e-9, "{:?}", wahl("72o")); + // away from the 45 % line the sampled choice agrees with the equity rule (oracle: the exact caller's threshold on class equities) + let tisch = jp::Tisch { mein_drin: 0.5, ziel: 10.0, tot: 0.0, gegner: vec![jp::Sitz { drin: 1.0, rest: 9.0 }] }; + let rake = jp::RakeModell::Linear { satz: 0.0, deckel: 0.0 }; + let mut w169 = [0f32; KLASSEN]; + for (c, x) in w169.iter_mut().enumerate() { + *x = vorflop_kombos(c); + } + let eq = jp::klassen_gegen(&w169, 20_000); + let mut gepruft = 0; + for c in bb.iter() { + let e = eq[c.class].unwrap() as f64; + if (e - 0.45).abs() > 0.05 { + gepruft += 1; + assert_eq!(c.action as usize == call, jp::ruft_bestantwort(e, &tisch, 0, &rake), "class {} eq {e}", vorflop_name(c.class)); + } + } + assert!(gepruft > 100, "{gepruft}"); + let _ = fold; + } + + #[test] + fn spec2_the_best_response_value_is_never_below_the_table_value() { + // (a) pushfold: the table calls always, the best response folds the bottom of the range -> clearly positive gain at the BB node + let (s, st) = pushfold(); + let t = leere_tabellen(); + let r = Rechner { s: &s, t: &t, st: &st }; + let mut prm = params(600); + prm.exact_jam = false; + let nr = node_br(&r, &[], &[klasse("AKs")], &prm, &Seeds::derive(11), None); + for c in nr.choices.iter().filter(|c| c.n > 1) { + assert!(c.v_br - c.v_table >= -4.0 * c.se_gain, "class {} {:?}", vorflop_name(c.class), c); + } + let g = node_gains(&nr.choices); + assert_eq!(g.len(), 1); + assert!(g[0].gain > 0.3 && g[0].gain > 3.0 * g[0].se, "{:?}", g[0]); + // (b) a deeper heads-up tree with a random table: at every opponent node the gain is >= 0 up to noise + let s = Spiel::neu("vorflop20"); + let st = tafel_bytes(&s, &|ni, c, n| { + let mut x = Rng(misch(ni as u64 * 1000 + c as u64, 77) | 1); + let w: Vec = (0..n).map(|_| 1 + x.unter(100)).collect(); + let sum: u32 = w.iter().sum(); + let mut v: Vec = w.iter().map(|a| (a * 255 / sum) as u8).collect(); + let rest = 255 - v.iter().map(|x| *x as u32).sum::(); + v[0] += rest as u8; + v + }); + let r = Rechner { s: &s, t: &t, st: &st }; + let nr = node_br(&r, &[], &[klasse("T9s"), klasse("22")], ¶ms(300), &Seeds::derive(3), None); + let gains = node_gains(&nr.choices); + assert!(gains.len() >= 3, "{}", gains.len()); + for g in &gains { + assert!(g.gain >= -3.0 * g.se.max(1e-9), "{g:?}"); + } + } + + #[test] + fn spec3_the_all_in_uses_the_exact_caller() { + let (s, st) = pushfold(); + let t = leere_tabellen(); + let r = Rechner { s: &s, t: &t, st: &st }; + let prm = params(3000); + let h72 = klasse("72o"); + let nr = node_br(&r, &[], &[h72, klasse("AA")], &prm, &Seeds::derive(21), None); + assert!(nr.exact_jam_applied); + let jam = nr.moves.iter().find(|m| m.role == Rolle::Jam).unwrap(); + assert_eq!(jam.source, Source::ExactJam); + // the opponent's choice at his node equals the exact caller class by class + let (y, fold, call) = bb_knoten(&s); + let my = y.menue(&s); + let key = y.schluessel(&my); + let w = Zustand::start(&s); + let rw0 = r.reichweite(&[]); + let mut pol = Politik::new(); + let je = exact_jam_response(&r, &w, 1, &rw0, &mut pol).expect("applies: the BB only has fold / call"); + for c in 0..KLASSEN { + let erwartet = if je.ruft[0][c] { call } else { fold }; + assert_eq!(pol[&(key, c)] as usize, erwartet); + } + // consistent with the closed-form price: the BB calls 9 into 20 + assert!((je.tisch.ziel - 10.0).abs() < 1e-9 && (je.tisch.mein_drin - 0.5).abs() < 1e-9 && (je.tisch.gegner[0].drin - 1.0).abs() < 1e-9); + // W_BR of the all-in (paired rollouts with the exact policy) agrees with the independent exact evaluator ev_jam + for c in &nr.classes { + let x = c.jam_exact.expect("cross check present"); + let wj = &c.moves[jam.idx].w_br; + let tol = 4.0 * (x.se * x.se + wj.se * wj.se).sqrt() + 0.05; + assert!((x.mean - wj.mean).abs() < tol, "class {}: ev_jam {:?} vs rollouts {:?}", vorflop_name(c.class), x, wj); + } + // fold is worth exactly minus the small blind and has no opponent decisions + let fold_idx = nr.moves.iter().position(|m| m.role == Rolle::Fold).unwrap(); + assert_eq!(nr.moves[fold_idx].source, Source::Fixed); + for c in &nr.classes { + assert!((c.moves[fold_idx].w_br.mean + 0.5).abs() < 1e-9); + } + // with only fold and all-in on the menu the best other move is fold; the all-in minus fold is formed paired on the same deals + let c72 = nr.classes.iter().find(|c| c.class == h72).unwrap(); + let d = c72.allin_minus_best_other.as_ref().unwrap(); + assert_eq!(nr.moves[d.best_other].role, Rolle::Fold); + // 72o jamming 10 bb into a BB that calls exactly when it pays loses clearly against fold (about -2.1 against -0.5) + assert!(d.diff.upper < 0.0, "{:?}", d.diff); + let caa = nr.classes.iter().find(|c| c.class == klasse("AA")).unwrap(); + assert!(caa.allin_minus_best_other.as_ref().unwrap().diff.lower > 0.0); + } + + #[test] + fn spec3b_a_best_response_cannot_help_us_on_average_over_our_jam_range() { + // zero-sum, no rake: averaged over our whole jam range (all classes weighted by combos) the best response is worth no more than the table answer + let (s, st) = pushfold(); + let t = leere_tabellen(); + let r = Rechner { s: &s, t: &t, st: &st }; + let alle: Vec = (0..KLASSEN).collect(); + let mut prm = params(400); + prm.diagnose = false; + let nr = node_br(&r, &[], &alle, &prm, &Seeds::derive(8), None); + let jam = nr.moves.iter().find(|m| m.role == Rolle::Jam).unwrap().idx; + let g: f64 = nr.classes.iter().map(|c| vorflop_kombos(c.class) as f64).sum(); + let mittel: f64 = nr.classes.iter().map(|c| vorflop_kombos(c.class) as f64 / g * c.moves[jam].br_minus_table.mean).sum(); + let se: f64 = nr.classes.iter().map(|c| (vorflop_kombos(c.class) as f64 / g * c.moves[jam].br_minus_table.se).powi(2)).sum::().sqrt(); + assert!(mittel <= 3.0 * se, "{mittel} {se}"); + assert!(mittel < -0.1, "the BB's best response must cost the jam range something: {mittel}"); + } + + #[test] + fn spec4_selection_and_valuation_use_separate_seeds() { + assert!(Seeds::new(1, 1, 2).is_err() && Seeds::new(1, 2, 1).is_err() && Seeds::new(2, 1, 1).is_err()); + assert!(Seeds::new(1, 2, 3).is_ok()); + for base in 0..2000u64 { + let s = Seeds::derive(base); + assert!(s.choice != s.value && s.choice != s.best && s.value != s.best); + } + } + + #[test] + #[should_panic(expected = "different seeds")] + fn spec4b_node_br_aborts_when_choice_and_value_seeds_are_equal() { + let (s, st) = pushfold(); + let t = leere_tabellen(); + let r = Rechner { s: &s, t: &t, st: &st }; + node_br(&r, &[], &[0], ¶ms(10), &Seeds { choice: 5, value: 5, best: 6 }, None); + } + + #[test] + fn spec5_multi_level_tree_runs_and_pruning_is_reported() { + let s = Spiel::neu("vorflop20"); + let t = leere_tabellen(); + let st = tafel_bytes(&s, &|_, _, n| { + let mut v = vec![0u8; n]; + let base = 255 / n as u32; + v.iter_mut().for_each(|x| *x = base as u8); + v[0] += (255 - base * n as u32) as u8; + v + }); + let r = Rechner { s: &s, t: &t, st: &st }; + let mut prm = params(40); + prm.diagnose = false; + prm.reach_min = 0.0; + let a = node_br(&r, &[], &[klasse("AKs")], &prm, &Seeds::derive(1), None); + prm.reach_min = 0.2; + let b = node_br(&r, &[], &[klasse("AKs")], &prm, &Seeds::derive(1), None); + let (na, nb): (usize, usize) = (a.moves.iter().map(|m| m.opp_nodes).sum(), b.moves.iter().map(|m| m.opp_nodes).sum()); + assert!(na > nb && b.moves.iter().map(|m| m.pruned_mass).sum::() > 0.0, "{na} {nb}"); + assert!(b.choice_rollouts < a.choice_rollouts); + } +} diff --git a/entscheiden/motor/src/vorflop_selbst_rechnen.rs b/entscheiden/motor/src/vorflop_selbst_rechnen.rs index 9396badd..2c9ea3db 100644 --- a/entscheiden/motor/src/vorflop_selbst_rechnen.rs +++ b/entscheiden/motor/src/vorflop_selbst_rechnen.rs @@ -47,6 +47,7 @@ pub struct Rechner<'a> { } /// Ranges je Sitz in Klassen (Produkt der Tafelanteile der Zuege dieses Sitzes auf dem Weg) und die Erreichbarkeit des Knotens unter der Tafel. +#[derive(Clone)] pub struct Reichweite { pub w: [[f32; KLASSEN]; MAXN], pub erreich: f64, @@ -74,6 +75,9 @@ pub struct Ueber<'a> { pub mischung: &'a [Vec], } +/// Feste Wahl je (Vorflop-Knoten, Klasse) statt der Tafelmischung: Index des Menuezugs (beste Antwort der Gegner, `vorflop_selbst_br_nach.rs`). Leer = Tafel. +pub type Politik = std::collections::HashMap<(u64, usize), u8>; + /// Rohe Stichprobe einer Klasse (vor der Bewertung). #[derive(Clone)] pub struct Roh { @@ -162,26 +166,30 @@ impl Rechner<'_> { /// Wie `reichweite`; `gepostet[p]`: Sitz p hat nachgepostet, sein Mitgehen vor dem Flop war keine Wahl (wie `ranges_mit`: kein Tafelanteil). pub fn reichweite_mit(&self, pfad: &[(Zustand, u8)], gepostet: &[bool; MAXN]) -> Reichweite { - let mut w = [[1f32; KLASSEN]; MAXN]; - let mut erreich = 1f64; + let mut rw = Reichweite { w: [[1f32; KLASSEN]; MAXN], erreich: 1f64 }; for (z, code) in pfad { if gepostet[z.dran as usize] && z.strasse == 0 && z.hoch == 100 && *code == CALL { continue; } - let m = z.menue(self.s); - let Some(i) = m.liste().iter().position(|x| x.code == *code) else { continue }; - let (key, d) = (z.schluessel(&m), z.dran as usize); - let (mut vor, mut nach) = (0f64, 0f64); - for c in 0..KLASSEN { - let p = self.tafel(key, c, m.n).map_or(1.0 / m.n as f32, |v| v[i]); - let k = vorflop_kombos(c) as f64; - vor += k * w[d][c] as f64; - nach += k * (w[d][c] * p) as f64; - w[d][c] *= p; - } - erreich *= if vor > 0.0 { nach / vor } else { 0.0 }; + self.reichweite_schritt(&mut rw, z, *code); } - Reichweite { w, erreich } + rw + } + + /// Ein Zug des Wegs: die Range des Ziehenden wird mit dem Tafelanteil des Zugs `code` je Klasse multipliziert (ungesehene Punkte: gleichverteilt). + pub fn reichweite_schritt(&self, rw: &mut Reichweite, z: &Zustand, code: u8) { + let m = z.menue(self.s); + let Some(i) = m.liste().iter().position(|x| x.code == code) else { return }; + let (key, d) = (z.schluessel(&m), z.dran as usize); + let (mut vor, mut nach) = (0f64, 0f64); + for c in 0..KLASSEN { + let p = self.tafel(key, c, m.n).map_or(1.0 / m.n as f32, |v| v[i]); + let k = vorflop_kombos(c) as f64; + vor += k * rw.w[d][c] as f64; + nach += k * (rw.w[d][c] * p) as f64; + rw.w[d][c] *= p; + } + rw.erreich *= if vor > 0.0 { nach / vor } else { 0.0 }; } /// Zufallszahl der Wahl an diesem Punkt: aus Saat und Verlaufs-Pruefsumme (gleicher Verlauf = gleiche Zahl; gemeinsame Zufallszahlen auch nach @@ -212,7 +220,13 @@ impl Rechner<'_> { } /// Wie `spiele_aus_detail`; mit `ueber` spielt der Sitz `ueber.sitz` am Vorflop-Knoten `ueber.key` die gegebene Mischung je Klasse statt der Tafel (Regel gegen Ausnutzung). - pub fn spiele_aus_ueber(&self, mut z: Zustand, d: &mut Deal, p: usize, seed: u64, mut suche: Option<(&dyn Sucher, &mut Vec)>, ueber: Option<&Ueber>) -> Aus { + pub fn spiele_aus_ueber(&self, z: Zustand, d: &mut Deal, p: usize, seed: u64, suche: Option<(&dyn Sucher, &mut Vec)>, ueber: Option<&Ueber>) -> Aus { + self.spiele_aus_politik(z, d, p, seed, suche, ueber, None) + } + + /// Wie `spiele_aus_ueber`; mit `politik` spielt JEDER Sitz an den Vorflop-Knoten, die darin stehen, die feste Wahl (je Klasse) statt der Tafel. + #[allow(clippy::too_many_arguments)] + pub fn spiele_aus_politik(&self, mut z: Zustand, d: &mut Deal, p: usize, seed: u64, mut suche: Option<(&dyn Sucher, &mut Vec)>, ueber: Option<&Ueber>, politik: Option<&Politik>) -> Aus { let mut aus = Aus::default(); while !z.ende { let m = z.menue(self.s); @@ -248,6 +262,11 @@ impl Rechner<'_> { } } i = Self::waehle_u(Self::zahl(seed, &z), &v[..m.n]); + if let Some(a) = politik.filter(|_| z.strasse == 0).and_then(|po| po.get(&(z.schluessel(&m), kl))) { + if (*a as usize) < m.n { + i = *a as usize; + } + } } } if let Some((_, v)) = suche.as_mut() {