Actual source code: ex4.c

petsc-3.14.6 2021-03-30
Report Typos and Errors
  1: /*
  2:  *
  3:  *  Created on: Sep 25, 2017
  4:  *      Author: Fande Kong
  5:  */

  7: static char help[] = "Illustrate the use of MatResetPreallocation.\n";

  9: #include "petscmat.h"

 11: int main(int argc,char **argv)
 12: {
 13:   Mat             A;
 14:   MPI_Comm        comm;
 15:   PetscInt        n=5,m=5,*dnnz,*onnz,i,rstart,rend,M,N;
 16:   PetscErrorCode  ierr;

 18:   PetscInitialize(&argc,&argv,0,help);if (ierr) return ierr;
 19:   comm = MPI_COMM_WORLD;
 20:   PetscMalloc2(m,&dnnz,m,&onnz);
 21:   for (i=0; i<m; i++) {
 22:     dnnz[i] = 1;
 23:     onnz[i] = 1;
 24:   }
 25:   MatCreateAIJ(comm,m,n,PETSC_DETERMINE,PETSC_DETERMINE,PETSC_DECIDE,dnnz,PETSC_DECIDE,onnz,&A);
 26:   MatSetFromOptions(A);
 27:   MatSetUp(A);
 28:   PetscFree2(dnnz,onnz);

 30:   /* This assembly shrinks memory because we do not insert enough number of values */
 31:   MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
 32:   MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);

 34:   /* MatResetPreallocation restores the memory required by users */
 35:   MatResetPreallocation(A);
 36:   MatSetOption(A,MAT_NEW_NONZERO_ALLOCATION_ERR,PETSC_TRUE);
 37:   MatGetOwnershipRange(A,&rstart,&rend);
 38:   MatGetSize(A,&M,&N);
 39:   for (i=rstart; i<rend; i++) {
 40:     MatSetValue(A,i,i,2.0,INSERT_VALUES);
 41:     if (rend<N) {
 42:       MatSetValue(A,i,rend,1.0,INSERT_VALUES);
 43:     }
 44:   }
 45:   MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
 46:   MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
 47:   MatView(A,PETSC_VIEWER_STDOUT_WORLD);
 48:   MatDestroy(&A);
 49:   PetscFinalize();
 50:   return ierr;
 51: }

 53: /*TEST

 55:    test:
 56:       suffix: 1

 58:    test:
 59:       suffix: 2
 60:       nsize: 2

 62: TEST*/