Actual source code: itfunc.c

  1: #define PETSCKSP_DLL

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

 7:  #include private/kspimpl.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:    Notes:
 24:    One must call KSPSetComputeSingularValues() before calling KSPSetUp() 
 25:    (or use the option -ksp_compute_eigenvalues) in order for this routine to work correctly.

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

 31:    Level: advanced

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

 35: .seealso: KSPSetComputeSingularValues(), KSPMonitorSingularValue(), KSPComputeEigenvalues()
 36: @*/
 37: PetscErrorCode  KSPComputeExtremeSingularValues(KSP ksp,PetscReal *emax,PetscReal *emin)
 38: {

 45:   if (!ksp->calc_sings) {
 46:     SETERRQ(4,"Singular values not requested before KSPSetUp()");
 47:   }

 49:   if (ksp->ops->computeextremesingularvalues) {
 50:     (*ksp->ops->computeextremesingularvalues)(ksp,emax,emin);
 51:   } else {
 52:     *emin = -1.0;
 53:     *emax = -1.0;
 54:   }
 55:   return(0);
 56: }

 60: /*@
 61:    KSPComputeEigenvalues - Computes the extreme eigenvalues for the
 62:    preconditioned operator. Called after or during KSPSolve().

 64:    Not Collective

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

 71:    Output Parameters:
 72: +  r - real part of computed eigenvalues
 73: .  c - complex part of computed eigenvalues
 74: -  neig - number of eigenvalues computed (will be less than or equal to n)

 76:    Options Database Keys:
 77: +  -ksp_compute_eigenvalues - Prints eigenvalues to stdout
 78: -  -ksp_plot_eigenvalues - Plots eigenvalues in an x-window display

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

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

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

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

 98:    Level: advanced

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

102: .seealso: KSPSetComputeSingularValues(), KSPMonitorSingularValue(), KSPComputeExtremeSingularValues()
103: @*/
104: PetscErrorCode  KSPComputeEigenvalues(KSP ksp,PetscInt n,PetscReal *r,PetscReal *c,PetscInt *neig)
105: {

113:   if (!ksp->calc_sings) {
114:     SETERRQ(4,"Eigenvalues not requested before KSPSetUp()");
115:   }

117:   if (ksp->ops->computeeigenvalues) {
118:     (*ksp->ops->computeeigenvalues)(ksp,n,r,c,neig);
119:   } else {
120:     *neig = 0;
121:   }
122:   return(0);
123: }

127: /*@
128:    KSPSetUpOnBlocks - Sets up the preconditioner for each block in
129:    the block Jacobi, block Gauss-Seidel, and overlapping Schwarz 
130:    methods.

132:    Collective on KSP

134:    Input Parameter:
135: .  ksp - the KSP context

137:    Notes:
138:    KSPSetUpOnBlocks() is a routine that the user can optinally call for
139:    more precise profiling (via -log_summary) of the setup phase for these
140:    block preconditioners.  If the user does not call KSPSetUpOnBlocks(),
141:    it will automatically be called from within KSPSolve().
142:    
143:    Calling KSPSetUpOnBlocks() is the same as calling PCSetUpOnBlocks()
144:    on the PC context within the KSP context.

146:    Level: advanced

148: .keywords: KSP, setup, blocks

150: .seealso: PCSetUpOnBlocks(), KSPSetUp(), PCSetUp()
151: @*/
152: PetscErrorCode  KSPSetUpOnBlocks(KSP ksp)
153: {

158:   if (!ksp->pc) {KSPGetPC(ksp,&ksp->pc);}
159:   PCSetUpOnBlocks(ksp->pc);
160:   return(0);
161: }

165: /*@
166:    KSPSetUp - Sets up the internal data structures for the
167:    later use of an iterative solver.

169:    Collective on KSP

171:    Input Parameter:
172: .  ksp   - iterative context obtained from KSPCreate()

174:    Level: developer

176: .keywords: KSP, setup

178: .seealso: KSPCreate(), KSPSolve(), KSPDestroy()
179: @*/
180: PetscErrorCode  KSPSetUp(KSP ksp)
181: {


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

190:   if (!((PetscObject)ksp)->type_name){
191:     KSPSetType(ksp,KSPGMRES);
192:   }

194:   if (ksp->setupcalled == 2) return(0);

196:   PetscLogEventBegin(KSP_SetUp,ksp,ksp->vec_rhs,ksp->vec_sol,0);

198:   if (!ksp->setupcalled) {
199:     (*ksp->ops->setup)(ksp);
200:   }

202:   /* scale the matrix if requested */
203:   if (ksp->dscale) {
204:     Mat mat,pmat;
205:     if (!ksp->pc) {KSPGetPC(ksp,&ksp->pc);}
206:     PCGetOperators(ksp->pc,&mat,&pmat,PETSC_NULL);
207:     if (mat == pmat) {
208:       PetscScalar  *xx;
209:       PetscInt     i,n;
210:       PetscTruth   zeroflag = PETSC_FALSE;

212:       if (!ksp->diagonal) { /* allocate vector to hold diagonal */
213:         MatGetVecs(pmat,&ksp->diagonal,0);
214:       }
215:       MatGetDiagonal(mat,ksp->diagonal);
216:       VecGetLocalSize(ksp->diagonal,&n);
217:       VecGetArray(ksp->diagonal,&xx);
218:       for (i=0; i<n; i++) {
219:         if (xx[i] != 0.0) xx[i] = 1.0/sqrt(PetscAbsScalar(xx[i]));
220:         else {
221:           xx[i]     = 1.0;
222:           zeroflag  = PETSC_TRUE;
223:         }
224:       }
225:       VecRestoreArray(ksp->diagonal,&xx);
226:       if (zeroflag) {
227:         PetscInfo(ksp,"Zero detected in diagonal of matrix, using 1 at those locations\n");
228:       }
229:       MatDiagonalScale(mat,ksp->diagonal,ksp->diagonal);
230:       ksp->dscalefix2 = PETSC_FALSE;
231:     } else {
232:       SETERRQ(PETSC_ERR_SUP,"No support for diagonal scaling of linear system if preconditioner matrix not actual matrix");
233:     }
234:   }
235:   PetscLogEventEnd(KSP_SetUp,ksp,ksp->vec_rhs,ksp->vec_sol,0);
236:   if (!ksp->pc) {KSPGetPC(ksp,&ksp->pc);}
237:   PCSetUp(ksp->pc);
238:   if (ksp->nullsp) {
239:     PetscTruth test = PETSC_FALSE;
240:     PetscOptionsGetTruth(((PetscObject)ksp)->prefix,"-ksp_test_null_space",&test,PETSC_NULL);
241:     if (test) {
242:       Mat mat;
243:       PCGetOperators(ksp->pc,&mat,PETSC_NULL,PETSC_NULL);
244:       MatNullSpaceTest(ksp->nullsp,mat,PETSC_NULL);
245:     }
246:   }
247:   ksp->setupcalled = 2;
248:   return(0);
249: }

