ptolemy.actor.lib
Class ClockSensor

java.lang.Object
  extended by ptolemy.kernel.util.NamedObj
      extended by ptolemy.kernel.InstantiableNamedObj
          extended by ptolemy.kernel.Entity
              extended by ptolemy.kernel.ComponentEntity
                  extended by ptolemy.actor.AtomicActor
                      extended by ptolemy.actor.TypedAtomicActor
                          extended by ptolemy.actor.lib.Source
                              extended by ptolemy.actor.lib.TimedSource
                                  extended by ptolemy.actor.lib.ClockSensor
All Implemented Interfaces:
java.io.Serializable, java.lang.Cloneable, Actor, Executable, FiringsRecordable, Initializable, TimedActor, TypedActor, Changeable, Debuggable, DebugListener, Derivable, Instantiable, ModelErrorHandler, MoMLExportable, Moveable, Nameable

public class ClockSensor
extends TimedSource

This actor produces a periodic signal, a sequence of events at regularly spaced intervals. At the beginning of each time interval of length given by period, starting from the time at which initialize() is invoked, this actor initiates a sequence of output events with values given by values and offset into the period given by offsets. These parameters contain arrays, which are required to have the same length. The offsets array contains doubles, which must be nondecreasing and nonnegative, or an exception will be thrown when it is set. If any entry is greater than or equal to the period then the corresponding output will never be produced.

The values parameter by default contains an array of IntTokens with values 1 and 0. The default offsets array is {0.0, 1.0}. Thus, the default output will be alternating 1 and 0 with 50% duty cycle. The default period is 2.0.

The type of the output can be any token type. This type is inferred from the element type of the values parameter.

If the period is changed at any time, either by providing an input or by changing the parameter, then the new period will take effect as soon as possible. That is, if there is already a period in progress, it may be cut short if the new period is shorter so that its time matches the new period. But it will only be cut short if current time has not passed the cycle start time plus the new period. Otherwise, the period in progress will run to completion.

This actor can generate finite sequences by specifying a finite numberOfCycles. The numberOfCycles has a default value UNBOUNDED, indicating infinite length of executions. If numberOfCycles is a positive number, once the specified number of cycles has been completed, then this actor returns false from the postfire() method, which indicates to the director that the actor should not be fired again. (A cycle is "completed" each time the last event in the values array is produced).

The actor can also generate a finite sequence by giving a finite value to the stopTime parameter. This gives a time rather than a number of cycles, and thus can be used to stop the clock in the middle of a cycle, unlike numberOfCycles. Just like numberOfCycles, when the stop time is reached, the actor's postfire() method returns false.

If the trigger input is connected, then an output will only be produced if a input has been received since the last output. The trigger input has no effect on the first output. After the first output event, no further output event will be produced until a time greater than or equal to the time at which a trigger input is received. At that time, the output produced will have whatever value would have been produced if the trigger input was not connected. Note that this trigger is typically useful in a feedback situation, where the output of the clock eventually results in a trigger input. If the time-stamp of that trigger input is less than the time between clock events, then the clock will behave as if there were no trigger input. Otherwise, it will "skip beats."

This actor can be a bit tricky to use inside a ModalModel. In particular, if the actor is in a state refinement, then it may "skip a beat" because of the state not being the current state at the time of the beat. If this occurs, the clock will simply stop firing, and will produce no further outputs. To prevent this, the clock may be reinitialized (by setting the reset flag of a modal model transition). Alternatively, you can assign a value to the the period of the Clock in the setActions of the transition. This will also have the effect of waking up the clock, but with a subtle difference. If you use a reset transition, the clock starts over upon entering the destination state. If you set the period parameter instead, then the clock behaves as if it had been running all along (except that its period may get changed). Thus, in the first case, the output events are aligned with the time of the transition, while in the second case, they are aligned with the start time of the model execution.

This actor is a timed source; the untimed version is Pulse.

Since:
Ptolemy II 8.0
Version:
$Id: ClockSensor.java 57044 2010-01-27 22:41:05Z cxh $
Author:
Edward A. Lee, Haiyang Zheng
See Also:
Serialized Form
Accepted Rating:
Yellow (yuhong)
Proposed Rating:
Yellow (eal)

Nested Class Summary
 
Nested classes/interfaces inherited from class ptolemy.kernel.Entity
Entity.ContainedObjectsIterator
 
Field Summary
protected  int _cycleCount
          The count of cycles executed so far, or 0 before the start.
protected  Time _cycleStartTime
          The most recent cycle start time.
protected  boolean _enabled
          Indicator of whether the specified number of cycles have been completed.
protected  boolean _firstOutputProduced
          Indicator of whether the first output has been produced.
protected  Time _nextOutputTime
          The time for the next output.
protected  double[] _offsets
          Cache of offsets array value.
protected  boolean _outputProduced
          Indicator of whether an output was produced in this iteration.
protected  int _phase
          The phase of the next output.
private  double _previousPeriod
          The previous value of the period.
