/* F11XE_T1W_F C++ Header Example Program.
*
* Copyright 2021 Numerical Algorithms Group.
* Mark 27.3, 2021.
*/
#include <dco.hpp>
#include <iostream>
#include <nag.h>
#include <nagad.h>
#include <nagx04.h>
#include <stdio.h>
using namespace std;
int main()
{
int exit_status = 0;
nag::ad::handle_t ad_handle;
Integer ifail = 0;
cout << "F11XE_T1W_F C++ Header Example Program Results\n\n";
// Skip heading in data file
string mystr;
getline(cin, mystr);
// Read order of matrix and number of nonzero entries
Integer n, nnz;
cin >> n;
cin >> nnz;
nagad_t1w_w_rtype *a = 0, *x = 0, *y = 0;
double * ar = 0, *yr = 0, *dydx = 0;
Integer * icol = 0, *irow = 0;
a = new nagad_t1w_w_rtype[nnz];
x = new nagad_t1w_w_rtype[n];
y = new nagad_t1w_w_rtype[n];
icol = new Integer[nnz];
irow = new Integer[nnz];
ar = new double[nnz];
yr = new double[n];
dydx = new double[n * n];
// Read the matrix A
for (int i = 0; i < nnz; i++)
{
cin >> ar[i] >> irow[i] >> icol[i];
a[i] = ar[i];
}
// Read the vector x
for (int i = 0; i < n; i++)
{
cin >> yr[i];
}
// Create AD configuration data object
ifail = 0;
double inc = 1.0, zero = 0.0;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
x[i] = yr[i];
}
dco::derivative(x[i]) = inc;
// Calculate matrix-vector product
ifail = 0;
nag::ad::f11xe(ad_handle, n, nnz, a, irow, icol, "C", x, y, ifail);
dco::derivative(x[i]) = zero;
for (int j = 0; j < n; j++)
{
Integer k = j + i * n;
dydx[k] = dco::derivative(y[j]);
}
}
// Output results
cout.setf(ios::scientific, ios::floatfield);
cout.precision(4);
cout << " Matrix-vector product" << endl;
for (int i = 0; i < n; ++i)
{
cout.width(12);
cout << dco::value(y[i]) << endl;
}
cout << "\n Derivatives calculated: First order tangents\n";
cout << " Computational mode : algorithmic\n";
cout << "\n Derivatives of Y w.r.t X (A):\n";
cout << endl;
NagError fail;
INIT_FAIL(fail);
x04cac(Nag_ColMajor, Nag_GeneralMatrix, Nag_NonUnitDiag, n, n, dydx, n,
" dy_i/dx_j", 0, &fail);
ifail = 0;
delete[] a;
delete[] x;
delete[] y;
delete[] icol;
delete[] irow;
delete[] ar;
delete[] yr;
delete[] dydx;
return exit_status;
}