Actual source code: itcreate.c

  1: /*
  2:      The basic KSP routines, Create, View etc. are here.
  3: */
  4: #include <petsc/private/kspimpl.h>

  6: /* Logging support */
  7: PetscClassId  KSP_CLASSID;
  8: PetscClassId  DMKSP_CLASSID;
  9: PetscClassId  KSPGUESS_CLASSID;
 10: PetscLogEvent KSP_GMRESOrthogonalization, KSP_SetUp, KSP_Solve, KSP_SolveTranspose, KSP_MatSolve;

 12: /*
 13:    Contains the list of registered KSP routines
 14: */
 15: PetscFunctionList KSPList              = NULL;
 16: PetscBool         KSPRegisterAllCalled = PETSC_FALSE;

 18: /*
 19:    Contains the list of registered KSP monitors
 20: */
 21: PetscFunctionList KSPMonitorList              = NULL;
 22: PetscFunctionList KSPMonitorCreateList        = NULL;
 23: PetscFunctionList KSPMonitorDestroyList       = NULL;
 24: PetscBool         KSPMonitorRegisterAllCalled = PETSC_FALSE;

 26: /*@C
 27:   KSPLoad - Loads a KSP that has been stored in binary  with KSPView().

 29:   Collective on viewer

 31:   Input Parameters:
 32: + newdm - the newly loaded KSP, this needs to have been created with KSPCreate() or
 33:            some related function before a call to KSPLoad().
 34: - viewer - binary file viewer, obtained from PetscViewerBinaryOpen()

 36:    Level: intermediate

 38:   Notes:
 39:    The type is determined by the data in the file, any type set into the KSP before this call is ignored.

 41:   Notes for advanced users:
 42:   Most users should not need to know the details of the binary storage
 43:   format, since KSPLoad() and KSPView() completely hide these details.
 44:   But for anyone who's interested, the standard binary matrix storage
 45:   format is
 46: .vb
 47:      has not yet been determined
 48: .ve

 50: .seealso: PetscViewerBinaryOpen(), KSPView(), MatLoad(), VecLoad()
 51: @*/
 52: PetscErrorCode  KSPLoad(KSP newdm, PetscViewer viewer)
 53: {
 54:   PetscBool      isbinary;
 55:   PetscInt       classid;
 56:   char           type[256];
 57:   PC             pc;

 61:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);

 64:   PetscViewerBinaryRead(viewer,&classid,1,NULL,PETSC_INT);
 66:   PetscViewerBinaryRead(viewer,type,256,NULL,PETSC_CHAR);
 67:   KSPSetType(newdm, type);
 68:   if (newdm->ops->load) (*newdm->ops->load)(newdm,viewer);
 69:   KSPGetPC(newdm,&pc);
 70:   PCLoad(pc,viewer);
 71:   return 0;
 72: }

 74: #include <petscdraw.h>
 75: #if defined(PETSC_HAVE_SAWS)
 76: #include <petscviewersaws.h>
 77: #endif
 78: /*@C
 79:    KSPView - Prints the KSP data structure.

 81:    Collective on ksp

 83:    Input Parameters:
 84: +  ksp - the Krylov space context
 85: -  viewer - visualization context

 87:    Options Database Keys:
 88: .  -ksp_view - print the KSP data structure at the end of a KSPSolve call

 90:    Note:
 91:    The available visualization contexts include
 92: +     PETSC_VIEWER_STDOUT_SELF - standard output (default)
 93: -     PETSC_VIEWER_STDOUT_WORLD - synchronized standard
 94:          output where only the first processor opens
 95:          the file.  All other processors send their
 96:          data to the first processor to print.

 98:    The available formats include
 99: +     PETSC_VIEWER_DEFAULT - standard output (default)
100: -     PETSC_VIEWER_ASCII_INFO_DETAIL - more verbose output for PCBJACOBI and PCASM

102:    The user can open an alternative visualization context with
103:    PetscViewerASCIIOpen() - output to a specified file.

105:   In the debugger you can do "call KSPView(ksp,0)" to display the KSP. (The same holds for any PETSc object viewer).

107:    Level: beginner

109: .seealso: PCView(), PetscViewerASCIIOpen()
110: @*/
111: PetscErrorCode  KSPView(KSP ksp,PetscViewer viewer)
112: {
113:   PetscBool      iascii,isbinary,isdraw,isstring;
114: #if defined(PETSC_HAVE_SAWS)
115:   PetscBool      issaws;
116: #endif

119:   if (!viewer) {
120:     PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)ksp),&viewer);
121:   }

125:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
126:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);
127:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERDRAW,&isdraw);
128:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSTRING,&isstring);
129: #if defined(PETSC_HAVE_SAWS)
130:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSAWS,&issaws);
131: #endif
132:   if (iascii) {
133:     PetscObjectPrintClassNamePrefixType((PetscObject)ksp,viewer);
134:     if (ksp->ops->view) {
135:       PetscViewerASCIIPushTab(viewer);
136:       (*ksp->ops->view)(ksp,viewer);
137:       PetscViewerASCIIPopTab(viewer);
138:     }
139:     if (ksp->guess_zero) {
140:       PetscViewerASCIIPrintf(viewer,"  maximum iterations=%D, initial guess is zero\n",ksp->max_it);
141:     } else {
142:       PetscViewerASCIIPrintf(viewer,"  maximum iterations=%D, nonzero initial guess\n", ksp->max_it);
143:     }
144:     if (ksp->guess_knoll) PetscViewerASCIIPrintf(viewer,"  using preconditioner applied to right hand side for initial guess\n");
145:     PetscViewerASCIIPrintf(viewer,"  tolerances:  relative=%g, absolute=%g, divergence=%g\n",(double)ksp->rtol,(double)ksp->abstol,(double)ksp->divtol);
146:     if (ksp->pc_side == PC_RIGHT) {
147:       PetscViewerASCIIPrintf(viewer,"  right preconditioning\n");
148:     } else if (ksp->pc_side == PC_SYMMETRIC) {
149:       PetscViewerASCIIPrintf(viewer,"  symmetric preconditioning\n");
150:     } else {
151:       PetscViewerASCIIPrintf(viewer,"  left preconditioning\n");
152:     }
153:     if (ksp->guess) {
154:       PetscViewerASCIIPushTab(viewer);
155:       KSPGuessView(ksp->guess,viewer);
156:       PetscViewerASCIIPopTab(viewer);
157:     }
158:     if (ksp->dscale) PetscViewerASCIIPrintf(viewer,"  diagonally scaled system\n");
159:     PetscViewerASCIIPrintf(viewer,"  using %s norm type for convergence test\n",KSPNormTypes[ksp->normtype]);
160:   } else if (isbinary) {
161:     PetscInt    classid = KSP_FILE_CLASSID;
162:     MPI_Comm    comm;
163:     PetscMPIInt rank;
164:     char        type[256];

166:     PetscObjectGetComm((PetscObject)ksp,&comm);
167:     MPI_Comm_rank(comm,&rank);
168:     if (rank == 0) {
169:       PetscViewerBinaryWrite(viewer,&classid,1,PETSC_INT);
170:       PetscStrncpy(type,((PetscObject)ksp)->type_name,256);
171:       PetscViewerBinaryWrite(viewer,type,256,PETSC_CHAR);
172:     }
173:     if (ksp->ops->view) {
174:       (*ksp->ops->view)(ksp,viewer);
175:     }
176:   } else if (isstring) {
177:     const char *type;
178:     KSPGetType(ksp,&type);
179:     PetscViewerStringSPrintf(viewer," KSPType: %-7.7s",type);
180:     if (ksp->ops->view) (*ksp->ops->view)(ksp,viewer);
181:   } else if (isdraw) {
182:     PetscDraw draw;
183:     char      str[36];
184:     PetscReal x,y,bottom,h;
185:     PetscBool flg;

187:     PetscViewerDrawGetDraw(viewer,0,&draw);
188:     PetscDrawGetCurrentPoint(draw,&x,&y);
189:     PetscObjectTypeCompare((PetscObject)ksp,KSPPREONLY,&flg);
190:     if (!flg) {
191:       PetscStrncpy(str,"KSP: ",sizeof(str));
192:       PetscStrlcat(str,((PetscObject)ksp)->type_name,sizeof(str));
193:       PetscDrawStringBoxed(draw,x,y,PETSC_DRAW_RED,PETSC_DRAW_BLACK,str,NULL,&h);
194:       bottom = y - h;
195:     } else {
196:       bottom = y;
197:     }
198:     PetscDrawPushCurrentPoint(draw,x,bottom);
199: #if defined(PETSC_HAVE_SAWS)
200:   } else if (issaws) {
201:     PetscMPIInt rank;
202:     const char  *name;

204:     PetscObjectGetName((PetscObject)ksp,&name);
205:     MPI_Comm_rank(PETSC_COMM_WORLD,&rank);
206:     if (!((PetscObject)ksp)->amsmem && rank == 0) {
207:       char       dir[1024];

209:       PetscObjectViewSAWs((PetscObject)ksp,viewer);
210:       PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/its",name);
211:       PetscStackCallSAWs(SAWs_Register,(dir,&ksp->its,1,SAWs_READ,SAWs_INT));
212:       if (!ksp->res_hist) {
213:         KSPSetResidualHistory(ksp,NULL,PETSC_DECIDE,PETSC_TRUE);
214:       }
215:       PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/res_hist",name);
216:       PetscStackCallSAWs(SAWs_Register,(dir,ksp->res_hist,10,SAWs_READ,SAWs_DOUBLE));
217:     }
218: #endif
219:   } else if (ksp->ops->view) {
220:     (*ksp->ops->view)(ksp,viewer);
221:   }
222:   if (ksp->pc) {
223:     PCView(ksp->pc,viewer);
224:   }
225:   if (isdraw) {
226:     PetscDraw draw;
227:     PetscViewerDrawGetDraw(viewer,0,&draw);
228:     PetscDrawPopCurrentPoint(draw);
229:   }
230:   return 0;
231: }

