Kartenabstraktion (E2b): Farb-Isomorphie, River-EHS, Verteilungs-Histogramme, k-means
- blueprint::iso: kanonischer Schluessel je (Board, Hand), dichter Index je Strasse; Flop 1 286 792 / Turn 13 960 050 kanonische Deals (Waugh), Spec fuer Farbumbenennung. - blueprint::abstraktion: River-EHS mit Kartenentzug in einem sortierten Durchgang (gleich Brute-Force), 256 River-Quantile (monoton), Turn/Flop-Histogramme der River-EHS (16 Faecher), gewichtetes k-means (Cramer-Abstand) auf rohen Deals gezogen, Klassen nach Staerke sortiert. - bin/abstraktion baut die Tabellen nach daten/abstraktion/ (nicht im Repo, aus Saat reproduzierbar). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -10,3 +10,7 @@ hand/dialoge-klon.json
|
||||
# mac/: Bauergebnisse von swift build und bauen.sh
|
||||
mac/.build/
|
||||
mac/build/
|
||||
|
||||
# E2b: Abstraktionstabellen sind aus dem Saatwert reproduzierbar (src/bin/abstraktion.rs)
|
||||
daten/abstraktion/*.u8
|
||||
daten/abstraktion/*.f32
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
//! Builds the blueprint card abstraction tables (plan E2b) into `<out>/`:
|
||||
//! `river.f32` (255 EHS cuts), `turn.u8`, `flop.u8` (one class per canonical deal of `iso::Street`),
|
||||
//! and `BERICHT.txt` (sizes, class counts, timings). Deterministic for a fixed seed.
|
||||
//!
|
||||
//! abstraktion <out> [sample] threads: POKERBENCH_THREADS (default 2)
|
||||
//!
|
||||
//! Bench copies are named `pokerbench-engine-abstraktion.exe` (CLAUDE.md "Messlaeufe").
|
||||
|
||||
use rechner::blueprint::abstraktion::{cluster, histograms, river_cuts, BINS, CLASSES};
|
||||
use rechner::blueprint::iso::Street;
|
||||
use std::io::Write;
|
||||
use std::time::Instant;
|
||||
|
||||
fn main() {
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
let out = std::path::PathBuf::from(args.get(1).expect("abstraktion <out> [sample]"));
|
||||
let sample: usize = args.get(2).and_then(|s| s.parse().ok()).unwrap_or(400_000);
|
||||
let threads: usize = std::env::var("POKERBENCH_THREADS").ok().and_then(|s| s.parse().ok()).unwrap_or(2).max(1);
|
||||
std::fs::create_dir_all(&out).unwrap();
|
||||
let mut bericht = format!("Kartenabstraktion E2b: {CLASSES} Klassen, {BINS} Faecher, Stichprobe {sample}, {threads} Threads\n");
|
||||
let log = |b: &mut String, s: String| {
|
||||
println!("{s}");
|
||||
b.push_str(&s);
|
||||
b.push('\n');
|
||||
};
|
||||
|
||||
let t = Instant::now();
|
||||
let cuts = river_cuts(20_000, 0xE2B_0001);
|
||||
let bytes: Vec<u8> = cuts.iter().flat_map(|c| c.to_le_bytes()).collect();
|
||||
std::fs::write(out.join("river.f32"), bytes).unwrap();
|
||||
log(&mut bericht, format!("river: {} Schnitte aus 20000 Boards, {:.1}s; erste {:.4} Mitte {:.4} letzte {:.4}", cuts.len(), t.elapsed().as_secs_f64(), cuts[0], cuts[cuts.len() / 2], cuts[cuts.len() - 1]));
|
||||
|
||||
for (name, cards, seed) in [("turn", 4usize, 0xE2B_0004u64), ("flop", 3, 0xE2B_0003)] {
|
||||
let t = Instant::now();
|
||||
let street = Street::new(cards);
|
||||
let hist = histograms(&street, threads);
|
||||
let t_hist = t.elapsed().as_secs_f64();
|
||||
let classes = cluster(&street, &hist, sample, seed, threads);
|
||||
let mut counts = vec![0usize; CLASSES];
|
||||
classes.iter().for_each(|c| counts[*c as usize] += 1);
|
||||
std::fs::File::create(out.join(format!("{name}.u8"))).unwrap().write_all(&classes).unwrap();
|
||||
let leer = counts.iter().filter(|c| **c == 0).count();
|
||||
log(
|
||||
&mut bericht,
|
||||
format!(
|
||||
"{name}: {} Boards, {} Deals, Histogramme {:.1}s, gesamt {:.1}s; leere Klassen {leer}; kleinste {} groesste {}",
|
||||
street.boards.len(),
|
||||
street.count(),
|
||||
t_hist,
|
||||
t.elapsed().as_secs_f64(),
|
||||
counts.iter().min().unwrap(),
|
||||
counts.iter().max().unwrap()
|
||||
),
|
||||
);
|
||||
}
|
||||
std::fs::write(out.join("BERICHT.txt"), bericht).unwrap();
|
||||
}
|
||||
@@ -0,0 +1,381 @@
|
||||
//! Card abstraction for the blueprint (plan E2b, design `docs/notizen/DESIGN-E2-grundstrategie.md`).
|
||||
//!
|
||||
//! - **River**: hand strength against a uniformly random opponent hand (EHS, with card removal),
|
||||
//! cut into `CLASSES` quantiles of its distribution over all deals. Computed on the fly per board
|
||||
//! (`river_ehs`: one sorted pass over the 1081 live hands, about 30 µs), so no table.
|
||||
//! - **Turn / flop**: the distribution of the final river EHS over all run-outs (`BINS`-bin
|
||||
//! histogram per canonical deal of `iso::Street`), clustered by weighted k-means under the
|
||||
//! Cramér distance (L2 between the cumulative histograms, a proper metric for 1-D distributions
|
||||
//! that, unlike L1-EMD, k-means with mean centroids minimises exactly). One `u8` class per
|
||||
//! canonical deal.
|
||||
//!
|
||||
//! Imperfect recall: a class depends only on the current board and hand, never on earlier classes.
|
||||
|
||||
use super::iso::{self, Street};
|
||||
use crate::hand::fast7;
|
||||
use crate::rng::split_mix::Rng;
|
||||
|
||||
pub const CLASSES: usize = 256;
|
||||
pub const BINS: usize = 16;
|
||||
|
||||
/// All 1326 two-card combos as masks, ordered by (low card, high card) in deck order.
|
||||
pub fn combos() -> Vec<u64> {
|
||||
let d = iso::deck();
|
||||
let mut out = Vec::with_capacity(1326);
|
||||
for i in 0..52 {
|
||||
for j in i + 1..52 {
|
||||
out.push(d[i] | d[j]);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Deck position 0..52 of a single card bit (`13 * suit + rank`).
|
||||
fn pos(bit: u64) -> usize {
|
||||
let t = bit.trailing_zeros() as usize;
|
||||
13 * (t / 16) + t % 16
|
||||
}
|
||||
|
||||
/// Index of a two-card mask in `combos()`.
|
||||
pub fn combo_index(hand: u64) -> usize {
|
||||
let a = pos(hand & hand.wrapping_neg());
|
||||
let b = pos(hand & (hand - 1));
|
||||
// Combos before row `a`: sum over i < a of (51 - i).
|
||||
a * (103 - a) / 2 + (b - a - 1)
|
||||
}
|
||||
|
||||
/// EHS of every combo on a five-card board: P(win) + P(tie)/2 against a uniform live opponent hand.
|
||||
/// Combos that touch the board get `-1`.
|
||||
pub fn river_ehs(board: u64, all: &[u64]) -> Vec<f32> {
|
||||
let mut live: Vec<(u32, u16)> = all.iter().enumerate().filter(|(_, h)| *h & board == 0).map(|(i, h)| (fast7::score(board | h), i as u16)).collect();
|
||||
live.sort_unstable();
|
||||
let mut out = vec![-1f32; all.len()];
|
||||
// Running counts of hands strictly below the current score group, in total and per card.
|
||||
let (mut below, mut below_card) = (0i32, [0i32; 52]);
|
||||
let mut g = 0;
|
||||
while g < live.len() {
|
||||
let mut e = g;
|
||||
while e < live.len() && live[e].0 == live[g].0 {
|
||||
e += 1;
|
||||
}
|
||||
let mut tie_card = [0i32; 52];
|
||||
for (_, i) in &live[g..e] {
|
||||
let h = all[*i as usize];
|
||||
tie_card[pos(h & h.wrapping_neg())] += 1;
|
||||
tie_card[pos(h & (h - 1))] += 1;
|
||||
}
|
||||
let tie = (e - g) as i32;
|
||||
for (_, i) in &live[g..e] {
|
||||
let h = all[*i as usize];
|
||||
let (a, b) = (pos(h & h.wrapping_neg()), pos(h & (h - 1)));
|
||||
let wins = below - below_card[a] - below_card[b];
|
||||
let ties = tie - tie_card[a] - tie_card[b] + 1; // the hand itself was subtracted twice
|
||||
out[*i as usize] = (wins as f32 + 0.5 * ties as f32) / 990.0;
|
||||
}
|
||||
below += tie;
|
||||
for c in 0..52 {
|
||||
below_card[c] += tie_card[c];
|
||||
}
|
||||
g = e;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn bin(ehs: f32) -> usize {
|
||||
((ehs * BINS as f32) as usize).min(BINS - 1)
|
||||
}
|
||||
|
||||
/// Run `f(board_index)` over all boards of a street on `threads` threads, collecting the per-board
|
||||
/// results in board order.
|
||||
fn per_board<T: Send>(boards: usize, threads: usize, f: impl Fn(usize) -> T + Sync) -> Vec<T> {
|
||||
let next = std::sync::atomic::AtomicUsize::new(0);
|
||||
let mut parts: Vec<Vec<(usize, T)>> = std::thread::scope(|s| {
|
||||
let hs: Vec<_> = (0..threads.max(1))
|
||||
.map(|_| {
|
||||
s.spawn(|| {
|
||||
let mut mine = Vec::new();
|
||||
loop {
|
||||
let b = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
if b >= boards {
|
||||
return mine;
|
||||
}
|
||||
mine.push((b, f(b)));
|
||||
}
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
hs.into_iter().map(|h| h.join().unwrap()).collect()
|
||||
});
|
||||
let mut all: Vec<(usize, T)> = parts.drain(..).flatten().collect();
|
||||
all.sort_unstable_by_key(|x| x.0);
|
||||
all.into_iter().map(|x| x.1).collect()
|
||||
}
|
||||
|
||||
/// River-EHS histograms (counts) of every canonical deal of a turn (`street` with 4 board cards) or
|
||||
/// flop (3) street, in the street's dense index order.
|
||||
pub fn histograms(street: &Street, threads: usize) -> Vec<[u16; BINS]> {
|
||||
let all = combos();
|
||||
let deck = iso::deck();
|
||||
let per = per_board(street.boards.len(), threads, |bi| {
|
||||
let board = street.boards[bi];
|
||||
let hands = &street.hands[bi];
|
||||
let mut h = vec![[0u16; BINS]; hands.len()];
|
||||
let rest: Vec<u64> = deck.iter().copied().filter(|c| c & board == 0).collect();
|
||||
let mut add = |full: u64| {
|
||||
let ehs = river_ehs(full, &all);
|
||||
for (k, hand) in hands.iter().enumerate() {
|
||||
if hand & full == 0 {
|
||||
h[k][bin(ehs[combo_index(*hand)])] += 1;
|
||||
}
|
||||
}
|
||||
};
|
||||
match board.count_ones() {
|
||||
4 => rest.iter().for_each(|r| add(board | r)),
|
||||
3 => {
|
||||
for i in 0..rest.len() {
|
||||
for j in i + 1..rest.len() {
|
||||
add(board | rest[i] | rest[j]);
|
||||
}
|
||||
}
|
||||
}
|
||||
n => panic!("histograms need a flop or turn board, got {n} cards"),
|
||||
}
|
||||
h
|
||||
});
|
||||
per.into_iter().flatten().collect()
|
||||
}
|
||||
|
||||
/// Normalised cumulative histogram (the k-means point).
|
||||
fn cdf(h: &[u16; BINS]) -> [f32; BINS] {
|
||||
let n: u32 = h.iter().map(|x| *x as u32).sum();
|
||||
let mut out = [0f32; BINS];
|
||||
let mut acc = 0u32;
|
||||
for k in 0..BINS {
|
||||
acc += h[k] as u32;
|
||||
out[k] = acc as f32 / n.max(1) as f32;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn dist(a: &[f32; BINS], b: &[f32; BINS]) -> f32 {
|
||||
a.iter().zip(b).map(|(x, y)| (x - y) * (x - y)).sum()
|
||||
}
|
||||
|
||||
fn nearest(p: &[f32; BINS], centers: &[[f32; BINS]]) -> (usize, f32) {
|
||||
let mut best = (0, f32::INFINITY);
|
||||
for (k, c) in centers.iter().enumerate() {
|
||||
let d = dist(p, c);
|
||||
if d < best.1 {
|
||||
best = (k, d);
|
||||
}
|
||||
}
|
||||
best
|
||||
}
|
||||
|
||||
struct Draw(Rng);
|
||||
impl Draw {
|
||||
fn below(&mut self, n: usize) -> usize {
|
||||
let (x, r) = self.0.below(n as u64);
|
||||
self.0 = r;
|
||||
x as usize
|
||||
}
|
||||
fn unit(&mut self) -> f64 {
|
||||
let (x, r) = self.0.unit();
|
||||
self.0 = r;
|
||||
x
|
||||
}
|
||||
}
|
||||
|
||||
/// Weighted k-means (k-means++ seeding, Lloyd steps) on a training sample of deals drawn uniformly
|
||||
/// from all RAW deals (so a canonical deal weighs as many raw deals as it stands for), then every
|
||||
/// canonical deal is assigned to its nearest centre. Classes are relabelled by mean EHS, so class
|
||||
/// order means strength order. Returns one class per canonical deal.
|
||||
pub fn cluster(street: &Street, hist: &[[u16; BINS]], sample: usize, seed: u64, threads: usize) -> Vec<u8> {
|
||||
let mut rng = Draw(Rng::seeded(seed));
|
||||
let deck = iso::deck();
|
||||
let board_cards = street.boards[0].count_ones() as usize;
|
||||
let pts: Vec<[f32; BINS]> = (0..sample)
|
||||
.map(|_| {
|
||||
let mut m = 0u64;
|
||||
while (m.count_ones() as usize) < board_cards + 2 {
|
||||
m |= deck[rng.below(52)];
|
||||
}
|
||||
// Split the drawn cards: the first two set bits by draw order are not tracked, so draw
|
||||
// the hand from the drawn set uniformly instead.
|
||||
let cards: Vec<u64> = deck.iter().copied().filter(|c| c & m != 0).collect();
|
||||
let a = rng.below(cards.len());
|
||||
let mut b = rng.below(cards.len() - 1);
|
||||
if b >= a {
|
||||
b += 1;
|
||||
}
|
||||
let hand = cards[a] | cards[b];
|
||||
cdf(&hist[street.index(m & !hand, hand).unwrap() as usize])
|
||||
})
|
||||
.collect();
|
||||
// k-means++ seeding.
|
||||
let mut centers = vec![pts[rng.below(pts.len())]];
|
||||
let mut d2: Vec<f32> = pts.iter().map(|p| dist(p, ¢ers[0])).collect();
|
||||
while centers.len() < CLASSES {
|
||||
let total: f64 = d2.iter().map(|x| *x as f64).sum();
|
||||
let pick = if total <= 0.0 {
|
||||
rng.below(pts.len())
|
||||
} else {
|
||||
let mut t = rng.unit() * total;
|
||||
let mut k = 0;
|
||||
while k + 1 < pts.len() && t >= d2[k] as f64 {
|
||||
t -= d2[k] as f64;
|
||||
k += 1;
|
||||
}
|
||||
k
|
||||
};
|
||||
centers.push(pts[pick]);
|
||||
let c = *centers.last().unwrap();
|
||||
for (k, p) in pts.iter().enumerate() {
|
||||
d2[k] = d2[k].min(dist(p, &c));
|
||||
}
|
||||
}
|
||||
// Lloyd steps on the sample.
|
||||
for _ in 0..100 {
|
||||
let assign = par_assign(&pts, ¢ers, threads);
|
||||
let mut sum = vec![[0f64; BINS]; CLASSES];
|
||||
let mut cnt = vec![0usize; CLASSES];
|
||||
for (p, (k, _)) in pts.iter().zip(&assign) {
|
||||
cnt[*k] += 1;
|
||||
for b in 0..BINS {
|
||||
sum[*k][b] += p[b] as f64;
|
||||
}
|
||||
}
|
||||
let mut moved = 0f32;
|
||||
for k in 0..CLASSES {
|
||||
if cnt[k] == 0 {
|
||||
// An empty class takes the point farthest from its centre.
|
||||
let far = assign.iter().enumerate().max_by(|x, y| x.1 .1.total_cmp(&y.1 .1)).unwrap().0;
|
||||
centers[k] = pts[far];
|
||||
moved = f32::INFINITY;
|
||||
continue;
|
||||
}
|
||||
let mut c = [0f32; BINS];
|
||||
for b in 0..BINS {
|
||||
c[b] = (sum[k][b] / cnt[k] as f64) as f32;
|
||||
}
|
||||
moved = moved.max(dist(&c, ¢ers[k]));
|
||||
centers[k] = c;
|
||||
}
|
||||
if moved < 1e-7 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// Relabel by strength: mean EHS of a CDF point is 1 - mean(cdf) up to the bin width.
|
||||
let mut order: Vec<usize> = (0..CLASSES).collect();
|
||||
order.sort_by(|a, b| centers[*b].iter().sum::<f32>().total_cmp(¢ers[*a].iter().sum::<f32>()));
|
||||
let centers: Vec<[f32; BINS]> = order.iter().map(|k| centers[*k]).collect();
|
||||
let all: Vec<[f32; BINS]> = hist.iter().map(cdf).collect();
|
||||
par_assign(&all, ¢ers, threads).into_iter().map(|(k, _)| k as u8).collect()
|
||||
}
|
||||
|
||||
fn par_assign(pts: &[[f32; BINS]], centers: &[[f32; BINS]], threads: usize) -> Vec<(usize, f32)> {
|
||||
let chunk = pts.len().div_ceil(threads.max(1)).max(1);
|
||||
std::thread::scope(|s| {
|
||||
let hs: Vec<_> = pts.chunks(chunk).map(|c| s.spawn(move || c.iter().map(|p| nearest(p, centers)).collect::<Vec<_>>())).collect();
|
||||
hs.into_iter().flat_map(|h| h.join().unwrap()).collect()
|
||||
})
|
||||
}
|
||||
|
||||
/// River class thresholds: the `CLASSES - 1` inner quantiles of EHS over raw river deals, estimated
|
||||
/// from `boards` random boards (all live hands of each).
|
||||
pub fn river_cuts(boards: usize, seed: u64) -> Vec<f32> {
|
||||
let mut rng = Draw(Rng::seeded(seed));
|
||||
let deck = iso::deck();
|
||||
let all = combos();
|
||||
let mut v = Vec::with_capacity(boards * 1081);
|
||||
for _ in 0..boards {
|
||||
let mut m = 0u64;
|
||||
while m.count_ones() < 5 {
|
||||
m |= deck[rng.below(52)];
|
||||
}
|
||||
v.extend(river_ehs(m, &all).into_iter().filter(|x| *x >= 0.0));
|
||||
}
|
||||
v.sort_unstable_by(|a, b| a.total_cmp(b));
|
||||
(1..CLASSES).map(|k| v[k * v.len() / CLASSES]).collect()
|
||||
}
|
||||
|
||||
/// River class of an EHS value under `cuts` (monotone: higher EHS, higher or equal class).
|
||||
pub fn river_class(ehs: f32, cuts: &[f32]) -> u8 {
|
||||
cuts.partition_point(|c| *c <= ehs) as u8
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::card::Card;
|
||||
|
||||
fn m(t: &str) -> u64 {
|
||||
fast7::mask(&Card::parse_list(t).unwrap())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn combo_index_is_the_position_in_combos() {
|
||||
let all = combos();
|
||||
for (i, h) in all.iter().enumerate() {
|
||||
assert_eq!(combo_index(*h), i);
|
||||
}
|
||||
}
|
||||
|
||||
/// EHS by the sorted pass equals brute force over all live opponent hands.
|
||||
#[test]
|
||||
fn river_ehs_matches_brute_force() {
|
||||
let all = combos();
|
||||
for board in ["Ah Kd 7c 7s 2h", "9h Th Jh 2c 3d", "2c 2d 2h 2s Ac"] {
|
||||
let b = m(board);
|
||||
let fast = river_ehs(b, &all);
|
||||
for (i, h) in all.iter().enumerate().step_by(37) {
|
||||
if h & b != 0 {
|
||||
assert_eq!(fast[i], -1.0);
|
||||
continue;
|
||||
}
|
||||
let me = fast7::score(b | h);
|
||||
let (mut w, mut n) = (0f32, 0f32);
|
||||
for o in &all {
|
||||
if o & (b | h) == 0 {
|
||||
n += 1.0;
|
||||
let s = fast7::score(b | o);
|
||||
w += if me > s { 1.0 } else if me == s { 0.5 } else { 0.0 };
|
||||
}
|
||||
}
|
||||
assert_eq!(n, 990.0);
|
||||
assert!((fast[i] - w / n).abs() < 1e-6, "{board} combo {i}: {} vs {}", fast[i], w / n);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn river_classes_are_monotone_and_fill_the_range() {
|
||||
let cuts = river_cuts(400, 7);
|
||||
assert_eq!(cuts.len(), CLASSES - 1);
|
||||
assert!(cuts.windows(2).all(|w| w[0] <= w[1]));
|
||||
assert_eq!(river_class(0.0, &cuts), 0);
|
||||
assert_eq!(river_class(1.0, &cuts) as usize, CLASSES - 1);
|
||||
let mut last = 0;
|
||||
for k in 0..=1000 {
|
||||
let c = river_class(k as f32 / 1000.0, &cuts);
|
||||
assert!(c >= last);
|
||||
last = c;
|
||||
}
|
||||
}
|
||||
|
||||
/// The nuts on the turn stay the nuts on every river; a dead hand stays dead.
|
||||
#[test]
|
||||
fn turn_histograms_put_locked_hands_at_the_ends() {
|
||||
let s = Street::new(4);
|
||||
let bi = s.board_keys.binary_search(&iso::board_key(m("2c 7d 9h Ks"))).unwrap();
|
||||
let sub = Street { board_keys: vec![s.board_keys[bi]], boards: vec![s.boards[bi]], hand_keys: vec![s.hand_keys[bi].clone()], hands: vec![s.hands[bi].clone()], offset: vec![0, s.hand_keys[bi].len() as u32] };
|
||||
let h = histograms(&sub, 1);
|
||||
assert_eq!(h.len(), sub.count());
|
||||
for (k, x) in h.iter().enumerate() {
|
||||
assert_eq!(x.iter().map(|c| *c as u32).sum::<u32>(), 46, "deal {k}");
|
||||
}
|
||||
// Find the canonical representative of KK on this board (top set): almost all mass high.
|
||||
let kk = sub.hand_keys[0].binary_search(&iso::deal_key(m("2c 7d 9h Ks"), m("Kh Kd"))).unwrap();
|
||||
assert!(h[kk][BINS - 1] >= 40, "{:?}", h[kk]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
//! Suit isomorphism for (board, hand) on one street (plan E2b).
|
||||
//!
|
||||
//! Two deals that differ only by a renaming of the suits are strategically identical. The canonical
|
||||
//! key of a deal is the list of the four suits' `(board ranks, hand ranks)` pairs, sorted descending:
|
||||
//! renaming the suits only permutes that list, so the sorted list is the same for every renaming and
|
||||
//! differs for anything else. The board's own key is the same list without the hand ranks.
|
||||
//!
|
||||
//! `Street` enumerates the canonical boards of a street and, per board, the canonical hands, giving a
|
||||
//! dense index `0..count()` for lookup tables (imperfect recall: the board is a set, the order in
|
||||
//! which its cards came does not matter). Known sizes (Waugh 2013): flop 1 286 792, turn 13 960 050.
|
||||
|
||||
use crate::hand::fast7;
|
||||
|
||||
/// 13 rank bits of each suit lane of a card mask (`hand::fast7` layout).
|
||||
fn lanes(m: u64) -> [u32; 4] {
|
||||
[(m & 0x1FFF) as u32, ((m >> 16) & 0x1FFF) as u32, ((m >> 32) & 0x1FFF) as u32, ((m >> 48) & 0x1FFF) as u32]
|
||||
}
|
||||
|
||||
/// Canonical key of a board alone.
|
||||
pub fn board_key(board: u64) -> u64 {
|
||||
let mut b = lanes(board);
|
||||
b.sort_unstable_by(|x, y| y.cmp(x));
|
||||
b.iter().fold(0u64, |k, x| (k << 13) | *x as u64)
|
||||
}
|
||||
|
||||
/// Canonical key of board + hand.
|
||||
pub fn deal_key(board: u64, hand: u64) -> u128 {
|
||||
let (b, h) = (lanes(board), lanes(hand));
|
||||
let mut pairs = [(b[0], h[0]), (b[1], h[1]), (b[2], h[2]), (b[3], h[3])];
|
||||
pairs.sort_unstable_by(|x, y| y.cmp(x));
|
||||
pairs.iter().fold(0u128, |k, (b, h)| (k << 26) | ((*b as u128) << 13) | *h as u128)
|
||||
}
|
||||
|
||||
/// All 52 card bits.
|
||||
pub fn deck() -> Vec<u64> {
|
||||
(0..4).flat_map(|s| (0..13).map(move |r| 1u64 << (16 * s + r))).collect()
|
||||
}
|
||||
|
||||
/// All `k`-card subsets of the deck as masks.
|
||||
pub fn subsets(k: usize) -> Vec<u64> {
|
||||
let d = deck();
|
||||
let mut out = Vec::new();
|
||||
let mut idx: Vec<usize> = (0..k).collect();
|
||||
loop {
|
||||
out.push(idx.iter().fold(0u64, |m, i| m | d[*i]));
|
||||
let mut i = k;
|
||||
while i > 0 && idx[i - 1] == 52 - k + i - 1 {
|
||||
i -= 1;
|
||||
}
|
||||
if i == 0 {
|
||||
return out;
|
||||
}
|
||||
idx[i - 1] += 1;
|
||||
for j in i..k {
|
||||
idx[j] = idx[j - 1] + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The canonical deals of one street: canonical boards (sorted by key) and per board its canonical
|
||||
/// hands (sorted by key), with prefix offsets for the dense index.
|
||||
pub struct Street {
|
||||
pub board_keys: Vec<u64>,
|
||||
/// One representative board mask per canonical board (same order as `board_keys`).
|
||||
pub boards: Vec<u64>,
|
||||
/// Per board, its canonical deal keys, sorted.
|
||||
pub hand_keys: Vec<Vec<u128>>,
|
||||
/// Per board, one representative hand mask per deal key (same order as `hand_keys`).
|
||||
pub hands: Vec<Vec<u64>>,
|
||||
pub offset: Vec<u32>,
|
||||
}
|
||||
|
||||
impl Street {
|
||||
/// Enumerate the street with `board_cards` board cards (3 = flop, 4 = turn, 5 = river).
|
||||
pub fn new(board_cards: usize) -> Street {
|
||||
let mut reps: Vec<(u64, u64)> = Vec::new();
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
for b in subsets(board_cards) {
|
||||
let k = board_key(b);
|
||||
if seen.insert(k) {
|
||||
reps.push((k, b));
|
||||
}
|
||||
}
|
||||
reps.sort_unstable();
|
||||
let hole = subsets(2);
|
||||
let mut hand_keys = Vec::with_capacity(reps.len());
|
||||
let mut hands = Vec::with_capacity(reps.len());
|
||||
let mut offset = Vec::with_capacity(reps.len() + 1);
|
||||
let mut total = 0u32;
|
||||
for (_, b) in &reps {
|
||||
let mut ks: Vec<(u128, u64)> = hole.iter().filter(|h| *h & b == 0).map(|h| (deal_key(*b, *h), *h)).collect();
|
||||
ks.sort_unstable_by_key(|x| x.0);
|
||||
ks.dedup_by_key(|x| x.0);
|
||||
offset.push(total);
|
||||
total += ks.len() as u32;
|
||||
hand_keys.push(ks.iter().map(|x| x.0).collect());
|
||||
hands.push(ks.iter().map(|x| x.1).collect());
|
||||
}
|
||||
offset.push(total);
|
||||
Street { board_keys: reps.iter().map(|x| x.0).collect(), boards: reps.iter().map(|x| x.1).collect(), hand_keys, hands, offset }
|
||||
}
|
||||
|
||||
/// Number of canonical deals.
|
||||
pub fn count(&self) -> usize {
|
||||
*self.offset.last().unwrap_or(&0) as usize
|
||||
}
|
||||
|
||||
/// Dense index of a deal, or `None` for an impossible one (overlapping cards).
|
||||
pub fn index(&self, board: u64, hand: u64) -> Option<u32> {
|
||||
if board & hand != 0 {
|
||||
return None;
|
||||
}
|
||||
let bi = self.board_keys.binary_search(&board_key(board)).ok()?;
|
||||
let hi = self.hand_keys[bi].binary_search(&deal_key(board, hand)).ok()?;
|
||||
Some(self.offset[bi] + hi as u32)
|
||||
}
|
||||
}
|
||||
|
||||
/// A canonical deal's cards: `(board, hand)` of the representative at `index`.
|
||||
pub fn deal_at(street: &Street, index: u32) -> (u64, u64) {
|
||||
let bi = street.offset.partition_point(|o| *o <= index) - 1;
|
||||
let hi = (index - street.offset[bi]) as usize;
|
||||
(street.boards[bi], street.hands[bi][hi])
|
||||
}
|
||||
|
||||
/// Mask of card list (re-export for callers that work with `Card`s).
|
||||
pub use fast7::mask;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn flop_has_the_known_number_of_canonical_deals() {
|
||||
let s = Street::new(3);
|
||||
assert_eq!(s.board_keys.len(), 1755);
|
||||
assert_eq!(s.count(), 1_286_792);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turn_has_the_known_number_of_canonical_deals() {
|
||||
let s = Street::new(4);
|
||||
assert_eq!(s.board_keys.len(), 16_432);
|
||||
assert_eq!(s.count(), 13_960_050);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_suit_renaming_keeps_the_index() {
|
||||
let s = Street::new(3);
|
||||
let m = |t: &str| mask(&crate::card::Card::parse_list(t).unwrap());
|
||||
let a = s.index(m("Ah 7h 2c"), m("Kh Qd")).unwrap();
|
||||
let b = s.index(m("As 7s 2d"), m("Ks Qc")).unwrap();
|
||||
let c = s.index(m("As 7s 2d"), m("Ks Qd")).unwrap();
|
||||
assert_eq!(a, b);
|
||||
assert_ne!(a, c, "the queen's suit relation to the board differs");
|
||||
let (board, hand) = deal_at(&s, a);
|
||||
assert_eq!(s.index(board, hand), Some(a));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
//! Offline-Grundstrategie (Plan E2): Abstraktion und Loeser.
|
||||
|
||||
pub mod abstraktion;
|
||||
pub mod iso;
|
||||
@@ -3,6 +3,7 @@
|
||||
//! Pipeline: parse (json) → decode (wire) → check (guard) → assess (equity, odds)
|
||||
//! → choose (engine) → enforce (guard) → render (wire).
|
||||
|
||||
pub mod blueprint;
|
||||
pub mod card;
|
||||
pub mod cfr;
|
||||
pub mod engine;
|
||||
|
||||
Reference in New Issue
Block a user