Actual source code: ex72.c
petsc-3.4.5 2014-06-29
2: #include <petscmat.h>
4: #if !defined(PETSC_USE_COMPLEX)
6: static char help[] = "Reads in a Symmetric matrix in MatrixMarket format. Writes\n\
7: it using the PETSc sparse format. It also adds a Vector set to random values to the\n\
8: output file. Input parameters are:\n\
9: -fin <filename> : input file\n\
10: -fout <filename> : output file\n\n";
14: int main(int argc,char **args)
15: {
16: Mat A;
17: Vec b;
18: char filein[PETSC_MAX_PATH_LEN],fileout[PETSC_MAX_PATH_LEN],buf[PETSC_MAX_PATH_LEN];
19: PetscInt i,m,n,nnz,col,row;
21: PetscMPIInt size;
22: PetscScalar val;
23: FILE *file;
24: PetscViewer view;
25: PetscRandom r;
27: PetscInitialize(&argc,&args,(char*)0,help);
29: MPI_Comm_size(PETSC_COMM_WORLD,&size);
30: if (size > 1) SETERRQ(PETSC_COMM_WORLD,1,"Uniprocessor Example only\n");
32: /* Read in matrix and RHS */
33: PetscOptionsGetString(NULL,"-fin",filein,PETSC_MAX_PATH_LEN,NULL);
34: PetscFOpen(PETSC_COMM_SELF,filein,"r",&file);
36: /* process header with comments */
37: do fgets(buf,PETSC_MAX_PATH_LEN-1,file);
38: while (buf[0] == '%');
40: /* The first non-comment line has the matrix dimensions */
41: sscanf(buf,"%d %d %d\n",&m,&n,&nnz);
42: printf ("m = %d, n = %d, nnz = %d\n",m,n,nnz);
44: MatCreateSeqAIJ(PETSC_COMM_WORLD,m,n,nnz*2/m,0,&A);
45: MatSetOption(A,MAT_NEW_NONZERO_ALLOCATION_ERR,PETSC_FALSE);
46: VecCreate(PETSC_COMM_WORLD,&b);
47: VecSetSizes(b,PETSC_DECIDE,n);
48: VecSetFromOptions(b);
49: PetscRandomCreate(PETSC_COMM_SELF,&r);
50: PetscRandomSetFromOptions(r);
51: VecSetRandom(b,r);
53: for (i=0; i<nnz; i++) {
54: fscanf(file,"%d %d %le\n",&row,&col,(double*)&val);
55: row = row-1; col = col-1;
56: MatSetValues(A,1,&row,1,&col,&val,INSERT_VALUES);
57: if (row != col) {
58: MatSetValues(A,1,&col,1,&row,&val,INSERT_VALUES);
59: }
60: }
61: fclose(file);
63: MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
64: MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
66: PetscPrintf(PETSC_COMM_SELF,"Reading matrix completes.\n");
67: PetscOptionsGetString(NULL,"-fout",fileout,PETSC_MAX_PATH_LEN,NULL);
68: PetscViewerBinaryOpen(PETSC_COMM_WORLD,fileout,FILE_MODE_WRITE,&view);
69: MatView(A,view);
70: VecView(b,view);
71: PetscViewerDestroy(&view);
73: VecDestroy(&b);
74: MatDestroy(&A);
75: PetscRandomDestroy(&r);
77: PetscFinalize();
78: return 0;
79: }
80: #else
82: int main(int argc,char **args)
83: {
84: fprintf(stdout,"This example does not work for complex numbers.\n");
85: return 0;
86: }
87: #endif