Utilities#

1D Utility Module#

This module provides utility functions for setting up and managing 1D domains in influencer games. It includes tools for creating color schemes, plotting critical values, and handling domain-specific configurations.

The module is designed to work with the InflGame package and supports creating structured 1D environments for simulations involving agent dynamics and resource distributions.

Dependencies:#

  • InflGame.utils

Usage:#

The critical_values_plot function can be used to plot critical values for a given resource distribution and number of agents, while the color_list_maker function generates random colors for agents.

Functions

InflGame.domains.one_d.one_utils.bifurcation_type_helper(matrix, reach_parameters, tolerance=0.01)#

Classify bifurcation types based on equilibrium structure transitions.

Identifies two types of bifurcations:

  1. Type 1 (Symmetry-breaking): Local symmetric equilibrium becomes unstable and splits into asymmetric equilibria (number of groups increases)

  2. Type 2 (Basin shift): Basins of attraction shift local grouping without increasing group count (number of groups stays same or decreases)

Parameters:
matrixdict

Dictionary containing equilibrium position matrix under key 'max'.

reach_parametersarray_like

Array of reach parameter values corresponding to equilibrium configurations.

tolerancefloat, optional

Tolerance for position grouping in equilibrium classification, by default 1e-2.

Returns:
dict

Dictionary of classified bifurcations, where each key maps to:

  • 'reach_parameter' (float): Reach parameter value at bifurcation

  • 'type' (str): Bifurcation type ('1' or '2')

  • 'classification_new' (str): New equilibrium structure after bifurcation

Notes

The classification_new field shows the equilibrium structure after bifurcation occurs. Type 1 bifurcations indicate structural instability, while Type 2 indicate basin reorganization.

InflGame.domains.one_d.one_utils.classify_equilibrium_type(positions, tolerance=0.001)#

Classify equilibrium type based on spatial grouping of agents.

Groups agents whose positions are within tolerance and returns a classification string describing the group sizes in spatial order (left to right).

Parameters:
positionsarray_like

Array of agent positions (supports both NumPy arrays and torch tensors).

tolerancefloat, optional

Tolerance for considering positions as equal, by default 1e-3.

Returns:
str

String describing equilibrium type with groups in spatial order:

  • '(n)': All \(n\) agents at the same position

  • '(n-1,1)': \(n-1\) agents grouped at lower position, 1 isolated higher

  • '(1,n-1)': 1 agent isolated at lower position, \(n-1\) grouped higher

  • '(2,1,1,2)': Groups listed left to right by position

Examples

>>> positions = np.array([0.2, 0.2, 0.5, 0.8, 0.8])
>>> classify_equilibrium_type(positions)
'(2,1,2)'
InflGame.domains.one_d.one_utils.critical_values_plot(num_agents, bin_points, resource_distribution, axis, reach_start=0.3, reach_end=0, refinements=2, crit_cs='Greys')#

Plot critical values given a resource distribution and number of agents \(t_*\) (assuming symmetric splitting).

This function calculates and visualizes critical threshold values for agent positioning in a 1D domain, using recursive symmetric splitting to determine equilibrium configurations.

Parameters:
num_agentsint

Number of agents in the system.

bin_pointsnp.ndarray

Points representing bins for resource discretization.

resource_distributiontorch.Tensor

Distribution of resources across the domain.

axisplt.Axes

Matplotlib axis object to plot on.

reach_startfloat, optional

Starting reach value for critical threshold visualization, by default 0.3.

reach_endfloat, optional

Ending reach value for critical threshold visualization, by default 0.

refinementsint, optional

Number of refinement iterations for symmetric splitting, by default 2.

crit_csstr, optional

Colormap scheme for the critical value plot, by default ‘Greys’.

Returns:
tuple

A tuple containing: - axis (plt.Axes): Updated matplotlib axis with plotted critical values - mean_for_axis (List[torch.Tensor]): List of mean values for each split level - std_divisions (List[List[float]]): List of standard deviation values at each bifurcation level

InflGame.domains.one_d.one_utils.direction_strength_1d(gradient_function, two_a, parameter_instance=0, ids=[0, 1], pos=None)#

Compute gradient strength in a 1D direction using PyTorch operations.

Evaluates the gradient function across a 2D grid to compute directional gradient strengths, useful for vector field visualization in 1D domains.

Parameters:
gradient_functioncallable

Function to compute gradients, should accept position and parameters.

two_abool

Flag indicating whether the gradient function uses a two-argument coordinate array format.

parameter_instanceUnion[list, np.ndarray, torch.Tensor], optional

Parameters for the influence function, by default 0.

idsList[int], optional

Indices of agents to compute gradients for, by default [0, 1].

postorch.Tensor, optional

Position tensor for agents, by default None.

Returns:
torch.Tensor

Computed gradient values as a flattened tensor of shape \((10000,)\) for a 100x100 grid.

InflGame.domains.one_d.one_utils.direction_strength_1d_OLD(gradient_function, two_a, parameter_instance=0, ids=[0, 1], pos=None)#

Compute gradient strength in a 1D direction (legacy NumPy implementation).

Deprecated since version This: is the original NumPy-based implementation. Use direction_strength_1d for PyTorch-based operations with autograd support.

