/* nag_lapackeig_zgejsv (f08kvc) Example Program.
*
* Copyright 2020 Numerical Algorithms Group.
*
* Mark 27.1, 2020.
*/

#include <math.h>
#include <nag.h>
#include <stdio.h>

static Integer normalize_vectors(Nag_OrderType order, Integer m, Integer n,
Complex v[], Complex x[]);

int main(void) {
/* Scalars */
double eps, serrbd;
Integer exit_status = 0;
Integer pda, pdu, pdv;
Integer i, j, m, n, n_uvecs, n_vvecs;
/* Arrays */
Complex *a = 0, *u = 0, *v = 0, *x = 0;
double *rcondu = 0, *rcondv = 0, *s = 0;
double rwork[7];
Integer iwork[3];
char nag_enum_arg[40];

/* Nag Types */
Nag_OrderType order;
Nag_Preprocess joba;
Nag_LeftVecsType jobu;
Nag_RightVecsType jobv;
Nag_ZeroCols jobr;
Nag_TransType jobt;
Nag_Perturb jobp;
NagError fail;

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

INIT_FAIL(fail);

printf("nag_lapackeig_zgejsv (f08kvc) Example Program Results\n\n");

/* Skip heading in data file */
scanf("%*[^\n]");
scanf("%" NAG_IFMT "%" NAG_IFMT "%*[^\n]", &m, &n);

if (n < 0 || m < n) {
printf("Invalid n or nrhs\n");
exit_status = 1;
goto END;
;
}

/* Read Nag type arguments by name and convert to value */
scanf(" %39s%*[^\n]", nag_enum_arg);
/* nag_enum_name_to_value (x04nac).
* Converts NAG enum member name to value
*/
joba = (Nag_Preprocess)nag_enum_name_to_value(nag_enum_arg);
scanf(" %39s%*[^\n]", nag_enum_arg);
jobu = (Nag_LeftVecsType)nag_enum_name_to_value(nag_enum_arg);
scanf(" %39s%*[^\n]", nag_enum_arg);
jobv = (Nag_RightVecsType)nag_enum_name_to_value(nag_enum_arg);
scanf(" %39s%*[^\n]", nag_enum_arg);
jobr = (Nag_ZeroCols)nag_enum_name_to_value(nag_enum_arg);
scanf(" %39s%*[^\n]", nag_enum_arg);
jobt = (Nag_TransType)nag_enum_name_to_value(nag_enum_arg);
scanf(" %39s%*[^\n]", nag_enum_arg);
jobp = (Nag_Perturb)nag_enum_name_to_value(nag_enum_arg);

/* Size of u and v depends on some of the above Nag type arguments. */
n_uvecs = 1;
if (jobu == Nag_LeftVecs) {
n_uvecs = m;
} else if (jobu == Nag_LeftSpan) {
n_uvecs = n;
} else if (jobu == Nag_NotLeftWork && jobv == Nag_RightVecs &&
jobt == Nag_Trans && m == n) {
n_uvecs = m;
}
if (jobv == Nag_NotRightVecs) {
n_vvecs = 1;
} else {
n_vvecs = n;
}
#ifdef NAG_COLUMN_MAJOR
pda = m;
pdu = m;
pdv = n;
#else
pda = n;
pdu = n_uvecs;
pdv = n_vvecs;
#endif

if (!(a = NAG_ALLOC(m * n, Complex)) || !(rcondu = NAG_ALLOC(m, double)) ||
!(rcondv = NAG_ALLOC(m, double)) || !(s = NAG_ALLOC(n, double)) ||
!(u = NAG_ALLOC(m * n_uvecs, Complex)) ||
!(v = NAG_ALLOC(n_vvecs * n_vvecs, Complex)) ||
!(x = NAG_ALLOC(n, Complex))) {
printf("Allocation failure\n");
exit_status = -1;
goto END;
}

/* Read the m by n matrix A from data file */
for (i = 1; i <= m; i++)
for (j = 1; j <= n; j++)
scanf(" ( %lf , %lf )", &A(i, j).re, &A(i, j).im);
scanf("%*[^\n]");

/* nag_lapackeig_zgejsv (f08kvc)
* Compute the singular values and left and right singular vectors
* of A (A = U*S*V^T, m>=n).
*/
nag_lapackeig_zgejsv(order, joba, jobu, jobv, jobr, jobt, jobp, m, n, a, pda,
s, u, pdu, v, pdv, rwork, iwork, &fail);
if (fail.code != NE_NOERROR) {
printf("Error from nag_lapackeig_zgejsv (f08kvc).\n%s\n", fail.message);
exit_status = 2;
goto END;
}

/* Get the machine precision, eps and compute the approximate
* error bound for the computed singular values. Note that for
* the 2-norm, s[0] = norm(A).
*/
eps = nag_machine_precision;
serrbd = eps * s[0];

/* Print (possibly scaled) singular values. */
if (fabs(rwork[0] - rwork[1]) < 2.0 * eps) {
/* No scaling required */
printf("Singular values\n");
for (j = 0; j < n; j++)
printf("%8.4f", s[j]);
} else {
printf("Scaled singular values\n");
for (j = 0; j < n; j++)
printf("%8.4f", s[j]);
printf("\nFor true singular values, multiply by a/b,\n");
printf("where a = %f and b = %f", rwork[0], rwork[1]);
}
printf("\n\n");

/* Print left and right (spanning) singular vectors, if requested.  using
* nag_file_print_matrix_complex_gen_comp (x04dbc)
* Print complex general matrix (comprehensive)
*/
x[0].re = 2.0;
if (jobu == Nag_LeftVecs || jobu == Nag_LeftSpan) {
/* Normalize left vectors so that largest element is real and positive */
exit_status = normalize_vectors(order, m, n, u, x);
if (exit_status > 0) {
exit_status = 3;
goto END;
}
fflush(stdout);
nag_file_print_matrix_complex_gen_comp(
order, Nag_GeneralMatrix, Nag_NonUnitDiag, m, n, u, pdu,
Nag_BracketForm, "%7.4f", "Left singular vectors", Nag_IntegerLabels, 0,
Nag_IntegerLabels, 0, 80, 0, 0, &fail);
if (fail.code != NE_NOERROR) {
printf("Error from nag_file_print_matrix_complex_gen_comp (x04dbc).\n"
"%s\n",
fail.message);
exit_status = 4;
goto END;
}
}
if (jobv == Nag_RightVecs || jobv == Nag_RightVecsJRots) {
/* Normalize V, using factors, x, for U if calculated */
exit_status = normalize_vectors(order, n, n, v, x);
if (exit_status > 0) {
exit_status = 5;
goto END;
}
printf("\n");
fflush(stdout);
nag_file_print_matrix_complex_gen_comp(
order, Nag_GeneralMatrix, Nag_NonUnitDiag, n, n, v, pdv,
Nag_BracketForm, "%7.4f", "Right singular vectors", Nag_IntegerLabels,
0, Nag_IntegerLabels, 0, 80, 0, 0, &fail);
if (fail.code != NE_NOERROR) {
printf("Error from nag_file_print_matrix_complex_gen_comp (x04dbc).\n"
"%s\n",
fail.message);
exit_status = 6;
goto END;
}
}

/* nag_lapackeig_ddisna (f08flc)
* Estimate reciprocal condition numbers for the singular vectors.
*/
nag_lapackeig_ddisna(Nag_LeftSingVecs, m, n, s, rcondu, &fail);
if (fail.code == NE_NOERROR)
nag_lapackeig_ddisna(Nag_RightSingVecs, m, n, s, rcondv, &fail);
if (fail.code != NE_NOERROR) {
printf("Error from nag_lapackeig_ddisna (f08flc).\n%s\n", fail.message);
exit_status = 7;
goto END;
}

if (joba == Nag_ColpivRrankCond || joba == Nag_FullpivRrankCond) {
printf("\n\nEstimate of the condition number of column equilibrated A\n");
printf("%11.1e", rwork[3]);
}

/* Print the approximate error bounds for the singular values and vectors. */
printf("\n\nError estimates (as multiples of machine precision)\n");
printf("\n   for the singular values\n%4ld\n", lrint(serrbd / X02AJC));

printf("\n   for left singular vectors\n");
for (i = 0; i < n; i++)
printf("%4ld", lrint(serrbd / rcondu[i] / X02AJC));

printf("\n\n   for right singular vectors\n");
for (i = 0; i < n; i++)
printf("%4ld", lrint(serrbd / rcondv[i] / X02AJC));
printf("\n");

END:
NAG_FREE(a);
NAG_FREE(rcondu);
NAG_FREE(rcondv);
NAG_FREE(s);
NAG_FREE(u);
NAG_FREE(v);
NAG_FREE(x);

return exit_status;
}

