Actual source code: ex42.c

petsc-3.7.2 2016-06-05
Report Typos and Errors
  2: static char help[] = "Solves a linear system in parallel with MINRES. Modified from ../tutorials/ex2.c \n\n";

  4: #include <petscksp.h>

  8: int main(int argc,char **args)
  9: {
 10:   Vec            x,b;      /* approx solution, RHS */
 11:   Mat            A;        /* linear system matrix */
 12:   KSP            ksp;      /* linear solver context */
 13:   PetscInt       Ii,Istart,Iend,m = 11;
 15:   PetscScalar    v;

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

 20:   /* Create parallel diagonal matrix */
 21:   MatCreate(PETSC_COMM_WORLD,&A);
 22:   MatSetSizes(A,PETSC_DECIDE,PETSC_DECIDE,m,m);
 23:   MatSetFromOptions(A);
 24:   MatMPIAIJSetPreallocation(A,1,NULL,1,NULL);
 25:   MatSeqAIJSetPreallocation(A,1,NULL);
 26:   MatSetUp(A);
 27:   MatGetOwnershipRange(A,&Istart,&Iend);

 29:   for (Ii=Istart; Ii<Iend; Ii++) {
 30:     v = (PetscReal)Ii+1;
 31:     MatSetValues(A,1,&Ii,1,&Ii,&v,INSERT_VALUES);
 32:   }
 33:   /* Make A sigular */
 34:   Ii = m - 1; /* last diagonal entry */
 35:   v  = 0.0;
 36:   MatSetValues(A,1,&Ii,1,&Ii,&v,INSERT_VALUES);
 37:   MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
 38:   MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);

 40:   /* A is symmetric. Set symmetric flag to enable KSP_type = minres */
 41:   MatSetOption(A,MAT_SYMMETRIC,PETSC_TRUE);

 43:   VecCreate(PETSC_COMM_WORLD,&b);
 44:   VecSetSizes(b,PETSC_DECIDE,m);
 45:   VecSetFromOptions(b);
 46:   VecDuplicate(b,&x);
 47:   VecSet(x,1.0);
 48:   MatMult(A,x,b);
 49:   VecSet(x,0.0);

 51:   /* Create linear solver context */
 52:   KSPCreate(PETSC_COMM_WORLD,&ksp);
 53:   KSPSetOperators(ksp,A,A);
 54:   KSPSetFromOptions(ksp);
 55:   KSPSolve(ksp,b,x);

 57:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 58:                       Check solution and clean up
 59:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
 60:   VecView(x,PETSC_VIEWER_STDOUT_WORLD);

 62:   /* Free work space. */
 63:   KSPDestroy(&ksp);
 64:   VecDestroy(&x);
 65:   VecDestroy(&b);
 66:   MatDestroy(&A);

 68:   PetscFinalize();
 69:   return 0;
 70: }