ptolemy.domains.ddf.kernel
Class DDFDirector

java.lang.Object
  extended by ptolemy.kernel.util.NamedObj
      extended by ptolemy.kernel.util.Attribute
          extended by ptolemy.actor.Director
              extended by ptolemy.domains.ddf.kernel.DDFDirector
All Implemented Interfaces:
java.io.Serializable, java.lang.Cloneable, Executable, Initializable, Changeable, Debuggable, DebugListener, Derivable, ModelErrorHandler, MoMLExportable, Moveable, Nameable

public class DDFDirector
extends Director

The dynamic dataflow (DDF) domain is a superset of the synchronous dataflow(SDF) and Boolean dataflow(BDF) domains. In the SDF domain, an actor consumes and produces a fixed number of tokens per firing. This static information makes possible compile-time scheduling. In the DDF domain, there are few constraints on the production and consumption behavior of actors, and the schedulers make no attempt to construct a compile-time schedule. Instead, each actor has a set of firing rules (patterns) and can be fired if one of them is satisfied, i.e., one particular firing pattern forms a prefix of sequences of unconsumed tokens at input ports. The canonical actors in the DDF domain include Select and Switch, which consume or produce tokens on different channels based on the token received from the control port. You can also use the two-channel versions BooleanSelect and BooleanSwitch.

The dynamic scheduler implemented in this director fires all enabled and non-deferrable actors once in a basic iteration. A deferrable actor is one that will not help one of the downstream actors become enabled because that downstream actor either already has enough tokens on the channel connecting those two actors or is waiting for tokens on another channel. If no actor fires so far, which means there is no enabled and non-deferrable actor, then among all enabled and deferrable actors, this director fires those which have the smallest maximum number of tokens on their output channels which satisfy the demand of destination actors. If still no actor fires, then there is no enabled actor. A user can treat several such basic iterations as a single iteration by adding a parameter with name requiredFiringsPerIteration to an actor (which is often a sink actor or an actor directly connected to output port of the composite actor) and specifying the number of times this actor must be fired in a single iteration. If the value of the parameter runUntilDeadlockInOneIteration is a BooleanToken with value true, one single iteration consists of repeating the basic iteration until deadlock is reached (thus overriding the previous definition of one iteration), which is the status of the model where all active actors under the control of this director are unable to fire because their firing rules are not satisfied. However, they may be able to fire again during next iteration when tokens are transferred in from an outside domain. Note runUntilDeadlockInOneIteration can be set to true only when this director is not on the top level.

The algorithm implementing one basic iteration goes like this:

 E = set of enabled actors
 D = set of deferrable enabled actors
 
One basic(default) iteration consists of:
 if (E\D != empty set) {
 fire (E\D)
 } else if (D != empty set) {
 fire minimax(D)
 } else {
 declare deadlock
 }
 
The function "minimax(D)" returns a subset of D with the smallest maximum number of tokens on their output channels which satisfy the demand of destination actors.

Note that any SDF model can be run with a DDF Director. However, the notion of iteration is different. One could try to imitate the SDF iteration in the DDF domain by controlling the number of firings in one iteration for some actors, such as requiring a plotter to plot a fixed number of points in each iteration.

In the DDF domain, the firing rule of any actor is specified by the token consumption rates of its input ports. A general DDF actor could change the consumption rates of its input ports after each firing of this actor. For multiports, an array token could be used to specify different rates for different channels connected to the same multiport. Note that in SDF, all channels connected to the same multiport have the same rate.

Based on DDFSimpleSched in Ptolemy Classic, by Edward Lee. See E. A. Lee et al., "The Almagest," documentation for Ptolemy Classic, Vol. 1, Chapter 7, 1997.

Since:
Ptolemy II 4.1
Version:
$Id: DDFDirector.java 57040 2010-01-27 20:52:32Z cxh $
Author:
Gang Zhou
See Also:
Serialized Form
Accepted Rating:
Yellow (cxh)
Proposed Rating:
Yellow (zgang)

Nested Class Summary
private static class DDFDirector.ActorInfo
          This private class is data structure for recording an actor's information during the execution.
 
