Actual source code: itfunc.c

petsc-3.6.4 2016-04-12
Report Typos and Errors
  2: /*
  3:       Interface KSP routines that the user calls.
  4: */

  6: #include <petsc/private/kspimpl.h>   /*I "petscksp.h" I*/
  7: #include <petscdm.h>

 11: /*@
 12:    KSPComputeExtremeSingularValues - Computes the extreme singular values
 13:    for the preconditioned operator. Called after or during KSPSolve().

 15:    Not Collective

 17:    Input Parameter:
 18: .  ksp - iterative context obtained from KSPCreate()

 20:    Output Parameters:
 21: .  emin, emax - extreme singular values

 23:    Options Database Keys:
 24: .  -ksp_compute_singularvalues - compute extreme singular values and print when KSPSolve completes.

 26:    Notes:
 27:    One must call KSPSetComputeSingularValues() before calling KSPSetUp()
 28:    (or use the option -ksp_compute_eigenvalues) in order for this routine to work correctly.

 30:    Many users may just want to use the monitoring routine
 31:    KSPMonitorSingularValue() (which can be set with option -ksp_monitor_singular_value)
 32:    to print the extreme singular values at each iteration of the linear solve.

 34:    Estimates of the smallest singular value may be very inaccurate, especially if the Krylov method has not converged.
 35:    The largest singular value is usually accurate to within a few percent if the method has converged, but is still not
 36:    intended for eigenanalysis.

 38:    Disable restarts if using KSPGMRES, otherwise this estimate will only be using those iterations after the last
 39:    restart. See KSPGMRESSetRestart() for more details.

 41:    Level: advanced

 43: .keywords: KSP, compute, extreme, singular, values

 45: .seealso: KSPSetComputeSingularValues(), KSPMonitorSingularValue(), KSPComputeEigenvalues()
 46: @*/
 47: PetscErrorCode  KSPComputeExtremeSingularValues(KSP ksp,PetscReal *emax,PetscReal *emin)
 48: {

 55:   if (!ksp->calc_sings) SETERRQ(PetscObjectComm((PetscObject)ksp),4,"Singular values not requested before KSPSetUp()");

 57:   if (ksp->ops->computeextremesingularvalues) {
 58:     (*ksp->ops->computeextremesingularvalues)(ksp,emax,emin);
 59:   } else {
 60:     *emin = -1.0;
 61:     *emax = -1.0;
 62:   }
 63:   return(0);
 64: }

 68: /*@
 69:    KSPComputeEigenvalues - Computes the extreme eigenvalues for the
 70:    preconditioned operator. Called after or during KSPSolve().

 72:    Not Collective

 74:    Input Parameter:
 75: +  ksp - iterative context obtained from KSPCreate()
 76: -  n - size of arrays r and c. The number of eigenvalues computed (neig) will, in
 77:        general, be less than this.

 79:    Output Parameters:
 80: +  r - real part of computed eigenvalues, provided by user with a dimension of at least n
 81: .  c - complex part of computed eigenvalues, provided by user with a dimension of at least n
 82: -  neig - actual number of eigenvalues computed (will be less than or equal to n)

 84:    Options Database Keys:
 85: +  -ksp_compute_eigenvalues - Prints eigenvalues to stdout
 86: -  -ksp_plot_eigenvalues - Plots eigenvalues in an x-window display

 88:    Notes:
 89:    The number of eigenvalues estimated depends on the size of the Krylov space
 90:    generated during the KSPSolve() ; for example, with
 91:    CG it corresponds to the number of CG iterations, for GMRES it is the number
 92:    of GMRES iterations SINCE the last restart. Any extra space in r[] and c[]
 93:    will be ignored.

 95:    KSPComputeEigenvalues() does not usually provide accurate estimates; it is
 96:    intended only for assistance in understanding the convergence of iterative
 97:    methods, not for eigenanalysis. For accurate computation of eigenvalues we recommend using
 98:    the excellent package SLEPc.

100:    One must call KSPSetComputeEigenvalues() before calling KSPSetUp()
101:    in order for this routine to work correctly.

103:    Many users may just want to use the monitoring routine
104:    KSPMonitorSingularValue() (which can be set with option -ksp_monitor_singular_value)
105:    to print the singular values at each iteration of the linear solve.

107:    Level: advanced

109: .keywords: KSP, compute, extreme, singular, values

111: .seealso: KSPSetComputeSingularValues(), KSPMonitorSingularValue(), KSPComputeExtremeSingularValues()
112: @*/
113: PetscErrorCode  KSPComputeEigenvalues(KSP ksp,PetscInt n,PetscReal r[],PetscReal c[],PetscInt *neig)
114: {

121:   if (n<0) SETERRQ(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_OUTOFRANGE,"Requested < 0 Eigenvalues");
123:   if (!ksp->calc_sings) SETERRQ(PetscObjectComm((PetscObject)ksp),4,"Eigenvalues not requested before KSPSetUp()");

125:   if (ksp->ops->computeeigenvalues) {
126:     (*ksp->ops->computeeigenvalues)(ksp,n,r,c,neig);
127:   } else {
128:     *neig = 0;
129:   }
130:   return(0);
131: }

135: /*@
136:    KSPSetUpOnBlocks - Sets up the preconditioner for each block in
137:    the block Jacobi, block Gauss-Seidel, and overlapping Schwarz
138:    methods.

140:    Collective on KSP

142:    Input Parameter:
143: .  ksp - the KSP context

145:    Notes:
146:    KSPSetUpOnBlocks() is a routine that the user can optinally call for
147:    more precise profiling (via -log_summary) of the setup phase for these
148:    block preconditioners.  If the user does not call KSPSetUpOnBlocks(),
149:    it will automatically be called from within KSPSolve().

151:    Calling KSPSetUpOnBlocks() is the same as calling PCSetUpOnBlocks()
152:    on the PC context within the KSP context.

154:    Level: advanced

156: .keywords: KSP, setup, blocks

158: .seealso: PCSetUpOnBlocks(), KSPSetUp(), PCSetUp()
159: @*/
160: PetscErrorCode  KSPSetUpOnBlocks(KSP ksp)
161: {

166:   if (!ksp->pc) {KSPGetPC(ksp,&ksp->pc);}
167:   PCSetUpOnBlocks(ksp->pc);
168:   return(0);
169: }

173: /*@
174:    KSPSetReusePreconditioner - reuse the current preconditioner, do not construct a new one even if the operator changes

176:    Collective on KSP

178:    Input Parameters:
179: +  ksp   - iterative context obtained from KSPCreate()
180: -  flag - PETSC_TRUE to reuse the current preconditioner

182:    Level: intermediate

184: .keywords: KSP, setup

186: .seealso: KSPCreate(), KSPSolve(), KSPDestroy(), PCSetReusePreconditioner()
187: @*/
188: PetscErrorCode  KSPSetReusePreconditioner(KSP ksp,PetscBool flag)
189: {

194:   PCSetReusePreconditioner(ksp->pc,flag);
195:   return(0);
196: }

200: /*@
201:    KSPSetSkipPCSetFromOptions - prevents KSPSetFromOptions() from call PCSetFromOptions(). This is used if the same PC is shared by more than one KSP so its options are not resetable for each KSP

203:    Collective on KSP

205:    Input Parameters:
206: +  ksp   - iterative context obtained from KSPCreate()
207: -  flag - PETSC_TRUE to skip calling the PCSetFromOptions()

209:    Level: intermediate

211: .keywords: KSP, setup

213: .seealso: KSPCreate(), KSPSolve(), KSPDestroy(), PCSetReusePreconditioner()
214: @*/
215: PetscErrorCode  KSPSetSkipPCSetFromOptions(KSP ksp,PetscBool flag)
216: {
219:   ksp->skippcsetfromoptions = flag;
220:   return(0);
221: }

