Actual source code: itfunc.c

petsc-master 2020-06-03
Report Typos and Errors

  2: /*
  3:       Interface KSP routines that the user calls.
  4: */

  6:  #include <petsc/private/kspimpl.h>
  7:  #include <petscdm.h>

  9: PETSC_STATIC_INLINE PetscErrorCode ObjectView(PetscObject obj, PetscViewer viewer, PetscViewerFormat format)
 10: {

 13:   PetscViewerPushFormat(viewer, format);
 14:   PetscObjectView(obj, viewer);
 15:   PetscViewerPopFormat(viewer);
 16:   return(0);
 17: }

 19: /*@
 20:    KSPComputeExtremeSingularValues - Computes the extreme singular values
 21:    for the preconditioned operator. Called after or during KSPSolve().

 23:    Not Collective

 25:    Input Parameter:
 26: .  ksp - iterative context obtained from KSPCreate()

 28:    Output Parameters:
 29: .  emin, emax - extreme singular values

 31:    Options Database Keys:
 32: .  -ksp_view_singularvalues - compute extreme singular values and print when KSPSolve completes.

 34:    Notes:
 35:    One must call KSPSetComputeSingularValues() before calling KSPSetUp()
 36:    (or use the option -ksp_view_eigenvalues) in order for this routine to work correctly.

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

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

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

 49:    Level: advanced

 51: .seealso: KSPSetComputeSingularValues(), KSPMonitorSingularValue(), KSPComputeEigenvalues(), KSP
 52: @*/
 53: PetscErrorCode  KSPComputeExtremeSingularValues(KSP ksp,PetscReal *emax,PetscReal *emin)
 54: {

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

 63:   if (ksp->ops->computeextremesingularvalues) {
 64:     (*ksp->ops->computeextremesingularvalues)(ksp,emax,emin);
 65:   } else {
 66:     *emin = -1.0;
 67:     *emax = -1.0;
 68:   }
 69:   return(0);
 70: }

 72: /*@
 73:    KSPComputeEigenvalues - Computes the extreme eigenvalues for the
 74:    preconditioned operator. Called after or during KSPSolve().

 76:    Not Collective

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

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

 88:    Options Database Keys:
 89: .  -ksp_view_eigenvalues - Prints eigenvalues to stdout

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

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

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

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

110:    Level: advanced

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

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

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

134: /*@
135:    KSPComputeRitz - Computes the Ritz or harmonic Ritz pairs associated to the
136:    smallest or largest in modulus, for the preconditioned operator.
137:    Called after KSPSolve().

139:    Not Collective

141:    Input Parameter:
142: +  ksp   - iterative context obtained from KSPCreate()
143: .  ritz  - PETSC_TRUE or PETSC_FALSE for ritz pairs or harmonic Ritz pairs, respectively
144: .  small - PETSC_TRUE or PETSC_FALSE for smallest or largest (harmonic) Ritz values, respectively
145: -  nrit  - number of (harmonic) Ritz pairs to compute

147:    Output Parameters:
148: +  nrit  - actual number of computed (harmonic) Ritz pairs
149: .  S     - multidimensional vector with Ritz vectors
150: .  tetar - real part of the Ritz values
151: -  tetai - imaginary part of the Ritz values

153:    Notes:
154:    -For GMRES, the (harmonic) Ritz pairs are computed from the Hessenberg matrix obtained during
155:    the last complete cycle, or obtained at the end of the solution if the method is stopped before
156:    a restart. Then, the number of actual (harmonic) Ritz pairs computed is less or equal to the restart
157:    parameter for GMRES if a complete cycle has been performed or less or equal to the number of GMRES
158:    iterations.
159:    -Moreover, for real matrices, the (harmonic) Ritz pairs are possibly complex-valued. In such a case,
160:    the routine selects the complex (harmonic) Ritz value and its conjugate, and two successive columns of S
161:    are equal to the real and the imaginary parts of the associated vectors.
162:    -the (harmonic) Ritz pairs are given in order of increasing (harmonic) Ritz values in modulus
163:    -this is currently not implemented when PETSc is built with complex numbers

165:    One must call KSPSetComputeRitz() before calling KSPSetUp()
166:    in order for this routine to work correctly.

168:    Level: advanced

170: .seealso: KSPSetComputeRitz(), KSP
171: @*/
172: PetscErrorCode  KSPComputeRitz(KSP ksp,PetscBool ritz,PetscBool small,PetscInt *nrit,Vec S[],PetscReal tetar[],PetscReal tetai[])
173: {

178:   if (!ksp->calc_ritz) SETERRQ(PetscObjectComm((PetscObject)ksp),4,"Ritz pairs not requested before KSPSetUp()");
179:   if (ksp->ops->computeritz) {(*ksp->ops->computeritz)(ksp,ritz,small,nrit,S,tetar,tetai);}
180:   return(0);
181: }
182: /*@
183:    KSPSetUpOnBlocks - Sets up the preconditioner for each block in
184:    the block Jacobi, block Gauss-Seidel, and overlapping Schwarz
185:    methods.

187:    Collective on ksp

189:    Input Parameter:
190: .  ksp - the KSP context

192:    Notes:
193:    KSPSetUpOnBlocks() is a routine that the user can optinally call for
194:    more precise profiling (via -log_view) of the setup phase for these
195:    block preconditioners.  If the user does not call KSPSetUpOnBlocks(),
196:    it will automatically be called from within KSPSolve().

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

201:    Level: advanced

203: .seealso: PCSetUpOnBlocks(), KSPSetUp(), PCSetUp(), KSP
204: @*/
205: PetscErrorCode  KSPSetUpOnBlocks(KSP ksp)
206: {
207:   PC             pc;
209:   PCFailedReason pcreason;

213:   KSPGetPC(ksp,&pc);
214:   PCSetUpOnBlocks(pc);
215:   PCGetFailedReason(pc,&pcreason);
216:   if (pcreason) {
217:     ksp->reason = KSP_DIVERGED_PC_FAILED;
218:   }
219:   return(0);
220: }

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

225:    Collective on ksp

227:    Input Parameters:
228: +  ksp   - iterative context obtained from KSPCreate()
229: -  flag - PETSC_TRUE to reuse the current preconditioner

231:    Level: intermediate

233: .seealso: KSPCreate(), KSPSolve(), KSPDestroy(), PCSetReusePreconditioner(), KSP
234: @*/
235: PetscErrorCode  KSPSetReusePreconditioner(KSP ksp,PetscBool flag)
236: {
237:   PC             pc;

242:   KSPGetPC(ksp,&pc);
243:   PCSetReusePreconditioner(pc,flag);
244:   return(0);
245: }

247: /*@
248:    KSPGetReusePreconditioner - Determines if the KSP reuses the current preconditioner even if the operator in the preconditioner has changed.

250:    Collective on ksp

252:    Input Parameters:
253: .  ksp   - iterative context obtained from KSPCreate()

255:    Output Parameters:
256: .  flag - the boolean flag

258:    Level: intermediate

260: .seealso: KSPCreate(), KSPSolve(), KSPDestroy(), KSPSetReusePreconditioner(), KSP
261: @*/
262: PetscErrorCode  KSPGetReusePreconditioner(KSP ksp,PetscBool *flag)
263: {

269:   *flag = PETSC_FALSE;
270:   if (ksp->pc) {
271:     PCGetReusePreconditioner(ksp->pc,flag);
272:   }
273:   return(0);
274: }

276: /*@
277:    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

279:    Collective on ksp

281:    Input Parameters:
282: +  ksp   - iterative context obtained from KSPCreate()
283: -  flag - PETSC_TRUE to skip calling the PCSetFromOptions()

285:    Level: intermediate

287: .seealso: KSPCreate(), KSPSolve(), KSPDestroy(), PCSetReusePreconditioner(), KSP
288: @*/
289: PetscErrorCode  KSPSetSkipPCSetFromOptions(KSP ksp,PetscBool flag)
290: {
293:   ksp->skippcsetfromoptions = flag;
294:   return(0);
295: }

