/*
   - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
   SLEPc - Scalable Library for Eigenvalue Problem Computations
   Copyright (c) 2002-, Universitat Politecnica de Valencia, Spain

   This file is part of SLEPc.
   SLEPc is distributed under a 2-clause BSD license (see LICENSE).
   - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*/

static char help[] = "Eigenvalue problem with Bethe-Salpeter structure.\n\n"
  "The command line options are:\n"
  "  -n <n>, where <n> = dimension of the blocks.\n"
  "  -R <filename>, R matrix.\n"
  "  -C <filename>, C matrix.\n\n";

#include <slepceps.h>

/*
   This example computes eigenvalues of a matrix

        H = [  R    C
              -C^H -R^T ],

   where R is Hermitian and C is complex symmetric. In particular, R and C have the
   following Toeplitz structure:

        R = pentadiag{a,b,c,conj(b),conj(a)}
        C = tridiag{b,d,b}

   where a,b,d are complex scalars, and c is real.

   Alternatively, use -R and -C command-line options to load matrices from file.
*/

int main(int argc,char **argv)
{
  Mat            H,R,C;      /* problem matrices */
  EPS            eps;        /* eigenproblem solver context */
  PetscScalar    a,b,c,d;
  PetscReal      lev;
  PetscInt       n=24,Istart,Iend,i,nconv;
  PetscBool      flg,terse,checkorthog,nest=PETSC_FALSE;
  Vec            t,*x,*y;
  PetscViewer    viewer;
  char           filename[PETSC_MAX_PATH_LEN];

  PetscFunctionBeginUser;
  PetscCall(SlepcInitialize(&argc,&argv,NULL,help));

  /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
             Compute (or load) the problem matrices R and C
     - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

  PetscCall(PetscOptionsHasName(NULL,NULL,"-R",&flg));

  if (flg) {

    PetscCall(PetscPrintf(PETSC_COMM_WORLD,"\nBethe-Salpeter eigenproblem stored in file\n\n"));
    PetscCall(PetscPrintf(PETSC_COMM_WORLD," Reading %s matrices from a binary file...\n",PetscDefined(USE_COMPLEX)?"COMPLEX":"REAL"));

    PetscCall(PetscOptionsGetString(NULL,NULL,"-R",filename,sizeof(filename),&flg));
    PetscCall(PetscViewerBinaryOpen(PETSC_COMM_WORLD,filename,FILE_MODE_READ,&viewer));
    PetscCall(MatCreate(PETSC_COMM_WORLD,&R));
    PetscCall(MatSetFromOptions(R));
    PetscCall(MatLoad(R,viewer));
    PetscCall(PetscViewerDestroy(&viewer));

    PetscCall(PetscOptionsGetString(NULL,NULL,"-C",filename,sizeof(filename),&flg));
    PetscCheck(flg,PETSC_COMM_WORLD,PETSC_ERR_USER_INPUT,"Must indicate file for both R and C matrices");
    PetscCall(PetscViewerBinaryOpen(PETSC_COMM_WORLD,filename,FILE_MODE_READ,&viewer));
    PetscCall(MatCreate(PETSC_COMM_WORLD,&C));
    PetscCall(MatSetFromOptions(C));
    PetscCall(MatLoad(C,viewer));
    PetscCall(PetscViewerDestroy(&viewer));

  } else {

    PetscCall(PetscOptionsGetInt(NULL,NULL,"-n",&n,NULL));
    PetscCall(PetscPrintf(PETSC_COMM_WORLD,"\nBethe-Salpeter eigenproblem, n=%" PetscInt_FMT "\n\n",n));

#if defined(PETSC_USE_COMPLEX)
    a = PetscCMPLX(-0.1,0.2);
    b = PetscCMPLX(1.0,0.5);
    d = PetscCMPLX(2.0,0.2);
#else
    a = -0.1;
    b = 1.0;
    d = 2.0;
#endif
    c = 4.5;

    PetscCall(MatCreate(PETSC_COMM_WORLD,&R));
    PetscCall(MatSetSizes(R,PETSC_DECIDE,PETSC_DECIDE,n,n));
    PetscCall(MatSetFromOptions(R));

    PetscCall(MatCreate(PETSC_COMM_WORLD,&C));
    PetscCall(MatSetSizes(C,PETSC_DECIDE,PETSC_DECIDE,n,n));
    PetscCall(MatSetFromOptions(C));

    PetscCall(MatGetOwnershipRange(R,&Istart,&Iend));
    for (i=Istart;i<Iend;i++) {
      if (i>1) PetscCall(MatSetValue(R,i,i-2,a,INSERT_VALUES));
      if (i>0) PetscCall(MatSetValue(R,i,i-1,b,INSERT_VALUES));
      PetscCall(MatSetValue(R,i,i,c,INSERT_VALUES));
      if (i<n-1) PetscCall(MatSetValue(R,i,i+1,PetscConj(b),INSERT_VALUES));
      if (i<n-2) PetscCall(MatSetValue(R,i,i+2,PetscConj(a),INSERT_VALUES));
    }

    PetscCall(MatGetOwnershipRange(C,&Istart,&Iend));
    for (i=Istart;i<Iend;i++) {
      if (i>0) PetscCall(MatSetValue(C,i,i-1,b,INSERT_VALUES));
      PetscCall(MatSetValue(C,i,i,d,INSERT_VALUES));
      if (i<n-1) PetscCall(MatSetValue(C,i,i+1,b,INSERT_VALUES));
    }

    PetscCall(MatAssemblyBegin(R,MAT_FINAL_ASSEMBLY));
    PetscCall(MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY));
    PetscCall(MatAssemblyEnd(R,MAT_FINAL_ASSEMBLY));
    PetscCall(MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY));
  }

  PetscCall(MatCreateBSE(R,C,&H));

  /* if you prefer, set the vector type so that MatCreateVecs() returns nested vectors */
  PetscCall(PetscOptionsGetBool(NULL,NULL,"-nest",&nest,NULL));
  if (nest) PetscCall(MatNestSetVecType(H,VECNEST));

  /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
                Create the eigensolver and set various options
     - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

  PetscCall(EPSCreate(PETSC_COMM_WORLD,&eps));
  PetscCall(EPSSetOperators(eps,H,NULL));
  PetscCall(EPSSetProblemType(eps,EPS_BSE));
  PetscCall(EPSSetFromOptions(eps));

  /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
                 Solve the eigensystem and display solution
     - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

  PetscCall(EPSSolve(eps));

  /* show detailed info unless -terse option is given by user */
  PetscCall(PetscOptionsHasName(NULL,NULL,"-terse",&terse));
  if (terse) PetscCall(EPSErrorView(eps,EPS_ERROR_RELATIVE,NULL));
  else {
    PetscCall(PetscViewerPushFormat(PETSC_VIEWER_STDOUT_WORLD,PETSC_VIEWER_ASCII_INFO_DETAIL));
    PetscCall(EPSConvergedReasonView(eps,PETSC_VIEWER_STDOUT_WORLD));
    PetscCall(EPSErrorView(eps,EPS_ERROR_RELATIVE,PETSC_VIEWER_STDOUT_WORLD));
    PetscCall(PetscViewerPopFormat(PETSC_VIEWER_STDOUT_WORLD));
  }

  /* check bi-orthogonality */
  PetscCall(PetscOptionsHasName(NULL,NULL,"-checkorthog",&checkorthog));
  PetscCall(EPSGetConverged(eps,&nconv));
  if (checkorthog && nconv>0) {
    PetscCall(MatCreateVecs(H,&t,NULL));
    PetscCall(VecDuplicateVecs(t,nconv,&x));
    PetscCall(VecDuplicateVecs(t,nconv,&y));
    for (i=0;i<nconv;i++) {
      PetscCall(EPSGetEigenvector(eps,i,x[i],NULL));
      PetscCall(EPSGetLeftEigenvector(eps,i,y[i],NULL));
    }
    PetscCall(VecCheckOrthogonality(x,nconv,y,nconv,NULL,NULL,&lev));
    if (lev<100*PETSC_MACHINE_EPSILON) PetscCall(PetscPrintf(PETSC_COMM_WORLD," Level of bi-orthogonality of eigenvectors < 100*eps\n\n"));
    else PetscCall(PetscPrintf(PETSC_COMM_WORLD," Level of bi-orthogonality of eigenvectors: %g\n\n",(double)lev));
    PetscCall(VecDestroy(&t));
    PetscCall(VecDestroyVecs(nconv,&x));
    PetscCall(VecDestroyVecs(nconv,&y));
  }

  PetscCall(EPSDestroy(&eps));
  PetscCall(MatDestroy(&R));
  PetscCall(MatDestroy(&C));
  PetscCall(MatDestroy(&H));
  PetscCall(SlepcFinalize());
  return 0;
}