private  boolean _tentative
          Flag indicating that an update to period is occurring in the fire() method.
private  Time _tentativeCycleStartTime
          The tentative start time of the most recent cycle.
private  boolean _tentativeEnabled
          The indicator of whether the specified number of cycles have been completed.
protected  Time _tentativeNextOutputTime
          The tentative time for the next output.
private  int _tentativePhase
          The tentative phase of the next output.
private  boolean _tentativeTriggered
          Tentative indicator of triggered state.
private  boolean _triggered
          Indicator of whether trigger inputs have arrived since the last output.
 Parameter numberOfCycles
          The number of cycles to produce, or UNBOUNDED to specify no limit.
 Parameter offsets
          The offsets at which the specified values will be produced.
 PortParameter period
          The period of the output waveform.
 Parameter values
          The values that will be produced at the specified offsets.
 
Fields inherited from class ptolemy.actor.lib.TimedSource
stopTime, stopTimeIsLocal
 
Fields inherited from class ptolemy.actor.lib.Source
output, trigger
 
Fields inherited from class ptolemy.actor.AtomicActor
_actorFiringListeners, _initializables, _notifyingActorFiring, _stopRequested
 
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
ClockSensor(CompositeEntity container, java.lang.String name)
          Construct an actor with the specified container and name.
 
Method Summary
protected  void _catchUp()
          Catch up the tentative view of what the next output time should be.
protected  Token _getValue(int index)
          Get the specified output value, checking the form of the values parameter.
protected  boolean _isTimeForOutput()
          If the current time is not the the _tentativeNextOutputTime, we still output the data, only by changing the current model time.
protected  void _updateStates()
          Update the states and request refiring if necessary.
protected  void _updateTentativeValues()
          Copy values committed in initialize() or in the last postfire() into the corresponding tentative variables.
 void attributeChanged(Attribute attribute)
          If the argument is the offsets parameter, check that the array is nondecreasing and has the right dimension; if the argument is period, check that it is positive.
 java.lang.Object clone(Workspace workspace)
          Clone the actor into the specified workspace.
 void fire()
          Output the current value of the clock if the time is right and, if connected, a trigger has been received.
 void initialize()
          Schedule the first firing and initialize local variables.
 boolean postfire()
          Update the state of the actor and schedule the next firing, if appropriate.
 boolean prefire()
          Check that the length of the values and offsets parameters are the same.
 
Methods inherited from class ptolemy.actor.lib.TimedSource
getModelStopTime, getStopTime, wrapup
 
Methods inherited from class ptolemy.actor.TypedAtomicActor
_addPort, _fireAt, _fireAt, attributeTypeChanged, clone, newPort, typeConstraintList, typeConstraints
 
Methods inherited from class ptolemy.actor.AtomicActor
_actorFiring, _actorFiring, addActorFiringListener, addInitializable, connectionsChanged, createReceivers, declareDelayDependency, getCausalityInterface, getDirector, getExecutiveDirector, getManager, inputPortList, isFireFunctional, isStrict, iterate, newReceiver, outputPortList, preinitialize, pruneDependencies, recordFiring, removeActorFiringListener, removeDependency, removeInitializable, setContainer, stop, stopFire, terminate
 
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
_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, _debug, _debug, _debug, _debug, _debug, _getIndentPrefix, _isMoMLSuppressed, _markContentsDerived, _propagateValue, _recordDecoratedAttributes, _removeAttribute, _splitName, _stripNumericSuffix, addChangeListener, addDebugListener, attributeList, attributeList, 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, propagateValue, propagateValues, removeChangeListener, removeDebugListener, 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.actor.Executable
isFireFunctional, isStrict, iterate, stop, stopFire, terminate
 
Methods inherited from interface ptolemy.actor.Initializable
addInitializable, preinitialize, removeInitializable
 
Methods inherited from interface ptolemy.kernel.util.Nameable
description, getContainer, getDisplayName, getFullName, getName, getName, setName
 
Methods inherited from interface ptolemy.kernel.util.Derivable
getDerivedLevel, getDerivedList, propagateValue
 

Field Detail

numberOfCycles

public Parameter numberOfCycles
The number of cycles to produce, or UNBOUNDED to specify no limit. This is an integer with default UNBOUNDED.


offsets

public Parameter offsets
The offsets at which the specified values will be produced. This parameter must contain an array of doubles, and it defaults to {0.0, 1.0}.


period

public PortParameter period
The period of the output waveform. This is a double that defaults to 2.0.


values

public Parameter values
The values that will be produced at the specified offsets. This parameter must contain an ArrayToken, and it defaults to {1, 0}


_cycleCount

protected transient int _cycleCount
The count of cycles executed so far, or 0 before the start.


_cycleStartTime

protected transient Time _cycleStartTime
The most recent cycle start time.


_enabled

protected transient boolean _enabled
Indicator of whether the specified number of cycles have been completed. Also used in derived classes to turn on and off the clock.


_firstOutputProduced