Nested classes/interfaces inherited from class ptolemy.kernel.util.NamedObj
NamedObj.ContainedObjectsIterator
 
Field Summary
private  java.util.HashMap _actorsInfo
          A HashMap containing actors' information.
private  java.util.LinkedList _actorsToCheckNumberOfFirings
          A list to store those actors for which positive requiredFiringsPerIteration has been defined.
private  java.util.Set _disabledActors
          The set of actors that have returned false in their postfire() methods and therefore become disabled.
private  boolean _firedOne
          A flag indicating whether at least one actor has been fired so far.
private  boolean _isTypeResolutionDisabled
          A flag indicating whether type resolution is disabled.
private  int _iterationCount
          The number of iterations.
private  boolean _runUntilDeadlock
          A boolean initialized with value in the parameter runUntilDeadlockInOneIteration.
 Parameter iterations
          A Parameter representing the number of times that postfire() may be called before it returns false.
 Parameter maximumReceiverCapacity
          A Parameter representing the maximum capacity of each receiver controlled by this director.
 Parameter runUntilDeadlockInOneIteration
          A parameter indicating whether one iteration consists of repeated basic iterations until deadlock.
 
Fields inherited from class ptolemy.actor.Director
_actorsFinishedExecution, _currentTime, _finishRequested, _initializables, _stopRequested, timeResolution
 
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
DDFDirector()
          Construct a director in the default workspace with an empty string as its name.
DDFDirector(CompositeEntity container, java.lang.String name)
          Construct a director in the given container with the given name.
DDFDirector(Workspace workspace)
          Construct a director in the workspace with an empty name.
 
Method Summary
protected  boolean _fireActor(Actor actor)
          Iterate the actor once.
protected  ActorEnablingStatus _getActorStatus(Actor actor)
          Determine actor enabling status.
private  int[] _getTokenConsumptionRate(IOPort port)
          Get token consumption rate for the given port.
private  int _getTokenConsumptionRate(Receiver receiver)
          Get token consumption rate for the given receiver.
private  int[] _getTokenProductionRate(IOPort port)
          Get token production rate for the given port.
private  void _init()
          Initialize the object.
protected  boolean _isDeferrable(Actor actor)
          Check each remote receiver to see whether the number of tokens in the receiver is greater than or equal to the tokenConsumptionRate of the containing port.
protected  boolean _isEnabled(Actor actor)
          Check to see whether the actor is enabled.
protected  void _updateConnectedActorsStatus(Actor actor)
          Update the enabling status of the given actor and all actors connected to this actor.
 void attributeChanged(Attribute attribute)
          If the attribute being changed is runUntilDeadlockInOneIteration and it is set to be true, then verify this director is not at the top level.
 void disableTypeResolution(boolean flag)
          Set the flag indicating whether type resolution is disabled or not.
 void fire()
          Execute the model for one iteration.
 void initialize()
          Initialize the model controlled by this director.
 void initialize(Actor actor)
          Initialize the given actor.
 void invalidateResolvedTypes()
          Call base class method to invalidate resolved types if the flag to disable type resolution is set to false.
 void merge(DDFDirector insideDirector)
          Merge an opaque composite actor controlled by an inside DDFDirector with the outside domain controlled by this director.
 Receiver newReceiver()
          Return a new QueueReceiver.
 boolean postfire()
          Increment the number of iterations.
 boolean prefire()
          Check the input ports of the container composite actor (if there are any) to see whether they have enough tokens, and return true if they do.
 java.lang.String[] suggestedModalModelDirectors()
          Return an array of suggested directors to use with an embedded ModalModel.
 boolean supportMultirateFiring()
          Return true to indicate that a ModalModel under control of this director supports multirate firing.
 boolean transferInputs(IOPort port)
          Override the base class method to transfer enough tokens to complete an internal iteration.
 boolean transferOutputs(IOPort port)
          Override the base class method to transfer enough tokens to fulfill the output production rate.
 