297: /*@
298:    KSPSetUp - Sets up the internal data structures for the
299:    later use of an iterative solver.

301:    Collective on ksp

303:    Input Parameter:
304: .  ksp   - iterative context obtained from KSPCreate()

306:    Level: developer

308: .seealso: KSPCreate(), KSPSolve(), KSPDestroy(), KSP
309: @*/
310: PetscErrorCode KSPSetUp(KSP ksp)
311: {
313:   Mat            A,B;
314:   Mat            mat,pmat;
315:   MatNullSpace   nullsp;
316:   PCFailedReason pcreason;


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

324:   if (!((PetscObject)ksp)->type_name) {
325:     KSPSetType(ksp,KSPGMRES);
326:   }
327:   KSPSetUpNorms_Private(ksp,PETSC_TRUE,&ksp->normtype,&ksp->pc_side);

329:   if (ksp->dmActive && !ksp->setupstage) {
330:     /* first time in so build matrix and vector data structures using DM */
331:     if (!ksp->vec_rhs) {DMCreateGlobalVector(ksp->dm,&ksp->vec_rhs);}
332:     if (!ksp->vec_sol) {DMCreateGlobalVector(ksp->dm,&ksp->vec_sol);}
333:     DMCreateMatrix(ksp->dm,&A);
334:     KSPSetOperators(ksp,A,A);
335:     PetscObjectDereference((PetscObject)A);
336:   }

338:   if (ksp->dmActive) {
339:     DMKSP kdm;
340:     DMGetDMKSP(ksp->dm,&kdm);

342:     if (kdm->ops->computeinitialguess && ksp->setupstage != KSP_SETUP_NEWRHS) {
343:       /* only computes initial guess the first time through */
344:       (*kdm->ops->computeinitialguess)(ksp,ksp->vec_sol,kdm->initialguessctx);
345:       KSPSetInitialGuessNonzero(ksp,PETSC_TRUE);
346:     }
347:     if (kdm->ops->computerhs) {
348:       (*kdm->ops->computerhs)(ksp,ksp->vec_rhs,kdm->rhsctx);
349:     }

351:     if (ksp->setupstage != KSP_SETUP_NEWRHS) {
352:       if (kdm->ops->computeoperators) {
353:         KSPGetOperators(ksp,&A,&B);
354:         (*kdm->ops->computeoperators)(ksp,A,B,kdm->operatorsctx);
355:       } else SETERRQ(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_WRONGSTATE,"You called KSPSetDM() but did not use DMKSPSetComputeOperators() or KSPSetDMActive(ksp,PETSC_FALSE);");
356:     }
357:   }

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

362:   switch (ksp->setupstage) {
363:   case KSP_SETUP_NEW:
364:     (*ksp->ops->setup)(ksp);
365:     break;
366:   case KSP_SETUP_NEWMATRIX: {   /* This should be replaced with a more general mechanism */
367:     if (ksp->setupnewmatrix) {
368:       (*ksp->ops->setup)(ksp);
369:     }
370:   } break;
371:   default: break;
372:   }

374:   if (!ksp->pc) {KSPGetPC(ksp,&ksp->pc);}
375:   PCGetOperators(ksp->pc,&mat,&pmat);
376:   /* scale the matrix if requested */
377:   if (ksp->dscale) {
378:     PetscScalar *xx;
379:     PetscInt    i,n;
380:     PetscBool   zeroflag = PETSC_FALSE;
381:     if (!ksp->pc) {KSPGetPC(ksp,&ksp->pc);}
382:     if (!ksp->diagonal) { /* allocate vector to hold diagonal */
383:       MatCreateVecs(pmat,&ksp->diagonal,NULL);
384:     }
385:     MatGetDiagonal(pmat,ksp->diagonal);
386:     VecGetLocalSize(ksp->diagonal,&n);
387:     VecGetArray(ksp->diagonal,&xx);
388:     for (i=0; i<n; i++) {
389:       if (xx[i] != 0.0) xx[i] = 1.0/PetscSqrtReal(PetscAbsScalar(xx[i]));
390:       else {
391:         xx[i]    = 1.0;
392:         zeroflag = PETSC_TRUE;
393:       }
394:     }
395:     VecRestoreArray(ksp->diagonal,&xx);
396:     if (zeroflag) {
397:       PetscInfo(ksp,"Zero detected in diagonal of matrix, using 1 at those locations\n");
398:     }
399:     MatDiagonalScale(pmat,ksp->diagonal,ksp->diagonal);
400:     if (mat != pmat) {MatDiagonalScale(mat,ksp->diagonal,ksp->diagonal);}
401:     ksp->dscalefix2 = PETSC_FALSE;
402:   }
403:   PetscLogEventEnd(KSP_SetUp,ksp,ksp->vec_rhs,ksp->vec_sol,0);
404:   PCSetErrorIfFailure(ksp->pc,ksp->errorifnotconverged);
405:   PCSetUp(ksp->pc);
406:   PCGetFailedReason(ksp->pc,&pcreason);
407:   if (pcreason) {
408:     ksp->reason = KSP_DIVERGED_PC_FAILED;
409:   }

411:   MatGetNullSpace(mat,&nullsp);
412:   if (nullsp) {
413:     PetscBool test = PETSC_FALSE;
414:     PetscOptionsGetBool(((PetscObject)ksp)->options,((PetscObject)ksp)->prefix,"-ksp_test_null_space",&test,NULL);
415:     if (test) {
416:       MatNullSpaceTest(nullsp,mat,NULL);
417:     }
418:   }
419:   ksp->setupstage = KSP_SETUP_NEWRHS;
420:   return(0);
421: }

423: static PetscErrorCode KSPReasonView_Internal(KSP ksp, PetscViewer viewer, PetscViewerFormat format)
424: {
426:   PetscBool      isAscii;

429:   if (format != PETSC_VIEWER_DEFAULT) {PetscViewerPushFormat(viewer,format);}
430:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&isAscii);
431:   if (isAscii) {
432:     PetscViewerASCIIAddTab(viewer,((PetscObject)ksp)->tablevel);
433:     if (ksp->reason > 0) {
434:       if (((PetscObject) ksp)->prefix) {
435:         PetscViewerASCIIPrintf(viewer,"Linear %s solve converged due to %s iterations %D\n",((PetscObject) ksp)->prefix,KSPConvergedReasons[ksp->reason],ksp->its);
436:       } else {
437:         PetscViewerASCIIPrintf(viewer,"Linear solve converged due to %s iterations %D\n",KSPConvergedReasons[ksp->reason],ksp->its);
438:       }
439:     } else {
440:       if (((PetscObject) ksp)->prefix) {
441:         PetscViewerASCIIPrintf(viewer,"Linear %s solve did not converge due to %s iterations %D\n",((PetscObject) ksp)->prefix,KSPConvergedReasons[ksp->reason],ksp->its);
442:       } else {
443:         PetscViewerASCIIPrintf(viewer,"Linear solve did not converge due to %s iterations %D\n",KSPConvergedReasons[ksp->reason],ksp->its);
444:       }
445:       if (ksp->reason == KSP_DIVERGED_PC_FAILED) {
446:         PCFailedReason reason;
447:         PCGetFailedReason(ksp->pc,&reason);
448:         PetscViewerASCIIPrintf(viewer,"               PC_FAILED due to %s \n",PCFailedReasons[reason]);
449:       }
450:     }
451:     PetscViewerASCIISubtractTab(viewer,((PetscObject)ksp)->tablevel);
452:   }
453:   if (format != PETSC_VIEWER_DEFAULT) {PetscViewerPopFormat(viewer);}
454:   return(0);
455: }

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

460:    Collective on ksp

462:    Parameter:
463: +  ksp - iterative context obtained from KSPCreate()
464: -  viewer - the viewer to display the reason


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

470:    Level: beginner

472: .seealso: KSPCreate(), KSPSetUp(), KSPDestroy(), KSPSetTolerances(), KSPConvergedDefault(),
473:           KSPSolveTranspose(), KSPGetIterationNumber(), KSP
474: @*/
475: PetscErrorCode KSPReasonView(KSP ksp,PetscViewer viewer)
476: {

480:   KSPReasonView_Internal(ksp, viewer, PETSC_VIEWER_DEFAULT);
481:   return(0);
482: }

484: #if defined(PETSC_HAVE_THREADSAFETY)
485: #define KSPReasonViewFromOptions KSPReasonViewFromOptionsUnsafe
486: #else
487: #endif
488: /*@C
489:   KSPReasonViewFromOptions - Processes command line options to determine if/how a KSPReason is to be viewed.

491:   Collective on ksp

493:   Input Parameters:
494: . ksp   - the KSP object

496:   Level: intermediate

498: @*/
499: PetscErrorCode KSPReasonViewFromOptions(KSP ksp)
500: {
501:   PetscViewer       viewer;
502:   PetscBool         flg;
503:   PetscViewerFormat format;
504:   PetscErrorCode    ierr;

507:   PetscOptionsGetViewer(PetscObjectComm((PetscObject)ksp),((PetscObject)ksp)->options,((PetscObject)ksp)->prefix,"-ksp_converged_reason",&viewer,&format,&flg);
508:   if (flg) {
509:     KSPReasonView_Internal(ksp, viewer, format);
510:     PetscViewerDestroy(&viewer);
511:   }
512:   return(0);
513: }

515:  #include <petscdraw.h>

517: static PetscErrorCode KSPViewEigenvalues_Internal(KSP ksp, PetscBool isExplicit, PetscViewer viewer, PetscViewerFormat format)
518: {
519:   PetscReal     *r, *c;
520:   PetscInt       n, i, neig;
521:   PetscBool      isascii, isdraw;
522:   PetscMPIInt    rank;

526:   MPI_Comm_rank(PetscObjectComm((PetscObject) ksp), &rank);
527:   PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWERASCII, &isascii);
528:   PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWERDRAW,  &isdraw);
529:   if (isExplicit) {
530:     VecGetSize(ksp->vec_sol,&n);
531:     PetscMalloc2(n, &r, n, &c);
532:     KSPComputeEigenvaluesExplicitly(ksp, n, r, c);
533:     neig = n;
534:   } else {
535:     PetscInt nits;

537:     KSPGetIterationNumber(ksp, &nits);
538:     n    = nits+2;
539:     if (!nits) {PetscViewerASCIIPrintf(viewer, "Zero iterations in solver, cannot approximate any eigenvalues\n");return(0);}
540:     PetscMalloc2(n, &r, n, &c);
541:     KSPComputeEigenvalues(ksp, n, r, c, &neig);
542:   }
543:   if (isascii) {
544:     PetscViewerASCIIPrintf(viewer, "%s computed eigenvalues\n", isExplicit ? "Explicitly" : "Iteratively");
545:     for (i = 0; i < neig; ++i) {
546:       if (c[i] >= 0.0) {PetscViewerASCIIPrintf(viewer, "%g + %gi\n", (double) r[i],  (double) c[i]);}
547:       else             {PetscViewerASCIIPrintf(viewer, "%g - %gi\n", (double) r[i], -(double) c[i]);}
548:     }
549:   } else if (isdraw && !rank) {
550:     PetscDraw   draw;
551:     PetscDrawSP drawsp;

553:     if (format == PETSC_VIEWER_DRAW_CONTOUR) {
554:       KSPPlotEigenContours_Private(ksp,neig,r,c);
555:     } else {
556:       if (!ksp->eigviewer) {PetscViewerDrawOpen(PETSC_COMM_SELF,NULL,isExplicit ? "Explicitly Computed Eigenvalues" : "Iteratively Computed Eigenvalues",PETSC_DECIDE,PETSC_DECIDE,400,400,&ksp->eigviewer);}
557:       PetscViewerDrawGetDraw(ksp->eigviewer,0,&draw);
558:       PetscDrawSPCreate(draw,1,&drawsp);
559:       PetscDrawSPReset(drawsp);
560:       for (i = 0; i < neig; ++i) {PetscDrawSPAddPoint(drawsp,r+i,c+i);}
561:       PetscDrawSPDraw(drawsp,PETSC_TRUE);
562:       PetscDrawSPSave(drawsp);
563:       PetscDrawSPDestroy(&drawsp);
564:     }
565:   }
566:   PetscFree2(r, c);
567:   return(0);
568: }