233: /*@C
234:    KSPViewFromOptions - View from Options

236:    Collective on KSP

238:    Input Parameters:
239: +  A - Krylov solver context
240: .  obj - Optional object
241: -  name - command line option

243:    Level: intermediate
244: .seealso:  KSP, KSPView, PetscObjectViewFromOptions(), KSPCreate()
245: @*/
246: PetscErrorCode  KSPViewFromOptions(KSP A,PetscObject obj,const char name[])
247: {
249:   PetscObjectViewFromOptions((PetscObject)A,obj,name);
250:   return 0;
251: }

253: /*@
254:    KSPSetNormType - Sets the norm that is used for convergence testing.

256:    Logically Collective on ksp

258:    Input Parameters:
259: +  ksp - Krylov solver context
260: -  normtype - one of
261: $   KSP_NORM_NONE - skips computing the norm, this should generally only be used if you are using
262: $                 the Krylov method as a smoother with a fixed small number of iterations.
263: $                 Implicitly sets KSPConvergedSkip() as KSP convergence test.
264: $                 Note that certain algorithms such as KSPGMRES ALWAYS require the norm calculation,
265: $                 for these methods the norms are still computed, they are just not used in
266: $                 the convergence test.
267: $   KSP_NORM_PRECONDITIONED - the default for left preconditioned solves, uses the l2 norm
268: $                 of the preconditioned residual P^{-1}(b - A x)
269: $   KSP_NORM_UNPRECONDITIONED - uses the l2 norm of the true b - Ax residual.
270: $   KSP_NORM_NATURAL - supported  by KSPCG, KSPCR, KSPCGNE, KSPCGS

272:    Options Database Key:
273: .   -ksp_norm_type <none,preconditioned,unpreconditioned,natural> - set KSP norm type

275:    Notes:
276:    Not all combinations of preconditioner side (see KSPSetPCSide()) and norm type are supported by all Krylov methods.
277:    If only one is set, PETSc tries to automatically change the other to find a compatible pair.  If no such combination
278:    is supported, PETSc will generate an error.

280:    Developer Notes:
281:    Supported combinations of norm and preconditioner side are set using KSPSetSupportedNorm().

283:    Level: advanced

285: .seealso: KSPSetUp(), KSPSolve(), KSPDestroy(), KSPConvergedSkip(), KSPSetCheckNormIteration(), KSPSetPCSide(), KSPGetPCSide(), KSPNormType
286: @*/
287: PetscErrorCode  KSPSetNormType(KSP ksp,KSPNormType normtype)
288: {
291:   ksp->normtype = ksp->normtype_set = normtype;
292:   return 0;
293: }

295: /*@
296:    KSPSetCheckNormIteration - Sets the first iteration at which the norm of the residual will be
297:      computed and used in the convergence test.

299:    Logically Collective on ksp

301:    Input Parameters:
302: +  ksp - Krylov solver context
303: -  it  - use -1 to check at all iterations

305:    Notes:
306:    Currently only works with KSPCG, KSPBCGS and KSPIBCGS

308:    Use KSPSetNormType(ksp,KSP_NORM_NONE) to never check the norm

310:    On steps where the norm is not computed, the previous norm is still in the variable, so if you run with, for example,
311:     -ksp_monitor the residual norm will appear to be unchanged for several iterations (though it is not really unchanged).
312:    Level: advanced

314: .seealso: KSPSetUp(), KSPSolve(), KSPDestroy(), KSPConvergedSkip(), KSPSetNormType()
315: @*/
316: PetscErrorCode  KSPSetCheckNormIteration(KSP ksp,PetscInt it)
317: {
320:   ksp->chknorm = it;
321:   return 0;
322: }

