/* nag_real_sparse_eigensystem_option (f12adc) Example Program.
 *
 * NAGPRODCODE Version.
 *
 * Copyright 2016 Numerical Algorithms Group.
 *
 * Mark 26, 2016.
 */

#include <math.h>
#include <nag.h>
#include <nag_stdlib.h>
#include <stdio.h>
#include <nagf12.h>
#include <nagf16.h>

static void mv(Integer, double *, double *);
static void my_dgttrf(Integer, double *, double *, double *,
                      double *, Integer *, Integer *);
static void my_dgttrs(Integer, double *, double *, double *,
                      double *, Integer *, double *, double *);

int main(void)
{
  /* Constants */
  Integer licomm = 140, imon = 0;
  /* Scalars */
  double estnrm, h, rho, s, s1, s2, s3, sigmai, sigmar;
  Integer exit_status, info, irevcm, j, lcomm, n, nconv, ncv;
  Integer nev, niter, nshift, nx;
  /* Nag types */
  NagError fail;

  /* Arrays */
  double *comm = 0, *dd = 0, *dl = 0, *du = 0, *du2 = 0, *eigvr = 0;
  double *eigvi = 0, *eigest = 0, *resid = 0, *x2 = 0, *v = 0;
  Integer *icomm = 0, *ipiv = 0;
  /* Pointers */
  double *mx = 0, *x = 0, *y = 0;

  exit_status = 0;
  INIT_FAIL(fail);

  printf("nag_real_sparse_eigensystem_option (f12adc) Example "
         "Program Results\n");
  /* Skip heading in data file */
  scanf("%*[^\n] ");
  /* Read problem parameter values from data file. */
  scanf("%" NAG_IFMT "%" NAG_IFMT "%" NAG_IFMT "%lf%lf%lf%*[^\n] ", &nx, &nev,
        &ncv, &rho, &sigmar, &sigmai);
  n = nx * nx;
  lcomm = 3 * n + 3 * ncv * ncv + 6 * ncv + 60;
  /* Allocate memory */
  if (!(comm = NAG_ALLOC(lcomm, double)) ||
      !(eigvr = NAG_ALLOC(ncv, double)) ||
      !(eigvi = NAG_ALLOC(ncv, double)) ||
      !(eigest = NAG_ALLOC(ncv, double)) ||
      !(dd = NAG_ALLOC(n, double)) ||
      !(dl = NAG_ALLOC(n, double)) ||
      !(du = NAG_ALLOC(n, double)) ||
      !(du2 = NAG_ALLOC(n, double)) ||
      !(resid = NAG_ALLOC(n, double)) ||
      !(v = NAG_ALLOC(n * ncv, double)) ||
      !(x2 = NAG_ALLOC(n, double)) ||
      !(icomm = NAG_ALLOC(licomm, Integer)) ||
      !(ipiv = NAG_ALLOC(n, Integer)))
  {
    printf("Allocation failure\n");
    exit_status = -1;
    goto END;
  }
  /* Initialize communication arrays for problem using
     nag_real_sparse_eigensystem_init (f12aac). */
  nag_real_sparse_eigensystem_init(n, nev, ncv, icomm, licomm, comm,
                                   lcomm, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_real_sparse_eigensystem_init (f12aac).\n%s\n",
           fail.message);
    exit_status = 1;
    goto END;
  }
  /* Select the required spectrum using
     nag_real_sparse_eigensystem_option (f12adc). */
  nag_real_sparse_eigensystem_option("SHIFTED REAL", icomm, comm, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_real_sparse_eigensystem_init (f12aac).\n%s\n",
           fail.message);
    exit_status = 1;
    goto END;
  }
  /* Select the problem type using
     nag_real_sparse_eigensystem_option (f12adc). */
  nag_real_sparse_eigensystem_option("GENERALIZED", icomm, comm, &fail);
  /* Construct C = A - SIGMA*I, and factor C using my_dgttrf. */
  h = 1.0 / (double) (n + 1);
  s = rho / 2.0;
  s1 = -1.0 / h - s - sigmar * h / 6.0;
  s2 = 2.0 / h - sigmar * 4.0 * h / 6.0;
  s3 = -1.0 / h + s - sigmar * h / 6.0;
  for (j = 0; j <= n - 2; ++j) {
    dl[j] = s1;
    dd[j] = s2;
    du[j] = s3;
  }
  dd[n - 1] = s2;

  my_dgttrf(n, dl, dd, du, du2, ipiv, &info);

  irevcm = 0;