Methods inherited from class ptolemy.actor.Director
_description, _fireContainerAt, _isEmbedded, _isTopLevel, _transferInputs, _transferOutputs, addInitializable, createSchedule, defaultDependency, finish, fireAt, fireAt, fireAtCurrentTime, getCausalityInterface, getCurrentTime, getErrorTolerance, getGlobalTime, getModelNextIterationTime, getModelStartTime, getModelStopTime, getModelTime, getNextIterationTime, getStartTime, getStopTime, getTimeResolution, implementsStrictActorSemantics, invalidateSchedule, isFireFunctional, isStopRequested, isStrict, iterate, preinitialize, preinitialize, removeInitializable, requestInitialization, setContainer, setCurrentTime, setModelTime, stop, stopFire, terminate, wrapup
 
Methods inherited from class ptolemy.kernel.util.Attribute
_checkContainer, _getContainedObject, _propagateExistence, clone, getContainer, moveDown, moveToFirst, moveToIndex, moveToLast, moveUp, setName, updateContent
 
Methods inherited from class ptolemy.kernel.util.NamedObj
_addAttribute, _adjustOverride, _attachText, _cloneFixAttributeFields, _debug, _debug, _debug, _debug, _debug, _exportMoMLContents, _getIndentPrefix, _isMoMLSuppressed, _markContentsDerived, _propagateValue, _recordDecoratedAttributes, _removeAttribute, _splitName, _stripNumericSuffix, _validateSettables, addChangeListener, addDebugListener, attributeList, attributeList, attributeTypeChanged, clone, containedObjectsIterator, deepContains, depthInHierarchy, description, description, event, executeChangeRequests, exportMoML, exportMoML, exportMoML, exportMoML, exportMoML, exportMoMLPlain, getAttribute, getAttribute, getAttributes, getChangeListeners, getClassName, getDecoratorAttribute, getDecoratorAttributes, getDerivedLevel, getDerivedList, getDisplayName, getElementName, getFullName, getModelErrorHandler, getName, getName, getPrototypeList, getSource, handleModelError, isDeferringChangeRequests, isOverridden, isPersistent, lazyContainedObjectsIterator, message, propagateExistence, propagateValue, propagateValues, removeChangeListener, removeDebugListener, requestChange, setClassName, setDeferringChangeRequests, setDerivedLevel, setDisplayName, setModelErrorHandler, setPersistent, setSource, sortContainedObjects, toplevel, toString, uniqueName, validateSettables, workspace
 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

iterations

public Parameter iterations
A Parameter representing the number of times that postfire() may be called before it returns false. If the value is less than or equal to zero, then the execution will never return false in postfire(), and thus the execution can continue forever or until the model is deadlocked. The default value is an IntToken with the value zero.


maximumReceiverCapacity

public Parameter maximumReceiverCapacity
A Parameter representing the maximum capacity of each receiver controlled by this director. This is an integer that defaults to 0, which means the queue in each receiver is unbounded. To specify bounded queues, set this to a positive integer.


runUntilDeadlockInOneIteration

public Parameter runUntilDeadlockInOneIteration
A parameter indicating whether one iteration consists of repeated basic iterations until deadlock. If this parameter is true, the model will be executed until deadlock in one iteration. The default value is a BooleanToken with the value false. It cannot be set to true if this director is at the top level.


_isTypeResolutionDisabled

private boolean _isTypeResolutionDisabled
A flag indicating whether type resolution is disabled.


_firedOne

private boolean _firedOne
A flag indicating whether at least one actor has been fired so far.


_iterationCount

private int _iterationCount
The number of iterations.


_runUntilDeadlock

private boolean _runUntilDeadlock
A boolean initialized with value in the parameter runUntilDeadlockInOneIteration.


_actorsInfo

private java.util.HashMap _actorsInfo
A HashMap containing actors' information. Each actor is mapped to an ActorInfo object.


_actorsToCheckNumberOfFirings

private java.util.LinkedList _actorsToCheckNumberOfFirings
A list to store those actors for which positive requiredFiringsPerIteration has been defined.


_disabledActors

private java.util.Set _disabledActors
The set of actors that have returned false in their postfire() methods and therefore become disabled.

Constructor Detail

DDFDirector

public DDFDirector()
            throws IllegalActionException,
                   NameDuplicationException
