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

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. 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 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)[source]

Bases: EnsembleVisualizationMixin

Finite-agent simulations sampled at common times, e.g., from the same initial state with different seeds, or from different initial states.

Ensembles are created by Simulator.run_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.

Parameters:
  • simulator (Simulator)

  • t (np.ndarray)

  • x (np.ndarray)

  • q (np.ndarray)

  • p (np.ndarray)

  • seeds (np.ndarray)

  • x0 (np.ndarray)

  • q0 (np.ndarray)

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,). 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

x0

The initial strategic distribution of each run, of shape (M, n, 1). 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

simulator

The simulator that produced the runs.

Type:

Simulator

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.

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 of x, p, and q over time (plot_ensemble_bands).

  • 'kpi': median and quantile bands of 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, and plot_deterministic_approximation.

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. 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_ternary_plot_multi_population(simulator, scale=30, fontsize=8, figsize=(4, 3), plot_edm_trajectory=False, filename=None, show=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.

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)[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.

Return type:

None

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

None

Parameters:
  • simulator (Simulator)

  • plot_deterministic_approximation (bool)

  • kwargs (dict[str, Any])

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.

  • 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.

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.

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 of x, p, and q over time (plot_ensemble_bands).

  • 'kpi': median and quantile bands of 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, and plot_deterministic_approximation.

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, xlim=None, ylim=None, filename=None, figsize=(4, 2), fontsize=8, show=True)[source]

Plot the median and quantile 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).

The bands 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).

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.

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

  • plot_median (bool, optional) – Whether to plot the median. Defaults to True.

  • plot_deterministic_approximation (bool, optional) – Whether to plot the trajectories of the deterministic approximation (EDM-PDM) as dotted lines. 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.

  • 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, 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) 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 (4, 2).

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

  • show (bool, optional) – Whether to show the figures. 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)[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.

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, xlim=None, ylim=None, yscale='linear', filename=None, figsize=(4, 2), fontsize=8, show=True)[source]

Plot the median and quantile 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.

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. Defaults to ((0.05, 0.95), (0.25, 0.75)).

  • plot_median (bool, optional) – Whether to plot the median. Defaults to True.

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

  • 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.

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)[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.

Return type:

None