AnyLogic
Expand
Font size

Engine API

Engine provides a set of functions for accessing and modifying the model settings, controlling the model execution, and so on. If an engine function is accessed from an experiment or an agent, it must be accompanied by the getEngine(). prefix. Engine functions are vital when you write Java code for your custom experiment.

Model execution control
Function Description
boolean run() Engine command that is applicable only in PAUSED state. In other states does nothing and returns false.
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 (state: FINISHED)
  • the defined model execution time has run out (state: FINISHED)
  • pause() was called (state: PAUSED)
  • top-level agent has been destroyed (state: FINISHED)
  • exception occurred during event execution or agent destruction (state: ERROR)
This function should never be called from the model execution thread!
By the time this function finishes, then engine may already be in PAUSED, FINISHED, or ERROR state.
boolean runFast() Runs the model in the fastest possible way in the same (calling) thread. The run is done in virtual time mode regardless any settings. The function finishes in one of the following cases:
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:
  • illegal engine state when it is called (returns false, in all other cases - returns true)
  • there are no more events and equations to execute (state: FINISHED)
  • the defined model execution time has run out (state: FINISHED)
  • pause() was called (state: PAUSED)
  • finish() was called (state: FINISHED)
  • top-level agent has been destroyed (state: FINISHED)
  • exception occurred during model execution (state: ERROR)
The model is locked for both write and read during the entire run, so you should not try to display presentation of the agents, or execute any concurrent actions that may access the model.
boolean runFast(double pauseTime) Calls runFast() but pauses the model execution at the specified model time and returns true. If the model finishes (because the defined model execution time has run out or finish() method called) before the pauseTime, the function runs the model until the finish moment only. Returns false if the engine state does not allow running.

pauseTime — the time to pause the model execution
boolean pause() Engine command that is applicable only in RUNNING state. In other states it does nothing and returns false.
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 function 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 paused right after the current event execution.
  • When this function is called from other locations (e.g. from the user-defined concurrent thread), it waits for the model execution thread to terminate and returns true.
By the time this function finishes, the engine may be in PAUSED, FINISHED, or ERROR state.
boolean step() Makes at most one discrete step of the model (can be done from the PAUSED state only). Finishes in either FINISHED, ERROR or PAUSED state. Returns false if the engine state does not allow for making a step.
This function should never be called from the model execution thread!
boolean stop() Stops and destroys the model, see also finish() function, which doesn’t destroy the model.
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.
  • If this function is called during “run fast“ execution, then it simply finishes the model - you should manually take care of stopping the engine after you collect all required data from the finished model.
boolean finish() Terminates the model after execution of current event. Doesn’t destroy the model.
Engine command that is applicable only in RUNNING or PAUSED state. In other states it does nothing and returns false.
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), it 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.
double getProgress() Return the progress of the simulation: a number between 0 and 1 depending on what part of experiment is completed, or -1 if not known (i.e. the stop time is not set). In IDLE and ERROR states also returns -1.
Experiment.State getState() Returns the current state of the engine. Possible values:
  • IDLE — no model is set for execution, doing nothing
  • PAUSED — model is set and has started, ready to run or make a step
  • RUNNING — in the loop of model execution invoked by run() or runFast()
  • FINISHED — the model execution is finished successfully, but the model is not yet destroyed
  • ERROR — the model execution is finished with error, the model is not yet destroyed
  • PLEASE_WAIT —  in the process of executing a non-interruptable command like pause(), step() or stop()
The correctness is not guaranteed as the state may be modified concurrently.
Start and stop time
Function Description
double getStartTime() Returns the currently set simulation start time (in model time units) - the model time at which the simulation starts, by default it is 0.
double getStartTime(TimeUnits units) Returns the currently set simulation start time (in the specified time units) - the model time at which the simulation starts, by default it is 0.

