ptolemy.codegen.actor
Class Director

java.lang.Object
  extended by ptolemy.kernel.util.NamedObj
      extended by ptolemy.codegen.kernel.CodeGeneratorHelper
          extended by ptolemy.codegen.actor.Director
All Implemented Interfaces:
java.io.Serializable, java.lang.Cloneable, ActorCodeGenerator, ComponentCodeGenerator, Changeable, Debuggable, DebugListener, Derivable, ModelErrorHandler, MoMLExportable, Moveable, Nameable
Direct Known Subclasses:
CaseDirector, CaseDirector, Director, FSMDirector, FSMDirector, FSMDirector, PNDirector, PNDirector, SDFDirector, StaticSchedulingDirector, StaticSchedulingDirector

public class Director
extends CodeGeneratorHelper

Code generator helper associated with the ptolemy.actor.Director class. This class is also associated with a code generator. FIXME: need documentation on how subclasses should extend this class.

Since:
Ptolemy II 8.0
Version:
$Id: Director.java 57046 2010-01-27 23:35:53Z cxh $
Author:
Ye Zhou, Gang Zhou
See Also:
CodeGenerator, Serialized Form
Accepted Rating:
Yellow (zhouye)
Proposed Rating:
Yellow (zhouye)

Nested Class Summary
 
Nested classes/interfaces inherited from class ptolemy.codegen.kernel.CodeGeneratorHelper
CodeGeneratorHelper.Channel, CodeGeneratorHelper.VariableScope
 
Nested classes/interfaces inherited from class ptolemy.kernel.util.NamedObj
NamedObj.ContainedObjectsIterator
 
Field Summary
protected  Director _director
          The associated director.
protected static java.lang.String _eol
          End of line character.
protected static java.lang.String _INDENT1
          Indent string for indent level 1.
protected static java.lang.String _INDENT2
          Indent string for indent level 2.
protected static java.lang.String _INDENT3
          Indent string for indent level 3.
protected static java.lang.String _INDENT4
          Indent string for indent level 4.
 
Fields inherited from class ptolemy.codegen.kernel.CodeGeneratorHelper
_codeGenerator, _codeStream, _parseTreeCodeGenerator, _portConversions, _referencedParameters
 
Fields inherited from class ptolemy.kernel.util.NamedObj
_changeListeners, _changeLock, _changeRequests, _debugging, _debugListeners, _elementName, _isPersistent, _verbose, _workspace, ATTRIBUTES, CLASSNAME, COMPLETE, CONTENTS, DEEP, FULLNAME, LINKS
 
Constructor Summary
Director(Director director)
          Construct the code generator helper associated with the given director.
 
Method Summary
protected  int _ceilToPowerOfTwo(int value)
          Return the minimum number of power of two that is greater than or equal to the given integer.
protected static java.lang.String _getIndentPrefix(int level)
          Return a number of spaces that is proportional to the argument.
protected  void _updateConnectedPortsOffset(IOPort port, java.lang.StringBuffer code, int rate)
          Update the offsets of the buffers associated with the ports connected with the given port in its downstream.
