Skip to main content

PopGames logo

A Python package to model and simulate population games.

PyPI version PyPI - Python Version docs


Documentation

Full API reference and usage examples are available at:

https://martinez-piazuelo.github.io/popgames/


Installation

PopGames is available on PyPI and can be installed using pip.

Install from PyPI

pip install popgames

This installs the latest released version together with its dependencies.

Install the development version

If you want the latest features, you can install the development version directly from GitHub:

pip install git+https://github.com/Martinez-Piazuelo/popgames.git

Optional: Numba backend

To speed up large simulations with the optional Numba backend, install the numba extra:

pip install "popgames[numba]"

Numba is only needed when a simulator is created with backend="numba".

Verify the installation

You can verify that PopGames is installed correctly by running:

import popgames
print(popgames.__version__)

If no errors occur, the installation was successful.

Quick Usage Example

PopGames follows an object-oriented design built around four core components:

  • Population game: defines the strategic environment
  • Payoff mechanism: specifies the payoff perceived by agents
  • Revision process: determines how agents update their strategies
  • Simulator: orchestrates and runs the simulation

This example demonstrates how to simulate a simple population game using popgames.

We model the classic Prisoner’s Dilemma, where agents repeatedly choose between two strategies:

  • Cooperate
  • Defect

Although mutual cooperation is socially optimal, evolutionary dynamics often drive the population toward defection.


Define the fitness function

We begin by defining the fitness function for the Prisoner's Dilemma. The payoff parameters satisfy

T > R > P > S

where:

  • T – temptation to defect
  • R – reward for mutual cooperation
  • P – punishment for mutual defection
  • S – sucker's payoff

The fitness function is then of the form:

f(x) = [[R, S], [T, P]]x

which can be implemented in Python as follows:

import numpy as np

T, R, P, S = 3, 2, 1, 0

def fitness_function(x):
    return np.dot(
        np.array([[R, S], [T, P]]),
        x
    )

Create the population game and payoff mechanism objects

Next we instantiate the population game and payoff mechanism objects by specifying the number of strategies and the fitness function.

from popgames import (
    SinglePopulationGame,
    PayoffMechanism,
)

population_game = SinglePopulationGame(
    num_strategies=2,
    fitness_function=fitness_function,
)

payoff_mechanism = PayoffMechanism(
    h_map=fitness_function,
    n=2,
)

Define the revision process object

Agents revise their strategies according to a Poisson revision process combined with a softmax revision protocol. We therefore define the corresponding revision process object as follows.

from popgames import PoissonRevisionProcess
from popgames.revision_protocol import Softmax

revision_process = PoissonRevisionProcess(
    Poisson_clock_rate=1,
    revision_protocol=Softmax(0.1),
)

Instantiate the simulator and run the simulation

We now create the simulator and run the population dynamics. The simulation considers a population of 1000 agents starting from an equal split between the two strategies.

from popgames import Simulator

sim = Simulator(
    population_game=population_game,
    payoff_mechanism=payoff_mechanism,
    revision_processes=revision_process,
    num_agents=1000
)

x0 = np.array([0.5, 0.5]).reshape(2, 1)  # Initial state

sim.reset(x0=x0)
out = sim.run(T_sim=30)

Visualize the results

Finally, we visualize the evolution of the population state using matplotlib.

import matplotlib.pyplot as plt

plt.figure(figsize=(3, 3))

plt.plot(out.t, out.x[0, :], label="Cooperators")
plt.plot(out.t, out.x[1, :], label="Defectors")

plt.xlabel("Time")
plt.ylabel("Population fraction")
plt.legend()
plt.grid()

plt.tight_layout()
plt.show()

PopGames also provides built-in visualization utilities supporting ternary plots, univariate projections, and custom key performance indicators. For more details, see the API reference documentation.

Every plot type accepts ax: existing matplotlib axes to draw on (one per figure the plot would otherwise create), which makes it easy to compose several plots into one figure. The figure then belongs to you: it is neither saved, shown, nor closed by PopGames.

fig, axes = plt.subplots(1, 3, figsize=(12, 3))
sim.plot(plot_type="kpi", ax=axes[0])
sim.plot(plot_type="univariate", ax=axes[1:])  # x(t) and p(t)
fig.tight_layout()
fig.savefig("simulation.pdf")

Run an ensemble of simulations

