river_spieler::lock_villain nutzt RangeRead::believed_row (eine Quelle mit der Leseschicht), Gewicht je Knoten trust(gegen Bets / Fold)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-14 21:30:17 +01:00
co-authored by Claude Opus 5.5
parent ca30bc6213
commit 3b5cee5442
2 changed files with 394 additions and 411 deletions
-6
View File
@@ -1,6 +0,0 @@
575 eindeutige Anfragen, Schalter ['SOLVER_RIVER=1', 'SOLVER_TURN=1', 'GRUNDSTRATEGIE=D:\\Projects\\pokerfreak\\.claude\\worktrees\\engine-lecks-angreifen-de7b88\\daten', 'MDF_UNREAD=0', 'TURN_SPIEL=grund']
TURN 1-Gegner: 478 Solver 427 ( 89.3 %) Zeit Solver p50 2045 p99 3781 max 4345 ms solver=427 e3=43 heuristik=8
TURN 2-Gegner: 88 Solver 0 ( 0.0 %) Zeit Solver p50 0 p99 0 max 0 ms heuristik=88
TURN 3-Gegner: 7 Solver 0 ( 0.0 %) Zeit Solver p50 0 p99 0 max 0 ms heuristik=7
TURN 4-Gegner: 2 Solver 0 ( 0.0 %) Zeit Solver p50 0 p99 0 max 0 ms heuristik=2
TURN alle Anfragen: p50 1191 p99 3753 max 4345 ms
+394 -405
View File
@@ -1,405 +1,394 @@
//! Stage A of "solver everywhere": the heads-up RIVER decided by an equilibrium solve over real combos, //! Stage A of "solver everywhere": the heads-up RIVER decided by an equilibrium solve over real combos,
//! as the primary decision maker (not a veto). Switch `SOLVER_RIVER` (default off). //! as the primary decision maker (not a veto). Switch `SOLVER_RIVER` (default off).
//! //!
//! - **Game:** `cfr::turn_river_game::build_river` - the river alone, with the observed river line //! - **Game:** `cfr::turn_river_game::build_river` - the river alone, with the observed river line
//! inside the tree (exact sizes), position, three bet sizes plus all-in, raises. Solved with the //! inside the tree (exact sizes), position, three bet sizes plus all-in, raises. Solved with the
//! vectorised CFR+ of `TrSolver` over real combos: card removal and showdowns are exact per combo //! vectorised CFR+ of `TrSolver` over real combos: card removal and showdowns are exact per combo
//! (no strength buckets, blockers count). //! (no strength buckets, blockers count).
//! - **Ranges** come from the hand's action history: where the blueprint recognises the spot (scenario //! - **Ranges** come from the hand's action history: where the blueprint recognises the spot (scenario
//! family of `blueprint::ranges`, loaded via `GRUNDSTRATEGIE`) both ranges are the blueprint's along //! family of `blueprint::ranges`, loaded via `GRUNDSTRATEGIE`) both ranges are the blueprint's along
//! the line played; everywhere else both come from the engine's range model //! the line played; everywhere else both come from the engine's range model
//! (`exploit::range_model::range_spec` -> `range_filter`): the villain's with its (gated) read, hero's //! (`exploit::range_model::range_spec` -> `range_filter`): the villain's with its (gated) read, hero's
//! own as the same model sees hero's line, without a read. `SOLVER_RIVER=modell` forces the range //! own as the same model sees hero's line, without a read. `SOLVER_RIVER=modell` forces the range
//! model also in blueprint spots (a measurement arm: it shows the model path on the LBR scenario). //! model also in blueprint spots (a measurement arm: it shows the model path on the LBR scenario).
//! - **One solve per public state.** The ranges do not depend on hero's cards (the game deals card //! - **One solve per public state.** The ranges do not depend on hero's cards (the game deals card
//! removal itself), so a solve serves every hero hand at the node; solves are cached by public state. //! removal itself), so a solve serves every hero hand at the node; solves are cached by public state.
//! Every hero hand outside the modelled range joins the solve at a token weight, so it gets a //! Every hero hand outside the modelled range joins the solve at a token weight, so it gets a
//! strategy without moving the equilibrium. //! strategy without moving the equilibrium.
//! - **Time budget:** CFR+ runs at most `ITERS` iterations and stops at `BUDGET_MS` wall time; under //! - **Time budget:** CFR+ runs at most `ITERS` iterations and stops at `BUDGET_MS` wall time; under
//! `MIN_ITERS` finished iterations the heuristic keeps the decision (`None`). //! `MIN_ITERS` finished iterations the heuristic keeps the decision (`None`).
//! //!
//! Not in the slice (the heuristic plays): multiway rivers, tournaments (the caller only asks for cash), //! Not in the slice (the heuristic plays): multiway rivers, tournaments (the caller only asks for cash),
//! Omaha and other variants (hole cards != 2), spots whose line leaves the tree. //! Omaha and other variants (hole cards != 2), spots whose line leaves the tree.
use crate::card::Card; use crate::card::Card;
use crate::cfr::river_game::Act; use crate::cfr::river_game::Act;
use crate::cfr::turn_river_game::{build_river, Hands, Menu, TNode, TrBets, TrSolver}; use crate::cfr::turn_river_game::{build_river, Hands, Menu, TNode, TrBets, TrSolver};
use crate::exploit::range_read::RangeRead; use crate::exploit::range_read::RangeRead;
use crate::engine::river_subgame::{legal_choice, river_line}; use crate::engine::river_subgame::{legal_choice, river_line};
use crate::game::{Decision, Spot, Street, Villain}; use crate::game::{Decision, Spot, Street, Villain};
use crate::hand::fast7; use crate::hand::fast7;
use crate::rng::Rng; use crate::rng::Rng;
use std::collections::HashMap; use std::collections::HashMap;
use std::hash::{Hash, Hasher}; use std::hash::{Hash, Hasher};
use std::sync::atomic::{AtomicU8, Ordering}; use std::sync::atomic::{AtomicU8, Ordering};
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
/// Who plays the heads-up river. /// Who plays the heads-up river.
#[derive(Clone, Copy, Debug, PartialEq, Eq)] #[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RiverSpieler { pub enum RiverSpieler {
/// The heuristic (default). /// The heuristic (default).
Aus, Aus,
/// The solver; blueprint ranges where the spot is a blueprint scenario, else the range model. /// The solver; blueprint ranges where the spot is a blueprint scenario, else the range model.
An, An,
/// The solver with range-model ranges everywhere (measurement arm). /// The solver with range-model ranges everywhere (measurement arm).
Modell, Modell,
} }
static MODE: AtomicU8 = AtomicU8::new(0); static MODE: AtomicU8 = AtomicU8::new(0);
pub fn set_river_spieler(mode: RiverSpieler) { pub fn set_river_spieler(mode: RiverSpieler) {
MODE.store( MODE.store(
match mode { match mode {
RiverSpieler::Aus => 0, RiverSpieler::Aus => 0,
RiverSpieler::An => 1, RiverSpieler::An => 1,
RiverSpieler::Modell => 2, RiverSpieler::Modell => 2,
}, },
Ordering::Relaxed, Ordering::Relaxed,
); );
} }
pub fn river_spieler() -> RiverSpieler { pub fn river_spieler() -> RiverSpieler {
match MODE.load(Ordering::Relaxed) { match MODE.load(Ordering::Relaxed) {
1 => RiverSpieler::An, 1 => RiverSpieler::An,
2 => RiverSpieler::Modell, 2 => RiverSpieler::Modell,
_ => RiverSpieler::Aus, _ => RiverSpieler::Aus,
} }
} }
/// `SOLVER_RIVER`: `1`/`an` -> `An`, `modell` -> `Modell`, else `Aus`. /// `SOLVER_RIVER`: `1`/`an` -> `An`, `modell` -> `Modell`, else `Aus`.
pub fn from_env() -> RiverSpieler { pub fn from_env() -> RiverSpieler {
match std::env::var("SOLVER_RIVER").as_deref() { match std::env::var("SOLVER_RIVER").as_deref() {
Ok("1") | Ok("an") => RiverSpieler::An, Ok("1") | Ok("an") => RiverSpieler::An,
Ok("modell") => RiverSpieler::Modell, Ok("modell") => RiverSpieler::Modell,
_ => RiverSpieler::Aus, _ => RiverSpieler::Aus,
} }
} }
/// CFR+ iterations at most. /// CFR+ iterations at most.
pub const ITERS: u32 = 600; pub const ITERS: u32 = 600;
/// Fewer finished iterations than this (time budget hit): the heuristic decides. /// Fewer finished iterations than this (time budget hit): the heuristic decides.
pub const MIN_ITERS: u32 = 100; pub const MIN_ITERS: u32 = 100;
/// Wall-time budget of one solve. /// Wall-time budget of one solve.
pub const BUDGET_MS: f64 = 1500.0; pub const BUDGET_MS: f64 = 1500.0;
/// The river bet menu: 33 %, 75 %, 125 % pot and all-in; raises to 3x or all-in, two raises. /// The river bet menu: 33 %, 75 %, 125 % pot and all-in; raises to 3x or all-in, two raises.
fn river_menu() -> Menu { fn river_menu() -> Menu {
Menu { fracs: vec![0.33, 0.75, 1.25], raise_mult: vec![3.0], max_raises: 2, allin: true } Menu { fracs: vec![0.33, 0.75, 1.25], raise_mult: vec![3.0], max_raises: 2, allin: true }
} }
/// One solved river node: what every hero hand at this public state shares. /// One solved river node: what every hero hand at this public state shares.
pub struct Solved { pub struct Solved {
rows: Vec<f64>, rows: Vec<f64>,
acts: Vec<Act>, acts: Vec<Act>,
hero_masks: Vec<u64>, hero_masks: Vec<u64>,
pub millis: f64, pub millis: f64,
pub iterations: u32, pub iterations: u32,
pub combos: [usize; 2], pub combos: [usize; 2],
pub nodes: usize, pub nodes: usize,
pub source: &'static str, pub source: &'static str,
} }
/// Masks and weights of a combo list off the `dead` cards. `fill`: every other two-card combo joins at a /// Masks and weights of a combo list off the `dead` cards. `fill`: every other two-card combo joins at a
/// token weight, so each possible hero hand has a strategy in the one solve (CFR's regrets of a hand do /// token weight, so each possible hero hand has a strategy in the one solve (CFR's regrets of a hand do
/// not depend on its own reach, so a token-weight hand plays its counterfactual best line without moving /// not depend on its own reach, so a token-weight hand plays its counterfactual best line without moving
/// the equilibrium). /// the equilibrium).
fn hands_of(list: &[(Vec<Card>, f64)], dead: u64, fill: bool) -> Hands { fn hands_of(list: &[(Vec<Card>, f64)], dead: u64, fill: bool) -> Hands {
let mut w: HashMap<u64, f64> = HashMap::new(); let mut w: HashMap<u64, f64> = HashMap::new();
for (c, x) in list { for (c, x) in list {
if c.len() == 2 && *x > 0.0 && x.is_finite() { if c.len() == 2 && *x > 0.0 && x.is_finite() {
let m = fast7::mask(c); let m = fast7::mask(c);
if m & dead == 0 && m.count_ones() == 2 { if m & dead == 0 && m.count_ones() == 2 {
let e = w.entry(m).or_insert(0.0); let e = w.entry(m).or_insert(0.0);
*e = e.max(*x); *e = e.max(*x);
} }
} }
} }
let top = w.values().copied().fold(0.0f64, f64::max).max(1e-12); let top = w.values().copied().fold(0.0f64, f64::max).max(1e-12);
if fill { if fill {
let bits: Vec<u64> = (0..4u32).flat_map(|s| (0..13u32).map(move |r| 1u64 << (16 * s + r))).filter(|b| b & dead == 0).collect(); let bits: Vec<u64> = (0..4u32).flat_map(|s| (0..13u32).map(move |r| 1u64 << (16 * s + r))).filter(|b| b & dead == 0).collect();
for i in 0..bits.len() { for i in 0..bits.len() {
for j in i + 1..bits.len() { for j in i + 1..bits.len() {
w.entry(bits[i] | bits[j]).or_insert(top * TOKEN); w.entry(bits[i] | bits[j]).or_insert(top * TOKEN);
} }
} }
} }
let mut v: Vec<(u64, f64)> = w.into_iter().collect(); let mut v: Vec<(u64, f64)> = w.into_iter().collect();
v.sort_by(|a, b| a.0.cmp(&b.0)); v.sort_by(|a, b| a.0.cmp(&b.0));
Hands { masks: v.iter().map(|x| x.0).collect(), weights: v.iter().map(|x| x.1).collect() } Hands { masks: v.iter().map(|x| x.0).collect(), weights: v.iter().map(|x| x.1).collect() }
} }
/// Relative weight of a hero hand outside the modelled range. /// Relative weight of a hero hand outside the modelled range.
const TOKEN: f64 = 1e-6; const TOKEN: f64 = 1e-6;
/// Solve the river of `spot`'s public state with these ranges; every hero hand gets a strategy. `None` off the heads-up river slice, off the tree, or when the budget left too few iterations. /// Solve the river of `spot`'s public state with these ranges; every hero hand gets a strategy. `None` off the heads-up river slice, off the tree, or when the budget left too few iterations.
pub fn solve_river(spot: &Spot, hero: &[(Vec<Card>, f64)], villain_list: &[(Vec<Card>, f64)], source: &'static str, read: Option<&RangeRead>) -> Option<Solved> { pub fn solve_river(spot: &Spot, hero: &[(Vec<Card>, f64)], villain_list: &[(Vec<Card>, f64)], source: &'static str, read: Option<&RangeRead>) -> Option<Solved> {
if spot.street != Street::River || spot.board.len() != 5 || spot.live_villains().count() != 1 { if spot.street != Street::River || spot.board.len() != 5 || spot.live_villains().count() != 1 {
return None; return None;
} }
let villain = spot.live_villains().next()?; let villain = spot.live_villains().next()?;
let (first, forced, c) = river_line(spot, villain); let (first, forced, c) = river_line(spot, villain);
let pot = spot.pot - c[0] - c[1]; let pot = spot.pot - c[0] - c[1];
let stack = (spot.hero_stack + c[0]).min(villain.stack + c[1]); let stack = (spot.hero_stack + c[0]).min(villain.stack + c[1]);
if pot <= 0.0 || stack <= 0.0 { if pot <= 0.0 || stack <= 0.0 {
return None; return None;
} }
let started = std::time::Instant::now(); let started = std::time::Instant::now();
let turn = fast7::mask(&spot.board[..4]); let turn = fast7::mask(&spot.board[..4]);
let river = fast7::bit(spot.board[4]); let river = fast7::bit(spot.board[4]);
let dead = turn | river; let dead = turn | river;
let hands = [hands_of(hero, dead, true), hands_of(villain_list, dead, false)]; let hands = [hands_of(hero, dead, true), hands_of(villain_list, dead, false)];
if hands[0].masks.is_empty() || hands[1].masks.is_empty() { if hands[0].masks.is_empty() || hands[1].masks.is_empty() {
return None; return None;
} }
let bets = TrBets { pot, stack, first, turn: river_menu(), river: river_menu() }; let bets = TrBets { pot, stack, first, turn: river_menu(), river: river_menu() };
let game = build_river(&bets, &forced); let game = build_river(&bets, &forced);
let at = game.at?; let at = game.at?;
if !matches!(game.nodes.get(at), Some(TNode::Dec { player: 0, street: 1, .. })) { if !matches!(game.nodes.get(at), Some(TNode::Dec { player: 0, street: 1, .. })) {
return None; return None;
} }
let combos = [hands[0].masks.len(), hands[1].masks.len()]; let combos = [hands[0].masks.len(), hands[1].masks.len()];
let hero_masks = hands[0].masks.clone(); let hero_masks = hands[0].masks.clone();
let acts = game.acts[at].clone(); let acts = game.acts[at].clone();
let nodes = game.nodes.len(); let nodes = game.nodes.len();
let villain_weights = hands[1].weights.clone(); let villain_weights = hands[1].weights.clone();
let mut solver = TrSolver::with_cards(game, hands, turn, vec![river], 1.0); let mut solver = TrSolver::with_cards(game, hands, turn, vec![river], 1.0);
if let Some(r) = read { if let Some(r) = read {
lock_villain(&mut solver, r, pot, dead, &villain_weights); lock_villain(&mut solver, r, pot, dead, &villain_weights);
} }
let mut done = 0; let mut done = 0;
while done < ITERS { while done < ITERS {
solver.iterate(); solver.iterate();
done += 1; done += 1;
if done % 10 == 0 && started.elapsed().as_secs_f64() * 1e3 > BUDGET_MS { if done % 10 == 0 && started.elapsed().as_secs_f64() * 1e3 > BUDGET_MS {
break; break;
} }
} }
if done < MIN_ITERS { if done < MIN_ITERS {
return None; return None;
} }
let strategy = solver.strategy(); let strategy = solver.strategy();
let rows: Vec<f64> = (0..combos[0]).flat_map(|i| strategy.row(at, 0, i).to_vec()).collect(); let rows: Vec<f64> = (0..combos[0]).flat_map(|i| strategy.row(at, 0, i).to_vec()).collect();
let millis = started.elapsed().as_secs_f64() * 1e3; let millis = started.elapsed().as_secs_f64() * 1e3;
Some(Solved { rows, acts, hero_masks, millis, iterations: done, combos, nodes, source }) Some(Solved { rows, acts, hero_masks, millis, iterations: done, combos, nodes, source })
} }
/// Hero's action for the real hand from a solved node: the equilibrium mix, realised from the spot seed. /// Hero's action for the real hand from a solved node: the equilibrium mix, realised from the spot seed.
fn decide_from(spot: &Spot, solved: &Solved, hero_mask: u64) -> Option<Decision> { fn decide_from(spot: &Spot, solved: &Solved, hero_mask: u64) -> Option<Decision> {
let idx = solved.hero_masks.iter().position(|m| *m == hero_mask)?; let idx = solved.hero_masks.iter().position(|m| *m == hero_mask)?;
let a = solved.acts.len(); let a = solved.acts.len();
let row = &solved.rows[idx * a..(idx + 1) * a]; let row = &solved.rows[idx * a..(idx + 1) * a];
let (draw, _) = Rng::seeded(spot.seed).unit(); let (draw, _) = Rng::seeded(spot.seed).unit();
let mut acc = 0.0; let mut acc = 0.0;
let mut pick = a.saturating_sub(1); let mut pick = a.saturating_sub(1);
for (k, p) in row.iter().enumerate() { for (k, p) in row.iter().enumerate() {
acc += p; acc += p;
if draw < acc { if draw < acc {
pick = k; pick = k;
break; break;
} }
} }
let act = *solved.acts.get(pick)?; let act = *solved.acts.get(pick)?;
let choice = legal_choice(spot, act); let choice = legal_choice(spot, act);
let p = row.get(pick).copied().unwrap_or(0.0); let p = row.get(pick).copied().unwrap_or(0.0);
Some(Decision::new( Some(Decision::new(
choice, choice,
p.clamp(0.0, 1.0), p.clamp(0.0, 1.0),
format!( format!(
"river solver ({}): {}x{} combos, {} nodes, {} iters, {act:?} p {p:.2}, {:.0} ms", "river solver ({}): {}x{} combos, {} nodes, {} iters, {act:?} p {p:.2}, {:.0} ms",
solved.source, solved.combos[0], solved.combos[1], solved.nodes, solved.iterations, solved.millis solved.source, solved.combos[0], solved.combos[1], solved.nodes, solved.iterations, solved.millis
), ),
)) ))
} }
/// Both ranges from the range model (the action history): hero's as the model reads hero's own line /// Both ranges from the range model (the action history): hero's as the model reads hero's own line
/// (no read), the villain's with its gated read. Board cards only are dead (not hero's). /// (no read), the villain's with its gated read. Board cards only are dead (not hero's).
pub fn model_lists(spot: &Spot) -> Option<(Vec<(Vec<Card>, f64)>, Vec<(Vec<Card>, f64)>)> { pub fn model_lists(spot: &Spot) -> Option<(Vec<(Vec<Card>, f64)>, Vec<(Vec<Card>, f64)>)> {
let villain = spot.live_villains().next()?; let villain = spot.live_villains().next()?;
let rules = spot.rules(); let rules = spot.rules();
let list = |who: &Villain| { let list = |who: &Villain| {
let filter = crate::engine::range_filter::range_filter(&crate::exploit::range_model::range_spec(spot, who), rules, spot.variant, &spot.board); let filter = crate::engine::range_filter::range_filter(&crate::exploit::range_model::range_spec(spot, who), rules, spot.variant, &spot.board);
crate::engine::range_combos::combos(&rules, &filter, &spot.board) crate::engine::range_combos::combos(&rules, &filter, &spot.board)
}; };
let me = Villain { seat: spot.hero_seat, stack: spot.hero_stack, folded: false, profile: None }; let me = Villain { seat: spot.hero_seat, stack: spot.hero_stack, folded: false, profile: None };
let eins = |l: Vec<Vec<Card>>| l.into_iter().map(|c| (c, 1.0)).collect::<Vec<_>>(); let eins = |l: Vec<Vec<Card>>| l.into_iter().map(|c| (c, 1.0)).collect::<Vec<_>>();
Some((eins(list(&me)?), eins(list(villain)?))) Some((eins(list(&me)?), eins(list(villain)?)))
} }
/// The read layer (`exploit::range_read`, switch `GEGNER_RANGE=1`, default off): the villain's read from /// The read layer (`exploit::range_read`, switch `GEGNER_RANGE=1`, default off): the villain's read from
/// its UNGATED profile, or `None` = the plain solver. /// its UNGATED profile, or `None` = the plain solver.
pub fn read_of(raw: &Spot) -> Option<RangeRead> { pub fn read_of(raw: &Spot) -> Option<RangeRead> {
if std::env::var("GEGNER_RANGE").as_deref() != Ok("1") { if std::env::var("GEGNER_RANGE").as_deref() != Ok("1") {
return None; return None;
} }
let villain = raw.live_villains().next()?; let villain = raw.live_villains().next()?;
RangeRead::from_profile(villain.profile.as_ref()) RangeRead::from_profile(villain.profile.as_ref())
} }
/// Weighted mid-rank percentile of each combo's current strength (`fast7` score with `board`) within /// Weighted mid-rank percentile of each combo's current strength (`fast7` score with `board`) within
/// the list. Exact on the river; current strength only (draw-blind) on flop and turn. /// the list. Exact on the river; current strength only (draw-blind) on flop and turn.
pub fn percentiles(masks: &[u64], weights: &[f64], board: u64) -> Vec<f64> { pub fn percentiles(masks: &[u64], weights: &[f64], board: u64) -> Vec<f64> {
let score: Vec<u32> = masks.iter().map(|m| fast7::score(m | board)).collect(); let score: Vec<u32> = masks.iter().map(|m| fast7::score(m | board)).collect();
let mut order: Vec<usize> = (0..masks.len()).collect(); let mut order: Vec<usize> = (0..masks.len()).collect();
order.sort_by_key(|i| score[*i]); order.sort_by_key(|i| score[*i]);
let total: f64 = weights.iter().sum::<f64>().max(1e-300); let total: f64 = weights.iter().sum::<f64>().max(1e-300);
let mut out = vec![0.5; masks.len()]; let mut out = vec![0.5; masks.len()];
let mut below = 0.0; let mut below = 0.0;
let mut k = 0; let mut k = 0;
while k < order.len() { while k < order.len() {
let mut e = k; let mut e = k;
let mut tie = 0.0; let mut tie = 0.0;
while e < order.len() && score[order[e]] == score[order[k]] { while e < order.len() && score[order[e]] == score[order[k]] {
tie += weights[order[e]]; tie += weights[order[e]];
e += 1; e += 1;
} }
for &i in &order[k..e] { for &i in &order[k..e] {
out[i] = (below + tie / 2.0) / total; out[i] = (below + tie / 2.0) / total;
} }
below += tie; below += tie;
k = e; k = e;
} }
out out
} }
/// The ranges of this spot (hero, villain) and where they came from: the blueprint where it recognises /// The ranges of this spot (hero, villain) and where they came from: the blueprint where it recognises
/// the spot (unless `mode` is `Modell`), else the range model of the action history. THE HOOK of the /// the spot (unless `mode` is `Modell`), else the range model of the action history. THE HOOK of the
/// read layer: with a read, the villain's final weights are tilted by strength percentile /// read layer: with a read, the villain's final weights are tilted by strength percentile
/// (`RangeRead::reweigh`); `read = None` returns the lists unchanged. Used by stages A, B and C. /// (`RangeRead::reweigh`); `read = None` returns the lists unchanged. Used by stages A, B and C.
pub fn solver_lists(spot: &Spot, mode: RiverSpieler, read: Option<&RangeRead>) -> Option<(Vec<(Vec<Card>, f64)>, Vec<(Vec<Card>, f64)>, &'static str)> { pub fn solver_lists(spot: &Spot, mode: RiverSpieler, read: Option<&RangeRead>) -> Option<(Vec<(Vec<Card>, f64)>, Vec<(Vec<Card>, f64)>, &'static str)> {
let (h, mut v, source) = match mode { let (h, mut v, source) = match mode {
RiverSpieler::An => match crate::blueprint::ranges::gewichtete_listen_offen(spot) { RiverSpieler::An => match crate::blueprint::ranges::gewichtete_listen_offen(spot) {
Some((h, v)) => (h, v, "grund"), Some((h, v)) => (h, v, "grund"),
None => { None => {
let (h, v) = model_lists(spot)?; let (h, v) = model_lists(spot)?;
(h, v, "modell") (h, v, "modell")
} }
}, },
_ => { _ => {
let (h, v) = model_lists(spot)?; let (h, v) = model_lists(spot)?;
(h, v, "modell") (h, v, "modell")
} }
}; };
if let Some(r) = read.filter(|r| r.confidence > 0.0) { if let Some(r) = read.filter(|r| r.confidence > 0.0) {
let board = fast7::mask(&spot.board); let board = fast7::mask(&spot.board);
let masks: Vec<u64> = v.iter().map(|(c, _)| fast7::mask(c)).collect(); let masks: Vec<u64> = v.iter().map(|(c, _)| fast7::mask(c)).collect();
let weights: Vec<f64> = v.iter().map(|(_, w)| *w).collect(); let weights: Vec<f64> = v.iter().map(|(_, w)| *w).collect();
let pct = percentiles(&masks, &weights, board); let pct = percentiles(&masks, &weights, board);
let pairs: Vec<(f64, f64)> = weights.iter().copied().zip(pct).collect(); let pairs: Vec<(f64, f64)> = weights.iter().copied().zip(pct).collect();
for ((_, w), x) in v.iter_mut().zip(r.reweigh(&pairs)) { for ((_, w), x) in v.iter_mut().zip(r.reweigh(&pairs)) {
*w = x; *w = x;
} }
} }
Some((h, v, source)) Some((h, v, source))
} }
/// Value hands bet from this strength percentile up when the believed villain is checked to /// Lock the villain's river decisions toward the read (restricted Nash response, `TrSolver::lock`):
/// (as `river_subgame`'s VALUE_RANK). /// the believed row per combo is `RangeRead::believed_row` (one source of truth with the read layer).
const BELIEVED_VALUE_RANK: f64 = 0.60; /// Facing an opening bet the weight is the fold read's trust, where it may bet the bluff read's trust;
/// facing a raise the node stays free (the read says nothing about raises). Nodes the read has no
/// Lock the villain's river decisions toward the read (restricted Nash response): facing a bet it folds /// opinion on stay pure CFR.
/// the weakest `fold_to_bet` share of its range and calls the rest (weight = the fold read's trust); fn lock_villain(solver: &mut TrSolver, read: &RangeRead, pot: f64, board: u64, villain_weights: &[f64]) {
/// checked to, it bets its top `1 - BELIEVED_VALUE_RANK` at the size nearest 75 % pot plus the weakest let pct = percentiles(solver.masks(1), villain_weights, board);
/// hands as bluffs so that the air share of the bet is `bluff_share` (weight = the bluff read's trust). // The action that led into each node (a raise faced vs an opening bet faced).
/// Facing a raise it stays free. let mut incoming: Vec<Option<Act>> = vec![None; solver.game.nodes.len()];
fn lock_villain(solver: &mut TrSolver, read: &RangeRead, pot: f64, board: u64, villain_weights: &[f64]) { for (k, n) in solver.game.nodes.iter().enumerate() {
let pct = percentiles(solver.masks(1), villain_weights, board); if let TNode::Dec { kids, .. } = n {
// The action that led into each node (a raise faced vs an opening bet faced). for (c, kid) in kids.iter().enumerate() {
let mut incoming: Vec<Option<Act>> = vec![None; solver.game.nodes.len()]; incoming[*kid] = solver.game.acts[k].get(c).copied();
for (k, n) in solver.game.nodes.iter().enumerate() { }
if let TNode::Dec { kids, .. } = n { }
for (c, kid) in kids.iter().enumerate() { }
incoming[*kid] = solver.game.acts[k].get(c).copied(); let nodes: Vec<(usize, Vec<Act>)> = solver
} .game
} .nodes
} .iter()
let nodes: Vec<(usize, Vec<Act>)> = solver .enumerate()
.game .filter_map(|(k, n)| match n {
.nodes TNode::Dec { player: 1, .. } => Some((k, solver.game.acts[k].clone())),
.iter() _ => None,
.enumerate() })
.filter_map(|(k, n)| match n { .collect();
TNode::Dec { player: 1, .. } => Some((k, solver.game.acts[k].clone())), for (node, acts) in nodes {
_ => None, let facing = acts.contains(&Act::Fold);
}) if facing && !matches!(incoming[node], Some(Act::Bet(_))) {
.collect(); continue;
for (node, acts) in nodes { }
let a = acts.len(); let rows: Option<Vec<f64>> = pct.iter().map(|p| read.believed_row(2, &acts, pot, *p)).collect::<Option<Vec<Vec<f64>>>>().map(|r| r.concat());
let facing_bet = acts.contains(&Act::Fold) && matches!(incoming[node], Some(Act::Bet(_))); if let Some(rows) = rows {
if facing_bet { solver.lock(node, rows, read.trust(!facing, 2));
let Some(f) = read.fold_to_bet(2) else { continue }; }
let call = acts.iter().position(|x| *x == Act::Call).unwrap_or(1); }
let rows: Vec<f64> = pct.iter().flat_map(|p| (0..a).map(move |k| if *p < f { f64::from(k == 0) } else { f64::from(k == call) })).collect(); }
solver.lock(node, rows, read.trust(false, 2));
} else if !acts.contains(&Act::Fold) && acts.first() == Some(&Act::Check) { static CACHE: Mutex<Option<HashMap<u64, Arc<Solved>>>> = Mutex::new(None);
let Some((bet, to)) = acts.iter().enumerate().filter_map(|(k, x)| if let Act::Bet(t) = x { Some((k, *t)) } else { None }).min_by(|x, y| (x.1 / pot - 0.75).abs().total_cmp(&(y.1 / pot - 0.75).abs())) else { continue }; const CACHE_MAX: usize = 4096;
let bs = read.bluff_share(2, to / pot).clamp(0.0, 0.9);
let value = 1.0 - BELIEVED_VALUE_RANK; /// Identity of the public state, the villain's read and the mode (not hero's cards).
let bluff = (value * bs / (1.0 - bs)).min(BELIEVED_VALUE_RANK); fn public_key(spot: &Spot, mode: RiverSpieler) -> u64 {
let rows: Vec<f64> = pct.iter().flat_map(|p| (0..a).map(move |k| if *p >= BELIEVED_VALUE_RANK || *p < bluff { f64::from(k == bet) } else { f64::from(k == 0) })).collect(); let mut h = std::collections::hash_map::DefaultHasher::new();
solver.lock(node, rows, read.trust(true, 2)); format!("{:?}", spot.history).hash(&mut h);
} format!("{:?}", spot.board).hash(&mut h);
} [spot.pot, spot.to_call, spot.hero_stack, spot.big_blind].iter().for_each(|x| x.to_bits().hash(&mut h));
} spot.live_villains().for_each(|v| {
(v.seat, v.stack.to_bits()).hash(&mut h);
static CACHE: Mutex<Option<HashMap<u64, Arc<Solved>>>> = Mutex::new(None); format!("{:?}", v.profile).hash(&mut h);
const CACHE_MAX: usize = 4096; });
(spot.hero_seat, spot.button_seat, spot.seats, MODE.load(Ordering::Relaxed), mode as u8, ITERS).hash(&mut h);
/// Identity of the public state, the villain's read and the mode (not hero's cards). h.finish()
fn public_key(spot: &Spot, mode: RiverSpieler) -> u64 { }
let mut h = std::collections::hash_map::DefaultHasher::new();
format!("{:?}", spot.history).hash(&mut h); /// The live decision: the river solved to equilibrium for hero's real hand, or `None` (switch off, not
format!("{:?}", spot.board).hash(&mut h); /// a heads-up Hold'em river, off the tree, budget) and the heuristic keeps the decision. `spot` carries
[spot.pot, spot.to_call, spot.hero_stack, spot.big_blind].iter().for_each(|x| x.to_bits().hash(&mut h)); /// the ungated reads; the villain range uses the gated ones, as the heuristic's does.
spot.live_villains().for_each(|v| { pub fn river_spieler_decision(raw: &Spot) -> Option<Decision> {
(v.seat, v.stack.to_bits()).hash(&mut h); let mode = river_spieler();
format!("{:?}", v.profile).hash(&mut h); if mode == RiverSpieler::Aus || raw.street != Street::River || raw.hero_cards.len() != 2 || raw.board.len() != 5 {
}); return None;
(spot.hero_seat, spot.button_seat, spot.seats, MODE.load(Ordering::Relaxed), mode as u8, ITERS).hash(&mut h); }
h.finish() let gated = crate::engine::read_gate::gate_reads(raw);
} let spot = &gated;
if spot.live_villains().count() != 1 {
/// The live decision: the river solved to equilibrium for hero's real hand, or `None` (switch off, not return None;
/// a heads-up Hold'em river, off the tree, budget) and the heuristic keeps the decision. `spot` carries }
/// the ungated reads; the villain range uses the gated ones, as the heuristic's does. let hero_mask = fast7::mask(&spot.hero_cards);
pub fn river_spieler_decision(raw: &Spot) -> Option<Decision> { if hero_mask & fast7::mask(&spot.board) != 0 {
let mode = river_spieler(); return None;
if mode == RiverSpieler::Aus || raw.street != Street::River || raw.hero_cards.len() != 2 || raw.board.len() != 5 { }
return None; let read = read_of(raw);
} let mut key = public_key(spot, mode);
let gated = crate::engine::read_gate::gate_reads(raw); if read.is_some() {
let spot = &gated; let mut h = std::collections::hash_map::DefaultHasher::new();
if spot.live_villains().count() != 1 { (key, format!("{:?}", raw.live_villains().next().map(|v| v.profile.clone()))).hash(&mut h);
return None; key = h.finish();
} }
let hero_mask = fast7::mask(&spot.hero_cards); let cached = CACHE.lock().ok().and_then(|m| m.as_ref().and_then(|m| m.get(&key).cloned()));
if hero_mask & fast7::mask(&spot.board) != 0 { let solved = match cached {
return None; Some(s) => s,
} None => {
let read = read_of(raw); let (hero, villain, source) = solver_lists(spot, mode, read.as_ref())?;
let mut key = public_key(spot, mode); let solved = Arc::new(solve_river(spot, &hero, &villain, source, read.as_ref())?);
if read.is_some() { if let Ok(mut m) = CACHE.lock() {
let mut h = std::collections::hash_map::DefaultHasher::new(); let map = m.get_or_insert_with(HashMap::new);
(key, format!("{:?}", raw.live_villains().next().map(|v| v.profile.clone()))).hash(&mut h); if map.len() >= CACHE_MAX {
key = h.finish(); map.clear();
} }
let cached = CACHE.lock().ok().and_then(|m| m.as_ref().and_then(|m| m.get(&key).cloned())); map.insert(key, solved.clone());
let solved = match cached { }
Some(s) => s, solved
None => { }
let (hero, villain, source) = solver_lists(spot, mode, read.as_ref())?; };
let solved = Arc::new(solve_river(spot, &hero, &villain, source, read.as_ref())?); decide_from(spot, &solved, hero_mask)
if let Ok(mut m) = CACHE.lock() { }
let map = m.get_or_insert_with(HashMap::new);
if map.len() >= CACHE_MAX { #[cfg(test)]
map.clear(); mod tests;
}
map.insert(key, solved.clone());
}
solved
}
};
decide_from(spot, &solved, hero_mask)
}
#[cfg(test)]
mod tests;