ptolemy.domains.fsm.kernel
Class FSMActor

java.lang.Object
  extended byptolemy.kernel.util.NamedObj
      extended byptolemy.kernel.InstantiableNamedObj
          extended byptolemy.kernel.Entity
              extended byptolemy.kernel.ComponentEntity
                  extended byptolemy.kernel.CompositeEntity
                      extended byptolemy.domains.fsm.kernel.FSMActor
All Implemented Interfaces:
Actor, Changeable, java.lang.Cloneable, Debuggable, DebugListener, Derivable, Executable, ExplicitChangeContext, Instantiable, ModelErrorHandler, MoMLExportable, Nameable, java.io.Serializable, TypedActor
Direct Known Subclasses:
InterfaceAutomaton, ModalController

public class FSMActor
extends CompositeEntity
implements TypedActor, ExplicitChangeContext

An FSMActor contains a set of states and transitions. A transition has a guard expression and a trigger expression. A transition is enabled and can be taken when its guard is true. A transition is triggered and must be taken when its trigger is true. A transition can contain a set of actions.

When an FSMActor is fired, the outgoing transitions of the current state are examined. An IllegalActionException is thrown if there is more than one enabled transition. If there is exactly one enabled transition then it is chosen and the choice actions contained by the transition are executed. An FSMActor does not change state during successive firings in one iteration in order to support domains that iterate to a fixed point. When the FSMActor is postfired, the chosen transition of the latest firing of the actor is committed. The commit actions contained by the transition are executed and the current state of the actor is set to the destination state of the transition.

An FSMActor enters its initial state during initialization. The name of the initial state is specified by the initialStateName string attribute. When the actor reaches a final state, then the postfire method will return false, indicating that the actor does not wish to be fired again. The finalStateNames string attribute is a comma-separated list of the names of final states.

The guards and actions of FSM transitions are specified using expressions. These expressions are evaluated in the scope returned by getPortScope. This scope binds identifiers for FSM ports as defined in the following paragraph. These identifiers are in the scope of guard and action expressions prior to any variables, and may shadow variables with appropriately chosen names. Given appropriately chosen port names, there may be conflicts between these various identifiers. These conflicts are detected and an exception is thrown during execution.

For every input port, the identifier "portName_channelIndex" refers to the last input received from the port on the given channel. The type of this identifier is the same as the type of the port. This token may have been consumed in the current firing or in a previous firing. The identifier "portName_channelIndex_isPresent" is true if the port consumed an input on the given channel in the current firing of the FSM. The type of this identifier is always boolean. Lastly, the identifier "portName_channelIndexArray" refers the array of all tokens consumed from the port in the last firing. This identifier has an array type whose element type is the type of the corresponding input port. Additionally, for conciseness when referencing single ports, the first channel may be referred to without the channel index, i.e. by the identifiers "portName", "portName_isPresent", and "portNameArray".

An FSMActor can be used in a modal model to represent the mode control logic. A state can have a TypedActor refinement. A transition in an FSMActor can be preemptive or non-preemptive. When a preemptive transition is chosen, the refinement of its source state is not fired. A non-preemptive transition can only be chosen after the refinement of its source state is fired.

Since:
Ptolemy II 0.4
Version:
$Id: FSMActor.java,v 1.119.2.2 2004/06/20 03:11:58 cxh Exp $
Author:
Xiaojun Liu
See Also:
State, Transition, Action, FSMDirector, Serialized Form
Accepted Rating:
Yellow (kienhuis)
Proposed Rating:
Yellow (liuxj)

Nested Class Summary
 
Nested classes inherited from class ptolemy.kernel.CompositeEntity
CompositeEntity.ContainedObjectsIterator
 
Field Summary
protected  State _currentState
           
protected  java.util.Map _inputTokenMap
           
protected  Transition _lastChosenTransition
           
protected  boolean _stopRequested
          Indicator that a stop has been requested by a call to stop().
 StringAttribute finalStateNames
          Attribute specifying the names of the final states of this actor.
 StringAttribute initialStateName
          Attribute specifying the name of the initial state of this actor.
 
