casacore
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>
34 #include <casacore/casa/Arrays/Vector.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>. The actual structure of the
169 // data block used by <src>AutoDiff</src> is described in
170 // <linkto class=AutoDiffRep>AutoDiffRep</linkto>.
171 // </synopsis>
172 //
173 // <example>
174 // <srcblock>
175 // // First a simple example.
176 // // We have a function of the form f(x,y,z); and want to know the
177 // // value of the function for x=10; y=20; z=30; and for
178 // // the derivatives at those point.
179 // // Specify the values; and indicate 3 derivatives:
180 // AutoDiff<Double> x(10.0, 3, 0);
181 // AutoDiff<Double> y(20.0, 3, 1);
182 // AutoDiff<Double> z(30.0, 3, 2);
183 // // The result will be:
184 // AutoDiff<Double> result = x*y + sin(z);
185 // cout << result.value() << endl;
186 // // 199.012
187 // cout << result.derivatives() << endl;
188 // // [20, 10, 0.154251]
189 // // Note: sin(30) = -0.988; cos(30) = 0.154251;
190 // </srcblock>
191 //
192 // See for an extensive example the demo program dAutoDiff. It is
193 // based on the example given above, and shows also the use of second
194 // derivatives (which is just using <src>AutoDiff<AutoDiff<Double> ></src>
195 // as template argument).
196 // <srcblock>
197 // // The function, with fixed parameters a,b:
198 // template <class T> class f {
199 // public:
200 // T operator()(const T& x) { return a_p*a_p*a_p*b_p*b_p*x; }
201 // void set(const T& a, const T& b) { a_p = a; b_p = b; }
202 // private:
203 // T a_p;
204 // T b_p;
205 // };
206 // // Call it with different template arguments:
207 // Double a0(2), b0(3), x0(7);
208 // f<Double> f0; f0.set(a0, b0);
209 // cout << "Value: " << f0(x0) << endl;
210 //
211 // AutoDiff<Double> a1(2,2,0), b1(3,2,1), x1(7);
212 // f<AutoDiff<Double> > f1; f1.set(a1, b1);
213 // cout << "Diff a,b: " << f1(x1) << endl;
214 //
215 // AutoDiff<Double> a2(2), b2(3), x2(7,1,0);
216 // f<AutoDiff<Double> > f2; f2.set(a2, b2);
217 // cout << "Diff x: " << f2(x2) << endl;
218 //
219 // AutoDiff<AutoDiff<Double> > a3(AutoDiff<Double>(2,2,0),2,0),
220 // b3(AutoDiff<Double>(3,2,1),2,1), x3(AutoDiff<Double>(7),2);
221 // f<AutoDiff<AutoDiff<Double> > > f3; f3.set(a3, b3);
222 // cout << "Diff2 a,b: " << f3(x3) << endl;
223 //
224 // AutoDiff<AutoDiff<Double> > a4(AutoDiff<Double>(2),1),
225 // b4(AutoDiff<Double>(3),1),
226 // x4(AutoDiff<Double>(7,1,0),1,0);
227 // f<AutoDiff<AutoDiff<Double> > > f4; f4.set(a4, b4);
228 // cout << "Diff2 x: " << f4(x4) << endl;
229 //
230 // // Result will be:
231 // // Value: 504
232 // // Diff a,b: (504, [756, 336])
233 // // Diff x: (504, [72])
234 // // Diff2 a,b: ((504, [756, 336]), [(756, [756, 504]), (336, [504, 112])])
235 // // Diff2 x: ((504, [72]), [(72, [0])])
236 //
237 // // It needed the template instantiations definitions:
238 // template class f<Double>;
239 // template class f<AutoDiff<Double> >;
240 // template class f<AutoDiff<AutoDiff<Double> > >;
241 // </srcblock>
242 // </example>
243 //
244 // <motivation>
245 // The creation of the class was motivated by least-squares non-linear fit where
246 // partial derivatives of a fitted function are needed. It would be tedious
247 // to create functionals for all partial derivatives of a function.
248 // </motivation>
249 //
250 // <templating arg=T>
251 // <li> any class that has the standard mathematical and comparisons
252 // defined
253 // </templating>
254 //
255 // <todo asof="2001/06/07">
256 // <li> Nothing I know
257 // </todo>
258 
259 template <class T> class AutoDiff {
260  public:
261  //# Typedefs
262  typedef T value_type;
263  typedef value_type& reference;
264  typedef const value_type& const_reference;
265  typedef value_type* iterator;
266  typedef const value_type* const_iterator;
267 
268  //# Constructors
269  // Construct a constant with a value of zero. Zero derivatives.
270  AutoDiff();
271 
272  // Construct a constant with a value of v. Zero derivatives.
273  AutoDiff(const T &v);
274 
275  // A function f(x0,x1,...,xn,...) with a value of v. The
276  // total number of derivatives is ndiffs, the nth derivative is one, and all
277  // others are zero.
278  AutoDiff(const T &v, const uInt ndiffs, const uInt n);
279 
280  // A function f(x0,x1,...,xn,...) with a value of v. The
281  // total number of derivatives is ndiffs.
282  // All derivatives are zero.
283  AutoDiff(const T &v, const uInt ndiffs);
284 
285  // Construct one from another
286  AutoDiff(const AutoDiff<T> &other);
287 
288  // Construct a function f(x0,x1,...,xn) of a value v and a vector of
289  // derivatives derivs(0) = df/dx0, derivs(1) = df/dx1, ...
290  AutoDiff(const T &v, const Vector<T> &derivs);
291 
292  ~AutoDiff();
293 
294  // Assignment operator. Assign a constant to variable. All derivatives
295  // are zero.
296  AutoDiff<T> &operator=(const T &v);
297 
298  // Assign one to another.
299  AutoDiff<T> &operator=(const AutoDiff<T> &other);
300 
301  // In-place mathematical operators
302  // <group>
303  void operator*=(const AutoDiff<T> &other);
304  void operator/=(const AutoDiff<T> &other);
305  void operator+=(const AutoDiff<T> &other);
306  void operator-=(const AutoDiff<T> &other);
307  void operator*=(const T other);
308  void operator/=(const T other);
309  void operator+=(const T other);
310  void operator-=(const T other);
311  // </group>
312 
313  // Returns the value of the function
314  // <group>
315  T &value() { return val_p; }
316  const T &value() const { return val_p; }
317  // </group>
318 
319  // Returns a vector of the derivatives of an AutoDiff
320  // <group>
321  const Vector<T>& derivatives() const {return grad_p; }
323  void derivatives(Vector<T> &res) const;
324  // </group>
325 
326  // Returns a specific derivative. The second set does not check for
327  // a valid which; the first set does through Vector addressing.
328  // <group>
329  T &derivative(uInt which) { return grad_p(which); }
330  const T &derivative(uInt which) const { return grad_p(which); }
331  T &deriv(uInt which) { return grad_p[which]; }
332  const T &deriv(uInt which) const { return grad_p[which]; }
333  // </group>
334 
335  // Return total number of derivatives
336  uInt nDerivatives() const { return nd_p; }
337 
338  // Is it a constant, i.e., with zero derivatives?
339  Bool isConstant() const { return nd_p == 0; }
340 
341  private:
342  //# Data
343  // The function value
344  T val_p;
345  // The number of derivatives
347  // The derivatives
349 };
350 
351 
352 } //# NAMESPACE CASACORE - END
353 
354 #ifndef CASACORE_NO_AUTO_TEMPLATES
355 #include <casacore/scimath/Mathematics/AutoDiff.tcc>
356 #endif //# CASACORE_NO_AUTO_TEMPLATES
357 #endif
A 1-D Specialization of the Array class.
Definition: ArrayIO.h:45
uInt nd_p
The number of derivatives.
Definition: AutoDiff.h:346
const T & value() const
Definition: AutoDiff.h:316
AutoDiff()
Construct a constant with a value of zero.
value_type * iterator
Definition: AutoDiff.h:265
Vector< T > grad_p
The derivatives.
Definition: AutoDiff.h:348
const Vector< T > & derivatives() const
Returns a vector of the derivatives of an AutoDiff.
Definition: AutoDiff.h:321
uInt nDerivatives() const
Return total number of derivatives.
Definition: AutoDiff.h:336
const T & deriv(uInt which) const
Definition: AutoDiff.h:332
const T & derivative(uInt which) const
Definition: AutoDiff.h:330
Bool isConstant() const
Is it a constant, i.e., with zero derivatives?
Definition: AutoDiff.h:339
bool Bool
Define the standard types used by Casacore.
Definition: aipstype.h:42
Class that computes partial derivatives by automatic differentiation.
Definition: AutoDiff.h:259
value_type & reference
Definition: AutoDiff.h:263
T val_p
The function value.
Definition: AutoDiff.h:344
void operator/=(const AutoDiff< T > &other)
T & deriv(uInt which)
Definition: AutoDiff.h:331
void operator-=(const AutoDiff< T > &other)
const value_type * const_iterator
Definition: AutoDiff.h:266
Vector< T > & derivatives()
Definition: AutoDiff.h:322
void operator*=(const AutoDiff< T > &other)
In-place mathematical operators.
T & value()
Returns the value of the function.
Definition: AutoDiff.h:315
this file contains all the compiler specific defines
Definition: mainpage.dox:28
void operator+=(const AutoDiff< T > &other)
T & derivative(uInt which)
Returns a specific derivative.
Definition: AutoDiff.h:329
unsigned int uInt
Definition: aipstype.h:51
AutoDiff< T > & operator=(const T &v)
Assignment operator.
const value_type & const_reference
Definition: AutoDiff.h:264