570: static PetscErrorCode KSPViewSingularvalues_Internal(KSP ksp, PetscViewer viewer, PetscViewerFormat format)
571: {
572:   PetscReal      smax, smin;
573:   PetscInt       nits;
574:   PetscBool      isascii;

578:   PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWERASCII, &isascii);
579:   KSPGetIterationNumber(ksp, &nits);
580:   if (!nits) {PetscViewerASCIIPrintf(viewer, "Zero iterations in solver, cannot approximate any singular values\n");return(0);}
581:   KSPComputeExtremeSingularValues(ksp, &smax, &smin);
582:   if (isascii) {PetscViewerASCIIPrintf(viewer, "Iteratively computed extreme singular values: max %g min %g max/min %g\n",(double)smax,(double)smin,(double)(smax/smin));}
583:   return(0);
584: }

586: static PetscErrorCode KSPViewFinalResidual_Internal(KSP ksp, PetscViewer viewer, PetscViewerFormat format)
587: {
588:   PetscBool      isascii;

592:   PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWERASCII, &isascii);
593:   if (ksp->dscale && !ksp->dscalefix) SETERRQ(PetscObjectComm((PetscObject) ksp), PETSC_ERR_ARG_WRONGSTATE, "Cannot compute final scale with -ksp_diagonal_scale except also with -ksp_diagonal_scale_fix");
594:   if (isascii) {
595:     Mat       A;
596:     Vec       t;
597:     PetscReal norm;

599:     PCGetOperators(ksp->pc, &A, NULL);
600:     VecDuplicate(ksp->vec_rhs, &t);
601:     KSP_MatMult(ksp, A, ksp->vec_sol, t);
602:     VecAYPX(t, -1.0, ksp->vec_rhs);
603:     VecNorm(t, NORM_2, &norm);
604:     VecDestroy(&t);
605:     PetscViewerASCIIPrintf(viewer, "KSP final norm of residual %g\n", (double) norm);
606:   }
607:   return(0);
608: }

610: static PetscErrorCode KSPSolve_Private(KSP ksp,Vec b,Vec x)
611: {
613:   PetscBool      flg = PETSC_FALSE,inXisinB=PETSC_FALSE,guess_zero;
614:   Mat            mat,pmat;
615:   MPI_Comm       comm;
616:   MatNullSpace   nullsp;
617:   Vec            btmp,vec_rhs=NULL;

620:   comm = PetscObjectComm((PetscObject)ksp);
621:   if (x && x == b) {
622:     if (!ksp->guess_zero) SETERRQ(comm,PETSC_ERR_ARG_INCOMP,"Cannot use x == b with nonzero initial guess");
623:     VecDuplicate(b,&x);
624:     inXisinB = PETSC_TRUE;
625:   }
626:   if (b) {
627:     PetscObjectReference((PetscObject)b);
628:     VecDestroy(&ksp->vec_rhs);
629:     ksp->vec_rhs = b;
630:   }
631:   if (x) {
632:     PetscObjectReference((PetscObject)x);
633:     VecDestroy(&ksp->vec_sol);
634:     ksp->vec_sol = x;
635:   }

637:   if (ksp->viewPre) {ObjectView((PetscObject) ksp, ksp->viewerPre, ksp->formatPre);}

639:   if (ksp->presolve) {(*ksp->presolve)(ksp,ksp->vec_rhs,ksp->vec_sol,ksp->prectx);}

641:   /* reset the residual history list if requested */
642:   if (ksp->res_hist_reset) ksp->res_hist_len = 0;

644:   PetscLogEventBegin(KSP_Solve,ksp,ksp->vec_rhs,ksp->vec_sol,0);

646:   if (ksp->guess) {
647:     PetscObjectState ostate,state;

649:     KSPGuessSetUp(ksp->guess);
650:     PetscObjectStateGet((PetscObject)ksp->vec_sol,&ostate);
651:     KSPGuessFormGuess(ksp->guess,ksp->vec_rhs,ksp->vec_sol);
652:     PetscObjectStateGet((PetscObject)ksp->vec_sol,&state);
653:     if (state != ostate) {
654:       ksp->guess_zero = PETSC_FALSE;
655:     } else {
656:       PetscInfo(ksp,"Using zero initial guess since the KSPGuess object did not change the vector\n");
657:       ksp->guess_zero = PETSC_TRUE;
658:     }
659:   }

661:   /* KSPSetUp() scales the matrix if needed */
662:   KSPSetUp(ksp);
663:   KSPSetUpOnBlocks(ksp);

665:   VecSetErrorIfLocked(ksp->vec_sol,3);

667:   PCGetOperators(ksp->pc,&mat,&pmat);
668:   /* diagonal scale RHS if called for */
669:   if (ksp->dscale) {
670:     VecPointwiseMult(ksp->vec_rhs,ksp->vec_rhs,ksp->diagonal);
671:     /* second time in, but matrix was scaled back to original */
672:     if (ksp->dscalefix && ksp->dscalefix2) {
673:       Mat mat,pmat;

675:       PCGetOperators(ksp->pc,&mat,&pmat);
676:       MatDiagonalScale(pmat,ksp->diagonal,ksp->diagonal);
677:       if (mat != pmat) {MatDiagonalScale(mat,ksp->diagonal,ksp->diagonal);}
678:     }

680:     /* scale initial guess */
681:     if (!ksp->guess_zero) {
682:       if (!ksp->truediagonal) {
683:         VecDuplicate(ksp->diagonal,&ksp->truediagonal);
684:         VecCopy(ksp->diagonal,ksp->truediagonal);
685:         VecReciprocal(ksp->truediagonal);
686:       }
687:       VecPointwiseMult(ksp->vec_sol,ksp->vec_sol,ksp->truediagonal);
688:     }
689:   }
690:   PCPreSolve(ksp->pc,ksp);

692:   if (ksp->guess_zero) { VecSet(ksp->vec_sol,0.0);}
693:   if (ksp->guess_knoll) { /* The Knoll trick is independent on the KSPGuess specified */
694:     PCApply(ksp->pc,ksp->vec_rhs,ksp->vec_sol);
695:     KSP_RemoveNullSpace(ksp,ksp->vec_sol);
696:     ksp->guess_zero = PETSC_FALSE;
697:   }

699:   /* can we mark the initial guess as zero for this solve? */
700:   guess_zero = ksp->guess_zero;
701:   if (!ksp->guess_zero) {
702:     PetscReal norm;

704:     VecNormAvailable(ksp->vec_sol,NORM_2,&flg,&norm);
705:     if (flg && !norm) ksp->guess_zero = PETSC_TRUE;
706:   }
707:   if (ksp->transpose_solve) {
708:     MatGetNullSpace(pmat,&nullsp);
709:   } else {
710:     MatGetTransposeNullSpace(pmat,&nullsp);
711:   }
712:   if (nullsp) {
713:     VecDuplicate(ksp->vec_rhs,&btmp);
714:     VecCopy(ksp->vec_rhs,btmp);
715:     MatNullSpaceRemove(nullsp,btmp);
716:     vec_rhs      = ksp->vec_rhs;
717:     ksp->vec_rhs = btmp;
718:   }
719:   VecLockReadPush(ksp->vec_rhs);
720:   if (ksp->reason == KSP_DIVERGED_PC_FAILED) {
721:     VecSetInf(ksp->vec_sol);
722:   }
723:   (*ksp->ops->solve)(ksp);

725:   VecLockReadPop(ksp->vec_rhs);
726:   if (nullsp) {
727:     ksp->vec_rhs = vec_rhs;
728:     VecDestroy(&btmp);
729:   }

731:   ksp->guess_zero = guess_zero;

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

736:   if (ksp->viewReason) {KSPReasonView_Internal(ksp, ksp->viewerReason, ksp->formatReason);}
737:   PCPostSolve(ksp->pc,ksp);

739:   /* diagonal scale solution if called for */
740:   if (ksp->dscale) {
741:     VecPointwiseMult(ksp->vec_sol,ksp->vec_sol,ksp->diagonal);
742:     /* unscale right hand side and matrix */
743:     if (ksp->dscalefix) {
744:       Mat mat,pmat;

746:       VecReciprocal(ksp->diagonal);
747:       VecPointwiseMult(ksp->vec_rhs,ksp->vec_rhs,ksp->diagonal);
748:       PCGetOperators(ksp->pc,&mat,&pmat);
749:       MatDiagonalScale(pmat,ksp->diagonal,ksp->diagonal);
750:       if (mat != pmat) {MatDiagonalScale(mat,ksp->diagonal,ksp->diagonal);}
751:       VecReciprocal(ksp->diagonal);
752:       ksp->dscalefix2 = PETSC_TRUE;
753:     }
754:   }
755:   PetscLogEventEnd(KSP_Solve,ksp,ksp->vec_rhs,ksp->vec_sol,0);
756:   if (ksp->guess) {
757:     KSPGuessUpdate(ksp->guess,ksp->vec_rhs,ksp->vec_sol);
758:   }
759:   if (ksp->postsolve) {
760:     (*ksp->postsolve)(ksp,ksp->vec_rhs,ksp->vec_sol,ksp->postctx);
761:   }

763:   PCGetOperators(ksp->pc,&mat,&pmat);
764:   if (ksp->viewEV)       {KSPViewEigenvalues_Internal(ksp, PETSC_FALSE, ksp->viewerEV,    ksp->formatEV);}
765:   if (ksp->viewEVExp)    {KSPViewEigenvalues_Internal(ksp, PETSC_TRUE,  ksp->viewerEVExp, ksp->formatEVExp);}
766:   if (ksp->viewSV)       {KSPViewSingularvalues_Internal(ksp, ksp->viewerSV, ksp->formatSV);}
767:   if (ksp->viewFinalRes) {KSPViewFinalResidual_Internal(ksp, ksp->viewerFinalRes, ksp->formatFinalRes);}
768:   if (ksp->viewMat)      {ObjectView((PetscObject) mat,           ksp->viewerMat,    ksp->formatMat);}
769:   if (ksp->viewPMat)     {ObjectView((PetscObject) pmat,          ksp->viewerPMat,   ksp->formatPMat);}
770:   if (ksp->viewRhs)      {ObjectView((PetscObject) ksp->vec_rhs,  ksp->viewerRhs,    ksp->formatRhs);}
771:   if (ksp->viewSol)      {ObjectView((PetscObject) ksp->vec_sol,  ksp->viewerSol,    ksp->formatSol);}
772:   if (ksp->view)         {ObjectView((PetscObject) ksp,           ksp->viewer,       ksp->format);}
773:   if (ksp->viewDScale)   {ObjectView((PetscObject) ksp->diagonal, ksp->viewerDScale, ksp->formatDScale);}
774:   if (ksp->viewMatExp)   {
775:     Mat A, B;

777:     PCGetOperators(ksp->pc, &A, NULL);
778:     if (ksp->transpose_solve) {
779:       Mat AT;

781:       MatCreateTranspose(A, &AT);
782:       MatComputeOperator(AT, MATAIJ, &B);
783:       MatDestroy(&AT);
784:     } else {
785:       MatComputeOperator(A, MATAIJ, &B);
786:     }
787:     ObjectView((PetscObject) B, ksp->viewerMatExp, ksp->formatMatExp);
788:     MatDestroy(&B);
789:   }
790:   if (ksp->viewPOpExp)   {
791:     Mat B;

793:     KSPComputeOperator(ksp, MATAIJ, &B);
794:     ObjectView((PetscObject) B, ksp->viewerPOpExp, ksp->formatPOpExp);
795:     MatDestroy(&B);
796:   }

798:   if (inXisinB) {
799:     VecCopy(x,b);
800:     VecDestroy(&x);
801:   }
802:   PetscObjectSAWsBlock((PetscObject)ksp);
803:   if (ksp->errorifnotconverged && ksp->reason < 0 && ksp->reason != KSP_DIVERGED_ITS) SETERRQ1(comm,PETSC_ERR_NOT_CONVERGED,"KSPSolve has not converged, reason %s",KSPConvergedReasons[ksp->reason]);
804:   return(0);
805: }