Parameters:
gradient_functioncallable

Function to compute gradients.

two_abool

Flag indicating whether to use two-argument coordinate array format.

parameter_instancelist | np.ndarray | torch.Tensor, optional

Parameters for the gradient function, by default 0.

idslist, optional

Indices for the gradient computation, by default [0, 1].

postorch.Tensor, optional

Position tensor, by default None.

Returns:
np.ndarray

Computed gradients as a NumPy array.

InflGame.domains.one_d.one_utils.generate_constrained_2d_points(num_points=50, method='analytical_transform')#

Generate 2D points satisfying simplex projection constraints.

Generates 2D points \((x,y)\) that satisfy the constraints:

  1. \(x \in [-1/\sqrt{2}, 1/\sqrt{2}]\)

  2. \(y \in [-1/\sqrt{2}, 1/\sqrt{2}]\)

  3. \((x-y) \in [-1/\sqrt{2}, 1/\sqrt{2}]\)

These constraints ensure the points can be validly projected back to 3D simplex coordinates.

Following Influencer Games patterns:

  • Use torch tensor operations for autograd compatibility

  • State management with .clone() for torch tensors

  • Handle domain bounds properly for 1D domain type

  • Return torch.float32 tensors

  • Memory management with matrix clearing

Parameters:
num_pointsint, optional

Number of valid 2D points to generate, by default 50.

methodstr, optional

Generation method, by default ‘analytical_transform’.

  • 'analytical_transform': Transform from \((u,v)\) coordinates with analytic bounds

  • 'rejection_sampling': Random sampling with constraint rejection

  • 'grid_filtering': Grid-based approach with constraint filtering

Returns:
dict

Dictionary containing:

  • 'points_2d' (torch.Tensor): Generated 2D points of shape \((N, 2)\)

  • 'constraint_values' (torch.Tensor): Constraint check values \([x, y, x-y]\)

  • 'method' (str): Method used for generation

  • Additional metadata depending on method (success_rate, acceptance_rate, etc.)

InflGame.domains.one_d.one_utils.projection_to_3d_auto_constrained(matrix, target_bounds=(0.0, 1.0), tolerance=1e-08, max_iterations=100)#

Project 2D plane coordinates back to 3D simplex coordinates with automatic constraint satisfaction.

Uses the Moore-Penrose pseudo-inverse to compute a base 3D projection from 2D coordinates, then applies an offset along the \([1,1,1]\) direction to ensure all coordinates satisfy simplex constraints (all elements within target_bounds).

Following Influencer Games patterns:

  • Use torch tensor operations for autograd compatibility

  • State management with .clone() for torch tensors

  • Adaptive optimization to find optimal offset parameter

  • Handle single vector and batch inputs

  • Ensure consistent dtype=torch.float32 output

  • Convergence checking with project tolerance patterns

Parameters:
matrixtorch.Tensor

Input tensor of shape \((2,)\) or \((N, 2)\) containing 2D plane coordinates.

target_boundstuple, optional

Tuple \((min\_val, max\_val)\) for coordinate constraints, by default (0.0, 1.0).

tolerancefloat, optional

Convergence tolerance for constraint satisfaction, by default 1e-8.

max_iterationsint, optional

Maximum iterations for offset optimization (currently unused), by default 100.

Returns:
torch.Tensor

Projected 3D coordinates of shape \((3,)\) or \((N, 3)\) with dtype=torch.float32, all elements guaranteed to be within target_bounds.

InflGame.domains.one_d.one_utils.projection_to_plane_coordinates(matrix)#

Project 3D simplex coordinates to 2D plane coordinates using orthogonal projection.

Uses an orthogonal projection matrix to map 3D barycentric coordinates onto a 2D plane for visualization purposes. The projection preserves relative distances and orientations.

Following project patterns:

  • Use vectorized torch operations for performance

  • Handle dtype compatibility automatically

  • Maintain tensor device consistency

  • Handle single vector and batch inputs

  • Ensure consistent dtype=torch.float32 output

Parameters:
matrixtorch.Tensor

Input tensor of shape \((3,)\) or \((N, 3)\) containing 3D coordinates.

Returns:
torch.Tensor

Projected 2D coordinates of shape \((2,)\) or \((N, 2)\) with dtype=torch.float32.

InflGame.domains.one_d.one_utils.symmetric_splitting(bin_points, resource_distribution, bifurcation_count, means)#

Perform symmetric splitting of resource distribution based on means.

Recursively divides the resource distribution into symmetric regions based on bifurcation count, calculating local means for each split region.

Parameters:
bin_pointsUnion[np.ndarray, torch.Tensor]

Points representing bins for resource discretization.

resource_distributionUnion[torch.Tensor, np.ndarray]

Distribution of resources across the domain.

bifurcation_countint

Number of bifurcation levels, determines \(2^{bifurcation\_count}\) splits.

meansList[float]

List of mean values from previous bifurcation level used as boundaries.

Returns:
Tuple[List[torch.Tensor], List[torch.Tensor]]

A tuple containing: - symmetric_splits (List[torch.Tensor]): List of locally computed means for each split region - final_array (List[torch.Tensor]): Combined list of boundary means and local means