225: /*@
226:    KSPSetUp - Sets up the internal data structures for the
227:    later use of an iterative solver.

229:    Collective on KSP

231:    Input Parameter:
232: .  ksp   - iterative context obtained from KSPCreate()

234:    Level: developer

236: .keywords: KSP, setup

238: .seealso: KSPCreate(), KSPSolve(), KSPDestroy()
239: @*/
240: PetscErrorCode  KSPSetUp(KSP ksp)
241: {
243:   Mat            A,B;
244:   Mat            mat,pmat;
245:   MatNullSpace   nullsp;
246: 

250:   /* reset the convergence flag from the previous solves */
251:   ksp->reason = KSP_CONVERGED_ITERATING;

253:   if (!((PetscObject)ksp)->type_name) {
254:     KSPSetType(ksp,KSPGMRES);
255:   }
256:   KSPSetUpNorms_Private(ksp,&ksp->normtype,&ksp->pc_side);

258:   if (ksp->dmActive && !ksp->setupstage) {
259:     /* first time in so build matrix and vector data structures using DM */
260:     if (!ksp->vec_rhs) {DMCreateGlobalVector(ksp->dm,&ksp->vec_rhs);}
261:     if (!ksp->vec_sol) {DMCreateGlobalVector(ksp->dm,&ksp->vec_sol);}
262:     DMCreateMatrix(ksp->dm,&A);
263:     KSPSetOperators(ksp,A,A);
264:     PetscObjectDereference((PetscObject)A);
265:   }

267:   if (ksp->dmActive) {
268:     DMKSP kdm;
269:     DMGetDMKSP(ksp->dm,&kdm);

271:     if (kdm->ops->computeinitialguess && ksp->setupstage != KSP_SETUP_NEWRHS) {
272:       /* only computes initial guess the first time through */
273:       (*kdm->ops->computeinitialguess)(ksp,ksp->vec_sol,kdm->initialguessctx);
274:       KSPSetInitialGuessNonzero(ksp,PETSC_TRUE);
275:     }
276:     if (kdm->ops->computerhs) {
277:       (*kdm->ops->computerhs)(ksp,ksp->vec_rhs,kdm->rhsctx);
278:     }

280:     if (ksp->setupstage != KSP_SETUP_NEWRHS) {
281:       if (kdm->ops->computeoperators) {
282:         KSPGetOperators(ksp,&A,&B);
283:         (*kdm->ops->computeoperators)(ksp,A,B,kdm->operatorsctx);
284:         KSPSetOperators(ksp,A,B);
285:       } else SETERRQ(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_WRONGSTATE,"You called KSPSetDM() but did not use DMKSPSetComputeOperators() or KSPSetDMActive(dm,PETSC_FALSE);");
286:     }
287:   }

289:   if (ksp->setupstage == KSP_SETUP_NEWRHS) return(0);
290:   PetscLogEventBegin(KSP_SetUp,ksp,ksp->vec_rhs,ksp->vec_sol,0);

292:   switch (ksp->setupstage) {
293:   case KSP_SETUP_NEW:
294:     (*ksp->ops->setup)(ksp);
295:     break;
296:   case KSP_SETUP_NEWMATRIX: {   /* This should be replaced with a more general mechanism */
297:   } break;
298:   default: break;
299:   }

301:   PCGetOperators(ksp->pc,&mat,&pmat);
302:   /* scale the matrix if requested */
303:   if (ksp->dscale) {
304:     PetscScalar *xx;
305:     PetscInt    i,n;
306:     PetscBool   zeroflag = PETSC_FALSE;
307:     if (!ksp->pc) {KSPGetPC(ksp,&ksp->pc);}
308:     if (!ksp->diagonal) { /* allocate vector to hold diagonal */
309:       MatCreateVecs(pmat,&ksp->diagonal,0);
310:     }
311:     MatGetDiagonal(pmat,ksp->diagonal);
312:     VecGetLocalSize(ksp->diagonal,&n);
313:     VecGetArray(ksp->diagonal,&xx);
314:     for (i=0; i<n; i++) {
315:       if (xx[i] != 0.0) xx[i] = 1.0/PetscSqrtReal(PetscAbsScalar(xx[i]));
316:       else {
317:         xx[i]    = 1.0;
318:         zeroflag = PETSC_TRUE;
319:       }
320:     }
321:     VecRestoreArray(ksp->diagonal,&xx);
322:     if (zeroflag) {
323:       PetscInfo(ksp,"Zero detected in diagonal of matrix, using 1 at those locations\n");
324:     }
325:     MatDiagonalScale(pmat,ksp->diagonal,ksp->diagonal);
326:     if (mat != pmat) {MatDiagonalScale(mat,ksp->diagonal,ksp->diagonal);}
327:     ksp->dscalefix2 = PETSC_FALSE;
328:   }
329:   PetscLogEventEnd(KSP_SetUp,ksp,ksp->vec_rhs,ksp->vec_sol,0);
330:   if (!ksp->pc) {KSPGetPC(ksp,&ksp->pc);}
331:   PCSetErrorIfFailure(ksp->pc,ksp->errorifnotconverged);
332:   PCSetUp(ksp->pc);
333:   MatGetNullSpace(mat,&nullsp);
334:   if (nullsp) {
335:     PetscBool test = PETSC_FALSE;
336:     PetscOptionsGetBool(((PetscObject)ksp)->prefix,"-ksp_test_null_space",&test,NULL);
337:     if (test) {
338:       MatNullSpaceTest(nullsp,mat,NULL);
339:     }
340:   }
341:   ksp->setupstage = KSP_SETUP_NEWRHS;
342:   return(0);
343: }

347: /*@
348:    KSPReasonView - Displays the reason a KSP solve converged or diverged to a viewer

350:    Collective on KSP

352:    Parameter:
353: +  ksp - iterative context obtained from KSPCreate()
354: -  viewer - the viewer to display the reason


357:    Options Database Keys:
358: .  -ksp_converged_reason - print reason for converged or diverged, also prints number of iterations

360:    Level: beginner

362: .keywords: KSP, solve, linear system

364: .seealso: KSPCreate(), KSPSetUp(), KSPDestroy(), KSPSetTolerances(), KSPConvergedDefault(),
365:           KSPSolveTranspose(), KSPGetIterationNumber()
366: @*/
367: PetscErrorCode  KSPReasonView(KSP ksp,PetscViewer viewer)
368: {
370:   PetscBool      isAscii;

373:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&isAscii);
374:   if (isAscii) {
375:     PetscViewerASCIIAddTab(viewer,((PetscObject)ksp)->tablevel);
376:     if (ksp->reason > 0) {
377:       if (((PetscObject) ksp)->prefix) {
378:         PetscViewerASCIIPrintf(viewer,"Linear %s solve converged due to %s iterations %D\n",((PetscObject) ksp)->prefix,KSPConvergedReasons[ksp->reason],ksp->its);
379:       } else {
380:         PetscViewerASCIIPrintf(viewer,"Linear solve converged due to %s iterations %D\n",KSPConvergedReasons[ksp->reason],ksp->its);
381:       }
382:     } else {
383:       if (((PetscObject) ksp)->prefix) {
384:         PetscViewerASCIIPrintf(viewer,"Linear %s solve did not converge due to %s iterations %D\n",((PetscObject) ksp)->prefix,KSPConvergedReasons[ksp->reason],ksp->its);
385:       } else {
386:         PetscViewerASCIIPrintf(viewer,"Linear solve did not converge due to %s iterations %D\n",KSPConvergedReasons[ksp->reason],ksp->its);
387:       }
388:     }
389:     PetscViewerASCIISubtractTab(viewer,((PetscObject)ksp)->tablevel);
390:   }
391:   return(0);
392: }

395: #if defined(PETSC_HAVE_THREADSAFETY)
396: #define KSPReasonViewFromOptions KSPReasonViewFromOptionsUnsafe
398: #else
400: #endif
401: /*@C
402:   KSPReasonViewFromOptions - Processes command line options to determine if/how a KSPReason is to be viewed. 

404:   Collective on KSP

406:   Input Parameters:
407: . ksp   - the KSP object

409:   Level: intermediate

411: @*/
412: PetscErrorCode KSPReasonViewFromOptions(KSP ksp)
413: {
414:   PetscErrorCode    ierr;
415:   PetscViewer       viewer;
416:   PetscBool         flg;
417:   static PetscBool  incall = PETSC_FALSE;
418:   PetscViewerFormat format;

421:   if (incall) return(0);
422:   incall = PETSC_TRUE;
423:   PetscOptionsGetViewer(PetscObjectComm((PetscObject)ksp),((PetscObject)ksp)->prefix,"-ksp_converged_reason",&viewer,&format,&flg);
424:   if (flg) {
425:     PetscViewerPushFormat(viewer,format);
426:     KSPReasonView(ksp,viewer);
427:     PetscViewerPopFormat(viewer);
428:     PetscViewerDestroy(&viewer);
429:   }
430:   incall = PETSC_FALSE;
431:   return(0);
432: }

434: #if defined(PETSC_HAVE_THREADSAFETY)
435: #undef KSPReasonViewFromOptions
436: PetscErrorCode KSPReasonViewFromOptions(KSP ksp)
437: {
439: #pragma omp critical
440:   KSPReasonViewFromOptionsUnsafe(ksp);
441:   return ierr;
442: }
443: #endif