Finite-agent simulations are stochastic, so a single run shows only one possible outcome. run_ensemble runs many simulations and samples them at common times, either from the same initial state with different seeds, or from different initial states:

# Same initial state, 20 different seeds
ens = sim.run_ensemble(T_sim=10, num_runs=20, x0=x0, seed=0)
ens.plot(plot_type="bands", variables=["x"], plot_deterministic_approximation=True)

# 10 random initial states, same seed
from popgames.utilities import sample_initial_states

x0s = sample_initial_states(population_game, num=10, seed=1)
ens = sim.run_ensemble(T_sim=10, x0=x0s, seed=[0] * len(x0s))
ens.plot(plot_type="kpi", plot_deterministic_approximation=True)

The result holds the runs in arrays of shape (runs, strategies, times) (e.g., ens.x), with helpers such as ens.mean() and ens.quantile(...), and plots of quantile bands, KPIs, ternary trajectories, and final states.

integrate_ensemble does the same for the deterministic approximation (EDM-PDM), e.g., to check that trajectories from many initial states converge. Its bands pool all initial states by default, and statistic="mean_std" shows the mean and standard deviation instead of the median and quantiles:

ens = sim.integrate_ensemble(T_sim=10, x0=x0s)
ens.plot(plot_type="bands", variables=["x"], statistic="mean_std")

For games with many strategies, layout="per_strategy" draws one panel per strategy, and reference={"x": x_star} (or plot_gne=True) adds the equilibrium as dashed lines. Quantities derived from the state, such as temperatures that depend on x, can be plotted the same way with derived={"T": lambda run: ...} (a function of each run returning an array of shape (m, K)), and evaluated on all runs with ens.apply(...). See the usage examples in the documentation for more details.

Contributing

Contributions are welcome. If you would like to improve popgames, please follow the workflow below.

1. Fork and clone the repository

Fork the repository on GitHub, then clone your fork locally:

git clone https://github.com/<your-username>/popgames.git
cd popgames

Create a new branch for your changes:

git checkout -b your-feature-branch-name

2. Set up the development environment

This project uses uv for dependency and environment management.

Install uv if it is not already installed:

pip install uv

Install the development environment with:

uv sync

This installs the package together with the default dependency groups used for development and documentation.

The repository also uses a Taskfile to define common development commands. The Task runner (go-task) is installed automatically as part of the development dependencies.


3. Run the test suite

Before submitting a pull request, ensure all tests pass:

uv run task test

4. Format and check the code

Please ensure your code is properly formatted and passes all checks before opening a pull request:

uv run task format
uv run task check

5. Submit a pull request

Push your branch to your fork and open a pull request against the main repository.

Please include:

  • A clear description of the changes
  • Any relevant issue references
  • Tests for new functionality when applicable
  • Documentation updates if needed

Development notes

  • Keep contributions focused and minimal.
  • Follow the existing project structure and coding style.
  • Run formatting, linting, and tests locally before submitting your pull request.

Metadata

Release files for popgames 1.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for popgames 1.2.0
File Size Uploaded Provenance Actions
popgames-1.2.0.tar.gz 53.6 kB With provenance Details for popgames-1.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for popgames 1.2.0
File Interpreter ABI Platform Actions
popgames-1.2.0-py3-none-any.whl Python 3 none any Details for popgames-1.2.0-py3-none-any.whl

Total release size: 115.7 kB

Release files / popgames-1.2.0.tar.gz

Download URL popgames-1.2.0.tar.gz
Size 53.6 kB
Tags Source
SHA-256 checksum
How to use checksums
a819df11955e51ea49d0b01e643b88f06d98770f79d5ef78b0d1dbb5f29688c7
BLAKE2b-256 checksum
How to use checksums
a9f61bbe38409f6ed0780bcd110aeac0687fca8d43661bb7e10f9722f75d46fc
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 24, 2026.

Transparency log

Release files / popgames-1.2.0-py3-none-any.whl

Download URL popgames-1.2.0-py3-none-any.whl
Size 62.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
cccb4aad77b9f5a331677b43af8f66d11142c399b02cf6c12be6459fbea40002
BLAKE2b-256 checksum
How to use checksums
04a98bcba106ccf5f9d4dd2d4ce68eadecd1f3398f90180ab4366e59db596e4f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 24, 2026.

Transparency log

Security for popgames 1.2.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for popgames-1.2.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 24, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page