Fields inherited from class ptolemy.kernel.util.NamedObj
_changeListeners, _changeLock, _changeRequests, _debugging, _debugListeners, _elementName, _isPersistent, _workspace, ATTRIBUTES, CLASSNAME, COMPLETE, CONTENTS, DEEP, FULLNAME, LINKS
 
Fields inherited from interface ptolemy.actor.Executable
COMPLETED, NOT_READY, STOP_ITERATING
 
Constructor Summary
FSMActor()
          Construct an FSMActor in the default workspace with an empty string as its name.
FSMActor(CompositeEntity container, java.lang.String name)
          Create an FSMActor in the specified container with the specified name.
FSMActor(Workspace workspace)
          Construct an FSMActor in the specified workspace with an empty string as its name.
 
Method Summary
protected  void _addEntity(ComponentEntity entity)
          Add a state to this FSMActor.
protected  void _addRelation(ComponentRelation relation)
          Add a transition to this FSMActor.
protected  Transition _checkTransition(java.util.List transitionList)
          Return the enabled transition among the given list of transitions.
protected  Transition _chooseTransition(java.util.List transitionList)
          Return the enabled transition among the given list of transitions.
protected  void _commitLastChosenTransition()
          Execute all commit actions contained by the transition chosen during the last call to _chooseTransition().
protected  boolean _isRefinementOutput(IOPort port, int channel)
          Return true if the channel of the port is connected to an output port of the refinement of current state.
protected  void _readInputs()
          Set the value of the shadow variables for input ports of this actor.
protected  void _readInputs(IOPort port, int channel)
          Read tokens from the given channel of the given input port and make them accessible to the expressions of guards and transitions through the port scope.
protected  void _readOutputsFromRefinement()
          Set the input variables for channels that are connected to an output port of the refinement of current state.
protected  void _setCurrentConnectionMap()
           
 void attributeChanged(Attribute attribute)
          React to a change in an attribute.
 java.lang.Object clone(Workspace workspace)
          Clone the actor into the specified workspace.
 State currentState()
          Return the current state of this actor.
 void fire()
          Set the values of input variables.
 Entity getContext()
          Return the change context being made explicit.
 Director getDirector()
          Return the director responsible for the execution of this actor.
 Director getExecutiveDirector()
          Return the executive director (same as getDirector()).
 FunctionDependency getFunctionDependency()
          Return an instance of DirectedGraph, where the nodes are IOPorts, and the edges are the relations between ports.
 State getInitialState()
          Return the initial state of this actor.
 Manager getManager()
          Return the Manager responsible for execution of this actor, if there is one.
 java.util.List getModifiedVariables()
          Return a list of variables that this entity modifies.
 ParserScope getPortScope()
          Return a scope object that has current values from input ports of this FSMActor in scope.
 void initialize()
          Initialize this actor.
 java.util.List inputPortList()
          Return a list of the input ports.
 boolean isOpaque()
          Return true.
 int iterate(int count)
          Invoke a specified number of iterations of the actor.
 Port newPort(java.lang.String name)
          Create a new TypedIOPort with the specified name.
 Receiver newReceiver()
          Return a new receiver obtained from the director.
 ComponentRelation newRelation(java.lang.String name)
          Create a new instance of Transition with the specified name in this actor, and return it.
 java.util.List outputPortList()
          Return a list of the output ports.
 boolean postfire()
          Execute actions on the last chosen transition.
 boolean prefire()
          Return true.
 void preinitialize()
          Create receivers and input variables for the input ports of this actor, and validate attributes of this actor, and attributes of the ports of this actor.
 void reset()
          Reset current state to the initial state.
 void setHDFFSMActor(boolean flag)
          Set the HDFFSMActor flag.
 void setNewIteration(boolean newIteration)
          Set the flag indicating whether we are at the start of a new iteration (firing).
 void stop()
          Request that execution of the current iteration stop as soon as possible.
 void stopFire()
          Do nothing.
 void terminate()
          Call stop().
 java.util.List typeConstraintList()
          Return the type constraints of this actor.
 void wrapup()
          Do nothing.
 
