/* F01EJ_A1W_F C++ Header Example Program.
*
* Copyright 2024 Numerical Algorithms Group.
* Mark 30.1, 2024.
*/
#include <dco.hpp>
#include <iostream>
#include <nag.h>
#include <nagad.h>
#include <nagx04.h>
#include <stdio.h>
#include <string>
using namespace std;
int main()
{
cout << "F01EJ_A1W_F C++ Header Example Program Results\n\n";
// Skip heading in data file
string mystr;
getline(cin, mystr);
// Read problem size and number of right-hand-sides
Integer n;
cin >> n;
// Allocate arrays containing A and its factorized form, B
// and the solution X.
std::vector<dco::ga1s<double>::type> a(n*n), a_in(n*n);
std::vector<double> ar(n*n);
// Create AD tape
dco::ga1s<double>::global_tape = dco::ga1s<double>::tape_t::create();
// Read the matrix A
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < n; ++j)
{
Integer k = i + j * n;
cin >> a_in[k];
}
}
// Register and copy
dco::ga1s<double>::global_tape->register_variable(a_in);
a = a_in;
// Find log(A)
dco::ga1s<double>::type imnorm;
Integer ifail = 0;
nag::ad::handle_t ad_handle;
nag::ad::f01ej(ad_handle, n, a.data(), n, imnorm, ifail);
// Print log(A)
ar = dco::value(a);
cout << endl;
NagError fail;
INIT_FAIL(fail);
x04cac(Nag_ColMajor, Nag_GeneralMatrix, Nag_NonUnitDiag, n, n, ar.data(), n,
" Log(A)", 0, &fail);
cout << "\n\n Derivatives calculated: First order adjoints\n";
cout << " Computational mode : algorithmic\n";
cout << "\n Derivatives of diagional of log(A) w.r.t diagonal of A:\n";
// Obtain derivatives
for (int i = 0; i < n; i++)
{
Integer k = i * n + i;
dco::derivative(a[k]) = 1.0;
dco::ga1s<double>::global_tape->interpret_adjoint();
for (int j = 0; j < n; j++)
{
Integer l = j + j * n, p = i + j * n;
ar[p] = dco::derivative(a_in[l]);
}
dco::ga1s<double>::global_tape->zero_adjoints();
}
cout << endl;
INIT_FAIL(fail);
x04cac(Nag_ColMajor, Nag_GeneralMatrix, Nag_NonUnitDiag, n, n, ar.data(), n,
" d(logA(i,i)/dA(j,j)", 0, &fail);
dco::ga1s<double>::tape_t::remove(dco::ga1s<double>::global_tape);
return 0;
}