Construct a director in the default workspace with an empty string as its name. The director is added to the list of objects in the workspace. Increment the version number of the workspace.

Throws:
IllegalActionException - If the name has a period in it, or the director is not compatible with the specified container.
NameDuplicationException - If the container already contains an entity with the specified name.

DDFDirector

public DDFDirector(Workspace workspace)
            throws IllegalActionException,
                   NameDuplicationException
Construct a director in the workspace with an empty name. The director is added to the list of objects in the workspace. Increment the version number of the workspace.

Parameters:
workspace - The workspace of this object.
Throws:
IllegalActionException - If the name has a period in it, or the director is not compatible with the specified container.
NameDuplicationException - If the container already contains an entity with the specified name.

DDFDirector

public DDFDirector(CompositeEntity container,
                   java.lang.String name)
            throws IllegalActionException,
                   NameDuplicationException
Construct a director in the given container with the given name. The container argument must not be null, or a NullPointerException will be thrown. If the name argument is null, then the name is set to the empty string. Increment the version number of the workspace.

Parameters:
container - The container of this director.
name - Name of this director.
Throws:
IllegalActionException - Not thrown in this base class. May be thrown in the derived classes if the director is not compatible with the specified container.
NameDuplicationException - If the name collides with an attribute that already exists in the given container.
Method Detail

attributeChanged

public void attributeChanged(Attribute attribute)
                      throws IllegalActionException
If the attribute being changed is runUntilDeadlockInOneIteration and it is set to be true, then verify this director is not at the top level.

Overrides:
attributeChanged in class Director
Parameters:
attribute - The changed parameter.
Throws:
IllegalActionException - If this director is at top level and runUntilDeadlockInOneIteration is set to be true, or getToken() throws IllegalActionException.

disableTypeResolution

public void disableTypeResolution(boolean flag)
Set the flag indicating whether type resolution is disabled or not. This method is used in an ActorRecursion actor. When a composite actor is cloned into an ActorRecursion actor, type compatibility has already been checked, therefore there is no need to invalidate resolved types.

Parameters:
flag - The flag to be set.

fire

public void fire()
          throws IllegalActionException
Execute the model for one iteration. First scan all active actors to put all enabled and non-deferrable actors in a list and find the minimax actors. Fire all actors once in the list. If no actor has been fired, fire the minimax actors. If still no actor has been fired, a deadlock has been detected. This concludes one basic iteration, and by default also one iteration of this director. However, if some actor has a parameter named requiredFiringsPerIteration defined, continue to execute basic iterations until the actor has been fired at least the number of times given in that parameter. If more than one actor has such a parameter, then the iteration will continue until all are satisfied. If the parameter runUntilDeadlockInOneIteration has value true, one iteration consists of repeatedly executing basic iterations until the actors under control of this director have reached a deadlock.

Specified by:
fire in interface Executable
Overrides:
fire in class Director
Throws:
IllegalActionException - If any actor executed by this actor returns false in prefire().

initialize

public void initialize()
                throws IllegalActionException
Initialize the model controlled by this director. Initialize the actors associated with this director. Set all the state variables to the their initial values. The order in which the actors are initialized is arbitrary. If actors connected directly to output ports produce initial tokens, then send those tokens to the outside of the composite actor.

Specified by:
initialize in interface Initializable
Overrides:
initialize in class Director
Throws:
IllegalActionException - If the initialize() method of one of the associated actors throws it.

initialize

public void initialize(Actor actor)
                throws IllegalActionException
Initialize the given actor. This method is called by the initialize() method of the director, and by the manager whenever an actor is added to the executing model as a mutation. It first calls the actor's initialize() method which may emit initial tokens. Then it updates the enabling status of the actor and all actors connected to this actor. Finally it records the value given by requiredFiringsPerIteration if the actor has such a parameter. Any change to this parameter during execution will be ignored.

Overrides:
initialize in class Director
Parameters:
actor - The actor to be initialized.
Throws:
IllegalActionException - If the requiredFiringsPerIteration parameter does not contain an IntToken.

invalidateResolvedTypes

