macropod macropod - 4 months ago 26
C++ Question

How to incorporate time-varying parameters from lookup table into boost::odeint, c++

I am trying to numerically integrate a nonlinear system using boost::odeint. The system has time-varying parameters that are generated externally, and I want to incorporate this into my program. Is this possible with odeint? In Matlab, if you were to do something similar, you would need to interpolate the values as they become available.

Thank you in advance for your help!

Answer

You can solve nonlinear time-varying system easily with odeint. The following example of a nonlinear time-varying system is taken from Applied Nonlinear Control by Slotine

enter image description here

Let u = 6sint, now we can insert this time-varying parameter in ode(), therefore, this is my code for solving the system.

#include <iostream>
#include <boost/math/constants/constants.hpp>
#include <boost/numeric/odeint.hpp>
#include <fstream>

std::ofstream data("data.txt");

using namespace boost::numeric::odeint;

typedef std::vector< double > state_type;

class System
{
public:
    System(const double& deltaT);
    void updateSystem();
    void updateODE();
private:
    double u, t, dt;
    runge_kutta_dopri5 < state_type > stepper;
    state_type y;
    void ode(const state_type &y, state_type &dy, double t);
};

System::System(const double& deltaT) :  u(0.0), dt(deltaT), t(0.0), y(2)
{
    /*
       x = y[0]
      dx = y[1] = dy[0]
     ddx        = dy[1] = ode equation
     */

    // initial values
    y[0] = 2.0;  //  x1 
    y[1] = 0.0;  //  x2
}

void System::updateODE()
{
    // store data for plotting  
    data << t << " " << y[0] << std::endl;

    //=========================================================================
    using namespace std::placeholders;
    stepper.do_step(std::bind(&System::ode, this, _1, _2, _3), y, t, dt);
    t += dt;
}

void System::updateSystem()
{
    // time-varying parameter. 
    u = 6.0*sin(t);
}

void System::ode(const state_type &y, state_type &dy, double t)
{
    //#####################( ODE Equation )################################
    dy[0] = y[1];
    dy[1] = u - 0.1*y[1] - pow(y[0],5); 
}

int main(int argc, char **argv)
{
    const double dt(0.001); 
    System sys(dt);

    for (double t(0.0); t <= 50.0; t += dt){
        // update time-varying parameters of the system 
        sys.updateSystem();
        // solve the ODE one step forward. 
        sys.updateODE();
    }

    return 0;
}

The result is (i.e. same result presented in the aforementioned book).

enter image description here