Actual source code: itfunc.c

  1: #define PETSCKSP_DLL

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

 7:  #include 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:   PCSetUpOnBlocks(ksp->pc);
159:   return(0);
160: }

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

168:    Collective on KSP

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

173:    Level: developer

175: .keywords: KSP, setup

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


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

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

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


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

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

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

250: /*@
251:    KSPSolve - Solves linear system.

253:    Collective on KSP

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

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

271:    Notes:

273:    The operator is specified with PCSetOperators().

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

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

288:    Level: beginner

290: .keywords: KSP, solve, linear system

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


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

321:   PetscOptionsHasName(((PetscObject)ksp)->prefix,"-ksp_view_binary",&flg);
322:   if (flg) {
323:     Mat mat;
324:     PCGetOperators(ksp->pc,&mat,PETSC_NULL,PETSC_NULL);
325:     MatView(mat,PETSC_VIEWER_BINARY_(((PetscObject)ksp)->comm));
326:     VecView(ksp->vec_rhs,PETSC_VIEWER_BINARY_(((PetscObject)ksp)->comm));
327:   }

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

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

343:   ksp->transpose_solve = PETSC_FALSE;
344: 
345:   /* KSPSetUp() scales the matrix if needed */
346:   KSPSetUp(ksp);
347:   KSPSetUpOnBlocks(ksp);

349:   /* diagonal scale RHS if called for */
350:   if (ksp->dscale) {
351:     VecPointwiseMult(ksp->vec_rhs,ksp->vec_rhs,ksp->diagonal);
352:     /* second time in, but matrix was scaled back to original */
353:     if (ksp->dscalefix && ksp->dscalefix2) {
354:       Mat mat;

356:       PCGetOperators(ksp->pc,&mat,PETSC_NULL,PETSC_NULL);
357:       MatDiagonalScale(mat,ksp->diagonal,ksp->diagonal);
358:     }

360:     /*  scale initial guess */
361:     if (!ksp->guess_zero) {
362:       if (!ksp->truediagonal) {
363:         VecDuplicate(ksp->diagonal,&ksp->truediagonal);
364:         VecCopy(ksp->diagonal,ksp->truediagonal);
365:         VecReciprocal(ksp->truediagonal);
366:       }
367:       VecPointwiseMult(ksp->vec_sol,ksp->vec_sol,ksp->truediagonal);
368:     }
369:   }
370:   PCPreSolve(ksp->pc,ksp);

372:   if (ksp->guess_zero) { VecSet(ksp->vec_sol,0.0);}
373:   if (ksp->guess_knoll) {
374:     PCApply(ksp->pc,ksp->vec_rhs,ksp->vec_sol);
375:     KSP_RemoveNullSpace(ksp,ksp->vec_sol);
376:     ksp->guess_zero = PETSC_FALSE;
377:   }
378:   (*ksp->ops->solve)(ksp);
379:   if (!ksp->reason) {
380:     SETERRQ(PETSC_ERR_PLIB,"Internal error, solver returned without setting converged reason");
381:   }
382:   if (ksp->printreason) {
383:     if (ksp->reason > 0) {
384:       PetscPrintf(((PetscObject)ksp)->comm,"Linear solve converged due to %s iterations %D\n",KSPConvergedReasons[ksp->reason],ksp->its);
385:     } else {
386:       PetscPrintf(((PetscObject)ksp)->comm,"Linear solve did not converge due to %s iterations %D\n",KSPConvergedReasons[ksp->reason],ksp->its);
387:     }
388:   }
389:   PCPostSolve(ksp->pc,ksp);

391:   /* diagonal scale solution if called for */
392:   if (ksp->dscale) {
393:     VecPointwiseMult(ksp->vec_sol,ksp->vec_sol,ksp->diagonal);
394:     /* unscale right hand side and matrix */
395:     if (ksp->dscalefix) {
396:       Mat mat;

398:       VecReciprocal(ksp->diagonal);
399:       VecPointwiseMult(ksp->vec_rhs,ksp->vec_rhs,ksp->diagonal);
400:       PCGetOperators(ksp->pc,&mat,PETSC_NULL,PETSC_NULL);
401:       MatDiagonalScale(mat,ksp->diagonal,ksp->diagonal);
402:       VecReciprocal(ksp->diagonal);
403:       ksp->dscalefix2 = PETSC_TRUE;
404:     }
405:   }

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

410:   PetscOptionsHasName(((PetscObject)ksp)->prefix,"-ksp_compute_eigenvalues",&flag1);
411:   PetscOptionsHasName(((PetscObject)ksp)->prefix,"-ksp_plot_eigenvalues",&flag2);
412:   if (flag1 || flag2) {
413:     PetscInt   nits,n,i,neig;
414:     PetscReal *r,*c;
415: 
416:     KSPGetIterationNumber(ksp,&nits);
417:     n = nits+2;

419:     if (!n) {
420:       PetscPrintf(((PetscObject)ksp)->comm,"Zero iterations in solver, cannot approximate any eigenvalues\n");
421:     } else {
422:       PetscMalloc(2*n*sizeof(PetscReal),&r);
423:       c = r + n;
424:       KSPComputeEigenvalues(ksp,n,r,c,&neig);
425:       if (flag1) {
426:         PetscPrintf(((PetscObject)ksp)->comm,"Iteratively computed eigenvalues\n");
427:         for (i=0; i<neig; i++) {
428:           if (c[i] >= 0.0) {PetscPrintf(((PetscObject)ksp)->comm,"%G + %Gi\n",r[i],c[i]);}
429:           else             {PetscPrintf(((PetscObject)ksp)->comm,"%G - %Gi\n",r[i],-c[i]);}
430:         }
431:       }
432:       if (flag2 && !rank) {
433:         PetscDraw   draw;
434:         PetscDrawSP drawsp;

436:         PetscViewerDrawOpen(PETSC_COMM_SELF,0,"Iteratively Computed Eigenvalues",PETSC_DECIDE,PETSC_DECIDE,300,300,&viewer);
437:         PetscViewerDrawGetDraw(viewer,0,&draw);
438:         PetscDrawSPCreate(draw,1,&drawsp);
439:         for (i=0; i<neig; i++) {
440:           PetscDrawSPAddPoint(drawsp,r+i,c+i);
441:         }
442:         PetscDrawSPDraw(drawsp);
443:         PetscDrawSPDestroy(drawsp);
444:         PetscViewerDestroy(viewer);
445:       }
446:       PetscFree(r);
447:     }
448:   }

