Actual source code: ex27.c

petsc-3.7.3 2016-08-01
Report Typos and Errors
  2: static char help[] = "Tests repeated use of assembly for matrices.\n\
  3:  does nasty case where matrix must be rebuilt.\n\n";

  5: #include <petscmat.h>

  9: int main(int argc,char **args)
 10: {
 11:   Mat            C;
 12:   PetscInt       i,j,m = 5,n = 2,Ii,J;
 14:   PetscMPIInt    rank,size;
 15:   PetscScalar    v;
 16:   Vec            x,y;

 18:   PetscInitialize(&argc,&args,(char*)0,help);
 19:   MPI_Comm_rank(PETSC_COMM_WORLD,&rank);
 20:   MPI_Comm_size(PETSC_COMM_WORLD,&size);
 21:   n    = 2*size;

 23:   /* Create the matrix for the five point stencil, YET AGAIN */
 24:   MatCreate(PETSC_COMM_WORLD,&C);
 25:   MatSetSizes(C,PETSC_DECIDE,PETSC_DECIDE,m*n,m*n);
 26:   MatSetFromOptions(C);
 27:   for (i=0; i<m; i++) {
 28:     for (j=2*rank; j<2*rank+2; j++) {
 29:       v = -1.0;  Ii = j + n*i;
 30:       if (i>0)   {J = Ii - n; MatSetValues(C,1,&Ii,1,&J,&v,INSERT_VALUES);}
 31:       if (i<m-1) {J = Ii + n; MatSetValues(C,1,&Ii,1,&J,&v,INSERT_VALUES);}
 32:       if (j>0)   {J = Ii - 1; MatSetValues(C,1,&Ii,1,&J,&v,INSERT_VALUES);}
 33:       if (j<n-1) {J = Ii + 1; MatSetValues(C,1,&Ii,1,&J,&v,INSERT_VALUES);}
 34:       v = 4.0; MatSetValues(C,1,&Ii,1,&Ii,&v,INSERT_VALUES);
 35:     }
 36:   }
 37:   MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY);
 38:   MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY);
 39:   for (i=0; i<m; i++) {
 40:     for (j=2*rank; j<2*rank+2; j++) {
 41:       v = 1.0;  Ii = j + n*i;
 42:       if (i>0)   {J = Ii - n; MatSetValues(C,1,&Ii,1,&J,&v,INSERT_VALUES);}
 43:       if (i<m-1) {J = Ii + n; MatSetValues(C,1,&Ii,1,&J,&v,INSERT_VALUES);}
 44:       if (j>0)   {J = Ii - 1; MatSetValues(C,1,&Ii,1,&J,&v,INSERT_VALUES);}
 45:       if (j<n-1) {J = Ii + 1; MatSetValues(C,1,&Ii,1,&J,&v,INSERT_VALUES);}
 46:       v = -4.0; MatSetValues(C,1,&Ii,1,&Ii,&v,INSERT_VALUES);
 47:     }
 48:   }
 49:   /* Introduce new nonzero that requires new construction for
 50:       matrix-vector product */
 51:   if (rank) {
 52:     Ii   = rank-1; J = m*n-1;
 53:     MatSetValues(C,1,&Ii,1,&J,&v,INSERT_VALUES);
 54:   }
 55:   MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY);
 56:   MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY);

 58:   MatView(C,PETSC_VIEWER_STDOUT_WORLD);

 60:   /* Form a couple of vectors to test matrix-vector product */
 61:   VecCreate(PETSC_COMM_WORLD,&x);
 62:   VecSetSizes(x,PETSC_DECIDE,m*n);
 63:   VecSetFromOptions(x);
 64:   VecDuplicate(x,&y);
 65:   v    = 1.0; VecSet(x,v);
 66:   MatMult(C,x,y);

 68:   MatDestroy(&C);
 69:   VecDestroy(&x);
 70:   VecDestroy(&y);
 71:   PetscFinalize();
 72:   return 0;
 73: }