//! Read layer for the postflop subgame solver (plan D1c): how a villain's MEMORY (`Profile`, filled //! from `lesen/zaehler.py`, `lesen/gedaechtnis.py`, the HUD) changes what the solver believes about //! that villain, and how far hero may move off the equilibrium for it. //! //! The solver builds each villain's range from the hand's action history and solves an equilibrium. //! A `RangeRead` then says, per villain: //! //! - **`reweigh`**: tilt the history range by strength percentile. A looser-than-population player //! (vpip above the prior) holds weaker hands for the same line → weight shifts down the range; a //! tighter one → up. `w'(c) = w(c) · exp(tilt · (p − ½))`, total mass kept. //! - **`bluff_share(street, size)`**: the believed air share of the villain's betting range for a bet //! of `size` (pot fraction). Starts at the indifference share `s/(1+2s)`, scaled by the street's //! aggression read against the population, then pulled toward the SHOWN river air share by its //! count (`river_bluff_shown`, half weight at `STREET_PRIOR` bets). //! - **`fold_to_bet(street)`**: the street's fold-to-bet read (already shrunk by its sample on the //! wire), else the pooled read. //! - **`confidence`**: how far the read may be trusted, from the real sample sizes. The solver turns //! it into the KL trust radius (`engine::river_subgame::lambda_from_confidence`): hero's line is //! `argmax E_belief[EV] − λ·KL(σ ‖ σ_equilibrium)`, so a thin read stays at the equilibrium. //! //! No population prior is added here: every field is either the wire read (already shrunk by its own //! sample) or the equilibrium default. `from_profile(None)` is `None` = the solver's baseline exactly. //! Live only behind the switch `GEGNER_RANGE=1` (default off). use super::posterior::DEFAULT_AGGRESSION; use crate::cfr::river_game::Act; use super::profile::Profile; use super::sample::{PRIOR, STREET_PRIOR}; /// How strongly a vpip gap to the population tilts the range: tilt = TILT_SCALE · (prior − vpip)/prior. /// At 1.0 a player twice as loose as the population (vpip 0.56) gets tilt −1: the bottom of the /// history range weighs e^0.5 ≈ 1.65× the top instead of the same. pub const TILT_SCALE: f64 = 1.0; /// The tilt never exceeds this either way (a 90 % vpip player is not infinitely weak). pub const TILT_MAX: f64 = 2.0; /// Range percentile at/above which the believed villain value-bets when it may bet (as the river /// gearbox's `VALUE_RANK`). pub const VALUE_PCT: f64 = 0.60; /// Range percentile at/below which the believed villain may bluff (as `BLUFF_RANK`). pub const BLUFF_PCT: f64 = 0.30; /// The bet size (pot fraction) the believed villain uses when several are offered: the nearest. pub const BELIEVED_BET_FRACTION: f64 = 0.66; /// The read the solver applies to one villain. #[derive(Clone, Copy, Debug, PartialEq)] pub struct RangeRead { /// Range tilt by strength percentile; > 0 stronger than the history range, < 0 weaker. pub tilt: f64, /// Aggression per street `[flop, turn, river]` relative to the population (1 = population). pub aggression_ratio: [Option; 3], /// Shown river air share and how many shown river bets it rests on. pub shown: Option<(f64, f64)>, /// Fold-to-bet per street `[flop, turn, river]` (street read, else pooled). pub fold: [Option; 3], /// Trust in the fold / range reads (`Profile::confidence`), in [0, 1). pub confidence: f64, /// Trust in the bluff reads (`Profile::bluff_read_confidence`), in [0, 1). pub bluff_confidence: f64, } /// Measurement switch (read once): `GEGNER_RANGE=1` lets the river gearbox (`engine::river_subgame`) /// apply the read layer. Default off: bit-identical to before. pub fn on() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); *ON.get_or_init(|| std::env::var("GEGNER_RANGE").as_deref() == Ok("1")) } fn ok(x: Option) -> Option { x.filter(|v| v.is_finite()) } impl RangeRead { /// The read of one villain, or `None` without a profile or without any confidence (the solver /// then plays its equilibrium unchanged). pub fn from_profile(p: Option<&Profile>) -> Option { let p = p?; let confidence = ok(p.confidence).unwrap_or(0.0).clamp(0.0, 0.999); let bluff_confidence = ok(p.bluff_read_confidence()).unwrap_or(0.0).clamp(0.0, 0.999); let shown = match (ok(p.river_bluff_share), ok(p.river_bluff_shown)) { (Some(s), Some(n)) if n > 0.0 => Some((s.clamp(0.0, 1.0), n)), _ => None, }; if confidence <= 0.0 && bluff_confidence <= 0.0 && shown.is_none() { return None; } let prior_vpip = PRIOR.vpip.unwrap_or(0.28); let tilt = ok(p.vpip) .map(|v| (TILT_SCALE * (prior_vpip - v) / prior_vpip).clamp(-TILT_MAX, TILT_MAX)) .unwrap_or(0.0); let pooled = ok(p.aggression); let ratio = |a: Option| ok(a).or(pooled).map(|a| (a / DEFAULT_AGGRESSION).max(0.0)); let fold_pooled = ok(p.fold_to_bet); Some(RangeRead { tilt, aggression_ratio: [ratio(p.flop_aggression), ratio(p.turn_aggression), ratio(p.river_aggression)], shown, fold: [0, 1, 2].map(|i| ok(p.street_fold_to_bet[i]).or(fold_pooled).map(|f| f.clamp(0.0, 1.0))), confidence, bluff_confidence, }) } /// New weights for the villain's history range. `combos[i] = (weight, strength percentile within /// the range in [0, 1])`. Total mass is kept; zero weights stay zero. pub fn reweigh(&self, combos: &[(f64, f64)]) -> Vec { let raw: Vec = combos.iter().map(|(w, p)| w * (self.tilt * (p.clamp(0.0, 1.0) - 0.5)).exp()).collect(); let before: f64 = combos.iter().map(|(w, _)| w).sum(); let after: f64 = raw.iter().sum(); if after <= 0.0 || !after.is_finite() { return combos.iter().map(|(w, _)| *w).collect(); } raw.iter().map(|w| w * before / after).collect() } /// Believed air share of the villain's betting range on `street` (0 flop, 1 turn, 2 river) for a /// bet of `size` × pot. The indifference share `s/(1+2s)` (what makes a bluff-catcher's call break /// even) scaled by the street's aggression ratio, then — on the river — pulled toward the shown /// air share by `n/(n+STREET_PRIOR)`. pub fn bluff_share(&self, street: usize, size: f64) -> f64 { let s = size.max(0.0); let indifferent = s / (1.0 + 2.0 * s); let ratio = self.aggression_ratio.get(street).copied().flatten().unwrap_or(1.0); let from_aggression = (indifferent * ratio).clamp(0.0, 0.95); match self.shown { Some((share, n)) if street == 2 => { let w = n / (n + STREET_PRIOR); from_aggression + w * (share - from_aggression) } _ => from_aggression, } } /// Believed fold-to-bet on `street`, `None` = the solver's own (equilibrium) answer. pub fn fold_to_bet(&self, street: usize) -> Option { self.fold.get(street).copied().flatten() } /// The believed villain's strategy at one decision node, for node-locking in the solver /// (restricted Nash response: villain plays `(1−w)·σ_cfr + w·believed`, `w` = the solver's trust). /// `acts` are the node's actions (sizes = street totals in chips), `pot` the pot before this /// street's bets, `pct` the combo's strength percentile in the villain's (weighted) range. One /// probability per act, or `None` = no opinion (the node stays pure CFR). /// /// - **Facing a bet** (`Fold` and `Call` offered): folds below the street's fold-to-bet read by /// percentile, calls above; never raises (the read says nothing about raising). No fold read → /// `None`. /// - **May bet** (`Check` and `Bet` offered): value-bets from `VALUE_PCT`, bluffs below `BLUFF_PCT` /// with the probability that makes the air share of its betting range `bluff_share(street, size)`, /// checks the middle; one size (nearest `BELIEVED_BET_FRACTION`). No aggression read on the street /// (and, on the river, no shown bets) → `None`. /// /// On flop and turn `pct` is current strength (draw-blind), so the bluff region holds the draws: /// read it as "bets with nothing made", semi-bluffs included. pub fn believed_row(&self, street: u8, acts: &[Act], pot: f64, pct: f64) -> Option> { let st = street as usize; if st > 2 || acts.is_empty() || !pct.is_finite() { return None; } let pct = pct.clamp(0.0, 1.0); let has = |f: fn(&Act) -> bool| acts.iter().any(f); if has(|a| matches!(a, Act::Fold)) && has(|a| matches!(a, Act::Call)) { let f = self.fold_to_bet(st)?; let fold = pct < f; return Some(acts.iter().map(|a| match a { Act::Fold => fold as u8 as f64, Act::Call => !fold as u8 as f64, _ => 0.0, }).collect()); } if has(|a| matches!(a, Act::Check)) && has(|a| matches!(a, Act::Bet(_))) { let read = self.aggression_ratio[st].is_some() || (st == 2 && self.shown.is_some()); if !read || pot <= 0.0 { return None; } let (ix, to) = acts .iter() .enumerate() .filter_map(|(i, a)| if let Act::Bet(x) = a { Some((i, *x)) } else { None }) .min_by(|a, b| (a.1 / pot - BELIEVED_BET_FRACTION).abs().total_cmp(&(b.1 / pot - BELIEVED_BET_FRACTION).abs()))?; let share = self.bluff_share(st, to / pot).clamp(0.0, 0.95); // air share = BLUFF_PCT·b / ((1−VALUE_PCT) + BLUFF_PCT·b) → b let bluff = (share * (1.0 - VALUE_PCT) / (BLUFF_PCT * (1.0 - share))).clamp(0.0, 1.0); let bet = if pct >= VALUE_PCT { 1.0 } else if pct <= BLUFF_PCT { bluff } else { 0.0 }; return Some(acts.iter().enumerate().map(|(i, a)| match a { Act::Check => 1.0 - bet, _ if i == ix => bet, _ => 0.0, }).collect()); } None } /// The confidence a hero line exploiting this read may use: the bluff confidence for lines that /// rest on the villain's betting (calling down, folding bluff-catchers), the plain one otherwise. /// A shown-hand count lifts the bluff confidence to at least its own weight on the river. pub fn trust(&self, against_bets: bool, street: usize) -> f64 { if !against_bets { return self.confidence; } let shown = match self.shown { Some((_, n)) if street == 2 => n / (n + STREET_PRIOR), _ => 0.0, }; self.bluff_confidence.max(shown).min(0.999) } } #[cfg(test)] mod tests { use super::*; fn p() -> Profile { Profile { vpip: Some(0.28), aggression: Some(0.35), fold_to_bet: Some(0.45), confidence: Some(0.6), ..Profile::default() } } #[test] fn no_profile_or_no_trust_is_the_baseline() { assert_eq!(RangeRead::from_profile(None), None); assert_eq!(RangeRead::from_profile(Some(&Profile { vpip: Some(0.5), ..Profile::default() })), None); } #[test] fn population_player_changes_nothing() { let r = RangeRead::from_profile(Some(&p())).unwrap(); assert!(r.tilt.abs() < 1e-12); let w = [(1.0, 0.1), (2.0, 0.5), (1.0, 0.9)]; assert_eq!(r.reweigh(&w), vec![1.0, 2.0, 1.0]); assert!((r.bluff_share(2, 1.0) - 1.0 / 3.0).abs() < 1e-12, "pot bet: indifference share 1/3"); assert_eq!(r.fold_to_bet(1), Some(0.45)); } #[test] fn loose_player_weighs_the_bottom_tight_player_the_top() { let w = [(1.0, 0.0), (1.0, 1.0)]; let loose = RangeRead::from_profile(Some(&Profile { vpip: Some(0.56), ..p() })).unwrap(); let lw = loose.reweigh(&w); assert!((loose.tilt + 1.0).abs() < 1e-12); assert!(lw[0] > lw[1] && (lw[0] + lw[1] - 2.0).abs() < 1e-12, "mass kept: {lw:?}"); let tight = RangeRead::from_profile(Some(&Profile { vpip: Some(0.14), ..p() })).unwrap(); let tw = tight.reweigh(&w); assert!(tw[1] > tw[0]); let mad = RangeRead::from_profile(Some(&Profile { vpip: Some(1.0), ..p() })).unwrap(); assert_eq!(mad.tilt, -TILT_MAX); } #[test] fn street_aggression_and_shown_air_move_the_bluff_share() { let barreler = RangeRead::from_profile(Some(&Profile { river_aggression: Some(0.7), ..p() })).unwrap(); assert!((barreler.bluff_share(2, 1.0) - 2.0 / 3.0).abs() < 1e-12); assert!((barreler.bluff_share(1, 1.0) - 1.0 / 3.0).abs() < 1e-12, "turn falls back to pooled"); let honest = Profile { river_bluff_share: Some(0.0), river_bluff_shown: Some(15.0), ..p() }; let r = RangeRead::from_profile(Some(&honest)).unwrap(); assert!((r.bluff_share(2, 1.0) - 1.0 / 6.0).abs() < 1e-12, "half way to 0 at STREET_PRIOR shown bets"); assert!((r.bluff_share(1, 1.0) - 1.0 / 3.0).abs() < 1e-12, "shown river bets say nothing about the turn"); assert_eq!(r.trust(true, 2), 0.6, "the read itself is stronger"); let unread = RangeRead::from_profile(Some(&Profile { aggression_confidence: Some(0.0), ..honest })).unwrap(); assert!((unread.trust(true, 2) - 0.5).abs() < 1e-12, "shown bets alone earn their own weight"); assert_eq!(unread.trust(true, 1), 0.0); } #[test] fn believed_rows_for_the_solver_lock() { let r = RangeRead::from_profile(Some(&Profile { river_aggression: Some(0.35), ..p() })).unwrap(); let facing = [Act::Fold, Act::Call, Act::Raise(30.0)]; assert_eq!(r.believed_row(2, &facing, 10.0, 0.2), Some(vec![1.0, 0.0, 0.0])); assert_eq!(r.believed_row(2, &facing, 10.0, 0.7), Some(vec![0.0, 1.0, 0.0])); let open = [Act::Check, Act::Bet(3.3), Act::Bet(6.6), Act::Bet(10.0)]; assert_eq!(r.believed_row(2, &open, 10.0, 0.9), Some(vec![0.0, 0.0, 1.0, 0.0]), "value on the 2/3 size"); assert_eq!(r.believed_row(2, &open, 10.0, 0.45), Some(vec![1.0, 0.0, 0.0, 0.0]), "middle checks"); let air = r.believed_row(2, &open, 10.0, 0.1).unwrap(); // the betting range's air share is the indifference share at 0.66 pot let b = air[2]; let share = BLUFF_PCT * b / ((1.0 - VALUE_PCT) + BLUFF_PCT * b); assert!((share - 0.66 / 2.32).abs() < 1e-9, "air share {share}"); assert!((air.iter().sum::() - 1.0).abs() < 1e-12); let unread = RangeRead::from_profile(Some(&Profile { fold_to_bet: None, aggression: None, ..p() })).unwrap(); assert_eq!(unread.believed_row(2, &facing, 10.0, 0.2), None, "no fold read, no opinion"); assert_eq!(unread.believed_row(2, &open, 10.0, 0.2), None, "no aggression read, no opinion"); assert_eq!(r.believed_row(3, &open, 10.0, 0.2), None); } #[test] fn bluff_trust_is_the_weaker_read() { let thin = Profile { aggression_confidence: Some(0.06), ..p() }; let r = RangeRead::from_profile(Some(&thin)).unwrap(); assert_eq!(r.trust(false, 2), 0.6); assert!((r.trust(true, 2) - 0.06).abs() < 1e-12); } }