### Get Help for poker_ai train start command Source: https://github.com/keithlee96/pluribus-poker-ai/blob/develop/README.md View help information for starting the training process of a poker agent. ```bash poker_ai train start --help ``` -------------------------------- ### Install Dependencies with npm Source: https://github.com/keithlee96/pluribus-poker-ai/blob/develop/applications/visualisation/frontend/README.md Run this command to install all necessary project dependencies. ```bash npm install ``` -------------------------------- ### Install poker_ai from PyPI Source: https://github.com/keithlee96/pluribus-poker-ai/blob/develop/README.md Install the poker_ai package using pip. This is the recommended method for general use. ```bash pip install poker_ai ``` -------------------------------- ### Install poker_ai from Source (Development) Source: https://github.com/keithlee96/pluribus-poker-ai/blob/develop/README.md Install the poker_ai package from source for development. This requires cloning the repository and using pip in editable mode. ```bash git clone https://github.com/fedden/poker_ai.git # Though really we should use ssh here! cd /path/to/poker_ai pip install . ``` -------------------------------- ### Get Help for poker_ai train resume command Source: https://github.com/keithlee96/pluribus-poker-ai/blob/develop/README.md Get help on how to resume a previously interrupted training session for a poker agent. ```bash poker_ai train resume --help ``` -------------------------------- ### Get Help for poker_ai play command Source: https://github.com/keithlee96/pluribus-poker-ai/blob/develop/README.md Display help for the 'play' command, used to play against a trained poker bot. ```bash poker_ai play --help ``` -------------------------------- ### Get Help on Pluribus Poker AI Commands Source: https://context7.com/keithlee96/pluribus-poker-ai/llms.txt Use the CLI to list all available commands or get specific help for clustering, training, or playing commands. ```bash poker_ai --help ``` ```bash poker_ai cluster --help ``` ```bash poker_ai train start --help ``` ```bash poker_ai play --help ``` -------------------------------- ### Get Help for poker_ai CLI Source: https://github.com/keithlee96/pluribus-poker-ai/blob/develop/README.md View all available commands for the poker_ai command-line interface by using the --help flag. ```bash poker_ai --help ``` -------------------------------- ### Serve with Hot Reload using npm Source: https://github.com/keithlee96/pluribus-poker-ai/blob/develop/applications/visualisation/frontend/README.md Use this command to start a development server with hot reloading enabled, typically accessible at localhost:8080. ```bash npm run dev ``` -------------------------------- ### Install Git Flow (Debian/Ubuntu) Source: https://github.com/keithlee96/pluribus-poker-ai/blob/develop/CONTRIBUTING.md Install the Git Flow extension on Debian or Ubuntu systems using the apt package manager. ```bash sudo apt install git-flow ``` -------------------------------- ### Start poker bot training Source: https://github.com/keithlee96/pluribus-poker-ai/blob/develop/README.md Initiate the training process for a poker bot using the MCCFR algorithm. This command starts iterative self-play to refine the agent's strategy. ```bash poker_ai train start ``` -------------------------------- ### Work with Cards and Evaluate Hands in Python Source: https://context7.com/keithlee96/pluribus-poker-ai/llms.txt Demonstrates the usage of the Card class for representing poker cards and the Evaluator class for ranking hands using an optimized algorithm. Shows card creation, property access, comparison, and hand evaluation setup. ```python from poker_ai.poker.card import Card from poker_ai.poker.evaluation.evaluator import Evaluator # Create cards using rank (2-14) and suit ace_spades = Card(rank=14, suit="spades") # Ace of Spades king_hearts = Card(rank="king", suit="hearts") # King of Hearts ten_diamonds = Card(rank=10, suit="diamonds") # Ten of Diamonds print(ace_spades) # # Card properties print(f"Rank: {ace_spades.rank}") # 'ace' print(f"Rank int: {ace_spades.rank_int}") # 14 print(f"Suit: {ace_spades.suit}") # 'spades' # Cards can be compared print(ace_spades > king_hearts) # True # Create an evaluator evaluator = Evaluator() # Evaluate a 5-7 card hand (board + hole cards) board = [ Card(14, "hearts").eval_card, # Ah Card(13, "hearts").eval_card, # Kh Card(12, "hearts").eval_card, # Qh Card(11, "hearts").eval_card, # Jh Card(2, "clubs").eval_card, # 2c ] hand = [ Card(10, "hearts").eval_card, # Th Card(9, "spades").eval_card, # 9s ] ``` -------------------------------- ### Run Single-Process Training Source: https://context7.com/keithlee96/pluribus-poker-ai/llms.txt Use this Python script for simpler setups or debugging. It configures and runs single-process training for the poker AI. ```python from pathlib import Path from poker_ai.ai.singleprocess.train import simple_search from poker_ai import utils # Create save directory save_path = utils.io.create_dir("single_process_training") # Configuration dictionary config = { "strategy_interval": 20, "n_iterations": 1000, "lcfr_threshold": 200, "discount_interval": 200, "prune_threshold": 200, "c": -20000, "n_players": 3, "dump_iteration": 100, "update_threshold": 200, } # Run single-process training simple_search( config=config, save_path=save_path, lut_path="./card_info_lut_dir", pickle_dir=False, strategy_interval=config["strategy_interval"], n_iterations=config["n_iterations"], lcfr_threshold=config["lcfr_threshold"], discount_interval=config["discount_interval"], prune_threshold=config["prune_threshold"], c=config["c"], n_players=config["n_players"], dump_iteration=config["dump_iteration"], update_threshold=config["update_threshold"], ) # Load trained agent import joblib trained_agent = joblib.load(save_path / "agent.joblib") print(f"Trained strategies: {len(trained_agent['strategy'])}") print(f"Final timestep: {trained_agent['timestep']}") ``` -------------------------------- ### Get Help for poker_ai cluster command Source: https://github.com/keithlee96/pluribus-poker-ai/blob/develop/README.md Obtain detailed help for the 'cluster' command, which is used for producing lookup tables. ```bash poker_ai cluster --help ``` -------------------------------- ### Run Python tests with pytest Source: https://github.com/keithlee96/pluribus-poker-ai/blob/develop/README.md Execute the project's tests using the pytest framework. Ensure you are in the repository's root directory after cloning and installing pytest. ```bash cd /path/to/poker_ai pip install pytest pytest ``` -------------------------------- ### Information Sets for Strategy Lookup Source: https://context7.com/keithlee96/pluribus-poker-ai/llms.txt Explains how to use the `info_set` property to get a unique identifier for a player's current strategic situation, which is crucial for strategy lookup tables. ```APIDOC ## Information Sets for Strategy Lookup ### Description The `info_set` property returns a unique string identifier for the current player's information state, used as a key for strategy lookup tables. ### Method N/A (Python code examples) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ### Code Example ```python from poker_ai.games.short_deck.state import new_game # Create game with card info lookup tables loaded state = new_game(n_players=3, lut_path="./card_info_lut_dir") # Get the information set for the current player info_set = state.info_set print(f"Information set: {info_set}") # Use info_set as key for strategy dictionaries strategy = { info_set: {"fold": 0.1, "call": 0.6, "raise": 0.3} } # Get initial regret/strategy templates for new info sets initial_regret = state.initial_regret initial_strategy = state.initial_strategy ``` ``` -------------------------------- ### Create Feature Branch Source: https://github.com/keithlee96/pluribus-poker-ai/blob/develop/CONTRIBUTING.md Start a new feature branch using Git Flow. Feature branches are created off the 'develop' branch. ```bash git flow feature start my-feature-branch-name-here ``` -------------------------------- ### Build Documentation Source: https://github.com/keithlee96/pluribus-poker-ai/blob/develop/README.md Builds the project's HTML documentation. Navigate to the docs directory, run 'make html', and then serve the built HTML files using a simple HTTP server. ```bash # Build the documentation. cd /path/to/poker_ai/docs make html cd ./_build/html # Run a webserver and navigate to localhost and the port (usually 8000) in your browser. python -m http.server ``` -------------------------------- ### Build Frontend for Poker Visualisation Source: https://github.com/keithlee96/pluribus-poker-ai/blob/develop/applications/visualisation/README.md Navigate to the frontend directory and run the build command to prepare static files for the PokerPlot class. This is a prerequisite for running the visualization. ```bash cd frontend npm run build ``` -------------------------------- ### Build for Production with npm Source: https://github.com/keithlee96/pluribus-poker-ai/blob/develop/applications/visualisation/frontend/README.md Execute this command to create a minified production build of the project. ```bash npm run build ``` -------------------------------- ### Build for Production and Analyze Bundle with npm Source: https://github.com/keithlee96/pluribus-poker-ai/blob/develop/applications/visualisation/frontend/README.md This command builds the project for production and generates a report from the bundle analyzer. ```bash npm run build --report ``` -------------------------------- ### Train AI with Multi-Process Server Source: https://context7.com/keithlee96/pluribus-poker-ai/llms.txt Sets up and runs a multi-process server for distributed AI training. Configures training parameters such as iteration counts, pruning thresholds, and synchronization options. Includes functionality to resume training from a saved checkpoint. ```python from pathlib import Path from poker_ai.ai.multiprocess.server import Server from poker_ai import utils save_path = utils.io.create_dir("my_training") server = Server( strategy_interval=20, n_iterations=10000, lcfr_threshold=400, discount_interval=400, prune_threshold=400, c=-20000, n_players=3, dump_iteration=20, update_threshold=400, save_path=save_path, lut_path="./card_info_lut_dir", pickle_dir=False, sync_update_strategy=True, sync_cfr=True, sync_discount=True, sync_serialise=True, ) try: server.search() except KeyboardInterrupt: print("Stopping training...") finally: server.terminate() import joblib config = joblib.load("./my_training/server.gz") resumed_server = Server.from_dict(config) resumed_server.search() ``` -------------------------------- ### Run a Complete Poker Round with PokerEngine in Python Source: https://context7.com/keithlee96/pluribus-poker-ai/llms.txt Illustrates how to use the PokerEngine class to manage a full poker hand, including dealing, betting rounds, and determining the winner. Requires setting up players, a table, and a pot. ```python from poker_ai.poker.engine import PokerEngine from poker_ai.poker.table import PokerTable from poker_ai.poker.pot import Pot from poker_ai.poker.random_player import RandomPlayer from poker_ai import utils # Set seed for reproducibility utils.random.seed(42) # Configuration initial_chips = 10000 small_blind = 50 big_blind = 100 # Create the pot (shared between all players) pot = Pot() # Create players (RandomPlayer makes random legal moves) players = [ RandomPlayer( name=f'player_{i}', initial_chips=initial_chips, pot=pot ) for i in range(6) ] # Create table with players table = PokerTable(players=players, pot=pot) # Create engine to manage the game engine = PokerEngine( table=table, small_blind=small_blind, big_blind=big_blind ) # Play one complete round of poker engine.play_one_round() # Check results for player in table.players: print(f"{player.name}: {player.n_chips} chips") # Access engine properties print(f"Active players: {engine.n_active_players}") print(f"Players with moves: {engine.n_players_with_moves}") print(f"All-in players: {engine.n_all_in_players}") ``` -------------------------------- ### Apply Actions and Traverse Game States in Python Source: https://context7.com/keithlee96/pluribus-poker-ai/llms.txt Demonstrates how to apply actions to create new immutable game states, check legal actions, and traverse through possible game paths. Essential for CFR algorithms. ```python from poker_ai.games.short_deck.state import ShortDeckPokerState, new_game # Create initial game state state = new_game(n_players=3, lut_path="./card_info_lut_dir") # Check legal actions before applying print(f"Legal actions: {state.legal_actions}") # Output: ['fold', 'call', 'raise'] # Apply an action to get a new state (original state unchanged) if "call" in state.legal_actions: new_state = state.apply_action("call") # Traverse all possible actions from a state for action in state.legal_actions: next_state = state.apply_action(action) print(f"After {action}: player_i={next_state.player_i}, stage={next_state.betting_stage}") # Play through a complete game current_state = state while not current_state.is_terminal: # Get available actions for current player actions = current_state.legal_actions # Choose an action (here we just call) action = "call" if "call" in actions else actions[0] if action is not None: # None means player has folded current_state = current_state.apply_action(action) # Get final payouts when game is terminal payouts = current_state.payout print(f"Game finished! Payouts: {payouts}") # Output: {0: -150, 1: 300, 2: -150} (chips gained/lost per player) ``` -------------------------------- ### Applying Actions and Traversing Game States Source: https://context7.com/keithlee96/pluribus-poker-ai/llms.txt Demonstrates how to apply actions to game states, traverse through possible game states, and play through a complete game of poker. ```APIDOC ## Applying Actions and Traversing Game States ### Description Apply actions to create new game states. This immutable pattern is essential for CFR algorithms that need to explore multiple action branches. ### Method N/A (Python code examples) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ### Code Example ```python from poker_ai.games.short_deck.state import ShortDeckPokerState, new_game # Create initial game state state = new_game(n_players=3, lut_path="./card_info_lut_dir") # Check legal actions before applying print(f"Legal actions: {state.legal_actions}") # Apply an action to get a new state (original state unchanged) if "call" in state.legal_actions: new_state = state.apply_action("call") # Traverse all possible actions from a state for action in state.legal_actions: next_state = state.apply_action(action) print(f"After {action}: player_i={next_state.player_i}, stage={next_state.betting_stage}") # Play through a complete game current_state = state while not current_state.is_terminal: actions = current_state.legal_actions action = "call" if "call" in actions else actions[0] if action is not None: current_state = current_state.apply_action(action) # Get final payouts when game is terminal payouts = current_state.payout print(f"Game finished! Payouts: {payouts}") ``` ``` -------------------------------- ### Run Poker Plotting Script in Python Source: https://github.com/keithlee96/pluribus-poker-ai/blob/develop/applications/visualisation/README.md This Python script demonstrates how to initialize and use the `PokerPlot` class to visualize a `ShortDeckPokerState`. Ensure necessary imports are present and follow the sequence of obtaining a state and updating the plot. ```python from plot import PokerPlot from poker_ai.games.short_deck.player import ShortDeckPokerPlayer from poker_ai.games.short_deck.state import ShortDeckPokerState from poker_ai.poker.pot import Pot def get_state() -> ShortDeckPokerState: """Gets a state to visualise""" n_players = 6 pot = Pot() players = [ ShortDeckPokerPlayer(player_i=player_i, initial_chips=10000, pot=pot) for player_i in range(n_players) ] return ShortDeckPokerState( players=players, pickle_dir="../../research/blueprint_algo/" ) pp: PokerPlot = PokerPlot() # If you visit http://localhost:5000/ now you will see an empty table. # ... later on in the code, as proxy for some code that obtains a new state ... # Obtain a new state. state: ShortDeckPokerState = get_state() # Update the state to be plotted, this is sent via websockets to the frontend. pp.update_state(state) # If you visit http://localhost:5000/ now you will see table with 6 players. ``` -------------------------------- ### Manage Players and Pot in Poker Game Source: https://context7.com/keithlee96/pluribus-poker-ai/llms.txt Demonstrates creating players, adding them to a shared pot, performing betting actions (bet, call, raise, fold), and managing player states like chip counts and active status. Handles side pot creation for all-in situations. ```python from poker_ai.poker.player import Player from poker_ai.poker.pot import Pot from poker_ai.poker.card import Card pot = Pot() player1 = Player(name="Alice", initial_chips=1000, pot=pot) player2 = Player(name="Bob", initial_chips=1000, pot=pot) player1.add_private_card(Card(14, "spades")) player1.add_private_card(Card(14, "hearts")) player1.add_to_pot(100) # Bet 100 chips player2.add_to_pot(100) # Call 100 chips print(f"Pot total: {pot.total}") # 200 print(f"Player1 bet chips: {player1.n_bet_chips}") # 100 print(f"Player1 remaining: {player1.n_chips}") # 900 fold_action = player2.fold() print(f"Player2 active: {player2.is_active}") # False players = [player1, player2] call_action = player1.call(players) raise_action = player1.raise_to(n_chips=200) print(f"Is all-in: {player1.is_all_in}") # True if n_chips == 0 and active side_pots = pot.side_pots print(f"Side pots: {side_pots}") ``` -------------------------------- ### Play against the poker bot Source: https://github.com/keithlee96/pluribus-poker-ai/blob/develop/README.md Launch a game to play against a trained poker bot. The results will be saved to a YAML file. ```bash poker_ai play ``` -------------------------------- ### Information Sets for Strategy Lookup in Python Source: https://context7.com/keithlee96/pluribus-poker-ai/llms.txt Shows how to retrieve the unique information set identifier for the current player, which is used as a key for strategy lookup tables. Also demonstrates obtaining initial regret and strategy templates. ```python from poker_ai.games.short_deck.state import new_game # Create game with card info lookup tables loaded state = new_game(n_players=3, lut_path="./card_info_lut_dir") # Get the information set for the current player # This clusters similar strategic situations together info_set = state.info_set print(f"Information set: {info_set}") # Output: {"cards_cluster": 42, "history": [{"pre_flop": ["call", "raise"]}]} # Use info_set as key for strategy dictionaries strategy = { info_set: {"fold": 0.1, "call": 0.6, "raise": 0.3} } # Get initial regret/strategy templates for new info sets initial_regret = state.initial_regret # {'fold': 0, 'call': 0, 'raise': 0} initial_strategy = state.initial_strategy # {'fold': 0, 'call': 0, 'raise': 0} ``` -------------------------------- ### Create a New Game with ShortDeckPokerState in Python Source: https://context7.com/keithlee96/pluribus-poker-ai/llms.txt Demonstrates creating a new poker game state using either manual configuration or a convenience function. The `ShortDeckPokerState` class is immutable, facilitating game tree traversal. ```python from poker_ai.games.short_deck.state import ShortDeckPokerState, new_game from poker_ai.games.short_deck.player import ShortDeckPokerPlayer from poker_ai.poker.pot import Pot # Method 1: Create game manually with full control n_players = 3 pot = Pot() players = [ ShortDeckPokerPlayer(player_i=player_i, initial_chips=10000, pot=pot) for player_i in range(n_players) ] state = ShortDeckPokerState( players=players, small_blind=50, big_blind=100, lut_path="./card_info_lut_dir", # Path to clustering lookup tables load_card_lut=True ) # Method 2: Use convenience function for quick game creation state = new_game(n_players=3, lut_path="./card_info_lut_dir") # Access game state properties print(f"Current player index: {state.player_i}") print(f"Current player: {state.current_player}") print(f"Betting stage: {state.betting_stage}") # pre_flop, flop, turn, river, show_down print(f"Legal actions: {state.legal_actions}") # ['fold', 'call', 'raise'] or [None] print(f"Is terminal: {state.is_terminal}") print(f"Community cards: {state.community_cards}") print(f"Private hands: {state.private_hands}") ``` -------------------------------- ### Visualize Game State in Browser Source: https://context7.com/keithlee96/pluribus-poker-ai/llms.txt This Python code sets up a visualization server to display game states in a web browser in real-time. It's useful for debugging and demonstrations. ```python from applications.visualisation.plot import PokerPlot from poker_ai.games.short_deck.state import ShortDeckPokerState from poker_ai.games.short_deck.player import ShortDeckPokerPlayer from poker_ai.poker.pot import Pot def create_game_state() -> ShortDeckPokerState: """Create a game state for visualization.""" n_players = 6 pot = Pot() players = [ ShortDeckPokerPlayer(player_i=i, initial_chips=10000, pot=pot) for i in range(n_players) ] return ShortDeckPokerState( players=players, lut_path="./card_info_lut_dir" ) # Initialize the poker plot server pp = PokerPlot() # Server now running at http://localhost:5000/ # Create and display a game state state = create_game_state() pp.update_state(state) # Browser will show table with 6 players, cards, and pot # Update visualization as game progresses new_state = state.apply_action("call") pp.update_state(new_state) # Visualization updates via WebSocket ``` -------------------------------- ### Tag and Push Parent Docker Image Source: https://github.com/keithlee96/pluribus-poker-ai/blob/develop/README.md Tags the pokerai image with a version and pushes it to the registry. This is necessary for remote testing dependencies. Ensure the version tag is correct. ```bash docker tag pokerai pokerai/pokerai:1.0.0rc1 ``` ```bash docker push pokerai/pokerai:1.0.0rc1 ``` -------------------------------- ### Clone Repository (HTTPS) Source: https://github.com/keithlee96/pluribus-poker-ai/blob/develop/CONTRIBUTING.md Use this command to clone the repository using HTTPS. This is an alternative if SSH is not configured. ```bash git clone https://github.com/fedden/poker_ai.git ``` -------------------------------- ### Build Test Docker Image Source: https://github.com/keithlee96/pluribus-poker-ai/blob/develop/README.md Builds the test Docker image. This image is used for running the project's test suite. ```bash docker build -t pokeraitest . ``` -------------------------------- ### Build Card Information Lookup Tables Source: https://context7.com/keithlee96/pluribus-poker-ai/llms.txt Use the CardInfoLutBuilder to create abstraction buckets for grouping similar card combinations, making CFR tractable. This process can be time-consuming. ```python from poker_ai.clustering.card_info_lut_builder import CardInfoLutBuilder # Create builder with simulation parameters builder = CardInfoLutBuilder( n_simulations_river=6, # Monte Carlo samples for river EHS n_simulations_turn=6, # Samples for turn potential-aware distributions n_simulations_flop=6, # Samples for flop distributions low_card_rank=10, # Lowest card rank (10 = Ten, for short deck) high_card_rank=14, # Highest card rank (14 = Ace) save_dir="./lut_output" # Directory to save lookup tables ) # Compute all clusters (this takes significant time) builder.compute( n_river_clusters=50, # Number of river buckets n_turn_clusters=50, # Number of turn buckets n_flop_clusters=50, # Number of flop buckets ) # Access the computed lookup table card_info_lut = builder.card_info_lut print(f"Pre-flop entries: {len(card_info_lut['pre_flop'])}") print(f"Flop entries: {len(card_info_lut['flop'])}") print(f"Turn entries: {len(card_info_lut['turn'])}") print(f"River entries: {len(card_info_lut['river'])}") # Access centroids for each betting round centroids = builder.centroids print(f"River centroids shape: {centroids['river'].shape}") # Load previously computed lookup tables import joblib card_info_lut = joblib.load("./lut_output/card_info_lut.joblib") centroids = joblib.load("./lut_output/centroids.joblib") ``` -------------------------------- ### Initialize Git Flow Source: https://github.com/keithlee96/pluribus-poker-ai/blob/develop/CONTRIBUTING.md Initialize Git Flow in the repository. Follow the prompts to configure branch names for production releases and next release integration. ```bash git flow init ``` -------------------------------- ### Initialize dat.GUI Controls for DAG Orientation Source: https://github.com/keithlee96/pluribus-poker-ai/blob/develop/applications/strategy_dag_visualisation/index.html Sets up a dat.GUI control to dynamically change the DAG orientation of the ForceGraph3D. The 'DAG Orientation' control accepts various orientation values and updates the graph accordingly. ```javascript const controls = { 'DAG Orientation': 'td'}; const gui = new dat.GUI(); gui.add(controls, 'DAG Orientation', ['td', 'bu', 'lr', 'rl', 'zout', 'zin', 'radialout', 'radialin', null]) .onChange(orientation => graph && graph.dagMode(orientation)); ``` -------------------------------- ### Build Parent Docker Image Source: https://github.com/keithlee96/pluribus-poker-ai/blob/develop/README.md Builds the parent Docker image with all dependencies. Ensure the LUT_DIR argument points to the correct location of pickled card information lookup tables. ```bash docker build --build-arg LUT_DIR=research/blueprint_algo -f ParentDockerfile -t pokerai . ``` -------------------------------- ### Clone Repository (SSH) Source: https://github.com/keithlee96/pluribus-poker-ai/blob/develop/CONTRIBUTING.md Use this command to clone the repository using SSH, which is recommended for authenticated access. ```bash git clone git@github.com:fedden/poker_ai.git ``` -------------------------------- ### Run Terminal Poker Application Source: https://github.com/keithlee96/pluribus-poker-ai/blob/develop/README.md Launches the poker AI application from the terminal. Requires specifying the agent type, pickle directory, and strategy path. Ensure you are in the root directory of the poker_ai project. ```bash cd /path/to/poker_ai/dir python -m poker_ai.terminal.runner \ --agent offline \ --pickle_dir ./research/blueprint_algo \ --strategy_path ./research/blueprint_algo/offline_strategy_285800.gz ``` -------------------------------- ### Run poker_ai cluster command Source: https://github.com/keithlee96/pluribus-poker-ai/blob/develop/README.md Execute the 'cluster' command to generate lookup tables for public information in poker. This process compresses game states for tractability. ```bash poker_ai cluster ``` -------------------------------- ### Serializing Agents with Joblib Source: https://context7.com/keithlee96/pluribus-poker-ai/llms.txt Use joblib to serialize trained poker AI agents for later deployment or loading. This is a common pattern for saving and loading agent models. ```python joblib.dump(agent, 'agent.joblib') ``` -------------------------------- ### Accessing Agent Strategy Source: https://context7.com/keithlee96/pluribus-poker-ai/llms.txt Lookup the strategy for a given information set from a trained agent. Ensure the agent is loaded and the state object is correctly initialized. ```python agent.strategy[state.info_set] ``` -------------------------------- ### Add and Commit Changes Source: https://github.com/keithlee96/pluribus-poker-ai/blob/develop/CONTRIBUTING.md Stage all changes and commit them with a descriptive message. This is a standard Git workflow for saving progress. ```bash git add . git commit -m 'commit message here' ``` -------------------------------- ### Configure ForceGraph3D Instance Source: https://github.com/keithlee96/pluribus-poker-ai/blob/develop/applications/strategy_dag_visualisation/index.html Initializes and configures a ForceGraph3D instance with specific visual and physical properties. This includes setting the DAG mode, level distance, background color, link properties, node size, and forces like collision and charge. ```javascript const NODE_REL_SIZE = 1; const graph = ForceGraph3D() .dagMode('td') .dagLevelDistance(200) .backgroundColor('#101020') .linkColor(() => 'rgba(255,255,255,0.2)') .nodeRelSize(NODE_REL_SIZE) .nodeId('path') .nodeVal('size') .nodeLabel('path') .nodeAutoColorBy('module') .nodeOpacity(0.9) .linkDirectionalParticles(2) .linkDirectionalParticleWidth(0.8) .linkDirectionalParticleSpeed(0.006) .d3Force('collision', d3.forceCollide(node => Math.cbrt(node.size) * NODE_REL_SIZE)); // Decrease repel intensity graph.d3Force('charge').strength(-15); ``` -------------------------------- ### Using ShortDeckPokerState for Simulation Source: https://context7.com/keithlee96/pluribus-poker-ai/llms.txt Instantiate `ShortDeckPokerState` to simulate games or represent game states. This is useful for game simulation and tree traversal within the AI framework. ```python ShortDeckPokerState(deck, history, cards, next_player) ``` -------------------------------- ### Play Against a Trained Bot with Pluribus Poker AI Source: https://context7.com/keithlee96/pluribus-poker-ai/llms.txt Launches an interactive terminal application to play Short Deck poker against a trained AI agent. Can run directly from the Python module. ```bash poker_ai play \ --lut_path ./research/blueprint_algo \ --agent offline \ --strategy_path ./agent.joblib ``` ```python python -m poker_ai.terminal.runner \ --lut_path ./research/blueprint_algo \ --agent offline \ --strategy_path ./research/blueprint_algo/offline_strategy_285800.gz \ --no_debug_quick_start ``` -------------------------------- ### Working with Cards and Hand Evaluation Source: https://context7.com/keithlee96/pluribus-poker-ai/llms.txt Covers the `Card` class for representing poker cards and the `Evaluator` class for ranking poker hands. ```APIDOC ## Working with Cards and Hand Evaluation ### Description The `Card` class represents poker cards, and the `Evaluator` class ranks poker hands using an optimized variant of Cactus Kev's algorithm. ### Method N/A (Python code examples) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ### Code Example ```python from poker_ai.poker.card import Card from poker_ai.poker.evaluation.evaluator import Evaluator ace_spades = Card(rank=14, suit="spades") king_hearts = Card(rank="king", suit="hearts") ten_diamonds = Card(rank=10, suit="diamonds") print(ace_spades) print(f"Rank: {ace_spades.rank}") print(f"Rank int: {ace_spades.rank_int}") print(f"Suit: {ace_spades.suit}") print(ace_spades > king_hearts) evaluator = Evaluator() board = [ Card(14, "hearts").eval_card, Card(13, "hearts").eval_card, Card(12, "hearts").eval_card, Card(11, "hearts").eval_card, Card(2, "clubs").eval_card, ] hand = [ Card(10, "hearts").eval_card, Card(9, "spades").eval_card, ] ``` ``` -------------------------------- ### Cluster Card Information Sets with Pluribus Poker AI Source: https://context7.com/keithlee96/pluribus-poker-ai/llms.txt Preprocesses card information by grouping similar combinations into lookup tables. This is essential before training AI agents to reduce the complexity of game states. ```bash poker_ai cluster ``` ```bash poker_ai cluster \ --low_card_rank 10 \ --high_card_rank 14 \ --n_river_clusters 50 \ --n_turn_clusters 50 \ --n_flop_clusters 50 \ --n_simulations_river 6 \ --n_simulations_turn 6 \ --n_simulations_flop 6 \ --save_dir ./my_lut_dir ``` -------------------------------- ### Train a Poker AI Agent with Pluribus Poker AI Source: https://context7.com/keithlee96/pluribus-poker-ai/llms.txt Trains an AI agent using Monte Carlo Counterfactual Regret Minimization (MCCFR) through iterative self-play. Supports custom configurations and resuming previous training sessions. ```bash poker_ai train start ``` ```bash poker_ai train start \ --n_iterations 1500 \ --n_players 3 \ --strategy_interval 20 \ --lcfr_threshold 400 \ --discount_interval 400 \ --prune_threshold 400 \ --c -20000 \ --dump_iteration 20 \ --update_threshold 400 \ --lut_path ./card_info_lut_dir \ --multi_process \ --nickname my_training_run ``` ```bash poker_ai train resume --server_config_path ./path/to/server.gz ``` -------------------------------- ### State-Based Poker Traversal Source: https://github.com/keithlee96/pluribus-poker-ai/blob/develop/README.md Initializes a poker game state and iterates through legal actions, applying each action to create a new game state. This is core to MCCFR algorithm implementation. ```python pot = Pot() players = [ ShortDeckPokerPlayer(player_i=player_i, initial_chips=10000, pot=pot) for player_i in range(n_players) ] state = ShortDeckPokerState(players=players) for action in state.legal_actions: new_state: ShortDeckPokerState = state.apply_action(action) ``` -------------------------------- ### Poker Engine API Source: https://context7.com/keithlee96/pluribus-poker-ai/llms.txt Details on using the `PokerEngine` to manage and run a complete poker hand, from dealing to winner computation. ```APIDOC ## Running a Complete Poker Round with PokerEngine ### Description The `PokerEngine` class manages the lifecycle of a complete poker hand, handling dealing, betting rounds, and winner computation. ### Method N/A (Python code examples) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ### Code Example ```python from poker_ai.poker.engine import PokerEngine from poker_ai.poker.table import PokerTable from poker_ai.poker.pot import Pot from poker_ai.poker.random_player import RandomPlayer from poker_ai import utils utils.random.seed(42) initial_chips = 10000 small_blind = 50 big_blind = 100 pot = Pot() players = [ RandomPlayer(name=f'player_{i}', initial_chips=initial_chips, pot=pot) for i in range(6) ] table = PokerTable(players=players, pot=pot) engine = PokerEngine( table=table, small_blind=small_blind, big_blind=big_blind ) engine.play_one_round() for player in table.players: print(f"{player.name}: {player.n_chips} chips") print(f"Active players: {engine.n_active_players}") print(f"Players with moves: {engine.n_players_with_moves}") print(f"All-in players: {engine.n_all_in_players}") ``` ``` -------------------------------- ### Run Tests with Docker Source: https://github.com/keithlee96/pluribus-poker-ai/blob/develop/README.md Executes the pytest test suite within the pokeraitest Docker container. The -it flags ensure interactive mode. ```bash docker run -it pokeraitest pytest ``` -------------------------------- ### Run CFR Algorithm for AI Training Source: https://context7.com/keithlee96/pluribus-poker-ai/llms.txt Initiates a single iteration of the Counterfactual Regret (CFR) algorithm for a specified player and game state. Supports standard CFR and CFR with pruning for performance optimization. Requires an Agent object to store learned strategies and regrets. ```python from poker_ai.ai.ai import cfr, cfrp, calculate_strategy, update_strategy from poker_ai.ai.agent import Agent from poker_ai.games.short_deck.state import new_game agent = Agent() state = new_game(n_players=3, lut_path="./card_info_lut_dir") player_i = 0 iteration = 1 expected_value = cfr( agent=agent, state=state, i=player_i, t=iteration, locks={} ) print(f"Expected value for player {player_i}: {expected_value}") pruning_threshold = -20000 ev_pruned = cfrp( agent=agent, state=state, i=player_i, t=iteration, c=pruning_threshold, locks={} ) info_set = state.info_set regret = agent.regret.get(info_set, state.initial_regret) strategy = calculate_strategy(regret) print(f"Strategy: {strategy}") update_strategy(agent, state, player_i, iteration, locks={}) print(f"Number of info sets with regret: {len(agent.regret)}") print(f"Number of info sets with strategy: {len(agent.strategy)}") ``` -------------------------------- ### Play Deterministic Poker Round Source: https://github.com/keithlee96/pluribus-poker-ai/blob/develop/README.md Sets up and plays a single round of Texas Hold'em Poker using a deterministic engine. This is useful for testing and development of AI algorithms. ```python from poker_ai import utils from poker_ai.ai.dummy import RandomPlayer from poker_ai.poker.table import PokerTable from poker_ai.poker.engine import PokerEngine from poker_ai.poker.pot import Pot # Seed so things are deterministic. utils.random.seed(42) # Some settings for the amount of chips. initial_chips_amount = 10000 small_blind_amount = 50 big_blind_amount = 100 # Create the pot. pot = Pot() # Instanciate six players that will make random moves, make sure # they can reference the pot so they can add chips to it. players = [ RandomPlayer( name=f'player {player_i}', initial_chips=initial_chips_amount, pot=pot) for player_i in range(6) ] # Create the table with the players on it. table = PokerTable(players=players, pot=pot) # Create the engine that will manage the poker game lifecycle. engine = PokerEngine( table=table, small_blind=small_blind_amount, big_blind=big_blind_amount) # Play a round of Texas Hold'em Poker! engine.play_one_round() ``` -------------------------------- ### Visualize Short Deck Poker State Source: https://github.com/keithlee96/pluribus-poker-ai/blob/develop/README.md Initializes and updates a PokerPlot object to visualize the current state of a Short Deck Poker game. This is useful for debugging and observing AI behavior in real-time. ```python from plot import PokerPlot from poker_ai.games.short_deck.player import ShortDeckPokerPlayer from poker_ai.games.short_deck.state import ShortDeckPokerState from poker_ai.poker.pot import Pot def get_state() -> ShortDeckPokerState: """Gets a state to visualise""" n_players = 6 pot = Pot() players = [ ShortDeckPokerPlayer(player_i=player_i, initial_chips=10000, pot=pot) for player_i in range(n_players) ] return ShortDeckPokerState( players=players, pickle_dir="../../research/blueprint_algo/" ) pp: PokerPlot = PokerPlot() # If you visit http://localhost:5000/ now you will see an empty table. # ... later on in the code, as proxy for some code that obtains a new state ... # Obtain a new state. state: ShortDeckPokerState = get_state() # Update the state to be plotted, this is sent via websockets to the frontend. pp.update_state(state) # http://localhost:5000/ will now display a table with 6 players. ``` -------------------------------- ### Load and Process CSV Data for Graph Source: https://github.com/keithlee96/pluribus-poker-ai/blob/develop/applications/strategy_dag_visualisation/index.html Fetches data from a CSV file, parses it, and transforms it into nodes and links for the ForceGraph3D. It filters data based on level and constructs the graph structure, then initializes the graph with the processed data. ```javascript fetch('./dataset.csv') .then(r => r.text()) .then(d3.csvParse) .then(data => { const nodes = [], links = []; data.forEach(({ size, path }) => { const levels = path.split('/'), level = levels.length - 1, module = level > 0 ? levels[1] : null, leaf = levels.pop(), parent = levels.join('/'); if (level < 3) { const node = { path, leaf, module, size: +size || 20, level }; nodes.push(node); if (parent) { console.log({source: parent, target: path, targetNode: node}) links.push({source: parent, target: path, targetNode: node}); } } }); graph(document.getElementById('graph')) .graphData({ nodes, links }); }); ``` -------------------------------- ### Fetch Latest Changes Source: https://github.com/keithlee96/pluribus-poker-ai/blob/develop/CONTRIBUTING.md Fetch the latest changes from all remote branches and prune any branches that have been deleted remotely. This ensures your local repository is up-to-date. ```bash git fetch origin -p ``` -------------------------------- ### Rebase Feature Branch onto Develop Source: https://github.com/keithlee96/pluribus-poker-ai/blob/develop/CONTRIBUTING.md Integrate the latest changes from the 'develop' branch into your current feature branch. This helps resolve conflicts early and keeps your feature branch up-to-date. ```bash git rebase develop feature/my-feature-branch-name-here ``` -------------------------------- ### Rebase Local Develop Branch Source: https://github.com/keithlee96/pluribus-poker-ai/blob/develop/CONTRIBUTING.md Update your local 'develop' branch to match the latest changes from the remote 'develop' branch. This is crucial before rebasing your feature branch. ```bash git rebase origin/develop develop ``` -------------------------------- ### Force Push Feature Branch Source: https://github.com/keithlee96/pluribus-poker-ai/blob/develop/CONTRIBUTING.md Force push your feature branch to the remote repository after rebasing. Use with caution, as this overwrites the remote history. Only use on branches solely worked on by you. ```bash git push origin feature/my-feature-branch-name-here --force ``` -------------------------------- ### Push Feature Branch Source: https://github.com/keithlee96/pluribus-poker-ai/blob/develop/CONTRIBUTING.md Push the newly created feature branch to the remote repository. This makes your branch available for collaboration and pull requests. ```bash git push origin feature/my-feature-branch-name-here ``` -------------------------------- ### Evaluate Poker Hand Rank Source: https://context7.com/keithlee96/pluribus-poker-ai/llms.txt Evaluates a given poker hand against a board to determine its rank. Lower ranks indicate better hands, with 1 being a Royal Flush. Also provides human-readable hand class and percentile ranking. ```python rank = evaluator.evaluate(board, hand) print(f"Hand rank: {rank}") # 1 (Royal Flush!) rank_class = evaluator.get_rank_class(rank) hand_name = evaluator.class_to_string(rank_class) print(f"Hand: {hand_name}") # "Straight Flush" percentile = evaluator.get_five_card_rank_percentage(rank) print(f"Percentile: {percentile:.4f}") # 0.0001 (top 0.01%) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.