Methods inherited from class ptolemy.kernel.CompositeEntity
_adjustDeferrals, _description, _exportMoMLContents, _finishedAddEntity, _removeEntity, _removeRelation, allAtomicEntityList, allowLevelCrossingConnect, classDefinitionList, connect, connect, containedObjectsIterator, deepEntityList, deepGetEntities, entityList, entityList, exportLinks, getAttribute, getEntities, getEntity, getPort, getRelation, getRelations, isAtomic, numberOfClassDefinitions, numberOfEntities, numberOfRelations, numEntities, numRelations, relationList, removeAllEntities, removeAllRelations, uniqueName, validateSettables
 
Methods inherited from class ptolemy.kernel.ComponentEntity
_addPort, _checkContainer, _getContainedObject, _propagateExistence, getContainer, instantiate, propagateExistence, setContainer, setName
 
Methods inherited from class ptolemy.kernel.Entity
_removePort, connectedPortList, connectedPorts, connectionsChanged, getPorts, linkedRelationList, linkedRelations, portList, removeAllPorts, setClassDefinition
 
Methods inherited from class ptolemy.kernel.InstantiableNamedObj
_setParent, exportMoML, getChildren, getElementName, getParent, getPrototypeList, isClassDefinition
 
Methods inherited from class ptolemy.kernel.util.NamedObj
_addAttribute, _attachText, _cloneFixAttributeFields, _debug, _debug, _debug, _debug, _debug, _getIndentPrefix, _isMoMLSuppressed, _markContentsDerived, _propagateValue, _removeAttribute, _splitName, _stripNumericSuffix, addChangeListener, addDebugListener, attributeList, attributeList, attributeTypeChanged, clone, deepContains, depthInHierarchy, description, description, event, executeChangeRequests, exportMoML, exportMoML, exportMoML, exportMoML, getAttribute, getAttributes, getChangeListeners, getClassName, getDerivedLevel, getDerivedList, getFullName, getModelErrorHandler, getName, getName, getSource, handleModelError, isDeferringChangeRequests, isOverridden, isPersistent, message, propagateValue, propagateValues, removeChangeListener, removeDebugListener, requestChange, setClassName, setDeferringChangeRequests, setDerivedLevel, setModelErrorHandler, setPersistent, setSource, toplevel, toString, workspace
 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 
Methods inherited from interface ptolemy.kernel.util.Nameable
description, getContainer, getFullName, getName, getName, setName
 
Methods inherited from interface ptolemy.kernel.util.Derivable
getDerivedLevel, getDerivedList, propagateValue
 

Field Detail

finalStateNames

public StringAttribute finalStateNames
Attribute specifying the names of the final states of this actor. The names are separated by commas. Space characters at the beginning, the end, and around commas are ignored. Space characters within a name are preserved. For example, the value " final, my state 5" designates states "final" and "my state 5" as final.


initialStateName

public StringAttribute initialStateName
Attribute specifying the name of the initial state of this actor.


_currentState

protected State _currentState

_inputTokenMap

protected java.util.Map _inputTokenMap

_lastChosenTransition

protected Transition _lastChosenTransition

_stopRequested

protected boolean _stopRequested
Indicator that a stop has been requested by a call to stop().

Constructor Detail

FSMActor

public FSMActor()
Construct an FSMActor in the default workspace with an empty string as its name. Add the actor to the workspace directory. Increment the version number of the workspace.


FSMActor

public FSMActor(Workspace workspace)
Construct an FSMActor in the specified workspace with an empty string as its name. You can then change the name with setName(). If the workspace argument is null, then use the default workspace. Add the actor to the workspace directory. Increment the version number of the workspace.

Parameters:
workspace - The workspace that will list the actor.

FSMActor

public FSMActor(CompositeEntity container,
                java.lang.String name)
         throws IllegalActionException,
                NameDuplicationException
Create an FSMActor in the specified container with the specified name. The name must be unique within the container or an exception is thrown. The container argument must not be null, or a NullPointerException will be thrown.

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

attributeChanged

public void attributeChanged(Attribute attribute)
                      throws IllegalActionException
React to a change in an attribute. If the changed attribute is the initialStateName attribute, record the change but do not check whether this actor contains a state with the specified name.

