Files
pokerfreak/src/wire/decode_villain.rs
T

369 lines
18 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 crate::exploit::mark::with_mark;
use crate::exploit::profile::Profile;
use crate::exploit::sample::{hud_profile, shrink_aggression, shrink_street, CHECK_RAISE_ANCHOR, FOLD_TO_THREE_BET_ANCHOR};
use crate::fault::Fault;
use crate::game::Villain;
use crate::json::field::{at, join, optional, text};
use crate::json::member::{flag_member, number_member, opt_items_member, opt_number_member, u8_member};
use crate::json::Value;
/// `profile.shown` of the memory handover (`lesen/uebergabe.py`, plan D3): the preflop-class
/// distribution of the shown hands per line, already shrunk toward the line population. The two
/// river lines ("river-aggr", "river-passiv"); a missing line takes the player's overall `klassen`.
/// Absent, or no usable distribution: `None` (the profile unchanged).
fn shown_river(object: &Value, path: &str) -> Result<Option<[[f64; crate::exploit::range_spec::CLASSES]; 2]>, Fault> {
use crate::exploit::range_spec::CLASSES;
let Some(shown) = optional(object, path, "shown")? else { return Ok(None) };
let at_shown = join(path, "shown");
let dist = |v: &Value, at: &str| -> Result<Option<[f64; CLASSES]>, Fault> {
Ok(match opt_items_member(v, at, "klassen")? {
Some(items) if items.len() == CLASSES => {
let mut d = [0.0; CLASSES];
for (i, x) in items.iter().enumerate() {
match x {
Value::Number(n) if n.is_finite() && *n >= 0.0 => d[i] = *n,
_ => return Ok(None),
}
}
(d.iter().sum::<f64>() > 0.0).then_some(d)
}
_ => None,
})
};
let overall = dist(shown, &at_shown)?;
let at_lines = join(&at_shown, "linien");
let line = |name: &str| -> Result<Option<[f64; CLASSES]>, Fault> {
let Some(lines) = optional(shown, &at_shown, "linien")? else { return Ok(None) };
let Some(l) = optional(lines, &at_lines, name)? else { return Ok(None) };
dist(l, &join(&at_lines, name))
};
let (aggr, passiv) = (line("river-aggr")?.or(overall), line("river-passiv")?.or(overall));
Ok(match (aggr, passiv) {
(Some(a), Some(p)) => Some([a, p]),
_ => None,
})
}
/// Schalter `PROFIL_OHNE=<Feld>,<Feld>,...` (einmal gelesen; aus = bitgleich): diese Glieder des Gegnerprofils gelten als
/// nicht geschickt (Drahtnamen wie `foldToBet`, `aggression`, `reads`). Misst und schaltet einzelne Profil-Teile ab, ohne
/// den Laeufer zu aendern (messung/basis/PROFILTEILE.md). Bleibt kein Glied uebrig, ist der Gegner ungelesen.
fn profil_ohne() -> &'static [String] {
use std::sync::OnceLock;
static O: OnceLock<Vec<String>> = OnceLock::new();
O.get_or_init(|| {
std::env::var("PROFIL_OHNE")
.map(|v| v.split(',').map(|t| t.trim().to_string()).filter(|t| !t.is_empty()).collect())
.unwrap_or_default()
})
}
fn profile(villain: &Value, path: &str) -> Result<Option<Profile>, Fault> {
let Some(object) = optional(villain, path, "profile")? else {
return Ok(None);
};
let gefiltert;
let object = match (profil_ohne(), object) {
(ohne, Value::Object(glieder)) if !ohne.is_empty() => {
let rest: Vec<(String, Value)> = glieder.iter().filter(|(k, _)| !ohne.iter().any(|o| o == k)).cloned().collect();
if rest.is_empty() {
return Ok(None);
}
gefiltert = Value::Object(rest);
&gefiltert
}
_ => object,
};
let at_profile = join(path, "profile");
let raw = Profile {
vpip: opt_number_member(object, &at_profile, "vpip")?,
pfr: opt_number_member(object, &at_profile, "pfr")?,
fold_to_bet: opt_number_member(object, &at_profile, "foldToBet")?,
aggression: opt_number_member(object, &at_profile, "aggression")?,
// Per-street reads come as raw rate + sample (`streets` below) and are shrunk toward the pooled
// read there; nothing unshrunk lands here.
turn_aggression: None,
river_aggression: None,
street_fold_to_bet: [None; 3],
// HUD extras (lesen/profil.py DURCHGEREICHT): same client names on the wire.
cbet: opt_number_member(object, &at_profile, "cbet")?,
fold_to_cbet: opt_number_member(object, &at_profile, "foldToCbet")?,
three_bet: opt_number_member(object, &at_profile, "threeBet")?,
fold_to_three_bet: opt_number_member(object, &at_profile, "foldToThreeBet")?,
steal: opt_number_member(object, &at_profile, "steal")?,
check_raise: opt_number_member(object, &at_profile, "checkRaise")?,
wtsd: opt_number_member(object, &at_profile, "wtsd")?,
wsd: opt_number_member(object, &at_profile, "wsd")?,
// Not on the wire: confidence is derived from `hands` by `shrink` below (half-life PRIOR_HANDS).
confidence: None,
aggression_confidence: None,
// Showdown read (extension, lesen/profil.py mit_zaehlung under GEGNER_SHOWDOWN): air share of the
// player's river bets seen at showdown and how many. Raw: the river gearbox blends it by its
// own count (`engine::river_subgame::river_bluff_aggression`).
river_bluff_share: opt_number_member(object, &at_profile, "riverBluffShare")?,
river_bluff_shown: opt_number_member(object, &at_profile, "riverBluffShown")?,
// Only from the memory handover (`reads`, below).
flop_aggression: None,
shown_river: shown_river(object, &at_profile)?,
fold_to_steal: None,
fold_to_raise: None,
// Raise frequency facing a postflop bet (`RERAISE_TIEFE` gate): a forced read for measurement
// (`LBR_PROFIL`); live it comes counted through `reads.raiseToBet` below. Absent: None.
raise_to_bet: opt_number_member(object, &at_profile, "raiseToBet")?,
raise_to_bet_n: None,
reraise_to_raise: opt_number_member(object, &at_profile, "reraiseToRaise")?,
size_gain: None,
fold_only: false,
pool_baseline: false,
pool_raise_value: false,
bet_open: [None; 3],
vorwissen: crate::exploit::profile::Vorwissen::LEER,
};
// `hands` (extension, exploit::sample): with it, few hands count little; the line stats rest on
// the fraction of hands their spot arises in (`hud_profile`, shared with the sim's HUD mode).
let shrunk = match opt_number_member(object, &at_profile, "hands")? {
Some(hands) => hud_profile(&raw, hands),
None => raw,
};
// `aggressionActions` (extension, lesen/profil.py): the postflop moves the aggression was measured
// over. Aggression then trusts its OWN sample, not the HUD hand count.
let pooled = match opt_number_member(object, &at_profile, "aggressionActions")? {
Some(actions) => shrink_aggression(shrunk, raw.aggression, actions),
None => shrunk,
};
let lined = streets(object, &at_profile, pooled)?;
let mut gelesen = with_reads(object, &at_profile, lined)?;
// `vorwissen.roh` (lesen/vorwissen/draht.py): rohe Haende des Spielers im Jahresprofil; nur `SPAET_FOLD` liest sie.
if let Ok(Some(vw)) = optional(object, &at_profile, "vorwissen") {
gelesen.vorwissen.haende_roh = opt_number_member(vw, &join(&at_profile, "vorwissen"), "roh").ok().flatten().filter(|h| h.is_finite() && *h >= 0.0);
}
Ok(Some(gelesen))
}
/// One counted read of the memory handover (`profile.reads.<name>`, FORMAT-gegner-uebergabe):
/// `n` chances, `k` hits, optional hierarchical `prior` `[α, β]`.
struct CountedRead {
n: f64,
k: f64,
prior: Option<(f64, f64)>,
}
impl CountedRead {
/// Posterior mean `(k + α) / (n + α + β)`; without a `prior` the core's anchor at `strength`
/// pseudo-chances. `None` without a chance or a usable anchor.
fn posterior(&self, anchor: Option<f64>, strength: f64) -> Option<f64> {
if !(self.n > 0.0) {
return None;
}
let (a, b) = match self.prior {
Some(ab) => ab,
None => {
let m = anchor.filter(|m| m.is_finite())?.clamp(0.0, 1.0);
(m * strength, (1.0 - m) * strength)
}
};
let total = self.n + a + b;
(total > 0.0).then(|| ((self.k + a) / total).clamp(0.0, 1.0))
}
/// The read's own confidence `n / (n + α + β)` (prior strength or `strength`).
fn confidence(&self, strength: f64) -> f64 {
let s = self.prior.map_or(strength, |(a, b)| a + b);
if self.n > 0.0 { self.n / (self.n + s) } else { 0.0 }
}
}
fn counted(reads: &Value, path: &str, name: &str) -> Result<Option<CountedRead>, Fault> {
let Some(r) = optional(reads, path, name)? else { return Ok(None) };
let at_read = join(path, name);
let (Some(n), Some(k)) = (opt_number_member(r, &at_read, "n")?, opt_number_member(r, &at_read, "k")?) else {
return Ok(None);
};
if !(n.is_finite() && k.is_finite()) || n <= 0.0 || k < 0.0 || k > n {
return Ok(None);
}
let prior = match opt_items_member(r, &at_read, "prior")? {
Some([Value::Number(a), Value::Number(b)]) if *a > 0.0 && *b > 0.0 => Some((*a, *b)),
_ => None,
};
Ok(Some(CountedRead { n, k, prior }))
}
/// Pseudo-chances of the core's own anchor for a line read without a delivered prior.
const LINE_PRIOR: f64 = 15.0;
/// Population anchors of reads that have none in `sample::PRIOR`.
const CBET_ANCHOR: f64 = 0.60;
const THREE_BET_ANCHOR: f64 = 0.07;
const STEAL_ANCHOR: f64 = 0.35;
const FOLD_TO_STEAL_ANCHOR: f64 = 0.65;
const FOLD_TO_RAISE_ANCHOR: f64 = 0.45;
/// Strength of the counted raise-facing-a-bet read (= `sim::memory`); its anchor is the core's 0.30 or
/// the stake pool's under `POOL_STUFE=rtb` (`exploit::pool_stufe::rtb_anchor`).
const RAISE_TO_BET_PRIOR: f64 = 10.0;
/// `reads` (extension, the memory handover `lesen/uebergabe.py`, switch GEGNER_GEDAECHTNIS): counted
/// reads with their true sample replace the HUD/shrunk rates, one posterior per read; the confidences
/// rise to the counted samples. Absent or empty: the profile unchanged (bit-identical).
fn with_reads(object: &Value, path: &str, p: Profile) -> Result<Profile, Fault> {
let Some(reads) = optional(object, path, "reads")? else { return Ok(p) };
let path = &join(path, "reads");
let get = |name: &str| counted(reads, path, name);
let mut out = p;
let pr = crate::exploit::sample::PRIOR;
if let Some(r) = get("vpip")? {
out.vpip = r.posterior(pr.vpip, crate::exploit::sample::PRIOR_HANDS).or(out.vpip);
let c = r.confidence(crate::exploit::sample::PRIOR_HANDS);
out.confidence = Some(out.confidence.unwrap_or(0.0).max(c));
}
if let Some(r) = get("pfr")? {
out.pfr = r.posterior(pr.pfr, crate::exploit::sample::PRIOR_HANDS).or(out.pfr);
}
if let Some(r) = get("foldToBet")? {
out.fold_to_bet = r.posterior(pr.fold_to_bet, crate::exploit::sample::PRIOR_HANDS).or(out.fold_to_bet);
}
if let Some(r) = get("aggression")? {
out.aggression = r.posterior(pr.aggression, crate::exploit::sample::AGGRESSION_HALF).or(out.aggression);
out.aggression_confidence = Some(r.confidence(crate::exploit::sample::AGGRESSION_HALF));
}
let pooled_aggr = out.aggression;
if let Some(r) = get("flopAggression")? {
out.flop_aggression = r.posterior(pooled_aggr, crate::exploit::sample::STREET_PRIOR);
}
if let Some(r) = get("turnAggression")? {
out.turn_aggression = r.posterior(pooled_aggr, crate::exploit::sample::STREET_PRIOR).or(out.turn_aggression);
}
if let Some(r) = get("riverAggression")? {
out.river_aggression = r.posterior(pooled_aggr, crate::exploit::sample::STREET_PRIOR).or(out.river_aggression);
}
let pooled_fold = out.fold_to_bet;
for (i, name) in ["flopFoldToBet", "turnFoldToBet", "riverFoldToBet"].iter().enumerate() {
if let Some(r) = get(name)? {
out.street_fold_to_bet[i] = r.posterior(pooled_fold, crate::exploit::sample::STREET_PRIOR).or(out.street_fold_to_bet[i]);
}
}
let fold_anchor = pooled_fold.or(Some(crate::exploit::fold_chance::DEFAULT_FOLD_TO_BET));
if let Some(r) = get("foldToCbet")? {
out.fold_to_cbet = r.posterior(fold_anchor, LINE_PRIOR).or(out.fold_to_cbet);
}
if let Some(r) = get("foldToThreeBet")? {
out.fold_to_three_bet = r.posterior(Some(FOLD_TO_THREE_BET_ANCHOR), LINE_PRIOR).or(out.fold_to_three_bet);
}
if let Some(r) = get("checkRaise")? {
out.check_raise = r.posterior(Some(CHECK_RAISE_ANCHOR), crate::exploit::sample::CHECK_RAISE_KAPPA).or(out.check_raise);
}
if let Some(r) = get("cbet")? {
out.cbet = r.posterior(Some(CBET_ANCHOR), LINE_PRIOR).or(out.cbet);
}
if let Some(r) = get("threeBet")? {
out.three_bet = r.posterior(Some(THREE_BET_ANCHOR), LINE_PRIOR).or(out.three_bet);
}
if let Some(r) = get("steal")? {
out.steal = r.posterior(Some(STEAL_ANCHOR), LINE_PRIOR).or(out.steal);
}
// The three reads counted since 14.11. (gedaechtnis-voll 9b37738), anchors as eichung.MOTOR.
if let Some(r) = get("foldToSteal")? {
out.fold_to_steal = r.posterior(Some(FOLD_TO_STEAL_ANCHOR), crate::exploit::sample::PRIOR_HANDS);
}
if let Some(r) = get("foldToRaise")? {
out.fold_to_raise = r.posterior(Some(FOLD_TO_RAISE_ANCHOR), LINE_PRIOR);
}
// Raises facing a postflop bet over folds + calls + raises facing one (lesen/zaehler.py raiseToBet):
// shrunk toward RAISE_TO_BET_ANCHOR with RAISE_TO_BET_PRIOR pseudo-samples, exactly as the sim
// memory (`sim::memory`), so ladder and live read the same number. Only `RERAISE_TIEFE` uses it.
// Open bets over checks + open bets per street (lesen/zaehler.py flop|turn|riverBetOpen): the raw
// counts; `exploit::bet_open` shrinks them toward the pool (sim::memory bet_open, same counts).
for (i, name) in ["flopBetOpen", "turnBetOpen", "riverBetOpen"].iter().enumerate() {
if let Some(r) = get(name)? {
out.bet_open[i] = Some((r.k, r.n));
}
}
// Groessenaufgeloeste Reads (VORWISSEN_KERN): <strasse>FoldToBet_<klasse>, riverBluffShown_<klasse>; roh gezaehlt,
// der Kern schrumpft sie je Zelle (`exploit::profile::Zaehlung`). Ohne die Namen: unveraendert.
let zaehlung = |r: CountedRead| crate::exploit::profile::Zaehlung { k: r.k, n: r.n, prior: r.prior };
for (si, s) in ["flop", "turn", "river"].iter().enumerate() {
for (ci, c) in crate::exploit::profile::KLASSEN.iter().enumerate() {
if let Some(r) = get(&format!("{s}FoldToBet_{c}"))? {
out.vorwissen.fold[si][ci] = Some(zaehlung(r));
}
}
}
for (ci, c) in crate::exploit::profile::KLASSEN.iter().enumerate() {
if let Some(r) = get(&format!("riverBluffShown_{c}"))? {
out.vorwissen.bluff_river[ci] = Some(zaehlung(r));
}
if let Some(r) = get(&format!("riverVerlust_{c}"))? {
out.vorwissen.verlust_river[ci] = Some(zaehlung(r));
}
}
if let Some(r) = get("raiseToBet")? {
out.raise_to_bet = r.posterior(Some(crate::exploit::pool_stufe::rtb_anchor()), RAISE_TO_BET_PRIOR);
out.raise_to_bet_n = Some(r.n);
}
// Re-raises when raised after an own postflop bet/raise on that street (lesen/zaehler.py
// reraiseToRaise), same anchor and prior.
if let Some(r) = get("reraiseToRaise")? {
out.reraise_to_raise = r.posterior(Some(crate::exploit::pool_stufe::rtb_anchor()), RAISE_TO_BET_PRIOR);
}
// Shown river bets: raw share and count (the river gearbox blends them by their own count).
if let Some(r) = get("riverBluffShown")? {
if out.river_bluff_shown.is_none() {
out.river_bluff_share = Some(r.k / r.n);
out.river_bluff_shown = Some(r.n);
}
}
Ok(out)
}
/// Per-street reads (extension, lesen/profil.py `strassen`): the rate seen on one street and the moves
/// it rests on, each pulled toward the pooled (already shrunk) read by `shrink_street`. The engine
/// already plays them (turn/river subgame, fold_chance); the session memory fills them in the sim.
fn streets(object: &Value, path: &str, pooled: Profile) -> Result<Profile, Fault> {
let read = |rate: &str, count: &str, anchor: Option<f64>| -> Result<Option<f64>, Fault> {
Ok(match opt_number_member(object, path, count)? {
Some(n) => shrink_street(opt_number_member(object, path, rate)?, n, anchor),
None => None,
})
};
let turn_aggression = read("turnAggression", "turnAggressionActions", pooled.aggression)?;
let river_aggression = read("riverAggression", "riverAggressionActions", pooled.aggression)?;
let street_fold_to_bet = [
read("flopFoldToBet", "flopFacingBet", pooled.fold_to_bet)?,
read("turnFoldToBet", "turnFacingBet", pooled.fold_to_bet)?,
read("riverFoldToBet", "riverFacingBet", pooled.fold_to_bet)?,
];
Ok(Profile {
turn_aggression: turn_aggression.or(pooled.turn_aggression),
river_aggression: river_aggression.or(pooled.river_aggression),
street_fold_to_bet,
..pooled
})
}
/// `marke` (extension, exploit::mark): the client's label fills what the profile does not know.
fn marked_profile(villain: &Value, path: &str) -> Result<Option<Profile>, Fault> {
let measured = profile(villain, path)?;
Ok(match optional(villain, path, "marke")? {
Some(mark) => with_mark(measured, text(mark, &join(path, "marke"))?),
None => measured,
})
}
fn villain(value: &Value, path: &str) -> Result<Villain, Fault> {
Ok(Villain {
seat: u8_member(value, path, "seat")?,
stack: number_member(value, path, "stack")?,
folded: flag_member(value, path, "folded")?,
profile: marked_profile(value, path)?,
})
}
/// `villains`: optional array; absent means none.
pub fn villains(root: &Value) -> Result<Vec<Villain>, Fault> {
crate::exploit::pool_stufe::set_big_blind(number_member(root, "", "bigBlind").unwrap_or(f64::NAN));
opt_items_member(root, "", "villains")?
.unwrap_or(&[])
.iter()
.enumerate()
.map(|(i, v)| villain(v, &at("villains", i)))
.collect()
}