324: /*@
325:    KSPSetLagNorm - Lags the residual norm calculation so that it is computed as part of the MPI_Allreduce() for
326:    computing the inner products for the next iteration.  This can reduce communication costs at the expense of doing
327:    one additional iteration.

329:    Logically Collective on ksp

331:    Input Parameters:
332: +  ksp - Krylov solver context
333: -  flg - PETSC_TRUE or PETSC_FALSE

335:    Options Database Keys:
336: .  -ksp_lag_norm - lag the calculated residual norm

338:    Notes:
339:    Currently only works with KSPIBCGS.

341:    Use KSPSetNormType(ksp,KSP_NORM_NONE) to never check the norm

343:    If you lag the norm and run with, for example, -ksp_monitor, the residual norm reported will be the lagged one.
344:    Level: advanced

346: .seealso: KSPSetUp(), KSPSolve(), KSPDestroy(), KSPConvergedSkip(), KSPSetNormType(), KSPSetCheckNormIteration()
347: @*/
348: PetscErrorCode  KSPSetLagNorm(KSP ksp,PetscBool flg)
349: {
352:   ksp->lagnorm = flg;
353:   return 0;
354: }

356: /*@
357:    KSPSetSupportedNorm - Sets a norm and preconditioner side supported by a KSP

359:    Logically Collective

361:    Input Parameters:
362: +  ksp - Krylov method
363: .  normtype - supported norm type
364: .  pcside - preconditioner side that can be used with this norm
365: -  priority - positive integer preference for this combination; larger values have higher priority

367:    Level: developer

369:    Notes:
370:    This function should be called from the implementation files KSPCreate_XXX() to declare
371:    which norms and preconditioner sides are supported. Users should not need to call this
372:    function.

374: .seealso: KSPSetNormType(), KSPSetPCSide()
375: @*/
376: PetscErrorCode KSPSetSupportedNorm(KSP ksp,KSPNormType normtype,PCSide pcside,PetscInt priority)
377: {
379:   ksp->normsupporttable[normtype][pcside] = priority;
380:   return 0;
381: }

383: PetscErrorCode KSPNormSupportTableReset_Private(KSP ksp)
384: {
385:   PetscMemzero(ksp->normsupporttable,sizeof(ksp->normsupporttable));
386:   ksp->pc_side  = ksp->pc_side_set;
387:   ksp->normtype = ksp->normtype_set;
388:   return 0;
389: }

391: PetscErrorCode KSPSetUpNorms_Private(KSP ksp,PetscBool errorifnotsupported,KSPNormType *normtype,PCSide *pcside)
392: {
393:   PetscInt i,j,best,ibest = 0,jbest = 0;

395:   best = 0;
396:   for (i=0; i<KSP_NORM_MAX; i++) {
397:     for (j=0; j<PC_SIDE_MAX; j++) {
398:       if ((ksp->normtype == KSP_NORM_DEFAULT || ksp->normtype == i) && (ksp->pc_side == PC_SIDE_DEFAULT || ksp->pc_side == j) && (ksp->normsupporttable[i][j] > best)) {
399:         best  = ksp->normsupporttable[i][j];
400:         ibest = i;
401:         jbest = j;
402:       }
403:     }
404:   }
405:   if (best < 1 && errorifnotsupported) {
409:     SETERRQ(PetscObjectComm((PetscObject)ksp),PETSC_ERR_SUP,"KSP %s does not support %s with %s",((PetscObject)ksp)->type_name,KSPNormTypes[ksp->normtype],PCSides[ksp->pc_side]);
410:   }
411:   if (normtype) *normtype = (KSPNormType)ibest;
412:   if (pcside)   *pcside   = (PCSide)jbest;
413:   return 0;
414: }

416: /*@
417:    KSPGetNormType - Gets the norm that is used for convergence testing.

419:    Not Collective

421:    Input Parameter:
422: .  ksp - Krylov solver context

424:    Output Parameter:
425: .  normtype - norm that is used for convergence testing

427:    Level: advanced

429: .seealso: KSPNormType, KSPSetNormType(), KSPConvergedSkip()
430: @*/
431: PetscErrorCode  KSPGetNormType(KSP ksp, KSPNormType *normtype)
432: {
435:   KSPSetUpNorms_Private(ksp,PETSC_TRUE,&ksp->normtype,&ksp->pc_side);
436:   *normtype = ksp->normtype;
437:   return 0;
438: }

