Actual source code: iterativ.c
1: /*
2: This file contains some simple default routines.
3: These routines should be SHORT, since they will be included in every
4: executable image that uses the iterative routines (note that, through
5: the registry system, we provide a way to load only the truly necessary
6: files)
7: */
8: #include <petsc/private/kspimpl.h>
9: #include <petscdmshell.h>
10: #include <petscdraw.h>
12: /*@
13: KSPGetResidualNorm - Gets the last (possibly approximate and/or preconditioned) residual norm that has been computed.
15: Not Collective
17: Input Parameter:
18: . ksp - the iterative context
20: Output Parameter:
21: . rnorm - residual norm
23: Level: intermediate
25: Note:
26: For some methods, such as `KSPGMRES`, the norm is not computed directly from the residual.
28: The type of norm used by the method can be controlled with `KSPSetNormType()`
30: .seealso: [](chapter_ksp), `KSP`, `KSPSetNormType()`, `KSPBuildResidual()`, `KSPNormType`
31: @*/
32: PetscErrorCode KSPGetResidualNorm(KSP ksp, PetscReal *rnorm)
33: {
34: PetscFunctionBegin;
37: *rnorm = ksp->rnorm;
38: PetscFunctionReturn(PETSC_SUCCESS);
39: }
41: /*@
42: KSPGetIterationNumber - Gets the current iteration number; if the `KSPSolve()` is complete, returns the number of iterations used.
44: Not Collective
46: Input Parameter:
47: . ksp - the iterative context
49: Output Parameter:
50: . its - number of iterations
52: Level: intermediate
54: Note:
55: During the ith iteration this returns i-1
57: .seealso: [](chapter_ksp), `KSP`, `KSPGetResidualNorm()`, `KSPBuildResidual()`, `KSPGetResidualNorm()`, `KSPGetTotalIterations()`
58: @*/
59: PetscErrorCode KSPGetIterationNumber(KSP ksp, PetscInt *its)
60: {
61: PetscFunctionBegin;
64: *its = ksp->its;
65: PetscFunctionReturn(PETSC_SUCCESS);
66: }
68: /*@
69: KSPGetTotalIterations - Gets the total number of iterations this `KSP` object has performed since was created, counted over all linear solves
71: Not Collective
73: Input Parameter:
74: . ksp - the iterative context
76: Output Parameter:
77: . its - total number of iterations
79: Level: intermediate
81: Note:
82: Use `KSPGetIterationNumber()` to get the count for the most recent solve only
83: If this is called within a `KSPSolve()` (such as in a `KSPMonitor` routine) then it does not include iterations within that current solve
85: .seealso: [](chapter_ksp), `KSP`, `KSPBuildResidual()`, `KSPGetResidualNorm()`, `KSPGetIterationNumber()`
86: @*/
87: PetscErrorCode KSPGetTotalIterations(KSP ksp, PetscInt *its)
88: {
89: PetscFunctionBegin;
92: *its = ksp->totalits;
93: PetscFunctionReturn(PETSC_SUCCESS);
94: }
96: /*@C
97: KSPMonitorResidual - Print the (possibly preconditioned) residual norm at each iteration of an iterative solver.
99: Collective
101: Input Parameters:
102: + ksp - iterative context
103: . n - iteration number
104: . rnorm - 2-norm (preconditioned) residual value (may be estimated).
105: - vf - The viewer context
107: Options Database Key:
108: . -ksp_monitor - Activates `KSPMonitorResidual()`
110: Level: intermediate
112: Note:
113: For some methods, such as `KSPGMRES`, the norm is not computed directly from the residual.
115: The type of norm used by the method can be controlled with `KSPSetNormType()`
117: This is not called directly by users, rather one calls `KSPMonitorSet()`, with this function as an argument, to cause the monitor
118: to be used during the KSP solve.
120: .seealso: [](chapter_ksp), `KSP`, `KSPMonitorSet()`, `KSPMonitorTrueResidual()`, `KSPMonitorResidualDraw()`, `KSPMonitorResidualDrawLG()`,
121: `KSPMonitorResidualRange()`, `KSPMonitorTrueResidualDraw()`, `KSPMonitorTrueResidualDrawLG()`, `KSPMonitorTrueResidualMax()`,
122: `KSPMonitorSingularValue()`, `KSPMonitorSolutionDrawLG()`, `KSPMonitorSolutionDraw()`, `KSPMonitorSolution()`,
123: `KSPMonitorErrorDrawLG()`, `KSPMonitorErrorDraw()`, KSPMonitorError()`
124: @*/
125: PetscErrorCode KSPMonitorResidual(KSP ksp, PetscInt n, PetscReal rnorm, PetscViewerAndFormat *vf)
126: {
127: PetscViewer viewer = vf->viewer;
128: PetscViewerFormat format = vf->format;
129: PetscInt tablevel;
130: const char *prefix;
132: PetscFunctionBegin;
134: PetscCall(PetscObjectGetTabLevel((PetscObject)ksp, &tablevel));
135: PetscCall(PetscObjectGetOptionsPrefix((PetscObject)ksp, &prefix));
136: PetscCall(PetscViewerPushFormat(viewer, format));
137: PetscCall(PetscViewerASCIIAddTab(viewer, tablevel));
138: if (n == 0 && prefix) PetscCall(PetscViewerASCIIPrintf(viewer, " Residual norms for %s solve.\n", prefix));
139: PetscCall(PetscViewerASCIIPrintf(viewer, "%3" PetscInt_FMT " KSP Residual norm %14.12e \n", n, (double)rnorm));
140: PetscCall(PetscViewerASCIISubtractTab(viewer, tablevel));
141: PetscCall(PetscViewerPopFormat(viewer));
142: PetscFunctionReturn(PETSC_SUCCESS);
143: }
145: /*@C
146: KSPMonitorResidualDraw - Plots the (possibly preconditioned) residual at each iteration of an iterative solver.
148: Collective
150: Input Parameters:
151: + ksp - iterative context
152: . n - iteration number
153: . rnorm - 2-norm (preconditioned) residual value (may be estimated).
154: - vf - The viewer context
156: Options Database Key:
157: . -ksp_monitor draw - Activates `KSPMonitorResidualDraw()`
159: Level: intermediate
161: Note:
162: This is not called directly by users, rather one calls `KSPMonitorSet()`, with this function as an argument, to cause the monitor
163: to be used during the `KSP` solve.
165: .seealso: [](chapter_ksp), `KSP`, `KSPMonitorSet()`, `KSPMonitorTrueResidual()`, `KSPMonitorResidual()`, `KSPMonitorResidualDrawLG()`
166: @*/
167: PetscErrorCode KSPMonitorResidualDraw(KSP ksp, PetscInt n, PetscReal rnorm, PetscViewerAndFormat *vf)
168: {
169: PetscViewer viewer = vf->viewer;
170: PetscViewerFormat format = vf->format;
171: Vec r;
173: PetscFunctionBegin;
175: PetscCall(PetscViewerPushFormat(viewer, format));
176: PetscCall(KSPBuildResidual(ksp, NULL, NULL, &r));
177: PetscCall(PetscObjectSetName((PetscObject)r, "Residual"));
178: PetscCall(PetscObjectCompose((PetscObject)r, "__Vec_bc_zero__", (PetscObject)ksp));
179: PetscCall(VecView(r, viewer));
180: PetscCall(PetscObjectCompose((PetscObject)r, "__Vec_bc_zero__", NULL));
181: PetscCall(VecDestroy(&r));
182: PetscCall(PetscViewerPopFormat(viewer));
183: PetscFunctionReturn(PETSC_SUCCESS);
184: }
186: /*@C
187: KSPMonitorResidualDrawLG - Plots the (possibly preconditioned) residual norm at each iteration of an iterative solver.
189: Collective
191: Input Parameters:
192: + ksp - iterative context
193: . n - iteration number
194: . rnorm - 2-norm (preconditioned) residual value (may be estimated).
195: - vf - The viewer context
197: Options Database Key:
198: . -ksp_monitor draw::draw_lg - Activates `KSPMonitorResidualDrawLG()`
200: Level: intermediate
202: Notes:
203: This is not called directly by users, rather one calls `KSPMonitorSet()`, with this function as an argument, to cause the monitor
204: to be used during the `KSP` solve.
206: Use `KSPMonitorResidualDrawLGCreate()` to create the context used with this monitor
208: .seealso: [](chapter_ksp), `KSP`, `PETSCVIEWERDRAW`, `KSPMonitorSet()`, `KSPMonitorTrueResidual()`, `KSPMonitorResidualDraw()`, `KSPMonitorResidual()`
209: @*/
210: PetscErrorCode KSPMonitorResidualDrawLG(KSP ksp, PetscInt n, PetscReal rnorm, PetscViewerAndFormat *vf)
211: {
212: PetscViewer viewer = vf->viewer;
213: PetscViewerFormat format = vf->format;
214: PetscDrawLG lg = vf->lg;
215: KSPConvergedReason reason;
216: PetscReal x, y;
218: PetscFunctionBegin;
221: PetscCall(PetscViewerPushFormat(viewer, format));
222: if (!n) PetscCall(PetscDrawLGReset(lg));
223: x = (PetscReal)n;
224: if (rnorm > 0.0) y = PetscLog10Real(rnorm);
225: else y = -15.0;
226: PetscCall(PetscDrawLGAddPoint(lg, &x, &y));
227: PetscCall(KSPGetConvergedReason(ksp, &reason));
228: if (n <= 20 || !(n % 5) || reason) {
229: PetscCall(PetscDrawLGDraw(lg));
230: PetscCall(PetscDrawLGSave(lg));
231: }
232: PetscCall(PetscViewerPopFormat(viewer));
233: PetscFunctionReturn(PETSC_SUCCESS);
234: }
236: /*@C
237: KSPMonitorResidualDrawLGCreate - Creates the context for the (possibly preconditioned) residual norm monitor `KSPMonitorResidualDrawLG()`
239: Collective
241: Input Parameters:
242: + viewer - The `PetscViewer` of type `PETSCVIEWERDRAW`
243: . format - The viewer format
244: - ctx - An optional user context
246: Output Parameter:
247: . vf - The viewer context
249: Level: intermediate
251: .seealso: [](chapter_ksp), `KSP`, `PETSCVIEWERDRAW`, `KSPMonitorSet()`, `KSPMonitorTrueResidual()`, `KSPMonitorResidualDrawLG()`,
252: `PetscViewerFormat`, `PetscViewer`, `PetscViewerAndFormat`
253: @*/
254: PetscErrorCode KSPMonitorResidualDrawLGCreate(PetscViewer viewer, PetscViewerFormat format, void *ctx, PetscViewerAndFormat **vf)
255: {
256: PetscFunctionBegin;
257: PetscCall(PetscViewerAndFormatCreate(viewer, format, vf));
258: (*vf)->data = ctx;
259: PetscCall(KSPMonitorLGCreate(PetscObjectComm((PetscObject)viewer), NULL, NULL, "Log Residual Norm", 1, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, &(*vf)->lg));
260: PetscFunctionReturn(PETSC_SUCCESS);
261: }
263: /*
264: This is the same as KSPMonitorResidual() except it prints fewer digits of the residual as the residual gets smaller.
265: This is because the later digits are meaningless and are often different on different machines; by using this routine different
266: machines will usually generate the same output.
268: Deprecated: Intentionally has no manual page
269: */
270: PetscErrorCode KSPMonitorResidualShort(KSP ksp, PetscInt its, PetscReal fnorm, PetscViewerAndFormat *vf)
271: {
272: PetscViewer viewer = vf->viewer;
273: PetscViewerFormat format = vf->format;
274: PetscInt tablevel;
275: const char *prefix;
277: PetscFunctionBegin;
279: PetscCall(PetscObjectGetTabLevel((PetscObject)ksp, &tablevel));
280: PetscCall(PetscObjectGetOptionsPrefix((PetscObject)ksp, &prefix));
281: PetscCall(PetscViewerPushFormat(viewer, format));
282: PetscCall(PetscViewerASCIIAddTab(viewer, tablevel));
283: if (its == 0 && prefix) PetscCall(PetscViewerASCIIPrintf(viewer, " Residual norms for %s solve.\n", prefix));
284: if (fnorm > 1.e-9) PetscCall(PetscViewerASCIIPrintf(viewer, "%3" PetscInt_FMT " KSP Residual norm %g \n", its, (double)fnorm));
285: else if (fnorm > 1.e-11) PetscCall(PetscViewerASCIIPrintf(viewer, "%3" PetscInt_FMT " KSP Residual norm %5.3e \n", its, (double)fnorm));
286: else PetscCall(PetscViewerASCIIPrintf(viewer, "%3" PetscInt_FMT " KSP Residual norm < 1.e-11\n", its));
287: PetscCall(PetscViewerASCIISubtractTab(viewer, tablevel));
288: PetscCall(PetscViewerPopFormat(viewer));
289: PetscFunctionReturn(PETSC_SUCCESS);
290: }
292: PetscErrorCode KSPMonitorRange_Private(KSP ksp, PetscInt it, PetscReal *per)
293: {
294: Vec resid;
295: const PetscScalar *r;
296: PetscReal rmax, pwork;
297: PetscInt i, n, N;
299: PetscFunctionBegin;
300: PetscCall(KSPBuildResidual(ksp, NULL, NULL, &resid));
301: PetscCall(VecNorm(resid, NORM_INFINITY, &rmax));
302: PetscCall(VecGetLocalSize(resid, &n));
303: PetscCall(VecGetSize(resid, &N));
304: PetscCall(VecGetArrayRead(resid, &r));
305: pwork = 0.0;
306: for (i = 0; i < n; ++i) pwork += (PetscAbsScalar(r[i]) > .20 * rmax);
307: PetscCall(VecRestoreArrayRead(resid, &r));
308: PetscCall(VecDestroy(&resid));
309: PetscCall(MPIU_Allreduce(&pwork, per, 1, MPIU_REAL, MPIU_SUM, PetscObjectComm((PetscObject)ksp)));
310: *per = *per / N;
311: PetscFunctionReturn(PETSC_SUCCESS);
312: }
314: /*@C
315: KSPMonitorResidualRange - Prints the percentage of residual elements that are more then 10 percent of the maximum value.
317: Collective
319: Input Parameters:
320: + ksp - iterative context
321: . it - iteration number
322: . rnorm - 2-norm (preconditioned) residual value (may be estimated).
323: - vf - The viewer context
325: Options Database Key:
326: . -ksp_monitor_range - Activates `KSPMonitorResidualRange()`
328: Level: intermediate
330: Note:
331: This is not called directly by users, rather one calls `KSPMonitorSet()`, with this function as an argument, to cause the monitor
332: to be used during the `KSP` solve.
334: .seealso: [](chapter_ksp), `KSP`, `KSPMonitorSet()`, `KSPMonitorResidual()`
335: @*/
336: PetscErrorCode KSPMonitorResidualRange(KSP ksp, PetscInt it, PetscReal rnorm, PetscViewerAndFormat *vf)
337: {
338: static PetscReal prev;
339: PetscViewer viewer = vf->viewer;
340: PetscViewerFormat format = vf->format;
341: PetscInt tablevel;
342: const char *prefix;
343: PetscReal perc, rel;
345: PetscFunctionBegin;
347: PetscCall(PetscObjectGetTabLevel((PetscObject)ksp, &tablevel));
348: PetscCall(PetscObjectGetOptionsPrefix((PetscObject)ksp, &prefix));
349: PetscCall(PetscViewerPushFormat(viewer, format));
350: PetscCall(PetscViewerASCIIAddTab(viewer, tablevel));
351: if (!it) prev = rnorm;
352: if (it == 0 && prefix) PetscCall(PetscViewerASCIIPrintf(viewer, " Residual norms for %s solve.\n", prefix));
353: PetscCall(KSPMonitorRange_Private(ksp, it, &perc));
354: rel = (prev - rnorm) / prev;
355: prev = rnorm;
356: PetscCall(PetscViewerASCIIPrintf(viewer, "%3" PetscInt_FMT " KSP preconditioned resid norm %14.12e Percent values above 20 percent of maximum %5.2f relative decrease %5.2e ratio %5.2e \n", it, (double)rnorm, (double)(100.0 * perc), (double)rel, (double)(rel / perc)));
357: PetscCall(PetscViewerASCIISubtractTab(viewer, tablevel));
358: PetscCall(PetscViewerPopFormat(viewer));
359: PetscFunctionReturn(PETSC_SUCCESS);
360: }
362: /*@C
363: KSPMonitorTrueResidual - Prints the true residual norm, as well as the (possibly preconditioned) approximate residual norm, at each iteration of an iterative solver.
365: Collective
367: Input Parameters:
368: + ksp - iterative context
369: . n - iteration number
370: . rnorm - 2-norm (preconditioned) residual value (may be estimated).
371: - vf - The viewer context
373: Options Database Key:
374: . -ksp_monitor_true_residual - Activates `KSPMonitorTrueResidual()`
376: Level: intermediate
378: Notes:
379: When using right preconditioning, these values are equivalent.
381: This is not called directly by users, rather one calls `KSPMonitorSet()`, with this function as an argument, to cause the monitor
382: to be used during the `KSP` solve.
384: .seealso: [](chapter_ksp), `KSP`, `KSPMonitorSet()`, `KSPMonitorResidual()`, `KSPMonitorTrueResidualMaxNorm()`, `PetscViewerAndFormat`
385: @*/
386: PetscErrorCode KSPMonitorTrueResidual(KSP ksp, PetscInt n, PetscReal rnorm, PetscViewerAndFormat *vf)
387: {
388: PetscViewer viewer = vf->viewer;
389: PetscViewerFormat format = vf->format;
390: Vec r;
391: PetscReal truenorm, bnorm;
392: char normtype[256];
393: PetscInt tablevel;
394: const char *prefix;
396: PetscFunctionBegin;
398: PetscCall(PetscObjectGetTabLevel((PetscObject)ksp, &tablevel));
399: PetscCall(PetscObjectGetOptionsPrefix((PetscObject)ksp, &prefix));
400: PetscCall(PetscStrncpy(normtype, KSPNormTypes[ksp->normtype], sizeof(normtype)));
401: PetscCall(PetscStrtolower(normtype));
402: PetscCall(KSPBuildResidual(ksp, NULL, NULL, &r));
403: PetscCall(VecNorm(r, NORM_2, &truenorm));
404: PetscCall(VecNorm(ksp->vec_rhs, NORM_2, &bnorm));
405: PetscCall(VecDestroy(&r));
407: PetscCall(PetscViewerPushFormat(viewer, format));
408: PetscCall(PetscViewerASCIIAddTab(viewer, tablevel));
409: if (n == 0 && prefix) PetscCall(PetscViewerASCIIPrintf(viewer, " Residual norms for %s solve.\n", prefix));
410: PetscCall(PetscViewerASCIIPrintf(viewer, "%3" PetscInt_FMT " KSP %s resid norm %14.12e true resid norm %14.12e ||r(i)||/||b|| %14.12e\n", n, normtype, (double)rnorm, (double)truenorm, (double)(truenorm / bnorm)));
411: PetscCall(PetscViewerASCIISubtractTab(viewer, tablevel));
412: PetscCall(PetscViewerPopFormat(viewer));
413: PetscFunctionReturn(PETSC_SUCCESS);
414: }
416: /*@C
417: KSPMonitorTrueResidualDraw - Plots the true residual at each iteration of an iterative solver.
419: Collective
421: Input Parameters:
422: + ksp - iterative context
423: . n - iteration number
424: . rnorm - 2-norm (preconditioned) residual value (may be estimated).
425: - vf - The viewer context of type `PETSCVIEWERDRAW`
427: Options Database Key:
428: . -ksp_monitor_true_residual draw - Activates `KSPMonitorResidualDraw()`
430: Level: intermediate
432: Note:
433: This is not called directly by users, rather one calls `KSPMonitorSet()`, with this function as an argument, to cause the monitor
434: to be used during the `KSP` solve.
436: .seealso: [](chapter_ksp), `PETSCVIEWERDRAW`, `KSP`, `KSPMonitorSet()`, `KSPMonitorTrueResidual()`, `KSPMonitorResidual()`,
437: `KSPMonitorTrueResidualDrawLG()`, `PetscViewerAndFormat`
438: @*/
439: PetscErrorCode KSPMonitorTrueResidualDraw(KSP ksp, PetscInt n, PetscReal rnorm, PetscViewerAndFormat *vf)
440: {
441: PetscViewer viewer = vf->viewer;
442: PetscViewerFormat format = vf->format;
443: Vec r;
445: PetscFunctionBegin;
447: PetscCall(PetscViewerPushFormat(viewer, format));
448: PetscCall(KSPBuildResidual(ksp, NULL, NULL, &r));
449: PetscCall(PetscObjectSetName((PetscObject)r, "Residual"));
450: PetscCall(PetscObjectCompose((PetscObject)r, "__Vec_bc_zero__", (PetscObject)ksp));
451: PetscCall(VecView(r, viewer));
452: PetscCall(PetscObjectCompose((PetscObject)r, "__Vec_bc_zero__", NULL));
453: PetscCall(VecDestroy(&r));
454: PetscCall(PetscViewerPopFormat(viewer));
455: PetscFunctionReturn(PETSC_SUCCESS);
456: }
458: /*@C
459: KSPMonitorTrueResidualDrawLG - Plots the true residual norm at each iteration of an iterative solver.
461: Collective
463: Input Parameters:
464: + ksp - iterative context
465: . n - iteration number
466: . rnorm - 2-norm (preconditioned) residual value (may be estimated).
467: - vf - The viewer context
469: Options Database Key:
470: . -ksp_monitor_true_residual draw::draw_lg - Activates `KSPMonitorTrueResidualDrawLG()`
472: Level: intermediate
474: Notes:
475: This is not called directly by users, rather one calls `KSPMonitorSet()`, with this function as an argument, to cause the monitor
476: to be used during the `KSP` solve.
478: Call `KSPMonitorTrueResidualDrawLGCreate()` to create the context needed for this monitor
480: .seealso: [](chapter_ksp), `PETSCVIEWERDRAW`, `KSP`, `KSPMonitorSet()`, `KSPMonitorTrueResidual()`, `KSPMonitorTrueResidualDraw()`, `KSPMonitorResidual`,
481: `KSPMonitorTrueResidualDrawLGCreate()`
482: @*/
483: PetscErrorCode KSPMonitorTrueResidualDrawLG(KSP ksp, PetscInt n, PetscReal rnorm, PetscViewerAndFormat *vf)
484: {
485: PetscViewer viewer = vf->viewer;
486: PetscViewerFormat format = vf->format;
487: PetscDrawLG lg = vf->lg;
488: Vec r;
489: KSPConvergedReason reason;
490: PetscReal truenorm, x[2], y[2];
492: PetscFunctionBegin;
495: PetscCall(KSPBuildResidual(ksp, NULL, NULL, &r));
496: PetscCall(VecNorm(r, NORM_2, &truenorm));
497: PetscCall(VecDestroy(&r));
498: PetscCall(PetscViewerPushFormat(viewer, format));
499: if (!n) PetscCall(PetscDrawLGReset(lg));
500: x[0] = (PetscReal)n;
501: if (rnorm > 0.0) y[0] = PetscLog10Real(rnorm);
502: else y[0] = -15.0;
503: x[1] = (PetscReal)n;
504: if (truenorm > 0.0) y[1] = PetscLog10Real(truenorm);
505: else y[1] = -15.0;
506: PetscCall(PetscDrawLGAddPoint(lg, x, y));
507: PetscCall(KSPGetConvergedReason(ksp, &reason));
508: if (n <= 20 || !(n % 5) || reason) {
509: PetscCall(PetscDrawLGDraw(lg));
510: PetscCall(PetscDrawLGSave(lg));
511: }
512: PetscCall(PetscViewerPopFormat(viewer));
513: PetscFunctionReturn(PETSC_SUCCESS);
514: }
516: /*@C
517: KSPMonitorTrueResidualDrawLGCreate - Creates the context for the true residual monitor `KSPMonitorTrueResidualDrawLG()`
519: Collective
521: Input Parameters:
522: + viewer - The `PetscViewer` of type `PETSCVIEWERDRAW`
523: . format - The viewer format
524: - ctx - An optional user context
526: Output Parameter:
527: . vf - The viewer context
529: Level: intermediate
531: .seealso: [](chapter_ksp), `PETSCVIEWERDRAW`, `KSP`, `KSPMonitorSet()`, `KSPMonitorTrueResidual()`, `PetscViewerAndFormat`
532: @*/
533: PetscErrorCode KSPMonitorTrueResidualDrawLGCreate(PetscViewer viewer, PetscViewerFormat format, void *ctx, PetscViewerAndFormat **vf)
534: {
535: const char *names[] = {"preconditioned", "true"};
537: PetscFunctionBegin;
538: PetscCall(PetscViewerAndFormatCreate(viewer, format, vf));
539: (*vf)->data = ctx;
540: PetscCall(KSPMonitorLGCreate(PetscObjectComm((PetscObject)viewer), NULL, NULL, "Log Residual Norm", 2, names, PETSC_DECIDE, PETSC_DECIDE, 400, 300, &(*vf)->lg));
541: PetscFunctionReturn(PETSC_SUCCESS);
542: }
544: /*@C
545: KSPMonitorTrueResidualMax - Prints the true residual max norm at each iteration of an iterative solver.
547: Collective
549: Input Parameters:
550: + ksp - iterative context
551: . n - iteration number
552: . rnorm - 2-norm (preconditioned) residual value (may be estimated).
553: - vf - The viewer context
555: Options Database Key:
556: . -ksp_monitor_true_residual_max - Activates `KSPMonitorTrueResidualMax()`
558: Level: intermediate
560: Note:
561: This is not called directly by users, rather one calls `KSPMonitorSet()`, with this function as an argument, to cause the monitor
562: to be used during the `KSP` solve.
564: .seealso: [](chapter_ksp), `KSP`, `KSPMonitorSet()`, `KSPMonitorResidual()`, `KSPMonitorTrueResidualMaxNorm()`
565: @*/
566: PetscErrorCode KSPMonitorTrueResidualMax(KSP ksp, PetscInt n, PetscReal rnorm, PetscViewerAndFormat *vf)
567: {
568: PetscViewer viewer = vf->viewer;
569: PetscViewerFormat format = vf->format;
570: Vec r;
571: PetscReal truenorm, bnorm;
572: char normtype[256];
573: PetscInt tablevel;
574: const char *prefix;
576: PetscFunctionBegin;
578: PetscCall(PetscObjectGetTabLevel((PetscObject)ksp, &tablevel));
579: PetscCall(PetscObjectGetOptionsPrefix((PetscObject)ksp, &prefix));
580: PetscCall(PetscStrncpy(normtype, KSPNormTypes[ksp->normtype], sizeof(normtype)));
581: PetscCall(PetscStrtolower(normtype));
582: PetscCall(KSPBuildResidual(ksp, NULL, NULL, &r));
583: PetscCall(VecNorm(r, NORM_INFINITY, &truenorm));
584: PetscCall(VecNorm(ksp->vec_rhs, NORM_INFINITY, &bnorm));
585: PetscCall(VecDestroy(&r));
587: PetscCall(PetscViewerPushFormat(viewer, format));
588: PetscCall(PetscViewerASCIIAddTab(viewer, tablevel));
589: if (n == 0 && prefix) PetscCall(PetscViewerASCIIPrintf(viewer, " Residual norms for %s solve.\n", prefix));
590: PetscCall(PetscViewerASCIIPrintf(viewer, "%3" PetscInt_FMT " KSP %s true resid max norm %14.12e ||r(i)||/||b|| %14.12e\n", n, normtype, (double)truenorm, (double)(truenorm / bnorm)));
591: PetscCall(PetscViewerASCIISubtractTab(viewer, tablevel));
592: PetscCall(PetscViewerPopFormat(viewer));
593: PetscFunctionReturn(PETSC_SUCCESS);
594: }
596: /*@C
597: KSPMonitorError - Prints the error norm, as well as the (possibly preconditioned) residual norm, at each iteration of an iterative solver.
599: Collective
601: Input Parameters:
602: + ksp - iterative context
603: . n - iteration number
604: . rnorm - 2-norm (preconditioned) residual value (may be estimated).
605: - vf - The viewer context
607: Options Database Key:
608: . -ksp_monitor_error - Activates `KSPMonitorError()`
610: Level: intermediate
612: Note:
613: This is not called directly by users, rather one calls `KSPMonitorSet()`, with this function as an argument, to cause the monitor
614: to be used during the `KSP` solve.
616: .seealso: [](chapter_ksp), `KSP`, `KSPMonitorSet()`, `KSPMonitorResidual()`, `KSPMonitorTrueResidualMaxNorm()`
617: @*/
618: PetscErrorCode KSPMonitorError(KSP ksp, PetscInt n, PetscReal rnorm, PetscViewerAndFormat *vf)
619: {
620: PetscViewer viewer = vf->viewer;
621: PetscViewerFormat format = vf->format;
622: DM dm;
623: Vec sol;
624: PetscReal *errors;
625: PetscInt Nf, f;
626: PetscInt tablevel;
627: const char *prefix;
629: PetscFunctionBegin;
631: PetscCall(PetscObjectGetTabLevel((PetscObject)ksp, &tablevel));
632: PetscCall(PetscObjectGetOptionsPrefix((PetscObject)ksp, &prefix));
633: PetscCall(KSPGetDM(ksp, &dm));
634: PetscCall(DMGetNumFields(dm, &Nf));
635: PetscCall(DMGetGlobalVector(dm, &sol));
636: PetscCall(KSPBuildSolution(ksp, sol, NULL));
637: /* TODO: Make a different monitor that flips sign for SNES, Newton system is A dx = -b, so we need to negate the solution */
638: PetscCall(VecScale(sol, -1.0));
639: PetscCall(PetscCalloc1(Nf, &errors));
640: PetscCall(DMComputeError(dm, sol, errors, NULL));
642: PetscCall(PetscViewerPushFormat(viewer, format));
643: PetscCall(PetscViewerASCIIAddTab(viewer, tablevel));
644: if (n == 0 && prefix) PetscCall(PetscViewerASCIIPrintf(viewer, " Error norms for %s solve.\n", prefix));
645: PetscCall(PetscViewerASCIIPrintf(viewer, "%3" PetscInt_FMT " KSP Error norm %s", n, Nf > 1 ? "[" : ""));
646: PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_FALSE));
647: for (f = 0; f < Nf; ++f) {
648: if (f > 0) PetscCall(PetscViewerASCIIPrintf(viewer, ", "));
649: PetscCall(PetscViewerASCIIPrintf(viewer, "%14.12e", (double)errors[f]));
650: }
651: PetscCall(PetscViewerASCIIPrintf(viewer, "%s resid norm %14.12e\n", Nf > 1 ? "]" : "", (double)rnorm));
652: PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_TRUE));
653: PetscCall(PetscViewerASCIISubtractTab(viewer, tablevel));
654: PetscCall(PetscViewerPopFormat(viewer));
655: PetscCall(DMRestoreGlobalVector(dm, &sol));
656: PetscFunctionReturn(PETSC_SUCCESS);
657: }
659: /*@C
660: KSPMonitorErrorDraw - Plots the error at each iteration of an iterative solver.
662: Collective
664: Input Parameters:
665: + ksp - iterative context
666: . n - iteration number
667: . rnorm - 2-norm (preconditioned) residual value (may be estimated).
668: - vf - The viewer context
670: Options Database Key:
671: . -ksp_monitor_error draw - Activates `KSPMonitorErrorDraw()`
673: Level: intermediate
675: Note:
676: This is not called directly by users, rather one calls `KSPMonitorSet()`, with this function as an argument, to cause the monitor
677: to be used during the `KSP` solve.
679: .seealso: [](chapter_ksp), `PETSCVIEWERDRAW`, `KSP`, `KSPMonitorSet()`, `KSPMonitorTrueResidual()`, `KSPMonitorErrorDrawLG()`
680: @*/
681: PetscErrorCode KSPMonitorErrorDraw(KSP ksp, PetscInt n, PetscReal rnorm, PetscViewerAndFormat *vf)
682: {
683: PetscViewer viewer = vf->viewer;
684: PetscViewerFormat format = vf->format;
685: DM dm;
686: Vec sol, e;
688: PetscFunctionBegin;
690: PetscCall(PetscViewerPushFormat(viewer, format));
691: PetscCall(KSPGetDM(ksp, &dm));
692: PetscCall(DMGetGlobalVector(dm, &sol));
693: PetscCall(KSPBuildSolution(ksp, sol, NULL));
694: PetscCall(DMComputeError(dm, sol, NULL, &e));
695: PetscCall(PetscObjectSetName((PetscObject)e, "Error"));
696: PetscCall(PetscObjectCompose((PetscObject)e, "__Vec_bc_zero__", (PetscObject)ksp));
697: PetscCall(VecView(e, viewer));
698: PetscCall(PetscObjectCompose((PetscObject)e, "__Vec_bc_zero__", NULL));
699: PetscCall(VecDestroy(&e));
700: PetscCall(DMRestoreGlobalVector(dm, &sol));
701: PetscCall(PetscViewerPopFormat(viewer));
702: PetscFunctionReturn(PETSC_SUCCESS);
703: }
705: /*@C
706: KSPMonitorErrorDrawLG - Plots the error and residual norm at each iteration of an iterative solver.
708: Collective
710: Input Parameters:
711: + ksp - iterative context
712: . n - iteration number
713: . rnorm - 2-norm (preconditioned) residual value (may be estimated).
714: - vf - The viewer context
716: Options Database Key:
717: . -ksp_monitor_error draw::draw_lg - Activates `KSPMonitorTrueResidualDrawLG()`
719: Level: intermediate
721: Notes:
722: This is not called directly by users, rather one calls `KSPMonitorSet()`, with this function as an argument, to cause the monitor
723: to be used during the `KSP` solve.
725: Call `KSPMonitorErrorDrawLGCreate()` to create the context used with this monitor
727: .seealso: [](chapter_ksp), `PETSCVIEWERDRAW`, `KSP`, `KSPMonitorSet()`, `KSPMonitorTrueResidual()`, `KSPMonitorErrorDraw()`
728: @*/
729: PetscErrorCode KSPMonitorErrorDrawLG(KSP ksp, PetscInt n, PetscReal rnorm, PetscViewerAndFormat *vf)
730: {
731: PetscViewer viewer = vf->viewer;
732: PetscViewerFormat format = vf->format;
733: PetscDrawLG lg = vf->lg;
734: DM dm;
735: Vec sol;
736: KSPConvergedReason reason;
737: PetscReal *x, *errors;
738: PetscInt Nf, f;
740: PetscFunctionBegin;
743: PetscCall(KSPGetDM(ksp, &dm));
744: PetscCall(DMGetNumFields(dm, &Nf));
745: PetscCall(DMGetGlobalVector(dm, &sol));
746: PetscCall(KSPBuildSolution(ksp, sol, NULL));
747: /* TODO: Make a different monitor that flips sign for SNES, Newton system is A dx = -b, so we need to negate the solution */
748: PetscCall(VecScale(sol, -1.0));
749: PetscCall(PetscCalloc2(Nf + 1, &x, Nf + 1, &errors));
750: PetscCall(DMComputeError(dm, sol, errors, NULL));
752: PetscCall(PetscViewerPushFormat(viewer, format));
753: if (!n) PetscCall(PetscDrawLGReset(lg));
754: for (f = 0; f < Nf; ++f) {
755: x[f] = (PetscReal)n;
756: errors[f] = errors[f] > 0.0 ? PetscLog10Real(errors[f]) : -15.;
757: }
758: x[Nf] = (PetscReal)n;
759: errors[Nf] = rnorm > 0.0 ? PetscLog10Real(rnorm) : -15.;
760: PetscCall(PetscDrawLGAddPoint(lg, x, errors));
761: PetscCall(KSPGetConvergedReason(ksp, &reason));
762: if (n <= 20 || !(n % 5) || reason) {
763: PetscCall(PetscDrawLGDraw(lg));
764: PetscCall(PetscDrawLGSave(lg));
765: }
766: PetscCall(PetscViewerPopFormat(viewer));
767: PetscFunctionReturn(PETSC_SUCCESS);
768: }
770: /*@C
771: KSPMonitorErrorDrawLGCreate - Creates the context for the error and preconditioned residual plotter `KSPMonitorErrorDrawLG()`
773: Collective
775: Input Parameters:
776: + viewer - The `PetscViewer`
777: . format - The viewer format
778: - ctx - An optional user context
780: Output Parameter:
781: . vf - The viewer context
783: Level: intermediate
785: .seealso: [](chapter_ksp), `PETSCVIEWERDRAW`, `KSP`, `KSPMonitorSet()`, `KSPMonitorTrueResidual()`, `KSPMonitorErrorDrawLG()`, `KSPMonitorErrorDrawLG()`
786: @*/
787: PetscErrorCode KSPMonitorErrorDrawLGCreate(PetscViewer viewer, PetscViewerFormat format, void *ctx, PetscViewerAndFormat **vf)
788: {
789: KSP ksp = (KSP)ctx;
790: DM dm;
791: char **names;
792: PetscInt Nf, f;
794: PetscFunctionBegin;
795: PetscCall(KSPGetDM(ksp, &dm));
796: PetscCall(DMGetNumFields(dm, &Nf));
797: PetscCall(PetscMalloc1(Nf + 1, &names));
798: for (f = 0; f < Nf; ++f) {
799: PetscObject disc;
800: const char *fname;
801: char lname[PETSC_MAX_PATH_LEN];
803: PetscCall(DMGetField(dm, f, NULL, &disc));
804: PetscCall(PetscObjectGetName(disc, &fname));
805: PetscCall(PetscStrncpy(lname, fname, PETSC_MAX_PATH_LEN));
806: PetscCall(PetscStrlcat(lname, " Error", PETSC_MAX_PATH_LEN));
807: PetscCall(PetscStrallocpy(lname, &names[f]));
808: }
809: PetscCall(PetscStrallocpy("residual", &names[Nf]));
810: PetscCall(PetscViewerAndFormatCreate(viewer, format, vf));
811: (*vf)->data = ctx;
812: PetscCall(KSPMonitorLGCreate(PetscObjectComm((PetscObject)viewer), NULL, NULL, "Log Error Norm", Nf + 1, (const char **)names, PETSC_DECIDE, PETSC_DECIDE, 400, 300, &(*vf)->lg));
813: for (f = 0; f <= Nf; ++f) PetscCall(PetscFree(names[f]));
814: PetscCall(PetscFree(names));
815: PetscFunctionReturn(PETSC_SUCCESS);
816: }
818: /*@C
819: KSPMonitorSolution - Print the solution norm at each iteration of an iterative solver.
821: Collective
823: Input Parameters:
824: + ksp - iterative context
825: . n - iteration number
826: . rnorm - 2-norm (preconditioned) residual value (may be estimated).
827: - vf - The viewer context
829: Options Database Key:
830: . -ksp_monitor_solution - Activates `KSPMonitorSolution()`
832: Level: intermediate
834: Note:
835: This is not called directly by users, rather one calls `KSPMonitorSet()`, with this function as an argument, to cause the monitor
836: to be used during the `KSP` solve.
838: .seealso: [](chapter_ksp), `KSPMonitorSet()`, `KSPMonitorTrueResidual()`
839: @*/
840: PetscErrorCode KSPMonitorSolution(KSP ksp, PetscInt n, PetscReal rnorm, PetscViewerAndFormat *vf)
841: {
842: PetscViewer viewer = vf->viewer;
843: PetscViewerFormat format = vf->format;
844: Vec x;
845: PetscReal snorm;
846: PetscInt tablevel;
847: const char *prefix;
849: PetscFunctionBegin;
851: PetscCall(KSPBuildSolution(ksp, NULL, &x));
852: PetscCall(VecNorm(x, NORM_2, &snorm));
853: PetscCall(PetscObjectGetTabLevel((PetscObject)ksp, &tablevel));
854: PetscCall(PetscObjectGetOptionsPrefix((PetscObject)ksp, &prefix));
855: PetscCall(PetscViewerPushFormat(viewer, format));
856: PetscCall(PetscViewerASCIIAddTab(viewer, tablevel));
857: if (n == 0 && prefix) PetscCall(PetscViewerASCIIPrintf(viewer, " Solution norms for %s solve.\n", prefix));
858: PetscCall(PetscViewerASCIIPrintf(viewer, "%3" PetscInt_FMT " KSP Solution norm %14.12e \n", n, (double)snorm));
859: PetscCall(PetscViewerASCIISubtractTab(viewer, tablevel));
860: PetscCall(PetscViewerPopFormat(viewer));
861: PetscFunctionReturn(PETSC_SUCCESS);
862: }
864: /*@C
865: KSPMonitorSolutionDraw - Plots the solution at each iteration of an iterative solver.
867: Collective
869: Input Parameters:
870: + ksp - iterative context
871: . n - iteration number
872: . rnorm - 2-norm (preconditioned) residual value (may be estimated).
873: - vf - The viewer context
875: Options Database Key:
876: . -ksp_monitor_solution draw - Activates `KSPMonitorSolutionDraw()`
878: Level: intermediate
880: Note:
881: This is not called directly by users, rather one calls `KSPMonitorSet()`, with this function as an argument, to cause the monitor
882: to be used during the `KSP` solve.
884: .seealso: [](chapter_ksp), `KSPMonitorSet()`, `KSPMonitorTrueResidual()`
885: @*/
886: PetscErrorCode KSPMonitorSolutionDraw(KSP ksp, PetscInt n, PetscReal rnorm, PetscViewerAndFormat *vf)
887: {
888: PetscViewer viewer = vf->viewer;
889: PetscViewerFormat format = vf->format;
890: Vec x;
892: PetscFunctionBegin;
894: PetscCall(KSPBuildSolution(ksp, NULL, &x));
895: PetscCall(PetscViewerPushFormat(viewer, format));
896: PetscCall(PetscObjectSetName((PetscObject)x, "Solution"));
897: PetscCall(PetscObjectCompose((PetscObject)x, "__Vec_bc_zero__", (PetscObject)ksp));
898: PetscCall(VecView(x, viewer));
899: PetscCall(PetscObjectCompose((PetscObject)x, "__Vec_bc_zero__", NULL));
900: PetscCall(PetscViewerPopFormat(viewer));
901: PetscFunctionReturn(PETSC_SUCCESS);
902: }
904: /*@C
905: KSPMonitorSolutionDrawLG - Plots the solution norm at each iteration of an iterative solver.
907: Collective
909: Input Parameters:
910: + ksp - iterative context
911: . n - iteration number
912: . rnorm - 2-norm (preconditioned) residual value (may be estimated).
913: - vf - The viewer context
915: Options Database Key:
916: . -ksp_monitor_solution draw::draw_lg - Activates `KSPMonitorSolutionDrawLG()`
918: Level: intermediate
920: Notes:
921: This is not called directly by users, rather one calls `KSPMonitorSet()`, with this function as an argument, to cause the monitor
922: to be used during the `KSP` solve.
924: Call `KSPMonitorSolutionDrawLGCreate()` to create the context needed with this monitor
926: .seealso: [](chapter_ksp), `KSP`, `KSPMonitorSet()`, `KSPMonitorTrueResidual()`, `KSPMonitorSolutionDrawLGCreate()`
927: @*/
928: PetscErrorCode KSPMonitorSolutionDrawLG(KSP ksp, PetscInt n, PetscReal rnorm, PetscViewerAndFormat *vf)
929: {
930: PetscViewer viewer = vf->viewer;
931: PetscViewerFormat format = vf->format;
932: PetscDrawLG lg = vf->lg;
933: Vec u;
934: KSPConvergedReason reason;
935: PetscReal snorm, x, y;
937: PetscFunctionBegin;
940: PetscCall(KSPBuildSolution(ksp, NULL, &u));
941: PetscCall(VecNorm(u, NORM_2, &snorm));
942: PetscCall(PetscViewerPushFormat(viewer, format));
943: if (!n) PetscCall(PetscDrawLGReset(lg));
944: x = (PetscReal)n;
945: if (snorm > 0.0) y = PetscLog10Real(snorm);
946: else y = -15.0;
947: PetscCall(PetscDrawLGAddPoint(lg, &x, &y));
948: PetscCall(KSPGetConvergedReason(ksp, &reason));
949: if (n <= 20 || !(n % 5) || reason) {
950: PetscCall(PetscDrawLGDraw(lg));
951: PetscCall(PetscDrawLGSave(lg));
952: }
953: PetscCall(PetscViewerPopFormat(viewer));
954: PetscFunctionReturn(PETSC_SUCCESS);
955: }
957: /*@C
958: KSPMonitorSolutionDrawLGCreate - Creates the context for the `KSP` monitor `KSPMonitorSolutionDrawLG()`
960: Collective
962: Input Parameters:
963: + viewer - The `PetscViewer`
964: . format - The viewer format
965: - ctx - An optional user context
967: Output Parameter:
968: . vf - The viewer context
970: Level: intermediate
972: Note:
973: This is not called directly by users, rather one calls `KSPMonitorSet()`, with this function as an argument, to cause the monitor
974: to be used during the `KSP` solve.
976: .seealso: [](chapter_ksp), `KSPMonitorSet()`, `KSPMonitorTrueResidual()`
977: @*/
978: PetscErrorCode KSPMonitorSolutionDrawLGCreate(PetscViewer viewer, PetscViewerFormat format, void *ctx, PetscViewerAndFormat **vf)
979: {
980: PetscFunctionBegin;
981: PetscCall(PetscViewerAndFormatCreate(viewer, format, vf));
982: (*vf)->data = ctx;
983: PetscCall(KSPMonitorLGCreate(PetscObjectComm((PetscObject)viewer), NULL, NULL, "Log Solution Norm", 1, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, &(*vf)->lg));
984: PetscFunctionReturn(PETSC_SUCCESS);
985: }
987: /*@C
988: KSPMonitorSingularValue - Prints the two norm of the true residual and estimation of the extreme singular values of the preconditioned problem at each iteration.
990: Logically Collective
992: Input Parameters:
993: + ksp - the iterative context
994: . n - the iteration
995: . rnorm - the two norm of the residual
996: - vf - The viewer context
998: Options Database Key:
999: . -ksp_monitor_singular_value - Activates `KSPMonitorSingularValue()`
1001: Level: intermediate
1003: Notes:
1004: The `KSPCG` solver uses the Lanczos technique for eigenvalue computation,
1005: while `KSPGMRES` uses the Arnoldi technique; other iterative methods do
1006: not currently compute singular values.
1008: This is not called directly by users, rather one calls `KSPMonitorSet()`, with this function as an argument, to cause the monitor
1009: to be used during the `KSP` solve.
1011: Call `KSPMonitorSingularValueCreate()` to create the context needed by this monitor
1013: .seealso: [](chapter_ksp), `KSP`, `KSPMonitorSet()`, `KSPComputeExtremeSingularValues()`, `KSPMonitorSingularValueCreate()`
1014: @*/
1015: PetscErrorCode KSPMonitorSingularValue(KSP ksp, PetscInt n, PetscReal rnorm, PetscViewerAndFormat *vf)
1016: {
1017: PetscViewer viewer = vf->viewer;
1018: PetscViewerFormat format = vf->format;
1019: PetscReal emin, emax;
1020: PetscInt tablevel;
1021: const char *prefix;
1023: PetscFunctionBegin;
1026: PetscCall(PetscObjectGetTabLevel((PetscObject)ksp, &tablevel));
1027: PetscCall(PetscObjectGetOptionsPrefix((PetscObject)ksp, &prefix));
1028: PetscCall(PetscViewerPushFormat(viewer, format));
1029: PetscCall(PetscViewerASCIIAddTab(viewer, tablevel));
1030: if (n == 0 && prefix) PetscCall(PetscViewerASCIIPrintf(viewer, " Residual norms for %s solve.\n", prefix));
1031: if (!ksp->calc_sings) {
1032: PetscCall(PetscViewerASCIIPrintf(viewer, "%3" PetscInt_FMT " KSP Residual norm %14.12e \n", n, (double)rnorm));
1033: } else {
1034: PetscCall(KSPComputeExtremeSingularValues(ksp, &emax, &emin));
1035: PetscCall(PetscViewerASCIIPrintf(viewer, "%3" PetscInt_FMT " KSP Residual norm %14.12e %% max %14.12e min %14.12e max/min %14.12e\n", n, (double)rnorm, (double)emax, (double)emin, (double)(emax / emin)));
1036: }
1037: PetscCall(PetscViewerASCIISubtractTab(viewer, tablevel));
1038: PetscCall(PetscViewerPopFormat(viewer));
1039: PetscFunctionReturn(PETSC_SUCCESS);
1040: }
1042: /*@C
1043: KSPMonitorSingularValueCreate - Creates the singular value monitor context needed by `KSPMonitorSingularValue()`
1045: Collective
1047: Input Parameters:
1048: + viewer - The PetscViewer
1049: . format - The viewer format
1050: - ctx - An optional user context
1052: Output Parameter:
1053: . vf - The viewer context
1055: Level: intermediate
1057: .seealso: [](chapter_ksp), `KSP`, `KSPMonitorSet()`, `KSPMonitorSingularValue()`, `PetscViewer`
1058: @*/
1059: PetscErrorCode KSPMonitorSingularValueCreate(PetscViewer viewer, PetscViewerFormat format, void *ctx, PetscViewerAndFormat **vf)
1060: {
1061: KSP ksp = (KSP)ctx;
1063: PetscFunctionBegin;
1064: PetscCall(PetscViewerAndFormatCreate(viewer, format, vf));
1065: (*vf)->data = ctx;
1066: PetscCall(KSPSetComputeSingularValues(ksp, PETSC_TRUE));
1067: PetscFunctionReturn(PETSC_SUCCESS);
1068: }
1070: /*@C
1071: KSPMonitorDynamicToleranceCreate - Creates the context used by `KSPMonitorDynamicTolerance()`
1073: Logically Collective
1075: Output Parameter:
1076: . ctx - a void pointer
1078: Options Database Key:
1079: . -sub_ksp_dynamic_tolerance <coef> - coefficient of dynamic tolerance for inner solver, default is 1.0
1081: Level: advanced
1083: Note:
1084: Use before calling `KSPMonitorSet()` with `KSPMonitorDynamicTolerance()`
1086: The default coefficient for the tolerance can be changed with `KSPMonitorDynamicToleranceSetCoefficient()`
1088: .seealso: [](sec_flexibleksp), `KSP`, `KSPMonitorDynamicTolerance()`, `KSPMonitorDynamicToleranceDestroy()`, `KSPMonitorDynamicToleranceSetCoefficient()`
1089: @*/
1090: PetscErrorCode KSPMonitorDynamicToleranceCreate(void *ctx)
1091: {
1092: KSPDynTolCtx *scale;
1094: PetscFunctionBegin;
1095: PetscCall(PetscMalloc1(1, &scale));
1096: scale->bnrm = -1.0;
1097: scale->coef = 1.0;
1098: *(void **)ctx = scale;
1099: PetscFunctionReturn(PETSC_SUCCESS);
1100: }
1102: /*@C
1103: KSPMonitorDynamicToleranceSetCoefficient - Sets the coefficient in the context used by `KSPMonitorDynamicTolerance()`
1105: Logically Collective
1107: Output Parameters:
1108: + ctx - the context for `KSPMonitorDynamicTolerance()`
1109: - coeff - the coefficient, default is 1.0
1111: Options Database Key:
1112: . -sub_ksp_dynamic_tolerance <coef> - coefficient of dynamic tolerance for inner solver, default is 1.0
1114: Level: advanced
1116: Note:
1117: Use before calling `KSPMonitorSet()` and after `KSPMonitorDynamicToleranceCreate()`
1119: .seealso: [](sec_flexibleksp), `KSP`, `KSPMonitorDynamicTolerance()`, `KSPMonitorDynamicToleranceDestroy()`, `KSPMonitorDynamicToleranceCreate()`
1120: @*/
1121: PetscErrorCode KSPMonitorDynamicToleranceSetCoefficient(void *ctx, PetscReal coeff)
1122: {
1123: KSPDynTolCtx *scale = (KSPDynTolCtx *)ctx;
1125: PetscFunctionBegin;
1126: scale->coef = coeff;
1127: PetscFunctionReturn(PETSC_SUCCESS);
1128: }
1130: /*@C
1131: KSPMonitorDynamicTolerance - A monitor that changes the inner tolerance of nested preconditioners in every outer iteration in an adaptive way.
1133: Collective
1135: Input Parameters:
1136: + ksp - iterative context
1137: . n - iteration number (not used)
1138: . fnorm - the current residual norm
1139: - ctx - context used by monitor
1141: Options Database Key:
1142: . -sub_ksp_dynamic_tolerance <coef> - coefficient of dynamic tolerance for inner solver, default is 1.0
1144: Level: advanced
1146: Notes:
1147: Applies for `PCKSP`, `PCBJACOBI`, and `PCDEFLATION` preconditioners
1149: This may be useful for a flexible preconditioned Krylov method, such as `KSPFGMRES`, [](sec_flexibleksp) to
1150: control the accuracy of the inner solves needed to guarantee convergence of the outer iterations.
1152: This is not called directly by users, rather one calls `KSPMonitorSet()`, with this function as an argument, to cause the monitor
1153: to be used during the `KSP` solve.
1155: Use `KSPMonitorDynamicToleranceCreate()` and `KSPMonitorDynamicToleranceSetCoefficient()` to create the context needed by this
1156: monitor function.
1158: Pass the context and `KSPMonitorDynamicToleranceDestroy()` to `KSPMonitorSet()`
1160: .seealso: [](sec_flexibleksp), `KSP`, `KSPMonitorDynamicToleranceCreate()`, `KSPMonitorDynamicToleranceDestroy()`, `KSPMonitorDynamicToleranceSetCoefficient()`
1161: @*/
1162: PetscErrorCode KSPMonitorDynamicTolerance(KSP ksp, PetscInt its, PetscReal fnorm, void *dummy)
1163: {
1164: PC pc;
1165: PetscReal outer_rtol, outer_abstol, outer_dtol, inner_rtol;
1166: PetscInt outer_maxits, nksp, first, i;
1167: KSPDynTolCtx *scale = (KSPDynTolCtx *)dummy;
1168: KSP *subksp = NULL;
1169: KSP kspinner;
1170: PetscBool flg;
1172: PetscFunctionBegin;
1173: PetscCall(KSPGetPC(ksp, &pc));
1175: /* compute inner_rtol */
1176: if (scale->bnrm < 0.0) {
1177: Vec b;
1178: PetscCall(KSPGetRhs(ksp, &b));
1179: PetscCall(VecNorm(b, NORM_2, &(scale->bnrm)));
1180: }
1181: PetscCall(KSPGetTolerances(ksp, &outer_rtol, &outer_abstol, &outer_dtol, &outer_maxits));
1182: inner_rtol = PetscMin(scale->coef * scale->bnrm * outer_rtol / fnorm, 0.999);
1184: /* if pc is ksp */
1185: PetscCall(PetscObjectTypeCompare((PetscObject)pc, PCKSP, &flg));
1186: if (flg) {
1187: PetscCall(PCKSPGetKSP(pc, &kspinner));
1188: PetscCall(KSPSetTolerances(kspinner, inner_rtol, outer_abstol, outer_dtol, outer_maxits));
1189: PetscFunctionReturn(PETSC_SUCCESS);
1190: }
1192: /* if pc is bjacobi */
1193: PetscCall(PetscObjectTypeCompare((PetscObject)pc, PCBJACOBI, &flg));
1194: if (flg) {
1195: PetscCall(PCBJacobiGetSubKSP(pc, &nksp, &first, &subksp));
1196: if (subksp) {
1197: for (i = 0; i < nksp; i++) PetscCall(KSPSetTolerances(subksp[i], inner_rtol, outer_abstol, outer_dtol, outer_maxits));
1198: PetscFunctionReturn(PETSC_SUCCESS);
1199: }
1200: }
1202: /* if pc is deflation*/
1203: PetscCall(PetscObjectTypeCompare((PetscObject)pc, PCDEFLATION, &flg));
1204: if (flg) {
1205: PetscCall(PCDeflationGetCoarseKSP(pc, &kspinner));
1206: PetscCall(KSPSetTolerances(kspinner, inner_rtol, outer_abstol, outer_dtol, PETSC_DEFAULT));
1207: PetscFunctionReturn(PETSC_SUCCESS);
1208: }
1210: /* todo: dynamic tolerance may apply to other types of pc */
1211: PetscFunctionReturn(PETSC_SUCCESS);
1212: }
1214: /*@C
1215: KSPMonitorDynamicToleranceDestroy - Destroy the monitor context used in `KSPMonitorDynamicTolerance()`
1217: Input Parameter:
1218: . ctx - the monitor context
1220: Level: advanced
1222: Note:
1223: This is not called directly but is passed to `KSPMonitorSet()` along with `KSPMonitorDynamicTolerance()`
1225: .seealso: `KSP`, `KSPMonitorDynamicTolerance()`, `KSPMonitorSet()`, `KSPMonitorDynamicToleranceCreate()`
1226: @*/
1227: PetscErrorCode KSPMonitorDynamicToleranceDestroy(void **ctx)
1228: {
1229: PetscFunctionBegin;
1230: PetscCall(PetscFree(*ctx));
1231: PetscFunctionReturn(PETSC_SUCCESS);
1232: }
1234: /*@C
1235: KSPConvergedSkip - Convergence test that do not return as converged
1236: until the maximum number of iterations is reached.
1238: Collective
1240: Input Parameters:
1241: + ksp - iterative context
1242: . n - iteration number
1243: . rnorm - 2-norm residual value (may be estimated)
1244: - dummy - unused convergence context
1246: Output Parameter:
1247: . reason - `KSP_CONVERGED_ITERATING`, `KSP_CONVERGED_ITS`
1249: Level: advanced
1251: Notes:
1252: This should be used as the convergence test with the option
1253: `KSPSetNormType`(ksp,`KSP_NORM_NONE`), since norms of the residual are
1254: not computed. Convergence is then declared after the maximum number
1255: of iterations have been reached. Useful when one is using `KSPCG` or
1256: `KSPBCGS`. [](sec_flexibleksp)
1258: .seealso: [](chapter_ksp), `KSP`, `KSPCG`, `KSPBCGS`, `KSPSetConvergenceTest()`, `KSPSetTolerances()`, `KSPSetNormType()`, [](sec_flexibleksp),
1259: `KSPConvergedReason`
1260: @*/
1261: PetscErrorCode KSPConvergedSkip(KSP ksp, PetscInt n, PetscReal rnorm, KSPConvergedReason *reason, void *dummy)
1262: {
1263: PetscFunctionBegin;
1266: *reason = KSP_CONVERGED_ITERATING;
1267: if (n >= ksp->max_it) *reason = KSP_CONVERGED_ITS;
1268: PetscFunctionReturn(PETSC_SUCCESS);
1269: }
1271: /*@C
1272: KSPConvergedDefaultCreate - Creates and initializes the context used by the `KSPConvergedDefault()` function
1274: Note Collective
1276: Output Parameter:
1277: . ctx - convergence context
1279: Level: intermediate
1281: .seealso: [](chapter_ksp), `KSP`, `KSPConvergedDefault()`, `KSPConvergedDefaultDestroy()`, `KSPSetConvergenceTest()`, `KSPSetTolerances()`,
1282: `KSPConvergedSkip()`, `KSPConvergedReason`, `KSPGetConvergedReason()`, `KSPConvergedDefaultSetUIRNorm()`, `KSPConvergedDefaultSetUMIRNorm()`,
1283: `KSPConvergedDefaultSetConvergedMaxits()`
1284: @*/
1285: PetscErrorCode KSPConvergedDefaultCreate(void **ctx)
1286: {
1287: KSPConvergedDefaultCtx *cctx;
1289: PetscFunctionBegin;
1290: PetscCall(PetscNew(&cctx));
1291: *ctx = cctx;
1292: PetscFunctionReturn(PETSC_SUCCESS);
1293: }
1295: /*@
1296: KSPConvergedDefaultSetUIRNorm - makes the default convergence test use || B*(b - A*(initial guess))||
1297: instead of || B*b ||. In the case of right preconditioner or if `KSPSetNormType`(ksp,`KSP_NORM_UNPRECONDITIONED`)
1298: is used there is no B in the above formula. UIRNorm is short for Use Initial Residual Norm.
1300: Collective
1302: Input Parameters:
1303: . ksp - iterative context
1305: Options Database Key:
1306: . -ksp_converged_use_initial_residual_norm <bool> - Use initial residual norm for computing relative convergence
1308: Level: intermediate
1310: Notes:
1311: Use `KSPSetTolerances()` to alter the defaults for rtol, abstol, dtol.
1313: The precise values of reason are macros such as `KSP_CONVERGED_RTOL`, which
1314: are defined in petscksp.h.
1316: If the convergence test is not `KSPConvergedDefault()` then this is ignored.
1318: If right preconditioning is being used then B does not appear in the above formula.
1320: .seealso: [](chapter_ksp), `KSP`, `KSPSetConvergenceTest()`, `KSPSetTolerances()`, `KSPConvergedSkip()`, `KSPConvergedReason`, `KSPGetConvergedReason()`, `KSPConvergedDefaultSetUMIRNorm()`, `KSPConvergedDefaultSetConvergedMaxits()`
1321: @*/
1322: PetscErrorCode KSPConvergedDefaultSetUIRNorm(KSP ksp)
1323: {
1324: KSPConvergedDefaultCtx *ctx = (KSPConvergedDefaultCtx *)ksp->cnvP;
1326: PetscFunctionBegin;
1328: if (ksp->converged != KSPConvergedDefault) PetscFunctionReturn(PETSC_SUCCESS);
1329: PetscCheck(!ctx->mininitialrtol, PetscObjectComm((PetscObject)ksp), PETSC_ERR_ARG_WRONGSTATE, "Cannot use KSPConvergedDefaultSetUIRNorm() and KSPConvergedDefaultSetUMIRNorm() together");
1330: ctx->initialrtol = PETSC_TRUE;
1331: PetscFunctionReturn(PETSC_SUCCESS);
1332: }
1334: /*@
1335: KSPConvergedDefaultSetUMIRNorm - makes the default convergence test use min(|| B*(b - A*(initial guess))||,|| B*b ||)
1336: In the case of right preconditioner or if `KSPSetNormType`(ksp,`KSP_NORM_UNPRECONDITIONED`)
1337: is used there is no B in the above formula. UMIRNorm is short for Use Minimum Initial Residual Norm.
1339: Collective
1341: Input Parameters:
1342: . ksp - iterative context
1344: Options Database Key:
1345: . -ksp_converged_use_min_initial_residual_norm <bool> - Use minimum of initial residual norm and b for computing relative convergence
1347: Level: intermediate
1349: Use `KSPSetTolerances()` to alter the defaults for rtol, abstol, dtol.
1351: The precise values of reason are macros such as `KSP_CONVERGED_RTOL`, which
1352: are defined in petscksp.h.
1354: .seealso: [](chapter_ksp), `KSP`, `KSPSetConvergenceTest()`, `KSPSetTolerances()`, `KSPConvergedSkip()`, `KSPConvergedReason`, `KSPGetConvergedReason()`, `KSPConvergedDefaultSetUIRNorm()`, `KSPConvergedDefaultSetConvergedMaxits()`
1355: @*/
1356: PetscErrorCode KSPConvergedDefaultSetUMIRNorm(KSP ksp)
1357: {
1358: KSPConvergedDefaultCtx *ctx = (KSPConvergedDefaultCtx *)ksp->cnvP;
1360: PetscFunctionBegin;
1362: if (ksp->converged != KSPConvergedDefault) PetscFunctionReturn(PETSC_SUCCESS);
1363: PetscCheck(!ctx->initialrtol, PetscObjectComm((PetscObject)ksp), PETSC_ERR_ARG_WRONGSTATE, "Cannot use KSPConvergedDefaultSetUIRNorm() and KSPConvergedDefaultSetUMIRNorm() together");
1364: ctx->mininitialrtol = PETSC_TRUE;
1365: PetscFunctionReturn(PETSC_SUCCESS);
1366: }
1368: /*@
1369: KSPConvergedDefaultSetConvergedMaxits - allows the default convergence test to declare convergence and return `KSP_CONVERGED_ITS` if the maximum number of iterations is reached
1371: Collective
1373: Input Parameters:
1374: + ksp - iterative context
1375: - flg - boolean flag
1377: Options Database Key:
1378: . -ksp_converged_maxits <bool> - Declare convergence if the maximum number of iterations is reached
1380: Level: intermediate
1382: Note:
1383: The precise values of reason available in `KSPConvergedReason`
1385: .seealso: [](chapter_ksp), `KSP`, `KSPSetConvergenceTest()`, `KSPSetTolerances()`, `KSPConvergedSkip()`, `KSPConvergedReason`, `KSPGetConvergedReason()`, `KSPConvergedDefaultSetUMIRNorm()`, `KSPConvergedDefaultSetUIRNorm()`
1386: @*/
1387: PetscErrorCode KSPConvergedDefaultSetConvergedMaxits(KSP ksp, PetscBool flg)
1388: {
1389: KSPConvergedDefaultCtx *ctx = (KSPConvergedDefaultCtx *)ksp->cnvP;
1391: PetscFunctionBegin;
1394: if (ksp->converged != KSPConvergedDefault) PetscFunctionReturn(PETSC_SUCCESS);
1395: ctx->convmaxits = flg;
1396: PetscFunctionReturn(PETSC_SUCCESS);
1397: }
1399: /*@C
1400: KSPConvergedDefault - Default code to determine convergence of the linear iterative solvers
1402: Collective
1404: Input Parameters:
1405: + ksp - iterative context
1406: . n - iteration number
1407: . rnorm - residual norm (may be estimated, depending on the method may be the preconditioned residual norm)
1408: - ctx - convergence context which must be created by `KSPConvergedDefaultCreate()`
1410: Output Parameter:
1411: . reason - the convergence reason; it is positive if the iteration has converged,
1412: negative if the iteration has diverged, and `KSP_CONVERGED_ITERATING` otherwise
1414: Options Database Keys:
1415: + -ksp_max_it - maximum number of linear iterations
1416: . -ksp_rtol rtol - relative tolerance used in default determination of convergence, i.e. if residual norm decreases by this factor than convergence is declared
1417: . -ksp_atol abstol - absolute tolerance used in default convergence test, i.e. if residual norm is less than this then convergence is declared
1418: . -ksp_divtol tol - if residual norm increases by this factor than divergence is declared
1419: . -ksp_converged_use_initial_residual_norm - see `KSPConvergedDefaultSetUIRNorm()`
1420: . -ksp_converged_use_min_initial_residual_norm - see `KSPConvergedDefaultSetUMIRNorm()`
1421: - -ksp_converged_maxits - see `KSPConvergedDefaultSetConvergedMaxits()`
1423: Level: advanced
1425: Notes:
1426: `KSPConvergedDefault()` reaches convergence when rnorm < MAX (rtol * rnorm_0, abstol);
1427: Divergence is detected if rnorm > dtol * rnorm_0, or when failures are detected throughout the iteration.
1428: By default, reaching the maximum number of iterations is considered divergence (i.e. KSP_DIVERGED_ITS).
1429: In order to have PETSc declaring convergence in such a case (i.e. `KSP_CONVERGED_ITS`), users can use `KSPConvergedDefaultSetConvergedMaxits()`
1431: where:
1432: + rtol - relative tolerance,
1433: . abstol - absolute tolerance.
1434: . dtol - divergence tolerance,
1435: - rnorm_0 - the two norm of the right hand side (or the preconditioned norm, depending on what was set with
1436: `KSPSetNormType()`. When initial guess is non-zero you
1437: can call `KSPConvergedDefaultSetUIRNorm()` to use the norm of (b - A*(initial guess))
1438: as the starting point for relative norm convergence testing, that is as rnorm_0.
1439: Call `KSPConvergedDefaultSetUMIRNorm()` to use the minimum of the norm of (b - A*(initial guess)) and the norm of b as the starting point.
1441: Use `KSPSetTolerances()` to alter the defaults for rtol, abstol, dtol.
1443: Use `KSPSetNormType()` (or -ksp_norm_type <none,preconditioned,unpreconditioned,natural>) to change the norm used for computing rnorm
1445: The precise values of reason are available in `KSPConvergedReason`
1447: This routine is used by `KSP` by default so the user generally never needs call it directly.
1449: Use `KSPSetConvergenceTest()` to provide your own test instead of using this one.
1451: Call `KSPSetConvergenceTest()` with the ctx, as created above and the destruction function `KSPConvergedDefaultDestroy()`
1453: .seealso: [](chapter_ksp), `KSP`, `KSPSetConvergenceTest()`, `KSPSetTolerances()`, `KSPConvergedSkip()`, `KSPConvergedReason`, `KSPGetConvergedReason()`,
1454: `KSPConvergedDefaultSetUIRNorm()`, `KSPConvergedDefaultSetUMIRNorm()`, `KSPConvergedDefaultSetConvergedMaxits()`, `KSPConvergedDefaultCreate()`, `KSPConvergedDefaultDestroy()`
1455: @*/
1456: PetscErrorCode KSPConvergedDefault(KSP ksp, PetscInt n, PetscReal rnorm, KSPConvergedReason *reason, void *ctx)
1457: {
1458: KSPConvergedDefaultCtx *cctx = (KSPConvergedDefaultCtx *)ctx;
1459: KSPNormType normtype;
1461: PetscFunctionBegin;
1465: PetscCheck(cctx, PetscObjectComm((PetscObject)ksp), PETSC_ERR_ARG_NULL, "Convergence context must have been created with KSPConvergedDefaultCreate()");
1466: *reason = KSP_CONVERGED_ITERATING;
1468: if (cctx->convmaxits && n >= ksp->max_it) {
1469: *reason = KSP_CONVERGED_ITS;
1470: PetscCall(PetscInfo(ksp, "Linear solver has converged. Maximum number of iterations reached %" PetscInt_FMT "\n", n));
1471: PetscFunctionReturn(PETSC_SUCCESS);
1472: }
1473: PetscCall(KSPGetNormType(ksp, &normtype));
1474: if (normtype == KSP_NORM_NONE) PetscFunctionReturn(PETSC_SUCCESS);
1476: if (!n) {
1477: /* if user gives initial guess need to compute norm of b */
1478: if (!ksp->guess_zero && !cctx->initialrtol) {
1479: PetscReal snorm = 0.0;
1480: if (ksp->normtype == KSP_NORM_UNPRECONDITIONED || ksp->pc_side == PC_RIGHT) {
1481: PetscCall(PetscInfo(ksp, "user has provided nonzero initial guess, computing 2-norm of RHS\n"));
1482: PetscCall(VecNorm(ksp->vec_rhs, NORM_2, &snorm)); /* <- b'*b */
1483: } else {
1484: Vec z;
1485: /* Should avoid allocating the z vector each time but cannot stash it in cctx because if KSPReset() is called the vector size might change */
1486: PetscCall(VecDuplicate(ksp->vec_rhs, &z));
1487: PetscCall(KSP_PCApply(ksp, ksp->vec_rhs, z));
1488: if (ksp->normtype == KSP_NORM_PRECONDITIONED) {
1489: PetscCall(PetscInfo(ksp, "user has provided nonzero initial guess, computing 2-norm of preconditioned RHS\n"));
1490: PetscCall(VecNorm(z, NORM_2, &snorm)); /* dp <- b'*B'*B*b */
1491: } else if (ksp->normtype == KSP_NORM_NATURAL) {
1492: PetscScalar norm;
1493: PetscCall(PetscInfo(ksp, "user has provided nonzero initial guess, computing natural norm of RHS\n"));
1494: PetscCall(VecDot(ksp->vec_rhs, z, &norm));
1495: snorm = PetscSqrtReal(PetscAbsScalar(norm)); /* dp <- b'*B*b */
1496: }
1497: PetscCall(VecDestroy(&z));
1498: }
1499: /* handle special case of zero RHS and nonzero guess */
1500: if (!snorm) {
1501: PetscCall(PetscInfo(ksp, "Special case, user has provided nonzero initial guess and zero RHS\n"));
1502: snorm = rnorm;
1503: }
1504: if (cctx->mininitialrtol) ksp->rnorm0 = PetscMin(snorm, rnorm);
1505: else ksp->rnorm0 = snorm;
1506: } else {
1507: ksp->rnorm0 = rnorm;
1508: }
1509: ksp->ttol = PetscMax(ksp->rtol * ksp->rnorm0, ksp->abstol);
1510: }
1512: if (n <= ksp->chknorm) PetscFunctionReturn(PETSC_SUCCESS);
1514: if (PetscIsInfOrNanReal(rnorm)) {
1515: PCFailedReason pcreason;
1516: PetscInt sendbuf, recvbuf;
1517: PetscCall(PCGetFailedReasonRank(ksp->pc, &pcreason));
1518: sendbuf = (PetscInt)pcreason;
1519: PetscCallMPI(MPI_Allreduce(&sendbuf, &recvbuf, 1, MPIU_INT, MPI_MAX, PetscObjectComm((PetscObject)ksp)));
1520: if (recvbuf) {
1521: *reason = KSP_DIVERGED_PC_FAILED;
1522: PetscCall(PCSetFailedReason(ksp->pc, (PCFailedReason)recvbuf));
1523: PetscCall(PetscInfo(ksp, "Linear solver pcsetup fails, declaring divergence \n"));
1524: } else {
1525: *reason = KSP_DIVERGED_NANORINF;
1526: PetscCall(PetscInfo(ksp, "Linear solver has created a not a number (NaN) as the residual norm, declaring divergence \n"));
1527: }
1528: } else if (rnorm <= ksp->ttol) {
1529: if (rnorm < ksp->abstol) {
1530: PetscCall(PetscInfo(ksp, "Linear solver has converged. Residual norm %14.12e is less than absolute tolerance %14.12e at iteration %" PetscInt_FMT "\n", (double)rnorm, (double)ksp->abstol, n));
1531: *reason = KSP_CONVERGED_ATOL;
1532: } else {
1533: if (cctx->initialrtol) {
1534: PetscCall(PetscInfo(ksp, "Linear solver has converged. Residual norm %14.12e is less than relative tolerance %14.12e times initial residual norm %14.12e at iteration %" PetscInt_FMT "\n", (double)rnorm, (double)ksp->rtol, (double)ksp->rnorm0, n));
1535: } else {
1536: PetscCall(PetscInfo(ksp, "Linear solver has converged. Residual norm %14.12e is less than relative tolerance %14.12e times initial right hand side norm %14.12e at iteration %" PetscInt_FMT "\n", (double)rnorm, (double)ksp->rtol, (double)ksp->rnorm0, n));
1537: }
1538: *reason = KSP_CONVERGED_RTOL;
1539: }
1540: } else if (rnorm >= ksp->divtol * ksp->rnorm0) {
1541: PetscCall(PetscInfo(ksp, "Linear solver is diverging. Initial right hand size norm %14.12e, current residual norm %14.12e at iteration %" PetscInt_FMT "\n", (double)ksp->rnorm0, (double)rnorm, n));
1542: *reason = KSP_DIVERGED_DTOL;
1543: }
1544: PetscFunctionReturn(PETSC_SUCCESS);
1545: }
1547: /*@C
1548: KSPConvergedDefaultDestroy - Frees the space used by the `KSPConvergedDefault()` function context
1550: Not Collective
1552: Input Parameters:
1553: . ctx - convergence context
1555: Level: intermediate
1557: Note:
1558: Pass this function name into `KSPSetConvergenceTest()` along with the context obtained with `KSPConvergedDefaultCreate()` and `KSPConvergedDefault()`
1560: .seealso: [](chapter_ksp), `KSP`, `KSPConvergedDefault()`, `KSPConvergedDefaultCreate()`, `KSPSetConvergenceTest()`, `KSPSetTolerances()`, `KSPConvergedSkip()`,
1561: `KSPConvergedReason`, `KSPGetConvergedReason()`, `KSPConvergedDefaultSetUIRNorm()`, `KSPConvergedDefaultSetUMIRNorm()`
1562: @*/
1563: PetscErrorCode KSPConvergedDefaultDestroy(void *ctx)
1564: {
1565: KSPConvergedDefaultCtx *cctx = (KSPConvergedDefaultCtx *)ctx;
1567: PetscFunctionBegin;
1568: PetscCall(VecDestroy(&cctx->work));
1569: PetscCall(PetscFree(ctx));
1570: PetscFunctionReturn(PETSC_SUCCESS);
1571: }
1573: /*
1574: KSPBuildSolutionDefault - Default code to create/move the solution.
1576: Collective
1578: Input Parameters:
1579: + ksp - iterative context
1580: - v - pointer to the user's vector
1582: Output Parameter:
1583: . V - pointer to a vector containing the solution
1585: Level: advanced
1587: Developers Note:
1588: This is PETSC_EXTERN because it may be used by user written plugin `KSPType` implementations
1590: .seealso: [](chapter_ksp), `KSP`, `KSPGetSolution()`, `KSPBuildResidualDefault()`
1591: */
1592: PetscErrorCode KSPBuildSolutionDefault(KSP ksp, Vec v, Vec *V)
1593: {
1594: PetscFunctionBegin;
1595: if (ksp->pc_side == PC_RIGHT) {
1596: if (ksp->pc) {
1597: PetscCheck(v, PetscObjectComm((PetscObject)ksp), PETSC_ERR_SUP, "Not working with right preconditioner");
1598: PetscCall(KSP_PCApply(ksp, ksp->vec_sol, v));
1599: *V = v;
1600: } else {
1601: if (v) {
1602: PetscCall(VecCopy(ksp->vec_sol, v));
1603: *V = v;
1604: } else *V = ksp->vec_sol;
1605: }
1606: } else if (ksp->pc_side == PC_SYMMETRIC) {
1607: if (ksp->pc) {
1608: PetscCheck(!ksp->transpose_solve, PetscObjectComm((PetscObject)ksp), PETSC_ERR_SUP, "Not working with symmetric preconditioner and transpose solve");
1609: PetscCheck(v, PetscObjectComm((PetscObject)ksp), PETSC_ERR_SUP, "Not working with symmetric preconditioner");
1610: PetscCall(PCApplySymmetricRight(ksp->pc, ksp->vec_sol, v));
1611: *V = v;
1612: } else {
1613: if (v) {
1614: PetscCall(VecCopy(ksp->vec_sol, v));
1615: *V = v;
1616: } else *V = ksp->vec_sol;
1617: }
1618: } else {
1619: if (v) {
1620: PetscCall(VecCopy(ksp->vec_sol, v));
1621: *V = v;
1622: } else *V = ksp->vec_sol;
1623: }
1624: PetscFunctionReturn(PETSC_SUCCESS);
1625: }
1627: /*
1628: KSPBuildResidualDefault - Default code to compute the residual.
1630: Collecive on ksp
1632: Input Parameters:
1633: . ksp - iterative context
1634: . t - pointer to temporary vector
1635: . v - pointer to user vector
1637: Output Parameter:
1638: . V - pointer to a vector containing the residual
1640: Level: advanced
1642: Developers Note:
1643: This is PETSC_EXTERN because it may be used by user written plugin `KSPType` implementations
1645: .seealso: [](chapter_ksp), `KSP`, `KSPBuildSolutionDefault()`
1646: */
1647: PetscErrorCode KSPBuildResidualDefault(KSP ksp, Vec t, Vec v, Vec *V)
1648: {
1649: Mat Amat, Pmat;
1651: PetscFunctionBegin;
1652: if (!ksp->pc) PetscCall(KSPGetPC(ksp, &ksp->pc));
1653: PetscCall(PCGetOperators(ksp->pc, &Amat, &Pmat));
1654: PetscCall(KSPBuildSolution(ksp, t, NULL));
1655: PetscCall(KSP_MatMult(ksp, Amat, t, v));
1656: PetscCall(VecAYPX(v, -1.0, ksp->vec_rhs));
1657: *V = v;
1658: PetscFunctionReturn(PETSC_SUCCESS);
1659: }
1661: /*@C
1662: KSPCreateVecs - Gets a number of work vectors suitably sized for the operator in the `KSP`
1664: Collective
1666: Input Parameters:
1667: + ksp - iterative context
1668: . rightn - number of right work vectors
1669: - leftn - number of left work vectors to allocate
1671: Output Parameters:
1672: + right - the array of vectors created
1673: - left - the array of left vectors
1675: Level: advanced
1677: Notes:
1678: The right vector has as many elements as the matrix has columns. The left
1679: vector has as many elements as the matrix has rows.
1681: The vectors are new vectors that are not owned by the `KSP`, they should be destroyed with calls to `VecDestroyVecs()` when no longer needed.
1683: Developers Note:
1684: First tries to duplicate the rhs and solution vectors of the `KSP`, if they do not exist tries to get them from the matrix, if
1685: that does not exist tries to get them from the `DM` (if it is provided).
1687: .seealso: [](chapter_ksp), `MatCreateVecs()`, `VecDestroyVecs()`, `KSPSetWorkVecs()`
1688: @*/
1689: PetscErrorCode KSPCreateVecs(KSP ksp, PetscInt rightn, Vec **right, PetscInt leftn, Vec **left)
1690: {
1691: Vec vecr = NULL, vecl = NULL;
1692: PetscBool matset, pmatset, isshell, preferdm = PETSC_FALSE;
1693: Mat mat = NULL;
1695: PetscFunctionBegin;
1696: if (ksp->dm) {
1697: PetscCall(PetscObjectTypeCompare((PetscObject)ksp->dm, DMSHELL, &isshell));
1698: preferdm = isshell ? PETSC_FALSE : PETSC_TRUE;
1699: }
1700: if (rightn) {
1701: PetscCheck(right, PetscObjectComm((PetscObject)ksp), PETSC_ERR_ARG_INCOMP, "You asked for right vectors but did not pass a pointer to hold them");
1702: if (ksp->vec_sol) vecr = ksp->vec_sol;
1703: else {
1704: if (preferdm) {
1705: PetscCall(DMGetGlobalVector(ksp->dm, &vecr));
1706: } else if (ksp->pc) {
1707: PetscCall(PCGetOperatorsSet(ksp->pc, &matset, &pmatset));
1708: /* check for mat before pmat because for KSPLSQR pmat may be a different size than mat since pmat maybe mat'*mat */
1709: if (matset) {
1710: PetscCall(PCGetOperators(ksp->pc, &mat, NULL));
1711: PetscCall(MatCreateVecs(mat, &vecr, NULL));
1712: } else if (pmatset) {
1713: PetscCall(PCGetOperators(ksp->pc, NULL, &mat));
1714: PetscCall(MatCreateVecs(mat, &vecr, NULL));
1715: }
1716: }
1717: if (!vecr && ksp->dm) PetscCall(DMGetGlobalVector(ksp->dm, &vecr));
1718: PetscCheck(vecr, PetscObjectComm((PetscObject)ksp), PETSC_ERR_ARG_WRONGSTATE, "You requested a vector from a KSP that cannot provide one");
1719: }
1720: PetscCall(VecDuplicateVecs(vecr, rightn, right));
1721: if (!ksp->vec_sol) {
1722: if (preferdm) {
1723: PetscCall(DMRestoreGlobalVector(ksp->dm, &vecr));
1724: } else if (mat) {
1725: PetscCall(VecDestroy(&vecr));
1726: } else if (ksp->dm) {
1727: PetscCall(DMRestoreGlobalVector(ksp->dm, &vecr));
1728: }
1729: }
1730: }
1731: if (leftn) {
1732: PetscCheck(left, PetscObjectComm((PetscObject)ksp), PETSC_ERR_ARG_INCOMP, "You asked for left vectors but did not pass a pointer to hold them");
1733: if (ksp->vec_rhs) vecl = ksp->vec_rhs;
1734: else {
1735: if (preferdm) {
1736: PetscCall(DMGetGlobalVector(ksp->dm, &vecl));
1737: } else if (ksp->pc) {
1738: PetscCall(PCGetOperatorsSet(ksp->pc, &matset, &pmatset));
1739: /* check for mat before pmat because for KSPLSQR pmat may be a different size than mat since pmat maybe mat'*mat */
1740: if (matset) {
1741: PetscCall(PCGetOperators(ksp->pc, &mat, NULL));
1742: PetscCall(MatCreateVecs(mat, NULL, &vecl));
1743: } else if (pmatset) {
1744: PetscCall(PCGetOperators(ksp->pc, NULL, &mat));
1745: PetscCall(MatCreateVecs(mat, NULL, &vecl));
1746: }
1747: }
1748: if (!vecl && ksp->dm) PetscCall(DMGetGlobalVector(ksp->dm, &vecl));
1749: PetscCheck(vecl, PetscObjectComm((PetscObject)ksp), PETSC_ERR_ARG_WRONGSTATE, "You requested a vector from a KSP that cannot provide one");
1750: }
1751: PetscCall(VecDuplicateVecs(vecl, leftn, left));
1752: if (!ksp->vec_rhs) {
1753: if (preferdm) {
1754: PetscCall(DMRestoreGlobalVector(ksp->dm, &vecl));
1755: } else if (mat) {
1756: PetscCall(VecDestroy(&vecl));
1757: } else if (ksp->dm) {
1758: PetscCall(DMRestoreGlobalVector(ksp->dm, &vecl));
1759: }
1760: }
1761: }
1762: PetscFunctionReturn(PETSC_SUCCESS);
1763: }
1765: /*@C
1766: KSPSetWorkVecs - Sets a number of work vectors into a `KSP` object
1768: Collective
1770: Input Parameters:
1771: + ksp - iterative context
1772: - nw - number of work vectors to allocate
1774: Level: developer
1776: Developers Note:
1777: This is PETSC_EXTERN because it may be used by user written plugin `KSPType` implementations
1779: .seealso: [](chapter_ksp), `KSP`, `KSPCreateVecs()`
1780: @*/
1781: PetscErrorCode KSPSetWorkVecs(KSP ksp, PetscInt nw)
1782: {
1783: PetscFunctionBegin;
1784: PetscCall(VecDestroyVecs(ksp->nwork, &ksp->work));
1785: ksp->nwork = nw;
1786: PetscCall(KSPCreateVecs(ksp, nw, &ksp->work, 0, NULL));
1787: PetscFunctionReturn(PETSC_SUCCESS);
1788: }
1790: /*
1791: KSPDestroyDefault - Destroys a iterative context variable for methods with no separate context. Preferred calling sequence `KSPDestroy()`.
1793: Input Parameter:
1794: . ksp - the iterative context
1796: Developers Note:
1797: This is PETSC_EXTERN because it may be used by user written plugin `KSPType` implementations
1799: */
1800: PetscErrorCode KSPDestroyDefault(KSP ksp)
1801: {
1802: PetscFunctionBegin;
1804: PetscCall(PetscFree(ksp->data));
1805: PetscFunctionReturn(PETSC_SUCCESS);
1806: }
1808: /*@
1809: KSPGetConvergedReason - Gets the reason the `KSP` iteration was stopped.
1811: Not Collective
1813: Input Parameter:
1814: . ksp - the `KSP` context
1816: Output Parameter:
1817: . reason - negative value indicates diverged, positive value converged, see `KSPConvergedReason` for the possible values
1819: Options Database Key:
1820: . -ksp_converged_reason - prints the reason to standard out
1822: Level: intermediate
1824: Notes:
1825: If this routine is called before or doing the `KSPSolve()` the value of `KSP_CONVERGED_ITERATING` is returned
1827: .seealso: [](chapter_ksp), `KSPConvergedReason`, `KSP`, `KSPSetConvergenceTest()`, `KSPConvergedDefault()`, `KSPSetTolerances()`, `KSPConvergedReason`,
1828: `KSPConvergedReasonView()`
1829: @*/
1830: PetscErrorCode KSPGetConvergedReason(KSP ksp, KSPConvergedReason *reason)
1831: {
1832: PetscFunctionBegin;
1835: *reason = ksp->reason;
1836: PetscFunctionReturn(PETSC_SUCCESS);
1837: }
1839: /*@C
1840: KSPGetConvergedReasonString - Return a human readable string for a `KSPConvergedReason`
1842: Not Collective
1844: Input Parameter:
1845: . ksp - the `KSP` context
1847: Output Parameter:
1848: . strreason - a human readable string that describes ksp converged reason
1850: Level: beginner
1852: .seealso: [](chapter_ksp), `KSP`, `KSPGetConvergedReason()`
1853: @*/
1854: PetscErrorCode KSPGetConvergedReasonString(KSP ksp, const char **strreason)
1855: {
1856: PetscFunctionBegin;
1859: *strreason = KSPConvergedReasons[ksp->reason];
1860: PetscFunctionReturn(PETSC_SUCCESS);
1861: }
1863: #include <petsc/private/dmimpl.h>
1864: /*@
1865: KSPSetDM - Sets the `DM` that may be used by some preconditioners
1867: Logically Collective
1869: Input Parameters:
1870: + ksp - the `KSP`
1871: - dm - the `DM`, cannot be `NULL` to remove a previously set `DM`
1873: Level: intermediate
1875: Notes:
1876: If this is used then the `KSP` will attempt to use the `DM` to create the matrix and use the routine set with
1877: `DMKSPSetComputeOperators()`. Use `KSPSetDMActive`(ksp,`PETSC_FALSE`) to instead use the matrix you've provided with
1878: `KSPSetOperators()`.
1880: A `DM` can only be used for solving one problem at a time because information about the problem is stored on the `DM`,
1881: even when not using interfaces like `DMKSPSetComputeOperators()`. Use `DMClone()` to get a distinct `DM` when solving
1882: different problems using the same function space.
1884: .seealso: [](chapter_ksp), `KSP`, `DM`, `KSPGetDM()`, `KSPSetDMActive()`, `KSPSetComputeOperators()`, `KSPSetComputeRHS()`, `KSPSetComputeInitialGuess()`, `DMKSPSetComputeOperators()`, `DMKSPSetComputeRHS()`, `DMKSPSetComputeInitialGuess()`
1885: @*/
1886: PetscErrorCode KSPSetDM(KSP ksp, DM dm)
1887: {
1888: PC pc;
1890: PetscFunctionBegin;
1893: PetscCall(PetscObjectReference((PetscObject)dm));
1894: if (ksp->dm) { /* Move the DMSNES context over to the new DM unless the new DM already has one */
1895: if (ksp->dm->dmksp && !dm->dmksp) {
1896: DMKSP kdm;
1897: PetscCall(DMCopyDMKSP(ksp->dm, dm));
1898: PetscCall(DMGetDMKSP(ksp->dm, &kdm));
1899: if (kdm->originaldm == ksp->dm) kdm->originaldm = dm; /* Grant write privileges to the replacement DM */
1900: }
1901: PetscCall(DMDestroy(&ksp->dm));
1902: }
1903: ksp->dm = dm;
1904: ksp->dmAuto = PETSC_FALSE;
1905: PetscCall(KSPGetPC(ksp, &pc));
1906: PetscCall(PCSetDM(pc, dm));
1907: ksp->dmActive = PETSC_TRUE;
1908: PetscFunctionReturn(PETSC_SUCCESS);
1909: }
1911: /*@
1912: KSPSetDMActive - Indicates the `DM` should be used to generate the linear system matrix and right hand side vector
1914: Logically Collective
1916: Input Parameters:
1917: + ksp - the `KSP`
1918: - flg - use the `DM`
1920: Level: intermediate
1922: Note:
1923: By default `KSPSetDM()` sets the `DM` as active, call `KSPSetDMActive`(ksp,`PETSC_FALSE`); after `KSPSetDM`(ksp,dm) to not have the `KSP` object use the `DM` to generate the matrices.
1925: .seealso: [](chapter_ksp), `KSP`, `DM`, `KSPGetDM()`, `KSPSetDM()`, `SNESSetDM()`, `KSPSetComputeOperators()`, `KSPSetComputeRHS()`, `KSPSetComputeInitialGuess()`
1926: @*/
1927: PetscErrorCode KSPSetDMActive(KSP ksp, PetscBool flg)
1928: {
1929: PetscFunctionBegin;
1932: ksp->dmActive = flg;
1933: PetscFunctionReturn(PETSC_SUCCESS);
1934: }
1936: /*@
1937: KSPGetDM - Gets the `DM` that may be used by some preconditioners
1939: Not Collective
1941: Input Parameter:
1942: . ksp - the `KSP`
1944: Output Parameter:
1945: . dm - the `DM`
1947: Level: intermediate
1949: .seealso: [](chapter_ksp), `KSP`, `DM`, `KSPSetDM()`, `KSPSetDMActive()`
1950: @*/
1951: PetscErrorCode KSPGetDM(KSP ksp, DM *dm)
1952: {
1953: PetscFunctionBegin;
1955: if (!ksp->dm) {
1956: PetscCall(DMShellCreate(PetscObjectComm((PetscObject)ksp), &ksp->dm));
1957: ksp->dmAuto = PETSC_TRUE;
1958: }
1959: *dm = ksp->dm;
1960: PetscFunctionReturn(PETSC_SUCCESS);
1961: }
1963: /*@
1964: KSPSetApplicationContext - Sets the optional user-defined context for the linear solver.
1966: Logically Collective
1968: Input Parameters:
1969: + ksp - the `KSP` context
1970: - usrP - optional user context
1972: Level: intermediate
1974: Notes:
1975: The user context is a way for users to attach any information to the `KSP` that they may need later when interacting with the `KSP`
1977: Use `KSPGetApplicationContext()` to get access to the context at a later time.
1979: Fortran Note:
1980: To use this from Fortran you must write a Fortran interface definition for this
1981: function that tells Fortran the Fortran derived data type that you are passing in as the ctx argument.
1983: .seealso: [](chapter_ksp), `KSP`, `KSPGetApplicationContext()`
1984: @*/
1985: PetscErrorCode KSPSetApplicationContext(KSP ksp, void *usrP)
1986: {
1987: PC pc;
1989: PetscFunctionBegin;
1991: ksp->user = usrP;
1992: PetscCall(KSPGetPC(ksp, &pc));
1993: PetscCall(PCSetApplicationContext(pc, usrP));
1994: PetscFunctionReturn(PETSC_SUCCESS);
1995: }
1997: /*@
1998: KSPGetApplicationContext - Gets the user-defined context for the linear solver set with `KSPSetApplicationContext()`
2000: Not Collective
2002: Input Parameter:
2003: . ksp - `KSP` context
2005: Output Parameter:
2006: . usrP - user context
2008: Level: intermediate
2010: Fortran Notes:
2011: To use this from Fortran you must write a Fortran interface definition for this
2012: function that tells Fortran the Fortran derived data type that you are passing in as the ctx argument.
2014: .seealso: [](chapter_ksp), `KSP`, `KSPSetApplicationContext()`
2015: @*/
2016: PetscErrorCode KSPGetApplicationContext(KSP ksp, void *usrP)
2017: {
2018: PetscFunctionBegin;
2020: *(void **)usrP = ksp->user;
2021: PetscFunctionReturn(PETSC_SUCCESS);
2022: }
2024: #include <petsc/private/pcimpl.h>
2026: /*@
2027: KSPCheckSolve - Checks if the `PCSetUp()` or `KSPSolve()` failed and set the error flag for the outer `PC`. A `KSP_DIVERGED_ITS` is
2028: not considered a failure in this context
2030: Collective
2032: Input Parameters:
2033: + ksp - the linear solver `KSP` context.
2034: . pc - the preconditioner context
2035: - vec - a vector that will be initialized with Inf to indicate lack of convergence
2037: Level: developer
2039: Note:
2040: This is called within `KSPSolve()` and `PCApply()` to check if an error has been detected on any particular MPI ranks. By initializing the vector
2041: with Inf the next call to `KSPCheckNorm()` or `KSPCheckDot()` will provide the same information to all the MPI ranks that an error occurred on
2042: at least one of the ranks.
2044: This may be called by a subset of the processes in the `PC`.
2046: Developer Note:
2047: This is used to manage returning with appropriate information from preconditioners whose inner `KSP` solvers have failed in some way
2049: .seealso: [](chapter_ksp), `KSP`, `KSPCreate()`, `KSPSetType()`, `KSP`, `KSPCheckNorm()`, `KSPCheckDot()`
2050: @*/
2051: PetscErrorCode KSPCheckSolve(KSP ksp, PC pc, Vec vec)
2052: {
2053: PCFailedReason pcreason;
2054: PC subpc;
2056: PetscFunctionBegin;
2057: PetscCall(KSPGetPC(ksp, &subpc));
2058: PetscCall(PCGetFailedReason(subpc, &pcreason));
2059: if (pcreason || (ksp->reason < 0 && ksp->reason != KSP_DIVERGED_ITS)) {
2060: PetscCheck(!pc->erroriffailure, PETSC_COMM_SELF, PETSC_ERR_NOT_CONVERGED, "Detected not converged in KSP inner solve: KSP reason %s PC reason %s", KSPConvergedReasons[ksp->reason], PCFailedReasons[pcreason]);
2061: PetscCall(PetscInfo(ksp, "Detected not converged in KSP inner solve: KSP reason %s PC reason %s\n", KSPConvergedReasons[ksp->reason], PCFailedReasons[pcreason]));
2062: pc->failedreason = PC_SUBPC_ERROR;
2063: if (vec) PetscCall(VecSetInf(vec));
2064: }
2065: PetscFunctionReturn(PETSC_SUCCESS);
2066: }