AnyLogic
Expand
Font size

Agent API

Parameters
Function Description
<T> T getParameter(String name) Returns the value of the parameter with the given name.
Throws an error if there is no parameter with the given name.

name — name of the static parameter
String[] getParameterNames() Returns an array that contains the names of all static parameters.
boolean setParameter(String name, Object value, boolean callOnChange) Sets the given value to the parameter with the given name. Returns true if the operation was successful; otherwise, returns false.

name — name of the static parameter
value — new value
callOnChange — pass true to enable calling additional custom code on parameter value change
void setParametersToDefaultValues() Sets all static parameters to their default values. This function is designed to be used in custom experiments for easier setup of the top-level agent in certain situations.
void markParametersAreSet() Use this function to mark agents created with no-argument constructor as having all the parameters set. This will prevent agents from parameter initialization at the first place where they are sent (in library blocks, populations etc.).
Dimensions

These functions are used by elements that require knowing the agent's dimensions during processing, for example, conveyors.

Function Description
void setDimensions(double lengthInMeters, double widthInMeters, double heightInMeters) Sets the length, the width, and the height of the agent in meters.

lengthInUnits — new value of agent's length
widthInUnits — new value of agent's width
heightInUnits — new value of agent's height
void setDimensions(double lengthInUnits, double widthInUnits, double heightInUnits, LengthUnits units) Sets the length, the width, and the height of the agent in given units.

lengthInUnits — new value of agent's length
widthInUnits — new value of agent's width
heightInUnits — new value of agent's height
units — a constant defining the length units
double getHeight() Returns the height of the agent in meters.
double getHeight(LengthUnits units) Returns the height of the agent in given units.

units — a constant defining the length units
void setHeight() Sets the height of the agent in meters.
void setHeight(double heightInUnits, LengthUnits units) Sets the height of the agent in given units.

heightInUnits — new value of agent's height
units — a constant defining the length units
double getLength() Returns the length of the agent in meters.
double getLength(LengthUnits units) Returns the length of the agent in given units.

units — a constant defining the length units
void setLength() Sets the length of the agent in meters. This only affects the agents handled by the blocks of the Process Modeling Library and Material Handling Library. To change the length of pedestrians, cars and other library-specific agents, use the library-specific API of these agents.
void setLength(double lengthInUnits, LengthUnits units) Sets the length of the agent in given units. This only affects the agents handled by the blocks of the Process Modeling Library and Material Handling Library. To change the length of pedestrians, cars and other library-specific agents, use the library-specific API of these agents.

lengthInUnits — new value of agent's length
units — a constant defining the length units
double getWidth() Returns the width of the agent in meters.
double getWidth(LengthUnits units) Returns the width of the agent in given units.

units — a constant defining the length units
void setWidth() Sets the width of the agent in meters.
void setWidth(double widthInUnits, LengthUnits units) Sets the width of the agent in given units.

widthInUnits — new value of agent's width
units — a constant defining the length units
Animation
Function Description
Color getColor() Returns the color of the agent's default animation shape. The color may be set using setColor(Color) function, or otherwise it will be chosen randomly.
In case of custom agent type, use getFillColor() or any similar function of the shape.
void setColor(Color color) Sets the color of the agent's default animation shape. Applies if the agent was created by a Source (PedSource, etc.) block with the "New agent" (“New pedestrian”, etc.) property set to the default "Agent" option. Also applies if the agent was created using the new Agent() constructor.
In case of custom agent type, use setFillColor() or any similar function of the shape.

color — new color
void highlight(boolean yes) Turns on/off highlighting of this agent animation.

yes — a boolean value. Pass true to turn on the highlighting; pass false to turn it off.
Scale
Function Description
Scale getScale() Returns the scale used by the space of this agent. The default scale is 10 pixels per meter.
double toLengthUnits(double lengthInPixels, LengthUnits units) Converts the given length in pixels to the length in length units using the scale of this agent that acts as "space".

lengthInPixels — length in pixels; units — a constant defining the length units
double toPixels(double lengthInUnits, LengthUnits units) Converts the length in the given length units to length in pixels using the scale of this agent that acts as "space".

