Actual source code: itfunc.c

petsc-dev 2014-02-02
Report Typos and Errors
  2: /*
  3:       Interface KSP routines that the user calls.
  4: */

  6: #include <petsc-private/kspimpl.h>   /*I "petscksp.h" I*/
  7: #include <petscdm.h>

 11: /*@
 12:    KSPComputeExtremeSingularValues - Computes the extreme singular values
 13:    for the preconditioned operator. Called after or during KSPSolve().

 15:    Not Collective

 17:    Input Parameter:
 18: .  ksp - iterative context obtained from KSPCreate()

 20:    Output Parameters:
 21: .  emin, emax - extreme singular values

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

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

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

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

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

 41:    Level: advanced

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

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

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

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

 68: /*@
 69:    KSPComputeEigenvalues - Computes the extreme eigenvalues for the
 70:    preconditioned operator. Called after or during KSPSolve().

 72:    Not Collective

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

 79:    Output Parameters:
 80: +  r - real part of computed eigenvalues
 81: .  c - complex part of computed eigenvalues
 82: -  neig - number of eigenvalues computed (will be less than or equal to n)

 84:    Options Database Keys:
 85: +  -ksp_compute_eigenvalues - Prints eigenvalues to stdout
 86: -  -ksp_plot_eigenvalues - Plots eigenvalues in an x-window display

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

 95:    KSPComputeEigenvalues() does not usually provide accurate estimates; it is
 96:    intended only for assistance in understanding the convergence of iterative
 97:    methods, not for eigenanalysis.

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

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

106:    Level: advanced

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

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

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

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

133: /*@
134:    KSPSetUpOnBlocks - Sets up the preconditioner for each block in
135:    the block Jacobi, block Gauss-Seidel, and overlapping Schwarz
136:    methods.

138:    Collective on KSP

140:    Input Parameter:
141: .  ksp - the KSP context

143:    Notes:
144:    KSPSetUpOnBlocks() is a routine that the user can optinally call for
145:    more precise profiling (via -log_summary) of the setup phase for these
146:    block preconditioners.  If the user does not call KSPSetUpOnBlocks(),
147:    it will automatically be called from within KSPSolve().

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

152:    Level: advanced

154: .keywords: KSP, setup, blocks

156: .seealso: PCSetUpOnBlocks(), KSPSetUp(), PCSetUp()
157: @*/
158: PetscErrorCode  KSPSetUpOnBlocks(KSP ksp)
159: {

164:   if (!ksp->pc) {KSPGetPC(ksp,&ksp->pc);}
165:   PCSetUpOnBlocks(ksp->pc);
166:   return(0);
167: }

171: /*@
172:    KSPSetUp - Sets up the internal data structures for the
173:    later use of an iterative solver.

175:    Collective on KSP

177:    Input Parameter:
178: .  ksp   - iterative context obtained from KSPCreate()

180:    Level: developer

182: .keywords: KSP, setup

184: .seealso: KSPCreate(), KSPSolve(), KSPDestroy()
185: @*/
186: PetscErrorCode  KSPSetUp(KSP ksp)
187: {
189:   Mat            A,B;
190:   MatStructure   stflg = SAME_NONZERO_PATTERN;


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

198:   if (!((PetscObject)ksp)->type_name) {
199:     KSPSetType(ksp,KSPGMRES);
200:   }
201:   KSPSetUpNorms_Private(ksp,&ksp->normtype,&ksp->pc_side);

203:   if (ksp->dmActive && !ksp->setupstage) {
204:     /* first time in so build matrix and vector data structures using DM */
205:     if (!ksp->vec_rhs) {DMCreateGlobalVector(ksp->dm,&ksp->vec_rhs);}
206:     if (!ksp->vec_sol) {DMCreateGlobalVector(ksp->dm,&ksp->vec_sol);}
207:     DMCreateMatrix(ksp->dm,&A);
208:     KSPSetOperators(ksp,A,A,stflg);
209:     PetscObjectDereference((PetscObject)A);
210:   }

212:   if (ksp->dmActive) {
213:     DMKSP kdm;
214:     DMGetDMKSP(ksp->dm,&kdm);

216:     if (kdm->ops->computeinitialguess && ksp->setupstage != KSP_SETUP_NEWRHS) {
217:       /* only computes initial guess the first time through */
218:       (*kdm->ops->computeinitialguess)(ksp,ksp->vec_sol,kdm->initialguessctx);
219:       KSPSetInitialGuessNonzero(ksp,PETSC_TRUE);
220:     }
221:     if (kdm->ops->computerhs) {
222:       (*kdm->ops->computerhs)(ksp,ksp->vec_rhs,kdm->rhsctx);
223:     }

225:     if (ksp->setupstage != KSP_SETUP_NEWRHS) {
226:       if (kdm->ops->computeoperators) {
227:         KSPGetOperators(ksp,&A,&B,NULL);
228:         (*kdm->ops->computeoperators)(ksp,A,B,&stflg,kdm->operatorsctx);
229:         KSPSetOperators(ksp,A,B,stflg);
230:       } else SETERRQ(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_WRONGSTATE,"You called KSPSetDM() but did not use DMKSPSetComputeOperators() or KSPSetDMActive(dm,PETSC_FALSE);");
231:     }
232:   }

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

237:   switch (ksp->setupstage) {
238:   case KSP_SETUP_NEW:
239:     (*ksp->ops->setup)(ksp);
240:     break;
241:   case KSP_SETUP_NEWMATRIX: {   /* This should be replaced with a more general mechanism */
242:     KSPChebyshevSetNewMatrix(ksp);
243:   } break;
244:   default: break;
245:   }

247:   /* scale the matrix if requested */
248:   if (ksp->dscale) {
249:     Mat         mat,pmat;
250:     PetscScalar *xx;
251:     PetscInt    i,n;
252:     PetscBool   zeroflag = PETSC_FALSE;
253:     if (!ksp->pc) {KSPGetPC(ksp,&ksp->pc);}
254:     PCGetOperators(ksp->pc,&mat,&pmat,NULL);
255:     if (!ksp->diagonal) { /* allocate vector to hold diagonal */
256:       MatGetVecs(pmat,&ksp->diagonal,0);
257:     }
258:     MatGetDiagonal(pmat,ksp->diagonal);
259:     VecGetLocalSize(ksp->diagonal,&n);
260:     VecGetArray(ksp->diagonal,&xx);
261:     for (i=0; i<n; i++) {
262:       if (xx[i] != 0.0) xx[i] = 1.0/PetscSqrtReal(PetscAbsScalar(xx[i]));
263:       else {
264:         xx[i]    = 1.0;
265:         zeroflag = PETSC_TRUE;
266:       }
267:     }
268:     VecRestoreArray(ksp->diagonal,&xx);
269:     if (zeroflag) {
270:       PetscInfo(ksp,"Zero detected in diagonal of matrix, using 1 at those locations\n");
271:     }
272:     MatDiagonalScale(pmat,ksp->diagonal,ksp->diagonal);
273:     if (mat != pmat) {MatDiagonalScale(mat,ksp->diagonal,ksp->diagonal);}
274:     ksp->dscalefix2 = PETSC_FALSE;
275:   }
276:   PetscLogEventEnd(KSP_SetUp,ksp,ksp->vec_rhs,ksp->vec_sol,0);
277:   if (!ksp->pc) {KSPGetPC(ksp,&ksp->pc);}
278:   PCSetUp(ksp->pc);
279:   if (ksp->nullsp) {
280:     PetscBool test = PETSC_FALSE;
281:     PetscOptionsGetBool(((PetscObject)ksp)->prefix,"-ksp_test_null_space",&test,NULL);
282:     if (test) {
283:       Mat mat;
284:       PCGetOperators(ksp->pc,&mat,NULL,NULL);
285:       MatNullSpaceTest(ksp->nullsp,mat,NULL);
286:     }
287:   }
288:   ksp->setupstage = KSP_SETUP_NEWRHS;
289:   return(0);
290: }

