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

NAG AD Library Introduction
Example description
/* 
  nag::ad::c05rc Tangent Example Program.
 */

#include <dco.hpp>
#include <nagad.h>

int main()
{
  using T = dco::gt1s<double>::type;

  // Scalars
  const Integer maxfev = 1000, mode = 2, n = 7, nprint = 0;

  std::cout << " nag::ad::c05rc Tangent Example Program Results\n";

  // problem parameters and starting value
  std::vector<T> ruser = {-1, 3, -2, -2, -1}, x(7, -1);

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

  std::vector<T> diag(n, 1), fjac(n * n), fvec(n), qtf(n), r(n * (n + 1) / 2);
  T  factor = 100, xtol = sqrt(X02AJC);
  Integer nfev, njev;

  auto fcn = [&](nag::ad::handle_t &     ad_handle,
                const Integer &         n,
                const T *x,
                T *fvec,
                T *fjac,
                Integer &               iflag)
              {
                if (iflag != 2)
                {
                  for (int i = 0; i < n; ++i)
                  {
                    fvec[i] = (ruser[1] + ruser[2] * x[i]) * x[i] - ruser[4];
                  }
                  for (int i = 1; i < n; ++i)
                  {
                    fvec[i] = fvec[i] + ruser[0] * x[i - 1];
                  }
                  for (int i = 0; i < n - 1; ++i)
                  {
                    fvec[i] = fvec[i] + ruser[3] * x[i + 1];
                  }
                }
                else
                {
                  for (int i = 0; i < n * n; ++i)
                  {
                    fjac[i] = 0.0;
                  }
                  fjac[0] = ruser[1] + 2.0 * ruser[2] * x[0];
                  fjac[n] = ruser[3];
                  for (int i = 1; i < n - 1; ++i)
                  {
                    int k       = i * n + i;
                    fjac[k - n] = ruser[0];
                    fjac[k]     = ruser[1] + 2.0 * ruser[2] * x[i];
                    fjac[k + n] = ruser[3];
                  }
                  fjac[n * n - n - 1] = ruser[0];
                  fjac[n * n - 1]     = ruser[1] + 2.0 * ruser[2] * x[n - 1];
                }
                iflag = 0;
              };

  ifail = 0;

  // Seed all input tangents to 1.0
  dco::derivative(ruser) = 1.0;

  nag::ad::c05rc(ad_handle, fcn, n, x.data(), fvec.data(), fjac.data(), xtol, maxfev, mode, diag.data(),
                 factor, nprint, nfev, njev, r.data(), qtf.data(), ifail);

  std::cout.setf(std::ios::scientific, std::ios::floatfield);
  std::cout.precision(4);
  std::cout << " Solution:\n";
  for (int i = 0; i < n; ++i)
  {
    std::cout.width(3);
    std::cout << i + 1;
    std::cout.width(12);
    std::cout << x[i] << std::endl;
  }

  double druser = 0;
  for (int i = 0; i < x.size(); ++i)
  {
    druser += dco::derivative(x[i]);
  }
  std::cout << " Sum of derivatives = " << druser << "\n";

  return 0;
}