From 9c318660c2399e3eefeabdbb482ee5bb29745878 Mon Sep 17 00:00:00 2001 From: Marc Mintel Date: Fri, 30 Oct 2026 12:00:35 +0100 Subject: [PATCH] Stichprobe je Gegner und reads: der Kern vertraut duennen Werten weniger und sagt, wie er sieht Opponent stats come without a hand count, so 70 % VPIP over two hands counted like a long record, and nobody could see how the engine read a player. Optional profile.hands pulls frequencies toward the population (w = hands / (hands + 30)); without it nothing changes. The response gains `reads` (seat, style, foldChance, trust) next to the contract keys; VERTRAG.md is untouched. Co-Authored-By: Claude Opus 5.5 --- src/exploit/mod.rs | 57 +++++++++++----------- src/exploit/sample.rs | 49 +++++++++++++++++++ src/wire/decode_villain.rs | 82 ++++++++++++++++--------------- src/wire/mod.rs | 1 + src/wire/reads.rs | 60 +++++++++++++++++++++++ src/wire/respond.rs | 23 ++++++--- tests/exploit_sample.rs | 98 ++++++++++++++++++++++++++++++++++++++ 7 files changed, 297 insertions(+), 73 deletions(-) create mode 100644 src/exploit/sample.rs create mode 100644 src/wire/reads.rs create mode 100644 tests/exploit_sample.rs diff --git a/src/exploit/mod.rs b/src/exploit/mod.rs index b7d5724f..b998513e 100644 --- a/src/exploit/mod.rs +++ b/src/exploit/mod.rs @@ -1,28 +1,29 @@ -//! Exploitation layer: reads opponent profiles, moves thresholds and range guesses. - -pub mod adjust; -pub mod band_bounds; -pub mod band_stretch; -pub mod bet_ratio; -pub mod bluff_share; -pub mod call_floor; -pub mod fold_chance; -pub mod fold_equity_scale; -pub mod made_ladder; -pub mod pot_trace; -pub mod preflop_role; -pub mod profile; -pub mod range_guess; -pub mod range_model; -pub mod range_spec; -pub mod range_narrowing; -pub mod role_band; -pub mod role_from_history; -pub mod size_notch; -pub mod street_continuation; -pub mod steal_width; -pub mod style; -pub mod style_rung; -pub mod style_shift; -pub mod table_fold; -pub mod thresholds; +//! Exploitation layer: reads opponent profiles, moves thresholds and range guesses. + +pub mod adjust; +pub mod band_bounds; +pub mod band_stretch; +pub mod bet_ratio; +pub mod bluff_share; +pub mod call_floor; +pub mod fold_chance; +pub mod fold_equity_scale; +pub mod made_ladder; +pub mod pot_trace; +pub mod preflop_role; +pub mod profile; +pub mod range_guess; +pub mod range_model; +pub mod range_spec; +pub mod range_narrowing; +pub mod role_band; +pub mod role_from_history; +pub mod sample; +pub mod size_notch; +pub mod street_continuation; +pub mod steal_width; +pub mod style; +pub mod style_rung; +pub mod style_shift; +pub mod table_fold; +pub mod thresholds; diff --git a/src/exploit/sample.rs b/src/exploit/sample.rs new file mode 100644 index 00000000..f523f499 --- /dev/null +++ b/src/exploit/sample.rs @@ -0,0 +1,49 @@ +//! How much a profile is worth: its sample. Opponent statistics come without a hand count, so +//! the caller sends one (`villains[].profile.hands`, extension, not in VERTRAG.md). Few hands +//! mean the numbers are mostly noise; they are pulled toward the population before anything +//! reads them. +//! +//! | step | rule | +//! |---|---| +//! | trust | `w = hands / (hands + PRIOR_HANDS)`; no, negative or broken count: 0 | +//! | shrink | each known frequency `x` becomes `p + w * (x - p)` with the population `p` in `PRIOR` | +//! | absent | a missing frequency stays missing; a profile without `hands` is used as given | + +use crate::exploit::profile::Profile; + +/// Hands at which the sample and the population weigh the same (`trust` 0.5). +pub const PRIOR_HANDS: f64 = 30.0; + +/// The population an unknown opponent is assumed to be: a regular of the stock. +pub const PRIOR: Profile = Profile { + vpip: Some(0.28), + pfr: Some(0.18), + fold_to_bet: Some(0.45), + aggression: Some(0.35), +}; + +/// Weight of the sample in `[0, 1)`. +pub fn trust(hands: f64) -> f64 { + if hands.is_nan() || hands <= 0.0 { + return 0.0; + } + hands / (hands + PRIOR_HANDS) +} + +fn pull(x: Option, p: Option, w: f64) -> Option { + match (x.filter(|v| !v.is_nan()), p) { + (Some(x), Some(p)) => Some(p + w * (x - p)), + (x, _) => x, + } +} + +/// The profile as the engine should believe it after `hands` hands. +pub fn shrink(profile: &Profile, hands: f64) -> Profile { + let w = trust(hands); + Profile { + vpip: pull(profile.vpip, PRIOR.vpip, w), + pfr: pull(profile.pfr, PRIOR.pfr, w), + fold_to_bet: pull(profile.fold_to_bet, PRIOR.fold_to_bet, w), + aggression: pull(profile.aggression, PRIOR.aggression, w), + } +} diff --git a/src/wire/decode_villain.rs b/src/wire/decode_villain.rs index 2d88de2c..8cb0c475 100644 --- a/src/wire/decode_villain.rs +++ b/src/wire/decode_villain.rs @@ -1,38 +1,44 @@ -use crate::exploit::profile::Profile; -use crate::fault::Fault; -use crate::game::Villain; -use crate::json::field::{at, join, optional}; -use crate::json::member::{flag_member, number_member, opt_items_member, opt_number_member, u8_member}; -use crate::json::Value; - -fn profile(villain: &Value, path: &str) -> Result, Fault> { - let Some(object) = optional(villain, path, "profile")? else { - return Ok(None); - }; - let at_profile = join(path, "profile"); - Ok(Some(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")?, - })) -} - -fn villain(value: &Value, path: &str) -> Result { - Ok(Villain { - seat: u8_member(value, path, "seat")?, - stack: number_member(value, path, "stack")?, - folded: flag_member(value, path, "folded")?, - profile: profile(value, path)?, - }) -} - -/// `villains`: optional array; absent means none. -pub fn villains(root: &Value) -> Result, Fault> { - opt_items_member(root, "", "villains")? - .unwrap_or(&[]) - .iter() - .enumerate() - .map(|(i, v)| villain(v, &at("villains", i))) - .collect() -} +use crate::exploit::profile::Profile; +use crate::exploit::sample::shrink; +use crate::fault::Fault; +use crate::game::Villain; +use crate::json::field::{at, join, optional}; +use crate::json::member::{flag_member, number_member, opt_items_member, opt_number_member, u8_member}; +use crate::json::Value; + +fn profile(villain: &Value, path: &str) -> Result, Fault> { + let Some(object) = optional(villain, path, "profile")? else { + return Ok(None); + }; + 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")?, + }; + // `hands` (extension, exploit::sample): with it, few hands count little + Ok(Some(match opt_number_member(object, &at_profile, "hands")? { + Some(hands) => shrink(&raw, hands), + None => raw, + })) +} + +fn villain(value: &Value, path: &str) -> Result { + Ok(Villain { + seat: u8_member(value, path, "seat")?, + stack: number_member(value, path, "stack")?, + folded: flag_member(value, path, "folded")?, + profile: profile(value, path)?, + }) +} + +/// `villains`: optional array; absent means none. +pub fn villains(root: &Value) -> Result, Fault> { + opt_items_member(root, "", "villains")? + .unwrap_or(&[]) + .iter() + .enumerate() + .map(|(i, v)| villain(v, &at("villains", i))) + .collect() +} diff --git a/src/wire/mod.rs b/src/wire/mod.rs index 98674d02..138edfbe 100644 --- a/src/wire/mod.rs +++ b/src/wire/mod.rs @@ -10,4 +10,5 @@ pub mod decode_name; pub mod decode_tournament; pub mod decode_villain; pub mod encode; +pub mod reads; pub mod respond; diff --git a/src/wire/reads.rs b/src/wire/reads.rs new file mode 100644 index 00000000..aef1aa12 --- /dev/null +++ b/src/wire/reads.rs @@ -0,0 +1,60 @@ +//! Response extension `reads` (not in VERTRAG.md): how the engine read each villain that came +//! with a profile - the style it acts on, the chance it folds to a two-thirds-pot bet, and how +//! much of the profile it trusts (exploit::sample). The caller shows it; nothing decides on it. + +use crate::exploit::fold_chance::{fold_chance, REFERENCE_RATIO}; +use crate::exploit::sample::trust; +use crate::exploit::style::{classify, Style}; +use crate::game::Villain; +use crate::json::Value; + +/// Wire name of a style. +pub fn style_name(style: Style) -> &'static str { + match style { + Style::Unknown => "unknown", + Style::Nit => "nit", + Style::LooseAggressive => "looseAggressive", + Style::CallingStation => "callingStation", + Style::Regular => "regular", + } +} + +fn round2(x: f64) -> f64 { + (x * 100.0).round() / 100.0 +} + +/// `hands` of the villain on `seat` in the request, if it sent one. +fn hands_of(request: &Value, seat: u8) -> Option { + let Value::Object(root) = request else { return None }; + let Some((_, Value::Array(villains))) = root.iter().find(|(k, _)| k == "villains") else { return None }; + villains.iter().find_map(|v| { + let Value::Object(f) = v else { return None }; + let on_seat = f.iter().any(|(k, s)| k == "seat" && *s == Value::Number(f64::from(seat))); + let Some((_, Value::Object(p))) = f.iter().find(|(k, _)| k == "profile") else { return None }; + if !on_seat { + return None; + } + p.iter().find_map(|(k, h)| match (k.as_str(), h) { + ("hands", Value::Number(n)) => Some(*n), + _ => None, + }) + }) +} + +/// One entry per villain with a profile; None when there is none. +pub fn reads(request: &Value, villains: &[Villain]) -> Option { + let out: Vec = villains + .iter() + .filter_map(|v| { + let p = v.profile.as_ref()?; + let w = hands_of(request, v.seat).map_or(1.0, trust); + Some(Value::Object(vec![ + ("seat".to_string(), Value::Number(f64::from(v.seat))), + ("style".to_string(), Value::String(style_name(classify(p)).to_string())), + ("foldChance".to_string(), Value::Number(round2(fold_chance(Some(p), REFERENCE_RATIO, false)))), + ("trust".to_string(), Value::Number(round2(w))), + ])) + }) + .collect(); + (!out.is_empty()).then_some(Value::Array(out)) +} diff --git a/src/wire/respond.rs b/src/wire/respond.rs index a6cd17e7..b71cd0e3 100644 --- a/src/wire/respond.rs +++ b/src/wire/respond.rs @@ -1,6 +1,7 @@ use super::decode::decode; use super::decode_extras::extras; use super::encode::{encode, encode_value}; +use super::reads::reads; use crate::engine::decide::{decide, decide_with}; use crate::engine::double_board::decide_double; use crate::engine::run_twice::{run_twice, RunTwice}; @@ -10,7 +11,9 @@ use crate::guard::enforce::enforce; use crate::guard::validate::check; use crate::json::{parse, render, Value}; -fn pipeline(line: &str) -> Result<(Decision, Option<(RunTwice, String)>), Fault> { +type Answer = (Decision, Option<(RunTwice, String)>, Option); + +fn pipeline(line: &str) -> Result { let value = parse(line)?; let spot: Spot = check(decode(&value)?)?; let extras = extras(&value)?; @@ -22,20 +25,26 @@ fn pipeline(line: &str) -> Result<(Decision, Option<(RunTwice, String)>), Fault> }, }; let rit = extras.rit_offered.then(|| run_twice(&spot, &decision)); - Ok((decision, rit)) + Ok((decision, rit, reads(&value, &spot.villains))) } /// One request line in, one response line out (without trailing newline). Never panics. -/// With `ritOffered` the answer carries `rit` and `ritReason` after the contract keys. +/// With `ritOffered` the answer carries `rit` and `ritReason` after the contract keys; with +/// villain profiles it carries `reads` (wire::reads). pub fn respond(line: &str) -> String { match pipeline(line) { - Ok((decision, None)) => encode(&decision), - Ok((decision, Some((answer, reason)))) => { + Ok((decision, None, None)) => encode(&decision), + Ok((decision, rit, gelesen)) => { let Value::Object(mut felder) = encode_value(&decision) else { return encode(&decision); }; - felder.push(("rit".to_string(), Value::String(answer.name().to_string()))); - felder.push(("ritReason".to_string(), Value::String(reason))); + if let Some((answer, reason)) = rit { + felder.push(("rit".to_string(), Value::String(answer.name().to_string()))); + felder.push(("ritReason".to_string(), Value::String(reason))); + } + if let Some(r) = gelesen { + felder.push(("reads".to_string(), r)); + } render(&Value::Object(felder)) } Err(fault) => encode(&Decision::abstain(format!("invalid request: {fault}"))), diff --git a/tests/exploit_sample.rs b/tests/exploit_sample.rs new file mode 100644 index 00000000..cc4f885e --- /dev/null +++ b/tests/exploit_sample.rs @@ -0,0 +1,98 @@ +//! Opponent sample size (request extension `villains[].profile.hands`) and what the engine read +//! (response extension `reads`). Neither is in VERTRAG.md. +//! +//! * Without `hands` a profile is used as given (old requests unchanged). +//! * With `hands`, every frequency is pulled toward the population: `p + w * (x - p)` with +//! `w = hands / (hands + PRIOR_HANDS)`. +//! * The response carries `reads`: per villain with a profile `{seat, style, foldChance, trust}`; +//! none without profiles. + +use pokerfreak::exploit::profile::Profile; +use pokerfreak::exploit::sample::{shrink, trust, PRIOR_HANDS, PRIOR}; +use pokerfreak::wire::respond::respond; + +fn station() -> Profile { + Profile { vpip: Some(0.60), pfr: Some(0.05), fold_to_bet: Some(0.15), aggression: Some(0.20) } +} + +#[test] +fn trust_grows_with_hands() { + assert_eq!(trust(0.0), 0.0); + assert!((trust(PRIOR_HANDS) - 0.5).abs() < 1e-12); + assert!(trust(1000.0) > 0.95); + assert_eq!(trust(-5.0), 0.0, "nonsense counts as no hands"); + assert_eq!(trust(f64::NAN), 0.0); +} + +#[test] +fn no_hands_is_the_population() { + let p = shrink(&station(), 0.0); + assert_eq!((p.vpip, p.pfr, p.fold_to_bet, p.aggression), + (Some(PRIOR.vpip.unwrap()), Some(PRIOR.pfr.unwrap()), Some(PRIOR.fold_to_bet.unwrap()), + Some(PRIOR.aggression.unwrap()))); +} + +#[test] +fn many_hands_keep_the_reads() { + let p = shrink(&station(), 10_000.0); + assert!((p.vpip.unwrap() - 0.60).abs() < 0.01); + assert!((p.fold_to_bet.unwrap() - 0.15).abs() < 0.01); +} + +#[test] +fn missing_values_stay_missing() { + let p = shrink(&Profile { vpip: Some(0.5), ..Profile::default() }, 30.0); + assert!(p.pfr.is_none() && p.fold_to_bet.is_none() && p.aggression.is_none()); +} + +fn request(profile: &str) -> String { + format!( + r#"{{"variant":"NLHE","bigBlind":1.0,"seats":2,"heroSeat":1,"buttonSeat":2, +"heroCards":[{{"rank":"ACE","suit":"SPADES"}},{{"rank":"KING","suit":"SPADES"}}], +"board":{{"FLOP":null,"TURN":null,"RIVER":null}},"street":"PREFLOP","pot":1.5,"toCall":0.5,"heroStack":100.0, +"legalActions":["FOLD","CALL","RAISE"],"minRaiseTo":2.0,"maxRaiseTo":100.0, +"villains":[{{"seat":2,"stack":100.0,"folded":false{profile}}}],"seed":7}}"# + ) +} + +#[test] +fn the_answer_says_how_it_read_each_villain() { + let answer = respond(&request(r#","profile":{"vpip":0.6,"pfr":0.05,"foldToBet":0.15,"hands":5000}"#)); + assert!(answer.contains("\"reads\":["), "{answer}"); + let reads = &answer; + assert!(reads.contains(r#""seat":2"#), "{answer}"); + assert!(reads.contains(r#""style":"callingStation""#), "{answer}"); + assert!(reads.contains(r#""trust":0.99"#), "{answer}"); + assert!(reads.contains(r#""foldChance":0.15"#), "{answer}"); +} + +#[test] +fn few_hands_read_as_regular() { + // the same loose numbers over 2 hands: pulled almost to the population - not a station yet + let answer = respond(&request(r#","profile":{"vpip":0.6,"pfr":0.05,"foldToBet":0.15,"hands":2}"#)); + assert!(answer.contains("\"reads\":["), "{answer}"); + let reads = &answer; + assert!(reads.contains(r#""style":"regular""#), "{answer}"); + assert!(reads.contains(r#""trust":0.06"#), "{answer}"); +} + +#[test] +fn without_hands_the_profile_counts_fully() { + let answer = respond(&request(r#","profile":{"vpip":0.6,"pfr":0.05,"foldToBet":0.15}"#)); + assert!(answer.contains("\"reads\":["), "{answer}"); + let reads = &answer; + assert!(reads.contains(r#""style":"callingStation""#), "{answer}"); + assert!(reads.contains(r#""trust":1"#), "{answer}"); +} + +#[test] +fn no_profile_no_reads() { + let answer = respond(&request("")); + assert!(!answer.contains("\"reads\""), "{answer}"); +} + +#[test] +fn a_malformed_hands_count_is_an_invalid_request() { + let answer = respond(&request(r#","profile":{"vpip":0.6,"hands":"viele"}"#)); + assert!(answer.contains("invalid request"), "{answer}"); +}