Actual source code: ex50.c

petsc-3.8.4 2018-03-24
Report Typos and Errors

  2:  #include <petscmat.h>

  4: #if !defined(PETSC_USE_64BIT_INDICES)
  5: static char help[] = "Reads in a matrix and vector in ASCII format. Writes\n\
  6: them using the PETSc sparse format. Input parameters are:\n\
  7:   -fin <filename> : input file\n\
  8:   -fout <filename> : output file\n\n";
  9: #endif


 12: int main(int argc,char **args)
 13: {
 14: #if !defined(PETSC_USE_64BIT_INDICES)
 15:   Mat            A;
 16:   Vec            b;
 17:   char           filein[PETSC_MAX_PATH_LEN],finname[PETSC_MAX_PATH_LEN],fileout[PETSC_MAX_PATH_LEN];
 18:   PetscInt       n,col,row,rowin;
 20:   PetscBool      flg;
 21:   PetscScalar    val,*array;
 22:   FILE           *file;
 23:   PetscViewer    view;

 25:   PetscInitialize(&argc,&args,(char*)0,help);if (ierr) return ierr;
 26:   /* Read in matrix and RHS */
 27:   PetscOptionsGetString(NULL,NULL,"-fin",filein,256,&flg);
 28:   if (!flg) SETERRQ(PETSC_COMM_WORLD,1,"Must indicate file for reading");
 29:   PetscOptionsGetString(NULL,NULL,"-fout",fileout,256,&flg);
 30:   if (!flg) SETERRQ(PETSC_COMM_WORLD,1,"Must indicate file for writing");

 32:   PetscFixFilename(filein,finname);
 33:   if (!(file = fopen(finname,"r"))) SETERRQ(PETSC_COMM_SELF,1,"Cannot open input file\n");
 34:   if (fscanf(file,"%d\n",&n) != 1) SETERRQ(PETSC_COMM_SELF,1,"Badly formatted input file\n");

 36:   MatCreate(PETSC_COMM_WORLD,&A);
 37:   MatSetSizes(A,PETSC_DECIDE,PETSC_DECIDE,n,n);
 38:   MatSetFromOptions(A);
 39:   VecCreate(PETSC_COMM_WORLD,&b);
 40:   VecSetSizes(b,PETSC_DECIDE,n);
 41:   VecSetFromOptions(b);

 43:   for (row=0; row<n; row++) {
 44:     if (fscanf(file,"row %d:",&rowin) != 1) SETERRQ(PETSC_COMM_SELF,1,"Badly formatted input file\n");
 45:     if (rowin != row) SETERRQ(PETSC_COMM_SELF,1,"Bad file");
 46:     while (fscanf(file," %d %le",&col,(double*)&val)) {
 47:       MatSetValues(A,1,&row,1,&col,&val,INSERT_VALUES);
 48:     }
 49:   }
 50:   MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
 51:   MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
 52:   VecGetArray(b,&array);
 53:   for (row=0; row<n; row++) {
 54:     if (fscanf(file," ii= %d %le",&col,(double*)(array+row)) != 2)  SETERRQ(PETSC_COMM_SELF,1,"Badly formatted input file\n");
 55:   }
 56:   VecRestoreArray(b,&array);

 58:   fclose(file);

 60:   PetscPrintf(PETSC_COMM_SELF,"Reading matrix complete.\n");
 61:   PetscViewerBinaryOpen(PETSC_COMM_WORLD,fileout,FILE_MODE_WRITE,&view);
 62:   MatView(A,view);
 63:   VecView(b,view);
 64:   PetscViewerDestroy(&view);

 66:   VecDestroy(&b);
 67:   MatDestroy(&A);
 68:   PetscFinalize();
 69:   return ierr;
 70: #else
 71:   return 0;
 72: #endif
 73: }