1use 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
39type 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#[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
80pub struct Trainer {
113 game: Arc<SolverGame>,
114 algorithm: SolverAlgorithm,
115 update_schedule: UpdateSchedule,
116 iterations_completed: u64,
118 node_data: Vec<Mutex<NodeData>>,
119}
120
121#[derive(Debug, Clone, PartialEq)]
151pub struct Policy {
152 rows: Vec<Vec<Vec<f64>>>,
153}
154
155impl Policy {
156 pub fn rows(&self) -> &[Vec<Vec<f64>>] {
158 &self.rows
159 }
160}
161
162#[derive(Debug, Clone, PartialEq, Eq)]
164#[non_exhaustive]
165pub enum PolicyError {
166 NodeCount {
168 policy: usize,
170 game: usize,
172 },
173 Shape {
175 node: usize,
177 },
178 NotDistribution {
180 node: usize,
182 },
183 NotSymmetric {
185 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#[derive(Debug, Clone, PartialEq, Eq)]
209#[non_exhaustive]
210pub enum TrainerError {
211 Board(BoardError),
213 TreeBoardMismatch,
216 InvalidTree {
222 reason: &'static str,
224 },
225 EmptyRange {
227 player: Player,
229 },
230 InvalidCombo {
232 player: Player,
234 index: usize,
236 },
237 DuplicateCombo {
239 player: Player,
241 index: usize,
243 },
244 ComboConflictsWithBoard {
248 player: Player,
250 index: usize,
252 },
253 InvalidWeight {
255 player: Player,
257 index: usize,
259 },
260 NoCompatibleDeals,
263 ZeroBuckets,
265 AsymmetricRange {
271 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
326fn 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 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
415fn 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 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
500pub struct SolverGame {
507 tree: super::tree::Tree,
508 initial_board: Vec<Card>,
509 combos: [Vec<Combo>; 2],
510 board_eval_cache: HashMap<Vec<Card>, Arc<[Vec<u32>; 2]>>,
514 combo_index: [HashMap<(Card, Card), usize>; 2],
519 terminal_index: TerminalIndex,
521 board_order_cache: HashMap<Vec<Card>, Arc<BoardOrder>>,
522 abstraction: CardAbstraction,
526 bucket_maps: HashMap<Vec<Card>, Arc<[Vec<usize>; 2]>>,
531 identity_buckets: [Vec<usize>; 2],
535 suit_groups: HashMap<Vec<Card>, Arc<SuitGroups>>,
539 node_meta: Vec<(usize, Vec<Card>)>,
545 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#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
558pub struct TrainerOptions {
559 pub algorithm: SolverAlgorithm,
561 pub schedule: UpdateSchedule,
563 pub abstraction: CardAbstraction,
565}
566
567#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
576pub struct CardAbstraction {
577 pub flop: Option<usize>,
579 pub turn: Option<usize>,
581 pub river: Option<usize>,
583}
584
585#[derive(Debug, Clone, PartialEq)]
587#[non_exhaustive]
588pub struct Evaluation {
589 pub nodes: Vec<NodeEvaluation>,
591 pub root_values: [f64; 2],
597}
598
599#[derive(Debug, Clone, PartialEq)]
604pub struct NodeEvaluation {
605 pub ev: Vec<f64>,
612 pub equity: Option<Vec<f64>>,
618}
619
620#[derive(Debug, Clone, Copy, PartialEq)]
631pub struct Exploitability {
632 pub oop: f64,
634 pub ip: f64,
636 pub total: f64,
638}
639
640impl std::fmt::Debug for Trainer {
641 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 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 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 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 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 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 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 pub fn algorithm(&self) -> SolverAlgorithm {
847 self.algorithm
848 }
849
850 pub fn update_schedule(&self) -> UpdateSchedule {
852 self.update_schedule
853 }
854
855 pub fn iterations_completed(&self) -> u64 {
860 self.iterations_completed
861 }
862
863 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 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 pub fn game(&self) -> &Arc<SolverGame> {
922 &self.game
923 }
924
925 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 pub fn evaluate(&self) -> Evaluation {
944 self.game.evaluate(&self.policy())
945 }
946
947 pub fn exploitability(&self) -> Exploitability {
949 self.game.exploitability(&self.policy())
950 }
951
952 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 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 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 #[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 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 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 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 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 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 pub fn tree(&self) -> &Node {
1130 &self.tree.root
1131 }
1132
1133 pub fn board(&self) -> &[Card] {
1135 &self.tree.board
1136 }
1137
1138 pub fn node_board(&self, node_id: usize) -> &[Card] {
1144 &self.node_meta[node_id].1
1145 }
1146
1147 pub fn combos(&self, player: Player) -> &[Combo] {
1150 &self.combos[player.index()]
1151 }
1152
1153 pub fn abstraction(&self) -> CardAbstraction {
1155 self.abstraction
1156 }
1157
1158 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 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 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 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 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 #[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 #[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 #[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 #[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
1502fn 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
1528fn 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
1542fn 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
1582fn 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 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
1614fn 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
1644fn 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 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
1678fn 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 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; }
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
1775fn 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
1794fn 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 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 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 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 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 let oop_range = Range::parse("JJ,KQo").unwrap();
2003 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; 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 }
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); 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); let expected_call = pot / (pot + bet); 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 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 fn multi_street_scenario_combos() -> [Vec<Combo>; 2] {
2185 let dead = CardSet::from_cards(&turn_board());
2186 let oop_combos = Range::parse("JJ,54o").unwrap().combos(dead);
2188 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); 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 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 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); let expected_call = pot / (pot + bet); 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 fn two_suit_turn_board() -> Vec<Card> {
2351 ["2c", "7d", "9c", "Jd"]
2356 .iter()
2357 .map(|s| s.parse::<Card>().unwrap())
2358 .collect()
2359 }
2360
2361 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 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 #[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 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; }
2522 assert!(
2523 seen.insert(b),
2524 "expected every distinct-score combo to get a distinct bucket, got {bijective:?}"
2525 );
2526 }
2527 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 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 #[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 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 #[test]
2651 fn river_buckets_reduced_stays_zero_sum_and_respects_hand_strength_order() {
2652 let board = river_board(); let dead = CardSet::from_cards(&board);
2654 let oop_range = Range::parse("JJ,QQ,KQo,72o").unwrap();
2657 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]) .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 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 #[test]
2759 fn avg_score_matches_naive_full_enumeration_average() {
2760 let board = two_suit_turn_board(); 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 ["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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[test]
3187 fn equity_is_none_before_the_river() {
3188 let scenario = build_multi_street_scenario(); 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 #[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 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 #[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 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 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 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 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 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 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 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 #[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 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 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)); 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 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
3937fn 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}