Ersetzt die irrefuehrende Oracle-Leiter durch eine ehrliche Messmethodik (Oracle aus, Read via Memory/Posterior gegen eine gezogene Gegner-Population). Stufen: - 0 Exploitation-Luecke: +18.98 bb/100 gegen die gezogene Population - 1 Kalibrierung an echte HUD-Daten (lesen/kalibrierung.py) - 2 Zwillings-Tor (EGTA + Exploitability-Waechter): Offense +43.95, Boden gto -36.25 (verliert gegen Balancierte - die Oracle-verdeckte Wurzel) - 3 Adaptive Liga L0-L3 (reaktiv / modellierend / Liga) - 4 Sim-to-Real: HUD-Gap (sim::simreal) + Outcome-Abgleich (lesen/liveabgleich.py): real -266.75 vs Sim +43.95 => Gap -311; A/B-Pipeline + Runbook fertig, nur der geldechte Live-Lauf unter beiden Armen bleibt offen - 5 Optimizer (Diagonal-CMA-ES, parallel): Nemesis -414.81 bb/100 Befunde und Architektur in docs/notizen/. Lab-Tests gruen (Rust lib 92/0, python liveabgleich/kalibrierung/gegnersignal gruen). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
283 lines
12 KiB
Rust
283 lines
12 KiB
Rust
//! Engine bridge from a live river spot to the pure CFR river solver (`cfr::river`).
|
||
//!
|
||
//! This is the Stage-A wiring: it turns the engine's own belief (the villain range model, as built
|
||
//! in `engine::decide::postflop`) into strength buckets, solves the heads-up river subgame to
|
||
//! equilibrium, and reads back hero's **mixed** action for the bucket its real hand sits in. All
|
||
//! poker-specific sourcing lives here; the solver stays a pure game over abstract buckets.
|
||
//!
|
||
//! # What changed from the first slice (and why it matters for exploitability)
|
||
//!
|
||
//! The first version solved with hero as a revealed **point mass** (one known hand) and then
|
||
//! collapsed the equilibrium mix to its majority action. Both make the line maximally exploitable:
|
||
//! a point-mass hero lets the solved villain best-respond to hero's exact strength (no need to
|
||
//! balance), and a pure readback cannot bluff or defend at the right frequency. Against a villain
|
||
//! that best-responds over hero's TRUE range, that bleeds — which the postflop-exploitability
|
||
//! harness (`sim::exploit_river`) measured at 32–108 bb/100.
|
||
//!
|
||
//! This version models hero with the **same strength distribution as the villain** (a symmetric
|
||
//! river prior — both players reach the river with strength spread over the board's quantiles) and
|
||
//! returns the equilibrium **mix** for hero's bucket. That is a balanced RANGE strategy: value
|
||
//! buckets bet, a calibrated fraction of air bluffs (bluff-to-value `s/(P+s)`), bluff-catchers
|
||
//! defend at MDF `P/(P+s)`. Live play realises the mix from the spot seed; the harness reads the
|
||
//! frequency directly.
|
||
//!
|
||
//! # Slice (v1)
|
||
//!
|
||
//! **Heads-up river**, both hero nodes of the solver's tree:
|
||
//! - hero first to act (`to_call == 0`) → check / bet,
|
||
//! - hero facing a bet (`to_call > 0`, the pre-bet pot `pot - to_call`, bet `to_call`) → fold / call.
|
||
//!
|
||
//! Multiway, or a villain range the engine cannot enumerate, returns `None` so the caller keeps the
|
||
//! heuristic. The solver equilibrium is the unexploitable baseline; whether wiring it into live play
|
||
//! also holds the bb/100 ladder is a measured question, not an assumption.
|
||
//!
|
||
//! # Named approximations
|
||
//!
|
||
//! - Hero's river range is modelled as the villain's strength distribution, not hero's true line-
|
||
//! consistent range. The closer the two, the lower the residual exploitability.
|
||
//! - The villain range is cut into `BUCKETS` equal-count (quantile) buckets, so a higher bucket index
|
||
//! always wins the showdown; the quantile cut makes the modelled distribution uniform over buckets.
|
||
//! - The solver's action abstraction is one bet size, no raises (`cfr::river` v1).
|
||
|
||
use crate::card::Card;
|
||
use crate::cfr::river::tree_with_chance;
|
||
use crate::cfr::solve::{solve, Solved};
|
||
use crate::game::{Choice, Decision, Spot, Street};
|
||
use crate::hand::showdown::judge;
|
||
use crate::hand::strength::Strength;
|
||
use crate::rng::Rng;
|
||
use crate::sizing::candidates::candidates;
|
||
|
||
/// CFR+ iterations per live solve. Enough for the tiny tree (9 nodes) to converge; an
|
||
/// under-converged solve is itself exploitable, so this is not shaved.
|
||
const ITERS: u32 = 12_000;
|
||
/// Target bet size as a fraction of the pot; the nearest legal candidate is used.
|
||
const TARGET_BET_FRACTION: f64 = 0.66;
|
||
|
||
/// Hero's equilibrium mix at the river node the spot sits on.
|
||
pub struct RiverPlan {
|
||
/// `true` = hero is facing a bet (`mix` is `[fold, call]`); `false` = hero acts first
|
||
/// (`mix` is `[check, bet]`).
|
||
pub facing: bool,
|
||
/// The two action probabilities for hero's bucket, in the order above.
|
||
pub mix: [f64; 2],
|
||
/// The bet-to total when acting first (the raise size); `0` facing a bet.
|
||
pub bet_to: f64,
|
||
/// Human reason for the decision log.
|
||
pub reason: String,
|
||
}
|
||
|
||
impl RiverPlan {
|
||
/// Probability of the aggressive action (bet, or call facing a bet).
|
||
fn forward(&self) -> f64 {
|
||
self.mix[1]
|
||
}
|
||
}
|
||
|
||
/// The legal bet-to total nearest `TARGET_BET_FRACTION * pot`, or `None` if nothing is bettable.
|
||
fn bet_to(spot: &Spot) -> Option<f64> {
|
||
let target = TARGET_BET_FRACTION * spot.pot;
|
||
candidates(spot)
|
||
.into_iter()
|
||
.filter(|to| *to > 0.0 && *to <= spot.hero_stack)
|
||
.min_by(|a, b| (a - target).abs().total_cmp(&(b - target).abs()))
|
||
}
|
||
|
||
/// Two hole-card hands can be dealt together only if they share no card.
|
||
fn disjoint(a: &[Card], b: &[Card]) -> bool {
|
||
a.iter().all(|c| !b.contains(c))
|
||
}
|
||
|
||
/// A solved card-exact river subgame plus the shared strength ladder, so hero's real hand can be
|
||
/// placed on the same buckets the solve used.
|
||
struct Subgame {
|
||
solved: Solved,
|
||
ladder: Vec<Strength>,
|
||
}
|
||
|
||
impl Subgame {
|
||
/// The bucket a strength sits in on the shared ladder (its ascending rank, clamped to the top).
|
||
fn bucket(&self, s: Strength) -> usize {
|
||
self.ladder.partition_point(|d| *d < s).min(self.ladder.len() - 1)
|
||
}
|
||
}
|
||
|
||
/// Build and solve the card-exact heads-up river subgame the engine believes it is in. Hero's range
|
||
/// is modelled as the villain's believed range (`hero_combos == villain_combos`, a symmetric river
|
||
/// prior); both are bucketed by **exact showdown strength** on one shared ascending ladder, and the
|
||
/// joint deal table carries **card removal** between the two ranges — the same construction the
|
||
/// exploitability harness uses for the true game. This faithfulness is what lets the equilibrium it
|
||
/// plays actually be unexploitable; the coarse symmetric-uniform first cut was not, and measured
|
||
/// worse than the heuristic. `None` for fewer than two distinct strengths.
|
||
fn subgame(spot: &Spot, hero_combos: &[Vec<Card>], villain_combos: &[Vec<Card>], pot: f64, bet: f64) -> Option<Subgame> {
|
||
let rules = spot.rules();
|
||
let judged = |combos: &[Vec<Card>]| -> Vec<(Vec<Card>, Strength)> {
|
||
combos.iter().filter_map(|c| judge(&rules, c, &spot.board).ok().map(|s| (c.clone(), s))).collect()
|
||
};
|
||
let hero = judged(hero_combos);
|
||
let villain = judged(villain_combos);
|
||
if hero.is_empty() || villain.is_empty() {
|
||
return None;
|
||
}
|
||
let mut ladder: Vec<Strength> = hero.iter().chain(&villain).map(|(_, s)| *s).collect();
|
||
ladder.sort();
|
||
ladder.dedup();
|
||
let n = ladder.len();
|
||
if n < 2 {
|
||
return None;
|
||
}
|
||
let bucket = |s: Strength| ladder.partition_point(|d| *d < s).min(n - 1);
|
||
let mut chance = vec![0.0; n * n];
|
||
for (hc, hs) in &hero {
|
||
let hb = bucket(*hs);
|
||
for (vc, vs) in &villain {
|
||
if disjoint(hc, vc) {
|
||
chance[hb * n + bucket(*vs)] += 1.0;
|
||
}
|
||
}
|
||
}
|
||
let total: f64 = chance.iter().sum();
|
||
if total <= 0.0 {
|
||
return None;
|
||
}
|
||
chance.iter_mut().for_each(|x| *x /= total);
|
||
let tree = tree_with_chance(n, chance, pot, bet);
|
||
Some(Subgame { solved: solve(&tree, ITERS, Rng::seeded(spot.seed)), ladder })
|
||
}
|
||
|
||
/// Solve the heads-up river subgame from the engine's belief (`villain_combos`) and return hero's
|
||
/// equilibrium mix at the node the spot sits on, or `None` when the v1 slice does not apply (the
|
||
/// caller then keeps the heuristic).
|
||
pub fn river_plan(spot: &Spot, villain_combos: &[Vec<Card>]) -> Option<RiverPlan> {
|
||
if spot.street != Street::River {
|
||
return None;
|
||
}
|
||
if spot.live_villains().count() != 1 || villain_combos.is_empty() {
|
||
return None;
|
||
}
|
||
let rules = spot.rules();
|
||
let hero_strength = judge(&rules, &spot.hero_cards, &spot.board).ok()?;
|
||
|
||
if spot.to_call == 0.0 {
|
||
let bet = bet_to(spot)?;
|
||
let game = subgame(spot, villain_combos, villain_combos, spot.pot, bet)?;
|
||
let hb = game.bucket(hero_strength);
|
||
let probs = game.solved.strategy.row(0, hb).to_vec(); // [check, bet]
|
||
let bet_p = probs.get(1).copied().unwrap_or(0.0);
|
||
Some(RiverPlan {
|
||
facing: false,
|
||
mix: [probs.first().copied().unwrap_or(1.0 - bet_p), bet_p],
|
||
bet_to: bet,
|
||
reason: format!("river subgame: bucket {hb}/{}, p(bet) {bet_p:.2}", game.ladder.len()),
|
||
})
|
||
} else {
|
||
// Facing a bet: the solver's pre-bet pot is `pot - to_call`, the bet is `to_call`.
|
||
let p = spot.pot - spot.to_call;
|
||
let bet = spot.to_call;
|
||
if p <= 0.0 || bet <= 0.0 {
|
||
return None;
|
||
}
|
||
let game = subgame(spot, villain_combos, villain_combos, p, bet)?;
|
||
let hb = game.bucket(hero_strength);
|
||
let row = game.solved.strategy.row(4, hb).to_vec(); // [fold, call]
|
||
let call_p = row.get(1).copied().unwrap_or(0.0);
|
||
Some(RiverPlan {
|
||
facing: true,
|
||
mix: [row.first().copied().unwrap_or(1.0 - call_p), call_p],
|
||
bet_to: 0.0,
|
||
reason: format!("river subgame: bucket {hb}/{} facing bet, p(call) {call_p:.2}", game.ladder.len()),
|
||
})
|
||
}
|
||
}
|
||
|
||
/// Realise a `RiverPlan` into a concrete decision, mixing from the spot seed (deterministic per spot,
|
||
/// correct frequency across the range of deals). Confidence rises as the mix leaves 50/50.
|
||
pub fn realize(spot: &Spot, plan: &RiverPlan) -> Decision {
|
||
let (draw, _) = Rng::seeded(spot.seed).unit();
|
||
let aggressive = draw < plan.forward();
|
||
let choice = match (plan.facing, aggressive) {
|
||
(false, true) => Choice::Raise { to: plan.bet_to },
|
||
(false, false) => Choice::Check,
|
||
(true, true) => Choice::Call,
|
||
(true, false) => Choice::Fold,
|
||
};
|
||
let confidence = 0.5 + (plan.forward() - 0.5).abs();
|
||
Decision::new(choice, confidence, plan.reason.clone())
|
||
}
|
||
|
||
/// Build the villain belief combos the way `decide::postflop` does (gated reads, enumerated range)
|
||
/// and return hero's river mix — the measurement entry point for `sim::exploit_river`, faithful to
|
||
/// what the live engine would play. `None` when the slice does not apply.
|
||
pub fn river_mix(spot: &Spot) -> Option<RiverPlan> {
|
||
if spot.street != Street::River {
|
||
return None;
|
||
}
|
||
let gated = crate::engine::read_gate::gate_reads(spot);
|
||
let spot = &gated;
|
||
if spot.live_villains().count() != 1 {
|
||
return None;
|
||
}
|
||
let villain = spot.live_villains().next()?;
|
||
let rules = spot.rules();
|
||
let filter = crate::engine::range_filter::range_filter(
|
||
&crate::exploit::range_model::range_spec(spot, villain),
|
||
rules,
|
||
spot.variant,
|
||
&spot.board,
|
||
);
|
||
let dead: Vec<Card> = spot.hero_cards.iter().chain(&spot.board).copied().collect();
|
||
let list = crate::engine::range_combos::combos(&rules, &filter, &dead)?;
|
||
river_plan(spot, &list)
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
use crate::game::{ActionKind, Villain};
|
||
use crate::variant::Variant;
|
||
|
||
/// A heads-up river spot where hero is first to act into `pot` with check or a two-thirds bet.
|
||
fn river_to_act(board: &[Card], hero: &str, pot: f64) -> Spot {
|
||
Spot {
|
||
variant: Variant::Nlhe,
|
||
big_blind: 1.0,
|
||
seats: 2,
|
||
hero_seat: 1,
|
||
button_seat: Some(1),
|
||
hero_cards: Card::parse_list(hero).unwrap(),
|
||
board: board.to_vec(),
|
||
street: Street::River,
|
||
pot,
|
||
to_call: 0.0,
|
||
hero_stack: pot * 4.0,
|
||
min_raise_to: Some(pot * 0.66),
|
||
max_raise_to: Some(pot * 4.0),
|
||
legal: vec![ActionKind::Check, ActionKind::Raise],
|
||
allowed_sizes: Some(vec![pot * 0.66]),
|
||
villains: vec![Villain { seat: 2, stack: pot * 4.0, folded: false, profile: None }],
|
||
seed: 0x5EED_B17E,
|
||
history: Vec::new(),
|
||
}
|
||
}
|
||
|
||
/// A river spot the slice accepts (heads-up, hero to act) returns a mix, and a strong made hand
|
||
/// leans to betting. Guards the wiring, not the exact frequency.
|
||
#[test]
|
||
fn a_made_hand_to_act_gets_a_river_mix_that_leans_to_bet() {
|
||
let board = Card::parse_list("Ah Kd 7c 2s 9h").unwrap();
|
||
let villain: Vec<Vec<Card>> = ["Ad Jc", "Qh Qd", "Jd Jh", "8c 8d", "6h 6d", "5c 4c", "Td 9c", "Kc Qc"]
|
||
.iter()
|
||
.map(|c| Card::parse_list(c).unwrap())
|
||
.collect();
|
||
let spot = river_to_act(&board, "Ac As", 6.0); // overpair-strength: top two on this board
|
||
let plan = river_plan(&spot, &villain).expect("heads-up river to-act is in slice");
|
||
assert!(!plan.facing);
|
||
assert!(plan.bet_to > 0.0);
|
||
assert!(
|
||
plan.forward() > 0.5,
|
||
"a strong made hand should lean to betting, got p(bet) {:.2}",
|
||
plan.forward()
|
||
);
|
||
}
|
||
}
|