units — constant defining the time units
java.util.Date getStartDate() Returns the date corresponding to the start time of the simulation (in local TimeZone set in the Java Virtual Machine).
double getStopTime() Returns the currently set simulation stop time (in model time units) - the model time at which the simulation should stop, or +infinity if stop time is not set.
double getStopTime(TimeUnits units) Returns the currently set simulation stop time (in the specified time units) - the model time at which the simulation the simulation should stop, or +infinity if stop time is not set.

units — constant defining the time units
java.util.Date getStopDate() Returns the date corresponding to the stop time of the simulation (in local TimeZone set in the Java Virtual Machine). Returns null if the stop time is infinity.
void setStartTime(double tstart) Sets the start time for the simulation - the initial value of the model clock. By default it is 0. Has no effect if called after the model starts running.

tstart — the simulation start time, in model time units
void setStartTime(double tstart, TimeUnits units) Sets the start time for the simulation - the initial value of the model clock. By default it is 0. Has no effect if called after the model starts running.

tstart — the simulation start time, in the given time units
units — constant defining the time units
void setStartDate(java.util.Date date) Sets the date corresponding to the start time of the simulation.

date — the date corresponding to the start time of the simulation (composed in the default time zone)
void setStopTime(double tstop) Sets the stop time for the simulation, in model time units. The simulation won’t stop if the stop time set at runtime is earlier than the current model time or equals +infinity. If any event(s) are scheduled exactly at stop time, they will be executed. By default the stop time is +infinity, so the simulation may run infinitely.

tstop — the model time to stop the simulation, in model time units
void setStopTime(double tstop, TimeUnits units) Sets the stop time for the simulation, in the given time units. The simulation won’t stop if the stop time set at runtime is earlier than the current model time or equals +infinity. If any event(s) are scheduled exactly at stop time, they will be executed. By default the stop time is +infinity, so the simulation may run infinitely.

tstop — the model time to stop the simulation, in the given time units
units — constant defining the time units
void setStopDate(java.util.Date date) Sets the stop time of the simulation by converting the stop date provided to the model time, subject to the start time, start date and time unit settings. Discards the previously set stop time.

date — the stop date for the simulation (composed in the default time zone)
Time
Function Description
double time() Returns the current model (logical) time, in model time units.
double time(TimeUnits units) Returns the current model (logical) time, in the given time units.

units — constant defining the time units
java.util.Date date() Returns the current model date with respect to the start time/date and the model time units.
java.util.Date timeToDate(double t) Converts the given model time to date with respect to the start date, start time and model time unit settings, returns null if the time is infinity.

t — the model time
double dateToTime(java.util.Date d) Converts the given date to model time with respect to the start date, start time and model time unit settings.

d — the model date
int getAmPm() Indicates whether the hour of the current model date with respect to the start time/date and the model time unit is before noon (AM) or after noon (PM). This function is used for the 12-hour clock. E.g., at 10:04:15.250 PM the result is 1. Possible values:
  • 0 — AM
  • 1 — PM
