Actual source code: ex30.c

  1: static char help[] = "Reads a PETSc matrix and vector from a file and solves a linear system.\n\
  2: It is copied and intended to move dirty codes from ksp/tutorials/ex10.c and simplify ex10.c.\n\
  3:   Input parameters include\n\
  4:   -f0 <input_file> : first file to load (small system)\n\
  5:   -f1 <input_file> : second file to load (larger system)\n\n\
  6:   -trans  : solve transpose system instead\n\n";
  7: /*
  8:   This code  can be used to test PETSc interface to other packages.\n\
  9:   Examples of command line options:       \n\
 10:    ex30 -f0 <datafile> -ksp_type preonly  \n\
 11:         -help -ksp_view                  \n\
 12:         -num_numfac <num_numfac> -num_rhs <num_rhs> \n\
 13:         -ksp_type preonly -pc_type lu -pc_factor_mat_solver_type superlu or superlu_dist or mumps \n\
 14:         -ksp_type preonly -pc_type cholesky -pc_factor_mat_solver_type mumps \n\
 15:    mpiexec -n <np> ex30 -f0 <datafile> -ksp_type cg -pc_type asm -pc_asm_type basic -sub_pc_type icc -mat_type sbaij

 17:    ./ex30 -f0 $D/small -mat_sigma -3.999999999999999 -ksp_type fgmres -pc_type lu -pc_factor_mat_solver_type superlu -mat_superlu_conditionnumber -ckerror -mat_superlu_diagpivotthresh 0
 18:    ./ex30 -f0 $D/small -mat_sigma -3.999999999999999 -ksp_type fgmres -pc_type hypre -pc_hypre_type boomeramg -ksp_type fgmres -ckError
 19:    ./ex30 -f0 $D/small -mat_sigma -3.999999999999999 -ksp_type fgmres -pc_type lu -pc_factor_mat_solver_type petsc -pc_factor_shift_type NONZERO -pc_factor_shift_amount 1.e-5 -ckerror
 20:  \n\n";
 21: */

 23: #include <petscksp.h>
 24: /*
 25:   Include "petscpreload.h" so that we can use the PetscPreload API for careful profiling
 26: */
 27: #include <petscpreload.h>

 29: int main(int argc, char **args)
 30: {
 31:   KSP         ksp;
 32:   Mat         A, B;
 33:   Vec         x, b, u, b2;                 /* approx solution, RHS, exact solution */
 34:   PetscViewer fd;                          /* viewer */
 35:   char        file[4][PETSC_MAX_PATH_LEN]; /* input file name */
 36:   PetscBool   table = PETSC_FALSE, flg, flgB = PETSC_FALSE, trans = PETSC_FALSE, partition = PETSC_FALSE, initialguess = PETSC_FALSE;
 37:   PetscBool   outputSoln = PETSC_FALSE;
 38:   PetscInt    its, num_numfac;
 39:   PetscReal   rnorm, enorm;
 40:   PetscBool   preload = PETSC_TRUE, isSymmetric, ckrnorm = PETSC_TRUE, Test_MatDuplicate = PETSC_FALSE, ckerror = PETSC_FALSE;
 41:   PetscMPIInt rank;
 42:   PetscScalar sigma;
 43:   PetscInt    m;

 45:   PetscFunctionBeginUser;
 46:   PetscCall(PetscInitialize(&argc, &args, NULL, help));
 47:   PetscCallMPI(MPI_Comm_rank(PETSC_COMM_WORLD, &rank));
 48:   PetscCall(PetscOptionsGetBool(NULL, NULL, "-table", &table, NULL));
 49:   PetscCall(PetscOptionsGetBool(NULL, NULL, "-trans", &trans, NULL));
 50:   PetscCall(PetscOptionsGetBool(NULL, NULL, "-partition", &partition, NULL));
 51:   PetscCall(PetscOptionsGetBool(NULL, NULL, "-initialguess", &initialguess, NULL));
 52:   PetscCall(PetscOptionsGetBool(NULL, NULL, "-output_solution", &outputSoln, NULL));
 53:   PetscCall(PetscOptionsGetBool(NULL, NULL, "-ckrnorm", &ckrnorm, NULL));
 54:   PetscCall(PetscOptionsGetBool(NULL, NULL, "-ckerror", &ckerror, NULL));

 56:   /*
 57:      Determine files from which we read the two linear systems
 58:      (matrix and right-hand-side vector).
 59:   */
 60:   PetscCall(PetscOptionsGetString(NULL, NULL, "-f", file[0], sizeof(file[0]), &flg));
 61:   if (flg) {
 62:     PetscCall(PetscStrncpy(file[1], file[0], sizeof(file[1])));
 63:     preload = PETSC_FALSE;
 64:   } else {
 65:     PetscCall(PetscOptionsGetString(NULL, NULL, "-f0", file[0], sizeof(file[0]), &flg));
 66:     PetscCheck(flg, PETSC_COMM_WORLD, PETSC_ERR_USER_INPUT, "Must indicate binary file with the -f0 or -f option");
 67:     PetscCall(PetscOptionsGetString(NULL, NULL, "-f1", file[1], sizeof(file[1]), &flg));
 68:     if (!flg) preload = PETSC_FALSE; /* don't bother with second system */
 69:   }

 71:   /* -----------------------------------------------------------
 72:                   Beginning of linear solver loop
 73:      ----------------------------------------------------------- */
 74:   /*
 75:      Loop through the linear solve 2 times.
 76:       - The intention here is to preload and solve a small system;
 77:         then load another (larger) system and solve it as well.
 78:         This process preloads the instructions with the smaller
 79:         system so that more accurate performance monitoring (via
 80:         -log_view) can be done with the larger one (that actually
 81:         is the system of interest).
 82:   */
 83:   PetscPreLoadBegin(preload, "Load system");

 85:   /* - - - - - - - - - - - New Stage - - - - - - - - - - - - -
 86:                          Load system
 87:    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

 89:   /*
 90:      Open binary file.  Note that we use FILE_MODE_READ to indicate
 91:      reading from this file.
 92:   */
 93:   PetscCall(PetscViewerBinaryOpen(PETSC_COMM_WORLD, file[PetscPreLoadIt], FILE_MODE_READ, &fd));

 95:   /*
 96:      Load the matrix and vector; then destroy the viewer.
 97:   */
 98:   PetscCall(MatCreate(PETSC_COMM_WORLD, &A));
 99:   PetscCall(MatSetFromOptions(A));
100:   PetscCall(MatLoad(A, fd));

102:   flg = PETSC_FALSE;
103:   PetscCall(PetscOptionsGetString(NULL, NULL, "-rhs", file[2], sizeof(file[2]), &flg));
104:   if (flg) { /* rhs is stored in a separate file */
105:     PetscCall(PetscViewerDestroy(&fd));
106:     PetscCall(PetscViewerBinaryOpen(PETSC_COMM_WORLD, file[2], FILE_MODE_READ, &fd));
107:     PetscCall(VecCreate(PETSC_COMM_WORLD, &b));
108:     PetscCall(VecLoad(b, fd));
109:   } else {
110:     /* if file contains no RHS, then use a vector of all ones */
111:     PetscCall(PetscInfo(0, "Using vector of ones for RHS\n"));
112:     PetscCall(MatGetLocalSize(A, &m, NULL));
113:     PetscCall(VecCreate(PETSC_COMM_WORLD, &b));
114:     PetscCall(VecSetSizes(b, m, PETSC_DECIDE));
115:     PetscCall(VecSetFromOptions(b));
116:     PetscCall(VecSet(b, 1.0));
117:     PetscCall(PetscObjectSetName((PetscObject)b, "Rhs vector"));
118:   }
119:   PetscCall(PetscViewerDestroy(&fd));

121:   /* Test MatDuplicate() */
122:   if (Test_MatDuplicate) {
123:     PetscCall(MatDuplicate(A, MAT_COPY_VALUES, &B));
124:     PetscCall(MatEqual(A, B, &flg));
125:     if (!flg) PetscCall(PetscPrintf(PETSC_COMM_WORLD, "  A != B \n"));
126:     PetscCall(MatDestroy(&B));
127:   }

129:   /* Add a shift to A */
130:   PetscCall(PetscOptionsGetScalar(NULL, NULL, "-mat_sigma", &sigma, &flg));
131:   if (flg) {
132:     PetscCall(PetscOptionsGetString(NULL, NULL, "-fB", file[2], sizeof(file[2]), &flgB));
133:     if (flgB) {
134:       /* load B to get A = A + sigma*B */
135:       PetscCall(PetscViewerBinaryOpen(PETSC_COMM_WORLD, file[2], FILE_MODE_READ, &fd));
136:       PetscCall(MatCreate(PETSC_COMM_WORLD, &B));
137:       PetscCall(MatSetOptionsPrefix(B, "B_"));
138:       PetscCall(MatLoad(B, fd));
139:       PetscCall(PetscViewerDestroy(&fd));
140:       PetscCall(MatAXPY(A, sigma, B, DIFFERENT_NONZERO_PATTERN)); /* A <- sigma*B + A */
141:     } else {
142:       PetscCall(MatShift(A, sigma));
143:     }
144:   }

146:   /* Make A singular for testing zero-pivot of ilu factorization        */
147:   /* Example: ./ex30 -f0 <datafile> -test_zeropivot -set_row_zero -pc_factor_shift_nonzero */
148:   flg = PETSC_FALSE;
149:   PetscCall(PetscOptionsGetBool(NULL, NULL, "-test_zeropivot", &flg, NULL));
150:   if (flg) {
151:     PetscInt           row, ncols;
152:     const PetscInt    *cols;
153:     const PetscScalar *vals;
154:     PetscBool          flg1 = PETSC_FALSE;
155:     PetscScalar       *zeros;
156:     row = 0;
157:     PetscCall(MatGetRow(A, row, &ncols, &cols, &vals));
158:     PetscCall(PetscCalloc1(ncols + 1, &zeros));
159:     flg1 = PETSC_FALSE;
160:     PetscCall(PetscOptionsGetBool(NULL, NULL, "-set_row_zero", &flg1, NULL));
161:     if (flg1) { /* set entire row as zero */
162:       PetscCall(MatSetValues(A, 1, &row, ncols, cols, zeros, INSERT_VALUES));
163:     } else { /* only set (row,row) entry as zero */
164:       PetscCall(MatSetValues(A, 1, &row, 1, &row, zeros, INSERT_VALUES));
165:     }
166:     PetscCall(MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY));
167:     PetscCall(MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY));
168:   }