292: #include <petscdraw.h>
295: /*@
296:    KSPSolve - Solves linear system.

298:    Collective on KSP

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

305:    Options Database Keys:
306: +  -ksp_compute_eigenvalues - compute preconditioned operators eigenvalues
307: .  -ksp_plot_eigenvalues - plot the computed eigenvalues in an X-window
308: .  -ksp_compute_eigenvalues_explicitly - compute the eigenvalues by forming the dense operator and useing LAPACK
309: .  -ksp_plot_eigenvalues_explicitly - plot the explicitly computing eigenvalues
310: .  -ksp_view_mat binary - save matrix to the default binary viewer
311: .  -ksp_view_pmat binary - save matrix used to build preconditioner to the default binary viewer
312: .  -ksp_view_rhs binary - save right hand side vector to the default binary viewer
313: .  -ksp_view_solution binary - save computed solution vector to the default binary viewer
314:            (can be read later with src/ksp/examples/tutorials/ex10.c for testing solvers)
315: .  -ksp_view_mat_explicit - for matrix-free operators, computes the matrix entries and views them
316: .  -ksp_view_preconditioned_operator_explicit - computes the product of the preconditioner and matrix as an explicit matrix and views it
317: .  -ksp_converged_reason - print reason for converged or diverged, also prints number of iterations
318: .  -ksp_final_residual - print 2-norm of true linear system residual at the end of the solution process
319: -  -ksp_view - print the ksp data structure at the end of the system solution

321:    Notes:

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

325:    The operator is specified with KSPSetOperators().

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

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

335:    Understanding Convergence:
336:    The routines KSPMonitorSet(), KSPComputeEigenvalues(), and
337:    KSPComputeEigenvaluesExplicitly() provide information on additional
338:    options to monitor convergence and print eigenvalue information.

340:    Level: beginner

342: .keywords: KSP, solve, linear system

344: .seealso: KSPCreate(), KSPSetUp(), KSPDestroy(), KSPSetTolerances(), KSPConvergedDefault(),
345:           KSPSolveTranspose(), KSPGetIterationNumber()
346: @*/
347: PetscErrorCode  KSPSolve(KSP ksp,Vec b,Vec x)
348: {
349:   PetscErrorCode    ierr;
350:   PetscMPIInt       rank;
351:   PetscBool         flag1,flag2,flag3,flg = PETSC_FALSE,inXisinB=PETSC_FALSE,guess_zero;
352:   Mat               mat,premat;


359:   if (x && x == b) {
360:     if (!ksp->guess_zero) SETERRQ(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_INCOMP,"Cannot use x == b with nonzero initial guess");
361:     VecDuplicate(b,&x);
362:     inXisinB = PETSC_TRUE;
363:   }
364:   if (b) {
365:     PetscObjectReference((PetscObject)b);
366:     VecDestroy(&ksp->vec_rhs);
367:     ksp->vec_rhs = b;
368:   }
369:   if (x) {
370:     PetscObjectReference((PetscObject)x);
371:     VecDestroy(&ksp->vec_sol);
372:     ksp->vec_sol = x;
373:   }
374:   KSPViewFromOptions(ksp,NULL,"-ksp_view_pre");

376:   if (ksp->presolve) {
377:     (*ksp->presolve)(ksp,ksp->vec_rhs,ksp->vec_sol,ksp->prectx);
378:   }
379:   PetscLogEventBegin(KSP_Solve,ksp,ksp->vec_rhs,ksp->vec_sol,0);

381:   /* reset the residual history list if requested */
382:   if (ksp->res_hist_reset) ksp->res_hist_len = 0;
383:   ksp->transpose_solve = PETSC_FALSE;

385:   if (ksp->guess) {
386:     KSPFischerGuessFormGuess(ksp->guess,ksp->vec_rhs,ksp->vec_sol);
387:     ksp->guess_zero = PETSC_FALSE;
388:   }
389:   /* KSPSetUp() scales the matrix if needed */
390:   KSPSetUp(ksp);
391:   KSPSetUpOnBlocks(ksp);

393:   /* diagonal scale RHS if called for */
394:   if (ksp->dscale) {
395:     VecPointwiseMult(ksp->vec_rhs,ksp->vec_rhs,ksp->diagonal);
396:     /* second time in, but matrix was scaled back to original */
397:     if (ksp->dscalefix && ksp->dscalefix2) {
398:       Mat mat,pmat;

400:       PCGetOperators(ksp->pc,&mat,&pmat,NULL);
401:       MatDiagonalScale(pmat,ksp->diagonal,ksp->diagonal);
402:       if (mat != pmat) {MatDiagonalScale(mat,ksp->diagonal,ksp->diagonal);}
403:     }

405:     /*  scale initial guess */
406:     if (!ksp->guess_zero) {
407:       if (!ksp->truediagonal) {
408:         VecDuplicate(ksp->diagonal,&ksp->truediagonal);
409:         VecCopy(ksp->diagonal,ksp->truediagonal);
410:         VecReciprocal(ksp->truediagonal);
411:       }
412:       VecPointwiseMult(ksp->vec_sol,ksp->vec_sol,ksp->truediagonal);
413:     }
414:   }
415:   PCPreSolve(ksp->pc,ksp);

417:   if (ksp->guess_zero) { VecSet(ksp->vec_sol,0.0);}
418:   if (ksp->guess_knoll) {
419:     PCApply(ksp->pc,ksp->vec_rhs,ksp->vec_sol);
420:     KSP_RemoveNullSpace(ksp,ksp->vec_sol);
421:     ksp->guess_zero = PETSC_FALSE;
422:   }

424:   /* can we mark the initial guess as zero for this solve? */
425:   guess_zero = ksp->guess_zero;
426:   if (!ksp->guess_zero) {
427:     PetscReal norm;

429:     VecNormAvailable(ksp->vec_sol,NORM_2,&flg,&norm);
430:     if (flg && !norm) ksp->guess_zero = PETSC_TRUE;
431:   }
432:   (*ksp->ops->solve)(ksp);
433:   ksp->guess_zero = guess_zero;

435:   if (!ksp->reason) SETERRQ(PetscObjectComm((PetscObject)ksp),PETSC_ERR_PLIB,"Internal error, solver returned without setting converged reason");
436:   if (ksp->printreason) {
437:     PetscViewerASCIIAddTab(PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)ksp)),((PetscObject)ksp)->tablevel);
438:     if (ksp->reason > 0) {
439:       PetscViewerASCIIPrintf(PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)ksp)),"Linear solve converged due to %s iterations %D\n",KSPConvergedReasons[ksp->reason],ksp->its);
440:     } else {
441:       PetscViewerASCIIPrintf(PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)ksp)),"Linear solve did not converge due to %s iterations %D\n",KSPConvergedReasons[ksp->reason],ksp->its);
442:     }
443:     PetscViewerASCIISubtractTab(PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)ksp)),((PetscObject)ksp)->tablevel);
444:   }
445:   PCPostSolve(ksp->pc,ksp);

447:   /* diagonal scale solution if called for */
448:   if (ksp->dscale) {
449:     VecPointwiseMult(ksp->vec_sol,ksp->vec_sol,ksp->diagonal);
450:     /* unscale right hand side and matrix */
451:     if (ksp->dscalefix) {
452:       Mat mat,pmat;

454:       VecReciprocal(ksp->diagonal);
455:       VecPointwiseMult(ksp->vec_rhs,ksp->vec_rhs,ksp->diagonal);
456:       PCGetOperators(ksp->pc,&mat,&pmat,NULL);
457:       MatDiagonalScale(pmat,ksp->diagonal,ksp->diagonal);
458:       if (mat != pmat) {MatDiagonalScale(mat,ksp->diagonal,ksp->diagonal);}
459:       VecReciprocal(ksp->diagonal);
460:       ksp->dscalefix2 = PETSC_TRUE;
461:     }
462:   }
463:   PetscLogEventEnd(KSP_Solve,ksp,ksp->vec_rhs,ksp->vec_sol,0);
464:   if (ksp->postsolve) {
465:     (*ksp->postsolve)(ksp,ksp->vec_rhs,ksp->vec_sol,ksp->postctx);
466:   }

468:   if (ksp->guess) {
469:     KSPFischerGuessUpdate(ksp->guess,ksp->vec_sol);
470:   }

472:   MPI_Comm_rank(PetscObjectComm((PetscObject)ksp),&rank);

