TMB Documentation  v1.9.11
romberg.hpp
Go to the documentation of this file.
1 // Copyright (C) 2013-2015 Kasper Kristensen
2 // License: GPL-2
3 
15 namespace romberg {
51  template<class Type, class F>
52  Type integrate(F f, Type a, Type b, int n = 7, int p = 2){
53  Type e;
54  return CppAD::RombergOne(f, a, b, n, p, e);
55  }
56 
57  /* Construct 1D slice of vector function */
58  template<class Type, class F>
59  struct slicefun{
60  F* f;
61  vector<Type> x;
62  int slice;
63  slicefun(F* f_, vector<Type> x_, int slice_) {
64  f=f_; x=x_; slice=slice_;
65  }
66  Type operator()(Type y){
67  x(slice) = y;
68  return f->operator()(x);
69  }
70  };
71 
72  /* integrate along i'th slice, f vector function */
73  template<class Type, class F>
74  Type integrate_slice(F &f, vector<Type> x, int i, Type a, Type b, int n=7, int p=2){
75  return integrate(slicefun<Type, F>(&f, x, i), a, b, n, p);
76  }
77 
78  template<class Type>
79  struct multivariate_integrand{
80  virtual Type operator()(vector<Type>) = 0;
81  };
82 
83  template<class Type>
84  struct integratelast : multivariate_integrand<Type>{
85  slicefun<Type,multivariate_integrand<Type> >* fslice;
86  int n, p;
87  Type a, b;
88  integratelast(multivariate_integrand<Type> &f, int dim, Type a_, Type b_, int n_ = 7, int p_ = 2){
89  int slice = dim - 1;
90  vector<Type> x(dim);
91  fslice = new slicefun<Type,multivariate_integrand<Type> >(&f, x, slice);
92  n=n_; p=p_;
93  a=a_; b=b_;
94  }
95  ~integratelast(){delete fslice;}
96  Type operator()(vector<Type> y){
97  for(int i=0; i < y.size(); i++) fslice->x[i] = y[i];
98  return integrate(*fslice, a, b, n, p);
99  }
100  };
101 
102  template<class Type>
103  Type integrate_multi(multivariate_integrand<Type> &f, vector<Type> a, vector<Type> b, int n = 7, int p = 2){
104  int dim = a.size();
105  integratelast<Type> ffirst(f, dim, a(dim - 1), b(dim - 1), n, p);
106  if(dim == 1){
107  vector<Type> y(0);
108  return ffirst(y);
109  } else {
110  vector<Type> afirst = a.segment(0, dim - 1);
111  vector<Type> bfirst = b.segment(0, dim - 1);
112  return integrate_multi(ffirst, afirst, bfirst, n, p);
113  }
114  }
115 
153  template<class Type, class F>
154  Type integrate(F f, vector<Type> a, vector<Type> b, int n=7, int p=2){
155  // Wrap f in container
156  struct integrand : multivariate_integrand<Type>{
157  F f;
158  integrand(F f_) : f(f_) {}
159  Type operator()(vector<Type> x){
160  return f(x);
161  }
162  };
163  integrand f_cpy(f);
164  return integrate_multi(f_cpy, a, b, n, p);
165  }
166 }
Vector class used by TMB.
Definition: vector.hpp:17
Type integrate(F f, Type a, Type b, int n=7, int p=2)
1D numerical integration using Romberg&#39;s method.
Definition: romberg.hpp:52
Univariate and multivariate numerical integration.
Definition: romberg.hpp:15
License: GPL v2