Package lbnl.actor.lib
Class Simulator
- java.lang.Object
-
- All Implemented Interfaces:
java.lang.Cloneable,Actor,Executable,FiringsRecordable,Initializable,SequenceActor,TypedActor,Changeable,Debuggable,DebugListener,Derivable,Instantiable,ModelErrorHandler,MoMLExportable,Moveable,Nameable
- Direct Known Subclasses:
LabVIEWSimulator
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 parameterprogramNamewith argumentsprogramArguments. 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$
- Author:
- Michael Wetter
-
-
Nested Class Summary
-
Nested classes/interfaces inherited from class ptolemy.kernel.Entity
Entity.ContainedObjectsIterator
-
-
Field Summary
Fields Modifier and Type Field Description protected booleanclientTerminatedFlag, set to true when the clients terminates the communication.protected ClientProcesscliProThread that runs the simulation.protected double[]dblWriDouble values that were written to the socket.protected booleanfirstFireFlag that is true during the first firing of this actor/.protected intflagWriSimulation flag to be written in socket.protected booleanisHeadlessFlag, set thetrueif Ptolemy is run without any graphical interface.protected static java.lang.StringLSSystem dependent line separator.protected DoubleMatrixTokenoutTokOutput tokens.protected booleanoutTokStaleprotected intporNoPort number that is actually used for BSD socket.ParameterprogramArgumentsArguments of program that starts the simulation.FileParameterprogramNameName of program that starts the simulation.protected ServerserverServer used for data exchange.ParametershowConsoleWindowIf true (the default), a window will be created that shows the console output.protected doublesimTimAbsTolAbsolute floating-point tolerance for events assumed to be simultaneous.protected doublesimTimPrePtolemy's time at the last call of the fire method.protected doublesimTimReaPreTime read from the simulation program at the last call of the fire method.FileParametersimulationLogFileFile name to which this actor writes the simulation log.FileParametersocketConfigurationFileFile name to which this actor writes the socket configuration.ParametersocketPortNumberPort number for BSD socket (used if non-negative).ParametersocketTimeoutSocket time out in milliseconds.ParametersynchronizeWithClientIf true, attempts to sychronize timing with the client.protected java.lang.StringterminationMessageMessage that will be displayed in the warning window when the client terminated, but Ptolemy continues with the simulation.protected TimetokTimTime of token that will be written to the client.protected java.lang.ThreadwarWinThread that is used if a warning window need to be shown.protected java.lang.StringworDirWorking directory of the subprocess.FileParameterworkingDirectoryWorking 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.TypedAtomicActor
_typesValid
-
Fields inherited from class ptolemy.actor.AtomicActor
_actorFiringListeners, _initializables, _notifyingActorFiring, _stopRequested
-
Fields inherited from class ptolemy.kernel.util.NamedObj
_changeListeners, _changeLock, _changeRequests, _debugging, _debugListeners, _deferChangeRequests, _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
Constructors Constructor Description Simulator(CompositeEntity container, java.lang.String name)Constructs an actor with the given container and name.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description 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.Objectclone(Workspace workspace)Clone the actor into the specified workspace.static java.lang.StringcutQuotationMarks(java.lang.String str)Cut the leading and terminating quotation marks if present.voidfire()Send the input token to the client program and send the output from the client program to the output port.voidfireAndSanityCheck()The legacy firing behavior.voidfireAndSynchronize()The new firing behavior.voidinitialize()Initialize state variables.voidpreinitialize()Initializes the data members and checks if the parameters of the actor are valid.static java.lang.StringresolveCommandName(java.io.File programName)Resolve the command string.static java.lang.StringresolveDirectory(NamedObj namedObj, java.lang.String dir)Resolve the working string.voidwrapup()Closes sockets and shuts down the simulator.-
Methods inherited from class ptolemy.domains.sdf.lib.SDFTransformer
prefire
-
Methods inherited from class ptolemy.actor.TypedAtomicActor
_containedTypeConstraints, _customTypeConstraints, _defaultTypeConstraints, _fireAt, _fireAt, attributeTypeChanged, clone, isBackwardTypeInferenceEnabled, newPort, typeConstraintList, typeConstraints
-
Methods inherited from class ptolemy.actor.AtomicActor
_actorFiring, _actorFiring, _declareDelayDependency, 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
_addPort, _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, _containedDecorators, _copyChangeRequestList, _debug, _debug, _debug, _debug, _debug, _executeChangeRequests, _getIndentPrefix, _isMoMLSuppressed, _markContentsDerived, _notifyHierarchyListenersAfterChange, _notifyHierarchyListenersBeforeChange, _propagateValue, _removeAttribute, _splitName, _stripNumericSuffix, addChangeListener, addDebugListener, addHierarchyListener, attributeChanged, attributeDeleted, attributeList, attributeList, decorators, 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, notifyOfNameChange, propagateValue, propagateValues, removeAttribute, removeChangeListener, removeDebugListener, removeHierarchyListener, 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.kernel.util.Derivable
getDerivedLevel, getDerivedList, propagateValue
-
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
-
-
-
-
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.
-
synchronizeWithClient
public Parameter synchronizeWithClient
If true, attempts to sychronize timing with the client.
-
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.
-
worDir
protected java.lang.String worDir
Working directory of the subprocess.
-
flagWri
protected int flagWri
Simulation flag to be written in socket.
-
outTok
protected DoubleMatrixToken outTok
Output tokens.
-
simTimPre
protected double simTimPre
Ptolemy's time at the last call of the fire method. Only used by the legacy firing method.
-
simTimReaPre
protected double simTimReaPre
Time read from the simulation program at the last call of the fire method. Only used by the legacy firing method.
-
outTokStale
protected boolean outTokStale
-
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 thetrueif Ptolemy is run without any graphical interface. IfisHeadless=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 Time 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
-
simTimAbsTol
protected double simTimAbsTol
Absolute floating-point tolerance for events assumed to be simultaneous.
-
-
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 theinitandsteppublic members to the parameters of the new actor.- Overrides:
clonein classTypedAtomicActor- 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 IllegalActionExceptionSend the input token to the client program and send the output from the client program to the output port.- Specified by:
firein interfaceExecutable- Overrides:
firein classAtomicActor<TypedIOPort>- Throws:
IllegalActionException- If the simulation time between Ptolemy and the client program is not synchronized.
-
fireAndSanityCheck
public void fireAndSanityCheck() throws IllegalActionExceptionThe legacy firing behavior. Checks that the client and the simulator are synchronized. Maintained only for backwards-compatibility.- Throws:
IllegalActionException- If thrown while checking the input for a token, reading or writing to the server, getting the input or if there are problems with the time.
-
fireAndSynchronize
public void fireAndSynchronize() throws IllegalActionExceptionThe new firing behavior. Attempts to synchronize the simulator's timing with that of the client.- Throws:
IllegalActionException- If thrown while checking the input for a token, reading or writing to the server, getting the input or if there are problems with the time.
-
_outputInitToken
protected void _outputInitToken() throws IllegalActionExceptionOutput the first token during initialize.- Throws:
IllegalActionException- If there the client flag is non-zero, or the double array returned by the server is null.
-
_writeToServer
protected void _writeToServer() throws IllegalActionExceptionWrite 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 IllegalActionExceptionRead 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 IllegalActionExceptionInitializes the data members and checks if the parameters of the actor are valid.- Specified by:
preinitializein interfaceInitializable- Overrides:
preinitializein classAtomicActor<TypedIOPort>- 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 IllegalActionExceptionResolve 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 modeldir- 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 IllegalActionExceptionStart the simulation program.- Throws:
IllegalActionException- If the simulation process arguments are invalid.
-
initialize
public void initialize() throws IllegalActionExceptionInitialize state variables.- Specified by:
initializein interfaceInitializable- Overrides:
initializein classAtomicActor<TypedIOPort>- Throws:
IllegalActionException- If the parent class throws it or if the server socket cannot be opened
-
wrapup
public void wrapup() throws IllegalActionExceptionCloses sockets and shuts down the simulator.- Specified by:
wrapupin interfaceInitializable- Overrides:
wrapupin classAtomicActor<TypedIOPort>- 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.
-
-