lengthInUnits — length in length units; units — a constant defining the length units
Agent in flowchart
Function Description
FlowchartBlock currentBlock() Returns the current flowchart block this agent is being processed in.
double getBlockEnterTime() Returns the time when the agent entered the flowchart block where it currently resides. If the agent hasn't entered the flowchart yet, returns Double.NaN, which indicates that the result of the function call is invalid.
double getFlowchartEntryTime() Returns the time when the agent entered the first block in the flowchart. If the agent hasn't entered the flowchart yet, returns Double.NaN, which indicates that the result of the function call is invalid.
Resources
Function Description
<T extends Agent> List<T> resourceUnits() Returns the list of resource units seized by the agent or an empty list if no resource units have been seized.
Agent resourceUnitOfPool(Agent pool) Returns the first occurrence of a resource unit from the given ResourcePool block among the seized resource units, or null if no units were found.

pool — ResourcePool block
<T extends Agent> List<T> resourceUnitsOfPool(Agent pool) Returns the list of resource units currently seized by this agent from the given ResourcePool block.

pool — ResourcePool block
<T extends Agent> List<T> resourceUnitsOfSeize(Agent seize) Return the list of resource units currently seized by this agent in the given Seize block.

seize — Seize block
Communication

The information on Agent API in charge of agent communication is described extensively in the article Communication between agents.

Connections
Function Description
<T extends Agent> List<T> getConnections() Returns a collection of agents connected to this agent (bi-directionally) or an empty collection if there are no connections at all. You should not modify this collection.
int getConnectionsNumber() Returns the number of agents connected to this agent.
Agent getConnectedAgent(int index) Returns the connected agent with the given index.

index — index of the connected agent
Agent getRandomConnectedAgent() Returns a randomly chosen connected agent.
boolean isConnectedTo(Agent a) Checks whether this agent is connected to the given agent. If they are connected, returns true; otherwise, returns false.

a — another agent
boolean connectTo(Agent a) Creates a bi-directional connection between this agent and the given agent and returns true. Throws an error if you try to connect the agent to itself. Does nothing and returns false if these agents are already connected.

a — another agent
void disconnectFrom(Agent a) Disconnects this agent from the given agent.

a — another agent
void disconnectFromAll() Disconnects the agent from all other agents.
Connection network
Function Description
NetworkType getNetworkType() Returns the network type. Note that this type has not necessarily been applied.
double getNetworkConnectionRange() Returns the range of agent connections. Applies to all in range network. In case of GIS space, the range is measured in meters.
double getNetworkConnectionsPerAgent() Returns the average (or exact) number of connections per agent. Applies to random, ring lattice and small world networks.
double getNetworkNeighborLinkProbability() Returns the probability of an agent connection being a neighbor. Applies to small world network.
int getNetworkScaleFreeM() Returns the number of connections in a scale free network.
void applyNetwork() Discards all existing connections and establishes a new connection network according to the current network settings.
void applyNetwork(Random r) Discards all existing connections and establishes new connection network according to the current network settings, using the given random number generator, if required by network type.
void setNetworkAllInRange(double connectionRange) Sets network type to the one when agents are connected if the distance between them is less or equal to the given connectionRange. This network type is only possible in continuous space. Call applyNetwork() to actually create network connections.

connectionRange — maximum distance between agents
void setNetworkRandom(double connectionsPerAgent) Sets network type to random with the given average number of connections per agent. Call applyNetwork() to actually create network connections.

connectionsPerAgent — average number of connections per agent
void setNetworkRingLattice(int connectionsPerAgent) Sets network type to ring lattice. All agents are organized in a ring in their natural order and each agent is connected to the given number of closest neighbors. Call applyNetwork() to actually create network connections.

connectionsPerAgent — number of connections per agent (even)
void setNetworkScaleFree(int m) Sets the network type to scale free. Scale free network is constructed according to Barabasi, A.L. and R. Albert. 1999. Emergence of scaling in random networks. Science 286(5439): 509-512. Call applyNetwork() to actually create network connections.

