ptolemy.domains.dt.kernel
Class DTDirector

java.lang.Object
  extended by ptolemy.kernel.util.NamedObj
      extended by ptolemy.kernel.util.Attribute
          extended by ptolemy.actor.Director
              extended by ptolemy.actor.sched.StaticSchedulingDirector
                  extended by ptolemy.domains.sdf.kernel.SDFDirector
                      extended by ptolemy.domains.dt.kernel.DTDirector
All Implemented Interfaces:
java.io.Serializable, java.lang.Cloneable, Executable, Initializable, TimedDirector, PeriodicDirector, Changeable, Debuggable, DebugListener, Derivable, ModelErrorHandler, MoMLExportable, Moveable, Nameable

public class DTDirector
extends SDFDirector
implements TimedDirector

The Discrete Time (DT) domain director.

DT overview

The Discrete Time (DT) domain is a timed extension of the Synchronous Dataflow (SDF) domain. Like SDF, it has static scheduling of the dataflow graph model. Similarly, DT requires that the data rates on the ports of all actors be known beforehand and fixed. DT handles feedback systems in the same way that SDF does, but with additional constraints on initial tokens.

Local and Global Time

Because of the inherent concurrency occurring within SDF models, there are two notions of time in DT -- global time and local time. Global time increases steadily as execution progresses. Moreover, global time increases by fixed discrete amounts given by the period parameter. On the other hand, each receiver is associated with an independent local time. All the receivers have distinct local times as an iteration proceeds. The local time of a receiver during an iteration depends on the global time, period, firing count, port rates, and the schedule. These local times obey the following constraint:
Global Time <= Local Time <= (Global Time + period)
The exact way that local time increments during an iteration is described in detail in the DTReceiver documentation.

Period Parameter

The DT director has a period parameter which specifies the amount of time per iteration. For hierarchical DT, this period parameter only makes sense on the top-level. The user cannot explicitly set the period parameter for a DT subsystem inside another DT system. For heterogeneous hierarchies (e.g. DT inside DE or DT inside CT), the period parameter specifies the time interval between firings of the DT subsystem. The DT subsystem will not fire on times that are not integer multiples of the period parameter.

.

DT Features

The design of the DT domain is motivated by the following criteria:
  1. ) Uniform Token Flow: The time interval between tokens should be regular and unchanging. This conforms to the idea of having sampled systems with fixed rates. Although the tokens flowing in DT do not keep internal time stamps, each actor can query the DT director for its own local time. This local time is uniformly increasing by a constant fraction of the director's period. Local time is incremented every time the get() method is called to obtain a token.
  2. ) Causality: Tokens produced by an actor should only depend on tokens produced or consumed in the past. This makes sense because we don't expect an actor to produce a token before it can calculate the token's value. For example, if an actor needs three tokens A, B, and C to compute token D, then the time when tokens A, B, and C are consumed should be earlier than or equal to the time when token D is produced. Note that in DT, time does not get incremented due to computation.
  3. ) SDF-style semantics: Ideally, we want DT to be a timed-superset of SDF with compatible token flow and scheduling. However, we can only approximate this behavior. It is not possible to have uniform token flow, causality, and SDF-style semantics at the same time. Causality breaks for non-homogeneous actors in a feedback system when fully-compatible SDF-style semantics is adopted. To remedy this situation, every actor in DT that has non-homogeneous input ports should produce initial tokens at each of its output ports.

Design Notes

DT (Discrete Time) is a timed model of computation. In order to benefit from the internal time-keeping mechanism of DT, one should use actors aware of time. For example, one should use TimedPlotter or TimedScope instead of SequencePlotter or SequenceScope.

Top-level DT Directors have a period parameter that can be set by the user. Setting the period parameter of a non-top-level DT Director under hierarchical DT has no meaning; and hence will be ignored.

