Actual source code: ex55.c

petsc-3.12.2 2019-11-22
Report Typos and Errors
  1: static const char help[]="Example demonstrating PCCOMPOSITE where one of the inner PCs uses a different operator\n\
  2: \n";

  4: /*T
  5:    Concepts: KSP^using nested solves
  6:    Concepts: PC^using composite PCs
  7:    Processors: n
  8: T*/
  9:  #include <petscksp.h>

 11: int main(int argc, char **argv)
 12: {
 14:   PetscInt       n=10,i,col[3];
 15:   Vec            x,b;
 16:   Mat            A,B;
 17:   KSP            ksp;
 18:   PC             pc,subpc;
 19:   PetscScalar    value[3];

 21:   PetscInitialize(&argc,&argv,(char*)0,help);if (ierr) return ierr;

 23:   /* Create a diagonal matrix with a given distribution of diagonal elements */
 24:   MatCreate(PETSC_COMM_WORLD,&A);
 25:   MatSetSizes(A,PETSC_DECIDE,PETSC_DECIDE,n,n);
 26:   MatSetFromOptions(A);
 27:   MatSetUp(A);
 28:    /*
 29:      Assemble matrix
 30:   */
 31:   value[0] = -1.0; value[1] = 2.0; value[2] = -1.0;
 32:   for (i=1; i<n-1; i++) {
 33:     col[0] = i-1; col[1] = i; col[2] = i+1;
 34:     MatSetValues(A,1,&i,3,col,value,INSERT_VALUES);
 35:   }
 36:   i    = n - 1; col[0] = n - 2; col[1] = n - 1;
 37:   MatSetValues(A,1,&i,2,col,value,INSERT_VALUES);
 38:   i    = 0; col[0] = 0; col[1] = 1; value[0] = 2.0; value[1] = -1.0;
 39:   MatSetValues(A,1,&i,2,col,value,INSERT_VALUES);
 40:   MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
 41:   MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
 42: 
 43:   MatCreateVecs(A,&x,&b);

 45:   /* Create a KSP object */
 46:   KSPCreate(PETSC_COMM_WORLD,&ksp);
 47:   KSPSetOperators(ksp,A,A);

 49:   /* Set up a composite preconditioner */
 50:   KSPGetPC(ksp,&pc);
 51:   PCSetType(pc,PCCOMPOSITE); /* default composite with single Identity PC */
 52:   PCCompositeSetType(pc,PC_COMPOSITE_ADDITIVE);
 53:   PCCompositeAddPC(pc,PCLU);
 54:   PCCompositeGetPC(pc,0,&subpc);
 55:   /*  B is set to the diagonal of A; this demonstrates that setting the operator for a subpc changes the preconditioning */
 56:   MatDuplicate(A,MAT_DO_NOT_COPY_VALUES,&B);
 57:   MatGetDiagonal(A,b);
 58:   MatDiagonalSet(B,b,ADD_VALUES);
 59:   PCSetOperators(subpc,B,B);
 60:   PCCompositeAddPC(pc,PCNONE);

 62:   KSPSetFromOptions(ksp);
 63:   KSPSolve(ksp,b,x);

 65:   KSPDestroy(&ksp);
 66:   MatDestroy(&A);
 67:   MatDestroy(&B);
 68:   VecDestroy(&x);
 69:   VecDestroy(&b);
 70:   PetscFinalize();
 71:   return ierr;
 72: }

 74: /*TEST

 76:    test:
 77:      args: -ksp_monitor -pc_composite_type multiplicative

 79: TEST*/