474:   PCGetOperators(ksp->pc,&mat,&premat,NULL);
475:   MatViewFromOptions(mat,((PetscObject)ksp)->prefix,"-ksp_view_mat");
476:   MatViewFromOptions(premat,((PetscObject)ksp)->prefix,"-ksp_view_pmat");
477:   VecViewFromOptions(ksp->vec_rhs,((PetscObject)ksp)->prefix,"-ksp_view_rhs");

479:   flag1 = PETSC_FALSE;
480:   flag2 = PETSC_FALSE;
481:   flag3 = PETSC_FALSE;
482:   PetscOptionsGetBool(((PetscObject)ksp)->prefix,"-ksp_compute_eigenvalues",&flag1,NULL);
483:   PetscOptionsGetBool(((PetscObject)ksp)->prefix,"-ksp_plot_eigenvalues",&flag2,NULL);
484:   PetscOptionsGetBool(((PetscObject)ksp)->prefix,"-ksp_plot_eigencontours",&flag3,NULL);
485:   if (flag1 || flag2 || flag3) {
486:     PetscInt  nits,n,i,neig;
487:     PetscReal *r,*c;

489:     KSPGetIterationNumber(ksp,&nits);
490:     n    = nits+2;

492:     if (!nits) {
493:       PetscPrintf(PetscObjectComm((PetscObject)ksp),"Zero iterations in solver, cannot approximate any eigenvalues\n");
494:     } else {
495:       PetscMalloc2(n,&r,n,&c);
496:       KSPComputeEigenvalues(ksp,n,r,c,&neig);
497:       if (flag1) {
498:         PetscPrintf(PetscObjectComm((PetscObject)ksp),"Iteratively computed eigenvalues\n");
499:         for (i=0; i<neig; i++) {
500:           if (c[i] >= 0.0) {
501:             PetscPrintf(PetscObjectComm((PetscObject)ksp),"%g + %gi\n",(double)r[i],(double)c[i]);
502:           } else {
503:             PetscPrintf(PetscObjectComm((PetscObject)ksp),"%g - %gi\n",(double)r[i],-(double)c[i]);
504:           }
505:         }
506:       }
507:       if (flag2 && !rank) {
508:         PetscDraw   draw;
509:         PetscDrawSP drawsp;

511:         if (!ksp->eigviewer) {
512:           PetscViewerDrawOpen(PETSC_COMM_SELF,0,"Iteratively Computed Eigenvalues",PETSC_DECIDE,PETSC_DECIDE,400,400,&ksp->eigviewer);
513:         }
514:         PetscViewerDrawGetDraw(ksp->eigviewer,0,&draw);
515:         PetscDrawSPCreate(draw,1,&drawsp);
516:         PetscDrawSPReset(drawsp);
517:         for (i=0; i<neig; i++) {
518:           PetscDrawSPAddPoint(drawsp,r+i,c+i);
519:         }
520:         PetscDrawSPDraw(drawsp,PETSC_TRUE);
521:         PetscDrawSPDestroy(&drawsp);
522:       }
523:       if (flag3 && !rank) {
524:         KSPPlotEigenContours_Private(ksp,neig,r,c);
525:       }
526:       PetscFree2(r,c);
527:     }
528:   }

530:   flag1 = PETSC_FALSE;
531:   PetscOptionsGetBool(((PetscObject)ksp)->prefix,"-ksp_compute_singularvalues",&flag1,NULL);
532:   if (flag1) {
533:     PetscInt nits;

535:     KSPGetIterationNumber(ksp,&nits);
536:     if (!nits) {
537:       PetscPrintf(PetscObjectComm((PetscObject)ksp),"Zero iterations in solver, cannot approximate any singular values\n");
538:     } else {
539:       PetscReal emax,emin;

541:       KSPComputeExtremeSingularValues(ksp,&emax,&emin);
542:       PetscPrintf(PetscObjectComm((PetscObject)ksp),"Iteratively computed extreme singular values: max %g min %g max/min %g\n",(double)emax,(double)emin,(double)(emax/emin));
543:     }
544:   }


547:   flag1 = PETSC_FALSE;
548:   flag2 = PETSC_FALSE;
549:   PetscOptionsGetBool(((PetscObject)ksp)->prefix,"-ksp_compute_eigenvalues_explicitly",&flag1,NULL);
550:   PetscOptionsGetBool(((PetscObject)ksp)->prefix,"-ksp_plot_eigenvalues_explicitly",&flag2,NULL);
551:   if (flag1 || flag2) {
552:     PetscInt  n,i;
553:     PetscReal *r,*c;
554:     VecGetSize(ksp->vec_sol,&n);
555:     PetscMalloc2(n,&r,n,&c);
556:     KSPComputeEigenvaluesExplicitly(ksp,n,r,c);
557:     if (flag1) {
558:       PetscPrintf(PetscObjectComm((PetscObject)ksp),"Explicitly computed eigenvalues\n");
559:       for (i=0; i<n; i++) {
560:         if (c[i] >= 0.0) {
561:           PetscPrintf(PetscObjectComm((PetscObject)ksp),"%g + %gi\n",(double)r[i],(double)c[i]);
562:         } else {
563:           PetscPrintf(PetscObjectComm((PetscObject)ksp),"%g - %gi\n",(double)r[i],-(double)c[i]);
564:         }
565:       }
566:     }
567:     if (flag2 && !rank) {
568:       PetscDraw   draw;
569:       PetscDrawSP drawsp;

571:       if (!ksp->eigviewer) {
572:         PetscViewerDrawOpen(PETSC_COMM_SELF,0,"Explicitly Computed Eigenvalues",0,320,400,400,&ksp->eigviewer);
573:       }
574:       PetscViewerDrawGetDraw(ksp->eigviewer,0,&draw);
575:       PetscDrawSPCreate(draw,1,&drawsp);
576:       PetscDrawSPReset(drawsp);
577:       for (i=0; i<n; i++) {
578:         PetscDrawSPAddPoint(drawsp,r+i,c+i);
579:       }
580:       PetscDrawSPDraw(drawsp,PETSC_TRUE);
581:       PetscDrawSPDestroy(&drawsp);
582:     }
583:     PetscFree2(r,c);
584:   }

586:   PetscOptionsHasName(((PetscObject)ksp)->prefix,"-ksp_view_mat_explicit",&flag2);
587:   if (flag2) {
588:     Mat A,B;
589:     PCGetOperators(ksp->pc,&A,NULL,NULL);
590:     MatComputeExplicitOperator(A,&B);
591:     MatViewFromOptions(B,((PetscObject)ksp)->prefix,"-ksp_view_mat_explicit");
592:     MatDestroy(&B);
593:   }
594:   PetscOptionsHasName(((PetscObject)ksp)->prefix,"-ksp_view_preconditioned_operator_explicit",&flag2);
595:   if (flag2) {
596:     Mat B;
597:     KSPComputeExplicitOperator(ksp,&B);
598:     MatViewFromOptions(B,((PetscObject)ksp)->prefix,"-ksp_view_preconditioned_operator_explicit");
599:     MatDestroy(&B);
600:   }
601:   KSPViewFromOptions(ksp,NULL,"-ksp_view");

603:   flg  = PETSC_FALSE;
604:   PetscOptionsGetBool(((PetscObject)ksp)->prefix,"-ksp_final_residual",&flg,NULL);
605:   if (flg) {
606:     Mat       A;
607:     Vec       t;
608:     PetscReal norm;
609:     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");
610:     PCGetOperators(ksp->pc,&A,0,0);
611:     VecDuplicate(ksp->vec_rhs,&t);
612:     KSP_MatMult(ksp,A,ksp->vec_sol,t);
613:     VecAYPX(t, -1.0, ksp->vec_rhs);
614:     VecNorm(t,NORM_2,&norm);
615:     VecDestroy(&t);
616:     PetscPrintf(PetscObjectComm((PetscObject)ksp),"KSP final norm of residual %g\n",(double)norm);
617:   }
618:   VecViewFromOptions(ksp->vec_sol,((PetscObject)ksp)->prefix,"-ksp_view_solution");

