diff --git a/MODULES.md b/MODULES.md index 42a72a71..ae16e399 100644 --- a/MODULES.md +++ b/MODULES.md @@ -41,7 +41,7 @@ Zufall kommt nur aus `rng::Rng`, das als Wert mitgegeben wird (Seed: Erweiterung | `equity` | Monte-Carlo-Equity gegen Gegner-Ranges (`Any`, `Exact`, `Filter`, `Combos`), Rejection Sampling oder direktes Ziehen aus einer aufgezählten Hand-Liste, 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` | 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, Sicherheit, Begründung. NLHE und AOF am 6er-Tisch: Gleichgewicht aus der erzeugten CFR-Tabelle (`generated_charts`, `generated_lookup`, `cfr_advice`); die Ausnutzung verschiebt nur deren Grenze (`exploit_border`). Sonst gelten die Heuristik-Charts (`full_chart`, `push_chart`). | +| `preflop` | Rankings und Perzentile (Hold'em 169 Klassen, Short Deck 81 Klassen, PLO4 und PLO5 je ein Strukturwert), Button aus `buttonSeat` oder aus den geposteten Blinds, Position jedes Sitzes, Situation, Sicherheit, Begründung. NLHE und AOF am 6er-Tisch: Gleichgewicht aus der erzeugten CFR-Tabelle (`generated_charts`, `generated_lookup`, `cfr_advice`); die Ausnutzung verschiebt nur deren Grenze (`exploit_border`). Sonst gelten die Heuristik-Charts (`full_chart`, `push_chart`). | | `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, ob Draws weiterspielen und welchen Bluff-Anteil die Range behält. Dazu `fold_chance` (P(Aufgabe) je Gegner), `table_fold` (alle Gegner), `bluff_share`, `call_floor` (womit ein Gegner einen Einsatz callt) und `steal_width` (Steal-Breite aus der Fold-Neigung der Blinds). | | `engine` | `decide` setzt alles zusammen. `range_filter` macht aus einer Range-Beschreibung ein Prädikat (mit Bluff-Anteil), `range_combos` zählt Zwei-Karten-Ranges auf, `called_equity` rechnet die Equity gegen die Calling-Range, `bluff` liefert den Erwartungswert in zwei Zweigen, die Bluff-Arten und die Leitplanken. `choose_postflop_with`: 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. `double_board`: dieselbe Lage je Board entschieden, die höhere Equity gewinnt. `run_twice`: Equity gegen Bruchpunkt → annehmen, ablehnen oder `ABSTAIN` | @@ -282,7 +282,7 @@ Stand 2026-10-28, Seed `0x5EED_0001`, bb/100 mit 95-%-Intervall (in Klammern ohn Gegen die Calling Station ist der Vorsprung am kleinsten und am unsichersten: Gewonnen wird dort nur über Value Bets, Bluffs bringen nichts. -## Tests (`cargo test`, 816) +## Tests (`cargo test`, 832) - **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): @@ -297,12 +297,14 @@ Gegen die Calling Station ist der Vorsprung am kleinsten und am unsichersten: Ge - `bluff_property`: 4 000 Zufalls-Spots. Geblufft wird nur, wenn der Fold-Zweig positiv ist und die Summe beider Zweige positiv und über der passiven Linie liegt. Nie gegen Never-Folder; reine Bluffs nur heads-up. - `pipeline_bluff` mit Referenzszenarien: weniger Bluffs gegen die Calling Station, mehr gegen den Nit, breitere Steals gegen Nits, Bluff-Catch gegen den Maniac, Fold gegen den Nit - **CFR:** `cfr_kuhn`, `cfr_games`, `cfr_equity`, `cfr_hand_class`, `cfr_three_way`, `cfr_nash`, `generated_charts_*`, `preflop_cfr_advice`, `cfr_multi` (Mehrere Verteidiger: Identität mit den alten Spielen, Auszahlungssummen, Gegenprobe exakt und gesampelt, Reproduktion), `short_deck_charts` (Vollständigkeit, Randhände, direkte Showdowns), `preflop_multi_advice` (Rat nach Gegnerzahl: BTN Q8o öffnet gegen einen und foldet gegen zwei Verteidiger, EP KTo foldet am vollen Tisch; Rückfälle) +- **PLO4:** `pipeline_plo4` (echte Anfrage wird beantwortet, 2/3/5 Karten werden abgelehnt, Omaha-Regel mit Gegenprobe zur Hold'em-Wertung, Doppel-Board-Begründung, Pot-Limit-Deckel; Boards der echten Hand 166344000006) und `preflop_plo4` (Tabelle reproduziert aus allen 270 725 Händen, Rangkorrelation mit gesampelter Equity > 0,85) - **Vertrag:** `pipeline_contract` mit dem Beispiel aus VERTRAG.md - **Spielstärke:** `sim_strength` (Gegner, Tischmechanik und Chip-Bilanz bei 2, 3 und 6 Spielern, Determinismus, Gewinnrate heads-up gegen jeden Gegner; langer Lauf mit 6-max hinter `--ignored`) - **Zusatzfelder:** `pipeline_double_board` (benannte Referenzen: Set auf einem Board ≥ 0,80, Unterpaar auf dem anderen ≤ 0,45; ein Board verbessert, das andere nicht), `pipeline_run_twice`, `pipeline_extras_neutral` (ohne die Felder bitgleich zur Pipeline davor) ## Annahmen und Grenzen +- `PLO4` (Wire-Name; VERTRAG.md kennt die Variante nicht und bleibt unverändert): vier Lochkarten, genau zwei davon plus drei vom Board, Pot-Limit wie `PLO5`, `boardDouble` und Bomb Pot (erster Zug auf dem Flop) laufen über denselben Weg. Vorflop gibt es keine CFR-Tabelle, geantwortet wird wie bei `PLO5` aus der Heuristik, aber mit einem eigenen Vier-Karten-Strukturwert (`preflop::plo4_*`, Perzentile aus allen 270 725 Händen; die Gewichte sind gegen Equity-Stichproben kalibriert, Rangkorrelation ≈ 0,9). Grenzen: Der Wert ist eine Heuristik, keine Equity-Rangliste (Rainbow-Rundown J-T-9-8 landet im besten Drittel); die Gegner-Range postflop wird per Zufallsziehung gebildet, die Trials entsprechen denen von `PLO5`. - `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, und es gibt weder Bluff-Anteil noch Bluff-Catch-Sperre. diff --git a/src/engine/decide.rs b/src/engine/decide.rs index c0224d78..22db19f8 100644 --- a/src/engine/decide.rs +++ b/src/engine/decide.rs @@ -19,11 +19,11 @@ use crate::read::hand_read::read; use crate::rng::Rng; const TRIALS_TWO_CARD: u32 = 3000; -const TRIALS_FIVE_CARD: u32 = 1500; +const TRIALS_OMAHA: u32 = 1500; fn trials(spot: &Spot) -> u32 { - if spot.rules().hole_cards >= 5 { - TRIALS_FIVE_CARD + if spot.rules().hole_cards >= 4 { + TRIALS_OMAHA } else { TRIALS_TWO_CARD } diff --git a/src/preflop/hand_percentile.rs b/src/preflop/hand_percentile.rs index 6e1a0316..4cfed719 100644 --- a/src/preflop/hand_percentile.rs +++ b/src/preflop/hand_percentile.rs @@ -1,4 +1,5 @@ use super::holdem_percentile::holdem_percentile; +use super::plo4_percentile::plo4_percentile; use super::plo5_percentile::plo5_percentile; use super::short_deck_percentile::short_deck_percentile; use crate::card::Card; @@ -6,13 +7,15 @@ use crate::variant::{rules, DeckRule, Variant}; /// Strength percentile of a starting hand: 0.0 = best possible, 1.0 = worst. /// Two-card hands use a class ranking table chosen by the variant's deck (169 classes for the -/// full deck, 81 for the short deck); PLO5 uses a structural score. +/// full deck, 81 for the short deck); PLO4 and PLO5 use a structural score +/// each (the weights differ because a four-card hand has other suit and window shapes). /// Anything that is not a valid hand for the variant is `1.0`. pub fn percentile(variant: Variant, hole: &[Card]) -> f64 { let rules = rules(variant); match (rules.hole_cards, rules.deck) { (2, deck) if deck == DeckRule::SHORT => short_deck_percentile(hole), (2, _) => holdem_percentile(hole), + (4, _) => plo4_percentile(hole), (5, _) => plo5_percentile(hole), _ => 1.0, } diff --git a/src/preflop/mod.rs b/src/preflop/mod.rs index 5937e3bc..addaea44 100644 --- a/src/preflop/mod.rs +++ b/src/preflop/mod.rs @@ -20,6 +20,9 @@ pub mod holdem_percentile; pub mod holdem_ranking; pub mod multi_lookup; pub mod plan; +pub mod plo4_percentile; +pub mod plo4_score; +pub mod plo4_score_table; pub mod plo5_pair_bonus; pub mod plo5_percentile; pub mod plo5_rundown; diff --git a/src/preflop/plo4_percentile.rs b/src/preflop/plo4_percentile.rs new file mode 100644 index 00000000..d70a9f2d --- /dev/null +++ b/src/preflop/plo4_percentile.rs @@ -0,0 +1,14 @@ +//! Maps an Omaha-4 structural score to a percentile via the empirical score distribution. + +use super::plo4_score::score; +use super::plo4_score_table::{PERCENTILE_BY_SCORE, SCORE_MIN}; +use crate::card::Card; + +/// `1.0` unless `hole` is exactly four distinct cards. Monotone: a higher score never +/// gives a larger percentile. +pub fn plo4_percentile(hole: &[Card]) -> f64 { + score(hole).map_or(1.0, |s| { + let index = (s - SCORE_MIN).clamp(0, PERCENTILE_BY_SCORE.len() as i32 - 1); + PERCENTILE_BY_SCORE[index as usize] + }) +} diff --git a/src/preflop/plo4_score.rs b/src/preflop/plo4_score.rs new file mode 100644 index 00000000..932c6472 --- /dev/null +++ b/src/preflop/plo4_score.rs @@ -0,0 +1,66 @@ +//! Structural strength score of a four-card Omaha starting hand (higher = better). +//! +//! Same ingredients as the five-card score (`plo5_score`) but with weights of their own: with +//! four cards a hand is judged on pairs (trips/quads penalised), high cards, suitedness +//! (double-suited bonus, nut-suit bonus, three or four of one suit is dead weight), the best +//! rundown window and dangling cards. The five-card tables are not reused because their suit and +//! window weights assume five cards. Calibrated against sampled equity in +//! `tests/preflop_plo4.rs`. + +use super::plo5_pair_bonus::group_points; +use super::plo5_rundown::dangler_points; +use crate::card::Card; + +/// Points per card by rank value: with four cards every card is live, so mid cards count too. +const HIGH_CARD: [i32; 15] = [0, 0, 0, 0, 1, 1, 2, 3, 4, 5, 7, 9, 11, 13, 16]; +/// Bonus by number of cards in one suit (index 0..=4). +const BY_SUIT_SIZE: [i32; 5] = [0, 0, 6, 1, -10]; +/// Bonus for the highest card of a suit that has at least two cards, by rank value. +const BY_TOP_CARD: [i32; 15] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 5, 10]; +/// Bonus when two different suits are both shared (double suited). +const DOUBLE_SUITED: i32 = 8; +/// Points by distinct ranks inside the best window of five rank values. +const BY_WINDOW_FILL: [i32; 5] = [0, 0, 0, 7, 22]; + +/// `None` unless `hole` is exactly four distinct cards. +pub fn score(hole: &[Card]) -> Option { + let distinct = hole.iter().enumerate().all(|(i, c)| !hole[..i].contains(c)); + (hole.len() == 4 && distinct).then(|| score_of_valid(hole)) +} + +fn present(counts: &[u8; 15], value: usize) -> bool { + counts[if value == 1 { 14 } else { value }] > 0 +} + +fn window_points(counts: &[u8; 15]) -> i32 { + // Low windows are worth less: the straights they make are dominated, so the points scale + // with the top of the window (14 -> full weight, the wheel -> a third). + (1..=10) + .map(|low| { + let fill = (low..low + 5).filter(|v| present(counts, *v)).count().min(4); + BY_WINDOW_FILL[fill] * (low as i32 + 6) / 16 + }) + .max() + .unwrap_or(0) +} + +fn score_of_valid(hole: &[Card]) -> i32 { + let mut counts = [0u8; 15]; + let mut sizes = [0u8; 4]; + let mut tops = [0u8; 4]; + for card in hole { + let (value, suit) = (card.rank.value(), card.suit as usize); + counts[value as usize] += 1; + sizes[suit] += 1; + tops[suit] = tops[suit].max(value); + } + let groups: i32 = (2..=14).map(|v| group_points(v, counts[v])).sum(); + let high: i32 = hole.iter().map(|c| HIGH_CARD[c.rank.value() as usize]).sum(); + let suits: i32 = (0..4) + .filter(|s| sizes[*s] >= 2) + .map(|s| BY_SUIT_SIZE[sizes[s] as usize] + BY_TOP_CARD[tops[s] as usize]) + .sum::() + + if sizes.iter().filter(|n| **n == 2).count() == 2 { DOUBLE_SUITED } else { 0 }; + let lone = hole.iter().filter(|c| sizes[c.suit as usize] == 1).map(|c| c.rank.value()); + groups + high + suits + window_points(&counts) + dangler_points(&counts, lone) +} diff --git a/src/preflop/plo4_score_table.rs b/src/preflop/plo4_score_table.rs new file mode 100644 index 00000000..e05f63a7 --- /dev/null +++ b/src/preflop/plo4_score_table.rs @@ -0,0 +1,34 @@ +//! Empirical percentile of every Omaha-4 structural score (see `plo4_score::score`). +//! +//! Generated by enumerating all 270 725 four-card hands: entry `score - SCORE_MIN` is +//! (hands with a higher score + half the hands with this score) / all hands. +//! Regenerate whenever the weights in `plo4_score` change +//! (`cargo test --release --test preflop_plo4 -- --ignored --nocapture print_table`). + +pub const SCORE_MIN: i32 = -60; +pub const PERCENTILE_BY_SCORE: [f64; 233] = [ + 1.00000, 0.99999, 0.99999, 0.99999, 0.99999, 0.99999, 0.99999, 0.99999, 0.99998, 0.99998, + 0.99998, 0.99998, 0.99998, 0.99998, 0.99998, 0.99998, 0.99998, 0.99997, 0.99997, 0.99997, + 0.99997, 0.99997, 0.99997, 0.99997, 0.99997, 0.99997, 0.99997, 0.99997, 0.99997, 0.99997, + 0.99997, 0.99997, 0.99996, 0.99994, 0.99991, 0.99989, 0.99986, 0.99980, 0.99973, 0.99969, + 0.99965, 0.99958, 0.99946, 0.99926, 0.99908, 0.99894, 0.99873, 0.99847, 0.99830, 0.99813, + 0.99796, 0.99777, 0.99756, 0.99738, 0.99722, 0.99707, 0.99685, 0.99665, 0.99648, 0.99622, + 0.99577, 0.99532, 0.99483, 0.99430, 0.99367, 0.99280, 0.99161, 0.98986, 0.98694, 0.98312, + 0.97838, 0.97232, 0.96482, 0.95493, 0.94265, 0.92970, 0.91474, 0.89729, 0.87845, 0.85922, + 0.84058, 0.82205, 0.80289, 0.78129, 0.75890, 0.73603, 0.71252, 0.68911, 0.66480, 0.63956, + 0.61410, 0.58940, 0.56456, 0.53974, 0.51591, 0.49405, 0.47357, 0.45315, 0.43260, 0.41181, + 0.39109, 0.37136, 0.35270, 0.33396, 0.31537, 0.29783, 0.28199, 0.26744, 0.25372, 0.24084, + 0.22927, 0.21840, 0.20775, 0.19765, 0.18788, 0.17853, 0.16909, 0.15977, 0.15164, 0.14365, + 0.13552, 0.12785, 0.12031, 0.11340, 0.10735, 0.10209, 0.09748, 0.09262, 0.08785, 0.08352, + 0.07988, 0.07675, 0.07354, 0.07041, 0.06720, 0.06409, 0.06091, 0.05765, 0.05449, 0.05176, + 0.04918, 0.04640, 0.04362, 0.04093, 0.03875, 0.03686, 0.03503, 0.03332, 0.03185, 0.03070, + 0.02948, 0.02775, 0.02538, 0.02292, 0.02098, 0.01941, 0.01785, 0.01615, 0.01458, 0.01330, + 0.01213, 0.01093, 0.00970, 0.00880, 0.00818, 0.00765, 0.00716, 0.00687, 0.00672, 0.00652, + 0.00627, 0.00595, 0.00570, 0.00536, 0.00496, 0.00442, 0.00385, 0.00339, 0.00306, 0.00279, + 0.00254, 0.00230, 0.00203, 0.00182, 0.00162, 0.00140, 0.00120, 0.00104, 0.00092, 0.00082, + 0.00071, 0.00064, 0.00062, 0.00059, 0.00058, 0.00055, 0.00053, 0.00051, 0.00043, 0.00033, + 0.00028, 0.00024, 0.00022, 0.00020, 0.00018, 0.00018, 0.00017, 0.00016, 0.00011, 0.00007, + 0.00007, 0.00007, 0.00007, 0.00007, 0.00006, 0.00004, 0.00004, 0.00004, 0.00004, 0.00004, + 0.00004, 0.00004, 0.00003, 0.00002, 0.00002, 0.00002, 0.00002, 0.00002, 0.00002, 0.00002, + 0.00002, 0.00002, 0.00001, +]; diff --git a/src/variant/kind.rs b/src/variant/kind.rs index 7daeb78b..92ac8065 100644 --- a/src/variant/kind.rs +++ b/src/variant/kind.rs @@ -1,31 +1,33 @@ -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub enum Variant { - Nlhe, - Plo5, - KPoker, - Aof, - ShortDeck, -} - -impl Variant { - pub const ALL: [Variant; 5] = - [Variant::Nlhe, Variant::Plo5, Variant::KPoker, Variant::Aof, Variant::ShortDeck]; - - /// Contract names, plus `6+` as an alias for `SHORT_DECK`. - pub fn parse(text: &str) -> Option { - match text.trim() { - "6+" => Some(Variant::ShortDeck), - name => Variant::ALL.into_iter().find(|v| v.name() == name), - } - } - - pub fn name(self) -> &'static str { - match self { - Variant::Nlhe => "NLHE", - Variant::Plo5 => "PLO5", - Variant::KPoker => "K_POKER", - Variant::Aof => "AOF", - Variant::ShortDeck => "SHORT_DECK", - } - } -} +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Variant { + Nlhe, + Plo4, + Plo5, + KPoker, + Aof, + ShortDeck, +} + +impl Variant { + pub const ALL: [Variant; 6] = + [Variant::Nlhe, Variant::Plo4, Variant::Plo5, Variant::KPoker, Variant::Aof, Variant::ShortDeck]; + + /// Contract names, plus `6+` as an alias for `SHORT_DECK`. + pub fn parse(text: &str) -> Option { + match text.trim() { + "6+" => Some(Variant::ShortDeck), + name => Variant::ALL.into_iter().find(|v| v.name() == name), + } + } + + pub fn name(self) -> &'static str { + match self { + Variant::Nlhe => "NLHE", + Variant::Plo4 => "PLO4", + Variant::Plo5 => "PLO5", + Variant::KPoker => "K_POKER", + Variant::Aof => "AOF", + Variant::ShortDeck => "SHORT_DECK", + } + } +} diff --git a/src/variant/rules.rs b/src/variant/rules.rs index 1029d29c..0a4fd809 100644 --- a/src/variant/rules.rs +++ b/src/variant/rules.rs @@ -1,47 +1,53 @@ -use super::{ActionShape, DeckRule, HandRanking, HoleUsage, SizingRule, Variant}; - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct Rules { - pub hole_cards: usize, - pub hole_usage: HoleUsage, - pub sizing: SizingRule, - pub shape: ActionShape, - pub deck: DeckRule, - pub ranking: HandRanking, - /// Cards burned over a full hand (one before flop, turn and river). - pub burns: usize, -} - -const HOLDEM: Rules = Rules { - hole_cards: 2, - hole_usage: HoleUsage::BestFiveOfAll, - sizing: SizingRule::NoLimit, - shape: ActionShape::Full, - deck: DeckRule::FULL, - ranking: HandRanking::Standard, - burns: 3, -}; - -/// The single place where variants differ. -pub fn rules(variant: Variant) -> Rules { - match variant { - Variant::Nlhe => HOLDEM, - Variant::Plo5 => Rules { - hole_cards: 5, - hole_usage: HoleUsage::ExactlyTwoHole, - sizing: SizingRule::PotLimit, - ..HOLDEM - }, - Variant::KPoker => Rules { sizing: SizingRule::Menu, ..HOLDEM }, - Variant::Aof => Rules { - sizing: SizingRule::AllInOnly, - shape: ActionShape::Binary, - ..HOLDEM - }, - Variant::ShortDeck => Rules { - deck: DeckRule::SHORT, - ranking: HandRanking::FlushOverFullHouse, - ..HOLDEM - }, - } -} +use super::{ActionShape, DeckRule, HandRanking, HoleUsage, SizingRule, Variant}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Rules { + pub hole_cards: usize, + pub hole_usage: HoleUsage, + pub sizing: SizingRule, + pub shape: ActionShape, + pub deck: DeckRule, + pub ranking: HandRanking, + /// Cards burned over a full hand (one before flop, turn and river). + pub burns: usize, +} + +const HOLDEM: Rules = Rules { + hole_cards: 2, + hole_usage: HoleUsage::BestFiveOfAll, + sizing: SizingRule::NoLimit, + shape: ActionShape::Full, + deck: DeckRule::FULL, + ranking: HandRanking::Standard, + burns: 3, +}; + +/// The single place where variants differ. +pub fn rules(variant: Variant) -> Rules { + match variant { + Variant::Nlhe => HOLDEM, + Variant::Plo4 => Rules { + hole_cards: 4, + hole_usage: HoleUsage::ExactlyTwoHole, + sizing: SizingRule::PotLimit, + ..HOLDEM + }, + Variant::Plo5 => Rules { + hole_cards: 5, + hole_usage: HoleUsage::ExactlyTwoHole, + sizing: SizingRule::PotLimit, + ..HOLDEM + }, + Variant::KPoker => Rules { sizing: SizingRule::Menu, ..HOLDEM }, + Variant::Aof => Rules { + sizing: SizingRule::AllInOnly, + shape: ActionShape::Binary, + ..HOLDEM + }, + Variant::ShortDeck => Rules { + deck: DeckRule::SHORT, + ranking: HandRanking::FlushOverFullHouse, + ..HOLDEM + }, + } +} diff --git a/tests/card_basics.rs b/tests/card_basics.rs index 3f429e0c..1643f02c 100644 --- a/tests/card_basics.rs +++ b/tests/card_basics.rs @@ -76,6 +76,10 @@ fn rng_is_a_value() { fn variant_rules_table() { assert_eq!(Variant::parse("K_POKER"), Some(Variant::KPoker)); assert_eq!(Variant::parse("STUD"), None); + assert_eq!(Variant::parse("PLO4"), Some(Variant::Plo4)); + assert_eq!(rules(Variant::Plo4).hole_cards, 4); + assert_eq!(rules(Variant::Plo4).hole_usage, HoleUsage::ExactlyTwoHole); + assert_eq!(rules(Variant::Plo4).sizing, SizingRule::PotLimit); assert_eq!(rules(Variant::Plo5).hole_cards, 5); assert_eq!(rules(Variant::Plo5).hole_usage, HoleUsage::ExactlyTwoHole); assert_eq!(rules(Variant::Nlhe).hole_usage, HoleUsage::BestFiveOfAll); diff --git a/tests/pipeline_plo4.rs b/tests/pipeline_plo4.rs new file mode 100644 index 00000000..a6c401e0 --- /dev/null +++ b/tests/pipeline_plo4.rs @@ -0,0 +1,148 @@ +//! PLO4 (four hole cards, Omaha rule, pot-limit) end to end through `wire::respond::respond`. +//! +//! Spot template: hand 166344000006 of the real client log ("14R PLO 0.02-0.05", bomb pot with +//! double board, blinds 0.02/0.05, ante 0.10, two players left). The boards are the real ones +//! (first board 7d 9d Ks, turn 5d; second board 2d 3s Ad, turn 7c); the hole cards are chosen +//! for the tests because the log does not reveal them. A bomb pot has no preflop betting, so +//! the first decision is on the flop. + +mod support; + +use pokerfreak::hand::category::Category; +use pokerfreak::hand::showdown::best; +use pokerfreak::variant::HoleUsage; +use pokerfreak::wire::respond::respond; +use support::{action, board_json, cards_json, field, short, size}; + +/// Real boards of the template hand (flop, then flop + turn). +const BOARD_1: &str = "7d 9d Ks"; +const BOARD_2: &str = "2d 3s Ad"; +const BOARD_1_TURN: &str = "7d 9d Ks 5d"; +const BOARD_2_TURN: &str = "2d 3s Ad 7c"; +/// Top set on the first board, only a pair under the ace on the second. +const HERO: &str = "Kh Kd 8c 6c"; + +#[allow(clippy::too_many_arguments)] +fn request( + variant: &str, + hero: &str, + board: &str, + double: Option<&str>, + pot: f64, + to_call: f64, + legal: &str, + max_raise: f64, +) -> String { + let cards = short(board); + let street = match cards.len() { + 0 => "PREFLOP", + 3 => "FLOP", + 4 => "TURN", + _ => "RIVER", + }; + let double = double.map_or(String::new(), |b| format!(r#","boardDouble":{}"#, board_json(&short(b)))); + format!( + r#"{{"variant":"{variant}","bigBlind":0.05,"seats":6,"heroSeat":6,"buttonSeat":4,"heroCards":{},"board":{},"street":"{street}","pot":{pot},"toCall":{to_call},"heroStack":3.84,"minRaiseTo":{},"maxRaiseTo":{max_raise},"legalActions":{legal},"villains":[{{"seat":4,"stack":4.89,"folded":false}}]{double}}}"#, + cards_json(&short(hero)), + board_json(&cards), + (to_call * 2.0).max(0.05), + ) +} + +const FACING_BET: &str = r#"["FOLD","CALL","RAISE"]"#; +const CHECKED_TO: &str = r#"["CHECK","RAISE"]"#; + +#[test] +fn a_real_plo4_request_is_answered_not_rejected() { + let out = respond(&request("PLO4", HERO, BOARD_1, None, 0.2, 0.1, FACING_BET, 3.84)); + assert_ne!(action(&out), "ABSTAIN", "{out}"); + let reason = field(&out, "reason").unwrap_or(""); + assert!(!reason.contains("expected"), "{out}"); + // Top set on a two-tone board with the nut-flush draw dead: never a fold. + assert_ne!(action(&out), "FOLD", "{out}"); +} + +#[test] +fn the_bomb_pot_turn_is_answered_too() { + let out = respond(&request("PLO4", HERO, BOARD_1_TURN, None, 0.4, 0.0, CHECKED_TO, 3.84)); + assert_ne!(action(&out), "ABSTAIN", "{out}"); +} + +#[test] +fn any_other_number_of_hole_cards_is_refused() { + for hero in ["Kh Kd", "Kh Kd 8c", "Kh Kd 8c 6c 2h"] { + let out = respond(&request("PLO4", hero, BOARD_1, None, 0.2, 0.1, FACING_BET, 3.84)); + assert_eq!(action(&out), "ABSTAIN", "{hero}: {out}"); + let reason = field(&out, "reason").unwrap_or(""); + assert!(reason.contains("expected 4 cards for PLO4"), "{hero}: {out}"); + } + // The neighbours keep their own counts: four cards are not a PLO5 or NLHE hand. + for variant in ["PLO5", "NLHE"] { + let out = respond(&request(variant, HERO, BOARD_1, None, 0.2, 0.1, FACING_BET, 3.84)); + assert_eq!(action(&out), "ABSTAIN", "{variant}: {out}"); + } +} + +#[test] +fn omaha_rule_exactly_two_hole_cards_decide_the_hand() { + // Three hole hearts plus Jh Th would be a royal flush at Hold'em; at Omaha only two hole + // cards may play, so there is no flush and no straight. + let (hole, board) = (short("Ah Kh Qh 2c"), short("Jh Th 3d")); + let omaha = best(HoleUsage::ExactlyTwoHole, &hole, &board).expect("valid"); + let holdem = best(HoleUsage::BestFiveOfAll, &hole, &board).expect("valid"); + assert_eq!(holdem.category, Category::StraightFlush); + assert!(omaha.category <= Category::Pair, "{:?}", omaha.category); + + // And so the pipeline reads the same thing: no made straight or flush. + let line = request("PLO4", "Ah Kh Qh 2c", "Jh Th 3d 8c 4s", None, 1.0, 0.0, CHECKED_TO, 3.84); + let out = respond(&line); + let category = field(&out, "category").unwrap_or(""); + assert!(!category.contains("Flush") && !category.contains("Straight"), "{out}"); +} + +#[test] +fn omaha_rule_four_hole_cards_cannot_be_used_together() { + // Quads in the hand are only one pair for Omaha's two-card pick, never four of a kind. + let (hole, board) = (short("Ah Ad Ac As"), short("2d 7h 9c Js 4h")); + let omaha = best(HoleUsage::ExactlyTwoHole, &hole, &board).expect("valid"); + assert_eq!(omaha.category, Category::Pair); +} + +#[test] +fn double_board_reason_names_the_judgement_of_both_boards() { + // `board` is the weak one (pair of kings under the ace), `boardDouble` the set board. + let out = respond(&request("PLO4", HERO, BOARD_2, Some(BOARD_1), 0.4, 0.0, CHECKED_TO, 3.84)); + let reason = field(&out, "reason").unwrap_or(""); + assert!(reason.contains("double board"), "{out}"); + assert!(reason.contains("board 2"), "the second board was the better one: {out}"); + assert!(reason.contains("pot split"), "{out}"); + let same = respond(&request("PLO4", HERO, BOARD_1, Some(BOARD_2), 0.4, 0.0, CHECKED_TO, 3.84)); + assert_eq!(field(&same, "equity"), field(&out, "equity"), "board order must not matter"); + assert_ne!(action(&out), "ABSTAIN", "{out}"); +} + +#[test] +fn double_board_works_on_the_turn_as_well() { + let out = respond(&request("PLO4", HERO, BOARD_2_TURN, Some(BOARD_1_TURN), 0.4, 0.0, CHECKED_TO, 3.84)); + assert_ne!(action(&out), "ABSTAIN", "{out}"); + assert!(field(&out, "reason").unwrap_or("").contains("double board"), "{out}"); +} + +#[test] +fn raises_never_exceed_the_pot() { + let mut raises = 0; + for (pot, to_call) in [(0.2, 0.0), (0.2, 0.1), (0.5, 0.0), (0.5, 0.25), (1.2, 0.4), (3.0, 1.0), (0.4, 0.4)] { + for (board, hero) in [(BOARD_1, HERO), (BOARD_1_TURN, HERO), (BOARD_1, "Ks Kc 9h 9c"), (BOARD_2, "Ac Ah 5d 4d")] { + let legal = if to_call > 0.0 { FACING_BET } else { CHECKED_TO }; + // The table would allow far more than the pot: the core must cap at pot-limit. + let out = respond(&request("PLO4", hero, board, None, pot, to_call, legal, 3.84)); + if action(&out) == "RAISE" { + raises += 1; + let s = size(&out).expect("raise carries a size"); + let cap = pot + 2.0 * to_call; + assert!(s <= cap + 1e-9, "raise to {s} over pot-limit cap {cap}: {out}"); + } + } + } + assert!(raises > 0, "the monsters in the grid must raise at least once"); +} diff --git a/tests/preflop_advise.rs b/tests/preflop_advise.rs index 756c6fff..75f72071 100644 --- a/tests/preflop_advise.rs +++ b/tests/preflop_advise.rs @@ -370,6 +370,17 @@ fn omaha_five_cards_use_the_same_charts() { assert_eq!(advise(&junk, &Thresholds::BASE).action, ChartAction::Fold); } +#[test] +fn omaha_four_cards_use_the_same_charts_with_their_own_ranking() { + let strong = spot_with(Variant::Plo4, cards("Ah Ad Kh Kd"), BUTTON, 1.5, 1.0, 100.0); + let junk = spot_with(Variant::Plo4, cards("2c 7d 4h 9s"), BUTTON, 1.5, 1.0, 100.0); + assert_eq!(advise(&strong, &Thresholds::BASE).action, ChartAction::Raise); + assert_eq!(advise(&junk, &Thresholds::BASE).action, ChartAction::Fold); + // Two or five cards are not a PLO4 hand. + let five = spot_with(Variant::Plo4, cards("Ah Ad Kh Kd Jc"), BUTTON, 1.5, 1.0, 100.0); + assert_eq!(advise(&five, &Thresholds::BASE).percentile, 1.0); +} + #[test] fn invalid_hole_cards_fold_without_panicking() { let one = spot_with(Variant::Nlhe, cards("Ah"), BUTTON, 1.5, 1.0, 100.0); @@ -389,10 +400,10 @@ fn degenerate_numbers_do_not_panic() { ]; for (pot, to_call, stack) in weird { for variant in Variant::ALL { - let hole = if variant == Variant::Plo5 { - "Ah Ad Kh Kd Jc" - } else { - "Ah Ad" + let hole = match variant { + Variant::Plo5 => "Ah Ad Kh Kd Jc", + Variant::Plo4 => "Ah Ad Kh Kd", + _ => "Ah Ad", }; let s = spot_with(variant, cards(hole), BUTTON, pot, to_call, stack); let p = advise(&s, &Thresholds::BASE); diff --git a/tests/preflop_plo4.rs b/tests/preflop_plo4.rs new file mode 100644 index 00000000..8fd5081a --- /dev/null +++ b/tests/preflop_plo4.rs @@ -0,0 +1,185 @@ +//! Omaha-4 starting-hand ranking: structure, table reproducibility and calibration against +//! sampled equity. +//! +//! Regenerate `preflop::plo4_score_table` after changing the `plo4_score` weights: +//! `cargo test --release --test preflop_plo4 -- --ignored --nocapture print_table` +use pokerfreak::card::Card; +use pokerfreak::equity::monte_carlo::estimate; +use pokerfreak::equity::query::Query; +use pokerfreak::equity::villain_range::VillainRange; +use pokerfreak::preflop::hand_percentile::percentile; +use pokerfreak::preflop::plo4_score::score; +use pokerfreak::preflop::plo4_score_table::{PERCENTILE_BY_SCORE, SCORE_MIN}; +use pokerfreak::rng::Rng; +use pokerfreak::variant::{rules, Variant}; + +fn hand(text: &str) -> Vec { + Card::parse_list(text).expect("valid cards") +} + +fn pct(text: &str) -> f64 { + percentile(Variant::Plo4, &hand(text)) +} + +/// Score histogram over all 270 725 four-card hands. +fn histogram() -> (i32, Vec, u64) { + let all: Vec = (0..52).filter_map(Card::from_index).collect(); + let mut by_score: std::collections::BTreeMap = Default::default(); + let mut total = 0; + for a in 0..52 { + for b in a + 1..52 { + for c in b + 1..52 { + for d in c + 1..52 { + let s = score(&[all[a], all[b], all[c], all[d]]).expect("valid"); + *by_score.entry(s).or_default() += 1; + total += 1; + } + } + } + } + let min = *by_score.keys().next().expect("scores"); + let max = *by_score.keys().last().expect("scores"); + let counts = (min..=max).map(|s| by_score.get(&s).copied().unwrap_or(0)).collect(); + (min, counts, total) +} + +#[test] +#[ignore] +fn print_table() { + let (min, counts, total) = histogram(); + let mut above = 0u64; + let mut entries: Vec = counts + .iter() + .rev() + .map(|n| { + let p = (above as f64 + *n as f64 / 2.0) / total as f64; + above += n; + p + }) + .collect(); + entries.reverse(); + println!("pub const SCORE_MIN: i32 = {min};"); + println!("pub const PERCENTILE_BY_SCORE: [f64; {}] = [", entries.len()); + for row in entries.chunks(10) { + let line: Vec = row.iter().map(|p| format!("{p:.5}")).collect(); + println!(" {},", line.join(", ")); + } + println!("];"); +} + +#[test] +fn the_table_reproduces_from_the_score_distribution() { + let (min, counts, total) = histogram(); + assert_eq!(total, 270_725); + assert_eq!(min, SCORE_MIN); + assert_eq!(counts.len(), PERCENTILE_BY_SCORE.len()); + let mut above = 0u64; + for (i, n) in counts.iter().enumerate().rev() { + let expected = (above as f64 + *n as f64 / 2.0) / total as f64; + assert!((PERCENTILE_BY_SCORE[i] - expected).abs() < 6e-6, "score {}", min + i as i32); + above += n; + } +} + +#[test] +fn only_four_distinct_cards_are_ranked() { + assert_eq!(pct("Ah Kd"), 1.0); + assert_eq!(pct("Ah Kd Qc"), 1.0); + assert_eq!(pct("Ah Kd Qc Js Th"), 1.0); + assert_eq!(pct("Ah Ah Qc Js"), 1.0); + assert!(pct("Ah Kd Qc Js") < 1.0); +} + +#[test] +fn percentile_is_monotone_in_the_score() { + assert!(PERCENTILE_BY_SCORE.windows(2).all(|w| w[0] >= w[1])); +} + +#[test] +fn double_suited_big_pairs_beat_rainbow_junk() { + assert!(pct("Ah As Kh Ks") < 0.01, "{}", pct("Ah As Kh Ks")); + assert!(pct("2c 7d 4h 9s") > 0.8); +} + +#[test] +fn four_card_structure_is_valued() { + assert!(pct("Ah Kh Qd Jd") < pct("Ah Kd Qc Js"), "double suited"); + assert!(pct("Jh Td 9c 8s") < pct("Jh 8d 5c 2s"), "rundown"); + assert!(pct("Ah Ad Kh Kd") < pct("Ah Ad Ac Kh"), "trips"); + assert!(pct("Ah Ad Ac Kh") < pct("Ah Ad Ac As"), "quads"); + assert!(pct("Ah Ad Kh Kd") < pct("Ah Ad Kc Qs"), "double suited pairs"); +} + +#[test] +fn four_card_rundowns_and_broadways_rank_high_without_a_fifth_card() { + // A five-card table would see these as incomplete hands; here a rainbow rundown is a + // top-third hand and a double-suited one clearly better. + assert!(pct("Jh Td 9c 8s") < 0.35, "{}", pct("Jh Td 9c 8s")); + assert!(pct("Jh Td 9h 8d") < pct("Jh Td 9c 8s")); + assert!(pct("Ah Kd Qc Js") < 0.10, "{}", pct("Ah Kd Qc Js")); +} + +/// Equity against one random Omaha hand on a random board, deterministic seed. +fn equity(hole: &[Card], seed: u64) -> f64 { + let query = Query { + rules: rules(Variant::Plo4), + hero: hole, + board: &[], + villains: &[VillainRange::Any], + trials: 4_000, + }; + estimate(&query, Rng::seeded(seed)).expect("estimate").0.share +} + +/// Deterministic pseudo-random four-card hands (LCG), independent of the crate's Rng. +fn sample_hands(count: usize) -> Vec> { + let mut state: u64 = 0x9E37_79B9_7F4A_7C15; + let mut next = move || { + state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (state >> 33) as u8 + }; + (0..count) + .map(|_| { + let mut picked: Vec = Vec::new(); + while picked.len() < 4 { + let c = next() % 52; + if !picked.contains(&c) { + picked.push(c); + } + } + picked.into_iter().filter_map(Card::from_index).collect() + }) + .collect() +} + +fn ranks(values: &[f64]) -> Vec { + let mut order: Vec = (0..values.len()).collect(); + order.sort_by(|a, b| values[*a].total_cmp(&values[*b])); + let mut out = vec![0.0; values.len()]; + for (rank, i) in order.into_iter().enumerate() { + out[i] = rank as f64; + } + out +} + +#[test] +fn the_ranking_agrees_with_sampled_equity() { + let hands = sample_hands(250); + let strength: Vec = hands.iter().map(|h| 1.0 - percentile(Variant::Plo4, h)).collect(); + let share: Vec = hands.iter().enumerate().map(|(i, h)| equity(h, 100 + i as u64)).collect(); + let (a, b) = (ranks(&strength), ranks(&share)); + let n = a.len() as f64; + let (ma, mb) = (a.iter().sum::() / n, b.iter().sum::() / n); + let cov: f64 = a.iter().zip(&b).map(|(x, y)| (x - ma) * (y - mb)).sum(); + let var = |v: &[f64], m: f64| v.iter().map(|x| (x - m) * (x - m)).sum::(); + if std::env::var("PLO4_DEBUG").is_ok() { + let mut rows: Vec<(f64, usize)> = (0..hands.len()).map(|i| ((a[i] - b[i]) / n, i)).collect(); + rows.sort_by(|x, y| x.0.total_cmp(&y.0)); + for (d, i) in rows.iter().take(8).chain(rows.iter().rev().take(8)) { + let t: Vec = hands[*i].iter().map(|c| format!("{}{}", c.rank.value(), c.suit as usize)).collect(); + eprintln!("{d:+.2} eq {:.3} pct {:.3} {}", share[*i], percentile(Variant::Plo4, &hands[*i]), t.join(" ")); + } + } + let spearman = cov / (var(&a, ma) * var(&b, mb)).sqrt(); + assert!(spearman > 0.85, "rank correlation with equity {spearman}"); +} diff --git a/tests/spot_fixture/mod.rs b/tests/spot_fixture/mod.rs index 67bada60..f815708a 100644 --- a/tests/spot_fixture/mod.rs +++ b/tests/spot_fixture/mod.rs @@ -72,7 +72,11 @@ pub fn preflop() -> Spot { } pub fn with_variant(spot: Spot, variant: Variant) -> Spot { - let hole = if variant == Variant::Plo5 { "Ah 5h Kd Qc 9s" } else { "Ah 5h" }; + let hole = match variant { + Variant::Plo5 => "Ah 5h Kd Qc 9s", + Variant::Plo4 => "Ah 5h Kd Qc", + _ => "Ah 5h", + }; Spot { variant, hero_cards: cards(hole), ..spot } }