/* nag::ad::c05au Tangent over Adjoint Example Program.
*/
#include <dco.hpp>
#include <iostream>
#include <nagad.h>
// Function which calls NAG AD Library routines.
template <typename T> void func(T r, T &x);
// Driver with the adjoint calls.
// Finds the zero point f(xv) = 0 for the function
// f(x) = x - exp(-r*x) using an initial approximation of xv.
// Also, computes the Hessian d2x_dr2 = d2xv/dr2.
void driver(const double &rv, double &xv, double &d2x_dr2);
int main()
{
std::cout << " nag::ad::c05au Tangent over Adjoint Example Program Results\n";
// Set problem parameters
double rv = 1.0;
// Solution x
double xv;
// Derivative of x
double d2x_dr2;
// Call driver
driver(rv, xv, d2x_dr2);
// Print outputs
std::cout << "\n Derivatives calculated: Second order adjoints\n";
std::cout << " Computational mode : algorithmic\n";
std::cout.setf(std::ios::scientific, std::ios::floatfield);
std::cout.precision(12);
std::cout << "\n Solution:\n";
std::cout << " x = " << xv << std::endl;
std::cout << "\n Second derivative of solution x w.r.t. parameter r:\n";
std::cout << " d2x/dr2(x) = " << d2x_dr2 << std::endl;
return 0;
}
// Driver with the adjoint calls.
// Finds the zero point f(xv) = 0 for the function
// f(x) = x - exp(-r*x) using an initial approximation of xv.
// Also, computes the Hessian d2x_dr2 = d2xv/dr2.
void driver(const double &rv, double &xv, double &d2x_dr2)
{
using mode = dco::ga1s<dco::gt1s<double>::type>;
using T = mode::type;
// Create the AD tape
mode::global_tape = mode::tape_t::create();
// Function parameter r
T r = rv;
// Register variable to differentiate w.r.t.
dco::derivative(dco::value(r)) = 1.0;
mode::global_tape->register_variable(r);
// Variable to differentiate
T x;
// Call the NAG AD Lib functions
func(r, x);
// Extract the computed solution
xv = dco::passive_value(x);
mode::global_tape->register_output_variable(x);
dco::derivative(x) = 1.0;
mode::global_tape->interpret_adjoint();
// Extract the derivatives
d2x_dr2 = dco::derivative(dco::derivative(r));
// Remove tape
mode::tape_t::remove(mode::global_tape);
}
// Function which calls NAG AD Library routines.
template <typename T> void func(T r, T &x)
{
// Active variables
T a, b, h = 0.1;
T eps = 1.0e-5, eta = 0.0;
// Initial guess to the zero
dco::passive_value(x) = 1.0;
// Create AD configuration data object
nag::ad::handle_t ad_handle;
// Routine for computing an approximation to a simple zero of the continuous
// function f using an initial approximation.
Integer ifail = 0;
nag::ad::c05au(ad_handle, x, h, eps, eta,
[&](nag::ad::handle_t const& handle, T const& x, T & z) {
z = x - exp(-r * x);
},
a, b, ifail);
}