Actual source code: itfunc.c
petsc-3.12.2 2019-11-22
2: /*
3: Interface KSP routines that the user calls.
4: */
6: #include <petsc/private/kspimpl.h>
7: #include <petscdm.h>
9: PETSC_STATIC_INLINE PetscErrorCode ObjectView(PetscObject obj, PetscViewer viewer, PetscViewerFormat format)
10: {
13: PetscViewerPushFormat(viewer, format);
14: PetscObjectView(obj, viewer);
15: PetscViewerPopFormat(viewer);
16: return(0);
17: }
19: /*@
20: KSPComputeExtremeSingularValues - Computes the extreme singular values
21: for the preconditioned operator. Called after or during KSPSolve().
23: Not Collective
25: Input Parameter:
26: . ksp - iterative context obtained from KSPCreate()
28: Output Parameters:
29: . emin, emax - extreme singular values
31: Options Database Keys:
32: . -ksp_view_singularvalues - compute extreme singular values and print when KSPSolve completes.
34: Notes:
35: One must call KSPSetComputeSingularValues() before calling KSPSetUp()
36: (or use the option -ksp_view_eigenvalues) in order for this routine to work correctly.
38: Many users may just want to use the monitoring routine
39: KSPMonitorSingularValue() (which can be set with option -ksp_monitor_singular_value)
40: to print the extreme singular values at each iteration of the linear solve.
42: Estimates of the smallest singular value may be very inaccurate, especially if the Krylov method has not converged.
43: The largest singular value is usually accurate to within a few percent if the method has converged, but is still not
44: intended for eigenanalysis.
46: Disable restarts if using KSPGMRES, otherwise this estimate will only be using those iterations after the last
47: restart. See KSPGMRESSetRestart() for more details.
49: Level: advanced
51: .seealso: KSPSetComputeSingularValues(), KSPMonitorSingularValue(), KSPComputeEigenvalues(), KSP
52: @*/
53: PetscErrorCode KSPComputeExtremeSingularValues(KSP ksp,PetscReal *emax,PetscReal *emin)
54: {
61: if (!ksp->calc_sings) SETERRQ(PetscObjectComm((PetscObject)ksp),4,"Singular values not requested before KSPSetUp()");
63: if (ksp->ops->computeextremesingularvalues) {
64: (*ksp->ops->computeextremesingularvalues)(ksp,emax,emin);
65: } else {
66: *emin = -1.0;
67: *emax = -1.0;
68: }
69: return(0);
70: }
72: /*@
73: KSPComputeEigenvalues - Computes the extreme eigenvalues for the
74: preconditioned operator. Called after or during KSPSolve().
76: Not Collective
78: Input Parameter:
79: + ksp - iterative context obtained from KSPCreate()
80: - n - size of arrays r and c. The number of eigenvalues computed (neig) will, in
81: general, be less than this.
83: Output Parameters:
84: + r - real part of computed eigenvalues, provided by user with a dimension of at least n
85: . c - complex part of computed eigenvalues, provided by user with a dimension of at least n
86: - neig - actual number of eigenvalues computed (will be less than or equal to n)
88: Options Database Keys:
89: + -ksp_view_eigenvalues - Prints eigenvalues to stdout
91: Notes:
92: The number of eigenvalues estimated depends on the size of the Krylov space
93: generated during the KSPSolve() ; for example, with
94: CG it corresponds to the number of CG iterations, for GMRES it is the number
95: of GMRES iterations SINCE the last restart. Any extra space in r[] and c[]
96: will be ignored.
98: KSPComputeEigenvalues() does not usually provide accurate estimates; it is
99: intended only for assistance in understanding the convergence of iterative
100: methods, not for eigenanalysis. For accurate computation of eigenvalues we recommend using
101: the excellent package SLEPc.
103: One must call KSPSetComputeEigenvalues() before calling KSPSetUp()
104: in order for this routine to work correctly.
106: Many users may just want to use the monitoring routine
107: KSPMonitorSingularValue() (which can be set with option -ksp_monitor_singular_value)
108: to print the singular values at each iteration of the linear solve.
110: Level: advanced
112: .seealso: KSPSetComputeSingularValues(), KSPMonitorSingularValue(), KSPComputeExtremeSingularValues(), KSP
113: @*/
114: PetscErrorCode KSPComputeEigenvalues(KSP ksp,PetscInt n,PetscReal r[],PetscReal c[],PetscInt *neig)
115: {
122: if (n<0) SETERRQ(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_OUTOFRANGE,"Requested < 0 Eigenvalues");
124: if (!ksp->calc_sings) SETERRQ(PetscObjectComm((PetscObject)ksp),4,"Eigenvalues not requested before KSPSetUp()");
126: if (n && ksp->ops->computeeigenvalues) {
127: (*ksp->ops->computeeigenvalues)(ksp,n,r,c,neig);
128: } else {
129: *neig = 0;
130: }
131: return(0);
132: }
134: /*@
135: KSPComputeRitz - Computes the Ritz or harmonic Ritz pairs associated to the
136: smallest or largest in modulus, for the preconditioned operator.
137: Called after KSPSolve().
139: Not Collective
141: Input Parameter:
142: + ksp - iterative context obtained from KSPCreate()
143: . ritz - PETSC_TRUE or PETSC_FALSE for ritz pairs or harmonic Ritz pairs, respectively
144: . small - PETSC_TRUE or PETSC_FALSE for smallest or largest (harmonic) Ritz values, respectively
145: - nrit - number of (harmonic) Ritz pairs to compute
147: Output Parameters:
148: + nrit - actual number of computed (harmonic) Ritz pairs
149: . S - multidimensional vector with Ritz vectors
150: . tetar - real part of the Ritz values
151: - tetai - imaginary part of the Ritz values
153: Notes:
154: -For GMRES, the (harmonic) Ritz pairs are computed from the Hessenberg matrix obtained during
155: the last complete cycle, or obtained at the end of the solution if the method is stopped before
156: a restart. Then, the number of actual (harmonic) Ritz pairs computed is less or equal to the restart
157: parameter for GMRES if a complete cycle has been performed or less or equal to the number of GMRES
158: iterations.
159: -Moreover, for real matrices, the (harmonic) Ritz pairs are possibly complex-valued. In such a case,
160: the routine selects the complex (harmonic) Ritz value and its conjugate, and two successive columns of S
161: are equal to the real and the imaginary parts of the associated vectors.
162: -the (harmonic) Ritz pairs are given in order of increasing (harmonic) Ritz values in modulus
163: -this is currently not implemented when PETSc is built with complex numbers
165: One must call KSPSetComputeRitz() before calling KSPSetUp()
166: in order for this routine to work correctly.
168: Level: advanced
170: .seealso: KSPSetComputeRitz(), KSP
171: @*/
172: PetscErrorCode KSPComputeRitz(KSP ksp,PetscBool ritz,PetscBool small,PetscInt *nrit,Vec S[],PetscReal tetar[],PetscReal tetai[])
173: {
178: if (!ksp->calc_ritz) SETERRQ(PetscObjectComm((PetscObject)ksp),4,"Ritz pairs not requested before KSPSetUp()");
179: if (ksp->ops->computeritz) {(*ksp->ops->computeritz)(ksp,ritz,small,nrit,S,tetar,tetai);}
180: return(0);
181: }
182: /*@
183: KSPSetUpOnBlocks - Sets up the preconditioner for each block in
184: the block Jacobi, block Gauss-Seidel, and overlapping Schwarz
185: methods.
187: Collective on ksp
189: Input Parameter:
190: . ksp - the KSP context
192: Notes:
193: KSPSetUpOnBlocks() is a routine that the user can optinally call for
194: more precise profiling (via -log_view) of the setup phase for these
195: block preconditioners. If the user does not call KSPSetUpOnBlocks(),
196: it will automatically be called from within KSPSolve().
198: Calling KSPSetUpOnBlocks() is the same as calling PCSetUpOnBlocks()
199: on the PC context within the KSP context.
201: Level: advanced
203: .seealso: PCSetUpOnBlocks(), KSPSetUp(), PCSetUp(), KSP
204: @*/
205: PetscErrorCode KSPSetUpOnBlocks(KSP ksp)
206: {
207: PC pc;
209: PCFailedReason pcreason;
213: KSPGetPC(ksp,&pc);
214: PCSetUpOnBlocks(pc);
215: PCGetFailedReason(pc,&pcreason);
216: if (pcreason) {
217: ksp->reason = KSP_DIVERGED_PC_FAILED;
218: }
219: return(0);
220: }
222: /*@
223: KSPSetReusePreconditioner - reuse the current preconditioner, do not construct a new one even if the operator changes
225: Collective on ksp
227: Input Parameters:
228: + ksp - iterative context obtained from KSPCreate()
229: - flag - PETSC_TRUE to reuse the current preconditioner
231: Level: intermediate
233: .seealso: KSPCreate(), KSPSolve(), KSPDestroy(), PCSetReusePreconditioner(), KSP
234: @*/
235: PetscErrorCode KSPSetReusePreconditioner(KSP ksp,PetscBool flag)
236: {
237: PC pc;
242: KSPGetPC(ksp,&pc);
243: PCSetReusePreconditioner(pc,flag);
244: return(0);
245: }
247: /*@
248: 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
250: Collective on ksp
252: Input Parameters:
253: + ksp - iterative context obtained from KSPCreate()
254: - flag - PETSC_TRUE to skip calling the PCSetFromOptions()
256: Level: intermediate
258: .seealso: KSPCreate(), KSPSolve(), KSPDestroy(), PCSetReusePreconditioner(), KSP
259: @*/
260: PetscErrorCode KSPSetSkipPCSetFromOptions(KSP ksp,PetscBool flag)
261: {
264: ksp->skippcsetfromoptions = flag;
265: return(0);
266: }
268: /*@
269: KSPSetUp - Sets up the internal data structures for the
270: later use of an iterative solver.
272: Collective on ksp
274: Input Parameter:
275: . ksp - iterative context obtained from KSPCreate()
277: Level: developer
279: .seealso: KSPCreate(), KSPSolve(), KSPDestroy(), KSP
280: @*/
281: PetscErrorCode KSPSetUp(KSP ksp)
282: {
284: Mat A,B;
285: Mat mat,pmat;
286: MatNullSpace nullsp;
287: PCFailedReason pcreason;
288:
292: /* reset the convergence flag from the previous solves */
293: ksp->reason = KSP_CONVERGED_ITERATING;
295: if (!((PetscObject)ksp)->type_name) {
296: KSPSetType(ksp,KSPGMRES);
297: }
298: KSPSetUpNorms_Private(ksp,PETSC_TRUE,&ksp->normtype,&ksp->pc_side);
300: if (ksp->dmActive && !ksp->setupstage) {
301: /* first time in so build matrix and vector data structures using DM */
302: if (!ksp->vec_rhs) {DMCreateGlobalVector(ksp->dm,&ksp->vec_rhs);}
303: if (!ksp->vec_sol) {DMCreateGlobalVector(ksp->dm,&ksp->vec_sol);}
304: DMCreateMatrix(ksp->dm,&A);
305: KSPSetOperators(ksp,A,A);
306: PetscObjectDereference((PetscObject)A);
307: }
309: if (ksp->dmActive) {
310: DMKSP kdm;
311: DMGetDMKSP(ksp->dm,&kdm);
313: if (kdm->ops->computeinitialguess && ksp->setupstage != KSP_SETUP_NEWRHS) {
314: /* only computes initial guess the first time through */
315: (*kdm->ops->computeinitialguess)(ksp,ksp->vec_sol,kdm->initialguessctx);
316: KSPSetInitialGuessNonzero(ksp,PETSC_TRUE);
317: }
318: if (kdm->ops->computerhs) {
319: (*kdm->ops->computerhs)(ksp,ksp->vec_rhs,kdm->rhsctx);
320: }
322: if (ksp->setupstage != KSP_SETUP_NEWRHS) {
323: if (kdm->ops->computeoperators) {
324: KSPGetOperators(ksp,&A,&B);
325: (*kdm->ops->computeoperators)(ksp,A,B,kdm->operatorsctx);
326: } else SETERRQ(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_WRONGSTATE,"You called KSPSetDM() but did not use DMKSPSetComputeOperators() or KSPSetDMActive(ksp,PETSC_FALSE);");
327: }
328: }
330: if (ksp->setupstage == KSP_SETUP_NEWRHS) return(0);
331: PetscLogEventBegin(KSP_SetUp,ksp,ksp->vec_rhs,ksp->vec_sol,0);
333: switch (ksp->setupstage) {
334: case KSP_SETUP_NEW:
335: (*ksp->ops->setup)(ksp);
336: break;
337: case KSP_SETUP_NEWMATRIX: { /* This should be replaced with a more general mechanism */
338: if (ksp->setupnewmatrix) {
339: (*ksp->ops->setup)(ksp);
340: }
341: } break;
342: default: break;
343: }
345: if (!ksp->pc) {KSPGetPC(ksp,&ksp->pc);}
346: PCGetOperators(ksp->pc,&mat,&pmat);
347: /* scale the matrix if requested */
348: if (ksp->dscale) {
349: PetscScalar *xx;
350: PetscInt i,n;
351: PetscBool zeroflag = PETSC_FALSE;
352: if (!ksp->pc) {KSPGetPC(ksp,&ksp->pc);}
353: if (!ksp->diagonal) { /* allocate vector to hold diagonal */
354: MatCreateVecs(pmat,&ksp->diagonal,0);
355: }
356: MatGetDiagonal(pmat,ksp->diagonal);
357: VecGetLocalSize(ksp->diagonal,&n);
358: VecGetArray(ksp->diagonal,&xx);
359: for (i=0; i<n; i++) {
360: if (xx[i] != 0.0) xx[i] = 1.0/PetscSqrtReal(PetscAbsScalar(xx[i]));
361: else {
362: xx[i] = 1.0;
363: zeroflag = PETSC_TRUE;
364: }
365: }
366: VecRestoreArray(ksp->diagonal,&xx);
367: if (zeroflag) {
368: PetscInfo(ksp,"Zero detected in diagonal of matrix, using 1 at those locations\n");
369: }
370: MatDiagonalScale(pmat,ksp->diagonal,ksp->diagonal);
371: if (mat != pmat) {MatDiagonalScale(mat,ksp->diagonal,ksp->diagonal);}
372: ksp->dscalefix2 = PETSC_FALSE;
373: }
374: PetscLogEventEnd(KSP_SetUp,ksp,ksp->vec_rhs,ksp->vec_sol,0);
375: PCSetErrorIfFailure(ksp->pc,ksp->errorifnotconverged);
376: PCSetUp(ksp->pc);
377: PCGetFailedReason(ksp->pc,&pcreason);
378: if (pcreason) {
379: ksp->reason = KSP_DIVERGED_PC_FAILED;
380: }
382: MatGetNullSpace(mat,&nullsp);
383: if (nullsp) {
384: PetscBool test = PETSC_FALSE;
385: PetscOptionsGetBool(((PetscObject)ksp)->options,((PetscObject)ksp)->prefix,"-ksp_test_null_space",&test,NULL);
386: if (test) {
387: MatNullSpaceTest(nullsp,mat,NULL);
388: }
389: }
390: ksp->setupstage = KSP_SETUP_NEWRHS;
391: return(0);
392: }
394: static PetscErrorCode KSPReasonView_Internal(KSP ksp, PetscViewer viewer, PetscViewerFormat format)
395: {
397: PetscBool isAscii;
400: if (format != PETSC_VIEWER_DEFAULT) {PetscViewerPushFormat(viewer,format);}
401: PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&isAscii);
402: if (isAscii) {
403: PetscViewerASCIIAddTab(viewer,((PetscObject)ksp)->tablevel);
404: if (ksp->reason > 0) {
405: if (((PetscObject) ksp)->prefix) {
406: PetscViewerASCIIPrintf(viewer,"Linear %s solve converged due to %s iterations %D\n",((PetscObject) ksp)->prefix,KSPConvergedReasons[ksp->reason],ksp->its);
407: } else {
408: PetscViewerASCIIPrintf(viewer,"Linear solve converged due to %s iterations %D\n",KSPConvergedReasons[ksp->reason],ksp->its);
409: }
410: } else {
411: if (((PetscObject) ksp)->prefix) {
412: PetscViewerASCIIPrintf(viewer,"Linear %s solve did not converge due to %s iterations %D\n",((PetscObject) ksp)->prefix,KSPConvergedReasons[ksp->reason],ksp->its);
413: } else {
414: PetscViewerASCIIPrintf(viewer,"Linear solve did not converge due to %s iterations %D\n",KSPConvergedReasons[ksp->reason],ksp->its);
415: }
416: if (ksp->reason == KSP_DIVERGED_PC_FAILED) {
417: PCFailedReason reason;
418: PCGetFailedReason(ksp->pc,&reason);
419: PetscViewerASCIIPrintf(viewer," PC_FAILED due to %s \n",PCFailedReasons[reason]);
420: }
421: }
422: PetscViewerASCIISubtractTab(viewer,((PetscObject)ksp)->tablevel);
423: }
424: if (format != PETSC_VIEWER_DEFAULT) {PetscViewerPopFormat(viewer);}
425: return(0);
426: }
428: /*@
429: KSPReasonView - Displays the reason a KSP solve converged or diverged to a viewer
431: Collective on ksp
433: Parameter:
434: + ksp - iterative context obtained from KSPCreate()
435: - viewer - the viewer to display the reason
438: Options Database Keys:
439: . -ksp_converged_reason - print reason for converged or diverged, also prints number of iterations
441: Level: beginner
443: .seealso: KSPCreate(), KSPSetUp(), KSPDestroy(), KSPSetTolerances(), KSPConvergedDefault(),
444: KSPSolveTranspose(), KSPGetIterationNumber(), KSP
445: @*/
446: PetscErrorCode KSPReasonView(KSP ksp,PetscViewer viewer)
447: {
451: KSPReasonView_Internal(ksp, viewer, PETSC_VIEWER_DEFAULT);
452: return(0);
453: }
455: #if defined(PETSC_HAVE_THREADSAFETY)
456: #define KSPReasonViewFromOptions KSPReasonViewFromOptionsUnsafe
457: #else
458: #endif
459: /*@C
460: KSPReasonViewFromOptions - Processes command line options to determine if/how a KSPReason is to be viewed.
462: Collective on ksp
464: Input Parameters:
465: . ksp - the KSP object
467: Level: intermediate
469: @*/
470: PetscErrorCode KSPReasonViewFromOptions(KSP ksp)
471: {
472: PetscViewer viewer;
473: PetscBool flg;
474: PetscViewerFormat format;
475: PetscErrorCode ierr;
478: PetscOptionsGetViewer(PetscObjectComm((PetscObject)ksp),((PetscObject)ksp)->options,((PetscObject)ksp)->prefix,"-ksp_converged_reason",&viewer,&format,&flg);
479: if (flg) {
480: KSPReasonView_Internal(ksp, viewer, format);
481: PetscViewerDestroy(&viewer);
482: }
483: return(0);
484: }
486: #include <petscdraw.h>
488: static PetscErrorCode KSPViewEigenvalues_Internal(KSP ksp, PetscBool isExplicit, PetscViewer viewer, PetscViewerFormat format)
489: {
490: PetscReal *r, *c;
491: PetscInt n, i, neig;
492: PetscBool isascii, isdraw;
493: PetscMPIInt rank;
497: MPI_Comm_rank(PetscObjectComm((PetscObject) ksp), &rank);
498: PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWERASCII, &isascii);
499: PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWERDRAW, &isdraw);
500: if (isExplicit) {
501: VecGetSize(ksp->vec_sol,&n);
502: PetscMalloc2(n, &r, n, &c);
503: KSPComputeEigenvaluesExplicitly(ksp, n, r, c);
504: neig = n;
505: } else {
506: PetscInt nits;
508: KSPGetIterationNumber(ksp, &nits);
509: n = nits+2;
510: if (!nits) {PetscViewerASCIIPrintf(viewer, "Zero iterations in solver, cannot approximate any eigenvalues\n");return(0);}
511: PetscMalloc2(n, &r, n, &c);
512: KSPComputeEigenvalues(ksp, n, r, c, &neig);
513: }
514: if (isascii) {
515: PetscViewerASCIIPrintf(viewer, "%s computed eigenvalues\n", isExplicit ? "Explicitly" : "Iteratively");
516: for (i = 0; i < neig; ++i) {
517: if (c[i] >= 0.0) {PetscViewerASCIIPrintf(viewer, "%g + %gi\n", (double) r[i], (double) c[i]);}
518: else {PetscViewerASCIIPrintf(viewer, "%g - %gi\n", (double) r[i], -(double) c[i]);}
519: }
520: } else if (isdraw && !rank) {
521: PetscDraw draw;
522: PetscDrawSP drawsp;
524: if (format == PETSC_VIEWER_DRAW_CONTOUR) {
525: KSPPlotEigenContours_Private(ksp,neig,r,c);
526: } else {
527: if (!ksp->eigviewer) {PetscViewerDrawOpen(PETSC_COMM_SELF,0,isExplicit ? "Explicitly Computed Eigenvalues" : "Iteratively Computed Eigenvalues",PETSC_DECIDE,PETSC_DECIDE,400,400,&ksp->eigviewer);}
528: PetscViewerDrawGetDraw(ksp->eigviewer,0,&draw);
529: PetscDrawSPCreate(draw,1,&drawsp);
530: PetscDrawSPReset(drawsp);
531: for (i = 0; i < neig; ++i) {PetscDrawSPAddPoint(drawsp,r+i,c+i);}
532: PetscDrawSPDraw(drawsp,PETSC_TRUE);
533: PetscDrawSPSave(drawsp);
534: PetscDrawSPDestroy(&drawsp);
535: }
536: }
537: PetscFree2(r, c);
538: return(0);
539: }
541: static PetscErrorCode KSPViewSingularvalues_Internal(KSP ksp, PetscViewer viewer, PetscViewerFormat format)
542: {
543: PetscReal smax, smin;
544: PetscInt nits;
545: PetscBool isascii;
549: PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWERASCII, &isascii);
550: KSPGetIterationNumber(ksp, &nits);
551: if (!nits) {PetscViewerASCIIPrintf(viewer, "Zero iterations in solver, cannot approximate any singular values\n");return(0);}
552: KSPComputeExtremeSingularValues(ksp, &smax, &smin);
553: if (isascii) {PetscViewerASCIIPrintf(viewer, "Iteratively computed extreme singular values: max %g min %g max/min %g\n",(double)smax,(double)smin,(double)(smax/smin));}
554: return(0);
555: }
557: static PetscErrorCode KSPViewFinalResidual_Internal(KSP ksp, PetscViewer viewer, PetscViewerFormat format)
558: {
559: PetscBool isascii;
563: PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWERASCII, &isascii);
564: if (ksp->dscale && !ksp->dscalefix) SETERRQ(PetscObjectComm((PetscObject) ksp), PETSC_ERR_ARG_WRONGSTATE, "Cannot compute final scale with -ksp_diagonal_scale except also with -ksp_diagonal_scale_fix");
565: if (isascii) {
566: Mat A;
567: Vec t;
568: PetscReal norm;
570: PCGetOperators(ksp->pc, &A, NULL);
571: VecDuplicate(ksp->vec_rhs, &t);
572: KSP_MatMult(ksp, A, ksp->vec_sol, t);
573: VecAYPX(t, -1.0, ksp->vec_rhs);
574: VecNorm(t, NORM_2, &norm);
575: VecDestroy(&t);
576: PetscViewerASCIIPrintf(viewer, "KSP final norm of residual %g\n", (double) norm);
577: }
578: return(0);
579: }
581: /*@
582: KSPSolve - Solves linear system.
584: Collective on ksp
586: Parameter:
587: + ksp - iterative context obtained from KSPCreate()
588: . b - the right hand side vector
589: - x - the solution (this may be the same vector as b, then b will be overwritten with answer)
591: Options Database Keys:
592: + -ksp_view_eigenvalues - compute preconditioned operators eigenvalues
593: . -ksp_view_eigenvalues_explicitly - compute the eigenvalues by forming the dense operator and using LAPACK
594: . -ksp_view_mat binary - save matrix to the default binary viewer
595: . -ksp_view_pmat binary - save matrix used to build preconditioner to the default binary viewer
596: . -ksp_view_rhs binary - save right hand side vector to the default binary viewer
597: . -ksp_view_solution binary - save computed solution vector to the default binary viewer
598: (can be read later with src/ksp/examples/tutorials/ex10.c for testing solvers)
599: . -ksp_view_mat_explicit - for matrix-free operators, computes the matrix entries and views them
600: . -ksp_view_preconditioned_operator_explicit - computes the product of the preconditioner and matrix as an explicit matrix and views it
601: . -ksp_converged_reason - print reason for converged or diverged, also prints number of iterations
602: . -ksp_view_final_residual - print 2-norm of true linear system residual at the end of the solution process
603: - -ksp_view - print the ksp data structure at the end of the system solution
605: Notes:
607: If one uses KSPSetDM() then x or b need not be passed. Use KSPGetSolution() to access the solution in this case.
609: The operator is specified with KSPSetOperators().
611: Call KSPGetConvergedReason() to determine if the solver converged or failed and
612: why. The number of iterations can be obtained from KSPGetIterationNumber().
614: If you provide a matrix that has a MatSetNullSpace() and MatSetTransposeNullSpace() this will use that information to solve singular systems
615: in the least squares sense with a norm minimizing solution.
616: $
617: $ A x = b where b = b_p + b_t where b_t is not in the range of A (and hence by the fundamental theorem of linear algebra is in the nullspace(A') see MatSetNullSpace()
618: $
619: $ KSP first removes b_t producing the linear system A x = b_p (which has multiple solutions) and solves this to find the ||x|| minimizing solution (and hence
620: $ it finds the solution x orthogonal to the nullspace(A). The algorithm is simply in each iteration of the Krylov method we remove the nullspace(A) from the search
621: $ direction thus the solution which is a linear combination of the search directions has no component in the nullspace(A).
622: $
623: $ We recommend always using GMRES for such singular systems.
624: $ If nullspace(A) = nullspace(A') (note symmetric matrices always satisfy this property) then both left and right preconditioning will work
625: $ If nullspace(A) != nullspace(A') then left preconditioning will work but right preconditioning may not work (or it may).
627: Developer Note: The reason we cannot always solve nullspace(A) != nullspace(A') systems with right preconditioning is because we need to remove at each iteration
628: the nullspace(AB) from the search direction. While we know the nullspace(A) the nullspace(AB) equals B^-1 times the nullspace(A) but except for trivial preconditioners
629: such as diagonal scaling we cannot apply the inverse of the preconditioner to a vector and thus cannot compute the nullspace(AB).
632: If using a direct method (e.g., via the KSP solver
633: KSPPREONLY and a preconditioner such as PCLU/PCILU),
634: then its=1. See KSPSetTolerances() and KSPConvergedDefault()
635: for more details.
637: Understanding Convergence:
638: The routines KSPMonitorSet(), KSPComputeEigenvalues(), and
639: KSPComputeEigenvaluesExplicitly() provide information on additional
640: options to monitor convergence and print eigenvalue information.
642: Level: beginner
644: .seealso: KSPCreate(), KSPSetUp(), KSPDestroy(), KSPSetTolerances(), KSPConvergedDefault(),
645: KSPSolveTranspose(), KSPGetIterationNumber(), MatNullSpaceCreate(), MatSetNullSpace(), MatSetTransposeNullSpace(), KSP
646: @*/
647: PetscErrorCode KSPSolve(KSP ksp,Vec b,Vec x)
648: {
649: PetscErrorCode ierr;
650: PetscBool flg = PETSC_FALSE,inXisinB=PETSC_FALSE,guess_zero;
651: Mat mat,pmat;
652: MPI_Comm comm;
653: MatNullSpace nullsp;
654: Vec btmp,vec_rhs=0;
660: comm = PetscObjectComm((PetscObject)ksp);
661: if (x && x == b) {
662: if (!ksp->guess_zero) SETERRQ(comm,PETSC_ERR_ARG_INCOMP,"Cannot use x == b with nonzero initial guess");
663: VecDuplicate(b,&x);
664: inXisinB = PETSC_TRUE;
665: }
666: if (b) {
667: PetscObjectReference((PetscObject)b);
668: VecDestroy(&ksp->vec_rhs);
669: ksp->vec_rhs = b;
670: }
671: if (x) {
672: PetscObjectReference((PetscObject)x);
673: VecDestroy(&ksp->vec_sol);
674: ksp->vec_sol = x;
675: }
676: if (ksp->viewPre) {ObjectView((PetscObject) ksp, ksp->viewerPre, ksp->formatPre);}
678: ksp->transpose_solve = PETSC_FALSE;
680: if (ksp->presolve) {(*ksp->presolve)(ksp,ksp->vec_rhs,ksp->vec_sol,ksp->prectx);}
682: /* reset the residual history list if requested */
683: if (ksp->res_hist_reset) ksp->res_hist_len = 0;
685: PetscLogEventBegin(KSP_Solve,ksp,ksp->vec_rhs,ksp->vec_sol,0);
687: if (ksp->guess) {
688: PetscObjectState ostate,state;
690: KSPGuessSetUp(ksp->guess);
691: PetscObjectStateGet((PetscObject)ksp->vec_sol,&ostate);
692: KSPGuessFormGuess(ksp->guess,ksp->vec_rhs,ksp->vec_sol);
693: PetscObjectStateGet((PetscObject)ksp->vec_sol,&state);
694: if (state != ostate) {
695: ksp->guess_zero = PETSC_FALSE;
696: } else {
697: PetscInfo(ksp,"Using zero initial guess since the KSPGuess object did not change the vector\n");
698: ksp->guess_zero = PETSC_TRUE;
699: }
700: }
702: /* KSPSetUp() scales the matrix if needed */
703: KSPSetUp(ksp);
704: KSPSetUpOnBlocks(ksp);
706: VecSetErrorIfLocked(ksp->vec_sol,3);
708: PCGetOperators(ksp->pc,&mat,&pmat);
709: /* diagonal scale RHS if called for */
710: if (ksp->dscale) {
711: VecPointwiseMult(ksp->vec_rhs,ksp->vec_rhs,ksp->diagonal);
712: /* second time in, but matrix was scaled back to original */
713: if (ksp->dscalefix && ksp->dscalefix2) {
714: Mat mat,pmat;
716: PCGetOperators(ksp->pc,&mat,&pmat);
717: MatDiagonalScale(pmat,ksp->diagonal,ksp->diagonal);
718: if (mat != pmat) {MatDiagonalScale(mat,ksp->diagonal,ksp->diagonal);}
719: }
721: /* scale initial guess */
722: if (!ksp->guess_zero) {
723: if (!ksp->truediagonal) {
724: VecDuplicate(ksp->diagonal,&ksp->truediagonal);
725: VecCopy(ksp->diagonal,ksp->truediagonal);
726: VecReciprocal(ksp->truediagonal);
727: }
728: VecPointwiseMult(ksp->vec_sol,ksp->vec_sol,ksp->truediagonal);
729: }
730: }
731: PCPreSolve(ksp->pc,ksp);
733: if (ksp->guess_zero) { VecSet(ksp->vec_sol,0.0);}
734: if (ksp->guess_knoll) { /* The Knoll trick is independent on the KSPGuess specified */
735: PCApply(ksp->pc,ksp->vec_rhs,ksp->vec_sol);
736: KSP_RemoveNullSpace(ksp,ksp->vec_sol);
737: ksp->guess_zero = PETSC_FALSE;
738: }
740: /* can we mark the initial guess as zero for this solve? */
741: guess_zero = ksp->guess_zero;
742: if (!ksp->guess_zero) {
743: PetscReal norm;
745: VecNormAvailable(ksp->vec_sol,NORM_2,&flg,&norm);
746: if (flg && !norm) ksp->guess_zero = PETSC_TRUE;
747: }
748: MatGetTransposeNullSpace(pmat,&nullsp);
749: if (nullsp) {
750: VecDuplicate(ksp->vec_rhs,&btmp);
751: VecCopy(ksp->vec_rhs,btmp);
752: MatNullSpaceRemove(nullsp,btmp);
753: vec_rhs = ksp->vec_rhs;
754: ksp->vec_rhs = btmp;
755: }
756: VecLockReadPush(ksp->vec_rhs);
757: if (ksp->reason == KSP_DIVERGED_PC_FAILED) {
758: VecSetInf(ksp->vec_sol);
759: }
760: (*ksp->ops->solve)(ksp);
762: VecLockReadPop(ksp->vec_rhs);
763: if (nullsp) {
764: ksp->vec_rhs = vec_rhs;
765: VecDestroy(&btmp);
766: }
768: ksp->guess_zero = guess_zero;
770: if (!ksp->reason) SETERRQ(comm,PETSC_ERR_PLIB,"Internal error, solver returned without setting converged reason");
771: ksp->totalits += ksp->its;
773: if (ksp->viewReason) {KSPReasonView_Internal(ksp, ksp->viewerReason, ksp->formatReason);}
774: PCPostSolve(ksp->pc,ksp);
776: /* diagonal scale solution if called for */
777: if (ksp->dscale) {
778: VecPointwiseMult(ksp->vec_sol,ksp->vec_sol,ksp->diagonal);
779: /* unscale right hand side and matrix */
780: if (ksp->dscalefix) {
781: Mat mat,pmat;
783: VecReciprocal(ksp->diagonal);
784: VecPointwiseMult(ksp->vec_rhs,ksp->vec_rhs,ksp->diagonal);
785: PCGetOperators(ksp->pc,&mat,&pmat);
786: MatDiagonalScale(pmat,ksp->diagonal,ksp->diagonal);
787: if (mat != pmat) {MatDiagonalScale(mat,ksp->diagonal,ksp->diagonal);}
788: VecReciprocal(ksp->diagonal);
789: ksp->dscalefix2 = PETSC_TRUE;
790: }
791: }
792: PetscLogEventEnd(KSP_Solve,ksp,ksp->vec_rhs,ksp->vec_sol,0);
793: if (ksp->guess) {
794: KSPGuessUpdate(ksp->guess,ksp->vec_rhs,ksp->vec_sol);
795: }
796: if (ksp->postsolve) {
797: (*ksp->postsolve)(ksp,ksp->vec_rhs,ksp->vec_sol,ksp->postctx);
798: }
800: PCGetOperators(ksp->pc,&mat,&pmat);
801: if (ksp->viewEV) {KSPViewEigenvalues_Internal(ksp, PETSC_FALSE, ksp->viewerEV, ksp->formatEV);}
802: if (ksp->viewEVExp) {KSPViewEigenvalues_Internal(ksp, PETSC_TRUE, ksp->viewerEVExp, ksp->formatEVExp);}
803: if (ksp->viewSV) {KSPViewSingularvalues_Internal(ksp, ksp->viewerSV, ksp->formatSV);}
804: if (ksp->viewFinalRes) {KSPViewFinalResidual_Internal(ksp, ksp->viewerFinalRes, ksp->formatFinalRes);}
805: if (ksp->viewMat) {ObjectView((PetscObject) mat, ksp->viewerMat, ksp->formatMat);}
806: if (ksp->viewPMat) {ObjectView((PetscObject) pmat, ksp->viewerPMat, ksp->formatPMat);}
807: if (ksp->viewRhs) {ObjectView((PetscObject) ksp->vec_rhs, ksp->viewerRhs, ksp->formatRhs);}
808: if (ksp->viewSol) {ObjectView((PetscObject) ksp->vec_sol, ksp->viewerSol, ksp->formatSol);}
809: if (ksp->view) {ObjectView((PetscObject) ksp, ksp->viewer, ksp->format);}
810: if (ksp->viewDScale) {ObjectView((PetscObject) ksp->diagonal, ksp->viewerDScale, ksp->formatDScale);}
811: if (ksp->viewMatExp) {
812: Mat A, B;
814: PCGetOperators(ksp->pc, &A, NULL);
815: MatComputeOperator(A, MATAIJ, &B);
816: ObjectView((PetscObject) B, ksp->viewerMatExp, ksp->formatMatExp);
817: MatDestroy(&B);
818: }
819: if (ksp->viewPOpExp) {
820: Mat B;
822: KSPComputeOperator(ksp, MATAIJ, &B);
823: ObjectView((PetscObject) B, ksp->viewerPOpExp, ksp->formatPOpExp);
824: MatDestroy(&B);
825: }
827: if (inXisinB) {
828: VecCopy(x,b);
829: VecDestroy(&x);
830: }
831: PetscObjectSAWsBlock((PetscObject)ksp);
832: if (ksp->errorifnotconverged && ksp->reason < 0 && ksp->reason != KSP_DIVERGED_ITS) SETERRQ1(comm,PETSC_ERR_NOT_CONVERGED,"KSPSolve has not converged, reason %s",KSPConvergedReasons[ksp->reason]);
833: return(0);
834: }
836: /*@
837: KSPSolveTranspose - Solves the transpose of a linear system.
839: Collective on ksp
841: Input Parameter:
842: + ksp - iterative context obtained from KSPCreate()
843: . b - right hand side vector
844: - x - solution vector
846: Notes:
847: For complex numbers this solve the non-Hermitian transpose system.
849: This currently does NOT correctly use the null space of the operator and its transpose for solving singular systems.
851: Developer Notes:
852: We need to implement a KSPSolveHermitianTranspose()
854: Level: developer
856: .seealso: KSPCreate(), KSPSetUp(), KSPDestroy(), KSPSetTolerances(), KSPConvergedDefault(),
857: KSPSolve(), KSP
858: @*/
860: PetscErrorCode KSPSolveTranspose(KSP ksp,Vec b,Vec x)
861: {
863: PetscBool inXisinB=PETSC_FALSE;
864: Vec vec_rhs = 0,btmp;
865: Mat mat,pmat;
866: MatNullSpace nullsp;
872: if (x == b) {
873: VecDuplicate(b,&x);
874: inXisinB = PETSC_TRUE;
875: }
876: PetscObjectReference((PetscObject)b);
877: PetscObjectReference((PetscObject)x);
878: VecDestroy(&ksp->vec_rhs);
879: VecDestroy(&ksp->vec_sol);
881: ksp->vec_rhs = b;
882: ksp->vec_sol = x;
883: ksp->transpose_solve = PETSC_TRUE;
885: if (ksp->presolve) {(*ksp->presolve)(ksp,ksp->vec_rhs,ksp->vec_sol,ksp->prectx);}
887: PetscLogEventBegin(KSP_SolveTranspose,ksp,ksp->vec_rhs,ksp->vec_sol,0);
888: if (ksp->guess) {
889: PetscObjectState ostate,state;
891: KSPGuessSetUp(ksp->guess);
892: PetscObjectStateGet((PetscObject)ksp->vec_sol,&ostate);
893: KSPGuessFormGuess(ksp->guess,ksp->vec_rhs,ksp->vec_sol);
894: PetscObjectStateGet((PetscObject)ksp->vec_sol,&state);
895: if (state != ostate) {
896: ksp->guess_zero = PETSC_FALSE;
897: } else {
898: PetscInfo(ksp,"Using zero initial guess since the KSPGuess object did not change the vector\n");
899: ksp->guess_zero = PETSC_TRUE;
900: }
901: }
903: KSPSetUp(ksp);
904: KSPSetUpOnBlocks(ksp);
905: if (ksp->guess_zero) { VecSet(ksp->vec_sol,0.0);}
907: PCGetOperators(ksp->pc,&mat,&pmat);
908: MatGetNullSpace(pmat,&nullsp);
909: if (nullsp) {
910: VecDuplicate(ksp->vec_rhs,&btmp);
911: VecCopy(ksp->vec_rhs,btmp);
912: MatNullSpaceRemove(nullsp,btmp);
913: vec_rhs = ksp->vec_rhs;
914: ksp->vec_rhs = btmp;
915: }
917: (*ksp->ops->solve)(ksp);
918: ksp->totalits += ksp->its;
919: if (nullsp) {
920: ksp->vec_rhs = vec_rhs;
921: VecDestroy(&btmp);
922: }
923: if (!ksp->reason) SETERRQ(PetscObjectComm((PetscObject)ksp),PETSC_ERR_PLIB,"Internal error, solver returned without setting converged reason");
924: if (ksp->viewReason) {KSPReasonView_Internal(ksp, ksp->viewerReason, ksp->formatReason);}
925: PetscLogEventEnd(KSP_SolveTranspose,ksp,ksp->vec_rhs,ksp->vec_sol,0);
926: if (ksp->guess) {
927: KSPGuessUpdate(ksp->guess,ksp->vec_rhs,ksp->vec_sol);
928: }
929: if (ksp->postsolve) {
930: (*ksp->postsolve)(ksp,ksp->vec_rhs,ksp->vec_sol,ksp->postctx);
931: }
933: if (ksp->viewMat) {ObjectView((PetscObject) mat, ksp->viewerMat, ksp->formatMat);}
934: if (ksp->viewPMat) {ObjectView((PetscObject) pmat, ksp->viewerPMat, ksp->formatPMat);}
935: if (ksp->viewRhs) {ObjectView((PetscObject) ksp->vec_rhs, ksp->viewerRhs, ksp->formatRhs);}
936: if (ksp->viewSol) {ObjectView((PetscObject) ksp->vec_sol, ksp->viewerSol, ksp->formatSol);}
937: if (ksp->view) {ObjectView((PetscObject) ksp, ksp->viewer, ksp->format);}
939: if (inXisinB) {
940: VecCopy(x,b);
941: VecDestroy(&x);
942: }
943: if (ksp->errorifnotconverged && ksp->reason < 0) SETERRQ(PetscObjectComm((PetscObject)ksp),PETSC_ERR_NOT_CONVERGED,"KSPSolve has not converged");
944: return(0);
945: }
947: /*@
948: KSPResetViewers - Resets all the viewers set from the options database during KSPSetFromOptions()
950: Collective on ksp
952: Input Parameter:
953: . ksp - iterative context obtained from KSPCreate()
955: Level: beginner
957: .seealso: KSPCreate(), KSPSetUp(), KSPSolve(), KSPSetFromOptions(), KSP
958: @*/
959: PetscErrorCode KSPResetViewers(KSP ksp)
960: {
965: if (!ksp) return(0);
966: PetscViewerDestroy(&ksp->viewer);
967: PetscViewerDestroy(&ksp->viewerPre);
968: PetscViewerDestroy(&ksp->viewerReason);
969: PetscViewerDestroy(&ksp->viewerMat);
970: PetscViewerDestroy(&ksp->viewerPMat);
971: PetscViewerDestroy(&ksp->viewerRhs);
972: PetscViewerDestroy(&ksp->viewerSol);
973: PetscViewerDestroy(&ksp->viewerMatExp);
974: PetscViewerDestroy(&ksp->viewerEV);
975: PetscViewerDestroy(&ksp->viewerSV);
976: PetscViewerDestroy(&ksp->viewerEVExp);
977: PetscViewerDestroy(&ksp->viewerFinalRes);
978: PetscViewerDestroy(&ksp->viewerPOpExp);
979: PetscViewerDestroy(&ksp->viewerDScale);
980: ksp->view = PETSC_FALSE;
981: ksp->viewPre = PETSC_FALSE;
982: ksp->viewReason = PETSC_FALSE;
983: ksp->viewMat = PETSC_FALSE;
984: ksp->viewPMat = PETSC_FALSE;
985: ksp->viewRhs = PETSC_FALSE;
986: ksp->viewSol = PETSC_FALSE;
987: ksp->viewMatExp = PETSC_FALSE;
988: ksp->viewEV = PETSC_FALSE;
989: ksp->viewSV = PETSC_FALSE;
990: ksp->viewEVExp = PETSC_FALSE;
991: ksp->viewFinalRes = PETSC_FALSE;
992: ksp->viewPOpExp = PETSC_FALSE;
993: ksp->viewDScale = PETSC_FALSE;
994: return(0);
995: }
997: /*@
998: KSPReset - Resets a KSP context to the kspsetupcalled = 0 state and removes any allocated Vecs and Mats
1000: Collective on ksp
1002: Input Parameter:
1003: . ksp - iterative context obtained from KSPCreate()
1005: Level: beginner
1007: .seealso: KSPCreate(), KSPSetUp(), KSPSolve(), KSP
1008: @*/
1009: PetscErrorCode KSPReset(KSP ksp)
1010: {
1015: if (!ksp) return(0);
1016: if (ksp->ops->reset) {
1017: (*ksp->ops->reset)(ksp);
1018: }
1019: if (ksp->pc) {PCReset(ksp->pc);}
1020: if (ksp->guess) {
1021: KSPGuess guess = ksp->guess;
1022: if (guess->ops->reset) { (*guess->ops->reset)(guess); }
1023: }
1024: VecDestroyVecs(ksp->nwork,&ksp->work);
1025: VecDestroy(&ksp->vec_rhs);
1026: VecDestroy(&ksp->vec_sol);
1027: VecDestroy(&ksp->diagonal);
1028: VecDestroy(&ksp->truediagonal);
1030: KSPResetViewers(ksp);
1032: ksp->setupstage = KSP_SETUP_NEW;
1033: return(0);
1034: }
1036: /*@
1037: KSPDestroy - Destroys KSP context.
1039: Collective on ksp
1041: Input Parameter:
1042: . ksp - iterative context obtained from KSPCreate()
1044: Level: beginner
1046: .seealso: KSPCreate(), KSPSetUp(), KSPSolve(), KSP
1047: @*/
1048: PetscErrorCode KSPDestroy(KSP *ksp)
1049: {
1051: PC pc;
1054: if (!*ksp) return(0);
1056: if (--((PetscObject)(*ksp))->refct > 0) {*ksp = 0; return(0);}
1058: PetscObjectSAWsViewOff((PetscObject)*ksp);
1060: /*
1061: Avoid a cascading call to PCReset(ksp->pc) from the following call:
1062: PCReset() shouldn't be called from KSPDestroy() as it is unprotected by pc's
1063: refcount (and may be shared, e.g., by other ksps).
1064: */
1065: pc = (*ksp)->pc;
1066: (*ksp)->pc = NULL;
1067: KSPReset((*ksp));
1068: (*ksp)->pc = pc;
1069: if ((*ksp)->ops->destroy) {(*(*ksp)->ops->destroy)(*ksp);}
1071: KSPGuessDestroy(&(*ksp)->guess);
1072: DMDestroy(&(*ksp)->dm);
1073: PCDestroy(&(*ksp)->pc);
1074: PetscFree((*ksp)->res_hist_alloc);
1075: if ((*ksp)->convergeddestroy) {
1076: (*(*ksp)->convergeddestroy)((*ksp)->cnvP);
1077: }
1078: KSPMonitorCancel((*ksp));
1079: PetscViewerDestroy(&(*ksp)->eigviewer);
1080: PetscHeaderDestroy(ksp);
1081: return(0);
1082: }
1084: /*@
1085: KSPSetPCSide - Sets the preconditioning side.
1087: Logically Collective on ksp
1089: Input Parameter:
1090: . ksp - iterative context obtained from KSPCreate()
1092: Output Parameter:
1093: . side - the preconditioning side, where side is one of
1094: .vb
1095: PC_LEFT - left preconditioning (default)
1096: PC_RIGHT - right preconditioning
1097: PC_SYMMETRIC - symmetric preconditioning
1098: .ve
1100: Options Database Keys:
1101: . -ksp_pc_side <right,left,symmetric>
1103: Notes:
1104: Left preconditioning is used by default for most Krylov methods except KSPFGMRES which only supports right preconditioning.
1106: For methods changing the side of the preconditioner changes the norm type that is used, see KSPSetNormType().
1108: Symmetric preconditioning is currently available only for the KSPQCG method. Note, however, that
1109: symmetric preconditioning can be emulated by using either right or left
1110: preconditioning and a pre or post processing step.
1112: Setting the PC side often affects the default norm type. See KSPSetNormType() for details.
1114: Level: intermediate
1116: .seealso: KSPGetPCSide(), KSPSetNormType(), KSPGetNormType(), KSP
1117: @*/
1118: PetscErrorCode KSPSetPCSide(KSP ksp,PCSide side)
1119: {
1123: ksp->pc_side = ksp->pc_side_set = side;
1124: return(0);
1125: }
1127: /*@
1128: KSPGetPCSide - Gets the preconditioning side.
1130: Not Collective
1132: Input Parameter:
1133: . ksp - iterative context obtained from KSPCreate()
1135: Output Parameter:
1136: . side - the preconditioning side, where side is one of
1137: .vb
1138: PC_LEFT - left preconditioning (default)
1139: PC_RIGHT - right preconditioning
1140: PC_SYMMETRIC - symmetric preconditioning
1141: .ve
1143: Level: intermediate
1145: .seealso: KSPSetPCSide(), KSP
1146: @*/
1147: PetscErrorCode KSPGetPCSide(KSP ksp,PCSide *side)
1148: {
1154: KSPSetUpNorms_Private(ksp,PETSC_TRUE,&ksp->normtype,&ksp->pc_side);
1155: *side = ksp->pc_side;
1156: return(0);
1157: }
1159: /*@
1160: KSPGetTolerances - Gets the relative, absolute, divergence, and maximum
1161: iteration tolerances used by the default KSP convergence tests.
1163: Not Collective
1165: Input Parameter:
1166: . ksp - the Krylov subspace context
1168: Output Parameters:
1169: + rtol - the relative convergence tolerance
1170: . abstol - the absolute convergence tolerance
1171: . dtol - the divergence tolerance
1172: - maxits - maximum number of iterations
1174: Notes:
1175: The user can specify NULL for any parameter that is not needed.
1177: Level: intermediate
1179: maximum, iterations
1181: .seealso: KSPSetTolerances(), KSP
1182: @*/
1183: PetscErrorCode KSPGetTolerances(KSP ksp,PetscReal *rtol,PetscReal *abstol,PetscReal *dtol,PetscInt *maxits)
1184: {
1187: if (abstol) *abstol = ksp->abstol;
1188: if (rtol) *rtol = ksp->rtol;
1189: if (dtol) *dtol = ksp->divtol;
1190: if (maxits) *maxits = ksp->max_it;
1191: return(0);
1192: }
1194: /*@
1195: KSPSetTolerances - Sets the relative, absolute, divergence, and maximum
1196: iteration tolerances used by the default KSP convergence testers.
1198: Logically Collective on ksp
1200: Input Parameters:
1201: + ksp - the Krylov subspace context
1202: . rtol - the relative convergence tolerance, relative decrease in the (possibly preconditioned) residual norm
1203: . abstol - the absolute convergence tolerance absolute size of the (possibly preconditioned) residual norm
1204: . dtol - the divergence tolerance, amount (possibly preconditioned) residual norm can increase before KSPConvergedDefault() concludes that the method is diverging
1205: - maxits - maximum number of iterations to use
1207: Options Database Keys:
1208: + -ksp_atol <abstol> - Sets abstol
1209: . -ksp_rtol <rtol> - Sets rtol
1210: . -ksp_divtol <dtol> - Sets dtol
1211: - -ksp_max_it <maxits> - Sets maxits
1213: Notes:
1214: Use PETSC_DEFAULT to retain the default value of any of the tolerances.
1216: See KSPConvergedDefault() for details how these parameters are used in the default convergence test. See also KSPSetConvergenceTest()
1217: for setting user-defined stopping criteria.
1219: Level: intermediate
1221: convergence, maximum, iterations
1223: .seealso: KSPGetTolerances(), KSPConvergedDefault(), KSPSetConvergenceTest(), KSP
1224: @*/
1225: PetscErrorCode KSPSetTolerances(KSP ksp,PetscReal rtol,PetscReal abstol,PetscReal dtol,PetscInt maxits)
1226: {
1234: if (rtol != PETSC_DEFAULT) {
1235: 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);
1236: ksp->rtol = rtol;
1237: }
1238: if (abstol != PETSC_DEFAULT) {
1239: if (abstol < 0.0) SETERRQ1(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_OUTOFRANGE,"Absolute tolerance %g must be non-negative",(double)abstol);
1240: ksp->abstol = abstol;
1241: }
1242: if (dtol != PETSC_DEFAULT) {
1243: if (dtol < 0.0) SETERRQ1(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_OUTOFRANGE,"Divergence tolerance %g must be larger than 1.0",(double)dtol);
1244: ksp->divtol = dtol;
1245: }
1246: if (maxits != PETSC_DEFAULT) {
1247: if (maxits < 0) SETERRQ1(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of iterations %D must be non-negative",maxits);
1248: ksp->max_it = maxits;
1249: }
1250: return(0);
1251: }
1253: /*@
1254: KSPSetInitialGuessNonzero - Tells the iterative solver that the
1255: initial guess is nonzero; otherwise KSP assumes the initial guess
1256: is to be zero (and thus zeros it out before solving).
1258: Logically Collective on ksp
1260: Input Parameters:
1261: + ksp - iterative context obtained from KSPCreate()
1262: - flg - PETSC_TRUE indicates the guess is non-zero, PETSC_FALSE indicates the guess is zero
1264: Options database keys:
1265: . -ksp_initial_guess_nonzero : use nonzero initial guess; this takes an optional truth value (0/1/no/yes/true/false)
1267: Level: beginner
1269: Notes:
1270: If this is not called the X vector is zeroed in the call to KSPSolve().
1272: .seealso: KSPGetInitialGuessNonzero(), KSPSetGuessType(), KSPGuessType, KSP
1273: @*/
1274: PetscErrorCode KSPSetInitialGuessNonzero(KSP ksp,PetscBool flg)
1275: {
1279: ksp->guess_zero = (PetscBool) !(int)flg;
1280: return(0);
1281: }
1283: /*@
1284: KSPGetInitialGuessNonzero - Determines whether the KSP solver is using
1285: a zero initial guess.
1287: Not Collective
1289: Input Parameter:
1290: . ksp - iterative context obtained from KSPCreate()
1292: Output Parameter:
1293: . flag - PETSC_TRUE if guess is nonzero, else PETSC_FALSE
1295: Level: intermediate
1297: .seealso: KSPSetInitialGuessNonzero(), KSP
1298: @*/
1299: PetscErrorCode KSPGetInitialGuessNonzero(KSP ksp,PetscBool *flag)
1300: {
1304: if (ksp->guess_zero) *flag = PETSC_FALSE;
1305: else *flag = PETSC_TRUE;
1306: return(0);
1307: }
1309: /*@
1310: KSPSetErrorIfNotConverged - Causes KSPSolve() to generate an error if the solver has not converged.
1312: Logically Collective on ksp
1314: Input Parameters:
1315: + ksp - iterative context obtained from KSPCreate()
1316: - flg - PETSC_TRUE indicates you want the error generated
1318: Options database keys:
1319: . -ksp_error_if_not_converged : this takes an optional truth value (0/1/no/yes/true/false)
1321: Level: intermediate
1323: Notes:
1324: Normally PETSc continues if a linear solver fails to converge, you can call KSPGetConvergedReason() after a KSPSolve()
1325: to determine if it has converged.
1328: .seealso: KSPGetErrorIfNotConverged(), KSP
1329: @*/
1330: PetscErrorCode KSPSetErrorIfNotConverged(KSP ksp,PetscBool flg)
1331: {
1335: ksp->errorifnotconverged = flg;
1336: return(0);
1337: }
1339: /*@
1340: KSPGetErrorIfNotConverged - Will KSPSolve() generate an error if the solver does not converge?
1342: Not Collective
1344: Input Parameter:
1345: . ksp - iterative context obtained from KSPCreate()
1347: Output Parameter:
1348: . flag - PETSC_TRUE if it will generate an error, else PETSC_FALSE
1350: Level: intermediate
1352: .seealso: KSPSetErrorIfNotConverged(), KSP
1353: @*/
1354: PetscErrorCode KSPGetErrorIfNotConverged(KSP ksp,PetscBool *flag)
1355: {
1359: *flag = ksp->errorifnotconverged;
1360: return(0);
1361: }
1363: /*@
1364: KSPSetInitialGuessKnoll - Tells the iterative solver to use PCApply(pc,b,..) to compute the initial guess (The Knoll trick)
1366: Logically Collective on ksp
1368: Input Parameters:
1369: + ksp - iterative context obtained from KSPCreate()
1370: - flg - PETSC_TRUE or PETSC_FALSE
1372: Level: advanced
1374: Developer Note: the Knoll trick is not currently implemented using the KSPGuess class
1376: .seealso: KSPGetInitialGuessKnoll(), KSPSetInitialGuessNonzero(), KSPGetInitialGuessNonzero(), KSP
1377: @*/
1378: PetscErrorCode KSPSetInitialGuessKnoll(KSP ksp,PetscBool flg)
1379: {
1383: ksp->guess_knoll = flg;
1384: return(0);
1385: }
1387: /*@
1388: KSPGetInitialGuessKnoll - Determines whether the KSP solver is using the Knoll trick (using PCApply(pc,b,...) to compute
1389: the initial guess
1391: Not Collective
1393: Input Parameter:
1394: . ksp - iterative context obtained from KSPCreate()
1396: Output Parameter:
1397: . flag - PETSC_TRUE if using Knoll trick, else PETSC_FALSE
1399: Level: advanced
1401: .seealso: KSPSetInitialGuessKnoll(), KSPSetInitialGuessNonzero(), KSPGetInitialGuessNonzero(), KSP
1402: @*/
1403: PetscErrorCode KSPGetInitialGuessKnoll(KSP ksp,PetscBool *flag)
1404: {
1408: *flag = ksp->guess_knoll;
1409: return(0);
1410: }
1412: /*@
1413: KSPGetComputeSingularValues - Gets the flag indicating whether the extreme singular
1414: values will be calculated via a Lanczos or Arnoldi process as the linear
1415: system is solved.
1417: Not Collective
1419: Input Parameter:
1420: . ksp - iterative context obtained from KSPCreate()
1422: Output Parameter:
1423: . flg - PETSC_TRUE or PETSC_FALSE
1425: Options Database Key:
1426: . -ksp_monitor_singular_value - Activates KSPSetComputeSingularValues()
1428: Notes:
1429: Currently this option is not valid for all iterative methods.
1431: Many users may just want to use the monitoring routine
1432: KSPMonitorSingularValue() (which can be set with option -ksp_monitor_singular_value)
1433: to print the singular values at each iteration of the linear solve.
1435: Level: advanced
1437: .seealso: KSPComputeExtremeSingularValues(), KSPMonitorSingularValue(), KSP
1438: @*/
1439: PetscErrorCode KSPGetComputeSingularValues(KSP ksp,PetscBool *flg)
1440: {
1444: *flg = ksp->calc_sings;
1445: return(0);
1446: }
1448: /*@
1449: KSPSetComputeSingularValues - Sets a flag so that the extreme singular
1450: values will be calculated via a Lanczos or Arnoldi process as the linear
1451: system is solved.
1453: Logically Collective on ksp
1455: Input Parameters:
1456: + ksp - iterative context obtained from KSPCreate()
1457: - flg - PETSC_TRUE or PETSC_FALSE
1459: Options Database Key:
1460: . -ksp_monitor_singular_value - Activates KSPSetComputeSingularValues()
1462: Notes:
1463: Currently this option is not valid for all iterative methods.
1465: Many users may just want to use the monitoring routine
1466: KSPMonitorSingularValue() (which can be set with option -ksp_monitor_singular_value)
1467: to print the singular values at each iteration of the linear solve.
1469: Level: advanced
1471: .seealso: KSPComputeExtremeSingularValues(), KSPMonitorSingularValue(), KSP
1472: @*/
1473: PetscErrorCode KSPSetComputeSingularValues(KSP ksp,PetscBool flg)
1474: {
1478: ksp->calc_sings = flg;
1479: return(0);
1480: }
1482: /*@
1483: KSPGetComputeEigenvalues - Gets the flag indicating that the extreme eigenvalues
1484: values will be calculated via a Lanczos or Arnoldi process as the linear
1485: system is solved.
1487: Not Collective
1489: Input Parameter:
1490: . ksp - iterative context obtained from KSPCreate()
1492: Output Parameter:
1493: . flg - PETSC_TRUE or PETSC_FALSE
1495: Notes:
1496: Currently this option is not valid for all iterative methods.
1498: Level: advanced
1500: .seealso: KSPComputeEigenvalues(), KSPComputeEigenvaluesExplicitly(), KSP
1501: @*/
1502: PetscErrorCode KSPGetComputeEigenvalues(KSP ksp,PetscBool *flg)
1503: {
1507: *flg = ksp->calc_sings;
1508: return(0);
1509: }
1511: /*@
1512: KSPSetComputeEigenvalues - Sets a flag so that the extreme eigenvalues
1513: values will be calculated via a Lanczos or Arnoldi process as the linear
1514: system is solved.
1516: Logically Collective on ksp
1518: Input Parameters:
1519: + ksp - iterative context obtained from KSPCreate()
1520: - flg - PETSC_TRUE or PETSC_FALSE
1522: Notes:
1523: Currently this option is not valid for all iterative methods.
1525: Level: advanced
1527: .seealso: KSPComputeEigenvalues(), KSPComputeEigenvaluesExplicitly(), KSP
1528: @*/
1529: PetscErrorCode KSPSetComputeEigenvalues(KSP ksp,PetscBool flg)
1530: {
1534: ksp->calc_sings = flg;
1535: return(0);
1536: }
1538: /*@
1539: KSPSetComputeRitz - Sets a flag so that the Ritz or harmonic Ritz pairs
1540: will be calculated via a Lanczos or Arnoldi process as the linear
1541: system is solved.
1543: Logically Collective on ksp
1545: Input Parameters:
1546: + ksp - iterative context obtained from KSPCreate()
1547: - flg - PETSC_TRUE or PETSC_FALSE
1549: Notes:
1550: Currently this option is only valid for the GMRES method.
1552: Level: advanced
1554: .seealso: KSPComputeRitz(), KSP
1555: @*/
1556: PetscErrorCode KSPSetComputeRitz(KSP ksp, PetscBool flg)
1557: {
1561: ksp->calc_ritz = flg;
1562: return(0);
1563: }
1565: /*@
1566: KSPGetRhs - Gets the right-hand-side vector for the linear system to
1567: be solved.
1569: Not Collective
1571: Input Parameter:
1572: . ksp - iterative context obtained from KSPCreate()
1574: Output Parameter:
1575: . r - right-hand-side vector
1577: Level: developer
1579: .seealso: KSPGetSolution(), KSPSolve(), KSP
1580: @*/
1581: PetscErrorCode KSPGetRhs(KSP ksp,Vec *r)
1582: {
1586: *r = ksp->vec_rhs;
1587: return(0);
1588: }
1590: /*@
1591: KSPGetSolution - Gets the location of the solution for the
1592: linear system to be solved. Note that this may not be where the solution
1593: is stored during the iterative process; see KSPBuildSolution().
1595: Not Collective
1597: Input Parameters:
1598: . ksp - iterative context obtained from KSPCreate()
1600: Output Parameters:
1601: . v - solution vector
1603: Level: developer
1605: .seealso: KSPGetRhs(), KSPBuildSolution(), KSPSolve(), KSP
1606: @*/
1607: PetscErrorCode KSPGetSolution(KSP ksp,Vec *v)
1608: {
1612: *v = ksp->vec_sol;
1613: return(0);
1614: }
1616: /*@
1617: KSPSetPC - Sets the preconditioner to be used to calculate the
1618: application of the preconditioner on a vector.
1620: Collective on ksp
1622: Input Parameters:
1623: + ksp - iterative context obtained from KSPCreate()
1624: - pc - the preconditioner object
1626: Notes:
1627: Use KSPGetPC() to retrieve the preconditioner context (for example,
1628: to free it at the end of the computations).
1630: Level: developer
1632: .seealso: KSPGetPC(), KSP
1633: @*/
1634: PetscErrorCode KSPSetPC(KSP ksp,PC pc)
1635: {
1642: PetscObjectReference((PetscObject)pc);
1643: PCDestroy(&ksp->pc);
1644: ksp->pc = pc;
1645: PetscLogObjectParent((PetscObject)ksp,(PetscObject)ksp->pc);
1646: return(0);
1647: }
1649: /*@
1650: KSPGetPC - Returns a pointer to the preconditioner context
1651: set with KSPSetPC().
1653: Not Collective
1655: Input Parameters:
1656: . ksp - iterative context obtained from KSPCreate()
1658: Output Parameter:
1659: . pc - preconditioner context
1661: Level: developer
1663: .seealso: KSPSetPC(), KSP
1664: @*/
1665: PetscErrorCode KSPGetPC(KSP ksp,PC *pc)
1666: {
1672: if (!ksp->pc) {
1673: PCCreate(PetscObjectComm((PetscObject)ksp),&ksp->pc);
1674: PetscObjectIncrementTabLevel((PetscObject)ksp->pc,(PetscObject)ksp,0);
1675: PetscLogObjectParent((PetscObject)ksp,(PetscObject)ksp->pc);
1676: PetscObjectSetOptions((PetscObject)ksp->pc,((PetscObject)ksp)->options);
1677: }
1678: *pc = ksp->pc;
1679: return(0);
1680: }
1682: /*@
1683: KSPMonitor - runs the user provided monitor routines, if they exist
1685: Collective on ksp
1687: Input Parameters:
1688: + ksp - iterative context obtained from KSPCreate()
1689: . it - iteration number
1690: - rnorm - relative norm of the residual
1692: Notes:
1693: This routine is called by the KSP implementations.
1694: It does not typically need to be called by the user.
1696: Level: developer
1698: .seealso: KSPMonitorSet()
1699: @*/
1700: PetscErrorCode KSPMonitor(KSP ksp,PetscInt it,PetscReal rnorm)
1701: {
1702: PetscInt i, n = ksp->numbermonitors;
1706: for (i=0; i<n; i++) {
1707: (*ksp->monitor[i])(ksp,it,rnorm,ksp->monitorcontext[i]);
1708: }
1709: return(0);
1710: }
1712: /*
1714: Checks if two monitors are identical; if they are then it destroys the new one
1715: */
1716: PetscErrorCode PetscMonitorCompare(PetscErrorCode (*nmon)(void),void *nmctx,PetscErrorCode (*nmdestroy)(void**),PetscErrorCode (*mon)(void),void *mctx,PetscErrorCode (*mdestroy)(void**),PetscBool *identical)
1717: {
1718: *identical = PETSC_FALSE;
1719: if (nmon == mon && nmdestroy == mdestroy) {
1720: if (nmctx == mctx) *identical = PETSC_TRUE;
1721: else if (nmdestroy == (PetscErrorCode (*)(void**)) PetscViewerAndFormatDestroy) {
1722: PetscViewerAndFormat *old = (PetscViewerAndFormat*)mctx, *newo = (PetscViewerAndFormat*)nmctx;
1723: if (old->viewer == newo->viewer && old->format == newo->format) *identical = PETSC_TRUE;
1724: }
1725: if (*identical) {
1726: if (mdestroy) {
1728: (*mdestroy)(&nmctx);
1729: }
1730: }
1731: }
1732: return(0);
1733: }
1735: /*@C
1736: KSPMonitorSet - Sets an ADDITIONAL function to be called at every iteration to monitor
1737: the residual/error etc.
1739: Logically Collective on ksp
1741: Input Parameters:
1742: + ksp - iterative context obtained from KSPCreate()
1743: . monitor - pointer to function (if this is NULL, it turns off monitoring
1744: . mctx - [optional] context for private data for the
1745: monitor routine (use NULL if no context is desired)
1746: - monitordestroy - [optional] routine that frees monitor context
1747: (may be NULL)
1749: Calling Sequence of monitor:
1750: $ monitor (KSP ksp, PetscInt it, PetscReal rnorm, void *mctx)
1752: + ksp - iterative context obtained from KSPCreate()
1753: . it - iteration number
1754: . rnorm - (estimated) 2-norm of (preconditioned) residual
1755: - mctx - optional monitoring context, as set by KSPMonitorSet()
1757: Options Database Keys:
1758: + -ksp_monitor - sets KSPMonitorDefault()
1759: . -ksp_monitor_true_residual - sets KSPMonitorTrueResidualNorm()
1760: . -ksp_monitor_max - sets KSPMonitorTrueResidualMaxNorm()
1761: . -ksp_monitor_lg_residualnorm - sets line graph monitor,
1762: uses KSPMonitorLGResidualNormCreate()
1763: . -ksp_monitor_lg_true_residualnorm - sets line graph monitor,
1764: uses KSPMonitorLGResidualNormCreate()
1765: . -ksp_monitor_singular_value - sets KSPMonitorSingularValue()
1766: - -ksp_monitor_cancel - cancels all monitors that have
1767: been hardwired into a code by
1768: calls to KSPMonitorSet(), but
1769: does not cancel those set via
1770: the options database.
1772: Notes:
1773: The default is to do nothing. To print the residual, or preconditioned
1774: residual if KSPSetNormType(ksp,KSP_NORM_PRECONDITIONED) was called, use
1775: KSPMonitorDefault() as the monitoring routine, with a ASCII viewer as the
1776: context.
1778: Several different monitoring routines may be set by calling
1779: KSPMonitorSet() multiple times; all will be called in the
1780: order in which they were set.
1782: Fortran Notes:
1783: Only a single monitor function can be set for each KSP object
1785: Level: beginner
1787: .seealso: KSPMonitorDefault(), KSPMonitorLGResidualNormCreate(), KSPMonitorCancel(), KSP
1788: @*/
1789: PetscErrorCode KSPMonitorSet(KSP ksp,PetscErrorCode (*monitor)(KSP,PetscInt,PetscReal,void*),void *mctx,PetscErrorCode (*monitordestroy)(void**))
1790: {
1791: PetscInt i;
1793: PetscBool identical;
1797: for (i=0; i<ksp->numbermonitors;i++) {
1798: PetscMonitorCompare((PetscErrorCode (*)(void))monitor,mctx,monitordestroy,(PetscErrorCode (*)(void))ksp->monitor[i],ksp->monitorcontext[i],ksp->monitordestroy[i],&identical);
1799: if (identical) return(0);
1800: }
1801: if (ksp->numbermonitors >= MAXKSPMONITORS) SETERRQ(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_OUTOFRANGE,"Too many KSP monitors set");
1802: ksp->monitor[ksp->numbermonitors] = monitor;
1803: ksp->monitordestroy[ksp->numbermonitors] = monitordestroy;
1804: ksp->monitorcontext[ksp->numbermonitors++] = (void*)mctx;
1805: return(0);
1806: }
1808: /*@
1809: KSPMonitorCancel - Clears all monitors for a KSP object.
1811: Logically Collective on ksp
1813: Input Parameters:
1814: . ksp - iterative context obtained from KSPCreate()
1816: Options Database Key:
1817: . -ksp_monitor_cancel - Cancels all monitors that have
1818: been hardwired into a code by calls to KSPMonitorSet(),
1819: but does not cancel those set via the options database.
1821: Level: intermediate
1823: .seealso: KSPMonitorDefault(), KSPMonitorLGResidualNormCreate(), KSPMonitorSet(), KSP
1824: @*/
1825: PetscErrorCode KSPMonitorCancel(KSP ksp)
1826: {
1828: PetscInt i;
1832: for (i=0; i<ksp->numbermonitors; i++) {
1833: if (ksp->monitordestroy[i]) {
1834: (*ksp->monitordestroy[i])(&ksp->monitorcontext[i]);
1835: }
1836: }
1837: ksp->numbermonitors = 0;
1838: return(0);
1839: }
1841: /*@C
1842: KSPGetMonitorContext - Gets the monitoring context, as set by
1843: KSPMonitorSet() for the FIRST monitor only.
1845: Not Collective
1847: Input Parameter:
1848: . ksp - iterative context obtained from KSPCreate()
1850: Output Parameter:
1851: . ctx - monitoring context
1853: Level: intermediate
1855: .seealso: KSPMonitorDefault(), KSPMonitorLGResidualNormCreate(), KSP
1856: @*/
1857: PetscErrorCode KSPGetMonitorContext(KSP ksp,void **ctx)
1858: {
1861: *ctx = (ksp->monitorcontext[0]);
1862: return(0);
1863: }
1865: /*@
1866: KSPSetResidualHistory - Sets the array used to hold the residual history.
1867: If set, this array will contain the residual norms computed at each
1868: iteration of the solver.
1870: Not Collective
1872: Input Parameters:
1873: + ksp - iterative context obtained from KSPCreate()
1874: . a - array to hold history
1875: . na - size of a
1876: - reset - PETSC_TRUE indicates the history counter is reset to zero
1877: for each new linear solve
1879: Level: advanced
1881: Notes:
1882: The array is NOT freed by PETSc so the user needs to keep track of
1883: it and destroy once the KSP object is destroyed.
1885: If 'a' is NULL then space is allocated for the history. If 'na' PETSC_DECIDE or PETSC_DEFAULT then a
1886: default array of length 10000 is allocated.
1888: .seealso: KSPGetResidualHistory(), KSP
1890: @*/
1891: PetscErrorCode KSPSetResidualHistory(KSP ksp,PetscReal a[],PetscInt na,PetscBool reset)
1892: {
1898: PetscFree(ksp->res_hist_alloc);
1899: if (na != PETSC_DECIDE && na != PETSC_DEFAULT && a) {
1900: ksp->res_hist = a;
1901: ksp->res_hist_max = na;
1902: } else {
1903: if (na != PETSC_DECIDE && na != PETSC_DEFAULT) ksp->res_hist_max = na;
1904: else ksp->res_hist_max = 10000; /* like default ksp->max_it */
1905: PetscCalloc1(ksp->res_hist_max,&ksp->res_hist_alloc);
1907: ksp->res_hist = ksp->res_hist_alloc;
1908: }
1909: ksp->res_hist_len = 0;
1910: ksp->res_hist_reset = reset;
1911: return(0);
1912: }
1914: /*@C
1915: KSPGetResidualHistory - Gets the array used to hold the residual history
1916: and the number of residuals it contains.
1918: Not Collective
1920: Input Parameter:
1921: . ksp - iterative context obtained from KSPCreate()
1923: Output Parameters:
1924: + a - pointer to array to hold history (or NULL)
1925: - na - number of used entries in a (or NULL)
1927: Level: advanced
1929: Notes:
1930: Can only be called after a KSPSetResidualHistory() otherwise a and na are set to zero
1932: The Fortran version of this routine has a calling sequence
1933: $ call KSPGetResidualHistory(KSP ksp, integer na, integer ierr)
1934: note that you have passed a Fortran array into KSPSetResidualHistory() and you need
1935: to access the residual values from this Fortran array you provided. Only the na (number of
1936: residual norms currently held) is set.
1938: .seealso: KSPGetResidualHistory(), KSP
1940: @*/
1941: PetscErrorCode KSPGetResidualHistory(KSP ksp,PetscReal *a[],PetscInt *na)
1942: {
1945: if (a) *a = ksp->res_hist;
1946: if (na) *na = ksp->res_hist_len;
1947: return(0);
1948: }
1950: /*@C
1951: KSPSetConvergenceTest - Sets the function to be used to determine
1952: convergence.
1954: Logically Collective on ksp
1956: Input Parameters:
1957: + ksp - iterative context obtained from KSPCreate()
1958: . converge - pointer to the function
1959: . cctx - context for private data for the convergence routine (may be null)
1960: - destroy - a routine for destroying the context (may be null)
1962: Calling sequence of converge:
1963: $ converge (KSP ksp, PetscInt it, PetscReal rnorm, KSPConvergedReason *reason,void *mctx)
1965: + ksp - iterative context obtained from KSPCreate()
1966: . it - iteration number
1967: . rnorm - (estimated) 2-norm of (preconditioned) residual
1968: . reason - the reason why it has converged or diverged
1969: - cctx - optional convergence context, as set by KSPSetConvergenceTest()
1972: Notes:
1973: Must be called after the KSP type has been set so put this after
1974: a call to KSPSetType(), or KSPSetFromOptions().
1976: The default convergence test, KSPConvergedDefault(), aborts if the
1977: residual grows to more than 10000 times the initial residual.
1979: The default is a combination of relative and absolute tolerances.
1980: The residual value that is tested may be an approximation; routines
1981: that need exact values should compute them.
1983: In the default PETSc convergence test, the precise values of reason
1984: are macros such as KSP_CONVERGED_RTOL, which are defined in petscksp.h.
1986: Level: advanced
1988: .seealso: KSPConvergedDefault(), KSPGetConvergenceContext(), KSPSetTolerances(), KSP, KSPGetConvergenceTest(), KSPGetAndClearConvergenceTest()
1989: @*/
1990: PetscErrorCode KSPSetConvergenceTest(KSP ksp,PetscErrorCode (*converge)(KSP,PetscInt,PetscReal,KSPConvergedReason*,void*),void *cctx,PetscErrorCode (*destroy)(void*))
1991: {
1996: if (ksp->convergeddestroy) {
1997: (*ksp->convergeddestroy)(ksp->cnvP);
1998: }
1999: ksp->converged = converge;
2000: ksp->convergeddestroy = destroy;
2001: ksp->cnvP = (void*)cctx;
2002: return(0);
2003: }
2005: /*@C
2006: KSPGetConvergenceTest - Gets the function to be used to determine
2007: convergence.
2009: Logically Collective on ksp
2011: Input Parameter:
2012: . ksp - iterative context obtained from KSPCreate()
2014: Output Parameter:
2015: + converge - pointer to convergence test function
2016: . cctx - context for private data for the convergence routine (may be null)
2017: - destroy - a routine for destroying the context (may be null)
2019: Calling sequence of converge:
2020: $ converge (KSP ksp, PetscInt it, PetscReal rnorm, KSPConvergedReason *reason,void *mctx)
2022: + ksp - iterative context obtained from KSPCreate()
2023: . it - iteration number
2024: . rnorm - (estimated) 2-norm of (preconditioned) residual
2025: . reason - the reason why it has converged or diverged
2026: - cctx - optional convergence context, as set by KSPSetConvergenceTest()
2028: Level: advanced
2030: .seealso: KSPConvergedDefault(), KSPGetConvergenceContext(), KSPSetTolerances(), KSP, KSPSetConvergenceTest(), KSPGetAndClearConvergenceTest()
2031: @*/
2032: PetscErrorCode KSPGetConvergenceTest(KSP ksp,PetscErrorCode (**converge)(KSP,PetscInt,PetscReal,KSPConvergedReason*,void*),void **cctx,PetscErrorCode (**destroy)(void*))
2033: {
2036: if (converge) *converge = ksp->converged;
2037: if (destroy) *destroy = ksp->convergeddestroy;
2038: if (cctx) *cctx = ksp->cnvP;
2039: return(0);
2040: }
2042: /*@C
2043: KSPGetAndClearConvergenceTest - Gets the function to be used to determine convergence. Removes the current test without calling destroy on the test context
2045: Logically Collective on ksp
2047: Input Parameter:
2048: . ksp - iterative context obtained from KSPCreate()
2050: Output Parameter:
2051: + converge - pointer to convergence test function
2052: . cctx - context for private data for the convergence routine
2053: - destroy - a routine for destroying the context
2055: Calling sequence of converge:
2056: $ converge (KSP ksp, PetscInt it, PetscReal rnorm, KSPConvergedReason *reason,void *mctx)
2058: + ksp - iterative context obtained from KSPCreate()
2059: . it - iteration number
2060: . rnorm - (estimated) 2-norm of (preconditioned) residual
2061: . reason - the reason why it has converged or diverged
2062: - cctx - optional convergence context, as set by KSPSetConvergenceTest()
2064: Level: advanced
2066: Notes: This is intended to be used to allow transferring the convergence test (and its context) to another testing object (for example another KSP) and then calling
2067: KSPSetConvergenceTest() on this original KSP. If you just called KSPGetConvergenceTest() followed by KSPSetConvergenceTest() the original context information
2068: would be destroyed and hence the transferred context would be invalid and trigger a crash on use
2070: .seealso: KSPConvergedDefault(), KSPGetConvergenceContext(), KSPSetTolerances(), KSP, KSPSetConvergenceTest(), KSPGetConvergenceTest()
2071: @*/
2072: PetscErrorCode KSPGetAndClearConvergenceTest(KSP ksp,PetscErrorCode (**converge)(KSP,PetscInt,PetscReal,KSPConvergedReason*,void*),void **cctx,PetscErrorCode (**destroy)(void*))
2073: {
2076: *converge = ksp->converged;
2077: *destroy = ksp->convergeddestroy;
2078: *cctx = ksp->cnvP;
2079: ksp->converged = NULL;
2080: ksp->cnvP = NULL;
2081: ksp->convergeddestroy = NULL;
2082: return(0);
2083: }
2085: /*@C
2086: KSPGetConvergenceContext - Gets the convergence context set with
2087: KSPSetConvergenceTest().
2089: Not Collective
2091: Input Parameter:
2092: . ksp - iterative context obtained from KSPCreate()
2094: Output Parameter:
2095: . ctx - monitoring context
2097: Level: advanced
2099: .seealso: KSPConvergedDefault(), KSPSetConvergenceTest(), KSP
2100: @*/
2101: PetscErrorCode KSPGetConvergenceContext(KSP ksp,void **ctx)
2102: {
2105: *ctx = ksp->cnvP;
2106: return(0);
2107: }
2109: /*@C
2110: KSPBuildSolution - Builds the approximate solution in a vector provided.
2111: This routine is NOT commonly needed (see KSPSolve()).
2113: Collective on ksp
2115: Input Parameter:
2116: . ctx - iterative context obtained from KSPCreate()
2118: Output Parameter:
2119: Provide exactly one of
2120: + v - location to stash solution.
2121: - V - the solution is returned in this location. This vector is created
2122: internally. This vector should NOT be destroyed by the user with
2123: VecDestroy().
2125: Notes:
2126: This routine can be used in one of two ways
2127: .vb
2128: KSPBuildSolution(ksp,NULL,&V);
2129: or
2130: KSPBuildSolution(ksp,v,NULL); or KSPBuildSolution(ksp,v,&v);
2131: .ve
2132: In the first case an internal vector is allocated to store the solution
2133: (the user cannot destroy this vector). In the second case the solution
2134: is generated in the vector that the user provides. Note that for certain
2135: methods, such as KSPCG, the second case requires a copy of the solution,
2136: while in the first case the call is essentially free since it simply
2137: returns the vector where the solution already is stored. For some methods
2138: like GMRES this is a reasonably expensive operation and should only be
2139: used in truly needed.
2141: Level: advanced
2143: .seealso: KSPGetSolution(), KSPBuildResidual(), KSP
2144: @*/
2145: PetscErrorCode KSPBuildSolution(KSP ksp,Vec v,Vec *V)
2146: {
2151: if (!V && !v) SETERRQ(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_WRONG,"Must provide either v or V");
2152: if (!V) V = &v;
2153: (*ksp->ops->buildsolution)(ksp,v,V);
2154: return(0);
2155: }
2157: /*@C
2158: KSPBuildResidual - Builds the residual in a vector provided.
2160: Collective on ksp
2162: Input Parameter:
2163: . ksp - iterative context obtained from KSPCreate()
2165: Output Parameters:
2166: + v - optional location to stash residual. If v is not provided,
2167: then a location is generated.
2168: . t - work vector. If not provided then one is generated.
2169: - V - the residual
2171: Notes:
2172: Regardless of whether or not v is provided, the residual is
2173: returned in V.
2175: Level: advanced
2177: .seealso: KSPBuildSolution()
2178: @*/
2179: PetscErrorCode KSPBuildResidual(KSP ksp,Vec t,Vec v,Vec *V)
2180: {
2182: PetscBool flag = PETSC_FALSE;
2183: Vec w = v,tt = t;
2187: if (!w) {
2188: VecDuplicate(ksp->vec_rhs,&w);
2189: PetscLogObjectParent((PetscObject)ksp,(PetscObject)w);
2190: }
2191: if (!tt) {
2192: VecDuplicate(ksp->vec_sol,&tt); flag = PETSC_TRUE;
2193: PetscLogObjectParent((PetscObject)ksp,(PetscObject)tt);
2194: }
2195: (*ksp->ops->buildresidual)(ksp,tt,w,V);
2196: if (flag) {VecDestroy(&tt);}
2197: return(0);
2198: }
2200: /*@
2201: KSPSetDiagonalScale - Tells KSP to symmetrically diagonally scale the system
2202: before solving. This actually CHANGES the matrix (and right hand side).
2204: Logically Collective on ksp
2206: Input Parameter:
2207: + ksp - the KSP context
2208: - scale - PETSC_TRUE or PETSC_FALSE
2210: Options Database Key:
2211: + -ksp_diagonal_scale -
2212: - -ksp_diagonal_scale_fix - scale the matrix back AFTER the solve
2215: Notes:
2216: Scales the matrix by D^(-1/2) A D^(-1/2) [D^(1/2) x ] = D^(-1/2) b
2217: where D_{ii} is 1/abs(A_{ii}) unless A_{ii} is zero and then it is 1.
2219: BE CAREFUL with this routine: it actually scales the matrix and right
2220: hand side that define the system. After the system is solved the matrix
2221: and right hand side remain scaled unless you use KSPSetDiagonalScaleFix()
2223: This should NOT be used within the SNES solves if you are using a line
2224: search.
2226: If you use this with the PCType Eisenstat preconditioner than you can
2227: use the PCEisenstatSetNoDiagonalScaling() option, or -pc_eisenstat_no_diagonal_scaling
2228: to save some unneeded, redundant flops.
2230: Level: intermediate
2232: .seealso: KSPGetDiagonalScale(), KSPSetDiagonalScaleFix(), KSP
2233: @*/
2234: PetscErrorCode KSPSetDiagonalScale(KSP ksp,PetscBool scale)
2235: {
2239: ksp->dscale = scale;
2240: return(0);
2241: }
2243: /*@
2244: KSPGetDiagonalScale - Checks if KSP solver scales the matrix and
2245: right hand side
2247: Not Collective
2249: Input Parameter:
2250: . ksp - the KSP context
2252: Output Parameter:
2253: . scale - PETSC_TRUE or PETSC_FALSE
2255: Notes:
2256: BE CAREFUL with this routine: it actually scales the matrix and right
2257: hand side that define the system. After the system is solved the matrix
2258: and right hand side remain scaled unless you use KSPSetDiagonalScaleFix()
2260: Level: intermediate
2262: .seealso: KSPSetDiagonalScale(), KSPSetDiagonalScaleFix(), KSP
2263: @*/
2264: PetscErrorCode KSPGetDiagonalScale(KSP ksp,PetscBool *scale)
2265: {
2269: *scale = ksp->dscale;
2270: return(0);
2271: }
2273: /*@
2274: KSPSetDiagonalScaleFix - Tells KSP to diagonally scale the system
2275: back after solving.
2277: Logically Collective on ksp
2279: Input Parameter:
2280: + ksp - the KSP context
2281: - fix - PETSC_TRUE to scale back after the system solve, PETSC_FALSE to not
2282: rescale (default)
2284: Notes:
2285: Must be called after KSPSetDiagonalScale()
2287: Using this will slow things down, because it rescales the matrix before and
2288: after each linear solve. This is intended mainly for testing to allow one
2289: to easily get back the original system to make sure the solution computed is
2290: accurate enough.
2292: Level: intermediate
2294: .seealso: KSPGetDiagonalScale(), KSPSetDiagonalScale(), KSPGetDiagonalScaleFix(), KSP
2295: @*/
2296: PetscErrorCode KSPSetDiagonalScaleFix(KSP ksp,PetscBool fix)
2297: {
2301: ksp->dscalefix = fix;
2302: return(0);
2303: }
2305: /*@
2306: KSPGetDiagonalScaleFix - Determines if KSP diagonally scales the system
2307: back after solving.
2309: Not Collective
2311: Input Parameter:
2312: . ksp - the KSP context
2314: Output Parameter:
2315: . fix - PETSC_TRUE to scale back after the system solve, PETSC_FALSE to not
2316: rescale (default)
2318: Notes:
2319: Must be called after KSPSetDiagonalScale()
2321: If PETSC_TRUE will slow things down, because it rescales the matrix before and
2322: after each linear solve. This is intended mainly for testing to allow one
2323: to easily get back the original system to make sure the solution computed is
2324: accurate enough.
2326: Level: intermediate
2328: .seealso: KSPGetDiagonalScale(), KSPSetDiagonalScale(), KSPSetDiagonalScaleFix(), KSP
2329: @*/
2330: PetscErrorCode KSPGetDiagonalScaleFix(KSP ksp,PetscBool *fix)
2331: {
2335: *fix = ksp->dscalefix;
2336: return(0);
2337: }
2339: /*@C
2340: KSPSetComputeOperators - set routine to compute the linear operators
2342: Logically Collective
2344: Input Arguments:
2345: + ksp - the KSP context
2346: . func - function to compute the operators
2347: - ctx - optional context
2349: Calling sequence of func:
2350: $ func(KSP ksp,Mat A,Mat B,void *ctx)
2352: + ksp - the KSP context
2353: . A - the linear operator
2354: . B - preconditioning matrix
2355: - ctx - optional user-provided context
2357: Notes:
2358: The user provided func() will be called automatically at the very next call to KSPSolve(). It will not be called at future KSPSolve() calls
2359: unless either KSPSetComputeOperators() or KSPSetOperators() is called before that KSPSolve() is called.
2361: To reuse the same preconditioner for the next KSPSolve() and not compute a new one based on the most recently computed matrix call KSPSetReusePreconditioner()
2363: Level: beginner
2365: .seealso: KSPSetOperators(), KSPSetComputeRHS(), DMKSPSetComputeOperators(), KSPSetComputeInitialGuess()
2366: @*/
2367: PetscErrorCode KSPSetComputeOperators(KSP ksp,PetscErrorCode (*func)(KSP,Mat,Mat,void*),void *ctx)
2368: {
2370: DM dm;
2374: KSPGetDM(ksp,&dm);
2375: DMKSPSetComputeOperators(dm,func,ctx);
2376: if (ksp->setupstage == KSP_SETUP_NEWRHS) ksp->setupstage = KSP_SETUP_NEWMATRIX;
2377: return(0);
2378: }
2380: /*@C
2381: KSPSetComputeRHS - set routine to compute the right hand side of the linear system
2383: Logically Collective
2385: Input Arguments:
2386: + ksp - the KSP context
2387: . func - function to compute the right hand side
2388: - ctx - optional context
2390: Calling sequence of func:
2391: $ func(KSP ksp,Vec b,void *ctx)
2393: + ksp - the KSP context
2394: . b - right hand side of linear system
2395: - ctx - optional user-provided context
2397: Notes:
2398: The routine you provide will be called EACH you call KSPSolve() to prepare the new right hand side for that solve
2400: Level: beginner
2402: .seealso: KSPSolve(), DMKSPSetComputeRHS(), KSPSetComputeOperators()
2403: @*/
2404: PetscErrorCode KSPSetComputeRHS(KSP ksp,PetscErrorCode (*func)(KSP,Vec,void*),void *ctx)
2405: {
2407: DM dm;
2411: KSPGetDM(ksp,&dm);
2412: DMKSPSetComputeRHS(dm,func,ctx);
2413: return(0);
2414: }
2416: /*@C
2417: KSPSetComputeInitialGuess - set routine to compute the initial guess of the linear system
2419: Logically Collective
2421: Input Arguments:
2422: + ksp - the KSP context
2423: . func - function to compute the initial guess
2424: - ctx - optional context
2426: Calling sequence of func:
2427: $ func(KSP ksp,Vec x,void *ctx)
2429: + ksp - the KSP context
2430: . x - solution vector
2431: - ctx - optional user-provided context
2433: Notes: This should only be used in conjunction with KSPSetComputeRHS(), KSPSetComputeOperators(), otherwise
2434: call KSPSetInitialGuessNonzero() and set the initial guess values in the solution vector passed to KSPSolve().
2436: Level: beginner
2438: .seealso: KSPSolve(), KSPSetComputeRHS(), KSPSetComputeOperators(), DMKSPSetComputeInitialGuess()
2439: @*/
2440: PetscErrorCode KSPSetComputeInitialGuess(KSP ksp,PetscErrorCode (*func)(KSP,Vec,void*),void *ctx)
2441: {
2443: DM dm;
2447: KSPGetDM(ksp,&dm);
2448: DMKSPSetComputeInitialGuess(dm,func,ctx);
2449: return(0);
2450: }