Skip to main content

native_solver/solver/
cfr.rs

1//! Combo-vectorized CFR: instead of recursing per fixed hand pair (as the
2//! Kuhn poker trainer does), each information set holds one regret/
3//! strategy row **per combo** in the acting player's range
4//! (`[action][combo]`), and terminal values are computed as a weighted
5//! sum over the opponent's live (non-card-conflicting) combos. This is
6//! the standard technique real postflop solvers use to solve a whole
7//! range at once instead of one hand match-up at a time.
8//!
9//! `Chance` nodes (dealt community cards) are handled the same way: each
10//! candidate card is equally likely conditional on a legal private deal.
11//! Both players' hole cards are excluded: hero conflicts are masked while
12//! aggregating branches and opponent conflicts are masked at terminals.
13//! Every compatible private deal therefore has `N - 4` possible next
14//! cards among the N cards not yet on the board, so raw counterfactual
15//! values divide by `N - 4`, not by an own-hand-only conditional count.
16//!
17//! Sibling subtrees (a decision node's actions, a chance node's dealt
18//! cards) are independent recursions given the strategy at this node, so
19//! they're evaluated in parallel with `rayon`. Each decision node's
20//! regret/strategy tables live behind a `Mutex` to make that safe — actual
21//! contention is near zero, since a node is touched only by the one or two
22//! threads whose branch passes through it.
23
24use super::discount::{IterationUpdate, SolverAlgorithm, UpdateSchedule};
25use super::terminal::{BoardOrder, TerminalIndex};
26use super::tree::{validate_board, BoardError, Node, Player, Terminal};
27#[cfg(test)]
28use crate::card::CardSet;
29use crate::card::{bit, mask_has, mask_of, Card};
30use crate::eval::score_7;
31use crate::range::Combo;
32use rayon::prelude::*;
33use std::collections::HashMap;
34use std::sync::{Arc, Mutex};
35
36mod reach_scratch;
37use reach_scratch::ReachScratch;
38
39struct NodeData {
40    regret_sum: Vec<Vec<f64>>,
41    strategy_sum: Vec<Vec<f64>>,
42}
43
44impl NodeData {
45    fn empty() -> Self {
46        Self {
47            regret_sum: Vec::new(),
48            strategy_sum: Vec::new(),
49        }
50    }
51
52    fn sized(num_actions: usize, num_combos: usize) -> Self {
53        Self {
54            regret_sum: vec![vec![0.0; num_combos]; num_actions],
55            strategy_sum: vec![vec![0.0; num_combos]; num_actions],
56        }
57    }
58}
59
60/// Which player learns, and which CFV vectors are needed by this traversal.
61/// A missing vector stays empty; reaches remain available for own-reach
62/// averaging and bucket weights even when only one player's CFV is returned.
63#[derive(Clone, Copy)]
64struct TrainingPass {
65    update: IterationUpdate,
66    updating: Option<usize>,
67    values: u8,
68}
69
70impl TrainingPass {
71    fn computes(self, player: usize) -> bool {
72        self.values & (1 << player) != 0
73    }
74}
75
76/// Trains a strategy for one game with counterfactual regret minimization.
77///
78/// A trainer owns the regret and strategy tables. The game itself
79/// ([`SolverGame`]) is immutable and shared through [`Trainer::game`], so a
80/// [`Policy`] snapshot can be read while training continues.
81///
82/// # Examples
83///
84/// ```
85/// use native_solver::{build_tree, Card, CardSet, Chips, GameConfig, Player, Range, Trainer, TrainerOptions};
86///
87/// let board = ["Ks", "Th", "7s", "4d", "2s"]
88///     .iter()
89///     .map(|card| card.parse())
90///     .collect::<Result<Vec<Card>, _>>()?;
91/// let dead = CardSet::from_cards(&board);
92/// let oop = "AA,KQs".parse::<Range>()?.combos(dead);
93/// let ip = "QQ,JJ".parse::<Range>()?.combos(dead);
94/// let config = GameConfig::new(board, Chips::whole(100), Chips::whole(100)).with_bet_sizes([1.0]);
95///
96/// let mut trainer = Trainer::new(build_tree(&config)?, [oop, ip], TrainerOptions::default())?;
97/// trainer.train(200);
98/// assert_eq!(trainer.iterations_completed(), 200);
99///
100/// // Node 0 is OOP's first decision: one row per action, one column per OOP combo.
101/// let strategy = trainer.average_strategy(0);
102/// assert_eq!(strategy[0].len(), trainer.game().combos(Player::Oop).len());
103///
104/// // How much a best response could still gain, in chips.
105/// assert!(trainer.exploitability().total < 1.0);
106/// # Ok::<(), Box<dyn std::error::Error>>(())
107/// ```
108pub struct Trainer {
109    game: Arc<SolverGame>,
110    algorithm: SolverAlgorithm,
111    update_schedule: UpdateSchedule,
112    /// Full iterations completed across every call to `train`.
113    iterations_completed: u64,
114    node_data: Vec<Mutex<NodeData>>,
115}
116
117/// A snapshot of the average strategy at every decision node.
118///
119/// Take one with [`Trainer::policy`]; it does not change as training continues.
120/// Pass it to [`SolverGame`]'s read methods. The probabilities are normalized,
121/// suit-symmetrized, and stored per bucket as `[node][action][bucket]`
122/// ([`Policy::rows`]), so a policy can be saved and later restored with
123/// [`SolverGame::policy_from_rows`].
124///
125/// # Examples
126///
127/// ```
128/// # use native_solver::*;
129/// # let board = ["Ks", "Th", "7s", "4d", "2s"].iter().map(|c| c.parse()).collect::<Result<Vec<Card>, _>>()?;
130/// # let dead = CardSet::from_cards(&board);
131/// # let config = GameConfig::new(board, Chips::whole(100), Chips::whole(100)).with_bet_sizes([1.0]);
132/// # let ranges = ["AA,KQs", "QQ,JJ"].map(|r| r.parse::<Range>().unwrap().combos(dead));
133/// # let mut trainer = Trainer::new(build_tree(&config)?, ranges, TrainerOptions::default())?;
134/// trainer.train(100);
135/// let policy = trainer.policy();
136/// let saved: Vec<Vec<Vec<f64>>> = policy.rows().to_vec();
137///
138/// // More training does not change the snapshot.
139/// trainer.train(100);
140/// let restored = trainer.game().policy_from_rows(saved)?;
141/// assert_eq!(restored, policy);
142/// let exploitability = trainer.game().exploitability(&restored).total;
143/// assert!(exploitability.is_finite());
144/// # Ok::<(), Box<dyn std::error::Error>>(())
145/// ```
146#[derive(Debug, Clone, PartialEq)]
147pub struct Policy {
148    rows: Vec<Vec<Vec<f64>>>,
149}
150
151impl Policy {
152    /// `[node][action][bucket]` probabilities, e.g. for persisting a snapshot.
153    pub fn rows(&self) -> &[Vec<Vec<f64>>] {
154        &self.rows
155    }
156}
157
158/// Why persisted policy rows do not fit a game (see [`SolverGame::policy_from_rows`]).
159#[derive(Debug, Clone, PartialEq, Eq)]
160#[non_exhaustive]
161pub enum PolicyError {
162    /// The policy has a different number of decision nodes than the game.
163    NodeCount {
164        /// Decision nodes in the policy.
165        policy: usize,
166        /// Decision nodes in the game.
167        game: usize,
168    },
169    /// A node's action or bucket count differs from the game's.
170    Shape {
171        /// The first mismatched decision node id.
172        node: usize,
173    },
174    /// A bucket's probabilities are not finite, nonnegative, and summing to 1.
175    NotDistribution {
176        /// The first invalid decision node id.
177        node: usize,
178    },
179    /// Suit-equivalent buckets have different probabilities.
180    NotSymmetric {
181        /// The first asymmetric decision node id.
182        node: usize,
183    },
184}
185
186impl std::fmt::Display for PolicyError {
187    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
188        match self {
189            Self::NodeCount { policy, game } => {
190                write!(f, "policy has {policy} nodes, game has {game}")
191            }
192            Self::Shape { node } => write!(f, "policy shape does not match node {node}"),
193            Self::NotDistribution { node } => {
194                write!(f, "policy at node {node} is not a probability distribution")
195            }
196            Self::NotSymmetric { node } => write!(f, "policy at node {node} is not suit-symmetric"),
197        }
198    }
199}
200
201impl std::error::Error for PolicyError {}
202
203/// Why [`Trainer::new`] rejected its inputs.
204#[derive(Debug, Clone, PartialEq, Eq)]
205#[non_exhaustive]
206pub enum TrainerError {
207    /// The tree's board is not a legal flop, turn, or river.
208    Board(BoardError),
209    /// The tree's nodes do not continue from its board: they reach a
210    /// showdown before the river, or deal a card past the river.
211    TreeBoardMismatch,
212    /// The tree is malformed: decision ids are not exactly
213    /// `0..num_decision_nodes`, actions and children differ in length, a
214    /// chance node does not deal every undealt card exactly once or groups
215    /// cards that are not suit swaps of each other, or a terminal investment
216    /// is negative or not finite.
217    InvalidTree {
218        /// What was wrong.
219        reason: &'static str,
220    },
221    /// A player's range has no combo with positive weight.
222    EmptyRange {
223        /// The player whose range is empty.
224        player: Player,
225    },
226    /// A combo holds the same card twice.
227    InvalidCombo {
228        /// The player whose range holds the combo.
229        player: Player,
230        /// The combo's index in that player's range.
231        index: usize,
232    },
233    /// A combo appears more than once in the same range.
234    DuplicateCombo {
235        /// The player whose range holds the combo.
236        player: Player,
237        /// The index of the second occurrence.
238        index: usize,
239    },
240    /// A combo uses a card that is already on the initial board.
241    ///
242    /// Pass the board as dead cards to [`Range::combos`](crate::Range::combos).
243    ComboConflictsWithBoard {
244        /// The player whose range holds the combo.
245        player: Player,
246        /// The combo's index in that player's range.
247        index: usize,
248    },
249    /// A combo weight is negative or not finite.
250    InvalidWeight {
251        /// The player whose range holds the combo.
252        player: Player,
253        /// The combo's index in that player's range.
254        index: usize,
255    },
256    /// Every pair of positive-weight combos shares a card, so no deal is
257    /// possible and every value would be undefined.
258    NoCompatibleDeals,
259    /// A [`CardAbstraction`] street asks for zero buckets.
260    ZeroBuckets,
261    /// A range is not closed under the initial board's free-suit swaps.
262    ///
263    /// This is required when the tree groups chance cards by suit isomorphism
264    /// (with equal weights for swapped combos) or when flop or turn buckets are
265    /// on.
266    AsymmetricRange {
267        /// The player whose range is asymmetric.
268        player: Player,
269    },
270}
271
272impl std::fmt::Display for TrainerError {
273    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
274        match self {
275            Self::Board(error) => write!(f, "invalid initial board: {error}"),
276            Self::TreeBoardMismatch => write!(f, "tree does not match the initial board"),
277            Self::InvalidTree { reason } => write!(f, "invalid tree: {reason}"),
278            Self::EmptyRange { player } => {
279                write!(f, "{player:?} range has no combo with positive weight")
280            }
281            Self::InvalidCombo { player, index } => {
282                write!(f, "{player:?} combo {index} must hold two distinct cards")
283            }
284            Self::DuplicateCombo { player, index } => {
285                write!(f, "{player:?} combo {index} repeats an earlier combo")
286            }
287            Self::ComboConflictsWithBoard { player, index } => write!(
288                f,
289                "{player:?} combo {index} uses a card on the initial board"
290            ),
291            Self::InvalidWeight { player, index } => write!(
292                f,
293                "{player:?} combo {index} weight must be finite and nonnegative"
294            ),
295            Self::NoCompatibleDeals => {
296                write!(f, "no pair of positive-weight combos can be dealt together")
297            }
298            Self::ZeroBuckets => write!(f, "card abstraction bucket counts must be positive"),
299            Self::AsymmetricRange { player } => write!(
300                f,
301                "{player:?} range must be suit-symmetric for suit isomorphism or flop/turn buckets"
302            ),
303        }
304    }
305}
306
307impl std::error::Error for TrainerError {
308    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
309        match self {
310            Self::Board(error) => Some(error),
311            _ => None,
312        }
313    }
314}
315
316impl From<BoardError> for TrainerError {
317    fn from(error: BoardError) -> Self {
318        Self::Board(error)
319    }
320}
321
322/// Rejects inputs that [`Trainer`] cannot solve as a legal game.
323fn validate_trainer_inputs(
324    tree: &super::tree::Tree,
325    combos: &[Vec<Combo>; 2],
326    abstraction: CardAbstraction,
327) -> Result<(), TrainerError> {
328    let initial_board = tree.board.as_slice();
329    validate_board(initial_board)?;
330    let mut seen_ids = vec![false; tree.num_decision_nodes];
331    validate_tree(&tree.root, &mut initial_board.to_vec(), &mut seen_ids)?;
332    if seen_ids.iter().any(|&seen| !seen) {
333        return Err(TrainerError::InvalidTree {
334            reason: "decision ids must cover 0..num_decision_nodes",
335        });
336    }
337
338    let board = mask_of(initial_board);
339    let mut masks = [Vec::new(), Vec::new()];
340    for (p, player) in [Player::Oop, Player::Ip].into_iter().enumerate() {
341        let mut seen = std::collections::HashSet::new();
342        for (index, combo) in combos[p].iter().enumerate() {
343            let [a, b] = combo.cards;
344            if a == b {
345                return Err(TrainerError::InvalidCombo { player, index });
346            }
347            if !combo.weight.is_finite() || combo.weight < 0.0 {
348                return Err(TrainerError::InvalidWeight { player, index });
349            }
350            if !seen.insert(normalize_pair(a, b)) {
351                return Err(TrainerError::DuplicateCombo { player, index });
352            }
353            if combo.bits() & board != 0 {
354                return Err(TrainerError::ComboConflictsWithBoard { player, index });
355            }
356            if combo.weight > 0.0 {
357                masks[p].push(combo.bits());
358            }
359        }
360        if masks[p].is_empty() {
361            return Err(TrainerError::EmptyRange { player });
362        }
363    }
364    if !masks[0]
365        .iter()
366        .any(|&oop| masks[1].iter().any(|&ip| oop & ip == 0))
367    {
368        return Err(TrainerError::NoCompatibleDeals);
369    }
370
371    if [abstraction.flop, abstraction.turn, abstraction.river].contains(&Some(0)) {
372        return Err(TrainerError::ZeroBuckets);
373    }
374    // Suit-reduced trees derive non-representative runouts by relabeling, so
375    // swapped combos must exist with equal weights. Flop and turn buckets
376    // average scores over suit-grouped runouts (`avg_score`), which only needs
377    // the swapped combos to exist. Later boards only remove free suits, so
378    // the initial board's free-suit swaps cover every reachable board.
379    let reduced = has_suit_reduction(&tree.root);
380    let averaged_buckets = (abstraction.flop.is_some() && initial_board.len() == 3)
381        || (abstraction.turn.is_some() && initial_board.len() <= 4);
382    if reduced || averaged_buckets {
383        let free: Vec<u8> = (0..4)
384            .filter(|&s| !initial_board.iter().any(|&c| c.suit() == s))
385            .collect();
386        for (p, player) in [Player::Oop, Player::Ip].into_iter().enumerate() {
387            let weights: HashMap<(Card, Card), f64> = combos[p]
388                .iter()
389                .map(|combo| (normalize_pair(combo.cards[0], combo.cards[1]), combo.weight))
390                .collect();
391            for (i, &sa) in free.iter().enumerate() {
392                for &sb in &free[i + 1..] {
393                    for combo in &combos[p] {
394                        let [a, b] = combo.cards;
395                        let swapped = normalize_pair(swap_suit(a, sa, sb), swap_suit(b, sa, sb));
396                        let symmetric = match weights.get(&swapped) {
397                            Some(&weight) => !reduced || weight == combo.weight,
398                            None => false,
399                        };
400                        if !symmetric {
401                            return Err(TrainerError::AsymmetricRange { player });
402                        }
403                    }
404                }
405            }
406        }
407    }
408    Ok(())
409}
410
411/// Checks the structure [`Trainer`] relies on while walking `node` from `board`.
412fn validate_tree(
413    node: &Node,
414    board: &mut Vec<Card>,
415    seen_ids: &mut [bool],
416) -> Result<(), TrainerError> {
417    let invalid = |reason| Err(TrainerError::InvalidTree { reason });
418    match node {
419        Node::Decision {
420            id,
421            actions,
422            children,
423            ..
424        } => {
425            match seen_ids.get_mut(*id) {
426                Some(seen) if !*seen => *seen = true,
427                Some(_) => return invalid("decision ids must be unique"),
428                None => return invalid("decision ids must be below num_decision_nodes"),
429            }
430            if actions.is_empty() || actions.len() != children.len() {
431                return invalid("decisions need matching nonempty actions and children");
432            }
433            for child in children {
434                validate_tree(child, board, seen_ids)?;
435            }
436        }
437        Node::Chance { children } => {
438            if board.len() >= 5 {
439                return Err(TrainerError::TreeBoardMismatch);
440            }
441            let mut dealt = mask_of(board);
442            let mut count = 0;
443            for (members, _) in children {
444                if members.is_empty() {
445                    return invalid("chance classes must not be empty");
446                }
447                for &card in members {
448                    if mask_has(dealt, card) {
449                        return invalid("chance nodes must deal each undealt card exactly once");
450                    }
451                    dealt |= bit(card);
452                    count += 1;
453                }
454                // Grouped cards are derived from `members[0]` by swapping two
455                // suits, which is only a symmetry when both suits are off the
456                // board and the ranks match.
457                if members.len() > 1
458                    && members.iter().any(|&card| {
459                        card.rank() != members[0].rank()
460                            || board.iter().any(|&b| b.suit() == card.suit())
461                    })
462                {
463                    return invalid(
464                        "chance classes must group one rank in suits absent from the board",
465                    );
466                }
467            }
468            if count != 52 - board.len() {
469                return invalid("chance nodes must deal each undealt card exactly once");
470            }
471            for (members, child) in children {
472                board.push(members[0]);
473                let result = validate_tree(child, board, seen_ids);
474                board.pop();
475                result?;
476            }
477        }
478        Node::Terminal(terminal) => {
479            let invested = match terminal {
480                Terminal::Fold { invested, .. } => invested,
481                Terminal::Showdown { invested } => {
482                    if board.len() != 5 {
483                        return Err(TrainerError::TreeBoardMismatch);
484                    }
485                    invested
486                }
487            };
488            if invested.iter().any(|x| !x.is_finite() || *x < 0.0) {
489                return invalid("terminal investments must be finite and nonnegative");
490            }
491        }
492    }
493    Ok(())
494}
495
496/// Everything about a solve that training does not change.
497///
498/// It holds the tree, the ranges, board caches, card abstraction, and
499/// suit-symmetry groups. Its read methods (`evaluate`, `exploitability`,
500/// `average_strategy`) take a [`Policy`], so they can run while a [`Trainer`]
501/// keeps training. Get one from [`Trainer::game`].
502pub struct SolverGame {
503    tree: super::tree::Tree,
504    initial_board: Vec<Card>,
505    combos: [Vec<Combo>; 2],
506    /// [`evaluate_7`](crate::evaluate_7) scores for every complete (5-card) board reachable via
507    /// a `Chance` node, precomputed once so `train()` doesn't recompute
508    /// hand strengths for the same board on every iteration.
509    board_eval_cache: HashMap<Vec<Card>, [Vec<u32>; 2]>,
510    /// Per player: `(min(card1,card2), max(card1,card2))` -> index into
511    /// `combos[player]`. Used by `chance_value`'s suit-isomorphism
512    /// relabeling to look up which combo a suit-swapped combo corresponds
513    /// to, without a linear scan.
514    combo_index: [HashMap<(Card, Card), usize>; 2],
515    /// Linear-time card-removal kernels and immutable per-board rank orders.
516    terminal_index: TerminalIndex,
517    board_order_cache: HashMap<Vec<Card>, BoardOrder>,
518    /// Per-street card abstraction setting this trainer was built with —
519    /// see [`CardAbstraction`] and the module doc comment's "card
520    /// abstraction" section. `CardAbstraction::default()` never buckets.
521    abstraction: CardAbstraction,
522    /// Per board (any length reachable by a Decision node — flop/turn use
523    /// `avg_score`, river uses the real [`evaluate_7`](crate::evaluate_7) score), per player:
524    /// combo index -> bucket index. Only populated for streets
525    /// `abstraction` actually buckets.
526    bucket_maps: HashMap<Vec<Card>, [Vec<usize>; 2]>,
527    /// Per player: `0..combos[player].len()`, the fallback "every combo is
528    /// its own bucket" mapping used at any node not covered by
529    /// `bucket_maps` (a street `abstraction` leaves unbucketed).
530    identity_buckets: [Vec<usize>; 2],
531    /// Exact board-stabilizing suit orbits in bucket coordinates. Only reduced
532    /// trees need this: roundoff must not turn interchangeable hands into
533    /// different policies and invalidate representative-only chance traversal.
534    suit_groups: HashMap<Vec<Card>, [Vec<Vec<usize>>; 2]>,
535    /// Per decision node id: `(acting player index, board at that node)`,
536    /// recorded once during `init_node_data` — `average_strategy` needs
537    /// this to look up the node's bucket map and expand bucket-level
538    /// probabilities back out to the per-combo output the API contract
539    /// promises.
540    node_meta: Vec<(usize, Vec<Card>)>,
541    #[cfg(test)]
542    use_pairwise_terminals: std::sync::atomic::AtomicBool,
543    #[cfg(test)]
544    terminal_calls: [std::sync::atomic::AtomicUsize; 2],
545}
546
547/// How a [`Trainer`] learns: the update rule, the update order, and card abstraction.
548///
549/// The default is DCFR with simultaneous updates and every street solved
550/// exactly.
551#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
552pub struct TrainerOptions {
553    /// The regret and strategy-averaging rule.
554    pub algorithm: SolverAlgorithm,
555    /// Whether both players update together or in alternation.
556    pub schedule: UpdateSchedule,
557    /// Which streets are bucketed, and into how many buckets.
558    pub abstraction: CardAbstraction,
559}
560
561/// Which streets let hands of similar strength share one strategy (bucketing).
562///
563/// `Some(n)` groups each player's combos on that street into at most `n`
564/// percentile buckets of hand strength that share a strategy. Tied strengths
565/// stay in one bucket, so there can be fewer than `n`. `None` solves the street
566/// exactly, and the default (all `None`) never buckets. Flop and turn buckets
567/// use the mean river strength over the remaining runouts; river buckets use
568/// the exact strength.
569#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
570pub struct CardAbstraction {
571    /// Bucket count for decisions on a 3-card board.
572    pub flop: Option<usize>,
573    /// Bucket count for decisions on a 4-card board.
574    pub turn: Option<usize>,
575    /// Bucket count for decisions on a 5-card board.
576    pub river: Option<usize>,
577}
578
579/// [`SolverGame::evaluate`]'s result: per-node values under a policy.
580#[derive(Debug, Clone, PartialEq)]
581#[non_exhaustive]
582pub struct Evaluation {
583    /// One entry per decision node, indexed by node id.
584    pub nodes: Vec<NodeEvaluation>,
585    /// Root `[OOP, IP]` raw range-weighted values, not EVs.
586    ///
587    /// They are zero-sum like [`Trainer::train`]'s return, but under the evaluated
588    /// policy. See [the conventions](crate::conventions) for the
589    /// normalization.
590    pub root_values: [f64; 2],
591}
592
593/// Values at one decision node under a policy, per combo of the acting player.
594///
595/// Combos are in the acting player's range order. Equity is only reported on a
596/// complete five-card board, where it is exact.
597#[derive(Debug, Clone, PartialEq)]
598pub struct NodeEvaluation {
599    /// Each combo's EV from this node on, in input chips.
600    ///
601    /// It is the raw counterfactual value divided by the opponent's compatible
602    /// reach (`0.0` when no opponent combo is compatible). Payoffs count half the
603    /// initial pot as each player's own investment, as in [`Terminal`]. This is the
604    /// value of the whole node under the policy, not of any single action.
605    pub ev: Vec<f64>,
606    /// Each combo's showdown win probability; `Some` only on a complete board.
607    ///
608    /// Ties count half. The probability is against the opponent's compatible,
609    /// reach-weighted range at this node, or `0.5` when no opponent combo is
610    /// compatible.
611    pub equity: Option<Vec<f64>>,
612}
613
614/// How much a best response could gain against a policy, in chips.
615///
616/// `oop` and `ip` are each player's best-response value: the range-weighted EV
617/// of deviating to a perfect best response while the other player keeps the
618/// average strategy. In a zero-sum game they cancel at an exact Nash
619/// equilibrium, so `total`, their average, is `0` there and grows with how much
620/// either side can still gain. Values are in the same chips as the pot (not
621/// mbb or a percentage of the pot), averaged over compatible initial deals
622/// weighted by both ranges. Every field is NaN when that joint weight is zero
623/// or not finite; treat such a result as invalid.
624#[derive(Debug, Clone, Copy, PartialEq)]
625pub struct Exploitability {
626    /// OOP's best-response value against IP's average strategy, in chips.
627    pub oop: f64,
628    /// IP's best-response value against OOP's average strategy, in chips.
629    pub ip: f64,
630    /// `(oop + ip) / 2`: the exploitability, in chips.
631    pub total: f64,
632}
633
634impl std::fmt::Debug for Trainer {
635    /// A summary: the update rule, progress, and the game, not the tables.
636    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
637        f.debug_struct("Trainer")
638            .field("algorithm", &self.algorithm)
639            .field("update_schedule", &self.update_schedule)
640            .field("iterations_completed", &self.iterations_completed)
641            .field("game", &self.game)
642            .finish_non_exhaustive()
643    }
644}
645
646impl std::fmt::Debug for SolverGame {
647    /// A summary: board, tree size, range sizes, and abstraction.
648    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
649        f.debug_struct("SolverGame")
650            .field("board", &self.tree.board)
651            .field("num_decision_nodes", &self.tree.num_decision_nodes)
652            .field("num_combos", &[self.combos[0].len(), self.combos[1].len()])
653            .field("abstraction", &self.abstraction)
654            .finish_non_exhaustive()
655    }
656}
657
658impl Trainer {
659    /// Builds a trainer for `tree` and both players' combos.
660    ///
661    /// The combo order is kept and is the combo axis of every per-combo result.
662    /// `options` selects the update rule, the update order (fixed for this
663    /// trainer's lifetime; an alternating iteration is an OOP pass followed by an
664    /// IP pass), and per-street card abstraction.
665    ///
666    /// Trees with grouped chance cards (suit isomorphism) need ranges closed
667    /// under every suit swap that fixes the board, with equal weights for
668    /// swapped combos; flop and turn buckets need the swapped combos to exist.
669    /// Ranges from [`Range::combos`](crate::Range::combos) satisfy both when
670    /// `dead` is exactly the tree's board.
671    ///
672    /// # Errors
673    /// Returns a [`TrainerError`] if the tree's board is illegal, the tree
674    /// does not continue from it or is malformed, a range is empty or holds
675    /// invalid, repeated, or board-blocked combos, no deal is possible, an
676    /// abstraction asks for zero buckets, or a range is not suit-symmetric as
677    /// required above.
678    pub fn new(
679        tree: super::tree::Tree,
680        combos: [Vec<Combo>; 2],
681        options: TrainerOptions,
682    ) -> Result<Self, TrainerError> {
683        validate_trainer_inputs(&tree, &combos, options.abstraction)?;
684        Ok(Self::new_unchecked(tree, combos, options))
685    }
686
687    /// `new` without input validation, for tests that drive the terminal
688    /// kernels with deliberately degenerate ranges.
689    fn new_unchecked(
690        tree: super::tree::Tree,
691        combos: [Vec<Combo>; 2],
692        options: TrainerOptions,
693    ) -> Self {
694        let initial_board = tree.board.clone();
695        let TrainerOptions {
696            algorithm,
697            schedule: update_schedule,
698            abstraction,
699        } = options;
700        let mut board_eval_cache = HashMap::new();
701        precompute_board_eval(&tree.root, &initial_board, &combos, &mut board_eval_cache);
702        // `precompute_board_eval` only inserts entries for boards reached
703        // through a `Chance` node, so a solve that *starts* already at a
704        // complete river board (no chance nodes in the tree at all — the
705        // common "solve this exact river spot" case) would otherwise never
706        // get an entry, silently disabling bucketing for it.
707        if initial_board.len() == 5 {
708            board_eval_cache
709                .entry(initial_board.clone())
710                .or_insert_with(|| eval_combos_if_complete(&combos, &initial_board));
711        }
712
713        let combo_index = [build_combo_index(&combos[0]), build_combo_index(&combos[1])];
714        let terminal_index = TerminalIndex::new(&combos);
715        let board_order_cache = board_eval_cache
716            .iter()
717            .filter(|(board, _)| board.len() == 5)
718            .map(|(board, scores)| {
719                (
720                    board.clone(),
721                    BoardOrder::new(&combos, scores, mask_of(board)),
722                )
723            })
724            .collect();
725
726        let mut bucket_maps: HashMap<Vec<Card>, [Vec<usize>; 2]> = HashMap::new();
727        if let Some(n) = abstraction.river {
728            // The cache also holds turn boards (with empty scores); bucketing
729            // those would give turn decisions zero buckets.
730            for (board, scores) in board_eval_cache.iter().filter(|(b, _)| b.len() == 5) {
731                let scores_f64 = [
732                    scores[0].iter().map(|&s| s as f64).collect::<Vec<f64>>(),
733                    scores[1].iter().map(|&s| s as f64).collect::<Vec<f64>>(),
734                ];
735                bucket_maps.insert(
736                    board.clone(),
737                    [
738                        compute_percentile_buckets(&scores_f64[0], n),
739                        compute_percentile_buckets(&scores_f64[1], n),
740                    ],
741                );
742            }
743        }
744        if abstraction.flop.is_some() || abstraction.turn.is_some() {
745            // Every board a Decision node could actually be built at: the
746            // initial board itself (same "starts already at this street"
747            // reasoning as the river fix above), plus every board reached
748            // by dealing a class representative — matching precisely what
749            // `cfr()` ever recurses into (`chance_value` never visits a
750            // non-representative member's own board; it derives those via
751            // relabeling), so this can't miss or over-collect a board.
752            let mut reachable_boards = std::collections::HashSet::new();
753            reachable_boards.insert(initial_board.clone());
754            collect_reachable_boards(&tree.root, &initial_board, &mut reachable_boards);
755            let mut avg_score_cache = HashMap::new();
756            for board in &reachable_boards {
757                let n = match board.len() {
758                    3 => abstraction.flop,
759                    4 => abstraction.turn,
760                    _ => None,
761                };
762                if let Some(n) = n {
763                    let scores = avg_score(
764                        board,
765                        &combos,
766                        &combo_index,
767                        &board_eval_cache,
768                        &mut avg_score_cache,
769                    );
770                    bucket_maps.insert(
771                        board.clone(),
772                        [
773                            compute_percentile_buckets(&scores[0], n),
774                            compute_percentile_buckets(&scores[1], n),
775                        ],
776                    );
777                }
778            }
779        }
780        let identity_buckets = [
781            (0..combos[0].len()).collect(),
782            (0..combos[1].len()).collect(),
783        ];
784
785        let mut node_data: Vec<NodeData> = (0..tree.num_decision_nodes)
786            .map(|_| NodeData::empty())
787            .collect();
788        let mut node_meta: Vec<(usize, Vec<Card>)> = vec![(0, Vec::new()); tree.num_decision_nodes];
789        init_node_data(
790            &tree.root,
791            &initial_board,
792            &bucket_maps,
793            &identity_buckets,
794            &mut node_data,
795            &mut node_meta,
796        );
797        let node_data: Vec<Mutex<NodeData>> = node_data.into_iter().map(Mutex::new).collect();
798        let mut suit_groups = HashMap::new();
799        if has_suit_reduction(&tree.root) {
800            for (_, board) in &node_meta {
801                suit_groups.entry(board.clone()).or_insert_with(|| {
802                    let maps = bucket_maps.get(board).unwrap_or(&identity_buckets);
803                    suit_bucket_groups(board, &combos, &combo_index, maps)
804                });
805            }
806        }
807
808        let game = SolverGame {
809            tree,
810            initial_board,
811            combos,
812            board_eval_cache,
813            combo_index,
814            terminal_index,
815            board_order_cache,
816            abstraction,
817            bucket_maps,
818            identity_buckets,
819            suit_groups,
820            node_meta,
821            #[cfg(test)]
822            use_pairwise_terminals: std::sync::atomic::AtomicBool::new(false),
823            #[cfg(test)]
824            terminal_calls: std::array::from_fn(|_| std::sync::atomic::AtomicUsize::new(0)),
825        };
826        Self {
827            game: Arc::new(game),
828            algorithm,
829            update_schedule,
830            iterations_completed: 0,
831            node_data,
832        }
833    }
834
835    /// The fixed update policy selected at construction.
836    pub fn algorithm(&self) -> SolverAlgorithm {
837        self.algorithm
838    }
839
840    /// The fixed player-update order selected at construction.
841    pub fn update_schedule(&self) -> UpdateSchedule {
842        self.update_schedule
843    }
844
845    /// Iterations completed across all calls to [`train`](Self::train).
846    ///
847    /// An alternating iteration counts once, though it makes two passes. DCFR uses
848    /// this count as its discounting clock.
849    pub fn iterations_completed(&self) -> u64 {
850        self.iterations_completed
851    }
852
853    /// Runs `iterations` more training iterations.
854    ///
855    /// Returns the root `[OOP, IP]` raw range-weighted values under the last
856    /// iteration's current strategy. They are a progress signal, not EVs, and say
857    /// nothing about convergence; use [`exploitability`](Self::exploitability) for
858    /// that and [`average_strategy`](Self::average_strategy) for the result. With
859    /// alternating updates the values come from the final IP pass.
860    ///
861    /// # Panics
862    /// Panics if the total iteration count would overflow `u64`.
863    pub fn train(&mut self, iterations: u32) -> [f64; 2] {
864        let mut last = [0.0, 0.0];
865        // Borrow the shared game, not `self`, so the iteration clock can advance.
866        let game = Arc::clone(&self.game);
867        let board = game.initial_board.clone();
868        let empty_eval = [Vec::new(), Vec::new()];
869        let board_eval = game.board_eval_cache.get(&board).unwrap_or(&empty_eval);
870        for step in 0..iterations {
871            let iteration = self
872                .iterations_completed
873                .checked_add(1)
874                .expect("CFR iteration counter overflow");
875            let update = self.algorithm.iteration(iteration);
876            let reach0: Vec<f64> = self.game.combos[0].iter().map(|c| c.weight).collect();
877            let reach1: Vec<f64> = self.game.combos[1].iter().map(|c| c.weight).collect();
878            let reach = [reach0.as_slice(), reach1.as_slice()];
879            let pass = match self.update_schedule {
880                UpdateSchedule::Simultaneous => TrainingPass {
881                    update,
882                    updating: None,
883                    values: 3,
884                },
885                UpdateSchedule::Alternating => {
886                    self.cfr(
887                        &self.game.tree.root,
888                        reach,
889                        &board,
890                        board_eval,
891                        TrainingPass {
892                            update,
893                            updating: Some(0),
894                            values: 1,
895                        },
896                    );
897                    // Preserve the exact public train() return on the final IP
898                    // pass. Interior iterations need only the learning player's
899                    // CFVs; no zero-sum reconstruction or extra traversal.
900                    TrainingPass {
901                        update,
902                        updating: Some(1),
903                        values: if step + 1 == iterations { 3 } else { 2 },
904                    }
905                }
906            };
907            let [cfv0, cfv1] = self.cfr(&self.game.tree.root, reach, &board, board_eval, pass);
908            let ev0: f64 = cfv0
909                .iter()
910                .zip(&self.game.combos[0])
911                .map(|(v, c)| v * c.weight)
912                .sum();
913            let ev1: f64 = cfv1
914                .iter()
915                .zip(&self.game.combos[1])
916                .map(|(v, c)| v * c.weight)
917                .sum();
918            last = [ev0, ev1];
919            self.iterations_completed = iteration;
920        }
921        last
922    }
923
924    /// The shared, immutable game definition.
925    pub fn game(&self) -> &Arc<SolverGame> {
926        &self.game
927    }
928
929    /// Snapshot of the average strategy at this iteration boundary.
930    pub fn policy(&self) -> Policy {
931        Policy {
932            rows: (0..self.node_data.len())
933                .map(|id| self.average_bucket_strategy(id))
934                .collect(),
935        }
936    }
937
938    /// [`SolverGame::evaluate`] under the current average strategy.
939    pub fn evaluate(&self) -> Evaluation {
940        self.game.evaluate(&self.policy())
941    }
942
943    /// [`SolverGame::exploitability`] under the current average strategy.
944    pub fn exploitability(&self) -> Exploitability {
945        self.game.exploitability(&self.policy())
946    }
947
948    /// The trained average strategy for one decision node, as
949    /// `[action][combo]` (see [`SolverGame::average_strategy`]).
950    ///
951    /// # Panics
952    /// Panics if `node_id` is not below [`SolverGame::num_decision_nodes`].
953    pub fn average_strategy(&self, node_id: usize) -> Vec<Vec<f64>> {
954        self.game
955            .expand_strategy(node_id, &self.average_bucket_strategy(node_id))
956    }
957
958    /// Normalized strategy sums in bucket coordinates, suit-symmetrized.
959    fn average_bucket_strategy(&self, node_id: usize) -> Vec<Vec<f64>> {
960        let (player, board) = &self.game.node_meta[node_id];
961        let (num_buckets, _) = self.game.combo_buckets(*player, board);
962        let data = self.node_data[node_id].lock().unwrap();
963        let num_actions = data.regret_sum.len();
964        let mut bucket_strategy: Vec<Vec<f64>> = (0..num_actions)
965            .map(|a| {
966                (0..num_buckets)
967                    .map(|b| {
968                        let total: f64 = (0..num_actions).map(|a2| data.strategy_sum[a2][b]).sum();
969                        if total > 0.0 {
970                            data.strategy_sum[a][b] / total
971                        } else {
972                            1.0 / num_actions as f64
973                        }
974                    })
975                    .collect()
976            })
977            .collect();
978        self.game.symmetrize_strategy(node_id, &mut bucket_strategy);
979        bucket_strategy
980    }
981
982    fn current_strategy(&self, id: usize, num_actions: usize, num_combos: usize) -> Vec<Vec<f64>> {
983        let data = self.node_data[id].lock().unwrap();
984        let mut strategy = vec![vec![0.0; num_combos]; num_actions];
985        for i in 0..num_combos {
986            let mut total = 0.0;
987            for (regret_row, strat_row) in data.regret_sum.iter().zip(strategy.iter_mut()) {
988                let r = regret_row[i].max(0.0);
989                strat_row[i] = r;
990                total += r;
991            }
992            if total > 0.0 {
993                for row in strategy.iter_mut().take(num_actions) {
994                    row[i] /= total;
995                }
996            } else {
997                for row in strategy.iter_mut().take(num_actions) {
998                    row[i] = 1.0 / num_actions as f64;
999                }
1000            }
1001        }
1002        self.game.symmetrize_strategy(id, &mut strategy);
1003        strategy
1004    }
1005
1006    /// Recurse into `node`. Sibling subtrees (a decision's actions, a
1007    /// chance node's dealt cards) are independent given the strategy
1008    /// fixed at this node, so they run in parallel via rayon; only the
1009    /// regret/strategy-sum update at the end takes the node's `Mutex`.
1010    fn cfr(
1011        &self,
1012        node: &Node,
1013        reach: [&[f64]; 2],
1014        board: &[Card],
1015        board_eval: &[Vec<u32>; 2],
1016        pass: TrainingPass,
1017    ) -> [Vec<f64>; 2] {
1018        match node {
1019            Node::Terminal(t) => std::array::from_fn(|p| {
1020                if pass.computes(p) {
1021                    self.game
1022                        .terminal_value_for_player(t, p, reach[1 - p], board, board_eval)
1023                } else {
1024                    Vec::new()
1025                }
1026            }),
1027            Node::Chance { children } => self.chance_value(children, reach, board, pass),
1028            Node::Decision {
1029                id,
1030                player,
1031                actions,
1032                children,
1033            } => {
1034                let p = player.index();
1035                let num_own_combos = self.game.combos[p].len();
1036                let num_other_combos = self.game.combos[1 - p].len();
1037                let (num_buckets, buckets) = self.game.combo_buckets(p, board);
1038                let strategy = self.current_strategy(*id, actions.len(), num_buckets);
1039
1040                let child_cfvs: Vec<[Vec<f64>; 2]> = children
1041                    .par_iter()
1042                    .enumerate()
1043                    .map(|(a, child)| {
1044                        // This action changes only the acting player's reach.
1045                        // Each sibling owns that vector; the unchanged opponent
1046                        // slice is shared read-only through the recursive call.
1047                        let mut own_reach = ReachScratch::copy_from(reach[p]);
1048                        for i in 0..num_own_combos {
1049                            own_reach[i] *= strategy[a][buckets[i]];
1050                        }
1051                        let mut child_reach = reach;
1052                        child_reach[p] = &own_reach;
1053                        self.cfr(child, child_reach, board, board_eval, pass)
1054                    })
1055                    .collect();
1056
1057                let mut own_cfv = vec![0.0; if pass.computes(p) { num_own_combos } else { 0 }];
1058                let mut other_cfv = vec![
1059                    0.0;
1060                    if pass.computes(1 - p) {
1061                        num_other_combos
1062                    } else {
1063                        0
1064                    }
1065                ];
1066                for (a, cfv) in child_cfvs.iter().enumerate() {
1067                    let own = &cfv[p];
1068                    let other = &cfv[1 - p];
1069                    for (i, v) in own_cfv.iter_mut().enumerate() {
1070                        *v += strategy[a][buckets[i]] * own[i];
1071                    }
1072                    for (j, v) in other_cfv.iter_mut().enumerate() {
1073                        *v += other[j];
1074                    }
1075                }
1076
1077                // A non-updating player's strategy affects the requested CFVs,
1078                // but its regrets and strategy mass must remain untouched.
1079                if pass.updating.is_some_and(|target| target != p) {
1080                    return if p == 0 {
1081                        [own_cfv, other_cfv]
1082                    } else {
1083                        [other_cfv, own_cfv]
1084                    };
1085                }
1086
1087                // With no abstraction maps every bucket is exactly combo i.
1088                // Its merge weight is one even for zero/board-dead own reach;
1089                // terminal CFVs already exclude impossible private deals.
1090                // Do not infer this from bucket counts: tied scores can leave
1091                // holes in a map while still sharing a bucket.
1092                // Board-dead combos add no average-strategy mass, matching the
1093                // bucketed path's `effective_reach` below.
1094                if self.game.bucket_maps.is_empty() {
1095                    let board_set = mask_of(board);
1096                    let mut data = self.node_data[*id].lock().unwrap();
1097                    for (a, cfv) in child_cfvs.iter().enumerate() {
1098                        for (i, &own) in cfv[p].iter().enumerate() {
1099                            // Keep the old zero-initialized delta accumulation,
1100                            // including its signed-zero behavior.
1101                            let delta = 0.0 + (own - own_cfv[i]);
1102                            data.regret_sum[a][i] =
1103                                pass.update.regret(data.regret_sum[a][i], delta);
1104                            if self.game.combos[p][i].bits() & board_set == 0 {
1105                                data.strategy_sum[a][i] += reach[p][i] * strategy[a][i];
1106                            }
1107                            data.strategy_sum[a][i] =
1108                                pass.update.strategy_sum(data.strategy_sum[a][i]);
1109                        }
1110                    }
1111                    return if p == 0 {
1112                        [own_cfv, other_cfv]
1113                    } else {
1114                        [other_cfv, own_cfv]
1115                    };
1116                }
1117
1118                // `effective_reach` treats a combo whose hole card physically
1119                // conflicts with `board` (impossible on this specific
1120                // runout — see `eval_combos_if_complete`'s doc comment) as
1121                // reach 0 for the bucket-merge weighting and the strategy
1122                // sum below, so a phantom combo sharing a bucket with a real
1123                // one can never skew the real combo's regret or average. When every combo is
1124                // its own bucket (unabstracted, or `river_buckets` capped to
1125                // a bijection) each bucket's total is either that one
1126                // combo's own reach or — if masked or genuinely zero — falls
1127                // through to the equal-weight branch below with a single
1128                // member, which reduces exactly to the plain per-combo
1129                // regret update this replaces (`own[i] - own_cfv[i]`, no
1130                // reach weighting at all), so this is an exact
1131                // generalization, not a behavior change, for that case.
1132                let board_set = mask_of(board);
1133                let effective_reach: Vec<f64> = (0..num_own_combos)
1134                    .map(|i| {
1135                        let [h1, h2] = self.game.combos[p][i].cards;
1136                        if mask_has(board_set, h1) || mask_has(board_set, h2) {
1137                            0.0
1138                        } else {
1139                            reach[p][i]
1140                        }
1141                    })
1142                    .collect();
1143                let mut bucket_reach_total = vec![0.0; num_buckets];
1144                let mut bucket_size = vec![0usize; num_buckets];
1145                for i in 0..num_own_combos {
1146                    bucket_reach_total[buckets[i]] += effective_reach[i];
1147                    bucket_size[buckets[i]] += 1;
1148                }
1149
1150                {
1151                    let mut data = self.node_data[*id].lock().unwrap();
1152                    for (a, cfv) in child_cfvs.iter().enumerate() {
1153                        let own = &cfv[p];
1154                        let mut regret_delta = vec![0.0; num_buckets];
1155                        for i in 0..num_own_combos {
1156                            let b = buckets[i];
1157                            let delta = own[i] - own_cfv[i];
1158                            let weight = if bucket_reach_total[b] > 0.0 {
1159                                effective_reach[i] / bucket_reach_total[b]
1160                            } else {
1161                                1.0 / bucket_size[b] as f64
1162                            };
1163                            regret_delta[b] += weight * delta;
1164                            data.strategy_sum[a][b] += effective_reach[i] * strategy[a][b];
1165                        }
1166                        for (b, delta) in regret_delta.iter().enumerate() {
1167                            data.regret_sum[a][b] =
1168                                pass.update.regret(data.regret_sum[a][b], *delta);
1169                            // Once per bucket, after every combo's contribution:
1170                            // never apply DCFR discounting inside the combo loop.
1171                            data.strategy_sum[a][b] =
1172                                pass.update.strategy_sum(data.strategy_sum[a][b]);
1173                        }
1174                    }
1175                }
1176
1177                if p == 0 {
1178                    [own_cfv, other_cfv]
1179                } else {
1180                    [other_cfv, own_cfv]
1181                }
1182            }
1183        }
1184    }
1185
1186    /// Average raw `cfv` over every legal next card of each compatible
1187    /// private deal. Hero-card conflicts are excluded here; opponent-card
1188    /// conflicts are excluded at terminals. Together they leave N - 4
1189    /// possible cards, even though the outer vector is hero-combo indexed.
1190    ///
1191    /// `children` is grouped into suit-isomorphism classes (see
1192    /// `tree::deal_classes`): only the class's representative
1193    /// (`members[0]`) is actually recursed into. Every other member's
1194    /// counterfactual values are derived from the representative's by
1195    /// `relabel_cfv` — a swap of the two suits involved is a symmetry of
1196    /// the game (it doesn't change tree structure or [`evaluate_7`](crate::evaluate_7)
1197    /// outcomes), so member `card`'s cfv for combo `j` equals the
1198    /// representative's cfv for the combo obtained by applying that same
1199    /// suit swap to combo `j`'s two cards. With isomorphism disabled every
1200    /// class is a singleton and this reduces to the original per-card loop.
1201    fn chance_value(
1202        &self,
1203        children: &[(Vec<Card>, Node)],
1204        reach: [&[f64]; 2],
1205        board: &[Card],
1206        pass: TrainingPass,
1207    ) -> [Vec<f64>; 2] {
1208        let n: usize = children.iter().map(|(members, _)| members.len()).sum();
1209        let divisor = (n as f64) - 4.0;
1210
1211        let class_results: Vec<(&Vec<Card>, [Vec<f64>; 2])> = children
1212            .par_iter()
1213            .map(|(members, child)| {
1214                let rep = members[0];
1215                let mut child_board = board.to_vec();
1216                child_board.push(rep);
1217                let empty_eval = [Vec::new(), Vec::new()];
1218                let child_board_eval = self
1219                    .game
1220                    .board_eval_cache
1221                    .get(&child_board)
1222                    .unwrap_or(&empty_eval);
1223                let child_cfv = self.cfr(child, reach, &child_board, child_board_eval, pass);
1224                (members, child_cfv)
1225            })
1226            .collect();
1227
1228        let mut out: [Vec<f64>; 2] = std::array::from_fn(|p| {
1229            vec![
1230                0.0;
1231                if pass.computes(p) {
1232                    self.game.combos[p].len()
1233                } else {
1234                    0
1235                }
1236            ]
1237        });
1238        for (members, rep_cfv) in &class_results {
1239            let rep = members[0];
1240            for &card in members.iter() {
1241                for p in 0..2 {
1242                    if !pass.computes(p) {
1243                        continue;
1244                    }
1245                    let values = if card == rep {
1246                        rep_cfv[p].clone()
1247                    } else {
1248                        self.game
1249                            .relabel_cfv(p, &rep_cfv[p], rep.suit(), card.suit())
1250                    };
1251                    for (
1252                        i,
1253                        &Combo {
1254                            cards: [h1, h2], ..
1255                        },
1256                    ) in self.game.combos[p].iter().enumerate()
1257                    {
1258                        if h1 != card && h2 != card {
1259                            out[p][i] += values[i];
1260                        }
1261                    }
1262                }
1263            }
1264        }
1265        for values in &mut out {
1266            for v in values {
1267                *v /= divisor;
1268            }
1269        }
1270        out
1271    }
1272}
1273
1274impl SolverGame {
1275    /// Number of regret/strategy rows (buckets, or plain combos if
1276    /// unabstracted) `player`'s combos collapse into at the given `board`.
1277    fn combo_buckets(&self, player: usize, board: &[Card]) -> (usize, &[usize]) {
1278        bucket_count_and_map(player, board, &self.bucket_maps, &self.identity_buckets)
1279    }
1280
1281    /// Values at every decision node under `policy`.
1282    ///
1283    /// Reads only the game and `policy`, so it can run while training continues and
1284    /// always describes the iteration `policy` was taken at. One call walks the
1285    /// whole tree, so call it once and index the result rather than once per node.
1286    ///
1287    /// # Examples
1288    ///
1289    /// ```
1290    /// # use native_solver::*;
1291    /// # let board = ["Ks", "Th", "7s", "4d", "2s"].iter().map(|c| c.parse()).collect::<Result<Vec<Card>, _>>()?;
1292    /// # let dead = CardSet::from_cards(&board);
1293    /// # let config = GameConfig::new(board, Chips::whole(100), Chips::whole(100)).with_bet_sizes([1.0]);
1294    /// # let ranges = ["AA,KQs", "QQ,JJ"].map(|r| r.parse::<Range>().unwrap().combos(dead));
1295    /// # let mut trainer = Trainer::new(build_tree(&config)?, ranges, TrainerOptions::default())?;
1296    /// trainer.train(100);
1297    /// let evaluation = trainer.game().evaluate(&trainer.policy());
1298    /// assert_eq!(evaluation.nodes.len(), trainer.game().num_decision_nodes());
1299    ///
1300    /// // Root values are zero-sum.
1301    /// let [oop, ip] = evaluation.root_values;
1302    /// assert!((oop + ip).abs() < 1e-6);
1303    ///
1304    /// // EV of each OOP combo at the root, in chips.
1305    /// let root_ev = &evaluation.nodes[0].ev;
1306    /// assert_eq!(root_ev.len(), trainer.game().combos(Player::Oop).len());
1307    /// # Ok::<(), Box<dyn std::error::Error>>(())
1308    /// ```
1309    pub fn evaluate(&self, policy: &Policy) -> Evaluation {
1310        let mut out = HashMap::new();
1311        let board = self.initial_board.clone();
1312        let empty_eval = [Vec::new(), Vec::new()];
1313        let board_eval = self.board_eval_cache.get(&board).unwrap_or(&empty_eval);
1314        let reach0: Vec<f64> = self.combos[0].iter().map(|c| c.weight).collect();
1315        let reach1: Vec<f64> = self.combos[1].iter().map(|c| c.weight).collect();
1316        let [cfv0, cfv1] = self.evaluate_node(
1317            policy,
1318            &self.tree.root,
1319            &[reach0, reach1],
1320            &board,
1321            board_eval,
1322            &mut out,
1323        );
1324        let ev0: f64 = cfv0
1325            .iter()
1326            .zip(&self.combos[0])
1327            .map(|(v, c)| v * c.weight)
1328            .sum();
1329        let ev1: f64 = cfv1
1330            .iter()
1331            .zip(&self.combos[1])
1332            .map(|(v, c)| v * c.weight)
1333            .sum();
1334        // `evaluate_node` visits every decision node exactly once.
1335        let nodes = (0..self.node_meta.len())
1336            .map(|id| out.remove(&id).expect("every decision node is evaluated"))
1337            .collect();
1338        Evaluation {
1339            nodes,
1340            root_values: [ev0, ev1],
1341        }
1342    }
1343
1344    /// How much a best response could gain against `policy`, in chips.
1345    ///
1346    /// Runs one best-response pass for each player against the other's policy; see
1347    /// [`Exploitability`] for the definition.
1348    pub fn exploitability(&self, policy: &Policy) -> Exploitability {
1349        let board = self.initial_board.clone();
1350        let empty_eval = [Vec::new(), Vec::new()];
1351        let board_eval = self.board_eval_cache.get(&board).unwrap_or(&empty_eval);
1352        let reach0: Vec<f64> = self.combos[0].iter().map(|c| c.weight).collect();
1353        let reach1: Vec<f64> = self.combos[1].iter().map(|c| c.weight).collect();
1354
1355        // CFVs remain unnormalized throughout recursion. Only the public
1356        // metric is an expectation over legal initial deals, rather than a
1357        // sum that changes with the size or common scale of either range.
1358        let board_set = mask_of(&board);
1359        let live = |c: &Combo| !mask_has(board_set, c.cards[0]) && !mask_has(board_set, c.cards[1]);
1360        let compatible_mass =
1361            self.terminal_index
1362                .compatible_mass(&self.combos, 0, &reach1, board_set);
1363        let joint_mass: f64 = self.combos[0]
1364            .iter()
1365            .zip(&compatible_mass)
1366            .filter(|(c, _)| live(c))
1367            .map(|(c, mass)| c.weight * mass)
1368            .sum();
1369        if !joint_mass.is_finite() || joint_mass <= 0.0 {
1370            return Exploitability {
1371                oop: f64::NAN,
1372                ip: f64::NAN,
1373                total: f64::NAN,
1374            };
1375        }
1376
1377        let br0 = self.best_response_value(
1378            policy,
1379            &self.tree.root,
1380            0,
1381            &[reach0.clone(), reach1.clone()],
1382            &board,
1383            board_eval,
1384        );
1385        let br1 = self.best_response_value(
1386            policy,
1387            &self.tree.root,
1388            1,
1389            &[reach0, reach1],
1390            &board,
1391            board_eval,
1392        );
1393        let oop = br0
1394            .iter()
1395            .zip(&self.combos[0])
1396            .filter(|(_, c)| live(c))
1397            .map(|(v, c)| v * c.weight)
1398            .sum::<f64>()
1399            / joint_mass;
1400        let ip = br1
1401            .iter()
1402            .zip(&self.combos[1])
1403            .filter(|(_, c)| live(c))
1404            .map(|(v, c)| v * c.weight)
1405            .sum::<f64>()
1406            / joint_mass;
1407        Exploitability {
1408            oop,
1409            ip,
1410            total: (oop + ip) / 2.0,
1411        }
1412    }
1413
1414    /// The betting tree this trainer is solving, e.g. to look up node ids
1415    /// by walking its structure.
1416    pub fn tree(&self) -> &Node {
1417        &self.tree.root
1418    }
1419
1420    /// The board the tree starts from ([`Tree::board`](crate::Tree::board)).
1421    pub fn board(&self) -> &[Card] {
1422        &self.tree.board
1423    }
1424
1425    /// The community cards dealt so far at decision node `node_id` (e.g.
1426    /// for display, or to label which card a `Chance` branch led through).
1427    ///
1428    /// # Panics
1429    /// Panics if `node_id` is not below [`num_decision_nodes`](Self::num_decision_nodes).
1430    pub fn node_board(&self, node_id: usize) -> &[Card] {
1431        &self.node_meta[node_id].1
1432    }
1433
1434    /// `player`'s combos, in the order of every per-combo result (the combo
1435    /// axis of `average_strategy`, [`NodeEvaluation::ev`], and so on).
1436    pub fn combos(&self, player: Player) -> &[Combo] {
1437        &self.combos[player.index()]
1438    }
1439
1440    /// The card abstraction this game was built with.
1441    pub fn abstraction(&self) -> CardAbstraction {
1442        self.abstraction
1443    }
1444
1445    /// The strategy at `node_id` under `policy`, as `[action][combo]` probabilities.
1446    ///
1447    /// Combos follow the acting player's range order. With card abstraction, every
1448    /// combo in a bucket reports the bucket's shared probabilities.
1449    ///
1450    /// # Panics
1451    /// Panics if `node_id` is not below [`num_decision_nodes`](Self::num_decision_nodes)
1452    /// or `policy` was taken from a different game.
1453    pub fn average_strategy(&self, policy: &Policy, node_id: usize) -> Vec<Vec<f64>> {
1454        self.expand_strategy(node_id, &policy.rows[node_id])
1455    }
1456
1457    /// Expands bucket rows to one probability per combo of the acting player.
1458    fn expand_strategy(&self, node_id: usize, bucket_strategy: &[Vec<f64>]) -> Vec<Vec<f64>> {
1459        let (player, board) = &self.node_meta[node_id];
1460        let (_, buckets) = self.combo_buckets(*player, board);
1461        bucket_strategy
1462            .iter()
1463            .map(|row| buckets.iter().map(|&b| row[b]).collect())
1464            .collect()
1465    }
1466
1467    /// Restores a policy saved from [`Policy::rows`].
1468    ///
1469    /// The rows must fit this game: one row set per decision node, one row per
1470    /// action, one entry per bucket, each bucket a probability distribution, and
1471    /// suit-equivalent buckets identical. Rows are used as given, so reads match
1472    /// the saved policy bit for bit. See [`Policy`] for an example.
1473    ///
1474    /// # Errors
1475    /// Returns a [`PolicyError`] naming the first node whose rows have the
1476    /// wrong count or shape, are not distributions, or are not symmetric.
1477    pub fn policy_from_rows(&self, rows: Vec<Vec<Vec<f64>>>) -> Result<Policy, PolicyError> {
1478        fn action_counts(node: &Node, out: &mut [usize]) {
1479            match node {
1480                Node::Decision {
1481                    id,
1482                    actions,
1483                    children,
1484                    ..
1485                } => {
1486                    out[*id] = actions.len();
1487                    children.iter().for_each(|child| action_counts(child, out));
1488                }
1489                Node::Chance { children } => children
1490                    .iter()
1491                    .for_each(|(_, child)| action_counts(child, out)),
1492                Node::Terminal(_) => {}
1493            }
1494        }
1495        if rows.len() != self.num_decision_nodes() {
1496            return Err(PolicyError::NodeCount {
1497                policy: rows.len(),
1498                game: self.num_decision_nodes(),
1499            });
1500        }
1501        let mut actions = vec![0; rows.len()];
1502        action_counts(&self.tree.root, &mut actions);
1503        for (id, node_rows) in rows.iter().enumerate() {
1504            let (player, board) = &self.node_meta[id];
1505            let (num_buckets, _) = self.combo_buckets(*player, board);
1506            if node_rows.len() != actions[id]
1507                || node_rows.iter().any(|row| row.len() != num_buckets)
1508            {
1509                return Err(PolicyError::Shape { node: id });
1510            }
1511            for b in 0..num_buckets {
1512                let total: f64 = node_rows.iter().map(|row| row[b]).sum();
1513                if node_rows
1514                    .iter()
1515                    .any(|row| !row[b].is_finite() || row[b] < 0.0)
1516                    || (total - 1.0).abs() > 1e-9
1517                {
1518                    return Err(PolicyError::NotDistribution { node: id });
1519                }
1520            }
1521            if let Some(groups) = self.suit_groups.get(board) {
1522                let asymmetric = groups[*player].iter().any(|group| {
1523                    node_rows.iter().any(|row| {
1524                        group
1525                            .iter()
1526                            .any(|&b| row[b].to_bits() != row[group[0]].to_bits())
1527                    })
1528                });
1529                if asymmetric {
1530                    return Err(PolicyError::NotSymmetric { node: id });
1531                }
1532            }
1533        }
1534        Ok(Policy { rows })
1535    }
1536
1537    /// Each combo's bucket, per board and player, sorted by board.
1538    ///
1539    /// Empty when no street is bucketed. A saved policy can use it to check that
1540    /// its rows still describe the same hands.
1541    pub fn bucket_assignments(&self) -> Vec<(&[Card], &[Vec<usize>; 2])> {
1542        let mut maps: Vec<_> = self
1543            .bucket_maps
1544            .iter()
1545            .map(|(board, maps)| (board.as_slice(), maps))
1546            .collect();
1547        maps.sort_unstable_by(|a, b| a.0.cmp(b.0));
1548        maps
1549    }
1550
1551    /// Number of decision nodes (valid `node_id`s are `0..num_decision_nodes`).
1552    pub fn num_decision_nodes(&self) -> usize {
1553        self.node_meta.len()
1554    }
1555
1556    fn symmetrize_strategy(&self, id: usize, strategy: &mut [Vec<f64>]) {
1557        let (player, board) = &self.node_meta[id];
1558        if let Some(groups) = self.suit_groups.get(board) {
1559            for group in &groups[*player] {
1560                for row in strategy.iter_mut() {
1561                    let probability =
1562                        group.iter().map(|&i| row[i]).sum::<f64>() / group.len() as f64;
1563                    for &i in group {
1564                        row[i] = probability;
1565                    }
1566                }
1567            }
1568        }
1569    }
1570
1571    /// Re-expresses `rep_cfv` (computed with the class representative
1572    /// dealt, i.e. under a board whose newest card has suit `suit_a`) as
1573    /// the cfv for a board whose newest card is the same rank but suit
1574    /// `suit_b` instead: swapping `suit_a`/`suit_b` on both players' cards
1575    /// leaves the tree structure and every hand-strength comparison
1576    /// unchanged (both suits were free before this deal, so the swap fixes
1577    /// the rest of the board), so combo `j`'s cfv under the `suit_b`
1578    /// version equals the representative's cfv for whichever combo `j`
1579    /// becomes after swapping its two cards' suits.
1580    fn relabel_cfv(&self, player: usize, rep_cfv: &[f64], suit_a: u8, suit_b: u8) -> Vec<f64> {
1581        self.combos[player]
1582            .iter()
1583            .map(
1584                |&Combo {
1585                     cards: [h1, h2], ..
1586                 }| {
1587                    let s1 = swap_suit(h1, suit_a, suit_b);
1588                    let s2 = swap_suit(h2, suit_a, suit_b);
1589                    let idx = self.combo_index[player][&normalize_pair(s1, s2)];
1590                    rep_cfv[idx]
1591                },
1592            )
1593            .collect()
1594    }
1595
1596    /// `evaluate()`'s recursion — mirrors `cfr()`'s structure (same
1597    /// [`Terminal`]/`Chance`/`Decision` handling), but reads the fixed
1598    /// `average_strategy` at each decision node instead of computing a
1599    /// "current" one via regret matching, and never touches `node_data`.
1600    /// `terminal_value` doesn't need a parallel version — it's already
1601    /// policy-agnostic, depending only on the `reach` and `board_eval`
1602    /// threaded down to it, not on how the strategy that produced `reach`
1603    /// was obtained.
1604    ///
1605    /// `average_strategy` already expands any river/flop/turn bucketing
1606    /// back out to one probability per real combo (see its own doc
1607    /// comment), so — unlike `cfr()`'s training branch — this never needs
1608    /// bucket-aware weighting: every combo's regret/EV here is already
1609    /// fully independent, matching the pre-abstraction per-combo design.
1610    fn evaluate_node(
1611        &self,
1612        policy: &Policy,
1613        node: &Node,
1614        reach: &[Vec<f64>; 2],
1615        board: &[Card],
1616        board_eval: &[Vec<u32>; 2],
1617        out: &mut HashMap<usize, NodeEvaluation>,
1618    ) -> [Vec<f64>; 2] {
1619        match node {
1620            Node::Terminal(t) => self.terminal_value(t, reach, board, board_eval),
1621            Node::Chance { children } => {
1622                self.evaluate_chance_value(policy, children, reach, board, out)
1623            }
1624            Node::Decision {
1625                id,
1626                player,
1627                children,
1628                ..
1629            } => {
1630                let p = player.index();
1631                let num_own_combos = self.combos[p].len();
1632                let num_other_combos = self.combos[1 - p].len();
1633                let strategy = self.average_strategy(policy, *id);
1634
1635                let child_cfvs: Vec<[Vec<f64>; 2]> = children
1636                    .iter()
1637                    .enumerate()
1638                    .map(|(a, child)| {
1639                        let mut child_reach = reach.clone();
1640                        for i in 0..num_own_combos {
1641                            child_reach[p][i] *= strategy[a][i];
1642                        }
1643                        self.evaluate_node(policy, child, &child_reach, board, board_eval, out)
1644                    })
1645                    .collect();
1646
1647                let mut own_ev = vec![0.0; num_own_combos];
1648                let mut other_ev = vec![0.0; num_other_combos];
1649                for (a, cfv) in child_cfvs.iter().enumerate() {
1650                    let own = &cfv[p];
1651                    let other = &cfv[1 - p];
1652                    for i in 0..num_own_combos {
1653                        own_ev[i] += strategy[a][i] * own[i];
1654                    }
1655                    for (j, v) in other_ev.iter_mut().enumerate() {
1656                        *v += other[j];
1657                    }
1658                }
1659
1660                let equity = if board.len() == 5 {
1661                    Some(self.equity_at_node(p, reach, board, board_eval))
1662                } else {
1663                    None
1664                };
1665
1666                // `own_ev` here is still a raw counterfactual value: a SUM
1667                // weighted by the opponent's *unnormalized* reach across all
1668                // their live combos (the convention used throughout this
1669                // module — see `showdown_cfv`/`terminal_value`/`chance_value`),
1670                // not a human-meaningful "expected value of holding this
1671                // exact combo". By CFR's `v(I) = pi_{-i}(I) * u_i(sigma|I)`
1672                // identity, dividing by the opponent's total live reach
1673                // (`non_conflicting_reach_sum`, the same board/hand-blocking
1674                // exclusion `equity_at_node` already applies) recovers the
1675                // true per-combo expected value for display. Only the
1676                // *stored* value is normalized this way — the *returned*
1677                // own_ev/other_ev must stay in the raw convention so the
1678                // parent's own weighted-sum aggregation and the chance-node
1679                // relabeling stay correct.
1680                let board_set = mask_of(board);
1681                let compatible_mass =
1682                    self.terminal_index
1683                        .compatible_mass(&self.combos, p, &reach[1 - p], board_set);
1684                let display_ev: Vec<f64> = (0..num_own_combos)
1685                    .map(|i| {
1686                        let denom = compatible_mass[i];
1687                        if denom > 0.0 {
1688                            own_ev[i] / denom
1689                        } else {
1690                            0.0
1691                        }
1692                    })
1693                    .collect();
1694                out.insert(
1695                    *id,
1696                    NodeEvaluation {
1697                        ev: display_ev,
1698                        equity,
1699                    },
1700                );
1701
1702                if p == 0 {
1703                    [own_ev, other_ev]
1704                } else {
1705                    [other_ev, own_ev]
1706                }
1707            }
1708        }
1709    }
1710
1711    /// `evaluate_node`'s counterpart to `chance_value`: same
1712    /// suit-isomorphism relabeling (see that function's doc comment for
1713    /// why a class's non-representative members can't just reuse the
1714    /// representative's own values unchanged), but recursing via
1715    /// `evaluate_node` instead of `cfr`.
1716    fn evaluate_chance_value(
1717        &self,
1718        policy: &Policy,
1719        children: &[(Vec<Card>, Node)],
1720        reach: &[Vec<f64>; 2],
1721        board: &[Card],
1722        out: &mut HashMap<usize, NodeEvaluation>,
1723    ) -> [Vec<f64>; 2] {
1724        let n: usize = children.iter().map(|(members, _)| members.len()).sum();
1725        let divisor = (n as f64) - 4.0;
1726
1727        let class_results: Vec<(&Vec<Card>, [Vec<f64>; 2])> = children
1728            .iter()
1729            .map(|(members, child)| {
1730                let rep = members[0];
1731                let mut child_board = board.to_vec();
1732                child_board.push(rep);
1733                let empty_eval = [Vec::new(), Vec::new()];
1734                let child_board_eval = self
1735                    .board_eval_cache
1736                    .get(&child_board)
1737                    .unwrap_or(&empty_eval);
1738                let child_cfv =
1739                    self.evaluate_node(policy, child, reach, &child_board, child_board_eval, out);
1740                (members, child_cfv)
1741            })
1742            .collect();
1743
1744        let mut cfv0 = vec![0.0; self.combos[0].len()];
1745        let mut cfv1 = vec![0.0; self.combos[1].len()];
1746
1747        for (members, rep_cfv) in &class_results {
1748            let rep = members[0];
1749            for &card in members.iter() {
1750                let (cfv0_card, cfv1_card) = if card == rep {
1751                    (rep_cfv[0].clone(), rep_cfv[1].clone())
1752                } else {
1753                    (
1754                        self.relabel_cfv(0, &rep_cfv[0], rep.suit(), card.suit()),
1755                        self.relabel_cfv(1, &rep_cfv[1], rep.suit(), card.suit()),
1756                    )
1757                };
1758                for (
1759                    i,
1760                    &Combo {
1761                        cards: [h1, h2], ..
1762                    },
1763                ) in self.combos[0].iter().enumerate()
1764                {
1765                    if h1 != card && h2 != card {
1766                        cfv0[i] += cfv0_card[i];
1767                    }
1768                }
1769                for (
1770                    j,
1771                    &Combo {
1772                        cards: [h1, h2], ..
1773                    },
1774                ) in self.combos[1].iter().enumerate()
1775                {
1776                    if h1 != card && h2 != card {
1777                        cfv1[j] += cfv1_card[j];
1778                    }
1779                }
1780            }
1781        }
1782
1783        for v in &mut cfv0 {
1784            *v /= divisor;
1785        }
1786        for v in &mut cfv1 {
1787            *v /= divisor;
1788        }
1789        [cfv0, cfv1]
1790    }
1791
1792    /// One player (`x`)'s counterfactual value when `x` plays a perfect
1793    /// best response — for each of `x`'s own combos independently, the
1794    /// single action maximizing that combo's value, no mixing — against the
1795    /// *other* player's fixed `average_strategy` everywhere else in the
1796    /// tree. Structurally this is `evaluate_node` specialized to only ever
1797    /// report `x`'s own side: at a decision node belonging to the other
1798    /// player, it's exactly `evaluate_node`'s "other" (non-acting) output,
1799    /// since that's already an unweighted sum across actions (the
1800    /// opponent's `average_strategy` weighting is baked in via the
1801    /// `child_reach` scaling before recursing, same as there); at `x`'s own
1802    /// decision nodes, the analogous weighted-average is replaced with a
1803    /// per-combo `max` over the actions' returned values. `terminal_value`
1804    /// is reused unchanged (policy-agnostic, see `evaluate_node`'s doc
1805    /// comment) and `x`'s own reach is threaded down unmodified at `x`'s own
1806    /// nodes — `terminal_value` never reads a player's *own* reach for that
1807    /// player's own cfv (only the opponent's, to weight how likely the
1808    /// opponent was to actually play into this node — see
1809    /// `non_conflicting_reach_sum`'s callers), so unlike `evaluate_node`,
1810    /// which needs both sides' cfv and hence both sides' reach scaled
1811    /// correctly, this only ever needs the *non-deviating* player's reach
1812    /// threaded correctly.
1813    fn best_response_value(
1814        &self,
1815        policy: &Policy,
1816        node: &Node,
1817        x: usize,
1818        reach: &[Vec<f64>; 2],
1819        board: &[Card],
1820        board_eval: &[Vec<u32>; 2],
1821    ) -> Vec<f64> {
1822        match node {
1823            Node::Terminal(t) => {
1824                self.terminal_value_for_player(t, x, &reach[1 - x], board, board_eval)
1825            }
1826            Node::Chance { children } => {
1827                self.best_response_chance_value(policy, children, x, reach, board)
1828            }
1829            Node::Decision {
1830                id,
1831                player,
1832                children,
1833                ..
1834            } => {
1835                let p = player.index();
1836                if p == x {
1837                    let num_own_combos = self.combos[x].len();
1838                    let child_vals: Vec<Vec<f64>> = children
1839                        .par_iter()
1840                        .map(|child| {
1841                            self.best_response_value(policy, child, x, reach, board, board_eval)
1842                        })
1843                        .collect();
1844                    (0..num_own_combos)
1845                        .map(|i| {
1846                            child_vals
1847                                .iter()
1848                                .map(|v| v[i])
1849                                .fold(f64::NEG_INFINITY, f64::max)
1850                        })
1851                        .collect()
1852                } else {
1853                    let num_opp_combos = self.combos[p].len();
1854                    let strategy = self.average_strategy(policy, *id);
1855                    let child_vals: Vec<Vec<f64>> = children
1856                        .par_iter()
1857                        .enumerate()
1858                        .map(|(a, child)| {
1859                            let mut child_reach = reach.clone();
1860                            for i in 0..num_opp_combos {
1861                                child_reach[p][i] *= strategy[a][i];
1862                            }
1863                            self.best_response_value(
1864                                policy,
1865                                child,
1866                                x,
1867                                &child_reach,
1868                                board,
1869                                board_eval,
1870                            )
1871                        })
1872                        .collect();
1873                    let num_own_combos = self.combos[x].len();
1874                    let mut out = vec![0.0; num_own_combos];
1875                    for v in &child_vals {
1876                        for (i, val) in v.iter().enumerate() {
1877                            out[i] += val;
1878                        }
1879                    }
1880                    out
1881                }
1882            }
1883        }
1884    }
1885
1886    /// `best_response_value`'s counterpart to `chance_value`/
1887    /// `evaluate_chance_value`: same suit-isomorphism relabeling (only the
1888    /// class representative is actually recursed into; other members reuse
1889    /// `relabel_cfv`), specialized to the single player `x` whose
1890    /// best-response value this whole pass tracks.
1891    fn best_response_chance_value(
1892        &self,
1893        policy: &Policy,
1894        children: &[(Vec<Card>, Node)],
1895        x: usize,
1896        reach: &[Vec<f64>; 2],
1897        board: &[Card],
1898    ) -> Vec<f64> {
1899        let n: usize = children.iter().map(|(members, _)| members.len()).sum();
1900        let divisor = (n as f64) - 4.0;
1901
1902        let class_results: Vec<(&Vec<Card>, Vec<f64>)> = children
1903            .par_iter()
1904            .map(|(members, child)| {
1905                let rep = members[0];
1906                let mut child_board = board.to_vec();
1907                child_board.push(rep);
1908                let empty_eval = [Vec::new(), Vec::new()];
1909                let child_board_eval = self
1910                    .board_eval_cache
1911                    .get(&child_board)
1912                    .unwrap_or(&empty_eval);
1913                let child_val = self.best_response_value(
1914                    policy,
1915                    child,
1916                    x,
1917                    reach,
1918                    &child_board,
1919                    child_board_eval,
1920                );
1921                (members, child_val)
1922            })
1923            .collect();
1924
1925        let mut out = vec![0.0; self.combos[x].len()];
1926        for (members, rep_val) in &class_results {
1927            let rep = members[0];
1928            for &card in members.iter() {
1929                let val_card = if card == rep {
1930                    rep_val.clone()
1931                } else {
1932                    self.relabel_cfv(x, rep_val, rep.suit(), card.suit())
1933                };
1934                for (
1935                    i,
1936                    &Combo {
1937                        cards: [h1, h2], ..
1938                    },
1939                ) in self.combos[x].iter().enumerate()
1940                {
1941                    if h1 != card && h2 != card {
1942                        out[i] += val_card[i];
1943                    }
1944                }
1945            }
1946        }
1947        for v in &mut out {
1948            *v /= divisor;
1949        }
1950        out
1951    }
1952
1953    /// Raw showdown win probability for each of `player`'s combos against
1954    /// the opponent's `reach`-weighted range at this node — only valid
1955    /// (and only ever called) once `board_eval` is a complete board's real
1956    /// [`evaluate_7`](crate::evaluate_7) scores. Excludes opponent combos blocked by the hero's
1957    /// own two cards *and* ones that physically conflict with the board
1958    /// (same exclusion `showdown_cfv` uses — without it, a phantom
1959    /// opponent combo could still be assigned nonzero weight here even
1960    /// though `reach` was never masked for it, since that masking only
1961    /// ever happens inside bucket-merge aggregation during training, not
1962    /// in this reach vector itself).
1963    fn equity_at_node(
1964        &self,
1965        player: usize,
1966        reach: &[Vec<f64>; 2],
1967        board: &[Card],
1968        board_eval: &[Vec<u32>; 2],
1969    ) -> Vec<f64> {
1970        let board_set = mask_of(board);
1971        let positive_reach: Vec<f64> = reach[1 - player]
1972            .iter()
1973            .map(|&r| if r <= 0.0 { 0.0 } else { r })
1974            .collect();
1975        let mass =
1976            self.terminal_index
1977                .compatible_mass(&self.combos, player, &positive_reach, board_set);
1978        let net = self.terminal_index.showdown(
1979            &self.combos,
1980            player,
1981            &positive_reach,
1982            board_eval,
1983            &self.board_order_cache[board],
1984            board_set,
1985            &[1.0, 1.0],
1986        );
1987        net.iter()
1988            .zip(mass)
1989            .map(|(net, mass)| {
1990                if mass > 0.0 {
1991                    0.5 + 0.5 * net / mass
1992                } else {
1993                    0.5
1994                }
1995            })
1996            .collect()
1997    }
1998
1999    fn terminal_value(
2000        &self,
2001        t: &Terminal,
2002        reach: &[Vec<f64>; 2],
2003        board: &[Card],
2004        board_eval: &[Vec<u32>; 2],
2005    ) -> [Vec<f64>; 2] {
2006        [
2007            self.terminal_value_for_player(t, 0, &reach[1], board, board_eval),
2008            self.terminal_value_for_player(t, 1, &reach[0], board, board_eval),
2009        ]
2010    }
2011
2012    fn terminal_value_for_player(
2013        &self,
2014        t: &Terminal,
2015        player: usize,
2016        reach_opp: &[f64],
2017        board: &[Card],
2018        board_eval: &[Vec<u32>; 2],
2019    ) -> Vec<f64> {
2020        #[cfg(test)]
2021        self.terminal_calls[player].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2022        let board_set = mask_of(board);
2023        #[cfg(test)]
2024        if self
2025            .use_pairwise_terminals
2026            .load(std::sync::atomic::Ordering::Relaxed)
2027        {
2028            return (0..self.combos[player].len())
2029                .map(|i| {
2030                    let [a, b] = self.combos[player][i].cards;
2031                    if mask_has(board_set, a) || mask_has(board_set, b) {
2032                        return 0.0;
2033                    }
2034                    match t {
2035                        Terminal::Fold { winner, invested } => {
2036                            let value = if winner.index() == player {
2037                                invested[1 - player]
2038                            } else {
2039                                -invested[player]
2040                            };
2041                            value * self.non_conflicting_reach_sum(player, i, reach_opp, board_set)
2042                        }
2043                        Terminal::Showdown { invested } => {
2044                            self.showdown_cfv(player, i, invested, reach_opp, board_eval, board_set)
2045                        }
2046                    }
2047                })
2048                .collect();
2049        }
2050        match t {
2051            Terminal::Fold { winner, invested } => {
2052                let value = if winner.index() == player {
2053                    invested[1 - player]
2054                } else {
2055                    -invested[player]
2056                };
2057                self.terminal_index
2058                    .compatible_mass(&self.combos, player, reach_opp, board_set)
2059                    .into_iter()
2060                    .map(|mass| value * mass)
2061                    .collect()
2062            }
2063            Terminal::Showdown { invested } => self.terminal_index.showdown(
2064                &self.combos,
2065                player,
2066                reach_opp,
2067                board_eval,
2068                &self.board_order_cache[board],
2069                board_set,
2070                invested,
2071            ),
2072        }
2073    }
2074
2075    /// Sums `reach_opp` over the opponent's combos that are actually live
2076    /// against `player`'s own combo `combo_idx`: not blocked by `player`'s
2077    /// two hole cards, *and* not physically impossible given `board_set`
2078    /// (an opponent combo whose card was itself dealt onto the board this
2079    /// branch can never really be held here — see `chance_value`'s doc
2080    /// comment on the "N-4" private-deal normalization this complements. Without this
2081    /// check a board-conflicting opponent combo would still contribute its
2082    /// full reach weight to this terminal, breaking the zero-sum
2083    /// invariant).
2084    #[cfg(test)]
2085    fn non_conflicting_reach_sum(
2086        &self,
2087        player: usize,
2088        combo_idx: usize,
2089        reach_opp: &[f64],
2090        board_set: u64,
2091    ) -> f64 {
2092        let opp = 1 - player;
2093        let [h1, h2] = self.combos[player][combo_idx].cards;
2094        self.combos[opp]
2095            .iter()
2096            .zip(reach_opp)
2097            .filter(
2098                |(
2099                    Combo {
2100                        cards: [v1, v2], ..
2101                    },
2102                    _,
2103                )| {
2104                    *v1 != h1
2105                        && *v1 != h2
2106                        && *v2 != h1
2107                        && *v2 != h2
2108                        && !mask_has(board_set, *v1)
2109                        && !mask_has(board_set, *v2)
2110                },
2111            )
2112            .map(|(_, &r)| r)
2113            .sum()
2114    }
2115
2116    /// Same board-conflict exclusion as `non_conflicting_reach_sum`,
2117    /// applied to the opponent combos aggregated over for a showdown value
2118    /// (see that function's doc comment).
2119    #[cfg(test)]
2120    fn showdown_cfv(
2121        &self,
2122        player: usize,
2123        combo_idx: usize,
2124        invested: &[f64; 2],
2125        reach_opp: &[f64],
2126        board_eval: &[Vec<u32>; 2],
2127        board_set: u64,
2128    ) -> f64 {
2129        let opp = 1 - player;
2130        let [h1, h2] = self.combos[player][combo_idx].cards;
2131        let hero_score = board_eval[player][combo_idx];
2132        let mut cfv = 0.0;
2133        for (
2134            j,
2135            &Combo {
2136                cards: [v1, v2], ..
2137            },
2138        ) in self.combos[opp].iter().enumerate()
2139        {
2140            if v1 == h1 || v1 == h2 || v2 == h1 || v2 == h2 {
2141                continue;
2142            }
2143            if mask_has(board_set, v1) || mask_has(board_set, v2) {
2144                continue;
2145            }
2146            let villain_score = board_eval[opp][j];
2147            let net = match hero_score.cmp(&villain_score) {
2148                std::cmp::Ordering::Greater => invested[opp],
2149                std::cmp::Ordering::Less => -invested[player],
2150                std::cmp::Ordering::Equal => (invested[opp] - invested[player]) / 2.0,
2151            };
2152            cfv += reach_opp[j] * net;
2153        }
2154        cfv
2155    }
2156}
2157
2158/// `(min(c1,c2), max(c1,c2))`, the order-independent key `combo_index` and
2159/// `relabel_cfv` use to look up a combo regardless of the tuple order
2160/// `range::hand_combos` happened to store it in.
2161fn normalize_pair(c1: Card, c2: Card) -> (Card, Card) {
2162    if c1 <= c2 {
2163        (c1, c2)
2164    } else {
2165        (c2, c1)
2166    }
2167}
2168
2169fn build_combo_index(combos: &[Combo]) -> HashMap<(Card, Card), usize> {
2170    combos
2171        .iter()
2172        .enumerate()
2173        .map(
2174            |(
2175                i,
2176                &Combo {
2177                    cards: [c1, c2], ..
2178                },
2179            )| (normalize_pair(c1, c2), i),
2180        )
2181        .collect()
2182}
2183
2184/// `card` with its suit swapped to the other side of the `suit_a`/`suit_b`
2185/// transposition (identity if `card` uses neither suit).
2186fn swap_suit(card: Card, suit_a: u8, suit_b: u8) -> Card {
2187    let s = card.suit();
2188    let new_suit = if s == suit_a {
2189        suit_b
2190    } else if s == suit_b {
2191        suit_a
2192    } else {
2193        s
2194    };
2195    Card(card.rank() * 4 + new_suit)
2196}
2197
2198/// [`evaluate_7`](crate::evaluate_7) scores for every combo, if `board` is a complete 5-card
2199/// board — otherwise empty (no [`Terminal::Showdown`] is ever reachable with
2200/// an incomplete board, so it's never read in that case).
2201///
2202/// A combo whose hole card was itself dealt as one of `board`'s later
2203/// (post-initial-deal) cards is physically impossible for this specific
2204/// board — `chance_value`'s per-node exclusion check always drops such a
2205/// combo from every aggregate sum before it reaches the root (that's the
2206/// whole point of the "N-4" private-deal normalization this module's doc comment
2207/// describes), so its score here is never actually read. Skipping
2208/// [`evaluate_7`](crate::evaluate_7) for it (sentinel `0`) avoids feeding it a 7-card hand that
2209/// can't occur in reality — e.g. a pocket-pair combo whose two ranks-match
2210/// a rank that also completes trips/quads on the board, which pushes one
2211/// rank to 5 "occurrences" among the 7 cards, a pattern `eval::evaluate_5`'s
2212/// lookup table correctly never populates (impossible with 4 suits/rank).
2213fn eval_combos_if_complete(combos: &[Vec<Combo>; 2], board: &[Card]) -> [Vec<u32>; 2] {
2214    if board.len() != 5 {
2215        return [Vec::new(), Vec::new()];
2216    }
2217    let board_set = mask_of(board);
2218    let score = |combo: &Combo| {
2219        if mask_has(board_set, combo.cards[0]) || mask_has(board_set, combo.cards[1]) {
2220            return 0;
2221        }
2222        score_7([
2223            combo.cards[0],
2224            combo.cards[1],
2225            board[0],
2226            board[1],
2227            board[2],
2228            board[3],
2229            board[4],
2230        ])
2231    };
2232    [
2233        combos[0].iter().map(score).collect(),
2234        combos[1].iter().map(score).collect(),
2235    ]
2236}
2237
2238/// Walks every `Chance` branch once, filling `cache` with the
2239/// [`evaluate_7`](crate::evaluate_7) scores for each complete board reachable from `board`.
2240fn precompute_board_eval(
2241    node: &Node,
2242    board: &[Card],
2243    combos: &[Vec<Combo>; 2],
2244    cache: &mut HashMap<Vec<Card>, [Vec<u32>; 2]>,
2245) {
2246    match node {
2247        Node::Decision { children, .. } => {
2248            for child in children {
2249                precompute_board_eval(child, board, combos, cache);
2250            }
2251        }
2252        Node::Chance { children } => {
2253            for (members, child) in children {
2254                // Only the class representative is actually recursed into
2255                // by `chance_value` — other members' values are derived by
2256                // relabeling, never by looking up their own board here.
2257                let rep = members[0];
2258                let mut child_board = board.to_vec();
2259                child_board.push(rep);
2260                cache
2261                    .entry(child_board.clone())
2262                    .or_insert_with(|| eval_combos_if_complete(combos, &child_board));
2263                precompute_board_eval(child, &child_board, combos, cache);
2264            }
2265        }
2266        Node::Terminal(_) => {}
2267    }
2268}
2269
2270/// Every board a `Decision` node is ever actually built at, below `board`
2271/// (not including `board` itself — callers that need the starting board
2272/// too, e.g. a solve beginning already at the target street, add it
2273/// separately). Mirrors `precompute_board_eval`'s representative-only
2274/// descent through `Chance` nodes for the same reason: those are the only
2275/// boards `cfr()` ever recurses into.
2276fn collect_reachable_boards(
2277    node: &Node,
2278    board: &[Card],
2279    acc: &mut std::collections::HashSet<Vec<Card>>,
2280) {
2281    match node {
2282        Node::Decision { children, .. } => {
2283            for child in children {
2284                collect_reachable_boards(child, board, acc);
2285            }
2286        }
2287        Node::Chance { children } => {
2288            for (members, child) in children {
2289                let rep = members[0];
2290                let mut child_board = board.to_vec();
2291                child_board.push(rep);
2292                acc.insert(child_board.clone());
2293                collect_reachable_boards(child, &child_board, acc);
2294            }
2295        }
2296        Node::Terminal(_) => {}
2297    }
2298}
2299
2300/// Splits combos into `num_buckets` contiguous, roughly-equal-sized groups
2301/// by score percentile (river: real [`evaluate_7`](crate::evaluate_7) scores; flop/turn:
2302/// `avg_score`'s future-score expectation) — sorting by score and cutting
2303/// every `n / num_buckets`-th combo keeps the assignment monotonic (a
2304/// higher-scoring combo never lands in a lower bucket than a
2305/// lower-scoring one). When `num_buckets >= scores.len()` this reduces to
2306/// an exact bijection (every combo its own bucket, in score order) — the
2307/// baseline [`CardAbstraction`]'s per-street `Some(n)` for large `n` needs
2308/// to behave identically to `None`.
2309fn compute_percentile_buckets(scores: &[f64], num_buckets: usize) -> Vec<usize> {
2310    let n = scores.len();
2311    if n == 0 {
2312        return Vec::new();
2313    }
2314    let num_buckets = num_buckets.clamp(1, n);
2315    let mut order: Vec<usize> = (0..n).collect();
2316    order.sort_by(|&i, &j| scores[i].partial_cmp(&scores[j]).unwrap());
2317    let mut bucket_of = vec![0usize; n];
2318    for (rank, &i) in order.iter().enumerate() {
2319        bucket_of[i] = rank * num_buckets / n;
2320        // Never split a run of exactly-equal scores across a bucket
2321        // boundary: two combos this function scores identically are often
2322        // suit-swap-equivalent under `avg_score`'s isomorphism-class
2323        // averaging (or the river's raw `evaluate_7` tie), and
2324        // `chance_value`'s relabeling assumes such combos always share
2325        // the exact same strategy — a boundary landing mid-tie would
2326        // silently break that invariant.
2327        if rank > 0 && scores[i] == scores[order[rank - 1]] {
2328            bucket_of[i] = bucket_of[order[rank - 1]];
2329        }
2330    }
2331    bucket_of
2332}
2333
2334/// Each combo's expected [`evaluate_7`](crate::evaluate_7) score from `board` through to the
2335/// river, averaged over future streets — the proxy [`CardAbstraction`]'s
2336/// flop/turn bucketing ranks combos by, since (unlike the river) their
2337/// hand isn't final yet. This is coarser than true equity: it's a plain
2338/// average of the eventual showdown *score*, not a win probability against
2339/// an opponent range, so it doesn't capture *how* a hand realizes its
2340/// value (e.g. a made hand with no more equity to gain and a drawing hand
2341/// with the same average score play very differently in reality) — but it
2342/// reuses the exact [`evaluate_7`](crate::evaluate_7) machinery already computed for real
2343/// showdowns, needs no separate equity engine, and preserves the right
2344/// ordering for the common case (stronger hands now tend to stay stronger).
2345///
2346/// Always groups future deals by suit-isomorphism class (`deal_classes`
2347/// with `suit_isomorphism: true`) regardless of whether the *tree* itself
2348/// was built with isomorphism — grouping same-rank free-suit cards is
2349/// always a valid equivalence, so this one-time precomputation is cheaper
2350/// this way, and when the tree *was* isomorphism-reduced this also means
2351/// every board it visits at the base case is already in `board_eval_cache`
2352/// (zero redundant [`evaluate_7`](crate::evaluate_7) calls beyond what training needs anyway).
2353fn avg_score(
2354    board: &[Card],
2355    combos: &[Vec<Combo>; 2],
2356    combo_index: &[HashMap<(Card, Card), usize>; 2],
2357    board_eval_cache: &HashMap<Vec<Card>, [Vec<u32>; 2]>,
2358    cache: &mut HashMap<Vec<Card>, [Vec<f64>; 2]>,
2359) -> [Vec<f64>; 2] {
2360    if let Some(v) = cache.get(board) {
2361        return v.clone();
2362    }
2363    let result = if board.len() == 5 {
2364        let scores = match board_eval_cache.get(board) {
2365            Some(scores) => scores.clone(),
2366            None => eval_combos_if_complete(combos, board),
2367        };
2368        [
2369            scores[0].iter().map(|&s| s as f64).collect(),
2370            scores[1].iter().map(|&s| s as f64).collect(),
2371        ]
2372    } else {
2373        let mut sum = [vec![0.0; combos[0].len()], vec![0.0; combos[1].len()]];
2374        let mut weight = [vec![0.0; combos[0].len()], vec![0.0; combos[1].len()]];
2375        for members in super::tree::deal_classes(true, board) {
2376            let rep = members[0];
2377            let mut next_board = board.to_vec();
2378            next_board.push(rep);
2379            // `child[p][i]` is the real (or further-averaged) score for
2380            // combo `i` under board+`rep` specifically. For any *other*
2381            // class member `m`, a fixed combo's score under board+`m`
2382            // isn't `child[p][i]` (the two boards aren't the same!) — it's
2383            // `child`'s value for whichever combo `i` becomes after
2384            // swapping `rep`'s suit with `m`'s (the same relabeling
2385            // `chance_value`/`relabel_cfv` uses, for the same reason: that
2386            // suit swap is the symmetry that maps board+`m` to board+`rep`).
2387            let child = avg_score(&next_board, combos, combo_index, board_eval_cache, cache);
2388            for &m in &members {
2389                let (suit_a, suit_b) = (rep.suit(), m.suit());
2390                for p in 0..2 {
2391                    for (
2392                        i,
2393                        &Combo {
2394                            cards: [h1, h2], ..
2395                        },
2396                    ) in combos[p].iter().enumerate()
2397                    {
2398                        if h1 == m || h2 == m {
2399                            continue; // this combo can't coexist with m being dealt
2400                        }
2401                        let idx = if m == rep {
2402                            i
2403                        } else {
2404                            let s1 = swap_suit(h1, suit_a, suit_b);
2405                            let s2 = swap_suit(h2, suit_a, suit_b);
2406                            combo_index[p][&normalize_pair(s1, s2)]
2407                        };
2408                        sum[p][i] += child[p][idx];
2409                        weight[p][i] += 1.0;
2410                    }
2411                }
2412            }
2413        }
2414        [
2415            sum[0]
2416                .iter()
2417                .zip(&weight[0])
2418                .map(|(&s, &w)| if w > 0.0 { s / w } else { 0.0 })
2419                .collect(),
2420            sum[1]
2421                .iter()
2422                .zip(&weight[1])
2423                .map(|(&s, &w)| if w > 0.0 { s / w } else { 0.0 })
2424                .collect(),
2425        ]
2426    };
2427    cache.insert(board.to_vec(), result.clone());
2428    result
2429}
2430
2431/// `player`'s bucket count and combo->bucket map at `board`: the
2432/// precomputed river map if one exists there, else the identity fallback
2433/// (every combo its own bucket — non-river nodes, or `river_buckets: None`).
2434fn bucket_count_and_map<'a>(
2435    player: usize,
2436    board: &[Card],
2437    bucket_maps: &'a HashMap<Vec<Card>, [Vec<usize>; 2]>,
2438    identity_buckets: &'a [Vec<usize>; 2],
2439) -> (usize, &'a [usize]) {
2440    match bucket_maps.get(board) {
2441        Some(maps) => {
2442            let map = &maps[player];
2443            let num_buckets = map.iter().copied().max().map_or(0, |m| m + 1);
2444            (num_buckets, map)
2445        }
2446        None => (identity_buckets[player].len(), &identity_buckets[player]),
2447    }
2448}
2449
2450/// Walks the tree threading `board` (mirroring `precompute_board_eval`'s
2451/// representative-only descent through `Chance` nodes) to size each
2452/// decision node's regret/strategy tables by its actual bucket count and
2453/// record `(player, board)` in `node_meta` for `average_strategy` to use.
2454fn init_node_data(
2455    node: &Node,
2456    board: &[Card],
2457    bucket_maps: &HashMap<Vec<Card>, [Vec<usize>; 2]>,
2458    identity_buckets: &[Vec<usize>; 2],
2459    out: &mut [NodeData],
2460    node_meta: &mut [(usize, Vec<Card>)],
2461) {
2462    match node {
2463        Node::Decision {
2464            id,
2465            player,
2466            actions,
2467            children,
2468        } => {
2469            let p = player.index();
2470            let (num_buckets, _) = bucket_count_and_map(p, board, bucket_maps, identity_buckets);
2471            out[*id] = NodeData::sized(actions.len(), num_buckets);
2472            node_meta[*id] = (p, board.to_vec());
2473            for child in children {
2474                init_node_data(child, board, bucket_maps, identity_buckets, out, node_meta);
2475            }
2476        }
2477        Node::Chance { children } => {
2478            for (members, child) in children {
2479                let rep = members[0];
2480                let mut child_board = board.to_vec();
2481                child_board.push(rep);
2482                init_node_data(
2483                    child,
2484                    &child_board,
2485                    bucket_maps,
2486                    identity_buckets,
2487                    out,
2488                    node_meta,
2489                );
2490            }
2491        }
2492        Node::Terminal(_) => {}
2493    }
2494}
2495
2496#[cfg(test)]
2497mod tests {
2498    use super::*;
2499    use crate::card::Card;
2500    use crate::range::Range;
2501    use crate::solver::tree::{build_tree, GameConfig};
2502    use crate::solver::Chips;
2503
2504    #[test]
2505    fn dcfr_discounts_once_per_bucket_after_adding_the_full_iteration() {
2506        use crate::solver::tree::{Action, Player, Tree};
2507        let c = |s: &str| s.parse::<Card>().unwrap();
2508        let board = ["2c", "3d", "7h", "8s", "9c"].map(c).to_vec();
2509        // Both AA combos have the same strength and merge into one bucket.
2510        // Unequal reaches expose mistakenly discounting after each combo.
2511        let combos = [
2512            vec![
2513                Combo::new(c("Ac"), c("Ad"), 1.0),
2514                Combo::new(c("Ah"), c("As"), 3.0),
2515            ],
2516            vec![Combo::new(c("Kh"), c("Kd"), 1.0)],
2517        ];
2518        let tree = Tree {
2519            board: board.clone(),
2520            root: Node::Decision {
2521                id: 0,
2522                player: Player::Oop,
2523                actions: vec![Action::Check, Action::Bet(Chips::whole(8))],
2524                children: vec![
2525                    Node::Terminal(Terminal::Fold {
2526                        winner: Player::Oop,
2527                        invested: [8.0, 8.0],
2528                    }),
2529                    Node::Terminal(Terminal::Fold {
2530                        winner: Player::Ip,
2531                        invested: [8.0, 8.0],
2532                    }),
2533                ],
2534            },
2535            num_decision_nodes: 1,
2536        };
2537        let mut trainer = Trainer::new(
2538            tree,
2539            combos,
2540            TrainerOptions {
2541                algorithm: SolverAlgorithm::Dcfr,
2542                abstraction: CardAbstraction {
2543                    river: Some(1),
2544                    ..CardAbstraction::default()
2545                },
2546                ..TrainerOptions::default()
2547            },
2548        )
2549        .unwrap();
2550        assert_eq!(trainer.train(1), [0.0, 0.0]);
2551        {
2552            let data = trainer.node_data[0].lock().unwrap();
2553            // Uniform strategy gives instantaneous regret +/-8. At t=1
2554            // both signs discount by 1/2, and total strategy mass 4 by 1/4.
2555            assert_eq!(data.regret_sum, vec![vec![4.0], vec![-4.0]]);
2556            assert_eq!(data.strategy_sum, vec![vec![0.5], vec![0.5]]);
2557        }
2558        assert_eq!(trainer.train(1), [32.0, -32.0]);
2559        {
2560            let data = trainer.node_data[0].lock().unwrap();
2561            let positive = 2.0_f64.powf(1.5);
2562            assert_eq!(data.regret_sum[0][0], 4.0 * positive / (positive + 1.0));
2563            // The action now always loses 16 relative to the current action;
2564            // both the old -4 and new -16 are discounted together.
2565            assert_eq!(data.regret_sum[1][0], -10.0);
2566            assert_eq!(data.strategy_sum[0][0], 2.0);
2567            assert_eq!(data.strategy_sum[1][0], 2.0 / 9.0);
2568        }
2569        // Iteration weights are 1^2:2^2, so (.5+4)/5 = .9.
2570        for probability in &trainer.average_strategy(0)[0] {
2571            assert!((probability - 0.9).abs() < 1e-15);
2572        }
2573    }
2574
2575    #[test]
2576    fn chunking_preserves_all_update_state_through_chance_nodes() {
2577        let pool = rayon::ThreadPoolBuilder::new()
2578            .num_threads(1)
2579            .build()
2580            .unwrap();
2581        pool.install(|| {
2582            let c = |s: &str| s.parse::<Card>().unwrap();
2583            let cfg = GameConfig {
2584                board: ["2c", "7d", "9h", "Js"].map(c).to_vec(),
2585                pot: Chips::whole(2),
2586                effective_stack: Chips::whole(1),
2587                bet_sizes: vec![0.5],
2588                max_raises: 0,
2589                suit_isomorphism: false,
2590            };
2591            let combos = [
2592                vec![
2593                    Combo::new(c("Jh"), c("Jd"), 0.7),
2594                    Combo::new(c("Ac"), c("Kd"), 1.0),
2595                ],
2596                vec![Combo::new(c("7h"), c("6s"), 1.0)],
2597            ];
2598            for (algorithm, schedule) in [
2599                SolverAlgorithm::Cfr,
2600                SolverAlgorithm::CfrPlus,
2601                SolverAlgorithm::Dcfr,
2602            ]
2603            .into_iter()
2604            .flat_map(|a| {
2605                [UpdateSchedule::Simultaneous, UpdateSchedule::Alternating].map(|s| (a, s))
2606            }) {
2607                let make = || {
2608                    Trainer::new(
2609                        build_tree(&cfg).unwrap(),
2610                        combos.clone(),
2611                        TrainerOptions {
2612                            algorithm,
2613                            schedule,
2614                            abstraction: CardAbstraction {
2615                                river: Some(2),
2616                                ..CardAbstraction::default()
2617                            },
2618                        },
2619                    )
2620                    .unwrap()
2621                };
2622                let mut whole = make();
2623                let mut chunks = make();
2624                let expected = whole.train(11);
2625                chunks.train(3);
2626                chunks.train(0);
2627                assert_eq!(chunks.train(8), expected, "{algorithm:?}");
2628                assert_eq!(whole.iterations_completed(), 11);
2629                assert_eq!(chunks.iterations_completed(), 11);
2630                for (a, b) in whole.node_data.iter().zip(&chunks.node_data) {
2631                    let a = a.lock().unwrap();
2632                    let b = b.lock().unwrap();
2633                    assert_eq!(a.regret_sum, b.regret_sum, "{algorithm:?}");
2634                    assert_eq!(a.strategy_sum, b.strategy_sum, "{algorithm:?}");
2635                }
2636            }
2637        });
2638    }
2639
2640    fn river_board() -> Vec<Card> {
2641        ["2h", "7c", "9d", "Jc", "4s"]
2642            .iter()
2643            .map(|s| s.parse::<Card>().unwrap())
2644            .collect()
2645    }
2646
2647    struct Scenario {
2648        tree: super::super::tree::Tree,
2649        trainer_combos: [Vec<Combo>; 2],
2650        pot: f64,
2651        bet: f64,
2652    }
2653
2654    fn build_scenario() -> Scenario {
2655        let board = river_board();
2656        let dead = CardSet::from_cards(&board);
2657        // OOP: JJ (value, always beats IP's 99) + KQo (air, always loses to IP's 99).
2658        let oop_range = Range::parse("JJ,KQo").unwrap();
2659        // IP: 99 (bluffcatcher — beats KQo, loses to JJ).
2660        let ip_range = Range::parse("99").unwrap();
2661        let oop_combos = oop_range.combos(dead);
2662        let ip_combos = ip_range.combos(dead);
2663
2664        let pot = 100.0;
2665        let bet = 100.0; // pot-size bet
2666        let cfg = GameConfig {
2667            board: board.clone(),
2668            pot: Chips::from_f64(pot).unwrap(),
2669            effective_stack: Chips::whole(200),
2670            bet_sizes: vec![bet / pot],
2671            max_raises: 0,
2672            suit_isomorphism: false,
2673        };
2674        let tree = build_tree(&cfg).unwrap();
2675        Scenario {
2676            tree,
2677            trainer_combos: [oop_combos, ip_combos],
2678            pot,
2679            bet,
2680        }
2681    }
2682
2683    fn is_jj(c1: Card, c2: Card) -> bool {
2684        c1.rank() == 9 && c2.rank() == 9 // J = rank index 9
2685    }
2686
2687    #[test]
2688    fn zero_sum_at_root() {
2689        let scenario = build_scenario();
2690        let mut trainer = Trainer::new(
2691            scenario.tree,
2692            scenario.trainer_combos,
2693            TrainerOptions {
2694                algorithm: SolverAlgorithm::CfrPlus,
2695                ..TrainerOptions::default()
2696            },
2697        )
2698        .unwrap();
2699        let [ev0, ev1] = trainer.train(20_000);
2700        assert!(
2701            (ev0 + ev1).abs() < 1.0,
2702            "expected zero-sum root EV, got ev0={ev0}, ev1={ev1}"
2703        );
2704    }
2705
2706    #[test]
2707    fn converges_to_known_bet_and_call_frequencies() {
2708        let scenario = build_scenario();
2709        let value_combo_count = scenario.trainer_combos[0]
2710            .iter()
2711            .filter(
2712                |&&Combo {
2713                     cards: [c1, c2], ..
2714                 }| is_jj(c1, c2),
2715            )
2716            .count();
2717        let bluff_combo_count = scenario.trainer_combos[0].len() - value_combo_count;
2718        let wv = value_combo_count as f64;
2719        let wb = bluff_combo_count as f64;
2720        let pot = scenario.pot;
2721        let bet = scenario.bet;
2722
2723        let root_id = match &scenario.tree.root {
2724            Node::Decision { id, .. } => *id,
2725            _ => panic!("expected decision"),
2726        };
2727        let ip_facing_bet_id = match &scenario.tree.root {
2728            Node::Decision { children, .. } => match &children[1] {
2729                Node::Decision { id, .. } => *id,
2730                _ => panic!("expected IP decision facing the bet"),
2731            },
2732            _ => panic!("expected decision"),
2733        };
2734
2735        let combos0 = scenario.trainer_combos[0].clone();
2736        let mut trainer = Trainer::new(
2737            scenario.tree,
2738            scenario.trainer_combos,
2739            TrainerOptions {
2740                algorithm: SolverAlgorithm::CfrPlus,
2741                ..TrainerOptions::default()
2742            },
2743        )
2744        .unwrap();
2745        trainer.train(60_000);
2746
2747        let root_strategy = trainer.average_strategy(root_id); // [action][combo], action 1 = Bet
2748        let combos0 = &combos0;
2749        let bet_freq_value: Vec<f64> = combos0
2750            .iter()
2751            .enumerate()
2752            .filter(
2753                |(
2754                    _,
2755                    &Combo {
2756                        cards: [c1, c2], ..
2757                    },
2758                )| is_jj(c1, c2),
2759            )
2760            .map(|(i, _)| root_strategy[1][i])
2761            .collect();
2762        let bet_freq_bluff: Vec<f64> = combos0
2763            .iter()
2764            .enumerate()
2765            .filter(
2766                |(
2767                    _,
2768                    &Combo {
2769                        cards: [c1, c2], ..
2770                    },
2771                )| !is_jj(c1, c2),
2772            )
2773            .map(|(i, _)| root_strategy[1][i])
2774            .collect();
2775
2776        let tol = 0.05;
2777        for f in &bet_freq_value {
2778            assert!(
2779                (f - 1.0).abs() < tol,
2780                "value combo should always bet, got {f}"
2781            );
2782        }
2783        let expected_beta = (bet / (pot + bet)) * (wv / wb);
2784        for f in &bet_freq_bluff {
2785            assert!(
2786                (f - expected_beta).abs() < tol,
2787                "expected bluff bet freq {expected_beta}, got {f}"
2788            );
2789        }
2790
2791        let ip_strategy = trainer.average_strategy(ip_facing_bet_id); // action 1 = Call
2792        let expected_call = pot / (pot + bet); // MDF
2793        for &f in &ip_strategy[1] {
2794            assert!(
2795                (f - expected_call).abs() < tol,
2796                "expected call freq (MDF) {expected_call}, got {f}"
2797            );
2798        }
2799    }
2800
2801    // --- Multi-street (turn -> chance node deals the river -> river betting) ---
2802    //
2803    // Board starts on the turn (4 cards); a single chance node deals all 48
2804    // possible river cards. The hands below were checked to keep the same win/lose
2805    // ordering across *every* possible river card.
2806    //
2807    // Unlike the single-street scenario, reaching the river here still
2808    // leaves a full betting round before showdown, so the single-street closed-form
2809    // bluff-frequency formula (which assumed an immediate showdown) no
2810    // longer applies exactly — a genuine multi-street equilibrium can bluff
2811    // at a different rate once the value of retaining bluffs into a further
2812    // street of betting is accounted for. Empirically, two of the three
2813    // single-street relationships still hold almost
2814    // exactly even with a full river betting round: value bets ~100% of the
2815    // time, and IP's calling frequency still matches the pot-odds MDF
2816    // formula. Only the bluffing frequency itself shifts. So this test
2817    // checks those two robust relationships precisely, and checks the
2818    // bluffing frequency only qualitatively (genuine interior mixing, and
2819    // identical across combos of the same hand type).
2820    fn turn_board() -> Vec<Card> {
2821        ["2c", "7d", "9h", "Js"]
2822            .iter()
2823            .map(|s| s.parse::<Card>().unwrap())
2824            .collect()
2825    }
2826
2827    struct MultiStreetScenario {
2828        tree: super::super::tree::Tree,
2829        trainer_combos: [Vec<Combo>; 2],
2830        pot: f64,
2831        bet: f64,
2832    }
2833
2834    /// `Range::combos()` iterates a `HashMap<String, f64>` internally, whose
2835    /// element order isn't guaranteed to match between two independently
2836    /// parsed `Range`s (see the suit-isomorphism equivalence test's doc
2837    /// comment for the same pitfall) — build these once and share/clone
2838    /// them across trainers being compared, rather than calling
2839    /// `build_multi_street_scenario()` (which re-parses fresh) more than once.
2840    fn multi_street_scenario_combos() -> [Vec<Combo>; 2] {
2841        let dead = CardSet::from_cards(&turn_board());
2842        // OOP: JJ (value, always beats IP's 76o on any river) + 54o (air, always loses).
2843        let oop_combos = Range::parse("JJ,54o").unwrap().combos(dead);
2844        // IP: 76o (bluffcatcher — always beats 54o, always loses to JJ, on any river).
2845        let ip_combos = Range::parse("76o").unwrap().combos(dead);
2846        [oop_combos, ip_combos]
2847    }
2848
2849    fn build_multi_street_scenario() -> MultiStreetScenario {
2850        build_multi_street_scenario_with_combos(multi_street_scenario_combos())
2851    }
2852
2853    fn build_multi_street_scenario_with_combos(
2854        trainer_combos: [Vec<Combo>; 2],
2855    ) -> MultiStreetScenario {
2856        let board = turn_board();
2857        let pot = 100.0;
2858        let bet = 100.0;
2859        let cfg = GameConfig {
2860            board: board.clone(),
2861            pot: Chips::from_f64(pot).unwrap(),
2862            effective_stack: Chips::whole(200),
2863            bet_sizes: vec![bet / pot],
2864            max_raises: 0,
2865            suit_isomorphism: false,
2866        };
2867        let tree = build_tree(&cfg).unwrap();
2868        MultiStreetScenario {
2869            tree,
2870            trainer_combos,
2871            pot,
2872            bet,
2873        }
2874    }
2875
2876    fn is_pocket_jacks(c1: Card, c2: Card) -> bool {
2877        c1.rank() == 9 && c2.rank() == 9
2878    }
2879
2880    #[test]
2881    fn multi_street_zero_sum_at_root() {
2882        let scenario = build_multi_street_scenario();
2883        let mut trainer = Trainer::new(
2884            scenario.tree,
2885            scenario.trainer_combos,
2886            TrainerOptions {
2887                algorithm: SolverAlgorithm::CfrPlus,
2888                ..TrainerOptions::default()
2889            },
2890        )
2891        .unwrap();
2892        let [ev0, ev1] = trainer.train(500);
2893        assert!(
2894            (ev0 + ev1).abs() < 1.0,
2895            "expected zero-sum root EV, got ev0={ev0}, ev1={ev1}"
2896        );
2897    }
2898
2899    #[test]
2900    fn multi_street_value_bets_and_ip_defends_at_mdf() {
2901        let scenario = build_multi_street_scenario();
2902        let pot = scenario.pot;
2903        let bet = scenario.bet;
2904
2905        let root_id = match &scenario.tree.root {
2906            Node::Decision { id, .. } => *id,
2907            _ => panic!("expected decision"),
2908        };
2909        let ip_facing_bet_id = match &scenario.tree.root {
2910            Node::Decision { children, .. } => match &children[1] {
2911                Node::Decision { id, .. } => *id,
2912                _ => panic!("expected IP decision facing the bet"),
2913            },
2914            _ => panic!("expected decision"),
2915        };
2916
2917        let combos0 = scenario.trainer_combos[0].clone();
2918        let mut trainer = Trainer::new(
2919            scenario.tree,
2920            scenario.trainer_combos,
2921            TrainerOptions {
2922                algorithm: SolverAlgorithm::CfrPlus,
2923                ..TrainerOptions::default()
2924            },
2925        )
2926        .unwrap();
2927        trainer.train(4_000);
2928
2929        let root_strategy = trainer.average_strategy(root_id); // [action][combo], action 1 = Bet
2930        let bet_freq_value: Vec<f64> = combos0
2931            .iter()
2932            .enumerate()
2933            .filter(
2934                |(
2935                    _,
2936                    &Combo {
2937                        cards: [c1, c2], ..
2938                    },
2939                )| is_pocket_jacks(c1, c2),
2940            )
2941            .map(|(i, _)| root_strategy[1][i])
2942            .collect();
2943        let bet_freq_bluff: Vec<f64> = combos0
2944            .iter()
2945            .enumerate()
2946            .filter(
2947                |(
2948                    _,
2949                    &Combo {
2950                        cards: [c1, c2], ..
2951                    },
2952                )| !is_pocket_jacks(c1, c2),
2953            )
2954            .map(|(i, _)| root_strategy[1][i])
2955            .collect();
2956
2957        let tol = 0.08;
2958        // Slightly looser: pure-value combos should approach betting 100%
2959        // of the time, but CFR+'s average strategy converges at O(1/sqrt(T))
2960        // and this scenario's tree got noticeably bigger once the
2961        // board-conflict exclusion fix (see the cfr.rs module doc)
2962        // stopped a phantom-combo bug from artificially accelerating early
2963        // convergence, so this specific check needs a bit more slack at a
2964        // fixed, debug-build-friendly iteration count.
2965        let value_bet_tol = 0.1;
2966        for f in &bet_freq_value {
2967            assert!(
2968                (f - 1.0).abs() < value_bet_tol,
2969                "value combo should always bet, got {f}"
2970            );
2971        }
2972
2973        // Bluffing frequency: checked only qualitatively (see comment above)
2974        // — genuine interior mixing, not degenerate, and identical across
2975        // combos of the same hand type (verifies symmetric combos are
2976        // treated symmetrically by the chance-node averaging).
2977        let bluff_avg = bet_freq_bluff.iter().sum::<f64>() / bet_freq_bluff.len() as f64;
2978        assert!(
2979            (0.01..0.9).contains(&bluff_avg),
2980            "expected genuine interior bluff mixing, got {bluff_avg}"
2981        );
2982        for f in &bet_freq_bluff {
2983            assert!((f - bluff_avg).abs() < 0.02, "combos of the same hand type should bet at the same frequency, got {f} vs avg {bluff_avg}");
2984        }
2985        assert!(
2986            bluff_avg < bet_freq_value[0],
2987            "bluffs should bet less often than value, got bluff={bluff_avg}, value={}",
2988            bet_freq_value[0]
2989        );
2990
2991        let ip_strategy = trainer.average_strategy(ip_facing_bet_id); // action 1 = Call
2992        let expected_call = pot / (pot + bet); // MDF
2993        for &f in &ip_strategy[1] {
2994            assert!(
2995                (f - expected_call).abs() < tol,
2996                "expected call freq (MDF) {expected_call}, got {f}"
2997            );
2998        }
2999    }
3000
3001    // --- Suit isomorphism: reduced (chance-node classes + relabeling)
3002    // must converge to the same equilibrium as unreduced (one child per
3003    // card), since it's purely a computational grouping and shouldn't
3004    // change the underlying extensive-form game at all.
3005
3006    fn two_suit_turn_board() -> Vec<Card> {
3007        // Only clubs and diamonds on board -> hearts and spades are both
3008        // free, so river deals actually get grouped into classes of size
3009        // up to 2 (unlike `turn_board()`, which is rainbow and gets no
3010        // isomorphism reduction at all).
3011        ["2c", "7d", "9c", "Jd"]
3012            .iter()
3013            .map(|s| s.parse::<Card>().unwrap())
3014            .collect()
3015    }
3016
3017    /// `Range::combos()` iterates a `HashMap<String, f64>` internally, whose
3018    /// element order isn't guaranteed to match between two independently
3019    /// parsed `Range`s (std `HashMap`'s per-instance hasher keys differ) —
3020    /// so building the reduced/unreduced scenarios from two separate
3021    /// `Range::parse` calls would silently compare unrelated combos
3022    /// position-wise. Build the combo lists once and share them so "combo
3023    /// index i" means the same physical combo in both trainers.
3024    fn build_two_suit_scenario(
3025        suit_isomorphism: bool,
3026        trainer_combos: [Vec<Combo>; 2],
3027    ) -> MultiStreetScenario {
3028        let board = two_suit_turn_board();
3029        let pot = 100.0;
3030        let bet = 100.0;
3031        let cfg = GameConfig {
3032            board: board.clone(),
3033            pot: Chips::from_f64(pot).unwrap(),
3034            effective_stack: Chips::whole(200),
3035            bet_sizes: vec![bet / pot],
3036            max_raises: 0,
3037            suit_isomorphism,
3038        };
3039        let tree = build_tree(&cfg).unwrap();
3040        MultiStreetScenario {
3041            tree,
3042            trainer_combos,
3043            pot,
3044            bet,
3045        }
3046    }
3047
3048    fn two_suit_scenario_combos() -> [Vec<Combo>; 2] {
3049        let dead = CardSet::from_cards(&two_suit_turn_board());
3050        let oop_combos = Range::parse("JJ,54o").unwrap().combos(dead);
3051        let ip_combos = Range::parse("76o").unwrap().combos(dead);
3052        [oop_combos, ip_combos]
3053    }
3054
3055    #[test]
3056    fn suit_isomorphism_actually_reduces_the_tree() {
3057        let combos = two_suit_scenario_combos();
3058        let reduced = build_two_suit_scenario(true, combos.clone());
3059        let unreduced = build_two_suit_scenario(false, combos);
3060        assert!(
3061            reduced.tree.num_decision_nodes < unreduced.tree.num_decision_nodes,
3062            "expected fewer decision nodes with isomorphism enabled, got {} (reduced) vs {} (unreduced)",
3063            reduced.tree.num_decision_nodes,
3064            unreduced.tree.num_decision_nodes
3065        );
3066    }
3067
3068    /// Node ids are allocated in preorder during `build()`, so the "check"
3069    /// branch (built before the "bet" branch) consumes a different number
3070    /// of ids depending on how much the chance node inside it is reduced —
3071    /// the same numeric id can point at unrelated nodes in the reduced vs.
3072    /// unreduced trees. So ids must be looked up per-tree, not shared.
3073    fn root_and_ip_facing_bet_ids(root: &Node) -> (usize, usize) {
3074        let Node::Decision {
3075            id: root_id,
3076            children,
3077            ..
3078        } = root
3079        else {
3080            panic!("expected decision")
3081        };
3082        let Node::Decision {
3083            id: ip_facing_bet_id,
3084            ..
3085        } = &children[1]
3086        else {
3087            panic!("expected IP decision facing the bet")
3088        };
3089        (*root_id, *ip_facing_bet_id)
3090    }
3091
3092    #[test]
3093    fn suit_isomorphism_reduced_and_unreduced_converge_to_the_same_equilibrium() {
3094        let combos = two_suit_scenario_combos();
3095        let reduced = build_two_suit_scenario(true, combos.clone());
3096        let unreduced = build_two_suit_scenario(false, combos);
3097
3098        let (reduced_root_id, reduced_ip_facing_bet_id) =
3099            root_and_ip_facing_bet_ids(&reduced.tree.root);
3100        let (unreduced_root_id, unreduced_ip_facing_bet_id) =
3101            root_and_ip_facing_bet_ids(&unreduced.tree.root);
3102
3103        let iterations = 3_000;
3104        let mut reduced_trainer = Trainer::new(
3105            reduced.tree,
3106            reduced.trainer_combos,
3107            TrainerOptions {
3108                algorithm: SolverAlgorithm::CfrPlus,
3109                ..TrainerOptions::default()
3110            },
3111        )
3112        .unwrap();
3113        reduced_trainer.train(iterations);
3114        let mut unreduced_trainer = Trainer::new(
3115            unreduced.tree,
3116            unreduced.trainer_combos,
3117            TrainerOptions {
3118                algorithm: SolverAlgorithm::CfrPlus,
3119                ..TrainerOptions::default()
3120            },
3121        )
3122        .unwrap();
3123        unreduced_trainer.train(iterations);
3124
3125        let tol = 0.05;
3126        for (row_r, row_u) in reduced_trainer
3127            .average_strategy(reduced_root_id)
3128            .iter()
3129            .zip(unreduced_trainer.average_strategy(unreduced_root_id).iter())
3130        {
3131            for (&fr, &fu) in row_r.iter().zip(row_u.iter()) {
3132                assert!(
3133                    (fr - fu).abs() < tol,
3134                    "root strategy mismatch: reduced={fr}, unreduced={fu}"
3135                );
3136            }
3137        }
3138        for (row_r, row_u) in reduced_trainer
3139            .average_strategy(reduced_ip_facing_bet_id)
3140            .iter()
3141            .zip(
3142                unreduced_trainer
3143                    .average_strategy(unreduced_ip_facing_bet_id)
3144                    .iter(),
3145            )
3146        {
3147            for (&fr, &fu) in row_r.iter().zip(row_u.iter()) {
3148                assert!(
3149                    (fr - fu).abs() < tol,
3150                    "IP-facing-bet strategy mismatch: reduced={fr}, unreduced={fu}"
3151                );
3152            }
3153        }
3154    }
3155
3156    // --- River card abstraction (bucketing) ---
3157
3158    #[test]
3159    fn compute_percentile_buckets_is_monotonic_and_bijective_when_large_enough() {
3160        let scores = [30.0, 10.0, 20.0, 10.0, 40.0];
3161        let n = scores.len();
3162
3163        // A bucket count >= the combo count must be an exact bijection
3164        // *over distinct scores*: every combo its own bucket, in score
3165        // order, except that combos 1 and 3 (tied at 10.0) must always
3166        // share a bucket (see `compute_percentile_buckets_never_splits_a_tie`)
3167        // — so 4 distinct buckets for 5 combos here, not 5.
3168        let bijective = compute_percentile_buckets(&scores, 100);
3169        assert_eq!(
3170            bijective[1], bijective[3],
3171            "tied scores must share a bucket, got {bijective:?}"
3172        );
3173        let mut seen = std::collections::HashSet::new();
3174        for (i, &b) in bijective.iter().enumerate() {
3175            if i == 3 {
3176                continue; // shares combo 1's bucket, already recorded
3177            }
3178            assert!(
3179                seen.insert(b),
3180                "expected every distinct-score combo to get a distinct bucket, got {bijective:?}"
3181            );
3182        }
3183        // Monotonic: a strictly higher score never lands in a lower bucket.
3184        for i in 0..n {
3185            for j in 0..n {
3186                if scores[i] < scores[j] {
3187                    assert!(
3188                        bijective[i] <= bijective[j],
3189                        "score {} (bucket {}) should not outrank score {} (bucket {})",
3190                        scores[i],
3191                        bijective[i],
3192                        scores[j],
3193                        bijective[j]
3194                    );
3195                }
3196            }
3197        }
3198
3199        // A small bucket count must actually merge combos (fewer distinct
3200        // buckets used than combos) while staying monotonic and in range.
3201        let reduced = compute_percentile_buckets(&scores, 2);
3202        let distinct: std::collections::HashSet<usize> = reduced.iter().copied().collect();
3203        assert!(
3204            distinct.len() <= 2,
3205            "expected at most 2 distinct buckets, got {distinct:?}"
3206        );
3207        assert!(reduced.iter().all(|&b| b < 2));
3208        for i in 0..n {
3209            for j in 0..n {
3210                if scores[i] < scores[j] {
3211                    assert!(reduced[i] <= reduced[j]);
3212                }
3213            }
3214        }
3215    }
3216
3217    /// `river_buckets: Some(n)` with `n` at least as large as either
3218    /// player's combo count must be a bijection (see
3219    /// `compute_percentile_buckets_is_monotonic_and_bijective_when_large_enough`),
3220    /// so it must converge to the same equilibrium as `None` — this is the
3221    /// same kind of equivalence check as suit isomorphism's, and also
3222    /// exercises the board_eval_cache fix for a solve that starts already
3223    /// at a complete river board (no `Chance` node at all, so
3224    /// `precompute_board_eval` alone would never seed a bucket map for it).
3225    #[test]
3226    fn river_buckets_bijective_matches_unbucketed() {
3227        let board = river_board();
3228        let dead = CardSet::from_cards(&board);
3229        let oop_combos = Range::parse("JJ,KQo").unwrap().combos(dead);
3230        let ip_combos = Range::parse("99").unwrap().combos(dead);
3231        let pot = 100.0;
3232        let bet = 100.0;
3233        let cfg = GameConfig {
3234            board: board.clone(),
3235            pot: Chips::from_f64(pot).unwrap(),
3236            effective_stack: Chips::whole(200),
3237            bet_sizes: vec![bet / pot],
3238            max_raises: 0,
3239            suit_isomorphism: false,
3240        };
3241
3242        let tree_none = build_tree(&cfg).unwrap();
3243        let tree_bucketed = build_tree(&cfg).unwrap();
3244        let (root_id, ip_facing_bet_id) = root_and_ip_facing_bet_ids(&tree_none.root);
3245
3246        let iterations = 3_000;
3247        let mut trainer_none = Trainer::new(
3248            tree_none,
3249            [oop_combos.clone(), ip_combos.clone()],
3250            TrainerOptions {
3251                algorithm: SolverAlgorithm::CfrPlus,
3252                ..TrainerOptions::default()
3253            },
3254        )
3255        .unwrap();
3256        trainer_none.train(iterations);
3257        // 100 exceeds both players' combo counts here, so this is a bijection on both sides.
3258        let mut trainer_bucketed = Trainer::new(
3259            tree_bucketed,
3260            [oop_combos, ip_combos],
3261            TrainerOptions {
3262                algorithm: SolverAlgorithm::CfrPlus,
3263                abstraction: CardAbstraction {
3264                    river: Some(100),
3265                    ..Default::default()
3266                },
3267                ..TrainerOptions::default()
3268            },
3269        )
3270        .unwrap();
3271        trainer_bucketed.train(iterations);
3272
3273        let tol = 0.05;
3274        for (row_n, row_b) in trainer_none
3275            .average_strategy(root_id)
3276            .iter()
3277            .zip(trainer_bucketed.average_strategy(root_id).iter())
3278        {
3279            for (&fn_, &fb) in row_n.iter().zip(row_b.iter()) {
3280                assert!(
3281                    (fn_ - fb).abs() < tol,
3282                    "root strategy mismatch: none={fn_}, bucketed(bijective)={fb}"
3283                );
3284            }
3285        }
3286        for (row_n, row_b) in trainer_none
3287            .average_strategy(ip_facing_bet_id)
3288            .iter()
3289            .zip(trainer_bucketed.average_strategy(ip_facing_bet_id).iter())
3290        {
3291            for (&fn_, &fb) in row_n.iter().zip(row_b.iter()) {
3292                assert!(
3293                    (fn_ - fb).abs() < tol,
3294                    "IP-facing-bet strategy mismatch: none={fn_}, bucketed(bijective)={fb}"
3295                );
3296            }
3297        }
3298    }
3299
3300    /// With a genuinely small bucket count, exact per-combo behavior isn't
3301    /// expected (that's the whole point of abstraction), but the trained
3302    /// strategy should still be sane: zero-sum at the root, and betting
3303    /// frequency should respect real hand-strength ordering across three
3304    /// clearly-separated tiers (trips > overpair > air) sharing only 3
3305    /// buckets between them.
3306    #[test]
3307    fn river_buckets_reduced_stays_zero_sum_and_respects_hand_strength_order() {
3308        let board = river_board(); // 2h 7c 9d Jc 4s
3309        let dead = CardSet::from_cards(&board);
3310        // OOP: JJ (trips jacks - top tier), QQ (overpair - middle tier),
3311        // KQo+72o (air, kicker-only - bottom tier).
3312        let oop_range = Range::parse("JJ,QQ,KQo,72o").unwrap();
3313        // IP: 99 (trips nines, beats everything but JJ) + 55 (a small
3314        // pocket pair unconnected to the board, beaten by QQ but ahead of
3315        // pure air). Giving IP a *range* instead of a single fixed hand
3316        // matters here: with IP holding only 99, QQ and air would both
3317        // simply always lose to IP's one possible hand, making them
3318        // strategically interchangeable "always-losing" bluff candidates
3319        // with no real reason for one to bet more than the other — 55
3320        // gives QQ genuine partial equity (it beats 55, loses to 99) so it
3321        // actually is a distinct middle tier.
3322        let ip_range = Range::parse("99,55").unwrap();
3323        let oop_combos = oop_range.combos(dead);
3324        let ip_combos = ip_range.combos(dead);
3325
3326        let pot = 100.0;
3327        let bet = 100.0;
3328        let cfg = GameConfig {
3329            board: board.clone(),
3330            pot: Chips::from_f64(pot).unwrap(),
3331            effective_stack: Chips::whole(200),
3332            bet_sizes: vec![bet / pot],
3333            max_raises: 0,
3334            suit_isomorphism: false,
3335        };
3336        let tree = build_tree(&cfg).unwrap();
3337        let (root_id, _) = root_and_ip_facing_bet_ids(&tree.root);
3338
3339        let combos0 = oop_combos.clone();
3340        let mut trainer = Trainer::new(
3341            tree,
3342            [oop_combos, ip_combos],
3343            TrainerOptions {
3344                algorithm: SolverAlgorithm::CfrPlus,
3345                abstraction: CardAbstraction {
3346                    river: Some(3),
3347                    ..Default::default()
3348                },
3349                ..TrainerOptions::default()
3350            },
3351        )
3352        .unwrap();
3353        let [ev0, ev1] = trainer.train(4_000);
3354        assert!(
3355            (ev0 + ev1).abs() < 1.0,
3356            "expected zero-sum root EV even under abstraction, got ev0={ev0}, ev1={ev1}"
3357        );
3358
3359        let is_jj = |c1: Card, c2: Card| c1.rank() == 9 && c2.rank() == 9;
3360        let is_qq = |c1: Card, c2: Card| c1.rank() == 10 && c2.rank() == 10;
3361        let avg = |pred: &dyn Fn(Card, Card) -> bool, strategy: &[Vec<f64>]| -> f64 {
3362            let matching: Vec<f64> = combos0
3363                .iter()
3364                .enumerate()
3365                .filter(
3366                    |(
3367                        _,
3368                        &Combo {
3369                            cards: [c1, c2], ..
3370                        },
3371                    )| pred(c1, c2),
3372                )
3373                .map(|(i, _)| strategy[1][i]) // action 1 = Bet
3374                .collect();
3375            matching.iter().sum::<f64>() / matching.len() as f64
3376        };
3377
3378        let root_strategy = trainer.average_strategy(root_id);
3379        let bet_freq_jj = avg(&is_jj, &root_strategy);
3380        let bet_freq_qq = avg(&is_qq, &root_strategy);
3381        let bet_freq_air = avg(&|c1, c2| !is_jj(c1, c2) && !is_qq(c1, c2), &root_strategy);
3382
3383        // With only 3 buckets shared across 4 hand types, the top bucket
3384        // will typically end up merging JJ (only 3 combos, the very top of
3385        // the score range) with some of the next-highest-scoring QQ
3386        // combos — so an unbucketed-style ">90% bet" floor for JJ alone
3387        // isn't a fair expectation here; what abstraction should still
3388        // guarantee is that hand-strength order isn't inverted, and that
3389        // trips clearly bets more than pure air (not diluted down to it).
3390        let tol = 0.05;
3391        assert!(
3392            bet_freq_jj >= bet_freq_qq - tol,
3393            "trips should bet at least as often as the overpair tier, got jj={bet_freq_jj}, qq={bet_freq_qq}"
3394        );
3395        assert!(
3396            bet_freq_qq >= bet_freq_air - tol,
3397            "overpair should bet at least as often as pure air, got qq={bet_freq_qq}, air={bet_freq_air}"
3398        );
3399        assert!(
3400            bet_freq_jj > bet_freq_air + 0.1,
3401            "trips should still clearly out-bet pure air despite bucketing, got jj={bet_freq_jj}, air={bet_freq_air}"
3402        );
3403    }
3404
3405    // --- Flop/turn card abstraction ---
3406
3407    /// Cross-checks `avg_score`'s suit-isomorphism-class-weighted
3408    /// averaging against a naive full 1-card-at-a-time enumeration (no
3409    /// classes at all) — the same "fast path vs. reference" pattern
3410    /// `eval::evaluate_5` is validated with elsewhere in this codebase.
3411    /// Uses a two-suit board (like `two_suit_turn_board`) specifically so
3412    /// classes of size > 1 actually get exercised, not just trivial
3413    /// singletons.
3414    #[test]
3415    fn avg_score_matches_naive_full_enumeration_average() {
3416        let board = two_suit_turn_board(); // 2c 7d 9c Jd -- h/s free
3417        let dead = CardSet::from_cards(&board);
3418        let combos = Range::parse("JJ,54o").unwrap().combos(dead);
3419        let used = CardSet::from_cards(&board);
3420
3421        let naive: Vec<f64> = combos
3422            .iter()
3423            .map(
3424                |&Combo {
3425                     cards: [h1, h2], ..
3426                 }| {
3427                    let mut sum = 0.0;
3428                    let mut count = 0.0;
3429                    for c in Card::all() {
3430                        if used.contains(c) || c == h1 || c == h2 {
3431                            continue;
3432                        }
3433                        let mut river = board.clone();
3434                        river.push(c);
3435                        let score =
3436                            score_7([h1, h2, river[0], river[1], river[2], river[3], river[4]]);
3437                        sum += score as f64;
3438                        count += 1.0;
3439                    }
3440                    sum / count
3441                },
3442            )
3443            .collect();
3444
3445        let board_eval_cache = HashMap::new();
3446        let mut memo = HashMap::new();
3447        let combo_index = [build_combo_index(&combos), HashMap::new()];
3448        let via_classes = avg_score(
3449            &board,
3450            &[combos.clone(), Vec::new()],
3451            &combo_index,
3452            &board_eval_cache,
3453            &mut memo,
3454        );
3455
3456        for (i, (&n, &c)) in naive.iter().zip(via_classes[0].iter()).enumerate() {
3457            assert!((n - c).abs() < 1e-9, "combo {i}: naive={n}, avg_score={c}");
3458        }
3459    }
3460
3461    fn flop_board() -> Vec<Card> {
3462        // Monotone (all clubs) -> maximal isomorphism benefit (3 free
3463        // suits), keeping the two-chance-node tree small enough to train
3464        // quickly even without bucketing, for the equivalence check below.
3465        ["2c", "7c", "9c"]
3466            .iter()
3467            .map(|s| s.parse::<Card>().unwrap())
3468            .collect()
3469    }
3470
3471    struct FlopScenario {
3472        tree: super::super::tree::Tree,
3473        trainer_combos: [Vec<Combo>; 2],
3474    }
3475
3476    fn flop_scenario_combos() -> [Vec<Combo>; 2] {
3477        let dead = CardSet::from_cards(&flop_board());
3478        let oop_combos = Range::parse("JJ,54o").unwrap().combos(dead);
3479        let ip_combos = Range::parse("76o").unwrap().combos(dead);
3480        [oop_combos, ip_combos]
3481    }
3482
3483    fn build_flop_scenario(trainer_combos: [Vec<Combo>; 2]) -> FlopScenario {
3484        let board = flop_board();
3485        let cfg = GameConfig {
3486            board: board.clone(),
3487            pot: Chips::whole(100),
3488            effective_stack: Chips::whole(200),
3489            bet_sizes: vec![1.0],
3490            max_raises: 0,
3491            suit_isomorphism: true,
3492        };
3493        let tree = build_tree(&cfg).unwrap();
3494        FlopScenario {
3495            tree,
3496            trainer_combos,
3497        }
3498    }
3499
3500    /// `CardAbstraction { turn: Some(n), .. }` with `n` at least as large
3501    /// as either player's combo count must be a bijection on the turn
3502    /// street (same reasoning as `compute_percentile_buckets_...`), so it
3503    /// must converge to the same equilibrium as no abstraction at all.
3504    /// Uses `turn_board()`'s scenario directly (a solve that *starts*
3505    /// already at the turn — no chance node deals into it), which also
3506    /// exercises the "initial board" inclusion in `collect_reachable_boards`
3507    /// usage for turn/flop, mirroring the river case.
3508    #[test]
3509    fn turn_buckets_bijective_matches_unbucketed() {
3510        let combos = multi_street_scenario_combos();
3511        let scenario_none = build_multi_street_scenario_with_combos(combos.clone());
3512        let scenario_bucketed = build_multi_street_scenario_with_combos(combos);
3513        let (root_id, ip_facing_bet_id) = root_and_ip_facing_bet_ids(&scenario_none.tree.root);
3514
3515        let iterations = 1_500;
3516        let mut trainer_none = Trainer::new(
3517            scenario_none.tree,
3518            scenario_none.trainer_combos,
3519            TrainerOptions {
3520                algorithm: SolverAlgorithm::CfrPlus,
3521                ..TrainerOptions::default()
3522            },
3523        )
3524        .unwrap();
3525        trainer_none.train(iterations);
3526        let mut trainer_bucketed = Trainer::new(
3527            scenario_bucketed.tree,
3528            scenario_bucketed.trainer_combos,
3529            TrainerOptions {
3530                algorithm: SolverAlgorithm::CfrPlus,
3531                abstraction: CardAbstraction {
3532                    turn: Some(100),
3533                    ..Default::default()
3534                },
3535                ..TrainerOptions::default()
3536            },
3537        )
3538        .unwrap();
3539        trainer_bucketed.train(iterations);
3540
3541        let tol = 0.05;
3542        for (row_n, row_b) in trainer_none
3543            .average_strategy(root_id)
3544            .iter()
3545            .zip(trainer_bucketed.average_strategy(root_id).iter())
3546        {
3547            for (&fn_, &fb) in row_n.iter().zip(row_b.iter()) {
3548                assert!(
3549                    (fn_ - fb).abs() < tol,
3550                    "root strategy mismatch: none={fn_}, bucketed(bijective)={fb}"
3551                );
3552            }
3553        }
3554        for (row_n, row_b) in trainer_none
3555            .average_strategy(ip_facing_bet_id)
3556            .iter()
3557            .zip(trainer_bucketed.average_strategy(ip_facing_bet_id).iter())
3558        {
3559            for (&fn_, &fb) in row_n.iter().zip(row_b.iter()) {
3560                assert!(
3561                    (fn_ - fb).abs() < tol,
3562                    "IP-facing-bet strategy mismatch: none={fn_}, bucketed(bijective)={fb}"
3563                );
3564            }
3565        }
3566    }
3567
3568    /// Same equivalence check, but on the flop: `CardAbstraction { flop:
3569    /// Some(n), .. }` bijective must match unabstracted, exercising a tree
3570    /// with *two* chance nodes (flop deals the turn, which deals the
3571    /// river) and `avg_score`'s two-level recursion.
3572    #[test]
3573    fn flop_buckets_bijective_matches_unbucketed() {
3574        let combos = flop_scenario_combos();
3575        let scenario_none = build_flop_scenario(combos.clone());
3576        let scenario_bucketed = build_flop_scenario(combos);
3577        let (root_id, ip_facing_bet_id) = root_and_ip_facing_bet_ids(&scenario_none.tree.root);
3578
3579        let iterations = 300;
3580        let mut trainer_none = Trainer::new(
3581            scenario_none.tree,
3582            scenario_none.trainer_combos,
3583            TrainerOptions {
3584                algorithm: SolverAlgorithm::CfrPlus,
3585                ..TrainerOptions::default()
3586            },
3587        )
3588        .unwrap();
3589        trainer_none.train(iterations);
3590        let mut trainer_bucketed = Trainer::new(
3591            scenario_bucketed.tree,
3592            scenario_bucketed.trainer_combos,
3593            TrainerOptions {
3594                algorithm: SolverAlgorithm::CfrPlus,
3595                abstraction: CardAbstraction {
3596                    flop: Some(100),
3597                    ..Default::default()
3598                },
3599                ..TrainerOptions::default()
3600            },
3601        )
3602        .unwrap();
3603        trainer_bucketed.train(iterations);
3604
3605        let tol = 0.08;
3606        for (row_n, row_b) in trainer_none
3607            .average_strategy(root_id)
3608            .iter()
3609            .zip(trainer_bucketed.average_strategy(root_id).iter())
3610        {
3611            for (&fn_, &fb) in row_n.iter().zip(row_b.iter()) {
3612                assert!(
3613                    (fn_ - fb).abs() < tol,
3614                    "root strategy mismatch: none={fn_}, bucketed(bijective)={fb}"
3615                );
3616            }
3617        }
3618        for (row_n, row_b) in trainer_none
3619            .average_strategy(ip_facing_bet_id)
3620            .iter()
3621            .zip(trainer_bucketed.average_strategy(ip_facing_bet_id).iter())
3622        {
3623            for (&fn_, &fb) in row_n.iter().zip(row_b.iter()) {
3624                assert!(
3625                    (fn_ - fb).abs() < tol,
3626                    "IP-facing-bet strategy mismatch: none={fn_}, bucketed(bijective)={fb}"
3627                );
3628            }
3629        }
3630    }
3631
3632    /// With a small turn bucket count, exact per-combo behavior isn't
3633    /// expected, but zero-sum should still hold and JJ (the only real
3634    /// value hand, always beating IP's fixed 76o) should still bet
3635    /// noticeably more than pure air (54o, which always loses) — the same
3636    /// kind of sanity check as the river's reduced-bucket test, adapted to
3637    /// a street where the strength proxy is `avg_score`, not a final
3638    /// `evaluate_7` score.
3639    #[test]
3640    fn turn_buckets_reduced_stays_zero_sum_and_respects_hand_strength_order() {
3641        let scenario = build_multi_street_scenario();
3642        let (root_id, _) = root_and_ip_facing_bet_ids(&scenario.tree.root);
3643        let combos0 = scenario.trainer_combos[0].clone();
3644
3645        let mut trainer = Trainer::new(
3646            scenario.tree,
3647            scenario.trainer_combos,
3648            TrainerOptions {
3649                algorithm: SolverAlgorithm::CfrPlus,
3650                abstraction: CardAbstraction {
3651                    turn: Some(2),
3652                    ..Default::default()
3653                },
3654                ..TrainerOptions::default()
3655            },
3656        )
3657        .unwrap();
3658        let [ev0, ev1] = trainer.train(1_500);
3659        assert!(
3660            (ev0 + ev1).abs() < 1.0,
3661            "expected zero-sum root EV even under turn abstraction, got ev0={ev0}, ev1={ev1}"
3662        );
3663
3664        let is_jj = |c1: Card, c2: Card| c1.rank() == 9 && c2.rank() == 9;
3665        let root_strategy = trainer.average_strategy(root_id);
3666        let bet_freq_jj: Vec<f64> = combos0
3667            .iter()
3668            .enumerate()
3669            .filter(
3670                |(
3671                    _,
3672                    &Combo {
3673                        cards: [c1, c2], ..
3674                    },
3675                )| is_jj(c1, c2),
3676            )
3677            .map(|(i, _)| root_strategy[1][i])
3678            .collect();
3679        let bet_freq_air: Vec<f64> = combos0
3680            .iter()
3681            .enumerate()
3682            .filter(
3683                |(
3684                    _,
3685                    &Combo {
3686                        cards: [c1, c2], ..
3687                    },
3688                )| !is_jj(c1, c2),
3689            )
3690            .map(|(i, _)| root_strategy[1][i])
3691            .collect();
3692        let avg_jj = bet_freq_jj.iter().sum::<f64>() / bet_freq_jj.len() as f64;
3693        let avg_air = bet_freq_air.iter().sum::<f64>() / bet_freq_air.len() as f64;
3694        assert!(avg_jj > avg_air + 0.1, "value should still clearly out-bet air despite turn bucketing, got jj={avg_jj}, air={avg_air}");
3695    }
3696
3697    /// A naive rank-based percentile split can place two *exactly tied*
3698    /// scores into different buckets purely because their sort positions
3699    /// straddle a cut point. That's specifically dangerous under suit
3700    /// isomorphism: two combos related by a free-suit swap always get the
3701    /// identical `avg_score` (a provable symmetry — the whole future
3702    /// board/outcome distribution is suit-blind), and `chance_value`'s
3703    /// relabeling assumes such combos always share one strategy, so
3704    /// splitting their tie across a bucket boundary would silently break
3705    /// that invariant. Regression test for exactly that bug, found via
3706    /// `flop_and_isomorphism_interaction_stays_zero_sum` below.
3707    #[test]
3708    fn compute_percentile_buckets_never_splits_a_tie() {
3709        let scores = [10.0, 10.0, 10.0, 20.0, 20.0, 30.0, 40.0, 40.0];
3710        for num_buckets in 1..=scores.len() {
3711            let buckets = compute_percentile_buckets(&scores, num_buckets);
3712            for (a, b) in [(0, 1), (1, 2), (3, 4), (6, 7)] {
3713                assert_eq!(
3714                    buckets[a], buckets[b],
3715                    "num_buckets={num_buckets}: tied scores {}/{} got different buckets {:?}",
3716                    scores[a], scores[b], buckets
3717                );
3718            }
3719        }
3720    }
3721
3722    /// Regression test for a real bug found while building flop/turn
3723    /// abstraction: with isomorphism enabled, `chance_value`'s relabeling
3724    /// requires every ancestor decision node (bucketed or not) to treat
3725    /// suit-swap-equivalent combos identically. A flop decision node
3726    /// bucketed by `avg_score` broke that when tied scores landed in
3727    /// different buckets (fixed by `compute_percentile_buckets_never_splits_a_tie`'s
3728    /// fix) — the visible symptom was the root EV silently losing its
3729    /// zero-sum property at some iteration counts (but not others,
3730    /// depending on when the bucket-shared regret happened to matter),
3731    /// entirely deterministically (not a floating-point/thread-ordering
3732    /// issue — reproduced bit-for-bit across repeated runs), which is why
3733    /// this checks several iteration counts, not just one.
3734    #[test]
3735    fn flop_and_isomorphism_interaction_stays_zero_sum() {
3736        for iters in [1u32, 5, 20, 100] {
3737            let combos = flop_scenario_combos();
3738            let scenario = build_flop_scenario(combos);
3739            let mut trainer = Trainer::new(
3740                scenario.tree,
3741                scenario.trainer_combos,
3742                TrainerOptions {
3743                    algorithm: SolverAlgorithm::CfrPlus,
3744                    abstraction: CardAbstraction {
3745                        flop: Some(2),
3746                        ..Default::default()
3747                    },
3748                    ..TrainerOptions::default()
3749                },
3750            )
3751            .unwrap();
3752            let [ev0, ev1] = trainer.train(iters);
3753            assert!(
3754                (ev0 + ev1).abs() < 1e-6,
3755                "iters={iters}: expected exact zero-sum, got ev0={ev0}, ev1={ev1}, sum={}",
3756                ev0 + ev1
3757            );
3758        }
3759    }
3760
3761    // --- EV / equity (Trainer::evaluate) ---
3762
3763    #[test]
3764    fn evaluate_average_strategy_root_ev_is_zero_sum() {
3765        let scenario = build_scenario();
3766        let mut trainer = Trainer::new(
3767            scenario.tree,
3768            scenario.trainer_combos,
3769            TrainerOptions {
3770                algorithm: SolverAlgorithm::CfrPlus,
3771                ..TrainerOptions::default()
3772            },
3773        )
3774        .unwrap();
3775        trainer.train(20_000);
3776        let [ev0, ev1] = trainer.evaluate().root_values;
3777        assert!(
3778            (ev0 + ev1).abs() < 1.0,
3779            "expected zero-sum root EV under the average strategy, got ev0={ev0}, ev1={ev1}"
3780        );
3781    }
3782
3783    /// `river_board()`'s scenario (`build_scenario`) has a known winner at
3784    /// showdown: OOP's JJ always beats IP's fixed 99, OOP's KQo always
3785    /// loses to it. Equity is exact and cheap at a river (complete-board)
3786    /// node, so this checks it directly against hand-derived values,
3787    /// unlike EV (which folds in betting and is only checked qualitatively
3788    /// elsewhere).
3789    #[test]
3790    fn river_equity_matches_known_showdown_outcomes() {
3791        let scenario = build_scenario();
3792        let root_id = match &scenario.tree.root {
3793            Node::Decision { id, .. } => *id,
3794            _ => panic!("expected decision"),
3795        };
3796        let combos0 = scenario.trainer_combos[0].clone();
3797        let mut trainer = Trainer::new(
3798            scenario.tree,
3799            scenario.trainer_combos,
3800            TrainerOptions {
3801                algorithm: SolverAlgorithm::CfrPlus,
3802                ..TrainerOptions::default()
3803            },
3804        )
3805        .unwrap();
3806        trainer.train(5_000);
3807
3808        let eval = trainer.evaluate().nodes;
3809        let root_eval = eval.get(root_id).expect("root should have an evaluation");
3810        let equity = root_eval
3811            .equity
3812            .as_ref()
3813            .expect("river (complete board) node should have equity");
3814
3815        for (
3816            i,
3817            &Combo {
3818                cards: [c1, c2], ..
3819            },
3820        ) in combos0.iter().enumerate()
3821        {
3822            if is_jj(c1, c2) {
3823                assert!(
3824                    (equity[i] - 1.0).abs() < 1e-9,
3825                    "JJ should have 100% equity vs IP's fixed 99, got {}",
3826                    equity[i]
3827                );
3828            } else {
3829                assert!(
3830                    equity[i].abs() < 1e-9,
3831                    "KQo should have 0% equity vs IP's fixed 99, got {}",
3832                    equity[i]
3833                );
3834            }
3835        }
3836    }
3837
3838    /// Equity is only computed where it's cheap and exact (a complete
3839    /// board) — see `NodeEvaluation`'s doc comment for why flop/turn
3840    /// equity isn't implemented yet. A pre-river node's evaluation should
3841    /// still have a sensible EV, just no equity figure.
3842    #[test]
3843    fn equity_is_none_before_the_river() {
3844        let scenario = build_multi_street_scenario(); // starts at the turn, one chance node to the river
3845        let root_id = match &scenario.tree.root {
3846            Node::Decision { id, .. } => *id,
3847            _ => panic!("expected decision"),
3848        };
3849        let mut trainer = Trainer::new(
3850            scenario.tree,
3851            scenario.trainer_combos,
3852            TrainerOptions {
3853                algorithm: SolverAlgorithm::CfrPlus,
3854                ..TrainerOptions::default()
3855            },
3856        )
3857        .unwrap();
3858        trainer.train(500);
3859
3860        let eval = trainer.evaluate().nodes;
3861        let root_eval = eval.get(root_id).expect("root should have an evaluation");
3862        assert!(
3863            root_eval.equity.is_none(),
3864            "expected no equity figure at a pre-river (incomplete board) node"
3865        );
3866        assert_eq!(
3867            root_eval.ev.len(),
3868            trainer.game.combos(Player::Oop).len(),
3869            "EV should still be reported per combo"
3870        );
3871    }
3872
3873    /// Regression test for a normalization bug: the per-node `NodeEvaluation.ev`
3874    /// stored for display must be a true per-combo expected value, not the
3875    /// raw counterfactual value `v(I) = sum_j reach_opp[j] * payoff_j` used
3876    /// internally elsewhere in this module (a sum over the opponent's whole
3877    /// live range, which scales with the *number* of opponent combos and can
3878    /// be many times larger than any real outcome). In `build_scenario`, the
3879    /// most any combo can win is `pot + bet` (called and won) and the most it
3880    /// can lose is `bet` (called and lost), so every displayed EV must stay
3881    /// within that range — the un-normalized bug produced values in the
3882    /// hundreds to thousands, far outside it.
3883    #[test]
3884    fn evaluate_ev_is_normalized_per_combo_not_raw_counterfactual_value() {
3885        let scenario = build_scenario();
3886        let pot = scenario.pot;
3887        let bet = scenario.bet;
3888        let root_id = match &scenario.tree.root {
3889            Node::Decision { id, .. } => *id,
3890            _ => panic!("expected decision"),
3891        };
3892        let ip_facing_bet_id = match &scenario.tree.root {
3893            Node::Decision { children, .. } => match &children[1] {
3894                Node::Decision { id, .. } => *id,
3895                _ => panic!("expected IP decision facing the bet"),
3896            },
3897            _ => panic!("expected decision"),
3898        };
3899
3900        let mut trainer = Trainer::new(
3901            scenario.tree,
3902            scenario.trainer_combos,
3903            TrainerOptions {
3904                algorithm: SolverAlgorithm::CfrPlus,
3905                ..TrainerOptions::default()
3906            },
3907        )
3908        .unwrap();
3909        trainer.train(20_000);
3910        let eval = trainer.evaluate().nodes;
3911
3912        let bound = pot + bet;
3913        let root_eval = eval.get(root_id).expect("root should have an evaluation");
3914        for &ev in &root_eval.ev {
3915            assert!(
3916                ev.abs() <= bound + 1e-6,
3917                "root EV {ev} exceeds the game's stake bound of {bound}"
3918            );
3919        }
3920        let ip_eval = eval
3921            .get(ip_facing_bet_id)
3922            .expect("IP-facing-bet node should have an evaluation");
3923        for &ev in &ip_eval.ev {
3924            assert!(
3925                ev.abs() <= bound + 1e-6,
3926                "IP-facing-bet EV {ev} exceeds the game's stake bound of {bound}"
3927            );
3928        }
3929
3930        // JJ always bets and always beats IP's fixed 99, so under the
3931        // converged average strategy its root EV should be close to
3932        // winning the pot every time it isn't check-through — strictly
3933        // positive, not just "in bounds".
3934        let combos0 = trainer.game.combos(Player::Oop);
3935        for (
3936            i,
3937            &Combo {
3938                cards: [c1, c2], ..
3939            },
3940        ) in combos0.iter().enumerate()
3941        {
3942            if is_jj(c1, c2) {
3943                assert!(
3944                    root_eval.ev[i] > 0.0,
3945                    "JJ should have positive EV, got {}",
3946                    root_eval.ev[i]
3947                );
3948            }
3949        }
3950    }
3951
3952    // --- Exploitability (Trainer::exploitability) ---
3953
3954    /// `Exploitability::total` is the standard `(BR0 + BR1) / 2` figure — it
3955    /// can never be meaningfully negative (best-responding to a fixed
3956    /// opponent strategy can never do worse than the strategy actually
3957    /// played) and shrinks toward 0 as training converges. Check the
3958    /// monotonic trend rather than an iteration-specific value; separate
3959    /// analytical tests below pin the units and normalization.
3960    #[test]
3961    fn policy_snapshot_is_frozen_and_matches_trainer_reads() {
3962        let board: Vec<Card> = ["2c", "7c", "9d", "Jd"]
3963            .iter()
3964            .map(|s| s.parse::<Card>().unwrap())
3965            .collect();
3966        let dead = CardSet::from_cards(&board);
3967        let combos = [
3968            Range::parse("AA:0.5,KK,QQ").unwrap().combos(dead),
3969            Range::parse("JJ,TT").unwrap().combos(dead),
3970        ];
3971        let cfg = GameConfig {
3972            board: board.clone(),
3973            pot: Chips::whole(100),
3974            effective_stack: Chips::whole(150),
3975            bet_sizes: vec![0.5, 1.0],
3976            max_raises: 1,
3977            suit_isomorphism: true,
3978        };
3979        let abstraction = CardAbstraction {
3980            river: Some(2),
3981            ..CardAbstraction::default()
3982        };
3983        let make = || {
3984            Trainer::new(
3985                build_tree(&cfg).unwrap(),
3986                combos.clone(),
3987                TrainerOptions {
3988                    algorithm: SolverAlgorithm::Dcfr,
3989                    abstraction,
3990                    ..TrainerOptions::default()
3991                },
3992            )
3993            .unwrap()
3994        };
3995        let bits = |evaluation: Evaluation| {
3996            let nodes: Vec<Vec<u64>> = evaluation
3997                .nodes
3998                .iter()
3999                .map(|e| e.ev.iter().map(|v| v.to_bits()).collect())
4000                .collect();
4001            (nodes, evaluation.root_values.map(f64::to_bits))
4002        };
4003
4004        let mut trainer = make();
4005        trainer.train(30);
4006        let policy = trainer.policy();
4007        let game = Arc::clone(trainer.game());
4008        let evaluation = bits(game.evaluate(&policy));
4009        let exploitability = game.exploitability(&policy).total.to_bits();
4010        assert_eq!(evaluation, bits(trainer.evaluate()));
4011        assert_eq!(exploitability, trainer.exploitability().total.to_bits());
4012        for id in 0..game.num_decision_nodes() {
4013            assert_eq!(
4014                trainer.average_strategy(id),
4015                game.average_strategy(&policy, id)
4016            );
4017        }
4018
4019        // Training on does not disturb the snapshot, which still equals a
4020        // fresh trainer stopped at the same iteration.
4021        trainer.train(30);
4022        assert_ne!(evaluation, bits(trainer.evaluate()));
4023        assert_eq!(evaluation, bits(game.evaluate(&policy)));
4024        assert_eq!(exploitability, game.exploitability(&policy).total.to_bits());
4025        let mut fresh = make();
4026        fresh.train(30);
4027        assert_eq!(evaluation, bits(fresh.evaluate()));
4028
4029        // A policy rebuilt from its rows (as a save does) reads identically,
4030        // and rows that do not fit the game are rejected.
4031        let restored = game.policy_from_rows(policy.rows().to_vec()).unwrap();
4032        assert_eq!(evaluation, bits(game.evaluate(&restored)));
4033        let mut short = policy.rows().to_vec();
4034        short.pop();
4035        assert!(game.policy_from_rows(short).is_err());
4036        let mut skewed = policy.rows().to_vec();
4037        skewed[0][0][0] += 0.5;
4038        assert!(game.policy_from_rows(skewed).is_err());
4039
4040        // A distribution that breaks suit symmetry is rejected: chance nodes
4041        // derive non-representative cards from the representative's values.
4042        let (id, b, partner) = game
4043            .node_meta
4044            .iter()
4045            .enumerate()
4046            .find_map(|(id, (player, board))| {
4047                let group = game.suit_groups.get(board)?[*player]
4048                    .iter()
4049                    .find(|g| g.len() > 1)?;
4050                Some((id, group[0], group[1]))
4051            })
4052            .expect("suit-reduced fixture has a nontrivial suit group");
4053        let mut asymmetric = policy.rows().to_vec();
4054        let rows = &mut asymmetric[id];
4055        rows.iter_mut().for_each(|row| row[b] = 0.0);
4056        rows[0][b] = 1.0;
4057        rows.iter_mut().for_each(|row| row[partner] = 0.0);
4058        let last = rows.len() - 1;
4059        rows[last][partner] = 1.0;
4060        assert!(last > 0);
4061        assert!(
4062            matches!(game.policy_from_rows(asymmetric).unwrap_err(), PolicyError::NotSymmetric { node } if node == id)
4063        );
4064    }
4065
4066    #[test]
4067    fn exploitability_decreases_with_more_training() {
4068        let few = build_scenario();
4069        let mut few_trainer = Trainer::new(
4070            few.tree,
4071            few.trainer_combos,
4072            TrainerOptions {
4073                algorithm: SolverAlgorithm::CfrPlus,
4074                ..TrainerOptions::default()
4075            },
4076        )
4077        .unwrap();
4078        few_trainer.train(100);
4079        let few_expl = few_trainer.exploitability();
4080
4081        let many = build_scenario();
4082        let mut many_trainer = Trainer::new(
4083            many.tree,
4084            many.trainer_combos,
4085            TrainerOptions {
4086                algorithm: SolverAlgorithm::CfrPlus,
4087                ..TrainerOptions::default()
4088            },
4089        )
4090        .unwrap();
4091        many_trainer.train(20_000);
4092        let many_expl = many_trainer.exploitability();
4093
4094        assert!(
4095            few_expl.total > -1e-6,
4096            "exploitability should never be meaningfully negative, got {}",
4097            few_expl.total
4098        );
4099        assert!(
4100            many_expl.total > -1e-6,
4101            "exploitability should never be meaningfully negative, got {}",
4102            many_expl.total
4103        );
4104        assert!(
4105            many_expl.total < few_expl.total,
4106            "expected exploitability to shrink with more training: 100 iters -> {}, 20,000 iters -> {}",
4107            few_expl.total,
4108            many_expl.total
4109        );
4110    }
4111
4112    #[test]
4113    fn exploitability_is_near_zero_after_convergence() {
4114        let scenario = build_scenario();
4115        let pot = scenario.pot;
4116        let mut trainer = Trainer::new(
4117            scenario.tree,
4118            scenario.trainer_combos,
4119            TrainerOptions {
4120                algorithm: SolverAlgorithm::CfrPlus,
4121                ..TrainerOptions::default()
4122            },
4123        )
4124        .unwrap();
4125        trainer.train(20_000);
4126        let expl = trainer.exploitability();
4127        assert!(
4128            expl.total < pot * 0.001,
4129            "expected exploitability below 0.1% of pot after 20,000 iterations, got {}",
4130            expl.total
4131        );
4132    }
4133
4134    // A tiny, independently solvable river game. OOP always wins showdown:
4135    // check wins 5; bet wins 10 when IP calls and 5 when IP folds. With the
4136    // untrained uniform strategy, BR(OOP) = 7.5, BR(IP) = -5, so exploitability
4137    // is 1.25 chips. This pins a NONZERO metric, unlike an equilibrium-only
4138    // assertion that would pass with any (or no) normalization.
4139    fn analytical_exploitability_trainer(combos: [Vec<Combo>; 2]) -> Trainer {
4140        use crate::solver::tree::{Action, Player, Tree};
4141        let board: Vec<Card> = ["2c", "7d", "9h", "Js", "Qd"]
4142            .iter()
4143            .map(|s| s.parse::<Card>().unwrap())
4144            .collect();
4145        let scores = eval_combos_if_complete(&combos, &board);
4146        let dead = mask_of(&board);
4147        // Assert the fixture's actual hand ordering, including every legal
4148        // pair; otherwise the analytical payoff argument would be invalid.
4149        for (
4150            i,
4151            &Combo {
4152                cards: [h1, h2], ..
4153            },
4154        ) in combos[0].iter().enumerate()
4155        {
4156            for (
4157                j,
4158                &Combo {
4159                    cards: [v1, v2], ..
4160                },
4161            ) in combos[1].iter().enumerate()
4162            {
4163                if [h1, h2, v1, v2].iter().any(|&c| mask_has(dead, c))
4164                    || h1 == v1
4165                    || h1 == v2
4166                    || h2 == v1
4167                    || h2 == v2
4168                {
4169                    continue;
4170                }
4171                assert!(
4172                    scores[0][i] > scores[1][j],
4173                    "fixture requires OOP to win every legal showdown"
4174                );
4175            }
4176        }
4177        let tree = Tree {
4178            board: board.clone(),
4179            root: Node::Decision {
4180                id: 0,
4181                player: Player::Oop,
4182                actions: vec![Action::Check, Action::Bet(Chips::whole(5))],
4183                children: vec![
4184                    Node::Terminal(Terminal::Showdown {
4185                        invested: [5.0, 5.0],
4186                    }),
4187                    Node::Decision {
4188                        id: 1,
4189                        player: Player::Ip,
4190                        actions: vec![Action::Call, Action::Fold],
4191                        children: vec![
4192                            Node::Terminal(Terminal::Showdown {
4193                                invested: [10.0, 10.0],
4194                            }),
4195                            Node::Terminal(Terminal::Fold {
4196                                winner: Player::Oop,
4197                                invested: [10.0, 5.0],
4198                            }),
4199                        ],
4200                    },
4201                ],
4202            },
4203            num_decision_nodes: 2,
4204        };
4205        // Unchecked: the fixtures deliberately include board-blocked combos
4206        // and impossible deals, which the kernels must still ignore.
4207        Trainer::new_unchecked(
4208            tree,
4209            combos,
4210            TrainerOptions {
4211                algorithm: SolverAlgorithm::CfrPlus,
4212                ..TrainerOptions::default()
4213            },
4214        )
4215    }
4216
4217    fn weighted_combo(a: &str, b: &str, weight: f64) -> Combo {
4218        Combo::new(
4219            a.parse::<Card>().unwrap(),
4220            b.parse::<Card>().unwrap(),
4221            weight,
4222        )
4223    }
4224
4225    fn assert_analytical_exploitability(expl: Exploitability) {
4226        assert!(
4227            (expl.oop - 7.5).abs() < 1e-10,
4228            "OOP BR must be 7.5 chips, got {}",
4229            expl.oop
4230        );
4231        assert!(
4232            (expl.ip + 5.0).abs() < 1e-10,
4233            "IP BR must be -5 chips, got {}",
4234            expl.ip
4235        );
4236        assert!(
4237            (expl.total - 1.25).abs() < 1e-10,
4238            "exploitability must be 1.25 chips, got {}",
4239            expl.total
4240        );
4241    }
4242
4243    #[test]
4244    fn exploitability_matches_analytical_best_responses_with_blockers() {
4245        // Three legal deals, not the four pairs in the Cartesian product:
4246        // AcAd cannot be dealt against AcKs. Board-blocked entries on BOTH
4247        // sides must affect neither numerator nor denominator.
4248        let combos = [
4249            vec![
4250                weighted_combo("Ac", "Ad", 1.0),
4251                weighted_combo("Ah", "As", 1.0),
4252                weighted_combo("Qd", "Qc", 1.0),
4253            ],
4254            vec![
4255                weighted_combo("Kc", "Kd", 1.0),
4256                weighted_combo("Ac", "Ks", 1.0),
4257                weighted_combo("2c", "3d", 1.0),
4258            ],
4259        ];
4260        assert_analytical_exploitability(
4261            analytical_exploitability_trainer(combos).exploitability(),
4262        );
4263    }
4264
4265    #[test]
4266    fn exploitability_chip_units_ignore_range_weight_scale() {
4267        for (oop_scale, ip_scale) in [(1.0, 1.0), (0.25, 1.0), (1.0, 0.7), (0.25, 0.7)] {
4268            let combos = [
4269                vec![
4270                    weighted_combo("Ac", "Ad", oop_scale),
4271                    weighted_combo("Ah", "As", 0.3 * oop_scale),
4272                ],
4273                vec![
4274                    weighted_combo("Kc", "Kd", ip_scale),
4275                    weighted_combo("Ac", "Ks", 0.6 * ip_scale),
4276                ],
4277            ];
4278            assert_analytical_exploitability(
4279                analytical_exploitability_trainer(combos).exploitability(),
4280            );
4281        }
4282    }
4283
4284    #[test]
4285    fn exploitability_rejects_zero_or_nonfinite_joint_mass() {
4286        for combos in [
4287            [
4288                vec![weighted_combo("Ac", "Ad", 1.0)],
4289                vec![weighted_combo("Ac", "Ks", 1.0)],
4290            ],
4291            [
4292                vec![weighted_combo("Ac", "Ad", 0.0)],
4293                vec![weighted_combo("Kc", "Kd", 1.0)],
4294            ],
4295            [
4296                vec![weighted_combo("Qd", "Qc", 1.0)],
4297                vec![weighted_combo("Kc", "Kd", 1.0)],
4298            ],
4299            [
4300                vec![weighted_combo("Ac", "Ad", f64::INFINITY)],
4301                vec![weighted_combo("Kc", "Kd", 1.0)],
4302            ],
4303            [
4304                vec![weighted_combo("Ac", "Ad", f64::NAN)],
4305                vec![weighted_combo("Kc", "Kd", 1.0)],
4306            ],
4307        ] {
4308            let expl = analytical_exploitability_trainer(combos).exploitability();
4309            assert!(
4310                expl.oop.is_nan() && expl.ip.is_nan() && expl.total.is_nan(),
4311                "undefined metric must not appear converged: {expl:?}"
4312            );
4313        }
4314    }
4315
4316    /// `best_response_chance_value` (the counterpart to `chance_value`'s
4317    /// suit-isomorphism relabeling) is only exercised by a scenario with an
4318    /// actual `Chance` node whose classes have more than one member — this
4319    /// codebase has repeatedly found relabeling bugs that only manifest
4320    /// with isomorphism enabled, so mirror
4321    /// `suit_isomorphism_reduced_and_unreduced_converge_to_the_same_equilibrium`
4322    /// and check that isomorphism-reduced and unreduced trees converge to
4323    /// the same exploitability rather than merely not-crashing.
4324    #[test]
4325    fn exploitability_isomorphism_reduced_and_unreduced_match() {
4326        let combos = two_suit_scenario_combos();
4327        let reduced = build_two_suit_scenario(true, combos.clone());
4328        let unreduced = build_two_suit_scenario(false, combos);
4329
4330        let iterations = 3_000;
4331        let mut reduced_trainer = Trainer::new(
4332            reduced.tree,
4333            reduced.trainer_combos,
4334            TrainerOptions {
4335                algorithm: SolverAlgorithm::CfrPlus,
4336                ..TrainerOptions::default()
4337            },
4338        )
4339        .unwrap();
4340        reduced_trainer.train(iterations);
4341        let mut unreduced_trainer = Trainer::new(
4342            unreduced.tree,
4343            unreduced.trainer_combos,
4344            TrainerOptions {
4345                algorithm: SolverAlgorithm::CfrPlus,
4346                ..TrainerOptions::default()
4347            },
4348        )
4349        .unwrap();
4350        unreduced_trainer.train(iterations);
4351
4352        let reduced_expl = reduced_trainer.exploitability();
4353        let unreduced_expl = unreduced_trainer.exploitability();
4354        // Reduced/unreduced training takes different floating-point paths
4355        // (different iteration order over the tree) to the same underlying
4356        // equilibrium, so — unlike the average-strategy comparison this test
4357        // mirrors, whose *probabilities* are naturally bounded to [0, 1] and
4358        // so can use a tight absolute tolerance — exploitability's chip
4359        // magnitude calls for a relative tolerance instead.
4360        let rel_diff =
4361            (reduced_expl.total - unreduced_expl.total).abs() / unreduced_expl.total.abs().max(1.0);
4362        assert!(
4363            rel_diff < 0.1,
4364            "expected matching exploitability with isomorphism enabled/disabled: reduced={}, unreduced={}",
4365            reduced_expl.total,
4366            unreduced_expl.total
4367        );
4368    }
4369}
4370
4371#[cfg(test)]
4372mod terminal_regression_tests {
4373    use super::*;
4374    use crate::card::Card;
4375    use crate::solver::tree::{Player, Tree};
4376    use crate::solver::Chips;
4377
4378    fn close(actual: f64, expected: f64) {
4379        let tolerance = 2e-10 + expected.abs() * 2e-12;
4380        assert!(
4381            (actual - expected).abs() <= tolerance,
4382            "actual={actual}, expected={expected}, tolerance={tolerance}"
4383        );
4384    }
4385
4386    #[test]
4387    fn linear_terminals_match_pairwise_oracle() {
4388        // Entire deck includes initial-board conflicts, overlaps, equal-rank
4389        // groups, empty support and every valid two-card blocker pattern.
4390        let full: Vec<_> = (0..52)
4391            .flat_map(|a| (a + 1..52).map(move |b| Combo::new(Card(a), Card(b), 1.0)))
4392            .collect();
4393        let mut asymmetric = full.iter().step_by(7).copied().collect::<Vec<_>>();
4394        asymmetric.reverse();
4395        let Combo {
4396            cards: [a, b],
4397            weight,
4398        } = asymmetric[3];
4399        asymmetric.push(Combo::new(b, a, weight)); // repeated, reversed exact pair
4400        for board in [
4401            ["2c", "7d", "9h", "Js", "Qd"],
4402            ["Tc", "Jc", "Qc", "Kc", "Ac"],
4403            ["Jh", "Js", "2c", "2d", "3h"],
4404        ] {
4405            let board: Vec<_> = board.iter().map(|s| s.parse::<Card>().unwrap()).collect();
4406            for combos in [
4407                [full.clone(), full.clone()],
4408                [asymmetric.clone(), full.clone()],
4409                [full.clone(), Vec::new()],
4410            ] {
4411                let tree = Tree {
4412                    board: board.clone(),
4413                    root: Node::Terminal(Terminal::Showdown {
4414                        invested: [37.0, 121.0],
4415                    }),
4416                    num_decision_nodes: 0,
4417                };
4418                // Unchecked: blocked, repeated, and empty ranges exercise the
4419                // kernels' degenerate paths.
4420                let trainer = Trainer::new_unchecked(
4421                    tree,
4422                    combos,
4423                    TrainerOptions {
4424                        algorithm: SolverAlgorithm::CfrPlus,
4425                        ..TrainerOptions::default()
4426                    },
4427                );
4428                for phase in 0..3 {
4429                    let reach: [Vec<f64>; 2] = std::array::from_fn(|p| {
4430                        (0..trainer.game.combos[p].len())
4431                            .map(|i| {
4432                                if phase == 2 || (i + phase) % 5 == 0 {
4433                                    0.0
4434                                } else {
4435                                    ((i * 37 + p * 19 + phase) % 103) as f64 / 103.0
4436                                }
4437                            })
4438                            .collect()
4439                    });
4440                    for terminal in [
4441                        Terminal::Showdown {
4442                            invested: [37.0, 121.0],
4443                        },
4444                        Terminal::Showdown {
4445                            invested: [50.0, 50.0],
4446                        },
4447                        Terminal::Fold {
4448                            winner: Player::Oop,
4449                            invested: [37.0, 121.0],
4450                        },
4451                        Terminal::Fold {
4452                            winner: Player::Ip,
4453                            invested: [37.0, 121.0],
4454                        },
4455                    ] {
4456                        let scores = eval_combos_if_complete(&trainer.game.combos, &board);
4457                        trainer
4458                            .game
4459                            .use_pairwise_terminals
4460                            .store(false, std::sync::atomic::Ordering::Relaxed);
4461                        let actual = trainer
4462                            .game
4463                            .terminal_value(&terminal, &reach, &board, &scores);
4464                        if let Terminal::Showdown { invested } = &terminal {
4465                            for p in 0..2 {
4466                                let before =
4467                                    trainer.game.terminal_index.showdown_before_rank_cache(
4468                                        &trainer.game.combos,
4469                                        p,
4470                                        &reach[1 - p],
4471                                        &scores,
4472                                        &trainer.game.board_order_cache[&board],
4473                                        mask_of(&board),
4474                                        invested,
4475                                    );
4476                                assert_eq!(
4477                                    actual[p].iter().map(|x| x.to_bits()).collect::<Vec<_>>(),
4478                                    before.iter().map(|x| x.to_bits()).collect::<Vec<_>>()
4479                                );
4480                            }
4481                        }
4482                        trainer
4483                            .game
4484                            .use_pairwise_terminals
4485                            .store(true, std::sync::atomic::Ordering::Relaxed);
4486                        let reference = trainer
4487                            .game
4488                            .terminal_value(&terminal, &reach, &board, &scores);
4489                        for p in 0..2 {
4490                            for (a, b) in actual[p].iter().zip(&reference[p]) {
4491                                close(*a, *b);
4492                            }
4493                        }
4494                    }
4495                }
4496            }
4497        }
4498    }
4499
4500    #[test]
4501    fn linear_terminals_preserve_training_and_best_response() {
4502        use crate::range::Range;
4503        use crate::solver::tree::{build_tree, GameConfig};
4504        for board in [
4505            vec!["2c", "7d", "9h", "Js", "Qd"],
4506            vec!["Jh", "Js", "2c", "2d"],
4507        ] {
4508            let board: Vec<_> = board.iter().map(|s| s.parse::<Card>().unwrap()).collect();
4509            let combos: [Vec<_>; 2] = ["AA,KK,JJ,54s:0.3", "QQ,TT,88,65s:0.7"].map(|s| {
4510                let mut v = Range::parse(s).unwrap().combos(CardSet::from_cards(&board));
4511                v.sort_by_key(|c| (c.cards[0], c.cards[1]));
4512                v
4513            });
4514            let cfg = GameConfig {
4515                board: board.clone(),
4516                pot: Chips::whole(100),
4517                effective_stack: Chips::whole(100),
4518                bet_sizes: vec![0.5],
4519                max_raises: 0,
4520                suit_isomorphism: false,
4521            };
4522            let mut actual = Trainer::new(
4523                build_tree(&cfg).unwrap(),
4524                combos.clone(),
4525                TrainerOptions {
4526                    algorithm: SolverAlgorithm::CfrPlus,
4527                    ..TrainerOptions::default()
4528                },
4529            )
4530            .unwrap();
4531            let mut reference = Trainer::new(
4532                build_tree(&cfg).unwrap(),
4533                combos,
4534                TrainerOptions {
4535                    algorithm: SolverAlgorithm::CfrPlus,
4536                    ..TrainerOptions::default()
4537                },
4538            )
4539            .unwrap();
4540            reference
4541                .game
4542                .use_pairwise_terminals
4543                .store(true, std::sync::atomic::Ordering::Relaxed);
4544            let ev_a = actual.train(60);
4545            let ev_b = reference.train(60);
4546            for p in 0..2 {
4547                close(ev_a[p], ev_b[p]);
4548            }
4549            for id in 0..actual.game.tree.num_decision_nodes {
4550                for (a, b) in actual
4551                    .average_strategy(id)
4552                    .iter()
4553                    .flatten()
4554                    .zip(reference.average_strategy(id).iter().flatten())
4555                {
4556                    close(*a, *b);
4557                }
4558            }
4559            let a = actual.exploitability();
4560            let b = reference.exploitability();
4561            close(a.oop, b.oop);
4562            close(a.ip, b.ip);
4563            close(a.total, b.total);
4564            let a = actual.evaluate().nodes;
4565            let b = reference.evaluate().nodes;
4566            for (eval, other) in a.iter().zip(&b) {
4567                for (x, y) in eval.ev.iter().zip(&other.ev) {
4568                    close(*x, *y);
4569                }
4570            }
4571        }
4572    }
4573}
4574
4575#[cfg(test)]
4576#[path = "cfr/target_values_tests.rs"]
4577mod target_values_tests;
4578
4579#[cfg(test)]
4580#[path = "suit_reduction_tests.rs"]
4581mod suit_reduction_tests;
4582
4583fn has_suit_reduction(node: &Node) -> bool {
4584    match node {
4585        Node::Chance { children } => children
4586            .iter()
4587            .any(|(members, child)| members.len() > 1 || has_suit_reduction(child)),
4588        Node::Decision { children, .. } => children.iter().any(has_suit_reduction),
4589        Node::Terminal(_) => false,
4590    }
4591}
4592
4593/// The free-suit transpositions generate the board's full stabilizer. Union
4594/// bucket indices so overlapping abstraction buckets still form a partition.
4595fn suit_bucket_groups(
4596    board: &[Card],
4597    combos: &[Vec<Combo>; 2],
4598    index: &[HashMap<(Card, Card), usize>; 2],
4599    maps: &[Vec<usize>; 2],
4600) -> [Vec<Vec<usize>>; 2] {
4601    let free: Vec<u8> = (0..4)
4602        .filter(|s| !board.iter().any(|&c| c.suit() == *s))
4603        .collect();
4604    std::array::from_fn(|p| {
4605        if free.len() < 2 {
4606            return Vec::new();
4607        }
4608        let n = maps[p].iter().max().map_or(0, |b| b + 1);
4609        let mut parent: Vec<usize> = (0..n).collect();
4610        fn root(parent: &[usize], mut i: usize) -> usize {
4611            while parent[i] != i {
4612                i = parent[i];
4613            }
4614            i
4615        }
4616        for (a, &sa) in free.iter().enumerate() {
4617            for &sb in &free[a + 1..] {
4618                for (
4619                    i,
4620                    &Combo {
4621                        cards: [h1, h2],
4622                        weight: w,
4623                    },
4624                ) in combos[p].iter().enumerate()
4625                {
4626                    let pair = normalize_pair(swap_suit(h1, sa, sb), swap_suit(h2, sa, sb));
4627                    let &j = index[p]
4628                        .get(&pair)
4629                        .expect("suit reduction requires suit-closed ranges");
4630                    assert_eq!(
4631                        w, combos[p][j].weight,
4632                        "suit reduction requires suit-symmetric range weights"
4633                    );
4634                    let (x, y) = (root(&parent, maps[p][i]), root(&parent, maps[p][j]));
4635                    parent[x.max(y)] = x.min(y);
4636                }
4637            }
4638        }
4639        let mut groups = vec![Vec::new(); n];
4640        for i in 0..n {
4641            groups[root(&parent, i)].push(i);
4642        }
4643        groups.into_iter().filter(|group| group.len() > 1).collect()
4644    })
4645}