diff --git a/entscheiden/decide.py b/entscheiden/decide.py index 9cf6ffef..d317e6b1 100644 --- a/entscheiden/decide.py +++ b/entscheiden/decide.py @@ -30,7 +30,7 @@ QUELLE = os.environ.get("COINPOKER_KERN_QUELLE", os.path.join(BASE, "..")) # Hand in haende.jsonl, mit welchem Engine-Stand sie gespielt wurde (runner.py liest den Arm nach # diesem Import). SCHALTER_DATEI = os.path.join(BASE, "..", "betrieb", "kern_schalter.txt") -BEKANNTE_SCHALTER = ("MDF_UNREAD", "RAISE_DRAWS", "RAISE_PRIOR", "TURN_SPIEL", "GRUNDSTRATEGIE", "SOLVER_RIVER", "SOLVER_TURN", "SOLVER_FLOP", "SOLVER_RIVER3") +BEKANNTE_SCHALTER = ("MDF_UNREAD", "RAISE_DRAWS", "RAISE_PRIOR", "TURN_SPIEL", "GRUNDSTRATEGIE", "SOLVER_RIVER", "SOLVER_TURN", "SOLVER_FLOP", "SOLVER_RIVER3", "SOLVER_TURN3", "SOLVER_FLOP3") # Pfade gehoeren nicht in die Arm-Marke. OHNE_MARKE = ("GRUNDSTRATEGIE",) diff --git a/lesen/roentgen.py b/lesen/roentgen.py index 152c47a2..4ce27628 100644 --- a/lesen/roentgen.py +++ b/lesen/roentgen.py @@ -59,7 +59,7 @@ KLASSEN_NAME = { "heuristik": "Heuristik", "enthaltung": "Enthaltung", } # Gleiche Liste wie entscheiden/decide.py: nur Messschalter, keine beliebige Umgebung. -BEKANNTE_SCHALTER = ("MDF_UNREAD", "RAISE_DRAWS", "RAISE_PRIOR", "TURN_SPIEL", "GRUNDSTRATEGIE", "SOLVER_RIVER", "SOLVER_TURN", "SOLVER_FLOP", "SOLVER_RIVER3") +BEKANNTE_SCHALTER = ("MDF_UNREAD", "RAISE_DRAWS", "RAISE_PRIOR", "TURN_SPIEL", "GRUNDSTRATEGIE", "SOLVER_RIVER", "SOLVER_TURN", "SOLVER_FLOP", "SOLVER_RIVER3", "SOLVER_TURN3", "SOLVER_FLOP3") OHNE_MARKE = ("GRUNDSTRATEGIE",) IDLE_PRIORITY_CLASS = 0x00000040 KERN_KOPIE = "pokerbench-roentgen-nachspiel" + (".exe" if sys.platform == "win32" else "") diff --git a/lesen/solver_abdeckung.py b/lesen/solver_abdeckung.py index cc346e79..6dad10b9 100644 --- a/lesen/solver_abdeckung.py +++ b/lesen/solver_abdeckung.py @@ -71,19 +71,30 @@ def main(): ap.add_argument("--street", action="append", default=[]) ap.add_argument("--json", help="Ergebnis auch als JSON hierhin") ap.add_argument("--zeilen", help="je Anfrage eine JSON-Zeile (Street, Gegner, Klasse, ms, Grund) hierhin") + ap.add_argument("--sekunden", type=float, default=0, help="nach so vielen Sekunden aufhoeren (0 = alle)") + ap.add_argument("--mischen", type=int, help="Anfragen mit diesem Seed mischen (Stichprobe ueber alle Streets)") + ap.add_argument("--normal", action="store_true", help="Kern in normaler Prioritaet (wie live), sonst Idle") args = ap.parse_args() env = {k: v for k, v in os.environ.items() if k not in roentgen.BEKANNTE_SCHALTER} for kv in args.env: k, v = kv.split("=", 1) env[k] = v liste = anfragen(args.schatten, {s.upper() for s in args.street}) - extra = {"creationflags": IDLE} if sys.platform == "win32" else {} + if args.mischen is not None: + import random + random.Random(args.mischen).shuffle(liste) + extra = {"creationflags": IDLE} if sys.platform == "win32" and not args.normal else {} p = subprocess.Popen([args.kern], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True, encoding="utf-8", env=env, bufsize=1, **extra) zeilen = open(args.zeilen, "w", encoding="utf-8") if args.zeilen else None zaehl = collections.defaultdict(collections.Counter) zeiten = collections.defaultdict(list) + start = time.perf_counter() + gemacht = 0 for a in liste: + if args.sekunden and time.perf_counter() - start > args.sekunden: + break + gemacht += 1 t0 = time.perf_counter() p.stdin.write(json.dumps(a) + "\n") p.stdin.flush() @@ -107,7 +118,7 @@ def main(): if zeilen: zeilen.close() ergebnis = {} - print(f"{len(liste)} eindeutige Anfragen, Schalter {args.env}") + print(f"{gemacht} von {len(liste)} eindeutigen Anfragen, Schalter {args.env}") for (st, n), c in sorted(zaehl.items()): tot = sum(c.values()) s = c.get("solver", 0) @@ -118,7 +129,11 @@ def main(): ergebnis[f"{st}/{n}"] = {"anfragen": tot, "solver": s, "klassen": dict(c), "p50_ms": quantil(zs, .5), "p99_ms": quantil(zs, .99), "max_ms": max(zs or [0])} for (st, alle), zs in sorted((k, v) for k, v in zeiten.items() if k[1] == "alle"): - print(f"{st:6} alle Anfragen: p50 {quantil(zs, .5):.0f} p99 {quantil(zs, .99):.0f} max {max(zs):.0f} ms") + frist = {"TURN": 1250, "FLOP": 2000, "RIVER": 2000}.get(st) + ueber = sum(z > frist for z in zs) if frist else 0 + print(f"{st:6} alle Anfragen: n {len(zs)} p50 {quantil(zs, .5):.0f} p99 {quantil(zs, .99):.0f} max {max(zs):.0f} ms" + + (f", ueber Frist {frist} ms: {ueber}" if frist else "")) + ergebnis[f"{st}/alle"] = {"n": len(zs), "p50_ms": quantil(zs, .5), "p99_ms": quantil(zs, .99), "max_ms": max(zs), "ueber_frist": ueber} if args.json: with open(args.json, "w", encoding="utf-8") as f: json.dump(ergebnis, f, indent=1) diff --git a/messung_solver/latenz-spiel.sh b/messung_solver/latenz-spiel.sh new file mode 100644 index 00000000..81f4993f --- /dev/null +++ b/messung_solver/latenz-spiel.sh @@ -0,0 +1,16 @@ +#!/bin/bash +# Latenz unter Spielbedingungen: 5 Minuten, ein Kern in NORMALER Prioritaet (wie decide.py live), alle +# Solver-Schalter an, echte Uhr (kein SOLVER_ZEIT=fest), gemischte Stichprobe echter Schatten-Anfragen +# aller Postflop-Streets (HU und Multiway). Nur starten, wenn hoechstens 2 Mess-Threads laufen. +# Ausgabe: messung_solver/latenz-spiel.txt (p50/p99/max je Street und je Gegnerzahl, Anzahl ueber Frist). +# bash messung_solver/latenz-spiel.sh [Sekunden=300] +cd "$(dirname "$0")/.." +L=../engine-lecks-angreifen-de7b88 +K="$(pwd -W)/messung_solver/bin/pokerbench-solver-latenz.exe" +GS="GRUNDSTRATEGIE=D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\daten" +python3 lesen/solver_abdeckung.py --kern "$K" --schatten $L/betrieb/scratch --normal --mischen 7 --sekunden "${1:-300}" \ + --env MDF_UNREAD=0 --env TURN_SPIEL=grund --env OPEN_JAM=1 --env "$GS" \ + --env SOLVER_RIVER=1 --env SOLVER_TURN=1 --env SOLVER_FLOP=1 --env SOLVER_RIVER3=1 --env SOLVER_TURN3=1 --env SOLVER_FLOP3=1 \ + --street FLOP --street TURN --street RIVER \ + --json messung_solver/latenz-spiel.json --zeilen messung_solver/latenz-spiel-zeilen.jsonl > messung_solver/latenz-spiel.txt 2>&1 +cat messung_solver/latenz-spiel.txt diff --git a/src/bin/ab_zelle.rs b/src/bin/ab_zelle.rs index 521b50ef..dc738161 100644 --- a/src/bin/ab_zelle.rs +++ b/src/bin/ab_zelle.rs @@ -74,6 +74,9 @@ fn apply_arm() { rechner::engine::turn_game::set_turn_ueberall(rechner::engine::turn_game::turn_ueberall_from_env()); rechner::engine::flop_spieler::set_flop_spieler(rechner::engine::flop_spieler::from_env()); rechner::engine::river3_spieler::set_river3(rechner::engine::river3_spieler::from_env()); + let (turn3, flop3) = rechner::engine::multi3_spieler::from_env(); + rechner::engine::multi3_spieler::set_turn3(turn3); + rechner::engine::multi3_spieler::set_flop3(flop3); use rechner::engine::turn_game::{set_turn_player, TurnPlayer}; let turn_grund = std::env::var("TURN_SPIEL").as_deref() == Ok("grund"); set_turn_player(if turn_grund { TurnPlayer::Grund } else { TurnPlayer::Off }); diff --git a/src/bin/engine_lbr.rs b/src/bin/engine_lbr.rs index 8a31c855..99d143f5 100644 --- a/src/bin/engine_lbr.rs +++ b/src/bin/engine_lbr.rs @@ -39,6 +39,9 @@ fn main() { rechner::engine::turn_game::set_turn_ueberall(rechner::engine::turn_game::turn_ueberall_from_env()); rechner::engine::flop_spieler::set_flop_spieler(rechner::engine::flop_spieler::from_env()); rechner::engine::river3_spieler::set_river3(rechner::engine::river3_spieler::from_env()); + let (turn3, flop3) = rechner::engine::multi3_spieler::from_env(); + rechner::engine::multi3_spieler::set_turn3(turn3); + rechner::engine::multi3_spieler::set_flop3(flop3); if rechner::engine::river_spieler::river_spieler() == rechner::engine::river_spieler::RiverSpieler::An { assert!(rechner::blueprint::ranges::grundstrategie().is_some(), "SOLVER_RIVER=1 on LBR needs GRUNDSTRATEGIE (else it measures the model path)"); } diff --git a/src/cfr/mod.rs b/src/cfr/mod.rs index 5563f426..dbc45ee6 100644 --- a/src/cfr/mod.rs +++ b/src/cfr/mod.rs @@ -89,6 +89,7 @@ pub mod open3_game; pub mod open_game; pub mod payoffs; pub mod river3; +pub mod multi3; pub mod permille; pub mod plo5_bucket; pub mod push_fold3_game; diff --git a/src/cfr/multi3.rs b/src/cfr/multi3.rs new file mode 100644 index 00000000..f7091f0f --- /dev/null +++ b/src/cfr/multi3.rs @@ -0,0 +1,469 @@ +//! The 3-handed TURN and FLOP: Monte-Carlo CFR over real combos for three (or four) players across +//! more than one street, the multi-street sibling of `cfr::river3` (same solver, same approximations). +//! +//! - **Game:** one betting round per entry of `menus` (street 0 = the street being decided), between +//! them a deal node with `slots` children: slot `j` is the `j`-th card of an evenly strided list of the +//! undealt deck (a card abstraction, as stage B's river cards). Cards still missing at the showdown +//! (the flop game's river, any runout after an all-in) are dealt uniformly from the remaining deck +//! per iteration. Bets and raises are amounts of the street (`Act` as in `river_game`), stacks are +//! capped at the smallest live stack (no side pots). With a common cap, every player still in either +//! is all-in or has matched at a street's end, so an all-in ends the betting and runs the board out. +//! - **Solver:** external sampling with a vector traverser as in `river3`. Per iteration and traverser: +//! the others' hands are sampled jointly (card-disjoint), then the deal (slot cards disjoint from them, +//! the rest uniformly), the traverser's hands that collide with any sampled card count zero. The +//! traverser walks all its actions, the others one sampled action each, a deal node follows the +//! sampled slot. Showdown per traverser hand against the best active opponent on the full board. +//! Linear-weighted regrets; the average strategy is kept for street-0 nodes only (what is played). +//! +//! Named approximations: no equilibrium guarantee with three players; `slots` of the next street's +//! cards; one bet size and one raise on later streets; no side pots; Monte-Carlo noise. + +use crate::cfr::river3::{Hands3, Menu3}; +use crate::cfr::river_game::Act; +use crate::hand::fast7; + +#[derive(Clone, Debug)] +pub enum NodeM { + /// `player` acts on `street`; `acts[k]` (street amounts) leads to `kids[k]`. + Dec { player: usize, street: usize, acts: Vec, kids: Vec }, + /// The next street's card: child `j` = slot `j`. + Deal { kids: Vec }, + /// The hand ends: `c` = contributions over the game's streets, `active` = players still in. + Term { c: Vec, active: u32 }, +} + +#[derive(Clone, Debug)] +pub struct GameM { + pub nodes: Vec, + pub players: usize, + /// Pot before the game's first street. + pub pot: f64, + /// Common cap on a player's contribution over the game's streets. + pub cap: f64, + pub slots: usize, +} + +#[derive(Clone)] +struct State { + c: Vec, + active: u32, + pending: u32, + raises: u8, + to_act: usize, + street: usize, + /// Every player's contribution at the start of this street. + level: f64, +} + +impl GameM { + /// `menus[s]` = the betting of street `s`; `slots` = children of each deal node. + pub fn build(players: usize, pot: f64, cap: f64, menus: &[Menu3], slots: usize) -> GameM { + let mut g = GameM { nodes: Vec::new(), players, pot, cap, slots: slots.max(1) }; + let all = (1u32 << players) - 1; + let s = State { c: vec![0.0; players], active: all, pending: all, raises: 0, to_act: 0, street: 0, level: 0.0 }; + g.grow(s, menus); + g + } + + fn eps(&self) -> f64 { + 1e-9 * self.cap.max(1.0) + } + + fn next(&self, s: &State, from: usize) -> Option { + (1..=self.players).map(|k| (from + k) % self.players).find(|p| s.pending & (1 << p) != 0) + } + + fn grow(&mut self, s: State, menus: &[Menu3]) -> usize { + let eps = self.eps(); + if s.active.count_ones() == 1 { + self.nodes.push(NodeM::Term { c: s.c.clone(), active: s.active }); + return self.nodes.len() - 1; + } + if s.pending == 0 { + let top = s.c.iter().copied().fold(0.0, f64::max); + if s.street + 1 >= menus.len() || top >= self.cap - eps { + self.nodes.push(NodeM::Term { c: s.c.clone(), active: s.active }); + return self.nodes.len() - 1; + } + let id = self.nodes.len(); + self.nodes.push(NodeM::Deal { kids: Vec::new() }); + let first = (0..self.players).find(|p| s.active & (1 << p) != 0).unwrap_or(0); + let t = State { pending: s.active, raises: 0, to_act: first, street: s.street + 1, level: top, ..s.clone() }; + // Every slot has the same betting tree; they are separate nodes (the regrets differ per card). + let kids: Vec = (0..self.slots).map(|_| self.grow(t.clone(), menus)).collect(); + if let NodeM::Deal { kids: k } = &mut self.nodes[id] { + *k = kids; + } + return id; + } + let menu = &menus[s.street]; + let p = s.to_act; + let top = s.c.iter().copied().fold(0.0, f64::max); + let mut acts: Vec = Vec::new(); + let mut totals: Vec = Vec::new(); + if top > s.c[p] + eps { + acts.push(Act::Fold); + acts.push(Act::Call); + totals.extend([s.c[p], top]); + if s.raises < menu.max_raises && top < self.cap - eps { + let r = (s.level + (top - s.level) * menu.raise_mult).min(self.cap); + if r > top + eps && r < self.cap - eps { + acts.push(Act::Raise(r - s.level)); + totals.push(r); + } + if menu.allin { + acts.push(Act::Raise(self.cap - s.level)); + totals.push(self.cap); + } + } + } else { + acts.push(Act::Check); + totals.push(s.c[p]); + if self.cap > top + eps { + let pot_now = self.pot + s.c.iter().sum::(); + let mut sizes: Vec = menu.fracs.iter().map(|f| top + f * pot_now).filter(|b| *b < self.cap - eps).collect(); + if menu.allin { + sizes.push(self.cap); + } + sizes.sort_by(f64::total_cmp); + sizes.dedup_by(|a, b| (*a - *b).abs() < eps); + for b in sizes { + acts.push(Act::Bet(b - s.level)); + totals.push(b); + } + } + } + let id = self.nodes.len(); + self.nodes.push(NodeM::Dec { player: p, street: s.street, acts: acts.clone(), kids: Vec::new() }); + let mut kids = Vec::with_capacity(acts.len()); + for (a, total) in acts.iter().zip(&totals) { + let mut t = s.clone(); + t.pending &= !(1 << p); + match a { + Act::Fold => t.active &= !(1 << p), + Act::Call | Act::Check => t.c[p] = top.max(t.c[p]), + Act::Bet(_) | Act::Raise(_) => { + t.c[p] = *total; + t.raises += u8::from(matches!(a, Act::Raise(_))); + t.pending = (0..self.players).filter(|q| *q != p && t.active & (1 << q) != 0 && t.c[*q] < self.cap - eps).fold(0, |m, q| m | (1 << q)); + } + } + if t.c[p] >= self.cap - eps { + t.pending &= !(1 << p); + } + if let Some(n) = self.next(&t, p) { + t.to_act = n; + } + kids.push(self.grow(t, menus)); + } + if let NodeM::Dec { kids: k, .. } = &mut self.nodes[id] { + *k = kids; + } + id + } + + /// Follow an observed line of street 0 from the root (as `river3::Game3::follow`). + pub fn follow(&self, line: &[(usize, Act)]) -> Option { + let mut at = 0; + for (who, a) in line { + let NodeM::Dec { player, acts, kids, .. } = &self.nodes[at] else { return None }; + if player != who { + return None; + } + let k = match a { + Act::Bet(x) | Act::Raise(x) => acts + .iter() + .enumerate() + .filter_map(|(k, t)| match t { + Act::Bet(y) | Act::Raise(y) => Some((k, (y - x).abs())), + _ => None, + }) + .min_by(|p, q| p.1.total_cmp(&q.1))? + .0, + _ => acts.iter().position(|t| t == a)?, + }; + at = kids[k]; + } + Some(at) + } +} + +struct Xs(u64); + +impl Xs { + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + fn unit(&mut self) -> f64 { + (self.next() >> 11) as f64 / (1u64 << 53) as f64 + } + fn below(&mut self, n: usize) -> usize { + ((self.unit() * n as f64) as usize).min(n.saturating_sub(1)) + } +} + +/// The 52 card bits. +fn deck() -> Vec { + (0..4).flat_map(|s| (0..13).map(move |r| 1u64 << (16 * s + r))).collect() +} + +pub struct SolverM { + pub game: GameM, + hands: Vec, + board: u64, + /// The slot cards of the next street (evenly strided over the undealt deck). + slot_cards: Vec, + /// Cards dealt per iteration beyond the slot card (uniformly from the rest). + extra: usize, + cum: Vec>, + regret: Vec>, + avg: Vec>, + rng: Xs, + t: u64, +} + +/// One iteration's sampled cards. +struct Draw { + picked: Vec, + slot: usize, + /// Score of each player's sampled hand (the traverser's entry unused). + opp: Vec, + /// The traverser's score per hand on the full board (0 where not live). + mine: Vec, +} + +impl SolverM { + /// `hands[p]` per player in acting order; `board` = the cards out now (3 or 4). + pub fn new(game: GameM, hands: Vec, board: u64, seed: u64) -> SolverM { + assert_eq!(hands.len(), game.players); + let undealt: Vec = deck().into_iter().filter(|c| c & board == 0).collect(); + let k = game.slots.min(undealt.len()); + let step = undealt.len() as f64 / k as f64; + let slot_cards: Vec = (0..k).map(|j| undealt[(j as f64 * step) as usize]).collect(); + // The next street's card comes from the slots, any further card uniformly. + let extra = (5 - board.count_ones() as usize).saturating_sub(1); + let cum = hands + .iter() + .map(|h| { + let mut acc = 0.0; + h.weights.iter().map(|w| { + acc += w.max(0.0); + acc + }).collect() + }) + .collect(); + let regret = game.nodes.iter().map(|n| match n { + NodeM::Dec { player, acts, .. } => vec![0.0; hands[*player].masks.len() * acts.len()], + _ => Vec::new(), + }).collect(); + let avg = game.nodes.iter().map(|n| match n { + NodeM::Dec { player, street: 0, acts, .. } => vec![0.0; hands[*player].masks.len() * acts.len()], + _ => Vec::new(), + }).collect(); + SolverM { game, hands, board, slot_cards, extra, cum, regret, avg, rng: Xs(seed | 1), t: 0 } + } + + pub fn masks(&self, p: usize) -> &[u64] { + &self.hands[p].masks + } + + fn sample(&mut self, p: usize) -> usize { + let c = &self.cum[p]; + let x = self.rng.unit() * c.last().copied().unwrap_or(0.0); + c.partition_point(|v| *v <= x).min(c.len() - 1) + } + + /// Sample the others' hands and the runout for traverser `i`; `None` if no disjoint draw is found. + fn draw(&mut self, i: usize) -> Option { + let n = self.game.players; + let mut picked = vec![usize::MAX; n]; + let mut used = 0u64; + let mut ok = false; + for _ in 0..64 { + used = 0; + ok = true; + for p in (0..n).filter(|p| *p != i) { + let h = self.sample(p); + let m = self.hands[p].masks[h]; + if m & used != 0 { + ok = false; + break; + } + used |= m; + picked[p] = h; + } + if ok { + break; + } + } + if !ok { + return None; + } + let missing = 5 - self.board.count_ones() as usize; + let mut run = 0u64; + let mut slot = 0; + if missing > 0 { + let free: Vec = (0..self.slot_cards.len()).filter(|j| self.slot_cards[*j] & used == 0).collect(); + if free.is_empty() { + return None; + } + slot = free[self.rng.below(free.len())]; + run |= self.slot_cards[slot]; + } + for _ in 0..self.extra { + let rest: Vec = deck().into_iter().filter(|c| c & (self.board | used | run) == 0).collect(); + run |= rest[self.rng.below(rest.len())]; + } + let full = self.board | run; + let opp = (0..n).map(|p| if p == i { 0 } else { fast7::score(self.hands[p].masks[picked[p]] | full) }).collect(); + let mine = self.hands[i].masks.iter().map(|m| if m & (used | run) == 0 { fast7::score(m | full) + 1 } else { 0 }).collect(); + Some(Draw { picked, slot, opp, mine }) + } + + /// One iteration: every player once as the traverser. + pub fn iterate(&mut self) { + self.t += 1; + for i in 0..self.game.players { + let Some(d) = self.draw(i) else { continue }; + let live: Vec = d.mine.iter().map(|s| if *s > 0 { 1.0 } else { 0.0 }).collect(); + let reach = live.clone(); + self.walk(0, i, &d, &live, &reach); + } + } + + pub fn run(&mut self, iterations: u32) { + for _ in 0..iterations { + self.iterate(); + } + } + + fn current(regret: &[f64], a: usize, out: &mut [f64]) { + let pos: f64 = regret.iter().map(|r| r.max(0.0)).sum(); + if pos > 0.0 { + for k in 0..a { + out[k] = regret[k].max(0.0) / pos; + } + } else { + out.iter_mut().for_each(|x| *x = 1.0 / a as f64); + } + } + + fn walk(&mut self, node: usize, i: usize, d: &Draw, live: &[f64], reach: &[f64]) -> Vec { + let n = live.len(); + match &self.game.nodes[node] { + NodeM::Term { c, active } => { + let pot = self.game.pot + c.iter().sum::(); + let mine = c[i]; + if active & (1 << i) == 0 { + return live.iter().map(|l| -mine * l).collect(); + } + if active.count_ones() == 1 { + return live.iter().map(|l| (pot - mine) * l).collect(); + } + let mut best = 0u32; + let mut ties = 0usize; + for p in (0..self.game.players).filter(|p| *p != i && active & (1 << p) != 0) { + let s = d.opp[p]; + if s > best { + best = s; + ties = 1; + } else if s == best { + ties += 1; + } + } + (0..n) + .map(|h| { + if live[h] == 0.0 { + return 0.0; + } + let s = d.mine[h] - 1; + let share = if s > best { + pot + } else if s == best { + pot / (ties + 1) as f64 + } else { + 0.0 + }; + share - mine + }) + .collect() + } + NodeM::Deal { kids } => { + let k = kids[d.slot.min(kids.len() - 1)]; + self.walk(k, i, d, live, reach) + } + NodeM::Dec { player, street, acts, kids } => { + let (p, a, kids, keep_avg) = (*player, acts.len(), kids.clone(), *street == 0); + if p == i { + let mut sigma = vec![0.0; n * a]; + for h in 0..n { + Self::current(&self.regret[node][h * a..(h + 1) * a], a, &mut sigma[h * a..(h + 1) * a]); + } + let mut vals: Vec> = Vec::with_capacity(a); + for k in 0..a { + let r: Vec = (0..n).map(|h| reach[h] * sigma[h * a + k]).collect(); + vals.push(self.walk(kids[k], i, d, live, &r)); + } + let t = self.t as f64; + let mut out = vec![0.0; n]; + for h in 0..n { + if live[h] == 0.0 { + continue; + } + let v: f64 = (0..a).map(|k| sigma[h * a + k] * vals[k][h]).sum(); + out[h] = v; + for k in 0..a { + self.regret[node][h * a + k] += t * (vals[k][h] - v); + if keep_avg { + self.avg[node][h * a + k] += t * reach[h] * sigma[h * a + k]; + } + } + } + out + } else { + let h = d.picked[p]; + let mut sigma = vec![0.0; a]; + Self::current(&self.regret[node][h * a..(h + 1) * a], a, &mut sigma); + let x = self.rng.unit(); + let mut acc = 0.0; + let mut k = a - 1; + for (j, s) in sigma.iter().enumerate() { + acc += s; + if x < acc { + k = j; + break; + } + } + self.walk(kids[k], i, d, live, reach) + } + } + } + } + + /// The average strategy of player `p`'s hand `h` at a street-0 `node` (uniform where never reached). + pub fn row(&self, node: usize, h: usize) -> Vec { + let NodeM::Dec { acts, .. } = &self.game.nodes[node] else { return Vec::new() }; + let a = acts.len(); + let s = &self.avg[node]; + if s.len() < (h + 1) * a { + return vec![1.0 / a as f64; a]; + } + let s = &s[h * a..(h + 1) * a]; + let tot: f64 = s.iter().sum(); + if tot > 0.0 { + s.iter().map(|x| x / tot).collect() + } else { + vec![1.0 / a as f64; a] + } + } + + pub fn iterations(&self) -> u64 { + self.t + } +} + +#[cfg(test)] +mod tests; diff --git a/src/cfr/multi3/tests.rs b/src/cfr/multi3/tests.rs new file mode 100644 index 00000000..572aba28 --- /dev/null +++ b/src/cfr/multi3/tests.rs @@ -0,0 +1,121 @@ +use super::*; +use crate::card::Card; +use crate::cfr::river3::Menu3; +use crate::hand::fast7; + +fn later() -> Menu3 { + Menu3 { fracs: vec![0.75], raise_mult: 3.0, max_raises: 1, allin: true } +} + +fn all_hands(board: u64) -> Hands3 { + let deck: Vec = crate::card::deck::full().into_iter().map(fast7::bit).filter(|b| b & board == 0).collect(); + let mut masks = Vec::new(); + for a in 0..deck.len() { + for b in (a + 1)..deck.len() { + masks.push(deck[a] | deck[b]); + } + } + let weights = vec![1.0; masks.len()]; + Hands3 { masks, weights } +} + +/// Every `k`-th combo (a smaller range of the same shape) plus the named hands. +fn some_hands(board: u64, k: usize, named: &[&str]) -> Hands3 { + let all = all_hands(board); + let mut masks: Vec = all.masks.iter().step_by(k).copied().collect(); + for n in named { + let m = fast7::mask(&Card::parse_list(n).unwrap()); + if !masks.contains(&m) { + masks.push(m); + } + } + let weights = vec![1.0; masks.len()]; + Hands3 { masks, weights } +} + +fn idx(h: &Hands3, cards: &str) -> usize { + let m = fast7::mask(&Card::parse_list(cards).unwrap()); + h.masks.iter().position(|x| *x == m).unwrap() +} + +fn prob(row: &[f64], acts: &[Act], f: impl Fn(&Act) -> bool) -> f64 { + row.iter().zip(acts).filter(|(_, a)| f(a)).map(|(p, _)| p).sum() +} + +#[test] +fn the_turn_tree_deals_a_river_and_closes_every_line() { + let g = GameM::build(3, 10.0, 100.0, &[Menu3::standard(), later()], 6); + let deals = g.nodes.iter().filter(|n| matches!(n, NodeM::Deal { .. })).count(); + assert!(deals > 3 && g.nodes.len() < 200_000, "{} nodes, {deals} deals", g.nodes.len()); + // Check, check, check deals the river with all three in; the river opens with player 0. + let at = g.follow(&[(0, Act::Check), (1, Act::Check), (2, Act::Check)]).unwrap(); + let NodeM::Deal { kids } = &g.nodes[at] else { panic!("{:?}", g.nodes[at]) }; + assert_eq!(kids.len(), 6); + assert!(matches!(&g.nodes[kids[0]], NodeM::Dec { player: 0, street: 1, .. })); + // An all-in and a call end the betting: a terminal, no deal. + let at = g.follow(&[(0, Act::Bet(100.0)), (1, Act::Call), (2, Act::Fold)]).unwrap(); + assert!(matches!(&g.nodes[at], NodeM::Term { active: 3, .. })); + // Later-street amounts are amounts of that street: after 3.3 and two calls (pot 19.9) the river bet is 0.75 x 19.9. + let at = g.follow(&[(0, Act::Bet(3.3)), (1, Act::Call), (2, Act::Call)]).unwrap(); + let NodeM::Deal { kids } = &g.nodes[at] else { panic!() }; + let NodeM::Dec { acts, .. } = &g.nodes[kids[0]] else { panic!() }; + assert!(acts.iter().any(|a| matches!(a, Act::Bet(x) if (x - 0.75 * 19.9).abs() < 1e-6)), "{acts:?}"); +} + +/// Turn, three-handed, facing a bet and a call: top set continues, air with no draw folds. +#[test] +fn turn_three_handed_set_continues_and_air_folds() { + let b = fast7::mask(&Card::parse_list("Ah 7d 2c Ks").unwrap()); + let h = some_hands(b, 4, &["As Ad", "6s 5d", "9c 8h"]); + let g = GameM::build(3, 10.0, 100.0, &[Menu3::standard(), later()], 6); + let at = g.follow(&[(0, Act::Bet(7.5)), (1, Act::Call)]).unwrap(); + let mut s = SolverM::new(g, vec![h.clone(), h.clone(), h.clone()], b, 11); + s.run(6_000); + let NodeM::Dec { acts, .. } = s.game.nodes[at].clone() else { panic!() }; + let set = s.row(at, idx(&h, "As Ad")); + assert!(prob(&set, &acts, |a| *a == Act::Fold) < 0.05, "{set:?} {acts:?}"); + let air = s.row(at, idx(&h, "9c 8h")); + assert!(prob(&air, &acts, |a| *a == Act::Fold) > 0.7, "{air:?} {acts:?}"); +} + +/// Flop, three-handed: the game deals turn slots, the river uniformly, and the nuts never fold. +#[test] +fn flop_three_handed_runs_and_the_nuts_continue() { + let b = fast7::mask(&Card::parse_list("Ah 7d 2c").unwrap()); + let h = some_hands(b, 6, &["As Ad", "9c 8h"]); + let g = GameM::build(3, 10.0, 100.0, &[Menu3::standard(), later()], 5); + let at = g.follow(&[(0, Act::Bet(7.5)), (1, Act::Call)]).unwrap(); + let mut s = SolverM::new(g, vec![h.clone(), h.clone(), h.clone()], b, 5); + s.run(4_000); + let NodeM::Dec { acts, .. } = s.game.nodes[at].clone() else { panic!() }; + let set = s.row(at, idx(&h, "As Ad")); + assert!(prob(&set, &acts, |a| *a == Act::Fold) < 0.05, "{set:?} {acts:?}"); +} + +#[test] +fn deterministic() { + let b = fast7::mask(&Card::parse_list("Ah 7d 2c Ks").unwrap()); + let h = some_hands(b, 9, &[]); + let run = || { + let g = GameM::build(3, 10.0, 100.0, &[Menu3::standard(), later()], 4); + let mut s = SolverM::new(g, vec![h.clone(), h.clone(), h.clone()], b, 3); + s.run(300); + s.row(0, 5) + }; + assert_eq!(run(), run()); +} + +#[test] +#[ignore] +fn timing() { + for (board, slots, label) in [("Ah 7d 2c Ks", 8, "turn"), ("Ah 7d 2c", 6, "flop")] { + let b = fast7::mask(&Card::parse_list(board).unwrap()); + let h = some_hands(b, 6, &[]); + let g = GameM::build(3, 10.0, 100.0, &[Menu3::standard(), later()], slots); + let nodes = g.nodes.len(); + let mut s = SolverM::new(g, vec![h.clone(), h.clone(), h.clone()], b, 3); + let t = std::time::Instant::now(); + s.run(2_000); + println!("{label}: {nodes} nodes, {} hands, 2000 iters {:.0} ms", h.masks.len(), t.elapsed().as_secs_f64() * 1e3); + } +} diff --git a/src/engine/decide.rs b/src/engine/decide.rs index 43479119..f0687702 100644 --- a/src/engine/decide.rs +++ b/src/engine/decide.rs @@ -120,6 +120,11 @@ fn postflop(spot: &Spot, thresholds: &Thresholds, raw: &Spot, premium: f64) -> D if let Some(d) = super::turn_game::turn_solver_decision(raw) { return d.with_equity(equity.share); } + // Multiway turn and flop (off by default, SOLVER_TURN3 / SOLVER_FLOP3): 3- and 4-handed + // spots decided by Monte-Carlo CFR over the remaining streets (`engine::multi3_spieler`). + if let Some(d) = super::multi3_spieler::multi3_decision(raw) { + return d.with_equity(equity.share); + } // Stage C, solver everywhere (off by default, SOLVER_FLOP): every heads-up flop. if let Some(d) = super::flop_spieler::flop_spieler_decision(raw) { return d.with_equity(equity.share); diff --git a/src/engine/mod.rs b/src/engine/mod.rs index 3c61469f..ee010a6f 100644 --- a/src/engine/mod.rs +++ b/src/engine/mod.rs @@ -19,6 +19,7 @@ pub mod read_gate; pub mod range_combos; pub mod range_filter; pub mod read_label; +pub mod multi3_spieler; pub mod river3_spieler; pub mod river_spieler; pub mod river_subgame; diff --git a/src/engine/multi3_spieler.rs b/src/engine/multi3_spieler.rs new file mode 100644 index 00000000..bd9a59b7 --- /dev/null +++ b/src/engine/multi3_spieler.rs @@ -0,0 +1,186 @@ +//! "Solver everywhere", the MULTIWAY turn and flop: 3- and 4-handed spots decided by Monte-Carlo CFR +//! over real combos across the remaining streets (`cfr::multi3`), the sibling of the multiway river +//! (`engine::river3_spieler`, same ranges, line replay and approximations). Switches `SOLVER_TURN3` +//! and `SOLVER_FLOP3` (default off: no decision, the engine is bit-identical). +//! +//! - **Turn game:** turn betting (33/75 % pot, all-in, one raise ×3), `TURN_SLOTS` river cards, river +//! betting (75 % pot, all-in, one raise), showdown. +//! - **Flop game:** flop betting (as the turn above), `FLOP_SLOTS` turn cards, turn betting (75 %, +//! all-in, one raise), the river dealt and checked down (as stage C, no river betting). +//! - **Ranges** per player from the range model of the line (gated reads), at most `MAX_COMBOS`. +//! - **Time:** `frist::TURN_MS` / `frist::FLOP_MS` per decision, own caps `TURN_BUDGET_MS` / +//! `FLOP_BUDGET_MS`; under `MIN_ITERS` iterations the heuristic decides. +//! +//! Named approximations: no equilibrium guarantee with three players; stacks capped at the smallest +//! live stack (no side pots); the next street's card from a few slots; one size on later streets. + +use crate::cfr::multi3::{GameM, NodeM, SolverM}; +use crate::cfr::river3::Menu3; +use crate::cfr::river_game::Act; +use crate::engine::river3_spieler::{acting_order, model_hands, street_line3}; +use crate::engine::river_subgame::legal_choice; +use crate::game::{Decision, Spot, Street, Villain}; +use crate::hand::fast7; +use crate::rng::Rng; +use std::sync::atomic::{AtomicBool, Ordering}; + +static TURN3: AtomicBool = AtomicBool::new(false); +static FLOP3: AtomicBool = AtomicBool::new(false); + +pub fn set_turn3(on: bool) { + TURN3.store(on, Ordering::Relaxed); +} + +pub fn set_flop3(on: bool) { + FLOP3.store(on, Ordering::Relaxed); +} + +pub fn turn3() -> bool { + TURN3.load(Ordering::Relaxed) +} + +pub fn flop3() -> bool { + FLOP3.load(Ordering::Relaxed) +} + +fn on(key: &str) -> bool { + matches!(std::env::var(key).as_deref(), Ok("1") | Ok("an")) +} + +/// `SOLVER_TURN3=1`, `SOLVER_FLOP3=1`. +pub fn from_env() -> (bool, bool) { + (on("SOLVER_TURN3"), on("SOLVER_FLOP3")) +} + +/// Iteration cap (and the count under `SOLVER_ZEIT=fest`). +pub const ITERS: u32 = 12_000; +/// Fewest iterations a decision may rest on. +pub const MIN_ITERS: u32 = 1_000; +/// Own caps of one solve, inside the street's decision total. +pub const TURN_BUDGET_MS: f64 = 1050.0; +pub const FLOP_BUDGET_MS: f64 = 1700.0; +/// Most combos per player. +pub const MAX_COMBOS: usize = 200; +pub const TURN_SLOTS: usize = 8; +pub const FLOP_SLOTS: usize = 6; + +fn later() -> Menu3 { + Menu3 { fracs: vec![0.75], raise_mult: 3.0, max_raises: 1, allin: true } +} + +pub struct SolvedM { + pub row: Vec, + pub acts: Vec, + pub iterations: u64, + pub millis: f64, + pub players: usize, + pub nodes: usize, + pub combos: Vec, +} + +/// Solve this 3- or 4-handed turn or flop (gated spot) and return hero's average strategy at its node. +pub fn solve_multi3(spot: &Spot) -> Option { + let villains = spot.live_villains().count(); + let (cards, cap_ms, total, slots) = match spot.street { + Street::Turn => (4, TURN_BUDGET_MS, crate::engine::frist::TURN_MS, TURN_SLOTS), + Street::Flop => (3, FLOP_BUDGET_MS, crate::engine::frist::FLOP_MS, FLOP_SLOTS), + _ => return None, + }; + if spot.board.len() != cards || spot.hero_cards.len() != 2 || !(2..=3).contains(&villains) { + return None; + } + let budget = crate::engine::frist::budget_ms(cap_ms, total); + if budget <= 0.0 { + return None; + } + let started = std::time::Instant::now(); + let order = acting_order(spot)?; + let (line, c) = street_line3(spot, &order, spot.street)?; + let me = order.iter().position(|s| *s == spot.hero_seat)?; + let stack_of = |seat: u8| -> f64 { + if seat == spot.hero_seat { + spot.hero_stack + } else { + spot.live_villains().find(|v| v.seat == seat).map_or(0.0, |v| v.stack) + } + }; + let cap = order.iter().enumerate().map(|(i, s)| stack_of(*s) + c[i]).fold(f64::INFINITY, f64::min); + let pot = spot.pot - c.iter().sum::(); + if pot <= 0.0 || !cap.is_finite() || cap <= c.iter().copied().fold(0.0, f64::max) { + return None; + } + let board = fast7::mask(&spot.board); + let hero_mask = fast7::mask(&spot.hero_cards); + let mut hands = Vec::with_capacity(order.len()); + for seat in &order { + let h = if *seat == spot.hero_seat { + model_hands(spot, &Villain { seat: *seat, stack: spot.hero_stack, folded: false, profile: None }, board, Some(hero_mask), MAX_COMBOS)? + } else { + let v = spot.live_villains().find(|v| v.seat == *seat)?; + model_hands(spot, v, board, None, MAX_COMBOS)? + }; + hands.push(h); + } + let game = GameM::build(order.len(), pot, cap, &[Menu3::standard(), later()], slots); + let at = game.follow(&line)?; + let NodeM::Dec { player, acts, .. } = &game.nodes[at] else { return None }; + if *player != me { + return None; + } + let acts = acts.clone(); + let nodes = game.nodes.len(); + let combos: Vec = hands.iter().map(|h| h.masks.len()).collect(); + let hero_index = hands[me].masks.iter().position(|m| *m == hero_mask)?; + let mut solver = SolverM::new(game, hands, board, spot.seed ^ 0x9e37_79b9_7f4a_7c15); + let mut done = 0u32; + while done < ITERS { + solver.iterate(); + done += 1; + if done % 50 == 0 && started.elapsed().as_secs_f64() * 1e3 > budget { + break; + } + } + if done < MIN_ITERS { + return None; + } + let row = solver.row(at, hero_index); + Some(SolvedM { row, acts, iterations: solver.iterations(), millis: started.elapsed().as_secs_f64() * 1e3, players: order.len(), nodes, combos }) +} + +/// The live multiway turn/flop decision, or `None` and the heuristic keeps it. +pub fn multi3_decision(raw: &Spot) -> Option { + let on = match raw.street { + Street::Turn => turn3(), + Street::Flop => flop3(), + _ => false, + }; + if !on || raw.hero_cards.len() != 2 || raw.live_villains().count() < 2 { + return None; + } + let gated = crate::engine::read_gate::gate_reads(raw); + let s = solve_multi3(&gated)?; + let (draw, _) = Rng::seeded(gated.seed).unit(); + let mut acc = 0.0; + let mut pick = s.acts.len() - 1; + for (k, p) in s.row.iter().enumerate() { + acc += p; + if draw < acc { + pick = k; + break; + } + } + let act = s.acts[pick]; + let p = s.row[pick]; + let street = if gated.street == Street::Turn { "turn3" } else { "flop3" }; + Some(Decision::new( + legal_choice(&gated, act), + p.clamp(0.0, 1.0), + format!( + "solver {street} ({} players): {:?} combos, {} nodes, {} iters, {act:?} p {p:.2}, {:.0} ms", + s.players, s.combos, s.nodes, s.iterations, s.millis + ), + )) +} + +#[cfg(test)] +mod tests; diff --git a/src/engine/multi3_spieler/tests.rs b/src/engine/multi3_spieler/tests.rs new file mode 100644 index 00000000..a1e079e0 --- /dev/null +++ b/src/engine/multi3_spieler/tests.rs @@ -0,0 +1,108 @@ +use super::*; +use crate::card::Card; +use crate::game::{ActionKind, ActionRecord, Choice, SeenAction, Spot, Street, Villain}; +use crate::variant::Variant; +use std::sync::Mutex; + +static LOCK: Mutex<()> = Mutex::new(()); + +fn rec(street: Street, seat: u8, action: SeenAction, amount: Option) -> ActionRecord { + ActionRecord { street, seat, action, amount } +} + +/// Six-max, three-way: button (hero, seat 4) opens 2.5, SB (5) and BB (0) call (pot 7.5). On the flop +/// SB checks, BB bets 3.75, hero to act. On the turn (flop bet called by all, pot 18.75) SB checks, BB +/// bets 6, hero to act. +fn three_way(street: Street, hero: &str) -> Spot { + use SeenAction::*; + use Street::*; + let mut history = vec![ + rec(Preflop, 5, PostSmallBlind, Some(0.5)), + rec(Preflop, 0, PostBigBlind, Some(1.0)), + rec(Preflop, 1, Fold, None), + rec(Preflop, 2, Fold, None), + rec(Preflop, 3, Fold, None), + rec(Preflop, 4, Raise, Some(2.5)), + rec(Preflop, 5, Call, Some(2.5)), + rec(Preflop, 0, Call, Some(2.5)), + rec(Flop, 5, Check, None), + rec(Flop, 0, Bet, Some(3.75)), + ]; + let (board, pot, to_call, stack) = if street == Flop { + ("Ah 7d 2c", 11.25, 3.75, 97.5) + } else { + history.extend([rec(Flop, 4, Call, Some(3.75)), rec(Flop, 5, Call, Some(3.75)), rec(Turn, 5, Check, None), rec(Turn, 0, Bet, Some(6.0))]); + ("Ah 7d 2c Ks", 24.75, 6.0, 93.75) + }; + Spot { + variant: Variant::Nlhe, + big_blind: 1.0, + seats: 6, + hero_seat: 4, + button_seat: None, + hero_cards: Card::parse_list(hero).unwrap(), + board: Card::parse_list(board).unwrap(), + street, + pot, + to_call, + hero_stack: stack, + min_raise_to: Some(2.0 * to_call), + max_raise_to: Some(stack), + legal: vec![ActionKind::Fold, ActionKind::Call, ActionKind::Raise], + allowed_sizes: None, + villains: vec![ + Villain { seat: 5, stack, folded: false, profile: None }, + Villain { seat: 0, stack: stack - to_call, folded: false, profile: None }, + ], + seed: 9, + history, + } +} + +fn fold(s: &SolvedM) -> f64 { + s.row.iter().zip(&s.acts).filter(|(_, a)| **a == Act::Fold).map(|(p, _)| p).sum() +} + +#[test] +fn off_decides_nothing_and_heads_up_is_not_in_the_slice() { + let _g = LOCK.lock().unwrap(); + set_turn3(false); + set_flop3(false); + assert!(multi3_decision(&three_way(Street::Turn, "As Ad")).is_none()); + assert!(multi3_decision(&three_way(Street::Flop, "As Ad")).is_none()); + set_turn3(true); + set_flop3(true); + let mut hu = three_way(Street::Turn, "As Ad"); + hu.villains.pop(); + assert!(multi3_decision(&hu).is_none()); + set_turn3(false); + set_flop3(false); +} + +#[test] +fn on_decides_three_way_turns_and_flops_legally_and_in_time() { + let _g = LOCK.lock().unwrap(); + set_turn3(true); + set_flop3(true); + for (street, limit, tag) in [(Street::Turn, 1.25, "solver turn3 (3 players)"), (Street::Flop, 2.0, "solver flop3 (3 players)")] { + for hero in ["As Ad", "6s 5d", "Kc Qc"] { + let t = std::time::Instant::now(); + let d = multi3_decision(&three_way(street, hero)).expect("3-way spot is in the slice"); + assert!(t.elapsed().as_secs_f64() < limit, "{street:?} {:?}", t.elapsed()); + assert!(d.reason.contains(tag), "{}", d.reason); + assert!(matches!(d.choice, Choice::Fold | Choice::Call | Choice::Raise { .. }), "{:?}", d.choice); + } + } + set_turn3(false); + set_flop3(false); +} + +#[test] +fn top_set_continues_and_air_folds_three_way() { + for street in [Street::Turn, Street::Flop] { + let s = solve_multi3(&three_way(street, "As Ad")).unwrap(); + assert!(fold(&s) < 0.05, "{street:?} {:?} {:?}", s.row, s.acts); + } + let s = solve_multi3(&three_way(Street::Turn, "6s 5d")).unwrap(); + assert!(fold(&s) > 0.6, "{:?} {:?}", s.row, s.acts); +} diff --git a/src/engine/river3_spieler.rs b/src/engine/river3_spieler.rs index 35e31f98..e64c9887 100644 --- a/src/engine/river3_spieler.rs +++ b/src/engine/river3_spieler.rs @@ -63,13 +63,13 @@ pub fn acting_order(spot: &Spot) -> Option> { Some(seats) } -/// The observed river line among the live players: `(index in order, act)`, the street -/// contributions per player, and whether it is consistent with hero's price. -fn river_line(spot: &Spot, order: &[u8]) -> Option<(Vec<(usize, Act)>, Vec)> { +/// The observed line of `street` among the live players: `(index in order, act)` and the street +/// contributions per player; `None` if it is not consistent with hero's price. +pub(crate) fn street_line3(spot: &Spot, order: &[u8], street: Street) -> Option<(Vec<(usize, Act)>, Vec)> { let mut c = vec![0.0; order.len()]; let mut line = Vec::new(); let mut aggressed = false; - for r in spot.history.iter().filter(|r| r.street == Street::River) { + for r in spot.history.iter().filter(|r| r.street == street) { let Some(who) = order.iter().position(|s| *s == r.seat) else { // A player no longer in: a check or fold is harmless, money in is not representable. if matches!(r.action, SeenAction::Bet | SeenAction::Raise | SeenAction::AllIn | SeenAction::Call) { @@ -101,17 +101,17 @@ fn river_line(spot: &Spot, order: &[u8]) -> Option<(Vec<(usize, Act)>, Vec) /// The model range of `who`'s line, as card masks off the board (weight 1 each), heaviest-first order /// of the model, at most `MAX_COMBOS`; `keep` joins at a token weight if missing. -fn model_hands(spot: &Spot, who: &Villain, board: u64, keep: Option) -> Option { +pub(crate) fn model_hands(spot: &Spot, who: &Villain, board: u64, keep: Option, max: usize) -> Option { let rules = spot.rules(); let filter = crate::engine::range_filter::range_filter(&crate::exploit::range_model::range_spec(spot, who), rules, spot.variant, &spot.board); let list: Vec> = crate::engine::range_combos::combos(&rules, &filter, &spot.board)?; let mut masks: Vec = list.iter().filter(|c| c.len() == 2).map(|c| fast7::mask(c)).filter(|m| m & board == 0 && m.count_ones() == 2).collect(); masks.sort_unstable(); masks.dedup(); - if masks.len() > MAX_COMBOS { + if masks.len() > max { // Evenly strided, so the kept range keeps its shape (the model gives no weights to rank by). - let step = masks.len() as f64 / MAX_COMBOS as f64; - masks = (0..MAX_COMBOS).map(|k| masks[(k as f64 * step) as usize]).collect(); + let step = masks.len() as f64 / max as f64; + masks = (0..max).map(|k| masks[(k as f64 * step) as usize]).collect(); } let mut weights = vec![1.0; masks.len()]; if let Some(k) = keep { @@ -145,7 +145,7 @@ pub fn solve_river3(spot: &Spot) -> Option { } let started = std::time::Instant::now(); let order = acting_order(spot)?; - let (line, c) = river_line(spot, &order)?; + let (line, c) = street_line3(spot, &order, Street::River)?; let me = order.iter().position(|s| *s == spot.hero_seat)?; let stack_of = |seat: u8| -> f64 { if seat == spot.hero_seat { @@ -164,10 +164,10 @@ pub fn solve_river3(spot: &Spot) -> Option { let mut hands = Vec::with_capacity(order.len()); for seat in &order { let h = if *seat == spot.hero_seat { - model_hands(spot, &Villain { seat: *seat, stack: spot.hero_stack, folded: false, profile: None }, board, Some(hero_mask))? + model_hands(spot, &Villain { seat: *seat, stack: spot.hero_stack, folded: false, profile: None }, board, Some(hero_mask), MAX_COMBOS)? } else { let v = spot.live_villains().find(|v| v.seat == *seat)?; - model_hands(spot, v, board, None)? + model_hands(spot, v, board, None, MAX_COMBOS)? }; hands.push(h); } diff --git a/src/main.rs b/src/main.rs index bbc097d1..dc8c2bd6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -41,6 +41,9 @@ fn main() { rechner::engine::turn_game::set_turn_ueberall(rechner::engine::turn_game::turn_ueberall_from_env()); rechner::engine::flop_spieler::set_flop_spieler(rechner::engine::flop_spieler::from_env()); rechner::engine::river3_spieler::set_river3(rechner::engine::river3_spieler::from_env()); + let (turn3, flop3) = rechner::engine::multi3_spieler::from_env(); + rechner::engine::multi3_spieler::set_turn3(turn3); + rechner::engine::multi3_spieler::set_flop3(flop3); let stdin = io::stdin(); let stdout = io::stdout(); if let Err(error) = serve(stdin.lock(), stdout.lock()) { diff --git a/tests/roentgen_spec.py b/tests/roentgen_spec.py index 36a3b017..21ce9330 100644 --- a/tests/roentgen_spec.py +++ b/tests/roentgen_spec.py @@ -58,6 +58,8 @@ class Klasse(unittest.TestCase): self.assertEqual(k("PREFLOP", "BB vs open, call top 30% -> call"), "regeln") self.assertEqual(k("TURN", "turn game: 30x40 combos, 9 nodes, Check p 0.6, solved in 80 ms"), "e3") self.assertEqual(k("RIVER", "river solver (modell): 300x200 combos, 21 nodes, 600 iters, Fold p 0.9, 40 ms"), "solver") + self.assertEqual(k("TURN", "solver turn3 (3 players): [200, 200, 200] combos, 28671 nodes, 9000 iters, Call p 0.7, 1000 ms"), "solver") + self.assertEqual(k("FLOP", "solver flop3 (3 players): [200, 200, 200] combos, 21571 nodes, 9000 iters, Call p 0.7, 1600 ms"), "solver") self.assertEqual(k("RIVER", "river3 solver (3 players): [300, 300, 300] combos, 271 nodes, 40000 iters, Fold p 0.9, 900 ms"), "solver") self.assertEqual(k("TURN", "defensive turn veto: x (heuristic would call)"), "turn_veto") self.assertEqual(k("RIVER", "defensive veto: x (heuristic would call)"), "river_veto")