620:   if (inXisinB) {
621:     VecCopy(x,b);
622:     VecDestroy(&x);
623:   }
624:   PetscObjectSAWsBlock((PetscObject)ksp);
625:   if (ksp->errorifnotconverged && ksp->reason < 0) SETERRQ(PetscObjectComm((PetscObject)ksp),PETSC_ERR_NOT_CONVERGED,"KSPSolve has not converged");
626:   return(0);
627: }

631: /*@
632:    KSPSolveTranspose - Solves the transpose of a linear system.

634:    Collective on KSP

636:    Input Parameter:
637: +  ksp - iterative context obtained from KSPCreate()
638: .  b - right hand side vector
639: -  x - solution vector

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

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

645:    Level: developer

647: .keywords: KSP, solve, linear system

649: .seealso: KSPCreate(), KSPSetUp(), KSPDestroy(), KSPSetTolerances(), KSPConvergedDefault(),
650:           KSPSolve()
651: @*/

653: PetscErrorCode  KSPSolveTranspose(KSP ksp,Vec b,Vec x)
654: {
656:   PetscBool      inXisinB=PETSC_FALSE;

662:   if (x == b) {
663:     VecDuplicate(b,&x);
664:     inXisinB = PETSC_TRUE;
665:   }
666:   PetscObjectReference((PetscObject)b);
667:   PetscObjectReference((PetscObject)x);
668:   VecDestroy(&ksp->vec_rhs);
669:   VecDestroy(&ksp->vec_sol);

671:   ksp->vec_rhs         = b;
672:   ksp->vec_sol         = x;
673:   ksp->transpose_solve = PETSC_TRUE;

675:   KSPSetUp(ksp);
676:   if (ksp->guess_zero) { VecSet(ksp->vec_sol,0.0);}
677:   (*ksp->ops->solve)(ksp);
678:   if (!ksp->reason) SETERRQ(PetscObjectComm((PetscObject)ksp),PETSC_ERR_PLIB,"Internal error, solver returned without setting converged reason");
679:   if (ksp->printreason) {
680:     if (ksp->reason > 0) {
681:       PetscPrintf(PetscObjectComm((PetscObject)ksp),"Linear solve converged due to %s iterations %D\n",KSPConvergedReasons[ksp->reason],ksp->its);
682:     } else {
683:       PetscPrintf(PetscObjectComm((PetscObject)ksp),"Linear solve did not converge due to %s iterations %D\n",KSPConvergedReasons[ksp->reason],ksp->its);
684:     }
685:   }
686:   if (inXisinB) {
687:     VecCopy(x,b);
688:     VecDestroy(&x);
689:   }
690:   if (ksp->errorifnotconverged && ksp->reason < 0) SETERRQ(PetscObjectComm((PetscObject)ksp),PETSC_ERR_NOT_CONVERGED,"KSPSolve has not converged");
691:   return(0);
692: }

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

699:    Collective on KSP

701:    Input Parameter:
702: .  ksp - iterative context obtained from KSPCreate()

704:    Level: beginner

706: .keywords: KSP, destroy

708: .seealso: KSPCreate(), KSPSetUp(), KSPSolve()
709: @*/
710: PetscErrorCode  KSPReset(KSP ksp)
711: {

716:   if (!ksp) return(0);
717:   if (ksp->ops->reset) {
718:     (*ksp->ops->reset)(ksp);
719:   }
720:   if (ksp->pc) {PCReset(ksp->pc);}
721:   KSPFischerGuessDestroy(&ksp->guess);
722:   VecDestroyVecs(ksp->nwork,&ksp->work);
723:   VecDestroy(&ksp->vec_rhs);
724:   VecDestroy(&ksp->vec_sol);
725:   VecDestroy(&ksp->diagonal);
726:   VecDestroy(&ksp->truediagonal);
727:   MatNullSpaceDestroy(&ksp->nullsp);

729:   ksp->setupstage = KSP_SETUP_NEW;
730:   return(0);
731: }

735: /*@
736:    KSPDestroy - Destroys KSP context.

738:    Collective on KSP

740:    Input Parameter:
741: .  ksp - iterative context obtained from KSPCreate()

743:    Level: beginner

745: .keywords: KSP, destroy

747: .seealso: KSPCreate(), KSPSetUp(), KSPSolve()
748: @*/
749: PetscErrorCode  KSPDestroy(KSP *ksp)
750: {
752:   PC             pc;

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

759:   PetscObjectSAWsViewOff((PetscObject)*ksp);
760:   /*
761:    Avoid a cascading call to PCReset(ksp->pc) from the following call:
762:    PCReset() shouldn't be called from KSPDestroy() as it is unprotected by pc's
763:    refcount (and may be shared, e.g., by other ksps).
764:    */
765:   pc         = (*ksp)->pc;
766:   (*ksp)->pc = NULL;
767:   KSPReset((*ksp));
768:   (*ksp)->pc = pc;
769:     if ((*ksp)->ops->destroy) {(*(*ksp)->ops->destroy)(*ksp);}

771:   DMDestroy(&(*ksp)->dm);
772:   PCDestroy(&(*ksp)->pc);
773:   PetscFree((*ksp)->res_hist_alloc);
774:   if ((*ksp)->convergeddestroy) {
775:     (*(*ksp)->convergeddestroy)((*ksp)->cnvP);
776:   }
777:   KSPMonitorCancel((*ksp));
778:   PetscViewerDestroy(&(*ksp)->eigviewer);
779:   PetscHeaderDestroy(ksp);
780:   return(0);
781: }

785: /*@
786:     KSPSetPCSide - Sets the preconditioning side.

788:     Logically Collective on KSP

790:     Input Parameter:
791: .   ksp - iterative context obtained from KSPCreate()

793:     Output Parameter:
794: .   side - the preconditioning side, where side is one of
795: .vb
796:       PC_LEFT - left preconditioning (default)
797:       PC_RIGHT - right preconditioning
798:       PC_SYMMETRIC - symmetric preconditioning
799: .ve

801:     Options Database Keys:
802: .   -ksp_pc_side <right,left,symmetric>

804:     Notes:
805:     Left preconditioning is used by default for most Krylov methods except KSPFGMRES which only supports right preconditioning.
806:     Symmetric preconditioning is currently available only for the KSPQCG method. Note, however, that
807:     symmetric preconditioning can be emulated by using either right or left
808:     preconditioning and a pre or post processing step.

810:     Level: intermediate

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

814: .seealso: KSPGetPCSide()
815: @*/
816: PetscErrorCode  KSPSetPCSide(KSP ksp,PCSide side)
817: {
821:   ksp->pc_side = side;
822:   return(0);
823: }

827: /*@
828:     KSPGetPCSide - Gets the preconditioning side.

830:     Not Collective

832:     Input Parameter:
833: .   ksp - iterative context obtained from KSPCreate()

835:     Output Parameter:
836: .   side - the preconditioning side, where side is one of
837: .vb
838:       PC_LEFT - left preconditioning (default)
839:       PC_RIGHT - right preconditioning
840:       PC_SYMMETRIC - symmetric preconditioning
841: .ve

843:     Level: intermediate

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

847: .seealso: KSPSetPCSide()
848: @*/
849: PetscErrorCode  KSPGetPCSide(KSP ksp,PCSide *side)
850: {

856:   KSPSetUpNorms_Private(ksp,&ksp->normtype,&ksp->pc_side);
857:   *side = ksp->pc_side;
858:   return(0);
859: }

863: /*@
864:    KSPGetTolerances - Gets the relative, absolute, divergence, and maximum
865:    iteration tolerances used by the default KSP convergence tests.

867:    Not Collective

869:    Input Parameter:
870: .  ksp - the Krylov subspace context

872:    Output Parameters:
873: +  rtol - the relative convergence tolerance
874: .  abstol - the absolute convergence tolerance
875: .  dtol - the divergence tolerance
876: -  maxits - maximum number of iterations

878:    Notes:
879:    The user can specify NULL for any parameter that is not needed.

881:    Level: intermediate

883: .keywords: KSP, get, tolerance, absolute, relative, divergence, convergence,
884:            maximum, iterations

886: .seealso: KSPSetTolerances()
887: @*/
888: PetscErrorCode  KSPGetTolerances(KSP ksp,PetscReal *rtol,PetscReal *abstol,PetscReal *dtol,PetscInt *maxits)
889: {
892:   if (abstol) *abstol = ksp->abstol;
893:   if (rtol) *rtol = ksp->rtol;
894:   if (dtol) *dtol = ksp->divtol;
895:   if (maxits) *maxits = ksp->max_it;
896:   return(0);
897: }

