Actual source code: itfunc.c

petsc-3.15.0 2021-04-05
Report Typos and Errors
  1: /*
  2:       Interface KSP routines that the user calls.
  3: */

  5: #include <petsc/private/kspimpl.h>
  6: #include <petsc/private/matimpl.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 Parameters:
 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 Parameters:
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:   PCGetFailedReasonRank(pc,&pcreason);
216:   /* TODO: this code was wrong and is still wrong, there is no way to propogate the failure to all processes; their is no code to handle a ksp->reason on only some ranks */
217:   if (pcreason) {
218:     ksp->reason = KSP_DIVERGED_PC_FAILED;
219:   }
220:   return(0);
221: }

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

226:    Collective on ksp

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

232:    Level: intermediate

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

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

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

251:    Collective on ksp

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

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

259:    Level: intermediate

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

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

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

280:    Collective on ksp

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

286:    Level: intermediate

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

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

302:    Collective on ksp

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

307:    Level: developer

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


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

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

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

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

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

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

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

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

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

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

425: /*@C
426:    KSPConvergedReasonView - Displays the reason a KSP solve converged or diverged to a viewer

428:    Collective on ksp

430:    Parameter:
431: +  ksp - iterative context obtained from KSPCreate()
432: -  viewer - the viewer to display the reason

434:    Options Database Keys:
435: +  -ksp_converged_reason - print reason for converged or diverged, also prints number of iterations
436: -  -ksp_converged_reason ::failed - only print reason and number of iterations when diverged

438:    Notes:
439:      To change the format of the output call PetscViewerPushFormat(viewer,format) before this call. Use PETSC_VIEWER_DEFAULT for the default,
440:      use PETSC_VIEWER_FAILED to only display a reason if it fails.

442:    Level: beginner

444: .seealso: KSPCreate(), KSPSetUp(), KSPDestroy(), KSPSetTolerances(), KSPConvergedDefault(),
445:           KSPSolveTranspose(), KSPGetIterationNumber(), KSP, KSPGetConvergedReason(), PetscViewerPushFormat(), PetscViewerPopFormat()
446: @*/
447: PetscErrorCode KSPConvergedReasonView(KSP ksp, PetscViewer viewer)
448: {
449:   PetscErrorCode    ierr;
450:   PetscBool         isAscii;
451:   PetscViewerFormat format;

454:   if (!viewer) viewer = PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)ksp));
455:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&isAscii);
456:   if (isAscii) {
457:     PetscViewerGetFormat(viewer, &format);
458:     PetscViewerASCIIAddTab(viewer,((PetscObject)ksp)->tablevel);
459:     if (ksp->reason > 0 && format != PETSC_VIEWER_FAILED) {
460:       if (((PetscObject) ksp)->prefix) {
461:         PetscViewerASCIIPrintf(viewer,"Linear %s solve converged due to %s iterations %D\n",((PetscObject) ksp)->prefix,KSPConvergedReasons[ksp->reason],ksp->its);
462:       } else {
463:         PetscViewerASCIIPrintf(viewer,"Linear solve converged due to %s iterations %D\n",KSPConvergedReasons[ksp->reason],ksp->its);
464:       }
465:     } else if (ksp->reason <= 0) {
466:       if (((PetscObject) ksp)->prefix) {
467:         PetscViewerASCIIPrintf(viewer,"Linear %s solve did not converge due to %s iterations %D\n",((PetscObject) ksp)->prefix,KSPConvergedReasons[ksp->reason],ksp->its);
468:       } else {
469:         PetscViewerASCIIPrintf(viewer,"Linear solve did not converge due to %s iterations %D\n",KSPConvergedReasons[ksp->reason],ksp->its);
470:       }
471:       if (ksp->reason == KSP_DIVERGED_PC_FAILED) {
472:         PCFailedReason reason;
473:         PCGetFailedReason(ksp->pc,&reason);
474:         PetscViewerASCIIPrintf(viewer,"               PC failed due to %s \n",PCFailedReasons[reason]);
475:       }
476:     }
477:     PetscViewerASCIISubtractTab(viewer,((PetscObject)ksp)->tablevel);
478:   }
479:   return(0);
480: }

482: /*@C
483:    KSPConvergedReasonViewSet - Sets an ADDITIONAL function that is to be used at the
484:     end of the linear solver to display the convergence reason of the linear solver.

486:    Logically Collective on KSP

488:    Input Parameters:
489: +  ksp - the KSP context
490: .  f - the ksp converged reason view function
491: .  vctx - [optional] user-defined context for private data for the
492:           ksp converged reason view routine (use NULL if no context is desired)
493: -  reasonviewdestroy - [optional] routine that frees reasonview context
494:           (may be NULL)

496:    Options Database Keys:
497: +    -ksp_converged_reason        - sets a default KSPConvergedReasonView()
498: -    -ksp_converged_reason_view_cancel - cancels all converged reason viewers that have
499:                             been hardwired into a code by
500:                             calls to KSPConvergedReasonViewSet(), but
501:                             does not cancel those set via
502:                             the options database.

504:    Notes:
505:    Several different converged reason view routines may be set by calling
506:    KSPConvergedReasonViewSet() multiple times; all will be called in the
507:    order in which they were set.

509:    Level: intermediate

511: .seealso: KSPConvergedReasonView(), KSPConvergedReasonViewCancel()
512: @*/
513: PetscErrorCode  KSPConvergedReasonViewSet(KSP ksp,PetscErrorCode (*f)(KSP,void*),void *vctx,PetscErrorCode (*reasonviewdestroy)(void**))
514: {
515:   PetscInt       i;
517:   PetscBool      identical;

521:   for (i=0; i<ksp->numberreasonviews;i++) {
522:     PetscMonitorCompare((PetscErrorCode (*)(void))f,vctx,reasonviewdestroy,(PetscErrorCode (*)(void))ksp->reasonview[i],ksp->reasonviewcontext[i],ksp->reasonviewdestroy[i],&identical);
523:     if (identical) return(0);
524:   }
525:   if (ksp->numberreasonviews >= MAXKSPREASONVIEWS) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Too many KSP reasonview set");
526:   ksp->reasonview[ksp->numberreasonviews]          = f;
527:   ksp->reasonviewdestroy[ksp->numberreasonviews]   = reasonviewdestroy;
528:   ksp->reasonviewcontext[ksp->numberreasonviews++] = (void*)vctx;
529:   return(0);
530: }

532: /*@
533:    KSPConvergedReasonViewCancel - Clears all the reasonview functions for a KSP object.

535:    Collective on KSP

537:    Input Parameter:
538: .  ksp - iterative context obtained from KSPCreate()

540:    Level: intermediate

542: .seealso: KSPCreate(), KSPDestroy(), KSPReset()
543: @*/
544: PetscErrorCode  KSPConvergedReasonViewCancel(KSP ksp)
545: {
547:   PetscInt       i;

551:   for (i=0; i<ksp->numberreasonviews; i++) {
552:     if (ksp->reasonviewdestroy[i]) {
553:       (*ksp->reasonviewdestroy[i])(&ksp->reasonviewcontext[i]);
554:     }
555:   }
556:   ksp->numberreasonviews = 0;
557:   return(0);
558: }

560: /*@
561:   KSPConvergedReasonViewFromOptions - Processes command line options to determine if/how a KSPReason is to be viewed.

563:   Collective on ksp

565:   Input Parameters:
566: . ksp   - the KSP object

568:   Level: intermediate

570: .seealso: KSPConvergedReasonView()
571: @*/
572: PetscErrorCode KSPConvergedReasonViewFromOptions(KSP ksp)
573: {
574:   PetscViewer       viewer;
575:   PetscBool         flg;
576:   PetscViewerFormat format;
577:   PetscErrorCode    ierr;
578:   PetscInt          i;


582:   /* Call all user-provided reason review routines */
583:   for (i=0; i<ksp->numberreasonviews; i++) {
584:     (*ksp->reasonview[i])(ksp,ksp->reasonviewcontext[i]);
585:   }

587:   /* Call the default PETSc routine */
588:   PetscOptionsGetViewer(PetscObjectComm((PetscObject)ksp),((PetscObject)ksp)->options,((PetscObject)ksp)->prefix,"-ksp_converged_reason",&viewer,&format,&flg);
589:   if (flg) {
590:     PetscViewerPushFormat(viewer,format);
591:     KSPConvergedReasonView(ksp, viewer);
592:     PetscViewerPopFormat(viewer);
593:     PetscViewerDestroy(&viewer);
594:   }
595:   return(0);
596: }

598: /*@C
599:   KSPConvergedRateView - Displays the reason a KSP solve converged or diverged to a viewer

601:   Collective on ksp

603:   Input Parameters:
604: +  ksp    - iterative context obtained from KSPCreate()
605: -  viewer - the viewer to display the reason

607:   Options Database Keys:
608: . -ksp_converged_rate - print reason for convergence or divergence and the convergence rate (or 0.0 for divergence)

610:   Notes:
611:   To change the format of the output, call PetscViewerPushFormat(viewer,format) before this call.

613:   Suppose that the residual is reduced linearly, $r_k = c^k r_0$, which means $log r_k = log r_0 + k log c$. After linear regression,
614:   the slope is $\log c$. The coefficient of determination is given by $1 - \frac{\sum_i (y_i - f(x_i))^2}{\sum_i (y_i - \bar y)}$,
615:   see also https://en.wikipedia.org/wiki/Coefficient_of_determination

617:   Level: intermediate

619: .seealso: KSPConvergedReasonView(), KSPGetConvergedRate(), KSPSetTolerances(), KSPConvergedDefault()
620: @*/
621: PetscErrorCode KSPConvergedRateView(KSP ksp, PetscViewer viewer)
622: {
623:   PetscViewerFormat format;
624:   PetscBool         isAscii;
625:   PetscReal         rrate, rRsq, erate, eRsq;
626:   PetscInt          its;
627:   const char       *prefix, *reason = KSPConvergedReasons[ksp->reason];
628:   PetscErrorCode    ierr;

631:   KSPGetOptionsPrefix(ksp, &prefix);
632:   KSPGetIterationNumber(ksp, &its);
633:   KSPComputeConvergenceRate(ksp, &rrate, &rRsq, &erate, &eRsq);
634:   if (!viewer) viewer = PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)ksp));
635:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&isAscii);
636:   if (isAscii) {
637:     PetscViewerGetFormat(viewer, &format);
638:     PetscViewerASCIIAddTab(viewer,((PetscObject)ksp)->tablevel);
639:     if (ksp->reason > 0) {
640:       if (prefix) {PetscViewerASCIIPrintf(viewer, "Linear %s solve converged due to %s iterations %D", prefix, reason, its);}
641:       else        {PetscViewerASCIIPrintf(viewer, "Linear solve converged due to %s iterations %D", reason, its);}
642:       PetscViewerASCIIUseTabs(viewer, PETSC_FALSE);
643:       if (rRsq >= 0.0) {PetscViewerASCIIPrintf(viewer, " res rate %g R^2 %g", rrate, rRsq);}
644:       if (eRsq >= 0.0) {PetscViewerASCIIPrintf(viewer, " error rate %g R^2 %g", erate, eRsq);}
645:       PetscViewerASCIIPrintf(viewer, "\n");
646:       PetscViewerASCIIUseTabs(viewer, PETSC_TRUE);
647:     } else if (ksp->reason <= 0) {
648:       if (prefix) {PetscViewerASCIIPrintf(viewer, "Linear %s solve did not converge due to %s iterations %D", prefix, reason, its);}
649:       else        {PetscViewerASCIIPrintf(viewer, "Linear solve did not converge due to %s iterations %D", reason, its);}
650:       PetscViewerASCIIUseTabs(viewer, PETSC_FALSE);
651:       if (rRsq >= 0.0) {PetscViewerASCIIPrintf(viewer, " res rate %g R^2 %g", rrate, rRsq);}
652:       if (eRsq >= 0.0) {PetscViewerASCIIPrintf(viewer, " error rate %g R^2 %g", erate, eRsq);}
653:       PetscViewerASCIIPrintf(viewer, "\n");
654:       PetscViewerASCIIUseTabs(viewer, PETSC_TRUE);
655:       if (ksp->reason == KSP_DIVERGED_PC_FAILED) {
656:         PCFailedReason reason;
657:         PCGetFailedReason(ksp->pc,&reason);
658:         PetscViewerASCIIPrintf(viewer,"               PC failed due to %s \n",PCFailedReasons[reason]);
659:       }
660:     }
661:     PetscViewerASCIISubtractTab(viewer,((PetscObject)ksp)->tablevel);
662:   }
663:   return(0);
664: }

