Rake-aware CFR and charts: rake rule, ante situation, regenerated preflop charts
Secures the worktree's uncommitted state before merging into main. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+26
-2
@@ -42,6 +42,7 @@ Zufall kommt nur aus `rng::Rng`, das als Wert mitgegeben wird (Seed: Erweiterung
|
||||
| `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, 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`). |
|
||||
| `rake` | Rake als reine Rechnung (5 %, Cap je Hand, Vorflop 0, Aufteilung auf Side Pots) und was ein Blatt der Chart-Spiele zahlt. |
|
||||
| `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` |
|
||||
@@ -252,7 +253,7 @@ Zwei Sonderfälle:
|
||||
|
||||
## Spielstärke (`sim`, `tests/sim_strength.rs`)
|
||||
|
||||
**Tisch:** No-Limit Hold'em, 2 bis 10 Plätze, Blinds 0,5/1, jeder beginnt mit 100 bb, ohne Rake und Antes. Platz 1 ist der Button, heads-up setzt er den Small Blind. Die Engine sitzt auf einem Platz und bekommt dieselbe Anfrage wie aus der Hülle: `pot` mit allen Einsätzen, `toCall`, `minRaiseTo`/`maxRaiseTo` (Mindest-Raise nach der letzten vollen Erhöhung), `legalActions`, alle Gegner mit Stack und Fold-Status, `history` mit Blinds und Aktionen. Jede Anfrage geht durch `guard::validate`; eine abgelehnte wird gezählt und muss 0 bleiben. `ABSTAIN` gilt am Tisch als Check, sonst Fold. Side Pots werden Stufe für Stufe verteilt, Gleichstände geteilt; jeder Test prüft die Chip-Bilanz.
|
||||
**Tisch:** No-Limit Hold'em, 2 bis 10 Plätze, Blinds 0,5/1, jeder beginnt mit 100 bb, ohne Rake und Antes (`play_hand`, `measure`) oder mit den Kosten des gemessenen Tisches (`play_hand_at`, `measure_at`, `TableCost::MEASURED`, siehe „Rake“). Platz 1 ist der Button, heads-up setzt er den Small Blind. Die Engine sitzt auf einem Platz und bekommt dieselbe Anfrage wie aus der Hülle: `pot` mit allen Einsätzen, `toCall`, `minRaiseTo`/`maxRaiseTo` (Mindest-Raise nach der letzten vollen Erhöhung), `legalActions`, alle Gegner mit Stack und Fold-Status, `history` mit Blinds und Aktionen. Jede Anfrage geht durch `guard::validate`; eine abgelehnte wird gezählt und muss 0 bleiben. `ABSTAIN` gilt am Tisch als Check, sonst Fold. Side Pots werden Stufe für Stufe verteilt, Gleichstände geteilt; jeder Test prüft die Chip-Bilanz.
|
||||
|
||||
**Gegner** (schauen nie auf ihre Karten): Calling Station (callt alles, erhöht nie), Folder (gibt bei jedem Preis auf, checkt sonst), Zufall-legal (gleichverteilt unter den legalen Optionen, Raise-Größe gleichverteilt zwischen Minimum und All-in).
|
||||
|
||||
@@ -293,6 +294,29 @@ Gegen die Calling Station ist der Vorsprung am kleinsten und am unsichersten: Ge
|
||||
|
||||
Alle Rückgänge gegen Zufall liegen im Intervall.
|
||||
|
||||
## Rake (`rake`, `tests/rake_rule.rs`, `tests/cfr_rake.rs`)
|
||||
|
||||
**Quelle:** `game.winnerInfo` (`potAmount` gegen `potAmountAfterRake`), Tisch 1000/2000, Ante 320, 1134 Hände. Herleitung im Kopf von `src/rake/mod.rs`, Messbericht in der Hülle (`archiv/echt/RAKE-gemessen.md`).
|
||||
|
||||
**Regel:** 5 % vom Topf samt Antes, Cap 1 bb **je Hand**, Side Pots teilen ihn nach Größe. Endet die Hand vor dem Flop: 0. Ein Vorflop-All-in mit Board zahlt. `rakeCapGT3` ist als Feld da, aber nicht belegt (an diesem Tisch gleich dem Cap, an den Mikro-Tischen widersprechen die Daten der Konfiguration).
|
||||
|
||||
**Charts:** Nur das volle Deck (NLHE, AOF, Mehrgegner); für Short Deck gibt es keine Messung. Ein Fold zahlt nichts, ein All-in die Regel, ein Topf mit Chips dahinter den am Tisch gemessenen mittleren Rake je Flop-Topf. Der Topf wird nach dem Rake geteilt, die Spiele sind also nicht mehr nullsummig. Die Antes gehen nur in diese Rechnung ein, nicht als totes Geld in die Bäume. Grenze: Das macht die Charts für einen Tisch mit Ante vermutlich zu eng.
|
||||
|
||||
**Verschiebung** (Combo-Anteile, ohne → mit Rake, 100 bb): BB-Call gegen EP 0,425 → 0,198, gegen BTN 0,476 → 0,244, gegen SB 0,581 → 0,331. SB-Call gegen BTN 0,177 → 0,119. BB-3-Bet gegen BTN 0,124 → 0,137, gegen SB 0,172 → 0,195. Open EP 0,249 → 0,219, BTN 0,360 → 0,349, SB unverändert 0,50. Push 10 bb: EP 0,132 → 0,119, BTN 0,327 → 0,348.
|
||||
|
||||
**Netto** (bb/100, 95 %, Seed `0x5EED_0001`, HU 4 000 Hände, 6-max 1 200; `cargo test --release --test sim_strength net_run -- --ignored --nocapture`):
|
||||
|
||||
| Tisch | Gegner | brutto, alte Charts | netto, alte Charts | netto, neue Charts | Rake des ganzen Tisches |
|
||||
|---|---|---|---|---|---|
|
||||
| heads-up | Calling Station | +280,0 ± 23,8 | +288,9 ± 26,3 | +288,9 ± 26,3 | 42,9 |
|
||||
| heads-up | Folder | +75,0 ± 0 | +91,0 ± 0 | +91,0 ± 0 | 0 |
|
||||
| heads-up | Zufall | +168,2 ± 65,9 | +152,7 ± 65,0 | +152,7 ± 65,0 | 16,7 |
|
||||
| 6-max | Calling Station | +118,3 ± 73,2 | +110,1 ± 76,5 | +110,1 ± 76,5 | 40,0 |
|
||||
| 6-max | Folder | +37,1 ± 3,3 | +53,5 ± 5,1 | +53,5 ± 5,1 | 2,4 |
|
||||
| 6-max | Zufall | +670,8 ± 169,7 | +649,7 ± 171,0 | +679,3 ± 169,7 | 84,3 |
|
||||
|
||||
Netto liegt teils über brutto, weil die Antes dem Gewinner zufallen. Heads-up nutzt keine CFR-Tabelle. Keine Änderung durch die neuen Charts liegt außerhalb des Intervalls: Diese Gegner schauen nicht auf ihre Karten und prüfen Vorflop-Grenzen kaum.
|
||||
|
||||
## Große Runde 2026-10-29: Stärke, Einsatzplan, ICM-lite
|
||||
|
||||
**Kern** (`engine/size_policy.rs`, `icm/`, Änderungen in `decide`, `options`, `postflop`, `bluff`, `cfr_advice`, `sizing/preflop`):
|
||||
@@ -376,7 +400,7 @@ Die Bubble callt nie eine Hand, die Cash foldet. Öffnen und Shoven verschiebt d
|
||||
- `bluff_fold_chance`, `bluff_share`, `bluff_range`
|
||||
- `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)
|
||||
- **CFR:** `cfr_kuhn`, `cfr_games`, `cfr_equity`, `cfr_hand_class`, `cfr_three_way`, `cfr_nash`, `generated_charts_*`, `preflop_cfr_advice`, `cfr_rake`, `rake_rule`, `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 A5o 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)
|
||||
- **Größen und Turnier:** `engine_size_policy` (Commitment-Leiter, Bänder, Pot-Kontrolle, Stapelbänder), `icm_bubble` (Harville, Bubble enger als Cash, ohne Lage bitgleich), `pipeline_tournament` (Feld `tournament` über `respond`, kaputte und unbepreisbare Lagen, Feld über 10 Spieler per Stichprobe)
|
||||
- **Vertrag:** `pipeline_contract` mit dem Beispiel aus VERTRAG.md
|
||||
|
||||
+91
-72
@@ -1,72 +1,91 @@
|
||||
//! Everything a game builder needs to know about the deck: rules, exact deal weights, the
|
||||
//! equity matrix and the strength order of the classes.
|
||||
|
||||
use super::chance_table::{chance_table, ChanceTable};
|
||||
use super::chart_deck::ChartDeck;
|
||||
use super::equity_matrix::EquityMatrix;
|
||||
use super::frozen_equity::frozen_equity_for;
|
||||
use super::hand_class::{classes_in, CLASS_COUNT};
|
||||
use crate::fault::Fault;
|
||||
use crate::variant::{rules, Rules};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Environment {
|
||||
pub rules: Rules,
|
||||
pub equity: EquityMatrix,
|
||||
pub chance: ChanceTable,
|
||||
/// Classes of the deck, strongest first: by all-in equity against a uniformly random hand.
|
||||
pub order: Vec<usize>,
|
||||
}
|
||||
|
||||
impl Environment {
|
||||
/// Two-card games only (the classes are two-card hands).
|
||||
pub fn new(rules: &Rules, equity: EquityMatrix) -> Result<Environment, Fault> {
|
||||
if rules.hole_cards != 2 {
|
||||
return Err(Fault::Invalid {
|
||||
field: "rules".into(),
|
||||
detail: "hand classes need exactly two hole cards".into(),
|
||||
});
|
||||
}
|
||||
let chance = chance_table(rules.deck);
|
||||
let vs_random = |c: usize| -> f64 {
|
||||
let (num, den) = (0..CLASS_COUNT).fold((0.0, 0.0), |(n, d), j| {
|
||||
let p = chance.probability(c, j);
|
||||
(n + p * equity.get(c, j), d + p)
|
||||
});
|
||||
if den > 0.0 {
|
||||
num / den
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
};
|
||||
let mut order = classes_in(rules.deck);
|
||||
order.sort_by(|a, b| {
|
||||
vs_random(*b).partial_cmp(&vs_random(*a)).unwrap_or(std::cmp::Ordering::Equal).then(a.cmp(b))
|
||||
});
|
||||
Ok(Environment { rules: *rules, equity, chance, order })
|
||||
}
|
||||
|
||||
/// Full deck, hold'em rules, the frozen equity table.
|
||||
pub fn frozen() -> Environment {
|
||||
Environment::frozen_for(ChartDeck::Full)
|
||||
}
|
||||
|
||||
/// The deck's rules and its frozen equity table.
|
||||
pub fn frozen_for(deck: ChartDeck) -> Environment {
|
||||
let variant = deck.variant();
|
||||
Environment::new(&rules(variant), frozen_equity_for(deck)).unwrap_or_else(|_| {
|
||||
// Unreachable: both rule sets have two hole cards. Kept total instead of panicking.
|
||||
let r = rules(variant);
|
||||
Environment {
|
||||
rules: r,
|
||||
equity: EquityMatrix::neutral(),
|
||||
chance: chance_table(r.deck),
|
||||
order: classes_in(r.deck),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn classes(&self) -> usize {
|
||||
CLASS_COUNT
|
||||
}
|
||||
}
|
||||
//! Everything a game builder needs to know about the deck: rules, exact deal weights, the
|
||||
//! equity matrix and the strength order of the classes.
|
||||
|
||||
use super::chance_table::{chance_table, ChanceTable};
|
||||
use super::chart_deck::ChartDeck;
|
||||
use super::equity_matrix::EquityMatrix;
|
||||
use super::frozen_equity::frozen_equity_for;
|
||||
use super::hand_class::{classes_in, CLASS_COUNT};
|
||||
use crate::fault::Fault;
|
||||
use crate::rake::{ChartRake, CHART_ANTES_BB};
|
||||
use crate::variant::{rules, Rules};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Environment {
|
||||
pub rules: Rules,
|
||||
pub equity: EquityMatrix,
|
||||
pub chance: ChanceTable,
|
||||
/// Classes of the deck, strongest first: by all-in equity against a uniformly random hand.
|
||||
pub order: Vec<usize>,
|
||||
/// What the leaves pay. The hold'em tables are derived with the measured rake; short deck has
|
||||
/// no measured table and stays without.
|
||||
pub rake: ChartRake,
|
||||
/// Antes of the whole table, bb: dead money in every pot, the winner of a fold takes them too.
|
||||
/// A constant per player does not change a decision, so nobody's own ante is subtracted.
|
||||
pub antes: f64,
|
||||
}
|
||||
|
||||
impl Environment {
|
||||
/// Two-card games only (the classes are two-card hands).
|
||||
pub fn new(rules: &Rules, equity: EquityMatrix) -> Result<Environment, Fault> {
|
||||
if rules.hole_cards != 2 {
|
||||
return Err(Fault::Invalid {
|
||||
field: "rules".into(),
|
||||
detail: "hand classes need exactly two hole cards".into(),
|
||||
});
|
||||
}
|
||||
let chance = chance_table(rules.deck);
|
||||
let vs_random = |c: usize| -> f64 {
|
||||
let (num, den) = (0..CLASS_COUNT).fold((0.0, 0.0), |(n, d), j| {
|
||||
let p = chance.probability(c, j);
|
||||
(n + p * equity.get(c, j), d + p)
|
||||
});
|
||||
if den > 0.0 {
|
||||
num / den
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
};
|
||||
let mut order = classes_in(rules.deck);
|
||||
order.sort_by(|a, b| {
|
||||
vs_random(*b).partial_cmp(&vs_random(*a)).unwrap_or(std::cmp::Ordering::Equal).then(a.cmp(b))
|
||||
});
|
||||
Ok(Environment { rules: *rules, equity, chance, order, rake: ChartRake::None, antes: 0.0 })
|
||||
}
|
||||
|
||||
/// Full deck, hold'em rules, the frozen equity table, the measured rake and antes.
|
||||
pub fn frozen() -> Environment {
|
||||
Environment::frozen_for(ChartDeck::Full)
|
||||
}
|
||||
|
||||
/// `frozen` without rake and antes: a zero-sum game.
|
||||
pub fn frozen_free_table() -> Environment {
|
||||
Environment { rake: ChartRake::None, antes: 0.0, ..Environment::frozen() }
|
||||
}
|
||||
|
||||
/// The deck's rules and its frozen equity table.
|
||||
pub fn frozen_for(deck: ChartDeck) -> Environment {
|
||||
let variant = deck.variant();
|
||||
let (rake, antes) = match deck {
|
||||
ChartDeck::Full => (ChartRake::Measured, CHART_ANTES_BB),
|
||||
ChartDeck::Short => (ChartRake::None, 0.0),
|
||||
};
|
||||
let env = Environment::new(&rules(variant), frozen_equity_for(deck)).unwrap_or_else(|_| {
|
||||
// Unreachable: both rule sets have two hole cards. Kept total instead of panicking.
|
||||
let r = rules(variant);
|
||||
Environment {
|
||||
rules: r,
|
||||
equity: EquityMatrix::neutral(),
|
||||
chance: chance_table(r.deck),
|
||||
order: classes_in(r.deck),
|
||||
rake: ChartRake::None,
|
||||
antes: 0.0,
|
||||
}
|
||||
});
|
||||
Environment { rake, antes, ..env }
|
||||
}
|
||||
|
||||
pub fn classes(&self) -> usize {
|
||||
CLASS_COUNT
|
||||
}
|
||||
}
|
||||
|
||||
+12
-3
@@ -40,6 +40,7 @@ use super::spot_params::{
|
||||
};
|
||||
use super::wake_range::{equity_against, top_membership};
|
||||
use crate::fault::Fault;
|
||||
use crate::rake::ChartRake;
|
||||
use crate::variant::DeckRule;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
@@ -85,7 +86,11 @@ pub fn three_bet_size(place: Place) -> f64 {
|
||||
}
|
||||
}
|
||||
|
||||
/// Spread of a pot that pays raw equity.
|
||||
const ALL_IN_SPREAD: f64 = 1.0;
|
||||
|
||||
struct Builder {
|
||||
rake: ChartRake,
|
||||
equity: Vec<f64>,
|
||||
places: Vec<Place>,
|
||||
posted: Vec<f64>,
|
||||
@@ -121,6 +126,9 @@ impl Builder {
|
||||
fn pot(&self, members: Vec<usize>, amount: f64, realization: f64, spread: f64) -> MultiOutcome {
|
||||
let invested = self.invested(&members, amount);
|
||||
let pot = invested.iter().sum::<f64>() + self.dead;
|
||||
// Spread 1 and equal weights mean an all-in; anything else leaves chips behind.
|
||||
let rake = if spread == ALL_IN_SPREAD { self.rake.all_in(pot) } else { self.rake.postflop(pot) };
|
||||
let pot = pot - rake;
|
||||
let last = members.iter().copied().max_by_key(|p| self.places[*p].postflop_order()).unwrap_or(0);
|
||||
let weights: Vec<f64> = members.iter().map(|p| if *p == last { 1.0 } else { realization }).collect();
|
||||
let pair_share = if members.len() == 2 {
|
||||
@@ -178,7 +186,7 @@ impl Builder {
|
||||
jam_folded[i] = y;
|
||||
let t_jam_folded = self.uncontested(0, &jam_folded);
|
||||
let t_jam_folded = self.add(MultiNode::Terminal(t_jam_folded));
|
||||
let jam_called = self.pot(vec![0, i], s, 1.0, 1.0);
|
||||
let jam_called = self.pot(vec![0, i], s, 1.0, ALL_IN_SPREAD);
|
||||
let t_jam_called = self.add(MultiNode::Terminal(jam_called));
|
||||
let vs_jam = self.add(MultiNode::Decision {
|
||||
player: i,
|
||||
@@ -204,7 +212,7 @@ pub fn multi_open_tree(env: &Environment, seat: Seat, defenders: usize, depth_bb
|
||||
let x = open_size(seat);
|
||||
let n = CLASS_COUNT;
|
||||
let equity: Vec<f64> = (0..n * n).map(|k| env.equity.get(k / n, k % n)).collect();
|
||||
let mut b = Builder { equity: equity.clone(), places: places.clone(), posted: posted.clone(), dead: lineup.dead_money(), open: x, depth: depth_bb, nodes: Vec::new() };
|
||||
let mut b = Builder { rake: env.rake, equity: equity.clone(), places: places.clone(), posted: posted.clone(), dead: lineup.dead_money() + env.antes, open: x, depth: depth_bb, nodes: Vec::new() };
|
||||
|
||||
let mut fold_row = vec![0.0; places.len()];
|
||||
fold_row[0] = -posted[0];
|
||||
@@ -214,7 +222,8 @@ pub fn multi_open_tree(env: &Environment, seat: Seat, defenders: usize, depth_bb
|
||||
let raised = if r < 1.0 {
|
||||
let wake = equity_against(env, &top_membership(env, WAKE_FRACTION));
|
||||
let ip = lineup.in_position_against_field();
|
||||
let pot = 2.0 * x + lineup.dead_money() + posted.iter().skip(1).sum::<f64>();
|
||||
let pot = 2.0 * x + lineup.dead_money() + env.antes + posted.iter().skip(1).sum::<f64>();
|
||||
let pot = pot - env.rake.postflop(pot);
|
||||
let values = wake.iter().map(|e| pot * share(*e, ip, REALIZATION_OOP_SINGLE_RAISED) - x).collect();
|
||||
let rest = posted.iter().enumerate().map(|(p, v)| if p == 0 { 0.0 } else { -v }).collect();
|
||||
let t_woken = b.add(MultiNode::Terminal(MultiOutcome::Own { player: 0, values, rest }));
|
||||
|
||||
+16
-13
@@ -64,6 +64,9 @@ pub fn open3_tree(env: &Environment, seat: Seat, depth_bb: f64) -> Result<Tree3,
|
||||
nodes.push(node);
|
||||
nodes.len() - 1
|
||||
};
|
||||
let a = env.antes;
|
||||
let after_postflop_rake = |pot: f64| pot + a - env.rake.postflop(pot + a);
|
||||
let after_all_in_rake = |pot: f64| pot + a - env.rake.all_in(pot + a);
|
||||
let heads = |b: usize, pot: f64, invested: [f64; 3], share: &Vec<f64>| Node3::Terminal(Outcome::Heads {
|
||||
a: 0,
|
||||
b,
|
||||
@@ -74,12 +77,12 @@ pub fn open3_tree(env: &Environment, seat: Seat, depth_bb: f64) -> Result<Tree3,
|
||||
|
||||
// Small blind folds: the big blind's tree, the small blind dead.
|
||||
let t_open_fold = add(Node3::Terminal(Outcome::Flat([0.0, 0.0, 0.0])));
|
||||
let t_blinds_fold = add(Node3::Terminal(Outcome::Flat([sb + bb, -sb, -bb])));
|
||||
let t_bb_calls = add(heads(2, 2.0 * x + sb, [x, sb, x], &single));
|
||||
let t_opener_folds_bb = add(Node3::Terminal(Outcome::Flat([-x, -sb, x + sb])));
|
||||
let t_bb_three_bet_called = add(heads(2, 2.0 * y + sb, [y, sb, y], &three_bet));
|
||||
let t_bb_folds_jam = add(Node3::Terminal(Outcome::Flat([y + sb, -sb, -y])));
|
||||
let t_bb_calls_jam = add(heads(2, 2.0 * s + sb, [s, sb, s], &jam));
|
||||
let t_blinds_fold = add(Node3::Terminal(Outcome::Flat([sb + bb + a, -sb, -bb])));
|
||||
let t_bb_calls = add(heads(2, after_postflop_rake(2.0 * x + sb), [x, sb, x], &single));
|
||||
let t_opener_folds_bb = add(Node3::Terminal(Outcome::Flat([-x, -sb, x + sb + a])));
|
||||
let t_bb_three_bet_called = add(heads(2, after_postflop_rake(2.0 * y + sb), [y, sb, y], &three_bet));
|
||||
let t_bb_folds_jam = add(Node3::Terminal(Outcome::Flat([y + sb + a, -sb, -y])));
|
||||
let t_bb_calls_jam = add(heads(2, after_all_in_rake(2.0 * s + sb), [s, sb, s], &jam));
|
||||
let vs_jam = add(Node3::Decision { player: 2, name: "vs_jam", children: vec![t_bb_folds_jam, t_bb_calls_jam] });
|
||||
let vs_three_bet = add(Node3::Decision {
|
||||
player: 0,
|
||||
@@ -90,9 +93,9 @@ pub fn open3_tree(env: &Environment, seat: Seat, depth_bb: f64) -> Result<Tree3,
|
||||
add(Node3::Decision { player: 2, name: "defend", children: vec![t_blinds_fold, t_bb_calls, vs_three_bet] });
|
||||
|
||||
// Small blind calls: the big blind folds or makes it three-way.
|
||||
let t_bb_folds_behind = add(heads(1, 2.0 * x + bb, [x, x, bb], &single));
|
||||
let t_bb_folds_behind = add(heads(1, after_postflop_rake(2.0 * x + bb), [x, x, bb], &single));
|
||||
let t_three_way = add(Node3::Terminal(Outcome::Three {
|
||||
pot: 3.0 * x,
|
||||
pot: after_postflop_rake(3.0 * x),
|
||||
invested: [x, x, x],
|
||||
weights: blinds_oop,
|
||||
spread: REALIZATION_SPREAD,
|
||||
@@ -101,10 +104,10 @@ pub fn open3_tree(env: &Environment, seat: Seat, depth_bb: f64) -> Result<Tree3,
|
||||
add(Node3::Decision { player: 2, name: "bb_overcall", children: vec![t_bb_folds_behind, t_three_way] });
|
||||
|
||||
// Small blind 3-bets: the big blind is out.
|
||||
let t_opener_folds_sb = add(Node3::Terminal(Outcome::Flat([-x, x + bb, -bb])));
|
||||
let t_sb_three_bet_called = add(heads(1, 2.0 * z + bb, [z, z, bb], &three_bet));
|
||||
let t_sb_folds_jam = add(Node3::Terminal(Outcome::Flat([z + bb, -z, -bb])));
|
||||
let t_sb_calls_jam = add(heads(1, 2.0 * s + bb, [s, s, bb], &jam));
|
||||
let t_opener_folds_sb = add(Node3::Terminal(Outcome::Flat([-x, x + bb + a, -bb])));
|
||||
let t_sb_three_bet_called = add(heads(1, after_postflop_rake(2.0 * z + bb), [z, z, bb], &three_bet));
|
||||
let t_sb_folds_jam = add(Node3::Terminal(Outcome::Flat([z + bb + a, -z, -bb])));
|
||||
let t_sb_calls_jam = add(heads(1, after_all_in_rake(2.0 * s + bb), [s, s, bb], &jam));
|
||||
let sb_vs_jam =
|
||||
add(Node3::Decision { player: 1, name: "sb_vs_jam", children: vec![t_sb_folds_jam, t_sb_calls_jam] });
|
||||
let vs_sb_three_bet = add(Node3::Decision {
|
||||
@@ -120,7 +123,7 @@ pub fn open3_tree(env: &Environment, seat: Seat, depth_bb: f64) -> Result<Tree3,
|
||||
player: 0,
|
||||
values: wake
|
||||
.iter()
|
||||
.map(|e| (2.0 * x + sb + bb) * share(*e, wake_ip, REALIZATION_OOP_SINGLE_RAISED) - x)
|
||||
.map(|e| after_postflop_rake(2.0 * x + sb + bb) * share(*e, wake_ip, REALIZATION_OOP_SINGLE_RAISED) - x)
|
||||
.collect(),
|
||||
rest: [0.0, -sb, -bb],
|
||||
};
|
||||
|
||||
@@ -41,14 +41,16 @@ pub fn open_tree(env: &Environment, seat: Seat, depth_bb: f64) -> Result<Tree, F
|
||||
});
|
||||
}
|
||||
let (s, x, y) = (depth_bb, open_size(seat), THREE_BET_SIZE);
|
||||
let dead = seat.dead_money();
|
||||
let dead = seat.dead_money() + env.antes;
|
||||
let ip = seat.is_in_position_against_big_blind();
|
||||
let r = field_folds(seat.players_behind());
|
||||
let wake = equity_against(env, &top_membership(env, WAKE_FRACTION));
|
||||
let wake_ip = seat == Seat::Button;
|
||||
let wake_pot = 2.0 * x + SMALL_BLIND + BIG_BLIND + env.antes;
|
||||
let wake_pot = wake_pot - env.rake.postflop(wake_pot);
|
||||
let wake_payoff = Payoff::Own(
|
||||
wake.iter()
|
||||
.map(|e| (2.0 * x + SMALL_BLIND + BIG_BLIND) * share(*e, wake_ip, REALIZATION_OOP_SINGLE_RAISED) - x)
|
||||
.map(|e| wake_pot * share(*e, wake_ip, REALIZATION_OOP_SINGLE_RAISED) - x)
|
||||
.collect(),
|
||||
);
|
||||
|
||||
|
||||
+47
-41
@@ -1,41 +1,47 @@
|
||||
//! Payoff matrices for the two kinds of showdown the games use. `u(i, j)` is always the net
|
||||
//! result in bb for player 0 (invested chips already subtracted).
|
||||
|
||||
use super::environment::Environment;
|
||||
use super::hand_class::CLASS_COUNT;
|
||||
use super::spot_params::REALIZATION_SPREAD;
|
||||
use super::tree::Payoff;
|
||||
|
||||
fn matrix(env: &Environment, f: impl Fn(f64) -> f64) -> Payoff {
|
||||
Payoff::Pair(
|
||||
(0..CLASS_COUNT * CLASS_COUNT)
|
||||
.map(|k| f(env.equity.get(k / CLASS_COUNT, k % CLASS_COUNT)))
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
/// All-in showdown: raw equity of the whole pot.
|
||||
pub fn all_in(env: &Environment, pot: f64, invested: f64) -> Payoff {
|
||||
matrix(env, |eq| pot * eq - invested)
|
||||
}
|
||||
|
||||
/// Pot not yet decided by chips: each side gets `share` of it (see `share`).
|
||||
/// `player0_in_position` says who is who.
|
||||
pub fn postflop(env: &Environment, pot: f64, invested: f64, player0_in_position: bool, realization: f64) -> Payoff {
|
||||
matrix(env, |eq| pot * share(eq, player0_in_position, realization) - invested)
|
||||
}
|
||||
|
||||
/// Player 0's share of the pot given his all-in equity: stretch the equity around 50 % by
|
||||
/// `REALIZATION_SPREAD`, weight the out-of-position side by `realization`, split in proportion.
|
||||
/// The two players' shares always add up to 1.
|
||||
pub fn share(equity: f64, player0_in_position: bool, realization: f64) -> f64 {
|
||||
let stretched = (0.5 + REALIZATION_SPREAD * (equity - 0.5)).clamp(0.0, 1.0);
|
||||
let (ip, oop) = if player0_in_position {
|
||||
(stretched, realization * (1.0 - stretched))
|
||||
} else {
|
||||
(1.0 - stretched, realization * stretched)
|
||||
};
|
||||
let total = ip + oop;
|
||||
let ip_share = if total > 0.0 { ip / total } else { 0.5 };
|
||||
if player0_in_position { ip_share } else { 1.0 - ip_share }
|
||||
}
|
||||
//! Payoff matrices for the two kinds of showdown the games use. `u(i, j)` is always the net
|
||||
//! result in bb for player 0 (invested chips already subtracted). The pot is split after the
|
||||
//! rake of `env`; a fold pays none.
|
||||
|
||||
use super::environment::Environment;
|
||||
use super::hand_class::CLASS_COUNT;
|
||||
use super::spot_params::REALIZATION_SPREAD;
|
||||
use super::tree::Payoff;
|
||||
|
||||
fn matrix(env: &Environment, rake: f64, f: impl Fn(f64) -> f64) -> Payoff {
|
||||
let pair = (0..CLASS_COUNT * CLASS_COUNT)
|
||||
.map(|k| f(env.equity.get(k / CLASS_COUNT, k % CLASS_COUNT)))
|
||||
.collect();
|
||||
if rake > 0.0 {
|
||||
Payoff::Raked { pair, rake }
|
||||
} else {
|
||||
Payoff::Pair(pair)
|
||||
}
|
||||
}
|
||||
|
||||
/// All-in showdown: raw equity of the whole pot.
|
||||
pub fn all_in(env: &Environment, pot: f64, invested: f64) -> Payoff {
|
||||
let rake = env.rake.all_in(pot);
|
||||
matrix(env, rake, |eq| (pot - rake) * eq - invested)
|
||||
}
|
||||
|
||||
/// Pot not yet decided by chips: each side gets `share` of it (see `share`).
|
||||
/// `player0_in_position` says who is who.
|
||||
pub fn postflop(env: &Environment, pot: f64, invested: f64, player0_in_position: bool, realization: f64) -> Payoff {
|
||||
let rake = env.rake.postflop(pot);
|
||||
matrix(env, rake, |eq| (pot - rake) * share(eq, player0_in_position, realization) - invested)
|
||||
}
|
||||
|
||||
/// Player 0's share of the pot given his all-in equity: stretch the equity around 50 % by
|
||||
/// `REALIZATION_SPREAD`, weight the out-of-position side by `realization`, split in proportion.
|
||||
/// The two players' shares always add up to 1.
|
||||
pub fn share(equity: f64, player0_in_position: bool, realization: f64) -> f64 {
|
||||
let stretched = (0.5 + REALIZATION_SPREAD * (equity - 0.5)).clamp(0.0, 1.0);
|
||||
let (ip, oop) = if player0_in_position {
|
||||
(stretched, realization * (1.0 - stretched))
|
||||
} else {
|
||||
(1.0 - stretched, realization * stretched)
|
||||
};
|
||||
let total = ip + oop;
|
||||
let ip_share = if total > 0.0 { ip / total } else { 0.5 };
|
||||
if player0_in_position { ip_share } else { 1.0 - ip_share }
|
||||
}
|
||||
|
||||
@@ -47,6 +47,8 @@ pub fn push_fold3_tree(env: &Environment, seat: Seat, depth_bb: f64) -> Result<T
|
||||
let wake = equity_against(env, &top_membership(env, WAKE_FRACTION));
|
||||
let r = field_folds(seat.players_before_blinds());
|
||||
let heads = all_in_share(env);
|
||||
let a = env.antes;
|
||||
let after_rake = |pot: f64| pot + a - env.rake.all_in(pot + a);
|
||||
|
||||
let mut nodes: Vec<Node3> = Vec::new();
|
||||
let mut add = |node: Node3| -> usize {
|
||||
@@ -54,13 +56,13 @@ pub fn push_fold3_tree(env: &Environment, seat: Seat, depth_bb: f64) -> Result<T
|
||||
nodes.len() - 1
|
||||
};
|
||||
let t_fold = add(Node3::Terminal(Outcome::Flat([0.0, 0.0, 0.0])));
|
||||
let t_blinds_fold = add(Node3::Terminal(Outcome::Flat([sb + bb, -sb, -bb])));
|
||||
let t_blinds_fold = add(Node3::Terminal(Outcome::Flat([sb + bb + a, -sb, -bb])));
|
||||
let t_big_blind_calls =
|
||||
add(Node3::Terminal(Outcome::Heads { a: 0, b: 2, pot: 2.0 * s + sb, invested: [s, sb, s], share: heads.clone() }));
|
||||
add(Node3::Terminal(Outcome::Heads { a: 0, b: 2, pot: after_rake(2.0 * s + sb), invested: [s, sb, s], share: heads.clone() }));
|
||||
let t_small_blind_calls =
|
||||
add(Node3::Terminal(Outcome::Heads { a: 0, b: 1, pot: 2.0 * s + bb, invested: [s, s, bb], share: heads }));
|
||||
add(Node3::Terminal(Outcome::Heads { a: 0, b: 1, pot: after_rake(2.0 * s + bb), invested: [s, s, bb], share: heads }));
|
||||
let t_three_way =
|
||||
add(Node3::Terminal(Outcome::Three { pot: 3.0 * s, invested: [s, s, s], weights: [1.0; 3], spread: 1.0 }));
|
||||
add(Node3::Terminal(Outcome::Three { pot: after_rake(3.0 * s), invested: [s, s, s], weights: [1.0; 3], spread: 1.0 }));
|
||||
let call = add(Node3::Decision { player: 2, name: "call", children: vec![t_blinds_fold, t_big_blind_calls] });
|
||||
let overcall =
|
||||
add(Node3::Decision { player: 2, name: "bb_overcall", children: vec![t_small_blind_calls, t_three_way] });
|
||||
@@ -68,7 +70,7 @@ pub fn push_fold3_tree(env: &Environment, seat: Seat, depth_bb: f64) -> Result<T
|
||||
let pushed = if r < 1.0 {
|
||||
let woken = Outcome::Own {
|
||||
player: 0,
|
||||
values: wake.iter().map(|e| e * (2.0 * s + sb + bb) - s).collect(),
|
||||
values: wake.iter().map(|e| e * after_rake(2.0 * s + sb + bb) - s).collect(),
|
||||
rest: [0.0, -sb, -bb],
|
||||
};
|
||||
let t_woken = add(Node3::Terminal(woken));
|
||||
|
||||
@@ -27,9 +27,11 @@ pub fn push_fold_tree(env: &Environment, seat: Seat, depth_bb: f64) -> Result<Tr
|
||||
return Err(Fault::Invalid { field: "depth_bb".into(), detail: "stack must be at least 1.5 bb".into() });
|
||||
}
|
||||
let s = depth_bb;
|
||||
let dead = seat.dead_money();
|
||||
let dead = seat.dead_money() + env.antes;
|
||||
let wake = equity_against(env, &top_membership(env, WAKE_FRACTION));
|
||||
let wake_payoff = Payoff::Own(wake.iter().map(|e| e * (2.0 * s + SMALL_BLIND + BIG_BLIND) - s).collect());
|
||||
let wake_pot = 2.0 * s + SMALL_BLIND + BIG_BLIND + env.antes;
|
||||
let wake_pot = wake_pot - env.rake.all_in(wake_pot);
|
||||
let wake_payoff = Payoff::Own(wake.iter().map(|e| e * wake_pot - s).collect());
|
||||
let r = field_folds(seat.players_behind());
|
||||
|
||||
// Built bottom-up; indices are fixed by push order.
|
||||
|
||||
@@ -38,7 +38,7 @@ fn header(deck: ChartDeck) -> String {
|
||||
//! weight is the product of the three pairwise compatibilities (`cfr::tree3`).
|
||||
//! - Class-vs-class all-in equity: seeded Monte Carlo, `hand::showdown::judge`. Three-way pots
|
||||
//! split by the weaker pairwise equity of each hand, normalised (`cfr::three_way`).
|
||||
//! - Blinds 0.5 / 1, 6-max. EP, MP, CO and BTN face BOTH blinds as players (three-player games);
|
||||
{rake_note}//! - Blinds 0.5 / 1, 6-max. EP, MP, CO and BTN face BOTH blinds as players (three-player games);
|
||||
//! the small blind as first actor faces the big blind. Players between the first actor and the
|
||||
//! small blind are a multiway tax: each holds a continuing hand (top {wake:.0} % of combos) with
|
||||
//! probability {wake_p:.2}; if one does, the first actor is simply called by that range.
|
||||
@@ -67,6 +67,7 @@ fn header(deck: ChartDeck) -> String {
|
||||
charts = deck.charts_file(),
|
||||
equity = deck.equity_file(),
|
||||
deck = deck_lines(deck),
|
||||
rake_note = rake_lines(deck),
|
||||
wake = WAKE_FRACTION * 100.0,
|
||||
wake_p = WAKE_FRACTION,
|
||||
open = OPEN_SIZE,
|
||||
@@ -79,6 +80,18 @@ fn header(deck: ChartDeck) -> String {
|
||||
)
|
||||
}
|
||||
|
||||
fn rake_lines(deck: ChartDeck) -> &'static str {
|
||||
match deck {
|
||||
ChartDeck::Full => "\
|
||||
//! - Rake (`crate::rake`, measured at the table 1000/2000, ante 0.16 bb): a fold pays none, an
|
||||
//! all-in 5 % of the pot with the antes, capped at 1 bb; a pot with chips behind the mean rake of
|
||||
//! such flop pots at that table. The pot is split after the rake, so the games are not zero-sum.
|
||||
//! Antes of six seats are dead money in every pot; the winner of a fold takes them too.
|
||||
",
|
||||
ChartDeck::Short => "",
|
||||
}
|
||||
}
|
||||
|
||||
fn meta_line(label: &str, meta: &SpotMeta) -> String {
|
||||
let curve: Vec<String> = meta.checkpoints.iter().map(|(_, e)| e.to_string()).collect();
|
||||
format!(
|
||||
|
||||
@@ -202,6 +202,10 @@ fn header(evidence: &[Evidence], spots: &[MultiRecord]) -> String {
|
||||
//! weakest pairwise equity, normalised (`cfr::multi_shares`, two hands: the equity itself),
|
||||
//! stretched by {spread} around the even share, the player last to act postflop weighted 1.0,
|
||||
//! everybody else {oop} ({oop3} in 3-bet pots), normalised again.
|
||||
//! - Rake (`crate::rake`, measured at the table 1000/2000, ante 0.16 bb): a fold pays none, an
|
||||
//! all-in 5 % of the pot with the antes, capped at 1 bb; a pot with chips behind the mean rake of
|
||||
//! such flop pots at that table. The pot is split after the rake, so the games are not zero-sum.
|
||||
//! Antes of six seats are dead money in every pot; the winner of a fold takes them too.
|
||||
//! - Solver: chance-sampled CFR+ (one deal per iteration, every player traverses with its own
|
||||
//! class open over all 169 classes, the others' actions weighted by their strategy), regrets
|
||||
//! floored at 0, average weighted by iteration; {iterations} iterations from seed {cfr_seed}.
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! Counterfactual value of a terminal node for one traverser, given the opponent's reach.
|
||||
//!
|
||||
//! For player 0: `value[i] = sum_j chance[i][j] * opp[j] * payoff(i, j)`.
|
||||
//! For player 1: `value[j] = -sum_i chance[i][j] * opp[i] * payoff(i, j)` (zero-sum).
|
||||
//! For player 1: `value[j] = -sum_i chance[i][j] * opp[i] * (payoff(i, j) + rake)`; the rake is 0
|
||||
//! on every leaf but `Payoff::Raked`, so the rest of the game is zero-sum.
|
||||
//! The traverser's own reach is not part of the value.
|
||||
|
||||
use super::tree::Payoff;
|
||||
@@ -12,13 +13,17 @@ pub fn terminal_value(payoff: &Payoff, chance: &[f64], classes: usize, player: u
|
||||
for i in 0..n {
|
||||
let row = &chance[i * n..(i + 1) * n];
|
||||
let pair_row = match payoff {
|
||||
Payoff::Pair(m) => m.get(i * n..(i + 1) * n),
|
||||
Payoff::Pair(m) | Payoff::Raked { pair: m, .. } => m.get(i * n..(i + 1) * n),
|
||||
_ => None,
|
||||
};
|
||||
let rake = match payoff {
|
||||
Payoff::Raked { rake, .. } => *rake,
|
||||
_ => 0.0,
|
||||
};
|
||||
let scale = match payoff {
|
||||
Payoff::Flat(c) => *c,
|
||||
Payoff::Own(v) => v.get(i).copied().unwrap_or(0.0),
|
||||
Payoff::Pair(_) => 1.0,
|
||||
Payoff::Pair(_) | Payoff::Raked { .. } => 1.0,
|
||||
};
|
||||
if player == 0 {
|
||||
let mut acc = 0.0;
|
||||
@@ -28,7 +33,7 @@ pub fn terminal_value(payoff: &Payoff, chance: &[f64], classes: usize, player: u
|
||||
acc += row[j] * opp[j] * m[j];
|
||||
}
|
||||
}
|
||||
None if matches!(payoff, Payoff::Pair(_)) => {}
|
||||
None if matches!(payoff, Payoff::Pair(_) | Payoff::Raked { .. }) => {}
|
||||
None => {
|
||||
for j in 0..n {
|
||||
acc += row[j] * opp[j];
|
||||
@@ -45,10 +50,10 @@ pub fn terminal_value(payoff: &Payoff, chance: &[f64], classes: usize, player: u
|
||||
match pair_row {
|
||||
Some(m) => {
|
||||
for j in 0..n {
|
||||
out[j] -= row[j] * weight * m[j];
|
||||
out[j] -= row[j] * weight * (m[j] + rake);
|
||||
}
|
||||
}
|
||||
None if matches!(payoff, Payoff::Pair(_)) => {}
|
||||
None if matches!(payoff, Payoff::Pair(_) | Payoff::Raked { .. }) => {}
|
||||
None => {
|
||||
for j in 0..n {
|
||||
out[j] -= row[j] * weight * scale;
|
||||
|
||||
+4
-1
@@ -3,7 +3,8 @@
|
||||
//!
|
||||
//! - Player 0 holds class `i`, player 1 holds class `j`; `chance[i * classes + j]` is the
|
||||
//! probability of that deal (card removal is already inside).
|
||||
//! - Every payoff is the result for player 0; player 1 receives the negative (zero-sum).
|
||||
//! - Every payoff is the result for player 0; player 1 receives the negative (zero-sum), minus the
|
||||
//! rake where a leaf pays one (`Payoff::Raked`).
|
||||
//! - A node is a decision of one player (children = actions), a chance split with fixed
|
||||
//! probabilities (e.g. "the field behind folds"), or a terminal payoff.
|
||||
|
||||
@@ -15,6 +16,8 @@ pub enum Payoff {
|
||||
Own(Vec<f64>),
|
||||
/// Depends on both classes (`classes * classes` entries, `[i * classes + j]`).
|
||||
Pair(Vec<f64>),
|
||||
/// `pair` is player 0's result after the rake; player 1 receives `-(pair + rake)`.
|
||||
Raked { pair: Vec<f64>, rake: f64 },
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
|
||||
@@ -16,6 +16,7 @@ pub mod icm;
|
||||
pub mod json;
|
||||
pub mod odds;
|
||||
pub mod preflop;
|
||||
pub mod rake;
|
||||
pub mod read;
|
||||
pub mod rng;
|
||||
pub mod sim;
|
||||
|
||||
+15
-2
@@ -16,7 +16,7 @@ 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::game::{SeenAction, Spot};
|
||||
use crate::variant::ActionShape;
|
||||
|
||||
/// At or below this effective stack (bb) raising ranges become jamming ranges.
|
||||
@@ -120,6 +120,19 @@ fn from_equilibrium(
|
||||
PreflopPlan { action, percentile: hand, certainty, reason }
|
||||
}
|
||||
|
||||
/// The pot minus the antes the history names: antes are dead money, not action, and six of them
|
||||
/// (2.46 bb first in, measured) would read as a limp. Without records the pot stays as it is.
|
||||
fn pot_without_antes(spot: &Spot) -> f64 {
|
||||
let antes: f64 = spot
|
||||
.history
|
||||
.iter()
|
||||
.filter(|r| r.action == SeenAction::PostAnte)
|
||||
.filter_map(|r| r.amount)
|
||||
.filter(|a| a.is_finite() && *a > 0.0)
|
||||
.sum();
|
||||
spot.pot - antes
|
||||
}
|
||||
|
||||
/// Advice for a preflop spot.
|
||||
///
|
||||
/// 1. Where the frozen CFR tables cover the spot (`cfr_advice`: NLHE and AOF, first in,
|
||||
@@ -132,7 +145,7 @@ fn from_equilibrium(
|
||||
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 situation = classify(spot.to_call, spot.big_blind, pot_without_antes(spot), spot.hero_stack);
|
||||
let depth = effective_stack_bb(spot);
|
||||
let scale = scale_for(spot, situation, thresholds);
|
||||
let row = cutoffs(spot, situation, depth, scale);
|
||||
|
||||
+2378
-2374
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
+111
@@ -0,0 +1,111 @@
|
||||
//! Rake as plain arithmetic, in the currency of the pot it is given.
|
||||
//!
|
||||
//! **Source.** `game.winnerInfo` of the client log carries `potAmount` and `potAmountAfterRake`
|
||||
//! per pot, `roomProperties` the configuration (`shell: archiv/echt/RAKE-gemessen.md`). Measured
|
||||
//! per hand at the table 1000/2000, ante 320 ("Big Ben", 1134 hands):
|
||||
//! - 5 % of the pot, antes included, capped at 1 big blind: 1023 of 1046 hands with a board match
|
||||
//! exactly. Of the others 20 are run-it-twice hands (two lines of 1000 each, together the cap)
|
||||
//! and 3 merge lines of two hands in the log.
|
||||
//! - The cap holds per hand. Side pots share it in proportion to their size (96 of 106 hands
|
||||
//! with several pots sum to exactly the cap).
|
||||
//! - A hand that ends before the flop pays nothing (86 of 86; 2 more hands show no board only
|
||||
//! because the log lost it). A preflop all-in that runs out the board does pay (319 hands).
|
||||
//!
|
||||
//! **Assumptions.** `cap_more_than_three` follows the order's reading of `rakeCapGT3` ("more than
|
||||
//! three players in the pot"). The log cannot confirm it: at 1000/2000 both caps are equal, and
|
||||
//! the micro tables contradict their configuration (0.05/0.10 configures 0.6 and 0.25 yet took
|
||||
//! 1.0 twice; 0.02/0.05 configures 0.3 and 0.13 yet took 0.5 four times, once with four players
|
||||
//! in the pot). Those tables also rake some preflop pots (`rakeGTPPf` 5). Only the rule of
|
||||
//! 1000/2000 is therefore treated as measured; no micro rule is modelled here.
|
||||
|
||||
/// Rake of one table. All amounts in the pot's currency.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct RakeRule {
|
||||
/// Percent of the pot (`rake`).
|
||||
pub percent: f64,
|
||||
/// Cap of a hand (`rakeCap`).
|
||||
pub cap: f64,
|
||||
/// Cap with more than three players in the pot (`rakeCapGT3`).
|
||||
pub cap_more_than_three: f64,
|
||||
}
|
||||
|
||||
/// How far a hand got: rake is taken once a flop is dealt, whoever is left.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum HandEnd {
|
||||
NoFlop,
|
||||
FlopDealt,
|
||||
}
|
||||
|
||||
/// Players above which `cap_more_than_three` applies.
|
||||
const PLAYERS_ON_THE_PLAIN_CAP: usize = 3;
|
||||
const PERCENT: f64 = 100.0;
|
||||
|
||||
impl RakeRule {
|
||||
/// The measured table in big blinds: 5 %, cap 1 bb (2000 at blinds 1000/2000).
|
||||
pub const MEASURED_BB: RakeRule = RakeRule { percent: 5.0, cap: 1.0, cap_more_than_three: 1.0 };
|
||||
|
||||
/// Rake of a whole hand. `pot` is everything contested, antes included, uncalled chips not.
|
||||
pub fn of_hand(&self, pot: f64, players_in_pot: usize, end: HandEnd) -> f64 {
|
||||
if end == HandEnd::NoFlop {
|
||||
return 0.0;
|
||||
}
|
||||
let cap = if players_in_pot > PLAYERS_ON_THE_PLAIN_CAP { self.cap_more_than_three } else { self.cap };
|
||||
(pot * self.percent / PERCENT).max(0.0).min(cap)
|
||||
}
|
||||
}
|
||||
|
||||
/// A hand's rake over its side pots, in proportion to their size.
|
||||
pub fn split_over_pots(rake: f64, pots: &[f64]) -> Vec<f64> {
|
||||
let total: f64 = pots.iter().sum();
|
||||
pots.iter().map(|p| if total > 0.0 { rake * p / total } else { 0.0 }).collect()
|
||||
}
|
||||
|
||||
/// The uncalled top of the highest contribution: `(player, amount)`. It goes back to that player
|
||||
/// and is no part of the pot (`potAmount` of the log does not contain it).
|
||||
pub fn uncalled(contributions: &[f64]) -> Option<(usize, f64)> {
|
||||
let mut order: Vec<usize> = (0..contributions.len()).collect();
|
||||
order.sort_by(|a, b| contributions[*b].total_cmp(&contributions[*a]));
|
||||
match order[..] {
|
||||
[top, second, ..] => Some((top, contributions[top] - contributions[second])),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Ante of the measured table in big blinds (320 at big blind 2000), per player.
|
||||
pub const MEASURED_ANTE_BB: f64 = 0.16;
|
||||
/// Seats the chart games assume for the antes in their pots.
|
||||
const CHART_SEATS: f64 = 6.0;
|
||||
/// Antes of a whole table in the chart games, bb: dead money in every pot.
|
||||
pub const CHART_ANTES_BB: f64 = CHART_SEATS * MEASURED_ANTE_BB;
|
||||
|
||||
/// Mean rake in bb of hands by their pot on the flop in bb, antes included, as upper bound of the
|
||||
/// bucket: 728 hands that saw a flop at 1000/2000. It is more than 5 % of the flop pot because the
|
||||
/// pot still grows after the flop. Above the last bound the means stop rising (0.91 to 0.95).
|
||||
const MEAN_RAKE_BY_FLOP_POT: [(f64, f64); 5] = [(6.0, 0.489), (10.0, 0.720), (15.0, 0.850), (25.0, 0.906), (f64::INFINITY, 0.950)];
|
||||
|
||||
/// What a leaf of the chart games pays, for a pot with the antes in it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ChartRake {
|
||||
None,
|
||||
Measured,
|
||||
}
|
||||
|
||||
impl ChartRake {
|
||||
/// Pot that is decided by showdown now: the rule itself.
|
||||
pub fn all_in(self, pot: f64) -> f64 {
|
||||
match self {
|
||||
ChartRake::None => 0.0,
|
||||
ChartRake::Measured => RakeRule::MEASURED_BB.of_hand(pot, 2, HandEnd::FlopDealt),
|
||||
}
|
||||
}
|
||||
|
||||
/// Pot with chips behind: its final size is unknown here, so the measured mean applies.
|
||||
pub fn postflop(self, pot: f64) -> f64 {
|
||||
match self {
|
||||
ChartRake::None => 0.0,
|
||||
ChartRake::Measured => {
|
||||
MEAN_RAKE_BY_FLOP_POT.iter().find(|(bound, _)| pot < *bound).map_or(0.0, |(_, rake)| *rake)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+17
-5
@@ -1,5 +1,5 @@
|
||||
use super::opponent::Opponent;
|
||||
use super::table::{deal, play_hand, HandSetup};
|
||||
use super::table::{deal, play_hand_at, HandSetup, TableCost};
|
||||
use crate::rng::Rng;
|
||||
use std::fmt;
|
||||
|
||||
@@ -28,6 +28,8 @@ pub struct Measurement {
|
||||
pub decisions: u32,
|
||||
pub abstains: u32,
|
||||
pub invalid: u32,
|
||||
/// Mean rake of the whole table per hand, bb/100 (0 at the free table).
|
||||
pub rake_bb_per_100: f64,
|
||||
}
|
||||
|
||||
impl Measurement {
|
||||
@@ -57,9 +59,15 @@ fn mix(seed: u64, n: u64) -> u64 {
|
||||
Rng::seeded(seed ^ n.wrapping_mul(0xD1B5_4A32_D192_ED03)).next_u64().0
|
||||
}
|
||||
|
||||
/// Plays `deals` deals, each from every seat, and returns hero's win rate with its interval.
|
||||
/// A sample is one deal's mean over the seats, so position and card luck cancel within it.
|
||||
/// `measure_at` the free table: the gross win rate.
|
||||
pub fn measure(setup: &Setup) -> Measurement {
|
||||
measure_at(setup, TableCost::FREE)
|
||||
}
|
||||
|
||||
/// Plays `deals` deals, each from every seat, and returns hero's win rate with its interval, net
|
||||
/// of what `cost` takes. A sample is one deal's mean over the seats, so position and card luck
|
||||
/// cancel within it.
|
||||
pub fn measure_at(setup: &Setup, cost: TableCost) -> Measurement {
|
||||
let players = setup.players;
|
||||
let mut samples = Vec::with_capacity(setup.deals as usize);
|
||||
let mut raw_samples = Vec::with_capacity(setup.deals as usize);
|
||||
@@ -72,18 +80,21 @@ pub fn measure(setup: &Setup) -> Measurement {
|
||||
decisions: 0,
|
||||
abstains: 0,
|
||||
invalid: 0,
|
||||
rake_bb_per_100: 0.0,
|
||||
};
|
||||
let mut rake = 0.0;
|
||||
for d in 0..setup.deals {
|
||||
let (cards, _) = deal(players as usize, Rng::seeded(mix(setup.seed, d as u64)));
|
||||
let (mut sum, mut raw) = (0.0, 0.0);
|
||||
for hero_seat in 1..=players {
|
||||
let r = play_hand(&HandSetup {
|
||||
let r = play_hand_at(&HandSetup {
|
||||
deal: &cards,
|
||||
hero_seat,
|
||||
opponent: setup.opponent,
|
||||
stack_bb: setup.stack_bb,
|
||||
seed: mix(setup.seed ^ 0xA5A5, (d as u64) << 8 | hero_seat as u64),
|
||||
});
|
||||
}, cost);
|
||||
rake += r.rake;
|
||||
sum += r.hero_net - r.luck;
|
||||
raw += r.hero_net;
|
||||
m.hands += 1;
|
||||
@@ -94,6 +105,7 @@ pub fn measure(setup: &Setup) -> Measurement {
|
||||
samples.push(sum / players as f64);
|
||||
raw_samples.push(raw / players as f64);
|
||||
}
|
||||
m.rake_bb_per_100 = 100.0 * rake / m.hands.max(1) as f64;
|
||||
(m.bb_per_100, m.ci95) = rate(&samples);
|
||||
(m.raw_bb_per_100, m.raw_ci95) = rate(&raw_samples);
|
||||
m
|
||||
|
||||
+66
-12
@@ -1,6 +1,8 @@
|
||||
//! One hand of No-Limit Hold'em at a table of 2-10 seats: the engine on one seat, a fixed
|
||||
//! opponent on all others. Seat 1 is the button; heads-up the button posts the small blind.
|
||||
//! Big blind 1, small blind 0.5, everybody starts with `stack_bb`. No rake, no antes.
|
||||
//! Big blind 1, small blind 0.5, everybody starts with `stack_bb`. Rake and antes come from
|
||||
//! `TableCost`; `play_hand` is the free table. The rake leaves the table: the players' results
|
||||
//! then sum to minus the rake. Antes are dead money in the pot and no part of a street's bet.
|
||||
|
||||
use super::luck;
|
||||
use super::opponent::{Act, Opponent, View};
|
||||
@@ -9,6 +11,7 @@ use crate::engine::decide::decide;
|
||||
use crate::game::{ActionKind, ActionRecord, Choice, SeenAction, Spot, Street, Villain};
|
||||
use crate::guard::validate::check;
|
||||
use crate::hand::showdown::best;
|
||||
use crate::rake::{split_over_pots, uncalled, HandEnd, RakeRule, MEASURED_ANTE_BB};
|
||||
use crate::rng::Rng;
|
||||
use crate::variant::{HoleUsage, Variant};
|
||||
|
||||
@@ -16,6 +19,20 @@ const SMALL_BLIND: f64 = 0.5;
|
||||
const BIG_BLIND: f64 = 1.0;
|
||||
const EPS: f64 = 1e-9;
|
||||
|
||||
/// What a table takes besides the blinds.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct TableCost {
|
||||
/// Per player, in big blinds.
|
||||
pub ante_bb: f64,
|
||||
pub rake: Option<RakeRule>,
|
||||
}
|
||||
|
||||
impl TableCost {
|
||||
pub const FREE: TableCost = TableCost { ante_bb: 0.0, rake: None };
|
||||
/// The table measured in `rake`: ante 0.16 bb, 5 % capped at 1 bb.
|
||||
pub const MEASURED: TableCost = TableCost { ante_bb: MEASURED_ANTE_BB, rake: Some(RakeRule::MEASURED_BB) };
|
||||
}
|
||||
|
||||
/// Cards for one hand: `holes[seat - 1]` and the full board in deal order.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Deal {
|
||||
@@ -48,14 +65,17 @@ pub struct HandResult {
|
||||
pub abstains: u32,
|
||||
/// Requests the guard refused: a simulator bug, must stay 0.
|
||||
pub invalid: u32,
|
||||
/// Sum of all players' results; must be 0.
|
||||
/// Sum of all players' results plus the rake; must be 0.
|
||||
pub chips_lost: f64,
|
||||
/// Rake of the hand, big blinds.
|
||||
pub rake: f64,
|
||||
/// What the board cards decided (see `sim::luck`); expectation 0.
|
||||
pub luck: f64,
|
||||
}
|
||||
|
||||
struct Table<'a> {
|
||||
setup: &'a HandSetup<'a>,
|
||||
cost: TableCost,
|
||||
hero: usize,
|
||||
stack: Vec<f64>,
|
||||
bet: Vec<f64>,
|
||||
@@ -113,6 +133,14 @@ impl Table<'_> {
|
||||
self.total[i] += amount;
|
||||
}
|
||||
|
||||
/// Dead money: in the pot, not in the street's bet.
|
||||
fn post_ante(&mut self, i: usize, amount: f64) {
|
||||
let amount = amount.min(self.stack[i]);
|
||||
self.stack[i] -= amount;
|
||||
self.total[i] += amount;
|
||||
self.record(i, SeenAction::PostAnte, Some(amount));
|
||||
}
|
||||
|
||||
fn post(&mut self, i: usize, amount: f64, action: SeenAction) {
|
||||
self.put(i, amount);
|
||||
self.record(i, action, Some(self.bet[i]));
|
||||
@@ -279,11 +307,15 @@ impl Table<'_> {
|
||||
self.last_raise = BIG_BLIND;
|
||||
}
|
||||
|
||||
/// Side pots level by level; ties split evenly.
|
||||
fn showdown(&self) -> Vec<f64> {
|
||||
/// Side pots level by level; ties split evenly. Returns everybody's winnings and the rake.
|
||||
fn showdown(&self) -> (Vec<f64>, f64) {
|
||||
let n = self.players();
|
||||
let mut won = vec![0.0; n];
|
||||
let mut left = self.total.clone();
|
||||
if let Some((top, amount)) = uncalled(&left) {
|
||||
left[top] -= amount;
|
||||
won[top] += amount;
|
||||
}
|
||||
let strength: Vec<_> = (0..n)
|
||||
.map(|i| {
|
||||
(!self.folded[i]).then(|| {
|
||||
@@ -292,6 +324,7 @@ impl Table<'_> {
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let mut pots: Vec<(f64, Vec<usize>)> = Vec::new();
|
||||
loop {
|
||||
let contenders: Vec<usize> = (0..n).filter(|i| !self.folded[*i] && left[*i] > EPS).collect();
|
||||
let Some(level) = contenders.iter().map(|i| left[*i]).min_by(f64::total_cmp) else {
|
||||
@@ -303,20 +336,35 @@ impl Table<'_> {
|
||||
part
|
||||
}).sum();
|
||||
let top = contenders.iter().filter_map(|i| strength[*i]).max().expect("a contender");
|
||||
let winners: Vec<usize> = contenders.into_iter().filter(|i| strength[*i] == Some(top)).collect();
|
||||
for w in &winners {
|
||||
won[*w] += pot / winners.len() as f64;
|
||||
pots.push((pot, contenders.into_iter().filter(|i| strength[*i] == Some(top)).collect()));
|
||||
}
|
||||
let sizes: Vec<f64> = pots.iter().map(|(pot, _)| *pot).collect();
|
||||
let rake = self.rake_of(sizes.iter().sum());
|
||||
for ((pot, winners), taken) in pots.iter().zip(split_over_pots(rake, &sizes)) {
|
||||
for w in winners {
|
||||
won[*w] += (pot - taken) / winners.len() as f64;
|
||||
}
|
||||
}
|
||||
won
|
||||
(won, rake)
|
||||
}
|
||||
|
||||
fn rake_of(&self, pot: f64) -> f64 {
|
||||
let end = if self.street == Street::Preflop { HandEnd::NoFlop } else { HandEnd::FlopDealt };
|
||||
self.cost.rake.map_or(0.0, |rule| rule.of_hand(pot, self.live(), end))
|
||||
}
|
||||
}
|
||||
|
||||
/// Plays one hand to the end and reports hero's result.
|
||||
/// Plays one hand at the free table and reports hero's result.
|
||||
pub fn play_hand(setup: &HandSetup) -> HandResult {
|
||||
play_hand_at(setup, TableCost::FREE)
|
||||
}
|
||||
|
||||
/// Plays one hand to the end at a table with `cost` and reports hero's result.
|
||||
pub fn play_hand_at(setup: &HandSetup, cost: TableCost) -> HandResult {
|
||||
let n = setup.deal.holes.len();
|
||||
let mut t = Table {
|
||||
setup,
|
||||
cost,
|
||||
hero: setup.hero_seat as usize - 1,
|
||||
stack: vec![setup.stack_bb; n],
|
||||
bet: vec![0.0; n],
|
||||
@@ -327,8 +375,13 @@ pub fn play_hand(setup: &HandSetup) -> HandResult {
|
||||
last_raise: BIG_BLIND,
|
||||
history: Vec::new(),
|
||||
rng: Rng::seeded(setup.seed),
|
||||
result: HandResult { hero_net: 0.0, hero_decisions: 0, abstains: 0, invalid: 0, chips_lost: 0.0, luck: 0.0 },
|
||||
result: HandResult { hero_net: 0.0, hero_decisions: 0, abstains: 0, invalid: 0, chips_lost: 0.0, rake: 0.0, luck: 0.0 },
|
||||
};
|
||||
if cost.ante_bb > 0.0 {
|
||||
for i in 0..n {
|
||||
t.post_ante(i, cost.ante_bb);
|
||||
}
|
||||
}
|
||||
let (sb, bb) = if n == 2 { (0, 1) } else { (1, 2) };
|
||||
t.post(sb, SMALL_BLIND, SeenAction::PostSmallBlind);
|
||||
t.post(bb, BIG_BLIND, SeenAction::PostBigBlind);
|
||||
@@ -341,9 +394,10 @@ pub fn play_hand(setup: &HandSetup) -> HandResult {
|
||||
t.next_street(street);
|
||||
t.round(1 % n);
|
||||
}
|
||||
let won = t.showdown();
|
||||
let (won, rake) = t.showdown();
|
||||
let nets: Vec<f64> = (0..n).map(|i| t.stack[i] + won[i] - setup.stack_bb).collect();
|
||||
t.result.hero_net = nets[t.hero];
|
||||
t.result.chips_lost = nets.iter().sum();
|
||||
t.result.rake = rake;
|
||||
t.result.chips_lost = nets.iter().sum::<f64>() + rake;
|
||||
t.result
|
||||
}
|
||||
|
||||
+147
-147
@@ -1,147 +1,147 @@
|
||||
//! The two preflop game trees: structure, input faults and exact payoff identities.
|
||||
//!
|
||||
//! Identities used (all independent of the solver): with a symmetric chance table and an
|
||||
//! antisymmetric equity matrix, "always push / always call" from the small blind is worth
|
||||
//! exactly 0 (a fair coin on every deal), "always push / always fold" is +1 (the big blind),
|
||||
//! "always fold" is -0.5 (the small blind already posted).
|
||||
mod cfr_support;
|
||||
|
||||
use pokerfreak::cfr::environment::Environment;
|
||||
use pokerfreak::cfr::exploitability::game_value;
|
||||
use pokerfreak::cfr::open_game::open_tree;
|
||||
use pokerfreak::cfr::push_fold_game::push_fold_tree;
|
||||
use pokerfreak::cfr::seat::Seat;
|
||||
use pokerfreak::cfr::spot_params::{OPEN_SIZE, THREE_BET_SIZE, WAKE_FRACTION};
|
||||
use pokerfreak::cfr::strategy::Strategy;
|
||||
use pokerfreak::cfr::tree::Node;
|
||||
use pokerfreak::cfr::wake_range::top_membership;
|
||||
use pokerfreak::variant::{rules, Variant};
|
||||
|
||||
fn env() -> Environment {
|
||||
Environment::frozen()
|
||||
}
|
||||
|
||||
fn names(tree: &pokerfreak::cfr::tree::Tree) -> Vec<&'static str> {
|
||||
tree.nodes
|
||||
.iter()
|
||||
.filter_map(|n| match n {
|
||||
Node::Decision { name, .. } => Some(*name),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seats_know_how_many_players_act_behind_them() {
|
||||
let behind: Vec<usize> = Seat::ALL.iter().map(|s| s.players_behind()).collect();
|
||||
// EP, MP, CO, BTN, SB: the big blind is the modelled opponent, the others are "behind".
|
||||
assert_eq!(behind, vec![4, 3, 2, 1, 0]);
|
||||
assert!(Seat::Button.is_in_position_against_big_blind());
|
||||
assert!(!Seat::SmallBlind.is_in_position_against_big_blind());
|
||||
assert_eq!(Seat::Early.label(), "EP");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn push_fold_tree_has_two_decisions_over_169_classes() {
|
||||
let tree = push_fold_tree(&env(), Seat::Button, 10.0).expect("tree");
|
||||
assert_eq!(tree.classes, 169);
|
||||
let mut found = names(&tree);
|
||||
found.sort_unstable();
|
||||
assert_eq!(found, vec!["call", "push"]);
|
||||
assert!(tree.find("push").is_some() && tree.find("call").is_some());
|
||||
assert_eq!(tree.action_count(tree.find("push").unwrap()), Some(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_tree_has_the_four_documented_decisions() {
|
||||
let tree = open_tree(&env(), Seat::Cutoff, 40.0).expect("tree");
|
||||
for name in ["open", "defend", "vs_three_bet", "vs_jam"] {
|
||||
assert!(tree.find(name).is_some(), "{name}");
|
||||
}
|
||||
assert_eq!(tree.action_count(tree.find("open").unwrap()), Some(2));
|
||||
assert_eq!(tree.action_count(tree.find("defend").unwrap()), Some(3));
|
||||
assert_eq!(tree.action_count(tree.find("vs_three_bet").unwrap()), Some(3));
|
||||
assert_eq!(tree.action_count(tree.find("vs_jam").unwrap()), Some(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_stack_depths_are_faults_not_panics() {
|
||||
let e = env();
|
||||
for depth in [f64::NAN, f64::INFINITY, 0.0, -5.0, 0.5] {
|
||||
assert!(push_fold_tree(&e, Seat::Button, depth).is_err(), "push {depth}");
|
||||
assert!(open_tree(&e, Seat::Button, depth).is_err(), "open {depth}");
|
||||
}
|
||||
// The 3-bet size must fit below the stack, otherwise the 3-bet line is not a raise.
|
||||
assert!(open_tree(&e, Seat::Button, THREE_BET_SIZE).is_err());
|
||||
assert!(open_tree(&e, Seat::Button, OPEN_SIZE).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn environment_rejects_rules_that_are_not_two_card_hold_em() {
|
||||
let equity = pokerfreak::cfr::frozen_equity::frozen_equity();
|
||||
assert!(Environment::new(&rules(Variant::Plo5), equity.clone()).is_err());
|
||||
assert!(Environment::new(&rules(Variant::Nlhe), equity.clone()).is_ok());
|
||||
assert!(Environment::new(&rules(Variant::Aof), equity).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn small_blind_push_fold_identities_are_exact() {
|
||||
let tree = push_fold_tree(&env(), Seat::SmallBlind, 10.0).expect("tree");
|
||||
let strat = |push: usize, call: usize| {
|
||||
Strategy::pure(&tree, |name, _class| if name == "push" { push } else { call })
|
||||
};
|
||||
assert!((game_value(&tree, &strat(0, 0)) + 0.5).abs() < 1e-9, "fold: -0.5");
|
||||
assert!((game_value(&tree, &strat(1, 0)) - 1.0).abs() < 1e-9, "push, they fold: +1");
|
||||
assert!(game_value(&tree, &strat(1, 1)).abs() < 1e-9, "push, they call: fair coin");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn small_blind_open_identities_are_exact() {
|
||||
let tree = open_tree(&env(), Seat::SmallBlind, 40.0).expect("tree");
|
||||
// Actions: open [fold, raise]; defend [fold, call, 3-bet]; vs_three_bet [fold, call, jam];
|
||||
// vs_jam [fold, call].
|
||||
let strat = |open: usize, defend: usize| {
|
||||
Strategy::pure(&tree, |name, _| match name {
|
||||
"open" => open,
|
||||
"defend" => defend,
|
||||
_ => 0,
|
||||
})
|
||||
};
|
||||
assert!((game_value(&tree, &strat(0, 0)) + 0.5).abs() < 1e-9, "fold the small blind");
|
||||
assert!((game_value(&tree, &strat(1, 0)) - 1.0).abs() < 1e-9, "raise, big blind folds");
|
||||
// Raise, big blind 3-bets everything, the opener always folds: loses the open.
|
||||
assert!((game_value(&tree, &strat(1, 2)) + OPEN_SIZE_SB).abs() < 1e-9);
|
||||
}
|
||||
|
||||
const OPEN_SIZE_SB: f64 = pokerfreak::cfr::spot_params::SMALL_BLIND_OPEN_SIZE;
|
||||
|
||||
#[test]
|
||||
fn players_behind_cost_the_opener_money_when_they_wake_up() {
|
||||
// Pushing everything and being folded to is worth the dead money + big blind only if
|
||||
// nobody behind wakes up; the earlier the seat, the more often somebody does.
|
||||
let e = env();
|
||||
let value = |seat: Seat| {
|
||||
let tree = push_fold_tree(&e, seat, 10.0).expect("tree");
|
||||
game_value(&tree, &Strategy::pure(&tree, |name, _| if name == "push" { 1 } else { 0 }))
|
||||
};
|
||||
// Push-all/fold-all values: BTN > CO > MP > EP (more wake-up chances), all below 1.5.
|
||||
assert!(value(Seat::Button) > value(Seat::Cutoff));
|
||||
assert!(value(Seat::Cutoff) > value(Seat::Middle));
|
||||
assert!(value(Seat::Middle) > value(Seat::Early));
|
||||
assert!(value(Seat::Button) < 1.5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wake_range_membership_covers_exactly_the_requested_share_of_combos() {
|
||||
let e = env();
|
||||
let membership = top_membership(&e, WAKE_FRACTION);
|
||||
let combos: f64 = (0..169)
|
||||
.map(|c| membership[c] * pokerfreak::cfr::hand_class::class_combos(c).len() as f64)
|
||||
.sum();
|
||||
assert!((combos / 1326.0 - WAKE_FRACTION).abs() < 1e-9);
|
||||
assert!(membership.iter().all(|m| (0.0..=1.0).contains(m)));
|
||||
assert_eq!(membership[cfr_support::id("AA")], 1.0);
|
||||
assert_eq!(membership[cfr_support::id("72o")], 0.0);
|
||||
assert_eq!(top_membership(&e, 0.0).iter().sum::<f64>(), 0.0);
|
||||
assert!((top_membership(&e, 1.0).iter().sum::<f64>() - 169.0).abs() < 1e-9);
|
||||
}
|
||||
//! The two preflop game trees: structure, input faults and exact payoff identities.
|
||||
//!
|
||||
//! Identities used (all independent of the solver): with a symmetric chance table and an
|
||||
//! antisymmetric equity matrix, "always push / always call" from the small blind is worth
|
||||
//! exactly 0 (a fair coin on every deal), "always push / always fold" is +1 (the big blind),
|
||||
//! "always fold" is -0.5 (the small blind already posted).
|
||||
mod cfr_support;
|
||||
|
||||
use pokerfreak::cfr::environment::Environment;
|
||||
use pokerfreak::cfr::exploitability::game_value;
|
||||
use pokerfreak::cfr::open_game::open_tree;
|
||||
use pokerfreak::cfr::push_fold_game::push_fold_tree;
|
||||
use pokerfreak::cfr::seat::Seat;
|
||||
use pokerfreak::cfr::spot_params::{OPEN_SIZE, THREE_BET_SIZE, WAKE_FRACTION};
|
||||
use pokerfreak::cfr::strategy::Strategy;
|
||||
use pokerfreak::cfr::tree::Node;
|
||||
use pokerfreak::cfr::wake_range::top_membership;
|
||||
use pokerfreak::variant::{rules, Variant};
|
||||
|
||||
fn env() -> Environment {
|
||||
Environment::frozen_free_table()
|
||||
}
|
||||
|
||||
fn names(tree: &pokerfreak::cfr::tree::Tree) -> Vec<&'static str> {
|
||||
tree.nodes
|
||||
.iter()
|
||||
.filter_map(|n| match n {
|
||||
Node::Decision { name, .. } => Some(*name),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seats_know_how_many_players_act_behind_them() {
|
||||
let behind: Vec<usize> = Seat::ALL.iter().map(|s| s.players_behind()).collect();
|
||||
// EP, MP, CO, BTN, SB: the big blind is the modelled opponent, the others are "behind".
|
||||
assert_eq!(behind, vec![4, 3, 2, 1, 0]);
|
||||
assert!(Seat::Button.is_in_position_against_big_blind());
|
||||
assert!(!Seat::SmallBlind.is_in_position_against_big_blind());
|
||||
assert_eq!(Seat::Early.label(), "EP");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn push_fold_tree_has_two_decisions_over_169_classes() {
|
||||
let tree = push_fold_tree(&env(), Seat::Button, 10.0).expect("tree");
|
||||
assert_eq!(tree.classes, 169);
|
||||
let mut found = names(&tree);
|
||||
found.sort_unstable();
|
||||
assert_eq!(found, vec!["call", "push"]);
|
||||
assert!(tree.find("push").is_some() && tree.find("call").is_some());
|
||||
assert_eq!(tree.action_count(tree.find("push").unwrap()), Some(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_tree_has_the_four_documented_decisions() {
|
||||
let tree = open_tree(&env(), Seat::Cutoff, 40.0).expect("tree");
|
||||
for name in ["open", "defend", "vs_three_bet", "vs_jam"] {
|
||||
assert!(tree.find(name).is_some(), "{name}");
|
||||
}
|
||||
assert_eq!(tree.action_count(tree.find("open").unwrap()), Some(2));
|
||||
assert_eq!(tree.action_count(tree.find("defend").unwrap()), Some(3));
|
||||
assert_eq!(tree.action_count(tree.find("vs_three_bet").unwrap()), Some(3));
|
||||
assert_eq!(tree.action_count(tree.find("vs_jam").unwrap()), Some(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_stack_depths_are_faults_not_panics() {
|
||||
let e = env();
|
||||
for depth in [f64::NAN, f64::INFINITY, 0.0, -5.0, 0.5] {
|
||||
assert!(push_fold_tree(&e, Seat::Button, depth).is_err(), "push {depth}");
|
||||
assert!(open_tree(&e, Seat::Button, depth).is_err(), "open {depth}");
|
||||
}
|
||||
// The 3-bet size must fit below the stack, otherwise the 3-bet line is not a raise.
|
||||
assert!(open_tree(&e, Seat::Button, THREE_BET_SIZE).is_err());
|
||||
assert!(open_tree(&e, Seat::Button, OPEN_SIZE).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn environment_rejects_rules_that_are_not_two_card_hold_em() {
|
||||
let equity = pokerfreak::cfr::frozen_equity::frozen_equity();
|
||||
assert!(Environment::new(&rules(Variant::Plo5), equity.clone()).is_err());
|
||||
assert!(Environment::new(&rules(Variant::Nlhe), equity.clone()).is_ok());
|
||||
assert!(Environment::new(&rules(Variant::Aof), equity).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn small_blind_push_fold_identities_are_exact() {
|
||||
let tree = push_fold_tree(&env(), Seat::SmallBlind, 10.0).expect("tree");
|
||||
let strat = |push: usize, call: usize| {
|
||||
Strategy::pure(&tree, |name, _class| if name == "push" { push } else { call })
|
||||
};
|
||||
assert!((game_value(&tree, &strat(0, 0)) + 0.5).abs() < 1e-9, "fold: -0.5");
|
||||
assert!((game_value(&tree, &strat(1, 0)) - 1.0).abs() < 1e-9, "push, they fold: +1");
|
||||
assert!(game_value(&tree, &strat(1, 1)).abs() < 1e-9, "push, they call: fair coin");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn small_blind_open_identities_are_exact() {
|
||||
let tree = open_tree(&env(), Seat::SmallBlind, 40.0).expect("tree");
|
||||
// Actions: open [fold, raise]; defend [fold, call, 3-bet]; vs_three_bet [fold, call, jam];
|
||||
// vs_jam [fold, call].
|
||||
let strat = |open: usize, defend: usize| {
|
||||
Strategy::pure(&tree, |name, _| match name {
|
||||
"open" => open,
|
||||
"defend" => defend,
|
||||
_ => 0,
|
||||
})
|
||||
};
|
||||
assert!((game_value(&tree, &strat(0, 0)) + 0.5).abs() < 1e-9, "fold the small blind");
|
||||
assert!((game_value(&tree, &strat(1, 0)) - 1.0).abs() < 1e-9, "raise, big blind folds");
|
||||
// Raise, big blind 3-bets everything, the opener always folds: loses the open.
|
||||
assert!((game_value(&tree, &strat(1, 2)) + OPEN_SIZE_SB).abs() < 1e-9);
|
||||
}
|
||||
|
||||
const OPEN_SIZE_SB: f64 = pokerfreak::cfr::spot_params::SMALL_BLIND_OPEN_SIZE;
|
||||
|
||||
#[test]
|
||||
fn players_behind_cost_the_opener_money_when_they_wake_up() {
|
||||
// Pushing everything and being folded to is worth the dead money + big blind only if
|
||||
// nobody behind wakes up; the earlier the seat, the more often somebody does.
|
||||
let e = env();
|
||||
let value = |seat: Seat| {
|
||||
let tree = push_fold_tree(&e, seat, 10.0).expect("tree");
|
||||
game_value(&tree, &Strategy::pure(&tree, |name, _| if name == "push" { 1 } else { 0 }))
|
||||
};
|
||||
// Push-all/fold-all values: BTN > CO > MP > EP (more wake-up chances), all below 1.5.
|
||||
assert!(value(Seat::Button) > value(Seat::Cutoff));
|
||||
assert!(value(Seat::Cutoff) > value(Seat::Middle));
|
||||
assert!(value(Seat::Middle) > value(Seat::Early));
|
||||
assert!(value(Seat::Button) < 1.5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wake_range_membership_covers_exactly_the_requested_share_of_combos() {
|
||||
let e = env();
|
||||
let membership = top_membership(&e, WAKE_FRACTION);
|
||||
let combos: f64 = (0..169)
|
||||
.map(|c| membership[c] * pokerfreak::cfr::hand_class::class_combos(c).len() as f64)
|
||||
.sum();
|
||||
assert!((combos / 1326.0 - WAKE_FRACTION).abs() < 1e-9);
|
||||
assert!(membership.iter().all(|m| (0.0..=1.0).contains(m)));
|
||||
assert_eq!(membership[cfr_support::id("AA")], 1.0);
|
||||
assert_eq!(membership[cfr_support::id("72o")], 0.0);
|
||||
assert_eq!(top_membership(&e, 0.0).iter().sum::<f64>(), 0.0);
|
||||
assert!((top_membership(&e, 1.0).iter().sum::<f64>() - 169.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
+1
-1
@@ -151,7 +151,7 @@ fn four_defenders_have_every_overcall_history_as_its_own_decision() {
|
||||
|
||||
#[test]
|
||||
fn every_terminal_pays_out_exactly_the_chips_put_in() {
|
||||
let env = env();
|
||||
let env = Environment::frozen_free_table();
|
||||
let mut rng = Rng::seeded(11);
|
||||
for (seat, k, _) in multi_plan() {
|
||||
let tree = multi_open_tree(&env, seat, k, 40.0).expect("tree");
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
//! Die Chart-Spiele mit Rake: wer was trägt, was ein Fold kostet, und dass die Grenzen enger werden.
|
||||
|
||||
use pokerfreak::cfr::environment::Environment;
|
||||
use pokerfreak::cfr::exploitability::game_value;
|
||||
use pokerfreak::cfr::multi_solve::width;
|
||||
use pokerfreak::cfr::payoffs::{postflop, share};
|
||||
use pokerfreak::cfr::multi_tree::{multi_open_tree, MultiNode, MultiOutcome};
|
||||
use pokerfreak::cfr::open_game::open_tree;
|
||||
use pokerfreak::cfr::push_fold3_game::push_fold3_tree;
|
||||
use pokerfreak::cfr::push_fold_game::push_fold_tree;
|
||||
use pokerfreak::cfr::seat::Seat;
|
||||
use pokerfreak::cfr::solve::solve;
|
||||
use pokerfreak::cfr::strategy::Strategy;
|
||||
use pokerfreak::cfr::terminal_value::terminal_value;
|
||||
use pokerfreak::cfr::tree::Payoff;
|
||||
use pokerfreak::cfr::walk3::game_value3;
|
||||
use pokerfreak::rake::ChartRake;
|
||||
use pokerfreak::rng::Rng;
|
||||
|
||||
fn raked() -> Environment {
|
||||
Environment::frozen()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_tables_of_the_full_deck_carry_the_rake_and_short_deck_does_not() {
|
||||
use pokerfreak::cfr::chart_deck::ChartDeck;
|
||||
assert_eq!(raked().rake, ChartRake::Measured);
|
||||
assert!((raked().antes - 0.96).abs() < 1e-12);
|
||||
assert_eq!(Environment::frozen_for(ChartDeck::Short).antes, 0.0);
|
||||
assert_eq!(Environment::frozen_free_table().antes, 0.0);
|
||||
assert_eq!(Environment::frozen_free_table().rake, ChartRake::None);
|
||||
assert_eq!(Environment::frozen_for(ChartDeck::Short).rake, ChartRake::None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_raked_leaf_takes_the_rake_from_player_one_as_well() {
|
||||
// Zwei Klassen, Spieler 0 gewinnt netto 3, der Rake ist 1: Spieler 1 verliert 4.
|
||||
let payoff = Payoff::Raked { pair: vec![3.0; 4], rake: 1.0 };
|
||||
let chance = vec![0.25; 4];
|
||||
let opp = vec![1.0, 1.0];
|
||||
assert_eq!(terminal_value(&payoff, &chance, 2, 0, &opp), vec![1.5, 1.5]);
|
||||
assert_eq!(terminal_value(&payoff, &chance, 2, 1, &opp), vec![-2.0, -2.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn heads_up_all_in_for_a_fair_coin_costs_each_side_half_the_rake() {
|
||||
let tree = push_fold_tree(&raked(), Seat::SmallBlind, 10.0).expect("tree");
|
||||
let strat = |push: usize, call: usize| Strategy::pure(&tree, |name, _| if name == "push" { push } else { call });
|
||||
// 20 bb Topf plus 0,96 bb Antes, davon der Cap von 1 bb: je 9,98 zurück für 10 Einsatz.
|
||||
assert!((game_value(&tree, &strat(1, 1)) + 0.02).abs() < 1e-9, "{}", game_value(&tree, &strat(1, 1)));
|
||||
// Ein Fold zahlt keinen Rake, der Sieger nimmt Blind und Antes.
|
||||
assert!((game_value(&tree, &strat(1, 0)) - 1.96).abs() < 1e-9);
|
||||
assert!((game_value(&tree, &strat(0, 0)) + 0.5).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn three_way_all_in_splits_the_rake_in_three() {
|
||||
let tree = push_fold3_tree(&raked(), Seat::Button, 10.0).expect("tree");
|
||||
let all_in = Strategy::pure(&tree, |_, _| 1);
|
||||
for p in 0..3 {
|
||||
let v = game_value3(&tree, &all_in, p);
|
||||
assert!((v - ((30.96 - 1.0) / 3.0 - 10.0)).abs() < 1e-9, "player {p}: {v}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_multi_defender_pot_pays_the_rake_and_a_fold_does_not() {
|
||||
let tree = multi_open_tree(&raked(), Seat::Cutoff, 2, 40.0).expect("tree");
|
||||
let env = raked();
|
||||
let dead = tree.lineup.dead_money() + env.antes;
|
||||
let classes = vec![0; tree.players];
|
||||
let (mut pots, mut flats) = (0, 0);
|
||||
for node in &tree.nodes {
|
||||
let MultiNode::Terminal(outcome) = node else { continue };
|
||||
let total: f64 = tree.payoff(outcome, &classes).iter().sum();
|
||||
match outcome {
|
||||
MultiOutcome::Pot { invested, .. } => {
|
||||
let gross = invested.iter().sum::<f64>() + dead;
|
||||
let all_in = invested.iter().any(|x| *x >= 40.0);
|
||||
let rake = if all_in { raked().rake.all_in(gross) } else { raked().rake.postflop(gross) };
|
||||
assert!(rake > 0.0);
|
||||
assert!((total - (dead - rake)).abs() < 1e-9, "{total} {dead} {rake}");
|
||||
pots += 1;
|
||||
}
|
||||
MultiOutcome::Flat(_) => flats += 1,
|
||||
MultiOutcome::Own { .. } => {}
|
||||
}
|
||||
}
|
||||
assert!(pots >= 3 && flats >= 3, "{pots} {flats}");
|
||||
}
|
||||
|
||||
/// Anteil der Combos, die im Spiel Small Blind gegen Big Blind die Aktion `action` wählen.
|
||||
fn share_of_combos(env: &Environment, name: &str, action: usize) -> f64 {
|
||||
let tree = open_tree(env, Seat::SmallBlind, 100.0).expect("tree");
|
||||
let solved = solve(&tree, 2000, Rng::seeded(1));
|
||||
let node = tree.find(name).expect("node");
|
||||
let row: Vec<u16> = (0..tree.classes)
|
||||
.map(|class| (solved.strategy.probability(node, class, action) * 1000.0).round() as u16)
|
||||
.collect();
|
||||
width(env, &row)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rake_alone_takes_marginal_calls_from_the_defender() {
|
||||
const CALL: usize = 1;
|
||||
let with = share_of_combos(&Environment { antes: 0.0, ..raked() }, "defend", CALL);
|
||||
let without = share_of_combos(&Environment::frozen_free_table(), "defend", CALL);
|
||||
assert!(with < without - 0.01, "mit Rake {with}, ohne {without}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_postflop_pot_is_split_after_the_rake() {
|
||||
let env = raked();
|
||||
let (pot, invested) = (6.46, 2.5);
|
||||
let rake = env.rake.postflop(pot);
|
||||
let Payoff::Raked { pair, rake: paid } = postflop(&env, pot, invested, true, 0.85) else {
|
||||
panic!("rake expected");
|
||||
};
|
||||
assert_eq!(paid, rake);
|
||||
for (k, u) in pair.iter().enumerate() {
|
||||
let eq = env.equity.get(k / 169, k % 169);
|
||||
assert!((u - ((pot - rake) * share(eq, true, 0.85) - invested)).abs() < 1e-12);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn antes_widen_the_defence_again() {
|
||||
const CALL: usize = 1;
|
||||
let with = share_of_combos(&raked(), "defend", CALL);
|
||||
let without = share_of_combos(&Environment { antes: 0.0, ..raked() }, "defend", CALL);
|
||||
assert!(with > without + 0.01, "mit Antes {with}, ohne {without}");
|
||||
}
|
||||
+175
-175
@@ -1,175 +1,175 @@
|
||||
//! The three-player abstraction: deal weights, three-way pot shares and the game trees.
|
||||
//!
|
||||
//! Three-way shares come from the pairwise class equities (`cfr::three_way`): each hand's share is
|
||||
//! the weaker of its two pairwise equities, normalised. Reference: Monte Carlo with the engine's
|
||||
//! own evaluator over 200 000 boards for fixed combos (standard error about 0.1 %). The
|
||||
//! approximation is coarse. Observed (approx / sampled):
|
||||
//!
|
||||
//! | hands | approximation | Monte Carlo |
|
||||
//! |---|---|---|
|
||||
//! | AA, KK, QQ | 0.696 / 0.154 / 0.150 | 0.665 / 0.168 / 0.167 |
|
||||
//! | AKo, QQ, 72o | 0.386 / 0.508 / 0.106 | 0.396 / 0.494 / 0.110 |
|
||||
//! | AKs, AQo, KQo | 0.607 / 0.197 / 0.197 | 0.743 / 0.181 / 0.076 |
|
||||
//! | 22, AKo, T9s | 0.348 / 0.349 / 0.303 | 0.283 / 0.370 / 0.347 |
|
||||
//! | JTs, 99, AQo | 0.297 / 0.376 / 0.326 | 0.323 / 0.305 / 0.373 |
|
||||
//!
|
||||
//! Largest error 0.136 (dominated hands: AKs over AQo and KQo), root mean square 0.058. The
|
||||
//! product of the pairwise equities (0.129 / 0.068) and other means were not better. The
|
||||
//! favourite is kept where it is clear (a lead of 0.1 or more); near-even triples may swap.
|
||||
use pokerfreak::card::Card;
|
||||
use pokerfreak::cfr::environment::Environment;
|
||||
use pokerfreak::cfr::hand_class::{class_of, CLASS_COUNT};
|
||||
use pokerfreak::cfr::open3_game::open3_tree;
|
||||
use pokerfreak::cfr::push_fold3_game::push_fold3_tree;
|
||||
use pokerfreak::cfr::seat::Seat;
|
||||
use pokerfreak::cfr::strategy::Strategy;
|
||||
use pokerfreak::cfr::three_way::three_way_shares;
|
||||
use pokerfreak::cfr::tree3::Node3;
|
||||
use pokerfreak::cfr::walk3::{exploitability3, game_value3};
|
||||
use pokerfreak::equity::monte_carlo::estimate;
|
||||
use pokerfreak::equity::query::Query;
|
||||
use pokerfreak::equity::villain_range::VillainRange;
|
||||
use pokerfreak::rng::Rng;
|
||||
use pokerfreak::variant::{rules, Variant};
|
||||
|
||||
const SHARE_TOLERANCE: f64 = 0.14;
|
||||
|
||||
fn cs(text: &str) -> Vec<Card> {
|
||||
Card::parse_list(text).expect("cards")
|
||||
}
|
||||
|
||||
fn class(text: &str) -> usize {
|
||||
let c = cs(text);
|
||||
class_of(c[0], c[1]).expect("class")
|
||||
}
|
||||
|
||||
/// Monte-Carlo share of the first hand against the other two.
|
||||
fn sampled(hands: [&str; 3]) -> f64 {
|
||||
let villains = [VillainRange::Exact(cs(hands[1])), VillainRange::Exact(cs(hands[2]))];
|
||||
let hero = cs(hands[0]);
|
||||
let query = Query { rules: rules(Variant::Nlhe), hero: &hero, board: &[], villains: &villains, trials: 200_000 };
|
||||
estimate(&query, Rng::seeded(77)).expect("estimate").0.share
|
||||
}
|
||||
|
||||
fn approximated(env: &Environment, hands: [&str; 3]) -> [f64; 3] {
|
||||
let c = hands.map(class);
|
||||
let e = |x: usize, y: usize| if x == y { 0.5 } else { env.equity.get(c[x], c[y]) };
|
||||
three_way_shares([[e(0, 0), e(0, 1), e(0, 2)], [e(1, 0), e(1, 1), e(1, 2)], [e(2, 0), e(2, 1), e(2, 2)]], [1.0; 3], 1.0)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn three_way_shares_track_monte_carlo_and_keep_the_order() {
|
||||
let env = Environment::frozen();
|
||||
let matchups = [
|
||||
["Ah As", "Kh Ks", "Qd Qc"],
|
||||
["Ah Kd", "Qc Qs", "7h 2c"],
|
||||
["Ah Kh", "Ad Qc", "Kc Qd"],
|
||||
["2h 2d", "Ac Ks", "Th 9h"],
|
||||
["Js Ts", "9c 9d", "Ad Qh"],
|
||||
];
|
||||
for hands in matchups {
|
||||
let approx = approximated(&env, hands);
|
||||
let exact = [0, 1, 2].map(|k| sampled([hands[k], hands[(k + 1) % 3], hands[(k + 2) % 3]]));
|
||||
println!("{hands:?}: approx {approx:.3?}, sampled {exact:.3?}");
|
||||
for k in 0..3 {
|
||||
assert!(
|
||||
(approx[k] - exact[k]).abs() < SHARE_TOLERANCE,
|
||||
"{hands:?} hand {k}: approx {:.3}, sampled {:.3}",
|
||||
approx[k],
|
||||
exact[k]
|
||||
);
|
||||
}
|
||||
let best = |v: [f64; 3]| (0..3).fold(0, |b, k| if v[k] > v[b] { k } else { b });
|
||||
let mut sorted = exact;
|
||||
sorted.sort_by(|a, b| b.total_cmp(a));
|
||||
if sorted[0] - sorted[1] >= 0.1 {
|
||||
assert_eq!(best(approx), best(exact), "{hands:?}: favourite");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shares_sum_to_one_and_are_symmetric() {
|
||||
let eq = [[0.5, 0.7, 0.6], [0.3, 0.5, 0.55], [0.4, 0.45, 0.5]];
|
||||
for (weights, spread) in [([1.0; 3], 1.0), ([1.0, 0.85, 0.85], 1.3)] {
|
||||
let s = three_way_shares(eq, weights, spread);
|
||||
assert!((s.iter().sum::<f64>() - 1.0).abs() < 1e-12);
|
||||
assert!(s.iter().all(|x| (0.0..=1.0).contains(x)));
|
||||
}
|
||||
// Swapping two players swaps their shares.
|
||||
let swapped = [[0.5, 0.4, 0.45], [0.6, 0.5, 0.7], [0.55, 0.3, 0.5]];
|
||||
let (a, b) = (three_way_shares(eq, [1.0; 3], 1.0), three_way_shares(swapped, [1.0; 3], 1.0));
|
||||
assert!((a[0] - b[1]).abs() < 1e-12 && (a[1] - b[2]).abs() < 1e-12 && (a[2] - b[0]).abs() < 1e-12);
|
||||
// Equal hands split evenly; position weight moves chips to the player in position.
|
||||
let even = [[0.5; 3]; 3];
|
||||
assert!(three_way_shares(even, [1.0; 3], 1.3).iter().all(|x| (x - 1.0 / 3.0).abs() < 1e-12));
|
||||
let positional = three_way_shares(even, [1.0, 0.85, 0.85], 1.3);
|
||||
assert!(positional[0] > 1.0 / 3.0 && positional[1] < 1.0 / 3.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn triple_deal_weights_are_a_symmetric_distribution_close_to_the_pairwise_one() {
|
||||
let env = Environment::frozen();
|
||||
let tree = push_fold3_tree(&env, Seat::Button, 10.0).expect("tree");
|
||||
let n = CLASS_COUNT;
|
||||
let (aa, kk, ak, t9) = (class("Ah As"), class("Kh Ks"), class("Ah Kd"), class("Th 9h"));
|
||||
assert!((tree.weight(aa, kk, ak) - tree.weight(ak, aa, kk)).abs() < 1e-18);
|
||||
// Three pairs of aces cannot be dealt; the pairwise product only makes it rare (a known limit
|
||||
// of the approximation: 0.7 % of the weight of AA, KK, T9s, which needs no shared card).
|
||||
assert!(tree.weight(aa, aa, aa) < 0.01 * tree.weight(aa, kk, t9));
|
||||
let total: f64 = (0..n).map(|i| (0..n).map(|j| (0..n).map(|k| tree.weight(i, j, k)).sum::<f64>()).sum::<f64>()).sum();
|
||||
assert!((total - 1.0).abs() < 1e-9, "total {total}");
|
||||
// The two-player marginal stays within a few percent of the exact pairwise weight.
|
||||
for (i, j) in [(aa, kk), (aa, ak), (ak, t9), (kk, kk)] {
|
||||
let marginal: f64 = (0..n).map(|k| tree.weight(i, j, k)).sum();
|
||||
let exact = env.chance.probability(i, j);
|
||||
assert!((marginal / exact - 1.0).abs() < 0.05, "({i}, {j}): marginal {marginal}, exact {exact}");
|
||||
}
|
||||
}
|
||||
|
||||
fn pure(tree: &pokerfreak::cfr::tree3::Tree3, aggressive: bool) -> Strategy {
|
||||
Strategy::pure(tree, |_, _| if aggressive { 1 } else { 0 })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn push_fold_identities() {
|
||||
let env = Environment::frozen();
|
||||
// Button: nobody between the button and the small blind.
|
||||
let tree = push_fold3_tree(&env, Seat::Button, 10.0).expect("tree");
|
||||
// Everybody folds: the button's fold is worth 0.
|
||||
assert!(game_value3(&tree, &pure(&tree, false), 0).abs() < 1e-12);
|
||||
// The button always jams, both blinds always fold: +1.5 / -0.5 / -1.
|
||||
let steal = Strategy::pure(&tree, |name, _| usize::from(name == "push"));
|
||||
let values = [0, 1, 2].map(|p| game_value3(&tree, &steal, p));
|
||||
assert!((values[0] - 1.5).abs() < 1e-9 && (values[1] + 0.5).abs() < 1e-9 && (values[2] + 1.0).abs() < 1e-9, "{values:?}");
|
||||
// Everybody jams and calls: a symmetric three-way all-in, every player breaks even.
|
||||
let all_in = pure(&tree, true);
|
||||
for p in 0..3 {
|
||||
assert!(game_value3(&tree, &all_in, p).abs() < 1e-9, "player {p}");
|
||||
}
|
||||
// Calling everything is exploitable, the frozen-style check can fail.
|
||||
assert!(exploitability3(&tree, &all_in) > 0.1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_trees_have_the_documented_decisions_and_refuse_bad_input() {
|
||||
let env = Environment::frozen();
|
||||
let names = |nodes: &[Node3]| -> Vec<&'static str> {
|
||||
nodes.iter().filter_map(|n| match n {
|
||||
Node3::Decision { name, .. } => Some(*name),
|
||||
_ => None,
|
||||
}).collect()
|
||||
};
|
||||
let push = push_fold3_tree(&env, Seat::Early, 12.0).expect("tree");
|
||||
let mut found = names(&push.nodes);
|
||||
found.sort();
|
||||
assert_eq!(found, vec!["bb_overcall", "call", "push", "sb_call"]);
|
||||
let open = open3_tree(&env, Seat::Cutoff, 40.0).expect("tree");
|
||||
let mut found = names(&open.nodes);
|
||||
found.sort();
|
||||
assert_eq!(found, vec!["bb_overcall", "defend", "open", "sb_defend", "sb_vs_jam", "vs_jam", "vs_sb_three_bet", "vs_three_bet"]);
|
||||
assert!(push_fold3_tree(&env, Seat::SmallBlind, 10.0).is_err());
|
||||
assert!(open3_tree(&env, Seat::SmallBlind, 40.0).is_err());
|
||||
assert!(open3_tree(&env, Seat::Button, 10.0).is_err());
|
||||
assert!(push_fold3_tree(&env, Seat::Button, f64::NAN).is_err());
|
||||
}
|
||||
//! The three-player abstraction: deal weights, three-way pot shares and the game trees.
|
||||
//!
|
||||
//! Three-way shares come from the pairwise class equities (`cfr::three_way`): each hand's share is
|
||||
//! the weaker of its two pairwise equities, normalised. Reference: Monte Carlo with the engine's
|
||||
//! own evaluator over 200 000 boards for fixed combos (standard error about 0.1 %). The
|
||||
//! approximation is coarse. Observed (approx / sampled):
|
||||
//!
|
||||
//! | hands | approximation | Monte Carlo |
|
||||
//! |---|---|---|
|
||||
//! | AA, KK, QQ | 0.696 / 0.154 / 0.150 | 0.665 / 0.168 / 0.167 |
|
||||
//! | AKo, QQ, 72o | 0.386 / 0.508 / 0.106 | 0.396 / 0.494 / 0.110 |
|
||||
//! | AKs, AQo, KQo | 0.607 / 0.197 / 0.197 | 0.743 / 0.181 / 0.076 |
|
||||
//! | 22, AKo, T9s | 0.348 / 0.349 / 0.303 | 0.283 / 0.370 / 0.347 |
|
||||
//! | JTs, 99, AQo | 0.297 / 0.376 / 0.326 | 0.323 / 0.305 / 0.373 |
|
||||
//!
|
||||
//! Largest error 0.136 (dominated hands: AKs over AQo and KQo), root mean square 0.058. The
|
||||
//! product of the pairwise equities (0.129 / 0.068) and other means were not better. The
|
||||
//! favourite is kept where it is clear (a lead of 0.1 or more); near-even triples may swap.
|
||||
use pokerfreak::card::Card;
|
||||
use pokerfreak::cfr::environment::Environment;
|
||||
use pokerfreak::cfr::hand_class::{class_of, CLASS_COUNT};
|
||||
use pokerfreak::cfr::open3_game::open3_tree;
|
||||
use pokerfreak::cfr::push_fold3_game::push_fold3_tree;
|
||||
use pokerfreak::cfr::seat::Seat;
|
||||
use pokerfreak::cfr::strategy::Strategy;
|
||||
use pokerfreak::cfr::three_way::three_way_shares;
|
||||
use pokerfreak::cfr::tree3::Node3;
|
||||
use pokerfreak::cfr::walk3::{exploitability3, game_value3};
|
||||
use pokerfreak::equity::monte_carlo::estimate;
|
||||
use pokerfreak::equity::query::Query;
|
||||
use pokerfreak::equity::villain_range::VillainRange;
|
||||
use pokerfreak::rng::Rng;
|
||||
use pokerfreak::variant::{rules, Variant};
|
||||
|
||||
const SHARE_TOLERANCE: f64 = 0.14;
|
||||
|
||||
fn cs(text: &str) -> Vec<Card> {
|
||||
Card::parse_list(text).expect("cards")
|
||||
}
|
||||
|
||||
fn class(text: &str) -> usize {
|
||||
let c = cs(text);
|
||||
class_of(c[0], c[1]).expect("class")
|
||||
}
|
||||
|
||||
/// Monte-Carlo share of the first hand against the other two.
|
||||
fn sampled(hands: [&str; 3]) -> f64 {
|
||||
let villains = [VillainRange::Exact(cs(hands[1])), VillainRange::Exact(cs(hands[2]))];
|
||||
let hero = cs(hands[0]);
|
||||
let query = Query { rules: rules(Variant::Nlhe), hero: &hero, board: &[], villains: &villains, trials: 200_000 };
|
||||
estimate(&query, Rng::seeded(77)).expect("estimate").0.share
|
||||
}
|
||||
|
||||
fn approximated(env: &Environment, hands: [&str; 3]) -> [f64; 3] {
|
||||
let c = hands.map(class);
|
||||
let e = |x: usize, y: usize| if x == y { 0.5 } else { env.equity.get(c[x], c[y]) };
|
||||
three_way_shares([[e(0, 0), e(0, 1), e(0, 2)], [e(1, 0), e(1, 1), e(1, 2)], [e(2, 0), e(2, 1), e(2, 2)]], [1.0; 3], 1.0)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn three_way_shares_track_monte_carlo_and_keep_the_order() {
|
||||
let env = Environment::frozen();
|
||||
let matchups = [
|
||||
["Ah As", "Kh Ks", "Qd Qc"],
|
||||
["Ah Kd", "Qc Qs", "7h 2c"],
|
||||
["Ah Kh", "Ad Qc", "Kc Qd"],
|
||||
["2h 2d", "Ac Ks", "Th 9h"],
|
||||
["Js Ts", "9c 9d", "Ad Qh"],
|
||||
];
|
||||
for hands in matchups {
|
||||
let approx = approximated(&env, hands);
|
||||
let exact = [0, 1, 2].map(|k| sampled([hands[k], hands[(k + 1) % 3], hands[(k + 2) % 3]]));
|
||||
println!("{hands:?}: approx {approx:.3?}, sampled {exact:.3?}");
|
||||
for k in 0..3 {
|
||||
assert!(
|
||||
(approx[k] - exact[k]).abs() < SHARE_TOLERANCE,
|
||||
"{hands:?} hand {k}: approx {:.3}, sampled {:.3}",
|
||||
approx[k],
|
||||
exact[k]
|
||||
);
|
||||
}
|
||||
let best = |v: [f64; 3]| (0..3).fold(0, |b, k| if v[k] > v[b] { k } else { b });
|
||||
let mut sorted = exact;
|
||||
sorted.sort_by(|a, b| b.total_cmp(a));
|
||||
if sorted[0] - sorted[1] >= 0.1 {
|
||||
assert_eq!(best(approx), best(exact), "{hands:?}: favourite");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shares_sum_to_one_and_are_symmetric() {
|
||||
let eq = [[0.5, 0.7, 0.6], [0.3, 0.5, 0.55], [0.4, 0.45, 0.5]];
|
||||
for (weights, spread) in [([1.0; 3], 1.0), ([1.0, 0.85, 0.85], 1.3)] {
|
||||
let s = three_way_shares(eq, weights, spread);
|
||||
assert!((s.iter().sum::<f64>() - 1.0).abs() < 1e-12);
|
||||
assert!(s.iter().all(|x| (0.0..=1.0).contains(x)));
|
||||
}
|
||||
// Swapping two players swaps their shares.
|
||||
let swapped = [[0.5, 0.4, 0.45], [0.6, 0.5, 0.7], [0.55, 0.3, 0.5]];
|
||||
let (a, b) = (three_way_shares(eq, [1.0; 3], 1.0), three_way_shares(swapped, [1.0; 3], 1.0));
|
||||
assert!((a[0] - b[1]).abs() < 1e-12 && (a[1] - b[2]).abs() < 1e-12 && (a[2] - b[0]).abs() < 1e-12);
|
||||
// Equal hands split evenly; position weight moves chips to the player in position.
|
||||
let even = [[0.5; 3]; 3];
|
||||
assert!(three_way_shares(even, [1.0; 3], 1.3).iter().all(|x| (x - 1.0 / 3.0).abs() < 1e-12));
|
||||
let positional = three_way_shares(even, [1.0, 0.85, 0.85], 1.3);
|
||||
assert!(positional[0] > 1.0 / 3.0 && positional[1] < 1.0 / 3.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn triple_deal_weights_are_a_symmetric_distribution_close_to_the_pairwise_one() {
|
||||
let env = Environment::frozen();
|
||||
let tree = push_fold3_tree(&env, Seat::Button, 10.0).expect("tree");
|
||||
let n = CLASS_COUNT;
|
||||
let (aa, kk, ak, t9) = (class("Ah As"), class("Kh Ks"), class("Ah Kd"), class("Th 9h"));
|
||||
assert!((tree.weight(aa, kk, ak) - tree.weight(ak, aa, kk)).abs() < 1e-18);
|
||||
// Three pairs of aces cannot be dealt; the pairwise product only makes it rare (a known limit
|
||||
// of the approximation: 0.7 % of the weight of AA, KK, T9s, which needs no shared card).
|
||||
assert!(tree.weight(aa, aa, aa) < 0.01 * tree.weight(aa, kk, t9));
|
||||
let total: f64 = (0..n).map(|i| (0..n).map(|j| (0..n).map(|k| tree.weight(i, j, k)).sum::<f64>()).sum::<f64>()).sum();
|
||||
assert!((total - 1.0).abs() < 1e-9, "total {total}");
|
||||
// The two-player marginal stays within a few percent of the exact pairwise weight.
|
||||
for (i, j) in [(aa, kk), (aa, ak), (ak, t9), (kk, kk)] {
|
||||
let marginal: f64 = (0..n).map(|k| tree.weight(i, j, k)).sum();
|
||||
let exact = env.chance.probability(i, j);
|
||||
assert!((marginal / exact - 1.0).abs() < 0.05, "({i}, {j}): marginal {marginal}, exact {exact}");
|
||||
}
|
||||
}
|
||||
|
||||
fn pure(tree: &pokerfreak::cfr::tree3::Tree3, aggressive: bool) -> Strategy {
|
||||
Strategy::pure(tree, |_, _| if aggressive { 1 } else { 0 })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn push_fold_identities() {
|
||||
let env = Environment::frozen_free_table();
|
||||
// Button: nobody between the button and the small blind.
|
||||
let tree = push_fold3_tree(&env, Seat::Button, 10.0).expect("tree");
|
||||
// Everybody folds: the button's fold is worth 0.
|
||||
assert!(game_value3(&tree, &pure(&tree, false), 0).abs() < 1e-12);
|
||||
// The button always jams, both blinds always fold: +1.5 / -0.5 / -1.
|
||||
let steal = Strategy::pure(&tree, |name, _| usize::from(name == "push"));
|
||||
let values = [0, 1, 2].map(|p| game_value3(&tree, &steal, p));
|
||||
assert!((values[0] - 1.5).abs() < 1e-9 && (values[1] + 0.5).abs() < 1e-9 && (values[2] + 1.0).abs() < 1e-9, "{values:?}");
|
||||
// Everybody jams and calls: a symmetric three-way all-in, every player breaks even.
|
||||
let all_in = pure(&tree, true);
|
||||
for p in 0..3 {
|
||||
assert!(game_value3(&tree, &all_in, p).abs() < 1e-9, "player {p}");
|
||||
}
|
||||
// Calling everything is exploitable, the frozen-style check can fail.
|
||||
assert!(exploitability3(&tree, &all_in) > 0.1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_trees_have_the_documented_decisions_and_refuse_bad_input() {
|
||||
let env = Environment::frozen();
|
||||
let names = |nodes: &[Node3]| -> Vec<&'static str> {
|
||||
nodes.iter().filter_map(|n| match n {
|
||||
Node3::Decision { name, .. } => Some(*name),
|
||||
_ => None,
|
||||
}).collect()
|
||||
};
|
||||
let push = push_fold3_tree(&env, Seat::Early, 12.0).expect("tree");
|
||||
let mut found = names(&push.nodes);
|
||||
found.sort();
|
||||
assert_eq!(found, vec!["bb_overcall", "call", "push", "sb_call"]);
|
||||
let open = open3_tree(&env, Seat::Cutoff, 40.0).expect("tree");
|
||||
let mut found = names(&open.nodes);
|
||||
found.sort();
|
||||
assert_eq!(found, vec!["bb_overcall", "defend", "open", "sb_defend", "sb_vs_jam", "vs_jam", "vs_sb_three_bet", "vs_three_bet"]);
|
||||
assert!(push_fold3_tree(&env, Seat::SmallBlind, 10.0).is_err());
|
||||
assert!(open3_tree(&env, Seat::SmallBlind, 40.0).is_err());
|
||||
assert!(open3_tree(&env, Seat::Button, 10.0).is_err());
|
||||
assert!(push_fold3_tree(&env, Seat::Button, f64::NAN).is_err());
|
||||
}
|
||||
|
||||
+172
-171
@@ -1,171 +1,172 @@
|
||||
//! The generator reproduces the frozen tables; the recorded convergence iteration is real.
|
||||
//!
|
||||
//! Full reproduction (same seed, same iteration count => identical permille tables and
|
||||
//! metadata) is checked for a few representative spots, because every spot costs thousands of
|
||||
//! full-width CFR iterations. For the remaining spots the claim "the argmax chart is final from
|
||||
//! `stable_since` on" is checked by re-running only to that iteration, on a seeded sample of
|
||||
//! spots (`SAMPLE`). Three-player open spots cost minutes each at test optimisation, so the
|
||||
//! sampled `stable_since` check covers the push/fold spots of both decks and the open spots of
|
||||
//! the small blind (two players); the three-player open solver is the same generic `solve` and
|
||||
//! is covered through the three-player push/fold spots and the Nash test.
|
||||
use pokerfreak::cfr::chart_deck::ChartDeck;
|
||||
use pokerfreak::cfr::chart_signature::signature;
|
||||
use pokerfreak::cfr::environment::Environment;
|
||||
use pokerfreak::cfr::frozen_spot::PushFoldSpot;
|
||||
use pokerfreak::cfr::frozen_strategy::{open_strategy, push_fold3_strategy, push_fold_strategy};
|
||||
use pokerfreak::cfr::open_game::open_tree;
|
||||
use pokerfreak::cfr::push_fold3_game::push_fold3_tree;
|
||||
use pokerfreak::cfr::push_fold_game::push_fold_tree;
|
||||
use pokerfreak::cfr::render_charts::render_charts;
|
||||
use pokerfreak::cfr::run_plan::{open_iterations, push_fold_iterations, CFR_SEED};
|
||||
use pokerfreak::cfr::seat::Seat;
|
||||
use pokerfreak::cfr::solve::solve;
|
||||
use pokerfreak::cfr::spot_solver::{solve_open_spot, solve_push_fold_spot};
|
||||
use pokerfreak::preflop::generated_charts::{AOF_PUSH_FOLD, OPEN, PUSH_FOLD};
|
||||
use pokerfreak::preflop::generated_charts_short as short;
|
||||
use pokerfreak::rng::Rng;
|
||||
use pokerfreak::variant::{rules, Variant};
|
||||
|
||||
/// How many spots of each kind are re-run up to `stable_since`.
|
||||
const SAMPLE: u64 = 3;
|
||||
|
||||
#[test]
|
||||
fn iteration_counts_in_the_tables_are_the_plan() {
|
||||
for push in [&PUSH_FOLD[..], &short::PUSH_FOLD[..]] {
|
||||
assert!(push.iter().all(|s| s.meta.iterations == push_fold_iterations(s.seat)));
|
||||
}
|
||||
for open in [&OPEN[..], &short::OPEN[..]] {
|
||||
assert!(open.iter().all(|s| s.meta.iterations == open_iterations(s.seat)));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_push_fold_spot_is_reproduced_bit_for_bit() {
|
||||
// One three-player spot (button against both blinds) and one two-player spot.
|
||||
let env = Environment::frozen();
|
||||
for (seat, depth) in [(Seat::Button, 10u8), (Seat::SmallBlind, 5)] {
|
||||
let frozen = PUSH_FOLD.iter().find(|s| s.seat == seat && s.depth_bb == depth).expect("spot");
|
||||
let again = solve_push_fold_spot(&env, seat, depth).expect("spot");
|
||||
assert_eq!(&again, frozen, "{} {depth}bb", seat.label());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_short_deck_push_fold_spot_is_reproduced_bit_for_bit() {
|
||||
let env = Environment::frozen_for(ChartDeck::Short);
|
||||
let frozen = short::PUSH_FOLD.iter().find(|s| s.seat == Seat::Early && s.depth_bb == 15).expect("spot");
|
||||
assert_eq!(&solve_push_fold_spot(&env, Seat::Early, 15).expect("spot"), frozen);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_open_spot_is_reproduced_bit_for_bit() {
|
||||
let env = Environment::frozen();
|
||||
let frozen = OPEN.iter().find(|s| s.seat == Seat::SmallBlind && s.depth_bb == 40).expect("spot");
|
||||
let again = solve_open_spot(&env, Seat::SmallBlind, 40).expect("spot");
|
||||
assert_eq!(&again, frozen);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_all_in_or_fold_rules_generate_the_same_push_fold_tables() {
|
||||
// Generic over rules: the AOF rule set (binary action shape) yields the identical spot.
|
||||
let nlhe = Environment::frozen();
|
||||
let aof = Environment::new(&rules(Variant::Aof), pokerfreak::cfr::frozen_equity::frozen_equity())
|
||||
.expect("environment");
|
||||
let a = solve_push_fold_spot(&aof, Seat::Middle, 12).expect("spot");
|
||||
let b = solve_push_fold_spot(&nlhe, Seat::Middle, 12).expect("spot");
|
||||
assert_eq!(a, b);
|
||||
assert_eq!(&a, AOF_PUSH_FOLD.iter().find(|s| s.seat == Seat::Middle && s.depth_bb == 12).expect("spot"));
|
||||
}
|
||||
|
||||
fn sample_indices(len: usize, count: u64, seed: u64) -> Vec<usize> {
|
||||
let (picks, _) = (0..count).fold((Vec::new(), Rng::seeded(seed)), |(mut picks, rng), _| {
|
||||
let (k, rng) = rng.below(len as u64);
|
||||
picks.push(k as usize);
|
||||
(picks, rng)
|
||||
});
|
||||
picks
|
||||
}
|
||||
|
||||
fn push_fold_is_final_from_stable_since(env: &Environment, spot: &PushFoldSpot) {
|
||||
let label = format!("{} {}bb", spot.seat.label(), spot.depth_bb);
|
||||
if spot.seat == Seat::SmallBlind {
|
||||
let tree = push_fold_tree(env, spot.seat, spot.depth_bb as f64).expect("tree");
|
||||
let frozen = signature(&push_fold_strategy(&tree, spot).expect("strategy"));
|
||||
let early = solve(&tree, spot.meta.stable_since, Rng::seeded(CFR_SEED));
|
||||
assert_eq!(signature(&early.strategy), frozen, "{label}");
|
||||
} else {
|
||||
let tree = push_fold3_tree(env, spot.seat, spot.depth_bb as f64).expect("tree");
|
||||
let frozen = signature(&push_fold3_strategy(&tree, spot).expect("strategy"));
|
||||
let early = solve(&tree, spot.meta.stable_since, Rng::seeded(CFR_SEED));
|
||||
assert_eq!(signature(&early.strategy), frozen, "{label}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_argmax_chart_is_final_from_the_recorded_iteration_on_sampled_push_fold_spots() {
|
||||
let env = Environment::frozen();
|
||||
for k in sample_indices(PUSH_FOLD.len(), SAMPLE, 3) {
|
||||
push_fold_is_final_from_stable_since(&env, &PUSH_FOLD[k]);
|
||||
}
|
||||
let env = Environment::frozen_for(ChartDeck::Short);
|
||||
for k in sample_indices(short::PUSH_FOLD.len(), SAMPLE, 4) {
|
||||
push_fold_is_final_from_stable_since(&env, &short::PUSH_FOLD[k]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_argmax_chart_is_final_from_the_recorded_iteration_on_the_small_blind_open_spots() {
|
||||
let decks = [(Environment::frozen(), &OPEN[..]), (Environment::frozen_for(ChartDeck::Short), &short::OPEN[..])];
|
||||
for (env, open) in decks {
|
||||
for spot in open.iter().filter(|s| s.seat == Seat::SmallBlind) {
|
||||
let tree = open_tree(&env, spot.seat, spot.depth_bb as f64).expect("tree");
|
||||
let frozen = signature(&open_strategy(&tree, spot).expect("strategy"));
|
||||
let early = solve(&tree, spot.meta.stable_since, Rng::seeded(CFR_SEED));
|
||||
assert_eq!(signature(&early.strategy), frozen, "{} {}bb", spot.seat.label(), spot.depth_bb);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rendering_is_pure_and_describes_every_spot() {
|
||||
let text = render_charts(ChartDeck::Full, &PUSH_FOLD[..2], &OPEN[..1]);
|
||||
assert_eq!(text, render_charts(ChartDeck::Full, &PUSH_FOLD[..2], &OPEN[..1]));
|
||||
assert!(text.contains("PushFoldSpot {"));
|
||||
assert!(text.contains("OpenSpot {"));
|
||||
assert!(text.contains("cargo run --release --bin chartgen"));
|
||||
assert!(text.contains(&format!("{}", PUSH_FOLD[0].meta.iterations)));
|
||||
}
|
||||
|
||||
fn unix(text: &str) -> String {
|
||||
text.replace("\r\n", "\n")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_frozen_chart_file_is_exactly_what_the_generator_prints() {
|
||||
// `chartgen charts` renders its spots with `render_charts`; rendering the frozen spots back
|
||||
// must give the committed file, byte for byte (header, convergence table and data).
|
||||
let committed = unix(include_str!("../src/preflop/generated_charts.rs"));
|
||||
assert!(committed == render_charts(ChartDeck::Full, &PUSH_FOLD, &OPEN), "generated_charts.rs differs from the renderer output");
|
||||
let committed = unix(include_str!("../src/preflop/generated_charts_short.rs"));
|
||||
assert!(
|
||||
committed == render_charts(ChartDeck::Short, &short::PUSH_FOLD, &short::OPEN),
|
||||
"generated_charts_short.rs differs from the renderer output"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_frozen_equity_file_is_exactly_what_the_generator_prints() {
|
||||
use pokerfreak::cfr::generated_equity as frozen;
|
||||
use pokerfreak::cfr::render_equity::render_equity;
|
||||
let committed = unix(include_str!("../src/cfr/generated_equity.rs"));
|
||||
assert!(
|
||||
committed == render_equity(pokerfreak::cfr::chart_deck::ChartDeck::Full, frozen::SEED, frozen::SAMPLES, &frozen::TRIANGLE),
|
||||
"generated_equity.rs differs from the renderer output"
|
||||
);
|
||||
use pokerfreak::cfr::generated_equity_short as short_equity;
|
||||
let committed = unix(include_str!("../src/cfr/generated_equity_short.rs"));
|
||||
assert!(
|
||||
committed == render_equity(ChartDeck::Short, short_equity::SEED, short_equity::SAMPLES, &short_equity::TRIANGLE),
|
||||
"generated_equity_short.rs differs from the renderer output"
|
||||
);
|
||||
}
|
||||
//! The generator reproduces the frozen tables; the recorded convergence iteration is real.
|
||||
//!
|
||||
//! Full reproduction (same seed, same iteration count => identical permille tables and
|
||||
//! metadata) is checked for a few representative spots, because every spot costs thousands of
|
||||
//! full-width CFR iterations. For the remaining spots the claim "the argmax chart is final from
|
||||
//! `stable_since` on" is checked by re-running only to that iteration, on a seeded sample of
|
||||
//! spots (`SAMPLE`). Three-player open spots cost minutes each at test optimisation, so the
|
||||
//! sampled `stable_since` check covers the push/fold spots of both decks and the open spots of
|
||||
//! the small blind (two players); the three-player open solver is the same generic `solve` and
|
||||
//! is covered through the three-player push/fold spots and the Nash test.
|
||||
use pokerfreak::cfr::chart_deck::ChartDeck;
|
||||
use pokerfreak::cfr::chart_signature::signature;
|
||||
use pokerfreak::cfr::environment::Environment;
|
||||
use pokerfreak::cfr::frozen_spot::PushFoldSpot;
|
||||
use pokerfreak::cfr::frozen_strategy::{open_strategy, push_fold3_strategy, push_fold_strategy};
|
||||
use pokerfreak::cfr::open_game::open_tree;
|
||||
use pokerfreak::cfr::push_fold3_game::push_fold3_tree;
|
||||
use pokerfreak::cfr::push_fold_game::push_fold_tree;
|
||||
use pokerfreak::cfr::render_charts::render_charts;
|
||||
use pokerfreak::cfr::run_plan::{open_iterations, push_fold_iterations, CFR_SEED};
|
||||
use pokerfreak::cfr::seat::Seat;
|
||||
use pokerfreak::cfr::solve::solve;
|
||||
use pokerfreak::cfr::spot_solver::{solve_open_spot, solve_push_fold_spot};
|
||||
use pokerfreak::preflop::generated_charts::{AOF_PUSH_FOLD, OPEN, PUSH_FOLD};
|
||||
use pokerfreak::preflop::generated_charts_short as short;
|
||||
use pokerfreak::rng::Rng;
|
||||
use pokerfreak::variant::{rules, Variant};
|
||||
|
||||
/// How many spots of each kind are re-run up to `stable_since`.
|
||||
const SAMPLE: u64 = 3;
|
||||
|
||||
#[test]
|
||||
fn iteration_counts_in_the_tables_are_the_plan() {
|
||||
for push in [&PUSH_FOLD[..], &short::PUSH_FOLD[..]] {
|
||||
assert!(push.iter().all(|s| s.meta.iterations == push_fold_iterations(s.seat)));
|
||||
}
|
||||
for open in [&OPEN[..], &short::OPEN[..]] {
|
||||
assert!(open.iter().all(|s| s.meta.iterations == open_iterations(s.seat)));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_push_fold_spot_is_reproduced_bit_for_bit() {
|
||||
// One three-player spot (button against both blinds) and one two-player spot.
|
||||
let env = Environment::frozen();
|
||||
for (seat, depth) in [(Seat::Button, 10u8), (Seat::SmallBlind, 5)] {
|
||||
let frozen = PUSH_FOLD.iter().find(|s| s.seat == seat && s.depth_bb == depth).expect("spot");
|
||||
let again = solve_push_fold_spot(&env, seat, depth).expect("spot");
|
||||
assert_eq!(&again, frozen, "{} {depth}bb", seat.label());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_short_deck_push_fold_spot_is_reproduced_bit_for_bit() {
|
||||
let env = Environment::frozen_for(ChartDeck::Short);
|
||||
let frozen = short::PUSH_FOLD.iter().find(|s| s.seat == Seat::Early && s.depth_bb == 15).expect("spot");
|
||||
assert_eq!(&solve_push_fold_spot(&env, Seat::Early, 15).expect("spot"), frozen);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_open_spot_is_reproduced_bit_for_bit() {
|
||||
let env = Environment::frozen();
|
||||
let frozen = OPEN.iter().find(|s| s.seat == Seat::SmallBlind && s.depth_bb == 40).expect("spot");
|
||||
let again = solve_open_spot(&env, Seat::SmallBlind, 40).expect("spot");
|
||||
assert_eq!(&again, frozen);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_all_in_or_fold_rules_generate_the_same_push_fold_tables() {
|
||||
// Generic over rules: the AOF rule set (binary action shape) yields the identical spot.
|
||||
let nlhe = Environment::frozen();
|
||||
let aof = Environment::new(&rules(Variant::Aof), pokerfreak::cfr::frozen_equity::frozen_equity())
|
||||
.expect("environment");
|
||||
let aof = Environment { rake: nlhe.rake, antes: nlhe.antes, ..aof };
|
||||
let a = solve_push_fold_spot(&aof, Seat::Middle, 12).expect("spot");
|
||||
let b = solve_push_fold_spot(&nlhe, Seat::Middle, 12).expect("spot");
|
||||
assert_eq!(a, b);
|
||||
assert_eq!(&a, AOF_PUSH_FOLD.iter().find(|s| s.seat == Seat::Middle && s.depth_bb == 12).expect("spot"));
|
||||
}
|
||||
|
||||
fn sample_indices(len: usize, count: u64, seed: u64) -> Vec<usize> {
|
||||
let (picks, _) = (0..count).fold((Vec::new(), Rng::seeded(seed)), |(mut picks, rng), _| {
|
||||
let (k, rng) = rng.below(len as u64);
|
||||
picks.push(k as usize);
|
||||
(picks, rng)
|
||||
});
|
||||
picks
|
||||
}
|
||||
|
||||
fn push_fold_is_final_from_stable_since(env: &Environment, spot: &PushFoldSpot) {
|
||||
let label = format!("{} {}bb", spot.seat.label(), spot.depth_bb);
|
||||
if spot.seat == Seat::SmallBlind {
|
||||
let tree = push_fold_tree(env, spot.seat, spot.depth_bb as f64).expect("tree");
|
||||
let frozen = signature(&push_fold_strategy(&tree, spot).expect("strategy"));
|
||||
let early = solve(&tree, spot.meta.stable_since, Rng::seeded(CFR_SEED));
|
||||
assert_eq!(signature(&early.strategy), frozen, "{label}");
|
||||
} else {
|
||||
let tree = push_fold3_tree(env, spot.seat, spot.depth_bb as f64).expect("tree");
|
||||
let frozen = signature(&push_fold3_strategy(&tree, spot).expect("strategy"));
|
||||
let early = solve(&tree, spot.meta.stable_since, Rng::seeded(CFR_SEED));
|
||||
assert_eq!(signature(&early.strategy), frozen, "{label}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_argmax_chart_is_final_from_the_recorded_iteration_on_sampled_push_fold_spots() {
|
||||
let env = Environment::frozen();
|
||||
for k in sample_indices(PUSH_FOLD.len(), SAMPLE, 3) {
|
||||
push_fold_is_final_from_stable_since(&env, &PUSH_FOLD[k]);
|
||||
}
|
||||
let env = Environment::frozen_for(ChartDeck::Short);
|
||||
for k in sample_indices(short::PUSH_FOLD.len(), SAMPLE, 4) {
|
||||
push_fold_is_final_from_stable_since(&env, &short::PUSH_FOLD[k]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_argmax_chart_is_final_from_the_recorded_iteration_on_the_small_blind_open_spots() {
|
||||
let decks = [(Environment::frozen(), &OPEN[..]), (Environment::frozen_for(ChartDeck::Short), &short::OPEN[..])];
|
||||
for (env, open) in decks {
|
||||
for spot in open.iter().filter(|s| s.seat == Seat::SmallBlind) {
|
||||
let tree = open_tree(&env, spot.seat, spot.depth_bb as f64).expect("tree");
|
||||
let frozen = signature(&open_strategy(&tree, spot).expect("strategy"));
|
||||
let early = solve(&tree, spot.meta.stable_since, Rng::seeded(CFR_SEED));
|
||||
assert_eq!(signature(&early.strategy), frozen, "{} {}bb", spot.seat.label(), spot.depth_bb);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rendering_is_pure_and_describes_every_spot() {
|
||||
let text = render_charts(ChartDeck::Full, &PUSH_FOLD[..2], &OPEN[..1]);
|
||||
assert_eq!(text, render_charts(ChartDeck::Full, &PUSH_FOLD[..2], &OPEN[..1]));
|
||||
assert!(text.contains("PushFoldSpot {"));
|
||||
assert!(text.contains("OpenSpot {"));
|
||||
assert!(text.contains("cargo run --release --bin chartgen"));
|
||||
assert!(text.contains(&format!("{}", PUSH_FOLD[0].meta.iterations)));
|
||||
}
|
||||
|
||||
fn unix(text: &str) -> String {
|
||||
text.replace("\r\n", "\n")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_frozen_chart_file_is_exactly_what_the_generator_prints() {
|
||||
// `chartgen charts` renders its spots with `render_charts`; rendering the frozen spots back
|
||||
// must give the committed file, byte for byte (header, convergence table and data).
|
||||
let committed = unix(include_str!("../src/preflop/generated_charts.rs"));
|
||||
assert!(committed == render_charts(ChartDeck::Full, &PUSH_FOLD, &OPEN), "generated_charts.rs differs from the renderer output");
|
||||
let committed = unix(include_str!("../src/preflop/generated_charts_short.rs"));
|
||||
assert!(
|
||||
committed == render_charts(ChartDeck::Short, &short::PUSH_FOLD, &short::OPEN),
|
||||
"generated_charts_short.rs differs from the renderer output"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_frozen_equity_file_is_exactly_what_the_generator_prints() {
|
||||
use pokerfreak::cfr::generated_equity as frozen;
|
||||
use pokerfreak::cfr::render_equity::render_equity;
|
||||
let committed = unix(include_str!("../src/cfr/generated_equity.rs"));
|
||||
assert!(
|
||||
committed == render_equity(pokerfreak::cfr::chart_deck::ChartDeck::Full, frozen::SEED, frozen::SAMPLES, &frozen::TRIANGLE),
|
||||
"generated_equity.rs differs from the renderer output"
|
||||
);
|
||||
use pokerfreak::cfr::generated_equity_short as short_equity;
|
||||
let committed = unix(include_str!("../src/cfr/generated_equity_short.rs"));
|
||||
assert!(
|
||||
committed == render_equity(ChartDeck::Short, short_equity::SEED, short_equity::SAMPLES, &short_equity::TRIANGLE),
|
||||
"generated_equity_short.rs differs from the renderer output"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
//! Antes are dead money, not action: a pot of blinds plus antes is still unopened.
|
||||
//!
|
||||
//! Measured at the table 1000/2000: six antes of 320 make a first-in pot of 2.46 bb
|
||||
//! (`game.potInfo` 4920), above the 2.25 bb the chip-count heuristic allows for "blinds only".
|
||||
//!
|
||||
//! Six-max, button on seat 3: EP 0, MP 1, CO 2, BTN 3, SB 4, BB 5. Big blind = 1.0.
|
||||
use pokerfreak::card::Card;
|
||||
use pokerfreak::exploit::thresholds::Thresholds;
|
||||
use pokerfreak::game::{ActionKind, ActionRecord, SeenAction, Spot, Street, Villain};
|
||||
use pokerfreak::preflop::advise::advise;
|
||||
use pokerfreak::preflop::plan::PreflopPlan;
|
||||
use pokerfreak::variant::Variant;
|
||||
|
||||
const ANTE: f64 = 0.16;
|
||||
const SEATS: [u8; 6] = [0, 1, 2, 3, 4, 5];
|
||||
|
||||
fn record(seat: u8, action: SeenAction, amount: Option<f64>) -> ActionRecord {
|
||||
ActionRecord { street: Street::Preflop, seat, action, amount }
|
||||
}
|
||||
|
||||
fn table(ante: f64) -> Vec<ActionRecord> {
|
||||
let mut h: Vec<ActionRecord> = if ante > 0.0 {
|
||||
SEATS.iter().map(|s| record(*s, SeenAction::PostAnte, Some(ante))).collect()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
h.push(record(4, SeenAction::PostSmallBlind, Some(0.5)));
|
||||
h.push(record(5, SeenAction::PostBigBlind, Some(1.0)));
|
||||
h
|
||||
}
|
||||
|
||||
fn spot(hole: &str, hero_seat: u8, history: Vec<ActionRecord>, pot: f64, to_call: f64) -> Spot {
|
||||
Spot {
|
||||
variant: Variant::Nlhe,
|
||||
big_blind: 1.0,
|
||||
seats: 6,
|
||||
hero_seat,
|
||||
button_seat: Some(3),
|
||||
hero_cards: Card::parse_list(hole).expect("cards"),
|
||||
board: vec![],
|
||||
street: Street::Preflop,
|
||||
pot,
|
||||
to_call,
|
||||
hero_stack: 100.0,
|
||||
min_raise_to: Some(2.0 * to_call.max(1.0) + 1.0),
|
||||
max_raise_to: Some(100.0),
|
||||
legal: vec![ActionKind::Fold, ActionKind::Call, ActionKind::Raise],
|
||||
allowed_sizes: None,
|
||||
villains: SEATS
|
||||
.iter()
|
||||
.filter(|s| **s != hero_seat)
|
||||
.map(|s| Villain { seat: *s, stack: 100.0, folded: false, profile: None })
|
||||
.collect(),
|
||||
seed: 1,
|
||||
history,
|
||||
}
|
||||
}
|
||||
|
||||
fn plan(s: &Spot) -> PreflopPlan {
|
||||
advise(s, &Thresholds::BASE)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_full_table_of_antes_is_still_first_in() {
|
||||
let antes = plan(&spot("Ah Kd", 3, table(ANTE), 1.5 + 6.0 * ANTE, 1.0));
|
||||
let free = plan(&spot("Ah Kd", 3, table(0.0), 1.5, 1.0));
|
||||
assert!(antes.reason.contains("CFR"), "{}", antes.reason);
|
||||
assert_eq!(antes.reason, free.reason);
|
||||
assert_eq!(antes.action, free.action);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_small_blind_first_in_reads_the_table_with_antes() {
|
||||
let p = plan(&spot("Qh 3d", 4, table(ANTE), 1.5 + 6.0 * ANTE, 0.5));
|
||||
assert!(p.reason.contains("CFR"), "{}", p.reason);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_limper_is_still_a_limper_with_antes() {
|
||||
let mut h = table(ANTE);
|
||||
h.push(record(1, SeenAction::Call, Some(1.0)));
|
||||
let antes = plan(&spot("Ah Kd", 3, h, 2.5 + 6.0 * ANTE, 1.0));
|
||||
assert!(antes.reason.contains("limp"), "{}", antes.reason);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_open_is_still_an_open_with_antes() {
|
||||
let mut h = table(ANTE);
|
||||
h.push(record(0, SeenAction::Raise, Some(2.5)));
|
||||
let antes = plan(&spot("Ah Kd", 3, h.clone(), 4.0 + 6.0 * ANTE, 2.5));
|
||||
let mut free = table(0.0);
|
||||
free.push(record(0, SeenAction::Raise, Some(2.5)));
|
||||
assert_eq!(antes.reason, plan(&spot("Ah Kd", 3, free, 4.0, 2.5)).reason);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_big_pot_without_ante_records_still_counts_as_limped() {
|
||||
// No history to tell antes from a limp: the chip count stays the only witness.
|
||||
let p = plan(&spot("Ah Kd", 3, Vec::new(), 2.46, 1.0));
|
||||
assert!(p.reason.contains("limp"), "{}", p.reason);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unusable_ante_amounts_are_ignored() {
|
||||
let mut h = table(0.0);
|
||||
h.push(record(0, SeenAction::PostAnte, Some(f64::NAN)));
|
||||
h.push(record(1, SeenAction::PostAnte, Some(-5.0)));
|
||||
h.push(record(2, SeenAction::PostAnte, None));
|
||||
let p = plan(&spot("Ah Kd", 3, h, 2.46, 1.0));
|
||||
assert!(p.reason.contains("limp"), "{}", p.reason);
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
//! Spezifikation der Rake-Rechnung. Die Zahlen stammen aus echten Händen des Tisches 1000/2000
|
||||
//! (`game.winnerInfo`, `potAmount` gegen `potAmountAfterRake`); die Hand steht am Fall.
|
||||
|
||||
use pokerfreak::rake::{split_over_pots, uncalled, ChartRake, HandEnd, RakeRule, MEASURED_ANTE_BB};
|
||||
|
||||
/// Der gemessene Tisch in seiner eigenen Währung.
|
||||
const TABLE: RakeRule = RakeRule { percent: 5.0, cap: 2000.0, cap_more_than_three: 2000.0 };
|
||||
|
||||
fn near(a: f64, b: f64) {
|
||||
assert!((a - b).abs() < 1e-9, "{a} != {b}");
|
||||
}
|
||||
|
||||
// -- Eine Hand ------------------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_pot_under_the_cap_pays_five_percent_antes_included() {
|
||||
// Hand 166457200019, Topf 4640 samt Antes: 232 Rake.
|
||||
near(TABLE.of_hand(4640.0, 2, HandEnd::FlopDealt), 232.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cap_stops_the_rake() {
|
||||
// Hand 166408600402: Topf 191680, 2000 Rake.
|
||||
near(TABLE.of_hand(191_680.0, 2, HandEnd::FlopDealt), 2000.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cap_starts_exactly_at_twenty_big_blinds() {
|
||||
near(TABLE.of_hand(39_999.0, 2, HandEnd::FlopDealt), 1999.95);
|
||||
near(TABLE.of_hand(40_000.0, 2, HandEnd::FlopDealt), 2000.0);
|
||||
near(TABLE.of_hand(40_001.0, 2, HandEnd::FlopDealt), 2000.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn heads_up_pays_the_same_as_three_players() {
|
||||
assert_eq!(TABLE.of_hand(10_000.0, 2, HandEnd::FlopDealt), TABLE.of_hand(10_000.0, 3, HandEnd::FlopDealt));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hand_that_ends_before_the_flop_pays_nothing() {
|
||||
assert_eq!(TABLE.of_hand(21_600.0, 2, HandEnd::NoFlop), 0.0);
|
||||
assert_eq!(TABLE.of_hand(1_000_000.0, 6, HandEnd::NoFlop), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn more_than_three_players_use_their_own_cap_and_three_do_not() {
|
||||
let rule = RakeRule { percent: 5.0, cap: 100.0, cap_more_than_three: 40.0 };
|
||||
near(rule.of_hand(10_000.0, 3, HandEnd::FlopDealt), 100.0);
|
||||
near(rule.of_hand(10_000.0, 4, HandEnd::FlopDealt), 40.0);
|
||||
near(rule.of_hand(500.0, 4, HandEnd::FlopDealt), 25.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_or_broken_pot_pays_nothing() {
|
||||
assert_eq!(TABLE.of_hand(0.0, 2, HandEnd::FlopDealt), 0.0);
|
||||
assert_eq!(TABLE.of_hand(-5.0, 2, HandEnd::FlopDealt), 0.0);
|
||||
assert_eq!(TABLE.of_hand(f64::NAN, 2, HandEnd::FlopDealt), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_measured_table_in_big_blinds_is_the_table_above() {
|
||||
let bb = 2000.0;
|
||||
for pot in [4640.0, 39_999.0, 191_680.0] {
|
||||
near(RakeRule::MEASURED_BB.of_hand(pot / bb, 2, HandEnd::FlopDealt) * bb, TABLE.of_hand(pot, 2, HandEnd::FlopDealt));
|
||||
}
|
||||
near(MEASURED_ANTE_BB, 320.0 / bb);
|
||||
}
|
||||
|
||||
// -- Side Pots ------------------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn the_cap_holds_per_hand_and_is_shared_in_proportion_to_the_pots() {
|
||||
// Hand 166408600403: Töpfe 609640 und 574480, abgezogen 1029,69 und 970,31.
|
||||
let pots = [609_640.0, 574_480.0];
|
||||
let total = TABLE.of_hand(pots.iter().sum(), 2, HandEnd::FlopDealt);
|
||||
let parts = split_over_pots(total, &pots);
|
||||
near(total, 2000.0);
|
||||
assert!((parts[0] - 1029.69).abs() < 0.01, "{}", parts[0]);
|
||||
assert!((parts[1] - 970.31).abs() < 0.01, "{}", parts[1]);
|
||||
near(parts.iter().sum(), 2000.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_to_split_stays_empty_or_zero() {
|
||||
assert!(split_over_pots(100.0, &[]).is_empty());
|
||||
assert_eq!(split_over_pots(100.0, &[0.0, 0.0]), vec![0.0, 0.0]);
|
||||
assert_eq!(split_over_pots(100.0, &[50.0]), vec![100.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_part_nobody_called_comes_back() {
|
||||
assert_eq!(uncalled(&[10.0, 4.0, 4.0]), Some((0, 6.0)));
|
||||
assert_eq!(uncalled(&[1.0, 8.0, 3.0]), Some((1, 5.0)));
|
||||
assert_eq!(uncalled(&[5.0, 5.0]).map(|u| u.1), Some(0.0));
|
||||
assert_eq!(uncalled(&[5.0]), None);
|
||||
}
|
||||
|
||||
// -- Rake in den Chart-Spielen --------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn no_rake_is_no_rake() {
|
||||
assert_eq!(ChartRake::None.postflop(5.5), 0.0);
|
||||
assert_eq!(ChartRake::None.all_in(200.0), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_all_in_pays_the_exact_rule_on_the_pot() {
|
||||
near(ChartRake::Measured.all_in(200.0), 1.0);
|
||||
near(ChartRake::Measured.all_in(5.96), 0.05 * 5.96);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pot_with_chips_behind_pays_what_such_pots_paid_at_the_table() {
|
||||
// Mittlerer Rake je Flop-Topf (Topf samt Antes, aus 728 Händen; Kopf von `rake`).
|
||||
near(ChartRake::Measured.postflop(4.0), 0.489);
|
||||
near(ChartRake::Measured.postflop(6.46), 0.720);
|
||||
near(ChartRake::Measured.postflop(10.0), 0.850);
|
||||
near(ChartRake::Measured.postflop(19.46), 0.906);
|
||||
near(ChartRake::Measured.postflop(60.0), 0.950);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_flop_pot_on_a_bucket_bound_belongs_to_the_next_bucket() {
|
||||
near(ChartRake::Measured.postflop(6.0), 0.720);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_postflop_rake_never_shrinks_with_the_pot_and_never_passes_the_cap() {
|
||||
let mut last = 0.0;
|
||||
for k in 0..400 {
|
||||
let r = ChartRake::Measured.postflop(k as f64 * 0.5);
|
||||
assert!(r >= last && r <= 1.0, "{k}: {r}");
|
||||
last = r;
|
||||
}
|
||||
}
|
||||
+75
-2
@@ -11,8 +11,8 @@
|
||||
use pokerfreak::card::Card;
|
||||
use pokerfreak::rng::Rng;
|
||||
use pokerfreak::sim::opponent::{Act, Opponent, View};
|
||||
use pokerfreak::sim::session::{measure, Measurement, Setup};
|
||||
use pokerfreak::sim::table::{deal, play_hand, Deal, HandSetup};
|
||||
use pokerfreak::sim::session::{measure, measure_at, Measurement, Setup};
|
||||
use pokerfreak::sim::table::{deal, play_hand, play_hand_at, Deal, HandSetup, TableCost};
|
||||
|
||||
fn setup(players: u8, opponent: Opponent, deals: u32) -> Setup {
|
||||
Setup { players, opponent, deals, stack_bb: 100.0, seed: 0x5EED_0001 }
|
||||
@@ -200,3 +200,76 @@ fn long_run_heads_up_and_six_max() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// -- Rake und Ante --------------------------------------------------------------------------
|
||||
|
||||
fn at_measured_table(d: &Deal, hero_seat: u8, opponent: Opponent) -> pokerfreak::sim::table::HandResult {
|
||||
play_hand_at(&HandSetup { deal: d, hero_seat, opponent, stack_bb: 100.0, seed: 1 }, TableCost::MEASURED)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hand_that_ends_before_the_flop_pays_antes_but_no_rake() {
|
||||
// Heads-up: der Folder gibt seinen Small Blind und seine Ante ab.
|
||||
let d = fixed_deal(&["2c 7d", "As Ah"], "Kd Qc 9s 4h 3c");
|
||||
let r = at_measured_table(&d, 2, Opponent::Folder);
|
||||
assert_eq!(r.rake, 0.0);
|
||||
assert!((r.hero_net - 0.66).abs() < 1e-9, "{}", r.hero_net);
|
||||
assert!(r.chips_lost.abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_showdown_pays_rake_and_the_chips_balance() {
|
||||
let d = fixed_deal(&["As Ah", "7c 2d"], "Kd Qc 9s 4h 3c");
|
||||
let free = play_hand(&HandSetup { deal: &d, hero_seat: 1, opponent: Opponent::CallingStation, stack_bb: 100.0, seed: 1 });
|
||||
let raked = at_measured_table(&d, 1, Opponent::CallingStation);
|
||||
assert!(raked.rake > 0.0 && raked.rake <= 1.0, "{}", raked.rake);
|
||||
assert!(free.hero_net > 0.0);
|
||||
assert!(raked.chips_lost.abs() < 1e-9, "{}", raked.chips_lost);
|
||||
assert!(raked.invalid == 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn six_handed_random_hands_balance_with_the_rake_within_the_cap() {
|
||||
for seed in 0..40 {
|
||||
let (d, _) = deal(6, Rng::seeded(seed));
|
||||
for hero_seat in 1..=6u8 {
|
||||
let r = play_hand_at(
|
||||
&HandSetup { deal: &d, hero_seat, opponent: Opponent::RandomLegal, stack_bb: 100.0, seed },
|
||||
TableCost::MEASURED,
|
||||
);
|
||||
assert!(r.chips_lost.abs() < 1e-6, "{}", r.chips_lost);
|
||||
assert!(r.rake >= 0.0 && r.rake <= 1.0 + 1e-9, "{}", r.rake);
|
||||
assert_eq!(r.invalid, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_free_table_takes_nothing() {
|
||||
let m = measure(&setup(2, Opponent::RandomLegal, 20));
|
||||
assert_eq!(m.rake_bb_per_100, 0.0);
|
||||
let n = measure_at(&setup(2, Opponent::RandomLegal, 20), TableCost::MEASURED);
|
||||
assert!(n.rake_bb_per_100 > 0.0);
|
||||
assert_eq!(n.invalid, 0);
|
||||
}
|
||||
|
||||
/// Netto-Messung am gemessenen Tisch: 95-%-Intervall, Vergleichszahlen in MODULES.md.
|
||||
const NET_RUN: [(u8, u32); 2] = [(2, 2000), (6, 200)];
|
||||
|
||||
#[test]
|
||||
#[ignore = "Netto-Lauf: cargo test --release --test sim_strength net_run -- --ignored --nocapture"]
|
||||
fn net_run_at_the_measured_table() {
|
||||
for (players, deals) in NET_RUN {
|
||||
for opponent in Opponent::ALL {
|
||||
let gross = measure(&setup(players, opponent, deals));
|
||||
let net = measure_at(&setup(players, opponent, deals), TableCost::MEASURED);
|
||||
let ante_only = measure_at(&setup(players, opponent, deals), TableCost { rake: None, ..TableCost::MEASURED });
|
||||
println!(
|
||||
"{players} Spieler, {}: brutto {gross} | nur Ante {ante_only} | netto {net} | Rake Tisch {:.1} bb/100",
|
||||
opponent.name(),
|
||||
net.rake_bb_per_100
|
||||
);
|
||||
assert_eq!(net.invalid, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user