Files
pokerfreak/src/engine/postflop.rs
T
mmintelandClaude Opus 5.5 031c550014 Pruefstand: Vetos in der Begruendung, POSTERIOR auf echten Spots, Kandidaten fluss/ENTHALTUNG, Werkzeuge tor_echt + kippliste
- vermerk.rs: jede Regel, die eine Aktion nach der Grundrechnung ueberstimmt, haengt sich an reason;
  bitgleich auf 48 672 Anfragen (0 Abweichungen ausser reason)
- POSTERIOR=...,fluss (S2 nur am River): echte NL2-Spots holdout +53 276 bb eq; Tor wegen Pflichtfall offen
- ENTHALTUNG=passiv: gehaltener Raise im Fehler -> beste passive Linie statt ABSTAIN (Laeufer foldete +EV-Calls)
- livefaelle: Kommawerte (POSTERIOR=bluff,schutz,beleg) wurden abgeschnitten
- Alle neuen Schalter aus = Live-Stand bitgleich; nichts live geschaltet

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 18:00:02 +01:00

335 lines
15 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.
use super::bluff::RaiseKind;
use super::called::Called;
use super::effective::{effective, Effective};
use super::options::{action_evs, passive_ev, scored, Scored};
use super::passive::cheapest_continue;
use super::read_label::describe;
use super::uncertainty::abstain_confidence;
use crate::equity::estimate::Estimate;
use crate::exploit::thresholds::Thresholds;
use crate::game::{ActionKind, Choice, Decision, Spot};
use crate::odds::{break_even::break_even, ev};
use crate::read::hand_read::HandRead;
use crate::rng::Rng;
fn label(choice: Choice, kind: Option<RaiseKind>) -> String {
match (choice, kind) {
(Choice::Raise { to }, Some(RaiseKind::Semibluff)) => format!("semibluff raise to {to:.2}"),
(Choice::Raise { to }, Some(RaiseKind::Bluff)) => format!("bluff raise to {to:.2}"),
(Choice::Raise { to }, Some(RaiseKind::ThinValue)) => format!("thin value raise to {to:.2}"),
(Choice::Raise { to }, _) => format!("raise to {to:.2}"),
(other, _) => other.name().to_lowercase(),
}
}
/// Highest EV wins; the first of equals wins (options are ordered passive first).
fn best(options: &[Scored]) -> Option<Scored> {
options.iter().copied().fold(None, |acc, s| match acc {
Some(b) if b.ev >= s.ev => Some(b),
_ => Some(s),
})
}
/// EV-indifference band for size mixing: raise sizes within `MIX_BAND` standard errors (in
/// chips) of the best are treated as tied. Half a standard error is a conservative tie — well
/// inside what the equity estimate can resolve. Overridable via `SIZE_MIX_BAND` (read once) for
/// a width sweep. The mix only ever deviates from the argmax (never to a higher-EV size), so a
/// wider band trades a larger by-construction point-estimate bias for more unpredictability:
/// paired ladder (vs the deterministic baseline) measured 1.0σ at −0.56 ±0.95 bb/100 / 227 spots
/// and 0.5σ at −0.23 ±0.59 / 112 spots — both indistinguishable from zero; 0.5σ is the default
/// as the cleaner ≥0 proof that still mixes where sizes are genuinely tied. See
/// BEFUND-size-mix-ev-neutral.md.
const MIX_BAND: f64 = 0.5;
fn mix_band() -> f64 {
use std::sync::OnceLock;
static BAND: OnceLock<f64> = OnceLock::new();
*BAND.get_or_init(|| {
std::env::var("SIZE_MIX_BAND")
.ok()
.and_then(|v| v.parse::<f64>().ok())
.filter(|&b| b.is_finite() && b >= 0.0)
.unwrap_or(MIX_BAND)
})
}
/// Decorrelates the size-mix draw from the equity Monte-Carlo stream, which seeds off
/// `spot.seed` directly. Any fixed non-zero salt works.
const MIX_SALT: u64 = 0x5F3B_C1D2_7A49_E6B5;
/// Measurement toggle (read once): `SIZE_MIX=0` disables size mixing so one run can measure the
/// engine with mixing on vs off on the same deals (paired). Default on.
fn size_mix_enabled() -> bool {
use std::sync::OnceLock;
static ON: OnceLock<bool> = OnceLock::new();
*ON.get_or_init(|| std::env::var("SIZE_MIX").as_deref() != Ok("0"))
}
/// Among the raise sizes within `error` chips of the winning raise (EV-indistinguishable under
/// the equity estimate), a seeded draw picks one. Pure: the winner is returned unchanged unless
/// it is a raise with two or more tied raise sizes. EV-neutral by construction — it only ever
/// swaps between statistically tied sizes.
fn pick_mixed(options: &[Scored], winner: Scored, error: f64, seed: u64) -> Scored {
if !matches!(winner.choice, Choice::Raise { .. }) || error <= 0.0 {
return winner;
}
let tied: Vec<Scored> = options
.iter()
.copied()
.filter(|s| matches!(s.choice, Choice::Raise { .. }) && winner.ev - s.ev <= error)
.collect();
if tied.len() <= 1 {
return winner;
}
let (idx, _) = Rng::seeded(seed).below(tied.len() as u64);
tied[idx as usize]
}
/// Equilibrium play mixes its bet sizes; a pure argmax over sizes is in principle readable (a
/// thinking villain clusters "big size => value"). Where two or more raise sizes are EV-tied
/// (within one standard error of the equity estimate), hero cannot tell them apart, so it draws
/// one — seeded off `spot.seed`, so paired runs stay reproducible and only the mixed spots
/// differ from the deterministic line. Only raise sizes mix; check/call/fold never do. Because
/// it only swaps between statistically tied sizes it is EV-neutral by construction: safe against
/// the non-adjusting fish/stations the ladder's edge rests on, and it can never be a measured
/// loser. The gain is only against villains who would otherwise read a fixed size.
fn mix_size(spot: &Spot, estimate: &Estimate, options: &[Scored], winner: Scored) -> Scored {
if !size_mix_enabled() {
return winner;
}
let Choice::Raise { to } = winner.choice else {
return winner;
};
let error = mix_band() * estimate.std_error.max(0.0) * ev::final_pot(spot.pot, spot.to_call, to);
pick_mixed(options, winner, error, spot.seed ^ MIX_SALT)
}
/// EV lead of the winner over the next-best alternative, counting folding (0) and the
/// call it passed up.
fn lead(spot: &Spot, share: f64, options: &[Scored], winner: Scored) -> f64 {
let rivals = options
.iter()
.filter(|s| s.choice != winner.choice)
.map(|s| s.ev)
.chain((winner.choice != Choice::Fold).then(ev::fold))
.chain(
(winner.choice == Choice::Fold && spot.is_legal(ActionKind::Call))
.then(|| ev::call(share, spot.pot, spot.to_call)),
);
rivals
.fold(None, |m: Option<f64>, x| Some(m.map_or(x, |m| m.max(x))))
.map_or(winner.ev.abs(), |r| winner.ev - r)
}
fn confidence(spot: &Spot, gap: f64) -> f64 {
let scale = (spot.pot + spot.to_call).max(spot.big_blind).max(f64::MIN_POSITIVE);
0.5 + 0.5 * (4.0 * gap.max(0.0) / scale).tanh()
}
/// Opening of every reason: the read, plus the player count when multiway.
fn headline(read: &HandRead, eff: &Effective) -> String {
if eff.villains > 1 {
format!("{} ({}-way)", describe(read), eff.villains)
} else {
describe(read)
}
}
/// `(lead, error)` when a raise leads the best passive line by less than its own EV
/// standard error, `std_error * final pot` (the money at stake). A negative lead
/// (the passive line is worth more) counts as inside the error.
fn marginal_raise(
spot: &Spot,
eff: &Effective,
estimate: &Estimate,
to: f64,
raise_ev: f64,
) -> Option<(f64, f64)> {
let passive = passive_ev(spot, eff.share)?;
let gap = raise_ev - passive;
let error = estimate.std_error.max(0.0) * ev::final_pot(spot.pot, spot.to_call, to);
(gap < error).then_some((gap, error))
}
/// `ENTHALTUNG=passiv` (off by default = bit-identical): a semibluff/bluff raise whose EV lead over the
/// best passive line is inside its error no longer ABSTAINs (the runner turns an ABSTAIN facing a bet
/// into FOLD, `betrieb/runner.py::nie_verstreichen`), it plays the best passive option the option gates
/// kept (check, call, else fold). Pruefstand 18.11.: Jc7s on JhTd8c, equity 0.58 vs break-even 0.32,
/// call +0.16, folded because a 0.72 semibluff led by +0.00 (`messung/pruefstand/BERICHT.md`).
fn passiv_statt_enthaltung(options: &[Scored]) -> Option<Scored> {
use std::sync::OnceLock;
static AN: OnceLock<bool> = OnceLock::new();
if !*AN.get_or_init(|| std::env::var("ENTHALTUNG").is_ok_and(|v| v.trim() == "passiv")) {
return None;
}
let passiv: Vec<Scored> = options.iter().copied().filter(|o| !matches!(o.choice, Choice::Raise { .. })).collect();
best(&passiv)
}
/// `choose_postflop_with` when nothing is known about the calling range: the whole
/// range calls, so the called branch uses the overall share.
pub fn choose_postflop(
spot: &Spot,
estimate: &Estimate,
thresholds: &Thresholds,
read: &HandRead,
) -> Decision {
choose_postflop_with(spot, estimate, &Called::flat(estimate.share), thresholds, read)
}
/// The rule for a postflop spot, given an equity estimate, the share against the
/// calling range per raise size (`called`) and the hand read.
///
/// 1. Invalid equity: ABSTAIN with confidence 0.
/// 2. `effective` (texture stance x multiway) gives the realised share, call margin,
/// value threshold and which raises are allowed.
/// 3. Score check / call / fold / value raises / semibluffs / bluffs (`options::scored`,
/// raises over two branches: fold and called) and take the maximum EV. Never folds
/// when check is legal.
/// 4. Uncertainty: facing fold-or-call with `|share - (break-even + call margin)| <
/// abstain_band + 2 * std_error`, or a winning raise whose EV lead over the best
/// passive line is below `std_error * final pot`: ABSTAIN with a small confidence
/// (0.05..0.30, `uncertainty::abstain_confidence`).
/// 5. Otherwise `confidence` rises with the EV lead over the runner-up, relative to the pot.
pub fn choose_postflop_with(
spot: &Spot,
estimate: &Estimate,
called: &Called,
thresholds: &Thresholds,
read: &HandRead,
) -> Decision {
let raw = estimate.share;
if !(raw.is_finite() && (0.0..=1.0).contains(&raw)) {
return Decision::abstain("equity unavailable");
}
let eff = effective(spot, raw, thresholds, read);
let share = eff.share;
let be = break_even(spot.pot, spot.to_call);
let head = headline(read, &eff);
let options = scored(spot, &eff, thresholds, read, called);
let winner = best(&options);
let priced = |decision: Decision| decision.with_evs(action_evs(spot, share, &options));
// Weltklasse-Linie (Owner 8.11.): die Engine ENTSCHEIDET jeden knappen Fold-oder-Call-Spot selbst
// (Call iff `share >= break-even + call_margin`, das `scored` erzwingt; sonst Fold) statt sich
// im Unsicherheitsband um den Breakpoint zu enthalten. Das alte Band gab ABSTAIN zurueck -> live
// Fold, und foldete so die rausch-nahe +EV-Call-SEITE weg (Overfold-Leak, besonders Flop/Turn mit
// grossem std_error; PLO5-Benchmark-Defekt). Der `call_margin` bleibt unveraendert die Call-
// Schwelle - nur die Enthaltung faellt weg, der `winner` (EV-Maximum) entscheidet. Das MARGINALE
// Raise-Band unten (Spew-Schutz gegen Fold-Equity-Raises) bleibt.
if let Some(Scored { choice: Choice::Raise { to }, ev: raise_ev, kind }) = winner {
// A value raise stays a raise inside its error: the hand is strong enough on its own
// account, the lead only says how much better than checking it is. Only the raises
// that on fold equity (semibluff, bluff) are held back by the error.
let held = kind != Some(RaiseKind::Value);
if let Some((gap, error)) = held.then(|| marginal_raise(spot, &eff, estimate, to, raise_ev)).flatten() {
if let Some(p) = passiv_statt_enthaltung(&options) {
super::options::vermerke(spot, &eff, read, Some(&p));
super::vermerk::notiere(format!("ENTHALTUNG: Raise im Fehler -> {}", super::vermerk::aktion(&p.choice)));
return priced(Decision::new(
p.choice,
abstain_confidence(gap, error),
format!("{head}: raise EV lead {gap:+.2} inside its error {error:.2}, EV {} {:+.2}", label(p.choice, p.kind), p.ev),
));
}
return priced(Decision::new(
Choice::Abstain,
abstain_confidence(gap, error),
format!("{head}: raise EV lead {gap:+.2} inside its error {error:.2}"),
));
}
}
// CHECK_FALLE: a value bet becomes a check against an aggressive read (engine::check_falle).
if let Some(Scored { choice: Choice::Raise { .. }, kind: Some(RaiseKind::Value), .. }) = winner {
if super::check_falle::falle(spot, share) {
return priced(Decision::new(
Choice::Check,
0.5,
format!("{head}: check trap vs aggressive read, equity {raw:.2} vs break-even {be:.2}"),
));
}
}
// The abstain gate above decided WHETHER to raise on the best size; once committed, mix the
// SIZE among EV-tied raises so the line is not a readable pure argmax (EV-neutral, seeded).
let winner = winner.map(|w| mix_size(spot, estimate, &options, w));
// Vermerke (text only): option gates of switches that shaped this winner (`engine::vermerk`).
super::options::vermerke(spot, &eff, read, winner.as_ref());
priced(match winner {
Some(w) => {
let shown = match w.choice {
Choice::Fold => ev::call(share, spot.pot, spot.to_call),
_ => w.ev,
};
let name = match w.choice {
Choice::Fold => "call".to_string(),
other => label(other, w.kind),
};
Decision::new(
w.choice,
confidence(spot, lead(spot, share, &options, w)),
format!("{head}: equity {raw:.2} vs break-even {be:.2}, EV {name} {shown:+.2}"),
)
}
None => match cheapest_continue(spot) {
Some(choice) => Decision::new(
choice,
0.5,
format!("{head}: equity {raw:.2} vs break-even {be:.2}, only continuing action available"),
),
None => Decision::abstain("no actionable option"),
},
})
}
#[cfg(test)]
mod size_mix_tests {
use super::*;
fn raise(to: f64, ev: f64) -> Scored {
Scored { choice: Choice::Raise { to }, ev, kind: Some(RaiseKind::Value) }
}
#[test]
fn mix_only_swaps_between_ev_tied_sizes() {
// Top raise 10.0; 9.8 is within the 0.5 band (gap 0.2), 5.0 is well outside.
let options = vec![raise(2.0, 10.0), raise(3.0, 9.8), raise(4.0, 5.0)];
let winner = raise(2.0, 10.0);
let mut seen: std::collections::BTreeSet<u64> = Default::default();
for seed in 0..64u64 {
let picked = pick_mixed(&options, winner, 0.5, seed);
match picked.choice {
Choice::Raise { to } => {
assert!(to == 2.0 || to == 3.0, "mixed into a non-tied size {to}");
seen.insert(to.to_bits());
}
other => panic!("mix changed the action to {other:?}"),
}
}
assert_eq!(seen.len(), 2, "did not draw across both tied sizes");
}
#[test]
fn mix_is_a_no_op_without_a_tie() {
let options = vec![raise(2.0, 10.0), raise(3.0, 5.0)];
let winner = raise(2.0, 10.0);
for seed in 0..16u64 {
assert_eq!(pick_mixed(&options, winner, 0.5, seed).choice, winner.choice);
}
}
#[test]
fn mix_never_touches_a_non_raise_winner() {
let call = Scored { choice: Choice::Call, ev: 1.0, kind: None };
let options = vec![call, raise(2.0, 10.0)];
assert_eq!(pick_mixed(&options, call, 5.0, 7).choice, Choice::Call);
}
#[test]
fn zero_error_is_deterministic() {
let options = vec![raise(2.0, 10.0), raise(3.0, 10.0)];
let winner = raise(2.0, 10.0);
assert_eq!(pick_mixed(&options, winner, 0.0, 3).choice, winner.choice);
}
}