807: /*@
808:    KSPSolve - Solves linear system.

810:    Collective on ksp

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

817:    Options Database Keys:
818: +  -ksp_view_eigenvalues - compute preconditioned operators eigenvalues
819: .  -ksp_view_eigenvalues_explicitly - compute the eigenvalues by forming the dense operator and using LAPACK
820: .  -ksp_view_mat binary - save matrix to the default binary viewer
821: .  -ksp_view_pmat binary - save matrix used to build preconditioner to the default binary viewer
822: .  -ksp_view_rhs binary - save right hand side vector to the default binary viewer
823: .  -ksp_view_solution binary - save computed solution vector to the default binary viewer
824:            (can be read later with src/ksp/tutorials/ex10.c for testing solvers)
825: .  -ksp_view_mat_explicit - for matrix-free operators, computes the matrix entries and views them
826: .  -ksp_view_preconditioned_operator_explicit - computes the product of the preconditioner and matrix as an explicit matrix and views it
827: .  -ksp_converged_reason - print reason for converged or diverged, also prints number of iterations
828: .  -ksp_view_final_residual - print 2-norm of true linear system residual at the end of the solution process
829: -  -ksp_view - print the ksp data structure at the end of the system solution

831:    Notes:

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

835:    The operator is specified with KSPSetOperators().

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

840:    If you provide a matrix that has a MatSetNullSpace() and MatSetTransposeNullSpace() this will use that information to solve singular systems
841:    in the least squares sense with a norm minimizing solution.
842: $
843: $                   A x = b   where b = b_p + b_t where b_t is not in the range of A (and hence by the fundamental theorem of linear algebra is in the nullspace(A') see MatSetNullSpace()
844: $
845: $    KSP first removes b_t producing the linear system  A x = b_p (which has multiple solutions) and solves this to find the ||x|| minimizing solution (and hence
846: $    it finds the solution x orthogonal to the nullspace(A). The algorithm is simply in each iteration of the Krylov method we remove the nullspace(A) from the search
847: $    direction thus the solution which is a linear combination of the search directions has no component in the nullspace(A).
848: $
849: $    We recommend always using GMRES for such singular systems.
850: $    If nullspace(A) = nullspace(A') (note symmetric matrices always satisfy this property) then both left and right preconditioning will work
851: $    If nullspace(A) != nullspace(A') then left preconditioning will work but right preconditioning may not work (or it may).

853:    Developer Note: The reason we cannot always solve  nullspace(A) != nullspace(A') systems with right preconditioning is because we need to remove at each iteration
854:        the nullspace(AB) from the search direction. While we know the nullspace(A) the nullspace(AB) equals B^-1 times the nullspace(A) but except for trivial preconditioners
855:        such as diagonal scaling we cannot apply the inverse of the preconditioner to a vector and thus cannot compute the nullspace(AB).


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

863:    Understanding Convergence:
864:    The routines KSPMonitorSet(), KSPComputeEigenvalues(), and
865:    KSPComputeEigenvaluesExplicitly() provide information on additional
866:    options to monitor convergence and print eigenvalue information.

868:    Level: beginner

870: .seealso: KSPCreate(), KSPSetUp(), KSPDestroy(), KSPSetTolerances(), KSPConvergedDefault(),
871:           KSPSolveTranspose(), KSPGetIterationNumber(), MatNullSpaceCreate(), MatSetNullSpace(), MatSetTransposeNullSpace(), KSP
872: @*/
873: PetscErrorCode KSPSolve(KSP ksp,Vec b,Vec x)
874: {

881:   ksp->transpose_solve = PETSC_FALSE;
882:   KSPSolve_Private(ksp,b,x);
883:   return(0);
884: }

886: /*@
887:    KSPSolveTranspose - Solves the transpose of a linear system.

889:    Collective on ksp

891:    Input Parameter:
892: +  ksp - iterative context obtained from KSPCreate()
893: .  b - right hand side vector
894: -  x - solution vector

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

899:    Developer Notes:
900:     We need to implement a KSPSolveHermitianTranspose()

902:    Level: developer

904: .seealso: KSPCreate(), KSPSetUp(), KSPDestroy(), KSPSetTolerances(), KSPConvergedDefault(),
905:           KSPSolve(), KSP
906: @*/
907: PetscErrorCode KSPSolveTranspose(KSP ksp,Vec b,Vec x)
908: {

915:   ksp->transpose_solve = PETSC_TRUE;
916:   KSPSolve_Private(ksp,b,x);
917:   return(0);
918: }

920: /*@
921:    KSPResetViewers - Resets all the viewers set from the options database during KSPSetFromOptions()

923:    Collective on ksp

925:    Input Parameter:
926: .  ksp - iterative context obtained from KSPCreate()

928:    Level: beginner

930: .seealso: KSPCreate(), KSPSetUp(), KSPSolve(), KSPSetFromOptions(), KSP
931: @*/
932: PetscErrorCode  KSPResetViewers(KSP ksp)
933: {

938:   if (!ksp) return(0);
939:   PetscViewerDestroy(&ksp->viewer);
940:   PetscViewerDestroy(&ksp->viewerPre);
941:   PetscViewerDestroy(&ksp->viewerReason);
942:   PetscViewerDestroy(&ksp->viewerMat);
943:   PetscViewerDestroy(&ksp->viewerPMat);
944:   PetscViewerDestroy(&ksp->viewerRhs);
945:   PetscViewerDestroy(&ksp->viewerSol);
946:   PetscViewerDestroy(&ksp->viewerMatExp);
947:   PetscViewerDestroy(&ksp->viewerEV);
948:   PetscViewerDestroy(&ksp->viewerSV);
949:   PetscViewerDestroy(&ksp->viewerEVExp);
950:   PetscViewerDestroy(&ksp->viewerFinalRes);
951:   PetscViewerDestroy(&ksp->viewerPOpExp);
952:   PetscViewerDestroy(&ksp->viewerDScale);
953:   ksp->view         = PETSC_FALSE;
954:   ksp->viewPre      = PETSC_FALSE;
955:   ksp->viewReason   = PETSC_FALSE;
956:   ksp->viewMat      = PETSC_FALSE;
957:   ksp->viewPMat     = PETSC_FALSE;
958:   ksp->viewRhs      = PETSC_FALSE;
959:   ksp->viewSol      = PETSC_FALSE;
960:   ksp->viewMatExp   = PETSC_FALSE;
961:   ksp->viewEV       = PETSC_FALSE;
962:   ksp->viewSV       = PETSC_FALSE;
963:   ksp->viewEVExp    = PETSC_FALSE;
964:   ksp->viewFinalRes = PETSC_FALSE;
965:   ksp->viewPOpExp   = PETSC_FALSE;
966:   ksp->viewDScale   = PETSC_FALSE;
967:   return(0);
968: }

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

973:    Collective on ksp

975:    Input Parameter:
976: .  ksp - iterative context obtained from KSPCreate()

978:    Level: beginner

980: .seealso: KSPCreate(), KSPSetUp(), KSPSolve(), KSP
981: @*/
982: PetscErrorCode  KSPReset(KSP ksp)
983: {

988:   if (!ksp) return(0);
989:   if (ksp->ops->reset) {
990:     (*ksp->ops->reset)(ksp);
991:   }
992:   if (ksp->pc) {PCReset(ksp->pc);}
993:   if (ksp->guess) {
994:     KSPGuess guess = ksp->guess;
995:     if (guess->ops->reset) { (*guess->ops->reset)(guess); }
996:   }
997:   VecDestroyVecs(ksp->nwork,&ksp->work);
998:   VecDestroy(&ksp->vec_rhs);
999:   VecDestroy(&ksp->vec_sol);
1000:   VecDestroy(&ksp->diagonal);
1001:   VecDestroy(&ksp->truediagonal);

1003:   KSPResetViewers(ksp);

1005:   ksp->setupstage = KSP_SETUP_NEW;
1006:   return(0);
1007: }

