ptolemy.actor.sched
Class FixedPointDirector

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.actor.sched.FixedPointDirector
All Implemented Interfaces:
java.io.Serializable, java.lang.Cloneable, Executable, Initializable, SuperdenseTimeDirector, Changeable, Debuggable, DebugListener, Derivable, ModelErrorHandler, MoMLExportable, Moveable, Nameable
Direct Known Subclasses:
ContinuousDirector, SRDirector

public class FixedPointDirector
extends StaticSchedulingDirector
implements SuperdenseTimeDirector

A base class for directors that have fixed point semantics at each iteration. An iteration consists of repeated firings of the actors controlled by this director until a fixed point is reached. An iteration has converged if firing actors will not change signal status any more.

At the beginning of each iteration, the status of all inputs and outputs is unknown. Upon firing an actor, the status of its output signals may become known. Once the status of a signal becomes known, it cannot be changed back to unknown in the iteration. This monotonicity constraint ensures the existence and uniqueness of the fixed point. During an iteration, the prefire() and fire() methods of the controlled actors may be repeatedly invoked, but the postfire() method will be invoked exactly once after the fixed point has been found. The postfire() methods of the contained actors are invoked only in the postfire() method of this director, and they are invoked in arbitrary order.

If the prefire() method of an actor returns false, then this director assumes that all the outputs of the actor are absent. The actor has declined to fire.

Although this director does not require any specific ordering of actor firings, a scheduler is used to choose an efficient ordering.

By default, actors are strict, which means that all their input signals must be known before the actor can be fired. Here, what we mean by "fired" is that prefire() is invoked, and if it returns true, then fire() is invoked. Such actors will be fired only once in an iteration. A non-strict actor can be fired regardless of the status of its inputs, and may be fired repeatedly in an iteration if some of the inputs are unknown. Once an actor is fired with all its inputs known, it will not be fired again in the same iteration. A composite actor containing this director is a non-strict actor.

For an actor to be used under the control of this director, it must either be strict, or if it is non-strict, it must be monotonic. Montonicity implies two constraints on the actor. First, if prefire() ever returns true during an iteration, then it will return true on all subsequent invocations in the same iteration(). Second, if either prefire() or fire() call clear() on an output port, then no subsequent invocation in the same iteration can call put() on the port. If prefire() or fire() call put() on an output port with some token, then no subsequent invocation in the same iteration can call clear() or put() with a token with a different value. These constraints ensure determinacy.

If synchronizeToRealTime is set to true, then the postfire() method stalls until the real time elapsed since the model started matches the current time. This ensures that the director does not get ahead of real time. However, of course, this does not ensure that the director keeps up with real time. Note that this synchronization occurs after actors have been fired, but before they have been postfired.

This class is based on the original SRDirector, written by Paul Whitaker.

Since:
Ptolemy II 5.2
Version:
$Id: FixedPointDirector.java 59167 2010-09-21 17:08:02Z cxh $
Author:
Haiyang Zheng and Edward A. Lee
See Also:
Serialized Form
Accepted Rating:
Yellow (eal)
Proposed Rating:
Green (hyzheng)

Nested Class Summary
 
Nested classes/interfaces inherited from class ptolemy.kernel.util.NamedObj
NamedObj.ContainedObjectsIterator
 
Field Summary
private  java.util.Set _actorsAllowedToFire
          The set of actors that have returned true in their prefire() methods in the current iteration.
private  java.util.Set _actorsFinishedFiring
          The set of actors that have been fired in this iteration with all inputs known.
private  java.util.Set _actorsFired
          Actors that were fired in the most recent invocation of the fire() method.
private  java.util.Set _cachedAllInputsKnown
          The set of actors that have all inputs known in the given iteration.
private  boolean _cachedFunctionalProperty
          The cache of the functional property of the container of this director.
private  int _currentIteration
          The count of iterations executed.
private  int _currentNumberOfKnownReceivers
          The current number of receivers with known state.
private  long _functionalPropertyVersion
          Version number for the cached functional property.
protected  int _index
          The current index of the model.
private  int _lastNumberOfKnownReceivers
          The number of receivers with known state on the last phase of actor firings.
private  long _realStartTime
          The real time at which the model begins executing.
protected  java.util.List _receivers
          List of all receivers this director has created.
 Parameter iterations
          The number of times that postfire may be called before it returns false.
 Parameter synchronizeToRealTime
          Specify whether the execution should synchronize to the real time.
 
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
FixedPointDirector()
          Construct a director in the default workspace with an empty string as its name.
FixedPointDirector(CompositeEntity container, java.lang.String name)
          Construct a director in the given container with the given name.