450:   PetscOptionsHasName(((PetscObject)ksp)->prefix,"-ksp_compute_eigenvalues_explicitly",&flag1);
451:   PetscOptionsHasName(((PetscObject)ksp)->prefix,"-ksp_plot_eigenvalues_explicitly",&flag2);
452:   if (flag1 || flag2) {
453:     PetscInt  n,i;
454:     PetscReal *r,*c;
455:     VecGetSize(ksp->vec_sol,&n);
456:     PetscMalloc(2*n*sizeof(PetscReal),&r);
457:     c = r + n;
458:     KSPComputeEigenvaluesExplicitly(ksp,n,r,c);
459:     if (flag1) {
460:       PetscPrintf(((PetscObject)ksp)->comm,"Explicitly computed eigenvalues\n");
461:       for (i=0; i<n; i++) {
462:         if (c[i] >= 0.0) {PetscPrintf(((PetscObject)ksp)->comm,"%G + %Gi\n",r[i],c[i]);}
463:         else             {PetscPrintf(((PetscObject)ksp)->comm,"%G - %Gi\n",r[i],-c[i]);}
464:       }
465:     }
466:     if (flag2 && !rank) {
467:       PetscDraw   draw;
468:       PetscDrawSP drawsp;

470:       PetscViewerDrawOpen(PETSC_COMM_SELF,0,"Explicitly Computed Eigenvalues",0,320,300,300,&viewer);
471:       PetscViewerDrawGetDraw(viewer,0,&draw);
472:       PetscDrawSPCreate(draw,1,&drawsp);
473:       for (i=0; i<n; i++) {
474:         PetscDrawSPAddPoint(drawsp,r+i,c+i);
475:       }
476:       PetscDrawSPDraw(drawsp);
477:       PetscDrawSPDestroy(drawsp);
478:       PetscViewerDestroy(viewer);
479:     }
480:     PetscFree(r);
481:   }

483:   PetscOptionsHasName(((PetscObject)ksp)->prefix,"-ksp_view_operator",&flag2);
484:   if (flag2) {
485:     Mat         A,B;
486:     PetscViewer viewer;

488:     PCGetOperators(ksp->pc,&A,PETSC_NULL,PETSC_NULL);
489:     MatComputeExplicitOperator(A,&B);
490:     PetscViewerASCIIGetStdout(((PetscObject)ksp)->comm,&viewer);
491:     PetscViewerPushFormat(viewer,PETSC_VIEWER_ASCII_MATLAB);
492:     MatView(B,viewer);
493:     PetscViewerPopFormat(viewer);
494:     MatDestroy(B);
495:   }
496:   PetscOptionsHasName(((PetscObject)ksp)->prefix,"-ksp_view_operator_binary",&flag2);
497:   if (flag2) {
498:     Mat A,B;
499:     PCGetOperators(ksp->pc,&A,PETSC_NULL,PETSC_NULL);
500:     MatComputeExplicitOperator(A,&B);
501:     MatView(B,PETSC_VIEWER_BINARY_(((PetscObject)ksp)->comm));
502:     MatDestroy(B);
503:   }
504:   PetscOptionsHasName(((PetscObject)ksp)->prefix,"-ksp_view_preconditioned_operator_binary",&flag2);
505:   if (flag2) {
506:     Mat B;
507:     KSPComputeExplicitOperator(ksp,&B);
508:     MatView(B,PETSC_VIEWER_BINARY_(((PetscObject)ksp)->comm));
509:     MatDestroy(B);
510:   }
511:   PetscOptionsHasName(((PetscObject)ksp)->prefix,"-ksp_view_preconditioner_binary",&flag2);
512:   if (flag2) {
513:     Mat B;
514:     PCComputeExplicitOperator(ksp->pc,&B);
515:     MatView(B,PETSC_VIEWER_BINARY_(((PetscObject)ksp)->comm));
516:     MatDestroy(B);
517:   }
518:   if (!viewed) {
519:     PetscOptionsGetString(((PetscObject)ksp)->prefix,"-ksp_view",filename,PETSC_MAX_PATH_LEN,&flg);
520:     if (flg && !PetscPreLoadingOn) {
521:       PetscViewerASCIIOpen(((PetscObject)ksp)->comm,filename,&viewer);
522:       KSPView(ksp,viewer);
523:       PetscViewerDestroy(viewer);
524:     }
525:   }
526:   PetscOptionsHasName(((PetscObject)ksp)->prefix,"-ksp_final_residual",&flg);
527:   if (flg) {
528:     Mat         A;
529:     Vec         t;
530:     PetscReal   norm;
531:     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");
532:     PCGetOperators(ksp->pc,&A,0,0);
533:     VecDuplicate(ksp->vec_sol,&t);
534:     KSP_MatMult(ksp,A,ksp->vec_sol,t);
535:     VecWAXPY(t,-1.0,t,ksp->vec_rhs);
536:     VecNorm(t,NORM_2,&norm);
537:     VecDestroy(t);
538:     PetscPrintf(((PetscObject)ksp)->comm,"KSP final norm of residual %G\n",norm);
539:   }
540:   if (inXisinB) {
541:     VecCopy(x,b);
542:     VecDestroy(x);
543:   }
544:   return(0);
545: }