170:   /* Check whether A is symmetric */
171:   flg = PETSC_FALSE;
172:   PetscCall(PetscOptionsGetBool(NULL, NULL, "-check_symmetry", &flg, NULL));
173:   if (flg) {
174:     Mat Atrans;
175:     PetscCall(MatTranspose(A, MAT_INITIAL_MATRIX, &Atrans));
176:     PetscCall(MatEqual(A, Atrans, &isSymmetric));
177:     if (isSymmetric) {
178:       PetscCall(PetscPrintf(PETSC_COMM_WORLD, "A is symmetric \n"));
179:     } else {
180:       PetscCall(PetscPrintf(PETSC_COMM_WORLD, "A is non-symmetric \n"));
181:     }
182:     PetscCall(MatDestroy(&Atrans));
183:   }

185:   PetscCall(VecDuplicate(b, &b2));
186:   PetscCall(VecDuplicate(b, &x));
187:   PetscCall(PetscObjectSetName((PetscObject)x, "Solution vector"));
188:   PetscCall(VecDuplicate(b, &u));
189:   PetscCall(PetscObjectSetName((PetscObject)u, "True Solution vector"));

191:   if (ckerror) { /* Set true solution */
192:     PetscCall(VecSet(u, 1.0));
193:     PetscCall(MatMult(A, u, b));
194:   }

