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

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

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

int main()
{
  // Scalars
  const Integer maxfev = 1000, mode = 2, n = 7, nprint = 0;

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

  // problem parameters and starting value
  std::vector<double> 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<double> diag(n, 1), fjac(n * n), fvec(n), qtf(n), r(n * (n + 1) / 2);
  double  factor = 100, xtol = sqrt(X02AJC);
  Integer nfev, njev;

  auto fcn = [&](nag::ad::handle_t &     ad_handle,
                const Integer &         n,
                const double *x,
                double *fvec,
                double *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;
  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;
  }


  return 0;
}