static Integer normalize_vectors(Nag_OrderType order, Integer m, Integer n,
Complex v[], Complex x[]) {
/* Each complex vector v[] is normalized so that the element of largest
* magnitude is scaled to be real and positive
*/

double r, rmax, scal;
Integer colinc, rowinc, i, j, k, l, indv, errors = 0;
Complex alpha, y[1];
NagError fail;

INIT_FAIL(fail);

if (order == Nag_ColMajor) {
rowinc = 1;
colinc = m;
} else {
rowinc = n;
colinc = 1;
}

scal = x[0].re;
indv = 0;
for (j = 0; j < n; j++) {

if (scal > 1.5) {
* Find element of eigenvector with largest absolute value.
*/
rmax = 0.0;
l = indv;
k = 0;
for (i = 0; i < m; i++) {
/* nag_complex_abs (a02dbc). Modulus of a complex number.  */
r = nag_complex_abs(v[l]);
if (r > rmax) {
rmax = r;
k = l;
}
l += rowinc;
}

/* Normalization factor beta */
x[j].re = v[k].re / rmax;
x[j].im = -v[k].im / rmax;
}

/* Scale current vector v_j by factor x[j] using:
* nag_blast_zaxpby (f16gcc) which performs y := alpha*x + beta*y.
*/
alpha = nag_complex_create(0.0, 0.0);
nag_blast_zaxpby(m, alpha, y, 1, x[j], &v[indv], rowinc, &fail);
if (fail.code != NE_NOERROR) {
printf("Error from nag_blast_zaxpby (f16gcc).\n%s\n", fail.message);
errors = 2;
goto END;
}
indv += colinc;
}
END:
return errors;
}