Overrides:
attributeChanged in class NamedObj
Parameters:
attribute - The attribute that changed.
Throws:
IllegalActionException - If thrown by the superclass attributeChanged() method.

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 attribute public members to refer to the attributes of the new actor.

Overrides:
clone in class CompositeEntity
Parameters:
workspace - The workspace for the new actor.
Returns:
A new FSMActor.
Throws:
java.lang.CloneNotSupportedException - If a derived class contains an attribute that cannot be cloned.

currentState

public State currentState()
Return the current state of this actor.

Returns:
The current state of this actor.

fire

public void fire()
          throws IllegalActionException
Set the values of input variables. Choose the enabled transition among the outgoing transitions of the current state. Throw an exception if there is more than one transition enabled. Otherwise, execute the choice actions contained by the chosen transition.

Specified by:
fire in interface Executable
Throws:
IllegalActionException - If there is more than one transition enabled.

getContext

public Entity getContext()
Return the change context being made explicit. This class returns this.

Specified by:
getContext in interface ExplicitChangeContext

getDirector

public Director getDirector()
Return the director responsible for the execution of this actor. In this class, this is always the executive director. Return null if either there is no container or the container has no director.

Specified by:
getDirector in interface Actor
Returns:
The director that invokes this actor.

getExecutiveDirector

public Director getExecutiveDirector()
Return the executive director (same as getDirector()).

Specified by:
getExecutiveDirector in interface Actor
Returns:
The executive director.

getInitialState

public State getInitialState()
                      throws IllegalActionException
Return the initial state of this actor. The name of the initial state is specified by the initialStateName attribute. An exception is thrown if this actor does not contain a state with the specified name. This method is read-synchronized on the workspace.

Returns:
The initial state of this actor.
Throws:
IllegalActionException - If this actor does not contain a state with the specified name.

getFunctionDependency

public FunctionDependency getFunctionDependency()
Return an instance of DirectedGraph, where the nodes are IOPorts, and the edges are the relations between ports. The graph shows the dependencies between the input and output ports. If there is a path between a pair, input and output, they are dependent. Otherwise, they are independent.

Specified by:
getFunctionDependency in interface Actor
Returns:
A FunctionDependency object of an FSM actor.
See Also:
FunctionDependency

getManager

public Manager getManager()
Return the Manager responsible for execution of this actor, if there is one. Otherwise, return null.

Specified by:
getManager in interface Actor
Returns:
The manager.

getModifiedVariables

public java.util.List getModifiedVariables()
                                    throws IllegalActionException
Return a list of variables that this entity modifies. The variables are assumed to have a change context of the given entity. This method returns the destinations of all choice and commit identifiers.

Specified by:
getModifiedVariables in interface ExplicitChangeContext
Returns:
A list of variables.
Throws:
IllegalActionException - If the list of modified variables cannot be returned.

getPortScope

public ParserScope getPortScope()
Return a scope object that has current values from input ports of this FSMActor in scope. This scope is used to evaluate guard expressions and set and output actions.


initialize

public void initialize()
                throws IllegalActionException
Initialize this actor. Goto initial state.

Specified by:
initialize in interface Executable
Throws:
IllegalActionException - If a derived class throws it.

inputPortList

public java.util.List inputPortList()
Return a list of the input ports. This method is read-synchronized on the workspace.

Specified by:
inputPortList in interface Actor
Returns:
A list of input IOPort objects.

isOpaque

public boolean isOpaque()
Return true.

Overrides:
isOpaque in class CompositeEntity
Returns:
True.
See Also:
CompositeEntity

iterate

public int iterate(int count)
            throws IllegalActionException
Invoke a specified number of iterations of the actor. An iteration is equivalent to invoking prefire(), fire(), and postfire(), in that order. In an iteration, if prefire() returns true, then fire() will be called once, followed by postfire(). Otherwise, if prefire() returns false, fire() and postfire() are not invoked, and this method returns NOT_READY. If postfire() returns false, then no more iterations are invoked, and this method returns STOP_ITERATING. Otherwise, it returns COMPLETED. If stop() is called while this is executing, then cease executing and return STOP_ITERATING.