253: /*@
254:    KSPSolve - Solves linear system.

256:    Collective on KSP

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

263:    Options Database Keys:
264: +  -ksp_compute_eigenvalues - compute preconditioned operators eigenvalues
265: .  -ksp_plot_eigenvalues - plot the computed eigenvalues in an X-window
266: .  -ksp_compute_eigenvalues_explicitly - compute the eigenvalues by forming the dense operator and useing LAPACK
267: .  -ksp_plot_eigenvalues_explicitly - plot the explicitly computing eigenvalues
268: .  -ksp_view_binary - save matrix and right hand side that define linear system to the default binary viewer (can be
269:                                 read later with src/ksp/examples/tutorials/ex10.c for testing solvers)
270: .  -ksp_converged_reason - print reason for converged or diverged, also prints number of iterations
271: .  -ksp_final_residual - print 2-norm of true linear system residual at the end of the solution process
272: -  -ksp_view - print the ksp data structure at the end of the system solution

274:    Notes:

276:    The operator is specified with PCSetOperators().

278:    Call KSPGetConvergedReason() to determine if the solver converged or failed and 
279:    why. The number of iterations can be obtained from KSPGetIterationNumber().
280:    
281:    If using a direct method (e.g., via the KSP solver
282:    KSPPREONLY and a preconditioner such as PCLU/PCILU),
283:    then its=1.  See KSPSetTolerances() and KSPDefaultConverged()
284:    for more details.

286:    Understanding Convergence:
287:    The routines KSPMonitorSet(), KSPComputeEigenvalues(), and
288:    KSPComputeEigenvaluesExplicitly() provide information on additional
289:    options to monitor convergence and print eigenvalue information.

291:    Level: beginner

293: .keywords: KSP, solve, linear system

295: .seealso: KSPCreate(), KSPSetUp(), KSPDestroy(), KSPSetTolerances(), KSPDefaultConverged(),
296:           KSPSolveTranspose(), KSPGetIterationNumber()
297: @*/
298: PetscErrorCode  KSPSolve(KSP ksp,Vec b,Vec x)
299: {
301:   PetscMPIInt    rank;
302:   PetscTruth     flag1,flag2,viewed=PETSC_FALSE,flg = PETSC_FALSE,inXisinB=PETSC_FALSE,guess_zero;
303:   char           view[10];
304:   char           filename[PETSC_MAX_PATH_LEN];
305:   PetscViewer    viewer;
306: 


313:   if (x == b) {
314:     VecDuplicate(b,&x);
315:     inXisinB = PETSC_TRUE;
316:   }
317:   PetscObjectReference((PetscObject)b);
318:   PetscObjectReference((PetscObject)x);
319:   if (ksp->vec_rhs) {VecDestroy(ksp->vec_rhs);}
320:   if (ksp->vec_sol) {VecDestroy(ksp->vec_sol);}
321:   ksp->vec_rhs = b;
322:   ksp->vec_sol = x;

324:   PetscOptionsGetTruth(((PetscObject)ksp)->prefix,"-ksp_view_binary",&flg,PETSC_NULL);
325:   if (flg) {
326:     Mat mat;
327:     PCGetOperators(ksp->pc,&mat,PETSC_NULL,PETSC_NULL);
328:     MatView(mat,PETSC_VIEWER_BINARY_(((PetscObject)ksp)->comm));
329:     VecView(ksp->vec_rhs,PETSC_VIEWER_BINARY_(((PetscObject)ksp)->comm));
330:   }
331:   PetscLogEventBegin(KSP_Solve,ksp,ksp->vec_rhs,ksp->vec_sol,0);

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

336:   PetscOptionsGetString(((PetscObject)ksp)->prefix,"-ksp_view",view,10,&flg);
337:   if (flg) {
338:     PetscStrcmp(view,"before",&viewed);
339:     if (viewed){
340:       PetscViewer viewer;
341:       PetscViewerASCIIGetStdout(((PetscObject)ksp)->comm,&viewer);
342:       KSPView(ksp,viewer);
343:     }
344:   }

346:   ksp->transpose_solve = PETSC_FALSE;

348:   if (ksp->guess) {
349:     KSPFischerGuessFormGuess(ksp->guess,ksp->vec_rhs,ksp->vec_sol);
350:     ksp->guess_zero = PETSC_FALSE;
351:   }
352:   /* KSPSetUp() scales the matrix if needed */
353:   KSPSetUp(ksp);
354:   KSPSetUpOnBlocks(ksp);

356:   /* diagonal scale RHS if called for */
357:   if (ksp->dscale) {
358:     VecPointwiseMult(ksp->vec_rhs,ksp->vec_rhs,ksp->diagonal);
359:     /* second time in, but matrix was scaled back to original */
360:     if (ksp->dscalefix && ksp->dscalefix2) {
361:       Mat mat;

363:       PCGetOperators(ksp->pc,&mat,PETSC_NULL,PETSC_NULL);
364:       MatDiagonalScale(mat,ksp->diagonal,ksp->diagonal);
365:     }

367:     /*  scale initial guess */
368:     if (!ksp->guess_zero) {
369:       if (!ksp->truediagonal) {
370:         VecDuplicate(ksp->diagonal,&ksp->truediagonal);
371:         VecCopy(ksp->diagonal,ksp->truediagonal);
372:         VecReciprocal(ksp->truediagonal);
373:       }
374:       VecPointwiseMult(ksp->vec_sol,ksp->vec_sol,ksp->truediagonal);
375:     }
376:   }
377:   PCPreSolve(ksp->pc,ksp);

379:   if (ksp->guess_zero) { VecSet(ksp->vec_sol,0.0);}
380:   if (ksp->guess_knoll) {
381:     PCApply(ksp->pc,ksp->vec_rhs,ksp->vec_sol);
382:     KSP_RemoveNullSpace(ksp,ksp->vec_sol);
383:     ksp->guess_zero = PETSC_FALSE;
384:   }

386:   /* can we mark the initial guess as zero for this solve? */
387:   guess_zero = ksp->guess_zero;
388:   if (!ksp->guess_zero) {
389:     PetscReal norm;

391:     VecNormAvailable(ksp->vec_sol,NORM_2,&flg,&norm);
392:     if (flg && !norm) {
393:       ksp->guess_zero = PETSC_TRUE;
394:     }
395:   }
396:   (*ksp->ops->solve)(ksp);
397:   ksp->guess_zero = guess_zero;

399:   if (!ksp->reason) {
400:     SETERRQ(PETSC_ERR_PLIB,"Internal error, solver returned without setting converged reason");
401:   }
402:   if (ksp->printreason) {
403:     if (ksp->reason > 0) {
404:       PetscPrintf(((PetscObject)ksp)->comm,"Linear solve converged due to %s iterations %D\n",KSPConvergedReasons[ksp->reason],ksp->its);
405:     } else {
406:       PetscPrintf(((PetscObject)ksp)->comm,"Linear solve did not converge due to %s iterations %D\n",KSPConvergedReasons[ksp->reason],ksp->its);
407:     }
408:   }
409:   PCPostSolve(ksp->pc,ksp);

411:   /* diagonal scale solution if called for */
412:   if (ksp->dscale) {
413:     VecPointwiseMult(ksp->vec_sol,ksp->vec_sol,ksp->diagonal);
414:     /* unscale right hand side and matrix */
415:     if (ksp->dscalefix) {
416:       Mat mat;

418:       VecReciprocal(ksp->diagonal);
419:       VecPointwiseMult(ksp->vec_rhs,ksp->vec_rhs,ksp->diagonal);
420:       PCGetOperators(ksp->pc,&mat,PETSC_NULL,PETSC_NULL);
421:       MatDiagonalScale(mat,ksp->diagonal,ksp->diagonal);
422:       VecReciprocal(ksp->diagonal);
423:       ksp->dscalefix2 = PETSC_TRUE;
424:     }
425:   }
426:   PetscLogEventEnd(KSP_Solve,ksp,ksp->vec_rhs,ksp->vec_sol,0);

428:   if (ksp->guess) {
429:     KSPFischerGuessUpdate(ksp->guess,ksp->vec_sol);
430:   }

432:   MPI_Comm_rank(((PetscObject)ksp)->comm,&rank);

434:   flag1 = PETSC_FALSE;
435:   flag2 = PETSC_FALSE;
436:   PetscOptionsGetTruth(((PetscObject)ksp)->prefix,"-ksp_compute_eigenvalues",&flag1,PETSC_NULL);
437:   PetscOptionsGetTruth(((PetscObject)ksp)->prefix,"-ksp_plot_eigenvalues",&flag2,PETSC_NULL);
438:   if (flag1 || flag2) {
439:     PetscInt   nits,n,i,neig;
440:     PetscReal *r,*c;
441: 
442:     KSPGetIterationNumber(ksp,&nits);
443:     n = nits+2;

445:     if (!nits) {
446:       PetscPrintf(((PetscObject)ksp)->comm,"Zero iterations in solver, cannot approximate any eigenvalues\n");
447:     } else {
448:       PetscMalloc(2*n*sizeof(PetscReal),&r);
449:       c = r + n;
450:       KSPComputeEigenvalues(ksp,n,r,c,&neig);
451:       if (flag1) {
452:         PetscPrintf(((PetscObject)ksp)->comm,"Iteratively computed eigenvalues\n");
453:         for (i=0; i<neig; i++) {
454:           if (c[i] >= 0.0) {PetscPrintf(((PetscObject)ksp)->comm,"%G + %Gi\n",r[i],c[i]);}
455:           else             {PetscPrintf(((PetscObject)ksp)->comm,"%G - %Gi\n",r[i],-c[i]);}
456:         }
457:       }
458:       if (flag2 && !rank) {
459:         PetscDraw   draw;
460:         PetscDrawSP drawsp;

462:         PetscViewerDrawOpen(PETSC_COMM_SELF,0,"Iteratively Computed Eigenvalues",PETSC_DECIDE,PETSC_DECIDE,300,300,&viewer);
463:         PetscViewerDrawGetDraw(viewer,0,&draw);
464:         PetscDrawSPCreate(draw,1,&drawsp);
465:         for (i=0; i<neig; i++) {
466:           PetscDrawSPAddPoint(drawsp,r+i,c+i);
467:         }
468:         PetscDrawSPDraw(drawsp);
469:         PetscDrawSPDestroy(drawsp);
470:         PetscViewerDestroy(viewer);
471:       }
472:       PetscFree(r);
473:     }
474:   }

476:   flag1 = PETSC_FALSE;
477:   PetscOptionsGetTruth(((PetscObject)ksp)->prefix,"-ksp_compute_singularvalues",&flag1,PETSC_NULL);
478:   if (flag1) {
479:     PetscInt   nits;

481:     KSPGetIterationNumber(ksp,&nits);
482:     if (!nits) {
483:       PetscPrintf(((PetscObject)ksp)->comm,"Zero iterations in solver, cannot approximate any singular values\n");
484:     } else {
485:       PetscReal emax,emin;

487:       KSPComputeExtremeSingularValues(ksp,&emax,&emin);
488:       PetscPrintf(((PetscObject)ksp)->comm,"Iteratively computed extreme singular values: max %G min %G max/min %G\n",emax,emin,emax/emin);
489:     }
490:   }


493:   flag1 = PETSC_FALSE;
494:   flag2 = PETSC_FALSE;
495:   PetscOptionsGetTruth(((PetscObject)ksp)->prefix,"-ksp_compute_eigenvalues_explicitly",&flag1,PETSC_NULL);
496:   PetscOptionsGetTruth(((PetscObject)ksp)->prefix,"-ksp_plot_eigenvalues_explicitly",&flag2,PETSC_NULL);
497:   if (flag1 || flag2) {
498:     PetscInt  n,i;
499:     PetscReal *r,*c;
500:     VecGetSize(ksp->vec_sol,&n);
501:     PetscMalloc2(n,PetscReal,&r,n,PetscReal,&c);
502:     KSPComputeEigenvaluesExplicitly(ksp,n,r,c);
503:     if (flag1) {
504:       PetscPrintf(((PetscObject)ksp)->comm,"Explicitly computed eigenvalues\n");
505:       for (i=0; i<n; i++) {
506:         if (c[i] >= 0.0) {PetscPrintf(((PetscObject)ksp)->comm,"%G + %Gi\n",r[i],c[i]);}
507:         else             {PetscPrintf(((PetscObject)ksp)->comm,"%G - %Gi\n",r[i],-c[i]);}
508:       }
509:     }
510:     if (flag2 && !rank) {
511:       PetscDraw   draw;
512:       PetscDrawSP drawsp;

514:       PetscViewerDrawOpen(PETSC_COMM_SELF,0,"Explicitly Computed Eigenvalues",0,320,300,300,&viewer);
515:       PetscViewerDrawGetDraw(viewer,0,&draw);
516:       PetscDrawSPCreate(draw,1,&drawsp);
517:       for (i=0; i<n; i++) {
518:         PetscDrawSPAddPoint(drawsp,r+i,c+i);
519:       }
520:       PetscDrawSPDraw(drawsp);
521:       PetscDrawSPDestroy(drawsp);
522:       PetscViewerDestroy(viewer);
523:     }
524:     PetscFree2(r,c);
525:   }

527:   flag2 = PETSC_FALSE;
528:   PetscOptionsGetTruth(((PetscObject)ksp)->prefix,"-ksp_view_operator",&flag2,PETSC_NULL);
529:   if (flag2) {
530:     Mat         A,B;
531:     PetscViewer viewer;

533:     PCGetOperators(ksp->pc,&A,PETSC_NULL,PETSC_NULL);
534:     MatComputeExplicitOperator(A,&B);
535:     PetscViewerASCIIGetStdout(((PetscObject)ksp)->comm,&viewer);
536:     PetscViewerPushFormat(viewer,PETSC_VIEWER_ASCII_MATLAB);
537:     MatView(B,viewer);
538:     PetscViewerPopFormat(viewer);
539:     MatDestroy(B);
540:   }
541:   flag2 = PETSC_FALSE;
542:   PetscOptionsGetTruth(((PetscObject)ksp)->prefix,"-ksp_view_operator_binary",&flag2,PETSC_NULL);
543:   if (flag2) {
544:     Mat A,B;
545:     PCGetOperators(ksp->pc,&A,PETSC_NULL,PETSC_NULL);
546:     MatComputeExplicitOperator(A,&B);
547:     MatView(B,PETSC_VIEWER_BINARY_(((PetscObject)ksp)->comm));
548:     MatDestroy(B);
549:   }
550:   flag2 = PETSC_FALSE;
551:   PetscOptionsGetTruth(((PetscObject)ksp)->prefix,"-ksp_view_preconditioned_operator_binary",&flag2,PETSC_NULL);
552:   if (flag2) {
553:     Mat B;
554:     KSPComputeExplicitOperator(ksp,&B);
555:     MatView(B,PETSC_VIEWER_BINARY_(((PetscObject)ksp)->comm));
556:     MatDestroy(B);
557:   }
558:   flag2 = PETSC_FALSE;
559:   PetscOptionsGetTruth(((PetscObject)ksp)->prefix,"-ksp_view_preconditioner_binary",&flag2,PETSC_NULL);
560:   if (flag2) {
561:     Mat B;
562:     PCComputeExplicitOperator(ksp->pc,&B);
563:     MatView(B,PETSC_VIEWER_BINARY_(((PetscObject)ksp)->comm));
564:     MatDestroy(B);
565:   }
566:   if (!viewed) {
567:     PetscOptionsGetString(((PetscObject)ksp)->prefix,"-ksp_view",filename,PETSC_MAX_PATH_LEN,&flg);
568:     if (flg && !PetscPreLoadingOn) {
569:       PetscViewerASCIIOpen(((PetscObject)ksp)->comm,filename,&viewer);
570:       KSPView(ksp,viewer);
571:       PetscViewerDestroy(viewer);
572:     }
573:   }
574:   flg  = PETSC_FALSE;
575:   PetscOptionsGetTruth(((PetscObject)ksp)->prefix,"-ksp_final_residual",&flg,PETSC_NULL);
576:   if (flg) {
577:     Mat         A;
578:     Vec         t;
579:     PetscReal   norm;
580:     if (ksp->dscale && !ksp->dscalefix) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Cannot compute final scale with -ksp_diagonal_scale except also with -ksp_diagonal_scale_fix");
581:     PCGetOperators(ksp->pc,&A,0,0);
582:     VecDuplicate(ksp->vec_sol,&t);
583:     KSP_MatMult(ksp,A,ksp->vec_sol,t);
584:     VecWAXPY(t,-1.0,t,ksp->vec_rhs);
585:     VecNorm(t,NORM_2,&norm);
586:     VecDestroy(t);
587:     PetscPrintf(((PetscObject)ksp)->comm,"KSP final norm of residual %G\n",norm);
588:   }
589:   if (inXisinB) {
590:     VecCopy(x,b);
591:     VecDestroy(x);
592:   }
593:   return(0);
594: }