1009: /*@
1010:    KSPDestroy - Destroys KSP context.

1012:    Collective on ksp

1014:    Input Parameter:
1015: .  ksp - iterative context obtained from KSPCreate()

1017:    Level: beginner

1019: .seealso: KSPCreate(), KSPSetUp(), KSPSolve(), KSP
1020: @*/
1021: PetscErrorCode  KSPDestroy(KSP *ksp)
1022: {
1024:   PC             pc;

1027:   if (!*ksp) return(0);
1029:   if (--((PetscObject)(*ksp))->refct > 0) {*ksp = NULL; return(0);}

1031:   PetscObjectSAWsViewOff((PetscObject)*ksp);

1033:   /*
1034:    Avoid a cascading call to PCReset(ksp->pc) from the following call:
1035:    PCReset() shouldn't be called from KSPDestroy() as it is unprotected by pc's
1036:    refcount (and may be shared, e.g., by other ksps).
1037:    */
1038:   pc         = (*ksp)->pc;
1039:   (*ksp)->pc = NULL;
1040:   KSPReset((*ksp));
1041:   (*ksp)->pc = pc;
1042:   if ((*ksp)->ops->destroy) {(*(*ksp)->ops->destroy)(*ksp);}

1044:   KSPGuessDestroy(&(*ksp)->guess);
1045:   DMDestroy(&(*ksp)->dm);
1046:   PCDestroy(&(*ksp)->pc);
1047:   PetscFree((*ksp)->res_hist_alloc);
1048:   if ((*ksp)->convergeddestroy) {
1049:     (*(*ksp)->convergeddestroy)((*ksp)->cnvP);
1050:   }
1051:   KSPMonitorCancel((*ksp));
1052:   PetscViewerDestroy(&(*ksp)->eigviewer);
1053:   PetscHeaderDestroy(ksp);
1054:   return(0);
1055: }

1057: /*@
1058:     KSPSetPCSide - Sets the preconditioning side.

1060:     Logically Collective on ksp

1062:     Input Parameter:
1063: .   ksp - iterative context obtained from KSPCreate()

1065:     Output Parameter:
1066: .   side - the preconditioning side, where side is one of
1067: .vb
1068:       PC_LEFT - left preconditioning (default)
1069:       PC_RIGHT - right preconditioning
1070:       PC_SYMMETRIC - symmetric preconditioning
1071: .ve

1073:     Options Database Keys:
1074: .   -ksp_pc_side <right,left,symmetric>

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

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

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

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

1087:     Level: intermediate

1089: .seealso: KSPGetPCSide(), KSPSetNormType(), KSPGetNormType(), KSP
1090: @*/
1091: PetscErrorCode  KSPSetPCSide(KSP ksp,PCSide side)
1092: {
1096:   ksp->pc_side = ksp->pc_side_set = side;
1097:   return(0);
1098: }

1100: /*@
1101:     KSPGetPCSide - Gets the preconditioning side.

1103:     Not Collective

1105:     Input Parameter:
1106: .   ksp - iterative context obtained from KSPCreate()

1108:     Output Parameter:
1109: .   side - the preconditioning side, where side is one of
1110: .vb
1111:       PC_LEFT - left preconditioning (default)
1112:       PC_RIGHT - right preconditioning
1113:       PC_SYMMETRIC - symmetric preconditioning
1114: .ve

1116:     Level: intermediate

1118: .seealso: KSPSetPCSide(), KSP
1119: @*/
1120: PetscErrorCode  KSPGetPCSide(KSP ksp,PCSide *side)
1121: {

1127:   KSPSetUpNorms_Private(ksp,PETSC_TRUE,&ksp->normtype,&ksp->pc_side);
1128:   *side = ksp->pc_side;
1129:   return(0);
1130: }

1132: /*@
1133:    KSPGetTolerances - Gets the relative, absolute, divergence, and maximum
1134:    iteration tolerances used by the default KSP convergence tests.

1136:    Not Collective

1138:    Input Parameter:
1139: .  ksp - the Krylov subspace context

1141:    Output Parameters:
1142: +  rtol - the relative convergence tolerance
1143: .  abstol - the absolute convergence tolerance
1144: .  dtol - the divergence tolerance
1145: -  maxits - maximum number of iterations

1147:    Notes:
1148:    The user can specify NULL for any parameter that is not needed.

1150:    Level: intermediate

1152:            maximum, iterations

1154: .seealso: KSPSetTolerances(), KSP
1155: @*/
1156: PetscErrorCode  KSPGetTolerances(KSP ksp,PetscReal *rtol,PetscReal *abstol,PetscReal *dtol,PetscInt *maxits)
1157: {
1160:   if (abstol) *abstol = ksp->abstol;
1161:   if (rtol) *rtol = ksp->rtol;
1162:   if (dtol) *dtol = ksp->divtol;
1163:   if (maxits) *maxits = ksp->max_it;
1164:   return(0);
1165: }

1167: /*@
1168:    KSPSetTolerances - Sets the relative, absolute, divergence, and maximum
1169:    iteration tolerances used by the default KSP convergence testers.

1171:    Logically Collective on ksp

1173:    Input Parameters:
1174: +  ksp - the Krylov subspace context
1175: .  rtol - the relative convergence tolerance, relative decrease in the (possibly preconditioned) residual norm
1176: .  abstol - the absolute convergence tolerance   absolute size of the (possibly preconditioned) residual norm
1177: .  dtol - the divergence tolerance,   amount (possibly preconditioned) residual norm can increase before KSPConvergedDefault() concludes that the method is diverging
1178: -  maxits - maximum number of iterations to use

1180:    Options Database Keys:
1181: +  -ksp_atol <abstol> - Sets abstol
1182: .  -ksp_rtol <rtol> - Sets rtol
1183: .  -ksp_divtol <dtol> - Sets dtol
1184: -  -ksp_max_it <maxits> - Sets maxits

1186:    Notes:
1187:    Use PETSC_DEFAULT to retain the default value of any of the tolerances.

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

1192:    Level: intermediate

1194:            convergence, maximum, iterations

1196: .seealso: KSPGetTolerances(), KSPConvergedDefault(), KSPSetConvergenceTest(), KSP
1197: @*/
1198: PetscErrorCode  KSPSetTolerances(KSP ksp,PetscReal rtol,PetscReal abstol,PetscReal dtol,PetscInt maxits)
1199: {

1207:   if (rtol != PETSC_DEFAULT) {
1208:     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);
1209:     ksp->rtol = rtol;
1210:   }
1211:   if (abstol != PETSC_DEFAULT) {
1212:     if (abstol < 0.0) SETERRQ1(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_OUTOFRANGE,"Absolute tolerance %g must be non-negative",(double)abstol);
1213:     ksp->abstol = abstol;
1214:   }
1215:   if (dtol != PETSC_DEFAULT) {
1216:     if (dtol < 0.0) SETERRQ1(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_OUTOFRANGE,"Divergence tolerance %g must be larger than 1.0",(double)dtol);
1217:     ksp->divtol = dtol;
1218:   }
1219:   if (maxits != PETSC_DEFAULT) {
1220:     if (maxits < 0) SETERRQ1(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of iterations %D must be non-negative",maxits);
1221:     ksp->max_it = maxits;
1222:   }
1223:   return(0);
1224: }

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

1231:    Logically Collective on ksp

1233:    Input Parameters:
1234: +  ksp - iterative context obtained from KSPCreate()
1235: -  flg - PETSC_TRUE indicates the guess is non-zero, PETSC_FALSE indicates the guess is zero

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

1240:    Level: beginner

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

1245: .seealso: KSPGetInitialGuessNonzero(), KSPSetGuessType(), KSPGuessType, KSP
1246: @*/
1247: PetscErrorCode  KSPSetInitialGuessNonzero(KSP ksp,PetscBool flg)
1248: {
1252:   ksp->guess_zero = (PetscBool) !(int)flg;
1253:   return(0);
1254: }

1256: /*@
1257:    KSPGetInitialGuessNonzero - Determines whether the KSP solver is using
1258:    a zero initial guess.

1260:    Not Collective

1262:    Input Parameter:
1263: .  ksp - iterative context obtained from KSPCreate()

1265:    Output Parameter:
1266: .  flag - PETSC_TRUE if guess is nonzero, else PETSC_FALSE

1268:    Level: intermediate

1270: .seealso: KSPSetInitialGuessNonzero(), KSP
1271: @*/
1272: PetscErrorCode  KSPGetInitialGuessNonzero(KSP ksp,PetscBool  *flag)
1273: {
1277:   if (ksp->guess_zero) *flag = PETSC_FALSE;
1278:   else *flag = PETSC_TRUE;
1279:   return(0);
1280: }

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

1285:    Logically Collective on ksp

1287:    Input Parameters:
1288: +  ksp - iterative context obtained from KSPCreate()
1289: -  flg - PETSC_TRUE indicates you want the error generated

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

1294:    Level: intermediate

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


1301: .seealso: KSPGetErrorIfNotConverged(), KSP
1302: @*/
1303: PetscErrorCode  KSPSetErrorIfNotConverged(KSP ksp,PetscBool flg)
1304: {
1308:   ksp->errorifnotconverged = flg;
1309:   return(0);
1310: }

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

1315:    Not Collective

1317:    Input Parameter:
1318: .  ksp - iterative context obtained from KSPCreate()

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

1323:    Level: intermediate

1325: .seealso: KSPSetErrorIfNotConverged(), KSP
1326: @*/
1327: PetscErrorCode  KSPGetErrorIfNotConverged(KSP ksp,PetscBool  *flag)
1328: {
1332:   *flag = ksp->errorifnotconverged;
1333:   return(0);
1334: }

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

1339:    Logically Collective on ksp

1341:    Input Parameters:
1342: +  ksp - iterative context obtained from KSPCreate()
1343: -  flg - PETSC_TRUE or PETSC_FALSE

1345:    Level: advanced

1347:    Developer Note: the Knoll trick is not currently implemented using the KSPGuess class

1349: .seealso: KSPGetInitialGuessKnoll(), KSPSetInitialGuessNonzero(), KSPGetInitialGuessNonzero(), KSP
1350: @*/
1351: PetscErrorCode  KSPSetInitialGuessKnoll(KSP ksp,PetscBool flg)
1352: {
1356:   ksp->guess_knoll = flg;
1357:   return(0);
1358: }

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

1364:    Not Collective

1366:    Input Parameter:
1367: .  ksp - iterative context obtained from KSPCreate()

1369:    Output Parameter:
1370: .  flag - PETSC_TRUE if using Knoll trick, else PETSC_FALSE

1372:    Level: advanced

1374: .seealso: KSPSetInitialGuessKnoll(), KSPSetInitialGuessNonzero(), KSPGetInitialGuessNonzero(), KSP
1375: @*/
1376: PetscErrorCode  KSPGetInitialGuessKnoll(KSP ksp,PetscBool  *flag)
1377: {
1381:   *flag = ksp->guess_knoll;
1382:   return(0);
1383: }

