Actual source code: ex15.c

  1: /*$Id: ex15.c,v 1.28 2001/08/07 21:30:50 bsmith Exp $*/

  3: static char help[] = "SLES on an operator with a null space.nn";

 5:  #include petscsles.h

  7: int main(int argc,char **args)
  8: {
  9:   Vec          x,b,u;      /* approx solution, RHS, exact solution */
 10:   Mat          A;            /* linear system matrix */
 11:   SLES         sles;         /* SLES context */
 12:   int          ierr,i,n = 10,col[3],its,i1,i2;
 13:   PetscScalar  none = -1.0,value[3],avalue;
 14:   PetscReal    norm;
 15:   PC           pc;

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

 20:   /* Create vectors */
 21:   VecCreate(PETSC_COMM_WORLD,&x);
 22:   VecSetSizes(x,PETSC_DECIDE,n);
 23:   VecSetFromOptions(x);
 24:   VecDuplicate(x,&b);
 25:   VecDuplicate(x,&u);

 27:   /* create a solution that is orthogonal to the constants */
 28:   VecGetOwnershipRange(u,&i1,&i2);
 29:   for (i=i1; i<i2; i++) {
 30:     avalue = i;
 31:     VecSetValues(u,1,&i,&avalue,INSERT_VALUES);
 32:   }
 33:   VecAssemblyBegin(u);
 34:   VecAssemblyEnd(u);
 35:   VecSum(u,&avalue);
 36:   avalue = -avalue/(PetscReal)n;
 37:   VecShift(&avalue,u);

 39:   /* Create and assemble matrix */
 40:   MatCreate(PETSC_COMM_WORLD,PETSC_DECIDE,PETSC_DECIDE,n,n,&A);
 41:   MatSetFromOptions(A);
 42:   value[0] = -1.0; value[1] = 2.0; value[2] = -1.0;
 43:   for (i=1; i<n-1; i++) {
 44:     col[0] = i-1; col[1] = i; col[2] = i+1;
 45:     MatSetValues(A,1,&i,3,col,value,INSERT_VALUES);
 46:   }
 47:   i = n - 1; col[0] = n - 2; col[1] = n - 1; value[1] = 1.0;
 48:   MatSetValues(A,1,&i,2,col,value,INSERT_VALUES);
 49:   i = 0; col[0] = 0; col[1] = 1; value[0] = 1.0; value[1] = -1.0;
 50:   MatSetValues(A,1,&i,2,col,value,INSERT_VALUES);
 51:   MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
 52:   MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
 53:   MatMult(A,u,b);

 55:   /* Create SLES context; set operators and options; solve linear system */
 56:   SLESCreate(PETSC_COMM_WORLD,&sles);
 57:   SLESSetOperators(sles,A,A,DIFFERENT_NONZERO_PATTERN);

 59:   /* Insure that preconditioner has same null space as matrix */
 60:   SLESGetPC(sles,&pc);

 62:   SLESSetFromOptions(sles);
 63:   SLESSolve(sles,b,x,&its);
 64:   /* SLESView(sles,PETSC_VIEWER_STDOUT_WORLD); */

 66:   /* Check error */
 67:   VecAXPY(&none,u,x);
 68:   VecNorm(x,NORM_2,&norm);
 69:   PetscPrintf(PETSC_COMM_WORLD,"Norm of error %A, Iterations %dn",norm,its);

 71:   /* Free work space */
 72:   VecDestroy(x);VecDestroy(u);
 73:   VecDestroy(b);MatDestroy(A);
 74:   SLESDestroy(sles);
 75:   PetscFinalize();
 76:   return 0;
 77: }