Actual source code: ex50.c

  2: static char help[] = "Reads in a matrix and vector in ASCII format. Writes\n\
  3: them using the PETSc sparse format. Input parameters are:\n\
  4:   -fin <filename> : input file\n\
  5:   -fout <filename> : output file\n\n";

 7:  #include petscmat.h

 11: int main(int argc,char **args)
 12: {
 13:   Mat            A;
 14:   Vec            b;
 15:   char           filein[PETSC_MAX_PATH_LEN],finname[PETSC_MAX_PATH_LEN],fileout[PETSC_MAX_PATH_LEN];
 16:   PetscInt       n,col,row,rowin;
 18:   PetscTruth     flg;
 19:   PetscScalar    val,*array;
 20:   FILE*          file;
 21:   PetscViewer    view;

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

 25:   /* Read in matrix and RHS */
 26:   PetscOptionsGetString(PETSC_NULL,"-fin",filein,255,&flg);
 27:   if (!flg) SETERRQ(1,"Must indicate file for reading");
 28:   PetscOptionsGetString(PETSC_NULL,"-fout",fileout,255,&flg);
 29:   if (!flg) SETERRQ(1,"Must indicate file for writing");

 31:   PetscFixFilename(filein,finname);
 32:   if (!(file = fopen(finname,"r"))) {
 33:     SETERRQ(1,"cannot open input file\n");
 34:   }
 35:   fscanf(file,"%d\n",&n);

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

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

 59:   fclose(file);

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

 67:   VecDestroy(b);
 68:   MatDestroy(A);

 70:   PetscFinalize();
 71:   return 0;
 72: }