Specified by:
iterate in interface Executable
Parameters:
count - The number of iterations to perform.
Returns:
NOT_READY, STOP_ITERATING, or COMPLETED.
Throws:
IllegalActionException - If iterating is not permitted, or if prefire(), fire(), or postfire() throw it.

newPort

public Port newPort(java.lang.String name)
             throws NameDuplicationException
Create a new TypedIOPort with the specified name. The container of the port is set to this actor. This method is write-synchronized on the workspace.

Overrides:
newPort in class ComponentEntity
Parameters:
name - The name for the new port.
Returns:
The new port.
Throws:
NameDuplicationException - If the actor already has a port with the specified name.

newReceiver

public Receiver newReceiver()
                     throws IllegalActionException
Return a new receiver obtained from the director.

Specified by:
newReceiver in interface Actor
Returns:
A new object implementing the Receiver interface.
Throws:
IllegalActionException - If there is no director.

newRelation

public ComponentRelation newRelation(java.lang.String name)
                              throws IllegalActionException,
                                     NameDuplicationException
Create a new instance of Transition with the specified name in this actor, and return it. This method is write-synchronized on the workspace.

Overrides:
newRelation in class CompositeEntity
Parameters:
name - The name of the new transition.
Returns:
A transition with the given name.
Throws:
IllegalActionException - If the name argument is null.
NameDuplicationException - If name collides with that of a transition already in this actor.

outputPortList

public java.util.List outputPortList()
Return a list of the output ports. This method is read-synchronized on the workspace.

Specified by:
outputPortList in interface Actor
Returns:
A list of output IOPort objects.

postfire

public boolean postfire()
                 throws IllegalActionException
Execute actions on the last chosen transition. Change state to the destination state of the last chosen transition.

Specified by:
postfire in interface Executable
Returns:
True, unless stop() has been called, in which case, false.
Throws:
IllegalActionException - If any action throws it.

prefire

public boolean prefire()
                throws IllegalActionException
Return true.

Specified by:
prefire in interface Executable
Returns:
True.
Throws:
IllegalActionException - Not thrown in this base class.

preinitialize

public void preinitialize()
                   throws IllegalActionException
Create receivers and input variables for the input ports of this actor, and validate attributes of this actor, and attributes of the ports of this actor. Set current state to the initial state. Throw an exception if this actor does not contain a state with name specified by the initialStateName attribute.

Specified by:
preinitialize in interface Executable
Throws:
IllegalActionException - If this actor does not contain a state with name specified by the initialStateName attribute.

reset

public void reset()
           throws IllegalActionException
Reset current state to the initial state. The name of the initial state is specified by the initialStateName attribute.

Throws:
IllegalActionException - If this actor does not contain a state with name specified by the initialStateName attribute.

setHDFFSMActor

public void setHDFFSMActor(boolean flag)
Set the HDFFSMActor flag.

Parameters:
flag - Indicator that whether the FSMActor is under a HDFFSMDirector.

setNewIteration

public void setNewIteration(boolean newIteration)
Set the flag indicating whether we are at the start of a new iteration (firing). Normally, the flag is set to true. It is only set to false in HDF.

Parameters:
newIteration -

stop

public void stop()
Request that execution of the current iteration stop as soon as possible. In this class, we set a flag indicating that this request has been made (the protected variable _stopRequested). This will result in postfire() returning false.

Specified by:
stop in interface Executable

stopFire

public void stopFire()
Do nothing.

Specified by:
stopFire in interface Executable

terminate

public void terminate()
Call stop().

Specified by:
terminate in interface Executable

typeConstraintList

public java.util.List typeConstraintList()
Return the type constraints of this actor. The constraints have the form of a list of inequalities. This method first creates constraints such that the type of any input port that does not have its type declared must be less than or equal to the type of any output port that does not have its type declared. Type constraints from the contained Typeables (ports, variables, and parameters) are collected. In addition, type constraints from all the transitions are added. These constraints are determined by the guard and trigger expressions of transitions, and actions contained by the transitions. This method is read-synchronized on the workspace.