445: #include <petscdraw.h>
448: /*@
449:    KSPSolve - Solves linear system.

451:    Collective on KSP

453:    Parameter:
454: +  ksp - iterative context obtained from KSPCreate()
455: .  b - the right hand side vector
456: -  x - the solution  (this may be the same vector as b, then b will be overwritten with answer)

458:    Options Database Keys:
459: +  -ksp_compute_eigenvalues - compute preconditioned operators eigenvalues
460: .  -ksp_plot_eigenvalues - plot the computed eigenvalues in an X-window
461: .  -ksp_compute_eigenvalues_explicitly - compute the eigenvalues by forming the dense operator and useing LAPACK
462: .  -ksp_plot_eigenvalues_explicitly - plot the explicitly computing eigenvalues
463: .  -ksp_view_mat binary - save matrix to the default binary viewer
464: .  -ksp_view_pmat binary - save matrix used to build preconditioner to the default binary viewer
465: .  -ksp_view_rhs binary - save right hand side vector to the default binary viewer
466: .  -ksp_view_solution binary - save computed solution vector to the default binary viewer
467:            (can be read later with src/ksp/examples/tutorials/ex10.c for testing solvers)
468: .  -ksp_view_mat_explicit - for matrix-free operators, computes the matrix entries and views them
469: .  -ksp_view_preconditioned_operator_explicit - computes the product of the preconditioner and matrix as an explicit matrix and views it
470: .  -ksp_converged_reason - print reason for converged or diverged, also prints number of iterations
471: .  -ksp_final_residual - print 2-norm of true linear system residual at the end of the solution process
472: -  -ksp_view - print the ksp data structure at the end of the system solution

474:    Notes:

476:    If one uses KSPSetDM() then x or b need not be passed. Use KSPGetSolution() to access the solution in this case.

478:    The operator is specified with KSPSetOperators().

480:    Call KSPGetConvergedReason() to determine if the solver converged or failed and
481:    why. The number of iterations can be obtained from KSPGetIterationNumber().

483:    If using a direct method (e.g., via the KSP solver
484:    KSPPREONLY and a preconditioner such as PCLU/PCILU),
485:    then its=1.  See KSPSetTolerances() and KSPConvergedDefault()
486:    for more details.

488:    Understanding Convergence:
489:    The routines KSPMonitorSet(), KSPComputeEigenvalues(), and
490:    KSPComputeEigenvaluesExplicitly() provide information on additional
491:    options to monitor convergence and print eigenvalue information.

493:    Level: beginner

495: .keywords: KSP, solve, linear system

497: .seealso: KSPCreate(), KSPSetUp(), KSPDestroy(), KSPSetTolerances(), KSPConvergedDefault(),
498:           KSPSolveTranspose(), KSPGetIterationNumber()
499: @*/
500: PetscErrorCode  KSPSolve(KSP ksp,Vec b,Vec x)
501: {
502:   PetscErrorCode    ierr;
503:   PetscMPIInt       rank;
504:   PetscBool         flag1,flag2,flag3,flg = PETSC_FALSE,inXisinB=PETSC_FALSE,guess_zero;
505:   Mat               mat,pmat;
506:   MPI_Comm          comm;
507:   PetscInt          pcreason;
508:   MatNullSpace      nullsp;
509:   Vec               btmp,vec_rhs=0;

515:   comm = PetscObjectComm((PetscObject)ksp);
516:   if (x && x == b) {
517:     if (!ksp->guess_zero) SETERRQ(comm,PETSC_ERR_ARG_INCOMP,"Cannot use x == b with nonzero initial guess");
518:     VecDuplicate(b,&x);
519:     inXisinB = PETSC_TRUE;
520:   }
521:   if (b) {
522:     PetscObjectReference((PetscObject)b);
523:     VecDestroy(&ksp->vec_rhs);
524:     ksp->vec_rhs = b;
525:   }
526:   if (x) {
527:     PetscObjectReference((PetscObject)x);
528:     VecDestroy(&ksp->vec_sol);
529:     ksp->vec_sol = x;
530:   }
531:   KSPViewFromOptions(ksp,NULL,"-ksp_view_pre");

533:   if (ksp->presolve) {
534:     (*ksp->presolve)(ksp,ksp->vec_rhs,ksp->vec_sol,ksp->prectx);
535:   }
536:   PetscLogEventBegin(KSP_Solve,ksp,ksp->vec_rhs,ksp->vec_sol,0);

538:   /* reset the residual history list if requested */
539:   if (ksp->res_hist_reset) ksp->res_hist_len = 0;
540:   ksp->transpose_solve = PETSC_FALSE;

542:   if (ksp->guess) {
543:     KSPFischerGuessFormGuess(ksp->guess,ksp->vec_rhs,ksp->vec_sol);
544:     ksp->guess_zero = PETSC_FALSE;
545:   }
546:   /* KSPSetUp() scales the matrix if needed */
547:   KSPSetUp(ksp);
548:   PCGetSetUpFailedReason(ksp->pc,&pcreason);
549:   if (pcreason) {
550:     ksp->reason = KSP_DIVERGED_PCSETUP_FAILED;
551:     goto skipsolve;
552:   }
553:   KSPSetUpOnBlocks(ksp);
554:   VecLocked(ksp->vec_sol,3);

556:   PCGetOperators(ksp->pc,&mat,&pmat);
557:   /* diagonal scale RHS if called for */
558:   if (ksp->dscale) {
559:     VecPointwiseMult(ksp->vec_rhs,ksp->vec_rhs,ksp->diagonal);
560:     /* second time in, but matrix was scaled back to original */
561:     if (ksp->dscalefix && ksp->dscalefix2) {
562:       Mat mat,pmat;

564:       PCGetOperators(ksp->pc,&mat,&pmat);
565:       MatDiagonalScale(pmat,ksp->diagonal,ksp->diagonal);
566:       if (mat != pmat) {MatDiagonalScale(mat,ksp->diagonal,ksp->diagonal);}
567:     }

569:     /*  scale initial guess */
570:     if (!ksp->guess_zero) {
571:       if (!ksp->truediagonal) {
572:         VecDuplicate(ksp->diagonal,&ksp->truediagonal);
573:         VecCopy(ksp->diagonal,ksp->truediagonal);
574:         VecReciprocal(ksp->truediagonal);
575:       }
576:       VecPointwiseMult(ksp->vec_sol,ksp->vec_sol,ksp->truediagonal);
577:     }
578:   }
579:   PCPreSolve(ksp->pc,ksp);

581:   if (ksp->guess_zero) { VecSet(ksp->vec_sol,0.0);}
582:   if (ksp->guess_knoll) {
583:     PCApply(ksp->pc,ksp->vec_rhs,ksp->vec_sol);
584:     KSP_RemoveNullSpace(ksp,ksp->vec_sol);
585:     ksp->guess_zero = PETSC_FALSE;
586:   }

588:   /* can we mark the initial guess as zero for this solve? */
589:   guess_zero = ksp->guess_zero;
590:   if (!ksp->guess_zero) {
591:     PetscReal norm;

593:     VecNormAvailable(ksp->vec_sol,NORM_2,&flg,&norm);
594:     if (flg && !norm) ksp->guess_zero = PETSC_TRUE;
595:   }
596:   MatGetTransposeNullSpace(pmat,&nullsp);
597:   if (nullsp) {
598:     VecDuplicate(ksp->vec_rhs,&btmp);
599:     VecCopy(ksp->vec_rhs,btmp);
600:     MatNullSpaceRemove(nullsp,btmp);
601:     vec_rhs      = ksp->vec_rhs;
602:     ksp->vec_rhs = btmp;
603:   }
604:   VecLockPush(ksp->vec_rhs);
605:   (*ksp->ops->solve)(ksp);
606:   VecLockPop(ksp->vec_rhs);
607:   if (nullsp) {
608:     ksp->vec_rhs = vec_rhs;
609:     VecDestroy(&btmp);
610:   }

612:   ksp->guess_zero = guess_zero;


615:   if (!ksp->reason) SETERRQ(comm,PETSC_ERR_PLIB,"Internal error, solver returned without setting converged reason");
616:   ksp->totalits += ksp->its;

618:   skipsolve:
619:   KSPReasonViewFromOptions(ksp);
620:   PCPostSolve(ksp->pc,ksp);

622:   /* diagonal scale solution if called for */
623:   if (ksp->dscale) {
624:     VecPointwiseMult(ksp->vec_sol,ksp->vec_sol,ksp->diagonal);
625:     /* unscale right hand side and matrix */
626:     if (ksp->dscalefix) {
627:       Mat mat,pmat;

629:       VecReciprocal(ksp->diagonal);
630:       VecPointwiseMult(ksp->vec_rhs,ksp->vec_rhs,ksp->diagonal);
631:       PCGetOperators(ksp->pc,&mat,&pmat);
632:       MatDiagonalScale(pmat,ksp->diagonal,ksp->diagonal);
633:       if (mat != pmat) {MatDiagonalScale(mat,ksp->diagonal,ksp->diagonal);}
634:       VecReciprocal(ksp->diagonal);
635:       ksp->dscalefix2 = PETSC_TRUE;
636:     }
637:   }
638:   PetscLogEventEnd(KSP_Solve,ksp,ksp->vec_rhs,ksp->vec_sol,0);
639:   if (ksp->postsolve) {
640:     (*ksp->postsolve)(ksp,ksp->vec_rhs,ksp->vec_sol,ksp->postctx);
641:   }

643:   if (ksp->guess) {
644:     KSPFischerGuessUpdate(ksp->guess,ksp->vec_sol);
645:   }

647:   MPI_Comm_rank(comm,&rank);

649:   MatViewFromOptions(mat,(PetscObject)ksp,"-ksp_view_mat");
650:   MatViewFromOptions(pmat,(PetscObject)ksp,"-ksp_view_pmat");
651:   VecViewFromOptions(ksp->vec_rhs,(PetscObject)ksp,"-ksp_view_rhs");

653:   flag1 = PETSC_FALSE;
654:   flag2 = PETSC_FALSE;
655:   flag3 = PETSC_FALSE;
656:   PetscOptionsGetBool(((PetscObject)ksp)->prefix,"-ksp_compute_eigenvalues",&flag1,NULL);
657:   PetscOptionsGetBool(((PetscObject)ksp)->prefix,"-ksp_plot_eigenvalues",&flag2,NULL);
658:   PetscOptionsGetBool(((PetscObject)ksp)->prefix,"-ksp_plot_eigencontours",&flag3,NULL);
659:   if (flag1 || flag2 || flag3) {
660:     PetscInt  nits,n,i,neig;
661:     PetscReal *r,*c;

663:     KSPGetIterationNumber(ksp,&nits);
664:     n    = nits+2;

666:     if (!nits) {
667:       PetscPrintf(comm,"Zero iterations in solver, cannot approximate any eigenvalues\n");
668:     } else {
669:       PetscMalloc2(n,&r,n,&c);
670:       KSPComputeEigenvalues(ksp,n,r,c,&neig);
671:       if (flag1) {
672:         PetscPrintf(comm,"Iteratively computed eigenvalues\n");
673:         for (i=0; i<neig; i++) {
674:           if (c[i] >= 0.0) {
675:             PetscPrintf(comm,"%g + %gi\n",(double)r[i],(double)c[i]);
676:           } else {
677:             PetscPrintf(comm,"%g - %gi\n",(double)r[i],-(double)c[i]);
678:           }
679:         }
680:       }
681:       if (flag2 && !rank) {
682:         PetscDraw   draw;
683:         PetscDrawSP drawsp;

685:         if (!ksp->eigviewer) {
686:           PetscViewerDrawOpen(PETSC_COMM_SELF,0,"Iteratively Computed Eigenvalues",PETSC_DECIDE,PETSC_DECIDE,400,400,&ksp->eigviewer);
687:         }
688:         PetscViewerDrawGetDraw(ksp->eigviewer,0,&draw);
689:         PetscDrawSPCreate(draw,1,&drawsp);
690:         PetscDrawSPReset(drawsp);
691:         for (i=0; i<neig; i++) {
692:           PetscDrawSPAddPoint(drawsp,r+i,c+i);
693:         }
694:         PetscDrawSPDraw(drawsp,PETSC_TRUE);
695:         PetscDrawSPDestroy(&drawsp);
696:       }
697:       if (flag3 && !rank) {
698:         KSPPlotEigenContours_Private(ksp,neig,r,c);
699:       }
700:       PetscFree2(r,c);
701:     }
702:   }

704:   flag1 = PETSC_FALSE;
705:   PetscOptionsGetBool(((PetscObject)ksp)->prefix,"-ksp_compute_singularvalues",&flag1,NULL);
706:   if (flag1) {
707:     PetscInt nits;

709:     KSPGetIterationNumber(ksp,&nits);
710:     if (!nits) {
711:       PetscPrintf(comm,"Zero iterations in solver, cannot approximate any singular values\n");
712:     } else {
713:       PetscReal emax,emin;

715:       KSPComputeExtremeSingularValues(ksp,&emax,&emin);
716:       PetscPrintf(comm,"Iteratively computed extreme singular values: max %g min %g max/min %g\n",(double)emax,(double)emin,(double)(emax/emin));
717:     }
718:   }


721:   flag1 = PETSC_FALSE;
722:   flag2 = PETSC_FALSE;
723:   PetscOptionsGetBool(((PetscObject)ksp)->prefix,"-ksp_compute_eigenvalues_explicitly",&flag1,NULL);
724:   PetscOptionsGetBool(((PetscObject)ksp)->prefix,"-ksp_plot_eigenvalues_explicitly",&flag2,NULL);
725:   if (flag1 || flag2) {
726:     PetscInt  n,i;
727:     PetscReal *r,*c;
728:     VecGetSize(ksp->vec_sol,&n);
729:     PetscMalloc2(n,&r,n,&c);
730:     KSPComputeEigenvaluesExplicitly(ksp,n,r,c);
731:     if (flag1) {
732:       PetscPrintf(comm,"Explicitly computed eigenvalues\n");
733:       for (i=0; i<n; i++) {
734:         if (c[i] >= 0.0) {
735:           PetscPrintf(comm,"%g + %gi\n",(double)r[i],(double)c[i]);
736:         } else {
737:           PetscPrintf(comm,"%g - %gi\n",(double)r[i],-(double)c[i]);
738:         }
739:       }
740:     }
741:     if (flag2 && !rank) {
742:       PetscDraw   draw;
743:       PetscDrawSP drawsp;

745:       if (!ksp->eigviewer) {
746:         PetscViewerDrawOpen(PETSC_COMM_SELF,0,"Explicitly Computed Eigenvalues",0,320,400,400,&ksp->eigviewer);
747:       }
748:       PetscViewerDrawGetDraw(ksp->eigviewer,0,&draw);
749:       PetscDrawSPCreate(draw,1,&drawsp);
750:       PetscDrawSPReset(drawsp);
751:       for (i=0; i<n; i++) {
752:         PetscDrawSPAddPoint(drawsp,r+i,c+i);
753:       }
754:       PetscDrawSPDraw(drawsp,PETSC_TRUE);
755:       PetscDrawSPDestroy(&drawsp);
756:     }
757:     PetscFree2(r,c);
758:   }

760:   PetscOptionsHasName(((PetscObject)ksp)->prefix,"-ksp_view_mat_explicit",&flag2);
761:   if (flag2) {
762:     Mat A,B;
763:     PCGetOperators(ksp->pc,&A,NULL);
764:     MatComputeExplicitOperator(A,&B);
765:     MatViewFromOptions(B,(PetscObject)ksp,"-ksp_view_mat_explicit");
766:     MatDestroy(&B);
767:   }
768:   PetscOptionsHasName(((PetscObject)ksp)->prefix,"-ksp_view_preconditioned_operator_explicit",&flag2);
769:   if (flag2) {
770:     Mat B;
771:     KSPComputeExplicitOperator(ksp,&B);
772:     MatViewFromOptions(B,(PetscObject)ksp,"-ksp_view_preconditioned_operator_explicit");
773:     MatDestroy(&B);
774:   }
775:   KSPViewFromOptions(ksp,NULL,"-ksp_view");

777:   flg  = PETSC_FALSE;
778:   PetscOptionsGetBool(((PetscObject)ksp)->prefix,"-ksp_final_residual",&flg,NULL);
779:   if (flg) {
780:     Mat       A;
781:     Vec       t;
782:     PetscReal norm;
783:     if (ksp->dscale && !ksp->dscalefix) SETERRQ(comm,PETSC_ERR_ARG_WRONGSTATE,"Cannot compute final scale with -ksp_diagonal_scale except also with -ksp_diagonal_scale_fix");
784:     PCGetOperators(ksp->pc,&A,NULL);
785:     VecDuplicate(ksp->vec_rhs,&t);
786:     KSP_MatMult(ksp,A,ksp->vec_sol,t);
787:     VecAYPX(t, -1.0, ksp->vec_rhs);
788:     VecNorm(t,NORM_2,&norm);
789:     VecDestroy(&t);
790:     PetscPrintf(comm,"KSP final norm of residual %g\n",(double)norm);
791:   }
792:   VecViewFromOptions(ksp->vec_sol,(PetscObject)ksp,"-ksp_view_solution");

794:   if (inXisinB) {
795:     VecCopy(x,b);
796:     VecDestroy(&x);
797:   }
798:   PetscObjectSAWsBlock((PetscObject)ksp);
799:   if (ksp->errorifnotconverged && ksp->reason < 0) SETERRQ(comm,PETSC_ERR_NOT_CONVERGED,"KSPSolve has not converged");
800:   return(0);
801: }