901: /*@
902:    KSPSetTolerances - Sets the relative, absolute, divergence, and maximum
903:    iteration tolerances used by the default KSP convergence testers.

905:    Logically Collective on KSP

907:    Input Parameters:
908: +  ksp - the Krylov subspace context
909: .  rtol - the relative convergence tolerance
910:    (relative decrease in the residual norm)
911: .  abstol - the absolute convergence tolerance
912:    (absolute size of the residual norm)
913: .  dtol - the divergence tolerance
914:    (amount residual can increase before KSPConvergedDefault()
915:    concludes that the method is diverging)
916: -  maxits - maximum number of iterations to use

918:    Options Database Keys:
919: +  -ksp_atol <abstol> - Sets abstol
920: .  -ksp_rtol <rtol> - Sets rtol
921: .  -ksp_divtol <dtol> - Sets dtol
922: -  -ksp_max_it <maxits> - Sets maxits

924:    Notes:
925:    Use PETSC_DEFAULT to retain the default value of any of the tolerances.

927:    See KSPConvergedDefault() for details on the use of these parameters
928:    in the default convergence test.  See also KSPSetConvergenceTest()
929:    for setting user-defined stopping criteria.

931:    Level: intermediate

933: .keywords: KSP, set, tolerance, absolute, relative, divergence,
934:            convergence, maximum, iterations

936: .seealso: KSPGetTolerances(), KSPConvergedDefault(), KSPSetConvergenceTest()
937: @*/
938: PetscErrorCode  KSPSetTolerances(KSP ksp,PetscReal rtol,PetscReal abstol,PetscReal dtol,PetscInt maxits)
939: {

947:   if (rtol != PETSC_DEFAULT) {
948:     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);
949:     ksp->rtol = rtol;
950:   }
951:   if (abstol != PETSC_DEFAULT) {
952:     if (abstol < 0.0) SETERRQ1(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_OUTOFRANGE,"Absolute tolerance %g must be non-negative",(double)abstol);
953:     ksp->abstol = abstol;
954:   }
955:   if (dtol != PETSC_DEFAULT) {
956:     if (dtol < 0.0) SETERRQ1(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_OUTOFRANGE,"Divergence tolerance %g must be larger than 1.0",(double)dtol);
957:     ksp->divtol = dtol;
958:   }
959:   if (maxits != PETSC_DEFAULT) {
960:     if (maxits < 0) SETERRQ1(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of iterations %D must be non-negative",maxits);
961:     ksp->max_it = maxits;
962:   }
963:   return(0);
964: }

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

973:    Logically Collective on KSP

975:    Input Parameters:
976: +  ksp - iterative context obtained from KSPCreate()
977: -  flg - PETSC_TRUE indicates the guess is non-zero, PETSC_FALSE indicates the guess is zero

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

982:    Level: beginner

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

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

989: .seealso: KSPGetInitialGuessNonzero(), KSPSetInitialGuessKnoll(), KSPGetInitialGuessKnoll()
990: @*/
991: PetscErrorCode  KSPSetInitialGuessNonzero(KSP ksp,PetscBool flg)
992: {
996:   ksp->guess_zero = (PetscBool) !(int)flg;
997:   return(0);
998: }

1002: /*@
1003:    KSPGetInitialGuessNonzero - Determines whether the KSP solver is using
1004:    a zero initial guess.

1006:    Not Collective

1008:    Input Parameter:
1009: .  ksp - iterative context obtained from KSPCreate()

1011:    Output Parameter:
1012: .  flag - PETSC_TRUE if guess is nonzero, else PETSC_FALSE

1014:    Level: intermediate

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

1018: .seealso: KSPSetInitialGuessNonzero(), KSPSetInitialGuessKnoll(), KSPGetInitialGuessKnoll()
1019: @*/
1020: PetscErrorCode  KSPGetInitialGuessNonzero(KSP ksp,PetscBool  *flag)
1021: {
1025:   if (ksp->guess_zero) *flag = PETSC_FALSE;
1026:   else *flag = PETSC_TRUE;
1027:   return(0);
1028: }

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

1035:    Logically Collective on KSP

1037:    Input Parameters:
1038: +  ksp - iterative context obtained from KSPCreate()
1039: -  flg - PETSC_TRUE indicates you want the error generated

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

1044:    Level: intermediate

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

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

1052: .seealso: KSPGetInitialGuessNonzero(), KSPSetInitialGuessKnoll(), KSPGetInitialGuessKnoll(), KSPGetErrorIfNotConverged()
1053: @*/
1054: PetscErrorCode  KSPSetErrorIfNotConverged(KSP ksp,PetscBool flg)
1055: {
1059:   ksp->errorifnotconverged = flg;
1060:   return(0);
1061: }

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

1068:    Not Collective

1070:    Input Parameter:
1071: .  ksp - iterative context obtained from KSPCreate()

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

1076:    Level: intermediate

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

1080: .seealso: KSPSetInitialGuessNonzero(), KSPSetInitialGuessKnoll(), KSPGetInitialGuessKnoll(), KSPSetErrorIfNotConverged()
1081: @*/
1082: PetscErrorCode  KSPGetErrorIfNotConverged(KSP ksp,PetscBool  *flag)
1083: {
1087:   *flag = ksp->errorifnotconverged;
1088:   return(0);
1089: }

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

1096:    Logically Collective on KSP

1098:    Input Parameters:
1099: +  ksp - iterative context obtained from KSPCreate()
1100: -  flg - PETSC_TRUE or PETSC_FALSE

1102:    Level: advanced


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

1107: .seealso: KSPGetInitialGuessKnoll(), KSPSetInitialGuessNonzero(), KSPGetInitialGuessNonzero()
1108: @*/
1109: PetscErrorCode  KSPSetInitialGuessKnoll(KSP ksp,PetscBool flg)
1110: {
1114:   ksp->guess_knoll = flg;
1115:   return(0);
1116: }

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

1124:    Not Collective

1126:    Input Parameter:
1127: .  ksp - iterative context obtained from KSPCreate()

1129:    Output Parameter:
1130: .  flag - PETSC_TRUE if using Knoll trick, else PETSC_FALSE

1132:    Level: advanced

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

1136: .seealso: KSPSetInitialGuessKnoll(), KSPSetInitialGuessNonzero(), KSPGetInitialGuessNonzero()
1137: @*/
1138: PetscErrorCode  KSPGetInitialGuessKnoll(KSP ksp,PetscBool  *flag)
1139: {
1143:   *flag = ksp->guess_knoll;
1144:   return(0);
1145: }

1149: /*@
1150:    KSPGetComputeSingularValues - Gets the flag indicating whether the extreme singular
1151:    values will be calculated via a Lanczos or Arnoldi process as the linear
1152:    system is solved.

1154:    Not Collective

1156:    Input Parameter:
1157: .  ksp - iterative context obtained from KSPCreate()

1159:    Output Parameter:
1160: .  flg - PETSC_TRUE or PETSC_FALSE

1162:    Options Database Key:
1163: .  -ksp_monitor_singular_value - Activates KSPSetComputeSingularValues()

1165:    Notes:
1166:    Currently this option is not valid for all iterative methods.

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

1172:    Level: advanced

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

1176: .seealso: KSPComputeExtremeSingularValues(), KSPMonitorSingularValue()
1177: @*/
1178: PetscErrorCode  KSPGetComputeSingularValues(KSP ksp,PetscBool  *flg)
1179: {
1183:   *flg = ksp->calc_sings;
1184:   return(0);
1185: }

1189: /*@
1190:    KSPSetComputeSingularValues - Sets a flag so that the extreme singular
1191:    values will be calculated via a Lanczos or Arnoldi process as the linear
1192:    system is solved.

1194:    Logically Collective on KSP

1196:    Input Parameters:
1197: +  ksp - iterative context obtained from KSPCreate()
1198: -  flg - PETSC_TRUE or PETSC_FALSE

1200:    Options Database Key:
1201: .  -ksp_monitor_singular_value - Activates KSPSetComputeSingularValues()

1203:    Notes:
1204:    Currently this option is not valid for all iterative methods.

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

1210:    Level: advanced

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

1214: .seealso: KSPComputeExtremeSingularValues(), KSPMonitorSingularValue()
1215: @*/
1216: PetscErrorCode  KSPSetComputeSingularValues(KSP ksp,PetscBool flg)
1217: {
1221:   ksp->calc_sings = flg;
1222:   return(0);
1223: }

