Actual source code: itfunc.c
petsc-3.7.1 2016-05-15
Report Typos and Errors

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

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

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

     15:    Not Collective

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

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

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

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

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

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

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

     41:    Level: advanced

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

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

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

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

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

     72:    Not Collective

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

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

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

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

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

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

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

    107:    Level: advanced

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

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

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

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

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

    140:    Not Collective

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

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

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

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

    169:    Level: advanced

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

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

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

    192:    Collective on KSP

    194:    Input Parameter:
    195: .  ksp - the KSP context

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

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

    206:    Level: advanced

    208: .keywords: KSP, setup, blocks

    210: .seealso: PCSetUpOnBlocks(), KSPSetUp(), PCSetUp()
    211: @*/
    212: PetscErrorCode  KSPSetUpOnBlocks(KSP ksp)
    213: {
    215:   PCFailedReason pcreason;

    219:   if (!ksp->pc) {KSPGetPC(ksp,&ksp->pc);}
    220:   PCSetUpOnBlocks(ksp->pc);
    221:   PCGetSetUpFailedReason(ksp->pc,&pcreason);
    222:   if (pcreason) {
    223:     ksp->reason = KSP_DIVERGED_PCSETUP_FAILED;
    224:   }
    225:   return(0);
    226: }

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

    233:    Collective on KSP

    235:    Input Parameters:
    236: +  ksp   - iterative context obtained from KSPCreate()
    237: -  flag - PETSC_TRUE to reuse the current preconditioner

    239:    Level: intermediate

    241: .keywords: KSP, setup

    243: .seealso: KSPCreate(), KSPSolve(), KSPDestroy(), PCSetReusePreconditioner()
    244: @*/
    245: PetscErrorCode  KSPSetReusePreconditioner(KSP ksp,PetscBool flag)
    246: {

    251:   PCSetReusePreconditioner(ksp->pc,flag);
    252:   return(0);
    253: }

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

    260:    Collective on KSP

    262:    Input Parameters:
    263: +  ksp   - iterative context obtained from KSPCreate()
    264: -  flag - PETSC_TRUE to skip calling the PCSetFromOptions()

    266:    Level: intermediate

    268: .keywords: KSP, setup

    270: .seealso: KSPCreate(), KSPSolve(), KSPDestroy(), PCSetReusePreconditioner()
    271: @*/
    272: PetscErrorCode  KSPSetSkipPCSetFromOptions(KSP ksp,PetscBool flag)
    273: {
    276:   ksp->skippcsetfromoptions = flag;
    277:   return(0);
    278: }

    282: /*@
    283:    KSPSetUp - Sets up the internal data structures for the
    284:    later use of an iterative solver.

    286:    Collective on KSP

    288:    Input Parameter:
    289: .  ksp   - iterative context obtained from KSPCreate()

    291:    Level: developer

    293: .keywords: KSP, setup

    295: .seealso: KSPCreate(), KSPSolve(), KSPDestroy()
    296: @*/
    297: PetscErrorCode KSPSetUp(KSP ksp)
    298: {
    300:   Mat            A,B;
    301:   Mat            mat,pmat;
    302:   MatNullSpace   nullsp;
    303:   PCFailedReason pcreason;
    304:

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

    311:   if (!((PetscObject)ksp)->type_name) {
    312:     KSPSetType(ksp,KSPGMRES);
    313:   }
    314:   KSPSetUpNorms_Private(ksp,&ksp->normtype,&ksp->pc_side);

    316:   if (ksp->dmActive && !ksp->setupstage) {
    317:     /* first time in so build matrix and vector data structures using DM */
    318:     if (!ksp->vec_rhs) {DMCreateGlobalVector(ksp->dm,&ksp->vec_rhs);}
    319:     if (!ksp->vec_sol) {DMCreateGlobalVector(ksp->dm,&ksp->vec_sol);}
    320:     DMCreateMatrix(ksp->dm,&A);
    321:     KSPSetOperators(ksp,A,A);
    322:     PetscObjectDereference((PetscObject)A);
    323:   }

    325:   if (ksp->dmActive) {
    326:     DMKSP kdm;
    327:     DMGetDMKSP(ksp->dm,&kdm);

    329:     if (kdm->ops->computeinitialguess && ksp->setupstage != KSP_SETUP_NEWRHS) {
    330:       /* only computes initial guess the first time through */
    331:       (*kdm->ops->computeinitialguess)(ksp,ksp->vec_sol,kdm->initialguessctx);
    332:       KSPSetInitialGuessNonzero(ksp,PETSC_TRUE);
    333:     }
    334:     if (kdm->ops->computerhs) {
    335:       (*kdm->ops->computerhs)(ksp,ksp->vec_rhs,kdm->rhsctx);
    336:     }

    338:     if (ksp->setupstage != KSP_SETUP_NEWRHS) {
    339:       if (kdm->ops->computeoperators) {
    340:         KSPGetOperators(ksp,&A,&B);
    341:         (*kdm->ops->computeoperators)(ksp,A,B,kdm->operatorsctx);
    342:         KSPSetOperators(ksp,A,B);
    343:       } else SETERRQ(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_WRONGSTATE,"You called KSPSetDM() but did not use DMKSPSetComputeOperators() or KSPSetDMActive(dm,PETSC_FALSE);");
    344:     }
    345:   }

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

    350:   switch (ksp->setupstage) {
    351:   case KSP_SETUP_NEW:
    352:     (*ksp->ops->setup)(ksp);
    353:     break;
    354:   case KSP_SETUP_NEWMATRIX: {   /* This should be replaced with a more general mechanism */
    355:   } break;
    356:   default: break;
    357:   }

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

    396:   MatGetNullSpace(mat,&nullsp);
    397:   if (nullsp) {
    398:     PetscBool test = PETSC_FALSE;
    399:     PetscOptionsGetBool(((PetscObject)ksp)->options,((PetscObject)ksp)->prefix,"-ksp_test_null_space",&test,NULL);
    400:     if (test) {
    401:       MatNullSpaceTest(nullsp,mat,NULL);
    402:     }
    403:   }
    404:   ksp->setupstage = KSP_SETUP_NEWRHS;
    405:   return(0);
    406: }

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

    413:    Collective on KSP

    415:    Parameter:
    416: +  ksp - iterative context obtained from KSPCreate()
    417: -  viewer - the viewer to display the reason

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

    423:    Level: beginner

    425: .keywords: KSP, solve, linear system

    427: .seealso: KSPCreate(), KSPSetUp(), KSPDestroy(), KSPSetTolerances(), KSPConvergedDefault(),
    428:           KSPSolveTranspose(), KSPGetIterationNumber()
    429: @*/
    430: PetscErrorCode KSPReasonView(KSP ksp,PetscViewer viewer)
    431: {
    433:   PetscBool      isAscii;

    436:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&isAscii);
    437:   if (isAscii) {
    438:     PetscViewerASCIIAddTab(viewer,((PetscObject)ksp)->tablevel);
    439:     if (ksp->reason > 0) {
    440:       if (((PetscObject) ksp)->prefix) {
    441:         PetscViewerASCIIPrintf(viewer,"Linear %s solve converged due to %s iterations %D\n",((PetscObject) ksp)->prefix,KSPConvergedReasons[ksp->reason],ksp->its);
    442:       } else {
    443:         PetscViewerASCIIPrintf(viewer,"Linear solve converged due to %s iterations %D\n",KSPConvergedReasons[ksp->reason],ksp->its);
    444:       }
    445:     } else {
    446:       if (((PetscObject) ksp)->prefix) {
    447:         PetscViewerASCIIPrintf(viewer,"Linear %s solve did not converge due to %s iterations %D\n",((PetscObject) ksp)->prefix,KSPConvergedReasons[ksp->reason],ksp->its);
    448:       } else {
    449:         PetscViewerASCIIPrintf(viewer,"Linear solve did not converge due to %s iterations %D\n",KSPConvergedReasons[ksp->reason],ksp->its);
    450:       }
    451:       if (ksp->reason == KSP_DIVERGED_PCSETUP_FAILED) {
    452:         PCFailedReason reason;
    453:         PCGetSetUpFailedReason(ksp->pc,&reason);
    454:         PetscViewerASCIIPrintf(viewer,"               PCSETUP_FAILED due to %s \n",PCFailedReasons[reason]);
    455:       }
    456:     }
    457:     PetscViewerASCIISubtractTab(viewer,((PetscObject)ksp)->tablevel);
    458:   }
    459:   return(0);
    460: }

    463: #if defined(PETSC_HAVE_THREADSAFETY)
    464: #define KSPReasonViewFromOptions KSPReasonViewFromOptionsUnsafe
    466: #else
    468: #endif
    469: /*@C
    470:   KSPReasonViewFromOptions - Processes command line options to determine if/how a KSPReason is to be viewed.

    472:   Collective on KSP

    474:   Input Parameters:
    475: . ksp   - the KSP object

    477:   Level: intermediate

    479: @*/
    480: PetscErrorCode KSPReasonViewFromOptions(KSP ksp)
    481: {
    482:   PetscErrorCode    ierr;
    483:   PetscViewer       viewer;
    484:   PetscBool         flg;
    485:   PetscViewerFormat format;

    488:   PetscOptionsGetViewer(PetscObjectComm((PetscObject)ksp),((PetscObject)ksp)->prefix,"-ksp_converged_reason",&viewer,&format,&flg);
    489:   if (flg) {
    490:     PetscViewerPushFormat(viewer,format);
    491:     KSPReasonView(ksp,viewer);
    492:     PetscViewerPopFormat(viewer);
    493:     PetscViewerDestroy(&viewer);
    494:   }
    495:   return(0);
    496: }

    498: #include <petscdraw.h>
    501: /*@
    502:    KSPSolve - Solves linear system.

    504:    Collective on KSP

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

    511:    Options Database Keys:
    512: +  -ksp_compute_eigenvalues - compute preconditioned operators eigenvalues
    513: .  -ksp_plot_eigenvalues - plot the computed eigenvalues in an X-window
    514: .  -ksp_plot_eigencontours - plot the computed eigenvalues in an X-window with contours
    515: .  -ksp_compute_eigenvalues_explicitly - compute the eigenvalues by forming the dense operator and using LAPACK
    516: .  -ksp_plot_eigenvalues_explicitly - plot the explicitly computing eigenvalues
    517: .  -ksp_view_mat binary - save matrix to the default binary viewer
    518: .  -ksp_view_pmat binary - save matrix used to build preconditioner to the default binary viewer
    519: .  -ksp_view_rhs binary - save right hand side vector to the default binary viewer
    520: .  -ksp_view_solution binary - save computed solution vector to the default binary viewer
    521:            (can be read later with src/ksp/examples/tutorials/ex10.c for testing solvers)
    522: .  -ksp_view_mat_explicit - for matrix-free operators, computes the matrix entries and views them
    523: .  -ksp_view_preconditioned_operator_explicit - computes the product of the preconditioner and matrix as an explicit matrix and views it
    524: .  -ksp_converged_reason - print reason for converged or diverged, also prints number of iterations
    525: .  -ksp_final_residual - print 2-norm of true linear system residual at the end of the solution process
    526: -  -ksp_view - print the ksp data structure at the end of the system solution

    528:    Notes:

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

    532:    The operator is specified with KSPSetOperators().

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

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

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

    547:    Level: beginner

    549: .keywords: KSP, solve, linear system

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

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

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

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

    594:   if (ksp->guess) {
    595:     KSPFischerGuessFormGuess(ksp->guess,ksp->vec_rhs,ksp->vec_sol);
    596:     ksp->guess_zero = PETSC_FALSE;
    597:   }
    598:   /* KSPSetUp() scales the matrix if needed */
    599:   KSPSetUp(ksp);
    600:   KSPSetUpOnBlocks(ksp);

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

    604:   PCGetOperators(ksp->pc,&mat,&pmat);
    605:   /* diagonal scale RHS if called for */
    606:   if (ksp->dscale) {
    607:     VecPointwiseMult(ksp->vec_rhs,ksp->vec_rhs,ksp->diagonal);
    608:     /* second time in, but matrix was scaled back to original */
    609:     if (ksp->dscalefix && ksp->dscalefix2) {
    610:       Mat mat,pmat;

    612:       PCGetOperators(ksp->pc,&mat,&pmat);
    613:       MatDiagonalScale(pmat,ksp->diagonal,ksp->diagonal);
    614:       if (mat != pmat) {MatDiagonalScale(mat,ksp->diagonal,ksp->diagonal);}
    615:     }

    617:     /*  scale initial guess */
    618:     if (!ksp->guess_zero) {
    619:       if (!ksp->truediagonal) {
    620:         VecDuplicate(ksp->diagonal,&ksp->truediagonal);
    621:         VecCopy(ksp->diagonal,ksp->truediagonal);
    622:         VecReciprocal(ksp->truediagonal);
    623:       }
    624:       VecPointwiseMult(ksp->vec_sol,ksp->vec_sol,ksp->truediagonal);
    625:     }
    626:   }
    627:   PCPreSolve(ksp->pc,ksp);

    629:   if (ksp->guess_zero) { VecSet(ksp->vec_sol,0.0);}
    630:   if (ksp->guess_knoll) {
    631:     PCApply(ksp->pc,ksp->vec_rhs,ksp->vec_sol);
    632:     KSP_RemoveNullSpace(ksp,ksp->vec_sol);
    633:     ksp->guess_zero = PETSC_FALSE;
    634:   }

    636:   /* can we mark the initial guess as zero for this solve? */
    637:   guess_zero = ksp->guess_zero;
    638:   if (!ksp->guess_zero) {
    639:     PetscReal norm;

    641:     VecNormAvailable(ksp->vec_sol,NORM_2,&flg,&norm);
    642:     if (flg && !norm) ksp->guess_zero = PETSC_TRUE;
    643:   }
    644:   MatGetTransposeNullSpace(pmat,&nullsp);
    645:   if (nullsp) {
    646:     VecDuplicate(ksp->vec_rhs,&btmp);
    647:     VecCopy(ksp->vec_rhs,btmp);
    648:     MatNullSpaceRemove(nullsp,btmp);
    649:     vec_rhs      = ksp->vec_rhs;
    650:     ksp->vec_rhs = btmp;
    651:   }
    652:   VecLockPush(ksp->vec_rhs);
    653:   if (ksp->reason == KSP_DIVERGED_PCSETUP_FAILED) {
    654:     VecSetInf(ksp->vec_sol);
    655:   }
    656:   (*ksp->ops->solve)(ksp);
    657:
    658:   VecLockPop(ksp->vec_rhs);
    659:   if (nullsp) {
    660:     ksp->vec_rhs = vec_rhs;
    661:     VecDestroy(&btmp);
    662:   }

    664:   ksp->guess_zero = guess_zero;

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

    670:   KSPReasonViewFromOptions(ksp);
    671:   PCPostSolve(ksp->pc,ksp);

    673:   /* diagonal scale solution if called for */
    674:   if (ksp->dscale) {
    675:     VecPointwiseMult(ksp->vec_sol,ksp->vec_sol,ksp->diagonal);
    676:     /* unscale right hand side and matrix */
    677:     if (ksp->dscalefix) {
    678:       Mat mat,pmat;

    680:       VecReciprocal(ksp->diagonal);
    681:       VecPointwiseMult(ksp->vec_rhs,ksp->vec_rhs,ksp->diagonal);
    682:       PCGetOperators(ksp->pc,&mat,&pmat);
    683:       MatDiagonalScale(pmat,ksp->diagonal,ksp->diagonal);
    684:       if (mat != pmat) {MatDiagonalScale(mat,ksp->diagonal,ksp->diagonal);}
    685:       VecReciprocal(ksp->diagonal);
    686:       ksp->dscalefix2 = PETSC_TRUE;
    687:     }
    688:   }
    689:   PetscLogEventEnd(KSP_Solve,ksp,ksp->vec_rhs,ksp->vec_sol,0);
    690:   if (ksp->postsolve) {
    691:     (*ksp->postsolve)(ksp,ksp->vec_rhs,ksp->vec_sol,ksp->postctx);
    692:   }

    694:   if (ksp->guess) {
    695:     KSPFischerGuessUpdate(ksp->guess,ksp->vec_sol);
    696:   }

    699:   PCGetOperators(ksp->pc,&mat,&pmat);
    700:   MatViewFromOptions(mat,(PetscObject)ksp,"-ksp_view_mat");
    701:   MatViewFromOptions(pmat,(PetscObject)ksp,"-ksp_view_pmat");
    702:   VecViewFromOptions(ksp->vec_rhs,(PetscObject)ksp,"-ksp_view_rhs");

    704:   PetscOptionsGetViewer(PetscObjectComm((PetscObject)ksp),((PetscObject)ksp)->prefix,"-ksp_compute_eigenvalues",NULL,NULL,&flag1);
    705:   PetscOptionsGetViewer(PetscObjectComm((PetscObject)ksp),((PetscObject)ksp)->prefix,"-ksp_plot_eigenvalues",NULL,NULL,&flag2);
    706:   PetscOptionsGetViewer(PetscObjectComm((PetscObject)ksp),((PetscObject)ksp)->prefix,"-ksp_plot_eigencontours",NULL,NULL,&flag3);
    707:   if (flag1 || flag2 || flag3) {
    708:     PetscInt    nits,n,i,neig;
    709:     PetscReal   *r,*c;

    711:     KSPGetIterationNumber(ksp,&nits);
    712:     n    = nits+2;

    714:     if (!nits) {
    715:       PetscPrintf(comm,"Zero iterations in solver, cannot approximate any eigenvalues\n");
    716:     } else {
    717:       PetscMPIInt rank;
    718:       MPI_Comm_rank(comm,&rank);
    719:       PetscMalloc2(n,&r,n,&c);
    720:       KSPComputeEigenvalues(ksp,n,r,c,&neig);
    721:       if (flag1) {
    722:         PetscPrintf(comm,"Iteratively computed eigenvalues\n");
    723:         for (i=0; i<neig; i++) {
    724:           if (c[i] >= 0.0) {
    725:             PetscPrintf(comm,"%g + %gi\n",(double)r[i],(double)c[i]);
    726:           } else {
    727:             PetscPrintf(comm,"%g - %gi\n",(double)r[i],-(double)c[i]);
    728:           }
    729:         }
    730:       }
    731:       if (flag2 && !rank) {
    732:         PetscDraw   draw;
    733:         PetscDrawSP drawsp;

    735:         if (!ksp->eigviewer) {
    736:           PetscViewerDrawOpen(PETSC_COMM_SELF,0,"Iteratively Computed Eigenvalues",PETSC_DECIDE,PETSC_DECIDE,400,400,&ksp->eigviewer);
    737:         }
    738:         PetscViewerDrawGetDraw(ksp->eigviewer,0,&draw);
    739:         PetscDrawSPCreate(draw,1,&drawsp);
    740:         for (i=0; i<neig; i++) {
    741:           PetscDrawSPAddPoint(drawsp,r+i,c+i);
    742:         }
    743:         PetscDrawSPDraw(drawsp,PETSC_TRUE);
    744:         PetscDrawSPSave(drawsp);
    745:         PetscDrawSPDestroy(&drawsp);
    746:       }
    747:       if (flag3 && !rank) {
    748:         KSPPlotEigenContours_Private(ksp,neig,r,c);
    749:       }
    750:       PetscFree2(r,c);
    751:     }
    752:   }

    754:   PetscOptionsGetViewer(PetscObjectComm((PetscObject)ksp),((PetscObject)ksp)->prefix,"-ksp_compute_singularvalues",NULL,NULL,&flag1);
    755:   if (flag1) {
    756:     PetscInt nits;

    758:     KSPGetIterationNumber(ksp,&nits);
    759:     if (!nits) {
    760:       PetscPrintf(comm,"Zero iterations in solver, cannot approximate any singular values\n");
    761:     } else {
    762:       PetscReal emax,emin;

    764:       KSPComputeExtremeSingularValues(ksp,&emax,&emin);
    765:       PetscPrintf(comm,"Iteratively computed extreme singular values: max %g min %g max/min %g\n",(double)emax,(double)emin,(double)(emax/emin));
    766:     }
    767:   }

    769:   PetscOptionsGetViewer(PetscObjectComm((PetscObject)ksp),((PetscObject)ksp)->prefix,"-ksp_compute_eigenvalues_explicitly",NULL,NULL,&flag1);
    770:   PetscOptionsGetViewer(PetscObjectComm((PetscObject)ksp),((PetscObject)ksp)->prefix,"-ksp_plot_eigenvalues_explicitly",NULL,NULL,&flag2);
    771:   if (flag1 || flag2) {
    772:     PetscInt    n,i;
    773:     PetscReal   *r,*c;
    774:     PetscMPIInt rank;
    775:     MPI_Comm_rank(comm,&rank);
    776:     VecGetSize(ksp->vec_sol,&n);
    777:     PetscMalloc2(n,&r,n,&c);
    778:     KSPComputeEigenvaluesExplicitly(ksp,n,r,c);
    779:     if (flag1) {
    780:       PetscPrintf(comm,"Explicitly computed eigenvalues\n");
    781:       for (i=0; i<n; i++) {
    782:         if (c[i] >= 0.0) {
    783:           PetscPrintf(comm,"%g + %gi\n",(double)r[i],(double)c[i]);
    784:         } else {
    785:           PetscPrintf(comm,"%g - %gi\n",(double)r[i],-(double)c[i]);
    786:         }
    787:       }
    788:     }
    789:     if (flag2 && !rank) {
    790:       PetscDraw   draw;
    791:       PetscDrawSP drawsp;

    793:       if (!ksp->eigviewer) {
    794:         PetscViewerDrawOpen(PETSC_COMM_SELF,0,"Explicitly Computed Eigenvalues",PETSC_DECIDE,PETSC_DECIDE,400,400,&ksp->eigviewer);
    795:       }
    796:       PetscViewerDrawGetDraw(ksp->eigviewer,0,&draw);
    797:       PetscDrawSPCreate(draw,1,&drawsp);
    798:       PetscDrawSPReset(drawsp);
    799:       for (i=0; i<n; i++) {
    800:         PetscDrawSPAddPoint(drawsp,r+i,c+i);
    801:       }
    802:       PetscDrawSPDraw(drawsp,PETSC_TRUE);
    803:       PetscDrawSPSave(drawsp);
    804:       PetscDrawSPDestroy(&drawsp);
    805:     }
    806:     PetscFree2(r,c);
    807:   }

    809:   PetscOptionsGetViewer(PetscObjectComm((PetscObject)ksp),((PetscObject)ksp)->prefix,"-ksp_view_mat_explicit",NULL,NULL,&flag2);
    810:   if (flag2) {
    811:     Mat A,B;
    812:     PCGetOperators(ksp->pc,&A,NULL);
    813:     MatComputeExplicitOperator(A,&B);
    814:     MatViewFromOptions(B,(PetscObject)ksp,"-ksp_view_mat_explicit");
    815:     MatDestroy(&B);
    816:   }
    817:   PetscOptionsGetViewer(PetscObjectComm((PetscObject)ksp),((PetscObject)ksp)->prefix,"-ksp_view_preconditioned_operator_explicit",NULL,NULL,&flag2);
    818:   if (flag2) {
    819:     Mat B;
    820:     KSPComputeExplicitOperator(ksp,&B);
    821:     MatViewFromOptions(B,(PetscObject)ksp,"-ksp_view_preconditioned_operator_explicit");
    822:     MatDestroy(&B);
    823:   }
    824:   KSPViewFromOptions(ksp,NULL,"-ksp_view");

    826:   PetscOptionsGetViewer(PetscObjectComm((PetscObject)ksp),((PetscObject)ksp)->prefix,"-ksp_final_residual",NULL,NULL,&flg);
    827:   if (flg) {
    828:     Mat       A;
    829:     Vec       t;
    830:     PetscReal norm;
    831:     if (ksp->dscale && !ksp->dscalefix) SETERRQ(comm,PETSC_ERR_ARG_WRONGSTATE,"Cannot compute final scale with -ksp_diagonal_scale except also with -ksp_diagonal_scale_fix");
    832:     PCGetOperators(ksp->pc,&A,NULL);
    833:     VecDuplicate(ksp->vec_rhs,&t);
    834:     KSP_MatMult(ksp,A,ksp->vec_sol,t);
    835:     VecAYPX(t, -1.0, ksp->vec_rhs);
    836:     VecNorm(t,NORM_2,&norm);
    837:     VecDestroy(&t);
    838:     PetscPrintf(comm,"KSP final norm of residual %g\n",(double)norm);
    839:   }
    840:   VecViewFromOptions(ksp->vec_sol,(PetscObject)ksp,"-ksp_view_solution");

    842:   if (inXisinB) {
    843:     VecCopy(x,b);
    844:     VecDestroy(&x);
    845:   }
    846:   PetscObjectSAWsBlock((PetscObject)ksp);
    847:   if (ksp->errorifnotconverged && ksp->reason < 0) SETERRQ(comm,PETSC_ERR_NOT_CONVERGED,"KSPSolve has not converged");
    848:   return(0);
    849: }

    853: /*@
    854:    KSPSolveTranspose - Solves the transpose of a linear system.

    856:    Collective on KSP

    858:    Input Parameter:
    859: +  ksp - iterative context obtained from KSPCreate()
    860: .  b - right hand side vector
    861: -  x - solution vector

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

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

    867:    Level: developer

    869: .keywords: KSP, solve, linear system

    871: .seealso: KSPCreate(), KSPSetUp(), KSPDestroy(), KSPSetTolerances(), KSPConvergedDefault(),
    872:           KSPSolve()
    873: @*/

    875: PetscErrorCode  KSPSolveTranspose(KSP ksp,Vec b,Vec x)
    876: {
    878:   PetscBool      inXisinB=PETSC_FALSE;

    884:   if (x == b) {
    885:     VecDuplicate(b,&x);
    886:     inXisinB = PETSC_TRUE;
    887:   }
    888:   PetscObjectReference((PetscObject)b);
    889:   PetscObjectReference((PetscObject)x);
    890:   VecDestroy(&ksp->vec_rhs);
    891:   VecDestroy(&ksp->vec_sol);

    893:   ksp->vec_rhs         = b;
    894:   ksp->vec_sol         = x;
    895:   ksp->transpose_solve = PETSC_TRUE;

    897:   KSPSetUp(ksp);
    898:   if (ksp->guess_zero) { VecSet(ksp->vec_sol,0.0);}
    899:   (*ksp->ops->solve)(ksp);
    900:   if (!ksp->reason) SETERRQ(PetscObjectComm((PetscObject)ksp),PETSC_ERR_PLIB,"Internal error, solver returned without setting converged reason");
    901:   KSPReasonViewFromOptions(ksp);
    902:   if (inXisinB) {
    903:     VecCopy(x,b);
    904:     VecDestroy(&x);
    905:   }
    906:   if (ksp->errorifnotconverged && ksp->reason < 0) SETERRQ(PetscObjectComm((PetscObject)ksp),PETSC_ERR_NOT_CONVERGED,"KSPSolve has not converged");
    907:   return(0);
    908: }

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

    915:    Collective on KSP

    917:    Input Parameter:
    918: .  ksp - iterative context obtained from KSPCreate()

    920:    Level: beginner

    922: .keywords: KSP, destroy

    924: .seealso: KSPCreate(), KSPSetUp(), KSPSolve()
    925: @*/
    926: PetscErrorCode  KSPReset(KSP ksp)
    927: {

    932:   if (!ksp) return(0);
    933:   if (ksp->ops->reset) {
    934:     (*ksp->ops->reset)(ksp);
    935:   }
    936:   if (ksp->pc) {PCReset(ksp->pc);}
    937:   KSPFischerGuessDestroy(&ksp->guess);
    938:   VecDestroyVecs(ksp->nwork,&ksp->work);
    939:   VecDestroy(&ksp->vec_rhs);
    940:   VecDestroy(&ksp->vec_sol);
    941:   VecDestroy(&ksp->diagonal);
    942:   VecDestroy(&ksp->truediagonal);

    944:   ksp->setupstage = KSP_SETUP_NEW;
    945:   return(0);
    946: }

    950: /*@
    951:    KSPDestroy - Destroys KSP context.

    953:    Collective on KSP

    955:    Input Parameter:
    956: .  ksp - iterative context obtained from KSPCreate()

    958:    Level: beginner

    960: .keywords: KSP, destroy

    962: .seealso: KSPCreate(), KSPSetUp(), KSPSolve()
    963: @*/
    964: PetscErrorCode  KSPDestroy(KSP *ksp)
    965: {
    967:   PC             pc;

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

    974:   PetscObjectSAWsViewOff((PetscObject)*ksp);
    975:   /*
    976:    Avoid a cascading call to PCReset(ksp->pc) from the following call:
    977:    PCReset() shouldn't be called from KSPDestroy() as it is unprotected by pc's
    978:    refcount (and may be shared, e.g., by other ksps).
    979:    */
    980:   pc         = (*ksp)->pc;
    981:   (*ksp)->pc = NULL;
    982:   KSPReset((*ksp));
    983:   (*ksp)->pc = pc;
    984:     if ((*ksp)->ops->destroy) {(*(*ksp)->ops->destroy)(*ksp);}

    986:   DMDestroy(&(*ksp)->dm);
    987:   PCDestroy(&(*ksp)->pc);
    988:   PetscFree((*ksp)->res_hist_alloc);
    989:   if ((*ksp)->convergeddestroy) {
    990:     (*(*ksp)->convergeddestroy)((*ksp)->cnvP);
    991:   }
    992:   KSPMonitorCancel((*ksp));
    993:   PetscViewerDestroy(&(*ksp)->eigviewer);
    994:   PetscHeaderDestroy(ksp);
    995:   return(0);
    996: }

    1000: /*@
    1001:     KSPSetPCSide - Sets the preconditioning side.

    1003:     Logically Collective on KSP

    1005:     Input Parameter:
    1006: .   ksp - iterative context obtained from KSPCreate()

    1008:     Output Parameter:
    1009: .   side - the preconditioning side, where side is one of
    1010: .vb
    1011:       PC_LEFT - left preconditioning (default)
    1012:       PC_RIGHT - right preconditioning
    1013:       PC_SYMMETRIC - symmetric preconditioning
    1014: .ve

    1016:     Options Database Keys:
    1017: .   -ksp_pc_side <right,left,symmetric>

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

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

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

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

    1030:     Level: intermediate

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

    1034: .seealso: KSPGetPCSide(), KSPSetNormType(), KSPGetNormType()
    1035: @*/
    1036: PetscErrorCode  KSPSetPCSide(KSP ksp,PCSide side)
    1037: {
    1041:   ksp->pc_side = ksp->pc_side_set = side;
    1042:   return(0);
    1043: }

    1047: /*@
    1048:     KSPGetPCSide - Gets the preconditioning side.

    1050:     Not Collective

    1052:     Input Parameter:
    1053: .   ksp - iterative context obtained from KSPCreate()

    1055:     Output Parameter:
    1056: .   side - the preconditioning side, where side is one of
    1057: .vb
    1058:       PC_LEFT - left preconditioning (default)
    1059:       PC_RIGHT - right preconditioning
    1060:       PC_SYMMETRIC - symmetric preconditioning
    1061: .ve

    1063:     Level: intermediate

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

    1067: .seealso: KSPSetPCSide()
    1068: @*/
    1069: PetscErrorCode  KSPGetPCSide(KSP ksp,PCSide *side)
    1070: {

    1076:   KSPSetUpNorms_Private(ksp,&ksp->normtype,&ksp->pc_side);
    1077:   *side = ksp->pc_side;
    1078:   return(0);
    1079: }

    1083: /*@
    1084:    KSPGetTolerances - Gets the relative, absolute, divergence, and maximum
    1085:    iteration tolerances used by the default KSP convergence tests.

    1087:    Not Collective

    1089:    Input Parameter:
    1090: .  ksp - the Krylov subspace context

    1092:    Output Parameters:
    1093: +  rtol - the relative convergence tolerance
    1094: .  abstol - the absolute convergence tolerance
    1095: .  dtol - the divergence tolerance
    1096: -  maxits - maximum number of iterations

    1098:    Notes:
    1099:    The user can specify NULL for any parameter that is not needed.

    1101:    Level: intermediate

    1103: .keywords: KSP, get, tolerance, absolute, relative, divergence, convergence,
    1104:            maximum, iterations

    1106: .seealso: KSPSetTolerances()
    1107: @*/
    1108: PetscErrorCode  KSPGetTolerances(KSP ksp,PetscReal *rtol,PetscReal *abstol,PetscReal *dtol,PetscInt *maxits)
    1109: {
    1112:   if (abstol) *abstol = ksp->abstol;
    1113:   if (rtol) *rtol = ksp->rtol;
    1114:   if (dtol) *dtol = ksp->divtol;
    1115:   if (maxits) *maxits = ksp->max_it;
    1116:   return(0);
    1117: }

    1121: /*@
    1122:    KSPSetTolerances - Sets the relative, absolute, divergence, and maximum
    1123:    iteration tolerances used by the default KSP convergence testers.

    1125:    Logically Collective on KSP

    1127:    Input Parameters:
    1128: +  ksp - the Krylov subspace context
    1129: .  rtol - the relative convergence tolerance, relative decrease in the (possibly preconditioned) residual norm
    1130: .  abstol - the absolute convergence tolerance   absolute size of the (possibly preconditioned) residual norm
    1131: .  dtol - the divergence tolerance,   amount (possibly preconditioned) residual norm can increase before KSPConvergedDefault() concludes that the method is diverging
    1132: -  maxits - maximum number of iterations to use

    1134:    Options Database Keys:
    1135: +  -ksp_atol <abstol> - Sets abstol
    1136: .  -ksp_rtol <rtol> - Sets rtol
    1137: .  -ksp_divtol <dtol> - Sets dtol
    1138: -  -ksp_max_it <maxits> - Sets maxits

    1140:    Notes:
    1141:    Use PETSC_DEFAULT to retain the default value of any of the tolerances.

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

    1146:    Level: intermediate

    1148: .keywords: KSP, set, tolerance, absolute, relative, divergence,
    1149:            convergence, maximum, iterations

    1151: .seealso: KSPGetTolerances(), KSPConvergedDefault(), KSPSetConvergenceTest()
    1152: @*/
    1153: PetscErrorCode  KSPSetTolerances(KSP ksp,PetscReal rtol,PetscReal abstol,PetscReal dtol,PetscInt maxits)
    1154: {

    1162:   if (rtol != PETSC_DEFAULT) {
    1163:     if (rtol < 0.0 || 1.0 <= rtol) SETERRQ1(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_OUTOFRANGE,"Relative tolerance %g must be non-negative and less than 1.0",(double)rtol);
    1164:     ksp->rtol = rtol;
    1165:   }
    1166:   if (abstol != PETSC_DEFAULT) {
    1167:     if (abstol < 0.0) SETERRQ1(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_OUTOFRANGE,"Absolute tolerance %g must be non-negative",(double)abstol);
    1168:     ksp->abstol = abstol;
    1169:   }
    1170:   if (dtol != PETSC_DEFAULT) {
    1171:     if (dtol < 0.0) SETERRQ1(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_OUTOFRANGE,"Divergence tolerance %g must be larger than 1.0",(double)dtol);
    1172:     ksp->divtol = dtol;
    1173:   }
    1174:   if (maxits != PETSC_DEFAULT) {
    1175:     if (maxits < 0) SETERRQ1(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of iterations %D must be non-negative",maxits);
    1176:     ksp->max_it = maxits;
    1177:   }
    1178:   return(0);
    1179: }

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

    1188:    Logically Collective on KSP

    1190:    Input Parameters:
    1191: +  ksp - iterative context obtained from KSPCreate()
    1192: -  flg - PETSC_TRUE indicates the guess is non-zero, PETSC_FALSE indicates the guess is zero

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

    1197:    Level: beginner

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

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

    1204: .seealso: KSPGetInitialGuessNonzero(), KSPSetInitialGuessKnoll(), KSPGetInitialGuessKnoll()
    1205: @*/
    1206: PetscErrorCode  KSPSetInitialGuessNonzero(KSP ksp,PetscBool flg)
    1207: {
    1211:   ksp->guess_zero = (PetscBool) !(int)flg;
    1212:   return(0);
    1213: }

    1217: /*@
    1218:    KSPGetInitialGuessNonzero - Determines whether the KSP solver is using
    1219:    a zero initial guess.

    1221:    Not Collective

    1223:    Input Parameter:
    1224: .  ksp - iterative context obtained from KSPCreate()

    1226:    Output Parameter:
    1227: .  flag - PETSC_TRUE if guess is nonzero, else PETSC_FALSE

    1229:    Level: intermediate

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

    1233: .seealso: KSPSetInitialGuessNonzero(), KSPSetInitialGuessKnoll(), KSPGetInitialGuessKnoll()
    1234: @*/
    1235: PetscErrorCode  KSPGetInitialGuessNonzero(KSP ksp,PetscBool  *flag)
    1236: {
    1240:   if (ksp->guess_zero) *flag = PETSC_FALSE;
    1241:   else *flag = PETSC_TRUE;
    1242:   return(0);
    1243: }

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

    1250:    Logically Collective on KSP

    1252:    Input Parameters:
    1253: +  ksp - iterative context obtained from KSPCreate()
    1254: -  flg - PETSC_TRUE indicates you want the error generated

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

    1259:    Level: intermediate

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

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

    1267: .seealso: KSPGetInitialGuessNonzero(), KSPSetInitialGuessKnoll(), KSPGetInitialGuessKnoll(), KSPGetErrorIfNotConverged()
    1268: @*/
    1269: PetscErrorCode  KSPSetErrorIfNotConverged(KSP ksp,PetscBool flg)
    1270: {
    1274:   ksp->errorifnotconverged = flg;
    1275:   return(0);
    1276: }

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

    1283:    Not Collective

    1285:    Input Parameter:
    1286: .  ksp - iterative context obtained from KSPCreate()

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

    1291:    Level: intermediate

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

    1295: .seealso: KSPSetInitialGuessNonzero(), KSPSetInitialGuessKnoll(), KSPGetInitialGuessKnoll(), KSPSetErrorIfNotConverged()
    1296: @*/
    1297: PetscErrorCode  KSPGetErrorIfNotConverged(KSP ksp,PetscBool  *flag)
    1298: {
    1302:   *flag = ksp->errorifnotconverged;
    1303:   return(0);
    1304: }

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

    1311:    Logically Collective on KSP

    1313:    Input Parameters:
    1314: +  ksp - iterative context obtained from KSPCreate()
    1315: -  flg - PETSC_TRUE or PETSC_FALSE

    1317:    Level: advanced

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

    1322: .seealso: KSPGetInitialGuessKnoll(), KSPSetInitialGuessNonzero(), KSPGetInitialGuessNonzero()
    1323: @*/
    1324: PetscErrorCode  KSPSetInitialGuessKnoll(KSP ksp,PetscBool flg)
    1325: {
    1329:   ksp->guess_knoll = flg;
    1330:   return(0);
    1331: }

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

    1339:    Not Collective

    1341:    Input Parameter:
    1342: .  ksp - iterative context obtained from KSPCreate()

    1344:    Output Parameter:
    1345: .  flag - PETSC_TRUE if using Knoll trick, else PETSC_FALSE

    1347:    Level: advanced

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

    1351: .seealso: KSPSetInitialGuessKnoll(), KSPSetInitialGuessNonzero(), KSPGetInitialGuessNonzero()
    1352: @*/
    1353: PetscErrorCode  KSPGetInitialGuessKnoll(KSP ksp,PetscBool  *flag)
    1354: {
    1358:   *flag = ksp->guess_knoll;
    1359:   return(0);
    1360: }

    1364: /*@
    1365:    KSPGetComputeSingularValues - Gets the flag indicating whether the extreme singular
    1366:    values will be calculated via a Lanczos or Arnoldi process as the linear
    1367:    system is solved.

    1369:    Not Collective

    1371:    Input Parameter:
    1372: .  ksp - iterative context obtained from KSPCreate()

    1374:    Output Parameter:
    1375: .  flg - PETSC_TRUE or PETSC_FALSE

    1377:    Options Database Key:
    1378: .  -ksp_monitor_singular_value - Activates KSPSetComputeSingularValues()

    1380:    Notes:
    1381:    Currently this option is not valid for all iterative methods.

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

    1387:    Level: advanced

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

    1391: .seealso: KSPComputeExtremeSingularValues(), KSPMonitorSingularValue()
    1392: @*/
    1393: PetscErrorCode  KSPGetComputeSingularValues(KSP ksp,PetscBool  *flg)
    1394: {
    1398:   *flg = ksp->calc_sings;
    1399:   return(0);
    1400: }

    1404: /*@
    1405:    KSPSetComputeSingularValues - Sets a flag so that the extreme singular
    1406:    values will be calculated via a Lanczos or Arnoldi process as the linear
    1407:    system is solved.

    1409:    Logically Collective on KSP

    1411:    Input Parameters:
    1412: +  ksp - iterative context obtained from KSPCreate()
    1413: -  flg - PETSC_TRUE or PETSC_FALSE

    1415:    Options Database Key:
    1416: .  -ksp_monitor_singular_value - Activates KSPSetComputeSingularValues()

    1418:    Notes:
    1419:    Currently this option is not valid for all iterative methods.

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

    1425:    Level: advanced

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

    1429: .seealso: KSPComputeExtremeSingularValues(), KSPMonitorSingularValue()
    1430: @*/
    1431: PetscErrorCode  KSPSetComputeSingularValues(KSP ksp,PetscBool flg)
    1432: {
    1436:   ksp->calc_sings = flg;
    1437:   return(0);
    1438: }

    1442: /*@
    1443:    KSPGetComputeEigenvalues - Gets the flag indicating that the extreme eigenvalues
    1444:    values will be calculated via a Lanczos or Arnoldi process as the linear
    1445:    system is solved.

    1447:    Not Collective

    1449:    Input Parameter:
    1450: .  ksp - iterative context obtained from KSPCreate()

    1452:    Output Parameter:
    1453: .  flg - PETSC_TRUE or PETSC_FALSE

    1455:    Notes:
    1456:    Currently this option is not valid for all iterative methods.

    1458:    Level: advanced

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

    1462: .seealso: KSPComputeEigenvalues(), KSPComputeEigenvaluesExplicitly()
    1463: @*/
    1464: PetscErrorCode  KSPGetComputeEigenvalues(KSP ksp,PetscBool  *flg)
    1465: {
    1469:   *flg = ksp->calc_sings;
    1470:   return(0);
    1471: }

    1475: /*@
    1476:    KSPSetComputeEigenvalues - Sets a flag so that the extreme eigenvalues
    1477:    values will be calculated via a Lanczos or Arnoldi process as the linear
    1478:    system is solved.

    1480:    Logically Collective on KSP

    1482:    Input Parameters:
    1483: +  ksp - iterative context obtained from KSPCreate()
    1484: -  flg - PETSC_TRUE or PETSC_FALSE

    1486:    Notes:
    1487:    Currently this option is not valid for all iterative methods.

    1489:    Level: advanced

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

    1493: .seealso: KSPComputeEigenvalues(), KSPComputeEigenvaluesExplicitly()
    1494: @*/
    1495: PetscErrorCode  KSPSetComputeEigenvalues(KSP ksp,PetscBool flg)
    1496: {
    1500:   ksp->calc_sings = flg;
    1501:   return(0);
    1502: }

    1506: /*@
    1507:    KSPSetComputeRitz - Sets a flag so that the Ritz or harmonic Ritz pairs
    1508:    will be calculated via a Lanczos or Arnoldi process as the linear
    1509:    system is solved.

    1511:    Logically Collective on KSP

    1513:    Input Parameters:
    1514: +  ksp - iterative context obtained from KSPCreate()
    1515: -  flg - PETSC_TRUE or PETSC_FALSE

    1517:    Notes:
    1518:    Currently this option is only valid for the GMRES method.

    1520:    Level: advanced

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

    1524: .seealso: KSPComputeRitz()
    1525: @*/
    1526: PetscErrorCode  KSPSetComputeRitz(KSP ksp, PetscBool flg)
    1527: {
    1531:   ksp->calc_ritz = flg;
    1532:   return(0);
    1533: }

    1537: /*@
    1538:    KSPGetRhs - Gets the right-hand-side vector for the linear system to
    1539:    be solved.

    1541:    Not Collective

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

    1546:    Output Parameter:
    1547: .  r - right-hand-side vector

    1549:    Level: developer

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

    1553: .seealso: KSPGetSolution(), KSPSolve()
    1554: @*/
    1555: PetscErrorCode  KSPGetRhs(KSP ksp,Vec *r)
    1556: {
    1560:   *r = ksp->vec_rhs;
    1561:   return(0);
    1562: }

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

    1571:    Not Collective

    1573:    Input Parameters:
    1574: .  ksp - iterative context obtained from KSPCreate()

    1576:    Output Parameters:
    1577: .  v - solution vector

    1579:    Level: developer

    1581: .keywords: KSP, get, solution

    1583: .seealso: KSPGetRhs(),  KSPBuildSolution(), KSPSolve()
    1584: @*/
    1585: PetscErrorCode  KSPGetSolution(KSP ksp,Vec *v)
    1586: {
    1590:   *v = ksp->vec_sol;
    1591:   return(0);
    1592: }

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

    1600:    Collective on KSP

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

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

    1610:    Level: developer

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

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

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

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

    1637:    Not Collective

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

    1642:    Output Parameter:
    1643: .  pc - preconditioner context

    1645:    Level: developer

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

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

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

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

    1672:    Collective on KSP

    1674:    Input Parameters:
    1675: +  ksp - iterative context obtained from KSPCreate()
    1676: .  it - iteration number
    1677: -  rnorm - relative norm of the residual

    1679:    Notes:
    1680:    This routine is called by the KSP implementations.
    1681:    It does not typically need to be called by the user.

    1683:    Level: developer

    1685: .seealso: KSPMonitorSet()
    1686: @*/
    1687: PetscErrorCode KSPMonitor(KSP ksp,PetscInt it,PetscReal rnorm)
    1688: {
    1689:   PetscInt       i, n = ksp->numbermonitors;

    1693:   for (i=0; i<n; i++) {
    1694:     (*ksp->monitor[i])(ksp,it,rnorm,ksp->monitorcontext[i]);
    1695:   }
    1696:   return(0);
    1697: }

    1701: /*@C
    1702:    KSPMonitorSet - Sets an ADDITIONAL function to be called at every iteration to monitor
    1703:    the residual/error etc.

    1705:    Logically Collective on KSP

    1707:    Input Parameters:
    1708: +  ksp - iterative context obtained from KSPCreate()
    1709: .  monitor - pointer to function (if this is NULL, it turns off monitoring
    1710: .  mctx    - [optional] context for private data for the
    1711:              monitor routine (use NULL if no context is desired)
    1712: -  monitordestroy - [optional] routine that frees monitor context
    1713:           (may be NULL)

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

    1718: +  ksp - iterative context obtained from KSPCreate()
    1719: .  it - iteration number
    1720: .  rnorm - (estimated) 2-norm of (preconditioned) residual
    1721: -  mctx  - optional monitoring context, as set by KSPMonitorSet()

    1723:    Options Database Keys:
    1724: +    -ksp_monitor        - sets KSPMonitorDefault()
    1725: .    -ksp_monitor_true_residual    - sets KSPMonitorTrueResidualNorm()
    1726: .    -ksp_monitor_max    - sets KSPMonitorTrueResidualMaxNorm()
    1727: .    -ksp_monitor_lg_residualnorm    - sets line graph monitor,
    1728:                            uses KSPMonitorLGResidualNormCreate()
    1729: .    -ksp_monitor_lg_true_residualnorm   - sets line graph monitor,
    1730:                            uses KSPMonitorLGResidualNormCreate()
    1731: .    -ksp_monitor_singular_value    - sets KSPMonitorSingularValue()
    1732: -    -ksp_monitor_cancel - cancels all monitors that have
    1733:                           been hardwired into a code by
    1734:                           calls to KSPMonitorSet(), but
    1735:                           does not cancel those set via
    1736:                           the options database.

    1738:    Notes:
    1739:    The default is to do nothing.  To print the residual, or preconditioned
    1740:    residual if KSPSetNormType(ksp,KSP_NORM_PRECONDITIONED) was called, use
    1741:    KSPMonitorDefault() as the monitoring routine, with a ASCII viewer as the
    1742:    context.

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

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

    1750:    Level: beginner

    1752: .keywords: KSP, set, monitor

    1754: .seealso: KSPMonitorDefault(), KSPMonitorLGResidualNormCreate(), KSPMonitorCancel()
    1755: @*/
    1756: PetscErrorCode  KSPMonitorSet(KSP ksp,PetscErrorCode (*monitor)(KSP,PetscInt,PetscReal,void*),void *mctx,PetscErrorCode (*monitordestroy)(void**))
    1757: {
    1758:   PetscInt       i;

    1763:   if (ksp->numbermonitors >= MAXKSPMONITORS) SETERRQ(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_OUTOFRANGE,"Too many KSP monitors set");
    1764:   for (i=0; i<ksp->numbermonitors;i++) {
    1765:     if (monitor == ksp->monitor[i] && monitordestroy == ksp->monitordestroy[i] && mctx == ksp->monitorcontext[i]) {
    1766:       if (monitordestroy) {
    1767:         (*monitordestroy)(&mctx);
    1768:       }
    1769:       return(0);
    1770:     }
    1771:   }
    1772:   ksp->monitor[ksp->numbermonitors]          = monitor;
    1773:   ksp->monitordestroy[ksp->numbermonitors]   = monitordestroy;
    1774:   ksp->monitorcontext[ksp->numbermonitors++] = (void*)mctx;
    1775:   return(0);
    1776: }

    1780: /*@
    1781:    KSPMonitorCancel - Clears all monitors for a KSP object.

    1783:    Logically Collective on KSP

    1785:    Input Parameters:
    1786: .  ksp - iterative context obtained from KSPCreate()

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

    1793:    Level: intermediate

    1795: .keywords: KSP, set, monitor

    1797: .seealso: KSPMonitorDefault(), KSPMonitorLGResidualNormCreate(), KSPMonitorSet()
    1798: @*/
    1799: PetscErrorCode  KSPMonitorCancel(KSP ksp)
    1800: {
    1802:   PetscInt       i;

    1806:   for (i=0; i<ksp->numbermonitors; i++) {
    1807:     if (ksp->monitordestroy[i]) {
    1808:       (*ksp->monitordestroy[i])(&ksp->monitorcontext[i]);
    1809:     }
    1810:   }
    1811:   ksp->numbermonitors = 0;
    1812:   return(0);
    1813: }

    1817: /*@C
    1818:    KSPGetMonitorContext - Gets the monitoring context, as set by
    1819:    KSPMonitorSet() for the FIRST monitor only.

    1821:    Not Collective

    1823:    Input Parameter:
    1824: .  ksp - iterative context obtained from KSPCreate()

    1826:    Output Parameter:
    1827: .  ctx - monitoring context

    1829:    Level: intermediate

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

    1833: .seealso: KSPMonitorDefault(), KSPMonitorLGResidualNormCreate()
    1834: @*/
    1835: PetscErrorCode  KSPGetMonitorContext(KSP ksp,void **ctx)
    1836: {
    1839:   *ctx =      (ksp->monitorcontext[0]);
    1840:   return(0);
    1841: }

    1845: /*@
    1846:    KSPSetResidualHistory - Sets the array used to hold the residual history.
    1847:    If set, this array will contain the residual norms computed at each
    1848:    iteration of the solver.

    1850:    Not Collective

    1852:    Input Parameters:
    1853: +  ksp - iterative context obtained from KSPCreate()
    1854: .  a   - array to hold history
    1855: .  na  - size of a
    1856: -  reset - PETSC_TRUE indicates the history counter is reset to zero
    1857:            for each new linear solve

    1859:    Level: advanced

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

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

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

    1869: .seealso: KSPGetResidualHistory()

    1871: @*/
    1872: PetscErrorCode  KSPSetResidualHistory(KSP ksp,PetscReal a[],PetscInt na,PetscBool reset)
    1873: {

    1879:   PetscFree(ksp->res_hist_alloc);
    1880:   if (na != PETSC_DECIDE && na != PETSC_DEFAULT && a) {
    1881:     ksp->res_hist     = a;
    1882:     ksp->res_hist_max = na;
    1883:   } else {
    1884:     if (na != PETSC_DECIDE && na != PETSC_DEFAULT) ksp->res_hist_max = na;
    1885:     else                                           ksp->res_hist_max = 10000; /* like default ksp->max_it */
    1886:     PetscCalloc1(ksp->res_hist_max,&ksp->res_hist_alloc);

    1888:     ksp->res_hist = ksp->res_hist_alloc;
    1889:   }
    1890:   ksp->res_hist_len   = 0;
    1891:   ksp->res_hist_reset = reset;
    1892:   return(0);
    1893: }

    1897: /*@C
    1898:    KSPGetResidualHistory - Gets the array used to hold the residual history
    1899:    and the number of residuals it contains.

    1901:    Not Collective

    1903:    Input Parameter:
    1904: .  ksp - iterative context obtained from KSPCreate()

    1906:    Output Parameters:
    1907: +  a   - pointer to array to hold history (or NULL)
    1908: -  na  - number of used entries in a (or NULL)

    1910:    Level: advanced

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

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

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

    1923: .seealso: KSPGetResidualHistory()

    1925: @*/
    1926: PetscErrorCode  KSPGetResidualHistory(KSP ksp,PetscReal *a[],PetscInt *na)
    1927: {
    1930:   if (a) *a = ksp->res_hist;
    1931:   if (na) *na = ksp->res_hist_len;
    1932:   return(0);
    1933: }

    1937: /*@C
    1938:    KSPSetConvergenceTest - Sets the function to be used to determine
    1939:    convergence.

    1941:    Logically Collective on KSP

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

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

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

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

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

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

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

    1973:    Level: advanced

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

    1977: .seealso: KSPConvergedDefault(), KSPGetConvergenceContext(), KSPSetTolerances()
    1978: @*/
    1979: PetscErrorCode  KSPSetConvergenceTest(KSP ksp,PetscErrorCode (*converge)(KSP,PetscInt,PetscReal,KSPConvergedReason*,void*),void *cctx,PetscErrorCode (*destroy)(void*))
    1980: {

    1985:   if (ksp->convergeddestroy) {
    1986:     (*ksp->convergeddestroy)(ksp->cnvP);
    1987:   }
    1988:   ksp->converged        = converge;
    1989:   ksp->convergeddestroy = destroy;
    1990:   ksp->cnvP             = (void*)cctx;
    1991:   return(0);
    1992: }

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

    2000:    Not Collective

    2002:    Input Parameter:
    2003: .  ksp - iterative context obtained from KSPCreate()

    2005:    Output Parameter:
    2006: .  ctx - monitoring context

    2008:    Level: advanced

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

    2012: .seealso: KSPConvergedDefault(), KSPSetConvergenceTest()
    2013: @*/
    2014: PetscErrorCode  KSPGetConvergenceContext(KSP ksp,void **ctx)
    2015: {
    2018:   *ctx = ksp->cnvP;
    2019:   return(0);
    2020: }

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

    2028:    Collective on KSP

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

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

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

    2056:    Level: advanced

    2058: .keywords: KSP, build, solution

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

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

    2076: /*@C
    2077:    KSPBuildResidual - Builds the residual in a vector provided.

    2079:    Collective on KSP

    2081:    Input Parameter:
    2082: .  ksp - iterative context obtained from KSPCreate()

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

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

    2094:    Level: advanced

    2096: .keywords: KSP, build, residual

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

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

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

    2127:    Logically Collective on KSP

    2129:    Input Parameter:
    2130: +  ksp - the KSP context
    2131: -  scale - PETSC_TRUE or PETSC_FALSE

    2133:    Options Database Key:
    2134: +   -ksp_diagonal_scale -
    2135: -   -ksp_diagonal_scale_fix - scale the matrix back AFTER the solve

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

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

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

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

    2152:    Level: intermediate

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

    2156: .seealso: KSPGetDiagonalScale(), KSPSetDiagonalScaleFix()
    2157: @*/
    2158: PetscErrorCode  KSPSetDiagonalScale(KSP ksp,PetscBool scale)
    2159: {
    2163:   ksp->dscale = scale;
    2164:   return(0);
    2165: }

    2169: /*@
    2170:    KSPGetDiagonalScale - Checks if KSP solver scales the matrix and
    2171:                           right hand side

    2173:    Not Collective

    2175:    Input Parameter:
    2176: .  ksp - the KSP context

    2178:    Output Parameter:
    2179: .  scale - PETSC_TRUE or PETSC_FALSE

    2181:    Notes:
    2182:     BE CAREFUL with this routine: it actually scales the matrix and right
    2183:     hand side that define the system. After the system is solved the matrix
    2184:     and right hand side remain scaled  unless you use KSPSetDiagonalScaleFix()

    2186:    Level: intermediate

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

    2190: .seealso: KSPSetDiagonalScale(), KSPSetDiagonalScaleFix()
    2191: @*/
    2192: PetscErrorCode  KSPGetDiagonalScale(KSP ksp,PetscBool  *scale)
    2193: {
    2197:   *scale = ksp->dscale;
    2198:   return(0);
    2199: }

    2203: /*@
    2204:    KSPSetDiagonalScaleFix - Tells KSP to diagonally scale the system
    2205:      back after solving.

    2207:    Logically Collective on KSP

    2209:    Input Parameter:
    2210: +  ksp - the KSP context
    2211: -  fix - PETSC_TRUE to scale back after the system solve, PETSC_FALSE to not
    2212:          rescale (default)

    2214:    Notes:
    2215:      Must be called after KSPSetDiagonalScale()

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

    2222:    Level: intermediate

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

    2226: .seealso: KSPGetDiagonalScale(), KSPSetDiagonalScale(), KSPGetDiagonalScaleFix()
    2227: @*/
    2228: PetscErrorCode  KSPSetDiagonalScaleFix(KSP ksp,PetscBool fix)
    2229: {
    2233:   ksp->dscalefix = fix;
    2234:   return(0);
    2235: }

    2239: /*@
    2240:    KSPGetDiagonalScaleFix - Determines if KSP diagonally scales the system
    2241:      back after solving.

    2243:    Not Collective

    2245:    Input Parameter:
    2246: .  ksp - the KSP context

    2248:    Output Parameter:
    2249: .  fix - PETSC_TRUE to scale back after the system solve, PETSC_FALSE to not
    2250:          rescale (default)

    2252:    Notes:
    2253:      Must be called after KSPSetDiagonalScale()

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

    2260:    Level: intermediate

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

    2264: .seealso: KSPGetDiagonalScale(), KSPSetDiagonalScale(), KSPSetDiagonalScaleFix()
    2265: @*/
    2266: PetscErrorCode  KSPGetDiagonalScaleFix(KSP ksp,PetscBool  *fix)
    2267: {
    2271:   *fix = ksp->dscalefix;
    2272:   return(0);
    2273: }

    2277: /*@C
    2278:    KSPSetComputeOperators - set routine to compute the linear operators

    2280:    Logically Collective

    2282:    Input Arguments:
    2283: +  ksp - the KSP context
    2284: .  func - function to compute the operators
    2285: -  ctx - optional context

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

    2290: +  ksp - the KSP context
    2291: .  A - the linear operator
    2292: .  B - preconditioning matrix
    2293: -  ctx - optional user-provided context

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

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

    2300:    Level: beginner

    2302: .seealso: KSPSetOperators(), KSPSetComputeRHS(), DMKSPSetComputeOperators(), KSPSetComputeInitialGuess()
    2303: @*/
    2304: PetscErrorCode KSPSetComputeOperators(KSP ksp,PetscErrorCode (*func)(KSP,Mat,Mat,void*),void *ctx)
    2305: {
    2307:   DM             dm;

    2311:   KSPGetDM(ksp,&dm);
    2312:   DMKSPSetComputeOperators(dm,func,ctx);
    2313:   if (ksp->setupstage == KSP_SETUP_NEWRHS) ksp->setupstage = KSP_SETUP_NEWMATRIX;
    2314:   return(0);
    2315: }

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

    2322:    Logically Collective

    2324:    Input Arguments:
    2325: +  ksp - the KSP context
    2326: .  func - function to compute the right hand side
    2327: -  ctx - optional context

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

    2332: +  ksp - the KSP context
    2333: .  b - right hand side of linear system
    2334: -  ctx - optional user-provided context

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

    2338:    Level: beginner

    2340: .seealso: KSPSolve(), DMKSPSetComputeRHS(), KSPSetComputeOperators()
    2341: @*/
    2342: PetscErrorCode KSPSetComputeRHS(KSP ksp,PetscErrorCode (*func)(KSP,Vec,void*),void *ctx)
    2343: {
    2345:   DM             dm;

    2349:   KSPGetDM(ksp,&dm);
    2350:   DMKSPSetComputeRHS(dm,func,ctx);
    2351:   return(0);
    2352: }

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

    2359:    Logically Collective

    2361:    Input Arguments:
    2362: +  ksp - the KSP context
    2363: .  func - function to compute the initial guess
    2364: -  ctx - optional context

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

    2369: +  ksp - the KSP context
    2370: .  x - solution vector
    2371: -  ctx - optional user-provided context

    2373:    Level: beginner

    2375: .seealso: KSPSolve(), KSPSetComputeRHS(), KSPSetComputeOperators(), DMKSPSetComputeInitialGuess()
    2376: @*/
    2377: PetscErrorCode KSPSetComputeInitialGuess(KSP ksp,PetscErrorCode (*func)(KSP,Vec,void*),void *ctx)
    2378: {
    2380:   DM             dm;

    2384:   KSPGetDM(ksp,&dm);
    2385:   DMKSPSetComputeInitialGuess(dm,func,ctx);
    2386:   return(0);
    2387: }