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:
VisualizationMixinSimulates 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
PoissonRevisionProcessinstances; 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 withnumba.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
risintegrate_edm_pdmfrom(x0_r, q0_r)over[0, T_sim], sampled at the timest_eval. The result is anEnsembleResult(withis_deterministic=Trueand no seeds), so it supports the same statistics and plots as the ensembles of finite-agent simulations fromrun_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 (seepopgames.utilities.sample_initial_states). Similarly forq0.
The number of runs
Mis 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)), andq0(shape(M, d, 1)), whereKis the number of sampling times.- Return type:
- 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
runandintegrate_edm_pdm(and ofscipy.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 strategyiover time.log.x[:, k](shape(n,)) is the strategic distribution at timelog.t[k].log.x[:, [k]](shape(n, 1)) is the same distribution as a column vector, as expected byreset,integrate_edm_pdm, and the payoff functions.
- Returns:
The log with fields
t(shape(K,)),x(shape(n, K)),q(shape(d, K)), andp(shape(n, K)), whereKis 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.,axto draw on existingmatplotlibaxes (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
seedfrom now on (as ifseedhad 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
rresets the simulator withreset(x0_r, q0_r, seed=seed_r)and runs it forT_simtime units. Its state is then sampled at the timest_eval: the value at timetis the state after the last revision event at or beforet(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, anp.random.Generator, or None to derive independent seeds for the runs, or a sequence with one seed per run (e.g.,[7] * Mto 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 (seepopgames.utilities.sample_initial_states). Similarly forq0.
The number of runs
Misnum_runsor 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 timetmay lag behind by up tolog_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)), andq0(shape(M, d, 1)), whereKis the number of sampling times.- Return type:
—
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:
EnsembleVisualizationMixinSimulations 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 bySimulator.integrate_ensemble. The arrays have one leading axis for the runs, followed by the layout ofSimulator.log:ens.x[r](shape(n, K)) is runr, withens.x[r, i]the trajectory of strategyi.ens.x[:, i](shape(M, K)) holds the trajectories of strategyiin all runs.ens.x[:, :, k](shape(M, n)) holds the strategic distributions of all runs at timeens.t[k].
Runs with the same initial state
(x0, q0)form a group (groupsandgroup_index). Statistics such asmeanandquantilepool all runs; usesubsetfor 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, seeplot_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. Runrcan be reproduced withsim.reset(ens.x0[r], ens.q0[r], seed=int(ens.seeds[r]))followed bysim.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:resetrounds 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
- 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, andpin the layout ofSimulator.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)), andp(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_pdmonce 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)), andp(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)), andp(shape(M, n)).- Return type:
SimpleNamespace
- mean()[source]¶
The mean over all runs at each sampling time (see
subsetfor the mean per initial state).- Returns:
Fields
t(shape(K,)),x(shape(n, K)),q(shape(d, K)), andp(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_plottersfor all options):'bands': median and quantile bands (or mean and standard deviation bands,statistic='mean_std') ofx,p, andqover 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, andax(existingmatplotlibaxes 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 aTypeError.self (EnsembleResult)
- Return type:
None
- quantile(quantiles)[source]¶
The quantiles over all runs at each sampling time (see
subsetfor 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, andp. For a single quantile,xhas shape(n, K)(similarly forqandp); for several quantiles, it has shape(Q, n, K), with one entry per quantile.- Return type:
SimpleNamespace
—
Visualization Mixin
- class popgames.plotting.visualization_mixin.VisualizationMixin[source]¶
Bases:
objectVisualization 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.,axto draw on existingmatplotlibaxes (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
xof 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’ (
nentries, e.g., of shape(n, 1)), ‘q’ (dentries), 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 withreference['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=3strategies.- 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
matplotlibaxes 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 (seeadd_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
matplotlibaxes 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 (seeadd_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,axto draw on an existingmatplotlibaxes (the figure is then neither saved, shown, nor closed), orlegend=Falseto leave the legend out (seepopgames.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 hasn^k=3strategies.- 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
matplotlibaxes 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 (seeadd_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)+1plots, one for each vectorx,q, andp, against time, and forxandpthe 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.,
axto draw on existingmatplotlibaxes: one per plot, in the orderx(per population),p(per population), andq(ifd > 0). The figures are then neither saved, shown, nor closed.reference(values per variable, e.g.,{'x': x_star}) andplot_gne(the GNE as the reference ofx) add dashed horizontal lines, seemake_reference_values.legend=Falseleaves the legends out (seepopgames.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, andp, 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.,
axto draw on existingmatplotlibaxes: one per plot, in the orderx_1, ..., x_n,p_1, ..., p_n, andq_1, ..., q_d. The figures are then neither saved, shown, nor closed.reference(values per variable, e.g.,{'x': x_star}) andplot_gne(the GNE as the reference ofx) add dashed horizontal lines, seemake_reference_values.legend=Falseleaves the legends out (seepopgames.plotting.add_shared_legend).
- Return type:
None
—
Ensemble Visualization Mixin
- class popgames.plotting.visualization_mixin.EnsembleVisualizationMixin[source]¶
Bases:
objectVisualization 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_plottersfor all options):'bands': median and quantile bands (or mean and standard deviation bands,statistic='mean_std') ofx,p, andqover 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, andax(existingmatplotlibaxes 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 aTypeError.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
xandp, and one forq(ifd > 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). Withstatistic='mean_std', the solid line is the mean instead, and the bands are the mean plus or minusnum_stdstandard deviations.With
layout='joint', all the strategies of a figure share one panel. Withlayout='per_strategy', each strategy has its own panel (titled with the strategy), laid out in a grid ofncolscolumns 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 onx, 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 ofxif 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). Withpool_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 withpool_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}withx_starof 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 withreference['x']. Defaults to False.reference_style (dict, optional) – Keyword arguments of
matplotlib.axes.Axes.axhlineoverriding 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 (seeEnsembleResult.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.pdforbands_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
matplotlibaxes to draw on, one per panel that would otherwise be generated, in the order of the initial states (unless pooled) and, for each one, ofx(per population),p(per population),q, and the derived quantities (and of the entries, withlayout='per_strategy'), e.g., the array of axes fromplt.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 (seepopgames.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
tis 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.pdforfinal_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
matplotlibaxes 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 (seepopgames.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, andpin the layout ofSimulator.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
matplotlibaxes 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 (seepopgames.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
matplotlibaxes 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 (seepopgames.plotting.add_shared_legend). Defaults to True.
- Return type:
None
—
Plotting helpers
Draw one legend for several plots of a figure, e.g., ternary plots drawn with
ax=...andlegend=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