440: #if defined(PETSC_HAVE_SAWS)
441: #include <petscviewersaws.h>
442: #endif

444: /*@
445:    KSPSetOperators - Sets the matrix associated with the linear system
446:    and a (possibly) different one associated with the preconditioner.

448:    Collective on ksp

450:    Input Parameters:
451: +  ksp - the KSP context
452: .  Amat - the matrix that defines the linear system
453: -  Pmat - the matrix to be used in constructing the preconditioner, usually the same as Amat.

455:    Notes:

457:     If you know the operator Amat has a null space you can use MatSetNullSpace() and MatSetTransposeNullSpace() to supply the null
458:     space to Amat and the KSP solvers will automatically use that null space as needed during the solution process.

460:     All future calls to KSPSetOperators() must use the same size matrices!

462:     Passing a NULL for Amat or Pmat removes the matrix that is currently used.

464:     If you wish to replace either Amat or Pmat but leave the other one untouched then
465:     first call KSPGetOperators() to get the one you wish to keep, call PetscObjectReference()
466:     on it and then pass it back in in your call to KSPSetOperators().

468:     Level: beginner

470:    Alternative usage: If the operators have NOT been set with KSP/PCSetOperators() then the operators
471:       are created in PC and returned to the user. In this case, if both operators
472:       mat and pmat are requested, two DIFFERENT operators will be returned. If
473:       only one is requested both operators in the PC will be the same (i.e. as
474:       if one had called KSP/PCSetOperators() with the same argument for both Mats).
475:       The user must set the sizes of the returned matrices and their type etc just
476:       as if the user created them with MatCreate(). For example,

478: $         KSP/PCGetOperators(ksp/pc,&mat,NULL); is equivalent to
479: $           set size, type, etc of mat

481: $         MatCreate(comm,&mat);
482: $         KSP/PCSetOperators(ksp/pc,mat,mat);
483: $         PetscObjectDereference((PetscObject)mat);
484: $           set size, type, etc of mat

486:      and

488: $         KSP/PCGetOperators(ksp/pc,&mat,&pmat); is equivalent to
489: $           set size, type, etc of mat and pmat

491: $         MatCreate(comm,&mat);
492: $         MatCreate(comm,&pmat);
493: $         KSP/PCSetOperators(ksp/pc,mat,pmat);
494: $         PetscObjectDereference((PetscObject)mat);
495: $         PetscObjectDereference((PetscObject)pmat);
496: $           set size, type, etc of mat and pmat

498:     The rational for this support is so that when creating a TS, SNES, or KSP the hierarchy
499:     of underlying objects (i.e. SNES, KSP, PC, Mat) and their livespans can be completely
500:     managed by the top most level object (i.e. the TS, SNES, or KSP). Another way to look
501:     at this is when you create a SNES you do not NEED to create a KSP and attach it to
502:     the SNES object (the SNES object manages it for you). Similarly when you create a KSP
503:     you do not need to attach a PC to it (the KSP object manages the PC object for you).
504:     Thus, why should YOU have to create the Mat and attach it to the SNES/KSP/PC, when
505:     it can be created for you?

507: .seealso: KSPSolve(), KSPGetPC(), PCGetOperators(), PCSetOperators(), KSPGetOperators(), KSPSetComputeOperators(), KSPSetComputeInitialGuess(), KSPSetComputeRHS()
508: @*/
509: PetscErrorCode  KSPSetOperators(KSP ksp,Mat Amat,Mat Pmat)
510: {
516:   if (!ksp->pc) KSPGetPC(ksp,&ksp->pc);
517:   PCSetOperators(ksp->pc,Amat,Pmat);
518:   if (ksp->setupstage == KSP_SETUP_NEWRHS) ksp->setupstage = KSP_SETUP_NEWMATRIX;  /* so that next solve call will call PCSetUp() on new matrix */
519:   return 0;
520: }

