Files
pokerfreak/src/sim/fluss2.rs
T

568 lines
20 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Fluss 2 (19.11.): the value of a heads-up postflop decision with every later street PLAYED, not looked up.
//!
//! The old flow measure (`messung/solver_kern/werk/turn_offen.py`, `drei.py`) priced the later streets with the
//! population's mean result per cell, over SHOWDOWN hands only. A line in which someone folds later never reaches the
//! showdown, so the cells were biased by the line itself: a bet with air that is called looked −6 to −16 bb worse than
//! it is (its later bluffs that win are missing), a check with trips +46 bb better. Both exclusions of the solver core
//! (air heads-up, trips/monsters multiway) came from that term.
//!
//! Here a spot is played to the end, many times:
//! - **Hero** decides every later node with the real core (`decide` + `enforce`, in-process, the switches of the
//! process environment, `engine::start::aus_umgebung`), exactly the live path.
//! - **Villain** acts by the measured NL2 strategy P(action | cell, node) of `ranges_echt` (IPW-corrected for the
//! showdown selection, built on the non-sealed players, calibrated on the sealed ones), population type `*`.
//! A node without an L row takes the A row (action shares, not hand-dependent); counted as `rueckfall`.
//! - **Villain's hand** is drawn from the `ranges_echt` range at the spot (default), or is the real hand (`echt`).
//! - **Cards**: the run-out is drawn at random; the villain hand, the run-out and the villain's action draws are fixed
//! per (spot, rollout) before the first decision, so two arms see the same cards (common random numbers).
//! - **Money**: hero's net from the spot in big blinds (fold = −what hero added since the spot), rake of the live rule
//! on the contested pot.
//!
//! Named approximations: villain bet sizes are the middle of each token class (k 1/3, m 0.6, g 1, u 1.5 pot), a raise
//! goes to 3x; villain's type is the population; heads-up only.
use crate::card::Card;
use crate::exploit::ranges_echt as re;
use crate::game::{ActionKind, ActionRecord, Choice, Decision, SeenAction, Spot, Street};
use crate::hand::fast7;
use crate::rake::{HandEnd, RakeRule};
use crate::rng::Rng;
/// Result of one rollout.
#[derive(Clone, Debug, Default)]
pub struct Lauf {
/// Hero's net from the spot, in big blinds.
pub netto: f64,
/// Hero's first decision (`FOLD`, `CHECK`, `CALL`, `RAISE <to>`).
pub erste: String,
/// Hero decisions in this rollout.
pub hero: u32,
/// Villain decisions taken from the A row (no hand-dependent L row at the node).
pub rueckfall: u32,
/// Villain decisions.
pub gegner: u32,
}
/// A spot prepared once for all rollouts: the decoded request and the villain's range as combos.
pub struct Vorlage {
pub spot: Spot,
vseat: u8,
key: re::Key,
/// Villain combos with weights (range draw), disjoint from board and hero.
kombos: Vec<([Card; 2], f64)>,
echt: Option<[Card; 2]>,
}
/// Why a spot cannot be played.
#[derive(Debug)]
pub enum Fehlt {
NichtHeadsUp,
KeinSchluessel,
KeineRange,
}
impl Vorlage {
/// `echt`: the villain's real hand, used instead of the range draw when given.
pub fn neu(spot: Spot, t: &re::Tabelle, echt: Option<[Card; 2]>) -> Result<Vorlage, Fehlt> {
if spot.live_villains().count() != 1 || spot.street == Street::Preflop || spot.hero_cards.len() != 2 {
return Err(Fehlt::NichtHeadsUp);
}
let v = spot.live_villains().next().unwrap().clone();
let auf_strasse = spot.history.iter().any(|r| r.street == spot.street);
let key = crate::engine::solver_kern::schluessel_bis(&spot, &v, spot.street, auf_strasse).ok_or(Fehlt::KeinSchluessel)?;
let mut kombos = Vec::new();
if echt.is_none() {
let (zeile, _) = t.range(&key).ok_or(Fehlt::KeineRange)?;
let tot = fast7::mask(&spot.board);
let held = fast7::mask(&spot.hero_cards);
let deck: Vec<Card> = crate::card::deck::full().into_iter().filter(|c| tot & fast7::bit(*c) == 0).collect();
let mut alle = Vec::new();
let mut anzahl = vec![0.0f64; zeile.werte.len()];
for i in 0..deck.len() {
for j in i + 1..deck.len() {
let h = [deck[i], deck[j]];
let z = re::zelle(&h, &spot.board).min(zeile.werte.len() - 1);
anzahl[z] += 1.0;
alle.push((h, z));
}
}
for (h, z) in alle {
if fast7::mask(&h) & held != 0 {
continue;
}
let w = zeile.werte[z] / anzahl[z].max(1.0);
if w > 0.0 {
kombos.push((h, w));
}
}
if kombos.is_empty() {
return Err(Fehlt::KeineRange);
}
}
Ok(Vorlage { vseat: v.seat, key, kombos, echt, spot })
}
}
const H: usize = 0;
const V: usize = 1;
struct Lage<'a> {
v: &'a Vorlage,
t: &'a re::Tabelle,
hand: [Vec<Card>; 2],
board: Vec<Card>,
rest: Vec<Card>,
street: Street,
stack: [f64; 2],
beitrag: [f64; 2],
pot: f64,
added: f64,
hoch: f64,
inc: f64,
acted: [bool; 2],
oop: usize,
key: re::Key,
history: Vec<ActionRecord>,
zufall: Rng,
lauf: Lauf,
schritt: u64,
}
enum Ende {
Weiter,
Fold(usize),
Showdown,
}
fn naechste(s: Street) -> Street {
match s {
Street::Flop => Street::Turn,
_ => Street::River,
}
}
impl Lage<'_> {
fn bb(&self) -> f64 {
self.v.spot.big_blind
}
fn rake(&self, pot: f64) -> f64 {
RakeRule::MICRO_BB.of_hand(pot / self.bb(), 2, HandEnd::FlopDealt) * self.bb()
}
fn seat(&self, wer: usize) -> u8 {
if wer == H {
self.v.spot.hero_seat
} else {
self.v.vseat
}
}
/// Put `bis` (street total) for `wer`; returns the record action and the ranges_echt token.
fn setzen(&mut self, wer: usize, bis: f64) {
let bis = bis.min(self.beitrag[wer] + self.stack[wer]).max(self.beitrag[wer]);
let add = bis - self.beitrag[wer];
let topf_vor = self.pot;
let allin = self.stack[wer] - add <= 1e-9;
let (tok, akt) = if bis <= self.hoch + 1e-9 {
('c', if allin { SeenAction::AllIn } else { SeenAction::Call })
} else if self.hoch <= 1e-9 {
(re::einsatz_token(add, topf_vor, allin), if allin { SeenAction::AllIn } else { SeenAction::Bet })
} else {
(if allin { 'j' } else { 'r' }, if allin { SeenAction::AllIn } else { SeenAction::Raise })
};
if bis > self.hoch + 1e-9 {
self.inc = (bis - self.hoch).max(self.inc);
self.hoch = bis;
self.acted = [false, false];
}
self.acted[wer] = true;
self.stack[wer] -= add;
self.beitrag[wer] = bis;
self.pot += add;
if wer == H {
self.added += add;
}
self.key.linie.push(tok);
self.history.push(ActionRecord { street: self.street, seat: self.seat(wer), action: akt, amount: Some(bis) });
}
fn checken(&mut self, wer: usize) {
self.acted[wer] = true;
self.key.linie.push('x');
self.history.push(ActionRecord { street: self.street, seat: self.seat(wer), action: SeenAction::Check, amount: None });
}
fn folden(&mut self, wer: usize) {
self.history.push(ActionRecord { street: self.street, seat: self.seat(wer), action: SeenAction::Fold, amount: None });
}
fn runde_zu(&self) -> bool {
self.acted[H] && self.acted[V] && (self.beitrag[H] - self.beitrag[V]).abs() <= 1e-9
|| (self.beitrag[H] - self.beitrag[V]).abs() <= 1e-9 && (self.stack[H] <= 1e-9 || self.stack[V] <= 1e-9) && (self.acted[H] || self.acted[V])
}
fn hero_spot(&self) -> Spot {
let s = &self.v.spot;
let to_call = (self.beitrag[V] - self.beitrag[H]).max(0.0).min(self.stack[H]);
let mut legal = Vec::new();
let kann_raise = self.stack[H] > to_call + 1e-9 && self.stack[V] > 1e-9;
if to_call > 1e-9 {
legal.extend([ActionKind::Fold, ActionKind::Call]);
} else {
legal.push(ActionKind::Check);
}
if kann_raise {
legal.push(ActionKind::Raise);
}
let max = self.beitrag[H] + self.stack[H];
let min = if self.hoch > 1e-9 { self.hoch + self.inc.max(self.bb()) } else { self.beitrag[H] + self.bb() };
let mut villains = s.villains.clone();
for v in villains.iter_mut() {
if v.seat == self.v.vseat {
v.stack = self.stack[V];
}
}
Spot {
board: self.board.clone(),
street: self.street,
pot: self.pot,
to_call,
hero_stack: self.stack[H],
min_raise_to: kann_raise.then_some(min.min(max)),
max_raise_to: kann_raise.then_some(max),
legal,
allowed_sizes: None,
villains,
seed: s.seed ^ self.schritt.wrapping_mul(0x9E37_79B9_7F4A_7C15),
history: self.history.clone(),
..s.clone()
}
}
fn hero_zug(&mut self) -> Ende {
// The first decision is the spot itself, unchanged (it must equal the batch answer of the same arm).
let spot = if self.schritt == 0 { self.v.spot.clone() } else { self.hero_spot() };
self.schritt += 1;
let d: Decision = match crate::guard::validate::check(spot.clone()) {
Ok(sp) => crate::guard::enforce::enforce(&sp, crate::engine::decide::decide(&sp)),
Err(_) => Decision::new(if spot.to_call > 0.0 { Choice::Fold } else { Choice::Check }, 0.0, "fluss2: ungueltig".to_string()),
};
self.lauf.hero += 1;
let text = match d.choice {
Choice::Raise { to } => format!("RAISE {:.4}", to),
c => format!("{c:?}").to_uppercase(),
};
if self.lauf.erste.is_empty() {
self.lauf.erste = text;
}
match d.choice {
Choice::Fold if spot.to_call > 1e-9 => {
self.folden(H);
Ende::Fold(H)
}
Choice::Raise { to } if spot.legal.contains(&ActionKind::Raise) => {
let to = to.clamp(spot.min_raise_to.unwrap_or(to), spot.max_raise_to.unwrap_or(to));
self.setzen(H, to);
Ende::Weiter
}
_ if spot.to_call > 1e-9 => {
self.setzen(H, self.beitrag[V]);
Ende::Weiter
}
_ => {
self.checken(H);
Ende::Weiter
}
}
}
fn gegner_zug(&mut self) -> Ende {
self.lauf.gegner += 1;
let zu_zahlen = (self.beitrag[H] - self.beitrag[V]).max(0.0);
let verf: &[char] = if zu_zahlen > 1e-9 {
if self.stack[V] > zu_zahlen + 1e-9 && self.stack[H] > 1e-9 {
&['f', 'c', 'r', 'j']
} else {
&['f', 'c']
}
} else if self.stack[V] > 1e-9 && self.stack[H] > 1e-9 {
&['x', 'k', 'm', 'g', 'u', 'j']
} else {
&['x']
};
let zelle = re::zelle(&self.hand[V], &self.board);
let passiv = if zu_zahlen > 1e-9 { 'f' } else { 'x' };
let mut p: Vec<f64> = Vec::with_capacity(verf.len());
let mut fehlt_passiv = false;
for a in verf {
match self.t.strategie(&self.key, *a) {
Some((z, _)) => p.push(z.werte.get(zelle).copied().unwrap_or(0.0).max(0.0)),
None => {
if *a == passiv {
fehlt_passiv = true;
}
p.push(0.0);
}
}
}
let summe: f64 = p.iter().sum();
if fehlt_passiv && summe < 1.0 {
let k = verf.iter().position(|a| *a == passiv).unwrap();
p[k] = 1.0 - summe;
}
if p.iter().sum::<f64>() <= 1e-9 {
self.lauf.rueckfall += 1;
p = vec![0.0; verf.len()];
if let Some((z, _)) = self.t.aktionen(&self.key) {
for (k, a) in verf.iter().enumerate() {
if let Some(i) = "xkmgujfcr".find(*a) {
p[k] = z.werte.get(i).copied().unwrap_or(0.0).max(0.0);
}
}
}
if p.iter().sum::<f64>() <= 1e-9 {
p[verf.iter().position(|a| *a == if zu_zahlen > 1e-9 { 'c' } else { 'x' }).unwrap_or(0)] = 1.0;
}
}
let summe: f64 = p.iter().sum();
let (u, z) = self.zufall.unit();
self.zufall = z;
let mut acc = 0.0;
let mut wahl = verf[verf.len() - 1];
for (k, a) in verf.iter().enumerate() {
acc += p[k] / summe;
if u < acc {
wahl = *a;
break;
}
}
let bb = self.bb();
let alles = self.beitrag[V] + self.stack[V];
match wahl {
'f' => {
self.folden(V);
Ende::Fold(V)
}
'x' => {
self.checken(V);
Ende::Weiter
}
'c' => {
self.setzen(V, self.beitrag[H]);
Ende::Weiter
}
'j' => {
self.setzen(V, alles);
Ende::Weiter
}
'r' => {
let bis = (3.0 * self.hoch).max(self.hoch + self.inc.max(bb));
self.setzen(V, bis);
Ende::Weiter
}
tok => {
let q = match tok {
'k' => 0.33,
'm' => 0.6,
'g' => 1.0,
_ => 1.5,
};
let bis = self.beitrag[V] + (q * self.pot).max(bb);
self.setzen(V, bis);
Ende::Weiter
}
}
}
fn neue_strasse(&mut self) {
self.street = naechste(self.street);
let k = self.rest.pop().expect("run-out");
self.board.push(k);
self.beitrag = [0.0, 0.0];
self.hoch = 0.0;
self.inc = 0.0;
self.acted = [false, false];
self.key.linie.push('/');
self.key.strasse = match self.street {
Street::Turn => 't',
_ => 'r',
};
self.key.textur = re::textur(&self.board);
}
fn abrechnen(&mut self, e: Ende) -> f64 {
match e {
Ende::Fold(H) => -self.added,
Ende::Fold(_) => {
let frei = (self.beitrag[H] - self.beitrag[V]).max(0.0);
let umkaempft = self.pot - frei;
umkaempft - self.rake(umkaempft) + frei - self.added
}
_ => {
while self.board.len() < 5 {
let k = self.rest.pop().expect("run-out");
self.board.push(k);
}
let b = fast7::mask(&self.board);
let sh = fast7::score(b | fast7::mask(&self.hand[H]));
let sv = fast7::score(b | fast7::mask(&self.hand[V]));
let netto_topf = self.pot - self.rake(self.pot);
let anteil = if sh > sv {
1.0
} else if sh == sv {
0.5
} else {
0.0
};
anteil * netto_topf - self.added
}
}
}
fn spielen(&mut self) -> f64 {
// Who is to act first: the spot is hero's decision.
let mut am_zug = H;
for _ in 0..40 {
let e = if am_zug == H { self.hero_zug() } else { self.gegner_zug() };
match e {
Ende::Weiter => {}
fertig => return self.abrechnen(fertig),
}
if self.runde_zu() {
if self.street == Street::River || self.stack[H] <= 1e-9 || self.stack[V] <= 1e-9 {
return self.abrechnen(Ende::Showdown);
}
self.neue_strasse();
am_zug = self.oop;
} else {
am_zug = 1 - am_zug;
}
}
self.abrechnen(Ende::Showdown)
}
}
/// Street contributions on the current street from the history (raise-to semantics), the highest level and the last
/// raise increment.
fn strassen_stand(spot: &Spot, vseat: u8) -> ([f64; 2], f64, f64) {
let mut b = [0.0f64; 2];
let (mut hoch, mut inc) = (0.0f64, 0.0f64);
for r in spot.history.iter().filter(|r| r.street == spot.street) {
let wer = if r.seat == spot.hero_seat {
H
} else if r.seat == vseat {
V
} else {
continue;
};
let neu = match r.action {
SeenAction::Check | SeenAction::Fold => b[wer],
SeenAction::Call => r.amount.unwrap_or(hoch).max(b[wer]),
_ => r.amount.unwrap_or(b[wer]).max(b[wer]),
};
if neu > hoch + 1e-9 {
inc = (neu - hoch).max(inc);
hoch = neu;
}
b[wer] = neu;
}
(b, hoch, inc)
}
/// One rollout of the spot, `nr` its index (the common random numbers).
pub fn lauf(v: &Vorlage, t: &re::Tabelle, nr: u64) -> Lauf {
let s = &v.spot;
let mut rng = Rng::seeded(s.seed ^ 0xF1u64.wrapping_mul(nr.wrapping_add(1)).wrapping_mul(0x2545_F491_4F6C_DD1D));
let vil: [Card; 2] = match v.echt {
Some(h) => h,
None => {
let summe: f64 = v.kombos.iter().map(|(_, w)| w).sum();
let (u, r) = rng.unit();
rng = r;
let mut acc = 0.0;
let mut wahl = v.kombos[v.kombos.len() - 1].0;
for (h, w) in &v.kombos {
acc += w / summe;
if u < acc {
wahl = *h;
break;
}
}
wahl
}
};
let tot = fast7::mask(&s.board) | fast7::mask(&s.hero_cards) | fast7::mask(&vil);
let mut deck: Vec<Card> = crate::card::deck::full().into_iter().filter(|c| tot & fast7::bit(*c) == 0).collect();
let mut rest = Vec::new();
for _ in s.board.len()..5 {
let (k, r) = rng.below(deck.len() as u64);
rng = r;
rest.push(deck.swap_remove(k as usize));
}
rest.reverse();
let (beitrag, hoch, inc) = strassen_stand(s, v.vseat);
let vstack = s.live_villains().next().map(|x| x.stack).unwrap_or(0.0);
let to_call = s.to_call;
let hero_oop = v.key.pos == 'i';
let acted = if to_call > 1e-9 { [false, true] } else if hero_oop { [false, false] } else { [false, true] };
let mut l = Lage {
v,
t,
hand: [s.hero_cards.clone(), vil.to_vec()],
board: s.board.clone(),
rest,
street: s.street,
stack: [s.hero_stack, vstack],
beitrag,
pot: s.pot,
added: 0.0,
hoch,
inc,
acted,
oop: if hero_oop { H } else { V },
key: v.key.clone(),
history: s.history.clone(),
zufall: rng,
lauf: Lauf::default(),
schritt: 0,
};
let netto = l.spielen() / s.big_blind;
Lauf { netto, ..l.lauf }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn strassen_stand_liest_raise_to() {
use crate::game::{Villain, SeenAction::*};
let rec = |street, seat, action, amount| ActionRecord { street, seat, action, amount };
let spot = Spot {
variant: crate::variant::Variant::Nlhe,
big_blind: 1.0,
seats: 6,
hero_seat: 1,
button_seat: Some(2),
hero_cards: Card::parse_list("Ah Kd").unwrap(),
board: Card::parse_list("2c 7d 9h").unwrap(),
street: Street::Flop,
pot: 13.0,
to_call: 6.0,
hero_stack: 90.0,
min_raise_to: None,
max_raise_to: None,
legal: vec![],
allowed_sizes: None,
villains: vec![Villain { seat: 2, stack: 85.0, folded: false, profile: None }],
seed: 1,
history: vec![rec(Street::Flop, 1, Bet, Some(2.0)), rec(Street::Flop, 2, Raise, Some(8.0))],
};
let (b, hoch, inc) = strassen_stand(&spot, 2);
assert_eq!(b, [2.0, 8.0]);
assert_eq!(hoch, 8.0);
assert_eq!(inc, 6.0);
}
}