/* nag_zggevx (f08wpc) Example Program.
*
* Copyright 2017 Numerical Algorithms Group.
*
* Mark 26.1, 2017.
*/

#include <stdio.h>
#include <math.h>
#include <nag.h>
#include <nag_stdlib.h>
#include <naga02.h>
#include <nagf08.h>
#include <nagm01.h>
#include <nagx02.h>

#ifdef __cplusplus
extern "C"
{
#endif
static Integer NAG_CALL compare(const Nag_Pointer a, const Nag_Pointer b);
static Integer normalize_vectors(Integer n, Complex v[], Complex e[],
size_t rank[]);
static Integer sort_values (Integer n, Complex alpha[],
Complex beta[], Complex e[],
double rconde[], double rcondv[],
size_t rank[], double emod[]);
#ifdef __cplusplus
}
#endif

int main(void)
{
/* Scalars */
Complex z;
double abnorm, abnrm, bbnrm, eps, small, tol;
Integer i, ihi, ilo, j, n, pda, pdb, pdvl, pdvr;
Integer exit_status = 0, verbose = 0;

/* Arrays */
Complex *a = 0, *alpha = 0, *b = 0, *beta = 0, *vl = 0, *vr = 0;
Complex *e = 0;
double *emod = 0;
size_t *rank = 0;
double *lscale = 0, *rconde = 0, *rcondv = 0, *rscale = 0;
char nag_enum_arg[40];

/* Nag Types */
NagError fail;
Nag_OrderType order;
Nag_LeftVecsType jobvl;
Nag_RightVecsType jobvr;
Nag_RCondType sense;

#ifdef NAG_COLUMN_MAJOR
#define A(I, J)  a[(J-1)*pda + I - 1]
#define B(I, J)  b[(J-1)*pdb + I - 1]
order = Nag_ColMajor;
#else
#define A(I, J)  a[(I-1)*pda + J - 1]
#define B(I, J)  b[(I-1)*pdb + J - 1]
order = Nag_RowMajor;
#endif

INIT_FAIL(fail);

printf("nag_zggevx (f08wpc) Example Program Results\n");

/* Skip heading in data file */
scanf("%*[^\n]");
scanf("%" NAG_IFMT "%*[^\n]", &n);
if (n < 0) {
printf("Invalid n\n");
exit_status = 1;
goto END;
}
scanf(" %39s%*[^\n]", nag_enum_arg);
/* nag_enum_name_to_value (x04nac).
* Converts NAG enum member name to value
*/
jobvl = (Nag_LeftVecsType) nag_enum_name_to_value(nag_enum_arg);
scanf(" %39s%*[^\n]", nag_enum_arg);
jobvr = (Nag_RightVecsType) nag_enum_name_to_value(nag_enum_arg);
scanf(" %39s%*[^\n]", nag_enum_arg);
sense = (Nag_RCondType) nag_enum_name_to_value(nag_enum_arg);

pda = n;
pdb = n;
pdvl = (jobvl == Nag_LeftVecs ? n : 1);
pdvr = (jobvr == Nag_RightVecs ? n : 1);

/* Allocate memory */
if (!(a = NAG_ALLOC(n * n, Complex)) ||
!(b = NAG_ALLOC(n * n, Complex)) ||
!(alpha = NAG_ALLOC(n, Complex)) ||
!(beta = NAG_ALLOC(n, Complex)) ||
!(e = NAG_ALLOC(n, Complex)) ||
!(emod = NAG_ALLOC(n, double)) ||
!(rank = NAG_ALLOC(n, size_t)) ||
!(vl = NAG_ALLOC(pdvl * pdvl, Complex)) ||
!(vr = NAG_ALLOC(pdvr * pdvr, Complex)) ||
!(lscale = NAG_ALLOC(n, double)) ||
!(rconde = NAG_ALLOC(n, double)) ||
!(rcondv = NAG_ALLOC(n, double)) || !(rscale = NAG_ALLOC(n, double)))
{
printf("Allocation failure\n");
exit_status = -1;
goto END;
}

/* Read in the matrices A and B */
for (i = 1; i <= n; ++i)
for (j = 1; j <= n; ++j)
scanf(" ( %lf , %lf )", &A(i, j).re, &A(i, j).im);
scanf("%*[^\n]");
for (i = 1; i <= n; ++i)
for (j = 1; j <= n; ++j)
scanf(" ( %lf , %lf )", &B(i, j).re, &B(i, j).im);
scanf("%*[^\n]");

/* Solve the generalized eigenvalue problem using nag_zggevx (f08wpc). */
nag_zggevx(order, Nag_BalanceBoth, jobvl, jobvr, sense, n, a, pda, b, pdb,
alpha, beta, vl, pdvl, vr, pdvr, &ilo, &ihi, lscale, rscale,
&abnrm, &bbnrm, rconde, rcondv, &fail);
if (fail.code != NE_NOERROR) {
printf("Error from nag_zggevx (f08wpc).\n%s\n", fail.message);
exit_status = 1;
goto END;
}

/* nag_real_safe_small_number (x02amc), nag_machine_precision (x02ajc) */
eps = nag_machine_precision;
small = nag_real_safe_small_number;
if (abnrm == 0.0)
abnorm = ABS(bbnrm);
else if (bbnrm == 0.0)
abnorm = ABS(abnrm);
else if (ABS(abnrm) >= ABS(bbnrm))
abnorm = ABS(abnrm) * sqrt(1.0 + (bbnrm / abnrm) * (bbnrm / abnrm));
else
abnorm = ABS(bbnrm) * sqrt(1.0 + (abnrm / bbnrm) * (abnrm / bbnrm));

tol = eps * abnorm;

/* Print out eigenvalues and associated condition number and bounds */
if (verbose && sense != Nag_NotRCond)
printf("\n R = Reciprocal condition number, E = Error bound\n");
printf("\n");
printf("%22s", "Eigenvalues");

/* Sort values by decreasing modulus and store in e[] */
exit_status=sort_values(n, alpha, beta, e, rconde, rcondv, rank, emod);

if (verbose && (sense == Nag_RCondEigVals || sense == Nag_RCondBoth))
printf("%15s%10s", "R", "E");
printf("\n");
for (j = 0; j < n; ++j) {
/* Print out information on the j-th eigenvalue */
if (nag_complex_abs(alpha[j]) * small >= nag_complex_abs(beta[j])) {
printf("%2" NAG_IFMT " is numerically infinite or undetermined\n",
j + 1);
printf("   alpha = (%9.4f, %9.4f), beta = (%9.4f, %9.4f)\n",
alpha[j].re, alpha[j].im, beta[j].re, beta[j].im);
}
else {
z = nag_complex_divide(alpha[j], beta[j]);
printf("%2" NAG_IFMT " (%13.4e, %13.4e)", j + 1, z.re, z.im);
if (verbose && (sense == Nag_RCondEigVals || sense == Nag_RCondBoth)) {
printf(" %10.1e", rconde[j]);
if (rconde[j] > 0.0)
printf(" %9.1e", tol / rconde[j]);
else
printf(" infinite");
}
printf("\n");
}
}

if (jobvl == Nag_LeftVecs) {
exit_status = normalize_vectors(n, vl, e, rank);
}
if (jobvr == Nag_RightVecs && exit_status == 0) {
exit_status = normalize_vectors(n, vr, e, rank);
}

/* Print out information on the eigenvectors as requested */
if (jobvl == Nag_LeftVecs) {
printf("\n");
/* Print left eigenvectors using nag_gen_complx_mat_print (x04dac). */
fflush(stdout);
nag_gen_complx_mat_print(order, Nag_GeneralMatrix, Nag_NonUnitDiag, n,
n, vl, pdvl, "    Left eigenvectors (columns)",
0, &fail);
}
if (jobvr == Nag_RightVecs && fail.code == NE_NOERROR) {
printf("\n");
/* Print right eigenvectors using nag_gen_complx_mat_print (x04dac). */
fflush(stdout);
nag_gen_complx_mat_print(order, Nag_GeneralMatrix, Nag_NonUnitDiag, n,
n, vr, pdvr, "    Right eigenvectors (columns)",
0, &fail);
}
if (fail.code != NE_NOERROR) {
printf("Error from nag_gen_complx_mat_print (x04dac).\n%s\n",
fail.message);
exit_status = 1;
goto END;
}
if (verbose && (sense == Nag_RCondEigVecs || sense == Nag_RCondBoth)) {
printf("%2s", "R");
for (j = 0; j < n; ++j)
printf(" %8.1e", rcondv[j]);
printf("\n%2s", "E");
for (j = 0; j < n; ++j) {
if (rcondv[j] > 0.0)
printf(" %8.1e", tol / rcondv[j]);
else
printf(" infinite");
}
printf("\n");
}

END:
NAG_FREE(a);
NAG_FREE(b);
NAG_FREE(alpha);
NAG_FREE(beta);
NAG_FREE(vl);
NAG_FREE(vr);
NAG_FREE(lscale);
NAG_FREE(rconde);
NAG_FREE(rcondv);
NAG_FREE(rscale);
NAG_FREE(e);
NAG_FREE(emod);
NAG_FREE(rank);

return exit_status;
}

