Actual source code: itfunc.c

petsc-master 2020-08-25
Report Typos and Errors
  1: /*
  2:       Interface KSP routines that the user calls.
  3: */

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

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

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

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

 23:    Not Collective

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

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

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

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

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

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

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

 49:    Level: advanced

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

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

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

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

 76:    Not Collective

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

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

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

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

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

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

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

110:    Level: advanced

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

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

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

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

139:    Not Collective

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

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

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

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

168:    Level: advanced

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

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

187:    Collective on ksp

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

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

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

201:    Level: advanced

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

213:   KSPGetPC(ksp,&pc);
214:   PCSetUpOnBlocks(pc);
215:   PCGetFailedReasonRank(pc,&pcreason);
216:   /* TODO: this code was wrong and is still wrong, there is no way to propogate the failure to all processes; their is no code to handle a ksp->reason on only some ranks */
217:   if (pcreason) {
218:     ksp->reason = KSP_DIVERGED_PC_FAILED;
219:   }
220:   return(0);
221: }

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

226:    Collective on ksp

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

232:    Level: intermediate

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

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

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

251:    Collective on ksp

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

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

259:    Level: intermediate

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

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

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

280:    Collective on ksp

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

286:    Level: intermediate

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

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

302:    Collective on ksp

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

307:    Level: developer

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


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

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

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

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

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

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

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

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

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

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

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

428:    Collective on ksp

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


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

439:    Level: beginner

441: .seealso: KSPCreate(), KSPSetUp(), KSPDestroy(), KSPSetTolerances(), KSPConvergedDefault(),
442:           KSPSolveTranspose(), KSPGetIterationNumber(), KSP, KSPGetConvergedReason()
443: @*/
444: PetscErrorCode KSPConvergedReasonView(KSP ksp, PetscViewer viewer, PetscViewerFormat format)
445: {
447:   PetscBool      isAscii;

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

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

482:   Collective on ksp

484:   Input Parameters:
485: . ksp   - the KSP object

487:   Level: intermediate

489: @*/
490: PetscErrorCode KSPConvergedReasonViewFromOptions(KSP ksp)
491: {
492:   PetscViewer       viewer;
493:   PetscBool         flg;
494:   PetscViewerFormat format;
495:   PetscErrorCode    ierr;

498:   PetscOptionsGetViewer(PetscObjectComm((PetscObject)ksp),((PetscObject)ksp)->options,((PetscObject)ksp)->prefix,"-ksp_converged_reason",&viewer,&format,&flg);
499:   if (flg) {
500:     KSPConvergedReasonView(ksp, viewer, format);
501:     PetscViewerDestroy(&viewer);
502:   }
503:   return(0);
504: }

506:  #include <petscdraw.h>

508: static PetscErrorCode KSPViewEigenvalues_Internal(KSP ksp, PetscBool isExplicit, PetscViewer viewer, PetscViewerFormat format)
509: {
510:   PetscReal     *r, *c;
511:   PetscInt       n, i, neig;
512:   PetscBool      isascii, isdraw;
513:   PetscMPIInt    rank;

517:   MPI_Comm_rank(PetscObjectComm((PetscObject) ksp), &rank);
518:   PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWERASCII, &isascii);
519:   PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWERDRAW,  &isdraw);
520:   if (isExplicit) {
521:     VecGetSize(ksp->vec_sol,&n);
522:     PetscMalloc2(n, &r, n, &c);
523:     KSPComputeEigenvaluesExplicitly(ksp, n, r, c);
524:     neig = n;
525:   } else {
526:     PetscInt nits;

528:     KSPGetIterationNumber(ksp, &nits);
529:     n    = nits+2;
530:     if (!nits) {PetscViewerASCIIPrintf(viewer, "Zero iterations in solver, cannot approximate any eigenvalues\n");return(0);}
531:     PetscMalloc2(n, &r, n, &c);
532:     KSPComputeEigenvalues(ksp, n, r, c, &neig);
533:   }
534:   if (isascii) {
535:     PetscViewerASCIIPrintf(viewer, "%s computed eigenvalues\n", isExplicit ? "Explicitly" : "Iteratively");
536:     for (i = 0; i < neig; ++i) {
537:       if (c[i] >= 0.0) {PetscViewerASCIIPrintf(viewer, "%g + %gi\n", (double) r[i],  (double) c[i]);}
538:       else             {PetscViewerASCIIPrintf(viewer, "%g - %gi\n", (double) r[i], -(double) c[i]);}
539:     }
540:   } else if (isdraw && !rank) {
541:     PetscDraw   draw;
542:     PetscDrawSP drawsp;

544:     if (format == PETSC_VIEWER_DRAW_CONTOUR) {
545:       KSPPlotEigenContours_Private(ksp,neig,r,c);
546:     } else {
547:       if (!ksp->eigviewer) {PetscViewerDrawOpen(PETSC_COMM_SELF,NULL,isExplicit ? "Explicitly Computed Eigenvalues" : "Iteratively Computed Eigenvalues",PETSC_DECIDE,PETSC_DECIDE,400,400,&ksp->eigviewer);}
548:       PetscViewerDrawGetDraw(ksp->eigviewer,0,&draw);
549:       PetscDrawSPCreate(draw,1,&drawsp);
550:       PetscDrawSPReset(drawsp);
551:       for (i = 0; i < neig; ++i) {PetscDrawSPAddPoint(drawsp,r+i,c+i);}
552:       PetscDrawSPDraw(drawsp,PETSC_TRUE);
553:       PetscDrawSPSave(drawsp);
554:       PetscDrawSPDestroy(&drawsp);
555:     }
556:   }
557:   PetscFree2(r, c);
558:   return(0);
559: }

561: static PetscErrorCode KSPViewSingularvalues_Internal(KSP ksp, PetscViewer viewer, PetscViewerFormat format)
562: {
563:   PetscReal      smax, smin;
564:   PetscInt       nits;
565:   PetscBool      isascii;

569:   PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWERASCII, &isascii);
570:   KSPGetIterationNumber(ksp, &nits);
571:   if (!nits) {PetscViewerASCIIPrintf(viewer, "Zero iterations in solver, cannot approximate any singular values\n");return(0);}
572:   KSPComputeExtremeSingularValues(ksp, &smax, &smin);
573:   if (isascii) {PetscViewerASCIIPrintf(viewer, "Iteratively computed extreme singular values: max %g min %g max/min %g\n",(double)smax,(double)smin,(double)(smax/smin));}
574:   return(0);
575: }

577: static PetscErrorCode KSPViewFinalResidual_Internal(KSP ksp, PetscViewer viewer, PetscViewerFormat format)
578: {
579:   PetscBool      isascii;

583:   PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWERASCII, &isascii);
584:   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");
585:   if (isascii) {
586:     Mat       A;
587:     Vec       t;
588:     PetscReal norm;

590:     PCGetOperators(ksp->pc, &A, NULL);
591:     VecDuplicate(ksp->vec_rhs, &t);
592:     KSP_MatMult(ksp, A, ksp->vec_sol, t);
593:     VecAYPX(t, -1.0, ksp->vec_rhs);
594:     VecNorm(t, NORM_2, &norm);
595:     VecDestroy(&t);
596:     PetscViewerASCIIPrintf(viewer, "KSP final norm of residual %g\n", (double) norm);
597:   }
598:   return(0);
599: }

