ptolemy.actor
Class AtomicActor

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
All Implemented Interfaces:
java.io.Serializable, java.lang.Cloneable, Actor, Executable, FiringsRecordable, Initializable, Changeable, Debuggable, DebugListener, Derivable, Instantiable, ModelErrorHandler, MoMLExportable, Moveable, Nameable
Direct Known Subclasses:
NCComponentBase, TypedAtomicActor

public class AtomicActor
extends ComponentEntity
implements Actor, FiringsRecordable

An AtomicActor is an executable entity that cannot itself contain other actors. The Ports of AtomicActors are constrained to be IOPorts. Derived classes may further constrain the ports by overriding the public method newPort() to create a port of the appropriate subclass, and the protected method _addPort() to throw an exception if its argument is a port that is not of the appropriate subclass. In this base class, the actor does nothing in the action methods (prefire, fire, ...).

Since:
Ptolemy II 0.2
Version:
$Id: AtomicActor.java 59156 2010-09-21 14:33:12Z cxh $
Author:
Mudit Goel, Edward A. Lee, Lukito Muliadi, Steve Neuendorffer, Contributor: Daniel Crawl
See Also:
CompositeActor, IOPort, Serialized Form
Accepted Rating:
Green (neuendor)
Proposed Rating:
Green (eal)

Nested Class Summary
 
Nested classes/interfaces inherited from class ptolemy.kernel.Entity
Entity.ContainedObjectsIterator
 
Field Summary
protected  java.util.LinkedList _actorFiringListeners
          The list of ActorFiringListeners registered with this object.
private  java.util.List _cachedInputPorts
           
private  java.util.List _cachedOutputPorts
           
private  CausalityInterface _causalityInterface
          The causality interface, if it has been created.
private  Director _causalityInterfaceDirector
          The director for which the causality interface was created.
protected  java.util.List<Initializable> _initializables
          List of objects whose (pre)initialize() and wrapup() methods should be slaved to these.
private  long _inputPortsVersion
           
protected  boolean _notifyingActorFiring
          Flag that is true if there are actor firing listeners.
private  long _outputPortsVersion
           
private  long _receiversVersion
          Record of the workspace version the last time receivers were created.
protected  boolean _stopRequested
          Indicator that a stop has been requested by a call to stop().
 
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
AtomicActor()
          Construct an actor in the default workspace with an empty string as its name.
AtomicActor(CompositeEntity container, java.lang.String name)
          Create a new actor in the specified container with the specified name.
AtomicActor(Workspace workspace)
          Construct an actor in the specified workspace with an empty string as a name.
 
Method Summary
protected  void _actorFiring(FiringEvent.FiringEventType type, int multiplicity)
          Send an actor firing event type to all actor firing listeners that have registered with this actor.
protected  void _actorFiring(FiringEvent event)
          Send an actor firing event to all actor firing listeners that have registered with this actor.
