Actual source code: snes.c
petsc-3.14.2 2020-12-03
1: #include <petsc/private/snesimpl.h>
2: #include <petscdmshell.h>
3: #include <petscdraw.h>
4: #include <petscds.h>
5: #include <petscdmadaptor.h>
6: #include <petscconvest.h>
8: PetscBool SNESRegisterAllCalled = PETSC_FALSE;
9: PetscFunctionList SNESList = NULL;
11: /* Logging support */
12: PetscClassId SNES_CLASSID, DMSNES_CLASSID;
13: PetscLogEvent SNES_Solve, SNES_Setup, SNES_FunctionEval, SNES_JacobianEval, SNES_NGSEval, SNES_NGSFuncEval, SNES_NPCSolve, SNES_ObjectiveEval;
15: /*@
16: SNESSetErrorIfNotConverged - Causes SNESSolve() to generate an error if the solver has not converged.
18: Logically Collective on SNES
20: Input Parameters:
21: + snes - iterative context obtained from SNESCreate()
22: - flg - PETSC_TRUE indicates you want the error generated
24: Options database keys:
25: . -snes_error_if_not_converged : this takes an optional truth value (0/1/no/yes/true/false)
27: Level: intermediate
29: Notes:
30: Normally PETSc continues if a linear solver fails to converge, you can call SNESGetConvergedReason() after a SNESSolve()
31: to determine if it has converged.
33: .seealso: SNESGetErrorIfNotConverged(), KSPGetErrorIfNotConverged(), KSPSetErrorIFNotConverged()
34: @*/
35: PetscErrorCode SNESSetErrorIfNotConverged(SNES snes,PetscBool flg)
36: {
40: snes->errorifnotconverged = flg;
41: return(0);
42: }
44: /*@
45: SNESGetErrorIfNotConverged - Will SNESSolve() generate an error if the solver does not converge?
47: Not Collective
49: Input Parameter:
50: . snes - iterative context obtained from SNESCreate()
52: Output Parameter:
53: . flag - PETSC_TRUE if it will generate an error, else PETSC_FALSE
55: Level: intermediate
57: .seealso: SNESSetErrorIfNotConverged(), KSPGetErrorIfNotConverged(), KSPSetErrorIFNotConverged()
58: @*/
59: PetscErrorCode SNESGetErrorIfNotConverged(SNES snes,PetscBool *flag)
60: {
64: *flag = snes->errorifnotconverged;
65: return(0);
66: }
68: /*@
69: SNESSetAlwaysComputesFinalResidual - does the SNES always compute the residual at the final solution?
71: Logically Collective on SNES
73: Input Parameters:
74: + snes - the shell SNES
75: - flg - is the residual computed?
77: Level: advanced
79: .seealso: SNESGetAlwaysComputesFinalResidual()
80: @*/
81: PetscErrorCode SNESSetAlwaysComputesFinalResidual(SNES snes, PetscBool flg)
82: {
85: snes->alwayscomputesfinalresidual = flg;
86: return(0);
87: }
89: /*@
90: SNESGetAlwaysComputesFinalResidual - does the SNES always compute the residual at the final solution?
92: Logically Collective on SNES
94: Input Parameter:
95: . snes - the shell SNES
97: Output Parameter:
98: . flg - is the residual computed?
100: Level: advanced
102: .seealso: SNESSetAlwaysComputesFinalResidual()
103: @*/
104: PetscErrorCode SNESGetAlwaysComputesFinalResidual(SNES snes, PetscBool *flg)
105: {
108: *flg = snes->alwayscomputesfinalresidual;
109: return(0);
110: }
112: /*@
113: SNESSetFunctionDomainError - tells SNES that the input vector to your SNESFunction is not
114: in the functions domain. For example, negative pressure.
116: Logically Collective on SNES
118: Input Parameters:
119: . snes - the SNES context
121: Level: advanced
123: .seealso: SNESCreate(), SNESSetFunction(), SNESFunction
124: @*/
125: PetscErrorCode SNESSetFunctionDomainError(SNES snes)
126: {
129: if (snes->errorifnotconverged) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"User code indicates input vector is not in the function domain");
130: snes->domainerror = PETSC_TRUE;
131: return(0);
132: }
134: /*@
135: SNESSetJacobianDomainError - tells SNES that computeJacobian does not make sense any more. For example there is a negative element transformation.
137: Logically Collective on SNES
139: Input Parameters:
140: . snes - the SNES context
142: Level: advanced
144: .seealso: SNESCreate(), SNESSetFunction(), SNESFunction(), SNESSetFunctionDomainError()
145: @*/
146: PetscErrorCode SNESSetJacobianDomainError(SNES snes)
147: {
150: if (snes->errorifnotconverged) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"User code indicates computeJacobian does not make sense");
151: snes->jacobiandomainerror = PETSC_TRUE;
152: return(0);
153: }
155: /*@
156: SNESSetCheckJacobianDomainError - if or not to check jacobian domain error after each Jacobian evaluation. By default, we check Jacobian domain error
157: in the debug mode, and do not check it in the optimized mode.
159: Logically Collective on SNES
161: Input Parameters:
162: + snes - the SNES context
163: - flg - indicates if or not to check jacobian domain error after each Jacobian evaluation
165: Level: advanced
167: .seealso: SNESCreate(), SNESSetFunction(), SNESFunction(), SNESSetFunctionDomainError(), SNESGetCheckJacobianDomainError()
168: @*/
169: PetscErrorCode SNESSetCheckJacobianDomainError(SNES snes, PetscBool flg)
170: {
173: snes->checkjacdomainerror = flg;
174: return(0);
175: }
177: /*@
178: SNESGetCheckJacobianDomainError - Get an indicator whether or not we are checking Jacobian domain errors after each Jacobian evaluation.
180: Logically Collective on SNES
182: Input Parameters:
183: . snes - the SNES context
185: Output Parameters:
186: . flg - PETSC_FALSE indicates that we don't check jacobian domain errors after each Jacobian evaluation
188: Level: advanced
190: .seealso: SNESCreate(), SNESSetFunction(), SNESFunction(), SNESSetFunctionDomainError(), SNESSetCheckJacobianDomainError()
191: @*/
192: PetscErrorCode SNESGetCheckJacobianDomainError(SNES snes, PetscBool *flg)
193: {
197: *flg = snes->checkjacdomainerror;
198: return(0);
199: }
201: /*@
202: SNESGetFunctionDomainError - Gets the status of the domain error after a call to SNESComputeFunction;
204: Logically Collective on SNES
206: Input Parameters:
207: . snes - the SNES context
209: Output Parameters:
210: . domainerror - Set to PETSC_TRUE if there's a domain error; PETSC_FALSE otherwise.
212: Level: advanced
214: .seealso: SNESSetFunctionDomainError(), SNESComputeFunction()
215: @*/
216: PetscErrorCode SNESGetFunctionDomainError(SNES snes, PetscBool *domainerror)
217: {
221: *domainerror = snes->domainerror;
222: return(0);
223: }
225: /*@
226: SNESGetJacobianDomainError - Gets the status of the Jacobian domain error after a call to SNESComputeJacobian;
228: Logically Collective on SNES
230: Input Parameters:
231: . snes - the SNES context
233: Output Parameters:
234: . domainerror - Set to PETSC_TRUE if there's a jacobian domain error; PETSC_FALSE otherwise.
236: Level: advanced
238: .seealso: SNESSetFunctionDomainError(), SNESComputeFunction(),SNESGetFunctionDomainError()
239: @*/
240: PetscErrorCode SNESGetJacobianDomainError(SNES snes, PetscBool *domainerror)
241: {
245: *domainerror = snes->jacobiandomainerror;
246: return(0);
247: }
249: /*@C
250: SNESLoad - Loads a SNES that has been stored in binary with SNESView().
252: Collective on PetscViewer
254: Input Parameters:
255: + newdm - the newly loaded SNES, this needs to have been created with SNESCreate() or
256: some related function before a call to SNESLoad().
257: - viewer - binary file viewer, obtained from PetscViewerBinaryOpen()
259: Level: intermediate
261: Notes:
262: The type is determined by the data in the file, any type set into the SNES before this call is ignored.
264: Notes for advanced users:
265: Most users should not need to know the details of the binary storage
266: format, since SNESLoad() and TSView() completely hide these details.
267: But for anyone who's interested, the standard binary matrix storage
268: format is
269: .vb
270: has not yet been determined
271: .ve
273: .seealso: PetscViewerBinaryOpen(), SNESView(), MatLoad(), VecLoad()
274: @*/
275: PetscErrorCode SNESLoad(SNES snes, PetscViewer viewer)
276: {
278: PetscBool isbinary;
279: PetscInt classid;
280: char type[256];
281: KSP ksp;
282: DM dm;
283: DMSNES dmsnes;
288: PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);
289: if (!isbinary) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Invalid viewer; open viewer with PetscViewerBinaryOpen()");
291: PetscViewerBinaryRead(viewer,&classid,1,NULL,PETSC_INT);
292: if (classid != SNES_FILE_CLASSID) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_WRONG,"Not SNES next in file");
293: PetscViewerBinaryRead(viewer,type,256,NULL,PETSC_CHAR);
294: SNESSetType(snes, type);
295: if (snes->ops->load) {
296: (*snes->ops->load)(snes,viewer);
297: }
298: SNESGetDM(snes,&dm);
299: DMGetDMSNES(dm,&dmsnes);
300: DMSNESLoad(dmsnes,viewer);
301: SNESGetKSP(snes,&ksp);
302: KSPLoad(ksp,viewer);
303: return(0);
304: }
306: #include <petscdraw.h>
307: #if defined(PETSC_HAVE_SAWS)
308: #include <petscviewersaws.h>
309: #endif
311: /*@C
312: SNESViewFromOptions - View from Options
314: Collective on SNES
316: Input Parameters:
317: + A - the application ordering context
318: . obj - Optional object
319: - name - command line option
321: Level: intermediate
322: .seealso: SNES, SNESView, PetscObjectViewFromOptions(), SNESCreate()
323: @*/
324: PetscErrorCode SNESViewFromOptions(SNES A,PetscObject obj,const char name[])
325: {
330: PetscObjectViewFromOptions((PetscObject)A,obj,name);
331: return(0);
332: }
334: PETSC_EXTERN PetscErrorCode SNESComputeJacobian_DMDA(SNES,Vec,Mat,Mat,void*);
336: /*@C
337: SNESView - Prints the SNES data structure.
339: Collective on SNES
341: Input Parameters:
342: + SNES - the SNES context
343: - viewer - visualization context
345: Options Database Key:
346: . -snes_view - Calls SNESView() at end of SNESSolve()
348: Notes:
349: The available visualization contexts include
350: + PETSC_VIEWER_STDOUT_SELF - standard output (default)
351: - PETSC_VIEWER_STDOUT_WORLD - synchronized standard
352: output where only the first processor opens
353: the file. All other processors send their
354: data to the first processor to print.
356: The user can open an alternative visualization context with
357: PetscViewerASCIIOpen() - output to a specified file.
359: Level: beginner
361: .seealso: PetscViewerASCIIOpen()
362: @*/
363: PetscErrorCode SNESView(SNES snes,PetscViewer viewer)
364: {
365: SNESKSPEW *kctx;
367: KSP ksp;
368: SNESLineSearch linesearch;
369: PetscBool iascii,isstring,isbinary,isdraw;
370: DMSNES dmsnes;
371: #if defined(PETSC_HAVE_SAWS)
372: PetscBool issaws;
373: #endif
377: if (!viewer) {
378: PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes),&viewer);
379: }
383: PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
384: PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSTRING,&isstring);
385: PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);
386: PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERDRAW,&isdraw);
387: #if defined(PETSC_HAVE_SAWS)
388: PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSAWS,&issaws);
389: #endif
390: if (iascii) {
391: SNESNormSchedule normschedule;
392: DM dm;
393: PetscErrorCode (*cJ)(SNES,Vec,Mat,Mat,void*);
394: void *ctx;
395: const char *pre = "";
397: PetscObjectPrintClassNamePrefixType((PetscObject)snes,viewer);
398: if (!snes->setupcalled) {
399: PetscViewerASCIIPrintf(viewer," SNES has not been set up so information may be incomplete\n");
400: }
401: if (snes->ops->view) {
402: PetscViewerASCIIPushTab(viewer);
403: (*snes->ops->view)(snes,viewer);
404: PetscViewerASCIIPopTab(viewer);
405: }
406: PetscViewerASCIIPrintf(viewer," maximum iterations=%D, maximum function evaluations=%D\n",snes->max_its,snes->max_funcs);
407: PetscViewerASCIIPrintf(viewer," tolerances: relative=%g, absolute=%g, solution=%g\n",(double)snes->rtol,(double)snes->abstol,(double)snes->stol);
408: if (snes->usesksp) {
409: PetscViewerASCIIPrintf(viewer," total number of linear solver iterations=%D\n",snes->linear_its);
410: }
411: PetscViewerASCIIPrintf(viewer," total number of function evaluations=%D\n",snes->nfuncs);
412: SNESGetNormSchedule(snes, &normschedule);
413: if (normschedule > 0) {PetscViewerASCIIPrintf(viewer," norm schedule %s\n",SNESNormSchedules[normschedule]);}
414: if (snes->gridsequence) {
415: PetscViewerASCIIPrintf(viewer," total number of grid sequence refinements=%D\n",snes->gridsequence);
416: }
417: if (snes->ksp_ewconv) {
418: kctx = (SNESKSPEW*)snes->kspconvctx;
419: if (kctx) {
420: PetscViewerASCIIPrintf(viewer," Eisenstat-Walker computation of KSP relative tolerance (version %D)\n",kctx->version);
421: PetscViewerASCIIPrintf(viewer," rtol_0=%g, rtol_max=%g, threshold=%g\n",(double)kctx->rtol_0,(double)kctx->rtol_max,(double)kctx->threshold);
422: PetscViewerASCIIPrintf(viewer," gamma=%g, alpha=%g, alpha2=%g\n",(double)kctx->gamma,(double)kctx->alpha,(double)kctx->alpha2);
423: }
424: }
425: if (snes->lagpreconditioner == -1) {
426: PetscViewerASCIIPrintf(viewer," Preconditioned is never rebuilt\n");
427: } else if (snes->lagpreconditioner > 1) {
428: PetscViewerASCIIPrintf(viewer," Preconditioned is rebuilt every %D new Jacobians\n",snes->lagpreconditioner);
429: }
430: if (snes->lagjacobian == -1) {
431: PetscViewerASCIIPrintf(viewer," Jacobian is never rebuilt\n");
432: } else if (snes->lagjacobian > 1) {
433: PetscViewerASCIIPrintf(viewer," Jacobian is rebuilt every %D SNES iterations\n",snes->lagjacobian);
434: }
435: SNESGetDM(snes,&dm);
436: DMSNESGetJacobian(dm,&cJ,&ctx);
437: if (snes->mf_operator) {
438: PetscViewerASCIIPrintf(viewer," Jacobian is applied matrix-free with differencing\n");
439: pre = "Preconditioning ";
440: }
441: if (cJ == SNESComputeJacobianDefault) {
442: PetscViewerASCIIPrintf(viewer," %sJacobian is built using finite differences one column at a time\n",pre);
443: } else if (cJ == SNESComputeJacobianDefaultColor) {
444: PetscViewerASCIIPrintf(viewer," %sJacobian is built using finite differences with coloring\n",pre);
445: /* it slightly breaks data encapsulation for access the DMDA information directly */
446: } else if (cJ == SNESComputeJacobian_DMDA) {
447: MatFDColoring fdcoloring;
448: PetscObjectQuery((PetscObject)dm,"DMDASNES_FDCOLORING",(PetscObject*)&fdcoloring);
449: if (fdcoloring) {
450: PetscViewerASCIIPrintf(viewer," %sJacobian is built using colored finite differences on a DMDA\n",pre);
451: } else {
452: PetscViewerASCIIPrintf(viewer," %sJacobian is built using a DMDA local Jacobian\n",pre);
453: }
454: } else if (snes->mf) {
455: PetscViewerASCIIPrintf(viewer," Jacobian is applied matrix-free with differencing, no explict Jacobian\n");
456: }
457: } else if (isstring) {
458: const char *type;
459: SNESGetType(snes,&type);
460: PetscViewerStringSPrintf(viewer," SNESType: %-7.7s",type);
461: if (snes->ops->view) {(*snes->ops->view)(snes,viewer);}
462: } else if (isbinary) {
463: PetscInt classid = SNES_FILE_CLASSID;
464: MPI_Comm comm;
465: PetscMPIInt rank;
466: char type[256];
468: PetscObjectGetComm((PetscObject)snes,&comm);
469: MPI_Comm_rank(comm,&rank);
470: if (!rank) {
471: PetscViewerBinaryWrite(viewer,&classid,1,PETSC_INT);
472: PetscStrncpy(type,((PetscObject)snes)->type_name,sizeof(type));
473: PetscViewerBinaryWrite(viewer,type,sizeof(type),PETSC_CHAR);
474: }
475: if (snes->ops->view) {
476: (*snes->ops->view)(snes,viewer);
477: }
478: } else if (isdraw) {
479: PetscDraw draw;
480: char str[36];
481: PetscReal x,y,bottom,h;
483: PetscViewerDrawGetDraw(viewer,0,&draw);
484: PetscDrawGetCurrentPoint(draw,&x,&y);
485: PetscStrncpy(str,"SNES: ",sizeof(str));
486: PetscStrlcat(str,((PetscObject)snes)->type_name,sizeof(str));
487: PetscDrawStringBoxed(draw,x,y,PETSC_DRAW_BLUE,PETSC_DRAW_BLACK,str,NULL,&h);
488: bottom = y - h;
489: PetscDrawPushCurrentPoint(draw,x,bottom);
490: if (snes->ops->view) {
491: (*snes->ops->view)(snes,viewer);
492: }
493: #if defined(PETSC_HAVE_SAWS)
494: } else if (issaws) {
495: PetscMPIInt rank;
496: const char *name;
498: PetscObjectGetName((PetscObject)snes,&name);
499: MPI_Comm_rank(PETSC_COMM_WORLD,&rank);
500: if (!((PetscObject)snes)->amsmem && !rank) {
501: char dir[1024];
503: PetscObjectViewSAWs((PetscObject)snes,viewer);
504: PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/its",name);
505: PetscStackCallSAWs(SAWs_Register,(dir,&snes->iter,1,SAWs_READ,SAWs_INT));
506: if (!snes->conv_hist) {
507: SNESSetConvergenceHistory(snes,NULL,NULL,PETSC_DECIDE,PETSC_TRUE);
508: }
509: PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/conv_hist",name);
510: PetscStackCallSAWs(SAWs_Register,(dir,snes->conv_hist,10,SAWs_READ,SAWs_DOUBLE));
511: }
512: #endif
513: }
514: if (snes->linesearch) {
515: SNESGetLineSearch(snes, &linesearch);
516: PetscViewerASCIIPushTab(viewer);
517: SNESLineSearchView(linesearch, viewer);
518: PetscViewerASCIIPopTab(viewer);
519: }
520: if (snes->npc && snes->usesnpc) {
521: PetscViewerASCIIPushTab(viewer);
522: SNESView(snes->npc, viewer);
523: PetscViewerASCIIPopTab(viewer);
524: }
525: PetscViewerASCIIPushTab(viewer);
526: DMGetDMSNES(snes->dm,&dmsnes);
527: DMSNESView(dmsnes, viewer);
528: PetscViewerASCIIPopTab(viewer);
529: if (snes->usesksp) {
530: SNESGetKSP(snes,&ksp);
531: PetscViewerASCIIPushTab(viewer);
532: KSPView(ksp,viewer);
533: PetscViewerASCIIPopTab(viewer);
534: }
535: if (isdraw) {
536: PetscDraw draw;
537: PetscViewerDrawGetDraw(viewer,0,&draw);
538: PetscDrawPopCurrentPoint(draw);
539: }
540: return(0);
541: }
543: /*
544: We retain a list of functions that also take SNES command
545: line options. These are called at the end SNESSetFromOptions()
546: */
547: #define MAXSETFROMOPTIONS 5
548: static PetscInt numberofsetfromoptions;
549: static PetscErrorCode (*othersetfromoptions[MAXSETFROMOPTIONS])(SNES);
551: /*@C
552: SNESAddOptionsChecker - Adds an additional function to check for SNES options.
554: Not Collective
556: Input Parameter:
557: . snescheck - function that checks for options
559: Level: developer
561: .seealso: SNESSetFromOptions()
562: @*/
563: PetscErrorCode SNESAddOptionsChecker(PetscErrorCode (*snescheck)(SNES))
564: {
566: if (numberofsetfromoptions >= MAXSETFROMOPTIONS) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE, "Too many options checkers, only %D allowed", MAXSETFROMOPTIONS);
567: othersetfromoptions[numberofsetfromoptions++] = snescheck;
568: return(0);
569: }
571: PETSC_INTERN PetscErrorCode SNESDefaultMatrixFreeCreate2(SNES,Vec,Mat*);
573: static PetscErrorCode SNESSetUpMatrixFree_Private(SNES snes, PetscBool hasOperator, PetscInt version)
574: {
575: Mat J;
577: MatNullSpace nullsp;
582: if (!snes->vec_func && (snes->jacobian || snes->jacobian_pre)) {
583: Mat A = snes->jacobian, B = snes->jacobian_pre;
584: MatCreateVecs(A ? A : B, NULL,&snes->vec_func);
585: }
587: if (version == 1) {
588: MatCreateSNESMF(snes,&J);
589: MatMFFDSetOptionsPrefix(J,((PetscObject)snes)->prefix);
590: MatSetFromOptions(J);
591: } else if (version == 2) {
592: if (!snes->vec_func) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"SNESSetFunction() must be called first");
593: #if !defined(PETSC_USE_COMPLEX) && !defined(PETSC_USE_REAL_SINGLE) && !defined(PETSC_USE_REAL___FLOAT128) && !defined(PETSC_USE_REAL___FP16)
594: SNESDefaultMatrixFreeCreate2(snes,snes->vec_func,&J);
595: #else
596: SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP, "matrix-free operator routines (version 2)");
597: #endif
598: } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE, "matrix-free operator routines, only version 1 and 2");
600: /* attach any user provided null space that was on Amat to the newly created matrix free matrix */
601: if (snes->jacobian) {
602: MatGetNullSpace(snes->jacobian,&nullsp);
603: if (nullsp) {
604: MatSetNullSpace(J,nullsp);
605: }
606: }
608: PetscInfo1(snes,"Setting default matrix-free operator routines (version %D)\n", version);
609: if (hasOperator) {
611: /* This version replaces the user provided Jacobian matrix with a
612: matrix-free version but still employs the user-provided preconditioner matrix. */
613: SNESSetJacobian(snes,J,NULL,NULL,NULL);
614: } else {
615: /* This version replaces both the user-provided Jacobian and the user-
616: provided preconditioner Jacobian with the default matrix free version. */
617: if ((snes->npcside== PC_LEFT) && snes->npc) {
618: if (!snes->jacobian){SNESSetJacobian(snes,J,NULL,NULL,NULL);}
619: } else {
620: KSP ksp;
621: PC pc;
622: PetscBool match;
624: SNESSetJacobian(snes,J,J,MatMFFDComputeJacobian,NULL);
625: /* Force no preconditioner */
626: SNESGetKSP(snes,&ksp);
627: KSPGetPC(ksp,&pc);
628: PetscObjectTypeCompare((PetscObject)pc,PCSHELL,&match);
629: if (!match) {
630: PetscInfo(snes,"Setting default matrix-free preconditioner routines\nThat is no preconditioner is being used\n");
631: PCSetType(pc,PCNONE);
632: }
633: }
634: }
635: MatDestroy(&J);
636: return(0);
637: }
639: static PetscErrorCode DMRestrictHook_SNESVecSol(DM dmfine,Mat Restrict,Vec Rscale,Mat Inject,DM dmcoarse,void *ctx)
640: {
641: SNES snes = (SNES)ctx;
643: Vec Xfine,Xfine_named = NULL,Xcoarse;
646: if (PetscLogPrintInfo) {
647: PetscInt finelevel,coarselevel,fineclevel,coarseclevel;
648: DMGetRefineLevel(dmfine,&finelevel);
649: DMGetCoarsenLevel(dmfine,&fineclevel);
650: DMGetRefineLevel(dmcoarse,&coarselevel);
651: DMGetCoarsenLevel(dmcoarse,&coarseclevel);
652: PetscInfo4(dmfine,"Restricting SNES solution vector from level %D-%D to level %D-%D\n",finelevel,fineclevel,coarselevel,coarseclevel);
653: }
654: if (dmfine == snes->dm) Xfine = snes->vec_sol;
655: else {
656: DMGetNamedGlobalVector(dmfine,"SNESVecSol",&Xfine_named);
657: Xfine = Xfine_named;
658: }
659: DMGetNamedGlobalVector(dmcoarse,"SNESVecSol",&Xcoarse);
660: if (Inject) {
661: MatRestrict(Inject,Xfine,Xcoarse);
662: } else {
663: MatRestrict(Restrict,Xfine,Xcoarse);
664: VecPointwiseMult(Xcoarse,Xcoarse,Rscale);
665: }
666: DMRestoreNamedGlobalVector(dmcoarse,"SNESVecSol",&Xcoarse);
667: if (Xfine_named) {DMRestoreNamedGlobalVector(dmfine,"SNESVecSol",&Xfine_named);}
668: return(0);
669: }
671: static PetscErrorCode DMCoarsenHook_SNESVecSol(DM dm,DM dmc,void *ctx)
672: {
676: DMCoarsenHookAdd(dmc,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,ctx);
677: return(0);
678: }
680: /* This may be called to rediscretize the operator on levels of linear multigrid. The DM shuffle is so the user can
681: * safely call SNESGetDM() in their residual evaluation routine. */
682: static PetscErrorCode KSPComputeOperators_SNES(KSP ksp,Mat A,Mat B,void *ctx)
683: {
684: SNES snes = (SNES)ctx;
686: Vec X,Xnamed = NULL;
687: DM dmsave;
688: void *ctxsave;
689: PetscErrorCode (*jac)(SNES,Vec,Mat,Mat,void*) = NULL;
692: dmsave = snes->dm;
693: KSPGetDM(ksp,&snes->dm);
694: if (dmsave == snes->dm) X = snes->vec_sol; /* We are on the finest level */
695: else { /* We are on a coarser level, this vec was initialized using a DM restrict hook */
696: DMGetNamedGlobalVector(snes->dm,"SNESVecSol",&Xnamed);
697: X = Xnamed;
698: SNESGetJacobian(snes,NULL,NULL,&jac,&ctxsave);
699: /* If the DM's don't match up, the MatFDColoring context needed for the jacobian won't match up either -- fixit. */
700: if (jac == SNESComputeJacobianDefaultColor) {
701: SNESSetJacobian(snes,NULL,NULL,SNESComputeJacobianDefaultColor,NULL);
702: }
703: }
704: /* Make sure KSP DM has the Jacobian computation routine */
705: {
706: DMSNES sdm;
708: DMGetDMSNES(snes->dm, &sdm);
709: if (!sdm->ops->computejacobian) {
710: DMCopyDMSNES(dmsave, snes->dm);
711: }
712: }
713: /* Compute the operators */
714: SNESComputeJacobian(snes,X,A,B);
715: /* Put the previous context back */
716: if (snes->dm != dmsave && jac == SNESComputeJacobianDefaultColor) {
717: SNESSetJacobian(snes,NULL,NULL,jac,ctxsave);
718: }
720: if (Xnamed) {DMRestoreNamedGlobalVector(snes->dm,"SNESVecSol",&Xnamed);}
721: snes->dm = dmsave;
722: return(0);
723: }
725: /*@
726: SNESSetUpMatrices - ensures that matrices are available for SNES, to be called by SNESSetUp_XXX()
728: Collective
730: Input Arguments:
731: . snes - snes to configure
733: Level: developer
735: .seealso: SNESSetUp()
736: @*/
737: PetscErrorCode SNESSetUpMatrices(SNES snes)
738: {
740: DM dm;
741: DMSNES sdm;
744: SNESGetDM(snes,&dm);
745: DMGetDMSNES(dm,&sdm);
746: if (!snes->jacobian && snes->mf) {
747: Mat J;
748: void *functx;
749: MatCreateSNESMF(snes,&J);
750: MatMFFDSetOptionsPrefix(J,((PetscObject)snes)->prefix);
751: MatSetFromOptions(J);
752: SNESGetFunction(snes,NULL,NULL,&functx);
753: SNESSetJacobian(snes,J,J,NULL,NULL);
754: MatDestroy(&J);
755: } else if (snes->mf_operator && !snes->jacobian_pre && !snes->jacobian) {
756: Mat J,B;
757: MatCreateSNESMF(snes,&J);
758: MatMFFDSetOptionsPrefix(J,((PetscObject)snes)->prefix);
759: MatSetFromOptions(J);
760: DMCreateMatrix(snes->dm,&B);
761: /* sdm->computejacobian was already set to reach here */
762: SNESSetJacobian(snes,J,B,NULL,NULL);
763: MatDestroy(&J);
764: MatDestroy(&B);
765: } else if (!snes->jacobian_pre) {
766: PetscErrorCode (*nspconstr)(DM, PetscInt, PetscInt, MatNullSpace *);
767: PetscDS prob;
768: Mat J, B;
769: MatNullSpace nullspace = NULL;
770: PetscBool hasPrec = PETSC_FALSE;
771: PetscInt Nf;
773: J = snes->jacobian;
774: DMGetDS(dm, &prob);
775: if (prob) {PetscDSHasJacobianPreconditioner(prob, &hasPrec);}
776: if (J) {PetscObjectReference((PetscObject) J);}
777: else if (hasPrec) {DMCreateMatrix(snes->dm, &J);}
778: DMCreateMatrix(snes->dm, &B);
779: PetscDSGetNumFields(prob, &Nf);
780: DMGetNullSpaceConstructor(snes->dm, Nf, &nspconstr);
781: if (nspconstr) (*nspconstr)(snes->dm, Nf, Nf, &nullspace);
782: MatSetNullSpace(B, nullspace);
783: MatNullSpaceDestroy(&nullspace);
784: SNESSetJacobian(snes, J ? J : B, B, NULL, NULL);
785: MatDestroy(&J);
786: MatDestroy(&B);
787: }
788: {
789: KSP ksp;
790: SNESGetKSP(snes,&ksp);
791: KSPSetComputeOperators(ksp,KSPComputeOperators_SNES,snes);
792: DMCoarsenHookAdd(snes->dm,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,snes);
793: }
794: return(0);
795: }
797: /*@C
798: SNESMonitorSetFromOptions - Sets a monitor function and viewer appropriate for the type indicated by the user
800: Collective on SNES
802: Input Parameters:
803: + snes - SNES object you wish to monitor
804: . name - the monitor type one is seeking
805: . help - message indicating what monitoring is done
806: . manual - manual page for the monitor
807: . monitor - the monitor function
808: - monitorsetup - a function that is called once ONLY if the user selected this monitor that may set additional features of the SNES or PetscViewer objects
810: Level: developer
812: .seealso: PetscOptionsGetViewer(), PetscOptionsGetReal(), PetscOptionsHasName(), PetscOptionsGetString(),
813: PetscOptionsGetIntArray(), PetscOptionsGetRealArray(), PetscOptionsBool()
814: PetscOptionsInt(), PetscOptionsString(), PetscOptionsReal(), PetscOptionsBool(),
815: PetscOptionsName(), PetscOptionsBegin(), PetscOptionsEnd(), PetscOptionsHead(),
816: PetscOptionsStringArray(),PetscOptionsRealArray(), PetscOptionsScalar(),
817: PetscOptionsBoolGroupBegin(), PetscOptionsBoolGroup(), PetscOptionsBoolGroupEnd(),
818: PetscOptionsFList(), PetscOptionsEList()
819: @*/
820: PetscErrorCode SNESMonitorSetFromOptions(SNES snes,const char name[],const char help[], const char manual[],PetscErrorCode (*monitor)(SNES,PetscInt,PetscReal,PetscViewerAndFormat*),PetscErrorCode (*monitorsetup)(SNES,PetscViewerAndFormat*))
821: {
822: PetscErrorCode ierr;
823: PetscViewer viewer;
824: PetscViewerFormat format;
825: PetscBool flg;
828: PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject) snes)->options,((PetscObject)snes)->prefix,name,&viewer,&format,&flg);
829: if (flg) {
830: PetscViewerAndFormat *vf;
831: PetscViewerAndFormatCreate(viewer,format,&vf);
832: PetscObjectDereference((PetscObject)viewer);
833: if (monitorsetup) {
834: (*monitorsetup)(snes,vf);
835: }
836: SNESMonitorSet(snes,(PetscErrorCode (*)(SNES,PetscInt,PetscReal,void*))monitor,vf,(PetscErrorCode (*)(void**))PetscViewerAndFormatDestroy);
837: }
838: return(0);
839: }
841: /*@
842: SNESSetFromOptions - Sets various SNES and KSP parameters from user options.
844: Collective on SNES
846: Input Parameter:
847: . snes - the SNES context
849: Options Database Keys:
850: + -snes_type <type> - newtonls, newtontr, ngmres, ncg, nrichardson, qn, vi, fas, SNESType for complete list
851: . -snes_stol - convergence tolerance in terms of the norm
852: of the change in the solution between steps
853: . -snes_atol <abstol> - absolute tolerance of residual norm
854: . -snes_rtol <rtol> - relative decrease in tolerance norm from initial
855: . -snes_divergence_tolerance <divtol> - if the residual goes above divtol*rnorm0, exit with divergence
856: . -snes_force_iteration <force> - force SNESSolve() to take at least one iteration
857: . -snes_max_it <max_it> - maximum number of iterations
858: . -snes_max_funcs <max_funcs> - maximum number of function evaluations
859: . -snes_max_fail <max_fail> - maximum number of line search failures allowed before stopping, default is none
860: . -snes_max_linear_solve_fail - number of linear solver failures before SNESSolve() stops
861: . -snes_lag_preconditioner <lag> - how often preconditioner is rebuilt (use -1 to never rebuild)
862: . -snes_lag_preconditioner_persists <true,false> - retains the -snes_lag_preconditioner information across multiple SNESSolve()
863: . -snes_lag_jacobian <lag> - how often Jacobian is rebuilt (use -1 to never rebuild)
864: . -snes_lag_jacobian_persists <true,false> - retains the -snes_lag_jacobian information across multiple SNESSolve()
865: . -snes_trtol <trtol> - trust region tolerance
866: . -snes_no_convergence_test - skip convergence test in nonlinear
867: solver; hence iterations will continue until max_it
868: or some other criterion is reached. Saves expense
869: of convergence test
870: . -snes_monitor [ascii][:filename][:viewer format] - prints residual norm at each iteration. if no filename given prints to stdout
871: . -snes_monitor_solution [ascii binary draw][:filename][:viewer format] - plots solution at each iteration
872: . -snes_monitor_residual [ascii binary draw][:filename][:viewer format] - plots residual (not its norm) at each iteration
873: . -snes_monitor_solution_update [ascii binary draw][:filename][:viewer format] - plots update to solution at each iteration
874: . -snes_monitor_lg_residualnorm - plots residual norm at each iteration
875: . -snes_monitor_lg_range - plots residual norm at each iteration
876: . -snes_fd - use finite differences to compute Jacobian; very slow, only for testing
877: . -snes_fd_color - use finite differences with coloring to compute Jacobian
878: . -snes_mf_ksp_monitor - if using matrix-free multiply then print h at each KSP iteration
879: . -snes_converged_reason - print the reason for convergence/divergence after each solve
880: . -npc_snes_type <type> - the SNES type to use as a nonlinear preconditioner
881: . -snes_test_jacobian <optional threshold> - compare the user provided Jacobian with one computed via finite differences to check for errors. If a threshold is given, display only those entries whose difference is greater than the threshold.
882: - -snes_test_jacobian_view - display the user provided Jacobian, the finite difference Jacobian and the difference between them to help users detect the location of errors in the user provided Jacobian.
884: Options Database for Eisenstat-Walker method:
885: + -snes_ksp_ew - use Eisenstat-Walker method for determining linear system convergence
886: . -snes_ksp_ew_version ver - version of Eisenstat-Walker method
887: . -snes_ksp_ew_rtol0 <rtol0> - Sets rtol0
888: . -snes_ksp_ew_rtolmax <rtolmax> - Sets rtolmax
889: . -snes_ksp_ew_gamma <gamma> - Sets gamma
890: . -snes_ksp_ew_alpha <alpha> - Sets alpha
891: . -snes_ksp_ew_alpha2 <alpha2> - Sets alpha2
892: - -snes_ksp_ew_threshold <threshold> - Sets threshold
894: Notes:
895: To see all options, run your program with the -help option or consult the users manual
897: Notes:
898: SNES supports three approaches for computing (approximate) Jacobians: user provided via SNESSetJacobian(), matrix free, and computing explictly with
899: finite differences and coloring using MatFDColoring. It is also possible to use automatic differentiation and the MatFDColoring object.
901: Level: beginner
903: .seealso: SNESSetOptionsPrefix(), SNESResetFromOptions(), SNES, SNESCreate()
904: @*/
905: PetscErrorCode SNESSetFromOptions(SNES snes)
906: {
907: PetscBool flg,pcset,persist,set;
908: PetscInt i,indx,lag,grids;
909: const char *deft = SNESNEWTONLS;
910: const char *convtests[] = {"default","skip"};
911: SNESKSPEW *kctx = NULL;
912: char type[256], monfilename[PETSC_MAX_PATH_LEN];
914: PCSide pcside;
915: const char *optionsprefix;
919: SNESRegisterAll();
920: PetscObjectOptionsBegin((PetscObject)snes);
921: if (((PetscObject)snes)->type_name) deft = ((PetscObject)snes)->type_name;
922: PetscOptionsFList("-snes_type","Nonlinear solver method","SNESSetType",SNESList,deft,type,256,&flg);
923: if (flg) {
924: SNESSetType(snes,type);
925: } else if (!((PetscObject)snes)->type_name) {
926: SNESSetType(snes,deft);
927: }
928: PetscOptionsReal("-snes_stol","Stop if step length less than","SNESSetTolerances",snes->stol,&snes->stol,NULL);
929: PetscOptionsReal("-snes_atol","Stop if function norm less than","SNESSetTolerances",snes->abstol,&snes->abstol,NULL);
931: PetscOptionsReal("-snes_rtol","Stop if decrease in function norm less than","SNESSetTolerances",snes->rtol,&snes->rtol,NULL);
932: PetscOptionsReal("-snes_divergence_tolerance","Stop if residual norm increases by this factor","SNESSetDivergenceTolerance",snes->divtol,&snes->divtol,NULL);
933: PetscOptionsInt("-snes_max_it","Maximum iterations","SNESSetTolerances",snes->max_its,&snes->max_its,NULL);
934: PetscOptionsInt("-snes_max_funcs","Maximum function evaluations","SNESSetTolerances",snes->max_funcs,&snes->max_funcs,NULL);
935: PetscOptionsInt("-snes_max_fail","Maximum nonlinear step failures","SNESSetMaxNonlinearStepFailures",snes->maxFailures,&snes->maxFailures,NULL);
936: PetscOptionsInt("-snes_max_linear_solve_fail","Maximum failures in linear solves allowed","SNESSetMaxLinearSolveFailures",snes->maxLinearSolveFailures,&snes->maxLinearSolveFailures,NULL);
937: PetscOptionsBool("-snes_error_if_not_converged","Generate error if solver does not converge","SNESSetErrorIfNotConverged",snes->errorifnotconverged,&snes->errorifnotconverged,NULL);
938: PetscOptionsBool("-snes_force_iteration","Force SNESSolve() to take at least one iteration","SNESSetForceIteration",snes->forceiteration,&snes->forceiteration,NULL);
939: PetscOptionsBool("-snes_check_jacobian_domain_error","Check Jacobian domain error after Jacobian evaluation","SNESCheckJacobianDomainError",snes->checkjacdomainerror,&snes->checkjacdomainerror,NULL);
941: PetscOptionsInt("-snes_lag_preconditioner","How often to rebuild preconditioner","SNESSetLagPreconditioner",snes->lagpreconditioner,&lag,&flg);
942: if (flg) {
943: if (lag == -1) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_USER,"Cannot set the lag to -1 from the command line since the preconditioner must be built as least once, perhaps you mean -2");
944: SNESSetLagPreconditioner(snes,lag);
945: }
946: PetscOptionsBool("-snes_lag_preconditioner_persists","Preconditioner lagging through multiple SNES solves","SNESSetLagPreconditionerPersists",snes->lagjac_persist,&persist,&flg);
947: if (flg) {
948: SNESSetLagPreconditionerPersists(snes,persist);
949: }
950: PetscOptionsInt("-snes_lag_jacobian","How often to rebuild Jacobian","SNESSetLagJacobian",snes->lagjacobian,&lag,&flg);
951: if (flg) {
952: if (lag == -1) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_USER,"Cannot set the lag to -1 from the command line since the Jacobian must be built as least once, perhaps you mean -2");
953: SNESSetLagJacobian(snes,lag);
954: }
955: PetscOptionsBool("-snes_lag_jacobian_persists","Jacobian lagging through multiple SNES solves","SNESSetLagJacobianPersists",snes->lagjac_persist,&persist,&flg);
956: if (flg) {
957: SNESSetLagJacobianPersists(snes,persist);
958: }
960: PetscOptionsInt("-snes_grid_sequence","Use grid sequencing to generate initial guess","SNESSetGridSequence",snes->gridsequence,&grids,&flg);
961: if (flg) {
962: SNESSetGridSequence(snes,grids);
963: }
965: PetscOptionsEList("-snes_convergence_test","Convergence test","SNESSetConvergenceTest",convtests,2,"default",&indx,&flg);
966: if (flg) {
967: switch (indx) {
968: case 0: SNESSetConvergenceTest(snes,SNESConvergedDefault,NULL,NULL); break;
969: case 1: SNESSetConvergenceTest(snes,SNESConvergedSkip,NULL,NULL); break;
970: }
971: }
973: PetscOptionsEList("-snes_norm_schedule","SNES Norm schedule","SNESSetNormSchedule",SNESNormSchedules,5,"function",&indx,&flg);
974: if (flg) { SNESSetNormSchedule(snes,(SNESNormSchedule)indx); }
976: PetscOptionsEList("-snes_function_type","SNES Norm schedule","SNESSetFunctionType",SNESFunctionTypes,2,"unpreconditioned",&indx,&flg);
977: if (flg) { SNESSetFunctionType(snes,(SNESFunctionType)indx); }
979: kctx = (SNESKSPEW*)snes->kspconvctx;
981: PetscOptionsBool("-snes_ksp_ew","Use Eisentat-Walker linear system convergence test","SNESKSPSetUseEW",snes->ksp_ewconv,&snes->ksp_ewconv,NULL);
983: PetscOptionsInt("-snes_ksp_ew_version","Version 1, 2 or 3","SNESKSPSetParametersEW",kctx->version,&kctx->version,NULL);
984: PetscOptionsReal("-snes_ksp_ew_rtol0","0 <= rtol0 < 1","SNESKSPSetParametersEW",kctx->rtol_0,&kctx->rtol_0,NULL);
985: PetscOptionsReal("-snes_ksp_ew_rtolmax","0 <= rtolmax < 1","SNESKSPSetParametersEW",kctx->rtol_max,&kctx->rtol_max,NULL);
986: PetscOptionsReal("-snes_ksp_ew_gamma","0 <= gamma <= 1","SNESKSPSetParametersEW",kctx->gamma,&kctx->gamma,NULL);
987: PetscOptionsReal("-snes_ksp_ew_alpha","1 < alpha <= 2","SNESKSPSetParametersEW",kctx->alpha,&kctx->alpha,NULL);
988: PetscOptionsReal("-snes_ksp_ew_alpha2","alpha2","SNESKSPSetParametersEW",kctx->alpha2,&kctx->alpha2,NULL);
989: PetscOptionsReal("-snes_ksp_ew_threshold","0 < threshold < 1","SNESKSPSetParametersEW",kctx->threshold,&kctx->threshold,NULL);
991: flg = PETSC_FALSE;
992: PetscOptionsBool("-snes_monitor_cancel","Remove all monitors","SNESMonitorCancel",flg,&flg,&set);
993: if (set && flg) {SNESMonitorCancel(snes);}
995: SNESMonitorSetFromOptions(snes,"-snes_monitor","Monitor norm of function","SNESMonitorDefault",SNESMonitorDefault,NULL);
996: SNESMonitorSetFromOptions(snes,"-snes_monitor_short","Monitor norm of function with fewer digits","SNESMonitorDefaultShort",SNESMonitorDefaultShort,NULL);
997: SNESMonitorSetFromOptions(snes,"-snes_monitor_range","Monitor range of elements of function","SNESMonitorRange",SNESMonitorRange,NULL);
999: SNESMonitorSetFromOptions(snes,"-snes_monitor_ratio","Monitor ratios of the norm of function for consecutive steps","SNESMonitorRatio",SNESMonitorRatio,SNESMonitorRatioSetUp);
1000: SNESMonitorSetFromOptions(snes,"-snes_monitor_field","Monitor norm of function (split into fields)","SNESMonitorDefaultField",SNESMonitorDefaultField,NULL);
1001: SNESMonitorSetFromOptions(snes,"-snes_monitor_solution","View solution at each iteration","SNESMonitorSolution",SNESMonitorSolution,NULL);
1002: SNESMonitorSetFromOptions(snes,"-snes_monitor_solution_update","View correction at each iteration","SNESMonitorSolutionUpdate",SNESMonitorSolutionUpdate,NULL);
1003: SNESMonitorSetFromOptions(snes,"-snes_monitor_residual","View residual at each iteration","SNESMonitorResidual",SNESMonitorResidual,NULL);
1004: SNESMonitorSetFromOptions(snes,"-snes_monitor_jacupdate_spectrum","Print the change in the spectrum of the Jacobian","SNESMonitorJacUpdateSpectrum",SNESMonitorJacUpdateSpectrum,NULL);
1005: SNESMonitorSetFromOptions(snes,"-snes_monitor_fields","Monitor norm of function per field","SNESMonitorSet",SNESMonitorFields,NULL);
1007: PetscOptionsString("-snes_monitor_python","Use Python function","SNESMonitorSet",NULL,monfilename,sizeof(monfilename),&flg);
1008: if (flg) {PetscPythonMonitorSet((PetscObject)snes,monfilename);}
1010: flg = PETSC_FALSE;
1011: PetscOptionsBool("-snes_monitor_lg_residualnorm","Plot function norm at each iteration","SNESMonitorLGResidualNorm",flg,&flg,NULL);
1012: if (flg) {
1013: PetscDrawLG ctx;
1015: SNESMonitorLGCreate(PetscObjectComm((PetscObject)snes),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,&ctx);
1016: SNESMonitorSet(snes,SNESMonitorLGResidualNorm,ctx,(PetscErrorCode (*)(void**))PetscDrawLGDestroy);
1017: }
1018: flg = PETSC_FALSE;
1019: PetscOptionsBool("-snes_monitor_lg_range","Plot function range at each iteration","SNESMonitorLGRange",flg,&flg,NULL);
1020: if (flg) {
1021: PetscViewer ctx;
1023: PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,&ctx);
1024: SNESMonitorSet(snes,SNESMonitorLGRange,ctx,(PetscErrorCode (*)(void**))PetscViewerDestroy);
1025: }
1027: flg = PETSC_FALSE;
1028: PetscOptionsBool("-snes_fd","Use finite differences (slow) to compute Jacobian","SNESComputeJacobianDefault",flg,&flg,NULL);
1029: if (flg) {
1030: void *functx;
1031: DM dm;
1032: DMSNES sdm;
1033: SNESGetDM(snes,&dm);
1034: DMGetDMSNES(dm,&sdm);
1035: sdm->jacobianctx = NULL;
1036: SNESGetFunction(snes,NULL,NULL,&functx);
1037: SNESSetJacobian(snes,snes->jacobian,snes->jacobian_pre,SNESComputeJacobianDefault,functx);
1038: PetscInfo(snes,"Setting default finite difference Jacobian matrix\n");
1039: }
1041: flg = PETSC_FALSE;
1042: PetscOptionsBool("-snes_fd_function","Use finite differences (slow) to compute function from user objective","SNESObjectiveComputeFunctionDefaultFD",flg,&flg,NULL);
1043: if (flg) {
1044: SNESSetFunction(snes,NULL,SNESObjectiveComputeFunctionDefaultFD,NULL);
1045: }
1047: flg = PETSC_FALSE;
1048: PetscOptionsBool("-snes_fd_color","Use finite differences with coloring to compute Jacobian","SNESComputeJacobianDefaultColor",flg,&flg,NULL);
1049: if (flg) {
1050: DM dm;
1051: DMSNES sdm;
1052: SNESGetDM(snes,&dm);
1053: DMGetDMSNES(dm,&sdm);
1054: sdm->jacobianctx = NULL;
1055: SNESSetJacobian(snes,snes->jacobian,snes->jacobian_pre,SNESComputeJacobianDefaultColor,NULL);
1056: PetscInfo(snes,"Setting default finite difference coloring Jacobian matrix\n");
1057: }
1059: flg = PETSC_FALSE;
1060: PetscOptionsBool("-snes_mf_operator","Use a Matrix-Free Jacobian with user-provided preconditioner matrix","SNESSetUseMatrixFree",PETSC_FALSE,&snes->mf_operator,&flg);
1061: if (flg && snes->mf_operator) {
1062: snes->mf_operator = PETSC_TRUE;
1063: snes->mf = PETSC_TRUE;
1064: }
1065: flg = PETSC_FALSE;
1066: PetscOptionsBool("-snes_mf","Use a Matrix-Free Jacobian with no preconditioner matrix","SNESSetUseMatrixFree",PETSC_FALSE,&snes->mf,&flg);
1067: if (!flg && snes->mf_operator) snes->mf = PETSC_TRUE;
1068: PetscOptionsInt("-snes_mf_version","Matrix-Free routines version 1 or 2","None",snes->mf_version,&snes->mf_version,NULL);
1070: flg = PETSC_FALSE;
1071: SNESGetNPCSide(snes,&pcside);
1072: PetscOptionsEnum("-snes_npc_side","SNES nonlinear preconditioner side","SNESSetNPCSide",PCSides,(PetscEnum)pcside,(PetscEnum*)&pcside,&flg);
1073: if (flg) {SNESSetNPCSide(snes,pcside);}
1075: #if defined(PETSC_HAVE_SAWS)
1076: /*
1077: Publish convergence information using SAWs
1078: */
1079: flg = PETSC_FALSE;
1080: PetscOptionsBool("-snes_monitor_saws","Publish SNES progress using SAWs","SNESMonitorSet",flg,&flg,NULL);
1081: if (flg) {
1082: void *ctx;
1083: SNESMonitorSAWsCreate(snes,&ctx);
1084: SNESMonitorSet(snes,SNESMonitorSAWs,ctx,SNESMonitorSAWsDestroy);
1085: }
1086: #endif
1087: #if defined(PETSC_HAVE_SAWS)
1088: {
1089: PetscBool set;
1090: flg = PETSC_FALSE;
1091: PetscOptionsBool("-snes_saws_block","Block for SAWs at end of SNESSolve","PetscObjectSAWsBlock",((PetscObject)snes)->amspublishblock,&flg,&set);
1092: if (set) {
1093: PetscObjectSAWsSetBlock((PetscObject)snes,flg);
1094: }
1095: }
1096: #endif
1098: for (i = 0; i < numberofsetfromoptions; i++) {
1099: (*othersetfromoptions[i])(snes);
1100: }
1102: if (snes->ops->setfromoptions) {
1103: (*snes->ops->setfromoptions)(PetscOptionsObject,snes);
1104: }
1106: /* process any options handlers added with PetscObjectAddOptionsHandler() */
1107: PetscObjectProcessOptionsHandlers(PetscOptionsObject,(PetscObject)snes);
1108: PetscOptionsEnd();
1110: if (snes->linesearch) {
1111: SNESGetLineSearch(snes, &snes->linesearch);
1112: SNESLineSearchSetFromOptions(snes->linesearch);
1113: }
1115: if (snes->usesksp) {
1116: if (!snes->ksp) {SNESGetKSP(snes,&snes->ksp);}
1117: KSPSetOperators(snes->ksp,snes->jacobian,snes->jacobian_pre);
1118: KSPSetFromOptions(snes->ksp);
1119: }
1121: /* if user has set the SNES NPC type via options database, create it. */
1122: SNESGetOptionsPrefix(snes, &optionsprefix);
1123: PetscOptionsHasName(((PetscObject)snes)->options,optionsprefix, "-npc_snes_type", &pcset);
1124: if (pcset && (!snes->npc)) {
1125: SNESGetNPC(snes, &snes->npc);
1126: }
1127: if (snes->npc) {
1128: SNESSetFromOptions(snes->npc);
1129: }
1130: snes->setfromoptionscalled++;
1131: return(0);
1132: }
1134: /*@
1135: SNESResetFromOptions - Sets various SNES and KSP parameters from user options ONLY if the SNES was previously set from options
1137: Collective on SNES
1139: Input Parameter:
1140: . snes - the SNES context
1142: Level: beginner
1144: .seealso: SNESSetFromOptions(), SNESSetOptionsPrefix()
1145: @*/
1146: PetscErrorCode SNESResetFromOptions(SNES snes)
1147: {
1151: if (snes->setfromoptionscalled) {SNESSetFromOptions(snes);}
1152: return(0);
1153: }
1155: /*@C
1156: SNESSetComputeApplicationContext - Sets an optional function to compute a user-defined context for
1157: the nonlinear solvers.
1159: Logically Collective on SNES
1161: Input Parameters:
1162: + snes - the SNES context
1163: . compute - function to compute the context
1164: - destroy - function to destroy the context
1166: Level: intermediate
1168: Notes:
1169: This function is currently not available from Fortran.
1171: .seealso: SNESGetApplicationContext(), SNESSetComputeApplicationContext(), SNESGetApplicationContext()
1172: @*/
1173: PetscErrorCode SNESSetComputeApplicationContext(SNES snes,PetscErrorCode (*compute)(SNES,void**),PetscErrorCode (*destroy)(void**))
1174: {
1177: snes->ops->usercompute = compute;
1178: snes->ops->userdestroy = destroy;
1179: return(0);
1180: }
1182: /*@
1183: SNESSetApplicationContext - Sets the optional user-defined context for
1184: the nonlinear solvers.
1186: Logically Collective on SNES
1188: Input Parameters:
1189: + snes - the SNES context
1190: - usrP - optional user context
1192: Level: intermediate
1194: Fortran Notes:
1195: To use this from Fortran you must write a Fortran interface definition for this
1196: function that tells Fortran the Fortran derived data type that you are passing in as the ctx argument.
1198: .seealso: SNESGetApplicationContext()
1199: @*/
1200: PetscErrorCode SNESSetApplicationContext(SNES snes,void *usrP)
1201: {
1203: KSP ksp;
1207: SNESGetKSP(snes,&ksp);
1208: KSPSetApplicationContext(ksp,usrP);
1209: snes->user = usrP;
1210: return(0);
1211: }
1213: /*@
1214: SNESGetApplicationContext - Gets the user-defined context for the
1215: nonlinear solvers.
1217: Not Collective
1219: Input Parameter:
1220: . snes - SNES context
1222: Output Parameter:
1223: . usrP - user context
1225: Fortran Notes:
1226: To use this from Fortran you must write a Fortran interface definition for this
1227: function that tells Fortran the Fortran derived data type that you are passing in as the ctx argument.
1229: Level: intermediate
1231: .seealso: SNESSetApplicationContext()
1232: @*/
1233: PetscErrorCode SNESGetApplicationContext(SNES snes,void *usrP)
1234: {
1237: *(void**)usrP = snes->user;
1238: return(0);
1239: }
1241: /*@
1242: SNESSetUseMatrixFree - indicates that SNES should use matrix free finite difference matrix vector products internally to apply the Jacobian.
1244: Collective on SNES
1246: Input Parameters:
1247: + snes - SNES context
1248: . mf_operator - use matrix-free only for the Amat used by SNESSetJacobian(), this means the user provided Pmat will continue to be used
1249: - mf - use matrix-free for both the Amat and Pmat used by SNESSetJacobian(), both the Amat and Pmat set in SNESSetJacobian() will be ignored
1251: Options Database:
1252: + -snes_mf - use matrix free for both the mat and pmat operator
1253: . -snes_mf_operator - use matrix free only for the mat operator
1254: . -snes_fd_color - compute the Jacobian via coloring and finite differences.
1255: - -snes_fd - compute the Jacobian via finite differences (slow)
1257: Level: intermediate
1259: Notes:
1260: SNES supports three approaches for computing (approximate) Jacobians: user provided via SNESSetJacobian(), matrix free, and computing explictly with
1261: finite differences and coloring using MatFDColoring. It is also possible to use automatic differentiation and the MatFDColoring object.
1263: .seealso: SNESGetUseMatrixFree(), MatCreateSNESMF(), SNESComputeJacobianDefaultColor()
1264: @*/
1265: PetscErrorCode SNESSetUseMatrixFree(SNES snes,PetscBool mf_operator,PetscBool mf)
1266: {
1271: snes->mf = mf_operator ? PETSC_TRUE : mf;
1272: snes->mf_operator = mf_operator;
1273: return(0);
1274: }
1276: /*@
1277: SNESGetUseMatrixFree - indicates if the SNES uses matrix free finite difference matrix vector products to apply the Jacobian.
1279: Collective on SNES
1281: Input Parameter:
1282: . snes - SNES context
1284: Output Parameters:
1285: + mf_operator - use matrix-free only for the Amat used by SNESSetJacobian(), this means the user provided Pmat will continue to be used
1286: - mf - use matrix-free for both the Amat and Pmat used by SNESSetJacobian(), both the Amat and Pmat set in SNESSetJacobian() will be ignored
1288: Options Database:
1289: + -snes_mf - use matrix free for both the mat and pmat operator
1290: - -snes_mf_operator - use matrix free only for the mat operator
1292: Level: intermediate
1294: .seealso: SNESSetUseMatrixFree(), MatCreateSNESMF()
1295: @*/
1296: PetscErrorCode SNESGetUseMatrixFree(SNES snes,PetscBool *mf_operator,PetscBool *mf)
1297: {
1300: if (mf) *mf = snes->mf;
1301: if (mf_operator) *mf_operator = snes->mf_operator;
1302: return(0);
1303: }
1305: /*@
1306: SNESGetIterationNumber - Gets the number of nonlinear iterations completed
1307: at this time.
1309: Not Collective
1311: Input Parameter:
1312: . snes - SNES context
1314: Output Parameter:
1315: . iter - iteration number
1317: Notes:
1318: For example, during the computation of iteration 2 this would return 1.
1320: This is useful for using lagged Jacobians (where one does not recompute the
1321: Jacobian at each SNES iteration). For example, the code
1322: .vb
1323: SNESGetIterationNumber(snes,&it);
1324: if (!(it % 2)) {
1325: [compute Jacobian here]
1326: }
1327: .ve
1328: can be used in your ComputeJacobian() function to cause the Jacobian to be
1329: recomputed every second SNES iteration.
1331: After the SNES solve is complete this will return the number of nonlinear iterations used.
1333: Level: intermediate
1335: .seealso: SNESGetLinearSolveIterations()
1336: @*/
1337: PetscErrorCode SNESGetIterationNumber(SNES snes,PetscInt *iter)
1338: {
1342: *iter = snes->iter;
1343: return(0);
1344: }
1346: /*@
1347: SNESSetIterationNumber - Sets the current iteration number.
1349: Not Collective
1351: Input Parameter:
1352: + snes - SNES context
1353: - iter - iteration number
1355: Level: developer
1357: .seealso: SNESGetLinearSolveIterations()
1358: @*/
1359: PetscErrorCode SNESSetIterationNumber(SNES snes,PetscInt iter)
1360: {
1365: PetscObjectSAWsTakeAccess((PetscObject)snes);
1366: snes->iter = iter;
1367: PetscObjectSAWsGrantAccess((PetscObject)snes);
1368: return(0);
1369: }
1371: /*@
1372: SNESGetNonlinearStepFailures - Gets the number of unsuccessful steps
1373: attempted by the nonlinear solver.
1375: Not Collective
1377: Input Parameter:
1378: . snes - SNES context
1380: Output Parameter:
1381: . nfails - number of unsuccessful steps attempted
1383: Notes:
1384: This counter is reset to zero for each successive call to SNESSolve().
1386: Level: intermediate
1388: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(),
1389: SNESSetMaxNonlinearStepFailures(), SNESGetMaxNonlinearStepFailures()
1390: @*/
1391: PetscErrorCode SNESGetNonlinearStepFailures(SNES snes,PetscInt *nfails)
1392: {
1396: *nfails = snes->numFailures;
1397: return(0);
1398: }
1400: /*@
1401: SNESSetMaxNonlinearStepFailures - Sets the maximum number of unsuccessful steps
1402: attempted by the nonlinear solver before it gives up.
1404: Not Collective
1406: Input Parameters:
1407: + snes - SNES context
1408: - maxFails - maximum of unsuccessful steps
1410: Level: intermediate
1412: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(),
1413: SNESGetMaxNonlinearStepFailures(), SNESGetNonlinearStepFailures()
1414: @*/
1415: PetscErrorCode SNESSetMaxNonlinearStepFailures(SNES snes, PetscInt maxFails)
1416: {
1419: snes->maxFailures = maxFails;
1420: return(0);
1421: }
1423: /*@
1424: SNESGetMaxNonlinearStepFailures - Gets the maximum number of unsuccessful steps
1425: attempted by the nonlinear solver before it gives up.
1427: Not Collective
1429: Input Parameter:
1430: . snes - SNES context
1432: Output Parameter:
1433: . maxFails - maximum of unsuccessful steps
1435: Level: intermediate
1437: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(),
1438: SNESSetMaxNonlinearStepFailures(), SNESGetNonlinearStepFailures()
1440: @*/
1441: PetscErrorCode SNESGetMaxNonlinearStepFailures(SNES snes, PetscInt *maxFails)
1442: {
1446: *maxFails = snes->maxFailures;
1447: return(0);
1448: }
1450: /*@
1451: SNESGetNumberFunctionEvals - Gets the number of user provided function evaluations
1452: done by SNES.
1454: Not Collective
1456: Input Parameter:
1457: . snes - SNES context
1459: Output Parameter:
1460: . nfuncs - number of evaluations
1462: Level: intermediate
1464: Notes:
1465: Reset every time SNESSolve is called unless SNESSetCountersReset() is used.
1467: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(), SNESSetCountersReset()
1468: @*/
1469: PetscErrorCode SNESGetNumberFunctionEvals(SNES snes, PetscInt *nfuncs)
1470: {
1474: *nfuncs = snes->nfuncs;
1475: return(0);
1476: }
1478: /*@
1479: SNESGetLinearSolveFailures - Gets the number of failed (non-converged)
1480: linear solvers.
1482: Not Collective
1484: Input Parameter:
1485: . snes - SNES context
1487: Output Parameter:
1488: . nfails - number of failed solves
1490: Level: intermediate
1492: Options Database Keys:
1493: . -snes_max_linear_solve_fail <num> - The number of failures before the solve is terminated
1495: Notes:
1496: This counter is reset to zero for each successive call to SNESSolve().
1498: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures()
1499: @*/
1500: PetscErrorCode SNESGetLinearSolveFailures(SNES snes,PetscInt *nfails)
1501: {
1505: *nfails = snes->numLinearSolveFailures;
1506: return(0);
1507: }
1509: /*@
1510: SNESSetMaxLinearSolveFailures - the number of failed linear solve attempts
1511: allowed before SNES returns with a diverged reason of SNES_DIVERGED_LINEAR_SOLVE
1513: Logically Collective on SNES
1515: Input Parameters:
1516: + snes - SNES context
1517: - maxFails - maximum allowed linear solve failures
1519: Level: intermediate
1521: Options Database Keys:
1522: . -snes_max_linear_solve_fail <num> - The number of failures before the solve is terminated
1524: Notes:
1525: By default this is 0; that is SNES returns on the first failed linear solve
1527: .seealso: SNESGetLinearSolveFailures(), SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations()
1528: @*/
1529: PetscErrorCode SNESSetMaxLinearSolveFailures(SNES snes, PetscInt maxFails)
1530: {
1534: snes->maxLinearSolveFailures = maxFails;
1535: return(0);
1536: }
1538: /*@
1539: SNESGetMaxLinearSolveFailures - gets the maximum number of linear solve failures that
1540: are allowed before SNES terminates
1542: Not Collective
1544: Input Parameter:
1545: . snes - SNES context
1547: Output Parameter:
1548: . maxFails - maximum of unsuccessful solves allowed
1550: Level: intermediate
1552: Notes:
1553: By default this is 1; that is SNES returns on the first failed linear solve
1555: .seealso: SNESGetLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(),
1556: @*/
1557: PetscErrorCode SNESGetMaxLinearSolveFailures(SNES snes, PetscInt *maxFails)
1558: {
1562: *maxFails = snes->maxLinearSolveFailures;
1563: return(0);
1564: }
1566: /*@
1567: SNESGetLinearSolveIterations - Gets the total number of linear iterations
1568: used by the nonlinear solver.
1570: Not Collective
1572: Input Parameter:
1573: . snes - SNES context
1575: Output Parameter:
1576: . lits - number of linear iterations
1578: Notes:
1579: This counter is reset to zero for each successive call to SNESSolve() unless SNESSetCountersReset() is used.
1581: If the linear solver fails inside the SNESSolve() the iterations for that call to the linear solver are not included. If you wish to count them
1582: then call KSPGetIterationNumber() after the failed solve.
1584: Level: intermediate
1586: .seealso: SNESGetIterationNumber(), SNESGetLinearSolveFailures(), SNESGetMaxLinearSolveFailures(), SNESSetCountersReset()
1587: @*/
1588: PetscErrorCode SNESGetLinearSolveIterations(SNES snes,PetscInt *lits)
1589: {
1593: *lits = snes->linear_its;
1594: return(0);
1595: }
1597: /*@
1598: SNESSetCountersReset - Sets whether or not the counters for linear iterations and function evaluations
1599: are reset every time SNESSolve() is called.
1601: Logically Collective on SNES
1603: Input Parameter:
1604: + snes - SNES context
1605: - reset - whether to reset the counters or not
1607: Notes:
1608: This defaults to PETSC_TRUE
1610: Level: developer
1612: .seealso: SNESGetNumberFunctionEvals(), SNESGetLinearSolveIterations(), SNESGetNPC()
1613: @*/
1614: PetscErrorCode SNESSetCountersReset(SNES snes,PetscBool reset)
1615: {
1619: snes->counters_reset = reset;
1620: return(0);
1621: }
1624: /*@
1625: SNESSetKSP - Sets a KSP context for the SNES object to use
1627: Not Collective, but the SNES and KSP objects must live on the same MPI_Comm
1629: Input Parameters:
1630: + snes - the SNES context
1631: - ksp - the KSP context
1633: Notes:
1634: The SNES object already has its KSP object, you can obtain with SNESGetKSP()
1635: so this routine is rarely needed.
1637: The KSP object that is already in the SNES object has its reference count
1638: decreased by one.
1640: Level: developer
1642: .seealso: KSPGetPC(), SNESCreate(), KSPCreate(), SNESSetKSP()
1643: @*/
1644: PetscErrorCode SNESSetKSP(SNES snes,KSP ksp)
1645: {
1652: PetscObjectReference((PetscObject)ksp);
1653: if (snes->ksp) {PetscObjectDereference((PetscObject)snes->ksp);}
1654: snes->ksp = ksp;
1655: return(0);
1656: }
1658: /* -----------------------------------------------------------*/
1659: /*@
1660: SNESCreate - Creates a nonlinear solver context.
1662: Collective
1664: Input Parameters:
1665: . comm - MPI communicator
1667: Output Parameter:
1668: . outsnes - the new SNES context
1670: Options Database Keys:
1671: + -snes_mf - Activates default matrix-free Jacobian-vector products,
1672: and no preconditioning matrix
1673: . -snes_mf_operator - Activates default matrix-free Jacobian-vector
1674: products, and a user-provided preconditioning matrix
1675: as set by SNESSetJacobian()
1676: - -snes_fd - Uses (slow!) finite differences to compute Jacobian
1678: Level: beginner
1680: Developer Notes:
1681: SNES always creates a KSP object even though many SNES methods do not use it. This is
1682: unfortunate and should be fixed at some point. The flag snes->usesksp indicates if the
1683: particular method does use KSP and regulates if the information about the KSP is printed
1684: in SNESView(). TSSetFromOptions() does call SNESSetFromOptions() which can lead to users being confused
1685: by help messages about meaningless SNES options.
1687: SNES always creates the snes->kspconvctx even though it is used by only one type. This should
1688: be fixed.
1690: .seealso: SNESSolve(), SNESDestroy(), SNES, SNESSetLagPreconditioner(), SNESSetLagJacobian()
1692: @*/
1693: PetscErrorCode SNESCreate(MPI_Comm comm,SNES *outsnes)
1694: {
1696: SNES snes;
1697: SNESKSPEW *kctx;
1701: *outsnes = NULL;
1702: SNESInitializePackage();
1704: PetscHeaderCreate(snes,SNES_CLASSID,"SNES","Nonlinear solver","SNES",comm,SNESDestroy,SNESView);
1706: snes->ops->converged = SNESConvergedDefault;
1707: snes->usesksp = PETSC_TRUE;
1708: snes->tolerancesset = PETSC_FALSE;
1709: snes->max_its = 50;
1710: snes->max_funcs = 10000;
1711: snes->norm = 0.0;
1712: snes->xnorm = 0.0;
1713: snes->ynorm = 0.0;
1714: snes->normschedule = SNES_NORM_ALWAYS;
1715: snes->functype = SNES_FUNCTION_DEFAULT;
1716: #if defined(PETSC_USE_REAL_SINGLE)
1717: snes->rtol = 1.e-5;
1718: #else
1719: snes->rtol = 1.e-8;
1720: #endif
1721: snes->ttol = 0.0;
1722: #if defined(PETSC_USE_REAL_SINGLE)
1723: snes->abstol = 1.e-25;
1724: #else
1725: snes->abstol = 1.e-50;
1726: #endif
1727: #if defined(PETSC_USE_REAL_SINGLE)
1728: snes->stol = 1.e-5;
1729: #else
1730: snes->stol = 1.e-8;
1731: #endif
1732: #if defined(PETSC_USE_REAL_SINGLE)
1733: snes->deltatol = 1.e-6;
1734: #else
1735: snes->deltatol = 1.e-12;
1736: #endif
1737: snes->divtol = 1.e4;
1738: snes->rnorm0 = 0;
1739: snes->nfuncs = 0;
1740: snes->numFailures = 0;
1741: snes->maxFailures = 1;
1742: snes->linear_its = 0;
1743: snes->lagjacobian = 1;
1744: snes->jac_iter = 0;
1745: snes->lagjac_persist = PETSC_FALSE;
1746: snes->lagpreconditioner = 1;
1747: snes->pre_iter = 0;
1748: snes->lagpre_persist = PETSC_FALSE;
1749: snes->numbermonitors = 0;
1750: snes->data = NULL;
1751: snes->setupcalled = PETSC_FALSE;
1752: snes->ksp_ewconv = PETSC_FALSE;
1753: snes->nwork = 0;
1754: snes->work = NULL;
1755: snes->nvwork = 0;
1756: snes->vwork = NULL;
1757: snes->conv_hist_len = 0;
1758: snes->conv_hist_max = 0;
1759: snes->conv_hist = NULL;
1760: snes->conv_hist_its = NULL;
1761: snes->conv_hist_reset = PETSC_TRUE;
1762: snes->counters_reset = PETSC_TRUE;
1763: snes->vec_func_init_set = PETSC_FALSE;
1764: snes->reason = SNES_CONVERGED_ITERATING;
1765: snes->npcside = PC_RIGHT;
1766: snes->setfromoptionscalled = 0;
1768: snes->mf = PETSC_FALSE;
1769: snes->mf_operator = PETSC_FALSE;
1770: snes->mf_version = 1;
1772: snes->numLinearSolveFailures = 0;
1773: snes->maxLinearSolveFailures = 1;
1775: snes->vizerotolerance = 1.e-8;
1776: snes->checkjacdomainerror = PetscDefined(USE_DEBUG) ? PETSC_TRUE : PETSC_FALSE;
1778: /* Set this to true if the implementation of SNESSolve_XXX does compute the residual at the final solution. */
1779: snes->alwayscomputesfinalresidual = PETSC_FALSE;
1781: /* Create context to compute Eisenstat-Walker relative tolerance for KSP */
1782: PetscNewLog(snes,&kctx);
1784: snes->kspconvctx = (void*)kctx;
1785: kctx->version = 2;
1786: kctx->rtol_0 = .3; /* Eisenstat and Walker suggest rtol_0=.5, but
1787: this was too large for some test cases */
1788: kctx->rtol_last = 0.0;
1789: kctx->rtol_max = .9;
1790: kctx->gamma = 1.0;
1791: kctx->alpha = .5*(1.0 + PetscSqrtReal(5.0));
1792: kctx->alpha2 = kctx->alpha;
1793: kctx->threshold = .1;
1794: kctx->lresid_last = 0.0;
1795: kctx->norm_last = 0.0;
1797: *outsnes = snes;
1798: return(0);
1799: }
1801: /*MC
1802: SNESFunction - Functional form used to convey the nonlinear function to be solved by SNES
1804: Synopsis:
1805: #include "petscsnes.h"
1806: PetscErrorCode SNESFunction(SNES snes,Vec x,Vec f,void *ctx);
1808: Collective on snes
1810: Input Parameters:
1811: + snes - the SNES context
1812: . x - state at which to evaluate residual
1813: - ctx - optional user-defined function context, passed in with SNESSetFunction()
1815: Output Parameter:
1816: . f - vector to put residual (function value)
1818: Level: intermediate
1820: .seealso: SNESSetFunction(), SNESGetFunction()
1821: M*/
1823: /*@C
1824: SNESSetFunction - Sets the function evaluation routine and function
1825: vector for use by the SNES routines in solving systems of nonlinear
1826: equations.
1828: Logically Collective on SNES
1830: Input Parameters:
1831: + snes - the SNES context
1832: . r - vector to store function value
1833: . f - function evaluation routine; see SNESFunction for calling sequence details
1834: - ctx - [optional] user-defined context for private data for the
1835: function evaluation routine (may be NULL)
1837: Notes:
1838: The Newton-like methods typically solve linear systems of the form
1839: $ f'(x) x = -f(x),
1840: where f'(x) denotes the Jacobian matrix and f(x) is the function.
1842: Level: beginner
1844: .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetPicard(), SNESFunction
1845: @*/
1846: PetscErrorCode SNESSetFunction(SNES snes,Vec r,PetscErrorCode (*f)(SNES,Vec,Vec,void*),void *ctx)
1847: {
1849: DM dm;
1853: if (r) {
1856: PetscObjectReference((PetscObject)r);
1857: VecDestroy(&snes->vec_func);
1859: snes->vec_func = r;
1860: }
1861: SNESGetDM(snes,&dm);
1862: DMSNESSetFunction(dm,f,ctx);
1863: return(0);
1864: }
1867: /*@C
1868: SNESSetInitialFunction - Sets the function vector to be used as the
1869: function norm at the initialization of the method. In some
1870: instances, the user has precomputed the function before calling
1871: SNESSolve. This function allows one to avoid a redundant call
1872: to SNESComputeFunction in that case.
1874: Logically Collective on SNES
1876: Input Parameters:
1877: + snes - the SNES context
1878: - f - vector to store function value
1880: Notes:
1881: This should not be modified during the solution procedure.
1883: This is used extensively in the SNESFAS hierarchy and in nonlinear preconditioning.
1885: Level: developer
1887: .seealso: SNESSetFunction(), SNESComputeFunction(), SNESSetInitialFunctionNorm()
1888: @*/
1889: PetscErrorCode SNESSetInitialFunction(SNES snes, Vec f)
1890: {
1892: Vec vec_func;
1898: if (snes->npcside== PC_LEFT && snes->functype == SNES_FUNCTION_PRECONDITIONED) {
1899: snes->vec_func_init_set = PETSC_FALSE;
1900: return(0);
1901: }
1902: SNESGetFunction(snes,&vec_func,NULL,NULL);
1903: VecCopy(f, vec_func);
1905: snes->vec_func_init_set = PETSC_TRUE;
1906: return(0);
1907: }
1909: /*@
1910: SNESSetNormSchedule - Sets the SNESNormSchedule used in covergence and monitoring
1911: of the SNES method.
1913: Logically Collective on SNES
1915: Input Parameters:
1916: + snes - the SNES context
1917: - normschedule - the frequency of norm computation
1919: Options Database Key:
1920: . -snes_norm_schedule <none, always, initialonly, finalonly, initalfinalonly>
1922: Notes:
1923: Only certain SNES methods support certain SNESNormSchedules. Most require evaluation
1924: of the nonlinear function and the taking of its norm at every iteration to
1925: even ensure convergence at all. However, methods such as custom Gauss-Seidel methods
1926: (SNESNGS) and the like do not require the norm of the function to be computed, and therfore
1927: may either be monitored for convergence or not. As these are often used as nonlinear
1928: preconditioners, monitoring the norm of their error is not a useful enterprise within
1929: their solution.
1931: Level: developer
1933: .seealso: SNESGetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1934: @*/
1935: PetscErrorCode SNESSetNormSchedule(SNES snes, SNESNormSchedule normschedule)
1936: {
1939: snes->normschedule = normschedule;
1940: return(0);
1941: }
1944: /*@
1945: SNESGetNormSchedule - Gets the SNESNormSchedule used in covergence and monitoring
1946: of the SNES method.
1948: Logically Collective on SNES
1950: Input Parameters:
1951: + snes - the SNES context
1952: - normschedule - the type of the norm used
1954: Level: advanced
1956: .seealso: SNESSetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1957: @*/
1958: PetscErrorCode SNESGetNormSchedule(SNES snes, SNESNormSchedule *normschedule)
1959: {
1962: *normschedule = snes->normschedule;
1963: return(0);
1964: }
1967: /*@
1968: SNESSetFunctionNorm - Sets the last computed residual norm.
1970: Logically Collective on SNES
1972: Input Parameters:
1973: + snes - the SNES context
1975: - normschedule - the frequency of norm computation
1977: Level: developer
1979: .seealso: SNESGetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1980: @*/
1981: PetscErrorCode SNESSetFunctionNorm(SNES snes, PetscReal norm)
1982: {
1985: snes->norm = norm;
1986: return(0);
1987: }
1989: /*@
1990: SNESGetFunctionNorm - Gets the last computed norm of the residual
1992: Not Collective
1994: Input Parameter:
1995: . snes - the SNES context
1997: Output Parameter:
1998: . norm - the last computed residual norm
2000: Level: developer
2002: .seealso: SNESSetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
2003: @*/
2004: PetscErrorCode SNESGetFunctionNorm(SNES snes, PetscReal *norm)
2005: {
2009: *norm = snes->norm;
2010: return(0);
2011: }
2013: /*@
2014: SNESGetUpdateNorm - Gets the last computed norm of the Newton update
2016: Not Collective
2018: Input Parameter:
2019: . snes - the SNES context
2021: Output Parameter:
2022: . ynorm - the last computed update norm
2024: Level: developer
2026: .seealso: SNESSetNormSchedule(), SNESComputeFunction(), SNESGetFunctionNorm()
2027: @*/
2028: PetscErrorCode SNESGetUpdateNorm(SNES snes, PetscReal *ynorm)
2029: {
2033: *ynorm = snes->ynorm;
2034: return(0);
2035: }
2037: /*@
2038: SNESGetSolutionNorm - Gets the last computed norm of the solution
2040: Not Collective
2042: Input Parameter:
2043: . snes - the SNES context
2045: Output Parameter:
2046: . xnorm - the last computed solution norm
2048: Level: developer
2050: .seealso: SNESSetNormSchedule(), SNESComputeFunction(), SNESGetFunctionNorm(), SNESGetUpdateNorm()
2051: @*/
2052: PetscErrorCode SNESGetSolutionNorm(SNES snes, PetscReal *xnorm)
2053: {
2057: *xnorm = snes->xnorm;
2058: return(0);
2059: }
2061: /*@C
2062: SNESSetFunctionType - Sets the SNESNormSchedule used in covergence and monitoring
2063: of the SNES method.
2065: Logically Collective on SNES
2067: Input Parameters:
2068: + snes - the SNES context
2069: - normschedule - the frequency of norm computation
2071: Notes:
2072: Only certain SNES methods support certain SNESNormSchedules. Most require evaluation
2073: of the nonlinear function and the taking of its norm at every iteration to
2074: even ensure convergence at all. However, methods such as custom Gauss-Seidel methods
2075: (SNESNGS) and the like do not require the norm of the function to be computed, and therfore
2076: may either be monitored for convergence or not. As these are often used as nonlinear
2077: preconditioners, monitoring the norm of their error is not a useful enterprise within
2078: their solution.
2080: Level: developer
2082: .seealso: SNESGetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
2083: @*/
2084: PetscErrorCode SNESSetFunctionType(SNES snes, SNESFunctionType type)
2085: {
2088: snes->functype = type;
2089: return(0);
2090: }
2093: /*@C
2094: SNESGetFunctionType - Gets the SNESNormSchedule used in covergence and monitoring
2095: of the SNES method.
2097: Logically Collective on SNES
2099: Input Parameters:
2100: + snes - the SNES context
2101: - normschedule - the type of the norm used
2103: Level: advanced
2105: .seealso: SNESSetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
2106: @*/
2107: PetscErrorCode SNESGetFunctionType(SNES snes, SNESFunctionType *type)
2108: {
2111: *type = snes->functype;
2112: return(0);
2113: }
2115: /*MC
2116: SNESNGSFunction - function used to convey a Gauss-Seidel sweep on the nonlinear function
2118: Synopsis:
2119: #include <petscsnes.h>
2120: $ SNESNGSFunction(SNES snes,Vec x,Vec b,void *ctx);
2122: Collective on snes
2124: Input Parameters:
2125: + X - solution vector
2126: . B - RHS vector
2127: - ctx - optional user-defined Gauss-Seidel context
2129: Output Parameter:
2130: . X - solution vector
2132: Level: intermediate
2134: .seealso: SNESSetNGS(), SNESGetNGS()
2135: M*/
2137: /*@C
2138: SNESSetNGS - Sets the user nonlinear Gauss-Seidel routine for
2139: use with composed nonlinear solvers.
2141: Input Parameters:
2142: + snes - the SNES context
2143: . f - function evaluation routine to apply Gauss-Seidel see SNESNGSFunction
2144: - ctx - [optional] user-defined context for private data for the
2145: smoother evaluation routine (may be NULL)
2147: Notes:
2148: The NGS routines are used by the composed nonlinear solver to generate
2149: a problem appropriate update to the solution, particularly FAS.
2151: Level: intermediate
2153: .seealso: SNESGetFunction(), SNESComputeNGS()
2154: @*/
2155: PetscErrorCode SNESSetNGS(SNES snes,PetscErrorCode (*f)(SNES,Vec,Vec,void*),void *ctx)
2156: {
2158: DM dm;
2162: SNESGetDM(snes,&dm);
2163: DMSNESSetNGS(dm,f,ctx);
2164: return(0);
2165: }
2167: PetscErrorCode SNESPicardComputeFunction(SNES snes,Vec x,Vec f,void *ctx)
2168: {
2170: DM dm;
2171: DMSNES sdm;
2174: SNESGetDM(snes,&dm);
2175: DMGetDMSNES(dm,&sdm);
2176: if (!sdm->ops->computepfunction) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetPicard() to provide Picard function.");
2177: if (!sdm->ops->computepjacobian) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetPicard() to provide Picard Jacobian.");
2178: /* A(x)*x - b(x) */
2179: PetscStackPush("SNES Picard user function");
2180: (*sdm->ops->computepfunction)(snes,x,f,sdm->pctx);
2181: PetscStackPop;
2182: PetscStackPush("SNES Picard user Jacobian");
2183: (*sdm->ops->computepjacobian)(snes,x,snes->jacobian,snes->jacobian_pre,sdm->pctx);
2184: PetscStackPop;
2185: VecScale(f,-1.0);
2186: MatMultAdd(snes->jacobian,x,f,f);
2187: return(0);
2188: }
2190: PetscErrorCode SNESPicardComputeJacobian(SNES snes,Vec x1,Mat J,Mat B,void *ctx)
2191: {
2193: /* the jacobian matrix should be pre-filled in SNESPicardComputeFunction */
2194: return(0);
2195: }
2197: /*@C
2198: SNESSetPicard - Use SNES to solve the semilinear-system A(x) x = b(x) via a Picard type iteration (Picard linearization)
2200: Logically Collective on SNES
2202: Input Parameters:
2203: + snes - the SNES context
2204: . r - vector to store function value
2205: . b - function evaluation routine
2206: . Amat - matrix with which A(x) x - b(x) is to be computed
2207: . Pmat - matrix from which preconditioner is computed (usually the same as Amat)
2208: . J - function to compute matrix value, see SNESJacobianFunction for details on its calling sequence
2209: - ctx - [optional] user-defined context for private data for the
2210: function evaluation routine (may be NULL)
2212: Notes:
2213: We do not recomemend using this routine. It is far better to provide the nonlinear function F() and some approximation to the Jacobian and use
2214: an approximate Newton solver. This interface is provided to allow porting/testing a previous Picard based code in PETSc before converting it to approximate Newton.
2216: One can call SNESSetPicard() or SNESSetFunction() (and possibly SNESSetJacobian()) but cannot call both
2218: $ Solves the equation A(x) x = b(x) via the defect correction algorithm A(x^{n}) (x^{n+1} - x^{n}) = b(x^{n}) - A(x^{n})x^{n}
2219: $ Note that when an exact solver is used this corresponds to the "classic" Picard A(x^{n}) x^{n+1} = b(x^{n}) iteration.
2221: Run with -snes_mf_operator to solve the system with Newton's method using A(x^{n}) to construct the preconditioner.
2223: We implement the defect correction form of the Picard iteration because it converges much more generally when inexact linear solvers are used then
2224: the direct Picard iteration A(x^n) x^{n+1} = b(x^n)
2226: There is some controversity over the definition of a Picard iteration for nonlinear systems but almost everyone agrees that it involves a linear solve and some
2227: believe it is the iteration A(x^{n}) x^{n+1} = b(x^{n}) hence we use the name Picard. If anyone has an authoritative reference that defines the Picard iteration
2228: different please contact us at petsc-dev@mcs.anl.gov and we'll have an entirely new argument :-).
2230: Level: intermediate
2232: .seealso: SNESGetFunction(), SNESSetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESGetPicard(), SNESLineSearchPreCheckPicard(), SNESJacobianFunction
2233: @*/
2234: PetscErrorCode SNESSetPicard(SNES snes,Vec r,PetscErrorCode (*b)(SNES,Vec,Vec,void*),Mat Amat, Mat Pmat, PetscErrorCode (*J)(SNES,Vec,Mat,Mat,void*),void *ctx)
2235: {
2237: DM dm;
2241: SNESGetDM(snes, &dm);
2242: DMSNESSetPicard(dm,b,J,ctx);
2243: SNESSetFunction(snes,r,SNESPicardComputeFunction,ctx);
2244: SNESSetJacobian(snes,Amat,Pmat,SNESPicardComputeJacobian,ctx);
2245: return(0);
2246: }
2248: /*@C
2249: SNESGetPicard - Returns the context for the Picard iteration
2251: Not Collective, but Vec is parallel if SNES is parallel. Collective if Vec is requested, but has not been created yet.
2253: Input Parameter:
2254: . snes - the SNES context
2256: Output Parameter:
2257: + r - the function (or NULL)
2258: . f - the function (or NULL); see SNESFunction for calling sequence details
2259: . Amat - the matrix used to defined the operation A(x) x - b(x) (or NULL)
2260: . Pmat - the matrix from which the preconditioner will be constructed (or NULL)
2261: . J - the function for matrix evaluation (or NULL); see SNESJacobianFunction for calling sequence details
2262: - ctx - the function context (or NULL)
2264: Level: advanced
2266: .seealso: SNESSetPicard(), SNESGetFunction(), SNESGetJacobian(), SNESGetDM(), SNESFunction, SNESJacobianFunction
2267: @*/
2268: PetscErrorCode SNESGetPicard(SNES snes,Vec *r,PetscErrorCode (**f)(SNES,Vec,Vec,void*),Mat *Amat, Mat *Pmat, PetscErrorCode (**J)(SNES,Vec,Mat,Mat,void*),void **ctx)
2269: {
2271: DM dm;
2275: SNESGetFunction(snes,r,NULL,NULL);
2276: SNESGetJacobian(snes,Amat,Pmat,NULL,NULL);
2277: SNESGetDM(snes,&dm);
2278: DMSNESGetPicard(dm,f,J,ctx);
2279: return(0);
2280: }
2282: /*@C
2283: SNESSetComputeInitialGuess - Sets a routine used to compute an initial guess for the problem
2285: Logically Collective on SNES
2287: Input Parameters:
2288: + snes - the SNES context
2289: . func - function evaluation routine
2290: - ctx - [optional] user-defined context for private data for the
2291: function evaluation routine (may be NULL)
2293: Calling sequence of func:
2294: $ func (SNES snes,Vec x,void *ctx);
2296: . f - function vector
2297: - ctx - optional user-defined function context
2299: Level: intermediate
2301: .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian()
2302: @*/
2303: PetscErrorCode SNESSetComputeInitialGuess(SNES snes,PetscErrorCode (*func)(SNES,Vec,void*),void *ctx)
2304: {
2307: if (func) snes->ops->computeinitialguess = func;
2308: if (ctx) snes->initialguessP = ctx;
2309: return(0);
2310: }
2312: /* --------------------------------------------------------------- */
2313: /*@C
2314: SNESGetRhs - Gets the vector for solving F(x) = rhs. If rhs is not set
2315: it assumes a zero right hand side.
2317: Logically Collective on SNES
2319: Input Parameter:
2320: . snes - the SNES context
2322: Output Parameter:
2323: . rhs - the right hand side vector or NULL if the right hand side vector is null
2325: Level: intermediate
2327: .seealso: SNESGetSolution(), SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetFunction()
2328: @*/
2329: PetscErrorCode SNESGetRhs(SNES snes,Vec *rhs)
2330: {
2334: *rhs = snes->vec_rhs;
2335: return(0);
2336: }
2338: /*@
2339: SNESComputeFunction - Calls the function that has been set with SNESSetFunction().
2341: Collective on SNES
2343: Input Parameters:
2344: + snes - the SNES context
2345: - x - input vector
2347: Output Parameter:
2348: . y - function vector, as set by SNESSetFunction()
2350: Notes:
2351: SNESComputeFunction() is typically used within nonlinear solvers
2352: implementations, so most users would not generally call this routine
2353: themselves.
2355: Level: developer
2357: .seealso: SNESSetFunction(), SNESGetFunction()
2358: @*/
2359: PetscErrorCode SNESComputeFunction(SNES snes,Vec x,Vec y)
2360: {
2362: DM dm;
2363: DMSNES sdm;
2371: VecValidValues(x,2,PETSC_TRUE);
2373: SNESGetDM(snes,&dm);
2374: DMGetDMSNES(dm,&sdm);
2375: if (sdm->ops->computefunction) {
2376: if (sdm->ops->computefunction != SNESObjectiveComputeFunctionDefaultFD) {
2377: PetscLogEventBegin(SNES_FunctionEval,snes,x,y,0);
2378: }
2379: VecLockReadPush(x);
2380: PetscStackPush("SNES user function");
2381: /* ensure domainerror is false prior to computefunction evaluation (may not have been reset) */
2382: snes->domainerror = PETSC_FALSE;
2383: (*sdm->ops->computefunction)(snes,x,y,sdm->functionctx);
2384: PetscStackPop;
2385: VecLockReadPop(x);
2386: if (sdm->ops->computefunction != SNESObjectiveComputeFunctionDefaultFD) {
2387: PetscLogEventEnd(SNES_FunctionEval,snes,x,y,0);
2388: }
2389: } else if (snes->vec_rhs) {
2390: MatMult(snes->jacobian, x, y);
2391: } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetFunction() or SNESSetDM() before SNESComputeFunction(), likely called from SNESSolve().");
2392: if (snes->vec_rhs) {
2393: VecAXPY(y,-1.0,snes->vec_rhs);
2394: }
2395: snes->nfuncs++;
2396: /*
2397: domainerror might not be set on all processes; so we tag vector locally with Inf and the next inner product or norm will
2398: propagate the value to all processes
2399: */
2400: if (snes->domainerror) {
2401: VecSetInf(y);
2402: }
2403: return(0);
2404: }
2406: /*@
2407: SNESComputeNGS - Calls the Gauss-Seidel function that has been set with SNESSetNGS().
2409: Collective on SNES
2411: Input Parameters:
2412: + snes - the SNES context
2413: . x - input vector
2414: - b - rhs vector
2416: Output Parameter:
2417: . x - new solution vector
2419: Notes:
2420: SNESComputeNGS() is typically used within composed nonlinear solver
2421: implementations, so most users would not generally call this routine
2422: themselves.
2424: Level: developer
2426: .seealso: SNESSetNGS(), SNESComputeFunction()
2427: @*/
2428: PetscErrorCode SNESComputeNGS(SNES snes,Vec b,Vec x)
2429: {
2431: DM dm;
2432: DMSNES sdm;
2440: if (b) {VecValidValues(b,2,PETSC_TRUE);}
2441: PetscLogEventBegin(SNES_NGSEval,snes,x,b,0);
2442: SNESGetDM(snes,&dm);
2443: DMGetDMSNES(dm,&sdm);
2444: if (sdm->ops->computegs) {
2445: if (b) {VecLockReadPush(b);}
2446: PetscStackPush("SNES user NGS");
2447: (*sdm->ops->computegs)(snes,x,b,sdm->gsctx);
2448: PetscStackPop;
2449: if (b) {VecLockReadPop(b);}
2450: } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetNGS() before SNESComputeNGS(), likely called from SNESSolve().");
2451: PetscLogEventEnd(SNES_NGSEval,snes,x,b,0);
2452: return(0);
2453: }
2455: PetscErrorCode SNESTestJacobian(SNES snes)
2456: {
2457: Mat A,B,C,D,jacobian;
2458: Vec x = snes->vec_sol,f = snes->vec_func;
2459: PetscErrorCode ierr;
2460: PetscReal nrm,gnorm;
2461: PetscReal threshold = 1.e-5;
2462: MatType mattype;
2463: PetscInt m,n,M,N;
2464: void *functx;
2465: PetscBool complete_print = PETSC_FALSE,threshold_print = PETSC_FALSE,test = PETSC_FALSE,flg,istranspose;
2466: PetscViewer viewer,mviewer;
2467: MPI_Comm comm;
2468: PetscInt tabs;
2469: static PetscBool directionsprinted = PETSC_FALSE;
2470: PetscViewerFormat format;
2473: PetscObjectOptionsBegin((PetscObject)snes);
2474: PetscOptionsName("-snes_test_jacobian","Compare hand-coded and finite difference Jacobians","None",&test);
2475: PetscOptionsReal("-snes_test_jacobian", "Threshold for element difference between hand-coded and finite difference being meaningful", "None", threshold, &threshold,NULL);
2476: PetscOptionsViewer("-snes_test_jacobian_view","View difference between hand-coded and finite difference Jacobians element entries","None",&mviewer,&format,&complete_print);
2477: if (!complete_print) {
2478: PetscOptionsDeprecated("-snes_test_jacobian_display","-snes_test_jacobian_view","3.13",NULL);
2479: PetscOptionsViewer("-snes_test_jacobian_display","Display difference between hand-coded and finite difference Jacobians","None",&mviewer,&format,&complete_print);
2480: }
2481: /* for compatibility with PETSc 3.9 and older. */
2482: PetscOptionsDeprecated("-snes_test_jacobian_display_threshold","-snes_test_jacobian","3.13","-snes_test_jacobian accepts an optional threshold (since v3.10)");
2483: PetscOptionsReal("-snes_test_jacobian_display_threshold", "Display difference between hand-coded and finite difference Jacobians which exceed input threshold", "None", threshold, &threshold, &threshold_print);
2484: PetscOptionsEnd();
2485: if (!test) return(0);
2487: PetscObjectGetComm((PetscObject)snes,&comm);
2488: PetscViewerASCIIGetStdout(comm,&viewer);
2489: PetscViewerASCIIGetTab(viewer, &tabs);
2490: PetscViewerASCIISetTab(viewer, ((PetscObject)snes)->tablevel);
2491: PetscViewerASCIIPrintf(viewer," ---------- Testing Jacobian -------------\n");
2492: if (!complete_print && !directionsprinted) {
2493: PetscViewerASCIIPrintf(viewer," Run with -snes_test_jacobian_view and optionally -snes_test_jacobian <threshold> to show difference\n");
2494: PetscViewerASCIIPrintf(viewer," of hand-coded and finite difference Jacobian entries greater than <threshold>.\n");
2495: }
2496: if (!directionsprinted) {
2497: PetscViewerASCIIPrintf(viewer," Testing hand-coded Jacobian, if (for double precision runs) ||J - Jfd||_F/||J||_F is\n");
2498: PetscViewerASCIIPrintf(viewer," O(1.e-8), the hand-coded Jacobian is probably correct.\n");
2499: directionsprinted = PETSC_TRUE;
2500: }
2501: if (complete_print) {
2502: PetscViewerPushFormat(mviewer,format);
2503: }
2505: PetscObjectTypeCompare((PetscObject)snes->jacobian,MATMFFD,&flg);
2506: if (!flg) jacobian = snes->jacobian;
2507: else jacobian = snes->jacobian_pre;
2509: if (!x) {
2510: MatCreateVecs(jacobian, &x, NULL);
2511: } else {
2512: PetscObjectReference((PetscObject) x);
2513: }
2514: if (!f) {
2515: VecDuplicate(x, &f);
2516: } else {
2517: PetscObjectReference((PetscObject) f);
2518: }
2519: /* evaluate the function at this point because SNESComputeJacobianDefault() assumes that the function has been evaluated and put into snes->vec_func */
2520: SNESComputeFunction(snes,x,f);
2521: VecDestroy(&f);
2522: PetscObjectTypeCompare((PetscObject)snes,SNESKSPTRANSPOSEONLY,&istranspose);
2523: while (jacobian) {
2524: Mat JT = NULL, Jsave = NULL;
2526: if (istranspose) {
2527: MatCreateTranspose(jacobian,&JT);
2528: Jsave = jacobian;
2529: jacobian = JT;
2530: }
2531: PetscObjectBaseTypeCompareAny((PetscObject)jacobian,&flg,MATSEQAIJ,MATMPIAIJ,MATSEQDENSE,MATMPIDENSE,MATSEQBAIJ,MATMPIBAIJ,MATSEQSBAIJ,MATMPISBAIJ,"");
2532: if (flg) {
2533: A = jacobian;
2534: PetscObjectReference((PetscObject)A);
2535: } else {
2536: MatComputeOperator(jacobian,MATAIJ,&A);
2537: }
2539: MatGetType(A,&mattype);
2540: MatGetSize(A,&M,&N);
2541: MatGetLocalSize(A,&m,&n);
2542: MatCreate(PetscObjectComm((PetscObject)A),&B);
2543: MatSetType(B,mattype);
2544: MatSetSizes(B,m,n,M,N);
2545: MatSetBlockSizesFromMats(B,A,A);
2546: MatSetUp(B);
2547: MatSetOption(B,MAT_NEW_NONZERO_ALLOCATION_ERR,PETSC_FALSE);
2549: SNESGetFunction(snes,NULL,NULL,&functx);
2550: SNESComputeJacobianDefault(snes,x,B,B,functx);
2552: MatDuplicate(B,MAT_COPY_VALUES,&D);
2553: MatAYPX(D,-1.0,A,DIFFERENT_NONZERO_PATTERN);
2554: MatNorm(D,NORM_FROBENIUS,&nrm);
2555: MatNorm(A,NORM_FROBENIUS,&gnorm);
2556: MatDestroy(&D);
2557: if (!gnorm) gnorm = 1; /* just in case */
2558: PetscViewerASCIIPrintf(viewer," ||J - Jfd||_F/||J||_F = %g, ||J - Jfd||_F = %g\n",(double)(nrm/gnorm),(double)nrm);
2560: if (complete_print) {
2561: PetscViewerASCIIPrintf(viewer," Hand-coded Jacobian ----------\n");
2562: MatView(A,mviewer);
2563: PetscViewerASCIIPrintf(viewer," Finite difference Jacobian ----------\n");
2564: MatView(B,mviewer);
2565: }
2567: if (threshold_print || complete_print) {
2568: PetscInt Istart, Iend, *ccols, bncols, cncols, j, row;
2569: PetscScalar *cvals;
2570: const PetscInt *bcols;
2571: const PetscScalar *bvals;
2573: MatCreate(PetscObjectComm((PetscObject)A),&C);
2574: MatSetType(C,mattype);
2575: MatSetSizes(C,m,n,M,N);
2576: MatSetBlockSizesFromMats(C,A,A);
2577: MatSetUp(C);
2578: MatSetOption(C,MAT_NEW_NONZERO_ALLOCATION_ERR,PETSC_FALSE);
2580: MatAYPX(B,-1.0,A,DIFFERENT_NONZERO_PATTERN);
2581: MatGetOwnershipRange(B,&Istart,&Iend);
2583: for (row = Istart; row < Iend; row++) {
2584: MatGetRow(B,row,&bncols,&bcols,&bvals);
2585: PetscMalloc2(bncols,&ccols,bncols,&cvals);
2586: for (j = 0, cncols = 0; j < bncols; j++) {
2587: if (PetscAbsScalar(bvals[j]) > threshold) {
2588: ccols[cncols] = bcols[j];
2589: cvals[cncols] = bvals[j];
2590: cncols += 1;
2591: }
2592: }
2593: if (cncols) {
2594: MatSetValues(C,1,&row,cncols,ccols,cvals,INSERT_VALUES);
2595: }
2596: MatRestoreRow(B,row,&bncols,&bcols,&bvals);
2597: PetscFree2(ccols,cvals);
2598: }
2599: MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY);
2600: MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY);
2601: PetscViewerASCIIPrintf(viewer," Hand-coded minus finite-difference Jacobian with tolerance %g ----------\n",(double)threshold);
2602: MatView(C,complete_print ? mviewer : viewer);
2603: MatDestroy(&C);
2604: }
2605: MatDestroy(&A);
2606: MatDestroy(&B);
2607: MatDestroy(&JT);
2608: if (Jsave) jacobian = Jsave;
2609: if (jacobian != snes->jacobian_pre) {
2610: jacobian = snes->jacobian_pre;
2611: PetscViewerASCIIPrintf(viewer," ---------- Testing Jacobian for preconditioner -------------\n");
2612: }
2613: else jacobian = NULL;
2614: }
2615: VecDestroy(&x);
2616: if (complete_print) {
2617: PetscViewerPopFormat(mviewer);
2618: }
2619: if (mviewer) { PetscViewerDestroy(&mviewer); }
2620: PetscViewerASCIISetTab(viewer,tabs);
2621: return(0);
2622: }
2624: /*@
2625: SNESComputeJacobian - Computes the Jacobian matrix that has been set with SNESSetJacobian().
2627: Collective on SNES
2629: Input Parameters:
2630: + snes - the SNES context
2631: - x - input vector
2633: Output Parameters:
2634: + A - Jacobian matrix
2635: - B - optional preconditioning matrix
2637: Options Database Keys:
2638: + -snes_lag_preconditioner <lag>
2639: . -snes_lag_jacobian <lag>
2640: . -snes_test_jacobian <optional threshold> - compare the user provided Jacobian with one compute via finite differences to check for errors. If a threshold is given, display only those entries whose difference is greater than the threshold.
2641: . -snes_test_jacobian_view - display the user provided Jacobian, the finite difference Jacobian and the difference between them to help users detect the location of errors in the user provided Jacobian
2642: . -snes_compare_explicit - Compare the computed Jacobian to the finite difference Jacobian and output the differences
2643: . -snes_compare_explicit_draw - Compare the computed Jacobian to the finite difference Jacobian and draw the result
2644: . -snes_compare_explicit_contour - Compare the computed Jacobian to the finite difference Jacobian and draw a contour plot with the result
2645: . -snes_compare_operator - Make the comparison options above use the operator instead of the preconditioning matrix
2646: . -snes_compare_coloring - Compute the finite difference Jacobian using coloring and display norms of difference
2647: . -snes_compare_coloring_display - Compute the finite differece Jacobian using coloring and display verbose differences
2648: . -snes_compare_coloring_threshold - Display only those matrix entries that differ by more than a given threshold
2649: . -snes_compare_coloring_threshold_atol - Absolute tolerance for difference in matrix entries to be displayed by -snes_compare_coloring_threshold
2650: . -snes_compare_coloring_threshold_rtol - Relative tolerance for difference in matrix entries to be displayed by -snes_compare_coloring_threshold
2651: . -snes_compare_coloring_draw - Compute the finite differece Jacobian using coloring and draw differences
2652: - -snes_compare_coloring_draw_contour - Compute the finite differece Jacobian using coloring and show contours of matrices and differences
2655: Notes:
2656: Most users should not need to explicitly call this routine, as it
2657: is used internally within the nonlinear solvers.
2659: Developer Notes:
2660: This has duplicative ways of checking the accuracy of the user provided Jacobian (see the options above). This is for historical reasons, the routine SNESTestJacobian() use to used
2661: for with the SNESType of test that has been removed.
2663: Level: developer
2665: .seealso: SNESSetJacobian(), KSPSetOperators(), MatStructure, SNESSetLagPreconditioner(), SNESSetLagJacobian()
2666: @*/
2667: PetscErrorCode SNESComputeJacobian(SNES snes,Vec X,Mat A,Mat B)
2668: {
2670: PetscBool flag;
2671: DM dm;
2672: DMSNES sdm;
2673: KSP ksp;
2679: VecValidValues(X,2,PETSC_TRUE);
2680: SNESGetDM(snes,&dm);
2681: DMGetDMSNES(dm,&sdm);
2683: if (!sdm->ops->computejacobian) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_USER,"Must call SNESSetJacobian(), DMSNESSetJacobian(), DMDASNESSetJacobianLocal(), etc");
2685: /* make sure that MatAssemblyBegin/End() is called on A matrix if it is matrix free */
2687: if (snes->lagjacobian == -2) {
2688: snes->lagjacobian = -1;
2690: PetscInfo(snes,"Recomputing Jacobian/preconditioner because lag is -2 (means compute Jacobian, but then never again) \n");
2691: } else if (snes->lagjacobian == -1) {
2692: PetscInfo(snes,"Reusing Jacobian/preconditioner because lag is -1\n");
2693: PetscObjectTypeCompare((PetscObject)A,MATMFFD,&flag);
2694: if (flag) {
2695: MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
2696: MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
2697: }
2698: return(0);
2699: } else if (snes->lagjacobian > 1 && (snes->iter + snes->jac_iter) % snes->lagjacobian) {
2700: PetscInfo2(snes,"Reusing Jacobian/preconditioner because lag is %D and SNES iteration is %D\n",snes->lagjacobian,snes->iter);
2701: PetscObjectTypeCompare((PetscObject)A,MATMFFD,&flag);
2702: if (flag) {
2703: MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
2704: MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
2705: }
2706: return(0);
2707: }
2708: if (snes->npc && snes->npcside== PC_LEFT) {
2709: MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
2710: MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
2711: return(0);
2712: }
2714: PetscLogEventBegin(SNES_JacobianEval,snes,X,A,B);
2715: VecLockReadPush(X);
2716: PetscStackPush("SNES user Jacobian function");
2717: (*sdm->ops->computejacobian)(snes,X,A,B,sdm->jacobianctx);
2718: PetscStackPop;
2719: VecLockReadPop(X);
2720: PetscLogEventEnd(SNES_JacobianEval,snes,X,A,B);
2722: /* attach latest linearization point to the preconditioning matrix */
2723: PetscObjectCompose((PetscObject)B,"__SNES_latest_X",(PetscObject)X);
2725: /* the next line ensures that snes->ksp exists */
2726: SNESGetKSP(snes,&ksp);
2727: if (snes->lagpreconditioner == -2) {
2728: PetscInfo(snes,"Rebuilding preconditioner exactly once since lag is -2\n");
2729: KSPSetReusePreconditioner(snes->ksp,PETSC_FALSE);
2730: snes->lagpreconditioner = -1;
2731: } else if (snes->lagpreconditioner == -1) {
2732: PetscInfo(snes,"Reusing preconditioner because lag is -1\n");
2733: KSPSetReusePreconditioner(snes->ksp,PETSC_TRUE);
2734: } else if (snes->lagpreconditioner > 1 && (snes->iter + snes->pre_iter) % snes->lagpreconditioner) {
2735: PetscInfo2(snes,"Reusing preconditioner because lag is %D and SNES iteration is %D\n",snes->lagpreconditioner,snes->iter);
2736: KSPSetReusePreconditioner(snes->ksp,PETSC_TRUE);
2737: } else {
2738: PetscInfo(snes,"Rebuilding preconditioner\n");
2739: KSPSetReusePreconditioner(snes->ksp,PETSC_FALSE);
2740: }
2742: SNESTestJacobian(snes);
2743: /* make sure user returned a correct Jacobian and preconditioner */
2746: {
2747: PetscBool flag = PETSC_FALSE,flag_draw = PETSC_FALSE,flag_contour = PETSC_FALSE,flag_operator = PETSC_FALSE;
2748: PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject) snes)->options,((PetscObject)snes)->prefix,"-snes_compare_explicit",NULL,NULL,&flag);
2749: PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject) snes)->options,((PetscObject)snes)->prefix,"-snes_compare_explicit_draw",NULL,NULL,&flag_draw);
2750: PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject) snes)->options,((PetscObject)snes)->prefix,"-snes_compare_explicit_draw_contour",NULL,NULL,&flag_contour);
2751: PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject) snes)->options,((PetscObject)snes)->prefix,"-snes_compare_operator",NULL,NULL,&flag_operator);
2752: if (flag || flag_draw || flag_contour) {
2753: Mat Bexp_mine = NULL,Bexp,FDexp;
2754: PetscViewer vdraw,vstdout;
2755: PetscBool flg;
2756: if (flag_operator) {
2757: MatComputeOperator(A,MATAIJ,&Bexp_mine);
2758: Bexp = Bexp_mine;
2759: } else {
2760: /* See if the preconditioning matrix can be viewed and added directly */
2761: PetscObjectBaseTypeCompareAny((PetscObject)B,&flg,MATSEQAIJ,MATMPIAIJ,MATSEQDENSE,MATMPIDENSE,MATSEQBAIJ,MATMPIBAIJ,MATSEQSBAIJ,MATMPIBAIJ,"");
2762: if (flg) Bexp = B;
2763: else {
2764: /* If the "preconditioning" matrix is itself MATSHELL or some other type without direct support */
2765: MatComputeOperator(B,MATAIJ,&Bexp_mine);
2766: Bexp = Bexp_mine;
2767: }
2768: }
2769: MatConvert(Bexp,MATSAME,MAT_INITIAL_MATRIX,&FDexp);
2770: SNESComputeJacobianDefault(snes,X,FDexp,FDexp,NULL);
2771: PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes),&vstdout);
2772: if (flag_draw || flag_contour) {
2773: PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes),NULL,"Explicit Jacobians",PETSC_DECIDE,PETSC_DECIDE,300,300,&vdraw);
2774: if (flag_contour) {PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR);}
2775: } else vdraw = NULL;
2776: PetscViewerASCIIPrintf(vstdout,"Explicit %s\n",flag_operator ? "Jacobian" : "preconditioning Jacobian");
2777: if (flag) {MatView(Bexp,vstdout);}
2778: if (vdraw) {MatView(Bexp,vdraw);}
2779: PetscViewerASCIIPrintf(vstdout,"Finite difference Jacobian\n");
2780: if (flag) {MatView(FDexp,vstdout);}
2781: if (vdraw) {MatView(FDexp,vdraw);}
2782: MatAYPX(FDexp,-1.0,Bexp,SAME_NONZERO_PATTERN);
2783: PetscViewerASCIIPrintf(vstdout,"User-provided matrix minus finite difference Jacobian\n");
2784: if (flag) {MatView(FDexp,vstdout);}
2785: if (vdraw) { /* Always use contour for the difference */
2786: PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR);
2787: MatView(FDexp,vdraw);
2788: PetscViewerPopFormat(vdraw);
2789: }
2790: if (flag_contour) {PetscViewerPopFormat(vdraw);}
2791: PetscViewerDestroy(&vdraw);
2792: MatDestroy(&Bexp_mine);
2793: MatDestroy(&FDexp);
2794: }
2795: }
2796: {
2797: PetscBool flag = PETSC_FALSE,flag_display = PETSC_FALSE,flag_draw = PETSC_FALSE,flag_contour = PETSC_FALSE,flag_threshold = PETSC_FALSE;
2798: PetscReal threshold_atol = PETSC_SQRT_MACHINE_EPSILON,threshold_rtol = 10*PETSC_SQRT_MACHINE_EPSILON;
2799: PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring",NULL,NULL,&flag);
2800: PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_display",NULL,NULL,&flag_display);
2801: PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_draw",NULL,NULL,&flag_draw);
2802: PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_draw_contour",NULL,NULL,&flag_contour);
2803: PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_threshold",NULL,NULL,&flag_threshold);
2804: if (flag_threshold) {
2805: PetscOptionsGetReal(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_threshold_rtol",&threshold_rtol,NULL);
2806: PetscOptionsGetReal(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_threshold_atol",&threshold_atol,NULL);
2807: }
2808: if (flag || flag_display || flag_draw || flag_contour || flag_threshold) {
2809: Mat Bfd;
2810: PetscViewer vdraw,vstdout;
2811: MatColoring coloring;
2812: ISColoring iscoloring;
2813: MatFDColoring matfdcoloring;
2814: PetscErrorCode (*func)(SNES,Vec,Vec,void*);
2815: void *funcctx;
2816: PetscReal norm1,norm2,normmax;
2818: MatDuplicate(B,MAT_DO_NOT_COPY_VALUES,&Bfd);
2819: MatColoringCreate(Bfd,&coloring);
2820: MatColoringSetType(coloring,MATCOLORINGSL);
2821: MatColoringSetFromOptions(coloring);
2822: MatColoringApply(coloring,&iscoloring);
2823: MatColoringDestroy(&coloring);
2824: MatFDColoringCreate(Bfd,iscoloring,&matfdcoloring);
2825: MatFDColoringSetFromOptions(matfdcoloring);
2826: MatFDColoringSetUp(Bfd,iscoloring,matfdcoloring);
2827: ISColoringDestroy(&iscoloring);
2829: /* This method of getting the function is currently unreliable since it doesn't work for DM local functions. */
2830: SNESGetFunction(snes,NULL,&func,&funcctx);
2831: MatFDColoringSetFunction(matfdcoloring,(PetscErrorCode (*)(void))func,funcctx);
2832: PetscObjectSetOptionsPrefix((PetscObject)matfdcoloring,((PetscObject)snes)->prefix);
2833: PetscObjectAppendOptionsPrefix((PetscObject)matfdcoloring,"coloring_");
2834: MatFDColoringSetFromOptions(matfdcoloring);
2835: MatFDColoringApply(Bfd,matfdcoloring,X,snes);
2836: MatFDColoringDestroy(&matfdcoloring);
2838: PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes),&vstdout);
2839: if (flag_draw || flag_contour) {
2840: PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes),NULL,"Colored Jacobians",PETSC_DECIDE,PETSC_DECIDE,300,300,&vdraw);
2841: if (flag_contour) {PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR);}
2842: } else vdraw = NULL;
2843: PetscViewerASCIIPrintf(vstdout,"Explicit preconditioning Jacobian\n");
2844: if (flag_display) {MatView(B,vstdout);}
2845: if (vdraw) {MatView(B,vdraw);}
2846: PetscViewerASCIIPrintf(vstdout,"Colored Finite difference Jacobian\n");
2847: if (flag_display) {MatView(Bfd,vstdout);}
2848: if (vdraw) {MatView(Bfd,vdraw);}
2849: MatAYPX(Bfd,-1.0,B,SAME_NONZERO_PATTERN);
2850: MatNorm(Bfd,NORM_1,&norm1);
2851: MatNorm(Bfd,NORM_FROBENIUS,&norm2);
2852: MatNorm(Bfd,NORM_MAX,&normmax);
2853: PetscViewerASCIIPrintf(vstdout,"User-provided matrix minus finite difference Jacobian, norm1=%g normFrob=%g normmax=%g\n",(double)norm1,(double)norm2,(double)normmax);
2854: if (flag_display) {MatView(Bfd,vstdout);}
2855: if (vdraw) { /* Always use contour for the difference */
2856: PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR);
2857: MatView(Bfd,vdraw);
2858: PetscViewerPopFormat(vdraw);
2859: }
2860: if (flag_contour) {PetscViewerPopFormat(vdraw);}
2862: if (flag_threshold) {
2863: PetscInt bs,rstart,rend,i;
2864: MatGetBlockSize(B,&bs);
2865: MatGetOwnershipRange(B,&rstart,&rend);
2866: for (i=rstart; i<rend; i++) {
2867: const PetscScalar *ba,*ca;
2868: const PetscInt *bj,*cj;
2869: PetscInt bn,cn,j,maxentrycol = -1,maxdiffcol = -1,maxrdiffcol = -1;
2870: PetscReal maxentry = 0,maxdiff = 0,maxrdiff = 0;
2871: MatGetRow(B,i,&bn,&bj,&ba);
2872: MatGetRow(Bfd,i,&cn,&cj,&ca);
2873: if (bn != cn) SETERRQ(((PetscObject)A)->comm,PETSC_ERR_PLIB,"Unexpected different nonzero pattern in -snes_compare_coloring_threshold");
2874: for (j=0; j<bn; j++) {
2875: PetscReal rdiff = PetscAbsScalar(ca[j]) / (threshold_atol + threshold_rtol*PetscAbsScalar(ba[j]));
2876: if (PetscAbsScalar(ba[j]) > PetscAbs(maxentry)) {
2877: maxentrycol = bj[j];
2878: maxentry = PetscRealPart(ba[j]);
2879: }
2880: if (PetscAbsScalar(ca[j]) > PetscAbs(maxdiff)) {
2881: maxdiffcol = bj[j];
2882: maxdiff = PetscRealPart(ca[j]);
2883: }
2884: if (rdiff > maxrdiff) {
2885: maxrdiffcol = bj[j];
2886: maxrdiff = rdiff;
2887: }
2888: }
2889: if (maxrdiff > 1) {
2890: PetscViewerASCIIPrintf(vstdout,"row %D (maxentry=%g at %D, maxdiff=%g at %D, maxrdiff=%g at %D):",i,(double)maxentry,maxentrycol,(double)maxdiff,maxdiffcol,(double)maxrdiff,maxrdiffcol);
2891: for (j=0; j<bn; j++) {
2892: PetscReal rdiff;
2893: rdiff = PetscAbsScalar(ca[j]) / (threshold_atol + threshold_rtol*PetscAbsScalar(ba[j]));
2894: if (rdiff > 1) {
2895: PetscViewerASCIIPrintf(vstdout," (%D,%g:%g)",bj[j],(double)PetscRealPart(ba[j]),(double)PetscRealPart(ca[j]));
2896: }
2897: }
2898: PetscViewerASCIIPrintf(vstdout,"\n",i,maxentry,maxdiff,maxrdiff);
2899: }
2900: MatRestoreRow(B,i,&bn,&bj,&ba);
2901: MatRestoreRow(Bfd,i,&cn,&cj,&ca);
2902: }
2903: }
2904: PetscViewerDestroy(&vdraw);
2905: MatDestroy(&Bfd);
2906: }
2907: }
2908: return(0);
2909: }
2911: /*MC
2912: SNESJacobianFunction - Function used to convey the nonlinear Jacobian of the function to be solved by SNES
2914: Synopsis:
2915: #include "petscsnes.h"
2916: PetscErrorCode SNESJacobianFunction(SNES snes,Vec x,Mat Amat,Mat Pmat,void *ctx);
2918: Collective on snes
2920: Input Parameters:
2921: + x - input vector, the Jacobian is to be computed at this value
2922: - ctx - [optional] user-defined Jacobian context
2924: Output Parameters:
2925: + Amat - the matrix that defines the (approximate) Jacobian
2926: - Pmat - the matrix to be used in constructing the preconditioner, usually the same as Amat.
2928: Level: intermediate
2930: .seealso: SNESSetFunction(), SNESGetFunction(), SNESSetJacobian(), SNESGetJacobian()
2931: M*/
2933: /*@C
2934: SNESSetJacobian - Sets the function to compute Jacobian as well as the
2935: location to store the matrix.
2937: Logically Collective on SNES
2939: Input Parameters:
2940: + snes - the SNES context
2941: . Amat - the matrix that defines the (approximate) Jacobian
2942: . Pmat - the matrix to be used in constructing the preconditioner, usually the same as Amat.
2943: . J - Jacobian evaluation routine (if NULL then SNES retains any previously set value), see SNESJacobianFunction for details
2944: - ctx - [optional] user-defined context for private data for the
2945: Jacobian evaluation routine (may be NULL) (if NULL then SNES retains any previously set value)
2947: Notes:
2948: If the Amat matrix and Pmat matrix are different you must call MatAssemblyBegin/End() on
2949: each matrix.
2951: If you know the operator Amat has a null space you can use MatSetNullSpace() and MatSetTransposeNullSpace() to supply the null
2952: space to Amat and the KSP solvers will automatically use that null space as needed during the solution process.
2954: If using SNESComputeJacobianDefaultColor() to assemble a Jacobian, the ctx argument
2955: must be a MatFDColoring.
2957: Other defect-correction schemes can be used by computing a different matrix in place of the Jacobian. One common
2958: example is to use the "Picard linearization" which only differentiates through the highest order parts of each term.
2960: Level: beginner
2962: .seealso: KSPSetOperators(), SNESSetFunction(), MatMFFDComputeJacobian(), SNESComputeJacobianDefaultColor(), MatStructure, J,
2963: SNESSetPicard(), SNESJacobianFunction
2964: @*/
2965: PetscErrorCode SNESSetJacobian(SNES snes,Mat Amat,Mat Pmat,PetscErrorCode (*J)(SNES,Vec,Mat,Mat,void*),void *ctx)
2966: {
2968: DM dm;
2976: SNESGetDM(snes,&dm);
2977: DMSNESSetJacobian(dm,J,ctx);
2978: if (Amat) {
2979: PetscObjectReference((PetscObject)Amat);
2980: MatDestroy(&snes->jacobian);
2982: snes->jacobian = Amat;
2983: }
2984: if (Pmat) {
2985: PetscObjectReference((PetscObject)Pmat);
2986: MatDestroy(&snes->jacobian_pre);
2988: snes->jacobian_pre = Pmat;
2989: }
2990: return(0);
2991: }
2993: /*@C
2994: SNESGetJacobian - Returns the Jacobian matrix and optionally the user
2995: provided context for evaluating the Jacobian.
2997: Not Collective, but Mat object will be parallel if SNES object is
2999: Input Parameter:
3000: . snes - the nonlinear solver context
3002: Output Parameters:
3003: + Amat - location to stash (approximate) Jacobian matrix (or NULL)
3004: . Pmat - location to stash matrix used to compute the preconditioner (or NULL)
3005: . J - location to put Jacobian function (or NULL), see SNESJacobianFunction for details on its calling sequence
3006: - ctx - location to stash Jacobian ctx (or NULL)
3008: Level: advanced
3010: .seealso: SNESSetJacobian(), SNESComputeJacobian(), SNESJacobianFunction, SNESGetFunction()
3011: @*/
3012: PetscErrorCode SNESGetJacobian(SNES snes,Mat *Amat,Mat *Pmat,PetscErrorCode (**J)(SNES,Vec,Mat,Mat,void*),void **ctx)
3013: {
3015: DM dm;
3016: DMSNES sdm;
3020: if (Amat) *Amat = snes->jacobian;
3021: if (Pmat) *Pmat = snes->jacobian_pre;
3022: SNESGetDM(snes,&dm);
3023: DMGetDMSNES(dm,&sdm);
3024: if (J) *J = sdm->ops->computejacobian;
3025: if (ctx) *ctx = sdm->jacobianctx;
3026: return(0);
3027: }
3029: static PetscErrorCode SNESSetDefaultComputeJacobian(SNES snes)
3030: {
3032: DM dm;
3033: DMSNES sdm;
3036: SNESGetDM(snes,&dm);
3037: DMGetDMSNES(dm,&sdm);
3038: if (!sdm->ops->computejacobian && snes->jacobian_pre) {
3039: DM dm;
3040: PetscBool isdense,ismf;
3042: SNESGetDM(snes,&dm);
3043: PetscObjectTypeCompareAny((PetscObject)snes->jacobian_pre,&isdense,MATSEQDENSE,MATMPIDENSE,MATDENSE,NULL);
3044: PetscObjectTypeCompareAny((PetscObject)snes->jacobian_pre,&ismf,MATMFFD,MATSHELL,NULL);
3045: if (isdense) {
3046: DMSNESSetJacobian(dm,SNESComputeJacobianDefault,NULL);
3047: } else if (!ismf) {
3048: DMSNESSetJacobian(dm,SNESComputeJacobianDefaultColor,NULL);
3049: }
3050: }
3051: return(0);
3052: }
3054: /*@
3055: SNESSetUp - Sets up the internal data structures for the later use
3056: of a nonlinear solver.
3058: Collective on SNES
3060: Input Parameters:
3061: . snes - the SNES context
3063: Notes:
3064: For basic use of the SNES solvers the user need not explicitly call
3065: SNESSetUp(), since these actions will automatically occur during
3066: the call to SNESSolve(). However, if one wishes to control this
3067: phase separately, SNESSetUp() should be called after SNESCreate()
3068: and optional routines of the form SNESSetXXX(), but before SNESSolve().
3070: Level: advanced
3072: .seealso: SNESCreate(), SNESSolve(), SNESDestroy()
3073: @*/
3074: PetscErrorCode SNESSetUp(SNES snes)
3075: {
3077: DM dm;
3078: DMSNES sdm;
3079: SNESLineSearch linesearch, pclinesearch;
3080: void *lsprectx,*lspostctx;
3081: PetscErrorCode (*precheck)(SNESLineSearch,Vec,Vec,PetscBool*,void*);
3082: PetscErrorCode (*postcheck)(SNESLineSearch,Vec,Vec,Vec,PetscBool*,PetscBool*,void*);
3083: PetscErrorCode (*func)(SNES,Vec,Vec,void*);
3084: Vec f,fpc;
3085: void *funcctx;
3086: PetscErrorCode (*jac)(SNES,Vec,Mat,Mat,void*);
3087: void *jacctx,*appctx;
3088: Mat j,jpre;
3092: if (snes->setupcalled) return(0);
3093: PetscLogEventBegin(SNES_Setup,snes,0,0,0);
3095: if (!((PetscObject)snes)->type_name) {
3096: SNESSetType(snes,SNESNEWTONLS);
3097: }
3099: SNESGetFunction(snes,&snes->vec_func,NULL,NULL);
3101: SNESGetDM(snes,&dm);
3102: DMGetDMSNES(dm,&sdm);
3103: if (!sdm->ops->computefunction) SETERRQ(PetscObjectComm((PetscObject)dm),PETSC_ERR_ARG_WRONGSTATE,"Function never provided to SNES object");
3104: SNESSetDefaultComputeJacobian(snes);
3106: if (!snes->vec_func) {
3107: DMCreateGlobalVector(dm,&snes->vec_func);
3108: }
3110: if (!snes->ksp) {
3111: SNESGetKSP(snes, &snes->ksp);
3112: }
3114: if (snes->linesearch) {
3115: SNESGetLineSearch(snes, &snes->linesearch);
3116: SNESLineSearchSetFunction(snes->linesearch,SNESComputeFunction);
3117: }
3119: if (snes->npc && (snes->npcside== PC_LEFT)) {
3120: snes->mf = PETSC_TRUE;
3121: snes->mf_operator = PETSC_FALSE;
3122: }
3124: if (snes->npc) {
3125: /* copy the DM over */
3126: SNESGetDM(snes,&dm);
3127: SNESSetDM(snes->npc,dm);
3129: SNESGetFunction(snes,&f,&func,&funcctx);
3130: VecDuplicate(f,&fpc);
3131: SNESSetFunction(snes->npc,fpc,func,funcctx);
3132: SNESGetJacobian(snes,&j,&jpre,&jac,&jacctx);
3133: SNESSetJacobian(snes->npc,j,jpre,jac,jacctx);
3134: SNESGetApplicationContext(snes,&appctx);
3135: SNESSetApplicationContext(snes->npc,appctx);
3136: VecDestroy(&fpc);
3138: /* copy the function pointers over */
3139: PetscObjectCopyFortranFunctionPointers((PetscObject)snes,(PetscObject)snes->npc);
3141: /* default to 1 iteration */
3142: SNESSetTolerances(snes->npc,0.0,0.0,0.0,1,snes->npc->max_funcs);
3143: if (snes->npcside==PC_RIGHT) {
3144: SNESSetNormSchedule(snes->npc,SNES_NORM_FINAL_ONLY);
3145: } else {
3146: SNESSetNormSchedule(snes->npc,SNES_NORM_NONE);
3147: }
3148: SNESSetFromOptions(snes->npc);
3150: /* copy the line search context over */
3151: if (snes->linesearch && snes->npc->linesearch) {
3152: SNESGetLineSearch(snes,&linesearch);
3153: SNESGetLineSearch(snes->npc,&pclinesearch);
3154: SNESLineSearchGetPreCheck(linesearch,&precheck,&lsprectx);
3155: SNESLineSearchGetPostCheck(linesearch,&postcheck,&lspostctx);
3156: SNESLineSearchSetPreCheck(pclinesearch,precheck,lsprectx);
3157: SNESLineSearchSetPostCheck(pclinesearch,postcheck,lspostctx);
3158: PetscObjectCopyFortranFunctionPointers((PetscObject)linesearch, (PetscObject)pclinesearch);
3159: }
3160: }
3161: if (snes->mf) {
3162: SNESSetUpMatrixFree_Private(snes, snes->mf_operator, snes->mf_version);
3163: }
3164: if (snes->ops->usercompute && !snes->user) {
3165: (*snes->ops->usercompute)(snes,(void**)&snes->user);
3166: }
3168: snes->jac_iter = 0;
3169: snes->pre_iter = 0;
3171: if (snes->ops->setup) {
3172: (*snes->ops->setup)(snes);
3173: }
3175: SNESSetDefaultComputeJacobian(snes);
3177: if (snes->npc && (snes->npcside== PC_LEFT)) {
3178: if (snes->functype == SNES_FUNCTION_PRECONDITIONED) {
3179: if (snes->linesearch){
3180: SNESGetLineSearch(snes,&linesearch);
3181: SNESLineSearchSetFunction(linesearch,SNESComputeFunctionDefaultNPC);
3182: }
3183: }
3184: }
3185: PetscLogEventEnd(SNES_Setup,snes,0,0,0);
3186: snes->setupcalled = PETSC_TRUE;
3187: return(0);
3188: }
3190: /*@
3191: SNESReset - Resets a SNES context to the snessetupcalled = 0 state and removes any allocated Vecs and Mats
3193: Collective on SNES
3195: Input Parameter:
3196: . snes - iterative context obtained from SNESCreate()
3198: Level: intermediate
3200: Notes:
3201: Also calls the application context destroy routine set with SNESSetComputeApplicationContext()
3203: .seealso: SNESCreate(), SNESSetUp(), SNESSolve()
3204: @*/
3205: PetscErrorCode SNESReset(SNES snes)
3206: {
3211: if (snes->ops->userdestroy && snes->user) {
3212: (*snes->ops->userdestroy)((void**)&snes->user);
3213: snes->user = NULL;
3214: }
3215: if (snes->npc) {
3216: SNESReset(snes->npc);
3217: }
3219: if (snes->ops->reset) {
3220: (*snes->ops->reset)(snes);
3221: }
3222: if (snes->ksp) {
3223: KSPReset(snes->ksp);
3224: }
3226: if (snes->linesearch) {
3227: SNESLineSearchReset(snes->linesearch);
3228: }
3230: VecDestroy(&snes->vec_rhs);
3231: VecDestroy(&snes->vec_sol);
3232: VecDestroy(&snes->vec_sol_update);
3233: VecDestroy(&snes->vec_func);
3234: MatDestroy(&snes->jacobian);
3235: MatDestroy(&snes->jacobian_pre);
3236: VecDestroyVecs(snes->nwork,&snes->work);
3237: VecDestroyVecs(snes->nvwork,&snes->vwork);
3239: snes->alwayscomputesfinalresidual = PETSC_FALSE;
3241: snes->nwork = snes->nvwork = 0;
3242: snes->setupcalled = PETSC_FALSE;
3243: return(0);
3244: }
3246: /*@
3247: SNESDestroy - Destroys the nonlinear solver context that was created
3248: with SNESCreate().
3250: Collective on SNES
3252: Input Parameter:
3253: . snes - the SNES context
3255: Level: beginner
3257: .seealso: SNESCreate(), SNESSolve()
3258: @*/
3259: PetscErrorCode SNESDestroy(SNES *snes)
3260: {
3264: if (!*snes) return(0);
3266: if (--((PetscObject)(*snes))->refct > 0) {*snes = NULL; return(0);}
3268: SNESReset((*snes));
3269: SNESDestroy(&(*snes)->npc);
3271: /* if memory was published with SAWs then destroy it */
3272: PetscObjectSAWsViewOff((PetscObject)*snes);
3273: if ((*snes)->ops->destroy) {(*((*snes))->ops->destroy)((*snes));}
3275: if ((*snes)->dm) {DMCoarsenHookRemove((*snes)->dm,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,*snes);}
3276: DMDestroy(&(*snes)->dm);
3277: KSPDestroy(&(*snes)->ksp);
3278: SNESLineSearchDestroy(&(*snes)->linesearch);
3280: PetscFree((*snes)->kspconvctx);
3281: if ((*snes)->ops->convergeddestroy) {
3282: (*(*snes)->ops->convergeddestroy)((*snes)->cnvP);
3283: }
3284: if ((*snes)->conv_hist_alloc) {
3285: PetscFree2((*snes)->conv_hist,(*snes)->conv_hist_its);
3286: }
3287: SNESMonitorCancel((*snes));
3288: PetscHeaderDestroy(snes);
3289: return(0);
3290: }
3292: /* ----------- Routines to set solver parameters ---------- */
3294: /*@
3295: SNESSetLagPreconditioner - Determines when the preconditioner is rebuilt in the nonlinear solve.
3297: Logically Collective on SNES
3299: Input Parameters:
3300: + snes - the SNES context
3301: - lag - -1 indicates NEVER rebuild, 1 means rebuild every time the Jacobian is computed within a single nonlinear solve, 2 means every second time
3302: the Jacobian is built etc. -2 indicates rebuild preconditioner at next chance but then never rebuild after that
3304: Options Database Keys:
3305: + -snes_lag_jacobian_persists <true,false> - sets the persistence
3306: . -snes_lag_jacobian <-2,1,2,...> - sets the lag
3307: . -snes_lag_preconditioner_persists <true,false> - sets the persistence
3308: - -snes_lag_preconditioner <-2,1,2,...> - sets the lag
3310: Notes:
3311: The default is 1
3312: The preconditioner is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1 or SNESSetLagPreconditionerPersists() was called
3313: If -1 is used before the very first nonlinear solve the preconditioner is still built because there is no previous preconditioner to use
3315: Level: intermediate
3317: .seealso: SNESSetTrustRegionTolerance(), SNESGetLagPreconditioner(), SNESSetLagJacobian(), SNESGetLagJacobian(), SNESSetLagPreconditionerPersists(),
3318: SNESSetLagJacobianPersists()
3320: @*/
3321: PetscErrorCode SNESSetLagPreconditioner(SNES snes,PetscInt lag)
3322: {
3325: if (lag < -2) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag must be -2, -1, 1 or greater");
3326: if (!lag) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag cannot be 0");
3328: snes->lagpreconditioner = lag;
3329: return(0);
3330: }
3332: /*@
3333: SNESSetGridSequence - sets the number of steps of grid sequencing that SNES does
3335: Logically Collective on SNES
3337: Input Parameters:
3338: + snes - the SNES context
3339: - steps - the number of refinements to do, defaults to 0
3341: Options Database Keys:
3342: . -snes_grid_sequence <steps>
3344: Level: intermediate
3346: Notes:
3347: Use SNESGetSolution() to extract the fine grid solution after grid sequencing.
3349: .seealso: SNESSetTrustRegionTolerance(), SNESGetLagPreconditioner(), SNESSetLagJacobian(), SNESGetLagJacobian(), SNESGetGridSequence()
3351: @*/
3352: PetscErrorCode SNESSetGridSequence(SNES snes,PetscInt steps)
3353: {
3357: snes->gridsequence = steps;
3358: return(0);
3359: }
3361: /*@
3362: SNESGetGridSequence - gets the number of steps of grid sequencing that SNES does
3364: Logically Collective on SNES
3366: Input Parameter:
3367: . snes - the SNES context
3369: Output Parameter:
3370: . steps - the number of refinements to do, defaults to 0
3372: Options Database Keys:
3373: . -snes_grid_sequence <steps>
3375: Level: intermediate
3377: Notes:
3378: Use SNESGetSolution() to extract the fine grid solution after grid sequencing.
3380: .seealso: SNESSetTrustRegionTolerance(), SNESGetLagPreconditioner(), SNESSetLagJacobian(), SNESGetLagJacobian(), SNESSetGridSequence()
3382: @*/
3383: PetscErrorCode SNESGetGridSequence(SNES snes,PetscInt *steps)
3384: {
3387: *steps = snes->gridsequence;
3388: return(0);
3389: }
3391: /*@
3392: SNESGetLagPreconditioner - Indicates how often the preconditioner is rebuilt
3394: Not Collective
3396: Input Parameter:
3397: . snes - the SNES context
3399: Output Parameter:
3400: . lag - -1 indicates NEVER rebuild, 1 means rebuild every time the Jacobian is computed within a single nonlinear solve, 2 means every second time
3401: the Jacobian is built etc. -2 indicates rebuild preconditioner at next chance but then never rebuild after that
3403: Options Database Keys:
3404: + -snes_lag_jacobian_persists <true,false> - sets the persistence
3405: . -snes_lag_jacobian <-2,1,2,...> - sets the lag
3406: . -snes_lag_preconditioner_persists <true,false> - sets the persistence
3407: - -snes_lag_preconditioner <-2,1,2,...> - sets the lag
3409: Notes:
3410: The default is 1
3411: The preconditioner is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1
3413: Level: intermediate
3415: .seealso: SNESSetTrustRegionTolerance(), SNESSetLagPreconditioner(), SNESSetLagJacobianPersists(), SNESSetLagPreconditionerPersists()
3417: @*/
3418: PetscErrorCode SNESGetLagPreconditioner(SNES snes,PetscInt *lag)
3419: {
3422: *lag = snes->lagpreconditioner;
3423: return(0);
3424: }
3426: /*@
3427: SNESSetLagJacobian - Determines when the Jacobian is rebuilt in the nonlinear solve. See SNESSetLagPreconditioner() for determining how
3428: often the preconditioner is rebuilt.
3430: Logically Collective on SNES
3432: Input Parameters:
3433: + snes - the SNES context
3434: - lag - -1 indicates NEVER rebuild, 1 means rebuild every time the Jacobian is computed within a single nonlinear solve, 2 means every second time
3435: the Jacobian is built etc. -2 means rebuild at next chance but then never again
3437: Options Database Keys:
3438: + -snes_lag_jacobian_persists <true,false> - sets the persistence
3439: . -snes_lag_jacobian <-2,1,2,...> - sets the lag
3440: . -snes_lag_preconditioner_persists <true,false> - sets the persistence
3441: - -snes_lag_preconditioner <-2,1,2,...> - sets the lag.
3443: Notes:
3444: The default is 1
3445: The Jacobian is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1
3446: If -1 is used before the very first nonlinear solve the CODE WILL FAIL! because no Jacobian is used, use -2 to indicate you want it recomputed
3447: at the next Newton step but never again (unless it is reset to another value)
3449: Level: intermediate
3451: .seealso: SNESSetTrustRegionTolerance(), SNESGetLagPreconditioner(), SNESSetLagPreconditioner(), SNESGetLagJacobianPersists(), SNESSetLagPreconditionerPersists()
3453: @*/
3454: PetscErrorCode SNESSetLagJacobian(SNES snes,PetscInt lag)
3455: {
3458: if (lag < -2) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag must be -2, -1, 1 or greater");
3459: if (!lag) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag cannot be 0");
3461: snes->lagjacobian = lag;
3462: return(0);
3463: }
3465: /*@
3466: SNESGetLagJacobian - Indicates how often the Jacobian is rebuilt. See SNESGetLagPreconditioner() to determine when the preconditioner is rebuilt
3468: Not Collective
3470: Input Parameter:
3471: . snes - the SNES context
3473: Output Parameter:
3474: . lag - -1 indicates NEVER rebuild, 1 means rebuild every time the Jacobian is computed within a single nonlinear solve, 2 means every second time
3475: the Jacobian is built etc.
3477: Notes:
3478: The default is 1
3479: The jacobian is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1 or SNESSetLagJacobianPersists() was called.
3481: Level: intermediate
3483: .seealso: SNESSetTrustRegionTolerance(), SNESSetLagJacobian(), SNESSetLagPreconditioner(), SNESGetLagPreconditioner(), SNESSetLagJacobianPersists(), SNESSetLagPreconditionerPersists()
3485: @*/
3486: PetscErrorCode SNESGetLagJacobian(SNES snes,PetscInt *lag)
3487: {
3490: *lag = snes->lagjacobian;
3491: return(0);
3492: }
3494: /*@
3495: SNESSetLagJacobianPersists - Set whether or not the Jacobian lagging persists through multiple solves
3497: Logically collective on SNES
3499: Input Parameter:
3500: + snes - the SNES context
3501: - flg - jacobian lagging persists if true
3503: Options Database Keys:
3504: + -snes_lag_jacobian_persists <true,false> - sets the persistence
3505: . -snes_lag_jacobian <-2,1,2,...> - sets the lag
3506: . -snes_lag_preconditioner_persists <true,false> - sets the persistence
3507: - -snes_lag_preconditioner <-2,1,2,...> - sets the lag
3510: Notes:
3511: This is useful both for nonlinear preconditioning, where it's appropriate to have the Jacobian be stale by
3512: several solves, and for implicit time-stepping, where Jacobian lagging in the inner nonlinear solve over several
3513: timesteps may present huge efficiency gains.
3515: Level: developer
3517: .seealso: SNESSetLagPreconditionerPersists(), SNESSetLagJacobian(), SNESGetLagJacobian(), SNESGetNPC(), SNESSetLagJacobianPersists()
3519: @*/
3520: PetscErrorCode SNESSetLagJacobianPersists(SNES snes,PetscBool flg)
3521: {
3525: snes->lagjac_persist = flg;
3526: return(0);
3527: }
3529: /*@
3530: SNESSetLagPreconditionerPersists - Set whether or not the preconditioner lagging persists through multiple solves
3532: Logically Collective on SNES
3534: Input Parameter:
3535: + snes - the SNES context
3536: - flg - preconditioner lagging persists if true
3538: Options Database Keys:
3539: + -snes_lag_jacobian_persists <true,false> - sets the persistence
3540: . -snes_lag_jacobian <-2,1,2,...> - sets the lag
3541: . -snes_lag_preconditioner_persists <true,false> - sets the persistence
3542: - -snes_lag_preconditioner <-2,1,2,...> - sets the lag
3544: Notes:
3545: This is useful both for nonlinear preconditioning, where it's appropriate to have the preconditioner be stale
3546: by several solves, and for implicit time-stepping, where preconditioner lagging in the inner nonlinear solve over
3547: several timesteps may present huge efficiency gains.
3549: Level: developer
3551: .seealso: SNESSetLagJacobianPersists(), SNESSetLagJacobian(), SNESGetLagJacobian(), SNESGetNPC(), SNESSetLagPreconditioner()
3553: @*/
3554: PetscErrorCode SNESSetLagPreconditionerPersists(SNES snes,PetscBool flg)
3555: {
3559: snes->lagpre_persist = flg;
3560: return(0);
3561: }
3563: /*@
3564: SNESSetForceIteration - force SNESSolve() to take at least one iteration regardless of the initial residual norm
3566: Logically Collective on SNES
3568: Input Parameters:
3569: + snes - the SNES context
3570: - force - PETSC_TRUE require at least one iteration
3572: Options Database Keys:
3573: . -snes_force_iteration <force> - Sets forcing an iteration
3575: Notes:
3576: This is used sometimes with TS to prevent TS from detecting a false steady state solution
3578: Level: intermediate
3580: .seealso: SNESSetTrustRegionTolerance(), SNESSetDivergenceTolerance()
3581: @*/
3582: PetscErrorCode SNESSetForceIteration(SNES snes,PetscBool force)
3583: {
3586: snes->forceiteration = force;
3587: return(0);
3588: }
3590: /*@
3591: SNESGetForceIteration - Whether or not to force SNESSolve() take at least one iteration regardless of the initial residual norm
3593: Logically Collective on SNES
3595: Input Parameters:
3596: . snes - the SNES context
3598: Output Parameter:
3599: . force - PETSC_TRUE requires at least one iteration.
3601: Level: intermediate
3603: .seealso: SNESSetForceIteration(), SNESSetTrustRegionTolerance(), SNESSetDivergenceTolerance()
3604: @*/
3605: PetscErrorCode SNESGetForceIteration(SNES snes,PetscBool *force)
3606: {
3609: *force = snes->forceiteration;
3610: return(0);
3611: }
3613: /*@
3614: SNESSetTolerances - Sets various parameters used in convergence tests.
3616: Logically Collective on SNES
3618: Input Parameters:
3619: + snes - the SNES context
3620: . abstol - absolute convergence tolerance
3621: . rtol - relative convergence tolerance
3622: . stol - convergence tolerance in terms of the norm of the change in the solution between steps, || delta x || < stol*|| x ||
3623: . maxit - maximum number of iterations
3624: - maxf - maximum number of function evaluations (-1 indicates no limit)
3626: Options Database Keys:
3627: + -snes_atol <abstol> - Sets abstol
3628: . -snes_rtol <rtol> - Sets rtol
3629: . -snes_stol <stol> - Sets stol
3630: . -snes_max_it <maxit> - Sets maxit
3631: - -snes_max_funcs <maxf> - Sets maxf
3633: Notes:
3634: The default maximum number of iterations is 50.
3635: The default maximum number of function evaluations is 1000.
3637: Level: intermediate
3639: .seealso: SNESSetTrustRegionTolerance(), SNESSetDivergenceTolerance(), SNESSetForceIteration()
3640: @*/
3641: PetscErrorCode SNESSetTolerances(SNES snes,PetscReal abstol,PetscReal rtol,PetscReal stol,PetscInt maxit,PetscInt maxf)
3642: {
3651: if (abstol != PETSC_DEFAULT) {
3652: if (abstol < 0.0) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Absolute tolerance %g must be non-negative",(double)abstol);
3653: snes->abstol = abstol;
3654: }
3655: if (rtol != PETSC_DEFAULT) {
3656: if (rtol < 0.0 || 1.0 <= rtol) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Relative tolerance %g must be non-negative and less than 1.0",(double)rtol);
3657: snes->rtol = rtol;
3658: }
3659: if (stol != PETSC_DEFAULT) {
3660: if (stol < 0.0) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Step tolerance %g must be non-negative",(double)stol);
3661: snes->stol = stol;
3662: }
3663: if (maxit != PETSC_DEFAULT) {
3664: if (maxit < 0) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of iterations %D must be non-negative",maxit);
3665: snes->max_its = maxit;
3666: }
3667: if (maxf != PETSC_DEFAULT) {
3668: if (maxf < -1) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of function evaluations %D must be -1 or nonnegative",maxf);
3669: snes->max_funcs = maxf;
3670: }
3671: snes->tolerancesset = PETSC_TRUE;
3672: return(0);
3673: }
3675: /*@
3676: SNESSetDivergenceTolerance - Sets the divergence tolerance used for the SNES divergence test.
3678: Logically Collective on SNES
3680: Input Parameters:
3681: + snes - the SNES context
3682: - divtol - the divergence tolerance. Use -1 to deactivate the test.
3684: Options Database Keys:
3685: . -snes_divergence_tolerance <divtol> - Sets divtol
3687: Notes:
3688: The default divergence tolerance is 1e4.
3690: Level: intermediate
3692: .seealso: SNESSetTolerances(), SNESGetDivergenceTolerance
3693: @*/
3694: PetscErrorCode SNESSetDivergenceTolerance(SNES snes,PetscReal divtol)
3695: {
3700: if (divtol != PETSC_DEFAULT) {
3701: snes->divtol = divtol;
3702: }
3703: else {
3704: snes->divtol = 1.0e4;
3705: }
3706: return(0);
3707: }
3709: /*@
3710: SNESGetTolerances - Gets various parameters used in convergence tests.
3712: Not Collective
3714: Input Parameters:
3715: + snes - the SNES context
3716: . atol - absolute convergence tolerance
3717: . rtol - relative convergence tolerance
3718: . stol - convergence tolerance in terms of the norm
3719: of the change in the solution between steps
3720: . maxit - maximum number of iterations
3721: - maxf - maximum number of function evaluations
3723: Notes:
3724: The user can specify NULL for any parameter that is not needed.
3726: Level: intermediate
3728: .seealso: SNESSetTolerances()
3729: @*/
3730: PetscErrorCode SNESGetTolerances(SNES snes,PetscReal *atol,PetscReal *rtol,PetscReal *stol,PetscInt *maxit,PetscInt *maxf)
3731: {
3734: if (atol) *atol = snes->abstol;
3735: if (rtol) *rtol = snes->rtol;
3736: if (stol) *stol = snes->stol;
3737: if (maxit) *maxit = snes->max_its;
3738: if (maxf) *maxf = snes->max_funcs;
3739: return(0);
3740: }
3742: /*@
3743: SNESGetDivergenceTolerance - Gets divergence tolerance used in divergence test.
3745: Not Collective
3747: Input Parameters:
3748: + snes - the SNES context
3749: - divtol - divergence tolerance
3751: Level: intermediate
3753: .seealso: SNESSetDivergenceTolerance()
3754: @*/
3755: PetscErrorCode SNESGetDivergenceTolerance(SNES snes,PetscReal *divtol)
3756: {
3759: if (divtol) *divtol = snes->divtol;
3760: return(0);
3761: }
3763: /*@
3764: SNESSetTrustRegionTolerance - Sets the trust region parameter tolerance.
3766: Logically Collective on SNES
3768: Input Parameters:
3769: + snes - the SNES context
3770: - tol - tolerance
3772: Options Database Key:
3773: . -snes_trtol <tol> - Sets tol
3775: Level: intermediate
3777: .seealso: SNESSetTolerances()
3778: @*/
3779: PetscErrorCode SNESSetTrustRegionTolerance(SNES snes,PetscReal tol)
3780: {
3784: snes->deltatol = tol;
3785: return(0);
3786: }
3788: /*
3789: Duplicate the lg monitors for SNES from KSP; for some reason with
3790: dynamic libraries things don't work under Sun4 if we just use
3791: macros instead of functions
3792: */
3793: PetscErrorCode SNESMonitorLGResidualNorm(SNES snes,PetscInt it,PetscReal norm,void *ctx)
3794: {
3799: KSPMonitorLGResidualNorm((KSP)snes,it,norm,ctx);
3800: return(0);
3801: }
3803: PetscErrorCode SNESMonitorLGCreate(MPI_Comm comm,const char host[],const char label[],int x,int y,int m,int n,PetscDrawLG *lgctx)
3804: {
3808: KSPMonitorLGResidualNormCreate(comm,host,label,x,y,m,n,lgctx);
3809: return(0);
3810: }
3812: PETSC_INTERN PetscErrorCode SNESMonitorRange_Private(SNES,PetscInt,PetscReal*);
3814: PetscErrorCode SNESMonitorLGRange(SNES snes,PetscInt n,PetscReal rnorm,void *monctx)
3815: {
3816: PetscDrawLG lg;
3817: PetscErrorCode ierr;
3818: PetscReal x,y,per;
3819: PetscViewer v = (PetscViewer)monctx;
3820: static PetscReal prev; /* should be in the context */
3821: PetscDraw draw;
3825: PetscViewerDrawGetDrawLG(v,0,&lg);
3826: if (!n) {PetscDrawLGReset(lg);}
3827: PetscDrawLGGetDraw(lg,&draw);
3828: PetscDrawSetTitle(draw,"Residual norm");
3829: x = (PetscReal)n;
3830: if (rnorm > 0.0) y = PetscLog10Real(rnorm);
3831: else y = -15.0;
3832: PetscDrawLGAddPoint(lg,&x,&y);
3833: if (n < 20 || !(n % 5) || snes->reason) {
3834: PetscDrawLGDraw(lg);
3835: PetscDrawLGSave(lg);
3836: }
3838: PetscViewerDrawGetDrawLG(v,1,&lg);
3839: if (!n) {PetscDrawLGReset(lg);}
3840: PetscDrawLGGetDraw(lg,&draw);
3841: PetscDrawSetTitle(draw,"% elemts > .2*max elemt");
3842: SNESMonitorRange_Private(snes,n,&per);
3843: x = (PetscReal)n;
3844: y = 100.0*per;
3845: PetscDrawLGAddPoint(lg,&x,&y);
3846: if (n < 20 || !(n % 5) || snes->reason) {
3847: PetscDrawLGDraw(lg);
3848: PetscDrawLGSave(lg);
3849: }
3851: PetscViewerDrawGetDrawLG(v,2,&lg);
3852: if (!n) {prev = rnorm;PetscDrawLGReset(lg);}
3853: PetscDrawLGGetDraw(lg,&draw);
3854: PetscDrawSetTitle(draw,"(norm -oldnorm)/oldnorm");
3855: x = (PetscReal)n;
3856: y = (prev - rnorm)/prev;
3857: PetscDrawLGAddPoint(lg,&x,&y);
3858: if (n < 20 || !(n % 5) || snes->reason) {
3859: PetscDrawLGDraw(lg);
3860: PetscDrawLGSave(lg);
3861: }
3863: PetscViewerDrawGetDrawLG(v,3,&lg);
3864: if (!n) {PetscDrawLGReset(lg);}
3865: PetscDrawLGGetDraw(lg,&draw);
3866: PetscDrawSetTitle(draw,"(norm -oldnorm)/oldnorm*(% > .2 max)");
3867: x = (PetscReal)n;
3868: y = (prev - rnorm)/(prev*per);
3869: if (n > 2) { /*skip initial crazy value */
3870: PetscDrawLGAddPoint(lg,&x,&y);
3871: }
3872: if (n < 20 || !(n % 5) || snes->reason) {
3873: PetscDrawLGDraw(lg);
3874: PetscDrawLGSave(lg);
3875: }
3876: prev = rnorm;
3877: return(0);
3878: }
3880: /*@
3881: SNESMonitor - runs the user provided monitor routines, if they exist
3883: Collective on SNES
3885: Input Parameters:
3886: + snes - nonlinear solver context obtained from SNESCreate()
3887: . iter - iteration number
3888: - rnorm - relative norm of the residual
3890: Notes:
3891: This routine is called by the SNES implementations.
3892: It does not typically need to be called by the user.
3894: Level: developer
3896: .seealso: SNESMonitorSet()
3897: @*/
3898: PetscErrorCode SNESMonitor(SNES snes,PetscInt iter,PetscReal rnorm)
3899: {
3901: PetscInt i,n = snes->numbermonitors;
3904: VecLockReadPush(snes->vec_sol);
3905: for (i=0; i<n; i++) {
3906: (*snes->monitor[i])(snes,iter,rnorm,snes->monitorcontext[i]);
3907: }
3908: VecLockReadPop(snes->vec_sol);
3909: return(0);
3910: }
3912: /* ------------ Routines to set performance monitoring options ----------- */
3914: /*MC
3915: SNESMonitorFunction - functional form passed to SNESMonitorSet() to monitor convergence of nonlinear solver
3917: Synopsis:
3918: #include <petscsnes.h>
3919: $ PetscErrorCode SNESMonitorFunction(SNES snes,PetscInt its, PetscReal norm,void *mctx)
3921: Collective on snes
3923: Input Parameters:
3924: + snes - the SNES context
3925: . its - iteration number
3926: . norm - 2-norm function value (may be estimated)
3927: - mctx - [optional] monitoring context
3929: Level: advanced
3931: .seealso: SNESMonitorSet(), SNESMonitorGet()
3932: M*/
3934: /*@C
3935: SNESMonitorSet - Sets an ADDITIONAL function that is to be used at every
3936: iteration of the nonlinear solver to display the iteration's
3937: progress.
3939: Logically Collective on SNES
3941: Input Parameters:
3942: + snes - the SNES context
3943: . f - the monitor function, see SNESMonitorFunction for the calling sequence
3944: . mctx - [optional] user-defined context for private data for the
3945: monitor routine (use NULL if no context is desired)
3946: - monitordestroy - [optional] routine that frees monitor context
3947: (may be NULL)
3949: Options Database Keys:
3950: + -snes_monitor - sets SNESMonitorDefault()
3951: . -snes_monitor_lg_residualnorm - sets line graph monitor,
3952: uses SNESMonitorLGCreate()
3953: - -snes_monitor_cancel - cancels all monitors that have
3954: been hardwired into a code by
3955: calls to SNESMonitorSet(), but
3956: does not cancel those set via
3957: the options database.
3959: Notes:
3960: Several different monitoring routines may be set by calling
3961: SNESMonitorSet() multiple times; all will be called in the
3962: order in which they were set.
3964: Fortran Notes:
3965: Only a single monitor function can be set for each SNES object
3967: Level: intermediate
3969: .seealso: SNESMonitorDefault(), SNESMonitorCancel(), SNESMonitorFunction
3970: @*/
3971: PetscErrorCode SNESMonitorSet(SNES snes,PetscErrorCode (*f)(SNES,PetscInt,PetscReal,void*),void *mctx,PetscErrorCode (*monitordestroy)(void**))
3972: {
3973: PetscInt i;
3975: PetscBool identical;
3979: for (i=0; i<snes->numbermonitors;i++) {
3980: PetscMonitorCompare((PetscErrorCode (*)(void))f,mctx,monitordestroy,(PetscErrorCode (*)(void))snes->monitor[i],snes->monitorcontext[i],snes->monitordestroy[i],&identical);
3981: if (identical) return(0);
3982: }
3983: if (snes->numbermonitors >= MAXSNESMONITORS) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Too many monitors set");
3984: snes->monitor[snes->numbermonitors] = f;
3985: snes->monitordestroy[snes->numbermonitors] = monitordestroy;
3986: snes->monitorcontext[snes->numbermonitors++] = (void*)mctx;
3987: return(0);
3988: }
3990: /*@
3991: SNESMonitorCancel - Clears all the monitor functions for a SNES object.
3993: Logically Collective on SNES
3995: Input Parameters:
3996: . snes - the SNES context
3998: Options Database Key:
3999: . -snes_monitor_cancel - cancels all monitors that have been hardwired
4000: into a code by calls to SNESMonitorSet(), but does not cancel those
4001: set via the options database
4003: Notes:
4004: There is no way to clear one specific monitor from a SNES object.
4006: Level: intermediate
4008: .seealso: SNESMonitorDefault(), SNESMonitorSet()
4009: @*/
4010: PetscErrorCode SNESMonitorCancel(SNES snes)
4011: {
4013: PetscInt i;
4017: for (i=0; i<snes->numbermonitors; i++) {
4018: if (snes->monitordestroy[i]) {
4019: (*snes->monitordestroy[i])(&snes->monitorcontext[i]);
4020: }
4021: }
4022: snes->numbermonitors = 0;
4023: return(0);
4024: }
4026: /*MC
4027: SNESConvergenceTestFunction - functional form used for testing of convergence of nonlinear solver
4029: Synopsis:
4030: #include <petscsnes.h>
4031: $ PetscErrorCode SNESConvergenceTest(SNES snes,PetscInt it,PetscReal xnorm,PetscReal gnorm,PetscReal f,SNESConvergedReason *reason,void *cctx)
4033: Collective on snes
4035: Input Parameters:
4036: + snes - the SNES context
4037: . it - current iteration (0 is the first and is before any Newton step)
4038: . xnorm - 2-norm of current iterate
4039: . gnorm - 2-norm of current step
4040: . f - 2-norm of function
4041: - cctx - [optional] convergence context
4043: Output Parameter:
4044: . reason - reason for convergence/divergence, only needs to be set when convergence or divergence is detected
4046: Level: intermediate
4048: .seealso: SNESSetConvergenceTest(), SNESGetConvergenceTest()
4049: M*/
4051: /*@C
4052: SNESSetConvergenceTest - Sets the function that is to be used
4053: to test for convergence of the nonlinear iterative solution.
4055: Logically Collective on SNES
4057: Input Parameters:
4058: + snes - the SNES context
4059: . SNESConvergenceTestFunction - routine to test for convergence
4060: . cctx - [optional] context for private data for the convergence routine (may be NULL)
4061: - destroy - [optional] destructor for the context (may be NULL; PETSC_NULL_FUNCTION in Fortran)
4063: Level: advanced
4065: .seealso: SNESConvergedDefault(), SNESConvergedSkip(), SNESConvergenceTestFunction
4066: @*/
4067: PetscErrorCode SNESSetConvergenceTest(SNES snes,PetscErrorCode (*SNESConvergenceTestFunction)(SNES,PetscInt,PetscReal,PetscReal,PetscReal,SNESConvergedReason*,void*),void *cctx,PetscErrorCode (*destroy)(void*))
4068: {
4073: if (!SNESConvergenceTestFunction) SNESConvergenceTestFunction = SNESConvergedSkip;
4074: if (snes->ops->convergeddestroy) {
4075: (*snes->ops->convergeddestroy)(snes->cnvP);
4076: }
4077: snes->ops->converged = SNESConvergenceTestFunction;
4078: snes->ops->convergeddestroy = destroy;
4079: snes->cnvP = cctx;
4080: return(0);
4081: }
4083: /*@
4084: SNESGetConvergedReason - Gets the reason the SNES iteration was stopped.
4086: Not Collective
4088: Input Parameter:
4089: . snes - the SNES context
4091: Output Parameter:
4092: . reason - negative value indicates diverged, positive value converged, see SNESConvergedReason or the
4093: manual pages for the individual convergence tests for complete lists
4095: Options Database:
4096: . -snes_converged_reason - prints the reason to standard out
4098: Level: intermediate
4100: Notes:
4101: Should only be called after the call the SNESSolve() is complete, if it is called earlier it returns the value SNES__CONVERGED_ITERATING.
4103: .seealso: SNESSetConvergenceTest(), SNESSetConvergedReason(), SNESConvergedReason
4104: @*/
4105: PetscErrorCode SNESGetConvergedReason(SNES snes,SNESConvergedReason *reason)
4106: {
4110: *reason = snes->reason;
4111: return(0);
4112: }
4114: /*@
4115: SNESSetConvergedReason - Sets the reason the SNES iteration was stopped.
4117: Not Collective
4119: Input Parameters:
4120: + snes - the SNES context
4121: - reason - negative value indicates diverged, positive value converged, see SNESConvergedReason or the
4122: manual pages for the individual convergence tests for complete lists
4124: Level: intermediate
4126: .seealso: SNESGetConvergedReason(), SNESSetConvergenceTest(), SNESConvergedReason
4127: @*/
4128: PetscErrorCode SNESSetConvergedReason(SNES snes,SNESConvergedReason reason)
4129: {
4132: snes->reason = reason;
4133: return(0);
4134: }
4136: /*@
4137: SNESSetConvergenceHistory - Sets the array used to hold the convergence history.
4139: Logically Collective on SNES
4141: Input Parameters:
4142: + snes - iterative context obtained from SNESCreate()
4143: . a - array to hold history, this array will contain the function norms computed at each step
4144: . its - integer array holds the number of linear iterations for each solve.
4145: . na - size of a and its
4146: - reset - PETSC_TRUE indicates each new nonlinear solve resets the history counter to zero,
4147: else it continues storing new values for new nonlinear solves after the old ones
4149: Notes:
4150: If 'a' and 'its' are NULL then space is allocated for the history. If 'na' PETSC_DECIDE or PETSC_DEFAULT then a
4151: default array of length 10000 is allocated.
4153: This routine is useful, e.g., when running a code for purposes
4154: of accurate performance monitoring, when no I/O should be done
4155: during the section of code that is being timed.
4157: Level: intermediate
4159: .seealso: SNESGetConvergenceHistory()
4161: @*/
4162: PetscErrorCode SNESSetConvergenceHistory(SNES snes,PetscReal a[],PetscInt its[],PetscInt na,PetscBool reset)
4163: {
4170: if (!a) {
4171: if (na == PETSC_DECIDE || na == PETSC_DEFAULT) na = 1000;
4172: PetscCalloc2(na,&a,na,&its);
4173: snes->conv_hist_alloc = PETSC_TRUE;
4174: }
4175: snes->conv_hist = a;
4176: snes->conv_hist_its = its;
4177: snes->conv_hist_max = na;
4178: snes->conv_hist_len = 0;
4179: snes->conv_hist_reset = reset;
4180: return(0);
4181: }
4183: #if defined(PETSC_HAVE_MATLAB_ENGINE)
4184: #include <engine.h> /* MATLAB include file */
4185: #include <mex.h> /* MATLAB include file */
4187: PETSC_EXTERN mxArray *SNESGetConvergenceHistoryMatlab(SNES snes)
4188: {
4189: mxArray *mat;
4190: PetscInt i;
4191: PetscReal *ar;
4194: mat = mxCreateDoubleMatrix(snes->conv_hist_len,1,mxREAL);
4195: ar = (PetscReal*) mxGetData(mat);
4196: for (i=0; i<snes->conv_hist_len; i++) ar[i] = snes->conv_hist[i];
4197: PetscFunctionReturn(mat);
4198: }
4199: #endif
4201: /*@C
4202: SNESGetConvergenceHistory - Gets the array used to hold the convergence history.
4204: Not Collective
4206: Input Parameter:
4207: . snes - iterative context obtained from SNESCreate()
4209: Output Parameters:
4210: + a - array to hold history
4211: . its - integer array holds the number of linear iterations (or
4212: negative if not converged) for each solve.
4213: - na - size of a and its
4215: Notes:
4216: The calling sequence for this routine in Fortran is
4217: $ call SNESGetConvergenceHistory(SNES snes, integer na, integer ierr)
4219: This routine is useful, e.g., when running a code for purposes
4220: of accurate performance monitoring, when no I/O should be done
4221: during the section of code that is being timed.
4223: Level: intermediate
4225: .seealso: SNESSetConvergenceHistory()
4227: @*/
4228: PetscErrorCode SNESGetConvergenceHistory(SNES snes,PetscReal *a[],PetscInt *its[],PetscInt *na)
4229: {
4232: if (a) *a = snes->conv_hist;
4233: if (its) *its = snes->conv_hist_its;
4234: if (na) *na = snes->conv_hist_len;
4235: return(0);
4236: }
4238: /*@C
4239: SNESSetUpdate - Sets the general-purpose update function called
4240: at the beginning of every iteration of the nonlinear solve. Specifically
4241: it is called just before the Jacobian is "evaluated".
4243: Logically Collective on SNES
4245: Input Parameters:
4246: + snes - The nonlinear solver context
4247: - func - The function
4249: Calling sequence of func:
4250: $ func (SNES snes, PetscInt step);
4252: . step - The current step of the iteration
4254: Level: advanced
4256: Note: This is NOT what one uses to update the ghost points before a function evaluation, that should be done at the beginning of your FormFunction()
4257: This is not used by most users.
4259: .seealso SNESSetJacobian(), SNESSolve()
4260: @*/
4261: PetscErrorCode SNESSetUpdate(SNES snes, PetscErrorCode (*func)(SNES, PetscInt))
4262: {
4265: snes->ops->update = func;
4266: return(0);
4267: }
4269: /*
4270: SNESScaleStep_Private - Scales a step so that its length is less than the
4271: positive parameter delta.
4273: Input Parameters:
4274: + snes - the SNES context
4275: . y - approximate solution of linear system
4276: . fnorm - 2-norm of current function
4277: - delta - trust region size
4279: Output Parameters:
4280: + gpnorm - predicted function norm at the new point, assuming local
4281: linearization. The value is zero if the step lies within the trust
4282: region, and exceeds zero otherwise.
4283: - ynorm - 2-norm of the step
4285: Note:
4286: For non-trust region methods such as SNESNEWTONLS, the parameter delta
4287: is set to be the maximum allowable step size.
4289: */
4290: PetscErrorCode SNESScaleStep_Private(SNES snes,Vec y,PetscReal *fnorm,PetscReal *delta,PetscReal *gpnorm,PetscReal *ynorm)
4291: {
4292: PetscReal nrm;
4293: PetscScalar cnorm;
4301: VecNorm(y,NORM_2,&nrm);
4302: if (nrm > *delta) {
4303: nrm = *delta/nrm;
4304: *gpnorm = (1.0 - nrm)*(*fnorm);
4305: cnorm = nrm;
4306: VecScale(y,cnorm);
4307: *ynorm = *delta;
4308: } else {
4309: *gpnorm = 0.0;
4310: *ynorm = nrm;
4311: }
4312: return(0);
4313: }
4315: /*@C
4316: SNESConvergedReasonView - Displays the reason a SNES solve converged or diverged to a viewer
4318: Collective on SNES
4320: Parameter:
4321: + snes - iterative context obtained from SNESCreate()
4322: - viewer - the viewer to display the reason
4325: Options Database Keys:
4326: + -snes_converged_reason - print reason for converged or diverged, also prints number of iterations
4327: - -snes_converged_reason ::failed - only print reason and number of iterations when diverged
4329: Notes:
4330: To change the format of the output call PetscViewerPushFormat(viewer,format) before this call. Use PETSC_VIEWER_DEFAULT for the default,
4331: use PETSC_VIEWER_FAILED to only display a reason if it fails.
4333: Level: beginner
4335: .seealso: SNESCreate(), SNESSetUp(), SNESDestroy(), SNESSetTolerances(), SNESConvergedDefault(), SNESGetConvergedReason(), SNESConvergedReasonViewFromOptions(),
4336: PetscViewerPushFormat(), PetscViewerPopFormat()
4338: @*/
4339: PetscErrorCode SNESConvergedReasonView(SNES snes,PetscViewer viewer)
4340: {
4341: PetscViewerFormat format;
4342: PetscBool isAscii;
4343: PetscErrorCode ierr;
4346: if (!viewer) viewer = PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)snes));
4347: PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&isAscii);
4348: if (isAscii) {
4349: PetscViewerGetFormat(viewer, &format);
4350: PetscViewerASCIIAddTab(viewer,((PetscObject)snes)->tablevel);
4351: if (format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
4352: DM dm;
4353: Vec u;
4354: PetscDS prob;
4355: PetscInt Nf, f;
4356: PetscErrorCode (**exactSol)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar[], void *);
4357: void **exactCtx;
4358: PetscReal error;
4360: SNESGetDM(snes, &dm);
4361: SNESGetSolution(snes, &u);
4362: DMGetDS(dm, &prob);
4363: PetscDSGetNumFields(prob, &Nf);
4364: PetscMalloc2(Nf, &exactSol, Nf, &exactCtx);
4365: for (f = 0; f < Nf; ++f) {PetscDSGetExactSolution(prob, f, &exactSol[f], &exactCtx[f]);}
4366: DMComputeL2Diff(dm, 0.0, exactSol, exactCtx, u, &error);
4367: PetscFree2(exactSol, exactCtx);
4368: if (error < 1.0e-11) {PetscViewerASCIIPrintf(viewer, "L_2 Error: < 1.0e-11\n");}
4369: else {PetscViewerASCIIPrintf(viewer, "L_2 Error: %g\n", error);}
4370: }
4371: if (snes->reason > 0 && format != PETSC_VIEWER_FAILED) {
4372: if (((PetscObject) snes)->prefix) {
4373: PetscViewerASCIIPrintf(viewer,"Nonlinear %s solve converged due to %s iterations %D\n",((PetscObject) snes)->prefix,SNESConvergedReasons[snes->reason],snes->iter);
4374: } else {
4375: PetscViewerASCIIPrintf(viewer,"Nonlinear solve converged due to %s iterations %D\n",SNESConvergedReasons[snes->reason],snes->iter);
4376: }
4377: } else if (snes->reason <= 0) {
4378: if (((PetscObject) snes)->prefix) {
4379: PetscViewerASCIIPrintf(viewer,"Nonlinear %s solve did not converge due to %s iterations %D\n",((PetscObject) snes)->prefix,SNESConvergedReasons[snes->reason],snes->iter);
4380: } else {
4381: PetscViewerASCIIPrintf(viewer,"Nonlinear solve did not converge due to %s iterations %D\n",SNESConvergedReasons[snes->reason],snes->iter);
4382: }
4383: }
4384: PetscViewerASCIISubtractTab(viewer,((PetscObject)snes)->tablevel);
4385: }
4386: return(0);
4387: }
4389: /*@
4390: SNESConvergedReasonViewFromOptions - Processes command line options to determine if/how a SNESReason is to be viewed.
4392: Collective on SNES
4394: Input Parameters:
4395: . snes - the SNES object
4397: Level: intermediate
4399: .seealso: SNESCreate(), SNESSetUp(), SNESDestroy(), SNESSetTolerances(), SNESConvergedDefault(), SNESGetConvergedReason(), SNESConvergedReasonView()
4401: @*/
4402: PetscErrorCode SNESConvergedReasonViewFromOptions(SNES snes)
4403: {
4404: PetscErrorCode ierr;
4405: PetscViewer viewer;
4406: PetscBool flg;
4407: static PetscBool incall = PETSC_FALSE;
4408: PetscViewerFormat format;
4411: if (incall) return(0);
4412: incall = PETSC_TRUE;
4413: PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_converged_reason",&viewer,&format,&flg);
4414: if (flg) {
4415: PetscViewerPushFormat(viewer,format);
4416: SNESConvergedReasonView(snes,viewer);
4417: PetscViewerPopFormat(viewer);
4418: PetscViewerDestroy(&viewer);
4419: }
4420: incall = PETSC_FALSE;
4421: return(0);
4422: }
4424: /*@
4425: SNESSolve - Solves a nonlinear system F(x) = b.
4426: Call SNESSolve() after calling SNESCreate() and optional routines of the form SNESSetXXX().
4428: Collective on SNES
4430: Input Parameters:
4431: + snes - the SNES context
4432: . b - the constant part of the equation F(x) = b, or NULL to use zero.
4433: - x - the solution vector.
4435: Notes:
4436: The user should initialize the vector,x, with the initial guess
4437: for the nonlinear solve prior to calling SNESSolve. In particular,
4438: to employ an initial guess of zero, the user should explicitly set
4439: this vector to zero by calling VecSet().
4441: Level: beginner
4443: .seealso: SNESCreate(), SNESDestroy(), SNESSetFunction(), SNESSetJacobian(), SNESSetGridSequence(), SNESGetSolution()
4444: @*/
4445: PetscErrorCode SNESSolve(SNES snes,Vec b,Vec x)
4446: {
4447: PetscErrorCode ierr;
4448: PetscBool flg;
4449: PetscInt grid;
4450: Vec xcreated = NULL;
4451: DM dm;
4460: /* High level operations using the nonlinear solver */
4461: {
4462: PetscViewer viewer;
4463: PetscViewerFormat format;
4464: PetscInt num;
4465: PetscBool flg;
4466: static PetscBool incall = PETSC_FALSE;
4468: if (!incall) {
4469: /* Estimate the convergence rate of the discretization */
4470: PetscOptionsGetViewer(PetscObjectComm((PetscObject) snes),((PetscObject)snes)->options, ((PetscObject) snes)->prefix, "-snes_convergence_estimate", &viewer, &format, &flg);
4471: if (flg) {
4472: PetscConvEst conv;
4473: DM dm;
4474: PetscReal *alpha; /* Convergence rate of the solution error for each field in the L_2 norm */
4475: PetscInt Nf;
4477: incall = PETSC_TRUE;
4478: SNESGetDM(snes, &dm);
4479: DMGetNumFields(dm, &Nf);
4480: PetscCalloc1(Nf, &alpha);
4481: PetscConvEstCreate(PetscObjectComm((PetscObject) snes), &conv);
4482: PetscConvEstSetSolver(conv, (PetscObject) snes);
4483: PetscConvEstSetFromOptions(conv);
4484: PetscConvEstSetUp(conv);
4485: PetscConvEstGetConvRate(conv, alpha);
4486: PetscViewerPushFormat(viewer, format);
4487: PetscConvEstRateView(conv, alpha, viewer);
4488: PetscViewerPopFormat(viewer);
4489: PetscViewerDestroy(&viewer);
4490: PetscConvEstDestroy(&conv);
4491: PetscFree(alpha);
4492: incall = PETSC_FALSE;
4493: }
4494: /* Adaptively refine the initial grid */
4495: num = 1;
4496: PetscOptionsGetInt(NULL, ((PetscObject) snes)->prefix, "-snes_adapt_initial", &num, &flg);
4497: if (flg) {
4498: DMAdaptor adaptor;
4500: incall = PETSC_TRUE;
4501: DMAdaptorCreate(PetscObjectComm((PetscObject)snes), &adaptor);
4502: DMAdaptorSetSolver(adaptor, snes);
4503: DMAdaptorSetSequenceLength(adaptor, num);
4504: DMAdaptorSetFromOptions(adaptor);
4505: DMAdaptorSetUp(adaptor);
4506: DMAdaptorAdapt(adaptor, x, DM_ADAPTATION_INITIAL, &dm, &x);
4507: DMAdaptorDestroy(&adaptor);
4508: incall = PETSC_FALSE;
4509: }
4510: /* Use grid sequencing to adapt */
4511: num = 0;
4512: PetscOptionsGetInt(NULL, ((PetscObject) snes)->prefix, "-snes_adapt_sequence", &num, NULL);
4513: if (num) {
4514: DMAdaptor adaptor;
4516: incall = PETSC_TRUE;
4517: DMAdaptorCreate(PetscObjectComm((PetscObject)snes), &adaptor);
4518: DMAdaptorSetSolver(adaptor, snes);
4519: DMAdaptorSetSequenceLength(adaptor, num);
4520: DMAdaptorSetFromOptions(adaptor);
4521: DMAdaptorSetUp(adaptor);
4522: DMAdaptorAdapt(adaptor, x, DM_ADAPTATION_SEQUENTIAL, &dm, &x);
4523: DMAdaptorDestroy(&adaptor);
4524: incall = PETSC_FALSE;
4525: }
4526: }
4527: }
4528: if (!x) {
4529: SNESGetDM(snes,&dm);
4530: DMCreateGlobalVector(dm,&xcreated);
4531: x = xcreated;
4532: }
4533: SNESViewFromOptions(snes,NULL,"-snes_view_pre");
4535: for (grid=0; grid<snes->gridsequence; grid++) {PetscViewerASCIIPushTab(PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)snes)));}
4536: for (grid=0; grid<snes->gridsequence+1; grid++) {
4538: /* set solution vector */
4539: if (!grid) {PetscObjectReference((PetscObject)x);}
4540: VecDestroy(&snes->vec_sol);
4541: snes->vec_sol = x;
4542: SNESGetDM(snes,&dm);
4544: /* set affine vector if provided */
4545: if (b) { PetscObjectReference((PetscObject)b); }
4546: VecDestroy(&snes->vec_rhs);
4547: snes->vec_rhs = b;
4549: if (snes->vec_rhs && (snes->vec_func == snes->vec_rhs)) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"Right hand side vector cannot be function vector");
4550: if (snes->vec_func == snes->vec_sol) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"Solution vector cannot be function vector");
4551: if (snes->vec_rhs == snes->vec_sol) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"Solution vector cannot be right hand side vector");
4552: if (!snes->vec_sol_update /* && snes->vec_sol */) {
4553: VecDuplicate(snes->vec_sol,&snes->vec_sol_update);
4554: PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->vec_sol_update);
4555: }
4556: DMShellSetGlobalVector(dm,snes->vec_sol);
4557: SNESSetUp(snes);
4559: if (!grid) {
4560: if (snes->ops->computeinitialguess) {
4561: (*snes->ops->computeinitialguess)(snes,snes->vec_sol,snes->initialguessP);
4562: }
4563: }
4565: if (snes->conv_hist_reset) snes->conv_hist_len = 0;
4566: if (snes->counters_reset) {snes->nfuncs = 0; snes->linear_its = 0; snes->numFailures = 0;}
4568: PetscLogEventBegin(SNES_Solve,snes,0,0,0);
4569: (*snes->ops->solve)(snes);
4570: PetscLogEventEnd(SNES_Solve,snes,0,0,0);
4571: if (!snes->reason) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Internal error, solver returned without setting converged reason");
4572: snes->domainerror = PETSC_FALSE; /* clear the flag if it has been set */
4574: if (snes->lagjac_persist) snes->jac_iter += snes->iter;
4575: if (snes->lagpre_persist) snes->pre_iter += snes->iter;
4577: PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_test_local_min",NULL,NULL,&flg);
4578: if (flg && !PetscPreLoadingOn) { SNESTestLocalMin(snes); }
4579: SNESConvergedReasonViewFromOptions(snes);
4581: if (snes->errorifnotconverged && snes->reason < 0) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_NOT_CONVERGED,"SNESSolve has not converged");
4582: if (snes->reason < 0) break;
4583: if (grid < snes->gridsequence) {
4584: DM fine;
4585: Vec xnew;
4586: Mat interp;
4588: DMRefine(snes->dm,PetscObjectComm((PetscObject)snes),&fine);
4589: if (!fine) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_INCOMP,"DMRefine() did not perform any refinement, cannot continue grid sequencing");
4590: DMCreateInterpolation(snes->dm,fine,&interp,NULL);
4591: DMCreateGlobalVector(fine,&xnew);
4592: MatInterpolate(interp,x,xnew);
4593: DMInterpolate(snes->dm,interp,fine);
4594: MatDestroy(&interp);
4595: x = xnew;
4597: SNESReset(snes);
4598: SNESSetDM(snes,fine);
4599: SNESResetFromOptions(snes);
4600: DMDestroy(&fine);
4601: PetscViewerASCIIPopTab(PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)snes)));
4602: }
4603: }
4604: SNESViewFromOptions(snes,NULL,"-snes_view");
4605: VecViewFromOptions(snes->vec_sol,(PetscObject)snes,"-snes_view_solution");
4606: DMMonitor(snes->dm);
4608: VecDestroy(&xcreated);
4609: PetscObjectSAWsBlock((PetscObject)snes);
4610: return(0);
4611: }
4613: /* --------- Internal routines for SNES Package --------- */
4615: /*@C
4616: SNESSetType - Sets the method for the nonlinear solver.
4618: Collective on SNES
4620: Input Parameters:
4621: + snes - the SNES context
4622: - type - a known method
4624: Options Database Key:
4625: . -snes_type <type> - Sets the method; use -help for a list
4626: of available methods (for instance, newtonls or newtontr)
4628: Notes:
4629: See "petsc/include/petscsnes.h" for available methods (for instance)
4630: + SNESNEWTONLS - Newton's method with line search
4631: (systems of nonlinear equations)
4632: - SNESNEWTONTR - Newton's method with trust region
4633: (systems of nonlinear equations)
4635: Normally, it is best to use the SNESSetFromOptions() command and then
4636: set the SNES solver type from the options database rather than by using
4637: this routine. Using the options database provides the user with
4638: maximum flexibility in evaluating the many nonlinear solvers.
4639: The SNESSetType() routine is provided for those situations where it
4640: is necessary to set the nonlinear solver independently of the command
4641: line or options database. This might be the case, for example, when
4642: the choice of solver changes during the execution of the program,
4643: and the user's application is taking responsibility for choosing the
4644: appropriate method.
4646: Developer Notes:
4647: SNESRegister() adds a constructor for a new SNESType to SNESList, SNESSetType() locates
4648: the constructor in that list and calls it to create the spexific object.
4650: Level: intermediate
4652: .seealso: SNESType, SNESCreate(), SNESDestroy(), SNESGetType(), SNESSetFromOptions()
4654: @*/
4655: PetscErrorCode SNESSetType(SNES snes,SNESType type)
4656: {
4657: PetscErrorCode ierr,(*r)(SNES);
4658: PetscBool match;
4664: PetscObjectTypeCompare((PetscObject)snes,type,&match);
4665: if (match) return(0);
4667: PetscFunctionListFind(SNESList,type,&r);
4668: if (!r) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_UNKNOWN_TYPE,"Unable to find requested SNES type %s",type);
4669: /* Destroy the previous private SNES context */
4670: if (snes->ops->destroy) {
4671: (*(snes)->ops->destroy)(snes);
4672: snes->ops->destroy = NULL;
4673: }
4674: /* Reinitialize function pointers in SNESOps structure */
4675: snes->ops->setup = NULL;
4676: snes->ops->solve = NULL;
4677: snes->ops->view = NULL;
4678: snes->ops->setfromoptions = NULL;
4679: snes->ops->destroy = NULL;
4681: /* It may happen the user has customized the line search before calling SNESSetType */
4682: if (((PetscObject)snes)->type_name) {
4683: SNESLineSearchDestroy(&snes->linesearch);
4684: }
4686: /* Call the SNESCreate_XXX routine for this particular Nonlinear solver */
4687: snes->setupcalled = PETSC_FALSE;
4689: PetscObjectChangeTypeName((PetscObject)snes,type);
4690: (*r)(snes);
4691: return(0);
4692: }
4694: /*@C
4695: SNESGetType - Gets the SNES method type and name (as a string).
4697: Not Collective
4699: Input Parameter:
4700: . snes - nonlinear solver context
4702: Output Parameter:
4703: . type - SNES method (a character string)
4705: Level: intermediate
4707: @*/
4708: PetscErrorCode SNESGetType(SNES snes,SNESType *type)
4709: {
4713: *type = ((PetscObject)snes)->type_name;
4714: return(0);
4715: }
4717: /*@
4718: SNESSetSolution - Sets the solution vector for use by the SNES routines.
4720: Logically Collective on SNES
4722: Input Parameters:
4723: + snes - the SNES context obtained from SNESCreate()
4724: - u - the solution vector
4726: Level: beginner
4728: @*/
4729: PetscErrorCode SNESSetSolution(SNES snes, Vec u)
4730: {
4731: DM dm;
4737: PetscObjectReference((PetscObject) u);
4738: VecDestroy(&snes->vec_sol);
4740: snes->vec_sol = u;
4742: SNESGetDM(snes, &dm);
4743: DMShellSetGlobalVector(dm, u);
4744: return(0);
4745: }
4747: /*@
4748: SNESGetSolution - Returns the vector where the approximate solution is
4749: stored. This is the fine grid solution when using SNESSetGridSequence().
4751: Not Collective, but Vec is parallel if SNES is parallel
4753: Input Parameter:
4754: . snes - the SNES context
4756: Output Parameter:
4757: . x - the solution
4759: Level: intermediate
4761: .seealso: SNESGetSolutionUpdate(), SNESGetFunction()
4762: @*/
4763: PetscErrorCode SNESGetSolution(SNES snes,Vec *x)
4764: {
4768: *x = snes->vec_sol;
4769: return(0);
4770: }
4772: /*@
4773: SNESGetSolutionUpdate - Returns the vector where the solution update is
4774: stored.
4776: Not Collective, but Vec is parallel if SNES is parallel
4778: Input Parameter:
4779: . snes - the SNES context
4781: Output Parameter:
4782: . x - the solution update
4784: Level: advanced
4786: .seealso: SNESGetSolution(), SNESGetFunction()
4787: @*/
4788: PetscErrorCode SNESGetSolutionUpdate(SNES snes,Vec *x)
4789: {
4793: *x = snes->vec_sol_update;
4794: return(0);
4795: }
4797: /*@C
4798: SNESGetFunction - Returns the vector where the function is stored.
4800: Not Collective, but Vec is parallel if SNES is parallel. Collective if Vec is requested, but has not been created yet.
4802: Input Parameter:
4803: . snes - the SNES context
4805: Output Parameter:
4806: + r - the vector that is used to store residuals (or NULL if you don't want it)
4807: . f - the function (or NULL if you don't want it); see SNESFunction for calling sequence details
4808: - ctx - the function context (or NULL if you don't want it)
4810: Level: advanced
4812: Notes: The vector r DOES NOT, in general contain the current value of the SNES nonlinear function
4814: .seealso: SNESSetFunction(), SNESGetSolution(), SNESFunction
4815: @*/
4816: PetscErrorCode SNESGetFunction(SNES snes,Vec *r,PetscErrorCode (**f)(SNES,Vec,Vec,void*),void **ctx)
4817: {
4819: DM dm;
4823: if (r) {
4824: if (!snes->vec_func) {
4825: if (snes->vec_rhs) {
4826: VecDuplicate(snes->vec_rhs,&snes->vec_func);
4827: } else if (snes->vec_sol) {
4828: VecDuplicate(snes->vec_sol,&snes->vec_func);
4829: } else if (snes->dm) {
4830: DMCreateGlobalVector(snes->dm,&snes->vec_func);
4831: }
4832: }
4833: *r = snes->vec_func;
4834: }
4835: SNESGetDM(snes,&dm);
4836: DMSNESGetFunction(dm,f,ctx);
4837: return(0);
4838: }
4840: /*@C
4841: SNESGetNGS - Returns the NGS function and context.
4843: Input Parameter:
4844: . snes - the SNES context
4846: Output Parameter:
4847: + f - the function (or NULL) see SNESNGSFunction for details
4848: - ctx - the function context (or NULL)
4850: Level: advanced
4852: .seealso: SNESSetNGS(), SNESGetFunction()
4853: @*/
4855: PetscErrorCode SNESGetNGS (SNES snes, PetscErrorCode (**f)(SNES, Vec, Vec, void*), void ** ctx)
4856: {
4858: DM dm;
4862: SNESGetDM(snes,&dm);
4863: DMSNESGetNGS(dm,f,ctx);
4864: return(0);
4865: }
4867: /*@C
4868: SNESSetOptionsPrefix - Sets the prefix used for searching for all
4869: SNES options in the database.
4871: Logically Collective on SNES
4873: Input Parameter:
4874: + snes - the SNES context
4875: - prefix - the prefix to prepend to all option names
4877: Notes:
4878: A hyphen (-) must NOT be given at the beginning of the prefix name.
4879: The first character of all runtime options is AUTOMATICALLY the hyphen.
4881: Level: advanced
4883: .seealso: SNESSetFromOptions()
4884: @*/
4885: PetscErrorCode SNESSetOptionsPrefix(SNES snes,const char prefix[])
4886: {
4891: PetscObjectSetOptionsPrefix((PetscObject)snes,prefix);
4892: if (!snes->ksp) {SNESGetKSP(snes,&snes->ksp);}
4893: if (snes->linesearch) {
4894: SNESGetLineSearch(snes,&snes->linesearch);
4895: PetscObjectSetOptionsPrefix((PetscObject)snes->linesearch,prefix);
4896: }
4897: KSPSetOptionsPrefix(snes->ksp,prefix);
4898: return(0);
4899: }
4901: /*@C
4902: SNESAppendOptionsPrefix - Appends to the prefix used for searching for all
4903: SNES options in the database.
4905: Logically Collective on SNES
4907: Input Parameters:
4908: + snes - the SNES context
4909: - prefix - the prefix to prepend to all option names
4911: Notes:
4912: A hyphen (-) must NOT be given at the beginning of the prefix name.
4913: The first character of all runtime options is AUTOMATICALLY the hyphen.
4915: Level: advanced
4917: .seealso: SNESGetOptionsPrefix()
4918: @*/
4919: PetscErrorCode SNESAppendOptionsPrefix(SNES snes,const char prefix[])
4920: {
4925: PetscObjectAppendOptionsPrefix((PetscObject)snes,prefix);
4926: if (!snes->ksp) {SNESGetKSP(snes,&snes->ksp);}
4927: if (snes->linesearch) {
4928: SNESGetLineSearch(snes,&snes->linesearch);
4929: PetscObjectAppendOptionsPrefix((PetscObject)snes->linesearch,prefix);
4930: }
4931: KSPAppendOptionsPrefix(snes->ksp,prefix);
4932: return(0);
4933: }
4935: /*@C
4936: SNESGetOptionsPrefix - Sets the prefix used for searching for all
4937: SNES options in the database.
4939: Not Collective
4941: Input Parameter:
4942: . snes - the SNES context
4944: Output Parameter:
4945: . prefix - pointer to the prefix string used
4947: Notes:
4948: On the fortran side, the user should pass in a string 'prefix' of
4949: sufficient length to hold the prefix.
4951: Level: advanced
4953: .seealso: SNESAppendOptionsPrefix()
4954: @*/
4955: PetscErrorCode SNESGetOptionsPrefix(SNES snes,const char *prefix[])
4956: {
4961: PetscObjectGetOptionsPrefix((PetscObject)snes,prefix);
4962: return(0);
4963: }
4966: /*@C
4967: SNESRegister - Adds a method to the nonlinear solver package.
4969: Not collective
4971: Input Parameters:
4972: + name_solver - name of a new user-defined solver
4973: - routine_create - routine to create method context
4975: Notes:
4976: SNESRegister() may be called multiple times to add several user-defined solvers.
4978: Sample usage:
4979: .vb
4980: SNESRegister("my_solver",MySolverCreate);
4981: .ve
4983: Then, your solver can be chosen with the procedural interface via
4984: $ SNESSetType(snes,"my_solver")
4985: or at runtime via the option
4986: $ -snes_type my_solver
4988: Level: advanced
4990: Note: If your function is not being put into a shared library then use SNESRegister() instead
4992: .seealso: SNESRegisterAll(), SNESRegisterDestroy()
4994: Level: advanced
4995: @*/
4996: PetscErrorCode SNESRegister(const char sname[],PetscErrorCode (*function)(SNES))
4997: {
5001: SNESInitializePackage();
5002: PetscFunctionListAdd(&SNESList,sname,function);
5003: return(0);
5004: }
5006: PetscErrorCode SNESTestLocalMin(SNES snes)
5007: {
5009: PetscInt N,i,j;
5010: Vec u,uh,fh;
5011: PetscScalar value;
5012: PetscReal norm;
5015: SNESGetSolution(snes,&u);
5016: VecDuplicate(u,&uh);
5017: VecDuplicate(u,&fh);
5019: /* currently only works for sequential */
5020: PetscPrintf(PetscObjectComm((PetscObject)snes),"Testing FormFunction() for local min\n");
5021: VecGetSize(u,&N);
5022: for (i=0; i<N; i++) {
5023: VecCopy(u,uh);
5024: PetscPrintf(PetscObjectComm((PetscObject)snes),"i = %D\n",i);
5025: for (j=-10; j<11; j++) {
5026: value = PetscSign(j)*PetscExpReal(PetscAbs(j)-10.0);
5027: VecSetValue(uh,i,value,ADD_VALUES);
5028: SNESComputeFunction(snes,uh,fh);
5029: VecNorm(fh,NORM_2,&norm);
5030: PetscPrintf(PetscObjectComm((PetscObject)snes)," j norm %D %18.16e\n",j,norm);
5031: value = -value;
5032: VecSetValue(uh,i,value,ADD_VALUES);
5033: }
5034: }
5035: VecDestroy(&uh);
5036: VecDestroy(&fh);
5037: return(0);
5038: }
5040: /*@
5041: SNESKSPSetUseEW - Sets SNES use Eisenstat-Walker method for
5042: computing relative tolerance for linear solvers within an inexact
5043: Newton method.
5045: Logically Collective on SNES
5047: Input Parameters:
5048: + snes - SNES context
5049: - flag - PETSC_TRUE or PETSC_FALSE
5051: Options Database:
5052: + -snes_ksp_ew - use Eisenstat-Walker method for determining linear system convergence
5053: . -snes_ksp_ew_version ver - version of Eisenstat-Walker method
5054: . -snes_ksp_ew_rtol0 <rtol0> - Sets rtol0
5055: . -snes_ksp_ew_rtolmax <rtolmax> - Sets rtolmax
5056: . -snes_ksp_ew_gamma <gamma> - Sets gamma
5057: . -snes_ksp_ew_alpha <alpha> - Sets alpha
5058: . -snes_ksp_ew_alpha2 <alpha2> - Sets alpha2
5059: - -snes_ksp_ew_threshold <threshold> - Sets threshold
5061: Notes:
5062: Currently, the default is to use a constant relative tolerance for
5063: the inner linear solvers. Alternatively, one can use the
5064: Eisenstat-Walker method, where the relative convergence tolerance
5065: is reset at each Newton iteration according progress of the nonlinear
5066: solver.
5068: Level: advanced
5070: Reference:
5071: S. C. Eisenstat and H. F. Walker, "Choosing the forcing terms in an
5072: inexact Newton method", SISC 17 (1), pp.16-32, 1996.
5074: .seealso: SNESKSPGetUseEW(), SNESKSPGetParametersEW(), SNESKSPSetParametersEW()
5075: @*/
5076: PetscErrorCode SNESKSPSetUseEW(SNES snes,PetscBool flag)
5077: {
5081: snes->ksp_ewconv = flag;
5082: return(0);
5083: }
5085: /*@
5086: SNESKSPGetUseEW - Gets if SNES is using Eisenstat-Walker method
5087: for computing relative tolerance for linear solvers within an
5088: inexact Newton method.
5090: Not Collective
5092: Input Parameter:
5093: . snes - SNES context
5095: Output Parameter:
5096: . flag - PETSC_TRUE or PETSC_FALSE
5098: Notes:
5099: Currently, the default is to use a constant relative tolerance for
5100: the inner linear solvers. Alternatively, one can use the
5101: Eisenstat-Walker method, where the relative convergence tolerance
5102: is reset at each Newton iteration according progress of the nonlinear
5103: solver.
5105: Level: advanced
5107: Reference:
5108: S. C. Eisenstat and H. F. Walker, "Choosing the forcing terms in an
5109: inexact Newton method", SISC 17 (1), pp.16-32, 1996.
5111: .seealso: SNESKSPSetUseEW(), SNESKSPGetParametersEW(), SNESKSPSetParametersEW()
5112: @*/
5113: PetscErrorCode SNESKSPGetUseEW(SNES snes, PetscBool *flag)
5114: {
5118: *flag = snes->ksp_ewconv;
5119: return(0);
5120: }
5122: /*@
5123: SNESKSPSetParametersEW - Sets parameters for Eisenstat-Walker
5124: convergence criteria for the linear solvers within an inexact
5125: Newton method.
5127: Logically Collective on SNES
5129: Input Parameters:
5130: + snes - SNES context
5131: . version - version 1, 2 (default is 2) or 3
5132: . rtol_0 - initial relative tolerance (0 <= rtol_0 < 1)
5133: . rtol_max - maximum relative tolerance (0 <= rtol_max < 1)
5134: . gamma - multiplicative factor for version 2 rtol computation
5135: (0 <= gamma2 <= 1)
5136: . alpha - power for version 2 rtol computation (1 < alpha <= 2)
5137: . alpha2 - power for safeguard
5138: - threshold - threshold for imposing safeguard (0 < threshold < 1)
5140: Note:
5141: Version 3 was contributed by Luis Chacon, June 2006.
5143: Use PETSC_DEFAULT to retain the default for any of the parameters.
5145: Level: advanced
5147: Reference:
5148: S. C. Eisenstat and H. F. Walker, "Choosing the forcing terms in an
5149: inexact Newton method", Utah State University Math. Stat. Dept. Res.
5150: Report 6/94/75, June, 1994, to appear in SIAM J. Sci. Comput.
5152: .seealso: SNESKSPSetUseEW(), SNESKSPGetUseEW(), SNESKSPGetParametersEW()
5153: @*/
5154: PetscErrorCode SNESKSPSetParametersEW(SNES snes,PetscInt version,PetscReal rtol_0,PetscReal rtol_max,PetscReal gamma,PetscReal alpha,PetscReal alpha2,PetscReal threshold)
5155: {
5156: SNESKSPEW *kctx;
5160: kctx = (SNESKSPEW*)snes->kspconvctx;
5161: if (!kctx) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"No Eisenstat-Walker context existing");
5170: if (version != PETSC_DEFAULT) kctx->version = version;
5171: if (rtol_0 != PETSC_DEFAULT) kctx->rtol_0 = rtol_0;
5172: if (rtol_max != PETSC_DEFAULT) kctx->rtol_max = rtol_max;
5173: if (gamma != PETSC_DEFAULT) kctx->gamma = gamma;
5174: if (alpha != PETSC_DEFAULT) kctx->alpha = alpha;
5175: if (alpha2 != PETSC_DEFAULT) kctx->alpha2 = alpha2;
5176: if (threshold != PETSC_DEFAULT) kctx->threshold = threshold;
5178: if (kctx->version < 1 || kctx->version > 3) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Only versions 1, 2 and 3 are supported: %D",kctx->version);
5179: if (kctx->rtol_0 < 0.0 || kctx->rtol_0 >= 1.0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"0.0 <= rtol_0 < 1.0: %g",(double)kctx->rtol_0);
5180: if (kctx->rtol_max < 0.0 || kctx->rtol_max >= 1.0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"0.0 <= rtol_max (%g) < 1.0\n",(double)kctx->rtol_max);
5181: if (kctx->gamma < 0.0 || kctx->gamma > 1.0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"0.0 <= gamma (%g) <= 1.0\n",(double)kctx->gamma);
5182: if (kctx->alpha <= 1.0 || kctx->alpha > 2.0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"1.0 < alpha (%g) <= 2.0\n",(double)kctx->alpha);
5183: if (kctx->threshold <= 0.0 || kctx->threshold >= 1.0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"0.0 < threshold (%g) < 1.0\n",(double)kctx->threshold);
5184: return(0);
5185: }
5187: /*@
5188: SNESKSPGetParametersEW - Gets parameters for Eisenstat-Walker
5189: convergence criteria for the linear solvers within an inexact
5190: Newton method.
5192: Not Collective
5194: Input Parameters:
5195: snes - SNES context
5197: Output Parameters:
5198: + version - version 1, 2 (default is 2) or 3
5199: . rtol_0 - initial relative tolerance (0 <= rtol_0 < 1)
5200: . rtol_max - maximum relative tolerance (0 <= rtol_max < 1)
5201: . gamma - multiplicative factor for version 2 rtol computation (0 <= gamma2 <= 1)
5202: . alpha - power for version 2 rtol computation (1 < alpha <= 2)
5203: . alpha2 - power for safeguard
5204: - threshold - threshold for imposing safeguard (0 < threshold < 1)
5206: Level: advanced
5208: .seealso: SNESKSPSetUseEW(), SNESKSPGetUseEW(), SNESKSPSetParametersEW()
5209: @*/
5210: PetscErrorCode SNESKSPGetParametersEW(SNES snes,PetscInt *version,PetscReal *rtol_0,PetscReal *rtol_max,PetscReal *gamma,PetscReal *alpha,PetscReal *alpha2,PetscReal *threshold)
5211: {
5212: SNESKSPEW *kctx;
5216: kctx = (SNESKSPEW*)snes->kspconvctx;
5217: if (!kctx) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"No Eisenstat-Walker context existing");
5218: if (version) *version = kctx->version;
5219: if (rtol_0) *rtol_0 = kctx->rtol_0;
5220: if (rtol_max) *rtol_max = kctx->rtol_max;
5221: if (gamma) *gamma = kctx->gamma;
5222: if (alpha) *alpha = kctx->alpha;
5223: if (alpha2) *alpha2 = kctx->alpha2;
5224: if (threshold) *threshold = kctx->threshold;
5225: return(0);
5226: }
5228: PetscErrorCode KSPPreSolve_SNESEW(KSP ksp, Vec b, Vec x, SNES snes)
5229: {
5231: SNESKSPEW *kctx = (SNESKSPEW*)snes->kspconvctx;
5232: PetscReal rtol = PETSC_DEFAULT,stol;
5235: if (!snes->ksp_ewconv) return(0);
5236: if (!snes->iter) {
5237: rtol = kctx->rtol_0; /* first time in, so use the original user rtol */
5238: VecNorm(snes->vec_func,NORM_2,&kctx->norm_first);
5239: }
5240: else {
5241: if (kctx->version == 1) {
5242: rtol = (snes->norm - kctx->lresid_last)/kctx->norm_last;
5243: if (rtol < 0.0) rtol = -rtol;
5244: stol = PetscPowReal(kctx->rtol_last,kctx->alpha2);
5245: if (stol > kctx->threshold) rtol = PetscMax(rtol,stol);
5246: } else if (kctx->version == 2) {
5247: rtol = kctx->gamma * PetscPowReal(snes->norm/kctx->norm_last,kctx->alpha);
5248: stol = kctx->gamma * PetscPowReal(kctx->rtol_last,kctx->alpha);
5249: if (stol > kctx->threshold) rtol = PetscMax(rtol,stol);
5250: } else if (kctx->version == 3) { /* contributed by Luis Chacon, June 2006. */
5251: rtol = kctx->gamma * PetscPowReal(snes->norm/kctx->norm_last,kctx->alpha);
5252: /* safeguard: avoid sharp decrease of rtol */
5253: stol = kctx->gamma*PetscPowReal(kctx->rtol_last,kctx->alpha);
5254: stol = PetscMax(rtol,stol);
5255: rtol = PetscMin(kctx->rtol_0,stol);
5256: /* safeguard: avoid oversolving */
5257: stol = kctx->gamma*(kctx->norm_first*snes->rtol)/snes->norm;
5258: stol = PetscMax(rtol,stol);
5259: rtol = PetscMin(kctx->rtol_0,stol);
5260: } else SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Only versions 1, 2 or 3 are supported: %D",kctx->version);
5261: }
5262: /* safeguard: avoid rtol greater than one */
5263: rtol = PetscMin(rtol,kctx->rtol_max);
5264: KSPSetTolerances(ksp,rtol,PETSC_DEFAULT,PETSC_DEFAULT,PETSC_DEFAULT);
5265: PetscInfo3(snes,"iter %D, Eisenstat-Walker (version %D) KSP rtol=%g\n",snes->iter,kctx->version,(double)rtol);
5266: return(0);
5267: }
5269: PetscErrorCode KSPPostSolve_SNESEW(KSP ksp, Vec b, Vec x, SNES snes)
5270: {
5272: SNESKSPEW *kctx = (SNESKSPEW*)snes->kspconvctx;
5273: PCSide pcside;
5274: Vec lres;
5277: if (!snes->ksp_ewconv) return(0);
5278: KSPGetTolerances(ksp,&kctx->rtol_last,NULL,NULL,NULL);
5279: kctx->norm_last = snes->norm;
5280: if (kctx->version == 1) {
5281: PC pc;
5282: PetscBool isNone;
5284: KSPGetPC(ksp, &pc);
5285: PetscObjectTypeCompare((PetscObject) pc, PCNONE, &isNone);
5286: KSPGetPCSide(ksp,&pcside);
5287: if (pcside == PC_RIGHT || isNone) { /* XXX Should we also test KSP_UNPRECONDITIONED_NORM ? */
5288: /* KSP residual is true linear residual */
5289: KSPGetResidualNorm(ksp,&kctx->lresid_last);
5290: } else {
5291: /* KSP residual is preconditioned residual */
5292: /* compute true linear residual norm */
5293: VecDuplicate(b,&lres);
5294: MatMult(snes->jacobian,x,lres);
5295: VecAYPX(lres,-1.0,b);
5296: VecNorm(lres,NORM_2,&kctx->lresid_last);
5297: VecDestroy(&lres);
5298: }
5299: }
5300: return(0);
5301: }
5303: /*@
5304: SNESGetKSP - Returns the KSP context for a SNES solver.
5306: Not Collective, but if SNES object is parallel, then KSP object is parallel
5308: Input Parameter:
5309: . snes - the SNES context
5311: Output Parameter:
5312: . ksp - the KSP context
5314: Notes:
5315: The user can then directly manipulate the KSP context to set various
5316: options, etc. Likewise, the user can then extract and manipulate the
5317: PC contexts as well.
5319: Level: beginner
5321: .seealso: KSPGetPC(), SNESCreate(), KSPCreate(), SNESSetKSP()
5322: @*/
5323: PetscErrorCode SNESGetKSP(SNES snes,KSP *ksp)
5324: {
5331: if (!snes->ksp) {
5332: PetscBool monitor = PETSC_FALSE;
5334: KSPCreate(PetscObjectComm((PetscObject)snes),&snes->ksp);
5335: PetscObjectIncrementTabLevel((PetscObject)snes->ksp,(PetscObject)snes,1);
5336: PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->ksp);
5338: KSPSetPreSolve(snes->ksp,(PetscErrorCode (*)(KSP,Vec,Vec,void*))KSPPreSolve_SNESEW,snes);
5339: KSPSetPostSolve(snes->ksp,(PetscErrorCode (*)(KSP,Vec,Vec,void*))KSPPostSolve_SNESEW,snes);
5341: PetscOptionsGetBool(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-ksp_monitor_snes",&monitor,NULL);
5342: if (monitor) {
5343: KSPMonitorSet(snes->ksp,KSPMonitorSNES,snes,NULL);
5344: }
5345: monitor = PETSC_FALSE;
5346: PetscOptionsGetBool(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-ksp_monitor_snes_lg",&monitor,NULL);
5347: if (monitor) {
5348: PetscObject *objs;
5349: KSPMonitorSNESLGResidualNormCreate(PetscObjectComm((PetscObject)snes),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,600,600,&objs);
5350: objs[0] = (PetscObject) snes;
5351: KSPMonitorSet(snes->ksp,(PetscErrorCode (*)(KSP,PetscInt,PetscReal,void*))KSPMonitorSNESLGResidualNorm,objs,(PetscErrorCode (*)(void**))KSPMonitorSNESLGResidualNormDestroy);
5352: }
5353: PetscObjectSetOptions((PetscObject)snes->ksp,((PetscObject)snes)->options);
5354: }
5355: *ksp = snes->ksp;
5356: return(0);
5357: }
5360: #include <petsc/private/dmimpl.h>
5361: /*@
5362: SNESSetDM - Sets the DM that may be used by some nonlinear solvers or their underlying preconditioners
5364: Logically Collective on SNES
5366: Input Parameters:
5367: + snes - the nonlinear solver context
5368: - dm - the dm, cannot be NULL
5370: Notes:
5371: A DM can only be used for solving one problem at a time because information about the problem is stored on the DM,
5372: even when not using interfaces like DMSNESSetFunction(). Use DMClone() to get a distinct DM when solving different
5373: problems using the same function space.
5375: Level: intermediate
5377: .seealso: SNESGetDM(), KSPSetDM(), KSPGetDM()
5378: @*/
5379: PetscErrorCode SNESSetDM(SNES snes,DM dm)
5380: {
5382: KSP ksp;
5383: DMSNES sdm;
5388: PetscObjectReference((PetscObject)dm);
5389: if (snes->dm) { /* Move the DMSNES context over to the new DM unless the new DM already has one */
5390: if (snes->dm->dmsnes && !dm->dmsnes) {
5391: DMCopyDMSNES(snes->dm,dm);
5392: DMGetDMSNES(snes->dm,&sdm);
5393: if (sdm->originaldm == snes->dm) sdm->originaldm = dm; /* Grant write privileges to the replacement DM */
5394: }
5395: DMCoarsenHookRemove(snes->dm,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,snes);
5396: DMDestroy(&snes->dm);
5397: }
5398: snes->dm = dm;
5399: snes->dmAuto = PETSC_FALSE;
5401: SNESGetKSP(snes,&ksp);
5402: KSPSetDM(ksp,dm);
5403: KSPSetDMActive(ksp,PETSC_FALSE);
5404: if (snes->npc) {
5405: SNESSetDM(snes->npc, snes->dm);
5406: SNESSetNPCSide(snes,snes->npcside);
5407: }
5408: return(0);
5409: }
5411: /*@
5412: SNESGetDM - Gets the DM that may be used by some preconditioners
5414: Not Collective but DM obtained is parallel on SNES
5416: Input Parameter:
5417: . snes - the preconditioner context
5419: Output Parameter:
5420: . dm - the dm
5422: Level: intermediate
5424: .seealso: SNESSetDM(), KSPSetDM(), KSPGetDM()
5425: @*/
5426: PetscErrorCode SNESGetDM(SNES snes,DM *dm)
5427: {
5432: if (!snes->dm) {
5433: DMShellCreate(PetscObjectComm((PetscObject)snes),&snes->dm);
5434: snes->dmAuto = PETSC_TRUE;
5435: }
5436: *dm = snes->dm;
5437: return(0);
5438: }
5440: /*@
5441: SNESSetNPC - Sets the nonlinear preconditioner to be used.
5443: Collective on SNES
5445: Input Parameters:
5446: + snes - iterative context obtained from SNESCreate()
5447: - pc - the preconditioner object
5449: Notes:
5450: Use SNESGetNPC() to retrieve the preconditioner context (for example,
5451: to configure it using the API).
5453: Level: developer
5455: .seealso: SNESGetNPC(), SNESHasNPC()
5456: @*/
5457: PetscErrorCode SNESSetNPC(SNES snes, SNES pc)
5458: {
5465: PetscObjectReference((PetscObject) pc);
5466: SNESDestroy(&snes->npc);
5467: snes->npc = pc;
5468: PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->npc);
5469: return(0);
5470: }
5472: /*@
5473: SNESGetNPC - Creates a nonlinear preconditioning solver (SNES) to be used to precondition the nonlinear solver.
5475: Not Collective; but any changes to the obtained SNES object must be applied collectively
5477: Input Parameter:
5478: . snes - iterative context obtained from SNESCreate()
5480: Output Parameter:
5481: . pc - preconditioner context
5483: Options Database:
5484: . -npc_snes_type <type> - set the type of the SNES to use as the nonlinear preconditioner
5486: Notes:
5487: If a SNES was previously set with SNESSetNPC() then that SNES is returned, otherwise a new SNES object is created.
5489: The (preconditioner) SNES returned automatically inherits the same nonlinear function and Jacobian supplied to the original
5490: SNES during SNESSetUp()
5492: Level: developer
5494: .seealso: SNESSetNPC(), SNESHasNPC(), SNES, SNESCreate()
5495: @*/
5496: PetscErrorCode SNESGetNPC(SNES snes, SNES *pc)
5497: {
5499: const char *optionsprefix;
5504: if (!snes->npc) {
5505: SNESCreate(PetscObjectComm((PetscObject)snes),&snes->npc);
5506: PetscObjectIncrementTabLevel((PetscObject)snes->npc,(PetscObject)snes,1);
5507: PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->npc);
5508: SNESGetOptionsPrefix(snes,&optionsprefix);
5509: SNESSetOptionsPrefix(snes->npc,optionsprefix);
5510: SNESAppendOptionsPrefix(snes->npc,"npc_");
5511: SNESSetCountersReset(snes->npc,PETSC_FALSE);
5512: }
5513: *pc = snes->npc;
5514: return(0);
5515: }
5517: /*@
5518: SNESHasNPC - Returns whether a nonlinear preconditioner exists
5520: Not Collective
5522: Input Parameter:
5523: . snes - iterative context obtained from SNESCreate()
5525: Output Parameter:
5526: . has_npc - whether the SNES has an NPC or not
5528: Level: developer
5530: .seealso: SNESSetNPC(), SNESGetNPC()
5531: @*/
5532: PetscErrorCode SNESHasNPC(SNES snes, PetscBool *has_npc)
5533: {
5536: *has_npc = (PetscBool) (snes->npc ? PETSC_TRUE : PETSC_FALSE);
5537: return(0);
5538: }
5540: /*@
5541: SNESSetNPCSide - Sets the preconditioning side.
5543: Logically Collective on SNES
5545: Input Parameter:
5546: . snes - iterative context obtained from SNESCreate()
5548: Output Parameter:
5549: . side - the preconditioning side, where side is one of
5550: .vb
5551: PC_LEFT - left preconditioning
5552: PC_RIGHT - right preconditioning (default for most nonlinear solvers)
5553: .ve
5555: Options Database Keys:
5556: . -snes_pc_side <right,left>
5558: Notes:
5559: SNESNRICHARDSON and SNESNCG only support left preconditioning.
5561: Level: intermediate
5563: .seealso: SNESGetNPCSide(), KSPSetPCSide()
5564: @*/
5565: PetscErrorCode SNESSetNPCSide(SNES snes,PCSide side)
5566: {
5570: snes->npcside= side;
5571: return(0);
5572: }
5574: /*@
5575: SNESGetNPCSide - Gets the preconditioning side.
5577: Not Collective
5579: Input Parameter:
5580: . snes - iterative context obtained from SNESCreate()
5582: Output Parameter:
5583: . side - the preconditioning side, where side is one of
5584: .vb
5585: PC_LEFT - left preconditioning
5586: PC_RIGHT - right preconditioning (default for most nonlinear solvers)
5587: .ve
5589: Level: intermediate
5591: .seealso: SNESSetNPCSide(), KSPGetPCSide()
5592: @*/
5593: PetscErrorCode SNESGetNPCSide(SNES snes,PCSide *side)
5594: {
5598: *side = snes->npcside;
5599: return(0);
5600: }
5602: /*@
5603: SNESSetLineSearch - Sets the linesearch on the SNES instance.
5605: Collective on SNES
5607: Input Parameters:
5608: + snes - iterative context obtained from SNESCreate()
5609: - linesearch - the linesearch object
5611: Notes:
5612: Use SNESGetLineSearch() to retrieve the preconditioner context (for example,
5613: to configure it using the API).
5615: Level: developer
5617: .seealso: SNESGetLineSearch()
5618: @*/
5619: PetscErrorCode SNESSetLineSearch(SNES snes, SNESLineSearch linesearch)
5620: {
5627: PetscObjectReference((PetscObject) linesearch);
5628: SNESLineSearchDestroy(&snes->linesearch);
5630: snes->linesearch = linesearch;
5632: PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->linesearch);
5633: return(0);
5634: }
5636: /*@
5637: SNESGetLineSearch - Returns a pointer to the line search context set with SNESSetLineSearch()
5638: or creates a default line search instance associated with the SNES and returns it.
5640: Not Collective
5642: Input Parameter:
5643: . snes - iterative context obtained from SNESCreate()
5645: Output Parameter:
5646: . linesearch - linesearch context
5648: Level: beginner
5650: .seealso: SNESSetLineSearch(), SNESLineSearchCreate()
5651: @*/
5652: PetscErrorCode SNESGetLineSearch(SNES snes, SNESLineSearch *linesearch)
5653: {
5655: const char *optionsprefix;
5660: if (!snes->linesearch) {
5661: SNESGetOptionsPrefix(snes, &optionsprefix);
5662: SNESLineSearchCreate(PetscObjectComm((PetscObject)snes), &snes->linesearch);
5663: SNESLineSearchSetSNES(snes->linesearch, snes);
5664: SNESLineSearchAppendOptionsPrefix(snes->linesearch, optionsprefix);
5665: PetscObjectIncrementTabLevel((PetscObject) snes->linesearch, (PetscObject) snes, 1);
5666: PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->linesearch);
5667: }
5668: *linesearch = snes->linesearch;
5669: return(0);
5670: }