lbnl.actor.lib
Class Simulator

java.lang.Object
  extended by ptolemy.kernel.util.NamedObj
      extended by ptolemy.kernel.InstantiableNamedObj
          extended by ptolemy.kernel.Entity
              extended by ptolemy.kernel.ComponentEntity
                  extended by ptolemy.actor.AtomicActor
                      extended by ptolemy.actor.TypedAtomicActor
                          extended by ptolemy.domains.sdf.lib.SDFTransformer
                              extended by lbnl.actor.lib.Simulator
All Implemented Interfaces:
java.io.Serializable, java.lang.Cloneable, Actor, Executable, FiringsRecordable, Initializable, SequenceActor, TypedActor, Changeable, Debuggable, DebugListener, Derivable, Instantiable, ModelErrorHandler, MoMLExportable, Moveable, Nameable

public class Simulator
extends SDFTransformer

Actor that calls a simulation program of a dynamic system that is coupled to Ptolemy II. At the start of the simulation, this actor fires a system command that is defined by the parameter programName with arguments programArguments. It then initiates a socket connection and uses the socket to exchange data with the external simulation program each time the actor is fired.

Since:
Ptolemy II 8.0
Version:
$Id: Simulator.java 59203 2010-09-23 21:41:27Z cxh $
Author:
Michael Wetter
See Also:
Serialized Form

Nested Class Summary
 
Nested classes/interfaces inherited from class ptolemy.kernel.Entity
Entity.ContainedObjectsIterator
 
Field Summary
protected  boolean clientTerminated
          Flag, set to true when the clients terminates the communication.
protected  ClientProcess cliPro
          Thread that runs the simulation.
protected  double[] dblWri
          Double values that were written to the socket.
protected  boolean firstFire
          Flag that is true during the first firing of this actor/.
protected  boolean isHeadless
          Flag, set the true if Ptolemy is run without any graphical interface.
protected static java.lang.String LS
          System dependent line separator.
protected  DoubleMatrixToken outTok
          Output tokens.
protected  int porNo
          Port number that is actually used for BSD socket.
 Parameter programArguments
          Arguments of program that starts the simulation.
 FileParameter programName
          Name of program that starts the simulation.
protected  Server server
          Server used for data exchange.
 Parameter showConsoleWindow
          If true (the default), a window will be created that shows the console output.
protected  java.lang.Process simProJav
          Process that runs the simulation.
protected  double simTimPre
          Ptolemy's time at the last call of the fire method.
protected  double simTimReaPre
          Time read from the simulation program at the last call of the fire method.
 FileParameter simulationLogFile
          File name to which this actor writes the simulation log.
 FileParameter socketConfigurationFile
          File name to which this actor writes the socket configuration.
 Parameter socketPortNumber
          Port number for BSD socket (used if non-negative).
 Parameter socketTimeout
          Socket time out in milliseconds.
protected  java.lang.String terminationMessage
          Message that will be displayed in the warning window when the client terminated, but Ptolemy continues with the simulation.
protected  double tokTim
          Time of token that will be written to the client.
protected  java.lang.Thread warWin
          Thread that is used if a warning window need to be shown.
protected  java.lang.String worDir
          Working directory of the subprocess.
 FileParameter workingDirectory
          Working directory of the simulation.
 
Fields inherited from class ptolemy.domains.sdf.lib.SDFTransformer
input, input_tokenConsumptionRate, output, output_tokenInitProduction, output_tokenProductionRate
 
Fields inherited from class ptolemy.actor.AtomicActor
_actorFiringListeners, _initializables, _notifyingActorFiring, _stopRequested
 
Fields inherited from class ptolemy.kernel.util.NamedObj
_changeListeners, _changeLock, _changeRequests, _debugging, _debugListeners, _elementName, _isPersistent, _verbose, _workspace, ATTRIBUTES, CLASSNAME, COMPLETE, CONTENTS, DEEP, FULLNAME, LINKS
 
Fields inherited from interface ptolemy.actor.Executable
COMPLETED, NOT_READY, STOP_ITERATING
 
Constructor Summary
Simulator(CompositeEntity container, java.lang.String name)
          Constructs an actor with the given container and name.
 
Method Summary
protected  double[] _getDoubleArray(Token t)
          Get a double array from the Token.
protected  void _outputInitToken()
          Output the first token during initialize.
protected  void _readFromServer()
          Read the data from the server instance, which will read it from the client program.
protected  void _startSimulation()
          Start the simulation program.
protected  void _writeToServer()
          Write the data to the server instance, which will send it to the client program.
 java.lang.Object clone(Workspace workspace)
          Clone the actor into the specified workspace.
static java.lang.String cutQuotationMarks(java.lang.String str)
          Cut the leading and terminating quotation marks if present.
 void fire()
          Send the input token to the client program and send the output from the client program to the output port.
 void initialize()
          Initialize state variables.
 void preinitialize()
          Initializes the data members and checks if the parameters of the actor are valid.
static java.lang.String resolveCommandName(java.io.File programName)
          Resolve the command string.