549: /*@
550:    KSPSolveTranspose - Solves the transpose of a linear system. Usually
551:    accessed through KSPSolveTranspose().

553:    Collective on KSP

555:    Input Parameter:
556: +  ksp - iterative context obtained from KSPCreate()
557: .  b - right hand side vector
558: -  x - solution vector

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

564:    Level: developer

566: .keywords: KSP, solve, linear system

568: .seealso: KSPCreate(), KSPSetUp(), KSPDestroy(), KSPSetTolerances(), KSPDefaultConverged(),
569:           KSPSolve()
570: @*/
571: PetscErrorCode  KSPSolveTranspose(KSP ksp,Vec b,Vec x)
572: {
574:   PetscTruth     inXisinB=PETSC_FALSE;

580:   if (x == b) {
581:     VecDuplicate(b,&x);
582:     inXisinB = PETSC_TRUE;
583:   }
584:   PetscObjectReference((PetscObject)b);
585:   PetscObjectReference((PetscObject)x);
586:   if (ksp->vec_rhs) {VecDestroy(ksp->vec_rhs);}
587:   if (ksp->vec_sol) {VecDestroy(ksp->vec_sol);}
588:   ksp->vec_rhs = b;
589:   ksp->vec_sol = x;
590:   ksp->transpose_solve = PETSC_TRUE;
591:   KSPSetUp(ksp);
592:   if (ksp->guess_zero) { VecSet(ksp->vec_sol,0.0);}
593:   (*ksp->ops->solve)(ksp);
594:   if (inXisinB) {
595:     VecCopy(x,b);
596:     VecDestroy(x);
597:   }
598:   return(0);
599: }

603: /*@
604:    KSPDestroy - Destroys KSP context.

606:    Collective on KSP

608:    Input Parameter:
609: .  ksp - iterative context obtained from KSPCreate()

611:    Level: beginner

613: .keywords: KSP, destroy

615: .seealso: KSPCreate(), KSPSetUp(), KSPSolve()
616: @*/
617: PetscErrorCode  KSPDestroy(KSP ksp)
618: {

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

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

628:   if (ksp->ops->destroy) {
629:     (*ksp->ops->destroy)(ksp);
630:   }
631:   PetscFree(ksp->res_hist_alloc);
632:   KSPMonitorCancel(ksp);
633:   PCDestroy(ksp->pc);
634:   if (ksp->vec_rhs) {VecDestroy(ksp->vec_rhs);}
635:   if (ksp->vec_sol) {VecDestroy(ksp->vec_sol);}
636:   if (ksp->diagonal) {VecDestroy(ksp->diagonal);}
637:   if (ksp->truediagonal) {VecDestroy(ksp->truediagonal);}
638:   if (ksp->nullsp) {MatNullSpaceDestroy(ksp->nullsp);}
639:   if (ksp->convergeddestroy) {
640:     (*ksp->convergeddestroy)(ksp->cnvP);
641:   }
642:   PetscHeaderDestroy(ksp);
643:   return(0);
644: }

648: /*@
649:     KSPSetPreconditionerSide - Sets the preconditioning side.

651:     Collective on KSP

653:     Input Parameter:
654: .   ksp - iterative context obtained from KSPCreate()

656:     Output Parameter:
657: .   side - the preconditioning side, where side is one of
658: .vb
659:       PC_LEFT - left preconditioning (default)
660:       PC_RIGHT - right preconditioning
661:       PC_SYMMETRIC - symmetric preconditioning
662: .ve

664:     Options Database Keys:
665: +   -ksp_left_pc - Sets left preconditioning
666: .   -ksp_right_pc - Sets right preconditioning
667: -   -ksp_symmetric_pc - Sets symmetric preconditioning

669:     Notes:
670:     Left preconditioning is used by default.  Symmetric preconditioning is
671:     currently available only for the KSPQCG method. Note, however, that
672:     symmetric preconditioning can be emulated by using either right or left
673:     preconditioning and a pre or post processing step.

675:     Level: intermediate

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

679: .seealso: KSPGetPreconditionerSide()
680: @*/
681: PetscErrorCode  KSPSetPreconditionerSide(KSP ksp,PCSide side)
682: {
685:   ksp->pc_side = side;
686:   return(0);
687: }

691: /*@
692:     KSPGetPreconditionerSide - Gets the preconditioning side.

694:     Not Collective

696:     Input Parameter:
697: .   ksp - iterative context obtained from KSPCreate()

699:     Output Parameter:
700: .   side - the preconditioning side, where side is one of
701: .vb
702:       PC_LEFT - left preconditioning (default)
703:       PC_RIGHT - right preconditioning
704:       PC_SYMMETRIC - symmetric preconditioning
705: .ve

707:     Level: intermediate

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

711: .seealso: KSPSetPreconditionerSide()
712: @*/
713: PetscErrorCode  KSPGetPreconditionerSide(KSP ksp,PCSide *side)
714: {
718:   *side = ksp->pc_side;
719:   return(0);
720: }