598: /*@
599:    KSPSolveTranspose - Solves the transpose of a linear system. Usually
600:    accessed through KSPSolveTranspose().

602:    Collective on KSP

604:    Input Parameter:
605: +  ksp - iterative context obtained from KSPCreate()
606: .  b - right hand side vector
607: -  x - solution vector

609:    Note:
610:    Currently only supported by KSPType of KSPPREONLY. This routine is usally 
611:    only used internally by the BiCG solver on the subblocks in BJacobi and ASM.

613:    Level: developer

615: .keywords: KSP, solve, linear system

617: .seealso: KSPCreate(), KSPSetUp(), KSPDestroy(), KSPSetTolerances(), KSPDefaultConverged(),
618:           KSPSolve()
619: @*/
620: PetscErrorCode  KSPSolveTranspose(KSP ksp,Vec b,Vec x)
621: {
623:   PetscTruth     inXisinB=PETSC_FALSE;

629:   if (x == b) {
630:     VecDuplicate(b,&x);
631:     inXisinB = PETSC_TRUE;
632:   }
633:   PetscObjectReference((PetscObject)b);
634:   PetscObjectReference((PetscObject)x);
635:   if (ksp->vec_rhs) {VecDestroy(ksp->vec_rhs);}
636:   if (ksp->vec_sol) {VecDestroy(ksp->vec_sol);}
637:   ksp->vec_rhs = b;
638:   ksp->vec_sol = x;
639:   ksp->transpose_solve = PETSC_TRUE;
640:   KSPSetUp(ksp);
641:   if (ksp->guess_zero) { VecSet(ksp->vec_sol,0.0);}
642:   (*ksp->ops->solve)(ksp);
643:   if (!ksp->reason) {
644:     SETERRQ(PETSC_ERR_PLIB,"Internal error, solver returned without setting converged reason");
645:   }
646:   if (ksp->printreason) {
647:     if (ksp->reason > 0) {
648:       PetscPrintf(((PetscObject)ksp)->comm,"Linear solve converged due to %s iterations %D\n",KSPConvergedReasons[ksp->reason],ksp->its);
649:     } else {
650:       PetscPrintf(((PetscObject)ksp)->comm,"Linear solve did not converge due to %s iterations %D\n",KSPConvergedReasons[ksp->reason],ksp->its);
651:     }
652:   }
653:   if (inXisinB) {
654:     VecCopy(x,b);
655:     VecDestroy(x);
656:   }
657:   return(0);
658: }

