File: base2ad.cpp

package info (click to toggle)
cppad 2025.00.00.2-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 11,552 kB
  • sloc: cpp: 112,594; sh: 5,972; ansic: 179; python: 71; sed: 12; makefile: 10
file content (269 lines) | stat: -rw-r--r-- 7,492 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later
// SPDX-FileCopyrightText: Bradley M. Bell <bradbell@seanet.com>
// SPDX-FileContributor: 2003-24 Bradley M. Bell
// ----------------------------------------------------------------------------

/*
{xrst_begin base2ad.cpp}
{xrst_spell
  cccc
}

Taylor's Ode Solver: base2ad Example and Test
#############################################

See Also
********
:ref:`taylor_ode.cpp-name` , :ref:`mul_level_ode.cpp-name`

Purpose
*******
This is a realistic example using :ref:`base2ad-name` to create
an ``AD`` < *Base* > function from an *Base* function.
The function represents an ordinary differential equation.
It is differentiated with respect to
its :ref:`variables<glossary@Variable>` .
These derivatives are used by the :ref:`taylor_ode-name` method.
This solution is then differentiated with respect to
the functions :ref:`dynamic parameters<glossary@Parameter@Dynamic>` .

ODE
***
For this example the function
:math:`y : \B{R} \times \B{R}^n \rightarrow \B{R}^n` is defined by
:math:`y(0, x) = 0` and
:math:`\partial_t y(t, x) = g(y, x)` where
:math:`g : \B{R}^n \times \B{R}^n \rightarrow \B{R}^n` is defined by

.. math::

   g(y, x) =
   \left( \begin{array}{c}
         x_0     \\
         x_1 y_0 \\
         \vdots  \\
         x_{n-1} y_{n-2}
   \end{array} \right)

ODE Solution
************
The solution for this example can be calculated by
starting with the first row and then using the solution
for the first row to solve the second and so on.
Doing this we obtain

.. math::

   y(t, x ) =
   \left( \begin{array}{c}
      x_0 t                  \\
      x_1 x_0 t^2 / 2        \\
      \vdots                 \\
      x_{n-1} x_{n-2} \ldots x_0 t^n / n !
   \end{array} \right)

Derivative of ODE Solution
**************************
Differentiating the solution above,
with respect to the parameter vector :math:`x`,
we notice that

.. math::

   \partial_x y(t, x ) =
   \left( \begin{array}{cccc}
   y_0 (t,x) / x_0      & 0                   & \cdots & 0      \\
   y_1 (t,x) / x_0      & y_1 (t,x) / x_1     & 0      & \vdots \\
   \vdots               & \vdots              & \ddots & 0      \\
   y_{n-1} (t,x) / x_0  & y_{n-1} (t,x) / x_1 & \cdots & y_{n-1} (t,x) / x_{n-1}
   \end{array} \right)

Taylor's Method Using AD
************************
We define the function :math:`z(t, x)` by the equation

.. math::

   z ( t , x ) = g[ y ( t , x ), x ]

see :ref:`taylor_ode-name` for the method used to compute the
Taylor coefficients w.r.t :math:`t` of :math:`y(t, x)`.

Source
******
{xrst_literal
   // BEGIN C++
   // END C++
}

{xrst_end base2ad.cpp}
--------------------------------------------------------------------------
*/
// BEGIN C++

# include <cppad/cppad.hpp>

