Simulator

This module defines the Simulator class, which provides numerical tools to simulate the interplay between population games, payoff mechanisms, and revision processes.

The simulator tracks the evolution of strategic distributions and payoffs over time. It supports both finite-agent simulations and numerical integration of deterministic dynamics models.

The simulator is equipped with a VisualizationMixin implementing useful visualization tools.

—

Simulator

class popgames.simulator.Simulator(population_game, payoff_mechanism, revision_processes, num_agents, fast_path=True, pdm_method='RK4', pdm_max_step=0.01, seed=None, backend='numpy')[source]

Bases: VisualizationMixin

Simulates the interplay between the three core objects: i) A population game, ii) A payoff mechanism, and iii) a list of revision processes (one per population).

Initialize the simulator object.

Parameters:
  • population_game (PopulationGame) – The population game object.

  • payoff_mechanism (PayoffMechanism) – The payoff mechanism object.

  • revision_processes (Union[RevisionProcessABC, list[RevisionProcessABC]]) – A single revision process for the single-population case, or a list of revision processes for the multi-population case, where each element corresponds to a specific population.

  • num_agents (Union[int, list[int]]) – The number of agents as an integer for the single-population case, or a list of integers specifying the number of agents in each population for the multi-population case.

  • fast_path (bool) – Whether to use the fast simulation path. It is only used if all revision processes are PoissonRevisionProcess instances; otherwise the per-agent simulation path is used. Set to False to force the per-agent path (e.g., for comparison). Defaults to True.

  • pdm_method (str) – Method used to integrate the PDM between revision events. Either ‘RK4’ or any method supported by scipy.integrate.solve_ivp (e.g., ‘Radau’ for stiff PDMs). Defaults to ‘RK4’.

  • pdm_max_step (float) – Maximum step size used to integrate the PDM between revision events. Defaults to 0.01.

  • seed (Union[int, np.random.Generator], optional) – Seed or random number generator for the simulation. Defaults to None, in which case NumPy’s global random state is used (see np.random.seed). Custom (non-Poisson) revision processes always draw from their own random sources.

  • backend (str) – Either ‘numpy’ or ‘numba’. The ‘numba’ backend compiles the fast simulation path with Numba (requires pip install popgames[numba]). It requires the fast path, built-in revision protocols, pdm_method='RK4', and payoff mechanism functions that can be compiled with numba.njit; otherwise, a warning is logged and the ‘numpy’ backend is used. Compilation takes a few seconds on the first run of each session. Defaults to ‘numpy’.

integrate_edm_pdm(t_span, x0, q0=None, t_eval=None, method='Radau', output_trajectory=True)[source]

Numerically integrate the underlying EDM-PDM system.

This method relies on scipy.integrate.solve_ivp.

Parameters:
  • t_span (tuple) – The time span of the integration.

  • x0 (np.ndarray) – The initial strategic distribution of the society.

  • q0 (np.ndarray) – The initial state of the PDM. Defaults to None.

  • t_eval (list) – The times at which to evaluate the integration. Defaults to None.

  • method (str) – The integration method. Defaults to ‘Radau’.

  • output_trajectory (bool) – Whether to output the trajectory or just the final state-output pair. Defaults to True.

Returns:

The integration results as a SimpleNamespace object.

Return type:

SimpleNamespace

integrate_ensemble(T_sim, x0=None, q0=None, t_eval=None, method='Radau')[source]

Integrate the deterministic approximation (EDM-PDM) from several initial states, e.g., to check that every trajectory converges regardless of where it starts.

Each run r is integrate_edm_pdm from (x0_r, q0_r) over [0, T_sim], sampled at the times t_eval. The result is an EnsembleResult (with is_deterministic=True and no seeds), so it supports the same statistics and plots as the ensembles of finite-agent simulations from run_ensemble. For instance, ens.plot(plot_type='bands', statistic='mean_std') shows the mean and standard deviation over the initial states.

The initial states can be shared by all runs or given per run, as in run_ensemble:

  • x0: an array of shape (n, 1) (or None) shared by all runs, or an array of shape (M, n, 1) with one initial state per run (see popgames.utilities.sample_initial_states). Similarly for q0.

The number of runs M is the length of the per-run arguments (which must agree), or 1 if there are none.

Parameters:
  • T_sim (float) – The time horizon of each run.

  • x0 (np.ndarray, optional) – The initial strategic distribution, of shape (n, 1) for all runs or (M, n, 1) per run. Defaults to None, in which case the initial state of the last reset (log.x[:, [0]]) is used.

  • q0 (np.ndarray, optional) – The initial state of the PDM, of shape (d, 1) for all runs or (M, d, 1) per run. Defaults to None, in which case the initial state of the last reset (log.q[:, [0]]) is used.

  • t_eval (np.ndarray, optional) – Non-decreasing times in [0, T_sim] at which the runs are sampled. Defaults to None, in which case 201 evenly spaced times are used.

  • method (str, optional) – The integration method (see integrate_edm_pdm). Defaults to ‘Radau’.

Returns:

The sampled runs, with fields t (shape (K,)), x (shape (M, n, K)), q (shape (M, d, K)), p (shape (M, n, K)), x0 (shape (M, n, 1)), and q0 (shape (M, d, 1)), where K is the number of sampling times.

Return type:

EnsembleResult

property log: SimpleNamespace

The simulation log since the last reset, with one row per variable and one column per log entry.