protected  void _addPort(Port port)
          Override the base class to throw an exception if the added port is not an instance of IOPort.
 void addActorFiringListener(ActorFiringListener listener)
          Append a listener to the current set of actor firing listeners.
 void addInitializable(Initializable initializable)
          Add the specified object to the list of objects whose preinitialize(), initialize(), and wrapup() methods should be invoked upon invocation of the corresponding methods of this object.
 java.lang.Object clone(Workspace workspace)
          Clone this actor into the specified workspace.
 void connectionsChanged(Port port)
          Create new receivers if the port is an input port and there is a director.
 void createReceivers()
          Create receivers for each input port.
 void declareDelayDependency(IOPort input, IOPort output, double timeDelay)
          Set the dependency that the specified output port has on the specified input port to represent a time delay with the specified value.
 void fire()
          Do nothing.
 CausalityInterface getCausalityInterface()
          Return a causality interface for this actor.
 Director getDirector()
          Return the director responsible for the execution of this actor.
 Director getExecutiveDirector()
          Return the executive director (same as getDirector()).
 Manager getManager()
          Return the Manager responsible for execution of this actor, if there is one.
 void initialize()
          Initialize this actor.
 java.util.List inputPortList()
          List all the input ports.
 boolean isFireFunctional()
          Return true.
 boolean isStrict()
          Return true in this base class.
 int iterate(int count)
          Invoke a specified number of iterations of the actor.
 Port newPort(java.lang.String name)
          Create a new IOPort with the specified name.
 Receiver newReceiver()
          Return a new receiver of a type compatible with the director.
 java.util.List outputPortList()
          List the output ports.
 boolean postfire()
          Return true, unless stop() has been called, in which case, return false.
 boolean prefire()
          Return true.
 void preinitialize()
          Create receivers.
 void pruneDependencies()
          Deprecated. There is no need to override this method anymore. Just call removeDependency() in preinitialize().
 void recordFiring(FiringEvent.FiringEventType type)
          Record a firing event.
 void removeActorFiringListener(ActorFiringListener listener)
          Unregister an actor firing listener.
 void removeDependency(IOPort input, IOPort output)
          Remove the dependency that the specified output port has, by default, on the specified input port.
 void removeInitializable(Initializable initializable)
          Remove the specified object from the list of objects whose preinitialize(), initialize(), and wrapup() methods should be invoked upon invocation of the corresponding methods of this object.
 void setContainer(CompositeEntity container)
          Override the base class to invalidate the schedule and resolved types of the director.
 void stop()
          Request that execution of the current iteration stop as soon as possible.
 void stopFire()
          Request that execution of the current iteration complete.
 void terminate()
          Terminate execution immediately.
 void wrapup()
          Do nothing except invoke the wrapup() methods of any objects that have been registered with addInitializable().
 
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, attributeTypeChanged, clone, 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.kernel.util.Nameable
description, getContainer, getDisplayName, getFullName, getName, getName, setName
 
Methods inherited from interface ptolemy.kernel.util.Derivable
getDerivedLevel, getDerivedList, propagateValue
 

Field Detail

_actorFiringListeners

protected java.util.LinkedList _actorFiringListeners
The list of ActorFiringListeners registered with this object. NOTE: Because of the way we synchronize on this object, it should never be reset to null after the first list is created.


_initializables

protected transient java.util.List<Initializable> _initializables
List of objects whose (pre)initialize() and wrapup() methods should be slaved to these.


_notifyingActorFiring

protected boolean _notifyingActorFiring
Flag that is true if there are actor firing listeners.


_stopRequested

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


_inputPortsVersion

private transient long _inputPortsVersion

_cachedInputPorts

private transient java.util.List _cachedInputPorts

_outputPortsVersion

private transient long _outputPortsVersion

_cachedOutputPorts

private transient java.util.List _cachedOutputPorts

_causalityInterface

private CausalityInterface _causalityInterface
The causality interface, if it has been created.


_causalityInterfaceDirector

private Director _causalityInterfaceDirector
The director for which the causality interface was created.


_receiversVersion

private long _receiversVersion
Record of the workspace version the last time receivers were created.

Constructor Detail

AtomicActor

public AtomicActor()
Construct an actor in the default workspace with an empty string as its name. Increment the version number of the workspace. The object is added to the workspace directory.


AtomicActor

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

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

AtomicActor

public AtomicActor(CompositeEntity container,
                   java.lang.String name)
            throws IllegalActionException,
                   NameDuplicationException
Create a new actor 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 (see the setContainer() method).
NameDuplicationException - If the name coincides with an entity already in the container.
Method Detail

addInitializable

public void addInitializable(Initializable initializable)
Add the specified object to the list of objects whose preinitialize(), initialize(), and wrapup() methods should be invoked upon invocation of the corresponding methods of this object.

Specified by:
addInitializable in interface Initializable
Parameters:
initializable - The object whose methods should be invoked.
See Also:
removeInitializable(Initializable), CompositeActor.addPiggyback(Executable)