FixedPointDirector(Workspace workspace)
          Construct a director in the given workspace with an empty name.
 
Method Summary
private  boolean _areAllInputsKnown(Actor actor)
          Return true if all the inputs of the specified actor are known.
private  void _fireActor(Actor actor)
          Fire an actor.
private  boolean _hasIterationConverged()
          Return true if this iteration has converged.
private  void _init()
          Initialize the director by creating the parameters and setting their values and types.
private  boolean _isReadyToFire(Actor actor)
          Return true if the specified actor is ready to fire.
private  boolean _postfireActor(Actor actor)
          Return the result of the postfire() method of the specified actor if it is allowed to be fired in the current iteration.
protected  void _receiverChanged()
          React to the change in receiver status by incrementing the count of known receivers.
protected  void _resetAllReceivers()
          Reset all receivers to unknown status and clear out variables used to track which actors fired in the last iteration.
private  void _sendAbsentToAllUnknownOutputsOf(Actor actor)
          Call the send(index, null) method of each output port with unknown status of the specified actor
protected  void _synchronizeToRealTime()
          Synchronize to real time, if appropriate.
 java.lang.Object clone(Workspace workspace)
          Clone the director into the specified workspace.
 void fire()
          Prefire and fire actors in the order given by the scheduler until the iteration converges.
 int getIndex()
          Return the current index of the director.
 boolean implementsStrictActorSemantics()
          Return true, indicating that this director assumes and exports the strict actor semantics, as described in this paper: A.
 void initialize()
          Initialize the director and all deeply contained actors by calling the super.initialize() method.
 boolean isFireFunctional()
          Return true if all the controlled actors' isFireFunctional() methods return true.
 boolean isStrict()
          Return false.
 Receiver newReceiver()
          Return a new FixedPointReceiver.
 boolean postfire()
          Call postfire() on all contained actors that were fired in the current iteration.
 boolean prefire()
          Return true if the director is ready to fire.
 void setIndex(int index)
          Set the superdense time index.
 java.lang.String[] suggestedModalModelDirectors()
          Return an array of suggested directors to be used with ModalModel.
 boolean transferInputs(IOPort port)
          Transfer data from the specified input port of the container to the ports it is connected to on the inside.
 boolean transferOutputs(IOPort port)
          Transfer data from the specified output port of the container to the ports it is connected to on the outside.
 
Methods inherited from class ptolemy.actor.sched.StaticSchedulingDirector
_setScheduler, addDebugListener, getScheduler, invalidateSchedule, isScheduleValid, removeDebugListener, setScheduler
 
Methods inherited from class ptolemy.actor.Director
_description, _fireContainerAt, _isEmbedded, _isTopLevel, _transferInputs, _transferOutputs, addInitializable, attributeChanged, createSchedule, defaultDependency, finish, fireAt, fireAt, fireAtCurrentTime, getCausalityInterface, getCurrentTime, getErrorTolerance, getGlobalTime, getModelNextIterationTime, getModelStartTime, getModelStopTime, getModelTime, getNextIterationTime, getStartTime, getStopTime, getTimeResolution, initialize, invalidateResolvedTypes, isStopRequested, iterate, preinitialize, preinitialize, removeInitializable, requestInitialization, setContainer, setCurrentTime, setModelTime, stop, stopFire, supportMultirateFiring, terminate, wrapup
 
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
 

Field Detail

iterations

public Parameter iterations
The number of times that postfire may be called before it returns false. The type must be int, and the value defaults to zero. 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.


synchronizeToRealTime

public Parameter synchronizeToRealTime
Specify whether the execution should synchronize to the real time. This parameter has type boolean and defaults to false. If set to true, then this director stalls in the prefire() method until the elapsed real real time matches the current time. If the period parameter has value 0.0 (the default), then changing this parameter to true has no effect. Note that in this base class, there is no period parameter and time is never advanced, so this will have no effect. It has effect in derived classes.


_index

protected int _index
The current index of the model.


_receivers

protected java.util.List _receivers
List of all receivers this director has created.


_actorsAllowedToFire

private java.util.Set _actorsAllowedToFire
The set of actors that have returned true in their prefire() methods in the current iteration. This is used only to check monotonicity constraints.


_actorsFinishedFiring

private java.util.Set _actorsFinishedFiring
The set of actors that have been fired in this iteration with all inputs known.


_actorsFired

private java.util.Set _actorsFired
Actors that were fired in the most recent invocation of the fire() method.


_cachedAllInputsKnown

private java.util.Set _cachedAllInputsKnown
The set of actors that have all inputs known in the given iteration.