The layout is the same as the output of run and integrate_edm_pdm (and of scipy.integrate.solve_ivp), so finite-agent and deterministic trajectories can be compared directly. Standard NumPy indexing applies:

  • log.x[i] (shape (K,)) is the trajectory of strategy i over time.

  • log.x[:, k] (shape (n,)) is the strategic distribution at time log.t[k].

  • log.x[:, [k]] (shape (n, 1)) is the same distribution as a column vector, as expected by reset, integrate_edm_pdm, and the payoff functions.

Returns:

The log with fields t (shape (K,)), x (shape (n, K)), q (shape (d, K)), and p (shape (n, K)), where K is the number of log entries.

Return type:

SimpleNamespace

plot(*, plot_type='kpi', filename=None, figsize=None, fontsize=None, show=True, **kwargs)

Unified plotting interface supporting some predefined plot types.

Plot the results of the last simulation.

Parameters:
  • plot_type (str) – Plot type. Defaults to ‘x(t)’.

  • filename (str, optional) – If not None the figure is saved with that filename. Defaults to None.

  • figsize (tuple[int, int], optional) – Matplotlib’s figsize. Defaults to (3, 3).

  • fontsize (int, optional) – Matplotlib’s fontsize. Defaults to 10.

  • show (bool, optional) – Whether to show the figure. Defaults to True.

  • **kwargs (dict[str, Any] | Any) – Additional keyword arguments to bypass to the selected plot_type, e.g., ax to draw on existing matplotlib axes (one per figure the plot would otherwise create; the figure is then neither saved, shown, nor closed). Warning: unrecognized arguments are silently ignored.

  • self (Simulator)

Return type:

None

reset(x0=None, q0=None, seed=None)[source]

Resets the simulator.

Parameters:
  • x0 (np.ndarray, Optional) – The initial state for the strategic distribution of the society. Defaults to None.

  • q0 (np.ndarray, Optional) – The initial state for the payoff mechanism’s PDM. Defaults to None.

  • seed (Union[int, np.random.Generator], optional) – If provided, the simulator draws from a new random number generator seeded with seed from now on (as if seed had been passed to the constructor). Defaults to None, in which case the current random number generator is kept.

Return type:

None

run(T_sim, verbose=False, log_interval=None)[source]

Run the simulation.

Parameters:
  • T_sim (int) – The total time to simulate (in units specified by the agents’ alarm clocks).

  • verbose (bool) – Whether to print simulation information. Defaults to False.

  • log_interval (float, optional) – Minimum time between consecutive log entries. Defaults to None, in which case every revision event is logged. The final state is always logged.

Returns:

The simulation results as a SimpleNamespace object.

Return type:

SimpleNamespace

See also

run_ensemble(): Run the simulation for several seeds and/or initial states, sampled at common times.

run_ensemble(T_sim, num_runs=None, t_eval=None, seed=None, x0=None, q0=None, log_interval=None)[source]

Run several finite-agent simulations, e.g., from the same initial state with different seeds, or from different initial states.

Each run r resets the simulator with reset(x0_r, q0_r, seed=seed_r) and runs it for T_sim time units. Its state is then sampled at the times t_eval: the value at time t is the state after the last revision event at or before t (the state of a finite population is constant between events).

The seeds and the initial states can be shared by all runs or given per run:

  • seed: an integer, a np.random.Generator, or None to derive independent seeds for the runs, or a sequence with one seed per run (e.g., [7] * M to use the same seed in all runs).

  • x0: an array of shape (n, 1) (or None) shared by all runs, or an array of shape (M, n, 1) with one initial state per run (see popgames.utilities.sample_initial_states). Similarly for q0.

The number of runs M is num_runs or the length of the per-run arguments (which must agree).

After the call, the simulator holds the last run (e.g., in log), and its random number generator is the one it had before the call.

Parameters:
  • T_sim (int) – The total time to simulate in each run.

  • num_runs (int, optional) – The number of runs. Defaults to None, in which case it is the length of the per-run arguments (required if there are none).

  • t_eval (np.ndarray, optional) – Non-decreasing times in [0, T_sim] at which the runs are sampled. Defaults to None, in which case 201 evenly spaced times are used.

  • seed (Union[int, np.random.Generator, Sequence[int]], optional) – Seed or random number generator from which independent seeds for the runs are derived, or a sequence of non-negative integers with the seed of each run. Defaults to None, in which case the seeds are derived from the simulator’s random number generator (NumPy’s global random state if the simulator has no seed, see np.random.seed).

  • x0 (np.ndarray, optional) – The initial strategic distribution, of shape (n, 1) for all runs or (M, n, 1) per run. Defaults to None, in which case the initial state of the last reset (log.x[:, [0]]) is used for all runs.

  • q0 (np.ndarray, optional) – The initial state of the PDM, of shape (d, 1) for all runs or (M, d, 1) per run. Defaults to None, in which case the initial state of the last reset (log.q[:, [0]]) is used for all runs.

  • log_interval (float, optional) – Minimum time between consecutive log entries within each run (see run). Defaults to None, in which case every revision event is logged and the sampled states are exact. Setting it reduces memory usage in very large runs, but then the state sampled at time t may lag behind by up to log_interval.

Returns:

The sampled runs, with fields t (shape (K,)), x (shape (M, n, K)), q (shape (M, d, K)), p (shape (M, n, K)), seeds (shape (M,)), x0 (shape (M, n, 1)), and q0 (shape (M, d, 1)), where K is the number of sampling times.

Return type:

EnsembleResult

—

Ensemble Result

