casacore
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
AutoDiff.h
Go to the documentation of this file.
1 //# AutoDiff.h: An automatic differentiating class for functions
2 //# Copyright (C) 1995,1998,1999,2001,2002
3 //# Associated Universities, Inc. Washington DC, USA.
4 //#
5 //# This library is free software; you can redistribute it and/or modify it
6 //# under the terms of the GNU Library General Public License as published by
7 //# the Free Software Foundation; either version 2 of the License, or (at your
8 //# option) any later version.
9 //#
10 //# This library is distributed in the hope that it will be useful, but WITHOUT
11 //# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 //# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public
13 //# License for more details.
14 //#
15 //# You should have received a copy of the GNU Library General Public License
16 //# along with this library; if not, write to the Free Software Foundation,
17 //# Inc., 675 Massachusetts Ave, Cambridge, MA 02139, USA.
18 //#
19 //# Correspondence concerning AIPS++ should be addressed as follows:
20 //# Internet email: aips2-request@nrao.edu.
21 //# Postal address: AIPS++ Project Office
22 //# National Radio Astronomy Observatory
23 //# 520 Edgemont Road
24 //# Charlottesville, VA 22903-2475 USA
25 //#
26 //#
27 //# $Id$
28 
29 #ifndef SCIMATH_AUTODIFF_H
30 #define SCIMATH_AUTODIFF_H
31 
32 //# Includes
33 #include <casacore/casa/aips.h>
35 
36 namespace casacore { //# NAMESPACE CASACORE - BEGIN
37 
38 // <summary>
39 // Class that computes partial derivatives by automatic differentiation.
40 // </summary>
41 //
42 // <use visibility=export>
43 //
44 // <reviewed reviewer="UNKNOWN" date="before2004/08/25" tests="tAutoDiff.cc" demos="dAutoDiff.cc">
45 // </reviewed>
46 //
47 // <prerequisite>
48 // <li>
49 // </prerequisite>
50 //
51 // <etymology>
52 // Class that computes partial derivatives by automatic differentiation, thus
53 // AutoDiff.
54 // </etymology>
55 //
56 // <synopsis>
57 // Class that computes partial derivatives by automatic differentiation.
58 // It does this by storing the value of a function and the values of its first
59 // derivatives with respect to its independent parameters. When a mathematical
60 // operation is applied to an AutoDiff object, the derivative values of the
61 // resulting new object are computed according to chain rules
62 // of differentiation.
63 //
64 // Suppose we have a function f(x0,x1,...,xn) and its differential is
65 // <srcblock>
66 // df = (df/dx0)*dx0 + (df/dx1)*dx1 + ... + (df/dxn)*dxn
67 // </srcblock>
68 // We can build a class that has the value of the function,
69 // f(x0,x1,...,xn), and the values of the derivatives, (df/dx0), (df/dx1),
70 // ..., (df/dxn) at (x0,x1,...,xn), as class members.
71 //
72 // Now if we have another function, g(x0,x1,...,xn) and its differential is
73 // dg = (dg/dx0)*dx0 + (dg/dx1)*dx1 + ... + (dg/dxn)*dxn,
74 // since
75 // <srcblock>
76 // d(f+g) = df + dg,
77 // d(f*g) = g*df + f*dg,
78 // d(f/g) = df/g - fdg/g^2,
79 // dsin(f) = cos(f)df,
80 // ...,
81 // </srcblock>
82 // we can calculate
83 // <srcblock>
84 // d(f+g), d(f*g), ...,
85 // </srcblock> based on our information on
86 // <srcblock>
87 // df/dx0, df/dx1, ..., dg/dx0, dg/dx1, ..., dg/dxn.
88 // </srcblock>
89 // All we need to do is to define the operators and derivatives of common
90 // mathematical functions.
91 //
92 // To be able to use the class as an automatic differentiator of a function
93 // object, we need a templated function object, i.e. an object with:
94 // <ul>
95 // <li> a <src> template <class T> T operator()(const T)</src>
96 // <li> or multiple variable input like:
97 // <src> template <class T> T operator()(const Vector<T> &)</src>
98 // <li> all variables and constants used in the calculation of the function
99 // value should have been typed with T
100 // </ul>
101 // A simple example of such a function object could be:
102 // <srcblock>
103 // template <class T> f {
104 // public:
105 // T operator()(const T &x, const T &a, const T &b) {
106 // return a*b*x; }
107 // };
108 // // Instantiate the following versions:
109 // template class f<Double>;
110 // template class f<AutoDiff<Double> >;
111 // </srcblock>
112 // A call with values will produce the function value:
113 // <srcblock>
114 // cout << f(7.0, 2.0, 3.0) << endl;
115 // // will produce the value at x=7 for a=2; b=3:
116 // 42
117 // // But a call indicating that we want derivatives to a and b:
118 // cout << f(AutoDiff<Double>(7.0), AutoDiff<Double>(2.0, 2, 0),
119 // AutoDiff<Double>(3.0, 2, 1)) << endl;
120 // // will produce the value at x=7 for a=2; b=3:
121 // // and the partial derivatives wrt a and b at x=7:
122 // (42, [21, 14])
123 // // The following will calculate the derivate wrt x:
124 // cout << f(AutoDiff<Double>(7.0, 1, 0), AutoDiff<Double>(2.0),
125 // AutoDiff<Double>(3.0)) << endl;
126 // (42,[6])
127 // </srcblock>
128 // In actual practice, there are a few rules to obey for the structure of
129 // the function object if you want to use the function object and its
130 // derivatives in least squares fitting procedures in the Fitting
131 // module. The major one is to view the function object having 'fixed' and
132 // 'variable' parameters. I.e., rather than viewing the function as
133 // depending on parameters <em>a, b, x</em> (<src>f(a,b,x)</src>), the
134 // function is considered to be <src>f(x; a,b)</src>, where <em>a, b</em>
135 // are 'fixed' parameters, and <em>x</em> a variable parameter.
136 // Fixed parameters should be contained in a
137 // <linkto class=FunctionParam>FunctionParam</linkto> container object;
138 // while the variable parameter(s) are given in the function
139 // <src>operator()</src>. See <linkto class=Function>Function</linkto> class
140 // for details.
141 //
142 // A Gaussian spectral profile would in general have the center frequency,
143 // the width and the amplitude as fixed parameters, and the frequency as
144 // a variable. Given a spectrum, you would solve for the fixed parameters,
145 // given spectrum values. However, in other cases the role of the
146 // parameters could be reversed. An example could be a whole stack of
147 // observed (in the laboratory) spectra at different temperatures at
148 // one frequency. In that case the width would be the variable parameter,
149 // and the frequency one of the fixed (and to be solved for)parameters.
150 //
151 // Since the calculation of the derivatives is done with simple overloading,
152 // the calculation of second (and higher) derivatives is easy. It should be
153 // noted that higher deivatives are inefficient in the current incarnation
154 // (there is no knowledge e.g. about symmetry in the Jacobian). However,
155 // it is a very good way to get the correct answers of the derivatives. In
156 // practice actual production code will be better off with specialization
157 // of the <src>f<AutoDiff<> ></src> implementation.
158 //
159 // The <src>AutoDiff</src> class is the class the user communicates with.
160 // Alias classes (<linkto class=AutoDiffA>AutoDiffA</linkto> and
161 // <linkto class=AutoDiffA>AutoDiffX</linkto>) exists
162 // to make it possible to have different incarnations of a templated
163 // method (e.g. a generic one and a specialized one). See the
164 // <src>dAutoDiff</src> demo for an example of its use.
165 //
166 // All operators and functions are declared in <linkto file=AutoDiffMath.h>
167 // AutoDiffMath</linkto>. The output operator in
168 // <linkto file=AutoDiffIO.h>AutoDiffIO</linkto>.
169 // </synopsis>
170 //
171 // <example>
172 // <srcblock>
173 // // First a simple example.
174 // // We have a function of the form f(x,y,z); and want to know the
175 // // value of the function for x=10; y=20; z=30; and for
176 // // the derivatives at those point.
177 // // Specify the values; and indicate 3 derivatives:
178 // AutoDiff<Double> x(10.0, 3, 0);
179 // AutoDiff<Double> y(20.0, 3, 1);
180 // AutoDiff<Double> z(30.0, 3, 2);
181 // // The result will be:
182 // AutoDiff<Double> result = x*y + sin(z);
183 // cout << result.value() << endl;
184 // // 199.012
185 // cout << result.derivatives() << endl;
186 // // [20, 10, 0.154251]
187 // // Note: sin(30) = -0.988; cos(30) = 0.154251;
188 // </srcblock>
189 //
190 // See for an extensive example the demo program dAutoDiff. It is
191 // based on the example given above, and shows also the use of second
192 // derivatives (which is just using <src>AutoDiff<AutoDiff<Double> ></src>
193 // as template argument).
194 // <srcblock>
195 // // The function, with fixed parameters a,b:
196 // template <class T> class f {
197 // public:
198 // T operator()(const T& x) { return a_p*a_p*a_p*b_p*b_p*x; }
199 // void set(const T& a, const T& b) { a_p = a; b_p = b; }
200 // private:
201 // T a_p;
202 // T b_p;
203 // };
204 // // Call it with different template arguments:
205 // Double a0(2), b0(3), x0(7);
206 // f<Double> f0; f0.set(a0, b0);
207 // cout << "Value: " << f0(x0) << endl;
208 //
209 // AutoDiff<Double> a1(2,2,0), b1(3,2,1), x1(7);
210 // f<AutoDiff<Double> > f1; f1.set(a1, b1);
211 // cout << "Diff a,b: " << f1(x1) << endl;
212 //
213 // AutoDiff<Double> a2(2), b2(3), x2(7,1,0);
214 // f<AutoDiff<Double> > f2; f2.set(a2, b2);
215 // cout << "Diff x: " << f2(x2) << endl;
216 //
217 // AutoDiff<AutoDiff<Double> > a3(AutoDiff<Double>(2,2,0),2,0),
218 // b3(AutoDiff<Double>(3,2,1),2,1), x3(AutoDiff<Double>(7),2);
219 // f<AutoDiff<AutoDiff<Double> > > f3; f3.set(a3, b3);
220 // cout << "Diff2 a,b: " << f3(x3) << endl;
221 //
222 // AutoDiff<AutoDiff<Double> > a4(AutoDiff<Double>(2),1),
223 // b4(AutoDiff<Double>(3),1),
224 // x4(AutoDiff<Double>(7,1,0),1,0);
225 // f<AutoDiff<AutoDiff<Double> > > f4; f4.set(a4, b4);
226 // cout << "Diff2 x: " << f4(x4) << endl;
227 //
228 // // Result will be:
229 // // Value: 504
230 // // Diff a,b: (504, [756, 336])
231 // // Diff x: (504, [72])
232 // // Diff2 a,b: ((504, [756, 336]), [(756, [756, 504]), (336, [504, 112])])
233 // // Diff2 x: ((504, [72]), [(72, [0])])
234 //
235 // // It needed the template instantiations definitions:
236 // template class f<Double>;
237 // template class f<AutoDiff<Double> >;
238 // template class f<AutoDiff<AutoDiff<Double> > >;
239 // </srcblock>
240 // </example>
241 //
242 // <motivation>
243 // The creation of the class was motivated by least-squares non-linear fit where
244 // partial derivatives of a fitted function are needed. It would be tedious
245 // to create functionals for all partial derivatives of a function.
246 // </motivation>
247 //
248 // <templating arg=T>
249 // <li> any class that has the standard mathematical and comparisons
250 // defined
251 // </templating>
252 //
253 // <todo asof="2001/06/07">
254 // <li> Nothing I know
255 // </todo>
256 
257 template <class T> class AutoDiff {
258  public:
259  //# Typedefs
260  typedef T value_type;
262  typedef const value_type& const_reference;
264  typedef const value_type* const_iterator;
265 
266  //# Constructors
267  // Construct a constant with a value of zero. Zero derivatives.
268  AutoDiff();
269 
270  // Construct a constant with a value of v. Zero derivatives.
271  AutoDiff(const T &v);
272 
273  // A function f(x0,x1,...,xn,...) with a value of v. The
274  // total number of derivatives is ndiffs, the nth derivative is one, and all
275  // others are zero.
276  AutoDiff(const T &v, const uInt ndiffs, const uInt n);
277 
278  // A function f(x0,x1,...,xn,...) with a value of v. The
279  // total number of derivatives is ndiffs.
280  // All derivatives are zero.
281  AutoDiff(const T &v, const uInt ndiffs);
282 
283  // Construct one from another
284  AutoDiff(const AutoDiff<T> &other);
285 
286  // Construct a function f(x0,x1,...,xn) of a value v and a vector of
287  // derivatives derivs(0) = df/dx0, derivs(1) = df/dx1, ...
288  AutoDiff(const T &v, const Vector<T> &derivs);
289 
290  ~AutoDiff();
291 
292  // Assignment operator. Assign a constant to variable. All derivatives
293  // are zero.
294  AutoDiff<T> &operator=(const T &v);
295 
296  // Assign one to another.
297  AutoDiff<T> &operator=(const AutoDiff<T> &other);
298 
299  // In-place mathematical operators
300  // <group>
301  void operator*=(const AutoDiff<T> &other);
302  void operator/=(const AutoDiff<T> &other);
303  void operator+=(const AutoDiff<T> &other);
304  void operator-=(const AutoDiff<T> &other);
305  void operator*=(const T other);
306  void operator/=(const T other);
307  void operator+=(const T other);
308  void operator-=(const T other);
309  // </group>
310 
311  // Returns the value of the function
312  // <group>
313  T &value() { return val_p; }
314  const T &value() const { return val_p; }
315  // </group>
316 
317  // Returns a vector of the derivatives of an AutoDiff
318  // <group>
319  const Vector<T>& derivatives() const {return grad_p; }
321  void derivatives(Vector<T> &res) const;
322  // </group>
323 
324  // Returns a specific derivative. The second set does not check for
325  // a valid which; the first set does through Vector addressing.
326  // <group>
327  T &derivative(uInt which) { return grad_p(which); }
328  const T &derivative(uInt which) const { return grad_p(which); }
329  T &deriv(uInt which) { return grad_p[which]; }
330  const T &deriv(uInt which) const { return grad_p[which]; }
331  // </group>
332 
333  // Return total number of derivatives
334  uInt nDerivatives() const { return nd_p; }
335 
336  // Is it a constant, i.e., with zero derivatives?
337  Bool isConstant() const { return nd_p == 0; }
338 
339  private:
340  //# Data
341  // The function value
342  T val_p;
343  // The number of derivatives
345  // The derivatives
347 };
348 
349 
350 } //# NAMESPACE CASACORE - END
351 
352 #ifndef CASACORE_NO_AUTO_TEMPLATES
353 #include <casacore/scimath/Mathematics/AutoDiff.tcc>
354 #endif //# CASACORE_NO_AUTO_TEMPLATES
355 #endif
const Vector< T > & derivatives() const
Returns a vector of the derivatives of an AutoDiff.
Definition: AutoDiff.h:319
uInt nd_p
The number of derivatives.
Definition: AutoDiff.h:344
AutoDiff()
Construct a constant with a value of zero.
value_type * iterator
Definition: AutoDiff.h:263
const T & value() const
Definition: AutoDiff.h:314
Vector< T > grad_p
The derivatives.
Definition: AutoDiff.h:346
uInt nDerivatives() const
Return total number of derivatives.
Definition: AutoDiff.h:334
const T & deriv(uInt which) const
Definition: AutoDiff.h:330
bool Bool
Define the standard types used by Casacore.
Definition: aipstype.h:42
Class that computes partial derivatives by automatic differentiation.
Definition: AutoDiff.h:257
value_type & reference
Definition: AutoDiff.h:261
const T & derivative(uInt which) const
Definition: AutoDiff.h:328
T val_p
The function value.
Definition: AutoDiff.h:342
void operator/=(const AutoDiff< T > &other)
T & deriv(uInt which)
Definition: AutoDiff.h:329
Bool isConstant() const
Is it a constant, i.e., with zero derivatives?
Definition: AutoDiff.h:337
void operator-=(const AutoDiff< T > &other)
const value_type * const_iterator
Definition: AutoDiff.h:264
Vector< T > & derivatives()
Definition: AutoDiff.h:320
void operator*=(const AutoDiff< T > &other)
In-place mathematical operators.
T & value()
Returns the value of the function.
Definition: AutoDiff.h:313
void operator+=(const AutoDiff< T > &other)
T & derivative(uInt which)
Returns a specific derivative.
Definition: AutoDiff.h:327
unsigned int uInt
Definition: aipstype.h:51
AutoDiff< T > & operator=(const T &v)
Assignment operator.
const value_type & const_reference
Definition: AutoDiff.h:262