196:   /* - - - - - - - - - - - New Stage - - - - - - - - - - - - -
197:                     Setup solve for system
198:    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

200:   if (partition) {
201:     MatPartitioning mpart;
202:     IS              mis, nis, is;
203:     PetscInt       *count;
204:     PetscMPIInt     size;
205:     Mat             BB;
206:     PetscCallMPI(MPI_Comm_size(PETSC_COMM_WORLD, &size));
207:     PetscCallMPI(MPI_Comm_rank(PETSC_COMM_WORLD, &rank));
208:     PetscCall(PetscMalloc1(size, &count));
209:     PetscCall(MatPartitioningCreate(PETSC_COMM_WORLD, &mpart));
210:     PetscCall(MatPartitioningSetAdjacency(mpart, A));
211:     /* PetscCall(MatPartitioningSetVertexWeights(mpart, weight)); */
212:     PetscCall(MatPartitioningSetFromOptions(mpart));
213:     PetscCall(MatPartitioningApply(mpart, &mis));
214:     PetscCall(MatPartitioningDestroy(&mpart));
215:     PetscCall(ISPartitioningToNumbering(mis, &nis));
216:     PetscCall(ISPartitioningCount(mis, size, count));
217:     PetscCall(ISDestroy(&mis));
218:     PetscCall(ISInvertPermutation(nis, count[rank], &is));
219:     PetscCall(PetscFree(count));
220:     PetscCall(ISDestroy(&nis));
221:     PetscCall(ISSort(is));
222:     PetscCall(MatCreateSubMatrix(A, is, is, MAT_INITIAL_MATRIX, &BB));