Returned by Simulator.run_ensemble (finite-agent simulations) and Simulator.integrate_ensemble (the deterministic approximation), sampled at common times, from the same initial state or from different ones.

class popgames.ensemble.EnsembleResult(simulator, t, x, q, p, seeds, x0, q0, is_deterministic=False)[source]

Bases: EnsembleVisualizationMixin

Simulations sampled at common times, e.g., from the same initial state with different seeds, or from different initial states.

Ensembles of finite-agent simulations are created by Simulator.run_ensemble, and ensembles of the deterministic approximation (EDM-PDM) from several initial states by Simulator.integrate_ensemble. The arrays have one leading axis for the runs, followed by the layout of Simulator.log:

  • ens.x[r] (shape (n, K)) is run r, with ens.x[r, i] the trajectory of strategy i.

  • ens.x[:, i] (shape (M, K)) holds the trajectories of strategy i in all runs.

  • ens.x[:, :, k] (shape (M, n)) holds the strategic distributions of all runs at time ens.t[k].

Runs with the same initial state (x0, q0) form a group (groups and group_index). Statistics such as mean and quantile pool all runs; use subset for statistics per group, e.g., ens.subset(ens.groups[g]).mean(). The plots show one group per initial state, unless the initial states are pooled (the default for deterministic ensembles, see plot_ensemble_bands).

Parameters:
  • simulator (Simulator)

  • t (np.ndarray)

  • x (np.ndarray)

  • q (np.ndarray)

  • p (np.ndarray)

  • seeds (np.ndarray | None)

  • x0 (np.ndarray)

  • q0 (np.ndarray)

  • is_deterministic (bool)

t

The sampling times, of shape (K,).

Type:

np.ndarray

x

The strategic distributions, of shape (M, n, K).

Type:

np.ndarray

q

The states of the PDM, of shape (M, d, K).

Type:

np.ndarray

p

The payoffs, of shape (M, n, K).

Type:

np.ndarray

seeds

The seeds of the runs, of shape (M,), or None for deterministic ensembles. Run r can be reproduced with sim.reset(ens.x0[r], ens.q0[r], seed=int(ens.seeds[r])) followed by sim.run(T_sim).

Type:

np.ndarray | None

x0

The initial strategic distribution of each run, of shape (M, n, 1). For finite-agent runs, this is the state the run actually started from: reset rounds the requested state to a whole number of agents per strategy.

Type:

np.ndarray

q0

The initial state of the PDM of each run, of shape (M, d, 1).

Type:

np.ndarray

groups

The indices of the runs of each group (runs with the same initial state), in order of first appearance.

Type:

list[np.ndarray]

group_index

The group of each run, of shape (M,).

Type:

np.ndarray

is_deterministic

Whether the runs are trajectories of the deterministic approximation (EDM-PDM) rather than finite-agent simulations.

Type:

bool

simulator

The simulator that produced the runs.

Type:

Simulator

apply(function, deterministic=False)[source]

Evaluate a quantity derived from the state on every run, e.g., a temperature or a constraint residual.

Parameters:
  • function (Callable[[SimpleNamespace], np.ndarray]) – Function mapping a run (with fields t, x, q, and p in the layout of Simulator.log, see __getitem__) to the quantity over time, of shape (m, K) (or (K,) for a scalar quantity).

  • deterministic (bool, optional) – Whether to evaluate it on the deterministic approximation from the initial state of each run (see deterministic) instead. Defaults to False.

Returns:

The quantity, of shape (M, m, K).

Return type:

np.ndarray

at(t)[source]

The states of all runs at the last sampling time at or before t.

Parameters:

t (float) – The time, with ens.t[0] <= t.

Returns:

Fields t (the sampling time used), x (shape (M, n)), q (shape (M, d)), and p (shape (M, n)).

Return type:

SimpleNamespace

deterministic(method='Radau')[source]

The deterministic approximation (EDM-PDM) from the initial state of each run, sampled at the same times.

The approximation is computed with Simulator.integrate_edm_pdm once per group (distinct initial state), and cached. For a deterministic ensemble, these are the runs themselves.

Parameters:

method (str) – The integration method. Defaults to ‘Radau’.

Returns:

Fields t (shape (K,)), x (shape (M, n, K)), q (shape (M, d, K)), and p (shape (M, n, K)), with the same layout as the ensemble.

Return type:

SimpleNamespace

final()[source]

The states of all runs at the last sampling time (see at).

Returns:

Fields t, x (shape (M, n)), q (shape (M, d)), and p (shape (M, n)).

Return type:

SimpleNamespace

mean()[source]

The mean over all runs at each sampling time (see subset for the mean per initial state).

Returns:

Fields t (shape (K,)), x (shape (n, K)), q (shape (d, K)), and p (shape (n, K)).

Return type:

SimpleNamespace

property num_groups: int

The number of groups (distinct initial states).

property num_runs: int

The number of runs M.

plot(*, plot_type='bands', **kwargs)

Unified plotting interface for ensembles of finite-agent simulations.

Supported plot types (see their functions in popgames.plotting.ensemble_plotters for all options):

  • 'bands': median and quantile bands (or mean and standard deviation bands, statistic='mean_std') of x, p, and q over time, per initial state or pooled, in one panel or one panel per strategy, with optional reference lines such as an equilibrium, and of quantities derived from the state (plot_ensemble_bands).

  • 'kpi': the same bands for a KPI over time (plot_ensemble_kpi).

  • 'ternary': trajectories of the runs on the simplex (plot_ensemble_ternary).

  • 'final': distribution of the strategic distributions at the final (or a given) time (plot_ensemble_final).

