philsupertramp/game-math
Loading...
Searching...
No Matches
odeBDF2.h
Go to the documentation of this file.
1
12#pragma once
13
14#include "../lin_alg/newton.h"
15#include "../utils.h"
16#include "ode.h"
17#include "odeTrapez.h"
18#include <iostream>
19
20
30ODEBDF2(const ODE& fun, const std::vector<double>& tInterval, const Matrix<double>& y0, const ODEOption& option) {
31 size_t tDim = tInterval.size();
32 size_t elem_size = y0.columns();
33 auto h = option.h;
34 auto TOL = option.TOL;
35 auto maxIter = option.maxIter;
36 auto Jac = option.Jac;
37 if(h == 0) { h = (tInterval[tDim - 1] - tInterval[0]) / 1000.0; }
38
39 // % initialize result vectors
40 size_t result_dim = ((tInterval[tDim - 1] - tInterval[0]) / h) + 1;
41 Matrix<double> t(0, result_dim, 1, 1);
42 size_t n = result_dim;
43 auto y = zeros(n, elem_size);
44 Matrix<int> iter(0, n, 1);
45
46 t(0, 0) = tInterval[0];
47 t(1, 0) = t(0, 0) + h;
48
49 auto y1 = ODETrapez(fun, { t(0, 0), t(1, 0) }, y0, option).Y;
50 y.SetRow(0, y1(0));
51 y.SetRow(1, y1(1));
52 auto E = eye(elem_size);
53
54 for(size_t l = 1; l < n - 1; l++) {
55 auto y_act = y(l - 1).Transpose();
56 auto k = 0;
57 auto delta = ones(elem_size);
58
59 while(norm(delta) > TOL && k < maxIter) {
60 auto current_fun = fun(t(l, 0) + h, y_act);
61 auto F =
62 -1.0 * ((-1.0 / 2.0) * y(l - 1).Transpose() + h * current_fun + 2.0 * y(l).Transpose() - 3.0 / 2.0 * y_act);
63 auto J = h * Jac(t(l, 0), y_act) - (3.0 / 2.0) * E;
64 delta = gaussSeidel(J, F);
65 y_act += delta;
66 k += 1;
67 }
68 if(k >= maxIter) { std::cout << "Warning: Max number iterations reached." << std::endl; }
69 iter(l, 0) = k;
70 t(l + 1, 0) = t(l, 0) + h;
71 y.SetRow(l + 1, y_act);
72 }
73 return { y, t, iter };
74}
75
Definition: Matrix.h:42
void SetRow(size_t index, const Matrix< T > &other)
Definition: Matrix.h:541
size_t columns() const
Definition: Matrix.h:198
Matrix< double > gaussSeidel(const Matrix< double > &A, const Matrix< double > &b)
Definition: gaussSeidel.h:29
Matrix< double > eye(size_t rows, size_t columns=0)
double norm(const Matrix< double > &in)
Matrix< double > ones(size_t rows, size_t columns=1, size_t elements=1)
Matrix< double > zeros(size_t rows, size_t columns, size_t elements=1)
ODEResult ODEBDF2(const ODE &fun, const std::vector< double > &tInterval, const Matrix< double > &y0, const ODEOption &option)
Definition: odeBDF2.h:30
ODEResult ODETrapez(const ODE &fun, const std::vector< double > &tInterval, const Matrix< double > &y0, const ODEOption &option)
Definition: odeTrapez.h:28
std::function< Matrix< double >(double, Matrix< double >)> ODE
alias for ODE
Definition: ode.h:17
Definition: ode.h:56
double TOL
tolerance for the algorithm to determine convergence
Definition: ode.h:60
int maxIter
max iterations for integrated newton steps
Definition: ode.h:62
double h
step width of t
Definition: ode.h:58
ODEJac Jac
jacobian matrix of given function
Definition: ode.h:64
Definition: ode.h:25