662: /*@
663:    KSPDestroy - Destroys KSP context.

665:    Collective on KSP

667:    Input Parameter:
668: .  ksp - iterative context obtained from KSPCreate()

670:    Level: beginner

672: .keywords: KSP, destroy

674: .seealso: KSPCreate(), KSPSetUp(), KSPSolve()
675: @*/
676: PetscErrorCode  KSPDestroy(KSP ksp)
677: {

682:   if (--((PetscObject)ksp)->refct > 0) return(0);

684:   /* if memory was published with AMS then destroy it */
685:   PetscObjectDepublish(ksp);

687:   if (ksp->ops->destroy) {
688:     (*ksp->ops->destroy)(ksp);
689:   }
690:   if (ksp->guess) {
691:     KSPFischerGuessDestroy(ksp->guess);
692:   }
693:   PetscFree(ksp->res_hist_alloc);
694:   KSPMonitorCancel(ksp);
695:   if (ksp->pc) {PCDestroy(ksp->pc);}
696:   if (ksp->vec_rhs) {VecDestroy(ksp->vec_rhs);}
697:   if (ksp->vec_sol) {VecDestroy(ksp->vec_sol);}
698:   if (ksp->diagonal) {VecDestroy(ksp->diagonal);}
699:   if (ksp->truediagonal) {VecDestroy(ksp->truediagonal);}
700:   if (ksp->nullsp) {MatNullSpaceDestroy(ksp->nullsp);}
701:   if (ksp->convergeddestroy) {(*ksp->convergeddestroy)(ksp->cnvP);}
702:   PetscHeaderDestroy(ksp);
703:   return(0);
704: }

708: /*@
709:     KSPSetPreconditionerSide - Sets the preconditioning side.

711:     Collective on KSP

713:     Input Parameter:
714: .   ksp - iterative context obtained from KSPCreate()

716:     Output Parameter:
717: .   side - the preconditioning side, where side is one of
718: .vb
719:       PC_LEFT - left preconditioning (default)
720:       PC_RIGHT - right preconditioning
721:       PC_SYMMETRIC - symmetric preconditioning
722: .ve

724:     Options Database Keys:
725: +   -ksp_left_pc - Sets left preconditioning
726: .   -ksp_right_pc - Sets right preconditioning
727: -   -ksp_symmetric_pc - Sets symmetric preconditioning

729:     Notes:
730:     Left preconditioning is used by default.  Symmetric preconditioning is
731:     currently available only for the KSPQCG method. Note, however, that
732:     symmetric preconditioning can be emulated by using either right or left
733:     preconditioning and a pre or post processing step.

735:     Level: intermediate

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

739: .seealso: KSPGetPreconditionerSide()
740: @*/
741: PetscErrorCode  KSPSetPreconditionerSide(KSP ksp,PCSide side)
742: {
745:   ksp->pc_side = side;
746:   return(0);
747: }

751: /*@
752:     KSPGetPreconditionerSide - Gets the preconditioning side.

754:     Not Collective

756:     Input Parameter:
757: .   ksp - iterative context obtained from KSPCreate()

759:     Output Parameter:
760: .   side - the preconditioning side, where side is one of
761: .vb
762:       PC_LEFT - left preconditioning (default)
763:       PC_RIGHT - right preconditioning
764:       PC_SYMMETRIC - symmetric preconditioning
765: .ve

767:     Level: intermediate

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

771: .seealso: KSPSetPreconditionerSide()
772: @*/
773: PetscErrorCode  KSPGetPreconditionerSide(KSP ksp,PCSide *side)
774: {
778:   *side = ksp->pc_side;
779:   return(0);
780: }

