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 reach_scratch;
37use reach_scratch::ReachScratch;
38
39struct NodeData {
40 regret_sum: Vec<Vec<f64>>,
41 strategy_sum: Vec<Vec<f64>>,
42}
43
44impl NodeData {
45 fn empty() -> Self {
46 Self {
47 regret_sum: Vec::new(),
48 strategy_sum: Vec::new(),
49 }
50 }
51
52 fn sized(num_actions: usize, num_combos: usize) -> Self {
53 Self {
54 regret_sum: vec![vec![0.0; num_combos]; num_actions],
55 strategy_sum: vec![vec![0.0; num_combos]; num_actions],
56 }
57 }
58}
59
60#[derive(Clone, Copy)]
64struct TrainingPass {
65 update: IterationUpdate,
66 updating: Option<usize>,
67 values: u8,
68}
69
70impl TrainingPass {
71 fn computes(self, player: usize) -> bool {
72 self.values & (1 << player) != 0
73 }
74}
75
76pub struct Trainer {
109 game: Arc<SolverGame>,
110 algorithm: SolverAlgorithm,
111 update_schedule: UpdateSchedule,
112 iterations_completed: u64,
114 node_data: Vec<Mutex<NodeData>>,
115}
116
117#[derive(Debug, Clone, PartialEq)]
147pub struct Policy {
148 rows: Vec<Vec<Vec<f64>>>,
149}
150
151impl Policy {
152 pub fn rows(&self) -> &[Vec<Vec<f64>>] {
154 &self.rows
155 }
156}
157
158#[derive(Debug, Clone, PartialEq, Eq)]
160#[non_exhaustive]
161pub enum PolicyError {
162 NodeCount {
164 policy: usize,
166 game: usize,
168 },
169 Shape {
171 node: usize,
173 },
174 NotDistribution {
176 node: usize,
178 },
179 NotSymmetric {
181 node: usize,
183 },
184}
185
186impl std::fmt::Display for PolicyError {
187 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
188 match self {
189 Self::NodeCount { policy, game } => {
190 write!(f, "policy has {policy} nodes, game has {game}")
191 }
192 Self::Shape { node } => write!(f, "policy shape does not match node {node}"),
193 Self::NotDistribution { node } => {
194 write!(f, "policy at node {node} is not a probability distribution")
195 }
196 Self::NotSymmetric { node } => write!(f, "policy at node {node} is not suit-symmetric"),
197 }
198 }
199}
200
201impl std::error::Error for PolicyError {}
202
203#[derive(Debug, Clone, PartialEq, Eq)]
205#[non_exhaustive]
206pub enum TrainerError {
207 Board(BoardError),
209 TreeBoardMismatch,
212 InvalidTree {
218 reason: &'static str,
220 },
221 EmptyRange {
223 player: Player,
225 },
226 InvalidCombo {
228 player: Player,
230 index: usize,
232 },
233 DuplicateCombo {
235 player: Player,
237 index: usize,
239 },
240 ComboConflictsWithBoard {
244 player: Player,
246 index: usize,
248 },
249 InvalidWeight {
251 player: Player,
253 index: usize,
255 },
256 NoCompatibleDeals,
259 ZeroBuckets,
261 AsymmetricRange {
267 player: Player,
269 },
270}
271
272impl std::fmt::Display for TrainerError {
273 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
274 match self {
275 Self::Board(error) => write!(f, "invalid initial board: {error}"),
276 Self::TreeBoardMismatch => write!(f, "tree does not match the initial board"),
277 Self::InvalidTree { reason } => write!(f, "invalid tree: {reason}"),
278 Self::EmptyRange { player } => {
279 write!(f, "{player:?} range has no combo with positive weight")
280 }
281 Self::InvalidCombo { player, index } => {
282 write!(f, "{player:?} combo {index} must hold two distinct cards")
283 }
284 Self::DuplicateCombo { player, index } => {
285 write!(f, "{player:?} combo {index} repeats an earlier combo")
286 }
287 Self::ComboConflictsWithBoard { player, index } => write!(
288 f,
289 "{player:?} combo {index} uses a card on the initial board"
290 ),
291 Self::InvalidWeight { player, index } => write!(
292 f,
293 "{player:?} combo {index} weight must be finite and nonnegative"
294 ),
295 Self::NoCompatibleDeals => {
296 write!(f, "no pair of positive-weight combos can be dealt together")
297 }
298 Self::ZeroBuckets => write!(f, "card abstraction bucket counts must be positive"),
299 Self::AsymmetricRange { player } => write!(
300 f,
301 "{player:?} range must be suit-symmetric for suit isomorphism or flop/turn buckets"
302 ),
303 }
304 }
305}
306
307impl std::error::Error for TrainerError {
308 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
309 match self {
310 Self::Board(error) => Some(error),
311 _ => None,
312 }
313 }
314}
315
316impl From<BoardError> for TrainerError {
317 fn from(error: BoardError) -> Self {
318 Self::Board(error)
319 }
320}
321
322fn validate_trainer_inputs(
324 tree: &super::tree::Tree,
325 combos: &[Vec<Combo>; 2],
326 abstraction: CardAbstraction,
327) -> Result<(), TrainerError> {
328 let initial_board = tree.board.as_slice();
329 validate_board(initial_board)?;
330 let mut seen_ids = vec![false; tree.num_decision_nodes];
331 validate_tree(&tree.root, &mut initial_board.to_vec(), &mut seen_ids)?;
332 if seen_ids.iter().any(|&seen| !seen) {
333 return Err(TrainerError::InvalidTree {
334 reason: "decision ids must cover 0..num_decision_nodes",
335 });
336 }
337
338 let board = mask_of(initial_board);
339 let mut masks = [Vec::new(), Vec::new()];
340 for (p, player) in [Player::Oop, Player::Ip].into_iter().enumerate() {
341 let mut seen = std::collections::HashSet::new();
342 for (index, combo) in combos[p].iter().enumerate() {
343 let [a, b] = combo.cards;
344 if a == b {
345 return Err(TrainerError::InvalidCombo { player, index });
346 }
347 if !combo.weight.is_finite() || combo.weight < 0.0 {
348 return Err(TrainerError::InvalidWeight { player, index });
349 }
350 if !seen.insert(normalize_pair(a, b)) {
351 return Err(TrainerError::DuplicateCombo { player, index });
352 }
353 if combo.bits() & board != 0 {
354 return Err(TrainerError::ComboConflictsWithBoard { player, index });
355 }
356 if combo.weight > 0.0 {
357 masks[p].push(combo.bits());
358 }
359 }
360 if masks[p].is_empty() {
361 return Err(TrainerError::EmptyRange { player });
362 }
363 }
364 if !masks[0]
365 .iter()
366 .any(|&oop| masks[1].iter().any(|&ip| oop & ip == 0))
367 {
368 return Err(TrainerError::NoCompatibleDeals);
369 }
370
371 if [abstraction.flop, abstraction.turn, abstraction.river].contains(&Some(0)) {
372 return Err(TrainerError::ZeroBuckets);
373 }
374 let reduced = has_suit_reduction(&tree.root);
380 let averaged_buckets = (abstraction.flop.is_some() && initial_board.len() == 3)
381 || (abstraction.turn.is_some() && initial_board.len() <= 4);
382 if reduced || averaged_buckets {
383 let free: Vec<u8> = (0..4)
384 .filter(|&s| !initial_board.iter().any(|&c| c.suit() == s))
385 .collect();
386 for (p, player) in [Player::Oop, Player::Ip].into_iter().enumerate() {
387 let weights: HashMap<(Card, Card), f64> = combos[p]
388 .iter()
389 .map(|combo| (normalize_pair(combo.cards[0], combo.cards[1]), combo.weight))
390 .collect();
391 for (i, &sa) in free.iter().enumerate() {
392 for &sb in &free[i + 1..] {
393 for combo in &combos[p] {
394 let [a, b] = combo.cards;
395 let swapped = normalize_pair(swap_suit(a, sa, sb), swap_suit(b, sa, sb));
396 let symmetric = match weights.get(&swapped) {
397 Some(&weight) => !reduced || weight == combo.weight,
398 None => false,
399 };
400 if !symmetric {
401 return Err(TrainerError::AsymmetricRange { player });
402 }
403 }
404 }
405 }
406 }
407 }
408 Ok(())
409}
410
411fn validate_tree(
413 node: &Node,
414 board: &mut Vec<Card>,
415 seen_ids: &mut [bool],
416) -> Result<(), TrainerError> {
417 let invalid = |reason| Err(TrainerError::InvalidTree { reason });
418 match node {
419 Node::Decision {
420 id,
421 actions,
422 children,
423 ..
424 } => {
425 match seen_ids.get_mut(*id) {
426 Some(seen) if !*seen => *seen = true,
427 Some(_) => return invalid("decision ids must be unique"),
428 None => return invalid("decision ids must be below num_decision_nodes"),
429 }
430 if actions.is_empty() || actions.len() != children.len() {
431 return invalid("decisions need matching nonempty actions and children");
432 }
433 for child in children {
434 validate_tree(child, board, seen_ids)?;
435 }
436 }
437 Node::Chance { children } => {
438 if board.len() >= 5 {
439 return Err(TrainerError::TreeBoardMismatch);
440 }
441 let mut dealt = mask_of(board);
442 let mut count = 0;
443 for (members, _) in children {
444 if members.is_empty() {
445 return invalid("chance classes must not be empty");
446 }
447 for &card in members {
448 if mask_has(dealt, card) {
449 return invalid("chance nodes must deal each undealt card exactly once");
450 }
451 dealt |= bit(card);
452 count += 1;
453 }
454 if members.len() > 1
458 && members.iter().any(|&card| {
459 card.rank() != members[0].rank()
460 || board.iter().any(|&b| b.suit() == card.suit())
461 })
462 {
463 return invalid(
464 "chance classes must group one rank in suits absent from the board",
465 );
466 }
467 }
468 if count != 52 - board.len() {
469 return invalid("chance nodes must deal each undealt card exactly once");
470 }
471 for (members, child) in children {
472 board.push(members[0]);
473 let result = validate_tree(child, board, seen_ids);
474 board.pop();
475 result?;
476 }
477 }
478 Node::Terminal(terminal) => {
479 let invested = match terminal {
480 Terminal::Fold { invested, .. } => invested,
481 Terminal::Showdown { invested } => {
482 if board.len() != 5 {
483 return Err(TrainerError::TreeBoardMismatch);
484 }
485 invested
486 }
487 };
488 if invested.iter().any(|x| !x.is_finite() || *x < 0.0) {
489 return invalid("terminal investments must be finite and nonnegative");
490 }
491 }
492 }
493 Ok(())
494}
495
496pub struct SolverGame {
503 tree: super::tree::Tree,
504 initial_board: Vec<Card>,
505 combos: [Vec<Combo>; 2],
506 board_eval_cache: HashMap<Vec<Card>, [Vec<u32>; 2]>,
510 combo_index: [HashMap<(Card, Card), usize>; 2],
515 terminal_index: TerminalIndex,
517 board_order_cache: HashMap<Vec<Card>, BoardOrder>,
518 abstraction: CardAbstraction,
522 bucket_maps: HashMap<Vec<Card>, [Vec<usize>; 2]>,
527 identity_buckets: [Vec<usize>; 2],
531 suit_groups: HashMap<Vec<Card>, [Vec<Vec<usize>>; 2]>,
535 node_meta: Vec<(usize, Vec<Card>)>,
541 #[cfg(test)]
542 use_pairwise_terminals: std::sync::atomic::AtomicBool,
543 #[cfg(test)]
544 terminal_calls: [std::sync::atomic::AtomicUsize; 2],
545}
546
547#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
552pub struct TrainerOptions {
553 pub algorithm: SolverAlgorithm,
555 pub schedule: UpdateSchedule,
557 pub abstraction: CardAbstraction,
559}
560
561#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
570pub struct CardAbstraction {
571 pub flop: Option<usize>,
573 pub turn: Option<usize>,
575 pub river: Option<usize>,
577}
578
579#[derive(Debug, Clone, PartialEq)]
581#[non_exhaustive]
582pub struct Evaluation {
583 pub nodes: Vec<NodeEvaluation>,
585 pub root_values: [f64; 2],
591}
592
593#[derive(Debug, Clone, PartialEq)]
598pub struct NodeEvaluation {
599 pub ev: Vec<f64>,
606 pub equity: Option<Vec<f64>>,
612}
613
614#[derive(Debug, Clone, Copy, PartialEq)]
625pub struct Exploitability {
626 pub oop: f64,
628 pub ip: f64,
630 pub total: f64,
632}
633
634impl std::fmt::Debug for Trainer {
635 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
637 f.debug_struct("Trainer")
638 .field("algorithm", &self.algorithm)
639 .field("update_schedule", &self.update_schedule)
640 .field("iterations_completed", &self.iterations_completed)
641 .field("game", &self.game)
642 .finish_non_exhaustive()
643 }
644}
645
646impl std::fmt::Debug for SolverGame {
647 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
649 f.debug_struct("SolverGame")
650 .field("board", &self.tree.board)
651 .field("num_decision_nodes", &self.tree.num_decision_nodes)
652 .field("num_combos", &[self.combos[0].len(), self.combos[1].len()])
653 .field("abstraction", &self.abstraction)
654 .finish_non_exhaustive()
655 }
656}
657
658impl Trainer {
659 pub fn new(
679 tree: super::tree::Tree,
680 combos: [Vec<Combo>; 2],
681 options: TrainerOptions,
682 ) -> Result<Self, TrainerError> {
683 validate_trainer_inputs(&tree, &combos, options.abstraction)?;
684 Ok(Self::new_unchecked(tree, combos, options))
685 }
686
687 fn new_unchecked(
690 tree: super::tree::Tree,
691 combos: [Vec<Combo>; 2],
692 options: TrainerOptions,
693 ) -> Self {
694 let initial_board = tree.board.clone();
695 let TrainerOptions {
696 algorithm,
697 schedule: update_schedule,
698 abstraction,
699 } = options;
700 let mut board_eval_cache = HashMap::new();
701 precompute_board_eval(&tree.root, &initial_board, &combos, &mut board_eval_cache);
702 if initial_board.len() == 5 {
708 board_eval_cache
709 .entry(initial_board.clone())
710 .or_insert_with(|| eval_combos_if_complete(&combos, &initial_board));
711 }
712
713 let combo_index = [build_combo_index(&combos[0]), build_combo_index(&combos[1])];
714 let terminal_index = TerminalIndex::new(&combos);
715 let board_order_cache = board_eval_cache
716 .iter()
717 .filter(|(board, _)| board.len() == 5)
718 .map(|(board, scores)| {
719 (
720 board.clone(),
721 BoardOrder::new(&combos, scores, mask_of(board)),
722 )
723 })
724 .collect();
725
726 let mut bucket_maps: HashMap<Vec<Card>, [Vec<usize>; 2]> = HashMap::new();
727 if let Some(n) = abstraction.river {
728 for (board, scores) in board_eval_cache.iter().filter(|(b, _)| b.len() == 5) {
731 let scores_f64 = [
732 scores[0].iter().map(|&s| s as f64).collect::<Vec<f64>>(),
733 scores[1].iter().map(|&s| s as f64).collect::<Vec<f64>>(),
734 ];
735 bucket_maps.insert(
736 board.clone(),
737 [
738 compute_percentile_buckets(&scores_f64[0], n),
739 compute_percentile_buckets(&scores_f64[1], n),
740 ],
741 );
742 }
743 }
744 if abstraction.flop.is_some() || abstraction.turn.is_some() {
745 let mut reachable_boards = std::collections::HashSet::new();
753 reachable_boards.insert(initial_board.clone());
754 collect_reachable_boards(&tree.root, &initial_board, &mut reachable_boards);
755 let mut avg_score_cache = HashMap::new();
756 for board in &reachable_boards {
757 let n = match board.len() {
758 3 => abstraction.flop,
759 4 => abstraction.turn,
760 _ => None,
761 };
762 if let Some(n) = n {
763 let scores = avg_score(
764 board,
765 &combos,
766 &combo_index,
767 &board_eval_cache,
768 &mut avg_score_cache,
769 );
770 bucket_maps.insert(
771 board.clone(),
772 [
773 compute_percentile_buckets(&scores[0], n),
774 compute_percentile_buckets(&scores[1], n),
775 ],
776 );
777 }
778 }
779 }
780 let identity_buckets = [
781 (0..combos[0].len()).collect(),
782 (0..combos[1].len()).collect(),
783 ];
784
785 let mut node_data: Vec<NodeData> = (0..tree.num_decision_nodes)
786 .map(|_| NodeData::empty())
787 .collect();
788 let mut node_meta: Vec<(usize, Vec<Card>)> = vec![(0, Vec::new()); tree.num_decision_nodes];
789 init_node_data(
790 &tree.root,
791 &initial_board,
792 &bucket_maps,
793 &identity_buckets,
794 &mut node_data,
795 &mut node_meta,
796 );
797 let node_data: Vec<Mutex<NodeData>> = node_data.into_iter().map(Mutex::new).collect();
798 let mut suit_groups = HashMap::new();
799 if has_suit_reduction(&tree.root) {
800 for (_, board) in &node_meta {
801 suit_groups.entry(board.clone()).or_insert_with(|| {
802 let maps = bucket_maps.get(board).unwrap_or(&identity_buckets);
803 suit_bucket_groups(board, &combos, &combo_index, maps)
804 });
805 }
806 }
807
808 let game = SolverGame {
809 tree,
810 initial_board,
811 combos,
812 board_eval_cache,
813 combo_index,
814 terminal_index,
815 board_order_cache,
816 abstraction,
817 bucket_maps,
818 identity_buckets,
819 suit_groups,
820 node_meta,
821 #[cfg(test)]
822 use_pairwise_terminals: std::sync::atomic::AtomicBool::new(false),
823 #[cfg(test)]
824 terminal_calls: std::array::from_fn(|_| std::sync::atomic::AtomicUsize::new(0)),
825 };
826 Self {
827 game: Arc::new(game),
828 algorithm,
829 update_schedule,
830 iterations_completed: 0,
831 node_data,
832 }
833 }
834
835 pub fn algorithm(&self) -> SolverAlgorithm {
837 self.algorithm
838 }
839
840 pub fn update_schedule(&self) -> UpdateSchedule {
842 self.update_schedule
843 }
844
845 pub fn iterations_completed(&self) -> u64 {
850 self.iterations_completed
851 }
852
853 pub fn train(&mut self, iterations: u32) -> [f64; 2] {
864 let mut last = [0.0, 0.0];
865 let game = Arc::clone(&self.game);
867 let board = game.initial_board.clone();
868 let empty_eval = [Vec::new(), Vec::new()];
869 let board_eval = game.board_eval_cache.get(&board).unwrap_or(&empty_eval);
870 for step in 0..iterations {
871 let iteration = self
872 .iterations_completed
873 .checked_add(1)
874 .expect("CFR iteration counter overflow");
875 let update = self.algorithm.iteration(iteration);
876 let reach0: Vec<f64> = self.game.combos[0].iter().map(|c| c.weight).collect();
877 let reach1: Vec<f64> = self.game.combos[1].iter().map(|c| c.weight).collect();
878 let reach = [reach0.as_slice(), reach1.as_slice()];
879 let pass = match self.update_schedule {
880 UpdateSchedule::Simultaneous => TrainingPass {
881 update,
882 updating: None,
883 values: 3,
884 },
885 UpdateSchedule::Alternating => {
886 self.cfr(
887 &self.game.tree.root,
888 reach,
889 &board,
890 board_eval,
891 TrainingPass {
892 update,
893 updating: Some(0),
894 values: 1,
895 },
896 );
897 TrainingPass {
901 update,
902 updating: Some(1),
903 values: if step + 1 == iterations { 3 } else { 2 },
904 }
905 }
906 };
907 let [cfv0, cfv1] = self.cfr(&self.game.tree.root, reach, &board, board_eval, pass);
908 let ev0: f64 = cfv0
909 .iter()
910 .zip(&self.game.combos[0])
911 .map(|(v, c)| v * c.weight)
912 .sum();
913 let ev1: f64 = cfv1
914 .iter()
915 .zip(&self.game.combos[1])
916 .map(|(v, c)| v * c.weight)
917 .sum();
918 last = [ev0, ev1];
919 self.iterations_completed = iteration;
920 }
921 last
922 }
923
924 pub fn game(&self) -> &Arc<SolverGame> {
926 &self.game
927 }
928
929 pub fn policy(&self) -> Policy {
931 Policy {
932 rows: (0..self.node_data.len())
933 .map(|id| self.average_bucket_strategy(id))
934 .collect(),
935 }
936 }
937
938 pub fn evaluate(&self) -> Evaluation {
940 self.game.evaluate(&self.policy())
941 }
942
943 pub fn exploitability(&self) -> Exploitability {
945 self.game.exploitability(&self.policy())
946 }
947
948 pub fn average_strategy(&self, node_id: usize) -> Vec<Vec<f64>> {
954 self.game
955 .expand_strategy(node_id, &self.average_bucket_strategy(node_id))
956 }
957
958 fn average_bucket_strategy(&self, node_id: usize) -> Vec<Vec<f64>> {
960 let (player, board) = &self.game.node_meta[node_id];
961 let (num_buckets, _) = self.game.combo_buckets(*player, board);
962 let data = self.node_data[node_id].lock().unwrap();
963 let num_actions = data.regret_sum.len();
964 let mut bucket_strategy: Vec<Vec<f64>> = (0..num_actions)
965 .map(|a| {
966 (0..num_buckets)
967 .map(|b| {
968 let total: f64 = (0..num_actions).map(|a2| data.strategy_sum[a2][b]).sum();
969 if total > 0.0 {
970 data.strategy_sum[a][b] / total
971 } else {
972 1.0 / num_actions as f64
973 }
974 })
975 .collect()
976 })
977 .collect();
978 self.game.symmetrize_strategy(node_id, &mut bucket_strategy);
979 bucket_strategy
980 }
981
982 fn current_strategy(&self, id: usize, num_actions: usize, num_combos: usize) -> Vec<Vec<f64>> {
983 let data = self.node_data[id].lock().unwrap();
984 let mut strategy = vec![vec![0.0; num_combos]; num_actions];
985 for i in 0..num_combos {
986 let mut total = 0.0;
987 for (regret_row, strat_row) in data.regret_sum.iter().zip(strategy.iter_mut()) {
988 let r = regret_row[i].max(0.0);
989 strat_row[i] = r;
990 total += r;
991 }
992 if total > 0.0 {
993 for row in strategy.iter_mut().take(num_actions) {
994 row[i] /= total;
995 }
996 } else {
997 for row in strategy.iter_mut().take(num_actions) {
998 row[i] = 1.0 / num_actions as f64;
999 }
1000 }
1001 }
1002 self.game.symmetrize_strategy(id, &mut strategy);
1003 strategy
1004 }
1005
1006 fn cfr(
1011 &self,
1012 node: &Node,
1013 reach: [&[f64]; 2],
1014 board: &[Card],
1015 board_eval: &[Vec<u32>; 2],
1016 pass: TrainingPass,
1017 ) -> [Vec<f64>; 2] {
1018 match node {
1019 Node::Terminal(t) => std::array::from_fn(|p| {
1020 if pass.computes(p) {
1021 self.game
1022 .terminal_value_for_player(t, p, reach[1 - p], board, board_eval)
1023 } else {
1024 Vec::new()
1025 }
1026 }),
1027 Node::Chance { children } => self.chance_value(children, reach, board, pass),
1028 Node::Decision {
1029 id,
1030 player,
1031 actions,
1032 children,
1033 } => {
1034 let p = player.index();
1035 let num_own_combos = self.game.combos[p].len();
1036 let num_other_combos = self.game.combos[1 - p].len();
1037 let (num_buckets, buckets) = self.game.combo_buckets(p, board);
1038 let strategy = self.current_strategy(*id, actions.len(), num_buckets);
1039
1040 let child_cfvs: Vec<[Vec<f64>; 2]> = children
1041 .par_iter()
1042 .enumerate()
1043 .map(|(a, child)| {
1044 let mut own_reach = ReachScratch::copy_from(reach[p]);
1048 for i in 0..num_own_combos {
1049 own_reach[i] *= strategy[a][buckets[i]];
1050 }
1051 let mut child_reach = reach;
1052 child_reach[p] = &own_reach;
1053 self.cfr(child, child_reach, board, board_eval, pass)
1054 })
1055 .collect();
1056
1057 let mut own_cfv = vec![0.0; if pass.computes(p) { num_own_combos } else { 0 }];
1058 let mut other_cfv = vec![
1059 0.0;
1060 if pass.computes(1 - p) {
1061 num_other_combos
1062 } else {
1063 0
1064 }
1065 ];
1066 for (a, cfv) in child_cfvs.iter().enumerate() {
1067 let own = &cfv[p];
1068 let other = &cfv[1 - p];
1069 for (i, v) in own_cfv.iter_mut().enumerate() {
1070 *v += strategy[a][buckets[i]] * own[i];
1071 }
1072 for (j, v) in other_cfv.iter_mut().enumerate() {
1073 *v += other[j];
1074 }
1075 }
1076
1077 if pass.updating.is_some_and(|target| target != p) {
1080 return if p == 0 {
1081 [own_cfv, other_cfv]
1082 } else {
1083 [other_cfv, own_cfv]
1084 };
1085 }
1086
1087 if self.game.bucket_maps.is_empty() {
1095 let board_set = mask_of(board);
1096 let mut data = self.node_data[*id].lock().unwrap();
1097 for (a, cfv) in child_cfvs.iter().enumerate() {
1098 for (i, &own) in cfv[p].iter().enumerate() {
1099 let delta = 0.0 + (own - own_cfv[i]);
1102 data.regret_sum[a][i] =
1103 pass.update.regret(data.regret_sum[a][i], delta);
1104 if self.game.combos[p][i].bits() & board_set == 0 {
1105 data.strategy_sum[a][i] += reach[p][i] * strategy[a][i];
1106 }
1107 data.strategy_sum[a][i] =
1108 pass.update.strategy_sum(data.strategy_sum[a][i]);
1109 }
1110 }
1111 return if p == 0 {
1112 [own_cfv, other_cfv]
1113 } else {
1114 [other_cfv, own_cfv]
1115 };
1116 }
1117
1118 let board_set = mask_of(board);
1133 let effective_reach: Vec<f64> = (0..num_own_combos)
1134 .map(|i| {
1135 let [h1, h2] = self.game.combos[p][i].cards;
1136 if mask_has(board_set, h1) || mask_has(board_set, h2) {
1137 0.0
1138 } else {
1139 reach[p][i]
1140 }
1141 })
1142 .collect();
1143 let mut bucket_reach_total = vec![0.0; num_buckets];
1144 let mut bucket_size = vec![0usize; num_buckets];
1145 for i in 0..num_own_combos {
1146 bucket_reach_total[buckets[i]] += effective_reach[i];
1147 bucket_size[buckets[i]] += 1;
1148 }
1149
1150 {
1151 let mut data = self.node_data[*id].lock().unwrap();
1152 for (a, cfv) in child_cfvs.iter().enumerate() {
1153 let own = &cfv[p];
1154 let mut regret_delta = vec![0.0; num_buckets];
1155 for i in 0..num_own_combos {
1156 let b = buckets[i];
1157 let delta = own[i] - own_cfv[i];
1158 let weight = if bucket_reach_total[b] > 0.0 {
1159 effective_reach[i] / bucket_reach_total[b]
1160 } else {
1161 1.0 / bucket_size[b] as f64
1162 };
1163 regret_delta[b] += weight * delta;
1164 data.strategy_sum[a][b] += effective_reach[i] * strategy[a][b];
1165 }
1166 for (b, delta) in regret_delta.iter().enumerate() {
1167 data.regret_sum[a][b] =
1168 pass.update.regret(data.regret_sum[a][b], *delta);
1169 data.strategy_sum[a][b] =
1172 pass.update.strategy_sum(data.strategy_sum[a][b]);
1173 }
1174 }
1175 }
1176
1177 if p == 0 {
1178 [own_cfv, other_cfv]
1179 } else {
1180 [other_cfv, own_cfv]
1181 }
1182 }
1183 }
1184 }
1185
1186 fn chance_value(
1202 &self,
1203 children: &[(Vec<Card>, Node)],
1204 reach: [&[f64]; 2],
1205 board: &[Card],
1206 pass: TrainingPass,
1207 ) -> [Vec<f64>; 2] {
1208 let n: usize = children.iter().map(|(members, _)| members.len()).sum();
1209 let divisor = (n as f64) - 4.0;
1210
1211 let class_results: Vec<(&Vec<Card>, [Vec<f64>; 2])> = children
1212 .par_iter()
1213 .map(|(members, child)| {
1214 let rep = members[0];
1215 let mut child_board = board.to_vec();
1216 child_board.push(rep);
1217 let empty_eval = [Vec::new(), Vec::new()];
1218 let child_board_eval = self
1219 .game
1220 .board_eval_cache
1221 .get(&child_board)
1222 .unwrap_or(&empty_eval);
1223 let child_cfv = self.cfr(child, reach, &child_board, child_board_eval, pass);
1224 (members, child_cfv)
1225 })
1226 .collect();
1227
1228 let mut out: [Vec<f64>; 2] = std::array::from_fn(|p| {
1229 vec![
1230 0.0;
1231 if pass.computes(p) {
1232 self.game.combos[p].len()
1233 } else {
1234 0
1235 }
1236 ]
1237 });
1238 for (members, rep_cfv) in &class_results {
1239 let rep = members[0];
1240 for &card in members.iter() {
1241 for p in 0..2 {
1242 if !pass.computes(p) {
1243 continue;
1244 }
1245 let values = if card == rep {
1246 rep_cfv[p].clone()
1247 } else {
1248 self.game
1249 .relabel_cfv(p, &rep_cfv[p], rep.suit(), card.suit())
1250 };
1251 for (
1252 i,
1253 &Combo {
1254 cards: [h1, h2], ..
1255 },
1256 ) in self.game.combos[p].iter().enumerate()
1257 {
1258 if h1 != card && h2 != card {
1259 out[p][i] += values[i];
1260 }
1261 }
1262 }
1263 }
1264 }
1265 for values in &mut out {
1266 for v in values {
1267 *v /= divisor;
1268 }
1269 }
1270 out
1271 }
1272}
1273
1274impl SolverGame {
1275 fn combo_buckets(&self, player: usize, board: &[Card]) -> (usize, &[usize]) {
1278 bucket_count_and_map(player, board, &self.bucket_maps, &self.identity_buckets)
1279 }
1280
1281 pub fn evaluate(&self, policy: &Policy) -> Evaluation {
1310 let mut out = HashMap::new();
1311 let board = self.initial_board.clone();
1312 let empty_eval = [Vec::new(), Vec::new()];
1313 let board_eval = self.board_eval_cache.get(&board).unwrap_or(&empty_eval);
1314 let reach0: Vec<f64> = self.combos[0].iter().map(|c| c.weight).collect();
1315 let reach1: Vec<f64> = self.combos[1].iter().map(|c| c.weight).collect();
1316 let [cfv0, cfv1] = self.evaluate_node(
1317 policy,
1318 &self.tree.root,
1319 &[reach0, reach1],
1320 &board,
1321 board_eval,
1322 &mut out,
1323 );
1324 let ev0: f64 = cfv0
1325 .iter()
1326 .zip(&self.combos[0])
1327 .map(|(v, c)| v * c.weight)
1328 .sum();
1329 let ev1: f64 = cfv1
1330 .iter()
1331 .zip(&self.combos[1])
1332 .map(|(v, c)| v * c.weight)
1333 .sum();
1334 let nodes = (0..self.node_meta.len())
1336 .map(|id| out.remove(&id).expect("every decision node is evaluated"))
1337 .collect();
1338 Evaluation {
1339 nodes,
1340 root_values: [ev0, ev1],
1341 }
1342 }
1343
1344 pub fn exploitability(&self, policy: &Policy) -> Exploitability {
1349 let board = self.initial_board.clone();
1350 let empty_eval = [Vec::new(), Vec::new()];
1351 let board_eval = self.board_eval_cache.get(&board).unwrap_or(&empty_eval);
1352 let reach0: Vec<f64> = self.combos[0].iter().map(|c| c.weight).collect();
1353 let reach1: Vec<f64> = self.combos[1].iter().map(|c| c.weight).collect();
1354
1355 let board_set = mask_of(&board);
1359 let live = |c: &Combo| !mask_has(board_set, c.cards[0]) && !mask_has(board_set, c.cards[1]);
1360 let compatible_mass =
1361 self.terminal_index
1362 .compatible_mass(&self.combos, 0, &reach1, board_set);
1363 let joint_mass: f64 = self.combos[0]
1364 .iter()
1365 .zip(&compatible_mass)
1366 .filter(|(c, _)| live(c))
1367 .map(|(c, mass)| c.weight * mass)
1368 .sum();
1369 if !joint_mass.is_finite() || joint_mass <= 0.0 {
1370 return Exploitability {
1371 oop: f64::NAN,
1372 ip: f64::NAN,
1373 total: f64::NAN,
1374 };
1375 }
1376
1377 let br0 = self.best_response_value(
1378 policy,
1379 &self.tree.root,
1380 0,
1381 &[reach0.clone(), reach1.clone()],
1382 &board,
1383 board_eval,
1384 );
1385 let br1 = self.best_response_value(
1386 policy,
1387 &self.tree.root,
1388 1,
1389 &[reach0, reach1],
1390 &board,
1391 board_eval,
1392 );
1393 let oop = br0
1394 .iter()
1395 .zip(&self.combos[0])
1396 .filter(|(_, c)| live(c))
1397 .map(|(v, c)| v * c.weight)
1398 .sum::<f64>()
1399 / joint_mass;
1400 let ip = br1
1401 .iter()
1402 .zip(&self.combos[1])
1403 .filter(|(_, c)| live(c))
1404 .map(|(v, c)| v * c.weight)
1405 .sum::<f64>()
1406 / joint_mass;
1407 Exploitability {
1408 oop,
1409 ip,
1410 total: (oop + ip) / 2.0,
1411 }
1412 }
1413
1414 pub fn tree(&self) -> &Node {
1417 &self.tree.root
1418 }
1419
1420 pub fn board(&self) -> &[Card] {
1422 &self.tree.board
1423 }
1424
1425 pub fn node_board(&self, node_id: usize) -> &[Card] {
1431 &self.node_meta[node_id].1
1432 }
1433
1434 pub fn combos(&self, player: Player) -> &[Combo] {
1437 &self.combos[player.index()]
1438 }
1439
1440 pub fn abstraction(&self) -> CardAbstraction {
1442 self.abstraction
1443 }
1444
1445 pub fn average_strategy(&self, policy: &Policy, node_id: usize) -> Vec<Vec<f64>> {
1454 self.expand_strategy(node_id, &policy.rows[node_id])
1455 }
1456
1457 fn expand_strategy(&self, node_id: usize, bucket_strategy: &[Vec<f64>]) -> Vec<Vec<f64>> {
1459 let (player, board) = &self.node_meta[node_id];
1460 let (_, buckets) = self.combo_buckets(*player, board);
1461 bucket_strategy
1462 .iter()
1463 .map(|row| buckets.iter().map(|&b| row[b]).collect())
1464 .collect()
1465 }
1466
1467 pub fn policy_from_rows(&self, rows: Vec<Vec<Vec<f64>>>) -> Result<Policy, PolicyError> {
1478 fn action_counts(node: &Node, out: &mut [usize]) {
1479 match node {
1480 Node::Decision {
1481 id,
1482 actions,
1483 children,
1484 ..
1485 } => {
1486 out[*id] = actions.len();
1487 children.iter().for_each(|child| action_counts(child, out));
1488 }
1489 Node::Chance { children } => children
1490 .iter()
1491 .for_each(|(_, child)| action_counts(child, out)),
1492 Node::Terminal(_) => {}
1493 }
1494 }
1495 if rows.len() != self.num_decision_nodes() {
1496 return Err(PolicyError::NodeCount {
1497 policy: rows.len(),
1498 game: self.num_decision_nodes(),
1499 });
1500 }
1501 let mut actions = vec![0; rows.len()];
1502 action_counts(&self.tree.root, &mut actions);
1503 for (id, node_rows) in rows.iter().enumerate() {
1504 let (player, board) = &self.node_meta[id];
1505 let (num_buckets, _) = self.combo_buckets(*player, board);
1506 if node_rows.len() != actions[id]
1507 || node_rows.iter().any(|row| row.len() != num_buckets)
1508 {
1509 return Err(PolicyError::Shape { node: id });
1510 }
1511 for b in 0..num_buckets {
1512 let total: f64 = node_rows.iter().map(|row| row[b]).sum();
1513 if node_rows
1514 .iter()
1515 .any(|row| !row[b].is_finite() || row[b] < 0.0)
1516 || (total - 1.0).abs() > 1e-9
1517 {
1518 return Err(PolicyError::NotDistribution { node: id });
1519 }
1520 }
1521 if let Some(groups) = self.suit_groups.get(board) {
1522 let asymmetric = groups[*player].iter().any(|group| {
1523 node_rows.iter().any(|row| {
1524 group
1525 .iter()
1526 .any(|&b| row[b].to_bits() != row[group[0]].to_bits())
1527 })
1528 });
1529 if asymmetric {
1530 return Err(PolicyError::NotSymmetric { node: id });
1531 }
1532 }
1533 }
1534 Ok(Policy { rows })
1535 }
1536
1537 pub fn bucket_assignments(&self) -> Vec<(&[Card], &[Vec<usize>; 2])> {
1542 let mut maps: Vec<_> = self
1543 .bucket_maps
1544 .iter()
1545 .map(|(board, maps)| (board.as_slice(), maps))
1546 .collect();
1547 maps.sort_unstable_by(|a, b| a.0.cmp(b.0));
1548 maps
1549 }
1550
1551 pub fn num_decision_nodes(&self) -> usize {
1553 self.node_meta.len()
1554 }
1555
1556 fn symmetrize_strategy(&self, id: usize, strategy: &mut [Vec<f64>]) {
1557 let (player, board) = &self.node_meta[id];
1558 if let Some(groups) = self.suit_groups.get(board) {
1559 for group in &groups[*player] {
1560 for row in strategy.iter_mut() {
1561 let probability =
1562 group.iter().map(|&i| row[i]).sum::<f64>() / group.len() as f64;
1563 for &i in group {
1564 row[i] = probability;
1565 }
1566 }
1567 }
1568 }
1569 }
1570
1571 fn relabel_cfv(&self, player: usize, rep_cfv: &[f64], suit_a: u8, suit_b: u8) -> Vec<f64> {
1581 self.combos[player]
1582 .iter()
1583 .map(
1584 |&Combo {
1585 cards: [h1, h2], ..
1586 }| {
1587 let s1 = swap_suit(h1, suit_a, suit_b);
1588 let s2 = swap_suit(h2, suit_a, suit_b);
1589 let idx = self.combo_index[player][&normalize_pair(s1, s2)];
1590 rep_cfv[idx]
1591 },
1592 )
1593 .collect()
1594 }
1595
1596 fn evaluate_node(
1611 &self,
1612 policy: &Policy,
1613 node: &Node,
1614 reach: &[Vec<f64>; 2],
1615 board: &[Card],
1616 board_eval: &[Vec<u32>; 2],
1617 out: &mut HashMap<usize, NodeEvaluation>,
1618 ) -> [Vec<f64>; 2] {
1619 match node {
1620 Node::Terminal(t) => self.terminal_value(t, reach, board, board_eval),
1621 Node::Chance { children } => {
1622 self.evaluate_chance_value(policy, children, reach, board, out)
1623 }
1624 Node::Decision {
1625 id,
1626 player,
1627 children,
1628 ..
1629 } => {
1630 let p = player.index();
1631 let num_own_combos = self.combos[p].len();
1632 let num_other_combos = self.combos[1 - p].len();
1633 let strategy = self.average_strategy(policy, *id);
1634
1635 let child_cfvs: Vec<[Vec<f64>; 2]> = children
1636 .iter()
1637 .enumerate()
1638 .map(|(a, child)| {
1639 let mut child_reach = reach.clone();
1640 for i in 0..num_own_combos {
1641 child_reach[p][i] *= strategy[a][i];
1642 }
1643 self.evaluate_node(policy, child, &child_reach, board, board_eval, out)
1644 })
1645 .collect();
1646
1647 let mut own_ev = vec![0.0; num_own_combos];
1648 let mut other_ev = vec![0.0; num_other_combos];
1649 for (a, cfv) in child_cfvs.iter().enumerate() {
1650 let own = &cfv[p];
1651 let other = &cfv[1 - p];
1652 for i in 0..num_own_combos {
1653 own_ev[i] += strategy[a][i] * own[i];
1654 }
1655 for (j, v) in other_ev.iter_mut().enumerate() {
1656 *v += other[j];
1657 }
1658 }
1659
1660 let equity = if board.len() == 5 {
1661 Some(self.equity_at_node(p, reach, board, board_eval))
1662 } else {
1663 None
1664 };
1665
1666 let board_set = mask_of(board);
1681 let compatible_mass =
1682 self.terminal_index
1683 .compatible_mass(&self.combos, p, &reach[1 - p], board_set);
1684 let display_ev: Vec<f64> = (0..num_own_combos)
1685 .map(|i| {
1686 let denom = compatible_mass[i];
1687 if denom > 0.0 {
1688 own_ev[i] / denom
1689 } else {
1690 0.0
1691 }
1692 })
1693 .collect();
1694 out.insert(
1695 *id,
1696 NodeEvaluation {
1697 ev: display_ev,
1698 equity,
1699 },
1700 );
1701
1702 if p == 0 {
1703 [own_ev, other_ev]
1704 } else {
1705 [other_ev, own_ev]
1706 }
1707 }
1708 }
1709 }
1710
1711 fn evaluate_chance_value(
1717 &self,
1718 policy: &Policy,
1719 children: &[(Vec<Card>, Node)],
1720 reach: &[Vec<f64>; 2],
1721 board: &[Card],
1722 out: &mut HashMap<usize, NodeEvaluation>,
1723 ) -> [Vec<f64>; 2] {
1724 let n: usize = children.iter().map(|(members, _)| members.len()).sum();
1725 let divisor = (n as f64) - 4.0;
1726
1727 let class_results: Vec<(&Vec<Card>, [Vec<f64>; 2])> = children
1728 .iter()
1729 .map(|(members, child)| {
1730 let rep = members[0];
1731 let mut child_board = board.to_vec();
1732 child_board.push(rep);
1733 let empty_eval = [Vec::new(), Vec::new()];
1734 let child_board_eval = self
1735 .board_eval_cache
1736 .get(&child_board)
1737 .unwrap_or(&empty_eval);
1738 let child_cfv =
1739 self.evaluate_node(policy, child, reach, &child_board, child_board_eval, out);
1740 (members, child_cfv)
1741 })
1742 .collect();
1743
1744 let mut cfv0 = vec![0.0; self.combos[0].len()];
1745 let mut cfv1 = vec![0.0; self.combos[1].len()];
1746
1747 for (members, rep_cfv) in &class_results {
1748 let rep = members[0];
1749 for &card in members.iter() {
1750 let (cfv0_card, cfv1_card) = if card == rep {
1751 (rep_cfv[0].clone(), rep_cfv[1].clone())
1752 } else {
1753 (
1754 self.relabel_cfv(0, &rep_cfv[0], rep.suit(), card.suit()),
1755 self.relabel_cfv(1, &rep_cfv[1], rep.suit(), card.suit()),
1756 )
1757 };
1758 for (
1759 i,
1760 &Combo {
1761 cards: [h1, h2], ..
1762 },
1763 ) in self.combos[0].iter().enumerate()
1764 {
1765 if h1 != card && h2 != card {
1766 cfv0[i] += cfv0_card[i];
1767 }
1768 }
1769 for (
1770 j,
1771 &Combo {
1772 cards: [h1, h2], ..
1773 },
1774 ) in self.combos[1].iter().enumerate()
1775 {
1776 if h1 != card && h2 != card {
1777 cfv1[j] += cfv1_card[j];
1778 }
1779 }
1780 }
1781 }
1782
1783 for v in &mut cfv0 {
1784 *v /= divisor;
1785 }
1786 for v in &mut cfv1 {
1787 *v /= divisor;
1788 }
1789 [cfv0, cfv1]
1790 }
1791
1792 fn best_response_value(
1814 &self,
1815 policy: &Policy,
1816 node: &Node,
1817 x: usize,
1818 reach: &[Vec<f64>; 2],
1819 board: &[Card],
1820 board_eval: &[Vec<u32>; 2],
1821 ) -> Vec<f64> {
1822 match node {
1823 Node::Terminal(t) => {
1824 self.terminal_value_for_player(t, x, &reach[1 - x], board, board_eval)
1825 }
1826 Node::Chance { children } => {
1827 self.best_response_chance_value(policy, children, x, reach, board)
1828 }
1829 Node::Decision {
1830 id,
1831 player,
1832 children,
1833 ..
1834 } => {
1835 let p = player.index();
1836 if p == x {
1837 let num_own_combos = self.combos[x].len();
1838 let child_vals: Vec<Vec<f64>> = children
1839 .par_iter()
1840 .map(|child| {
1841 self.best_response_value(policy, child, x, reach, board, board_eval)
1842 })
1843 .collect();
1844 (0..num_own_combos)
1845 .map(|i| {
1846 child_vals
1847 .iter()
1848 .map(|v| v[i])
1849 .fold(f64::NEG_INFINITY, f64::max)
1850 })
1851 .collect()
1852 } else {
1853 let num_opp_combos = self.combos[p].len();
1854 let strategy = self.average_strategy(policy, *id);
1855 let child_vals: Vec<Vec<f64>> = children
1856 .par_iter()
1857 .enumerate()
1858 .map(|(a, child)| {
1859 let mut child_reach = reach.clone();
1860 for i in 0..num_opp_combos {
1861 child_reach[p][i] *= strategy[a][i];
1862 }
1863 self.best_response_value(
1864 policy,
1865 child,
1866 x,
1867 &child_reach,
1868 board,
1869 board_eval,
1870 )
1871 })
1872 .collect();
1873 let num_own_combos = self.combos[x].len();
1874 let mut out = vec![0.0; num_own_combos];
1875 for v in &child_vals {
1876 for (i, val) in v.iter().enumerate() {
1877 out[i] += val;
1878 }
1879 }
1880 out
1881 }
1882 }
1883 }
1884 }
1885
1886 fn best_response_chance_value(
1892 &self,
1893 policy: &Policy,
1894 children: &[(Vec<Card>, Node)],
1895 x: usize,
1896 reach: &[Vec<f64>; 2],
1897 board: &[Card],
1898 ) -> Vec<f64> {
1899 let n: usize = children.iter().map(|(members, _)| members.len()).sum();
1900 let divisor = (n as f64) - 4.0;
1901
1902 let class_results: Vec<(&Vec<Card>, Vec<f64>)> = children
1903 .par_iter()
1904 .map(|(members, child)| {
1905 let rep = members[0];
1906 let mut child_board = board.to_vec();
1907 child_board.push(rep);
1908 let empty_eval = [Vec::new(), Vec::new()];
1909 let child_board_eval = self
1910 .board_eval_cache
1911 .get(&child_board)
1912 .unwrap_or(&empty_eval);
1913 let child_val = self.best_response_value(
1914 policy,
1915 child,
1916 x,
1917 reach,
1918 &child_board,
1919 child_board_eval,
1920 );
1921 (members, child_val)
1922 })
1923 .collect();
1924
1925 let mut out = vec![0.0; self.combos[x].len()];
1926 for (members, rep_val) in &class_results {
1927 let rep = members[0];
1928 for &card in members.iter() {
1929 let val_card = if card == rep {
1930 rep_val.clone()
1931 } else {
1932 self.relabel_cfv(x, rep_val, rep.suit(), card.suit())
1933 };
1934 for (
1935 i,
1936 &Combo {
1937 cards: [h1, h2], ..
1938 },
1939 ) in self.combos[x].iter().enumerate()
1940 {
1941 if h1 != card && h2 != card {
1942 out[i] += val_card[i];
1943 }
1944 }
1945 }
1946 }
1947 for v in &mut out {
1948 *v /= divisor;
1949 }
1950 out
1951 }
1952
1953 fn equity_at_node(
1964 &self,
1965 player: usize,
1966 reach: &[Vec<f64>; 2],
1967 board: &[Card],
1968 board_eval: &[Vec<u32>; 2],
1969 ) -> Vec<f64> {
1970 let board_set = mask_of(board);
1971 let positive_reach: Vec<f64> = reach[1 - player]
1972 .iter()
1973 .map(|&r| if r <= 0.0 { 0.0 } else { r })
1974 .collect();
1975 let mass =
1976 self.terminal_index
1977 .compatible_mass(&self.combos, player, &positive_reach, board_set);
1978 let net = self.terminal_index.showdown(
1979 &self.combos,
1980 player,
1981 &positive_reach,
1982 board_eval,
1983 &self.board_order_cache[board],
1984 board_set,
1985 &[1.0, 1.0],
1986 );
1987 net.iter()
1988 .zip(mass)
1989 .map(|(net, mass)| {
1990 if mass > 0.0 {
1991 0.5 + 0.5 * net / mass
1992 } else {
1993 0.5
1994 }
1995 })
1996 .collect()
1997 }
1998
1999 fn terminal_value(
2000 &self,
2001 t: &Terminal,
2002 reach: &[Vec<f64>; 2],
2003 board: &[Card],
2004 board_eval: &[Vec<u32>; 2],
2005 ) -> [Vec<f64>; 2] {
2006 [
2007 self.terminal_value_for_player(t, 0, &reach[1], board, board_eval),
2008 self.terminal_value_for_player(t, 1, &reach[0], board, board_eval),
2009 ]
2010 }
2011
2012 fn terminal_value_for_player(
2013 &self,
2014 t: &Terminal,
2015 player: usize,
2016 reach_opp: &[f64],
2017 board: &[Card],
2018 board_eval: &[Vec<u32>; 2],
2019 ) -> Vec<f64> {
2020 #[cfg(test)]
2021 self.terminal_calls[player].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2022 let board_set = mask_of(board);
2023 #[cfg(test)]
2024 if self
2025 .use_pairwise_terminals
2026 .load(std::sync::atomic::Ordering::Relaxed)
2027 {
2028 return (0..self.combos[player].len())
2029 .map(|i| {
2030 let [a, b] = self.combos[player][i].cards;
2031 if mask_has(board_set, a) || mask_has(board_set, b) {
2032 return 0.0;
2033 }
2034 match t {
2035 Terminal::Fold { winner, invested } => {
2036 let value = if winner.index() == player {
2037 invested[1 - player]
2038 } else {
2039 -invested[player]
2040 };
2041 value * self.non_conflicting_reach_sum(player, i, reach_opp, board_set)
2042 }
2043 Terminal::Showdown { invested } => {
2044 self.showdown_cfv(player, i, invested, reach_opp, board_eval, board_set)
2045 }
2046 }
2047 })
2048 .collect();
2049 }
2050 match t {
2051 Terminal::Fold { winner, invested } => {
2052 let value = if winner.index() == player {
2053 invested[1 - player]
2054 } else {
2055 -invested[player]
2056 };
2057 self.terminal_index
2058 .compatible_mass(&self.combos, player, reach_opp, board_set)
2059 .into_iter()
2060 .map(|mass| value * mass)
2061 .collect()
2062 }
2063 Terminal::Showdown { invested } => self.terminal_index.showdown(
2064 &self.combos,
2065 player,
2066 reach_opp,
2067 board_eval,
2068 &self.board_order_cache[board],
2069 board_set,
2070 invested,
2071 ),
2072 }
2073 }
2074
2075 #[cfg(test)]
2085 fn non_conflicting_reach_sum(
2086 &self,
2087 player: usize,
2088 combo_idx: usize,
2089 reach_opp: &[f64],
2090 board_set: u64,
2091 ) -> f64 {
2092 let opp = 1 - player;
2093 let [h1, h2] = self.combos[player][combo_idx].cards;
2094 self.combos[opp]
2095 .iter()
2096 .zip(reach_opp)
2097 .filter(
2098 |(
2099 Combo {
2100 cards: [v1, v2], ..
2101 },
2102 _,
2103 )| {
2104 *v1 != h1
2105 && *v1 != h2
2106 && *v2 != h1
2107 && *v2 != h2
2108 && !mask_has(board_set, *v1)
2109 && !mask_has(board_set, *v2)
2110 },
2111 )
2112 .map(|(_, &r)| r)
2113 .sum()
2114 }
2115
2116 #[cfg(test)]
2120 fn showdown_cfv(
2121 &self,
2122 player: usize,
2123 combo_idx: usize,
2124 invested: &[f64; 2],
2125 reach_opp: &[f64],
2126 board_eval: &[Vec<u32>; 2],
2127 board_set: u64,
2128 ) -> f64 {
2129 let opp = 1 - player;
2130 let [h1, h2] = self.combos[player][combo_idx].cards;
2131 let hero_score = board_eval[player][combo_idx];
2132 let mut cfv = 0.0;
2133 for (
2134 j,
2135 &Combo {
2136 cards: [v1, v2], ..
2137 },
2138 ) in self.combos[opp].iter().enumerate()
2139 {
2140 if v1 == h1 || v1 == h2 || v2 == h1 || v2 == h2 {
2141 continue;
2142 }
2143 if mask_has(board_set, v1) || mask_has(board_set, v2) {
2144 continue;
2145 }
2146 let villain_score = board_eval[opp][j];
2147 let net = match hero_score.cmp(&villain_score) {
2148 std::cmp::Ordering::Greater => invested[opp],
2149 std::cmp::Ordering::Less => -invested[player],
2150 std::cmp::Ordering::Equal => (invested[opp] - invested[player]) / 2.0,
2151 };
2152 cfv += reach_opp[j] * net;
2153 }
2154 cfv
2155 }
2156}
2157
2158fn normalize_pair(c1: Card, c2: Card) -> (Card, Card) {
2162 if c1 <= c2 {
2163 (c1, c2)
2164 } else {
2165 (c2, c1)
2166 }
2167}
2168
2169fn build_combo_index(combos: &[Combo]) -> HashMap<(Card, Card), usize> {
2170 combos
2171 .iter()
2172 .enumerate()
2173 .map(
2174 |(
2175 i,
2176 &Combo {
2177 cards: [c1, c2], ..
2178 },
2179 )| (normalize_pair(c1, c2), i),
2180 )
2181 .collect()
2182}
2183
2184fn swap_suit(card: Card, suit_a: u8, suit_b: u8) -> Card {
2187 let s = card.suit();
2188 let new_suit = if s == suit_a {
2189 suit_b
2190 } else if s == suit_b {
2191 suit_a
2192 } else {
2193 s
2194 };
2195 Card(card.rank() * 4 + new_suit)
2196}
2197
2198fn eval_combos_if_complete(combos: &[Vec<Combo>; 2], board: &[Card]) -> [Vec<u32>; 2] {
2214 if board.len() != 5 {
2215 return [Vec::new(), Vec::new()];
2216 }
2217 let board_set = mask_of(board);
2218 let score = |combo: &Combo| {
2219 if mask_has(board_set, combo.cards[0]) || mask_has(board_set, combo.cards[1]) {
2220 return 0;
2221 }
2222 score_7([
2223 combo.cards[0],
2224 combo.cards[1],
2225 board[0],
2226 board[1],
2227 board[2],
2228 board[3],
2229 board[4],
2230 ])
2231 };
2232 [
2233 combos[0].iter().map(score).collect(),
2234 combos[1].iter().map(score).collect(),
2235 ]
2236}
2237
2238fn precompute_board_eval(
2241 node: &Node,
2242 board: &[Card],
2243 combos: &[Vec<Combo>; 2],
2244 cache: &mut HashMap<Vec<Card>, [Vec<u32>; 2]>,
2245) {
2246 match node {
2247 Node::Decision { children, .. } => {
2248 for child in children {
2249 precompute_board_eval(child, board, combos, cache);
2250 }
2251 }
2252 Node::Chance { children } => {
2253 for (members, child) in children {
2254 let rep = members[0];
2258 let mut child_board = board.to_vec();
2259 child_board.push(rep);
2260 cache
2261 .entry(child_board.clone())
2262 .or_insert_with(|| eval_combos_if_complete(combos, &child_board));
2263 precompute_board_eval(child, &child_board, combos, cache);
2264 }
2265 }
2266 Node::Terminal(_) => {}
2267 }
2268}
2269
2270fn collect_reachable_boards(
2277 node: &Node,
2278 board: &[Card],
2279 acc: &mut std::collections::HashSet<Vec<Card>>,
2280) {
2281 match node {
2282 Node::Decision { children, .. } => {
2283 for child in children {
2284 collect_reachable_boards(child, board, acc);
2285 }
2286 }
2287 Node::Chance { children } => {
2288 for (members, child) in children {
2289 let rep = members[0];
2290 let mut child_board = board.to_vec();
2291 child_board.push(rep);
2292 acc.insert(child_board.clone());
2293 collect_reachable_boards(child, &child_board, acc);
2294 }
2295 }
2296 Node::Terminal(_) => {}
2297 }
2298}
2299
2300fn compute_percentile_buckets(scores: &[f64], num_buckets: usize) -> Vec<usize> {
2310 let n = scores.len();
2311 if n == 0 {
2312 return Vec::new();
2313 }
2314 let num_buckets = num_buckets.clamp(1, n);
2315 let mut order: Vec<usize> = (0..n).collect();
2316 order.sort_by(|&i, &j| scores[i].partial_cmp(&scores[j]).unwrap());
2317 let mut bucket_of = vec![0usize; n];
2318 for (rank, &i) in order.iter().enumerate() {
2319 bucket_of[i] = rank * num_buckets / n;
2320 if rank > 0 && scores[i] == scores[order[rank - 1]] {
2328 bucket_of[i] = bucket_of[order[rank - 1]];
2329 }
2330 }
2331 bucket_of
2332}
2333
2334fn avg_score(
2354 board: &[Card],
2355 combos: &[Vec<Combo>; 2],
2356 combo_index: &[HashMap<(Card, Card), usize>; 2],
2357 board_eval_cache: &HashMap<Vec<Card>, [Vec<u32>; 2]>,
2358 cache: &mut HashMap<Vec<Card>, [Vec<f64>; 2]>,
2359) -> [Vec<f64>; 2] {
2360 if let Some(v) = cache.get(board) {
2361 return v.clone();
2362 }
2363 let result = if board.len() == 5 {
2364 let scores = match board_eval_cache.get(board) {
2365 Some(scores) => scores.clone(),
2366 None => eval_combos_if_complete(combos, board),
2367 };
2368 [
2369 scores[0].iter().map(|&s| s as f64).collect(),
2370 scores[1].iter().map(|&s| s as f64).collect(),
2371 ]
2372 } else {
2373 let mut sum = [vec![0.0; combos[0].len()], vec![0.0; combos[1].len()]];
2374 let mut weight = [vec![0.0; combos[0].len()], vec![0.0; combos[1].len()]];
2375 for members in super::tree::deal_classes(true, board) {
2376 let rep = members[0];
2377 let mut next_board = board.to_vec();
2378 next_board.push(rep);
2379 let child = avg_score(&next_board, combos, combo_index, board_eval_cache, cache);
2388 for &m in &members {
2389 let (suit_a, suit_b) = (rep.suit(), m.suit());
2390 for p in 0..2 {
2391 for (
2392 i,
2393 &Combo {
2394 cards: [h1, h2], ..
2395 },
2396 ) in combos[p].iter().enumerate()
2397 {
2398 if h1 == m || h2 == m {
2399 continue; }
2401 let idx = if m == rep {
2402 i
2403 } else {
2404 let s1 = swap_suit(h1, suit_a, suit_b);
2405 let s2 = swap_suit(h2, suit_a, suit_b);
2406 combo_index[p][&normalize_pair(s1, s2)]
2407 };
2408 sum[p][i] += child[p][idx];
2409 weight[p][i] += 1.0;
2410 }
2411 }
2412 }
2413 }
2414 [
2415 sum[0]
2416 .iter()
2417 .zip(&weight[0])
2418 .map(|(&s, &w)| if w > 0.0 { s / w } else { 0.0 })
2419 .collect(),
2420 sum[1]
2421 .iter()
2422 .zip(&weight[1])
2423 .map(|(&s, &w)| if w > 0.0 { s / w } else { 0.0 })
2424 .collect(),
2425 ]
2426 };
2427 cache.insert(board.to_vec(), result.clone());
2428 result
2429}
2430
2431fn bucket_count_and_map<'a>(
2435 player: usize,
2436 board: &[Card],
2437 bucket_maps: &'a HashMap<Vec<Card>, [Vec<usize>; 2]>,
2438 identity_buckets: &'a [Vec<usize>; 2],
2439) -> (usize, &'a [usize]) {
2440 match bucket_maps.get(board) {
2441 Some(maps) => {
2442 let map = &maps[player];
2443 let num_buckets = map.iter().copied().max().map_or(0, |m| m + 1);
2444 (num_buckets, map)
2445 }
2446 None => (identity_buckets[player].len(), &identity_buckets[player]),
2447 }
2448}
2449
2450fn init_node_data(
2455 node: &Node,
2456 board: &[Card],
2457 bucket_maps: &HashMap<Vec<Card>, [Vec<usize>; 2]>,
2458 identity_buckets: &[Vec<usize>; 2],
2459 out: &mut [NodeData],
2460 node_meta: &mut [(usize, Vec<Card>)],
2461) {
2462 match node {
2463 Node::Decision {
2464 id,
2465 player,
2466 actions,
2467 children,
2468 } => {
2469 let p = player.index();
2470 let (num_buckets, _) = bucket_count_and_map(p, board, bucket_maps, identity_buckets);
2471 out[*id] = NodeData::sized(actions.len(), num_buckets);
2472 node_meta[*id] = (p, board.to_vec());
2473 for child in children {
2474 init_node_data(child, board, bucket_maps, identity_buckets, out, node_meta);
2475 }
2476 }
2477 Node::Chance { children } => {
2478 for (members, child) in children {
2479 let rep = members[0];
2480 let mut child_board = board.to_vec();
2481 child_board.push(rep);
2482 init_node_data(
2483 child,
2484 &child_board,
2485 bucket_maps,
2486 identity_buckets,
2487 out,
2488 node_meta,
2489 );
2490 }
2491 }
2492 Node::Terminal(_) => {}
2493 }
2494}
2495
2496#[cfg(test)]
2497mod tests {
2498 use super::*;
2499 use crate::card::Card;
2500 use crate::range::Range;
2501 use crate::solver::tree::{build_tree, GameConfig};
2502 use crate::solver::Chips;
2503
2504 #[test]
2505 fn dcfr_discounts_once_per_bucket_after_adding_the_full_iteration() {
2506 use crate::solver::tree::{Action, Player, Tree};
2507 let c = |s: &str| s.parse::<Card>().unwrap();
2508 let board = ["2c", "3d", "7h", "8s", "9c"].map(c).to_vec();
2509 let combos = [
2512 vec![
2513 Combo::new(c("Ac"), c("Ad"), 1.0),
2514 Combo::new(c("Ah"), c("As"), 3.0),
2515 ],
2516 vec![Combo::new(c("Kh"), c("Kd"), 1.0)],
2517 ];
2518 let tree = Tree {
2519 board: board.clone(),
2520 root: Node::Decision {
2521 id: 0,
2522 player: Player::Oop,
2523 actions: vec![Action::Check, Action::Bet(Chips::whole(8))],
2524 children: vec![
2525 Node::Terminal(Terminal::Fold {
2526 winner: Player::Oop,
2527 invested: [8.0, 8.0],
2528 }),
2529 Node::Terminal(Terminal::Fold {
2530 winner: Player::Ip,
2531 invested: [8.0, 8.0],
2532 }),
2533 ],
2534 },
2535 num_decision_nodes: 1,
2536 };
2537 let mut trainer = Trainer::new(
2538 tree,
2539 combos,
2540 TrainerOptions {
2541 algorithm: SolverAlgorithm::Dcfr,
2542 abstraction: CardAbstraction {
2543 river: Some(1),
2544 ..CardAbstraction::default()
2545 },
2546 ..TrainerOptions::default()
2547 },
2548 )
2549 .unwrap();
2550 assert_eq!(trainer.train(1), [0.0, 0.0]);
2551 {
2552 let data = trainer.node_data[0].lock().unwrap();
2553 assert_eq!(data.regret_sum, vec![vec![4.0], vec![-4.0]]);
2556 assert_eq!(data.strategy_sum, vec![vec![0.5], vec![0.5]]);
2557 }
2558 assert_eq!(trainer.train(1), [32.0, -32.0]);
2559 {
2560 let data = trainer.node_data[0].lock().unwrap();
2561 let positive = 2.0_f64.powf(1.5);
2562 assert_eq!(data.regret_sum[0][0], 4.0 * positive / (positive + 1.0));
2563 assert_eq!(data.regret_sum[1][0], -10.0);
2566 assert_eq!(data.strategy_sum[0][0], 2.0);
2567 assert_eq!(data.strategy_sum[1][0], 2.0 / 9.0);
2568 }
2569 for probability in &trainer.average_strategy(0)[0] {
2571 assert!((probability - 0.9).abs() < 1e-15);
2572 }
2573 }
2574
2575 #[test]
2576 fn chunking_preserves_all_update_state_through_chance_nodes() {
2577 let pool = rayon::ThreadPoolBuilder::new()
2578 .num_threads(1)
2579 .build()
2580 .unwrap();
2581 pool.install(|| {
2582 let c = |s: &str| s.parse::<Card>().unwrap();
2583 let cfg = GameConfig {
2584 board: ["2c", "7d", "9h", "Js"].map(c).to_vec(),
2585 pot: Chips::whole(2),
2586 effective_stack: Chips::whole(1),
2587 bet_sizes: vec![0.5],
2588 max_raises: 0,
2589 suit_isomorphism: false,
2590 };
2591 let combos = [
2592 vec![
2593 Combo::new(c("Jh"), c("Jd"), 0.7),
2594 Combo::new(c("Ac"), c("Kd"), 1.0),
2595 ],
2596 vec![Combo::new(c("7h"), c("6s"), 1.0)],
2597 ];
2598 for (algorithm, schedule) in [
2599 SolverAlgorithm::Cfr,
2600 SolverAlgorithm::CfrPlus,
2601 SolverAlgorithm::Dcfr,
2602 ]
2603 .into_iter()
2604 .flat_map(|a| {
2605 [UpdateSchedule::Simultaneous, UpdateSchedule::Alternating].map(|s| (a, s))
2606 }) {
2607 let make = || {
2608 Trainer::new(
2609 build_tree(&cfg).unwrap(),
2610 combos.clone(),
2611 TrainerOptions {
2612 algorithm,
2613 schedule,
2614 abstraction: CardAbstraction {
2615 river: Some(2),
2616 ..CardAbstraction::default()
2617 },
2618 },
2619 )
2620 .unwrap()
2621 };
2622 let mut whole = make();
2623 let mut chunks = make();
2624 let expected = whole.train(11);
2625 chunks.train(3);
2626 chunks.train(0);
2627 assert_eq!(chunks.train(8), expected, "{algorithm:?}");
2628 assert_eq!(whole.iterations_completed(), 11);
2629 assert_eq!(chunks.iterations_completed(), 11);
2630 for (a, b) in whole.node_data.iter().zip(&chunks.node_data) {
2631 let a = a.lock().unwrap();
2632 let b = b.lock().unwrap();
2633 assert_eq!(a.regret_sum, b.regret_sum, "{algorithm:?}");
2634 assert_eq!(a.strategy_sum, b.strategy_sum, "{algorithm:?}");
2635 }
2636 }
2637 });
2638 }
2639
2640 fn river_board() -> Vec<Card> {
2641 ["2h", "7c", "9d", "Jc", "4s"]
2642 .iter()
2643 .map(|s| s.parse::<Card>().unwrap())
2644 .collect()
2645 }
2646
2647 struct Scenario {
2648 tree: super::super::tree::Tree,
2649 trainer_combos: [Vec<Combo>; 2],
2650 pot: f64,
2651 bet: f64,
2652 }
2653
2654 fn build_scenario() -> Scenario {
2655 let board = river_board();
2656 let dead = CardSet::from_cards(&board);
2657 let oop_range = Range::parse("JJ,KQo").unwrap();
2659 let ip_range = Range::parse("99").unwrap();
2661 let oop_combos = oop_range.combos(dead);
2662 let ip_combos = ip_range.combos(dead);
2663
2664 let pot = 100.0;
2665 let bet = 100.0; let cfg = GameConfig {
2667 board: board.clone(),
2668 pot: Chips::from_f64(pot).unwrap(),
2669 effective_stack: Chips::whole(200),
2670 bet_sizes: vec![bet / pot],
2671 max_raises: 0,
2672 suit_isomorphism: false,
2673 };
2674 let tree = build_tree(&cfg).unwrap();
2675 Scenario {
2676 tree,
2677 trainer_combos: [oop_combos, ip_combos],
2678 pot,
2679 bet,
2680 }
2681 }
2682
2683 fn is_jj(c1: Card, c2: Card) -> bool {
2684 c1.rank() == 9 && c2.rank() == 9 }
2686
2687 #[test]
2688 fn zero_sum_at_root() {
2689 let scenario = build_scenario();
2690 let mut trainer = Trainer::new(
2691 scenario.tree,
2692 scenario.trainer_combos,
2693 TrainerOptions {
2694 algorithm: SolverAlgorithm::CfrPlus,
2695 ..TrainerOptions::default()
2696 },
2697 )
2698 .unwrap();
2699 let [ev0, ev1] = trainer.train(20_000);
2700 assert!(
2701 (ev0 + ev1).abs() < 1.0,
2702 "expected zero-sum root EV, got ev0={ev0}, ev1={ev1}"
2703 );
2704 }
2705
2706 #[test]
2707 fn converges_to_known_bet_and_call_frequencies() {
2708 let scenario = build_scenario();
2709 let value_combo_count = scenario.trainer_combos[0]
2710 .iter()
2711 .filter(
2712 |&&Combo {
2713 cards: [c1, c2], ..
2714 }| is_jj(c1, c2),
2715 )
2716 .count();
2717 let bluff_combo_count = scenario.trainer_combos[0].len() - value_combo_count;
2718 let wv = value_combo_count as f64;
2719 let wb = bluff_combo_count as f64;
2720 let pot = scenario.pot;
2721 let bet = scenario.bet;
2722
2723 let root_id = match &scenario.tree.root {
2724 Node::Decision { id, .. } => *id,
2725 _ => panic!("expected decision"),
2726 };
2727 let ip_facing_bet_id = match &scenario.tree.root {
2728 Node::Decision { children, .. } => match &children[1] {
2729 Node::Decision { id, .. } => *id,
2730 _ => panic!("expected IP decision facing the bet"),
2731 },
2732 _ => panic!("expected decision"),
2733 };
2734
2735 let combos0 = scenario.trainer_combos[0].clone();
2736 let mut trainer = Trainer::new(
2737 scenario.tree,
2738 scenario.trainer_combos,
2739 TrainerOptions {
2740 algorithm: SolverAlgorithm::CfrPlus,
2741 ..TrainerOptions::default()
2742 },
2743 )
2744 .unwrap();
2745 trainer.train(60_000);
2746
2747 let root_strategy = trainer.average_strategy(root_id); let combos0 = &combos0;
2749 let bet_freq_value: Vec<f64> = combos0
2750 .iter()
2751 .enumerate()
2752 .filter(
2753 |(
2754 _,
2755 &Combo {
2756 cards: [c1, c2], ..
2757 },
2758 )| is_jj(c1, c2),
2759 )
2760 .map(|(i, _)| root_strategy[1][i])
2761 .collect();
2762 let bet_freq_bluff: Vec<f64> = combos0
2763 .iter()
2764 .enumerate()
2765 .filter(
2766 |(
2767 _,
2768 &Combo {
2769 cards: [c1, c2], ..
2770 },
2771 )| !is_jj(c1, c2),
2772 )
2773 .map(|(i, _)| root_strategy[1][i])
2774 .collect();
2775
2776 let tol = 0.05;
2777 for f in &bet_freq_value {
2778 assert!(
2779 (f - 1.0).abs() < tol,
2780 "value combo should always bet, got {f}"
2781 );
2782 }
2783 let expected_beta = (bet / (pot + bet)) * (wv / wb);
2784 for f in &bet_freq_bluff {
2785 assert!(
2786 (f - expected_beta).abs() < tol,
2787 "expected bluff bet freq {expected_beta}, got {f}"
2788 );
2789 }
2790
2791 let ip_strategy = trainer.average_strategy(ip_facing_bet_id); let expected_call = pot / (pot + bet); for &f in &ip_strategy[1] {
2794 assert!(
2795 (f - expected_call).abs() < tol,
2796 "expected call freq (MDF) {expected_call}, got {f}"
2797 );
2798 }
2799 }
2800
2801 fn turn_board() -> Vec<Card> {
2821 ["2c", "7d", "9h", "Js"]
2822 .iter()
2823 .map(|s| s.parse::<Card>().unwrap())
2824 .collect()
2825 }
2826
2827 struct MultiStreetScenario {
2828 tree: super::super::tree::Tree,
2829 trainer_combos: [Vec<Combo>; 2],
2830 pot: f64,
2831 bet: f64,
2832 }
2833
2834 fn multi_street_scenario_combos() -> [Vec<Combo>; 2] {
2841 let dead = CardSet::from_cards(&turn_board());
2842 let oop_combos = Range::parse("JJ,54o").unwrap().combos(dead);
2844 let ip_combos = Range::parse("76o").unwrap().combos(dead);
2846 [oop_combos, ip_combos]
2847 }
2848
2849 fn build_multi_street_scenario() -> MultiStreetScenario {
2850 build_multi_street_scenario_with_combos(multi_street_scenario_combos())
2851 }
2852
2853 fn build_multi_street_scenario_with_combos(
2854 trainer_combos: [Vec<Combo>; 2],
2855 ) -> MultiStreetScenario {
2856 let board = turn_board();
2857 let pot = 100.0;
2858 let bet = 100.0;
2859 let cfg = GameConfig {
2860 board: board.clone(),
2861 pot: Chips::from_f64(pot).unwrap(),
2862 effective_stack: Chips::whole(200),
2863 bet_sizes: vec![bet / pot],
2864 max_raises: 0,
2865 suit_isomorphism: false,
2866 };
2867 let tree = build_tree(&cfg).unwrap();
2868 MultiStreetScenario {
2869 tree,
2870 trainer_combos,
2871 pot,
2872 bet,
2873 }
2874 }
2875
2876 fn is_pocket_jacks(c1: Card, c2: Card) -> bool {
2877 c1.rank() == 9 && c2.rank() == 9
2878 }
2879
2880 #[test]
2881 fn multi_street_zero_sum_at_root() {
2882 let scenario = build_multi_street_scenario();
2883 let mut trainer = Trainer::new(
2884 scenario.tree,
2885 scenario.trainer_combos,
2886 TrainerOptions {
2887 algorithm: SolverAlgorithm::CfrPlus,
2888 ..TrainerOptions::default()
2889 },
2890 )
2891 .unwrap();
2892 let [ev0, ev1] = trainer.train(500);
2893 assert!(
2894 (ev0 + ev1).abs() < 1.0,
2895 "expected zero-sum root EV, got ev0={ev0}, ev1={ev1}"
2896 );
2897 }
2898
2899 #[test]
2900 fn multi_street_value_bets_and_ip_defends_at_mdf() {
2901 let scenario = build_multi_street_scenario();
2902 let pot = scenario.pot;
2903 let bet = scenario.bet;
2904
2905 let root_id = match &scenario.tree.root {
2906 Node::Decision { id, .. } => *id,
2907 _ => panic!("expected decision"),
2908 };
2909 let ip_facing_bet_id = match &scenario.tree.root {
2910 Node::Decision { children, .. } => match &children[1] {
2911 Node::Decision { id, .. } => *id,
2912 _ => panic!("expected IP decision facing the bet"),
2913 },
2914 _ => panic!("expected decision"),
2915 };
2916
2917 let combos0 = scenario.trainer_combos[0].clone();
2918 let mut trainer = Trainer::new(
2919 scenario.tree,
2920 scenario.trainer_combos,
2921 TrainerOptions {
2922 algorithm: SolverAlgorithm::CfrPlus,
2923 ..TrainerOptions::default()
2924 },
2925 )
2926 .unwrap();
2927 trainer.train(4_000);
2928
2929 let root_strategy = trainer.average_strategy(root_id); let bet_freq_value: Vec<f64> = combos0
2931 .iter()
2932 .enumerate()
2933 .filter(
2934 |(
2935 _,
2936 &Combo {
2937 cards: [c1, c2], ..
2938 },
2939 )| is_pocket_jacks(c1, c2),
2940 )
2941 .map(|(i, _)| root_strategy[1][i])
2942 .collect();
2943 let bet_freq_bluff: Vec<f64> = combos0
2944 .iter()
2945 .enumerate()
2946 .filter(
2947 |(
2948 _,
2949 &Combo {
2950 cards: [c1, c2], ..
2951 },
2952 )| !is_pocket_jacks(c1, c2),
2953 )
2954 .map(|(i, _)| root_strategy[1][i])
2955 .collect();
2956
2957 let tol = 0.08;
2958 let value_bet_tol = 0.1;
2966 for f in &bet_freq_value {
2967 assert!(
2968 (f - 1.0).abs() < value_bet_tol,
2969 "value combo should always bet, got {f}"
2970 );
2971 }
2972
2973 let bluff_avg = bet_freq_bluff.iter().sum::<f64>() / bet_freq_bluff.len() as f64;
2978 assert!(
2979 (0.01..0.9).contains(&bluff_avg),
2980 "expected genuine interior bluff mixing, got {bluff_avg}"
2981 );
2982 for f in &bet_freq_bluff {
2983 assert!((f - bluff_avg).abs() < 0.02, "combos of the same hand type should bet at the same frequency, got {f} vs avg {bluff_avg}");
2984 }
2985 assert!(
2986 bluff_avg < bet_freq_value[0],
2987 "bluffs should bet less often than value, got bluff={bluff_avg}, value={}",
2988 bet_freq_value[0]
2989 );
2990
2991 let ip_strategy = trainer.average_strategy(ip_facing_bet_id); let expected_call = pot / (pot + bet); for &f in &ip_strategy[1] {
2994 assert!(
2995 (f - expected_call).abs() < tol,
2996 "expected call freq (MDF) {expected_call}, got {f}"
2997 );
2998 }
2999 }
3000
3001 fn two_suit_turn_board() -> Vec<Card> {
3007 ["2c", "7d", "9c", "Jd"]
3012 .iter()
3013 .map(|s| s.parse::<Card>().unwrap())
3014 .collect()
3015 }
3016
3017 fn build_two_suit_scenario(
3025 suit_isomorphism: bool,
3026 trainer_combos: [Vec<Combo>; 2],
3027 ) -> MultiStreetScenario {
3028 let board = two_suit_turn_board();
3029 let pot = 100.0;
3030 let bet = 100.0;
3031 let cfg = GameConfig {
3032 board: board.clone(),
3033 pot: Chips::from_f64(pot).unwrap(),
3034 effective_stack: Chips::whole(200),
3035 bet_sizes: vec![bet / pot],
3036 max_raises: 0,
3037 suit_isomorphism,
3038 };
3039 let tree = build_tree(&cfg).unwrap();
3040 MultiStreetScenario {
3041 tree,
3042 trainer_combos,
3043 pot,
3044 bet,
3045 }
3046 }
3047
3048 fn two_suit_scenario_combos() -> [Vec<Combo>; 2] {
3049 let dead = CardSet::from_cards(&two_suit_turn_board());
3050 let oop_combos = Range::parse("JJ,54o").unwrap().combos(dead);
3051 let ip_combos = Range::parse("76o").unwrap().combos(dead);
3052 [oop_combos, ip_combos]
3053 }
3054
3055 #[test]
3056 fn suit_isomorphism_actually_reduces_the_tree() {
3057 let combos = two_suit_scenario_combos();
3058 let reduced = build_two_suit_scenario(true, combos.clone());
3059 let unreduced = build_two_suit_scenario(false, combos);
3060 assert!(
3061 reduced.tree.num_decision_nodes < unreduced.tree.num_decision_nodes,
3062 "expected fewer decision nodes with isomorphism enabled, got {} (reduced) vs {} (unreduced)",
3063 reduced.tree.num_decision_nodes,
3064 unreduced.tree.num_decision_nodes
3065 );
3066 }
3067
3068 fn root_and_ip_facing_bet_ids(root: &Node) -> (usize, usize) {
3074 let Node::Decision {
3075 id: root_id,
3076 children,
3077 ..
3078 } = root
3079 else {
3080 panic!("expected decision")
3081 };
3082 let Node::Decision {
3083 id: ip_facing_bet_id,
3084 ..
3085 } = &children[1]
3086 else {
3087 panic!("expected IP decision facing the bet")
3088 };
3089 (*root_id, *ip_facing_bet_id)
3090 }
3091
3092 #[test]
3093 fn suit_isomorphism_reduced_and_unreduced_converge_to_the_same_equilibrium() {
3094 let combos = two_suit_scenario_combos();
3095 let reduced = build_two_suit_scenario(true, combos.clone());
3096 let unreduced = build_two_suit_scenario(false, combos);
3097
3098 let (reduced_root_id, reduced_ip_facing_bet_id) =
3099 root_and_ip_facing_bet_ids(&reduced.tree.root);
3100 let (unreduced_root_id, unreduced_ip_facing_bet_id) =
3101 root_and_ip_facing_bet_ids(&unreduced.tree.root);
3102
3103 let iterations = 3_000;
3104 let mut reduced_trainer = Trainer::new(
3105 reduced.tree,
3106 reduced.trainer_combos,
3107 TrainerOptions {
3108 algorithm: SolverAlgorithm::CfrPlus,
3109 ..TrainerOptions::default()
3110 },
3111 )
3112 .unwrap();
3113 reduced_trainer.train(iterations);
3114 let mut unreduced_trainer = Trainer::new(
3115 unreduced.tree,
3116 unreduced.trainer_combos,
3117 TrainerOptions {
3118 algorithm: SolverAlgorithm::CfrPlus,
3119 ..TrainerOptions::default()
3120 },
3121 )
3122 .unwrap();
3123 unreduced_trainer.train(iterations);
3124
3125 let tol = 0.05;
3126 for (row_r, row_u) in reduced_trainer
3127 .average_strategy(reduced_root_id)
3128 .iter()
3129 .zip(unreduced_trainer.average_strategy(unreduced_root_id).iter())
3130 {
3131 for (&fr, &fu) in row_r.iter().zip(row_u.iter()) {
3132 assert!(
3133 (fr - fu).abs() < tol,
3134 "root strategy mismatch: reduced={fr}, unreduced={fu}"
3135 );
3136 }
3137 }
3138 for (row_r, row_u) in reduced_trainer
3139 .average_strategy(reduced_ip_facing_bet_id)
3140 .iter()
3141 .zip(
3142 unreduced_trainer
3143 .average_strategy(unreduced_ip_facing_bet_id)
3144 .iter(),
3145 )
3146 {
3147 for (&fr, &fu) in row_r.iter().zip(row_u.iter()) {
3148 assert!(
3149 (fr - fu).abs() < tol,
3150 "IP-facing-bet strategy mismatch: reduced={fr}, unreduced={fu}"
3151 );
3152 }
3153 }
3154 }
3155
3156 #[test]
3159 fn compute_percentile_buckets_is_monotonic_and_bijective_when_large_enough() {
3160 let scores = [30.0, 10.0, 20.0, 10.0, 40.0];
3161 let n = scores.len();
3162
3163 let bijective = compute_percentile_buckets(&scores, 100);
3169 assert_eq!(
3170 bijective[1], bijective[3],
3171 "tied scores must share a bucket, got {bijective:?}"
3172 );
3173 let mut seen = std::collections::HashSet::new();
3174 for (i, &b) in bijective.iter().enumerate() {
3175 if i == 3 {
3176 continue; }
3178 assert!(
3179 seen.insert(b),
3180 "expected every distinct-score combo to get a distinct bucket, got {bijective:?}"
3181 );
3182 }
3183 for i in 0..n {
3185 for j in 0..n {
3186 if scores[i] < scores[j] {
3187 assert!(
3188 bijective[i] <= bijective[j],
3189 "score {} (bucket {}) should not outrank score {} (bucket {})",
3190 scores[i],
3191 bijective[i],
3192 scores[j],
3193 bijective[j]
3194 );
3195 }
3196 }
3197 }
3198
3199 let reduced = compute_percentile_buckets(&scores, 2);
3202 let distinct: std::collections::HashSet<usize> = reduced.iter().copied().collect();
3203 assert!(
3204 distinct.len() <= 2,
3205 "expected at most 2 distinct buckets, got {distinct:?}"
3206 );
3207 assert!(reduced.iter().all(|&b| b < 2));
3208 for i in 0..n {
3209 for j in 0..n {
3210 if scores[i] < scores[j] {
3211 assert!(reduced[i] <= reduced[j]);
3212 }
3213 }
3214 }
3215 }
3216
3217 #[test]
3226 fn river_buckets_bijective_matches_unbucketed() {
3227 let board = river_board();
3228 let dead = CardSet::from_cards(&board);
3229 let oop_combos = Range::parse("JJ,KQo").unwrap().combos(dead);
3230 let ip_combos = Range::parse("99").unwrap().combos(dead);
3231 let pot = 100.0;
3232 let bet = 100.0;
3233 let cfg = GameConfig {
3234 board: board.clone(),
3235 pot: Chips::from_f64(pot).unwrap(),
3236 effective_stack: Chips::whole(200),
3237 bet_sizes: vec![bet / pot],
3238 max_raises: 0,
3239 suit_isomorphism: false,
3240 };
3241
3242 let tree_none = build_tree(&cfg).unwrap();
3243 let tree_bucketed = build_tree(&cfg).unwrap();
3244 let (root_id, ip_facing_bet_id) = root_and_ip_facing_bet_ids(&tree_none.root);
3245
3246 let iterations = 3_000;
3247 let mut trainer_none = Trainer::new(
3248 tree_none,
3249 [oop_combos.clone(), ip_combos.clone()],
3250 TrainerOptions {
3251 algorithm: SolverAlgorithm::CfrPlus,
3252 ..TrainerOptions::default()
3253 },
3254 )
3255 .unwrap();
3256 trainer_none.train(iterations);
3257 let mut trainer_bucketed = Trainer::new(
3259 tree_bucketed,
3260 [oop_combos, ip_combos],
3261 TrainerOptions {
3262 algorithm: SolverAlgorithm::CfrPlus,
3263 abstraction: CardAbstraction {
3264 river: Some(100),
3265 ..Default::default()
3266 },
3267 ..TrainerOptions::default()
3268 },
3269 )
3270 .unwrap();
3271 trainer_bucketed.train(iterations);
3272
3273 let tol = 0.05;
3274 for (row_n, row_b) in trainer_none
3275 .average_strategy(root_id)
3276 .iter()
3277 .zip(trainer_bucketed.average_strategy(root_id).iter())
3278 {
3279 for (&fn_, &fb) in row_n.iter().zip(row_b.iter()) {
3280 assert!(
3281 (fn_ - fb).abs() < tol,
3282 "root strategy mismatch: none={fn_}, bucketed(bijective)={fb}"
3283 );
3284 }
3285 }
3286 for (row_n, row_b) in trainer_none
3287 .average_strategy(ip_facing_bet_id)
3288 .iter()
3289 .zip(trainer_bucketed.average_strategy(ip_facing_bet_id).iter())
3290 {
3291 for (&fn_, &fb) in row_n.iter().zip(row_b.iter()) {
3292 assert!(
3293 (fn_ - fb).abs() < tol,
3294 "IP-facing-bet strategy mismatch: none={fn_}, bucketed(bijective)={fb}"
3295 );
3296 }
3297 }
3298 }
3299
3300 #[test]
3307 fn river_buckets_reduced_stays_zero_sum_and_respects_hand_strength_order() {
3308 let board = river_board(); let dead = CardSet::from_cards(&board);
3310 let oop_range = Range::parse("JJ,QQ,KQo,72o").unwrap();
3313 let ip_range = Range::parse("99,55").unwrap();
3323 let oop_combos = oop_range.combos(dead);
3324 let ip_combos = ip_range.combos(dead);
3325
3326 let pot = 100.0;
3327 let bet = 100.0;
3328 let cfg = GameConfig {
3329 board: board.clone(),
3330 pot: Chips::from_f64(pot).unwrap(),
3331 effective_stack: Chips::whole(200),
3332 bet_sizes: vec![bet / pot],
3333 max_raises: 0,
3334 suit_isomorphism: false,
3335 };
3336 let tree = build_tree(&cfg).unwrap();
3337 let (root_id, _) = root_and_ip_facing_bet_ids(&tree.root);
3338
3339 let combos0 = oop_combos.clone();
3340 let mut trainer = Trainer::new(
3341 tree,
3342 [oop_combos, ip_combos],
3343 TrainerOptions {
3344 algorithm: SolverAlgorithm::CfrPlus,
3345 abstraction: CardAbstraction {
3346 river: Some(3),
3347 ..Default::default()
3348 },
3349 ..TrainerOptions::default()
3350 },
3351 )
3352 .unwrap();
3353 let [ev0, ev1] = trainer.train(4_000);
3354 assert!(
3355 (ev0 + ev1).abs() < 1.0,
3356 "expected zero-sum root EV even under abstraction, got ev0={ev0}, ev1={ev1}"
3357 );
3358
3359 let is_jj = |c1: Card, c2: Card| c1.rank() == 9 && c2.rank() == 9;
3360 let is_qq = |c1: Card, c2: Card| c1.rank() == 10 && c2.rank() == 10;
3361 let avg = |pred: &dyn Fn(Card, Card) -> bool, strategy: &[Vec<f64>]| -> f64 {
3362 let matching: Vec<f64> = combos0
3363 .iter()
3364 .enumerate()
3365 .filter(
3366 |(
3367 _,
3368 &Combo {
3369 cards: [c1, c2], ..
3370 },
3371 )| pred(c1, c2),
3372 )
3373 .map(|(i, _)| strategy[1][i]) .collect();
3375 matching.iter().sum::<f64>() / matching.len() as f64
3376 };
3377
3378 let root_strategy = trainer.average_strategy(root_id);
3379 let bet_freq_jj = avg(&is_jj, &root_strategy);
3380 let bet_freq_qq = avg(&is_qq, &root_strategy);
3381 let bet_freq_air = avg(&|c1, c2| !is_jj(c1, c2) && !is_qq(c1, c2), &root_strategy);
3382
3383 let tol = 0.05;
3391 assert!(
3392 bet_freq_jj >= bet_freq_qq - tol,
3393 "trips should bet at least as often as the overpair tier, got jj={bet_freq_jj}, qq={bet_freq_qq}"
3394 );
3395 assert!(
3396 bet_freq_qq >= bet_freq_air - tol,
3397 "overpair should bet at least as often as pure air, got qq={bet_freq_qq}, air={bet_freq_air}"
3398 );
3399 assert!(
3400 bet_freq_jj > bet_freq_air + 0.1,
3401 "trips should still clearly out-bet pure air despite bucketing, got jj={bet_freq_jj}, air={bet_freq_air}"
3402 );
3403 }
3404
3405 #[test]
3415 fn avg_score_matches_naive_full_enumeration_average() {
3416 let board = two_suit_turn_board(); let dead = CardSet::from_cards(&board);
3418 let combos = Range::parse("JJ,54o").unwrap().combos(dead);
3419 let used = CardSet::from_cards(&board);
3420
3421 let naive: Vec<f64> = combos
3422 .iter()
3423 .map(
3424 |&Combo {
3425 cards: [h1, h2], ..
3426 }| {
3427 let mut sum = 0.0;
3428 let mut count = 0.0;
3429 for c in Card::all() {
3430 if used.contains(c) || c == h1 || c == h2 {
3431 continue;
3432 }
3433 let mut river = board.clone();
3434 river.push(c);
3435 let score =
3436 score_7([h1, h2, river[0], river[1], river[2], river[3], river[4]]);
3437 sum += score as f64;
3438 count += 1.0;
3439 }
3440 sum / count
3441 },
3442 )
3443 .collect();
3444
3445 let board_eval_cache = HashMap::new();
3446 let mut memo = HashMap::new();
3447 let combo_index = [build_combo_index(&combos), HashMap::new()];
3448 let via_classes = avg_score(
3449 &board,
3450 &[combos.clone(), Vec::new()],
3451 &combo_index,
3452 &board_eval_cache,
3453 &mut memo,
3454 );
3455
3456 for (i, (&n, &c)) in naive.iter().zip(via_classes[0].iter()).enumerate() {
3457 assert!((n - c).abs() < 1e-9, "combo {i}: naive={n}, avg_score={c}");
3458 }
3459 }
3460
3461 fn flop_board() -> Vec<Card> {
3462 ["2c", "7c", "9c"]
3466 .iter()
3467 .map(|s| s.parse::<Card>().unwrap())
3468 .collect()
3469 }
3470
3471 struct FlopScenario {
3472 tree: super::super::tree::Tree,
3473 trainer_combos: [Vec<Combo>; 2],
3474 }
3475
3476 fn flop_scenario_combos() -> [Vec<Combo>; 2] {
3477 let dead = CardSet::from_cards(&flop_board());
3478 let oop_combos = Range::parse("JJ,54o").unwrap().combos(dead);
3479 let ip_combos = Range::parse("76o").unwrap().combos(dead);
3480 [oop_combos, ip_combos]
3481 }
3482
3483 fn build_flop_scenario(trainer_combos: [Vec<Combo>; 2]) -> FlopScenario {
3484 let board = flop_board();
3485 let cfg = GameConfig {
3486 board: board.clone(),
3487 pot: Chips::whole(100),
3488 effective_stack: Chips::whole(200),
3489 bet_sizes: vec![1.0],
3490 max_raises: 0,
3491 suit_isomorphism: true,
3492 };
3493 let tree = build_tree(&cfg).unwrap();
3494 FlopScenario {
3495 tree,
3496 trainer_combos,
3497 }
3498 }
3499
3500 #[test]
3509 fn turn_buckets_bijective_matches_unbucketed() {
3510 let combos = multi_street_scenario_combos();
3511 let scenario_none = build_multi_street_scenario_with_combos(combos.clone());
3512 let scenario_bucketed = build_multi_street_scenario_with_combos(combos);
3513 let (root_id, ip_facing_bet_id) = root_and_ip_facing_bet_ids(&scenario_none.tree.root);
3514
3515 let iterations = 1_500;
3516 let mut trainer_none = Trainer::new(
3517 scenario_none.tree,
3518 scenario_none.trainer_combos,
3519 TrainerOptions {
3520 algorithm: SolverAlgorithm::CfrPlus,
3521 ..TrainerOptions::default()
3522 },
3523 )
3524 .unwrap();
3525 trainer_none.train(iterations);
3526 let mut trainer_bucketed = Trainer::new(
3527 scenario_bucketed.tree,
3528 scenario_bucketed.trainer_combos,
3529 TrainerOptions {
3530 algorithm: SolverAlgorithm::CfrPlus,
3531 abstraction: CardAbstraction {
3532 turn: Some(100),
3533 ..Default::default()
3534 },
3535 ..TrainerOptions::default()
3536 },
3537 )
3538 .unwrap();
3539 trainer_bucketed.train(iterations);
3540
3541 let tol = 0.05;
3542 for (row_n, row_b) in trainer_none
3543 .average_strategy(root_id)
3544 .iter()
3545 .zip(trainer_bucketed.average_strategy(root_id).iter())
3546 {
3547 for (&fn_, &fb) in row_n.iter().zip(row_b.iter()) {
3548 assert!(
3549 (fn_ - fb).abs() < tol,
3550 "root strategy mismatch: none={fn_}, bucketed(bijective)={fb}"
3551 );
3552 }
3553 }
3554 for (row_n, row_b) in trainer_none
3555 .average_strategy(ip_facing_bet_id)
3556 .iter()
3557 .zip(trainer_bucketed.average_strategy(ip_facing_bet_id).iter())
3558 {
3559 for (&fn_, &fb) in row_n.iter().zip(row_b.iter()) {
3560 assert!(
3561 (fn_ - fb).abs() < tol,
3562 "IP-facing-bet strategy mismatch: none={fn_}, bucketed(bijective)={fb}"
3563 );
3564 }
3565 }
3566 }
3567
3568 #[test]
3573 fn flop_buckets_bijective_matches_unbucketed() {
3574 let combos = flop_scenario_combos();
3575 let scenario_none = build_flop_scenario(combos.clone());
3576 let scenario_bucketed = build_flop_scenario(combos);
3577 let (root_id, ip_facing_bet_id) = root_and_ip_facing_bet_ids(&scenario_none.tree.root);
3578
3579 let iterations = 300;
3580 let mut trainer_none = Trainer::new(
3581 scenario_none.tree,
3582 scenario_none.trainer_combos,
3583 TrainerOptions {
3584 algorithm: SolverAlgorithm::CfrPlus,
3585 ..TrainerOptions::default()
3586 },
3587 )
3588 .unwrap();
3589 trainer_none.train(iterations);
3590 let mut trainer_bucketed = Trainer::new(
3591 scenario_bucketed.tree,
3592 scenario_bucketed.trainer_combos,
3593 TrainerOptions {
3594 algorithm: SolverAlgorithm::CfrPlus,
3595 abstraction: CardAbstraction {
3596 flop: Some(100),
3597 ..Default::default()
3598 },
3599 ..TrainerOptions::default()
3600 },
3601 )
3602 .unwrap();
3603 trainer_bucketed.train(iterations);
3604
3605 let tol = 0.08;
3606 for (row_n, row_b) in trainer_none
3607 .average_strategy(root_id)
3608 .iter()
3609 .zip(trainer_bucketed.average_strategy(root_id).iter())
3610 {
3611 for (&fn_, &fb) in row_n.iter().zip(row_b.iter()) {
3612 assert!(
3613 (fn_ - fb).abs() < tol,
3614 "root strategy mismatch: none={fn_}, bucketed(bijective)={fb}"
3615 );
3616 }
3617 }
3618 for (row_n, row_b) in trainer_none
3619 .average_strategy(ip_facing_bet_id)
3620 .iter()
3621 .zip(trainer_bucketed.average_strategy(ip_facing_bet_id).iter())
3622 {
3623 for (&fn_, &fb) in row_n.iter().zip(row_b.iter()) {
3624 assert!(
3625 (fn_ - fb).abs() < tol,
3626 "IP-facing-bet strategy mismatch: none={fn_}, bucketed(bijective)={fb}"
3627 );
3628 }
3629 }
3630 }
3631
3632 #[test]
3640 fn turn_buckets_reduced_stays_zero_sum_and_respects_hand_strength_order() {
3641 let scenario = build_multi_street_scenario();
3642 let (root_id, _) = root_and_ip_facing_bet_ids(&scenario.tree.root);
3643 let combos0 = scenario.trainer_combos[0].clone();
3644
3645 let mut trainer = Trainer::new(
3646 scenario.tree,
3647 scenario.trainer_combos,
3648 TrainerOptions {
3649 algorithm: SolverAlgorithm::CfrPlus,
3650 abstraction: CardAbstraction {
3651 turn: Some(2),
3652 ..Default::default()
3653 },
3654 ..TrainerOptions::default()
3655 },
3656 )
3657 .unwrap();
3658 let [ev0, ev1] = trainer.train(1_500);
3659 assert!(
3660 (ev0 + ev1).abs() < 1.0,
3661 "expected zero-sum root EV even under turn abstraction, got ev0={ev0}, ev1={ev1}"
3662 );
3663
3664 let is_jj = |c1: Card, c2: Card| c1.rank() == 9 && c2.rank() == 9;
3665 let root_strategy = trainer.average_strategy(root_id);
3666 let bet_freq_jj: Vec<f64> = combos0
3667 .iter()
3668 .enumerate()
3669 .filter(
3670 |(
3671 _,
3672 &Combo {
3673 cards: [c1, c2], ..
3674 },
3675 )| is_jj(c1, c2),
3676 )
3677 .map(|(i, _)| root_strategy[1][i])
3678 .collect();
3679 let bet_freq_air: Vec<f64> = combos0
3680 .iter()
3681 .enumerate()
3682 .filter(
3683 |(
3684 _,
3685 &Combo {
3686 cards: [c1, c2], ..
3687 },
3688 )| !is_jj(c1, c2),
3689 )
3690 .map(|(i, _)| root_strategy[1][i])
3691 .collect();
3692 let avg_jj = bet_freq_jj.iter().sum::<f64>() / bet_freq_jj.len() as f64;
3693 let avg_air = bet_freq_air.iter().sum::<f64>() / bet_freq_air.len() as f64;
3694 assert!(avg_jj > avg_air + 0.1, "value should still clearly out-bet air despite turn bucketing, got jj={avg_jj}, air={avg_air}");
3695 }
3696
3697 #[test]
3708 fn compute_percentile_buckets_never_splits_a_tie() {
3709 let scores = [10.0, 10.0, 10.0, 20.0, 20.0, 30.0, 40.0, 40.0];
3710 for num_buckets in 1..=scores.len() {
3711 let buckets = compute_percentile_buckets(&scores, num_buckets);
3712 for (a, b) in [(0, 1), (1, 2), (3, 4), (6, 7)] {
3713 assert_eq!(
3714 buckets[a], buckets[b],
3715 "num_buckets={num_buckets}: tied scores {}/{} got different buckets {:?}",
3716 scores[a], scores[b], buckets
3717 );
3718 }
3719 }
3720 }
3721
3722 #[test]
3735 fn flop_and_isomorphism_interaction_stays_zero_sum() {
3736 for iters in [1u32, 5, 20, 100] {
3737 let combos = flop_scenario_combos();
3738 let scenario = build_flop_scenario(combos);
3739 let mut trainer = Trainer::new(
3740 scenario.tree,
3741 scenario.trainer_combos,
3742 TrainerOptions {
3743 algorithm: SolverAlgorithm::CfrPlus,
3744 abstraction: CardAbstraction {
3745 flop: Some(2),
3746 ..Default::default()
3747 },
3748 ..TrainerOptions::default()
3749 },
3750 )
3751 .unwrap();
3752 let [ev0, ev1] = trainer.train(iters);
3753 assert!(
3754 (ev0 + ev1).abs() < 1e-6,
3755 "iters={iters}: expected exact zero-sum, got ev0={ev0}, ev1={ev1}, sum={}",
3756 ev0 + ev1
3757 );
3758 }
3759 }
3760
3761 #[test]
3764 fn evaluate_average_strategy_root_ev_is_zero_sum() {
3765 let scenario = build_scenario();
3766 let mut trainer = Trainer::new(
3767 scenario.tree,
3768 scenario.trainer_combos,
3769 TrainerOptions {
3770 algorithm: SolverAlgorithm::CfrPlus,
3771 ..TrainerOptions::default()
3772 },
3773 )
3774 .unwrap();
3775 trainer.train(20_000);
3776 let [ev0, ev1] = trainer.evaluate().root_values;
3777 assert!(
3778 (ev0 + ev1).abs() < 1.0,
3779 "expected zero-sum root EV under the average strategy, got ev0={ev0}, ev1={ev1}"
3780 );
3781 }
3782
3783 #[test]
3790 fn river_equity_matches_known_showdown_outcomes() {
3791 let scenario = build_scenario();
3792 let root_id = match &scenario.tree.root {
3793 Node::Decision { id, .. } => *id,
3794 _ => panic!("expected decision"),
3795 };
3796 let combos0 = scenario.trainer_combos[0].clone();
3797 let mut trainer = Trainer::new(
3798 scenario.tree,
3799 scenario.trainer_combos,
3800 TrainerOptions {
3801 algorithm: SolverAlgorithm::CfrPlus,
3802 ..TrainerOptions::default()
3803 },
3804 )
3805 .unwrap();
3806 trainer.train(5_000);
3807
3808 let eval = trainer.evaluate().nodes;
3809 let root_eval = eval.get(root_id).expect("root should have an evaluation");
3810 let equity = root_eval
3811 .equity
3812 .as_ref()
3813 .expect("river (complete board) node should have equity");
3814
3815 for (
3816 i,
3817 &Combo {
3818 cards: [c1, c2], ..
3819 },
3820 ) in combos0.iter().enumerate()
3821 {
3822 if is_jj(c1, c2) {
3823 assert!(
3824 (equity[i] - 1.0).abs() < 1e-9,
3825 "JJ should have 100% equity vs IP's fixed 99, got {}",
3826 equity[i]
3827 );
3828 } else {
3829 assert!(
3830 equity[i].abs() < 1e-9,
3831 "KQo should have 0% equity vs IP's fixed 99, got {}",
3832 equity[i]
3833 );
3834 }
3835 }
3836 }
3837
3838 #[test]
3843 fn equity_is_none_before_the_river() {
3844 let scenario = build_multi_street_scenario(); let root_id = match &scenario.tree.root {
3846 Node::Decision { id, .. } => *id,
3847 _ => panic!("expected decision"),
3848 };
3849 let mut trainer = Trainer::new(
3850 scenario.tree,
3851 scenario.trainer_combos,
3852 TrainerOptions {
3853 algorithm: SolverAlgorithm::CfrPlus,
3854 ..TrainerOptions::default()
3855 },
3856 )
3857 .unwrap();
3858 trainer.train(500);
3859
3860 let eval = trainer.evaluate().nodes;
3861 let root_eval = eval.get(root_id).expect("root should have an evaluation");
3862 assert!(
3863 root_eval.equity.is_none(),
3864 "expected no equity figure at a pre-river (incomplete board) node"
3865 );
3866 assert_eq!(
3867 root_eval.ev.len(),
3868 trainer.game.combos(Player::Oop).len(),
3869 "EV should still be reported per combo"
3870 );
3871 }
3872
3873 #[test]
3884 fn evaluate_ev_is_normalized_per_combo_not_raw_counterfactual_value() {
3885 let scenario = build_scenario();
3886 let pot = scenario.pot;
3887 let bet = scenario.bet;
3888 let root_id = match &scenario.tree.root {
3889 Node::Decision { id, .. } => *id,
3890 _ => panic!("expected decision"),
3891 };
3892 let ip_facing_bet_id = match &scenario.tree.root {
3893 Node::Decision { children, .. } => match &children[1] {
3894 Node::Decision { id, .. } => *id,
3895 _ => panic!("expected IP decision facing the bet"),
3896 },
3897 _ => panic!("expected decision"),
3898 };
3899
3900 let mut trainer = Trainer::new(
3901 scenario.tree,
3902 scenario.trainer_combos,
3903 TrainerOptions {
3904 algorithm: SolverAlgorithm::CfrPlus,
3905 ..TrainerOptions::default()
3906 },
3907 )
3908 .unwrap();
3909 trainer.train(20_000);
3910 let eval = trainer.evaluate().nodes;
3911
3912 let bound = pot + bet;
3913 let root_eval = eval.get(root_id).expect("root should have an evaluation");
3914 for &ev in &root_eval.ev {
3915 assert!(
3916 ev.abs() <= bound + 1e-6,
3917 "root EV {ev} exceeds the game's stake bound of {bound}"
3918 );
3919 }
3920 let ip_eval = eval
3921 .get(ip_facing_bet_id)
3922 .expect("IP-facing-bet node should have an evaluation");
3923 for &ev in &ip_eval.ev {
3924 assert!(
3925 ev.abs() <= bound + 1e-6,
3926 "IP-facing-bet EV {ev} exceeds the game's stake bound of {bound}"
3927 );
3928 }
3929
3930 let combos0 = trainer.game.combos(Player::Oop);
3935 for (
3936 i,
3937 &Combo {
3938 cards: [c1, c2], ..
3939 },
3940 ) in combos0.iter().enumerate()
3941 {
3942 if is_jj(c1, c2) {
3943 assert!(
3944 root_eval.ev[i] > 0.0,
3945 "JJ should have positive EV, got {}",
3946 root_eval.ev[i]
3947 );
3948 }
3949 }
3950 }
3951
3952 #[test]
3961 fn policy_snapshot_is_frozen_and_matches_trainer_reads() {
3962 let board: Vec<Card> = ["2c", "7c", "9d", "Jd"]
3963 .iter()
3964 .map(|s| s.parse::<Card>().unwrap())
3965 .collect();
3966 let dead = CardSet::from_cards(&board);
3967 let combos = [
3968 Range::parse("AA:0.5,KK,QQ").unwrap().combos(dead),
3969 Range::parse("JJ,TT").unwrap().combos(dead),
3970 ];
3971 let cfg = GameConfig {
3972 board: board.clone(),
3973 pot: Chips::whole(100),
3974 effective_stack: Chips::whole(150),
3975 bet_sizes: vec![0.5, 1.0],
3976 max_raises: 1,
3977 suit_isomorphism: true,
3978 };
3979 let abstraction = CardAbstraction {
3980 river: Some(2),
3981 ..CardAbstraction::default()
3982 };
3983 let make = || {
3984 Trainer::new(
3985 build_tree(&cfg).unwrap(),
3986 combos.clone(),
3987 TrainerOptions {
3988 algorithm: SolverAlgorithm::Dcfr,
3989 abstraction,
3990 ..TrainerOptions::default()
3991 },
3992 )
3993 .unwrap()
3994 };
3995 let bits = |evaluation: Evaluation| {
3996 let nodes: Vec<Vec<u64>> = evaluation
3997 .nodes
3998 .iter()
3999 .map(|e| e.ev.iter().map(|v| v.to_bits()).collect())
4000 .collect();
4001 (nodes, evaluation.root_values.map(f64::to_bits))
4002 };
4003
4004 let mut trainer = make();
4005 trainer.train(30);
4006 let policy = trainer.policy();
4007 let game = Arc::clone(trainer.game());
4008 let evaluation = bits(game.evaluate(&policy));
4009 let exploitability = game.exploitability(&policy).total.to_bits();
4010 assert_eq!(evaluation, bits(trainer.evaluate()));
4011 assert_eq!(exploitability, trainer.exploitability().total.to_bits());
4012 for id in 0..game.num_decision_nodes() {
4013 assert_eq!(
4014 trainer.average_strategy(id),
4015 game.average_strategy(&policy, id)
4016 );
4017 }
4018
4019 trainer.train(30);
4022 assert_ne!(evaluation, bits(trainer.evaluate()));
4023 assert_eq!(evaluation, bits(game.evaluate(&policy)));
4024 assert_eq!(exploitability, game.exploitability(&policy).total.to_bits());
4025 let mut fresh = make();
4026 fresh.train(30);
4027 assert_eq!(evaluation, bits(fresh.evaluate()));
4028
4029 let restored = game.policy_from_rows(policy.rows().to_vec()).unwrap();
4032 assert_eq!(evaluation, bits(game.evaluate(&restored)));
4033 let mut short = policy.rows().to_vec();
4034 short.pop();
4035 assert!(game.policy_from_rows(short).is_err());
4036 let mut skewed = policy.rows().to_vec();
4037 skewed[0][0][0] += 0.5;
4038 assert!(game.policy_from_rows(skewed).is_err());
4039
4040 let (id, b, partner) = game
4043 .node_meta
4044 .iter()
4045 .enumerate()
4046 .find_map(|(id, (player, board))| {
4047 let group = game.suit_groups.get(board)?[*player]
4048 .iter()
4049 .find(|g| g.len() > 1)?;
4050 Some((id, group[0], group[1]))
4051 })
4052 .expect("suit-reduced fixture has a nontrivial suit group");
4053 let mut asymmetric = policy.rows().to_vec();
4054 let rows = &mut asymmetric[id];
4055 rows.iter_mut().for_each(|row| row[b] = 0.0);
4056 rows[0][b] = 1.0;
4057 rows.iter_mut().for_each(|row| row[partner] = 0.0);
4058 let last = rows.len() - 1;
4059 rows[last][partner] = 1.0;
4060 assert!(last > 0);
4061 assert!(
4062 matches!(game.policy_from_rows(asymmetric).unwrap_err(), PolicyError::NotSymmetric { node } if node == id)
4063 );
4064 }
4065
4066 #[test]
4067 fn exploitability_decreases_with_more_training() {
4068 let few = build_scenario();
4069 let mut few_trainer = Trainer::new(
4070 few.tree,
4071 few.trainer_combos,
4072 TrainerOptions {
4073 algorithm: SolverAlgorithm::CfrPlus,
4074 ..TrainerOptions::default()
4075 },
4076 )
4077 .unwrap();
4078 few_trainer.train(100);
4079 let few_expl = few_trainer.exploitability();
4080
4081 let many = build_scenario();
4082 let mut many_trainer = Trainer::new(
4083 many.tree,
4084 many.trainer_combos,
4085 TrainerOptions {
4086 algorithm: SolverAlgorithm::CfrPlus,
4087 ..TrainerOptions::default()
4088 },
4089 )
4090 .unwrap();
4091 many_trainer.train(20_000);
4092 let many_expl = many_trainer.exploitability();
4093
4094 assert!(
4095 few_expl.total > -1e-6,
4096 "exploitability should never be meaningfully negative, got {}",
4097 few_expl.total
4098 );
4099 assert!(
4100 many_expl.total > -1e-6,
4101 "exploitability should never be meaningfully negative, got {}",
4102 many_expl.total
4103 );
4104 assert!(
4105 many_expl.total < few_expl.total,
4106 "expected exploitability to shrink with more training: 100 iters -> {}, 20,000 iters -> {}",
4107 few_expl.total,
4108 many_expl.total
4109 );
4110 }
4111
4112 #[test]
4113 fn exploitability_is_near_zero_after_convergence() {
4114 let scenario = build_scenario();
4115 let pot = scenario.pot;
4116 let mut trainer = Trainer::new(
4117 scenario.tree,
4118 scenario.trainer_combos,
4119 TrainerOptions {
4120 algorithm: SolverAlgorithm::CfrPlus,
4121 ..TrainerOptions::default()
4122 },
4123 )
4124 .unwrap();
4125 trainer.train(20_000);
4126 let expl = trainer.exploitability();
4127 assert!(
4128 expl.total < pot * 0.001,
4129 "expected exploitability below 0.1% of pot after 20,000 iterations, got {}",
4130 expl.total
4131 );
4132 }
4133
4134 fn analytical_exploitability_trainer(combos: [Vec<Combo>; 2]) -> Trainer {
4140 use crate::solver::tree::{Action, Player, Tree};
4141 let board: Vec<Card> = ["2c", "7d", "9h", "Js", "Qd"]
4142 .iter()
4143 .map(|s| s.parse::<Card>().unwrap())
4144 .collect();
4145 let scores = eval_combos_if_complete(&combos, &board);
4146 let dead = mask_of(&board);
4147 for (
4150 i,
4151 &Combo {
4152 cards: [h1, h2], ..
4153 },
4154 ) in combos[0].iter().enumerate()
4155 {
4156 for (
4157 j,
4158 &Combo {
4159 cards: [v1, v2], ..
4160 },
4161 ) in combos[1].iter().enumerate()
4162 {
4163 if [h1, h2, v1, v2].iter().any(|&c| mask_has(dead, c))
4164 || h1 == v1
4165 || h1 == v2
4166 || h2 == v1
4167 || h2 == v2
4168 {
4169 continue;
4170 }
4171 assert!(
4172 scores[0][i] > scores[1][j],
4173 "fixture requires OOP to win every legal showdown"
4174 );
4175 }
4176 }
4177 let tree = Tree {
4178 board: board.clone(),
4179 root: Node::Decision {
4180 id: 0,
4181 player: Player::Oop,
4182 actions: vec![Action::Check, Action::Bet(Chips::whole(5))],
4183 children: vec![
4184 Node::Terminal(Terminal::Showdown {
4185 invested: [5.0, 5.0],
4186 }),
4187 Node::Decision {
4188 id: 1,
4189 player: Player::Ip,
4190 actions: vec![Action::Call, Action::Fold],
4191 children: vec![
4192 Node::Terminal(Terminal::Showdown {
4193 invested: [10.0, 10.0],
4194 }),
4195 Node::Terminal(Terminal::Fold {
4196 winner: Player::Oop,
4197 invested: [10.0, 5.0],
4198 }),
4199 ],
4200 },
4201 ],
4202 },
4203 num_decision_nodes: 2,
4204 };
4205 Trainer::new_unchecked(
4208 tree,
4209 combos,
4210 TrainerOptions {
4211 algorithm: SolverAlgorithm::CfrPlus,
4212 ..TrainerOptions::default()
4213 },
4214 )
4215 }
4216
4217 fn weighted_combo(a: &str, b: &str, weight: f64) -> Combo {
4218 Combo::new(
4219 a.parse::<Card>().unwrap(),
4220 b.parse::<Card>().unwrap(),
4221 weight,
4222 )
4223 }
4224
4225 fn assert_analytical_exploitability(expl: Exploitability) {
4226 assert!(
4227 (expl.oop - 7.5).abs() < 1e-10,
4228 "OOP BR must be 7.5 chips, got {}",
4229 expl.oop
4230 );
4231 assert!(
4232 (expl.ip + 5.0).abs() < 1e-10,
4233 "IP BR must be -5 chips, got {}",
4234 expl.ip
4235 );
4236 assert!(
4237 (expl.total - 1.25).abs() < 1e-10,
4238 "exploitability must be 1.25 chips, got {}",
4239 expl.total
4240 );
4241 }
4242
4243 #[test]
4244 fn exploitability_matches_analytical_best_responses_with_blockers() {
4245 let combos = [
4249 vec![
4250 weighted_combo("Ac", "Ad", 1.0),
4251 weighted_combo("Ah", "As", 1.0),
4252 weighted_combo("Qd", "Qc", 1.0),
4253 ],
4254 vec![
4255 weighted_combo("Kc", "Kd", 1.0),
4256 weighted_combo("Ac", "Ks", 1.0),
4257 weighted_combo("2c", "3d", 1.0),
4258 ],
4259 ];
4260 assert_analytical_exploitability(
4261 analytical_exploitability_trainer(combos).exploitability(),
4262 );
4263 }
4264
4265 #[test]
4266 fn exploitability_chip_units_ignore_range_weight_scale() {
4267 for (oop_scale, ip_scale) in [(1.0, 1.0), (0.25, 1.0), (1.0, 0.7), (0.25, 0.7)] {
4268 let combos = [
4269 vec![
4270 weighted_combo("Ac", "Ad", oop_scale),
4271 weighted_combo("Ah", "As", 0.3 * oop_scale),
4272 ],
4273 vec![
4274 weighted_combo("Kc", "Kd", ip_scale),
4275 weighted_combo("Ac", "Ks", 0.6 * ip_scale),
4276 ],
4277 ];
4278 assert_analytical_exploitability(
4279 analytical_exploitability_trainer(combos).exploitability(),
4280 );
4281 }
4282 }
4283
4284 #[test]
4285 fn exploitability_rejects_zero_or_nonfinite_joint_mass() {
4286 for combos in [
4287 [
4288 vec![weighted_combo("Ac", "Ad", 1.0)],
4289 vec![weighted_combo("Ac", "Ks", 1.0)],
4290 ],
4291 [
4292 vec![weighted_combo("Ac", "Ad", 0.0)],
4293 vec![weighted_combo("Kc", "Kd", 1.0)],
4294 ],
4295 [
4296 vec![weighted_combo("Qd", "Qc", 1.0)],
4297 vec![weighted_combo("Kc", "Kd", 1.0)],
4298 ],
4299 [
4300 vec![weighted_combo("Ac", "Ad", f64::INFINITY)],
4301 vec![weighted_combo("Kc", "Kd", 1.0)],
4302 ],
4303 [
4304 vec![weighted_combo("Ac", "Ad", f64::NAN)],
4305 vec![weighted_combo("Kc", "Kd", 1.0)],
4306 ],
4307 ] {
4308 let expl = analytical_exploitability_trainer(combos).exploitability();
4309 assert!(
4310 expl.oop.is_nan() && expl.ip.is_nan() && expl.total.is_nan(),
4311 "undefined metric must not appear converged: {expl:?}"
4312 );
4313 }
4314 }
4315
4316 #[test]
4325 fn exploitability_isomorphism_reduced_and_unreduced_match() {
4326 let combos = two_suit_scenario_combos();
4327 let reduced = build_two_suit_scenario(true, combos.clone());
4328 let unreduced = build_two_suit_scenario(false, combos);
4329
4330 let iterations = 3_000;
4331 let mut reduced_trainer = Trainer::new(
4332 reduced.tree,
4333 reduced.trainer_combos,
4334 TrainerOptions {
4335 algorithm: SolverAlgorithm::CfrPlus,
4336 ..TrainerOptions::default()
4337 },
4338 )
4339 .unwrap();
4340 reduced_trainer.train(iterations);
4341 let mut unreduced_trainer = Trainer::new(
4342 unreduced.tree,
4343 unreduced.trainer_combos,
4344 TrainerOptions {
4345 algorithm: SolverAlgorithm::CfrPlus,
4346 ..TrainerOptions::default()
4347 },
4348 )
4349 .unwrap();
4350 unreduced_trainer.train(iterations);
4351
4352 let reduced_expl = reduced_trainer.exploitability();
4353 let unreduced_expl = unreduced_trainer.exploitability();
4354 let rel_diff =
4361 (reduced_expl.total - unreduced_expl.total).abs() / unreduced_expl.total.abs().max(1.0);
4362 assert!(
4363 rel_diff < 0.1,
4364 "expected matching exploitability with isomorphism enabled/disabled: reduced={}, unreduced={}",
4365 reduced_expl.total,
4366 unreduced_expl.total
4367 );
4368 }
4369}
4370
4371#[cfg(test)]
4372mod terminal_regression_tests {
4373 use super::*;
4374 use crate::card::Card;
4375 use crate::solver::tree::{Player, Tree};
4376 use crate::solver::Chips;
4377
4378 fn close(actual: f64, expected: f64) {
4379 let tolerance = 2e-10 + expected.abs() * 2e-12;
4380 assert!(
4381 (actual - expected).abs() <= tolerance,
4382 "actual={actual}, expected={expected}, tolerance={tolerance}"
4383 );
4384 }
4385
4386 #[test]
4387 fn linear_terminals_match_pairwise_oracle() {
4388 let full: Vec<_> = (0..52)
4391 .flat_map(|a| (a + 1..52).map(move |b| Combo::new(Card(a), Card(b), 1.0)))
4392 .collect();
4393 let mut asymmetric = full.iter().step_by(7).copied().collect::<Vec<_>>();
4394 asymmetric.reverse();
4395 let Combo {
4396 cards: [a, b],
4397 weight,
4398 } = asymmetric[3];
4399 asymmetric.push(Combo::new(b, a, weight)); for board in [
4401 ["2c", "7d", "9h", "Js", "Qd"],
4402 ["Tc", "Jc", "Qc", "Kc", "Ac"],
4403 ["Jh", "Js", "2c", "2d", "3h"],
4404 ] {
4405 let board: Vec<_> = board.iter().map(|s| s.parse::<Card>().unwrap()).collect();
4406 for combos in [
4407 [full.clone(), full.clone()],
4408 [asymmetric.clone(), full.clone()],
4409 [full.clone(), Vec::new()],
4410 ] {
4411 let tree = Tree {
4412 board: board.clone(),
4413 root: Node::Terminal(Terminal::Showdown {
4414 invested: [37.0, 121.0],
4415 }),
4416 num_decision_nodes: 0,
4417 };
4418 let trainer = Trainer::new_unchecked(
4421 tree,
4422 combos,
4423 TrainerOptions {
4424 algorithm: SolverAlgorithm::CfrPlus,
4425 ..TrainerOptions::default()
4426 },
4427 );
4428 for phase in 0..3 {
4429 let reach: [Vec<f64>; 2] = std::array::from_fn(|p| {
4430 (0..trainer.game.combos[p].len())
4431 .map(|i| {
4432 if phase == 2 || (i + phase) % 5 == 0 {
4433 0.0
4434 } else {
4435 ((i * 37 + p * 19 + phase) % 103) as f64 / 103.0
4436 }
4437 })
4438 .collect()
4439 });
4440 for terminal in [
4441 Terminal::Showdown {
4442 invested: [37.0, 121.0],
4443 },
4444 Terminal::Showdown {
4445 invested: [50.0, 50.0],
4446 },
4447 Terminal::Fold {
4448 winner: Player::Oop,
4449 invested: [37.0, 121.0],
4450 },
4451 Terminal::Fold {
4452 winner: Player::Ip,
4453 invested: [37.0, 121.0],
4454 },
4455 ] {
4456 let scores = eval_combos_if_complete(&trainer.game.combos, &board);
4457 trainer
4458 .game
4459 .use_pairwise_terminals
4460 .store(false, std::sync::atomic::Ordering::Relaxed);
4461 let actual = trainer
4462 .game
4463 .terminal_value(&terminal, &reach, &board, &scores);
4464 if let Terminal::Showdown { invested } = &terminal {
4465 for p in 0..2 {
4466 let before =
4467 trainer.game.terminal_index.showdown_before_rank_cache(
4468 &trainer.game.combos,
4469 p,
4470 &reach[1 - p],
4471 &scores,
4472 &trainer.game.board_order_cache[&board],
4473 mask_of(&board),
4474 invested,
4475 );
4476 assert_eq!(
4477 actual[p].iter().map(|x| x.to_bits()).collect::<Vec<_>>(),
4478 before.iter().map(|x| x.to_bits()).collect::<Vec<_>>()
4479 );
4480 }
4481 }
4482 trainer
4483 .game
4484 .use_pairwise_terminals
4485 .store(true, std::sync::atomic::Ordering::Relaxed);
4486 let reference = trainer
4487 .game
4488 .terminal_value(&terminal, &reach, &board, &scores);
4489 for p in 0..2 {
4490 for (a, b) in actual[p].iter().zip(&reference[p]) {
4491 close(*a, *b);
4492 }
4493 }
4494 }
4495 }
4496 }
4497 }
4498 }
4499
4500 #[test]
4501 fn linear_terminals_preserve_training_and_best_response() {
4502 use crate::range::Range;
4503 use crate::solver::tree::{build_tree, GameConfig};
4504 for board in [
4505 vec!["2c", "7d", "9h", "Js", "Qd"],
4506 vec!["Jh", "Js", "2c", "2d"],
4507 ] {
4508 let board: Vec<_> = board.iter().map(|s| s.parse::<Card>().unwrap()).collect();
4509 let combos: [Vec<_>; 2] = ["AA,KK,JJ,54s:0.3", "QQ,TT,88,65s:0.7"].map(|s| {
4510 let mut v = Range::parse(s).unwrap().combos(CardSet::from_cards(&board));
4511 v.sort_by_key(|c| (c.cards[0], c.cards[1]));
4512 v
4513 });
4514 let cfg = GameConfig {
4515 board: board.clone(),
4516 pot: Chips::whole(100),
4517 effective_stack: Chips::whole(100),
4518 bet_sizes: vec![0.5],
4519 max_raises: 0,
4520 suit_isomorphism: false,
4521 };
4522 let mut actual = Trainer::new(
4523 build_tree(&cfg).unwrap(),
4524 combos.clone(),
4525 TrainerOptions {
4526 algorithm: SolverAlgorithm::CfrPlus,
4527 ..TrainerOptions::default()
4528 },
4529 )
4530 .unwrap();
4531 let mut reference = Trainer::new(
4532 build_tree(&cfg).unwrap(),
4533 combos,
4534 TrainerOptions {
4535 algorithm: SolverAlgorithm::CfrPlus,
4536 ..TrainerOptions::default()
4537 },
4538 )
4539 .unwrap();
4540 reference
4541 .game
4542 .use_pairwise_terminals
4543 .store(true, std::sync::atomic::Ordering::Relaxed);
4544 let ev_a = actual.train(60);
4545 let ev_b = reference.train(60);
4546 for p in 0..2 {
4547 close(ev_a[p], ev_b[p]);
4548 }
4549 for id in 0..actual.game.tree.num_decision_nodes {
4550 for (a, b) in actual
4551 .average_strategy(id)
4552 .iter()
4553 .flatten()
4554 .zip(reference.average_strategy(id).iter().flatten())
4555 {
4556 close(*a, *b);
4557 }
4558 }
4559 let a = actual.exploitability();
4560 let b = reference.exploitability();
4561 close(a.oop, b.oop);
4562 close(a.ip, b.ip);
4563 close(a.total, b.total);
4564 let a = actual.evaluate().nodes;
4565 let b = reference.evaluate().nodes;
4566 for (eval, other) in a.iter().zip(&b) {
4567 for (x, y) in eval.ev.iter().zip(&other.ev) {
4568 close(*x, *y);
4569 }
4570 }
4571 }
4572 }
4573}
4574
4575#[cfg(test)]
4576#[path = "cfr/target_values_tests.rs"]
4577mod target_values_tests;
4578
4579#[cfg(test)]
4580#[path = "suit_reduction_tests.rs"]
4581mod suit_reduction_tests;
4582
4583fn has_suit_reduction(node: &Node) -> bool {
4584 match node {
4585 Node::Chance { children } => children
4586 .iter()
4587 .any(|(members, child)| members.len() > 1 || has_suit_reduction(child)),
4588 Node::Decision { children, .. } => children.iter().any(has_suit_reduction),
4589 Node::Terminal(_) => false,
4590 }
4591}
4592
4593fn suit_bucket_groups(
4596 board: &[Card],
4597 combos: &[Vec<Combo>; 2],
4598 index: &[HashMap<(Card, Card), usize>; 2],
4599 maps: &[Vec<usize>; 2],
4600) -> [Vec<Vec<usize>>; 2] {
4601 let free: Vec<u8> = (0..4)
4602 .filter(|s| !board.iter().any(|&c| c.suit() == *s))
4603 .collect();
4604 std::array::from_fn(|p| {
4605 if free.len() < 2 {
4606 return Vec::new();
4607 }
4608 let n = maps[p].iter().max().map_or(0, |b| b + 1);
4609 let mut parent: Vec<usize> = (0..n).collect();
4610 fn root(parent: &[usize], mut i: usize) -> usize {
4611 while parent[i] != i {
4612 i = parent[i];
4613 }
4614 i
4615 }
4616 for (a, &sa) in free.iter().enumerate() {
4617 for &sb in &free[a + 1..] {
4618 for (
4619 i,
4620 &Combo {
4621 cards: [h1, h2],
4622 weight: w,
4623 },
4624 ) in combos[p].iter().enumerate()
4625 {
4626 let pair = normalize_pair(swap_suit(h1, sa, sb), swap_suit(h2, sa, sb));
4627 let &j = index[p]
4628 .get(&pair)
4629 .expect("suit reduction requires suit-closed ranges");
4630 assert_eq!(
4631 w, combos[p][j].weight,
4632 "suit reduction requires suit-symmetric range weights"
4633 );
4634 let (x, y) = (root(&parent, maps[p][i]), root(&parent, maps[p][j]));
4635 parent[x.max(y)] = x.min(y);
4636 }
4637 }
4638 }
4639 let mut groups = vec![Vec::new(); n];
4640 for i in 0..n {
4641 groups[root(&parent, i)].push(i);
4642 }
4643 groups.into_iter().filter(|group| group.len() > 1).collect()
4644 })
4645}