Domain-polymorphic actors that want to take advantage of the multi-rate timing capabilities of DT should call getCurrentTime(channel_number) for every get(channel_number). Moreover, the call sequence should be ordered as follows: getCurrentTime(channel_number) before get(channel_number). Known bugs:

 1.) Put more tests on this case: when events come in faster than the period
 of a DT composite actor (e.g clock feeding DT)
 2.) Put more tests on this case: when DT composite actor doesn't fire because
 there aren't enough tokens.
 3.) Domain-polymorphic actors that use getCurrentTime() should be modified
 to use DT's multirate timing capabilities.
 CurrentTime  - modified
 TimedPlotter - modified
 TimedScope   - modified
 SequentialClock - no input ports, gets global time only
 PoissonClock - under investigation
 Clock        - under investigation
 Expression   - under investigation
 4.) This director does not implement fireAt(). Instead, it inherits
 the implementation from SDF, which isn't quite correct. It does not always
 return the correct next time of firing. As a workaround, this class does not
 check the values returned by fireAt(). Thus, if it is embedded in a domain
 that does not respect the calls to fireAt(), then the user could get
 odd behavior without any error reported.
 

Since:
Ptolemy II 1.0
Version:
$Id: DTDirector.java 57040 2010-01-27 20:52:32Z cxh $
Author:
C. Fong
See Also:
DTReceiver, SDFDirector, SDFReceiver, SDFScheduler, Serialized Form
Accepted Rating:
Yellow (vogel)
Proposed Rating:
Yellow (chf)

Nested Class Summary
private static class DTDirector.DTActor
          Inner class to cache important variables for contained actors
 
Nested classes/interfaces inherited from class ptolemy.kernel.util.NamedObj
NamedObj.ContainedObjectsIterator
 
Field Summary
private  java.util.ArrayList _actorTable
           
private  java.util.Hashtable _allActorsTable
           
private  Time _formerTimeFired
           
private  Time _formerValidTimeFired
           
private  boolean _inputTokensAvailable
           
private  boolean _isFiringAllowed
           
private  java.util.ArrayList _receiverTable
           
private  boolean _shouldDoInternalTransferOutputs
           
private  java.util.Map _shouldTransferOutputs
           
private static double _TOLERANCE
           
 
Fields inherited from class ptolemy.domains.sdf.kernel.SDFDirector
_iterationCount, _periodicDirectorHelper, allowDisconnectedGraphs, allowRateChanges, constrainBufferSizes, iterations, period, synchronizeToRealTime, vectorizationFactor
 
Fields inherited from class ptolemy.actor.sched.StaticSchedulingDirector
_postfireReturns
 
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
DTDirector()
          Construct a director in the default workspace with an empty string as its name.
DTDirector(CompositeEntity container, java.lang.String name)
          Construct a director in the given container with the given name.
DTDirector(Workspace workspace)
          Construct a director in the workspace with an empty name.
 
Method Summary
private  void _buildActorTable()
          Create an actor table that caches all the actors directed by this director.
private  void _buildOutputPortTable()
          Build the internal cache of all the ports directed by this director
private  void _buildReceiverTable()
          Build the internal cache of all the receivers directed by this director.
private  void _checkValidTimeIntervals()
          Check if the current time is a valid time for execution.
private  void _debugViewActorTable()
          For debugging purposes.
private  void _debugViewReceiverTable()
          For debugging purposes.
private  Director _getOutsideDirector()
          Convenience method for getting the director of the container that holds this director.
protected  int _getRepetitions(Actor actor)
          Get the number of times an actor repeats in the schedule of an SDF graph.
private  void _init()
          Most of the constructor initialization is relegated to this method.
private  void _issuePseudoFire(Time currentTime)
          Request the outside non-DT director to fire this TypedCompositeActor at time intervals equal to when the output tokens should be produced.
private  void _makeTokensAvailable()
          Enable the hasToken() method in the output ports of the TypedCompositeActor directed by this director.
private  void _makeTokensUnavailable()
          Disable the hasToken() method in the output ports of the TypedCompositeActor directed by this director.
private  void _requestRefireAt(Time time)
          Convenience method for asking the executive director to fire this director's container again at a specific time in the future.