784: /*@
785:    KSPGetTolerances - Gets the relative, absolute, divergence, and maximum
786:    iteration tolerances used by the default KSP convergence tests. 

788:    Not Collective

790:    Input Parameter:
791: .  ksp - the Krylov subspace context
792:   
793:    Output Parameters:
794: +  rtol - the relative convergence tolerance
795: .  abstol - the absolute convergence tolerance
796: .  dtol - the divergence tolerance
797: -  maxits - maximum number of iterations

799:    Notes:
800:    The user can specify PETSC_NULL for any parameter that is not needed.

802:    Level: intermediate

804: .keywords: KSP, get, tolerance, absolute, relative, divergence, convergence,
805:            maximum, iterations

807: .seealso: KSPSetTolerances()
808: @*/
809: PetscErrorCode  KSPGetTolerances(KSP ksp,PetscReal *rtol,PetscReal *abstol,PetscReal *dtol,PetscInt *maxits)
810: {
813:   if (abstol)   *abstol   = ksp->abstol;
814:   if (rtol)   *rtol   = ksp->rtol;
815:   if (dtol)   *dtol   = ksp->divtol;
816:   if (maxits) *maxits = ksp->max_it;
817:   return(0);
818: }

822: /*@
823:    KSPSetTolerances - Sets the relative, absolute, divergence, and maximum
824:    iteration tolerances used by the default KSP convergence testers. 

826:    Collective on KSP

828:    Input Parameters:
829: +  ksp - the Krylov subspace context
830: .  rtol - the relative convergence tolerance
831:    (relative decrease in the residual norm)
832: .  abstol - the absolute convergence tolerance 
833:    (absolute size of the residual norm)
834: .  dtol - the divergence tolerance
835:    (amount residual can increase before KSPDefaultConverged()
836:    concludes that the method is diverging)
837: -  maxits - maximum number of iterations to use

839:    Options Database Keys:
840: +  -ksp_atol <abstol> - Sets abstol
841: .  -ksp_rtol <rtol> - Sets rtol
842: .  -ksp_divtol <dtol> - Sets dtol
843: -  -ksp_max_it <maxits> - Sets maxits

845:    Notes:
846:    Use PETSC_DEFAULT to retain the default value of any of the tolerances.

848:    See KSPDefaultConverged() for details on the use of these parameters
849:    in the default convergence test.  See also KSPSetConvergenceTest() 
850:    for setting user-defined stopping criteria.

852:    Level: intermediate

854: .keywords: KSP, set, tolerance, absolute, relative, divergence, 
855:            convergence, maximum, iterations

857: .seealso: KSPGetTolerances(), KSPDefaultConverged(), KSPSetConvergenceTest()
858: @*/
859: PetscErrorCode  KSPSetTolerances(KSP ksp,PetscReal rtol,PetscReal abstol,PetscReal dtol,PetscInt maxits)
860: {
863:   if (abstol != PETSC_DEFAULT)   ksp->abstol   = abstol;
864:   if (rtol != PETSC_DEFAULT)   ksp->rtol   = rtol;
865:   if (dtol != PETSC_DEFAULT)   ksp->divtol = dtol;
866:   if (maxits != PETSC_DEFAULT) ksp->max_it = maxits;
867:   return(0);
868: }

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

877:    Collective on KSP

879:    Input Parameters:
880: +  ksp - iterative context obtained from KSPCreate()
881: -  flg - PETSC_TRUE indicates the guess is non-zero, PETSC_FALSE indicates the guess is zero

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

886:    Level: beginner

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

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

893: .seealso: KSPGetInitialGuessNonzero(), KSPSetInitialGuessKnoll(), KSPGetInitialGuessKnoll()
894: @*/
895: PetscErrorCode  KSPSetInitialGuessNonzero(KSP ksp,PetscTruth flg)
896: {
899:   ksp->guess_zero   = (PetscTruth)!(int)flg;
900:   return(0);
901: }

905: /*@
906:    KSPGetInitialGuessNonzero - Determines whether the KSP solver is using
907:    a zero initial guess.

909:    Not Collective

911:    Input Parameter:
912: .  ksp - iterative context obtained from KSPCreate()

914:    Output Parameter:
915: .  flag - PETSC_TRUE if guess is nonzero, else PETSC_FALSE

917:    Level: intermediate

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

921: .seealso: KSPSetInitialGuessNonzero(), KSPSetInitialGuessKnoll(), KSPGetInitialGuessKnoll()
922: @*/
923: PetscErrorCode  KSPGetInitialGuessNonzero(KSP ksp,PetscTruth *flag)
924: {
928:   if (ksp->guess_zero) *flag = PETSC_FALSE;
929:   else                 *flag = PETSC_TRUE;
930:   return(0);
931: }

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

938:    Collective on KSP

940:    Input Parameters:
941: +  ksp - iterative context obtained from KSPCreate()
942: -  flg - PETSC_TRUE or PETSC_FALSE

944:    Level: advanced


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

949: .seealso: KSPGetInitialGuessKnoll(), KSPSetInitialGuessNonzero(), KSPGetInitialGuessNonzero()
950: @*/
951: PetscErrorCode  KSPSetInitialGuessKnoll(KSP ksp,PetscTruth flg)
952: {
955:   ksp->guess_knoll   = flg;
956:   return(0);
957: }

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

965:    Not Collective

967:    Input Parameter:
968: .  ksp - iterative context obtained from KSPCreate()

970:    Output Parameter:
971: .  flag - PETSC_TRUE if using Knoll trick, else PETSC_FALSE

973:    Level: advanced

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

977: .seealso: KSPSetInitialGuessKnoll(), KSPSetInitialGuessNonzero(), KSPGetInitialGuessNonzero()
978: @*/
979: PetscErrorCode  KSPGetInitialGuessKnoll(KSP ksp,PetscTruth *flag)
980: {
984:   *flag = ksp->guess_knoll;
985:   return(0);
986: }

990: /*@
991:    KSPGetComputeSingularValues - Gets the flag indicating whether the extreme singular 
992:    values will be calculated via a Lanczos or Arnoldi process as the linear 
993:    system is solved.

995:    Collective on KSP

997:    Input Parameter:
998: .  ksp - iterative context obtained from KSPCreate()

1000:    Output Parameter:
1001: .  flg - PETSC_TRUE or PETSC_FALSE

1003:    Options Database Key:
1004: .  -ksp_monitor_singular_value - Activates KSPSetComputeSingularValues()

1006:    Notes:
1007:    Currently this option is not valid for all iterative methods.

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

1013:    Level: advanced

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

1017: .seealso: KSPComputeExtremeSingularValues(), KSPMonitorSingularValue()
1018: @*/
1019: PetscErrorCode  KSPGetComputeSingularValues(KSP ksp,PetscTruth *flg)
1020: {
1024:   *flg = ksp->calc_sings;
1025:   return(0);
1026: }

