/* F06YA_A1W_F C++ Header Example Program.
*
* Copyright 2023 Numerical Algorithms Group.
* Mark 29.1, 2023.
*/
#include <dco.hpp>
#include <iostream>
#include <math.h>
#include <nag.h>
#include <nagad.h>
#include <nagx04.h>
#include <stdio.h>
#include <string>
using namespace std;
int main()
{
int exit_status = 0;
nag::ad::handle_t ad_handle;
Integer ifail = 0;
cout << "F06YA_A1W_F C++ Header Example Program Results\n\n";
// Skip heading in data file
string mystr;
getline(cin, mystr);
// Read problem size and parameters
Integer m, n, k;
cin >> m >> n >> k;
double alphar, betar;
cin >> alphar >> betar;
nagad_a1w_w_rtype alpha, beta;
alpha = alphar;
beta = betar;
// Allocate arrays containing A and its factorized form, B
// and the solution X.
nagad_a1w_w_rtype *a = 0, *b = 0, *c = 0;
double * ar = 0, *br = 0, *cr = 0, *da = 0, *db = 0;
a = new nagad_a1w_w_rtype[k * m];
b = new nagad_a1w_w_rtype[n * k];
c = new nagad_a1w_w_rtype[m * n];
ar = new double[k * m];
br = new double[n * k];
cr = new double[m * n];
da = new double[m * n];
db = new double[m * n];
// Read the matrix A
double dd;
for (int i = 0; i < k; ++i)
{
for (int j = 0; j < m; ++j)
{
cin >> dd;
Integer l = i + j * k;
ar[l] = dd;
a[l] = dd;
}
}
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < k; ++j)
{
cin >> dd;
Integer l = i + j * n;
br[l] = dd;
b[l] = dd;
}
}
for (int i = 0; i < m * n; ++i)
{
cr[i] = 1.0;
c[i] = 1.0;
}
// Create AD tape
dco::ga1s<double>::global_tape = dco::ga1s<double>::tape_t::create();
// Create AD configuration data object
ifail = 0;
dco::ga1s<double>::global_tape->register_variable(alpha);
dco::ga1s<double>::global_tape->register_variable(beta);
// y = beta*y + alpha*A^T*b
ifail = 0;
nag::ad::f06ya(ad_handle, "T", "T", m, n, k, alpha, a, k, b, n, beta, c, m,
ifail);
for (int i = 0; i < m * n; ++i)
{
cr[i] = dco::value(c[i]);
}
cout << endl;
NagError fail;
INIT_FAIL(fail);
x04cac(Nag_ColMajor, Nag_GeneralMatrix, Nag_NonUnitDiag, m, n, cr, m,
" Matrix C after update", 0, &fail);
cout << "\n\n Derivatives calculated: First order adjoints\n";
cout << " Computational mode : algorithmic\n";
cout << "\n Derivatives of C w.r.t alpha and beta:\n";
for (int i = 0; i < m * n; ++i)
{
dco::ga1s<double>::global_tape->zero_adjoints();
double inc = 1.0;
dco::derivative(c[i]) += inc;
ifail = 0;
dco::ga1s<double>::global_tape->sparse_interpret() = true;
dco::ga1s<double>::global_tape->interpret_adjoint();
da[i] = dco::derivative(alpha);
db[i] = dco::derivative(beta);
}
// Print derivatives
cout << endl;
x04cac(Nag_ColMajor, Nag_GeneralMatrix, Nag_NonUnitDiag, m, n, da, m,
" dC/dalpha", 0, &fail);
cout << endl;
x04cac(Nag_ColMajor, Nag_GeneralMatrix, Nag_NonUnitDiag, m, n, db, m,
" dC/dbeta", 0, &fail);
dco::ga1s<double>::tape_t::remove(dco::ga1s<double>::global_tape);
return exit_status;
}