666: #include <petscdraw.h>

668: static PetscErrorCode KSPViewEigenvalues_Internal(KSP ksp, PetscBool isExplicit, PetscViewer viewer, PetscViewerFormat format)
669: {
670:   PetscReal     *r, *c;
671:   PetscInt       n, i, neig;
672:   PetscBool      isascii, isdraw;
673:   PetscMPIInt    rank;

677:   MPI_Comm_rank(PetscObjectComm((PetscObject) ksp), &rank);
678:   PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWERASCII, &isascii);
679:   PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWERDRAW,  &isdraw);
680:   if (isExplicit) {
681:     VecGetSize(ksp->vec_sol,&n);
682:     PetscMalloc2(n, &r, n, &c);
683:     KSPComputeEigenvaluesExplicitly(ksp, n, r, c);
684:     neig = n;
685:   } else {
686:     PetscInt nits;

688:     KSPGetIterationNumber(ksp, &nits);
689:     n    = nits+2;
690:     if (!nits) {PetscViewerASCIIPrintf(viewer, "Zero iterations in solver, cannot approximate any eigenvalues\n");return(0);}
691:     PetscMalloc2(n, &r, n, &c);
692:     KSPComputeEigenvalues(ksp, n, r, c, &neig);
693:   }
694:   if (isascii) {
695:     PetscViewerASCIIPrintf(viewer, "%s computed eigenvalues\n", isExplicit ? "Explicitly" : "Iteratively");
696:     for (i = 0; i < neig; ++i) {
697:       if (c[i] >= 0.0) {PetscViewerASCIIPrintf(viewer, "%g + %gi\n", (double) r[i],  (double) c[i]);}
698:       else             {PetscViewerASCIIPrintf(viewer, "%g - %gi\n", (double) r[i], -(double) c[i]);}
699:     }
700:   } else if (isdraw && !rank) {
701:     PetscDraw   draw;
702:     PetscDrawSP drawsp;

704:     if (format == PETSC_VIEWER_DRAW_CONTOUR) {
705:       KSPPlotEigenContours_Private(ksp,neig,r,c);
706:     } else {
707:       if (!ksp->eigviewer) {PetscViewerDrawOpen(PETSC_COMM_SELF,NULL,isExplicit ? "Explicitly Computed Eigenvalues" : "Iteratively Computed Eigenvalues",PETSC_DECIDE,PETSC_DECIDE,400,400,&ksp->eigviewer);}
708:       PetscViewerDrawGetDraw(ksp->eigviewer,0,&draw);
709:       PetscDrawSPCreate(draw,1,&drawsp);
710:       PetscDrawSPReset(drawsp);
711:       for (i = 0; i < neig; ++i) {PetscDrawSPAddPoint(drawsp,r+i,c+i);}
712:       PetscDrawSPDraw(drawsp,PETSC_TRUE);
713:       PetscDrawSPSave(drawsp);
714:       PetscDrawSPDestroy(&drawsp);
715:     }
716:   }
717:   PetscFree2(r, c);
718:   return(0);
719: }

721: static PetscErrorCode KSPViewSingularvalues_Internal(KSP ksp, PetscViewer viewer, PetscViewerFormat format)
722: {
723:   PetscReal      smax, smin;
724:   PetscInt       nits;
725:   PetscBool      isascii;

729:   PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWERASCII, &isascii);
730:   KSPGetIterationNumber(ksp, &nits);
731:   if (!nits) {PetscViewerASCIIPrintf(viewer, "Zero iterations in solver, cannot approximate any singular values\n");return(0);}
732:   KSPComputeExtremeSingularValues(ksp, &smax, &smin);
733:   if (isascii) {PetscViewerASCIIPrintf(viewer, "Iteratively computed extreme singular values: max %g min %g max/min %g\n",(double)smax,(double)smin,(double)(smax/smin));}
734:   return(0);
735: }

737: static PetscErrorCode KSPViewFinalResidual_Internal(KSP ksp, PetscViewer viewer, PetscViewerFormat format)
738: {
739:   PetscBool      isascii;

743:   PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWERASCII, &isascii);
744:   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");
745:   if (isascii) {
746:     Mat       A;
747:     Vec       t;
748:     PetscReal norm;

750:     PCGetOperators(ksp->pc, &A, NULL);
751:     VecDuplicate(ksp->vec_rhs, &t);
752:     KSP_MatMult(ksp, A, ksp->vec_sol, t);
753:     VecAYPX(t, -1.0, ksp->vec_rhs);
754:     VecNorm(t, NORM_2, &norm);
755:     VecDestroy(&t);
756:     PetscViewerASCIIPrintf(viewer, "KSP final norm of residual %g\n", (double) norm);
757:   }
758:   return(0);
759: }

761: static PetscErrorCode KSPMonitorPauseFinal_Internal(KSP ksp)
762: {
763:   PetscInt       i;

767:   if (!ksp->pauseFinal) return(0);
768:   for (i = 0; i < ksp->numbermonitors; ++i) {
769:     PetscViewerAndFormat *vf = (PetscViewerAndFormat *) ksp->monitorcontext[i];
770:     PetscDraw             draw;
771:     PetscReal             lpause;

773:     if (!vf) continue;
774:     if (vf->lg) {
776:       if (((PetscObject) vf->lg)->classid != PETSC_DRAWLG_CLASSID) continue;
777:       PetscDrawLGGetDraw(vf->lg, &draw);
778:       PetscDrawGetPause(draw, &lpause);
779:       PetscDrawSetPause(draw, -1.0);
780:       PetscDrawPause(draw);
781:       PetscDrawSetPause(draw, lpause);
782:     } else {
783:       PetscBool isdraw;

786:       if (((PetscObject) vf->viewer)->classid != PETSC_VIEWER_CLASSID) continue;
787:       PetscObjectTypeCompare((PetscObject) vf->viewer, PETSCVIEWERDRAW, &isdraw);
788:       if (!isdraw) continue;
789:       PetscViewerDrawGetDraw(vf->viewer, 0, &draw);
790:       PetscDrawGetPause(draw, &lpause);
791:       PetscDrawSetPause(draw, -1.0);
792:       PetscDrawPause(draw);
793:       PetscDrawSetPause(draw, lpause);
794:     }
795:   }
796:   return(0);
797: }

