From 015baff121d387c9ca6d7bb3a478a09edd556317 Mon Sep 17 00:00:00 2001 From: Marc Mintel Date: Sat, 7 Nov 2026 09:59:18 +0100 Subject: [PATCH] PLO5-Preflop: Struktur-Chart gegen echte Equity kalibriert Die Preflop-Heuristik war bisher ungemessen gegen echte All-in-Equity. Neue Mess-/Kalibrier-Hilfe (bin/plo5_calibrate) misst mit dem vorhandenen Monte-Carlo-Kern (SSOT) die Rangkorrelation Score<->Equity und erzeugt die Perzentil-Tabelle neu. Kalibrierte Gewichte (benannt, begruendet, keine Magic Numbers): - Rundown rangbewusst: hohe Runs zaehlen mehr als tiefe (WINDOW_HEIGHT). - Hohe Karten steiler, kleine Paare flacher (Omaha-Equity folgt den hohen Karten). - Suit-Wert nutbewusst: ein tiefer Zwei-Flush und der tote dritte Suit-Karten- Bonus werden nicht mehr ueberbewertet. - Perzentil-Tabelle aus den neuen Gewichten neu ausgezaehlt. Beleg (Spearman rho, 200 Haende, fester Seed, unverzerrter Sampler): heads-up 0.760 -> 0.858, 3 Gegner 0.787 -> 0.877, 5 Gegner 0.772 -> 0.871. Struktur-Invarianten in tests/preflop_plo5.rs bleiben gruen (Sampler-Modulo- Bias entfernt), zwei Equity-Belege ergaenzt. NLHE-Benchmark unveraendert (+0.00). --- src/bin/plo5_calibrate.rs | 225 ++++++++++++++++++++++++++++++++ src/preflop/plo5_pair_bonus.rs | 10 +- src/preflop/plo5_rundown.rs | 26 +++- src/preflop/plo5_score_table.rs | 60 +++++---- src/preflop/plo5_suits.rs | 17 ++- tests/preflop_plo5.rs | 108 ++++++++++++++- 6 files changed, 399 insertions(+), 47 deletions(-) create mode 100644 src/bin/plo5_calibrate.rs diff --git a/src/bin/plo5_calibrate.rs b/src/bin/plo5_calibrate.rs new file mode 100644 index 00000000..3d1e234b --- /dev/null +++ b/src/bin/plo5_calibrate.rs @@ -0,0 +1,225 @@ +//! Mess- und Kalibrier-Hilfe fuer die PLO5-Preflop-Chart. +//! +//! Die Preflop-Heuristik (`plo5_score`) rankt Starthaende strukturell. Diese Hilfe misst, +//! wie gut diese Ordnung der ECHTEN All-in-Preflop-Equity folgt, indem sie den vorhandenen +//! Monte-Carlo-Equity-Kern (`equity::monte_carlo`) nutzt (SSOT, kein zweiter Rechner). +//! +//! ```text +//! cargo run --release --bin plo5_calibrate -- measure # Rangkorrelation Score<->Equity +//! cargo run --release --bin plo5_calibrate -- measure --villains 1 --hands 200 --trials 40000 +//! cargo run --release --bin plo5_calibrate -- table # Perzentil-Tabelle neu erzeugen +//! ``` +//! +//! `measure` nennt die Spearman-Rangkorrelation Score<->Equity und die groebsten +//! Fehl-Einordnungen (Haende, deren Score-Rang weit vom Equity-Rang abweicht). +//! `table` zaehlt alle 2 598 960 Fuenf-Karten-Haende aus und schreibt den Quelltext der +//! Perzentil-Tabelle nach stdout (Fortschritt nach stderr). + +use rechner::card::{deck, Card}; +use rechner::equity::monte_carlo::estimate; +use rechner::equity::query::Query; +use rechner::equity::villain_range::VillainRange; +use rechner::preflop::plo5_score::score; +use rechner::rng::Rng; +use rechner::variant::{rules, Variant}; + +/// Basis-Seed des Equity-Kerns; fester Wert fuer Reproduzierbarkeit. +const EQUITY_SEED: u64 = 0x50C5_0C51_2024_2024; +/// Seed des deterministischen Hand-Samplers (unabhaengig vom Equity-Kern). +const SAMPLER_SEED: u64 = 0x2545_F491_4F6C_DD1D; +const DEFAULT_HANDS: usize = 200; +const DEFAULT_TRIALS: u32 = 40_000; +const DEFAULT_VILLAINS: usize = 1; +/// So viele der groebsten Fehl-Einordnungen werden gezeigt. +const WORST_SHOWN: usize = 14; + +fn option(args: &[String], name: &str) -> Option { + args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).and_then(|v| v.parse().ok()) +} + +/// Deterministische Pseudo-Zufalls-Fuenfkartenhaende (LCG), unabhaengig vom Rng des Kerns. +/// Spiegelt den Sampler aus `tests/preflop_plo5.rs`, damit Messung und Test dieselbe Grundmenge sehen. +fn sample_hands(count: usize) -> Vec> { + const CARDS: u8 = 52; + /// Groesstes Vielfache von 52 im Byte (4 * 52); Bytes darueber werden verworfen, damit kein + /// `byte % 52` die Asse unterrepraesentiert. + const CUTOFF: u8 = 208; + let mut state: u64 = SAMPLER_SEED; + let mut next = move || { + state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (state >> 33) as u8 + }; + let mut draw_card = move || loop { + let byte = next(); + if byte < CUTOFF { + return byte % CARDS; + } + }; + (0..count) + .map(|_| { + let mut picked: Vec = Vec::new(); + while picked.len() < 5 { + let c = draw_card(); + if !picked.contains(&c) { + picked.push(c); + } + } + picked.into_iter().filter_map(Card::from_index).collect() + }) + .collect() +} + +/// Echte Heads-up-/Multiway-Equity einer Starthand gegen `villains` zufaellige Gegner. +/// Gleicher Seed je Hand => gemeinsame Zufallszahlen, die Rang-Vergleiche entrauschen. +fn equity_of(hand: &[Card], villains_count: usize, trials: u32) -> f64 { + let villains: Vec = (0..villains_count).map(|_| VillainRange::Any).collect(); + let query = Query { rules: rules(Variant::Plo5), hero: hand, board: &[], villains: &villains, trials }; + estimate(&query, Rng::seeded(EQUITY_SEED)).expect("equity estimate").0.share +} + +/// Durchschnittsraenge (1-basiert): gleich grosse Werte teilen den mittleren Rang. +fn average_ranks(values: &[f64]) -> Vec { + let mut order: Vec = (0..values.len()).collect(); + order.sort_by(|a, b| values[*a].partial_cmp(&values[*b]).unwrap()); + let mut ranks = vec![0.0; values.len()]; + let mut i = 0; + while i < order.len() { + let mut j = i; + while j + 1 < order.len() && values[order[j + 1]] == values[order[i]] { + j += 1; + } + let rank = (i + j) as f64 / 2.0 + 1.0; + for &idx in &order[i..=j] { + ranks[idx] = rank; + } + i = j + 1; + } + ranks +} + +fn pearson(a: &[f64], b: &[f64]) -> f64 { + let n = a.len() as f64; + let (ma, mb) = (a.iter().sum::() / n, b.iter().sum::() / n); + let cov: f64 = a.iter().zip(b).map(|(x, y)| (x - ma) * (y - mb)).sum(); + let va: f64 = a.iter().map(|x| (x - ma).powi(2)).sum(); + let vb: f64 = b.iter().map(|y| (y - mb).powi(2)).sum(); + cov / (va.sqrt() * vb.sqrt()) +} + +/// Spearman-Rangkorrelation zweier gleich langer Reihen. +fn spearman(x: &[f64], y: &[f64]) -> f64 { + pearson(&average_ranks(x), &average_ranks(y)) +} + +fn measure(args: &[String]) { + let hands = sample_hands(option(args, "--hands").unwrap_or(DEFAULT_HANDS)); + let villains = option(args, "--villains").unwrap_or(DEFAULT_VILLAINS); + let trials = option(args, "--trials").unwrap_or(DEFAULT_TRIALS); + let scores: Vec = hands.iter().map(|h| score(h).expect("score") as f64).collect(); + let equities: Vec = hands.iter().map(|h| equity_of(h, villains, trials)).collect(); + let rho = spearman(&scores, &equities); + println!("PLO5 Score<->Equity Spearman rho = {rho:.4}"); + println!(" Haende {}, Gegner {villains}, Trials {trials}, Equity-Seed {EQUITY_SEED:#x}", hands.len()); + + let score_ranks = average_ranks(&scores); + let equity_ranks = average_ranks(&equities); + let n = hands.len() as f64; + let mut gaps: Vec<(f64, usize)> = (0..hands.len()) + // Score hoch = stark; Equity hoch = stark. Beide Raenge sollten gleichlaufen. + .map(|i| (((score_ranks[i] - equity_ranks[i]).abs()) / n, i)) + .collect(); + gaps.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap()); + println!(" Groebste Fehl-Einordnungen (|Score-Rang - Equity-Rang| / n):"); + for (gap, i) in gaps.into_iter().take(WORST_SHOWN) { + let text: String = hands[i].iter().map(|c| c.short()).collect::>().join(" "); + println!( + " {text:<20} Score {:>4} (Rang {:>5.0}) Equity {:.4} (Rang {:>5.0}) Luecke {gap:.3}", + scores[i] as i32, score_ranks[i], equities[i], equity_ranks[i] + ); + } +} + +/// Zaehlt alle Fuenf-Karten-Haende aus und baut die Perzentil-Tabelle: Eintrag `score - min` ist +/// (Haende mit hoeherem Score + halbe Haende mit diesem Score) / alle Haende. +fn table() { + let full = deck::full(); + let mut counts: std::collections::BTreeMap = std::collections::BTreeMap::new(); + let mut total: u64 = 0; + let n = full.len(); + for a in 0..n { + for b in a + 1..n { + for c in b + 1..n { + for d in c + 1..n { + for e in d + 1..n { + let hole = [full[a], full[b], full[c], full[d], full[e]]; + let s = score(&hole).expect("score"); + *counts.entry(s).or_insert(0) += 1; + total += 1; + } + } + } + } + } + eprintln!("table: {total} Haende, Score von {} bis {}", counts.keys().next().unwrap(), counts.keys().last().unwrap()); + let min = *counts.keys().next().unwrap(); + let max = *counts.keys().last().unwrap(); + let len = (max - min + 1) as usize; + // Perzentil = (strikt bessere + halbe gleich gute) / alle. Score aufsteigend durchlaufen + // und dabei die kumulierte Zahl schlechterer Haende mitfuehren. + let mut worse_or_equal_below: u64 = 0; + let mut percentile = vec![0.0f64; len]; + for s in min..=max { + let here = *counts.get(&s).unwrap_or(&0); + let strictly_better = total - worse_or_equal_below - here; + percentile[(s - min) as usize] = (strictly_better as f64 + here as f64 / 2.0) / total as f64; + worse_or_equal_below += here; + } + print!("{}", render_table(min, &percentile)); +} + +fn render_table(min: i32, percentile: &[f64]) -> String { + let mut out = String::new(); + out.push_str("//! Empirischer Perzentilwert jedes Omaha-5-Strukturscores (siehe `plo5_score::score`).\n"); + out.push_str("//!\n"); + out.push_str("//! Erzeugt durch Auszaehlen aller 2 598 960 Fuenf-Karten-Haende: Eintrag `score - SCORE_MIN` ist\n"); + out.push_str("//! (Haende mit hoeherem Score + halbe Haende mit diesem Score) / alle Haende.\n"); + out.push_str("//! Neu erzeugen, sobald sich die Gewichte in den `plo5_*`-Dateien aendern\n"); + out.push_str("//! (`cargo run --release --bin plo5_calibrate -- table`).\n\n"); + out.push_str(&format!("pub const SCORE_MIN: i32 = {min};\n")); + out.push_str(&format!("pub const PERCENTILE_BY_SCORE: [f64; {}] = [\n", percentile.len())); + for chunk in percentile.chunks(10) { + let row: Vec = chunk.iter().map(|v| format!("{v:.5}")).collect(); + out.push_str(&format!(" {},\n", row.join(", "))); + } + out.push_str("];\n"); + out +} + +/// Zeigt Score, Perzentil und echte Heads-up-Equity einzelner Haende (zum Auswaehlen von +/// Beispielen): `plo5_calibrate rank "6c 9d 7s 8d Ah" "2c As 3s 2s 3c"`. +fn rank(args: &[String]) { + use rechner::preflop::hand_percentile::percentile; + for text in args { + let hole = Card::parse_list(text).expect("cards"); + let eq = equity_of(&hole, 1, 60_000); + println!( + "{text:<20} Score {:>4} Perzentil {:.4} Equity {:.4}", + score(&hole).expect("score"), + percentile(Variant::Plo5, &hole), + eq + ); + } +} + +fn main() { + let args: Vec = std::env::args().skip(1).collect(); + match args.first().map(String::as_str) { + Some("measure") => measure(&args[1..]), + Some("table") => table(), + Some("rank") => rank(&args[1..]), + _ => { + eprintln!("usage: plo5_calibrate measure|table [options]"); + std::process::exit(2); + } + } +} diff --git a/src/preflop/plo5_pair_bonus.rs b/src/preflop/plo5_pair_bonus.rs index 318c8cb1..7f049d2a 100644 --- a/src/preflop/plo5_pair_bonus.rs +++ b/src/preflop/plo5_pair_bonus.rs @@ -1,9 +1,13 @@ //! Score value of a pair, indexed by rank value (2..=14); 0 and 1 unused. -pub const PAIR_BONUS: [i32; 15] = [0, 0, 2, 3, 4, 6, 8, 10, 13, 16, 20, 24, 28, 34, 40]; +/// Flattened at the bottom: low pairs barely improve an Omaha hand, while the big pairs +/// stay dominant. Strictly increasing so bigger pairs always outrank smaller ones. +pub const PAIR_BONUS: [i32; 15] = [0, 0, 0, 1, 2, 3, 5, 7, 10, 13, 17, 21, 26, 32, 40]; -/// Points per card for being a high card, indexed by rank value. -pub const HIGH_CARD: [i32; 15] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 6, 8, 10]; +/// Points per card for being a high card, indexed by rank value. Steepened at the top: +/// high cards drive Omaha equity because they make the nut hands, so broadway is rewarded +/// harder while nine and below stay at zero (junk stays junk). +pub const HIGH_CARD: [i32; 15] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 6, 8, 10, 13]; pub const TRIPS_PENALTY: i32 = 25; pub const QUADS_PENALTY: i32 = 60; diff --git a/src/preflop/plo5_rundown.rs b/src/preflop/plo5_rundown.rs index d4112cef..aab4455c 100644 --- a/src/preflop/plo5_rundown.rs +++ b/src/preflop/plo5_rundown.rs @@ -3,6 +3,12 @@ /// Best points for `k` distinct ranks inside one window of five rank values. const BY_WINDOW_FILL: [i32; 6] = [0, 0, 0, 4, 12, 22]; const DANGLER_PENALTY: i32 = 7; +/// A window needs at least this many distinct ranks before it counts as a real run. +const CONNECTED_MIN: usize = 3; +/// Height bonus for the top card of the best connected run, indexed by its rank value. +/// A king-high run makes far more nut straights than a wheelish run of the same length, +/// so equity rewards reaching into the broadway range; low runs stay at the base points. +const WINDOW_HEIGHT: [i32; 15] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 5, 7, 9, 11]; /// Rank `value` (2..=14) is present; the ace also counts as value 1. fn present(counts: &[u8; 15], value: usize) -> bool { @@ -13,17 +19,23 @@ fn present(counts: &[u8; 15], value: usize) -> bool { } } -/// Most distinct ranks in any window of five consecutive values (wheel included). -fn best_window_fill(counts: &[u8; 15]) -> usize { +/// Most distinct ranks in any window of five consecutive values (wheel included), +/// with the highest present value in that best window. +fn best_window(counts: &[u8; 15]) -> (usize, usize) { (1..=10) - .map(|low| (low..low + 5).filter(|v| present(counts, *v)).count()) - .max() - .unwrap_or(0) + .map(|low| { + let present: Vec = (low..low + 5).filter(|v| present(counts, *v)).collect(); + (present.len(), present.last().copied().unwrap_or(0)) + }) + .max_by_key(|(fill, top)| (*fill, *top)) + .unwrap_or((0, 0)) } -/// Points for how well the distinct ranks hang together. +/// Points for how well the distinct ranks hang together, plus a height bonus that +/// rewards high rundowns over low ones. pub fn connectedness_points(counts: &[u8; 15]) -> i32 { - BY_WINDOW_FILL[best_window_fill(counts).min(5)] + let (fill, top) = best_window(counts); + BY_WINDOW_FILL[fill.min(5)] + if fill >= CONNECTED_MIN { WINDOW_HEIGHT[top] } else { 0 } } /// A single card is dangling if it is unpaired, shares no suit, and sits more diff --git a/src/preflop/plo5_score_table.rs b/src/preflop/plo5_score_table.rs index b93d0feb..5c194bd5 100644 --- a/src/preflop/plo5_score_table.rs +++ b/src/preflop/plo5_score_table.rs @@ -1,32 +1,34 @@ -//! Empirical percentile of every Omaha-5 structural score (see `plo5_score::score`). +//! Empirischer Perzentilwert jedes Omaha-5-Strukturscores (siehe `plo5_score::score`). //! -//! Generated by enumerating all 2 598 960 five-card hands: entry `score - SCORE_MIN` is -//! (hands with a higher score + half the hands with this score) / all hands. -//! Regenerate whenever the weights in the `plo5_*` files change. +//! Erzeugt durch Auszaehlen aller 2 598 960 Fuenf-Karten-Haende: Eintrag `score - SCORE_MIN` ist +//! (Haende mit hoeherem Score + halbe Haende mit diesem Score) / alle Haende. +//! Neu erzeugen, sobald sich die Gewichte in den `plo5_*`-Dateien aendern +//! (`cargo run --release --bin plo5_calibrate -- table`). -pub const SCORE_MIN: i32 = -50; -pub const PERCENTILE_BY_SCORE: [f64; 225] = [ - 0.99996, 0.99991, 0.99991, 0.99990, 0.99990, 0.99990, 0.99990, 0.99989, 0.99988, 0.99987, - 0.99986, 0.99986, 0.99986, 0.99986, 0.99985, 0.99985, 0.99985, 0.99985, 0.99984, 0.99984, - 0.99983, 0.99982, 0.99982, 0.99982, 0.99982, 0.99982, 0.99982, 0.99981, 0.99981, 0.99979, - 0.99977, 0.99975, 0.99973, 0.99969, 0.99965, 0.99960, 0.99940, 0.99914, 0.99886, 0.99855, - 0.99819, 0.99775, 0.99726, 0.99668, 0.99616, 0.99566, 0.99521, 0.99481, 0.99445, 0.99411, - 0.99378, 0.99337, 0.99295, 0.99263, 0.99232, 0.99201, 0.99174, 0.99149, 0.99113, 0.99063, - 0.98990, 0.98890, 0.98739, 0.98546, 0.98269, 0.97915, 0.97239, 0.96527, 0.95637, 0.94681, - 0.93620, 0.92548, 0.91148, 0.89575, 0.87821, 0.85969, 0.84310, 0.82537, 0.80892, 0.79118, - 0.77384, 0.75756, 0.74199, 0.72573, 0.71093, 0.69633, 0.68055, 0.66573, 0.64699, 0.62954, - 0.61349, 0.59864, 0.58179, 0.56494, 0.54469, 0.52169, 0.50182, 0.48085, 0.46359, 0.44462, - 0.42700, 0.40869, 0.39143, 0.37533, 0.35999, 0.34430, 0.32846, 0.31366, 0.29635, 0.28139, - 0.26659, 0.25320, 0.24003, 0.22852, 0.21677, 0.20301, 0.19188, 0.18150, 0.17264, 0.16218, - 0.15219, 0.14314, 0.13503, 0.12803, 0.12186, 0.11593, 0.11043, 0.10617, 0.10207, 0.09779, - 0.09317, 0.08923, 0.08514, 0.08135, 0.07749, 0.07354, 0.06933, 0.06534, 0.06165, 0.05825, - 0.05549, 0.05279, 0.05010, 0.04756, 0.04522, 0.04297, 0.04032, 0.03783, 0.03585, 0.03396, - 0.03271, 0.03155, 0.03014, 0.02874, 0.02762, 0.02672, 0.02553, 0.02394, 0.02259, 0.02144, - 0.02066, 0.01983, 0.01877, 0.01785, 0.01687, 0.01559, 0.01389, 0.01248, 0.01108, 0.00976, - 0.00862, 0.00758, 0.00681, 0.00603, 0.00535, 0.00465, 0.00401, 0.00349, 0.00310, 0.00274, - 0.00241, 0.00209, 0.00191, 0.00173, 0.00166, 0.00159, 0.00142, 0.00127, 0.00118, 0.00111, - 0.00106, 0.00102, 0.00099, 0.00094, 0.00086, 0.00075, 0.00068, 0.00064, 0.00063, 0.00062, - 0.00061, 0.00058, 0.00051, 0.00045, 0.00042, 0.00039, 0.00037, 0.00032, 0.00028, 0.00026, - 0.00025, 0.00024, 0.00019, 0.00013, 0.00010, 0.00007, 0.00007, 0.00006, 0.00005, 0.00004, - 0.00003, 0.00002, 0.00001, 0.00000, 0.00000, +pub const SCORE_MIN: i32 = -53; +pub const PERCENTILE_BY_SCORE: [f64; 240] = [ + 0.99996, 0.99991, 0.99991, 0.99991, 0.99991, 0.99991, 0.99990, 0.99990, 0.99990, 0.99989, + 0.99989, 0.99989, 0.99988, 0.99988, 0.99988, 0.99988, 0.99988, 0.99986, 0.99985, 0.99985, + 0.99985, 0.99985, 0.99985, 0.99985, 0.99985, 0.99984, 0.99983, 0.99983, 0.99981, 0.99979, + 0.99979, 0.99978, 0.99976, 0.99973, 0.99962, 0.99934, 0.99902, 0.99879, 0.99857, 0.99817, + 0.99752, 0.99685, 0.99639, 0.99606, 0.99575, 0.99548, 0.99521, 0.99494, 0.99465, 0.99424, + 0.99384, 0.99353, 0.99317, 0.99267, 0.99204, 0.99136, 0.99076, 0.99027, 0.98980, 0.98925, + 0.98830, 0.98717, 0.98599, 0.98404, 0.98006, 0.97472, 0.96966, 0.96364, 0.95721, 0.95177, + 0.94551, 0.93506, 0.92137, 0.91024, 0.90117, 0.89018, 0.87715, 0.86323, 0.84857, 0.83267, + 0.81629, 0.79968, 0.78331, 0.76862, 0.75330, 0.73478, 0.71247, 0.69186, 0.67445, 0.65534, + 0.63581, 0.61628, 0.59820, 0.58223, 0.56346, 0.54073, 0.51788, 0.49923, 0.48333, 0.46540, + 0.44927, 0.43569, 0.42095, 0.40267, 0.38414, 0.37070, 0.35980, 0.34837, 0.33573, 0.32031, + 0.30358, 0.28661, 0.27187, 0.26034, 0.24928, 0.23800, 0.22553, 0.21469, 0.20624, 0.19886, + 0.19112, 0.18428, 0.17811, 0.17134, 0.16441, 0.15722, 0.15032, 0.14362, 0.13769, 0.13210, + 0.12568, 0.11959, 0.11383, 0.10906, 0.10560, 0.10167, 0.09717, 0.09147, 0.08616, 0.08199, + 0.07865, 0.07525, 0.07146, 0.06777, 0.06378, 0.05971, 0.05635, 0.05380, 0.05097, 0.04836, + 0.04630, 0.04418, 0.04210, 0.04024, 0.03884, 0.03791, 0.03638, 0.03436, 0.03241, 0.03077, + 0.02958, 0.02865, 0.02757, 0.02627, 0.02435, 0.02251, 0.02138, 0.01999, 0.01823, 0.01652, + 0.01517, 0.01399, 0.01286, 0.01180, 0.01068, 0.00979, 0.00924, 0.00862, 0.00797, 0.00723, + 0.00663, 0.00624, 0.00593, 0.00563, 0.00538, 0.00512, 0.00488, 0.00478, 0.00455, 0.00413, + 0.00367, 0.00332, 0.00298, 0.00251, 0.00217, 0.00195, 0.00172, 0.00146, 0.00124, 0.00116, + 0.00113, 0.00109, 0.00106, 0.00105, 0.00102, 0.00095, 0.00082, 0.00072, 0.00070, 0.00065, + 0.00059, 0.00051, 0.00044, 0.00041, 0.00039, 0.00035, 0.00027, 0.00020, 0.00019, 0.00019, + 0.00017, 0.00016, 0.00015, 0.00015, 0.00015, 0.00014, 0.00012, 0.00011, 0.00010, 0.00010, + 0.00009, 0.00008, 0.00007, 0.00006, 0.00006, 0.00004, 0.00003, 0.00003, 0.00002, 0.00001, ]; diff --git a/src/preflop/plo5_suits.rs b/src/preflop/plo5_suits.rs index ad2f04df..26478197 100644 --- a/src/preflop/plo5_suits.rs +++ b/src/preflop/plo5_suits.rs @@ -1,11 +1,16 @@ //! Suitedness points for a five-card Omaha hand. -/// Bonus by number of cards in one suit (index 0..=5). -const BY_SUIT_SIZE: [i32; 6] = [0, 0, 10, 12, 6, -8]; -/// Bonus for the highest card of a suit that has at least two cards, by rank value. -const BY_TOP_CARD: [i32; 15] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 5, 10]; -/// Bonus when two different suits are both shared (double suited or better). -const DOUBLE_SUITED: i32 = 12; +/// Bonus by number of cards in one suit (index 0..=5). A two-card suit is the whole flush +/// value: only two hole cards ever play, so the third and fourth same-suit cards are mostly +/// dead blockers and must not outscore a clean two-flush. Five of one suit is a trap. +const BY_SUIT_SIZE: [i32; 6] = [0, 0, 7, 6, 2, -12]; +/// Bonus for the highest card of a suit that has at least two cards, by rank value. A flush +/// only pays when it is near the nuts; low two-flushes lose multiway, so the height carries +/// most of the suit value and a low suit is worth little on its own. +const BY_TOP_CARD: [i32; 15] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 4, 7, 12]; +/// Bonus when two different suits are both shared (double suited or better). Modest: the +/// second suited pair is often low and only a backup flush draw. +const DOUBLE_SUITED: i32 = 7; /// `sizes[s]` = cards in suit `s`; `tops[s]` = highest rank value in suit `s`. pub fn suit_points(sizes: &[u8; 4], tops: &[u8; 4]) -> i32 { diff --git a/tests/preflop_plo5.rs b/tests/preflop_plo5.rs index 0be9af6f..cad5837b 100644 --- a/tests/preflop_plo5.rs +++ b/tests/preflop_plo5.rs @@ -1,7 +1,11 @@ use rechner::card::Card; +use rechner::equity::monte_carlo::estimate; +use rechner::equity::query::Query; +use rechner::equity::villain_range::VillainRange; use rechner::preflop::hand_percentile::percentile; use rechner::preflop::plo5_score::score; -use rechner::variant::Variant; +use rechner::rng::Rng; +use rechner::variant::{rules, Variant}; fn hand(text: &str) -> Vec { Card::parse_list(text).expect("valid cards") @@ -12,7 +16,12 @@ fn pct(text: &str) -> f64 { } /// Deterministic pseudo-random 5-card hands (LCG), independent of the crate's Rng. +/// Card indices are drawn by rejection (bytes >= 4*52 are discarded) so every card is equally +/// likely: a plain `byte % 52` would under-sample the aces and skew the hand distribution. fn sample_hands(count: usize) -> Vec> { + const CARDS: u8 = 52; + /// Largest multiple of 52 that fits in a byte (4 * 52); bytes at or above it are rejected. + const CUTOFF: u8 = 208; let mut state: u64 = 0x2545_F491_4F6C_DD1D; let mut next = move || { state = state @@ -20,11 +29,17 @@ fn sample_hands(count: usize) -> Vec> { .wrapping_add(1442695040888963407); (state >> 33) as u8 }; + let mut draw_card = move || loop { + let byte = next(); + if byte < CUTOFF { + return byte % CARDS; + } + }; (0..count) .map(|_| { let mut picked: Vec = Vec::new(); while picked.len() < 5 { - let c = next() % 52; + let c = draw_card(); if !picked.contains(&c) { picked.push(c); } @@ -104,3 +119,92 @@ fn score_rejects_wrong_card_counts() { assert_eq!(score(&hand("Ah Kd Qc Js Th 9h")), None); assert_eq!(score(&hand("Ah Ah Qc Js Th")), None); } + +// --- Kalibrierung gegen echte All-in-Preflop-Equity --------------------------------------- +// +// Die Struktur-Invarianten oben sagen nur, dass die Chart in sich stimmig ist. Die folgenden +// Spezifikationen pruefen, dass ihre Ordnung der ECHTEN Equity folgt, gemessen mit dem +// vorhandenen Monte-Carlo-Kern (`equity::monte_carlo`, SSOT). Fester Seed => reproduzierbar. + +/// Basis-Seed des Equity-Kerns; identisch zum Mess-Werkzeug `bin/plo5_calibrate`. +const EQUITY_SEED: u64 = 0x50C5_0C51_2024_2024; + +/// Echte Heads-up-Equity einer Starthand gegen einen zufaelligen Gegner; gleicher Seed je +/// Hand => gemeinsame Zufallszahlen, die den Rang-Vergleich entrauschen. +fn equity(text: &str, trials: u32) -> f64 { + let hole = hand(text); + let villains = [VillainRange::Any]; + let query = Query { rules: rules(Variant::Plo5), hero: &hole, board: &[], villains: &villains, trials }; + estimate(&query, Rng::seeded(EQUITY_SEED)).expect("equity").0.share +} + +/// Durchschnittsraenge (1-basiert): gleich grosse Werte teilen den mittleren Rang. +fn average_ranks(values: &[f64]) -> Vec { + let mut order: Vec = (0..values.len()).collect(); + order.sort_by(|a, b| values[*a].partial_cmp(&values[*b]).unwrap()); + let mut ranks = vec![0.0; values.len()]; + let mut i = 0; + while i < order.len() { + let mut j = i; + while j + 1 < order.len() && values[order[j + 1]] == values[order[i]] { + j += 1; + } + let rank = (i + j) as f64 / 2.0 + 1.0; + order[i..=j].iter().for_each(|&idx| ranks[idx] = rank); + i = j + 1; + } + ranks +} + +fn pearson(a: &[f64], b: &[f64]) -> f64 { + let n = a.len() as f64; + let (ma, mb) = (a.iter().sum::() / n, b.iter().sum::() / n); + let cov: f64 = a.iter().zip(b).map(|(x, y)| (x - ma) * (y - mb)).sum(); + let va: f64 = a.iter().map(|x| (x - ma).powi(2)).sum::().sqrt(); + let vb: f64 = b.iter().map(|y| (y - mb).powi(2)).sum::().sqrt(); + cov / (va * vb) +} + +fn spearman(x: &[f64], y: &[f64]) -> f64 { + pearson(&average_ranks(x), &average_ranks(y)) +} + +/// Vor der Kalibrierung lag die Rangkorrelation Score<->Equity bei rho ~ 0.75 (heads-up, +/// 200 Haende). Die kalibrierte Chart raeumt diese Schwelle klar: ihre Perzentil-Ordnung +/// folgt der echten Equity messbar besser. Score hoch = stark, Equity hoch = stark => die +/// Raenge laufen gleich, rho ist positiv. +#[test] +fn score_ordering_tracks_real_equity() { + const BAR: f64 = 0.78; + let hands = sample_hands(150); + let scores: Vec = hands.iter().map(|h| score(h).expect("score") as f64).collect(); + let equities: Vec = hands + .iter() + .map(|h| { + let text: String = h.iter().map(|c| c.short()).collect::>().join(" "); + equity(&text, 6000) + }) + .collect(); + let rho = spearman(&scores, &equities); + assert!(rho > BAR, "rho {rho} should clear the calibration bar {BAR}"); +} + +/// Konkrete Fehl-Einordnungen, die die unkalibrierte Chart falsch hatte und die jetzt stimmen: +/// hohe, koordinierte Haende schlagen niedrige Ass-/Paar-Haende, so wie es die echte Equity sagt. +/// (Perzentil klein = stark.) +#[test] +fn calibrated_chart_fixes_known_misrankings() { + // Hoher Rundown gegen tief-doppelt-suited-Muell: die unkalibrierte Chart gab dem Muell + // (voller Zwei-Flush- und Doppel-Suit-Bonus auf Lowcards) den hoeheren Score. Die echte + // Equity sieht den hohen Rundown klar vorn; die kalibrierte Chart jetzt auch. + let high_run = "Qs Jh Td 9c 4h"; + let low_double_suited_junk = "4d 2h 4h 6h 3d"; + assert!(equity(high_run, 20000) > equity(low_double_suited_junk, 20000)); + assert!(pct(high_run) < pct(low_double_suited_junk)); + + // Hohe Karten gegen kleines Paar mit Lowcards: vorher stand das kleine Paar im Score hoeher. + let high_cards = "8s Td Ad 5c 4h"; + let low_pair_junk = "6s 4s 4d 3c 2d"; + assert!(equity(high_cards, 20000) > equity(low_pair_junk, 20000)); + assert!(pct(high_cards) < pct(low_pair_junk)); +}