ptolemy.domains.continuous.kernel
Class ContinuousIntegrator

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.domains.continuous.kernel.ContinuousIntegrator
All Implemented Interfaces:
java.io.Serializable, java.lang.Cloneable, Actor, Executable, FiringsRecordable, Initializable, TypedActor, ContinuousStatefulComponent, ContinuousStepSizeController, Changeable, Debuggable, DebugListener, Derivable, Instantiable, ModelErrorHandler, MoMLExportable, Moveable, Nameable
Direct Known Subclasses:
Integrator

public class ContinuousIntegrator
extends TypedAtomicActor
implements ContinuousStatefulComponent, ContinuousStepSizeController

The integrator in the continuous domain. The derivative port receives the derivative of the state of the integrator with respect to time. The state output port shows the state of the integrator. So an ordinary differential equation (ODE), dx/dt = f(x, t), can be built as follows:

            +---------------+
     dx/dt  |               |   x
 +--------->|   Integrator  |---------+----->
 |          |               |         |
 |          +----^-----^----+         |
 |                                    |
 |             |---------|            |
 +-------------| f(x, t) |<-----------+
               |---------|
 

An integrator also has a port-parameter called initialState. The parameter provides the initial state for integration during the initialization stage of execution. If during execution an input token is provided on the port, then the state of the integrator will be reset at that time to the value of the token. The default value of the parameter is 0.0.

An integrator also has an input port named impulse. When present, a token at the impulse input port is interpreted as the weight of a Dirac delta function. It causes an increment or decrement to the state at the time of the arrival of the value. If both impulse and initialState have data on the same microstep, then initialState dominates.

Note that both impulse and reset expect to receive discrete inputs. To preserve continuity, this means that those inputs should be present only when the solver step size is zero. If this assumption is violated, then this actor will throw an exception.

An integrator can generate an output (its current state) before the derivative input is known, and hence can be used in feedback loops like that above without creating a causality loop. Since impulse and initialState inputs affect the output immediately, using them in feedback loops may require inclusion of a TimeDelay actor.

For different ODE solving methods, the functionality of an integrator may be different. The delegation and strategy design patterns are used in this class, the abstract ODESolver class, and the concrete ODE solver classes. Some solver-dependent methods of integrators delegate to the concrete ODE solvers.

An integrator can possibly have several auxiliary variables for the ODE solvers to use. The ODE solver class provides the number of variables needed for that particular solver. The auxiliary variables can be set and get by setAuxVariables() and getAuxVariables() methods.

This class is based on the CTBaseIntegrator by Jie Liu and Haiyang Zheng, but it has more ports and provides more functionality.

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

Nested Class Summary
private static class ContinuousIntegrator.IntegratorCausalityInterface
          Custom causality interface that fine tunes the equivalent ports and removes the dependence of the state output on the derivative input.
 
Nested classes/interfaces inherited from class ptolemy.kernel.Entity
Entity.ContainedObjectsIterator
 
Field Summary
private  double[] _auxVariables
          Auxiliary variable array.
private  CausalityInterface _causalityInterface
          The custom causality interface.
private  double _lastOutput
          The last output produced in the same round.
private  int _lastRound
          The last round this integrator is fired.
private  double _state
          The state of the integrator.
private  boolean _successful
          Indicate whether the latest step is successful from this integrator's point of view.
private  double _tentativeState
          The tentative state.
 TypedIOPort derivative
          The derivative port.
 TypedIOPort impulse
          The impulse input port.
 PortParameter initialState
          The initial state of type DoubleToken.
 TypedIOPort state
          The state port.
 
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
ContinuousIntegrator(CompositeEntity container, java.lang.String name)
          Construct an integrator with the specified name and a container.
 
