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

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

#include "dco.hpp"

#include <iostream>
#include <math.h>
#include <nag.h>
#include <nagad.h>
#include <stdio.h>
using namespace std;

int main()
{
  // Scalars
  int           exit_status = 0;
  const Integer m           = 7;

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

  // Data points and values.
  double            xr[m], yr[m];
  nagad_a1w_w_rtype x[m], y[m];

  xr[0] = 0.0;
  xr[1] = 0.2;
  xr[2] = 0.4;
  xr[3] = 0.6;
  xr[4] = 0.75;
  xr[5] = 0.9;
  xr[6] = 1.0;

  for (int i = 0; i < m; i++)
  {
    yr[i] = exp(xr[i]);
    x[i]  = xr[i];
    y[i]  = yr[i];
  }

  // 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;

  // Register variables to differentiate w.r.t.
  for (int i = 0; i < m; i++)
  {
    dco::ga1s<double>::global_tape->register_variable(x[i]);
    dco::ga1s<double>::global_tape->register_variable(y[i]);
  }

  // Call the AD routine
  const Integer     lck = m + 4, lwrk = 6 * m + 16;
  nagad_a1w_w_rtype c[lck], lamda[lck], wrk[lwrk];
  ifail = 0;
  nag::ad::e01ba(ad_handle, m, x, y, lamda, c, lck, wrk, lwrk, ifail);

  // Evaluate computed spline using e02bb
  double            xint_r = 0.5;
  nagad_a1w_w_rtype xint, fit;
  xint  = xint_r;
  ifail = 0;
  nag::ad::e02bb(ad_handle, lck, lamda, c, xint, fit, ifail);

  cout << "\n Value of fitted spline at x = " << xint_r;
  cout.precision(5);
  cout << " is: " << dco::value(fit) << endl;

  // Setup evaluation of derivatives via adjoints.
  double inc = 1.0;
  dco::derivative(fit) += inc;

  ifail                                              = 0;
  dco::ga1s<double>::global_tape->sparse_interpret() = true;
  dco::ga1s<double>::global_tape->interpret_adjoint();

  cout << "\n Derivatives calculated: First order adjoints\n";
  cout << " Computational mode    : algorithmic\n";

  // Get derivatives
  cout << "\n Derivatives of fitted value w.r.t. data points:\n";
  cout << "  j    d/dx(j)      d/y(j)\n";
  cout.setf(ios::scientific, ios::floatfield);
  cout.precision(4);
  for (int j = 0; j < m; j++)
  {
    double dx = dco::derivative(x[j]);
    double dy = dco::derivative(y[j]);
    cout.width(3);
    cout << j + 1;
    cout.width(12);
    cout << dx;
    cout.width(12);
    cout << dy << endl;
  }

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

  return exit_status;
}