protected  void _updatePortOffset(IOPort port, java.lang.StringBuffer code, int rate)
          Update the read offsets of the buffer associated with the given port.
 java.lang.String createOffsetVariablesIfNeeded()
          Generate code for declaring read and write offset variables if needed.
 java.lang.String generateCodeForGet(IOPort port, int channel)
          Generate the code for getting data from the specified port channel.
 java.lang.String generateCodeForSend(IOPort port, int channel, java.lang.String dataToken)
          Generate the code for sending data to the specified port channel.
 java.lang.String generateFireCode()
          Generate the code for the firing of actors.
 java.lang.String generateFireFunctionCode()
          Generate The fire function code.
 java.lang.String generateInitializeCode()
          Generate the initialize code for this director.
 java.lang.String generateMainLoop()
          Generate a main loop for an execution under the control of this director.
 void generateModeTransitionCode(java.lang.StringBuffer code)
          Generate mode transition code.
 java.lang.String generateOffset(java.lang.String offsetString, IOPort port, int channel, boolean isWrite, CodeGeneratorHelper helper)
          Generate the expression that represents the offset in the generated code.
 java.lang.String generatePostfireCode()
          Generate the postfire code of the associated composite actor.
 java.lang.String generatePreinitializeCode()
          Generate the preinitialize code for this director.
 void generateTransferInputsCode(IOPort inputPort, java.lang.StringBuffer code)
          Generate code for transferring enough tokens to complete an internal iteration.
 void generateTransferOutputsCode(IOPort outputPort, java.lang.StringBuffer code)
          Generate code for transferring enough tokens to fulfill the output production rate.
 java.lang.String generateVariableDeclaration()
          Generate variable declarations for inputs and outputs and parameters.
 java.lang.String generateVariableInitialization()
          Generate variable initialization for the referenced parameters.
 java.lang.String generateWrapupCode()
          Generate the wrapup code of the director associated with this helper class.
 int getBufferSize(IOPort port, int channelNumber)
          Return the buffer size of a given channel (i.e, a given port and a given channel number).
 NamedObj getComponent()
          Return the director associated with this class.
 java.util.Set getHeaderFiles()
          Get the files needed by the code generated from this helper class.
 java.util.Set getIncludeDirectories()
          Return an empty HashSet.
 java.util.Set getLibraries()
          Return an empty HashSet.
 java.util.Set getLibraryDirectories()
          Return an empty HashSet.
 java.util.Set getModifiedVariables()
          Return a set of parameters that will be modified during the execution of the model.
 java.lang.String getReference(Attribute attribute, java.lang.String[] channelAndOffset, CodeGeneratorHelper helper)
          Return an unique label for the given attribute referenced by the given helper.
 java.lang.String getReference(TypedIOPort port, java.lang.String[] channelAndOffset, boolean forComposite, boolean isWrite, CodeGeneratorHelper helper)
          Return an unique label for the given port channel referenced by the given helper.
static java.util.List<CodeGeneratorHelper.Channel> getReferenceChannels(IOPort port, int channelNumber)
          Return the reference channels for the specified port channel.
 double getWCET()
          Return the worst case execution time (WCET) seen by this director.
 
Methods inherited from class ptolemy.codegen.kernel.CodeGeneratorHelper
_createBufferSizeAndOffsetMap, _createInputBufferSizeAndOffsetMap, _findClosedParen, _generateBlockCode, _generateBlockCode, _generateFireCode, _generateTypeConvertMethod, _generateTypeConvertStatement, _generateTypeConvertStatements, _getCastType, _getChannelAndOffset, _getFireFunctionArguments, _getHelper, _getHelper, _getReference, _getReferenceChannels, _getTypeConvertChannels, _getTypeConvertReference, _indexOf, _replaceMacro, addFunctionUsed, addNewTypeUsed, analyzeTypeConvert, checkLocal, checkRemote, codeGenType, copyFilesToCodeDirectory, generateChannelOffset, generateFireFunctionCode2, generateName, generateOffset, generatePortReference, generatePrefireCode, generateSimpleName, generateTypeConvertFireCode, generateTypeConvertFireCode, generateVariableName, getBufferSize, getCodeGenerator, getDefaultBlocks, getDirector, getDirectorHelper, getFunctionInvocation, getNewInvocation, getObject, getParameterValue, getParseTreeCodeGenerator, getPort, getRates, getReadOffset, getReference, getReference, getReference, getReference, getSharedCode, getSinkChannels, getSize, getSourceChannel, getWriteOffset, isPrimitive, isPrimitive, parseList, processCode, resetInputPortsOffset, setBufferSize, setCodeGenerator, setReadOffset, setWriteOffset, targetType, toString
 