Method Summary
 void attributeChanged(Attribute attribute)
          If the specified attribute is initialState, then reset the state of the integrator to its value.
 java.lang.Object clone(Workspace workspace)
          Clone this actor into the specified workspace.
 void fire()
          If the value at the derivative port is known, and the current step size is bigger than 0, perform an integration.
 double[] getAuxVariables()
          Return the auxiliary variables in a double array.
 CausalityInterface getCausalityInterface()
          Return a causality interface for this actor.
 double getDerivative()
          Get the current value of the derivative input port.
 double getState()
          Return the state of the integrator.
 double getTentativeState()
          Return the tentative state.
 void initialize()
          Initialize the integrator.
 boolean isStepSizeAccurate()
          Return true if the state is resolved successfully.
 boolean isStrict()
          Return false.
 boolean postfire()
          Update the state.
 boolean prefire()
          If either the impulse or initialState input is unknown, then return false.
 double refinedStepSize()
          Return the estimation of the refined next step size.
 void rollBackToCommittedState()
          Roll back to committed state.
 void setAuxVariables(int index, double value)
          Set the value of an auxiliary variable.
 void setTentativeState(double value)
          Set the tentative state.
 double suggestedStepSize()
          Return the suggested next step size.
 
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, getDirector, getExecutiveDirector, getManager, inputPortList, isFireFunctional, iterate, newReceiver, outputPortList, preinitialize, pruneDependencies, recordFiring, removeActorFiringListener, removeDependency, removeInitializable, setContainer, stop, stopFire, terminate, wrapup
 
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, getDirector, getExecutiveDirector, getManager, inputPortList, newReceiver, outputPortList
 
Methods inherited from interface ptolemy.actor.Executable
isFireFunctional, iterate, stop, stopFire, terminate
 
Methods inherited from interface ptolemy.actor.Initializable
addInitializable, preinitialize, removeInitializable, wrapup
 
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

impulse

public TypedIOPort impulse
The impulse input port. This is a single port of type double.


derivative

public TypedIOPort derivative
The derivative port. This is a single port of type double.


state

public TypedIOPort state
The state port. This is a single port of type double.


initialState

public PortParameter initialState
The initial state of type DoubleToken. The default value is 0.0.


_auxVariables

private double[] _auxVariables
Auxiliary variable array. This is used by the solver to record intermediate values in a multi-step solver algorithm.


_causalityInterface

private CausalityInterface _causalityInterface
The custom causality interface.


_lastOutput

private double _lastOutput
The last output produced in the same round.


_lastRound

private int _lastRound
The last round this integrator is fired.


_state

private double _state
The state of the integrator.


_successful

private boolean _successful
Indicate whether the latest step is successful from this integrator's point of view.


_tentativeState

private double _tentativeState
The tentative state.

Constructor Detail

ContinuousIntegrator

public ContinuousIntegrator(CompositeEntity container,
                            java.lang.String name)
                     throws NameDuplicationException,
                            IllegalActionException
Construct an integrator with the specified name and a container. The integrator is in the same workspace as the container.

Parameters:
container - The container.
name - The name.
Throws:
NameDuplicationException - If the name is used by another actor in the container.
IllegalActionException - If ports can not be created, or thrown by the super class.
Method Detail

attributeChanged

public void attributeChanged(Attribute attribute)
                      throws IllegalActionException
If the specified attribute is initialState, then reset the state of the integrator to its value.

Overrides:
attributeChanged in class NamedObj
Parameters:
attribute - The attribute that has changed.
Throws:
IllegalActionException - If the new parameter value is not valid.

clone

public java.lang.Object clone(Workspace workspace)
                       throws java.lang.CloneNotSupportedException
Clone this actor into the specified workspace. The new actor is not added to the directory of that workspace (you must do this yourself if you want it there). The result is a new actor with the same ports as the original, but no connections and no container. A container must be set before much can be done with this actor.

Overrides:
clone in class AtomicActor
Parameters:
workspace - The workspace for the cloned object.
Returns:
A new ComponentEntity.
Throws:
java.lang.CloneNotSupportedException - If cloned ports cannot have as their container the cloned entity (this should not occur), or if one of the attributes cannot be cloned.
See Also:
NamedObj.exportMoML(Writer, int, String), NamedObj.setDeferringChangeRequests(boolean)

fire

public void fire()
          throws IllegalActionException
If the value at the derivative port is known, and the current step size is bigger than 0, perform an integration. If the impulse port is known and has data, then add the value provided to the state; if the initialState port is known and has data, then reset the state to the provided value. If both impulse and initialState have data, then initialState dominates. If either is unknown, then simply return, leaving the output unknown. Note that the signals provided at these two ports are required to be purely discrete. This is enforced by throwing an exception if the current microstep is zero when they have input data.

Specified by:
fire in interface Executable
Overrides:
fire in class AtomicActor
Throws:
IllegalActionException - If the input is infinite or not a number, or if thrown by the solver, or if data is present at either impulse or initialState and the step size is greater than zero.