public void invalidateResolvedTypes()
Call base class method to invalidate resolved types if the flag to disable type resolution is set to false. If the flag is true, override the base class method to skip invalidating resolved types. This method is used for an ActorRecursion actor. When a composite actor is cloned into an ActorRecursion actor, type compatibility has already been checked, therefore there is no need to invalidate resolved types.

Overrides:
invalidateResolvedTypes in class Director

merge

public void merge(DDFDirector insideDirector)
Merge an opaque composite actor controlled by an inside DDFDirector with the outside domain controlled by this director. It aggregates the status variables for the inside actors with the status variables for the outside actors. This method can be used in ActorRecursion which clones a composite actor into itself and then merges with the outside DDF domain.

Parameters:
insideDirector - The inside DDFDirector to be merged.

newReceiver

public Receiver newReceiver()
Return a new QueueReceiver. Set the capacity of the FIFO queue in the receiver to the value specified by the director parameter maximumReceiverCapacity if that value is greater than 0.

Overrides:
newReceiver in class Director
Returns:
A new QueueReceiver.

postfire

public boolean postfire()
                 throws IllegalActionException
Increment the number of iterations. Return false if the system has finished executing by reaching the iteration limit or the system is deadlocked.

Specified by:
postfire in interface Executable
Overrides:
postfire in class Director
Returns:
True if the Director wants to be fired again in the future.
Throws:
IllegalActionException - If the iterations parameter does not contain a legal value.

prefire

public boolean prefire()
                throws IllegalActionException
Check the input ports of the container composite actor (if there are any) to see whether they have enough tokens, and return true if they do. If there are no input ports, then also return true. Otherwise, return false. If an input port does not have a parameter tokenConsumptionRate, then skip checking on that port because it will transfer all tokens (if there are any) to the inside. Note the difference from SDF domain where the default rate is 1. Finally, initialize numberOfFirings to zero for those actors for which positive requiredFiringsPerIteration has been defined.

Specified by:
prefire in interface Executable
Overrides:
prefire in class Director
Returns:
true If all of the input ports of the container of this director have enough tokens.
Throws:
IllegalActionException - If any called method throws IllegalActionException.

suggestedModalModelDirectors

public java.lang.String[] suggestedModalModelDirectors()
Return an array of suggested directors to use with an embedded ModalModel. Each director is specified by its full class name. The first director in the array will be the default director used by a modal model.

Overrides:
suggestedModalModelDirectors in class Director
Returns:
An array of suggested directors to be used with ModalModel.
See Also:
Director.suggestedModalModelDirectors()

supportMultirateFiring

public boolean supportMultirateFiring()
Return true to indicate that a ModalModel under control of this director supports multirate firing.

Overrides:
supportMultirateFiring in class Director
Returns:
True indicating a ModalModel under control of this director supports multirate firing.

transferInputs

public boolean transferInputs(IOPort port)
                       throws IllegalActionException
Override the base class method to transfer enough tokens to complete an internal iteration. If the token consumption rate is defined for the port and there are not enough tokens, throw an exception. If the token consumption rate is not defined for the port, transfer all tokens (if there are any) contained by the port. Finally it updates enabling status for all inside opaque actors that receive data from this port.

Overrides:
transferInputs in class Director
Parameters:
port - The port to transfer tokens from.
Returns:
True if data are transferred.
Throws:
IllegalActionException - If the port is not an opaque input port, or if there are not enough input tokens available.

transferOutputs

public boolean transferOutputs(IOPort port)
                        throws IllegalActionException
Override the base class method to transfer enough tokens to fulfill the output production rate. If the token production rate is defined for the port and there are not enough tokens, throw an exception. If the token production rate is not defined for the port, transfer all tokens (if there are any) contained on the inside by the port.

Overrides:
transferOutputs in class Director
Parameters:
port - The port to transfer tokens from.
Returns:
True if data are transferred.
Throws:
IllegalActionException - If the port is not an opaque output port, or if there are not enough output tokens available.

_fireActor

protected boolean _fireActor(Actor actor)
                      throws IllegalActionException