601: static PetscErrorCode KSPSolve_Private(KSP ksp,Vec b,Vec x)
602: {
604:   PetscBool      flg = PETSC_FALSE,inXisinB=PETSC_FALSE,guess_zero;
605:   Mat            mat,pmat;
606:   MPI_Comm       comm;
607:   MatNullSpace   nullsp;
608:   Vec            btmp,vec_rhs=NULL;

611:   comm = PetscObjectComm((PetscObject)ksp);
612:   if (x && x == b) {
613:     if (!ksp->guess_zero) SETERRQ(comm,PETSC_ERR_ARG_INCOMP,"Cannot use x == b with nonzero initial guess");
614:     VecDuplicate(b,&x);
615:     inXisinB = PETSC_TRUE;
616:   }
617:   if (b) {
618:     PetscObjectReference((PetscObject)b);
619:     VecDestroy(&ksp->vec_rhs);
620:     ksp->vec_rhs = b;
621:   }
622:   if (x) {
623:     PetscObjectReference((PetscObject)x);
624:     VecDestroy(&ksp->vec_sol);
625:     ksp->vec_sol = x;
626:   }

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

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

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

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

637:   if (ksp->guess) {
638:     PetscObjectState ostate,state;

640:     KSPGuessSetUp(ksp->guess);
641:     PetscObjectStateGet((PetscObject)ksp->vec_sol,&ostate);
642:     KSPGuessFormGuess(ksp->guess,ksp->vec_rhs,ksp->vec_sol);
643:     PetscObjectStateGet((PetscObject)ksp->vec_sol,&state);
644:     if (state != ostate) {
645:       ksp->guess_zero = PETSC_FALSE;
646:     } else {
647:       PetscInfo(ksp,"Using zero initial guess since the KSPGuess object did not change the vector\n");
648:       ksp->guess_zero = PETSC_TRUE;
649:     }
650:   }

652:   /* KSPSetUp() scales the matrix if needed */
653:   KSPSetUp(ksp);
654:   KSPSetUpOnBlocks(ksp);

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

658:   PCGetOperators(ksp->pc,&mat,&pmat);
659:   /* diagonal scale RHS if called for */
660:   if (ksp->dscale) {
661:     VecPointwiseMult(ksp->vec_rhs,ksp->vec_rhs,ksp->diagonal);
662:     /* second time in, but matrix was scaled back to original */
663:     if (ksp->dscalefix && ksp->dscalefix2) {
664:       Mat mat,pmat;

666:       PCGetOperators(ksp->pc,&mat,&pmat);
667:       MatDiagonalScale(pmat,ksp->diagonal,ksp->diagonal);
668:       if (mat != pmat) {MatDiagonalScale(mat,ksp->diagonal,ksp->diagonal);}
669:     }

671:     /* scale initial guess */
672:     if (!ksp->guess_zero) {
673:       if (!ksp->truediagonal) {
674:         VecDuplicate(ksp->diagonal,&ksp->truediagonal);
675:         VecCopy(ksp->diagonal,ksp->truediagonal);
676:         VecReciprocal(ksp->truediagonal);
677:       }
678:       VecPointwiseMult(ksp->vec_sol,ksp->vec_sol,ksp->truediagonal);
679:     }
680:   }
681:   PCPreSolve(ksp->pc,ksp);

683:   if (ksp->guess_zero) { VecSet(ksp->vec_sol,0.0);}
684:   if (ksp->guess_knoll) { /* The Knoll trick is independent on the KSPGuess specified */
685:     PCApply(ksp->pc,ksp->vec_rhs,ksp->vec_sol);
686:     KSP_RemoveNullSpace(ksp,ksp->vec_sol);
687:     ksp->guess_zero = PETSC_FALSE;
688:   }

690:   /* can we mark the initial guess as zero for this solve? */
691:   guess_zero = ksp->guess_zero;
692:   if (!ksp->guess_zero) {
693:     PetscReal norm;

695:     VecNormAvailable(ksp->vec_sol,NORM_2,&flg,&norm);
696:     if (flg && !norm) ksp->guess_zero = PETSC_TRUE;
697:   }
698:   if (ksp->transpose_solve) {
699:     MatGetNullSpace(pmat,&nullsp);
700:   } else {
701:     MatGetTransposeNullSpace(pmat,&nullsp);
702:   }
703:   if (nullsp) {
704:     VecDuplicate(ksp->vec_rhs,&btmp);
705:     VecCopy(ksp->vec_rhs,btmp);
706:     MatNullSpaceRemove(nullsp,btmp);
707:     vec_rhs      = ksp->vec_rhs;
708:     ksp->vec_rhs = btmp;
709:   }
710:   VecLockReadPush(ksp->vec_rhs);
711:   if (ksp->reason == KSP_DIVERGED_PC_FAILED) {
712:     VecSetInf(ksp->vec_sol);
713:   }
714:   (*ksp->ops->solve)(ksp);

716:   VecLockReadPop(ksp->vec_rhs);
717:   if (nullsp) {
718:     ksp->vec_rhs = vec_rhs;
719:     VecDestroy(&btmp);
720:   }

722:   ksp->guess_zero = guess_zero;

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

727:   if (ksp->viewReason) {KSPConvergedReasonView(ksp, ksp->viewerReason, ksp->formatReason);}
728:   PCPostSolve(ksp->pc,ksp);

730:   /* diagonal scale solution if called for */
731:   if (ksp->dscale) {
732:     VecPointwiseMult(ksp->vec_sol,ksp->vec_sol,ksp->diagonal);
733:     /* unscale right hand side and matrix */
734:     if (ksp->dscalefix) {
735:       Mat mat,pmat;

737:       VecReciprocal(ksp->diagonal);
738:       VecPointwiseMult(ksp->vec_rhs,ksp->vec_rhs,ksp->diagonal);
739:       PCGetOperators(ksp->pc,&mat,&pmat);
740:       MatDiagonalScale(pmat,ksp->diagonal,ksp->diagonal);
741:       if (mat != pmat) {MatDiagonalScale(mat,ksp->diagonal,ksp->diagonal);}
742:       VecReciprocal(ksp->diagonal);
743:       ksp->dscalefix2 = PETSC_TRUE;
744:     }
745:   }
746:   PetscLogEventEnd(KSP_Solve,ksp,ksp->vec_rhs,ksp->vec_sol,0);
747:   if (ksp->guess) {
748:     KSPGuessUpdate(ksp->guess,ksp->vec_rhs,ksp->vec_sol);
749:   }
750:   if (ksp->postsolve) {
751:     (*ksp->postsolve)(ksp,ksp->vec_rhs,ksp->vec_sol,ksp->postctx);
752:   }

754:   PCGetOperators(ksp->pc,&mat,&pmat);
755:   if (ksp->viewEV)       {KSPViewEigenvalues_Internal(ksp, PETSC_FALSE, ksp->viewerEV,    ksp->formatEV);}
756:   if (ksp->viewEVExp)    {KSPViewEigenvalues_Internal(ksp, PETSC_TRUE,  ksp->viewerEVExp, ksp->formatEVExp);}
757:   if (ksp->viewSV)       {KSPViewSingularvalues_Internal(ksp, ksp->viewerSV, ksp->formatSV);}
758:   if (ksp->viewFinalRes) {KSPViewFinalResidual_Internal(ksp, ksp->viewerFinalRes, ksp->formatFinalRes);}
759:   if (ksp->viewMat)      {ObjectView((PetscObject) mat,           ksp->viewerMat,    ksp->formatMat);}
760:   if (ksp->viewPMat)     {ObjectView((PetscObject) pmat,          ksp->viewerPMat,   ksp->formatPMat);}
761:   if (ksp->viewRhs)      {ObjectView((PetscObject) ksp->vec_rhs,  ksp->viewerRhs,    ksp->formatRhs);}
762:   if (ksp->viewSol)      {ObjectView((PetscObject) ksp->vec_sol,  ksp->viewerSol,    ksp->formatSol);}
763:   if (ksp->view)         {ObjectView((PetscObject) ksp,           ksp->viewer,       ksp->format);}
764:   if (ksp->viewDScale)   {ObjectView((PetscObject) ksp->diagonal, ksp->viewerDScale, ksp->formatDScale);}
765:   if (ksp->viewMatExp)   {
766:     Mat A, B;

768:     PCGetOperators(ksp->pc, &A, NULL);
769:     if (ksp->transpose_solve) {
770:       Mat AT;

772:       MatCreateTranspose(A, &AT);
773:       MatComputeOperator(AT, MATAIJ, &B);
774:       MatDestroy(&AT);
775:     } else {
776:       MatComputeOperator(A, MATAIJ, &B);
777:     }
778:     ObjectView((PetscObject) B, ksp->viewerMatExp, ksp->formatMatExp);
779:     MatDestroy(&B);
780:   }
781:   if (ksp->viewPOpExp)   {
782:     Mat B;

784:     KSPComputeOperator(ksp, MATAIJ, &B);
785:     ObjectView((PetscObject) B, ksp->viewerPOpExp, ksp->formatPOpExp);
786:     MatDestroy(&B);
787:   }

789:   if (inXisinB) {
790:     VecCopy(x,b);
791:     VecDestroy(&x);
792:   }
793:   PetscObjectSAWsBlock((PetscObject)ksp);
794:   if (ksp->errorifnotconverged && ksp->reason < 0 && ksp->reason != KSP_DIVERGED_ITS) {
795:     if (ksp->reason == KSP_DIVERGED_PC_FAILED) {
796:       PCFailedReason reason;
797:       PCGetFailedReason(ksp->pc,&reason);
798:       SETERRQ2(comm,PETSC_ERR_NOT_CONVERGED,"KSPSolve has not converged, reason %s PC failed due to %s",KSPConvergedReasons[ksp->reason],PCFailedReasons[reason]);
799:     } else SETERRQ1(comm,PETSC_ERR_NOT_CONVERGED,"KSPSolve has not converged, reason %s",KSPConvergedReasons[ksp->reason]);
800:   }
801:   return(0);
802: }