805: /*@
806:    KSPSolveTranspose - Solves the transpose of a linear system.

808:    Collective on KSP

810:    Input Parameter:
811: +  ksp - iterative context obtained from KSPCreate()
812: .  b - right hand side vector
813: -  x - solution vector

815:    Notes: For complex numbers this solve the non-Hermitian transpose system.

817:    Developer Notes: We need to implement a KSPSolveHermitianTranspose()

819:    Level: developer

821: .keywords: KSP, solve, linear system

823: .seealso: KSPCreate(), KSPSetUp(), KSPDestroy(), KSPSetTolerances(), KSPConvergedDefault(),
824:           KSPSolve()
825: @*/

827: PetscErrorCode  KSPSolveTranspose(KSP ksp,Vec b,Vec x)
828: {
830:   PetscBool      inXisinB=PETSC_FALSE;

836:   if (x == b) {
837:     VecDuplicate(b,&x);
838:     inXisinB = PETSC_TRUE;
839:   }
840:   PetscObjectReference((PetscObject)b);
841:   PetscObjectReference((PetscObject)x);
842:   VecDestroy(&ksp->vec_rhs);
843:   VecDestroy(&ksp->vec_sol);

845:   ksp->vec_rhs         = b;
846:   ksp->vec_sol         = x;
847:   ksp->transpose_solve = PETSC_TRUE;

849:   KSPSetUp(ksp);
850:   if (ksp->guess_zero) { VecSet(ksp->vec_sol,0.0);}
851:   (*ksp->ops->solve)(ksp);
852:   if (!ksp->reason) SETERRQ(PetscObjectComm((PetscObject)ksp),PETSC_ERR_PLIB,"Internal error, solver returned without setting converged reason");
853:   KSPReasonViewFromOptions(ksp);
854:   if (inXisinB) {
855:     VecCopy(x,b);
856:     VecDestroy(&x);
857:   }
858:   if (ksp->errorifnotconverged && ksp->reason < 0) SETERRQ(PetscObjectComm((PetscObject)ksp),PETSC_ERR_NOT_CONVERGED,"KSPSolve has not converged");
859:   return(0);
860: }

864: /*@
865:    KSPReset - Resets a KSP context to the kspsetupcalled = 0 state and removes any allocated Vecs and Mats

867:    Collective on KSP

869:    Input Parameter:
870: .  ksp - iterative context obtained from KSPCreate()

872:    Level: beginner

874: .keywords: KSP, destroy

876: .seealso: KSPCreate(), KSPSetUp(), KSPSolve()
877: @*/
878: PetscErrorCode  KSPReset(KSP ksp)
879: {

884:   if (!ksp) return(0);
885:   if (ksp->ops->reset) {
886:     (*ksp->ops->reset)(ksp);
887:   }
888:   if (ksp->pc) {PCReset(ksp->pc);}
889:   KSPFischerGuessDestroy(&ksp->guess);
890:   VecDestroyVecs(ksp->nwork,&ksp->work);
891:   VecDestroy(&ksp->vec_rhs);
892:   VecDestroy(&ksp->vec_sol);
893:   VecDestroy(&ksp->diagonal);
894:   VecDestroy(&ksp->truediagonal);

896:   ksp->setupstage = KSP_SETUP_NEW;
897:   return(0);
898: }

902: /*@
903:    KSPDestroy - Destroys KSP context.

905:    Collective on KSP

907:    Input Parameter:
908: .  ksp - iterative context obtained from KSPCreate()

910:    Level: beginner

912: .keywords: KSP, destroy

914: .seealso: KSPCreate(), KSPSetUp(), KSPSolve()
915: @*/
916: PetscErrorCode  KSPDestroy(KSP *ksp)
917: {
919:   PC             pc;

922:   if (!*ksp) return(0);
924:   if (--((PetscObject)(*ksp))->refct > 0) {*ksp = 0; return(0);}

926:   PetscObjectSAWsViewOff((PetscObject)*ksp);
927:   /*
928:    Avoid a cascading call to PCReset(ksp->pc) from the following call:
929:    PCReset() shouldn't be called from KSPDestroy() as it is unprotected by pc's
930:    refcount (and may be shared, e.g., by other ksps).
931:    */
932:   pc         = (*ksp)->pc;
933:   (*ksp)->pc = NULL;
934:   KSPReset((*ksp));
935:   (*ksp)->pc = pc;
936:     if ((*ksp)->ops->destroy) {(*(*ksp)->ops->destroy)(*ksp);}

938:   DMDestroy(&(*ksp)->dm);
939:   PCDestroy(&(*ksp)->pc);
940:   PetscFree((*ksp)->res_hist_alloc);
941:   if ((*ksp)->convergeddestroy) {
942:     (*(*ksp)->convergeddestroy)((*ksp)->cnvP);
943:   }
944:   KSPMonitorCancel((*ksp));
945:   PetscViewerDestroy(&(*ksp)->eigviewer);
946:   PetscHeaderDestroy(ksp);
947:   return(0);
948: }

952: /*@
953:     KSPSetPCSide - Sets the preconditioning side.

955:     Logically Collective on KSP

957:     Input Parameter:
958: .   ksp - iterative context obtained from KSPCreate()

960:     Output Parameter:
961: .   side - the preconditioning side, where side is one of
962: .vb
963:       PC_LEFT - left preconditioning (default)
964:       PC_RIGHT - right preconditioning
965:       PC_SYMMETRIC - symmetric preconditioning
966: .ve

968:     Options Database Keys:
969: .   -ksp_pc_side <right,left,symmetric>

971:     Notes:
972:     Left preconditioning is used by default for most Krylov methods except KSPFGMRES which only supports right preconditioning.

974:     For methods changing the side of the preconditioner changes the norm type that is used, see KSPSetNormType().

976:     Symmetric preconditioning is currently available only for the KSPQCG method. Note, however, that
977:     symmetric preconditioning can be emulated by using either right or left
978:     preconditioning and a pre or post processing step.

980:     Setting the PC side often affects the default norm type.  See KSPSetNormType() for details.

982:     Level: intermediate

984: .keywords: KSP, set, right, left, symmetric, side, preconditioner, flag

986: .seealso: KSPGetPCSide(), KSPSetNormType(), KSPGetNormType()
987: @*/
988: PetscErrorCode  KSPSetPCSide(KSP ksp,PCSide side)
989: {
993:   ksp->pc_side = ksp->pc_side_set = side;
994:   return(0);
995: }

999: /*@
1000:     KSPGetPCSide - Gets the preconditioning side.

1002:     Not Collective

1004:     Input Parameter:
1005: .   ksp - iterative context obtained from KSPCreate()

1007:     Output Parameter:
1008: .   side - the preconditioning side, where side is one of
1009: .vb
1010:       PC_LEFT - left preconditioning (default)
1011:       PC_RIGHT - right preconditioning
1012:       PC_SYMMETRIC - symmetric preconditioning
1013: .ve

1015:     Level: intermediate

1017: .keywords: KSP, get, right, left, symmetric, side, preconditioner, flag

1019: .seealso: KSPSetPCSide()
1020: @*/
1021: PetscErrorCode  KSPGetPCSide(KSP ksp,PCSide *side)
1022: {

1028:   KSPSetUpNorms_Private(ksp,&ksp->normtype,&ksp->pc_side);
1029:   *side = ksp->pc_side;
1030:   return(0);
1031: }

