Class Simulator<T extends Number & Comparable<T>>
java.lang.Object
org.djutils.event.LocalEventProducer
nl.tudelft.simulation.dsol.simulators.Simulator<T>
- Type Parameters:
T
- the time type
- All Implemented Interfaces:
Serializable
,Runnable
,Remote
,SimulatorInterface<T>
,EventProducer
- Direct Known Subclasses:
DessSimulator
,DevsSimulator
public abstract class Simulator<T extends Number & Comparable<T>>
extends LocalEventProducer
implements SimulatorInterface<T>, Runnable
The Simulator class is an abstract implementation of the SimulatorInterface.
Copyright (c) 2002-2024 Delft University of Technology, Jaffalaan 5, 2628 BX Delft, the Netherlands. All rights reserved. See for project information https://simulation.tudelft.nl. The DSOL project is distributed under a three-clause BSD-style license, which can be found at https://https://simulation.tudelft.nl/dsol/docs/latest/license.html.
- Author:
- Alexander Verbraeck relative types are the same.
- See Also:
-
Nested Class Summary
Modifier and TypeClassDescriptionprotected static class
The worker thread to execute the run() method of the Simulator and to start/stop the simulation. -
Field Summary
Modifier and TypeFieldDescriptionprotected DsolModel<T,
? extends SimulatorInterface<T>> The model that is currently active; is null before initialize() has been called.protected Replication<T>
The currently active replication; is null before initialize() has been called.protected ReplicationState
The replication state of the simulator, that indicates the state of the Replication state machine.protected boolean
the run flag semaphore indicating that the run() method has started (and might have stopped).protected RunState
The run state of the simulator, that indicates the state of the Simulator state machine.protected boolean
whether the runUntilTime should carry out the calculation(s) for that time or not.protected T
The runUntil time in case we want to stop before the end of the replication time.protected Object
the simulatorSemaphore.protected T
simulatorTime represents the simulationTime.protected Simulator.SimulatorWorkerThread
a worker.Fields inherited from interface org.djutils.event.EventProducer
FIRST_POSITION, LAST_POSITION
Fields inherited from interface nl.tudelft.simulation.dsol.simulators.SimulatorInterface
START_EVENT, STARTING_EVENT, STOP_EVENT, STOPPING_EVENT, TIME_CHANGED_EVENT
-
Constructor Summary
-
Method Summary
Modifier and TypeMethodDescriptionvoid
addScheduledMethodOnInitialize
(Object target, String method, Object[] args) Add a method call that has to be performed at the end if initialize, and before the model starts.void
cleanUp()
Clean up the simulator after a replication.void
End the replication before the official ending time.protected void
fireTimedEvent
(EventType event) fireTimedEvent method to be called for a no-payload TimedEvent.final Level
Return the current error log level to use in the logger for simulation execution errors.final ErrorStrategy
Return the current error handling strategy for an execution error for a SimEvent.Get the logger for a simulator.DsolModel<T,
? extends SimulatorInterface<T>> getModel()
Returns the currently executed model, or null when the initialize method has not yet been called.Returns the currently executed replication, or null when the initialize method has not yet been called.Get the replication state of the simulator.Get the run state of the simulator.Returns the absolute simulator time.protected void
handleSimulationException
(Exception exception) Handle an exception thrown by executing a SimEvent according to the ErrorStrategy.void
initialize
(DsolModel<T, ? extends SimulatorInterface<T>> model, Replication<T> replication) Initializes the simulator with a replication for a model.abstract void
run()
The run method defines the actual time step mechanism of the simulator.void
Runs the simulator up to a certain time; any events at that time, or the solving of the differential equation at that timestep, will not yet be executed.void
runUpToAndIncluding
(T stopTime) Runs the simulator up to a certain time; all events at that time, or the solving of the differential equation at that timestep, will be executed.final void
setErrorLogLevel
(Level errorLogLevel) Set the error log level to use in the logger for simulation execution errors.final void
setErrorStrategy
(ErrorStrategy errorStrategy) Set the error handling strategy for an execution error for a SimEvent, using the default error log level.final void
setErrorStrategy
(ErrorStrategy newErrorStrategy, Level newErrorLogLevel) Set the error handling strategy for an execution error for a SimEvent.void
start()
Starts the simulator, and fire a START_EVENT that the simulator was started.void
Implementation of the start method.void
step()
Steps the simulator, and fire a STEP_EVENT to indicate the simulator made a step.protected abstract void
stepImpl()
The implementation body of the step() method.void
stop()
Stops the simulator, and fire a STOP_EVENT that the simulator was stopped.protected void
stopImpl()
Implementation of the stop behavior.void
warmup()
Fire the WARMUP event to clear the statistics after the warmup period.Methods inherited from class org.djutils.event.LocalEventProducer
addListener, addListener, addListener, addListener, fireEvent, fireEvent, fireEvent, fireTimedEvent, fireTimedEvent, fireTimedEvent, fireUnverifiedEvent, fireUnverifiedEvent, fireUnverifiedTimedEvent, fireUnverifiedTimedEvent, getEventListenerMap, getEventTypesWithListeners, getListenerReferences, hasListeners, numberOfListeners, removeAllListeners, removeAllListeners, removeListener
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
Methods inherited from interface org.djutils.event.EventProducer
addListener, addListener, addListener, addListener, fireEvent, fireEvent, fireEvent, fireTimedEvent, fireTimedEvent, fireTimedEvent, fireUnverifiedEvent, fireUnverifiedEvent, fireUnverifiedTimedEvent, fireUnverifiedTimedEvent, getEventListenerMap, getEventTypesWithListeners, getListenerReferences, hasListeners, numberOfListeners, removeAllListeners, removeAllListeners, removeListener
Methods inherited from interface nl.tudelft.simulation.dsol.simulators.SimulatorInterface
addScheduledMethodOnInitialize, isInitialized, isStartingOrRunning, isStoppingOrStopped
-
Field Details
-
simulatorTime
simulatorTime represents the simulationTime. -
runUntilTime
The runUntil time in case we want to stop before the end of the replication time. -
runUntilIncluding
protected boolean runUntilIncludingwhether the runUntilTime should carry out the calculation(s) for that time or not. -
runState
The run state of the simulator, that indicates the state of the Simulator state machine. -
replicationState
The replication state of the simulator, that indicates the state of the Replication state machine. -
replication
The currently active replication; is null before initialize() has been called. -
model
protected DsolModel<T extends Number & Comparable<T>,? extends SimulatorInterface<T extends Number & Comparable<T>>> modelThe model that is currently active; is null before initialize() has been called. -
worker
a worker. -
semaphore
the simulatorSemaphore. -
runflag
protected boolean runflagthe run flag semaphore indicating that the run() method has started (and might have stopped).
-
-
Constructor Details
-
Simulator
Constructs a new Simulator.- Parameters:
id
- the id of the simulator, used in logging and firing of events.
-
-
Method Details
-
initialize
public void initialize(DsolModel<T, ? extends SimulatorInterface<T>> model, Replication<T> replication) throws SimRuntimeExceptionInitializes the simulator with a replication for a model. It immediately fires a START_REPLICATION_EVENT and a TIME_CHANGED_EVENT with the starting time. It does not yet fire a WARMUP_EVENT in case the warmup time is zero; this will only be done after the simulator has been started. Note that the listeners of all statistics objects are removed when the simulator is initialized with the replication. Connecting the statistics objects to the simulation should be done between the initialize(...) method and starting the simulator, or could even be delayed till the WARMUP_EVENT has been fired.- Specified by:
initialize
in interfaceSimulatorInterface<T extends Number & Comparable<T>>
- Parameters:
model
- DsolModel<T, S>; the model to initializereplication
- Replication<T, ? extends SimulatorInterface<T>>; the replication to use for running the model- Throws:
SimRuntimeException
- when the simulator is running
-
addScheduledMethodOnInitialize
public void addScheduledMethodOnInitialize(Object target, String method, Object[] args) throws SimRuntimeException Add a method call that has to be performed at the end if initialize, and before the model starts. This can, for instance, be used to schedule the execution of simulation events before initialize has been called, and solved the problem that, for discrete event simulators, the scheduleEvent(...) methods cannot be called before initialize().- Specified by:
addScheduledMethodOnInitialize
in interfaceSimulatorInterface<T extends Number & Comparable<T>>
- Parameters:
target
- Object; the target on which the method needs to be executedmethod
- String; the name of the method to call on initialization of the modelargs
- Object[]; the arguments of the method. Usenew Object[] {}
for no arguments.- Throws:
SimRuntimeException
- whenever the event is scheduled in the past.
-
startImpl
Implementation of the start method. Checks preconditions for running and fires the right events.- Throws:
SimRuntimeException
- when the simulator is already running, or when the replication is missing or has ended
-
start
Starts the simulator, and fire a START_EVENT that the simulator was started. Note that when the simulator was already started an exception will be thrown, and no event will be fired. The start uses the RunUntil property with a value of the end time of the replication whenstarting the simulator.- Specified by:
start
in interfaceSimulatorInterface<T extends Number & Comparable<T>>
- Throws:
SimRuntimeException
- whenever starting fails. Possible occasions include starting an already started simulator
-
runUpTo
Runs the simulator up to a certain time; any events at that time, or the solving of the differential equation at that timestep, will not yet be executed.- Specified by:
runUpTo
in interfaceSimulatorInterface<T extends Number & Comparable<T>>
- Parameters:
stopTime
- T; the absolute time till when we want to run the simulation, coded as a SimTime object- Throws:
SimRuntimeException
- whenever starting fails. Possible occasions include starting a started simulator
-
runUpToAndIncluding
Runs the simulator up to a certain time; all events at that time, or the solving of the differential equation at that timestep, will be executed.- Specified by:
runUpToAndIncluding
in interfaceSimulatorInterface<T extends Number & Comparable<T>>
- Parameters:
stopTime
- T; the absolute time till when we want to run the simulation, coded as a SimTime object- Throws:
SimRuntimeException
- whenever starting fails. Possible occasions include starting a started simulator
-
stepImpl
protected abstract void stepImpl()The implementation body of the step() method. The stepImpl() method should fire the TIME_CHANGED_EVENT before the execution of the simulation event, or before executing the integration of the differential equation for the next timestep. So the time is changed first to match the logic carried out for that time, and then the action for that time is carried out. This is INDEPENDENT of the fact whether the time changes or not. The TIME_CHANGED_EVENT is always fired. -
step
Steps the simulator, and fire a STEP_EVENT to indicate the simulator made a step. Note that when the simulator is running an exception will be thrown, and no event will be fired.- Specified by:
step
in interfaceSimulatorInterface<T extends Number & Comparable<T>>
- Throws:
SimRuntimeException
- whenever stepping fails. Possible occasions include stepping an already running simulator
-
stopImpl
protected void stopImpl()Implementation of the stop behavior. -
stop
Stops the simulator, and fire a STOP_EVENT that the simulator was stopped. Note that when the simulator was already stopped an exception will be thrown, and no event will be fired.- Specified by:
stop
in interfaceSimulatorInterface<T extends Number & Comparable<T>>
- Throws:
SimRuntimeException
- whenever stopping fails. Possible occasions include stopping an already stopped simulator
-
warmup
public void warmup()Fire the WARMUP event to clear the statistics after the warmup period. Note that for a discrete event simulator, the warmup event can be scheduled, whereas for a continuous simulator, the warmup event must be detected based on the simulation time. -
cleanUp
public void cleanUp()Clean up the simulator after a replication. Remove the worker thread.- Specified by:
cleanUp
in interfaceSimulatorInterface<T extends Number & Comparable<T>>
-
endReplication
End the replication before the official ending time. When the simulation is running, it will fire a STOP_EVENT followed by an END_REPLICATION_EVENT, and will stop the running of the simulator, moving the RunState and the ReplicatioNState both to the ENDED state. When the simulation time is not equal to or larger than the length of the replication, a logger warning is given, but the method is fully executed. In that case it does set the simulation time to the end time of the replication, to avoid restarting of the simulator.- Specified by:
endReplication
in interfaceSimulatorInterface<T extends Number & Comparable<T>>
- Throws:
SimRuntimeException
- when the simulator had already terminated, or is not initialized
-
getErrorStrategy
Return the current error handling strategy for an execution error for a SimEvent.- Specified by:
getErrorStrategy
in interfaceSimulatorInterface<T extends Number & Comparable<T>>
- Returns:
- errorStrategy ErrorStrategy; the current error handling strategy for an execution error for a SimEvent
-
setErrorStrategy
Set the error handling strategy for an execution error for a SimEvent, using the default error log level.- Specified by:
setErrorStrategy
in interfaceSimulatorInterface<T extends Number & Comparable<T>>
- Parameters:
errorStrategy
- ErrorStrategy; the error handling strategy for an execution error for a SimEvent
-
setErrorStrategy
Set the error handling strategy for an execution error for a SimEvent.- Specified by:
setErrorStrategy
in interfaceSimulatorInterface<T extends Number & Comparable<T>>
- Parameters:
newErrorStrategy
- ErrorStrategy; the error handling strategy for an execution error for a SimEventnewErrorLogLevel
- Level; the error log level to use in the logger for simulation execution errors
-
getErrorLogLevel
Return the current error log level to use in the logger for simulation execution errors.- Specified by:
getErrorLogLevel
in interfaceSimulatorInterface<T extends Number & Comparable<T>>
- Returns:
- Level; the current error log level to use in the logger for simulation execution errors
-
setErrorLogLevel
Set the error log level to use in the logger for simulation execution errors.- Specified by:
setErrorLogLevel
in interfaceSimulatorInterface<T extends Number & Comparable<T>>
- Parameters:
errorLogLevel
- Level; the error log level to use in the logger for simulation execution errors
-
handleSimulationException
Handle an exception thrown by executing a SimEvent according to the ErrorStrategy. A call to this method needs to be built into the run() method of every Simulator subclass.- Parameters:
exception
- Exception; the exception that was thrown when executing the SimEvent
-
run
public abstract void run()The run method defines the actual time step mechanism of the simulator. The implementation of this method depends on the formalism. Where discrete event formalisms loop over an event list, continuous simulators take predefined time steps. Make sure that:
- SimulatorInterface.TIME_CHANGED_EVENT is fired when the time of the simulator changes
- the warmup() method is called when the warmup period has expired (through an event or based on simulation time)
- the endReplication() method is called when the replication has ended
- the simulator runs until the runUntil time, which is also set by the start() method. -
getSimulatorTime
Returns the absolute simulator time.- Specified by:
getSimulatorTime
in interfaceSimulatorInterface<T extends Number & Comparable<T>>
- Returns:
- the simulator time.
-
getReplication
Returns the currently executed replication, or null when the initialize method has not yet been called.- Specified by:
getReplication
in interfaceSimulatorInterface<T extends Number & Comparable<T>>
- Returns:
- Replication<T>; the current replication, or null when the model has not yet been initialized
-
getModel
Returns the currently executed model, or null when the initialize method has not yet been called.- Specified by:
getModel
in interfaceSimulatorInterface<T extends Number & Comparable<T>>
- Returns:
- DsolModel<T, ? extends SimulatorInterface>; the currently executed model, or null when the model has not yet been initialized
-
getLogger
Get the logger for a simulator. Since the loggers display the simulator time, each logger that runs in the same JVM needs to have its own logger.- Specified by:
getLogger
in interfaceSimulatorInterface<T extends Number & Comparable<T>>
- Returns:
- SimLogger; the logger that is specific for this simulator
-
getRunState
Get the run state of the simulator.- Specified by:
getRunState
in interfaceSimulatorInterface<T extends Number & Comparable<T>>
- Returns:
- RunState; the run state of the simulator
-
getReplicationState
Get the replication state of the simulator.- Specified by:
getReplicationState
in interfaceSimulatorInterface<T extends Number & Comparable<T>>
- Returns:
- ReplicationState; the replication state of the simulator
-
fireTimedEvent
fireTimedEvent method to be called for a no-payload TimedEvent.- Parameters:
event
- the event to fire at the current time
-