static Integer normalize_vectors(Integer n, Complex v[], Complex e[],
size_t rank[])
{

Complex           scal;
double            r, rr;
Integer           errors = 0, i, j, k;
NagError          fail;

INIT_FAIL(fail);

#ifdef NAG_COLUMN_MAJOR
#define V(I, J)  v[(J-1)*n + I - 1]
#else
#define V(I, J)  v[(I-1)*n + J - 1]
#endif
/* Re-normalize the eigenvectors, largest absolute element real */
for (i=1; i<=n; i++) {
k = 0;
r = -1.0;
for (j=1; j<=n; j++) {
rr = nag_complex_abs(V(j,i));
if (rr>r) {
r = rr;
k = j;
}
}
scal.re = V(k,i).re/(r*r);
scal.im = -V(k,i).im/(r*r);
for (j=1; j<=n; j++) {
V(j,i) = nag_complex_multiply(V(j,i),scal);
}
V(k,i).re = 1.0;
V(k,i).im = 0.0;
}
/* Sort eigenvectors according to rank */
for (i=1; i<=n; i++) {
for (j=1; j<=n; j++)
e[j-1] = V(i,j);

/* Sort eigenvector row i using nag_reorder_vector (m01esc). */
nag_reorder_vector((Pointer) e, (size_t) n, sizeof(Complex),
(ptrdiff_t) sizeof(Complex), rank, &fail);
if (fail.code != NE_NOERROR) {
printf("Error from nag_reorder_vector (m01esc).\n%s\n", fail.message);
errors = 5;
goto END;
}
for (j=1; j<=n; j++)
V(i,j) = e[j-1];
}
#undef V
END:
return errors;
}

