Package sim.engine

Class SimState

java.lang.Object
sim.engine.SimState
All Implemented Interfaces:
Serializable

public class SimState extends Object implements Serializable
SimState represents the simulation proper. Your simulations generally will contain one top-level object which subclasses from SimState.

A SimState contains the random number generator and the simulator's schedule. You should not change the schedule to another Schedule object.

When a simulation is begun, SimState's start() method is called. Then the schedule is stepped some N times. Last, the SimState's finish() method is called, and the simulation is over.

SimStates are serializable; if you wish to be able to checkpoint your simulation and read from checkpoints, you should endeavor to make all objects in the simulation serializable as well. Prior to serializing to a checkpoint, preCheckpoint() is called. Then after serialization, postCheckpoint() is called. When a SimState is loaded from a checkpoint, awakeFromCheckpoint() is called to give you a chance to make any adjustments. SimState also implements several methods which call these methods and then serialize the SimState to files and to streams.

SimState also maintains a private registry of AsynchronousSteppable objects, and handles pausing and resuming them during the checkpointing process, and killing them during finish() in case they had not completed yet.

If you override any of the methods foo() in SimState, should remember to always call super.foo() for any such method foo().

See Also:
  • Field Summary

    Fields
    Modifier and Type
    Field
    Description
    The SimState's random number generator
    SimState's schedule
  • Constructor Summary

    Constructors
    Modifier
    Constructor
    Description
     
    SimState(long seed)
    Creates a SimState with a new random number generator initialized to the given seed, plus a new, empty schedule.
    protected
    SimState(long seed, Schedule schedule)
    Creates a SimState with the schedule, creating a new random number generator.
    protected
    Creates a SimState with a new schedule, the provided random number generator, and a bogus seed (0).
    protected
    Creates a SimState with the given random number generator and schedule, and sets the seed to a bogus value (0).
  • Method Summary

    Modifier and Type
    Method
    Description
    boolean
    Registers an AsynchronousSteppable to get its pause() method called prior to checkpointing, its resume() method to be called after checkpointing or recovery, and its stop() method to be called at finish() time.
    protected static String
     
    double[]
    assess(int numObjectives)
    Override this method to return a multiobjective optimization assessment of the simulation run.
    Returns all the AsynchronousSteppable items presently in the registry.
    void
    Called after the SimState was created by reading from a checkpointed object.
    Returns the PrintWriter used to describe a high-quality assessed SimState.
    static void
    doLoop(Class c, String[] args)
    Calls doLoop(MakesSimState,args), passing in a MakesSimState which creates SimStates of the provided Class c, using the constructor new ().
    static void
    doLoop(MakesSimState generator, String[] args)
    A convenient top-level loop for the simulation command-line.
    void
    Called either at the proper or a premature end to the simulation.
    long
    job()
    Returns the job number set by the doLoop(...) facility.
    protected static boolean
    keyExists(String key, String[] args)
     
    void
    A Steppable on the schedule can call this method to cancel the simulation.
    void
    Deprecated. 
    void
    Called just after the SimState was checkpointed (serialized out to a file to be unserialized and fired up at a future time).
    void
    Hook for distributed MASON, called immediately after stepping the schedule.
    void
    Called just before the SimState is being checkpointed (serialized out to a file to be unserialized and fired up at a future time).
    void
    Hook for distributed MASON, called immediately before stepping the schedule.
    Primes the generator.
    static void
     
    Override this to add a tab to the Console.
    Override this to add a tab name to the Console.
    static SimState
    Creates a SimState from checkpoint.
    static SimState
    Creates and returns a new SimState object read in from the provided stream.
    boolean
    Returns true if the simulation is a remote proxy simulation.
    long
    Override this to revise the steps displayed in the Console.
    double
    Override this to revise the time displayed in the Console.
    void
    Unregisters an AsynchronousSteppable from the asynchronous registry.
    long
    Returns the seed set by the doLoop(...) facility and by the constructor.
    void
    This method is called to set the PrintWriter used in getDescription() [which is more important to you].
    void
    setJob(long job)
     
    void
    setOptimizationParameters(double[] parameterValues)
    You only override this method to set parameter values for purposes of optimization: MASON's optimization facility (in contrib/optimize) may call this to set up certain parameters in bulk prior to running the model and assessing it with assess(...).
    void
    setSeed(long seed)
     
    void
    Called immediately prior to starting the simulation, or in-between simulation runs.
    static double
    Returns MASON's Version
    Writes the state to a checkpoint and returns the state.
    void
    Serializes out the SimState, and the entire simulation state (not including the graphical interfaces) to the provided stream.

    Methods inherited from class java.lang.Object

    clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
  • Field Details

    • random

      public MersenneTwisterFast random
      The SimState's random number generator
    • schedule

      public Schedule schedule
      SimState's schedule
  • Constructor Details

    • SimState

      public SimState(long seed)
      Creates a SimState with a new random number generator initialized to the given seed, plus a new, empty schedule.
    • SimState

      protected SimState(MersenneTwisterFast random, Schedule schedule)
      Creates a SimState with the given random number generator and schedule, and sets the seed to a bogus value (0). This should only be used by SimState subclasses which need to use an existing random number generator and schedule.
    • SimState

      protected SimState(long seed, Schedule schedule)
      Creates a SimState with the schedule, creating a new random number generator. This should only be used by SimState subclasses which need to use an existing schedule.
    • SimState

      protected SimState(MersenneTwisterFast random)
      Creates a SimState with a new schedule, the provided random number generator, and a bogus seed (0). This should only be used by SimState subclasses which need to use an existing random number generator.
  • Method Details

    • setSeed

      public void setSeed(long seed)
    • primeGenerator

      public static MersenneTwisterFast primeGenerator(MersenneTwisterFast generator)
      Primes the generator. Mersenne Twister seeds its first 624 numbers using a basic linear congruential generator; thereafter it uses the MersenneTwister algorithm to build new seeds. Those first 624 numbers are generally just fine, but to be extra safe, you can prime the generator by calling nextInt() on it some (N>1) * 624 times. This method does exactly that, presently with N=2 ( + 1 ).
    • start

      public void start()
      Called immediately prior to starting the simulation, or in-between simulation runs. This gives you a chance to set up initially, or reset from the last simulation run. The default version simply replaces the Schedule with a completely new one.
    • finish

      public void finish()
      Called either at the proper or a premature end to the simulation. If the user quits the program, this function may not be called. It is possible for this method to be called multiple times. If you need to check for this possibility, the easiest way is to set a flag in start() and clear it in the first finish().
    • kill

      public void kill()
      A Steppable on the schedule can call this method to cancel the simulation. All existing AsynchronousSteppables are stopped, and then the schedule is reset. AsynchronousSteppables, ParallelSequences, and non-main threads should not call this method directly -- it will deadlock. Instead, they may kill the simulation by scheduling a Steppable for the next timestep which calls state.kill().
    • addToAsynchronousRegistry

      public boolean addToAsynchronousRegistry(AsynchronousSteppable stop)
      Registers an AsynchronousSteppable to get its pause() method called prior to checkpointing, its resume() method to be called after checkpointing or recovery, and its stop() method to be called at finish() time. The purpose of the addToCleanup() method is to provide the simulation with a way of stopping existing threads which the user has created in the background.

      An AsynchronousSteppable cannot be added multiple times to the same registry -- if it's there it's there. Returns false if the AsynchronousSteppable could not be added, either because the simulation is stopped or in the process of finish()ing.

    • removeFromAsynchronousRegistry

      public void removeFromAsynchronousRegistry(AsynchronousSteppable stop)
      Unregisters an AsynchronousSteppable from the asynchronous registry.
    • asynchronousRegistry

      public AsynchronousSteppable[] asynchronousRegistry()
      Returns all the AsynchronousSteppable items presently in the registry. The returned array is not used internally -- you are free to modify it.
    • preCheckpoint

      public void preCheckpoint()
      Called just before the SimState is being checkpointed (serialized out to a file to be unserialized and fired up at a future time). You should override this to prepare your SimState object appropriately. Be sure to call super.preCheckpoint().
    • postCheckpoint

      public void postCheckpoint()
      Called just after the SimState was checkpointed (serialized out to a file to be unserialized and fired up at a future time). You cam override this as you see fit. Be sure to call super.postCheckpoint().
    • awakeFromCheckpoint

      public void awakeFromCheckpoint()
      Called after the SimState was created by reading from a checkpointed object. You should set up your SimState in any way necessary (reestablishing file connections, etc.) to fix anything that may no longer exist. Be sure to call super.awakeFromCheckpoint().
    • writeToCheckpoint

      public void writeToCheckpoint(OutputStream stream) throws IOException
      Serializes out the SimState, and the entire simulation state (not including the graphical interfaces) to the provided stream. Calls preCheckpoint() before and postCheckpoint() afterwards. Throws an IOException if the stream becomes invalid (prematurely closes, etc.). Does not close or flush the stream.
      Throws:
      IOException
    • writeToCheckpoint

      public SimState writeToCheckpoint(File file)
      Writes the state to a checkpoint and returns the state. If an exception is raised, it is printed and null is returned.
    • readFromCheckpoint

      public static SimState readFromCheckpoint(File file)
      Creates a SimState from checkpoint. If an exception is raised, it is printed and null is returned.
    • readFromCheckpoint

      Creates and returns a new SimState object read in from the provided stream. Calls awakeFromCheckpoint(). Throws an IOException if the stream becomes invalid (prematurely closes etc.). Throws a ClassNotFoundException if a serialized object is not found in the CLASSPATH and thus cannot be created. Throws an OptionalDataException if the stream is corrupted. Throws a ClassCastException if the top-level object is not actually a SimState. Does not close or flush the stream.
      Throws:
      IOException
      ClassNotFoundException
      OptionalDataException
      ClassCastException
    • keyExists

      protected static boolean keyExists(String key, String[] args)
    • argumentForKey

      protected static String argumentForKey(String key, String[] args)
    • seed

      public long seed()
      Returns the seed set by the doLoop(...) facility and by the constructor. Only to be used for GUIs to display possible seed values.
    • setJob

      public void setJob(long job)
    • job

      public long job()
      Returns the job number set by the doLoop(...) facility. This number is not incremented by the GUI.
    • doLoop

      public static void doLoop(Class c, String[] args)
      Calls doLoop(MakesSimState,args), passing in a MakesSimState which creates SimStates of the provided Class c, using the constructor new ().
    • doLoop

      public static void doLoop(MakesSimState generator, String[] args)
      A convenient top-level loop for the simulation command-line. Takes a MakesSimState which is responsible for providing a SimState to run the simulation on, plus the application's argument list in args. This loop is capable of:
      • Repeating a job multiple times
    • printlnSynchronized

      public static void printlnSynchronized(String val)
    • nameThread

      public void nameThread()
      Deprecated.
    • version

      public static double version()
      Returns MASON's Version
    • preSchedule

      public void preSchedule()
      Hook for distributed MASON, called immediately before stepping the schedule.
    • postSchedule

      public void postSchedule()
      Hook for distributed MASON, called immediately after stepping the schedule.
    • assess

      public double[] assess(int numObjectives)
      Override this method to return a multiobjective optimization assessment of the simulation run. You should return an assessment of the model performance for each of some N >= 1 objectives (N is the length of the array). For each objective i, the returned assessment[i] should be between 0 (the lowest quality) and 1 (the highest quality) inclusive. The default version of this method simply returns all 0, meaning a horrible, no good, very bad simulation run.

      This method is only used by the distributed optimization facility and will be called, possibly repeatedly, after start() and before finish(). If you're not doing distributed optimization, it'll never be called, so you can ignore this method. By default the method nonsensically always returns an optimimum score, that is, it suggests that the model is ideally calibrated.

    • setOptimizationParameters

      public void setOptimizationParameters(double[] parameterValues)
      You only override this method to set parameter values for purposes of optimization: MASON's optimization facility (in contrib/optimize) may call this to set up certain parameters in bulk prior to running the model and assessing it with assess(...). Otherwise you don't fool with this.
    • setDescription

      public void setDescription(PrintWriter writer)
      This method is called to set the PrintWriter used in getDescription() [which is more important to you].
    • description

      public PrintWriter description()
      Returns the PrintWriter used to describe a high-quality assessed SimState. If getDescription() returns a PrintWriter (as opposed to null), you can use this to write out descriptive statistics, indeed anything you like, as the simulation is running to describe it. This is done at the end of optimization, when one or more SimState models, typically the best one discovered, will be run one final time with a PrintWriter description. The description will be set prior to start() and should not be saved nor written to after finish().
    • remoteProxy

      public boolean remoteProxy()
      Returns true if the simulation is a remote proxy simulation. Don't override this: it's provided mostly for the distributed visualizer.
    • remoteSteps

      public long remoteSteps()
      Override this to revise the steps displayed in the Console. Don't override this: it's provided mostly for the distributed visualizer.
    • remoteTime

      public double remoteTime()
      Override this to revise the time displayed in the Console. Ordinarily you should leave this alone: it's provided mostly for the distributed visualizer.
    • provideAdditionalTab

      public JComponent provideAdditionalTab()
      Override this to add a tab to the Console. Normally you'd not do this from the SimState, but the Distributed code needs to use this.
    • provideAdditionalTabName

      public String provideAdditionalTabName()
      Override this to add a tab name to the Console. Normally you'd not do this from the SimState, but the Distributed code needs to use this.