getAuxVariables

public double[] getAuxVariables()
Return the auxiliary variables in a double array. The auxiliary variables are created in the prefire() method and may be set during each firing of the actor. Return null if the auxiliary variables have never been created.

Returns:
The auxiliary variables in a double array.
See Also:
setAuxVariables(int, double)

getCausalityInterface

public CausalityInterface getCausalityInterface()
Return a causality interface for this actor. This causality interface expresses dependencies that are instances of BooleanDependency that declare that the state output port does not depend on any of the input ports at this microstep. Moreover, the initialState and impulse ports are equivalent (to process inputs at either, you need to know about inputs at the other). You do not need to know about inputs at derivative.

Specified by:
getCausalityInterface in interface Actor
Overrides:
getCausalityInterface in class AtomicActor
Returns:
A representation of the dependencies between input ports and output ports.

getDerivative

public double getDerivative()
                     throws NoTokenException,
                            IllegalActionException
Get the current value of the derivative input port.

Returns:
The current value at the derivative input port.
Throws:
NoTokenException - If reading the input throws it.
IllegalActionException - If thrown while reading the input.

getState

public final double getState()
Return the state of the integrator. The returned state is the latest confirmed state.

Returns:
The state of the integrator.

getTentativeState

public double getTentativeState()
Return the tentative state.

Returns:
The tentative state.
See Also:
setTentativeState(double)

initialize

public void initialize()
                throws IllegalActionException
Initialize the integrator. Check for the existence of a director and an ODE solver. Set the state to the value given by initialState.

Specified by:
initialize in interface Initializable
Overrides:
initialize in class AtomicActor
Throws:
IllegalActionException - If there is no director, or the director has no ODE solver, or the initialState parameter does not contain a valid token, or the superclass throws it.

isStepSizeAccurate

public boolean isStepSizeAccurate()
Return true if the state is resolved successfully. If the input is not available, or the input is a result of divide by zero, a NumericalNonconvergeException is thrown.

Specified by:
isStepSizeAccurate in interface ContinuousStepSizeController
Returns:
True if the state is resolved successfully.

isStrict

public boolean isStrict()
Return false. This actor can produce some outputs even the inputs are unknown. This actor is crucial at breaking feedback loops during simulation.

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

postfire

public boolean postfire()
                 throws IllegalActionException
Update the state. This commits the tentative state.

Specified by:
postfire in interface Executable
Overrides:
postfire in class AtomicActor
Returns:
True always.
Throws:
IllegalActionException - Not thrown in this base class.

prefire

public boolean prefire()
                throws IllegalActionException
If either the impulse or initialState input is unknown, then return false. Otherwise, return true.

Specified by:
prefire in interface Executable
Overrides:
prefire in class AtomicActor
Returns:
True If the actor is ready to fire.
Throws:
IllegalActionException - If the superclass throws it.

suggestedStepSize

public double suggestedStepSize()
Return the suggested next step size. This method delegates to the integratorPredictedStepSize() method of the current ODESolver.

Specified by:
suggestedStepSize in interface ContinuousStepSizeController
Returns:
The suggested next step size.

refinedStepSize

public double refinedStepSize()
Return the estimation of the refined next step size. If this integrator considers the current step to be accurate, then return the current step size, otherwise return half of the current step size.

Specified by:
refinedStepSize in interface ContinuousStepSizeController
Returns:
The refined step size.

rollBackToCommittedState

public void rollBackToCommittedState()
Roll back to committed state. This resets the tentative state to the current state.

Specified by:
rollBackToCommittedState in interface ContinuousStatefulComponent

setAuxVariables

public void setAuxVariables(int index,
                            double value)
                     throws InvalidStateException
Set the value of an auxiliary variable. The index indicates which auxiliary variable in the auxVariables array. If the index is out of the bound of the auxiliary variable array, an InvalidStateException is thrown to indicate an inconsistency in the ODE solver.

Parameters:
index - The index in the auxVariables array.
value - The value to be set.
Throws:
InvalidStateException - If the index is out of the range of the auxiliary variable array.
See Also:
getAuxVariables()

setTentativeState

public final void setTentativeState(double value)
Set the tentative state. Tentative state is the state that the ODE solver resolved in one step. This may not be the final state due to error control or event detection.

Parameters:
value - The value to be set.
See Also:
getTentativeState()