int getDayOfMonth() Returns the day of the month of the current model date with respect to the start time/date and the model time unit.
The first day of the month is 1.
int getDayOfYear() Returns the serial number of the day in the year for the current model date with respect to the start time/date and the model time unit.
The first day of the year is 1.
int getDayOfWeek() Returns the day of the week of the current model date with respect to the start time/date and the model time unit.
The result depends on the system locale: for example, in some the week starts with Sunday (so Monday will be 2 in that case), while in others — with Monday (so Monday is 1).
int getHour() Returns the hour of the morning or afternoon of the current model date with respect to the start time/date and the model time unit.
This function is used for the 12-hour clock.
Noon and midnight are represented by 0, not by 12.
For example, at 10:04:15.250 PM the result is 10.
int getHourOfDay() Returns the hour of day of the current model date with respect to the start time/date and the model time unit.
This function is used for the 24-hour clock.
For example, at 10:04:15.250 PM the result is 22.
int getMillisecond() Returns the millisecond within the second of the current model date with respect to the start time/date and the model time unit.
E.g., at 10:04:15.250 PM the result is 250.
int getMinute() Returns the minute within the hour of the current model date with respect to the start time/date and the model time unit.
For example, at 10:04:15.250 PM the result is 4.
int getMonth() Returns the month of the current model date with respect to the start time/date and the model time unit.
This is a calendar-specific value.
The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0. The last month depends on the number of months in a year.
Valid values:
0 — JANUARY
1 — FEBRUARY
2 — MARCH
3 — APRIL
4 — MAY
5 — JUNE
6 — JULY
7 — AUGUST
8 — SEPTEMBER
9 — OCTOBER
10 — NOVEMBER
11 — DECEMBER
12 — UNDECIMBER (indicates the thirteenth month of the year. Although Gregorian calendar does not use this value, lunar calendars do).
int getSecond() Returns the second within the minute of the current model date with respect to the start time/date and the model time unit.
For example, at 10:04:15.250 PM the result is 15.
int getYear() Returns the year of the current model date with respect to the start time/date and the model time unit.
This is a calendar-specific value.
TimeUnits getTimeUnit() Returns the constant defining the model time units.
Top-level agent
Function Description
Agent getRoot() Returns the top-level agent setup for the engine. Usually (and by default) it is an instance of the agent type Main.
Database
Function Description
ModelDatabase getModelDatabase() Returns the the database of this model.
Random number generator
Function Description
java.util.Random getDefaultRandomGenerator() Returns the currently used default random number generator.
void setDefaultRandomGenerator(java.util.Random r) Changes the default random number generator.

r — the new random number generator
Model snapshots
Function Description
void saveRootObjectSnapshot(String snapshotFileName) Saves top-level agent and current state of the simulation engine into a specified snapshot file. This function is designed to be used in custom experiments and is available in AnyLogic Professional version only. This function shouldn't be called from the model-execution thread (except calling from custom experiments where the model is executed using runFast() function). Also, this function shouldn't be called when this engine is in RUNNING state.

snapshotFileName - the absolute path to the snapshot file
The created snapshot file may only be used in loadRootObjectFromSnapshot() functions, i.e. it isn't compatible with any experiments with animation (it is compatible only with custom experiment).
Agent loadRootObjectFromSnapshot(String snapshotFileName) Loads and sets top-level agent from the given snapshot with caching contents of snapshot file (for performance speed-up). This function supports loading from snapshots created with any experiment with animation (i.e. not custom) and from snapshots saved using saveRootObjectSnapshot(String) function.

snapshotFileName — the absolute path to the snapshot file
Agent loadRootObjectFromSnapshot(String snapshotFileName, boolean cacheSnapshot) Loads and sets top-level agent from the given snapshot with optional caching contents of snapshot file (for performance speed-up). This function supports loading from snapshots created with any experiment with animation (i.e. not custom) and from snapshots saved using saveRootObjectSnapshot(String) function.

snapshotFileName — the absolute path to the snapshot file
cacheSnapshot — if true, snapshot file will be cached for performance speed-up
void flushSnapshotCache() Clears cache with contents of recently loaded snapshot file.
Cache is automatically cleared on new snapshot loading.
Error signaling
Function Description
RuntimeException error(String errorText) Signals an error during the model run by throwing a RuntimeException with the given text: errorText preceded by the agent full name. This function never returns a value, 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");

errorText — the text describing the error that will be displayed
RuntimeException error(Throwable cause, String errorText) Signals an error during the model run by throwing a RuntimeException with the given text: errorText. This function never returns a value, 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(String errorText) Signals a model logic error during the model run by throwing a ModelException with specified errorText. This function never returns a value, 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 storage", 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
RuntimeException errorInModel(Throwable cause, String errorText) Signals a model logic error during the model run by throwing a ModelException with specified errorText. This function never returns a value, 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 storage", 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
Numerical solvers
Function Description
Engine.SolverODEType getSolverODE() Returns solver type for ordinary differential equations.
Possible values:
  • SOLVER_ODE_EULER
  • SOLVER_ODE_RK4
