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