1227: /*@
1228:    KSPGetComputeEigenvalues - Gets the flag indicating that the extreme eigenvalues
1229:    values will be calculated via a Lanczos or Arnoldi process as the linear
1230:    system is solved.

1232:    Not Collective

1234:    Input Parameter:
1235: .  ksp - iterative context obtained from KSPCreate()

1237:    Output Parameter:
1238: .  flg - PETSC_TRUE or PETSC_FALSE

1240:    Notes:
1241:    Currently this option is not valid for all iterative methods.

1243:    Level: advanced

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

1247: .seealso: KSPComputeEigenvalues(), KSPComputeEigenvaluesExplicitly()
1248: @*/
1249: PetscErrorCode  KSPGetComputeEigenvalues(KSP ksp,PetscBool  *flg)
1250: {
1254:   *flg = ksp->calc_sings;
1255:   return(0);
1256: }

1260: /*@
1261:    KSPSetComputeEigenvalues - Sets a flag so that the extreme eigenvalues
1262:    values will be calculated via a Lanczos or Arnoldi process as the linear
1263:    system is solved.

1265:    Logically Collective on KSP

1267:    Input Parameters:
1268: +  ksp - iterative context obtained from KSPCreate()
1269: -  flg - PETSC_TRUE or PETSC_FALSE

1271:    Notes:
1272:    Currently this option is not valid for all iterative methods.

1274:    Level: advanced

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

1278: .seealso: KSPComputeEigenvalues(), KSPComputeEigenvaluesExplicitly()
1279: @*/
1280: PetscErrorCode  KSPSetComputeEigenvalues(KSP ksp,PetscBool flg)
1281: {
1285:   ksp->calc_sings = flg;
1286:   return(0);
1287: }

1291: /*@
1292:    KSPGetRhs - Gets the right-hand-side vector for the linear system to
1293:    be solved.

1295:    Not Collective

1297:    Input Parameter:
1298: .  ksp - iterative context obtained from KSPCreate()

1300:    Output Parameter:
1301: .  r - right-hand-side vector

1303:    Level: developer

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

1307: .seealso: KSPGetSolution(), KSPSolve()
1308: @*/
1309: PetscErrorCode  KSPGetRhs(KSP ksp,Vec *r)
1310: {
1314:   *r = ksp->vec_rhs;
1315:   return(0);
1316: }

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

1325:    Not Collective

1327:    Input Parameters:
1328: .  ksp - iterative context obtained from KSPCreate()

1330:    Output Parameters:
1331: .  v - solution vector

1333:    Level: developer

1335: .keywords: KSP, get, solution

1337: .seealso: KSPGetRhs(),  KSPBuildSolution(), KSPSolve()
1338: @*/
1339: PetscErrorCode  KSPGetSolution(KSP ksp,Vec *v)
1340: {
1344:   *v = ksp->vec_sol;
1345:   return(0);
1346: }

1350: /*@
1351:    KSPSetPC - Sets the preconditioner to be used to calculate the
1352:    application of the preconditioner on a vector.

1354:    Collective on KSP

1356:    Input Parameters:
1357: +  ksp - iterative context obtained from KSPCreate()
1358: -  pc   - the preconditioner object

1360:    Notes:
1361:    Use KSPGetPC() to retrieve the preconditioner context (for example,
1362:    to free it at the end of the computations).

1364:    Level: developer

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

1368: .seealso: KSPGetPC()
1369: @*/
1370: PetscErrorCode  KSPSetPC(KSP ksp,PC pc)
1371: {

1378:   PetscObjectReference((PetscObject)pc);
1379:   PCDestroy(&ksp->pc);
1380:   ksp->pc = pc;
1381:   PetscLogObjectParent((PetscObject)ksp,(PetscObject)ksp->pc);
1382:   return(0);
1383: }

1387: /*@
1388:    KSPGetPC - Returns a pointer to the preconditioner context
1389:    set with KSPSetPC().

1391:    Not Collective

1393:    Input Parameters:
1394: .  ksp - iterative context obtained from KSPCreate()

1396:    Output Parameter:
1397: .  pc - preconditioner context

1399:    Level: developer

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

1403: .seealso: KSPSetPC()
1404: @*/
1405: PetscErrorCode  KSPGetPC(KSP ksp,PC *pc)
1406: {

1412:   if (!ksp->pc) {
1413:     PCCreate(PetscObjectComm((PetscObject)ksp),&ksp->pc);
1414:     PetscObjectIncrementTabLevel((PetscObject)ksp->pc,(PetscObject)ksp,0);
1415:     PetscLogObjectParent((PetscObject)ksp,(PetscObject)ksp->pc);
1416:   }
1417:   *pc = ksp->pc;
1418:   return(0);
1419: }

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

1426:    Collective on KSP

1428:    Input Parameters:
1429: +  ksp - iterative context obtained from KSPCreate()
1430: .  it - iteration number
1431: -  rnorm - relative norm of the residual

1433:    Notes:
1434:    This routine is called by the KSP implementations.
1435:    It does not typically need to be called by the user.

1437:    Level: developer

1439: .seealso: KSPMonitorSet()
1440: @*/
1441: PetscErrorCode KSPMonitor(KSP ksp,PetscInt it,PetscReal rnorm)
1442: {
1443:   PetscInt       i, n = ksp->numbermonitors;

1447:   for (i=0; i<n; i++) {
1448:     (*ksp->monitor[i])(ksp,it,rnorm,ksp->monitorcontext[i]);
1449:   }
1450:   return(0);
1451: }

1455: /*@C
1456:    KSPMonitorSet - Sets an ADDITIONAL function to be called at every iteration to monitor
1457:    the residual/error etc.

1459:    Logically Collective on KSP

1461:    Input Parameters:
1462: +  ksp - iterative context obtained from KSPCreate()
1463: .  monitor - pointer to function (if this is NULL, it turns off monitoring
1464: .  mctx    - [optional] context for private data for the
1465:              monitor routine (use NULL if no context is desired)
1466: -  monitordestroy - [optional] routine that frees monitor context
1467:           (may be NULL)

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

1472: +  ksp - iterative context obtained from KSPCreate()
1473: .  it - iteration number
1474: .  rnorm - (estimated) 2-norm of (preconditioned) residual
1475: -  mctx  - optional monitoring context, as set by KSPMonitorSet()

1477:    Options Database Keys:
1478: +    -ksp_monitor        - sets KSPMonitorDefault()
1479: .    -ksp_monitor_true_residual    - sets KSPMonitorTrueResidualNorm()
1480: .    -ksp_monitor_max    - sets KSPMonitorTrueResidualMaxNorm()
1481: .    -ksp_monitor_lg_residualnorm    - sets line graph monitor,
1482:                            uses KSPMonitorLGResidualNormCreate()
1483: .    -ksp_monitor_lg_true_residualnorm   - sets line graph monitor,
1484:                            uses KSPMonitorLGResidualNormCreate()
1485: .    -ksp_monitor_singular_value    - sets KSPMonitorSingularValue()
1486: -    -ksp_monitor_cancel - cancels all monitors that have
1487:                           been hardwired into a code by
1488:                           calls to KSPMonitorSet(), but
1489:                           does not cancel those set via
1490:                           the options database.

1492:    Notes:
1493:    The default is to do nothing.  To print the residual, or preconditioned
1494:    residual if KSPSetNormType(ksp,KSP_NORM_PRECONDITIONED) was called, use
1495:    KSPMonitorDefault() as the monitoring routine, with a null monitoring
1496:    context.

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

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

1504:    Level: beginner

1506: .keywords: KSP, set, monitor

1508: .seealso: KSPMonitorDefault(), KSPMonitorLGResidualNormCreate(), KSPMonitorCancel()
1509: @*/
1510: PetscErrorCode  KSPMonitorSet(KSP ksp,PetscErrorCode (*monitor)(KSP,PetscInt,PetscReal,void*),void *mctx,PetscErrorCode (*monitordestroy)(void**))
1511: {
1512:   PetscInt       i;

1517:   if (ksp->numbermonitors >= MAXKSPMONITORS) SETERRQ(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_OUTOFRANGE,"Too many KSP monitors set");
1518:   for (i=0; i<ksp->numbermonitors;i++) {
1519:     if (monitor == ksp->monitor[i] && monitordestroy == ksp->monitordestroy[i] && mctx == ksp->monitorcontext[i]) {
1520:       if (monitordestroy) {
1521:         (*monitordestroy)(&mctx);
1522:       }
1523:       return(0);
1524:     }
1525:   }
1526:   ksp->monitor[ksp->numbermonitors]          = monitor;
1527:   ksp->monitordestroy[ksp->numbermonitors]   = monitordestroy;
1528:   ksp->monitorcontext[ksp->numbermonitors++] = (void*)mctx;
1529:   return(0);
1530: }