Engine.SolverNAEType getSolverNAE() Returns solver type for algebraic equations.
Possible values:
  • SOLVER_NAE_MODIFIED_NEWTON
  • SOLVER_NAE_FAST_NEWTON
  • SOLVER_NAE_CLASSIC_NEWTON
Engine.SolverDAEType getSolverDAE() Returns solver type for mixed differential-algebraic equations.
Possible values:
  • SOLVER_DAE_RK45_NEWTON
  • SOLVER_DAE_EULER_NEWTON
void setSolverODE(Engine.SolverODEType solverODE) Sets solver type for ordinary differential equations.
Available solvers:
  • SOLVER_ODE_EULER (default)
  • SOLVER_ODE_RK4

solverODE — solver type for ordinary differential equations
void setSolverNAE(Engine.SolverNAEType solverNAE) Sets solver type for algebraic equations.
Available solvers:
  • SOLVER_NAE_MODIFIED_NEWTON (default)
  • SOLVER_NAE_FAST_NEWTON
  • SOLVER_NAE_CLASSIC_NEWTON

solverNAE — solver type for algebraic equations
void setSolverDAE(Engine.SolverDAEType solverDAE) Sets solver type for mixed differential-algebraic equations.
Available solvers:
  • SOLVER_DAE_RK45_NEWTON (default)
  • SOLVER_DAE_EULER_NEWTON

solverDAE — solver type for mixed differential-algebraic equations
double getATOL() Returns the absolute tolerance of the numerical method.
double getRTOL() Returns the relative tolerance of the numerical method.
double getTTOL() Returns the time tolerance of the numerical method.
double getHTOL() Returns the fixed step of the numerical method.
void setATOL(double atol) Sets the absolute tolerance of the numerical method.

atol — the new absolute tolerance
void setRTOL(double rtol) Sets the relative tolerance of the numerical method.

rtol — the new relative tolerance
void setTTOL(double ttol) Sets the time tolerance of the numerical method.

ttol — the new time tolerance
void setHTOL(double htol) Sets the fixed step of the numerical method.

htol — the new fixed step
void setEventAwareSolver(boolean eventAwareSolver) This setting is actual for models having both System Dynamics equations and Discrete Event parts.
If true, SD equations will be solved with respect to each event occurrence time. This is the most precise technique, but in some cases it may significantly slow down the model, e.g. when many asynchronous agents generate dense events on the timeline.
If false, SD equations will be solved with fixed steps regardless event occurrences. As a result, an event will operate with some recent (not quite actual) values of continuous variables, namely, corresponding to the last result of numeric integration step. In the worst case, the values will be HTOL time units late. And similarly, in this mode SD formulas are not evaluated after each event execution, this is done only on fixed steps of the solver.
This setting is true by default.
Experiment
Function Description
Experiment<?> getExperiment() Returns the experiment controlling the model execution.
This method is not designed for AnyLogic Cloud, also returns null for custom experiments.
IExperimentHost getExperimentHost() Returns the experiment host object associated with this engine, or some dummy object with no functionality if there is none.
Custom experiment
Function Description
ExperimentCustom getExperimentCustom() Returns the custom experiment controlling the model execution. Returns null for other types of experiments.
void resetBeforeStart() This method should be called from custom experiments which use logging to database. Resets state variables which may be accessed by root parameters setup before start(Agent) is called. This method does nothing if state is not IDLE.
Advanced
Function Description
long getStep() Returns the number of events executed by the engine.
long getEventCount() Returns the number of currently scheduled events.
int getRunCount() Returns the number of the current simulation run, more precisely the number of times the model was destroyed.
How can we improve this article?