xref: /petsc/src/ksp/ksp/interface/itcreate.c (revision e4c66b91ec5ecaeb63ae1fb42799e6dff316a2f4)
1 
2 /*
3      The basic KSP routines, Create, View etc. are here.
4 */
5 #include <petsc/private/kspimpl.h>      /*I "petscksp.h" I*/
6 
7 /* Logging support */
8 PetscClassId  KSP_CLASSID;
9 PetscClassId  DMKSP_CLASSID;
10 PetscClassId  KSPGUESS_CLASSID;
11 PetscLogEvent KSP_GMRESOrthogonalization, KSP_SetUp, KSP_Solve;
12 
13 /*
14    Contains the list of registered KSP routines
15 */
16 PetscFunctionList KSPList              = 0;
17 PetscBool         KSPRegisterAllCalled = PETSC_FALSE;
18 
19 /*@C
20   KSPLoad - Loads a KSP that has been stored in binary  with KSPView().
21 
22   Collective on PetscViewer
23 
24   Input Parameters:
25 + newdm - the newly loaded KSP, this needs to have been created with KSPCreate() or
26            some related function before a call to KSPLoad().
27 - viewer - binary file viewer, obtained from PetscViewerBinaryOpen()
28 
29    Level: intermediate
30 
31   Notes:
32    The type is determined by the data in the file, any type set into the KSP before this call is ignored.
33 
34   Notes for advanced users:
35   Most users should not need to know the details of the binary storage
36   format, since KSPLoad() and KSPView() completely hide these details.
37   But for anyone who's interested, the standard binary matrix storage
38   format is
39 .vb
40      has not yet been determined
41 .ve
42 
43 .seealso: PetscViewerBinaryOpen(), KSPView(), MatLoad(), VecLoad()
44 @*/
45 PetscErrorCode  KSPLoad(KSP newdm, PetscViewer viewer)
46 {
47   PetscErrorCode ierr;
48   PetscBool      isbinary;
49   PetscInt       classid;
50   char           type[256];
51   PC             pc;
52 
53   PetscFunctionBegin;
54   PetscValidHeaderSpecific(newdm,KSP_CLASSID,1);
55   PetscValidHeaderSpecific(viewer,PETSC_VIEWER_CLASSID,2);
56   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);CHKERRQ(ierr);
57   if (!isbinary) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Invalid viewer; open viewer with PetscViewerBinaryOpen()");
58 
59   ierr = PetscViewerBinaryRead(viewer,&classid,1,NULL,PETSC_INT);CHKERRQ(ierr);
60   if (classid != KSP_FILE_CLASSID) SETERRQ(PetscObjectComm((PetscObject)newdm),PETSC_ERR_ARG_WRONG,"Not KSP next in file");
61   ierr = PetscViewerBinaryRead(viewer,type,256,NULL,PETSC_CHAR);CHKERRQ(ierr);
62   ierr = KSPSetType(newdm, type);CHKERRQ(ierr);
63   if (newdm->ops->load) {
64     ierr = (*newdm->ops->load)(newdm,viewer);CHKERRQ(ierr);
65   }
66   ierr = KSPGetPC(newdm,&pc);CHKERRQ(ierr);
67   ierr = PCLoad(pc,viewer);CHKERRQ(ierr);
68   PetscFunctionReturn(0);
69 }
70 
71 #include <petscdraw.h>
72 #if defined(PETSC_HAVE_SAWS)
73 #include <petscviewersaws.h>
74 #endif
75 /*@C
76    KSPView - Prints the KSP data structure.
77 
78    Collective on KSP
79 
80    Input Parameters:
81 +  ksp - the Krylov space context
82 -  viewer - visualization context
83 
84    Options Database Keys:
85 .  -ksp_view - print the ksp data structure at the end of a KSPSolve call
86 
87    Note:
88    The available visualization contexts include
89 +     PETSC_VIEWER_STDOUT_SELF - standard output (default)
90 -     PETSC_VIEWER_STDOUT_WORLD - synchronized standard
91          output where only the first processor opens
92          the file.  All other processors send their
93          data to the first processor to print.
94 
95    The user can open an alternative visualization context with
96    PetscViewerASCIIOpen() - output to a specified file.
97 
98    Level: beginner
99 
100 .keywords: KSP, view
101 
102 .seealso: PCView(), PetscViewerASCIIOpen()
103 @*/
104 PetscErrorCode  KSPView(KSP ksp,PetscViewer viewer)
105 {
106   PetscErrorCode ierr;
107   PetscBool      iascii,isbinary,isdraw;
108 #if defined(PETSC_HAVE_SAWS)
109   PetscBool      issaws;
110 #endif
111 
112   PetscFunctionBegin;
113   PetscValidHeaderSpecific(ksp,KSP_CLASSID,1);
114   if (!viewer) {
115     ierr = PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)ksp),&viewer);CHKERRQ(ierr);
116   }
117   PetscValidHeaderSpecific(viewer,PETSC_VIEWER_CLASSID,2);
118   PetscCheckSameComm(ksp,1,viewer,2);
119 
120   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);CHKERRQ(ierr);
121   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);CHKERRQ(ierr);
122   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERDRAW,&isdraw);CHKERRQ(ierr);
123 #if defined(PETSC_HAVE_SAWS)
124   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSAWS,&issaws);CHKERRQ(ierr);
125 #endif
126   if (iascii) {
127     ierr = PetscObjectPrintClassNamePrefixType((PetscObject)ksp,viewer);CHKERRQ(ierr);
128     if (ksp->ops->view) {
129       ierr = PetscViewerASCIIPushTab(viewer);CHKERRQ(ierr);
130       ierr = (*ksp->ops->view)(ksp,viewer);CHKERRQ(ierr);
131       ierr = PetscViewerASCIIPopTab(viewer);CHKERRQ(ierr);
132     }
133     if (ksp->guess_zero) {
134       ierr = PetscViewerASCIIPrintf(viewer,"  maximum iterations=%D, initial guess is zero\n",ksp->max_it);CHKERRQ(ierr);
135     } else {
136       ierr = PetscViewerASCIIPrintf(viewer,"  maximum iterations=%D, nonzero initial guess\n", ksp->max_it);CHKERRQ(ierr);
137     }
138     if (ksp->guess_knoll) {ierr = PetscViewerASCIIPrintf(viewer,"  using preconditioner applied to right hand side for initial guess\n");CHKERRQ(ierr);}
139     ierr = PetscViewerASCIIPrintf(viewer,"  tolerances:  relative=%g, absolute=%g, divergence=%g\n",(double)ksp->rtol,(double)ksp->abstol,(double)ksp->divtol);CHKERRQ(ierr);
140     if (ksp->pc_side == PC_RIGHT) {
141       ierr = PetscViewerASCIIPrintf(viewer,"  right preconditioning\n");CHKERRQ(ierr);
142     } else if (ksp->pc_side == PC_SYMMETRIC) {
143       ierr = PetscViewerASCIIPrintf(viewer,"  symmetric preconditioning\n");CHKERRQ(ierr);
144     } else {
145       ierr = PetscViewerASCIIPrintf(viewer,"  left preconditioning\n");CHKERRQ(ierr);
146     }
147     if (ksp->guess) {
148       ierr = PetscViewerASCIIPushTab(viewer);CHKERRQ(ierr);
149       ierr = KSPGuessView(ksp->guess,viewer);CHKERRQ(ierr);
150       ierr = PetscViewerASCIIPopTab(viewer);CHKERRQ(ierr);
151     }
152     if (ksp->dscale) {ierr = PetscViewerASCIIPrintf(viewer,"  diagonally scaled system\n");CHKERRQ(ierr);}
153     ierr = PetscViewerASCIIPrintf(viewer,"  using %s norm type for convergence test\n",KSPNormTypes[ksp->normtype]);CHKERRQ(ierr);
154   } else if (isbinary) {
155     PetscInt    classid = KSP_FILE_CLASSID;
156     MPI_Comm    comm;
157     PetscMPIInt rank;
158     char        type[256];
159 
160     ierr = PetscObjectGetComm((PetscObject)ksp,&comm);CHKERRQ(ierr);
161     ierr = MPI_Comm_rank(comm,&rank);CHKERRQ(ierr);
162     if (!rank) {
163       ierr = PetscViewerBinaryWrite(viewer,&classid,1,PETSC_INT,PETSC_FALSE);CHKERRQ(ierr);
164       ierr = PetscStrncpy(type,((PetscObject)ksp)->type_name,256);CHKERRQ(ierr);
165       ierr = PetscViewerBinaryWrite(viewer,type,256,PETSC_CHAR,PETSC_FALSE);CHKERRQ(ierr);
166     }
167     if (ksp->ops->view) {
168       ierr = (*ksp->ops->view)(ksp,viewer);CHKERRQ(ierr);
169     }
170   } else if (isdraw) {
171     PetscDraw draw;
172     char      str[36];
173     PetscReal x,y,bottom,h;
174     PetscBool flg;
175 
176     ierr = PetscViewerDrawGetDraw(viewer,0,&draw);CHKERRQ(ierr);
177     ierr = PetscDrawGetCurrentPoint(draw,&x,&y);CHKERRQ(ierr);
178     ierr = PetscObjectTypeCompare((PetscObject)ksp,KSPPREONLY,&flg);CHKERRQ(ierr);
179     if (!flg) {
180       ierr   = PetscStrncpy(str,"KSP: ",sizeof(str));CHKERRQ(ierr);
181       ierr   = PetscStrlcat(str,((PetscObject)ksp)->type_name,sizeof(str));CHKERRQ(ierr);
182       ierr   = PetscDrawStringBoxed(draw,x,y,PETSC_DRAW_RED,PETSC_DRAW_BLACK,str,NULL,&h);CHKERRQ(ierr);
183       bottom = y - h;
184     } else {
185       bottom = y;
186     }
187     ierr = PetscDrawPushCurrentPoint(draw,x,bottom);CHKERRQ(ierr);
188 #if defined(PETSC_HAVE_SAWS)
189   } else if (issaws) {
190     PetscMPIInt rank;
191     const char  *name;
192 
193     ierr = PetscObjectGetName((PetscObject)ksp,&name);CHKERRQ(ierr);
194     ierr = MPI_Comm_rank(PETSC_COMM_WORLD,&rank);CHKERRQ(ierr);
195     if (!((PetscObject)ksp)->amsmem && !rank) {
196       char       dir[1024];
197 
198       ierr = PetscObjectViewSAWs((PetscObject)ksp,viewer);CHKERRQ(ierr);
199       ierr = PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/its",name);CHKERRQ(ierr);
200       PetscStackCallSAWs(SAWs_Register,(dir,&ksp->its,1,SAWs_READ,SAWs_INT));
201       if (!ksp->res_hist) {
202         ierr = KSPSetResidualHistory(ksp,NULL,PETSC_DECIDE,PETSC_TRUE);CHKERRQ(ierr);
203       }
204       ierr = PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/res_hist",name);CHKERRQ(ierr);
205       PetscStackCallSAWs(SAWs_Register,(dir,ksp->res_hist,10,SAWs_READ,SAWs_DOUBLE));
206     }
207 #endif
208   } else if (ksp->ops->view) {
209     ierr = (*ksp->ops->view)(ksp,viewer);CHKERRQ(ierr);
210   }
211   if (!ksp->skippcsetfromoptions) {
212     if (!ksp->pc) {ierr = KSPGetPC(ksp,&ksp->pc);CHKERRQ(ierr);}
213     ierr = PCView(ksp->pc,viewer);CHKERRQ(ierr);
214   }
215   if (isdraw) {
216     PetscDraw draw;
217     ierr = PetscViewerDrawGetDraw(viewer,0,&draw);CHKERRQ(ierr);
218     ierr = PetscDrawPopCurrentPoint(draw);CHKERRQ(ierr);
219   }
220   PetscFunctionReturn(0);
221 }
222 
223 
224 /*@
225    KSPSetNormType - Sets the norm that is used for convergence testing.
226 
227    Logically Collective on KSP
228 
229    Input Parameter:
230 +  ksp - Krylov solver context
231 -  normtype - one of
232 $   KSP_NORM_NONE - skips computing the norm, this should only be used if you are using
233 $                 the Krylov method as a smoother with a fixed small number of iterations.
234 $                 Implicitly sets KSPConvergedSkip as KSP convergence test.
235 $   KSP_NORM_PRECONDITIONED - the default for left preconditioned solves, uses the l2 norm
236 $                 of the preconditioned residual P^{-1}(b - A x)
237 $   KSP_NORM_UNPRECONDITIONED - uses the l2 norm of the true b - Ax residual.
238 $   KSP_NORM_NATURAL - supported  by KSPCG, KSPCR, KSPCGNE, KSPCGS
239 
240 
241    Options Database Key:
242 .   -ksp_norm_type <none,preconditioned,unpreconditioned,natural>
243 
244    Notes:
245    Not all combinations of preconditioner side (see KSPSetPCSide()) and norm type are supported by all Krylov methods.
246    If only one is set, PETSc tries to automatically change the other to find a compatible pair.  If no such combination
247    is supported, PETSc will generate an error.
248 
249    Developer Notes:
250    Supported combinations of norm and preconditioner side are set using KSPSetSupportedNorm().
251 
252    Level: advanced
253 
254 .keywords: KSP, create, context, norms
255 
256 .seealso: KSPSetUp(), KSPSolve(), KSPDestroy(), KSPConvergedSkip(), KSPSetCheckNormIteration(), KSPSetPCSide(), KSPGetPCSide(), KSPNormType
257 @*/
258 PetscErrorCode  KSPSetNormType(KSP ksp,KSPNormType normtype)
259 {
260   PetscFunctionBegin;
261   PetscValidHeaderSpecific(ksp,KSP_CLASSID,1);
262   PetscValidLogicalCollectiveEnum(ksp,normtype,2);
263   ksp->normtype = ksp->normtype_set = normtype;
264   PetscFunctionReturn(0);
265 }
266 
267 /*@
268    KSPSetCheckNormIteration - Sets the first iteration at which the norm of the residual will be
269      computed and used in the convergence test.
270 
271    Logically Collective on KSP
272 
273    Input Parameter:
274 +  ksp - Krylov solver context
275 -  it  - use -1 to check at all iterations
276 
277    Notes:
278    Currently only works with KSPCG, KSPBCGS and KSPIBCGS
279 
280    Use KSPSetNormType(ksp,KSP_NORM_NONE) to never check the norm
281 
282    On steps where the norm is not computed, the previous norm is still in the variable, so if you run with, for example,
283     -ksp_monitor the residual norm will appear to be unchanged for several iterations (though it is not really unchanged).
284    Level: advanced
285 
286 .keywords: KSP, create, context, norms
287 
288 .seealso: KSPSetUp(), KSPSolve(), KSPDestroy(), KSPConvergedSkip(), KSPSetNormType()
289 @*/
290 PetscErrorCode  KSPSetCheckNormIteration(KSP ksp,PetscInt it)
291 {
292   PetscFunctionBegin;
293   PetscValidHeaderSpecific(ksp,KSP_CLASSID,1);
294   PetscValidLogicalCollectiveInt(ksp,it,2);
295   ksp->chknorm = it;
296   PetscFunctionReturn(0);
297 }
298 
299 /*@
300    KSPSetLagNorm - Lags the residual norm calculation so that it is computed as part of the MPI_Allreduce() for
301    computing the inner products for the next iteration.  This can reduce communication costs at the expense of doing
302    one additional iteration.
303 
304 
305    Logically Collective on KSP
306 
307    Input Parameter:
308 +  ksp - Krylov solver context
309 -  flg - PETSC_TRUE or PETSC_FALSE
310 
311    Options Database Keys:
312 .  -ksp_lag_norm - lag the calculated residual norm
313 
314    Notes:
315    Currently only works with KSPIBCGS.
316 
317    Use KSPSetNormType(ksp,KSP_NORM_NONE) to never check the norm
318 
319    If you lag the norm and run with, for example, -ksp_monitor, the residual norm reported will be the lagged one.
320    Level: advanced
321 
322 .keywords: KSP, create, context, norms
323 
324 .seealso: KSPSetUp(), KSPSolve(), KSPDestroy(), KSPConvergedSkip(), KSPSetNormType(), KSPSetCheckNormIteration()
325 @*/
326 PetscErrorCode  KSPSetLagNorm(KSP ksp,PetscBool flg)
327 {
328   PetscFunctionBegin;
329   PetscValidHeaderSpecific(ksp,KSP_CLASSID,1);
330   PetscValidLogicalCollectiveBool(ksp,flg,2);
331   ksp->lagnorm = flg;
332   PetscFunctionReturn(0);
333 }
334 
335 /*@
336    KSPSetSupportedNorm - Sets a norm and preconditioner side supported by a KSP
337 
338    Logically Collective
339 
340    Input Arguments:
341 +  ksp - Krylov method
342 .  normtype - supported norm type
343 .  pcside - preconditioner side that can be used with this norm
344 -  priority - positive integer preference for this combination; larger values have higher priority
345 
346    Level: developer
347 
348    Notes:
349    This function should be called from the implementation files KSPCreate_XXX() to declare
350    which norms and preconditioner sides are supported. Users should not need to call this
351    function.
352 
353 .seealso: KSPSetNormType(), KSPSetPCSide()
354 @*/
355 PetscErrorCode KSPSetSupportedNorm(KSP ksp,KSPNormType normtype,PCSide pcside,PetscInt priority)
356 {
357 
358   PetscFunctionBegin;
359   PetscValidHeaderSpecific(ksp,KSP_CLASSID,1);
360   ksp->normsupporttable[normtype][pcside] = priority;
361   PetscFunctionReturn(0);
362 }
363 
364 PetscErrorCode KSPNormSupportTableReset_Private(KSP ksp)
365 {
366   PetscErrorCode ierr;
367 
368   PetscFunctionBegin;
369   ierr = PetscMemzero(ksp->normsupporttable,sizeof(ksp->normsupporttable));CHKERRQ(ierr);
370   ksp->pc_side  = ksp->pc_side_set;
371   ksp->normtype = ksp->normtype_set;
372   PetscFunctionReturn(0);
373 }
374 
375 PetscErrorCode KSPSetUpNorms_Private(KSP ksp,PetscBool errorifnotsupported,KSPNormType *normtype,PCSide *pcside)
376 {
377   PetscInt i,j,best,ibest = 0,jbest = 0;
378 
379   PetscFunctionBegin;
380   best = 0;
381   for (i=0; i<KSP_NORM_MAX; i++) {
382     for (j=0; j<PC_SIDE_MAX; j++) {
383       if ((ksp->normtype == KSP_NORM_DEFAULT || ksp->normtype == i) && (ksp->pc_side == PC_SIDE_DEFAULT || ksp->pc_side == j) && (ksp->normsupporttable[i][j] > best)) {
384         best  = ksp->normsupporttable[i][j];
385         ibest = i;
386         jbest = j;
387       }
388     }
389   }
390   if (best < 1 && errorifnotsupported) {
391     if (ksp->normtype == KSP_NORM_DEFAULT && ksp->pc_side == PC_SIDE_DEFAULT) SETERRQ1(PetscObjectComm((PetscObject)ksp),PETSC_ERR_PLIB,"The %s KSP implementation did not call KSPSetSupportedNorm()",((PetscObject)ksp)->type_name);
392     if (ksp->normtype == KSP_NORM_DEFAULT) SETERRQ2(PetscObjectComm((PetscObject)ksp),PETSC_ERR_SUP,"KSP %s does not support %s",((PetscObject)ksp)->type_name,PCSides[ksp->pc_side]);
393     if (ksp->pc_side == PC_SIDE_DEFAULT) SETERRQ2(PetscObjectComm((PetscObject)ksp),PETSC_ERR_SUP,"KSP %s does not support %s",((PetscObject)ksp)->type_name,KSPNormTypes[ksp->normtype]);
394     SETERRQ3(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]);
395   }
396   if (normtype) *normtype = (KSPNormType)ibest;
397   if (pcside)   *pcside   = (PCSide)jbest;
398   PetscFunctionReturn(0);
399 }
400 
401 /*@
402    KSPGetNormType - Gets the norm that is used for convergence testing.
403 
404    Not Collective
405 
406    Input Parameter:
407 .  ksp - Krylov solver context
408 
409    Output Parameter:
410 .  normtype - norm that is used for convergence testing
411 
412    Level: advanced
413 
414 .keywords: KSP, create, context, norms
415 
416 .seealso: KSPNormType, KSPSetNormType(), KSPConvergedSkip()
417 @*/
418 PetscErrorCode  KSPGetNormType(KSP ksp, KSPNormType *normtype)
419 {
420   PetscErrorCode ierr;
421 
422   PetscFunctionBegin;
423   PetscValidHeaderSpecific(ksp,KSP_CLASSID,1);
424   PetscValidPointer(normtype,2);
425   ierr      = KSPSetUpNorms_Private(ksp,PETSC_TRUE,&ksp->normtype,&ksp->pc_side);CHKERRQ(ierr);
426   *normtype = ksp->normtype;
427   PetscFunctionReturn(0);
428 }
429 
430 #if defined(PETSC_HAVE_SAWS)
431 #include <petscviewersaws.h>
432 #endif
433 
434 /*@
435    KSPSetOperators - Sets the matrix associated with the linear system
436    and a (possibly) different one associated with the preconditioner.
437 
438    Collective on KSP and Mat
439 
440    Input Parameters:
441 +  ksp - the KSP context
442 .  Amat - the matrix that defines the linear system
443 -  Pmat - the matrix to be used in constructing the preconditioner, usually the same as Amat.
444 
445    Notes:
446 
447     If you know the operator Amat has a null space you can use MatSetNullSpace() and MatSetTransposeNullSpace() to supply the null
448     space to Amat and the KSP solvers will automatically use that null space as needed during the solution process.
449 
450     All future calls to KSPSetOperators() must use the same size matrices!
451 
452     Passing a NULL for Amat or Pmat removes the matrix that is currently used.
453 
454     If you wish to replace either Amat or Pmat but leave the other one untouched then
455     first call KSPGetOperators() to get the one you wish to keep, call PetscObjectReference()
456     on it and then pass it back in in your call to KSPSetOperators().
457 
458     Level: beginner
459 
460    Alternative usage: If the operators have NOT been set with KSP/PCSetOperators() then the operators
461       are created in PC and returned to the user. In this case, if both operators
462       mat and pmat are requested, two DIFFERENT operators will be returned. If
463       only one is requested both operators in the PC will be the same (i.e. as
464       if one had called KSP/PCSetOperators() with the same argument for both Mats).
465       The user must set the sizes of the returned matrices and their type etc just
466       as if the user created them with MatCreate(). For example,
467 
468 $         KSP/PCGetOperators(ksp/pc,&mat,NULL); is equivalent to
469 $           set size, type, etc of mat
470 
471 $         MatCreate(comm,&mat);
472 $         KSP/PCSetOperators(ksp/pc,mat,mat);
473 $         PetscObjectDereference((PetscObject)mat);
474 $           set size, type, etc of mat
475 
476      and
477 
478 $         KSP/PCGetOperators(ksp/pc,&mat,&pmat); is equivalent to
479 $           set size, type, etc of mat and pmat
480 
481 $         MatCreate(comm,&mat);
482 $         MatCreate(comm,&pmat);
483 $         KSP/PCSetOperators(ksp/pc,mat,pmat);
484 $         PetscObjectDereference((PetscObject)mat);
485 $         PetscObjectDereference((PetscObject)pmat);
486 $           set size, type, etc of mat and pmat
487 
488     The rational for this support is so that when creating a TS, SNES, or KSP the hierarchy
489     of underlying objects (i.e. SNES, KSP, PC, Mat) and their livespans can be completely
490     managed by the top most level object (i.e. the TS, SNES, or KSP). Another way to look
491     at this is when you create a SNES you do not NEED to create a KSP and attach it to
492     the SNES object (the SNES object manages it for you). Similarly when you create a KSP
493     you do not need to attach a PC to it (the KSP object manages the PC object for you).
494     Thus, why should YOU have to create the Mat and attach it to the SNES/KSP/PC, when
495     it can be created for you?
496 
497 .keywords: KSP, set, operators, matrix, preconditioner, linear system
498 
499 .seealso: KSPSolve(), KSPGetPC(), PCGetOperators(), PCSetOperators(), KSPGetOperators(), KSPSetComputeOperators(), KSPSetComputeInitialGuess(), KSPSetComputeRHS()
500 @*/
501 PetscErrorCode  KSPSetOperators(KSP ksp,Mat Amat,Mat Pmat)
502 {
503   PetscErrorCode ierr;
504 
505   PetscFunctionBegin;
506   PetscValidHeaderSpecific(ksp,KSP_CLASSID,1);
507   if (Amat) PetscValidHeaderSpecific(Amat,MAT_CLASSID,2);
508   if (Pmat) PetscValidHeaderSpecific(Pmat,MAT_CLASSID,3);
509   if (Amat) PetscCheckSameComm(ksp,1,Amat,2);
510   if (Pmat) PetscCheckSameComm(ksp,1,Pmat,3);
511   if (!ksp->pc) {ierr = KSPGetPC(ksp,&ksp->pc);CHKERRQ(ierr);}
512   ierr = PCSetOperators(ksp->pc,Amat,Pmat);CHKERRQ(ierr);
513   if (ksp->setupstage == KSP_SETUP_NEWRHS) ksp->setupstage = KSP_SETUP_NEWMATRIX;  /* so that next solve call will call PCSetUp() on new matrix */
514   PetscFunctionReturn(0);
515 }
516 
517 /*@
518    KSPGetOperators - Gets the matrix associated with the linear system
519    and a (possibly) different one associated with the preconditioner.
520 
521    Collective on KSP and Mat
522 
523    Input Parameter:
524 .  ksp - the KSP context
525 
526    Output Parameters:
527 +  Amat - the matrix that defines the linear system
528 -  Pmat - the matrix to be used in constructing the preconditioner, usually the same as Amat.
529 
530     Level: intermediate
531 
532    Notes:
533     DOES NOT increase the reference counts of the matrix, so you should NOT destroy them.
534 
535 .keywords: KSP, set, get, operators, matrix, preconditioner, linear system
536 
537 .seealso: KSPSolve(), KSPGetPC(), PCGetOperators(), PCSetOperators(), KSPSetOperators(), KSPGetOperatorsSet()
538 @*/
539 PetscErrorCode  KSPGetOperators(KSP ksp,Mat *Amat,Mat *Pmat)
540 {
541   PetscErrorCode ierr;
542 
543   PetscFunctionBegin;
544   PetscValidHeaderSpecific(ksp,KSP_CLASSID,1);
545   if (!ksp->pc) {ierr = KSPGetPC(ksp,&ksp->pc);CHKERRQ(ierr);}
546   ierr = PCGetOperators(ksp->pc,Amat,Pmat);CHKERRQ(ierr);
547   PetscFunctionReturn(0);
548 }
549 
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.
553 
554    Not collective, though the results on all processes should be the same
555 
556    Input Parameter:
557 .  pc - the KSP context
558 
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
562 
563    Level: intermediate
564 
565 .keywords: KSP, get, operators, matrix, linear system
566 
567 .seealso: PCSetOperators(), KSPGetOperators(), KSPSetOperators(), PCGetOperators(), PCGetOperatorsSet()
568 @*/
569 PetscErrorCode  KSPGetOperatorsSet(KSP ksp,PetscBool  *mat,PetscBool  *pmat)
570 {
571   PetscErrorCode ierr;
572 
573   PetscFunctionBegin;
574   PetscValidHeaderSpecific(ksp,KSP_CLASSID,1);
575   if (!ksp->pc) {ierr = KSPGetPC(ksp,&ksp->pc);CHKERRQ(ierr);}
576   ierr = PCGetOperatorsSet(ksp->pc,mat,pmat);CHKERRQ(ierr);
577   PetscFunctionReturn(0);
578 }
579 
580 /*@C
581    KSPSetPreSolve - Sets a function that is called before every KSPSolve() is started
582 
583    Logically Collective on KSP
584 
585    Input Parameters:
586 +   ksp - the solver object
587 .   presolve - the function to call before the solve
588 -   prectx - any context needed by the function
589 
590    Level: developer
591 
592 .keywords: KSP, create, context
593 
594 .seealso: KSPSetUp(), KSPSolve(), KSPDestroy(), KSP, KSPSetPostSolve()
595 @*/
596 PetscErrorCode  KSPSetPreSolve(KSP ksp,PetscErrorCode (*presolve)(KSP,Vec,Vec,void*),void *prectx)
597 {
598   PetscFunctionBegin;
599   PetscValidHeaderSpecific(ksp,KSP_CLASSID,1);
600   ksp->presolve = presolve;
601   ksp->prectx   = prectx;
602   PetscFunctionReturn(0);
603 }
604 
605 /*@C
606    KSPSetPostSolve - Sets a function that is called after every KSPSolve() completes (whether it converges or not)
607 
608    Logically Collective on KSP
609 
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
614 
615    Level: developer
616 
617 .keywords: KSP, create, context
618 
619 .seealso: KSPSetUp(), KSPSolve(), KSPDestroy(), KSP, KSPSetPreSolve()
620 @*/
621 PetscErrorCode  KSPSetPostSolve(KSP ksp,PetscErrorCode (*postsolve)(KSP,Vec,Vec,void*),void *postctx)
622 {
623   PetscFunctionBegin;
624   PetscValidHeaderSpecific(ksp,KSP_CLASSID,1);
625   ksp->postsolve = postsolve;
626   ksp->postctx   = postctx;
627   PetscFunctionReturn(0);
628 }
629 
630 /*@
631    KSPCreate - Creates the default KSP context.
632 
633    Collective on MPI_Comm
634 
635    Input Parameter:
636 .  comm - MPI communicator
637 
638    Output Parameter:
639 .  ksp - location to put the KSP context
640 
641    Notes:
642    The default KSP type is GMRES with a restart of 30, using modified Gram-Schmidt
643    orthogonalization.
644 
645    Level: beginner
646 
647 .keywords: KSP, create, context
648 
649 .seealso: KSPSetUp(), KSPSolve(), KSPDestroy(), KSP
650 @*/
651 PetscErrorCode  KSPCreate(MPI_Comm comm,KSP *inksp)
652 {
653   KSP            ksp;
654   PetscErrorCode ierr;
655   void           *ctx;
656 
657   PetscFunctionBegin;
658   PetscValidPointer(inksp,2);
659   *inksp = 0;
660   ierr = KSPInitializePackage();CHKERRQ(ierr);
661 
662   ierr = PetscHeaderCreate(ksp,KSP_CLASSID,"KSP","Krylov Method","KSP",comm,KSPDestroy,KSPView);CHKERRQ(ierr);
663 
664   ksp->max_it  = 10000;
665   ksp->pc_side = ksp->pc_side_set = PC_SIDE_DEFAULT;
666   ksp->rtol    = 1.e-5;
667 #if defined(PETSC_USE_REAL_SINGLE)
668   ksp->abstol  = 1.e-25;
669 #else
670   ksp->abstol  = 1.e-50;
671 #endif
672   ksp->divtol  = 1.e4;
673 
674   ksp->chknorm        = -1;
675   ksp->normtype       = ksp->normtype_set = KSP_NORM_DEFAULT;
676   ksp->rnorm          = 0.0;
677   ksp->its            = 0;
678   ksp->guess_zero     = PETSC_TRUE;
679   ksp->calc_sings     = PETSC_FALSE;
680   ksp->res_hist       = NULL;
681   ksp->res_hist_alloc = NULL;
682   ksp->res_hist_len   = 0;
683   ksp->res_hist_max   = 0;
684   ksp->res_hist_reset = PETSC_TRUE;
685   ksp->numbermonitors = 0;
686   ksp->setfromoptionscalled = 0;
687 
688   ierr                    = KSPConvergedDefaultCreate(&ctx);CHKERRQ(ierr);
689   ierr                    = KSPSetConvergenceTest(ksp,KSPConvergedDefault,ctx,KSPConvergedDefaultDestroy);CHKERRQ(ierr);
690   ksp->ops->buildsolution = KSPBuildSolutionDefault;
691   ksp->ops->buildresidual = KSPBuildResidualDefault;
692 
693   ksp->vec_sol    = 0;
694   ksp->vec_rhs    = 0;
695   ksp->pc         = 0;
696   ksp->data       = 0;
697   ksp->nwork      = 0;
698   ksp->work       = 0;
699   ksp->reason     = KSP_CONVERGED_ITERATING;
700   ksp->setupstage = KSP_SETUP_NEW;
701 
702   ierr = KSPNormSupportTableReset_Private(ksp);CHKERRQ(ierr);
703 
704   *inksp = ksp;
705   PetscFunctionReturn(0);
706 }
707 
708 /*@C
709    KSPSetType - Builds KSP for a particular solver.
710 
711    Logically Collective on KSP
712 
713    Input Parameters:
714 +  ksp      - the Krylov space context
715 -  type - a known method
716 
717    Options Database Key:
718 .  -ksp_type  <method> - Sets the method; use -help for a list
719     of available methods (for instance, cg or gmres)
720 
721    Notes:
722    See "petsc/include/petscksp.h" for available methods (for instance,
723    KSPCG or KSPGMRES).
724 
725   Normally, it is best to use the KSPSetFromOptions() command and
726   then set the KSP type from the options database rather than by using
727   this routine.  Using the options database provides the user with
728   maximum flexibility in evaluating the many different Krylov methods.
729   The KSPSetType() routine is provided for those situations where it
730   is necessary to set the iterative solver independently of the command
731   line or options database.  This might be the case, for example, when
732   the choice of iterative solver changes during the execution of the
733   program, and the user's application is taking responsibility for
734   choosing the appropriate method.  In other words, this routine is
735   not for beginners.
736 
737   Level: intermediate
738 
739   Developer Note: KSPRegister() is used to add Krylov types to KSPList from which they
740   are accessed by KSPSetType().
741 
742 .keywords: KSP, set, method
743 
744 .seealso: PCSetType(), KSPType, KSPRegister(), KSPCreate()
745 
746 @*/
747 PetscErrorCode  KSPSetType(KSP ksp, KSPType type)
748 {
749   PetscErrorCode ierr,(*r)(KSP);
750   PetscBool      match;
751   void           *ctx;
752 
753   PetscFunctionBegin;
754   PetscValidHeaderSpecific(ksp,KSP_CLASSID,1);
755   PetscValidCharPointer(type,2);
756 
757   ierr = PetscObjectTypeCompare((PetscObject)ksp,type,&match);CHKERRQ(ierr);
758   if (match) PetscFunctionReturn(0);
759 
760   ierr =  PetscFunctionListFind(KSPList,type,&r);CHKERRQ(ierr);
761   if (!r) SETERRQ1(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_UNKNOWN_TYPE,"Unable to find requested KSP type %s",type);
762   /* Destroy the previous private KSP context */
763   if (ksp->ops->destroy) {
764     ierr              = (*ksp->ops->destroy)(ksp);CHKERRQ(ierr);
765     ksp->ops->destroy = NULL;
766   }
767   /* Reinitialize function pointers in KSPOps structure */
768   ierr                    = PetscMemzero(ksp->ops,sizeof(struct _KSPOps));CHKERRQ(ierr);
769   ierr                    = KSPConvergedDefaultCreate(&ctx);CHKERRQ(ierr);
770   ierr                    = KSPSetConvergenceTest(ksp,KSPConvergedDefault,ctx,KSPConvergedDefaultDestroy);CHKERRQ(ierr);
771   ksp->ops->buildsolution = KSPBuildSolutionDefault;
772   ksp->ops->buildresidual = KSPBuildResidualDefault;
773   ierr                    = KSPNormSupportTableReset_Private(ksp);CHKERRQ(ierr);
774   /* Call the KSPCreate_XXX routine for this particular Krylov solver */
775   ksp->setupstage = KSP_SETUP_NEW;
776   ierr            = PetscObjectChangeTypeName((PetscObject)ksp,type);CHKERRQ(ierr);
777   ierr            = (*r)(ksp);CHKERRQ(ierr);
778   PetscFunctionReturn(0);
779 }
780 
781 /*@C
782    KSPGetType - Gets the KSP type as a string from the KSP object.
783 
784    Not Collective
785 
786    Input Parameter:
787 .  ksp - Krylov context
788 
789    Output Parameter:
790 .  name - name of KSP method
791 
792    Level: intermediate
793 
794 .keywords: KSP, get, method, name
795 
796 .seealso: KSPSetType()
797 @*/
798 PetscErrorCode  KSPGetType(KSP ksp,KSPType *type)
799 {
800   PetscFunctionBegin;
801   PetscValidHeaderSpecific(ksp,KSP_CLASSID,1);
802   PetscValidPointer(type,2);
803   *type = ((PetscObject)ksp)->type_name;
804   PetscFunctionReturn(0);
805 }
806 
807 /*@C
808   KSPRegister -  Adds a method to the Krylov subspace solver package.
809 
810    Not Collective
811 
812    Input Parameters:
813 +  name_solver - name of a new user-defined solver
814 -  routine_create - routine to create method context
815 
816    Notes:
817    KSPRegister() may be called multiple times to add several user-defined solvers.
818 
819    Sample usage:
820 .vb
821    KSPRegister("my_solver",MySolverCreate);
822 .ve
823 
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
828 
829    Level: advanced
830 
831 .keywords: KSP, register
832 
833 .seealso: KSPRegisterAll(), KSPRegisterDestroy()
834 
835 @*/
836 PetscErrorCode  KSPRegister(const char sname[],PetscErrorCode (*function)(KSP))
837 {
838   PetscErrorCode ierr;
839 
840   PetscFunctionBegin;
841   ierr = KSPInitializePackage();CHKERRQ(ierr);
842   ierr = PetscFunctionListAdd(&KSPList,sname,function);CHKERRQ(ierr);
843   PetscFunctionReturn(0);
844 }
845