Actual source code: ex50.c
petsc-3.9.4 2018-09-11
2: /*T
3: requires: !complex
4: T*/
6: #include <petscmat.h>
8: #if !defined(PETSC_USE_64BIT_INDICES)
9: static char help[] = "Reads in a matrix and vector in ASCII format. Writes\n\
10: them using the PETSc sparse format. Input parameters are:\n\
11: -fin <filename> : input file\n\
12: -fout <filename> : output file\n\n";
13: #endif
16: int main(int argc,char **args)
17: {
18: #if !defined(PETSC_USE_64BIT_INDICES)
19: Mat A;
20: Vec b;
21: char filein[PETSC_MAX_PATH_LEN],finname[PETSC_MAX_PATH_LEN],fileout[PETSC_MAX_PATH_LEN];
22: PetscInt n,col,row,rowin;
24: PetscBool flg;
25: PetscScalar val,*array;
26: FILE *file;
27: PetscViewer view;
29: PetscInitialize(&argc,&args,(char*)0,help);if (ierr) return ierr;
30: /* Read in matrix and RHS */
31: PetscOptionsGetString(NULL,NULL,"-fin",filein,256,&flg);
32: if (!flg) SETERRQ(PETSC_COMM_WORLD,1,"Must indicate file for reading");
33: PetscOptionsGetString(NULL,NULL,"-fout",fileout,256,&flg);
34: if (!flg) SETERRQ(PETSC_COMM_WORLD,1,"Must indicate file for writing");
36: PetscFixFilename(filein,finname);
37: if (!(file = fopen(finname,"r"))) SETERRQ(PETSC_COMM_SELF,1,"Cannot open input file\n");
38: if (fscanf(file,"%d\n",&n) != 1) SETERRQ(PETSC_COMM_SELF,1,"Badly formatted input file\n");
40: MatCreate(PETSC_COMM_WORLD,&A);
41: MatSetSizes(A,PETSC_DECIDE,PETSC_DECIDE,n,n);
42: MatSetFromOptions(A);
43: VecCreate(PETSC_COMM_WORLD,&b);
44: VecSetSizes(b,PETSC_DECIDE,n);
45: VecSetFromOptions(b);
47: for (row=0; row<n; row++) {
48: if (fscanf(file,"row %d:",&rowin) != 1) SETERRQ(PETSC_COMM_SELF,1,"Badly formatted input file\n");
49: if (rowin != row) SETERRQ(PETSC_COMM_SELF,1,"Bad file");
50: while (fscanf(file," %d %le",&col,(double*)&val)) {
51: MatSetValues(A,1,&row,1,&col,&val,INSERT_VALUES);
52: }
53: }
54: MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
55: MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
56: VecGetArray(b,&array);
57: for (row=0; row<n; row++) {
58: if (fscanf(file," ii= %d %le",&col,(double*)(array+row)) != 2) SETERRQ(PETSC_COMM_SELF,1,"Badly formatted input file\n");
59: }
60: VecRestoreArray(b,&array);
62: fclose(file);
64: PetscPrintf(PETSC_COMM_SELF,"Reading matrix complete.\n");
65: PetscViewerBinaryOpen(PETSC_COMM_WORLD,fileout,FILE_MODE_WRITE,&view);
66: MatView(A,view);
67: VecView(b,view);
68: PetscViewerDestroy(&view);
70: VecDestroy(&b);
71: MatDestroy(&A);
72: PetscFinalize();
73: return ierr;
74: #else
75: return 0;
76: #endif
77: }
81: /*TEST
83: test:
84: TODO: need to provide ASCII matrix to read in
86: TEST*/