Compare commits

...
Author SHA1 Message Date
mmintelandClaude Opus 5.5 6824778df1 Sicherung 01.12.: ungesicherte Dateien aus Worktree D:\Projects\pokerfreak\.claude\worktrees\agent-a081651b46db73399 (Zweig worktree-agent-a081651b46db73399, HEAD 2bd75b80)
1 Dateien. Nicht enthalten: 0 Dateien (Bau, Binaer, > 25 MB, archiv/lauf, Spuren echter Haende), 0 Loeschungen nicht nachgezogen. Der Worktree selbst ist unveraendert.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 13:36:21 +01:00
mmintelandClaude Opus 5.5 2bd75b802a WIP (pausiert, nicht fertig gemessen): draw-aware Turn-Buckets + turn_veto_ab A/B-Zelle
Gestoppt auf Owner-Wunsch (Rechner frei). Messung unvollstaendig: messung_r1/ enthaelt die bis
dahin fertigen Arme (off.* fuer n1 n2 n3 fish reg nit, aware/blind nur fuer nit und aware_ps n3).
Turn-Veto NICHT verdrahtet bis bewiesen.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 15:55:34 +01:00
20 changed files with 44489 additions and 24 deletions
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+70
View File
@@ -0,0 +1,70 @@
aware_ps n1 5EED0001
aware_pool n1 5EED0001
blind_ps n1 5EED0001
blind_pool n1 5EED0001
off n1 5EED0001
aware_ps n2 5EED0001
aware_pool n2 5EED0001
blind_ps n2 5EED0001
blind_pool n2 5EED0001
off n2 5EED0001
aware_ps n3 5EED0001
aware_pool n3 5EED0001
blind_ps n3 5EED0001
blind_pool n3 5EED0001
off n3 5EED0001
aware_ps fish 5EED0001
aware_pool fish 5EED0001
blind_ps fish 5EED0001
blind_pool fish 5EED0001
off fish 5EED0001
aware_ps reg 5EED0001
aware_pool reg 5EED0001
blind_ps reg 5EED0001
blind_pool reg 5EED0001
off reg 5EED0001
aware_ps nit 5EED0001
aware_pool nit 5EED0001
blind_ps nit 5EED0001
blind_pool nit 5EED0001
off nit 5EED0001
aware_ps maniac 5EED0001
aware_pool maniac 5EED0001
blind_ps maniac 5EED0001
blind_pool maniac 5EED0001
off maniac 5EED0001
aware_ps n1 5EED0002
aware_pool n1 5EED0002
blind_ps n1 5EED0002
blind_pool n1 5EED0002
off n1 5EED0002
aware_ps n2 5EED0002
aware_pool n2 5EED0002
blind_ps n2 5EED0002
blind_pool n2 5EED0002
off n2 5EED0002
aware_ps n3 5EED0002
aware_pool n3 5EED0002
blind_ps n3 5EED0002
blind_pool n3 5EED0002
off n3 5EED0002
aware_ps fish 5EED0002
aware_pool fish 5EED0002
blind_ps fish 5EED0002
blind_pool fish 5EED0002
off fish 5EED0002
aware_ps reg 5EED0002
aware_pool reg 5EED0002
blind_ps reg 5EED0002
blind_pool reg 5EED0002
off reg 5EED0002
aware_ps nit 5EED0002
aware_pool nit 5EED0002
blind_ps nit 5EED0002
blind_pool nit 5EED0002
off nit 5EED0002
aware_ps maniac 5EED0002
aware_pool maniac 5EED0002
blind_ps maniac 5EED0002
blind_pool maniac 5EED0002
off maniac 5EED0002
+15
View File
@@ -0,0 +1,15 @@
$D='C:\Users\marcm\AppData\Local\Temp\claude\9b7468b403d0d865\d4b34939-c1b6-47b3-ad5b-fb446c3b5fdb\scratchpad\r1'
$exe="$D\ab1.exe"
$todo=Get-Content "$D\todo.txt"
foreach($j in $todo){
while((Get-Process ab1 -ErrorAction SilentlyContinue | Measure-Object).Count -ge 2){ Start-Sleep -Seconds 15 }
$p=$j.Split(' '); $arm=$p[0];$opp=$p[1];$seed=$p[2]
Remove-Item Env:TURN_VETO,Env:TURN_BUCKET,Env:TURN_PER_STREET -ErrorAction SilentlyContinue
switch($arm){ 'off'{$env:TURN_VETO='0'} 'blind_ps'{$env:TURN_BUCKET='strength'} 'blind_pool'{$env:TURN_BUCKET='strength';$env:TURN_PER_STREET='0'} 'aware_pool'{$env:TURN_PER_STREET='0'} }
$env:OUT="$D\$arm.$opp.$seed.txt"
$pr=Start-Process -FilePath $exe -ArgumentList "$opp 4000 $seed" -RedirectStandardOutput "$D\$arm.$opp.$seed.log" -NoNewWindow -PassThru
try{$pr.PriorityClass='Idle'}catch{}
Start-Sleep -Seconds 3
}
while((Get-Process ab1 -ErrorAction SilentlyContinue | Measure-Object).Count -ge 1){ Start-Sleep -Seconds 15 }
'done' | Set-Content "$D\DONE2"
+7
View File
@@ -0,0 +1,7 @@
$D='C:\Users\marcm\AppData\Local\Temp\claude\9b7468b403d0d865\d4b34939-c1b6-47b3-ad5b-fb446c3b5fdb\scratchpad\r1'
$list=@()
foreach($seed in '5EED0001','5EED0002'){
foreach($arm in 'aware_ps','blind_ps','off'){ foreach($o in 'n3','n1','n2','reg','maniac','fish','nit'){ $list+="$arm $o $seed" } } }
foreach($seed in '5EED0001','5EED0002'){ foreach($arm in 'aware_pool','blind_pool'){ foreach($o in 'n3','n1','n2','reg','maniac','fish','nit'){ $list+="$arm $o $seed" } } }
$list=$list | ? { $p=$_ -split ' '; -not (Test-Path "$D\$($p[0]).$($p[1]).$($p[2]).txt") }
$list | Set-Content "$D\todo.txt"
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+20
View File
@@ -0,0 +1,20 @@
#!/bin/bash
# usage: run.sh dir exe deals
D=$1; EXE=$2; N=$3
jobs=()
for seed in 5EED0001 5EED0002; do for opp in n1 n2 n3 fish reg nit maniac; do
for arm in aware_ps aware_pool blind_ps blind_pool off; do
echo "$arm $opp $seed"
done; done; done > $D/jobs.txt
run1() { arm=$1; opp=$2; seed=$3; D=$4; EXE=$5; N=$6
case $arm in
off) export TURN_VETO=0;;
blind_ps) export TURN_BUCKET=strength;;
blind_pool) export TURN_BUCKET=strength TURN_PER_STREET=0;;
aware_pool) export TURN_PER_STREET=0;;
esac
OUT=$D/$arm.$opp.$seed.txt $EXE $opp $N $seed > $D/$arm.$opp.$seed.log 2>&1
}
export -f run1
cat $D/jobs.txt | xargs -P 30 -L1 bash -c 'run1 $0 $1 $2 '"$D $EXE $N"
echo done > $D/DONE
+60
View File
@@ -0,0 +1,60 @@
aware_ps n3 5EED0001
aware_ps n1 5EED0001
aware_ps n2 5EED0001
aware_ps reg 5EED0001
aware_ps maniac 5EED0001
aware_ps fish 5EED0001
blind_ps n3 5EED0001
blind_ps n1 5EED0001
blind_ps n2 5EED0001
blind_ps reg 5EED0001
blind_ps maniac 5EED0001
blind_ps fish 5EED0001
off maniac 5EED0001
aware_ps n3 5EED0002
aware_ps n1 5EED0002
aware_ps n2 5EED0002
aware_ps reg 5EED0002
aware_ps maniac 5EED0002
aware_ps fish 5EED0002
aware_ps nit 5EED0002
blind_ps n3 5EED0002
blind_ps n1 5EED0002
blind_ps n2 5EED0002
blind_ps reg 5EED0002
blind_ps maniac 5EED0002
blind_ps fish 5EED0002
blind_ps nit 5EED0002
off n3 5EED0002
off n1 5EED0002
off n2 5EED0002
off reg 5EED0002
off maniac 5EED0002
off fish 5EED0002
off nit 5EED0002
aware_pool n3 5EED0001
aware_pool n1 5EED0001
aware_pool n2 5EED0001
aware_pool reg 5EED0001
aware_pool maniac 5EED0001
aware_pool fish 5EED0001
blind_pool n3 5EED0001
blind_pool n1 5EED0001
blind_pool n2 5EED0001
blind_pool reg 5EED0001
blind_pool maniac 5EED0001
blind_pool fish 5EED0001
aware_pool n3 5EED0002
aware_pool n1 5EED0002
aware_pool n2 5EED0002
aware_pool reg 5EED0002
aware_pool maniac 5EED0002
aware_pool fish 5EED0002
aware_pool nit 5EED0002
blind_pool n3 5EED0002
blind_pool n1 5EED0002
blind_pool n2 5EED0002
blind_pool reg 5EED0002
blind_pool maniac 5EED0002
blind_pool fish 5EED0002
blind_pool nit 5EED0002
+112
View File
@@ -0,0 +1,112 @@
//! One ARM of a paired A/B over the whole measurement gate: the world population (`sim::welt`, every
//! archetype + the gto control, `draws` individuals each) AND the classic profiles (station, fish,
//! reg, nit, maniac, nemesis-1..3, `draws` seeds each). Memory read. Each cell's
//! per-deal luck-corrected samples (bb) go to `<out>/<row>.<k>.txt`. Two arms (two processes, same
//! rows, same deals) are compared deal by deal with `python messung_engine/ab.py <dirA> <dirB>`.
//!
//! The arm is chosen by environment so independent processes stay paired:
//! - `TURN_VETO`, `TURN_BUCKET`, `TURN_PER_STREET`: read by the turn track itself,
//! - every other track adds its switch in `apply_arm` below (identity on the engine branch).
//!
//! Run: `ab_zelle <out-dir> [welt-deals=2000] [klassik-deals=4000] [draws=4] [rows=all|welt|klassik|a,b,..]`
//! Threads: `POKERBENCH_THREADS` (default 16). Every cell is independent and deterministic, so the
//! thread count never changes a number. Run at priority Idle (see CLAUDE.md "Messlaeufe").
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::welt::{Persona, ARCHETYPES};
use std::sync::atomic::{AtomicUsize, Ordering};
/// World rows: same seeds as `welt_leiter`, so individuals and deals match the ladder.
const WELT_SEED: u64 = 0x5EED_0A11;
const DRAW_SEED: u64 = 0xD2A9_0000;
/// Classic rows: seed of `br_ladder` / `turn_veto_ab` for k = 0.
const KLASSIK_SEED: u64 = 0x5EED_0001;
const STACK_BB: f64 = 100.0;
const N1: Rules = Rules { call_margin: 0.215, raise_at: 0.587, bet_at: 0.548, open_at: 0.729, bluff: 0.068, size: 0.441 };
const N2: Rules = Rules { call_margin: 0.173, raise_at: 0.579, bet_at: 0.748, open_at: 0.800, bluff: 0.229, size: 0.996 };
const N3: Rules = Rules { call_margin: 0.396, raise_at: 0.769, bet_at: 0.615, open_at: 0.468, bluff: 0.261, size: 1.148 };
const KLASSIK: [&str; 8] = ["station", "fish", "reg", "nit", "maniac", "nemesis-1", "nemesis-2", "nemesis-3"];
/// Track switches read from the environment. Identity on the engine branch.
fn apply_arm() {}
fn klassik(name: &str) -> Option<Opponent> {
Some(match name {
"station" => Opponent::CallingStation,
"fish" => Opponent::Reader(Style::Fish),
"reg" => Opponent::Reader(Style::Reg),
"nit" => Opponent::Reader(Style::Nit),
"maniac" => Opponent::Reader(Style::Maniac),
"nemesis-1" => Opponent::Styled(N1),
"nemesis-2" => Opponent::Styled(N2),
"nemesis-3" => Opponent::Styled(N3),
_ => return None,
})
}
/// (opponent, deals, seed) of row `name`, individual/seed `k`.
fn cell(name: &str, k: u64, welt_deals: u32, klassik_deals: u32) -> (Opponent, u32, u64) {
if let Some(i) = ARCHETYPES.iter().position(|a| *a == name) {
let opp = Opponent::Welt(Persona::draw(i, Rng::seeded(DRAW_SEED + 1000 * i as u64 + k)).0);
return (opp, welt_deals, WELT_SEED ^ (k + 1).wrapping_mul(0x9E37_79B9));
}
if name == "gto" {
return (Opponent::Reader(Style::Gto), welt_deals, WELT_SEED ^ (k + 1).wrapping_mul(0x9E37_79B9));
}
let opp = klassik(name).unwrap_or_else(|| panic!("unbekannte Zeile {name}"));
(opp, klassik_deals, KLASSIK_SEED ^ k.wrapping_mul(0x9E37_79B9_7F4A_7C15))
}
fn main() {
let a: Vec<String> = std::env::args().collect();
let out = a.get(1).expect("ab_zelle <out-dir> [welt-deals] [klassik-deals] [draws] [rows]").clone();
let num = |i: usize, d: u32| a.get(i).and_then(|s| s.parse().ok()).unwrap_or(d);
let (welt_deals, klassik_deals, draws) = (num(2, 2000), num(3, 4000), num(4, 4) as u64);
let welt: Vec<String> = ARCHETYPES.iter().map(|s| s.to_string()).chain(["gto".to_string()]).collect();
let klass: Vec<String> = KLASSIK.iter().map(|s| s.to_string()).collect();
let rows: Vec<String> = match a.get(5).map(String::as_str) {
None | Some("all") => welt.into_iter().chain(klass).collect(),
Some("welt") => welt,
Some("klassik") => klass,
Some(list) => list.split(',').map(str::to_string).collect(),
};
let threads: usize = std::env::var("POKERBENCH_THREADS").ok().and_then(|s| s.parse().ok()).unwrap_or(16).max(1);
std::fs::create_dir_all(&out).expect("out dir");
// Cells still to play, the long ones (more deals) first so the threads finish together.
let mut jobs: Vec<(String, u64, u32)> = rows
.iter()
.flat_map(|name| (0..draws).map(move |k| (name.clone(), k)))
.filter(|(name, k)| !std::path::Path::new(&format!("{out}/{name}.{k}.txt")).exists())
.map(|(name, k)| {
let deals = cell(&name, k, welt_deals, klassik_deals).1;
(name, k, deals)
})
.collect();
jobs.sort_by(|a, b| b.2.cmp(&a.2));
let next = AtomicUsize::new(0);
std::thread::scope(|s| {
for _ in 0..threads.min(jobs.len().max(1)) {
s.spawn(|| {
apply_arm(); // per thread: some switches are thread-local
loop {
let j = next.fetch_add(1, Ordering::Relaxed);
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 body: Vec<String> = 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");
println!("{name:<12} k={k} {:>+8.2} bb/100 +-{:>6.2}", m.bb_per_100, m.ci95);
}
});
}
});
}
+44
View File
@@ -0,0 +1,44 @@
//! One opponent, Memory read only: the measurement cell of the turn-veto A/B. The configuration is
//! switched by environment (`TURN_VETO=0` off, `TURN_BUCKET=strength` legacy draw-blind buckets,
//! `TURN_PER_STREET=0` pooled belief aggression), so independent processes over the same seed and
//! deals are paired and can run in parallel.
//!
//! Run: `cargo run --release --bin turn_veto_ab <opp> [deals]` with opp in
//! n1 n2 n3 fish reg nit maniac.
use rechner::sim::opponent::Opponent;
use rechner::sim::reader::{Rules, Style};
use rechner::sim::session::{deal_samples, ReadMode, Setup};
const SEED: u64 = 0x5EED_0001;
const N1: Rules = Rules { call_margin: 0.215, raise_at: 0.587, bet_at: 0.548, open_at: 0.729, bluff: 0.068, size: 0.441 };
const N2: Rules = Rules { call_margin: 0.173, raise_at: 0.579, bet_at: 0.748, open_at: 0.800, bluff: 0.229, size: 0.996 };
const N3: Rules = Rules { call_margin: 0.396, raise_at: 0.769, bet_at: 0.615, open_at: 0.468, bluff: 0.261, size: 1.148 };
fn main() {
let mut args = std::env::args().skip(1);
let which = args.next().unwrap_or_else(|| "n1".into());
let deals: u32 = args.next().and_then(|s| s.parse().ok()).unwrap_or(2000);
let opponent = match which.as_str() {
"n1" => Opponent::Styled(N1),
"n2" => Opponent::Styled(N2),
"n3" => Opponent::Styled(N3),
"fish" => Opponent::Reader(Style::Fish),
"reg" => Opponent::Reader(Style::Reg),
"nit" => Opponent::Reader(Style::Nit),
"maniac" => Opponent::Reader(Style::Maniac),
other => panic!("unknown opponent {other}"),
};
// Optional third argument: the seed (default `SEED`); `OUT=<file>` dumps the per-deal
// luck-corrected samples (bb) for paired analysis across arms.
let seed: u64 = args.next().and_then(|s| u64::from_str_radix(s.trim_start_matches("0x"), 16).ok()).unwrap_or(SEED);
let setup = Setup { players: 2, opponent, deals, stack_bb: 100.0, seed, read: ReadMode::Memory };
let (samples, m) = deal_samples(&setup);
if let Ok(path) = std::env::var("OUT") {
let body: Vec<String> = samples.iter().map(|x| format!("{x}")).collect();
std::fs::write(path, body.join("
")).expect("write OUT");
}
println!("{which} Memory {:>+8.2} bb/100 ±{:>6.2} (raw {:>+8.2} ±{:>6.2}) deals {deals}", m.bb_per_100, m.ci95, m.raw_bb_per_100, m.raw_ci95);
}
+2 -1
View File
@@ -92,7 +92,8 @@ 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 {
return super::river_subgame::fold_veto(raw, floored);
let after_river = super::river_subgame::fold_veto(raw, floored);
return super::turn_subgame::turn_fold_veto(raw, after_river);
}
floored
}
+159 -23
View File
@@ -128,15 +128,89 @@ fn disjoint(a: &[Card], b: &[Card]) -> bool {
struct TurnGame {
tree: Tree,
solved: crate::cfr::solve::Solved,
/// Bucket count.
n: usize,
/// Current-strength ladder (legacy, draw-blind bucketing) - used when `cuts` is `None`.
ladder: Vec<Strength>,
/// Equity cut points (draw-aware bucketing): a hand whose river-averaged equity is `e` sits in
/// bucket `cuts.partition_point(|c| *c <= e)`.
cuts: Option<Vec<f64>>,
}
impl TurnGame {
fn bucket(&self, s: Strength) -> usize {
self.ladder.partition_point(|d| *d < s).min(self.ladder.len() - 1)
/// The bucket of hero's real hand: by river-averaged equity (draw-aware) or, in legacy mode, by
/// the current-strength rank.
fn hero_bucket(&self, spot: &Spot, villain: &[Vec<Card>]) -> Option<usize> {
let rules = spot.rules();
match &self.cuts {
Some(cuts) => {
let e = equities(spot, &[spot.hero_cards.clone()], villain)[0]?;
Some(cuts.partition_point(|c| *c <= e))
}
None => {
let st = judge(&rules, &spot.hero_cards, &spot.board).ok()?;
Some(self.ladder.partition_point(|d| *d < st).min(self.ladder.len() - 1))
}
}
}
}
/// Number of equity buckets for the draw-aware turn abstraction.
const EQUITY_BUCKETS: usize = 10;
/// Measurement switch (read once): `TURN_BUCKET=strength` restores the legacy draw-blind bucketing so
/// one binary measures old vs new on the same deals. Default: draw-aware equity buckets.
fn equity_bucketing() -> bool {
use std::sync::OnceLock;
static ON: OnceLock<bool> = OnceLock::new();
*ON.get_or_init(|| std::env::var("TURN_BUCKET").as_deref() != Ok("strength"))
}
/// Measurement switch (read once): `TURN_PER_STREET=0` makes the turn belief read the POOLED
/// postflop aggression instead of the per-street turn aggression.
fn per_street_belief() -> bool {
use std::sync::OnceLock;
static ON: OnceLock<bool> = OnceLock::new();
*ON.get_or_init(|| std::env::var("TURN_PER_STREET").as_deref() != Ok("0"))
}
/// River-averaged showdown equity of each subject hand against the `opp` range on this 4-card turn
/// board: for every river card, win=1 / tie=0.5 over the card-disjoint opponent combos, averaged over
/// runouts and opponents. This is what the draw-blind current-strength ladder lacks: a flush or
/// straight draw has weak turn strength but real realisable equity, and sits where the equity says.
/// `None` for a subject that cannot be judged.
fn equities(spot: &Spot, subjects: &[Vec<Card>], opp: &[Vec<Card>]) -> Vec<Option<f64>> {
let rules = spot.rules();
let mut score = vec![0.0f64; subjects.len()];
let mut count = vec![0.0f64; subjects.len()];
for r in &deck::without_in(rules.deck, &spot.board) {
let mut board5 = spot.board.clone();
board5.push(*r);
let ov: Vec<(&Vec<Card>, Strength)> = opp
.iter()
.filter(|c| !c.contains(r))
.filter_map(|c| judge(&rules, c, &board5).ok().map(|st| (c, st)))
.collect();
for (k, sc) in subjects.iter().enumerate() {
if sc.contains(r) {
continue;
}
let Ok(sst) = judge(&rules, sc, &board5) else { continue };
for (oc, ost) in &ov {
if disjoint(sc, oc) {
score[k] += match sst.cmp(ost) {
std::cmp::Ordering::Greater => 1.0,
std::cmp::Ordering::Equal => 0.5,
std::cmp::Ordering::Less => 0.0,
};
count[k] += 1.0;
}
}
}
}
score.iter().zip(&count).map(|(s, c)| (*c > 0.0).then(|| s / c)).collect()
}
/// Build the two river leaf-value matrices (`V_check`, `V_bet`) over the turn buckets by solving the
/// river subgame for every runout at both river-start pots and folding the equilibrium values back
/// onto the turn buckets with exact card removal. `turn_n` is the turn-bucket count, `turn_bucket`
@@ -259,13 +333,43 @@ fn build_turn(spot: &Spot, hero_combos: &[Vec<Card>], villain_combos: &[Vec<Card
let mut ladder: Vec<Strength> = hero.iter().chain(&villain).map(|(_, st)| *st).collect();
ladder.sort();
ladder.dedup();
let n = ladder.len();
if n < 2 {
return None;
}
let tb = |st: Strength| ladder.partition_point(|d| *d < st).min(n - 1);
let hero_b: Vec<(Vec<Card>, usize)> = hero.iter().map(|(c, st)| (c.clone(), tb(*st))).collect();
let villain_b: Vec<(Vec<Card>, usize)> = villain.iter().map(|(c, st)| (c.clone(), tb(*st))).collect();
type Placed = Vec<(Vec<Card>, usize)>;
let (n, cuts, hero_b, villain_b): (usize, Option<Vec<f64>>, Placed, Placed) = if equity_bucketing() {
// Draw-aware: bucket by river-averaged equity vs the opposing range, equal-mass cuts over
// both ranges together (one shared ladder, as before).
let hc: Vec<Vec<Card>> = hero.iter().map(|(c, _)| c.clone()).collect();
let vc: Vec<Vec<Card>> = villain.iter().map(|(c, _)| c.clone()).collect();
let he = equities(spot, &hc, &vc);
let ve = if hc == vc { he.clone() } else { equities(spot, &vc, &hc) };
let mut all: Vec<f64> = he.iter().chain(&ve).filter_map(|e| *e).collect();
all.sort_by(|a, b| a.total_cmp(b));
if all.len() < 2 {
return None;
}
let mut cuts: Vec<f64> = (1..EQUITY_BUCKETS).map(|i| all[i * all.len() / EQUITY_BUCKETS]).collect();
cuts.dedup();
let n = cuts.len() + 1;
if n < 2 {
return None;
}
let place = |src: &[(Vec<Card>, Strength)], eq: &[Option<f64>]| -> Placed {
src.iter()
.zip(eq)
.filter_map(|((c, _), e)| e.map(|e| (c.clone(), cuts.partition_point(|x| *x <= e))))
.collect()
};
let (hb, vb) = (place(&hero, &he), place(&villain, &ve));
(n, Some(cuts), hb, vb)
} else {
let n = ladder.len();
if n < 2 {
return None;
}
let tb = |st: Strength| ladder.partition_point(|d| *d < st).min(n - 1);
let hb = hero.iter().map(|(c, st)| (c.clone(), tb(*st))).collect();
let vb = villain.iter().map(|(c, st)| (c.clone(), tb(*st))).collect();
(n, None, hb, vb)
};
// Turn joint deal table over turn buckets (card removal between the two ranges).
let mut chance = vec![0.0; n * n];
@@ -285,7 +389,7 @@ fn build_turn(spot: &Spot, hero_combos: &[Vec<Card>], villain_combos: &[Vec<Card
let (leaf_check, leaf_bet) = river_leaves(spot, &hero_b, &villain_b, n, p, s)?;
let tree = tree_with_leaf(n, chance, p, leaf_check, leaf_bet);
let solved = solve(&tree, TURN_SOLVE_ITERS, Rng::seeded(spot.seed));
Some(TurnGame { tree, solved, ladder })
Some(TurnGame { tree, solved, n, ladder, cuts })
}
/// Solve the heads-up turn subgame from the engine's belief and return hero's equilibrium mix at the
@@ -297,20 +401,17 @@ pub fn turn_plan(spot: &Spot, villain_combos: &[Vec<Card>]) -> Option<TurnPlan>
if spot.live_villains().count() != 1 || villain_combos.is_empty() {
return None;
}
let rules = spot.rules();
let hero_strength = judge(&rules, &spot.hero_cards, &spot.board).ok()?;
if spot.to_call == 0.0 {
let s = bet_to(spot)?;
let game = build_turn(spot, villain_combos, villain_combos, spot.pot, s)?;
let hb = game.bucket(hero_strength);
let hb = game.hero_bucket(spot, villain_combos)?;
let probs = game.solved.strategy.row(0, hb).to_vec(); // [check, bet]
let bet_p = probs.get(1).copied().unwrap_or(0.0);
Some(TurnPlan {
facing: false,
mix: [probs.first().copied().unwrap_or(1.0 - bet_p), bet_p],
bet_to: s,
reason: format!("turn subgame: bucket {hb}/{}, p(bet) {bet_p:.2}", game.ladder.len()),
reason: format!("turn subgame: bucket {hb}/{}, p(bet) {bet_p:.2}", game.n),
})
} else {
// Facing a turn bet: the pre-bet pot is `pot - to_call`, the bet is `to_call`.
@@ -320,14 +421,14 @@ pub fn turn_plan(spot: &Spot, villain_combos: &[Vec<Card>]) -> Option<TurnPlan>
return None;
}
let game = build_turn(spot, villain_combos, villain_combos, p, s)?;
let hb = game.bucket(hero_strength);
let hb = game.hero_bucket(spot, villain_combos)?;
let row = game.solved.strategy.row(4, hb).to_vec(); // [fold, call]
let call_p = row.get(1).copied().unwrap_or(0.0);
Some(TurnPlan {
facing: true,
mix: [row.first().copied().unwrap_or(1.0 - call_p), call_p],
bet_to: 0.0,
reason: format!("turn subgame: bucket {hb}/{} facing bet, p(call) {call_p:.2}", game.ladder.len()),
reason: format!("turn subgame: bucket {hb}/{} facing bet, p(call) {call_p:.2}", game.n),
})
}
}
@@ -372,9 +473,6 @@ pub fn turn_exploit_plan(spot: &Spot, villain_combos: &[Vec<Card>], profile: Opt
if profile.and_then(|p| p.confidence).filter(|c| !c.is_nan()).unwrap_or(0.0) < CONFIDENCE_FLOOR {
return None;
}
let rules = spot.rules();
let hero_strength = judge(&rules, &spot.hero_cards, &spot.board).ok()?;
let (p, s, facing) = if spot.to_call == 0.0 {
(spot.pot, bet_to(spot)?, false)
} else {
@@ -386,11 +484,12 @@ pub fn turn_exploit_plan(spot: &Spot, villain_combos: &[Vec<Card>], profile: Opt
};
let game = build_turn(spot, villain_combos, villain_combos, p, s)?;
let n = game.ladder.len();
let opponent = believed_villain(&game.tree, n, profile, p, s, profile.and_then(|pr| pr.turn_aggression.or(pr.aggression)));
let n = game.n;
let aggr = profile.and_then(|pr| if per_street_belief() { pr.turn_aggression.or(pr.aggression) } else { pr.aggression });
let opponent = believed_villain(&game.tree, n, profile, p, s, aggr);
let lambda = lambda_from_confidence(profile.and_then(|p| p.confidence), p);
let tilted = kl_best_response(&game.tree, &opponent, &game.solved.strategy, 0, lambda);
let hb = game.bucket(hero_strength);
let hb = game.hero_bucket(spot, villain_combos)?;
let node = if facing { 4 } else { 0 };
let row = tilted.row(node, hb).to_vec();
@@ -593,4 +692,41 @@ mod tests {
let check = Decision::new(Choice::Check, 0.7, "heuristic check");
assert_eq!(turn_fold_veto(&spot, check.clone()), check, "a non-call base is never vetoed");
}
// --- draw-aware bucketing ---
fn hands(list: &[&str]) -> Vec<Vec<Card>> {
list.iter().map(|c| Card::parse_list(c).unwrap()).collect()
}
/// River-averaged equity carries what the turn strength lacks: a nut flush draw (9 outs plus
/// overcards) is worth far more than its current Ace-high, and more than a made bottom pair that
/// currently beats it only if the opposing range is strong - here it must clear a pure-air hand and
/// sit in a sane draw band.
#[test]
fn equity_values_a_flush_draw_above_air() {
let board = Card::parse_list("Kh 7h 3c 2d").unwrap();
let spot = turn_to_act(&board, "Ah 9h", 6.0);
let range = hands(&["Ks Qd", "Qh Qd", "Jd Jc", "Kd Tc", "Ac Qs", "8c 8d"]);
let subj = hands(&["Ah 9h", "Qs Jc"]);
let e = equities(&spot, &subj, &range);
let (draw, air) = (e[0].unwrap(), e[1].unwrap());
assert!(draw > air + 0.10, "draw {draw:.2} must clear air {air:.2}");
assert!((0.25..0.60).contains(&draw), "draw equity in a sane band, got {draw:.2}");
}
/// The draw-aware bucket puts a strong draw ABOVE a weak made hand it out-equities, where the
/// draw-blind current-strength rank puts it below - the exact misplacement that pushed draws to
/// fold. Checked on the bucket the real hand gets (hero_bucket) against the dealt ranges.
#[test]
fn a_strong_draw_lands_in_a_higher_bucket_than_a_weak_made_hand() {
let board = Card::parse_list("Kh 7h 3c 2d").unwrap();
let villain = hands(&["Ks Qd", "Qh Qd", "Jd Jc", "Kd Tc", "Ac Qs", "8c 8d", "Ad Js", "9s 9d", "Qc Jh", "5c 4d"]);
let draw = turn_to_act(&board, "Ah Qh", 6.0); // nut flush draw + overcard: Ace-high now
let weak = turn_to_act(&board, "4s 3d", 6.0); // bottom pair now (beats Ace-high)
let game = build_turn(&draw, &villain, &villain, 6.0, 4.0).expect("builds");
assert!(game.cuts.is_some(), "default bucketing is draw-aware");
let (bd, bw) = (game.hero_bucket(&draw, &villain).unwrap(), game.hero_bucket(&weak, &villain).unwrap());
assert!(bd >= bw, "draw bucket {bd} must not sit below the weak pair's {bw}");
}
}