diff --git a/src/cfr/turn_river_game.rs b/src/cfr/turn_river_game.rs index 1639722..74f7349 100644 --- a/src/cfr/turn_river_game.rs +++ b/src/cfr/turn_river_game.rs @@ -271,6 +271,11 @@ pub struct TrSolver { regret: Vec>, sums: Vec>, pub iterations: u32, + /// Spare buffers for `walk` (reused across calls and iterations; contents never read before + /// they are written, so reuse changes no value). + spare: Vec>, + /// Buffer for the f32 reach of `show_eq_into`. + o32: Vec, } /// The average strategy: per decision node, per copy (1 on the turn, one per river card on the @@ -303,6 +308,35 @@ pub struct Exploit { } fn matched(regret: &[f64], a: usize, out: &mut [f64]) { + match a { + 2 => matched_n::<2>(regret, out), + 3 => matched_n::<3>(regret, out), + 4 => matched_n::<4>(regret, out), + _ => matched_any(regret, a, out), + } +} + +/// `matched_any` for a fixed action count (same operations: `Iterator::sum` folds from -0.0, and +/// -0.0 + x == x bit for bit, so the sum is r[0] + r[1] + ... in order). +fn matched_n(regret: &[f64], out: &mut [f64]) { + for (r, o) in regret.chunks_exact(A).zip(out.chunks_exact_mut(A)) { + let mut s = r[0]; + for x in &r[1..] { + s += x; + } + if s > 0.0 { + for t in 0..A { + o[t] = r[t] / s; + } + } else { + for y in o.iter_mut() { + *y = 1.0 / A as f64; + } + } + } +} + +fn matched_any(regret: &[f64], a: usize, out: &mut [f64]) { for (r, o) in regret.chunks(a).zip(out.chunks_mut(a)) { let s: f64 = r.iter().sum(); if s > 0.0 { @@ -368,7 +402,7 @@ impl TrSolver { } let sums = regret.clone(); let masks = [hands[0].masks.clone(), hands[1].masks.clone()]; - TrSolver { game: std::sync::Arc::new(game), n, cards, masks, same, eq: None, eqm: Vec::new(), lock: Vec::new(), weights, rc, wr, regret, sums, iterations: 0 } + TrSolver { game: std::sync::Arc::new(game), n, cards, masks, same, eq: None, eqm: Vec::new(), lock: Vec::new(), weights, rc, wr, regret, sums, iterations: 0, spare: Vec::new(), o32: Vec::new() } } /// Stage C: the game's first street is the FLOP (`board` = three flop cards), the dealt card is the @@ -433,26 +467,32 @@ impl TrSolver { /// Showdown values from the equity table (stage C): `half * sum_j opp_j (2 eq_ij - 1)` over disjoint /// combos, as a dense matrix-vector product. fn show_eq(&self, r: usize, p: usize, opp: &[f64], half: f64) -> Vec { + let mut out = vec![0.0; self.n[p]]; + self.show_eq_into(r, p, opp, half, &mut Vec::new(), &mut out); + out + } + + /// `show_eq` into `out`, with `o` as the buffer for the f32 reach (same operations). + fn show_eq_into(&self, r: usize, p: usize, opp: &[f64], half: f64, o: &mut Vec, out: &mut [f64]) { let m = &self.eqm[r][p]; let k = self.n[1 - p]; - let o: Vec = opp.iter().map(|x| *x as f32).collect(); - m.chunks_exact(k) - .map(|row| { - let mut acc = [0.0f32; 8]; - let mut cr = row.chunks_exact(8); - let mut co = o.chunks_exact(8); - for (a, b) in (&mut cr).zip(&mut co) { - for t in 0..8 { - acc[t] += a[t] * b[t]; - } + o.clear(); + o.extend(opp.iter().map(|x| *x as f32)); + for (row, y) in m.chunks_exact(k).zip(out.iter_mut()) { + let mut acc = [0.0f32; 8]; + let mut cr = row.chunks_exact(8); + let mut co = o.chunks_exact(8); + for (a, b) in (&mut cr).zip(&mut co) { + for t in 0..8 { + acc[t] += a[t] * b[t]; } - let mut s: f32 = acc.iter().sum(); - for (a, b) in cr.remainder().iter().zip(co.remainder()) { - s += a * b; - } - half * s as f64 - }) - .collect() + } + let mut s: f32 = acc.iter().sum(); + for (a, b) in cr.remainder().iter().zip(co.remainder()) { + s += a * b; + } + *y = half * s as f64; + } } /// Lock decision `node` toward `believed` (one row of action probabilities per hand of the acting @@ -521,6 +561,13 @@ impl TrSolver { if self.eq.is_some() { return self.show_eq(r, p, opp, half); } + let mut out = vec![0.0; self.n[p]]; + self.show_into(p, r, opp, half, &mut out); + out + } + + /// `show` by rank into `out` (every entry written). + fn show_into(&self, p: usize, r: usize, opp: &[f64], half: f64, out: &mut [f64]) { let rc = &self.rc[r]; let (n_own, n_opp) = (self.n[p], self.n[1 - p]); let (own_o, own_r) = (&rc.order[p], &rc.rank[p]); @@ -536,7 +583,6 @@ impl TrSolver { let (mut less_t, mut less_c) = (0.0f64, [0.0f64; 64]); let mut eq_c = [0.0f64; 64]; let mut ptr = 0; - let mut out = vec![0.0; n_own]; let mut k = 0; while k < n_own { let s = own_r[own_o[k] as usize]; @@ -577,40 +623,93 @@ impl TrSolver { } k = e; } - out } fn mask_by_card(&self, v: &[f64], p: usize, r: usize) -> Vec { v.iter().zip(&self.rc[r].free[p]).map(|(x, f)| x * f).collect() } + /// A buffer of `n` zeros from the spares. + fn take(&mut self, n: usize) -> Vec { + let mut v = self.spare.pop().unwrap_or_default(); + v.clear(); + if v.capacity() < n { + // Room for the largest buffer `walk` asks for (hands x actions), so a spare never regrows. + let most = self.n[0].max(self.n[1]) * self.game.acts.iter().map(Vec::len).max().unwrap_or(1).max(1); + v.reserve(n.max(most)); + } + v.resize(n, 0.0); + v + } + + fn give(&mut self, v: Vec) { + self.spare.push(v); + } + + /// `disjoint(p, opp)[i] * v` into `out` (same operations as `disjoint` then the product). + fn fold_into(&self, p: usize, opp: &[f64], v: f64, out: &mut [f64]) { + let mut c = [0.0f64; 64]; + let mut t = 0.0; + for (j, w) in opp.iter().enumerate() { + let (a, b) = self.cards[1 - p][j]; + c[a] += w; + c[b] += w; + t += w; + } + for (i, o) in out.iter_mut().enumerate() { + let (a, b) = self.cards[p][i]; + *o = (t - c[a] - c[b] + self.same[p][i].map_or(0.0, |j| opp[j])) * v; + } + } + /// Counterfactual values of the traversing player `p`, one per own combo. fn walk(&mut self, node: usize, p: usize, own: &[f64], opp: &[f64], r: usize, weight: f64) -> Vec { let game = std::sync::Arc::clone(&self.game); match game.nodes[node] { TNode::Fold { folder, amt } => { let v = if folder == p { -amt } else { amt }; - self.disjoint(p, opp).into_iter().map(|x| x * v).collect() + let mut out = self.take(self.n[p]); + self.fold_into(p, opp, v, &mut out); + out + } + TNode::Show { half } => { + let mut out = self.take(self.n[p]); + if self.eq.is_some() { + let mut o = std::mem::take(&mut self.o32); + self.show_eq_into(r, p, opp, half, &mut o, &mut out); + self.o32 = o; + } else { + self.show_into(p, r, opp, half, &mut out); + } + out } - TNode::Show { half } => self.show(p, r, opp, half), TNode::Chance { child } => { - let mut total = vec![0.0; self.n[p]]; + let mut total = self.take(self.n[p]); + let mut o = self.take(own.len()); + let mut q = self.take(opp.len()); for ri in 0..self.rc.len() { - let o = self.mask_by_card(own, p, ri); - let q = self.mask_by_card(opp, 1 - p, ri); + for ((x, v), f) in o.iter_mut().zip(own).zip(&self.rc[ri].free[p]) { + *x = v * f; + } + for ((x, v), f) in q.iter_mut().zip(opp).zip(&self.rc[ri].free[1 - p]) { + *x = v * f; + } let v = self.walk(child, p, &o, &q, ri, weight); let free = &self.rc[ri].free[p]; for i in 0..total.len() { total[i] += self.wr * v[i] * free[i]; } + self.give(v); } + self.give(o); + self.give(q); total } TNode::Dec { player, street, ref kids } => { let a = kids.len(); let n = self.n[player]; let off = if street == 0 { 0 } else { r * n * a }; - let mut sigma = vec![0.0; n * a]; + let mut sigma = self.take(n * a); matched(&self.regret[node][off..off + n * a], a, &mut sigma); if let Some(Some((believed, w))) = self.lock.get(node) { for (x, b) in sigma.iter_mut().zip(believed) { @@ -618,31 +717,43 @@ impl TrSolver { } } if player == p { - let values: Vec> = kids - .iter() - .enumerate() - .map(|(k, kid)| { - let reach: Vec = (0..n).map(|i| own[i] * sigma[i * a + k]).collect(); - self.walk(*kid, p, &reach, opp, r, weight) - }) - .collect(); - let mut node_value = vec![0.0; n]; + let mut values: Vec> = Vec::with_capacity(a); + let mut reach = self.take(n); + for (k, kid) in kids.iter().enumerate() { + for (i, x) in reach.iter_mut().enumerate() { + *x = own[i] * sigma[i * a + k]; + } + values.push(self.walk(*kid, p, &reach, opp, r, weight)); + } + self.give(reach); + let mut node_value = self.take(n); + let (regret, sums) = (&mut self.regret[node], &mut self.sums[node]); for i in 0..n { node_value[i] = (0..a).map(|k| sigma[i * a + k] * values[k][i]).sum(); for k in 0..a { - let reg = &mut self.regret[node][off + i * a + k]; + let reg = &mut regret[off + i * a + k]; *reg = (*reg + values[k][i] - node_value[i]).max(0.0); - self.sums[node][off + i * a + k] += weight * own[i] * sigma[i * a + k]; + sums[off + i * a + k] += weight * own[i] * sigma[i * a + k]; } } + for v in values { + self.give(v); + } + self.give(sigma); node_value } else { - let mut total = vec![0.0; self.n[p]]; + let mut total = self.take(self.n[p]); + let mut reach = self.take(n); for (k, kid) in kids.iter().enumerate() { - let reach: Vec = (0..n).map(|j| opp[j] * sigma[j * a + k]).collect(); + for (j, x) in reach.iter_mut().enumerate() { + *x = opp[j] * sigma[j * a + k]; + } let v = self.walk(*kid, p, own, &reach, r, weight); total.iter_mut().zip(&v).for_each(|(t, x)| *t += x); + self.give(v); } + self.give(reach); + self.give(sigma); total } } diff --git a/src/engine/range_combos.rs b/src/engine/range_combos.rs index fa8b166..2b869b7 100644 --- a/src/engine/range_combos.rs +++ b/src/engine/range_combos.rs @@ -17,8 +17,8 @@ pub fn combos(rules: &Rules, filter: &HandFilter, dead: &[Card]) -> Option> = (0..pool.len()) .flat_map(|i| (i + 1..pool.len()).map(move |j| (i, j))) + .filter(|&(i, j)| filter(&[pool[i], pool[j]])) .map(|(i, j)| vec![pool[i], pool[j]]) - .filter(|hand| filter(hand)) .collect(); (!kept.is_empty()).then_some(kept) } diff --git a/src/engine/range_filter.rs b/src/engine/range_filter.rs index 1773fb1..1cbe0e4 100644 --- a/src/engine/range_filter.rs +++ b/src/engine/range_filter.rs @@ -1,4 +1,7 @@ use crate::card::{deck, Card}; +use std::cell::RefCell; +use std::collections::HashMap; +use std::rc::Rc; use crate::exploit::range_spec::{Continuation, RangeSpec}; use crate::preflop::hand_percentile::percentile; use crate::read::glance::glance; @@ -117,25 +120,85 @@ const RELAXED_HI: f64 = 0.5; /// When no hand of the preflop band meets some floor, the band contradicts what the /// villain did; the action wins and the band is relaxed to `[0, max(hi, 0.5)]`. pub fn range_filter(spec: &RangeSpec, rules: Rules, variant: Variant, board: &[Card]) -> HandFilter { - let board = board.to_vec(); - let (first, starved) = acceptances(spec, &rules, variant, &board); - let (spec, qs) = if starved { - let relaxed = RangeSpec { lo: 0.0, hi: spec.hi.max(RELAXED_HI), continues: spec.continues.clone() }; - let (qs, _) = acceptances(&relaxed, &rules, variant, &board); - (relaxed, qs) - } else { - (spec.clone(), first) + // The range depends on (spec, rules, variant, board) only - not on hero's cards - so one decision + // and every decision after it at the same spot (LBR asks every combo at a node) share it: the + // acceptances are computed once per key, and each hand's verdict once per key and hand. Text of + // the key: `Debug` of f64 round-trips, so different values never share an entry. + let key = format!("{spec:?}|{rules:?}|{variant:?}|{board:?}"); + let shared = FILTERS.with(|f| f.borrow().get(&key).cloned()); + let shared = match shared { + Some(s) => s, + None => { + let s = Rc::new(Kept::new(spec, rules, variant, board)); + FILTERS.with(|f| { + let mut f = f.borrow_mut(); + if f.len() >= FILTER_CACHE { + f.clear(); + } + f.insert(key, s.clone()); + }); + s + } }; - Box::new(move |hand: &[Card]| { - let p = percentile(variant, hand); - p >= spec.lo - && p <= spec.hi - && spec.continues.iter().zip(&qs).enumerate().all(|(step, (c, q))| { - match meets(&rules, c, hand, &board) { + Box::new(move |hand: &[Card]| shared.contains(hand)) +} + +/// Ranges kept per thread (a decision builds a few; LBR revisits one spot ~1000 times in a row). +const FILTER_CACHE: usize = 256; + +thread_local! { + static FILTERS: RefCell>> = RefCell::new(HashMap::new()); +} + +/// One built range: the (possibly relaxed) spec, its ticket thresholds, and the verdict per ordered +/// two-card hand once asked (0 = not yet, 1 = out, 2 = in). +struct Kept { + spec: RangeSpec, + qs: Vec, + rules: Rules, + variant: Variant, + board: Vec, + verdict: RefCell>, +} + +impl Kept { + fn new(spec: &RangeSpec, rules: Rules, variant: Variant, board: &[Card]) -> Kept { + let board = board.to_vec(); + let (first, starved) = acceptances(spec, &rules, variant, &board); + let (spec, qs) = if starved { + let relaxed = RangeSpec { lo: 0.0, hi: spec.hi.max(RELAXED_HI), continues: spec.continues.clone() }; + let (qs, _) = acceptances(&relaxed, &rules, variant, &board); + (relaxed, qs) + } else { + (spec.clone(), first) + }; + Kept { spec, qs, rules, variant, board, verdict: RefCell::new(vec![0; 52 * 52]) } + } + + fn judge(&self, hand: &[Card]) -> bool { + let p = percentile(self.variant, hand); + p >= self.spec.lo + && p <= self.spec.hi + && self.spec.continues.iter().zip(&self.qs).enumerate().all(|(step, (c, q))| { + match meets(&self.rules, c, hand, &self.board) { Some(true) => true, Some(false) => *q > 0.0 && ticket(hand, step) < *q, None => false, } }) - }) + } + + fn contains(&self, hand: &[Card]) -> bool { + if hand.len() != 2 { + return self.judge(hand); + } + let i = hand[0].index() as usize * 52 + hand[1].index() as usize; + let known = self.verdict.borrow()[i]; + if known != 0 { + return known == 2; + } + let v = self.judge(hand); + self.verdict.borrow_mut()[i] = if v { 2 } else { 1 }; + v + } } diff --git a/src/equity/monte_carlo.rs b/src/equity/monte_carlo.rs index 9aabf72..762b16a 100644 --- a/src/equity/monte_carlo.rs +++ b/src/equity/monte_carlo.rs @@ -1,13 +1,13 @@ use super::estimate::Estimate; use super::outcome::Outcome; use super::query::Query; -use super::sample::{deal, deal_combo, shuffle_front}; +use super::sample::{deal, deal_combo, shuffle_front, Pool}; use super::tally::Tally; use super::validate::remaining_deck; use super::villain_range::VillainRange; use crate::card::Card; use crate::fault::Fault; -use crate::hand::showdown::judge; +use crate::hand::showdown::{best_with_board, holdem_lanes, judge}; use crate::rng::Rng; /// Seeded Monte Carlo equity. Same query + same rng ⇒ same estimate. @@ -15,7 +15,7 @@ use crate::rng::Rng; /// `Filter` ranges are sampled by bounded rejection (see `sample::deal` for the fallback), /// `Combos` ranges directly from their list (`sample::deal_combo`). pub fn estimate(query: &Query, rng: Rng) -> Result<(Estimate, Rng), Fault> { - let mut pool = remaining_deck(query)?; + let mut pool = Pool::new(remaining_deck(query)?); let (tally, rng) = (0..query.trials).try_fold((Tally::default(), rng), |(tally, rng), _| { let (outcome, rng) = play_trial(query, &mut pool, rng)?; Ok::<_, Fault>((tally.record(outcome), rng)) @@ -24,30 +24,27 @@ pub fn estimate(query: &Query, rng: Rng) -> Result<(Estimate, Rng), Fault> { } /// One deal: villain hands first (in query order), then the rest of the board. -fn play_trial(query: &Query, pool: &mut [Card], rng: Rng) -> Result<(Outcome, Rng), Fault> { +fn play_trial(query: &Query, pool: &mut Pool, rng: Rng) -> Result<(Outcome, Rng), Fault> { let k = query.rules.hole_cards; let rules = &query.rules; let accept_all = |_: &[Card]| true; + // Sampled hands go to the front of the pool in villain order, `k` cards each, so a villain's + // start is the running sum over the sampled villains before it (recomputed below, no list). let mut front = 0; let mut rng = rng; - // Where each villain's cards: Some(start in pool) for sampled hands. - let mut starts: Vec> = Vec::with_capacity(query.villains.len()); for villain in query.villains { match villain { - VillainRange::Exact(_) => starts.push(None), + VillainRange::Exact(_) => {} VillainRange::Any => { rng = deal(pool, front, k, &accept_all, rng); - starts.push(Some(front)); front += k; } VillainRange::Filter(accept) => { rng = deal(pool, front, k, *accept, rng); - starts.push(Some(front)); front += k; } VillainRange::Combos(combos) => { rng = deal_combo(pool, front, k, combos, rng); - starts.push(Some(front)); front += k; } } @@ -55,18 +52,29 @@ fn play_trial(query: &Query, pool: &mut [Card], rng: Rng) -> Result<(Outcome, Rn let missing = 5 - query.board.len(); rng = shuffle_front(pool, front, missing, rng); let mut board = [query.hero[0]; 5]; - query.board.iter().chain(&pool[front..front + missing]).enumerate().for_each(|(i, c)| board[i] = *c); + query.board.iter().chain(&pool.cards[front..front + missing]).enumerate().for_each(|(i, c)| board[i] = *c); - let hero = judge(rules, query.hero, &board)?; + // Standard hold'em: the board's suit lanes once, each two-card hand adds its own cards. Same value + // as `judge`, whose checks cannot fail here: `remaining_deck` made hero, board and known hands + // distinct and in the deck, and every dealt card comes from the pool of the others. + let lanes = holdem_lanes(rules, &board); + let strength_of = |hand: &[Card]| match &lanes { + Some(l) if hand.len() == 2 => Ok(best_with_board(l, hand)), + _ => judge(rules, hand, &board), + }; + let hero = strength_of(query.hero)?; let mut rivals_best = None; let mut rivals_tied = 0u32; - for (villain, start) in query.villains.iter().zip(&starts) { - let hand: &[Card] = match (villain, start) { - (VillainRange::Exact(cards), _) => cards, - (_, Some(s)) => &pool[*s..*s + k], - (_, None) => &[], + let mut start = 0; + for villain in query.villains { + let hand: &[Card] = match villain { + VillainRange::Exact(cards) => cards, + _ => { + start += k; + &pool.cards[start - k..start] + } }; - let strength = judge(rules, hand, &board)?; + let strength = strength_of(hand)?; match rivals_best { Some(top) if strength < top => {} Some(top) if strength == top => rivals_tied += 1, diff --git a/src/equity/sample.rs b/src/equity/sample.rs index acabb09..8a3a3c5 100644 --- a/src/equity/sample.rs +++ b/src/equity/sample.rs @@ -2,6 +2,10 @@ //! //! The pool is only ever permuted, so any arrangement is a uniform starting point for the next //! partial Fisher-Yates pass; the arrangement itself never leaks out of `monte_carlo`. +//! +//! `Pool` keeps, next to the cards, where each card sits (by `Card::index`), so finding a card is one +//! lookup instead of a scan; every swap updates both. The swaps themselves are exactly those of the +//! plain slice version, so the arrangement (and every deal after it) is the same. use crate::card::Card; use crate::rng::Rng; @@ -9,8 +13,39 @@ use crate::rng::Rng; /// Attempts a `Filter` range gets per hand before the last sample is accepted unfiltered. pub const MAX_FILTER_ATTEMPTS: u32 = 200; +/// The cards still to deal from, and the position of each (`at[card.index()]`; `u8::MAX` for cards +/// not in the pool). +pub struct Pool { + pub cards: Vec, + at: [u8; 64], +} + +impl Pool { + pub fn new(cards: Vec) -> Pool { + let mut at = [u8::MAX; 64]; + for (i, c) in cards.iter().enumerate() { + at[c.index() as usize] = i as u8; + } + Pool { cards, at } + } + + pub fn len(&self) -> usize { + self.cards.len() + } + + pub fn is_empty(&self) -> bool { + self.cards.is_empty() + } + + fn swap(&mut self, i: usize, j: usize) { + self.cards.swap(i, j); + self.at[self.cards[i].index() as usize] = i as u8; + self.at[self.cards[j].index() as usize] = j as u8; + } +} + /// Moves `count` uniformly chosen cards from `pool[front..]` to `pool[front..front + count]`. -pub fn shuffle_front(pool: &mut [Card], front: usize, count: usize, rng: Rng) -> Rng { +pub fn shuffle_front(pool: &mut Pool, front: usize, count: usize, rng: Rng) -> Rng { (0..count).fold(rng, |rng, i| { let (offset, rng) = rng.below((pool.len() - front - i) as u64); pool.swap(front + i, front + i + offset as usize); @@ -21,11 +56,11 @@ pub fn shuffle_front(pool: &mut [Card], front: usize, count: usize, rng: Rng) -> /// Deals `count` cards at `front`, re-sampling while `accept` refuses (bounded). /// Fallback: after `MAX_FILTER_ATTEMPTS` refusals the last sample is kept, i.e. a range that /// (almost) never matches degrades to a uniformly random hand instead of failing the run. -pub fn deal(pool: &mut [Card], front: usize, count: usize, accept: &dyn Fn(&[Card]) -> bool, rng: Rng) -> Rng { +pub fn deal(pool: &mut Pool, front: usize, count: usize, accept: &dyn Fn(&[Card]) -> bool, rng: Rng) -> Rng { let mut rng = rng; for _ in 0..MAX_FILTER_ATTEMPTS { rng = shuffle_front(pool, front, count, rng); - if accept(&pool[front..front + count]) { + if accept(&pool.cards[front..front + count]) { break; } } @@ -35,16 +70,20 @@ pub fn deal(pool: &mut [Card], front: usize, count: usize, accept: &dyn Fn(&[Car /// Deals one of `combos` at `front`: a uniformly chosen hand, re-chosen while one of its /// cards is gone (dead or dealt), bounded by `MAX_FILTER_ATTEMPTS`. Fallback: an empty list, /// or no hand left after the attempts, deals `count` random cards instead. -pub fn deal_combo(pool: &mut [Card], front: usize, count: usize, combos: &[Vec], rng: Rng) -> Rng { +pub fn deal_combo(pool: &mut Pool, front: usize, count: usize, combos: &[Vec], rng: Rng) -> Rng { let mut rng = rng; for _ in 0..if combos.is_empty() { 0 } else { MAX_FILTER_ATTEMPTS } { let (i, next) = rng.below(combos.len() as u64); rng = next; let combo = &combos[i as usize]; - let available = combo.len() == count && combo.iter().all(|c| pool[front..].contains(c)); + // In `pool[front..]`: in the pool, at or behind `front`. + let available = combo.len() == count && combo.iter().all(|c| pool.at[c.index() as usize] as usize >= front && pool.at[c.index() as usize] != u8::MAX); if available { for (k, card) in combo.iter().enumerate() { - let at = front + k + pool[front + k..].iter().position(|p| p == card).unwrap_or(0); + // The card's place if it is in `pool[front + k..]`, else `front + k` (a no-op swap): + // what the scan `front + k + position(..).unwrap_or(0)` gave. + let p = pool.at[card.index() as usize] as usize; + let at = if p >= front + k && p < pool.len() && pool.cards[p] == *card { p } else { front + k }; pool.swap(front + k, at); } return rng; diff --git a/src/hand/showdown.rs b/src/hand/showdown.rs index d907801..3429a85 100644 --- a/src/hand/showdown.rs +++ b/src/hand/showdown.rs @@ -1,27 +1,45 @@ //! Best hand for a player under the variant's hole-card usage rule. use super::five::{evaluate, evaluate_in}; +use super::category::Category; use super::strength::Strength; use super::subset::{masks, pick}; use crate::card::Card; use crate::fault::Fault; -use crate::variant::{HoleUsage, Rules}; +use crate::variant::{DeckRule, HandRanking, HoleUsage, Rules}; /// Standard rules on the full deck: ace low in A-2-3-4-5, full house beats flush. /// Hold'em family: 5-7 cards in total. Omaha family: >= 2 hole and 3-5 board cards. /// Variants with their own deck or ladder go through `judge`. pub fn best(usage: HoleUsage, hole: &[Card], board: &[Card]) -> Result { distinct(hole, board)?; + if matches!(usage, HoleUsage::BestFiveOfAll) { + return best_of_all_standard(hole, board); + } select(usage, &evaluate, hole, board) } +/// `best_of_all(evaluate, ..)` by the direct evaluator: same checks, same value. +fn best_of_all_standard(hole: &[Card], board: &[Card]) -> Result { + if !(5..=7).contains(&(hole.len() + board.len())) || hole.is_empty() { + return Err(invalid("hold'em needs 5 to 7 cards including hole cards")); + } + Ok(best_standard(hole.iter().chain(board).copied())) +} + fn invalid(detail: &str) -> Fault { Fault::Invalid { field: "cards".into(), detail: detail.into() } } fn distinct(hole: &[Card], board: &[Card]) -> Result<(), Fault> { - let all: Vec = hole.iter().chain(board).copied().collect(); - let repeated = all.iter().enumerate().any(|(i, c)| all[..i].contains(c)); + // One bit per card (`index` is unique per rank and suit): a repeat finds its bit set. + let mut seen = 0u64; + let mut repeated = false; + for c in hole.iter().chain(board) { + let bit = 1u64 << c.index(); + repeated |= seen & bit != 0; + seen |= bit; + } if repeated { Err(Fault::Inconsistent("duplicate card".into())) } else { @@ -29,6 +47,122 @@ fn distinct(hole: &[Card], board: &[Card]) -> Result<(), Fault> { } } +/// The best five of 5 to 7 distinct cards under standard rules (full deck, standard ladder), without +/// enumerating subsets: the same `Strength` as `best_five_of(evaluate, ..)`, value for value (checked +/// against it on every 5-, 6- and 7-card hand, `tests::the_direct_evaluator_equals_enumeration_everywhere`). +fn best_standard(cards: impl Iterator) -> Strength { + best_of_lanes(lanes(cards)) +} + +/// One 13-bit lane per suit, bit `value - 2`. +fn lanes(cards: impl Iterator) -> [u32; 4] { + let mut s = [0u32; 4]; + for c in cards { + s[c.suit as usize] |= 1 << (c.rank.value() - 2); + } + s +} + +/// The suit lanes of a five-card board when `rules` are standard hold'em (two hole cards, best five +/// of all, full deck, standard ladder) - the case `best_with_board` serves - else `None`. +pub fn holdem_lanes(rules: &Rules, board: &[Card; 5]) -> Option<[u32; 4]> { + (rules.hole_cards == 2 && matches!(rules.hole_usage, HoleUsage::BestFiveOfAll) && standard(rules.deck, rules.ranking)) + .then(|| lanes(board.iter().copied())) +} + +/// The best five of a two-card `hole` and the board given as its lanes (`holdem_lanes`), for a caller +/// that guarantees the seven cards are distinct: the `Strength` `judge` gives them under standard +/// hold'em rules. +pub fn best_with_board(board: &[u32; 4], hole: &[Card]) -> Strength { + let mut s = *board; + for c in hole { + s[c.suit as usize] |= 1 << (c.rank.value() - 2); + } + best_of_lanes(s) +} + +fn best_of_lanes(s: [u32; 4]) -> Strength { + let v = |bit: u32| bit as u8 + 2; + let high = |bits: u32| 31 - bits.leading_zeros(); + // The `n` highest ranks of `bits` as values, most significant first. + let top = |mut bits: u32, out: &mut [u8; 5], from: usize, n: usize| { + for slot in out.iter_mut().skip(from).take(n) { + if bits == 0 { + break; + } + let h = high(bits); + *slot = v(h); + bits &= !(1 << h); + } + }; + // Top rank index of the highest five-run (ace also below the deuce), `None` without one. + let straight = |ranks: u32| { + let b = (ranks << 1) | ((ranks >> 12) & 1); + let run = b & (b >> 1) & (b >> 2) & (b >> 3) & (b >> 4); + (run != 0).then(|| 31 - run.leading_zeros() + 3) + }; + let mk = |c: Category, r: [u8; 5]| Strength::new(HandRanking::Standard, c, r); + let mut r = [0u8; 5]; + for lane in s { + if lane.count_ones() >= 5 { + return match straight(lane) { + Some(t) => mk(Category::StraightFlush, [v(t), 0, 0, 0, 0]), + None => { + top(lane, &mut r, 0, 5); + mk(Category::Flush, r) + } + }; + } + } + let ranks = s[0] | s[1] | s[2] | s[3]; + let four = s[0] & s[1] & s[2] & s[3]; + if four != 0 { + let q = high(four); + r[0] = v(q); + top(ranks & !(1 << q), &mut r, 1, 1); + return mk(Category::FourOfAKind, r); + } + let three = (s[0] & s[1] & s[2]) | (s[0] & s[1] & s[3]) | (s[0] & s[2] & s[3]) | (s[1] & s[2] & s[3]); + let two = (s[0] & s[1]) | (s[0] & s[2]) | (s[0] & s[3]) | (s[1] & s[2]) | (s[1] & s[3]) | (s[2] & s[3]); + if three != 0 { + let t = high(three); + let pair = two & !(1 << t); + if pair != 0 { + return mk(Category::FullHouse, [v(t), v(high(pair)), 0, 0, 0]); + } + } + if let Some(t) = straight(ranks) { + return mk(Category::Straight, [v(t), 0, 0, 0, 0]); + } + if three != 0 { + let t = high(three); + r[0] = v(t); + top(ranks & !(1 << t), &mut r, 1, 2); + return mk(Category::ThreeOfAKind, r); + } + if two.count_ones() >= 2 { + let hi = high(two); + let lo = high(two & !(1 << hi)); + r[0] = v(hi); + r[1] = v(lo); + top(ranks & !(1 << hi) & !(1 << lo), &mut r, 2, 1); + return mk(Category::TwoPair, r); + } + if two != 0 { + let p = high(two); + r[0] = v(p); + top(ranks & !(1 << p), &mut r, 1, 3); + return mk(Category::Pair, r); + } + top(ranks, &mut r, 0, 5); + mk(Category::HighCard, r) +} + +/// Standard rules: full deck and standard ladder (the direct evaluator applies). +fn standard(deck: DeckRule, ranking: HandRanking) -> bool { + deck == DeckRule::FULL && ranking == HandRanking::Standard +} + fn select( usage: HoleUsage, eval: &dyn Fn(&[Card; 5]) -> Strength, @@ -46,6 +180,11 @@ fn best_of_all(eval: &dyn Fn(&[Card; 5]) -> Strength, hole: &[Card], board: &[Ca if !(5..=7).contains(&all.len()) || hole.is_empty() { return Err(invalid("hold'em needs 5 to 7 cards including hole cards")); } + best_five_of(eval, &all) +} + +/// The best five-card subset of `all` (5 to 7 distinct cards) under `eval`, by enumeration. +fn best_five_of(eval: &dyn Fn(&[Card; 5]) -> Strength, all: &[Card]) -> Result { masks(all.len(), 5) .filter_map(|m| pick::<5>(&all, m)) .map(|five| eval(&five)) @@ -81,6 +220,93 @@ pub fn judge(rules: &Rules, hole: &[Card], board: &[Card]) -> Result Vec { + Card::parse_list("2c 3c 4c 5c 6c 7c 8c 9c Tc Jc Qc Kc Ac 2d 3d 4d 5d 6d 7d 8d 9d Td Jd Qd Kd Ad 2h 3h 4h 5h 6h 7h 8h 9h Th Jh Qh Kh Ah 2s 3s 4s 5s 6s 7s 8s 9s Ts Js Qs Ks As").unwrap() + } + + /// Every hand of `n` cards whose lowest card index is in `firsts`: the direct evaluator against + /// enumeration; returns the number checked. + fn every_hand(n: usize, firsts: impl Iterator) -> u64 { + let d = deck(); + let mut checked = 0u64; + let mut idx = vec![0usize; n]; + for f in firsts { + idx[0] = f; + // Odometer over the remaining n-1 strictly increasing indices. + for (j, slot) in idx.iter_mut().enumerate().skip(1) { + *slot = f + j; + } + if idx[n - 1] >= 52 { + continue; + } + loop { + let cards: Vec = idx.iter().map(|i| d[*i]).collect(); + let want = best_five_of(&evaluate, &cards).unwrap(); + let got = best_standard(cards.iter().copied()); + assert_eq!(got, want, "{:?}", cards.iter().map(|c| c.short()).collect::>()); + checked += 1; + // Advance (position 0 stays fixed). + let mut p = n - 1; + loop { + if p == 0 { + break; + } + if idx[p] < 52 - (n - p) { + idx[p] += 1; + for q in p + 1..n { + idx[q] = idx[q - 1] + 1; + } + break; + } + p -= 1; + } + if p == 0 { + break; + } + } + } + checked + } + + /// Every 5-card hand (fast enough for the normal suite). + #[test] + fn the_direct_evaluator_equals_enumeration_on_every_five_card_hand() { + assert_eq!(every_hand(5, 0..52), 2_598_960); + } + + #[test] + fn the_direct_evaluator_knows_wheel_and_steel_wheel() { + let c = |t: &str| Card::parse_list(t).unwrap(); + let w = best(HoleUsage::BestFiveOfAll, &c("Ah 2d"), &c("3c 4s 5h Kd Kc")).unwrap(); + assert_eq!((w.category, w.ranks), (Category::Straight, [5, 0, 0, 0, 0])); + let sf = best(HoleUsage::BestFiveOfAll, &c("Ah 2h"), &c("3h 4h 5h 6d 6c")).unwrap(); + assert_eq!((sf.category, sf.ranks), (Category::StraightFlush, [5, 0, 0, 0, 0])); + } + + /// Every 6- and 7-card hand (154 M), split over `PERF_THREADS` threads (default 2): + /// `cargo test --release the_direct_evaluator_equals_enumeration_everywhere -- --ignored --nocapture` + #[test] + #[ignore] + fn the_direct_evaluator_equals_enumeration_everywhere() { + let th: usize = std::env::var("PERF_THREADS").ok().and_then(|x| x.parse().ok()).unwrap_or(2); + for n in [6, 7] { + let total: u64 = std::thread::scope(|s| { + let hs: Vec<_> = (0..th).map(|t| s.spawn(move || every_hand(n, (0..52).filter(move |f| f % th == t)))).collect(); + hs.into_iter().map(|h| h.join().unwrap()).sum() + }); + eprintln!("{n} cards: {total} hands identical"); + assert_eq!(total, if n == 6 { 20_358_520 } else { 133_784_560 }); + } + } +} diff --git a/src/read/straight_draw.rs b/src/read/straight_draw.rs index 4e0f46a..466a733 100644 --- a/src/read/straight_draw.rs +++ b/src/read/straight_draw.rs @@ -12,9 +12,34 @@ use crate::variant::{HoleUsage, Rules}; /// How many different ranks complete a straight for hero. pub fn completing_ranks(rules: &Rules, census: &Census) -> u32 { + // The deck's windows once (at most 10), not once per rank. + let mut ws = [0u16; 16]; + let mut n = 0; + for w in windows(rules.deck) { + ws[n] = w; + n += 1; + } + let ws = &ws[..n]; + if matches!(rules.hole_usage, HoleUsage::BestFiveOfAll) { + // Rank `x` completes window `w` iff `x` is the one rank of `w` that hole + board lack and a + // hole rank in `w` is not on the board (the `completes` conditions, solved for `x`); so the + // completing ranks are the union, over windows missing exactly one rank, of that rank. + let (hole, board) = (census.hole_mask, census.board_mask); + let have = hole | board; + let done = ws.iter().fold(0u16, |done, &w| { + let missing = w & !have; + if missing.count_ones() == 1 && w & !board & !missing != 0 { done | missing } else { done } + }); + return (rules.deck.lowest.value()..=14u8).filter(|&pip| done & bit(pip) != 0 && census.total_count(pip) < 4).count() as u32; + } + scan(rules, census, ws) +} + +/// Every rank against every window (the definition; Omaha, and the reference for hold'em). +fn scan(rules: &Rules, census: &Census, ws: &[u16]) -> u32 { (rules.deck.lowest.value()..=14u8) .filter(|&pip| census.total_count(pip) < 4) - .filter(|&pip| windows(rules.deck).any(|w| completes(rules.hole_usage, census, w, bit(pip)))) + .filter(|&pip| ws.iter().any(|&w| completes(rules.hole_usage, census, w, bit(pip)))) .count() as u32 } @@ -59,3 +84,79 @@ fn backdoor_in(usage: HoleUsage, census: &Census, window: u16) -> bool { } } } + +#[cfg(test)] +mod perf_tests { + use super::*; + use crate::card::{Card, Rank, Suit}; + use crate::variant::{rules as rules_of, Variant}; + + /// The hold'em shortcut counts what the scan counts, on every rank pattern of two hole cards and a + /// flop, turn or river board (suits do not matter to straights), full and short deck. + #[test] + fn the_holdem_shortcut_equals_the_scan_on_every_rank_pattern() { + let ranks = [Rank::Two, Rank::Three, Rank::Four, Rank::Five, Rank::Six, Rank::Seven, Rank::Eight, Rank::Nine, Rank::Ten, Rank::Jack, Rank::Queen, Rank::King, Rank::Ace]; + let suits = [Suit::Clubs, Suit::Diamonds, Suit::Hearts, Suit::Spades]; + let mut checked = 0; + for variant in [Variant::Nlhe, Variant::ShortDeck] { + let rules = rules_of(variant); + let low = ranks.iter().position(|r| rules.deck.contains(*r)).unwrap(); + let deck = &ranks[low..]; + for n in 5..=7usize { + // Non-decreasing rank index sequences of length n, each rank at most four times. + let mut idx = vec![0usize; n]; + loop { + let mut used = [0usize; 13]; + let ok = idx.iter().all(|i| { + used[*i] += 1; + used[*i] <= 4 + }); + if ok { + // Every split into two hole cards and the board. + for a in 0..n { + for b in a + 1..n { + let mut seen = [0usize; 13]; + let cards: Vec = idx + .iter() + .map(|i| { + seen[*i] += 1; + Card { rank: deck[*i], suit: suits[seen[*i] - 1] } + }) + .collect(); + let hole = [cards[a], cards[b]]; + let board: Vec = (0..n).filter(|k| *k != a && *k != b).map(|k| cards[k]).collect(); + let census = Census::of(&hole, &board); + let ws: Vec = windows(rules.deck).collect(); + assert_eq!(completing_ranks(&rules, &census), scan(&rules, &census, &ws), "{hole:?} {board:?}"); + checked += 1; + } + } + } + // Next non-decreasing sequence. + let mut p = n; + loop { + if p == 0 { + break; + } + p -= 1; + if idx[p] + 1 < deck.len() { + idx[p] += 1; + for q in p + 1..n { + idx[q] = idx[p]; + } + break; + } + if p == 0 { + p = usize::MAX; + break; + } + } + if p == usize::MAX { + break; + } + } + } + } + assert!(checked > 100_000, "{checked}"); + } +}