724: /*@
725:    KSPGetTolerances - Gets the relative, absolute, divergence, and maximum
726:    iteration tolerances used by the default KSP convergence tests. 

728:    Not Collective

730:    Input Parameter:
731: .  ksp - the Krylov subspace context
732:   
733:    Output Parameters:
734: +  rtol - the relative convergence tolerance
735: .  abstol - the absolute convergence tolerance
736: .  dtol - the divergence tolerance
737: -  maxits - maximum number of iterations

739:    Notes:
740:    The user can specify PETSC_NULL for any parameter that is not needed.

742:    Level: intermediate

744: .keywords: KSP, get, tolerance, absolute, relative, divergence, convergence,
745:            maximum, iterations

747: .seealso: KSPSetTolerances()
748: @*/
749: PetscErrorCode  KSPGetTolerances(KSP ksp,PetscReal *rtol,PetscReal *abstol,PetscReal *dtol,PetscInt *maxits)
750: {
753:   if (abstol)   *abstol   = ksp->abstol;
754:   if (rtol)   *rtol   = ksp->rtol;
755:   if (dtol)   *dtol   = ksp->divtol;
756:   if (maxits) *maxits = ksp->max_it;
757:   return(0);
758: }

762: /*@
763:    KSPSetTolerances - Sets the relative, absolute, divergence, and maximum
764:    iteration tolerances used by the default KSP convergence testers. 

766:    Collective on KSP

768:    Input Parameters:
769: +  ksp - the Krylov subspace context
770: .  rtol - the relative convergence tolerance
771:    (relative decrease in the residual norm)
772: .  abstol - the absolute convergence tolerance 
773:    (absolute size of the residual norm)
774: .  dtol - the divergence tolerance
775:    (amount residual can increase before KSPDefaultConverged()
776:    concludes that the method is diverging)
777: -  maxits - maximum number of iterations to use

779:    Options Database Keys:
780: +  -ksp_atol <abstol> - Sets abstol
781: .  -ksp_rtol <rtol> - Sets rtol
782: .  -ksp_divtol <dtol> - Sets dtol
783: -  -ksp_max_it <maxits> - Sets maxits

785:    Notes:
786:    Use PETSC_DEFAULT to retain the default value of any of the tolerances.

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

792:    Level: intermediate

794: .keywords: KSP, set, tolerance, absolute, relative, divergence, 
795:            convergence, maximum, iterations

797: .seealso: KSPGetTolerances(), KSPDefaultConverged(), KSPSetConvergenceTest()
798: @*/
799: PetscErrorCode  KSPSetTolerances(KSP ksp,PetscReal rtol,PetscReal abstol,PetscReal dtol,PetscInt maxits)
800: {
803:   if (abstol != PETSC_DEFAULT)   ksp->abstol   = abstol;
804:   if (rtol != PETSC_DEFAULT)   ksp->rtol   = rtol;
805:   if (dtol != PETSC_DEFAULT)   ksp->divtol = dtol;
806:   if (maxits != PETSC_DEFAULT) ksp->max_it = maxits;
807:   return(0);
808: }

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

817:    Collective on KSP

819:    Input Parameters:
820: +  ksp - iterative context obtained from KSPCreate()
821: -  flg - PETSC_TRUE indicates the guess is non-zero, PETSC_FALSE indicates the guess is zero

823:    Level: beginner

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

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

830: .seealso: KSPGetInitialGuessNonzero(), KSPSetInitialGuessKnoll(), KSPGetInitialGuessKnoll()
831: @*/
832: PetscErrorCode  KSPSetInitialGuessNonzero(KSP ksp,PetscTruth flg)
833: {
836:   ksp->guess_zero   = (PetscTruth)!(int)flg;
837:   return(0);
838: }

842: /*@
843:    KSPGetInitialGuessNonzero - Determines whether the KSP solver is using
844:    a zero initial guess.

846:    Not Collective

848:    Input Parameter:
849: .  ksp - iterative context obtained from KSPCreate()

851:    Output Parameter:
852: .  flag - PETSC_TRUE if guess is nonzero, else PETSC_FALSE

854:    Level: intermediate

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

858: .seealso: KSPSetInitialGuessNonzero(), KSPSetInitialGuessKnoll(), KSPGetInitialGuessKnoll()
859: @*/
860: PetscErrorCode  KSPGetInitialGuessNonzero(KSP ksp,PetscTruth *flag)
861: {
865:   if (ksp->guess_zero) *flag = PETSC_FALSE;
866:   else                 *flag = PETSC_TRUE;
867:   return(0);
868: }

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

875:    Collective on KSP

877:    Input Parameters:
878: +  ksp - iterative context obtained from KSPCreate()
879: -  flg - PETSC_TRUE or PETSC_FALSE

881:    Level: advanced


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

886: .seealso: KSPGetInitialGuessKnoll(), KSPSetInitialGuessNonzero(), KSPGetInitialGuessNonzero()
887: @*/
888: PetscErrorCode  KSPSetInitialGuessKnoll(KSP ksp,PetscTruth flg)
889: {
892:   ksp->guess_knoll   = flg;
893:   return(0);
894: }

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

902:    Not Collective

904:    Input Parameter:
905: .  ksp - iterative context obtained from KSPCreate()

907:    Output Parameter:
908: .  flag - PETSC_TRUE if using Knoll trick, else PETSC_FALSE

910:    Level: advanced

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

914: .seealso: KSPSetInitialGuessKnoll(), KSPSetInitialGuessNonzero(), KSPGetInitialGuessNonzero()
915: @*/
916: PetscErrorCode  KSPGetInitialGuessKnoll(KSP ksp,PetscTruth *flag)
917: {
921:   *flag = ksp->guess_knoll;
922:   return(0);
923: }