static java.lang.String resolveDirectory(NamedObj namedObj, java.lang.String dir)
          Resolve the working string.
 void wrapup()
          Closes sockets and shuts down the simulator.
 
Methods inherited from class ptolemy.domains.sdf.lib.SDFTransformer
prefire
 
Methods inherited from class ptolemy.actor.TypedAtomicActor
_addPort, _fireAt, _fireAt, attributeTypeChanged, clone, newPort, typeConstraintList, typeConstraints
 
Methods inherited from class ptolemy.actor.AtomicActor
_actorFiring, _actorFiring, addActorFiringListener, addInitializable, connectionsChanged, createReceivers, declareDelayDependency, getCausalityInterface, getDirector, getExecutiveDirector, getManager, inputPortList, isFireFunctional, isStrict, iterate, newReceiver, outputPortList, postfire, pruneDependencies, recordFiring, removeActorFiringListener, removeDependency, removeInitializable, setContainer, stop, stopFire, terminate
 
Methods inherited from class ptolemy.kernel.ComponentEntity
_adjustDeferrals, _checkContainer, _getContainedObject, _propagateExistence, getContainer, instantiate, isAtomic, isOpaque, moveDown, moveToFirst, moveToIndex, moveToLast, moveUp, propagateExistence, setName
 
Methods inherited from class ptolemy.kernel.Entity
_description, _exportMoMLContents, _removePort, _validateSettables, connectedPortList, connectedPorts, containedObjectsIterator, getAttribute, getPort, getPorts, linkedRelationList, linkedRelations, portList, removeAllPorts, setClassDefinition, uniqueName
 
Methods inherited from class ptolemy.kernel.InstantiableNamedObj
_setParent, exportMoML, getChildren, getElementName, getParent, getPrototypeList, isClassDefinition, isWithinClassDefinition
 
Methods inherited from class ptolemy.kernel.util.NamedObj
_addAttribute, _adjustOverride, _attachText, _cloneFixAttributeFields, _debug, _debug, _debug, _debug, _debug, _getIndentPrefix, _isMoMLSuppressed, _markContentsDerived, _propagateValue, _recordDecoratedAttributes, _removeAttribute, _splitName, _stripNumericSuffix, addChangeListener, addDebugListener, attributeChanged, attributeList, attributeList, deepContains, depthInHierarchy, description, description, event, executeChangeRequests, exportMoML, exportMoML, exportMoML, exportMoML, exportMoMLPlain, getAttribute, getAttributes, getChangeListeners, getClassName, getDecoratorAttribute, getDecoratorAttributes, getDerivedLevel, getDerivedList, getDisplayName, getFullName, getModelErrorHandler, getName, getName, getSource, handleModelError, isDeferringChangeRequests, isOverridden, isPersistent, lazyContainedObjectsIterator, message, propagateValue, propagateValues, removeChangeListener, removeDebugListener, requestChange, setClassName, setDeferringChangeRequests, setDerivedLevel, setDisplayName, setModelErrorHandler, setPersistent, setSource, sortContainedObjects, toplevel, toString, validateSettables, workspace
 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 
Methods inherited from interface ptolemy.actor.Actor
createReceivers, getCausalityInterface, getDirector, getExecutiveDirector, getManager, inputPortList, newReceiver, outputPortList
 
Methods inherited from interface ptolemy.actor.Executable
isFireFunctional, isStrict, iterate, postfire, stop, stopFire, terminate
 
Methods inherited from interface ptolemy.actor.Initializable
addInitializable, removeInitializable
 
Methods inherited from interface ptolemy.kernel.util.Nameable
description, getContainer, getDisplayName, getFullName, getName, getName, setName
 
Methods inherited from interface ptolemy.kernel.util.Derivable
getDerivedLevel, getDerivedList, propagateValue
 

Field Detail

programArguments

public Parameter programArguments
Arguments of program that starts the simulation.


programName

public FileParameter programName
Name of program that starts the simulation.


socketPortNumber

public Parameter socketPortNumber
Port number for BSD socket (used if non-negative).


simulationLogFile

public FileParameter simulationLogFile
File name to which this actor writes the simulation log.


socketConfigurationFile

public FileParameter socketConfigurationFile
File name to which this actor writes the socket configuration.


socketTimeout

public Parameter socketTimeout
Socket time out in milliseconds.


workingDirectory

public FileParameter workingDirectory
Working directory of the simulation.


showConsoleWindow

public Parameter showConsoleWindow
If true (the default), a window will be created that shows the console output.


dblWri

protected double[] dblWri
Double values that were written to the socket.


cliPro

protected ClientProcess cliPro
Thread that runs the simulation.


porNo

protected int porNo
Port number that is actually used for BSD socket.


server

protected Server server
Server used for data exchange.


simProJav

protected java.lang.Process simProJav
Process that runs the simulation.


worDir

protected java.lang.String worDir
Working directory of the subprocess.


outTok

protected DoubleMatrixToken outTok
Output tokens.


simTimPre

protected double simTimPre
Ptolemy's time at the last call of the fire method.


simTimReaPre

protected double simTimReaPre
Time read from the simulation program at the last call of the fire method.