Methods inherited from class ptolemy.kernel.util.NamedObj
_addAttribute, _adjustOverride, _attachText, _cloneFixAttributeFields, _debug, _debug, _debug, _debug, _debug, _description, _exportMoMLContents, _getContainedObject, _isMoMLSuppressed, _markContentsDerived, _propagateExistence, _propagateValue, _recordDecoratedAttributes, _removeAttribute, _splitName, _stripNumericSuffix, _validateSettables, addChangeListener, addDebugListener, attributeChanged, attributeList, attributeList, attributeTypeChanged, clone, clone, containedObjectsIterator, deepContains, depthInHierarchy, description, description, event, executeChangeRequests, exportMoML, exportMoML, exportMoML, exportMoML, exportMoML, exportMoMLPlain, getAttribute, getAttribute, getAttributes, getChangeListeners, getClassName, getContainer, getDecoratorAttribute, getDecoratorAttributes, getDerivedLevel, getDerivedList, getDisplayName, getElementName, getFullName, getModelErrorHandler, getName, getName, getPrototypeList, getSource, handleModelError, isDeferringChangeRequests, isOverridden, isPersistent, lazyContainedObjectsIterator, message, moveDown, moveToFirst, moveToIndex, moveToLast, moveUp, propagateExistence, propagateValue, propagateValues, removeChangeListener, removeDebugListener, requestChange, setClassName, setDeferringChangeRequests, setDerivedLevel, setDisplayName, setModelErrorHandler, setName, setPersistent, setSource, sortContainedObjects, toplevel, uniqueName, validateSettables, workspace
 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

_eol

protected static final java.lang.String _eol
End of line character. Under Unix: "\n", under Windows: "\n\r". We use a end of line charactor so that the files we generate have the proper end of line character for use by other native tools.


_director

protected Director _director
The associated director.


_INDENT1

protected static final java.lang.String _INDENT1
Indent string for indent level 1.

See Also:
_getIndentPrefix(int)

_INDENT2

protected static final java.lang.String _INDENT2
Indent string for indent level 2.

See Also:
_getIndentPrefix(int)

_INDENT3

protected static final java.lang.String _INDENT3
Indent string for indent level 3.

See Also:
_getIndentPrefix(int)

_INDENT4

protected static final java.lang.String _INDENT4
Indent string for indent level 4.

See Also:
_getIndentPrefix(int)
Constructor Detail

Director

public Director(Director director)
Construct the code generator helper associated with the given director. Note before calling the generate*() methods, you must also call setCodeGenerator(CodeGenerator).

Parameters:
director - The associated director.
Method Detail

createOffsetVariablesIfNeeded

public java.lang.String createOffsetVariablesIfNeeded()
                                               throws IllegalActionException
Generate code for declaring read and write offset variables if needed. It delegates to the helpers of contained actors.

Specified by:
createOffsetVariablesIfNeeded in interface ActorCodeGenerator
Overrides:
createOffsetVariablesIfNeeded in class CodeGeneratorHelper
Returns:
The generated code.
Throws:
IllegalActionException - If thrown while creating offset variables.

generateCodeForSend

public java.lang.String generateCodeForSend(IOPort port,
                                            int channel,
                                            java.lang.String dataToken)
                                     throws IllegalActionException
Generate the code for sending data to the specified port channel. This returns an empty string. Subclasses may override this method to generate domain-specific code for sending data.

Parameters:
port - The specified port.
channel - The specified channel.
dataToken - The data to send.
Returns:
An empty string in this base class.
Throws:
IllegalActionException - Not thrown in this base class.

generateCodeForGet

public java.lang.String generateCodeForGet(IOPort port,
                                           int channel)
                                    throws IllegalActionException
Generate the code for getting data from the specified port channel. This returns an empty string. Subclasses may override this method to generate domain-specific code for getting data.

Parameters:
port - The specified port.
channel - The specified channel.
Returns:
An empty string in this base class.
Throws:
IllegalActionException - Not thrown in this base class.

generateFireCode

public java.lang.String generateFireCode()
                                  throws IllegalActionException
Generate the code for the firing of actors. In this base class, it is attempted to fire all the actors once. In subclasses such as the helpers for SDF and Giotto directors, the firings of actors observe the associated schedule. In addition, some special handling is needed, e.g., the iteration limit in SDF and time advancement in Giotto.

Specified by:
generateFireCode in interface ActorCodeGenerator
Overrides:
generateFireCode in class CodeGeneratorHelper
Returns:
The generated code.
Throws:
IllegalActionException - If the helper associated with an actor throws it while generating fire code for the actor.