927: /*@
928:    KSPGetComputeSingularValues - Gets the flag indicating whether the extreme singular 
929:    values will be calculated via a Lanczos or Arnoldi process as the linear 
930:    system is solved.

932:    Collective on KSP

934:    Input Parameter:
935: .  ksp - iterative context obtained from KSPCreate()

937:    Output Parameter:
938: .  flg - PETSC_TRUE or PETSC_FALSE

940:    Options Database Key:
941: .  -ksp_monitor_singular_value - Activates KSPSetComputeSingularValues()

943:    Notes:
944:    Currently this option is not valid for all iterative methods.

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

950:    Level: advanced

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

954: .seealso: KSPComputeExtremeSingularValues(), KSPMonitorSingularValue()
955: @*/
956: PetscErrorCode  KSPGetComputeSingularValues(KSP ksp,PetscTruth *flg)
957: {
961:   *flg = ksp->calc_sings;
962:   return(0);
963: }

967: /*@
968:    KSPSetComputeSingularValues - Sets a flag so that the extreme singular 
969:    values will be calculated via a Lanczos or Arnoldi process as the linear 
970:    system is solved.

972:    Collective on KSP

974:    Input Parameters:
975: +  ksp - iterative context obtained from KSPCreate()
976: -  flg - PETSC_TRUE or PETSC_FALSE

978:    Options Database Key:
979: .  -ksp_monitor_singular_value - Activates KSPSetComputeSingularValues()

981:    Notes:
982:    Currently this option is not valid for all iterative methods.

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

988:    Level: advanced

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

992: .seealso: KSPComputeExtremeSingularValues(), KSPMonitorSingularValue()
993: @*/
994: PetscErrorCode  KSPSetComputeSingularValues(KSP ksp,PetscTruth flg)
995: {
998:   ksp->calc_sings  = flg;
999:   return(0);
1000: }

1004: /*@
1005:    KSPGetComputeEigenvalues - Gets the flag indicating that the extreme eigenvalues
1006:    values will be calculated via a Lanczos or Arnoldi process as the linear 
1007:    system is solved.

1009:    Collective on KSP

1011:    Input Parameter:
1012: .  ksp - iterative context obtained from KSPCreate()

1014:    Output Parameter:
1015: .  flg - PETSC_TRUE or PETSC_FALSE

1017:    Notes:
1018:    Currently this option is not valid for all iterative methods.

1020:    Level: advanced

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

1024: .seealso: KSPComputeEigenvalues(), KSPComputeEigenvaluesExplicitly()
1025: @*/
1026: PetscErrorCode  KSPGetComputeEigenvalues(KSP ksp,PetscTruth *flg)
1027: {
1031:   *flg = ksp->calc_sings;
1032:   return(0);
1033: }

1037: /*@
1038:    KSPSetComputeEigenvalues - Sets a flag so that the extreme eigenvalues
1039:    values will be calculated via a Lanczos or Arnoldi process as the linear 
1040:    system is solved.

1042:    Collective on KSP

1044:    Input Parameters:
1045: +  ksp - iterative context obtained from KSPCreate()
1046: -  flg - PETSC_TRUE or PETSC_FALSE

1048:    Notes:
1049:    Currently this option is not valid for all iterative methods.

1051:    Level: advanced

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

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

1067: /*@
1068:    KSPGetRhs - Gets the right-hand-side vector for the linear system to
1069:    be solved.

1071:    Not Collective

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

1076:    Output Parameter:
1077: .  r - right-hand-side vector

1079:    Level: developer

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

1083: .seealso: KSPGetSolution(), KSPSolve()
1084: @*/
1085: PetscErrorCode  KSPGetRhs(KSP ksp,Vec *r)
1086: {
1090:   *r = ksp->vec_rhs;
1091:   return(0);
1092: }

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

1101:    Not Collective

1103:    Input Parameters:
1104: .  ksp - iterative context obtained from KSPCreate()

1106:    Output Parameters:
1107: .  v - solution vector

1109:    Level: developer

1111: .keywords: KSP, get, solution

1113: .seealso: KSPGetRhs(),  KSPBuildSolution(), KSPSolve()
1114: @*/
1115: PetscErrorCode  KSPGetSolution(KSP ksp,Vec *v)
1116: {
1120:   *v = ksp->vec_sol;
1121:   return(0);
1122: }

1126: /*@
1127:    KSPSetPC - Sets the preconditioner to be used to calculate the 
1128:    application of the preconditioner on a vector. 

1130:    Collective on KSP

1132:    Input Parameters:
1133: +  ksp - iterative context obtained from KSPCreate()
1134: -  pc   - the preconditioner object

1136:    Notes:
1137:    Use KSPGetPC() to retrieve the preconditioner context (for example,
1138:    to free it at the end of the computations).

1140:    Level: developer

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

1144: .seealso: KSPGetPC()
1145: @*/
1146: PetscErrorCode  KSPSetPC(KSP ksp,PC pc)
1147: {

1154:   PetscObjectReference((PetscObject)pc);
1155:   if (ksp->pc) {PCDestroy(ksp->pc);}
1156:   ksp->pc = pc;
1157:   return(0);
1158: }

1162: /*@
1163:    KSPGetPC - Returns a pointer to the preconditioner context
1164:    set with KSPSetPC().

1166:    Not Collective

1168:    Input Parameters:
1169: .  ksp - iterative context obtained from KSPCreate()

1171:    Output Parameter:
1172: .  pc - preconditioner context

1174:    Level: developer

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

1178: .seealso: KSPSetPC()
1179: @*/
1180: PetscErrorCode  KSPGetPC(KSP ksp,PC *pc)
1181: {
1185:   *pc = ksp->pc;
1186:   return(0);
1187: }