Iterate the actor once. Increment the firing number for it. Update the enabling status for each connected actor as well as itself.

Parameters:
actor - The actor to be fired.
Returns:
true if the actor is actually fired, false if not.
Throws:
IllegalActionException - If any called method throws IllegalActionException or the actor is not ready.

_getActorStatus

protected ActorEnablingStatus _getActorStatus(Actor actor)
                                       throws IllegalActionException
Determine actor enabling status. It must be one of the three: NOT_ENABLED, ENABLED_DEFERRABLE, ENABLED_NOT_DEFERRABLE.

Parameters:
actor - The actor to be checked.
Returns:
An int indicating actor enabling status.
Throws:
IllegalActionException - If any called method throws IllegalActionException.

_isDeferrable

protected boolean _isDeferrable(Actor actor)
                         throws IllegalActionException
Check each remote receiver to see whether the number of tokens in the receiver is greater than or equal to the tokenConsumptionRate of the containing port. The actor is deferrable if the above test is true for any receiver. At the same time, find the maximum number of tokens in all receivers, which is used to find minimax actors later on.

Parameters:
actor - The actor to be checked.
Returns:
true if the actor is deferrable, false if not.
Throws:
IllegalActionException - If any called method throws IllegalActionException.

_isEnabled

protected boolean _isEnabled(Actor actor)
                      throws IllegalActionException
Check to see whether the actor is enabled. It is enabled if the tokenConsumptionRate on each input port is satisfied by all receivers contained by this port.

Parameters:
actor - The actor to be checked.
Returns:
true if the actor is enabled, false if not.
Throws:
IllegalActionException - If any called method throws IllegalActionException.

_updateConnectedActorsStatus

protected void _updateConnectedActorsStatus(Actor actor)
                                     throws IllegalActionException
Update the enabling status of the given actor and all actors connected to this actor. This method gets called after the given actor gets initialized or fired.

Parameters:
actor - The actor to te checked.
Throws:
IllegalActionException - If _getActorStatus(Actor) throws IllegalActionException.

_getTokenConsumptionRate

private int[] _getTokenConsumptionRate(IOPort port)
                                throws IllegalActionException
Get token consumption rate for the given port. If the port is an input port of an actor controlled by this director, the default rate is 1 unless explicitly specified by a tokenConsumptionRate parameter. If the port is an input port of the container of this director, the default value is -1 unless explicitly specified by a tokenConsumptionRate parameter. The value -1 means consuming all tokens (if there are any) contained by the port.

Parameters:
port - The port to get token consumption rate.
Returns:
An int array of token consumption rates.
Throws:
IllegalActionException - If parameter throws it or the length of tokenConsumptionRate array is less than port width.

_getTokenConsumptionRate

private int _getTokenConsumptionRate(Receiver receiver)
                              throws IllegalActionException
Get token consumption rate for the given receiver. The port containing the receiver can be an input port of an actor controlled by this director or an output port of the container of this director. In the latter case, it actually returns the production rate.

Parameters:
receiver - The receiver to get token consumption rate.
Returns:
The token consumption rate of the given receiver.
Throws:
IllegalActionException - If any called method throws IllegalActionException.

_getTokenProductionRate

private int[] _getTokenProductionRate(IOPort port)
                               throws IllegalActionException
Get token production rate for the given port. The port argument should always be an output port of the container of this director. The convention is that if a parameter named tokenproductionRate is defined, return the value in that parameter. Otherwise, return an array of int each with value -1 which means the director should transfer all tokens contained on the inside by the port to the outside. Note the difference from SDF domain where the default rate is 1.

Parameters:
port - The port to get token production rate.
Returns:
An int array of token production rate.
Throws:
IllegalActionException - If parameter throws it or the length of tokenProductionRate array is less than port inside width or the port in the argument is not an output port of the container of this director.

_init

private void _init()
            throws IllegalActionException,
                   NameDuplicationException
Initialize the object. In this case, we give the DDFDirector an iterations parameter with default value zero, a maximumReceiverCapacity parameter with default value zero and a runUntilDeadlockInOneIteration parameter with default value false.

Throws:
IllegalActionException
NameDuplicationException