m — the number of connections in the network. The agent with index m will most likely be a hub.
void setNetworkSmallWorld(int connectionsPerAgent, double neighborLinkProbability) Sets network type to small world. Small world network can be obtained from a ring lattice by rewiring some links to long-distant links. Call applyNetwork() to actually create network connections.

connectionsPerAgent — number of connections per agent (even)
neighborLinkProbability — probability of connection to neighbors
void setNetworkUserDefined() Sets network type to user-defined. As a result, the subsequent call of applyNetwork() will do nothing. This is a default network type.
Space
Function Description
SpaceType getAgentSpaceType() Returns agent space type, if this object is an agent that has spatial information. Returns SPACE_UNDEFINED if no agent spatial information is defined.

SpaceType getEnvironmentSpaceType() Returns the agent space type, if this object is an environment that has spatial information. Returns SPACE_UNDEFINED if no environment spatial information is defined.
Agent getSpace() Returns the agent representing the space this agent lives in.
void setSpace(Agent space) Sets the space for the agent. Shouldn't be called for moving agents. Coordinates and rotations remain unchanged.

space — the agent representing the space this agent will live in
void setupSpace(AbstractShapeGISMap gisMap) Sets the environment to have GIS space based on the given gisMap. This function should be called only when the environment is empty. Throws an error if the space type of the environment is not GIS.

gisMap — the GIS map to use in this environment; shouldn't be null
void setupSpace(double width, double height) Sets the space to the given dimensions. The dimensions are used only when various layouts are applied and do not restrict the location or movement of the agents. This function should be called only when the environment is empty.

width — the width of the space
height — the height of the space
void setupSpace(double width, double height, double zHeight) Sets the space to the given dimensions. The dimensions are used only when various layouts are applied and do not restrict the location or movement of the agents. This function should be called only when the environment is empty.

width — the width of the space
height — the height of the space
zHeight — the height of the space along Z-axis
void setupSpace(double width, double height, int rows, int columns, NeighborhoodType neighborhoodType) Sets the space type to discrete with the given dimensions and neighborhood type. A cell in such environment will have a size of (width/columns) by (height/rows). This function should be called only when the environment is empty.

width — the width of the space
height — the height of the space
rows — the number of rows in the space
columns — the number of columns in the space
neighborhoodType — the type of neighborhood (Euclidean, Moore)
Movement

An extensive overview of Agent API in charge of movement is given in the Agent movement article.

Networks
Function Description
INetwork[] getNetworks() Returns an array of networks located in this agent or an empty array.
ConveyorNetwork[] getConveyorNetworks() Returns an array of conveyor networks located in this agent or an empty array.
RailwayNetwork[] getRailwayNetworks() Returns an array of railway networks located in this agent or an empty array.
RoadNetwork[] getRoadNetworks() Returns an array of road networks located in this agent or an empty array.
INode getNetworkNode() Returns the network node this agent is located in currently; actual for agents in continuous space.
Levels
Function Description
getLevel() Returns the level this agent lives in; actual for agents in continuous space.
Level[] getLevels() Returns an array of levels located in this agent or an empty array.
setLevel(Level level) Sets this agent to live in the given level; actual for agents in continuous space.

level — the level this agent will live in
Statechart
Function Description
boolean inState(IStatechartState<?,?> state) Returns true if the corresponding statechart of this agent is at the specified state, i.e. exactly in the state for a simple state and in one of its inner states for a composite state.

state — the state
Change notification
Function Description
void onChange() Notification to the agent that means "some of your data may have changed during this event". Possible causes are:
1. Re-evaluation of conditions in events and statechart transitions with Condition triggers
2. Re-calculation of rates in events and statechart transitions with Rate triggers
By default this function is called if the agent originates an event or if a message is received by one of its ports. This can be prevented by calling nothingChanged().
You can also call this function manually if you want a particular agent to notice the change even if it had no events.
void nothingChanged() If called during an event execution, prevents the engine from calling onChange() of the agent that originated the event. Has effect only within one event. Does not affect other agents where the user may have manually called onChange() or it got called by ports, etc.
Agents as containers

By default, every agent has an internal collection contents() similar to containers created in Batch and Pickup blocks of Process Modeling Library. The functions listed in this section help you add other agents to contents() and remove them as you see fit.

