1 /* --------------------------------------------------------------------------
2 CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-18 Bradley M. Bell
3
4 CppAD is distributed under the terms of the
5 Eclipse Public License Version 2.0.
6
7 This Source Code may also be made available under the following
8 Secondary License when the conditions for such availability set forth
9 in the Eclipse Public License, Version 2.0 are satisfied:
10 GNU General Public License, Version 2.0 or later.
11 ---------------------------------------------------------------------------- */
12 /*
13 $begin fadbad_det_lu.cpp$$
14 $spell
15 onetape
16 cppad
17 std
18 Lu
19 Fadbad
20 det
21 badiff.hpp
22 const
23 CppAD
24 typedef
25 diff
26 bool
27 srand
28 $$
29
30 $section Fadbad Speed: Gradient of Determinant Using Lu Factorization$$
31
32
33 $head Specifications$$
34 See $cref link_det_lu$$.
35
36 $head Implementation$$
37 $srccode%cpp% */
38 // suppress conversion warnings before other includes
39 # include <cppad/wno_conversion.hpp>
40 //
41 # include <FADBAD++/badiff.h>
42 # include <cppad/speed/det_by_lu.hpp>
43 # include <cppad/speed/uniform_01.hpp>
44 # include <cppad/utility/vector.hpp>
45
46 // list of possible options
47 # include <map>
48 extern std::map<std::string, bool> global_option;
49
link_det_lu(size_t size,size_t repeat,CppAD::vector<double> & matrix,CppAD::vector<double> & gradient)50 bool link_det_lu(
51 size_t size ,
52 size_t repeat ,
53 CppAD::vector<double> &matrix ,
54 CppAD::vector<double> &gradient )
55 {
56 // speed test global option values
57 if( global_option["onetape"] || global_option["atomic"] )
58 return false;
59 if( global_option["memory"] || global_option["optimize"] )
60 return false;
61 // -----------------------------------------------------
62 // setup
63 //
64 // object for computing determinant
65 typedef fadbad::B<double> ADScalar;
66 typedef CppAD::vector<ADScalar> ADVector;
67 CppAD::det_by_lu<ADScalar> Det(size);
68
69 size_t i; // temporary index
70 size_t m = 1; // number of dependent variables
71 size_t n = size * size; // number of independent variables
72 ADScalar detA; // AD value of the determinant
73 ADVector A(n); // AD version of matrix
74
75 // ------------------------------------------------------
76 while(repeat--)
77 { // get the next matrix
78 CppAD::uniform_01(n, matrix);
79
80 // set independent variable values
81 for(i = 0; i < n; i++)
82 A[i] = matrix[i];
83
84 // compute the determinant
85 detA = Det(A);
86
87 // create function object f : A -> detA
88 detA.diff(0, (unsigned int) m); // index 0 of m dependent variables
89
90 // evaluate and return gradient using reverse mode
91 for(i =0; i < n; i++)
92 gradient[i] = A[i].d(0); // partial detA w.r.t A[i]
93 }
94 // ---------------------------------------------------------
95 return true;
96 }
97 /* %$$
98 $end
99 */
100