//! Bounded exploitation of the opponents `read_gate` plays blind (switch `GEGNER_BREIT`, default off). //! //! `read_gate` hands the heuristic a read only for calling stations: acting on a nit's, a reg's or a //! maniac's read through the single-street bluff EV bled on the ladder (nit −50, maniac −148, reg −176 //! bb/100), because the read flowed into EVERY offensive channel at full strength (BEFUND-nit-read-leck: //! flop check → bluff-RAISE into a nutted continuing range). This module re-opens the read for the //! other styles, but only through a few narrow channels, each a single, local change to the blind //! decision that the read can price completely: //! //! | letter | channel | change | read | //! |---|---|---|---| //! | `c` | c-bet pressure | flop check → small c-bet (hero preflop aggressor, heads-up) | `fold_to_cbet` | //! | `b` | bluff veto | a pure-bluff bet → check | street fold-to-bet | //! | `r` | bluff-catch | river fold → call facing a bet | river gearbox (aggression / shown bluffs) | //! | `w` | thin value | river check → bet with a made hand | river gearbox | //! | `3` | light 3-bet | preflop call / top fold → 3-bet vs the lone opener | `fold_to_three_bet` | //! | `s` | steal width | unopened pot: opening width from the players behind | fold-to-bet of each | //! | `m` | light 3-bet, players behind | as `3`, the opener alone in, others still to act | `fold_to_three_bet`, `BEHIND_FOLD` each | //! //! Every read passes the same trust region before it is used (`bounded`): it is pulled toward the //! blind default by its confidence, then capped so the Bernoulli KL divergence from the blind default //! stays within `KL_PER_CONFIDENCE · confidence` nats. A thin read is the blind default; a strong //! read moves the parameter, never past the KL ball. The river channels' //! check is the node-locked best response of `river_br` (taken over from the paused WIP branch //! `worktree-agent-a3f0fb40e48710d66`): worst-case gain over a belief box, KL-capped deviation weight. //! //! Untouched: calling stations (already exploited by the heuristic, bit-identical), multiway pots, //! tournament spots (the caller applies this only with no ICM premium), and every decision the switch //! does not name. `GEGNER_BREIT=1` turns on the five original channels (c b r w 3); `s` and `m` (D1e) //! must be named (e.g. `GEGNER_BREIT=cbrw3sm`), so the measured meaning of `1` stays fixed. use super::bluff::is_bluff_hand; use super::read_gate::exploit_worthy; use super::river_br; use crate::exploit::fold_chance::{fold_base, DEFAULT_FOLD_TO_BET}; use crate::exploit::profile::Profile; use crate::exploit::sample::FOLD_TO_THREE_BET_ANCHOR; use crate::exploit::style::classify; use crate::game::{line, ActionKind, Choice, Decision, Spot, Street, Villain}; use crate::read::hand_read::HandRead; use crate::read::tier::{tier, Tier}; use crate::sizing::candidates::candidates; /// Below this confidence a read is not used at all (as the river gearbox's `CONFIDENCE_FLOOR`). pub const CONFIDENCE_FLOOR: f64 = 0.25; /// Trust-region radius per unit of confidence, in nats of Bernoulli KL from the blind default. pub const KL_PER_CONFIDENCE: f64 = 0.15; /// C-bet pressure: bet size as a pot fraction (small: cheap to be wrong, the folder folds anyway). pub const CBET_FRACTION: f64 = 0.33; /// C-bet pressure: the bet must beat checking by this share of the pot. pub const CBET_EDGE: f64 = 0.05; /// Thin value (`w`): least equity vs the range for the river check -> bet. pub const THIN_VALUE_EQUITY: f64 = 0.5; /// C-bet pressure: the trust-bounded fold-to-c-bet must exceed the blind default by this much. pub const CBET_READ_LIFT: f64 = 0.15; /// C-bet pressure: only hands up to this equity (strong hands keep the heuristic's own line). pub const CBET_MAX_EQUITY: f64 = 0.5; /// Equity a called c-bet keeps relative to the hand's equity against the full range. pub const CALLED_EQUITY_SHARE: f64 = 0.8; /// The channels the switch turns on. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct Channels { pub cbet: bool, pub bluff_veto: bool, pub bluff_catch: bool, pub thin_value: bool, pub light_three_bet: bool, pub steal: bool, pub three_bet_behind: bool, } impl Channels { pub fn parse(value: &str) -> Channels { let v = value.trim(); if v == "1" || v.eq_ignore_ascii_case("alle") { return Channels { cbet: true, bluff_veto: true, bluff_catch: true, thin_value: true, light_three_bet: true, steal: false, three_bet_behind: false, }; } Channels { cbet: v.contains('c'), bluff_veto: v.contains('b'), bluff_catch: v.contains('r'), thin_value: v.contains('w'), light_three_bet: v.contains('3'), steal: v.contains('s'), three_bet_behind: v.contains('m'), } } } /// The channels from `GEGNER_BREIT` (read once). pub fn channels() -> Channels { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); *ON.get_or_init(|| std::env::var("GEGNER_BREIT").map(|v| Channels::parse(&v)).unwrap_or_default()) } /// Measurement only (`GEGNER_BREIT_ROH=1`): the trust region is dropped (raw read, no confidence floor) /// to count how many decisions the bound itself holds back. Never set live. pub fn raw_reads() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); *ON.get_or_init(|| std::env::var("GEGNER_BREIT_ROH").is_ok_and(|v| v.trim() == "1")) } /// Measurement only (`GEGNER_BREIT_DIAG=1`): append `diag:` to every reason (see `diagnose`). pub fn diag_on() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); *ON.get_or_init(|| std::env::var("GEGNER_BREIT_DIAG").is_ok_and(|v| v.trim() == "1")) } /// Bernoulli KL divergence `KL(p ‖ q)` in nats. pub fn kl(p: f64, q: f64) -> f64 { let p = p.clamp(1e-9, 1.0 - 1e-9); let q = q.clamp(1e-9, 1.0 - 1e-9); p * (p / q).ln() + (1.0 - p) * ((1.0 - p) / (1.0 - q)).ln() } /// The trust region: `read` pulled toward `anchor` by `confidence`, then capped at KL radius /// `KL_PER_CONFIDENCE · confidence` from `anchor`. Below `CONFIDENCE_FLOOR` (or a non-finite input) /// the anchor itself. pub fn bounded(read: f64, anchor: f64, confidence: f64) -> f64 { if raw_reads() && read.is_finite() { return read.clamp(0.0, 1.0); // measurement counterfactual: no trust region } if !(read.is_finite() && anchor.is_finite() && confidence.is_finite()) || confidence < CONFIDENCE_FLOOR { return anchor; } let c = confidence.min(1.0); let target = anchor + c * (read.clamp(0.0, 1.0) - anchor); let radius = KL_PER_CONFIDENCE * c; if kl(target, anchor) <= radius { return target; } let (mut lo, mut hi) = (0.0f64, 1.0f64); for _ in 0..50 { let mid = 0.5 * (lo + hi); if kl(anchor + mid * (target - anchor), anchor) <= radius { lo = mid; } else { hi = mid; } } anchor + lo * (target - anchor) } /// The lone live villain whose read the gate drops (a non-station with a profile), else `None`. fn blind_read_villain(spot: &Spot) -> Option<(&Villain, Profile)> { let mut live = spot.live_villains(); let (Some(v), None) = (live.next(), live.next()) else { return None }; let p = v.profile?; if exploit_worthy(classify(&p)) { return None; // the heuristic already exploits it; leave it bit-identical } Some((v, p)) } /// The raw spot with the stake's pool blended into the lone blind villain's profile (`exploit::pool`, /// switch `GEGNER_POOL`); `None` when the pool is off, finds no stake, the pot is multiway, the villain /// is a station (exploited by the heuristic) or an aggressor (guard), or nothing changes. pub fn with_pool(raw: &Spot) -> Option { let pool = crate::exploit::pool::pool_for(raw.big_blind)?; let mut live = raw.live_villains(); let (Some(v), None) = (live.next(), live.next()) else { return None }; if v.profile.is_some_and(|p| exploit_worthy(classify(&p))) { return None; } let profile = crate::exploit::pool::pooled(&pool, v.profile)?; let seat = v.seat; let mut spot = raw.clone(); for v in spot.villains.iter_mut().filter(|v| v.seat == seat) { v.profile = Some(profile); } Some(spot) } fn confidence(p: &Profile) -> f64 { p.confidence.filter(|c| c.is_finite()).unwrap_or(0.0) } fn finite(x: Option) -> Option { x.filter(|v| v.is_finite()) } /// The legal bet nearest `fraction · pot` (a total street amount), if any. fn bet_near(spot: &Spot, fraction: f64) -> Option { let target = 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())) } fn street_index(street: Street) -> Option { match street { Street::Flop => Some(0), Street::Turn => Some(1), Street::River => Some(2), Street::Preflop => None, } } fn tagged(base: Decision, choice: Choice, tag: &str, why: String) -> Decision { Decision { choice, reason: format!("breit:{tag}: {why} | {}", base.reason), ..base } } /// Postflop: apply the switched-on channels to the heuristic's final decision (`base`, after floor and /// veto) on the RAW (ungated) spot. Returns `base` unchanged whenever no channel fires. pub fn postflop(raw: &Spot, hand: &HandRead, base: Decision) -> Decision { postflop_with(channels(), raw, hand, base) } pub fn postflop_with(ch: Channels, raw: &Spot, hand: &HandRead, base: Decision) -> Decision { if ch == Channels::default() || raw.street == Street::Preflop { return base; } let pooled = with_pool(raw); let raw = pooled.as_ref().unwrap_or(raw); let Some((_, p)) = blind_read_villain(raw) else { return base }; let conf = confidence(&p); let equity = base.equity.unwrap_or(0.5); let can_bet = raw.to_call == 0.0 && raw.is_legal(ActionKind::Raise); // c: c-bet pressure against a folder. if ch.cbet && base.choice == Choice::Check && can_bet && line::cbet_spot(&raw.history, raw.hero_seat, raw.street) { if let (Some(read), Some(b)) = (finite(p.fold_to_cbet), bet_near(raw, CBET_FRACTION)) { let anchor = finite(p.fold_to_bet).unwrap_or(DEFAULT_FOLD_TO_BET).min(DEFAULT_FOLD_TO_BET); let f = bounded(read, anchor, conf); let pot = raw.pot; let called = CALLED_EQUITY_SHARE * equity; let gain_at = |f: f64| f * pot + (1.0 - f) * (called * (pot + 2.0 * b) - b) - equity * pot; let gain = gain_at(f); // The heuristic checked blind for its own (multi-street) reasons, although this one-street // sum already pays at the blind default; so the read must lift the fold rate clearly // (`CBET_READ_LIFT` after the trust region) and the bet must gain over that default too. let lift = gain - gain_at(anchor); if equity <= CBET_MAX_EQUITY && f >= anchor + CBET_READ_LIFT && gain >= CBET_EDGE * pot && lift > 0.0 { let why = format!("fold to c-bet {read:.2} -> {f:.2} (conf {conf:.2}), +{:.2} pot", gain / pot); return tagged(base, Choice::Raise { to: b }, "c", why); } } } // b: no pure bluff into a caller. if ch.bluff_veto && raw.to_call == 0.0 && is_bluff_hand(hand, raw) && raw.is_legal(ActionKind::Check) { if let Choice::Raise { to } = base.choice { let i = street_index(raw.street); let read = if line::cbet_spot(&raw.history, raw.hero_seat, raw.street) { finite(p.fold_to_cbet) } else { None } .or_else(|| i.and_then(|i| finite(p.street_fold_to_bet[i]))) .or(finite(p.fold_to_bet)); if let Some(read) = read { let f = bounded(read, DEFAULT_FOLD_TO_BET, conf); let ev_at = |f: f64| f * raw.pot - (1.0 - f) * to; let ev = ev_at(f); // Only where the read flips the blind verdict (the blind fold rate pays the bluff). if ev < 0.0 && ev_at(DEFAULT_FOLD_TO_BET) >= 0.0 { let why = format!("fold {read:.2} -> {f:.2} (conf {conf:.2}), bluff EV {:.2} pot", ev / raw.pot); return tagged(base, Choice::Check, "b", why); } } } } // r / w: the node-locked river best response (`engine::river_br`, worst case over a belief box // around the read, deviation weight capped by a KL budget in the confidence), anchored at the // heuristic's own decision. Only its promote pieces: fold -> call, check -> bet. if raw.street == Street::River && (ch.bluff_catch || ch.thin_value) { let mut mask = 0u8; if ch.bluff_catch { mask |= river_br::PIECE_PROMOTE_CALL; } // Thin VALUE only: a made hand at least even against the range. Replay 14.11. without this: // 23 of 111 real river spots, nearly all air/board-only check -> small bet into a high HUD // fold-to-bet - the nit-leak pattern (a read fold rate turned into bluffs), not value. let value = tier(hand.made) != Tier::Weak && base.equity.is_some_and(|e| e >= THIN_VALUE_EQUITY); if ch.thin_value && value { mask |= river_br::PIECE_VALUE_BET; } let before = base.choice; let refined = river_br::refine_with(raw, base, mask); if refined.choice != before { let tag = if refined.choice == Choice::Call { "r" } else { "w" }; let why = refined.reason.clone(); return Decision { reason: format!("breit:{tag}: {why}"), ..refined }; } return refined; } base } /// Preflop `3`: the opener's fold-to-3-bet, trust-bounded, for an opener the gate plays blind. `None` /// when the channel is off, the opener is a station (its gated profile already carries the read) or /// has no usable read. pub fn fold_to_three_bet(raw: &Spot, seat: u8) -> Option { fold_to_three_bet_with(channels(), raw, seat) } pub fn fold_to_three_bet_with(ch: Channels, raw: &Spot, seat: u8) -> Option { if !ch.light_three_bet { return None; } let pooled = with_pool(raw); let raw = pooled.as_ref().unwrap_or(raw); let v = raw.villains.iter().find(|v| v.seat == seat && !v.folded)?; let p = v.profile?; if exploit_worthy(classify(&p)) { return None; } let read = finite(p.fold_to_three_bet)?; let conf = confidence(&p); (raw_reads() || conf >= CONFIDENCE_FLOOR).then(|| bounded(read, FOLD_TO_THREE_BET_ANCHOR, conf)) } /// `fold_to_three_bet` for channel `m`: the same trust-bounded read of `seat`, without the lone-villain /// pool (the pot has players behind) and only with `m` on. pub fn fold_to_three_bet_any(raw: &Spot, seat: u8) -> Option { let ch = channels(); let mut live = raw.live_villains(); if let (Some(_), None) = (live.next(), live.next()) { return fold_to_three_bet_with(ch, raw, seat); } if !ch.three_bet_behind { return None; } let v = raw.villains.iter().find(|v| v.seat == seat && !v.folded)?; let p = v.profile?; if exploit_worthy(classify(&p)) { return None; } let read = finite(p.fold_to_three_bet)?; let conf = confidence(&p); (raw_reads() || conf >= CONFIDENCE_FLOOR).then(|| bounded(read, FOLD_TO_THREE_BET_ANCHOR, conf)) } /// Steal (`s`): the opening-width multiplier of an unopened pot (`exploit::steal_width`) from the RAW /// spot: stations as the gated spot sees them, every other read fold-to-bet through the trust region /// (`bounded` toward the blind 0.45). `None` when the channel is off or nobody behind has a usable /// non-station read (then the gated `steal_width` is already the answer). pub fn steal_width_read(raw: &Spot) -> Option { steal_width_with(channels(), raw) } pub fn steal_width_with(ch: Channels, raw: &Spot) -> Option { if !ch.steal { return None; } let mut read_any = false; let folds: Vec = raw .live_villains() .map(|v| match v.profile { Some(p) if exploit_worthy(classify(&p)) => fold_base(Some(&p)), Some(p) => { let c = confidence(&p); if raw_reads() || c >= CONFIDENCE_FLOOR { read_any = true; bounded(fold_base(Some(&p)), DEFAULT_FOLD_TO_BET, c) } else { DEFAULT_FOLD_TO_BET } } None => DEFAULT_FOLD_TO_BET, }) .collect(); read_any.then(|| crate::exploit::steal_width::width_from_folds(&folds)) } /// Why the reading layer leaves this decision at the blind default: the FIRST failing condition of /// the cascade (structure -> profile -> confidence -> channel spot -> the channel's own test), as a /// code plus the villain's confidence. Measurement only (`GEGNER_BREIT_DIAG`); `decision` is final. pub fn diagnose(raw: &Spot, decision: &Decision, premium: f64) -> String { use crate::preflop::situation::Situation; let pooled = with_pool(raw); let raw = pooled.as_ref().unwrap_or(raw); let code: String = (|| -> String { if premium > 0.0 { return "icm".into(); } if decision.reason.contains("breit:") { return "breit:feuert".into(); } if raw.street == Street::Preflop { match crate::preflop::situation_of::situation_of(raw) { Situation::Unopened if !channels().steal => { return "pre:zuerst-rein (kein Kanal; Steal-Weite nur vs Stations)".into() } Situation::Unopened => { return match steal_width_read(raw) { None => "pre:s:kein-read".into(), Some(_) => "pre:s:breite-kippt-nicht".into(), } } Situation::FacingLimp => return "pre:limp (kein Kanal)".into(), Situation::FacingThreeBetPlus => return "pre:3bet+ (kein Kanal)".into(), Situation::FacingAllIn => return "pre:all-in (kein Kanal)".into(), Situation::FacingOpen => {} } let mut live = raw.live_villains(); let (Some(v), None) = (live.next(), live.next()) else { if !channels().three_bet_behind { return "pre:open:multiway".into(); } return match crate::preflop::advise::players_behind(raw) { None => "pre:m:caller-oder-kein-opener".into(), Some(_) => "pre:m:f3-mal-dahinter-unter-preis".into(), }; }; if line::opener(&raw.history) != Some(v.seat) { return "pre:open:nicht-opener".into(); } let Some(p) = v.profile else { return "pre:open:kein-profil".into() }; if exploit_worthy(classify(&p)) { return "pre:open:station".into(); } match decision.choice { Choice::Raise { .. } => return "pre:open:chart-raist-schon".into(), Choice::Fold if crate::preflop::hand_percentile::percentile(raw.variant, &raw.hero_cards) > 0.85 => { return "pre:open:muell-fold".into() } _ => {} } if finite(p.fold_to_three_bet).is_none() { return "pre:open:kein-f3-read".into(); } if confidence(&p) < CONFIDENCE_FLOOR && !raw_reads() { return "pre:open:vertrauen<0.25".into(); } return "pre:open:f3-unter-preis".into(); } let mut live = raw.live_villains(); let (Some(v), None) = (live.next(), live.next()) else { return "post:multiway".into() }; let Some(p) = v.profile else { return "post:kein-profil".into() }; if exploit_worthy(classify(&p)) { return "post:station (Heuristik nutzt schon)".into(); } let conf = confidence(&p); if conf < CONFIDENCE_FLOOR && !raw_reads() { return "post:vertrauen<0.25".into(); } let can_bet = raw.to_call == 0.0 && raw.is_legal(ActionKind::Raise); let cbet = line::cbet_spot(&raw.history, raw.hero_seat, raw.street); let hand = crate::read::hand_read::read(&raw.rules(), &raw.hero_cards, &raw.board).ok(); let bluff = hand.as_ref().is_some_and(|h| is_bluff_hand(h, raw)); let equity = decision.equity.unwrap_or(0.5); match decision.choice { Choice::Check if can_bet && cbet => { if finite(p.fold_to_cbet).is_none() { "post:c:kein-read".into() } else if equity > CBET_MAX_EQUITY { "post:c:hand-zu-stark".into() } else { let anchor = finite(p.fold_to_bet).unwrap_or(DEFAULT_FOLD_TO_BET).min(DEFAULT_FOLD_TO_BET); let read = p.fold_to_cbet.unwrap_or(anchor); if read < anchor + CBET_READ_LIFT { "post:c:read-unauffaellig".into() } else if bounded(read, anchor, conf) < anchor + CBET_READ_LIFT { "post:c:schranke".into() } else { "post:c:oekonomie".into() } } } Choice::Raise { to } if raw.to_call == 0.0 && bluff => { let read = finite(p.fold_to_cbet).filter(|_| cbet).or(finite(p.fold_to_bet)); match read { None => "post:b:kein-read".into(), Some(r) => { let ev = |f: f64| f * raw.pot - (1.0 - f) * to; if ev(DEFAULT_FOLD_TO_BET) < 0.0 { "post:b:blind-schon-negativ".into() } else if ev(r) >= 0.0 { "post:b:read-zahlt-bluff".into() } else { "post:b:schranke".into() } } } } _ if raw.street == Street::River => { if raw.to_call > 0.0 { match decision.choice { Choice::Fold => "post:r:br-kein-vorteil".into(), _ => "post:river-gegen-einsatz-weiter (kein Kanal noetig)".into(), } } else if decision.choice == Choice::Check { let made = hand.as_ref().is_some_and(|h| tier(h.made) != Tier::Weak) && equity >= THIN_VALUE_EQUITY; if made { "post:w:br-kein-vorteil".into() } else { "post:river-check-luft (kein Kanal)".into() } } else { "post:river-bet (kein Kanal)".into() } } Choice::Raise { .. } if raw.to_call == 0.0 => "post:value/semi-bet (kein Kanal)".into(), Choice::Check => "post:check-ohne-cbet-lage (kein Kanal)".into(), _ if raw.to_call > 0.0 => { format!("post:gegen-einsatz-{} (kein Kanal)", if raw.street == Street::Flop { "flop" } else { "turn" }) } _ => "post:sonst".into(), } })(); let conf = raw.live_villains().filter_map(|v| v.profile).map(|p| confidence(&p)).fold(f64::NAN, f64::max); format!("diag:{code} conf={conf:.2}") } #[cfg(test)] mod tests { use super::*; #[test] fn the_trust_region_holds_the_kl_ball() { assert_eq!(bounded(0.9, 0.45, 0.1), 0.45, "below the floor: blind default"); let f = bounded(0.95, 0.45, 0.8); assert!(f > 0.45 && f < 0.95); assert!(kl(f, 0.45) <= KL_PER_CONFIDENCE * 0.8 + 1e-9); // a small move inside the ball is just the confidence pull let g = bounded(0.50, 0.45, 0.8); assert!((g - (0.45 + 0.8 * 0.05)).abs() < 1e-12); // monotone in confidence assert!(bounded(0.95, 0.45, 0.5) < bounded(0.95, 0.45, 0.9)); assert_eq!(bounded(f64::NAN, 0.45, 0.9), 0.45); } #[test] fn the_switch_names_its_channels() { assert_eq!(Channels::parse(""), Channels::default()); assert_eq!(Channels::parse("0"), Channels::default()); let all = Channels::parse("1"); assert!(all.cbet && all.bluff_veto && all.bluff_catch && all.thin_value && all.light_three_bet); let some = Channels::parse("cb"); assert!(some.cbet && some.bluff_veto && !some.bluff_catch && !some.thin_value && !some.light_three_bet); assert!(Channels::parse("3").light_three_bet); assert!(!all.steal, "`1` keeps its measured meaning: steal must be named"); assert!(Channels::parse("cbrw3s").steal && Channels::parse("s").steal); assert!(!Channels::parse("s").cbet); assert!(!all.three_bet_behind && Channels::parse("m").three_bet_behind && !Channels::parse("m").steal); } }