Function Description
<T extends Agent> List<T> contents() Returns the list of agents that are stored in the agent's internal contents() collection.
addAgentToContents(Agent agent) Adds the given agent to the agent's internal contents() collection.

agent — the agent that is added to the internal collection
removeAgentFromContents(Agent agent) Removes the given agent from the agent's internal contents() collection.

agent — the agent that is removed from the internal collection
Synchronization steps
Function Description
boolean areStepsEnabled() Tests whether the time steps are enabled. If time steps are enabled, returns true. Otherwise, returns false.
void enableSteps(double stepDuration) Enables discrete time steps of the given duration.

stepDuration — duration of the time step
void disableSteps() Disables time steps.
Model execution control
Function Description
boolean runSimulation() This is an engine command that is applicable only in PAUSED state. In other states does nothing and returns false.
It puts the engine into RUNNING state and then starts the model execution in a separate thread. The execution may discontinue due to the one of the following reasons:
  • there are no more events to execute
  • the predefined model execution time has run out
  • pause() was called
  • top-level agent has been destroyed
  • exception occurred during event execution or agent destruction
This function should never be called from the model execution thread!
By the time this method finishes, then engine may already be in PAUSED, FINISHED, or ERROR state.
boolean pauseSimulation() This is an engine command that is applicable only in RUNNING state. In other states it does nothing and returns false.
This function puts the engine into PLEASE_WAIT state and then sets a flag that, when tested by the engine, causes it to pause after completing the current event execution. Further behavior depends on context where this method is called:
  • When this function is called from the model execution thread, from control action code, or from on-click code of a shape, it returns true immediately. The model is finished right after the current event execution.
  • When this function is called from other locations (e.g. the user-defined concurrent thread), it waits for the model execution thread to terminate and returns true.
