### Install Nashpy from Source Source: https://github.com/drvinceknight/nashpy/blob/main/docs/how-to/install-nashpy.md Follow these steps to clone the Nashpy repository and install a development version from source. Ensure you have git and flit installed. ```bash git clone https://github.com/drvinceknight/Nashpy.git ``` ```bash cd nashpy ``` ```bash python -m pip install flit ``` ```bash python -m flit install --symlink ``` -------------------------------- ### Install Nashpy from Source Source: https://github.com/drvinceknight/nashpy/blob/main/docs/contributing/how-to/how-to-install-the-library-from-source/index.md Use this command to install the Nashpy library from its source files. Ensure flit is installed first. ```bash python -m pip install flit python -m flit install ``` -------------------------------- ### Install and Symlink Nashpy for Documentation Build Source: https://github.com/drvinceknight/nashpy/blob/main/README.md Install Nashpy using flit and enable symlinking for the documentation build process. ```bash python -m pip install flit python -m flit install --symlink ``` -------------------------------- ### Install tox Source: https://github.com/drvinceknight/nashpy/blob/main/docs/contributing/how-to/how-to-run-benchmarks/index.md Install the tox package using pip. This is a prerequisite for running benchmarks. ```bash python -m pip install tox ``` -------------------------------- ### Install alex globally Source: https://github.com/drvinceknight/nashpy/blob/main/docs/contributing/how-to/how-to-check-for-insensitive-language/index.md Installs the 'alex' tool globally using npm. Ensure Node.js is installed beforehand. ```bash $ npm install alex --global ``` -------------------------------- ### Activate Virtual Environment and Install Tox Source: https://github.com/drvinceknight/nashpy/blob/main/README.md Activate the created virtual environment and install the tox testing tool. ```bash source env/bin/activate python -m pip install tox ``` -------------------------------- ### Initialize a Nashpy Game Source: https://github.com/drvinceknight/nashpy/blob/main/docs/how-to/use-moran-process-on-replacement-graph.md Setup a basic game instance using a payoff matrix. ```python >>> import nashpy as nash >>> import numpy as np >>> A = np.array([[3, 1], [1, 2]]) >>> game = nash.Game(A) ``` -------------------------------- ### Install and Run Mypy for Type Checking Source: https://github.com/drvinceknight/nashpy/blob/main/docs/contributing/how-to/how-to-write-a-typehint/index.md Provides commands to install Mypy and run it to check type annotations in a Python file. Ensure you have the necessary dependencies installed. ```default $ python -m pip install mypy $ python -m mypy --ignore-missing-imports ``` -------------------------------- ### Install Nashpy on Fedora Source: https://github.com/drvinceknight/nashpy/blob/main/README.md Install the Nashpy library on Fedora systems using the dnf package manager. ```bash dnf install python3-nashpy ``` -------------------------------- ### Install mdformat Source: https://github.com/drvinceknight/nashpy/blob/main/docs/contributing/how-to/how-to-format-markdown-files/index.md Use pip to install the mdformat package. ```default $ python -m pip install mdformat ``` -------------------------------- ### Initialize a Game for Replicator Dynamics Source: https://github.com/drvinceknight/nashpy/blob/main/docs/how-to/use-discrete_replicator_dynamics.md Setup the game environment by importing necessary libraries and defining the payoff matrix. ```python >>> import nashpy as nash >>> import numpy as np >>> A = np.array([[3, 2], [4, 1]]) >>> game = nash.Game(A) ``` -------------------------------- ### Install Mypy Source: https://github.com/drvinceknight/nashpy/blob/main/docs/contributing/discussion/mypy/index.md Command to install the Mypy static analysis tool via pip. ```default $ python -m pip install mypy ``` -------------------------------- ### Initialize Moran process Source: https://context7.com/drvinceknight/nashpy/llms.txt Setup for the Moran process, which requires positive payoffs in the game matrix. ```python import nashpy as nash import numpy as np # Coordination game with positive payoffs (required for Moran process) A = np.array([[3, 1], [1, 2]]) game = nash.Game(A) # Initial population: indices represent strategy types ``` -------------------------------- ### Install Editable Nashpy from Source Source: https://github.com/drvinceknight/nashpy/blob/main/docs/contributing/how-to/how-to-install-the-library-from-source/index.md Install Nashpy from source with the --symlink option for direct use of source file modifications. ```bash python -m flit install --symlink ``` -------------------------------- ### Initialize Game for Replicator Dynamics Source: https://github.com/drvinceknight/nashpy/blob/main/docs/how-to/use-replicator-dynamics.md Import nashpy and numpy, then create a Game object from a numpy array representing the payoff matrix. This is the initial setup for using replicator dynamics. ```python import nashpy as nash import numpy as np A = np.array([[3, 2], [4, 2]]) game = nash.Game(A) ``` -------------------------------- ### Install Nashpy using pip Source: https://github.com/drvinceknight/nashpy/blob/main/README.md Install the Nashpy library using pip for Python package management. ```bash python -m pip install nashpy ``` -------------------------------- ### Configure Read The Docs with .readthedocs.yml Source: https://github.com/drvinceknight/nashpy/blob/main/docs/contributing/discussion/readthedocs/index.md Defines the Python version and installation method for the documentation build environment. ```default python: version: 3.8 install: - method: pip path: . extra_requirements: - doc ``` -------------------------------- ### Install darglint Source: https://github.com/drvinceknight/nashpy/blob/main/docs/contributing/discussion/darglint/index.md Command to install darglint using pip. ```bash $ python -m pip install darglint ``` -------------------------------- ### Run Replicator Dynamics with Custom Start and Timepoints Source: https://github.com/drvinceknight/nashpy/blob/main/docs/how-to/use-replicator-dynamics.md Specify a custom initial strategy (y0) and a sequence of timepoints for the simulation. This allows for more control over the dynamics' starting conditions and duration. ```python y0 = np.array([0.9, 0.1]) timepoints = np.linspace(0, 10, 1000) game.replicator_dynamics(y0=y0, timepoints=timepoints) ``` -------------------------------- ### Stochastic Fictitious Play with Initial Play Counts Source: https://github.com/drvinceknight/nashpy/blob/main/docs/how-to/use-stochastic-fictitious-play.md Initialize the stochastic fictitious play algorithm with a starting point by providing initial play counts. This allows the algorithm to begin from a specific state rather than starting from scratch. ```python np.random.seed(0) play_counts = (np.array([0., 500.]), np.array([0., 500.])) play_counts_and_distributions = game.stochastic_fictitious_play(iterations=iterations, play_counts=play_counts) for play_counts, distributions in play_counts_and_distributions: row_play_counts, column_play_counts = play_counts row_distributions, column_distributions = distributions print(row_play_counts, column_play_counts) ... ``` -------------------------------- ### Example commit message Source: https://github.com/drvinceknight/nashpy/blob/main/docs/contributing/tutorial/index.md A template for the commit title and body when adding a contributor. ```default Add to list of contributors I am doing the contribution tutorial. ``` -------------------------------- ### Run Stochastic Fictitious Play (Convergent Example) Source: https://github.com/drvinceknight/nashpy/blob/main/docs/text-book/stochastic-fictitious-play.md Illustrates the stochastic fictitious play algorithm with tuned 'etha' and 'epsilon_bar' parameters, leading to convergence. Requires numpy, nashpy, and matplotlib. The output includes play counts and probability distributions. ```python A = np.array([[1 / 2, 1, 0], [0, 1 / 2, 1], [1, 0, 1 / 2]]) B = np.array([[1 / 2, 0, 1], [1, 1 / 2, 0], [0, 1, 1 / 2]]) game = nash.Game(A, B) iterations = 10000 etha = 0.1 epsilon_bar = 10**-1 np.random.seed(0) play_counts_and_distribuions = tuple(game.stochastic_fictitious_play(iterations=iterations, etha=etha, epsilon_bar=epsilon_bar)) play_counts_and_distribuions[-1] ``` ```python import matplotlib.pyplot as plt plt.figure() probabilities = [ row_play_counts / np.sum(row_play_counts) if np.sum(row_play_counts) != 0 else row_play_counts + 1 / len(row_play_counts) for (row_play_counts, col_play_counts), _ in play_counts_and_distribuions] for number, strategy in enumerate(zip(*probabilities)): plt.plot(strategy, label=f"$s_{number}$") plt.xlabel("Iteration") plt.ylabel("Probability") plt.title("Actions taken by row player") plt.legend() ``` -------------------------------- ### Asymmetric Replicator Dynamics: Steady State Example Source: https://github.com/drvinceknight/nashpy/blob/main/docs/text-book/asymmetric-replicator-dynamics.md Simulates asymmetric replicator dynamics for a game that converges to a stable steady state. Requires matplotlib, nashpy, and numpy. Initial strategy distributions for both players are provided. ```default >>> import matplotlib.pyplot as plt >>> import nashpy as nash >>> import numpy as np >>> A = np.array([[2, 2], [3, 4]]) >>> B = np.array([[4, 3], [3, 2]]) >>> game = nash.Game(A, B) >>> x0 = np.array([0.9, 0.1]) >>> y0 = np.array([0.3, 0.7]) >>> xs, ys = game.asymmetric_replicator_dynamics(x0=x0, y0=y0) ``` ```pycon >>> plt.figure(figsize=(15, 5)) >>> plt.subplot(1, 2, 1) >>> plt.plot(xs) >>> plt.title("Probability distribution of strategies over time for row player") >>> plt.legend([f"$s_{0}$", f"$s_{1}$"]) >>> plt.subplot(1, 2, 2) >>> plt.plot(ys) >>> plt.xlabel("Timepoints") >>> plt.ylabel("Probability") >>> plt.title("Probability distribution of strategies over time for column player") >>> plt.legend([f"$s_{0}$", f"$s_{1}$"]) ``` -------------------------------- ### Fictitious Play with Initial Play Counts Source: https://github.com/drvinceknight/nashpy/blob/main/docs/how-to/use-fictitious-play.md Initialize the Fictitious Play algorithm with a starting point by providing initial play counts. This allows for analysis from a specific state. ```python np.random.seed(1) play_counts = (np.array([0., 500.]), np.array([0., 500.])) play_counts = game.fictitious_play(iterations=iterations, play_counts=play_counts) for row_play_counts, column_play_counts in play_counts: print(row_play_counts, column_play_counts) ``` -------------------------------- ### Asymmetric Replicator Dynamics: Non-Convergence Example Source: https://github.com/drvinceknight/nashpy/blob/main/docs/text-book/asymmetric-replicator-dynamics.md Simulates asymmetric replicator dynamics for a game that does not converge to a steady state. Requires matplotlib, nashpy, and numpy. Initial strategy distributions for both players are provided. ```default >>> import matplotlib.pyplot as plt >>> import nashpy as nash >>> import numpy as np >>> A = np.array([[0, -1, 1], [1, 0, -1], [-1, 1, 0]]) >>> B = A.transpose() >>> game = nash.Game(A, B) >>> x0 = np.array([0.3, 0.35, 0.35]) >>> y0 = np.array([0.3, 0.35, 0.35]) >>> xs, ys = game.asymmetric_replicator_dynamics(x0=x0, y0=y0) ``` ```pycon >>> plt.figure(figsize=(15, 5)) >>> plt.subplot(1, 2, 1) >>> plt.plot(xs) >>> plt.title("Probability distribution of strategies over time for row player") >>> plt.legend([f"$s_{0}$", f"$s_{1}$", f"$s_{2}$"]) >>> plt.subplot(1, 2, 2) >>> plt.plot(ys) >>> plt.xlabel("Timepoints") >>> plt.ylabel("Probability") >>> plt.title("Probability distribution of strategies over time for column player") >>> plt.legend([f"$s_{0}$", f"$s_{1}$", f"$s_{2}$"]) ``` -------------------------------- ### Run Stochastic Fictitious Play (Divergent Example) Source: https://github.com/drvinceknight/nashpy/blob/main/docs/text-book/stochastic-fictitious-play.md Demonstrates the stochastic fictitious play algorithm with default parameters, which may lead to a lack of convergence. Requires numpy and nashpy. The output shows play counts for each player. ```python import numpy as np import nashpy as nash A = np.array([[0, 1, 0], [0, 0, 1], [1, 0, 0]]) B = np.array([[0, 0, 1], [1, 0, 0], [0, 1, 0]]) game = nash.Game(A, B) iterations = 10000 np.random.seed(0) play_counts_and_distribuions = tuple(game.stochastic_fictitious_play(iterations=iterations)) play_counts, distributions = play_counts_and_distribuions[-1] print(play_counts) ``` ```python import matplotlib.pyplot as plt plt.figure() probabilities = [ row_play_counts / np.sum(row_play_counts) if np.sum(row_play_counts) != 0 else row_play_counts + 1 / len(row_play_counts) for (row_play_counts, col_play_counts), _ in play_counts_and_distribuions] for number, strategy in enumerate(zip(*probabilities)): plt.plot(strategy, label=f"$s_{number}$") plt.xlabel("Iteration") plt.ylabel("Probability") plt.title("Actions taken by row player") plt.legend() ``` -------------------------------- ### Annotated Function with Type Hints Source: https://github.com/drvinceknight/nashpy/blob/main/docs/contributing/how-to/how-to-write-a-typehint/index.md Shows an example of a Python function with type hints for its parameters and return value, using NumPy arrays. ```default import numpy as np import numpy.typing as npt def make_tableau(M: npt.NDArray) -> npt.NDArray: """ Make a tableau for the given matrix M. This tableau corresponds to the polytope of the form: Mx <= 1 and x >= 0 Parameters ---------- M : array A matrix with linear coefficients defining the polytope. Returns ------- array The tableau that corresponds to the polytope. """ return np.append( np.append(M, np.eye(M.shape[0]), axis=1), np.ones((M.shape[0], 1)), axis=1, ) ``` -------------------------------- ### Alex CLI output with warnings Source: https://github.com/drvinceknight/nashpy/blob/main/docs/contributing/discussion/alex/index.md This is an example of the output generated by the alex CLI when it detects potentially insensitive language. It specifies the file, line number, warning type, and suggested correction. ```text $ alex main.md main.md 3:1-3:3 warning `He` may be insensitive, use `They`, `It` instead he-she retext-equality ⚠ 1 warning ``` -------------------------------- ### Build Documentation Source: https://github.com/drvinceknight/nashpy/blob/main/README.md Navigate to the docs directory and build the HTML documentation. ```bash cd docs make html ``` -------------------------------- ### darglint Google style errors Source: https://github.com/drvinceknight/nashpy/blob/main/docs/contributing/discussion/darglint/index.md Example output from darglint when checking a file against the Google style guide, indicating missing parameter and return descriptions. ```text main.py:get_mean:1: DAR101: - collection main.py:get_mean:1: DAR201: - return ``` -------------------------------- ### Initialize Game Matrix Source: https://github.com/drvinceknight/nashpy/blob/main/docs/how-to/use-fictitious-play.md Set up the game matrices A and B using NumPy arrays for use with Nashpy. ```python import nashpy as nash import numpy as np A = np.array([[3, 1], [0, 2]]) B = np.array([[2, 0], [1, 3]]) game = nash.Game(A, B) ``` -------------------------------- ### Create and Analyze a Game with Nashpy Source: https://github.com/drvinceknight/nashpy/blob/main/README.md Demonstrates creating a 2-player game using payoff matrices and finding equilibria using support enumeration. Requires importing the nashpy library. ```python import nashpy as nash A = [[1, 2], [3, 0]] B = [[0, 2], [3, 1]] game = nash.Game(A, B) for eq in game.support_enumeration(): print(eq) game[[0, 1], [1, 0]] ``` -------------------------------- ### Build Documentation with Sphinx Source: https://github.com/drvinceknight/nashpy/blob/main/docs/contributing/tutorial/index.md Navigate to the 'docs' directory and build the HTML documentation using Sphinx. This command generates the documentation in the `_build/html` directory. ```bash cd docs sphinx-build -b html . _build/html Running Sphinx v3.1.2 loading pickled environment... done building [mo]: targets for 0 po files that are out of date building [html]: targets for 2 source files that are out of date updating environment: 1 added, 2 changed, 1 removed reading sources... [100%] contributing/tutorial/index looking for now-outdated files... none found pickling environment... done checking consistency... done preparing documents... done writing output... [100%] index generating indices... genindex py-modindexdone highlighting module code... [100%] nashpy.learning.fictitious_play writing additional pages... searchdone copying images... [100%] _static/contributing/tutorial/cloning/main.png copying static files... ... done copying extra files... done dumping search index in English (code: en)... done dumping object inventory... done build succeeded. The HTML pages are in _build/html. ``` -------------------------------- ### Run all tests Source: https://github.com/drvinceknight/nashpy/blob/main/docs/contributing/how-to/how-to-run-tests/index.md Execute the full test suite using the default tox configuration. ```bash $ python -m tox ``` -------------------------------- ### Run all benchmarks Source: https://github.com/drvinceknight/nashpy/blob/main/docs/contributing/how-to/how-to-run-benchmarks/index.md Execute all defined benchmarks using tox. This command initiates the benchmark suite. ```bash python -m tox benchmark ``` -------------------------------- ### Initialize a Game for Support Enumeration Source: https://github.com/drvinceknight/nashpy/blob/main/docs/how-to/solve-with-support-enumeration.md Create a Nashpy Game instance using a payoff matrix. ```python >>> import nashpy as nash >>> import numpy as np >>> A = np.array([[1, -1], [-1, 1]]) >>> matching_pennies = nash.Game(A) ``` -------------------------------- ### Clone Repository and Create Virtual Environment Source: https://github.com/drvinceknight/nashpy/blob/main/README.md Clone the Nashpy repository and set up a Python virtual environment for development. ```bash git clone https://github.com/drvinceknight/nashpy.git cd nashpy python -m venv env ``` -------------------------------- ### GET /nashpy/game/fictitious_play Source: https://github.com/drvinceknight/nashpy/blob/main/docs/discussion/source/nashpy.md Executes the fictitious play algorithm to return a sequence of actions. ```APIDOC ## GET /nashpy/game/fictitious_play ### Description Return a given sequence of actions through fictitious play based on player beliefs and best responses. ### Parameters #### Query Parameters - **iterations** (int) - Required - The number of iterations of the algorithm. - **play_counts** (array) - Optional - The play counts. ### Response #### Success Response (200) - **result** (Generator) - The play counts. ``` -------------------------------- ### GET /nashpy/game/discrete_replicator_dynamics Source: https://github.com/drvinceknight/nashpy/blob/main/docs/discussion/source/nashpy.md Calculates the probability of each strategy being played over discrete time steps. ```APIDOC ## GET /nashpy/game/discrete_replicator_dynamics ### Description Returns an array containing the probability of each strategy being played over discrete time steps. Or if quantized, an array containing the number of players using each strategy over discrete time steps. ### Parameters #### Query Parameters - **initial_population** (array) - Required - The initial population distribution, or exact numbers for players of each strategy. - **steps** (int) - Optional - How many generations to run the step function. - **quantize** (bool) - Optional - Whether or not to use greenwoods algorithm to quantize the result. - **step_function** (func) - Optional - Determines which step function to be used. ### Response #### Success Response (200) - **result** (array) - The population distribution at distinct timepoints. ``` -------------------------------- ### Create and Analyze Games with Nashpy Source: https://context7.com/drvinceknight/nashpy/llms.txt Demonstrates initializing zero-sum and bi-matrix games using the Game class and calculating utilities for specific strategy profiles. ```python import nashpy as nash import numpy as np # Create a zero-sum game (e.g., Rock-Paper-Scissors) # Row player's payoff matrix only; column player gets -A rps_matrix = np.array([[0, -1, 1], [1, 0, -1], [-1, 1, 0]]) zero_sum_game = nash.Game(rps_matrix) print(zero_sum_game) # Output: # Zero sum game with payoff matrices: # Row player: # [[ 0 -1 1] # [ 1 0 -1] # [-1 1 0]] # Column player: # [[ 0 1 -1] # [-1 0 1] # [ 1 -1 0]] # Create a bi-matrix (non-zero-sum) game - Prisoner's Dilemma A = np.array([[3, 0], [5, 1]]) # Row player payoffs B = np.array([[3, 5], [0, 1]]) # Column player payoffs prisoners_dilemma = nash.Game(A, B) print(prisoners_dilemma) # Output: # Bi matrix game with payoff matrices: # Row player: # [[3 0] # [5 1]] # Column player: # [[3 5] # [0 1]] # Calculate utilities for given strategies # Strategies: row player plays [0.5, 0.5], column player plays [0.5, 0.5] sigma_r = np.array([0.5, 0.5]) sigma_c = np.array([0.5, 0.5]) utilities = prisoners_dilemma[sigma_r, sigma_c] print(f"Utilities: Row={utilities[0]:.2f}, Column={utilities[1]:.2f}") # Output: Utilities: Row=2.25, Column=2.25 ``` -------------------------------- ### Python function with docstring Source: https://github.com/drvinceknight/nashpy/blob/main/docs/contributing/discussion/darglint/index.md Example Python function with a docstring formatted in Numpy style. ```python def get_mean(collection): """ Obtain the average of a collection of objects. Parameters ---------- collection : list A list of numbers Returns ------- float The mean of the numbers. """ return sum(collection) / len(collection) ``` -------------------------------- ### lemke_howson_enumeration Source: https://github.com/drvinceknight/nashpy/blob/main/docs/discussion/source/nashpy.md Enumerates Nash equilibria by running the Lemke-Howson algorithm for all possible starting dropped labels. ```APIDOC ## lemke_howson_enumeration ### Description Obtain Nash equilibria for all possible starting dropped labels using the lemke howson algorithm. See Game.lemke_howson for more information. Note: this is not guaranteed to find all equilibria. ### Yields - **An equilibria** (Tuple) ``` -------------------------------- ### Create a Virtual Environment Source: https://github.com/drvinceknight/nashpy/blob/main/docs/contributing/how-to/how-to-create-a-virtualenv/index.md Use this command to create a new virtual environment. Replace `` with your desired environment name. ```bash $ python -m venv ``` -------------------------------- ### Validate Docstrings with Darglint Source: https://github.com/drvinceknight/nashpy/blob/main/docs/contributing/how-to/how-to-write-a-docstring/index.md Commands to install and run darglint to verify docstring formatting against the Numpy standard. ```default $ python -m pip install darglint $ darglint -s numpy ``` -------------------------------- ### Initialize a Game for Asymmetric Replicator Dynamics Source: https://github.com/drvinceknight/nashpy/blob/main/docs/how-to/use-asymmetric-replicator-dynamics.md Create a Nashpy Game instance using two payoff matrices. ```default >>> import nashpy as nash >>> import numpy as np >>> A = np.array([[3, 2], [4, 2]]) >>> B = np.array([[1, 3], [2, 4]]) >>> game = nash.Game(A, B) ``` -------------------------------- ### GET /nashpy/game/asymmetric_replicator_dynamics Source: https://github.com/drvinceknight/nashpy/blob/main/docs/discussion/source/nashpy.md Calculates the probability of each strategy being played over time using the asymmetric replicator dynamics algorithm. ```APIDOC ## GET /nashpy/game/asymmetric_replicator_dynamics ### Description Returns two arrays, corresponding to the two players, showing the probability of each strategy being played over time using the asymmetric replicator dynamics algorithm. ### Parameters #### Query Parameters - **x0** (array) - Optional - The initial population distribution of the row player. - **y0** (array) - Optional - The initial population distribution of the column player. - **timepoints** (array) - Optional - The iterable of timepoints. ### Response #### Success Response (200) - **result** (Tuple) - The 2 population distributions over time. ``` -------------------------------- ### Mypy error output Source: https://github.com/drvinceknight/nashpy/blob/main/docs/contributing/discussion/mypy/index.md Example of an error message generated by Mypy when type annotations are incompatible with function usage. ```default $ python -m mypy main.py main_with_wrong_types.py:17: error: Argument 1 to "len" has incompatible type "Iterable[Any]"; expected "Sized" Found 1 error in 1 file (checked 1 source file) ``` -------------------------------- ### Customize Initial Strategies and Timepoints Source: https://github.com/drvinceknight/nashpy/blob/main/docs/how-to/use-asymmetric-replicator-dynamics.md Provide custom initial strategy vectors and a specific sequence of timepoints for the dynamics calculation. ```pycon >>> x0 = np.array([0.4, 0.6]) >>> y0 = np.array([0.9, 0.1]) >>> timepoints = np.linspace(0, 10, 1000) >>> xs, ys = game.asymmetric_replicator_dynamics(x0=x0, y0=y0, timepoints=timepoints) >>> xs array([[0.4 , 0.6 ], [0.39784..., 0.60215...], [0.39569..., 0.60430...], ..., [0.17411..., 0.82588...], [0.17411..., 0.82588...], [0.17411..., 0.82588...]], shape=(1000, 2)) >>> ys array([[9.00000...e-01, 1.00000...e-01], [8.98183...e-01, 1.01816...e-01], [8.96338...e-01, 1.03661...e-01], ..., [1.86696...e-08, 9.99999...e-01], [1.82868...e-08, 9.99999...e-01], [1.79139...e-08, 9.99999...e-01]], shape=(1000, 2)) ``` -------------------------------- ### Get Best Response to Play Count Source: https://github.com/drvinceknight/nashpy/blob/main/docs/discussion/source/nashpy.learning.md Calculates the best response action given the opponent's play counts. ```APIDOC ## get_best_response_to_play_count ### Description Returns the best response to a belief based on the playing distribution of the opponent. ### Method N/A (Function) ### Endpoint N/A (Function) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (Returns) - **int** - The action that corresponds to the best response. #### Response Example N/A ``` -------------------------------- ### darglint Numpy style success Source: https://github.com/drvinceknight/nashpy/blob/main/docs/contributing/discussion/darglint/index.md Expected output when darglint finds no errors in a file checked against the Numpy style guide. ```text $ ``` -------------------------------- ### Build Halfspaces and Find Vertices Source: https://github.com/drvinceknight/nashpy/blob/main/docs/text-book/vertex-enumeration.md This snippet demonstrates how to build halfspaces from a game matrix and then find the non-trivial vertices of the resulting polytope using Nashpy and NumPy. It's useful for understanding the geometric representation of game strategies. ```python >>> import nashpy as nash >>> import numpy as np >>> A = np.array([[3, 1], [1, 3]]) >>> halfspaces = nash.polytope.build_halfspaces(A) >>> vertices = nash.polytope.non_trivial_vertices(halfspaces) >>> for vertex in vertices: ... print(vertex) (array([0.333..., 0...]), {0, 3}) (array([0..., 0.333...]), {1, 2}) (array([0.25, 0.25]), {0, 1}) ``` -------------------------------- ### Compute Nash Equilibria with Lemke-Howson Source: https://context7.com/drvinceknight/nashpy/llms.txt Uses the Lemke-Howson algorithm to find equilibria. Requires an initial dropped label or can enumerate all possible starting labels. ```python import nashpy as nash import numpy as np # Coordination game A = np.array([[2, 0], [0, 1]]) B = np.array([[2, 0], [0, 1]]) game = nash.Game(A, B) # Find one equilibrium with specific initial label sigma_r, sigma_c = game.lemke_howson(initial_dropped_label=0) print(f"Equilibrium (label=0):") print(f" Row: {sigma_r}, Column: {sigma_c}") # Enumerate equilibria for all possible starting labels print("\nEquilibria from all starting labels:") seen = set() for label in range(sum(A.shape)): sigma_r, sigma_c = game.lemke_howson(initial_dropped_label=label) key = (tuple(np.round(sigma_r, 4)), tuple(np.round(sigma_c, 4))) if key not in seen: seen.add(key) print(f" Label {label}: Row={sigma_r}, Column={sigma_c}") # Or use the enumeration method directly print("\nUsing lemke_howson_enumeration():") for eq in game.lemke_howson_enumeration(): print(f" {eq}") ``` -------------------------------- ### Initialize Game and Find Equilibria Source: https://github.com/drvinceknight/nashpy/blob/main/docs/how-to/solve-with-vertex-enumeration.md Initialize a game using a payoff matrix and then find all Nash equilibria using vertex enumeration. The equilibria are returned as a generator. ```python import nashpy as nash import numpy as np A = np.array([[1, -1], [-1, 1]]) matching_pennies = nash.Game(A) ``` ```python equilibria = matching_pennies.vertex_enumeration() for eq in equilibria: print(eq) ``` -------------------------------- ### Initialize Game for Moran Process Source: https://github.com/drvinceknight/nashpy/blob/main/docs/how-to/obtain-fixation-probabilities.md Sets up a game matrix and initializes a Nashpy Game object. This is a prerequisite for using Moran process methods. ```python import nashpy as nash import numpy as np A = np.array([[3, 1], [1, 2]]) game = nash.Game(A) ``` -------------------------------- ### Fictitious Play with Different Seed Source: https://github.com/drvinceknight/nashpy/blob/main/docs/how-to/use-fictitious-play.md Demonstrates the stochastic nature of Fictitious Play by running it with a different random seed. Observe how the play counts differ from the previous example. ```python np.random.seed(1) play_counts = game.fictitious_play(iterations=iterations) for row_play_counts, column_play_counts in play_counts: print(row_play_counts, column_play_counts) ``` -------------------------------- ### Create and Display a Bi matrix Game Source: https://github.com/drvinceknight/nashpy/blob/main/docs/text-book/solutions/best-responses.ipynb Initializes a bi matrix game using Nashpy with payoff matrices for two players. Displays the game's payoff matrices. ```python import nashpy as nash import numpy as np import matplotlib.pyplot as plt A = np.array(((-10, -13), (-15, 0))) B = np.array(((-10, -15), (-13, 0))) game = nash.Game(A, B) game ``` -------------------------------- ### Activate Virtual Environment on Windows Source: https://github.com/drvinceknight/nashpy/blob/main/docs/contributing/how-to/how-to-create-a-virtualenv/index.md Activate the created virtual environment on Windows systems. Ensure you are in the correct directory. ```bash $ env\Scripts\activate ``` -------------------------------- ### Create Virtual Environment Source: https://github.com/drvinceknight/nashpy/blob/main/docs/contributing/tutorial/index.md Create a virtual environment named 'env' for isolating Python dependencies. ```bash python -m venv env ``` -------------------------------- ### Check docstring format with Numpy style Source: https://github.com/drvinceknight/nashpy/blob/main/docs/contributing/discussion/darglint/index.md Command to check a Python file's docstring format against the Numpy style guide using darglint. This command should produce no output if the docstring adheres to the Numpy style. ```bash $ darglint -s numpy main.py ``` -------------------------------- ### Navigate to Nashpy Directory Source: https://github.com/drvinceknight/nashpy/blob/main/docs/contributing/tutorial/index.md Change the current directory to the cloned Nashpy source code directory. ```bash cd Nashpy ``` -------------------------------- ### Run Replicator Dynamics (Default Settings) Source: https://github.com/drvinceknight/nashpy/blob/main/docs/how-to/use-replicator-dynamics.md Call the replicator_dynamics method on a Game object to compute the strategies over time. By default, it starts with an equal probability distribution across actions and runs for a default number of time steps. ```python game.replicator_dynamics() ``` -------------------------------- ### Check docstring format with Google style Source: https://github.com/drvinceknight/nashpy/blob/main/docs/contributing/discussion/darglint/index.md Command to check a Python file's docstring format against the Google style guide using darglint. This may raise errors for missing parameters or return types in the docstring. ```bash $ darglint -s google main.py ``` -------------------------------- ### Check docstring format with Sphinx style Source: https://github.com/drvinceknight/nashpy/blob/main/docs/contributing/discussion/darglint/index.md Command to check a Python file's docstring format against the Sphinx style guide using darglint. Similar to Google style, it may report missing parameter and return information. ```bash $ darglint -s sphinx main.py ``` -------------------------------- ### Create a Game in Nashpy Source: https://github.com/drvinceknight/nashpy/blob/main/docs/tutorial/index.md Initialize a game using either a single payoff matrix for zero-sum games or a pair of matrices for general games. ```python >>> import nashpy as nash >>> import numpy as np >>> A = np.array([[0, -1, 1], [1, 0, -1], [-1, 1, 0]]) >>> rps = nash.Game(A) >>> rps Zero sum game with payoff matrices: Row player: [[ 0 -1 1] [ 1 0 -1] [-1 1 0]] Column player: [[ 0 1 -1] [-1 0 1] [ 1 -1 0]] ``` ```python >>> B = - A >>> rps = nash.Game(A, B) >>> rps Zero sum game with payoff matrices: Row player: [[ 0 -1 1] [ 1 0 -1] [-1 1 0]] Column player: [[ 0 1 -1] [-1 0 1] [ 1 -1 0]] ``` -------------------------------- ### Python Type Hint Syntax Source: https://github.com/drvinceknight/nashpy/blob/main/docs/contributing/how-to/how-to-write-a-typehint/index.md Illustrates the general syntax for annotating function parameters and return types in Python. ```default def ( variable_1: type = default_value, variable_2: type, ) -> type ``` -------------------------------- ### Create and switch to a new branch Source: https://github.com/drvinceknight/nashpy/blob/main/docs/contributing/how-to/how-to-create-a-branch/index.md Combines branch creation and checkout into a single command. ```bash $ git checkout -b ``` -------------------------------- ### Activate Virtual Environment on Linux/macOS Source: https://github.com/drvinceknight/nashpy/blob/main/docs/contributing/how-to/how-to-create-a-virtualenv/index.md Activate the created virtual environment on Linux or macOS systems. Ensure you are in the correct directory. ```bash $ source env/bin/activate ``` -------------------------------- ### Create a Zero-Sum Game Source: https://github.com/drvinceknight/nashpy/blob/main/docs/how-to/create-a-game.md Initialize a zero-sum game by passing a single payoff matrix to the nash.Game class. ```python >>> import nashpy as nash >>> import numpy as np >>> A = np.array([[1, -1], [-1, 1]]) >>> matching_pennies = nash.Game(A) >>> matching_pennies Zero sum game with payoff matrices: Row player: [[ 1 -1] [-1 1]] Column player: [[-1 1] [ 1 -1]] ``` -------------------------------- ### Run Project Tests with Tox Source: https://github.com/drvinceknight/nashpy/blob/main/README.md Execute the project's test suite using tox after making modifications. ```bash python -m tox ``` -------------------------------- ### Stage a file for commit Source: https://github.com/drvinceknight/nashpy/blob/main/docs/contributing/tutorial/index.md Use this command to stage a specific file before committing changes. ```default $ git add docs/contributing/reference/contributors/index.rst ``` -------------------------------- ### Create a Non-Zero-Sum Game Source: https://github.com/drvinceknight/nashpy/blob/main/docs/how-to/create-a-game.md Initialize a bi-matrix game by passing two payoff matrices to the nash.Game class. ```python >>> import nashpy as nash >>> import numpy as np >>> A = np.array([[3, 0], [5, 1]]) >>> B = np.array([[3, 5], [0, 1]]) >>> prisoners_dilemma = nash.Game(A, B) >>> prisoners_dilemma Bi matrix game with payoff matrices: Row player: [[3 0] [5 1]] Column player: [[3 5] [0 1]] ``` -------------------------------- ### Run alex on README.md Source: https://github.com/drvinceknight/nashpy/blob/main/docs/contributing/how-to/how-to-check-for-insensitive-language/index.md Executes 'alex' to check the 'README.md' file for insensitive language. ```bash $ alex README.md ``` -------------------------------- ### Simulate Imitation Dynamics in Nashpy Source: https://context7.com/drvinceknight/nashpy/llms.txt Simulates a population-based learning process where players copy successful strategies. Convergence to Nash equilibrium is expected. ```python import nashpy as nash import numpy as np # Coordination game A = np.array([[2, 0], [0, 1]]) B = np.array([[2, 0], [0, 1]]) game = nash.Game(A, B) # Run imitation dynamics equilibria = list(game.imitation_dynamics( population_size=100, iterations=1000, random_seed=42, threshold=0.5 )) sigma_r, sigma_c = equilibria[0] print(f"Row equilibrium strategy: {sigma_r}") print(f"Column equilibrium strategy: {sigma_c}") # Battle of the Sexes - may converge to different equilibria A = np.array([[3, 0], [0, 2]]) B = np.array([[2, 0], [0, 3]]) bos = nash.Game(A, B) # Run multiple times to see different convergence outcomes for seed in [1, 2, 3]: eq = list(bos.imitation_dynamics( population_size=50, iterations=500, random_seed=seed )) print(f"Seed {seed}: Row={eq[0][0]}, Col={eq[0][1]}") ``` -------------------------------- ### Run a Moran Process Simulation Source: https://github.com/drvinceknight/nashpy/blob/main/docs/how-to/use-moran-processes.md Execute the moran_process method to generate population states over time. Results are stochastic and depend on the initial population state. ```python >>> np.random.seed(0) >>> generations = game.moran_process(initial_population=(0, 0, 1)) >>> for population in generations: ... print(population) [0 0 1] [0 1 1] [0 1 1] ... [0 1 1] [1 1 1] ``` ```python >>> np.random.seed(2) >>> generations = game.moran_process(initial_population=(0, 0, 1)) >>> for population in generations: ... print(population) [0 0 1] [0 0 1] [0 0 0] ``` -------------------------------- ### Stage a file for commit Source: https://github.com/drvinceknight/nashpy/blob/main/docs/contributing/how-to/how-to-make-a-commit/index.md Use this command to add a specific file to the staging area before committing. Ensure the file path is correct. ```bash $ git add ``` -------------------------------- ### Clone Nashpy Repository Source: https://github.com/drvinceknight/nashpy/blob/main/docs/contributing/how-to/how-to-clone-the-repository/index.md Use this command to obtain a local copy of the Nashpy repository from GitHub. Replace `` with your GitHub username. ```default $ git clone https://github.com//Nashpy.git ``` -------------------------------- ### Execute Discrete Replicator Dynamics Source: https://github.com/drvinceknight/nashpy/blob/main/docs/how-to/use-discrete_replicator_dynamics.md Calculate strategy distribution over time steps using the discrete_replicator_dynamics method. ```python >>> initial_distribution=np.array([0.2,0.8]) >>> strategy_over_time = game.discrete_replicator_dynamics(initial_distribution, steps=100, quantize=False) >>> strategy_over_time array([[0.25581395, 0.74418605], [0.30494427, 0.69505573], [0.34559999, 0.65440001], ... [0.5 , 0.5 ], [0.5 , 0.5 ], [0.5 , 0.5 ]]) ```