All plot types accept filename, figsize, fontsize, show, plot_deterministic_approximation, and ax (existing matplotlib axes to draw on, one per figure the plot would otherwise create; the figure is then neither saved, shown, nor closed).

Parameters:
  • plot_type (str) – Plot type. Defaults to ‘bands’.

  • **kwargs (Any) – Keyword arguments of the selected plot type. Unrecognized arguments raise a TypeError.

  • self (EnsembleResult)

Return type:

None

quantile(quantiles)[source]

The quantiles over all runs at each sampling time (see subset for the quantiles per initial state).

Parameters:

quantiles (Union[float, Sequence[float]]) – One or several quantiles in [0, 1].

Returns:

Fields t (shape (K,)), x, q, and p. For a single quantile, x has shape (n, K) (similarly for q and p); for several quantiles, it has shape (Q, n, K), with one entry per quantile.

Return type:

SimpleNamespace

subset(runs)[source]

The ensemble restricted to some runs, e.g., ens.subset(ens.groups[g]) for the runs of group g.

Parameters:

runs (Union[Sequence[int], np.ndarray]) – The indices of the runs (or a boolean mask).

Returns:

A new ensemble with the selected runs.

Return type:

EnsembleResult

—

Visualization Mixin

class popgames.plotting.visualization_mixin.VisualizationMixin[source]

Bases: object

Visualization mixin to add plotting functionality to the Simulator class.

This class is expected to be mixed into the Simulator class. It is defined in a separate module to keep simulator.py clean.

plot(*, plot_type='kpi', filename=None, figsize=None, fontsize=None, show=True, **kwargs)[source]

Unified plotting interface supporting some predefined plot types.

Plot the results of the last simulation.

Parameters:
  • plot_type (str) – Plot type. Defaults to ‘x(t)’.

  • filename (str, optional) – If not None the figure is saved with that filename. Defaults to None.

  • figsize (tuple[int, int], optional) – Matplotlib’s figsize. Defaults to (3, 3).

  • fontsize (int, optional) – Matplotlib’s fontsize. Defaults to 10.

  • show (bool, optional) – Whether to show the figure. Defaults to True.

  • **kwargs (dict[str, Any] | Any) – Additional keyword arguments to bypass to the selected plot_type, e.g., ax to draw on existing matplotlib axes (one per figure the plot would otherwise create; the figure is then neither saved, shown, nor closed). Warning: unrecognized arguments are silently ignored.

  • self (Simulator)

Return type:

None

—

Supported Plots

popgames.plotting.plotters.make_default_kpi_function(simulator)[source]

Make the default KPI function: the Euclidean distance to the GNE over time, normalized by its initial value.

Parameters:

simulator (Simulator) – The simulator whose population game defines the GNE.

Returns:

The KPI function, mapping a log (with x of shape (n, K)) to an array of shape (K,), or None (with a warning) if no GNE was found.

Return type:

Callable[[SimpleNamespace], np.ndarray] | None

popgames.plotting.plotters.make_reference_values(simulator, reference=None, plot_gne=False, derived_sizes=None)[source]

Make the reference values plotted as horizontal lines (e.g., an equilibrium) per variable.

Parameters:
  • simulator (Simulator) – The simulator defining the dimensions and the GNE.

  • reference (dict[str, np.ndarray], optional) – Reference values per variable, among ‘x’, ‘p’ (n entries, e.g., of shape (n, 1)), ‘q’ (d entries), and the derived quantities (if any). A scalar is used for all the entries of the variable. Defaults to None.

  • plot_gne (bool, optional) – Whether to use the GNE (PopulationGame.compute_gne) as the reference of ‘x’. Cannot be combined with reference['x']. Defaults to False.

  • derived_sizes (dict[str, int], optional) – The number of entries of each derived quantity, by name. Defaults to None.

Returns:

The flattened reference values per variable.

Return type:

dict[str, np.ndarray]

popgames.plotting.plotters.make_ternary_plot_multi_population(simulator, scale=30, fontsize=8, figsize=(4, 3), plot_edm_trajectory=False, filename=None, show=True, ax=None, legend=True)[source]

Plot the trajectory of a multiple population in multiple ternary plots.

This method requires every population to have n^k=3 strategies.

Parameters:
  • simulator (Simulator) – Simulator instance holding the data for the plot.

  • scale (int, optional) – Scaling factor for the heatmap. Defaults to 30.

  • fontsize (int, optional) – Font size for the heatmap. Defaults to 8.

  • figsize (tuple[int, int], optional) – Figure size. Defaults to (4,3).

  • plot_edm_trajectory (bool, optional) – Whether to plot edm trajectory. Defaults to False.

  • filename (str, optional) – Filename to save the figure. Defaults to None.

  • show (bool, optional) – Whether to show the figure. Defaults to True.

  • ax (Sequence[Axes], optional) – Existing matplotlib axes to draw on, one per population. The figures are then neither saved, shown, nor closed. Defaults to None.

  • legend (bool, optional) – Whether to draw the legend in the plot. If False, its entries remain available through ax.get_legend_handles_labels(), e.g., for one legend shared by several plots (see add_shared_legend). Defaults to True.

Return type:

None

popgames.plotting.plotters.make_ternary_plot_single_population(simulator, potential_function=None, scale=30, fontsize=8, figsize=(4, 3), plot_edm_trajectory=False, filename=None, show=True, ax=None, legend=True)[source]

