ptolemy.domains.ct.kernel
Class CTBaseIntegrator

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.ct.kernel.CTBaseIntegrator
All Implemented Interfaces:
java.io.Serializable, java.lang.Cloneable, Actor, Executable, FiringsRecordable, Initializable, TimedActor, TypedActor, CTDynamicActor, CTStatefulActor, CTStepSizeControlActor, Changeable, Debuggable, DebugListener, Derivable, Instantiable, ModelErrorHandler, MoMLExportable, Moveable, Nameable
Direct Known Subclasses:
Integrator

public class CTBaseIntegrator
extends TypedAtomicActor
implements TimedActor, CTStepSizeControlActor, CTDynamicActor, CTStatefulActor

The base class for integrators in the continuous-time (CT) domain. An integrator has one input port and one output port. Conceptually, the input is the derivative of the output w.r.t. time. So an ordinary differential equation (ODE) dx/dt = f(x, t) can be built by:

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

An integrator is a dynamic actor that can emit a token (a state) at a time without knowing the input at that time. An integrator is a step size control actor that can control the accuracy of the ODE solution by adjusting step sizes. An integrator has memory, which is its state.

To help solving the ODE, a set of internal variables are used:
state: This is the value of the state variable at a time point, which has beed confirmed by all the step size control actors. tentative state: This is the value of the state variable which has not been confirmed. It is a starting point for other actors to estimate the accuracy of this integration step. history: The previous states and their derivatives. History may be used by multistep integration methods.

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

An integrator has one parameter: the initialState. At the initialization stage of the simulation, the state of the integrator is set to the initial state. Changes of the initialState made during execution cause the state to be reset to the specified value. The default value of the parameter is 0.0 of type double.

An integrator can possibly have several auxiliary variables for the the ODE solvers to use. The number of the auxiliary variables is checked before each iteration. 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.

Since:
Ptolemy II 0.2
Version:
$Id: CTBaseIntegrator.java 57040 2010-01-27 20:52:32Z cxh $
Author:
Jie Liu, Haiyang Zheng
See Also:
ODESolver, CTDirector, Serialized Form
Accepted Rating:
Red (yuhong)
Proposed Rating:
Yellow (hyzheng)

Nested Class Summary
private static class CTBaseIntegrator.DoubleDouble
          A data structure for storing two double numbers.
protected  class CTBaseIntegrator.History
          The history information, state and derivatives, at equidistance past time points.
 
Nested classes/interfaces inherited from class ptolemy.kernel.Entity
Entity.ContainedObjectsIterator
 
Field Summary
private  double[] _auxVariables
           
private  double _derivative
           
protected  CTBaseIntegrator.History _history
          The history of states and their derivative.
private  double _state
           
private  double _storedState
           
private  boolean _successful
           
private  double _tentativeDerivative
           
private  double _tentativeState
           
 Parameter initialState
          The initial state of type DoubleToken.
 TypedIOPort input
          The input port.
 TypedIOPort output
          The output 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
 
Fields inherited from interface ptolemy.actor.Executable
COMPLETED, NOT_READY, STOP_ITERATING
 
Fields inherited from interface ptolemy.actor.Executable
COMPLETED, NOT_READY, STOP_ITERATING
 
Constructor Summary
CTBaseIntegrator(CompositeEntity container, java.lang.String name)
          Construct an integrator, with a 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.
 void clearHistory()
          Clear the history information.
 void emitCurrentStates()
          Emit the tentative output, which is the current state of the integrator.
 void fire()
          Delegate to the integratorFire() method of the current ODE solver.
 double[] getAuxVariables()
          Return the auxiliary variables in a double array.
 double getDerivative()
          Return the derivative of the latest updated resolved state.
 double[] getHistory(int index)
          Return the history information of the last index-th step.
 int getHistoryCapacity()
          Return the history capacity.
 double getState()
          Return the state of the integrator.
 double getTentativeDerivative()
          Return the tentative derivative.
 double getTentativeState()
          Return the tentative state.
 int getValidHistoryCount()
          Return the number of valid history entries.
 void goToMarkedState()
          Go to the marked state.
 void initialize()
          Initialize the integrator.
 boolean isOutputAccurate()
          Always return true because an integrator's output is always accurate no matter what step size is chosen.
 boolean isStateAccurate()
          Return true if the state is resolved successfully.
 void markState()
          Mark and remember the current state.
 boolean postfire()
          Update the state and its derivative, and push them into history if the history capacity is bigger than 0.
 double predictedStepSize()
          Return the predicted next step size.
 boolean prefire()
          Setup the integrator to operate with the current ODE solver.
 void preinitialize()
          Override the base class to declare that the output does not depend on the input in a firing.
 double refinedStepSize()
          Return the estimation of the refined next step size.
 void setAuxVariables(int index, double value)
          Set the value of an auxiliary variable.
 void setHistoryCapacity(int cap)
          Set history capacity.
 void setTentativeDerivative(double value)
          Set the tentative derivative, dx/dt.
 void setTentativeState(double value)
          Set the tentative state.
 
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, clone, connectionsChanged, createReceivers, declareDelayDependency, getCausalityInterface, getDirector, getExecutiveDirector, getManager, inputPortList, isFireFunctional, isStrict, iterate, newReceiver, outputPortList, 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, 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, removeInitializable, wrapup
 
Methods inherited from interface ptolemy.kernel.util.Nameable
description, getContainer, getDisplayName, getFullName, getName, getName, setName
 
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, removeInitializable, wrapup
 
Methods inherited from interface ptolemy.kernel.util.Nameable
description, getContainer, getDisplayName, getFullName, getName, getName, setName
 
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, 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

