Class PythonScript
- java.lang.Object
-
- ptolemy.kernel.util.NamedObj
-
- ptolemy.kernel.InstantiableNamedObj
-
- ptolemy.kernel.Entity<T>
-
- ptolemy.kernel.ComponentEntity<T>
-
- ptolemy.actor.AtomicActor<TypedIOPort>
-
- ptolemy.actor.TypedAtomicActor
-
- ptolemy.actor.lib.python.PythonScript
-
- All Implemented Interfaces:
java.lang.Cloneable
,Actor
,Executable
,FiringsRecordable
,Initializable
,TypedActor
,Changeable
,Debuggable
,DebugListener
,Derivable
,Instantiable
,ModelErrorHandler
,MoMLExportable
,Moveable
,Nameable
public class PythonScript extends TypedAtomicActor
An actor of this class executes a Python script. There are two versions of this actor provided in the Vergil libraries. The one called "PythonActor" has an input port and an output port; to view or edit its Python script, look inside the actor. The second version is called "PythonScript" and has no ports; to view or edit its Python script, select Configure (or double click on the icon).Upon creation, this actor has no ports, and no parameters other than
script
; The script parameter has visibility EXPERT, and therefore does not normally show up in a configure dialog for the actor. To make the script visible and editable, you have two options. Including an instance of an attribute of class TextEditorConfigureFactory (with its attributeName parameter set to script) results in behavior like that of the Vergil "PythonScript." That is, to edit the script, you Configure the actor. If instead you include an instance of TextEditorTableauFactory, then to edit the script you look inside the actor. Use the latter if you wish to add additional attributes to the actor and hide the script from the users. Use the former if the script is the main means by which users interact with the actor.The functionality of an actor of this type is given by a Python script. As an example, a simplified version of the
Scale
actor can be implemented by the following script:1. class Main : 2. "scale" 3. def fire(self) : 4. if not self.input.hasToken(0) : 5. return 6. s = self.scale.getToken() 7. t = self.input.get(0) 8. self.output.broadcast(s.multiply(t))
Line 1 defines a Python class Main, which matches the value of the jythonClassName parameter. An instance of this class is created when the actor is initialized. Line 2 is a description of the purpose of the script. Lines 3-8 define the fire() method, which is called by the
fire()
method of this actor. In the method body, input and output are ports that have to have been added to the actor, and scale is a parameter that has to have been added to the actor (these can be added in the XML that defines the actor instance in an actor library). The Main class can provide other methods in theExecutable
interface as needed.In the script, use
self.actor
to access the actor. For example,self.actor.getDirector()
returns the current director of the actor. For debugging, useself.actor.debug(someMessage)
. The final message sent to the debug listeners of the actor will have the string "From script: " inserted at the beginning. To avoid generating the debug message when there are no listeners, use:if self.actor.isDebugging() : self.actor.debug(someMessage)
To use a Jython module, it is necessary to create a .py file located in a location where Jython can find it. The Jython
sys.path
variable contains the Jython path. One way to get the value of the sys.path variable is to enable debugging on the actor by right clicking and selecting "Listen to Actor", which will cause the preinitialize() method to print the contents of sys.path to standard out. Another way to get the value ofsys.path
is to run the Ptolemy model atptolemy/actor/lib/python/test/PythonSysPath
. For example, under Mac OS X for the ptII user, sys.path includes/Users/ptII/lib/Lib
. So, create that directory if necessary and place the .py file in that directory, for example/Users/ptII/lib/Lib/PtPythonSquare.py
class Main : "Read the input and send the square to the output" def fire(self) : token = self.input.get(0) self.output.broadcast(token.multiply(token)) return
Then set jythonClassName to the name of the Jython class, for example
PtPythonSquare.Main
. (Note that the jythonClassName parameter should be set to the value of the Jython class name before changing the script parameter to import a Jython module.)Then set script to to:
import PtPythonSquare PtPythonSquare = reload(PtPythonSquare)
This class relies on Jython, which is a Java implementation of Python.
As of November, 2011 $PTII/lib/jython.jar was based on Jython 2.5.2.
- Since:
- Ptolemy II 2.3
- Version:
- $Id$
- Author:
- Xiaojun Liu
- Pt.AcceptedRating:
- Red (reviewmoderator)
- Pt.ProposedRating:
- Yellow (liuxj)
-
-
Nested Class Summary
-
Nested classes/interfaces inherited from class ptolemy.kernel.Entity
Entity.ContainedObjectsIterator
-
-
Field Summary
Fields Modifier and Type Field Description StringAttribute
jythonClassName
The Jython class name to be invoked.StringAttribute
script
The script that specifies the function of this actor.-
Fields inherited from class ptolemy.actor.TypedAtomicActor
_typesValid
-
Fields inherited from class ptolemy.actor.AtomicActor
_actorFiringListeners, _initializables, _notifyingActorFiring, _stopRequested
-
Fields inherited from class ptolemy.kernel.util.NamedObj
_changeListeners, _changeLock, _changeRequests, _debugging, _debugListeners, _deferChangeRequests, _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
Constructors Constructor Description PythonScript(CompositeEntity container, java.lang.String name)
Construct an actor with the given container and name.
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description void
attributeChanged(Attribute attribute)
If script is changed, invoke the python interpreter to evaluate the script.java.lang.Object
clone(Workspace workspace)
Clone the actor into the specified workspace.void
debug(java.lang.String message)
Send the message to all registered debug listeners.void
fire()
Invoke the fire() method if defined in the script.void
initialize()
Invoke the initialize() method if defined in the script.boolean
isDebugging()
Return true if this actor has at least one debug listener.boolean
postfire()
Invoke the postfire() method if defined in the script.boolean
prefire()
Invoke the prefire() method if defined in the script.void
preinitialize()
Create an instance of the parameter named by the jythonClassName parameter that is defined in the script.void
stop()
Invoke the stop() method if defined in the script.void
stopFire()
Invoke the stopFire() method if defined in the script.void
terminate()
Invoke the terminate() method if defined in the script.void
wrapup()
Invoke the wrapup() method if defined in the script.-
Methods inherited from class ptolemy.actor.TypedAtomicActor
_containedTypeConstraints, _customTypeConstraints, _defaultTypeConstraints, _fireAt, _fireAt, attributeTypeChanged, clone, isBackwardTypeInferenceEnabled, newPort, typeConstraintList, typeConstraints
-
Methods inherited from class ptolemy.actor.AtomicActor
_actorFiring, _actorFiring, _declareDelayDependency, addActorFiringListener, addInitializable, connectionsChanged, createReceivers, declareDelayDependency, getCausalityInterface, getDirector, getExecutiveDirector, getManager, inputPortList, isFireFunctional, isStrict, iterate, newReceiver, outputPortList, pruneDependencies, recordFiring, removeActorFiringListener, removeDependency, removeInitializable, setContainer
-
Methods inherited from class ptolemy.kernel.ComponentEntity
_adjustDeferrals, _checkContainer, _getContainedObject, _propagateExistence, getContainer, instantiate, isAtomic, isOpaque, moveDown, moveToFirst, moveToIndex, moveToLast, moveUp, propagateExistence, setName
-
Methods inherited from class ptolemy.kernel.Entity
_addPort, _description, _exportMoMLContents, _removePort, _validateSettables, connectedPortList, connectedPorts, containedObjectsIterator, getAttribute, getPort, getPorts, linkedRelationList, linkedRelations, portList, removeAllPorts, setClassDefinition, uniqueName
-
Methods inherited from class ptolemy.kernel.InstantiableNamedObj
_setParent, exportMoML, getChildren, getElementName, getParent, getPrototypeList, isClassDefinition, isWithinClassDefinition
-
Methods inherited from class ptolemy.kernel.util.NamedObj
_addAttribute, _adjustOverride, _attachText, _cloneFixAttributeFields, _containedDecorators, _copyChangeRequestList, _debug, _debug, _debug, _debug, _debug, _executeChangeRequests, _getIndentPrefix, _isMoMLSuppressed, _markContentsDerived, _notifyHierarchyListenersAfterChange, _notifyHierarchyListenersBeforeChange, _propagateValue, _removeAttribute, _splitName, _stripNumericSuffix, addChangeListener, addDebugListener, addHierarchyListener, attributeDeleted, attributeList, attributeList, decorators, deepContains, depthInHierarchy, description, description, event, executeChangeRequests, exportMoML, exportMoML, exportMoML, exportMoML, exportMoMLPlain, getAttribute, getAttributes, getChangeListeners, getClassName, getDecoratorAttribute, getDecoratorAttributes, getDerivedLevel, getDerivedList, getDisplayName, getFullName, getModelErrorHandler, getName, getName, getSource, handleModelError, isDeferringChangeRequests, isOverridden, isPersistent, lazyContainedObjectsIterator, message, notifyOfNameChange, propagateValue, propagateValues, removeAttribute, removeChangeListener, removeDebugListener, removeHierarchyListener, requestChange, setClassName, setDeferringChangeRequests, setDerivedLevel, setDisplayName, setModelErrorHandler, setPersistent, setSource, sortContainedObjects, toplevel, toString, validateSettables, workspace
-
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
-
Methods inherited from interface ptolemy.actor.Actor
createReceivers, getCausalityInterface, getDirector, getExecutiveDirector, getManager, inputPortList, newReceiver, outputPortList
-
Methods inherited from interface ptolemy.kernel.util.Derivable
getDerivedLevel, getDerivedList, propagateValue
-
Methods inherited from interface ptolemy.actor.Executable
isFireFunctional, isStrict, iterate
-
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
-
jythonClassName
public StringAttribute jythonClassName
The Jython class name to be invoked. The default value is "Main", which indicates that the script parameter should define a class named "Main". If the script parameter imports a Jython module, for example: "import Foo", then Foo.py should define a class named "Main" and this parameter should have the value "Foo.Main". If the value of this parameter is anything other than "Main", then preinitialize() will reread the script. This is how Jython modules can be used. Note that the jythonClassName parameter should be set to the value of the Jython class name before changing the script parameter to import a Jython module.
-
script
public StringAttribute script
The script that specifies the function of this actor. The default value is a script that copies the input to the output.
-
-
Constructor Detail
-
PythonScript
public PythonScript(CompositeEntity container, java.lang.String name) throws NameDuplicationException, IllegalActionException
Construct an actor with the given container and name. In addition to invoking the base class constructor, create the script parameter, and initialize the script to provide an empty template.- Parameters:
container
- The container.name
- The name of this actor.- Throws:
NameDuplicationException
- If the container already has an actor with this name.IllegalActionException
- If the actor cannot be contained by the proposed container.
-
-
Method Detail
-
attributeChanged
public void attributeChanged(Attribute attribute) throws IllegalActionException
If script is changed, invoke the python interpreter to evaluate the script.- Overrides:
attributeChanged
in classNamedObj
- Parameters:
attribute
- The attribute that changed.- Throws:
IllegalActionException
- If there is any error in evaluating the script.
-
clone
public java.lang.Object clone(Workspace workspace) throws java.lang.CloneNotSupportedException
Clone the actor into the specified workspace. This calls the base class and then properly sets private variables.- Overrides:
clone
in classTypedAtomicActor
- Parameters:
workspace
- The workspace for the new object.- Returns:
- A new actor.
- 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)
-
debug
public void debug(java.lang.String message)
Send the message to all registered debug listeners. In the script, useself.actor.debug()
to call this method.- Parameters:
message
- The debug message.
-
fire
public void fire() throws IllegalActionException
Invoke the fire() method if defined in the script.- Specified by:
fire
in interfaceExecutable
- Overrides:
fire
in classAtomicActor<TypedIOPort>
- Throws:
IllegalActionException
- If there is any error in calling the fire() method defined by the script.
-
initialize
public void initialize() throws IllegalActionException
Invoke the initialize() method if defined in the script.- Specified by:
initialize
in interfaceInitializable
- Overrides:
initialize
in classAtomicActor<TypedIOPort>
- Throws:
IllegalActionException
- If there is any error in calling the initialize() method defined by the script.
-
isDebugging
public boolean isDebugging()
Return true if this actor has at least one debug listener.- Returns:
- True if this actor has at least one debug listener.
-
postfire
public boolean postfire() throws IllegalActionException
Invoke the postfire() method if defined in the script. Return true when the method return value is not zero, or the method does not return a value, or the method is not defined in the script.- Specified by:
postfire
in interfaceExecutable
- Overrides:
postfire
in classAtomicActor<TypedIOPort>
- Returns:
- False if postfire() is defined in the script and returns 0, true otherwise.
- Throws:
IllegalActionException
- If there is any error in calling the postfire() method defined by the script.
-
prefire
public boolean prefire() throws IllegalActionException
Invoke the prefire() method if defined in the script. Return true when the method return value is not zero, or the method does not return a value, or the method is not defined in the script.- Specified by:
prefire
in interfaceExecutable
- Overrides:
prefire
in classAtomicActor<TypedIOPort>
- Returns:
- False if prefire() is defined in the script and returns 0, true otherwise.
- Throws:
IllegalActionException
- If there is any error in calling the prefire() method.
-
preinitialize
public void preinitialize() throws IllegalActionException
Create an instance of the parameter named by the jythonClassName parameter that is defined in the script. Add all parameters and ports of this actor as attributes of the object, so that they become accessible to the methods defined in the script.- Specified by:
preinitialize
in interfaceInitializable
- Overrides:
preinitialize
in classAtomicActor<TypedIOPort>
- Throws:
IllegalActionException
- If there is any error in creating an instance of the class named by the jythonClassName class defined in the script.
-
stop
public void stop()
Invoke the stop() method if defined in the script. Ignore any error in calling the method.- Specified by:
stop
in interfaceExecutable
- Overrides:
stop
in classAtomicActor<TypedIOPort>
-
stopFire
public void stopFire()
Invoke the stopFire() method if defined in the script. Ignore any error in calling the method.- Specified by:
stopFire
in interfaceExecutable
- Overrides:
stopFire
in classAtomicActor<TypedIOPort>
-
terminate
public void terminate()
Invoke the terminate() method if defined in the script. Ignore any error in calling the method.- Specified by:
terminate
in interfaceExecutable
- Overrides:
terminate
in classAtomicActor<TypedIOPort>
-
wrapup
public void wrapup() throws IllegalActionException
Invoke the wrapup() method if defined in the script. Ignore any error in calling the method.- Specified by:
wrapup
in interfaceInitializable
- Overrides:
wrapup
in classAtomicActor<TypedIOPort>
- Throws:
IllegalActionException
- If there is any error in calling the wrapup() method defined in the script.
-
-