generateFireFunctionCode

public java.lang.String generateFireFunctionCode()
                                          throws IllegalActionException
Generate The fire function code. This method is called when the firing code of each actor is not inlined. Each actor's firing code is in a function with the same name as that of the actor.

Specified by:
generateFireFunctionCode in interface ActorCodeGenerator
Overrides:
generateFireFunctionCode in class CodeGeneratorHelper
Returns:
The fire function code.
Throws:
IllegalActionException - If thrown while generating fire code.

getHeaderFiles

public java.util.Set getHeaderFiles()
                             throws IllegalActionException
Get the files needed by the code generated from this helper class. This base class returns an empty set.

Specified by:
getHeaderFiles in interface ActorCodeGenerator
Overrides:
getHeaderFiles in class CodeGeneratorHelper
Returns:
A set of strings that are header files needed by the code generated from this helper class.
Throws:
IllegalActionException - If something goes wrong.

generateMainLoop

public java.lang.String generateMainLoop()
                                  throws IllegalActionException
Generate a main loop for an execution under the control of this director. In this base class, this simply delegates to generateFireCode() and generatePostfireCOde().

Returns:
Whatever generateFireCode() returns.
Throws:
IllegalActionException - Not thrown in this base class.

generateInitializeCode

public java.lang.String generateInitializeCode()
                                        throws IllegalActionException
Generate the initialize code for this director. The initialize code for the director is generated by appending the initialize code for each actor.

Specified by:
generateInitializeCode in interface ComponentCodeGenerator
Overrides:
generateInitializeCode in class CodeGeneratorHelper
Returns:
The generated initialize code.
Throws:
IllegalActionException - If the helper associated with an actor throws it while generating initialize code for the actor.

generateOffset

public java.lang.String generateOffset(java.lang.String offsetString,
                                       IOPort port,
                                       int channel,
                                       boolean isWrite,
                                       CodeGeneratorHelper helper)
                                throws IllegalActionException
Generate the expression that represents the offset in the generated code.

Parameters:
offsetString - The specified offset from the user.
port - The referenced port.
channel - The referenced port channel.
isWrite - Whether to generate the write or read offset.
helper - The specified helper.
Returns:
The expression that represents the offset in the generated code.
Throws:
IllegalActionException - If there is problems getting the port buffer size or the offset in the channel and offset map.

generatePostfireCode

public java.lang.String generatePostfireCode()
                                      throws IllegalActionException
Generate the postfire code of the associated composite actor.

Specified by:
generatePostfireCode in interface ActorCodeGenerator
Overrides:
generatePostfireCode in class CodeGeneratorHelper
Returns:
The postfire code of the associated composite actor.
Throws:
IllegalActionException - If the helper associated with an actor throws it while generating postfire code for the actor or while creating buffer size and offset map.

generatePreinitializeCode

public java.lang.String generatePreinitializeCode()
                                           throws IllegalActionException
Generate the preinitialize code for this director. The preinitialize code for the director is generated by appending the preinitialize code for each actor.

Specified by:
generatePreinitializeCode in interface ActorCodeGenerator
Overrides:
generatePreinitializeCode in class CodeGeneratorHelper
Returns:
The generated preinitialize code.
Throws:
IllegalActionException - If getting the helper fails, or if generating the preinitialize code for a helper fails, or if there is a problem getting the buffer size of a port.

generateModeTransitionCode

public void generateModeTransitionCode(java.lang.StringBuffer code)
                                throws IllegalActionException
Generate mode transition code. It delegates to the helpers of actors under the control of this director. The mode transition code generated in this method is executed after each global iteration, e.g., in HDF model.

Specified by:
generateModeTransitionCode in interface ActorCodeGenerator
Overrides:
generateModeTransitionCode in class CodeGeneratorHelper
Parameters:
code - The string buffer that the generated code is appended to.
Throws:
IllegalActionException - If an actor helper throws it while generating mode transition code.

generateTransferInputsCode

public void generateTransferInputsCode(IOPort inputPort,
                                       java.lang.StringBuffer code)
                                throws IllegalActionException
Generate code for transferring enough tokens to complete an internal iteration.

