Actual source code: itfunc.c

petsc-master 2019-07-16
Report Typos and Errors

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

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

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

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

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

 23:    Not Collective

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

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

 31:    Options Database Keys:
 32: .  -ksp_compute_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_compute_eigenvalues) in order for this routine to work correctly.

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

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

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

 49:    Level: advanced

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

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

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

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

 76:    Not Collective

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

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

 88:    Options Database Keys:
 89: +  -ksp_compute_eigenvalues - Prints eigenvalues to stdout
 90: -  -ksp_plot_eigenvalues - Plots eigenvalues in an x-window display

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

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

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

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

111:    Level: advanced

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

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

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

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

140:    Not Collective

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

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

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

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

169:    Level: advanced

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

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

188:    Collective on ksp

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

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

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

202:    Level: advanced

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

214:   KSPGetPC(ksp,&pc);
215:   PCSetUpOnBlocks(pc);
216:   PCGetFailedReason(pc,&pcreason);
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:    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

251:    Collective on ksp

253:    Input Parameters:
254: +  ksp   - iterative context obtained from KSPCreate()
255: -  flag - PETSC_TRUE to skip calling the PCSetFromOptions()

257:    Level: intermediate

259: .seealso: KSPCreate(), KSPSolve(), KSPDestroy(), PCSetReusePreconditioner(), KSP
260: @*/
261: PetscErrorCode  KSPSetSkipPCSetFromOptions(KSP ksp,PetscBool flag)
262: {
265:   ksp->skippcsetfromoptions = flag;
266:   return(0);
267: }

269: /*@
270:    KSPSetUp - Sets up the internal data structures for the
271:    later use of an iterative solver.

273:    Collective on ksp

275:    Input Parameter:
276: .  ksp   - iterative context obtained from KSPCreate()

278:    Level: developer

280: .seealso: KSPCreate(), KSPSolve(), KSPDestroy(), KSP
281: @*/
282: PetscErrorCode KSPSetUp(KSP ksp)
283: {
285:   Mat            A,B;
286:   Mat            mat,pmat;
287:   MatNullSpace   nullsp;
288:   PCFailedReason pcreason;
289: 

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

296:   if (!((PetscObject)ksp)->type_name) {
297:     KSPSetType(ksp,KSPGMRES);
298:   }
299:   KSPSetUpNorms_Private(ksp,PETSC_TRUE,&ksp->normtype,&ksp->pc_side);

301:   if (ksp->dmActive && !ksp->setupstage) {
302:     /* first time in so build matrix and vector data structures using DM */
303:     if (!ksp->vec_rhs) {DMCreateGlobalVector(ksp->dm,&ksp->vec_rhs);}
304:     if (!ksp->vec_sol) {DMCreateGlobalVector(ksp->dm,&ksp->vec_sol);}
305:     DMCreateMatrix(ksp->dm,&A);
306:     KSPSetOperators(ksp,A,A);
307:     PetscObjectDereference((PetscObject)A);
308:   }

310:   if (ksp->dmActive) {
311:     DMKSP kdm;
312:     DMGetDMKSP(ksp->dm,&kdm);

314:     if (kdm->ops->computeinitialguess && ksp->setupstage != KSP_SETUP_NEWRHS) {
315:       /* only computes initial guess the first time through */
316:       (*kdm->ops->computeinitialguess)(ksp,ksp->vec_sol,kdm->initialguessctx);
317:       KSPSetInitialGuessNonzero(ksp,PETSC_TRUE);
318:     }
319:     if (kdm->ops->computerhs) {
320:       (*kdm->ops->computerhs)(ksp,ksp->vec_rhs,kdm->rhsctx);
321:     }

323:     if (ksp->setupstage != KSP_SETUP_NEWRHS) {
324:       if (kdm->ops->computeoperators) {
325:         KSPGetOperators(ksp,&A,&B);
326:         (*kdm->ops->computeoperators)(ksp,A,B,kdm->operatorsctx);
327:       } else SETERRQ(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_WRONGSTATE,"You called KSPSetDM() but did not use DMKSPSetComputeOperators() or KSPSetDMActive(ksp,PETSC_FALSE);");
328:     }
329:   }

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

334:   switch (ksp->setupstage) {
335:   case KSP_SETUP_NEW:
336:     (*ksp->ops->setup)(ksp);
337:     break;
338:   case KSP_SETUP_NEWMATRIX: {   /* This should be replaced with a more general mechanism */
339:     if (ksp->setupnewmatrix) {
340:       (*ksp->ops->setup)(ksp);
341:     }
342:   } break;
343:   default: break;
344:   }

346:   if (!ksp->pc) {KSPGetPC(ksp,&ksp->pc);}
347:   PCGetOperators(ksp->pc,&mat,&pmat);
348:   /* scale the matrix if requested */
349:   if (ksp->dscale) {
350:     PetscScalar *xx;
351:     PetscInt    i,n;
352:     PetscBool   zeroflag = PETSC_FALSE;
353:     if (!ksp->pc) {KSPGetPC(ksp,&ksp->pc);}
354:     if (!ksp->diagonal) { /* allocate vector to hold diagonal */
355:       MatCreateVecs(pmat,&ksp->diagonal,0);
356:     }
357:     MatGetDiagonal(pmat,ksp->diagonal);
358:     VecGetLocalSize(ksp->diagonal,&n);
359:     VecGetArray(ksp->diagonal,&xx);
360:     for (i=0; i<n; i++) {
361:       if (xx[i] != 0.0) xx[i] = 1.0/PetscSqrtReal(PetscAbsScalar(xx[i]));
362:       else {
363:         xx[i]    = 1.0;
364:         zeroflag = PETSC_TRUE;
365:       }
366:     }
367:     VecRestoreArray(ksp->diagonal,&xx);
368:     if (zeroflag) {
369:       PetscInfo(ksp,"Zero detected in diagonal of matrix, using 1 at those locations\n");
370:     }
371:     MatDiagonalScale(pmat,ksp->diagonal,ksp->diagonal);
372:     if (mat != pmat) {MatDiagonalScale(mat,ksp->diagonal,ksp->diagonal);}
373:     ksp->dscalefix2 = PETSC_FALSE;
374:   }
375:   PetscLogEventEnd(KSP_SetUp,ksp,ksp->vec_rhs,ksp->vec_sol,0);
376:   PCSetErrorIfFailure(ksp->pc,ksp->errorifnotconverged);
377:   PCSetUp(ksp->pc);
378:   PCGetFailedReason(ksp->pc,&pcreason);
379:   if (pcreason) {
380:     ksp->reason = KSP_DIVERGED_PC_FAILED;
381:   }

383:   MatGetNullSpace(mat,&nullsp);
384:   if (nullsp) {
385:     PetscBool test = PETSC_FALSE;
386:     PetscOptionsGetBool(((PetscObject)ksp)->options,((PetscObject)ksp)->prefix,"-ksp_test_null_space",&test,NULL);
387:     if (test) {
388:       MatNullSpaceTest(nullsp,mat,NULL);
389:     }
390:   }
391:   ksp->setupstage = KSP_SETUP_NEWRHS;
392:   return(0);
393: }

395: static PetscErrorCode KSPReasonView_Internal(KSP ksp, PetscViewer viewer, PetscViewerFormat format)
396: {
398:   PetscBool      isAscii;

401:   if (format != PETSC_VIEWER_DEFAULT) {PetscViewerPushFormat(viewer,format);}
402:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&isAscii);
403:   if (isAscii) {
404:     PetscViewerASCIIAddTab(viewer,((PetscObject)ksp)->tablevel);
405:     if (ksp->reason > 0) {
406:       if (((PetscObject) ksp)->prefix) {
407:         PetscViewerASCIIPrintf(viewer,"Linear %s solve converged due to %s iterations %D\n",((PetscObject) ksp)->prefix,KSPConvergedReasons[ksp->reason],ksp->its);
408:       } else {
409:         PetscViewerASCIIPrintf(viewer,"Linear solve converged due to %s iterations %D\n",KSPConvergedReasons[ksp->reason],ksp->its);
410:       }
411:     } else {
412:       if (((PetscObject) ksp)->prefix) {
413:         PetscViewerASCIIPrintf(viewer,"Linear %s solve did not converge due to %s iterations %D\n",((PetscObject) ksp)->prefix,KSPConvergedReasons[ksp->reason],ksp->its);
414:       } else {
415:         PetscViewerASCIIPrintf(viewer,"Linear solve did not converge due to %s iterations %D\n",KSPConvergedReasons[ksp->reason],ksp->its);
416:       }
417:       if (ksp->reason == KSP_DIVERGED_PC_FAILED) {
418:         PCFailedReason reason;
419:         PCGetFailedReason(ksp->pc,&reason);
420:         PetscViewerASCIIPrintf(viewer,"               PC_FAILED due to %s \n",PCFailedReasons[reason]);
421:       }
422:     }
423:     PetscViewerASCIISubtractTab(viewer,((PetscObject)ksp)->tablevel);
424:   }
425:   if (format != PETSC_VIEWER_DEFAULT) {PetscViewerPopFormat(viewer);}
426:   return(0);
427: }

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

432:    Collective on ksp

434:    Parameter:
435: +  ksp - iterative context obtained from KSPCreate()
436: -  viewer - the viewer to display the reason


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

442:    Level: beginner

444: .seealso: KSPCreate(), KSPSetUp(), KSPDestroy(), KSPSetTolerances(), KSPConvergedDefault(),
445:           KSPSolveTranspose(), KSPGetIterationNumber(), KSP
446: @*/
447: PetscErrorCode KSPReasonView(KSP ksp,PetscViewer viewer)
448: {

452:   KSPReasonView_Internal(ksp, viewer, PETSC_VIEWER_DEFAULT);
453:   return(0);
454: }

