"""
Counterfactual Regret Minimization Plus (CFR+) Implementation
This script implements the CFR+ algorithm for solving zero-sum extensive-form games.
CFR+ is an enhancement of the original CFR algorithm that utilizes regret matching+,
which accelerates convergence by keeping track of positive cumulative regrets and
resetting negative regrets to zero.
The code is organized to handle generic extensive-form games, but for demonstration
purposes, we use a simple Kuhn Poker game.
Author: [Your Name]
Date: [Date]
"""
import numpy as np
import itertools
# Define the game
class KuhnPoker:
"""
A simple implementation of Kuhn Poker for use with CFR+.
In Kuhn Poker, each player is dealt one card from a deck of three cards.
Players can either bet or pass, with the highest card winning unless someone folds.
"""
def __init__(self):
self.cards = ['J', 'Q', 'K'] # The deck
self.players = [1, 2]
def infosets(self):
"""
Generate all possible information sets for the game.
Returns:
infoset_dict: A dictionary mapping information sets to unique keys.
"""
infoset_dict = {}
index = 0
for card in self.cards:
for history in ['', 'p', 'b', 'pp', 'pb', 'bp', 'bb']:
infoset = f'{card}:{history}'
infoset_dict.setdefault(infoset, index)
index += 1
return infoset_dict
def is_terminal(self, history):
"""
Check if the game has reached a terminal state.
Args:
history (str): The sequence of actions taken so far.
Returns:
bool: True if terminal, False otherwise.
"""
# Terminal conditions:
# - Two passes (pp)
# - A bet followed by a pass (bp)
# - Two bets (bb)
return history in ['pp', 'bp', 'bb']
def utility(self, history, cards):
"""
Calculate the utility for players at the terminal state.
Args:
history (str): The sequence of actions taken.
cards (dict): The cards held by each player.
Returns:
dict: Utilities for each player.
"""
pot = 1 # Start with initial pot size
if history == 'pp':
# Both players passed; highest card wins
winner = self.winner(cards)
utilities = {player: (1 if player == winner else -1) for player in self.players}
elif history == 'bp':
# Player 1 bet, Player 2 passed
utilities = {1: 1, 2: -1}
elif history == 'pb':
# Player 1 passed, Player 2 bet (not terminal)
utilities = {}
elif history == 'bb':
# Both players bet; highest card wins, pot is increased
pot = 2
winner = self.winner(cards)
utilities = {player: (pot if player == winner else -pot) for player in self.players}
else:
utilities = {}
return utilities
def winner(self, cards):
"""
Determine the winner based on the cards.
Args:
cards (dict): The cards held by each player.
Returns:
int: The winning player.
"""
rank = {'J': 1, 'Q': 2, 'K': 3}
if rank[cards[1]] > rank[cards[2]]:
return 1
else:
return 2
def get_available_actions(self, history):
"""
Get the available actions for the current state.
Args:
history (str): The sequence of actions taken.
Returns:
list: Available actions ('p' for pass, 'b' for bet).
"""
if history.endswith('b'):
# If last action was a bet, next player can only call or fold
return ['p', 'b']
else:
return ['p', 'b']
def get_next_player(self, history):
"""
Determine which player's turn it is.
Args:
history (str): The sequence of actions taken.
Returns:
int: The next player to act.
"""
return (len(history) % 2) + 1
# CFR+ Algorithm Implementation
class CFRPlus:
"""
Implementation of the CFR+ algorithm.
Attributes:
game (KuhnPoker): The game to solve.
regret_sum (dict): Accumulated positive regrets.
strategy_sum (dict): Cumulative strategy probabilities.
strategy (dict): Current strategy for each information set.
infoset_map (dict): Mapping of information sets to unique keys.
"""
def __init__(self, game):
self.game = game
self.regret_sum = {} # Positive cumulative regrets
self.strategy_sum = {} # Cumulative strategy
self.strategy = {} # Current strategy
self.infoset_map = game.infosets()
def get_strategy(self, infoset):
"""
Determine the strategy at a given information set using regret matching+.
Args:
infoset (str): The information set key.
Returns:
list: Probability distribution over actions.
"""
num_actions = 2 # 'p' and 'b'
positive_regrets = np.maximum(self.regret_sum.get(infoset, np.zeros(num_actions)), 0)
normalizing_sum = positive_regrets.sum()
if normalizing_sum > 0:
strategy = positive_regrets / normalizing_sum
else:
# If no positive regrets, choose uniform strategy
strategy = np.ones(num_actions) / num_actions
# Update the cumulative strategy
self.strategy_sum[infoset] = self.strategy_sum.get(infoset, np.zeros(num_actions)) + strategy
self.strategy[infoset] = strategy
return strategy
def get_average_strategy(self, infoset):
"""
Compute the average strategy over iterations.
Args:
infoset (str): The information set key.
Returns:
list: Average probability distribution over actions.
"""
total = self.strategy_sum.get(infoset, np.zeros(2)).sum()
if total > 0:
return self.strategy_sum[infoset] / total
else:
return np.ones(2) / 2
def cfr_plus(self, cards, history, pi1, pi2):
"""
The main CFR+ recursive function.
Args:
cards (dict): The cards held by each player.
history (str): The sequence of actions taken so far.
pi1 (float): Probability of player 1 reaching this node.
pi2 (float): Probability of player 2 reaching this node.
Returns:
float: The utility value from this node.
"""
# Check for terminal state
if self.game.is_terminal(history):
utilities = self.game.utility(history, cards)
return utilities.get(1, 0) - utilities.get(2, 0)
player = self.game.get_next_player(history)
opponent = 2 if player == 1 else 1
infoset = f'{cards[player]}:{history}'
# Get available actions and map them to indices
actions = self.game.get_available_actions(history)
action_map = {action: idx for idx, action in enumerate(actions)}
# Get current strategy
strategy = self.get_strategy(infoset)
# Initialize variables for regret calculation
num_actions = len(actions)
util = np.zeros(num_actions)
node_util = 0
# Recursively call cfr_plus for each action
for idx, action in enumerate(actions):
next_history = history + action
if player == 1:
util[idx] = -self.cfr_plus(cards, next_history, pi1 * strategy[idx], pi2)
else:
util[idx] = -self.cfr_plus(cards, next_history, pi1, pi2 * strategy[idx])
node_util += strategy[idx] * util[idx]
# Update regrets
regrets = util - node_util
if player == 1:
pi_opponent = pi2
pi_player = pi1
else:
pi_opponent = pi1
pi_player = pi2
# Regret Matching+ update
regret_sum = self.regret_sum.get(infoset, np.zeros(num_actions))
regret_sum += pi_opponent * regrets
self.regret_sum[infoset] = np.maximum(regret_sum, 0) # Only keep positive regrets
return node_util
def train(self, iterations):
"""
Train the CFR+ algorithm over a specified number of iterations.
Args:
iterations (int): Number of iterations to run.
"""
cards = self.game.cards
for _ in range(iterations):
# Shuffle and deal cards
card_permutations = list(itertools.permutations(cards))
for card_combo in card_permutations:
cards_dealt = {1: card_combo[0], 2: card_combo[1]}
self.cfr_plus(cards_dealt, '', 1, 1)
def get_nash_equilibrium(self):
"""
Retrieve the approximate Nash equilibrium strategy after training.
Returns:
dict: Average strategies for each information set.
"""
nash_equilibrium = {}
for infoset in self.infoset_map.keys():
avg_strategy = self.get_average_strategy(infoset)
nash_equilibrium[infoset] = avg_strategy
return nash_equilibrium
# Main execution
if __name__ == "__main__":
# Initialize the game and CFR+ solver
game = KuhnPoker()
cfr_plus_solver = CFRPlus(game)
# Train the solver
iterations = 10000
cfr_plus_solver.train(iterations)
# Retrieve the approximate Nash equilibrium
nash_equilibrium = cfr_plus_solver.get_nash_equilibrium()
# Display the strategies
print("Nash Equilibrium Strategies:")
for infoset, strategy in nash_equilibrium.items():
actions = ['p', 'b'] # pass and bet
strategy_str = ', '.join([f"{action}: {prob:.2f}" for action, prob in zip(actions, strategy)])
print(f"InfoSet {infoset}: {strategy_str}")