1191: /*@C
1192:    KSPMonitorSet - Sets an ADDITIONAL function to be called at every iteration to monitor 
1193:    the residual/error etc.
1194:       
1195:    Collective on KSP

1197:    Input Parameters:
1198: +  ksp - iterative context obtained from KSPCreate()
1199: .  monitor - pointer to function (if this is PETSC_NULL, it turns off monitoring
1200: .  mctx    - [optional] context for private data for the
1201:              monitor routine (use PETSC_NULL if no context is desired)
1202: -  monitordestroy - [optional] routine that frees monitor context
1203:           (may be PETSC_NULL)

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

1208: +  ksp - iterative context obtained from KSPCreate()
1209: .  it - iteration number
1210: .  rnorm - (estimated) 2-norm of (preconditioned) residual
1211: -  mctx  - optional monitoring context, as set by KSPMonitorSet()

1213:    Options Database Keys:
1214: +    -ksp_monitor        - sets KSPMonitorDefault()
1215: .    -ksp_monitor_true_residual    - sets KSPMonitorTrueResidualNorm()
1216: .    -ksp_monitor_draw    - sets line graph monitor,
1217:                            uses KSPMonitorLGCreate()
1218: .    -ksp_monitor_draw_true_residual   - sets line graph monitor,
1219:                            uses KSPMonitorLGCreate()
1220: .    -ksp_monitor_singular_value    - sets KSPMonitorSingularValue()
1221: -    -ksp_monitor_cancel - cancels all monitors that have
1222:                           been hardwired into a code by 
1223:                           calls to KSPMonitorSet(), but
1224:                           does not cancel those set via
1225:                           the options database.

1227:    Notes:  
1228:    The default is to do nothing.  To print the residual, or preconditioned 
1229:    residual if KSPSetNormType(ksp,KSP_NORM_PRECONDITIONED) was called, use 
1230:    KSPMonitorDefault() as the monitoring routine, with a null monitoring 
1231:    context. 

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

1237:    Level: beginner

1239: .keywords: KSP, set, monitor

1241: .seealso: KSPMonitorDefault(), KSPMonitorLGCreate(), KSPMonitorCancel()
1242: @*/
1243: PetscErrorCode  KSPMonitorSet(KSP ksp,PetscErrorCode (*monitor)(KSP,PetscInt,PetscReal,void*),void *mctx,PetscErrorCode (*monitordestroy)(void*))
1244: {
1245:   PetscInt i;

1249:   if (ksp->numbermonitors >= MAXKSPMONITORS) {
1250:     SETERRQ(PETSC_ERR_ARG_OUTOFRANGE,"Too many KSP monitors set");
1251:   }
1252:   for (i=0; i<ksp->numbermonitors;i++) {
1253:     if (monitor == ksp->monitor[i] && monitordestroy == ksp->monitordestroy[i] && mctx == ksp->monitorcontext[i]) return(0);

1255:     /* check if both default monitors that share common ASCII viewer */
1256:     if (monitor == ksp->monitor[i] && monitor == KSPMonitorDefault) {
1257:       if (mctx && ksp->monitorcontext[i]) {
1258:         PetscErrorCode          ierr;
1259:         PetscViewerASCIIMonitor viewer1 = (PetscViewerASCIIMonitor) mctx;
1260:         PetscViewerASCIIMonitor viewer2 = (PetscViewerASCIIMonitor) ksp->monitorcontext[i];
1261:         if (viewer1->viewer == viewer2->viewer) {
1262:           (*monitordestroy)(mctx);
1263:           return(0);
1264:         }
1265:       }
1266:     }
1267:   }
1268:   ksp->monitor[ksp->numbermonitors]           = monitor;
1269:   ksp->monitordestroy[ksp->numbermonitors]    = monitordestroy;
1270:   ksp->monitorcontext[ksp->numbermonitors++]  = (void*)mctx;
1271:   return(0);
1272: }

1276: /*@
1277:    KSPMonitorCancel - Clears all monitors for a KSP object.

1279:    Collective on KSP

1281:    Input Parameters:
1282: .  ksp - iterative context obtained from KSPCreate()

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

1289:    Level: intermediate

1291: .keywords: KSP, set, monitor

1293: .seealso: KSPMonitorDefault(), KSPMonitorLGCreate(), KSPMonitorSet()
1294: @*/
1295: PetscErrorCode  KSPMonitorCancel(KSP ksp)
1296: {
1298:   PetscInt       i;

1302:   for (i=0; i<ksp->numbermonitors; i++) {
1303:     if (ksp->monitordestroy[i]) {
1304:       (*ksp->monitordestroy[i])(ksp->monitorcontext[i]);
1305:     }
1306:   }
1307:   ksp->numbermonitors = 0;
1308:   return(0);
1309: }

1313: /*@C
1314:    KSPGetMonitorContext - Gets the monitoring context, as set by 
1315:    KSPMonitorSet() for the FIRST monitor only.

1317:    Not Collective

1319:    Input Parameter:
1320: .  ksp - iterative context obtained from KSPCreate()

1322:    Output Parameter:
1323: .  ctx - monitoring context

1325:    Level: intermediate

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

1329: .seealso: KSPMonitorDefault(), KSPMonitorLGCreate()
1330: @*/
1331: PetscErrorCode  KSPGetMonitorContext(KSP ksp,void **ctx)
1332: {
1335:   *ctx =      (ksp->monitorcontext[0]);
1336:   return(0);
1337: }