Plot the trajectory of a single population in a ternary plot.

This method requires the population to have n=3 strategies.

Parameters:
  • simulator (Simulator) – Simulator instance holding the data for the plot.

  • potential_function (Callable[[np.ndarray], np.ndarray], optional) – Potential function to plot heatmap. Defaults to None.

  • scale (int, optional) – Scaling factor for the heatmap. Defaults to 30.

  • fontsize (int, optional) – Font size for the heatmap. Defaults to 8.

  • figsize (tuple[int, int], optional) – Figure size. Defaults to (4,3).

  • plot_edm_trajectory (bool, optional) – Whether to plot edm trajectory. Defaults to False.

  • filename (str, optional) – Filename to save the figure. Defaults to None.

  • show (bool, optional) – Whether to show the figure. Defaults to True.

  • ax (Axes, optional) – Existing matplotlib axes to draw on. The figure is then neither saved, shown, nor closed. Defaults to None.

  • legend (bool, optional) – Whether to draw the legend in the plot. If False, its entries remain available through ax.get_legend_handles_labels(), e.g., for one legend shared by several plots (see add_shared_legend). Defaults to True.

Return type:

None

popgames.plotting.plotters.plot_kpi_over_time(simulator, plot_deterministic_approximation=False, **kwargs)[source]

Plot a KPI over time (by default, the normalized Euclidean distance to the GNE).

Parameters:
  • simulator (Simulator) – The simulator object holding the data to plot.

  • plot_deterministic_approximation (bool, optional) – Whether to plot the KPI under the deterministic approximation. Defaults to False.

  • **kwargs (dict[str, Any]) – Keyword arguments to specify plotting options, e.g., kpi_function, ax to draw on an existing matplotlib axes (the figure is then neither saved, shown, nor closed), or legend=False to leave the legend out (see popgames.plotting.add_shared_legend).

Return type:

None

popgames.plotting.plotters.plot_ternary_trajectories(simulator, plot_deterministic_approximation=False, scale=30, potential_function=None, **kwargs)[source]

Make a ternary plot for the simulated scenario.

This method is only supported for single-population games with n=3, and for multi-population games where each population has n^k=3 strategies.

Parameters:
  • scale (int) – Scaling factor for the ternary plot. Defaults to 30.

  • fontsize (int) – Fontsize for the plot. Defaults to 8.

  • figsize (tuple[int, int]) – Figure size. Defaults to (4, 3).

  • filename (str, optional) – Filename to save the figure. Defaults to None.

  • plot_edm_trajectory (bool) – Whether to plot edm trajectory or not. Defaults to False.

  • potential_function (Callable[[np.ndarray], np.ndarray]) – Potential function to plot as a heatmap. Defaults to None.

  • show (bool) – Whether to show the figure(s). Defaults to True.

  • ax (Axes | Sequence[Axes], optional) – Existing matplotlib axes to draw on, one per population (a single one for single-population games). The figures are then neither saved, shown, nor closed. Defaults to None.

  • legend (bool, optional) – Whether to draw the legend in the plot(s). If False, its entries remain available through ax.get_legend_handles_labels(), e.g., for one legend shared by several plots (see add_shared_legend). Defaults to True.

  • simulator (Simulator)

  • plot_deterministic_approximation (bool)

  • kwargs (dict[str, Any])

Return type:

None

popgames.plotting.plotters.plot_univariate_trajectories_joint(simulator, plot_deterministic_approximation=False, **kwargs)[source]

This method generates 2(num_populations)+1 plots, one for each vector x, q, and p, against time, and for x and p the plots are generated per population.

Optionally: It also plots the trajectory of each element under the deterministic approximation of the evolutionary dynamics model.

Parameters:
  • simulator (Simulator) – The simulator object holding the data to plot.

  • plot_deterministic_approximation (bool, optional) – Whether to plot the related trajectories under the deterministic approximation. Defaults to False.

  • **kwargs (dict[str, Any]) – Keyword arguments to specify plotting options, e.g., ax to draw on existing matplotlib axes: one per plot, in the order x (per population), p (per population), and q (if d > 0). The figures are then neither saved, shown, nor closed. reference (values per variable, e.g., {'x': x_star}) and plot_gne (the GNE as the reference of x) add dashed horizontal lines, see make_reference_values. legend=False leaves the legends out (see popgames.plotting.add_shared_legend).

Return type:

None

popgames.plotting.plotters.plot_univariate_trajectories_split(simulator, plot_deterministic_approximation=False, **kwargs)[source]

This method generates several plots, one for each element of the vectors x, q, and p, against time.

Optionally: It also plots the trajectory of each element under the deterministic approximation of the evolutionary dynamics model.

Parameters:
  • simulator (Simulator) – The simulator object holding the data to plot.

  • plot_deterministic_approximation (bool, optional) – Whether to plot the related trajectories under the deterministic approximation. Defaults to False.

  • **kwargs (dict[str, Any]) – Keyword arguments to specify plotting options, e.g., ax to draw on existing matplotlib axes: one per plot, in the order x_1, ..., x_n, p_1, ..., p_n, and q_1, ..., q_d. The figures are then neither saved, shown, nor closed. reference (values per variable, e.g., {'x': x_star}) and plot_gne (the GNE as the reference of x) add dashed horizontal lines, see make_reference_values. legend=False leaves the legends out (see popgames.plotting.add_shared_legend).

Return type:

None

—

Ensemble Visualization Mixin

class popgames.plotting.visualization_mixin.EnsembleVisualizationMixin[source]

