Global State

Last updated on 6th May 2024

The global state is an object that can be read by all agents. If a model doesn't need global variables, the model and all of its agents must be parameterized with the GlobalState type to compile correctly. If a model does need global variables, create a class for those global variables which extends GlobalState, then parameterize the model and its agents with that type.

// Model and agent using GlobalState.
public class MyModel extends AgentBasedModel<GlobalState> {}
public static final class MyAgent extends Agent<GlobalState> {}

// Custom globals class, with model and agent using this custom class.
public static final class MyGlobals extends GlobalState {
	public float preference = 0.35f;
public class MyModel2 extends AgentBasedModel<MyGlobals> {}
public static final class MyAgent2 extends Agent<MyGlobals> {}

Use the getGlobals() function, which is part of the GlobalState, to get global values and update them as necessary.

Modifying Globals via Agents

Do not attempt to change the values of globals from inside agents. Since agent actions happen in parallel, updating global values from agents may result in unexpected behavior. For best practices you should either update these values via a different function called by step, or if you wish to handle agent information via a singular agent that will receiving messages from desired agents and update separately to avoid conflicts.

Annotations can either set global state values from the console or report those values to the console.

public static final class MyGlobals extends GlobalState {
   @Input public float preference = 0.35f;

Setting Globals During Setup

Globals allows you to define variables that can be accessed and modified by both the model and agents within the system. However, during the setup process when you are creating agents via an injector, you should not by modifying globals. This is due to Java 8 lambda's. If you wish to properly modify Globals, make sure it is part of the message passing action of an agent, or make usage of an accumulator.