Parameters:
inputPort - The port to transfer tokens.
code - The string buffer that the generated code is appended to.
Throws:
IllegalActionException - If thrown while transferring tokens.

generateTransferOutputsCode

public void generateTransferOutputsCode(IOPort outputPort,
                                        java.lang.StringBuffer code)
                                 throws IllegalActionException
Generate code for transferring enough tokens to fulfill the output production rate.

Parameters:
outputPort - The port to transfer tokens.
code - The string buffer that the generated code is appended to.
Throws:
IllegalActionException - If thrown while transferring tokens.

generateVariableDeclaration

public java.lang.String generateVariableDeclaration()
                                             throws IllegalActionException
Generate variable declarations for inputs and outputs and parameters. Append the declarations to the given string buffer.

Specified by:
generateVariableDeclaration in interface ActorCodeGenerator
Overrides:
generateVariableDeclaration in class CodeGeneratorHelper
Returns:
code The generated code.
Throws:
IllegalActionException - If the helper class for the model director cannot be found.

generateVariableInitialization

public java.lang.String generateVariableInitialization()
                                                throws IllegalActionException
Generate variable initialization for the referenced parameters.

Specified by:
generateVariableInitialization in interface ActorCodeGenerator
Overrides:
generateVariableInitialization in class CodeGeneratorHelper
Returns:
code The generated code.
Throws:
IllegalActionException - If the helper class for the model director cannot be found.

generateWrapupCode

public java.lang.String generateWrapupCode()
                                    throws IllegalActionException
Generate the wrapup code of the director associated with this helper class. For this base class, this method just generate the wrapup code for each actor.

Specified by:
generateWrapupCode in interface ComponentCodeGenerator
Overrides:
generateWrapupCode in class CodeGeneratorHelper
Returns:
The generated wrapup code.
Throws:
IllegalActionException - If the helper class for each actor cannot be found, or if an error occurs while the helper generate the wrapup code.

getReference

public java.lang.String getReference(TypedIOPort port,
                                     java.lang.String[] channelAndOffset,
                                     boolean forComposite,
                                     boolean isWrite,
                                     CodeGeneratorHelper helper)
                              throws IllegalActionException
Return an unique label for the given port channel referenced by the given helper. By default, this delegates to the helper to generate the reference. Subclass may override this method to generate the desire label according to the given parameters.

Parameters:
port - The given port.
channelAndOffset - The given channel and offset.
forComposite - Whether the given helper is associated with a CompositeActor
isWrite - The type of the reference. True if this is a write reference; otherwise, this is a read reference.
helper - The specified helper.
Returns:
an unique reference label for the given port channel.
Throws:
IllegalActionException - If the helper throws it while generating the label.

getReference

public java.lang.String getReference(Attribute attribute,
                                     java.lang.String[] channelAndOffset,
                                     CodeGeneratorHelper helper)
                              throws IllegalActionException
Return an unique label for the given attribute referenced by the given helper. By default, this delegates to the helper to generate the reference. Subclass may override this method to generate the desire label according to the given parameters.

Parameters:
attribute - The given attribute.
channelAndOffset - The given channel and offset.
helper - The specified helper.
Returns:
an unique label for the given attribute.
Throws:
IllegalActionException - If the helper throws it while generating the label.

getReferenceChannels

public static java.util.List<CodeGeneratorHelper.Channel> getReferenceChannels(IOPort port,
                                                                               int channelNumber)
                                                                        throws IllegalActionException
Return the reference channels for the specified port channel. If the port channel is input or contained by an opaque CompositeActor, then this will return a list containing the given port channel. Otherwise, it returns a list of the connected sink channels.

Parameters:
port - The given port.
channelNumber - The given channel.
Returns:
The list of reference channels.
Throws:
IllegalActionException - If CodeGeneratorHelper.getSinkChannels(IOPort, int) throws it.

getBufferSize

public int getBufferSize(IOPort port,
                         int channelNumber)
                  throws IllegalActionException
Return the buffer size of a given channel (i.e, a given port and a given channel number). In this base class, this method always returns 1.