1385: /*@
1386:    KSPGetComputeSingularValues - Gets the flag indicating whether the extreme singular
1387:    values will be calculated via a Lanczos or Arnoldi process as the linear
1388:    system is solved.

1390:    Not Collective

1392:    Input Parameter:
1393: .  ksp - iterative context obtained from KSPCreate()

1395:    Output Parameter:
1396: .  flg - PETSC_TRUE or PETSC_FALSE

1398:    Options Database Key:
1399: .  -ksp_monitor_singular_value - Activates KSPSetComputeSingularValues()

1401:    Notes:
1402:    Currently this option is not valid for all iterative methods.

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

1408:    Level: advanced

1410: .seealso: KSPComputeExtremeSingularValues(), KSPMonitorSingularValue(), KSP
1411: @*/
1412: PetscErrorCode  KSPGetComputeSingularValues(KSP ksp,PetscBool  *flg)
1413: {
1417:   *flg = ksp->calc_sings;
1418:   return(0);
1419: }

1421: /*@
1422:    KSPSetComputeSingularValues - Sets a flag so that the extreme singular
1423:    values will be calculated via a Lanczos or Arnoldi process as the linear
1424:    system is solved.

1426:    Logically Collective on ksp

1428:    Input Parameters:
1429: +  ksp - iterative context obtained from KSPCreate()
1430: -  flg - PETSC_TRUE or PETSC_FALSE

1432:    Options Database Key:
1433: .  -ksp_monitor_singular_value - Activates KSPSetComputeSingularValues()

1435:    Notes:
1436:    Currently this option is not valid for all iterative methods.

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

1442:    Level: advanced

1444: .seealso: KSPComputeExtremeSingularValues(), KSPMonitorSingularValue(), KSP
1445: @*/
1446: PetscErrorCode  KSPSetComputeSingularValues(KSP ksp,PetscBool flg)
1447: {
1451:   ksp->calc_sings = flg;
1452:   return(0);
1453: }

1455: /*@
1456:    KSPGetComputeEigenvalues - Gets the flag indicating that the extreme eigenvalues
1457:    values will be calculated via a Lanczos or Arnoldi process as the linear
1458:    system is solved.

1460:    Not Collective

1462:    Input Parameter:
1463: .  ksp - iterative context obtained from KSPCreate()

1465:    Output Parameter:
1466: .  flg - PETSC_TRUE or PETSC_FALSE

1468:    Notes:
1469:    Currently this option is not valid for all iterative methods.

1471:    Level: advanced

1473: .seealso: KSPComputeEigenvalues(), KSPComputeEigenvaluesExplicitly(), KSP
1474: @*/
1475: PetscErrorCode  KSPGetComputeEigenvalues(KSP ksp,PetscBool  *flg)
1476: {
1480:   *flg = ksp->calc_sings;
1481:   return(0);
1482: }

1484: /*@
1485:    KSPSetComputeEigenvalues - Sets a flag so that the extreme eigenvalues
1486:    values will be calculated via a Lanczos or Arnoldi process as the linear
1487:    system is solved.

1489:    Logically Collective on ksp

1491:    Input Parameters:
1492: +  ksp - iterative context obtained from KSPCreate()
1493: -  flg - PETSC_TRUE or PETSC_FALSE

1495:    Notes:
1496:    Currently this option is not valid for all iterative methods.

1498:    Level: advanced

1500: .seealso: KSPComputeEigenvalues(), KSPComputeEigenvaluesExplicitly(), KSP
1501: @*/
1502: PetscErrorCode  KSPSetComputeEigenvalues(KSP ksp,PetscBool flg)
1503: {
1507:   ksp->calc_sings = flg;
1508:   return(0);
1509: }

1511: /*@
1512:    KSPSetComputeRitz - Sets a flag so that the Ritz or harmonic Ritz pairs
1513:    will be calculated via a Lanczos or Arnoldi process as the linear
1514:    system is solved.

1516:    Logically Collective on ksp

1518:    Input Parameters:
1519: +  ksp - iterative context obtained from KSPCreate()
1520: -  flg - PETSC_TRUE or PETSC_FALSE

1522:    Notes:
1523:    Currently this option is only valid for the GMRES method.

1525:    Level: advanced

1527: .seealso: KSPComputeRitz(), KSP
1528: @*/
1529: PetscErrorCode  KSPSetComputeRitz(KSP ksp, PetscBool flg)
1530: {
1534:   ksp->calc_ritz = flg;
1535:   return(0);
1536: }

1538: /*@
1539:    KSPGetRhs - Gets the right-hand-side vector for the linear system to
1540:    be solved.

1542:    Not Collective

1544:    Input Parameter:
1545: .  ksp - iterative context obtained from KSPCreate()

1547:    Output Parameter:
1548: .  r - right-hand-side vector

1550:    Level: developer

1552: .seealso: KSPGetSolution(), KSPSolve(), KSP
1553: @*/
1554: PetscErrorCode  KSPGetRhs(KSP ksp,Vec *r)
1555: {
1559:   *r = ksp->vec_rhs;
1560:   return(0);
1561: }

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

1568:    Not Collective

1570:    Input Parameters:
1571: .  ksp - iterative context obtained from KSPCreate()

1573:    Output Parameters:
1574: .  v - solution vector

1576:    Level: developer

1578: .seealso: KSPGetRhs(),  KSPBuildSolution(), KSPSolve(), KSP
1579: @*/
1580: PetscErrorCode  KSPGetSolution(KSP ksp,Vec *v)
1581: {
1585:   *v = ksp->vec_sol;
1586:   return(0);
1587: }

1589: /*@
1590:    KSPSetPC - Sets the preconditioner to be used to calculate the
1591:    application of the preconditioner on a vector.

1593:    Collective on ksp

1595:    Input Parameters:
1596: +  ksp - iterative context obtained from KSPCreate()
1597: -  pc   - the preconditioner object (can be NULL)

1599:    Notes:
1600:    Use KSPGetPC() to retrieve the preconditioner context.

1602:    Level: developer

1604: .seealso: KSPGetPC(), KSP
1605: @*/
1606: PetscErrorCode  KSPSetPC(KSP ksp,PC pc)
1607: {

1612:   if (pc) {
1615:   }
1616:   PetscObjectReference((PetscObject)pc);
1617:   PCDestroy(&ksp->pc);
1618:   ksp->pc = pc;
1619:   PetscLogObjectParent((PetscObject)ksp,(PetscObject)ksp->pc);
1620:   return(0);
1621: }

1623: /*@
1624:    KSPGetPC - Returns a pointer to the preconditioner context
1625:    set with KSPSetPC().

1627:    Not Collective

1629:    Input Parameters:
1630: .  ksp - iterative context obtained from KSPCreate()

1632:    Output Parameter:
1633: .  pc - preconditioner context

1635:    Level: developer

1637: .seealso: KSPSetPC(), KSP
1638: @*/
1639: PetscErrorCode  KSPGetPC(KSP ksp,PC *pc)
1640: {

1646:   if (!ksp->pc) {
1647:     PCCreate(PetscObjectComm((PetscObject)ksp),&ksp->pc);
1648:     PetscObjectIncrementTabLevel((PetscObject)ksp->pc,(PetscObject)ksp,0);
1649:     PetscLogObjectParent((PetscObject)ksp,(PetscObject)ksp->pc);
1650:     PetscObjectSetOptions((PetscObject)ksp->pc,((PetscObject)ksp)->options);
1651:   }
1652:   *pc = ksp->pc;
1653:   return(0);
1654: }

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

1659:    Collective on ksp

1661:    Input Parameters:
1662: +  ksp - iterative context obtained from KSPCreate()
1663: .  it - iteration number
1664: -  rnorm - relative norm of the residual

1666:    Notes:
1667:    This routine is called by the KSP implementations.
1668:    It does not typically need to be called by the user.

1670:    Level: developer

1672: .seealso: KSPMonitorSet()
1673: @*/
1674: PetscErrorCode KSPMonitor(KSP ksp,PetscInt it,PetscReal rnorm)
1675: {
1676:   PetscInt       i, n = ksp->numbermonitors;

1680:   for (i=0; i<n; i++) {
1681:     (*ksp->monitor[i])(ksp,it,rnorm,ksp->monitorcontext[i]);
1682:   }
1683:   return(0);
1684: }

1686: /*@C
1687:    KSPMonitorSet - Sets an ADDITIONAL function to be called at every iteration to monitor
1688:    the residual/error etc.

1690:    Logically Collective on ksp

1692:    Input Parameters:
1693: +  ksp - iterative context obtained from KSPCreate()
1694: .  monitor - pointer to function (if this is NULL, it turns off monitoring
1695: .  mctx    - [optional] context for private data for the
1696:              monitor routine (use NULL if no context is desired)
1697: -  monitordestroy - [optional] routine that frees monitor context
1698:           (may be NULL)

1700:    Calling Sequence of monitor:
1701: $     monitor (KSP ksp, PetscInt it, PetscReal rnorm, void *mctx)

1703: +  ksp - iterative context obtained from KSPCreate()
1704: .  it - iteration number
1705: .  rnorm - (estimated) 2-norm of (preconditioned) residual
1706: -  mctx  - optional monitoring context, as set by KSPMonitorSet()

1708:    Options Database Keys:
1709: +    -ksp_monitor        - sets KSPMonitorDefault()
1710: .    -ksp_monitor_true_residual    - sets KSPMonitorTrueResidualNorm()
1711: .    -ksp_monitor_max    - sets KSPMonitorTrueResidualMaxNorm()
1712: .    -ksp_monitor_lg_residualnorm    - sets line graph monitor,
1713:                            uses KSPMonitorLGResidualNormCreate()
1714: .    -ksp_monitor_lg_true_residualnorm   - sets line graph monitor,
1715:                            uses KSPMonitorLGResidualNormCreate()
1716: .    -ksp_monitor_singular_value    - sets KSPMonitorSingularValue()
1717: -    -ksp_monitor_cancel - cancels all monitors that have
1718:                           been hardwired into a code by
1719:                           calls to KSPMonitorSet(), but
1720:                           does not cancel those set via
1721:                           the options database.

1723:    Notes:
1724:    The default is to do nothing.  To print the residual, or preconditioned
1725:    residual if KSPSetNormType(ksp,KSP_NORM_PRECONDITIONED) was called, use
1726:    KSPMonitorDefault() as the monitoring routine, with a ASCII viewer as the
1727:    context.

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

1733:    Fortran Notes:
1734:     Only a single monitor function can be set for each KSP object

1736:    Level: beginner

1738: .seealso: KSPMonitorDefault(), KSPMonitorLGResidualNormCreate(), KSPMonitorCancel(), KSP
1739: @*/
1740: PetscErrorCode  KSPMonitorSet(KSP ksp,PetscErrorCode (*monitor)(KSP,PetscInt,PetscReal,void*),void *mctx,PetscErrorCode (*monitordestroy)(void**))
1741: {
1742:   PetscInt       i;
1744:   PetscBool      identical;

1748:   for (i=0; i<ksp->numbermonitors;i++) {
1749:     PetscMonitorCompare((PetscErrorCode (*)(void))monitor,mctx,monitordestroy,(PetscErrorCode (*)(void))ksp->monitor[i],ksp->monitorcontext[i],ksp->monitordestroy[i],&identical);
1750:     if (identical) return(0);
1751:   }
1752:   if (ksp->numbermonitors >= MAXKSPMONITORS) SETERRQ(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_OUTOFRANGE,"Too many KSP monitors set");
1753:   ksp->monitor[ksp->numbermonitors]          = monitor;
1754:   ksp->monitordestroy[ksp->numbermonitors]   = monitordestroy;
1755:   ksp->monitorcontext[ksp->numbermonitors++] = (void*)mctx;
1756:   return(0);
1757: }