addActorFiringListener

public void addActorFiringListener(ActorFiringListener listener)
Append a listener to the current set of actor firing listeners. If the listener is already in the set, it will not be added again. Note that this method is basically the same as addDebugListener in the class NamedObj.

Specified by:
addActorFiringListener in interface FiringsRecordable
Parameters:
listener - The listener to which to send actor firing messages.
See Also:
removeActorFiringListener(ActorFiringListener)

clone

public java.lang.Object clone(Workspace workspace)
                       throws java.lang.CloneNotSupportedException
Clone this actor into the specified workspace. The new actor is not added to the directory of that workspace (you must do this yourself if you want it there). The result is a new actor with the same ports as the original, but no connections and no container. A container must be set before much can be done with this actor.

Overrides:
clone in class ComponentEntity
Parameters:
workspace - The workspace for the cloned object.
Returns:
A new ComponentEntity.
Throws:
java.lang.CloneNotSupportedException - If cloned ports cannot have as their container the cloned entity (this should not occur), or if one of the attributes cannot be cloned.
See Also:
NamedObj.exportMoML(Writer, int, String), NamedObj.setDeferringChangeRequests(boolean)

connectionsChanged

public void connectionsChanged(Port port)
Create new receivers if the port is an input port and there is a director.

Overrides:
connectionsChanged in class Entity
Parameters:
port - The port that has connection changes.

createReceivers

public void createReceivers()
                     throws IllegalActionException
Create receivers for each input port.

Specified by:
createReceivers in interface Actor
Throws:
IllegalActionException - If any port throws it.
See Also:
createReceivers(), CompositeActor.createReceivers()

declareDelayDependency

public void declareDelayDependency(IOPort input,
                                   IOPort output,
                                   double timeDelay)
                            throws IllegalActionException
Set the dependency that the specified output port has on the specified input port to represent a time delay with the specified value. By default, each output port is assumed to have a dependency on all input ports. Subclasses can call this method in preinitialize() instead of implementing a custom CausalityInterface for the cases where output ports depend on input ports with a time delay. If the time delay is 0.0, this method nonetheless assumes that the output port does not (immediately) depend on the input port (this amounts to a superdense time delay of (0.0, 1)). There should be one such call for each input, output pair that does not have a dependency.

Parameters:
input - The input port.
output - The output port with a time delay dependency on the input port.
timeDelay - The time delay.
Throws:
IllegalActionException - Thrown if causality interface cannot be computed.
See Also:
getCausalityInterface()

fire

public void fire()
          throws IllegalActionException
Do nothing. Derived classes override this method to define their primary run-time action.

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

getCausalityInterface

public CausalityInterface getCausalityInterface()
                                         throws IllegalActionException
Return a causality interface for this actor. In this base class, we return an instance of DefaultCausalityInterface with the dependency type given by the director, or with a BooleanDependency if there is no director. This declares that all output ports of the actor depend on all input ports, unless the actor calls removeDependency(IOPort, IOPort) or declareDelayDependency(IOPort, IOPort, double). If this is called multiple times, the same object is returned each time unless the director has changed since the last call, in which case a new object is returned.

Specified by:
getCausalityInterface in interface Actor
Returns:
A representation of the dependencies between input ports and output ports.
Throws:
IllegalActionException - Thrown in subclasses if causality interface cannot be computed.

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.

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.

initialize

public void initialize()
                throws IllegalActionException
Initialize this actor. Derived classes override this method to perform actions that should occur once at the beginning of an execution, but after type resolution. Derived classes can produce output data and schedule events.

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

inputPortList

public java.util.List inputPortList()
List all the input ports. This method is read-synchronized on the workspace.

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

isFireFunctional

public boolean isFireFunctional()
Return true. Most actors are written so that the prefire() and fire() methods do not change the state of the actor. Hence, for convenience, this base class by default returns true. An actor that does change state in prefire() or fire() must override this method to return false.