522: /*@
523:    KSPGetOperators - Gets the matrix associated with the linear system
524:    and a (possibly) different one associated with the preconditioner.

526:    Collective on ksp

528:    Input Parameter:
529: .  ksp - the KSP context

531:    Output Parameters:
532: +  Amat - the matrix that defines the linear system
533: -  Pmat - the matrix to be used in constructing the preconditioner, usually the same as Amat.

535:     Level: intermediate

537:    Notes:
538:     DOES NOT increase the reference counts of the matrix, so you should NOT destroy them.

540: .seealso: KSPSolve(), KSPGetPC(), PCGetOperators(), PCSetOperators(), KSPSetOperators(), KSPGetOperatorsSet()
541: @*/
542: PetscErrorCode  KSPGetOperators(KSP ksp,Mat *Amat,Mat *Pmat)
543: {
545:   if (!ksp->pc) KSPGetPC(ksp,&ksp->pc);
546:   PCGetOperators(ksp->pc,Amat,Pmat);
547:   return 0;
548: }

550: /*@C
551:    KSPGetOperatorsSet - Determines if the matrix associated with the linear system and
552:    possibly a different one associated with the preconditioner have been set in the KSP.

554:    Not collective, though the results on all processes should be the same

556:    Input Parameter:
557: .  pc - the KSP context

559:    Output Parameters:
560: +  mat - the matrix associated with the linear system was set
561: -  pmat - matrix associated with the preconditioner was set, usually the same

563:    Level: intermediate

565: .seealso: PCSetOperators(), KSPGetOperators(), KSPSetOperators(), PCGetOperators(), PCGetOperatorsSet()
566: @*/
567: PetscErrorCode  KSPGetOperatorsSet(KSP ksp,PetscBool  *mat,PetscBool  *pmat)
568: {
570:   if (!ksp->pc) KSPGetPC(ksp,&ksp->pc);
571:   PCGetOperatorsSet(ksp->pc,mat,pmat);
572:   return 0;
573: }

575: /*@C
576:    KSPSetPreSolve - Sets a function that is called before every KSPSolve() is started

578:    Logically Collective on ksp

580:    Input Parameters:
581: +   ksp - the solver object
582: .   presolve - the function to call before the solve
583: -   prectx - any context needed by the function

585:    Calling sequence of presolve:
586: $  func(KSP ksp,Vec rhs,Vec x,void *ctx)

588: +  ksp - the KSP context
589: .  rhs - the right-hand side vector
590: .  x - the solution vector
591: -  ctx - optional user-provided context

593:    Level: developer

595: .seealso: KSPSetUp(), KSPSolve(), KSPDestroy(), KSP, KSPSetPostSolve()
596: @*/
597: PetscErrorCode  KSPSetPreSolve(KSP ksp,PetscErrorCode (*presolve)(KSP,Vec,Vec,void*),void *prectx)
598: {
600:   ksp->presolve = presolve;
601:   ksp->prectx   = prectx;
602:   return 0;
603: }

605: /*@C
606:    KSPSetPostSolve - Sets a function that is called after every KSPSolve() completes (whether it converges or not)

608:    Logically Collective on ksp

610:    Input Parameters:
611: +   ksp - the solver object
612: .   postsolve - the function to call after the solve
613: -   postctx - any context needed by the function

615:    Level: developer

617:    Calling sequence of postsolve:
618: $  func(KSP ksp,Vec rhs,Vec x,void *ctx)

620: +  ksp - the KSP context
621: .  rhs - the right-hand side vector
622: .  x - the solution vector
623: -  ctx - optional user-provided context

625: .seealso: KSPSetUp(), KSPSolve(), KSPDestroy(), KSP, KSPSetPreSolve()
626: @*/
627: PetscErrorCode  KSPSetPostSolve(KSP ksp,PetscErrorCode (*postsolve)(KSP,Vec,Vec,void*),void *postctx)
628: {
630:   ksp->postsolve = postsolve;
631:   ksp->postctx   = postctx;
632:   return 0;
633: }