799: static PetscErrorCode KSPSolve_Private(KSP ksp,Vec b,Vec x)
800: {
802:   PetscBool      flg = PETSC_FALSE,inXisinB=PETSC_FALSE,guess_zero;
803:   Mat            mat,pmat;
804:   MPI_Comm       comm;
805:   MatNullSpace   nullsp;
806:   Vec            btmp,vec_rhs=NULL;

809:   comm = PetscObjectComm((PetscObject)ksp);
810:   if (x && x == b) {
811:     if (!ksp->guess_zero) SETERRQ(comm,PETSC_ERR_ARG_INCOMP,"Cannot use x == b with nonzero initial guess");
812:     VecDuplicate(b,&x);
813:     inXisinB = PETSC_TRUE;
814:   }
815:   if (b) {
816:     PetscObjectReference((PetscObject)b);
817:     VecDestroy(&ksp->vec_rhs);
818:     ksp->vec_rhs = b;
819:   }
820:   if (x) {
821:     PetscObjectReference((PetscObject)x);
822:     VecDestroy(&ksp->vec_sol);
823:     ksp->vec_sol = x;
824:   }

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

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

830:   /* reset the residual history list if requested */
831:   if (ksp->res_hist_reset) ksp->res_hist_len = 0;
832:   if (ksp->err_hist_reset) ksp->err_hist_len = 0;

834:   if (ksp->guess) {
835:     PetscObjectState ostate,state;

837:     KSPGuessSetUp(ksp->guess);
838:     PetscObjectStateGet((PetscObject)ksp->vec_sol,&ostate);
839:     KSPGuessFormGuess(ksp->guess,ksp->vec_rhs,ksp->vec_sol);
840:     PetscObjectStateGet((PetscObject)ksp->vec_sol,&state);
841:     if (state != ostate) {
842:       ksp->guess_zero = PETSC_FALSE;
843:     } else {
844:       PetscInfo(ksp,"Using zero initial guess since the KSPGuess object did not change the vector\n");
845:       ksp->guess_zero = PETSC_TRUE;
846:     }
847:   }

849:   /* KSPSetUp() scales the matrix if needed */
850:   KSPSetUp(ksp);
851:   KSPSetUpOnBlocks(ksp);

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

855:   PetscLogEventBegin(KSP_Solve,ksp,ksp->vec_rhs,ksp->vec_sol,0);
856:   PCGetOperators(ksp->pc,&mat,&pmat);
857:   /* diagonal scale RHS if called for */
858:   if (ksp->dscale) {
859:     VecPointwiseMult(ksp->vec_rhs,ksp->vec_rhs,ksp->diagonal);
860:     /* second time in, but matrix was scaled back to original */
861:     if (ksp->dscalefix && ksp->dscalefix2) {
862:       Mat mat,pmat;

864:       PCGetOperators(ksp->pc,&mat,&pmat);
865:       MatDiagonalScale(pmat,ksp->diagonal,ksp->diagonal);
866:       if (mat != pmat) {MatDiagonalScale(mat,ksp->diagonal,ksp->diagonal);}
867:     }

869:     /* scale initial guess */
870:     if (!ksp->guess_zero) {
871:       if (!ksp->truediagonal) {
872:         VecDuplicate(ksp->diagonal,&ksp->truediagonal);
873:         VecCopy(ksp->diagonal,ksp->truediagonal);
874:         VecReciprocal(ksp->truediagonal);
875:       }
876:       VecPointwiseMult(ksp->vec_sol,ksp->vec_sol,ksp->truediagonal);
877:     }
878:   }
879:   PCPreSolve(ksp->pc,ksp);

881:   if (ksp->guess_zero) { VecSet(ksp->vec_sol,0.0);}
882:   if (ksp->guess_knoll) { /* The Knoll trick is independent on the KSPGuess specified */
883:     PCApply(ksp->pc,ksp->vec_rhs,ksp->vec_sol);
884:     KSP_RemoveNullSpace(ksp,ksp->vec_sol);
885:     ksp->guess_zero = PETSC_FALSE;
886:   }

888:   /* can we mark the initial guess as zero for this solve? */
889:   guess_zero = ksp->guess_zero;
890:   if (!ksp->guess_zero) {
891:     PetscReal norm;

893:     VecNormAvailable(ksp->vec_sol,NORM_2,&flg,&norm);
894:     if (flg && !norm) ksp->guess_zero = PETSC_TRUE;
895:   }
896:   if (ksp->transpose_solve) {
897:     MatGetNullSpace(pmat,&nullsp);
898:   } else {
899:     MatGetTransposeNullSpace(pmat,&nullsp);
900:   }
901:   if (nullsp) {
902:     VecDuplicate(ksp->vec_rhs,&btmp);
903:     VecCopy(ksp->vec_rhs,btmp);
904:     MatNullSpaceRemove(nullsp,btmp);
905:     vec_rhs      = ksp->vec_rhs;
906:     ksp->vec_rhs = btmp;
907:   }
908:   VecLockReadPush(ksp->vec_rhs);
909:   if (ksp->reason == KSP_DIVERGED_PC_FAILED) {
910:     VecSetInf(ksp->vec_sol);
911:   }
912:   (*ksp->ops->solve)(ksp);
913:   KSPMonitorPauseFinal_Internal(ksp);

915:   VecLockReadPop(ksp->vec_rhs);
916:   if (nullsp) {
917:     ksp->vec_rhs = vec_rhs;
918:     VecDestroy(&btmp);
919:   }

921:   ksp->guess_zero = guess_zero;

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

926:   KSPConvergedReasonViewFromOptions(ksp);

928:   if (ksp->viewRate) {
929:     PetscViewerPushFormat(ksp->viewerRate,ksp->formatRate);
930:     KSPConvergedRateView(ksp, ksp->viewerRate);
931:     PetscViewerPopFormat(ksp->viewerRate);
932:   }
933:   PCPostSolve(ksp->pc,ksp);

935:   /* diagonal scale solution if called for */
936:   if (ksp->dscale) {
937:     VecPointwiseMult(ksp->vec_sol,ksp->vec_sol,ksp->diagonal);
938:     /* unscale right hand side and matrix */
939:     if (ksp->dscalefix) {
940:       Mat mat,pmat;

942:       VecReciprocal(ksp->diagonal);
943:       VecPointwiseMult(ksp->vec_rhs,ksp->vec_rhs,ksp->diagonal);
944:       PCGetOperators(ksp->pc,&mat,&pmat);
945:       MatDiagonalScale(pmat,ksp->diagonal,ksp->diagonal);
946:       if (mat != pmat) {MatDiagonalScale(mat,ksp->diagonal,ksp->diagonal);}
947:       VecReciprocal(ksp->diagonal);
948:       ksp->dscalefix2 = PETSC_TRUE;
949:     }
950:   }
951:   PetscLogEventEnd(KSP_Solve,ksp,ksp->vec_rhs,ksp->vec_sol,0);
952:   if (ksp->guess) {
953:     KSPGuessUpdate(ksp->guess,ksp->vec_rhs,ksp->vec_sol);
954:   }
955:   if (ksp->postsolve) {
956:     (*ksp->postsolve)(ksp,ksp->vec_rhs,ksp->vec_sol,ksp->postctx);
957:   }

959:   PCGetOperators(ksp->pc,&mat,&pmat);
960:   if (ksp->viewEV)       {KSPViewEigenvalues_Internal(ksp, PETSC_FALSE, ksp->viewerEV,    ksp->formatEV);}
961:   if (ksp->viewEVExp)    {KSPViewEigenvalues_Internal(ksp, PETSC_TRUE,  ksp->viewerEVExp, ksp->formatEVExp);}
962:   if (ksp->viewSV)       {KSPViewSingularvalues_Internal(ksp, ksp->viewerSV, ksp->formatSV);}
963:   if (ksp->viewFinalRes) {KSPViewFinalResidual_Internal(ksp, ksp->viewerFinalRes, ksp->formatFinalRes);}
964:   if (ksp->viewMat)      {ObjectView((PetscObject) mat,           ksp->viewerMat,    ksp->formatMat);}
965:   if (ksp->viewPMat)     {ObjectView((PetscObject) pmat,          ksp->viewerPMat,   ksp->formatPMat);}
966:   if (ksp->viewRhs)      {ObjectView((PetscObject) ksp->vec_rhs,  ksp->viewerRhs,    ksp->formatRhs);}
967:   if (ksp->viewSol)      {ObjectView((PetscObject) ksp->vec_sol,  ksp->viewerSol,    ksp->formatSol);}
968:   if (ksp->view)         {ObjectView((PetscObject) ksp,           ksp->viewer,       ksp->format);}
969:   if (ksp->viewDScale)   {ObjectView((PetscObject) ksp->diagonal, ksp->viewerDScale, ksp->formatDScale);}
970:   if (ksp->viewMatExp)   {
971:     Mat A, B;

973:     PCGetOperators(ksp->pc, &A, NULL);
974:     if (ksp->transpose_solve) {
975:       Mat AT;

977:       MatCreateTranspose(A, &AT);
978:       MatComputeOperator(AT, MATAIJ, &B);
979:       MatDestroy(&AT);
980:     } else {
981:       MatComputeOperator(A, MATAIJ, &B);
982:     }
983:     ObjectView((PetscObject) B, ksp->viewerMatExp, ksp->formatMatExp);
984:     MatDestroy(&B);
985:   }
986:   if (ksp->viewPOpExp)   {
987:     Mat B;

989:     KSPComputeOperator(ksp, MATAIJ, &B);
990:     ObjectView((PetscObject) B, ksp->viewerPOpExp, ksp->formatPOpExp);
991:     MatDestroy(&B);
992:   }

994:   if (inXisinB) {
995:     VecCopy(x,b);
996:     VecDestroy(&x);
997:   }
998:   PetscObjectSAWsBlock((PetscObject)ksp);
999:   if (ksp->errorifnotconverged && ksp->reason < 0 && ksp->reason != KSP_DIVERGED_ITS) {
1000:     if (ksp->reason == KSP_DIVERGED_PC_FAILED) {
1001:       PCFailedReason reason;
1002:       PCGetFailedReason(ksp->pc,&reason);
1003:       SETERRQ2(comm,PETSC_ERR_NOT_CONVERGED,"KSPSolve has not converged, reason %s PC failed due to %s",KSPConvergedReasons[ksp->reason],PCFailedReasons[reason]);
1004:     } else SETERRQ1(comm,PETSC_ERR_NOT_CONVERGED,"KSPSolve has not converged, reason %s",KSPConvergedReasons[ksp->reason]);
1005:   }
1006:   return(0);
1007: }

1009: /*@
1010:    KSPSolve - Solves linear system.

1012:    Collective on ksp

1014:    Parameters:
1015: +  ksp - iterative context obtained from KSPCreate()
1016: .  b - the right hand side vector
1017: -  x - the solution (this may be the same vector as b, then b will be overwritten with answer)

1019:    Options Database Keys:
1020: +  -ksp_view_eigenvalues - compute preconditioned operators eigenvalues
1021: .  -ksp_view_eigenvalues_explicit - compute the eigenvalues by forming the dense operator and using LAPACK
1022: .  -ksp_view_mat binary - save matrix to the default binary viewer
1023: .  -ksp_view_pmat binary - save matrix used to build preconditioner to the default binary viewer
1024: .  -ksp_view_rhs binary - save right hand side vector to the default binary viewer
1025: .  -ksp_view_solution binary - save computed solution vector to the default binary viewer
1026:            (can be read later with src/ksp/tutorials/ex10.c for testing solvers)
1027: .  -ksp_view_mat_explicit - for matrix-free operators, computes the matrix entries and views them
1028: .  -ksp_view_preconditioned_operator_explicit - computes the product of the preconditioner and matrix as an explicit matrix and views it
1029: .  -ksp_converged_reason - print reason for converged or diverged, also prints number of iterations
1030: .  -ksp_view_final_residual - print 2-norm of true linear system residual at the end of the solution process
1031: -  -ksp_view - print the ksp data structure at the end of the system solution

1033:    Notes:

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

1037:    The operator is specified with KSPSetOperators().

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

1042:    If you provide a matrix that has a MatSetNullSpace() and MatSetTransposeNullSpace() this will use that information to solve singular systems
1043:    in the least squares sense with a norm minimizing solution.
1044: $
1045: $                   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()
1046: $
1047: $    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
1048: $    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
1049: $    direction thus the solution which is a linear combination of the search directions has no component in the nullspace(A).
1050: $
1051: $    We recommend always using GMRES for such singular systems.
1052: $    If nullspace(A) = nullspace(A') (note symmetric matrices always satisfy this property) then both left and right preconditioning will work
1053: $    If nullspace(A) != nullspace(A') then left preconditioning will work but right preconditioning may not work (or it may).

1055:    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
1056:        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
1057:        such as diagonal scaling we cannot apply the inverse of the preconditioner to a vector and thus cannot compute the nullspace(AB).


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

1065:    Understanding Convergence:
1066:    The routines KSPMonitorSet(), KSPComputeEigenvalues(), and
1067:    KSPComputeEigenvaluesExplicitly() provide information on additional
1068:    options to monitor convergence and print eigenvalue information.

1070:    Level: beginner

1072: .seealso: KSPCreate(), KSPSetUp(), KSPDestroy(), KSPSetTolerances(), KSPConvergedDefault(),
1073:           KSPSolveTranspose(), KSPGetIterationNumber(), MatNullSpaceCreate(), MatSetNullSpace(), MatSetTransposeNullSpace(), KSP,
1074:           KSPConvergedReasonView()
1075: @*/
1076: PetscErrorCode KSPSolve(KSP ksp,Vec b,Vec x)
1077: {

1084:   ksp->transpose_solve = PETSC_FALSE;
1085:   KSPSolve_Private(ksp,b,x);
1086:   return(0);
1087: }

1089: /*@
1090:    KSPSolveTranspose - Solves the transpose of a linear system.

1092:    Collective on ksp

1094:    Input Parameters:
1095: +  ksp - iterative context obtained from KSPCreate()
1096: .  b - right hand side vector
1097: -  x - solution vector

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

1102:    Developer Notes:
1103:     We need to implement a KSPSolveHermitianTranspose()

1105:    Level: developer

1107: .seealso: KSPCreate(), KSPSetUp(), KSPDestroy(), KSPSetTolerances(), KSPConvergedDefault(),
1108:           KSPSolve(), KSP
1109: @*/
1110: PetscErrorCode KSPSolveTranspose(KSP ksp,Vec b,Vec x)
1111: {

1118:   if (ksp->transpose.use_explicittranspose) {
1119:     Mat J,Jpre;
1120:     KSPGetOperators(ksp,&J,&Jpre);
1121:     if (!ksp->transpose.reuse_transpose) {
1122:       MatTranspose(J,MAT_INITIAL_MATRIX,&ksp->transpose.AT);
1123:       if (J != Jpre) {
1124:         MatTranspose(Jpre,MAT_INITIAL_MATRIX,&ksp->transpose.BT);
1125:       }
1126:       ksp->transpose.reuse_transpose = PETSC_TRUE;
1127:     } else {
1128:       MatTranspose(J,MAT_REUSE_MATRIX,&ksp->transpose.AT);
1129:       if (J != Jpre) {
1130:         MatTranspose(Jpre,MAT_REUSE_MATRIX,&ksp->transpose.BT);
1131:       }
1132:     }
1133:     if (J == Jpre && ksp->transpose.BT != ksp->transpose.AT) {
1134:       PetscObjectReference((PetscObject)ksp->transpose.AT);
1135:       ksp->transpose.BT = ksp->transpose.AT;
1136:     }
1137:     KSPSetOperators(ksp,ksp->transpose.AT,ksp->transpose.BT);
1138:   } else {
1139:     ksp->transpose_solve = PETSC_TRUE;
1140:   }
1141:   KSPSolve_Private(ksp,b,x);
1142:   return(0);
1143: }

1145: static PetscErrorCode KSPViewFinalMatResidual_Internal(KSP ksp, Mat B, Mat X, PetscViewer viewer, PetscViewerFormat format, PetscInt shift)
1146: {
1147:   Mat            A, R;
1148:   PetscReal      *norms;
1149:   PetscInt       i, N;
1150:   PetscBool      flg;

1154:   PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &flg);
1155:   if (flg) {
1156:     PCGetOperators(ksp->pc, &A, NULL);
1157:     MatMatMult(A, X, MAT_INITIAL_MATRIX, PETSC_DEFAULT, &R);
1158:     MatAYPX(R, -1.0, B, SAME_NONZERO_PATTERN);
1159:     MatGetSize(R, NULL, &N);
1160:     PetscMalloc1(N, &norms);
1161:     MatGetColumnNorms(R, NORM_2, norms);
1162:     MatDestroy(&R);
1163:     for (i = 0; i < N; ++i) {
1164:       PetscViewerASCIIPrintf(viewer, "%s #%D %g\n", i == 0 ? "KSP final norm of residual" : "                          ", shift + i, (double)norms[i]);
1165:     }
1166:     PetscFree(norms);
1167:   }
1168:   return(0);
1169: }