1341: /*@
1342:    KSPSetResidualHistory - Sets the array used to hold the residual history.
1343:    If set, this array will contain the residual norms computed at each
1344:    iteration of the solver.

1346:    Not Collective

1348:    Input Parameters:
1349: +  ksp - iterative context obtained from KSPCreate()
1350: .  a   - array to hold history
1351: .  na  - size of a
1352: -  reset - PETSC_TRUE indicates the history counter is reset to zero
1353:            for each new linear solve

1355:    Level: advanced

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

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

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

1365: .seealso: KSPGetResidualHistory()

1367: @*/
1368: PetscErrorCode  KSPSetResidualHistory(KSP ksp,PetscReal a[],PetscInt na,PetscTruth reset)
1369: {


1375:   PetscFree(ksp->res_hist_alloc);
1376:   if (na != PETSC_DECIDE && na != PETSC_DEFAULT && a) {
1377:     ksp->res_hist        = a;
1378:     ksp->res_hist_max    = na;
1379:   } else {
1380:     if (na != PETSC_DECIDE && na != PETSC_DEFAULT)
1381:       ksp->res_hist_max = na;
1382:     else
1383:       ksp->res_hist_max = 10000; /* like default ksp->max_it */
1384:     PetscMalloc(ksp->res_hist_max*sizeof(PetscReal),&ksp->res_hist_alloc);
1385:     ksp->res_hist = ksp->res_hist_alloc;
1386:   }
1387:   ksp->res_hist_len    = 0;
1388:   ksp->res_hist_reset  = reset;

1390:   return(0);
1391: }

1395: /*@C
1396:    KSPGetResidualHistory - Gets the array used to hold the residual history
1397:    and the number of residuals it contains.

1399:    Not Collective

1401:    Input Parameter:
1402: .  ksp - iterative context obtained from KSPCreate()

1404:    Output Parameters:
1405: +  a   - pointer to array to hold history (or PETSC_NULL)
1406: -  na  - number of used entries in a (or PETSC_NULL)

1408:    Level: advanced

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

1413:      The Fortran version of this routine has a calling sequence
1414: $   call KSPGetResidualHistory(KSP ksp, integer na, integer ierr)

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

1418: .seealso: KSPGetResidualHistory()

1420: @*/
1421: PetscErrorCode  KSPGetResidualHistory(KSP ksp,PetscReal *a[],PetscInt *na)
1422: {
1425:   if (a)  *a  = ksp->res_hist;
1426:   if (na) *na = ksp->res_hist_len;
1427:   return(0);
1428: }

1432: /*@C
1433:    KSPSetConvergenceTest - Sets the function to be used to determine
1434:    convergence.  

1436:    Collective on KSP

1438:    Input Parameters:
1439: +  ksp - iterative context obtained from KSPCreate()
1440: .  converge - pointer to int function
1441: -  cctx    - context for private data for the convergence routine (may be null)

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

1446: +  ksp - iterative context obtained from KSPCreate()
1447: .  it - iteration number
1448: .  rnorm - (estimated) 2-norm of (preconditioned) residual
1449: .  reason - the reason why it has converged or diverged
1450: -  cctx  - optional convergence context, as set by KSPSetConvergenceTest()


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

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

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

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

1467:    Level: advanced

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

1471: .seealso: KSPDefaultConverged(), KSPGetConvergenceContext()
1472: @*/
1473: PetscErrorCode  KSPSetConvergenceTest(KSP ksp,PetscErrorCode (*converge)(KSP,PetscInt,PetscReal,KSPConvergedReason*,void*),void *cctx,
1474:                                                         PetscErrorCode (*destroy)(void*))
1475: {

1480:   if (ksp->convergeddestroy) {
1481:     (*ksp->convergeddestroy)(ksp->cnvP);
1482:   }
1483:   ksp->converged        = converge;
1484:   ksp->convergeddestroy = destroy;
1485:   ksp->cnvP             = (void*)cctx;
1486:   return(0);
1487: }

1491: /*@C
1492:    KSPGetConvergenceContext - Gets the convergence context set with 
1493:    KSPSetConvergenceTest().  

1495:    Not Collective

1497:    Input Parameter:
1498: .  ksp - iterative context obtained from KSPCreate()

1500:    Output Parameter:
1501: .  ctx - monitoring context

1503:    Level: advanced

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

1507: .seealso: KSPDefaultConverged(), KSPSetConvergenceTest()
1508: @*/
1509: PetscErrorCode  KSPGetConvergenceContext(KSP ksp,void **ctx)
1510: {
1513:   *ctx = ksp->cnvP;
1514:   return(0);
1515: }

1519: /*@
1520:    KSPBuildSolution - Builds the approximate solution in a vector provided.
1521:    This routine is NOT commonly needed (see KSPSolve()).

1523:    Collective on KSP

1525:    Input Parameter:
1526: .  ctx - iterative context obtained from KSPCreate()

1528:    Output Parameter: 
1529:    Provide exactly one of
1530: +  v - location to stash solution.   
1531: -  V - the solution is returned in this location. This vector is created 
1532:        internally. This vector should NOT be destroyed by the user with
1533:        VecDestroy().

1535:    Notes:
1536:    This routine can be used in one of two ways
1537: .vb
1538:       KSPBuildSolution(ksp,PETSC_NULL,&V);
1539:    or
1540:       KSPBuildSolution(ksp,v,PETSC_NULL); 
1541: .ve
1542:    In the first case an internal vector is allocated to store the solution
1543:    (the user cannot destroy this vector). In the second case the solution
1544:    is generated in the vector that the user provides. Note that for certain 
1545:    methods, such as KSPCG, the second case requires a copy of the solution,
1546:    while in the first case the call is essentially free since it simply 
1547:    returns the vector where the solution already is stored.

1549:    Level: advanced

1551: .keywords: KSP, build, solution

1553: .seealso: KSPGetSolution(), KSPBuildResidual()
1554: @*/
1555: PetscErrorCode  KSPBuildSolution(KSP ksp,Vec v,Vec *V)
1556: {

1561:   if (!V && !v) SETERRQ(PETSC_ERR_ARG_WRONG,"Must provide either v or V");
1562:   if (!V) V = &v;
1563:   (*ksp->ops->buildsolution)(ksp,v,V);
1564:   return(0);
1565: }

