Benchmark harness and mark detection: paired simulation, reader, benchmark binary

Secures work in progress so the rake branch and the shell repo can be merged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-31 10:36:11 +01:00
co-authored by Claude Opus 5.5
parent 8c2039cdc4
commit 4fa0875765
18 changed files with 939 additions and 17 deletions
+19
View File
@@ -58,6 +58,7 @@ Zufall kommt nur aus `rng::Rng`, das als Wert mitgegeben wird (Seed: Erweiterung
| `buttonSeat` | Sitz des Buttons. Fehlt er, wird er aus `POST_SB`/`POST_BB` in `history` abgeleitet. Sitze dürfen ab 0 oder ab 1 zählen. Ist die Zählung mehrdeutig und ergibt verschiedene Buttons, bleibt die Position unbekannt. |
| `seed` | Seed der Simulation |
| `villains[].profile` | `{vpip, pfr, foldToBet, aggression}`, alle 0..1. Neu ist `aggression`: der Anteil der Postflop-Aktionen, die Bet oder Raise sind. Er steuert den Bluff-Anteil der Gegner-Range. |
| `villains[].marke` | Marke des Clients am Spieler (`Anfaenger`, `FISH`). Füllt fehlende Profilfelder wie bei einer passiven Calling Station (`exploit::mark`, Annahme, nicht gemessen; im Bestand steht bisher keine Marke). Gemessene Werte gewinnen, unbekannte Marken ändern nichts, kein Text → `ABSTAIN`. |
| `history` | Liste `{street, seat, action, amount?}`. `action` ∈ `POST_SB`, `POST_BB`, `POST_ANTE`, `FOLD`, `CHECK`, `CALL`, `BET`, `RAISE`, `ALL_IN`. `amount` = Gesamteinsatz des Sitzes auf dieser Straße nach der Aktion. Fehler nennen den Pfad, z. B. `history[2].action`. |
| `boardDouble` | Zweites Board (Form wie `board`). Je Board entschieden, die höhere Equity gewinnt, bei Gleichstand Board 1. Näherung siehe „Annahmen und Grenzen“. Ungleiche Länge, doppelte Karte, nicht bewertbares Board → `ABSTAIN`. |
| `ritOffered` | Run it twice wird angeboten. Antwort zusätzlich `rit` ∈ `ACCEPT`, `DECLINE`, `ABSTAIN` und `ritReason`. Annehmen, wenn die Equity über dem Bruchpunkt liegt: der Gewinn halbiert sich, aber auch das Risiko. Bruchpunkt `toCall / (pot + toCall)`; ohne offenen Call der faire Anteil `1 / Spieler im Pot`. Ohne Equity → `ABSTAIN`. Die Aktion bleibt dieselbe. |
@@ -293,6 +294,24 @@ Gegen die Calling Station ist der Vorsprung am kleinsten und am unsichersten: Ge
Alle Rückgänge gegen Zufall liegen im Intervall.
## Benchmark: besser oder schlechter als vorher?
```bash
cargo run --release --bin benchmark # gegen benchmarks/baseline.txt, Exit-Code 1 bei Rückschritt
cargo run --release --bin benchmark -- --save # die aktuelle Engine wird die Basislinie
```
Dauer rund 3,5 Minuten (`sim::benchmark`, `sim::paired`, `sim::reader`). Zehn feste Szenarien, 100 bb, ohne Rake und Antes: heads-up (1 000 Austeilungen) und 6-max (150) gegen Reg, Nit, Maniac, Fisch und Calling Station. Die vier ersten sehen ihre Karten an und spielen feste Regeln auf Equity gegen eine Zufallshand. Folder und Zufall fehlen: der eine ist bei +75 gesättigt, der andere überdeckt mit seiner Streuung alles.
**Urteil:** Verglichen wird je Austeilung, die Differenz neu minus Basislinie. Es heißt `BESSER` oder `SCHLECHTER`, wenn das 95-%-Intervall der mittleren Differenz die 0 ausschließt, `gleich`, wenn sich kein Ergebnis bewegt hat, sonst `nicht unterscheidbar`. `GESAMT` ist der Mittelwert der Szenarien, jedes gleich gewichtet. Andere Szenarien, Austeilungen oder Seeds verweigert der Vergleich.
**Grenzen:**
- Die Zahl misst nur gegen diese Bots, nicht gegen GTO und nicht gegen echte Tische. Die absoluten bb/100 sind nicht aussagekräftig, nur die Änderung.
- Bei zehn Szenarien kann eine Änderung auch zufällig in einem davon als `SCHLECHTER` erscheinen. `GESAMT` und die Zahl der geänderten Austeilungen mitlesen.
- Bleibt eine Änderung an der Engine gewollt, die Basislinie mit `--save` neu messen, sonst vergleicht jeder spätere Lauf mit dem alten Stand.
**Wert-Schwelle 0,58 statt 0,62** (`Thresholds::BASE.value_raise`, 2026-10-31): gesamt +11,63 ± 7,17 bb/100, auf frischem Seed +16,75 ± 15,64. Belegt ist der Gewinn nur gegen Calling Station und Maniac, gegen Reg und Nit nicht. 0,66 war schlechter (−9,79 ± 6,46), 0,54 von 0,58 nicht zu unterscheiden, bei fast doppelt so vielen geänderten Austeilungen.
## Große Runde 2026-10-29: Stärke, Einsatzplan, ICM-lite
**Kern** (`engine/size_policy.rs`, `icm/`, Änderungen in `decide`, `options`, `postflop`, `bluff`, `cfr_advice`, `sizing/preflop`):
File diff suppressed because one or more lines are too long
+87
View File
@@ -0,0 +1,87 @@
//! Is the engine better or worse than before? Plays the fixed scenarios of `sim::benchmark` and
//! compares them deal by deal with the saved baseline. Exit code 1 on a regression.
//!
//! ```text
//! cargo run --release --bin benchmark # compare with benchmarks/baseline.txt
//! cargo run --release --bin benchmark -- --save # the current engine becomes the baseline
//! ```
use pokerfreak::sim::benchmark::{parse, render, run_all, verdict_of_run, Report};
use pokerfreak::sim::paired::{Comparison, Verdict};
use std::process::{exit, Command};
use std::time::Instant;
use std::{env, fs};
const BASELINE: &str = "benchmarks/baseline.txt";
fn git(args: &[&str]) -> String {
Command::new("git")
.args(args)
.output()
.map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
.unwrap_or_default()
}
/// The commit, marked when the working tree differs from it.
fn version() -> String {
let dirty = if git(&["status", "--porcelain"]).is_empty() { "" } else { "+lokal" };
format!("{}{dirty}", git(&["rev-parse", "--short", "HEAD"]))
}
fn word(verdict: Verdict) -> &'static str {
match verdict {
Verdict::Identical => "gleich",
Verdict::Better => "BESSER",
Verdict::Worse => "SCHLECHTER",
Verdict::Unclear => "nicht unterscheidbar",
}
}
fn line(name: &str, c: &Comparison) -> String {
format!("{name:<26} {:>+8.2} ± {:>6.2} bb/100 {:>5} geändert {}", c.delta_bb_per_100, c.ci95, c.changed_deals, word(c.verdict))
}
fn print_report(report: &Report) {
for (name, c) in &report.scenarios {
println!("{}", line(name, c));
}
println!("{}", line("GESAMT", &report.overall));
if report.invalid > 0 {
println!("{} ungültige Anfragen: Fehler im Simulator oder der Prüfung", report.invalid);
}
}
fn main() {
let save = env::args().any(|a| a == "--save");
let started = Instant::now();
let run = run_all(&version());
for s in &run.scenarios {
println!("{:<26} {:>+9.2} bb/100 {:>6} Entscheidungen {:>4} ABSTAIN", s.name, s.bb_per_100(), s.decisions, s.abstains);
}
println!("{} in {:.0} s\n", run.label, started.elapsed().as_secs_f64());
if save {
if let Err(e) = fs::write(BASELINE, render(&run)) {
eprintln!("{BASELINE}: {e}");
exit(2);
}
println!("Basislinie gespeichert: {BASELINE}");
return;
}
let base = fs::read_to_string(BASELINE).map_err(|e| format!("{BASELINE}: {e}")).and_then(|t| parse(&t));
let report = base.and_then(|b| {
println!("gegen Basislinie {}", b.label);
verdict_of_run(&b, &run)
});
match report {
Ok(report) => {
print_report(&report);
if report.has_regression() {
exit(1);
}
}
Err(e) => {
eprintln!("{e}");
exit(2);
}
}
}
+33
View File
@@ -0,0 +1,33 @@
//! The client's own label of a player (`villains[].marke`), used until we have numbers.
//!
//! Assumption, not measured: a player the client marks as a beginner or fish plays like a passive
//! calling station. No marked player exists in the logs so far (`specialPlayerTagConfig` is off at
//! the measured tables), so these values are unchecked. Measured fields always win.
use super::profile::Profile;
/// What a beginner or fish is assumed to do where nothing is measured.
const WEAK_PLAYER: Profile = Profile {
vpip: Some(0.45),
pfr: Some(0.10),
fold_to_bet: Some(0.25),
aggression: Some(0.20),
};
fn prior(mark: &str) -> Option<Profile> {
matches!(mark, "Anfaenger" | "FISH").then_some(WEAK_PLAYER)
}
/// `measured` with its missing fields filled from the mark. Unknown marks change nothing.
pub fn with_mark(measured: Option<Profile>, mark: &str) -> Option<Profile> {
let Some(prior) = prior(mark) else {
return measured;
};
let known = measured.unwrap_or_default();
Some(Profile {
vpip: known.vpip.or(prior.vpip),
pfr: known.pfr.or(prior.pfr),
fold_to_bet: known.fold_to_bet.or(prior.fold_to_bet),
aggression: known.aggression.or(prior.aggression),
})
}
+1
View File
@@ -9,6 +9,7 @@ pub mod call_floor;
pub mod fold_chance;
pub mod fold_equity_scale;
pub mod made_ladder;
pub mod mark;
pub mod pot_trace;
pub mod preflop_role;
pub mod profile;
+1 -1
View File
@@ -17,7 +17,7 @@ pub struct Thresholds {
impl Thresholds {
pub const BASE: Thresholds = Thresholds {
call_margin: 0.02,
value_raise: 0.62,
value_raise: 0.58,
abstain_band: 0.015,
fold_equity_scale: 1.0,
range_width_scale: 1.0,
+180
View File
@@ -0,0 +1,180 @@
//! The benchmark: a fixed set of scenarios, run the same way for every version of the engine, so
//! that two runs can be compared deal by deal (`sim::paired`). The runs live in text files; the
//! pure parts are here, the file and clock work in `src/bin/benchmark.rs`.
use super::opponent::Opponent;
use super::paired::{compare, Comparison, Verdict};
use super::reader::Style;
use super::session::{deal_samples, Setup};
use std::thread;
const SEED: u64 = 0x5EED_0001;
const STACK_BB: f64 = 100.0;
const HEADS_UP_DEALS: u32 = 1000;
const SIX_MAX_DEALS: u32 = 150;
pub struct Scenario {
pub name: &'static str,
pub setup: Setup,
}
const fn scenario(name: &'static str, players: u8, opponent: Opponent) -> Scenario {
let deals = if players == 2 { HEADS_UP_DEALS } else { SIX_MAX_DEALS };
Scenario { name, setup: Setup { players, opponent, deals, stack_bb: STACK_BB, seed: SEED } }
}
/// Folder and random opponent are left out: the first is saturated at +75, the second's variance
/// would drown the total. `tests/sim_strength.rs` keeps watching both.
pub const SCENARIOS: [Scenario; 10] = [
scenario("heads-up reg", 2, Opponent::Reader(Style::Reg)),
scenario("heads-up nit", 2, Opponent::Reader(Style::Nit)),
scenario("heads-up maniac", 2, Opponent::Reader(Style::Maniac)),
scenario("heads-up fish", 2, Opponent::Reader(Style::Fish)),
scenario("heads-up calling station", 2, Opponent::CallingStation),
scenario("6-max reg", 6, Opponent::Reader(Style::Reg)),
scenario("6-max nit", 6, Opponent::Reader(Style::Nit)),
scenario("6-max maniac", 6, Opponent::Reader(Style::Maniac)),
scenario("6-max fish", 6, Opponent::Reader(Style::Fish)),
scenario("6-max calling station", 6, Opponent::CallingStation),
];
#[derive(Clone, Debug, PartialEq)]
pub struct ScenarioRun {
pub name: String,
pub deals: u32,
pub seed: u64,
pub decisions: u32,
pub abstains: u32,
/// Requests the guard refused: a simulator bug, must stay 0.
pub invalid: u32,
/// Hero's luck-corrected result per deal, bb.
pub samples: Vec<f64>,
}
impl ScenarioRun {
pub fn bb_per_100(&self) -> f64 {
100.0 * self.samples.iter().sum::<f64>() / self.samples.len().max(1) as f64
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Run {
/// Which version this is.
pub label: String,
pub scenarios: Vec<ScenarioRun>,
}
/// Plays every scenario, one thread each. The result does not depend on the threads.
pub fn run_all(label: &str) -> Run {
let scenarios = thread::scope(|scope| {
let running: Vec<_> = SCENARIOS
.iter()
.map(|s| {
scope.spawn(move || {
let (samples, m) = deal_samples(&s.setup);
ScenarioRun {
name: s.name.to_string(),
deals: s.setup.deals,
seed: s.setup.seed,
decisions: m.decisions,
abstains: m.abstains,
invalid: m.invalid,
samples,
}
})
})
.collect();
running.into_iter().map(|r| r.join().expect("a scenario panicked")).collect()
});
Run { label: label.to_string(), scenarios }
}
pub struct Report {
pub scenarios: Vec<(String, Comparison)>,
pub overall: Comparison,
pub invalid: u32,
}
impl Report {
/// Worse anywhere, even if the total hides it, or a request the guard refused.
pub fn has_regression(&self) -> bool {
self.invalid > 0
|| self.overall.verdict == Verdict::Worse
|| self.scenarios.iter().any(|(_, c)| c.verdict == Verdict::Worse)
}
}
/// The mean of independent scenarios, each counting the same; their variances add.
pub fn overall(comparisons: &[Comparison]) -> Comparison {
let k = comparisons.len().max(1) as f64;
let delta = comparisons.iter().map(|c| c.delta_bb_per_100).sum::<f64>() / k;
let ci95 = comparisons.iter().map(|c| c.ci95.powi(2)).sum::<f64>().sqrt() / k;
let identical = comparisons.iter().all(|c| c.verdict == Verdict::Identical);
Comparison {
delta_bb_per_100: delta,
ci95,
changed_deals: comparisons.iter().map(|c| c.changed_deals).sum(),
verdict: if identical { Verdict::Identical } else { Verdict::of(delta, ci95) },
}
}
/// Compares two runs. Runs under other conditions say nothing about the engine: refused.
pub fn verdict_of_run(base: &Run, new: &Run) -> Result<Report, String> {
if base.scenarios.len() != new.scenarios.len() {
return Err(format!("{} gegen {} Szenarien: Basislinie neu messen", base.scenarios.len(), new.scenarios.len()));
}
let mut scenarios = Vec::with_capacity(base.scenarios.len());
for (b, n) in base.scenarios.iter().zip(&new.scenarios) {
if b.name != n.name || b.deals != n.deals || b.seed != n.seed {
return Err(format!("andere Bedingungen: „{}“ gegen „{}“: Basislinie neu messen", b.name, n.name));
}
scenarios.push((b.name.clone(), compare(&b.samples, &n.samples)?));
}
let all: Vec<Comparison> = scenarios.iter().map(|(_, c)| *c).collect();
Ok(Report { overall: overall(&all), invalid: new.scenarios.iter().map(|s| s.invalid).sum(), scenarios })
}
/// The run as text. Floats are written so that they read back bit for bit.
pub fn render(run: &Run) -> String {
let mut text = format!("label {}\n", run.label);
for s in &run.scenarios {
let samples: Vec<String> = s.samples.iter().map(f64::to_string).collect();
text += &format!(
"scenario {}\ndeals {}\nseed {}\ncounts {} {} {}\nsamples {}\n",
s.name, s.deals, s.seed, s.decisions, s.abstains, s.invalid, samples.join(" ")
);
}
text
}
fn field<'a>(lines: &mut std::str::Lines<'a>, key: &str) -> Result<&'a str, String> {
let line = lines.next().ok_or_else(|| format!("„{key}“ fehlt"))?;
line.strip_prefix(key)
.and_then(|rest| rest.strip_prefix(' '))
.ok_or_else(|| format!("„{key}“ erwartet, „{line}“ gelesen"))
}
fn number<T: std::str::FromStr>(text: &str) -> Result<T, String> {
text.parse().map_err(|_| format!("keine Zahl: „{text}“"))
}
pub fn parse(text: &str) -> Result<Run, String> {
let mut lines = text.lines();
let label = field(&mut lines, "label")?.to_string();
let mut scenarios = Vec::new();
while lines.clone().next().is_some() {
let name = field(&mut lines, "scenario")?.to_string();
let deals: u32 = number(field(&mut lines, "deals")?)?;
let seed: u64 = number(field(&mut lines, "seed")?)?;
let counts = field(&mut lines, "counts")?.split(' ').map(number).collect::<Result<Vec<u32>, _>>()?;
let [decisions, abstains, invalid] = counts[..] else {
return Err(format!("„counts“ von „{name}“ hat {} Werte", counts.len()));
};
let samples = field(&mut lines, "samples")?.split(' ').map(number).collect::<Result<Vec<f64>, _>>()?;
if samples.len() != deals as usize {
return Err(format!("„{name}“: {deals} Austeilungen, {} Werte", samples.len()));
}
scenarios.push(ScenarioRun { name, deals, seed, decisions, abstains, invalid, samples });
}
Ok(Run { label, scenarios })
}
+3
View File
@@ -2,7 +2,10 @@
//! fixed opponents, win rate in bb/100 with a 95 % interval. Pure and deterministic; used by
//! `tests/sim_strength.rs`, not by the request pipeline.
pub mod benchmark;
pub mod luck;
pub mod opponent;
pub mod paired;
pub mod reader;
pub mod session;
pub mod table;
+7 -1
View File
@@ -1,3 +1,4 @@
use super::reader::Style;
use crate::rng::Rng;
/// What a fixed opponent sees: the price and, if raising is possible, its bounds
@@ -17,7 +18,7 @@ pub enum Act {
RaiseTo(f64),
}
/// Fixed opponents for the strength measurement. None of them looks at its cards.
/// Fixed opponents for the strength measurement. Only `Reader` looks at its cards.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Opponent {
/// Calls every bet, never raises.
@@ -26,6 +27,8 @@ pub enum Opponent {
Folder,
/// Uniform among the legal options; a raise is uniform between min and max.
RandomLegal,
/// Plays its cards in a fixed style; the table hands it its reading (`Style::act`).
Reader(Style),
}
impl Opponent {
@@ -36,6 +39,7 @@ impl Opponent {
Opponent::CallingStation => "calling station",
Opponent::Folder => "folder",
Opponent::RandomLegal => "random legal",
Opponent::Reader(style) => style.name(),
}
}
@@ -43,6 +47,8 @@ impl Opponent {
let facing = view.to_call > 0.0;
let passive = if facing { Act::Call } else { Act::Check };
match self {
// Without a reading there is nothing to play on; the table never asks this way.
Opponent::Reader(_) => (if facing { Act::Fold } else { Act::Check }, rng),
Opponent::CallingStation => (passive, rng),
Opponent::Folder => (if facing { Act::Fold } else { Act::Check }, rng),
Opponent::RandomLegal => {
+57
View File
@@ -0,0 +1,57 @@
//! Paired comparison of two measurements over the same deals: the difference per deal removes
//! what both runs share, so a small change shows long before the two win rates' intervals part.
/// 95 % two-sided normal quantile.
const Z95: f64 = 1.959_964;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Verdict {
/// Not a single result moved.
Identical,
/// The interval of the difference lies above 0.
Better,
/// The interval of the difference lies below 0.
Worse,
/// Something moved, but the interval still contains 0.
Unclear,
}
impl Verdict {
/// Judges a difference and the half width of its interval.
pub fn of(delta: f64, ci95: f64) -> Verdict {
if delta - ci95 > 0.0 {
Verdict::Better
} else if delta + ci95 < 0.0 {
Verdict::Worse
} else {
Verdict::Unclear
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Comparison {
/// New minus base, bb/100.
pub delta_bb_per_100: f64,
/// Half width of the 95 % interval of the difference, bb/100.
pub ci95: f64,
pub changed_deals: u32,
pub verdict: Verdict,
}
/// Compares per-deal results in bb. The deals must be the same ones, in the same order.
pub fn compare(base: &[f64], new: &[f64]) -> Result<Comparison, String> {
if base.len() != new.len() || base.is_empty() {
return Err(format!("{} gegen {} Austeilungen", base.len(), new.len()));
}
let diffs: Vec<f64> = base.iter().zip(new).map(|(b, n)| n - b).collect();
let changed_deals = diffs.iter().filter(|d| **d != 0.0).count() as u32;
if changed_deals == 0 {
return Ok(Comparison { delta_bb_per_100: 0.0, ci95: 0.0, changed_deals, verdict: Verdict::Identical });
}
let n = diffs.len() as f64;
let mean = diffs.iter().sum::<f64>() / n;
let var = diffs.iter().map(|d| (d - mean).powi(2)).sum::<f64>() / (n - 1.0).max(1.0);
let (delta, ci95) = (100.0 * mean, 100.0 * Z95 * (var / n).sqrt());
Ok(Comparison { delta_bb_per_100: delta, ci95, changed_deals, verdict: Verdict::of(delta, ci95) })
}
+121
View File
@@ -0,0 +1,121 @@
//! Opponents that look at their cards: fixed rules on equity against a random hand. Not a model
//! of real players, but they punish what card-blind opponents cannot, such as paying off strong
//! hands or bluffing into a caller.
use super::opponent::{Act, View};
use crate::card::{deck, Card};
use crate::hand::showdown::best;
use crate::rng::Rng;
use crate::variant::HoleUsage;
/// Boards drawn per strength estimate.
const STRENGTH_SAMPLES: usize = 200;
/// Up to this price (bb) a preflop raise is an open, above it a re-raise.
const OPEN_PRICE: f64 = 1.0;
/// Only hands below this strength bluff.
const BLUFF_BELOW: f64 = 0.45;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Style {
Reg,
Nit,
Maniac,
Fish,
}
/// What the table tells a reading opponent besides the `View`.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Reading {
/// Equity against one random hand, 0 to 1.
pub strength: f64,
pub pot: f64,
/// Already in front of it on this street.
pub own_bet: f64,
pub preflop: bool,
}
struct Rules {
/// Equity it wants above the pot odds to call.
call_margin: f64,
/// Raises a bet from here.
raise_at: f64,
/// Bets when checked to from here.
bet_at: f64,
/// Opens preflop from here.
open_at: f64,
/// How often it bluffs a weak hand when checked to.
bluff: f64,
/// Bet size as a share of the pot after calling.
size: f64,
}
impl Style {
pub const ALL: [Style; 4] = [Style::Reg, Style::Nit, Style::Maniac, Style::Fish];
pub fn name(self) -> &'static str {
match self {
Style::Reg => "reg",
Style::Nit => "nit",
Style::Maniac => "maniac",
Style::Fish => "fish",
}
}
fn rules(self) -> Rules {
match self {
Style::Reg => Rules { call_margin: 0.22, raise_at: 0.82, bet_at: 0.68, open_at: 0.62, bluff: 0.08, size: 2.0 / 3.0 },
Style::Nit => Rules { call_margin: 0.32, raise_at: 0.90, bet_at: 0.78, open_at: 0.70, bluff: 0.0, size: 0.5 },
Style::Maniac => Rules { call_margin: 0.08, raise_at: 0.70, bet_at: 0.55, open_at: 0.52, bluff: 0.35, size: 1.0 },
Style::Fish => Rules { call_margin: 0.02, raise_at: 0.92, bet_at: 0.80, open_at: 0.78, bluff: 0.02, size: 0.4 },
}
}
pub fn act(self, view: View, reading: Reading, rng: Rng) -> (Act, Rng) {
let rules = self.rules();
let s = reading.strength;
let to_call = view.to_call;
let raise_from = match (reading.preflop && to_call <= OPEN_PRICE, to_call > 0.0) {
(true, _) => rules.open_at,
(false, true) => rules.raise_at,
(false, false) => rules.bet_at,
};
let raise = Act::RaiseTo(reading.own_bet + to_call + rules.size * (reading.pot + to_call));
let can_raise = view.min_raise_to.is_some();
if can_raise && s >= raise_from {
return (raise, rng);
}
if to_call > 0.0 {
let price = to_call / (reading.pot + to_call);
return (if s >= price + rules.call_margin { Act::Call } else { Act::Fold }, rng);
}
if can_raise && !reading.preflop && s < BLUFF_BELOW {
let (u, rng) = rng.unit();
return (if u < rules.bluff { raise } else { Act::Check }, rng);
}
(Act::Check, rng)
}
}
/// Equity of `hole` against one random hand, ties counting half; seed-fixed Monte Carlo.
pub fn strength(hole: &[Card], board: &[Card], rng: Rng) -> f64 {
let mut known = hole.to_vec();
known.extend_from_slice(board);
let pool = deck::without(&known);
let missing = 5 - board.len();
let mut rng = rng;
let mut won = 0.0;
for _ in 0..STRENGTH_SAMPLES {
let (cards, next) = deck::draw(&pool, 2 + missing, rng).expect("enough cards");
rng = next;
let mut full = board.to_vec();
full.extend_from_slice(&cards[2..]);
let mine = best(HoleUsage::BestFiveOfAll, hole, &full).expect("valid cards");
let theirs = best(HoleUsage::BestFiveOfAll, &cards[..2], &full).expect("valid cards");
won += match mine.cmp(&theirs) {
std::cmp::Ordering::Greater => 1.0,
std::cmp::Ordering::Equal => 0.5,
std::cmp::Ordering::Less => 0.0,
};
}
won / STRENGTH_SAMPLES as f64
}
+6 -1
View File
@@ -60,6 +60,11 @@ fn mix(seed: u64, n: u64) -> u64 {
/// Plays `deals` deals, each from every seat, and returns hero's win rate with its interval.
/// A sample is one deal's mean over the seats, so position and card luck cancel within it.
pub fn measure(setup: &Setup) -> Measurement {
deal_samples(setup).1
}
/// Hero's luck-corrected result per deal in bb, for paired comparisons, with the measurement.
pub fn deal_samples(setup: &Setup) -> (Vec<f64>, Measurement) {
let players = setup.players;
let mut samples = Vec::with_capacity(setup.deals as usize);
let mut raw_samples = Vec::with_capacity(setup.deals as usize);
@@ -96,7 +101,7 @@ pub fn measure(setup: &Setup) -> Measurement {
}
(m.bb_per_100, m.ci95) = rate(&samples);
(m.raw_bb_per_100, m.raw_ci95) = rate(&raw_samples);
m
(samples, m)
}
/// Mean and 95 % half width of per-deal results, both in bb/100.
+17 -1
View File
@@ -4,6 +4,7 @@
use super::luck;
use super::opponent::{Act, Opponent, View};
use super::reader::{strength, Reading};
use crate::card::{deck, Card};
use crate::engine::decide::decide;
use crate::game::{ActionKind, ActionRecord, Choice, SeenAction, Spot, Street, Villain};
@@ -191,12 +192,27 @@ impl Table<'_> {
}
}
/// What a reading opponent knows. Its own seed, so that it does not depend on hero's play.
fn reading(&self, i: usize) -> Reading {
let board = &self.setup.deal.board[..self.street.board_len()];
let seed = self.setup.seed ^ ((i as u64 + 1) << 32) ^ (self.street.board_len() as u64 + 1).wrapping_mul(0x51_7CC1);
Reading {
strength: strength(&self.setup.deal.holes[i], board, Rng::seeded(seed)),
pot: self.total.iter().sum(),
own_bet: self.bet[i],
preflop: self.street == Street::Preflop,
}
}
fn act(&mut self, i: usize) -> bool {
let view = self.view(i);
let act = if i == self.hero {
self.hero_act(view)
} else {
let (act, rng) = self.setup.opponent.act(view, self.rng);
let (act, rng) = match self.setup.opponent {
Opponent::Reader(style) => style.act(view, self.reading(i), self.rng),
blind => blind.act(view, self.rng),
};
self.rng = rng;
act
};
+12 -2
View File
@@ -1,8 +1,9 @@
use crate::exploit::mark::with_mark;
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::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;
@@ -24,12 +25,21 @@ fn profile(villain: &Value, path: &str) -> Result<Option<Profile>, Fault> {
}))
}
/// `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: profile(value, path)?,
profile: marked_profile(value, path)?,
})
}
+3 -3
View File
@@ -43,14 +43,14 @@ fn semibluffs_need_at_most_two_villains() {
#[test]
fn effective_thresholds_combine_texture_and_player_count() {
// Medium hand, dry board (wetness 0.1): texture gives margin 0.034, value 0.692.
// Medium hand, dry board (wetness 0.1): texture gives margin 0.034, value 0.652.
let read = read_of(Made::MiddlePair, Draw::None, 0, SuitPattern::Rainbow, 0.1);
let spot = with_villains(round_flop(), 3);
let e = effective(&spot, 0.5, &BASE, &read);
assert_eq!(e.villains, 3);
assert!(close(e.share, 0.5 * 0.97 * 0.97), "{e:?}");
assert!(close(e.call_margin, 0.034 + 0.02), "{e:?}");
assert!(close(e.value_raise, 0.692 + 0.10), "{e:?}");
assert!(close(e.value_raise, 0.652 + 0.10), "{e:?}");
assert!(e.value_ok && e.raise_ok && !e.semibluff_ok);
}
@@ -84,7 +84,7 @@ fn a_share_that_calls_heads_up_folds_four_way() {
#[test]
fn a_share_that_value_raises_heads_up_only_calls_three_way() {
let share = estimate(0.70, 0.002);
let share = estimate(0.64, 0.002);
let heads_up = choose_postflop(&with_villains(round_flop(), 1), &share, &BASE, &neutral_read());
assert!(matches!(heads_up.choice, Choice::Raise { .. }), "{heads_up:?}");
let three_way = choose_postflop(&with_villains(round_flop(), 3), &share, &BASE, &neutral_read());
+8 -8
View File
@@ -7,7 +7,7 @@ use pokerfreak::read::made::Made;
use pokerfreak::read::suit_pattern::SuitPattern;
use spot_fixture::read_of;
const BASE: Thresholds = Thresholds::BASE; // call_margin 0.02, value_raise 0.62
const BASE: Thresholds = Thresholds::BASE; // call_margin 0.02, value_raise 0.58
fn close(a: f64, b: f64) -> bool {
(a - b).abs() < 1e-9
@@ -20,7 +20,7 @@ fn medium_hand_on_a_wet_board_loses_the_thin_value_raise_and_pays_more() {
assert!(!s.value_ok);
assert!(s.raise_ok);
assert!(close(s.call_margin, 0.02 + 0.01 + 0.04 * 0.8), "{s:?}");
assert!(close(s.value_raise, 0.62 + 0.06 + 0.12 * 0.8), "{s:?}");
assert!(close(s.value_raise, 0.58 + 0.06 + 0.12 * 0.8), "{s:?}");
}
#[test]
@@ -29,7 +29,7 @@ fn medium_hand_on_a_dry_board_may_still_value_raise_but_needs_more() {
let s = texture_stance(&BASE, &read, true);
assert!(s.value_ok);
assert!(close(s.call_margin, 0.02 + 0.01 + 0.004), "{s:?}");
assert!(close(s.value_raise, 0.62 + 0.06 + 0.012), "{s:?}");
assert!(close(s.value_raise, 0.58 + 0.06 + 0.012), "{s:?}");
}
#[test]
@@ -45,7 +45,7 @@ fn strong_hand_on_a_dry_board_raises_slightly_below_the_value_threshold() {
let read = read_of(Made::TopPairGoodKicker, Draw::None, 0, SuitPattern::Rainbow, 0.0);
let s = texture_stance(&BASE, &read, true);
assert!(s.value_ok);
assert!(close(s.value_raise, 0.58), "{s:?}");
assert!(close(s.value_raise, 0.54), "{s:?}");
assert!(close(s.call_margin, 0.02), "{s:?}");
}
@@ -53,7 +53,7 @@ fn strong_hand_on_a_dry_board_raises_slightly_below_the_value_threshold() {
fn strong_hand_on_a_wet_board_wants_more_equity_to_raise() {
let read = read_of(Made::Overpair, Draw::None, 0, SuitPattern::TwoTone, 1.0);
let s = texture_stance(&BASE, &read, true);
assert!(close(s.value_raise, 0.62 + 0.05), "{s:?}");
assert!(close(s.value_raise, 0.58 + 0.05), "{s:?}");
assert!(close(s.call_margin, 0.02 + 0.02), "{s:?}");
}
@@ -61,7 +61,7 @@ fn strong_hand_on_a_wet_board_wants_more_equity_to_raise() {
fn strong_hand_on_a_four_flush_board_is_more_careful_still() {
let read = read_of(Made::TwoPair, Draw::None, 0, SuitPattern::FourFlush, 0.5);
let s = texture_stance(&BASE, &read, true);
assert!(close(s.value_raise, 0.62 + 0.08 + 0.025), "{s:?}");
assert!(close(s.value_raise, 0.58 + 0.08 + 0.025), "{s:?}");
assert!(close(s.call_margin, 0.02 + 0.01 + 0.03), "{s:?}");
}
@@ -70,7 +70,7 @@ fn weak_hand_without_draw_facing_a_bet_is_stricter() {
let read = read_of(Made::BottomPair, Draw::None, 0, SuitPattern::Rainbow, 0.2);
let s = texture_stance(&BASE, &read, true);
assert!(close(s.call_margin, 0.05), "{s:?}");
assert!(close(s.value_raise, 0.72), "{s:?}");
assert!(close(s.value_raise, 0.68), "{s:?}");
}
#[test]
@@ -99,7 +99,7 @@ fn monsters_are_never_moved() {
for wet in [0.0, 0.5, 1.0] {
let read = read_of(Made::FullHouse, Draw::None, 0, suits, wet);
let s = texture_stance(&BASE, &read, true);
assert!(close(s.call_margin, 0.02) && close(s.value_raise, 0.62), "{s:?}");
assert!(close(s.call_margin, 0.02) && close(s.value_raise, 0.58), "{s:?}");
assert!(s.value_ok && s.raise_ok);
}
}
+60
View File
@@ -0,0 +1,60 @@
//! Extension field `villains[].marke`: the client's own label of a player, sent by the shell.
//!
//! A beginner or fish mark stands in for numbers we do not have yet: it fills the profile fields
//! that are missing, measured values win. Unknown marks change nothing.
mod support;
use pokerfreak::wire::respond::respond;
use support::{action, cards_json, field, short};
const STATION: &str = r#","profile":{"vpip":0.55,"pfr":0.05,"foldToBet":0.15,"aggression":0.2}"#;
const NIT: &str = r#","profile":{"vpip":0.11,"pfr":0.08,"foldToBet":0.8,"aggression":0.15}"#;
/// The button first in; the two blinds carry `extra` (a mark, a profile or both).
fn steal(hero: &str, extra: &str) -> String {
format!(
r#"{{"variant":"NLHE","bigBlind":1,"seats":6,"heroSeat":6,"buttonSeat":6,"heroCards":{},"street":"PREFLOP","pot":1.5,"toCall":1,"heroStack":100,"minRaiseTo":2,"maxRaiseTo":100,"legalActions":["FOLD","CALL","RAISE"],"villains":[{{"seat":1,"stack":100,"folded":false{extra}}},{{"seat":2,"stack":100,"folded":false{extra}}}]}}"#,
cards_json(&short(hero)),
)
}
/// K7o: an equilibrium open, not stolen against stations (`pipeline_bluff`).
const HERO: &str = "Kd 7c";
#[test]
fn a_beginner_mark_changes_the_recommendation() {
assert_eq!(action(&respond(&steal(HERO, ""))), "RAISE");
assert_eq!(action(&respond(&steal(HERO, r#","marke":"Anfaenger""#))), "FOLD");
}
#[test]
fn a_fish_mark_counts_like_a_beginner() {
assert_eq!(respond(&steal(HERO, r#","marke":"FISH""#)), respond(&steal(HERO, r#","marke":"Anfaenger""#)));
}
#[test]
fn an_unknown_mark_changes_nothing() {
assert_eq!(respond(&steal(HERO, r#","marke":"VIP""#)), respond(&steal(HERO, "")));
}
#[test]
fn measured_values_beat_the_mark() {
let measured = format!(r#","marke":"Anfaenger"{NIT}"#);
assert_eq!(respond(&steal(HERO, &measured)), respond(&steal(HERO, NIT)));
assert_ne!(respond(&steal(HERO, &measured)), respond(&steal(HERO, STATION)));
}
#[test]
fn a_mark_fills_only_the_missing_fields() {
// vpip measured tight, fold-to-bet from the mark: not the same player as the mark alone.
let partial = r#","marke":"Anfaenger","profile":{"vpip":0.11,"pfr":0.08}"#;
assert_eq!(action(&respond(&steal(HERO, partial))), action(&respond(&steal(HERO, r#","profile":{"vpip":0.11,"pfr":0.08,"foldToBet":0.25,"aggression":0.2}"#))));
}
#[test]
fn a_mark_that_is_no_text_is_refused() {
let out = respond(&steal(HERO, r#","marke":7"#));
assert_eq!(action(&out), "ABSTAIN", "{out}");
assert!(field(&out, "reason").unwrap_or("").contains("marke"), "{out}");
}
+273
View File
@@ -0,0 +1,273 @@
//! Benchmark: Ist eine Änderung besser oder schlechter? Dieselben Austeilungen, je Austeilung die
//! Differenz zur Basislinie, das Urteil nur, wenn das 95-%-Intervall der Differenz die 0 ausschließt.
use pokerfreak::rng::Rng;
use pokerfreak::sim::benchmark::{overall, parse, render, verdict_of_run, Run, ScenarioRun, SCENARIOS};
use pokerfreak::sim::opponent::{Act, Opponent, View};
use pokerfreak::sim::paired::{compare, Verdict};
use pokerfreak::sim::reader::{strength, Reading, Style};
use pokerfreak::sim::session::{deal_samples, measure, Setup};
use pokerfreak::card::Card;
fn scenario(name: &str, samples: Vec<f64>) -> ScenarioRun {
ScenarioRun {
name: name.to_string(),
deals: samples.len() as u32,
seed: 7,
decisions: 10,
abstains: 1,
invalid: 0,
samples,
}
}
fn run(scenarios: Vec<ScenarioRun>) -> Run {
Run { label: "abc123".to_string(), scenarios }
}
// -- Gepaarter Vergleich --------------------------------------------------------------------
#[test]
fn unchanged_results_are_identical_not_merely_unclear() {
let c = compare(&[1.0, -2.0, 3.0], &[1.0, -2.0, 3.0]).unwrap();
assert_eq!(c.verdict, Verdict::Identical);
assert_eq!(c.delta_bb_per_100, 0.0);
assert_eq!(c.ci95, 0.0);
assert_eq!(c.changed_deals, 0);
}
#[test]
fn a_clear_gain_is_better_a_clear_loss_is_worse() {
let base = vec![0.0; 100];
let gain: Vec<f64> = (0..100).map(|i| 1.0 + (i % 2) as f64 * 0.1).collect();
let loss: Vec<f64> = gain.iter().map(|g| -g).collect();
let better = compare(&base, &gain).unwrap();
assert_eq!(better.verdict, Verdict::Better);
assert!((better.delta_bb_per_100 - 105.0).abs() < 1e-9);
assert_eq!(better.changed_deals, 100);
assert_eq!(compare(&base, &loss).unwrap().verdict, Verdict::Worse);
}
#[test]
fn noise_around_zero_stays_unclear() {
let base = vec![0.0; 100];
let noise: Vec<f64> = (0..100).map(|i| if i % 2 == 0 { 5.0 } else { -5.0 }).collect();
assert_eq!(compare(&base, &noise).unwrap().verdict, Verdict::Unclear);
}
#[test]
fn the_interval_decides_at_its_edge() {
// Mittel 0,5, Standardabweichung der Differenzen 1,0: mit n = 16 trennt das Intervall (±0,49)
// gerade noch von 0, mit n = 12 (±0,566) nicht mehr.
let diffs = |n: usize| -> Vec<f64> {
(0..n).map(|i| if i % 2 == 0 { 0.5 + d(n) } else { 0.5 - d(n) }).collect()
};
fn d(n: usize) -> f64 {
(((n - 1) as f64) / n as f64).sqrt()
}
assert_eq!(compare(&vec![0.0; 16], &diffs(16)).unwrap().verdict, Verdict::Better);
assert_eq!(compare(&vec![0.0; 12], &diffs(12)).unwrap().verdict, Verdict::Unclear);
}
#[test]
fn different_lengths_are_refused() {
assert!(compare(&[1.0, 2.0], &[1.0]).is_err());
assert!(compare(&[], &[]).is_err());
}
// -- Gesamturteil ---------------------------------------------------------------------------
#[test]
fn the_verdict_covers_all_scenarios_with_equal_weight() {
let base = run(vec![scenario("a", vec![0.0; 50]), scenario("b", vec![0.0; 50])]);
let new = run(vec![scenario("a", vec![1.0; 50]), scenario("b", vec![0.0; 50])]);
let report = verdict_of_run(&base, &new).unwrap();
assert_eq!(report.scenarios[0].1.verdict, Verdict::Better);
assert_eq!(report.scenarios[1].1.verdict, Verdict::Identical);
assert!((report.overall.delta_bb_per_100 - 50.0).abs() < 1e-9);
assert_eq!(report.overall.verdict, Verdict::Better);
}
#[test]
fn a_loss_in_one_scenario_can_hide_in_the_total_but_not_in_the_report() {
let up: Vec<f64> = vec![2.0; 50];
let down: Vec<f64> = vec![-1.0; 50];
let base = run(vec![scenario("a", vec![0.0; 50]), scenario("b", vec![0.0; 50])]);
let new = run(vec![scenario("a", up), scenario("b", down)]);
let report = verdict_of_run(&base, &new).unwrap();
assert_eq!(report.overall.verdict, Verdict::Better);
assert_eq!(report.scenarios[1].1.verdict, Verdict::Worse);
assert!(report.has_regression());
}
#[test]
fn only_identical_scenarios_are_identical_overall() {
let base = run(vec![scenario("a", vec![1.0, 2.0])]);
let report = verdict_of_run(&base, &base.clone()).unwrap();
assert_eq!(report.overall.verdict, Verdict::Identical);
assert!(!report.has_regression());
}
#[test]
fn overall_of_independent_scenarios_adds_variances() {
let a = compare(&vec![0.0; 100], &(0..100).map(|i| if i % 2 == 0 { 1.0 } else { 0.0 }).collect::<Vec<_>>()).unwrap();
let o = overall(&[a, a]);
assert!((o.delta_bb_per_100 - a.delta_bb_per_100).abs() < 1e-9);
assert!((o.ci95 - a.ci95 / 2f64.sqrt()).abs() < 1e-9);
}
#[test]
fn comparing_other_conditions_is_refused() {
let base = run(vec![scenario("a", vec![0.0; 50])]);
let other_name = run(vec![scenario("b", vec![0.0; 50])]);
let other_deals = run(vec![scenario("a", vec![0.0; 40])]);
let mut other_seed = base.clone();
other_seed.scenarios[0].seed = 8;
let missing = run(vec![]);
for other in [other_name, other_deals, other_seed, missing] {
assert!(verdict_of_run(&base, &other).is_err());
}
}
#[test]
fn an_invalid_request_counts_as_a_regression() {
let base = run(vec![scenario("a", vec![1.0, 2.0])]);
let mut new = base.clone();
new.scenarios[0].invalid = 1;
assert!(verdict_of_run(&base, &new).unwrap().has_regression());
}
// -- Datei ----------------------------------------------------------------------------------
#[test]
fn the_file_returns_every_value_bit_for_bit() {
let r = run(vec![scenario("heads-up reg", vec![0.1 + 0.2, -1e-300, 1.0 / 3.0]), scenario("x", vec![5.0])]);
assert_eq!(parse(&render(&r)).unwrap(), r);
}
#[test]
fn a_damaged_file_is_refused() {
let good = render(&run(vec![scenario("a", vec![1.0, 2.0])]));
assert!(parse("").is_err());
assert!(parse(&good.replace("deals 2", "deals 3")).is_err());
assert!(parse(&good.replace(" 2\n", " zwei\n")).is_err());
assert!(parse("unsinn\n").is_err());
}
// -- Gegner, die ihre Karten ansehen --------------------------------------------------------
fn cards(text: &str) -> Vec<Card> {
Card::parse_list(text).expect("cards")
}
fn facing(to_call: f64) -> View {
View { to_call, min_raise_to: Some(to_call * 2.0), max_raise_to: Some(100.0) }
}
fn read(strength: f64, pot: f64) -> Reading {
Reading { strength, pot, own_bet: 0.0, preflop: false }
}
fn acts(style: Style, view: View, reading: Reading, n: u64) -> Vec<Act> {
(0..n).map(|s| style.act(view, reading, Rng::seeded(s)).0).collect()
}
#[test]
fn strength_ranks_hands_and_knows_the_nuts() {
let aces = strength(&cards("As Ah"), &[], Rng::seeded(1));
let trash = strength(&cards("7c 2d"), &[], Rng::seeded(1));
assert!(aces > 0.8 && trash < 0.42, "{aces} {trash}");
let nuts = strength(&cards("As Ks"), &cards("Qs Js Ts 2d 3c"), Rng::seeded(1));
assert_eq!(nuts, 1.0);
}
#[test]
fn every_style_folds_air_to_a_pot_bet_and_raises_the_nuts() {
for style in Style::ALL {
let view = facing(10.0);
assert!(acts(style, view, read(0.15, 20.0), 50).iter().all(|a| *a == Act::Fold), "{style:?}");
assert!(matches!(style.act(view, read(1.0, 20.0), Rng::seeded(1)).0, Act::RaiseTo(_)), "{style:?}");
}
}
#[test]
fn the_styles_differ_where_they_should() {
let view = facing(10.0);
// Mittlere Hand gegen eine Topf-Wette: der Fisch zahlt, der Nit nicht.
let middling = read(0.5, 20.0);
assert_eq!(Style::Fish.act(view, middling, Rng::seeded(1)).0, Act::Call);
assert_eq!(Style::Nit.act(view, middling, Rng::seeded(1)).0, Act::Fold);
// Luft ohne Preis: der Maniac blufft oft, der Nit nie, der Reg selten.
let free = View { to_call: 0.0, min_raise_to: Some(1.0), max_raise_to: Some(100.0) };
let bluffs = |style| acts(style, free, read(0.2, 10.0), 1000).iter().filter(|a| matches!(a, Act::RaiseTo(_))).count();
assert_eq!(bluffs(Style::Nit), 0);
assert!(bluffs(Style::Reg) > 20 && bluffs(Style::Reg) < 200, "{}", bluffs(Style::Reg));
assert!(bluffs(Style::Maniac) > 250, "{}", bluffs(Style::Maniac));
}
#[test]
fn a_bet_is_sized_from_the_pot_on_top_of_the_call() {
// Reg: zwei Drittel des Topfs nach dem Mitgehen. 5 gesetzt, 10 zu zahlen, 30 im Topf.
let view = View { to_call: 10.0, min_raise_to: Some(25.0), max_raise_to: Some(500.0) };
let reading = Reading { strength: 1.0, pot: 30.0, own_bet: 5.0, preflop: false };
let (act, _) = Style::Reg.act(view, reading, Rng::seeded(1));
let Act::RaiseTo(to) = act else { panic!("{act:?}") };
assert!((to - (5.0 + 10.0 + 40.0 * 2.0 / 3.0)).abs() < 1e-9, "{to}");
}
#[test]
fn preflop_a_good_hand_opens_but_does_not_reraise() {
let open = View { to_call: 0.5, min_raise_to: Some(2.0), max_raise_to: Some(100.0) };
let reraise = View { to_call: 2.0, min_raise_to: Some(5.0), max_raise_to: Some(100.0) };
let good = Reading { strength: 0.65, pot: 1.5, own_bet: 0.5, preflop: true };
assert!(matches!(Style::Reg.act(open, good, Rng::seeded(1)).0, Act::RaiseTo(_)));
assert_eq!(Style::Reg.act(reraise, Reading { pot: 4.0, ..good }, Rng::seeded(1)).0, Act::Call);
}
#[test]
fn a_raise_is_never_offered_when_impossible() {
let view = View { to_call: 5.0, min_raise_to: None, max_raise_to: None };
for style in Style::ALL {
assert_eq!(style.act(view, read(1.0, 10.0), Rng::seeded(1)).0, Act::Call);
}
}
#[test]
fn reading_opponents_play_legal_hands_and_lose_chips_to_nobody() {
for style in Style::ALL {
for players in [2u8, 6] {
let s = Setup { players, opponent: Opponent::Reader(style), deals: 4, stack_bb: 100.0, seed: 3 };
let m = measure(&s);
assert_eq!(m.invalid, 0, "{style:?} {players}");
assert!(m.decisions > 0);
}
}
}
#[test]
fn a_reading_opponent_does_not_play_like_a_blind_one() {
let s = |opponent| Setup { players: 2, opponent, deals: 40, stack_bb: 100.0, seed: 3 };
assert_ne!(deal_samples(&s(Opponent::Reader(Style::Nit))).0, deal_samples(&s(Opponent::Reader(Style::Maniac))).0);
}
// -- Messung --------------------------------------------------------------------------------
#[test]
fn deal_samples_agree_with_the_measurement() {
let s = Setup { players: 2, opponent: Opponent::RandomLegal, deals: 30, stack_bb: 100.0, seed: 9 };
let (samples, _) = deal_samples(&s);
let mean = samples.iter().sum::<f64>() / 30.0;
assert_eq!(samples.len(), 30);
assert!((100.0 * mean - measure(&s).bb_per_100).abs() < 1e-9);
}
#[test]
fn the_scenarios_have_unique_names_and_no_saturated_opponent() {
let mut names: Vec<_> = SCENARIOS.iter().map(|s| s.name).collect();
names.sort();
names.dedup();
assert_eq!(names.len(), SCENARIOS.len());
// Der Folder ist immer +75: er könnte keine Änderung zeigen.
assert!(SCENARIOS.iter().all(|s| s.setup.opponent != Opponent::Folder));
}