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

NAG AD Library Introduction
Example description
/* F08AH_T1W_F C++ Header Example Program.
 *
 * Copyright 2024 Numerical Algorithms Group.
 * Mark 30.1, 2024.
 */

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

// typedef DCO_TYPE nagad_t1w_w_rtype
typedef double                   DCO_BASE_TYPE;
typedef dco::gt1s<DCO_BASE_TYPE> DCO_MODE;
typedef DCO_MODE::type           DCO_TYPE;

int main()
{
  /* Scalars */
  Integer exit_status = 0;

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

  // Create handle
  nag::ad::handle_t ad_handle;
  Integer           ifail = 0;

  // Skip heading in data file
  string mystr;
  getline(cin, mystr);

  Integer m, n;
  cin >> m;
  cin >> n;

  Integer pda   = m;
  Integer lwork = 64 * n;

  Integer tau_len;
  if (m < n)
  {
    tau_len = m;
  }
  else
  {
    tau_len = n;
  }

  // Allocate arrays
  // nagad_t1w_w_rtype *a = 0, *tau = 0, *a_in = 0, *work = 0;
  DCO_TYPE *a = 0, *tau = 0, *work = 0, *a_in = 0;
  double *  l = 0, *dlda = 0;
  a    = new DCO_TYPE[m * n];
  work = new DCO_TYPE[lwork];
  a_in = new DCO_TYPE[m * n];
  tau  = new DCO_TYPE[tau_len];
  l    = new double[m * m];
  dlda = new double[m * n];

  // Read A from data file
  double tmp;
  for (int i = 0; i < m; ++i)
  {
    for (int j = 0; j < n; ++j)
    {
      cin >> tmp;
      a_in[i + j * m] = tmp;
    }
  }

  double d_zero = 0.0;
  for (int i = 0; i < m * n; i++)
  {
    // dco::derivative(a_in[i]) = d_zero;
    dco::derivative(a_in[i]) = d_zero;
    a[i]                     = a_in[i];
  }

  double d_one = 1.0;
  for (int j = 0; j < n; j++)
  {
    // dco::derivative(a[j*m]) = d_one;
    dco::derivative(a[j * m]) = d_one;
    nag::ad::f08ah(ad_handle, m, n, a, pda, tau, work, lwork, ifail);
    if (ifail != 0)
    {
      printf("Error from F08AH_T1W_F .\n%" NAG_IFMT " ", ifail);
      exit_status = 1;
      goto END;
    }
    if (j == 0)
    {
      for (int i = 0; i < m * m; ++i)
      {
        // l[i] = a[i].value
        l[i] = dco::value(a[i]);
      }
    }

    for (int i = 0; i < m; i++)
    {
      int ld = i * (m + 1);
      int k  = j * m + i;
      // drda[k] = a[l].tangent
      dlda[k] = dco::derivative(a[ld]);
    }

    for (int i = 0; i < m * n; i++)
      a[i] = a_in[i];
  }

  NagError fail;
  INIT_FAIL(fail);
  x04cac(Nag_ColMajor, Nag_LowerMatrix, Nag_NonUnitDiag, m, m, l, m,
         "L from Q factorization of A", 0, &fail);
  printf("\nDerivatives of diagonal of L w.r.t. first row of A\n");
  x04cac(Nag_ColMajor, Nag_GeneralMatrix, Nag_NonUnitDiag, m, n, dlda, m,
         "dL_ii/dA_j1", 0, &fail);

END:

  delete[] a;
  delete[] a_in;
  delete[] tau;
  delete[] l;
  delete[] dlda;
  delete[] work;

  return exit_status;
}