Specified by:
isFireFunctional in interface Executable
Returns:
True.

isStrict

public boolean isStrict()
Return true in this base class. By default, actors do not check their inputs to see whether they are known. They assume they are known. A derived class that can tolerate unknown inputs should override this method to return false.

Specified by:
isStrict in interface Executable
Returns:
True always in this base class.

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.

This base class method actually invokes prefire(), fire(), and postfire(), as described above, but a derived class may override the method to execute more efficient code.

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 IOPort with the specified name. The container of the port is set to this actor. This method is write-synchronized on the workspace. Normally this method is not called directly by actor code. Instead, a change request should be queued with the director.

Overrides:
newPort in class ComponentEntity
Parameters:
name - The name for the new port.
Returns:
The new port.
Throws:
NameDuplicationException - If this actor already has a port with the specified name.
See Also:
Workspace.getWriteAccess()

newReceiver

public Receiver newReceiver()
                     throws IllegalActionException
Return a new receiver of a type compatible with the director. Derived classes may further specialize this to return a receiver specialized to the particular actor.

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

outputPortList

public java.util.List outputPortList()
List 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
Return true, unless stop() has been called, in which case, return false. Derived classes override this method to define operations to be performed at the end of every iteration of its execution, after one invocation of the prefire() method and any number of invocations of the fire() method. This method typically wraps up an iteration, which may involve updating local state. In derived classes, this method returns false to indicate that this actor should not be fired again.

Specified by:
postfire in interface Executable
Returns:
True if execution can continue into the next iteration.
Throws:
IllegalActionException - Not thrown in this base class.

prefire

public boolean prefire()
                throws IllegalActionException
Return true. Derived classes override this method to define operations to be performed at the beginning of every iteration of its execution, prior the invocation of the fire() method. Derived classes may also use it to check preconditions for an iteration, if there are any.

Specified by:
prefire in interface Executable
Returns:
True if this actor is ready for firing, false otherwise.
Throws:
IllegalActionException - Not thrown in this base class.

preinitialize

public void preinitialize()
                   throws IllegalActionException
Create receivers. Derived classes can override this method to perform additional initialization functions, but they should call this base class methods or create the receivers themselves. This method gets executed exactly once prior to any other action methods. It cannot produce output data since type resolution is typically not yet done. It also gets invoked prior to any static scheduling that might occur in the domain, so it can change scheduling information.

Specified by:
preinitialize in interface Initializable
Throws:
IllegalActionException - Not thrown in this base class.

pruneDependencies

public void pruneDependencies()
                       throws IllegalActionException
Deprecated. There is no need to override this method anymore. Just call removeDependency() in preinitialize().

Prune the dependency declarations, which by default state that each output port depends on all input ports in a firing. This base class does no pruning, but subclasses that have output ports that do not depend on input ports should override this method to prune the dependencies. To declare that an output port does not depend on an input port, subclasses can call removeDependency(input, output) rather than implementing a specialized CausalityInterface, at least for the simple cases where output ports do not depend at all on input ports.

Throws:
IllegalActionException - Thrown by subclasses if causality interface cannot be computed.
See Also:
TimedDelay, removeDependency(IOPort, IOPort), getCausalityInterface()

recordFiring

public void recordFiring(FiringEvent.FiringEventType type)
Record a firing event.

Specified by:
recordFiring in interface FiringsRecordable
Parameters:
type - The firing event to be recorded.

removeActorFiringListener

public void removeActorFiringListener(ActorFiringListener listener)
Unregister an actor firing listener. If the specified listener has not been previously registered, then do nothing. Note that this method is basically the same as removeDebugListener in the class NamedObj.

Specified by:
removeActorFiringListener in interface FiringsRecordable
Parameters:
listener - The listener to remove from the list of listeners to which actor firing messages are sent.
See Also:
addActorFiringListener(ActorFiringListener)