private  void _reset()
           
 Dependency delayDependency(double delay)
          Return a boolean dependency representing a model-time delay of the specified amount.
 void fire()
          Go through the schedule and iterate every actor with calls to prefire() , fire() , and postfire().
 Time getModelNextIterationTime()
          Return the time value of the next iteration.
 double getPeriod()
          Get the global time increment per iteration for this director.
 void initialize()
          Initialize all the actors associated with this director by calling super.initialize().
 void invalidateSchedule()
          Process the mutation that occurred.
 Receiver newReceiver()
          Return a new receiver consistent with the DT domain.
 boolean postfire()
          Request the outside director to fire this director's container again for the next period.
 boolean prefire()
          Check the input ports of the container composite actor (if there are any) to see whether they have enough tokens.
 void setActorLocalTime(Time newTime, Actor actor)
          Set the local time of an actor in the model under this director.
 void setModelTime(Time newTime)
          Set a new value to the current time of the model, where the new time may be earlier than the current time.
 void setScheduler(Scheduler scheduler)
          Override the base class to ensure that the scheduler is an SDFScheduler and that its constrainBufferSizes parameter is set to false.
 boolean transferInputs(IOPort port)
          Override the base class method to make sure that enough tokens are available to complete one iteration.
 boolean transferOutputs(IOPort port)
          This is called by the outside director to get tokens from an opaque composite actor.
 void wrapup()
          Reset this director to an uninitialized state.
 
Methods inherited from class ptolemy.domains.sdf.kernel.SDFDirector
attributeChanged, clone, createSchedule, fireAt, periodValue, preinitialize, suggestedModalModelDirectors, supportMultirateFiring
 
Methods inherited from class ptolemy.actor.sched.StaticSchedulingDirector
_setScheduler, addDebugListener, getScheduler, isScheduleValid, removeDebugListener
 
Methods inherited from class ptolemy.actor.Director
_description, _fireContainerAt, _isEmbedded, _isTopLevel, _transferInputs, _transferOutputs, addInitializable, defaultDependency, finish, fireAt, fireAtCurrentTime, getCausalityInterface, getCurrentTime, getErrorTolerance, getGlobalTime, getModelStartTime, getModelStopTime, getModelTime, getNextIterationTime, getStartTime, getStopTime, getTimeResolution, implementsStrictActorSemantics, initialize, invalidateResolvedTypes, isFireFunctional, isStopRequested, isStrict, iterate, preinitialize, removeInitializable, requestInitialization, setContainer, setCurrentTime, stop, stopFire, terminate
 
Methods inherited from class ptolemy.kernel.util.Attribute
_checkContainer, _getContainedObject, _propagateExistence, 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, 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, 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
 
Methods inherited from interface ptolemy.actor.TimedDirector
getModelTime, getTimeResolution
 
Methods inherited from interface ptolemy.actor.Executable
isFireFunctional, isStrict, iterate, 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

_actorTable

private java.util.ArrayList _actorTable

_receiverTable

private java.util.ArrayList _receiverTable

_allActorsTable

private java.util.Hashtable _allActorsTable

_formerValidTimeFired

private Time _formerValidTimeFired

_formerTimeFired

private Time _formerTimeFired

_isFiringAllowed

private boolean _isFiringAllowed

_shouldDoInternalTransferOutputs

private boolean _shouldDoInternalTransferOutputs

_inputTokensAvailable

private boolean _inputTokensAvailable

_shouldTransferOutputs

private java.util.Map _shouldTransferOutputs

_TOLERANCE

private static final double _TOLERANCE
See Also:
Constant Field Values
Constructor Detail

DTDirector

public DTDirector()
           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.

DTDirector