635: /*@
636:    KSPCreate - Creates the default KSP context.

638:    Collective

640:    Input Parameter:
641: .  comm - MPI communicator

643:    Output Parameter:
644: .  ksp - location to put the KSP context

646:    Notes:
647:    The default KSP type is GMRES with a restart of 30, using modified Gram-Schmidt
648:    orthogonalization.

650:    Level: beginner

652: .seealso: KSPSetUp(), KSPSolve(), KSPDestroy(), KSP
653: @*/
654: PetscErrorCode  KSPCreate(MPI_Comm comm,KSP *inksp)
655: {
656:   KSP            ksp;
657:   void           *ctx;

660:   *inksp = NULL;
661:   KSPInitializePackage();

663:   PetscHeaderCreate(ksp,KSP_CLASSID,"KSP","Krylov Method","KSP",comm,KSPDestroy,KSPView);

665:   ksp->max_it  = 10000;
666:   ksp->pc_side = ksp->pc_side_set = PC_SIDE_DEFAULT;
667:   ksp->rtol    = 1.e-5;
668: #if defined(PETSC_USE_REAL_SINGLE)
669:   ksp->abstol  = 1.e-25;
670: #else
671:   ksp->abstol  = 1.e-50;
672: #endif
673:   ksp->divtol  = 1.e4;

675:   ksp->chknorm        = -1;
676:   ksp->normtype       = ksp->normtype_set = KSP_NORM_DEFAULT;
677:   ksp->rnorm          = 0.0;
678:   ksp->its            = 0;
679:   ksp->guess_zero     = PETSC_TRUE;
680:   ksp->calc_sings     = PETSC_FALSE;
681:   ksp->res_hist       = NULL;
682:   ksp->res_hist_alloc = NULL;
683:   ksp->res_hist_len   = 0;
684:   ksp->res_hist_max   = 0;
685:   ksp->res_hist_reset = PETSC_TRUE;
686:   ksp->err_hist       = NULL;
687:   ksp->err_hist_alloc = NULL;
688:   ksp->err_hist_len   = 0;
689:   ksp->err_hist_max   = 0;
690:   ksp->err_hist_reset = PETSC_TRUE;
691:   ksp->numbermonitors = 0;
692:   ksp->numberreasonviews = 0;
693:   ksp->setfromoptionscalled = 0;
694:   ksp->nmax = PETSC_DECIDE;

696:   KSPConvergedDefaultCreate(&ctx);
697:   KSPSetConvergenceTest(ksp,KSPConvergedDefault,ctx,KSPConvergedDefaultDestroy);
698:   ksp->ops->buildsolution = KSPBuildSolutionDefault;
699:   ksp->ops->buildresidual = KSPBuildResidualDefault;

701:   ksp->vec_sol    = NULL;
702:   ksp->vec_rhs    = NULL;
703:   ksp->pc         = NULL;
704:   ksp->data       = NULL;
705:   ksp->nwork      = 0;
706:   ksp->work       = NULL;
707:   ksp->reason     = KSP_CONVERGED_ITERATING;
708:   ksp->setupstage = KSP_SETUP_NEW;

710:   KSPNormSupportTableReset_Private(ksp);

712:   *inksp = ksp;
713:   return 0;
714: }

716: /*@C
717:    KSPSetType - Builds KSP for a particular solver.

719:    Logically Collective on ksp

721:    Input Parameters:
722: +  ksp      - the Krylov space context
723: -  type - a known method

725:    Options Database Key:
726: .  -ksp_type  <method> - Sets the method; use -help for a list
727:     of available methods (for instance, cg or gmres)

729:    Notes:
730:    See "petsc/include/petscksp.h" for available methods (for instance,
731:    KSPCG or KSPGMRES).

733:   Normally, it is best to use the KSPSetFromOptions() command and
734:   then set the KSP type from the options database rather than by using
735:   this routine.  Using the options database provides the user with
736:   maximum flexibility in evaluating the many different Krylov methods.
737:   The KSPSetType() routine is provided for those situations where it
738:   is necessary to set the iterative solver independently of the command
739:   line or options database.  This might be the case, for example, when
740:   the choice of iterative solver changes during the execution of the
741:   program, and the user's application is taking responsibility for
742:   choosing the appropriate method.  In other words, this routine is
743:   not for beginners.

745:   Level: intermediate

747:   Developer Note: KSPRegister() is used to add Krylov types to KSPList from which they
748:   are accessed by KSPSetType().

750: .seealso: PCSetType(), KSPType, KSPRegister(), KSPCreate()

752: @*/
753: PetscErrorCode  KSPSetType(KSP ksp, KSPType type)
754: {
755:   PetscBool      match;
756:   PetscErrorCode (*r)(KSP);


761:   PetscObjectTypeCompare((PetscObject)ksp,type,&match);
762:   if (match) return 0;

764:   PetscFunctionListFind(KSPList,type,&r);
766:   /* Destroy the previous private KSP context */
767:   if (ksp->ops->destroy) {
768:     (*ksp->ops->destroy)(ksp);
769:     ksp->ops->destroy = NULL;
770:   }
771:   /* Reinitialize function pointers in KSPOps structure */
772:   PetscMemzero(ksp->ops,sizeof(struct _KSPOps));
773:   ksp->ops->buildsolution = KSPBuildSolutionDefault;
774:   ksp->ops->buildresidual = KSPBuildResidualDefault;
775:   KSPNormSupportTableReset_Private(ksp);
776:   ksp->setupnewmatrix     = PETSC_FALSE; // restore default (setup not called in case of new matrix)
777:   /* Call the KSPCreate_XXX routine for this particular Krylov solver */
778:   ksp->setupstage = KSP_SETUP_NEW;
779:   (*r)(ksp);
780:   PetscObjectChangeTypeName((PetscObject)ksp,type);
781:   return 0;
782: }

