Lock-Gewicht je Gegnerknoten w * n/(n+kappa) (Restricted Nash Response nach Datenstuetzung). n aus ranges_echt (Masse-gewichtet), wett_kurve (# n= je Punkt, Minimum der Nachbarn), BETTOR (Beiblatt <tabelle>.n aus bettor_n.py), Raise-Pool (Konstante). Gespielte Linie behaelt w_linie. Mehrweg (pool_sperren, river3/multi3) gleich. Aus = bitgleiche Rechnung. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
804 lines
38 KiB
Rust
804 lines
38 KiB
Rust
//! "Solver everywhere", the MULTIWAY turn and flop: 3- and 4-handed spots decided by Monte-Carlo CFR
|
||
//! over real combos across the remaining streets (`cfr::multi3`), the sibling of the multiway river
|
||
//! (`engine::river3_spieler`, same ranges, line replay and approximations). Switches `SOLVER_TURN3`
|
||
//! and `SOLVER_FLOP3` (default off: no decision, the engine is bit-identical).
|
||
//!
|
||
//! - **Turn game:** turn betting (33/75 % pot, all-in, one raise ×3), `TURN_SLOTS` river cards, river
|
||
//! betting (75 % pot, all-in, one raise), showdown.
|
||
//! - **Flop game:** flop betting (as the turn above), `FLOP_SLOTS` turn cards, turn betting (75 %,
|
||
//! all-in, one raise), the river dealt and checked down (as stage C, no river betting).
|
||
//! - **Ranges** per player from the range model of the line (gated reads), at most `MAX_COMBOS`.
|
||
//! - **Time:** `frist::TURN_MS` / `frist::FLOP_MS` per decision, own caps `TURN_BUDGET_MS` /
|
||
//! `FLOP_BUDGET_MS`; under `MIN_ITERS` iterations the heuristic decides.
|
||
//!
|
||
//! Named approximations: no equilibrium guarantee with three players; stacks capped at the smallest
|
||
//! live stack (no side pots); the next street's card from a few slots; one size on later streets.
|
||
|
||
use crate::cfr::multi3::{GameM, NodeM, SolverM};
|
||
use crate::cfr::river3::Menu3;
|
||
use crate::cfr::river_game::Act;
|
||
use crate::engine::river3_spieler::{acting_order, model_hands, street_line3};
|
||
use crate::engine::river_subgame::legal_choice;
|
||
use crate::game::{Decision, Spot, Street, Villain};
|
||
use crate::hand::fast7;
|
||
use crate::rng::Rng;
|
||
use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
|
||
|
||
static TURN3: AtomicBool = AtomicBool::new(false);
|
||
static FLOP3: AtomicBool = AtomicBool::new(false);
|
||
/// Stage 4 (19.11.): streets whose multiway solver decides only without a bet to call (bit 0 flop,
|
||
/// bit 1 turn, bit 2 river; switch value `offen`), and hand classes (bits over `hand::klasse::KLASSEN`)
|
||
/// left to the heuristic on every multiway street (`SOLVER3_OHNE=nichts/zug`). Both 0 by default.
|
||
static NUR_OFFEN: AtomicU8 = AtomicU8::new(0);
|
||
static OHNE: AtomicU8 = AtomicU8::new(0);
|
||
/// Classes left to the heuristic on the multiway RIVER only (`SOLVER3_ROHNE=drilling/monster`): on dev the
|
||
/// river solver bet trips and better less often than live (`FLUSS_WERT`) and lost with them (19.11.).
|
||
static RIVER_OHNE: AtomicU8 = AtomicU8::new(0);
|
||
/// The same for the multiway FLOP and TURN (`SOLVER3_FOHNE`, `SOLVER3_TOHNE`; owner order 19.11.: no
|
||
/// raise->check with trips/monsters as on the river). Default 0.
|
||
static FLOP_OHNE: AtomicU8 = AtomicU8::new(0);
|
||
static TURN_OHNE: AtomicU8 = AtomicU8::new(0);
|
||
/// `SOLVER3_FSPERRE=1`: on the multiway flop facing a bet of at most the pot, a solver fold with top pair or
|
||
/// better goes to the heuristic (owner order 19.11., the overfold of 17.11.). Default off.
|
||
static FSPERRE: AtomicBool = AtomicBool::new(false);
|
||
/// `SOLVER3_ALLE=1`: every multiway spot. 5+-handed spots too (at most `MAX_AKTIV` villains decide, the others are
|
||
/// a pooled field that checks and calls every bet, hands sampled and in the showdown), and a live player without a
|
||
/// recorded act counts as folded (`follow_nachsicht`). Default off: those spots stay with the heuristic.
|
||
static ALLE: AtomicBool = AtomicBool::new(false);
|
||
/// `SOLVER3_FORM=1`: the solver's own row is shaped before the draw, so that no exclusion has to hand a class to the
|
||
/// heuristic (owner order 19.11.): (a) trips or better never check when a bet is possible (the mass goes to the bets),
|
||
/// (b) a pair, top pair or overpair facing a bet never raises (the mass goes to the call), (c) with `SOLVER3_FSPERRE`
|
||
/// the top-pair flop fold becomes a call. The answer stays the solver's (reason `solver-kern ... | form`). Default off.
|
||
static FORM: AtomicBool = AtomicBool::new(false);
|
||
|
||
/// `SOLVER3_POOL=<w>` (0 < w <= 1): the villains of the multiway solvers answer a bet like the measured pool instead of
|
||
/// like equilibrium players (weight `w`, the heads-up core's node lock). Cause of the hand rules `SOLVER3_FORM` and
|
||
/// `SOLVER3_FSPERRE` (20.11.): a CFR villain folds every hand that loses to hero's bet range and never pays off with a
|
||
/// worse hand, so thin value (trips, an overpair) is worth nothing against it and checking wins; the heads-up core had
|
||
/// the pool's fold curve all along (`wett_kurve`), the multiway solvers did not. Stored in thousandths, default 0 = off.
|
||
static POOL: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
|
||
|
||
pub fn set_pool(w: f64) {
|
||
POOL.store((w.clamp(0.0, 1.0) * 1000.0).round() as u32, Ordering::Relaxed);
|
||
}
|
||
|
||
pub(crate) fn pool_w() -> f64 {
|
||
POOL.load(Ordering::Relaxed) as f64 / 1000.0
|
||
}
|
||
|
||
/// `SOLVER3_LINIE=1`: the villains' acts already played on the observed line are fixed (the played act with probability 1).
|
||
/// Their ranges are the range model's of that line (the act is in them), but the tree let the act happen a second time by
|
||
/// the CFR strategy: a bet was weighted by how often CFR bets the hand (the range squared) and hero's node was reached in a
|
||
/// fraction of the iterations, with a row learned from a few noisy samples (the same double count the heads-up core fixed
|
||
/// with `linie=modell`). Default off.
|
||
static LINIE: AtomicBool = AtomicBool::new(false);
|
||
|
||
pub fn set_linie(on: bool) {
|
||
LINIE.store(on, Ordering::Relaxed);
|
||
}
|
||
|
||
pub(crate) fn linie() -> bool {
|
||
LINIE.load(Ordering::Relaxed)
|
||
}
|
||
|
||
/// The locks of the played line: at each node of `pfad` of a player other than `me`, every hand plays the act taken.
|
||
/// `acts(node)` = the node's act count, `hands[p]` = player `p`'s combos.
|
||
pub(crate) fn linie_sperren(pfad: &[(usize, usize)], me: usize, spieler: &dyn Fn(usize) -> Option<(usize, usize)>, hands: &[usize]) -> Vec<(usize, Vec<f64>)> {
|
||
pfad.iter()
|
||
.filter_map(|&(node, k)| {
|
||
let (p, a) = spieler(node)?;
|
||
if p == me || a < 2 {
|
||
return None;
|
||
}
|
||
let mut rows = vec![0.0; hands[p] * a];
|
||
for h in 0..hands[p] {
|
||
rows[h * a + k] = 1.0;
|
||
}
|
||
Some((node, rows))
|
||
})
|
||
.collect()
|
||
}
|
||
|
||
/// The pool's answer of villain `p` (index in the acting order) at a node facing a bet: fold the weakest `fold` share of
|
||
/// his range (soft edge), raise the strongest `raise_pool` share, call the rest. `q` = each hand's rank in his range.
|
||
/// `ratio` = the last bet or raise over the pot before it, `allin_ab` = the ratio at which a bet is all-in.
|
||
fn pool_zeile(spot: &Spot, who: &Villain, acts: &[Act], q: &[f64], ratio: f64, allin_ab: f64, strasse: Street, linie: Option<usize>) -> Option<Vec<f64>> {
|
||
let f = match linie {
|
||
None => crate::exploit::wett_kurve::pool_fold(spot, strasse, ratio, allin_ab, who.profile.as_ref())?,
|
||
Some(l) => crate::exploit::wett_kurve::pool_fold_linie(strasse, l, ratio, allin_ab, who.profile.as_ref())?,
|
||
};
|
||
let allin = ratio >= allin_ab - 1e-9;
|
||
let r = if allin { 0.0 } else { crate::engine::solver_kern::raise_pool(ratio) };
|
||
let fold_i = acts.iter().position(|a| *a == Act::Fold)?;
|
||
let call_i = acts.iter().position(|a| *a == Act::Call)?;
|
||
let raise_i = acts.iter().enumerate().filter_map(|(i, a)| if let Act::Raise(x) = a { Some((i, *x)) } else { None }).min_by(|a, b| a.1.total_cmp(&b.1)).map(|x| x.0);
|
||
let mut rows = Vec::with_capacity(q.len() * acts.len());
|
||
for &qi in q {
|
||
let mut row = vec![0.0; acts.len()];
|
||
let pf = crate::engine::solver_kern::rampe(qi, f, 0.08, true);
|
||
let pr = if raise_i.is_some() { crate::engine::solver_kern::rampe(qi, r, 0.04, false) * (1.0 - pf) } else { 0.0 };
|
||
row[fold_i] = pf;
|
||
if let Some(i) = raise_i {
|
||
row[i] = pr;
|
||
}
|
||
row[call_i] = (1.0 - pf - pr).max(0.0);
|
||
rows.extend(row);
|
||
}
|
||
Some(rows)
|
||
}
|
||
|
||
/// `SOLVER3_OFFEN=<w>` (0 < w <= 1): the villains of the multiway solvers play an OPEN node (nobody has bet, they may bet) like the
|
||
/// measured pool (the `BETTOR` table by board percentile, as the heads-up core's open nodes) instead of like equilibrium
|
||
/// players. Cause of the checked-back value hands (replay 19.11.): the tree locked every villain's answer to hero's bet to
|
||
/// the pool but left what he does after hero CHECKS to CFR; a CFR villain bets into a check with bluffs and thin value at
|
||
/// equilibrium frequency, hero's check collected from them and beat every bet (top two pair, a straight: check 0.8 to 1.0),
|
||
/// while the NL2 pool rarely bluffs. Thousandths, default 0 = off.
|
||
static OFFEN: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
|
||
|
||
pub fn set_offen(w: f64) {
|
||
OFFEN.store((w.clamp(0.0, 1.0) * 1000.0).round() as u32, Ordering::Relaxed);
|
||
}
|
||
|
||
pub(crate) fn offen_w() -> f64 {
|
||
OFFEN.load(Ordering::Relaxed) as f64 / 1000.0
|
||
}
|
||
|
||
/// What `pool_sperren` needs of a node: the actor, its acts and its kids, or a deal (the kids are the slots of the next
|
||
/// street's card), or the end.
|
||
pub(crate) enum KnotenSicht<'a> {
|
||
Dec { player: usize, acts: &'a [Act], kids: &'a [usize] },
|
||
Deal { kids: &'a [usize] },
|
||
Ende,
|
||
}
|
||
|
||
/// `SOLVER3_TIEF=1`: the pool locks (`SOLVER3_POOL`, `SOLVER3_OFFEN`) also hold on the streets AFTER the first one (the river of
|
||
/// the turn game, the turn of the flop game), at every card slot. Cause of the second half of the checked-back value hands
|
||
/// (replay 19.11.): the villains' answers on the first street were the pool's, but on every later street they were CFR players
|
||
/// again, who fold exactly the hands that lose to hero's betting range there and never pay off with a worse one: a bet on the
|
||
/// turn bought nothing on the river, checking (hiding the range) beat every bet. Default off.
|
||
static TIEF: AtomicBool = AtomicBool::new(false);
|
||
|
||
pub fn set_tief(on: bool) {
|
||
TIEF.store(on, Ordering::Relaxed);
|
||
}
|
||
|
||
pub(crate) fn tief() -> bool {
|
||
TIEF.load(Ordering::Relaxed)
|
||
}
|
||
|
||
/// One walk state of `pool_sperren`.
|
||
#[derive(Clone, Copy)]
|
||
struct Gang {
|
||
at: usize,
|
||
/// Contributions over the whole game.
|
||
c: [f64; 12],
|
||
/// The last bet or raise of the street: its increment, the pot before it, the level before it, whether it was a raise.
|
||
incr: f64,
|
||
before: f64,
|
||
prev_top: f64,
|
||
geraist: bool,
|
||
/// Every player's contribution at the start of this street, the street (0 = the one decided) and its card slot.
|
||
level: f64,
|
||
st: usize,
|
||
slot: usize,
|
||
/// Street 0: the last player to bet or raise (`pool_fold`'s line of the next street) and all who did.
|
||
letzter: Option<usize>,
|
||
aggr: u32,
|
||
}
|
||
|
||
/// The nodes of the first betting round at which a villain faces a bet (index, pool rows) and, with `offen`, the nodes at which
|
||
/// he may bet into a street nobody has bet yet (index, `BETTOR` rows); with `karten` (the slot cards of the next street) also
|
||
/// the same nodes of the next street at every slot. `knoten(i)` shows node `i`;
|
||
/// `hands[p]` = player `p`'s combos (masks), `pot` the pot before the street, `cap` the common cap, `passive` the pooled
|
||
/// players (never decide). The walk follows the tree from the root keeping the street's contributions.
|
||
#[allow(clippy::too_many_arguments)]
|
||
pub(crate) fn pool_sperren<'a>(
|
||
spot: &Spot,
|
||
order: &[u8],
|
||
me: usize,
|
||
passive: u32,
|
||
masks: &[&[u64]],
|
||
board: u64,
|
||
pot: f64,
|
||
cap: f64,
|
||
offen: bool,
|
||
karten: Option<&[u64]>,
|
||
knoten: &dyn Fn(usize) -> KnotenSicht<'a>,
|
||
) -> (Vec<(usize, std::sync::Arc<Vec<f64>>)>, Vec<(usize, std::sync::Arc<Vec<f64>>)>, std::collections::HashMap<usize, f64>) {
|
||
use std::collections::HashMap;
|
||
use std::sync::Arc;
|
||
let mut ranks: HashMap<(usize, usize), Vec<f64>> = HashMap::new();
|
||
let mut brett_pct: HashMap<(usize, usize), Vec<f64>> = HashMap::new();
|
||
// The board of a node: the cards out now, plus (on a later street) the slot's card (a combo that holds that card is never
|
||
// dealt in that slot; its rank there is not used).
|
||
let brett_von = |st: usize, slot: usize| -> u64 { if st == 0 { board } else { board | karten.map_or(0, |k| k[slot.min(k.len().saturating_sub(1))]) } };
|
||
let mut gecacht: HashMap<(u8, usize, usize, u64), Arc<Vec<f64>>> = HashMap::new();
|
||
let hash = |zahlen: &[u64]| -> u64 { zahlen.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, z| (h ^ z).wrapping_mul(0x0100_0000_01b3).rotate_left(23)) };
|
||
if order.len() > 12 {
|
||
return (Vec::new(), Vec::new(), HashMap::new());
|
||
}
|
||
// `STUETZUNG`: Beobachtungen hinter der Zeile je gesperrtem Knoten (leer ohne den Schalter oder ohne Zaehlung).
|
||
let mut ns: HashMap<usize, f64> = HashMap::new();
|
||
let stuetz = crate::engine::solver_kern::stuetzung().is_some();
|
||
let mut out = Vec::new();
|
||
let mut frei = Vec::new();
|
||
let naechste = match spot.street {
|
||
Street::Flop => Street::Turn,
|
||
_ => Street::River,
|
||
};
|
||
let mut stack = vec![Gang { at: 0, c: [0.0; 12], incr: 0.0, before: pot, prev_top: 0.0, geraist: false, level: 0.0, st: 0, slot: 0, letzter: None, aggr: 0 }];
|
||
while let Some(g) = stack.pop() {
|
||
let (player, acts, kids) = match knoten(g.at) {
|
||
KnotenSicht::Dec { player, acts, kids } => (player, acts, kids),
|
||
KnotenSicht::Deal { kids } => {
|
||
if karten.is_some_and(|k| !k.is_empty()) {
|
||
let top = g.c.iter().copied().fold(0.0, f64::max);
|
||
for (j, k) in kids.iter().enumerate() {
|
||
stack.push(Gang { at: *k, c: g.c, incr: 0.0, before: pot + g.c.iter().sum::<f64>(), prev_top: top, geraist: false, level: top, st: g.st + 1, slot: j, letzter: g.letzter, aggr: g.aggr });
|
||
}
|
||
}
|
||
continue;
|
||
}
|
||
KnotenSicht::Ende => continue,
|
||
};
|
||
let top = g.c.iter().copied().fold(0.0, f64::max);
|
||
let strasse = if g.st == 0 { spot.street } else { naechste };
|
||
let live = player != me && passive & (1 << player) == 0;
|
||
if live && (offen && !acts.contains(&Act::Fold) && g.incr == 0.0 && acts.iter().any(|a| matches!(a, Act::Bet(_))) || acts.contains(&Act::Fold) && g.incr > 0.0 && !g.geraist) {
|
||
if let Some(who) = spot.live_villains().find(|v| v.seat == order[player]) {
|
||
let b = brett_von(g.st, g.slot);
|
||
if acts.contains(&Act::Fold) {
|
||
let r = ranks.entry((player, g.slot + g.st * 64)).or_insert_with(|| crate::engine::river_spieler::percentiles(masks[player], &vec![1.0; masks[player].len()], b));
|
||
let allin_ab = (cap - g.prev_top) / g.before.max(1e-9);
|
||
let ratio = g.incr / g.before.max(1e-9);
|
||
let linie = if g.st == 0 { None } else if g.letzter == Some(me) { Some(0) } else if g.letzter.is_some() { Some(3) } else { Some(1) };
|
||
let schl = (0u8, player, g.slot + g.st * 64, hash(&[ratio.to_bits(), allin_ab.to_bits(), linie.map_or(9, |l| l as u64), acts.len() as u64]));
|
||
let rows = match gecacht.get(&schl) {
|
||
Some(x) => Some(x.clone()),
|
||
None => pool_zeile(spot, who, acts, r, ratio, allin_ab, strasse, linie).map(|v| {
|
||
let a = Arc::new(v);
|
||
gecacht.insert(schl, a.clone());
|
||
a
|
||
}),
|
||
};
|
||
if let Some(rows) = rows {
|
||
if stuetz {
|
||
let n = match linie {
|
||
None => crate::exploit::wett_kurve::pool_fold_n(spot, strasse, ratio, allin_ab),
|
||
Some(l) => crate::exploit::wett_kurve::pool_fold_linie_n(strasse, l, ratio, allin_ab),
|
||
};
|
||
ns.extend(n.map(|n| (g.at, n)));
|
||
}
|
||
out.push((g.at, rows));
|
||
}
|
||
} else {
|
||
let pfa = spot.history.iter().rev().find(|r| r.street == Street::Preflop && r.action.is_aggressive()).is_some_and(|r| r.seat == who.seat);
|
||
let before = match g.st {
|
||
0 => match spot.street {
|
||
Street::Turn => spot.history.iter().any(|r| r.seat == who.seat && r.street == Street::Flop && r.action.is_aggressive()),
|
||
Street::River => spot.history.iter().any(|r| r.seat == who.seat && r.street == Street::Turn && r.action.is_aggressive()),
|
||
_ => false,
|
||
},
|
||
_ => g.aggr & (1 << player) != 0,
|
||
};
|
||
let pot_now = pot + g.c.iter().sum::<f64>();
|
||
let pct = brett_pct.entry((player, g.slot + g.st * 64)).or_insert_with(|| crate::engine::solver_kern::brett_perzentil(masks[player], b));
|
||
let cap_str = cap - g.level;
|
||
let mut schl = vec![pot_now.to_bits(), cap_str.to_bits(), pfa as u64, before as u64];
|
||
schl.extend(acts.iter().map(|a| match a {
|
||
Act::Bet(x) => x.to_bits(),
|
||
_ => 0,
|
||
}));
|
||
let schl = (1u8, player, g.slot + g.st * 64, hash(&schl));
|
||
let rows = match gecacht.get(&schl) {
|
||
Some(x) => Some(x.clone()),
|
||
None => crate::engine::solver_kern::offen_zeile(strasse, pfa, before, pct, acts, pot_now, cap_str).map(|v| {
|
||
let a = Arc::new(v);
|
||
gecacht.insert(schl, a.clone());
|
||
a
|
||
}),
|
||
};
|
||
if let Some(rows) = rows {
|
||
if stuetz {
|
||
ns.extend(crate::engine::solver_kern::offen_n(strasse, pfa, before, pct).map(|n| (g.at, n)));
|
||
}
|
||
frei.push((g.at, rows));
|
||
}
|
||
}
|
||
}
|
||
}
|
||
for (a, k) in acts.iter().zip(kids) {
|
||
let mut t = Gang { at: *k, c: g.c, incr: g.incr, before: g.before, prev_top: g.prev_top, geraist: g.geraist, level: g.level, st: g.st, slot: g.slot, letzter: g.letzter, aggr: g.aggr };
|
||
match a {
|
||
Act::Fold | Act::Check => {}
|
||
Act::Call => t.c[player] = top,
|
||
Act::Bet(x) | Act::Raise(x) => {
|
||
let total = g.level + *x;
|
||
t.incr = total - top;
|
||
t.before = pot + g.c.iter().sum::<f64>();
|
||
t.prev_top = top;
|
||
t.geraist = matches!(a, Act::Raise(_));
|
||
t.c[player] = total;
|
||
if g.st == 0 {
|
||
t.letzter = Some(player);
|
||
t.aggr |= 1 << player;
|
||
}
|
||
}
|
||
}
|
||
stack.push(t);
|
||
}
|
||
}
|
||
(out, frei, ns)
|
||
}
|
||
|
||
/// The first street's menu; under `SOLVER3_ALLE` it allows as many raises as the observed line holds (the tree must
|
||
/// contain the line), else as given.
|
||
pub(crate) fn menu_fuer(line: &[(usize, Act)], mut menu: Menu3) -> Menu3 {
|
||
if alle() {
|
||
let raises = line.iter().filter(|(_, a)| matches!(a, Act::Raise(_))).count() as u8;
|
||
menu.max_raises = menu.max_raises.max(raises);
|
||
}
|
||
menu
|
||
}
|
||
|
||
pub fn set_form(on: bool) {
|
||
FORM.store(on, Ordering::Relaxed);
|
||
}
|
||
|
||
/// Shape the row of hero's node under `SOLVER3_FORM` (see there); returns whether it changed.
|
||
pub(crate) fn form_row(raw: &Spot, acts: &[Act], row: &mut [f64]) -> bool {
|
||
if !FORM.load(Ordering::Relaxed) || raw.hero_cards.len() != 2 || row.len() != acts.len() {
|
||
return false;
|
||
}
|
||
let k = crate::hand::klasse::klasse(&raw.hero_cards, &raw.board);
|
||
let facing = raw.to_call > 0.0;
|
||
let mut changed = false;
|
||
let mut moven = |row: &mut [f64], von: &dyn Fn(&Act) -> bool, nach: &dyn Fn(&Act) -> bool| {
|
||
let m: f64 = acts.iter().zip(row.iter()).filter(|(a, _)| von(a)).map(|(_, p)| *p).sum();
|
||
let ziele: Vec<usize> = (0..acts.len()).filter(|i| nach(&acts[*i])).collect();
|
||
if m <= 0.0 || ziele.is_empty() {
|
||
return;
|
||
}
|
||
let basis: f64 = ziele.iter().map(|i| row[*i]).sum();
|
||
for (i, a) in acts.iter().enumerate() {
|
||
if von(a) {
|
||
row[i] = 0.0;
|
||
}
|
||
}
|
||
for i in &ziele {
|
||
row[*i] += if basis > 0.0 { m * row[*i] / basis } else { m / ziele.len() as f64 };
|
||
}
|
||
changed = true;
|
||
};
|
||
if !facing && k >= 6 {
|
||
moven(row, &|a| *a == Act::Check, &|a| matches!(a, Act::Bet(_)));
|
||
}
|
||
if facing && (2..=4).contains(&k) {
|
||
moven(row, &|a| matches!(a, Act::Raise(_)), &|a| *a == Act::Call);
|
||
}
|
||
if fsperre_greift(raw) {
|
||
moven(row, &|a| *a == Act::Fold, &|a| *a == Act::Call);
|
||
}
|
||
changed
|
||
}
|
||
/// Most deciding villains of one solve (4 players: the largest game that fits the time budget).
|
||
pub const MAX_AKTIV: usize = 3;
|
||
|
||
pub fn set_alle(on: bool) {
|
||
ALLE.store(on, Ordering::Relaxed);
|
||
}
|
||
|
||
pub(crate) fn alle() -> bool {
|
||
ALLE.load(Ordering::Relaxed)
|
||
}
|
||
|
||
/// Bit mask over `order` (index) of the villains who only check or call: none up to `MAX_AKTIV` villains; with
|
||
/// more, the villains with the most aggressive line on this street decide (a bet counts before a call, a call
|
||
/// before a check, then acting order) and the rest are the field. `None` for 5+ players without `SOLVER3_ALLE`.
|
||
pub(crate) fn passiv_maske(spot: &Spot, order: &[u8]) -> Option<u32> {
|
||
let n = order.len();
|
||
if n <= MAX_AKTIV + 1 {
|
||
return Some(0);
|
||
}
|
||
if !alle() {
|
||
return None;
|
||
}
|
||
let punkte = |seat: u8| -> u32 {
|
||
spot.history
|
||
.iter()
|
||
.filter(|r| r.street == spot.street && r.seat == seat)
|
||
.map(|r| match r.action {
|
||
crate::game::SeenAction::Bet | crate::game::SeenAction::Raise | crate::game::SeenAction::AllIn => 3,
|
||
crate::game::SeenAction::Call => 2,
|
||
_ => 0,
|
||
})
|
||
.max()
|
||
.unwrap_or(0)
|
||
};
|
||
let mut rang: Vec<usize> = (0..n).filter(|i| order[*i] != spot.hero_seat).collect();
|
||
rang.sort_by_key(|i| std::cmp::Reverse(punkte(order[*i])));
|
||
Some(rang[MAX_AKTIV..].iter().fold(0u32, |m, i| m | (1 << i)))
|
||
}
|
||
|
||
// Why the last multiway call on this thread left the spot to the heuristic (`weg`); read only by the
|
||
// diagnosis tool `kern_grund`, never by a decision. Shared by flop/turn and river.
|
||
thread_local! {
|
||
static GRUND: std::cell::Cell<Option<&'static str>> = const { std::cell::Cell::new(None) };
|
||
}
|
||
|
||
pub(crate) fn weg<T>(g: &'static str) -> Option<T> {
|
||
GRUND.with(|x| x.set(Some(g)));
|
||
None
|
||
}
|
||
|
||
/// Take the recorded reason (and clear it).
|
||
pub fn grund_nehmen() -> Option<&'static str> {
|
||
GRUND.with(|x| x.take())
|
||
}
|
||
|
||
pub fn set_lage(nur_offen: u8, ohne: u8) {
|
||
NUR_OFFEN.store(nur_offen, Ordering::Relaxed);
|
||
OHNE.store(ohne, Ordering::Relaxed);
|
||
}
|
||
|
||
pub fn set_river_ohne(ohne: u8) {
|
||
RIVER_OHNE.store(ohne, Ordering::Relaxed);
|
||
}
|
||
|
||
/// Per-street classes for the flop and turn (bits as `set_river_ohne`).
|
||
pub fn set_strassen_ohne(flop: u8, turn: u8) {
|
||
FLOP_OHNE.store(flop, Ordering::Relaxed);
|
||
TURN_OHNE.store(turn, Ordering::Relaxed);
|
||
}
|
||
|
||
pub fn set_fsperre(on: bool) {
|
||
FSPERRE.store(on, Ordering::Relaxed);
|
||
}
|
||
|
||
fn klassen_env(key: &str) -> u8 {
|
||
ohne_bits(&std::env::var(key).unwrap_or_default()).unwrap_or_else(|| panic!("{key}: unknown hand class"))
|
||
}
|
||
|
||
/// `SOLVER3_ROHNE` (class names joined by `/`; an unknown name panics).
|
||
pub fn river_ohne_from_env() -> u8 {
|
||
klassen_env("SOLVER3_ROHNE")
|
||
}
|
||
|
||
/// All per-street exclusions and the flop fold lock from the environment (`SOLVER3_FOHNE`, `SOLVER3_TOHNE`,
|
||
/// `SOLVER3_ROHNE`, `SOLVER3_FSPERRE`).
|
||
pub fn ohne_from_env() {
|
||
set_river_ohne(river_ohne_from_env());
|
||
set_strassen_ohne(klassen_env("SOLVER3_FOHNE"), klassen_env("SOLVER3_TOHNE"));
|
||
set_fsperre(std::env::var("SOLVER3_FSPERRE").as_deref() == Ok("1"));
|
||
set_alle(std::env::var("SOLVER3_ALLE").as_deref() == Ok("1"));
|
||
set_form(std::env::var("SOLVER3_FORM").as_deref() == Ok("1"));
|
||
set_linie(std::env::var("SOLVER3_LINIE").as_deref() == Ok("1"));
|
||
crate::cfr::multi3::set_zufall(std::env::var("SOLVER3_KARTE").as_deref() == Ok("zufall"));
|
||
set_tief(std::env::var("SOLVER3_TIEF").as_deref() == Ok("1"));
|
||
set_offen(std::env::var("SOLVER3_OFFEN").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(0.0));
|
||
set_pool(std::env::var("SOLVER3_POOL").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(0.0));
|
||
}
|
||
|
||
/// `(nur_offen, ohne)` from `SOLVER_FLOP3` / `SOLVER_TURN3` / `SOLVER_RIVER3` = `offen` and
|
||
/// `SOLVER3_OHNE` (class names joined by `/`; an unknown name panics, a typo must not pass silently).
|
||
pub fn lage_from_env() -> (u8, u8) {
|
||
let mut nur = 0u8;
|
||
for (bit, key) in ["SOLVER_FLOP3", "SOLVER_TURN3", "SOLVER_RIVER3"].iter().enumerate() {
|
||
if std::env::var(key).as_deref() == Ok("offen") {
|
||
nur |= 1 << bit;
|
||
}
|
||
}
|
||
(nur, ohne_bits(&std::env::var("SOLVER3_OHNE").unwrap_or_default()).expect("SOLVER3_OHNE: unknown hand class"))
|
||
}
|
||
|
||
/// Class bits of `nichts/zug`; `None` for an unknown name.
|
||
pub fn ohne_bits(x: &str) -> Option<u8> {
|
||
let mut m = 0u8;
|
||
for k in x.split('/').filter(|k| !k.is_empty()) {
|
||
m |= 1 << crate::hand::klasse::KLASSEN.iter().position(|n| *n == k)?;
|
||
}
|
||
Some(m)
|
||
}
|
||
|
||
/// Own CPU cap of one multiway solve (turn, flop and river), `SOLVER3_MS` (read once); `default` without it.
|
||
/// Stage 4: `STATION_POSTFLOP=schmal` decides a spot against a demoted station twice (station read and
|
||
/// blind), each pass with its own solve, so a 3-way decision cost two full solves (river 2 x 1.5 s).
|
||
pub fn cap_ms(default: f64) -> f64 {
|
||
static MS: std::sync::OnceLock<Option<f64>> = std::sync::OnceLock::new();
|
||
MS.get_or_init(|| std::env::var("SOLVER3_MS").ok().and_then(|v| v.trim().parse().ok()).filter(|x: &f64| *x > 0.0)).unwrap_or(default)
|
||
}
|
||
|
||
/// Whether a multiway solver may decide this spot under the stage-4 limits.
|
||
#[cfg(test)]
|
||
pub(crate) fn lage_passt(raw: &Spot) -> bool {
|
||
lage_grund(raw).is_none()
|
||
}
|
||
|
||
/// The stage-4 limit that keeps a multiway solver from this spot (`None`: it may decide).
|
||
pub(crate) fn lage_grund(raw: &Spot) -> Option<&'static str> {
|
||
let bit = match raw.street {
|
||
Street::Flop => 1,
|
||
Street::Turn => 2,
|
||
Street::River => 4,
|
||
_ => return None,
|
||
};
|
||
if NUR_OFFEN.load(Ordering::Relaxed) & bit != 0 && raw.to_call > 0.0 {
|
||
return Some("mw nur offen");
|
||
}
|
||
let strasse = match bit {
|
||
1 => FLOP_OHNE.load(Ordering::Relaxed),
|
||
2 => TURN_OHNE.load(Ordering::Relaxed),
|
||
_ => RIVER_OHNE.load(Ordering::Relaxed),
|
||
};
|
||
let ohne = OHNE.load(Ordering::Relaxed) | strasse;
|
||
(ohne != 0 && raw.hero_cards.len() == 2 && (3..=5).contains(&raw.board.len()) && ohne & (1 << crate::hand::klasse::klasse(&raw.hero_cards, &raw.board)) != 0).then_some("mw klasse ausgeschlossen")
|
||
}
|
||
|
||
pub fn set_turn3(on: bool) {
|
||
TURN3.store(on, Ordering::Relaxed);
|
||
}
|
||
|
||
pub fn set_flop3(on: bool) {
|
||
FLOP3.store(on, Ordering::Relaxed);
|
||
}
|
||
|
||
pub fn turn3() -> bool {
|
||
TURN3.load(Ordering::Relaxed)
|
||
}
|
||
|
||
pub fn flop3() -> bool {
|
||
FLOP3.load(Ordering::Relaxed)
|
||
}
|
||
|
||
fn on(key: &str) -> bool {
|
||
matches!(std::env::var(key).as_deref(), Ok("1") | Ok("an") | Ok("offen"))
|
||
}
|
||
|
||
/// `SOLVER_TURN3=1`, `SOLVER_FLOP3=1` (`offen`: on, open spots only, see `lage_from_env`).
|
||
pub fn from_env() -> (bool, bool) {
|
||
(on("SOLVER_TURN3"), on("SOLVER_FLOP3"))
|
||
}
|
||
|
||
/// Iteration cap (and the count under `SOLVER_ZEIT=fest`).
|
||
pub const ITERS: u32 = 12_000;
|
||
/// Fewest iterations a decision may rest on.
|
||
pub const MIN_ITERS: u32 = 1_000;
|
||
/// Fewest iterations of the smallest game under `SOLVER3_ALLE`.
|
||
pub const MIN_ITERS_KLEIN: u32 = 250;
|
||
/// Own caps of one solve, inside the street's decision total.
|
||
pub const TURN_BUDGET_MS: f64 = 1050.0;
|
||
pub const FLOP_BUDGET_MS: f64 = 1700.0;
|
||
/// Most combos per player.
|
||
pub const MAX_COMBOS: usize = 200;
|
||
pub const TURN_SLOTS: usize = 8;
|
||
pub const FLOP_SLOTS: usize = 6;
|
||
|
||
fn later() -> Menu3 {
|
||
Menu3 { fracs: vec![0.75], raise_mult: 3.0, max_raises: 1, allin: true }
|
||
}
|
||
|
||
pub struct SolvedM {
|
||
pub row: Vec<f64>,
|
||
pub acts: Vec<Act>,
|
||
pub iterations: u64,
|
||
pub millis: f64,
|
||
pub players: usize,
|
||
pub nodes: usize,
|
||
pub combos: Vec<usize>,
|
||
}
|
||
|
||
/// Solve this 3- or 4-handed turn or flop (gated spot) and return hero's average strategy at its node.
|
||
pub fn solve_multi3(spot: &Spot) -> Option<SolvedM> {
|
||
let villains = spot.live_villains().count();
|
||
let (cards, cap_ms, total, slots) = match spot.street {
|
||
Street::Turn => (4, TURN_BUDGET_MS, crate::engine::frist::TURN_MS, TURN_SLOTS),
|
||
Street::Flop => (3, FLOP_BUDGET_MS, crate::engine::frist::FLOP_MS, FLOP_SLOTS),
|
||
_ => return None,
|
||
};
|
||
let slots = std::env::var("KERN_SLOTS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(slots);
|
||
if spot.board.len() != cards || spot.hero_cards.len() != 2 || villains < 2 {
|
||
return weg("mw lage");
|
||
}
|
||
let budget = crate::engine::frist::budget_ms(self::cap_ms(cap_ms), total);
|
||
if budget <= 0.0 {
|
||
return weg("mw keine zeit");
|
||
}
|
||
let started = std::time::Instant::now();
|
||
let cpu0 = crate::engine::frist::thread_cpu_ms();
|
||
let order = acting_order(spot).or_else(|| weg("mw ohne blinds"))?;
|
||
let passiv = passiv_maske(spot, &order).or_else(|| weg("mw 5+ spieler"))?;
|
||
let (line, c) = street_line3(spot, &order, spot.street).or_else(|| weg("mw linie"))?;
|
||
let me = order.iter().position(|s| *s == spot.hero_seat)?;
|
||
let stack_of = |seat: u8| -> f64 {
|
||
if seat == spot.hero_seat {
|
||
spot.hero_stack
|
||
} else {
|
||
spot.live_villains().find(|v| v.seat == seat).map_or(0.0, |v| v.stack)
|
||
}
|
||
};
|
||
let cap = order.iter().enumerate().map(|(i, s)| stack_of(*s) + c[i]).fold(f64::INFINITY, f64::min);
|
||
let pot = spot.pot - c.iter().sum::<f64>();
|
||
let top = c.iter().copied().fold(0.0, f64::max);
|
||
// Under ALLE a call that puts a player all-in (cap = the bet) is a spot too (fold or call, the board runs out),
|
||
// and a short stack below the bet (a side pot) is lifted to it: the common cap stays a named approximation.
|
||
let cap = if alle() { cap.max(top) } else { cap };
|
||
if pot <= 0.0 || !cap.is_finite() || if alle() { false } else { cap <= top } {
|
||
return weg("mw stack");
|
||
}
|
||
let board = fast7::mask(&spot.board);
|
||
let hero_mask = fast7::mask(&spot.hero_cards);
|
||
// Under SOLVER3_ALLE a game too big for the budget (fewer than MIN_ITERS iterations projected) is solved again
|
||
// smaller: fewer combos per player, fewer slots (a coarser abstraction beats the heuristic).
|
||
let stufen: Vec<(usize, usize)> = if alle() { vec![(MAX_COMBOS, slots), (100, (slots / 2).max(2)), (50, 2)] } else { vec![(MAX_COMBOS, slots)] };
|
||
for (lvl, (maxc, sl)) in stufen.iter().copied().enumerate() {
|
||
let letzte = lvl + 1 == stufen.len();
|
||
let erzwungen: Option<usize> = std::env::var("KERN_STUFE").ok().and_then(|v| v.trim().parse().ok());
|
||
if erzwungen.is_some_and(|n| n != lvl) {
|
||
continue;
|
||
}
|
||
let mut hands = Vec::with_capacity(order.len());
|
||
for seat in &order {
|
||
let h = if *seat == spot.hero_seat {
|
||
model_hands(spot, &Villain { seat: *seat, stack: spot.hero_stack, folded: false, profile: None }, board, Some(hero_mask), maxc)
|
||
} else {
|
||
let v = spot.live_villains().find(|v| v.seat == *seat)?;
|
||
model_hands(spot, v, board, None, maxc)
|
||
};
|
||
hands.push(h.or_else(|| weg("mw range leer"))?);
|
||
}
|
||
let menus = [menu_fuer(&line, Menu3::standard()), later()];
|
||
let game = if linie() { GameM::build_linie(order.len(), pot, cap, &menus, sl, passiv, &line, me) } else { GameM::build_passiv(order.len(), pot, cap, &menus, sl, passiv) };
|
||
let at = if alle() { game.follow_nachsicht(&line, me) } else { game.follow(&line) }.or_else(|| weg("mw linie nicht im baum"))?;
|
||
let NodeM::Dec { player, acts, .. } = &game.nodes[at] else { return weg("mw knoten") };
|
||
if *player != me {
|
||
return weg("mw knoten");
|
||
}
|
||
let acts = acts.clone();
|
||
let nodes = game.nodes.len();
|
||
let combos: Vec<usize> = hands.iter().map(|h| h.masks.len()).collect();
|
||
let hero_index = hands[me].masks.iter().position(|m| *m == hero_mask)?;
|
||
let mut solver = SolverM::new(game, hands, board, spot.seed ^ 0x9e37_79b9_7f4a_7c15);
|
||
if pool_w() > 0.0 || offen_w() > 0.0 {
|
||
let masks: Vec<&[u64]> = (0..order.len()).map(|p| solver.masks(p)).collect();
|
||
let t_sperre = std::time::Instant::now();
|
||
let vertreter = solver.slot_vertreter();
|
||
let karten = if tief() { Some(&vertreter[..]) } else { None };
|
||
let (sperren, frei, ns) = pool_sperren(spot, &order, me, passiv, &masks, board, pot, cap, offen_w() > 0.0, karten, &|i| match &solver.game.nodes[i] {
|
||
NodeM::Dec { player, acts, kids, .. } => KnotenSicht::Dec { player: *player, acts, kids },
|
||
NodeM::Deal { kids } => KnotenSicht::Deal { kids },
|
||
_ => KnotenSicht::Ende,
|
||
});
|
||
if pool_w() > 0.0 {
|
||
for (n, rows) in sperren {
|
||
solver.lock_geteilt(n, rows, crate::engine::solver_kern::stuetzung_gewicht(pool_w(), ns.get(&n).copied()));
|
||
}
|
||
}
|
||
for (n, rows) in frei {
|
||
solver.lock_geteilt(n, rows, crate::engine::solver_kern::stuetzung_gewicht(offen_w(), ns.get(&n).copied()));
|
||
}
|
||
if std::env::var("KERN_REGRET").is_ok() {
|
||
eprintln!("sperren {:.1} ms, {} nodes", t_sperre.elapsed().as_secs_f64() * 1e3, solver.game.nodes.len());
|
||
}
|
||
}
|
||
if linie() {
|
||
let hands_n: Vec<usize> = (0..order.len()).map(|p| solver.masks(p).len()).collect();
|
||
if let Some(pfad) = solver.game.pfad_nachsicht(&line, me) {
|
||
let sperren = linie_sperren(&pfad, me, &|n| match &solver.game.nodes[n] {
|
||
NodeM::Dec { player, acts, .. } => Some((*player, acts.len())),
|
||
_ => None,
|
||
}, &hands_n);
|
||
for (n, rows) in sperren {
|
||
solver.lock(n, rows, 1.0);
|
||
}
|
||
}
|
||
}
|
||
let cpu_stufe = crate::engine::frist::thread_cpu_ms();
|
||
let mut done = 0u32;
|
||
let mut zu_gross = false;
|
||
let art = if spot.street == Street::Turn { crate::engine::frist::Art::MwTurn } else { crate::engine::frist::Art::MwFlop };
|
||
let min_iter = crate::engine::frist::iter_min(art, if alle() && letzte { MIN_ITERS_KLEIN } else { MIN_ITERS });
|
||
while done < crate::engine::frist::iter_cap(art, ITERS) {
|
||
solver.iterate();
|
||
done += 1;
|
||
let jetzt = crate::engine::frist::thread_cpu_ms();
|
||
if done == 30 && !letzte && erzwungen.is_none() && (jetzt - cpu_stufe) / 30.0 * MIN_ITERS as f64 > budget - (jetzt - cpu0) {
|
||
zu_gross = true;
|
||
break;
|
||
}
|
||
if done % 50 == 0 && jetzt - cpu0 > budget {
|
||
// Over the budget: enough iterations end the solve; too few hand the spot to a smaller game, the
|
||
// smallest one runs on to its minimum.
|
||
if done >= min_iter {
|
||
break;
|
||
}
|
||
if !letzte {
|
||
zu_gross = true;
|
||
break;
|
||
}
|
||
if !alle() {
|
||
break;
|
||
}
|
||
}
|
||
if crate::engine::frist::notbremse() {
|
||
break;
|
||
}
|
||
}
|
||
if zu_gross {
|
||
continue;
|
||
}
|
||
crate::engine::frist::iter_log(art, done as u64);
|
||
// The smallest game under ALLE may rest on fewer iterations: a coarse solve still beats the heuristic.
|
||
if done < min_iter {
|
||
return weg("mw zu wenig iterationen");
|
||
}
|
||
if std::env::var("KERN_REGRET").is_ok() {
|
||
eprintln!("regret chips {:?} hero_index {hero_index} combos {combos:?}", solver.regret_chips(at, hero_index));
|
||
let mut v: Vec<(u32, String)> = (0..solver.masks(me).len()).map(|h| (fast7::score(solver.masks(me)[h] | board), format!("{:?}", solver.row(at, h).iter().map(|x| (x * 100.0).round() / 100.0).collect::<Vec<_>>()))).collect();
|
||
v.sort();
|
||
for (sc, r) in v {
|
||
eprintln!(" score {sc} row {r}");
|
||
}
|
||
}
|
||
let row = solver.row(at, hero_index);
|
||
return Some(SolvedM { row, acts, iterations: solver.iterations(), millis: started.elapsed().as_secs_f64() * 1e3, players: order.len(), nodes, combos });
|
||
}
|
||
weg("mw zu wenig iterationen")
|
||
}
|
||
|
||
/// `SOLVER3_FSPERRE`: flop, a bet of at most the pot before it (`pot` includes the bet), top pair or better.
|
||
pub(crate) fn fsperre_greift(raw: &Spot) -> bool {
|
||
FSPERRE.load(Ordering::Relaxed)
|
||
&& raw.street == Street::Flop
|
||
&& raw.to_call > 0.0
|
||
&& raw.to_call <= raw.pot - raw.to_call + 1e-9
|
||
&& raw.hero_cards.len() == 2
|
||
&& crate::hand::klasse::klasse(&raw.hero_cards, &raw.board) >= 3
|
||
}
|
||
|
||
/// The live multiway turn/flop decision, or `None` and the heuristic keeps it.
|
||
pub fn multi3_decision(raw: &Spot) -> Option<Decision> {
|
||
let on = match raw.street {
|
||
Street::Turn => turn3(),
|
||
Street::Flop => flop3(),
|
||
_ => false,
|
||
};
|
||
if !on || raw.hero_cards.len() != 2 || raw.live_villains().count() < 2 {
|
||
// The river is the river solver's (it has noted its own reason).
|
||
return if matches!(raw.street, Street::Flop | Street::Turn) { weg("mw schalter aus") } else { None };
|
||
}
|
||
if let Some(g) = lage_grund(raw) {
|
||
return weg(g);
|
||
}
|
||
let gated = crate::engine::read_gate::gate_reads(raw);
|
||
let s = solve_multi3(&gated)?;
|
||
let (draw, _) = Rng::seeded(gated.seed).unit();
|
||
let mut acc = 0.0;
|
||
let mut pick = s.acts.len() - 1;
|
||
let mut row = s.row.clone();
|
||
let geformt = form_row(raw, &s.acts, &mut row);
|
||
for (k, p) in row.iter().enumerate() {
|
||
acc += p;
|
||
if draw < acc {
|
||
pick = k;
|
||
break;
|
||
}
|
||
}
|
||
let act = s.acts[pick];
|
||
if act == Act::Fold && fsperre_greift(raw) {
|
||
return weg("mw fold-sperre");
|
||
}
|
||
let p = row[pick];
|
||
let street = if gated.street == Street::Turn { "turn3" } else { "flop3" };
|
||
Some(Decision::new(
|
||
legal_choice(&gated, act),
|
||
p.clamp(0.0, 1.0),
|
||
format!(
|
||
"solver-kern solver {street} ({} players): {:?} combos, {} nodes, {} iters, {act:?} p {p:.2}, {:.0} ms{}",
|
||
s.players, s.combos, s.nodes, s.iterations, s.millis, if geformt { " | form" } else { "" }
|
||
),
|
||
))
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests;
|