public DTDirector(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.

DTDirector

public DTDirector(CompositeEntity container,
                  java.lang.String name)
           throws IllegalActionException,
                  NameDuplicationException
Construct a director in the given container with the given name. If the container argument is null, 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 - Container of the director.
name - Name of this director.
Throws:
IllegalActionException - If the director is not compatible with the specified container.
NameDuplicationException - If the container is not a CompositeActor and the name collides with an entity in the container.
Method Detail

delayDependency

public Dependency delayDependency(double delay)
Return a boolean dependency representing a model-time delay of the specified amount.

Specified by:
delayDependency in interface TimedDirector
Parameters:
delay - A non-negative delay.
Returns:
A boolean dependency representing a delay.

fire

public void fire()
          throws IllegalActionException
Go through the schedule and iterate every actor with calls to prefire() , fire() , and postfire(). If this director is not in the top-level, get the outside director's current time; and check whether the returned time is an integer multiple of the period parameter. If it is not, then don't fire.

Specified by:
fire in interface Executable
Overrides:
fire in class StaticSchedulingDirector
Throws:
IllegalActionException - If an actor executed by this director returns false in its prefire().

getModelNextIterationTime

public Time getModelNextIterationTime()
Return the time value of the next iteration.

Overrides:
getModelNextIterationTime in class SDFDirector
Returns:
The time of the next iteration.
See Also:
Director.getModelTime()

getPeriod

public double getPeriod()
                 throws IllegalActionException
Get the global time increment per iteration for this director. This is a convenience method for getting the period parameter. For hierarchical DT (DT inside DT), extra calculation is done to compute the period as a fraction of the outside period.

Returns:
The value of the period parameter.
Throws:
IllegalActionException - If the period parameter is is not of type DoubleToken or IntToken.

initialize

public void initialize()
                throws IllegalActionException
Initialize all the actors associated with this director by calling super.initialize(). Determine which actors need to generate initial tokens for causality. All actors with nonhomogeneous input ports will need to generate initial tokens for all of their output ports. For example, if actor A has a nonhomogeneous input port and an output port with production rate 'm' then actor A needs to produce 'm' initial tokens on the output port.

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

invalidateSchedule

public void invalidateSchedule()
Process the mutation that occurred. Notify the parent class about the invalidated schedule. This method is called when an entity is instantiated under this director. This method is also called when a link is made between ports and/or relations. see also other mutation methods:

Overrides:
invalidateSchedule in class StaticSchedulingDirector
See Also:
NamedObj.attributeChanged(ptolemy.kernel.util.Attribute), NamedObj.attributeTypeChanged(ptolemy.kernel.util.Attribute)

newReceiver

public Receiver newReceiver()
Return a new receiver consistent with the DT domain.

Overrides:
newReceiver in class SDFDirector
Returns:
A new DTReceiver.

postfire

public boolean postfire()
                 throws IllegalActionException
Request the outside director to fire this director's container again for the next period.

Specified by:
postfire in interface Executable
Overrides:
postfire in class SDFDirector
Returns:
true if the Director wants to be fired again in the future.
Throws:
IllegalActionException - If the parent class throws it.

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. Always return true in order to allow firing or pseudo-firing. Pseudo-firing is needed when DT is interacting hierarchically with DE.

Specified by:
prefire in interface Executable
Overrides:
prefire in class SDFDirector
Returns:
True.
Throws:
IllegalActionException - If the parent class throws it.

setActorLocalTime

public void setActorLocalTime(Time newTime,
                              Actor actor)
Set the local time of an actor in the model under this director. This method is called by the DTReceiver class and doesn't need to be called by any other classes.

Parameters:
newTime - The new current simulation time.
actor - The actor to be assigned a new local time

setModelTime

public void setModelTime(Time newTime)
Set a new value to the current time of the model, where the new time may be earlier than the current time. Setting the time back to the past is allowed in DT.

Overrides:
setModelTime in class Director
Parameters:
newTime - The new current simulation time.
See Also:
Director.getModelTime()

setScheduler

public void setScheduler(Scheduler scheduler)
                  throws IllegalActionException,
                         NameDuplicationException
Override the base class to ensure that the scheduler is an SDFScheduler and that its constrainBufferSizes parameter is set to false.

Overrides:
setScheduler in class StaticSchedulingDirector
Parameters:
scheduler - The scheduler that this director will use.
Throws:
IllegalActionException - If the scheduler is not an instance of SDFScheduler.
NameDuplicationException - Not thrown in this base class, but derived classes may throw it if the scheduler is not compatible.
See Also:
StaticSchedulingDirector.getScheduler()

transferInputs

public boolean transferInputs(IOPort port)
                       throws IllegalActionException
Override the base class method to make sure that enough tokens are available to complete one iteration. This behavior is required to handle the case of non-homogeneous opaque composite actors. The port argument must be an opaque input port. If any channel of the input port has no data, then that channel is ignored.

Overrides:
transferInputs in class SDFDirector
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.

transferOutputs

public boolean transferOutputs(IOPort port)
                        throws IllegalActionException
This is called by the outside director to get tokens from an opaque composite actor. Return true if data is transferred from an output port of the container to the ports it is connected to on the outside. This method differs from the base class method in that this method will transfer all available tokens in the receivers, while the base class method will transfer at most one token. This behavior is required to handle the case of non-homogeneous opaque composite actors. The port argument must be an opaque output port. If any channel of the output port has no data, then that channel is ignored.

Overrides:
transferOutputs in class SDFDirector
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.

wrapup

public void wrapup()
            throws IllegalActionException
Reset this director to an uninitialized state.

Specified by:
wrapup in interface Initializable
Overrides:
wrapup in class Director
Throws:
IllegalActionException - If the parent class throws it

_getRepetitions

protected int _getRepetitions(Actor actor)
                       throws IllegalActionException
Get the number of times an actor repeats in the schedule of an SDF graph. If the actor does not exist, throw an exception.

Parameters:
actor - The actor whose firing count is needed.
Returns:
The number of times an actor repeats in the schedule.
Throws:
IllegalActionException - If actor does not exist.

_buildActorTable

private void _buildActorTable()
                       throws IllegalActionException
Create an actor table that caches all the actors directed by this director. This method is called once at initialize();

Throws:
IllegalActionException - If the scheduler is null

_buildReceiverTable

private void _buildReceiverTable()
                          throws IllegalActionException
Build the internal cache of all the receivers directed by this director.

Throws:
IllegalActionException - If methods called throw it.

_buildOutputPortTable

private void _buildOutputPortTable()
                            throws IllegalActionException
Build the internal cache of all the ports directed by this director

Throws:
IllegalActionException - If methods called throw it.

_checkValidTimeIntervals

private final void _checkValidTimeIntervals()
                                     throws IllegalActionException
Check if the current time is a valid time for execution. If the current time is not a integer multiple of the DT period, firing must not occur.

Throws:
IllegalActionException - If methods called throw it.

_debugViewActorTable

private void _debugViewActorTable()
                           throws IllegalActionException
For debugging purposes. Display the list of contained actors and other pertinent information about them.

Throws:
IllegalActionException - If there is a problem in obtaining the number of initial token for delay actors

_debugViewReceiverTable

private void _debugViewReceiverTable()
For debugging purposes. Display the list of contained receivers and other pertinent information about them.


_getOutsideDirector

private Director _getOutsideDirector()
Convenience method for getting the director of the container that holds this director. If this director is inside a toplevel container, then the returned value is null.

Returns:
The executive director

_issuePseudoFire

private void _issuePseudoFire(Time currentTime)
                       throws IllegalActionException
Request the outside non-DT director to fire this TypedCompositeActor at time intervals equal to when the output tokens should be produced. No actual firing occurs of the inside actors will occur; hence the name 'pseudo-firing'

Throws:
IllegalActionException

_makeTokensAvailable

private void _makeTokensAvailable()
                           throws IllegalActionException
Enable the hasToken() method in the output ports of the TypedCompositeActor directed by this director. This is used in composing DT with DE and CT.

Throws:
IllegalActionException

_makeTokensUnavailable

private void _makeTokensUnavailable()
                             throws IllegalActionException
Disable the hasToken() method in the output ports of the TypedCompositeActor directed by this director. This is used in composing DT with DE and CT.

Throws:
IllegalActionException

_requestRefireAt

private void _requestRefireAt(Time time)
                       throws IllegalActionException
Convenience method for asking the executive director to fire this director's container again at a specific time in the future.

Parameters:
time - The time when this director's container should be fired
Throws:
IllegalActionException - If getting the container or executive director fails

_init

private void _init()
Most of the constructor initialization is relegated to this method. Initialization process includes : - create a new actor table to cache all actors contained - create a new receiver table to cache all receivers contained - set default number of iterations - set period value


_reset

private void _reset()