Actual source code: ex10.c
2: static char help[] = "Reads a PETSc matrix and vector from a file and solves a linear system.\n\
3: This version first preloads and solves a small system, then loads \n\
4: another (larger) system and solves it as well. This example illustrates\n\
5: preloading of instructions with the smaller system so that more accurate\n\
6: performance monitoring can be done with the larger one (that actually\n\
7: is the system of interest). See the 'Performance Hints' chapter of the\n\
8: users manual for a discussion of preloading. Input parameters include\n\
9: -f0 <input_file> : first file to load (small system)\n\
10: -f1 <input_file> : second file to load (larger system)\n\n\
11: -trans : solve transpose system instead\n\n";
12: /*
13: This code can be used to test PETSc interface to other packages.\n\
14: Examples of command line options: \n\
15: ex10 -f0 <datafile> -ksp_type preonly \n\
16: -help -ksp_view \n\
17: -num_numfac <num_numfac> -num_rhs <num_rhs> \n\
18: -ksp_type preonly -pc_type lu -mat_type aijspooles/superlu/superlu_dist/aijmumps \n\
19: -ksp_type preonly -pc_type cholesky -mat_type sbaijspooles/dscpack/sbaijmumps \n\
20: -f0 <A> -fB <B> -mat_type sbaijmumps -ksp_type preonly -pc_type cholesky -test_inertia -mat_sigma <sigma> \n\
21: mpirun -np <np> ex10 -f0 <datafile> -ksp_type cg -pc_type asm -pc_asm_type basic -sub_pc_type icc -mat_type sbaij
22: \n\n";
23: */
24: /*T
25: Concepts: KSP^solving a linear system
26: Processors: n
27: T*/
29: /*
30: Include "petscksp.h" so that we can use KSP solvers. Note that this file
31: automatically includes:
32: petsc.h - base PETSc routines petscvec.h - vectors
33: petscsys.h - system routines petscmat.h - matrices
34: petscis.h - index sets petscksp.h - Krylov subspace methods
35: petscviewer.h - viewers petscpc.h - preconditioners
36: */
37: #include petscksp.h
41: int main(int argc,char **args)
42: {
43: KSP ksp; /* linear solver context */
44: Mat A,B; /* matrix */
45: Vec x,b,u; /* approx solution, RHS, exact solution */
46: PetscViewer fd; /* viewer */
47: char file[3][PETSC_MAX_PATH_LEN]; /* input file name */
48: PetscTruth table,flg,flgB=PETSC_FALSE,trans=PETSC_FALSE,partition=PETSC_FALSE;
50: PetscInt its,num_numfac;
51: PetscReal norm;
52: PetscLogDouble tsetup,tsetup1,tsetup2,tsolve,tsolve1,tsolve2;
53: PetscTruth preload=PETSC_TRUE,diagonalscale,isSymmetric,cknorm=PETSC_FALSE,Test_MatDuplicate=PETSC_FALSE;
54: PetscMPIInt rank;
55: PetscScalar sigma;
57: PetscInitialize(&argc,&args,(char *)0,help);
58: MPI_Comm_rank(PETSC_COMM_WORLD,&rank);
59: PetscOptionsHasName(PETSC_NULL,"-table",&table);
60: PetscOptionsHasName(PETSC_NULL,"-trans",&trans);
61: PetscOptionsHasName(PETSC_NULL,"-partition",&partition);
63: /*
64: Determine files from which we read the two linear systems
65: (matrix and right-hand-side vector).
66: */
67: PetscOptionsGetString(PETSC_NULL,"-f",file[0],PETSC_MAX_PATH_LEN-1,&flg);
68: if (flg) {
69: PetscStrcpy(file[1],file[0]);
70: preload = PETSC_FALSE;
71: } else {
72: PetscOptionsGetString(PETSC_NULL,"-f0",file[0],PETSC_MAX_PATH_LEN-1,&flg);
73: if (!flg) SETERRQ(1,"Must indicate binary file with the -f0 or -f option");
74: PetscOptionsGetString(PETSC_NULL,"-f1",file[1],PETSC_MAX_PATH_LEN-1,&flg);
75: if (!flg) {preload = PETSC_FALSE;} /* don't bother with second system */
76: }
78: /* -----------------------------------------------------------
79: Beginning of linear solver loop
80: ----------------------------------------------------------- */
81: /*
82: Loop through the linear solve 2 times.
83: - The intention here is to preload and solve a small system;
84: then load another (larger) system and solve it as well.
85: This process preloads the instructions with the smaller
86: system so that more accurate performance monitoring (via
87: -log_summary) can be done with the larger one (that actually
88: is the system of interest).
89: */
90: PreLoadBegin(preload,"Load system");
92: /* - - - - - - - - - - - New Stage - - - - - - - - - - - - -
93: Load system
94: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
96: /*
97: Open binary file. Note that we use FILE_MODE_READ to indicate
98: reading from this file.
99: */
100: PetscViewerBinaryOpen(PETSC_COMM_WORLD,file[PreLoadIt],FILE_MODE_READ,&fd);
101:
102: /*
103: Load the matrix and vector; then destroy the viewer.
104: */
105: MatLoad(fd,MATAIJ,&A);
106:
107: if (!preload){
108: flg = PETSC_FALSE;
109: PetscOptionsGetString(PETSC_NULL,"-rhs",file[2],PETSC_MAX_PATH_LEN-1,&flg);
110: if (flg){ /* rhs is stored in a separate file */
111: PetscViewerDestroy(fd);
112: PetscViewerBinaryOpen(PETSC_COMM_WORLD,file[2],FILE_MODE_READ,&fd);
113: }
114: }
115: if (rank){
116: PetscExceptionTry1(VecLoad(fd,PETSC_NULL,&b),PETSC_ERR_FILE_UNEXPECTED);
117: } else {
118: PetscExceptionTry1(VecLoad(fd,PETSC_NULL,&b),PETSC_ERR_FILE_READ);
119: }
120: if (PetscExceptionCaught(ierr,PETSC_ERR_FILE_UNEXPECTED) || PetscExceptionCaught(ierr,PETSC_ERR_FILE_READ)) { /* if file contains no RHS, then use a vector of all ones */
121: PetscInt m;
122: PetscScalar one = 1.0;
123: PetscInfo(0,"Using vector of ones for RHS\n");
124: MatGetLocalSize(A,&m,PETSC_NULL);
125: VecCreate(PETSC_COMM_WORLD,&b);
126: VecSetSizes(b,m,PETSC_DECIDE);
127: VecSetFromOptions(b);
128: VecSet(b,one);
129: } else
130: PetscViewerDestroy(fd);
132: /* Test MatDuplicate() */
133: if (Test_MatDuplicate){
134: MatDuplicate(A,MAT_COPY_VALUES,&B);
135: MatEqual(A,B,&flg);
136: if (!flg){
137: PetscPrintf(PETSC_COMM_WORLD," A != B \n");
138: }
139: MatDestroy(B);
140: }
142: /* Add a shift to A */
143: PetscOptionsGetScalar(PETSC_NULL,"-mat_sigma",&sigma,&flg);
144: if(flg) {
145: PetscOptionsGetString(PETSC_NULL,"-fB",file[2],PETSC_MAX_PATH_LEN-1,&flgB);
146: if (flgB){
147: /* load B to get A = A + sigma*B */
148: PetscViewerBinaryOpen(PETSC_COMM_WORLD,file[2],FILE_MODE_READ,&fd);
149: MatLoad(fd,MATAIJ,&B);
150: PetscViewerDestroy(fd);
151: MatAXPY(A,sigma,B,DIFFERENT_NONZERO_PATTERN); /* A <- sigma*B + A */
152: } else {
153: MatShift(A,sigma);
154: }
155: }
157: /* Make A singular for testing zero-pivot of ilu factorization */
158: /* Example: ./ex10 -f0 <datafile> -test_zeropivot -set_row_zero -pc_factor_shift_nonzero */
159: PetscOptionsHasName(PETSC_NULL, "-test_zeropivot", &flg);
160: if (flg) {
161: PetscInt row,ncols;
162: const PetscInt *cols;
163: const PetscScalar *vals;
164: PetscTruth flg1=PETSC_FALSE;
165: PetscScalar *zeros;
166: row = 0;
167: MatGetRow(A,row,&ncols,&cols,&vals);
168: PetscMalloc(sizeof(PetscScalar)*(ncols+1),&zeros);
169: PetscMemzero(zeros,(ncols+1)*sizeof(PetscScalar));
170: PetscOptionsHasName(PETSC_NULL, "-set_row_zero", &flg1);
171: if (flg1){ /* set entire row as zero */
172: MatSetValues(A,1,&row,ncols,cols,zeros,INSERT_VALUES);
173: } else { /* only set (row,row) entry as zero */
174: MatSetValues(A,1,&row,1,&row,zeros,INSERT_VALUES);
175: }
176: MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
177: MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
178: }
180: /* Check whether A is symmetric */
181: PetscOptionsHasName(PETSC_NULL, "-check_symmetry", &flg);
182: if (flg) {
183: Mat Atrans;
184: MatTranspose(A, &Atrans);
185: MatEqual(A, Atrans, &isSymmetric);
186: if (isSymmetric) {
187: PetscPrintf(PETSC_COMM_WORLD,"A is symmetric \n");
188: } else {
189: PetscPrintf(PETSC_COMM_WORLD,"A is non-symmetric \n");
190: }
191: MatDestroy(Atrans);
192: }
194: /*
195: If the loaded matrix is larger than the vector (due to being padded
196: to match the block size of the system), then create a new padded vector.
197: */
198: {
199: PetscInt m,n,j,mvec,start,end,indx;
200: Vec tmp;
201: PetscScalar *bold;
203: /* Create a new vector b by padding the old one */
204: MatGetLocalSize(A,&m,&n);
205: if (m != n) {
206: SETERRQ2(PETSC_ERR_ARG_SIZ, "This example is not intended for rectangular matrices (%d, %d)", m, n);
207: }
208: VecCreate(PETSC_COMM_WORLD,&tmp);
209: VecSetSizes(tmp,m,PETSC_DECIDE);
210: VecSetFromOptions(tmp);
211: VecGetOwnershipRange(b,&start,&end);
212: VecGetLocalSize(b,&mvec);
213: VecGetArray(b,&bold);
214: for (j=0; j<mvec; j++) {
215: indx = start+j;
216: VecSetValues(tmp,1,&indx,bold+j,INSERT_VALUES);
217: }
218: VecRestoreArray(b,&bold);
219: VecDestroy(b);
220: VecAssemblyBegin(tmp);
221: VecAssemblyEnd(tmp);
222: b = tmp;
223: }
224: VecDuplicate(b,&x);
225: VecDuplicate(b,&u);
226: VecSet(x,0.0);
228: /* - - - - - - - - - - - New Stage - - - - - - - - - - - - -
229: Setup solve for system
230: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
233: if (partition) {
234: MatPartitioning mpart;
235: IS mis,nis,isn,is;
236: PetscInt *count;
237: PetscMPIInt size;
238: Mat BB;
239: MPI_Comm_size(PETSC_COMM_WORLD,&size);
240: MPI_Comm_rank(PETSC_COMM_WORLD,&rank);
241: PetscMalloc(size*sizeof(PetscInt),&count);
242: MatPartitioningCreate(PETSC_COMM_WORLD, &mpart);
243: MatPartitioningSetAdjacency(mpart, A);
244: /* MatPartitioningSetVertexWeights(mpart, weight); */
245: MatPartitioningSetFromOptions(mpart);
246: MatPartitioningApply(mpart, &mis);
247: MatPartitioningDestroy(mpart);
248: ISPartitioningToNumbering(mis,&nis);
249: ISPartitioningCount(mis,count);
250: ISDestroy(mis);
251: ISInvertPermutation(nis, count[rank], &is);
252: PetscFree(count);
253: ISDestroy(nis);
254: ISSort(is);
255: ISAllGather(is,&isn);
256: MatGetSubMatrix(A,is,isn,PETSC_DECIDE,MAT_INITIAL_MATRIX,&BB);
258: /* need to move the vector also */
259: ISDestroy(is);
260: ISDestroy(isn);
261: MatDestroy(A);
262: A = BB;
263: }
264:
265: /*
266: Conclude profiling last stage; begin profiling next stage.
267: */
268: PreLoadStage("KSPSetUp");
270: /*
271: We also explicitly time this stage via PetscGetTime()
272: */
273: PetscGetTime(&tsetup1);
275: /*
276: Create linear solver; set operators; set runtime options.
277: */
278: KSPCreate(PETSC_COMM_WORLD,&ksp);
280: num_numfac = 1;
281: PetscOptionsGetInt(PETSC_NULL,"-num_numfac",&num_numfac,PETSC_NULL);
282: while ( num_numfac-- ){
283: /* KSPSetOperators(ksp,A,A,DIFFERENT_NONZERO_PATTERN); */
284: KSPSetOperators(ksp,A,A,SAME_NONZERO_PATTERN);
285: KSPSetFromOptions(ksp);
287: /*
288: Here we explicitly call KSPSetUp() and KSPSetUpOnBlocks() to
289: enable more precise profiling of setting up the preconditioner.
290: These calls are optional, since both will be called within
291: KSPSolve() if they haven't been called already.
292: */
293: KSPSetUp(ksp);
294: KSPSetUpOnBlocks(ksp);
295: PetscGetTime(&tsetup2);
296: tsetup = tsetup2 - tsetup1;
298: /*
299: Test MatGetInertia()
300: Usage:
301: ex10 -f0 <mat_binaryfile> -ksp_type preonly -pc_type cholesky -mat_type seqsbaij -test_inertia -mat_sigma <sigma>
302: */
303: PetscOptionsHasName(PETSC_NULL,"-test_inertia",&flg);
304: if (flg){
305: PC pc;
306: PetscInt nneg, nzero, npos;
307: Mat F;
308:
309: KSPGetPC(ksp,&pc);
310: PCGetFactoredMatrix(pc,&F);
311: MatGetInertia(F,&nneg,&nzero,&npos);
312: PetscPrintf(PETSC_COMM_SELF," MatInertia: nneg: %D, nzero: %D, npos: %D\n",nneg,nzero,npos);
313: }
315: /*
316: Tests "diagonal-scaling of preconditioned residual norm" as used
317: by many ODE integrator codes including SUNDIALS. Note this is different
318: than diagonally scaling the matrix before computing the preconditioner
319: */
320: PetscOptionsHasName(PETSC_NULL,"-diagonal_scale",&diagonalscale);
321: if (diagonalscale) {
322: PC pc;
323: PetscInt j,start,end,n;
324: Vec scale;
325:
326: KSPGetPC(ksp,&pc);
327: VecGetSize(x,&n);
328: VecDuplicate(x,&scale);
329: VecGetOwnershipRange(scale,&start,&end);
330: for (j=start; j<end; j++) {
331: VecSetValue(scale,j,((PetscReal)(j+1))/((PetscReal)n),INSERT_VALUES);
332: }
333: VecAssemblyBegin(scale);
334: VecAssemblyEnd(scale);
335: PCDiagonalScaleSet(pc,scale);
336: VecDestroy(scale);
338: }
340: /* - - - - - - - - - - - New Stage - - - - - - - - - - - - -
341: Solve system
342: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
344: /*
345: Begin profiling next stage
346: */
347: PreLoadStage("KSPSolve");
349: /*
350: Solve linear system; we also explicitly time this stage.
351: */
352: PetscGetTime(&tsolve1);
353: if (trans) {
354: KSPSolveTranspose(ksp,b,x);
355: KSPGetIterationNumber(ksp,&its);
356: } else {
357: PetscInt num_rhs=1;
358: PetscOptionsGetInt(PETSC_NULL,"-num_rhs",&num_rhs,PETSC_NULL);
359: PetscOptionsHasName(PETSC_NULL,"-cknorm",&cknorm);
360: while ( num_rhs-- ) {
361: KSPSolve(ksp,b,x);
362: }
363: KSPGetIterationNumber(ksp,&its);
364: if (cknorm){ /* Check error for each rhs */
365: if (trans) {
366: MatMultTranspose(A,x,u);
367: } else {
368: MatMult(A,x,u);
369: }
370: VecAXPY(u,-1.0,b);
371: VecNorm(u,NORM_2,&norm);
372: PetscPrintf(PETSC_COMM_WORLD," Number of iterations = %3D\n",its);
373: PetscPrintf(PETSC_COMM_WORLD," Residual norm %A\n",norm);
374: }
375: } /* while ( num_rhs-- ) */
376: PetscGetTime(&tsolve2);
377: tsolve = tsolve2 - tsolve1;
379: /*
380: Conclude profiling this stage
381: */
382: PreLoadStage("Cleanup");
384: /* - - - - - - - - - - - New Stage - - - - - - - - - - - - -
385: Check error, print output, free data structures.
386: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
388: /*
389: Check error
390: */
391: if (trans) {
392: MatMultTranspose(A,x,u);
393: } else {
394: MatMult(A,x,u);
395: }
396: VecAXPY(u,-1.0,b);
397: VecNorm(u,NORM_2,&norm);
399: /*
400: Write output (optinally using table for solver details).
401: - PetscPrintf() handles output for multiprocessor jobs
402: by printing from only one processor in the communicator.
403: - KSPView() prints information about the linear solver.
404: */
405: if (table) {
406: char *matrixname,kspinfo[120];
407: PetscViewer viewer;
409: /*
410: Open a string viewer; then write info to it.
411: */
412: PetscViewerStringOpen(PETSC_COMM_WORLD,kspinfo,120,&viewer);
413: KSPView(ksp,viewer);
414: PetscStrrchr(file[PreLoadIt],'/',&matrixname);
415: PetscPrintf(PETSC_COMM_WORLD,"%-8.8s %3D %2.0e %2.1e %2.1e %2.1e %s \n",
416: matrixname,its,norm,tsetup+tsolve,tsetup,tsolve,kspinfo);
418: /*
419: Destroy the viewer
420: */
421: PetscViewerDestroy(viewer);
422: } else {
423: PetscPrintf(PETSC_COMM_WORLD,"Number of iterations = %3D\n",its);
424: PetscPrintf(PETSC_COMM_WORLD,"Residual norm %A\n",norm);
425: }
427: PetscOptionsHasName(PETSC_NULL, "-ksp_reason", &flg);
428: if (flg){
429: KSPConvergedReason reason;
430: KSPGetConvergedReason(ksp,&reason);
431: PetscPrintf(PETSC_COMM_WORLD,"KSPConvergedReason: %D\n", reason);
432: }
433:
434: } /* while ( num_numfac-- ) */
436: /*
437: Free work space. All PETSc objects should be destroyed when they
438: are no longer needed.
439: */
440: MatDestroy(A); VecDestroy(b);
441: VecDestroy(u); VecDestroy(x);
442: KSPDestroy(ksp);
443: if (flgB) { MatDestroy(B); }
444: PreLoadEnd();
445: /* -----------------------------------------------------------
446: End of linear solver loop
447: ----------------------------------------------------------- */
449: PetscFinalize();
450: return 0;
451: }