1759: /*@
1760:    KSPMonitorCancel - Clears all monitors for a KSP object.

1762:    Logically Collective on ksp

1764:    Input Parameters:
1765: .  ksp - iterative context obtained from KSPCreate()

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

1772:    Level: intermediate

1774: .seealso: KSPMonitorDefault(), KSPMonitorLGResidualNormCreate(), KSPMonitorSet(), KSP
1775: @*/
1776: PetscErrorCode  KSPMonitorCancel(KSP ksp)
1777: {
1779:   PetscInt       i;

1783:   for (i=0; i<ksp->numbermonitors; i++) {
1784:     if (ksp->monitordestroy[i]) {
1785:       (*ksp->monitordestroy[i])(&ksp->monitorcontext[i]);
1786:     }
1787:   }
1788:   ksp->numbermonitors = 0;
1789:   return(0);
1790: }

1792: /*@C
1793:    KSPGetMonitorContext - Gets the monitoring context, as set by
1794:    KSPMonitorSet() for the FIRST monitor only.

1796:    Not Collective

1798:    Input Parameter:
1799: .  ksp - iterative context obtained from KSPCreate()

1801:    Output Parameter:
1802: .  ctx - monitoring context

1804:    Level: intermediate

1806: .seealso: KSPMonitorDefault(), KSPMonitorLGResidualNormCreate(), KSP
1807: @*/
1808: PetscErrorCode  KSPGetMonitorContext(KSP ksp,void **ctx)
1809: {
1812:   *ctx =      (ksp->monitorcontext[0]);
1813:   return(0);
1814: }

1816: /*@
1817:    KSPSetResidualHistory - Sets the array used to hold the residual history.
1818:    If set, this array will contain the residual norms computed at each
1819:    iteration of the solver.

1821:    Not Collective

1823:    Input Parameters:
1824: +  ksp - iterative context obtained from KSPCreate()
1825: .  a   - array to hold history
1826: .  na  - size of a
1827: -  reset - PETSC_TRUE indicates the history counter is reset to zero
1828:            for each new linear solve

1830:    Level: advanced

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

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

1839: .seealso: KSPGetResidualHistory(), KSP

1841: @*/
1842: PetscErrorCode  KSPSetResidualHistory(KSP ksp,PetscReal a[],PetscInt na,PetscBool reset)
1843: {


1849:   PetscFree(ksp->res_hist_alloc);
1850:   if (na != PETSC_DECIDE && na != PETSC_DEFAULT && a) {
1851:     ksp->res_hist     = a;
1852:     ksp->res_hist_max = na;
1853:   } else {
1854:     if (na != PETSC_DECIDE && na != PETSC_DEFAULT) ksp->res_hist_max = na;
1855:     else                                           ksp->res_hist_max = 10000; /* like default ksp->max_it */
1856:     PetscCalloc1(ksp->res_hist_max,&ksp->res_hist_alloc);

1858:     ksp->res_hist = ksp->res_hist_alloc;
1859:   }
1860:   ksp->res_hist_len   = 0;
1861:   ksp->res_hist_reset = reset;
1862:   return(0);
1863: }

1865: /*@C
1866:    KSPGetResidualHistory - Gets the array used to hold the residual history
1867:    and the number of residuals it contains.

1869:    Not Collective

1871:    Input Parameter:
1872: .  ksp - iterative context obtained from KSPCreate()

1874:    Output Parameters:
1875: +  a   - pointer to array to hold history (or NULL)
1876: -  na  - number of used entries in a (or NULL)

1878:    Level: advanced

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

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

1889: .seealso: KSPGetResidualHistory(), KSP

1891: @*/
1892: PetscErrorCode  KSPGetResidualHistory(KSP ksp,PetscReal *a[],PetscInt *na)
1893: {
1896:   if (a) *a = ksp->res_hist;
1897:   if (na) *na = ksp->res_hist_len;
1898:   return(0);
1899: }

1901: /*@C
1902:    KSPSetConvergenceTest - Sets the function to be used to determine
1903:    convergence.

1905:    Logically Collective on ksp

1907:    Input Parameters:
1908: +  ksp - iterative context obtained from KSPCreate()
1909: .  converge - pointer to the function
1910: .  cctx    - context for private data for the convergence routine (may be null)
1911: -  destroy - a routine for destroying the context (may be null)

1913:    Calling sequence of converge:
1914: $     converge (KSP ksp, PetscInt it, PetscReal rnorm, KSPConvergedReason *reason,void *mctx)

1916: +  ksp - iterative context obtained from KSPCreate()
1917: .  it - iteration number
1918: .  rnorm - (estimated) 2-norm of (preconditioned) residual
1919: .  reason - the reason why it has converged or diverged
1920: -  cctx  - optional convergence context, as set by KSPSetConvergenceTest()


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

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

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

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

1937:    Level: advanced

1939: .seealso: KSPConvergedDefault(), KSPGetConvergenceContext(), KSPSetTolerances(), KSP, KSPGetConvergenceTest(), KSPGetAndClearConvergenceTest()
1940: @*/
1941: PetscErrorCode  KSPSetConvergenceTest(KSP ksp,PetscErrorCode (*converge)(KSP,PetscInt,PetscReal,KSPConvergedReason*,void*),void *cctx,PetscErrorCode (*destroy)(void*))
1942: {

1947:   if (ksp->convergeddestroy) {
1948:     (*ksp->convergeddestroy)(ksp->cnvP);
1949:   }
1950:   ksp->converged        = converge;
1951:   ksp->convergeddestroy = destroy;
1952:   ksp->cnvP             = (void*)cctx;
1953:   return(0);
1954: }

1956: /*@C
1957:    KSPGetConvergenceTest - Gets the function to be used to determine
1958:    convergence.

1960:    Logically Collective on ksp

1962:    Input Parameter:
1963: .   ksp - iterative context obtained from KSPCreate()

1965:    Output Parameter:
1966: +  converge - pointer to convergence test function
1967: .  cctx    - context for private data for the convergence routine (may be null)
1968: -  destroy - a routine for destroying the context (may be null)

1970:    Calling sequence of converge:
1971: $     converge (KSP ksp, PetscInt it, PetscReal rnorm, KSPConvergedReason *reason,void *mctx)

1973: +  ksp - iterative context obtained from KSPCreate()
1974: .  it - iteration number
1975: .  rnorm - (estimated) 2-norm of (preconditioned) residual
1976: .  reason - the reason why it has converged or diverged
1977: -  cctx  - optional convergence context, as set by KSPSetConvergenceTest()

1979:    Level: advanced

1981: .seealso: KSPConvergedDefault(), KSPGetConvergenceContext(), KSPSetTolerances(), KSP, KSPSetConvergenceTest(), KSPGetAndClearConvergenceTest()
1982: @*/
1983: PetscErrorCode  KSPGetConvergenceTest(KSP ksp,PetscErrorCode (**converge)(KSP,PetscInt,PetscReal,KSPConvergedReason*,void*),void **cctx,PetscErrorCode (**destroy)(void*))
1984: {
1987:   if (converge) *converge = ksp->converged;
1988:   if (destroy)  *destroy  = ksp->convergeddestroy;
1989:   if (cctx)     *cctx     = ksp->cnvP;
1990:   return(0);
1991: }

1993: /*@C
1994:    KSPGetAndClearConvergenceTest - Gets the function to be used to determine convergence. Removes the current test without calling destroy on the test context

1996:    Logically Collective on ksp

1998:    Input Parameter:
1999: .   ksp - iterative context obtained from KSPCreate()

2001:    Output Parameter:
2002: +  converge - pointer to convergence test function
2003: .  cctx    - context for private data for the convergence routine
2004: -  destroy - a routine for destroying the context

2006:    Calling sequence of converge:
2007: $     converge (KSP ksp, PetscInt it, PetscReal rnorm, KSPConvergedReason *reason,void *mctx)

2009: +  ksp - iterative context obtained from KSPCreate()
2010: .  it - iteration number
2011: .  rnorm - (estimated) 2-norm of (preconditioned) residual
2012: .  reason - the reason why it has converged or diverged
2013: -  cctx  - optional convergence context, as set by KSPSetConvergenceTest()

2015:    Level: advanced

2017:    Notes: This is intended to be used to allow transferring the convergence test (and its context) to another testing object (for example another KSP) and then calling
2018:           KSPSetConvergenceTest() on this original KSP. If you just called KSPGetConvergenceTest() followed by KSPSetConvergenceTest() the original context information
2019:           would be destroyed and hence the transferred context would be invalid and trigger a crash on use

2021: .seealso: KSPConvergedDefault(), KSPGetConvergenceContext(), KSPSetTolerances(), KSP, KSPSetConvergenceTest(), KSPGetConvergenceTest()
2022: @*/
2023: PetscErrorCode  KSPGetAndClearConvergenceTest(KSP ksp,PetscErrorCode (**converge)(KSP,PetscInt,PetscReal,KSPConvergedReason*,void*),void **cctx,PetscErrorCode (**destroy)(void*))
2024: {
2027:   *converge             = ksp->converged;
2028:   *destroy              = ksp->convergeddestroy;
2029:   *cctx                 = ksp->cnvP;
2030:   ksp->converged        = NULL;
2031:   ksp->cnvP             = NULL;
2032:   ksp->convergeddestroy = NULL;
2033:   return(0);
2034: }

