diff --git a/messung_engine/warteschlange.txt b/messung_engine/warteschlange.txt index c10dd5f5..ccc35115 100644 --- a/messung_engine/warteschlange.txt +++ b/messung_engine/warteschlange.txt @@ -24,6 +24,7 @@ abstraktion|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b grundstrategie-s1|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\bin\pokerbench-engine-grundstrategie.exe|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\daten\abstraktion D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\daten\grundstrategie 400 1000000||D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88 engine-lbr|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\bin\pokerbench-engine-lbr.exe|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\lbr\engine-s1.txt 20000||D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88 #river-grund|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\bin\pokerbench-engine-rivergrund.exe|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\arme\river-grund 2000 4000 4 all|RIVER_DBR=grund;GRUNDSTRATEGIE=D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\daten;FRUEHSTOPP=arme\zaehl| +grundtextur-s1|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\bin\pokerbench-engine-grundtextur.exe|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\daten\abstraktion D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\daten\grundstrategie 400 1000000||D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88 grundstrategie-sb|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\bin\pokerbench-engine-grundszen.exe|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\daten\abstraktion D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\daten\grundstrategie 200 1000000 sb||D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88 grundstrategie-co|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\bin\pokerbench-engine-grundszen.exe|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\daten\abstraktion D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\daten\grundstrategie 200 1000000 co||D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88 grundstrategie-btn3|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\bin\pokerbench-engine-grundszen.exe|D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\daten\abstraktion D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\daten\grundstrategie 200 1000000 btn3||D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88 diff --git a/src/bin/grundtextur.rs b/src/bin/grundtextur.rs new file mode 100644 index 00000000..0aaa3c90 --- /dev/null +++ b/src/bin/grundtextur.rs @@ -0,0 +1,93 @@ +//! Computes a blueprint scenario with the board-texture refinement (`blueprint::textur`; plan E2, +//! gate "Abstraktion verfeinern, einmal"). Same as `grundstrategie`, other artefact names, so the +//! plain blueprint keeps running untouched: +//! +//! grundtextur [periode] [szenario] threads: POKERBENCH_THREADS +//! +//! Checkpoint `/-t.ckpt`, LBR lines `LBR-t-.txt`, marker `FERTIG-t-`. +//! The abstraction tables are the plain ones (`abstraktion` bin); the texture needs none of its own. +//! Experiments (not for production): `TEXTUR=grob|fein`, `TEXTUR_K=,` (default fein, 64,64), +//! `LBR_ALLE=` LBR every n rounds (default 20), `LBR_HAENDE=` hands of the periodic LBR (default +//! 20000), `FLOP_FEST="Ks 7d 2c"` fixed flop (diagnostic, as plateau_flop), `LBR_ENDE=` hands at the end (default 400000). Bench copy: `pokerbench-engine-grundtextur.exe`. + +use rechner::blueprint::lbr::lbr; +use rechner::blueprint::mccfr::{rechnen, Tabellen}; +use rechner::blueprint::s1::{Abstraktion, Grund}; +use rechner::blueprint::szenario::Szenario; +use rechner::blueprint::textur::Textur; +use std::io::Write; +use std::path::Path; +use std::time::Instant; + +fn env(k: &str, d: T) -> T { + std::env::var(k).ok().and_then(|s| s.parse().ok()).unwrap_or(d) +} + +fn main() { + let a: Vec = std::env::args().collect(); + if a.len() < 4 { + panic!("grundtextur [periode] [s1|sb|co|btn3|co3]"); + } + let runden: u64 = a[3].parse().unwrap(); + let periode: u64 = a.get(4).and_then(|s| s.parse().ok()).unwrap_or(1_000_000); + let name = a.get(5).map_or("s1", |s| s.as_str()); + let sz = Szenario::finde(name).unwrap_or_else(|| panic!("unknown scenario {name}")); + let sitze = if sz.id == "s1" { ["BB", "BTN"] } else { ["OOP", "IP"] }; + let threads: usize = env("POKERBENCH_THREADS", 2usize).max(1); + let k: Vec = std::env::var("TEXTUR_K").ok().map(|s| s.split(',').map(|x| x.parse().unwrap()).collect()).unwrap_or_else(|| vec![64, 64]); + let textur = match std::env::var("TEXTUR").ok().as_deref() { + None | Some("fein") | Some("") => Some(Textur::neu(false, k[0], k[1])), + Some("grob") => Some(Textur::neu(true, k[0], k[1])), + Some("aus") => None, + + Some(x) => panic!("TEXTUR={x}"), + }; + let beschr = textur.as_ref().map_or("ohne Textur (Vergleichslauf, Datei .ckpt)".to_string(), |t| format!("Flop {} Gruppen x {} Klassen, Turn {} Gruppen x {} Klassen", t.flop_gruppen, t.k_flop, t.turn_gruppen, t.k_turn)); + let nur_pruefen = textur.is_none(); + let out = Path::new(&a[2]); + std::fs::create_dir_all(out).unwrap(); + while !Path::new(&a[1]).join("BERICHT.txt").exists() { + std::thread::sleep(std::time::Duration::from_secs(30)); + } + let abs = Abstraktion::laden(Path::new(&a[1])).expect("abstraction tables"); + let mut spiel = match textur { + Some(t) => Grund::mit_textur(sz, abs, t), + None => Grund::mit(sz, abs), + }; + if let Ok(f) = std::env::var("FLOP_FEST") { + use rechner::card::Card; + spiel.flop_fest = Some(Card::parse_list(&f).unwrap().iter().fold(0, |m, c| m | rechner::hand::fast7::bit(*c))); + } + let mut tab = Tabellen::neu(&spiel); + let ckpt = out.join(if nur_pruefen { format!("{}.ckpt", sz.id) } else { format!("{}-t.ckpt", sz.id) }); + if tab.datei_lesen(&ckpt) { + println!("fortgesetzt bei Runde {}", tab.runden); + } + println!( + "{}-t: {} Eintraege ({:.0} MB), {beschr}, {threads} Threads, Periode {periode}", + sz.id, + tab.eintraege(), + tab.eintraege() as f64 * 16.0 / 1e6 + ); + let (alle, haende, ende): (u64, usize, usize) = (env("LBR_ALLE", 20), env("LBR_HAENDE", 20_000), env("LBR_ENDE", 400_000)); + while tab.runden < runden { + let t = Instant::now(); + rechnen(&spiel, &mut tab, 1, periode, threads, 0xE2D_5EED); + tab.datei_schreiben(&ckpt).unwrap(); + let s = t.elapsed().as_secs_f64(); + println!("Runde {} fertig: {:.1}s, {:.0} Iterationen/s", tab.runden, s, periode as f64 / s); + if tab.runden % alle == 0 || tab.runden == runden { + let t = Instant::now(); + let n = if tab.runden == runden { ende } else { haende }; + let e = lbr(&spiel, &tab, n, threads, 0x1B2 ^ tab.runden); + let zeile = format!( + "Runde {} LBR {:+.1} ±{:.1} bb/100 ({} {:+.1}, {} {:+.1}), {} Haende, {:.0}s", + tab.runden, e.bb100, e.ci95, sitze[0], e.je_sitz[0], sitze[1], e.je_sitz[1], e.haende, t.elapsed().as_secs_f64() + ); + println!("{zeile}"); + let mut f = std::fs::OpenOptions::new().create(true).append(true).open(out.join(format!("LBR-t-{}.txt", sz.id))).unwrap(); + writeln!(f, "{zeile}").unwrap(); + } + } + std::fs::write(out.join(format!("FERTIG-t-{}", sz.id)), format!("{} Runden\n", tab.runden)).unwrap(); +} diff --git a/src/blueprint/mod.rs b/src/blueprint/mod.rs index 50996dff..1ba15409 100644 --- a/src/blueprint/mod.rs +++ b/src/blueprint/mod.rs @@ -8,3 +8,4 @@ pub mod mccfr; pub mod ranges; pub mod s1; pub mod szenario; +pub mod textur; diff --git a/src/blueprint/ranges.rs b/src/blueprint/ranges.rs index 22f439d3..26e66367 100644 --- a/src/blueprint/ranges.rs +++ b/src/blueprint/ranges.rs @@ -104,14 +104,28 @@ static GRUND: [std::sync::OnceLock>; ALLE.len()] = [const { std::sync::OnceLock::new() }; ALLE.len()]; /// The blueprint of scenario `sz`, loaded once from `$GRUNDSTRATEGIE/abstraktion/` and -/// `$GRUNDSTRATEGIE/grundstrategie/.ckpt`; `None` without the variable or the files. +/// `$GRUNDSTRATEGIE/grundstrategie/`: with `GRUNDSTRATEGIE_TEXTUR=1` the board-texture refinement `-t.ckpt` where one exists +/// (and matches `Textur::standard()`), else the plain `.ckpt`; `None` without the variable or +/// the files. pub fn grundstrategie_fuer(sz: &Szenario) -> Option<&'static (Grund, Tabellen)> { GRUND[sz.index()] .get_or_init(|| { let dir = std::path::PathBuf::from(std::env::var_os("GRUNDSTRATEGIE")?); - let s = Grund::mit(ALLE.iter().find(|z| z.id == sz.id)?, super::s1::Abstraktion::laden(&dir.join("abstraktion")).ok()?); + let sz = ALLE.iter().find(|z| z.id == sz.id)?; + let abs = dir.join("abstraktion"); + let ckpt = dir.join("grundstrategie"); + let fein = ckpt.join(format!("{}-t.ckpt", sz.id)); + // Opt-in until the refined run has passed its gate (a run rewrites the file every round). + if std::env::var_os("GRUNDSTRATEGIE_TEXTUR").is_some_and(|v| v == "1") && fein.exists() { + let s = Grund::mit_textur(sz, super::s1::Abstraktion::laden(&abs).ok()?, super::textur::Textur::standard()); + let mut tab = Tabellen::neu(&s); + if super::textur::ckpt_passt(&fein, tab.eintraege()) && tab.datei_lesen(&fein) { + return Some((s, tab)); + } + } + let s = Grund::mit(sz, super::s1::Abstraktion::laden(&abs).ok()?); let mut tab = Tabellen::neu(&s); - tab.datei_lesen(&dir.join("grundstrategie").join(format!("{}.ckpt", sz.id))).then_some((s, tab)) + tab.datei_lesen(&ckpt.join(format!("{}.ckpt", sz.id))).then_some((s, tab)) }) .as_ref() } diff --git a/src/blueprint/s1.rs b/src/blueprint/s1.rs index 1c41f940..60ca4fcc 100644 --- a/src/blueprint/s1.rs +++ b/src/blueprint/s1.rs @@ -13,6 +13,7 @@ use super::abstraktion::{combo_index, combos, river_class, river_ehs, CLASSES}; use super::iso::{self, Street}; use super::mccfr::{Baum, Knoten, Spiel, Zufall}; use super::szenario::Szenario; +use super::textur::Textur; use crate::card::Card; use crate::cfr::hand_class::class_of; use crate::hand::fast7; @@ -177,7 +178,7 @@ impl Abstraktion { pub struct Deal { pub hand: [u64; 2], pub board: [u64; 5], - pub klasse: [[u8; 3]; 2], + pub klasse: [[u16; 3]; 2], /// +1 player 0 wins the showdown, -1 player 1, 0 split. pub sieger: i8, } @@ -195,6 +196,9 @@ pub struct Grund { pub gewicht: [Vec; 2], /// Diagnostic: deal this flop always (bit mask of 3 cards). pub flop_fest: Option, + /// Board-texture refinement of the flop / turn information sets (`textur.rs`); `None` = the + /// plain 256 board-blind classes of old (checkpoint `.ckpt`). + pub textur: Option, } /// Range weight per combo of `combos()` from a chart frequency per hand class. @@ -205,6 +209,13 @@ fn gewichte(alle: &[u64], f: impl Fn(Card, Card) -> f64) -> Vec { } impl Grund { + /// The game with the board-texture refinement (checkpoint `-t.ckpt`). + pub fn mit_textur(sz: &'static Szenario, abstraktion: Abstraktion, textur: Textur) -> Grund { + let mut g = Grund::mit(sz, abstraktion); + g.textur = Some(textur); + g + } + pub fn neu(abstraktion: Abstraktion) -> Grund { Grund::mit(Szenario::s1(), abstraktion) } @@ -232,7 +243,7 @@ impl Grund { let mut gewicht = [Vec::new(), Vec::new()]; gewicht[sz.eroeffner_spieler()] = eroeffner; gewicht[sz.verteidiger_spieler()] = verteidiger; - Grund { sz, baum: Einsatzbaum::neu(sz), abstraktion, alle, gewicht, flop_fest: None } + Grund { sz, baum: Einsatzbaum::neu(sz), abstraktion, alle, gewicht, flop_fest: None, textur: None } } fn hand_ziehen(&self, p: usize, tot: u64, rng: &mut Zufall) -> u64 { @@ -250,10 +261,14 @@ impl Grund { /// Class of `hand` on `strasse` with the street's board `board` (3, 4 or 5 cards); on the river /// `ehs` must be `river_ehs(board)`. pub fn klasse_von(&self, hand: u64, board: u64, strasse: usize, ehs: &[f32]) -> usize { - match strasse { + let plain = match strasse { 0 => self.abstraktion.flop.as_ref().map_or(0, |(s, t)| t[s.index(board, hand).unwrap() as usize] as usize), 1 => self.abstraktion.turn.as_ref().map_or(0, |(s, t)| t[s.index(board, hand).unwrap() as usize] as usize), - _ => river_class(ehs[combo_index(hand)], &self.abstraktion.river) as usize, + _ => return river_class(ehs[combo_index(hand)], &self.abstraktion.river) as usize, + }; + match &self.textur { + Some(t) => t.verfeinern(plain, board, strasse), + None => plain, } } } @@ -265,8 +280,8 @@ impl Spiel for Grund { &self.baum.baum } - fn klassen(&self, _: usize) -> usize { - CLASSES + fn klassen(&self, strasse: usize) -> usize { + self.textur.as_ref().and_then(|t| t.klassen(strasse)).unwrap_or(CLASSES) } fn ziehen(&self, rng: &mut Zufall) -> Deal { @@ -297,11 +312,7 @@ impl Spiel for Grund { let river = turn | board[4]; let ehs = river_ehs(river, &self.alle); let hand = [h0, h1]; - let klasse = hand.map(|h| { - let f = self.abstraktion.flop.as_ref().map_or(0, |(s, t)| t[s.index(flop, h).unwrap() as usize]); - let t = self.abstraktion.turn.as_ref().map_or(0, |(s, t)| t[s.index(turn, h).unwrap() as usize]); - [f, t, river_class(ehs[combo_index(h)], &self.abstraktion.river)] - }); + let klasse = hand.map(|h| [self.klasse_von(h, flop, 0, &ehs) as u16, self.klasse_von(h, turn, 1, &ehs) as u16, self.klasse_von(h, river, 2, &ehs) as u16]); let (a, b) = (fast7::score(river | h0), fast7::score(river | h1)); Deal { hand, board, klasse, sieger: (a > b) as i8 - (a < b) as i8 } } @@ -482,6 +493,38 @@ mod tests { lbr_faellt("co3"); } + /// The refined game: more information sets (texture groups on flop / turn), every class index + /// inside its street's space, values zero-sum, the plain game's entry count untouched, and a + /// short run still lowers LBR. + #[test] + fn the_textured_game_is_consistent() { + use crate::blueprint::lbr::lbr; + let plain = ohne_tabellen(Szenario::s1()); + let fein = Grund::mit_textur(Szenario::s1(), Abstraktion { flop: None, turn: None, river: river_cuts(50, 1) }, Textur::standard()); + let (tp, tf) = (Tabellen::neu(&plain), Tabellen::neu(&fein)); + eprintln!("S1 plain {} Eintraege, textured {} ({:.0} MB)", tp.eintraege(), tf.eintraege(), tf.eintraege() as f64 * 16.0 / 1e6); + assert!(tf.eintraege() > 2 * tp.eintraege()); + let mut rng = Zufall(Rng::seeded(4)); + for _ in 0..300 { + let d = fein.ziehen(&mut rng); + for p in 0..2 { + for st in 0..3 { + assert!((d.klasse[p][st] as usize) < fein.klassen(st), "street {st}"); + } + } + for e in 0..fein.baum.enden.len() { + let w = fein.wert(&d, e); + assert_eq!(w[0], -w[1]); + } + } + let mut tab = tf; + let roh = lbr(&fein, &tab, 1000, 2, 11); + rechnen(&fein, &mut tab, 10, 10_000, 2, 3); + let nachher = lbr(&fein, &tab, 1000, 2, 11); + eprintln!("textured LBR {:+.0} -> {:+.0}", roh.bb100, nachher.bb100); + assert!(nachher.bb100 < roh.bb100); + } + /// A short run on the real tree: deals are legal, values zero-sum, the tables move. #[test] fn s1_runs_and_stays_zero_sum() { diff --git a/src/blueprint/textur.rs b/src/blueprint/textur.rs new file mode 100644 index 00000000..36bad755 --- /dev/null +++ b/src/blueprint/textur.rs @@ -0,0 +1,251 @@ +//! Board-texture refinement of the card abstraction (plan E2, gate "Abstraktion verfeinern, einmal"; +//! finding `BEFUND-E2-plateau.md`). +//! +//! The plain abstraction gives a flop / turn hand one of 256 board-blind equity classes, so a +//! decision node has one action distribution per class for ALL boards. Here the information set of +//! a flop / turn decision is `(texture group of the public board, equity class)`: +//! +//! - the equity class is the old table class (strength ordered, 0..255), merged to `k` classes by +//! `class * k / 256` (neighbouring strengths), so memory and sparsity stay sane; +//! - the texture group is a dense id of a feature tuple of the board as a SET of cards (imperfect +//! recall, no deal order, so it is a pure function of the board mask and needs no table file): +//! - flop (3 cards): suit pattern (rainbow / two-tone / monotone), pairedness (none / pair / +//! trips), high card (A / K / Q-J / T-8 / lower), straight-draw wetness (number of five-rank +//! windows holding 3 board ranks: 0 / 1-2 / 3+); +//! - turn (4 cards): suit pattern (1111 / 211 / 22 / 31 / 4: flush draw, flush made, none), +//! pairedness (none / pair / two pair or trips / quads), most board ranks in one five-rank +//! window (a straight needs only a card / is open), high card (A / K / Q-T / lower). The turn +//! card's effect (flush-completing, pairing, straight-completing, overcard) is carried by the +//! difference of these features to the flop's, which the betting line (the node) already +//! separates by street and by the flop group's own strategy. +//! +//! The river stays as it was (EHS quantiles, 256 classes): a river hand's equity already is its +//! rank against the whole range on THIS board. +//! +//! A refined blueprint is a separate artefact: checkpoint `-t.ckpt` (the old `.ckpt` keeps +//! loading and running bit-identically). `Textur::standard()` is the version the ranges loader +//! expects; `Textur::neu` builds variants for experiments. + +use super::iso; + +/// One refinement: how coarse the groups are and how many equity classes each group keeps. +#[derive(Clone, Debug)] +pub struct Textur { + pub grob: bool, + /// Equity classes per group on the flop / turn (a divisor-friendly number <= 256). + pub k_flop: usize, + pub k_turn: usize, + /// Dense group id by feature code (`u16::MAX` = code never occurs). + flop_dicht: Vec, + turn_dicht: Vec, + pub flop_gruppen: usize, + pub turn_gruppen: usize, +} + +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] +} + +/// Rank bit mask (13 bits, ace high = bit 12) and per-rank card counts of a board. +fn raenge(board: u64) -> (u32, [u8; 13], [u32; 4]) { + let l = lanes(board); + let mut cnt = [0u8; 13]; + let mut union = 0u32; + for lane in l { + union |= lane; + for r in 0..13 { + cnt[r] += ((lane >> r) & 1) as u8; + } + } + (union, cnt, l) +} + +/// Distinct ranks inside each of the ten five-rank windows (A-5 wheel included): max and the number +/// of windows holding at least 3. +fn fenster(union: u32) -> (u32, u32) { + let mut best = 0; + let mut viele = 0; + for w in 0..10 { + let mask: u32 = if w == 9 { 0b1_0000_0000_1111 } else { 0b11111 << w }; + let c = (union & mask).count_ones(); + best = best.max(c); + if c >= 3 { + viele += 1; + } + } + (best, viele) +} + +fn hoch(union: u32, grob: bool) -> usize { + let r = 31 - union.leading_zeros(); // 0..12, ace = 12 + if grob { + return (r >= 11) as usize; // A or K + } + match r { + 12 => 0, + 11 => 1, + 10 | 9 => 2, + 6..=8 => 3, + _ => 4, + } +} + +/// Feature code of a flop board. +fn flop_code(board: u64, grob: bool) -> usize { + let (union, _, l) = raenge(board); + let n = union.count_ones() as usize; // 3, 2, 1 + let maxsuit = l.iter().map(|x| x.count_ones()).max().unwrap() as usize; // 1..3 + let (_, viele) = fenster(union); + let nass = if viele == 0 { 0 } else if viele <= 2 { 1 } else { 2 }; + let paar = 3 - n; // 0 none, 1 pair, 2 trips + if grob { + ((maxsuit - 1) * 2 + (paar > 0) as usize) * 3 + nass + } else { + (((maxsuit - 1) * 3 + paar) * 5 + hoch(union, false)) * 3 + nass + } +} + +/// Feature code of a turn board. +fn turn_code(board: u64, grob: bool) -> usize { + let (union, cnt, l) = raenge(board); + let mut s: Vec = l.iter().map(|x| x.count_ones()).collect(); + s.sort_unstable_by(|a, b| b.cmp(a)); + let muster = match (s[0], s[1]) { + (1, _) => 0, + (2, 1) => 1, + (2, _) => 2, + (3, _) => 3, + _ => 4, + }; + let n = union.count_ones(); // 4 none, 3 pair, 2 two pair / trips, 1 quads + let paar = match n { + 4 => 0, + 3 => 1, + 2 => 2, + _ => 3, + }; + debug_assert!(cnt.iter().map(|c| *c as u32).sum::() == 4); + let (fen, _) = fenster(union); + let strasse = (fen.max(2) - 2) as usize; // 0: <=2, 1: 3, 2: 4 + if grob { + (muster * 2 + (paar > 0) as usize) * 3 + strasse + } else { + (((muster * 4 + paar) * 3 + strasse) * 4) + hoch(union, false).min(3) + } +} + +impl Textur { + /// A refinement with `grob` groups and `k_flop` / `k_turn` equity classes per group. + pub fn neu(grob: bool, k_flop: usize, k_turn: usize) -> Textur { + assert!((1..=256).contains(&k_flop) && (1..=256).contains(&k_turn)); + let dicht = |boards: Vec, code: fn(u64, bool) -> usize| { + let mut codes: Vec = boards.iter().map(|b| code(*b, grob)).collect(); + codes.sort_unstable(); + codes.dedup(); + let mut v = vec![u16::MAX; codes.last().map_or(0, |m| m + 1)]; + for (i, c) in codes.iter().enumerate() { + v[*c] = i as u16; + } + (v, codes.len()) + }; + let (flop_dicht, flop_gruppen) = dicht(iso::subsets(3), flop_code); + let (turn_dicht, turn_gruppen) = dicht(iso::subsets(4), turn_code); + Textur { grob, k_flop, k_turn, flop_dicht, turn_dicht, flop_gruppen, turn_gruppen } + } + + /// The version the ranges loader and `grundtextur` use for `-t.ckpt`. + pub fn standard() -> Textur { + Textur::neu(false, 64, 64) + } + + /// Information-set classes of a street (flop 0, turn 1); the river is not refined. + pub fn klassen(&self, strasse: usize) -> Option { + match strasse { + 0 => Some(self.flop_gruppen * self.k_flop), + 1 => Some(self.turn_gruppen * self.k_turn), + _ => None, + } + } + + /// Texture group of a flop (3 cards) or turn (4 cards) board. + pub fn gruppe(&self, board: u64, strasse: usize) -> usize { + if strasse == 0 { + self.flop_dicht[flop_code(board, self.grob)] as usize + } else { + self.turn_dicht[turn_code(board, self.grob)] as usize + } + } + + /// Refined class of a hand whose plain equity class on this street is `klasse` (0..255). + pub fn verfeinern(&self, klasse: usize, board: u64, strasse: usize) -> usize { + let k = if strasse == 0 { self.k_flop } else { self.k_turn }; + self.gruppe(board, strasse) * k + klasse * k / 256 + } +} + +/// `true` if the checkpoint at `pfad` has exactly `eintraege` entries (header: rounds, length), so +/// it can be loaded into tables of that size without the length assertion firing. +pub fn ckpt_passt(pfad: &std::path::Path, eintraege: usize) -> bool { + use std::io::Read; + let Ok(mut f) = std::fs::File::open(pfad) else { return false }; + let mut kopf = [0u8; 16]; + if f.read_exact(&mut kopf).is_err() { + return false; + } + let n = u64::from_le_bytes(kopf[8..16].try_into().unwrap()) as usize; + n == eintraege && std::fs::metadata(pfad).map_or(false, |m| m.len() as usize == 16 + 16 * n) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::card::Card; + use crate::hand::fast7; + + fn m(t: &str) -> u64 { + fast7::mask(&Card::parse_list(t).unwrap()) + } + + #[test] + fn group_counts_are_sane() { + for grob in [false, true] { + let t = Textur::neu(grob, 64, 64); + eprintln!("grob={grob}: {} Flop-Gruppen, {} Turn-Gruppen", t.flop_gruppen, t.turn_gruppen); + assert!(t.flop_gruppen >= 10 && t.flop_gruppen <= 135); + assert!(t.turn_gruppen >= 15 && t.turn_gruppen <= 320); + } + } + + #[test] + fn suit_renaming_keeps_the_group_and_textures_differ() { + let t = Textur::standard(); + // Suit renaming. + assert_eq!(t.gruppe(m("Ah 7h 2c"), 0), t.gruppe(m("As 7s 2d"), 0)); + assert_eq!(t.gruppe(m("Ah 7h 2c 9d"), 1), t.gruppe(m("Ac 7c 2d 9h"), 1)); + // Genuinely different textures get different groups. + let g = |b: &str| t.gruppe(m(b), 0); + assert_ne!(g("Ks 7d 2c"), g("Ks 7s 2s"), "rainbow vs monotone"); + assert_ne!(g("Ks 7d 2c"), g("Ks Kd 2c"), "unpaired vs paired"); + assert_ne!(g("Ks 7d 2c"), g("9s 8d 7c"), "dry vs connected"); + assert_ne!(g("Ks 7d 2c"), g("7s 5d 2c"), "high card"); + let u = |b: &str| t.gruppe(m(b), 1); + assert_ne!(u("Ks 7d 2c 9h"), u("Ks 7s 2s 9s"), "no flush vs flush made"); + assert_ne!(u("Ks 7d 2c 9h"), u("Ks 7d 2c 7h"), "pairing card"); + assert_ne!(u("Ks 7d 2c 9h"), u("Ks 7d 8c 9h"), "straight possible"); + } + + #[test] + fn refined_classes_stay_inside_the_street_space() { + let t = Textur::standard(); + for (strasse, n) in [(0usize, 3usize), (1, 4)] { + let max = t.klassen(strasse).unwrap(); + for b in iso::subsets(n).iter().step_by(97) { + for c in [0usize, 1, 100, 255] { + assert!(t.verfeinern(c, *b, strasse) < max); + } + } + } + // Neighbouring strengths merge, order is kept. + assert!(t.verfeinern(255, m("Ks 7d 2c"), 0) > t.verfeinern(0, m("Ks 7d 2c"), 0)); + } +}