456: #if defined(PETSC_HAVE_THREADSAFETY)
457: #define KSPReasonViewFromOptions KSPReasonViewFromOptionsUnsafe
458: #else
459: #endif
460: /*@C
461:   KSPReasonViewFromOptions - Processes command line options to determine if/how a KSPReason is to be viewed.

463:   Collective on ksp

465:   Input Parameters:
466: . ksp   - the KSP object

468:   Level: intermediate

470: @*/
471: PetscErrorCode KSPReasonViewFromOptions(KSP ksp)
472: {
473:   PetscViewer       viewer;
474:   PetscBool         flg;
475:   PetscViewerFormat format;
476:   PetscErrorCode    ierr;

479:   PetscOptionsGetViewer(PetscObjectComm((PetscObject)ksp),((PetscObject)ksp)->options,((PetscObject)ksp)->prefix,"-ksp_converged_reason",&viewer,&format,&flg);
480:   if (flg) {
481:     KSPReasonView_Internal(ksp, viewer, format);
482:     PetscViewerDestroy(&viewer);
483:   }
484:   return(0);
485: }

487:  #include <petscdraw.h>

489: static PetscErrorCode KSPViewEigenvalues_Internal(KSP ksp, PetscBool isExplicit, PetscViewer viewer, PetscViewerFormat format)
490: {
491:   PetscReal     *r, *c;
492:   PetscInt       n, i, neig;
493:   PetscBool      isascii, isdraw;
494:   PetscMPIInt    rank;

498:   MPI_Comm_rank(PetscObjectComm((PetscObject) ksp), &rank);
499:   PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWERASCII, &isascii);
500:   PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWERDRAW,  &isdraw);
501:   if (isExplicit) {
502:     VecGetSize(ksp->vec_sol,&n);
503:     PetscMalloc2(n, &r, n, &c);
504:     KSPComputeEigenvaluesExplicitly(ksp, n, r, c);
505:     neig = n;
506:   } else {
507:     PetscInt nits;

509:     KSPGetIterationNumber(ksp, &nits);
510:     n    = nits+2;
511:     if (!nits) {PetscViewerASCIIPrintf(viewer, "Zero iterations in solver, cannot approximate any eigenvalues\n");return(0);}
512:     PetscMalloc2(n, &r, n, &c);
513:     KSPComputeEigenvalues(ksp, n, r, c, &neig);
514:   }
515:   if (isascii) {
516:     PetscViewerASCIIPrintf(viewer, "%s computed eigenvalues\n", isExplicit ? "Explicitly" : "Iteratively");
517:     for (i = 0; i < neig; ++i) {
518:       if (c[i] >= 0.0) {PetscViewerASCIIPrintf(viewer, "%g + %gi\n", (double) r[i],  (double) c[i]);}
519:       else             {PetscViewerASCIIPrintf(viewer, "%g - %gi\n", (double) r[i], -(double) c[i]);}
520:     }
521:   } else if (isdraw && !rank) {
522:     PetscDraw   draw;
523:     PetscDrawSP drawsp;

525:     if (format == PETSC_VIEWER_DRAW_CONTOUR) {
526:       KSPPlotEigenContours_Private(ksp,neig,r,c);
527:     } else {
528:       if (!ksp->eigviewer) {PetscViewerDrawOpen(PETSC_COMM_SELF,0,isExplicit ? "Explicitly Computed Eigenvalues" : "Iteratively Computed Eigenvalues",PETSC_DECIDE,PETSC_DECIDE,400,400,&ksp->eigviewer);}
529:       PetscViewerDrawGetDraw(ksp->eigviewer,0,&draw);
530:       PetscDrawSPCreate(draw,1,&drawsp);
531:       PetscDrawSPReset(drawsp);
532:       for (i = 0; i < neig; ++i) {PetscDrawSPAddPoint(drawsp,r+i,c+i);}
533:       PetscDrawSPDraw(drawsp,PETSC_TRUE);
534:       PetscDrawSPSave(drawsp);
535:       PetscDrawSPDestroy(&drawsp);
536:     }
537:   }
538:   PetscFree2(r, c);
539:   return(0);
540: }

542: static PetscErrorCode KSPViewSingularvalues_Internal(KSP ksp, PetscViewer viewer, PetscViewerFormat format)
543: {
544:   PetscReal      smax, smin;
545:   PetscInt       nits;
546:   PetscBool      isascii;

550:   PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWERASCII, &isascii);
551:   KSPGetIterationNumber(ksp, &nits);
552:   if (!nits) {PetscViewerASCIIPrintf(viewer, "Zero iterations in solver, cannot approximate any singular values\n");return(0);}
553:   KSPComputeExtremeSingularValues(ksp, &smax, &smin);
554:   if (isascii) {PetscViewerASCIIPrintf(viewer, "Iteratively computed extreme singular values: max %g min %g max/min %g\n",(double)smax,(double)smin,(double)(smax/smin));}
555:   return(0);
556: }

558: static PetscErrorCode KSPViewFinalResidual_Internal(KSP ksp, PetscViewer viewer, PetscViewerFormat format)
559: {
560:   PetscBool      isascii;

564:   PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWERASCII, &isascii);
565:   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");
566:   if (isascii) {
567:     Mat       A;
568:     Vec       t;
569:     PetscReal norm;

571:     PCGetOperators(ksp->pc, &A, NULL);
572:     VecDuplicate(ksp->vec_rhs, &t);
573:     KSP_MatMult(ksp, A, ksp->vec_sol, t);
574:     VecAYPX(t, -1.0, ksp->vec_rhs);
575:     VecNorm(t, NORM_2, &norm);
576:     VecDestroy(&t);
577:     PetscViewerASCIIPrintf(viewer, "KSP final norm of residual %g\n", (double) norm);
578:   }
579:   return(0);
580: }

582: /*@
583:    KSPSolve - Solves linear system.

585:    Collective on ksp

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

592:    Options Database Keys:
593: +  -ksp_compute_eigenvalues - compute preconditioned operators eigenvalues
594: .  -ksp_plot_eigenvalues - plot the computed eigenvalues in an X-window
595: .  -ksp_plot_eigencontours - plot the computed eigenvalues in an X-window with contours
596: .  -ksp_compute_eigenvalues_explicitly - compute the eigenvalues by forming the dense operator and using LAPACK
597: .  -ksp_plot_eigenvalues_explicitly - plot the explicitly computing eigenvalues
598: .  -ksp_view_mat binary - save matrix to the default binary viewer
599: .  -ksp_view_pmat binary - save matrix used to build preconditioner to the default binary viewer
600: .  -ksp_view_rhs binary - save right hand side vector to the default binary viewer
601: .  -ksp_view_solution binary - save computed solution vector to the default binary viewer
602:            (can be read later with src/ksp/examples/tutorials/ex10.c for testing solvers)
603: .  -ksp_view_mat_explicit - for matrix-free operators, computes the matrix entries and views them
604: .  -ksp_view_preconditioned_operator_explicit - computes the product of the preconditioner and matrix as an explicit matrix and views it
605: .  -ksp_converged_reason - print reason for converged or diverged, also prints number of iterations
606: .  -ksp_final_residual - print 2-norm of true linear system residual at the end of the solution process
607: -  -ksp_view - print the ksp data structure at the end of the system solution

609:    Notes:

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

613:    The operator is specified with KSPSetOperators().

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

618:    If you provide a matrix that has a MatSetNullSpace() and MatSetTransposeNullSpace() this will use that information to solve singular systems
619:    in the least squares sense with a norm minimizing solution.
620: $
621: $                   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()
622: $
623: $    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
624: $    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
625: $    direction thus the solution which is a linear combination of the search directions has no component in the nullspace(A).
626: $
627: $    We recommend always using GMRES for such singular systems.
628: $    If nullspace(A) = nullspace(A') (note symmetric matrices always satisfy this property) then both left and right preconditioning will work
629: $    If nullspace(A) != nullspace(A') then left preconditioning will work but right preconditioning may not work (or it may).

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


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

641:    Understanding Convergence:
642:    The routines KSPMonitorSet(), KSPComputeEigenvalues(), and
643:    KSPComputeEigenvaluesExplicitly() provide information on additional
644:    options to monitor convergence and print eigenvalue information.

646:    Level: beginner

648: .seealso: KSPCreate(), KSPSetUp(), KSPDestroy(), KSPSetTolerances(), KSPConvergedDefault(),
649:           KSPSolveTranspose(), KSPGetIterationNumber(), MatNullSpaceCreate(), MatSetNullSpace(), MatSetTransposeNullSpace(), KSP
650: @*/
651: PetscErrorCode KSPSolve(KSP ksp,Vec b,Vec x)
652: {
653:   PetscErrorCode    ierr;
654:   PetscBool         flg = PETSC_FALSE,inXisinB=PETSC_FALSE,guess_zero;
655:   Mat               mat,pmat;
656:   MPI_Comm          comm;
657:   MatNullSpace      nullsp;
658:   Vec               btmp,vec_rhs=0;

664:   comm = PetscObjectComm((PetscObject)ksp);
665:   if (x && x == b) {
666:     if (!ksp->guess_zero) SETERRQ(comm,PETSC_ERR_ARG_INCOMP,"Cannot use x == b with nonzero initial guess");
667:     VecDuplicate(b,&x);
668:     inXisinB = PETSC_TRUE;
669:   }
670:   if (b) {
671:     PetscObjectReference((PetscObject)b);
672:     VecDestroy(&ksp->vec_rhs);
673:     ksp->vec_rhs = b;
674:   }
675:   if (x) {
676:     PetscObjectReference((PetscObject)x);
677:     VecDestroy(&ksp->vec_sol);
678:     ksp->vec_sol = x;
679:   }
680:   if (ksp->viewPre) {ObjectView((PetscObject) ksp, ksp->viewerPre, ksp->formatPre);}

682:   ksp->transpose_solve = PETSC_FALSE;

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

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

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

691:   if (ksp->guess) {
692:     PetscObjectState ostate,state;

694:     KSPGuessSetUp(ksp->guess);
695:     PetscObjectStateGet((PetscObject)ksp->vec_sol,&ostate);
696:     KSPGuessFormGuess(ksp->guess,ksp->vec_rhs,ksp->vec_sol);
697:     PetscObjectStateGet((PetscObject)ksp->vec_sol,&state);
698:     if (state != ostate) {
699:       ksp->guess_zero = PETSC_FALSE;
700:     } else {
701:       PetscInfo(ksp,"Using zero initial guess since the KSPGuess object did not change the vector\n");
702:       ksp->guess_zero = PETSC_TRUE;
703:     }
704:   }

706:   /* KSPSetUp() scales the matrix if needed */
707:   KSPSetUp(ksp);
708:   KSPSetUpOnBlocks(ksp);

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

712:   PCGetOperators(ksp->pc,&mat,&pmat);
713:   /* diagonal scale RHS if called for */
714:   if (ksp->dscale) {
715:     VecPointwiseMult(ksp->vec_rhs,ksp->vec_rhs,ksp->diagonal);
716:     /* second time in, but matrix was scaled back to original */
717:     if (ksp->dscalefix && ksp->dscalefix2) {
718:       Mat mat,pmat;

720:       PCGetOperators(ksp->pc,&mat,&pmat);
721:       MatDiagonalScale(pmat,ksp->diagonal,ksp->diagonal);
722:       if (mat != pmat) {MatDiagonalScale(mat,ksp->diagonal,ksp->diagonal);}
723:     }

725:     /* scale initial guess */
726:     if (!ksp->guess_zero) {
727:       if (!ksp->truediagonal) {
728:         VecDuplicate(ksp->diagonal,&ksp->truediagonal);
729:         VecCopy(ksp->diagonal,ksp->truediagonal);
730:         VecReciprocal(ksp->truediagonal);
731:       }
732:       VecPointwiseMult(ksp->vec_sol,ksp->vec_sol,ksp->truediagonal);
733:     }
734:   }
735:   PCPreSolve(ksp->pc,ksp);

737:   if (ksp->guess_zero) { VecSet(ksp->vec_sol,0.0);}
738:   if (ksp->guess_knoll) { /* The Knoll trick is independent on the KSPGuess specified */
739:     PCApply(ksp->pc,ksp->vec_rhs,ksp->vec_sol);
740:     KSP_RemoveNullSpace(ksp,ksp->vec_sol);
741:     ksp->guess_zero = PETSC_FALSE;
742:   }

744:   /* can we mark the initial guess as zero for this solve? */
745:   guess_zero = ksp->guess_zero;
746:   if (!ksp->guess_zero) {
747:     PetscReal norm;

749:     VecNormAvailable(ksp->vec_sol,NORM_2,&flg,&norm);
750:     if (flg && !norm) ksp->guess_zero = PETSC_TRUE;
751:   }
752:   MatGetTransposeNullSpace(pmat,&nullsp);
753:   if (nullsp) {
754:     VecDuplicate(ksp->vec_rhs,&btmp);
755:     VecCopy(ksp->vec_rhs,btmp);
756:     MatNullSpaceRemove(nullsp,btmp);
757:     vec_rhs      = ksp->vec_rhs;
758:     ksp->vec_rhs = btmp;
759:   }
760:   VecLockReadPush(ksp->vec_rhs);
761:   if (ksp->reason == KSP_DIVERGED_PC_FAILED) {
762:     VecSetInf(ksp->vec_sol);
763:   }
764:   (*ksp->ops->solve)(ksp);

766:   VecLockReadPop(ksp->vec_rhs);
767:   if (nullsp) {
768:     ksp->vec_rhs = vec_rhs;
769:     VecDestroy(&btmp);
770:   }

772:   ksp->guess_zero = guess_zero;

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

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

780:   /* diagonal scale solution if called for */
781:   if (ksp->dscale) {
782:     VecPointwiseMult(ksp->vec_sol,ksp->vec_sol,ksp->diagonal);
783:     /* unscale right hand side and matrix */
784:     if (ksp->dscalefix) {
785:       Mat mat,pmat;

787:       VecReciprocal(ksp->diagonal);
788:       VecPointwiseMult(ksp->vec_rhs,ksp->vec_rhs,ksp->diagonal);
789:       PCGetOperators(ksp->pc,&mat,&pmat);
790:       MatDiagonalScale(pmat,ksp->diagonal,ksp->diagonal);
791:       if (mat != pmat) {MatDiagonalScale(mat,ksp->diagonal,ksp->diagonal);}
792:       VecReciprocal(ksp->diagonal);
793:       ksp->dscalefix2 = PETSC_TRUE;
794:     }
795:   }
796:   PetscLogEventEnd(KSP_Solve,ksp,ksp->vec_rhs,ksp->vec_sol,0);
797:   if (ksp->guess) {
798:     KSPGuessUpdate(ksp->guess,ksp->vec_rhs,ksp->vec_sol);
799:   }
800:   if (ksp->postsolve) {
801:     (*ksp->postsolve)(ksp,ksp->vec_rhs,ksp->vec_sol,ksp->postctx);
802:   }

804:   PCGetOperators(ksp->pc,&mat,&pmat);
805:   if (ksp->viewEV)       {KSPViewEigenvalues_Internal(ksp, PETSC_FALSE, ksp->viewerEV,    ksp->formatEV);}
806:   if (ksp->viewEVExp)    {KSPViewEigenvalues_Internal(ksp, PETSC_TRUE,  ksp->viewerEVExp, ksp->formatEVExp);}
807:   if (ksp->viewSV)       {KSPViewSingularvalues_Internal(ksp, ksp->viewerSV, ksp->formatSV);}
808:   if (ksp->viewFinalRes) {KSPViewFinalResidual_Internal(ksp, ksp->viewerFinalRes, ksp->formatFinalRes);}
809:   if (ksp->viewMat)      {ObjectView((PetscObject) mat,           ksp->viewerMat,    ksp->formatMat);}
810:   if (ksp->viewPMat)     {ObjectView((PetscObject) pmat,          ksp->viewerPMat,   ksp->formatPMat);}
811:   if (ksp->viewRhs)      {ObjectView((PetscObject) ksp->vec_rhs,  ksp->viewerRhs,    ksp->formatRhs);}
812:   if (ksp->viewSol)      {ObjectView((PetscObject) ksp->vec_sol,  ksp->viewerSol,    ksp->formatSol);}
813:   if (ksp->view)         {ObjectView((PetscObject) ksp,           ksp->viewer,       ksp->format);}
814:   if (ksp->viewDScale)   {ObjectView((PetscObject) ksp->diagonal, ksp->viewerDScale, ksp->formatDScale);}
815:   if (ksp->viewMatExp)   {
816:     Mat A, B;

818:     PCGetOperators(ksp->pc, &A, NULL);
819:     MatComputeOperator(A, MATAIJ, &B);
820:     ObjectView((PetscObject) B, ksp->viewerMatExp, ksp->formatMatExp);
821:     MatDestroy(&B);
822:   }
823:   if (ksp->viewPOpExp)   {
824:     Mat B;

826:     KSPComputeOperator(ksp, MATAIJ, &B);
827:     ObjectView((PetscObject) B, ksp->viewerPOpExp, ksp->formatPOpExp);
828:     MatDestroy(&B);
829:   }

831:   if (inXisinB) {
832:     VecCopy(x,b);
833:     VecDestroy(&x);
834:   }
835:   PetscObjectSAWsBlock((PetscObject)ksp);
836:   if (ksp->errorifnotconverged && ksp->reason < 0 && ksp->reason != KSP_DIVERGED_ITS) SETERRQ1(comm,PETSC_ERR_NOT_CONVERGED,"KSPSolve has not converged, reason %s",KSPConvergedReasons[ksp->reason]);
837:   return(0);
838: }

840: /*@
841:    KSPSolveTranspose - Solves the transpose of a linear system.

843:    Collective on ksp

845:    Input Parameter:
846: +  ksp - iterative context obtained from KSPCreate()
847: .  b - right hand side vector
848: -  x - solution vector

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

853:    This currently does NOT correctly use the null space of the operator and its transpose for solving singular systems.

855:    Developer Notes:
856:     We need to implement a KSPSolveHermitianTranspose()

858:    Level: developer

860: .seealso: KSPCreate(), KSPSetUp(), KSPDestroy(), KSPSetTolerances(), KSPConvergedDefault(),
861:           KSPSolve(), KSP
862: @*/

864: PetscErrorCode  KSPSolveTranspose(KSP ksp,Vec b,Vec x)
865: {
867:   PetscBool      inXisinB=PETSC_FALSE;
868:   Vec            vec_rhs = 0,btmp;
869:   Mat            mat,pmat;
870:   MatNullSpace   nullsp;

876:   if (x == b) {
877:     VecDuplicate(b,&x);
878:     inXisinB = PETSC_TRUE;
879:   }
880:   PetscObjectReference((PetscObject)b);
881:   PetscObjectReference((PetscObject)x);
882:   VecDestroy(&ksp->vec_rhs);
883:   VecDestroy(&ksp->vec_sol);

885:   ksp->vec_rhs         = b;
886:   ksp->vec_sol         = x;
887:   ksp->transpose_solve = PETSC_TRUE;

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

891:   if (ksp->guess) {
892:     PetscObjectState ostate,state;

894:     KSPGuessSetUp(ksp->guess);
895:     PetscObjectStateGet((PetscObject)ksp->vec_sol,&ostate);
896:     KSPGuessFormGuess(ksp->guess,ksp->vec_rhs,ksp->vec_sol);
897:     PetscObjectStateGet((PetscObject)ksp->vec_sol,&state);
898:     if (state != ostate) {
899:       ksp->guess_zero = PETSC_FALSE;
900:     } else {
901:       PetscInfo(ksp,"Using zero initial guess since the KSPGuess object did not change the vector\n");
902:       ksp->guess_zero = PETSC_TRUE;
903:     }
904:   }

906:   KSPSetUp(ksp);
907:   KSPSetUpOnBlocks(ksp);
908:   if (ksp->guess_zero) { VecSet(ksp->vec_sol,0.0);}

910:   PCGetOperators(ksp->pc,&mat,&pmat);
911:   MatGetNullSpace(pmat,&nullsp);
912:   if (nullsp) {
913:     VecDuplicate(ksp->vec_rhs,&btmp);
914:     VecCopy(ksp->vec_rhs,btmp);
915:     MatNullSpaceRemove(nullsp,btmp);
916:     vec_rhs      = ksp->vec_rhs;
917:     ksp->vec_rhs = btmp;
918:   }

920:   (*ksp->ops->solve)(ksp);
921:   ksp->totalits += ksp->its;
922:   if (nullsp) {
923:     ksp->vec_rhs = vec_rhs;
924:     VecDestroy(&btmp);
925:   }
926:   if (!ksp->reason) SETERRQ(PetscObjectComm((PetscObject)ksp),PETSC_ERR_PLIB,"Internal error, solver returned without setting converged reason");
927:   if (ksp->viewReason) {KSPReasonView_Internal(ksp, ksp->viewerReason, ksp->formatReason);}
928:   if (ksp->guess) {
929:     KSPGuessUpdate(ksp->guess,ksp->vec_rhs,ksp->vec_sol);
930:   }
931:   if (ksp->postsolve) {
932:     (*ksp->postsolve)(ksp,ksp->vec_rhs,ksp->vec_sol,ksp->postctx);
933:   }

935:   if (ksp->viewMat)      {ObjectView((PetscObject) mat,          ksp->viewerMat,  ksp->formatMat);}
936:   if (ksp->viewPMat)     {ObjectView((PetscObject) pmat,         ksp->viewerPMat, ksp->formatPMat);}
937:   if (ksp->viewRhs)      {ObjectView((PetscObject) ksp->vec_rhs, ksp->viewerRhs,  ksp->formatRhs);}
938:   if (ksp->viewSol)      {ObjectView((PetscObject) ksp->vec_sol, ksp->viewerSol,  ksp->formatSol);}
939:   if (ksp->view)         {ObjectView((PetscObject) ksp,          ksp->viewer,     ksp->format);}

941:   if (inXisinB) {
942:     VecCopy(x,b);
943:     VecDestroy(&x);
944:   }
945:   if (ksp->errorifnotconverged && ksp->reason < 0) SETERRQ(PetscObjectComm((PetscObject)ksp),PETSC_ERR_NOT_CONVERGED,"KSPSolve has not converged");
946:   return(0);
947: }

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

952:    Collective on ksp

954:    Input Parameter:
955: .  ksp - iterative context obtained from KSPCreate()

957:    Level: beginner

959: .seealso: KSPCreate(), KSPSetUp(), KSPSolve(), KSPSetFromOptions(), KSP
960: @*/
961: PetscErrorCode  KSPResetViewers(KSP ksp)
962: {

967:   if (!ksp) return(0);
968:   PetscViewerDestroy(&ksp->viewer);
969:   PetscViewerDestroy(&ksp->viewerPre);
970:   PetscViewerDestroy(&ksp->viewerReason);
971:   PetscViewerDestroy(&ksp->viewerMat);
972:   PetscViewerDestroy(&ksp->viewerPMat);
973:   PetscViewerDestroy(&ksp->viewerRhs);
974:   PetscViewerDestroy(&ksp->viewerSol);
975:   PetscViewerDestroy(&ksp->viewerMatExp);
976:   PetscViewerDestroy(&ksp->viewerEV);
977:   PetscViewerDestroy(&ksp->viewerSV);
978:   PetscViewerDestroy(&ksp->viewerEVExp);
979:   PetscViewerDestroy(&ksp->viewerFinalRes);
980:   PetscViewerDestroy(&ksp->viewerPOpExp);
981:   PetscViewerDestroy(&ksp->viewerDScale);
982:   ksp->view         = PETSC_FALSE;
983:   ksp->viewPre      = PETSC_FALSE;
984:   ksp->viewReason   = PETSC_FALSE;
985:   ksp->viewMat      = PETSC_FALSE;
986:   ksp->viewPMat     = PETSC_FALSE;
987:   ksp->viewRhs      = PETSC_FALSE;
988:   ksp->viewSol      = PETSC_FALSE;
989:   ksp->viewMatExp   = PETSC_FALSE;
990:   ksp->viewEV       = PETSC_FALSE;
991:   ksp->viewSV       = PETSC_FALSE;
992:   ksp->viewEVExp    = PETSC_FALSE;
993:   ksp->viewFinalRes = PETSC_FALSE;
994:   ksp->viewPOpExp   = PETSC_FALSE;
995:   ksp->viewDScale   = PETSC_FALSE;
996:   return(0);
997: }

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

1002:    Collective on ksp

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

1007:    Level: beginner

1009: .seealso: KSPCreate(), KSPSetUp(), KSPSolve(), KSP
1010: @*/
1011: PetscErrorCode  KSPReset(KSP ksp)
1012: {

1017:   if (!ksp) return(0);
1018:   if (ksp->ops->reset) {
1019:     (*ksp->ops->reset)(ksp);
1020:   }
1021:   if (ksp->pc) {PCReset(ksp->pc);}
1022:   if (ksp->guess) {
1023:     KSPGuess guess = ksp->guess;
1024:     if (guess->ops->reset) { (*guess->ops->reset)(guess); }
1025:   }
1026:   VecDestroyVecs(ksp->nwork,&ksp->work);
1027:   VecDestroy(&ksp->vec_rhs);
1028:   VecDestroy(&ksp->vec_sol);
1029:   VecDestroy(&ksp->diagonal);
1030:   VecDestroy(&ksp->truediagonal);

1032:   KSPResetViewers(ksp);

1034:   ksp->setupstage = KSP_SETUP_NEW;
1035:   return(0);
1036: }

1038: /*@
1039:    KSPDestroy - Destroys KSP context.

1041:    Collective on ksp

1043:    Input Parameter:
1044: .  ksp - iterative context obtained from KSPCreate()

1046:    Level: beginner

1048: .seealso: KSPCreate(), KSPSetUp(), KSPSolve(), KSP
1049: @*/
1050: PetscErrorCode  KSPDestroy(KSP *ksp)
1051: {
1053:   PC             pc;

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

1060:   PetscObjectSAWsViewOff((PetscObject)*ksp);

1062:   /*
1063:    Avoid a cascading call to PCReset(ksp->pc) from the following call:
1064:    PCReset() shouldn't be called from KSPDestroy() as it is unprotected by pc's
1065:    refcount (and may be shared, e.g., by other ksps).
1066:    */
1067:   pc         = (*ksp)->pc;
1068:   (*ksp)->pc = NULL;
1069:   KSPReset((*ksp));
1070:   (*ksp)->pc = pc;
1071:   if ((*ksp)->ops->destroy) {(*(*ksp)->ops->destroy)(*ksp);}

1073:   KSPGuessDestroy(&(*ksp)->guess);
1074:   DMDestroy(&(*ksp)->dm);
1075:   PCDestroy(&(*ksp)->pc);
1076:   PetscFree((*ksp)->res_hist_alloc);
1077:   if ((*ksp)->convergeddestroy) {
1078:     (*(*ksp)->convergeddestroy)((*ksp)->cnvP);
1079:   }
1080:   KSPMonitorCancel((*ksp));
1081:   PetscViewerDestroy(&(*ksp)->eigviewer);
1082:   PetscHeaderDestroy(ksp);
1083:   return(0);
1084: }

1086: /*@
1087:     KSPSetPCSide - Sets the preconditioning side.

1089:     Logically Collective on ksp

1091:     Input Parameter:
1092: .   ksp - iterative context obtained from KSPCreate()

1094:     Output Parameter:
1095: .   side - the preconditioning side, where side is one of
1096: .vb
1097:       PC_LEFT - left preconditioning (default)
1098:       PC_RIGHT - right preconditioning
1099:       PC_SYMMETRIC - symmetric preconditioning
1100: .ve

1102:     Options Database Keys:
1103: .   -ksp_pc_side <right,left,symmetric>

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

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

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

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

1116:     Level: intermediate

1118: .seealso: KSPGetPCSide(), KSPSetNormType(), KSPGetNormType(), KSP
1119: @*/
1120: PetscErrorCode  KSPSetPCSide(KSP ksp,PCSide side)
1121: {
1125:   ksp->pc_side = ksp->pc_side_set = side;
1126:   return(0);
1127: }

1129: /*@
1130:     KSPGetPCSide - Gets the preconditioning side.

1132:     Not Collective

1134:     Input Parameter:
1135: .   ksp - iterative context obtained from KSPCreate()

1137:     Output Parameter:
1138: .   side - the preconditioning side, where side is one of
1139: .vb
1140:       PC_LEFT - left preconditioning (default)
1141:       PC_RIGHT - right preconditioning
1142:       PC_SYMMETRIC - symmetric preconditioning
1143: .ve

1145:     Level: intermediate

1147: .seealso: KSPSetPCSide(), KSP
1148: @*/
1149: PetscErrorCode  KSPGetPCSide(KSP ksp,PCSide *side)
1150: {

1156:   KSPSetUpNorms_Private(ksp,PETSC_TRUE,&ksp->normtype,&ksp->pc_side);
1157:   *side = ksp->pc_side;
1158:   return(0);
1159: }

1161: /*@
1162:    KSPGetTolerances - Gets the relative, absolute, divergence, and maximum
1163:    iteration tolerances used by the default KSP convergence tests.

1165:    Not Collective

1167:    Input Parameter:
1168: .  ksp - the Krylov subspace context

1170:    Output Parameters:
1171: +  rtol - the relative convergence tolerance
1172: .  abstol - the absolute convergence tolerance
1173: .  dtol - the divergence tolerance
1174: -  maxits - maximum number of iterations

1176:    Notes:
1177:    The user can specify NULL for any parameter that is not needed.

1179:    Level: intermediate

1181:            maximum, iterations

1183: .seealso: KSPSetTolerances(), KSP
1184: @*/
1185: PetscErrorCode  KSPGetTolerances(KSP ksp,PetscReal *rtol,PetscReal *abstol,PetscReal *dtol,PetscInt *maxits)
1186: {
1189:   if (abstol) *abstol = ksp->abstol;
1190:   if (rtol) *rtol = ksp->rtol;
1191:   if (dtol) *dtol = ksp->divtol;
1192:   if (maxits) *maxits = ksp->max_it;
1193:   return(0);
1194: }

1196: /*@
1197:    KSPSetTolerances - Sets the relative, absolute, divergence, and maximum
1198:    iteration tolerances used by the default KSP convergence testers.

1200:    Logically Collective on ksp

1202:    Input Parameters:
1203: +  ksp - the Krylov subspace context
1204: .  rtol - the relative convergence tolerance, relative decrease in the (possibly preconditioned) residual norm
1205: .  abstol - the absolute convergence tolerance   absolute size of the (possibly preconditioned) residual norm
1206: .  dtol - the divergence tolerance,   amount (possibly preconditioned) residual norm can increase before KSPConvergedDefault() concludes that the method is diverging
1207: -  maxits - maximum number of iterations to use

1209:    Options Database Keys:
1210: +  -ksp_atol <abstol> - Sets abstol
1211: .  -ksp_rtol <rtol> - Sets rtol
1212: .  -ksp_divtol <dtol> - Sets dtol
1213: -  -ksp_max_it <maxits> - Sets maxits

1215:    Notes:
1216:    Use PETSC_DEFAULT to retain the default value of any of the tolerances.

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

1221:    Level: intermediate

1223:            convergence, maximum, iterations

1225: .seealso: KSPGetTolerances(), KSPConvergedDefault(), KSPSetConvergenceTest(), KSP
1226: @*/
1227: PetscErrorCode  KSPSetTolerances(KSP ksp,PetscReal rtol,PetscReal abstol,PetscReal dtol,PetscInt maxits)
1228: {

1236:   if (rtol != PETSC_DEFAULT) {
1237:     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);
1238:     ksp->rtol = rtol;
1239:   }
1240:   if (abstol != PETSC_DEFAULT) {
1241:     if (abstol < 0.0) SETERRQ1(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_OUTOFRANGE,"Absolute tolerance %g must be non-negative",(double)abstol);
1242:     ksp->abstol = abstol;
1243:   }
1244:   if (dtol != PETSC_DEFAULT) {
1245:     if (dtol < 0.0) SETERRQ1(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_OUTOFRANGE,"Divergence tolerance %g must be larger than 1.0",(double)dtol);
1246:     ksp->divtol = dtol;
1247:   }
1248:   if (maxits != PETSC_DEFAULT) {
1249:     if (maxits < 0) SETERRQ1(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of iterations %D must be non-negative",maxits);
1250:     ksp->max_it = maxits;
1251:   }
1252:   return(0);
1253: }

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

1260:    Logically Collective on ksp

1262:    Input Parameters:
1263: +  ksp - iterative context obtained from KSPCreate()
1264: -  flg - PETSC_TRUE indicates the guess is non-zero, PETSC_FALSE indicates the guess is zero

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

1269:    Level: beginner

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

1274: .seealso: KSPGetInitialGuessNonzero(), KSPSetGuessType(), KSPGuessType, KSP
1275: @*/
1276: PetscErrorCode  KSPSetInitialGuessNonzero(KSP ksp,PetscBool flg)
1277: {
1281:   ksp->guess_zero = (PetscBool) !(int)flg;
1282:   return(0);
1283: }

1285: /*@
1286:    KSPGetInitialGuessNonzero - Determines whether the KSP solver is using
1287:    a zero initial guess.

1289:    Not Collective

1291:    Input Parameter:
1292: .  ksp - iterative context obtained from KSPCreate()

1294:    Output Parameter:
1295: .  flag - PETSC_TRUE if guess is nonzero, else PETSC_FALSE

1297:    Level: intermediate

1299: .seealso: KSPSetInitialGuessNonzero(), KSP
1300: @*/
1301: PetscErrorCode  KSPGetInitialGuessNonzero(KSP ksp,PetscBool  *flag)
1302: {
1306:   if (ksp->guess_zero) *flag = PETSC_FALSE;
1307:   else *flag = PETSC_TRUE;
1308:   return(0);
1309: }

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

1314:    Logically Collective on ksp

1316:    Input Parameters:
1317: +  ksp - iterative context obtained from KSPCreate()
1318: -  flg - PETSC_TRUE indicates you want the error generated

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

1323:    Level: intermediate

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


1330: .seealso: KSPGetErrorIfNotConverged(), KSP
1331: @*/
1332: PetscErrorCode  KSPSetErrorIfNotConverged(KSP ksp,PetscBool flg)
1333: {
1337:   ksp->errorifnotconverged = flg;
1338:   return(0);
1339: }

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

1344:    Not Collective

1346:    Input Parameter:
1347: .  ksp - iterative context obtained from KSPCreate()

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

1352:    Level: intermediate

1354: .seealso: KSPSetErrorIfNotConverged(), KSP
1355: @*/
1356: PetscErrorCode  KSPGetErrorIfNotConverged(KSP ksp,PetscBool  *flag)
1357: {
1361:   *flag = ksp->errorifnotconverged;
1362:   return(0);
1363: }

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

1368:    Logically Collective on ksp

1370:    Input Parameters:
1371: +  ksp - iterative context obtained from KSPCreate()
1372: -  flg - PETSC_TRUE or PETSC_FALSE

1374:    Level: advanced

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

1378: .seealso: KSPGetInitialGuessKnoll(), KSPSetInitialGuessNonzero(), KSPGetInitialGuessNonzero(), KSP
1379: @*/
1380: PetscErrorCode  KSPSetInitialGuessKnoll(KSP ksp,PetscBool flg)
1381: {
1385:   ksp->guess_knoll = flg;
1386:   return(0);
1387: }

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

1393:    Not Collective

1395:    Input Parameter:
1396: .  ksp - iterative context obtained from KSPCreate()

1398:    Output Parameter:
1399: .  flag - PETSC_TRUE if using Knoll trick, else PETSC_FALSE

1401:    Level: advanced

1403: .seealso: KSPSetInitialGuessKnoll(), KSPSetInitialGuessNonzero(), KSPGetInitialGuessNonzero(), KSP
1404: @*/
1405: PetscErrorCode  KSPGetInitialGuessKnoll(KSP ksp,PetscBool  *flag)
1406: {
1410:   *flag = ksp->guess_knoll;
1411:   return(0);
1412: }

1414: /*@
1415:    KSPGetComputeSingularValues - Gets the flag indicating whether the extreme singular
1416:    values will be calculated via a Lanczos or Arnoldi process as the linear
1417:    system is solved.

1419:    Not Collective

1421:    Input Parameter:
1422: .  ksp - iterative context obtained from KSPCreate()

1424:    Output Parameter:
1425: .  flg - PETSC_TRUE or PETSC_FALSE

1427:    Options Database Key:
1428: .  -ksp_monitor_singular_value - Activates KSPSetComputeSingularValues()

1430:    Notes:
1431:    Currently this option is not valid for all iterative methods.

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

1437:    Level: advanced

1439: .seealso: KSPComputeExtremeSingularValues(), KSPMonitorSingularValue(), KSP
1440: @*/
1441: PetscErrorCode  KSPGetComputeSingularValues(KSP ksp,PetscBool  *flg)
1442: {
1446:   *flg = ksp->calc_sings;
1447:   return(0);
1448: }

1450: /*@
1451:    KSPSetComputeSingularValues - Sets a flag so that the extreme singular
1452:    values will be calculated via a Lanczos or Arnoldi process as the linear
1453:    system is solved.

1455:    Logically Collective on ksp

1457:    Input Parameters:
1458: +  ksp - iterative context obtained from KSPCreate()
1459: -  flg - PETSC_TRUE or PETSC_FALSE

1461:    Options Database Key:
1462: .  -ksp_monitor_singular_value - Activates KSPSetComputeSingularValues()

1464:    Notes:
1465:    Currently this option is not valid for all iterative methods.

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

1471:    Level: advanced

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

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

1489:    Not Collective

1491:    Input Parameter:
1492: .  ksp - iterative context obtained from KSPCreate()

1494:    Output Parameter:
1495: .  flg - PETSC_TRUE or PETSC_FALSE

1497:    Notes:
1498:    Currently this option is not valid for all iterative methods.

1500:    Level: advanced

1502: .seealso: KSPComputeEigenvalues(), KSPComputeEigenvaluesExplicitly(), KSP
1503: @*/
1504: PetscErrorCode  KSPGetComputeEigenvalues(KSP ksp,PetscBool  *flg)
1505: {
1509:   *flg = ksp->calc_sings;
1510:   return(0);
1511: }

1513: /*@
1514:    KSPSetComputeEigenvalues - Sets a flag so that the extreme eigenvalues
1515:    values will be calculated via a Lanczos or Arnoldi process as the linear
1516:    system is solved.

1518:    Logically Collective on ksp

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

1524:    Notes:
1525:    Currently this option is not valid for all iterative methods.

1527:    Level: advanced

1529: .seealso: KSPComputeEigenvalues(), KSPComputeEigenvaluesExplicitly(), KSP
1530: @*/
1531: PetscErrorCode  KSPSetComputeEigenvalues(KSP ksp,PetscBool flg)
1532: {
1536:   ksp->calc_sings = flg;
1537:   return(0);
1538: }

1540: /*@
1541:    KSPSetComputeRitz - Sets a flag so that the Ritz or harmonic Ritz pairs
1542:    will be calculated via a Lanczos or Arnoldi process as the linear
1543:    system is solved.

1545:    Logically Collective on ksp

1547:    Input Parameters:
1548: +  ksp - iterative context obtained from KSPCreate()
1549: -  flg - PETSC_TRUE or PETSC_FALSE

1551:    Notes:
1552:    Currently this option is only valid for the GMRES method.

1554:    Level: advanced

1556: .seealso: KSPComputeRitz(), KSP
1557: @*/
1558: PetscErrorCode  KSPSetComputeRitz(KSP ksp, PetscBool flg)
1559: {
1563:   ksp->calc_ritz = flg;
1564:   return(0);
1565: }

1567: /*@
1568:    KSPGetRhs - Gets the right-hand-side vector for the linear system to
1569:    be solved.

1571:    Not Collective

1573:    Input Parameter:
1574: .  ksp - iterative context obtained from KSPCreate()

1576:    Output Parameter:
1577: .  r - right-hand-side vector

1579:    Level: developer

1581: .seealso: KSPGetSolution(), KSPSolve(), KSP
1582: @*/
1583: PetscErrorCode  KSPGetRhs(KSP ksp,Vec *r)
1584: {
1588:   *r = ksp->vec_rhs;
1589:   return(0);
1590: }

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

1597:    Not Collective

1599:    Input Parameters:
1600: .  ksp - iterative context obtained from KSPCreate()

1602:    Output Parameters:
1603: .  v - solution vector

1605:    Level: developer

1607: .seealso: KSPGetRhs(),  KSPBuildSolution(), KSPSolve(), KSP
1608: @*/
1609: PetscErrorCode  KSPGetSolution(KSP ksp,Vec *v)
1610: {
1614:   *v = ksp->vec_sol;
1615:   return(0);
1616: }

1618: /*@
1619:    KSPSetPC - Sets the preconditioner to be used to calculate the
1620:    application of the preconditioner on a vector.

1622:    Collective on ksp

1624:    Input Parameters:
1625: +  ksp - iterative context obtained from KSPCreate()
1626: -  pc   - the preconditioner object

1628:    Notes:
1629:    Use KSPGetPC() to retrieve the preconditioner context (for example,
1630:    to free it at the end of the computations).

1632:    Level: developer

1634: .seealso: KSPGetPC(), KSP
1635: @*/
1636: PetscErrorCode  KSPSetPC(KSP ksp,PC pc)
1637: {

1644:   PetscObjectReference((PetscObject)pc);
1645:   PCDestroy(&ksp->pc);
1646:   ksp->pc = pc;
1647:   PetscLogObjectParent((PetscObject)ksp,(PetscObject)ksp->pc);
1648:   return(0);
1649: }

1651: /*@
1652:    KSPGetPC - Returns a pointer to the preconditioner context
1653:    set with KSPSetPC().

1655:    Not Collective

1657:    Input Parameters:
1658: .  ksp - iterative context obtained from KSPCreate()

1660:    Output Parameter:
1661: .  pc - preconditioner context

1663:    Level: developer

1665: .seealso: KSPSetPC(), KSP
1666: @*/
1667: PetscErrorCode  KSPGetPC(KSP ksp,PC *pc)
1668: {

1674:   if (!ksp->pc) {
1675:     PCCreate(PetscObjectComm((PetscObject)ksp),&ksp->pc);
1676:     PetscObjectIncrementTabLevel((PetscObject)ksp->pc,(PetscObject)ksp,0);
1677:     PetscLogObjectParent((PetscObject)ksp,(PetscObject)ksp->pc);
1678:     PetscObjectSetOptions((PetscObject)ksp->pc,((PetscObject)ksp)->options);
1679:   }
1680:   *pc = ksp->pc;
1681:   return(0);
1682: }

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

1687:    Collective on ksp

1689:    Input Parameters:
1690: +  ksp - iterative context obtained from KSPCreate()
1691: .  it - iteration number
1692: -  rnorm - relative norm of the residual

1694:    Notes:
1695:    This routine is called by the KSP implementations.
1696:    It does not typically need to be called by the user.

1698:    Level: developer

1700: .seealso: KSPMonitorSet()
1701: @*/
1702: PetscErrorCode KSPMonitor(KSP ksp,PetscInt it,PetscReal rnorm)
1703: {
1704:   PetscInt       i, n = ksp->numbermonitors;

1708:   for (i=0; i<n; i++) {
1709:     (*ksp->monitor[i])(ksp,it,rnorm,ksp->monitorcontext[i]);
1710:   }
1711:   return(0);
1712: }

1714: /*

1716:     Checks if two monitors are identical; if they are then it destroys the new one
1717: */
1718: PetscErrorCode PetscMonitorCompare(PetscErrorCode (*nmon)(void),void *nmctx,PetscErrorCode (*nmdestroy)(void**),PetscErrorCode (*mon)(void),void *mctx,PetscErrorCode (*mdestroy)(void**),PetscBool *identical)
1719: {
1720:   *identical = PETSC_FALSE;
1721:   if (nmon == mon && nmdestroy == mdestroy) {
1722:     if (nmctx == mctx) *identical = PETSC_TRUE;
1723:     else if (nmdestroy == (PetscErrorCode (*)(void**)) PetscViewerAndFormatDestroy) {
1724:       PetscViewerAndFormat *old = (PetscViewerAndFormat*)mctx, *newo = (PetscViewerAndFormat*)nmctx;
1725:       if (old->viewer == newo->viewer && old->format == newo->format) *identical = PETSC_TRUE;
1726:     }
1727:     if (*identical) {
1728:       if (mdestroy) {
1730:         (*mdestroy)(&nmctx);
1731:       }
1732:     }
1733:   }
1734:   return(0);
1735: }

1737: /*@C
1738:    KSPMonitorSet - Sets an ADDITIONAL function to be called at every iteration to monitor
1739:    the residual/error etc.

1741:    Logically Collective on ksp

1743:    Input Parameters:
1744: +  ksp - iterative context obtained from KSPCreate()
1745: .  monitor - pointer to function (if this is NULL, it turns off monitoring
1746: .  mctx    - [optional] context for private data for the
1747:              monitor routine (use NULL if no context is desired)
1748: -  monitordestroy - [optional] routine that frees monitor context
1749:           (may be NULL)

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

1754: +  ksp - iterative context obtained from KSPCreate()
1755: .  it - iteration number
1756: .  rnorm - (estimated) 2-norm of (preconditioned) residual
1757: -  mctx  - optional monitoring context, as set by KSPMonitorSet()

1759:    Options Database Keys:
1760: +    -ksp_monitor        - sets KSPMonitorDefault()
1761: .    -ksp_monitor_true_residual    - sets KSPMonitorTrueResidualNorm()
1762: .    -ksp_monitor_max    - sets KSPMonitorTrueResidualMaxNorm()
1763: .    -ksp_monitor_lg_residualnorm    - sets line graph monitor,
1764:                            uses KSPMonitorLGResidualNormCreate()
1765: .    -ksp_monitor_lg_true_residualnorm   - sets line graph monitor,
1766:                            uses KSPMonitorLGResidualNormCreate()
1767: .    -ksp_monitor_singular_value    - sets KSPMonitorSingularValue()
1768: -    -ksp_monitor_cancel - cancels all monitors that have
1769:                           been hardwired into a code by
1770:                           calls to KSPMonitorSet(), but
1771:                           does not cancel those set via
1772:                           the options database.

1774:    Notes:
1775:    The default is to do nothing.  To print the residual, or preconditioned
1776:    residual if KSPSetNormType(ksp,KSP_NORM_PRECONDITIONED) was called, use
1777:    KSPMonitorDefault() as the monitoring routine, with a ASCII viewer as the
1778:    context.

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

1784:    Fortran Notes:
1785:     Only a single monitor function can be set for each KSP object

1787:    Level: beginner

1789: .seealso: KSPMonitorDefault(), KSPMonitorLGResidualNormCreate(), KSPMonitorCancel(), KSP
1790: @*/
1791: PetscErrorCode  KSPMonitorSet(KSP ksp,PetscErrorCode (*monitor)(KSP,PetscInt,PetscReal,void*),void *mctx,PetscErrorCode (*monitordestroy)(void**))
1792: {
1793:   PetscInt       i;
1795:   PetscBool      identical;

1799:   for (i=0; i<ksp->numbermonitors;i++) {
1800:     PetscMonitorCompare((PetscErrorCode (*)(void))monitor,mctx,monitordestroy,(PetscErrorCode (*)(void))ksp->monitor[i],ksp->monitorcontext[i],ksp->monitordestroy[i],&identical);
1801:     if (identical) return(0);
1802:   }
1803:   if (ksp->numbermonitors >= MAXKSPMONITORS) SETERRQ(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_OUTOFRANGE,"Too many KSP monitors set");
1804:   ksp->monitor[ksp->numbermonitors]          = monitor;
1805:   ksp->monitordestroy[ksp->numbermonitors]   = monitordestroy;
1806:   ksp->monitorcontext[ksp->numbermonitors++] = (void*)mctx;
1807:   return(0);
1808: }

1810: /*@
1811:    KSPMonitorCancel - Clears all monitors for a KSP object.

1813:    Logically Collective on ksp

1815:    Input Parameters:
1816: .  ksp - iterative context obtained from KSPCreate()

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

1823:    Level: intermediate

1825: .seealso: KSPMonitorDefault(), KSPMonitorLGResidualNormCreate(), KSPMonitorSet(), KSP
1826: @*/
1827: PetscErrorCode  KSPMonitorCancel(KSP ksp)
1828: {
1830:   PetscInt       i;

1834:   for (i=0; i<ksp->numbermonitors; i++) {
1835:     if (ksp->monitordestroy[i]) {
1836:       (*ksp->monitordestroy[i])(&ksp->monitorcontext[i]);
1837:     }
1838:   }
1839:   ksp->numbermonitors = 0;
1840:   return(0);
1841: }

1843: /*@C
1844:    KSPGetMonitorContext - Gets the monitoring context, as set by
1845:    KSPMonitorSet() for the FIRST monitor only.

1847:    Not Collective

1849:    Input Parameter:
1850: .  ksp - iterative context obtained from KSPCreate()

1852:    Output Parameter:
1853: .  ctx - monitoring context

1855:    Level: intermediate

1857: .seealso: KSPMonitorDefault(), KSPMonitorLGResidualNormCreate(), KSP
1858: @*/
1859: PetscErrorCode  KSPGetMonitorContext(KSP ksp,void **ctx)
1860: {
1863:   *ctx =      (ksp->monitorcontext[0]);
1864:   return(0);
1865: }

1867: /*@
1868:    KSPSetResidualHistory - Sets the array used to hold the residual history.
1869:    If set, this array will contain the residual norms computed at each
1870:    iteration of the solver.

1872:    Not Collective

1874:    Input Parameters:
1875: +  ksp - iterative context obtained from KSPCreate()
1876: .  a   - array to hold history
1877: .  na  - size of a
1878: -  reset - PETSC_TRUE indicates the history counter is reset to zero
1879:            for each new linear solve

1881:    Level: advanced

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

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

1890: .seealso: KSPGetResidualHistory(), KSP

1892: @*/
1893: PetscErrorCode  KSPSetResidualHistory(KSP ksp,PetscReal a[],PetscInt na,PetscBool reset)
1894: {


1900:   PetscFree(ksp->res_hist_alloc);
1901:   if (na != PETSC_DECIDE && na != PETSC_DEFAULT && a) {
1902:     ksp->res_hist     = a;
1903:     ksp->res_hist_max = na;
1904:   } else {
1905:     if (na != PETSC_DECIDE && na != PETSC_DEFAULT) ksp->res_hist_max = na;
1906:     else                                           ksp->res_hist_max = 10000; /* like default ksp->max_it */
1907:     PetscCalloc1(ksp->res_hist_max,&ksp->res_hist_alloc);

1909:     ksp->res_hist = ksp->res_hist_alloc;
1910:   }
1911:   ksp->res_hist_len   = 0;
1912:   ksp->res_hist_reset = reset;
1913:   return(0);
1914: }

1916: /*@C
1917:    KSPGetResidualHistory - Gets the array used to hold the residual history
1918:    and the number of residuals it contains.

1920:    Not Collective

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

1925:    Output Parameters:
1926: +  a   - pointer to array to hold history (or NULL)
1927: -  na  - number of used entries in a (or NULL)

1929:    Level: advanced

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

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

1940: .seealso: KSPGetResidualHistory(), KSP

1942: @*/
1943: PetscErrorCode  KSPGetResidualHistory(KSP ksp,PetscReal *a[],PetscInt *na)
1944: {
1947:   if (a) *a = ksp->res_hist;
1948:   if (na) *na = ksp->res_hist_len;
1949:   return(0);
1950: }

1952: /*@C
1953:    KSPSetConvergenceTest - Sets the function to be used to determine
1954:    convergence.

1956:    Logically Collective on ksp

1958:    Input Parameters:
1959: +  ksp - iterative context obtained from KSPCreate()
1960: .  converge - pointer to int function
1961: .  cctx    - context for private data for the convergence routine (may be null)
1962: -  destroy - a routine for destroying the context (may be null)

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

1967: +  ksp - iterative context obtained from KSPCreate()
1968: .  it - iteration number
1969: .  rnorm - (estimated) 2-norm of (preconditioned) residual
1970: .  reason - the reason why it has converged or diverged
1971: -  cctx  - optional convergence context, as set by KSPSetConvergenceTest()


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

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

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

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

1988:    Level: advanced

1990: .seealso: KSPConvergedDefault(), KSPGetConvergenceContext(), KSPSetTolerances(), KSP, KSPGetConvergenceTest(), KSPGetAndClearConvergenceTest()
1991: @*/
1992: PetscErrorCode  KSPSetConvergenceTest(KSP ksp,PetscErrorCode (*converge)(KSP,PetscInt,PetscReal,KSPConvergedReason*,void*),void *cctx,PetscErrorCode (*destroy)(void*))
1993: {

1998:   if (ksp->convergeddestroy) {
1999:     (*ksp->convergeddestroy)(ksp->cnvP);
2000:   }
2001:   ksp->converged        = converge;
2002:   ksp->convergeddestroy = destroy;
2003:   ksp->cnvP             = (void*)cctx;
2004:   return(0);
2005: }

2007: /*@C
2008:    KSPGetConvergenceTest - Gets the function to be used to determine
2009:    convergence.

2011:    Logically Collective on ksp

2013:    Input Parameter:
2014: .   ksp - iterative context obtained from KSPCreate()

2016:    Output Parameter:
2017: +  converge - pointer to convergence test function
2018: .  cctx    - context for private data for the convergence routine (may be null)
2019: -  destroy - a routine for destroying the context (may be null)

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

2024: +  ksp - iterative context obtained from KSPCreate()
2025: .  it - iteration number
2026: .  rnorm - (estimated) 2-norm of (preconditioned) residual
2027: .  reason - the reason why it has converged or diverged
2028: -  cctx  - optional convergence context, as set by KSPSetConvergenceTest()

2030:    Level: advanced

2032: .seealso: KSPConvergedDefault(), KSPGetConvergenceContext(), KSPSetTolerances(), KSP, KSPSetConvergenceTest(), KSPGetAndClearConvergenceTest()
2033: @*/
2034: PetscErrorCode  KSPGetConvergenceTest(KSP ksp,PetscErrorCode (**converge)(KSP,PetscInt,PetscReal,KSPConvergedReason*,void*),void **cctx,PetscErrorCode (**destroy)(void*))
2035: {
2038:   if (converge) *converge = ksp->converged;
2039:   if (destroy)  *destroy  = ksp->convergeddestroy;
2040:   if (cctx)     *cctx     = ksp->cnvP;
2041:   return(0);
2042: }

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

2047:    Logically Collective on ksp

2049:    Input Parameter:
2050: .   ksp - iterative context obtained from KSPCreate()

2052:    Output Parameter:
2053: +  converge - pointer to convergence test function
2054: .  cctx    - context for private data for the convergence routine
2055: -  destroy - a routine for destroying the context

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

2060: +  ksp - iterative context obtained from KSPCreate()
2061: .  it - iteration number
2062: .  rnorm - (estimated) 2-norm of (preconditioned) residual
2063: .  reason - the reason why it has converged or diverged
2064: -  cctx  - optional convergence context, as set by KSPSetConvergenceTest()

2066:    Level: advanced

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

2072: .seealso: KSPConvergedDefault(), KSPGetConvergenceContext(), KSPSetTolerances(), KSP, KSPSetConvergenceTest(), KSPGetConvergenceTest()
2073: @*/
2074: PetscErrorCode  KSPGetAndClearConvergenceTest(KSP ksp,PetscErrorCode (**converge)(KSP,PetscInt,PetscReal,KSPConvergedReason*,void*),void **cctx,PetscErrorCode (**destroy)(void*))
2075: {
2078:   *converge             = ksp->converged;
2079:   *destroy              = ksp->convergeddestroy;
2080:   *cctx                 = ksp->cnvP;
2081:   ksp->converged        = NULL;
2082:   ksp->cnvP             = NULL;
2083:   ksp->convergeddestroy = NULL;
2084:   return(0);
2085: }

2087: /*@C
2088:    KSPGetConvergenceContext - Gets the convergence context set with
2089:    KSPSetConvergenceTest().

2091:    Not Collective

2093:    Input Parameter:
2094: .  ksp - iterative context obtained from KSPCreate()

2096:    Output Parameter:
2097: .  ctx - monitoring context

2099:    Level: advanced

2101: .seealso: KSPConvergedDefault(), KSPSetConvergenceTest(), KSP
2102: @*/
2103: PetscErrorCode  KSPGetConvergenceContext(KSP ksp,void **ctx)
2104: {
2107:   *ctx = ksp->cnvP;
2108:   return(0);
2109: }

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

2115:    Collective on ksp

2117:    Input Parameter:
2118: .  ctx - iterative context obtained from KSPCreate()

2120:    Output Parameter:
2121:    Provide exactly one of
2122: +  v - location to stash solution.
2123: -  V - the solution is returned in this location. This vector is created
2124:        internally. This vector should NOT be destroyed by the user with
2125:        VecDestroy().

2127:    Notes:
2128:    This routine can be used in one of two ways
2129: .vb
2130:       KSPBuildSolution(ksp,NULL,&V);
2131:    or
2132:       KSPBuildSolution(ksp,v,NULL); or KSPBuildSolution(ksp,v,&v);
2133: .ve
2134:    In the first case an internal vector is allocated to store the solution
2135:    (the user cannot destroy this vector). In the second case the solution
2136:    is generated in the vector that the user provides. Note that for certain
2137:    methods, such as KSPCG, the second case requires a copy of the solution,
2138:    while in the first case the call is essentially free since it simply
2139:    returns the vector where the solution already is stored. For some methods
2140:    like GMRES this is a reasonably expensive operation and should only be
2141:    used in truly needed.

2143:    Level: advanced

2145: .seealso: KSPGetSolution(), KSPBuildResidual(), KSP
2146: @*/
2147: PetscErrorCode  KSPBuildSolution(KSP ksp,Vec v,Vec *V)
2148: {

2153:   if (!V && !v) SETERRQ(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_WRONG,"Must provide either v or V");
2154:   if (!V) V = &v;
2155:   (*ksp->ops->buildsolution)(ksp,v,V);
2156:   return(0);
2157: }

2159: /*@C
2160:    KSPBuildResidual - Builds the residual in a vector provided.

2162:    Collective on ksp

2164:    Input Parameter:
2165: .  ksp - iterative context obtained from KSPCreate()

2167:    Output Parameters:
2168: +  v - optional location to stash residual.  If v is not provided,
2169:        then a location is generated.
2170: .  t - work vector.  If not provided then one is generated.
2171: -  V - the residual

2173:    Notes:
2174:    Regardless of whether or not v is provided, the residual is
2175:    returned in V.

2177:    Level: advanced

2179: .seealso: KSPBuildSolution()
2180: @*/
2181: PetscErrorCode  KSPBuildResidual(KSP ksp,Vec t,Vec v,Vec *V)
2182: {
2184:   PetscBool      flag = PETSC_FALSE;
2185:   Vec            w    = v,tt = t;

2189:   if (!w) {
2190:     VecDuplicate(ksp->vec_rhs,&w);
2191:     PetscLogObjectParent((PetscObject)ksp,(PetscObject)w);
2192:   }
2193:   if (!tt) {
2194:     VecDuplicate(ksp->vec_sol,&tt); flag = PETSC_TRUE;
2195:     PetscLogObjectParent((PetscObject)ksp,(PetscObject)tt);
2196:   }
2197:   (*ksp->ops->buildresidual)(ksp,tt,w,V);
2198:   if (flag) {VecDestroy(&tt);}
2199:   return(0);
2200: }

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

2206:    Logically Collective on ksp

2208:    Input Parameter:
2209: +  ksp - the KSP context
2210: -  scale - PETSC_TRUE or PETSC_FALSE

2212:    Options Database Key:
2213: +   -ksp_diagonal_scale -
2214: -   -ksp_diagonal_scale_fix - scale the matrix back AFTER the solve


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

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

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

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

2232:    Level: intermediate

2234: .seealso: KSPGetDiagonalScale(), KSPSetDiagonalScaleFix(), KSP
2235: @*/
2236: PetscErrorCode  KSPSetDiagonalScale(KSP ksp,PetscBool scale)
2237: {
2241:   ksp->dscale = scale;
2242:   return(0);
2243: }

2245: /*@
2246:    KSPGetDiagonalScale - Checks if KSP solver scales the matrix and
2247:                           right hand side

2249:    Not Collective

2251:    Input Parameter:
2252: .  ksp - the KSP context

2254:    Output Parameter:
2255: .  scale - PETSC_TRUE or PETSC_FALSE

2257:    Notes:
2258:     BE CAREFUL with this routine: it actually scales the matrix and right
2259:     hand side that define the system. After the system is solved the matrix
2260:     and right hand side remain scaled  unless you use KSPSetDiagonalScaleFix()

2262:    Level: intermediate

2264: .seealso: KSPSetDiagonalScale(), KSPSetDiagonalScaleFix(), KSP
2265: @*/
2266: PetscErrorCode  KSPGetDiagonalScale(KSP ksp,PetscBool  *scale)
2267: {
2271:   *scale = ksp->dscale;
2272:   return(0);
2273: }

2275: /*@
2276:    KSPSetDiagonalScaleFix - Tells KSP to diagonally scale the system
2277:      back after solving.

2279:    Logically Collective on ksp

2281:    Input Parameter:
2282: +  ksp - the KSP context
2283: -  fix - PETSC_TRUE to scale back after the system solve, PETSC_FALSE to not
2284:          rescale (default)

2286:    Notes:
2287:      Must be called after KSPSetDiagonalScale()

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

2294:    Level: intermediate

2296: .seealso: KSPGetDiagonalScale(), KSPSetDiagonalScale(), KSPGetDiagonalScaleFix(), KSP
2297: @*/
2298: PetscErrorCode  KSPSetDiagonalScaleFix(KSP ksp,PetscBool fix)
2299: {
2303:   ksp->dscalefix = fix;
2304:   return(0);
2305: }

2307: /*@
2308:    KSPGetDiagonalScaleFix - Determines if KSP diagonally scales the system
2309:      back after solving.

2311:    Not Collective

2313:    Input Parameter:
2314: .  ksp - the KSP context

2316:    Output Parameter:
2317: .  fix - PETSC_TRUE to scale back after the system solve, PETSC_FALSE to not
2318:          rescale (default)

2320:    Notes:
2321:      Must be called after KSPSetDiagonalScale()

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

2328:    Level: intermediate

2330: .seealso: KSPGetDiagonalScale(), KSPSetDiagonalScale(), KSPSetDiagonalScaleFix(), KSP
2331: @*/
2332: PetscErrorCode  KSPGetDiagonalScaleFix(KSP ksp,PetscBool  *fix)
2333: {
2337:   *fix = ksp->dscalefix;
2338:   return(0);
2339: }

2341: /*@C
2342:    KSPSetComputeOperators - set routine to compute the linear operators

2344:    Logically Collective

2346:    Input Arguments:
2347: +  ksp - the KSP context
2348: .  func - function to compute the operators
2349: -  ctx - optional context

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

2354: +  ksp - the KSP context
2355: .  A - the linear operator
2356: .  B - preconditioning matrix
2357: -  ctx - optional user-provided context

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

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

2365:    Level: beginner

2367: .seealso: KSPSetOperators(), KSPSetComputeRHS(), DMKSPSetComputeOperators(), KSPSetComputeInitialGuess()
2368: @*/
2369: PetscErrorCode KSPSetComputeOperators(KSP ksp,PetscErrorCode (*func)(KSP,Mat,Mat,void*),void *ctx)
2370: {
2372:   DM             dm;

2376:   KSPGetDM(ksp,&dm);
2377:   DMKSPSetComputeOperators(dm,func,ctx);
2378:   if (ksp->setupstage == KSP_SETUP_NEWRHS) ksp->setupstage = KSP_SETUP_NEWMATRIX;
2379:   return(0);
2380: }

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

2385:    Logically Collective

2387:    Input Arguments:
2388: +  ksp - the KSP context
2389: .  func - function to compute the right hand side
2390: -  ctx - optional context

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

2395: +  ksp - the KSP context
2396: .  b - right hand side of linear system
2397: -  ctx - optional user-provided context

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

2402:    Level: beginner

2404: .seealso: KSPSolve(), DMKSPSetComputeRHS(), KSPSetComputeOperators()
2405: @*/
2406: PetscErrorCode KSPSetComputeRHS(KSP ksp,PetscErrorCode (*func)(KSP,Vec,void*),void *ctx)
2407: {
2409:   DM             dm;

2413:   KSPGetDM(ksp,&dm);
2414:   DMKSPSetComputeRHS(dm,func,ctx);
2415:   return(0);
2416: }

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

2421:    Logically Collective

2423:    Input Arguments:
2424: +  ksp - the KSP context
2425: .  func - function to compute the initial guess
2426: -  ctx - optional context

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

2431: +  ksp - the KSP context
2432: .  x - solution vector
2433: -  ctx - optional user-provided context

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

2438:    Level: beginner

2440: .seealso: KSPSolve(), KSPSetComputeRHS(), KSPSetComputeOperators(), DMKSPSetComputeInitialGuess()
2441: @*/
2442: PetscErrorCode KSPSetComputeInitialGuess(KSP ksp,PetscErrorCode (*func)(KSP,Vec,void*),void *ctx)
2443: {
2445:   DM             dm;

2449:   KSPGetDM(ksp,&dm);
2450:   DMKSPSetComputeInitialGuess(dm,func,ctx);
2451:   return(0);
2452: }