#include "dco.hpp"
/* G01GC_A1W_F C++ Header Example Program.
*
* Copyright 2023 Numerical Algorithms Group.
* Mark 29.2, 2023.
*/
#include <iostream>
#include <nag.h>
#include <nagad.h>
#include <stdio.h>
#include <string>
using namespace std;
int main()
{
int exit_status = 0;
cout << "G01GC_A1W_F C++ Header Example Program Results\n\n";
// Create AD tape
dco::ga1s<double>::global_tape = dco::ga1s<double>::tape_t::create();
// Skip heading in data file
string mystr;
getline(cin, mystr);
// Read number of x values
Integer n;
cin >> n;
cout << " x df rlamda p";
cout << " p' df' rlamda'\n";
cout.setf(ios::scientific, ios::floatfield);
cout.setf(ios::right);
cout.precision(2);
nagad_a1w_w_rtype tol;
tol = 0.0;
Integer maxit = 100;
nagad_a1w_w_rtype *x = new nagad_a1w_w_rtype[n];
nagad_a1w_w_rtype *df = new nagad_a1w_w_rtype[n];
nagad_a1w_w_rtype *rlamda = new nagad_a1w_w_rtype[n];
// Create AD configuration data object
nag::ad::handle_t ad_handle;
// Loop over x values
for (Integer i = 0; i < n; ++i)
{
// Read next x, df, rlamda
double xr, dfr, rr;
cin >> xr;
cin >> dfr;
cin >> rr;
x[i] = xr;
df[i] = dfr;
rlamda[i] = rr;
// Register variables, i.e. differentiate w.r.t. x, df and rlamda
dco::ga1s<double>::global_tape->register_variable(x[i]);
dco::ga1s<double>::global_tape->register_variable(df[i]);
dco::ga1s<double>::global_tape->register_variable(rlamda[i]);
// Call NAG AD Routine
nagad_a1w_w_rtype p;
Integer ifail = 0;
nag::ad::g01gc(ad_handle, x[i], df[i], rlamda[i], tol, maxit, p, ifail);
// Reset adjoints, increment p, and evaluate adjoints
dco::ga1s<double>::global_tape->zero_adjoints();
double inc = 1.0;
dco::derivative(p) += inc;
dco::ga1s<double>::global_tape->sparse_interpret() = true;
dco::ga1s<double>::global_tape->interpret_adjoint();
// Get derivatives
double dpdx, dpdd, dpdr;
dpdx = dco::derivative(x[i]);
dpdd = dco::derivative(df[i]);
dpdr = dco::derivative(rlamda[i]);
// Output results
cout.width(9);
cout << x[i];
cout.width(9);
cout << df[i];
cout.width(9);
cout << rlamda[i];
cout.width(9);
cout << p;
cout.width(11);
cout << dpdx;
cout.width(11);
cout << dpdd;
cout.width(11);
cout << dpdr << endl;
}
dco::ga1s<double>::tape_t::remove(dco::ga1s<double>::global_tape);
delete[] x;
delete[] df;
delete[] rlamda;
return exit_status;
}