804: /*@
805:    KSPSolve - Solves linear system.

807:    Collective on ksp

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

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

828:    Notes:

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

832:    The operator is specified with KSPSetOperators().

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

837:    If you provide a matrix that has a MatSetNullSpace() and MatSetTransposeNullSpace() this will use that information to solve singular systems
838:    in the least squares sense with a norm minimizing solution.
839: $
840: $                   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()
841: $
842: $    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
843: $    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
844: $    direction thus the solution which is a linear combination of the search directions has no component in the nullspace(A).
845: $
846: $    We recommend always using GMRES for such singular systems.
847: $    If nullspace(A) = nullspace(A') (note symmetric matrices always satisfy this property) then both left and right preconditioning will work
848: $    If nullspace(A) != nullspace(A') then left preconditioning will work but right preconditioning may not work (or it may).

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


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

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

865:    Level: beginner

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

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

884: /*@
885:    KSPSolveTranspose - Solves the transpose of a linear system.

887:    Collective on ksp

889:    Input Parameters:
890: +  ksp - iterative context obtained from KSPCreate()
891: .  b - right hand side vector
892: -  x - solution vector

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

897:    Developer Notes:
898:     We need to implement a KSPSolveHermitianTranspose()

900:    Level: developer

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

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

918: static PetscErrorCode KSPViewFinalMatResidual_Internal(KSP ksp, Mat B, Mat X, PetscViewer viewer, PetscViewerFormat format, PetscInt shift)
919: {
920:   Mat            A, R;
921:   PetscReal      *norms;
922:   PetscInt       i, N;
923:   PetscBool      flg;

927:   PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &flg);
928:   if (flg) {
929:     PCGetOperators(ksp->pc, &A, NULL);
930:     MatMatMult(A, X, MAT_INITIAL_MATRIX, PETSC_DEFAULT, &R);
931:     MatAYPX(R, -1.0, B, SAME_NONZERO_PATTERN);
932:     MatGetSize(R, NULL, &N);
933:     PetscMalloc1(N, &norms);
934:     MatGetColumnNorms(R, NORM_2, norms);
935:     MatDestroy(&R);
936:     for (i = 0; i < N; ++i) {
937:       PetscViewerASCIIPrintf(viewer, "%s #%D %g\n", i == 0 ? "KSP final norm of residual" : "                          ", shift + i, (double)norms[i]);
938:     }
939:     PetscFree(norms);
940:   }
941:   return(0);
942: }

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

947:    Input Parameters:
948: +     ksp - iterative context
949: -     B - block of right-hand sides

951:    Output Parameter:
952: .     X - block of solutions

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

957:    Level: intermediate

959: .seealso:  KSPSolve(), MatMatSolve(), MATDENSE, KSPHPDDM, PCBJACOBI, PCASM
960: @*/
961: PetscErrorCode KSPMatSolve(KSP ksp, Mat B, Mat X)
962: {
963:   Mat            A, vB, vX;
964:   Vec            cb, cx;
965:   PetscInt       m1, M1, m2, M2, n1, N1, n2, N2, Bbn = PETSC_DECIDE;
966:   PetscBool      match;

975:   if (!B->assembled) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
976:   MatCheckPreallocated(X, 3);
977:   if (!X->assembled) {
978:     MatSetOption(X, MAT_NO_OFF_PROC_ENTRIES, PETSC_TRUE);
979:     MatAssemblyBegin(X, MAT_FINAL_ASSEMBLY);
980:     MatAssemblyEnd(X, MAT_FINAL_ASSEMBLY);
981:   }
982:   if (B == X) SETERRQ(PetscObjectComm((PetscObject)ksp), PETSC_ERR_ARG_IDN, "B and X must be different matrices");
983:   KSPGetOperators(ksp, &A, NULL);
984:   MatGetLocalSize(A, &m1, NULL);
985:   MatGetLocalSize(B, &m2, &n2);
986:   MatGetSize(A, &M1, NULL);
987:   MatGetSize(B, &M2, &N2);
988:   if (m1 != m2 || M1 != M2) SETERRQ4(PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Cannot use a block of right-hand sides with (m2,M2) = (%D,%D) for a linear system with (m1,M1) = (%D,%D)", m2, M2, m1, M1);
989:   MatGetLocalSize(X, &m1, &n1);
990:   MatGetSize(X, &M1, &N1);
991:   if (m1 != m2 || M1 != M2 || n1 != n2 || N1 != N2) SETERRQ8(PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Incompatible block of right-hand sides (m2,M2)x(n2,N2) = (%D,%D)x(%D,%D) and solutions (m1,M1)x(n1,N1) = (%D,%D)x(%D,%D)", m2, M2, n2, N2, m1, M1, n1, N1);
992:   PetscObjectBaseTypeCompareAny((PetscObject)B, &match, MATSEQDENSE, MATMPIDENSE, "");
993:   if (!match) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Provided block of right-hand sides not stored in a dense Mat");
994:   PetscObjectBaseTypeCompareAny((PetscObject)X, &match, MATSEQDENSE, MATMPIDENSE, "");
995:   if (!match) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Provided block of solutions not stored in a dense Mat");
996:   KSPSetUp(ksp);
997:   KSPSetUpOnBlocks(ksp);
998:   if (ksp->ops->matsolve) {
999:     if (ksp->guess_zero) {
1000:       MatZeroEntries(X);
1001:     }
1002:     PetscLogEventBegin(KSP_MatSolve, ksp, B, X, 0);
1003:     KSPGetMatSolveBlockSize(ksp, &Bbn);
1004:     /* by default, do a single solve with all columns */
1005:     if (Bbn == PETSC_DECIDE) Bbn = N2;
1006:     else if (Bbn < 1)        SETERRQ1(PetscObjectComm((PetscObject)ksp), PETSC_ERR_ARG_OUTOFRANGE, "KSPMatSolve() block size %D must be positive", Bbn);
1007:     PetscInfo2(ksp, "KSP type %s solving using blocks of width at most %D\n", ((PetscObject)ksp)->type_name, Bbn);
1008:     /* if -ksp_matsolve_block_size is greater than the actual number of columns, do a single solve with all columns */
1009:     if (Bbn >= N2) {
1010:       (*ksp->ops->matsolve)(ksp, B, X);
1011:       if (ksp->viewFinalRes) {
1012:         KSPViewFinalMatResidual_Internal(ksp, B, X, ksp->viewerFinalRes, ksp->formatFinalRes, 0);
1013:       }
1014:       if (ksp->viewReason) {
1015:         KSPConvergedReasonView(ksp, ksp->viewerReason,PETSC_VIEWER_DEFAULT);
1016:       }
1017:     } else {
1018:       for (n2 = 0; n2 < N2; n2 += Bbn) {
1019:         MatDenseGetSubMatrix(B, n2, PetscMin(n2+Bbn, N2), &vB);
1020:         MatDenseGetSubMatrix(X, n2, PetscMin(n2+Bbn, N2), &vX);
1021:         (*ksp->ops->matsolve)(ksp, vB, vX);
1022:         if (ksp->viewFinalRes) {
1023:           KSPViewFinalMatResidual_Internal(ksp, vB, vX, ksp->viewerFinalRes, ksp->formatFinalRes, n2);
1024:         }
1025:         if (ksp->viewReason) {
1026:           KSPConvergedReasonView(ksp, ksp->viewerReason,PETSC_VIEWER_DEFAULT);
1027:         }
1028:         MatDenseRestoreSubMatrix(B, &vB);
1029:         MatDenseRestoreSubMatrix(X, &vX);
1030:       }
1031:     }
1032:     if (ksp->view) {
1033:       KSPView(ksp, ksp->viewer);
1034:     }
1035:     PetscLogEventEnd(KSP_MatSolve, ksp, B, X, 0);
1036:   } else {
1037:     PetscInfo1(ksp, "KSP type %s solving column by column\n", ((PetscObject)ksp)->type_name);
1038:     for (n2 = 0; n2 < N2; ++n2) {
1039:       MatDenseGetColumnVecRead(B, n2, &cb);
1040:       MatDenseGetColumnVecWrite(X, n2, &cx);
1041:       KSPSolve(ksp, cb, cx);
1042:       MatDenseRestoreColumnVecWrite(X, n2, &cx);
1043:       MatDenseRestoreColumnVecRead(B, n2, &cb);
1044:     }
1045:   }
1046:   return(0);
1047: }

1049: /*@
1050:      KSPSetMatSolveBlockSize - Sets the maximum number of columns treated simultaneously in KSPMatSolve().

1052:     Logically collective

1054:    Input Parameters:
1055: +     ksp - iterative context
1056: -     bs - block size

1058:    Level: advanced

1060: .seealso:  KSPMatSolve(), KSPGetMatSolveBlockSize(), -mat_mumps_icntl_27, -matmatmult_Bbn
1061: @*/
1062: PetscErrorCode KSPSetMatSolveBlockSize(KSP ksp, PetscInt bs)
1063: {

1069:   PetscTryMethod(ksp, "KSPSetMatSolveBlockSize_C", (KSP, PetscInt), (ksp, bs));
1070:   return(0);
1071: }

1073: /*@
1074:      KSPGetMatSolveBlockSize - Gets the maximum number of columns treated simultaneously in KSPMatSolve().

1076:    Input Parameter:
1077: .     ksp - iterative context

1079:    Output Parameter:
1080: .     bs - block size

1082:    Level: advanced

1084: .seealso:  KSPMatSolve(), KSPSetMatSolveBlockSize(), -mat_mumps_icntl_27, -matmatmult_Bbn
1085: @*/
1086: PetscErrorCode KSPGetMatSolveBlockSize(KSP ksp, PetscInt *bs)
1087: {

1092:   *bs = PETSC_DECIDE;
1093:   PetscTryMethod(ksp, "KSPGetMatSolveBlockSize_C", (KSP, PetscInt*), (ksp, bs));
1094:   return(0);
1095: }

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

1100:    Collective on ksp

1102:    Input Parameter:
1103: .  ksp - iterative context obtained from KSPCreate()

1105:    Level: beginner

1107: .seealso: KSPCreate(), KSPSetUp(), KSPSolve(), KSPSetFromOptions(), KSP
1108: @*/
1109: PetscErrorCode  KSPResetViewers(KSP ksp)
1110: {

1115:   if (!ksp) return(0);
1116:   PetscViewerDestroy(&ksp->viewer);
1117:   PetscViewerDestroy(&ksp->viewerPre);
1118:   PetscViewerDestroy(&ksp->viewerReason);
1119:   PetscViewerDestroy(&ksp->viewerMat);
1120:   PetscViewerDestroy(&ksp->viewerPMat);
1121:   PetscViewerDestroy(&ksp->viewerRhs);
1122:   PetscViewerDestroy(&ksp->viewerSol);
1123:   PetscViewerDestroy(&ksp->viewerMatExp);
1124:   PetscViewerDestroy(&ksp->viewerEV);
1125:   PetscViewerDestroy(&ksp->viewerSV);
1126:   PetscViewerDestroy(&ksp->viewerEVExp);
1127:   PetscViewerDestroy(&ksp->viewerFinalRes);
1128:   PetscViewerDestroy(&ksp->viewerPOpExp);
1129:   PetscViewerDestroy(&ksp->viewerDScale);
1130:   ksp->view         = PETSC_FALSE;
1131:   ksp->viewPre      = PETSC_FALSE;
1132:   ksp->viewReason   = PETSC_FALSE;
1133:   ksp->viewMat      = PETSC_FALSE;
1134:   ksp->viewPMat     = PETSC_FALSE;
1135:   ksp->viewRhs      = PETSC_FALSE;
1136:   ksp->viewSol      = PETSC_FALSE;
1137:   ksp->viewMatExp   = PETSC_FALSE;
1138:   ksp->viewEV       = PETSC_FALSE;
1139:   ksp->viewSV       = PETSC_FALSE;
1140:   ksp->viewEVExp    = PETSC_FALSE;
1141:   ksp->viewFinalRes = PETSC_FALSE;
1142:   ksp->viewPOpExp   = PETSC_FALSE;
1143:   ksp->viewDScale   = PETSC_FALSE;
1144:   return(0);
1145: }

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

1150:    Collective on ksp

1152:    Input Parameter:
1153: .  ksp - iterative context obtained from KSPCreate()

1155:    Level: beginner

1157: .seealso: KSPCreate(), KSPSetUp(), KSPSolve(), KSP
1158: @*/
1159: PetscErrorCode  KSPReset(KSP ksp)
1160: {

1165:   if (!ksp) return(0);
1166:   if (ksp->ops->reset) {
1167:     (*ksp->ops->reset)(ksp);
1168:   }
1169:   if (ksp->pc) {PCReset(ksp->pc);}
1170:   if (ksp->guess) {
1171:     KSPGuess guess = ksp->guess;
1172:     if (guess->ops->reset) { (*guess->ops->reset)(guess); }
1173:   }
1174:   VecDestroyVecs(ksp->nwork,&ksp->work);
1175:   VecDestroy(&ksp->vec_rhs);
1176:   VecDestroy(&ksp->vec_sol);
1177:   VecDestroy(&ksp->diagonal);
1178:   VecDestroy(&ksp->truediagonal);

1180:   KSPResetViewers(ksp);

1182:   ksp->setupstage = KSP_SETUP_NEW;
1183:   return(0);
1184: }

1186: /*@
1187:    KSPDestroy - Destroys KSP context.

1189:    Collective on ksp

1191:    Input Parameter:
1192: .  ksp - iterative context obtained from KSPCreate()

1194:    Level: beginner

1196: .seealso: KSPCreate(), KSPSetUp(), KSPSolve(), KSP
1197: @*/
1198: PetscErrorCode  KSPDestroy(KSP *ksp)
1199: {
1201:   PC             pc;

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

1208:   PetscObjectSAWsViewOff((PetscObject)*ksp);

1210:   /*
1211:    Avoid a cascading call to PCReset(ksp->pc) from the following call:
1212:    PCReset() shouldn't be called from KSPDestroy() as it is unprotected by pc's
1213:    refcount (and may be shared, e.g., by other ksps).
1214:    */
1215:   pc         = (*ksp)->pc;
1216:   (*ksp)->pc = NULL;
1217:   KSPReset((*ksp));
1218:   (*ksp)->pc = pc;
1219:   if ((*ksp)->ops->destroy) {(*(*ksp)->ops->destroy)(*ksp);}

1221:   KSPGuessDestroy(&(*ksp)->guess);
1222:   DMDestroy(&(*ksp)->dm);
1223:   PCDestroy(&(*ksp)->pc);
1224:   PetscFree((*ksp)->res_hist_alloc);
1225:   if ((*ksp)->convergeddestroy) {
1226:     (*(*ksp)->convergeddestroy)((*ksp)->cnvP);
1227:   }
1228:   KSPMonitorCancel((*ksp));
1229:   PetscViewerDestroy(&(*ksp)->eigviewer);
1230:   PetscHeaderDestroy(ksp);
1231:   return(0);
1232: }

1234: /*@
1235:     KSPSetPCSide - Sets the preconditioning side.

1237:     Logically Collective on ksp

1239:     Input Parameter:
1240: .   ksp - iterative context obtained from KSPCreate()

1242:     Output Parameter:
1243: .   side - the preconditioning side, where side is one of
1244: .vb
1245:       PC_LEFT - left preconditioning (default)
1246:       PC_RIGHT - right preconditioning
1247:       PC_SYMMETRIC - symmetric preconditioning
1248: .ve

1250:     Options Database Keys:
1251: .   -ksp_pc_side <right,left,symmetric>

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

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

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

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

1264:     Level: intermediate

1266: .seealso: KSPGetPCSide(), KSPSetNormType(), KSPGetNormType(), KSP
1267: @*/
1268: PetscErrorCode  KSPSetPCSide(KSP ksp,PCSide side)
1269: {
1273:   ksp->pc_side = ksp->pc_side_set = side;
1274:   return(0);
1275: }

1277: /*@
1278:     KSPGetPCSide - Gets the preconditioning side.

1280:     Not Collective

1282:     Input Parameter:
1283: .   ksp - iterative context obtained from KSPCreate()

1285:     Output Parameter:
1286: .   side - the preconditioning side, where side is one of
1287: .vb
1288:       PC_LEFT - left preconditioning (default)
1289:       PC_RIGHT - right preconditioning
1290:       PC_SYMMETRIC - symmetric preconditioning
1291: .ve

1293:     Level: intermediate

1295: .seealso: KSPSetPCSide(), KSP
1296: @*/
1297: PetscErrorCode  KSPGetPCSide(KSP ksp,PCSide *side)
1298: {

1304:   KSPSetUpNorms_Private(ksp,PETSC_TRUE,&ksp->normtype,&ksp->pc_side);
1305:   *side = ksp->pc_side;
1306:   return(0);
1307: }

1309: /*@
1310:    KSPGetTolerances - Gets the relative, absolute, divergence, and maximum
1311:    iteration tolerances used by the default KSP convergence tests.

1313:    Not Collective

1315:    Input Parameter:
1316: .  ksp - the Krylov subspace context

1318:    Output Parameters:
1319: +  rtol - the relative convergence tolerance
1320: .  abstol - the absolute convergence tolerance
1321: .  dtol - the divergence tolerance
1322: -  maxits - maximum number of iterations

1324:    Notes:
1325:    The user can specify NULL for any parameter that is not needed.

1327:    Level: intermediate

1329:            maximum, iterations

1331: .seealso: KSPSetTolerances(), KSP
1332: @*/
1333: PetscErrorCode  KSPGetTolerances(KSP ksp,PetscReal *rtol,PetscReal *abstol,PetscReal *dtol,PetscInt *maxits)
1334: {
1337:   if (abstol) *abstol = ksp->abstol;
1338:   if (rtol) *rtol = ksp->rtol;
1339:   if (dtol) *dtol = ksp->divtol;
1340:   if (maxits) *maxits = ksp->max_it;
1341:   return(0);
1342: }

1344: /*@
1345:    KSPSetTolerances - Sets the relative, absolute, divergence, and maximum
1346:    iteration tolerances used by the default KSP convergence testers.

1348:    Logically Collective on ksp

1350:    Input Parameters:
1351: +  ksp - the Krylov subspace context
1352: .  rtol - the relative convergence tolerance, relative decrease in the (possibly preconditioned) residual norm
1353: .  abstol - the absolute convergence tolerance   absolute size of the (possibly preconditioned) residual norm
1354: .  dtol - the divergence tolerance,   amount (possibly preconditioned) residual norm can increase before KSPConvergedDefault() concludes that the method is diverging
1355: -  maxits - maximum number of iterations to use

1357:    Options Database Keys:
1358: +  -ksp_atol <abstol> - Sets abstol
1359: .  -ksp_rtol <rtol> - Sets rtol
1360: .  -ksp_divtol <dtol> - Sets dtol
1361: -  -ksp_max_it <maxits> - Sets maxits

1363:    Notes:
1364:    Use PETSC_DEFAULT to retain the default value of any of the tolerances.

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

1369:    Level: intermediate

1371:            convergence, maximum, iterations

1373: .seealso: KSPGetTolerances(), KSPConvergedDefault(), KSPSetConvergenceTest(), KSP
1374: @*/
1375: PetscErrorCode  KSPSetTolerances(KSP ksp,PetscReal rtol,PetscReal abstol,PetscReal dtol,PetscInt maxits)
1376: {

1384:   if (rtol != PETSC_DEFAULT) {
1385:     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);
1386:     ksp->rtol = rtol;
1387:   }
1388:   if (abstol != PETSC_DEFAULT) {
1389:     if (abstol < 0.0) SETERRQ1(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_OUTOFRANGE,"Absolute tolerance %g must be non-negative",(double)abstol);
1390:     ksp->abstol = abstol;
1391:   }
1392:   if (dtol != PETSC_DEFAULT) {
1393:     if (dtol < 0.0) SETERRQ1(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_OUTOFRANGE,"Divergence tolerance %g must be larger than 1.0",(double)dtol);
1394:     ksp->divtol = dtol;
1395:   }
1396:   if (maxits != PETSC_DEFAULT) {
1397:     if (maxits < 0) SETERRQ1(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of iterations %D must be non-negative",maxits);
1398:     ksp->max_it = maxits;
1399:   }
1400:   return(0);
1401: }

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

1408:    Logically Collective on ksp

1410:    Input Parameters:
1411: +  ksp - iterative context obtained from KSPCreate()
1412: -  flg - PETSC_TRUE indicates the guess is non-zero, PETSC_FALSE indicates the guess is zero

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

1417:    Level: beginner

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

1422: .seealso: KSPGetInitialGuessNonzero(), KSPSetGuessType(), KSPGuessType, KSP
1423: @*/
1424: PetscErrorCode  KSPSetInitialGuessNonzero(KSP ksp,PetscBool flg)
1425: {
1429:   ksp->guess_zero = (PetscBool) !(int)flg;
1430:   return(0);
1431: }

1433: /*@
1434:    KSPGetInitialGuessNonzero - Determines whether the KSP solver is using
1435:    a zero initial guess.

1437:    Not Collective

1439:    Input Parameter:
1440: .  ksp - iterative context obtained from KSPCreate()

1442:    Output Parameter:
1443: .  flag - PETSC_TRUE if guess is nonzero, else PETSC_FALSE

1445:    Level: intermediate

1447: .seealso: KSPSetInitialGuessNonzero(), KSP
1448: @*/
1449: PetscErrorCode  KSPGetInitialGuessNonzero(KSP ksp,PetscBool  *flag)
1450: {
1454:   if (ksp->guess_zero) *flag = PETSC_FALSE;
1455:   else *flag = PETSC_TRUE;
1456:   return(0);
1457: }

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

1462:    Logically Collective on ksp

1464:    Input Parameters:
1465: +  ksp - iterative context obtained from KSPCreate()
1466: -  flg - PETSC_TRUE indicates you want the error generated

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

1471:    Level: intermediate

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


1478: .seealso: KSPGetErrorIfNotConverged(), KSP
1479: @*/
1480: PetscErrorCode  KSPSetErrorIfNotConverged(KSP ksp,PetscBool flg)
1481: {
1485:   ksp->errorifnotconverged = flg;
1486:   return(0);
1487: }

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

1492:    Not Collective

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

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

1500:    Level: intermediate

1502: .seealso: KSPSetErrorIfNotConverged(), KSP
1503: @*/
1504: PetscErrorCode  KSPGetErrorIfNotConverged(KSP ksp,PetscBool  *flag)
1505: {
1509:   *flag = ksp->errorifnotconverged;
1510:   return(0);
1511: }

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

1516:    Logically Collective on ksp

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

1522:    Level: advanced

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

1526: .seealso: KSPGetInitialGuessKnoll(), KSPSetInitialGuessNonzero(), KSPGetInitialGuessNonzero(), KSP
1527: @*/
1528: PetscErrorCode  KSPSetInitialGuessKnoll(KSP ksp,PetscBool flg)
1529: {
1533:   ksp->guess_knoll = flg;
1534:   return(0);
1535: }

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

1541:    Not Collective

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

1546:    Output Parameter:
1547: .  flag - PETSC_TRUE if using Knoll trick, else PETSC_FALSE

1549:    Level: advanced

1551: .seealso: KSPSetInitialGuessKnoll(), KSPSetInitialGuessNonzero(), KSPGetInitialGuessNonzero(), KSP
1552: @*/
1553: PetscErrorCode  KSPGetInitialGuessKnoll(KSP ksp,PetscBool  *flag)
1554: {
1558:   *flag = ksp->guess_knoll;
1559:   return(0);
1560: }

1562: /*@
1563:    KSPGetComputeSingularValues - Gets the flag indicating whether the extreme singular
1564:    values will be calculated via a Lanczos or Arnoldi process as the linear
1565:    system is solved.

1567:    Not Collective

1569:    Input Parameter:
1570: .  ksp - iterative context obtained from KSPCreate()

1572:    Output Parameter:
1573: .  flg - PETSC_TRUE or PETSC_FALSE

1575:    Options Database Key:
1576: .  -ksp_monitor_singular_value - Activates KSPSetComputeSingularValues()

1578:    Notes:
1579:    Currently this option is not valid for all iterative methods.

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

1585:    Level: advanced

1587: .seealso: KSPComputeExtremeSingularValues(), KSPMonitorSingularValue(), KSP
1588: @*/
1589: PetscErrorCode  KSPGetComputeSingularValues(KSP ksp,PetscBool  *flg)
1590: {
1594:   *flg = ksp->calc_sings;
1595:   return(0);
1596: }

1598: /*@
1599:    KSPSetComputeSingularValues - Sets a flag so that the extreme singular
1600:    values will be calculated via a Lanczos or Arnoldi process as the linear
1601:    system is solved.

1603:    Logically Collective on ksp

1605:    Input Parameters:
1606: +  ksp - iterative context obtained from KSPCreate()
1607: -  flg - PETSC_TRUE or PETSC_FALSE

1609:    Options Database Key:
1610: .  -ksp_monitor_singular_value - Activates KSPSetComputeSingularValues()

1612:    Notes:
1613:    Currently this option is not valid for all iterative methods.

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

1619:    Level: advanced

1621: .seealso: KSPComputeExtremeSingularValues(), KSPMonitorSingularValue(), KSP
1622: @*/
1623: PetscErrorCode  KSPSetComputeSingularValues(KSP ksp,PetscBool flg)
1624: {
1628:   ksp->calc_sings = flg;
1629:   return(0);
1630: }

1632: /*@
1633:    KSPGetComputeEigenvalues - Gets the flag indicating that the extreme eigenvalues
1634:    values will be calculated via a Lanczos or Arnoldi process as the linear
1635:    system is solved.

1637:    Not Collective

1639:    Input Parameter:
1640: .  ksp - iterative context obtained from KSPCreate()

1642:    Output Parameter:
1643: .  flg - PETSC_TRUE or PETSC_FALSE

1645:    Notes:
1646:    Currently this option is not valid for all iterative methods.

1648:    Level: advanced

1650: .seealso: KSPComputeEigenvalues(), KSPComputeEigenvaluesExplicitly(), KSP
1651: @*/
1652: PetscErrorCode  KSPGetComputeEigenvalues(KSP ksp,PetscBool  *flg)
1653: {
1657:   *flg = ksp->calc_sings;
1658:   return(0);
1659: }

1661: /*@
1662:    KSPSetComputeEigenvalues - Sets a flag so that the extreme eigenvalues
1663:    values will be calculated via a Lanczos or Arnoldi process as the linear
1664:    system is solved.

1666:    Logically Collective on ksp

1668:    Input Parameters:
1669: +  ksp - iterative context obtained from KSPCreate()
1670: -  flg - PETSC_TRUE or PETSC_FALSE

1672:    Notes:
1673:    Currently this option is not valid for all iterative methods.

1675:    Level: advanced

1677: .seealso: KSPComputeEigenvalues(), KSPComputeEigenvaluesExplicitly(), KSP
1678: @*/
1679: PetscErrorCode  KSPSetComputeEigenvalues(KSP ksp,PetscBool flg)
1680: {
1684:   ksp->calc_sings = flg;
1685:   return(0);
1686: }

1688: /*@
1689:    KSPSetComputeRitz - Sets a flag so that the Ritz or harmonic Ritz pairs
1690:    will be calculated via a Lanczos or Arnoldi process as the linear
1691:    system is solved.

1693:    Logically Collective on ksp

1695:    Input Parameters:
1696: +  ksp - iterative context obtained from KSPCreate()
1697: -  flg - PETSC_TRUE or PETSC_FALSE

1699:    Notes:
1700:    Currently this option is only valid for the GMRES method.

1702:    Level: advanced

1704: .seealso: KSPComputeRitz(), KSP
1705: @*/
1706: PetscErrorCode  KSPSetComputeRitz(KSP ksp, PetscBool flg)
1707: {
1711:   ksp->calc_ritz = flg;
1712:   return(0);
1713: }

1715: /*@
1716:    KSPGetRhs - Gets the right-hand-side vector for the linear system to
1717:    be solved.

1719:    Not Collective

1721:    Input Parameter:
1722: .  ksp - iterative context obtained from KSPCreate()

1724:    Output Parameter:
1725: .  r - right-hand-side vector

1727:    Level: developer

1729: .seealso: KSPGetSolution(), KSPSolve(), KSP
1730: @*/
1731: PetscErrorCode  KSPGetRhs(KSP ksp,Vec *r)
1732: {
1736:   *r = ksp->vec_rhs;
1737:   return(0);
1738: }

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

1745:    Not Collective

1747:    Input Parameters:
1748: .  ksp - iterative context obtained from KSPCreate()

1750:    Output Parameters:
1751: .  v - solution vector

1753:    Level: developer

1755: .seealso: KSPGetRhs(),  KSPBuildSolution(), KSPSolve(), KSP
1756: @*/
1757: PetscErrorCode  KSPGetSolution(KSP ksp,Vec *v)
1758: {
1762:   *v = ksp->vec_sol;
1763:   return(0);
1764: }

1766: /*@
1767:    KSPSetPC - Sets the preconditioner to be used to calculate the
1768:    Section 1.5 Writing Application Codes with PETSc of the preconditioner on a vector.

1770:    Collective on ksp

1772:    Input Parameters:
1773: +  ksp - iterative context obtained from KSPCreate()
1774: -  pc   - the preconditioner object (can be NULL)

1776:    Notes:
1777:    Use KSPGetPC() to retrieve the preconditioner context.

1779:    Level: developer

1781: .seealso: KSPGetPC(), KSP
1782: @*/
1783: PetscErrorCode  KSPSetPC(KSP ksp,PC pc)
1784: {

1789:   if (pc) {
1792:   }
1793:   PetscObjectReference((PetscObject)pc);
1794:   PCDestroy(&ksp->pc);
1795:   ksp->pc = pc;
1796:   PetscLogObjectParent((PetscObject)ksp,(PetscObject)ksp->pc);
1797:   return(0);
1798: }

1800: /*@
1801:    KSPGetPC - Returns a pointer to the preconditioner context
1802:    set with KSPSetPC().

1804:    Not Collective

1806:    Input Parameters:
1807: .  ksp - iterative context obtained from KSPCreate()

1809:    Output Parameter:
1810: .  pc - preconditioner context

1812:    Level: developer

1814: .seealso: KSPSetPC(), KSP
1815: @*/
1816: PetscErrorCode  KSPGetPC(KSP ksp,PC *pc)
1817: {

1823:   if (!ksp->pc) {
1824:     PCCreate(PetscObjectComm((PetscObject)ksp),&ksp->pc);
1825:     PetscObjectIncrementTabLevel((PetscObject)ksp->pc,(PetscObject)ksp,0);
1826:     PetscLogObjectParent((PetscObject)ksp,(PetscObject)ksp->pc);
1827:     PetscObjectSetOptions((PetscObject)ksp->pc,((PetscObject)ksp)->options);
1828:   }
1829:   *pc = ksp->pc;
1830:   return(0);
1831: }

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

1836:    Collective on ksp

1838:    Input Parameters:
1839: +  ksp - iterative context obtained from KSPCreate()
1840: .  it - iteration number
1841: -  rnorm - relative norm of the residual

1843:    Notes:
1844:    This routine is called by the KSP implementations.
1845:    It does not typically need to be called by the user.

1847:    Level: developer

1849: .seealso: KSPMonitorSet()
1850: @*/
1851: PetscErrorCode KSPMonitor(KSP ksp,PetscInt it,PetscReal rnorm)
1852: {
1853:   PetscInt       i, n = ksp->numbermonitors;

1857:   for (i=0; i<n; i++) {
1858:     (*ksp->monitor[i])(ksp,it,rnorm,ksp->monitorcontext[i]);
1859:   }
1860:   return(0);
1861: }

1863: /*@C
1864:    KSPMonitorSet - Sets an ADDITIONAL function to be called at every iteration to monitor
1865:    the residual/error etc.

1867:    Logically Collective on ksp

1869:    Input Parameters:
1870: +  ksp - iterative context obtained from KSPCreate()
1871: .  monitor - pointer to function (if this is NULL, it turns off monitoring
1872: .  mctx    - [optional] context for private data for the
1873:              monitor routine (use NULL if no context is desired)
1874: -  monitordestroy - [optional] routine that frees monitor context
1875:           (may be NULL)

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

1880: +  ksp - iterative context obtained from KSPCreate()
1881: .  it - iteration number
1882: .  rnorm - (estimated) 2-norm of (preconditioned) residual
1883: -  mctx  - optional monitoring context, as set by KSPMonitorSet()

1885:    Options Database Keys:
1886: +    -ksp_monitor        - sets KSPMonitorDefault()
1887: .    -ksp_monitor_true_residual    - sets KSPMonitorTrueResidualNorm()
1888: .    -ksp_monitor_max    - sets KSPMonitorTrueResidualMaxNorm()
1889: .    -ksp_monitor_lg_residualnorm    - sets line graph monitor,
1890:                            uses KSPMonitorLGResidualNormCreate()
1891: .    -ksp_monitor_lg_true_residualnorm   - sets line graph monitor,
1892:                            uses KSPMonitorLGResidualNormCreate()
1893: .    -ksp_monitor_singular_value    - sets KSPMonitorSingularValue()
1894: -    -ksp_monitor_cancel - cancels all monitors that have
1895:                           been hardwired into a code by
1896:                           calls to KSPMonitorSet(), but
1897:                           does not cancel those set via
1898:                           the options database.

1900:    Notes:
1901:    The default is to do nothing.  To print the residual, or preconditioned
1902:    residual if KSPSetNormType(ksp,KSP_NORM_PRECONDITIONED) was called, use
1903:    KSPMonitorDefault() as the monitoring routine, with a ASCII viewer as the
1904:    context.

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

1910:    Fortran Notes:
1911:     Only a single monitor function can be set for each KSP object

1913:    Level: beginner

1915: .seealso: KSPMonitorDefault(), KSPMonitorLGResidualNormCreate(), KSPMonitorCancel(), KSP
1916: @*/
1917: PetscErrorCode  KSPMonitorSet(KSP ksp,PetscErrorCode (*monitor)(KSP,PetscInt,PetscReal,void*),void *mctx,PetscErrorCode (*monitordestroy)(void**))
1918: {
1919:   PetscInt       i;
1921:   PetscBool      identical;

1925:   for (i=0; i<ksp->numbermonitors;i++) {
1926:     PetscMonitorCompare((PetscErrorCode (*)(void))monitor,mctx,monitordestroy,(PetscErrorCode (*)(void))ksp->monitor[i],ksp->monitorcontext[i],ksp->monitordestroy[i],&identical);
1927:     if (identical) return(0);
1928:   }
1929:   if (ksp->numbermonitors >= MAXKSPMONITORS) SETERRQ(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_OUTOFRANGE,"Too many KSP monitors set");
1930:   ksp->monitor[ksp->numbermonitors]          = monitor;
1931:   ksp->monitordestroy[ksp->numbermonitors]   = monitordestroy;
1932:   ksp->monitorcontext[ksp->numbermonitors++] = (void*)mctx;
1933:   return(0);
1934: }

1936: /*@
1937:    KSPMonitorCancel - Clears all monitors for a KSP object.

1939:    Logically Collective on ksp

1941:    Input Parameters:
1942: .  ksp - iterative context obtained from KSPCreate()

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

1949:    Level: intermediate

1951: .seealso: KSPMonitorDefault(), KSPMonitorLGResidualNormCreate(), KSPMonitorSet(), KSP
1952: @*/
1953: PetscErrorCode  KSPMonitorCancel(KSP ksp)
1954: {
1956:   PetscInt       i;

1960:   for (i=0; i<ksp->numbermonitors; i++) {
1961:     if (ksp->monitordestroy[i]) {
1962:       (*ksp->monitordestroy[i])(&ksp->monitorcontext[i]);
1963:     }
1964:   }
1965:   ksp->numbermonitors = 0;
1966:   return(0);
1967: }

1969: /*@C
1970:    KSPGetMonitorContext - Gets the monitoring context, as set by
1971:    KSPMonitorSet() for the FIRST monitor only.

1973:    Not Collective

1975:    Input Parameter:
1976: .  ksp - iterative context obtained from KSPCreate()

1978:    Output Parameter:
1979: .  ctx - monitoring context

1981:    Level: intermediate

1983: .seealso: KSPMonitorDefault(), KSPMonitorLGResidualNormCreate(), KSP
1984: @*/
1985: PetscErrorCode  KSPGetMonitorContext(KSP ksp,void **ctx)
1986: {
1989:   *ctx =      (ksp->monitorcontext[0]);
1990:   return(0);
1991: }

1993: /*@
1994:    KSPSetResidualHistory - Sets the array used to hold the residual history.
1995:    If set, this array will contain the residual norms computed at each
1996:    iteration of the solver.

1998:    Not Collective

2000:    Input Parameters:
2001: +  ksp - iterative context obtained from KSPCreate()
2002: .  a   - array to hold history
2003: .  na  - size of a
2004: -  reset - PETSC_TRUE indicates the history counter is reset to zero
2005:            for each new linear solve

2007:    Level: advanced

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

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

2016: .seealso: KSPGetResidualHistory(), KSP

2018: @*/
2019: PetscErrorCode  KSPSetResidualHistory(KSP ksp,PetscReal a[],PetscInt na,PetscBool reset)
2020: {


2026:   PetscFree(ksp->res_hist_alloc);
2027:   if (na != PETSC_DECIDE && na != PETSC_DEFAULT && a) {
2028:     ksp->res_hist     = a;
2029:     ksp->res_hist_max = na;
2030:   } else {
2031:     if (na != PETSC_DECIDE && na != PETSC_DEFAULT) ksp->res_hist_max = na;
2032:     else                                           ksp->res_hist_max = 10000; /* like default ksp->max_it */
2033:     PetscCalloc1(ksp->res_hist_max,&ksp->res_hist_alloc);

2035:     ksp->res_hist = ksp->res_hist_alloc;
2036:   }
2037:   ksp->res_hist_len   = 0;
2038:   ksp->res_hist_reset = reset;
2039:   return(0);
2040: }

2042: /*@C
2043:    KSPGetResidualHistory - Gets the array used to hold the residual history
2044:    and the number of residuals it contains.

2046:    Not Collective

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

2051:    Output Parameters:
2052: +  a   - pointer to array to hold history (or NULL)
2053: -  na  - number of used entries in a (or NULL)

2055:    Level: advanced

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

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

2066: .seealso: KSPGetResidualHistory(), KSP

2068: @*/
2069: PetscErrorCode  KSPGetResidualHistory(KSP ksp,PetscReal *a[],PetscInt *na)
2070: {
2073:   if (a) *a = ksp->res_hist;
2074:   if (na) *na = ksp->res_hist_len;
2075:   return(0);
2076: }

2078: /*@C
2079:    KSPSetConvergenceTest - Sets the function to be used to determine
2080:    convergence.

2082:    Logically Collective on ksp

2084:    Input Parameters:
2085: +  ksp - iterative context obtained from KSPCreate()
2086: .  converge - pointer to the function
2087: .  cctx    - context for private data for the convergence routine (may be null)
2088: -  destroy - a routine for destroying the context (may be null)

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

2093: +  ksp - iterative context obtained from KSPCreate()
2094: .  it - iteration number
2095: .  rnorm - (estimated) 2-norm of (preconditioned) residual
2096: .  reason - the reason why it has converged or diverged
2097: -  cctx  - optional convergence context, as set by KSPSetConvergenceTest()


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

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

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

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

2114:    Level: advanced

2116: .seealso: KSPConvergedDefault(), KSPGetConvergenceContext(), KSPSetTolerances(), KSP, KSPGetConvergenceTest(), KSPGetAndClearConvergenceTest()
2117: @*/
2118: PetscErrorCode  KSPSetConvergenceTest(KSP ksp,PetscErrorCode (*converge)(KSP,PetscInt,PetscReal,KSPConvergedReason*,void*),void *cctx,PetscErrorCode (*destroy)(void*))
2119: {

2124:   if (ksp->convergeddestroy) {
2125:     (*ksp->convergeddestroy)(ksp->cnvP);
2126:   }
2127:   ksp->converged        = converge;
2128:   ksp->convergeddestroy = destroy;
2129:   ksp->cnvP             = (void*)cctx;
2130:   return(0);
2131: }

2133: /*@C
2134:    KSPGetConvergenceTest - Gets the function to be used to determine
2135:    convergence.

2137:    Logically Collective on ksp

2139:    Input Parameter:
2140: .   ksp - iterative context obtained from KSPCreate()

2142:    Output Parameter:
2143: +  converge - pointer to convergence test function
2144: .  cctx    - context for private data for the convergence routine (may be null)
2145: -  destroy - a routine for destroying the context (may be null)

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

2150: +  ksp - iterative context obtained from KSPCreate()
2151: .  it - iteration number
2152: .  rnorm - (estimated) 2-norm of (preconditioned) residual
2153: .  reason - the reason why it has converged or diverged
2154: -  cctx  - optional convergence context, as set by KSPSetConvergenceTest()

2156:    Level: advanced

2158: .seealso: KSPConvergedDefault(), KSPGetConvergenceContext(), KSPSetTolerances(), KSP, KSPSetConvergenceTest(), KSPGetAndClearConvergenceTest()
2159: @*/
2160: PetscErrorCode  KSPGetConvergenceTest(KSP ksp,PetscErrorCode (**converge)(KSP,PetscInt,PetscReal,KSPConvergedReason*,void*),void **cctx,PetscErrorCode (**destroy)(void*))
2161: {
2164:   if (converge) *converge = ksp->converged;
2165:   if (destroy)  *destroy  = ksp->convergeddestroy;
2166:   if (cctx)     *cctx     = ksp->cnvP;
2167:   return(0);
2168: }

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

2173:    Logically Collective on ksp

2175:    Input Parameter:
2176: .   ksp - iterative context obtained from KSPCreate()

2178:    Output Parameter:
2179: +  converge - pointer to convergence test function
2180: .  cctx    - context for private data for the convergence routine
2181: -  destroy - a routine for destroying the context

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

2186: +  ksp - iterative context obtained from KSPCreate()
2187: .  it - iteration number
2188: .  rnorm - (estimated) 2-norm of (preconditioned) residual
2189: .  reason - the reason why it has converged or diverged
2190: -  cctx  - optional convergence context, as set by KSPSetConvergenceTest()

2192:    Level: advanced

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

2198: .seealso: KSPConvergedDefault(), KSPGetConvergenceContext(), KSPSetTolerances(), KSP, KSPSetConvergenceTest(), KSPGetConvergenceTest()
2199: @*/
2200: PetscErrorCode  KSPGetAndClearConvergenceTest(KSP ksp,PetscErrorCode (**converge)(KSP,PetscInt,PetscReal,KSPConvergedReason*,void*),void **cctx,PetscErrorCode (**destroy)(void*))
2201: {
2204:   *converge             = ksp->converged;
2205:   *destroy              = ksp->convergeddestroy;
2206:   *cctx                 = ksp->cnvP;
2207:   ksp->converged        = NULL;
2208:   ksp->cnvP             = NULL;
2209:   ksp->convergeddestroy = NULL;
2210:   return(0);
2211: }

2213: /*@C
2214:    KSPGetConvergenceContext - Gets the convergence context set with
2215:    KSPSetConvergenceTest().

2217:    Not Collective

2219:    Input Parameter:
2220: .  ksp - iterative context obtained from KSPCreate()

2222:    Output Parameter:
2223: .  ctx - monitoring context

2225:    Level: advanced

2227: .seealso: KSPConvergedDefault(), KSPSetConvergenceTest(), KSP
2228: @*/
2229: PetscErrorCode  KSPGetConvergenceContext(KSP ksp,void **ctx)
2230: {
2233:   *ctx = ksp->cnvP;
2234:   return(0);
2235: }

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

2241:    Collective on ksp

2243:    Input Parameter:
2244: .  ctx - iterative context obtained from KSPCreate()

2246:    Output Parameter:
2247:    Provide exactly one of
2248: +  v - location to stash solution.
2249: -  V - the solution is returned in this location. This vector is created
2250:        internally. This vector should NOT be destroyed by the user with
2251:        VecDestroy().

2253:    Notes:
2254:    This routine can be used in one of two ways
2255: .vb
2256:       KSPBuildSolution(ksp,NULL,&V);
2257:    or
2258:       KSPBuildSolution(ksp,v,NULL); or KSPBuildSolution(ksp,v,&v);
2259: .ve
2260:    In the first case an internal vector is allocated to store the solution
2261:    (the user cannot destroy this vector). In the second case the solution
2262:    is generated in the vector that the user provides. Note that for certain
2263:    methods, such as KSPCG, the second case requires a copy of the solution,
2264:    while in the first case the call is essentially free since it simply
2265:    returns the vector where the solution already is stored. For some methods
2266:    like GMRES this is a reasonably expensive operation and should only be
2267:    used in truly needed.

2269:    Level: advanced

2271: .seealso: KSPGetSolution(), KSPBuildResidual(), KSP
2272: @*/
2273: PetscErrorCode  KSPBuildSolution(KSP ksp,Vec v,Vec *V)
2274: {

2279:   if (!V && !v) SETERRQ(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_WRONG,"Must provide either v or V");
2280:   if (!V) V = &v;
2281:   (*ksp->ops->buildsolution)(ksp,v,V);
2282:   return(0);
2283: }

2285: /*@C
2286:    KSPBuildResidual - Builds the residual in a vector provided.

2288:    Collective on ksp

2290:    Input Parameter:
2291: .  ksp - iterative context obtained from KSPCreate()

2293:    Output Parameters:
2294: +  v - optional location to stash residual.  If v is not provided,
2295:        then a location is generated.
2296: .  t - work vector.  If not provided then one is generated.
2297: -  V - the residual

2299:    Notes:
2300:    Regardless of whether or not v is provided, the residual is
2301:    returned in V.

2303:    Level: advanced

2305: .seealso: KSPBuildSolution()
2306: @*/
2307: PetscErrorCode  KSPBuildResidual(KSP ksp,Vec t,Vec v,Vec *V)
2308: {
2310:   PetscBool      flag = PETSC_FALSE;
2311:   Vec            w    = v,tt = t;

2315:   if (!w) {
2316:     VecDuplicate(ksp->vec_rhs,&w);
2317:     PetscLogObjectParent((PetscObject)ksp,(PetscObject)w);
2318:   }
2319:   if (!tt) {
2320:     VecDuplicate(ksp->vec_sol,&tt); flag = PETSC_TRUE;
2321:     PetscLogObjectParent((PetscObject)ksp,(PetscObject)tt);
2322:   }
2323:   (*ksp->ops->buildresidual)(ksp,tt,w,V);
2324:   if (flag) {VecDestroy(&tt);}
2325:   return(0);
2326: }

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

2332:    Logically Collective on ksp

2334:    Input Parameter:
2335: +  ksp - the KSP context
2336: -  scale - PETSC_TRUE or PETSC_FALSE

2338:    Options Database Key:
2339: +   -ksp_diagonal_scale -
2340: -   -ksp_diagonal_scale_fix - scale the matrix back AFTER the solve


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

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

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

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

2358:    Level: intermediate

2360: .seealso: KSPGetDiagonalScale(), KSPSetDiagonalScaleFix(), KSP
2361: @*/
2362: PetscErrorCode  KSPSetDiagonalScale(KSP ksp,PetscBool scale)
2363: {
2367:   ksp->dscale = scale;
2368:   return(0);
2369: }

2371: /*@
2372:    KSPGetDiagonalScale - Checks if KSP solver scales the matrix and
2373:                           right hand side

2375:    Not Collective

2377:    Input Parameter:
2378: .  ksp - the KSP context

2380:    Output Parameter:
2381: .  scale - PETSC_TRUE or PETSC_FALSE

2383:    Notes:
2384:     BE CAREFUL with this routine: it actually scales the matrix and right
2385:     hand side that define the system. After the system is solved the matrix
2386:     and right hand side remain scaled  unless you use KSPSetDiagonalScaleFix()

2388:    Level: intermediate

2390: .seealso: KSPSetDiagonalScale(), KSPSetDiagonalScaleFix(), KSP
2391: @*/
2392: PetscErrorCode  KSPGetDiagonalScale(KSP ksp,PetscBool  *scale)
2393: {
2397:   *scale = ksp->dscale;
2398:   return(0);
2399: }

2401: /*@
2402:    KSPSetDiagonalScaleFix - Tells KSP to diagonally scale the system
2403:      back after solving.

2405:    Logically Collective on ksp

2407:    Input Parameter:
2408: +  ksp - the KSP context
2409: -  fix - PETSC_TRUE to scale back after the system solve, PETSC_FALSE to not
2410:          rescale (default)

2412:    Notes:
2413:      Must be called after KSPSetDiagonalScale()

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

2420:    Level: intermediate

2422: .seealso: KSPGetDiagonalScale(), KSPSetDiagonalScale(), KSPGetDiagonalScaleFix(), KSP
2423: @*/
2424: PetscErrorCode  KSPSetDiagonalScaleFix(KSP ksp,PetscBool fix)
2425: {
2429:   ksp->dscalefix = fix;
2430:   return(0);
2431: }

2433: /*@
2434:    KSPGetDiagonalScaleFix - Determines if KSP diagonally scales the system
2435:      back after solving.

2437:    Not Collective

2439:    Input Parameter:
2440: .  ksp - the KSP context

2442:    Output Parameter:
2443: .  fix - PETSC_TRUE to scale back after the system solve, PETSC_FALSE to not
2444:          rescale (default)

2446:    Notes:
2447:      Must be called after KSPSetDiagonalScale()

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

2454:    Level: intermediate

2456: .seealso: KSPGetDiagonalScale(), KSPSetDiagonalScale(), KSPSetDiagonalScaleFix(), KSP
2457: @*/
2458: PetscErrorCode  KSPGetDiagonalScaleFix(KSP ksp,PetscBool  *fix)
2459: {
2463:   *fix = ksp->dscalefix;
2464:   return(0);
2465: }

2467: /*@C
2468:    KSPSetComputeOperators - set routine to compute the linear operators

2470:    Logically Collective

2472:    Input Arguments:
2473: +  ksp - the KSP context
2474: .  func - function to compute the operators
2475: -  ctx - optional context

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

2480: +  ksp - the KSP context
2481: .  A - the linear operator
2482: .  B - preconditioning matrix
2483: -  ctx - optional user-provided context

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

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

2491:    Level: beginner

2493: .seealso: KSPSetOperators(), KSPSetComputeRHS(), DMKSPSetComputeOperators(), KSPSetComputeInitialGuess()
2494: @*/
2495: PetscErrorCode KSPSetComputeOperators(KSP ksp,PetscErrorCode (*func)(KSP,Mat,Mat,void*),void *ctx)
2496: {
2498:   DM             dm;

2502:   KSPGetDM(ksp,&dm);
2503:   DMKSPSetComputeOperators(dm,func,ctx);
2504:   if (ksp->setupstage == KSP_SETUP_NEWRHS) ksp->setupstage = KSP_SETUP_NEWMATRIX;
2505:   return(0);
2506: }

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

2511:    Logically Collective

2513:    Input Arguments:
2514: +  ksp - the KSP context
2515: .  func - function to compute the right hand side
2516: -  ctx - optional context

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

2521: +  ksp - the KSP context
2522: .  b - right hand side of linear system
2523: -  ctx - optional user-provided context

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

2528:    Level: beginner

2530: .seealso: KSPSolve(), DMKSPSetComputeRHS(), KSPSetComputeOperators()
2531: @*/
2532: PetscErrorCode KSPSetComputeRHS(KSP ksp,PetscErrorCode (*func)(KSP,Vec,void*),void *ctx)
2533: {
2535:   DM             dm;

2539:   KSPGetDM(ksp,&dm);
2540:   DMKSPSetComputeRHS(dm,func,ctx);
2541:   return(0);
2542: }

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

2547:    Logically Collective

2549:    Input Arguments:
2550: +  ksp - the KSP context
2551: .  func - function to compute the initial guess
2552: -  ctx - optional context

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

2557: +  ksp - the KSP context
2558: .  x - solution vector
2559: -  ctx - optional user-provided context

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

2564:    Level: beginner

2566: .seealso: KSPSolve(), KSPSetComputeRHS(), KSPSetComputeOperators(), DMKSPSetComputeInitialGuess()
2567: @*/
2568: PetscErrorCode KSPSetComputeInitialGuess(KSP ksp,PetscErrorCode (*func)(KSP,Vec,void*),void *ctx)
2569: {
2571:   DM             dm;

2575:   KSPGetDM(ksp,&dm);
2576:   DMKSPSetComputeInitialGuess(dm,func,ctx);
2577:   return(0);
2578: }