REVCOMLOOP:
  /* repeated calls to reverse communication routine
     nag_real_sparse_eigensystem_iter (f12abc). */
  nag_real_sparse_eigensystem_iter(&irevcm, resid, v, &x, &y, &mx,
                                   &nshift, comm, icomm, &fail);
  if (irevcm != 5) {
    if (irevcm == -1) {
      /* Perform  y <--- OP*x = inv[A-SIGMA*M]*M*x using
         my_dggtrs */
      mv(n, x, x2);
      my_dgttrs(n, dl, dd, du, du2, ipiv, x2, y);
    }
    else if (irevcm == 1) {
      /* Perform  y <--- OP*x = inv[A-SIGMA*M]*M*x where
         mx is available. */
      my_dgttrs(n, dl, dd, du, du2, ipiv, mx, y);
    }
    else if (irevcm == 2) {
      /* Perform  y <--- M*x */
      mv(n, x, y);
    }
    else if (irevcm == 4 && imon == 1) {
      /* If imon=1, get monitoring information using
         nag_real_sparse_eigensystem_monit (f12aec). */
      nag_real_sparse_eigensystem_monit(&niter, &nconv, eigvr,
                                        eigvi, eigest, icomm, comm);
      /* Compute 2-norm of Ritz estimates using
         nag_dge_norm (f16rac). */
      nag_dge_norm(Nag_ColMajor, Nag_FrobeniusNorm, nev, 1, eigest,
                   nev, &estnrm, &fail);
      printf("Iteration %3" NAG_IFMT ", ", niter);
      printf(" No. converged = %3" NAG_IFMT ",", nconv);
      printf(" norm of estimates = %17.8e\n", estnrm);
    }
    goto REVCOMLOOP;
  }
  if (fail.code == NE_NOERROR) {
    /* Post-Process using nag_real_sparse_eigensystem_sol
       (f12acc) to compute eigenvalues/vectors. */
    nag_real_sparse_eigensystem_sol(&nconv, eigvr, eigvi, v, sigmar,
                                    sigmai, resid, v, comm, icomm, &fail);
    /* Print computed eigenvalues. */

    printf("\n The %4" NAG_IFMT " generalized Ritz values closest", nconv);
    printf(" to  unity are:\n\n");
    for (j = 0; j <= nconv - 1; ++j) {
      printf("%8" NAG_IFMT "%5s( %12.4f ,%12.4f )\n", j + 1, "",
             sigmar + 1.0 / eigvr[j], eigvi[j]);
    }
  }
  else {
    printf(" Error from nag_real_sparse_eigensystem_iter (f12abc).\n%s\n",
           fail.message);
    exit_status = 1;
    goto END;
  }
END:
  NAG_FREE(comm);
  NAG_FREE(eigvr);
  NAG_FREE(eigvi);
  NAG_FREE(eigest);
  NAG_FREE(dd);
  NAG_FREE(dl);
  NAG_FREE(du);
  NAG_FREE(du2);
  NAG_FREE(resid);
  NAG_FREE(v);
  NAG_FREE(icomm);
  NAG_FREE(ipiv);
  NAG_FREE(x2);
  return exit_status;
}

static void mv(Integer n, double *v, double *y)
{
  /* Compute the matrix vector multiplication Y<---M*X, where M is
     mass matrix formed by using piecewise linear elements on [0,1]. */

  /* Scalars */
  double h;
  Integer j;

  /* Function Body */
  h = 1.0 / (double) (6 * (n + 1));
  y[0] = h * (v[0] * 4.0 + v[1]);
  for (j = 1; j <= n - 2; ++j) {
    y[j] = h * (v[j - 1] + v[j] * 4.0 + v[j + 1]);
  }
  y[n - 1] = h * (v[n - 2] + v[n - 1] * 4.0);
  return;
} /* mv */

static void my_dgttrf(Integer n, double dl[], double d[],
                      double du[], double du2[], Integer ipiv[],
                      Integer *info)
{
  /* A simple C version of the Lapack routine dgttrf with argument
     checking removed */
  /* Scalars */
  double temp, fact;
  Integer i;
  /* Function Body */
  *info = 0;
  for (i = 0; i < n; ++i) {
    ipiv[i] = i;
  }
  for (i = 0; i < n - 2; ++i) {
    du2[i] = 0.0;
  }
  for (i = 0; i < n - 2; i++) {
    if (fabs(d[i]) >= fabs(dl[i])) {
      /* No row interchange required, eliminate dl[i]. */
      if (d[i] != 0.0) {
        fact = dl[i] / d[i];
        dl[i] = fact;
        d[i + 1] = d[i + 1] - fact * du[i];
      }
    }
    else {
      /* Interchange rows I and I+1, eliminate dl[I] */
      fact = d[i] / dl[i];
      d[i] = dl[i];
      dl[i] = fact;
      temp = du[i];
      du[i] = d[i + 1];
      d[i + 1] = temp - fact * d[i + 1];
      du2[i] = du[i + 1];
      du[i + 1] = -fact * du[i + 1];
      ipiv[i] = i + 1;
    }
  }
  if (n > 1) {
    i = n - 2;
    if (fabs(d[i]) >= fabs(dl[i])) {
      if (d[i] != 0.0) {
        fact = dl[i] / d[i];
        dl[i] = fact;
        d[i + 1] = d[i + 1] - fact * du[i];
      }
    }
    else {
      fact = d[i] / dl[i];
      d[i] = dl[i];
      dl[i] = fact;
      temp = du[i];
      du[i] = d[i + 1];
      d[i + 1] = temp - fact * d[i + 1];
      ipiv[i] = i + 1;
    }
  }
  /* Check for a zero on the diagonal of U. */
  for (i = 0; i < n; ++i) {
    if (d[i] == 0.0) {
      *info = i;
      goto END;
    }
  }
END:
  return;
}

static void my_dgttrs(Integer n, double dl[], double d[],
                      double du[], double du2[], Integer ipiv[],
                      double b[], double y[])
{
  /* A simple C version of the Lapack routine dgttrs with argument
     checking removed, the number of right-hand-sides=1, Trans='N' */
  /* Scalars */
  Integer i, ip;
  double temp;
  /* Solve L*x = b. */
  for (i = 0; i <= n - 1; ++i) {
    y[i] = b[i];
  }
  for (i = 0; i < n - 1; ++i) {
    ip = ipiv[i];
    temp = y[i + 1 - ip + i] - dl[i] * y[ip];
    y[i] = y[ip];
    y[i + 1] = temp;
  }
  /* Solve U*x = b. */
  y[n - 1] = y[n - 1] / d[n - 1];
  if (n > 1) {
    y[n - 2] = (y[n - 2] - du[n - 2] * y[n - 1]) / d[n - 2];
  }
  for (i = n - 3; i >= 0; --i) {
    y[i] = (y[i] - du[i] * y[i + 1] - du2[i] * y[i + 2]) / d[i];
  }
  return;
}