224:     /* need to move the vector also */
225:     PetscCall(ISDestroy(&is));
226:     PetscCall(MatDestroy(&A));
227:     A = BB;
228:   }

230:   /*
231:      Create linear solver; set operators; set runtime options.
232:   */
233:   PetscCall(KSPCreate(PETSC_COMM_WORLD, &ksp));
234:   PetscCall(KSPSetInitialGuessNonzero(ksp, initialguess));
235:   num_numfac = 1;
236:   PetscCall(PetscOptionsGetInt(NULL, NULL, "-num_numfac", &num_numfac, NULL));
237:   while (num_numfac--) {
238:     PetscCall(KSPSetOperators(ksp, A, A));
239:     PetscCall(KSPSetFromOptions(ksp));

241:     /*
242:      Here we explicitly call KSPSetUp() and KSPSetUpOnBlocks() to
243:      enable more precise profiling of setting up the preconditioner.
244:      These calls are optional, since both will be called within
245:      KSPSolve() if they haven't been called already.
246:     */
247:     PetscCall(KSPSetUp(ksp));
248:     PetscCall(KSPSetUpOnBlocks(ksp));

250:     /* - - - - - - - - - - - New Stage - - - - - - - - - - - - -
251:                          Solve system
252:       - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
253:     /*
254:      Solve linear system;
255:     */
256:     if (trans) {
257:       PetscCall(KSPSolveTranspose(ksp, b, x));
258:       PetscCall(KSPGetIterationNumber(ksp, &its));
259:     } else {
260:       PetscInt num_rhs = 1;
261:       PetscCall(PetscOptionsGetInt(NULL, NULL, "-num_rhs", &num_rhs, NULL));

263:       while (num_rhs--) PetscCall(KSPSolve(ksp, b, x));
264:       PetscCall(KSPGetIterationNumber(ksp, &its));
265:       if (ckrnorm) { /* Check residual for each rhs */
266:         if (trans) {
267:           PetscCall(MatMultTranspose(A, x, b2));
268:         } else {
269:           PetscCall(MatMult(A, x, b2));
270:         }
271:         PetscCall(VecAXPY(b2, -1.0, b));
272:         PetscCall(VecNorm(b2, NORM_2, &rnorm));
273:         PetscCall(PetscPrintf(PETSC_COMM_WORLD, "  Number of iterations = %3" PetscInt_FMT "\n", its));
274:         PetscCall(PetscPrintf(PETSC_COMM_WORLD, "  Residual norm %g\n", (double)rnorm));
275:       }
276:       if (ckerror && !trans) { /* Check error for each rhs */
277:         /* PetscCall(VecView(x,PETSC_VIEWER_STDOUT_WORLD)); */
278:         PetscCall(VecAXPY(u, -1.0, x));
279:         PetscCall(VecNorm(u, NORM_2, &enorm));
280:         PetscCall(PetscPrintf(PETSC_COMM_WORLD, "  Error norm %g\n", (double)enorm));
281:       }

283:     } /* while (num_rhs--) */

285:     /*
286:      Write output (optionally using table for solver details).
287:       - PetscPrintf() handles output for multiprocessor jobs
288:         by printing from only one processor in the communicator.
289:       - KSPView() prints information about the linear solver.
290:     */
291:     if (table && ckrnorm) {
292:       char       *matrixname = NULL, kspinfo[120];
293:       PetscViewer viewer;

295:       /*
296:         Open a string viewer; then write info to it.
297:       */
298:       PetscCall(PetscViewerStringOpen(PETSC_COMM_WORLD, kspinfo, sizeof(kspinfo), &viewer));
299:       PetscCall(KSPView(ksp, viewer));
300:       PetscCall(PetscStrrchr(file[PetscPreLoadIt], '/', &matrixname));
301:       PetscCall(PetscPrintf(PETSC_COMM_WORLD, "%-8.8s %3" PetscInt_FMT " %2.0e %s \n", matrixname, its, (double)rnorm, kspinfo));

303:       /*
304:         Destroy the viewer
305:       */
306:       PetscCall(PetscViewerDestroy(&viewer));
307:     }

309:     PetscCall(PetscOptionsGetString(NULL, NULL, "-solution", file[3], sizeof(file[3]), &flg));
310:     if (flg) {
311:       PetscViewer viewer;
312:       Vec         xstar;

314:       PetscCall(PetscViewerBinaryOpen(PETSC_COMM_WORLD, file[3], FILE_MODE_READ, &viewer));
315:       PetscCall(VecCreate(PETSC_COMM_WORLD, &xstar));
316:       PetscCall(VecLoad(xstar, viewer));
317:       PetscCall(VecAXPY(xstar, -1.0, x));
318:       PetscCall(VecNorm(xstar, NORM_2, &enorm));
319:       PetscCall(PetscPrintf(PETSC_COMM_WORLD, "Error norm %g\n", (double)enorm));
320:       PetscCall(VecDestroy(&xstar));
321:       PetscCall(PetscViewerDestroy(&viewer));
322:     }
323:     if (outputSoln) {
324:       PetscViewer viewer;

326:       PetscCall(PetscViewerBinaryOpen(PETSC_COMM_WORLD, "solution.petsc", FILE_MODE_WRITE, &viewer));
327:       PetscCall(VecView(x, viewer));
328:       PetscCall(PetscViewerDestroy(&viewer));
329:     }

331:     flg = PETSC_FALSE;
332:     PetscCall(PetscOptionsGetBool(NULL, NULL, "-ksp_reason", &flg, NULL));
333:     if (flg) {
334:       KSPConvergedReason reason;
335:       PetscCall(KSPGetConvergedReason(ksp, &reason));
336:       PetscCall(PetscPrintf(PETSC_COMM_WORLD, "KSPConvergedReason: %s\n", KSPConvergedReasons[reason]));
337:     }

339:   } /* while (num_numfac--) */

