NAG Library Manual, Mark 28.3
Interfaces:  FL   CL   CPP   AD 

NAG AD Library Introduction
Example description
/* S18DE_A1W_F C++ Header Example Program.
 *
 * Copyright 2022 Numerical Algorithms Group.
 * Mark 28.3, 2022.
 */

#include <dco.hpp>
#include <iostream>
#include <nag.h>
#include <nagad.h>
#include <stdio.h>
#include <string>
using namespace std;

int main()
{
  int exit_status = 0;

  // Input and output variables

  cout << "S18DE_A1W_F C++ Header Example Program Results\n\n";

  // Create AD tape
  dco::ga1s<double>::global_tape = dco::ga1s<double>::tape_t::create();

  // Create AD configuration data object
  Integer           ifail = 0;
  nag::ad::handle_t ad_handle;

  cout << "    nu               z             scal";
  cout << "         cy[0]                      dy/dnu\n";
  cout.setf(ios::scientific, ios::floatfield);
  cout.setf(ios::right);
  cout.precision(2);

  const Integer     n = 1;
  nagad_a1w_w_rtype fnu, x, zr, zi;
  nagad_a1w_w_ctype z, cy[n];
  Integer           nz;
  fnu = 5.5;
  zr  = -6.1;
  zi  = 9.8;
  z.real(zr);
  z.imag(zi);

  // Register x, i.e. differentiate w.r.t. x
  dco::ga1s<double>::global_tape->register_variable(fnu);

  // Call NAG AD Routine
  ifail = 0;
  nag::ad::s18de(ad_handle, fnu, z, n, "S", cy, nz, ifail);

  nagad_a1w_w_rtype cyr;
  cyr        = real(cy[0]);
  double inc = 1.0;
  dco::derivative(cyr) += inc;
  ifail                                              = 0;
  dco::ga1s<double>::global_tape->sparse_interpret() = true;
  dco::ga1s<double>::global_tape->interpret_adjoint();
  double dyrdnu;
  dyrdnu = dco::derivative(fnu);

  dco::ga1s<double>::global_tape->zero_adjoints();

  nagad_a1w_w_rtype cyi;
  cyi = imag(cy[0]);
  dco::derivative(cyi) += inc;
  ifail                                              = 0;
  dco::ga1s<double>::global_tape->sparse_interpret() = true;
  dco::ga1s<double>::global_tape->interpret_adjoint();
  double dyidnu;
  dyidnu = dco::derivative(fnu);

  cout.width(10);
  cout << dco::value(fnu) << " (";
  cout.width(9);
  cout << dco::value(real(z)) << ",";
  cout.width(10);
  cout << dco::value(imag(z)) << ")   S   (";
  cout.width(9);
  cout << dco::value(cyr) << ",";
  cout.width(10);
  cout << dco::value(cyi) << ")    (";
  cout.width(9);
  cout << dyrdnu << ",";
  cout.width(10);
  cout << dyidnu << ")" << endl;

  dco::ga1s<double>::tape_t::remove(dco::ga1s<double>::global_tape);

  return exit_status;
}