Plots#
Visualization Module#
This module provides visualization tools for analyzing and understanding the dynamics of adaptive environments and agent interactions for influencer games. It includes plotting utilities for various domains (1D, 2D, and simplex) and supports visualizing agent positions, gradients, influence distributions, and bifurcation dynamics.
The module is designed to work with the AdaptiveEnv class and provides a framework for creating visual representations of agent behaviors in influencer game environments.
Dependencies:#
InflGame.utils
InflGame.kernels
InflGame.domains
Usage:#
The Shell class can be used to visualize the results of simulations performed using the AdaptiveEnv class. It supports various visualization types, including position plots, gradient plots, probability plots, and bifurcation plots.
Example:#
from InflGame.adaptive.visualization import Shell
import torch
import numpy as np
# Initialize the Shell
shell = Shell(
num_agents=3,
agents_pos=np.array([0.2, 0.5, 0.8]),
parameters=torch.tensor([1.0, 1.0, 1.0]),
resource_distribution=torch.tensor([10.0, 20.0, 30.0]),
bin_points=np.array([0.1, 0.4, 0.7]),
infl_configs={'infl_type': 'gaussian'},
learning_rate_type='cosine_annealing',
learning_rate=[0.0001, 0.01, 15],
time_steps=100,
domain_type='1d',
domain_bounds=[0, 1]
)
# Set up the adaptive environment
shell.setup_adaptive_env()
# Plot agent positions
fig = shell.pos_plot()
fig.show()
Classes
- class InflGame.adaptive.visualization.Shell(num_agents, agents_pos, parameters, resource_distribution, bin_points, infl_configs={'infl_type': 'gaussian'}, learning_rate_type='cosine_annealing', learning_rate=[0.0001, 0.01, 15], time_steps=100, fp=0, infl_cshift=False, cshift=None, infl_fshift=False, Q=None, domain_type=None, rect_X=None, rect_Y=None, rect_positions=None, resource_grid=None, domain_bounds=[0, 1], resource_type='na', domain_refinement=10, tolerance=1e-05, tolerated_agents=None, ignore_zero_infl=False)#
The Shell class provides a framework for simulating and visualizing adaptive dynamics in various domains (1D, 2D, and simplex). It supports gradient ascent, influence distribution calculations, and plotting utilities for analyzing agent behaviors in resource distribution environments.
Methods
analyze_near_critical_point(x_star[, ...])Perform high-resolution analysis near the theoretical critical point x*.
analyze_zero_crossings(refined_parameters, ...)Perform detailed analysis of zero crossings in the refined parameter space.
bifurcation_plot_AD_MARL(parameters_AD, ...)Create side-by-side bifurcation plots comparing Adaptive Dynamics (AD) and Multi-Agent Reinforcement Learning (MARL) approaches.
calc_direction_and_strength([...])Calculate the direction and strength of gradients for agents via interacting with
InflGame.adaptive.grad_func_env.calc_infl_dist(pos, parameter_instance)Calculate the influence distribution for agents via thier influence kernels by interacting with the class
InflGame.adaptive.grad_func_env.dist_plot(agent_id[, parameter_instance, ...])Plot the agents' influence distributions distributions via the function
calc_infl_dist.dist_pos_gif(max_frames[, x_min, y_min, ...])Plot the agents' influence distributions and their positions into a gif.
dist_pos_plot(parameter_instance[, ...])Plots the agents' influence distributions with their their positions.
equilibrium_bifurcation_plot([matrix, ...])Plots the equilibrium bifurcation for agents over a range of reach parameters.
find_and_analyze_zero_crossings(test_eval, ...)Complete workflow to find, refine, and analyze eigenvalue zero crossings.
find_zero_crossings(test_eval, parameters_list)Identify parameter values where eigenvalue real parts are close to zero.
first_order_bifurcation_plot(processed_data)Generate and plot first-order bifurcation diagram with stability analysis.
grad_plot([title_ads, save, name_ads, font, ...])Plots the gradients of agents as the lines versus time.
jacobian_stability_fast(...[, ...])Calculate the stability of the symmetric Nash equilibrium via analytical computation of maximum eigenvalues.
plot_3d_fixed_diagonal_view([resolution, ...])Creates a 3D plot with fixed view looking down the x=y=z diagonal line, showing gradient ascent trajectories from multiple starting points with optional parallel processing.
plot_3d_fixed_diagonal_view_gif(max_frames)Create a 3D diagonal view GIF showing gradient ascent traces over varying reach parameters.
Creates an interactive 3D plot of gradient ascent paths from multiple starting points, with paths color-coded based on the initial position's quadrant.
pos_plot([title_ads, save, name_ads, font, ...])Plots the positions of agents over gradient ascent steps.
Plot the histogram of agents' positions at equilibrium for a given reach parameter via the function
InflGame.adaptive.grad_func_env.gradient_ascent.prob_plot([position, parameters, title_ads, ...])Plot the probability distribution of agents' influence over a bin/resource point via their relative influence over that point
Set up the adaptive environment for the simulation.
Set up the bifurcation environment for parameter sweep analysis.
simple_diagonal_test_point([point])Test a single point to verify gradient ascent functionality.
three_agent_pos_3A1d([x_star, title_ads, ...])Create combined visualization showing three-agent dynamics in 3D space alongside position trajectories.
three_agent_pos_3d([x_star, title_ads, ...])Visualize dynamics for three players: demonstrates the players positions changing in time in 3-d space.
vect_plot([agent_id, parameter_instance, ...])Plot the vector field of gradients for a specific agents calculated by the function
calc_direction_and_strength.- analyze_near_critical_point(x_star, padding=0.01, num_points=50)#
Perform high-resolution analysis near the theoretical critical point x*.
- Parameters:
x_star (torch.Tensor) – Theoretical critical point.
padding (float) – Range to examine on either side of x*.
num_points (int) – Number of parameter points to examine.
- Returns:
Analysis results focused on the critical point.
- Return type:
dict
- analyze_zero_crossings(refined_parameters, refined_eval, x_star=None)#
Perform detailed analysis of zero crossings in the refined parameter space.
- Parameters:
refined_parameters (torch.Tensor) – Tensor of refined parameter values.
refined_eval (torch.Tensor) – Tensor of eigenvalues at refined parameters.
x_star (Optional[torch.Tensor]) – Theoretical critical point (if available).
- Returns:
Dictionary of analysis results and figure handles.
- Return type:
dict
- bifurcation_plot_AD_MARL(parameters_AD, parameters_MARL, fontmain={'axis_size': 15, 'cbar_size': 16, 'default_size': 15, 'font_family': 'sans-serif', 'legend_size': 12, 'title_size': 18}, save=False, name_ads=[], save_types=['.png', '.svg'], paper_figure={'figure_id': 'pos_plot', 'paper': False, 'section': 'A'})#
Create side-by-side bifurcation plots comparing Adaptive Dynamics (AD) and Multi-Agent Reinforcement Learning (MARL) approaches.
This method generates comparative visualization showing how equilibrium positions change with parameter variation for both gradient-based adaptive dynamics and reinforcement learning methods.
- Parameters:
parameters_AD (dict) – Configuration dictionary for adaptive dynamics bifurcation with keys: - ‘reach_start’: Starting reach parameter value - ‘reach_end’: Ending reach parameter value - ‘reach_num_points’: Number of parameter points - ‘time_steps’: Gradient ascent iterations - ‘tolerance’: Convergence tolerance - ‘tolerated_agents’: Number of agents for convergence check - ‘plot_type’: Type of bifurcation plot - ‘refinements’: Plot refinement level - ‘title_ads’: Additional title strings - ‘cmaps’: Color map configuration - ‘cbar_config’: Colorbar configuration - ‘parallel_configs’: Parallel processing settings - ‘font’: Font configuration
parameters_MARL (dict) – Configuration dictionary for MARL bifurcation with keys: - ‘step_size’: Step size for RL environment - ‘resource’: Resource distribution type - ‘reach_start’: Starting reach parameter - ‘reach_end’: Ending reach parameter - ‘reach_parameters’: Array of reach parameter values - ‘refinements’: Plot refinement level - ‘plot_type’: Type of bifurcation plot - ‘infl_type’: Influence kernel type - ‘title_ads’: Additional title strings - ‘font’: Font configuration - ‘cbar_config’: Colorbar configuration
fontmain (dict) – Main font configuration for combined plot.
save (bool) – Whether to save the plot.
name_ads (List[str]) – Additional filename components for saving.
save_types (List[str]) – File formats for saving (e.g., [‘.png’, ‘.svg’]).
paper_figure (dict) – Paper figure configuration with ‘paper’, ‘section’, ‘figure_id’ keys.
- Returns:
Combined matplotlib figure with AD and MARL bifurcation plots.
- Return type:
matplotlib.figure.Figure
- calc_direction_and_strength(parameter_instance=0, agent_id=0, ids=[0, 1], pos=None, alt_form=False)#
Calculate the direction and strength of gradients for agents via interacting with
InflGame.adaptive.grad_func_env.- Parameters:
parameter_instance (Union[List[float], np.ndarray, torch.Tensor]) – Parameters for the influence function.
agent_id (int) – ID of the agent.
ids (List[int]) – IDs of agents of interest.
pos (Optional[torch.Tensor]) – Positions of agents.
- Returns:
The calculated gradients.
- Return type:
torch.Tensor
- calc_infl_dist(pos, parameter_instance)#
Calculate the influence distribution for agents via thier influence kernels by interacting with the class
InflGame.adaptive.grad_func_env.- Parameters:
pos (torch.Tensor) – Positions of agents.
parameter_instance (Union[List[float], np.ndarray, torch.Tensor]) – Parameters for the influence function.
- Returns:
The influence distribution.
- Return type:
torch.Tensor
- dist_plot(agent_id, parameter_instance=0, cmap='viridis', typelabels=['A', 'B', 'C'], save=False, name_ads=[], save_types=['.png', '.svg'], paper_figure={'figure_id': 'dist_plot', 'paper': False, 'section': 'A'}, font={'cbar_size': 16, 'default_size': 15, 'font_family': 'sans-serif', 'legend_size': 12, 'title_size': 18}, **kwargs)#
Plot the agents’ influence distributions distributions via the function
calc_infl_dist.- Parameters:
agent_id (int) – ID of the agent.
parameter_instance (Union[List[float], np.ndarray, torch.Tensor]) – Parameters for the influence function.
cmap (str) – Colormap for the plot.
typelabels (List[str]) – Labels for agent types.
kwargs – Additional arguments for plotting.
- Returns:
The generated plot figure.
- Return type:
matplotlib.figure.Figure
- dist_pos_gif(max_frames, x_min=None, y_min=None, output_filename='timelapse_test.gif', optimize_memory=True, dpi=100, fps=10, quality=8, verbose=False)#
Plot the agents’ influence distributions and their positions into a gif. Works for all domain types ‘1d’, ‘2d’, ‘simplex’. This is done by putting together frames of
dist_pos_plot.Optimized Performance Features: - Direct memory writing without intermediate files - Matplotlib figure recycling for memory efficiency - Optimized frame sampling - Configurable quality vs speed trade-offs
Simplex example
This is a 3 player influence distribution and position plot gif for a simplex domain`.#
- Parameters:
max_frames (int) – Maximum number of frames for the gif.
output_filename (str) – Name of the output GIF file.
optimize_memory (bool) – Whether to use memory optimization techniques.
dpi (int) – DPI for the frames (lower = faster, higher = better quality).
fps (int) – Frames per second for the GIF.
quality (int) – GIF compression quality (1-10, lower = smaller file).
verbose (bool) – Whether to print progress information.
- Returns:
The generated gif figure.
- Return type:
matplotlib.figure.Figure
- dist_pos_plot(parameter_instance, typelabels=['A', 'B', 'C'], cmap1='twilight', cmap2='viridis', title_ads=[], save=False, name_ads=[], x_min=None, y_min=None, save_types=['.png', '.svg'], paper_figure={'figure_id': 'dist_pos_plot', 'paper': False, 'section': 'A'}, font={'cbar_size': 16, 'default_size': 15, 'font_family': 'sans-serif', 'legend_size': 12, 'title_size': 18})#
Plots the agents’ influence distributions with their their positions. The influence distributions are calculated from
calc_infl_distand the position vectors are calculated viaInflGame.adaptive.grad_func_env.gradient_ascent. This function works with all 3 domain types ‘1d’,’2d’, and ‘simplex’.** In one dimension**
This is a 3 player influence distribution and position plot for a 1d domain`.#
For a simplex
This is a 2 player influence distribution and position plot for a simplex domain`.#
- Parameters:
parameter_instance (Union[List[float], np.ndarray, torch.Tensor]) – Parameters for the influence function.
typelabels (List[str]) – Labels for agent types.
cmap1 (str) – Colormap for the plot.
cmap2 (str) – Colormap for the plot.
title_ads (List[str]) – Additional titles for the plot.
save (bool) – Whether to save the plot.
name_ads (List[str]) – Additional names for saved files.
save_types (List[str]) – File types to save the plot.
- Returns:
The generated plot figure.
- Return type:
matplotlib.figure.Figure
- equilibrium_bifurcation_plot(matrix=None, reach_start=0.03, reach_end=0.3, reach_num_points=30, time_steps=100, initial_pos=None, current_alpha=0.5, tolerance=None, tolerated_agents=None, refinements=2, plot_type='heat', title_ads=[], name_ads=[], save=False, save_types=['.png', '.svg'], return_matrix=False, parallel_configs=None, cmaps={'crit': 'Greys', 'heat': 'Blues', 'trajectory': '#851321'}, font={'cbar_size': 16, 'default_size': 15, 'font_family': 'sans-serif', 'legend_size': 12, 'title_size': 18}, cbar_config={'center_labels': True, 'label_alignment': 'center', 'shrink': 0.8}, paper_figure={'figure_id': 'equilibrium_bifurcation_plot', 'paper': False, 'section': 'A'}, show_pred=False, envelope=False, optional_vline=None, verbose=True, complete=False, learning_rate=None, percentage=None)#
Plots the equilibrium bifurcation for agents over a range of reach parameters. As \(\sigma\) or as variance goes to zero for players’ influence kernels, the players begin to bifurcate. This plotting function computes the gradient ascent algorithm repetively for varying parameter values until the players reach an equilibrium.
I.e. each player will have a vector of final positions \(X_i=[x_1,x_2,\dots,x_A]\) where \(A\) is the number of test parameters and \(x_i\) is the final position of the \(i\) th player. Then the plot plots each players final position.
This is done via the function
final_pos_over_reach.1d example
This is a 5 player positions bifurcation plot for a 1d domain.#
the critical values are estimated via
InflGame.domains.one_d.utils.critical_values_plot.2d example
This is a 6 player positions bifurcation plot for a 2d domain.#
Simplex example
This is a 3 player positions bifurcation plot for a simplex.#
- Parameters:
matrix (Optional[Dict]) – Pre-computed matrix of final positions (optional, will compute if None).
reach_start (float) – Starting value of reach parameter.
reach_end (float) – Ending value of reach parameter.
reach_num_points (int) – Number of points in the reach parameter range.
time_steps (int) – Number of gradient ascent steps.
initial_pos (Union[List[float], np.ndarray]) – Initial positions of agents.
current_alpha (float) – Current alpha value.
tolerance (Optional[float]) – Tolerance for convergence.
tolerated_agents (Optional[int]) – Number of agents allowed to tolerate deviations.
refinements (int) – Refinement level for plotting.
plot_type (str) – Type of plot (‘heat’, ‘trajectory’, etc.).
title_ads (List[str]) – Additional titles for the plot.
name_ads (List[str]) – Additional names for saved files.
save (bool) – Whether to save the plot.
save_types (List[str]) – File types to save the plot.
return_matrix (bool) – Whether to return the final position matrix.
parallel_configs (Optional[Dict[str, Union[bool, int]]]) – Configuration dictionary for parallel processing with keys ‘parallel’, ‘max_workers’, ‘batch_size’.
cmaps (dict) – Color map configuration dictionary.
font (dict) – Font configuration dictionary.
cbar_config (dict) – Colorbar configuration dictionary.
paper_figure (dict) – Paper figure configuration dictionary.
show_pred (bool) – Whether to show predictions.
envelope (bool) – Whether to use envelope method.
optional_vline (Optional[List[float]]) – Optional vertical lines to add to plot.
verbose (bool) – Whether to print verbose output.
complete (bool) – Whether to compute complete bifurcation envelope.
learning_rate (Optional[List]) – Learning rate schedule.
percentage (Optional[float]) – Percentage threshold for envelope method.
- Returns:
The generated plot figure or final position matrix.
- Return type:
Union[torch.Tensor, matplotlib.figure.Figure]
- find_and_analyze_zero_crossings(test_eval, parameters_list, x_star=None, threshold=5.0)#
Complete workflow to find, refine, and analyze eigenvalue zero crossings.
- Parameters:
test_eval (torch.Tensor) – Tensor of eigenvalues.
parameters_list (torch.Tensor) – Tensor of parameter values.
x_star (Optional[torch.Tensor]) – Theoretical critical point (if available).
threshold (float) – Maximum absolute value to consider “close to zero”.
- Returns:
Analysis results dictionary.
- Return type:
Optional[dict]
- find_zero_crossings(test_eval, parameters_list, threshold=5.0)#
Identify parameter values where eigenvalue real parts are close to zero.
- Parameters:
test_eval (torch.Tensor) – Tensor of eigenvalues [n_params, n_agents].
parameters_list (torch.Tensor) – Tensor of parameter values [n_params, n_agents].
threshold (float) – Maximum absolute value to consider “close to zero”.
- Returns:
Tuple of (parameter indices, parameter values, real parts) near zero crossings.
- Return type:
Tuple[torch.Tensor, torch.Tensor, torch.Tensor]
- first_order_bifurcation_plot(processed_data, alpha_st=0, alpha_end=1, alpha_values=None, cutoff_index=None, title_ads=[], save=False, name_ads=[], font={'cbar_size': 16, 'default_size': 24, 'font_family': 'sans-serif', 'label_size': 10, 'legend_size': 12, 'table_size': 15, 'title_size': 34}, save_types=['.png', '.svg'], paper_figure={'figure_id': 'bif_diag', 'paper': False, 'section': '3_2_6'})#
Generate and plot first-order bifurcation diagram with stability analysis.
This method creates a visualization of first-order (saddle-node) bifurcations by computing equilibrium positions and their stability across a parameter range. The plot shows how equilibrium agent positions change as a resource parameter (alpha) varies, with stability indicated through
InflGame.adaptive.jacobian.jacobian_stability_fast.The method supports both original format (e.g., Gaussian kernels) and processed data format with pre-computed stability flips, making it flexible for different analysis workflows.
First-order bifurcations are characterized by the creation or annihilation of equilibrium pairs, typically visualized as branches that meet and disappear at critical parameter values.
Example Gaussian Bifurcation Diagram
First-order bifurcation plot for 5 players using symmetric Gaussian influence kernels.#
- Parameters:
infl_type (str) – Type of influence kernel (‘gaussian’, ‘beta’, etc.).
alpha_st (float) – Starting value of the resource parameter range.
alpha_end (float) – Ending value of the resource parameter range.
processed_data (Optional[dict]) – Pre-processed bifurcation data with ‘unstable_flip’, ‘stable_flip’, and optionally ‘cycles_end’.
alpha_values (Optional[np.ndarray]) – Array of alpha (parameter) values corresponding to equilibria.
cutoff_index (Optional[int]) – Index to truncate the data (useful for focusing on specific parameter ranges).
title_ads (List[str]) – Additional text to append to plot title.
save (bool) – Whether to save the plot to file.
name_ads (List[str]) – Additional text for saved filename.
font (Dict) – Font configuration dictionary with keys: ‘default_size’, ‘cbar_size’, ‘title_size’, ‘legend_size’, ‘table_size’, ‘label_size’, ‘font_family’.
save_types (List[str]) – List of file formats for saving (e.g., [‘.png’, ‘.svg’]).
paper_figure (dict) – Configuration for paper figure saving with keys: ‘paper’ (bool), ‘section’ (str), ‘figure_id’ (str).
- Returns:
The generated matplotlib figure object.
- Return type:
matplotlib.figure.Figure
- grad_plot(title_ads=[], save=False, name_ads=[], font={'cbar_size': 16, 'default_size': 15, 'font_family': 'sans-serif', 'legend_size': 12, 'title_size': 18}, save_types=['.png', '.svg'], paper_figure={'figure_id': 'grad_plot', 'paper': False, 'section': 'A'})#
Plots the gradients of agents as the lines versus time.
\[\frac{\partial}{\partial x_{(i,l)}}u_i(x)=\sum_{k=1}^{K}G_{i,k}(x_i,b_k)\frac{\partial}{\partial x_{(i,l)}}ln(f_{i}(x_i,b_k))\]Where \(x_i\) is the \(i\) th players position, \(b_k\in \mathbb{B}\) are the bin/resource points, \(B(b_k)\) is the resource value at \(b_k\), and \(G_i(x_i,b_k)\) probability of player \(i\) influencing the bin point \(b\). The gradients are calculated via
InflGame.adaptive.grad_func_env.gradient.- Parameters:
title_ads (List[str]) – Additional titles for the plot.
save (bool) – Whether to save the plot.
name_ads (List[str]) – Additional names for saved files.
save_types (List[str]) – File types to save the plot.
- Returns:
The generated plot figure.
- Return type:
matplotlib.figure.Figure
- jacobian_stability_fast(agent_parameter_instance, resource_distribution_type, resource_parameters, resource_entropy=False, infl_entropy=False)#
Calculate the stability of the symmetric Nash equilibrium via analytical computation of maximum eigenvalues.
This method analytically computes the Jacobian matrix eigenvalues at the symmetric Nash equilibrium to determine stability regions. Currently supports Gaussian and multi-variate Gaussian influence kernels.
The symmetric Nash equilibrium position is computed based on the resource distribution, and stability is assessed by examining the sign of the maximum real eigenvalue of the Jacobian.
- Parameters:
agent_parameter_instance (Union[List[float], np.ndarray]) – Parameters for the influence function (e.g., sigma for Gaussian).
resource_distribution_type (str) – Type of resource distribution (‘gauss_mix_2m’, ‘uniform’, etc.).
resource_parameters (Union[List[float], np.ndarray]) – Parameters defining the resource distribution for each test point.
resource_entropy (bool) – Whether to calculate and return entropy of resource distributions.
infl_entropy (bool) – Whether to calculate and return entropy of influence distributions.
- Returns:
Tuple containing: - List of critical parameter values (one per resource configuration) - List of resource entropies (empty if resource_entropy=False) - List of influence entropies (empty if infl_entropy=False)
- Return type:
Tuple[List[torch.Tensor], List[float], List[float]]
- Raises:
ValueError – If influence type is not ‘gaussian’ or ‘multi_gaussian’.
- plot_3d_fixed_diagonal_view(resolution=5, time_steps=10000, show_planes=True, figsize=(12, 10), seed=42, include_boundaries=True, elev=10, azim=45, num_workers=4, use_parallel=True, only_results=False, verbose=False)#
Creates a 3D plot with fixed view looking down the x=y=z diagonal line, showing gradient ascent trajectories from multiple starting points with optional parallel processing.
This method visualizes how agents starting from different initial positions converge or diverge under gradient ascent dynamics. The view is oriented to look down the main diagonal (x=y=z line) to better visualize symmetric and asymmetric equilibria. Paths are color-coded by the ordering of initial agent positions.
- Parameters:
resolution (int) – Number of test points per dimension (total points = resolution^3).
time_steps (int) – Maximum gradient ascent iterations per trajectory.
show_planes (bool) – Whether to display equality planes (x=y, y=z, x=z) for reference.
figsize (Tuple[int, int]) – Figure dimensions in inches (width, height).
seed (int) – Random seed for reproducibility of starting points.
include_boundaries (bool) – Whether to include boundary points in the analysis.
elev (int) – Elevation viewing angle in degrees (lower values look more downward).
azim (int) – Azimuth viewing angle in degrees (rotation around vertical axis).
num_workers (int) – Number of parallel worker processes.
use_parallel (bool) – Whether to use parallel processing for trajectory computation.
only_results (bool) – If True, return only the results dictionary without creating plot.
verbose (bool) – Whether to print detailed progress information.
- Returns:
Tuple of (matplotlib figure, list of trajectory result dictionaries).
- Return type:
Tuple[matplotlib.figure.Figure, List[dict]]
- plot_3d_fixed_diagonal_view_gif(max_frames, output_filename='3d_diagonal_traces.gif', resolution=5, time_steps=10000, show_planes=True, figsize=(12, 10), seed=42, include_boundaries=True, elev=10, azim=45, num_workers=4, use_parallel=True, reach_start=0.08, reach_end=0.25, optimize_memory=True, dpi=100, fps=10, quality=8, verbose=False)#
Create a 3D diagonal view GIF showing gradient ascent traces over varying reach parameters. Similar to dist_pos_gif but for 3D visualization. Works by varying the reach parameters and creating frames of
plot_3d_fixed_diagonal_view.Optimized Performance Features: - Direct memory writing without intermediate files - Matplotlib figure recycling for memory efficiency - Optimized frame sampling - Configurable quality vs speed trade-offs
- Parameters:
max_frames (int) – Maximum number of frames for the gif.
output_filename (str) – Name of the output GIF file.
resolution (int) – Resolution for point sampling in 3D plot.
time_steps (int) – Number of gradient ascent steps.
show_planes (bool) – Whether to show equality planes in 3D plot.
figsize (tuple) – Figure size for each frame.
seed (int) – Random seed for reproducibility.
include_boundaries (bool) – Whether to include boundary points in 3D plot.
elev (int) – Elevation angle for 3D view.
azim (int) – Azimuth angle for 3D view.
num_workers (int) – Number of parallel workers for 3D processing.
use_parallel (bool) – Whether to use parallel processing for 3D plots.
reach_start (float) – Starting reach parameter value.
reach_end (float) – Ending reach parameter value.
optimize_memory (bool) – Whether to use memory optimization techniques.
dpi (int) – DPI for the frames (lower = faster, higher = better quality).
fps (int) – Frames per second for the GIF.
quality (int) – GIF compression quality (1-10, lower = smaller file).
verbose (bool) – Whether to print progress information.
- Returns:
The final frame figure for display.
- Return type:
matplotlib.figure.Figure
- plot_3d_gradient_ascent_paths_interactive(resolution=5, time_steps=10000, start_color='red', end_color='green', title='3D Path of Gradient Ascent (Interactive)', show_planes=False)#
Creates an interactive 3D plot of gradient ascent paths from multiple starting points, with paths color-coded based on the initial position’s quadrant.
- Parameters:
resolution (int) – Resolution of the cube grid (points per dimension).
time_steps (int) – Maximum number of steps for gradient ascent.
start_color (str) – Color of the starting points.
end_color (str) – Color of the ending points (for converged paths).
title (str) – Plot title.
show_planes (bool) – Whether to show the equality planes (x=y, y=z, z=x).
- Returns:
Interactive 3D plot.
- Return type:
plotly.graph_objects.Figure
- pos_plot(title_ads=[], save=False, name_ads=[], font={'cbar_size': 16, 'default_size': 15, 'font_family': 'sans-serif', 'legend_size': 12, 'title_size': 18}, save_types=['.png', '.svg'], paper_figure={'figure_id': 'pos_plot', 'paper': False, 'section': 'A'})#
Plots the positions of agents over gradient ascent steps. The positions of players are calculated via the results of
InflGame.adaptive.grad_func_env.gradient_ascent- Parameters:
title_ads (List[str]) – Additional titles for the plot.
save (bool) – Whether to save the plot.
name_ads (List[str]) – Additional names for saved files.
save_types (List[str]) – File types to save the plot.
- Returns:
The generated plot figure.
- Return type:
matplotlib.figure.Figure
- position_at_equalibirum_histogram(reach_parameter=0.5, time_steps=100, initial_pos=0, current_alpha=0.5, tolerance=None, tolerated_agents=None, title_ads=[], name_ads=[], save=False, save_types=['.png', '.svg'], return_pos=False, parallel=True, max_workers=None, batch_size=None, paper_figure={'figure_id': 'position_at_equalibirum_histogram', 'paper': False, 'section': 'A'}, font={'cbar_size': 16, 'default_size': 15, 'font_family': 'sans-serif', 'legend_size': 12, 'title_size': 18})#
Plot the histogram of agents’ positions at equilibrium for a given reach parameter via the function
InflGame.adaptive.grad_func_env.gradient_ascent. This only works for ‘1d’ domains.
This is the histogram of player positions at equilibrium for 5 player game.#
- Parameters:
reach_parameter (float) – Reach parameter value.
time_steps (int) – Number of gradient ascent steps.
initial_pos (Union[List[float], np.ndarray]) – Initial positions of agents.
current_alpha (float) – Current alpha value.
tolerance (Optional[float]) – Tolerance for convergence.
tolerated_agents (Optional[int]) – Number of agents allowed to tolerate deviations.
title_ads (List[str]) – Additional titles for the plot.
name_ads (List[str]) – Additional names for saved files.
save (bool) – Whether to save the plot.
save_types (List[str]) – File types to save the plot.
return_pos (bool) – Whether to return the final positions.
parallel (bool) – Whether to use parallel processing.
max_workers (Optional[int]) – Maximum number of parallel workers (defaults to CPU count).
batch_size (Optional[int]) – Batch size for processing (auto-calculated if None).
paper_figure (dict) – Paper figure configuration dictionary.
font (dict) – Font configuration dictionary.
- Returns:
The generated plot figure or final positions.
- Return type:
Union[matplotlib.figure.Figure, Tuple[matplotlib.figure.Figure, np.ndarray]]
- prob_plot(position=[], parameters=[], title_ads=[], save=False, name_ads=[], font={'cbar_size': 16, 'default_size': 15, 'font_family': 'sans-serif', 'legend_size': 12, 'title_size': 18}, save_types=['.png', '.svg'], paper_figure={'figure_id': 'prob_plot', 'paper': False, 'section': 'A'})#
Plot the probability distribution of agents’ influence over a bin/resource point via their relative influence over that point
\[G_{i,k}(\mathbf{x},b_k)=\frac{f_{i}(x_i,b_k)}{\sum_{j=1}^{N}f_{j}(x_j,b_k)}.\]where \(f_{i}(x_i,b_k)\) is the \(i\) th players influence. The probabilities are calculated via
InflGame.adaptive.grad_func_env.prob_matrix.
This is an example of the a three player game with agents in position \([.1,.45,.9]\) . Here the the influence kernels are symmetric gaussian with with parameter (reach) \(\sigma=0.25\) .#
There can is also the option to have a fixed third party (infl_csift==True) and/or abstaining voters if (infl_fshift==True).
- Parameters:
position (np.ndarray) – Positions of agents.
parameters (np.ndarray) – Parameters for the influence function.
title_ads (List[str]) – Additional titles for the plot.
save (bool) – Whether to save the plot.
name_ads (List[str]) – Additional names for saved files.
save_types (List[str]) – File types to save the plot.
- Returns:
The generated plot figure.
- Return type:
matplotlib.figure.Figure
- setup_adaptive_env()#
Set up the adaptive environment for the simulation.
This initializes the
InflGame.adaptive.grad_func_env.AdaptiveEnvinstance with all parameters configured in the Shell constructor. The adaptive environment handles gradient ascent computation, influence calculations, and trajectory tracking.After calling this method, gradient ascent can be performed via
self.field.gradient_ascent()and results accessed throughself.field.pos_matrixandself.field.grad_matrix.
- setup_bifurcation_env()#
Set up the bifurcation environment for parameter sweep analysis.
This initializes the
InflGame.adaptive.bifurcation_analysis.BifurcationEnvinstance for computing equilibrium positions across parameter ranges. The bifurcation environment extends the adaptive environment with specialized methods for systematic parameter variation.After calling this method, bifurcation analysis can be performed via methods like
self.bif_field.final_pos_over_reach()andself.bif_field.equilibrium_bifurcation_complete().
- simple_diagonal_test_point(point=None)#
Test a single point to verify gradient ascent functionality.
This diagnostic method performs a simple gradient ascent run from a specified starting point to verify that the core optimization loop is working correctly. Useful for debugging and validation.
- Parameters:
point (Optional[torch.Tensor]) – Starting position for agents (defaults to [0.3, 0.5, 0.7] if None).
- Returns:
True if gradient ascent successfully generated a path, False otherwise.
- Return type:
bool
- three_agent_pos_3A1d(x_star=None, title_ads=[], save=False, name_ads=[], fontL={'cbar_size': 16, 'default_size': 15, 'font_family': 'sans-serif', 'legend_size': 12, 'title_size': 18}, fontR={'cbar_size': 16, 'default_size': 15, 'font_family': 'sans-serif', 'legend_size': 12, 'title_size': 18}, fontmain={'cbar_size': 16, 'default_size': 15, 'font_family': 'sans-serif', 'legend_size': 12, 'title_size': 18}, save_types=['.png', '.svg'], paper_figure={'figure_id': 'pos_plot', 'paper': False, 'section': 'A'})#
Create combined visualization showing three-agent dynamics in 3D space alongside position trajectories.
This method produces a side-by-side comparison plot for three-player games in 1D domains: - Left panel: 3D visualization of agent positions over time - Right panel: Traditional position vs. time plot
Only available for 1D domains with exactly 3 agents, as it visualizes the 3-dimensional trajectory space where each axis represents one agent’s position.
- Parameters:
x_star (Optional[float]) – Equilibrium position (computed from resource distribution if not provided).
title_ads (List[str]) – Additional title text components.
save (bool) – Whether to save the figure to file.
name_ads (List[str]) – Additional filename components for saving.
fontL (dict) – Font configuration dictionary for left (3D) panel.
fontR (dict) – Font configuration dictionary for right (position) panel.
fontmain (dict) – Font configuration dictionary for main title.
save_types (List[str]) – File formats for saving (e.g., [‘.png’, ‘.svg’]).
paper_figure (dict) – Paper figure configuration with ‘paper’, ‘section’, ‘figure_id’ keys.
- Returns:
Combined matplotlib figure with both visualizations.
- Return type:
matplotlib.figure.Figure
- Raises:
ValueError – If domain_type is not ‘1d’ or num_agents is not 3.
- three_agent_pos_3d(x_star=None, title_ads=[], name_ads=[], save=False, font={'cbar_size': 16, 'default_size': 15, 'font_family': 'sans-serif', 'legend_size': 12, 'title_size': 18}, save_types=['.png', '.svg'], paper_figure={'figure_id': 'three_players', 'paper': False, 'section': 'A'})#
Visualize dynamics for three players: demonstrates the players positions changing in time in 3-d space. Demonstrating the instability of 3-players in influencer games. Given that this function is in 3-d space for players with 1-d strategies there isn’t a way to visualize the 3 player dynamics in games with more then 1d strategy spaces. The positions of players are calculated via the results of
InflGame.adaptive.grad_func_env.gradient_ascent.
This is an example of the three player dynamics via their positions in time`.#
- Parameters:
x_star (Optional[float]) – Equilibrium position.
title_ads (List[str]) – Additional titles for the plot.
name_ads (List[str]) – Additional names for saved files.
save (bool) – Whether to save the plot.
save_types (List[str]) – File types to save the plot.
- Returns:
The generated plot figure.
- Return type:
matplotlib.figure.Figure
- vect_plot(agent_id=None, parameter_instance=None, cmap='viridis', typelabels=['A', 'B', 'C'], ids=[0, 1], pos=None, title_ads=[], save=False, name_ads=[], save_types=['.png', '.svg'], paper_figure={'figure_id': 'vect_plot', 'paper': False, 'section': 'A'}, font={'cbar_size': 16, 'default_size': 15, 'font_family': 'sans-serif', 'legend_size': 12, 'title_size': 18}, alt_form=False, **kwargs)#
Plot the vector field of gradients for a specific agents calculated by the function
calc_direction_and_strength. Currently only supports 1d domains
This is an example of the vector field for a three player game with only players 1 and 2 dynamics shown (player 3 is fixed)`.#
- Parameters:
agent_id (int) – ID of the agent.
parameter_instance (Union[List[float], np.ndarray, torch.Tensor]) – Parameters for the influence function.
cmap (str) – Colormap for the plot.
typelabels (List[str]) – Labels for agent types.
ids (List[int]) – IDs of agents of interest.
pos (Optional[torch.Tensor]) – Positions of agents.
title_ads (List[str]) – Additional titles for the plot.
save (bool) – Whether to save the plot.
name_ads (List[str]) – Additional names for saved files.
save_types (List[str]) – File types to save the plot.
kwargs – Additional arguments for plotting.
- Returns:
The generated plot figure.
- Return type:
matplotlib.figure.Figure