From 1ad6f76088ebc1bccda382f20617ba2cafe8f3e0 Mon Sep 17 00:00:00 2001 From: Marc Mintel Date: Wed, 28 Oct 2026 13:11:38 +0100 Subject: [PATCH] Bluffing and bluff catching driven by opponent frequencies - exploit::fold_chance: documented foldToBet -> P(fold) map by bet size, per villain - engine: two-branch EV for every raise (fold branch, called branch vs calling range) - semibluffs first, pure bluffs heads-up above a fold and EV threshold - betting ranges keep a bluff share (size, street, style or new profile.aggression) - guards: no bluffs vs never-folders, no bluff catch vs ranges without bluffs - steal width in unopened pots from how often the blinds fold - combo-list sampling for narrow two-card ranges Co-Authored-By: Claude Opus 5.5 --- MODULES.md | 80 +++--- src/engine/bluff.rs | 89 ++++++ src/engine/called.rs | 32 +++ src/engine/called_equity.rs | 71 +++++ src/engine/decide.rs | 155 ++++++----- src/engine/mod.rs | 32 ++- src/engine/options.rs | 96 +++++-- src/engine/postflop.rs | 323 +++++++++++----------- src/engine/range_combos.rs | 33 +++ src/engine/range_filter.rs | 160 +++++++++-- src/equity/monte_carlo.rs | 164 +++++------ src/equity/sample.rs | 87 +++--- src/equity/villain_range.rs | 25 +- src/exploit/adjust.rs | 115 ++++---- src/exploit/bluff_share.rs | 47 ++++ src/exploit/call_floor.rs | 22 ++ src/exploit/fold_chance.rs | 56 ++++ src/exploit/fold_equity_scale.rs | 12 +- src/exploit/mod.rs | 50 ++-- src/exploit/profile.rs | 26 +- src/exploit/range_spec.rs | 59 ++-- src/exploit/steal_width.rs | 18 ++ src/exploit/street_continuation.rs | 284 +++++++++---------- src/exploit/style_rung.rs | 12 + src/exploit/style_shift.rs | 96 +++---- src/exploit/table_fold.rs | 26 ++ src/preflop/advise.rs | 167 ++++++------ src/wire/decode_villain.rs | 75 ++--- tests/bluff_fold_chance.rs | 79 ++++++ tests/bluff_property.rs | 150 ++++++++++ tests/bluff_range.rs | 91 ++++++ tests/bluff_share.rs | 63 +++++ tests/engine_multiway.rs | 228 ++++++++-------- tests/engine_uncertainty.rs | 185 ++++++------- tests/exploit_adjust.rs | 271 +++++++++--------- tests/exploit_range_guess.rs | 1 + tests/exploit_style.rs | 1 + tests/pipeline_bluff.rs | 145 ++++++++++ tests/pipeline_postflop_v2.rs | 425 +++++++++++++++-------------- tests/range_model_fixture/mod.rs | 228 ++++++++-------- tests/range_model_robust.rs | 312 ++++++++++----------- 41 files changed, 2871 insertions(+), 1720 deletions(-) create mode 100644 src/engine/bluff.rs create mode 100644 src/engine/called.rs create mode 100644 src/engine/called_equity.rs create mode 100644 src/engine/range_combos.rs create mode 100644 src/exploit/bluff_share.rs create mode 100644 src/exploit/call_floor.rs create mode 100644 src/exploit/fold_chance.rs create mode 100644 src/exploit/steal_width.rs create mode 100644 src/exploit/style_rung.rs create mode 100644 src/exploit/table_fold.rs create mode 100644 tests/bluff_fold_chance.rs create mode 100644 tests/bluff_property.rs create mode 100644 tests/bluff_range.rs create mode 100644 tests/bluff_share.rs create mode 100644 tests/pipeline_bluff.rs diff --git a/MODULES.md b/MODULES.md index 7c59eb3e..4d8e61bb 100644 --- a/MODULES.md +++ b/MODULES.md @@ -1,18 +1,19 @@ # Modulübersicht – pokerfreak Reiner, funktionaler Entscheidungskern in Rust (nur Standardbibliothek). -Eine Datei = ein Begriff. Ein- und Ausgabe gibt es nur in `src/main.rs`. +Eine Datei = ein Begriff. Ein- und Ausgabe gibt es nur in `src/main.rs` und im Generator `src/bin/`. ## Pipeline ``` stdin-Zeile → json::parse (parsen) - → wire::decode (Struktur → Spot) - → guard::validate (prüfen: Karten, Chips, legalActions) + → wire::decode (Struktur → Spot, inkl. optionaler history) + → guard::validate (prüfen: Karten im Deck der Variante, Chips, legalActions) → engine::decide (bewerten + wählen) preflop: exploit::adjust → preflop::advise → engine::from_plan - postflop: exploit::range_guess → equity::monte_carlo → engine::postflop + postflop: read::read → exploit::range_spec je Gegner → engine::range_filter + → equity::monte_carlo → engine::choose_postflop → guard::enforce (Legalitätswächter, letzte Instanz) → wire::encode (ausgeben) stdout-Zeile @@ -25,46 +26,55 @@ Zufall kommt nur aus `rng::Rng`, das als Wert mitgegeben wird (Seed: Erweiterung | Modul | Aufgabe | |---|---| -| `card` | Rang, Farbe, Karte (Langnamen laut Vertrag und Kurzform `Ah`), Deck als Wert: voll, ohne tote Karten, seeded ziehen | +| `card` | Rang, Farbe, Karte (Langnamen laut Vertrag und Kurzform `Ah`), Deck als Wert je Deck-Regel (52 oder 36 Karten), ohne tote Karten, seeded ziehen | | `rng` | SplitMix64 als Wert: jeder Aufruf liefert Zahl und nächsten Generator | -| `variant` | `Variant` plus **eine** Regeltabelle `rules`: Lochkarten, Kartennutzung (beste 5 / genau 2+3), Sizing-Regel (NoLimit, PotLimit, Menu, AllInOnly), Aktionsform (Full, Binary). Sonst fragt niemand nach dem Variantennamen. | -| `game` | Summentypen `Street`, `ActionKind`, `Choice` (nur `Raise` trägt eine Größe), `Decision`, `Confidence` (per Konstruktion in 0..1), `Spot`, `Villain` | +| `variant` | `Variant` plus **eine** Regeltabelle `rules`: Lochkarten, Kartennutzung, Sizing-Regel, Aktionsform, Deck-Regel (`FULL`, `SHORT` ab Sechs), Rangfolge der Kategorien (`Standard`, `FlushOverFullHouse`), Anzahl Burn-Karten. Sonst fragt niemand nach dem Variantennamen. | +| `game` | Summentypen `Street`, `ActionKind`, `Choice` (nur `Raise` trägt eine Größe), `Decision`, `Confidence`, `Spot`, `Villain`; dazu `SeenAction` und `ActionRecord` für die beobachtete Aktionsfolge | | `fault` | Fehler als Werte: Syntax, Missing, Invalid, Inconsistent, Exhausted | -| `hand` | Kategorien, total geordnete Stärke, 5-Karten-Bewertung, Teilmengen, `showdown::best` je Kartennutzung (Hold'em / Omaha genau 2+3) | -| `equity` | Monte-Carlo-Equity gegen Gegner-Ranges (`Any`, `Exact`, `Filter`), Rejection Sampling, Gleichstand anteilig geteilt, Standardfehler, Prüfung der Anfrage | -| `odds` | Break-even `toCall/(pot+toCall)`, Bluff-Break-even, Fold Equity, Erwartungswert für Fold/Check/Call/Raise | +| `hand` | Kategorien, total geordnete Stärke, 5-Karten-Bewertung je Deck-Regel und Rangfolge (Short Deck: A-6-7-8-9 ist eine Straße, Flush schlägt Full House), `showdown::best`/`judge` je Kartennutzung | +| `read` | Handlesen nach Boardtextur: Farbmuster, Paarung, Verbundenheit, Nässe (Tabelle in `texture_wetness`); gemachte Hand (Air … Straight Flush, Top Pair mit Kicker-Güte, Overpair, Set gegen Trips), Draws (Backdoor, Gutshot, OESD, Flush, Combo), Outs, Nut-Draw, Stärkestufe. `glance` ist der schnelle Pfad für Range-Filter. | +| `equity` | Monte-Carlo-Equity gegen Gegner-Ranges (`Any`, `Exact`, `Filter`), Rejection Sampling, Gleichstand anteilig geteilt, Standardfehler, Prüfung der Anfrage, Deck-Kapazität inklusive Burn-Reserve | +| `odds` | Break-even, Bluff-Break-even, Fold Equity, Erwartungswert je Aktion, Endpot | | `sizing` | Raise-Kandidaten je Sizing-Regel. `allowedSizes` sind wortgleich die **einzige** Quelle. Dazu Grenzen (inkl. Short-All-in), All-in, Einpassen, Preflop-Größen | -| `preflop` | 169-Klassen-Ranking (Hold'em) und Strukturwert mit empirischer Verteilung (PLO5) als Perzentil, Position, Situation (Unopened … FacingAllIn), Chart-Tabellen (Full und Push/Fold), Sicherheit, Begründungstext | -| `exploit` | Gegnerstil aus vpip/pfr/foldToBet (eng, loose-aggressiv, Calling Station), verschiebt `Thresholds`, schätzt die Gegner-Range (`top_fraction`) | -| `engine` | `postflop`: Bruchpunkt-Regel (Equity gegen Break-even plus Marge, EV-Maximum, ABSTAIN im Unsicherheitsband ± 2 Standardfehler). `from_plan`: Chart zu Aktion. `passive`: ohne Gegner die billigste Weiterspiel-Aktion. `decide`: setzt alles zusammen | -| `guard` | `validate` vor dem Denken. `enforce`/`repair` nach dem Denken: nie Fold bei freiem Check, Größen legal, Binary nur aufgeben oder All-in. `settle`/`ledger`: Chip-Bilanz | -| `json` | JSON-Wert, strikter RFC-8259-Parser, Renderer (kürzeste Round-trip-Zahlen), Feldzugriffe mit Pfad im Fehler | -| `wire` | Anfrage zu `Spot` (Kurz- und Langnamen von Karten), `Decision` zu Antwortzeile in Vertragsreihenfolge, `respond` als Pipeline | -| `main.rs` | Einzige unreine Stelle: liest Zeilen, schreibt Zeilen. Eine Panik wird zur ABSTAIN-Zeile. | +| `preflop` | Rankings und Perzentile (Hold'em 169 Klassen, Short Deck 81 Klassen, PLO5 Strukturwert), Button aus `buttonSeat` oder aus den geposteten Blinds, Position jedes Sitzes, Situation, Charts, Sicherheit, Begründung. Für Hold'em und AOF kommen die Charts aus der erzeugten CFR-Tabelle `generated_charts`. | +| `cfr` | Offline-Ableitung der Preflop-Charts mit CFR (siehe unten). Der Kern liest nur die erzeugte Tabelle. | +| `exploit` | Gegnerstil aus vpip/pfr/foldToBet, verschiebt `Thresholds`. Range-Modell aus der Aktionsfolge: Rolle preflop (Opener, Caller, 3-Bettor, Limper, All-in) ergibt ein Band im Ranking, gestreckt nach Profil; postflop setzt jede Bet/Raise je nach Größe eine Mindesthand und ob Draws weiterspielen. | +| `engine` | `decide` setzt alles zusammen. `choose_postflop`: Bruchpunkt-Regel (Equity gegen Break-even plus Marge, EV-Maximum). Dazu Texturhaltung, Multiway-Schwellen (Realisierung sinkt, Marge und Value-Hürde steigen je Gegner), Semibluff mit Fold Equity (nur bis zwei Gegner, nie am River), Unsicherheitsband → `ABSTAIN` mit kleiner Confidence (höchstens 0,3), Begründung nennt die gelesene Hand | +| `guard` | `validate` vor dem Denken (auch: Karten außerhalb des Decks, zu viele Spieler für das Deck). `enforce`/`repair` nach dem Denken. `settle`/`ledger`: Chip-Bilanz | +| `json` | JSON-Wert, strikter RFC-8259-Parser, Renderer, Feldzugriffe mit Pfad im Fehler | +| `wire` | Anfrage zu `Spot` (inkl. `history`), `Decision` zu Antwortzeile in Vertragsreihenfolge, `respond` als Pipeline | +| `main.rs` | Einzige unreine Stelle des Kerns: liest Zeilen, schreibt Zeilen. Eine Panik wird zur ABSTAIN-Zeile. | ## Erweiterungsfelder (optional, außerhalb von VERTRAG.md) -`buttonSeat` (für die Position), `seed`, `villains[].profile {vpip, pfr, foldToBet}`. -Fehlen sie, gelten konservative Standardwerte: unbekannte Position → Early-Chart, unbekannter Gegner → vpip 0,30. +| Feld | Bedeutung | +|---|---| +| `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}` | +| `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`. | -## Tests (318, `cargo test`) +Neue Variante `SHORT_DECK` (Alias `6+`). Fehlen die Felder, gelten konservative Standardwerte: ohne Position → Early-Chart, ohne Gegnerprofil → vpip 0,30, ohne `history` → die alte Range-Schätzung. -- **Komponenten:** card, hand, equity, odds, sizing, guard, engine, preflop, exploit, json, wire -- **Equity-Referenzen** (Quelle steht im Test: PokerStove/ProPokerTools, Wikipedia-Starthandtabelle): - - AA gegen KK ≈ 82/18 - - AKo gegen QQ ≈ 43/57 - - AKs gegen 22 ≈ 50/50 - - AA gegen drei zufällige Hände ≈ 64 % - - Flush-Draw ≈ 35 %, gegengeprüft durch exakte Enumeration - - River-Spots exakt +## CFR-Preflop-Charts + +PLATZHALTER_CFR + +## Tests (`cargo test`) + +- **Komponenten:** je Modul, darunter `read_*` (Texturen, gemachte Hände, Draws, Outs), `range_model_*`, `position_*` (alle Sitze, alle Tischgrößen, beide Zählweisen), `short_deck_*` +- **Equity-Referenzen** (Quelle steht im Test): + - Hold'em: AA gegen KK ≈ 82/18, AKo gegen QQ ≈ 43/57, AKs gegen 22 ≈ 50/50, AA gegen drei Zufallshände ≈ 64 %, Flush-Draw ≈ 35 % (gegengeprüft durch Enumeration) + - Short Deck, exakt enumeriert: AA gegen KK 74,26 %, AKs gegen QQ 54,28 %, AKo gegen JTs 49,35 %; Häufigkeiten der Fünf-Karten-Kategorien über alle 376 992 Hände - **Property-Tests:** - - `engine_property`: 4 × 3000 Zufalls-Spots, prüft Legalität, Größen, Chip-Erhalt und Idempotenz von `enforce` - - `pipeline_property`: 400 zufällige JSON-Anfragen durch die ganze Pipeline -- **Vertrag:** `pipeline_contract` mit dem Beispiel aus VERTRAG.md. Dessen FLOP hat nur eine Karte, die Antwort ist daher ABSTAIN. + - `engine_property`: Zufalls-Spots, prüft Legalität, Größen, Chip-Erhalt, Idempotenz von `enforce` + - `pipeline_property`: 400 zufällige JSON-Anfragen aller Varianten (Karten aus dem jeweiligen Deck, zufällige `history`) durch die ganze Pipeline +- **Spezifikation v2:** `pipeline_postflop_v2` (Short Deck, Range-Verengung, Position aus der Historie, Multiway, Semibluff, Unsicherheit) +- **Vertrag:** `pipeline_contract` mit dem Beispiel aus VERTRAG.md ## Annahmen und Grenzen -- `K_POKER` ist nur über den Namen bekannt. Er läuft mit Hold'em-Karten und der Sizing-Regel `Menu`: Größen kommen aus `allowedSizes`, freie Größen nur als Rückfall. -- Was der Held auf der laufenden Straße schon gesetzt hat, steht nicht im Vertrag. Ein Raise-to gilt deshalb vollständig als neu eingezahlt, gepostete Blinds werden ignoriert. -- Welcher Gegner gesetzt hat, ist unbekannt. Die Range-Verengung trifft deshalb alle aktiven Gegner gleich. -- Die Charts sind Heuristik-Tabellen in `preflop/full_chart.rs` und `preflop/push_chart.rs`, keine Solver-Ausgabe. Meilenstein 5 (CFR offline) ist nicht umgesetzt. +- `K_POKER` läuft mit Hold'em-Karten und der Sizing-Regel `Menu`. +- Was der Held auf der laufenden Straße schon gesetzt hat, steht nicht im Vertrag. Ein Raise-to gilt vollständig als neu eingezahlt. +- Ohne `history` ist unbekannt, welcher Gegner gesetzt hat. Dann trifft die Range-Schätzung alle aktiven Gegner gleich. +- Short Deck: Straße schlägt Drilling (häufigste Regelung). Drei Burn-Karten werden nur als Platzbedarf im Deck geprüft, sie ändern die Equity nicht. diff --git a/src/engine/bluff.rs b/src/engine/bluff.rs new file mode 100644 index 00000000..2f1c5691 --- /dev/null +++ b/src/engine/bluff.rs @@ -0,0 +1,89 @@ +//! Bluffing and bluff catching: when a raise without a value hand pays, and when a call +//! with a hand that only beats bluffs is allowed. +//! +//! | rule | value | +//! |---|---| +//! | two branches | `EV = P(fold) * pot + (1 - P(fold)) * (called share * final pot - added)` | +//! | semibluff | real draw (`semibluff::has_real_draw`), at most two villains, fold branch > 0, EV > 0 and above the best passive line | +//! | pure bluff | weak hand without a real draw, heads-up, P(fold) >= 0.5, EV > 0 and at least 0.05 pot above the best passive line | +//! | never bluff | no semibluff or bluff when any live villain's foldToBet is at most 0.12 | +//! | never bluff-catch | facing a bet without a real draw, a hand below the bettor's value floor may not call when their bluff share is under 0.05 | + +use super::semibluff::has_real_draw; +use crate::exploit::range_spec::Continuation; +use crate::exploit::street_continuation::continuations; +use crate::game::{Spot, Villain}; +use crate::odds::ev::final_pot; +use crate::read::hand_read::HandRead; +use crate::read::tier::{tier, Tier}; + +/// A villain with foldToBet at or below this never folds: no bluffs against them. +pub const NEVER_FOLDS: f64 = 0.12; +/// A pure bluff needs at least this chance that everyone folds. +pub const PURE_BLUFF_MIN_FOLD: f64 = 0.5; +/// A pure bluff must beat the passive line by this share of the pot. +pub const PURE_BLUFF_EDGE: f64 = 0.05; +/// Below this bluff share a betting range counts as pure value. +pub const MIN_BLUFF_SHARE: f64 = 0.05; + +/// Why a raise is made. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum RaiseKind { + Value, + Semibluff, + Bluff, +} + +/// The two branches of a raise to `to` and their sum, in chips relative to folding now. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Branches { + /// `P(fold) * pot`: everyone folds, hero takes the pot. + pub fold: f64, + /// `(1 - P(fold)) * (called share * final pot - added)`: hero is called. + pub called: f64, + pub total: f64, +} + +/// `fold` = P(every villain folds), `called_share` = hero's (realised) share against the +/// calling range. Hero adds `to` (nothing committed on this street, see `odds::ev`). +pub fn branches(spot: &Spot, to: f64, fold: f64, called_share: f64) -> Branches { + let fold_branch = fold * spot.pot; + let called = (1.0 - fold) * (called_share * final_pot(spot.pot, spot.to_call, to) - to); + Branches { fold: fold_branch, called, total: fold_branch + called } +} + +/// Some live villain never folds (foldToBet at or below `NEVER_FOLDS`). +pub fn never_folds(spot: &Spot) -> bool { + spot.live_villains() + .any(|v| v.profile.and_then(|p| p.fold_to_bet).is_some_and(|f| f <= NEVER_FOLDS)) +} + +/// A hand to bluff with: weak and without a real draw. +pub fn is_bluff_hand(read: &HandRead, spot: &Spot) -> bool { + tier(read.made) == Tier::Weak && !has_real_draw(read, spot.street) +} + +/// The live villain who made the last bet or raise on this street, with their +/// continuation there. +fn bettor(spot: &Spot) -> Option<(&Villain, Continuation)> { + let seat = spot + .history + .iter() + .rev() + .find(|r| r.street == spot.street && r.action.is_aggressive()) + .map(|r| r.seat)?; + let villain = spot.live_villains().find(|v| v.seat == seat)?; + let here = continuations(spot, villain) + .into_iter() + .find(|c| c.board_len == spot.street.board_len())?; + Some((villain, here)) +} + +/// Calling would be a bluff catch against a range without bluffs: hero faces a bet, +/// holds no real draw, sits below the bettor's value floor, and the bettor's bluff share +/// is under `MIN_BLUFF_SHARE`. Unknown bettor (no history): never blocked. +pub fn bluff_catch_blocked(spot: &Spot, read: &HandRead) -> bool { + spot.to_call > 0.0 + && !has_real_draw(read, spot.street) + && bettor(spot).is_some_and(|(_, c)| read.made < c.min_made && c.bluff_share < MIN_BLUFF_SHARE) +} diff --git a/src/engine/called.rs b/src/engine/called.rs new file mode 100644 index 00000000..f2cca422 --- /dev/null +++ b/src/engine/called.rs @@ -0,0 +1,32 @@ +/// Hero's equity share in the called branch of a raise: against the hands that call +/// it, not against the whole range (a bet folds out the weak part, the rest is stronger). +/// Raw shares, before the multiway realisation discount. +#[derive(Clone, Debug, PartialEq)] +pub struct Called { + by_size: Vec<(f64, f64)>, + flat: Option, +} + +impl Called { + /// The same share for every size (no calling-range model: the whole range calls). + pub fn flat(share: f64) -> Called { + Called { by_size: Vec::new(), flat: Some(share) } + } + + /// One share per raise-to amount. + pub fn sized(by_size: Vec<(f64, f64)>) -> Called { + Called { by_size, flat: None } + } + + /// The share for a raise to `to`; `fallback` when the size is unknown or the share + /// is not a probability. + pub fn share_at(&self, to: f64, fallback: f64) -> f64 { + self.by_size + .iter() + .find(|(size, _)| (size - to).abs() < 1e-9) + .map(|(_, share)| *share) + .or(self.flat) + .filter(|s| s.is_finite() && (0.0..=1.0).contains(s)) + .unwrap_or(fallback) + } +} diff --git a/src/engine/called_equity.rs b/src/engine/called_equity.rs new file mode 100644 index 00000000..6334e659 --- /dev/null +++ b/src/engine/called_equity.rs @@ -0,0 +1,71 @@ +use super::called::Called; +use super::range_combos::{as_ranges, combos}; +use super::range_filter::{range_filter, HandFilter}; +use crate::card::Card; +use crate::equity::monte_carlo::estimate; +use crate::equity::query::Query; +use crate::equity::villain_range::VillainRange; +use crate::exploit::call_floor::call_continuation; +use crate::exploit::range_model::range_spec; +use crate::exploit::size_notch::size_notch; +use crate::exploit::table_fold::pressure_ratio; +use crate::game::{ActionKind, Spot}; +use crate::rng::Rng; +use crate::sizing::candidates::candidates; + +/// Trials per calling-range simulation (one per size notch, so a few per decision). +const CALLED_TRIALS: u32 = 1000; + +/// Hero's share against the hands that call a raise to each candidate size. +/// +/// Each live villain keeps their modelled range (`range_spec`) plus the calling floor +/// for that pressure (`exploit::call_floor`). Sizes in the same `size_notch` share one +/// simulation. A size whose simulation fails is left out (the engine then falls back +/// to the overall share). No legal raise: nothing to compute. +pub fn called_equity(spot: &Spot) -> Called { + if !spot.is_legal(ActionKind::Raise) { + return Called::sized(Vec::new()); + } + let notched: Vec<(f64, i32, f64)> = candidates(spot) + .into_iter() + .map(|to| { + let ratio = pressure_ratio(spot.pot, spot.to_call, to); + (to, size_notch(Some(ratio)), ratio) + }) + .collect(); + let shares: Vec<(i32, Option)> = notched.iter().fold(Vec::new(), |mut done, (_, notch, ratio)| { + if !done.iter().any(|(n, _)| n == notch) { + done.push((*notch, simulate(spot, *notch, *ratio))); + } + done + }); + Called::sized( + notched + .into_iter() + .filter_map(|(to, notch, _)| { + shares.iter().find(|(n, _)| *n == notch).and_then(|(_, s)| *s).map(|s| (to, s)) + }) + .collect(), + ) +} + +fn simulate(spot: &Spot, notch: i32, ratio: f64) -> Option { + let rules = spot.rules(); + let filters: Vec = spot + .live_villains() + .map(|v| { + let mut spec = range_spec(spot, v); + spec.continues.push(call_continuation(v, spot.street, ratio)); + range_filter(&spec, rules, spot.variant, &spot.board) + }) + .collect(); + if filters.is_empty() { + return None; + } + let dead: Vec = spot.hero_cards.iter().chain(&spot.board).copied().collect(); + let lists: Vec<_> = filters.iter().map(|f| combos(&rules, f, &dead)).collect(); + let ranges: Vec = as_ranges(&filters, &lists); + let query = Query { rules, hero: &spot.hero_cards, board: &spot.board, villains: &ranges, trials: CALLED_TRIALS }; + let seed = spot.seed ^ (0xCA11_0000_u64 + (notch + 8).clamp(0, 64) as u64); + estimate(&query, Rng::seeded(seed)).ok().map(|(e, _)| e.share) +} diff --git a/src/engine/decide.rs b/src/engine/decide.rs index b5bfdb10..0a488192 100644 --- a/src/engine/decide.rs +++ b/src/engine/decide.rs @@ -1,74 +1,81 @@ -use super::from_plan::from_plan; -use super::passive::cheapest_continue; -use super::postflop::choose_postflop; -use super::range_filter::{range_filter, HandFilter}; -use crate::equity::monte_carlo::estimate; -use crate::equity::query::Query; -use crate::equity::villain_range::VillainRange; -use crate::exploit::adjust::adjust; -use crate::exploit::profile::Profile; -use crate::exploit::range_model::range_spec; -use crate::exploit::thresholds::Thresholds; -use crate::game::{Decision, Spot, Street}; -use crate::guard::enforce::enforce; -use crate::preflop::advise::advise; -use crate::read::hand_read::read; -use crate::rng::Rng; - -const TRIALS_TWO_CARD: u32 = 3000; -const TRIALS_FIVE_CARD: u32 = 1500; - -fn trials(spot: &Spot) -> u32 { - if spot.rules().hole_cards >= 5 { - TRIALS_FIVE_CARD - } else { - TRIALS_TWO_CARD - } -} - -/// Postflop: read the hand, model each live villain's range, simulate, choose. -fn postflop(spot: &Spot, thresholds: &Thresholds) -> Decision { - let rules = spot.rules(); - let hand_read = match read(&rules, &spot.hero_cards, &spot.board) { - Ok(r) => r, - Err(fault) => return Decision::abstain(format!("hand read unavailable: {fault}")), - }; - let filters: Vec = spot - .live_villains() - .map(|v| range_filter(&range_spec(spot, v), rules, spot.variant, &spot.board)) - .collect(); - if filters.is_empty() { - return cheapest_continue(spot).map_or_else( - || Decision::abstain("no live opponent and nothing to continue with"), - |choice| Decision::new(choice, 0.5, "no live opponents: cheapest continuing action"), - ); - } - let ranges: Vec = - filters.iter().map(|f| VillainRange::Filter(f.as_ref())).collect(); - let query = Query { - rules, - hero: &spot.hero_cards, - board: &spot.board, - villains: &ranges, - trials: trials(spot), - }; - match estimate(&query, Rng::seeded(spot.seed)) { - Ok((equity, _)) => choose_postflop(spot, &equity, thresholds, &hand_read), - Err(fault) => Decision::abstain(format!("equity unavailable: {fault}")), - } -} - -fn think(spot: &Spot) -> Decision { - let profiles: Vec = spot.live_villains().filter_map(|v| v.profile).collect(); - let thresholds = adjust(Thresholds::BASE, &profiles); - match spot.street { - Street::Preflop => from_plan(spot, &advise(spot, &thresholds)), - Street::Flop | Street::Turn | Street::River => postflop(spot, &thresholds), - } -} - -/// Full decision for a validated spot (preflop chart or postflop read/equity/EV), -/// always passed through `guard::enforce::enforce`. -pub fn decide(spot: &Spot) -> Decision { - enforce(spot, think(spot)) -} +use super::called_equity::called_equity; +use super::from_plan::from_plan; +use super::passive::cheapest_continue; +use super::postflop::choose_postflop_with; +use super::range_combos::{as_ranges, combos}; +use super::range_filter::{range_filter, HandFilter}; +use crate::card::Card; +use crate::equity::monte_carlo::estimate; +use crate::equity::query::Query; +use crate::equity::villain_range::VillainRange; +use crate::exploit::adjust::adjust; +use crate::exploit::profile::Profile; +use crate::exploit::range_model::range_spec; +use crate::exploit::thresholds::Thresholds; +use crate::game::{Decision, Spot, Street}; +use crate::guard::enforce::enforce; +use crate::preflop::advise::advise; +use crate::read::hand_read::read; +use crate::rng::Rng; + +const TRIALS_TWO_CARD: u32 = 3000; +const TRIALS_FIVE_CARD: u32 = 1500; + +fn trials(spot: &Spot) -> u32 { + if spot.rules().hole_cards >= 5 { + TRIALS_FIVE_CARD + } else { + TRIALS_TWO_CARD + } +} + +/// Postflop: read the hand, model each live villain's range, simulate against it and +/// against the hands that would call each raise, choose. +fn postflop(spot: &Spot, thresholds: &Thresholds) -> Decision { + let rules = spot.rules(); + let hand_read = match read(&rules, &spot.hero_cards, &spot.board) { + Ok(r) => r, + Err(fault) => return Decision::abstain(format!("hand read unavailable: {fault}")), + }; + let filters: Vec = spot + .live_villains() + .map(|v| range_filter(&range_spec(spot, v), rules, spot.variant, &spot.board)) + .collect(); + if filters.is_empty() { + return cheapest_continue(spot).map_or_else( + || Decision::abstain("no live opponent and nothing to continue with"), + |choice| Decision::new(choice, 0.5, "no live opponents: cheapest continuing action"), + ); + } + let dead: Vec = spot.hero_cards.iter().chain(&spot.board).copied().collect(); + let lists: Vec<_> = filters.iter().map(|f| combos(&rules, f, &dead)).collect(); + let ranges: Vec = as_ranges(&filters, &lists); + let query = Query { + rules, + hero: &spot.hero_cards, + board: &spot.board, + villains: &ranges, + trials: trials(spot), + }; + match estimate(&query, Rng::seeded(spot.seed)) { + Ok((equity, _)) => { + choose_postflop_with(spot, &equity, &called_equity(spot), thresholds, &hand_read) + } + Err(fault) => Decision::abstain(format!("equity unavailable: {fault}")), + } +} + +fn think(spot: &Spot) -> Decision { + let profiles: Vec = spot.live_villains().filter_map(|v| v.profile).collect(); + let thresholds = adjust(Thresholds::BASE, &profiles); + match spot.street { + Street::Preflop => from_plan(spot, &advise(spot, &thresholds)), + Street::Flop | Street::Turn | Street::River => postflop(spot, &thresholds), + } +} + +/// Full decision for a validated spot (preflop chart or postflop read/equity/EV), +/// always passed through `guard::enforce::enforce`. +pub fn decide(spot: &Spot) -> Decision { + enforce(spot, think(spot)) +} diff --git a/src/engine/mod.rs b/src/engine/mod.rs index c8db2262..dd352f02 100644 --- a/src/engine/mod.rs +++ b/src/engine/mod.rs @@ -1,14 +1,18 @@ -//! Engine: composes assessment and choice into a decision. - -pub mod decide; -pub mod effective; -pub mod from_plan; -pub mod multiway; -pub mod options; -pub mod passive; -pub mod postflop; -pub mod range_filter; -pub mod read_label; -pub mod semibluff; -pub mod texture_stance; -pub mod uncertainty; +//! Engine: composes assessment and choice into a decision. + +pub mod bluff; +pub mod called; +pub mod called_equity; +pub mod decide; +pub mod effective; +pub mod from_plan; +pub mod multiway; +pub mod options; +pub mod passive; +pub mod postflop; +pub mod range_combos; +pub mod range_filter; +pub mod read_label; +pub mod semibluff; +pub mod texture_stance; +pub mod uncertainty; diff --git a/src/engine/options.rs b/src/engine/options.rs index c4cb0d92..cd70ea28 100644 --- a/src/engine/options.rs +++ b/src/engine/options.rs @@ -1,8 +1,15 @@ +use super::bluff::{ + bluff_catch_blocked, branches, is_bluff_hand, never_folds, RaiseKind, PURE_BLUFF_EDGE, + PURE_BLUFF_MIN_FOLD, +}; +use super::called::Called; use super::effective::Effective; +use super::multiway::realized_share; use super::semibluff::has_real_draw; +use crate::exploit::table_fold::table_fold; use crate::exploit::thresholds::Thresholds; use crate::game::{ActionKind, Choice, Spot}; -use crate::odds::{break_even::break_even, ev, fold_equity::fold_equity}; +use crate::odds::{break_even::break_even, ev}; use crate::read::hand_read::HandRead; use crate::sizing::candidates::candidates; @@ -11,6 +18,8 @@ use crate::sizing::candidates::candidates; pub struct Scored { pub choice: Choice, pub ev: f64, + /// Why, for raises; `None` for passive choices. + pub kind: Option, } /// EV of the best non-raising line, ignoring the call margin: check when free, the raw @@ -29,46 +38,77 @@ pub fn is_value_raise(eff: &Effective) -> bool { eff.raise_ok && eff.value_ok && eff.share >= eff.value_raise } +/// What kind of raise this hand could make here, if any. +fn raise_kind(spot: &Spot, eff: &Effective, read: &HandRead) -> Option { + let bluffable = eff.raise_ok && !never_folds(spot); + if is_value_raise(eff) { + Some(RaiseKind::Value) + } else if bluffable && eff.semibluff_ok && has_real_draw(read, spot.street) { + Some(RaiseKind::Semibluff) + } else if bluffable && eff.villains == 1 && is_bluff_hand(read, spot) { + Some(RaiseKind::Bluff) + } else { + None + } +} + /// Every action the rule lets hero consider, in preference order (passive first, so /// ties keep the cheaper line). With `eff` the effective (texture and multiway /// adjusted) numbers and `share = eff.share`: /// * check, when legal; -/// * call, when legal and `share >= break_even + eff.call_margin`; +/// * call, when legal, `share >= break_even + eff.call_margin`, and not a blocked bluff +/// catch (`bluff::bluff_catch_blocked`); /// * fold, when legal and check is not; -/// * each sizing candidate as a raise, when legal and either +/// * each sizing candidate as a raise, valued over two branches (`bluff::branches`): +/// P(all fold) from each villain's profile (`exploit::table_fold`, times +/// `fold_equity_scale`) and the share against the calling range (`called`, realised +/// for the table size). Kept when /// - it is a value raise (`is_value_raise`), or -/// - it is a semibluff: raising is allowed, at most two villains, a real draw -/// (`semibluff::has_real_draw`), and the raise EV is strictly above `passive_ev`. -/// -/// The raise EV uses `fold_equity(pot, to, fold_equity_scale, live villains)`, i.e. -/// `fe * pot + (1 - fe) * (share * final_pot - added)`. Pure bluffs never qualify. -pub fn scored(spot: &Spot, eff: &Effective, thresholds: &Thresholds, read: &HandRead) -> Vec { +/// - a semibluff (real draw, at most two villains, nobody who never folds) with a +/// positive fold branch, EV > 0 and EV above `passive_ev`, or +/// - a pure bluff (weak hand, heads-up, nobody who never folds) with P(fold) >= 0.5, +/// EV > 0 and EV at least `PURE_BLUFF_EDGE` pots above `passive_ev`. +pub fn scored( + spot: &Spot, + eff: &Effective, + thresholds: &Thresholds, + read: &HandRead, + called: &Called, +) -> Vec { let share = eff.share; let free = spot.is_legal(ActionKind::Check); let be = break_even(spot.pot, spot.to_call); - let live = spot.live_villains().count(); + let passive = |choice, ev| Scored { choice, ev, kind: None }; - let check = free.then(|| Scored { choice: Choice::Check, ev: ev::check(share, spot.pot) }); - let call = (spot.is_legal(ActionKind::Call) && share >= be + eff.call_margin) - .then(|| Scored { choice: Choice::Call, ev: ev::call(share, spot.pot, spot.to_call) }); - let fold = (spot.is_legal(ActionKind::Fold) && !free) - .then(|| Scored { choice: Choice::Fold, ev: ev::fold() }); + let check = free.then(|| passive(Choice::Check, ev::check(share, spot.pot))); + let call = (spot.is_legal(ActionKind::Call) + && share >= be + eff.call_margin + && !bluff_catch_blocked(spot, read)) + .then(|| passive(Choice::Call, ev::call(share, spot.pot, spot.to_call))); + let fold = (spot.is_legal(ActionKind::Fold) && !free).then(|| passive(Choice::Fold, ev::fold())); - let value = is_value_raise(eff); - let semi = eff.raise_ok && eff.semibluff_ok && has_real_draw(read, spot.street); + let kind = raise_kind(spot, eff, read).filter(|_| spot.is_legal(ActionKind::Raise)); let floor = passive_ev(spot, share).unwrap_or(f64::NEG_INFINITY); - let sizes = if spot.is_legal(ActionKind::Raise) && (value || semi) { + let raises = kind.map_or_else(Vec::new, |kind| { candidates(spot) - } else { - Vec::new() - }; - let raises = sizes - .into_iter() - .map(|to| { - let fe = fold_equity(spot.pot, to, thresholds.fold_equity_scale, live); - Scored { choice: Choice::Raise { to }, ev: ev::raise(share, spot.pot, spot.to_call, to, fe) } - }) - .filter(move |s| value || s.ev > floor); + .into_iter() + .filter_map(|to| { + let fe = table_fold(spot, to, thresholds.fold_equity_scale); + let against = realized_share(called.share_at(to, share), eff.villains); + let b = branches(spot, to, fe, against); + let keep = match kind { + RaiseKind::Value => true, + RaiseKind::Semibluff => b.fold > 0.0 && b.total > 0.0 && b.total > floor, + RaiseKind::Bluff => { + fe >= PURE_BLUFF_MIN_FOLD + && b.total > 0.0 + && b.total >= floor + PURE_BLUFF_EDGE * spot.pot + } + }; + keep.then_some(Scored { choice: Choice::Raise { to }, ev: b.total, kind: Some(kind) }) + }) + .collect() + }); check .into_iter() diff --git a/src/engine/postflop.rs b/src/engine/postflop.rs index 87855056..c1503b95 100644 --- a/src/engine/postflop.rs +++ b/src/engine/postflop.rs @@ -1,153 +1,170 @@ -use super::effective::{effective, Effective}; -use super::options::{is_value_raise, passive_ev, scored, Scored}; -use super::passive::cheapest_continue; -use super::read_label::describe; -use super::uncertainty::abstain_confidence; -use crate::equity::estimate::Estimate; -use crate::exploit::thresholds::Thresholds; -use crate::game::{ActionKind, Choice, Decision, Spot}; -use crate::odds::{break_even::break_even, ev}; -use crate::read::hand_read::HandRead; - -fn label(choice: Choice, semibluff: bool) -> String { - match choice { - Choice::Raise { to } if semibluff => format!("semibluff raise to {to:.2}"), - Choice::Raise { to } => format!("raise to {to:.2}"), - other => other.name().to_lowercase(), - } -} - -/// Highest EV wins; the first of equals wins (options are ordered passive first). -fn best(options: &[Scored]) -> Option { - options.iter().copied().fold(None, |acc, s| match acc { - Some(b) if b.ev >= s.ev => Some(b), - _ => Some(s), - }) -} - -/// EV lead of the winner over the next-best alternative, counting folding (0) and the -/// call it passed up. -fn lead(spot: &Spot, share: f64, options: &[Scored], winner: Scored) -> f64 { - let rivals = options - .iter() - .filter(|s| s.choice != winner.choice) - .map(|s| s.ev) - .chain((winner.choice != Choice::Fold).then(ev::fold)) - .chain( - (winner.choice == Choice::Fold && spot.is_legal(ActionKind::Call)) - .then(|| ev::call(share, spot.pot, spot.to_call)), - ); - rivals - .fold(None, |m: Option, x| Some(m.map_or(x, |m| m.max(x)))) - .map_or(winner.ev.abs(), |r| winner.ev - r) -} - -fn confidence(spot: &Spot, gap: f64) -> f64 { - let scale = (spot.pot + spot.to_call).max(spot.big_blind).max(f64::MIN_POSITIVE); - 0.5 + 0.5 * (4.0 * gap.max(0.0) / scale).tanh() -} - -/// Opening of every reason: the read, plus the player count when multiway. -fn headline(read: &HandRead, eff: &Effective) -> String { - if eff.villains > 1 { - format!("{} ({}-way)", describe(read), eff.villains) - } else { - describe(read) - } -} - -/// `(lead, error)` when a raise leads the best passive line by less than its own EV -/// standard error, `std_error * final pot` (the money at stake). A negative lead -/// (the passive line is worth more) counts as inside the error. -fn marginal_raise( - spot: &Spot, - eff: &Effective, - estimate: &Estimate, - to: f64, - raise_ev: f64, -) -> Option<(f64, f64)> { - let passive = passive_ev(spot, eff.share)?; - let gap = raise_ev - passive; - let error = estimate.std_error.max(0.0) * ev::final_pot(spot.pot, spot.to_call, to); - (gap < error).then_some((gap, error)) -} - -/// The rule for a postflop spot, given an equity estimate and the hand read. -/// -/// 1. Invalid equity: ABSTAIN with confidence 0. -/// 2. `effective` (texture stance x multiway) gives the realised share, call margin, -/// value threshold and which raises are allowed. -/// 3. Score check / call / fold / value raises / semibluffs (`options::scored`) and take -/// the maximum EV. Never folds when check is legal. -/// 4. Uncertainty: facing fold-or-call with `|share - (break-even + call margin)| < -/// abstain_band + 2 * std_error`, or a winning raise whose EV lead over the best -/// passive line is below `std_error * final pot`: ABSTAIN with a small confidence -/// (0.05..0.30, `uncertainty::abstain_confidence`). -/// 5. Otherwise `confidence` rises with the EV lead over the runner-up, relative to the pot. -pub fn choose_postflop( - spot: &Spot, - estimate: &Estimate, - thresholds: &Thresholds, - read: &HandRead, -) -> Decision { - let raw = estimate.share; - if !(raw.is_finite() && (0.0..=1.0).contains(&raw)) { - return Decision::abstain("equity unavailable"); - } - let eff = effective(spot, raw, thresholds, read); - let share = eff.share; - let be = break_even(spot.pot, spot.to_call); - let breakpoint = be + eff.call_margin; - let band = thresholds.abstain_band + 2.0 * estimate.std_error.max(0.0); - let facing_choice = spot.is_legal(ActionKind::Fold) - && spot.is_legal(ActionKind::Call) - && !spot.is_legal(ActionKind::Check); - let head = headline(read, &eff); - let options = scored(spot, &eff, thresholds, read); - let winner = best(&options); - - if let Some(Scored { choice: Choice::Raise { to }, ev: raise_ev }) = winner { - if let Some((gap, error)) = marginal_raise(spot, &eff, estimate, to, raise_ev) { - return Decision::new( - Choice::Abstain, - abstain_confidence(gap, error), - format!("{head}: raise EV lead {gap:+.2} inside its error {error:.2}"), - ); - } - } else if facing_choice && (share - breakpoint).abs() < band { - return Decision::new( - Choice::Abstain, - abstain_confidence((share - breakpoint).abs(), band), - format!( - "{head}: equity {raw:.2} (realised {share:.2}) vs break-even {be:.2} + margin {:.2}: inside uncertainty band {band:.3}", - eff.call_margin - ), - ); - } - - match winner { - Some(w) => { - let shown = match w.choice { - Choice::Fold => ev::call(share, spot.pot, spot.to_call), - _ => w.ev, - }; - let name = match w.choice { - Choice::Fold => "call".to_string(), - other => label(other, !is_value_raise(&eff)), - }; - Decision::new( - w.choice, - confidence(spot, lead(spot, share, &options, w)), - format!("{head}: equity {raw:.2} vs break-even {be:.2}, EV {name} {shown:+.2}"), - ) - } - None => match cheapest_continue(spot) { - Some(choice) => Decision::new( - choice, - 0.5, - format!("{head}: equity {raw:.2} vs break-even {be:.2}, only continuing action available"), - ), - None => Decision::abstain("no actionable option"), - }, - } -} +use super::bluff::RaiseKind; +use super::called::Called; +use super::effective::{effective, Effective}; +use super::options::{passive_ev, scored, Scored}; +use super::passive::cheapest_continue; +use super::read_label::describe; +use super::uncertainty::abstain_confidence; +use crate::equity::estimate::Estimate; +use crate::exploit::thresholds::Thresholds; +use crate::game::{ActionKind, Choice, Decision, Spot}; +use crate::odds::{break_even::break_even, ev}; +use crate::read::hand_read::HandRead; + +fn label(choice: Choice, kind: Option) -> String { + match (choice, kind) { + (Choice::Raise { to }, Some(RaiseKind::Semibluff)) => format!("semibluff raise to {to:.2}"), + (Choice::Raise { to }, Some(RaiseKind::Bluff)) => format!("bluff raise to {to:.2}"), + (Choice::Raise { to }, _) => format!("raise to {to:.2}"), + (other, _) => other.name().to_lowercase(), + } +} + +/// Highest EV wins; the first of equals wins (options are ordered passive first). +fn best(options: &[Scored]) -> Option { + options.iter().copied().fold(None, |acc, s| match acc { + Some(b) if b.ev >= s.ev => Some(b), + _ => Some(s), + }) +} + +/// EV lead of the winner over the next-best alternative, counting folding (0) and the +/// call it passed up. +fn lead(spot: &Spot, share: f64, options: &[Scored], winner: Scored) -> f64 { + let rivals = options + .iter() + .filter(|s| s.choice != winner.choice) + .map(|s| s.ev) + .chain((winner.choice != Choice::Fold).then(ev::fold)) + .chain( + (winner.choice == Choice::Fold && spot.is_legal(ActionKind::Call)) + .then(|| ev::call(share, spot.pot, spot.to_call)), + ); + rivals + .fold(None, |m: Option, x| Some(m.map_or(x, |m| m.max(x)))) + .map_or(winner.ev.abs(), |r| winner.ev - r) +} + +fn confidence(spot: &Spot, gap: f64) -> f64 { + let scale = (spot.pot + spot.to_call).max(spot.big_blind).max(f64::MIN_POSITIVE); + 0.5 + 0.5 * (4.0 * gap.max(0.0) / scale).tanh() +} + +/// Opening of every reason: the read, plus the player count when multiway. +fn headline(read: &HandRead, eff: &Effective) -> String { + if eff.villains > 1 { + format!("{} ({}-way)", describe(read), eff.villains) + } else { + describe(read) + } +} + +/// `(lead, error)` when a raise leads the best passive line by less than its own EV +/// standard error, `std_error * final pot` (the money at stake). A negative lead +/// (the passive line is worth more) counts as inside the error. +fn marginal_raise( + spot: &Spot, + eff: &Effective, + estimate: &Estimate, + to: f64, + raise_ev: f64, +) -> Option<(f64, f64)> { + let passive = passive_ev(spot, eff.share)?; + let gap = raise_ev - passive; + let error = estimate.std_error.max(0.0) * ev::final_pot(spot.pot, spot.to_call, to); + (gap < error).then_some((gap, error)) +} + +/// `choose_postflop_with` when nothing is known about the calling range: the whole +/// range calls, so the called branch uses the overall share. +pub fn choose_postflop( + spot: &Spot, + estimate: &Estimate, + thresholds: &Thresholds, + read: &HandRead, +) -> Decision { + choose_postflop_with(spot, estimate, &Called::flat(estimate.share), thresholds, read) +} + +/// The rule for a postflop spot, given an equity estimate, the share against the +/// calling range per raise size (`called`) and the hand read. +/// +/// 1. Invalid equity: ABSTAIN with confidence 0. +/// 2. `effective` (texture stance x multiway) gives the realised share, call margin, +/// value threshold and which raises are allowed. +/// 3. Score check / call / fold / value raises / semibluffs / bluffs (`options::scored`, +/// raises over two branches: fold and called) and take the maximum EV. Never folds +/// when check is legal. +/// 4. Uncertainty: facing fold-or-call with `|share - (break-even + call margin)| < +/// abstain_band + 2 * std_error`, or a winning raise whose EV lead over the best +/// passive line is below `std_error * final pot`: ABSTAIN with a small confidence +/// (0.05..0.30, `uncertainty::abstain_confidence`). +/// 5. Otherwise `confidence` rises with the EV lead over the runner-up, relative to the pot. +pub fn choose_postflop_with( + spot: &Spot, + estimate: &Estimate, + called: &Called, + thresholds: &Thresholds, + read: &HandRead, +) -> Decision { + let raw = estimate.share; + if !(raw.is_finite() && (0.0..=1.0).contains(&raw)) { + return Decision::abstain("equity unavailable"); + } + let eff = effective(spot, raw, thresholds, read); + let share = eff.share; + let be = break_even(spot.pot, spot.to_call); + let breakpoint = be + eff.call_margin; + let band = thresholds.abstain_band + 2.0 * estimate.std_error.max(0.0); + let facing_choice = spot.is_legal(ActionKind::Fold) + && spot.is_legal(ActionKind::Call) + && !spot.is_legal(ActionKind::Check); + let head = headline(read, &eff); + let options = scored(spot, &eff, thresholds, read, called); + let winner = best(&options); + + if let Some(Scored { choice: Choice::Raise { to }, ev: raise_ev, .. }) = winner { + if let Some((gap, error)) = marginal_raise(spot, &eff, estimate, to, raise_ev) { + return Decision::new( + Choice::Abstain, + abstain_confidence(gap, error), + format!("{head}: raise EV lead {gap:+.2} inside its error {error:.2}"), + ); + } + } else if facing_choice && (share - breakpoint).abs() < band { + return Decision::new( + Choice::Abstain, + abstain_confidence((share - breakpoint).abs(), band), + format!( + "{head}: equity {raw:.2} (realised {share:.2}) vs break-even {be:.2} + margin {:.2}: inside uncertainty band {band:.3}", + eff.call_margin + ), + ); + } + + match winner { + Some(w) => { + let shown = match w.choice { + Choice::Fold => ev::call(share, spot.pot, spot.to_call), + _ => w.ev, + }; + let name = match w.choice { + Choice::Fold => "call".to_string(), + other => label(other, w.kind), + }; + Decision::new( + w.choice, + confidence(spot, lead(spot, share, &options, w)), + format!("{head}: equity {raw:.2} vs break-even {be:.2}, EV {name} {shown:+.2}"), + ) + } + None => match cheapest_continue(spot) { + Some(choice) => Decision::new( + choice, + 0.5, + format!("{head}: equity {raw:.2} vs break-even {be:.2}, only continuing action available"), + ), + None => Decision::abstain("no actionable option"), + }, + } +} diff --git a/src/engine/range_combos.rs b/src/engine/range_combos.rs new file mode 100644 index 00000000..3bf38d97 --- /dev/null +++ b/src/engine/range_combos.rs @@ -0,0 +1,33 @@ +use super::range_filter::HandFilter; +use crate::card::{deck, Card}; +use crate::equity::villain_range::VillainRange; +use crate::variant::Rules; + +/// Every two-card hand outside `dead` that `filter` keeps, for direct sampling. +/// `None` for other hand sizes (too many to enumerate) or an empty range (the +/// simulation then falls back to the predicate and its documented fallback). +pub fn combos(rules: &Rules, filter: &HandFilter, dead: &[Card]) -> Option>> { + if rules.hole_cards != 2 { + return None; + } + let pool = deck::without_in(rules.deck, dead); + let kept: Vec> = (0..pool.len()) + .flat_map(|i| (i + 1..pool.len()).map(move |j| (i, j))) + .map(|(i, j)| vec![pool[i], pool[j]]) + .filter(|hand| filter(hand)) + .collect(); + (!kept.is_empty()).then_some(kept) +} + +/// The simulation's view of each villain: the enumerated list where there is one, +/// the predicate otherwise. +pub fn as_ranges<'a>(filters: &'a [HandFilter], lists: &'a [Option>>]) -> Vec> { + filters + .iter() + .zip(lists) + .map(|(f, list)| match list { + Some(hands) => VillainRange::Combos(hands), + None => VillainRange::Filter(f.as_ref()), + }) + .collect() +} diff --git a/src/engine/range_filter.rs b/src/engine/range_filter.rs index a15177f7..c4ef8b04 100644 --- a/src/engine/range_filter.rs +++ b/src/engine/range_filter.rs @@ -1,30 +1,130 @@ -use crate::card::Card; -use crate::exploit::range_spec::RangeSpec; -use crate::preflop::hand_percentile::percentile; -use crate::read::draw::Draw; -use crate::read::glance::glance; -use crate::variant::{Rules, Variant}; - -/// A villain's range as an owned predicate over hole cards. -pub type HandFilter = Box bool>; - -/// Turns a `RangeSpec` into the predicate Monte Carlo samples from: a hand is in when -/// its preflop percentile lies in `[lo, hi]` and, for every continuation, its made -/// hand on the first `board_len` board cards is at least `min_made` — or it holds at -/// least a gutshot when the continuation lets draws continue. A hand `glance` cannot -/// read is out. A `board_len` beyond the board is clamped to the whole board. -pub fn range_filter(spec: &RangeSpec, rules: Rules, variant: Variant, board: &[Card]) -> HandFilter { - let spec = spec.clone(); - let board = board.to_vec(); - Box::new(move |hand: &[Card]| { - let p = percentile(variant, hand); - p >= spec.lo - && p <= spec.hi - && spec.continues.iter().all(|c| { - match glance(&rules, hand, &board[..c.board_len.min(board.len())]) { - Ok((made, draw)) => made >= c.min_made || (c.draws_continue && draw >= Draw::Gutshot), - Err(_) => false, - } - }) - }) -} +use crate::card::{deck, Card}; +use crate::exploit::range_spec::{Continuation, RangeSpec}; +use crate::preflop::hand_percentile::percentile; +use crate::read::draw::Draw; +use crate::read::glance::glance; +use crate::rng::Rng; +use crate::variant::{Rules, Variant}; + +/// A villain's range as an owned predicate over hole cards. +pub type HandFilter = Box bool>; + +/// Hands sampled to weigh a range when the hole cards are too many to enumerate. +const SAMPLE: usize = 600; +const SAMPLE_SEED: u64 = 0xB1FF_5EED; + +/// Does `hand` meet the floor of `c` on its part of the board? `None` when unreadable. +fn meets(rules: &Rules, c: &Continuation, hand: &[Card], board: &[Card]) -> Option { + glance(rules, hand, &board[..c.board_len.min(board.len())]) + .ok() + .map(|(made, draw)| made >= c.min_made || (c.draws_continue && draw >= Draw::Gutshot)) +} + +/// A fixed number in `[0, 1)` per hand and continuation, independent of card order. +fn ticket(hand: &[Card], step: usize) -> f64 { + let mut idx: Vec = hand.iter().map(|c| c.index()).collect(); + idx.sort_unstable(); + let key = idx.iter().fold(step as u64, |h, i| h.wrapping_mul(0x100_0000_01B3) ^ u64::from(*i)); + Rng::seeded(key).unit().0 +} + +/// The starting hands the range is weighed over: every two-card hand, or a fixed sample. +fn population(rules: &Rules, board: &[Card]) -> Vec> { + let pool = deck::without_in(rules.deck, board); + if rules.hole_cards == 2 { + (0..pool.len()) + .flat_map(|i| (i + 1..pool.len()).map(move |j| (i, j))) + .map(|(i, j)| vec![pool[i], pool[j]]) + .collect() + } else { + (0..SAMPLE) + .scan(Rng::seeded(SAMPLE_SEED), |rng, _| { + deck::draw(&pool, rules.hole_cards, *rng).map(|(hand, next)| { + *rng = next; + hand + }) + }) + .collect() + } +} + +/// Ticket threshold that admits the `k` lowest tickets of `below`: halfway between the +/// k-th and the next ticket, 0 for none, above every ticket for all. +fn threshold(mut tickets: Vec, k: usize) -> f64 { + tickets.sort_by(|a, b| a.total_cmp(b)); + match (k, tickets.len()) { + (0, _) => 0.0, + (k, n) if k >= n => 1.0, + (k, _) => 0.5 * (tickets[k - 1] + tickets[k]), + } +} + +/// Ticket threshold per continuation for hands below its floor, chosen so that over the +/// population they make up `bluff_share` of the survivors: the `b * value / (1 - b)` +/// lowest tickets (rounded) are admitted. Second value: `true` when some continuation +/// has no value hand at all in what is left (the band contradicts the action). +fn acceptances(spec: &RangeSpec, rules: &Rules, variant: Variant, board: &[Card]) -> (Vec, bool) { + if spec.continues.is_empty() { + return (Vec::new(), false); + } + let start: Vec> = population(rules, board) + .into_iter() + .filter(|h| (spec.lo..=spec.hi).contains(&percentile(variant, h))) + .collect(); + let init = (start, Vec::new(), false); + let (_, qs, starved) = spec.continues.iter().enumerate().fold(init, |(alive, mut qs, starved), (step, c)| { + let judged: Vec<(Vec, Option)> = + alive.into_iter().map(|h| { let m = meets(rules, c, &h, board); (h, m) }).collect(); + let value = judged.iter().filter(|(_, m)| *m == Some(true)).count(); + let below: Vec = + judged.iter().filter(|(_, m)| *m == Some(false)).map(|(h, _)| ticket(h, step)).collect(); + let b = c.bluff_share.clamp(0.0, 0.99); + let k = if b > 0.0 { (b * value as f64 / (1.0 - b)).round() as usize } else { 0 }; + let q = threshold(below, k); + qs.push(q); + let next = judged + .into_iter() + .filter(|(h, m)| *m == Some(true) || (*m == Some(false) && ticket(h, step) < q)) + .map(|(h, _)| h) + .collect(); + (next, qs, starved || value == 0) + }); + (qs, starved) +} + +/// Upper end of the relaxed band (see `range_filter`). +const RELAXED_HI: f64 = 0.5; + +/// Turns a `RangeSpec` into the predicate Monte Carlo samples from: a hand is in when +/// its preflop percentile lies in `[lo, hi]` and, for every continuation, its made +/// hand on the first `board_len` board cards is at least `min_made` — or it holds at +/// least a gutshot when the continuation lets draws continue — or it is one of the +/// admitted bluffs: below the floor with a fixed per-hand ticket under the acceptance +/// that makes bluffs `bluff_share` of the range (`acceptances`). A hand `glance` cannot +/// read is out. A `board_len` beyond the board is clamped to the whole board. +/// +/// When no hand of the preflop band meets some floor, the band contradicts what the +/// villain did; the action wins and the band is relaxed to `[0, max(hi, 0.5)]`. +pub fn range_filter(spec: &RangeSpec, rules: Rules, variant: Variant, board: &[Card]) -> HandFilter { + let board = board.to_vec(); + let (first, starved) = acceptances(spec, &rules, variant, &board); + let (spec, qs) = if starved { + let relaxed = RangeSpec { lo: 0.0, hi: spec.hi.max(RELAXED_HI), continues: spec.continues.clone() }; + let (qs, _) = acceptances(&relaxed, &rules, variant, &board); + (relaxed, qs) + } else { + (spec.clone(), first) + }; + Box::new(move |hand: &[Card]| { + let p = percentile(variant, hand); + p >= spec.lo + && p <= spec.hi + && spec.continues.iter().zip(&qs).enumerate().all(|(step, (c, q))| { + match meets(&rules, c, hand, &board) { + Some(true) => true, + Some(false) => *q > 0.0 && ticket(hand, step) < *q, + None => false, + } + }) + }) +} diff --git a/src/equity/monte_carlo.rs b/src/equity/monte_carlo.rs index 4bb92a6b..d889f961 100644 --- a/src/equity/monte_carlo.rs +++ b/src/equity/monte_carlo.rs @@ -1,79 +1,85 @@ -use super::estimate::Estimate; -use super::outcome::Outcome; -use super::query::Query; -use super::sample::{deal, shuffle_front}; -use super::tally::Tally; -use super::validate::remaining_deck; -use super::villain_range::VillainRange; -use crate::card::Card; -use crate::fault::Fault; -use crate::hand::showdown::judge; -use crate::rng::Rng; - -/// Seeded Monte Carlo equity. Same query + same rng ⇒ same estimate. -/// -/// `Filter` ranges are sampled by bounded rejection (see `sample::deal` for the fallback). -pub fn estimate(query: &Query, rng: Rng) -> Result<(Estimate, Rng), Fault> { - let mut pool = remaining_deck(query)?; - let (tally, rng) = (0..query.trials).try_fold((Tally::default(), rng), |(tally, rng), _| { - let (outcome, rng) = play_trial(query, &mut pool, rng)?; - Ok::<_, Fault>((tally.record(outcome), rng)) - })?; - Ok((tally.finish(), rng)) -} - -/// One deal: villain hands first (in query order), then the rest of the board. -fn play_trial(query: &Query, pool: &mut [Card], rng: Rng) -> Result<(Outcome, Rng), Fault> { - let k = query.rules.hole_cards; - let rules = &query.rules; - let accept_all = |_: &[Card]| true; - let mut front = 0; - let mut rng = rng; - // Where each villain's cards live: Some(start in pool) for sampled hands. - let mut starts: Vec> = Vec::with_capacity(query.villains.len()); - for villain in query.villains { - match villain { - VillainRange::Exact(_) => starts.push(None), - VillainRange::Any => { - rng = deal(pool, front, k, &accept_all, rng); - starts.push(Some(front)); - front += k; - } - VillainRange::Filter(accept) => { - rng = deal(pool, front, k, *accept, rng); - starts.push(Some(front)); - front += k; - } - } - } - let missing = 5 - query.board.len(); - rng = shuffle_front(pool, front, missing, rng); - let mut board = [query.hero[0]; 5]; - query.board.iter().chain(&pool[front..front + missing]).enumerate().for_each(|(i, c)| board[i] = *c); - - let hero = judge(rules, query.hero, &board)?; - let mut rivals_best = None; - let mut rivals_tied = 0u32; - for (villain, start) in query.villains.iter().zip(&starts) { - let hand: &[Card] = match (villain, start) { - (VillainRange::Exact(cards), _) => cards, - (_, Some(s)) => &pool[*s..*s + k], - (_, None) => &[], - }; - let strength = judge(rules, hand, &board)?; - match rivals_best { - Some(top) if strength < top => {} - Some(top) if strength == top => rivals_tied += 1, - _ => { - rivals_best = Some(strength); - rivals_tied = 1; - } - } - } - let outcome = match rivals_best { - Some(top) if hero < top => Outcome::Loss, - Some(top) if hero == top => Outcome::Tie { ways: rivals_tied + 1 }, - _ => Outcome::Win, - }; - Ok((outcome, rng)) -} +use super::estimate::Estimate; +use super::outcome::Outcome; +use super::query::Query; +use super::sample::{deal, deal_combo, shuffle_front}; +use super::tally::Tally; +use super::validate::remaining_deck; +use super::villain_range::VillainRange; +use crate::card::Card; +use crate::fault::Fault; +use crate::hand::showdown::judge; +use crate::rng::Rng; + +/// Seeded Monte Carlo equity. Same query + same rng ⇒ same estimate. +/// +/// `Filter` ranges are sampled by bounded rejection (see `sample::deal` for the fallback), +/// `Combos` ranges directly from their list (`sample::deal_combo`). +pub fn estimate(query: &Query, rng: Rng) -> Result<(Estimate, Rng), Fault> { + let mut pool = remaining_deck(query)?; + let (tally, rng) = (0..query.trials).try_fold((Tally::default(), rng), |(tally, rng), _| { + let (outcome, rng) = play_trial(query, &mut pool, rng)?; + Ok::<_, Fault>((tally.record(outcome), rng)) + })?; + Ok((tally.finish(), rng)) +} + +/// One deal: villain hands first (in query order), then the rest of the board. +fn play_trial(query: &Query, pool: &mut [Card], rng: Rng) -> Result<(Outcome, Rng), Fault> { + let k = query.rules.hole_cards; + let rules = &query.rules; + let accept_all = |_: &[Card]| true; + let mut front = 0; + let mut rng = rng; + // Where each villain's cards live: Some(start in pool) for sampled hands. + let mut starts: Vec> = Vec::with_capacity(query.villains.len()); + for villain in query.villains { + match villain { + VillainRange::Exact(_) => starts.push(None), + VillainRange::Any => { + rng = deal(pool, front, k, &accept_all, rng); + starts.push(Some(front)); + front += k; + } + VillainRange::Filter(accept) => { + rng = deal(pool, front, k, *accept, rng); + starts.push(Some(front)); + front += k; + } + VillainRange::Combos(combos) => { + rng = deal_combo(pool, front, k, combos, rng); + starts.push(Some(front)); + front += k; + } + } + } + let missing = 5 - query.board.len(); + rng = shuffle_front(pool, front, missing, rng); + let mut board = [query.hero[0]; 5]; + query.board.iter().chain(&pool[front..front + missing]).enumerate().for_each(|(i, c)| board[i] = *c); + + let hero = judge(rules, query.hero, &board)?; + let mut rivals_best = None; + let mut rivals_tied = 0u32; + for (villain, start) in query.villains.iter().zip(&starts) { + let hand: &[Card] = match (villain, start) { + (VillainRange::Exact(cards), _) => cards, + (_, Some(s)) => &pool[*s..*s + k], + (_, None) => &[], + }; + let strength = judge(rules, hand, &board)?; + match rivals_best { + Some(top) if strength < top => {} + Some(top) if strength == top => rivals_tied += 1, + _ => { + rivals_best = Some(strength); + rivals_tied = 1; + } + } + } + let outcome = match rivals_best { + Some(top) if hero < top => Outcome::Loss, + Some(top) if hero == top => Outcome::Tie { ways: rivals_tied + 1 }, + _ => Outcome::Win, + }; + Ok((outcome, rng)) +} diff --git a/src/equity/sample.rs b/src/equity/sample.rs index 76e39a33..a97a8555 100644 --- a/src/equity/sample.rs +++ b/src/equity/sample.rs @@ -1,33 +1,54 @@ -//! Dealing from a pool that is rearranged in place (private to one simulation run). -//! -//! The pool is only ever permuted, so any arrangement is a uniform starting point for the next -//! partial Fisher-Yates pass; the arrangement itself never leaks out of `monte_carlo`. - -use crate::card::Card; -use crate::rng::Rng; - -/// Attempts a `Filter` range gets per hand before the last sample is accepted unfiltered. -pub const MAX_FILTER_ATTEMPTS: u32 = 200; - -/// Moves `count` uniformly chosen cards from `pool[front..]` to `pool[front..front + count]`. -pub fn shuffle_front(pool: &mut [Card], front: usize, count: usize, rng: Rng) -> Rng { - (0..count).fold(rng, |rng, i| { - let (offset, rng) = rng.below((pool.len() - front - i) as u64); - pool.swap(front + i, front + i + offset as usize); - rng - }) -} - -/// Deals `count` cards at `front`, re-sampling while `accept` refuses (bounded). -/// Fallback: after `MAX_FILTER_ATTEMPTS` refusals the last sample is kept, i.e. a range that -/// (almost) never matches degrades to a uniformly random hand instead of failing the run. -pub fn deal(pool: &mut [Card], front: usize, count: usize, accept: &dyn Fn(&[Card]) -> bool, rng: Rng) -> Rng { - let mut rng = rng; - for _ in 0..MAX_FILTER_ATTEMPTS { - rng = shuffle_front(pool, front, count, rng); - if accept(&pool[front..front + count]) { - break; - } - } - rng -} +//! Dealing from a pool that is rearranged in place (private to one simulation run). +//! +//! The pool is only ever permuted, so any arrangement is a uniform starting point for the next +//! partial Fisher-Yates pass; the arrangement itself never leaks out of `monte_carlo`. + +use crate::card::Card; +use crate::rng::Rng; + +/// Attempts a `Filter` range gets per hand before the last sample is accepted unfiltered. +pub const MAX_FILTER_ATTEMPTS: u32 = 200; + +/// Moves `count` uniformly chosen cards from `pool[front..]` to `pool[front..front + count]`. +pub fn shuffle_front(pool: &mut [Card], front: usize, count: usize, rng: Rng) -> Rng { + (0..count).fold(rng, |rng, i| { + let (offset, rng) = rng.below((pool.len() - front - i) as u64); + pool.swap(front + i, front + i + offset as usize); + rng + }) +} + +/// Deals `count` cards at `front`, re-sampling while `accept` refuses (bounded). +/// Fallback: after `MAX_FILTER_ATTEMPTS` refusals the last sample is kept, i.e. a range that +/// (almost) never matches degrades to a uniformly random hand instead of failing the run. +pub fn deal(pool: &mut [Card], front: usize, count: usize, accept: &dyn Fn(&[Card]) -> bool, rng: Rng) -> Rng { + let mut rng = rng; + for _ in 0..MAX_FILTER_ATTEMPTS { + rng = shuffle_front(pool, front, count, rng); + if accept(&pool[front..front + count]) { + break; + } + } + rng +} + +/// Deals one of `combos` at `front`: a uniformly chosen hand, re-chosen while one of its +/// cards is gone (dead or dealt), bounded by `MAX_FILTER_ATTEMPTS`. Fallback: an empty list, +/// or no hand left after the attempts, deals `count` random cards instead. +pub fn deal_combo(pool: &mut [Card], front: usize, count: usize, combos: &[Vec], rng: Rng) -> Rng { + let mut rng = rng; + for _ in 0..if combos.is_empty() { 0 } else { MAX_FILTER_ATTEMPTS } { + let (i, next) = rng.below(combos.len() as u64); + rng = next; + let combo = &combos[i as usize]; + let available = combo.len() == count && combo.iter().all(|c| pool[front..].contains(c)); + if available { + for (k, card) in combo.iter().enumerate() { + let at = front + k + pool[front + k..].iter().position(|p| p == card).unwrap_or(0); + pool.swap(front + k, at); + } + return rng; + } + } + shuffle_front(pool, front, count, rng) +} diff --git a/src/equity/villain_range.rs b/src/equity/villain_range.rs index 7ab678ad..170d1c1d 100644 --- a/src/equity/villain_range.rs +++ b/src/equity/villain_range.rs @@ -1,11 +1,14 @@ -use crate::card::Card; - -/// One opponent's assumed holdings. -pub enum VillainRange<'a> { - /// Any hand from the remaining deck. - Any, - /// A known hand (reference tests, showdown replays). - Exact(Vec), - /// Hands accepted by a pure predicate (e.g. "top 20 % by percentile"). - Filter(&'a dyn Fn(&[Card]) -> bool), -} +use crate::card::Card; + +/// One opponent's assumed holdings. +pub enum VillainRange<'a> { + /// Any hand from the remaining deck. + Any, + /// A known hand (reference tests, showdown replays). + Exact(Vec), + /// Hands accepted by a pure predicate (e.g. "top 20 % by percentile"). + Filter(&'a dyn Fn(&[Card]) -> bool), + /// An enumerated range: one of these hands, uniformly, among those still in the deck. + /// Exact for narrow ranges where rejection sampling of a `Filter` would give up. + Combos(&'a [Vec]), +} diff --git a/src/exploit/adjust.rs b/src/exploit/adjust.rs index ae555efd..249eb442 100644 --- a/src/exploit/adjust.rs +++ b/src/exploit/adjust.rs @@ -1,58 +1,57 @@ -use super::fold_equity_scale::{fold_equity_scale, MAX_SCALE, MIN_SCALE}; -use super::profile::Profile; -use super::style::classify; -use super::style_shift::shift_for; -use super::thresholds::Thresholds; - -/// Output ranges: whatever the inputs, the engine never sees thresholds outside these. -const CALL_MARGIN: (f64, f64) = (0.0, 0.15); -const VALUE_RAISE: (f64, f64) = (0.52, 0.85); -const ABSTAIN_BAND: (f64, f64) = (0.0, 0.05); -const RANGE_WIDTH: (f64, f64) = (0.6, 1.4); - -fn bounded(x: f64, (low, high): (f64, f64)) -> f64 { - if x.is_nan() { - low - } else { - x.clamp(low, high) - } -} - -/// `base` as seen against one profile; `None` when the profile says nothing. -fn against(base: Thresholds, profile: &Profile) -> Option { - shift_for(classify(profile)).map(|shift| Thresholds { - call_margin: bounded(base.call_margin + shift.call_margin, CALL_MARGIN), - value_raise: bounded(base.value_raise + shift.value_raise, VALUE_RAISE), - abstain_band: bounded(base.abstain_band, ABSTAIN_BAND), - fold_equity_scale: (base.fold_equity_scale - * fold_equity_scale(profile.fold_to_bet, shift.fold_equity_default)) - .clamp(MIN_SCALE, MAX_SCALE), - range_width_scale: bounded(base.range_width_scale * shift.range_width, RANGE_WIDTH), - }) -} - -/// Conservative merge of two opponents: keep the harder-to-continue value of each -/// threshold (higher margins, lower fold equity, narrower ranges). -fn conservative(a: Thresholds, b: Thresholds) -> Thresholds { - Thresholds { - call_margin: a.call_margin.max(b.call_margin), - value_raise: a.value_raise.max(b.value_raise), - abstain_band: a.abstain_band.max(b.abstain_band), - fold_equity_scale: a.fold_equity_scale.min(b.fold_equity_scale), - range_width_scale: a.range_width_scale.min(b.range_width_scale), - } -} - -/// Shift thresholds for the given live opponents' profiles. No profiles → `base` unchanged. -/// -/// Each profile is classified (`style::classify`) and moves `base` by its style -/// (`style_shift`); foldToBet, when given, sets `fold_equity_scale` continuously. -/// Profiles with no usable numbers are ignored; with several informative ones the -/// results are merged conservatively. Outputs are clamped to sane ranges. -pub fn adjust(base: Thresholds, profiles: &[Profile]) -> Thresholds { - profiles - .iter() - .filter_map(|p| against(base, p)) - .reduce(conservative) - .unwrap_or(base) -} +use super::fold_equity_scale::{MAX_SCALE, MIN_SCALE}; +use super::profile::Profile; +use super::style::classify; +use super::style_shift::shift_for; +use super::thresholds::Thresholds; + +/// Output ranges: whatever the inputs, the engine never sees thresholds outside these. +const CALL_MARGIN: (f64, f64) = (0.0, 0.15); +const VALUE_RAISE: (f64, f64) = (0.52, 0.85); +const ABSTAIN_BAND: (f64, f64) = (0.0, 0.05); +const RANGE_WIDTH: (f64, f64) = (0.6, 1.4); + +fn bounded(x: f64, (low, high): (f64, f64)) -> f64 { + if x.is_nan() { + low + } else { + x.clamp(low, high) + } +} + +/// `base` as seen against one profile; `None` when the profile says nothing. +fn against(base: Thresholds, profile: &Profile) -> Option { + shift_for(classify(profile)).map(|shift| Thresholds { + call_margin: bounded(base.call_margin + shift.call_margin, CALL_MARGIN), + value_raise: bounded(base.value_raise + shift.value_raise, VALUE_RAISE), + abstain_band: bounded(base.abstain_band, ABSTAIN_BAND), + fold_equity_scale: base.fold_equity_scale.clamp(MIN_SCALE, MAX_SCALE), + range_width_scale: bounded(base.range_width_scale * shift.range_width, RANGE_WIDTH), + }) +} + +/// Conservative merge of two opponents: keep the harder-to-continue value of each +/// threshold (higher margins, lower fold equity, narrower ranges). +fn conservative(a: Thresholds, b: Thresholds) -> Thresholds { + Thresholds { + call_margin: a.call_margin.max(b.call_margin), + value_raise: a.value_raise.max(b.value_raise), + abstain_band: a.abstain_band.max(b.abstain_band), + fold_equity_scale: a.fold_equity_scale.min(b.fold_equity_scale), + range_width_scale: a.range_width_scale.min(b.range_width_scale), + } +} + +/// Shift thresholds for the given live opponents' profiles. No profiles → `base` unchanged. +/// +/// Each profile is classified (`style::classify`) and moves `base` by its style +/// (`style_shift`). `fold_equity_scale` stays as given: how often each opponent folds is +/// estimated per opponent (`fold_chance`), so the profile is not counted here a second time. +/// Profiles with no usable numbers are ignored; with several informative ones the +/// results are merged conservatively. Outputs are clamped to sane ranges. +pub fn adjust(base: Thresholds, profiles: &[Profile]) -> Thresholds { + profiles + .iter() + .filter_map(|p| against(base, p)) + .reduce(conservative) + .unwrap_or(base) +} diff --git a/src/exploit/bluff_share.rs b/src/exploit/bluff_share.rs new file mode 100644 index 00000000..1a2418d4 --- /dev/null +++ b/src/exploit/bluff_share.rs @@ -0,0 +1,47 @@ +//! What part of an opponent's betting range is a bluff. +//! +//! | step | rule | +//! |---|---| +//! | base | `s / (1 + 2s)` for a bet of `s` pots: the river share at which a caller is indifferent (Chen/Ankenman, "The Mathematics of Poker"); unknown or broken size counts as 0.66 | +//! | street | river 1.0, turn 0.6, flop 0.5 (earlier, draws do the bluffing and already stay in the range), preflop 0 | +//! | style | nit 0.4, calling station 0.5 (passive players bet for value), loose-aggressive 1.5, otherwise 1.0 | +//! | aggression | when the profile gives it, `aggression / 0.45` (0.45 = an average aggression frequency) replaces the style factor, clamped to [0, 2] | +//! | cap | at most 0.6 | + +use super::profile::Profile; +use super::style::{classify, Style}; +use crate::game::Street; + +pub const NEUTRAL_RATIO: f64 = 0.66; +pub const MAX_BLUFF_SHARE: f64 = 0.6; +const AVERAGE_AGGRESSION: f64 = 0.45; +const MAX_FACTOR: f64 = 2.0; + +fn street_factor(street: Street) -> f64 { + match street { + Street::Preflop => 0.0, + Street::Flop => 0.5, + Street::Turn => 0.6, + Street::River => 1.0, + } +} + +fn style_factor(profile: Option<&Profile>) -> f64 { + let Some(p) = profile else { return 1.0 }; + match p.aggression.filter(|a| !a.is_nan()) { + Some(a) => (a.clamp(0.0, 1.0) / AVERAGE_AGGRESSION).clamp(0.0, MAX_FACTOR), + None => match classify(p) { + Style::Nit => 0.4, + Style::CallingStation => 0.5, + Style::LooseAggressive => 1.5, + Style::Regular | Style::Unknown => 1.0, + }, + } +} + +/// Bluff share of the range that bet `ratio` pots on `street`. Always in `[0, MAX_BLUFF_SHARE]`. +pub fn bluff_share(profile: Option<&Profile>, ratio: Option, street: Street) -> f64 { + let s = ratio.filter(|r| r.is_finite() && *r > 0.0).unwrap_or(NEUTRAL_RATIO); + let balanced = s / (1.0 + 2.0 * s); + (balanced * street_factor(street) * style_factor(profile)).clamp(0.0, MAX_BLUFF_SHARE) +} diff --git a/src/exploit/call_floor.rs b/src/exploit/call_floor.rs new file mode 100644 index 00000000..e9e11491 --- /dev/null +++ b/src/exploit/call_floor.rs @@ -0,0 +1,22 @@ +use super::made_ladder::rung; +use super::range_spec::Continuation; +use super::size_notch::size_notch; +use super::style_rung::style_rung; +use crate::game::{Street, Villain}; + +/// Rung of the weakest hand that calls a bet, per street (flop, turn, river) on +/// `made_ladder`: bottom pair on flop and turn, middle pair on the river. +const CALL_RUNG: [i32; 3] = [1, 1, 2]; + +/// What a villain continues with when hero bets `ratio` pots on `street`: the calling +/// floor moved by the size (`size_notch`) and the villain's style (`style_rung`); draws +/// call on flop and turn. This is the range the called branch of a bet is played against. +pub fn call_continuation(villain: &Villain, street: Street, ratio: f64) -> Continuation { + let slot = (street as usize).clamp(1, 3) - 1; + Continuation { + board_len: street.board_len(), + min_made: rung(CALL_RUNG[slot], size_notch(Some(ratio)) + style_rung(villain)), + draws_continue: street != Street::River, + bluff_share: 0.0, + } +} diff --git a/src/exploit/fold_chance.rs b/src/exploit/fold_chance.rs new file mode 100644 index 00000000..dbeb8b24 --- /dev/null +++ b/src/exploit/fold_chance.rs @@ -0,0 +1,56 @@ +//! How likely one opponent folds to a bet: the documented map from their profile. +//! +//! | step | rule | +//! |---|---| +//! | base `f` | `foldToBet`, clamped to [0, 1]; without it the style default: nit 0.65, calling station 0.20, loose-aggressive 0.40, otherwise 0.45 | +//! | size | `p = 1 - (1 - f)^(ratio / 0.66)`: foldToBet is a frequency against a typical two-thirds-pot bet, so at that size `p = f`; smaller bets fold less, bigger more, a zero bet never | +//! | raised | `p * 0.7` when the opponent already bet and is being raised (money invested, range stronger) | +//! | cap | at most 0.95: nobody folds for sure | +//! +//! `ratio` is the pressure: chips beyond a call over the pot after calling +//! (`table_fold::pressure_ratio`). + +use super::profile::Profile; +use super::style::{classify, Style}; + +/// Bet size (pot fraction) at which foldToBet is taken to be measured. +pub const REFERENCE_RATIO: f64 = 0.66; +/// Fold-to-bet of an opponent we know nothing about. +pub const DEFAULT_FOLD_TO_BET: f64 = 0.45; +/// Factor when the opponent is raised after betting. +pub const RAISE_RESISTANCE: f64 = 0.7; +/// Largest fold chance ever assumed for one opponent. +pub const MAX_FOLD: f64 = 0.95; + +fn style_default(style: Style) -> f64 { + match style { + Style::Nit => 0.65, + Style::CallingStation => 0.20, + Style::LooseAggressive => 0.40, + Style::Regular | Style::Unknown => DEFAULT_FOLD_TO_BET, + } +} + +/// The opponent's fold-to-bet at the reference size. +pub fn fold_base(profile: Option<&Profile>) -> f64 { + match profile { + None => DEFAULT_FOLD_TO_BET, + Some(p) => match p.fold_to_bet.filter(|f| !f.is_nan()) { + Some(f) => f.clamp(0.0, 1.0), + None => style_default(classify(p)), + }, + } +} + +/// P(this opponent folds) to a bet of `ratio` pots. Total: any input gives `[0, MAX_FOLD]`. +pub fn fold_chance(profile: Option<&Profile>, ratio: f64, facing_raise: bool) -> f64 { + let f = fold_base(profile); + let ratio = if ratio.is_nan() { 0.0 } else { ratio.max(0.0) }; + let sized = if f >= 1.0 { + if ratio > 0.0 { 1.0 } else { 0.0 } + } else { + 1.0 - (1.0 - f).powf(ratio / REFERENCE_RATIO) + }; + let raised = if facing_raise { sized * RAISE_RESISTANCE } else { sized }; + if raised.is_nan() { 0.0 } else { raised.clamp(0.0, MAX_FOLD) } +} diff --git a/src/exploit/fold_equity_scale.rs b/src/exploit/fold_equity_scale.rs index 919d558d..15fd1bca 100644 --- a/src/exploit/fold_equity_scale.rs +++ b/src/exploit/fold_equity_scale.rs @@ -1,13 +1,5 @@ -//! Fold-equity multiplier from an opponent's foldToBet. +//! Bounds of `Thresholds::fold_equity_scale`, the shared multiplier on every opponent's +//! fold chance (1.0 = neutral). The profile itself enters per opponent (`fold_chance`). pub const MIN_SCALE: f64 = 0.3; pub const MAX_SCALE: f64 = 1.6; - -/// `0.35 + 1.3 * foldToBet` clamped to `[0.3, 1.6]` (a 50 % folder is neutral, 1.0). -/// Continuous and increasing in `fold_to_bet`; without a figure, `fallback`. -pub fn fold_equity_scale(fold_to_bet: Option, fallback: f64) -> f64 { - fold_to_bet - .filter(|b| !b.is_nan()) - .map_or(fallback, |b| 0.35 + 1.3 * b.clamp(0.0, 1.0)) - .clamp(MIN_SCALE, MAX_SCALE) -} diff --git a/src/exploit/mod.rs b/src/exploit/mod.rs index b8c78aa3..b7d5724f 100644 --- a/src/exploit/mod.rs +++ b/src/exploit/mod.rs @@ -1,22 +1,28 @@ -//! 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 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 style; -pub mod style_shift; -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 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/profile.rs b/src/exploit/profile.rs index 54a088d3..6bf67998 100644 --- a/src/exploit/profile.rs +++ b/src/exploit/profile.rs @@ -1,11 +1,15 @@ -/// Observed opponent tendencies, all frequencies in `[0, 1]`. Every field optional. -/// Wire shape (extension): `"profile": {"vpip": 0.45, "pfr": 0.08, "foldToBet": 0.3}`. -#[derive(Clone, Copy, Debug, PartialEq, Default)] -pub struct Profile { - /// Voluntarily put money in pot, preflop. - pub vpip: Option, - /// Preflop raise frequency. - pub pfr: Option, - /// How often the player folds to a bet postflop. - pub fold_to_bet: Option, -} +/// Observed opponent tendencies, all frequencies in `[0, 1]`. Every field optional. +/// Wire shape (extension): +/// `"profile": {"vpip": 0.45, "pfr": 0.08, "foldToBet": 0.3, "aggression": 0.4}`. +#[derive(Clone, Copy, Debug, PartialEq, Default)] +pub struct Profile { + /// Voluntarily put money in pot, preflop. + pub vpip: Option, + /// Preflop raise frequency. + pub pfr: Option, + /// How often the player folds to a bet postflop. + pub fold_to_bet: Option, + /// Share of the player's postflop actions that are bets or raises (aggression + /// frequency). Steers how much of their betting range is a bluff (`bluff_share`). + pub aggression: Option, +} diff --git a/src/exploit/range_spec.rs b/src/exploit/range_spec.rs index 04d4cea0..acb03173 100644 --- a/src/exploit/range_spec.rs +++ b/src/exploit/range_spec.rs @@ -1,28 +1,31 @@ -use crate::read::made::Made; - -/// A villain's estimated holdings as data; the engine turns it into a predicate. -/// -/// A hand is in the range when its preflop percentile lies in `[lo, hi]` -/// (0 = best hand) and it satisfies every `Continuation`. -#[derive(Clone, Debug, PartialEq)] -pub struct RangeSpec { - pub lo: f64, - pub hi: f64, - pub continues: Vec, -} - -/// "Villain bet or raised when the board had `board_len` cards": only hands at least -/// `min_made` at that point stay in — plus drawing hands when `draws_continue`. -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct Continuation { - pub board_len: usize, - pub min_made: Made, - pub draws_continue: bool, -} - -impl RangeSpec { - /// The best `top` fraction of starting hands, no postflop filter. - pub fn top(top: f64) -> RangeSpec { - RangeSpec { lo: 0.0, hi: top, continues: Vec::new() } - } -} +use crate::read::made::Made; + +/// A villain's estimated holdings as data; the engine turns it into a predicate. +/// +/// A hand is in the range when its preflop percentile lies in `[lo, hi]` +/// (0 = best hand) and it satisfies every `Continuation`. +#[derive(Clone, Debug, PartialEq)] +pub struct RangeSpec { + pub lo: f64, + pub hi: f64, + pub continues: Vec, +} + +/// "Villain bet or raised when the board had `board_len` cards": only hands at least +/// `min_made` at that point stay in — plus drawing hands when `draws_continue` — plus +/// a bluff fraction: hands below the floor are admitted so that they make up +/// `bluff_share` of what passes (`engine::range_filter`). 0 = a pure value range. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Continuation { + pub board_len: usize, + pub min_made: Made, + pub draws_continue: bool, + pub bluff_share: f64, +} + +impl RangeSpec { + /// The best `top` fraction of starting hands, no postflop filter. + pub fn top(top: f64) -> RangeSpec { + RangeSpec { lo: 0.0, hi: top, continues: Vec::new() } + } +} diff --git a/src/exploit/steal_width.rs b/src/exploit/steal_width.rs new file mode 100644 index 00000000..13886790 --- /dev/null +++ b/src/exploit/steal_width.rs @@ -0,0 +1,18 @@ +use super::fold_chance::{fold_base, DEFAULT_FOLD_TO_BET}; +use crate::game::Spot; + +/// Width change per point of average fold-to-bet above the neutral 0.45. +const PER_FOLD: f64 = 1.5; +const BOUNDS: (f64, f64) = (0.7, 1.4); + +/// Opening-width multiplier for an unopened pot, from how often the players behind fold: +/// `1 + 1.5 * (mean fold_base - 0.45)`, clamped to [0.7, 1.4]. Nits behind widen the +/// steal, calling stations narrow it; no live villain or no profiles: 1.0. +pub fn steal_width(spot: &Spot) -> f64 { + let folds: Vec = spot.live_villains().map(|v| fold_base(v.profile.as_ref())).collect(); + if folds.is_empty() { + return 1.0; + } + let mean = folds.iter().sum::() / folds.len() as f64; + (1.0 + PER_FOLD * (mean - DEFAULT_FOLD_TO_BET)).clamp(BOUNDS.0, BOUNDS.1) +} diff --git a/src/exploit/street_continuation.rs b/src/exploit/street_continuation.rs index f431e849..ba042dee 100644 --- a/src/exploit/street_continuation.rs +++ b/src/exploit/street_continuation.rs @@ -1,142 +1,142 @@ -use super::bet_ratio::bet_ratios; -use super::made_ladder::rung; -use super::range_spec::Continuation; -use super::size_notch::size_notch; -use super::style::{classify, Style}; -use crate::game::{ActionRecord, SeenAction, Spot, Street, Villain}; -use crate::read::made::Made; - -/// A call of a bet at least this big (pot fractions) shows a hand with some showdown value. -const BIG_BET: f64 = 0.6; - -/// Floor rung of a bet / of a raise (or all-in) per street (flop, turn, river), see `LADDER` -/// in `made_ladder`: middle pair, top pair weak kicker, top pair good kicker for bets; -/// top pair good kicker, overpair, two pair for raises. -const BET_RUNG: [i32; 3] = [2, 3, 4]; -const RAISE_RUNG: [i32; 3] = [4, 5, 6]; -/// Draws are still in on flop and turn, not on the river. -const DRAWS: [bool; 3] = [true, true, false]; - -/// Looser styles lose one rung, the nit gains one. -fn style_shift(villain: &Villain) -> i32 { - match villain.profile.map(|p| classify(&p)) { - Some(Style::CallingStation | Style::LooseAggressive) => -1, - Some(Style::Nit) => 1, - _ => 0, - } -} - -/// Bet = 0, raise (RAISE or ALL_IN) = 1. -fn level(action: SeenAction) -> Option { - match action { - SeenAction::Bet => Some(0), - SeenAction::Raise | SeenAction::AllIn => Some(1), - _ => None, - } -} - -/// The strongest aggression of the villain on `street`: highest level, then biggest ratio. -fn own_aggression( - history: &[ActionRecord], - ratios: &[Option], - street: Street, - seat: u8, -) -> Option<(usize, Option)> { - history - .iter() - .zip(ratios) - .filter(|(r, _)| r.street == street && r.seat == seat) - .filter_map(|(r, ratio)| level(r.action).map(|l| (l, *ratio))) - .max_by(|a, b| { - a.0.cmp(&b.0).then( - a.1.unwrap_or(-1.0) - .partial_cmp(&b.1.unwrap_or(-1.0)) - .unwrap_or(std::cmp::Ordering::Equal), - ) - }) -} - -/// Did the villain call, on `street`, a bet or raise (by anyone) of at least `BIG_BET` pots? -fn called_big_bet( - history: &[ActionRecord], - ratios: &[Option], - street: Street, - seat: u8, -) -> bool { - history.iter().enumerate().any(|(i, r)| { - r.street == street - && r.seat == seat - && r.action == SeenAction::Call - && history[..i] - .iter() - .zip(&ratios[..i]) - .rev() - .find(|(b, _)| b.street == street && b.action.is_aggressive()) - .is_some_and(|(_, ratio)| ratio.is_some_and(|x| x >= BIG_BET)) - }) -} - -fn merge(a: Option<(Made, bool)>, b: Option<(Made, bool)>) -> Option<(Made, bool)> { - match (a, b) { - (Some((ma, da)), Some((mb, db))) => Some((ma.max(mb), da && db)), - (one, other) => one.or(other), - } -} - -/// One continuation for the villain on `street`, if their actions there say anything. -fn on_street( - spot: &Spot, - ratios: &[Option], - villain: &Villain, - street: Street, -) -> Option { - let slot = street as usize - 1; - let made_bet = - own_aggression(&spot.history, ratios, street, villain.seat).map(|(lvl, ratio)| { - let base = [BET_RUNG, RAISE_RUNG][lvl][slot]; - ( - rung(base, size_notch(ratio) + style_shift(villain)), - DRAWS[slot], - ) - }); - let made_call = called_big_bet(&spot.history, ratios, street, villain.seat).then(|| { - ( - if street == Street::River { - Made::MiddlePair - } else { - Made::BottomPair - }, - DRAWS[slot], - ) - }); - merge(made_bet, made_call).map(|(min_made, draws_continue)| Continuation { - board_len: street.board_len(), - min_made, - draws_continue, - }) -} - -/// Postflop narrowing from the villain own actions, one entry per dealt street -/// (`board_len <= spot.board.len()`), sorted by board length. -/// -/// - **Bet** keeps `[middle pair, top pair weak kicker, top pair good kicker]+` on -/// flop/turn/river; **raise or all-in** keeps `[top pair good kicker, overpair, two pair]+`. -/// Flop and turn bets keep draws, the river keeps made hands only. Several actions on -/// one street: the highest level (then the biggest) counts. -/// - The size (chips added / pot before, from the amounts in the history) moves the floor -/// by `size_notch` rungs: bigger is stricter. Unknown sizes or pots: no move. -/// - A calling station or loose-aggressive style (see `style::classify`) lowers the floor -/// one rung, a nit raises it one. The floor never drops below bottom pair. -/// - **Checks and calls add nothing**: the continuation only expresses a minimum strength, -/// and a check does not say the hand is weak (traps) nor does a call bound it from -/// below in a useful way. One exception, a mild floor: a call of a bet of at least 0.6 pot -/// keeps bottom pair or better (or a draw) on flop/turn, middle pair or better on the river. -/// Combined with the villain own bet on the same street the stricter floor wins. -pub fn continuations(spot: &Spot, villain: &Villain) -> Vec { - let ratios = bet_ratios(&spot.history); - [Street::Flop, Street::Turn, Street::River] - .into_iter() - .filter(|street| street.board_len() <= spot.board.len()) - .filter_map(|street| on_street(spot, &ratios, villain, street)) - .collect() -} +use super::bet_ratio::bet_ratios; +use super::bluff_share::bluff_share; +use super::made_ladder::rung; +use super::range_spec::Continuation; +use super::size_notch::size_notch; +use super::style_rung::style_rung; +use crate::game::{ActionRecord, SeenAction, Spot, Street, Villain}; +use crate::read::made::Made; + +/// A call of a bet at least this big (pot fractions) shows a hand with some showdown value. +const BIG_BET: f64 = 0.6; + +/// Floor rung of a bet / of a raise (or all-in) per street (flop, turn, river), see `LADDER` +/// in `made_ladder`: middle pair, top pair weak kicker, top pair good kicker for bets; +/// top pair good kicker, overpair, two pair for raises. +const BET_RUNG: [i32; 3] = [2, 3, 4]; +const RAISE_RUNG: [i32; 3] = [4, 5, 6]; +/// Draws are still in on flop and turn, not on the river. +const DRAWS: [bool; 3] = [true, true, false]; + +/// Bet = 0, raise (RAISE or ALL_IN) = 1. +fn level(action: SeenAction) -> Option { + match action { + SeenAction::Bet => Some(0), + SeenAction::Raise | SeenAction::AllIn => Some(1), + _ => None, + } +} + +/// The strongest aggression of the villain on `street`: highest level, then biggest ratio. +fn own_aggression( + history: &[ActionRecord], + ratios: &[Option], + street: Street, + seat: u8, +) -> Option<(usize, Option)> { + history + .iter() + .zip(ratios) + .filter(|(r, _)| r.street == street && r.seat == seat) + .filter_map(|(r, ratio)| level(r.action).map(|l| (l, *ratio))) + .max_by(|a, b| { + a.0.cmp(&b.0).then( + a.1.unwrap_or(-1.0) + .partial_cmp(&b.1.unwrap_or(-1.0)) + .unwrap_or(std::cmp::Ordering::Equal), + ) + }) +} + +/// Did the villain call, on `street`, a bet or raise (by anyone) of at least `BIG_BET` pots? +fn called_big_bet( + history: &[ActionRecord], + ratios: &[Option], + street: Street, + seat: u8, +) -> bool { + history.iter().enumerate().any(|(i, r)| { + r.street == street + && r.seat == seat + && r.action == SeenAction::Call + && history[..i] + .iter() + .zip(&ratios[..i]) + .rev() + .find(|(b, _)| b.street == street && b.action.is_aggressive()) + .is_some_and(|(_, ratio)| ratio.is_some_and(|x| x >= BIG_BET)) + }) +} + +/// (floor, draws continue, bluff share) +type Floor = (Made, bool, f64); + +fn merge(a: Option, b: Option) -> Option { + match (a, b) { + (Some((ma, da, ba)), Some((mb, db, bb))) => Some((ma.max(mb), da && db, ba.max(bb))), + (one, other) => one.or(other), + } +} + +/// One continuation for the villain on `street`, if their actions there say anything. +fn on_street( + spot: &Spot, + ratios: &[Option], + villain: &Villain, + street: Street, +) -> Option { + let slot = street as usize - 1; + let made_bet = + own_aggression(&spot.history, ratios, street, villain.seat).map(|(lvl, ratio)| { + let base = [BET_RUNG, RAISE_RUNG][lvl][slot]; + ( + rung(base, size_notch(ratio) + style_rung(villain)), + DRAWS[slot], + bluff_share(villain.profile.as_ref(), ratio, street), + ) + }); + let made_call = called_big_bet(&spot.history, ratios, street, villain.seat).then(|| { + ( + if street == Street::River { + Made::MiddlePair + } else { + Made::BottomPair + }, + DRAWS[slot], + 0.0, + ) + }); + merge(made_bet, made_call).map(|(min_made, draws_continue, bluff_share)| Continuation { + board_len: street.board_len(), + min_made, + draws_continue, + bluff_share, + }) +} + +/// Postflop narrowing from the villain own actions, one entry per dealt street +/// (`board_len <= spot.board.len()`), sorted by board length. +/// +/// - **Bet** keeps `[middle pair, top pair weak kicker, top pair good kicker]+` on +/// flop/turn/river; **raise or all-in** keeps `[top pair good kicker, overpair, two pair]+`. +/// Flop and turn bets keep draws, the river keeps made hands only. Several actions on +/// one street: the highest level (then the biggest) counts. +/// - The size (chips added / pot before, from the amounts in the history) moves the floor +/// by `size_notch` rungs: bigger is stricter. Unknown sizes or pots: no move. +/// - A calling station or loose-aggressive style (see `style::classify`) lowers the floor +/// one rung, a nit raises it one. The floor never drops below bottom pair. +/// - Bets and raises keep a **bluff fraction** below their floor (`bluff_share`: bet size, +/// street, style or aggression); calls keep none. +/// - **Checks and calls add nothing**: the continuation only expresses a minimum strength, +/// and a check does not say the hand is weak (traps) nor does a call bound it from +/// below in a useful way. One exception, a mild floor: a call of a bet of at least 0.6 pot +/// keeps bottom pair or better (or a draw) on flop/turn, middle pair or better on the river. +/// Combined with the villain own bet on the same street the stricter floor wins. +pub fn continuations(spot: &Spot, villain: &Villain) -> Vec { + let ratios = bet_ratios(&spot.history); + [Street::Flop, Street::Turn, Street::River] + .into_iter() + .filter(|street| street.board_len() <= spot.board.len()) + .filter_map(|street| on_street(spot, &ratios, villain, street)) + .collect() +} diff --git a/src/exploit/style_rung.rs b/src/exploit/style_rung.rs new file mode 100644 index 00000000..90fb6e22 --- /dev/null +++ b/src/exploit/style_rung.rs @@ -0,0 +1,12 @@ +use super::style::{classify, Style}; +use crate::game::Villain; + +/// How a villain's style moves a made-hand floor on `made_ladder`: looser styles +/// (calling station, loose-aggressive) one rung down, the nit one up. +pub fn style_rung(villain: &Villain) -> i32 { + match villain.profile.map(|p| classify(&p)) { + Some(Style::CallingStation | Style::LooseAggressive) => -1, + Some(Style::Nit) => 1, + _ => 0, + } +} diff --git a/src/exploit/style_shift.rs b/src/exploit/style_shift.rs index f880585b..b964eee7 100644 --- a/src/exploit/style_shift.rs +++ b/src/exploit/style_shift.rs @@ -1,51 +1,45 @@ -//! How each style moves the thresholds, as data. - -use super::style::Style; - -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct Shift { - /// Added to `call_margin`. - pub call_margin: f64, - /// Added to `value_raise`. - pub value_raise: f64, - /// Multiplies `range_width_scale`. - pub range_width: f64, - /// `fold_equity_scale` to use when the profile has no foldToBet figure. - pub fold_equity_default: f64, -} - -const NONE: Shift = Shift { - call_margin: 0.0, - value_raise: 0.0, - range_width: 1.0, - fold_equity_default: 1.0, -}; - -/// `None` for `Unknown`: nothing is learned from an empty profile. -pub fn shift_for(style: Style) -> Option { - match style { - Style::Unknown => None, - Style::Regular => Some(NONE), - // Their bets are strong, they fold to ours, we defend less. - Style::Nit => Some(Shift { - call_margin: 0.04, - value_raise: 0.02, - range_width: 0.85, - fold_equity_default: 1.25, - }), - // They call too much: value-bet thinner, never bluff. - Style::CallingStation => Some(Shift { - call_margin: 0.0, - value_raise: -0.04, - range_width: 1.0, - fold_equity_default: 0.5, - }), - // They bluff and raise light: call wider, defend wider. - Style::LooseAggressive => Some(Shift { - call_margin: -0.015, - value_raise: -0.01, - range_width: 1.15, - fold_equity_default: 0.9, - }), - } -} +//! How each style moves the thresholds, as data. + +use super::style::Style; + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Shift { + /// Added to `call_margin`. + pub call_margin: f64, + /// Added to `value_raise`. + pub value_raise: f64, + /// Multiplies `range_width_scale`. + pub range_width: f64, +} + +const NONE: Shift = Shift { + call_margin: 0.0, + value_raise: 0.0, + range_width: 1.0, +}; + +/// `None` for `Unknown`: nothing is learned from an empty profile. +pub fn shift_for(style: Style) -> Option { + match style { + Style::Unknown => None, + Style::Regular => Some(NONE), + // Their bets are strong, they fold to ours, we defend less. + Style::Nit => Some(Shift { + call_margin: 0.04, + value_raise: 0.02, + range_width: 0.85, + }), + // They call too much: value-bet thinner, never bluff. + Style::CallingStation => Some(Shift { + call_margin: 0.0, + value_raise: -0.04, + range_width: 1.0, + }), + // They bluff and raise light: call wider, defend wider. + Style::LooseAggressive => Some(Shift { + call_margin: -0.015, + value_raise: -0.01, + range_width: 1.15, + }), + } +} diff --git a/src/exploit/table_fold.rs b/src/exploit/table_fold.rs new file mode 100644 index 00000000..05d13dcb --- /dev/null +++ b/src/exploit/table_fold.rs @@ -0,0 +1,26 @@ +use super::fold_chance::{fold_chance, MAX_FOLD}; +use crate::game::Spot; + +/// Pressure of a raise to `to`: the chips beyond a call, `to - to_call`, over the pot +/// after calling, `pot + to_call`. A plain bet (`to_call = 0`) is `to / pot`. +/// 0 when the pot is empty or the numbers are not finite. +pub fn pressure_ratio(pot: f64, to_call: f64, to: f64) -> f64 { + let base = pot + to_call; + let ratio = (to - to_call).max(0.0) / base; + if base > 0.0 && ratio.is_finite() { ratio } else { 0.0 } +} + +/// P(every live villain folds) to hero raising to `to`: each villain's `fold_chance` +/// (from their own profile) times the shared `scale` (`Thresholds::fold_equity_scale`), +/// capped, multiplied over the villains as independent events. No live villain: 0. +pub fn table_fold(spot: &Spot, to: f64, scale: f64) -> f64 { + let ratio = pressure_ratio(spot.pot, spot.to_call, to); + let facing_raise = spot.to_call > 0.0; + let scale = if scale.is_finite() { scale.max(0.0) } else { 1.0 }; + let mut live = spot.live_villains().peekable(); + if live.peek().is_none() { + return 0.0; + } + live.map(|v| (fold_chance(v.profile.as_ref(), ratio, facing_raise) * scale).clamp(0.0, MAX_FOLD)) + .product() +} diff --git a/src/preflop/advise.rs b/src/preflop/advise.rs index 85a2ff99..95cdd943 100644 --- a/src/preflop/advise.rs +++ b/src/preflop/advise.rs @@ -1,80 +1,87 @@ -use super::allin_call_cutoff::call_cutoff; -use super::certainty::certainty; -use super::chart_decision::decide; -use super::chart_row::ChartRow; -use super::effective_stack::effective_stack_bb; -use super::full_chart::full_row; -use super::hand_percentile::percentile; -use super::plan::PreflopPlan; -use super::seat_position::seat_position; -use super::push_chart::push_cutoff; -use super::reason::describe; -use super::situation::{classify, Situation}; -use super::width_factor::width_factor; -use crate::exploit::thresholds::Thresholds; -use crate::game::Spot; -use crate::variant::ActionShape; - -/// At or below this effective stack (bb) raising ranges become jamming ranges. -const SHORT_STACK_BB: f64 = 15.0; - -/// A non-finite or non-positive width scale is ignored (treated as neutral). -fn sane_scale(scale: f64) -> f64 { - if scale.is_finite() && scale > 0.0 { - scale - } else { - 1.0 - } -} - -/// The cut-offs that apply here, before the hand is looked at. -fn cutoffs(spot: &Spot, situation: Situation, effective_bb: f64, scale: f64) -> ChartRow { - let rules = spot.rules(); - let pos = seat_position(spot, spot.hero_seat); - let width = width_factor(spot.seats, rules.hole_usage) * scale; - match (situation, rules.shape) { - (Situation::FacingAllIn, ActionShape::Full) => { - ChartRow::new(0.0, call_cutoff(spot.to_call, spot.pot), 0.0).scaled(scale) - } - (Situation::FacingAllIn, ActionShape::Binary) => { - ChartRow::new(0.0, 0.0, call_cutoff(spot.to_call, spot.pot)).scaled(scale) - } - (_, ActionShape::Binary) => { - ChartRow::new(0.0, 0.0, push_cutoff(pos, situation, effective_bb)).scaled(scale) - } - (_, ActionShape::Full) => { - let row = full_row(pos, situation) - .unwrap_or(ChartRow::new(0.0, 0.0, 0.0)) - .scaled(width); - if effective_bb <= SHORT_STACK_BB { - row.raises_become_jams() - } else { - row - } - } - } -} - -/// Chart lookup for a preflop spot. `thresholds.range_width_scale` widens/narrows ranges. -/// -/// Position (`position`), situation (`classify`) and the variant's rules pick a chart row; -/// the row is scaled by table size, game and `range_width_scale`; the hand's percentile -/// then selects jam / raise / call / fold. Binary-shape games only ever answer Jam or Fold. -pub fn advise(spot: &Spot, thresholds: &Thresholds) -> PreflopPlan { - let hand = percentile(spot.variant, &spot.hero_cards); - let pos = seat_position(spot, spot.hero_seat); - let situation = classify(spot.to_call, spot.big_blind, spot.pot, spot.hero_stack); - let row = cutoffs( - spot, - situation, - effective_stack_bb(spot), - sane_scale(thresholds.range_width_scale), - ); - let action = decide(hand, &row); - PreflopPlan { - action, - percentile: hand, - certainty: certainty(hand, &[row.raise, row.call, row.jam]), - reason: describe(pos, situation, action, &row), - } -} +use super::allin_call_cutoff::call_cutoff; +use super::certainty::certainty; +use super::chart_decision::decide; +use super::chart_row::ChartRow; +use super::effective_stack::effective_stack_bb; +use super::full_chart::full_row; +use super::hand_percentile::percentile; +use super::plan::PreflopPlan; +use super::seat_position::seat_position; +use super::push_chart::push_cutoff; +use super::reason::describe; +use super::situation::{classify, Situation}; +use super::width_factor::width_factor; +use crate::exploit::steal_width::steal_width; +use crate::exploit::thresholds::Thresholds; +use crate::game::Spot; +use crate::variant::ActionShape; + +/// At or below this effective stack (bb) raising ranges become jamming ranges. +const SHORT_STACK_BB: f64 = 15.0; + +/// A non-finite or non-positive width scale is ignored (treated as neutral). +fn sane_scale(scale: f64) -> f64 { + if scale.is_finite() && scale > 0.0 { + scale + } else { + 1.0 + } +} + +/// The cut-offs that apply here, before the hand is looked at. +fn cutoffs(spot: &Spot, situation: Situation, effective_bb: f64, scale: f64) -> ChartRow { + let rules = spot.rules(); + let pos = seat_position(spot, spot.hero_seat); + let width = width_factor(spot.seats, rules.hole_usage) * scale; + match (situation, rules.shape) { + (Situation::FacingAllIn, ActionShape::Full) => { + ChartRow::new(0.0, call_cutoff(spot.to_call, spot.pot), 0.0).scaled(scale) + } + (Situation::FacingAllIn, ActionShape::Binary) => { + ChartRow::new(0.0, 0.0, call_cutoff(spot.to_call, spot.pot)).scaled(scale) + } + (_, ActionShape::Binary) => { + ChartRow::new(0.0, 0.0, push_cutoff(pos, situation, effective_bb)).scaled(scale) + } + (_, ActionShape::Full) => { + let row = full_row(pos, situation) + .unwrap_or(ChartRow::new(0.0, 0.0, 0.0)) + .scaled(width); + if effective_bb <= SHORT_STACK_BB { + row.raises_become_jams() + } else { + row + } + } + } +} + +/// Width multiplier for this situation: `range_width_scale` (the profile shift), and in +/// unopened pots, which are steals, also how often the players behind fold +/// (`exploit::steal_width`: wider against nits, narrower against calling stations). +fn scale_for(spot: &Spot, situation: Situation, thresholds: &Thresholds) -> f64 { + let shift = sane_scale(thresholds.range_width_scale); + match situation { + Situation::Unopened => shift * steal_width(spot), + _ => shift, + } +} + +/// Chart lookup for a preflop spot, widened or narrowed by `scale_for`. +/// +/// Position (`position`), situation (`classify`) and the variant's rules pick a chart row; +/// the row is scaled by table size, game and `range_width_scale`; the hand's percentile +/// then selects jam / raise / call / fold. Binary-shape games only ever answer Jam or Fold. +pub fn advise(spot: &Spot, thresholds: &Thresholds) -> PreflopPlan { + let hand = percentile(spot.variant, &spot.hero_cards); + let pos = seat_position(spot, spot.hero_seat); + let situation = classify(spot.to_call, spot.big_blind, spot.pot, spot.hero_stack); + let row = cutoffs(spot, situation, effective_stack_bb(spot), scale_for(spot, situation, thresholds)); + let action = decide(hand, &row); + PreflopPlan { + action, + percentile: hand, + certainty: certainty(hand, &[row.raise, row.call, row.jam]), + reason: describe(pos, situation, action, &row), + } +} diff --git a/src/wire/decode_villain.rs b/src/wire/decode_villain.rs index 6edd6c38..2d88de2c 100644 --- a/src/wire/decode_villain.rs +++ b/src/wire/decode_villain.rs @@ -1,37 +1,38 @@ -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")?, - })) -} - -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::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() +} diff --git a/tests/bluff_fold_chance.rs b/tests/bluff_fold_chance.rs new file mode 100644 index 00000000..138b47e5 --- /dev/null +++ b/tests/bluff_fold_chance.rs @@ -0,0 +1,79 @@ +//! Spec: P(fold) of one opponent from their profile and the bet size. +//! +//! Mapping: `p = 1 - (1 - f)^(ratio / 0.66)`, `f` = foldToBet (or the style default), +//! times 0.7 when the opponent already bet (they are being raised), capped at 0.95. +//! foldToBet is measured against a typical two-thirds-pot bet, so at that size p = f. + +use pokerfreak::exploit::fold_chance::{ + fold_base, fold_chance, DEFAULT_FOLD_TO_BET, MAX_FOLD, RAISE_RESISTANCE, REFERENCE_RATIO, +}; +use pokerfreak::exploit::profile::Profile; +use pokerfreak::exploit::table_fold::pressure_ratio; + +fn folds(f: f64) -> Profile { + Profile { fold_to_bet: Some(f), ..Profile::default() } +} + +fn close(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-9 +} + +#[test] +fn at_the_reference_size_the_chance_is_fold_to_bet() { + for f in [0.1, 0.3, 0.5, 0.8] { + assert!(close(fold_chance(Some(&folds(f)), REFERENCE_RATIO, false), f), "{f}"); + } +} + +#[test] +fn bigger_bets_and_bigger_folders_fold_more() { + let p = folds(0.5); + let sizes = [0.1, 0.33, 0.5, 0.66, 1.0, 1.5, 3.0]; + for w in sizes.windows(2) { + assert!(fold_chance(Some(&p), w[0], false) < fold_chance(Some(&p), w[1], false)); + } + for w in [0.1, 0.3, 0.5, 0.7, 0.9].windows(2) { + assert!(fold_chance(Some(&folds(w[0])), 1.0, false) < fold_chance(Some(&folds(w[1])), 1.0, false)); + } +} + +#[test] +fn no_bet_no_fold_and_never_certain() { + assert_eq!(fold_chance(Some(&folds(0.9)), 0.0, false), 0.0); + assert!(fold_chance(Some(&folds(1.0)), 10.0, false) <= MAX_FOLD); + assert!(fold_chance(Some(&folds(0.0)), 10.0, false) == 0.0, "a player who never folds never folds"); +} + +#[test] +fn being_raised_after_betting_folds_less() { + let p = folds(0.6); + assert!(close(fold_chance(Some(&p), 1.0, true), RAISE_RESISTANCE * fold_chance(Some(&p), 1.0, false))); +} + +#[test] +fn without_fold_to_bet_the_style_decides() { + let nit = Profile { vpip: Some(0.10), pfr: Some(0.08), ..Profile::default() }; + let station = Profile { vpip: Some(0.55), pfr: Some(0.05), ..Profile::default() }; + assert_eq!(fold_base(None), DEFAULT_FOLD_TO_BET); + assert!(fold_base(Some(&nit)) > DEFAULT_FOLD_TO_BET); + assert!(fold_base(Some(&station)) < DEFAULT_FOLD_TO_BET); + assert_eq!(fold_base(Some(&folds(0.33))), 0.33); +} + +#[test] +fn garbage_inputs_stay_inside_zero_and_the_cap() { + for f in [f64::NAN, -1.0, 2.0] { + for r in [f64::NAN, -1.0, 0.5, f64::INFINITY] { + let p = fold_chance(Some(&folds(f)), r, false); + assert!((0.0..=MAX_FOLD).contains(&p), "{f} {r} -> {p}"); + } + } +} + +#[test] +fn pressure_is_the_extra_over_a_call_against_the_pot_after_calling() { + assert!(close(pressure_ratio(10.0, 0.0, 5.0), 0.5)); + // Raise to 20 over a bet of 5 into 10: 15 extra against a pot of 15. + assert!(close(pressure_ratio(10.0, 5.0, 20.0), 1.0)); + assert_eq!(pressure_ratio(0.0, 0.0, 0.0), 0.0); +} diff --git a/tests/bluff_property.rs b/tests/bluff_property.rs new file mode 100644 index 00000000..cd09bc5c --- /dev/null +++ b/tests/bluff_property.rs @@ -0,0 +1,150 @@ +//! Property: a bluff (or semibluff) is only ever chosen when both branches of its +//! expected value are accounted for and the total pays: +//! +//! EV = P(all fold) * pot + (1 - P(all fold)) * (called share * final pot - added) +//! +//! with a strictly positive fold branch, EV > 0 and EV above the best passive line. +//! Never against an opponent who never folds; pure bluffs heads-up only. + +mod spot_fixture; + +use pokerfreak::engine::bluff::{branches, NEVER_FOLDS, PURE_BLUFF_MIN_FOLD}; +use pokerfreak::engine::called::Called; +use pokerfreak::engine::effective::effective; +use pokerfreak::engine::multiway::realized_share; +use pokerfreak::engine::options::passive_ev; +use pokerfreak::engine::postflop::choose_postflop_with; +use pokerfreak::exploit::profile::Profile; +use pokerfreak::exploit::table_fold::table_fold; +use pokerfreak::exploit::thresholds::Thresholds; +use pokerfreak::game::{ActionKind, Choice, Spot, Street, Villain}; +use pokerfreak::read::draw::Draw; +use pokerfreak::read::made::Made; +use pokerfreak::read::suit_pattern::SuitPattern; +use pokerfreak::rng::Rng; +use spot_fixture::*; + +const MADES: [Made; 8] = [ + Made::Air, + Made::Underpair, + Made::BottomPair, + Made::MiddlePair, + Made::TopPairWeakKicker, + Made::TwoPair, + Made::Set, + Made::Flush, +]; +const DRAWS: [Draw; 5] = [Draw::None, Draw::Backdoor, Draw::Gutshot, Draw::OpenEnded, Draw::Flush]; + +struct Case { + spot: Spot, + share: f64, + called: f64, + made: Made, + draw: Draw, + outs: u8, +} + +fn pick(items: &[T], rng: Rng) -> (T, Rng) { + let (i, rng) = rng.below(items.len() as u64); + (items[i as usize], rng) +} + +fn profile(rng: Rng) -> (Option, Rng) { + let (kind, rng) = rng.below(4); + let (f, rng) = rng.unit(); + let (a, rng) = rng.unit(); + let p = match kind { + 0 => None, + 1 => Some(Profile { fold_to_bet: Some(f), ..Profile::default() }), + 2 => Some(Profile { fold_to_bet: Some(f * 0.1), aggression: Some(a), ..Profile::default() }), + _ => Some(Profile { vpip: Some(f * 0.6), pfr: Some(f * 0.3), aggression: Some(a), ..Profile::default() }), + }; + (p, rng) +} + +fn case(rng: Rng) -> (Case, Rng) { + let (pot, rng) = rng.unit(); + let (bet, rng) = rng.below(3); + let (street, rng) = pick(&[Street::Flop, Street::Turn, Street::River], rng); + let (n, rng) = rng.below(3); + let (share, rng) = rng.unit(); + let (drop, rng) = rng.unit(); + let (made, rng) = pick(&MADES, rng); + let (draw, rng) = pick(&DRAWS, rng); + let (outs, rng) = rng.below(13); + let pot = 2.0 + 40.0 * pot; + let to_call = [0.0, pot * 0.33, pot * 0.75][bet as usize]; + let (villains, rng) = (0..=n).fold((Vec::new(), rng), |(mut vs, rng), i| { + let (p, rng) = profile(rng); + vs.push(Villain { seat: i as u8 + 1, stack: 200.0, folded: false, profile: p }); + (vs, rng) + }); + let legal = if to_call > 0.0 { + vec![ActionKind::Fold, ActionKind::Call, ActionKind::Raise] + } else { + vec![ActionKind::Check, ActionKind::Raise] + }; + let spot = Spot { + street, + pot, + to_call, + hero_stack: 200.0, + min_raise_to: Some((to_call * 2.0).max(1.0)), + max_raise_to: Some(200.0), + legal, + villains, + ..round_flop() + }; + (Case { spot, share, called: share * (1.0 - drop * 0.8), made, draw, outs: outs as u8 }, rng) +} + +#[test] +fn bluffs_only_with_a_paying_two_branch_ev() { + let th = Thresholds::BASE; + let (mut bluffs, mut rng) = (0, Rng::seeded(0xB1_0FF)); + for _ in 0..4000 { + let (c, next) = case(rng); + rng = next; + let read = read_of(c.made, c.draw, c.outs, SuitPattern::Rainbow, 0.3); + let d = choose_postflop_with(&c.spot, &estimate(c.share, 0.002), &Called::flat(c.called), &th, &read); + let Choice::Raise { to } = d.choice else { continue }; + if !d.reason.contains("bluff") { + continue; + } + bluffs += 1; + let live = c.spot.live_villains().count(); + let eff = effective(&c.spot, c.share, &th, &read); + let fold = table_fold(&c.spot, to, th.fold_equity_scale); + let b = branches(&c.spot, to, fold, realized_share(c.called, live)); + let passive = passive_ev(&c.spot, eff.share).unwrap_or(f64::NEG_INFINITY); + assert!(fold > 0.0 && b.fold > 0.0, "{d:?} fold {fold}"); + assert!(b.total > 0.0 && b.total > passive, "{d:?}: {b:?} vs passive {passive}"); + assert!((b.fold + b.called - b.total).abs() < 1e-9); + assert!( + c.spot.live_villains().all(|v| v.profile.and_then(|p| p.fold_to_bet).is_none_or(|f| f > NEVER_FOLDS)), + "bluffed a never-folder: {d:?}" + ); + if !d.reason.contains("semibluff") { + assert_eq!(live, 1, "pure bluff multiway: {d:?}"); + assert!(fold >= PURE_BLUFF_MIN_FOLD, "{d:?} fold {fold}"); + } + if c.spot.street == Street::River { + assert!(!d.reason.contains("semibluff"), "{d:?}"); + } + } + assert!(bluffs > 50, "the generator must reach bluffs: {bluffs}"); +} + +#[test] +fn the_called_branch_matters() { + // Same spot, same overall equity: when the calls come from a much stronger range, + // the raise loses its edge and the passive line wins. + let spot = Spot { to_call: 0.0, legal: vec![ActionKind::Check, ActionKind::Raise], ..round_flop() }; + let read = read_of(Made::TopPairWeakKicker, Draw::None, 0, SuitPattern::Rainbow, 0.2); + let th = Thresholds::BASE; + let loose = choose_postflop_with(&spot, &estimate(0.75, 0.002), &Called::flat(0.75), &th, &read); + let tight = choose_postflop_with(&spot, &estimate(0.75, 0.002), &Called::flat(0.2), &th, &read); + assert!(matches!(loose.choice, Choice::Raise { .. }), "{loose:?}"); + assert_eq!(tight.choice, Choice::Check, "{tight:?}"); +} diff --git a/tests/bluff_range.rs b/tests/bluff_range.rs new file mode 100644 index 00000000..c7ea8a67 --- /dev/null +++ b/tests/bluff_range.rs @@ -0,0 +1,91 @@ +//! Spec: a betting range keeps a bluff fraction. +//! +//! A continuation with `bluff_share = b` lets hands below its floor through with a fixed, +//! per-hand acceptance so that, over all starting hands in the preflop band, the hands +//! below the floor make up `b` of what passes. Without it a bet is read as pure value +//! and hero folds every bluff catcher (systematic under-calling). + +mod spot_fixture; + +use pokerfreak::card::{deck, Card}; +use pokerfreak::engine::range_filter::range_filter; +use pokerfreak::exploit::range_spec::{Continuation, RangeSpec}; +use pokerfreak::read::glance::glance; +use pokerfreak::read::made::Made; +use pokerfreak::variant::{rules, Variant}; +use spot_fixture::cards; + +fn spec(bluff_share: f64) -> RangeSpec { + RangeSpec { + lo: 0.0, + hi: 0.6, + continues: vec![Continuation { + board_len: 5, + min_made: Made::TopPairGoodKicker, + draws_continue: false, + bluff_share, + }], + } +} + +fn all_hands(board: &[Card]) -> Vec<[Card; 2]> { + let pool = deck::without(board); + (0..pool.len()) + .flat_map(|i| (i + 1..pool.len()).map(move |j| (i, j))) + .map(|(i, j)| [pool[i], pool[j]]) + .collect() +} + +/// (passing hands, of which below the floor) +fn census(b: f64) -> (usize, usize) { + let board = cards("Kd 8s 4c 2h Jc"); + let filter = range_filter(&spec(b), rules(Variant::Nlhe), Variant::Nlhe, &board); + let r = rules(Variant::Nlhe); + all_hands(&board).iter().filter(|h| filter(&h[..])).fold((0, 0), |(n, air), h| { + let below = glance(&r, &h[..], &board).map_or(true, |(m, _)| m < Made::TopPairGoodKicker); + (n + 1, air + usize::from(below)) + }) +} + +#[test] +fn without_a_bluff_share_only_value_passes() { + let (n, air) = census(0.0); + assert!(n > 0); + assert_eq!(air, 0); +} + +#[test] +fn the_bluff_share_is_met_over_the_whole_range() { + for b in [0.1, 0.25, 0.4] { + let (n, air) = census(b); + let share = air as f64 / n as f64; + assert!((share - b).abs() < 0.03, "b = {b}: {air}/{n} = {share:.3}"); + } +} + +#[test] +fn acceptance_is_fixed_per_hand_and_order_free() { + let board = cards("Kd 8s 4c 2h Jc"); + let f = range_filter(&spec(0.3), rules(Variant::Nlhe), Variant::Nlhe, &board); + let g = range_filter(&spec(0.3), rules(Variant::Nlhe), Variant::Nlhe, &board); + for h in all_hands(&board).iter().take(400) { + let swapped = [h[1], h[0]]; + assert_eq!(f(&h[..]), g(&h[..])); + assert_eq!(f(&h[..]), f(&swapped[..])); + } +} + +#[test] +fn five_card_ranges_get_bluffs_too() { + let board = cards("Kd 8s 4c 2h Jc"); + let f = range_filter(&spec(0.3), rules(Variant::Plo5), Variant::Plo5, &board); + // A hand with no pair at all on this board still passes sometimes. + let pool = deck::without(&board); + let passing_air = (0..300) + .map(|i| [0, 7, 13, 21, 29].map(|k| pool[(i * 3 + k) % pool.len()])) + .filter(|h| h.iter().enumerate().all(|(i, c)| !h[..i].contains(c))) + .filter(|h| glance(&rules(Variant::Plo5), &h[..], &board).is_ok_and(|(m, _)| m < Made::TopPairGoodKicker)) + .filter(|h| f(&h[..])) + .count(); + assert!(passing_air > 0); +} diff --git a/tests/bluff_share.rs b/tests/bluff_share.rs new file mode 100644 index 00000000..02ffa9fd --- /dev/null +++ b/tests/bluff_share.rs @@ -0,0 +1,63 @@ +//! Spec: how much of an opponent's betting range is a bluff. +//! +//! Base: the balanced river share `s / (1 + 2s)` for a bet of `s` pots (a caller then is +//! indifferent: Chen/Ankenman, "The Mathematics of Poker"). Earlier streets keep +//! less pure air (draws do the bluffing): turn 0.6, flop 0.5. Style factor: nit 0.4, +//! calling station 0.5, loose-aggressive 1.5, else 1.0; an `aggression` figure +//! (share of postflop actions that are bets or raises) overrides it as `aggression / 0.45`, +//! clamped to [0, 2]. Capped at 0.6. + +use pokerfreak::exploit::bluff_share::{bluff_share, MAX_BLUFF_SHARE, NEUTRAL_RATIO}; +use pokerfreak::exploit::profile::Profile; +use pokerfreak::game::Street; + +fn close(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-9 +} + +#[test] +fn a_regular_on_the_river_bluffs_the_balanced_share() { + for s in [0.5, 1.0, 2.0] { + assert!(close(bluff_share(None, Some(s), Street::River), s / (1.0 + 2.0 * s)), "{s}"); + } + // Pot-size bet: one bluff for every two value bets. + assert!(close(bluff_share(None, Some(1.0), Street::River), 1.0 / 3.0)); +} + +#[test] +fn unknown_size_counts_as_two_thirds_pot() { + assert!(close( + bluff_share(None, None, Street::River), + bluff_share(None, Some(NEUTRAL_RATIO), Street::River) + )); +} + +#[test] +fn earlier_streets_hold_less_pure_air() { + let r = bluff_share(None, Some(1.0), Street::River); + assert!(close(bluff_share(None, Some(1.0), Street::Turn), 0.6 * r)); + assert!(close(bluff_share(None, Some(1.0), Street::Flop), 0.5 * r)); +} + +#[test] +fn styles_order_the_share() { + let nit = Profile { vpip: Some(0.10), pfr: Some(0.08), ..Profile::default() }; + let lag = Profile { vpip: Some(0.45), pfr: Some(0.30), ..Profile::default() }; + let station = Profile { vpip: Some(0.55), pfr: Some(0.05), ..Profile::default() }; + let at = |p: &Profile| bluff_share(Some(p), Some(1.0), Street::River); + assert!(at(&nit) < bluff_share(None, Some(1.0), Street::River)); + assert!(at(&station) < bluff_share(None, Some(1.0), Street::River)); + assert!(at(&lag) > bluff_share(None, Some(1.0), Street::River)); +} + +#[test] +fn aggression_overrides_the_style_and_the_cap_holds() { + let passive = Profile { aggression: Some(0.0), ..Profile::default() }; + assert_eq!(bluff_share(Some(&passive), Some(1.0), Street::River), 0.0); + let maniac = Profile { aggression: Some(1.0), ..Profile::default() }; + assert!(bluff_share(Some(&maniac), Some(1.0), Street::River) <= MAX_BLUFF_SHARE); + for r in [f64::NAN, -1.0, 0.0, 50.0] { + let b = bluff_share(Some(&maniac), Some(r), Street::River); + assert!((0.0..=MAX_BLUFF_SHARE).contains(&b), "{r} -> {b}"); + } +} diff --git a/tests/engine_multiway.rs b/tests/engine_multiway.rs index 44d63845..c5c2dca9 100644 --- a/tests/engine_multiway.rs +++ b/tests/engine_multiway.rs @@ -1,112 +1,116 @@ -mod spot_fixture; - -use pokerfreak::engine::effective::effective; -use pokerfreak::engine::multiway::{ - extra_call_margin, extra_value_raise, realized_share, semibluff_allowed, -}; -use pokerfreak::engine::postflop::choose_postflop; -use pokerfreak::exploit::thresholds::Thresholds; -use pokerfreak::game::Choice; -use pokerfreak::read::draw::Draw; -use pokerfreak::read::made::Made; -use pokerfreak::read::suit_pattern::SuitPattern; -use spot_fixture::*; - -const BASE: Thresholds = Thresholds::BASE; - -fn close(a: f64, b: f64) -> bool { - (a - b).abs() < 1e-9 -} - -#[test] -fn heads_up_changes_nothing() { - assert_eq!(realized_share(0.5, 1), 0.5); - assert_eq!(extra_call_margin(1), 0.0); - assert_eq!(extra_value_raise(1), 0.0); - assert_eq!(realized_share(0.5, 0), 0.5); -} - -#[test] -fn each_extra_villain_discounts_equity_and_raises_the_bars() { - assert!(close(realized_share(0.5, 4), 0.5 * 0.97f64.powi(3))); - assert!(close(extra_call_margin(3), 0.02)); - assert!(close(extra_value_raise(3), 0.10)); - assert!(realized_share(0.5, 5) < realized_share(0.5, 4)); - assert!(extra_value_raise(5) > extra_value_raise(4)); -} - -#[test] -fn semibluffs_need_at_most_two_villains() { - assert!(semibluff_allowed(0) && semibluff_allowed(1) && semibluff_allowed(2)); - assert!(!semibluff_allowed(3) && !semibluff_allowed(5)); -} - -#[test] -fn effective_thresholds_combine_texture_and_player_count() { - // Medium hand, dry board (wetness 0.1): texture gives margin 0.034, value 0.692. - 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!(e.value_ok && e.raise_ok && !e.semibluff_ok); -} - -#[test] -fn folded_villains_do_not_count() { - let mut spot = with_villains(round_flop(), 4); - spot.villains[0].folded = true; - spot.villains[1].folded = true; - let e = effective(&spot, 0.5, &BASE, &neutral_read()); - assert_eq!(e.villains, 2); - assert!(e.semibluff_ok); -} - -#[test] -fn no_live_villain_counts_as_one() { - let e = effective(&with_villains(round_flop(), 0), 0.5, &BASE, &neutral_read()); - assert_eq!(e.villains, 1); - assert_eq!(e.share, 0.5); -} - -// round_flop: pot 10, 5 to call, break-even 1/3. - -#[test] -fn a_share_that_calls_heads_up_folds_four_way() { - let share = estimate(0.38, 0.002); - let heads_up = choose_postflop(&with_villains(round_flop(), 1), &share, &BASE, &neutral_read()); - assert_eq!(heads_up.choice, Choice::Call, "{heads_up:?}"); - let four_way = choose_postflop(&with_villains(round_flop(), 4), &share, &BASE, &neutral_read()); - assert_eq!(four_way.choice, Choice::Fold, "{four_way:?}"); -} - -#[test] -fn a_share_that_value_raises_heads_up_only_calls_three_way() { - let share = estimate(0.70, 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()); - assert_eq!(three_way.choice, Choice::Call, "{three_way:?}"); -} - -#[test] -fn semibluff_works_two_way_but_not_three_way() { - let share = estimate(0.45, 0.005); - let two = choose_postflop(&with_villains(round_flop(), 2), &share, &BASE, &flush_draw_read()); - assert!(matches!(two.choice, Choice::Raise { .. }), "{two:?}"); - let three = choose_postflop(&with_villains(round_flop(), 3), &share, &BASE, &flush_draw_read()); - assert_eq!(three.choice, Choice::Call, "{three:?}"); -} - -#[test] -fn the_reason_names_the_player_count_when_multiway() { - let d = choose_postflop( - &with_villains(round_flop(), 3), - &estimate(0.45, 0.002), - &BASE, - &neutral_read(), - ); - assert!(d.reason.contains("3-way"), "{}", d.reason); -} +mod spot_fixture; + +use pokerfreak::engine::effective::effective; +use pokerfreak::engine::multiway::{ + extra_call_margin, extra_value_raise, realized_share, semibluff_allowed, +}; +use pokerfreak::engine::postflop::choose_postflop; +use pokerfreak::exploit::thresholds::Thresholds; +use pokerfreak::game::Choice; +use pokerfreak::read::draw::Draw; +use pokerfreak::read::made::Made; +use pokerfreak::read::suit_pattern::SuitPattern; +use spot_fixture::*; + +const BASE: Thresholds = Thresholds::BASE; + +fn close(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-9 +} + +#[test] +fn heads_up_changes_nothing() { + assert_eq!(realized_share(0.5, 1), 0.5); + assert_eq!(extra_call_margin(1), 0.0); + assert_eq!(extra_value_raise(1), 0.0); + assert_eq!(realized_share(0.5, 0), 0.5); +} + +#[test] +fn each_extra_villain_discounts_equity_and_raises_the_bars() { + assert!(close(realized_share(0.5, 4), 0.5 * 0.97f64.powi(3))); + assert!(close(extra_call_margin(3), 0.02)); + assert!(close(extra_value_raise(3), 0.10)); + assert!(realized_share(0.5, 5) < realized_share(0.5, 4)); + assert!(extra_value_raise(5) > extra_value_raise(4)); +} + +#[test] +fn semibluffs_need_at_most_two_villains() { + assert!(semibluff_allowed(0) && semibluff_allowed(1) && semibluff_allowed(2)); + assert!(!semibluff_allowed(3) && !semibluff_allowed(5)); +} + +#[test] +fn effective_thresholds_combine_texture_and_player_count() { + // Medium hand, dry board (wetness 0.1): texture gives margin 0.034, value 0.692. + 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!(e.value_ok && e.raise_ok && !e.semibluff_ok); +} + +#[test] +fn folded_villains_do_not_count() { + let mut spot = with_villains(round_flop(), 4); + spot.villains[0].folded = true; + spot.villains[1].folded = true; + let e = effective(&spot, 0.5, &BASE, &neutral_read()); + assert_eq!(e.villains, 2); + assert!(e.semibluff_ok); +} + +#[test] +fn no_live_villain_counts_as_one() { + let e = effective(&with_villains(round_flop(), 0), 0.5, &BASE, &neutral_read()); + assert_eq!(e.villains, 1); + assert_eq!(e.share, 0.5); +} + +// round_flop: pot 10, 5 to call, break-even 1/3. + +#[test] +fn a_share_that_calls_heads_up_folds_four_way() { + let share = estimate(0.38, 0.002); + let heads_up = choose_postflop(&with_villains(round_flop(), 1), &share, &BASE, &neutral_read()); + assert_eq!(heads_up.choice, Choice::Call, "{heads_up:?}"); + let four_way = choose_postflop(&with_villains(round_flop(), 4), &share, &BASE, &neutral_read()); + assert_eq!(four_way.choice, Choice::Fold, "{four_way:?}"); +} + +#[test] +fn a_share_that_value_raises_heads_up_only_calls_three_way() { + let share = estimate(0.70, 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()); + assert_eq!(three_way.choice, Choice::Call, "{three_way:?}"); +} + +#[test] +fn semibluff_works_two_way_but_not_three_way() { + // Folds are independent per villain (`exploit::table_fold`), so two-way fold equity + // is the square of one villain's. With foldy villains (scale 1.6: 0.67 each to a pot + // raise) the semibluff pays two-way; three-way it is not allowed at all. + let share = estimate(0.45, 0.005); + let foldy = Thresholds { fold_equity_scale: 1.6, ..BASE }; + let two = choose_postflop(&with_villains(round_flop(), 2), &share, &foldy, &flush_draw_read()); + assert!(matches!(two.choice, Choice::Raise { .. }), "{two:?}"); + let three = choose_postflop(&with_villains(round_flop(), 3), &share, &foldy, &flush_draw_read()); + assert_eq!(three.choice, Choice::Call, "{three:?}"); +} + +#[test] +fn the_reason_names_the_player_count_when_multiway() { + let d = choose_postflop( + &with_villains(round_flop(), 3), + &estimate(0.45, 0.002), + &BASE, + &neutral_read(), + ); + assert!(d.reason.contains("3-way"), "{}", d.reason); +} diff --git a/tests/engine_uncertainty.rs b/tests/engine_uncertainty.rs index b95820b7..79c28bf0 100644 --- a/tests/engine_uncertainty.rs +++ b/tests/engine_uncertainty.rs @@ -1,92 +1,93 @@ -mod spot_fixture; - -use pokerfreak::engine::postflop::choose_postflop; -use pokerfreak::engine::uncertainty::{abstain_confidence, MAX_UNCERTAIN_CONFIDENCE, MIN_UNCERTAIN_CONFIDENCE}; -use pokerfreak::exploit::thresholds::Thresholds; -use pokerfreak::game::Choice; -use pokerfreak::read::draw::Draw; -use pokerfreak::read::made::Made; -use pokerfreak::read::suit_pattern::SuitPattern; -use spot_fixture::*; - -const BASE: Thresholds = Thresholds::BASE; - -fn close(a: f64, b: f64) -> bool { - (a - b).abs() < 1e-9 -} - -#[test] -fn confidence_rises_linearly_from_the_edge_to_the_rim_of_the_band() { - assert!(close(abstain_confidence(0.0, 0.04), 0.05)); - assert!(close(abstain_confidence(0.02, 0.04), 0.175)); - assert!(close(abstain_confidence(0.04, 0.04), 0.30)); - assert_eq!(MIN_UNCERTAIN_CONFIDENCE, 0.05); - assert_eq!(MAX_UNCERTAIN_CONFIDENCE, 0.30); -} - -#[test] -fn confidence_never_leaves_its_range() { - for (d, w) in [(1.0, 0.04), (-1.0, 0.04), (0.01, 0.0), (f64::NAN, 0.1), (0.1, f64::NAN), (f64::INFINITY, 1.0)] { - let c = abstain_confidence(d, w); - assert!((0.05..=0.30).contains(&c), "{d} {w} -> {c}"); - } -} - -// round_flop: break-even 1/3, plain call margin 0.02 -> call breakpoint 0.3533. - -#[test] -fn abstain_near_the_effective_breakpoint_carries_small_confidence() { - let d = choose_postflop(&round_flop(), &estimate(0.34, 0.005), &BASE, &neutral_read()); - assert_eq!(d.choice, Choice::Abstain); - let c = d.confidence.value(); - assert!((0.05..=0.30).contains(&c), "{c}"); -} - -#[test] -fn closer_to_the_edge_means_less_confidence() { - let near = choose_postflop(&round_flop(), &estimate(0.352, 0.005), &BASE, &neutral_read()); - let rim = choose_postflop(&round_flop(), &estimate(0.335, 0.005), &BASE, &neutral_read()); - assert_eq!((near.choice, rim.choice), (Choice::Abstain, Choice::Abstain)); - assert!(near.confidence < rim.confidence, "{near:?} {rim:?}"); -} - -#[test] -fn the_band_applies_to_the_texture_adjusted_breakpoint() { - // Medium pair on a dry board: margin 0.02 + 0.01 + 0.004 = 0.034 -> breakpoint 0.3673. - // Share 0.38 is outside the band around the plain 0.3533 but inside the one around 0.3673. - let medium = read_of(Made::MiddlePair, Draw::None, 0, SuitPattern::Rainbow, 0.1); - let plain = choose_postflop(&round_flop(), &estimate(0.38, 0.001), &BASE, &neutral_read()); - let shifted = choose_postflop(&round_flop(), &estimate(0.38, 0.001), &BASE, &medium); - assert_eq!(plain.choice, Choice::Call); - assert_eq!(shifted.choice, Choice::Abstain, "{shifted:?}"); -} - -#[test] -fn the_band_applies_to_the_multiway_adjusted_breakpoint() { - // Three-way: realized 0.38 * 0.9409 = 0.3575, breakpoint 0.3333 + 0.04 = 0.3733. - let spot = with_villains(round_flop(), 3); - let d = choose_postflop(&spot, &estimate(0.38, 0.001), &BASE, &neutral_read()); - assert_eq!(d.choice, Choice::Abstain, "{d:?}"); -} - -#[test] -fn marginal_raise_versus_call_abstains_with_small_confidence() { - // Flush draw, share 0.40, fold-equity scale 0.4: the best raise (to 10) is worth 2.0 - // against the call's 1.0. EV standard error = std_error * final pot (25). - let th = Thresholds { fold_equity_scale: 0.4, ..BASE }; - let noisy = choose_postflop(&round_flop(), &estimate(0.40, 0.05), &th, &flush_draw_read()); - assert_eq!(noisy.choice, Choice::Abstain, "{noisy:?}"); - let c = noisy.confidence.value(); - assert!((0.05..=0.30).contains(&c), "{c}"); - let tight = choose_postflop(&round_flop(), &estimate(0.40, 0.02), &th, &flush_draw_read()); - assert!(matches!(tight.choice, Choice::Raise { .. }), "{tight:?}"); -} - -#[test] -fn invalid_equity_stays_at_zero_confidence() { - for share in [f64::NAN, -0.1, 1.5] { - let d = choose_postflop(&round_flop(), &estimate(share, 0.01), &BASE, &neutral_read()); - assert_eq!(d.choice, Choice::Abstain); - assert_eq!(d.confidence.value(), 0.0); - } -} +mod spot_fixture; + +use pokerfreak::engine::postflop::choose_postflop; +use pokerfreak::engine::uncertainty::{abstain_confidence, MAX_UNCERTAIN_CONFIDENCE, MIN_UNCERTAIN_CONFIDENCE}; +use pokerfreak::exploit::thresholds::Thresholds; +use pokerfreak::game::Choice; +use pokerfreak::read::draw::Draw; +use pokerfreak::read::made::Made; +use pokerfreak::read::suit_pattern::SuitPattern; +use spot_fixture::*; + +const BASE: Thresholds = Thresholds::BASE; + +fn close(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-9 +} + +#[test] +fn confidence_rises_linearly_from_the_edge_to_the_rim_of_the_band() { + assert!(close(abstain_confidence(0.0, 0.04), 0.05)); + assert!(close(abstain_confidence(0.02, 0.04), 0.175)); + assert!(close(abstain_confidence(0.04, 0.04), 0.30)); + assert_eq!(MIN_UNCERTAIN_CONFIDENCE, 0.05); + assert_eq!(MAX_UNCERTAIN_CONFIDENCE, 0.30); +} + +#[test] +fn confidence_never_leaves_its_range() { + for (d, w) in [(1.0, 0.04), (-1.0, 0.04), (0.01, 0.0), (f64::NAN, 0.1), (0.1, f64::NAN), (f64::INFINITY, 1.0)] { + let c = abstain_confidence(d, w); + assert!((0.05..=0.30).contains(&c), "{d} {w} -> {c}"); + } +} + +// round_flop: break-even 1/3, plain call margin 0.02 -> call breakpoint 0.3533. + +#[test] +fn abstain_near_the_effective_breakpoint_carries_small_confidence() { + let d = choose_postflop(&round_flop(), &estimate(0.34, 0.005), &BASE, &neutral_read()); + assert_eq!(d.choice, Choice::Abstain); + let c = d.confidence.value(); + assert!((0.05..=0.30).contains(&c), "{c}"); +} + +#[test] +fn closer_to_the_edge_means_less_confidence() { + let near = choose_postflop(&round_flop(), &estimate(0.352, 0.005), &BASE, &neutral_read()); + let rim = choose_postflop(&round_flop(), &estimate(0.335, 0.005), &BASE, &neutral_read()); + assert_eq!((near.choice, rim.choice), (Choice::Abstain, Choice::Abstain)); + assert!(near.confidence < rim.confidence, "{near:?} {rim:?}"); +} + +#[test] +fn the_band_applies_to_the_texture_adjusted_breakpoint() { + // Medium pair on a dry board: margin 0.02 + 0.01 + 0.004 = 0.034 -> breakpoint 0.3673. + // Share 0.38 is outside the band around the plain 0.3533 but inside the one around 0.3673. + let medium = read_of(Made::MiddlePair, Draw::None, 0, SuitPattern::Rainbow, 0.1); + let plain = choose_postflop(&round_flop(), &estimate(0.38, 0.001), &BASE, &neutral_read()); + let shifted = choose_postflop(&round_flop(), &estimate(0.38, 0.001), &BASE, &medium); + assert_eq!(plain.choice, Choice::Call); + assert_eq!(shifted.choice, Choice::Abstain, "{shifted:?}"); +} + +#[test] +fn the_band_applies_to_the_multiway_adjusted_breakpoint() { + // Three-way: realized 0.38 * 0.9409 = 0.3575, breakpoint 0.3333 + 0.04 = 0.3733. + let spot = with_villains(round_flop(), 3); + let d = choose_postflop(&spot, &estimate(0.38, 0.001), &BASE, &neutral_read()); + assert_eq!(d.choice, Choice::Abstain, "{d:?}"); +} + +#[test] +fn marginal_raise_versus_call_abstains_with_small_confidence() { + // Flush draw, share 0.40, fold-equity scale 0.85: P(fold) to a raise to 20 is + // 0.595 * 0.7 * 0.85 = 0.354, worth 3.54 - 0.646 * 2 = 2.25 against the call's 1.0. + // EV standard error = std_error * final pot (45): 2.25 noisy, 0.9 tight. + let th = Thresholds { fold_equity_scale: 0.85, ..BASE }; + let noisy = choose_postflop(&round_flop(), &estimate(0.40, 0.05), &th, &flush_draw_read()); + assert_eq!(noisy.choice, Choice::Abstain, "{noisy:?}"); + let c = noisy.confidence.value(); + assert!((0.05..=0.30).contains(&c), "{c}"); + let tight = choose_postflop(&round_flop(), &estimate(0.40, 0.02), &th, &flush_draw_read()); + assert!(matches!(tight.choice, Choice::Raise { .. }), "{tight:?}"); +} + +#[test] +fn invalid_equity_stays_at_zero_confidence() { + for share in [f64::NAN, -0.1, 1.5] { + let d = choose_postflop(&round_flop(), &estimate(share, 0.01), &BASE, &neutral_read()); + assert_eq!(d.choice, Choice::Abstain); + assert_eq!(d.confidence.value(), 0.0); + } +} diff --git a/tests/exploit_adjust.rs b/tests/exploit_adjust.rs index 06d1c583..97418c0d 100644 --- a/tests/exploit_adjust.rs +++ b/tests/exploit_adjust.rs @@ -1,141 +1,130 @@ -use pokerfreak::exploit::adjust::adjust; -use pokerfreak::exploit::profile::Profile; -use pokerfreak::exploit::thresholds::Thresholds; - -const BASE: Thresholds = Thresholds::BASE; - -fn profile(vpip: Option, pfr: Option, fold_to_bet: Option) -> Profile { - Profile { - vpip, - pfr, - fold_to_bet, - } -} - -fn station() -> Profile { - profile(Some(0.50), Some(0.05), Some(0.20)) -} - -fn nit() -> Profile { - profile(Some(0.10), Some(0.07), Some(0.75)) -} - -fn maniac() -> Profile { - profile(Some(0.60), Some(0.40), Some(0.40)) -} - -#[test] -fn no_information_changes_nothing() { - assert_eq!(adjust(BASE, &[]), BASE); - assert_eq!(adjust(BASE, &[Profile::default()]), BASE); - assert_eq!( - adjust(BASE, &[Profile::default(), Profile::default()]), - BASE - ); -} - -#[test] -fn calling_stations_are_value_bet_thinner_and_not_bluffed() { - let t = adjust(BASE, &[station()]); - assert!(t.fold_equity_scale < 0.7 * BASE.fold_equity_scale, "{t:?}"); - assert!(t.value_raise < BASE.value_raise); -} - -#[test] -fn nits_fold_more_and_bet_strong() { - let t = adjust(BASE, &[nit()]); - assert!(t.fold_equity_scale > BASE.fold_equity_scale); - assert!(t.call_margin > BASE.call_margin); - assert!(t.range_width_scale < BASE.range_width_scale); -} - -#[test] -fn aggressive_players_are_called_wider() { - let t = adjust(BASE, &[maniac()]); - assert!(t.call_margin < BASE.call_margin); - assert!(t.range_width_scale > BASE.range_width_scale); -} - -#[test] -fn more_fold_to_bet_never_lowers_fold_equity_scale() { - for (vpip, pfr) in [(0.30, 0.10), (0.15, 0.10), (0.55, 0.40), (0.50, 0.05)] { - let scales: Vec = (0..=20) - .map(|i| { - adjust( - BASE, - &[profile(Some(vpip), Some(pfr), Some(i as f64 / 20.0))], - ) - .fold_equity_scale - }) - .collect(); - assert!( - scales.windows(2).all(|w| w[0] <= w[1]), - "vpip {vpip}: {scales:?}" - ); - assert!(scales[20] > scales[0]); - } -} - -#[test] -fn several_profiles_combine_conservatively() { - let (s, n) = (adjust(BASE, &[station()]), adjust(BASE, &[nit()])); - let both = adjust(BASE, &[station(), nit()]); - assert_eq!(both.call_margin, s.call_margin.max(n.call_margin)); - assert_eq!( - both.fold_equity_scale, - s.fold_equity_scale.min(n.fold_equity_scale) - ); - assert_eq!(both.value_raise, s.value_raise.max(n.value_raise)); - assert_eq!( - both.range_width_scale, - s.range_width_scale.min(n.range_width_scale) - ); - // order does not matter, unknowns are ignored - assert_eq!(adjust(BASE, &[nit(), Profile::default(), station()]), both); -} - -#[test] -fn outputs_stay_in_sane_ranges_for_any_input() { - let grid = [ - None, - Some(-1.0), - Some(0.0), - Some(0.3), - Some(1.0), - Some(9.0), - Some(f64::NAN), - Some(f64::INFINITY), - ]; - for vpip in grid { - for pfr in grid { - for ftb in grid { - let t = adjust(BASE, &[profile(vpip, pfr, ftb)]); - assert!((0.0..=0.15).contains(&t.call_margin), "{t:?}"); - assert!((0.52..=0.85).contains(&t.value_raise), "{t:?}"); - assert!((0.0..=0.05).contains(&t.abstain_band), "{t:?}"); - assert!((0.3..=1.6).contains(&t.fold_equity_scale), "{t:?}"); - assert!((0.6..=1.4).contains(&t.range_width_scale), "{t:?}"); - } - } - } -} - -#[test] -fn adjust_is_pure() { - let ps = [station(), maniac()]; - assert_eq!(adjust(BASE, &ps), adjust(BASE, &ps)); -} - -#[test] -fn adjustments_compose_with_a_non_default_base() { - let tight = Thresholds { - fold_equity_scale: 0.8, - ..BASE - }; - let t = adjust(tight, &[nit()]); - assert!(t.fold_equity_scale > 0.8); - assert!( - adjust(tight, &[station()]).fold_equity_scale - < adjust(BASE, &[station()]).fold_equity_scale - ); -} +use pokerfreak::exploit::adjust::adjust; +use pokerfreak::exploit::profile::Profile; +use pokerfreak::exploit::thresholds::Thresholds; + +const BASE: Thresholds = Thresholds::BASE; + +fn profile(vpip: Option, pfr: Option, fold_to_bet: Option) -> Profile { + Profile { + vpip, + pfr, + fold_to_bet, + aggression: None, + } +} + +fn station() -> Profile { + profile(Some(0.50), Some(0.05), Some(0.20)) +} + +fn nit() -> Profile { + profile(Some(0.10), Some(0.07), Some(0.75)) +} + +fn maniac() -> Profile { + profile(Some(0.60), Some(0.40), Some(0.40)) +} + +#[test] +fn no_information_changes_nothing() { + assert_eq!(adjust(BASE, &[]), BASE); + assert_eq!(adjust(BASE, &[Profile::default()]), BASE); + assert_eq!( + adjust(BASE, &[Profile::default(), Profile::default()]), + BASE + ); +} + +#[test] +fn calling_stations_are_value_bet_thinner_and_not_bluffed() { + let t = adjust(BASE, &[station()]); + // Fold equity is per opponent now (`exploit::fold_chance`), not a shared threshold. + assert_eq!(t.fold_equity_scale, BASE.fold_equity_scale, "{t:?}"); + assert!(t.value_raise < BASE.value_raise); +} + +#[test] +fn nits_fold_more_and_bet_strong() { + let t = adjust(BASE, &[nit()]); + assert_eq!(t.fold_equity_scale, BASE.fold_equity_scale); + assert!(t.call_margin > BASE.call_margin); + assert!(t.range_width_scale < BASE.range_width_scale); +} + +#[test] +fn aggressive_players_are_called_wider() { + let t = adjust(BASE, &[maniac()]); + assert!(t.call_margin < BASE.call_margin); + assert!(t.range_width_scale > BASE.range_width_scale); +} + +#[test] +fn fold_to_bet_no_longer_moves_the_shared_scale() { + // foldToBet enters per opponent through `fold_chance`; counting it here too would + // count it twice. + for i in 0..=20 { + let t = adjust(BASE, &[profile(Some(0.3), Some(0.1), Some(i as f64 / 20.0))]); + assert_eq!(t.fold_equity_scale, BASE.fold_equity_scale); + } +} + +#[test] +fn several_profiles_combine_conservatively() { + let (s, n) = (adjust(BASE, &[station()]), adjust(BASE, &[nit()])); + let both = adjust(BASE, &[station(), nit()]); + assert_eq!(both.call_margin, s.call_margin.max(n.call_margin)); + assert_eq!( + both.fold_equity_scale, + s.fold_equity_scale.min(n.fold_equity_scale) + ); + assert_eq!(both.value_raise, s.value_raise.max(n.value_raise)); + assert_eq!( + both.range_width_scale, + s.range_width_scale.min(n.range_width_scale) + ); + // order does not matter, unknowns are ignored + assert_eq!(adjust(BASE, &[nit(), Profile::default(), station()]), both); +} + +#[test] +fn outputs_stay_in_sane_ranges_for_any_input() { + let grid = [ + None, + Some(-1.0), + Some(0.0), + Some(0.3), + Some(1.0), + Some(9.0), + Some(f64::NAN), + Some(f64::INFINITY), + ]; + for vpip in grid { + for pfr in grid { + for ftb in grid { + let t = adjust(BASE, &[profile(vpip, pfr, ftb)]); + assert!((0.0..=0.15).contains(&t.call_margin), "{t:?}"); + assert!((0.52..=0.85).contains(&t.value_raise), "{t:?}"); + assert!((0.0..=0.05).contains(&t.abstain_band), "{t:?}"); + assert!((0.3..=1.6).contains(&t.fold_equity_scale), "{t:?}"); + assert!((0.6..=1.4).contains(&t.range_width_scale), "{t:?}"); + } + } + } +} + +#[test] +fn adjust_is_pure() { + let ps = [station(), maniac()]; + assert_eq!(adjust(BASE, &ps), adjust(BASE, &ps)); +} + +#[test] +fn adjustments_compose_with_a_non_default_base() { + let tight = Thresholds { + fold_equity_scale: 0.8, + ..BASE + }; + // The shared fold-equity scale passes through untouched (profiles act per opponent). + assert_eq!(adjust(tight, &[nit()]).fold_equity_scale, 0.8); + assert_eq!(adjust(tight, &[station()]).fold_equity_scale, 0.8); +} diff --git a/tests/exploit_range_guess.rs b/tests/exploit_range_guess.rs index 80450e1d..3e8844ab 100644 --- a/tests/exploit_range_guess.rs +++ b/tests/exploit_range_guess.rs @@ -154,6 +154,7 @@ fn sticky_players_hold_wider_ranges_than_foldy_ones() { vpip: Some(0.3), pfr: None, fold_to_bet: Some(ftb), + aggression: None, }) }; assert!( diff --git a/tests/exploit_style.rs b/tests/exploit_style.rs index ec566a37..929c4d60 100644 --- a/tests/exploit_style.rs +++ b/tests/exploit_style.rs @@ -6,6 +6,7 @@ fn profile(vpip: Option, pfr: Option, fold_to_bet: Option) -> Pro vpip, pfr, fold_to_bet, + aggression: None, } } diff --git a/tests/pipeline_bluff.rs b/tests/pipeline_bluff.rs new file mode 100644 index 00000000..4df6671e --- /dev/null +++ b/tests/pipeline_bluff.rs @@ -0,0 +1,145 @@ +//! End-to-end spec for bluffing and bluff catching, steered by opponent frequencies. + +mod support; + +use pokerfreak::wire::respond::respond; +use support::{action, board_json, cards_json, field, short}; + +const NIT: &str = r#","profile":{"vpip":0.11,"pfr":0.08,"foldToBet":0.8,"aggression":0.15}"#; +const STATION: &str = r#","profile":{"vpip":0.55,"pfr":0.05,"foldToBet":0.15,"aggression":0.2}"#; +const MANIAC: &str = r#","profile":{"vpip":0.55,"pfr":0.35,"foldToBet":0.35,"aggression":0.8}"#; +const NEVER_FOLDS: &str = r#","profile":{"foldToBet":0.05}"#; + +fn reason(out: &str) -> String { + field(out, "reason").unwrap_or("").to_string() +} + +/// Heads-up river, checked to hero (button, seat 6) by the villain in seat 1. +fn river_checked_to_hero(hero: &str, board: &str, profile: &str) -> String { + format!( + r#"{{"variant":"NLHE","bigBlind":1,"seats":6,"heroSeat":6,"buttonSeat":6,"heroCards":{},"board":{},"street":"RIVER","pot":20,"toCall":0,"heroStack":100,"minRaiseTo":1,"maxRaiseTo":100,"legalActions":["CHECK","RAISE"],"villains":[{{"seat":1,"stack":100,"folded":false{profile}}}]}}"#, + cards_json(&short(hero)), + board_json(&short(board)), + ) +} + +/// Hero (button) raised preflop, the small blind called, checked down to the river, +/// where the small blind bets the pot (6 into 6). +fn river_facing_a_pot_bet(hero: &str, board: &str, profile: &str) -> String { + let history = r#"[{"street":"PREFLOP","seat":1,"action":"POST_SB","amount":0.5},{"street":"PREFLOP","seat":2,"action":"POST_BB","amount":1},{"street":"PREFLOP","seat":6,"action":"RAISE","amount":2.5},{"street":"PREFLOP","seat":1,"action":"CALL","amount":2.5},{"street":"PREFLOP","seat":2,"action":"FOLD"},{"street":"FLOP","seat":1,"action":"CHECK"},{"street":"FLOP","seat":6,"action":"CHECK"},{"street":"TURN","seat":1,"action":"CHECK"},{"street":"TURN","seat":6,"action":"CHECK"},{"street":"RIVER","seat":1,"action":"BET","amount":6}]"#; + format!( + r#"{{"variant":"NLHE","bigBlind":1,"seats":6,"heroSeat":6,"buttonSeat":6,"heroCards":{},"board":{},"street":"RIVER","pot":12,"toCall":6,"heroStack":97.5,"minRaiseTo":12,"maxRaiseTo":97.5,"legalActions":["FOLD","CALL","RAISE"],"villains":[{{"seat":1,"stack":91.5,"folded":false{profile}}},{{"seat":2,"stack":99,"folded":true}}],"history":{history}}}"#, + cards_json(&short(hero)), + board_json(&short(board)), + ) +} + +/// Unopened pot, hero on the button, both blinds with the same profile. +fn steal(hero: &str, profile: &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{profile}}},{{"seat":2,"stack":100,"folded":false{profile}}}]}}"#, + cards_json(&short(hero)), + ) +} + +/// Air on the river: no pair, no made straight or flush. +const AIR: [(&str, &str); 6] = [ + ("6h 5h", "As Kd 9c 7s 2d"), + ("Qc Jc", "As 8d 5h 3s 2c"), + ("Th 9h", "Ac Kd 6s 4c 2d"), + ("7d 6d", "Kc Qs Jh 3c 2s"), + ("Jd Td", "As 8c 6h 4d 3s"), + ("8s 7s", "Ad Qc Th 4h 2c"), +]; + +fn bluffs(profile: &str) -> usize { + AIR.iter() + .filter(|(hero, board)| action(&respond(&river_checked_to_hero(hero, board, profile))) == "RAISE") + .count() +} + +// ---------- Bluffing ---------- + +#[test] +fn the_nit_gets_bluffed_with_air() { + let out = respond(&river_checked_to_hero("6h 5h", "As Kd 9c 7s 2d", NIT)); + assert_eq!(action(&out), "RAISE", "{out}"); + assert!(reason(&out).contains("bluff"), "{out}"); +} + +#[test] +fn the_calling_station_does_not() { + let out = respond(&river_checked_to_hero("6h 5h", "As Kd 9c 7s 2d", STATION)); + assert_eq!(action(&out), "CHECK", "{out}"); +} + +#[test] +fn fewer_bluffs_against_the_station_more_against_the_nit() { + let (nit, unknown, station) = (bluffs(NIT), bluffs(""), bluffs(STATION)); + assert!(nit > unknown || nit == AIR.len(), "nit {nit}, unknown {unknown}"); + assert!(unknown >= station, "unknown {unknown}, station {station}"); + assert_eq!(station, 0); + assert_eq!(nit, AIR.len()); +} + +#[test] +fn never_bluff_someone_who_never_folds() { + assert_eq!(bluffs(NEVER_FOLDS), 0); +} + +// ---------- Stealing ---------- + +#[test] +fn steal_wider_against_nits_in_the_blinds() { + // Q6o (percentile 0.45) is outside the neutral button open (top 42 %): + // folded against unknowns and stations, opened against two nits. + let hero = "Qd 6c"; + let nit = respond(&steal(hero, NIT)); + assert_eq!(action(&nit), "RAISE", "{nit}"); + assert!(["FOLD", "ABSTAIN"].contains(&action(&respond(&steal(hero, ""))).as_str())); + assert_eq!(action(&respond(&steal(hero, STATION))), "FOLD"); + // A hand inside the neutral range (K4o, 0.40) is no longer stolen against stations. + assert_eq!(action(&respond(&steal("Kd 4c", ""))), "RAISE"); + assert_eq!(action(&respond(&steal("Kd 4c", STATION))), "FOLD"); +} + +// ---------- Bluff catching ---------- + +#[test] +fn a_bluff_catcher_calls_the_maniac() { + let out = respond(&river_facing_a_pot_bet("Qh 9h", "Ks 9d 4c 2s 7h", MANIAC)); + assert_eq!(action(&out), "CALL", "{out}"); +} + +#[test] +fn the_same_bluff_catcher_folds_to_the_nit() { + let out = respond(&river_facing_a_pot_bet("Qh 9h", "Ks 9d 4c 2s 7h", NIT)); + assert!(["FOLD", "ABSTAIN"].contains(&action(&out).as_str()), "{out}"); +} + +#[test] +fn no_bluff_catch_against_a_range_without_bluffs() { + let honest = r#","profile":{"vpip":0.25,"pfr":0.18,"foldToBet":0.5,"aggression":0.0}"#; + let out = respond(&river_facing_a_pot_bet("Qh 9h", "Ks 9d 4c 2s 7h", honest)); + assert!(["FOLD", "ABSTAIN"].contains(&action(&out).as_str()), "{out}"); +} + +#[test] +fn a_value_hand_still_calls_or_raises_the_nit() { + let out = respond(&river_facing_a_pot_bet("Kh Kc", "Ks 9d 4c 2s 7h", NIT)); + assert!(["CALL", "RAISE"].contains(&action(&out).as_str()), "{out}"); +} + +// ---------- Semibluffs first ---------- + +#[test] +fn draws_raise_as_semibluffs_not_as_pure_bluffs() { + let line = format!( + r#"{{"variant":"NLHE","bigBlind":1,"seats":6,"heroSeat":6,"buttonSeat":6,"heroCards":{},"board":{},"street":"FLOP","pot":10,"toCall":0,"heroStack":100,"minRaiseTo":1,"maxRaiseTo":100,"legalActions":["CHECK","RAISE"],"villains":[{{"seat":1,"stack":100,"folded":false{NIT}}}]}}"#, + cards_json(&short("8h 7h")), + board_json(&short("Kh 4h 2c")), + ); + let out = respond(&line); + assert_eq!(action(&out), "RAISE", "{out}"); + assert!(reason(&out).contains("semibluff"), "{out}"); +} diff --git a/tests/pipeline_postflop_v2.rs b/tests/pipeline_postflop_v2.rs index be76a360..ba96996a 100644 --- a/tests/pipeline_postflop_v2.rs +++ b/tests/pipeline_postflop_v2.rs @@ -1,209 +1,216 @@ -//! End-to-end spec for the postflop upgrade, short deck and position inference. - -mod support; - -use pokerfreak::wire::respond::respond; -use support::{action, board_json, cards_json, confidence, field, short, size}; - -struct Request<'a> { - variant: &'a str, - hero: &'a str, - board: &'a str, - street: &'a str, - pot: f64, - to_call: f64, - legal: &'a str, - villains: usize, - extra: &'a str, -} - -impl Request<'_> { - fn line(&self) -> String { - let villains: Vec = (0..self.villains) - .map(|i| format!(r#"{{"seat":{},"stack":40.0,"folded":false}}"#, i + 1)) - .collect(); - format!( - r#"{{"variant":"{}","bigBlind":1,"seats":6,"heroSeat":6,"buttonSeat":6,"heroCards":{},"board":{},"street":"{}","pot":{},"toCall":{},"heroStack":40,"minRaiseTo":{},"maxRaiseTo":40,"legalActions":{},"villains":[{}]{}}}"#, - self.variant, - cards_json(&short(self.hero)), - board_json(&short(self.board)), - self.street, - self.pot, - self.to_call, - (self.to_call * 2.0).max(1.0), - self.legal, - villains.join(","), - self.extra, - ) - } -} - -fn base() -> Request<'static> { - Request { - variant: "NLHE", - hero: "Ah Kd", - board: "Ks 7c 2d", - street: "FLOP", - pot: 10.0, - to_call: 0.0, - legal: r#"["CHECK","RAISE"]"#, - villains: 1, - extra: "", - } -} - -fn reason(out: &str) -> String { - field(out, "reason").unwrap_or("").to_string() -} - -// ---------- Short deck ---------- - -#[test] -fn short_deck_and_its_alias_are_accepted() { - for name in ["SHORT_DECK", "6+"] { - let out = respond(&Request { variant: name, hero: "Ah Ad", board: "As 9c 7d", ..base() }.line()); - assert_ne!(action(&out), "ABSTAIN", "{name}: {out}"); - } -} - -#[test] -fn short_deck_rejects_cards_below_six() { - let out = respond(&Request { variant: "SHORT_DECK", hero: "5h 5d", board: "As 9c 7d", ..base() }.line()); - assert_eq!(action(&out), "ABSTAIN", "{out}"); - assert_eq!(confidence(&out), 0.0); -} - -#[test] -fn short_deck_flush_is_played_as_a_monster_over_a_full_house_draw() { - // Hero holds the made flush; in short deck a flush beats a full house, so a - // villain's set that fills up is still behind — the flush must bet. - let out = respond( - &Request { variant: "SHORT_DECK", hero: "Ah 9h", board: "Kh 8h 6h 8c", street: "TURN", ..base() } - .line(), - ); - assert_eq!(action(&out), "RAISE", "{out}"); -} - -#[test] -fn short_deck_respects_allowed_sizes() { - let out = respond( - &Request { - variant: "SHORT_DECK", - hero: "Ah Ad", - board: "As 9c 7d", - extra: r#","allowedSizes":[3.5,7.25]"#, - ..base() - } - .line(), - ); - if action(&out) == "RAISE" { - let s = size(&out).unwrap(); - assert!(s == 3.5 || s == 7.25, "{out}"); - } -} - -// ---------- Action history ---------- - -#[test] -fn malformed_history_abstains_with_its_path() { - let out = respond( - &Request { extra: r#","history":[{"street":"FLOP","seat":1,"action":"DANCE"}]"#, ..base() }.line(), - ); - assert_eq!(action(&out), "ABSTAIN", "{out}"); - assert!(reason(&out).contains("history[0]"), "{out}"); -} - -#[test] -fn preflop_raiser_betting_flop_and_turn_narrows_range_so_middle_pair_gives_up() { - // Hero 9-9 on K-7-2-4 facing a turn bet from a player who raised preflop and bet both streets. - let history = r#","history":[{"street":"PREFLOP","seat":1,"action":"RAISE","amount":3},{"street":"PREFLOP","seat":6,"action":"CALL","amount":3},{"street":"FLOP","seat":1,"action":"BET","amount":5},{"street":"FLOP","seat":6,"action":"CALL","amount":5},{"street":"TURN","seat":1,"action":"BET","amount":14}]"#; - let narrowed = respond( - &Request { - hero: "9h 9c", - board: "Ks 7c 2d 4h", - street: "TURN", - pot: 30.0, - to_call: 14.0, - legal: r#"["FOLD","CALL","RAISE"]"#, - extra: history, - ..base() - } - .line(), - ); - assert!(["FOLD", "ABSTAIN"].contains(&action(&narrowed).as_str()), "{narrowed}"); -} - -#[test] -fn position_is_derived_from_history_when_button_is_missing() { - let line = format!( - r#"{{"variant":"NLHE","bigBlind":1,"seats":6,"heroSeat":4,"heroCards":{},"street":"PREFLOP","pot":1.5,"toCall":1,"heroStack":100,"minRaiseTo":2,"maxRaiseTo":100,"legalActions":["FOLD","CALL","RAISE"],"villains":[{{"seat":2,"stack":100,"folded":false}},{{"seat":3,"stack":100,"folded":false}}],"history":[{{"street":"PREFLOP","seat":2,"action":"POST_SB","amount":0.5}},{{"street":"PREFLOP","seat":3,"action":"POST_BB","amount":1}}]}}"#, - cards_json(&short("Ah Kh")) - ); - let out = respond(&line); - assert!(!reason(&out).contains("pos?"), "{out}"); -} - -// ---------- Multiway and semibluff ---------- - -#[test] -fn top_pair_continues_heads_up_but_folds_four_way() { - let spot = |villains| Request { - hero: "Qh Jd", - board: "Qs 8c 3d", - pot: 12.0, - to_call: 6.0, - legal: r#"["FOLD","CALL","RAISE"]"#, - villains, - ..base() - }; - let heads_up = respond(&spot(1).line()); - let four_way = respond(&spot(4).line()); - // Heads-up top pair continues (call or value raise); four-way the same price is a fold. - assert!(["CALL", "RAISE"].contains(&action(&heads_up).as_str()), "{heads_up}"); - assert!(["FOLD", "ABSTAIN"].contains(&action(&four_way).as_str()), "{four_way}"); -} - -#[test] -fn reasons_name_the_hand_read() { - let out = respond(&base().line()); - let text = reason(&out).to_lowercase(); - assert!(text.contains("top pair"), "{out}"); -} - -#[test] -fn no_semibluff_on_the_river() { - let out = respond( - &Request { - hero: "Jh Th", - board: "9h 8h 2c 3d Ks", - street: "RIVER", - legal: r#"["CHECK","RAISE"]"#, - ..base() - } - .line(), - ); - assert_eq!(action(&out), "CHECK", "missed draw on the river: {out}"); -} - -#[test] -fn uncertain_abstain_carries_small_but_positive_confidence() { - // Scan pot sizes around the breakpoint; any uncertainty ABSTAIN must have 0 < c <= 0.3. - (1..40).for_each(|i| { - let to_call = i as f64 * 0.5; - let out = respond( - &Request { - hero: "Ad 5c", - board: "Ks 9c 4h", - pot: 10.0, - to_call, - legal: r#"["FOLD","CALL"]"#, - ..base() - } - .line(), - ); - if action(&out) == "ABSTAIN" && reason(&out).contains("uncertain") { - let c = confidence(&out); - assert!(c > 0.0 && c <= 0.3, "{out}"); - } - }); -} +//! End-to-end spec for the postflop upgrade, short deck and position inference. + +mod support; + +use pokerfreak::wire::respond::respond; +use support::{action, board_json, cards_json, confidence, field, short, size}; + +struct Request<'a> { + variant: &'a str, + hero: &'a str, + board: &'a str, + street: &'a str, + pot: f64, + to_call: f64, + legal: &'a str, + villains: usize, + extra: &'a str, +} + +impl Request<'_> { + fn line(&self) -> String { + let villains: Vec = (0..self.villains) + .map(|i| format!(r#"{{"seat":{},"stack":40.0,"folded":false}}"#, i + 1)) + .collect(); + format!( + r#"{{"variant":"{}","bigBlind":1,"seats":6,"heroSeat":6,"buttonSeat":6,"heroCards":{},"board":{},"street":"{}","pot":{},"toCall":{},"heroStack":40,"minRaiseTo":{},"maxRaiseTo":40,"legalActions":{},"villains":[{}]{}}}"#, + self.variant, + cards_json(&short(self.hero)), + board_json(&short(self.board)), + self.street, + self.pot, + self.to_call, + (self.to_call * 2.0).max(1.0), + self.legal, + villains.join(","), + self.extra, + ) + } +} + +fn base() -> Request<'static> { + Request { + variant: "NLHE", + hero: "Ah Kd", + board: "Ks 7c 2d", + street: "FLOP", + pot: 10.0, + to_call: 0.0, + legal: r#"["CHECK","RAISE"]"#, + villains: 1, + extra: "", + } +} + +fn reason(out: &str) -> String { + field(out, "reason").unwrap_or("").to_string() +} + +// ---------- Short deck ---------- + +#[test] +fn short_deck_and_its_alias_are_accepted() { + for name in ["SHORT_DECK", "6+"] { + let out = respond(&Request { variant: name, hero: "Ah Ad", board: "As 9c 7d", ..base() }.line()); + assert_ne!(action(&out), "ABSTAIN", "{name}: {out}"); + } +} + +#[test] +fn short_deck_rejects_cards_below_six() { + let out = respond(&Request { variant: "SHORT_DECK", hero: "5h 5d", board: "As 9c 7d", ..base() }.line()); + assert_eq!(action(&out), "ABSTAIN", "{out}"); + assert_eq!(confidence(&out), 0.0); +} + +#[test] +fn short_deck_flush_is_played_as_a_monster_over_a_full_house_draw() { + // Hero holds the made flush; in short deck a flush beats a full house, so a + // villain's set that fills up is still behind — the flush must bet. + let out = respond( + &Request { variant: "SHORT_DECK", hero: "Ah 9h", board: "Kh 8h 6h 8c", street: "TURN", ..base() } + .line(), + ); + assert_eq!(action(&out), "RAISE", "{out}"); +} + +#[test] +fn short_deck_respects_allowed_sizes() { + let out = respond( + &Request { + variant: "SHORT_DECK", + hero: "Ah Ad", + board: "As 9c 7d", + extra: r#","allowedSizes":[3.5,7.25]"#, + ..base() + } + .line(), + ); + if action(&out) == "RAISE" { + let s = size(&out).unwrap(); + assert!(s == 3.5 || s == 7.25, "{out}"); + } +} + +// ---------- Action history ---------- + +#[test] +fn malformed_history_abstains_with_its_path() { + let out = respond( + &Request { extra: r#","history":[{"street":"FLOP","seat":1,"action":"DANCE"}]"#, ..base() }.line(), + ); + assert_eq!(action(&out), "ABSTAIN", "{out}"); + assert!(reason(&out).contains("history[0]"), "{out}"); +} + +#[test] +fn preflop_raiser_betting_flop_and_turn_narrows_range_so_middle_pair_gives_up() { + // Hero 9-9 on K-7-2-4 facing a turn bet from a player who raised preflop and bet both streets. + let history = r#","history":[{"street":"PREFLOP","seat":1,"action":"RAISE","amount":3},{"street":"PREFLOP","seat":6,"action":"CALL","amount":3},{"street":"FLOP","seat":1,"action":"BET","amount":5},{"street":"FLOP","seat":6,"action":"CALL","amount":5},{"street":"TURN","seat":1,"action":"BET","amount":14}]"#; + let narrowed = respond( + &Request { + hero: "9h 9c", + board: "Ks 7c 2d 4h", + street: "TURN", + pot: 30.0, + to_call: 14.0, + legal: r#"["FOLD","CALL","RAISE"]"#, + extra: history, + ..base() + } + .line(), + ); + assert!(["FOLD", "ABSTAIN"].contains(&action(&narrowed).as_str()), "{narrowed}"); +} + +#[test] +fn position_is_derived_from_history_when_button_is_missing() { + let line = format!( + r#"{{"variant":"NLHE","bigBlind":1,"seats":6,"heroSeat":4,"heroCards":{},"street":"PREFLOP","pot":1.5,"toCall":1,"heroStack":100,"minRaiseTo":2,"maxRaiseTo":100,"legalActions":["FOLD","CALL","RAISE"],"villains":[{{"seat":2,"stack":100,"folded":false}},{{"seat":3,"stack":100,"folded":false}}],"history":[{{"street":"PREFLOP","seat":2,"action":"POST_SB","amount":0.5}},{{"street":"PREFLOP","seat":3,"action":"POST_BB","amount":1}}]}}"#, + cards_json(&short("Ah Kh")) + ); + let out = respond(&line); + assert!(!reason(&out).contains("pos?"), "{out}"); +} + +// ---------- Multiway and semibluff ---------- + +#[test] +fn top_pair_continues_heads_up_but_folds_four_way() { + let spot = |villains| Request { + hero: "Qh Jd", + board: "Qs 8c 3d", + pot: 12.0, + to_call: 6.0, + legal: r#"["FOLD","CALL","RAISE"]"#, + villains, + ..base() + }; + let heads_up = respond(&spot(1).line()); + let four_way = respond(&spot(4).line()); + // Heads-up top pair continues (call or value raise); four-way the same price is a fold. + assert!(["CALL", "RAISE"].contains(&action(&heads_up).as_str()), "{heads_up}"); + assert!(["FOLD", "ABSTAIN"].contains(&action(&four_way).as_str()), "{four_way}"); +} + +#[test] +fn reasons_name_the_hand_read() { + let out = respond(&base().line()); + let text = reason(&out).to_lowercase(); + assert!(text.contains("top pair"), "{out}"); +} + +#[test] +fn no_semibluff_on_the_river() { + let river = Request { + hero: "Jh Th", + board: "9h 8h 2c 3d Ks", + street: "RIVER", + legal: r#"["CHECK","RAISE"]"#, + ..base() + } + .line(); + // A missed draw has no cards to come: it is never a semibluff. Against an unknown + // opponent it may still be a pure bluff (pipeline_bluff), against a station it checks. + let unknown = respond(&river); + assert!(!reason(&unknown).contains("semibluff"), "{unknown}"); + assert!(action(&unknown) == "CHECK" || reason(&unknown).contains("bluff raise"), "{unknown}"); + let station = respond(&river.replace( + r#""folded":false}"#, + r#""folded":false,"profile":{"vpip":0.55,"pfr":0.05,"foldToBet":0.15}}"#, + )); + assert_eq!(action(&station), "CHECK", "missed draw on the river: {station}"); +} + +#[test] +fn uncertain_abstain_carries_small_but_positive_confidence() { + // Scan pot sizes around the breakpoint; any uncertainty ABSTAIN must have 0 < c <= 0.3. + (1..40).for_each(|i| { + let to_call = i as f64 * 0.5; + let out = respond( + &Request { + hero: "Ad 5c", + board: "Ks 9c 4h", + pot: 10.0, + to_call, + legal: r#"["FOLD","CALL"]"#, + ..base() + } + .line(), + ); + if action(&out) == "ABSTAIN" && reason(&out).contains("uncertain") { + let c = confidence(&out); + assert!(c > 0.0 && c <= 0.3, "{out}"); + } + }); +} diff --git a/tests/range_model_fixture/mod.rs b/tests/range_model_fixture/mod.rs index 4fe6b937..f7d40e6d 100644 --- a/tests/range_model_fixture/mod.rs +++ b/tests/range_model_fixture/mod.rs @@ -1,114 +1,114 @@ -#![allow(dead_code)] -//! Builders for range-model tests. Table: 6 seats, 0-based, button on seat 3: -//! seat 3 BTN, 4 SB, 5 BB, 0 UTG (early), 1 MP (middle), 2 CO. Hero sits on seat 0. - -use pokerfreak::card::Card; -use pokerfreak::exploit::profile::Profile; -use pokerfreak::exploit::range_spec::{Continuation, RangeSpec}; -use pokerfreak::game::{ActionKind, ActionRecord, SeenAction, Spot, Street, Villain}; -use pokerfreak::variant::Variant; - -pub const HERO: u8 = 0; -pub const MIDDLE: u8 = 1; -pub const CUTOFF: u8 = 2; -pub const BUTTON: u8 = 3; -pub const SMALL_BLIND: u8 = 4; -pub const BIG_BLIND: u8 = 5; - -pub fn at(street: Street, seat: u8, action: SeenAction, amount: Option) -> ActionRecord { - ActionRecord { street, seat, action, amount } -} - -pub fn pre(seat: u8, action: SeenAction) -> ActionRecord { - at(Street::Preflop, seat, action, None) -} - -pub fn pre_amt(seat: u8, action: SeenAction, amount: f64) -> ActionRecord { - at(Street::Preflop, seat, action, Some(amount)) -} - -pub fn post(street: Street, seat: u8, action: SeenAction) -> ActionRecord { - at(street, seat, action, None) -} - -pub fn blinds() -> Vec { - vec![pre_amt(4, SeenAction::PostSmallBlind, 0.5), pre_amt(5, SeenAction::PostBigBlind, 1.0)] -} - -/// Blinds followed by `rest`. -pub fn hand(rest: Vec) -> Vec { - [blinds(), rest].concat() -} - -pub fn villain(seat: u8, profile: Option) -> Villain { - Villain { seat, stack: 100.0, folded: false, profile } -} - -pub fn profile(vpip: Option, pfr: Option, fold: Option) -> Option { - Some(Profile { vpip, pfr, fold_to_bet: fold }) -} - -pub fn vpip(value: f64) -> Option { - profile(Some(value), None, None) -} - -pub fn board_of(len: usize) -> Vec { - Card::parse_list(&"Kc 7d 2s 9h 4c"[..len * 3 - usize::from(len > 0)]).unwrap() -} - -fn street_of(len: usize) -> Street { - match len { - 0 => Street::Preflop, - 3 => Street::Flop, - 4 => Street::Turn, - _ => Street::River, - } -} - -/// A spot on the street matching `board_len` with the given history; villains: all but hero. -pub fn spot(board_len: usize, history: Vec, profile: Option) -> Spot { - Spot { - variant: Variant::Nlhe, - big_blind: 1.0, - seats: 6, - hero_seat: HERO, - button_seat: Some(3), - hero_cards: Card::parse_list("Ah Qd").unwrap(), - board: if board_len == 0 { vec![] } else { board_of(board_len) }, - street: street_of(board_len), - pot: 10.0, - to_call: 0.0, - hero_stack: 100.0, - min_raise_to: None, - max_raise_to: None, - legal: vec![ActionKind::Check, ActionKind::Raise], - allowed_sizes: None, - villains: [1u8, 2, 3, 4, 5].iter().map(|s| villain(*s, profile)).collect(), - seed: 1, - history, - } -} - -pub fn spec(spot: &Spot, seat: u8) -> RangeSpec { - let v = spot.villains.iter().find(|v| v.seat == seat).cloned().unwrap_or(villain(seat, None)); - pokerfreak::exploit::range_model::range_spec(spot, &v) -} - -pub fn width(s: &RangeSpec) -> f64 { - s.hi - s.lo -} - -pub fn well_formed(s: &RangeSpec, board_len: usize) -> bool { - let sorted = s.continues.windows(2).all(|w| w[0].board_len < w[1].board_len); - s.lo.is_finite() - && s.hi.is_finite() - && s.lo >= 0.0 - && s.hi <= 1.0 - && s.hi - s.lo >= 0.03 - 1e-12 - && sorted - && s.continues.iter().all(|c: &Continuation| (3..=5).contains(&c.board_len) && c.board_len <= board_len) -} - -pub fn continuation(s: &RangeSpec, board_len: usize) -> Option { - s.continues.iter().find(|c| c.board_len == board_len).copied() -} +#![allow(dead_code)] +//! Builders for range-model tests. Table: 6 seats, 0-based, button on seat 3: +//! seat 3 BTN, 4 SB, 5 BB, 0 UTG (early), 1 MP (middle), 2 CO. Hero sits on seat 0. + +use pokerfreak::card::Card; +use pokerfreak::exploit::profile::Profile; +use pokerfreak::exploit::range_spec::{Continuation, RangeSpec}; +use pokerfreak::game::{ActionKind, ActionRecord, SeenAction, Spot, Street, Villain}; +use pokerfreak::variant::Variant; + +pub const HERO: u8 = 0; +pub const MIDDLE: u8 = 1; +pub const CUTOFF: u8 = 2; +pub const BUTTON: u8 = 3; +pub const SMALL_BLIND: u8 = 4; +pub const BIG_BLIND: u8 = 5; + +pub fn at(street: Street, seat: u8, action: SeenAction, amount: Option) -> ActionRecord { + ActionRecord { street, seat, action, amount } +} + +pub fn pre(seat: u8, action: SeenAction) -> ActionRecord { + at(Street::Preflop, seat, action, None) +} + +pub fn pre_amt(seat: u8, action: SeenAction, amount: f64) -> ActionRecord { + at(Street::Preflop, seat, action, Some(amount)) +} + +pub fn post(street: Street, seat: u8, action: SeenAction) -> ActionRecord { + at(street, seat, action, None) +} + +pub fn blinds() -> Vec { + vec![pre_amt(4, SeenAction::PostSmallBlind, 0.5), pre_amt(5, SeenAction::PostBigBlind, 1.0)] +} + +/// Blinds followed by `rest`. +pub fn hand(rest: Vec) -> Vec { + [blinds(), rest].concat() +} + +pub fn villain(seat: u8, profile: Option) -> Villain { + Villain { seat, stack: 100.0, folded: false, profile } +} + +pub fn profile(vpip: Option, pfr: Option, fold: Option) -> Option { + Some(Profile { vpip, pfr, fold_to_bet: fold, aggression: None }) +} + +pub fn vpip(value: f64) -> Option { + profile(Some(value), None, None) +} + +pub fn board_of(len: usize) -> Vec { + Card::parse_list(&"Kc 7d 2s 9h 4c"[..len * 3 - usize::from(len > 0)]).unwrap() +} + +fn street_of(len: usize) -> Street { + match len { + 0 => Street::Preflop, + 3 => Street::Flop, + 4 => Street::Turn, + _ => Street::River, + } +} + +/// A spot on the street matching `board_len` with the given history; villains: all but hero. +pub fn spot(board_len: usize, history: Vec, profile: Option) -> Spot { + Spot { + variant: Variant::Nlhe, + big_blind: 1.0, + seats: 6, + hero_seat: HERO, + button_seat: Some(3), + hero_cards: Card::parse_list("Ah Qd").unwrap(), + board: if board_len == 0 { vec![] } else { board_of(board_len) }, + street: street_of(board_len), + pot: 10.0, + to_call: 0.0, + hero_stack: 100.0, + min_raise_to: None, + max_raise_to: None, + legal: vec![ActionKind::Check, ActionKind::Raise], + allowed_sizes: None, + villains: [1u8, 2, 3, 4, 5].iter().map(|s| villain(*s, profile)).collect(), + seed: 1, + history, + } +} + +pub fn spec(spot: &Spot, seat: u8) -> RangeSpec { + let v = spot.villains.iter().find(|v| v.seat == seat).cloned().unwrap_or(villain(seat, None)); + pokerfreak::exploit::range_model::range_spec(spot, &v) +} + +pub fn width(s: &RangeSpec) -> f64 { + s.hi - s.lo +} + +pub fn well_formed(s: &RangeSpec, board_len: usize) -> bool { + let sorted = s.continues.windows(2).all(|w| w[0].board_len < w[1].board_len); + s.lo.is_finite() + && s.hi.is_finite() + && s.lo >= 0.0 + && s.hi <= 1.0 + && s.hi - s.lo >= 0.03 - 1e-12 + && sorted + && s.continues.iter().all(|c: &Continuation| (3..=5).contains(&c.board_len) && c.board_len <= board_len) +} + +pub fn continuation(s: &RangeSpec, board_len: usize) -> Option { + s.continues.iter().find(|c| c.board_len == board_len).copied() +} diff --git a/tests/range_model_robust.rs b/tests/range_model_robust.rs index 8690056c..7bcc2cb3 100644 --- a/tests/range_model_robust.rs +++ b/tests/range_model_robust.rs @@ -1,156 +1,156 @@ -mod range_model_fixture; - -use pokerfreak::exploit::profile::Profile; -use pokerfreak::exploit::range_model::range_spec; -use pokerfreak::game::{ActionRecord, SeenAction, Street, Villain}; -use pokerfreak::rng::Rng; -use range_model_fixture::*; - -const FLOP: Street = Street::Flop; - -#[test] -fn unknown_seats_are_ignored() { - let s = spot( - 3, - hand(vec![pre(99, SeenAction::Raise), post(FLOP, 77, SeenAction::Bet)]), - None, - ); - for seat in [1u8, 2, 3, 99, 200] { - assert!(well_formed(&spec(&s, seat), 3)); - } -} - -#[test] -fn actions_out_of_order_stay_well_formed() { - let history = vec![ - post(FLOP, CUTOFF, SeenAction::Bet), - pre(CUTOFF, SeenAction::Raise), - post(Street::River, CUTOFF, SeenAction::Raise), - pre(CUTOFF, SeenAction::Fold), - pre(CUTOFF, SeenAction::PostBigBlind), - post(Street::Turn, CUTOFF, SeenAction::Call), - pre(CUTOFF, SeenAction::Check), - ]; - for len in [0usize, 3, 4, 5] { - let s = spot(len, history.clone(), None); - assert!(well_formed(&spec(&s, CUTOFF), len), "board {len}"); - } -} - -#[test] -fn board_and_street_that_disagree_stay_well_formed() { - let mut s = spot(3, hand(vec![post(FLOP, CUTOFF, SeenAction::Bet)]), None); - s.board.clear(); // flop street, no board cards - let r = spec(&s, CUTOFF); - assert!(well_formed(&r, 0)); - assert!(r.continues.is_empty()); -} - -#[test] -fn hero_and_duplicate_blinds_are_harmless() { - let history = vec![ - pre(HERO, SeenAction::PostBigBlind), - pre(HERO, SeenAction::PostSmallBlind), - pre(BIG_BLIND, SeenAction::PostBigBlind), - pre(BIG_BLIND, SeenAction::PostBigBlind), - ]; - let s = spot(0, history, None); - for seat in 0u8..8 { - assert!(well_formed(&spec(&s, seat), 0)); - } -} - -#[test] -fn nonsense_amounts_and_table_sizes_stay_well_formed() { - for amount in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -5.0, 0.0, 1e300] { - for seats in [0u8, 1, 2, 11, 255] { - let history = vec![ - at(Street::Preflop, CUTOFF, SeenAction::PostBigBlind, Some(amount)), - at(Street::Preflop, MIDDLE, SeenAction::Raise, Some(amount)), - at(Street::Preflop, CUTOFF, SeenAction::Call, Some(amount)), - at(FLOP, CUTOFF, SeenAction::Bet, Some(amount)), - at(FLOP, MIDDLE, SeenAction::Raise, Some(amount)), - at(FLOP, CUTOFF, SeenAction::Call, Some(amount)), - ]; - let mut s = spot(3, history, None); - s.seats = seats; - s.big_blind = amount; - s.pot = amount; - for seat in [MIDDLE, CUTOFF] { - assert!(well_formed(&spec(&s, seat), 3), "amount {amount} seats {seats}"); - } - } - } -} - -fn pick(rng: Rng, items: &[T]) -> (T, Rng) { - let (i, rng) = rng.below(items.len() as u64); - (items[i as usize], rng) -} - -fn random_record(rng: Rng) -> (ActionRecord, Rng) { - let (street, rng) = pick(rng, &Street::ALL); - let (seat, rng) = rng.below(12); - let (action, rng) = pick(rng, &SeenAction::ALL); - let (present, rng) = rng.below(4); - let (unit, rng) = rng.unit(); - let (odd, rng) = rng.below(20); - let amount = match (present, odd) { - (0, _) => None, - (_, 0) => Some(f64::NAN), - (_, 1) => Some(-unit), - _ => Some(unit * 60.0), - }; - (ActionRecord { street, seat: seat as u8, action, amount }, rng) -} - -fn random_frequency(rng: Rng) -> (Option, Rng) { - let (kind, rng) = rng.below(8); - let (unit, rng) = rng.unit(); - let value = match kind { - 0 | 1 => None, - 2 => Some(f64::NAN), - 3 => Some(unit * 3.0 - 1.0), - _ => Some(unit), - }; - (value, rng) -} - -#[test] -fn property_random_histories_always_give_a_well_formed_spec() { - let mut rng = Rng::seeded(0xBADC0FFEE); - for case in 0..4000 { - let (len, r) = rng.below(12); - rng = r; - let mut history = Vec::new(); - for _ in 0..len { - let (rec, r) = random_record(rng); - rng = r; - history.push(rec); - } - let (board, r) = pick(rng, &[0usize, 3, 4, 5]); - rng = r; - let (vpip, r) = random_frequency(rng); - let (pfr, r) = random_frequency(r); - let (fold, r) = random_frequency(r); - rng = r; - let (seats, r) = rng.below(13); - rng = r; - let (button, r) = rng.below(14); - rng = r; - let (seat, r) = rng.below(12); - rng = r; - let mut s = spot(board, history, Some(Profile { vpip, pfr, fold_to_bet: fold })); - s.seats = seats as u8; - s.button_seat = if button == 13 { None } else { Some(button as u8) }; - let v = Villain { seat: seat as u8, stack: 50.0, folded: false, profile: s.villains[0].profile }; - let r = range_spec(&s, &v); - assert!(well_formed(&r, board), "case {case}: {r:?} for {s:?}"); - } -} - -#[test] -fn property_spec_is_deterministic() { - let s = spot(4, hand(vec![pre(CUTOFF, SeenAction::Raise), post(Street::Turn, CUTOFF, SeenAction::Bet)]), None); - assert_eq!(spec(&s, CUTOFF), spec(&s, CUTOFF)); -} +mod range_model_fixture; + +use pokerfreak::exploit::profile::Profile; +use pokerfreak::exploit::range_model::range_spec; +use pokerfreak::game::{ActionRecord, SeenAction, Street, Villain}; +use pokerfreak::rng::Rng; +use range_model_fixture::*; + +const FLOP: Street = Street::Flop; + +#[test] +fn unknown_seats_are_ignored() { + let s = spot( + 3, + hand(vec![pre(99, SeenAction::Raise), post(FLOP, 77, SeenAction::Bet)]), + None, + ); + for seat in [1u8, 2, 3, 99, 200] { + assert!(well_formed(&spec(&s, seat), 3)); + } +} + +#[test] +fn actions_out_of_order_stay_well_formed() { + let history = vec![ + post(FLOP, CUTOFF, SeenAction::Bet), + pre(CUTOFF, SeenAction::Raise), + post(Street::River, CUTOFF, SeenAction::Raise), + pre(CUTOFF, SeenAction::Fold), + pre(CUTOFF, SeenAction::PostBigBlind), + post(Street::Turn, CUTOFF, SeenAction::Call), + pre(CUTOFF, SeenAction::Check), + ]; + for len in [0usize, 3, 4, 5] { + let s = spot(len, history.clone(), None); + assert!(well_formed(&spec(&s, CUTOFF), len), "board {len}"); + } +} + +#[test] +fn board_and_street_that_disagree_stay_well_formed() { + let mut s = spot(3, hand(vec![post(FLOP, CUTOFF, SeenAction::Bet)]), None); + s.board.clear(); // flop street, no board cards + let r = spec(&s, CUTOFF); + assert!(well_formed(&r, 0)); + assert!(r.continues.is_empty()); +} + +#[test] +fn hero_and_duplicate_blinds_are_harmless() { + let history = vec![ + pre(HERO, SeenAction::PostBigBlind), + pre(HERO, SeenAction::PostSmallBlind), + pre(BIG_BLIND, SeenAction::PostBigBlind), + pre(BIG_BLIND, SeenAction::PostBigBlind), + ]; + let s = spot(0, history, None); + for seat in 0u8..8 { + assert!(well_formed(&spec(&s, seat), 0)); + } +} + +#[test] +fn nonsense_amounts_and_table_sizes_stay_well_formed() { + for amount in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -5.0, 0.0, 1e300] { + for seats in [0u8, 1, 2, 11, 255] { + let history = vec![ + at(Street::Preflop, CUTOFF, SeenAction::PostBigBlind, Some(amount)), + at(Street::Preflop, MIDDLE, SeenAction::Raise, Some(amount)), + at(Street::Preflop, CUTOFF, SeenAction::Call, Some(amount)), + at(FLOP, CUTOFF, SeenAction::Bet, Some(amount)), + at(FLOP, MIDDLE, SeenAction::Raise, Some(amount)), + at(FLOP, CUTOFF, SeenAction::Call, Some(amount)), + ]; + let mut s = spot(3, history, None); + s.seats = seats; + s.big_blind = amount; + s.pot = amount; + for seat in [MIDDLE, CUTOFF] { + assert!(well_formed(&spec(&s, seat), 3), "amount {amount} seats {seats}"); + } + } + } +} + +fn pick(rng: Rng, items: &[T]) -> (T, Rng) { + let (i, rng) = rng.below(items.len() as u64); + (items[i as usize], rng) +} + +fn random_record(rng: Rng) -> (ActionRecord, Rng) { + let (street, rng) = pick(rng, &Street::ALL); + let (seat, rng) = rng.below(12); + let (action, rng) = pick(rng, &SeenAction::ALL); + let (present, rng) = rng.below(4); + let (unit, rng) = rng.unit(); + let (odd, rng) = rng.below(20); + let amount = match (present, odd) { + (0, _) => None, + (_, 0) => Some(f64::NAN), + (_, 1) => Some(-unit), + _ => Some(unit * 60.0), + }; + (ActionRecord { street, seat: seat as u8, action, amount }, rng) +} + +fn random_frequency(rng: Rng) -> (Option, Rng) { + let (kind, rng) = rng.below(8); + let (unit, rng) = rng.unit(); + let value = match kind { + 0 | 1 => None, + 2 => Some(f64::NAN), + 3 => Some(unit * 3.0 - 1.0), + _ => Some(unit), + }; + (value, rng) +} + +#[test] +fn property_random_histories_always_give_a_well_formed_spec() { + let mut rng = Rng::seeded(0xBADC0FFEE); + for case in 0..4000 { + let (len, r) = rng.below(12); + rng = r; + let mut history = Vec::new(); + for _ in 0..len { + let (rec, r) = random_record(rng); + rng = r; + history.push(rec); + } + let (board, r) = pick(rng, &[0usize, 3, 4, 5]); + rng = r; + let (vpip, r) = random_frequency(rng); + let (pfr, r) = random_frequency(r); + let (fold, r) = random_frequency(r); + rng = r; + let (seats, r) = rng.below(13); + rng = r; + let (button, r) = rng.below(14); + rng = r; + let (seat, r) = rng.below(12); + rng = r; + let mut s = spot(board, history, Some(Profile { vpip, pfr, fold_to_bet: fold, aggression: None })); + s.seats = seats as u8; + s.button_seat = if button == 13 { None } else { Some(button as u8) }; + let v = Villain { seat: seat as u8, stack: 50.0, folded: false, profile: s.villains[0].profile }; + let r = range_spec(&s, &v); + assert!(well_formed(&r, board), "case {case}: {r:?} for {s:?}"); + } +} + +#[test] +fn property_spec_is_deterministic() { + let s = spot(4, hand(vec![pre(CUTOFF, SeenAction::Raise), post(Street::Turn, CUTOFF, SeenAction::Bet)]), None); + assert_eq!(spec(&s, CUTOFF), spec(&s, CUTOFF)); +}