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::rng::Rng; use rechner::variant::{rules, Variant}; fn hand(text: &str) -> Vec { Card::parse_list(text).expect("valid cards") } fn pct(text: &str) -> f64 { percentile(Variant::Plo5, &hand(text)) } /// 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 .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() } #[test] fn double_suited_big_pairs_beat_rainbow_junk() { let strong = pct("Ah Ad Kh Kd Jc"); let junk = pct("2c 7d 4h 9s 3c"); assert!(strong < 0.05, "strong {strong}"); assert!(junk > 0.8, "junk {junk}"); assert!(strong < junk); } #[test] fn double_suited_beats_single_suited_with_same_ranks() { assert!(pct("Ah Kh Qd Jd Tc") < pct("Ah Kd Qc Js Ts")); } #[test] fn trips_and_quads_are_penalised() { assert!(pct("Ah Ad Kh Kd Qc") < pct("Ah Ad Ac Kh Qd")); assert!(pct("Ah Ad Ac Kh Qd") < pct("Ah Ad Ac As Kd")); } #[test] fn connected_rundowns_beat_scattered_cards_of_same_top() { assert!(pct("Jh Td 9c 8s 2h") < pct("Jh 8d 5c 3s 2h")); } #[test] fn bigger_pairs_beat_smaller_pairs() { assert!(pct("Ah Ad Kc Qs Jh") < pct("7h 7d Kc Qs Jh")); } #[test] fn suit_permutation_does_not_change_the_value() { assert_eq!(pct("Ah Ad Kh Kd Jc"), pct("As Ac Ks Kc Jd")); assert_eq!(pct("Ah Ad Kh Kd Jc"), pct("Jc Kd Kh Ad Ah")); } #[test] fn percentile_is_monotone_in_score() { let hands = sample_hands(1500); for a in &hands { for b in hands.iter().take(40) { let (sa, sb) = (score(a).expect("score"), score(b).expect("score")); let (pa, pb) = (percentile(Variant::Plo5, a), percentile(Variant::Plo5, b)); if sa > sb { assert!(pa <= pb); } if sa == sb { assert_eq!(pa, pb); } } } } #[test] fn random_hands_spread_evenly_over_the_unit_interval() { let hands = sample_hands(20_000); let values: Vec = hands.iter().map(|h| percentile(Variant::Plo5, h)).collect(); assert!(values.iter().all(|p| (0.0..=1.0).contains(p))); let mean = values.iter().sum::() / values.len() as f64; assert!((mean - 0.5).abs() < 0.02, "mean {mean}"); let top_decile = values.iter().filter(|p| **p < 0.1).count() as f64 / values.len() as f64; assert!((top_decile - 0.1).abs() < 0.03, "top decile {top_decile}"); } #[test] fn score_rejects_wrong_card_counts() { assert_eq!(score(&hand("Ah Kd")), None); 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)); }