Bases: object

Visualization mixin to add plotting functionality to the EnsembleResult class.

plot(*, plot_type='bands', **kwargs)[source]

Unified plotting interface for ensembles of finite-agent simulations.

Supported plot types (see their functions in popgames.plotting.ensemble_plotters for all options):

  • 'bands': median and quantile bands (or mean and standard deviation bands, statistic='mean_std') of x, p, and q over time, per initial state or pooled, in one panel or one panel per strategy, with optional reference lines such as an equilibrium, and of quantities derived from the state (plot_ensemble_bands).

  • 'kpi': the same bands for a KPI over time (plot_ensemble_kpi).

  • 'ternary': trajectories of the runs on the simplex (plot_ensemble_ternary).

  • 'final': distribution of the strategic distributions at the final (or a given) time (plot_ensemble_final).

All plot types accept filename, figsize, fontsize, show, plot_deterministic_approximation, and ax (existing matplotlib axes to draw on, one per figure the plot would otherwise create; the figure is then neither saved, shown, nor closed).

Parameters:
  • plot_type (str) – Plot type. Defaults to ‘bands’.

  • **kwargs (Any) – Keyword arguments of the selected plot type. Unrecognized arguments raise a TypeError.

  • self (EnsembleResult)

Return type:

None

—

Supported Ensemble Plots

popgames.plotting.ensemble_plotters.plot_ensemble_bands(ensemble, variables=('x', 'p', 'q'), bands=((0.05, 0.95), (0.25, 0.75)), plot_median=True, plot_deterministic_approximation=False, initial_state=None, pool_initial_states=None, statistic='quantile', num_std=(1,), linewidth=1.0, band_alpha=None, layout='joint', ncols=3, reference=None, plot_gne=False, reference_style=None, derived=None, xlim=None, ylim=None, filename=None, figsize=None, fontsize=8, show=True, ax=None, legend=True)[source]

Plot the median and quantile bands (or the mean and standard deviation bands) of the runs over time.

One figure is generated per population for x and p, and one for q (if d > 0). Each strategy has its own color: the solid line is the median over the runs, and the shaded regions are the bands between the given quantiles (e.g., 90% and 50% of the runs at each time with the default bands). With statistic='mean_std', the solid line is the mean instead, and the bands are the mean plus or minus num_std standard deviations.

With layout='joint', all the strategies of a figure share one panel. With layout='per_strategy', each strategy has its own panel (titled with the strategy), laid out in a grid of ncols columns sharing the time axis, e.g., for games with many strategies. Reference values, such as an equilibrium, are plotted as dashed horizontal lines in the color of each strategy, and the deterministic approximation as dotted lines.

Quantities derived from the state (derived), e.g., temperatures that depend on x, are plotted like the variables, after them. Their statistics are computed on the derived values of the runs (which differs from applying the function to the statistics of x if the function is nonlinear).

By default, the bands of a finite-agent ensemble only mix runs with the same initial state: if the ensemble has several initial states (groups), the figures are generated for each of them (or only for initial_state). With pool_initial_states=True, the bands mix all runs instead, e.g., to show how trajectories from many initial states converge. This is the default for deterministic ensembles (Simulator.integrate_ensemble), which have a single run per initial state.

Parameters:
  • ensemble (EnsembleResult) – The ensemble to plot.

  • variables (Sequence[str], optional) – The variables to plot, among ‘x’, ‘p’, and ‘q’. Defaults to all of them. Use [] to plot only the derived quantities.

  • bands (Sequence[tuple[float, float]], optional) – Pairs of lower and upper quantiles delimiting the bands (with statistic='quantile'). Defaults to ((0.05, 0.95), (0.25, 0.75)).

  • plot_median (bool, optional) – Whether to plot the central line: the median, or the mean with statistic='mean_std'. Defaults to True.

  • plot_deterministic_approximation (bool, optional) – Whether to plot the trajectories of the deterministic approximation (EDM-PDM) as dotted lines (when pooling several initial states, the same statistic as the central line over their trajectories). Ignored for deterministic ensembles. Defaults to False.

  • initial_state (int, optional) – The group (initial state) to plot, see EnsembleResult.groups. Defaults to None, in which case all groups are plotted. Cannot be combined with pool_initial_states=True.

  • pool_initial_states (bool, optional) – Whether the bands mix the runs of all initial states, in a single set of figures. Defaults to None, in which case it is True for deterministic ensembles and False otherwise.

  • statistic (str, optional) – ‘quantile’ for the median and quantile bands, or ‘mean_std’ for the mean and bands of plus or minus num_std (population) standard deviations. Note that the latter may leave the feasible region, e.g., become negative. Defaults to ‘quantile’.

  • num_std (Sequence[float], optional) – The widths of the bands in standard deviations (with statistic='mean_std'). Defaults to (1,).

  • linewidth (float, optional) – Line width of the central line. Defaults to 1.

  • band_alpha (float | Sequence[float], optional) – Opacity of the bands: one value for all of them, or one per band (widest first). Defaults to None, in which case 0.15 for the widest band, 0.25 for the next one, etc.

  • layout (str, optional) – ‘joint’ for one panel per figure, or ‘per_strategy’ for one panel per strategy. Defaults to ‘joint’.

  • ncols (int, optional) – Number of columns of the grid of panels (with layout='per_strategy'). Defaults to 3.

  • reference (dict[str, np.ndarray], optional) – Reference values plotted as dashed horizontal lines, per variable or derived quantity, e.g., {'x': x_star} with x_star of shape (n, 1). A scalar is used for all entries, e.g., {'T': 30.0}. Defaults to None.

  • plot_gne (bool, optional) – Whether to plot the GNE (if one is found) as the reference of x. Cannot be combined with reference['x']. Defaults to False.

  • reference_style (dict, optional) – Keyword arguments of matplotlib.axes.Axes.axhline overriding the style of the reference lines (dashed, in the color of each entry), e.g., {'color': 'black', 'linestyle': 'dotted'}. Defaults to None.

  • derived (dict[str, Callable[[SimpleNamespace], np.ndarray]], optional) – Quantities derived from the state, by name (a short symbol, used in the labels, e.g., 'T'): functions mapping a run (see EnsembleResult.apply) to an array of shape (m, K), one row per entry. Defaults to None.

  • xlim (tuple[float, float], optional) – Limits of the time axis. Defaults to None.

  • ylim (dict[str, tuple[float, float]], optional) – Limits of the vertical axis per variable or derived quantity, e.g., {'x': (0, 1)}. Defaults to None.

  • filename (str, optional) – If provided, each figure is saved with the variable and population (and the group, if there are several and they are not pooled) appended to the file name, e.g., bands_x_1.pdf or bands_x_1_x0_2.pdf. Defaults to None.

  • figsize (tuple[float, float], optional) – Figure size. Defaults to None, in which case (4, 2) is used per panel.

  • fontsize (int, optional) – Font size. Defaults to 8.

  • show (bool, optional) – Whether to show the figures. Defaults to True.

  • ax (Axes | Sequence[Axes], optional) – Existing matplotlib axes to draw on, one per panel that would otherwise be generated, in the order of the initial states (unless pooled) and, for each one, of x (per population), p (per population), q, and the derived quantities (and of the entries, with layout='per_strategy'), e.g., the array of axes from plt.subplots(2, 3). The figures are then neither saved, shown, nor closed. Defaults to None.

  • legend (bool, optional) – Whether to draw the legend(s). If False, the entries remain available through ax.get_legend_handles_labels(), e.g., for one legend shared by several plots (see popgames.plotting.add_shared_legend). Defaults to True.