1035: /*@
1036:    KSPGetTolerances - Gets the relative, absolute, divergence, and maximum
1037:    iteration tolerances used by the default KSP convergence tests.

1039:    Not Collective

1041:    Input Parameter:
1042: .  ksp - the Krylov subspace context

1044:    Output Parameters:
1045: +  rtol - the relative convergence tolerance
1046: .  abstol - the absolute convergence tolerance
1047: .  dtol - the divergence tolerance
1048: -  maxits - maximum number of iterations

1050:    Notes:
1051:    The user can specify NULL for any parameter that is not needed.

1053:    Level: intermediate

1055: .keywords: KSP, get, tolerance, absolute, relative, divergence, convergence,
1056:            maximum, iterations

1058: .seealso: KSPSetTolerances()
1059: @*/
1060: PetscErrorCode  KSPGetTolerances(KSP ksp,PetscReal *rtol,PetscReal *abstol,PetscReal *dtol,PetscInt *maxits)
1061: {
1064:   if (abstol) *abstol = ksp->abstol;
1065:   if (rtol) *rtol = ksp->rtol;
1066:   if (dtol) *dtol = ksp->divtol;
1067:   if (maxits) *maxits = ksp->max_it;
1068:   return(0);
1069: }

1073: /*@
1074:    KSPSetTolerances - Sets the relative, absolute, divergence, and maximum
1075:    iteration tolerances used by the default KSP convergence testers.

1077:    Logically Collective on KSP

1079:    Input Parameters:
1080: +  ksp - the Krylov subspace context
1081: .  rtol - the relative convergence tolerance, relative decrease in the (possibly preconditioned) residual norm
1082: .  abstol - the absolute convergence tolerance   absolute size of the (possibly preconditioned) residual norm
1083: .  dtol - the divergence tolerance,   amount (possibly preconditioned) residual norm can increase before KSPConvergedDefault() concludes that the method is diverging
1084: -  maxits - maximum number of iterations to use

1086:    Options Database Keys:
1087: +  -ksp_atol <abstol> - Sets abstol
1088: .  -ksp_rtol <rtol> - Sets rtol
1089: .  -ksp_divtol <dtol> - Sets dtol
1090: -  -ksp_max_it <maxits> - Sets maxits

1092:    Notes:
1093:    Use PETSC_DEFAULT to retain the default value of any of the tolerances.

1095:    See KSPConvergedDefault() for details how these parameters are used in the default convergence test.  See also KSPSetConvergenceTest()
1096:    for setting user-defined stopping criteria.

1098:    Level: intermediate

1100: .keywords: KSP, set, tolerance, absolute, relative, divergence,
1101:            convergence, maximum, iterations

1103: .seealso: KSPGetTolerances(), KSPConvergedDefault(), KSPSetConvergenceTest()
1104: @*/
1105: PetscErrorCode  KSPSetTolerances(KSP ksp,PetscReal rtol,PetscReal abstol,PetscReal dtol,PetscInt maxits)
1106: {

1114:   if (rtol != PETSC_DEFAULT) {
1115:     if (rtol < 0.0 || 1.0 <= rtol) SETERRQ1(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_OUTOFRANGE,"Relative tolerance %g must be non-negative and less than 1.0",(double)rtol);
1116:     ksp->rtol = rtol;
1117:   }
1118:   if (abstol != PETSC_DEFAULT) {
1119:     if (abstol < 0.0) SETERRQ1(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_OUTOFRANGE,"Absolute tolerance %g must be non-negative",(double)abstol);
1120:     ksp->abstol = abstol;
1121:   }
1122:   if (dtol != PETSC_DEFAULT) {
1123:     if (dtol < 0.0) SETERRQ1(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_OUTOFRANGE,"Divergence tolerance %g must be larger than 1.0",(double)dtol);
1124:     ksp->divtol = dtol;
1125:   }
1126:   if (maxits != PETSC_DEFAULT) {
1127:     if (maxits < 0) SETERRQ1(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of iterations %D must be non-negative",maxits);
1128:     ksp->max_it = maxits;
1129:   }
1130:   return(0);
1131: }

1135: /*@
1136:    KSPSetInitialGuessNonzero - Tells the iterative solver that the
1137:    initial guess is nonzero; otherwise KSP assumes the initial guess
1138:    is to be zero (and thus zeros it out before solving).

1140:    Logically Collective on KSP

1142:    Input Parameters:
1143: +  ksp - iterative context obtained from KSPCreate()
1144: -  flg - PETSC_TRUE indicates the guess is non-zero, PETSC_FALSE indicates the guess is zero

1146:    Options database keys:
1147: .  -ksp_initial_guess_nonzero : use nonzero initial guess; this takes an optional truth value (0/1/no/yes/true/false)

1149:    Level: beginner

1151:    Notes:
1152:     If this is not called the X vector is zeroed in the call to KSPSolve().

1154: .keywords: KSP, set, initial guess, nonzero

1156: .seealso: KSPGetInitialGuessNonzero(), KSPSetInitialGuessKnoll(), KSPGetInitialGuessKnoll()
1157: @*/
1158: PetscErrorCode  KSPSetInitialGuessNonzero(KSP ksp,PetscBool flg)
1159: {
1163:   ksp->guess_zero = (PetscBool) !(int)flg;
1164:   return(0);
1165: }

1169: /*@
1170:    KSPGetInitialGuessNonzero - Determines whether the KSP solver is using
1171:    a zero initial guess.

1173:    Not Collective

1175:    Input Parameter:
1176: .  ksp - iterative context obtained from KSPCreate()

1178:    Output Parameter:
1179: .  flag - PETSC_TRUE if guess is nonzero, else PETSC_FALSE

1181:    Level: intermediate

1183: .keywords: KSP, set, initial guess, nonzero

1185: .seealso: KSPSetInitialGuessNonzero(), KSPSetInitialGuessKnoll(), KSPGetInitialGuessKnoll()
1186: @*/
1187: PetscErrorCode  KSPGetInitialGuessNonzero(KSP ksp,PetscBool  *flag)
1188: {
1192:   if (ksp->guess_zero) *flag = PETSC_FALSE;
1193:   else *flag = PETSC_TRUE;
1194:   return(0);
1195: }

1199: /*@
1200:    KSPSetErrorIfNotConverged - Causes KSPSolve() to generate an error if the solver has not converged.

1202:    Logically Collective on KSP

1204:    Input Parameters:
1205: +  ksp - iterative context obtained from KSPCreate()
1206: -  flg - PETSC_TRUE indicates you want the error generated

1208:    Options database keys:
1209: .  -ksp_error_if_not_converged : this takes an optional truth value (0/1/no/yes/true/false)

1211:    Level: intermediate

1213:    Notes:
1214:     Normally PETSc continues if a linear solver fails to converge, you can call KSPGetConvergedReason() after a KSPSolve()
1215:     to determine if it has converged.

1217: .keywords: KSP, set, initial guess, nonzero

1219: .seealso: KSPGetInitialGuessNonzero(), KSPSetInitialGuessKnoll(), KSPGetInitialGuessKnoll(), KSPGetErrorIfNotConverged()
1220: @*/
1221: PetscErrorCode  KSPSetErrorIfNotConverged(KSP ksp,PetscBool flg)
1222: {
1226:   ksp->errorifnotconverged = flg;
1227:   return(0);
1228: }

1232: /*@
1233:    KSPGetErrorIfNotConverged - Will KSPSolve() generate an error if the solver does not converge?

1235:    Not Collective

1237:    Input Parameter:
1238: .  ksp - iterative context obtained from KSPCreate()

1240:    Output Parameter:
1241: .  flag - PETSC_TRUE if it will generate an error, else PETSC_FALSE

1243:    Level: intermediate

1245: .keywords: KSP, set, initial guess, nonzero

1247: .seealso: KSPSetInitialGuessNonzero(), KSPSetInitialGuessKnoll(), KSPGetInitialGuessKnoll(), KSPSetErrorIfNotConverged()
1248: @*/
1249: PetscErrorCode  KSPGetErrorIfNotConverged(KSP ksp,PetscBool  *flag)
1250: {
1254:   *flag = ksp->errorifnotconverged;
1255:   return(0);
1256: }

1260: /*@
1261:    KSPSetInitialGuessKnoll - Tells the iterative solver to use PCApply(pc,b,..) to compute the initial guess (The Knoll trick)

1263:    Logically Collective on KSP

1265:    Input Parameters:
1266: +  ksp - iterative context obtained from KSPCreate()
1267: -  flg - PETSC_TRUE or PETSC_FALSE

1269:    Level: advanced


1272: .keywords: KSP, set, initial guess, nonzero

1274: .seealso: KSPGetInitialGuessKnoll(), KSPSetInitialGuessNonzero(), KSPGetInitialGuessNonzero()
1275: @*/
1276: PetscErrorCode  KSPSetInitialGuessKnoll(KSP ksp,PetscBool flg)
1277: {
1281:   ksp->guess_knoll = flg;
1282:   return(0);
1283: }

1287: /*@
1288:    KSPGetInitialGuessKnoll - Determines whether the KSP solver is using the Knoll trick (using PCApply(pc,b,...) to compute
1289:      the initial guess

1291:    Not Collective

1293:    Input Parameter:
1294: .  ksp - iterative context obtained from KSPCreate()

1296:    Output Parameter:
1297: .  flag - PETSC_TRUE if using Knoll trick, else PETSC_FALSE

1299:    Level: advanced

1301: .keywords: KSP, set, initial guess, nonzero

1303: .seealso: KSPSetInitialGuessKnoll(), KSPSetInitialGuessNonzero(), KSPGetInitialGuessNonzero()
1304: @*/
1305: PetscErrorCode  KSPGetInitialGuessKnoll(KSP ksp,PetscBool  *flag)
1306: {
1310:   *flag = ksp->guess_knoll;
1311:   return(0);
1312: }

1316: /*@
1317:    KSPGetComputeSingularValues - Gets the flag indicating whether the extreme singular
1318:    values will be calculated via a Lanczos or Arnoldi process as the linear
1319:    system is solved.

1321:    Not Collective

1323:    Input Parameter:
1324: .  ksp - iterative context obtained from KSPCreate()

1326:    Output Parameter:
1327: .  flg - PETSC_TRUE or PETSC_FALSE

1329:    Options Database Key:
1330: .  -ksp_monitor_singular_value - Activates KSPSetComputeSingularValues()

1332:    Notes:
1333:    Currently this option is not valid for all iterative methods.

1335:    Many users may just want to use the monitoring routine
1336:    KSPMonitorSingularValue() (which can be set with option -ksp_monitor_singular_value)
1337:    to print the singular values at each iteration of the linear solve.

1339:    Level: advanced

1341: .keywords: KSP, set, compute, singular values

1343: .seealso: KSPComputeExtremeSingularValues(), KSPMonitorSingularValue()
1344: @*/
1345: PetscErrorCode  KSPGetComputeSingularValues(KSP ksp,PetscBool  *flg)
1346: {
1350:   *flg = ksp->calc_sings;
1351:   return(0);
1352: }

1356: /*@
1357:    KSPSetComputeSingularValues - Sets a flag so that the extreme singular
1358:    values will be calculated via a Lanczos or Arnoldi process as the linear
1359:    system is solved.

1361:    Logically Collective on KSP

1363:    Input Parameters:
1364: +  ksp - iterative context obtained from KSPCreate()
1365: -  flg - PETSC_TRUE or PETSC_FALSE

1367:    Options Database Key:
1368: .  -ksp_monitor_singular_value - Activates KSPSetComputeSingularValues()

1370:    Notes:
1371:    Currently this option is not valid for all iterative methods.

1373:    Many users may just want to use the monitoring routine
1374:    KSPMonitorSingularValue() (which can be set with option -ksp_monitor_singular_value)
1375:    to print the singular values at each iteration of the linear solve.

1377:    Level: advanced

1379: .keywords: KSP, set, compute, singular values

1381: .seealso: KSPComputeExtremeSingularValues(), KSPMonitorSingularValue()
1382: @*/
1383: PetscErrorCode  KSPSetComputeSingularValues(KSP ksp,PetscBool flg)
1384: {
1388:   ksp->calc_sings = flg;
1389:   return(0);
1390: }

1394: /*@
1395:    KSPGetComputeEigenvalues - Gets the flag indicating that the extreme eigenvalues
1396:    values will be calculated via a Lanczos or Arnoldi process as the linear
1397:    system is solved.

1399:    Not Collective

1401:    Input Parameter:
1402: .  ksp - iterative context obtained from KSPCreate()

1404:    Output Parameter:
1405: .  flg - PETSC_TRUE or PETSC_FALSE

1407:    Notes:
1408:    Currently this option is not valid for all iterative methods.

1410:    Level: advanced

1412: .keywords: KSP, set, compute, eigenvalues

1414: .seealso: KSPComputeEigenvalues(), KSPComputeEigenvaluesExplicitly()
1415: @*/
1416: PetscErrorCode  KSPGetComputeEigenvalues(KSP ksp,PetscBool  *flg)
1417: {
1421:   *flg = ksp->calc_sings;
1422:   return(0);
1423: }

1427: /*@
1428:    KSPSetComputeEigenvalues - Sets a flag so that the extreme eigenvalues
1429:    values will be calculated via a Lanczos or Arnoldi process as the linear
1430:    system is solved.

1432:    Logically Collective on KSP

1434:    Input Parameters:
1435: +  ksp - iterative context obtained from KSPCreate()
1436: -  flg - PETSC_TRUE or PETSC_FALSE

1438:    Notes:
1439:    Currently this option is not valid for all iterative methods.

1441:    Level: advanced

1443: .keywords: KSP, set, compute, eigenvalues

1445: .seealso: KSPComputeEigenvalues(), KSPComputeEigenvaluesExplicitly()
1446: @*/
1447: PetscErrorCode  KSPSetComputeEigenvalues(KSP ksp,PetscBool flg)
1448: {
1452:   ksp->calc_sings = flg;
1453:   return(0);
1454: }

1458: /*@
1459:    KSPGetRhs - Gets the right-hand-side vector for the linear system to
1460:    be solved.

1462:    Not Collective

1464:    Input Parameter:
1465: .  ksp - iterative context obtained from KSPCreate()

1467:    Output Parameter:
1468: .  r - right-hand-side vector

1470:    Level: developer

1472: .keywords: KSP, get, right-hand-side, rhs

1474: .seealso: KSPGetSolution(), KSPSolve()
1475: @*/
1476: PetscErrorCode  KSPGetRhs(KSP ksp,Vec *r)
1477: {
1481:   *r = ksp->vec_rhs;
1482:   return(0);
1483: }

1487: /*@
1488:    KSPGetSolution - Gets the location of the solution for the
1489:    linear system to be solved.  Note that this may not be where the solution
1490:    is stored during the iterative process; see KSPBuildSolution().

1492:    Not Collective

1494:    Input Parameters:
1495: .  ksp - iterative context obtained from KSPCreate()

1497:    Output Parameters:
1498: .  v - solution vector

1500:    Level: developer

1502: .keywords: KSP, get, solution

1504: .seealso: KSPGetRhs(),  KSPBuildSolution(), KSPSolve()
1505: @*/
1506: PetscErrorCode  KSPGetSolution(KSP ksp,Vec *v)
1507: {
1511:   *v = ksp->vec_sol;
1512:   return(0);
1513: }

1517: /*@
1518:    KSPSetPC - Sets the preconditioner to be used to calculate the
1519:    application of the preconditioner on a vector.

1521:    Collective on KSP

1523:    Input Parameters:
1524: +  ksp - iterative context obtained from KSPCreate()
1525: -  pc   - the preconditioner object

1527:    Notes:
1528:    Use KSPGetPC() to retrieve the preconditioner context (for example,
1529:    to free it at the end of the computations).

1531:    Level: developer

1533: .keywords: KSP, set, precondition, Binv

1535: .seealso: KSPGetPC()
1536: @*/
1537: PetscErrorCode  KSPSetPC(KSP ksp,PC pc)
1538: {

1545:   PetscObjectReference((PetscObject)pc);
1546:   PCDestroy(&ksp->pc);
1547:   ksp->pc = pc;
1548:   PetscLogObjectParent((PetscObject)ksp,(PetscObject)ksp->pc);
1549:   return(0);
1550: }

1554: /*@
1555:    KSPGetPC - Returns a pointer to the preconditioner context
1556:    set with KSPSetPC().

1558:    Not Collective

1560:    Input Parameters:
1561: .  ksp - iterative context obtained from KSPCreate()

1563:    Output Parameter:
1564: .  pc - preconditioner context

1566:    Level: developer

1568: .keywords: KSP, get, preconditioner, Binv

1570: .seealso: KSPSetPC()
1571: @*/
1572: PetscErrorCode  KSPGetPC(KSP ksp,PC *pc)
1573: {

1579:   if (!ksp->pc) {
1580:     PCCreate(PetscObjectComm((PetscObject)ksp),&ksp->pc);
1581:     PetscObjectIncrementTabLevel((PetscObject)ksp->pc,(PetscObject)ksp,0);
1582:     PetscLogObjectParent((PetscObject)ksp,(PetscObject)ksp->pc);
1583:   }
1584:   *pc = ksp->pc;
1585:   return(0);
1586: }

1590: /*@
1591:    KSPMonitor - runs the user provided monitor routines, if they exist

1593:    Collective on KSP

1595:    Input Parameters:
1596: +  ksp - iterative context obtained from KSPCreate()
1597: .  it - iteration number
1598: -  rnorm - relative norm of the residual

1600:    Notes:
1601:    This routine is called by the KSP implementations.
1602:    It does not typically need to be called by the user.

1604:    Level: developer

1606: .seealso: KSPMonitorSet()
1607: @*/
1608: PetscErrorCode KSPMonitor(KSP ksp,PetscInt it,PetscReal rnorm)
1609: {
1610:   PetscInt       i, n = ksp->numbermonitors;

1614:   for (i=0; i<n; i++) {
1615:     (*ksp->monitor[i])(ksp,it,rnorm,ksp->monitorcontext[i]);
1616:   }
1617:   return(0);
1618: }

1622: /*@C
1623:    KSPMonitorSet - Sets an ADDITIONAL function to be called at every iteration to monitor
1624:    the residual/error etc.

1626:    Logically Collective on KSP

1628:    Input Parameters:
1629: +  ksp - iterative context obtained from KSPCreate()
1630: .  monitor - pointer to function (if this is NULL, it turns off monitoring
1631: .  mctx    - [optional] context for private data for the
1632:              monitor routine (use NULL if no context is desired)
1633: -  monitordestroy - [optional] routine that frees monitor context
1634:           (may be NULL)

1636:    Calling Sequence of monitor:
1637: $     monitor (KSP ksp, int it, PetscReal rnorm, void *mctx)

1639: +  ksp - iterative context obtained from KSPCreate()
1640: .  it - iteration number
1641: .  rnorm - (estimated) 2-norm of (preconditioned) residual
1642: -  mctx  - optional monitoring context, as set by KSPMonitorSet()

1644:    Options Database Keys:
1645: +    -ksp_monitor        - sets KSPMonitorDefault()
1646: .    -ksp_monitor_true_residual    - sets KSPMonitorTrueResidualNorm()
1647: .    -ksp_monitor_max    - sets KSPMonitorTrueResidualMaxNorm()
1648: .    -ksp_monitor_lg_residualnorm    - sets line graph monitor,
1649:                            uses KSPMonitorLGResidualNormCreate()
1650: .    -ksp_monitor_lg_true_residualnorm   - sets line graph monitor,
1651:                            uses KSPMonitorLGResidualNormCreate()
1652: .    -ksp_monitor_singular_value    - sets KSPMonitorSingularValue()
1653: -    -ksp_monitor_cancel - cancels all monitors that have
1654:                           been hardwired into a code by
1655:                           calls to KSPMonitorSet(), but
1656:                           does not cancel those set via
1657:                           the options database.

1659:    Notes:
1660:    The default is to do nothing.  To print the residual, or preconditioned
1661:    residual if KSPSetNormType(ksp,KSP_NORM_PRECONDITIONED) was called, use
1662:    KSPMonitorDefault() as the monitoring routine, with a null monitoring
1663:    context.

1665:    Several different monitoring routines may be set by calling
1666:    KSPMonitorSet() multiple times; all will be called in the
1667:    order in which they were set.

1669:    Fortran notes: Only a single monitor function can be set for each KSP object

1671:    Level: beginner

1673: .keywords: KSP, set, monitor

1675: .seealso: KSPMonitorDefault(), KSPMonitorLGResidualNormCreate(), KSPMonitorCancel()
1676: @*/
1677: PetscErrorCode  KSPMonitorSet(KSP ksp,PetscErrorCode (*monitor)(KSP,PetscInt,PetscReal,void*),void *mctx,PetscErrorCode (*monitordestroy)(void**))
1678: {
1679:   PetscInt       i;

1684:   if (ksp->numbermonitors >= MAXKSPMONITORS) SETERRQ(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_OUTOFRANGE,"Too many KSP monitors set");
1685:   for (i=0; i<ksp->numbermonitors;i++) {
1686:     if (monitor == ksp->monitor[i] && monitordestroy == ksp->monitordestroy[i] && mctx == ksp->monitorcontext[i]) {
1687:       if (monitordestroy) {
1688:         (*monitordestroy)(&mctx);
1689:       }
1690:       return(0);
1691:     }
1692:   }
1693:   ksp->monitor[ksp->numbermonitors]          = monitor;
1694:   ksp->monitordestroy[ksp->numbermonitors]   = monitordestroy;
1695:   ksp->monitorcontext[ksp->numbermonitors++] = (void*)mctx;
1696:   return(0);
1697: }

1701: /*@
1702:    KSPMonitorCancel - Clears all monitors for a KSP object.

1704:    Logically Collective on KSP

1706:    Input Parameters:
1707: .  ksp - iterative context obtained from KSPCreate()

1709:    Options Database Key:
1710: .  -ksp_monitor_cancel - Cancels all monitors that have
1711:     been hardwired into a code by calls to KSPMonitorSet(),
1712:     but does not cancel those set via the options database.

1714:    Level: intermediate

1716: .keywords: KSP, set, monitor

1718: .seealso: KSPMonitorDefault(), KSPMonitorLGResidualNormCreate(), KSPMonitorSet()
1719: @*/
1720: PetscErrorCode  KSPMonitorCancel(KSP ksp)
1721: {
1723:   PetscInt       i;

1727:   for (i=0; i<ksp->numbermonitors; i++) {
1728:     if (ksp->monitordestroy[i]) {
1729:       (*ksp->monitordestroy[i])(&ksp->monitorcontext[i]);
1730:     }
1731:   }
1732:   ksp->numbermonitors = 0;
1733:   return(0);
1734: }

1738: /*@C
1739:    KSPGetMonitorContext - Gets the monitoring context, as set by
1740:    KSPMonitorSet() for the FIRST monitor only.

1742:    Not Collective

1744:    Input Parameter:
1745: .  ksp - iterative context obtained from KSPCreate()

1747:    Output Parameter:
1748: .  ctx - monitoring context

1750:    Level: intermediate

1752: .keywords: KSP, get, monitor, context

1754: .seealso: KSPMonitorDefault(), KSPMonitorLGResidualNormCreate()
1755: @*/
1756: PetscErrorCode  KSPGetMonitorContext(KSP ksp,void **ctx)
1757: {
1760:   *ctx =      (ksp->monitorcontext[0]);
1761:   return(0);
1762: }

1766: /*@
1767:    KSPSetResidualHistory - Sets the array used to hold the residual history.
1768:    If set, this array will contain the residual norms computed at each
1769:    iteration of the solver.

1771:    Not Collective

1773:    Input Parameters:
1774: +  ksp - iterative context obtained from KSPCreate()
1775: .  a   - array to hold history
1776: .  na  - size of a
1777: -  reset - PETSC_TRUE indicates the history counter is reset to zero
1778:            for each new linear solve

1780:    Level: advanced

1782:    Notes: The array is NOT freed by PETSc so the user needs to keep track of
1783:            it and destroy once the KSP object is destroyed.

1785:    If 'a' is NULL then space is allocated for the history. If 'na' PETSC_DECIDE or PETSC_DEFAULT then a
1786:    default array of length 10000 is allocated.

1788: .keywords: KSP, set, residual, history, norm

1790: .seealso: KSPGetResidualHistory()

1792: @*/
1793: PetscErrorCode  KSPSetResidualHistory(KSP ksp,PetscReal a[],PetscInt na,PetscBool reset)
1794: {


1800:   PetscFree(ksp->res_hist_alloc);
1801:   if (na != PETSC_DECIDE && na != PETSC_DEFAULT && a) {
1802:     ksp->res_hist     = a;
1803:     ksp->res_hist_max = na;
1804:   } else {
1805:     if (na != PETSC_DECIDE && na != PETSC_DEFAULT) ksp->res_hist_max = na;
1806:     else                                           ksp->res_hist_max = 10000; /* like default ksp->max_it */
1807:     PetscCalloc1(ksp->res_hist_max,&ksp->res_hist_alloc);

1809:     ksp->res_hist = ksp->res_hist_alloc;
1810:   }
1811:   ksp->res_hist_len   = 0;
1812:   ksp->res_hist_reset = reset;
1813:   return(0);
1814: }

1818: /*@C
1819:    KSPGetResidualHistory - Gets the array used to hold the residual history
1820:    and the number of residuals it contains.

1822:    Not Collective

1824:    Input Parameter:
1825: .  ksp - iterative context obtained from KSPCreate()

1827:    Output Parameters:
1828: +  a   - pointer to array to hold history (or NULL)
1829: -  na  - number of used entries in a (or NULL)

1831:    Level: advanced

1833:    Notes:
1834:      Can only be called after a KSPSetResidualHistory() otherwise a and na are set to zero

1836:      The Fortran version of this routine has a calling sequence
1837: $   call KSPGetResidualHistory(KSP ksp, integer na, integer ierr)
1838:     note that you have passed a Fortran array into KSPSetResidualHistory() and you need
1839:     to access the residual values from this Fortran array you provided. Only the na (number of
1840:     residual norms currently held) is set.

1842: .keywords: KSP, get, residual, history, norm

1844: .seealso: KSPGetResidualHistory()

1846: @*/
1847: PetscErrorCode  KSPGetResidualHistory(KSP ksp,PetscReal *a[],PetscInt *na)
1848: {
1851:   if (a) *a = ksp->res_hist;
1852:   if (na) *na = ksp->res_hist_len;
1853:   return(0);
1854: }

1858: /*@C
1859:    KSPSetConvergenceTest - Sets the function to be used to determine
1860:    convergence.

1862:    Logically Collective on KSP

1864:    Input Parameters:
1865: +  ksp - iterative context obtained from KSPCreate()
1866: .  converge - pointer to int function
1867: .  cctx    - context for private data for the convergence routine (may be null)
1868: -  destroy - a routine for destroying the context (may be null)

1870:    Calling sequence of converge:
1871: $     converge (KSP ksp, int it, PetscReal rnorm, KSPConvergedReason *reason,void *mctx)

1873: +  ksp - iterative context obtained from KSPCreate()
1874: .  it - iteration number
1875: .  rnorm - (estimated) 2-norm of (preconditioned) residual
1876: .  reason - the reason why it has converged or diverged
1877: -  cctx  - optional convergence context, as set by KSPSetConvergenceTest()


1880:    Notes:
1881:    Must be called after the KSP type has been set so put this after
1882:    a call to KSPSetType(), or KSPSetFromOptions().

1884:    The default convergence test, KSPConvergedDefault(), aborts if the
1885:    residual grows to more than 10000 times the initial residual.

1887:    The default is a combination of relative and absolute tolerances.
1888:    The residual value that is tested may be an approximation; routines
1889:    that need exact values should compute them.

1891:    In the default PETSc convergence test, the precise values of reason
1892:    are macros such as KSP_CONVERGED_RTOL, which are defined in petscksp.h.

1894:    Level: advanced

1896: .keywords: KSP, set, convergence, test, context

1898: .seealso: KSPConvergedDefault(), KSPGetConvergenceContext(), KSPSetTolerances()
1899: @*/
1900: PetscErrorCode  KSPSetConvergenceTest(KSP ksp,PetscErrorCode (*converge)(KSP,PetscInt,PetscReal,KSPConvergedReason*,void*),void *cctx,PetscErrorCode (*destroy)(void*))
1901: {

1906:   if (ksp->convergeddestroy) {
1907:     (*ksp->convergeddestroy)(ksp->cnvP);
1908:   }
1909:   ksp->converged        = converge;
1910:   ksp->convergeddestroy = destroy;
1911:   ksp->cnvP             = (void*)cctx;
1912:   return(0);
1913: }

1917: /*@C
1918:    KSPGetConvergenceContext - Gets the convergence context set with
1919:    KSPSetConvergenceTest().

1921:    Not Collective

1923:    Input Parameter:
1924: .  ksp - iterative context obtained from KSPCreate()

1926:    Output Parameter:
1927: .  ctx - monitoring context

1929:    Level: advanced

1931: .keywords: KSP, get, convergence, test, context

1933: .seealso: KSPConvergedDefault(), KSPSetConvergenceTest()
1934: @*/
1935: PetscErrorCode  KSPGetConvergenceContext(KSP ksp,void **ctx)
1936: {
1939:   *ctx = ksp->cnvP;
1940:   return(0);
1941: }

1945: /*@C
1946:    KSPBuildSolution - Builds the approximate solution in a vector provided.
1947:    This routine is NOT commonly needed (see KSPSolve()).

1949:    Collective on KSP

1951:    Input Parameter:
1952: .  ctx - iterative context obtained from KSPCreate()

1954:    Output Parameter:
1955:    Provide exactly one of
1956: +  v - location to stash solution.
1957: -  V - the solution is returned in this location. This vector is created
1958:        internally. This vector should NOT be destroyed by the user with
1959:        VecDestroy().

1961:    Notes:
1962:    This routine can be used in one of two ways
1963: .vb
1964:       KSPBuildSolution(ksp,NULL,&V);
1965:    or
1966:       KSPBuildSolution(ksp,v,NULL); or KSPBuildSolution(ksp,v,&v);
1967: .ve
1968:    In the first case an internal vector is allocated to store the solution
1969:    (the user cannot destroy this vector). In the second case the solution
1970:    is generated in the vector that the user provides. Note that for certain
1971:    methods, such as KSPCG, the second case requires a copy of the solution,
1972:    while in the first case the call is essentially free since it simply
1973:    returns the vector where the solution already is stored. For some methods
1974:    like GMRES this is a reasonably expensive operation and should only be
1975:    used in truly needed.

1977:    Level: advanced

1979: .keywords: KSP, build, solution

1981: .seealso: KSPGetSolution(), KSPBuildResidual()
1982: @*/
1983: PetscErrorCode  KSPBuildSolution(KSP ksp,Vec v,Vec *V)
1984: {

1989:   if (!V && !v) SETERRQ(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_WRONG,"Must provide either v or V");
1990:   if (!V) V = &v;
1991:   (*ksp->ops->buildsolution)(ksp,v,V);
1992:   return(0);
1993: }

1997: /*@C
1998:    KSPBuildResidual - Builds the residual in a vector provided.

2000:    Collective on KSP

2002:    Input Parameter:
2003: .  ksp - iterative context obtained from KSPCreate()

2005:    Output Parameters:
2006: +  v - optional location to stash residual.  If v is not provided,
2007:        then a location is generated.
2008: .  t - work vector.  If not provided then one is generated.
2009: -  V - the residual

2011:    Notes:
2012:    Regardless of whether or not v is provided, the residual is
2013:    returned in V.

2015:    Level: advanced

2017: .keywords: KSP, build, residual

2019: .seealso: KSPBuildSolution()
2020: @*/
2021: PetscErrorCode  KSPBuildResidual(KSP ksp,Vec t,Vec v,Vec *V)
2022: {
2024:   PetscBool      flag = PETSC_FALSE;
2025:   Vec            w    = v,tt = t;

2029:   if (!w) {
2030:     VecDuplicate(ksp->vec_rhs,&w);
2031:     PetscLogObjectParent((PetscObject)ksp,(PetscObject)w);
2032:   }
2033:   if (!tt) {
2034:     VecDuplicate(ksp->vec_sol,&tt); flag = PETSC_TRUE;
2035:     PetscLogObjectParent((PetscObject)ksp,(PetscObject)tt);
2036:   }
2037:   (*ksp->ops->buildresidual)(ksp,tt,w,V);
2038:   if (flag) {VecDestroy(&tt);}
2039:   return(0);
2040: }

2044: /*@
2045:    KSPSetDiagonalScale - Tells KSP to symmetrically diagonally scale the system
2046:      before solving. This actually CHANGES the matrix (and right hand side).

2048:    Logically Collective on KSP

2050:    Input Parameter:
2051: +  ksp - the KSP context
2052: -  scale - PETSC_TRUE or PETSC_FALSE

2054:    Options Database Key:
2055: +   -ksp_diagonal_scale -
2056: -   -ksp_diagonal_scale_fix - scale the matrix back AFTER the solve


2059:     Notes: Scales the matrix by  D^(-1/2)  A  D^(-1/2)  [D^(1/2) x ] = D^(-1/2) b
2060:        where D_{ii} is 1/abs(A_{ii}) unless A_{ii} is zero and then it is 1.

2062:     BE CAREFUL with this routine: it actually scales the matrix and right
2063:     hand side that define the system. After the system is solved the matrix
2064:     and right hand side remain scaled unless you use KSPSetDiagonalScaleFix()

2066:     This should NOT be used within the SNES solves if you are using a line
2067:     search.

2069:     If you use this with the PCType Eisenstat preconditioner than you can
2070:     use the PCEisenstatSetNoDiagonalScaling() option, or -pc_eisenstat_no_diagonal_scaling
2071:     to save some unneeded, redundant flops.

2073:    Level: intermediate

2075: .keywords: KSP, set, options, prefix, database

2077: .seealso: KSPGetDiagonalScale(), KSPSetDiagonalScaleFix()
2078: @*/
2079: PetscErrorCode  KSPSetDiagonalScale(KSP ksp,PetscBool scale)
2080: {
2084:   ksp->dscale = scale;
2085:   return(0);
2086: }

2090: /*@
2091:    KSPGetDiagonalScale - Checks if KSP solver scales the matrix and
2092:                           right hand side

2094:    Not Collective

2096:    Input Parameter:
2097: .  ksp - the KSP context

2099:    Output Parameter:
2100: .  scale - PETSC_TRUE or PETSC_FALSE

2102:    Notes:
2103:     BE CAREFUL with this routine: it actually scales the matrix and right
2104:     hand side that define the system. After the system is solved the matrix
2105:     and right hand side remain scaled  unless you use KSPSetDiagonalScaleFix()

2107:    Level: intermediate

2109: .keywords: KSP, set, options, prefix, database

2111: .seealso: KSPSetDiagonalScale(), KSPSetDiagonalScaleFix()
2112: @*/
2113: PetscErrorCode  KSPGetDiagonalScale(KSP ksp,PetscBool  *scale)
2114: {
2118:   *scale = ksp->dscale;
2119:   return(0);
2120: }

2124: /*@
2125:    KSPSetDiagonalScaleFix - Tells KSP to diagonally scale the system
2126:      back after solving.

2128:    Logically Collective on KSP

2130:    Input Parameter:
2131: +  ksp - the KSP context
2132: -  fix - PETSC_TRUE to scale back after the system solve, PETSC_FALSE to not
2133:          rescale (default)

2135:    Notes:
2136:      Must be called after KSPSetDiagonalScale()

2138:      Using this will slow things down, because it rescales the matrix before and
2139:      after each linear solve. This is intended mainly for testing to allow one
2140:      to easily get back the original system to make sure the solution computed is
2141:      accurate enough.

2143:    Level: intermediate

2145: .keywords: KSP, set, options, prefix, database

2147: .seealso: KSPGetDiagonalScale(), KSPSetDiagonalScale(), KSPGetDiagonalScaleFix()
2148: @*/
2149: PetscErrorCode  KSPSetDiagonalScaleFix(KSP ksp,PetscBool fix)
2150: {
2154:   ksp->dscalefix = fix;
2155:   return(0);
2156: }

2160: /*@
2161:    KSPGetDiagonalScaleFix - Determines if KSP diagonally scales the system
2162:      back after solving.

2164:    Not Collective

2166:    Input Parameter:
2167: .  ksp - the KSP context

2169:    Output Parameter:
2170: .  fix - PETSC_TRUE to scale back after the system solve, PETSC_FALSE to not
2171:          rescale (default)

2173:    Notes:
2174:      Must be called after KSPSetDiagonalScale()

2176:      If PETSC_TRUE will slow things down, because it rescales the matrix before and
2177:      after each linear solve. This is intended mainly for testing to allow one
2178:      to easily get back the original system to make sure the solution computed is
2179:      accurate enough.

2181:    Level: intermediate

2183: .keywords: KSP, set, options, prefix, database

2185: .seealso: KSPGetDiagonalScale(), KSPSetDiagonalScale(), KSPSetDiagonalScaleFix()
2186: @*/
2187: PetscErrorCode  KSPGetDiagonalScaleFix(KSP ksp,PetscBool  *fix)
2188: {
2192:   *fix = ksp->dscalefix;
2193:   return(0);
2194: }

2198: /*@C
2199:    KSPSetComputeOperators - set routine to compute the linear operators

2201:    Logically Collective

2203:    Input Arguments:
2204: +  ksp - the KSP context
2205: .  func - function to compute the operators
2206: -  ctx - optional context

2208:    Calling sequence of func:
2209: $  func(KSP ksp,Mat A,Mat B,void *ctx)

2211: +  ksp - the KSP context
2212: .  A - the linear operator
2213: .  B - preconditioning matrix
2214: -  ctx - optional user-provided context

2216:    Notes: The user provided func() will be called automatically at the very next call to KSPSolve(). It will not be called at future KSPSolve() calls
2217:           unless either KSPSetComputeOperators() or KSPSetOperators() is called before that KSPSolve() is called.

2219:           To reuse the same preconditioner for the next KSPSolve() and not compute a new one based on the most recently computed matrix call KSPSetReusePreconditioner()

2221:    Level: beginner

2223: .seealso: KSPSetOperators(), KSPSetComputeRHS(), DMKSPSetComputeOperators(), KSPSetComputeInitialGuess()
2224: @*/
2225: PetscErrorCode KSPSetComputeOperators(KSP ksp,PetscErrorCode (*func)(KSP,Mat,Mat,void*),void *ctx)
2226: {
2228:   DM             dm;

2232:   KSPGetDM(ksp,&dm);
2233:   DMKSPSetComputeOperators(dm,func,ctx);
2234:   if (ksp->setupstage == KSP_SETUP_NEWRHS) ksp->setupstage = KSP_SETUP_NEWMATRIX;
2235:   return(0);
2236: }

2240: /*@C
2241:    KSPSetComputeRHS - set routine to compute the right hand side of the linear system

2243:    Logically Collective

2245:    Input Arguments:
2246: +  ksp - the KSP context
2247: .  func - function to compute the right hand side
2248: -  ctx - optional context

2250:    Calling sequence of func:
2251: $  func(KSP ksp,Vec b,void *ctx)

2253: +  ksp - the KSP context
2254: .  b - right hand side of linear system
2255: -  ctx - optional user-provided context

2257:    Notes: The routine you provide will be called EACH you call KSPSolve() to prepare the new right hand side for that solve

2259:    Level: beginner

2261: .seealso: KSPSolve(), DMKSPSetComputeRHS(), KSPSetComputeOperators()
2262: @*/
2263: PetscErrorCode KSPSetComputeRHS(KSP ksp,PetscErrorCode (*func)(KSP,Vec,void*),void *ctx)
2264: {
2266:   DM             dm;

2270:   KSPGetDM(ksp,&dm);
2271:   DMKSPSetComputeRHS(dm,func,ctx);
2272:   return(0);
2273: }

2277: /*@C
2278:    KSPSetComputeInitialGuess - set routine to compute the initial guess of the linear system

2280:    Logically Collective

2282:    Input Arguments:
2283: +  ksp - the KSP context
2284: .  func - function to compute the initial guess
2285: -  ctx - optional context

2287:    Calling sequence of func:
2288: $  func(KSP ksp,Vec x,void *ctx)

2290: +  ksp - the KSP context
2291: .  x - solution vector
2292: -  ctx - optional user-provided context

2294:    Level: beginner

2296: .seealso: KSPSolve(), KSPSetComputeRHS(), KSPSetComputeOperators(), DMKSPSetComputeInitialGuess()
2297: @*/
2298: PetscErrorCode KSPSetComputeInitialGuess(KSP ksp,PetscErrorCode (*func)(KSP,Vec,void*),void *ctx)
2299: {
2301:   DM             dm;

2305:   KSPGetDM(ksp,&dm);
2306:   DMKSPSetComputeInitialGuess(dm,func,ctx);
2307:   return(0);
2308: }