/* F11DB_T1W_F C++ Header Example Program.
*
* Copyright 2020 Numerical Algorithms Group.
* Mark 27.1, 2020.
*/
#include <dco_light.hpp>
#include <nag.h>
#include <nagx04.h>
#include <nagad.h>
#include <stdio.h>
#include <iostream>
using namespace std;
int main(void)
{
int exit_status = 0;
void *ad_handle = 0;
Integer ifail = 0;
cout << "F11DB_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;
Integer la = 2*nnz;
Integer liwork = 7*n + 2;
nagad_t1w_w_rtype *a=0, *x=0, *y=0;
double *ar=0, *yr=0, *dxdy=0;
Integer *icol=0, *idiag=0, *ipivp=0, *ipivq=0, *irow=0;
Integer *istr=0, *iwork=0;
a = new nagad_t1w_w_rtype [la];
x = new nagad_t1w_w_rtype [n];
y = new nagad_t1w_w_rtype [n];
icol = new Integer [la];
idiag = new Integer [n];
ipivp = new Integer [n];
ipivq = new Integer [n];
irow = new Integer [la];
istr = new Integer [n+1];
iwork = new Integer [liwork];
ar = new double [la];
yr = new double [n];
dxdy = 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 y
for (int i=0; i<n; i++) {
cin >> yr[i];
y[i] = yr[i];
}
// Create AD configuration data object
ifail = 0;
x10aa_t1w_f_(ad_handle,ifail);
// Calculate LU factorization
Integer lfill = -1;
nagad_t1w_w_rtype dtol;
Integer nnzc, npivm;
dtol = 0.0;
ifail = 0;
f11da_t1w_f_(ad_handle,n,nnz,a,la,irow,icol,lfill,dtol,"C","N",
ipivp,ipivq,istr,idiag,nnzc,npivm,iwork,liwork,ifail,1,1);
// Check value of npivm
if (npivm>0) {
cout << " Factorization is not complete" << endl;
} else {
// Solve P L D U x = y
double inc = 1.0, zero = 0.0;
for (int i=0; i<n; i++) {
for (int j=0; j<n; j++) {
y[j] = yr[j];
}
nagad_t1w_inc_derivative(&y[i],inc);
ifail = 0;
f11db_t1w_f_(ad_handle,"N",n,a,la,irow,icol,ipivp,ipivq,istr,
idiag,"C",y,x,ifail,1,1);
for (int j=0; j<n; j++) {
Integer k = j + i*n;
dxdy[k] = nagad_t1w_get_derivative(x[j]);
}
nagad_t1w_set_derivative(&y[i],zero);
}
// Output results
cout.setf(ios::scientific,ios::floatfield);
cout.precision(4);
cout << " Solution vector" << endl;
for (int i=0; i<n; ++i) {
cout.width(12);cout << nagad_t1w_get_value(x[i]) << " ";
}
cout << "\n\n Derivatives calculated: First order tangents\n";
cout << " Computational mode : algorithmic\n";
cout << "\n Derivatives of solution X w.r.t RHS Y:\n";
// Print derivatives
cout << endl;
NagError fail;
INIT_FAIL(fail);
x04cac(Nag_ColMajor,Nag_GeneralMatrix,Nag_NonUnitDiag,n,n,dxdy,n,
" dx_i/dy_j",0,&fail);
}
// Remove computational data object
ifail = 0;
x10ab_t1w_f_(ad_handle,ifail);
delete [] a;
delete [] x;
delete [] y;
delete [] icol;
delete [] idiag;
delete [] ipivp;
delete [] ipivq;
delete [] irow;
delete [] istr;
delete [] iwork;
delete [] ar;
delete [] yr;
delete [] dxdy;
return exit_status;
}