Return type:

None

popgames.plotting.ensemble_plotters.plot_ensemble_final(ensemble, t=None, bins=20, alpha=0.5, plot_deterministic_approximation=False, plot_gne=True, filename=None, figsize=None, fontsize=8, show=True, ax=None, legend=True)[source]

Plot the distribution of the strategic distributions of the runs at a given time (the final time by default).

One figure is generated per population: a scatter plot on the simplex for populations with 3 strategies, and histograms of the strategies otherwise (only of the first strategy for populations with 2 strategies, since the second one is determined by the first). If the ensemble has several initial states (groups), the points and histograms of each group have their own color (up to 10 groups; black otherwise), and the histograms are plotted in one figure per strategy.

Parameters:
  • ensemble (EnsembleResult) – The ensemble to plot.

  • t (float, optional) – The time (the last sampling time at or before t is used). Defaults to None, in which case the final time is used.

  • bins (int, optional) – Number of bins of the histograms. Defaults to 20.

  • alpha (float, optional) – Opacity of the points (scatter plots) or bars (histograms). Defaults to 0.5.

  • plot_deterministic_approximation (bool, optional) – Whether to mark the state of the deterministic approximation (EDM-PDM) from each initial state at the same time. Defaults to False.

  • plot_gne (bool, optional) – Whether to mark the GNE (if one is found). Defaults to True.

  • filename (str, optional) – Filename to save the figures. The population (with several populations) and the strategy (for histograms with several initial states) are appended to the file name, e.g., final_pop_1.pdf or final_pop_1_x_2.pdf. Defaults to None.

  • figsize (tuple[float, float], optional) – Figure size. Defaults to None, in which case (4, 3) is used for scatter plots on the simplex and (4, 2) for histograms.

  • fontsize (int, optional) – Font size. Defaults to 8.

  • show (bool, optional) – Whether to show the figures. Defaults to True.

  • ax (Axes | Sequence[Axes], optional) – Existing matplotlib axes to draw on, one per figure that would otherwise be generated, in the order of the populations (and, for histograms with several initial states, of the strategies). The figures are then neither saved, shown, nor closed. Defaults to None.

  • legend (bool, optional) – Whether to draw the legend(s). If False, the entries remain available through ax.get_legend_handles_labels(), e.g., for one legend shared by several plots (see popgames.plotting.add_shared_legend). Defaults to True.

Return type:

None

popgames.plotting.ensemble_plotters.plot_ensemble_kpi(ensemble, kpi_function=None, bands=((0.05, 0.95), (0.25, 0.75)), plot_median=True, plot_deterministic_approximation=False, pool_initial_states=None, statistic='quantile', num_std=(1,), linewidth=1.0, band_alpha=None, xlim=None, ylim=None, yscale='linear', filename=None, figsize=(4, 2), fontsize=8, show=True, ax=None, legend=True)[source]

Plot the median and quantile bands (or the mean and standard deviation bands) of a KPI over time.

The KPI is evaluated on each run separately (see EnsembleResult.__getitem__). If the ensemble has several initial states (groups), one band is plotted per group, with one color per group, unless they are pooled into a single band (the default for deterministic ensembles).