static Integer sort_values (Integer n, Complex alpha[], Complex beta[],
Complex e[], double rconde[], double rcondv[],
size_t rank[], double emod[])
{
Integer       i, exit_status = 0;
NagError      fail;

INIT_FAIL(fail);

for (i = 0; i < n; ++i) {
/* nag_complex_divide (a02cdc): Quotient of two complex numbers;
* nag_complex_abs (a02ddc): Moduli of complex number.
*/
e[i] = nag_complex_divide(alpha[i], beta[i]);
emod[i] = nag_complex_abs(e[i]);
}
/* Rank sort eigenvalues by absolute values using
* nag_rank_sort (m01dsc).
*/
nag_rank_sort((Pointer) emod, (size_t) n, (ptrdiff_t) (sizeof(double)),
compare, Nag_Descending, rank, &fail);
if (fail.code != NE_NOERROR) {
printf("Error from nag_rank_sort (m01dsc).\n%s\n", fail.message);
exit_status = 10;
goto END;
}
/* Turn ranks into indices using nag_make_indices (m01zac). */
nag_make_indices(rank, (size_t) n, &fail);
if (fail.code != NE_NOERROR) {
printf("Error from nag_make_indices (m01zac).\n%s\n", fail.message);
exit_status = 11;
goto END;
}
/* Sort eigenvalues using nag_reorder_vector (m01esc). */
nag_reorder_vector((Pointer) e, (size_t) n, sizeof(Complex),
(ptrdiff_t) sizeof(Complex), rank, &fail);
if (fail.code != NE_NOERROR) {
printf("Error from nag_reorder_vector (m01esc).\n%s\n", fail.message);
exit_status = 12;
goto END;
}
nag_reorder_vector((Pointer) alpha, (size_t) n, sizeof(Complex),
(ptrdiff_t) sizeof(Complex), rank, &fail);
nag_reorder_vector((Pointer) beta, (size_t) n, sizeof(Complex),
(ptrdiff_t) sizeof(Complex), rank, &fail);
nag_reorder_vector((Pointer) rconde, (size_t) n, sizeof(double),
(ptrdiff_t) sizeof(double), rank, &fail);
nag_reorder_vector((Pointer) rcondv, (size_t) n, sizeof(double),
(ptrdiff_t) sizeof(double), rank, &fail);
END:
return exit_status;
}

static Integer NAG_CALL compare(const Nag_Pointer a, const Nag_Pointer b)
{
double x = *((const double *) a) - *((const double *) b);
return (x < 0.0 ? -1 : (x == 0.0 ? 0 : 1));
}