By the time this method finishes, the engine may be in PAUSED, FINISHED, or ERROR state.
boolean stopSimulation() This is an engine command that is applicable only in any non-IDLE state (in IDLE state does nothing and returns false.
If the state is RUNNING, the function sets a flag that, when tested by the model execution thread, causes it to terminate. Further behavior depends on context where this function is called:
  • When this function is called from the model execution thread, or from control action code, or from on-click code of a shape, it returns true immediately, leaving the model in PLEASE_WAIT state. The model is stopped and destroyed some time later (After Simulation Run code of an experiment or On Destroy code of the top-level agent may be used to handle this moment.
  • When this function is called from other locations (e.g. the user-defined concurrent thread), it waits for the model execution thread to terminate and then destroys the model (calls root.onDestroy()) and forgets it. Then it puts the engine into IDLE state and returns true.
boolean finishSimulation() This is an engine command that is applicable only in RUNNING or PAUSED state. In other states it does nothing and returns false.
The command sets a flag that, when tested by the engine, causes it to finish after completing the current event execution. Further behavior depends on the context where this function is called:
  • When this function is called from the model execution thread, control action code, or from on-click code of a shape, it returns true immediately. The model is finished right after the current event execution (After Simulation Run code of an experiment may be used to handle this moment).
  • When this function is called from other locations (e.g. from the user-defined concurrent thread), the function waits for the model execution thread to terminate and returns true.
By the time this function is executed, the engine may be in FINISHED or ERROR state.
Error signaling
Function Description
RuntimeException error(Throwable cause, String errorText) Signals an error during the model run by throwing a RuntimeException with errorText preceded by the agent full name. This function never returns, it throws runtime exception by itself. The return type is defined for the cases when you want to use the following form of call: throw error(my message);

cause — the cause (which will be saved for more detailed message), may be null
errorText — the text describing the error that will be displayed
RuntimeException errorInModel(Throwable cause, String errorText) Signals a model logic error during the model run by throwing a ModelException with specified error text preceded by the agent full name. This function never returns, it throws runtime exception by itself. The return type is defined for the cases when you want to use the following form of call: throw errorInModel(my message);
This function differs from error() in the way of displaying error message: model logic errors are "softer" than other errors, they happen in the models and signal the modeler that the model might need some parameter adjustments. Examples: "agent was unable to leave the flowchart block because the following block was busy", "insufficient capacity of pallet rack", etc.

cause — the cause (which will be saved for more detailed message), may be null
errorText — the text describing the error that will be displayed
void warning(String warningText) Signals a warning during the model run with warningText preceded by the agent full name.
This function checks against numerous warnings output:
  • When multiple warnings have the same warningText, only the first 10 of them are displayed.
  • When more than 1000 warnings with different warningText occur, all the subsequent warnings (including new occurrences of those in the first 1000) won't be displayed.
  • Be careful with using dynamically changing warningText (e.g. listing names of agents). For these cases we recommend that you use warning(warningTextFormat, args).
void warning(String warningTextFormat, Object ... args) Signals a warning during the model run with warningText preceded by the agent's full name.
This method checks against numerous warnings output:
  • When multiple warnings have the same warningTextFormat, only the first 10 of them are displayed.
  • It is safe to raise numerous warnings with the same format string (which defines the warning type) but if args vary, AnyLogic will display only the first 10 warnings of each warning type.
  • When more than 1000 warnings with different warningTextFormat occur, all the subsequent warnings (including new occurrences of those in the first 1000) won't be displayed.
Don't use dynamically changing warningTextFormat (e.g. listing names of agents), use args instead.
General information about agent
Function Description
int getId() Returns the unique identifier of this agent in the context of the model run.
String getName() Returns the name of this agent, i.e. the name of its instance in the owner object with the index in square brackets for replicated objects. For the top-level agent returns root. For default population, the population name is <population>.
String getFullName() Returns the name of the agent prefixed by the path from the top-level agent to this one.
String agentInfo() Returns basic information about the agent:
  • Whether agent's environment has been set
  • Current x, y, z-coordinates of the agent
  • Horizontal and vertical rotation of the agent in radians
  • Agent's movement speed
  • Whether the agent is currently moving or not
  • Agent's connections
String toString() Returns textual information on the agent (possibly, multiple lines). Use this function if you want to display information about an agent in the inspect window during the model run. To customize the function's output, go to the Advanced section of agent type properties and click Create toString() function with parameters. In the properties of the created function you can edit the function's body to suit your needs.
Advanced
Function Description
void create() Creates the agent's embedded objects and calls the user-defined functions: onBeforeCreate() at the beginning and onCreate() at the end.
This function is called after the agent has been constructed and its parameters have been setup by the owner object. If there are any embedded objects, doCreate() function should be implemented in subclass.
void createAndStart(Agent anyAgent) Assigns the owner of the agent to the top-level agent of the model, creates the internal structure of the agent (internally embedded agents, statecharts etc.) and starts it (this way the agent's statechart and events start living).
This function should be called for all agents custom-created in modeler's Java code with no-argument constructor.
Do not call this function for any agents created in usual way in the AnyLogic IDE and for agents created in AnyLogic library blocks (like Source, PedSource, etc.).

anyAgent — any valid agent of the model. You need to obtain top-level agent of the model which will become the true 'owner' of the created agent. It shouldn't be null and should have a getEngine() reference to a valid Engine.
<T extends AgentExtension> T ext(Class<T> c) Returns an extension of the given type. Creates the extension if it doesn't exist yet. In some cases tryExt() function might be useful, e.g. if you simply need to test whether the object has any extensions, without implicit creation.
When you define your custom extension class you should register it.
This function may throw an error if the requested extension is incompatible with extensions this object already has (e.g. you requested "Discrete space Agent" while the object already has "Continuous space Agent" extension).
Users shouldn't store the reference to the returned extension. Instead, they should store the reference to the underlying agent and, if needed, call this function to obtain the extension. The reason for this limitation is that the agent, at any time, may get another extension which could override some methods implemented in the previously added extension.
c — extension type. Use one of EXT_* constants or your custom extension class (if defined)
<T extends AgentExtension> tryExt(Class<T> c) Returns an extension of the given type only if this object already contains such extension. Returns null when no such extension is defined.

c — extension type. Use one of EXT_* constants or your custom extension class (if defined)
How can we improve this article?