1030: /*@
1031:    KSPSetComputeSingularValues - Sets a flag so that the extreme singular 
1032:    values will be calculated via a Lanczos or Arnoldi process as the linear 
1033:    system is solved.

1035:    Collective on KSP

1037:    Input Parameters:
1038: +  ksp - iterative context obtained from KSPCreate()
1039: -  flg - PETSC_TRUE or PETSC_FALSE

1041:    Options Database Key:
1042: .  -ksp_monitor_singular_value - Activates KSPSetComputeSingularValues()

1044:    Notes:
1045:    Currently this option is not valid for all iterative methods.

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

1051:    Level: advanced

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

1055: .seealso: KSPComputeExtremeSingularValues(), KSPMonitorSingularValue()
1056: @*/
1057: PetscErrorCode  KSPSetComputeSingularValues(KSP ksp,PetscTruth flg)
1058: {
1061:   ksp->calc_sings  = flg;
1062:   return(0);
1063: }

1067: /*@
1068:    KSPGetComputeEigenvalues - Gets the flag indicating that the extreme eigenvalues
1069:    values will be calculated via a Lanczos or Arnoldi process as the linear 
1070:    system is solved.

1072:    Collective on KSP

1074:    Input Parameter:
1075: .  ksp - iterative context obtained from KSPCreate()

1077:    Output Parameter:
1078: .  flg - PETSC_TRUE or PETSC_FALSE

1080:    Notes:
1081:    Currently this option is not valid for all iterative methods.

1083:    Level: advanced

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

1087: .seealso: KSPComputeEigenvalues(), KSPComputeEigenvaluesExplicitly()
1088: @*/
1089: PetscErrorCode  KSPGetComputeEigenvalues(KSP ksp,PetscTruth *flg)
1090: {
1094:   *flg = ksp->calc_sings;
1095:   return(0);
1096: }

1100: /*@
1101:    KSPSetComputeEigenvalues - Sets a flag so that the extreme eigenvalues
1102:    values will be calculated via a Lanczos or Arnoldi process as the linear 
1103:    system is solved.

1105:    Collective on KSP

1107:    Input Parameters:
1108: +  ksp - iterative context obtained from KSPCreate()
1109: -  flg - PETSC_TRUE or PETSC_FALSE

1111:    Notes:
1112:    Currently this option is not valid for all iterative methods.

1114:    Level: advanced

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

1118: .seealso: KSPComputeEigenvalues(), KSPComputeEigenvaluesExplicitly()
1119: @*/
1120: PetscErrorCode  KSPSetComputeEigenvalues(KSP ksp,PetscTruth flg)
1121: {
1124:   ksp->calc_sings  = flg;
1125:   return(0);
1126: }

1130: /*@
1131:    KSPGetRhs - Gets the right-hand-side vector for the linear system to
1132:    be solved.

1134:    Not Collective

1136:    Input Parameter:
1137: .  ksp - iterative context obtained from KSPCreate()

1139:    Output Parameter:
1140: .  r - right-hand-side vector

1142:    Level: developer

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

1146: .seealso: KSPGetSolution(), KSPSolve()
1147: @*/
1148: PetscErrorCode  KSPGetRhs(KSP ksp,Vec *r)
1149: {
1153:   *r = ksp->vec_rhs;
1154:   return(0);
1155: }

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

1164:    Not Collective

1166:    Input Parameters:
1167: .  ksp - iterative context obtained from KSPCreate()

1169:    Output Parameters:
1170: .  v - solution vector

1172:    Level: developer

1174: .keywords: KSP, get, solution

1176: .seealso: KSPGetRhs(),  KSPBuildSolution(), KSPSolve()
1177: @*/
1178: PetscErrorCode  KSPGetSolution(KSP ksp,Vec *v)
1179: {
1183:   *v = ksp->vec_sol;
1184:   return(0);
1185: }

1189: /*@
1190:    KSPSetPC - Sets the preconditioner to be used to calculate the 
1191:    application of the preconditioner on a vector. 

1193:    Collective on KSP

1195:    Input Parameters:
1196: +  ksp - iterative context obtained from KSPCreate()
1197: -  pc   - the preconditioner object

1199:    Notes:
1200:    Use KSPGetPC() to retrieve the preconditioner context (for example,
1201:    to free it at the end of the computations).

1203:    Level: developer

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

1207: .seealso: KSPGetPC()
1208: @*/
1209: PetscErrorCode  KSPSetPC(KSP ksp,PC pc)
1210: {

1217:   PetscObjectReference((PetscObject)pc);
1218:   if (ksp->pc) {PCDestroy(ksp->pc);}
1219:   ksp->pc = pc;
1220:   return(0);
1221: }

1225: /*@
1226:    KSPGetPC - Returns a pointer to the preconditioner context
1227:    set with KSPSetPC().

1229:    Not Collective

1231:    Input Parameters:
1232: .  ksp - iterative context obtained from KSPCreate()

1234:    Output Parameter:
1235: .  pc - preconditioner context

1237:    Level: developer

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

1241: .seealso: KSPSetPC()
1242: @*/
1243: PetscErrorCode  KSPGetPC(KSP ksp,PC *pc)
1244: {

1250:   if (!ksp->pc) {
1251:     PCCreate(((PetscObject)ksp)->comm,&ksp->pc);
1252:     PetscObjectIncrementTabLevel((PetscObject)ksp->pc,(PetscObject)ksp,0);
1253:   }
1254:   *pc = ksp->pc;
1255:   return(0);
1256: }

1260: /*@C
1261:    KSPMonitorSet - Sets an ADDITIONAL function to be called at every iteration to monitor 
1262:    the residual/error etc.
1263:       
1264:    Collective on KSP

1266:    Input Parameters:
1267: +  ksp - iterative context obtained from KSPCreate()
1268: .  monitor - pointer to function (if this is PETSC_NULL, it turns off monitoring
1269: .  mctx    - [optional] context for private data for the
1270:              monitor routine (use PETSC_NULL if no context is desired)
1271: -  monitordestroy - [optional] routine that frees monitor context
1272:           (may be PETSC_NULL)

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

1277: +  ksp - iterative context obtained from KSPCreate()
1278: .  it - iteration number
1279: .  rnorm - (estimated) 2-norm of (preconditioned) residual
1280: -  mctx  - optional monitoring context, as set by KSPMonitorSet()

1282:    Options Database Keys:
1283: +    -ksp_monitor        - sets KSPMonitorDefault()
1284: .    -ksp_monitor_true_residual    - sets KSPMonitorTrueResidualNorm()
1285: .    -ksp_monitor_draw    - sets line graph monitor,
1286:                            uses KSPMonitorLGCreate()
1287: .    -ksp_monitor_draw_true_residual   - sets line graph monitor,
1288:                            uses KSPMonitorLGCreate()
1289: .    -ksp_monitor_singular_value    - sets KSPMonitorSingularValue()
1290: -    -ksp_monitor_cancel - cancels all monitors that have
1291:                           been hardwired into a code by 
1292:                           calls to KSPMonitorSet(), but
1293:                           does not cancel those set via
1294:                           the options database.

1296:    Notes:  
1297:    The default is to do nothing.  To print the residual, or preconditioned 
1298:    residual if KSPSetNormType(ksp,KSP_NORM_PRECONDITIONED) was called, use 
1299:    KSPMonitorDefault() as the monitoring routine, with a null monitoring 
1300:    context. 

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

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

1308:    Level: beginner

1310: .keywords: KSP, set, monitor

1312: .seealso: KSPMonitorDefault(), KSPMonitorLGCreate(), KSPMonitorCancel()
1313: @*/
1314: PetscErrorCode  KSPMonitorSet(KSP ksp,PetscErrorCode (*monitor)(KSP,PetscInt,PetscReal,void*),void *mctx,PetscErrorCode (*monitordestroy)(void*))
1315: {
1316:   PetscInt i;

1320:   if (ksp->numbermonitors >= MAXKSPMONITORS) {
1321:     SETERRQ(PETSC_ERR_ARG_OUTOFRANGE,"Too many KSP monitors set");
1322:   }
1323:   for (i=0; i<ksp->numbermonitors;i++) {
1324:     if (monitor == ksp->monitor[i] && monitordestroy == ksp->monitordestroy[i] && mctx == ksp->monitorcontext[i]) return(0);

1326:     /* check if both default monitors that share common ASCII viewer */
1327:     if (monitor == ksp->monitor[i] && monitor == KSPMonitorDefault) {
1328:       if (mctx && ksp->monitorcontext[i]) {
1329:         PetscErrorCode          ierr;
1330:         PetscViewerASCIIMonitor viewer1 = (PetscViewerASCIIMonitor) mctx;
1331:         PetscViewerASCIIMonitor viewer2 = (PetscViewerASCIIMonitor) ksp->monitorcontext[i];
1332:         if (viewer1->viewer == viewer2->viewer) {
1333:           (*monitordestroy)(mctx);
1334:           return(0);
1335:         }
1336:       }
1337:     }
1338:   }
1339:   ksp->monitor[ksp->numbermonitors]           = monitor;
1340:   ksp->monitordestroy[ksp->numbermonitors]    = monitordestroy;
1341:   ksp->monitorcontext[ksp->numbermonitors++]  = (void*)mctx;
1342:   return(0);
1343: }