/*TEST

   testset:
      args: -eps_nev 4 -eps_ncv 16 -eps_krylovschur_bse_type {{shao gruning projectedbse}} -terse -checkorthog -nest {{0 1}}
      filter: sed -e "s/17496/17495/g" | sed -e "s/38566/38567/g" | sed -e "s/32172/32173/g"
      nsize: {{1 2}}
      test:
         suffix: 1
         requires: complex
      test:
         suffix: 1_real
         requires: !complex
      test:
         suffix: 1_dense
         args: -mat_type dense
         requires: complex
         output_file: output/ex55_1.out
      test:
         suffix: 1_cuda
         args: -mat_type aijcusparse
         requires: cuda complex
         output_file: output/ex55_1.out
      test:
         suffix: 1_real_cuda
         args: -mat_type aijcusparse
         requires: cuda !complex
         output_file: output/ex55_1_real.out
      test:
         suffix: 1_hip
         args: -mat_type aijhipsparse
         requires: hip complex
         output_file: output/ex55_1.out
      test:
         suffix: 1_real_hip
         args: -mat_type aijhipsparse
         requires: hip !complex
         output_file: output/ex55_1_real.out

   testset:
      args: -eps_nev 4 -eps_ncv 16 -eps_krylovschur_bse_type {{shao gruning projectedbse}} -st_type sinvert -terse
      filter: sed -e "s/17496/17495/g" | sed -e "s/38566/38567/g"
      test:
         suffix: 1_sinvert
         requires: complex
      test:
         nsize: 4
         args: -mat_type scalapack
         suffix: 1_sinvert_scalapack
         requires: complex scalapack !__float128
         output_file: output/ex55_1_sinvert.out
      test:
         suffix: 1_real_sinvert
         requires: !complex
      test:
         nsize: 4
         args: -mat_type scalapack
         suffix: 1_real_sinvert_scalapack
         requires: !complex scalapack !__float128
         output_file: output/ex55_1_real_sinvert.out

   testset:
      args: -n 90 -eps_threshold_absolute 2.5 -eps_ncv {{10 24}} -eps_krylovschur_bse_type {{shao gruning projectedbse}} -eps_tol 1e-14 -terse -checkorthog
      test:
         suffix: 2
         requires: double complex
      test:
         suffix: 2_real
         requires: double !complex

   testset:
      args: -eps_nev 28 -eps_ncv 18 -terse
      test:
         suffix: 3
         requires: !complex !single

TEST*/