Overrides:
getBufferSize in class CodeGeneratorHelper
Parameters:
port - The given port.
channelNumber - The given channel number.
Returns:
The buffer size of the given channel. This base class always returns 1.
Throws:
IllegalActionException - Not thrown in this base class.
See Also:
CodeGeneratorHelper.setBufferSize(IOPort, int, int)

getComponent

public NamedObj getComponent()
Return the director associated with this class.

Specified by:
getComponent in interface ComponentCodeGenerator
Overrides:
getComponent in class CodeGeneratorHelper
Returns:
The director associated with this class.

getIncludeDirectories

public java.util.Set getIncludeDirectories()
                                    throws IllegalActionException
Return an empty HashSet.

Specified by:
getIncludeDirectories in interface ActorCodeGenerator
Overrides:
getIncludeDirectories in class CodeGeneratorHelper
Returns:
An empty HashSet.
Throws:
IllegalActionException - Not thrown in this method.

getLibraries

public java.util.Set getLibraries()
                           throws IllegalActionException
Return an empty HashSet.

Specified by:
getLibraries in interface ActorCodeGenerator
Overrides:
getLibraries in class CodeGeneratorHelper
Returns:
An empty HashSet.
Throws:
IllegalActionException - Not thrown in this method.

getLibraryDirectories

public java.util.Set getLibraryDirectories()
                                    throws IllegalActionException
Return an empty HashSet.

Specified by:
getLibraryDirectories in interface ActorCodeGenerator
Overrides:
getLibraryDirectories in class CodeGeneratorHelper
Returns:
An empty HashSet.
Throws:
IllegalActionException - Not thrown in this method.

getModifiedVariables

public java.util.Set getModifiedVariables()
                                   throws IllegalActionException
Return a set of parameters that will be modified during the execution of the model. The director gets those variables if it implements ExplicitChangeContext interface.

Specified by:
getModifiedVariables in interface ActorCodeGenerator
Overrides:
getModifiedVariables in class CodeGeneratorHelper
Returns:
a set of parameters that will be modified.
Throws:
IllegalActionException - If the helper associated with an actor or director throws it while getting modified variables.

getWCET

public double getWCET()
               throws IllegalActionException
Return the worst case execution time (WCET) seen by this director.

Overrides:
getWCET in class CodeGeneratorHelper
Returns:
The Worst Case Execution Time (WCET).
Throws:
IllegalActionException - If there is a problem determining the WCET or a problem accessing the model.

_ceilToPowerOfTwo

protected int _ceilToPowerOfTwo(int value)
                         throws IllegalActionException
Return the minimum number of power of two that is greater than or equal to the given integer.

Parameters:
value - The given integer.
Returns:
the minimum number of power of two that is greater than or equal to the given integer.
Throws:
IllegalActionException - If the given integer is not positive.

_getIndentPrefix

protected static java.lang.String _getIndentPrefix(int level)
Return a number of spaces that is proportional to the argument. If the argument is negative or zero, return an empty string.

Parameters:
level - The level of indenting represented by the spaces.
Returns:
A string with zero or more spaces.
See Also:
_INDENT1

_updatePortOffset

protected void _updatePortOffset(IOPort port,
                                 java.lang.StringBuffer code,
                                 int rate)
                          throws IllegalActionException
Update the read offsets of the buffer associated with the given port.

Parameters:
port - The port whose read offset is to be updated.
code - The string buffer that the generated code is appended to.
rate - The rate, which must be greater than or equal to 0.
Throws:
IllegalActionException - If thrown while reading or writing offsets, or getting the buffer size, or if the rate is less than 0.

_updateConnectedPortsOffset

protected void _updateConnectedPortsOffset(IOPort port,
                                           java.lang.StringBuffer code,
                                           int rate)
                                    throws IllegalActionException
Update the offsets of the buffers associated with the ports connected with the given port in its downstream.

Parameters:
port - The port whose directly connected downstream actors update their write offsets.
code - The string buffer that the generated code is appended to.
rate - The rate, which must be greater than or equal to 0.
Throws:
IllegalActionException - If thrown while reading or writing offsets, or getting the buffer size, or if the rate is less than 0.