protected transient boolean _firstOutputProduced
Indicator of whether the first output has been produced.


_nextOutputTime

protected transient Time _nextOutputTime
The time for the next output.


_offsets

protected transient double[] _offsets
Cache of offsets array value.


_outputProduced

protected transient boolean _outputProduced
Indicator of whether an output was produced in this iteration.


_phase

protected transient int _phase
The phase of the next output.


_tentativeNextOutputTime

protected transient Time _tentativeNextOutputTime
The tentative time for the next output.


_previousPeriod

private transient double _previousPeriod
The previous value of the period.


_tentativeCycleStartTime

private transient Time _tentativeCycleStartTime
The tentative start time of the most recent cycle.


_tentative

private transient boolean _tentative
Flag indicating that an update to period is occurring in the fire() method.


_tentativeEnabled

private transient boolean _tentativeEnabled
The indicator of whether the specified number of cycles have been completed.


_tentativePhase

private transient int _tentativePhase
The tentative phase of the next output.


_tentativeTriggered

private transient boolean _tentativeTriggered
Tentative indicator of triggered state.


_triggered

private transient boolean _triggered
Indicator of whether trigger inputs have arrived since the last output.

Constructor Detail

ClockSensor

public ClockSensor(CompositeEntity container,
                   java.lang.String name)
            throws NameDuplicationException,
                   IllegalActionException
Construct an actor with the specified container and name.

Parameters:
container - The container.
name - The name of this actor.
Throws:
IllegalActionException - If the entity cannot be contained by the proposed container.
NameDuplicationException - If the container already has an actor with this name.
Method Detail

attributeChanged

public void attributeChanged(Attribute attribute)
                      throws IllegalActionException
If the argument is the offsets parameter, check that the array is nondecreasing and has the right dimension; if the argument is period, check that it is positive. Other sanity checks with period and values are done in the fire() method.

Overrides:
attributeChanged in class TimedSource
Parameters:
attribute - The attribute that changed.
Throws:
IllegalActionException - If the offsets array is not nondecreasing and nonnegative, or if the director will not respect the fireAt() call.

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 sets the parameter public members to refer to the parameters of the new actor.

Overrides:
clone in class AtomicActor
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)

fire

public void fire()
          throws IllegalActionException
Output the current value of the clock if the time is right and, if connected, a trigger has been received.

Specified by:
fire in interface Executable
Overrides:
fire in class Source
Throws:
IllegalActionException - If the value in the offsets parameter is encountered that is greater than the period, or if there is no director.

initialize

public void initialize()
                throws IllegalActionException
Schedule the first firing and initialize local variables.

Specified by:
initialize in interface Initializable
Overrides:
initialize in class TimedSource
Throws:
IllegalActionException - If the parent class throws it, or if the values parameter is not a row vector, or if the fireAt() method of the director throws it, or if the director will not respect the fireAt() call.

postfire

public boolean postfire()
                 throws IllegalActionException
Update the state of the actor and schedule the next firing, if appropriate.

Specified by:
postfire in interface Executable
Overrides:
postfire in class TimedSource
Returns:
True if execution can continue into the next iteration.
Throws:
IllegalActionException - If the director throws it when scheduling the next firing.

prefire

public boolean prefire()
                throws IllegalActionException
Check that the length of the values and offsets parameters are the same.

Specified by:
prefire in interface Executable
Overrides:
prefire in class TimedSource
Returns:
True.
Throws:
IllegalActionException - If the values and offsets parameters do not have the same length.

_catchUp

protected void _catchUp()
                 throws IllegalActionException
Catch up the tentative view of what the next output time should be. This sets _tentativeNextOutputTime to a value that is equal to or greater than current time, and it updates _tentativePhase and _tentativeCycleStartTime to correspond with this _tentativeNextOutputTime. If _tentativeNextOutputTime is already equal to or greater than current time, then do nothing.

Throws:
IllegalActionException - If the period is invalid.

_getValue

protected Token _getValue(int index)
                   throws IllegalActionException
Get the specified output value, checking the form of the values parameter.

Parameters:
index - The index of the output values.
Returns:
A token that contains the output value.
Throws:
IllegalActionException - If the index is out of the range of the values parameter.

_isTimeForOutput

protected boolean _isTimeForOutput()
If the current time is not the the _tentativeNextOutputTime, we still output the data, only by changing the current model time.

Returns:
True.

_updateTentativeValues

protected void _updateTentativeValues()
                               throws IllegalActionException
Copy values committed in initialize() or in the last postfire() into the corresponding tentative variables. In effect, this loads the last known good value for these variables, which is particularly important if time has gone backwards. This is done in a protected method because derived classes may want to override it.

Throws:
IllegalActionException - Not thrown in this base class.

_updateStates

protected void _updateStates()
                      throws IllegalActionException
Update the states and request refiring if necessary.

Throws:
IllegalActionException - If the numberOfCycles parameter does not contain a valid parameter or can not request refiring, or if the director will not respect the fireAt() call..