341:   /*
342:      Free work space.  All PETSc objects should be destroyed when they
343:      are no longer needed.
344:   */
345:   PetscCall(MatDestroy(&A));
346:   PetscCall(VecDestroy(&b));
347:   PetscCall(VecDestroy(&u));
348:   PetscCall(VecDestroy(&x));
349:   PetscCall(VecDestroy(&b2));
350:   PetscCall(KSPDestroy(&ksp));
351:   if (flgB) PetscCall(MatDestroy(&B));
352:   PetscPreLoadEnd();
353:   /* -----------------------------------------------------------
354:                       End of linear solver loop
355:      ----------------------------------------------------------- */

357:   PetscCall(PetscFinalize());
358:   return 0;
359: }

361: /*TEST

363:     test:
364:       args: -f ${DATAFILESPATH}/matrices/small -ksp_type preonly -pc_type ilu -pc_factor_mat_ordering_type natural -num_numfac 2 -pc_factor_reuse_fill
365:       requires: datafilespath !complex double !defined(PETSC_USE_64BIT_INDICES)
366:       output_file: output/ex30.out

368:     test:
369:       suffix: shiftnz
370:       args: -f0 ${DATAFILESPATH}/matrices/small -mat_sigma -4.0 -ksp_type preonly -pc_type lu -pc_factor_shift_type NONZERO -pc_factor_shift_amount 1.e-5
371:       requires: datafilespath !complex double !defined(PETSC_USE_64BIT_INDICES)

373:     test:
374:       suffix: shiftpd
375:       args: -f0 ${DATAFILESPATH}/matrices/small -mat_sigma -4.0 -ksp_type preonly -pc_type lu -pc_factor_shift_type POSITIVE_DEFINITE
376:       requires: datafilespath !complex double !defined(PETSC_USE_64BIT_INDICES)

378:     test:
379:       suffix: shift_cholesky_aij
380:       args: -f0 ${DATAFILESPATH}/matrices/small -mat_sigma -4.0 -ksp_type preonly -pc_type cholesky -pc_factor_shift_type NONZERO -pc_factor_shift_amount 1.e-5
381:       requires: datafilespath !complex double !defined(PETSC_USE_64BIT_INDICES)
382:       output_file: output/ex30_shiftnz.out

384:     test:
385:       suffix: shiftpd_2
386:       args: -f0 ${DATAFILESPATH}/matrices/small -mat_sigma -4.0 -ksp_type preonly -pc_type cholesky -pc_factor_shift_type POSITIVE_DEFINITE
387:       requires: datafilespath !complex double !defined(PETSC_USE_64BIT_INDICES)

389:     test:
390:       suffix: shift_cholesky_sbaij
391:       args: -f0 ${DATAFILESPATH}/matrices/small -mat_sigma -4.0 -ksp_type preonly -pc_type cholesky -pc_factor_shift_type NONZERO -pc_factor_shift_amount 1.e-5 -mat_type sbaij
392:       requires: datafilespath !complex double !defined(PETSC_USE_64BIT_INDICES)
393:       output_file: output/ex30_shiftnz.out

395:     test:
396:       suffix: shiftpd_2_sbaij
397:       args: -f0 ${DATAFILESPATH}/matrices/small -mat_sigma -4.0 -ksp_type preonly -pc_type cholesky -pc_factor_shift_type POSITIVE_DEFINITE -mat_type sbaij
398:       requires: datafilespath !complex double !defined(PETSC_USE_64BIT_INDICES)
399:       output_file: output/ex30_shiftpd_2.out

401:     test:
402:       suffix: shiftinblocks
403:       args: -f0 ${DATAFILESPATH}/matrices/small -mat_sigma -4.0 -ksp_type preonly -pc_type lu -pc_factor_shift_type INBLOCKS
404:       requires: datafilespath !complex double !defined(PETSC_USE_64BIT_INDICES)

406:     test:
407:       suffix: shiftinblocks2
408:       args: -f0 ${DATAFILESPATH}/matrices/small -mat_sigma -4.0 -ksp_type preonly -pc_type cholesky -pc_factor_shift_type INBLOCKS
409:       requires: datafilespath !complex double !defined(PETSC_USE_64BIT_INDICES)
410:       output_file: output/ex30_shiftinblocks.out

412:     test:
413:       suffix: shiftinblockssbaij
414:       args: -f0 ${DATAFILESPATH}/matrices/small -mat_sigma -4.0 -ksp_type preonly -pc_type cholesky -pc_factor_shift_type INBLOCKS -mat_type sbaij
415:       requires: datafilespath !complex double !defined(PETSC_USE_64BIT_INDICES)
416:       output_file: output/ex30_shiftinblocks.out

418: TEST*/