1171: /*@
1172:      KSPMatSolve - Solves a linear system with multiple right-hand sides stored as a MATDENSE. Unlike KSPSolve(), B and X must be different matrices.

1174:    Input Parameters:
1175: +     ksp - iterative context
1176: -     B - block of right-hand sides

1178:    Output Parameter:
1179: .     X - block of solutions

1181:    Notes:
1182:      This is a stripped-down version of KSPSolve(), which only handles -ksp_view, -ksp_converged_reason, and -ksp_view_final_residual.

1184:    Level: intermediate

1186: .seealso:  KSPSolve(), MatMatSolve(), MATDENSE, KSPHPDDM, PCBJACOBI, PCASM
1187: @*/
1188: PetscErrorCode KSPMatSolve(KSP ksp, Mat B, Mat X)
1189: {
1190:   Mat            A, vB, vX;
1191:   Vec            cb, cx;
1192:   PetscInt       m1, M1, m2, M2, n1, N1, n2, N2, Bbn = PETSC_DECIDE;
1193:   PetscBool      match;

1202:   if (!B->assembled) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
1203:   MatCheckPreallocated(X, 3);
1204:   if (!X->assembled) {
1205:     MatSetOption(X, MAT_NO_OFF_PROC_ENTRIES, PETSC_TRUE);
1206:     MatAssemblyBegin(X, MAT_FINAL_ASSEMBLY);
1207:     MatAssemblyEnd(X, MAT_FINAL_ASSEMBLY);
1208:   }
1209:   if (B == X) SETERRQ(PetscObjectComm((PetscObject)ksp), PETSC_ERR_ARG_IDN, "B and X must be different matrices");
1210:   KSPGetOperators(ksp, &A, NULL);
1211:   MatGetLocalSize(A, &m1, NULL);
1212:   MatGetLocalSize(B, &m2, &n2);
1213:   MatGetSize(A, &M1, NULL);
1214:   MatGetSize(B, &M2, &N2);
1215:   if (m1 != m2 || M1 != M2) SETERRQ4(PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Cannot use a block of right-hand sides with (m2,M2) = (%D,%D) for a linear system with (m1,M1) = (%D,%D)", m2, M2, m1, M1);
1216:   MatGetLocalSize(X, &m1, &n1);
1217:   MatGetSize(X, &M1, &N1);
1218:   if (m1 != m2 || M1 != M2 || n1 != n2 || N1 != N2) SETERRQ8(PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Incompatible block of right-hand sides (m2,M2)x(n2,N2) = (%D,%D)x(%D,%D) and solutions (m1,M1)x(n1,N1) = (%D,%D)x(%D,%D)", m2, M2, n2, N2, m1, M1, n1, N1);
1219:   PetscObjectBaseTypeCompareAny((PetscObject)B, &match, MATSEQDENSE, MATMPIDENSE, "");
1220:   if (!match) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Provided block of right-hand sides not stored in a dense Mat");
1221:   PetscObjectBaseTypeCompareAny((PetscObject)X, &match, MATSEQDENSE, MATMPIDENSE, "");
1222:   if (!match) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Provided block of solutions not stored in a dense Mat");
1223:   KSPSetUp(ksp);
1224:   KSPSetUpOnBlocks(ksp);
1225:   if (ksp->ops->matsolve) {
1226:     if (ksp->guess_zero) {
1227:       MatZeroEntries(X);
1228:     }
1229:     PetscLogEventBegin(KSP_MatSolve, ksp, B, X, 0);
1230:     KSPGetMatSolveBatchSize(ksp, &Bbn);
1231:     /* by default, do a single solve with all columns */
1232:     if (Bbn == PETSC_DECIDE) Bbn = N2;
1233:     else if (Bbn < 1) SETERRQ1(PetscObjectComm((PetscObject)ksp), PETSC_ERR_ARG_OUTOFRANGE, "KSPMatSolve() block size %D must be positive", Bbn);
1234:     PetscInfo2(ksp, "KSP type %s solving using blocks of width at most %D\n", ((PetscObject)ksp)->type_name, Bbn);
1235:     /* if -ksp_matsolve_batch_size is greater than the actual number of columns, do a single solve with all columns */
1236:     if (Bbn >= N2) {
1237:       (*ksp->ops->matsolve)(ksp, B, X);
1238:       if (ksp->viewFinalRes) {
1239:         KSPViewFinalMatResidual_Internal(ksp, B, X, ksp->viewerFinalRes, ksp->formatFinalRes, 0);
1240:       }

1242:       KSPConvergedReasonViewFromOptions(ksp);

1244:       if (ksp->viewRate) {
1245:         PetscViewerPushFormat(ksp->viewerRate,PETSC_VIEWER_DEFAULT);
1246:         KSPConvergedRateView(ksp, ksp->viewerRate);
1247:         PetscViewerPopFormat(ksp->viewerRate);
1248:       }
1249:     } else {
1250:       for (n2 = 0; n2 < N2; n2 += Bbn) {
1251:         MatDenseGetSubMatrix(B, n2, PetscMin(n2+Bbn, N2), &vB);
1252:         MatDenseGetSubMatrix(X, n2, PetscMin(n2+Bbn, N2), &vX);
1253:         (*ksp->ops->matsolve)(ksp, vB, vX);
1254:         if (ksp->viewFinalRes) {
1255:           KSPViewFinalMatResidual_Internal(ksp, vB, vX, ksp->viewerFinalRes, ksp->formatFinalRes, n2);
1256:         }

1258:         KSPConvergedReasonViewFromOptions(ksp);

1260:         if (ksp->viewRate) {
1261:           PetscViewerPushFormat(ksp->viewerRate,PETSC_VIEWER_DEFAULT);
1262:           KSPConvergedRateView(ksp, ksp->viewerRate);
1263:           PetscViewerPopFormat(ksp->viewerRate);
1264:         }
1265:         MatDenseRestoreSubMatrix(B, &vB);
1266:         MatDenseRestoreSubMatrix(X, &vX);
1267:       }
1268:     }
1269:     if (ksp->view) {
1270:       KSPView(ksp, ksp->viewer);
1271:     }
1272:     PetscLogEventEnd(KSP_MatSolve, ksp, B, X, 0);
1273:   } else {
1274:     PetscInfo1(ksp, "KSP type %s solving column by column\n", ((PetscObject)ksp)->type_name);
1275:     for (n2 = 0; n2 < N2; ++n2) {
1276:       MatDenseGetColumnVecRead(B, n2, &cb);
1277:       MatDenseGetColumnVecWrite(X, n2, &cx);
1278:       KSPSolve(ksp, cb, cx);
1279:       MatDenseRestoreColumnVecWrite(X, n2, &cx);
1280:       MatDenseRestoreColumnVecRead(B, n2, &cb);
1281:     }
1282:   }
1283:   return(0);
1284: }

1286: /*@
1287:      KSPSetMatSolveBatchSize - Sets the maximum number of columns treated simultaneously in KSPMatSolve().

1289:     Logically collective

1291:    Input Parameters:
1292: +     ksp - iterative context
1293: -     bs - block size

1295:    Level: advanced

1297: .seealso:  KSPMatSolve(), KSPGetMatSolveBatchSize(), -mat_mumps_icntl_27, -matmatmult_Bbn
1298: @*/
1299: PetscErrorCode KSPSetMatSolveBatchSize(KSP ksp, PetscInt bs)
1300: {
1304:   ksp->nmax = bs;
1305:   return(0);
1306: }

1308: /*@
1309:      KSPGetMatSolveBatchSize - Gets the maximum number of columns treated simultaneously in KSPMatSolve().

1311:    Input Parameter:
1312: .     ksp - iterative context

1314:    Output Parameter:
1315: .     bs - block size

1317:    Level: advanced

1319: .seealso:  KSPMatSolve(), KSPSetMatSolveBatchSize(), -mat_mumps_icntl_27, -matmatmult_Bbn
1320: @*/
1321: PetscErrorCode KSPGetMatSolveBatchSize(KSP ksp, PetscInt *bs)
1322: {
1326:   *bs = ksp->nmax;
1327:   return(0);
1328: }

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

1333:    Collective on ksp

1335:    Input Parameter:
1336: .  ksp - iterative context obtained from KSPCreate()

1338:    Level: beginner

1340: .seealso: KSPCreate(), KSPSetUp(), KSPSolve(), KSPSetFromOptions(), KSP
1341: @*/
1342: PetscErrorCode  KSPResetViewers(KSP ksp)
1343: {

1348:   if (!ksp) return(0);
1349:   PetscViewerDestroy(&ksp->viewer);
1350:   PetscViewerDestroy(&ksp->viewerPre);
1351:   PetscViewerDestroy(&ksp->viewerRate);
1352:   PetscViewerDestroy(&ksp->viewerMat);
1353:   PetscViewerDestroy(&ksp->viewerPMat);
1354:   PetscViewerDestroy(&ksp->viewerRhs);
1355:   PetscViewerDestroy(&ksp->viewerSol);
1356:   PetscViewerDestroy(&ksp->viewerMatExp);
1357:   PetscViewerDestroy(&ksp->viewerEV);
1358:   PetscViewerDestroy(&ksp->viewerSV);
1359:   PetscViewerDestroy(&ksp->viewerEVExp);
1360:   PetscViewerDestroy(&ksp->viewerFinalRes);
1361:   PetscViewerDestroy(&ksp->viewerPOpExp);
1362:   PetscViewerDestroy(&ksp->viewerDScale);
1363:   ksp->view         = PETSC_FALSE;
1364:   ksp->viewPre      = PETSC_FALSE;
1365:   ksp->viewMat      = PETSC_FALSE;
1366:   ksp->viewPMat     = PETSC_FALSE;
1367:   ksp->viewRhs      = PETSC_FALSE;
1368:   ksp->viewSol      = PETSC_FALSE;
1369:   ksp->viewMatExp   = PETSC_FALSE;
1370:   ksp->viewEV       = PETSC_FALSE;
1371:   ksp->viewSV       = PETSC_FALSE;
1372:   ksp->viewEVExp    = PETSC_FALSE;
1373:   ksp->viewFinalRes = PETSC_FALSE;
1374:   ksp->viewPOpExp   = PETSC_FALSE;
1375:   ksp->viewDScale   = PETSC_FALSE;
1376:   return(0);
1377: }

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

1382:    Collective on ksp

1384:    Input Parameter:
1385: .  ksp - iterative context obtained from KSPCreate()

1387:    Level: beginner

1389: .seealso: KSPCreate(), KSPSetUp(), KSPSolve(), KSP
1390: @*/
1391: PetscErrorCode  KSPReset(KSP ksp)
1392: {

1397:   if (!ksp) return(0);
1398:   if (ksp->ops->reset) {
1399:     (*ksp->ops->reset)(ksp);
1400:   }
1401:   if (ksp->pc) {PCReset(ksp->pc);}
1402:   if (ksp->guess) {
1403:     KSPGuess guess = ksp->guess;
1404:     if (guess->ops->reset) { (*guess->ops->reset)(guess); }
1405:   }
1406:   VecDestroyVecs(ksp->nwork,&ksp->work);
1407:   VecDestroy(&ksp->vec_rhs);
1408:   VecDestroy(&ksp->vec_sol);
1409:   VecDestroy(&ksp->diagonal);
1410:   VecDestroy(&ksp->truediagonal);

1412:   KSPResetViewers(ksp);

1414:   ksp->setupstage = KSP_SETUP_NEW;
1415:   ksp->nmax = PETSC_DECIDE;
1416:   return(0);
1417: }

1419: /*@C
1420:    KSPDestroy - Destroys KSP context.

1422:    Collective on ksp

1424:    Input Parameter:
1425: .  ksp - iterative context obtained from KSPCreate()

1427:    Level: beginner

1429: .seealso: KSPCreate(), KSPSetUp(), KSPSolve(), KSP
1430: @*/
1431: PetscErrorCode  KSPDestroy(KSP *ksp)
1432: {
1434:   PC             pc;

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

1441:   PetscObjectSAWsViewOff((PetscObject)*ksp);

1443:   /*
1444:    Avoid a cascading call to PCReset(ksp->pc) from the following call:
1445:    PCReset() shouldn't be called from KSPDestroy() as it is unprotected by pc's
1446:    refcount (and may be shared, e.g., by other ksps).
1447:    */
1448:   pc         = (*ksp)->pc;
1449:   (*ksp)->pc = NULL;
1450:   KSPReset((*ksp));
1451:   (*ksp)->pc = pc;
1452:   if ((*ksp)->ops->destroy) {(*(*ksp)->ops->destroy)(*ksp);}

1454:   if ((*ksp)->transpose.use_explicittranspose) {
1455:     MatDestroy(&(*ksp)->transpose.AT);
1456:     MatDestroy(&(*ksp)->transpose.BT);
1457:     (*ksp)->transpose.reuse_transpose = PETSC_FALSE;
1458:   }

1460:   KSPGuessDestroy(&(*ksp)->guess);
1461:   DMDestroy(&(*ksp)->dm);
1462:   PCDestroy(&(*ksp)->pc);
1463:   PetscFree((*ksp)->res_hist_alloc);
1464:   PetscFree((*ksp)->err_hist_alloc);
1465:   if ((*ksp)->convergeddestroy) {
1466:     (*(*ksp)->convergeddestroy)((*ksp)->cnvP);
1467:   }
1468:   KSPMonitorCancel((*ksp));
1469:   KSPConvergedReasonViewCancel((*ksp));
1470:   PetscViewerDestroy(&(*ksp)->eigviewer);
1471:   PetscHeaderDestroy(ksp);
1472:   return(0);
1473: }

1475: /*@
1476:     KSPSetPCSide - Sets the preconditioning side.

1478:     Logically Collective on ksp

1480:     Input Parameter:
1481: .   ksp - iterative context obtained from KSPCreate()

1483:     Output Parameter:
1484: .   side - the preconditioning side, where side is one of
1485: .vb
1486:       PC_LEFT - left preconditioning (default)
1487:       PC_RIGHT - right preconditioning
1488:       PC_SYMMETRIC - symmetric preconditioning
1489: .ve

1491:     Options Database Keys:
1492: .   -ksp_pc_side <right,left,symmetric>

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

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

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

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

1505:     Level: intermediate

1507: .seealso: KSPGetPCSide(), KSPSetNormType(), KSPGetNormType(), KSP
1508: @*/
1509: PetscErrorCode  KSPSetPCSide(KSP ksp,PCSide side)
1510: {
1514:   ksp->pc_side = ksp->pc_side_set = side;
1515:   return(0);
1516: }

1518: /*@
1519:     KSPGetPCSide - Gets the preconditioning side.

1521:     Not Collective

1523:     Input Parameter:
1524: .   ksp - iterative context obtained from KSPCreate()

1526:     Output Parameter:
1527: .   side - the preconditioning side, where side is one of
1528: .vb
1529:       PC_LEFT - left preconditioning (default)
1530:       PC_RIGHT - right preconditioning
1531:       PC_SYMMETRIC - symmetric preconditioning
1532: .ve

1534:     Level: intermediate

1536: .seealso: KSPSetPCSide(), KSP
1537: @*/
1538: PetscErrorCode  KSPGetPCSide(KSP ksp,PCSide *side)
1539: {

1545:   KSPSetUpNorms_Private(ksp,PETSC_TRUE,&ksp->normtype,&ksp->pc_side);
1546:   *side = ksp->pc_side;
1547:   return(0);
1548: }

1550: /*@
1551:    KSPGetTolerances - Gets the relative, absolute, divergence, and maximum
1552:    iteration tolerances used by the default KSP convergence tests.

1554:    Not Collective

1556:    Input Parameter:
1557: .  ksp - the Krylov subspace context

1559:    Output Parameters:
1560: +  rtol - the relative convergence tolerance
1561: .  abstol - the absolute convergence tolerance
1562: .  dtol - the divergence tolerance
1563: -  maxits - maximum number of iterations

1565:    Notes:
1566:    The user can specify NULL for any parameter that is not needed.

1568:    Level: intermediate

1570:            maximum, iterations

1572: .seealso: KSPSetTolerances(), KSP
1573: @*/
1574: PetscErrorCode  KSPGetTolerances(KSP ksp,PetscReal *rtol,PetscReal *abstol,PetscReal *dtol,PetscInt *maxits)
1575: {
1578:   if (abstol) *abstol = ksp->abstol;
1579:   if (rtol) *rtol = ksp->rtol;
1580:   if (dtol) *dtol = ksp->divtol;
1581:   if (maxits) *maxits = ksp->max_it;
1582:   return(0);
1583: }

1585: /*@
1586:    KSPSetTolerances - Sets the relative, absolute, divergence, and maximum
1587:    iteration tolerances used by the default KSP convergence testers.

1589:    Logically Collective on ksp

1591:    Input Parameters:
1592: +  ksp - the Krylov subspace context
1593: .  rtol - the relative convergence tolerance, relative decrease in the (possibly preconditioned) residual norm
1594: .  abstol - the absolute convergence tolerance   absolute size of the (possibly preconditioned) residual norm
1595: .  dtol - the divergence tolerance,   amount (possibly preconditioned) residual norm can increase before KSPConvergedDefault() concludes that the method is diverging
1596: -  maxits - maximum number of iterations to use

1598:    Options Database Keys:
1599: +  -ksp_atol <abstol> - Sets abstol
1600: .  -ksp_rtol <rtol> - Sets rtol
1601: .  -ksp_divtol <dtol> - Sets dtol
1602: -  -ksp_max_it <maxits> - Sets maxits

1604:    Notes:
1605:    Use PETSC_DEFAULT to retain the default value of any of the tolerances.

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

1610:    Level: intermediate

1612:            convergence, maximum, iterations

1614: .seealso: KSPGetTolerances(), KSPConvergedDefault(), KSPSetConvergenceTest(), KSP
1615: @*/
1616: PetscErrorCode  KSPSetTolerances(KSP ksp,PetscReal rtol,PetscReal abstol,PetscReal dtol,PetscInt maxits)
1617: {

1625:   if (rtol != PETSC_DEFAULT) {
1626:     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);
1627:     ksp->rtol = rtol;
1628:   }
1629:   if (abstol != PETSC_DEFAULT) {
1630:     if (abstol < 0.0) SETERRQ1(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_OUTOFRANGE,"Absolute tolerance %g must be non-negative",(double)abstol);
1631:     ksp->abstol = abstol;
1632:   }
1633:   if (dtol != PETSC_DEFAULT) {
1634:     if (dtol < 0.0) SETERRQ1(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_OUTOFRANGE,"Divergence tolerance %g must be larger than 1.0",(double)dtol);
1635:     ksp->divtol = dtol;
1636:   }
1637:   if (maxits != PETSC_DEFAULT) {
1638:     if (maxits < 0) SETERRQ1(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of iterations %D must be non-negative",maxits);
1639:     ksp->max_it = maxits;
1640:   }
1641:   return(0);
1642: }

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

1649:    Logically Collective on ksp

1651:    Input Parameters:
1652: +  ksp - iterative context obtained from KSPCreate()
1653: -  flg - PETSC_TRUE indicates the guess is non-zero, PETSC_FALSE indicates the guess is zero

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

1658:    Level: beginner

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

1663: .seealso: KSPGetInitialGuessNonzero(), KSPSetGuessType(), KSPGuessType, KSP
1664: @*/
1665: PetscErrorCode  KSPSetInitialGuessNonzero(KSP ksp,PetscBool flg)
1666: {
1670:   ksp->guess_zero = (PetscBool) !(int)flg;
1671:   return(0);
1672: }

1674: /*@
1675:    KSPGetInitialGuessNonzero - Determines whether the KSP solver is using
1676:    a zero initial guess.

1678:    Not Collective

1680:    Input Parameter:
1681: .  ksp - iterative context obtained from KSPCreate()

1683:    Output Parameter:
1684: .  flag - PETSC_TRUE if guess is nonzero, else PETSC_FALSE

1686:    Level: intermediate

1688: .seealso: KSPSetInitialGuessNonzero(), KSP
1689: @*/
1690: PetscErrorCode  KSPGetInitialGuessNonzero(KSP ksp,PetscBool  *flag)
1691: {
1695:   if (ksp->guess_zero) *flag = PETSC_FALSE;
1696:   else *flag = PETSC_TRUE;
1697:   return(0);
1698: }

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

1703:    Logically Collective on ksp

1705:    Input Parameters:
1706: +  ksp - iterative context obtained from KSPCreate()
1707: -  flg - PETSC_TRUE indicates you want the error generated

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

1712:    Level: intermediate

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


1719: .seealso: KSPGetErrorIfNotConverged(), KSP
1720: @*/
1721: PetscErrorCode  KSPSetErrorIfNotConverged(KSP ksp,PetscBool flg)
1722: {
1726:   ksp->errorifnotconverged = flg;
1727:   return(0);
1728: }

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

1733:    Not Collective

1735:    Input Parameter:
1736: .  ksp - iterative context obtained from KSPCreate()

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

1741:    Level: intermediate

1743: .seealso: KSPSetErrorIfNotConverged(), KSP
1744: @*/
1745: PetscErrorCode  KSPGetErrorIfNotConverged(KSP ksp,PetscBool  *flag)
1746: {
1750:   *flag = ksp->errorifnotconverged;
1751:   return(0);
1752: }

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

1757:    Logically Collective on ksp

1759:    Input Parameters:
1760: +  ksp - iterative context obtained from KSPCreate()
1761: -  flg - PETSC_TRUE or PETSC_FALSE

1763:    Level: advanced

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

1767: .seealso: KSPGetInitialGuessKnoll(), KSPSetInitialGuessNonzero(), KSPGetInitialGuessNonzero(), KSP
1768: @*/
1769: PetscErrorCode  KSPSetInitialGuessKnoll(KSP ksp,PetscBool flg)
1770: {
1774:   ksp->guess_knoll = flg;
1775:   return(0);
1776: }

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

1782:    Not Collective

1784:    Input Parameter:
1785: .  ksp - iterative context obtained from KSPCreate()

1787:    Output Parameter:
1788: .  flag - PETSC_TRUE if using Knoll trick, else PETSC_FALSE

1790:    Level: advanced

1792: .seealso: KSPSetInitialGuessKnoll(), KSPSetInitialGuessNonzero(), KSPGetInitialGuessNonzero(), KSP
1793: @*/
1794: PetscErrorCode  KSPGetInitialGuessKnoll(KSP ksp,PetscBool  *flag)
1795: {
1799:   *flag = ksp->guess_knoll;
1800:   return(0);
1801: }

1803: /*@
1804:    KSPGetComputeSingularValues - Gets the flag indicating whether the extreme singular
1805:    values will be calculated via a Lanczos or Arnoldi process as the linear
1806:    system is solved.

1808:    Not Collective

1810:    Input Parameter:
1811: .  ksp - iterative context obtained from KSPCreate()

1813:    Output Parameter:
1814: .  flg - PETSC_TRUE or PETSC_FALSE

1816:    Options Database Key:
1817: .  -ksp_monitor_singular_value - Activates KSPSetComputeSingularValues()

1819:    Notes:
1820:    Currently this option is not valid for all iterative methods.

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

1826:    Level: advanced

1828: .seealso: KSPComputeExtremeSingularValues(), KSPMonitorSingularValue(), KSP
1829: @*/
1830: PetscErrorCode  KSPGetComputeSingularValues(KSP ksp,PetscBool  *flg)
1831: {
1835:   *flg = ksp->calc_sings;
1836:   return(0);
1837: }

1839: /*@
1840:    KSPSetComputeSingularValues - Sets a flag so that the extreme singular
1841:    values will be calculated via a Lanczos or Arnoldi process as the linear
1842:    system is solved.

1844:    Logically Collective on ksp

1846:    Input Parameters:
1847: +  ksp - iterative context obtained from KSPCreate()
1848: -  flg - PETSC_TRUE or PETSC_FALSE

1850:    Options Database Key:
1851: .  -ksp_monitor_singular_value - Activates KSPSetComputeSingularValues()

1853:    Notes:
1854:    Currently this option is not valid for all iterative methods.

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

1860:    Level: advanced

1862: .seealso: KSPComputeExtremeSingularValues(), KSPMonitorSingularValue(), KSP
1863: @*/
1864: PetscErrorCode  KSPSetComputeSingularValues(KSP ksp,PetscBool flg)
1865: {
1869:   ksp->calc_sings = flg;
1870:   return(0);
1871: }

1873: /*@
1874:    KSPGetComputeEigenvalues - Gets the flag indicating that the extreme eigenvalues
1875:    values will be calculated via a Lanczos or Arnoldi process as the linear
1876:    system is solved.

1878:    Not Collective

1880:    Input Parameter:
1881: .  ksp - iterative context obtained from KSPCreate()

1883:    Output Parameter:
1884: .  flg - PETSC_TRUE or PETSC_FALSE

1886:    Notes:
1887:    Currently this option is not valid for all iterative methods.

1889:    Level: advanced

1891: .seealso: KSPComputeEigenvalues(), KSPComputeEigenvaluesExplicitly(), KSP
1892: @*/
1893: PetscErrorCode  KSPGetComputeEigenvalues(KSP ksp,PetscBool  *flg)
1894: {
1898:   *flg = ksp->calc_sings;
1899:   return(0);
1900: }

1902: /*@
1903:    KSPSetComputeEigenvalues - Sets a flag so that the extreme eigenvalues
1904:    values will be calculated via a Lanczos or Arnoldi process as the linear
1905:    system is solved.

1907:    Logically Collective on ksp

1909:    Input Parameters:
1910: +  ksp - iterative context obtained from KSPCreate()
1911: -  flg - PETSC_TRUE or PETSC_FALSE

1913:    Notes:
1914:    Currently this option is not valid for all iterative methods.

1916:    Level: advanced

1918: .seealso: KSPComputeEigenvalues(), KSPComputeEigenvaluesExplicitly(), KSP
1919: @*/
1920: PetscErrorCode  KSPSetComputeEigenvalues(KSP ksp,PetscBool flg)
1921: {
1925:   ksp->calc_sings = flg;
1926:   return(0);
1927: }

1929: /*@
1930:    KSPSetComputeRitz - Sets a flag so that the Ritz or harmonic Ritz pairs
1931:    will be calculated via a Lanczos or Arnoldi process as the linear
1932:    system is solved.

1934:    Logically Collective on ksp

1936:    Input Parameters:
1937: +  ksp - iterative context obtained from KSPCreate()
1938: -  flg - PETSC_TRUE or PETSC_FALSE

1940:    Notes:
1941:    Currently this option is only valid for the GMRES method.

1943:    Level: advanced

1945: .seealso: KSPComputeRitz(), KSP
1946: @*/
1947: PetscErrorCode  KSPSetComputeRitz(KSP ksp, PetscBool flg)
1948: {
1952:   ksp->calc_ritz = flg;
1953:   return(0);
1954: }

1956: /*@
1957:    KSPGetRhs - Gets the right-hand-side vector for the linear system to
1958:    be solved.

1960:    Not Collective

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

1965:    Output Parameter:
1966: .  r - right-hand-side vector

1968:    Level: developer

1970: .seealso: KSPGetSolution(), KSPSolve(), KSP
1971: @*/
1972: PetscErrorCode  KSPGetRhs(KSP ksp,Vec *r)
1973: {
1977:   *r = ksp->vec_rhs;
1978:   return(0);
1979: }

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

1986:    Not Collective

1988:    Input Parameters:
1989: .  ksp - iterative context obtained from KSPCreate()

1991:    Output Parameters:
1992: .  v - solution vector

1994:    Level: developer

1996: .seealso: KSPGetRhs(),  KSPBuildSolution(), KSPSolve(), KSP
1997: @*/
1998: PetscErrorCode  KSPGetSolution(KSP ksp,Vec *v)
1999: {
2003:   *v = ksp->vec_sol;
2004:   return(0);
2005: }

2007: /*@
2008:    KSPSetPC - Sets the preconditioner to be used to calculate the
2009:    application of the preconditioner on a vector.

2011:    Collective on ksp

2013:    Input Parameters:
2014: +  ksp - iterative context obtained from KSPCreate()
2015: -  pc   - the preconditioner object (can be NULL)

2017:    Notes:
2018:    Use KSPGetPC() to retrieve the preconditioner context.

2020:    Level: developer

2022: .seealso: KSPGetPC(), KSP
2023: @*/
2024: PetscErrorCode  KSPSetPC(KSP ksp,PC pc)
2025: {

2030:   if (pc) {
2033:   }
2034:   PetscObjectReference((PetscObject)pc);
2035:   PCDestroy(&ksp->pc);
2036:   ksp->pc = pc;
2037:   PetscLogObjectParent((PetscObject)ksp,(PetscObject)ksp->pc);
2038:   return(0);
2039: }

2041: /*@
2042:    KSPGetPC - Returns a pointer to the preconditioner context
2043:    set with KSPSetPC().

2045:    Not Collective

2047:    Input Parameters:
2048: .  ksp - iterative context obtained from KSPCreate()

2050:    Output Parameter:
2051: .  pc - preconditioner context

2053:    Level: developer

2055: .seealso: KSPSetPC(), KSP
2056: @*/
2057: PetscErrorCode  KSPGetPC(KSP ksp,PC *pc)
2058: {

2064:   if (!ksp->pc) {
2065:     PCCreate(PetscObjectComm((PetscObject)ksp),&ksp->pc);
2066:     PetscObjectIncrementTabLevel((PetscObject)ksp->pc,(PetscObject)ksp,0);
2067:     PetscLogObjectParent((PetscObject)ksp,(PetscObject)ksp->pc);
2068:     PetscObjectSetOptions((PetscObject)ksp->pc,((PetscObject)ksp)->options);
2069:   }
2070:   *pc = ksp->pc;
2071:   return(0);
2072: }

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

2077:    Collective on ksp

2079:    Input Parameters:
2080: +  ksp - iterative context obtained from KSPCreate()
2081: .  it - iteration number
2082: -  rnorm - relative norm of the residual

2084:    Notes:
2085:    This routine is called by the KSP implementations.
2086:    It does not typically need to be called by the user.

2088:    Level: developer

2090: .seealso: KSPMonitorSet()
2091: @*/
2092: PetscErrorCode KSPMonitor(KSP ksp,PetscInt it,PetscReal rnorm)
2093: {
2094:   PetscInt       i, n = ksp->numbermonitors;

2098:   for (i=0; i<n; i++) {
2099:     (*ksp->monitor[i])(ksp,it,rnorm,ksp->monitorcontext[i]);
2100:   }
2101:   return(0);
2102: }

2104: /*@C
2105:    KSPMonitorSet - Sets an ADDITIONAL function to be called at every iteration to monitor
2106:    the residual/error etc.

2108:    Logically Collective on ksp

2110:    Input Parameters:
2111: +  ksp - iterative context obtained from KSPCreate()
2112: .  monitor - pointer to function (if this is NULL, it turns off monitoring
2113: .  mctx    - [optional] context for private data for the
2114:              monitor routine (use NULL if no context is desired)
2115: -  monitordestroy - [optional] routine that frees monitor context
2116:           (may be NULL)

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

2121: +  ksp - iterative context obtained from KSPCreate()
2122: .  it - iteration number
2123: .  rnorm - (estimated) 2-norm of (preconditioned) residual
2124: -  mctx  - optional monitoring context, as set by KSPMonitorSet()

2126:    Options Database Keys:
2127: +    -ksp_monitor               - sets KSPMonitorResidual()
2128: .    -ksp_monitor draw          - sets KSPMonitorResidualDraw() and plots residual
2129: .    -ksp_monitor draw::draw_lg - sets KSPMonitorResidualDrawLG() and plots residual
2130: .    -ksp_monitor_pause_final   - Pauses any graphics when the solve finishes (only works for internal monitors)
2131: .    -ksp_monitor_true_residual - sets KSPMonitorTrueResidual()
2132: .    -ksp_monitor_true_residual draw::draw_lg - sets KSPMonitorTrueResidualDrawLG() and plots residual
2133: .    -ksp_monitor_max           - sets KSPMonitorTrueResidualMax()
2134: .    -ksp_monitor_singular_value - sets KSPMonitorSingularValue()
2135: -    -ksp_monitor_cancel - cancels all monitors that have
2136:                           been hardwired into a code by
2137:                           calls to KSPMonitorSet(), but
2138:                           does not cancel those set via
2139:                           the options database.

2141:    Notes:
2142:    The default is to do nothing.  To print the residual, or preconditioned
2143:    residual if KSPSetNormType(ksp,KSP_NORM_PRECONDITIONED) was called, use
2144:    KSPMonitorResidual() as the monitoring routine, with a ASCII viewer as the
2145:    context.

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

2151:    Fortran Notes:
2152:     Only a single monitor function can be set for each KSP object

2154:    Level: beginner

2156: .seealso: KSPMonitorResidual(), KSPMonitorCancel(), KSP
2157: @*/
2158: PetscErrorCode  KSPMonitorSet(KSP ksp,PetscErrorCode (*monitor)(KSP,PetscInt,PetscReal,void*),void *mctx,PetscErrorCode (*monitordestroy)(void**))
2159: {
2160:   PetscInt       i;
2162:   PetscBool      identical;

2166:   for (i=0; i<ksp->numbermonitors;i++) {
2167:     PetscMonitorCompare((PetscErrorCode (*)(void))monitor,mctx,monitordestroy,(PetscErrorCode (*)(void))ksp->monitor[i],ksp->monitorcontext[i],ksp->monitordestroy[i],&identical);
2168:     if (identical) return(0);
2169:   }
2170:   if (ksp->numbermonitors >= MAXKSPMONITORS) SETERRQ(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_OUTOFRANGE,"Too many KSP monitors set");
2171:   ksp->monitor[ksp->numbermonitors]          = monitor;
2172:   ksp->monitordestroy[ksp->numbermonitors]   = monitordestroy;
2173:   ksp->monitorcontext[ksp->numbermonitors++] = (void*)mctx;
2174:   return(0);
2175: }

2177: /*@
2178:    KSPMonitorCancel - Clears all monitors for a KSP object.

2180:    Logically Collective on ksp

2182:    Input Parameters:
2183: .  ksp - iterative context obtained from KSPCreate()

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

2190:    Level: intermediate

2192: .seealso: KSPMonitorResidual(), KSPMonitorSet(), KSP
2193: @*/
2194: PetscErrorCode  KSPMonitorCancel(KSP ksp)
2195: {
2197:   PetscInt       i;

2201:   for (i=0; i<ksp->numbermonitors; i++) {
2202:     if (ksp->monitordestroy[i]) {
2203:       (*ksp->monitordestroy[i])(&ksp->monitorcontext[i]);
2204:     }
2205:   }
2206:   ksp->numbermonitors = 0;
2207:   return(0);
2208: }

2210: /*@C
2211:    KSPGetMonitorContext - Gets the monitoring context, as set by
2212:    KSPMonitorSet() for the FIRST monitor only.

2214:    Not Collective

2216:    Input Parameter:
2217: .  ksp - iterative context obtained from KSPCreate()

2219:    Output Parameter:
2220: .  ctx - monitoring context

2222:    Level: intermediate

2224: .seealso: KSPMonitorResidual(), KSP
2225: @*/
2226: PetscErrorCode  KSPGetMonitorContext(KSP ksp,void **ctx)
2227: {
2230:   *ctx =      (ksp->monitorcontext[0]);
2231:   return(0);
2232: }

2234: /*@
2235:    KSPSetResidualHistory - Sets the array used to hold the residual history.
2236:    If set, this array will contain the residual norms computed at each
2237:    iteration of the solver.

2239:    Not Collective

2241:    Input Parameters:
2242: +  ksp - iterative context obtained from KSPCreate()
2243: .  a   - array to hold history
2244: .  na  - size of a
2245: -  reset - PETSC_TRUE indicates the history counter is reset to zero
2246:            for each new linear solve

2248:    Level: advanced

2250:    Notes:
2251:    If provided, he array is NOT freed by PETSc so the user needs to keep track of it and destroy once the KSP object is destroyed.
2252:    If 'a' is NULL then space is allocated for the history. If 'na' PETSC_DECIDE or PETSC_DEFAULT then a
2253:    default array of length 10000 is allocated.

2255: .seealso: KSPGetResidualHistory(), KSP

2257: @*/
2258: PetscErrorCode KSPSetResidualHistory(KSP ksp,PetscReal a[],PetscInt na,PetscBool reset)
2259: {


2265:   PetscFree(ksp->res_hist_alloc);
2266:   if (na != PETSC_DECIDE && na != PETSC_DEFAULT && a) {
2267:     ksp->res_hist     = a;
2268:     ksp->res_hist_max = na;
2269:   } else {
2270:     if (na != PETSC_DECIDE && na != PETSC_DEFAULT) ksp->res_hist_max = na;
2271:     else                                           ksp->res_hist_max = 10000; /* like default ksp->max_it */
2272:     PetscCalloc1(ksp->res_hist_max,&ksp->res_hist_alloc);

2274:     ksp->res_hist = ksp->res_hist_alloc;
2275:   }
2276:   ksp->res_hist_len   = 0;
2277:   ksp->res_hist_reset = reset;
2278:   return(0);
2279: }

2281: /*@C
2282:    KSPGetResidualHistory - Gets the array used to hold the residual history
2283:    and the number of residuals it contains.

2285:    Not Collective

2287:    Input Parameter:
2288: .  ksp - iterative context obtained from KSPCreate()

2290:    Output Parameters:
2291: +  a   - pointer to array to hold history (or NULL)
2292: -  na  - number of used entries in a (or NULL)

2294:    Level: advanced

2296:    Notes:
2297:      This array is borrowed and should not be freed by the caller.
2298:      Can only be called after a KSPSetResidualHistory() otherwise a and na are set to zero

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

2306: .seealso: KSPSetResidualHistory(), KSP

2308: @*/
2309: PetscErrorCode KSPGetResidualHistory(KSP ksp, const PetscReal *a[],PetscInt *na)
2310: {
2313:   if (a) *a = ksp->res_hist;
2314:   if (na) *na = ksp->res_hist_len;
2315:   return(0);
2316: }

2318: /*@
2319:   KSPSetErrorHistory - Sets the array used to hold the error history. If set, this array will contain the error norms computed at each iteration of the solver.

2321:   Not Collective

2323:   Input Parameters:
2324: + ksp   - iterative context obtained from KSPCreate()
2325: . a     - array to hold history
2326: . na    - size of a
2327: - reset - PETSC_TRUE indicates the history counter is reset to zero for each new linear solve

2329:   Level: advanced

2331:   Notes:
2332:   If provided, the array is NOT freed by PETSc so the user needs to keep track of it and destroy once the KSP object is destroyed.
2333:   If 'a' is NULL then space is allocated for the history. If 'na' PETSC_DECIDE or PETSC_DEFAULT then a default array of length 10000 is allocated.

2335: .seealso: KSPGetErrorHistory(), KSPSetResidualHistory(), KSP
2336: @*/
2337: PetscErrorCode KSPSetErrorHistory(KSP ksp, PetscReal a[], PetscInt na, PetscBool reset)
2338: {


2344:   PetscFree(ksp->err_hist_alloc);
2345:   if (na != PETSC_DECIDE && na != PETSC_DEFAULT && a) {
2346:     ksp->err_hist     = a;
2347:     ksp->err_hist_max = na;
2348:   } else {
2349:     if (na != PETSC_DECIDE && na != PETSC_DEFAULT) ksp->err_hist_max = na;
2350:     else                                           ksp->err_hist_max = 10000; /* like default ksp->max_it */
2351:     PetscCalloc1(ksp->err_hist_max, &ksp->err_hist_alloc);

2353:     ksp->err_hist = ksp->err_hist_alloc;
2354:   }
2355:   ksp->err_hist_len   = 0;
2356:   ksp->err_hist_reset = reset;
2357:   return(0);
2358: }

2360: /*@C
2361:   KSPGetErrorHistory - Gets the array used to hold the error history and the number of residuals it contains.

2363:   Not Collective

2365:   Input Parameter:
2366: . ksp - iterative context obtained from KSPCreate()

2368:   Output Parameters:
2369: + a  - pointer to array to hold history (or NULL)
2370: - na - number of used entries in a (or NULL)

2372:   Level: advanced

2374:   Notes:
2375:   This array is borrowed and should not be freed by the caller.
2376:   Can only be called after a KSPSetErrorHistory() otherwise a and na are set to zero
2377:   The Fortran version of this routine has a calling sequence
2378: $   call KSPGetErrorHistory(KSP ksp, integer na, integer ierr)
2379:   note that you have passed a Fortran array into KSPSetErrorHistory() and you need
2380:   to access the residual values from this Fortran array you provided. Only the na (number of
2381:   residual norms currently held) is set.

2383: .seealso: KSPSetErrorHistory(), KSPGetResidualHistory(), KSP
2384: @*/
2385: PetscErrorCode KSPGetErrorHistory(KSP ksp, const PetscReal *a[], PetscInt *na)
2386: {
2389:   if (a)  *a  = ksp->err_hist;
2390:   if (na) *na = ksp->err_hist_len;
2391:   return(0);
2392: }

2394: /*
2395:   KSPComputeConvergenceRate - Compute the convergence rate for the iteration

2397:   Not collective

2399:   Input Parameter:
2400: . ksp - The KSP

2402:   Output Parameters:
2403: + cr   - The residual contraction rate
2404: . rRsq - The coefficient of determination, R^2, indicating the linearity of the data
2405: . ce   - The error contraction rate
2406: - eRsq - The coefficient of determination, R^2, indicating the linearity of the data

2408:   Note:
2409:   Suppose that the residual is reduced linearly, $r_k = c^k r_0$, which means $log r_k = log r_0 + k log c$. After linear regression,
2410:   the slope is $\log c$. The coefficient of determination is given by $1 - \frac{\sum_i (y_i - f(x_i))^2}{\sum_i (y_i - \bar y)}$,
2411:   see also https://en.wikipedia.org/wiki/Coefficient_of_determination

2413:   Level: advanced

2415: .seealso: KSPConvergedRateView()
2416: */
2417: PetscErrorCode KSPComputeConvergenceRate(KSP ksp, PetscReal *cr, PetscReal *rRsq, PetscReal *ce, PetscReal *eRsq)
2418: {
2419:   PetscReal      const *hist;
2420:   PetscReal      *x, *y, slope, intercept, mean = 0.0, var = 0.0, res = 0.0;
2421:   PetscInt       n, k;

2425:   if (cr || rRsq) {
2426:     KSPGetResidualHistory(ksp, &hist, &n);
2427:     if (!n) {
2428:       if (cr)   *cr   =  0.0;
2429:       if (rRsq) *rRsq = -1.0;
2430:     } else {
2431:       PetscMalloc2(n, &x, n, &y);
2432:       for (k = 0; k < n; ++k) {
2433:         x[k] = k;
2434:         y[k] = PetscLogReal(hist[k]);
2435:         mean += y[k];
2436:       }
2437:       mean /= n;
2438:       PetscLinearRegression(n, x, y, &slope, &intercept);
2439:       for (k = 0; k < n; ++k) {
2440:         res += PetscSqr(y[k] - (slope*x[k] + intercept));
2441:         var += PetscSqr(y[k] - mean);
2442:       }
2443:       PetscFree2(x, y);
2444:       if (cr)   *cr   = PetscExpReal(slope);
2445:       if (rRsq) *rRsq = var < PETSC_MACHINE_EPSILON ? 0.0 : 1.0 - (res / var);
2446:     }
2447:   }
2448:   if (ce || eRsq) {
2449:     KSPGetErrorHistory(ksp, &hist, &n);
2450:     if (!n) {
2451:       if (ce)   *ce   =  0.0;
2452:       if (eRsq) *eRsq = -1.0;
2453:     } else {
2454:       PetscMalloc2(n, &x, n, &y);
2455:       for (k = 0; k < n; ++k) {
2456:         x[k] = k;
2457:         y[k] = PetscLogReal(hist[k]);
2458:         mean += y[k];
2459:       }
2460:       mean /= n;
2461:       PetscLinearRegression(n, x, y, &slope, &intercept);
2462:       for (k = 0; k < n; ++k) {
2463:         res += PetscSqr(y[k] - (slope*x[k] + intercept));
2464:         var += PetscSqr(y[k] - mean);
2465:       }
2466:       PetscFree2(x, y);
2467:       if (ce)   *ce   = PetscExpReal(slope);
2468:       if (eRsq) *eRsq = var < PETSC_MACHINE_EPSILON ? 0.0 : 1.0 - (res / var);
2469:     }
2470:   }
2471:   return(0);
2472: }

2474: /*@C
2475:    KSPSetConvergenceTest - Sets the function to be used to determine
2476:    convergence.

2478:    Logically Collective on ksp

2480:    Input Parameters:
2481: +  ksp - iterative context obtained from KSPCreate()
2482: .  converge - pointer to the function
2483: .  cctx    - context for private data for the convergence routine (may be null)
2484: -  destroy - a routine for destroying the context (may be null)

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

2489: +  ksp - iterative context obtained from KSPCreate()
2490: .  it - iteration number
2491: .  rnorm - (estimated) 2-norm of (preconditioned) residual
2492: .  reason - the reason why it has converged or diverged
2493: -  cctx  - optional convergence context, as set by KSPSetConvergenceTest()


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

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

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

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

2510:    Level: advanced

2512: .seealso: KSPConvergedDefault(), KSPGetConvergenceContext(), KSPSetTolerances(), KSP, KSPGetConvergenceTest(), KSPGetAndClearConvergenceTest()
2513: @*/
2514: PetscErrorCode  KSPSetConvergenceTest(KSP ksp,PetscErrorCode (*converge)(KSP,PetscInt,PetscReal,KSPConvergedReason*,void*),void *cctx,PetscErrorCode (*destroy)(void*))
2515: {

2520:   if (ksp->convergeddestroy) {
2521:     (*ksp->convergeddestroy)(ksp->cnvP);
2522:   }
2523:   ksp->converged        = converge;
2524:   ksp->convergeddestroy = destroy;
2525:   ksp->cnvP             = (void*)cctx;
2526:   return(0);
2527: }

2529: /*@C
2530:    KSPGetConvergenceTest - Gets the function to be used to determine
2531:    convergence.

2533:    Logically Collective on ksp

2535:    Input Parameter:
2536: .   ksp - iterative context obtained from KSPCreate()

2538:    Output Parameter:
2539: +  converge - pointer to convergence test function
2540: .  cctx    - context for private data for the convergence routine (may be null)
2541: -  destroy - a routine for destroying the context (may be null)

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

2546: +  ksp - iterative context obtained from KSPCreate()
2547: .  it - iteration number
2548: .  rnorm - (estimated) 2-norm of (preconditioned) residual
2549: .  reason - the reason why it has converged or diverged
2550: -  cctx  - optional convergence context, as set by KSPSetConvergenceTest()

2552:    Level: advanced

2554: .seealso: KSPConvergedDefault(), KSPGetConvergenceContext(), KSPSetTolerances(), KSP, KSPSetConvergenceTest(), KSPGetAndClearConvergenceTest()
2555: @*/
2556: PetscErrorCode  KSPGetConvergenceTest(KSP ksp,PetscErrorCode (**converge)(KSP,PetscInt,PetscReal,KSPConvergedReason*,void*),void **cctx,PetscErrorCode (**destroy)(void*))
2557: {
2560:   if (converge) *converge = ksp->converged;
2561:   if (destroy)  *destroy  = ksp->convergeddestroy;
2562:   if (cctx)     *cctx     = ksp->cnvP;
2563:   return(0);
2564: }

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

2569:    Logically Collective on ksp

2571:    Input Parameter:
2572: .   ksp - iterative context obtained from KSPCreate()

2574:    Output Parameter:
2575: +  converge - pointer to convergence test function
2576: .  cctx    - context for private data for the convergence routine
2577: -  destroy - a routine for destroying the context

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

2582: +  ksp - iterative context obtained from KSPCreate()
2583: .  it - iteration number
2584: .  rnorm - (estimated) 2-norm of (preconditioned) residual
2585: .  reason - the reason why it has converged or diverged
2586: -  cctx  - optional convergence context, as set by KSPSetConvergenceTest()

2588:    Level: advanced

2590:    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
2591:           KSPSetConvergenceTest() on this original KSP. If you just called KSPGetConvergenceTest() followed by KSPSetConvergenceTest() the original context information
2592:           would be destroyed and hence the transferred context would be invalid and trigger a crash on use

2594: .seealso: KSPConvergedDefault(), KSPGetConvergenceContext(), KSPSetTolerances(), KSP, KSPSetConvergenceTest(), KSPGetConvergenceTest()
2595: @*/
2596: PetscErrorCode  KSPGetAndClearConvergenceTest(KSP ksp,PetscErrorCode (**converge)(KSP,PetscInt,PetscReal,KSPConvergedReason*,void*),void **cctx,PetscErrorCode (**destroy)(void*))
2597: {
2600:   *converge             = ksp->converged;
2601:   *destroy              = ksp->convergeddestroy;
2602:   *cctx                 = ksp->cnvP;
2603:   ksp->converged        = NULL;
2604:   ksp->cnvP             = NULL;
2605:   ksp->convergeddestroy = NULL;
2606:   return(0);
2607: }

2609: /*@C
2610:    KSPGetConvergenceContext - Gets the convergence context set with
2611:    KSPSetConvergenceTest().

2613:    Not Collective

2615:    Input Parameter:
2616: .  ksp - iterative context obtained from KSPCreate()

2618:    Output Parameter:
2619: .  ctx - monitoring context

2621:    Level: advanced

2623: .seealso: KSPConvergedDefault(), KSPSetConvergenceTest(), KSP
2624: @*/
2625: PetscErrorCode  KSPGetConvergenceContext(KSP ksp,void **ctx)
2626: {
2629:   *ctx = ksp->cnvP;
2630:   return(0);
2631: }

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

2637:    Collective on ksp

2639:    Input Parameter:
2640: .  ctx - iterative context obtained from KSPCreate()

2642:    Output Parameter:
2643:    Provide exactly one of
2644: +  v - location to stash solution.
2645: -  V - the solution is returned in this location. This vector is created
2646:        internally. This vector should NOT be destroyed by the user with
2647:        VecDestroy().

2649:    Notes:
2650:    This routine can be used in one of two ways
2651: .vb
2652:       KSPBuildSolution(ksp,NULL,&V);
2653:    or
2654:       KSPBuildSolution(ksp,v,NULL); or KSPBuildSolution(ksp,v,&v);
2655: .ve
2656:    In the first case an internal vector is allocated to store the solution
2657:    (the user cannot destroy this vector). In the second case the solution
2658:    is generated in the vector that the user provides. Note that for certain
2659:    methods, such as KSPCG, the second case requires a copy of the solution,
2660:    while in the first case the call is essentially free since it simply
2661:    returns the vector where the solution already is stored. For some methods
2662:    like GMRES this is a reasonably expensive operation and should only be
2663:    used in truly needed.

2665:    Level: advanced

2667: .seealso: KSPGetSolution(), KSPBuildResidual(), KSP
2668: @*/
2669: PetscErrorCode  KSPBuildSolution(KSP ksp,Vec v,Vec *V)
2670: {

2675:   if (!V && !v) SETERRQ(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_WRONG,"Must provide either v or V");
2676:   if (!V) V = &v;
2677:   (*ksp->ops->buildsolution)(ksp,v,V);
2678:   return(0);
2679: }

2681: /*@C
2682:    KSPBuildResidual - Builds the residual in a vector provided.

2684:    Collective on ksp

2686:    Input Parameter:
2687: .  ksp - iterative context obtained from KSPCreate()

2689:    Output Parameters:
2690: +  v - optional location to stash residual.  If v is not provided,
2691:        then a location is generated.
2692: .  t - work vector.  If not provided then one is generated.
2693: -  V - the residual

2695:    Notes:
2696:    Regardless of whether or not v is provided, the residual is
2697:    returned in V.

2699:    Level: advanced

2701: .seealso: KSPBuildSolution()
2702: @*/
2703: PetscErrorCode  KSPBuildResidual(KSP ksp,Vec t,Vec v,Vec *V)
2704: {
2706:   PetscBool      flag = PETSC_FALSE;
2707:   Vec            w    = v,tt = t;

2711:   if (!w) {
2712:     VecDuplicate(ksp->vec_rhs,&w);
2713:     PetscLogObjectParent((PetscObject)ksp,(PetscObject)w);
2714:   }
2715:   if (!tt) {
2716:     VecDuplicate(ksp->vec_sol,&tt); flag = PETSC_TRUE;
2717:     PetscLogObjectParent((PetscObject)ksp,(PetscObject)tt);
2718:   }
2719:   (*ksp->ops->buildresidual)(ksp,tt,w,V);
2720:   if (flag) {VecDestroy(&tt);}
2721:   return(0);
2722: }

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

2728:    Logically Collective on ksp

2730:    Input Parameter:
2731: +  ksp - the KSP context
2732: -  scale - PETSC_TRUE or PETSC_FALSE

2734:    Options Database Key:
2735: +   -ksp_diagonal_scale -
2736: -   -ksp_diagonal_scale_fix - scale the matrix back AFTER the solve


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

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

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

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

2754:    Level: intermediate

2756: .seealso: KSPGetDiagonalScale(), KSPSetDiagonalScaleFix(), KSP
2757: @*/
2758: PetscErrorCode  KSPSetDiagonalScale(KSP ksp,PetscBool scale)
2759: {
2763:   ksp->dscale = scale;
2764:   return(0);
2765: }

2767: /*@
2768:    KSPGetDiagonalScale - Checks if KSP solver scales the matrix and
2769:                           right hand side

2771:    Not Collective

2773:    Input Parameter:
2774: .  ksp - the KSP context

2776:    Output Parameter:
2777: .  scale - PETSC_TRUE or PETSC_FALSE

2779:    Notes:
2780:     BE CAREFUL with this routine: it actually scales the matrix and right
2781:     hand side that define the system. After the system is solved the matrix
2782:     and right hand side remain scaled  unless you use KSPSetDiagonalScaleFix()

2784:    Level: intermediate

2786: .seealso: KSPSetDiagonalScale(), KSPSetDiagonalScaleFix(), KSP
2787: @*/
2788: PetscErrorCode  KSPGetDiagonalScale(KSP ksp,PetscBool  *scale)
2789: {
2793:   *scale = ksp->dscale;
2794:   return(0);
2795: }

2797: /*@
2798:    KSPSetDiagonalScaleFix - Tells KSP to diagonally scale the system
2799:      back after solving.

2801:    Logically Collective on ksp

2803:    Input Parameter:
2804: +  ksp - the KSP context
2805: -  fix - PETSC_TRUE to scale back after the system solve, PETSC_FALSE to not
2806:          rescale (default)

2808:    Notes:
2809:      Must be called after KSPSetDiagonalScale()

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

2816:    Level: intermediate

2818: .seealso: KSPGetDiagonalScale(), KSPSetDiagonalScale(), KSPGetDiagonalScaleFix(), KSP
2819: @*/
2820: PetscErrorCode  KSPSetDiagonalScaleFix(KSP ksp,PetscBool fix)
2821: {
2825:   ksp->dscalefix = fix;
2826:   return(0);
2827: }

2829: /*@
2830:    KSPGetDiagonalScaleFix - Determines if KSP diagonally scales the system
2831:      back after solving.

2833:    Not Collective

2835:    Input Parameter:
2836: .  ksp - the KSP context

2838:    Output Parameter:
2839: .  fix - PETSC_TRUE to scale back after the system solve, PETSC_FALSE to not
2840:          rescale (default)

2842:    Notes:
2843:      Must be called after KSPSetDiagonalScale()

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

2850:    Level: intermediate

2852: .seealso: KSPGetDiagonalScale(), KSPSetDiagonalScale(), KSPSetDiagonalScaleFix(), KSP
2853: @*/
2854: PetscErrorCode  KSPGetDiagonalScaleFix(KSP ksp,PetscBool  *fix)
2855: {
2859:   *fix = ksp->dscalefix;
2860:   return(0);
2861: }

2863: /*@C
2864:    KSPSetComputeOperators - set routine to compute the linear operators

2866:    Logically Collective

2868:    Input Arguments:
2869: +  ksp - the KSP context
2870: .  func - function to compute the operators
2871: -  ctx - optional context

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

2876: +  ksp - the KSP context
2877: .  A - the linear operator
2878: .  B - preconditioning matrix
2879: -  ctx - optional user-provided context

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

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

2887:    Level: beginner

2889: .seealso: KSPSetOperators(), KSPSetComputeRHS(), DMKSPSetComputeOperators(), KSPSetComputeInitialGuess()
2890: @*/
2891: PetscErrorCode KSPSetComputeOperators(KSP ksp,PetscErrorCode (*func)(KSP,Mat,Mat,void*),void *ctx)
2892: {
2894:   DM             dm;

2898:   KSPGetDM(ksp,&dm);
2899:   DMKSPSetComputeOperators(dm,func,ctx);
2900:   if (ksp->setupstage == KSP_SETUP_NEWRHS) ksp->setupstage = KSP_SETUP_NEWMATRIX;
2901:   return(0);
2902: }

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

2907:    Logically Collective

2909:    Input Arguments:
2910: +  ksp - the KSP context
2911: .  func - function to compute the right hand side
2912: -  ctx - optional context

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

2917: +  ksp - the KSP context
2918: .  b - right hand side of linear system
2919: -  ctx - optional user-provided context

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

2924:    Level: beginner

2926: .seealso: KSPSolve(), DMKSPSetComputeRHS(), KSPSetComputeOperators()
2927: @*/
2928: PetscErrorCode KSPSetComputeRHS(KSP ksp,PetscErrorCode (*func)(KSP,Vec,void*),void *ctx)
2929: {
2931:   DM             dm;

2935:   KSPGetDM(ksp,&dm);
2936:   DMKSPSetComputeRHS(dm,func,ctx);
2937:   return(0);
2938: }

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

2943:    Logically Collective

2945:    Input Arguments:
2946: +  ksp - the KSP context
2947: .  func - function to compute the initial guess
2948: -  ctx - optional context

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

2953: +  ksp - the KSP context
2954: .  x - solution vector
2955: -  ctx - optional user-provided context

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

2960:    Level: beginner

2962: .seealso: KSPSolve(), KSPSetComputeRHS(), KSPSetComputeOperators(), DMKSPSetComputeInitialGuess()
2963: @*/
2964: PetscErrorCode KSPSetComputeInitialGuess(KSP ksp,PetscErrorCode (*func)(KSP,Vec,void*),void *ctx)
2965: {
2967:   DM             dm;

2971:   KSPGetDM(ksp,&dm);
2972:   DMKSPSetComputeInitialGuess(dm,func,ctx);
2973:   return(0);
2974: }

2976: /*@
2977:    KSPSetUseExplicitTranspose - Determines if transpose the system explicitly
2978:    in KSPSolveTranspose.

2980:    Logically Collective on ksp

2982:    Input Parameter:
2983: .  ksp - the KSP context

2985:    Output Parameter:
2986: .  flg - PETSC_TRUE to transpose the system in KSPSolveTranspose, PETSC_FALSE to not
2987:          transpose (default)

2989:    Level: advanced

2991: .seealso: KSPSolveTranspose(), KSP
2992: @*/
2993: PetscErrorCode KSPSetUseExplicitTranspose(KSP ksp,PetscBool flg)
2994: {
2997:   ksp->transpose.use_explicittranspose = flg;
2998:   return(0);
2999: }