Files
pokerfreak/src/engine/postflop.rs
T
mmintelandClaude Opus 4.8 47d3ea8094 Engine: EV-neutrales Size-Mix, Stage-B-Solver-Infra, Turnier-Staerke-Leiter
Drei getestete/bewiesene Arbeitsstraenge dieser Session (128/128 Lib gruen):

- EV-neutrales Size-Mix (engine::postflop): das Postflop-Sizing war reiner
  EV-Argmax (deterministisch und damit lesbar). Es mischt jetzt seeded unter
  den Raise-Sizes, deren EV innerhalb 0.5 Standardfehlern des besten liegt
  (unter dem Modell nicht unterscheidbar) - nur Raises, nie check/call/fold.
  Gepaart gegen die deterministische Baseline bewiesen EV-neutral
  (-0.23 +/-0.59 bb/100, 112 Spots gemischt, jede Zeile ununterscheidbar von 0);
  der winzige Negativ-Punktschaetzer ist konstruktionsbedingt (Abweichung nur
  weg vom Argmax) und band-getrieben. Schalter SIZE_MIX / SIZE_MIX_BAND.
  Befund: docs/notizen/BEFUND-size-mix-ev-neutral.md.

- Stage B Turn+River-Subgame-Solver (cfr::turn_river, engine::turn_subgame) plus
  Per-Street-Aggression in der Belief (Profile turn_/river_aggression,
  sim::memory-Zaehler, believed_villain nimmt die Aggression als Parameter). Der
  Live-Turn-Fold-Veto wurde nach gepaarter Messung ZURUECKGENOMMEN (regressiert
  nemesis-1; Wurzel = draw-blinder Turn-Bucket, nicht Belief-Granularitaet ->
  Stage C). Solver- und Belief-Infra bleibt als getestete, Ladder-neutrale
  Primitive. Befund: docs/notizen/BEFUND-stage-b-turn-river-solver.md.

- Turnier-Staerke-Leiter (sim::turnier_leiter, bin turnier_leiter, icm::risk):
  ICM-$-gepaarte Leiter, die die ICM-Linie gegen Chip-EV beweist, Cash
  bit-identisch. Befunde: docs/notizen/BEFUND-turnier-*.md.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-12 12:06:39 +01:00

298 lines
13 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))
}
/// `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() {
return priced(Decision::new(
Choice::Abstain,
abstain_confidence(gap, error),
format!("{head}: raise EV lead {gap:+.2} inside its error {error:.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));
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);
}
}