1534: /*@
1535:    KSPMonitorCancel - Clears all monitors for a KSP object.

1537:    Logically Collective on KSP

1539:    Input Parameters:
1540: .  ksp - iterative context obtained from KSPCreate()

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

1547:    Level: intermediate

1549: .keywords: KSP, set, monitor

1551: .seealso: KSPMonitorDefault(), KSPMonitorLGResidualNormCreate(), KSPMonitorSet()
1552: @*/
1553: PetscErrorCode  KSPMonitorCancel(KSP ksp)
1554: {
1556:   PetscInt       i;

1560:   for (i=0; i<ksp->numbermonitors; i++) {
1561:     if (ksp->monitordestroy[i]) {
1562:       (*ksp->monitordestroy[i])(&ksp->monitorcontext[i]);
1563:     }
1564:   }
1565:   ksp->numbermonitors = 0;
1566:   return(0);
1567: }

1571: /*@C
1572:    KSPGetMonitorContext - Gets the monitoring context, as set by
1573:    KSPMonitorSet() for the FIRST monitor only.

1575:    Not Collective

1577:    Input Parameter:
1578: .  ksp - iterative context obtained from KSPCreate()

1580:    Output Parameter:
1581: .  ctx - monitoring context

1583:    Level: intermediate

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

1587: .seealso: KSPMonitorDefault(), KSPMonitorLGResidualNormCreate()
1588: @*/
1589: PetscErrorCode  KSPGetMonitorContext(KSP ksp,void **ctx)
1590: {
1593:   *ctx =      (ksp->monitorcontext[0]);
1594:   return(0);
1595: }

1599: /*@
1600:    KSPSetResidualHistory - Sets the array used to hold the residual history.
1601:    If set, this array will contain the residual norms computed at each
1602:    iteration of the solver.

1604:    Not Collective

1606:    Input Parameters:
1607: +  ksp - iterative context obtained from KSPCreate()
1608: .  a   - array to hold history
1609: .  na  - size of a
1610: -  reset - PETSC_TRUE indicates the history counter is reset to zero
1611:            for each new linear solve

1613:    Level: advanced

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

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

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

1623: .seealso: KSPGetResidualHistory()

1625: @*/
1626: PetscErrorCode  KSPSetResidualHistory(KSP ksp,PetscReal a[],PetscInt na,PetscBool reset)
1627: {


1633:   PetscFree(ksp->res_hist_alloc);
1634:   if (na != PETSC_DECIDE && na != PETSC_DEFAULT && a) {
1635:     ksp->res_hist     = a;
1636:     ksp->res_hist_max = na;
1637:   } else {
1638:     if (na != PETSC_DECIDE && na != PETSC_DEFAULT) ksp->res_hist_max = na;
1639:     else                                           ksp->res_hist_max = 10000; /* like default ksp->max_it */
1640:     PetscMalloc1(ksp->res_hist_max,&ksp->res_hist_alloc);

1642:     ksp->res_hist = ksp->res_hist_alloc;
1643:   }
1644:   ksp->res_hist_len   = 0;
1645:   ksp->res_hist_reset = reset;
1646:   return(0);
1647: }

1651: /*@C
1652:    KSPGetResidualHistory - Gets the array used to hold the residual history
1653:    and the number of residuals it contains.

1655:    Not Collective

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

1660:    Output Parameters:
1661: +  a   - pointer to array to hold history (or NULL)
1662: -  na  - number of used entries in a (or NULL)

1664:    Level: advanced

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

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

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

1677: .seealso: KSPGetResidualHistory()

1679: @*/
1680: PetscErrorCode  KSPGetResidualHistory(KSP ksp,PetscReal *a[],PetscInt *na)
1681: {
1684:   if (a) *a = ksp->res_hist;
1685:   if (na) *na = ksp->res_hist_len;
1686:   return(0);
1687: }

1691: /*@C
1692:    KSPSetConvergenceTest - Sets the function to be used to determine
1693:    convergence.

1695:    Logically Collective on KSP

1697:    Input Parameters:
1698: +  ksp - iterative context obtained from KSPCreate()
1699: .  converge - pointer to int function
1700: .  cctx    - context for private data for the convergence routine (may be null)
1701: -  destroy - a routine for destroying the context (may be null)

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

1706: +  ksp - iterative context obtained from KSPCreate()
1707: .  it - iteration number
1708: .  rnorm - (estimated) 2-norm of (preconditioned) residual
1709: .  reason - the reason why it has converged or diverged
1710: -  cctx  - optional convergence context, as set by KSPSetConvergenceTest()


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

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

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

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

1727:    Level: advanced

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

1731: .seealso: KSPConvergedDefault(), KSPGetConvergenceContext(), KSPSetTolerances()
1732: @*/
1733: PetscErrorCode  KSPSetConvergenceTest(KSP ksp,PetscErrorCode (*converge)(KSP,PetscInt,PetscReal,KSPConvergedReason*,void*),void *cctx,PetscErrorCode (*destroy)(void*))
1734: {

1739:   if (ksp->convergeddestroy) {
1740:     (*ksp->convergeddestroy)(ksp->cnvP);
1741:   }
1742:   ksp->converged        = converge;
1743:   ksp->convergeddestroy = destroy;
1744:   ksp->cnvP             = (void*)cctx;
1745:   return(0);
1746: }

1750: /*@C
1751:    KSPGetConvergenceContext - Gets the convergence context set with
1752:    KSPSetConvergenceTest().

1754:    Not Collective

1756:    Input Parameter:
1757: .  ksp - iterative context obtained from KSPCreate()

1759:    Output Parameter:
1760: .  ctx - monitoring context

1762:    Level: advanced

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

1766: .seealso: KSPConvergedDefault(), KSPSetConvergenceTest()
1767: @*/
1768: PetscErrorCode  KSPGetConvergenceContext(KSP ksp,void **ctx)
1769: {
1772:   *ctx = ksp->cnvP;
1773:   return(0);
1774: }

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

1782:    Collective on KSP

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

1787:    Output Parameter:
1788:    Provide exactly one of
1789: +  v - location to stash solution.
1790: -  V - the solution is returned in this location. This vector is created
1791:        internally. This vector should NOT be destroyed by the user with
1792:        VecDestroy().

1794:    Notes:
1795:    This routine can be used in one of two ways
1796: .vb
1797:       KSPBuildSolution(ksp,NULL,&V);
1798:    or
1799:       KSPBuildSolution(ksp,v,NULL); or KSPBuildSolution(ksp,v,&v);
1800: .ve
1801:    In the first case an internal vector is allocated to store the solution
1802:    (the user cannot destroy this vector). In the second case the solution
1803:    is generated in the vector that the user provides. Note that for certain
1804:    methods, such as KSPCG, the second case requires a copy of the solution,
1805:    while in the first case the call is essentially free since it simply
1806:    returns the vector where the solution already is stored. For some methods
1807:    like GMRES this is a reasonably expensive operation and should only be
1808:    used in truly needed.

1810:    Level: advanced

1812: .keywords: KSP, build, solution

