//! 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, /// Players who never decide: they check, and call every bet up to the cap (the pooled field of a /// 5+-handed spot, their hands still sampled and in the showdown). Bit mask, 0 = none. pub passive: u32, /// The observed line of street 0 and hero's index (`build_linie`). line: Vec<(usize, Act)>, me: 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, /// Position in the observed line while the walk is on it (`build_linie`, street 0 only). lp: Option, } 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 { Self::build_passiv(players, pot, cap, menus, slots, 0) } /// As `build`, the players in the bit mask `passive` only check or call. pub fn build_passiv(players: usize, pot: f64, cap: f64, menus: &[Menu3], slots: usize, passive: u32) -> GameM { Self::build_linie(players, pot, cap, menus, slots, passive, &[], 0) } /// As `build_passiv`, with the observed street-0 `line` at its exact sizes (see `river3::Game3::build_linie`). #[allow(clippy::too_many_arguments)] pub fn build_linie(players: usize, pot: f64, cap: f64, menus: &[Menu3], slots: usize, passive: u32, line: &[(usize, Act)], me: usize) -> GameM { let mut g = GameM { nodes: Vec::new(), players, pot, cap, slots: slots.max(1), passive, line: line.to_vec(), me }; 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, lp: if line.is_empty() { None } else { Some(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, lp: None, ..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 self.passive & (1 << p) != 0 { if top > s.c[p] + eps { acts.push(Act::Call); totals.push(top); } else { acts.push(Act::Check); totals.push(s.c[p]); } } else 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); } } } // The observed line (street 0): which act it takes here, and the exact size of an observed bet or raise. let mut on: Option<(usize, bool)> = None; if let Some(i) = s.lp { if let Some((who, obs)) = self.line.get(i).cloned() { if who == p { match obs { Act::Bet(x) | Act::Raise(x) => { let kind = |t: &Act| matches!((&obs, t), (Act::Bet(_), Act::Bet(_)) | (Act::Raise(_), Act::Raise(_))); let facing = top > s.c[p] + eps; let erlaubt = x > top + eps && x < self.cap - eps && !acts.iter().any(|t| kind(t) && matches!(t, Act::Bet(y) | Act::Raise(y) if (y - x).abs() < eps)); let platz = if facing { s.raises < menu.max_raises && matches!(obs, Act::Raise(_)) } else { matches!(obs, Act::Bet(_)) }; if erlaubt && platz && self.passive & (1 << p) == 0 { let at = acts.iter().position(|t| matches!(t, Act::Bet(y) | Act::Raise(y) if kind(t) && *y > x)).unwrap_or(acts.len()); acts.insert(at, if matches!(obs, Act::Bet(_)) { Act::Bet(x) } else { Act::Raise(x) }); totals.insert(at, x); } on = acts .iter() .enumerate() .filter_map(|(k, t)| match t { Act::Bet(y) | Act::Raise(y) if kind(t) => Some((k, (y - x).abs())), _ => None, }) .min_by(|a, b| a.1.total_cmp(&b.1)) .map(|(k, _)| (k, true)); } _ => on = acts.iter().position(|t| *t == obs).map(|k| (k, true)), } } else if p != self.me { on = acts.iter().position(|t| *t == Act::Fold).or_else(|| acts.iter().position(|t| matches!(t, Act::Check | Act::Call))).map(|k| (k, false)); } } } 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 (j, (a, total)) in acts.iter().zip(&totals).enumerate() { let mut t = s.clone(); t.lp = match (s.lp, on) { (Some(i), Some((k, eigene))) if k == j => Some(if eigene { i + 1 } else { i }), _ => None, }; 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) } /// As `follow`, but a player whose turn comes before the next recorded act and who is not `me` is taken /// to have folded when a bet is open, else checked (a live player without a recorded act: the history is incomplete, /// the pot says he put nothing more in). Ends at `me`'s next node. pub fn follow_nachsicht(&self, line: &[(usize, Act)], me: usize) -> Option { let mut at = 0; let skip = |at: usize, me: usize| -> Option { let NodeM::Dec { player, acts, kids, .. } = &self.nodes[at] else { return None }; if *player == me { return None; } let k = acts.iter().position(|t| *t == Act::Fold).or_else(|| acts.iter().position(|t| matches!(t, Act::Check | Act::Call)))?; Some(kids[k]) }; for (who, a) in line { loop { let NodeM::Dec { player, .. } = &self.nodes[at] else { return None }; if player == who { break; } at = skip(at, me)?; } at = self.step(at, a)?; } while let NodeM::Dec { player, .. } = &self.nodes[at] { if *player == me { break; } at = skip(at, me)?; } Some(at) } /// The nodes the observed line passes (node, index of the act taken), as `follow_nachsicht` walks it: a player whose /// turn comes before his recorded act and who is not `me` folds (bet open) or checks. Ends at `me`'s next node. pub fn pfad_nachsicht(&self, line: &[(usize, Act)], me: usize) -> Option> { let mut at = 0; let mut pfad = Vec::new(); let skip = |at: usize, pfad: &mut Vec<(usize, usize)>| -> Option { let NodeM::Dec { acts, kids, .. } = &self.nodes[at] else { return None }; let k = acts.iter().position(|t| *t == Act::Fold).or_else(|| acts.iter().position(|t| matches!(t, Act::Check | Act::Call)))?; pfad.push((at, k)); Some(kids[k]) }; for (who, a) in line { loop { let NodeM::Dec { player, .. } = &self.nodes[at] else { return None }; if player == who { break; } if *player == me { return None; } at = skip(at, &mut pfad)?; } let NodeM::Dec { acts, kids, .. } = &self.nodes[at] else { 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)?, }; pfad.push((at, k)); at = kids[k]; } while let NodeM::Dec { player, .. } = &self.nodes[at] { if *player == me { break; } at = skip(at, &mut pfad)?; } Some(pfad) } /// The child of `at` that the observed act `a` leads to (nearest size for bets and raises). fn step(&self, at: usize, a: &Act) -> Option { let NodeM::Dec { acts, kids, .. } = &self.nodes[at] else { 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)?, }; Some(kids[k]) } } 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() } /// `SOLVER3_KARTE=zufall` (default off): the next street's card is drawn uniformly from every undealt card and only /// *mapped* onto a slot (a chunk of neighbouring ranks), instead of dealing a few fixed representative cards. The fixed /// representatives (an even stride over a suit-major deck) hit a draw's outs by aliasing: 8 outs among 46 cards are 17 % /// of the river, but with 8 slots 0 to 2 slots hit (0 to 25 %), with 4 slots (the first fallback under time pressure) 0 /// to 50 %, with 2 slots 0, 50 or 100 %. A draw was then valued at ~0 and folded at "p 1.00" (live replay 19.11.). static ZUFALL: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); pub fn set_zufall(on: bool) { ZUFALL.store(on, std::sync::atomic::Ordering::Relaxed); } 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, /// `SOLVER3_KARTE=zufall`: every undealt card with its slot (rank-ordered chunks); empty = the fixed slot cards. karten_slot: Vec<(u64, usize)>, /// Cards dealt per iteration beyond the slot card (uniformly from the rest). extra: usize, cum: Vec>, regret: Vec>, avg: Vec>, rng: Xs, t: u64, /// As `river3::Solver3`: the pool's row per hand and its weight per node. locks: Vec>, f64)>>, } /// 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 { Self::new_mit(game, hands, board, seed, ZUFALL.load(std::sync::atomic::Ordering::Relaxed)) } /// As `new`, with the card mode given (`zufall`: see `ZUFALL`). pub fn new_mit(game: GameM, hands: Vec, board: u64, seed: u64, zufall: bool) -> 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(); let locks = vec![None; game.nodes.len()]; let karten_slot = if zufall && !undealt.is_empty() { // Rank-major order (low to high, the suits of a rank together), cut into `k` chunks of nearly equal size. let mut by_rank = undealt.clone(); by_rank.sort_by_key(|c| (c.trailing_zeros() % 16, c.trailing_zeros() / 16)); let n = by_rank.len(); by_rank.iter().enumerate().map(|(i, c)| (*c, (i * k / n).min(k.saturating_sub(1)))).collect() } else { Vec::new() }; SolverM { game, hands, board, slot_cards, karten_slot, extra, cum, regret, avg, rng: Xs(seed | 1), t: 0, locks } } /// Lock `node`'s player to the pool rows `rows` (one row per hand over the node's acts) with weight `w`. pub fn lock(&mut self, node: usize, rows: Vec, w: f64) { self.locks[node] = Some((std::sync::Arc::new(rows), w.clamp(0.0, 1.0))); } /// As `lock`, the rows shared with other nodes (the later streets' nodes repeat one row per player and card slot). pub fn lock_geteilt(&mut self, node: usize, rows: std::sync::Arc>, w: f64) { self.locks[node] = Some((rows, w.clamp(0.0, 1.0))); } pub fn masks(&self, p: usize) -> &[u64] { &self.hands[p].masks } /// One card per slot of the next street, the one the locks rank the hands on: the fixed slot card, or (`zufall`) the /// middle card of the slot's chunk. pub fn slot_vertreter(&self) -> Vec { if self.karten_slot.is_empty() { return self.slot_cards.clone(); } (0..self.slot_cards.len()) .map(|j| { let drin: Vec = self.karten_slot.iter().filter(|(_, s)| *s == j).map(|(c, _)| *c).collect(); drin.get(drin.len() / 2).copied().unwrap_or(0) }) .collect() } 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 { if self.karten_slot.is_empty() { 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]; } else { // Uniform over every card no sampled hand holds; its slot only picks the subtree. let free: Vec<(u64, usize)> = self.karten_slot.iter().copied().filter(|(c, _)| c & used == 0).collect(); if free.is_empty() { return None; } let (c, s) = free[self.rng.below(free.len())]; slot = s; run |= c; } } 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 { if self.game.passive & (1 << i) != 0 { continue; } 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); if let Some((rows, w)) = &self.locks[node] { for (k, s) in sigma.iter_mut().enumerate() { *s = (1.0 - w) * *s + w * rows[h * a + k]; } } 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] } } /// Diagnosis: the hand's regrets at `node` per action in chips (weighted mean of `value(a) - value(strategy)`). pub fn regret_chips(&self, node: usize, h: usize) -> Vec { let NodeM::Dec { acts, .. } = &self.game.nodes[node] else { return Vec::new() }; let a = acts.len(); let z = (self.t * (self.t + 1)) as f64 / 2.0; self.regret[node][h * a..(h + 1) * a].iter().map(|r| r / z).collect() } pub fn iterations(&self) -> u64 { self.t } } #[cfg(test)] mod tests;