input

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


output

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


initialState

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


_history

protected CTBaseIntegrator.History _history
The history of states and their derivative. This variable is needed by Linear Multistep (LMS) methods, like Trapezoidal rule and backward differential formula. This variable is protected so that derived classes may access it directly.


_auxVariables

private double[] _auxVariables

_derivative

private double _derivative

_state

private double _state

_storedState

private double _storedState

_successful

private boolean _successful

_tentativeDerivative

private double _tentativeDerivative

_tentativeState

private double _tentativeState
Constructor Detail

CTBaseIntegrator

public CTBaseIntegrator(CompositeEntity container,
                        java.lang.String name)
                 throws NameDuplicationException,
                        IllegalActionException
Construct an integrator, with a 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.

clearHistory

public void clearHistory()
Clear the history information.


emitCurrentStates

public void emitCurrentStates()
                       throws IllegalActionException
Emit the tentative output, which is the current state of the integrator.

Specified by:
emitCurrentStates in interface CTDynamicActor
Throws:
IllegalActionException - If the data transfer can not be completed.

fire

public void fire()
          throws IllegalActionException
Delegate to the integratorFire() method of the current ODE solver. The existence of a director and an ODE solver is not checked because it is checked in the prefire() method.

Specified by:
fire in interface Executable
Overrides:
fire in class AtomicActor
Throws:
IllegalActionException - If thrown by integratorFire() of the solver.

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)

getDerivative

public final double getDerivative()
Return the derivative of the latest updated resolved state.

Returns:
The derivative of the latest updated resolved state.

getHistory

public double[] getHistory(int index)
Return the history information of the last index-th step. The returned history array has length 2, where the first element is the history state, and the second element is the corresponding derivative. The index starts from 0. If the current time is t(n), then getHistory(0) gives the state and derivative of time t(n-1), and getHistory(1) corresponds to time t(n-2). The history information is equidistant in time, and the distance is the current step size. If the step sizes are changed during the execution, the history information will be self-adjusted. If the index is less than 0 or grater than the history capacity, a runtime IndexOutOfBoundsException will be thrown.

Parameters:
index - The index.
Returns:
The history array at the index point.

getHistoryCapacity

public final int getHistoryCapacity()
Return the history capacity.

Returns:
The maximum capacity of the history information.
See Also:
setHistoryCapacity(int)

getState

public final double getState()
Return the state of the integrator. The returned state is the latest confirmed state. If the history capacity is bigger than 0, the same state can be retrieved from getHistory(0)[0]. However, this method is more efficient.

Returns:
A double number as the state of the integrator.

getTentativeDerivative

public double getTentativeDerivative()
Return the tentative derivative.

Returns:
the tentative derivative.
See Also:
setTentativeDerivative(double)

getTentativeState

public double getTentativeState()
Return the tentative state.

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

getValidHistoryCount

public final int getValidHistoryCount()
Return the number of valid history entries. This number is always less than or equal to the history capacity.

Returns:
The number of valid history entries.

goToMarkedState

public void goToMarkedState()
Go to the marked state. After calling the markState() method, calling this method will bring the integrator back to the marked state. This method is used for rollbacking the execution to a previous time point. Note that derivative is not stored. Therefore, when states are restored, they need to be propagated through state transition actors such that the derivatives are restored (reconstructed) too.

Specified by:
goToMarkedState in interface CTStatefulActor

initialize

public void initialize()
                throws IllegalActionException
Initialize the integrator. Check for the existence of director and ODE solver. Update initial state parameter. Set the initial state to the tentative state and the state. Set tentative derivative to 0.0. Clear the history.

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

isOutputAccurate

public boolean isOutputAccurate()
Always return true because an integrator's output is always accurate no matter what step size is chosen.

Specified by:
isOutputAccurate in interface CTStepSizeControlActor
Returns:
True always.

isStateAccurate

public boolean isStateAccurate()
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:
isStateAccurate in interface CTStepSizeControlActor
Returns:
True if the state is resolved successfully.

markState

public void markState()
Mark and remember the current state. This remembered state can be retrieved by the goToMarkedState() method. The marked state may be used for rolling back the execution to a previous time point. Note that the derivative is not saved.

Specified by:
markState in interface CTStatefulActor

postfire

public boolean postfire()
                 throws IllegalActionException
Update the state and its derivative, and push them into history if the history capacity is bigger than 0.

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

predictedStepSize

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

Specified by:
predictedStepSize in interface CTStepSizeControlActor
Returns:
The predicteded next step size.

prefire

public boolean prefire()
                throws IllegalActionException
Setup the integrator to operate with the current ODE solver. This method checks whether there are enough auxiliary variables in the integrator for the current ODE solver. If not, create more auxiliary variables.

This method also adjusts the history information w.r.t. the current ODE solver and the current step size.

Specified by:
prefire in interface Executable
Overrides:
prefire in class AtomicActor
Returns:
True always.
Throws:
IllegalActionException - If there's no director or the director has no ODE solver.

preinitialize

public void preinitialize()
                   throws IllegalActionException
Override the base class to declare that the output does not depend on the input in a firing.

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

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 CTStepSizeControlActor
Returns:
The refined step size.

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()

setHistoryCapacity

public final void setHistoryCapacity(int cap)
Set history capacity. This will typically be set by the ODE solvers that uses the history. If the argument is less than 0, the capacity is set to 0.

Parameters:
cap - The capacity.
See Also:
getHistoryCapacity()

setTentativeDerivative

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

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

setTentativeState

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

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