1814: .seealso: KSPGetSolution(), KSPBuildResidual()
1815: @*/
1816: PetscErrorCode  KSPBuildSolution(KSP ksp,Vec v,Vec *V)
1817: {

1822:   if (!V && !v) SETERRQ(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_WRONG,"Must provide either v or V");
1823:   if (!V) V = &v;
1824:   (*ksp->ops->buildsolution)(ksp,v,V);
1825:   return(0);
1826: }

1830: /*@C
1831:    KSPBuildResidual - Builds the residual in a vector provided.

1833:    Collective on KSP

1835:    Input Parameter:
1836: .  ksp - iterative context obtained from KSPCreate()

1838:    Output Parameters:
1839: +  v - optional location to stash residual.  If v is not provided,
1840:        then a location is generated.
1841: .  t - work vector.  If not provided then one is generated.
1842: -  V - the residual

1844:    Notes:
1845:    Regardless of whether or not v is provided, the residual is
1846:    returned in V.

1848:    Level: advanced

1850: .keywords: KSP, build, residual

1852: .seealso: KSPBuildSolution()
1853: @*/
1854: PetscErrorCode  KSPBuildResidual(KSP ksp,Vec t,Vec v,Vec *V)
1855: {
1857:   PetscBool      flag = PETSC_FALSE;
1858:   Vec            w    = v,tt = t;

1862:   if (!w) {
1863:     VecDuplicate(ksp->vec_rhs,&w);
1864:     PetscLogObjectParent((PetscObject)ksp,(PetscObject)w);
1865:   }
1866:   if (!tt) {
1867:     VecDuplicate(ksp->vec_sol,&tt); flag = PETSC_TRUE;
1868:     PetscLogObjectParent((PetscObject)ksp,(PetscObject)tt);
1869:   }
1870:   (*ksp->ops->buildresidual)(ksp,tt,w,V);
1871:   if (flag) {VecDestroy(&tt);}
1872:   return(0);
1873: }

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

1881:    Logically Collective on KSP

1883:    Input Parameter:
1884: +  ksp - the KSP context
1885: -  scale - PETSC_TRUE or PETSC_FALSE

1887:    Options Database Key:
1888: +   -ksp_diagonal_scale -
1889: -   -ksp_diagonal_scale_fix - scale the matrix back AFTER the solve


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

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

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

1902:     If you use this with the PCType Eisenstat preconditioner than you can
1903:     use the PCEisenstatNoDiagonalScaling() option, or -pc_eisenstat_no_diagonal_scaling
1904:     to save some unneeded, redundant flops.

1906:    Level: intermediate

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

1910: .seealso: KSPGetDiagonalScale(), KSPSetDiagonalScaleFix()
1911: @*/
1912: PetscErrorCode  KSPSetDiagonalScale(KSP ksp,PetscBool scale)
1913: {
1917:   ksp->dscale = scale;
1918:   return(0);
1919: }

1923: /*@
1924:    KSPGetDiagonalScale - Checks if KSP solver scales the matrix and
1925:                           right hand side

1927:    Not Collective

1929:    Input Parameter:
1930: .  ksp - the KSP context

1932:    Output Parameter:
1933: .  scale - PETSC_TRUE or PETSC_FALSE

1935:    Notes:
1936:     BE CAREFUL with this routine: it actually scales the matrix and right
1937:     hand side that define the system. After the system is solved the matrix
1938:     and right hand side remain scaled  unless you use KSPSetDiagonalScaleFix()

1940:    Level: intermediate

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

1944: .seealso: KSPSetDiagonalScale(), KSPSetDiagonalScaleFix()
1945: @*/
1946: PetscErrorCode  KSPGetDiagonalScale(KSP ksp,PetscBool  *scale)
1947: {
1951:   *scale = ksp->dscale;
1952:   return(0);
1953: }

1957: /*@
1958:    KSPSetDiagonalScaleFix - Tells KSP to diagonally scale the system
1959:      back after solving.

1961:    Logically Collective on KSP

1963:    Input Parameter:
1964: +  ksp - the KSP context
1965: -  fix - PETSC_TRUE to scale back after the system solve, PETSC_FALSE to not
1966:          rescale (default)

1968:    Notes:
1969:      Must be called after KSPSetDiagonalScale()

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

1976:    Level: intermediate

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

1980: .seealso: KSPGetDiagonalScale(), KSPSetDiagonalScale(), KSPGetDiagonalScaleFix()
1981: @*/
1982: PetscErrorCode  KSPSetDiagonalScaleFix(KSP ksp,PetscBool fix)
1983: {
1987:   ksp->dscalefix = fix;
1988:   return(0);
1989: }

1993: /*@
1994:    KSPGetDiagonalScaleFix - Determines if KSP diagonally scales the system
1995:      back after solving.

1997:    Not Collective

1999:    Input Parameter:
2000: .  ksp - the KSP context

2002:    Output Parameter:
2003: .  fix - PETSC_TRUE to scale back after the system solve, PETSC_FALSE to not
2004:          rescale (default)

2006:    Notes:
2007:      Must be called after KSPSetDiagonalScale()

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

2014:    Level: intermediate

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

2018: .seealso: KSPGetDiagonalScale(), KSPSetDiagonalScale(), KSPSetDiagonalScaleFix()
2019: @*/
2020: PetscErrorCode  KSPGetDiagonalScaleFix(KSP ksp,PetscBool  *fix)
2021: {
2025:   *fix = ksp->dscalefix;
2026:   return(0);
2027: }

2031: /*@C
2032:    KSPSetComputeOperators - set routine to compute the linear operators

2034:    Logically Collective

2036:    Input Arguments:
2037: +  ksp - the KSP context
2038: .  func - function to compute the operators
2039: -  ctx - optional context

2041:    Calling sequence of func:
2042: $  func(KSP ksp,Mat *A,Mat *B,MatStructure *mstruct,void *ctx)

2044: +  ksp - the KSP context
2045: .  A - the linear operator
2046: .  B - preconditioning matrix
2047: .  mstruct - flag indicating structure, same as in KSPSetOperators(), one of SAME_NONZERO_PATTERN,DIFFERENT_NONZERO_PATTERN,SAME_PRECONDITIONER
2048: -  ctx - optional user-provided context

2050:    Level: beginner

2052: .seealso: KSPSetOperators(), DMKSPSetComputeOperators()
2053: @*/
2054: PetscErrorCode KSPSetComputeOperators(KSP ksp,PetscErrorCode (*func)(KSP,Mat,Mat,MatStructure*,void*),void *ctx)
2055: {
2057:   DM             dm;

2061:   KSPGetDM(ksp,&dm);
2062:   DMKSPSetComputeOperators(dm,func,ctx);
2063:   if (ksp->setupstage == KSP_SETUP_NEWRHS) ksp->setupstage = KSP_SETUP_NEWMATRIX;
2064:   return(0);
2065: }

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

2072:    Logically Collective

2074:    Input Arguments:
2075: +  ksp - the KSP context
2076: .  func - function to compute the right hand side
2077: -  ctx - optional context

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

2082: +  ksp - the KSP context
2083: .  b - right hand side of linear system
2084: -  ctx - optional user-provided context

2086:    Level: beginner

2088: .seealso: KSPSolve(), DMKSPSetComputeRHS()
2089: @*/
2090: PetscErrorCode KSPSetComputeRHS(KSP ksp,PetscErrorCode (*func)(KSP,Vec,void*),void *ctx)
2091: {
2093:   DM             dm;

2097:   KSPGetDM(ksp,&dm);
2098:   DMKSPSetComputeRHS(dm,func,ctx);
2099:   return(0);
2100: }

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

2107:    Logically Collective

2109:    Input Arguments:
2110: +  ksp - the KSP context
2111: .  func - function to compute the initial guess
2112: -  ctx - optional context

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

2117: +  ksp - the KSP context
2118: .  x - solution vector
2119: -  ctx - optional user-provided context

2121:    Level: beginner

2123: .seealso: KSPSolve(), DMKSPSetComputeInitialGuess()
2124: @*/
2125: PetscErrorCode KSPSetComputeInitialGuess(KSP ksp,PetscErrorCode (*func)(KSP,Vec,void*),void *ctx)
2126: {
2128:   DM             dm;

2132:   KSPGetDM(ksp,&dm);
2133:   DMKSPSetComputeInitialGuess(dm,func,ctx);
2134:   return(0);
2135: }