Parameters:
  • ensemble (EnsembleResult) – The ensemble to plot.

  • kpi_function (Callable[[SimpleNamespace], np.ndarray], optional) – Function mapping a run (with fields t, x, q, and p in the layout of Simulator.log) to the KPI over time, of shape (K,). Defaults to None, in which case the Euclidean distance to the GNE (normalized by its initial value) is used.

  • bands (Sequence[tuple[float, float]], optional) – Pairs of lower and upper quantiles delimiting the bands (with statistic='quantile'). Defaults to ((0.05, 0.95), (0.25, 0.75)).

  • plot_median (bool, optional) – Whether to plot the central line: the median, or the mean with statistic='mean_std'. Defaults to True.

  • plot_deterministic_approximation (bool, optional) – Whether to plot the KPI of the deterministic approximation (EDM-PDM). Ignored for deterministic ensembles. Defaults to False.

  • pool_initial_states (bool, optional) – Whether to plot a single band mixing the runs of all initial states. Defaults to None, in which case it is True for deterministic ensembles and False otherwise.

  • statistic (str, optional) – ‘quantile’ or ‘mean_std’, see plot_ensemble_bands. Defaults to ‘quantile’.

  • num_std (Sequence[float], optional) – The widths of the bands in standard deviations (with statistic='mean_std'). Defaults to (1,).

  • linewidth (float, optional) – Line width of the central line. Defaults to 1.

  • band_alpha (float | Sequence[float], optional) – Opacity of the bands: one value for all of them, or one per band (widest first). Defaults to None, in which case 0.15 for the widest band, 0.25 for the next one, etc.

  • xlim (tuple[float, float], optional) – Limits of the time axis. Defaults to None.

  • ylim (tuple[float, float], optional) – Limits of the vertical axis. Defaults to None.

  • yscale (str, optional) – Scale of the vertical axis. Defaults to ‘linear’.

  • filename (str, optional) – Filename to save the figure. Defaults to None.

  • figsize (tuple[float, float], optional) – Figure size. Defaults to (4, 2).

  • fontsize (int, optional) – Font size. Defaults to 8.

  • show (bool, optional) – Whether to show the figure. Defaults to True.

  • ax (Axes, optional) – Existing matplotlib axes to draw on. The figure is then neither saved, shown, nor closed. Defaults to None.

  • legend (bool, optional) – Whether to draw the legend(s). If False, the entries remain available through ax.get_legend_handles_labels(), e.g., for one legend shared by several plots (see popgames.plotting.add_shared_legend). Defaults to True.

Return type:

None

popgames.plotting.ensemble_plotters.plot_ensemble_ternary(ensemble, max_runs=50, alpha=0.2, plot_mean=False, plot_deterministic_approximation=False, plot_gne=True, filename=None, figsize=(4, 3), fontsize=8, show=True, ax=None, legend=True)[source]

Plot the trajectories of the runs on the simplex, as semi-transparent lines.

One ternary plot is generated per population with 3 strategies (other populations are skipped with a warning). If the ensemble has several initial states (groups), the plot is a phase portrait: the runs of each group have their own color (up to 10 groups; black otherwise), and the initial states are marked.

Parameters:
  • ensemble (EnsembleResult) – The ensemble to plot.

  • max_runs (int, optional) – Maximum number of runs to plot per initial state (the first ones). Defaults to 50.

  • alpha (float, optional) – Opacity of each run. Defaults to 0.2.

  • plot_mean (bool, optional) – Whether to plot the mean over the runs of each initial state. Defaults to False.

  • plot_deterministic_approximation (bool, optional) – Whether to plot the trajectory of the deterministic approximation (EDM-PDM) from each initial state. Defaults to False.

  • plot_gne (bool, optional) – Whether to plot the GNE (if one is found). Defaults to True.

  • filename (str, optional) – Filename to save the figures. With several populations, the population is appended to the file name, e.g., ternary_pop_1.pdf. Defaults to None.

  • figsize (tuple[float, float], optional) – Figure size. Defaults to (4, 3).

  • fontsize (int, optional) – Font size. Defaults to 8.

  • show (bool, optional) – Whether to show the figures. Defaults to True.

  • ax (Axes | Sequence[Axes], optional) – Existing matplotlib axes to draw on, one per population with 3 strategies. The figures are then neither saved, shown, nor closed. Defaults to None.

  • legend (bool, optional) – Whether to draw the legend(s). If False, the entries remain available through ax.get_legend_handles_labels(), e.g., for one legend shared by several plots (see popgames.plotting.add_shared_legend). Defaults to True.

Return type:

None

—

Plotting helpers

popgames.plotting.add_shared_legend(fig, axes=None, loc='upper center', ncol=None, fontsize=None, **kwargs)[source]

Draw one legend for several plots of a figure, e.g., ternary plots drawn with ax=... and legend=False.

The entries of all axes are collected (ax.get_legend_handles_labels()), keeping the first entry of each label, and drawn as a figure legend. Legends already drawn inside the axes are left as they are.

Parameters:
  • fig (Figure) – The figure.

  • axes (Axes | Sequence[Axes], optional) – The axes whose entries are collected. Defaults to None, in which case all the axes of the figure are used.

  • loc (str, optional) – Location of the legend (see matplotlib.figure.Figure.legend). Defaults to ‘upper center’.

  • ncol (int, optional) – Number of columns. Defaults to None, in which case all entries are in one row.

  • fontsize (int, optional) – Font size. Defaults to None, in which case Matplotlib’s default is used.

  • **kwargs – Further keyword arguments of matplotlib.figure.Figure.legend, e.g., bbox_to_anchor.

Returns:

The legend.

Return type:

matplotlib.legend.Legend