2036: /*@C
2037:    KSPGetConvergenceContext - Gets the convergence context set with
2038:    KSPSetConvergenceTest().

2040:    Not Collective

2042:    Input Parameter:
2043: .  ksp - iterative context obtained from KSPCreate()

2045:    Output Parameter:
2046: .  ctx - monitoring context

2048:    Level: advanced

2050: .seealso: KSPConvergedDefault(), KSPSetConvergenceTest(), KSP
2051: @*/
2052: PetscErrorCode  KSPGetConvergenceContext(KSP ksp,void **ctx)
2053: {
2056:   *ctx = ksp->cnvP;
2057:   return(0);
2058: }

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

2064:    Collective on ksp

2066:    Input Parameter:
2067: .  ctx - iterative context obtained from KSPCreate()

2069:    Output Parameter:
2070:    Provide exactly one of
2071: +  v - location to stash solution.
2072: -  V - the solution is returned in this location. This vector is created
2073:        internally. This vector should NOT be destroyed by the user with
2074:        VecDestroy().

2076:    Notes:
2077:    This routine can be used in one of two ways
2078: .vb
2079:       KSPBuildSolution(ksp,NULL,&V);
2080:    or
2081:       KSPBuildSolution(ksp,v,NULL); or KSPBuildSolution(ksp,v,&v);
2082: .ve
2083:    In the first case an internal vector is allocated to store the solution
2084:    (the user cannot destroy this vector). In the second case the solution
2085:    is generated in the vector that the user provides. Note that for certain
2086:    methods, such as KSPCG, the second case requires a copy of the solution,
2087:    while in the first case the call is essentially free since it simply
2088:    returns the vector where the solution already is stored. For some methods
2089:    like GMRES this is a reasonably expensive operation and should only be
2090:    used in truly needed.

2092:    Level: advanced

2094: .seealso: KSPGetSolution(), KSPBuildResidual(), KSP
2095: @*/
2096: PetscErrorCode  KSPBuildSolution(KSP ksp,Vec v,Vec *V)
2097: {

2102:   if (!V && !v) SETERRQ(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_WRONG,"Must provide either v or V");
2103:   if (!V) V = &v;
2104:   (*ksp->ops->buildsolution)(ksp,v,V);
2105:   return(0);
2106: }

2108: /*@C
2109:    KSPBuildResidual - Builds the residual in a vector provided.

2111:    Collective on ksp

2113:    Input Parameter:
2114: .  ksp - iterative context obtained from KSPCreate()

2116:    Output Parameters:
2117: +  v - optional location to stash residual.  If v is not provided,
2118:        then a location is generated.
2119: .  t - work vector.  If not provided then one is generated.
2120: -  V - the residual

2122:    Notes:
2123:    Regardless of whether or not v is provided, the residual is
2124:    returned in V.

2126:    Level: advanced

2128: .seealso: KSPBuildSolution()
2129: @*/
2130: PetscErrorCode  KSPBuildResidual(KSP ksp,Vec t,Vec v,Vec *V)
2131: {
2133:   PetscBool      flag = PETSC_FALSE;
2134:   Vec            w    = v,tt = t;

2138:   if (!w) {
2139:     VecDuplicate(ksp->vec_rhs,&w);
2140:     PetscLogObjectParent((PetscObject)ksp,(PetscObject)w);
2141:   }
2142:   if (!tt) {
2143:     VecDuplicate(ksp->vec_sol,&tt); flag = PETSC_TRUE;
2144:     PetscLogObjectParent((PetscObject)ksp,(PetscObject)tt);
2145:   }
2146:   (*ksp->ops->buildresidual)(ksp,tt,w,V);
2147:   if (flag) {VecDestroy(&tt);}
2148:   return(0);
2149: }

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

2155:    Logically Collective on ksp

2157:    Input Parameter:
2158: +  ksp - the KSP context
2159: -  scale - PETSC_TRUE or PETSC_FALSE

2161:    Options Database Key:
2162: +   -ksp_diagonal_scale -
2163: -   -ksp_diagonal_scale_fix - scale the matrix back AFTER the solve


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

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

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

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

2181:    Level: intermediate

2183: .seealso: KSPGetDiagonalScale(), KSPSetDiagonalScaleFix(), KSP
2184: @*/
2185: PetscErrorCode  KSPSetDiagonalScale(KSP ksp,PetscBool scale)
2186: {
2190:   ksp->dscale = scale;
2191:   return(0);
2192: }

2194: /*@
2195:    KSPGetDiagonalScale - Checks if KSP solver scales the matrix and
2196:                           right hand side

2198:    Not Collective

2200:    Input Parameter:
2201: .  ksp - the KSP context

2203:    Output Parameter:
2204: .  scale - PETSC_TRUE or PETSC_FALSE

2206:    Notes:
2207:     BE CAREFUL with this routine: it actually scales the matrix and right
2208:     hand side that define the system. After the system is solved the matrix
2209:     and right hand side remain scaled  unless you use KSPSetDiagonalScaleFix()

2211:    Level: intermediate

2213: .seealso: KSPSetDiagonalScale(), KSPSetDiagonalScaleFix(), KSP
2214: @*/
2215: PetscErrorCode  KSPGetDiagonalScale(KSP ksp,PetscBool  *scale)
2216: {
2220:   *scale = ksp->dscale;
2221:   return(0);
2222: }

2224: /*@
2225:    KSPSetDiagonalScaleFix - Tells KSP to diagonally scale the system
2226:      back after solving.

2228:    Logically Collective on ksp

2230:    Input Parameter:
2231: +  ksp - the KSP context
2232: -  fix - PETSC_TRUE to scale back after the system solve, PETSC_FALSE to not
2233:          rescale (default)

2235:    Notes:
2236:      Must be called after KSPSetDiagonalScale()

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

2243:    Level: intermediate

2245: .seealso: KSPGetDiagonalScale(), KSPSetDiagonalScale(), KSPGetDiagonalScaleFix(), KSP
2246: @*/
2247: PetscErrorCode  KSPSetDiagonalScaleFix(KSP ksp,PetscBool fix)
2248: {
2252:   ksp->dscalefix = fix;
2253:   return(0);
2254: }

2256: /*@
2257:    KSPGetDiagonalScaleFix - Determines if KSP diagonally scales the system
2258:      back after solving.

2260:    Not Collective

2262:    Input Parameter:
2263: .  ksp - the KSP context

2265:    Output Parameter:
2266: .  fix - PETSC_TRUE to scale back after the system solve, PETSC_FALSE to not
2267:          rescale (default)

2269:    Notes:
2270:      Must be called after KSPSetDiagonalScale()

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

2277:    Level: intermediate

2279: .seealso: KSPGetDiagonalScale(), KSPSetDiagonalScale(), KSPSetDiagonalScaleFix(), KSP
2280: @*/
2281: PetscErrorCode  KSPGetDiagonalScaleFix(KSP ksp,PetscBool  *fix)
2282: {
2286:   *fix = ksp->dscalefix;
2287:   return(0);
2288: }

2290: /*@C
2291:    KSPSetComputeOperators - set routine to compute the linear operators

2293:    Logically Collective

2295:    Input Arguments:
2296: +  ksp - the KSP context
2297: .  func - function to compute the operators
2298: -  ctx - optional context

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

2303: +  ksp - the KSP context
2304: .  A - the linear operator
2305: .  B - preconditioning matrix
2306: -  ctx - optional user-provided context

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

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

2314:    Level: beginner

2316: .seealso: KSPSetOperators(), KSPSetComputeRHS(), DMKSPSetComputeOperators(), KSPSetComputeInitialGuess()
2317: @*/
2318: PetscErrorCode KSPSetComputeOperators(KSP ksp,PetscErrorCode (*func)(KSP,Mat,Mat,void*),void *ctx)
2319: {
2321:   DM             dm;

2325:   KSPGetDM(ksp,&dm);
2326:   DMKSPSetComputeOperators(dm,func,ctx);
2327:   if (ksp->setupstage == KSP_SETUP_NEWRHS) ksp->setupstage = KSP_SETUP_NEWMATRIX;
2328:   return(0);
2329: }

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

2334:    Logically Collective

2336:    Input Arguments:
2337: +  ksp - the KSP context
2338: .  func - function to compute the right hand side
2339: -  ctx - optional context

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

2344: +  ksp - the KSP context
2345: .  b - right hand side of linear system
2346: -  ctx - optional user-provided context

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

2351:    Level: beginner

2353: .seealso: KSPSolve(), DMKSPSetComputeRHS(), KSPSetComputeOperators()
2354: @*/
2355: PetscErrorCode KSPSetComputeRHS(KSP ksp,PetscErrorCode (*func)(KSP,Vec,void*),void *ctx)
2356: {
2358:   DM             dm;

2362:   KSPGetDM(ksp,&dm);
2363:   DMKSPSetComputeRHS(dm,func,ctx);
2364:   return(0);
2365: }

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

2370:    Logically Collective

2372:    Input Arguments:
2373: +  ksp - the KSP context
2374: .  func - function to compute the initial guess
2375: -  ctx - optional context

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

2380: +  ksp - the KSP context
2381: .  x - solution vector
2382: -  ctx - optional user-provided context

2384:    Notes: This should only be used in conjunction with KSPSetComputeRHS(), KSPSetComputeOperators(), otherwise
2385:    call KSPSetInitialGuessNonzero() and set the initial guess values in the solution vector passed to KSPSolve().

2387:    Level: beginner

2389: .seealso: KSPSolve(), KSPSetComputeRHS(), KSPSetComputeOperators(), DMKSPSetComputeInitialGuess()
2390: @*/
2391: PetscErrorCode KSPSetComputeInitialGuess(KSP ksp,PetscErrorCode (*func)(KSP,Vec,void*),void *ctx)
2392: {
2394:   DM             dm;

2398:   KSPGetDM(ksp,&dm);
2399:   DMKSPSetComputeInitialGuess(dm,func,ctx);
2400:   return(0);
2401: }