Actual source code: ex2.c

petsc-3.8.4 2018-03-24
Report Typos and Errors

  2: static char help[] = "Tests PC and KSP on a tridiagonal matrix.  Note that most\n\
  3: users should employ the KSP interface instead of using PC directly.\n\n";

  5:  #include <petscksp.h>

  7: int main(int argc,char **args)
  8: {
  9:   Mat            mat;          /* matrix */
 10:   Vec            b,ustar,u;  /* vectors (RHS, exact solution, approx solution) */
 11:   PC             pc;           /* PC context */
 12:   KSP            ksp;          /* KSP context */
 14:   PetscInt       n = 10,i,its,col[3];
 15:   PetscScalar    value[3];
 16:   PCType         pcname;
 17:   KSPType        kspname;
 18:   PetscReal      norm,tol=1000.*PETSC_MACHINE_EPSILON;

 20:   PetscInitialize(&argc,&args,(char*)0,help);if (ierr) return ierr;
 21:   /* Create and initialize vectors */
 22:   VecCreateSeq(PETSC_COMM_SELF,n,&b);
 23:   VecCreateSeq(PETSC_COMM_SELF,n,&ustar);
 24:   VecCreateSeq(PETSC_COMM_SELF,n,&u);
 25:   VecSet(ustar,1.0);
 26:   VecSet(u,0.0);

 28:   /* Create and assemble matrix */
 29:   MatCreateSeqAIJ(PETSC_COMM_SELF,n,n,3,NULL,&mat);
 30:   value[0] = -1.0; value[1] = 2.0; value[2] = -1.0;
 31:   for (i=1; i<n-1; i++) {
 32:     col[0] = i-1; col[1] = i; col[2] = i+1;
 33:     MatSetValues(mat,1,&i,3,col,value,INSERT_VALUES);
 34:   }
 35:   i    = n - 1; col[0] = n - 2; col[1] = n - 1;
 36:   MatSetValues(mat,1,&i,2,col,value,INSERT_VALUES);
 37:   i    = 0; col[0] = 0; col[1] = 1; value[0] = 2.0; value[1] = -1.0;
 38:   MatSetValues(mat,1,&i,2,col,value,INSERT_VALUES);
 39:   MatAssemblyBegin(mat,MAT_FINAL_ASSEMBLY);
 40:   MatAssemblyEnd(mat,MAT_FINAL_ASSEMBLY);

 42:   /* Compute right-hand-side vector */
 43:   MatMult(mat,ustar,b);

 45:   /* Create PC context and set up data structures */
 46:   PCCreate(PETSC_COMM_WORLD,&pc);
 47:   PCSetType(pc,PCNONE);
 48:   PCSetFromOptions(pc);
 49:   PCSetOperators(pc,mat,mat);
 50:   PCSetUp(pc);

 52:   /* Create KSP context and set up data structures */
 53:   KSPCreate(PETSC_COMM_WORLD,&ksp);
 54:   KSPSetType(ksp,KSPRICHARDSON);
 55:   KSPSetFromOptions(ksp);
 56:   PCSetOperators(pc,mat,mat);
 57:   KSPSetPC(ksp,pc);
 58:   KSPSetUp(ksp);

 60:   /* Solve the problem */
 61:   KSPGetType(ksp,&kspname);
 62:   PCGetType(pc,&pcname);
 63:   PetscPrintf(PETSC_COMM_SELF,"Running %s with %s preconditioning\n",kspname,pcname);
 64:   KSPSolve(ksp,b,u);
 65:   VecAXPY(u,-1.0,ustar);
 66:   VecNorm(u,NORM_2,&norm);
 67:   KSPGetIterationNumber(ksp,&its);
 68:   if (norm > tol) {
 69:     PetscPrintf(PETSC_COMM_SELF,"2 norm of error %g Number of iterations %D\n",(double)norm,its);
 70:   }

 72:   /* Free data structures */
 73:   KSPDestroy(&ksp);
 74:   VecDestroy(&u);
 75:   VecDestroy(&ustar);
 76:   VecDestroy(&b);
 77:   MatDestroy(&mat);
 78:   PCDestroy(&pc);

 80:   PetscFinalize();
 81:   return ierr;
 82: }