clientTerminated

protected boolean clientTerminated
Flag, set to true when the clients terminates the communication.


warWin

protected java.lang.Thread warWin
Thread that is used if a warning window need to be shown.


terminationMessage

protected java.lang.String terminationMessage
Message that will be displayed in the warning window when the client terminated, but Ptolemy continues with the simulation.


isHeadless

protected boolean isHeadless
Flag, set the true if Ptolemy is run without any graphical interface. If isHeadless=true, this actor will not open any windows for reporting outputs or warnings.


firstFire

protected boolean firstFire
Flag that is true during the first firing of this actor/.


LS

protected static final java.lang.String LS
System dependent line separator.


tokTim

protected double tokTim
Time of token that will be written to the client. This is equal to the Ptolemy time minus one time step, because at time t_k, a client gets the output of other clients at t_{k-1}, which allows the client to compute the states and outputs at t_k

Constructor Detail

Simulator

public Simulator(CompositeEntity container,
                 java.lang.String name)
          throws NameDuplicationException,
                 IllegalActionException
Constructs an actor with the given container and name.

Parameters:
container - The container.
name - The name of this actor.
Throws:
IllegalActionException - If the actor cannot be contained by the proposed container.
NameDuplicationException - If the container already has an actor with this name.
Method Detail

clone

public java.lang.Object clone(Workspace workspace)
                       throws java.lang.CloneNotSupportedException
Clone the actor into the specified workspace. This calls the base class and then sets the init and step public members to the parameters of the new actor.

Overrides:
clone in class AtomicActor
Parameters:
workspace - The workspace for the new object.
Returns:
A new actor.
Throws:
java.lang.CloneNotSupportedException - If a derived class contains an attribute that cannot be cloned.
See Also:
NamedObj.exportMoML(Writer, int, String), NamedObj.setDeferringChangeRequests(boolean)

fire

public void fire()
          throws IllegalActionException
Send the input token to the client program and send the output from the client program to the output port.

Specified by:
fire in interface Executable
Overrides:
fire in class AtomicActor
Throws:
IllegalActionException - If the simulation time between Ptolemy and the client program is not synchronized.

_outputInitToken

protected void _outputInitToken()
                         throws IllegalActionException
Output the first token during initialize.

Throws:
IllegalActionException

_writeToServer

protected void _writeToServer()
                       throws IllegalActionException
Write the data to the server instance, which will send it to the client program.

Throws:
IllegalActionException - If there was an error when writing to the server.

_readFromServer

protected void _readFromServer()
                        throws IllegalActionException
Read the data from the server instance, which will read it from the client program.

Throws:
IllegalActionException - If there was an error when reading from the server.

preinitialize

public void preinitialize()
                   throws IllegalActionException
Initializes the data members and checks if the parameters of the actor are valid.

Specified by:
preinitialize in interface Initializable
Overrides:
preinitialize in class AtomicActor
Throws:
IllegalActionException - If the parameters of the actor are invalid, or if the file with the socket information cannot be written to disk.

resolveCommandName

public static java.lang.String resolveCommandName(java.io.File programName)
                                           throws IllegalActionException
Resolve the command string. This method replaces $CLASSPATH, relative file names and adds .exe to the command (under Windows)

Parameters:
programName - Name of program that starts the simulation.
Returns:
The command line string.
Throws:
IllegalActionException - If the simulation process arguments are invalid.

resolveDirectory

public static java.lang.String resolveDirectory(NamedObj namedObj,
                                                java.lang.String dir)
                                         throws IllegalActionException
Resolve the working string. This method adds the path of the MoML file to its argument if the argument is a relative directory.

Parameters:
namedObj - A named object, typically the container of the model
dir - The directory to be resolved.
Returns:
The resolved working string.
Throws:
IllegalActionException - If an attribute is found with the name "_uri" that is not an instance of the URIAttribute class

_startSimulation

protected void _startSimulation()
                         throws IllegalActionException
Start the simulation program.

Throws:
IllegalActionException - If the simulation process arguments are invalid.

initialize

public void initialize()
                throws IllegalActionException
Initialize state variables.

Specified by:
initialize in interface Initializable
Overrides:
initialize in class AtomicActor
Throws:
IllegalActionException - If the parent class throws it or if the server socket cannot be opened

wrapup

public void wrapup()
            throws IllegalActionException
Closes sockets and shuts down the simulator.

Specified by:
wrapup in interface Initializable
Overrides:
wrapup in class AtomicActor
Throws:
IllegalActionException - if the base class throws it or if an I/O error occurs when closing the socket.

cutQuotationMarks

public static java.lang.String cutQuotationMarks(java.lang.String str)
Cut the leading and terminating quotation marks if present.

Parameters:
str - The string.
Returns:
The string with leading and terminating quotation marks removed if present

_getDoubleArray

protected double[] _getDoubleArray(Token t)
                            throws IllegalActionException
Get a double array from the Token.

Parameters:
t - the token which must be a type that can be converted to an ArrayToken
Returns:
the double[] array with the elements of the Token
Throws:
IllegalActionException - If the base class throws it.