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,
//! 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
//! 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
//! (no strength buckets, blockers count).
//! - **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
//! 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
//! 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).
//! - **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.
//! Every hero hand outside the modelled range joins the solve at a token weight, so it gets a
//! strategy without moving the equilibrium.
//! - **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`).
//!
//! 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.
use crate::card::Card;
use crate::cfr::river_game::Act;
use crate::cfr::turn_river_game::{build_river, Hands, Menu, TNode, TrBets, TrSolver};
use crate::exploit::range_read::RangeRead;
use crate::engine::river_subgame::{legal_choice, river_line};
use crate::game::{Decision, Spot, Street, Villain};
use crate::hand::fast7;
use crate::rng::Rng;
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::sync::atomic::{AtomicU8, Ordering};
use std::sync::{Arc, Mutex};
/// Who plays the heads-up river.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RiverSpieler {
/// The heuristic (default).
Aus,
/// The solver; blueprint ranges where the spot is a blueprint scenario, else the range model.
An,
/// The solver with range-model ranges everywhere (measurement arm).
Modell,
}
static MODE: AtomicU8 = AtomicU8::new(0);
pub fn set_river_spieler(mode: RiverSpieler) {
MODE.store(
match mode {
RiverSpieler::Aus => 0,
RiverSpieler::An => 1,
RiverSpieler::Modell => 2,
},
Ordering::Relaxed,
);
}
pub fn river_spieler() -> RiverSpieler {
match MODE.load(Ordering::Relaxed) {
1 => RiverSpieler::An,
2 => RiverSpieler::Modell,
_ => RiverSpieler::Aus,
}
}
/// `SOLVER_RIVER`: `1`/`an` -> `An`, `modell` -> `Modell`, else `Aus`.
pub fn from_env() -> RiverSpieler {
match std::env::var("SOLVER_RIVER").as_deref() {
Ok("1") | Ok("an") => RiverSpieler::An,
Ok("modell") => RiverSpieler::Modell,
_ => RiverSpieler::Aus,
}
}
/// CFR+ iterations at most.
pub const ITERS: u32 = 600;
/// Fewer finished iterations than this (time budget hit): the heuristic decides.
pub const MIN_ITERS: u32 = 100;
/// Wall-time budget of one solve.
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.
fn river_menu() -> Menu {
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.
pub struct Solved {
rows: Vec<f64>,
acts: Vec<Act>,
hero_masks: Vec<u64>,
pub millis: f64,
pub iterations: u32,
pub combos: [usize; 2],
pub nodes: usize,
pub source: &'static str,
}
/// 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
/// not depend on its own reach, so a token-weight hand plays its counterfactual best line without moving
/// the equilibrium).
fn hands_of(list: &[(Vec<Card>, f64)], dead: u64, fill: bool) -> Hands {
let mut w: HashMap<u64, f64> = HashMap::new();
for (c, x) in list {
if c.len() == 2 && *x > 0.0 && x.is_finite() {
let m = fast7::mask(c);
if m & dead == 0 && m.count_ones() == 2 {
let e = w.entry(m).or_insert(0.0);
*e = e.max(*x);
}
}
}
let top = w.values().copied().fold(0.0f64, f64::max).max(1e-12);
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();
for i in 0..bits.len() {
for j in i + 1..bits.len() {
w.entry(bits[i] | bits[j]).or_insert(top * TOKEN);
}
}
}
let mut v: Vec<(u64, f64)> = w.into_iter().collect();
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() }
}
/// Relative weight of a hero hand outside the modelled range.
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.
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 {
return None;
}
let villain = spot.live_villains().next()?;
let (first, forced, c) = river_line(spot, villain);
let pot = spot.pot - c[0] - c[1];
let stack = (spot.hero_stack + c[0]).min(villain.stack + c[1]);
if pot <= 0.0 || stack <= 0.0 {
return None;
}
let started = std::time::Instant::now();
let turn = fast7::mask(&spot.board[..4]);
let river = fast7::bit(spot.board[4]);
let dead = turn | river;
let hands = [hands_of(hero, dead, true), hands_of(villain_list, dead, false)];
if hands[0].masks.is_empty() || hands[1].masks.is_empty() {
return None;
}
let bets = TrBets { pot, stack, first, turn: river_menu(), river: river_menu() };
let game = build_river(&bets, &forced);
let at = game.at?;
if !matches!(game.nodes.get(at), Some(TNode::Dec { player: 0, street: 1, .. })) {
return None;
}
let combos = [hands[0].masks.len(), hands[1].masks.len()];
let hero_masks = hands[0].masks.clone();
let acts = game.acts[at].clone();
let nodes = game.nodes.len();
let villain_weights = hands[1].weights.clone();
let mut solver = TrSolver::with_cards(game, hands, turn, vec![river], 1.0);
if let Some(r) = read {
lock_villain(&mut solver, r, pot, dead, &villain_weights);
}
let mut done = 0;
while done < ITERS {
solver.iterate();
done += 1;
if done % 10 == 0 && started.elapsed().as_secs_f64() * 1e3 > BUDGET_MS {
break;
}
}
if done < MIN_ITERS {
return None;
}
let strategy = solver.strategy();
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;
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.
fn decide_from(spot: &Spot, solved: &Solved, hero_mask: u64) -> Option<Decision> {
let idx = solved.hero_masks.iter().position(|m| *m == hero_mask)?;
let a = solved.acts.len();
let row = &solved.rows[idx * a..(idx + 1) * a];
let (draw, _) = Rng::seeded(spot.seed).unit();
let mut acc = 0.0;
let mut pick = a.saturating_sub(1);
for (k, p) in row.iter().enumerate() {
acc += p;
if draw < acc {
pick = k;
break;
}
}
let act = *solved.acts.get(pick)?;
let choice = legal_choice(spot, act);
let p = row.get(pick).copied().unwrap_or(0.0);
Some(Decision::new(
choice,
p.clamp(0.0, 1.0),
format!(
"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
),
))
}
/// 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).
pub fn model_lists(spot: &Spot) -> Option<(Vec<(Vec<Card>, f64)>, Vec<(Vec<Card>, f64)>)> {
let villain = spot.live_villains().next()?;
let rules = spot.rules();
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);
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 eins = |l: Vec<Vec<Card>>| l.into_iter().map(|c| (c, 1.0)).collect::<Vec<_>>();
Some((eins(list(&me)?), eins(list(villain)?)))
}
/// 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.
pub fn read_of(raw: &Spot) -> Option<RangeRead> {
if std::env::var("GEGNER_RANGE").as_deref() != Ok("1") {
return None;
}
let villain = raw.live_villains().next()?;
RangeRead::from_profile(villain.profile.as_ref())
}
/// 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.
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 mut order: Vec<usize> = (0..masks.len()).collect();
order.sort_by_key(|i| score[*i]);
let total: f64 = weights.iter().sum::<f64>().max(1e-300);
let mut out = vec![0.5; masks.len()];
let mut below = 0.0;
let mut k = 0;
while k < order.len() {
let mut e = k;
let mut tie = 0.0;
while e < order.len() && score[order[e]] == score[order[k]] {
tie += weights[order[e]];
e += 1;
}
for &i in &order[k..e] {
out[i] = (below + tie / 2.0) / total;
}
below += tie;
k = e;
}
out
}
/// 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
/// 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.
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 {
RiverSpieler::An => match crate::blueprint::ranges::gewichtete_listen_offen(spot) {
Some((h, v)) => (h, v, "grund"),
None => {
let (h, v) = model_lists(spot)?;
(h, v, "modell")
}
},
_ => {
let (h, v) = model_lists(spot)?;
(h, v, "modell")
}
};
if let Some(r) = read.filter(|r| r.confidence > 0.0) {
let board = fast7::mask(&spot.board);
let masks: Vec<u64> = v.iter().map(|(c, _)| fast7::mask(c)).collect();
let weights: Vec<f64> = v.iter().map(|(_, w)| *w).collect();
let pct = percentiles(&masks, &weights, board);
let pairs: Vec<(f64, f64)> = weights.iter().copied().zip(pct).collect();
for ((_, w), x) in v.iter_mut().zip(r.reweigh(&pairs)) {
*w = x;
}
}
Some((h, v, source))
}
/// Value hands bet from this strength percentile up when the believed villain is checked to
/// (as `river_subgame`'s VALUE_RANK).
const BELIEVED_VALUE_RANK: f64 = 0.60;
/// Lock the villain's river decisions toward the read (restricted Nash response): facing a bet it folds
/// the weakest `fold_to_bet` share of its range and calls the rest (weight = the fold read's trust);
/// checked to, it bets its top `1 - BELIEVED_VALUE_RANK` at the size nearest 75 % pot plus the weakest
/// hands as bluffs so that the air share of the bet is `bluff_share` (weight = the bluff read's trust).
/// Facing a raise it stays free.
fn lock_villain(solver: &mut TrSolver, read: &RangeRead, pot: f64, board: u64, villain_weights: &[f64]) {
let pct = percentiles(solver.masks(1), villain_weights, board);
// The action that led into each node (a raise faced vs an opening bet faced).
let mut incoming: Vec<Option<Act>> = vec![None; solver.game.nodes.len()];
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()
.enumerate()
.filter_map(|(k, n)| match n {
TNode::Dec { player: 1, .. } => Some((k, solver.game.acts[k].clone())),
_ => None,
})
.collect();
for (node, acts) in nodes {
let a = acts.len();
let facing_bet = acts.contains(&Act::Fold) && matches!(incoming[node], Some(Act::Bet(_)));
if facing_bet {
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) {
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 };
let bs = read.bluff_share(2, to / pot).clamp(0.0, 0.9);
let value = 1.0 - BELIEVED_VALUE_RANK;
let bluff = (value * bs / (1.0 - bs)).min(BELIEVED_VALUE_RANK);
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();
solver.lock(node, rows, read.trust(true, 2));
}
}
}
static CACHE: Mutex<Option<HashMap<u64, Arc<Solved>>>> = Mutex::new(None);
const CACHE_MAX: usize = 4096;
/// Identity of the public state, the villain's read and the mode (not hero's cards).
fn public_key(spot: &Spot, mode: RiverSpieler) -> u64 {
let mut h = std::collections::hash_map::DefaultHasher::new();
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);
format!("{:?}", v.profile).hash(&mut h);
});
(spot.hero_seat, spot.button_seat, spot.seats, MODE.load(Ordering::Relaxed), mode as u8, ITERS).hash(&mut h);
h.finish()
}
/// The live decision: the river solved to equilibrium for hero's real hand, or `None` (switch off, not
/// 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.
pub fn river_spieler_decision(raw: &Spot) -> Option<Decision> {
let mode = river_spieler();
if mode == RiverSpieler::Aus || raw.street != Street::River || raw.hero_cards.len() != 2 || raw.board.len() != 5 {
return None;
}
let gated = crate::engine::read_gate::gate_reads(raw);
let spot = &gated;
if spot.live_villains().count() != 1 {
return None;
}
let hero_mask = fast7::mask(&spot.hero_cards);
if hero_mask & fast7::mask(&spot.board) != 0 {
return None;
}
let read = read_of(raw);
let mut key = public_key(spot, mode);
if read.is_some() {
let mut h = std::collections::hash_map::DefaultHasher::new();
(key, format!("{:?}", raw.live_villains().next().map(|v| v.profile.clone()))).hash(&mut h);
key = h.finish();
}
let cached = CACHE.lock().ok().and_then(|m| m.as_ref().and_then(|m| m.get(&key).cloned()));
let solved = match cached {
Some(s) => s,
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())?);
if let Ok(mut m) = CACHE.lock() {
let map = m.get_or_insert_with(HashMap::new);
if map.len() >= CACHE_MAX {
map.clear();
}
map.insert(key, solved.clone());
}
solved
}
};
decide_from(spot, &solved, hero_mask)
}
#[cfg(test)]
mod tests;
//! 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).
//!
//! - **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
//! vectorised CFR+ of `TrSolver` over real combos: card removal and showdowns are exact per combo
//! (no strength buckets, blockers count).
//! - **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
//! 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
//! 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).
//! - **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.
//! Every hero hand outside the modelled range joins the solve at a token weight, so it gets a
//! strategy without moving the equilibrium.
//! - **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`).
//!
//! 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.
use crate::card::Card;
use crate::cfr::river_game::Act;
use crate::cfr::turn_river_game::{build_river, Hands, Menu, TNode, TrBets, TrSolver};
use crate::exploit::range_read::RangeRead;
use crate::engine::river_subgame::{legal_choice, river_line};
use crate::game::{Decision, Spot, Street, Villain};
use crate::hand::fast7;
use crate::rng::Rng;
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::sync::atomic::{AtomicU8, Ordering};
use std::sync::{Arc, Mutex};
/// Who plays the heads-up river.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RiverSpieler {
/// The heuristic (default).
Aus,
/// The solver; blueprint ranges where the spot is a blueprint scenario, else the range model.
An,
/// The solver with range-model ranges everywhere (measurement arm).
Modell,
}
static MODE: AtomicU8 = AtomicU8::new(0);
pub fn set_river_spieler(mode: RiverSpieler) {
MODE.store(
match mode {
RiverSpieler::Aus => 0,
RiverSpieler::An => 1,
RiverSpieler::Modell => 2,
},
Ordering::Relaxed,
);
}
pub fn river_spieler() -> RiverSpieler {
match MODE.load(Ordering::Relaxed) {
1 => RiverSpieler::An,
2 => RiverSpieler::Modell,
_ => RiverSpieler::Aus,
}
}
/// `SOLVER_RIVER`: `1`/`an` -> `An`, `modell` -> `Modell`, else `Aus`.
pub fn from_env() -> RiverSpieler {
match std::env::var("SOLVER_RIVER").as_deref() {
Ok("1") | Ok("an") => RiverSpieler::An,
Ok("modell") => RiverSpieler::Modell,
_ => RiverSpieler::Aus,
}
}
/// CFR+ iterations at most.
pub const ITERS: u32 = 600;
/// Fewer finished iterations than this (time budget hit): the heuristic decides.
pub const MIN_ITERS: u32 = 100;
/// Wall-time budget of one solve.
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.
fn river_menu() -> Menu {
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.
pub struct Solved {
rows: Vec<f64>,
acts: Vec<Act>,
hero_masks: Vec<u64>,
pub millis: f64,
pub iterations: u32,
pub combos: [usize; 2],
pub nodes: usize,
pub source: &'static str,
}
/// 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
/// not depend on its own reach, so a token-weight hand plays its counterfactual best line without moving
/// the equilibrium).
fn hands_of(list: &[(Vec<Card>, f64)], dead: u64, fill: bool) -> Hands {
let mut w: HashMap<u64, f64> = HashMap::new();
for (c, x) in list {
if c.len() == 2 && *x > 0.0 && x.is_finite() {
let m = fast7::mask(c);
if m & dead == 0 && m.count_ones() == 2 {
let e = w.entry(m).or_insert(0.0);
*e = e.max(*x);
}
}
}
let top = w.values().copied().fold(0.0f64, f64::max).max(1e-12);
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();
for i in 0..bits.len() {
for j in i + 1..bits.len() {
w.entry(bits[i] | bits[j]).or_insert(top * TOKEN);
}
}
}
let mut v: Vec<(u64, f64)> = w.into_iter().collect();
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() }
}
/// Relative weight of a hero hand outside the modelled range.
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.
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 {
return None;
}
let villain = spot.live_villains().next()?;
let (first, forced, c) = river_line(spot, villain);
let pot = spot.pot - c[0] - c[1];
let stack = (spot.hero_stack + c[0]).min(villain.stack + c[1]);
if pot <= 0.0 || stack <= 0.0 {
return None;
}
let started = std::time::Instant::now();
let turn = fast7::mask(&spot.board[..4]);
let river = fast7::bit(spot.board[4]);
let dead = turn | river;
let hands = [hands_of(hero, dead, true), hands_of(villain_list, dead, false)];
if hands[0].masks.is_empty() || hands[1].masks.is_empty() {
return None;
}
let bets = TrBets { pot, stack, first, turn: river_menu(), river: river_menu() };
let game = build_river(&bets, &forced);
let at = game.at?;
if !matches!(game.nodes.get(at), Some(TNode::Dec { player: 0, street: 1, .. })) {
return None;
}
let combos = [hands[0].masks.len(), hands[1].masks.len()];
let hero_masks = hands[0].masks.clone();
let acts = game.acts[at].clone();
let nodes = game.nodes.len();
let villain_weights = hands[1].weights.clone();
let mut solver = TrSolver::with_cards(game, hands, turn, vec![river], 1.0);
if let Some(r) = read {
lock_villain(&mut solver, r, pot, dead, &villain_weights);
}
let mut done = 0;
while done < ITERS {
solver.iterate();
done += 1;
if done % 10 == 0 && started.elapsed().as_secs_f64() * 1e3 > BUDGET_MS {
break;
}
}
if done < MIN_ITERS {
return None;
}
let strategy = solver.strategy();
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;
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.
fn decide_from(spot: &Spot, solved: &Solved, hero_mask: u64) -> Option<Decision> {
let idx = solved.hero_masks.iter().position(|m| *m == hero_mask)?;
let a = solved.acts.len();
let row = &solved.rows[idx * a..(idx + 1) * a];
let (draw, _) = Rng::seeded(spot.seed).unit();
let mut acc = 0.0;
let mut pick = a.saturating_sub(1);
for (k, p) in row.iter().enumerate() {
acc += p;
if draw < acc {
pick = k;
break;
}
}
let act = *solved.acts.get(pick)?;
let choice = legal_choice(spot, act);
let p = row.get(pick).copied().unwrap_or(0.0);
Some(Decision::new(
choice,
p.clamp(0.0, 1.0),
format!(
"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
),
))
}
/// 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).
pub fn model_lists(spot: &Spot) -> Option<(Vec<(Vec<Card>, f64)>, Vec<(Vec<Card>, f64)>)> {
let villain = spot.live_villains().next()?;
let rules = spot.rules();
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);
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 eins = |l: Vec<Vec<Card>>| l.into_iter().map(|c| (c, 1.0)).collect::<Vec<_>>();
Some((eins(list(&me)?), eins(list(villain)?)))
}
/// 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.
pub fn read_of(raw: &Spot) -> Option<RangeRead> {
if std::env::var("GEGNER_RANGE").as_deref() != Ok("1") {
return None;
}
let villain = raw.live_villains().next()?;
RangeRead::from_profile(villain.profile.as_ref())
}
/// 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.
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 mut order: Vec<usize> = (0..masks.len()).collect();
order.sort_by_key(|i| score[*i]);
let total: f64 = weights.iter().sum::<f64>().max(1e-300);
let mut out = vec![0.5; masks.len()];
let mut below = 0.0;
let mut k = 0;
while k < order.len() {
let mut e = k;
let mut tie = 0.0;
while e < order.len() && score[order[e]] == score[order[k]] {
tie += weights[order[e]];
e += 1;
}
for &i in &order[k..e] {
out[i] = (below + tie / 2.0) / total;
}
below += tie;
k = e;
}
out
}
/// 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
/// 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.
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 {
RiverSpieler::An => match crate::blueprint::ranges::gewichtete_listen_offen(spot) {
Some((h, v)) => (h, v, "grund"),
None => {
let (h, v) = model_lists(spot)?;
(h, v, "modell")
}
},
_ => {
let (h, v) = model_lists(spot)?;
(h, v, "modell")
}
};
if let Some(r) = read.filter(|r| r.confidence > 0.0) {
let board = fast7::mask(&spot.board);
let masks: Vec<u64> = v.iter().map(|(c, _)| fast7::mask(c)).collect();
let weights: Vec<f64> = v.iter().map(|(_, w)| *w).collect();
let pct = percentiles(&masks, &weights, board);
let pairs: Vec<(f64, f64)> = weights.iter().copied().zip(pct).collect();
for ((_, w), x) in v.iter_mut().zip(r.reweigh(&pairs)) {
*w = x;
}
}
Some((h, v, source))
}
/// Lock the villain's river decisions toward the read (restricted Nash response, `TrSolver::lock`):
/// the believed row per combo is `RangeRead::believed_row` (one source of truth with the read layer).
/// 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
/// opinion on stay pure CFR.
fn lock_villain(solver: &mut TrSolver, read: &RangeRead, pot: f64, board: u64, villain_weights: &[f64]) {
let pct = percentiles(solver.masks(1), villain_weights, board);
// The action that led into each node (a raise faced vs an opening bet faced).
let mut incoming: Vec<Option<Act>> = vec![None; solver.game.nodes.len()];
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()
.enumerate()
.filter_map(|(k, n)| match n {
TNode::Dec { player: 1, .. } => Some((k, solver.game.acts[k].clone())),
_ => None,
})
.collect();
for (node, acts) in nodes {
let facing = acts.contains(&Act::Fold);
if facing && !matches!(incoming[node], Some(Act::Bet(_))) {
continue;
}
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());
if let Some(rows) = rows {
solver.lock(node, rows, read.trust(!facing, 2));
}
}
}
static CACHE: Mutex<Option<HashMap<u64, Arc<Solved>>>> = Mutex::new(None);
const CACHE_MAX: usize = 4096;
/// Identity of the public state, the villain's read and the mode (not hero's cards).
fn public_key(spot: &Spot, mode: RiverSpieler) -> u64 {
let mut h = std::collections::hash_map::DefaultHasher::new();
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);
format!("{:?}", v.profile).hash(&mut h);
});
(spot.hero_seat, spot.button_seat, spot.seats, MODE.load(Ordering::Relaxed), mode as u8, ITERS).hash(&mut h);
h.finish()
}
/// The live decision: the river solved to equilibrium for hero's real hand, or `None` (switch off, not
/// 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.
pub fn river_spieler_decision(raw: &Spot) -> Option<Decision> {
let mode = river_spieler();
if mode == RiverSpieler::Aus || raw.street != Street::River || raw.hero_cards.len() != 2 || raw.board.len() != 5 {
return None;
}
let gated = crate::engine::read_gate::gate_reads(raw);
let spot = &gated;
if spot.live_villains().count() != 1 {
return None;
}
let hero_mask = fast7::mask(&spot.hero_cards);
if hero_mask & fast7::mask(&spot.board) != 0 {
return None;
}
let read = read_of(raw);
let mut key = public_key(spot, mode);
if read.is_some() {
let mut h = std::collections::hash_map::DefaultHasher::new();
(key, format!("{:?}", raw.live_villains().next().map(|v| v.profile.clone()))).hash(&mut h);
key = h.finish();
}
let cached = CACHE.lock().ok().and_then(|m| m.as_ref().and_then(|m| m.get(&key).cloned()));
let solved = match cached {
Some(s) => s,
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())?);
if let Ok(mut m) = CACHE.lock() {
let map = m.get_or_insert_with(HashMap::new);
if map.len() >= CACHE_MAX {
map.clear();
}
map.insert(key, solved.clone());
}
solved
}
};
decide_from(spot, &solved, hero_mask)
}
#[cfg(test)]
mod tests;