Actual source code: ex18.c

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

  3: #if !defined(PETSC_USE_COMPLEX)

  5: static char help[] = "Reads a PETSc matrix and vector from a file and solves a linear system.n
  6: Input arguments are:n
  7:   -f <input_file> : file to load.  For a 5X5 example of the 5-pt. stencil,n
  8:                     use the file petsc/src/mat/examples/matbinary.exnn";

 10:  #include petscmat.h
 11:  #include petscsles.h

 13: int main(int argc,char **args)
 14: {
 15:   int            ierr,its,m,n,mvec;
 16:   PetscLogDouble time1,time2,time;
 17:   PetscReal      norm;
 18:   PetscScalar    zero = 0.0,none = -1.0;
 19:   Vec            x,b,u;
 20:   Mat            A;
 21:   SLES           sles;
 22:   char           file[128];
 23:   PetscViewer    fd;

 25:   PetscInitialize(&argc,&args,(char *)0,help);

 27:   /* Read matrix and RHS */
 28:   PetscOptionsGetString(PETSC_NULL,"-f",file,127,PETSC_NULL);
 29:   PetscViewerBinaryOpen(PETSC_COMM_WORLD,file,PETSC_BINARY_RDONLY,&fd);
 30:   MatLoad(fd,MATSEQAIJ,&A);
 31:   VecLoad(fd,&b);
 32:   PetscViewerDestroy(fd);

 34:   /* 
 35:      If the load matrix is larger then the vector, due to being padded 
 36:      to match the blocksize then create a new padded vector
 37:   */
 38:   MatGetSize(A,&m,&n);
 39:   VecGetSize(b,&mvec);
 40:   if (m > mvec) {
 41:     Vec    tmp;
 42:     PetscScalar *bold,*bnew;
 43:     /* create a new vector b by padding the old one */
 44:     VecCreate(PETSC_COMM_WORLD,&tmp);
 45:     VecSetSizes(tmp,PETSC_DECIDE,m);
 46:     VecSetFromOptions(tmp);
 47:     VecGetArray(tmp,&bnew);
 48:     VecGetArray(b,&bold);
 49:     PetscMemcpy(bnew,bold,mvec*sizeof(PetscScalar));
 50:     VecDestroy(b);
 51:     b = tmp;
 52:   }

 54:   /* Set up solution */
 55:   VecDuplicate(b,&x);
 56:   VecDuplicate(b,&u);
 57:   VecSet(&zero,x);

 59:   /* Solve system */
 60:   PetscLogStagePush(1);
 61:   SLESCreate(PETSC_COMM_WORLD,&sles);
 62:   SLESSetOperators(sles,A,A,DIFFERENT_NONZERO_PATTERN);
 63:   SLESSetFromOptions(sles);
 64:   PetscGetTime(&time1);
 65:   SLESSolve(sles,b,x,&its);
 66:   PetscGetTime(&time2);
 67:   time = time2 - time1;
 68:   PetscLogStagePop();

 70:   /* Show result */
 71:   MatMult(A,x,u);
 72:   VecAXPY(&none,b,u);
 73:   VecNorm(u,NORM_2,&norm);
 74:   PetscPrintf(PETSC_COMM_WORLD,"Number of iterations = %3dn",its);
 75:   PetscPrintf(PETSC_COMM_WORLD,"Residual norm %An",norm);
 76:   PetscPrintf(PETSC_COMM_WORLD,"Time for solve = %5.2f secondsn",time);

 78:   /* Cleanup */
 79:   SLESDestroy(sles);
 80:   VecDestroy(x);
 81:   VecDestroy(b);
 82:   VecDestroy(u);
 83:   MatDestroy(A);

 85:   PetscFinalize();
 86:   return 0;
 87: }

 89: #else
 90: #include <stdio.h>
 91: int main(int argc,char **args)
 92: {
 93:   fprintf(stdout,"This example does not work for complex numbers.n");
 94:   return 0;
 95: }
 96: #endif