_cachedFunctionalProperty

private boolean _cachedFunctionalProperty
The cache of the functional property of the container of this director.


_currentNumberOfKnownReceivers

private int _currentNumberOfKnownReceivers
The current number of receivers with known state.


_currentIteration

private int _currentIteration
The count of iterations executed.


_functionalPropertyVersion

private transient long _functionalPropertyVersion
Version number for the cached functional property.


_lastNumberOfKnownReceivers

private int _lastNumberOfKnownReceivers
The number of receivers with known state on the last phase of actor firings.


_realStartTime

private long _realStartTime
The real time at which the model begins executing.

Constructor Detail

FixedPointDirector

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

FixedPointDirector

public FixedPointDirector(Workspace workspace)
                   throws IllegalActionException,
                          NameDuplicationException
Construct a director in the given 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 for 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.

FixedPointDirector

public FixedPointDirector(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 - Container of the director.
name - Name of this director.
Throws:
IllegalActionException - If the director is not compatible with the specified container.
NameDuplicationException - If the name collides with an attribute in the container.
Method Detail

clone

public java.lang.Object clone(Workspace workspace)
                       throws java.lang.CloneNotSupportedException
Clone the director into the specified workspace. This calls the base class and then sets the attribute public members to refer to the attributes of the new director.

Overrides:
clone in class StaticSchedulingDirector
Parameters:
workspace - The workspace for the new director.
Returns:
A new director.
Throws:
java.lang.CloneNotSupportedException - If a derived class contains an attribute that cannot be cloned.
See Also:
NamedObj.exportMoML(Writer, int, String), NamedObj.setDeferringChangeRequests(boolean)

fire

public void fire()
          throws IllegalActionException
Prefire and fire actors in the order given by the scheduler until the iteration converges. An iteration converges when a pass through the schedule does not change the status of any receiver.

Specified by:
fire in interface Executable
Overrides:
fire in class StaticSchedulingDirector
Throws:
IllegalActionException - If an actor violates the monotonicity constraints, or the prefire() or fire() method of the actor throws it.

getIndex

public int getIndex()
Return the current index of the director. The current index is a portion of the superdense time. Superdense time means that time is a real value and an index, allowing multiple sequential steps to occur at a fixed (real) time.

Specified by:
getIndex in interface SuperdenseTimeDirector
Returns:
the superdense time index
See Also:
setIndex(int), SuperdenseTimeDirector

implementsStrictActorSemantics

public boolean implementsStrictActorSemantics()
Return true, indicating that this director assumes and exports the strict actor semantics, as described in this paper:

A. Goderis, C. Brooks, I. Altintas, E. A. Lee, and C. Goble, "Heterogeneous Composition of Models of Computation," EECS Department, University of California, Berkeley, Tech. Rep. UCB/EECS-2007-139, Nov. 2007. http://www.eecs.berkeley.edu/Pubs/TechRpts/2007/EECS-2007-139.html

In particular, a director that implements this interface guarantees that it will not invoke the postfire() method of an actor until all its inputs are known at the current tag. Moreover, it it will only do so in its own postfire() method, and in its prefire() and fire() methods, it does not change its own state. Thus, such a director can be used within a model of computation that has a fixed-point semantics, such as SRDirector and ContinuousDirector.

Overrides:
implementsStrictActorSemantics in class Director
Returns:
True.

initialize

public void initialize()
                throws IllegalActionException
Initialize the director and all deeply contained actors by calling the super.initialize() method. Reset all private variables.

Specified by:
initialize in interface Initializable
Overrides:
initialize in class Director
Throws:
IllegalActionException - If the superclass throws it.

isFireFunctional

public boolean isFireFunctional()
Return true if all the controlled actors' isFireFunctional() methods return true. Otherwise, return false.

Specified by:
isFireFunctional in interface Executable
Overrides:
isFireFunctional in class Director
Returns:
True if all controlled actors are functional. Return false if there is no container or no actors in the container.

isStrict

public boolean isStrict()
Return false. The transferInputs() method checks whether the inputs are known before calling hasToken(). Thus this director tolerates unknown inputs.

Specified by:
isStrict in interface Executable
Overrides:
isStrict in class Director
Returns:
False.

newReceiver

public Receiver newReceiver()
Return a new FixedPointReceiver. If a subclass overrides this method, the receiver it creates must be a subclass of FixedPointReceiver, and it must add the receiver to the _receivers list (a protected member of this class).

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

postfire

public boolean postfire()
                 throws IllegalActionException
Call postfire() on all contained actors that were fired in the current iteration. Return false if the model has finished executing, either by reaching the iteration limit, or if no actors in the model return true in postfire(), or if stop has been requested, or if no actors fired at all in the last iteration. This method is called only once for each iteration. Note that actors are postfired in arbitrary order.

Specified by:
postfire in interface Executable
Overrides:
postfire in class StaticSchedulingDirector
Returns:
True if the execution is not finished.
Throws:
IllegalActionException - If the iterations parameter does not have a valid token, or if there still some unknown inputs (which indicates a causality loop).

prefire

public boolean prefire()
                throws IllegalActionException
Return true if the director is ready to fire. If synchronizeToRealTime is true, then wait for real time elapse to match or exceed model time. The return whatever the base class returns.

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

setIndex

public void setIndex(int index)
              throws IllegalActionException
Set the superdense time index. This should only be called by an enclosing director.

Specified by:
setIndex in interface SuperdenseTimeDirector
Parameters:
index - The index of the superdense time object. Events that occur at the same time have different indicies.
Throws:
IllegalActionException - Not thrown in this base class.
See Also:
getIndex(), SuperdenseTimeDirector

suggestedModalModelDirectors

public java.lang.String[] suggestedModalModelDirectors()
Return an array of suggested directors to be used with 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()

transferInputs

public boolean transferInputs(IOPort port)
                       throws IllegalActionException
Transfer data from the specified input port of the container to the ports it is connected to on the inside. If there is no data on the specified input port, then set the ports on the inside to absent by calling sendInside(index, null). This method delegates the data transfer operation to the transferInputs method of the super class.

Overrides:
transferInputs in class Director
Parameters:
port - The port to transfer tokens from.
Returns:
True if at least one token is transferred.
Throws:
IllegalActionException - If the port is not an opaque input port.

transferOutputs

public boolean transferOutputs(IOPort port)
                        throws IllegalActionException
Transfer data from the specified output port of the container to the ports it is connected to on the outside. If there is no data on the specified output port, then set the ports on the outside to absent by calling send(index, null). This method delegates the data transfer operation to the transferOutputs method of the super class.

Overrides:
transferOutputs in class Director
Parameters:
port - The port to transfer tokens from.
Returns:
True if at least one token is transferred.
Throws:
IllegalActionException - If the port is not an opaque output port.

_receiverChanged

protected void _receiverChanged()
React to the change in receiver status by incrementing the count of known receivers.


_resetAllReceivers

protected void _resetAllReceivers()
Reset all receivers to unknown status and clear out variables used to track which actors fired in the last iteration.


_synchronizeToRealTime

protected void _synchronizeToRealTime()
                               throws IllegalActionException
Synchronize to real time, if appropriate.

Throws:
IllegalActionException - If the synchronizeToRealTime parameter is ill formed.

_areAllInputsKnown

private boolean _areAllInputsKnown(Actor actor)
                            throws IllegalActionException
Return true if all the inputs of the specified actor are known.

Throws:
IllegalActionException

_fireActor

private void _fireActor(Actor actor)
                 throws IllegalActionException
Fire an actor. Call its prefire() method, and if that returns true, call its fire() method.

Throws:
IllegalActionException - If the prefire() method returns false having previously returned true in the same iteration, or if the prefire() or fire() method of the actor throws it.

_hasIterationConverged

private boolean _hasIterationConverged()
Return true if this iteration has converged. The iteration has converged if both the number of known receivers has not changed since the previous invocation of this method.


_init

private void _init()
            throws IllegalActionException,
                   NameDuplicationException
Initialize the director by creating the parameters and setting their values and types.

Throws:
IllegalActionException
NameDuplicationException

_isReadyToFire

private boolean _isReadyToFire(Actor actor)
                        throws IllegalActionException
Return true if the specified actor is ready to fire. An actor is ready to fire if it has not previously finished firing in this iteration and either it is strict and all inputs are known or it is nonstrict. Note that this ignores whether the actor has previously returned false in postfire().

Throws:
IllegalActionException

_postfireActor

private boolean _postfireActor(Actor actor)
                        throws IllegalActionException
Return the result of the postfire() method of the specified actor if it is allowed to be fired in the current iteration. If this actor is not to be fired in the current iteration, return true without calling the postfire() method of the actor.

Throws:
IllegalActionException

_sendAbsentToAllUnknownOutputsOf

private void _sendAbsentToAllUnknownOutputsOf(Actor actor)
                                       throws IllegalActionException
Call the send(index, null) method of each output port with unknown status of the specified actor

Parameters:
actor - The actor.
Throws:
IllegalActionException