1347: /*@
1348:    KSPMonitorCancel - Clears all monitors for a KSP object.

1350:    Collective on KSP

1352:    Input Parameters:
1353: .  ksp - iterative context obtained from KSPCreate()

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

1360:    Level: intermediate

1362: .keywords: KSP, set, monitor

1364: .seealso: KSPMonitorDefault(), KSPMonitorLGCreate(), KSPMonitorSet()
1365: @*/
1366: PetscErrorCode  KSPMonitorCancel(KSP ksp)
1367: {
1369:   PetscInt       i;

1373:   for (i=0; i<ksp->numbermonitors; i++) {
1374:     if (ksp->monitordestroy[i]) {
1375:       (*ksp->monitordestroy[i])(ksp->monitorcontext[i]);
1376:     }
1377:   }
1378:   ksp->numbermonitors = 0;
1379:   return(0);
1380: }

1384: /*@C
1385:    KSPGetMonitorContext - Gets the monitoring context, as set by 
1386:    KSPMonitorSet() for the FIRST monitor only.

1388:    Not Collective

1390:    Input Parameter:
1391: .  ksp - iterative context obtained from KSPCreate()

1393:    Output Parameter:
1394: .  ctx - monitoring context

1396:    Level: intermediate

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

1400: .seealso: KSPMonitorDefault(), KSPMonitorLGCreate()
1401: @*/
1402: PetscErrorCode  KSPGetMonitorContext(KSP ksp,void **ctx)
1403: {
1406:   *ctx =      (ksp->monitorcontext[0]);
1407:   return(0);
1408: }

1412: /*@
1413:    KSPSetResidualHistory - Sets the array used to hold the residual history.
1414:    If set, this array will contain the residual norms computed at each
1415:    iteration of the solver.

1417:    Not Collective

1419:    Input Parameters:
1420: +  ksp - iterative context obtained from KSPCreate()
1421: .  a   - array to hold history
1422: .  na  - size of a
1423: -  reset - PETSC_TRUE indicates the history counter is reset to zero
1424:            for each new linear solve

1426:    Level: advanced

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

1431:    If 'na' is PETSC_DECIDE or PETSC_DEFAULT, or 'a' is PETSC_NULL, then a 
1432:    default array of length 10000 is allocated.

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

1436: .seealso: KSPGetResidualHistory()

1438: @*/
1439: PetscErrorCode  KSPSetResidualHistory(KSP ksp,PetscReal a[],PetscInt na,PetscTruth reset)
1440: {


1446:   PetscFree(ksp->res_hist_alloc);
1447:   if (na != PETSC_DECIDE && na != PETSC_DEFAULT && a) {
1448:     ksp->res_hist        = a;
1449:     ksp->res_hist_max    = na;
1450:   } else {
1451:     if (na != PETSC_DECIDE && na != PETSC_DEFAULT)
1452:       ksp->res_hist_max = na;
1453:     else
1454:       ksp->res_hist_max = 10000; /* like default ksp->max_it */
1455:     PetscMalloc(ksp->res_hist_max*sizeof(PetscReal),&ksp->res_hist_alloc);
1456:     ksp->res_hist = ksp->res_hist_alloc;
1457:   }
1458:   ksp->res_hist_len    = 0;
1459:   ksp->res_hist_reset  = reset;

1461:   return(0);
1462: }

1466: /*@C
1467:    KSPGetResidualHistory - Gets the array used to hold the residual history
1468:    and the number of residuals it contains.

1470:    Not Collective

1472:    Input Parameter:
1473: .  ksp - iterative context obtained from KSPCreate()

1475:    Output Parameters:
1476: +  a   - pointer to array to hold history (or PETSC_NULL)
1477: -  na  - number of used entries in a (or PETSC_NULL)

1479:    Level: advanced

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

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

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

1492: .seealso: KSPGetResidualHistory()

1494: @*/
1495: PetscErrorCode  KSPGetResidualHistory(KSP ksp,PetscReal *a[],PetscInt *na)
1496: {
1499:   if (a)  *a  = ksp->res_hist;
1500:   if (na) *na = ksp->res_hist_len;
1501:   return(0);
1502: }

1506: /*@C
1507:    KSPSetConvergenceTest - Sets the function to be used to determine
1508:    convergence.  

1510:    Collective on KSP

1512:    Input Parameters:
1513: +  ksp - iterative context obtained from KSPCreate()
1514: .  converge - pointer to int function
1515: .  cctx    - context for private data for the convergence routine (may be null)
1516: -  destroy - a routine for destroying the context (may be null)

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

1521: +  ksp - iterative context obtained from KSPCreate()
1522: .  it - iteration number
1523: .  rnorm - (estimated) 2-norm of (preconditioned) residual
1524: .  reason - the reason why it has converged or diverged
1525: -  cctx  - optional convergence context, as set by KSPSetConvergenceTest()


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

1532:    The default convergence test, KSPDefaultConverged(), aborts if the 
1533:    residual grows to more than 10000 times the initial residual.

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

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

1542:    Level: advanced

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

1546: .seealso: KSPDefaultConverged(), KSPGetConvergenceContext()
1547: @*/
1548: PetscErrorCode  KSPSetConvergenceTest(KSP ksp,PetscErrorCode (*converge)(KSP,PetscInt,PetscReal,KSPConvergedReason*,void*),void *cctx,PetscErrorCode (*destroy)(void*))
1549: {

1554:   if (ksp->convergeddestroy) {
1555:     (*ksp->convergeddestroy)(ksp->cnvP);
1556:   }
1557:   ksp->converged        = converge;
1558:   ksp->convergeddestroy = destroy;
1559:   ksp->cnvP             = (void*)cctx;
1560:   return(0);
1561: }

1565: /*@C
1566:    KSPGetConvergenceContext - Gets the convergence context set with 
1567:    KSPSetConvergenceTest().  

1569:    Not Collective

1571:    Input Parameter:
1572: .  ksp - iterative context obtained from KSPCreate()

1574:    Output Parameter:
1575: .  ctx - monitoring context

1577:    Level: advanced

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

1581: .seealso: KSPDefaultConverged(), KSPSetConvergenceTest()
1582: @*/
1583: PetscErrorCode  KSPGetConvergenceContext(KSP ksp,void **ctx)
1584: {
1587:   *ctx = ksp->cnvP;
1588:   return(0);
1589: }

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

