Actual source code: ex50.c
petsc-3.6.1 2015-08-06
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
14: int main(int argc,char **args)
15: {
16: #if !defined(PETSC_USE_64BIT_INDICES)
17: Mat A;
18: Vec b;
19: char filein[PETSC_MAX_PATH_LEN],finname[PETSC_MAX_PATH_LEN],fileout[PETSC_MAX_PATH_LEN];
20: PetscInt n,col,row,rowin;
22: PetscBool flg;
23: PetscScalar val,*array;
24: FILE *file;
25: PetscViewer view;
27: PetscInitialize(&argc,&args,(char*)0,help);
29: /* Read in matrix and RHS */
30: PetscOptionsGetString(NULL,"-fin",filein,256,&flg);
31: if (!flg) SETERRQ(PETSC_COMM_WORLD,1,"Must indicate file for reading");
32: PetscOptionsGetString(NULL,"-fout",fileout,256,&flg);
33: if (!flg) SETERRQ(PETSC_COMM_WORLD,1,"Must indicate file for writing");
35: PetscFixFilename(filein,finname);
36: if (!(file = fopen(finname,"r"))) SETERRQ(PETSC_COMM_SELF,1,"cannot open input file\n");
37: fscanf(file,"%d\n",&n);
39: MatCreate(PETSC_COMM_WORLD,&A);
40: MatSetSizes(A,PETSC_DECIDE,PETSC_DECIDE,n,n);
41: MatSetFromOptions(A);
42: VecCreate(PETSC_COMM_WORLD,&b);
43: VecSetSizes(b,PETSC_DECIDE,n);
44: VecSetFromOptions(b);
46: for (row=0; row<n; row++) {
47: fscanf(file,"row %d:",&rowin);
48: if (rowin != row) SETERRQ(PETSC_COMM_SELF,1,"Bad file");
49: while (fscanf(file," %d %le",&col,(double*)&val)) {
50: MatSetValues(A,1,&row,1,&col,&val,INSERT_VALUES);
51: }
52: }
53: MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
54: MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
55: VecGetArray(b,&array);
56: for (row=0; row<n; row++) {
57: fscanf(file," ii= %d %le",&col,(double*)(array+row));
58: }
59: VecRestoreArray(b,&array);
61: fclose(file);
63: PetscPrintf(PETSC_COMM_SELF,"Reading matrix complete.\n");
64: PetscViewerBinaryOpen(PETSC_COMM_WORLD,fileout,FILE_MODE_WRITE,&view);
65: MatView(A,view);
66: VecView(b,view);
67: PetscViewerDestroy(&view);
69: VecDestroy(&b);
70: MatDestroy(&A);
72: PetscFinalize();
73: #endif
74: return 0;
75: }