Actual source code: ex3.c

  1: /*$Id: ex3.c,v 1.53 2001/08/07 03:03:43 balay Exp $*/

  3: static char help[] = "Demonstrates the use of fast Richardson for SOR. Andn
  4: also tests the MatRelax() routines.  Input parameters are:n
  5:  -n <n> : problem dimensionnn";

 7:  #include petscksp.h
 8:  #include petscpc.h

 10: int main(int argc,char **args)
 11: {
 12:   Mat     mat;          /* matrix */
 13:   Vec     b,ustar,u;  /* vectors (RHS, exact solution, approx solution) */
 14:   PC      pc;           /* PC context */
 15:   KSP     ksp;          /* KSP context */
 16:   int     ierr,n = 10,i,its,col[3];
 17:   PetscScalar  value[3],one = 1.0,zero = 0.0;
 18:   KSPType kspname;
 19:   PCType  pcname;

 21:   PetscInitialize(&argc,&args,(char *)0,help);
 22:   PetscOptionsGetInt(PETSC_NULL,"-n",&n,PETSC_NULL);

 24:   /* Create and initialize vectors */
 25:   VecCreateSeq(PETSC_COMM_SELF,n,&b);
 26:   VecCreateSeq(PETSC_COMM_SELF,n,&ustar);
 27:   VecCreateSeq(PETSC_COMM_SELF,n,&u);
 28:   VecSet(&one,ustar);
 29:   VecSet(&zero,u);

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

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

 48:   /* Create PC context and set up data structures */
 49:   PCCreate(PETSC_COMM_WORLD,&pc);
 50:   PCSetType(pc,PCNONE);
 51:   PCSetFromOptions(pc);
 52:   PCSetOperators(pc,mat,mat,DIFFERENT_NONZERO_PATTERN);
 53:   PCSetVector(pc,u);
 54:   PCSetUp(pc);

 56:   /* Create KSP context and set up data structures */
 57:   KSPCreate(PETSC_COMM_WORLD,&ksp);
 58:   KSPSetType(ksp,KSPRICHARDSON);
 59:   KSPSetFromOptions(ksp);
 60:   KSPSetSolution(ksp,u);
 61:   KSPSetRhs(ksp,b);
 62:   PCSetOperators(pc,mat,mat,DIFFERENT_NONZERO_PATTERN);
 63:   KSPSetPC(ksp,pc);
 64:   KSPSetUp(ksp);

 66:   /* Solve the problem */
 67:   KSPGetType(ksp,&kspname);
 68:   PCGetType(pc,&pcname);
 69:   PetscPrintf(PETSC_COMM_SELF,"Running %s with %s preconditioningn",kspname,pcname);
 70:   KSPSolve(ksp,&its);
 71:   PetscPrintf(PETSC_COMM_WORLD,"Number of iterations %dn",its);

 73:   /* Free data structures */
 74:   KSPDestroy(ksp);
 75:   VecDestroy(u);
 76:   VecDestroy(ustar);
 77:   VecDestroy(b);
 78:   MatDestroy(mat);
 79:   PCDestroy(pc);
 80:   PetscFinalize();
 81:   return 0;
 82: }
 83: