Actual source code: itfunc.c

petsc-3.8.4 2018-03-24
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: /*@
 10:    KSPComputeExtremeSingularValues - Computes the extreme singular values
 11:    for the preconditioned operator. Called after or during KSPSolve().

 13:    Not Collective

 15:    Input Parameter:
 16: .  ksp - iterative context obtained from KSPCreate()

 18:    Output Parameters:
 19: .  emin, emax - extreme singular values

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

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

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

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

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

 39:    Level: advanced

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

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

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

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

 64: /*@
 65:    KSPComputeEigenvalues - Computes the extreme eigenvalues for the
 66:    preconditioned operator. Called after or during KSPSolve().

 68:    Not Collective

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

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

 80:    Options Database Keys:
 81: +  -ksp_compute_eigenvalues - Prints eigenvalues to stdout
 82: -  -ksp_plot_eigenvalues - Plots eigenvalues in an x-window display

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

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

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

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

103:    Level: advanced

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

107: .seealso: KSPSetComputeSingularValues(), KSPMonitorSingularValue(), KSPComputeExtremeSingularValues()
108: @*/
109: PetscErrorCode  KSPComputeEigenvalues(KSP ksp,PetscInt n,PetscReal r[],PetscReal c[],PetscInt *neig)
110: {

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

121:   if (n && ksp->ops->computeeigenvalues) {
122:     (*ksp->ops->computeeigenvalues)(ksp,n,r,c,neig);
123:   } else {
124:     *neig = 0;
125:   }
126:   return(0);
127: }

129: /*@
130:    KSPComputeRitz - Computes the Ritz or harmonic Ritz pairs associated to the
131:    smallest or largest in modulus, for the preconditioned operator.
132:    Called after KSPSolve().

134:    Not Collective

136:    Input Parameter:
137: +  ksp   - iterative context obtained from KSPCreate()
138: .  ritz  - PETSC_TRUE or PETSC_FALSE for ritz pairs or harmonic Ritz pairs, respectively
139: .  small - PETSC_TRUE or PETSC_FALSE for smallest or largest (harmonic) Ritz values, respectively
140: .  nrit  - number of (harmonic) Ritz pairs to compute

142:    Output Parameters:
143: +  nrit  - actual number of computed (harmonic) Ritz pairs 
144: .  S     - multidimensional vector with Ritz vectors
145: .  tetar - real part of the Ritz values        
146: .  tetai - imaginary part of the Ritz values

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

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

163:    Level: advanced

165: .keywords: KSP, compute, ritz, values

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

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

184:    Collective on KSP

186:    Input Parameter:
187: .  ksp - the KSP context

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

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

198:    Level: advanced

200: .keywords: KSP, setup, blocks

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

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

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

224:    Collective on KSP

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

230:    Level: intermediate

232: .keywords: KSP, setup

234: .seealso: KSPCreate(), KSPSolve(), KSPDestroy(), PCSetReusePreconditioner()
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: .keywords: KSP, setup

261: .seealso: KSPCreate(), KSPSolve(), KSPDestroy(), PCSetReusePreconditioner()
262: @*/
263: PetscErrorCode  KSPSetSkipPCSetFromOptions(KSP ksp,PetscBool flag)
264: {
267:   ksp->skippcsetfromoptions = flag;
268:   return(0);
269: }

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

275:    Collective on KSP

277:    Input Parameter:
278: .  ksp   - iterative context obtained from KSPCreate()

280:    Level: developer

282: .keywords: KSP, setup

284: .seealso: KSPCreate(), KSPSolve(), KSPDestroy()
285: @*/
286: PetscErrorCode KSPSetUp(KSP ksp)
287: {
289:   Mat            A,B;
290:   Mat            mat,pmat;
291:   MatNullSpace   nullsp;
292:   PCFailedReason pcreason;
293: 

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

300:   if (!((PetscObject)ksp)->type_name) {
301:     KSPSetType(ksp,KSPGMRES);
302:   }
303:   KSPSetUpNorms_Private(ksp,PETSC_TRUE,&ksp->normtype,&ksp->pc_side);

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

314:   if (ksp->dmActive) {
315:     DMKSP kdm;
316:     DMGetDMKSP(ksp->dm,&kdm);

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

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

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

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

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

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

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

402:    Collective on KSP

404:    Parameter:
405: +  ksp - iterative context obtained from KSPCreate()
406: -  viewer - the viewer to display the reason


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

412:    Level: beginner

414: .keywords: KSP, solve, linear system

416: .seealso: KSPCreate(), KSPSetUp(), KSPDestroy(), KSPSetTolerances(), KSPConvergedDefault(),
417:           KSPSolveTranspose(), KSPGetIterationNumber()
418: @*/
419: PetscErrorCode KSPReasonView(KSP ksp,PetscViewer viewer)
420: {
422:   PetscBool      isAscii;

425:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&isAscii);
426:   if (isAscii) {
427:     PetscViewerASCIIAddTab(viewer,((PetscObject)ksp)->tablevel);
428:     if (ksp->reason > 0) {
429:       if (((PetscObject) ksp)->prefix) {
430:         PetscViewerASCIIPrintf(viewer,"Linear %s solve converged due to %s iterations %D\n",((PetscObject) ksp)->prefix,KSPConvergedReasons[ksp->reason],ksp->its);
431:       } else {
432:         PetscViewerASCIIPrintf(viewer,"Linear solve converged due to %s iterations %D\n",KSPConvergedReasons[ksp->reason],ksp->its);
433:       }
434:     } else {
435:       if (((PetscObject) ksp)->prefix) {
436:         PetscViewerASCIIPrintf(viewer,"Linear %s solve did not converge due to %s iterations %D\n",((PetscObject) ksp)->prefix,KSPConvergedReasons[ksp->reason],ksp->its);
437:       } else {
438:         PetscViewerASCIIPrintf(viewer,"Linear solve did not converge due to %s iterations %D\n",KSPConvergedReasons[ksp->reason],ksp->its);
439:       }
440:       if (ksp->reason == KSP_DIVERGED_PCSETUP_FAILED) {
441:         PCFailedReason reason;
442:         PCGetSetUpFailedReason(ksp->pc,&reason);
443:         PetscViewerASCIIPrintf(viewer,"               PCSETUP_FAILED due to %s \n",PCFailedReasons[reason]);
444:       }
445:     }
446:     PetscViewerASCIISubtractTab(viewer,((PetscObject)ksp)->tablevel);
447:   }
448:   return(0);
449: }

451: #if defined(PETSC_HAVE_THREADSAFETY)
452: #define KSPReasonViewFromOptions KSPReasonViewFromOptionsUnsafe
453: #else
454: #endif
455: /*@C
456:   KSPReasonViewFromOptions - Processes command line options to determine if/how a KSPReason is to be viewed.

458:   Collective on KSP

460:   Input Parameters:
461: . ksp   - the KSP object

463:   Level: intermediate

465: @*/
466: PetscErrorCode KSPReasonViewFromOptions(KSP ksp)
467: {
468:   PetscErrorCode    ierr;
469:   PetscViewer       viewer;
470:   PetscBool         flg;
471:   PetscViewerFormat format;

474:   PetscOptionsGetViewer(PetscObjectComm((PetscObject)ksp),((PetscObject)ksp)->prefix,"-ksp_converged_reason",&viewer,&format,&flg);
475:   if (flg) {
476:     PetscViewerPushFormat(viewer,format);
477:     KSPReasonView(ksp,viewer);
478:     PetscViewerPopFormat(viewer);
479:     PetscViewerDestroy(&viewer);
480:   }
481:   return(0);
482: }

484:  #include <petscdraw.h>
485: /*@C
486:    KSPSolve - Solves linear system.

488:    Collective on KSP

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

495:    Options Database Keys:
496: +  -ksp_compute_eigenvalues - compute preconditioned operators eigenvalues
497: .  -ksp_plot_eigenvalues - plot the computed eigenvalues in an X-window
498: .  -ksp_plot_eigencontours - plot the computed eigenvalues in an X-window with contours
499: .  -ksp_compute_eigenvalues_explicitly - compute the eigenvalues by forming the dense operator and using LAPACK
500: .  -ksp_plot_eigenvalues_explicitly - plot the explicitly computing eigenvalues
501: .  -ksp_view_mat binary - save matrix to the default binary viewer
502: .  -ksp_view_pmat binary - save matrix used to build preconditioner to the default binary viewer
503: .  -ksp_view_rhs binary - save right hand side vector to the default binary viewer
504: .  -ksp_view_solution binary - save computed solution vector to the default binary viewer
505:            (can be read later with src/ksp/examples/tutorials/ex10.c for testing solvers)
506: .  -ksp_view_mat_explicit - for matrix-free operators, computes the matrix entries and views them
507: .  -ksp_view_preconditioned_operator_explicit - computes the product of the preconditioner and matrix as an explicit matrix and views it
508: .  -ksp_converged_reason - print reason for converged or diverged, also prints number of iterations
509: .  -ksp_final_residual - print 2-norm of true linear system residual at the end of the solution process
510: -  -ksp_view - print the ksp data structure at the end of the system solution

512:    Notes:

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

516:    The operator is specified with KSPSetOperators().

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

521:    If you provide a matrix that has a MatSetNullSpace() and MatSetTransposeNullSpace() this will use that information to solve singular systems
522:    in the least squares sense with a norm minimizing solution.
523: $
524: $                   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()
525: $
526: $    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
527: $    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
528: $    direction thus the solution which is a linear combination of the search directions has no component in the nullspace(A).
529: $
530: $    We recommend always using GMRES for such singular systems.
531: $    If nullspace(A) = nullspace(A') (note symmetric matrices always satisfy this property) then both left and right preconditioning will work
532: $    If nullspace(A) != nullspace(A') then left preconditioning will work but right preconditioning may not work (or it may).

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


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

544:    Understanding Convergence:
545:    The routines KSPMonitorSet(), KSPComputeEigenvalues(), and
546:    KSPComputeEigenvaluesExplicitly() provide information on additional
547:    options to monitor convergence and print eigenvalue information.

549:    Level: beginner

551: .keywords: KSP, solve, linear system

553: .seealso: KSPCreate(), KSPSetUp(), KSPDestroy(), KSPSetTolerances(), KSPConvergedDefault(),
554:           KSPSolveTranspose(), KSPGetIterationNumber(), MatNullSpaceCreate(), MatSetNullSpace(), MatSetTransposeNullSpace()
555: @*/
556: PetscErrorCode KSPSolve(KSP ksp,Vec b,Vec x)
557: {
558:   PetscErrorCode    ierr;
559:   PetscBool         flag1,flag2,flag3,flg = PETSC_FALSE,inXisinB=PETSC_FALSE,guess_zero;
560:   Mat               mat,pmat;
561:   MPI_Comm          comm;
562:   MatNullSpace      nullsp;
563:   Vec               btmp,vec_rhs=0;

569:   comm = PetscObjectComm((PetscObject)ksp);
570:   if (x && x == b) {
571:     if (!ksp->guess_zero) SETERRQ(comm,PETSC_ERR_ARG_INCOMP,"Cannot use x == b with nonzero initial guess");
572:     VecDuplicate(b,&x);
573:     inXisinB = PETSC_TRUE;
574:   }
575:   if (b) {
576:     PetscObjectReference((PetscObject)b);
577:     VecDestroy(&ksp->vec_rhs);
578:     ksp->vec_rhs = b;
579:   }
580:   if (x) {
581:     PetscObjectReference((PetscObject)x);
582:     VecDestroy(&ksp->vec_sol);
583:     ksp->vec_sol = x;
584:   }
585:   KSPViewFromOptions(ksp,NULL,"-ksp_view_pre");

587:   if (ksp->presolve) {
588:     (*ksp->presolve)(ksp,ksp->vec_rhs,ksp->vec_sol,ksp->prectx);
589:   }
590:   PetscLogEventBegin(KSP_Solve,ksp,ksp->vec_rhs,ksp->vec_sol,0);

592:   /* reset the residual history list if requested */
593:   if (ksp->res_hist_reset) ksp->res_hist_len = 0;
594:   ksp->transpose_solve = PETSC_FALSE;

596:   if (ksp->guess) {
597:     PetscObjectState ostate,state;

599:     KSPGuessSetUp(ksp->guess);
600:     PetscObjectStateGet((PetscObject)ksp->vec_sol,&ostate);
601:     KSPGuessFormGuess(ksp->guess,ksp->vec_rhs,ksp->vec_sol);
602:     PetscObjectStateGet((PetscObject)ksp->vec_sol,&state);
603:     if (state != ostate) {
604:       ksp->guess_zero = PETSC_FALSE;
605:     } else {
606:       PetscInfo(ksp,"Using zero initial guess since the KSPGuess object did not change the vector\n");
607:       ksp->guess_zero = PETSC_TRUE;
608:     }
609:   }

611:   /* KSPSetUp() scales the matrix if needed */
612:   KSPSetUp(ksp);
613:   KSPSetUpOnBlocks(ksp);

615:   VecLocked(ksp->vec_sol,3);

617:   PCGetOperators(ksp->pc,&mat,&pmat);
618:   /* diagonal scale RHS if called for */
619:   if (ksp->dscale) {
620:     VecPointwiseMult(ksp->vec_rhs,ksp->vec_rhs,ksp->diagonal);
621:     /* second time in, but matrix was scaled back to original */
622:     if (ksp->dscalefix && ksp->dscalefix2) {
623:       Mat mat,pmat;

625:       PCGetOperators(ksp->pc,&mat,&pmat);
626:       MatDiagonalScale(pmat,ksp->diagonal,ksp->diagonal);
627:       if (mat != pmat) {MatDiagonalScale(mat,ksp->diagonal,ksp->diagonal);}
628:     }

630:     /* scale initial guess */
631:     if (!ksp->guess_zero) {
632:       if (!ksp->truediagonal) {
633:         VecDuplicate(ksp->diagonal,&ksp->truediagonal);
634:         VecCopy(ksp->diagonal,ksp->truediagonal);
635:         VecReciprocal(ksp->truediagonal);
636:       }
637:       VecPointwiseMult(ksp->vec_sol,ksp->vec_sol,ksp->truediagonal);
638:     }
639:   }
640:   PCPreSolve(ksp->pc,ksp);

642:   if (ksp->guess_zero) { VecSet(ksp->vec_sol,0.0);}
643:   if (ksp->guess_knoll) { /* The Knoll trick is independent on the KSPGuess specified */
644:     PCApply(ksp->pc,ksp->vec_rhs,ksp->vec_sol);
645:     KSP_RemoveNullSpace(ksp,ksp->vec_sol);
646:     ksp->guess_zero = PETSC_FALSE;
647:   }

649:   /* can we mark the initial guess as zero for this solve? */
650:   guess_zero = ksp->guess_zero;
651:   if (!ksp->guess_zero) {
652:     PetscReal norm;

654:     VecNormAvailable(ksp->vec_sol,NORM_2,&flg,&norm);
655:     if (flg && !norm) ksp->guess_zero = PETSC_TRUE;
656:   }
657:   MatGetTransposeNullSpace(pmat,&nullsp);
658:   if (nullsp) {
659:     VecDuplicate(ksp->vec_rhs,&btmp);
660:     VecCopy(ksp->vec_rhs,btmp);
661:     MatNullSpaceRemove(nullsp,btmp);
662:     vec_rhs      = ksp->vec_rhs;
663:     ksp->vec_rhs = btmp;
664:   }
665:   VecLockPush(ksp->vec_rhs);
666:   if (ksp->reason == KSP_DIVERGED_PCSETUP_FAILED) {
667:     VecSetInf(ksp->vec_sol);
668:   }
669:   (*ksp->ops->solve)(ksp);
670: 
671:   VecLockPop(ksp->vec_rhs);
672:   if (nullsp) {
673:     ksp->vec_rhs = vec_rhs;
674:     VecDestroy(&btmp);
675:   }

677:   ksp->guess_zero = guess_zero;


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

683:   KSPReasonViewFromOptions(ksp);
684:   PCPostSolve(ksp->pc,ksp);

686:   /* diagonal scale solution if called for */
687:   if (ksp->dscale) {
688:     VecPointwiseMult(ksp->vec_sol,ksp->vec_sol,ksp->diagonal);
689:     /* unscale right hand side and matrix */
690:     if (ksp->dscalefix) {
691:       Mat mat,pmat;

693:       VecReciprocal(ksp->diagonal);
694:       VecPointwiseMult(ksp->vec_rhs,ksp->vec_rhs,ksp->diagonal);
695:       PCGetOperators(ksp->pc,&mat,&pmat);
696:       MatDiagonalScale(pmat,ksp->diagonal,ksp->diagonal);
697:       if (mat != pmat) {MatDiagonalScale(mat,ksp->diagonal,ksp->diagonal);}
698:       VecReciprocal(ksp->diagonal);
699:       ksp->dscalefix2 = PETSC_TRUE;
700:     }
701:   }
702:   PetscLogEventEnd(KSP_Solve,ksp,ksp->vec_rhs,ksp->vec_sol,0);
703:   if (ksp->postsolve) {
704:     (*ksp->postsolve)(ksp,ksp->vec_rhs,ksp->vec_sol,ksp->postctx);
705:   }
706:   if (ksp->guess) {
707:     KSPGuessUpdate(ksp->guess,ksp->vec_rhs,ksp->vec_sol);
708:   }

710:   PCGetOperators(ksp->pc,&mat,&pmat);
711:   MatViewFromOptions(mat,(PetscObject)ksp,"-ksp_view_mat");
712:   MatViewFromOptions(pmat,(PetscObject)ksp,"-ksp_view_pmat");
713:   VecViewFromOptions(ksp->vec_rhs,(PetscObject)ksp,"-ksp_view_rhs");

715:   PetscOptionsGetViewer(PetscObjectComm((PetscObject)ksp),((PetscObject)ksp)->prefix,"-ksp_compute_eigenvalues",NULL,NULL,&flag1);
716:   PetscOptionsGetViewer(PetscObjectComm((PetscObject)ksp),((PetscObject)ksp)->prefix,"-ksp_plot_eigenvalues",NULL,NULL,&flag2);
717:   PetscOptionsGetViewer(PetscObjectComm((PetscObject)ksp),((PetscObject)ksp)->prefix,"-ksp_plot_eigencontours",NULL,NULL,&flag3);
718:   if (flag1 || flag2 || flag3) {
719:     PetscInt    nits,n,i,neig;
720:     PetscReal   *r,*c;

722:     KSPGetIterationNumber(ksp,&nits);
723:     n    = nits+2;

725:     if (!nits) {
726:       PetscPrintf(comm,"Zero iterations in solver, cannot approximate any eigenvalues\n");
727:     } else {
728:       PetscMPIInt rank;
729:       MPI_Comm_rank(comm,&rank);
730:       PetscMalloc2(n,&r,n,&c);
731:       KSPComputeEigenvalues(ksp,n,r,c,&neig);
732:       if (flag1) {
733:         PetscPrintf(comm,"Iteratively computed eigenvalues\n");
734:         for (i=0; i<neig; i++) {
735:           if (c[i] >= 0.0) {
736:             PetscPrintf(comm,"%g + %gi\n",(double)r[i],(double)c[i]);
737:           } else {
738:             PetscPrintf(comm,"%g - %gi\n",(double)r[i],-(double)c[i]);
739:           }
740:         }
741:       }
742:       if (flag2 && !rank) {
743:         PetscDraw   draw;
744:         PetscDrawSP drawsp;

746:         if (!ksp->eigviewer) {
747:           PetscViewerDrawOpen(PETSC_COMM_SELF,0,"Iteratively Computed Eigenvalues",PETSC_DECIDE,PETSC_DECIDE,400,400,&ksp->eigviewer);
748:         }
749:         PetscViewerDrawGetDraw(ksp->eigviewer,0,&draw);
750:         PetscDrawSPCreate(draw,1,&drawsp);
751:         for (i=0; i<neig; i++) {
752:           PetscDrawSPAddPoint(drawsp,r+i,c+i);
753:         }
754:         PetscDrawSPDraw(drawsp,PETSC_TRUE);
755:         PetscDrawSPSave(drawsp);
756:         PetscDrawSPDestroy(&drawsp);
757:       }
758:       if (flag3 && !rank) {
759:         KSPPlotEigenContours_Private(ksp,neig,r,c);
760:       }
761:       PetscFree2(r,c);
762:     }
763:   }

765:   PetscOptionsGetViewer(PetscObjectComm((PetscObject)ksp),((PetscObject)ksp)->prefix,"-ksp_compute_singularvalues",NULL,NULL,&flag1);
766:   if (flag1) {
767:     PetscInt nits;

769:     KSPGetIterationNumber(ksp,&nits);
770:     if (!nits) {
771:       PetscPrintf(comm,"Zero iterations in solver, cannot approximate any singular values\n");
772:     } else {
773:       PetscReal emax,emin;

775:       KSPComputeExtremeSingularValues(ksp,&emax,&emin);
776:       PetscPrintf(comm,"Iteratively computed extreme singular values: max %g min %g max/min %g\n",(double)emax,(double)emin,(double)(emax/emin));
777:     }
778:   }

780:   PetscOptionsGetViewer(PetscObjectComm((PetscObject)ksp),((PetscObject)ksp)->prefix,"-ksp_compute_eigenvalues_explicitly",NULL,NULL,&flag1);
781:   PetscOptionsGetViewer(PetscObjectComm((PetscObject)ksp),((PetscObject)ksp)->prefix,"-ksp_plot_eigenvalues_explicitly",NULL,NULL,&flag2);
782:   if (flag1 || flag2) {
783:     PetscInt    n,i;
784:     PetscReal   *r,*c;
785:     PetscMPIInt rank;
786:     MPI_Comm_rank(comm,&rank);
787:     VecGetSize(ksp->vec_sol,&n);
788:     PetscMalloc2(n,&r,n,&c);
789:     KSPComputeEigenvaluesExplicitly(ksp,n,r,c);
790:     if (flag1) {
791:       PetscPrintf(comm,"Explicitly computed eigenvalues\n");
792:       for (i=0; i<n; i++) {
793:         if (c[i] >= 0.0) {
794:           PetscPrintf(comm,"%g + %gi\n",(double)r[i],(double)c[i]);
795:         } else {
796:           PetscPrintf(comm,"%g - %gi\n",(double)r[i],-(double)c[i]);
797:         }
798:       }
799:     }
800:     if (flag2 && !rank) {
801:       PetscDraw   draw;
802:       PetscDrawSP drawsp;

804:       if (!ksp->eigviewer) {
805:         PetscViewerDrawOpen(PETSC_COMM_SELF,0,"Explicitly Computed Eigenvalues",PETSC_DECIDE,PETSC_DECIDE,400,400,&ksp->eigviewer);
806:       }
807:       PetscViewerDrawGetDraw(ksp->eigviewer,0,&draw);
808:       PetscDrawSPCreate(draw,1,&drawsp);
809:       PetscDrawSPReset(drawsp);
810:       for (i=0; i<n; i++) {
811:         PetscDrawSPAddPoint(drawsp,r+i,c+i);
812:       }
813:       PetscDrawSPDraw(drawsp,PETSC_TRUE);
814:       PetscDrawSPSave(drawsp);
815:       PetscDrawSPDestroy(&drawsp);
816:     }
817:     PetscFree2(r,c);
818:   }

820:   PetscOptionsGetViewer(PetscObjectComm((PetscObject)ksp),((PetscObject)ksp)->prefix,"-ksp_view_mat_explicit",NULL,NULL,&flag2);
821:   if (flag2) {
822:     Mat A,B;
823:     PCGetOperators(ksp->pc,&A,NULL);
824:     MatComputeExplicitOperator(A,&B);
825:     MatViewFromOptions(B,(PetscObject)ksp,"-ksp_view_mat_explicit");
826:     MatDestroy(&B);
827:   }
828:   PetscOptionsGetViewer(PetscObjectComm((PetscObject)ksp),((PetscObject)ksp)->prefix,"-ksp_view_preconditioned_operator_explicit",NULL,NULL,&flag2);
829:   if (flag2) {
830:     Mat B;
831:     KSPComputeExplicitOperator(ksp,&B);
832:     MatViewFromOptions(B,(PetscObject)ksp,"-ksp_view_preconditioned_operator_explicit");
833:     MatDestroy(&B);
834:   }
835:   KSPViewFromOptions(ksp,NULL,"-ksp_view");

837:   PetscOptionsGetViewer(PetscObjectComm((PetscObject)ksp),((PetscObject)ksp)->prefix,"-ksp_final_residual",NULL,NULL,&flg);
838:   if (flg) {
839:     Mat       A;
840:     Vec       t;
841:     PetscReal norm;
842:     if (ksp->dscale && !ksp->dscalefix) SETERRQ(comm,PETSC_ERR_ARG_WRONGSTATE,"Cannot compute final scale with -ksp_diagonal_scale except also with -ksp_diagonal_scale_fix");
843:     PCGetOperators(ksp->pc,&A,NULL);
844:     VecDuplicate(ksp->vec_rhs,&t);
845:     KSP_MatMult(ksp,A,ksp->vec_sol,t);
846:     VecAYPX(t, -1.0, ksp->vec_rhs);
847:     VecNorm(t,NORM_2,&norm);
848:     VecDestroy(&t);
849:     PetscPrintf(comm,"KSP final norm of residual %g\n",(double)norm);
850:   }
851:   VecViewFromOptions(ksp->vec_sol,(PetscObject)ksp,"-ksp_view_solution");

853:   if (inXisinB) {
854:     VecCopy(x,b);
855:     VecDestroy(&x);
856:   }
857:   PetscObjectSAWsBlock((PetscObject)ksp);
858:   if (ksp->errorifnotconverged && ksp->reason < 0) SETERRQ(comm,PETSC_ERR_NOT_CONVERGED,"KSPSolve has not converged");
859:   return(0);
860: }

862: /*@
863:    KSPSolveTranspose - Solves the transpose of a linear system.

865:    Collective on KSP

867:    Input Parameter:
868: +  ksp - iterative context obtained from KSPCreate()
869: .  b - right hand side vector
870: -  x - solution vector

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

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

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

878:    Level: developer

880: .keywords: KSP, solve, linear system

882: .seealso: KSPCreate(), KSPSetUp(), KSPDestroy(), KSPSetTolerances(), KSPConvergedDefault(),
883:           KSPSolve()
884: @*/

886: PetscErrorCode  KSPSolveTranspose(KSP ksp,Vec b,Vec x)
887: {
889:   PetscBool      inXisinB=PETSC_FALSE;
890:   Vec            vec_rhs = 0,btmp;
891:   Mat            mat,pmat;
892:   MatNullSpace   nullsp;

898:   if (x == b) {
899:     VecDuplicate(b,&x);
900:     inXisinB = PETSC_TRUE;
901:   }
902:   PetscObjectReference((PetscObject)b);
903:   PetscObjectReference((PetscObject)x);
904:   VecDestroy(&ksp->vec_rhs);
905:   VecDestroy(&ksp->vec_sol);

907:   ksp->vec_rhs         = b;
908:   ksp->vec_sol         = x;
909:   ksp->transpose_solve = PETSC_TRUE;

911:   KSPSetUp(ksp);
912:   KSPSetUpOnBlocks(ksp);
913:   if (ksp->guess_zero) { VecSet(ksp->vec_sol,0.0);}

915:   PCGetOperators(ksp->pc,&mat,&pmat);
916:   MatGetNullSpace(pmat,&nullsp);
917:   if (nullsp) {
918:     VecDuplicate(ksp->vec_rhs,&btmp);
919:     VecCopy(ksp->vec_rhs,btmp);
920:     MatNullSpaceRemove(nullsp,btmp);
921:     vec_rhs      = ksp->vec_rhs;
922:     ksp->vec_rhs = btmp;
923:   }

925:   (*ksp->ops->solve)(ksp);
926:   if (nullsp) {
927:     ksp->vec_rhs = vec_rhs;
928:     VecDestroy(&btmp);
929:   }
930:   if (!ksp->reason) SETERRQ(PetscObjectComm((PetscObject)ksp),PETSC_ERR_PLIB,"Internal error, solver returned without setting converged reason");
931:   KSPReasonViewFromOptions(ksp);

933:   MatViewFromOptions(mat,(PetscObject)ksp,"-ksp_view_mat");
934:   MatViewFromOptions(pmat,(PetscObject)ksp,"-ksp_view_pmat");
935:   VecViewFromOptions(ksp->vec_rhs,(PetscObject)ksp,"-ksp_view_rhs");
936:   VecViewFromOptions(ksp->vec_sol,(PetscObject)ksp,"-ksp_view_solution");

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

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

949:    Collective on KSP

951:    Input Parameter:
952: .  ksp - iterative context obtained from KSPCreate()

954:    Level: beginner

956: .keywords: KSP, destroy

958: .seealso: KSPCreate(), KSPSetUp(), KSPSolve()
959: @*/
960: PetscErrorCode  KSPReset(KSP ksp)
961: {

966:   if (!ksp) return(0);
967:   if (ksp->ops->reset) {
968:     (*ksp->ops->reset)(ksp);
969:   }
970:   if (ksp->pc) {PCReset(ksp->pc);}
971:   if (ksp->guess) {
972:     KSPGuess guess = ksp->guess;
973:     if (guess->ops->reset) { (*guess->ops->reset)(guess); }
974:   }
975:   VecDestroyVecs(ksp->nwork,&ksp->work);
976:   VecDestroy(&ksp->vec_rhs);
977:   VecDestroy(&ksp->vec_sol);
978:   VecDestroy(&ksp->diagonal);
979:   VecDestroy(&ksp->truediagonal);

981:   ksp->setupstage = KSP_SETUP_NEW;
982:   return(0);
983: }

985: /*@
986:    KSPDestroy - Destroys KSP context.

988:    Collective on KSP

990:    Input Parameter:
991: .  ksp - iterative context obtained from KSPCreate()

993:    Level: beginner

995: .keywords: KSP, destroy

997: .seealso: KSPCreate(), KSPSetUp(), KSPSolve()
998: @*/
999: PetscErrorCode  KSPDestroy(KSP *ksp)
1000: {
1002:   PC             pc;

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

1009:   PetscObjectSAWsViewOff((PetscObject)*ksp);
1010:   /*
1011:    Avoid a cascading call to PCReset(ksp->pc) from the following call:
1012:    PCReset() shouldn't be called from KSPDestroy() as it is unprotected by pc's
1013:    refcount (and may be shared, e.g., by other ksps).
1014:    */
1015:   pc         = (*ksp)->pc;
1016:   (*ksp)->pc = NULL;
1017:   KSPReset((*ksp));
1018:   (*ksp)->pc = pc;
1019:     if ((*ksp)->ops->destroy) {(*(*ksp)->ops->destroy)(*ksp);}

1021:   DMDestroy(&(*ksp)->dm);
1022:   PCDestroy(&(*ksp)->pc);
1023:   PetscFree((*ksp)->res_hist_alloc);
1024:   if ((*ksp)->convergeddestroy) {
1025:     (*(*ksp)->convergeddestroy)((*ksp)->cnvP);
1026:   }
1027:   KSPMonitorCancel((*ksp));
1028:   PetscViewerDestroy(&(*ksp)->eigviewer);
1029:   PetscHeaderDestroy(ksp);
1030:   return(0);
1031: }

1033: /*@
1034:     KSPSetPCSide - Sets the preconditioning side.

1036:     Logically Collective on KSP

1038:     Input Parameter:
1039: .   ksp - iterative context obtained from KSPCreate()

1041:     Output Parameter:
1042: .   side - the preconditioning side, where side is one of
1043: .vb
1044:       PC_LEFT - left preconditioning (default)
1045:       PC_RIGHT - right preconditioning
1046:       PC_SYMMETRIC - symmetric preconditioning
1047: .ve

1049:     Options Database Keys:
1050: .   -ksp_pc_side <right,left,symmetric>

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

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

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

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

1063:     Level: intermediate

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

1067: .seealso: KSPGetPCSide(), KSPSetNormType(), KSPGetNormType()
1068: @*/
1069: PetscErrorCode  KSPSetPCSide(KSP ksp,PCSide side)
1070: {
1074:   ksp->pc_side = ksp->pc_side_set = side;
1075:   return(0);
1076: }

1078: /*@
1079:     KSPGetPCSide - Gets the preconditioning side.

1081:     Not Collective

1083:     Input Parameter:
1084: .   ksp - iterative context obtained from KSPCreate()

1086:     Output Parameter:
1087: .   side - the preconditioning side, where side is one of
1088: .vb
1089:       PC_LEFT - left preconditioning (default)
1090:       PC_RIGHT - right preconditioning
1091:       PC_SYMMETRIC - symmetric preconditioning
1092: .ve

1094:     Level: intermediate

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

1098: .seealso: KSPSetPCSide()
1099: @*/
1100: PetscErrorCode  KSPGetPCSide(KSP ksp,PCSide *side)
1101: {

1107:   KSPSetUpNorms_Private(ksp,PETSC_TRUE,&ksp->normtype,&ksp->pc_side);
1108:   *side = ksp->pc_side;
1109:   return(0);
1110: }

1112: /*@
1113:    KSPGetTolerances - Gets the relative, absolute, divergence, and maximum
1114:    iteration tolerances used by the default KSP convergence tests.

1116:    Not Collective

1118:    Input Parameter:
1119: .  ksp - the Krylov subspace context

1121:    Output Parameters:
1122: +  rtol - the relative convergence tolerance
1123: .  abstol - the absolute convergence tolerance
1124: .  dtol - the divergence tolerance
1125: -  maxits - maximum number of iterations

1127:    Notes:
1128:    The user can specify NULL for any parameter that is not needed.

1130:    Level: intermediate

1132: .keywords: KSP, get, tolerance, absolute, relative, divergence, convergence,
1133:            maximum, iterations

1135: .seealso: KSPSetTolerances()
1136: @*/
1137: PetscErrorCode  KSPGetTolerances(KSP ksp,PetscReal *rtol,PetscReal *abstol,PetscReal *dtol,PetscInt *maxits)
1138: {
1141:   if (abstol) *abstol = ksp->abstol;
1142:   if (rtol) *rtol = ksp->rtol;
1143:   if (dtol) *dtol = ksp->divtol;
1144:   if (maxits) *maxits = ksp->max_it;
1145:   return(0);
1146: }

1148: /*@
1149:    KSPSetTolerances - Sets the relative, absolute, divergence, and maximum
1150:    iteration tolerances used by the default KSP convergence testers.

1152:    Logically Collective on KSP

1154:    Input Parameters:
1155: +  ksp - the Krylov subspace context
1156: .  rtol - the relative convergence tolerance, relative decrease in the (possibly preconditioned) residual norm
1157: .  abstol - the absolute convergence tolerance   absolute size of the (possibly preconditioned) residual norm
1158: .  dtol - the divergence tolerance,   amount (possibly preconditioned) residual norm can increase before KSPConvergedDefault() concludes that the method is diverging
1159: -  maxits - maximum number of iterations to use

1161:    Options Database Keys:
1162: +  -ksp_atol <abstol> - Sets abstol
1163: .  -ksp_rtol <rtol> - Sets rtol
1164: .  -ksp_divtol <dtol> - Sets dtol
1165: -  -ksp_max_it <maxits> - Sets maxits

1167:    Notes:
1168:    Use PETSC_DEFAULT to retain the default value of any of the tolerances.

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

1173:    Level: intermediate

1175: .keywords: KSP, set, tolerance, absolute, relative, divergence,
1176:            convergence, maximum, iterations

1178: .seealso: KSPGetTolerances(), KSPConvergedDefault(), KSPSetConvergenceTest()
1179: @*/
1180: PetscErrorCode  KSPSetTolerances(KSP ksp,PetscReal rtol,PetscReal abstol,PetscReal dtol,PetscInt maxits)
1181: {

1189:   if (rtol != PETSC_DEFAULT) {
1190:     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);
1191:     ksp->rtol = rtol;
1192:   }
1193:   if (abstol != PETSC_DEFAULT) {
1194:     if (abstol < 0.0) SETERRQ1(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_OUTOFRANGE,"Absolute tolerance %g must be non-negative",(double)abstol);
1195:     ksp->abstol = abstol;
1196:   }
1197:   if (dtol != PETSC_DEFAULT) {
1198:     if (dtol < 0.0) SETERRQ1(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_OUTOFRANGE,"Divergence tolerance %g must be larger than 1.0",(double)dtol);
1199:     ksp->divtol = dtol;
1200:   }
1201:   if (maxits != PETSC_DEFAULT) {
1202:     if (maxits < 0) SETERRQ1(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of iterations %D must be non-negative",maxits);
1203:     ksp->max_it = maxits;
1204:   }
1205:   return(0);
1206: }

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

1213:    Logically Collective on KSP

1215:    Input Parameters:
1216: +  ksp - iterative context obtained from KSPCreate()
1217: -  flg - PETSC_TRUE indicates the guess is non-zero, PETSC_FALSE indicates the guess is zero

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

1222:    Level: beginner

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

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

1229: .seealso: KSPGetInitialGuessNonzero(), KSPSetGuessType(), KSPGuessType
1230: @*/
1231: PetscErrorCode  KSPSetInitialGuessNonzero(KSP ksp,PetscBool flg)
1232: {
1236:   ksp->guess_zero = (PetscBool) !(int)flg;
1237:   return(0);
1238: }

1240: /*@
1241:    KSPGetInitialGuessNonzero - Determines whether the KSP solver is using
1242:    a zero initial guess.

1244:    Not Collective

1246:    Input Parameter:
1247: .  ksp - iterative context obtained from KSPCreate()

1249:    Output Parameter:
1250: .  flag - PETSC_TRUE if guess is nonzero, else PETSC_FALSE

1252:    Level: intermediate

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

1256: .seealso: KSPSetInitialGuessNonzero()
1257: @*/
1258: PetscErrorCode  KSPGetInitialGuessNonzero(KSP ksp,PetscBool  *flag)
1259: {
1263:   if (ksp->guess_zero) *flag = PETSC_FALSE;
1264:   else *flag = PETSC_TRUE;
1265:   return(0);
1266: }

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

1271:    Logically Collective on KSP

1273:    Input Parameters:
1274: +  ksp - iterative context obtained from KSPCreate()
1275: -  flg - PETSC_TRUE indicates you want the error generated

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

1280:    Level: intermediate

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

1286: .keywords: KSP

1288: .seealso: KSPGetErrorIfNotConverged()
1289: @*/
1290: PetscErrorCode  KSPSetErrorIfNotConverged(KSP ksp,PetscBool flg)
1291: {
1295:   ksp->errorifnotconverged = flg;
1296:   return(0);
1297: }

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

1302:    Not Collective

1304:    Input Parameter:
1305: .  ksp - iterative context obtained from KSPCreate()

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

1310:    Level: intermediate

1312: .keywords: KSP

1314: .seealso: KSPSetErrorIfNotConverged()
1315: @*/
1316: PetscErrorCode  KSPGetErrorIfNotConverged(KSP ksp,PetscBool  *flag)
1317: {
1321:   *flag = ksp->errorifnotconverged;
1322:   return(0);
1323: }

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

1328:    Logically Collective on KSP

1330:    Input Parameters:
1331: +  ksp - iterative context obtained from KSPCreate()
1332: -  flg - PETSC_TRUE or PETSC_FALSE

1334:    Level: advanced

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

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

1340: .seealso: KSPGetInitialGuessKnoll(), KSPSetInitialGuessNonzero(), KSPGetInitialGuessNonzero()
1341: @*/
1342: PetscErrorCode  KSPSetInitialGuessKnoll(KSP ksp,PetscBool flg)
1343: {
1347:   ksp->guess_knoll = flg;
1348:   return(0);
1349: }

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

1355:    Not Collective

1357:    Input Parameter:
1358: .  ksp - iterative context obtained from KSPCreate()

1360:    Output Parameter:
1361: .  flag - PETSC_TRUE if using Knoll trick, else PETSC_FALSE

1363:    Level: advanced

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

1367: .seealso: KSPSetInitialGuessKnoll(), KSPSetInitialGuessNonzero(), KSPGetInitialGuessNonzero()
1368: @*/
1369: PetscErrorCode  KSPGetInitialGuessKnoll(KSP ksp,PetscBool  *flag)
1370: {
1374:   *flag = ksp->guess_knoll;
1375:   return(0);
1376: }

1378: /*@
1379:    KSPGetComputeSingularValues - Gets the flag indicating whether the extreme singular
1380:    values will be calculated via a Lanczos or Arnoldi process as the linear
1381:    system is solved.

1383:    Not Collective

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

1388:    Output Parameter:
1389: .  flg - PETSC_TRUE or PETSC_FALSE

1391:    Options Database Key:
1392: .  -ksp_monitor_singular_value - Activates KSPSetComputeSingularValues()

1394:    Notes:
1395:    Currently this option is not valid for all iterative methods.

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

1401:    Level: advanced

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

1405: .seealso: KSPComputeExtremeSingularValues(), KSPMonitorSingularValue()
1406: @*/
1407: PetscErrorCode  KSPGetComputeSingularValues(KSP ksp,PetscBool  *flg)
1408: {
1412:   *flg = ksp->calc_sings;
1413:   return(0);
1414: }

1416: /*@
1417:    KSPSetComputeSingularValues - Sets a flag so that the extreme singular
1418:    values will be calculated via a Lanczos or Arnoldi process as the linear
1419:    system is solved.

1421:    Logically Collective on KSP

1423:    Input Parameters:
1424: +  ksp - iterative context obtained from KSPCreate()
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: .keywords: KSP, set, compute, singular values

1441: .seealso: KSPComputeExtremeSingularValues(), KSPMonitorSingularValue()
1442: @*/
1443: PetscErrorCode  KSPSetComputeSingularValues(KSP ksp,PetscBool flg)
1444: {
1448:   ksp->calc_sings = flg;
1449:   return(0);
1450: }

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

1457:    Not Collective

1459:    Input Parameter:
1460: .  ksp - iterative context obtained from KSPCreate()

1462:    Output Parameter:
1463: .  flg - PETSC_TRUE or PETSC_FALSE

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

1468:    Level: advanced

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

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

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

1488:    Logically Collective on KSP

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

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

1497:    Level: advanced

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

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

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

1517:    Logically Collective on KSP

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

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

1526:    Level: advanced

1528: .keywords: KSP, set, compute, ritz

1530: .seealso: KSPComputeRitz()
1531: @*/
1532: PetscErrorCode  KSPSetComputeRitz(KSP ksp, PetscBool flg)
1533: {
1537:   ksp->calc_ritz = flg;
1538:   return(0);
1539: }

1541: /*@
1542:    KSPGetRhs - Gets the right-hand-side vector for the linear system to
1543:    be solved.

1545:    Not Collective

1547:    Input Parameter:
1548: .  ksp - iterative context obtained from KSPCreate()

1550:    Output Parameter:
1551: .  r - right-hand-side vector

1553:    Level: developer

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

1557: .seealso: KSPGetSolution(), KSPSolve()
1558: @*/
1559: PetscErrorCode  KSPGetRhs(KSP ksp,Vec *r)
1560: {
1564:   *r = ksp->vec_rhs;
1565:   return(0);
1566: }

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

1573:    Not Collective

1575:    Input Parameters:
1576: .  ksp - iterative context obtained from KSPCreate()

1578:    Output Parameters:
1579: .  v - solution vector

1581:    Level: developer

1583: .keywords: KSP, get, solution

1585: .seealso: KSPGetRhs(),  KSPBuildSolution(), KSPSolve()
1586: @*/
1587: PetscErrorCode  KSPGetSolution(KSP ksp,Vec *v)
1588: {
1592:   *v = ksp->vec_sol;
1593:   return(0);
1594: }

1596: /*@
1597:    KSPSetPC - Sets the preconditioner to be used to calculate the
1598:    application of the preconditioner on a vector.

1600:    Collective on KSP

1602:    Input Parameters:
1603: +  ksp - iterative context obtained from KSPCreate()
1604: -  pc   - the preconditioner object

1606:    Notes:
1607:    Use KSPGetPC() to retrieve the preconditioner context (for example,
1608:    to free it at the end of the computations).

1610:    Level: developer

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

1614: .seealso: KSPGetPC()
1615: @*/
1616: PetscErrorCode  KSPSetPC(KSP ksp,PC pc)
1617: {

1624:   PetscObjectReference((PetscObject)pc);
1625:   PCDestroy(&ksp->pc);
1626:   ksp->pc = pc;
1627:   PetscLogObjectParent((PetscObject)ksp,(PetscObject)ksp->pc);
1628:   return(0);
1629: }

1631: /*@
1632:    KSPGetPC - Returns a pointer to the preconditioner context
1633:    set with KSPSetPC().

1635:    Not Collective

1637:    Input Parameters:
1638: .  ksp - iterative context obtained from KSPCreate()

1640:    Output Parameter:
1641: .  pc - preconditioner context

1643:    Level: developer

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

1647: .seealso: KSPSetPC()
1648: @*/
1649: PetscErrorCode  KSPGetPC(KSP ksp,PC *pc)
1650: {

1656:   if (!ksp->pc) {
1657:     PCCreate(PetscObjectComm((PetscObject)ksp),&ksp->pc);
1658:     PetscObjectIncrementTabLevel((PetscObject)ksp->pc,(PetscObject)ksp,0);
1659:     PetscLogObjectParent((PetscObject)ksp,(PetscObject)ksp->pc);
1660:   }
1661:   *pc = ksp->pc;
1662:   return(0);
1663: }

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

1668:    Collective on KSP

1670:    Input Parameters:
1671: +  ksp - iterative context obtained from KSPCreate()
1672: .  it - iteration number
1673: -  rnorm - relative norm of the residual

1675:    Notes:
1676:    This routine is called by the KSP implementations.
1677:    It does not typically need to be called by the user.

1679:    Level: developer

1681: .seealso: KSPMonitorSet()
1682: @*/
1683: PetscErrorCode KSPMonitor(KSP ksp,PetscInt it,PetscReal rnorm)
1684: {
1685:   PetscInt       i, n = ksp->numbermonitors;

1689:   for (i=0; i<n; i++) {
1690:     (*ksp->monitor[i])(ksp,it,rnorm,ksp->monitorcontext[i]);
1691:   }
1692:   return(0);
1693: }

1695: /*

1697:     Checks if two monitors are identical; if they are then it destroys the new one
1698: */
1699: PetscErrorCode PetscMonitorCompare(PetscErrorCode (*nmon)(void),void *nmctx,PetscErrorCode (*nmdestroy)(void**),PetscErrorCode (*mon)(void),void *mctx,PetscErrorCode (*mdestroy)(void**),PetscBool *identical)
1700: {
1701:   *identical = PETSC_FALSE;
1702:   if (nmon == mon && nmdestroy == mdestroy) {
1703:     if (nmctx == mctx) *identical = PETSC_TRUE;
1704:     else if (nmdestroy == (PetscErrorCode (*)(void**)) PetscViewerAndFormatDestroy) {
1705:       PetscViewerAndFormat *old = (PetscViewerAndFormat*)mctx, *newo = (PetscViewerAndFormat*)nmctx;
1706:       if (old->viewer == newo->viewer && old->format == newo->format) *identical = PETSC_TRUE;
1707:     }
1708:     if (*identical) {
1709:       if (mdestroy) {
1711:         (*mdestroy)(&nmctx);
1712:       }
1713:     }
1714:   }
1715:   return(0);
1716: }

1718: /*@C
1719:    KSPMonitorSet - Sets an ADDITIONAL function to be called at every iteration to monitor
1720:    the residual/error etc.

1722:    Logically Collective on KSP

1724:    Input Parameters:
1725: +  ksp - iterative context obtained from KSPCreate()
1726: .  monitor - pointer to function (if this is NULL, it turns off monitoring
1727: .  mctx    - [optional] context for private data for the
1728:              monitor routine (use NULL if no context is desired)
1729: -  monitordestroy - [optional] routine that frees monitor context
1730:           (may be NULL)

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

1735: +  ksp - iterative context obtained from KSPCreate()
1736: .  it - iteration number
1737: .  rnorm - (estimated) 2-norm of (preconditioned) residual
1738: -  mctx  - optional monitoring context, as set by KSPMonitorSet()

1740:    Options Database Keys:
1741: +    -ksp_monitor        - sets KSPMonitorDefault()
1742: .    -ksp_monitor_true_residual    - sets KSPMonitorTrueResidualNorm()
1743: .    -ksp_monitor_max    - sets KSPMonitorTrueResidualMaxNorm()
1744: .    -ksp_monitor_lg_residualnorm    - sets line graph monitor,
1745:                            uses KSPMonitorLGResidualNormCreate()
1746: .    -ksp_monitor_lg_true_residualnorm   - sets line graph monitor,
1747:                            uses KSPMonitorLGResidualNormCreate()
1748: .    -ksp_monitor_singular_value    - sets KSPMonitorSingularValue()
1749: -    -ksp_monitor_cancel - cancels all monitors that have
1750:                           been hardwired into a code by
1751:                           calls to KSPMonitorSet(), but
1752:                           does not cancel those set via
1753:                           the options database.

1755:    Notes:
1756:    The default is to do nothing.  To print the residual, or preconditioned
1757:    residual if KSPSetNormType(ksp,KSP_NORM_PRECONDITIONED) was called, use
1758:    KSPMonitorDefault() as the monitoring routine, with a ASCII viewer as the
1759:    context.

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

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

1767:    Level: beginner

1769: .keywords: KSP, set, monitor

1771: .seealso: KSPMonitorDefault(), KSPMonitorLGResidualNormCreate(), KSPMonitorCancel()
1772: @*/
1773: PetscErrorCode  KSPMonitorSet(KSP ksp,PetscErrorCode (*monitor)(KSP,PetscInt,PetscReal,void*),void *mctx,PetscErrorCode (*monitordestroy)(void**))
1774: {
1775:   PetscInt       i;
1777:   PetscBool      identical;

1781:   for (i=0; i<ksp->numbermonitors;i++) {
1782:     PetscMonitorCompare((PetscErrorCode (*)(void))monitor,mctx,monitordestroy,(PetscErrorCode (*)(void))ksp->monitor[i],ksp->monitorcontext[i],ksp->monitordestroy[i],&identical);
1783:     if (identical) return(0);
1784:   }
1785:   if (ksp->numbermonitors >= MAXKSPMONITORS) SETERRQ(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_OUTOFRANGE,"Too many KSP monitors set");
1786:   ksp->monitor[ksp->numbermonitors]          = monitor;
1787:   ksp->monitordestroy[ksp->numbermonitors]   = monitordestroy;
1788:   ksp->monitorcontext[ksp->numbermonitors++] = (void*)mctx;
1789:   return(0);
1790: }

1792: /*@
1793:    KSPMonitorCancel - Clears all monitors for a KSP object.

1795:    Logically Collective on KSP

1797:    Input Parameters:
1798: .  ksp - iterative context obtained from KSPCreate()

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

1805:    Level: intermediate

1807: .keywords: KSP, set, monitor

1809: .seealso: KSPMonitorDefault(), KSPMonitorLGResidualNormCreate(), KSPMonitorSet()
1810: @*/
1811: PetscErrorCode  KSPMonitorCancel(KSP ksp)
1812: {
1814:   PetscInt       i;

1818:   for (i=0; i<ksp->numbermonitors; i++) {
1819:     if (ksp->monitordestroy[i]) {
1820:       (*ksp->monitordestroy[i])(&ksp->monitorcontext[i]);
1821:     }
1822:   }
1823:   ksp->numbermonitors = 0;
1824:   return(0);
1825: }

1827: /*@C
1828:    KSPGetMonitorContext - Gets the monitoring context, as set by
1829:    KSPMonitorSet() for the FIRST monitor only.

1831:    Not Collective

1833:    Input Parameter:
1834: .  ksp - iterative context obtained from KSPCreate()

1836:    Output Parameter:
1837: .  ctx - monitoring context

1839:    Level: intermediate

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

1843: .seealso: KSPMonitorDefault(), KSPMonitorLGResidualNormCreate()
1844: @*/
1845: PetscErrorCode  KSPGetMonitorContext(KSP ksp,void **ctx)
1846: {
1849:   *ctx =      (ksp->monitorcontext[0]);
1850:   return(0);
1851: }

1853: /*@
1854:    KSPSetResidualHistory - Sets the array used to hold the residual history.
1855:    If set, this array will contain the residual norms computed at each
1856:    iteration of the solver.

1858:    Not Collective

1860:    Input Parameters:
1861: +  ksp - iterative context obtained from KSPCreate()
1862: .  a   - array to hold history
1863: .  na  - size of a
1864: -  reset - PETSC_TRUE indicates the history counter is reset to zero
1865:            for each new linear solve

1867:    Level: advanced

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

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

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

1877: .seealso: KSPGetResidualHistory()

1879: @*/
1880: PetscErrorCode  KSPSetResidualHistory(KSP ksp,PetscReal a[],PetscInt na,PetscBool reset)
1881: {


1887:   PetscFree(ksp->res_hist_alloc);
1888:   if (na != PETSC_DECIDE && na != PETSC_DEFAULT && a) {
1889:     ksp->res_hist     = a;
1890:     ksp->res_hist_max = na;
1891:   } else {
1892:     if (na != PETSC_DECIDE && na != PETSC_DEFAULT) ksp->res_hist_max = na;
1893:     else                                           ksp->res_hist_max = 10000; /* like default ksp->max_it */
1894:     PetscCalloc1(ksp->res_hist_max,&ksp->res_hist_alloc);

1896:     ksp->res_hist = ksp->res_hist_alloc;
1897:   }
1898:   ksp->res_hist_len   = 0;
1899:   ksp->res_hist_reset = reset;
1900:   return(0);
1901: }

1903: /*@C
1904:    KSPGetResidualHistory - Gets the array used to hold the residual history
1905:    and the number of residuals it contains.

1907:    Not Collective

1909:    Input Parameter:
1910: .  ksp - iterative context obtained from KSPCreate()

1912:    Output Parameters:
1913: +  a   - pointer to array to hold history (or NULL)
1914: -  na  - number of used entries in a (or NULL)

1916:    Level: advanced

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

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

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

1929: .seealso: KSPGetResidualHistory()

1931: @*/
1932: PetscErrorCode  KSPGetResidualHistory(KSP ksp,PetscReal *a[],PetscInt *na)
1933: {
1936:   if (a) *a = ksp->res_hist;
1937:   if (na) *na = ksp->res_hist_len;
1938:   return(0);
1939: }

1941: /*@C
1942:    KSPSetConvergenceTest - Sets the function to be used to determine
1943:    convergence.

1945:    Logically Collective on KSP

1947:    Input Parameters:
1948: +  ksp - iterative context obtained from KSPCreate()
1949: .  converge - pointer to int function
1950: .  cctx    - context for private data for the convergence routine (may be null)
1951: -  destroy - a routine for destroying the context (may be null)

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

1956: +  ksp - iterative context obtained from KSPCreate()
1957: .  it - iteration number
1958: .  rnorm - (estimated) 2-norm of (preconditioned) residual
1959: .  reason - the reason why it has converged or diverged
1960: -  cctx  - optional convergence context, as set by KSPSetConvergenceTest()


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

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

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

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

1977:    Level: advanced

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

1981: .seealso: KSPConvergedDefault(), KSPGetConvergenceContext(), KSPSetTolerances()
1982: @*/
1983: PetscErrorCode  KSPSetConvergenceTest(KSP ksp,PetscErrorCode (*converge)(KSP,PetscInt,PetscReal,KSPConvergedReason*,void*),void *cctx,PetscErrorCode (*destroy)(void*))
1984: {

1989:   if (ksp->convergeddestroy) {
1990:     (*ksp->convergeddestroy)(ksp->cnvP);
1991:   }
1992:   ksp->converged        = converge;
1993:   ksp->convergeddestroy = destroy;
1994:   ksp->cnvP             = (void*)cctx;
1995:   return(0);
1996: }

1998: /*@C
1999:    KSPGetConvergenceContext - Gets the convergence context set with
2000:    KSPSetConvergenceTest().

2002:    Not Collective

2004:    Input Parameter:
2005: .  ksp - iterative context obtained from KSPCreate()

2007:    Output Parameter:
2008: .  ctx - monitoring context

2010:    Level: advanced

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

2014: .seealso: KSPConvergedDefault(), KSPSetConvergenceTest()
2015: @*/
2016: PetscErrorCode  KSPGetConvergenceContext(KSP ksp,void **ctx)
2017: {
2020:   *ctx = ksp->cnvP;
2021:   return(0);
2022: }

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

2028:    Collective on KSP

2030:    Input Parameter:
2031: .  ctx - iterative context obtained from KSPCreate()

2033:    Output Parameter:
2034:    Provide exactly one of
2035: +  v - location to stash solution.
2036: -  V - the solution is returned in this location. This vector is created
2037:        internally. This vector should NOT be destroyed by the user with
2038:        VecDestroy().

2040:    Notes:
2041:    This routine can be used in one of two ways
2042: .vb
2043:       KSPBuildSolution(ksp,NULL,&V);
2044:    or
2045:       KSPBuildSolution(ksp,v,NULL); or KSPBuildSolution(ksp,v,&v);
2046: .ve
2047:    In the first case an internal vector is allocated to store the solution
2048:    (the user cannot destroy this vector). In the second case the solution
2049:    is generated in the vector that the user provides. Note that for certain
2050:    methods, such as KSPCG, the second case requires a copy of the solution,
2051:    while in the first case the call is essentially free since it simply
2052:    returns the vector where the solution already is stored. For some methods
2053:    like GMRES this is a reasonably expensive operation and should only be
2054:    used in truly needed.

2056:    Level: advanced

2058: .keywords: KSP, build, solution

2060: .seealso: KSPGetSolution(), KSPBuildResidual()
2061: @*/
2062: PetscErrorCode  KSPBuildSolution(KSP ksp,Vec v,Vec *V)
2063: {

2068:   if (!V && !v) SETERRQ(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_WRONG,"Must provide either v or V");
2069:   if (!V) V = &v;
2070:   (*ksp->ops->buildsolution)(ksp,v,V);
2071:   return(0);
2072: }

2074: /*@C
2075:    KSPBuildResidual - Builds the residual in a vector provided.

2077:    Collective on KSP

2079:    Input Parameter:
2080: .  ksp - iterative context obtained from KSPCreate()

2082:    Output Parameters:
2083: +  v - optional location to stash residual.  If v is not provided,
2084:        then a location is generated.
2085: .  t - work vector.  If not provided then one is generated.
2086: -  V - the residual

2088:    Notes:
2089:    Regardless of whether or not v is provided, the residual is
2090:    returned in V.

2092:    Level: advanced

2094: .keywords: KSP, build, residual

2096: .seealso: KSPBuildSolution()
2097: @*/
2098: PetscErrorCode  KSPBuildResidual(KSP ksp,Vec t,Vec v,Vec *V)
2099: {
2101:   PetscBool      flag = PETSC_FALSE;
2102:   Vec            w    = v,tt = t;

2106:   if (!w) {
2107:     VecDuplicate(ksp->vec_rhs,&w);
2108:     PetscLogObjectParent((PetscObject)ksp,(PetscObject)w);
2109:   }
2110:   if (!tt) {
2111:     VecDuplicate(ksp->vec_sol,&tt); flag = PETSC_TRUE;
2112:     PetscLogObjectParent((PetscObject)ksp,(PetscObject)tt);
2113:   }
2114:   (*ksp->ops->buildresidual)(ksp,tt,w,V);
2115:   if (flag) {VecDestroy(&tt);}
2116:   return(0);
2117: }

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

2123:    Logically Collective on KSP

2125:    Input Parameter:
2126: +  ksp - the KSP context
2127: -  scale - PETSC_TRUE or PETSC_FALSE

2129:    Options Database Key:
2130: +   -ksp_diagonal_scale -
2131: -   -ksp_diagonal_scale_fix - scale the matrix back AFTER the solve


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

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

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

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

2148:    Level: intermediate

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

2152: .seealso: KSPGetDiagonalScale(), KSPSetDiagonalScaleFix()
2153: @*/
2154: PetscErrorCode  KSPSetDiagonalScale(KSP ksp,PetscBool scale)
2155: {
2159:   ksp->dscale = scale;
2160:   return(0);
2161: }

2163: /*@
2164:    KSPGetDiagonalScale - Checks if KSP solver scales the matrix and
2165:                           right hand side

2167:    Not Collective

2169:    Input Parameter:
2170: .  ksp - the KSP context

2172:    Output Parameter:
2173: .  scale - PETSC_TRUE or PETSC_FALSE

2175:    Notes:
2176:     BE CAREFUL with this routine: it actually scales the matrix and right
2177:     hand side that define the system. After the system is solved the matrix
2178:     and right hand side remain scaled  unless you use KSPSetDiagonalScaleFix()

2180:    Level: intermediate

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

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

2195: /*@
2196:    KSPSetDiagonalScaleFix - Tells KSP to diagonally scale the system
2197:      back after solving.

2199:    Logically Collective on KSP

2201:    Input Parameter:
2202: +  ksp - the KSP context
2203: -  fix - PETSC_TRUE to scale back after the system solve, PETSC_FALSE to not
2204:          rescale (default)

2206:    Notes:
2207:      Must be called after KSPSetDiagonalScale()

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

2214:    Level: intermediate

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

2218: .seealso: KSPGetDiagonalScale(), KSPSetDiagonalScale(), KSPGetDiagonalScaleFix()
2219: @*/
2220: PetscErrorCode  KSPSetDiagonalScaleFix(KSP ksp,PetscBool fix)
2221: {
2225:   ksp->dscalefix = fix;
2226:   return(0);
2227: }

2229: /*@
2230:    KSPGetDiagonalScaleFix - Determines if KSP diagonally scales the system
2231:      back after solving.

2233:    Not Collective

2235:    Input Parameter:
2236: .  ksp - the KSP context

2238:    Output Parameter:
2239: .  fix - PETSC_TRUE to scale back after the system solve, PETSC_FALSE to not
2240:          rescale (default)

2242:    Notes:
2243:      Must be called after KSPSetDiagonalScale()

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

2250:    Level: intermediate

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

2254: .seealso: KSPGetDiagonalScale(), KSPSetDiagonalScale(), KSPSetDiagonalScaleFix()
2255: @*/
2256: PetscErrorCode  KSPGetDiagonalScaleFix(KSP ksp,PetscBool  *fix)
2257: {
2261:   *fix = ksp->dscalefix;
2262:   return(0);
2263: }

2265: /*@C
2266:    KSPSetComputeOperators - set routine to compute the linear operators

2268:    Logically Collective

2270:    Input Arguments:
2271: +  ksp - the KSP context
2272: .  func - function to compute the operators
2273: -  ctx - optional context

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

2278: +  ksp - the KSP context
2279: .  A - the linear operator
2280: .  B - preconditioning matrix
2281: -  ctx - optional user-provided context

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

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

2288:    Level: beginner

2290: .seealso: KSPSetOperators(), KSPSetComputeRHS(), DMKSPSetComputeOperators(), KSPSetComputeInitialGuess()
2291: @*/
2292: PetscErrorCode KSPSetComputeOperators(KSP ksp,PetscErrorCode (*func)(KSP,Mat,Mat,void*),void *ctx)
2293: {
2295:   DM             dm;

2299:   KSPGetDM(ksp,&dm);
2300:   DMKSPSetComputeOperators(dm,func,ctx);
2301:   if (ksp->setupstage == KSP_SETUP_NEWRHS) ksp->setupstage = KSP_SETUP_NEWMATRIX;
2302:   return(0);
2303: }

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

2308:    Logically Collective

2310:    Input Arguments:
2311: +  ksp - the KSP context
2312: .  func - function to compute the right hand side
2313: -  ctx - optional context

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

2318: +  ksp - the KSP context
2319: .  b - right hand side of linear system
2320: -  ctx - optional user-provided context

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

2324:    Level: beginner

2326: .seealso: KSPSolve(), DMKSPSetComputeRHS(), KSPSetComputeOperators()
2327: @*/
2328: PetscErrorCode KSPSetComputeRHS(KSP ksp,PetscErrorCode (*func)(KSP,Vec,void*),void *ctx)
2329: {
2331:   DM             dm;

2335:   KSPGetDM(ksp,&dm);
2336:   DMKSPSetComputeRHS(dm,func,ctx);
2337:   return(0);
2338: }

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

2343:    Logically Collective

2345:    Input Arguments:
2346: +  ksp - the KSP context
2347: .  func - function to compute the initial guess
2348: -  ctx - optional context

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

2353: +  ksp - the KSP context
2354: .  x - solution vector
2355: -  ctx - optional user-provided context

2357:    Level: beginner

2359: .seealso: KSPSolve(), KSPSetComputeRHS(), KSPSetComputeOperators(), DMKSPSetComputeInitialGuess()
2360: @*/
2361: PetscErrorCode KSPSetComputeInitialGuess(KSP ksp,PetscErrorCode (*func)(KSP,Vec,void*),void *ctx)
2362: {
2364:   DM             dm;

2368:   KSPGetDM(ksp,&dm);
2369:   DMKSPSetComputeInitialGuess(dm,func,ctx);
2370:   return(0);
2371: }