|
| 1 | +#include <adolc/adouble.h> // use of active doubles |
| 2 | +#include <adolc/drivers/drivers.h> // use of "Easy to Use" drivers |
| 3 | +// gradient(.) and hessian(.) |
| 4 | +#include <adolc/taping.h> // use of taping |
| 5 | + |
| 6 | +#include <iostream> |
| 7 | +using namespace std; |
| 8 | + |
| 9 | +#include <cstdlib> |
| 10 | +#include <thread> |
| 11 | + |
| 12 | +void derive(const short my_tape, double init) |
| 13 | +{ |
| 14 | + const int n = 100; |
| 15 | + |
| 16 | + double *xp = new double[n]; |
| 17 | + double yp = 0.0; |
| 18 | + adouble *x = new adouble[n]; |
| 19 | + adouble y = 1; |
| 20 | + |
| 21 | + for(int i = 0; i < n; i++) |
| 22 | + { |
| 23 | + xp[i] = (i + init)/(2. + i); // some initialization |
| 24 | + } |
| 25 | + |
| 26 | + trace_on(my_tape); |
| 27 | + |
| 28 | + for(int i = 0; i < n; i++) { |
| 29 | + x[i] <<= xp[i]; |
| 30 | + y *= x[i]; |
| 31 | + } |
| 32 | + |
| 33 | + y >>= yp; |
| 34 | + |
| 35 | + delete[] x; |
| 36 | + |
| 37 | + trace_off(); |
| 38 | + |
| 39 | + double* g = new double[n]; |
| 40 | + |
| 41 | + gradient(my_tape, n, xp, g); |
| 42 | + |
| 43 | + double** H = new double*[n]; |
| 44 | + |
| 45 | + for(int i = 0; i < n; i++) |
| 46 | + { |
| 47 | + H[i] = (double*) new double[i + 1]; |
| 48 | + } |
| 49 | + |
| 50 | + hessian(my_tape, n, xp, H); |
| 51 | + |
| 52 | + double errh = 0.; |
| 53 | + |
| 54 | + for(int i = 0; i < n; i++) |
| 55 | + { |
| 56 | + for(int j = 0; j < n; j++) |
| 57 | + { |
| 58 | + if (i>j) |
| 59 | + { |
| 60 | + errh += fabs(H[i][j] - g[i]/xp[j]); |
| 61 | + } |
| 62 | + } // end for |
| 63 | + } // end for |
| 64 | + |
| 65 | + std::cout << "Computed Hessian in tape " << my_tape |
| 66 | + << ", error = " |
| 67 | + << errh |
| 68 | + << std::endl; |
| 69 | + |
| 70 | + for(int i = 0; i < n; ++i) |
| 71 | + { |
| 72 | + delete[] H[i]; |
| 73 | + } |
| 74 | + |
| 75 | + delete[] H; |
| 76 | + delete[] g; |
| 77 | +} |
| 78 | + |
| 79 | + |
| 80 | +int main() |
| 81 | +{ |
| 82 | + std::vector<std::thread> threads; |
| 83 | + |
| 84 | + for(int i = 1; i <= 10; ++i) |
| 85 | + { |
| 86 | + threads.push_back(std::thread(derive, i, (double) i)); |
| 87 | + } |
| 88 | + |
| 89 | + for(auto& thread: threads) |
| 90 | + { |
| 91 | + thread.join(); |
| 92 | + } |
| 93 | + |
| 94 | + return 0; |
| 95 | +} |
| 96 | + |
0 commit comments