1569: /*@
1570:    KSPBuildResidual - Builds the residual in a vector provided.

1572:    Collective on KSP

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

1577:    Output Parameters:
1578: +  v - optional location to stash residual.  If v is not provided,
1579:        then a location is generated.
1580: .  t - work vector.  If not provided then one is generated.
1581: -  V - the residual

1583:    Notes:
1584:    Regardless of whether or not v is provided, the residual is 
1585:    returned in V.

1587:    Level: advanced

1589: .keywords: KSP, build, residual

1591: .seealso: KSPBuildSolution()
1592: @*/
1593: PetscErrorCode  KSPBuildResidual(KSP ksp,Vec t,Vec v,Vec *V)
1594: {
1596:   PetscTruth     flag = PETSC_FALSE;
1597:   Vec            w = v,tt = t;

1601:   if (!w) {
1602:     VecDuplicate(ksp->vec_rhs,&w);
1603:     PetscLogObjectParent((PetscObject)ksp,w);
1604:   }
1605:   if (!tt) {
1606:     VecDuplicate(ksp->vec_sol,&tt); flag = PETSC_TRUE;
1607:     PetscLogObjectParent((PetscObject)ksp,tt);
1608:   }
1609:   (*ksp->ops->buildresidual)(ksp,tt,w,V);
1610:   if (flag) {VecDestroy(tt);}
1611:   return(0);
1612: }

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

1620:    Collective on KSP

1622:    Input Parameter:
1623: +  ksp - the KSP context
1624: -  scale - PETSC_TRUE or PETSC_FALSE

1626:    Options Database Key:
1627: +   -ksp_diagonal_scale - 
1628: -   -ksp_diagonal_scale_fix - scale the matrix back AFTER the solve 


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

1635:     This routine is only used if the matrix and preconditioner matrix are
1636:     the same thing.

1638:     This should NOT be used within the SNES solves if you are using a line
1639:     search.
1640:  
1641:     If you use this with the PCType Eisenstat preconditioner than you can 
1642:     use the PCEisenstatNoDiagonalScaling() option, or -pc_eisenstat_no_diagonal_scaling
1643:     to save some unneeded, redundant flops.

1645:    Level: intermediate

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

1649: .seealso: KSPGetDiagonalScale(), KSPSetDiagonalScaleFix()
1650: @*/
1651: PetscErrorCode  KSPSetDiagonalScale(KSP ksp,PetscTruth scale)
1652: {
1655:   ksp->dscale = scale;
1656:   return(0);
1657: }

1661: /*@
1662:    KSPGetDiagonalScale - Checks if KSP solver scales the matrix and
1663:                           right hand side

1665:    Not Collective

1667:    Input Parameter:
1668: .  ksp - the KSP context

1670:    Output Parameter:
1671: .  scale - PETSC_TRUE or PETSC_FALSE

1673:    Notes:
1674:     BE CAREFUL with this routine: it actually scales the matrix and right 
1675:     hand side that define the system. After the system is solved the matrix
1676:     and right hand side remain scaled.

1678:     This routine is only used if the matrix and preconditioner matrix are
1679:     the same thing.

1681:    Level: intermediate

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

1685: .seealso: KSPSetDiagonalScale(), KSPSetDiagonalScaleFix()
1686: @*/
1687: PetscErrorCode  KSPGetDiagonalScale(KSP ksp,PetscTruth *scale)
1688: {
1692:   *scale = ksp->dscale;
1693:   return(0);
1694: }

1698: /*@
1699:    KSPSetDiagonalScaleFix - Tells KSP to diagonally scale the system
1700:      back after solving.

1702:    Collective on KSP

1704:    Input Parameter:
1705: +  ksp - the KSP context
1706: -  fix - PETSC_TRUE to scale back after the system solve, PETSC_FALSE to not 
1707:          rescale (default)

1709:    Notes:
1710:      Must be called after KSPSetDiagonalScale()

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

1717:     This routine is only used if the matrix and preconditioner matrix are
1718:     the same thing.

1720:    Level: intermediate

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

1724: .seealso: KSPGetDiagonalScale(), KSPSetDiagonalScale(), KSPGetDiagonalScaleFix()
1725: @*/
1726: PetscErrorCode  KSPSetDiagonalScaleFix(KSP ksp,PetscTruth fix)
1727: {
1730:   ksp->dscalefix = fix;
1731:   return(0);
1732: }

1736: /*@
1737:    KSPGetDiagonalScaleFix - Determines if KSP diagonally scales the system
1738:      back after solving.

1740:    Collective on KSP

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

1745:    Output Parameter:
1746: .  fix - PETSC_TRUE to scale back after the system solve, PETSC_FALSE to not 
1747:          rescale (default)

1749:    Notes:
1750:      Must be called after KSPSetDiagonalScale()

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

1757:     This routine is only used if the matrix and preconditioner matrix are
1758:     the same thing.

1760:    Level: intermediate

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

1764: .seealso: KSPGetDiagonalScale(), KSPSetDiagonalScale(), KSPSetDiagonalScaleFix()
1765: @*/
1766: PetscErrorCode  KSPGetDiagonalScaleFix(KSP ksp,PetscTruth *fix)
1767: {
1771:   *fix = ksp->dscalefix;
1772:   return(0);
1773: }