1597:    Collective on KSP

1599:    Input Parameter:
1600: .  ctx - iterative context obtained from KSPCreate()

1602:    Output Parameter: 
1603:    Provide exactly one of
1604: +  v - location to stash solution.   
1605: -  V - the solution is returned in this location. This vector is created 
1606:        internally. This vector should NOT be destroyed by the user with
1607:        VecDestroy().

1609:    Notes:
1610:    This routine can be used in one of two ways
1611: .vb
1612:       KSPBuildSolution(ksp,PETSC_NULL,&V);
1613:    or
1614:       KSPBuildSolution(ksp,v,PETSC_NULL); or KSPBuildSolution(ksp,v,&v);
1615: .ve
1616:    In the first case an internal vector is allocated to store the solution
1617:    (the user cannot destroy this vector). In the second case the solution
1618:    is generated in the vector that the user provides. Note that for certain 
1619:    methods, such as KSPCG, the second case requires a copy of the solution,
1620:    while in the first case the call is essentially free since it simply 
1621:    returns the vector where the solution already is stored. For some methods
1622:    like GMRES this is a reasonably expensive operation and should only be
1623:    used in truly needed.

1625:    Level: advanced

1627: .keywords: KSP, build, solution

1629: .seealso: KSPGetSolution(), KSPBuildResidual()
1630: @*/
1631: PetscErrorCode  KSPBuildSolution(KSP ksp,Vec v,Vec *V)
1632: {

1637:   if (!V && !v) SETERRQ(PETSC_ERR_ARG_WRONG,"Must provide either v or V");
1638:   if (!V) V = &v;
1639:   (*ksp->ops->buildsolution)(ksp,v,V);
1640:   return(0);
1641: }

1645: /*@C
1646:    KSPBuildResidual - Builds the residual in a vector provided.

1648:    Collective on KSP

1650:    Input Parameter:
1651: .  ksp - iterative context obtained from KSPCreate()

1653:    Output Parameters:
1654: +  v - optional location to stash residual.  If v is not provided,
1655:        then a location is generated.
1656: .  t - work vector.  If not provided then one is generated.
1657: -  V - the residual

1659:    Notes:
1660:    Regardless of whether or not v is provided, the residual is 
1661:    returned in V.

1663:    Level: advanced

1665: .keywords: KSP, build, residual

1667: .seealso: KSPBuildSolution()
1668: @*/
1669: PetscErrorCode  KSPBuildResidual(KSP ksp,Vec t,Vec v,Vec *V)
1670: {
1672:   PetscTruth     flag = PETSC_FALSE;
1673:   Vec            w = v,tt = t;

1677:   if (!w) {
1678:     VecDuplicate(ksp->vec_rhs,&w);
1679:     PetscLogObjectParent((PetscObject)ksp,w);
1680:   }
1681:   if (!tt) {
1682:     VecDuplicate(ksp->vec_sol,&tt); flag = PETSC_TRUE;
1683:     PetscLogObjectParent((PetscObject)ksp,tt);
1684:   }
1685:   (*ksp->ops->buildresidual)(ksp,tt,w,V);
1686:   if (flag) {VecDestroy(tt);}
1687:   return(0);
1688: }

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

1696:    Collective on KSP

1698:    Input Parameter:
1699: +  ksp - the KSP context
1700: -  scale - PETSC_TRUE or PETSC_FALSE

1702:    Options Database Key:
1703: +   -ksp_diagonal_scale - 
1704: -   -ksp_diagonal_scale_fix - scale the matrix back AFTER the solve 


1707:     BE CAREFUL with this routine: it actually scales the matrix and right 
1708:     hand side that define the system. After the system is solved the matrix
1709:     and right hand side remain scaled.

1711:     This routine is only used if the matrix and preconditioner matrix are
1712:     the same thing.

1714:     This should NOT be used within the SNES solves if you are using a line
1715:     search.
1716:  
1717:     If you use this with the PCType Eisenstat preconditioner than you can 
1718:     use the PCEisenstatNoDiagonalScaling() option, or -pc_eisenstat_no_diagonal_scaling
1719:     to save some unneeded, redundant flops.

1721:    Level: intermediate

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

1725: .seealso: KSPGetDiagonalScale(), KSPSetDiagonalScaleFix()
1726: @*/
1727: PetscErrorCode  KSPSetDiagonalScale(KSP ksp,PetscTruth scale)
1728: {
1731:   ksp->dscale = scale;
1732:   return(0);
1733: }

1737: /*@
1738:    KSPGetDiagonalScale - Checks if KSP solver scales the matrix and
1739:                           right hand side

1741:    Not Collective

1743:    Input Parameter:
1744: .  ksp - the KSP context

1746:    Output Parameter:
1747: .  scale - PETSC_TRUE or PETSC_FALSE

1749:    Notes:
1750:     BE CAREFUL with this routine: it actually scales the matrix and right 
1751:     hand side that define the system. After the system is solved the matrix
1752:     and right hand side remain scaled.

1754:     This routine is only used if the matrix and preconditioner matrix are
1755:     the same thing.

1757:    Level: intermediate

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

1761: .seealso: KSPSetDiagonalScale(), KSPSetDiagonalScaleFix()
1762: @*/
1763: PetscErrorCode  KSPGetDiagonalScale(KSP ksp,PetscTruth *scale)
1764: {
1768:   *scale = ksp->dscale;
1769:   return(0);
1770: }

1774: /*@
1775:    KSPSetDiagonalScaleFix - Tells KSP to diagonally scale the system
1776:      back after solving.

1778:    Collective on KSP

1780:    Input Parameter:
1781: +  ksp - the KSP context
1782: -  fix - PETSC_TRUE to scale back after the system solve, PETSC_FALSE to not 
1783:          rescale (default)

1785:    Notes:
1786:      Must be called after KSPSetDiagonalScale()

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

1793:     This routine is only used if the matrix and preconditioner matrix are
1794:     the same thing.

1796:    Level: intermediate

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

1800: .seealso: KSPGetDiagonalScale(), KSPSetDiagonalScale(), KSPGetDiagonalScaleFix()
1801: @*/
1802: PetscErrorCode  KSPSetDiagonalScaleFix(KSP ksp,PetscTruth fix)
1803: {
1806:   ksp->dscalefix = fix;
1807:   return(0);
1808: }

1812: /*@
1813:    KSPGetDiagonalScaleFix - Determines if KSP diagonally scales the system
1814:      back after solving.

1816:    Collective on KSP

1818:    Input Parameter:
1819: .  ksp - the KSP context

1821:    Output Parameter:
1822: .  fix - PETSC_TRUE to scale back after the system solve, PETSC_FALSE to not 
1823:          rescale (default)

1825:    Notes:
1826:      Must be called after KSPSetDiagonalScale()

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

1833:     This routine is only used if the matrix and preconditioner matrix are
1834:     the same thing.

1836:    Level: intermediate

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

1840: .seealso: KSPGetDiagonalScale(), KSPSetDiagonalScale(), KSPSetDiagonalScaleFix()
1841: @*/
1842: PetscErrorCode  KSPGetDiagonalScaleFix(KSP ksp,PetscTruth *fix)
1843: {
1847:   *fix = ksp->dscalefix;
1848:   return(0);
1849: }