From ff418fe005210f792e20db44a942f9f717798967 Mon Sep 17 00:00:00 2001 From: Marc Mintel Date: Fri, 13 Nov 2026 22:45:51 +0100 Subject: [PATCH] River-DBR (Roadmap #1) gemessen: Verlierer, Arm bleibt aus Data-Biased Robust Counter-Strategy (cfr::dbr) als Heads-up-River-Spieler mit Read-Konfidenz je Knoten. Leiter gegen zaehl: -32.74 +-2.91 bb/100, alle gemessenen Profile verlieren, auch balancierte. Arm RIVER_DBR aus, aus = bit-identisch. Dazu: Zaehlungen je Read (COUNTS=1, eich_sim.py), Session-Memory-API, geparktes Check-Raise-Modell (RAISE_MODEL, aus). Co-Authored-By: Claude Opus 5.5 --- messung_engine/ERGEBNISSE.md | 6 + messung_engine/eich_sim.py | 36 ++++ messung_engine/warteschlange.txt | 7 +- src/bin/ab_zelle.rs | 15 +- src/cfr/dbr.rs | 273 +++++++++++++++++++++++++++++++ src/cfr/mod.rs | 1 + src/engine/bluff.rs | 73 ++++++++- src/engine/decide.rs | 5 + src/engine/options.rs | 7 +- src/engine/river_subgame.rs | 176 +++++++++++++++++++- src/exploit/sample.rs | 2 + src/sim/memory.rs | 26 ++- src/sim/session.rs | 14 +- tests/line_reads.rs | 22 +++ 14 files changed, 644 insertions(+), 19 deletions(-) create mode 100644 messung_engine/eich_sim.py create mode 100644 src/cfr/dbr.rs diff --git a/messung_engine/ERGEBNISSE.md b/messung_engine/ERGEBNISSE.md index 056fa5e9..f195e159 100644 --- a/messung_engine/ERGEBNISSE.md +++ b/messung_engine/ERGEBNISSE.md @@ -20,3 +20,9 @@ Check-Raise: der Abschlag ist ein Zusatzterm an einer EV-Formel, die keine Raise Varianten wurden an der Leiter nachgestellt. Ersetzt wird er durch ein konsistentes Modell (Antwort des Gegners als gelernte Verteilung Fold/Call/Value-Raise/Bluff-Raise, Heros Antwort auf das Raise gerechnet) mit Priors, die aus echten Haenden geschaetzt sind (Empirical Bayes), statt handgesetzter Anker. + +## River-DBR (Roadmap #1, 13.11. nachts) + +Data-Biased Robust Counter-Strategy (Johanson/Bowling 2009, `src/cfr/dbr.rs`) als ganzer Heads-up-River-Spieler, w je Knoten = Read-Konfidenz, Arm RIVER_DBR=1. +Identitaet Arm aus vs zaehl: 0 Deals geaendert. Ergebnis gegen zaehl (58/76 Zellen, abgebrochen): **GESAMT -32.74 +-2.91 bb/100, alle 15 gemessenen Profile verlieren** (maniac -70.9, umgekehrt -59.3, nemesis-2 -51.1, balanciert -34.3). +Befund: verliert auch gegen balancierte Gegner, also liegt es nicht am Exploit, sondern am River-Spiel des Subgames selbst (eine Groesse, symmetrische Hero-Range, Schwellenmodell). Wie schon das volle Getriebe. Arm bleibt aus; Linie gestoppt. diff --git a/messung_engine/eich_sim.py b/messung_engine/eich_sim.py new file mode 100644 index 00000000..e607177f --- /dev/null +++ b/messung_engine/eich_sim.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python3 +"""Population-Priors der Sim per Empirical Bayes: liest die Zaehlungen eines Zaehl-Laufs +(`ab_zelle` mit COUNTS=1, je Zelle `..counts`: "read n k") und schaetzt je Read +(mu, kappa) mit lesen/eichung.py. Jede Zelle ist ein Gegner (Welt: ein gezogenes Individuum; +klassisch: dasselbe Profil mit anderem Seed). + + python messung_engine/eich_sim.py messung_engine/arme/zaehl +""" +import glob +import os +import sys + +_w = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(_w, "lesen")) + +import eichung + +ordner = sys.argv[1] +je_read = {} +for pfad in sorted(glob.glob(os.path.join(ordner, "*.counts"))): + zelle = os.path.basename(pfad)[: -len(".counts")] + for zeile in open(pfad, encoding="utf-8"): + teile = zeile.split() + if len(teile) == 3: + je_read.setdefault(teile[0], []).append((zelle, int(teile[1]), int(teile[2]))) + +for read, zellen in je_read.items(): + e = eichung.schaetzen([(n, k) for _, n, k in zellen]) + if not e: + continue + lo, hi = e["kappa_95"] + print(f"{read:15} mu={e['mu']:.4f} kappa={e['kappa']:8.1f} 95%=[{lo:.1f}, {hi:.1f}]" + f"{'+' if e['kappa_offen_nach_oben'] else ''} zellen={e['spieler']} chancen={e['chancen']}") + if "-v" in sys.argv: + for zelle, n, k in zellen: + print(f" {zelle:16} {k:6}/{n:<6} {k / n if n else float('nan'):.3f}") diff --git a/messung_engine/warteschlange.txt b/messung_engine/warteschlange.txt index 9b09d97b..0f92470a 100644 --- a/messung_engine/warteschlange.txt +++ b/messung_engine/warteschlange.txt @@ -1,4 +1,4 @@ -# id|exe|argumente|env|arbeitsordner (Arm-Ergebnisse: arme//, Vergleich: python ab.py arme/basis arme/) +# id|exe|argumente|env|arbeitsordner (Arm-Ergebnisse: arme//, Vergleich: python ab.py arme/basis arme/) basis|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\bin\pokerbench-engine-basis.exe|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\arme\basis 2000 4000 4 all|| id-turn|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\bin\pokerbench-engine-turn.exe|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\arme\id-turn 2000 4000 1 nemesis-1,nemesis-3,wert-sizer,textur-cbet|TURN_VETO=0| id-p2|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\bin\pokerbench-engine-p2.exe|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\arme\id-p2 2000 4000 1 nemesis-1,nemesis-3,wert-sizer,textur-cbet|| @@ -11,6 +11,9 @@ linie-basis|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b linie-cbet|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\bin\pokerbench-engine-linie.exe|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\arme\linie-cbet 2000 4000 4 all|READS=cbet| linie-xr|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\bin\pokerbench-engine-linie.exe|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\arme\linie-xr 2000 4000 4 all|READS=xr| linie-3bet|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\bin\pokerbench-engine-linie.exe|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\arme\linie-3bet 2000 4000 4 all|READS=3bet| -turn-draw-rest|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\bin\pokerbench-engine-turn.exe|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\arme\turn-draw 2000 4000 4 all|| +#turn-draw-rest|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\bin\pokerbench-engine-turn.exe|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\arme\turn-draw 2000 4000 4 all|| linie-xr2|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\bin\pokerbench-engine-linie2.exe|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\arme\linie-xr2 2000 4000 4 nemesis-2,check-raiser,cbet-folder,3bet-folder|READS=xr;POKERBENCH_THREADS=16| linie-xr3|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\bin\pokerbench-engine-linie3.exe|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\arme\linie-xr3 2000 4000 4 nemesis-2,check-raiser,cbet-folder,3bet-folder|READS=xr;POKERBENCH_THREADS=16| +zaehl|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\bin\pokerbench-engine-zaehl.exe|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\arme\zaehl 2000 4000 4 all|COUNTS=1;POKERBENCH_THREADS=28| +id-dbr|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\bin\pokerbench-engine-dbr.exe|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\arme\id-dbr 2000 4000 1 nemesis-1,nemesis-3,station,reg|POKERBENCH_THREADS=28| +dbr-an|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\bin\pokerbench-engine-dbr.exe|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\arme\dbr-an 2000 4000 4 all|RIVER_DBR=1;POKERBENCH_THREADS=28| diff --git a/src/bin/ab_zelle.rs b/src/bin/ab_zelle.rs index 54332b28..4cd0f352 100644 --- a/src/bin/ab_zelle.rs +++ b/src/bin/ab_zelle.rs @@ -15,7 +15,7 @@ use rechner::rng::Rng; use rechner::sim::opponent::Opponent; use rechner::sim::reader::{Rules, Style}; -use rechner::sim::session::{deal_samples, ReadMode, Setup}; +use rechner::sim::session::{deal_samples_memory, ReadMode, Setup}; use rechner::sim::welt::{Persona, ARCHETYPES}; use std::sync::atomic::{AtomicUsize, Ordering}; @@ -45,6 +45,10 @@ fn apply_arm() { _ => m, }); set_line_reads(mask); + // RAISE_MODEL=1: the check-raise in the tree of a bet into a check (`engine::bluff`). + rechner::engine::bluff::set_raise_model(std::env::var("RAISE_MODEL").as_deref() == Ok("1")); + // RIVER_DBR=1: the data-biased robust river counter-strategy (`engine::river_subgame::dbr_decision`). + rechner::engine::river_subgame::set_dbr(std::env::var("RIVER_DBR").as_deref() == Ok("1")); } fn klassik(name: &str) -> Option { @@ -110,13 +114,20 @@ fn main() { let Some((name, k, _)) = jobs.get(j) else { break }; let (opponent, deals, seed) = cell(name, *k, welt_deals, klassik_deals); let setup = Setup { players: 2, opponent, deals, stack_bb: STACK_BB, seed, read: ReadMode::Memory }; - let (samples, m) = deal_samples(&setup); + let (samples, m, memory) = deal_samples_memory(&setup); let body: Vec = samples.iter().map(|x| format!("{x}")).collect(); let file = format!("{out}/{name}.{k}.txt"); let tmp = format!("{file}.tmp"); std::fs::write(&tmp, body.join(" ")).expect("write samples"); std::fs::rename(&tmp, &file).expect("finish samples"); + // COUNTS=1: the read counts the hero gathered on this opponent (population-prior fit). + if std::env::var("COUNTS").as_deref() == Ok("1") { + let lines: Vec = + memory.line_counts().iter().map(|(r, n, k)| format!("{r} {n} {k}")).collect(); + std::fs::write(format!("{out}/{name}.{k}.counts"), lines.join(" +")).expect("write counts"); + } println!("{name:<12} k={k} {:>+8.2} bb/100 +-{:>6.2}", m.bb_per_100, m.ci95); } }); diff --git a/src/cfr/dbr.rs b/src/cfr/dbr.rs new file mode 100644 index 00000000..64da9916 --- /dev/null +++ b/src/cfr/dbr.rs @@ -0,0 +1,273 @@ +//! Data-Biased Robust counter-strategy (Johanson & Bowling, "Data Biased Robust Counter Strategies", +//! AISTATS 2009) - safe exploitation of a modelled opponent. +//! +//! CFR+ on a restricted game: at each of the modelled player's decision nodes it plays the MODEL +//! with weight `w[node]` and a freely learned (regret-matched) strategy with weight `1 - w`. The other +//! player - hero - solves this game with plain CFR+; its average strategy is the counter-strategy. +//! +//! - `w = 0` everywhere: the ordinary game, hero's strategy is a Nash equilibrium (unexploitable). +//! - `w = 1` everywhere: the opponent is the model, hero's strategy is a best response to it +//! (maximal exploitation, unbounded exploitability). +//! - in between: the opponent may deviate from the model wherever the data is thin, so hero only +//! exploits as far as the data reaches. Johanson & Bowling show the result is on (or near) the +//! Pareto frontier of "value against the model" versus "worst case against anyone". +//! +//! Unlike the KL tilt around GTO (`cfr::kl_br`), the counter-strategy's support is free: it can play +//! actions an equilibrium never plays (the thin value bet against a station), which is exactly the +//! offense the KL tilt could not reach (`docs/notizen/BEFUND-river-gearbox-belief-trust.md`). +//! +//! `w` is per node - the confidence of the model AT THAT NODE (how much of the villain's play there +//! the data has seen): a fold-to-bet read can be strong while the bluff read is thin. + +use super::regret_matching::matched; +use super::solver_state::SolverState; +use super::strategy::{average_strategy, Strategy}; +use super::terminal_value::terminal_value; +use super::tree::{Node, Tree}; +use super::value_walk::{root_values, Responder}; + +/// The modelled player, its model and the per-node weight of the model (0 = free, 1 = fixed). +pub struct Restriction<'a> { + pub player: usize, + pub model: &'a Strategy, + /// One weight per tree node; only the modelled player's decision nodes are read. + pub weight: Vec, +} + +impl Restriction<'_> { + fn w(&self, node: usize) -> f64 { + self.weight.get(node).copied().unwrap_or(0.0).clamp(0.0, 1.0) + } + + /// The modelled player's effective row block at `node`: `w * model + (1 - w) * free`. + fn mix(&self, node: usize, free: &[f64], classes: usize, actions: usize) -> Vec { + let w = self.w(node); + (0..classes * actions) + .map(|k| { + let model = self.model.row(node, k / actions).get(k % actions).copied().unwrap_or(0.0); + w * model + (1.0 - w) * free[k] + }) + .collect() + } +} + +/// One CFR+ iteration of the restricted game (alternating, linear averaging, as `cfr::iterate`). +pub fn iterate_restricted(tree: &Tree, state: SolverState, r: &Restriction) -> SolverState { + let (iteration, mut regret, mut sums) = state.into_parts(); + let next = iteration.saturating_add(1); + if tree.is_playable() && regret.len() == tree.nodes.len() { + let ones = vec![1.0; tree.classes]; + for player in 0..2 { + let mut pass = Pass { tree, r, player, weight: next as f64, regret: &mut regret, sums: &mut sums }; + pass.walk(tree.root, &ones, &ones); + } + } + SolverState::from_parts(next, regret, sums) +} + +/// Solve the restricted game for `iterations` and return the joint strategy: the counter-player's +/// average strategy, and for the modelled player its effective mix (model weighted with its average +/// free strategy) - so `value_walk` on the result evaluates the counter-strategy against the +/// restricted opponent it was trained on. +pub fn solve_restricted(tree: &Tree, r: &Restriction, iterations: u32) -> Strategy { + let mut state = SolverState::fresh(tree); + for _ in 0..iterations { + state = iterate_restricted(tree, state, r); + } + let avg = average_strategy(tree, &state); + let mut out = avg.clone(); + for (node, n) in tree.nodes.iter().enumerate() { + if let Node::Decision { player, name, children } = n { + if *player == r.player { + let a = children.len(); + let free: Vec = (0..tree.classes).flat_map(|c| avg.row(node, c).to_vec()).collect(); + let mixed = r.mix(node, &free, tree.classes, a); + out = out.with_rows(tree, name, |c| mixed[c * a..(c + 1) * a].to_vec()).unwrap_or(out); + } + } + } + out +} + +/// What player `hero` wins with `strategy`'s hero rows when the other player best-responds (the +/// worst case over all opponents), summed over the deal like `exploitability::game_value`. +pub fn worst_case_value(tree: &Tree, strategy: &Strategy, hero: usize) -> f64 { + let hero = hero.min(1); + let other: f64 = root_values(tree, strategy, Responder::Best, 1 - hero, &mut |_| {}).iter().sum(); + -other +} + +/// What player `hero` wins with `strategy`'s hero rows against the opponent rows of `opponent`. +pub fn value_against(tree: &Tree, strategy: &Strategy, opponent: &Strategy, hero: usize) -> f64 { + let hero = hero.min(1); + let mut joint = strategy.clone(); + for (node, n) in tree.nodes.iter().enumerate() { + if let Node::Decision { player, name, .. } = n { + if *player != hero { + joint = joint.with_rows(tree, name, |c| opponent.row(node, c).to_vec()).unwrap_or(joint); + } + } + } + root_values(tree, &joint, Responder::Follow, hero, &mut |_| {}).iter().sum() +} + +struct Pass<'a> { + tree: &'a Tree, + r: &'a Restriction<'a>, + player: usize, + weight: f64, + regret: &'a mut Vec>, + sums: &'a mut Vec>, +} + +impl Pass<'_> { + /// The strategy a decision node is played with this iteration: regret matching, mixed with the + /// model at the modelled player's nodes. Also returns the free (regret-matched) part. + fn sigma(&self, node: usize, player: usize, actions: usize) -> (Vec, Vec) { + let free = matched(&self.regret[node], actions); + if player == self.r.player { + (self.r.mix(node, &free, self.tree.classes, actions), free) + } else { + (free.clone(), free) + } + } + + fn walk(&mut self, node: usize, own: &[f64], opp: &[f64]) -> Vec { + let tree = self.tree; + let n = tree.classes; + match tree.nodes.get(node) { + None => vec![0.0; n], + Some(Node::Terminal(payoff)) => terminal_value(payoff, &tree.chance, n, self.player, opp), + Some(Node::Chance(branches)) => { + let mut total = vec![0.0; n]; + for (p, child) in branches { + let scaled: Vec = opp.iter().map(|x| x * p).collect(); + let value = self.walk(*child, own, &scaled); + total.iter_mut().zip(&value).for_each(|(t, v)| *t += v); + } + total + } + Some(Node::Decision { player, children, .. }) => { + let actions = children.len(); + if actions == 0 { + return vec![0.0; n]; + } + let (sigma, free) = self.sigma(node, *player, actions); + if *player == self.player { + self.own_node(node, children, &sigma, &free, own, opp) + } else { + let mut total = vec![0.0; n]; + for (a, child) in children.iter().enumerate() { + let reach: Vec = (0..n).map(|j| opp[j] * sigma[j * actions + a]).collect(); + let value = self.walk(*child, own, &reach); + total.iter_mut().zip(&value).for_each(|(t, v)| *t += v); + } + total + } + } + } + } + + /// The traverser's node: reach flows with the played (`sigma`) strategy; regrets and averages + /// belong to the free part (the model part is not chosen, so it carries no regret). + fn own_node(&mut self, node: usize, children: &[usize], sigma: &[f64], free: &[f64], own: &[f64], opp: &[f64]) -> Vec { + let n = self.tree.classes; + let actions = children.len(); + let values: Vec> = children + .iter() + .enumerate() + .map(|(a, child)| { + let reach: Vec = (0..n).map(|i| own[i] * sigma[i * actions + a]).collect(); + self.walk(*child, &reach, opp) + }) + .collect(); + let mut played = vec![0.0; n]; + for i in 0..n { + played[i] = (0..actions).map(|a| sigma[i * actions + a] * values[a][i]).sum(); + let free_value: f64 = (0..actions).map(|a| free[i * actions + a] * values[a][i]).sum(); + for a in 0..actions { + let r = &mut self.regret[node][i * actions + a]; + *r = (*r + values[a][i] - free_value).max(0.0); + self.sums[node][i * actions + a] += self.weight * own[i] * free[i * actions + a]; + } + } + played + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::cfr::exploitability::{exploitability, game_value}; + use crate::cfr::river::tree_with_chance; + use crate::cfr::solve::solve; + use crate::rng::Rng; + + /// A 6-bucket river with a uniform independent deal, pot 6, bet 4. + fn river() -> Tree { + let n = 6; + tree_with_chance(n, vec![1.0 / (n * n) as f64; n * n], 6.0, 4.0) + } + + /// A calling station: calls every bet, never bets when checked to. + fn station(tree: &Tree) -> Strategy { + let base = Strategy::uniform(tree); + let s = base.with_rows(tree, "v_bet", |_| vec![0.0, 1.0]).unwrap_or(base); + s.with_rows(tree, "v_check", |_| vec![1.0, 0.0]).unwrap_or(s) + } + + fn weights(tree: &Tree, w: f64) -> Vec { + tree.nodes + .iter() + .map(|n| match n { + Node::Decision { player: 1, .. } => w, + _ => 0.0, + }) + .collect() + } + + #[test] + fn zero_weight_is_nash() { + let tree = river(); + let model = station(&tree); + let r = Restriction { player: 1, model: &model, weight: weights(&tree, 0.0) }; + let s = solve_restricted(&tree, &r, 4000); + assert!(exploitability(&tree, &s) < 0.02, "{}", exploitability(&tree, &s)); + } + + #[test] + fn the_counter_strategy_trades_worst_case_for_value_against_the_model() { + let tree = river(); + let model = station(&tree); + let nash = solve(&tree, 4000, Rng::seeded(1)).strategy; + let v_star = game_value(&tree, &nash); + let mut last_model_value = f64::NEG_INFINITY; + let mut last_worst = f64::INFINITY; + for w in [0.0, 0.5, 0.8, 1.0] { + let r = Restriction { player: 1, model: &model, weight: weights(&tree, w) }; + let s = solve_restricted(&tree, &r, 4000); + let vs_model = value_against(&tree, &s, &model, 0); + let worst = worst_case_value(&tree, &s, 0); + // More trust in the model: never less value against it, never a better worst case. + assert!(vs_model >= last_model_value - 1e-3, "w {w}: {vs_model} < {last_model_value}"); + assert!(worst <= last_worst + 1e-3, "w {w}: {worst} > {last_worst}"); + assert!(worst <= v_star + 1e-2); + last_model_value = vs_model; + last_worst = worst; + } + // Against the station the counter-strategy beats the equilibrium clearly. + assert!(last_model_value > value_against(&tree, &nash, &model, 0) + 0.1); + } + + #[test] + fn it_value_bets_thin_where_the_equilibrium_never_bets() { + // Bucket 3 of 6 (a medium hand): the equilibrium checks it; against a station that calls + // everything it is a value bet (beats half the calling range). The KL tilt cannot reach this. + let tree = river(); + let model = station(&tree); + let r = Restriction { player: 1, model: &model, weight: weights(&tree, 1.0) }; + let s = solve_restricted(&tree, &r, 4000); + assert!(s.row(0, 4)[1] > 0.9, "{:?}", s.row(0, 4)); + assert!(s.row(0, 0)[1] < 0.1, "{:?}", s.row(0, 0)); // never bluffs a station + } +} diff --git a/src/cfr/mod.rs b/src/cfr/mod.rs index 736de7c0..b33c2a5f 100644 --- a/src/cfr/mod.rs +++ b/src/cfr/mod.rs @@ -62,6 +62,7 @@ pub mod chance_table; pub mod chart_deck; pub mod chart_signature; pub mod defenders; +pub mod dbr; pub mod deviation; pub mod environment; pub mod equity_matrix; diff --git a/src/engine/bluff.rs b/src/engine/bluff.rs index cc0c40a0..12e09af1 100644 --- a/src/engine/bluff.rs +++ b/src/engine/bluff.rs @@ -10,9 +10,12 @@ //! | never bluff-catch | facing a bet without a real draw, a hand below the bettor's value floor may not call when their bluff share is under 0.05 | use super::semibluff::has_real_draw; +use crate::exploit::bluff_share::bluff_share; +use crate::exploit::profile::Profile; use crate::exploit::range_spec::Continuation; +use crate::exploit::sample::CHECK_RAISE_ANCHOR; use crate::exploit::street_continuation::continuations; -use crate::game::{Spot, Villain}; +use crate::game::{line, Spot, Villain}; use crate::odds::break_even::break_even; use crate::odds::ev::final_pot; use crate::read::hand_read::HandRead; @@ -62,6 +65,74 @@ pub fn branches(spot: &Spot, to: f64, fold: f64, called_share: f64) -> Branches Branches { fold: fold_branch, called, total: fold_branch + called } } +/// Villain's check-raise as a multiple of hero's bet (model assumption: the standard 3x raise). +pub const CHECK_RAISE_MULTIPLE: f64 = 3.0; + +static RAISE_MODEL: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// Switch the check-raise response model on or off (ladder arm until proven). Default off. +pub fn set_raise_model(on: bool) { + RAISE_MODEL.store(on, std::sync::atomic::Ordering::Relaxed); +} + +fn raise_model_on() -> bool { + RAISE_MODEL.load(std::sync::atomic::Ordering::Relaxed) +} + +/// Heads-up, betting into a villain who checked this street: its check-raise rate (the read, else +/// the population's `CHECK_RAISE_ANCHOR`) and its profile. `None` elsewhere or with the model off. +pub fn check_raise_rate(spot: &Spot) -> Option<(f64, Option)> { + if !raise_model_on() { + return None; + } + let mut live = spot.live_villains(); + let (Some(v), None) = (live.next(), live.next()) else { return None }; + if !line::checked_to(&spot.history, v.seat, spot.street) { + return None; + } + let rho = v.profile.and_then(|p| p.check_raise).filter(|x| !x.is_nan()).unwrap_or(CHECK_RAISE_ANCHOR); + Some((rho.clamp(0.0, 1.0), v.profile)) +} + +/// A bet of `to` into a check, with the check-raise in the tree. The fold read counts folds over +/// folds and calls (raises are not in it, `sim::memory`, `lesen/zaehler.py`), so with a raise rate +/// `rho` the villain folds `(1 - rho) * fold`, calls `(1 - rho) * (1 - fold)` and raises `rho`; +/// against the raise hero plays its best response (`raise_response`). Ignoring the raise - as +/// `branches` does - overstates the fold branch by `1 / (1 - rho)` and drops the raise branch. +pub fn branches_vs_raise( + spot: &Spot, + to: f64, + fold: f64, + called_share: f64, + kind: RaiseKind, + rho: f64, + profile: Option<&Profile>, +) -> Branches { + let keep = 1.0 - rho; + let fold_branch = keep * fold * spot.pot; + let called = keep * (1.0 - fold) * (called_share * final_pot(spot.pot, spot.to_call, to) - to) + + rho * raise_response(spot, to, kind, profile); + Branches { fold: fold_branch, called, total: fold_branch + called } +} + +/// Hero's best response to a check-raise to `CHECK_RAISE_MULTIPLE * to`, in chips relative to +/// folding now: fold loses the bet; thin value beats the raise's bluffs (share `bluff_share` of the +/// raising range at that size) and calls when that pays. Bluffs and semibluffs fold (a draw's +/// equity against a value raise is not priced here - conservative). +pub fn raise_response(spot: &Spot, to: f64, kind: RaiseKind, profile: Option<&Profile>) -> f64 { + let fold = -to; + match kind { + RaiseKind::ThinValue => { + let raise_to = CHECK_RAISE_MULTIPLE * to; + let ratio = (raise_to - to) / (spot.pot + 2.0 * to); + let beats = bluff_share(profile, Some(ratio), spot.street); + let call = beats * (spot.pot + 2.0 * raise_to) - raise_to; + call.max(fold) + } + _ => fold, + } +} + /// Some villain never folds (foldToBet at or below `NEVER_FOLDS`). pub fn never_folds(spot: &Spot) -> bool { spot.live_villains() diff --git a/src/engine/decide.rs b/src/engine/decide.rs index 6b356b74..7a973b24 100644 --- a/src/engine/decide.rs +++ b/src/engine/decide.rs @@ -92,6 +92,11 @@ fn postflop(spot: &Spot, thresholds: &Thresholds, raw: &Spot, premium: f64) -> D // the offline/value-function form, not a live fold-veto. The turn solver + per-street belief // stay as tested primitives. See BEFUND-stage-b-turn-river-solver.md. if premium <= 0.0 { + // Arm (off by default, RIVER_DBR): the data-biased robust counter-strategy plays the + // heads-up river whenever the read is strong enough (`river_subgame::dbr_decision`). + if let Some(d) = super::river_subgame::dbr_decision(raw) { + return d.with_equity(equity.share); + } return super::river_subgame::fold_veto(raw, floored); } floored diff --git a/src/engine/options.rs b/src/engine/options.rs index c5f76914..7c2beb91 100644 --- a/src/engine/options.rs +++ b/src/engine/options.rs @@ -1,5 +1,5 @@ use super::bluff::{ - bluff_catch_blocked, branches, is_bluff_hand, never_folds, RaiseKind, PURE_BLUFF_EDGE, + bluff_catch_blocked, branches, branches_vs_raise, check_raise_rate, is_bluff_hand, never_folds, RaiseKind, PURE_BLUFF_EDGE, PURE_BLUFF_MIN_FOLD, }; use super::called::Called; @@ -133,7 +133,10 @@ pub fn scored( .filter_map(|to| { let fe = table_fold(spot, to, thresholds.fold_equity_scale); let against = realized_share(called.share_at(to, share), eff.villains); - let b = branches(spot, to, fe, against); + let b = match (kind, check_raise_rate(spot)) { + (RaiseKind::Value, _) | (_, None) => branches(spot, to, fe, against), + (k, Some((rho, profile))) => branches_vs_raise(spot, to, fe, against, k, rho, profile.as_ref()), + }; let keep = match kind { RaiseKind::Value | RaiseKind::ThinValue => true, RaiseKind::Semibluff => b.fold > 0.0 && b.total > 0.0 && b.total > floor, diff --git a/src/engine/river_subgame.rs b/src/engine/river_subgame.rs index 9f5fe625..7ac80d67 100644 --- a/src/engine/river_subgame.rs +++ b/src/engine/river_subgame.rs @@ -40,11 +40,12 @@ //! - The solver's action abstraction is one bet size, no raises (`cfr::river` v1). use crate::card::Card; +use crate::cfr::dbr::{solve_restricted, Restriction}; use crate::cfr::kl_br::kl_best_response; use crate::cfr::river::tree_with_chance; use crate::cfr::solve::{solve, Solved}; use crate::cfr::strategy::Strategy; -use crate::cfr::tree::Tree; +use crate::cfr::tree::{Node, Tree}; use crate::exploit::fold_chance::DEFAULT_FOLD_TO_BET; use crate::exploit::posterior::DEFAULT_AGGRESSION; use crate::exploit::profile::Profile; @@ -136,6 +137,13 @@ impl Subgame { /// plays actually be unexploitable; the coarse symmetric-uniform first cut was not, and measured /// worse than the heuristic. `None` for fewer than two distinct strengths. fn subgame(spot: &Spot, hero_combos: &[Vec], villain_combos: &[Vec], pot: f64, bet: f64) -> Option { + let (tree, ladder) = river_tree(spot, hero_combos, villain_combos, pot, bet)?; + let solved = solve(&tree, ITERS, Rng::seeded(spot.seed)); + Some(Subgame { tree, solved, ladder }) +} + +/// The card-exact river tree and its strength ladder, unsolved (see `subgame`). +fn river_tree(spot: &Spot, hero_combos: &[Vec], villain_combos: &[Vec], pot: f64, bet: f64) -> Option<(Tree, Vec)> { let rules = spot.rules(); let judged = |combos: &[Vec]| -> Vec<(Vec, Strength)> { combos.iter().filter_map(|c| judge(&rules, c, &spot.board).ok().map(|s| (c.clone(), s))).collect() @@ -167,9 +175,7 @@ fn subgame(spot: &Spot, hero_combos: &[Vec], villain_combos: &[Vec], return None; } chance.iter_mut().for_each(|x| *x /= total); - let tree = tree_with_chance(n, chance, pot, bet); - let solved = solve(&tree, ITERS, Rng::seeded(spot.seed)); - Some(Subgame { tree, solved, ladder }) + Some((tree_with_chance(n, chance, pot, bet), ladder)) } /// The believed villain strategy over the river tree, read off the opponent's `Profile`: how this @@ -191,9 +197,21 @@ fn subgame(spot: &Spot, hero_combos: &[Vec], villain_combos: &[Vec], /// default. Only the two villain rows matter to `kl_best_response` (it keeps hero's GTO rows); the /// base is a uniform strategy over the same tree, so the node widths line up. pub(crate) fn believed_villain(tree: &Tree, n: usize, profile: Option<&Profile>, pot: f64, bet: f64, aggression: Option) -> Strategy { + let rank = |c: usize| if n <= 1 { 1.0 } else { c as f64 / (n - 1) as f64 }; + believed_villain_ranked(tree, profile, pot, bet, aggression, rank) +} + +/// `believed_villain` with the position of each bucket in the villain's range given by `rank`. +fn believed_villain_ranked( + tree: &Tree, + profile: Option<&Profile>, + pot: f64, + bet: f64, + aggression: Option, + rank: impl Fn(usize) -> f64, +) -> Strategy { let f = profile.and_then(|p| p.fold_to_bet).filter(|x| !x.is_nan()).unwrap_or(DEFAULT_FOLD_TO_BET).clamp(0.0, 1.0); let a = aggression.filter(|x| !x.is_nan()).unwrap_or(DEFAULT_AGGRESSION).clamp(0.0, 1.0); - let rank = |c: usize| if n <= 1 { 1.0 } else { c as f64 / (n - 1) as f64 }; let gto_bluff = if pot + bet > 0.0 { bet / (pot + bet) } else { 0.0 }; let bluff_prob = if DEFAULT_AGGRESSION > 0.0 { (gto_bluff * a / DEFAULT_AGGRESSION).clamp(0.0, 1.0) } else { 0.0 }; @@ -360,6 +378,120 @@ pub fn river_exploit_plan(spot: &Spot, villain_combos: &[Vec], profile: Op }) } +static DBR: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// Switch the data-biased river counter-strategy on or off (ladder arm until proven). Default off. +pub fn set_dbr(on: bool) { + DBR.store(on, std::sync::atomic::Ordering::Relaxed); +} + +pub fn dbr_on() -> bool { + DBR.load(std::sync::atomic::Ordering::Relaxed) +} + +/// The believed villain with its thresholds on the COMBO MASS of its range, not on the rank of the +/// deduplicated strength ladder: `q[b]` is the mid-quantile of bucket `b` in the villain's marginal of +/// the deal table. On a paired board a few strength levels carry most combos; folding "the weakest +/// 45 %" must mean 45 % of the hands, not of the levels (BEFUND-river-gearbox-belief-trust, defect a). +fn believed_villain_by_mass(tree: &Tree, profile: Option<&Profile>, pot: f64, bet: f64, aggression: Option) -> Strategy { + let n = tree.classes; + let mut mass = vec![0.0; n]; + for h in 0..n { + for v in 0..n { + mass[v] += tree.chance.get(h * n + v).copied().unwrap_or(0.0); + } + } + let total: f64 = mass.iter().sum::().max(1e-12); + let mut below = 0.0; + let q: Vec = mass + .iter() + .map(|m| { + let mid = (below + m / 2.0) / total; + below += m; + mid + }) + .collect(); + believed_villain_ranked(tree, profile, pot, bet, aggression, |c| q[c]) +} + +/// The data-biased robust river counter-strategy (`cfr::dbr`): the villain plays the believed model +/// (`believed_villain_by_mass`) with the weight its data earns at each node - the fold-to-bet read's +/// confidence where it faces hero's bet, the bluff read's where it was checked to - and best-responds +/// wherever the data is thin. Hero's average strategy exploits the read only as far as the data goes, +/// with a FREE support (thin value against a station, which the KL tilt around GTO could not reach). +/// Below `CONFIDENCE_FLOOR` on both nodes the heuristic keeps the spot (`None`). +pub fn river_dbr_plan(spot: &Spot, villain_combos: &[Vec], profile: Option<&Profile>) -> Option { + if spot.street != Street::River || spot.live_villains().count() != 1 || villain_combos.is_empty() { + return None; + } + let p = profile?; + let ok = |x: Option| x.filter(|c| !c.is_nan()).unwrap_or(0.0).clamp(0.0, 1.0); + let w_call = ok(p.confidence); + let w_bet = ok(p.bluff_read_confidence()); + if w_call.max(w_bet) < CONFIDENCE_FLOOR { + return None; + } + let hero_strength = judge(&spot.rules(), &spot.hero_cards, &spot.board).ok()?; + let (pot, bet, facing) = if spot.to_call == 0.0 { + (spot.pot, bet_to(spot)?, false) + } else { + let pre = spot.pot - spot.to_call; + if pre <= 0.0 || spot.to_call <= 0.0 { + return None; + } + (pre, spot.to_call, true) + }; + let (tree, ladder) = river_tree(spot, villain_combos, villain_combos, pot, bet)?; + let model = believed_villain_by_mass(&tree, Some(p), pot, bet, river_bluff_aggression(Some(p), pot, bet)); + let weight: Vec = tree + .nodes + .iter() + .map(|node| match node { + Node::Decision { player: 1, name, .. } if *name == "v_bet" => w_call, + Node::Decision { player: 1, name, .. } if *name == "v_check" => w_bet, + _ => 0.0, + }) + .collect(); + let counter = solve_restricted(&tree, &Restriction { player: 1, model: &model, weight }, DBR_ITERS); + let hb = ladder.partition_point(|d| *d < hero_strength).min(ladder.len() - 1); + let node = if facing { 4 } else { 0 }; + let row = counter.row(node, hb).to_vec(); + let forward = row.get(1).copied().unwrap_or(0.0); + Some(RiverPlan { + facing, + mix: [row.first().copied().unwrap_or(1.0 - forward), forward], + bet_to: if facing { 0.0 } else { bet }, + reason: format!( + "river DBR: bucket {hb}/{}{}, w call {w_call:.2} bet {w_bet:.2}, p(fwd) {forward:.2}", + ladder.len(), + if facing { " facing bet" } else { "" } + ), + }) +} + +/// CFR+ iterations of the restricted river solve (same tiny tree as `ITERS`). +const DBR_ITERS: u32 = 4_000; + +/// The live DBR decision for a heads-up river spot (villain range from the engine's range model), or +/// `None` when it does not apply - the caller keeps the heuristic. +pub fn dbr_decision(spot: &Spot) -> Option { + if !dbr_on() || spot.street != Street::River || spot.live_villains().count() != 1 { + return None; + } + let villain = spot.live_villains().next()?; + let rules = spot.rules(); + let filter = crate::engine::range_filter::range_filter( + &crate::exploit::range_model::range_spec(spot, villain), + rules, + spot.variant, + &spot.board, + ); + let dead: Vec = spot.hero_cards.iter().chain(&spot.board).copied().collect(); + let list = crate::engine::range_combos::combos(&rules, &filter, &dead)?; + let plan = river_dbr_plan(spot, &list, villain.profile.as_ref())?; + Some(realize(spot, &plan)) +} + /// Below this believed call frequency the defensive veto folds: when the KL-bounded best response to /// the believed villain calls hero's bucket less than half the time, the believed bet is value-heavy /// enough that the heuristic's call is −EV. A full 0.5 keeps the veto to clear under-bluff reads. @@ -723,4 +855,38 @@ mod tests { let villain = sample_villain(); assert!(river_exploit_plan(&spot, &villain, spot.live_villains().next().unwrap().profile.as_ref()).is_none()); } + // --- data-biased robust counter-strategy (cfr::dbr) --- + + fn station_range() -> Vec> { + ["Ad Jc", "Kc Qc", "Kh Jh", "9d 8d", "9s Ts", "7d 6d", "7h 5h", "Qs Js", "Td Jd", "5c 4c", "6s 5s", "3c 3d", "4h 4d", "8h 8s"] + .iter() + .map(|c| Card::parse_list(c).unwrap()) + .collect() + } + + /// A confident station read: hero's middle pair, which the equilibrium mostly checks, turns into a + /// thin value bet - the free support the KL tilt could not reach. + #[test] + fn dbr_value_bets_a_middle_pair_into_a_confident_station() { + let board = Card::parse_list("Ah Kd 7c 2s 9h").unwrap(); + let mut spot = river_to_act(&board, "9c Tc", 6.0); + let station = prof(0.05, 0.05, 0.9); + spot.villains[0].profile = Some(station.clone()); + let range = station_range(); + let nash = river_plan(&spot, &range).expect("in slice"); + let dbr = river_dbr_plan(&spot, &range, Some(&station)).expect("confident read is in slice"); + eprintln!("nash p(bet) {:.2}, dbr {}", nash.forward(), dbr.reason); + assert!(dbr.forward() > 0.8, "{}", dbr.reason); + assert!(dbr.forward() > nash.forward() + 0.2, "nash {:.2} {}", nash.forward(), dbr.reason); + } + + /// Below the confidence floor on both nodes DBR stays out (the heuristic keeps the spot). + #[test] + fn dbr_stays_out_on_a_thin_read() { + let board = Card::parse_list("Ah Kd 7c 2s 9h").unwrap(); + let spot = river_to_act(&board, "9c Tc", 6.0); + let thin = prof(0.05, 0.05, 0.1); + assert!(river_dbr_plan(&spot, &station_range(), Some(&thin)).is_none()); + assert!(river_dbr_plan(&spot, &station_range(), None).is_none()); + } } diff --git a/src/exploit/sample.rs b/src/exploit/sample.rs index 5f782467..53d965de 100644 --- a/src/exploit/sample.rs +++ b/src/exploit/sample.rs @@ -105,6 +105,8 @@ pub fn shrink_aggression(profile: Profile, raw: Option, actions: f64) -> Pr /// 3-bet and check-raise. Shared by the sim memory and the wire. pub const FOLD_TO_THREE_BET_ANCHOR: f64 = 0.55; pub const CHECK_RAISE_ANCHOR: f64 = 0.08; +/// Prior strength of the check-raise read in pseudo-chances (Beta(mu*kappa, (1-mu)*kappa)). +pub const CHECK_RAISE_KAPPA: f64 = 15.0; /// Street samples at which one street's own read and the pooled read weigh the same — the session /// memory's `sim::memory::STREET_FOLD_PRIOR`, so a live street read earns trust as a simulated one. diff --git a/src/sim/memory.rs b/src/sim/memory.rs index 7bf056b9..0fccdd9b 100644 --- a/src/sim/memory.rs +++ b/src/sim/memory.rs @@ -98,7 +98,9 @@ fn line_read_on(bit: u8) -> bool { /// Population anchors the line reads shrink toward over `STREET_FOLD_PRIOR` samples (a regular's /// HUD): fold to 3-bet and check-raise have no pooled read to anchor on. -use crate::exploit::sample::{CHECK_RAISE_ANCHOR as CHECK_RAISE_PRIOR, FOLD_TO_THREE_BET_ANCHOR as FOLD_TO_THREE_BET_PRIOR}; +use crate::exploit::sample::{ + CHECK_RAISE_ANCHOR as CHECK_RAISE_PRIOR, CHECK_RAISE_KAPPA, FOLD_TO_THREE_BET_ANCHOR as FOLD_TO_THREE_BET_PRIOR, +}; static RIVER_SHOWDOWN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); @@ -133,6 +135,23 @@ impl SessionMemory { } /// Fold one finished hand's world observations (see `WorldHand`) into the world memory. + /// The raw (chances, hits) per read, for the empirical-Bayes fit of the population priors + /// (`lesen/eichung.py`), named like `lesen/zaehler.py`. + pub fn line_counts(&self) -> Vec<(&'static str, u32, u32)> { + let c = &self.c; + vec![ + ("vpip", c.hands, c.vpip), + ("pfr", c.hands, c.pfr), + ("aggression", c.aggressive + c.passive_call + c.passive_check, c.aggressive), + ("flopFoldToBet", c.street_fold[0] + c.street_call[0], c.street_fold[0]), + ("turnFoldToBet", c.street_fold[1] + c.street_call[1], c.street_fold[1]), + ("riverFoldToBet", c.street_fold[2] + c.street_call[2], c.street_fold[2]), + ("foldToCbet", c.cbet_faced, c.cbet_folded), + ("foldToThreeBet", c.three_bet_faced, c.three_bet_folded), + ("checkRaise", c.xr_chances, c.xr_made), + ] + } + pub fn observe_world_hand(&mut self, hand: &WorldHand) { self.world.observe_world_hand(hand); } @@ -278,8 +297,9 @@ impl SessionMemory { let fold_to_cbet = shrunk(self.c.cbet_folded, self.c.cbet_faced, flop_anchor).filter(|_| line_read_on(READ_CBET)); let fold_to_three_bet = shrunk(self.c.three_bet_folded, self.c.three_bet_faced, Some(FOLD_TO_THREE_BET_PRIOR)) .filter(|_| line_read_on(READ_THREE_BET)); - let check_raise = - shrunk(self.c.xr_made, self.c.xr_chances, Some(CHECK_RAISE_PRIOR)).filter(|_| line_read_on(READ_CHECK_RAISE)); + let check_raise = (self.c.xr_chances > 0) + .then(|| (self.c.xr_made as f64 + CHECK_RAISE_KAPPA * CHECK_RAISE_PRIOR) / (self.c.xr_chances as f64 + CHECK_RAISE_KAPPA)) + .filter(|_| line_read_on(READ_CHECK_RAISE)); Some(Profile { street_fold_to_bet, fold_to_cbet, diff --git a/src/sim/session.rs b/src/sim/session.rs index 67766613..c1421f12 100644 --- a/src/sim/session.rs +++ b/src/sim/session.rs @@ -89,20 +89,26 @@ pub fn measure_at(setup: &Setup, cost: TableCost) -> Measurement { /// Hero's luck-corrected result per deal in bb at the free table, for paired comparisons, with /// the measurement. pub fn deal_samples(setup: &Setup) -> (Vec, Measurement) { - let (corrected, _, m) = deal_samples_at(setup, TableCost::FREE); + let (corrected, _, m, _) = deal_samples_at(setup, TableCost::FREE); (corrected, m) } +/// `deal_samples` plus the session memory at the end (its counts feed the population-prior fit). +pub fn deal_samples_memory(setup: &Setup) -> (Vec, Measurement, SessionMemory) { + let (corrected, _, m, memory) = deal_samples_at(setup, TableCost::FREE); + (corrected, m, memory) +} + /// Per-deal (net result `y`, luck control signal `c`) at the free table. `c` has expectation ~0, /// so `y - beta*c` is unbiased for any beta; `y - c` (beta=1) is the sample the ladder stores. /// For analysing the estimator itself (control-variate / AIVAT): see `src/bin/aivat_bench.rs`. pub fn deal_net_and_luck(setup: &Setup) -> (Vec, Vec) { - let (corrected, raw, _) = deal_samples_at(setup, TableCost::FREE); + let (corrected, raw, _, _) = deal_samples_at(setup, TableCost::FREE); let luck = raw.iter().zip(&corrected).map(|(r, c)| r - c).collect(); (raw, luck) } -fn deal_samples_at(setup: &Setup, cost: TableCost) -> (Vec, Vec, Measurement) { +fn deal_samples_at(setup: &Setup, cost: TableCost) -> (Vec, Vec, Measurement, SessionMemory) { let players = setup.players; let mut samples = Vec::with_capacity(setup.deals as usize); let mut raw_samples = Vec::with_capacity(setup.deals as usize); @@ -155,7 +161,7 @@ fn deal_samples_at(setup: &Setup, cost: TableCost) -> (Vec, Vec, Measu m.rake_bb_per_100 = 100.0 * rake / m.hands.max(1) as f64; (m.bb_per_100, m.ci95) = rate(&samples); (m.raw_bb_per_100, m.raw_ci95) = rate(&raw_samples); - (samples, raw_samples, m) + (samples, raw_samples, m, memory) } /// Mean and 95 % half width of per-deal results, both in bb/100. diff --git a/tests/line_reads.rs b/tests/line_reads.rs index 9aae230b..4dccbf9f 100644 --- a/tests/line_reads.rs +++ b/tests/line_reads.rs @@ -105,3 +105,25 @@ fn the_cbet_is_priced_by_fold_to_cbet() { let sticky = table_fold(&flop_checked_to_hero(Profile { fold_to_cbet: Some(0.2), ..base }), 3.0, 1.0); assert!(folder > pooled + 0.2 && sticky < pooled - 0.1, "{sticky} {pooled} {folder}"); } + +#[test] +fn the_check_raise_sits_in_the_tree() { + use rechner::engine::bluff::{branches, branches_vs_raise, raise_response, RaiseKind}; + let quiet = flop_checked_to_hero(Profile::default()); + // No raise: exactly the two-branch EV. + assert_eq!(branches_vs_raise(&quiet, 3.0, 0.4, 0.3, RaiseKind::Bluff, 0.0, None), branches(&quiet, 3.0, 0.4, 0.3)); + // A raise rate scales the fold branch down (the fold read is fold | fold-or-call) and a bluff loses + // its bet to every raise. + let raised = branches_vs_raise(&quiet, 3.0, 0.4, 0.3, RaiseKind::Bluff, 0.2, None); + let plain = branches(&quiet, 3.0, 0.4, 0.3); + assert!((raised.fold - 0.8 * plain.fold).abs() < 1e-12); + assert!(raised.total < plain.total); + assert_eq!(raise_response(&quiet, 3.0, RaiseKind::Bluff, None), -3.0); + // Thin value calls a bluffy raiser and loses less than the bet; a passive raiser is value: fold. + let maniac = Profile { aggression: Some(0.9), ..Profile::default() }; + let passive = Profile { aggression: Some(0.05), ..Profile::default() }; + let mut river = flop_checked_to_hero(Profile::default()); + river.street = Street::River; + assert!(raise_response(&river, 3.0, RaiseKind::ThinValue, Some(&maniac)) > -3.0); + assert_eq!(raise_response(&river, 3.0, RaiseKind::ThinValue, Some(&passive)), -3.0); +}