// =========================================================================
namespace { // BEGIN empty namespace

typedef CppAD::AD<double>                  a_double;

typedef CPPAD_TESTVECTOR(double)           d_vector;
typedef CPPAD_TESTVECTOR(a_double)         a_vector;

typedef CppAD::ADFun<double>               fun_double;
typedef CppAD::ADFun<a_double, double>     afun_double;

// -------------------------------------------------------------------------
// class definition for C++ function object that defines ODE
class Ode {
private:
   // copy of x that is set by constructor and used by g(y)
   a_vector x_;
public:
   // constructor
   Ode(const a_vector& x) : x_(x)
   { }
   // the function g(y) given the parameter vector x
   a_vector operator() (const a_vector& y) const
   {  size_t n = y.size();
      a_vector g(n);
      g[0] = x_[0];
      for(size_t i = 1; i < n; i++)
         g[i] = x_[i] * y[i-1];
      //
      return g;
   }
};

// -------------------------------------------------------------------------
// Routine that uses Taylor's method to solve ordinary differential equaitons
a_vector taylor_ode(
   afun_double&     fun_g   ,  // function that defines the ODE
   size_t           order   ,  // order of Taylor's method used
   size_t           nstep   ,  // number of steps to take
   const a_double&  dt      ,  // Delta t for each step
   const a_vector&  y_ini)     // y(t) at the initial time
{
   // number of variables in the ODE
   size_t n = y_ini.size();

   // initialize y
   a_vector y = y_ini;

   // loop with respect to each step of Taylors method
   for(size_t s = 0; s < nstep; s++)
   {
      // initialize
      a_vector y_k   = y;
      a_double dt_k  = a_double(1.0);
      a_vector next  = y;

      for(size_t k = 0; k < order; k++)
      {
         // evaluate k-th order Taylor coefficient z^{(k)} (t)
         a_vector z_k = fun_g.Forward(k, y_k);

         // dt^{k+1}
         dt_k *= dt;

         // y^{(k+1)}
         for(size_t i = 0; i < n; i++)
         {  // y^{(k+1)}
            y_k[i] = z_k[i] / a_double(k + 1);

            // add term for k+1 Taylor coefficient
            // to solution for next y
            next[i] += y_k[i] * dt_k;
         }
      }

      // take step
      y = next;
   }
   return y;
}
} // END empty namespace

// ==========================================================================
// Routine that tests alogirhtmic differentiation of solutions computed
// by the routine taylor_ode.
bool base2ad(void)
{  bool ok = true;
   double eps = 100. * std::numeric_limits<double>::epsilon();

   // number of components in differential equation
   size_t n = 4;

   // record function g(y, x)
   // with y as the independent variables and x as dynamic parameters
   a_vector  ay(n), ax(n);
   for(size_t i = 0; i < n; i++)
      ay[i] = ax[i] = double(i + 1);
   CppAD::Independent(ay, ax);

   // fun_g
   Ode G(ax);
   a_vector ag = G(ay);
   fun_double fun_g(ay, ag);


   // afun_g
   afun_double afun_g( fun_g.base2ad() ); // differential equation

   // other arguments to taylor_ode
   size_t   order = n;       // order of Taylor's method used
   size_t   nstep = 2;       // number of steps to take
   a_double adt   = 1.;      // Delta t for each step
   a_vector ay_ini(n);       // initial value of y
   for(size_t i = 0; i < n; i++)
      ay_ini[i] = 0.;

   // declare x as independent variables
   CppAD::Independent(ax);

   // the independent variables if this function are
   // the dynamic parameters in afun_g
   afun_g.new_dynamic(ax);

   // integrate the differential equation
   a_vector ay_final;
   ay_final = taylor_ode(afun_g, order, nstep, adt, ay_ini);

   // define differentiable function object f(x) = y_final(x)
   // that computes its derivatives in double
   CppAD::ADFun<double> fun_f(ax, ay_final);

   // double version of ax
   d_vector x(n);
   for(size_t i = 0; i < n; i++)
      x[i] = Value( ax[i] );

   // check function values
   double check = 1.;
   double t     = double(nstep) * Value(adt);
   for(size_t i = 0; i < n; i++)
   {  check *= x[i] * t / double(i + 1);
      ok &= CppAD::NearEqual(Value(ay_final[i]), check, eps, eps);
   }

   // There appears to be a bug in g++ version 4.4.2 because it generates
   // a warning for the equivalent form
   // d_vector jac = fun_f.Jacobian(x);
   d_vector jac ( fun_f.Jacobian(x) );

   // check Jacobian
   for(size_t i = 0; i < n; i++)
   {  for(size_t j = 0; j < n; j++)
      {  double jac_ij = jac[i * n + j];
         if( i < j )
            check = 0.;
         else
            check = Value( ay_final[i] ) / x[j];
         ok &= CppAD::NearEqual(jac_ij, check, eps, eps);
      }
   }
   return ok;
}

// END C++