**There is no need to recreate the source code in this tutorial.** It already exists in the examples. So, read the explanations below, and then go play with the simulations in the
**examples/** directory, to learn how to use the SAIntegrator library. Enjoy!
It creates an instance of ```SA::RK2Integrator``` called ```integ```.
We could just as easily have used ```SA::EulerIntegrator```, ```SA::HeunsMethod```, ```SA::RK4Integrator```, or ```SA::RK3_8Integrator```, as their [constructor](#RK2IntegratorConstructor2) interfaces are identical.
The first argument of this constructor specifies the integration step-size. We will be integrating in 0.01 second steps.
The second argument specifies the state-size, the number of variables that we will be integrating per step. In this case we'll be integrating two position variables, and two velocity variables, so our state-size is 4.
The third specifies which variables comprise the state, to be updated by the Integrator. Here, we want to update the variables: cannon.pos[0], cannon.pos[1], cannon.vel[0]), and cannon.vel[1].
The fourth argument of the constructor is a pointer to a function that is responsible for generating state derivatives. Its type is as follows:
It's described in more detail [here](#typedef-DerivsFunc).
The final argument specifies a pointer to user-data which is passed-through to the derivative function and others. We'll demonstrate it later in this tutorial. For now we'll just pass NULL.
The array ```double* state_var_p[4]```, specifies the state variables to be updated by Integrator.
<aid=DerivsFunc></a>
#### DerivsFunc
The cannon ball simulation implements the following ```DerivsFunc```:
The Integrator calls ```calc_derivs``` function to generate the state derivatives, that is velocity, and acceleration.
First argument passed to this function is the current value of the independent variable. In this case, it represents time.
The second argument passed in is the current state array. It's length is the Integrator's state-size. The order of state values matches the order specified in ```state_var_p``` in the constructor.
The third argument, ```derivs```, is an array of (also of length state-size), which ```calc_derivs``` is responsible for populating.
For clarity here: state[0] and state[1] represent the cannonball position. state[2] and state[3] represent the cannonball velocity. derivs[0] and derivs[1] represents the time derivative of position, i.e., velocity. derivs[2] and derivs[3] represents the time derivative of velocity, i.e., acceleration.
#### The Integration Loop
The while loop, at the bottom of [Cannonball.cpp](#listing-Cannonball.cpp) is where the integration happens.
1. Loads the values of the variables that we specified in ```state_var_p``` into the integrator.
2. Steps forward by ```dt```, integrating the state-derivatives into the state, and finally
3. Unloads the result back into the variables that we specified in ```state_var_p```.
#### Getting and Setting The Independent Variable
```t = integ.getIndyVar();``` gets the time from the Integrator. So, why isn't this method called **getTime()**? Because we don't just have to integrate over time. We're integrating over the independent variable, which in the case of the Cannonball simulation happens to be time.
```integ.setIndyVar( double )``` sets the independent variable. So if we wanted to start our sim at t=4.0 seconds then we could replace ```double t = 0.0;``` with:
This section demonstrates how to use a RootFinder with our integrator, using the program in [examples/BouncyCannonball](examples/BouncyCannonBall/README.md). This example simulates a cannon ball that impacts the ground (defined as pos[1] = 0.0), and bounces. The BouncyCannonball example is the same as the Cannonball example, with some additional code.
The first code addition is to add the following line immediately after the instanciation of ```integ```.
The ```add_Rootfinder``` method tells ```integ``` to look for roots.
```add_Rootfinder``` is available for: ```SA::RK2Integrator```, ```SA::EulerIntegrator```, ```SA::HeunsMethod```, ```SA::RK4Integrator```, and ```SA::RK3_8Integrator```.
The first argument is the tolerance; the maximum error we'll accept. The error is the difference between some element of the current integration state (of our chosing), and the root of that element. The root is the value of the independent variable, where the particular state-element of interest (or function of that state-element) is zero. Specifically, for the BouncyCannonball example, a root is a value of ```t```, when the ball impacts the ground, where ```pos[1] == 0.0```.
The second argument is the slope constraint. This can have one three values:
1. ```Negative``` - the slope of the element of interest must be negative.
2. ```Unconstrained``` - no slope constraint.
3. ```Positive``` - the slope of the element of interest must be positive.
The third argument is a pointer to a function responsible for estimating the error. It's type is:
The [```find_roots```](#function-find_roots) method of the ```RootFinder``` object will determine the estimated correction in ```t``` to get ```state[1]``` to zero. Remember that ```state[1]``` is the value of cannon.pos[1], the cannon ball height above the ground.
If the error == 0.0, then ```state[1]``` is zero, meaning that our cannon ball has contacted the ground at time ```t```.
The first thing to do after finding the root is to reset the rootfinder, by calling ```root_finder->init();```. This allows the rootfinder to find more
roots as time progresses.
Then we make our impact result happen. Here, we want the cannon ball to bounce. So we flip the sign of the vertical velocity (```state[3]```), and keep the sign of the horizontal velocity as-is. In BouncyCannonBall we also make the cannonball lose a little bit of energy, so we multiply our velocity vector by 0.9.
The last difference between CannonBall and BouncyCannonBall is the change in the
duration of the simulation (So the bouncy ball can bounce several times).
So, the line ```while (t <5.1){```ischangedto
```while (t <20.0){```
#### [How to Run The BouncyCannonBall Example](examples/BouncyCannonBall/README.md)
This section demonstrates the ```EulerCromerIntegrator``` class using
the program in [examples/MassSpringDamper](examples/MassSpringDamper/README.md)
The EulerCromer algorithm is not a general-purpose integration algorithm like Runge-Kutta algorithms. It is integration algorithm often used in oscillatory systems like mass-spring-damper systems, and orbital systems because it conserves energy much better than Runge-Kutta.
```struct MassSpringDamper``` specifies the attributes of the [mass-spring-damper](https://en.wikipedia.org/wiki/Mass-spring-damper_model) system we want to simulate.
```struct ImpulseGenerator``` specifies a forcing function for our system, primarily to make
this simulation a little more interesting.
We've seen the ```print_header```, and ```print_state``` functions before. They're for generating CSV output for the simulation.
The ```acceleration``` function generates derivatives for the ```EulerCromerIntegrator```. It's of type [```Derivs2Func```](#typedef-Derivs2Func), a little different from the derivative generator function for Runge-Kutta Integrators.
The first argument (```dt```) specifies the integration step-size. We will be integrating in 0.001 second steps.
The second argument specifies the size of the position, and velocity vectors. So if our system model 3-dimensional, then this would be 3. This simulation is only one-dimensional so it's value is 1.
The third argument, ```x_p``` is a pointer to an array (of length one) of pointers to variables from which we load() and to which we unload() the position vector .
The fourth argument, ```v_p``` is a pointer to an array of pointers to variables from which we load() and to which we unload() the velcity vector.
The fifth argument of the constructor is a pointer to a function that is responsible for generating state derivatives. Its type is as follows:
This section demonstrates using SAIntegrator to evaluate a definite integral. using the program in [examples/DefiniteIntegral](examples/DefiniteIntegral/README.md).
DI.integrator = new SA::RK4Integrator(dx, 1, state, Order3Polynomial, &DI);
double result = DI.evaluate();
printf("Integral = %g.\n", result);
}
```
At the top of [DefiniteIntegral.cpp](#listing-DefiniteIntegral.cpp) , ```struct DefiniteIntegral ``` specifies everything relevant to the task. The ```evaluate``` method evaluates the integral from ```lower_limit``` to ```upper_limit```, and places the result in ```result```. The ```Coeff``` array contains the polynomial coefficients. ```integrator``` points to the SA::Integrator we intend to use.
```Order3Polynomial``` is our derivative function. Note we pass in the ```DefiniteIntegral``` object via ```udata```, so we have access to the coefficients.
```main``` sets up a ```DefiniteIntegral``` object and calls evaluate() the get the answer.
In the [DefiniteIntegral](examples/DefiniteIntegral/README.md) example, we use
```struct DefiniteIntegrator``` to specify everything necessary to evaluate a single definite integral. But, a nested integrator also needs access to the independent variables of the integrators that "enclose" it. So, in the DoubleIntegral example we need to modify ```struct DefiniteIntegrator```. First we expose the independent variable (```ivar```) and keep it updated in the ```evaluate``` method. Then we combine, or "stack" two DefiniteIntegrator's in ```struct IntegContext``` to be passed in user_data, so "inner" integrators have access to "outer" integrator's independent variables.
This section demonstrates the ```RKF45Integrator``` class using
the program in [examples/AsteroidFlyBy](examples/AsteroidFlyBy/README.md).
The RKF45Integrator is an adaptive step-size integrator. It adapts the
integration step-size to maintain a specified accuracy. If a particular step-size
doesn't produce the needed accuracy then the step-size is reduced and the integration step is performed again. If the needed accuracy is being produced then the step-size can be increased. There is some over-head in the extra calculations, that estimate the local-error. But, this can be more than made up for by the fact that the step-size is small **only** when necessary.
The listing below is a simulation of a relatively small asteroid flying past the Earth. As the asteroid approaches, and the acceleration of gravity gets stronger, the ```RKF45Integrator``` gradually reduces the step-size to maintain the required accuracy. As the asteroid retreats, the step-size is gradually increased, back to its normal, maximum value.
The first argument (```epsilon```) is unique to adaptive step-size integration. It specifies the allowable "local error", that is: the error per step. The ```RKF45Integrator``` automatically adjusts the step-size needed to achieve this accuracy. Local error is calculated for each state element. The largest of the element errors guides the step-size adaptation of the algorithm.
The second argument (```dt```) specifies the **maximum** integration step-size. Notice the difference between this, and non-adaptive step size integrators. Here, the actual step size is determined by the Runge-Kutta-Fehlberg algorithm. The method ```getLastStepSize()``` returns this actual step-size. It may be smaller than, but will not be larger than ```dt```.
In this simulation, ```dt``` is 60 seconds, but as the asteroid approaches the planet, and the acceleration of gravity increases, the Runge-Kutta-Fehlberg algorithm gradually reduces the step size down to ~ 3 seconds at closest approach to maintain the specified local accuracy.
The third argument specifies the state-size, in this case: 4.
The fourth argument specifies the list of variables comprising the state: ```flyby.pos[0], flyby.pos[1], flyby.vel[0]), and flyby.vel[1]```.
The fifth argument is a pointer to the derivatives generator function, ```gravity``` of type [(DerivsFunc)](#typedef-DerivsFunc).
The sixth argument is a pointer to the Flyby object.
#### [Running the AsteroidFlyBy Example](examples/AsteroidFlyBy/README.md).
This is the second of four available RK2Integrator constructors. This constructor interface is common to all of the Integrators derived from class ```SA::FirstOrderODEIntegrator```: ```SA::EulerIntegrator```, ```SA::HeunsMethod```, ```SA::RK2Integrator```, ```SA::RK4Integrator```, and ```SA::RK3_8Integrator```.
|N |```int``` |Number of state variables to be integrated|
|in\_out\_vars |```double*```|Array of pointers to the state variables from which we ```load()```, and to which we ```unload()``` the integrator state |
| derivs_func |[```DerivsFunc```](#typedef-DerivsFunc)| Function thats generates the function (the derivatives) to be integrated. |
|user_data |```void*``` | A pointer to user defined data that will be passed to a DerivsFunc when called by the Integrator. |
For more information, check out the SAIntegrator User's Guide, or even ```SAIntegrator.hh```.
This is the third of four available RKF45Integrator constructors.
```C++
RKF45Integrator( double epsilon,
double h,
unsigned int N,
double* in_out_vars[],
DerivsFunc derivs_func,
void* udata);
```
where:
|Parameter |Type |Description|
|-------------|-------------|-----------|
|epsilon |```double``` | Specifies the maximum allowable error per step.|
|h |```double``` | Default integration step-size. This is the maximum allowable step-size. |
|N |```int``` |Number of state variables to be integrated|
|in\_out\_vars |```double*```|Array of pointers to the state variables from which we ```load()```, and to which we ```unload()``` the integrator state |
| derivs_func |[```DerivsFunc```](#typedef-DerivsFunc)| Function thats generates the function (the derivatives) to be integrated. |
|user_data |```void*``` | A pointer to user defined data that will be passed to a DerivsFunc when called by the Integrator. |
For more information, check out the SAIntegrator User's Guide, or even ```SAIntegrator.hh```.