Specified by:
typeConstraintList in interface TypedActor
Returns:
A list of inequalities.
See Also:
Inequality

wrapup

public void wrapup()
            throws IllegalActionException
Do nothing. Derived classes override this method to define operations to be performed exactly once at the end of a complete execution of an application. It typically closes files, displays final results, etc.

Specified by:
wrapup in interface Executable
Throws:
IllegalActionException - Not thrown in this base class.

_addEntity

protected void _addEntity(ComponentEntity entity)
                   throws IllegalActionException,
                          NameDuplicationException
Add a state to this FSMActor. This overrides the base-class method to make sure the argument is an instance of State. This method is not synchronized on the workspace, so the caller should be.

Overrides:
_addEntity in class CompositeEntity
Parameters:
entity - State to contain.
Throws:
IllegalActionException - If the state has no name, or the action would result in a recursive containment structure, or the argument is not an instance of State.
NameDuplicationException - If the name collides with a name already on the state list.

_addRelation

protected void _addRelation(ComponentRelation relation)
                     throws IllegalActionException,
                            NameDuplicationException
Add a transition to this FSMActor. This method should not be used directly. Call the setContainer() method of the transition instead. This method does not set the container of the transition to refer to this container. This method is not synchronized on the workspace, so the caller should be.

Overrides:
_addRelation in class CompositeEntity
Parameters:
relation - Transition to contain.
Throws:
IllegalActionException - If the transition has no name, or is not an instance of Transition.
NameDuplicationException - If the name collides with a name already on the contained transitions list.

_checkTransition

protected Transition _checkTransition(java.util.List transitionList)
                               throws IllegalActionException
Return the enabled transition among the given list of transitions. Throw an exception if there is more than one transition enabled.

Parameters:
transitionList - A list of transitions.
Returns:
An enabled transition, or null if none is enabled.
Throws:
IllegalActionException - If there is more than one transition enabled.

_chooseTransition

protected Transition _chooseTransition(java.util.List transitionList)
                                throws IllegalActionException
Return the enabled transition among the given list of transitions. Execute the choice actions contained by the transition. Throw an exception if there is more than one transition enabled.

Parameters:
transitionList - A list of transitions.
Returns:
An enabled transition, or null if none is enabled.
Throws:
IllegalActionException - If there is more than one transition enabled.

_commitLastChosenTransition

protected void _commitLastChosenTransition()
                                    throws IllegalActionException
Execute all commit actions contained by the transition chosen during the last call to _chooseTransition(). Change current state to the destination state of the transition. Reset the refinement of the destination state if the reset parameter of the transition is true.

Throws:
IllegalActionException - If any commit action throws it, or the last chosen transition does not have a destination state.

_isRefinementOutput

protected boolean _isRefinementOutput(IOPort port,
                                      int channel)
                               throws IllegalActionException
Return true if the channel of the port is connected to an output port of the refinement of current state. If the current state does not have refinement, return false.

Parameters:
port - An input port of this actor.
channel - A channel of the input port.
Returns:
True if the channel of the port is connected to an output port of the refinement of current state.
Throws:
IllegalActionException - If the refinement specified for one of the states is not valid.

_setCurrentConnectionMap

protected void _setCurrentConnectionMap()
                                 throws IllegalActionException
Throws:
IllegalActionException

_readInputs

protected void _readInputs()
                    throws IllegalActionException
Set the value of the shadow variables for input ports of this actor.

Throws:
IllegalActionException - If a shadow variable cannot take the token read from its corresponding channel (should not occur).

_readInputs

protected void _readInputs(IOPort port,
                           int channel)
                    throws IllegalActionException
Read tokens from the given channel of the given input port and make them accessible to the expressions of guards and transitions through the port scope. If the specified port is not an input port, then do nothing.

Parameters:
port - An input port of this actor.
channel - A channel of the input port.
Throws:
IllegalActionException - If the port is not contained by this actor.

_readOutputsFromRefinement

protected void _readOutputsFromRefinement()
                                   throws IllegalActionException
Set the input variables for channels that are connected to an output port of the refinement of current state.

Throws:
IllegalActionException - If a value variable cannot take the token read from its corresponding channel.