784: /*@C
785:    KSPGetType - Gets the KSP type as a string from the KSP object.

787:    Not Collective

789:    Input Parameter:
790: .  ksp - Krylov context

792:    Output Parameter:
793: .  name - name of KSP method

795:    Level: intermediate

797: .seealso: KSPSetType()
798: @*/
799: PetscErrorCode  KSPGetType(KSP ksp,KSPType *type)
800: {
803:   *type = ((PetscObject)ksp)->type_name;
804:   return 0;
805: }

807: /*@C
808:   KSPRegister -  Adds a method to the Krylov subspace solver package.

810:    Not Collective

812:    Input Parameters:
813: +  name_solver - name of a new user-defined solver
814: -  routine_create - routine to create method context

816:    Notes:
817:    KSPRegister() may be called multiple times to add several user-defined solvers.

819:    Sample usage:
820: .vb
821:    KSPRegister("my_solver",MySolverCreate);
822: .ve

824:    Then, your solver can be chosen with the procedural interface via
825: $     KSPSetType(ksp,"my_solver")
826:    or at runtime via the option
827: $     -ksp_type my_solver

829:    Level: advanced

831: .seealso: KSPRegisterAll()
832: @*/
833: PetscErrorCode  KSPRegister(const char sname[],PetscErrorCode (*function)(KSP))
834: {
835:   KSPInitializePackage();
836:   PetscFunctionListAdd(&KSPList,sname,function);
837:   return 0;
838: }

840: PetscErrorCode KSPMonitorMakeKey_Internal(const char name[], PetscViewerType vtype, PetscViewerFormat format, char key[])
841: {
842:   PetscStrncpy(key, name, PETSC_MAX_PATH_LEN);
843:   PetscStrlcat(key, ":", PETSC_MAX_PATH_LEN);
844:   PetscStrlcat(key, vtype, PETSC_MAX_PATH_LEN);
845:   PetscStrlcat(key, ":", PETSC_MAX_PATH_LEN);
846:   PetscStrlcat(key, PetscViewerFormats[format], PETSC_MAX_PATH_LEN);
847:   return 0;
848: }

850: /*@C
851:   KSPMonitorRegister -  Adds Krylov subspace solver monitor routine.

853:   Not Collective

855:   Input Parameters:
856: + name    - name of a new monitor routine
857: . vtype   - A PetscViewerType for the output
858: . format  - A PetscViewerFormat for the output
859: . monitor - Monitor routine
860: . create  - Creation routine, or NULL
861: - destroy - Destruction routine, or NULL

863:   Notes:
864:   KSPMonitorRegister() may be called multiple times to add several user-defined monitors.

866:   Sample usage:
867: .vb
868:   KSPMonitorRegister("my_monitor",PETSCVIEWERASCII,PETSC_VIEWER_ASCII_INFO_DETAIL,MyMonitor,NULL,NULL);
869: .ve

871:   Then, your monitor can be chosen with the procedural interface via
872: $     KSPMonitorSetFromOptions(ksp,"-ksp_monitor_my_monitor","my_monitor",NULL)
873:   or at runtime via the option
874: $     -ksp_monitor_my_monitor

876:    Level: advanced

878: .seealso: KSPMonitorRegisterAll()
879: @*/
880: PetscErrorCode KSPMonitorRegister(const char name[], PetscViewerType vtype, PetscViewerFormat format,
881:                                   PetscErrorCode (*monitor)(KSP, PetscInt, PetscReal, PetscViewerAndFormat *),
882:                                   PetscErrorCode (*create)(PetscViewer, PetscViewerFormat, void *, PetscViewerAndFormat **),
883:                                   PetscErrorCode (*destroy)(PetscViewerAndFormat **))
884: {
885:   char           key[PETSC_MAX_PATH_LEN];

887:   KSPInitializePackage();
888:   KSPMonitorMakeKey_Internal(name, vtype, format, key);
889:   PetscFunctionListAdd(&KSPMonitorList, key, monitor);
890:   if (create)  PetscFunctionListAdd(&KSPMonitorCreateList,  key, create);
891:   if (destroy) PetscFunctionListAdd(&KSPMonitorDestroyList, key, destroy);
892:   return 0;
893: }