removeDependency

public void removeDependency(IOPort input,
                             IOPort output)
                      throws IllegalActionException
Remove the dependency that the specified output port has, by default, on the specified input port. By default, each output port is assumed to have a dependency on all input ports. Subclasses can call this method in preinitialize() instead of implementing a custom CausalityInterface for the simple cases where output ports do not depend at all on certain input ports. There should be one such call for each input, output pair that does not have a dependency.

Parameters:
input - The input port.
output - The output port that does not depend on the input port.
Throws:
IllegalActionException - Thrown if causality interface cannot be computed.
See Also:
getCausalityInterface()

removeInitializable

public void removeInitializable(Initializable initializable)
Remove the specified object from the list of objects whose preinitialize(), initialize(), and wrapup() methods should be invoked upon invocation of the corresponding methods of this object. If the specified object is not on the list, do nothing.

Specified by:
removeInitializable in interface Initializable
Parameters:
initializable - The object whose methods should no longer be invoked.
See Also:
addInitializable(Initializable), CompositeActor.removePiggyback(Executable)

setContainer

public void setContainer(CompositeEntity container)
                  throws IllegalActionException,
                         NameDuplicationException
Override the base class to invalidate the schedule and resolved types of the director.

Overrides:
setContainer in class ComponentEntity
Parameters:
container - The proposed container.
Throws:
IllegalActionException - If the action would result in a recursive containment structure, or if this entity and container are not in the same workspace.
NameDuplicationException - If the container already has an entity with the name of this entity.
See Also:
ComponentEntity.getContainer()

stop

public void stop()
Request that execution of the current iteration stop as soon as possible. In this base class, we set a flag indicating that this request has been made (the protected variable _stopRequested). Most atomic actors have bounded fire() methods, so they can simply ignore this. Atomic actors with unbounded fire() methods should react by saving their state and returning from the fire() method at the next convenient point.

Specified by:
stop in interface Executable

stopFire

public void stopFire()
Request that execution of the current iteration complete. Most atomic actors have bounded fire() methods, so they can simply ignore this. Atomic actors with unbounded fire() methods should override this method to save their state and return from the fire() method at the next convenient point. In this base class, do nothing.

Specified by:
stopFire in interface Executable

terminate

public void terminate()
Terminate execution immediately. In this base class, call stop(). Derived classes may wish to do something more aggressive, such as terminating any threads they have started.

Specified by:
terminate in interface Executable

wrapup

public void wrapup()
            throws IllegalActionException
Do nothing except invoke the wrapup() methods of any objects that have been registered with addInitializable(). 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 Initializable
Throws:
IllegalActionException - Not thrown in this base class.

_actorFiring

protected final void _actorFiring(FiringEvent event)
Send an actor firing event to all actor firing listeners that have registered with this actor.

Parameters:
event - The event.

_actorFiring

protected final void _actorFiring(FiringEvent.FiringEventType type,
                                  int multiplicity)
Send an actor firing event type to all actor firing listeners that have registered with this actor.

Parameters:
type - The type.
multiplicity - The multiplicity of the firing, that is, the number of times the firing will occur or has occurred.

_addPort

protected void _addPort(Port port)
                 throws IllegalActionException,
                        NameDuplicationException
Override the base class to throw an exception if the added port is not an instance of IOPort. This method should not be used directly. Call the setContainer() method of the port instead. This method does not set the container of the port to point to this entity. It assumes that the port is in the same workspace as this entity, but does not check. The caller should check. Derived classes may override this method to further constrain to a subclass of IOPort. This method is not synchronized on the workspace, so the caller should be.

Overrides:
_addPort in class ComponentEntity
Parameters:
port - The port to add to this entity.
Throws:
IllegalActionException - If the port class is not acceptable to this entity, or the port has no name.
NameDuplicationException - If the port name coincides with a name already in the entity.