xref: /petsc/src/snes/interface/snes.c (revision dadcf80911fb48939c55327431ae8d7e47dbe367)
1af0996ceSBarry Smith #include <petsc/private/snesimpl.h>      /*I "petscsnes.h"  I*/
207475bc1SBarry Smith #include <petscdmshell.h>
3d96771aaSLisandro Dalcin #include <petscdraw.h>
4a01aa210SMatthew G. Knepley #include <petscds.h>
534b4d3a8SMatthew G. Knepley #include <petscdmadaptor.h>
606fc46c8SMatthew G. Knepley #include <petscconvest.h>
79b94acceSBarry Smith 
8ace3abfcSBarry Smith PetscBool         SNESRegisterAllCalled = PETSC_FALSE;
90298fd71SBarry Smith PetscFunctionList SNESList              = NULL;
108ba1e511SMatthew Knepley 
118ba1e511SMatthew Knepley /* Logging support */
1222c6f798SBarry Smith PetscClassId  SNES_CLASSID, DMSNES_CLASSID;
13e3ed9ee7SBarry Smith PetscLogEvent SNES_Solve, SNES_Setup, SNES_FunctionEval, SNES_JacobianEval, SNES_NGSEval, SNES_NGSFuncEval, SNES_NPCSolve, SNES_ObjectiveEval;
14a09944afSBarry Smith 
15e113a28aSBarry Smith /*@
16e113a28aSBarry Smith    SNESSetErrorIfNotConverged - Causes SNESSolve() to generate an error if the solver has not converged.
17e113a28aSBarry Smith 
183f9fe445SBarry Smith    Logically Collective on SNES
19e113a28aSBarry Smith 
20e113a28aSBarry Smith    Input Parameters:
21e113a28aSBarry Smith +  snes - iterative context obtained from SNESCreate()
22e113a28aSBarry Smith -  flg - PETSC_TRUE indicates you want the error generated
23e113a28aSBarry Smith 
24e113a28aSBarry Smith    Options database keys:
2567b8a455SSatish Balay .  -snes_error_if_not_converged <true,false> - cause an immediate error condition and stop the program if the solver does not converge
26e113a28aSBarry Smith 
27e113a28aSBarry Smith    Level: intermediate
28e113a28aSBarry Smith 
29e113a28aSBarry Smith    Notes:
30e113a28aSBarry Smith     Normally PETSc continues if a linear solver fails to converge, you can call SNESGetConvergedReason() after a SNESSolve()
31e113a28aSBarry Smith     to determine if it has converged.
32e113a28aSBarry Smith 
334d651a51SPierre Jolivet .seealso: SNESGetErrorIfNotConverged(), KSPGetErrorIfNotConverged(), KSPSetErrorIfNotConverged()
34e113a28aSBarry Smith @*/
357087cfbeSBarry Smith PetscErrorCode  SNESSetErrorIfNotConverged(SNES snes,PetscBool flg)
36e113a28aSBarry Smith {
37e113a28aSBarry Smith   PetscFunctionBegin;
38e113a28aSBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
39acfcf0e5SJed Brown   PetscValidLogicalCollectiveBool(snes,flg,2);
40e113a28aSBarry Smith   snes->errorifnotconverged = flg;
41e113a28aSBarry Smith   PetscFunctionReturn(0);
42e113a28aSBarry Smith }
43e113a28aSBarry Smith 
44e113a28aSBarry Smith /*@
45e113a28aSBarry Smith    SNESGetErrorIfNotConverged - Will SNESSolve() generate an error if the solver does not converge?
46e113a28aSBarry Smith 
47e113a28aSBarry Smith    Not Collective
48e113a28aSBarry Smith 
49e113a28aSBarry Smith    Input Parameter:
50e113a28aSBarry Smith .  snes - iterative context obtained from SNESCreate()
51e113a28aSBarry Smith 
52e113a28aSBarry Smith    Output Parameter:
53e113a28aSBarry Smith .  flag - PETSC_TRUE if it will generate an error, else PETSC_FALSE
54e113a28aSBarry Smith 
55e113a28aSBarry Smith    Level: intermediate
56e113a28aSBarry Smith 
574d651a51SPierre Jolivet .seealso:  SNESSetErrorIfNotConverged(), KSPGetErrorIfNotConverged(), KSPSetErrorIfNotConverged()
58e113a28aSBarry Smith @*/
597087cfbeSBarry Smith PetscErrorCode  SNESGetErrorIfNotConverged(SNES snes,PetscBool  *flag)
60e113a28aSBarry Smith {
61e113a28aSBarry Smith   PetscFunctionBegin;
62e113a28aSBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
63534a8f05SLisandro Dalcin   PetscValidBoolPointer(flag,2);
64e113a28aSBarry Smith   *flag = snes->errorifnotconverged;
65e113a28aSBarry Smith   PetscFunctionReturn(0);
66e113a28aSBarry Smith }
67e113a28aSBarry Smith 
684fc747eaSLawrence Mitchell /*@
694fc747eaSLawrence Mitchell     SNESSetAlwaysComputesFinalResidual - does the SNES always compute the residual at the final solution?
704fc747eaSLawrence Mitchell 
714fc747eaSLawrence Mitchell    Logically Collective on SNES
724fc747eaSLawrence Mitchell 
734fc747eaSLawrence Mitchell     Input Parameters:
744fc747eaSLawrence Mitchell +   snes - the shell SNES
754fc747eaSLawrence Mitchell -   flg - is the residual computed?
764fc747eaSLawrence Mitchell 
774fc747eaSLawrence Mitchell    Level: advanced
784fc747eaSLawrence Mitchell 
794fc747eaSLawrence Mitchell .seealso: SNESGetAlwaysComputesFinalResidual()
804fc747eaSLawrence Mitchell @*/
814fc747eaSLawrence Mitchell PetscErrorCode  SNESSetAlwaysComputesFinalResidual(SNES snes, PetscBool flg)
824fc747eaSLawrence Mitchell {
834fc747eaSLawrence Mitchell   PetscFunctionBegin;
844fc747eaSLawrence Mitchell   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
854fc747eaSLawrence Mitchell   snes->alwayscomputesfinalresidual = flg;
864fc747eaSLawrence Mitchell   PetscFunctionReturn(0);
874fc747eaSLawrence Mitchell }
884fc747eaSLawrence Mitchell 
894fc747eaSLawrence Mitchell /*@
904fc747eaSLawrence Mitchell     SNESGetAlwaysComputesFinalResidual - does the SNES always compute the residual at the final solution?
914fc747eaSLawrence Mitchell 
924fc747eaSLawrence Mitchell    Logically Collective on SNES
934fc747eaSLawrence Mitchell 
944fc747eaSLawrence Mitchell     Input Parameter:
954fc747eaSLawrence Mitchell .   snes - the shell SNES
964fc747eaSLawrence Mitchell 
974fc747eaSLawrence Mitchell     Output Parameter:
984fc747eaSLawrence Mitchell .   flg - is the residual computed?
994fc747eaSLawrence Mitchell 
1004fc747eaSLawrence Mitchell    Level: advanced
1014fc747eaSLawrence Mitchell 
1024fc747eaSLawrence Mitchell .seealso: SNESSetAlwaysComputesFinalResidual()
1034fc747eaSLawrence Mitchell @*/
1044fc747eaSLawrence Mitchell PetscErrorCode  SNESGetAlwaysComputesFinalResidual(SNES snes, PetscBool *flg)
1054fc747eaSLawrence Mitchell {
1064fc747eaSLawrence Mitchell   PetscFunctionBegin;
1074fc747eaSLawrence Mitchell   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
1084fc747eaSLawrence Mitchell   *flg = snes->alwayscomputesfinalresidual;
1094fc747eaSLawrence Mitchell   PetscFunctionReturn(0);
1104fc747eaSLawrence Mitchell }
1114fc747eaSLawrence Mitchell 
112e725d27bSBarry Smith /*@
113bf388a1fSBarry Smith    SNESSetFunctionDomainError - tells SNES that the input vector to your SNESFunction is not
1144936397dSBarry Smith      in the functions domain. For example, negative pressure.
1154936397dSBarry Smith 
1163f9fe445SBarry Smith    Logically Collective on SNES
1174936397dSBarry Smith 
1184936397dSBarry Smith    Input Parameters:
1196a388c36SPeter Brune .  snes - the SNES context
1204936397dSBarry Smith 
12128529972SSatish Balay    Level: advanced
1224936397dSBarry Smith 
123bf388a1fSBarry Smith .seealso: SNESCreate(), SNESSetFunction(), SNESFunction
1244936397dSBarry Smith @*/
1257087cfbeSBarry Smith PetscErrorCode  SNESSetFunctionDomainError(SNES snes)
1264936397dSBarry Smith {
1274936397dSBarry Smith   PetscFunctionBegin;
1280700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
1295f80ce2aSJacob Faibussowitsch   PetscCheck(!snes->errorifnotconverged,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"User code indicates input vector is not in the function domain");
1304936397dSBarry Smith   snes->domainerror = PETSC_TRUE;
1314936397dSBarry Smith   PetscFunctionReturn(0);
1324936397dSBarry Smith }
1334936397dSBarry Smith 
1346a388c36SPeter Brune /*@
13507b62357SFande Kong    SNESSetJacobianDomainError - tells SNES that computeJacobian does not make sense any more. For example there is a negative element transformation.
13607b62357SFande Kong 
13707b62357SFande Kong    Logically Collective on SNES
13807b62357SFande Kong 
13907b62357SFande Kong    Input Parameters:
14007b62357SFande Kong .  snes - the SNES context
14107b62357SFande Kong 
14207b62357SFande Kong    Level: advanced
14307b62357SFande Kong 
14407b62357SFande Kong .seealso: SNESCreate(), SNESSetFunction(), SNESFunction(), SNESSetFunctionDomainError()
14507b62357SFande Kong @*/
14607b62357SFande Kong PetscErrorCode SNESSetJacobianDomainError(SNES snes)
14707b62357SFande Kong {
14807b62357SFande Kong   PetscFunctionBegin;
14907b62357SFande Kong   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
1505f80ce2aSJacob Faibussowitsch   PetscCheck(!snes->errorifnotconverged,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"User code indicates computeJacobian does not make sense");
15107b62357SFande Kong   snes->jacobiandomainerror = PETSC_TRUE;
15207b62357SFande Kong   PetscFunctionReturn(0);
15307b62357SFande Kong }
15407b62357SFande Kong 
15507b62357SFande Kong /*@
156b351a90bSFande Kong    SNESSetCheckJacobianDomainError - if or not to check jacobian domain error after each Jacobian evaluation. By default, we check Jacobian domain error
157b351a90bSFande Kong    in the debug mode, and do not check it in the optimized mode.
158b351a90bSFande Kong 
159b351a90bSFande Kong    Logically Collective on SNES
160b351a90bSFande Kong 
161b351a90bSFande Kong    Input Parameters:
162a2b725a8SWilliam Gropp +  snes - the SNES context
163a2b725a8SWilliam Gropp -  flg  - indicates if or not to check jacobian domain error after each Jacobian evaluation
164b351a90bSFande Kong 
165b351a90bSFande Kong    Level: advanced
166b351a90bSFande Kong 
1678383d7d7SFande Kong .seealso: SNESCreate(), SNESSetFunction(), SNESFunction(), SNESSetFunctionDomainError(), SNESGetCheckJacobianDomainError()
168b351a90bSFande Kong @*/
169b351a90bSFande Kong PetscErrorCode SNESSetCheckJacobianDomainError(SNES snes, PetscBool flg)
170b351a90bSFande Kong {
171b351a90bSFande Kong   PetscFunctionBegin;
172b351a90bSFande Kong   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
173b351a90bSFande Kong   snes->checkjacdomainerror = flg;
174b351a90bSFande Kong   PetscFunctionReturn(0);
175b351a90bSFande Kong }
176b351a90bSFande Kong 
177b351a90bSFande Kong /*@
1788383d7d7SFande Kong    SNESGetCheckJacobianDomainError - Get an indicator whether or not we are checking Jacobian domain errors after each Jacobian evaluation.
1798383d7d7SFande Kong 
1808383d7d7SFande Kong    Logically Collective on SNES
1818383d7d7SFande Kong 
1828383d7d7SFande Kong    Input Parameters:
1838383d7d7SFande Kong .  snes - the SNES context
1848383d7d7SFande Kong 
1858383d7d7SFande Kong    Output Parameters:
1868383d7d7SFande Kong .  flg  - PETSC_FALSE indicates that we don't check jacobian domain errors after each Jacobian evaluation
1878383d7d7SFande Kong 
1888383d7d7SFande Kong    Level: advanced
1898383d7d7SFande Kong 
1908383d7d7SFande Kong .seealso: SNESCreate(), SNESSetFunction(), SNESFunction(), SNESSetFunctionDomainError(), SNESSetCheckJacobianDomainError()
1918383d7d7SFande Kong @*/
1928383d7d7SFande Kong PetscErrorCode SNESGetCheckJacobianDomainError(SNES snes, PetscBool *flg)
1938383d7d7SFande Kong {
1948383d7d7SFande Kong   PetscFunctionBegin;
1958383d7d7SFande Kong   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
196534a8f05SLisandro Dalcin   PetscValidBoolPointer(flg,2);
1978383d7d7SFande Kong   *flg = snes->checkjacdomainerror;
1988383d7d7SFande Kong   PetscFunctionReturn(0);
1998383d7d7SFande Kong }
2008383d7d7SFande Kong 
2018383d7d7SFande Kong /*@
202c77b2880SPeter Brune    SNESGetFunctionDomainError - Gets the status of the domain error after a call to SNESComputeFunction;
2036a388c36SPeter Brune 
2046a388c36SPeter Brune    Logically Collective on SNES
2056a388c36SPeter Brune 
2066a388c36SPeter Brune    Input Parameters:
2076a388c36SPeter Brune .  snes - the SNES context
2086a388c36SPeter Brune 
2096a388c36SPeter Brune    Output Parameters:
210bf388a1fSBarry Smith .  domainerror - Set to PETSC_TRUE if there's a domain error; PETSC_FALSE otherwise.
2116a388c36SPeter Brune 
2126a388c36SPeter Brune    Level: advanced
2136a388c36SPeter Brune 
214bf388a1fSBarry Smith .seealso: SNESSetFunctionDomainError(), SNESComputeFunction()
2156a388c36SPeter Brune @*/
2166a388c36SPeter Brune PetscErrorCode  SNESGetFunctionDomainError(SNES snes, PetscBool *domainerror)
2176a388c36SPeter Brune {
2186a388c36SPeter Brune   PetscFunctionBegin;
2196a388c36SPeter Brune   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
220534a8f05SLisandro Dalcin   PetscValidBoolPointer(domainerror,2);
2216a388c36SPeter Brune   *domainerror = snes->domainerror;
2226a388c36SPeter Brune   PetscFunctionReturn(0);
2236a388c36SPeter Brune }
2246a388c36SPeter Brune 
22507b62357SFande Kong /*@
22607b62357SFande Kong    SNESGetJacobianDomainError - Gets the status of the Jacobian domain error after a call to SNESComputeJacobian;
22707b62357SFande Kong 
22807b62357SFande Kong    Logically Collective on SNES
22907b62357SFande Kong 
23007b62357SFande Kong    Input Parameters:
23107b62357SFande Kong .  snes - the SNES context
23207b62357SFande Kong 
23307b62357SFande Kong    Output Parameters:
23407b62357SFande Kong .  domainerror - Set to PETSC_TRUE if there's a jacobian domain error; PETSC_FALSE otherwise.
23507b62357SFande Kong 
23607b62357SFande Kong    Level: advanced
23707b62357SFande Kong 
23807b62357SFande Kong .seealso: SNESSetFunctionDomainError(), SNESComputeFunction(),SNESGetFunctionDomainError()
23907b62357SFande Kong @*/
24007b62357SFande Kong PetscErrorCode SNESGetJacobianDomainError(SNES snes, PetscBool *domainerror)
24107b62357SFande Kong {
24207b62357SFande Kong   PetscFunctionBegin;
24307b62357SFande Kong   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
244534a8f05SLisandro Dalcin   PetscValidBoolPointer(domainerror,2);
24507b62357SFande Kong   *domainerror = snes->jacobiandomainerror;
24607b62357SFande Kong   PetscFunctionReturn(0);
24707b62357SFande Kong }
24807b62357SFande Kong 
24955849f57SBarry Smith /*@C
25055849f57SBarry Smith   SNESLoad - Loads a SNES that has been stored in binary  with SNESView().
25155849f57SBarry Smith 
25255849f57SBarry Smith   Collective on PetscViewer
25355849f57SBarry Smith 
25455849f57SBarry Smith   Input Parameters:
25555849f57SBarry Smith + newdm - the newly loaded SNES, this needs to have been created with SNESCreate() or
25655849f57SBarry Smith            some related function before a call to SNESLoad().
25755849f57SBarry Smith - viewer - binary file viewer, obtained from PetscViewerBinaryOpen()
25855849f57SBarry Smith 
25955849f57SBarry Smith    Level: intermediate
26055849f57SBarry Smith 
26155849f57SBarry Smith   Notes:
26255849f57SBarry Smith    The type is determined by the data in the file, any type set into the SNES before this call is ignored.
26355849f57SBarry Smith 
26455849f57SBarry Smith   Notes for advanced users:
26555849f57SBarry Smith   Most users should not need to know the details of the binary storage
26655849f57SBarry Smith   format, since SNESLoad() and TSView() completely hide these details.
26755849f57SBarry Smith   But for anyone who's interested, the standard binary matrix storage
26855849f57SBarry Smith   format is
26955849f57SBarry Smith .vb
27055849f57SBarry Smith      has not yet been determined
27155849f57SBarry Smith .ve
27255849f57SBarry Smith 
27355849f57SBarry Smith .seealso: PetscViewerBinaryOpen(), SNESView(), MatLoad(), VecLoad()
27455849f57SBarry Smith @*/
2752d53ad75SBarry Smith PetscErrorCode  SNESLoad(SNES snes, PetscViewer viewer)
27655849f57SBarry Smith {
27755849f57SBarry Smith   PetscBool      isbinary;
278060da220SMatthew G. Knepley   PetscInt       classid;
27955849f57SBarry Smith   char           type[256];
28055849f57SBarry Smith   KSP            ksp;
2812d53ad75SBarry Smith   DM             dm;
2822d53ad75SBarry Smith   DMSNES         dmsnes;
28355849f57SBarry Smith 
28455849f57SBarry Smith   PetscFunctionBegin;
2852d53ad75SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
28655849f57SBarry Smith   PetscValidHeaderSpecific(viewer,PETSC_VIEWER_CLASSID,2);
2875f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary));
2885f80ce2aSJacob Faibussowitsch   PetscCheck(isbinary,PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Invalid viewer; open viewer with PetscViewerBinaryOpen()");
28955849f57SBarry Smith 
2905f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscViewerBinaryRead(viewer,&classid,1,NULL,PETSC_INT));
2915f80ce2aSJacob Faibussowitsch   PetscCheck(classid == SNES_FILE_CLASSID,PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_WRONG,"Not SNES next in file");
2925f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscViewerBinaryRead(viewer,type,256,NULL,PETSC_CHAR));
2935f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESSetType(snes, type));
2942d53ad75SBarry Smith   if (snes->ops->load) {
2955f80ce2aSJacob Faibussowitsch     CHKERRQ((*snes->ops->load)(snes,viewer));
296f2c2a1b9SBarry Smith   }
2975f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESGetDM(snes,&dm));
2985f80ce2aSJacob Faibussowitsch   CHKERRQ(DMGetDMSNES(dm,&dmsnes));
2995f80ce2aSJacob Faibussowitsch   CHKERRQ(DMSNESLoad(dmsnes,viewer));
3005f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESGetKSP(snes,&ksp));
3015f80ce2aSJacob Faibussowitsch   CHKERRQ(KSPLoad(ksp,viewer));
30255849f57SBarry Smith   PetscFunctionReturn(0);
30355849f57SBarry Smith }
3046a388c36SPeter Brune 
3059804daf3SBarry Smith #include <petscdraw.h>
306e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
307e04113cfSBarry Smith #include <petscviewersaws.h>
308bfb97211SBarry Smith #endif
3098404b7f3SBarry Smith 
310fe2efc57SMark /*@C
311fe2efc57SMark    SNESViewFromOptions - View from Options
312fe2efc57SMark 
313fe2efc57SMark    Collective on SNES
314fe2efc57SMark 
315fe2efc57SMark    Input Parameters:
316fe2efc57SMark +  A - the application ordering context
317736c3998SJose E. Roman .  obj - Optional object
318736c3998SJose E. Roman -  name - command line option
319fe2efc57SMark 
320fe2efc57SMark    Level: intermediate
321fe2efc57SMark .seealso:  SNES, SNESView, PetscObjectViewFromOptions(), SNESCreate()
322fe2efc57SMark @*/
323fe2efc57SMark PetscErrorCode  SNESViewFromOptions(SNES A,PetscObject obj,const char name[])
324fe2efc57SMark {
325fe2efc57SMark   PetscFunctionBegin;
326fe2efc57SMark   PetscValidHeaderSpecific(A,SNES_CLASSID,1);
3275f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscObjectViewFromOptions((PetscObject)A,obj,name));
328fe2efc57SMark   PetscFunctionReturn(0);
329fe2efc57SMark }
330fe2efc57SMark 
331789d8953SBarry Smith PETSC_EXTERN PetscErrorCode SNESComputeJacobian_DMDA(SNES,Vec,Mat,Mat,void*);
332789d8953SBarry Smith 
3337e2c5f70SBarry Smith /*@C
3349b94acceSBarry Smith    SNESView - Prints the SNES data structure.
3359b94acceSBarry Smith 
3364c49b128SBarry Smith    Collective on SNES
337fee21e36SBarry Smith 
338c7afd0dbSLois Curfman McInnes    Input Parameters:
339c7afd0dbSLois Curfman McInnes +  SNES - the SNES context
340c7afd0dbSLois Curfman McInnes -  viewer - visualization context
341c7afd0dbSLois Curfman McInnes 
3429b94acceSBarry Smith    Options Database Key:
343c8a8ba5cSLois Curfman McInnes .  -snes_view - Calls SNESView() at end of SNESSolve()
3449b94acceSBarry Smith 
3459b94acceSBarry Smith    Notes:
3469b94acceSBarry Smith    The available visualization contexts include
347b0a32e0cSBarry Smith +     PETSC_VIEWER_STDOUT_SELF - standard output (default)
348b0a32e0cSBarry Smith -     PETSC_VIEWER_STDOUT_WORLD - synchronized standard
349c8a8ba5cSLois Curfman McInnes          output where only the first processor opens
350c8a8ba5cSLois Curfman McInnes          the file.  All other processors send their
351c8a8ba5cSLois Curfman McInnes          data to the first processor to print.
3529b94acceSBarry Smith 
353052bf0daSPierre Jolivet    The available formats include
354052bf0daSPierre Jolivet +     PETSC_VIEWER_DEFAULT - standard output (default)
355052bf0daSPierre Jolivet -     PETSC_VIEWER_ASCII_INFO_DETAIL - more verbose output for SNESNASM
356052bf0daSPierre Jolivet 
3573e081fefSLois Curfman McInnes    The user can open an alternative visualization context with
358b0a32e0cSBarry Smith    PetscViewerASCIIOpen() - output to a specified file.
3599b94acceSBarry Smith 
360595c91d4SBarry Smith   In the debugger you can do "call SNESView(snes,0)" to display the SNES solver. (The same holds for any PETSc object viewer).
361595c91d4SBarry Smith 
36236851e7fSLois Curfman McInnes    Level: beginner
36336851e7fSLois Curfman McInnes 
364b0a32e0cSBarry Smith .seealso: PetscViewerASCIIOpen()
3659b94acceSBarry Smith @*/
3667087cfbeSBarry Smith PetscErrorCode  SNESView(SNES snes,PetscViewer viewer)
3679b94acceSBarry Smith {
368fa9f3622SBarry Smith   SNESKSPEW      *kctx;
36994b7f48cSBarry Smith   KSP            ksp;
3707f1410a3SPeter Brune   SNESLineSearch linesearch;
37172a02f06SBarry Smith   PetscBool      iascii,isstring,isbinary,isdraw;
3722d53ad75SBarry Smith   DMSNES         dmsnes;
373e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
374536b137fSBarry Smith   PetscBool      issaws;
375bfb97211SBarry Smith #endif
3769b94acceSBarry Smith 
3773a40ed3dSBarry Smith   PetscFunctionBegin;
3780700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3793050cee2SBarry Smith   if (!viewer) {
3805f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes),&viewer));
3813050cee2SBarry Smith   }
3820700a824SBarry Smith   PetscValidHeaderSpecific(viewer,PETSC_VIEWER_CLASSID,2);
383c9780b6fSBarry Smith   PetscCheckSameComm(snes,1,viewer,2);
38474679c65SBarry Smith 
3855f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii));
3865f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSTRING,&isstring));
3875f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary));
3885f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERDRAW,&isdraw));
389e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
3905f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSAWS,&issaws));
391bfb97211SBarry Smith #endif
39232077d6dSBarry Smith   if (iascii) {
393dc0571f2SMatthew G. Knepley     SNESNormSchedule normschedule;
3948404b7f3SBarry Smith     DM               dm;
3958404b7f3SBarry Smith     PetscErrorCode   (*cJ)(SNES,Vec,Mat,Mat,void*);
3968404b7f3SBarry Smith     void             *ctx;
397789d8953SBarry Smith     const char       *pre = "";
398dc0571f2SMatthew G. Knepley 
3995f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscObjectPrintClassNamePrefixType((PetscObject)snes,viewer));
400fce1e034SJed Brown     if (!snes->setupcalled) {
4015f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscViewerASCIIPrintf(viewer,"  SNES has not been set up so information may be incomplete\n"));
402fce1e034SJed Brown     }
403e7788613SBarry Smith     if (snes->ops->view) {
4045f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscViewerASCIIPushTab(viewer));
4055f80ce2aSJacob Faibussowitsch       CHKERRQ((*snes->ops->view)(snes,viewer));
4065f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscViewerASCIIPopTab(viewer));
4070ef38995SBarry Smith     }
4085f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscViewerASCIIPrintf(viewer,"  maximum iterations=%D, maximum function evaluations=%D\n",snes->max_its,snes->max_funcs));
4095f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscViewerASCIIPrintf(viewer,"  tolerances: relative=%g, absolute=%g, solution=%g\n",(double)snes->rtol,(double)snes->abstol,(double)snes->stol));
410efd4aadfSBarry Smith     if (snes->usesksp) {
4115f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscViewerASCIIPrintf(viewer,"  total number of linear solver iterations=%D\n",snes->linear_its));
412efd4aadfSBarry Smith     }
4135f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscViewerASCIIPrintf(viewer,"  total number of function evaluations=%D\n",snes->nfuncs));
4145f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESGetNormSchedule(snes, &normschedule));
4155f80ce2aSJacob Faibussowitsch     if (normschedule > 0) CHKERRQ(PetscViewerASCIIPrintf(viewer,"  norm schedule %s\n",SNESNormSchedules[normschedule]));
41617fe4bdfSPeter Brune     if (snes->gridsequence) {
4175f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscViewerASCIIPrintf(viewer,"  total number of grid sequence refinements=%D\n",snes->gridsequence));
41817fe4bdfSPeter Brune     }
4199b94acceSBarry Smith     if (snes->ksp_ewconv) {
420fa9f3622SBarry Smith       kctx = (SNESKSPEW*)snes->kspconvctx;
4219b94acceSBarry Smith       if (kctx) {
4225f80ce2aSJacob Faibussowitsch         CHKERRQ(PetscViewerASCIIPrintf(viewer,"  Eisenstat-Walker computation of KSP relative tolerance (version %D)\n",kctx->version));
4235f80ce2aSJacob Faibussowitsch         CHKERRQ(PetscViewerASCIIPrintf(viewer,"    rtol_0=%g, rtol_max=%g, threshold=%g\n",(double)kctx->rtol_0,(double)kctx->rtol_max,(double)kctx->threshold));
4245f80ce2aSJacob Faibussowitsch         CHKERRQ(PetscViewerASCIIPrintf(viewer,"    gamma=%g, alpha=%g, alpha2=%g\n",(double)kctx->gamma,(double)kctx->alpha,(double)kctx->alpha2));
4259b94acceSBarry Smith       }
4269b94acceSBarry Smith     }
427eb1f6c34SBarry Smith     if (snes->lagpreconditioner == -1) {
4285f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscViewerASCIIPrintf(viewer,"  Preconditioned is never rebuilt\n"));
429eb1f6c34SBarry Smith     } else if (snes->lagpreconditioner > 1) {
4305f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscViewerASCIIPrintf(viewer,"  Preconditioned is rebuilt every %D new Jacobians\n",snes->lagpreconditioner));
431eb1f6c34SBarry Smith     }
432eb1f6c34SBarry Smith     if (snes->lagjacobian == -1) {
4335f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscViewerASCIIPrintf(viewer,"  Jacobian is never rebuilt\n"));
434eb1f6c34SBarry Smith     } else if (snes->lagjacobian > 1) {
4355f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscViewerASCIIPrintf(viewer,"  Jacobian is rebuilt every %D SNES iterations\n",snes->lagjacobian));
436eb1f6c34SBarry Smith     }
4375f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESGetDM(snes,&dm));
4385f80ce2aSJacob Faibussowitsch     CHKERRQ(DMSNESGetJacobian(dm,&cJ,&ctx));
439789d8953SBarry Smith     if (snes->mf_operator) {
4405f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscViewerASCIIPrintf(viewer,"  Jacobian is applied matrix-free with differencing\n"));
441789d8953SBarry Smith       pre  = "Preconditioning ";
442789d8953SBarry Smith     }
4438404b7f3SBarry Smith     if (cJ == SNESComputeJacobianDefault) {
4445f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscViewerASCIIPrintf(viewer,"  %sJacobian is built using finite differences one column at a time\n",pre));
4458404b7f3SBarry Smith     } else if (cJ == SNESComputeJacobianDefaultColor) {
4465f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscViewerASCIIPrintf(viewer,"  %sJacobian is built using finite differences with coloring\n",pre));
447789d8953SBarry Smith     /* it slightly breaks data encapsulation for access the DMDA information directly */
448789d8953SBarry Smith     } else if (cJ == SNESComputeJacobian_DMDA) {
449789d8953SBarry Smith       MatFDColoring fdcoloring;
4505f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscObjectQuery((PetscObject)dm,"DMDASNES_FDCOLORING",(PetscObject*)&fdcoloring));
451789d8953SBarry Smith       if (fdcoloring) {
4525f80ce2aSJacob Faibussowitsch         CHKERRQ(PetscViewerASCIIPrintf(viewer,"  %sJacobian is built using colored finite differences on a DMDA\n",pre));
453789d8953SBarry Smith       } else {
4545f80ce2aSJacob Faibussowitsch         CHKERRQ(PetscViewerASCIIPrintf(viewer,"  %sJacobian is built using a DMDA local Jacobian\n",pre));
455789d8953SBarry Smith       }
456789d8953SBarry Smith     } else if (snes->mf) {
4575f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscViewerASCIIPrintf(viewer,"  Jacobian is applied matrix-free with differencing, no explicit Jacobian\n"));
4588404b7f3SBarry Smith     }
4590f5bd95cSBarry Smith   } else if (isstring) {
460317d6ea6SBarry Smith     const char *type;
4615f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESGetType(snes,&type));
4625f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscViewerStringSPrintf(viewer," SNESType: %-7.7s",type));
4635f80ce2aSJacob Faibussowitsch     if (snes->ops->view) CHKERRQ((*snes->ops->view)(snes,viewer));
46455849f57SBarry Smith   } else if (isbinary) {
46555849f57SBarry Smith     PetscInt    classid = SNES_FILE_CLASSID;
46655849f57SBarry Smith     MPI_Comm    comm;
46755849f57SBarry Smith     PetscMPIInt rank;
46855849f57SBarry Smith     char        type[256];
46955849f57SBarry Smith 
4705f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscObjectGetComm((PetscObject)snes,&comm));
4715f80ce2aSJacob Faibussowitsch     CHKERRMPI(MPI_Comm_rank(comm,&rank));
472dd400576SPatrick Sanan     if (rank == 0) {
4735f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscViewerBinaryWrite(viewer,&classid,1,PETSC_INT));
4745f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscStrncpy(type,((PetscObject)snes)->type_name,sizeof(type)));
4755f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscViewerBinaryWrite(viewer,type,sizeof(type),PETSC_CHAR));
47655849f57SBarry Smith     }
47755849f57SBarry Smith     if (snes->ops->view) {
4785f80ce2aSJacob Faibussowitsch       CHKERRQ((*snes->ops->view)(snes,viewer));
47955849f57SBarry Smith     }
48072a02f06SBarry Smith   } else if (isdraw) {
48172a02f06SBarry Smith     PetscDraw draw;
48272a02f06SBarry Smith     char      str[36];
48389fd9fafSBarry Smith     PetscReal x,y,bottom,h;
48472a02f06SBarry Smith 
4855f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscViewerDrawGetDraw(viewer,0,&draw));
4865f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscDrawGetCurrentPoint(draw,&x,&y));
4875f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscStrncpy(str,"SNES: ",sizeof(str)));
4885f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscStrlcat(str,((PetscObject)snes)->type_name,sizeof(str)));
4895f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscDrawStringBoxed(draw,x,y,PETSC_DRAW_BLUE,PETSC_DRAW_BLACK,str,NULL,&h));
49089fd9fafSBarry Smith     bottom = y - h;
4915f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscDrawPushCurrentPoint(draw,x,bottom));
492c4646bacSPeter Brune     if (snes->ops->view) {
4935f80ce2aSJacob Faibussowitsch       CHKERRQ((*snes->ops->view)(snes,viewer));
494c4646bacSPeter Brune     }
495e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
496536b137fSBarry Smith   } else if (issaws) {
497d45a07a7SBarry Smith     PetscMPIInt rank;
4982657e9d9SBarry Smith     const char *name;
499d45a07a7SBarry Smith 
5005f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscObjectGetName((PetscObject)snes,&name));
5015f80ce2aSJacob Faibussowitsch     CHKERRMPI(MPI_Comm_rank(PETSC_COMM_WORLD,&rank));
502dd400576SPatrick Sanan     if (!((PetscObject)snes)->amsmem && rank == 0) {
503d45a07a7SBarry Smith       char       dir[1024];
504d45a07a7SBarry Smith 
5055f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscObjectViewSAWs((PetscObject)snes,viewer));
5065f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/its",name));
5072657e9d9SBarry Smith       PetscStackCallSAWs(SAWs_Register,(dir,&snes->iter,1,SAWs_READ,SAWs_INT));
508bfb97211SBarry Smith       if (!snes->conv_hist) {
5095f80ce2aSJacob Faibussowitsch         CHKERRQ(SNESSetConvergenceHistory(snes,NULL,NULL,PETSC_DECIDE,PETSC_TRUE));
510bfb97211SBarry Smith       }
5115f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/conv_hist",name));
5122657e9d9SBarry Smith       PetscStackCallSAWs(SAWs_Register,(dir,snes->conv_hist,10,SAWs_READ,SAWs_DOUBLE));
513f05ece33SBarry Smith     }
514bfb97211SBarry Smith #endif
51572a02f06SBarry Smith   }
51672a02f06SBarry Smith   if (snes->linesearch) {
5175f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESGetLineSearch(snes, &linesearch));
5185f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscViewerASCIIPushTab(viewer));
5195f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESLineSearchView(linesearch, viewer));
5205f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscViewerASCIIPopTab(viewer));
52119bcc07fSBarry Smith   }
522efd4aadfSBarry Smith   if (snes->npc && snes->usesnpc) {
5235f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscViewerASCIIPushTab(viewer));
5245f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESView(snes->npc, viewer));
5255f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscViewerASCIIPopTab(viewer));
5264a0c5b0cSMatthew G Knepley   }
5275f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscViewerASCIIPushTab(viewer));
5285f80ce2aSJacob Faibussowitsch   CHKERRQ(DMGetDMSNES(snes->dm,&dmsnes));
5295f80ce2aSJacob Faibussowitsch   CHKERRQ(DMSNESView(dmsnes, viewer));
5305f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscViewerASCIIPopTab(viewer));
5312c155ee1SBarry Smith   if (snes->usesksp) {
5325f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESGetKSP(snes,&ksp));
5335f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscViewerASCIIPushTab(viewer));
5345f80ce2aSJacob Faibussowitsch     CHKERRQ(KSPView(ksp,viewer));
5355f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscViewerASCIIPopTab(viewer));
5362c155ee1SBarry Smith   }
53772a02f06SBarry Smith   if (isdraw) {
53872a02f06SBarry Smith     PetscDraw draw;
5395f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscViewerDrawGetDraw(viewer,0,&draw));
5405f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscDrawPopCurrentPoint(draw));
5417f1410a3SPeter Brune   }
5423a40ed3dSBarry Smith   PetscFunctionReturn(0);
5439b94acceSBarry Smith }
5449b94acceSBarry Smith 
54576b2cf59SMatthew Knepley /*
54676b2cf59SMatthew Knepley   We retain a list of functions that also take SNES command
54776b2cf59SMatthew Knepley   line options. These are called at the end SNESSetFromOptions()
54876b2cf59SMatthew Knepley */
54976b2cf59SMatthew Knepley #define MAXSETFROMOPTIONS 5
550a7cc72afSBarry Smith static PetscInt numberofsetfromoptions;
5516849ba73SBarry Smith static PetscErrorCode (*othersetfromoptions[MAXSETFROMOPTIONS])(SNES);
55276b2cf59SMatthew Knepley 
553ac226902SBarry Smith /*@C
55476b2cf59SMatthew Knepley   SNESAddOptionsChecker - Adds an additional function to check for SNES options.
55576b2cf59SMatthew Knepley 
55676b2cf59SMatthew Knepley   Not Collective
55776b2cf59SMatthew Knepley 
55876b2cf59SMatthew Knepley   Input Parameter:
55976b2cf59SMatthew Knepley . snescheck - function that checks for options
56076b2cf59SMatthew Knepley 
56176b2cf59SMatthew Knepley   Level: developer
56276b2cf59SMatthew Knepley 
56376b2cf59SMatthew Knepley .seealso: SNESSetFromOptions()
56476b2cf59SMatthew Knepley @*/
5657087cfbeSBarry Smith PetscErrorCode  SNESAddOptionsChecker(PetscErrorCode (*snescheck)(SNES))
56676b2cf59SMatthew Knepley {
56776b2cf59SMatthew Knepley   PetscFunctionBegin;
5685f80ce2aSJacob Faibussowitsch   PetscCheck(numberofsetfromoptions < MAXSETFROMOPTIONS,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE, "Too many options checkers, only %D allowed", MAXSETFROMOPTIONS);
56976b2cf59SMatthew Knepley   othersetfromoptions[numberofsetfromoptions++] = snescheck;
57076b2cf59SMatthew Knepley   PetscFunctionReturn(0);
57176b2cf59SMatthew Knepley }
57276b2cf59SMatthew Knepley 
57325acbd8eSLisandro Dalcin PETSC_INTERN PetscErrorCode SNESDefaultMatrixFreeCreate2(SNES,Vec,Mat*);
574aa3661deSLisandro Dalcin 
575ace3abfcSBarry Smith static PetscErrorCode SNESSetUpMatrixFree_Private(SNES snes, PetscBool hasOperator, PetscInt version)
576aa3661deSLisandro Dalcin {
577aa3661deSLisandro Dalcin   Mat            J;
578895c21f2SBarry Smith   MatNullSpace   nullsp;
579aa3661deSLisandro Dalcin 
580aa3661deSLisandro Dalcin   PetscFunctionBegin;
5810700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
582aa3661deSLisandro Dalcin 
58398613b67SLisandro Dalcin   if (!snes->vec_func && (snes->jacobian || snes->jacobian_pre)) {
58498613b67SLisandro Dalcin     Mat A = snes->jacobian, B = snes->jacobian_pre;
5855f80ce2aSJacob Faibussowitsch     CHKERRQ(MatCreateVecs(A ? A : B, NULL,&snes->vec_func));
58698613b67SLisandro Dalcin   }
58798613b67SLisandro Dalcin 
588aa3661deSLisandro Dalcin   if (version == 1) {
5895f80ce2aSJacob Faibussowitsch     CHKERRQ(MatCreateSNESMF(snes,&J));
5905f80ce2aSJacob Faibussowitsch     CHKERRQ(MatMFFDSetOptionsPrefix(J,((PetscObject)snes)->prefix));
5915f80ce2aSJacob Faibussowitsch     CHKERRQ(MatSetFromOptions(J));
592aa3661deSLisandro Dalcin   } else if (version == 2) {
5935f80ce2aSJacob Faibussowitsch     PetscCheck(snes->vec_func,PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"SNESSetFunction() must be called first");
594570b7f6dSBarry Smith #if !defined(PETSC_USE_COMPLEX) && !defined(PETSC_USE_REAL_SINGLE) && !defined(PETSC_USE_REAL___FLOAT128) && !defined(PETSC_USE_REAL___FP16)
5955f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESDefaultMatrixFreeCreate2(snes,snes->vec_func,&J));
596aa3661deSLisandro Dalcin #else
5972479783cSJose E. Roman     SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP, "matrix-free operator routines (version 2)");
598aa3661deSLisandro Dalcin #endif
5992479783cSJose E. Roman   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE, "matrix-free operator routines, only version 1 and 2");
600aa3661deSLisandro Dalcin 
601895c21f2SBarry Smith   /* attach any user provided null space that was on Amat to the newly created matrix free matrix */
602895c21f2SBarry Smith   if (snes->jacobian) {
6035f80ce2aSJacob Faibussowitsch     CHKERRQ(MatGetNullSpace(snes->jacobian,&nullsp));
604895c21f2SBarry Smith     if (nullsp) {
6055f80ce2aSJacob Faibussowitsch       CHKERRQ(MatSetNullSpace(J,nullsp));
606895c21f2SBarry Smith     }
607895c21f2SBarry Smith   }
608895c21f2SBarry Smith 
6095f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscInfo(snes,"Setting default matrix-free operator routines (version %D)\n", version));
610d3462f78SMatthew Knepley   if (hasOperator) {
6113232da50SPeter Brune 
612aa3661deSLisandro Dalcin     /* This version replaces the user provided Jacobian matrix with a
613aa3661deSLisandro Dalcin        matrix-free version but still employs the user-provided preconditioner matrix. */
6145f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESSetJacobian(snes,J,NULL,NULL,NULL));
615aa3661deSLisandro Dalcin   } else {
616aa3661deSLisandro Dalcin     /* This version replaces both the user-provided Jacobian and the user-
6173232da50SPeter Brune      provided preconditioner Jacobian with the default matrix free version. */
618b552625fSStefano Zampini     if (snes->npcside == PC_LEFT && snes->npc) {
6195f80ce2aSJacob Faibussowitsch       if (!snes->jacobian) CHKERRQ(SNESSetJacobian(snes,J,NULL,NULL,NULL));
620172a4300SPeter Brune     } else {
621789d8953SBarry Smith       KSP       ksp;
622789d8953SBarry Smith       PC        pc;
623789d8953SBarry Smith       PetscBool match;
624789d8953SBarry Smith 
6255f80ce2aSJacob Faibussowitsch       CHKERRQ(SNESSetJacobian(snes,J,J,MatMFFDComputeJacobian,NULL));
626aa3661deSLisandro Dalcin       /* Force no preconditioner */
6275f80ce2aSJacob Faibussowitsch       CHKERRQ(SNESGetKSP(snes,&ksp));
6285f80ce2aSJacob Faibussowitsch       CHKERRQ(KSPGetPC(ksp,&pc));
6295f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscObjectTypeCompare((PetscObject)pc,PCSHELL,&match));
630aa3661deSLisandro Dalcin       if (!match) {
6315f80ce2aSJacob Faibussowitsch         CHKERRQ(PetscInfo(snes,"Setting default matrix-free preconditioner routines\nThat is no preconditioner is being used\n"));
6325f80ce2aSJacob Faibussowitsch         CHKERRQ(PCSetType(pc,PCNONE));
633aa3661deSLisandro Dalcin       }
634aa3661deSLisandro Dalcin     }
635789d8953SBarry Smith   }
6365f80ce2aSJacob Faibussowitsch   CHKERRQ(MatDestroy(&J));
637aa3661deSLisandro Dalcin   PetscFunctionReturn(0);
638aa3661deSLisandro Dalcin }
639aa3661deSLisandro Dalcin 
640dfe15315SJed Brown static PetscErrorCode DMRestrictHook_SNESVecSol(DM dmfine,Mat Restrict,Vec Rscale,Mat Inject,DM dmcoarse,void *ctx)
641dfe15315SJed Brown {
642dfe15315SJed Brown   SNES           snes = (SNES)ctx;
6430298fd71SBarry Smith   Vec            Xfine,Xfine_named = NULL,Xcoarse;
644dfe15315SJed Brown 
645dfe15315SJed Brown   PetscFunctionBegin;
64616ebb321SJed Brown   if (PetscLogPrintInfo) {
64716ebb321SJed Brown     PetscInt finelevel,coarselevel,fineclevel,coarseclevel;
6485f80ce2aSJacob Faibussowitsch     CHKERRQ(DMGetRefineLevel(dmfine,&finelevel));
6495f80ce2aSJacob Faibussowitsch     CHKERRQ(DMGetCoarsenLevel(dmfine,&fineclevel));
6505f80ce2aSJacob Faibussowitsch     CHKERRQ(DMGetRefineLevel(dmcoarse,&coarselevel));
6515f80ce2aSJacob Faibussowitsch     CHKERRQ(DMGetCoarsenLevel(dmcoarse,&coarseclevel));
6525f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscInfo(dmfine,"Restricting SNES solution vector from level %D-%D to level %D-%D\n",finelevel,fineclevel,coarselevel,coarseclevel));
65316ebb321SJed Brown   }
654dfe15315SJed Brown   if (dmfine == snes->dm) Xfine = snes->vec_sol;
655dfe15315SJed Brown   else {
6565f80ce2aSJacob Faibussowitsch     CHKERRQ(DMGetNamedGlobalVector(dmfine,"SNESVecSol",&Xfine_named));
657dfe15315SJed Brown     Xfine = Xfine_named;
658dfe15315SJed Brown   }
6595f80ce2aSJacob Faibussowitsch   CHKERRQ(DMGetNamedGlobalVector(dmcoarse,"SNESVecSol",&Xcoarse));
660907f5c5aSLawrence Mitchell   if (Inject) {
6615f80ce2aSJacob Faibussowitsch     CHKERRQ(MatRestrict(Inject,Xfine,Xcoarse));
662907f5c5aSLawrence Mitchell   } else {
6635f80ce2aSJacob Faibussowitsch     CHKERRQ(MatRestrict(Restrict,Xfine,Xcoarse));
6645f80ce2aSJacob Faibussowitsch     CHKERRQ(VecPointwiseMult(Xcoarse,Xcoarse,Rscale));
665907f5c5aSLawrence Mitchell   }
6665f80ce2aSJacob Faibussowitsch   CHKERRQ(DMRestoreNamedGlobalVector(dmcoarse,"SNESVecSol",&Xcoarse));
6675f80ce2aSJacob Faibussowitsch   if (Xfine_named) CHKERRQ(DMRestoreNamedGlobalVector(dmfine,"SNESVecSol",&Xfine_named));
668dfe15315SJed Brown   PetscFunctionReturn(0);
669dfe15315SJed Brown }
670dfe15315SJed Brown 
67116ebb321SJed Brown static PetscErrorCode DMCoarsenHook_SNESVecSol(DM dm,DM dmc,void *ctx)
67216ebb321SJed Brown {
67316ebb321SJed Brown   PetscFunctionBegin;
6745f80ce2aSJacob Faibussowitsch   CHKERRQ(DMCoarsenHookAdd(dmc,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,ctx));
67516ebb321SJed Brown   PetscFunctionReturn(0);
67616ebb321SJed Brown }
67716ebb321SJed Brown 
678a6950cb2SJed Brown /* This may be called to rediscretize the operator on levels of linear multigrid. The DM shuffle is so the user can
679a6950cb2SJed Brown  * safely call SNESGetDM() in their residual evaluation routine. */
68023ee1639SBarry Smith static PetscErrorCode KSPComputeOperators_SNES(KSP ksp,Mat A,Mat B,void *ctx)
681caa4e7f2SJed Brown {
682caa4e7f2SJed Brown   SNES           snes = (SNES)ctx;
6830298fd71SBarry Smith   Vec            X,Xnamed = NULL;
684dfe15315SJed Brown   DM             dmsave;
6854e269d77SPeter Brune   void           *ctxsave;
68625ce1634SJed Brown   PetscErrorCode (*jac)(SNES,Vec,Mat,Mat,void*) = NULL;
687caa4e7f2SJed Brown 
688caa4e7f2SJed Brown   PetscFunctionBegin;
689dfe15315SJed Brown   dmsave = snes->dm;
6905f80ce2aSJacob Faibussowitsch   CHKERRQ(KSPGetDM(ksp,&snes->dm));
691dfe15315SJed Brown   if (dmsave == snes->dm) X = snes->vec_sol; /* We are on the finest level */
692dfe15315SJed Brown   else {                                     /* We are on a coarser level, this vec was initialized using a DM restrict hook */
6935f80ce2aSJacob Faibussowitsch     CHKERRQ(DMGetNamedGlobalVector(snes->dm,"SNESVecSol",&Xnamed));
694dfe15315SJed Brown     X    = Xnamed;
6955f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESGetJacobian(snes,NULL,NULL,&jac,&ctxsave));
6964e269d77SPeter Brune     /* If the DM's don't match up, the MatFDColoring context needed for the jacobian won't match up either -- fixit. */
6978d359177SBarry Smith     if (jac == SNESComputeJacobianDefaultColor) {
6985f80ce2aSJacob Faibussowitsch       CHKERRQ(SNESSetJacobian(snes,NULL,NULL,SNESComputeJacobianDefaultColor,NULL));
699dfe15315SJed Brown     }
7004e269d77SPeter Brune   }
7014dde8bb0SMatthew G. Knepley   /* Make sure KSP DM has the Jacobian computation routine */
7024dde8bb0SMatthew G. Knepley   {
7034dde8bb0SMatthew G. Knepley     DMSNES sdm;
7044e269d77SPeter Brune 
7055f80ce2aSJacob Faibussowitsch     CHKERRQ(DMGetDMSNES(snes->dm, &sdm));
7064dde8bb0SMatthew G. Knepley     if (!sdm->ops->computejacobian) {
7075f80ce2aSJacob Faibussowitsch       CHKERRQ(DMCopyDMSNES(dmsave, snes->dm));
7084dde8bb0SMatthew G. Knepley     }
7094dde8bb0SMatthew G. Knepley   }
7102b93b426SMatthew G. Knepley   /* Compute the operators */
7115f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESComputeJacobian(snes,X,A,B));
7122b93b426SMatthew G. Knepley   /* Put the previous context back */
7138d359177SBarry Smith   if (snes->dm != dmsave && jac == SNESComputeJacobianDefaultColor) {
7145f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESSetJacobian(snes,NULL,NULL,jac,ctxsave));
7154e269d77SPeter Brune   }
7164e269d77SPeter Brune 
7175f80ce2aSJacob Faibussowitsch   if (Xnamed) CHKERRQ(DMRestoreNamedGlobalVector(snes->dm,"SNESVecSol",&Xnamed));
718dfe15315SJed Brown   snes->dm = dmsave;
719caa4e7f2SJed Brown   PetscFunctionReturn(0);
720caa4e7f2SJed Brown }
721caa4e7f2SJed Brown 
7226cab3a1bSJed Brown /*@
7236cab3a1bSJed Brown    SNESSetUpMatrices - ensures that matrices are available for SNES, to be called by SNESSetUp_XXX()
7246cab3a1bSJed Brown 
7256cab3a1bSJed Brown    Collective
7266cab3a1bSJed Brown 
7274165533cSJose E. Roman    Input Parameter:
7286cab3a1bSJed Brown .  snes - snes to configure
7296cab3a1bSJed Brown 
7306cab3a1bSJed Brown    Level: developer
7316cab3a1bSJed Brown 
7326cab3a1bSJed Brown .seealso: SNESSetUp()
7336cab3a1bSJed Brown @*/
7346cab3a1bSJed Brown PetscErrorCode SNESSetUpMatrices(SNES snes)
7356cab3a1bSJed Brown {
7366cab3a1bSJed Brown   DM             dm;
737942e3340SBarry Smith   DMSNES         sdm;
7386cab3a1bSJed Brown 
7396cab3a1bSJed Brown   PetscFunctionBegin;
7405f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESGetDM(snes,&dm));
7415f80ce2aSJacob Faibussowitsch   CHKERRQ(DMGetDMSNES(dm,&sdm));
74258b371f3SBarry Smith   if (!snes->jacobian && snes->mf) {
7436cab3a1bSJed Brown     Mat  J;
7446cab3a1bSJed Brown     void *functx;
7455f80ce2aSJacob Faibussowitsch     CHKERRQ(MatCreateSNESMF(snes,&J));
7465f80ce2aSJacob Faibussowitsch     CHKERRQ(MatMFFDSetOptionsPrefix(J,((PetscObject)snes)->prefix));
7475f80ce2aSJacob Faibussowitsch     CHKERRQ(MatSetFromOptions(J));
7485f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESGetFunction(snes,NULL,NULL,&functx));
7495f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESSetJacobian(snes,J,J,NULL,NULL));
7505f80ce2aSJacob Faibussowitsch     CHKERRQ(MatDestroy(&J));
751caa4e7f2SJed Brown   } else if (snes->mf_operator && !snes->jacobian_pre && !snes->jacobian) {
7526cab3a1bSJed Brown     Mat J,B;
7535f80ce2aSJacob Faibussowitsch     CHKERRQ(MatCreateSNESMF(snes,&J));
7545f80ce2aSJacob Faibussowitsch     CHKERRQ(MatMFFDSetOptionsPrefix(J,((PetscObject)snes)->prefix));
7555f80ce2aSJacob Faibussowitsch     CHKERRQ(MatSetFromOptions(J));
7565f80ce2aSJacob Faibussowitsch     CHKERRQ(DMCreateMatrix(snes->dm,&B));
75706f20277SJed Brown     /* sdm->computejacobian was already set to reach here */
7585f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESSetJacobian(snes,J,B,NULL,NULL));
7595f80ce2aSJacob Faibussowitsch     CHKERRQ(MatDestroy(&J));
7605f80ce2aSJacob Faibussowitsch     CHKERRQ(MatDestroy(&B));
761caa4e7f2SJed Brown   } else if (!snes->jacobian_pre) {
7621ba9b98eSMatthew G. Knepley     PetscDS   prob;
7636cab3a1bSJed Brown     Mat       J, B;
7641ba9b98eSMatthew G. Knepley     PetscBool hasPrec   = PETSC_FALSE;
7651ba9b98eSMatthew G. Knepley 
7666cab3a1bSJed Brown     J    = snes->jacobian;
7675f80ce2aSJacob Faibussowitsch     CHKERRQ(DMGetDS(dm, &prob));
7685f80ce2aSJacob Faibussowitsch     if (prob) CHKERRQ(PetscDSHasJacobianPreconditioner(prob, &hasPrec));
7695f80ce2aSJacob Faibussowitsch     if (J)            CHKERRQ(PetscObjectReference((PetscObject) J));
7705f80ce2aSJacob Faibussowitsch     else if (hasPrec) CHKERRQ(DMCreateMatrix(snes->dm, &J));
7715f80ce2aSJacob Faibussowitsch     CHKERRQ(DMCreateMatrix(snes->dm, &B));
7725f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESSetJacobian(snes, J ? J : B, B, NULL, NULL));
7735f80ce2aSJacob Faibussowitsch     CHKERRQ(MatDestroy(&J));
7745f80ce2aSJacob Faibussowitsch     CHKERRQ(MatDestroy(&B));
7756cab3a1bSJed Brown   }
776caa4e7f2SJed Brown   {
777caa4e7f2SJed Brown     KSP ksp;
7785f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESGetKSP(snes,&ksp));
7795f80ce2aSJacob Faibussowitsch     CHKERRQ(KSPSetComputeOperators(ksp,KSPComputeOperators_SNES,snes));
7805f80ce2aSJacob Faibussowitsch     CHKERRQ(DMCoarsenHookAdd(snes->dm,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,snes));
781caa4e7f2SJed Brown   }
7826cab3a1bSJed Brown   PetscFunctionReturn(0);
7836cab3a1bSJed Brown }
7846cab3a1bSJed Brown 
7855e7c47f3SMatthew G. Knepley static PetscErrorCode SNESMonitorPauseFinal_Internal(SNES snes)
7865e7c47f3SMatthew G. Knepley {
7875e7c47f3SMatthew G. Knepley   PetscInt       i;
7885e7c47f3SMatthew G. Knepley 
7895e7c47f3SMatthew G. Knepley   PetscFunctionBegin;
7905e7c47f3SMatthew G. Knepley   if (!snes->pauseFinal) PetscFunctionReturn(0);
7915e7c47f3SMatthew G. Knepley   for (i = 0; i < snes->numbermonitors; ++i) {
7925e7c47f3SMatthew G. Knepley     PetscViewerAndFormat *vf = (PetscViewerAndFormat *) snes->monitorcontext[i];
7935e7c47f3SMatthew G. Knepley     PetscDraw             draw;
7945e7c47f3SMatthew G. Knepley     PetscReal             lpause;
7955e7c47f3SMatthew G. Knepley 
7965e7c47f3SMatthew G. Knepley     if (!vf) continue;
7975e7c47f3SMatthew G. Knepley     if (vf->lg) {
7985e7c47f3SMatthew G. Knepley       if (!PetscCheckPointer(vf->lg, PETSC_OBJECT)) continue;
7995e7c47f3SMatthew G. Knepley       if (((PetscObject) vf->lg)->classid != PETSC_DRAWLG_CLASSID) continue;
8005f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscDrawLGGetDraw(vf->lg, &draw));
8015f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscDrawGetPause(draw, &lpause));
8025f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscDrawSetPause(draw, -1.0));
8035f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscDrawPause(draw));
8045f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscDrawSetPause(draw, lpause));
8055e7c47f3SMatthew G. Knepley     } else {
8065e7c47f3SMatthew G. Knepley       PetscBool isdraw;
8075e7c47f3SMatthew G. Knepley 
8085e7c47f3SMatthew G. Knepley       if (!PetscCheckPointer(vf->viewer, PETSC_OBJECT)) continue;
8095e7c47f3SMatthew G. Knepley       if (((PetscObject) vf->viewer)->classid != PETSC_VIEWER_CLASSID) continue;
8105f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscObjectTypeCompare((PetscObject) vf->viewer, PETSCVIEWERDRAW, &isdraw));
8115e7c47f3SMatthew G. Knepley       if (!isdraw) continue;
8125f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscViewerDrawGetDraw(vf->viewer, 0, &draw));
8135f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscDrawGetPause(draw, &lpause));
8145f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscDrawSetPause(draw, -1.0));
8155f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscDrawPause(draw));
8165f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscDrawSetPause(draw, lpause));
8175e7c47f3SMatthew G. Knepley     }
8185e7c47f3SMatthew G. Knepley   }
8195e7c47f3SMatthew G. Knepley   PetscFunctionReturn(0);
8205e7c47f3SMatthew G. Knepley }
8215e7c47f3SMatthew G. Knepley 
822fde5950dSBarry Smith /*@C
823fde5950dSBarry Smith    SNESMonitorSetFromOptions - Sets a monitor function and viewer appropriate for the type indicated by the user
824fde5950dSBarry Smith 
825fde5950dSBarry Smith    Collective on SNES
826fde5950dSBarry Smith 
827fde5950dSBarry Smith    Input Parameters:
828fde5950dSBarry Smith +  snes - SNES object you wish to monitor
829fde5950dSBarry Smith .  name - the monitor type one is seeking
830fde5950dSBarry Smith .  help - message indicating what monitoring is done
831fde5950dSBarry Smith .  manual - manual page for the monitor
832fde5950dSBarry Smith .  monitor - the monitor function
833fde5950dSBarry Smith -  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
834fde5950dSBarry Smith 
835fde5950dSBarry Smith    Level: developer
836fde5950dSBarry Smith 
837fde5950dSBarry Smith .seealso: PetscOptionsGetViewer(), PetscOptionsGetReal(), PetscOptionsHasName(), PetscOptionsGetString(),
838fde5950dSBarry Smith           PetscOptionsGetIntArray(), PetscOptionsGetRealArray(), PetscOptionsBool()
839fde5950dSBarry Smith           PetscOptionsInt(), PetscOptionsString(), PetscOptionsReal(), PetscOptionsBool(),
840fde5950dSBarry Smith           PetscOptionsName(), PetscOptionsBegin(), PetscOptionsEnd(), PetscOptionsHead(),
841fde5950dSBarry Smith           PetscOptionsStringArray(),PetscOptionsRealArray(), PetscOptionsScalar(),
842fde5950dSBarry Smith           PetscOptionsBoolGroupBegin(), PetscOptionsBoolGroup(), PetscOptionsBoolGroupEnd(),
843fde5950dSBarry Smith           PetscOptionsFList(), PetscOptionsEList()
844fde5950dSBarry Smith @*/
845d43b4f6eSBarry Smith PetscErrorCode  SNESMonitorSetFromOptions(SNES snes,const char name[],const char help[], const char manual[],PetscErrorCode (*monitor)(SNES,PetscInt,PetscReal,PetscViewerAndFormat*),PetscErrorCode (*monitorsetup)(SNES,PetscViewerAndFormat*))
846fde5950dSBarry Smith {
847fde5950dSBarry Smith   PetscViewer       viewer;
848fde5950dSBarry Smith   PetscViewerFormat format;
849fde5950dSBarry Smith   PetscBool         flg;
850fde5950dSBarry Smith 
851fde5950dSBarry Smith   PetscFunctionBegin;
8525f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject) snes)->options,((PetscObject)snes)->prefix,name,&viewer,&format,&flg));
853fde5950dSBarry Smith   if (flg) {
854d43b4f6eSBarry Smith     PetscViewerAndFormat *vf;
8555f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscViewerAndFormatCreate(viewer,format,&vf));
8565f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscObjectDereference((PetscObject)viewer));
857fde5950dSBarry Smith     if (monitorsetup) {
8585f80ce2aSJacob Faibussowitsch       CHKERRQ((*monitorsetup)(snes,vf));
859fde5950dSBarry Smith     }
8605f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESMonitorSet(snes,(PetscErrorCode (*)(SNES,PetscInt,PetscReal,void*))monitor,vf,(PetscErrorCode (*)(void**))PetscViewerAndFormatDestroy));
861fde5950dSBarry Smith   }
862fde5950dSBarry Smith   PetscFunctionReturn(0);
863fde5950dSBarry Smith }
864fde5950dSBarry Smith 
8659b94acceSBarry Smith /*@
86694b7f48cSBarry Smith    SNESSetFromOptions - Sets various SNES and KSP parameters from user options.
8679b94acceSBarry Smith 
868c7afd0dbSLois Curfman McInnes    Collective on SNES
869c7afd0dbSLois Curfman McInnes 
8709b94acceSBarry Smith    Input Parameter:
8719b94acceSBarry Smith .  snes - the SNES context
8729b94acceSBarry Smith 
87336851e7fSLois Curfman McInnes    Options Database Keys:
874722329fbSBarry Smith +  -snes_type <type> - newtonls, newtontr, ngmres, ncg, nrichardson, qn, vi, fas, SNESType for complete list
87582738288SBarry Smith .  -snes_stol - convergence tolerance in terms of the norm
87682738288SBarry Smith                 of the change in the solution between steps
87770441072SBarry Smith .  -snes_atol <abstol> - absolute tolerance of residual norm
878b39c3a46SLois Curfman McInnes .  -snes_rtol <rtol> - relative decrease in tolerance norm from initial
879e4d06f11SPatrick Farrell .  -snes_divergence_tolerance <divtol> - if the residual goes above divtol*rnorm0, exit with divergence
880be5caee7SBarry Smith .  -snes_force_iteration <force> - force SNESSolve() to take at least one iteration
881b39c3a46SLois Curfman McInnes .  -snes_max_it <max_it> - maximum number of iterations
882b39c3a46SLois Curfman McInnes .  -snes_max_funcs <max_funcs> - maximum number of function evaluations
8834839bfe8SBarry Smith .  -snes_max_fail <max_fail> - maximum number of line search failures allowed before stopping, default is none
884ddf469c8SBarry Smith .  -snes_max_linear_solve_fail - number of linear solver failures before SNESSolve() stops
885a8054027SBarry Smith .  -snes_lag_preconditioner <lag> - how often preconditioner is rebuilt (use -1 to never rebuild)
8863d5a8a6aSBarry Smith .  -snes_lag_preconditioner_persists <true,false> - retains the -snes_lag_preconditioner information across multiple SNESSolve()
887e35cf81dSBarry Smith .  -snes_lag_jacobian <lag> - how often Jacobian is rebuilt (use -1 to never rebuild)
8883d5a8a6aSBarry Smith .  -snes_lag_jacobian_persists <true,false> - retains the -snes_lag_jacobian information across multiple SNESSolve()
889b39c3a46SLois Curfman McInnes .  -snes_trtol <trtol> - trust region tolerance
8902492ecdbSBarry Smith .  -snes_no_convergence_test - skip convergence test in nonlinear
89182738288SBarry Smith                                solver; hence iterations will continue until max_it
8921fbbfb26SLois Curfman McInnes                                or some other criterion is reached. Saves expense
89382738288SBarry Smith                                of convergence test
894fde5950dSBarry Smith .  -snes_monitor [ascii][:filename][:viewer format] - prints residual norm at each iteration. if no filename given prints to stdout
895fde5950dSBarry Smith .  -snes_monitor_solution [ascii binary draw][:filename][:viewer format] - plots solution at each iteration
896fde5950dSBarry Smith .  -snes_monitor_residual [ascii binary draw][:filename][:viewer format] - plots residual (not its norm) at each iteration
897fde5950dSBarry Smith .  -snes_monitor_solution_update [ascii binary draw][:filename][:viewer format] - plots update to solution at each iteration
8984619e776SBarry Smith .  -snes_monitor_lg_residualnorm - plots residual norm at each iteration
899459f5d12SBarry Smith .  -snes_monitor_lg_range - plots residual norm at each iteration
9005e7c47f3SMatthew G. Knepley .  -snes_monitor_pause_final - Pauses all monitor drawing after the solver ends
901e24b481bSBarry Smith .  -snes_fd - use finite differences to compute Jacobian; very slow, only for testing
902e2e60de9SPeter Brune .  -snes_fd_color - use finite differences with coloring to compute Jacobian
9035968eb51SBarry Smith .  -snes_mf_ksp_monitor - if using matrix-free multiply then print h at each KSP iteration
904b5badacbSBarry Smith .  -snes_converged_reason - print the reason for convergence/divergence after each solve
905e62ac41dSBarry Smith .  -npc_snes_type <type> - the SNES type to use as a nonlinear preconditioner
906e62ac41dSBarry Smith .   -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.
907e62ac41dSBarry Smith -   -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.
90882738288SBarry Smith 
90982738288SBarry Smith     Options Database for Eisenstat-Walker method:
910fa9f3622SBarry Smith +  -snes_ksp_ew - use Eisenstat-Walker method for determining linear system convergence
9114b27c08aSLois Curfman McInnes .  -snes_ksp_ew_version ver - version of  Eisenstat-Walker method
91236851e7fSLois Curfman McInnes .  -snes_ksp_ew_rtol0 <rtol0> - Sets rtol0
91336851e7fSLois Curfman McInnes .  -snes_ksp_ew_rtolmax <rtolmax> - Sets rtolmax
91436851e7fSLois Curfman McInnes .  -snes_ksp_ew_gamma <gamma> - Sets gamma
91536851e7fSLois Curfman McInnes .  -snes_ksp_ew_alpha <alpha> - Sets alpha
91636851e7fSLois Curfman McInnes .  -snes_ksp_ew_alpha2 <alpha2> - Sets alpha2
91736851e7fSLois Curfman McInnes -  -snes_ksp_ew_threshold <threshold> - Sets threshold
91882738288SBarry Smith 
91911ca99fdSLois Curfman McInnes    Notes:
920ec5066bdSBarry Smith    To see all options, run your program with the -help option or consult the users manual
921ec5066bdSBarry Smith 
922ec5066bdSBarry Smith    Notes:
923a5b23f4aSJose E. Roman       SNES supports three approaches for computing (approximate) Jacobians: user provided via SNESSetJacobian(), matrix free, and computing explicitly with
924ec5066bdSBarry Smith       finite differences and coloring using MatFDColoring. It is also possible to use automatic differentiation and the MatFDColoring object.
92583e2fdc7SBarry Smith 
92636851e7fSLois Curfman McInnes    Level: beginner
92736851e7fSLois Curfman McInnes 
928ec5066bdSBarry Smith .seealso: SNESSetOptionsPrefix(), SNESResetFromOptions(), SNES, SNESCreate()
9299b94acceSBarry Smith @*/
9307087cfbeSBarry Smith PetscErrorCode  SNESSetFromOptions(SNES snes)
9319b94acceSBarry Smith {
9328afaa268SBarry Smith   PetscBool      flg,pcset,persist,set;
933d8f46077SPeter Brune   PetscInt       i,indx,lag,grids;
93404d7464bSBarry Smith   const char     *deft        = SNESNEWTONLS;
935649ef022SMatthew Knepley   const char     *convtests[] = {"default","skip","correct_pressure"};
93685385478SLisandro Dalcin   SNESKSPEW      *kctx        = NULL;
937e8105e01SRichard Katz   char           type[256], monfilename[PETSC_MAX_PATH_LEN];
93885385478SLisandro Dalcin   PetscErrorCode ierr;
939c40d0f55SPeter Brune   PCSide         pcside;
940a64e098fSPeter Brune   const char     *optionsprefix;
9419b94acceSBarry Smith 
9423a40ed3dSBarry Smith   PetscFunctionBegin;
9430700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
9445f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESRegisterAll());
9453194b578SJed Brown   ierr = PetscObjectOptionsBegin((PetscObject)snes);CHKERRQ(ierr);
946639ff905SBarry Smith   if (((PetscObject)snes)->type_name) deft = ((PetscObject)snes)->type_name;
9475f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscOptionsFList("-snes_type","Nonlinear solver method","SNESSetType",SNESList,deft,type,256,&flg));
948d64ed03dSBarry Smith   if (flg) {
9495f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESSetType(snes,type));
9507adad957SLisandro Dalcin   } else if (!((PetscObject)snes)->type_name) {
9515f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESSetType(snes,deft));
952d64ed03dSBarry Smith   }
9535f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscOptionsReal("-snes_stol","Stop if step length less than","SNESSetTolerances",snes->stol,&snes->stol,NULL));
9545f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscOptionsReal("-snes_atol","Stop if function norm less than","SNESSetTolerances",snes->abstol,&snes->abstol,NULL));
955186905e3SBarry Smith 
9565f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscOptionsReal("-snes_rtol","Stop if decrease in function norm less than","SNESSetTolerances",snes->rtol,&snes->rtol,NULL));
9575f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscOptionsReal("-snes_divergence_tolerance","Stop if residual norm increases by this factor","SNESSetDivergenceTolerance",snes->divtol,&snes->divtol,NULL));
9585f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscOptionsInt("-snes_max_it","Maximum iterations","SNESSetTolerances",snes->max_its,&snes->max_its,NULL));
9595f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscOptionsInt("-snes_max_funcs","Maximum function evaluations","SNESSetTolerances",snes->max_funcs,&snes->max_funcs,NULL));
9605f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscOptionsInt("-snes_max_fail","Maximum nonlinear step failures","SNESSetMaxNonlinearStepFailures",snes->maxFailures,&snes->maxFailures,NULL));
9615f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscOptionsInt("-snes_max_linear_solve_fail","Maximum failures in linear solves allowed","SNESSetMaxLinearSolveFailures",snes->maxLinearSolveFailures,&snes->maxLinearSolveFailures,NULL));
9625f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscOptionsBool("-snes_error_if_not_converged","Generate error if solver does not converge","SNESSetErrorIfNotConverged",snes->errorifnotconverged,&snes->errorifnotconverged,NULL));
9635f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscOptionsBool("-snes_force_iteration","Force SNESSolve() to take at least one iteration","SNESSetForceIteration",snes->forceiteration,&snes->forceiteration,NULL));
9645f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscOptionsBool("-snes_check_jacobian_domain_error","Check Jacobian domain error after Jacobian evaluation","SNESCheckJacobianDomainError",snes->checkjacdomainerror,&snes->checkjacdomainerror,NULL));
96585385478SLisandro Dalcin 
9665f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscOptionsInt("-snes_lag_preconditioner","How often to rebuild preconditioner","SNESSetLagPreconditioner",snes->lagpreconditioner,&lag,&flg));
967a8054027SBarry Smith   if (flg) {
9685f80ce2aSJacob Faibussowitsch     PetscCheck(lag != -1,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");
9695f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESSetLagPreconditioner(snes,lag));
970a8054027SBarry Smith   }
9715f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscOptionsBool("-snes_lag_preconditioner_persists","Preconditioner lagging through multiple SNES solves","SNESSetLagPreconditionerPersists",snes->lagjac_persist,&persist,&flg));
97237ec4e1aSPeter Brune   if (flg) {
9735f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESSetLagPreconditionerPersists(snes,persist));
97437ec4e1aSPeter Brune   }
9755f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscOptionsInt("-snes_lag_jacobian","How often to rebuild Jacobian","SNESSetLagJacobian",snes->lagjacobian,&lag,&flg));
976e35cf81dSBarry Smith   if (flg) {
9775f80ce2aSJacob Faibussowitsch     PetscCheck(lag != -1,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");
9785f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESSetLagJacobian(snes,lag));
979e35cf81dSBarry Smith   }
9805f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscOptionsBool("-snes_lag_jacobian_persists","Jacobian lagging through multiple SNES solves","SNESSetLagJacobianPersists",snes->lagjac_persist,&persist,&flg));
98137ec4e1aSPeter Brune   if (flg) {
9825f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESSetLagJacobianPersists(snes,persist));
98337ec4e1aSPeter Brune   }
98437ec4e1aSPeter Brune 
9855f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscOptionsInt("-snes_grid_sequence","Use grid sequencing to generate initial guess","SNESSetGridSequence",snes->gridsequence,&grids,&flg));
986efd51863SBarry Smith   if (flg) {
9875f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESSetGridSequence(snes,grids));
988efd51863SBarry Smith   }
989a8054027SBarry Smith 
9905f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscOptionsEList("-snes_convergence_test","Convergence test","SNESSetConvergenceTest",convtests,sizeof(convtests)/sizeof(char*),"default",&indx,&flg));
99185385478SLisandro Dalcin   if (flg) {
99285385478SLisandro Dalcin     switch (indx) {
9935f80ce2aSJacob Faibussowitsch     case 0: CHKERRQ(SNESSetConvergenceTest(snes,SNESConvergedDefault,NULL,NULL)); break;
9945f80ce2aSJacob Faibussowitsch     case 1: CHKERRQ(SNESSetConvergenceTest(snes,SNESConvergedSkip,NULL,NULL)); break;
9955f80ce2aSJacob Faibussowitsch     case 2: CHKERRQ(SNESSetConvergenceTest(snes,SNESConvergedCorrectPressure,NULL,NULL)); break;
99685385478SLisandro Dalcin     }
99785385478SLisandro Dalcin   }
99885385478SLisandro Dalcin 
9995f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscOptionsEList("-snes_norm_schedule","SNES Norm schedule","SNESSetNormSchedule",SNESNormSchedules,5,"function",&indx,&flg));
10005f80ce2aSJacob Faibussowitsch   if (flg) CHKERRQ(SNESSetNormSchedule(snes,(SNESNormSchedule)indx));
1001fdacfa88SPeter Brune 
10025f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscOptionsEList("-snes_function_type","SNES Norm schedule","SNESSetFunctionType",SNESFunctionTypes,2,"unpreconditioned",&indx,&flg));
10035f80ce2aSJacob Faibussowitsch   if (flg) CHKERRQ(SNESSetFunctionType(snes,(SNESFunctionType)indx));
1004186905e3SBarry Smith 
100585385478SLisandro Dalcin   kctx = (SNESKSPEW*)snes->kspconvctx;
100685385478SLisandro Dalcin 
10075f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscOptionsBool("-snes_ksp_ew","Use Eisentat-Walker linear system convergence test","SNESKSPSetUseEW",snes->ksp_ewconv,&snes->ksp_ewconv,NULL));
1008186905e3SBarry Smith 
10095f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscOptionsInt("-snes_ksp_ew_version","Version 1, 2 or 3","SNESKSPSetParametersEW",kctx->version,&kctx->version,NULL));
10105f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscOptionsReal("-snes_ksp_ew_rtol0","0 <= rtol0 < 1","SNESKSPSetParametersEW",kctx->rtol_0,&kctx->rtol_0,NULL));
10115f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscOptionsReal("-snes_ksp_ew_rtolmax","0 <= rtolmax < 1","SNESKSPSetParametersEW",kctx->rtol_max,&kctx->rtol_max,NULL));
10125f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscOptionsReal("-snes_ksp_ew_gamma","0 <= gamma <= 1","SNESKSPSetParametersEW",kctx->gamma,&kctx->gamma,NULL));
10135f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscOptionsReal("-snes_ksp_ew_alpha","1 < alpha <= 2","SNESKSPSetParametersEW",kctx->alpha,&kctx->alpha,NULL));
10145f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscOptionsReal("-snes_ksp_ew_alpha2","alpha2","SNESKSPSetParametersEW",kctx->alpha2,&kctx->alpha2,NULL));
10155f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscOptionsReal("-snes_ksp_ew_threshold","0 < threshold < 1","SNESKSPSetParametersEW",kctx->threshold,&kctx->threshold,NULL));
1016186905e3SBarry Smith 
101790d69ab7SBarry Smith   flg  = PETSC_FALSE;
10185f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscOptionsBool("-snes_monitor_cancel","Remove all monitors","SNESMonitorCancel",flg,&flg,&set));
10195f80ce2aSJacob Faibussowitsch   if (set && flg) CHKERRQ(SNESMonitorCancel(snes));
1020eabae89aSBarry Smith 
10215f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESMonitorSetFromOptions(snes,"-snes_monitor","Monitor norm of function","SNESMonitorDefault",SNESMonitorDefault,SNESMonitorDefaultSetUp));
10225f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESMonitorSetFromOptions(snes,"-snes_monitor_short","Monitor norm of function with fewer digits","SNESMonitorDefaultShort",SNESMonitorDefaultShort,NULL));
10235f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESMonitorSetFromOptions(snes,"-snes_monitor_range","Monitor range of elements of function","SNESMonitorRange",SNESMonitorRange,NULL));
1024eabae89aSBarry Smith 
10255f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESMonitorSetFromOptions(snes,"-snes_monitor_ratio","Monitor ratios of the norm of function for consecutive steps","SNESMonitorRatio",SNESMonitorRatio,SNESMonitorRatioSetUp));
10265f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESMonitorSetFromOptions(snes,"-snes_monitor_field","Monitor norm of function (split into fields)","SNESMonitorDefaultField",SNESMonitorDefaultField,NULL));
10275f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESMonitorSetFromOptions(snes,"-snes_monitor_solution","View solution at each iteration","SNESMonitorSolution",SNESMonitorSolution,NULL));
10285f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESMonitorSetFromOptions(snes,"-snes_monitor_solution_update","View correction at each iteration","SNESMonitorSolutionUpdate",SNESMonitorSolutionUpdate,NULL));
10295f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESMonitorSetFromOptions(snes,"-snes_monitor_residual","View residual at each iteration","SNESMonitorResidual",SNESMonitorResidual,NULL));
10305f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESMonitorSetFromOptions(snes,"-snes_monitor_jacupdate_spectrum","Print the change in the spectrum of the Jacobian","SNESMonitorJacUpdateSpectrum",SNESMonitorJacUpdateSpectrum,NULL));
10315f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESMonitorSetFromOptions(snes,"-snes_monitor_fields","Monitor norm of function per field","SNESMonitorSet",SNESMonitorFields,NULL));
10325f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscOptionsBool("-snes_monitor_pause_final", "Pauses all draw monitors at the final iterate", "SNESMonitorPauseFinal_Internal", PETSC_FALSE, &snes->pauseFinal, NULL));
10332db13446SMatthew G. Knepley 
10345f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscOptionsString("-snes_monitor_python","Use Python function","SNESMonitorSet",NULL,monfilename,sizeof(monfilename),&flg));
10355f80ce2aSJacob Faibussowitsch   if (flg) CHKERRQ(PetscPythonMonitorSet((PetscObject)snes,monfilename));
10365180491cSLisandro Dalcin 
103790d69ab7SBarry Smith   flg  = PETSC_FALSE;
10385f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscOptionsBool("-snes_monitor_lg_range","Plot function range at each iteration","SNESMonitorLGRange",flg,&flg,NULL));
1039459f5d12SBarry Smith   if (flg) {
1040459f5d12SBarry Smith     PetscViewer ctx;
1041e24b481bSBarry Smith 
10425f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,&ctx));
10435f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESMonitorSet(snes,SNESMonitorLGRange,ctx,(PetscErrorCode (*)(void**))PetscViewerDestroy));
1044459f5d12SBarry Smith   }
10452e7541e6SPeter Brune 
104690d69ab7SBarry Smith   flg  = PETSC_FALSE;
10475f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscOptionsBool("-snes_converged_reason_view_cancel","Remove all converged reason viewers","SNESConvergedReasonViewCancel",flg,&flg,&set));
10485f80ce2aSJacob Faibussowitsch   if (set && flg) CHKERRQ(SNESConvergedReasonViewCancel(snes));
1049c4421ceaSFande Kong 
1050c4421ceaSFande Kong   flg  = PETSC_FALSE;
10515f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscOptionsBool("-snes_fd","Use finite differences (slow) to compute Jacobian","SNESComputeJacobianDefault",flg,&flg,NULL));
10524b27c08aSLois Curfman McInnes   if (flg) {
10536cab3a1bSJed Brown     void    *functx;
1054b1f624c7SBarry Smith     DM      dm;
1055b1f624c7SBarry Smith     DMSNES  sdm;
10565f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESGetDM(snes,&dm));
10575f80ce2aSJacob Faibussowitsch     CHKERRQ(DMGetDMSNES(dm,&sdm));
1058b1f624c7SBarry Smith     sdm->jacobianctx = NULL;
10595f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESGetFunction(snes,NULL,NULL,&functx));
10605f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESSetJacobian(snes,snes->jacobian,snes->jacobian_pre,SNESComputeJacobianDefault,functx));
10615f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscInfo(snes,"Setting default finite difference Jacobian matrix\n"));
10629b94acceSBarry Smith   }
1063639f9d9dSBarry Smith 
106444848bc4SPeter Brune   flg  = PETSC_FALSE;
10655f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscOptionsBool("-snes_fd_function","Use finite differences (slow) to compute function from user objective","SNESObjectiveComputeFunctionDefaultFD",flg,&flg,NULL));
106697584545SPeter Brune   if (flg) {
10675f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESSetFunction(snes,NULL,SNESObjectiveComputeFunctionDefaultFD,NULL));
106897584545SPeter Brune   }
106997584545SPeter Brune 
107097584545SPeter Brune   flg  = PETSC_FALSE;
10715f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscOptionsBool("-snes_fd_color","Use finite differences with coloring to compute Jacobian","SNESComputeJacobianDefaultColor",flg,&flg,NULL));
107244848bc4SPeter Brune   if (flg) {
1073c52e227fSPeter Brune     DM             dm;
1074c52e227fSPeter Brune     DMSNES         sdm;
10755f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESGetDM(snes,&dm));
10765f80ce2aSJacob Faibussowitsch     CHKERRQ(DMGetDMSNES(dm,&sdm));
1077aace71b7SPeter Brune     sdm->jacobianctx = NULL;
10785f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESSetJacobian(snes,snes->jacobian,snes->jacobian_pre,SNESComputeJacobianDefaultColor,NULL));
10795f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscInfo(snes,"Setting default finite difference coloring Jacobian matrix\n"));
108044848bc4SPeter Brune   }
108144848bc4SPeter Brune 
1082aa3661deSLisandro Dalcin   flg  = PETSC_FALSE;
10835f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscOptionsBool("-snes_mf_operator","Use a Matrix-Free Jacobian with user-provided preconditioner matrix","SNESSetUseMatrixFree",PETSC_FALSE,&snes->mf_operator,&flg));
1084d8f46077SPeter Brune   if (flg && snes->mf_operator) {
1085a8248277SBarry Smith     snes->mf_operator = PETSC_TRUE;
1086d8f46077SPeter Brune     snes->mf          = PETSC_TRUE;
1087a8248277SBarry Smith   }
1088aa3661deSLisandro Dalcin   flg  = PETSC_FALSE;
10895f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscOptionsBool("-snes_mf","Use a Matrix-Free Jacobian with no preconditioner matrix","SNESSetUseMatrixFree",PETSC_FALSE,&snes->mf,&flg));
1090d8f46077SPeter Brune   if (!flg && snes->mf_operator) snes->mf = PETSC_TRUE;
10915f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscOptionsInt("-snes_mf_version","Matrix-Free routines version 1 or 2","None",snes->mf_version,&snes->mf_version,NULL));
1092d28543b3SPeter Brune 
1093c40d0f55SPeter Brune   flg  = PETSC_FALSE;
10945f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESGetNPCSide(snes,&pcside));
10955f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscOptionsEnum("-snes_npc_side","SNES nonlinear preconditioner side","SNESSetNPCSide",PCSides,(PetscEnum)pcside,(PetscEnum*)&pcside,&flg));
10965f80ce2aSJacob Faibussowitsch   if (flg) CHKERRQ(SNESSetNPCSide(snes,pcside));
1097c40d0f55SPeter Brune 
1098e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
10998a70d858SHong Zhang   /*
11008a70d858SHong Zhang     Publish convergence information using SAWs
11018a70d858SHong Zhang   */
11028a70d858SHong Zhang   flg  = PETSC_FALSE;
11035f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscOptionsBool("-snes_monitor_saws","Publish SNES progress using SAWs","SNESMonitorSet",flg,&flg,NULL));
11048a70d858SHong Zhang   if (flg) {
11058a70d858SHong Zhang     void *ctx;
11065f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESMonitorSAWsCreate(snes,&ctx));
11075f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESMonitorSet(snes,SNESMonitorSAWs,ctx,SNESMonitorSAWsDestroy));
11088a70d858SHong Zhang   }
11098a70d858SHong Zhang #endif
11108a70d858SHong Zhang #if defined(PETSC_HAVE_SAWS)
1111b90c6cbeSBarry Smith   {
1112b90c6cbeSBarry Smith   PetscBool set;
1113b90c6cbeSBarry Smith   flg  = PETSC_FALSE;
11145f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscOptionsBool("-snes_saws_block","Block for SAWs at end of SNESSolve","PetscObjectSAWsBlock",((PetscObject)snes)->amspublishblock,&flg,&set));
1115b90c6cbeSBarry Smith   if (set) {
11165f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscObjectSAWsSetBlock((PetscObject)snes,flg));
1117b90c6cbeSBarry Smith   }
1118b90c6cbeSBarry Smith   }
1119b90c6cbeSBarry Smith #endif
1120b90c6cbeSBarry Smith 
112176b2cf59SMatthew Knepley   for (i = 0; i < numberofsetfromoptions; i++) {
11225f80ce2aSJacob Faibussowitsch     CHKERRQ((*othersetfromoptions[i])(snes));
112376b2cf59SMatthew Knepley   }
112476b2cf59SMatthew Knepley 
1125e7788613SBarry Smith   if (snes->ops->setfromoptions) {
11265f80ce2aSJacob Faibussowitsch     CHKERRQ((*snes->ops->setfromoptions)(PetscOptionsObject,snes));
1127639f9d9dSBarry Smith   }
11285d973c19SBarry Smith 
11295d973c19SBarry Smith   /* process any options handlers added with PetscObjectAddOptionsHandler() */
11305f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscObjectProcessOptionsHandlers(PetscOptionsObject,(PetscObject)snes));
1131b0a32e0cSBarry Smith   ierr = PetscOptionsEnd();CHKERRQ(ierr);
11324bbc92c1SBarry Smith 
1133d8d34be6SBarry Smith   if (snes->linesearch) {
11345f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESGetLineSearch(snes, &snes->linesearch));
11355f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESLineSearchSetFromOptions(snes->linesearch));
1136d8d34be6SBarry Smith   }
11379e764e56SPeter Brune 
11386aa5e7e9SBarry Smith   if (snes->usesksp) {
11395f80ce2aSJacob Faibussowitsch     if (!snes->ksp) CHKERRQ(SNESGetKSP(snes,&snes->ksp));
11405f80ce2aSJacob Faibussowitsch     CHKERRQ(KSPSetOperators(snes->ksp,snes->jacobian,snes->jacobian_pre));
11415f80ce2aSJacob Faibussowitsch     CHKERRQ(KSPSetFromOptions(snes->ksp));
11426aa5e7e9SBarry Smith   }
11436991f827SBarry Smith 
1144b5badacbSBarry Smith   /* if user has set the SNES NPC type via options database, create it. */
11455f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESGetOptionsPrefix(snes, &optionsprefix));
11465f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscOptionsHasName(((PetscObject)snes)->options,optionsprefix, "-npc_snes_type", &pcset));
1147efd4aadfSBarry Smith   if (pcset && (!snes->npc)) {
11485f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESGetNPC(snes, &snes->npc));
114951e86f29SPeter Brune   }
1150b5badacbSBarry Smith   if (snes->npc) {
11515f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESSetFromOptions(snes->npc));
1152b5badacbSBarry Smith   }
1153b3cd9a81SMatthew G. Knepley   snes->setfromoptionscalled++;
1154b3cd9a81SMatthew G. Knepley   PetscFunctionReturn(0);
1155b3cd9a81SMatthew G. Knepley }
1156b3cd9a81SMatthew G. Knepley 
1157b3cd9a81SMatthew G. Knepley /*@
1158b3cd9a81SMatthew G. Knepley    SNESResetFromOptions - Sets various SNES and KSP parameters from user options ONLY if the SNES was previously set from options
1159b3cd9a81SMatthew G. Knepley 
1160b3cd9a81SMatthew G. Knepley    Collective on SNES
1161b3cd9a81SMatthew G. Knepley 
1162b3cd9a81SMatthew G. Knepley    Input Parameter:
1163b3cd9a81SMatthew G. Knepley .  snes - the SNES context
1164b3cd9a81SMatthew G. Knepley 
1165b3cd9a81SMatthew G. Knepley    Level: beginner
1166b3cd9a81SMatthew G. Knepley 
1167b3cd9a81SMatthew G. Knepley .seealso: SNESSetFromOptions(), SNESSetOptionsPrefix()
1168b3cd9a81SMatthew G. Knepley @*/
1169b3cd9a81SMatthew G. Knepley PetscErrorCode SNESResetFromOptions(SNES snes)
1170b3cd9a81SMatthew G. Knepley {
1171b3cd9a81SMatthew G. Knepley   PetscFunctionBegin;
11725f80ce2aSJacob Faibussowitsch   if (snes->setfromoptionscalled) CHKERRQ(SNESSetFromOptions(snes));
11733a40ed3dSBarry Smith   PetscFunctionReturn(0);
11749b94acceSBarry Smith }
11759b94acceSBarry Smith 
1176bb9467b5SJed Brown /*@C
1177d25893d9SBarry Smith    SNESSetComputeApplicationContext - Sets an optional function to compute a user-defined context for
1178d25893d9SBarry Smith    the nonlinear solvers.
1179d25893d9SBarry Smith 
1180d25893d9SBarry Smith    Logically Collective on SNES
1181d25893d9SBarry Smith 
1182d25893d9SBarry Smith    Input Parameters:
1183d25893d9SBarry Smith +  snes - the SNES context
1184d25893d9SBarry Smith .  compute - function to compute the context
1185d25893d9SBarry Smith -  destroy - function to destroy the context
1186d25893d9SBarry Smith 
1187d25893d9SBarry Smith    Level: intermediate
1188d25893d9SBarry Smith 
1189bb9467b5SJed Brown    Notes:
1190bb9467b5SJed Brown    This function is currently not available from Fortran.
1191bb9467b5SJed Brown 
1192d25893d9SBarry Smith .seealso: SNESGetApplicationContext(), SNESSetComputeApplicationContext(), SNESGetApplicationContext()
1193d25893d9SBarry Smith @*/
1194d25893d9SBarry Smith PetscErrorCode  SNESSetComputeApplicationContext(SNES snes,PetscErrorCode (*compute)(SNES,void**),PetscErrorCode (*destroy)(void**))
1195d25893d9SBarry Smith {
1196d25893d9SBarry Smith   PetscFunctionBegin;
1197d25893d9SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
1198d25893d9SBarry Smith   snes->ops->usercompute = compute;
1199d25893d9SBarry Smith   snes->ops->userdestroy = destroy;
1200d25893d9SBarry Smith   PetscFunctionReturn(0);
1201d25893d9SBarry Smith }
1202a847f771SSatish Balay 
1203b07ff414SBarry Smith /*@
12049b94acceSBarry Smith    SNESSetApplicationContext - Sets the optional user-defined context for
12059b94acceSBarry Smith    the nonlinear solvers.
12069b94acceSBarry Smith 
12073f9fe445SBarry Smith    Logically Collective on SNES
1208fee21e36SBarry Smith 
1209c7afd0dbSLois Curfman McInnes    Input Parameters:
1210c7afd0dbSLois Curfman McInnes +  snes - the SNES context
1211c7afd0dbSLois Curfman McInnes -  usrP - optional user context
1212c7afd0dbSLois Curfman McInnes 
121336851e7fSLois Curfman McInnes    Level: intermediate
121436851e7fSLois Curfman McInnes 
121595452b02SPatrick Sanan    Fortran Notes:
121695452b02SPatrick Sanan     To use this from Fortran you must write a Fortran interface definition for this
1217daf670e6SBarry Smith     function that tells Fortran the Fortran derived data type that you are passing in as the ctx argument.
1218daf670e6SBarry Smith 
1219ecaffddaSVictor Eijkhout .seealso: SNESGetApplicationContext()
12209b94acceSBarry Smith @*/
12217087cfbeSBarry Smith PetscErrorCode  SNESSetApplicationContext(SNES snes,void *usrP)
12229b94acceSBarry Smith {
1223b07ff414SBarry Smith   KSP            ksp;
12241b2093e4SBarry Smith 
12253a40ed3dSBarry Smith   PetscFunctionBegin;
12260700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
12275f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESGetKSP(snes,&ksp));
12285f80ce2aSJacob Faibussowitsch   CHKERRQ(KSPSetApplicationContext(ksp,usrP));
12299b94acceSBarry Smith   snes->user = usrP;
12303a40ed3dSBarry Smith   PetscFunctionReturn(0);
12319b94acceSBarry Smith }
123274679c65SBarry Smith 
1233b07ff414SBarry Smith /*@
12349b94acceSBarry Smith    SNESGetApplicationContext - Gets the user-defined context for the
12359b94acceSBarry Smith    nonlinear solvers.
12369b94acceSBarry Smith 
1237c7afd0dbSLois Curfman McInnes    Not Collective
1238c7afd0dbSLois Curfman McInnes 
12399b94acceSBarry Smith    Input Parameter:
12409b94acceSBarry Smith .  snes - SNES context
12419b94acceSBarry Smith 
12429b94acceSBarry Smith    Output Parameter:
12439b94acceSBarry Smith .  usrP - user context
12449b94acceSBarry Smith 
124595452b02SPatrick Sanan    Fortran Notes:
124695452b02SPatrick Sanan     To use this from Fortran you must write a Fortran interface definition for this
1247daf670e6SBarry Smith     function that tells Fortran the Fortran derived data type that you are passing in as the ctx argument.
1248daf670e6SBarry Smith 
124936851e7fSLois Curfman McInnes    Level: intermediate
125036851e7fSLois Curfman McInnes 
12519b94acceSBarry Smith .seealso: SNESSetApplicationContext()
12529b94acceSBarry Smith @*/
1253e71120c6SJed Brown PetscErrorCode  SNESGetApplicationContext(SNES snes,void *usrP)
12549b94acceSBarry Smith {
12553a40ed3dSBarry Smith   PetscFunctionBegin;
12560700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
1257e71120c6SJed Brown   *(void**)usrP = snes->user;
12583a40ed3dSBarry Smith   PetscFunctionReturn(0);
12599b94acceSBarry Smith }
126074679c65SBarry Smith 
12619b94acceSBarry Smith /*@
1262ec5066bdSBarry Smith    SNESSetUseMatrixFree - indicates that SNES should use matrix free finite difference matrix vector products internally to apply the Jacobian.
12633565c898SBarry Smith 
12643565c898SBarry Smith    Collective on SNES
12653565c898SBarry Smith 
12663565c898SBarry Smith    Input Parameters:
12673565c898SBarry Smith +  snes - SNES context
12684ddffce6SLisandro Dalcin .  mf_operator - use matrix-free only for the Amat used by SNESSetJacobian(), this means the user provided Pmat will continue to be used
12694ddffce6SLisandro Dalcin -  mf - use matrix-free for both the Amat and Pmat used by SNESSetJacobian(), both the Amat and Pmat set in SNESSetJacobian() will be ignored
12703565c898SBarry Smith 
12713565c898SBarry Smith    Options Database:
12723565c898SBarry Smith + -snes_mf - use matrix free for both the mat and pmat operator
1273ec5066bdSBarry Smith . -snes_mf_operator - use matrix free only for the mat operator
1274ec5066bdSBarry Smith . -snes_fd_color - compute the Jacobian via coloring and finite differences.
1275ec5066bdSBarry Smith - -snes_fd - compute the Jacobian via finite differences (slow)
12763565c898SBarry Smith 
12773565c898SBarry Smith    Level: intermediate
12783565c898SBarry Smith 
1279ec5066bdSBarry Smith    Notes:
1280a5b23f4aSJose E. Roman       SNES supports three approaches for computing (approximate) Jacobians: user provided via SNESSetJacobian(), matrix free, and computing explicitly with
1281ec5066bdSBarry Smith       finite differences and coloring using MatFDColoring. It is also possible to use automatic differentiation and the MatFDColoring object.
1282ec5066bdSBarry Smith 
1283ec5066bdSBarry Smith .seealso:   SNESGetUseMatrixFree(), MatCreateSNESMF(), SNESComputeJacobianDefaultColor()
12843565c898SBarry Smith @*/
12853565c898SBarry Smith PetscErrorCode  SNESSetUseMatrixFree(SNES snes,PetscBool mf_operator,PetscBool mf)
12863565c898SBarry Smith {
12873565c898SBarry Smith   PetscFunctionBegin;
12883565c898SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
128988b4c220SStefano Zampini   PetscValidLogicalCollectiveBool(snes,mf_operator,2);
129088b4c220SStefano Zampini   PetscValidLogicalCollectiveBool(snes,mf,3);
12914ddffce6SLisandro Dalcin   snes->mf          = mf_operator ? PETSC_TRUE : mf;
12923565c898SBarry Smith   snes->mf_operator = mf_operator;
12933565c898SBarry Smith   PetscFunctionReturn(0);
12943565c898SBarry Smith }
12953565c898SBarry Smith 
12963565c898SBarry Smith /*@
1297ec5066bdSBarry Smith    SNESGetUseMatrixFree - indicates if the SNES uses matrix free finite difference matrix vector products to apply the Jacobian.
12983565c898SBarry Smith 
12993565c898SBarry Smith    Collective on SNES
13003565c898SBarry Smith 
13013565c898SBarry Smith    Input Parameter:
13023565c898SBarry Smith .  snes - SNES context
13033565c898SBarry Smith 
13043565c898SBarry Smith    Output Parameters:
13054ddffce6SLisandro Dalcin +  mf_operator - use matrix-free only for the Amat used by SNESSetJacobian(), this means the user provided Pmat will continue to be used
13064ddffce6SLisandro Dalcin -  mf - use matrix-free for both the Amat and Pmat used by SNESSetJacobian(), both the Amat and Pmat set in SNESSetJacobian() will be ignored
13073565c898SBarry Smith 
13083565c898SBarry Smith    Options Database:
13093565c898SBarry Smith + -snes_mf - use matrix free for both the mat and pmat operator
13103565c898SBarry Smith - -snes_mf_operator - use matrix free only for the mat operator
13113565c898SBarry Smith 
13123565c898SBarry Smith    Level: intermediate
13133565c898SBarry Smith 
13143565c898SBarry Smith .seealso:   SNESSetUseMatrixFree(), MatCreateSNESMF()
13153565c898SBarry Smith @*/
13163565c898SBarry Smith PetscErrorCode  SNESGetUseMatrixFree(SNES snes,PetscBool *mf_operator,PetscBool *mf)
13173565c898SBarry Smith {
13183565c898SBarry Smith   PetscFunctionBegin;
13193565c898SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
13203565c898SBarry Smith   if (mf)          *mf          = snes->mf;
13213565c898SBarry Smith   if (mf_operator) *mf_operator = snes->mf_operator;
13223565c898SBarry Smith   PetscFunctionReturn(0);
13233565c898SBarry Smith }
13243565c898SBarry Smith 
13253565c898SBarry Smith /*@
1326c8228a4eSBarry Smith    SNESGetIterationNumber - Gets the number of nonlinear iterations completed
1327c8228a4eSBarry Smith    at this time.
13289b94acceSBarry Smith 
1329c7afd0dbSLois Curfman McInnes    Not Collective
1330c7afd0dbSLois Curfman McInnes 
13319b94acceSBarry Smith    Input Parameter:
13329b94acceSBarry Smith .  snes - SNES context
13339b94acceSBarry Smith 
13349b94acceSBarry Smith    Output Parameter:
13359b94acceSBarry Smith .  iter - iteration number
13369b94acceSBarry Smith 
1337c8228a4eSBarry Smith    Notes:
1338c8228a4eSBarry Smith    For example, during the computation of iteration 2 this would return 1.
1339c8228a4eSBarry Smith 
1340c8228a4eSBarry Smith    This is useful for using lagged Jacobians (where one does not recompute the
134108405cd6SLois Curfman McInnes    Jacobian at each SNES iteration). For example, the code
134208405cd6SLois Curfman McInnes .vb
134308405cd6SLois Curfman McInnes       ierr = SNESGetIterationNumber(snes,&it);
134408405cd6SLois Curfman McInnes       if (!(it % 2)) {
134508405cd6SLois Curfman McInnes         [compute Jacobian here]
134608405cd6SLois Curfman McInnes       }
134708405cd6SLois Curfman McInnes .ve
1348c8228a4eSBarry Smith    can be used in your ComputeJacobian() function to cause the Jacobian to be
134908405cd6SLois Curfman McInnes    recomputed every second SNES iteration.
1350c8228a4eSBarry Smith 
1351c04deec6SBarry Smith    After the SNES solve is complete this will return the number of nonlinear iterations used.
1352c04deec6SBarry Smith 
135336851e7fSLois Curfman McInnes    Level: intermediate
135436851e7fSLois Curfman McInnes 
135571dbe336SPeter Brune .seealso:   SNESGetLinearSolveIterations()
13569b94acceSBarry Smith @*/
13577087cfbeSBarry Smith PetscErrorCode  SNESGetIterationNumber(SNES snes,PetscInt *iter)
13589b94acceSBarry Smith {
13593a40ed3dSBarry Smith   PetscFunctionBegin;
13600700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
13614482741eSBarry Smith   PetscValidIntPointer(iter,2);
13629b94acceSBarry Smith   *iter = snes->iter;
13633a40ed3dSBarry Smith   PetscFunctionReturn(0);
13649b94acceSBarry Smith }
136574679c65SBarry Smith 
1366360c497dSPeter Brune /*@
1367360c497dSPeter Brune    SNESSetIterationNumber - Sets the current iteration number.
1368360c497dSPeter Brune 
1369360c497dSPeter Brune    Not Collective
1370360c497dSPeter Brune 
1371d8d19677SJose E. Roman    Input Parameters:
1372a2b725a8SWilliam Gropp +  snes - SNES context
1373a2b725a8SWilliam Gropp -  iter - iteration number
1374360c497dSPeter Brune 
1375360c497dSPeter Brune    Level: developer
1376360c497dSPeter Brune 
137771dbe336SPeter Brune .seealso:   SNESGetLinearSolveIterations()
1378360c497dSPeter Brune @*/
1379360c497dSPeter Brune PetscErrorCode  SNESSetIterationNumber(SNES snes,PetscInt iter)
1380360c497dSPeter Brune {
1381360c497dSPeter Brune   PetscFunctionBegin;
1382360c497dSPeter Brune   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
13835f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscObjectSAWsTakeAccess((PetscObject)snes));
1384360c497dSPeter Brune   snes->iter = iter;
13855f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscObjectSAWsGrantAccess((PetscObject)snes));
1386360c497dSPeter Brune   PetscFunctionReturn(0);
1387360c497dSPeter Brune }
1388360c497dSPeter Brune 
13899b94acceSBarry Smith /*@
1390b850b91aSLisandro Dalcin    SNESGetNonlinearStepFailures - Gets the number of unsuccessful steps
13919b94acceSBarry Smith    attempted by the nonlinear solver.
13929b94acceSBarry Smith 
1393c7afd0dbSLois Curfman McInnes    Not Collective
1394c7afd0dbSLois Curfman McInnes 
13959b94acceSBarry Smith    Input Parameter:
13969b94acceSBarry Smith .  snes - SNES context
13979b94acceSBarry Smith 
13989b94acceSBarry Smith    Output Parameter:
13999b94acceSBarry Smith .  nfails - number of unsuccessful steps attempted
14009b94acceSBarry Smith 
1401c96a6f78SLois Curfman McInnes    Notes:
1402c96a6f78SLois Curfman McInnes    This counter is reset to zero for each successive call to SNESSolve().
1403c96a6f78SLois Curfman McInnes 
140436851e7fSLois Curfman McInnes    Level: intermediate
140536851e7fSLois Curfman McInnes 
1406e1c61ce8SBarry Smith .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(),
140758ebbce7SBarry Smith           SNESSetMaxNonlinearStepFailures(), SNESGetMaxNonlinearStepFailures()
14089b94acceSBarry Smith @*/
14097087cfbeSBarry Smith PetscErrorCode  SNESGetNonlinearStepFailures(SNES snes,PetscInt *nfails)
14109b94acceSBarry Smith {
14113a40ed3dSBarry Smith   PetscFunctionBegin;
14120700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
14134482741eSBarry Smith   PetscValidIntPointer(nfails,2);
141450ffb88aSMatthew Knepley   *nfails = snes->numFailures;
141550ffb88aSMatthew Knepley   PetscFunctionReturn(0);
141650ffb88aSMatthew Knepley }
141750ffb88aSMatthew Knepley 
141850ffb88aSMatthew Knepley /*@
1419b850b91aSLisandro Dalcin    SNESSetMaxNonlinearStepFailures - Sets the maximum number of unsuccessful steps
142050ffb88aSMatthew Knepley    attempted by the nonlinear solver before it gives up.
142150ffb88aSMatthew Knepley 
142250ffb88aSMatthew Knepley    Not Collective
142350ffb88aSMatthew Knepley 
142450ffb88aSMatthew Knepley    Input Parameters:
142550ffb88aSMatthew Knepley +  snes     - SNES context
142650ffb88aSMatthew Knepley -  maxFails - maximum of unsuccessful steps
142750ffb88aSMatthew Knepley 
142850ffb88aSMatthew Knepley    Level: intermediate
142950ffb88aSMatthew Knepley 
1430e1c61ce8SBarry Smith .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(),
143158ebbce7SBarry Smith           SNESGetMaxNonlinearStepFailures(), SNESGetNonlinearStepFailures()
143250ffb88aSMatthew Knepley @*/
14337087cfbeSBarry Smith PetscErrorCode  SNESSetMaxNonlinearStepFailures(SNES snes, PetscInt maxFails)
143450ffb88aSMatthew Knepley {
143550ffb88aSMatthew Knepley   PetscFunctionBegin;
14360700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
143750ffb88aSMatthew Knepley   snes->maxFailures = maxFails;
143850ffb88aSMatthew Knepley   PetscFunctionReturn(0);
143950ffb88aSMatthew Knepley }
144050ffb88aSMatthew Knepley 
144150ffb88aSMatthew Knepley /*@
1442b850b91aSLisandro Dalcin    SNESGetMaxNonlinearStepFailures - Gets the maximum number of unsuccessful steps
144350ffb88aSMatthew Knepley    attempted by the nonlinear solver before it gives up.
144450ffb88aSMatthew Knepley 
144550ffb88aSMatthew Knepley    Not Collective
144650ffb88aSMatthew Knepley 
144750ffb88aSMatthew Knepley    Input Parameter:
144850ffb88aSMatthew Knepley .  snes     - SNES context
144950ffb88aSMatthew Knepley 
145050ffb88aSMatthew Knepley    Output Parameter:
145150ffb88aSMatthew Knepley .  maxFails - maximum of unsuccessful steps
145250ffb88aSMatthew Knepley 
145350ffb88aSMatthew Knepley    Level: intermediate
145450ffb88aSMatthew Knepley 
1455e1c61ce8SBarry Smith .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(),
145658ebbce7SBarry Smith           SNESSetMaxNonlinearStepFailures(), SNESGetNonlinearStepFailures()
145758ebbce7SBarry Smith 
145850ffb88aSMatthew Knepley @*/
14597087cfbeSBarry Smith PetscErrorCode  SNESGetMaxNonlinearStepFailures(SNES snes, PetscInt *maxFails)
146050ffb88aSMatthew Knepley {
146150ffb88aSMatthew Knepley   PetscFunctionBegin;
14620700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
14634482741eSBarry Smith   PetscValidIntPointer(maxFails,2);
146450ffb88aSMatthew Knepley   *maxFails = snes->maxFailures;
14653a40ed3dSBarry Smith   PetscFunctionReturn(0);
14669b94acceSBarry Smith }
1467a847f771SSatish Balay 
14682541af92SBarry Smith /*@
14692541af92SBarry Smith    SNESGetNumberFunctionEvals - Gets the number of user provided function evaluations
14702541af92SBarry Smith      done by SNES.
14712541af92SBarry Smith 
14722541af92SBarry Smith    Not Collective
14732541af92SBarry Smith 
14742541af92SBarry Smith    Input Parameter:
14752541af92SBarry Smith .  snes     - SNES context
14762541af92SBarry Smith 
14772541af92SBarry Smith    Output Parameter:
14782541af92SBarry Smith .  nfuncs - number of evaluations
14792541af92SBarry Smith 
14802541af92SBarry Smith    Level: intermediate
14812541af92SBarry Smith 
148295452b02SPatrick Sanan    Notes:
148395452b02SPatrick Sanan     Reset every time SNESSolve is called unless SNESSetCountersReset() is used.
1484971e163fSPeter Brune 
1485971e163fSPeter Brune .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(), SNESSetCountersReset()
14862541af92SBarry Smith @*/
14877087cfbeSBarry Smith PetscErrorCode  SNESGetNumberFunctionEvals(SNES snes, PetscInt *nfuncs)
14882541af92SBarry Smith {
14892541af92SBarry Smith   PetscFunctionBegin;
14900700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
14912541af92SBarry Smith   PetscValidIntPointer(nfuncs,2);
14922541af92SBarry Smith   *nfuncs = snes->nfuncs;
14932541af92SBarry Smith   PetscFunctionReturn(0);
14942541af92SBarry Smith }
14952541af92SBarry Smith 
14963d4c4710SBarry Smith /*@
14973d4c4710SBarry Smith    SNESGetLinearSolveFailures - Gets the number of failed (non-converged)
14983d4c4710SBarry Smith    linear solvers.
14993d4c4710SBarry Smith 
15003d4c4710SBarry Smith    Not Collective
15013d4c4710SBarry Smith 
15023d4c4710SBarry Smith    Input Parameter:
15033d4c4710SBarry Smith .  snes - SNES context
15043d4c4710SBarry Smith 
15053d4c4710SBarry Smith    Output Parameter:
15063d4c4710SBarry Smith .  nfails - number of failed solves
15073d4c4710SBarry Smith 
15089d85da0cSMatthew G. Knepley    Level: intermediate
15099d85da0cSMatthew G. Knepley 
15109d85da0cSMatthew G. Knepley    Options Database Keys:
15119d85da0cSMatthew G. Knepley . -snes_max_linear_solve_fail <num> - The number of failures before the solve is terminated
15129d85da0cSMatthew G. Knepley 
15133d4c4710SBarry Smith    Notes:
15143d4c4710SBarry Smith    This counter is reset to zero for each successive call to SNESSolve().
15153d4c4710SBarry Smith 
1516e1c61ce8SBarry Smith .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures()
15173d4c4710SBarry Smith @*/
15187087cfbeSBarry Smith PetscErrorCode  SNESGetLinearSolveFailures(SNES snes,PetscInt *nfails)
15193d4c4710SBarry Smith {
15203d4c4710SBarry Smith   PetscFunctionBegin;
15210700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
15223d4c4710SBarry Smith   PetscValidIntPointer(nfails,2);
15233d4c4710SBarry Smith   *nfails = snes->numLinearSolveFailures;
15243d4c4710SBarry Smith   PetscFunctionReturn(0);
15253d4c4710SBarry Smith }
15263d4c4710SBarry Smith 
15273d4c4710SBarry Smith /*@
15283d4c4710SBarry Smith    SNESSetMaxLinearSolveFailures - the number of failed linear solve attempts
15293d4c4710SBarry Smith    allowed before SNES returns with a diverged reason of SNES_DIVERGED_LINEAR_SOLVE
15303d4c4710SBarry Smith 
15313f9fe445SBarry Smith    Logically Collective on SNES
15323d4c4710SBarry Smith 
15333d4c4710SBarry Smith    Input Parameters:
15343d4c4710SBarry Smith +  snes     - SNES context
15353d4c4710SBarry Smith -  maxFails - maximum allowed linear solve failures
15363d4c4710SBarry Smith 
15373d4c4710SBarry Smith    Level: intermediate
15383d4c4710SBarry Smith 
15399d85da0cSMatthew G. Knepley    Options Database Keys:
15409d85da0cSMatthew G. Knepley . -snes_max_linear_solve_fail <num> - The number of failures before the solve is terminated
15419d85da0cSMatthew G. Knepley 
154295452b02SPatrick Sanan    Notes:
154395452b02SPatrick Sanan     By default this is 0; that is SNES returns on the first failed linear solve
15443d4c4710SBarry Smith 
154558ebbce7SBarry Smith .seealso: SNESGetLinearSolveFailures(), SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations()
15463d4c4710SBarry Smith @*/
15477087cfbeSBarry Smith PetscErrorCode  SNESSetMaxLinearSolveFailures(SNES snes, PetscInt maxFails)
15483d4c4710SBarry Smith {
15493d4c4710SBarry Smith   PetscFunctionBegin;
15500700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
1551c5eb9154SBarry Smith   PetscValidLogicalCollectiveInt(snes,maxFails,2);
15523d4c4710SBarry Smith   snes->maxLinearSolveFailures = maxFails;
15533d4c4710SBarry Smith   PetscFunctionReturn(0);
15543d4c4710SBarry Smith }
15553d4c4710SBarry Smith 
15563d4c4710SBarry Smith /*@
15573d4c4710SBarry Smith    SNESGetMaxLinearSolveFailures - gets the maximum number of linear solve failures that
15583d4c4710SBarry Smith      are allowed before SNES terminates
15593d4c4710SBarry Smith 
15603d4c4710SBarry Smith    Not Collective
15613d4c4710SBarry Smith 
15623d4c4710SBarry Smith    Input Parameter:
15633d4c4710SBarry Smith .  snes     - SNES context
15643d4c4710SBarry Smith 
15653d4c4710SBarry Smith    Output Parameter:
15663d4c4710SBarry Smith .  maxFails - maximum of unsuccessful solves allowed
15673d4c4710SBarry Smith 
15683d4c4710SBarry Smith    Level: intermediate
15693d4c4710SBarry Smith 
157095452b02SPatrick Sanan    Notes:
157195452b02SPatrick Sanan     By default this is 1; that is SNES returns on the first failed linear solve
15723d4c4710SBarry Smith 
1573e1c61ce8SBarry Smith .seealso: SNESGetLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(),
15743d4c4710SBarry Smith @*/
15757087cfbeSBarry Smith PetscErrorCode  SNESGetMaxLinearSolveFailures(SNES snes, PetscInt *maxFails)
15763d4c4710SBarry Smith {
15773d4c4710SBarry Smith   PetscFunctionBegin;
15780700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
15793d4c4710SBarry Smith   PetscValidIntPointer(maxFails,2);
15803d4c4710SBarry Smith   *maxFails = snes->maxLinearSolveFailures;
15813d4c4710SBarry Smith   PetscFunctionReturn(0);
15823d4c4710SBarry Smith }
15833d4c4710SBarry Smith 
1584c96a6f78SLois Curfman McInnes /*@
1585b850b91aSLisandro Dalcin    SNESGetLinearSolveIterations - Gets the total number of linear iterations
1586c96a6f78SLois Curfman McInnes    used by the nonlinear solver.
1587c96a6f78SLois Curfman McInnes 
1588c7afd0dbSLois Curfman McInnes    Not Collective
1589c7afd0dbSLois Curfman McInnes 
1590c96a6f78SLois Curfman McInnes    Input Parameter:
1591c96a6f78SLois Curfman McInnes .  snes - SNES context
1592c96a6f78SLois Curfman McInnes 
1593c96a6f78SLois Curfman McInnes    Output Parameter:
1594c96a6f78SLois Curfman McInnes .  lits - number of linear iterations
1595c96a6f78SLois Curfman McInnes 
1596c96a6f78SLois Curfman McInnes    Notes:
1597971e163fSPeter Brune    This counter is reset to zero for each successive call to SNESSolve() unless SNESSetCountersReset() is used.
1598c96a6f78SLois Curfman McInnes 
1599010be392SBarry Smith    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
1600010be392SBarry Smith    then call KSPGetIterationNumber() after the failed solve.
1601010be392SBarry Smith 
160236851e7fSLois Curfman McInnes    Level: intermediate
160336851e7fSLois Curfman McInnes 
160471dbe336SPeter Brune .seealso:  SNESGetIterationNumber(), SNESGetLinearSolveFailures(), SNESGetMaxLinearSolveFailures(), SNESSetCountersReset()
1605c96a6f78SLois Curfman McInnes @*/
16067087cfbeSBarry Smith PetscErrorCode  SNESGetLinearSolveIterations(SNES snes,PetscInt *lits)
1607c96a6f78SLois Curfman McInnes {
16083a40ed3dSBarry Smith   PetscFunctionBegin;
16090700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
16104482741eSBarry Smith   PetscValidIntPointer(lits,2);
1611c96a6f78SLois Curfman McInnes   *lits = snes->linear_its;
16123a40ed3dSBarry Smith   PetscFunctionReturn(0);
1613c96a6f78SLois Curfman McInnes }
1614c96a6f78SLois Curfman McInnes 
1615971e163fSPeter Brune /*@
1616971e163fSPeter Brune    SNESSetCountersReset - Sets whether or not the counters for linear iterations and function evaluations
1617971e163fSPeter Brune    are reset every time SNESSolve() is called.
1618971e163fSPeter Brune 
1619971e163fSPeter Brune    Logically Collective on SNES
1620971e163fSPeter Brune 
1621d8d19677SJose E. Roman    Input Parameters:
1622971e163fSPeter Brune +  snes - SNES context
1623971e163fSPeter Brune -  reset - whether to reset the counters or not
1624971e163fSPeter Brune 
1625971e163fSPeter Brune    Notes:
1626fa19ca70SBarry Smith    This defaults to PETSC_TRUE
1627971e163fSPeter Brune 
1628971e163fSPeter Brune    Level: developer
1629971e163fSPeter Brune 
1630734794cfSBarry Smith .seealso:  SNESGetNumberFunctionEvals(), SNESGetLinearSolveIterations(), SNESGetNPC()
1631971e163fSPeter Brune @*/
1632971e163fSPeter Brune PetscErrorCode  SNESSetCountersReset(SNES snes,PetscBool reset)
1633971e163fSPeter Brune {
1634971e163fSPeter Brune   PetscFunctionBegin;
1635971e163fSPeter Brune   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
1636971e163fSPeter Brune   PetscValidLogicalCollectiveBool(snes,reset,2);
1637971e163fSPeter Brune   snes->counters_reset = reset;
1638971e163fSPeter Brune   PetscFunctionReturn(0);
1639971e163fSPeter Brune }
1640971e163fSPeter Brune 
16412999313aSBarry Smith /*@
16422999313aSBarry Smith    SNESSetKSP - Sets a KSP context for the SNES object to use
16432999313aSBarry Smith 
16442999313aSBarry Smith    Not Collective, but the SNES and KSP objects must live on the same MPI_Comm
16452999313aSBarry Smith 
16462999313aSBarry Smith    Input Parameters:
16472999313aSBarry Smith +  snes - the SNES context
16482999313aSBarry Smith -  ksp - the KSP context
16492999313aSBarry Smith 
16502999313aSBarry Smith    Notes:
16512999313aSBarry Smith    The SNES object already has its KSP object, you can obtain with SNESGetKSP()
16522999313aSBarry Smith    so this routine is rarely needed.
16532999313aSBarry Smith 
16542999313aSBarry Smith    The KSP object that is already in the SNES object has its reference count
16552999313aSBarry Smith    decreased by one.
16562999313aSBarry Smith 
16572999313aSBarry Smith    Level: developer
16582999313aSBarry Smith 
16592999313aSBarry Smith .seealso: KSPGetPC(), SNESCreate(), KSPCreate(), SNESSetKSP()
16602999313aSBarry Smith @*/
16617087cfbeSBarry Smith PetscErrorCode  SNESSetKSP(SNES snes,KSP ksp)
16622999313aSBarry Smith {
16632999313aSBarry Smith   PetscFunctionBegin;
16640700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
16650700a824SBarry Smith   PetscValidHeaderSpecific(ksp,KSP_CLASSID,2);
16662999313aSBarry Smith   PetscCheckSameComm(snes,1,ksp,2);
16675f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscObjectReference((PetscObject)ksp));
16685f80ce2aSJacob Faibussowitsch   if (snes->ksp) CHKERRQ(PetscObjectDereference((PetscObject)snes->ksp));
16692999313aSBarry Smith   snes->ksp = ksp;
16702999313aSBarry Smith   PetscFunctionReturn(0);
16712999313aSBarry Smith }
16722999313aSBarry Smith 
16739b94acceSBarry Smith /* -----------------------------------------------------------*/
167452baeb72SSatish Balay /*@
16759b94acceSBarry Smith    SNESCreate - Creates a nonlinear solver context.
16769b94acceSBarry Smith 
1677d083f849SBarry Smith    Collective
1678c7afd0dbSLois Curfman McInnes 
1679c7afd0dbSLois Curfman McInnes    Input Parameters:
1680906ed7ccSBarry Smith .  comm - MPI communicator
16819b94acceSBarry Smith 
16829b94acceSBarry Smith    Output Parameter:
16839b94acceSBarry Smith .  outsnes - the new SNES context
16849b94acceSBarry Smith 
1685c7afd0dbSLois Curfman McInnes    Options Database Keys:
1686c7afd0dbSLois Curfman McInnes +   -snes_mf - Activates default matrix-free Jacobian-vector products,
1687c7afd0dbSLois Curfman McInnes                and no preconditioning matrix
1688c7afd0dbSLois Curfman McInnes .   -snes_mf_operator - Activates default matrix-free Jacobian-vector
1689c7afd0dbSLois Curfman McInnes                products, and a user-provided preconditioning matrix
1690c7afd0dbSLois Curfman McInnes                as set by SNESSetJacobian()
1691c7afd0dbSLois Curfman McInnes -   -snes_fd - Uses (slow!) finite differences to compute Jacobian
1692c1f60f51SBarry Smith 
169336851e7fSLois Curfman McInnes    Level: beginner
169436851e7fSLois Curfman McInnes 
169595452b02SPatrick Sanan    Developer Notes:
169695452b02SPatrick Sanan     SNES always creates a KSP object even though many SNES methods do not use it. This is
1697efd4aadfSBarry Smith                     unfortunate and should be fixed at some point. The flag snes->usesksp indicates if the
1698efd4aadfSBarry Smith                     particular method does use KSP and regulates if the information about the KSP is printed
1699efd4aadfSBarry Smith                     in SNESView(). TSSetFromOptions() does call SNESSetFromOptions() which can lead to users being confused
1700efd4aadfSBarry Smith                     by help messages about meaningless SNES options.
1701efd4aadfSBarry Smith 
1702efd4aadfSBarry Smith                     SNES always creates the snes->kspconvctx even though it is used by only one type. This should
1703efd4aadfSBarry Smith                     be fixed.
1704efd4aadfSBarry Smith 
17053d5a8a6aSBarry Smith .seealso: SNESSolve(), SNESDestroy(), SNES, SNESSetLagPreconditioner(), SNESSetLagJacobian()
1706a8054027SBarry Smith 
17079b94acceSBarry Smith @*/
17087087cfbeSBarry Smith PetscErrorCode  SNESCreate(MPI_Comm comm,SNES *outsnes)
17099b94acceSBarry Smith {
17109b94acceSBarry Smith   SNES           snes;
1711fa9f3622SBarry Smith   SNESKSPEW      *kctx;
171237fcc0dbSBarry Smith 
17133a40ed3dSBarry Smith   PetscFunctionBegin;
1714ed1caa07SMatthew Knepley   PetscValidPointer(outsnes,2);
17150298fd71SBarry Smith   *outsnes = NULL;
17165f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESInitializePackage());
17178ba1e511SMatthew Knepley 
17185f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscHeaderCreate(snes,SNES_CLASSID,"SNES","Nonlinear solver","SNES",comm,SNESDestroy,SNESView));
17197adad957SLisandro Dalcin 
17208d359177SBarry Smith   snes->ops->converged    = SNESConvergedDefault;
17212c155ee1SBarry Smith   snes->usesksp           = PETSC_TRUE;
172288976e71SPeter Brune   snes->tolerancesset     = PETSC_FALSE;
17239b94acceSBarry Smith   snes->max_its           = 50;
17249750a799SBarry Smith   snes->max_funcs         = 10000;
17259b94acceSBarry Smith   snes->norm              = 0.0;
1726c1e67a49SFande Kong   snes->xnorm             = 0.0;
1727c1e67a49SFande Kong   snes->ynorm             = 0.0;
1728365a6726SPeter Brune   snes->normschedule      = SNES_NORM_ALWAYS;
17296c67d002SPeter Brune   snes->functype          = SNES_FUNCTION_DEFAULT;
17303a2046daSBarry Smith #if defined(PETSC_USE_REAL_SINGLE)
17313a2046daSBarry Smith   snes->rtol              = 1.e-5;
17323a2046daSBarry Smith #else
1733b4874afaSBarry Smith   snes->rtol              = 1.e-8;
17343a2046daSBarry Smith #endif
1735b4874afaSBarry Smith   snes->ttol              = 0.0;
17363a2046daSBarry Smith #if defined(PETSC_USE_REAL_SINGLE)
17373a2046daSBarry Smith   snes->abstol            = 1.e-25;
17383a2046daSBarry Smith #else
173970441072SBarry Smith   snes->abstol            = 1.e-50;
17403a2046daSBarry Smith #endif
17417cd0ae37SLisandro Dalcin #if defined(PETSC_USE_REAL_SINGLE)
17427cd0ae37SLisandro Dalcin   snes->stol              = 1.e-5;
17437cd0ae37SLisandro Dalcin #else
1744c60f73f4SPeter Brune   snes->stol              = 1.e-8;
17457cd0ae37SLisandro Dalcin #endif
17463a2046daSBarry Smith #if defined(PETSC_USE_REAL_SINGLE)
17473a2046daSBarry Smith   snes->deltatol          = 1.e-6;
17483a2046daSBarry Smith #else
17494b27c08aSLois Curfman McInnes   snes->deltatol          = 1.e-12;
17503a2046daSBarry Smith #endif
1751e37c518bSBarry Smith   snes->divtol            = 1.e4;
1752e37c518bSBarry Smith   snes->rnorm0            = 0;
17539b94acceSBarry Smith   snes->nfuncs            = 0;
175450ffb88aSMatthew Knepley   snes->numFailures       = 0;
175550ffb88aSMatthew Knepley   snes->maxFailures       = 1;
17567a00f4a9SLois Curfman McInnes   snes->linear_its        = 0;
1757e35cf81dSBarry Smith   snes->lagjacobian       = 1;
175837ec4e1aSPeter Brune   snes->jac_iter          = 0;
175937ec4e1aSPeter Brune   snes->lagjac_persist    = PETSC_FALSE;
1760a8054027SBarry Smith   snes->lagpreconditioner = 1;
176137ec4e1aSPeter Brune   snes->pre_iter          = 0;
176237ec4e1aSPeter Brune   snes->lagpre_persist    = PETSC_FALSE;
1763639f9d9dSBarry Smith   snes->numbermonitors    = 0;
1764c4421ceaSFande Kong   snes->numberreasonviews = 0;
17659e5d0892SLisandro Dalcin   snes->data              = NULL;
17664dc4c822SBarry Smith   snes->setupcalled       = PETSC_FALSE;
1767186905e3SBarry Smith   snes->ksp_ewconv        = PETSC_FALSE;
17686f24a144SLois Curfman McInnes   snes->nwork             = 0;
17699e5d0892SLisandro Dalcin   snes->work              = NULL;
177058c9b817SLisandro Dalcin   snes->nvwork            = 0;
17719e5d0892SLisandro Dalcin   snes->vwork             = NULL;
1772758f92a0SBarry Smith   snes->conv_hist_len     = 0;
1773758f92a0SBarry Smith   snes->conv_hist_max     = 0;
17740298fd71SBarry Smith   snes->conv_hist         = NULL;
17750298fd71SBarry Smith   snes->conv_hist_its     = NULL;
1776758f92a0SBarry Smith   snes->conv_hist_reset   = PETSC_TRUE;
1777971e163fSPeter Brune   snes->counters_reset    = PETSC_TRUE;
1778e4ed7901SPeter Brune   snes->vec_func_init_set = PETSC_FALSE;
1779184914b5SBarry Smith   snes->reason            = SNES_CONVERGED_ITERATING;
1780efd4aadfSBarry Smith   snes->npcside           = PC_RIGHT;
1781b3cd9a81SMatthew G. Knepley   snes->setfromoptionscalled = 0;
1782c40d0f55SPeter Brune 
1783d8f46077SPeter Brune   snes->mf          = PETSC_FALSE;
1784d8f46077SPeter Brune   snes->mf_operator = PETSC_FALSE;
1785d8f46077SPeter Brune   snes->mf_version  = 1;
1786d8f46077SPeter Brune 
17873d4c4710SBarry Smith   snes->numLinearSolveFailures = 0;
17883d4c4710SBarry Smith   snes->maxLinearSolveFailures = 1;
17893d4c4710SBarry Smith 
1790349187a7SBarry Smith   snes->vizerotolerance = 1.e-8;
179176bd3646SJed Brown   snes->checkjacdomainerror = PetscDefined(USE_DEBUG) ? PETSC_TRUE : PETSC_FALSE;
1792349187a7SBarry Smith 
17934fc747eaSLawrence Mitchell   /* Set this to true if the implementation of SNESSolve_XXX does compute the residual at the final solution. */
17944fc747eaSLawrence Mitchell   snes->alwayscomputesfinalresidual = PETSC_FALSE;
17954fc747eaSLawrence Mitchell 
17969b94acceSBarry Smith   /* Create context to compute Eisenstat-Walker relative tolerance for KSP */
17975f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscNewLog(snes,&kctx));
1798f5af7f23SKarl Rupp 
17999b94acceSBarry Smith   snes->kspconvctx  = (void*)kctx;
18009b94acceSBarry Smith   kctx->version     = 2;
18019b94acceSBarry Smith   kctx->rtol_0      = .3; /* Eisenstat and Walker suggest rtol_0=.5, but
18029b94acceSBarry Smith                              this was too large for some test cases */
180375567043SBarry Smith   kctx->rtol_last   = 0.0;
18049b94acceSBarry Smith   kctx->rtol_max    = .9;
18059b94acceSBarry Smith   kctx->gamma       = 1.0;
180662d1f40fSBarry Smith   kctx->alpha       = .5*(1.0 + PetscSqrtReal(5.0));
180771f87433Sdalcinl   kctx->alpha2      = kctx->alpha;
18089b94acceSBarry Smith   kctx->threshold   = .1;
180975567043SBarry Smith   kctx->lresid_last = 0.0;
181075567043SBarry Smith   kctx->norm_last   = 0.0;
18119b94acceSBarry Smith 
18129b94acceSBarry Smith   *outsnes = snes;
18133a40ed3dSBarry Smith   PetscFunctionReturn(0);
18149b94acceSBarry Smith }
18159b94acceSBarry Smith 
181688f0584fSBarry Smith /*MC
1817411c0326SBarry Smith     SNESFunction - Functional form used to convey the nonlinear function to be solved by SNES
181888f0584fSBarry Smith 
181988f0584fSBarry Smith      Synopsis:
1820411c0326SBarry Smith      #include "petscsnes.h"
1821411c0326SBarry Smith      PetscErrorCode SNESFunction(SNES snes,Vec x,Vec f,void *ctx);
182288f0584fSBarry Smith 
18231843f636SBarry Smith      Collective on snes
18241843f636SBarry Smith 
182588f0584fSBarry Smith      Input Parameters:
182688f0584fSBarry Smith +     snes - the SNES context
182788f0584fSBarry Smith .     x    - state at which to evaluate residual
182888f0584fSBarry Smith -     ctx     - optional user-defined function context, passed in with SNESSetFunction()
182988f0584fSBarry Smith 
183088f0584fSBarry Smith      Output Parameter:
183188f0584fSBarry Smith .     f  - vector to put residual (function value)
183288f0584fSBarry Smith 
1833878cb397SSatish Balay    Level: intermediate
1834878cb397SSatish Balay 
183588f0584fSBarry Smith .seealso:   SNESSetFunction(), SNESGetFunction()
183688f0584fSBarry Smith M*/
183788f0584fSBarry Smith 
18389b94acceSBarry Smith /*@C
18399b94acceSBarry Smith    SNESSetFunction - Sets the function evaluation routine and function
18409b94acceSBarry Smith    vector for use by the SNES routines in solving systems of nonlinear
18419b94acceSBarry Smith    equations.
18429b94acceSBarry Smith 
18433f9fe445SBarry Smith    Logically Collective on SNES
1844fee21e36SBarry Smith 
1845c7afd0dbSLois Curfman McInnes    Input Parameters:
1846c7afd0dbSLois Curfman McInnes +  snes - the SNES context
18476b7fb656SBarry Smith .  r - vector to store function values, may be NULL
1848f8b49ee9SBarry Smith .  f - function evaluation routine; see SNESFunction for calling sequence details
1849c7afd0dbSLois Curfman McInnes -  ctx - [optional] user-defined context for private data for the
18500298fd71SBarry Smith          function evaluation routine (may be NULL)
18519b94acceSBarry Smith 
18529b94acceSBarry Smith    Notes:
18539b94acceSBarry Smith    The Newton-like methods typically solve linear systems of the form
18549b94acceSBarry Smith $      f'(x) x = -f(x),
1855c7afd0dbSLois Curfman McInnes    where f'(x) denotes the Jacobian matrix and f(x) is the function.
18569b94acceSBarry Smith 
185736851e7fSLois Curfman McInnes    Level: beginner
185836851e7fSLois Curfman McInnes 
1859bf388a1fSBarry Smith .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetPicard(), SNESFunction
18609b94acceSBarry Smith @*/
1861f8b49ee9SBarry Smith PetscErrorCode  SNESSetFunction(SNES snes,Vec r,PetscErrorCode (*f)(SNES,Vec,Vec,void*),void *ctx)
18629b94acceSBarry Smith {
18636cab3a1bSJed Brown   DM             dm;
18646cab3a1bSJed Brown 
18653a40ed3dSBarry Smith   PetscFunctionBegin;
18660700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
1867d2a683ecSLisandro Dalcin   if (r) {
1868d2a683ecSLisandro Dalcin     PetscValidHeaderSpecific(r,VEC_CLASSID,2);
1869d2a683ecSLisandro Dalcin     PetscCheckSameComm(snes,1,r,2);
18705f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscObjectReference((PetscObject)r));
18715f80ce2aSJacob Faibussowitsch     CHKERRQ(VecDestroy(&snes->vec_func));
187285385478SLisandro Dalcin     snes->vec_func = r;
1873d2a683ecSLisandro Dalcin   }
18745f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESGetDM(snes,&dm));
18755f80ce2aSJacob Faibussowitsch   CHKERRQ(DMSNESSetFunction(dm,f,ctx));
1876bbc1464cSBarry Smith   if (f == SNESPicardComputeFunction) {
18775f80ce2aSJacob Faibussowitsch     CHKERRQ(DMSNESSetMFFunction(dm,SNESPicardComputeMFFunction,ctx));
1878bbc1464cSBarry Smith   }
18793a40ed3dSBarry Smith   PetscFunctionReturn(0);
18809b94acceSBarry Smith }
18819b94acceSBarry Smith 
1882e4ed7901SPeter Brune /*@C
1883e4ed7901SPeter Brune    SNESSetInitialFunction - Sets the function vector to be used as the
1884e4ed7901SPeter Brune    function norm at the initialization of the method.  In some
1885e4ed7901SPeter Brune    instances, the user has precomputed the function before calling
1886e4ed7901SPeter Brune    SNESSolve.  This function allows one to avoid a redundant call
1887e4ed7901SPeter Brune    to SNESComputeFunction in that case.
1888e4ed7901SPeter Brune 
1889e4ed7901SPeter Brune    Logically Collective on SNES
1890e4ed7901SPeter Brune 
1891e4ed7901SPeter Brune    Input Parameters:
1892e4ed7901SPeter Brune +  snes - the SNES context
1893e4ed7901SPeter Brune -  f - vector to store function value
1894e4ed7901SPeter Brune 
1895e4ed7901SPeter Brune    Notes:
1896e4ed7901SPeter Brune    This should not be modified during the solution procedure.
1897e4ed7901SPeter Brune 
1898e4ed7901SPeter Brune    This is used extensively in the SNESFAS hierarchy and in nonlinear preconditioning.
1899e4ed7901SPeter Brune 
1900e4ed7901SPeter Brune    Level: developer
1901e4ed7901SPeter Brune 
1902e4ed7901SPeter Brune .seealso: SNESSetFunction(), SNESComputeFunction(), SNESSetInitialFunctionNorm()
1903e4ed7901SPeter Brune @*/
1904e4ed7901SPeter Brune PetscErrorCode  SNESSetInitialFunction(SNES snes, Vec f)
1905e4ed7901SPeter Brune {
1906e4ed7901SPeter Brune   Vec            vec_func;
1907e4ed7901SPeter Brune 
1908e4ed7901SPeter Brune   PetscFunctionBegin;
1909e4ed7901SPeter Brune   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
1910e4ed7901SPeter Brune   PetscValidHeaderSpecific(f,VEC_CLASSID,2);
1911e4ed7901SPeter Brune   PetscCheckSameComm(snes,1,f,2);
1912efd4aadfSBarry Smith   if (snes->npcside == PC_LEFT && snes->functype == SNES_FUNCTION_PRECONDITIONED) {
1913902f982fSPeter Brune     snes->vec_func_init_set = PETSC_FALSE;
1914902f982fSPeter Brune     PetscFunctionReturn(0);
1915902f982fSPeter Brune   }
19165f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESGetFunction(snes,&vec_func,NULL,NULL));
19175f80ce2aSJacob Faibussowitsch   CHKERRQ(VecCopy(f,vec_func));
1918f5af7f23SKarl Rupp 
1919217b9c2eSPeter Brune   snes->vec_func_init_set = PETSC_TRUE;
1920e4ed7901SPeter Brune   PetscFunctionReturn(0);
1921e4ed7901SPeter Brune }
1922e4ed7901SPeter Brune 
1923534ebe21SPeter Brune /*@
1924a5b23f4aSJose E. Roman    SNESSetNormSchedule - Sets the SNESNormSchedule used in convergence and monitoring
1925534ebe21SPeter Brune    of the SNES method.
1926534ebe21SPeter Brune 
1927534ebe21SPeter Brune    Logically Collective on SNES
1928534ebe21SPeter Brune 
1929534ebe21SPeter Brune    Input Parameters:
1930534ebe21SPeter Brune +  snes - the SNES context
1931365a6726SPeter Brune -  normschedule - the frequency of norm computation
1932534ebe21SPeter Brune 
1933517f1916SMatthew G. Knepley    Options Database Key:
193467b8a455SSatish Balay .  -snes_norm_schedule <none, always, initialonly, finalonly, initialfinalonly> - set the schedule
1935517f1916SMatthew G. Knepley 
1936534ebe21SPeter Brune    Notes:
1937365a6726SPeter Brune    Only certain SNES methods support certain SNESNormSchedules.  Most require evaluation
1938534ebe21SPeter Brune    of the nonlinear function and the taking of its norm at every iteration to
1939534ebe21SPeter Brune    even ensure convergence at all.  However, methods such as custom Gauss-Seidel methods
1940a5b23f4aSJose E. Roman    (SNESNGS) and the like do not require the norm of the function to be computed, and therefore
1941534ebe21SPeter Brune    may either be monitored for convergence or not.  As these are often used as nonlinear
1942534ebe21SPeter Brune    preconditioners, monitoring the norm of their error is not a useful enterprise within
1943534ebe21SPeter Brune    their solution.
1944534ebe21SPeter Brune 
1945534ebe21SPeter Brune    Level: developer
1946534ebe21SPeter Brune 
1947365a6726SPeter Brune .seealso: SNESGetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1948534ebe21SPeter Brune @*/
1949365a6726SPeter Brune PetscErrorCode  SNESSetNormSchedule(SNES snes, SNESNormSchedule normschedule)
1950534ebe21SPeter Brune {
1951534ebe21SPeter Brune   PetscFunctionBegin;
1952534ebe21SPeter Brune   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
1953365a6726SPeter Brune   snes->normschedule = normschedule;
1954534ebe21SPeter Brune   PetscFunctionReturn(0);
1955534ebe21SPeter Brune }
1956534ebe21SPeter Brune 
1957534ebe21SPeter Brune /*@
1958a5b23f4aSJose E. Roman    SNESGetNormSchedule - Gets the SNESNormSchedule used in convergence and monitoring
1959534ebe21SPeter Brune    of the SNES method.
1960534ebe21SPeter Brune 
1961534ebe21SPeter Brune    Logically Collective on SNES
1962534ebe21SPeter Brune 
1963534ebe21SPeter Brune    Input Parameters:
1964534ebe21SPeter Brune +  snes - the SNES context
1965365a6726SPeter Brune -  normschedule - the type of the norm used
1966534ebe21SPeter Brune 
1967534ebe21SPeter Brune    Level: advanced
1968534ebe21SPeter Brune 
1969365a6726SPeter Brune .seealso: SNESSetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1970534ebe21SPeter Brune @*/
1971365a6726SPeter Brune PetscErrorCode  SNESGetNormSchedule(SNES snes, SNESNormSchedule *normschedule)
1972534ebe21SPeter Brune {
1973534ebe21SPeter Brune   PetscFunctionBegin;
1974534ebe21SPeter Brune   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
1975365a6726SPeter Brune   *normschedule = snes->normschedule;
1976534ebe21SPeter Brune   PetscFunctionReturn(0);
1977534ebe21SPeter Brune }
1978534ebe21SPeter Brune 
1979c5ce4427SMatthew G. Knepley /*@
1980c5ce4427SMatthew G. Knepley   SNESSetFunctionNorm - Sets the last computed residual norm.
1981c5ce4427SMatthew G. Knepley 
1982c5ce4427SMatthew G. Knepley   Logically Collective on SNES
1983c5ce4427SMatthew G. Knepley 
1984c5ce4427SMatthew G. Knepley   Input Parameters:
1985c5ce4427SMatthew G. Knepley + snes - the SNES context
1986c5ce4427SMatthew G. Knepley 
1987c5ce4427SMatthew G. Knepley - normschedule - the frequency of norm computation
1988c5ce4427SMatthew G. Knepley 
1989c5ce4427SMatthew G. Knepley   Level: developer
1990c5ce4427SMatthew G. Knepley 
1991c5ce4427SMatthew G. Knepley .seealso: SNESGetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1992c5ce4427SMatthew G. Knepley @*/
1993c5ce4427SMatthew G. Knepley PetscErrorCode SNESSetFunctionNorm(SNES snes, PetscReal norm)
1994c5ce4427SMatthew G. Knepley {
1995c5ce4427SMatthew G. Knepley   PetscFunctionBegin;
1996c5ce4427SMatthew G. Knepley   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
1997c5ce4427SMatthew G. Knepley   snes->norm = norm;
1998c5ce4427SMatthew G. Knepley   PetscFunctionReturn(0);
1999c5ce4427SMatthew G. Knepley }
2000c5ce4427SMatthew G. Knepley 
2001c5ce4427SMatthew G. Knepley /*@
2002c5ce4427SMatthew G. Knepley   SNESGetFunctionNorm - Gets the last computed norm of the residual
2003c5ce4427SMatthew G. Knepley 
2004c5ce4427SMatthew G. Knepley   Not Collective
2005c5ce4427SMatthew G. Knepley 
2006c5ce4427SMatthew G. Knepley   Input Parameter:
2007c5ce4427SMatthew G. Knepley . snes - the SNES context
2008c5ce4427SMatthew G. Knepley 
2009c5ce4427SMatthew G. Knepley   Output Parameter:
2010c5ce4427SMatthew G. Knepley . norm - the last computed residual norm
2011c5ce4427SMatthew G. Knepley 
2012c5ce4427SMatthew G. Knepley   Level: developer
2013c5ce4427SMatthew G. Knepley 
2014c5ce4427SMatthew G. Knepley .seealso: SNESSetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
2015c5ce4427SMatthew G. Knepley @*/
2016c5ce4427SMatthew G. Knepley PetscErrorCode SNESGetFunctionNorm(SNES snes, PetscReal *norm)
2017c5ce4427SMatthew G. Knepley {
2018c5ce4427SMatthew G. Knepley   PetscFunctionBegin;
2019c5ce4427SMatthew G. Knepley   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
2020*dadcf809SJacob Faibussowitsch   PetscValidRealPointer(norm, 2);
2021c5ce4427SMatthew G. Knepley   *norm = snes->norm;
2022c5ce4427SMatthew G. Knepley   PetscFunctionReturn(0);
2023c5ce4427SMatthew G. Knepley }
2024c5ce4427SMatthew G. Knepley 
2025c1e67a49SFande Kong /*@
2026c1e67a49SFande Kong   SNESGetUpdateNorm - Gets the last computed norm of the Newton update
2027c1e67a49SFande Kong 
2028c1e67a49SFande Kong   Not Collective
2029c1e67a49SFande Kong 
2030c1e67a49SFande Kong   Input Parameter:
2031c1e67a49SFande Kong . snes - the SNES context
2032c1e67a49SFande Kong 
2033c1e67a49SFande Kong   Output Parameter:
2034c1e67a49SFande Kong . ynorm - the last computed update norm
2035c1e67a49SFande Kong 
2036c1e67a49SFande Kong   Level: developer
2037c1e67a49SFande Kong 
2038c1e67a49SFande Kong .seealso: SNESSetNormSchedule(), SNESComputeFunction(), SNESGetFunctionNorm()
2039c1e67a49SFande Kong @*/
2040c1e67a49SFande Kong PetscErrorCode SNESGetUpdateNorm(SNES snes, PetscReal *ynorm)
2041c1e67a49SFande Kong {
2042c1e67a49SFande Kong   PetscFunctionBegin;
2043c1e67a49SFande Kong   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
2044*dadcf809SJacob Faibussowitsch   PetscValidRealPointer(ynorm, 2);
2045c1e67a49SFande Kong   *ynorm = snes->ynorm;
2046c1e67a49SFande Kong   PetscFunctionReturn(0);
2047c1e67a49SFande Kong }
2048c1e67a49SFande Kong 
2049c1e67a49SFande Kong /*@
20504591eaf2SFande Kong   SNESGetSolutionNorm - Gets the last computed norm of the solution
2051c1e67a49SFande Kong 
2052c1e67a49SFande Kong   Not Collective
2053c1e67a49SFande Kong 
2054c1e67a49SFande Kong   Input Parameter:
2055c1e67a49SFande Kong . snes - the SNES context
2056c1e67a49SFande Kong 
2057c1e67a49SFande Kong   Output Parameter:
2058c1e67a49SFande Kong . xnorm - the last computed solution norm
2059c1e67a49SFande Kong 
2060c1e67a49SFande Kong   Level: developer
2061c1e67a49SFande Kong 
2062c1e67a49SFande Kong .seealso: SNESSetNormSchedule(), SNESComputeFunction(), SNESGetFunctionNorm(), SNESGetUpdateNorm()
2063c1e67a49SFande Kong @*/
2064c1e67a49SFande Kong PetscErrorCode SNESGetSolutionNorm(SNES snes, PetscReal *xnorm)
2065c1e67a49SFande Kong {
2066c1e67a49SFande Kong   PetscFunctionBegin;
2067c1e67a49SFande Kong   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
2068*dadcf809SJacob Faibussowitsch   PetscValidRealPointer(xnorm, 2);
2069c1e67a49SFande Kong   *xnorm = snes->xnorm;
2070c1e67a49SFande Kong   PetscFunctionReturn(0);
2071c1e67a49SFande Kong }
2072c1e67a49SFande Kong 
207347073ea2SPeter Brune /*@C
2074a5b23f4aSJose E. Roman    SNESSetFunctionType - Sets the SNESNormSchedule used in convergence and monitoring
207547073ea2SPeter Brune    of the SNES method.
207647073ea2SPeter Brune 
207747073ea2SPeter Brune    Logically Collective on SNES
207847073ea2SPeter Brune 
207947073ea2SPeter Brune    Input Parameters:
208047073ea2SPeter Brune +  snes - the SNES context
208147073ea2SPeter Brune -  normschedule - the frequency of norm computation
208247073ea2SPeter Brune 
208347073ea2SPeter Brune    Notes:
208447073ea2SPeter Brune    Only certain SNES methods support certain SNESNormSchedules.  Most require evaluation
208547073ea2SPeter Brune    of the nonlinear function and the taking of its norm at every iteration to
208647073ea2SPeter Brune    even ensure convergence at all.  However, methods such as custom Gauss-Seidel methods
2087a5b23f4aSJose E. Roman    (SNESNGS) and the like do not require the norm of the function to be computed, and therefore
208847073ea2SPeter Brune    may either be monitored for convergence or not.  As these are often used as nonlinear
208947073ea2SPeter Brune    preconditioners, monitoring the norm of their error is not a useful enterprise within
209047073ea2SPeter Brune    their solution.
209147073ea2SPeter Brune 
209247073ea2SPeter Brune    Level: developer
209347073ea2SPeter Brune 
209447073ea2SPeter Brune .seealso: SNESGetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
209547073ea2SPeter Brune @*/
209647073ea2SPeter Brune PetscErrorCode  SNESSetFunctionType(SNES snes, SNESFunctionType type)
209747073ea2SPeter Brune {
209847073ea2SPeter Brune   PetscFunctionBegin;
209947073ea2SPeter Brune   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
210047073ea2SPeter Brune   snes->functype = type;
210147073ea2SPeter Brune   PetscFunctionReturn(0);
210247073ea2SPeter Brune }
210347073ea2SPeter Brune 
210447073ea2SPeter Brune /*@C
2105a5b23f4aSJose E. Roman    SNESGetFunctionType - Gets the SNESNormSchedule used in convergence and monitoring
210647073ea2SPeter Brune    of the SNES method.
210747073ea2SPeter Brune 
210847073ea2SPeter Brune    Logically Collective on SNES
210947073ea2SPeter Brune 
211047073ea2SPeter Brune    Input Parameters:
211147073ea2SPeter Brune +  snes - the SNES context
211247073ea2SPeter Brune -  normschedule - the type of the norm used
211347073ea2SPeter Brune 
211447073ea2SPeter Brune    Level: advanced
211547073ea2SPeter Brune 
211647073ea2SPeter Brune .seealso: SNESSetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
211747073ea2SPeter Brune @*/
211847073ea2SPeter Brune PetscErrorCode  SNESGetFunctionType(SNES snes, SNESFunctionType *type)
211947073ea2SPeter Brune {
212047073ea2SPeter Brune   PetscFunctionBegin;
212147073ea2SPeter Brune   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
212247073ea2SPeter Brune   *type = snes->functype;
2123534ebe21SPeter Brune   PetscFunctionReturn(0);
2124534ebe21SPeter Brune }
2125534ebe21SPeter Brune 
2126bf388a1fSBarry Smith /*MC
2127be95d8f1SBarry Smith     SNESNGSFunction - function used to convey a Gauss-Seidel sweep on the nonlinear function
2128bf388a1fSBarry Smith 
2129bf388a1fSBarry Smith      Synopsis:
2130aaa7dc30SBarry Smith      #include <petscsnes.h>
2131be95d8f1SBarry Smith $    SNESNGSFunction(SNES snes,Vec x,Vec b,void *ctx);
2132bf388a1fSBarry Smith 
21331843f636SBarry Smith      Collective on snes
21341843f636SBarry Smith 
21351843f636SBarry Smith      Input Parameters:
2136bf388a1fSBarry Smith +  X   - solution vector
2137bf388a1fSBarry Smith .  B   - RHS vector
2138bf388a1fSBarry Smith -  ctx - optional user-defined Gauss-Seidel context
2139bf388a1fSBarry Smith 
21401843f636SBarry Smith      Output Parameter:
21411843f636SBarry Smith .  X   - solution vector
21421843f636SBarry Smith 
2143878cb397SSatish Balay    Level: intermediate
2144878cb397SSatish Balay 
2145be95d8f1SBarry Smith .seealso:   SNESSetNGS(), SNESGetNGS()
2146bf388a1fSBarry Smith M*/
2147bf388a1fSBarry Smith 
2148c79ef259SPeter Brune /*@C
2149be95d8f1SBarry Smith    SNESSetNGS - Sets the user nonlinear Gauss-Seidel routine for
2150c79ef259SPeter Brune    use with composed nonlinear solvers.
2151c79ef259SPeter Brune 
2152c79ef259SPeter Brune    Input Parameters:
2153c79ef259SPeter Brune +  snes   - the SNES context
2154be95d8f1SBarry Smith .  f - function evaluation routine to apply Gauss-Seidel see SNESNGSFunction
2155c79ef259SPeter Brune -  ctx    - [optional] user-defined context for private data for the
21560298fd71SBarry Smith             smoother evaluation routine (may be NULL)
2157c79ef259SPeter Brune 
2158c79ef259SPeter Brune    Notes:
2159be95d8f1SBarry Smith    The NGS routines are used by the composed nonlinear solver to generate
2160c79ef259SPeter Brune     a problem appropriate update to the solution, particularly FAS.
2161c79ef259SPeter Brune 
2162d28543b3SPeter Brune    Level: intermediate
2163c79ef259SPeter Brune 
2164be95d8f1SBarry Smith .seealso: SNESGetFunction(), SNESComputeNGS()
2165c79ef259SPeter Brune @*/
2166be95d8f1SBarry Smith PetscErrorCode SNESSetNGS(SNES snes,PetscErrorCode (*f)(SNES,Vec,Vec,void*),void *ctx)
21676cab3a1bSJed Brown {
21686cab3a1bSJed Brown   DM             dm;
21696cab3a1bSJed Brown 
2170646217ecSPeter Brune   PetscFunctionBegin;
21716cab3a1bSJed Brown   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
21725f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESGetDM(snes,&dm));
21735f80ce2aSJacob Faibussowitsch   CHKERRQ(DMSNESSetNGS(dm,f,ctx));
2174646217ecSPeter Brune   PetscFunctionReturn(0);
2175646217ecSPeter Brune }
2176646217ecSPeter Brune 
2177bbc1464cSBarry Smith /*
2178bbc1464cSBarry Smith      This is used for -snes_mf_operator; it uses a duplicate of snes->jacobian_pre because snes->jacobian_pre cannot be
2179bbc1464cSBarry Smith    changed during the KSPSolve()
2180bbc1464cSBarry Smith */
2181bbc1464cSBarry Smith PetscErrorCode SNESPicardComputeMFFunction(SNES snes,Vec x,Vec f,void *ctx)
2182bbc1464cSBarry Smith {
2183bbc1464cSBarry Smith   DM             dm;
2184bbc1464cSBarry Smith   DMSNES         sdm;
2185bbc1464cSBarry Smith 
2186bbc1464cSBarry Smith   PetscFunctionBegin;
21875f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESGetDM(snes,&dm));
21885f80ce2aSJacob Faibussowitsch   CHKERRQ(DMGetDMSNES(dm,&sdm));
21895f80ce2aSJacob Faibussowitsch   PetscCheck(sdm->ops->computepjacobian,PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetPicard() to provide Picard Jacobian.");
2190bbc1464cSBarry Smith   /*  A(x)*x - b(x) */
2191bbc1464cSBarry Smith   if (sdm->ops->computepfunction) {
2192bbc1464cSBarry Smith     PetscStackPush("SNES Picard user function");
21935f80ce2aSJacob Faibussowitsch     CHKERRQ((*sdm->ops->computepfunction)(snes,x,f,sdm->pctx));
2194bbc1464cSBarry Smith     PetscStackPop;
21955f80ce2aSJacob Faibussowitsch     CHKERRQ(VecScale(f,-1.0));
2196bbc1464cSBarry Smith     if (!snes->picard) {
21970df40c35SBarry Smith       /* Cannot share nonzero pattern because of the possible use of SNESComputeJacobianDefault() */
21985f80ce2aSJacob Faibussowitsch       CHKERRQ(MatDuplicate(snes->jacobian_pre,MAT_DO_NOT_COPY_VALUES,&snes->picard));
2199bbc1464cSBarry Smith     }
2200bbc1464cSBarry Smith     PetscStackPush("SNES Picard user Jacobian");
22015f80ce2aSJacob Faibussowitsch     CHKERRQ((*sdm->ops->computepjacobian)(snes,x,snes->picard,snes->picard,sdm->pctx));
2202bbc1464cSBarry Smith     PetscStackPop;
22035f80ce2aSJacob Faibussowitsch     CHKERRQ(MatMultAdd(snes->picard,x,f,f));
2204bbc1464cSBarry Smith   } else {
2205bbc1464cSBarry Smith     PetscStackPush("SNES Picard user Jacobian");
22065f80ce2aSJacob Faibussowitsch     CHKERRQ((*sdm->ops->computepjacobian)(snes,x,snes->picard,snes->picard,sdm->pctx));
2207bbc1464cSBarry Smith     PetscStackPop;
22085f80ce2aSJacob Faibussowitsch     CHKERRQ(MatMult(snes->picard,x,f));
2209bbc1464cSBarry Smith   }
2210bbc1464cSBarry Smith   PetscFunctionReturn(0);
2211bbc1464cSBarry Smith }
2212bbc1464cSBarry Smith 
221325acbd8eSLisandro Dalcin PetscErrorCode SNESPicardComputeFunction(SNES snes,Vec x,Vec f,void *ctx)
22148b0a5094SBarry Smith {
2215e03ab78fSPeter Brune   DM             dm;
2216942e3340SBarry Smith   DMSNES         sdm;
22176cab3a1bSJed Brown 
22188b0a5094SBarry Smith   PetscFunctionBegin;
22195f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESGetDM(snes,&dm));
22205f80ce2aSJacob Faibussowitsch   CHKERRQ(DMGetDMSNES(dm,&sdm));
22215f80ce2aSJacob Faibussowitsch   PetscCheck(sdm->ops->computepjacobian,PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetPicard() to provide Picard Jacobian.");
22228b0a5094SBarry Smith   /*  A(x)*x - b(x) */
2223bbc1464cSBarry Smith   if (sdm->ops->computepfunction) {
222425acbd8eSLisandro Dalcin     PetscStackPush("SNES Picard user function");
22255f80ce2aSJacob Faibussowitsch     CHKERRQ((*sdm->ops->computepfunction)(snes,x,f,sdm->pctx));
222625acbd8eSLisandro Dalcin     PetscStackPop;
22275f80ce2aSJacob Faibussowitsch     CHKERRQ(VecScale(f,-1.0));
222825acbd8eSLisandro Dalcin     PetscStackPush("SNES Picard user Jacobian");
22295f80ce2aSJacob Faibussowitsch     CHKERRQ((*sdm->ops->computepjacobian)(snes,x,snes->jacobian,snes->jacobian_pre,sdm->pctx));
223025acbd8eSLisandro Dalcin     PetscStackPop;
22315f80ce2aSJacob Faibussowitsch     CHKERRQ(MatMultAdd(snes->jacobian_pre,x,f,f));
2232bbc1464cSBarry Smith   } else {
2233bbc1464cSBarry Smith     PetscStackPush("SNES Picard user Jacobian");
22345f80ce2aSJacob Faibussowitsch     CHKERRQ((*sdm->ops->computepjacobian)(snes,x,snes->jacobian,snes->jacobian_pre,sdm->pctx));
2235bbc1464cSBarry Smith     PetscStackPop;
22365f80ce2aSJacob Faibussowitsch     CHKERRQ(MatMult(snes->jacobian_pre,x,f));
2237bbc1464cSBarry Smith   }
22388b0a5094SBarry Smith   PetscFunctionReturn(0);
22398b0a5094SBarry Smith }
22408b0a5094SBarry Smith 
224125acbd8eSLisandro Dalcin PetscErrorCode SNESPicardComputeJacobian(SNES snes,Vec x1,Mat J,Mat B,void *ctx)
22428b0a5094SBarry Smith {
22438b0a5094SBarry Smith   PetscFunctionBegin;
2244e03ab78fSPeter Brune   /* the jacobian matrix should be pre-filled in SNESPicardComputeFunction */
2245bbc1464cSBarry Smith   /* must assembly if matrix-free to get the last SNES solution */
22465f80ce2aSJacob Faibussowitsch   CHKERRQ(MatAssemblyBegin(J,MAT_FINAL_ASSEMBLY));
22475f80ce2aSJacob Faibussowitsch   CHKERRQ(MatAssemblyEnd(J,MAT_FINAL_ASSEMBLY));
22488b0a5094SBarry Smith   PetscFunctionReturn(0);
22498b0a5094SBarry Smith }
22508b0a5094SBarry Smith 
22518b0a5094SBarry Smith /*@C
2252bbc1464cSBarry Smith    SNESSetPicard - Use SNES to solve the system A(x) x = bp(x) + b via a Picard type iteration (Picard linearization)
22538b0a5094SBarry Smith 
22548b0a5094SBarry Smith    Logically Collective on SNES
22558b0a5094SBarry Smith 
22568b0a5094SBarry Smith    Input Parameters:
22578b0a5094SBarry Smith +  snes - the SNES context
22586b7fb656SBarry Smith .  r - vector to store function values, may be NULL
22596b7fb656SBarry Smith .  bp - function evaluation routine, may be NULL
22606b7fb656SBarry Smith .  Amat - matrix with which A(x) x - bp(x) - b is to be computed
2261e5d3d808SBarry Smith .  Pmat - matrix from which preconditioner is computed (usually the same as Amat)
22626b7fb656SBarry Smith .  J  - function to compute matrix values, see SNESJacobianFunction() for details on its calling sequence
22636b7fb656SBarry Smith -  ctx - [optional] user-defined context for private data for the function evaluation routine (may be NULL)
22648b0a5094SBarry Smith 
22658b0a5094SBarry Smith    Notes:
22666b7fb656SBarry Smith     It is often better to provide the nonlinear function F() and some approximation to its Jacobian directly and use
2267f450aa47SBarry Smith     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.
2268f450aa47SBarry Smith 
22698b0a5094SBarry Smith     One can call SNESSetPicard() or SNESSetFunction() (and possibly SNESSetJacobian()) but cannot call both
22708b0a5094SBarry Smith 
22716b7fb656SBarry Smith $     Solves the equation A(x) x = bp(x) - b via the defect correction algorithm A(x^{n}) (x^{n+1} - x^{n}) = bp(x^{n}) + b - A(x^{n})x^{n}
22726b7fb656SBarry Smith $     Note that when an exact solver is used this corresponds to the "classic" Picard A(x^{n}) x^{n+1} = bp(x^{n}) + b iteration.
22738b0a5094SBarry Smith 
22748b0a5094SBarry Smith      Run with -snes_mf_operator to solve the system with Newton's method using A(x^{n}) to construct the preconditioner.
22758b0a5094SBarry Smith 
22760d04baf8SBarry Smith    We implement the defect correction form of the Picard iteration because it converges much more generally when inexact linear solvers are used then
22776b7fb656SBarry Smith    the direct Picard iteration A(x^n) x^{n+1} = bp(x^n) + b
22788b0a5094SBarry Smith 
22798b0a5094SBarry Smith    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
22808b0a5094SBarry Smith    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
22818b0a5094SBarry Smith    different please contact us at petsc-dev@mcs.anl.gov and we'll have an entirely new argument :-).
22828b0a5094SBarry Smith 
22836b7fb656SBarry Smith    When used with -snes_mf_operator this will run matrix-free Newton's method where the matrix-vector product is of the true Jacobian of A(x)x - bp(x) -b.
22846b7fb656SBarry Smith 
22856b7fb656SBarry Smith    When used with -snes_fd this will compute the true Jacobian (very slowly one column at at time) and thus represent Newton's method.
22866b7fb656SBarry Smith 
22876b7fb656SBarry Smith    When used with -snes_fd_coloring this will compute the Jacobian via coloring and thus represent a faster implementation of Newton's method. But the
22886b7fb656SBarry Smith    the nonzero structure of the Jacobian is, in general larger than that of the Picard matrix A so you must provide in A the needed nonzero structure for the correct
22896b7fb656SBarry Smith    coloring. When using DMDA this may mean creating the matrix A with DMCreateMatrix() using a wider stencil than strictly needed for A or with a DMDA_STENCIL_BOX.
22906b7fb656SBarry Smith    See the commment in src/snes/tutorials/ex15.c.
2291bbc1464cSBarry Smith 
2292f450aa47SBarry Smith    Level: intermediate
22938b0a5094SBarry Smith 
2294411c0326SBarry Smith .seealso: SNESGetFunction(), SNESSetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESGetPicard(), SNESLineSearchPreCheckPicard(), SNESJacobianFunction
22958b0a5094SBarry Smith @*/
2296bbc1464cSBarry Smith PetscErrorCode  SNESSetPicard(SNES snes,Vec r,PetscErrorCode (*bp)(SNES,Vec,Vec,void*),Mat Amat, Mat Pmat, PetscErrorCode (*J)(SNES,Vec,Mat,Mat,void*),void *ctx)
22978b0a5094SBarry Smith {
2298e03ab78fSPeter Brune   DM             dm;
2299e03ab78fSPeter Brune 
23008b0a5094SBarry Smith   PetscFunctionBegin;
23018b0a5094SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
23025f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESGetDM(snes, &dm));
23035f80ce2aSJacob Faibussowitsch   CHKERRQ(DMSNESSetPicard(dm,bp,J,ctx));
23045f80ce2aSJacob Faibussowitsch   CHKERRQ(DMSNESSetMFFunction(dm,SNESPicardComputeMFFunction,ctx));
23055f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESSetFunction(snes,r,SNESPicardComputeFunction,ctx));
23065f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESSetJacobian(snes,Amat,Pmat,SNESPicardComputeJacobian,ctx));
23078b0a5094SBarry Smith   PetscFunctionReturn(0);
23088b0a5094SBarry Smith }
23098b0a5094SBarry Smith 
23107971a8bfSPeter Brune /*@C
23117971a8bfSPeter Brune    SNESGetPicard - Returns the context for the Picard iteration
23127971a8bfSPeter Brune 
23137971a8bfSPeter Brune    Not Collective, but Vec is parallel if SNES is parallel. Collective if Vec is requested, but has not been created yet.
23147971a8bfSPeter Brune 
23157971a8bfSPeter Brune    Input Parameter:
23167971a8bfSPeter Brune .  snes - the SNES context
23177971a8bfSPeter Brune 
2318d8d19677SJose E. Roman    Output Parameters:
23190298fd71SBarry Smith +  r - the function (or NULL)
2320f8b49ee9SBarry Smith .  f - the function (or NULL); see SNESFunction for calling sequence details
2321e4357dc4SBarry Smith .  Amat - the matrix used to defined the operation A(x) x - b(x) (or NULL)
2322e4357dc4SBarry Smith .  Pmat  - the matrix from which the preconditioner will be constructed (or NULL)
2323f8b49ee9SBarry Smith .  J - the function for matrix evaluation (or NULL); see SNESJacobianFunction for calling sequence details
23240298fd71SBarry Smith -  ctx - the function context (or NULL)
23257971a8bfSPeter Brune 
23267971a8bfSPeter Brune    Level: advanced
23277971a8bfSPeter Brune 
2328e4357dc4SBarry Smith .seealso: SNESSetPicard(), SNESGetFunction(), SNESGetJacobian(), SNESGetDM(), SNESFunction, SNESJacobianFunction
23297971a8bfSPeter Brune @*/
2330d1e9a80fSBarry Smith 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)
23317971a8bfSPeter Brune {
23327971a8bfSPeter Brune   DM             dm;
23337971a8bfSPeter Brune 
23347971a8bfSPeter Brune   PetscFunctionBegin;
23357971a8bfSPeter Brune   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
23365f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESGetFunction(snes,r,NULL,NULL));
23375f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESGetJacobian(snes,Amat,Pmat,NULL,NULL));
23385f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESGetDM(snes,&dm));
23395f80ce2aSJacob Faibussowitsch   CHKERRQ(DMSNESGetPicard(dm,f,J,ctx));
23407971a8bfSPeter Brune   PetscFunctionReturn(0);
23417971a8bfSPeter Brune }
23427971a8bfSPeter Brune 
2343d25893d9SBarry Smith /*@C
2344d25893d9SBarry Smith    SNESSetComputeInitialGuess - Sets a routine used to compute an initial guess for the problem
2345d25893d9SBarry Smith 
2346d25893d9SBarry Smith    Logically Collective on SNES
2347d25893d9SBarry Smith 
2348d25893d9SBarry Smith    Input Parameters:
2349d25893d9SBarry Smith +  snes - the SNES context
2350d25893d9SBarry Smith .  func - function evaluation routine
2351d25893d9SBarry Smith -  ctx - [optional] user-defined context for private data for the
23520298fd71SBarry Smith          function evaluation routine (may be NULL)
2353d25893d9SBarry Smith 
2354d25893d9SBarry Smith    Calling sequence of func:
2355d25893d9SBarry Smith $    func (SNES snes,Vec x,void *ctx);
2356d25893d9SBarry Smith 
2357d25893d9SBarry Smith .  f - function vector
2358d25893d9SBarry Smith -  ctx - optional user-defined function context
2359d25893d9SBarry Smith 
2360d25893d9SBarry Smith    Level: intermediate
2361d25893d9SBarry Smith 
2362d25893d9SBarry Smith .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian()
2363d25893d9SBarry Smith @*/
2364d25893d9SBarry Smith PetscErrorCode  SNESSetComputeInitialGuess(SNES snes,PetscErrorCode (*func)(SNES,Vec,void*),void *ctx)
2365d25893d9SBarry Smith {
2366d25893d9SBarry Smith   PetscFunctionBegin;
2367d25893d9SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
2368d25893d9SBarry Smith   if (func) snes->ops->computeinitialguess = func;
2369d25893d9SBarry Smith   if (ctx)  snes->initialguessP            = ctx;
2370d25893d9SBarry Smith   PetscFunctionReturn(0);
2371d25893d9SBarry Smith }
2372d25893d9SBarry Smith 
23733ab0aad5SBarry Smith /* --------------------------------------------------------------- */
23741096aae1SMatthew Knepley /*@C
23751096aae1SMatthew Knepley    SNESGetRhs - Gets the vector for solving F(x) = rhs. If rhs is not set
23761096aae1SMatthew Knepley    it assumes a zero right hand side.
23771096aae1SMatthew Knepley 
23783f9fe445SBarry Smith    Logically Collective on SNES
23791096aae1SMatthew Knepley 
23801096aae1SMatthew Knepley    Input Parameter:
23811096aae1SMatthew Knepley .  snes - the SNES context
23821096aae1SMatthew Knepley 
23831096aae1SMatthew Knepley    Output Parameter:
23840298fd71SBarry Smith .  rhs - the right hand side vector or NULL if the right hand side vector is null
23851096aae1SMatthew Knepley 
23861096aae1SMatthew Knepley    Level: intermediate
23871096aae1SMatthew Knepley 
238885385478SLisandro Dalcin .seealso: SNESGetSolution(), SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetFunction()
23891096aae1SMatthew Knepley @*/
23907087cfbeSBarry Smith PetscErrorCode  SNESGetRhs(SNES snes,Vec *rhs)
23911096aae1SMatthew Knepley {
23921096aae1SMatthew Knepley   PetscFunctionBegin;
23930700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
23941096aae1SMatthew Knepley   PetscValidPointer(rhs,2);
239585385478SLisandro Dalcin   *rhs = snes->vec_rhs;
23961096aae1SMatthew Knepley   PetscFunctionReturn(0);
23971096aae1SMatthew Knepley }
23981096aae1SMatthew Knepley 
23999b94acceSBarry Smith /*@
2400bf388a1fSBarry Smith    SNESComputeFunction - Calls the function that has been set with SNESSetFunction().
24019b94acceSBarry Smith 
2402c7afd0dbSLois Curfman McInnes    Collective on SNES
2403c7afd0dbSLois Curfman McInnes 
24049b94acceSBarry Smith    Input Parameters:
2405c7afd0dbSLois Curfman McInnes +  snes - the SNES context
2406c7afd0dbSLois Curfman McInnes -  x - input vector
24079b94acceSBarry Smith 
24089b94acceSBarry Smith    Output Parameter:
24093638b69dSLois Curfman McInnes .  y - function vector, as set by SNESSetFunction()
24109b94acceSBarry Smith 
24111bffabb2SLois Curfman McInnes    Notes:
241236851e7fSLois Curfman McInnes    SNESComputeFunction() is typically used within nonlinear solvers
2413bbc1464cSBarry Smith    implementations, so users would not generally call this routine themselves.
241436851e7fSLois Curfman McInnes 
241536851e7fSLois Curfman McInnes    Level: developer
241636851e7fSLois Curfman McInnes 
2417bbc1464cSBarry Smith .seealso: SNESSetFunction(), SNESGetFunction(), SNESComputeMFFunction()
24189b94acceSBarry Smith @*/
24197087cfbeSBarry Smith PetscErrorCode  SNESComputeFunction(SNES snes,Vec x,Vec y)
24209b94acceSBarry Smith {
24216cab3a1bSJed Brown   DM             dm;
2422942e3340SBarry Smith   DMSNES         sdm;
24239b94acceSBarry Smith 
24243a40ed3dSBarry Smith   PetscFunctionBegin;
24250700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
24260700a824SBarry Smith   PetscValidHeaderSpecific(x,VEC_CLASSID,2);
24270700a824SBarry Smith   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
2428c9780b6fSBarry Smith   PetscCheckSameComm(snes,1,x,2);
2429c9780b6fSBarry Smith   PetscCheckSameComm(snes,1,y,3);
24305f80ce2aSJacob Faibussowitsch   CHKERRQ(VecValidValues(x,2,PETSC_TRUE));
2431184914b5SBarry Smith 
24325f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESGetDM(snes,&dm));
24335f80ce2aSJacob Faibussowitsch   CHKERRQ(DMGetDMSNES(dm,&sdm));
243432f3f7c2SPeter Brune   if (sdm->ops->computefunction) {
243594db00ebSBarry Smith     if (sdm->ops->computefunction != SNESObjectiveComputeFunctionDefaultFD) {
24365f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscLogEventBegin(SNES_FunctionEval,snes,x,y,0));
243794db00ebSBarry Smith     }
24385f80ce2aSJacob Faibussowitsch     CHKERRQ(VecLockReadPush(x));
2439d64ed03dSBarry Smith     PetscStackPush("SNES user function");
24408ddeebeaSSteve Benbow     /* ensure domainerror is false prior to computefunction evaluation (may not have been reset) */
24418ddeebeaSSteve Benbow     snes->domainerror = PETSC_FALSE;
24425f80ce2aSJacob Faibussowitsch     CHKERRQ((*sdm->ops->computefunction)(snes,x,y,sdm->functionctx));
2443d64ed03dSBarry Smith     PetscStackPop;
24445f80ce2aSJacob Faibussowitsch     CHKERRQ(VecLockReadPop(x));
244594db00ebSBarry Smith     if (sdm->ops->computefunction != SNESObjectiveComputeFunctionDefaultFD) {
24465f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscLogEventEnd(SNES_FunctionEval,snes,x,y,0));
244794db00ebSBarry Smith     }
2448c90fad12SPeter Brune   } else if (snes->vec_rhs) {
24495f80ce2aSJacob Faibussowitsch     CHKERRQ(MatMult(snes->jacobian, x, y));
2450644e2e5bSBarry Smith   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetFunction() or SNESSetDM() before SNESComputeFunction(), likely called from SNESSolve().");
245185385478SLisandro Dalcin   if (snes->vec_rhs) {
24525f80ce2aSJacob Faibussowitsch     CHKERRQ(VecAXPY(y,-1.0,snes->vec_rhs));
24533ab0aad5SBarry Smith   }
2454ae3c334cSLois Curfman McInnes   snes->nfuncs++;
2455422a814eSBarry Smith   /*
2456422a814eSBarry Smith      domainerror might not be set on all processes; so we tag vector locally with Inf and the next inner product or norm will
2457422a814eSBarry Smith      propagate the value to all processes
2458422a814eSBarry Smith   */
2459422a814eSBarry Smith   if (snes->domainerror) {
24605f80ce2aSJacob Faibussowitsch     CHKERRQ(VecSetInf(y));
2461422a814eSBarry Smith   }
24623a40ed3dSBarry Smith   PetscFunctionReturn(0);
24639b94acceSBarry Smith }
24649b94acceSBarry Smith 
2465c79ef259SPeter Brune /*@
2466bbc1464cSBarry Smith    SNESComputeMFFunction - Calls the function that has been set with SNESSetMFFunction().
2467bbc1464cSBarry Smith 
2468bbc1464cSBarry Smith    Collective on SNES
2469bbc1464cSBarry Smith 
2470bbc1464cSBarry Smith    Input Parameters:
2471bbc1464cSBarry Smith +  snes - the SNES context
2472bbc1464cSBarry Smith -  x - input vector
2473bbc1464cSBarry Smith 
2474bbc1464cSBarry Smith    Output Parameter:
2475bbc1464cSBarry Smith .  y - function vector, as set by SNESSetMFFunction()
2476bbc1464cSBarry Smith 
2477bbc1464cSBarry Smith    Notes:
2478bbc1464cSBarry Smith        SNESComputeMFFunction() is used within the matrix vector products called by the matrix created with MatCreateSNESMF()
2479bbc1464cSBarry Smith    so users would not generally call this routine themselves.
2480bbc1464cSBarry Smith 
2481bbc1464cSBarry Smith        Since this function is intended for use with finite differencing it does not subtract the right hand side vector provided with SNESSolve()
2482bbc1464cSBarry Smith     while SNESComputeFunction() does. As such, this routine cannot be used with  MatMFFDSetBase() with a provided F function value even if it applies the
2483bbc1464cSBarry Smith     same function as SNESComputeFunction() if a SNESSolve() right hand side vector is use because the two functions difference would include this right hand side function.
2484bbc1464cSBarry Smith 
2485bbc1464cSBarry Smith    Level: developer
2486bbc1464cSBarry Smith 
2487bbc1464cSBarry Smith .seealso: SNESSetFunction(), SNESGetFunction(), SNESComputeFunction(), MatCreateSNESMF
2488bbc1464cSBarry Smith @*/
2489bbc1464cSBarry Smith PetscErrorCode  SNESComputeMFFunction(SNES snes,Vec x,Vec y)
2490bbc1464cSBarry Smith {
2491bbc1464cSBarry Smith   DM             dm;
2492bbc1464cSBarry Smith   DMSNES         sdm;
2493bbc1464cSBarry Smith 
2494bbc1464cSBarry Smith   PetscFunctionBegin;
2495bbc1464cSBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
2496bbc1464cSBarry Smith   PetscValidHeaderSpecific(x,VEC_CLASSID,2);
2497bbc1464cSBarry Smith   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
2498bbc1464cSBarry Smith   PetscCheckSameComm(snes,1,x,2);
2499bbc1464cSBarry Smith   PetscCheckSameComm(snes,1,y,3);
25005f80ce2aSJacob Faibussowitsch   CHKERRQ(VecValidValues(x,2,PETSC_TRUE));
2501bbc1464cSBarry Smith 
25025f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESGetDM(snes,&dm));
25035f80ce2aSJacob Faibussowitsch   CHKERRQ(DMGetDMSNES(dm,&sdm));
25045f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscLogEventBegin(SNES_FunctionEval,snes,x,y,0));
25055f80ce2aSJacob Faibussowitsch   CHKERRQ(VecLockReadPush(x));
2506bbc1464cSBarry Smith   PetscStackPush("SNES user function");
2507bbc1464cSBarry Smith   /* ensure domainerror is false prior to computefunction evaluation (may not have been reset) */
2508bbc1464cSBarry Smith   snes->domainerror = PETSC_FALSE;
25095f80ce2aSJacob Faibussowitsch   CHKERRQ((*sdm->ops->computemffunction)(snes,x,y,sdm->mffunctionctx));
2510bbc1464cSBarry Smith   PetscStackPop;
25115f80ce2aSJacob Faibussowitsch   CHKERRQ(VecLockReadPop(x));
25125f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscLogEventEnd(SNES_FunctionEval,snes,x,y,0));
2513bbc1464cSBarry Smith   snes->nfuncs++;
2514bbc1464cSBarry Smith   /*
2515bbc1464cSBarry Smith      domainerror might not be set on all processes; so we tag vector locally with Inf and the next inner product or norm will
2516bbc1464cSBarry Smith      propagate the value to all processes
2517bbc1464cSBarry Smith   */
2518bbc1464cSBarry Smith   if (snes->domainerror) {
25195f80ce2aSJacob Faibussowitsch     CHKERRQ(VecSetInf(y));
2520bbc1464cSBarry Smith   }
2521bbc1464cSBarry Smith   PetscFunctionReturn(0);
2522bbc1464cSBarry Smith }
2523bbc1464cSBarry Smith 
2524bbc1464cSBarry Smith /*@
2525be95d8f1SBarry Smith    SNESComputeNGS - Calls the Gauss-Seidel function that has been set with  SNESSetNGS().
2526c79ef259SPeter Brune 
2527c79ef259SPeter Brune    Collective on SNES
2528c79ef259SPeter Brune 
2529c79ef259SPeter Brune    Input Parameters:
2530c79ef259SPeter Brune +  snes - the SNES context
2531c79ef259SPeter Brune .  x - input vector
2532c79ef259SPeter Brune -  b - rhs vector
2533c79ef259SPeter Brune 
2534c79ef259SPeter Brune    Output Parameter:
2535c79ef259SPeter Brune .  x - new solution vector
2536c79ef259SPeter Brune 
2537c79ef259SPeter Brune    Notes:
2538be95d8f1SBarry Smith    SNESComputeNGS() is typically used within composed nonlinear solver
2539c79ef259SPeter Brune    implementations, so most users would not generally call this routine
2540c79ef259SPeter Brune    themselves.
2541c79ef259SPeter Brune 
2542c79ef259SPeter Brune    Level: developer
2543c79ef259SPeter Brune 
2544be95d8f1SBarry Smith .seealso: SNESSetNGS(), SNESComputeFunction()
2545c79ef259SPeter Brune @*/
2546be95d8f1SBarry Smith PetscErrorCode  SNESComputeNGS(SNES snes,Vec b,Vec x)
2547646217ecSPeter Brune {
25486cab3a1bSJed Brown   DM             dm;
2549942e3340SBarry Smith   DMSNES         sdm;
2550646217ecSPeter Brune 
2551646217ecSPeter Brune   PetscFunctionBegin;
2552646217ecSPeter Brune   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
2553064a246eSJacob Faibussowitsch   PetscValidHeaderSpecific(x,VEC_CLASSID,3);
2554064a246eSJacob Faibussowitsch   if (b) PetscValidHeaderSpecific(b,VEC_CLASSID,2);
2555064a246eSJacob Faibussowitsch   PetscCheckSameComm(snes,1,x,3);
2556064a246eSJacob Faibussowitsch   if (b) PetscCheckSameComm(snes,1,b,2);
25575f80ce2aSJacob Faibussowitsch   if (b) CHKERRQ(VecValidValues(b,2,PETSC_TRUE));
25585f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscLogEventBegin(SNES_NGSEval,snes,x,b,0));
25595f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESGetDM(snes,&dm));
25605f80ce2aSJacob Faibussowitsch   CHKERRQ(DMGetDMSNES(dm,&sdm));
256122c6f798SBarry Smith   if (sdm->ops->computegs) {
25625f80ce2aSJacob Faibussowitsch     if (b) CHKERRQ(VecLockReadPush(b));
2563be95d8f1SBarry Smith     PetscStackPush("SNES user NGS");
25645f80ce2aSJacob Faibussowitsch     CHKERRQ((*sdm->ops->computegs)(snes,x,b,sdm->gsctx));
2565646217ecSPeter Brune     PetscStackPop;
25665f80ce2aSJacob Faibussowitsch     if (b) CHKERRQ(VecLockReadPop(b));
2567be95d8f1SBarry Smith   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetNGS() before SNESComputeNGS(), likely called from SNESSolve().");
25685f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscLogEventEnd(SNES_NGSEval,snes,x,b,0));
2569646217ecSPeter Brune   PetscFunctionReturn(0);
2570646217ecSPeter Brune }
2571646217ecSPeter Brune 
2572e885f1abSBarry Smith PetscErrorCode SNESTestJacobian(SNES snes)
2573e885f1abSBarry Smith {
257412837594SBarry Smith   Mat               A,B,C,D,jacobian;
2575e885f1abSBarry Smith   Vec               x = snes->vec_sol,f = snes->vec_func;
2576e885f1abSBarry Smith   PetscErrorCode    ierr;
2577e885f1abSBarry Smith   PetscReal         nrm,gnorm;
257881e7118cSBarry Smith   PetscReal         threshold = 1.e-5;
25790e276705SLisandro Dalcin   MatType           mattype;
2580e885f1abSBarry Smith   PetscInt          m,n,M,N;
2581e885f1abSBarry Smith   void              *functx;
25822cd624f9SStefano Zampini   PetscBool         complete_print = PETSC_FALSE,threshold_print = PETSC_FALSE,test = PETSC_FALSE,flg,istranspose;
25833325ff46SBarry Smith   PetscViewer       viewer,mviewer;
2584e885f1abSBarry Smith   MPI_Comm          comm;
2585e885f1abSBarry Smith   PetscInt          tabs;
258612837594SBarry Smith   static PetscBool  directionsprinted = PETSC_FALSE;
25873325ff46SBarry Smith   PetscViewerFormat format;
2588e885f1abSBarry Smith 
2589e885f1abSBarry Smith   PetscFunctionBegin;
2590fc35ed60SBarry Smith   ierr = PetscObjectOptionsBegin((PetscObject)snes);CHKERRQ(ierr);
25915f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscOptionsName("-snes_test_jacobian","Compare hand-coded and finite difference Jacobians","None",&test));
25925f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscOptionsReal("-snes_test_jacobian", "Threshold for element difference between hand-coded and finite difference being meaningful", "None", threshold, &threshold,NULL));
25935f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscOptionsViewer("-snes_test_jacobian_view","View difference between hand-coded and finite difference Jacobians element entries","None",&mviewer,&format,&complete_print));
259418d89885SKarl Rupp   if (!complete_print) {
25955f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscOptionsDeprecated("-snes_test_jacobian_display","-snes_test_jacobian_view","3.13",NULL));
25965f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscOptionsViewer("-snes_test_jacobian_display","Display difference between hand-coded and finite difference Jacobians","None",&mviewer,&format,&complete_print));
259718d89885SKarl Rupp   }
259818d89885SKarl Rupp   /* for compatibility with PETSc 3.9 and older. */
25995f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscOptionsDeprecated("-snes_test_jacobian_display_threshold","-snes_test_jacobian","3.13","-snes_test_jacobian accepts an optional threshold (since v3.10)"));
26005f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscOptionsReal("-snes_test_jacobian_display_threshold", "Display difference between hand-coded and finite difference Jacobians which exceed input threshold", "None", threshold, &threshold, &threshold_print));
2601e885f1abSBarry Smith   ierr = PetscOptionsEnd();CHKERRQ(ierr);
2602e885f1abSBarry Smith   if (!test) PetscFunctionReturn(0);
2603e885f1abSBarry Smith 
26045f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscObjectGetComm((PetscObject)snes,&comm));
26055f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscViewerASCIIGetStdout(comm,&viewer));
26065f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscViewerASCIIGetTab(viewer, &tabs));
26075f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscViewerASCIISetTab(viewer, ((PetscObject)snes)->tablevel));
26085f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscViewerASCIIPrintf(viewer,"  ---------- Testing Jacobian -------------\n"));
260912837594SBarry Smith   if (!complete_print && !directionsprinted) {
26105f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscViewerASCIIPrintf(viewer,"  Run with -snes_test_jacobian_view and optionally -snes_test_jacobian <threshold> to show difference\n"));
26115f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscViewerASCIIPrintf(viewer,"    of hand-coded and finite difference Jacobian entries greater than <threshold>.\n"));
261212837594SBarry Smith   }
261312837594SBarry Smith   if (!directionsprinted) {
26145f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscViewerASCIIPrintf(viewer,"  Testing hand-coded Jacobian, if (for double precision runs) ||J - Jfd||_F/||J||_F is\n"));
26155f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscViewerASCIIPrintf(viewer,"    O(1.e-8), the hand-coded Jacobian is probably correct.\n"));
261612837594SBarry Smith     directionsprinted = PETSC_TRUE;
2617e885f1abSBarry Smith   }
26183325ff46SBarry Smith   if (complete_print) {
26195f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscViewerPushFormat(mviewer,format));
2620e885f1abSBarry Smith   }
2621e885f1abSBarry Smith 
26225f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscObjectTypeCompare((PetscObject)snes->jacobian,MATMFFD,&flg));
262312837594SBarry Smith   if (!flg) jacobian = snes->jacobian;
262412837594SBarry Smith   else jacobian = snes->jacobian_pre;
262512837594SBarry Smith 
2626a82339d0SMatthew G. Knepley   if (!x) {
26275f80ce2aSJacob Faibussowitsch     CHKERRQ(MatCreateVecs(jacobian, &x, NULL));
2628a82339d0SMatthew G. Knepley   } else {
26295f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscObjectReference((PetscObject) x));
2630a82339d0SMatthew G. Knepley   }
2631a82339d0SMatthew G. Knepley   if (!f) {
26325f80ce2aSJacob Faibussowitsch     CHKERRQ(VecDuplicate(x, &f));
2633a82339d0SMatthew G. Knepley   } else {
26345f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscObjectReference((PetscObject) f));
2635a82339d0SMatthew G. Knepley   }
2636a82339d0SMatthew G. Knepley   /* evaluate the function at this point because SNESComputeJacobianDefault() assumes that the function has been evaluated and put into snes->vec_func */
26375f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESComputeFunction(snes,x,f));
26385f80ce2aSJacob Faibussowitsch   CHKERRQ(VecDestroy(&f));
26395f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscObjectTypeCompare((PetscObject)snes,SNESKSPTRANSPOSEONLY,&istranspose));
264012837594SBarry Smith   while (jacobian) {
26412cd624f9SStefano Zampini     Mat JT = NULL, Jsave = NULL;
26422cd624f9SStefano Zampini 
26432cd624f9SStefano Zampini     if (istranspose) {
26445f80ce2aSJacob Faibussowitsch       CHKERRQ(MatCreateTranspose(jacobian,&JT));
26452cd624f9SStefano Zampini       Jsave = jacobian;
26462cd624f9SStefano Zampini       jacobian = JT;
26472cd624f9SStefano Zampini     }
26485f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscObjectBaseTypeCompareAny((PetscObject)jacobian,&flg,MATSEQAIJ,MATMPIAIJ,MATSEQDENSE,MATMPIDENSE,MATSEQBAIJ,MATMPIBAIJ,MATSEQSBAIJ,MATMPISBAIJ,""));
264912837594SBarry Smith     if (flg) {
265012837594SBarry Smith       A    = jacobian;
26515f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscObjectReference((PetscObject)A));
265212837594SBarry Smith     } else {
26535f80ce2aSJacob Faibussowitsch       CHKERRQ(MatComputeOperator(jacobian,MATAIJ,&A));
265412837594SBarry Smith     }
2655e885f1abSBarry Smith 
26565f80ce2aSJacob Faibussowitsch     CHKERRQ(MatGetType(A,&mattype));
26575f80ce2aSJacob Faibussowitsch     CHKERRQ(MatGetSize(A,&M,&N));
26585f80ce2aSJacob Faibussowitsch     CHKERRQ(MatGetLocalSize(A,&m,&n));
26595f80ce2aSJacob Faibussowitsch     CHKERRQ(MatCreate(PetscObjectComm((PetscObject)A),&B));
26605f80ce2aSJacob Faibussowitsch     CHKERRQ(MatSetType(B,mattype));
26615f80ce2aSJacob Faibussowitsch     CHKERRQ(MatSetSizes(B,m,n,M,N));
26625f80ce2aSJacob Faibussowitsch     CHKERRQ(MatSetBlockSizesFromMats(B,A,A));
26635f80ce2aSJacob Faibussowitsch     CHKERRQ(MatSetUp(B));
26645f80ce2aSJacob Faibussowitsch     CHKERRQ(MatSetOption(B,MAT_NEW_NONZERO_ALLOCATION_ERR,PETSC_FALSE));
2665e885f1abSBarry Smith 
26665f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESGetFunction(snes,NULL,NULL,&functx));
26675f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESComputeJacobianDefault(snes,x,B,B,functx));
266812837594SBarry Smith 
26695f80ce2aSJacob Faibussowitsch     CHKERRQ(MatDuplicate(B,MAT_COPY_VALUES,&D));
26705f80ce2aSJacob Faibussowitsch     CHKERRQ(MatAYPX(D,-1.0,A,DIFFERENT_NONZERO_PATTERN));
26715f80ce2aSJacob Faibussowitsch     CHKERRQ(MatNorm(D,NORM_FROBENIUS,&nrm));
26725f80ce2aSJacob Faibussowitsch     CHKERRQ(MatNorm(A,NORM_FROBENIUS,&gnorm));
26735f80ce2aSJacob Faibussowitsch     CHKERRQ(MatDestroy(&D));
267412837594SBarry Smith     if (!gnorm) gnorm = 1; /* just in case */
26755f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscViewerASCIIPrintf(viewer,"  ||J - Jfd||_F/||J||_F = %g, ||J - Jfd||_F = %g\n",(double)(nrm/gnorm),(double)nrm));
267612837594SBarry Smith 
2677e885f1abSBarry Smith     if (complete_print) {
26785f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscViewerASCIIPrintf(viewer,"  Hand-coded Jacobian ----------\n"));
26795f80ce2aSJacob Faibussowitsch       CHKERRQ(MatView(A,mviewer));
26805f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscViewerASCIIPrintf(viewer,"  Finite difference Jacobian ----------\n"));
26815f80ce2aSJacob Faibussowitsch       CHKERRQ(MatView(B,mviewer));
2682e885f1abSBarry Smith     }
2683e885f1abSBarry Smith 
2684df10fb39SFande Kong     if (threshold_print || complete_print) {
2685e885f1abSBarry Smith       PetscInt          Istart, Iend, *ccols, bncols, cncols, j, row;
2686e885f1abSBarry Smith       PetscScalar       *cvals;
2687e885f1abSBarry Smith       const PetscInt    *bcols;
2688e885f1abSBarry Smith       const PetscScalar *bvals;
2689e885f1abSBarry Smith 
26905f80ce2aSJacob Faibussowitsch       CHKERRQ(MatCreate(PetscObjectComm((PetscObject)A),&C));
26915f80ce2aSJacob Faibussowitsch       CHKERRQ(MatSetType(C,mattype));
26925f80ce2aSJacob Faibussowitsch       CHKERRQ(MatSetSizes(C,m,n,M,N));
26935f80ce2aSJacob Faibussowitsch       CHKERRQ(MatSetBlockSizesFromMats(C,A,A));
26945f80ce2aSJacob Faibussowitsch       CHKERRQ(MatSetUp(C));
26955f80ce2aSJacob Faibussowitsch       CHKERRQ(MatSetOption(C,MAT_NEW_NONZERO_ALLOCATION_ERR,PETSC_FALSE));
26960e276705SLisandro Dalcin 
26975f80ce2aSJacob Faibussowitsch       CHKERRQ(MatAYPX(B,-1.0,A,DIFFERENT_NONZERO_PATTERN));
26985f80ce2aSJacob Faibussowitsch       CHKERRQ(MatGetOwnershipRange(B,&Istart,&Iend));
2699e885f1abSBarry Smith 
2700e885f1abSBarry Smith       for (row = Istart; row < Iend; row++) {
27015f80ce2aSJacob Faibussowitsch         CHKERRQ(MatGetRow(B,row,&bncols,&bcols,&bvals));
27025f80ce2aSJacob Faibussowitsch         CHKERRQ(PetscMalloc2(bncols,&ccols,bncols,&cvals));
2703e885f1abSBarry Smith         for (j = 0, cncols = 0; j < bncols; j++) {
270423a52b1dSBarry Smith           if (PetscAbsScalar(bvals[j]) > threshold) {
2705e885f1abSBarry Smith             ccols[cncols] = bcols[j];
2706e885f1abSBarry Smith             cvals[cncols] = bvals[j];
2707e885f1abSBarry Smith             cncols += 1;
2708e885f1abSBarry Smith           }
2709e885f1abSBarry Smith         }
2710e885f1abSBarry Smith         if (cncols) {
27115f80ce2aSJacob Faibussowitsch           CHKERRQ(MatSetValues(C,1,&row,cncols,ccols,cvals,INSERT_VALUES));
2712e885f1abSBarry Smith         }
27135f80ce2aSJacob Faibussowitsch         CHKERRQ(MatRestoreRow(B,row,&bncols,&bcols,&bvals));
27145f80ce2aSJacob Faibussowitsch         CHKERRQ(PetscFree2(ccols,cvals));
2715e885f1abSBarry Smith       }
27165f80ce2aSJacob Faibussowitsch       CHKERRQ(MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY));
27175f80ce2aSJacob Faibussowitsch       CHKERRQ(MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY));
27185f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscViewerASCIIPrintf(viewer,"  Hand-coded minus finite-difference Jacobian with tolerance %g ----------\n",(double)threshold));
27195f80ce2aSJacob Faibussowitsch       CHKERRQ(MatView(C,complete_print ? mviewer : viewer));
27205f80ce2aSJacob Faibussowitsch       CHKERRQ(MatDestroy(&C));
2721e885f1abSBarry Smith     }
27225f80ce2aSJacob Faibussowitsch     CHKERRQ(MatDestroy(&A));
27235f80ce2aSJacob Faibussowitsch     CHKERRQ(MatDestroy(&B));
27245f80ce2aSJacob Faibussowitsch     CHKERRQ(MatDestroy(&JT));
27252cd624f9SStefano Zampini     if (Jsave) jacobian = Jsave;
272612837594SBarry Smith     if (jacobian != snes->jacobian_pre) {
272712837594SBarry Smith       jacobian = snes->jacobian_pre;
27285f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscViewerASCIIPrintf(viewer,"  ---------- Testing Jacobian for preconditioner -------------\n"));
272912837594SBarry Smith     }
273012837594SBarry Smith     else jacobian = NULL;
273112837594SBarry Smith   }
27325f80ce2aSJacob Faibussowitsch   CHKERRQ(VecDestroy(&x));
27333325ff46SBarry Smith   if (complete_print) {
27345f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscViewerPopFormat(mviewer));
27353325ff46SBarry Smith   }
27365f80ce2aSJacob Faibussowitsch   if (mviewer) CHKERRQ(PetscViewerDestroy(&mviewer));
27375f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscViewerASCIISetTab(viewer,tabs));
2738e885f1abSBarry Smith   PetscFunctionReturn(0);
2739e885f1abSBarry Smith }
2740e885f1abSBarry Smith 
274162fef451SLois Curfman McInnes /*@
2742bf388a1fSBarry Smith    SNESComputeJacobian - Computes the Jacobian matrix that has been set with SNESSetJacobian().
274362fef451SLois Curfman McInnes 
2744d083f849SBarry Smith    Collective on SNES
2745c7afd0dbSLois Curfman McInnes 
274662fef451SLois Curfman McInnes    Input Parameters:
2747c7afd0dbSLois Curfman McInnes +  snes - the SNES context
2748c7afd0dbSLois Curfman McInnes -  x - input vector
274962fef451SLois Curfman McInnes 
275062fef451SLois Curfman McInnes    Output Parameters:
2751c7afd0dbSLois Curfman McInnes +  A - Jacobian matrix
2752d1e9a80fSBarry Smith -  B - optional preconditioning matrix
2753fee21e36SBarry Smith 
2754e35cf81dSBarry Smith   Options Database Keys:
275567b8a455SSatish Balay +    -snes_lag_preconditioner <lag> - how often to rebuild preconditioner
275667b8a455SSatish Balay .    -snes_lag_jacobian <lag> - how often to rebuild Jacobian
2757455a5933SJed Brown .    -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.
2758455a5933SJed Brown .    -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
2759693365a8SJed Brown .    -snes_compare_explicit - Compare the computed Jacobian to the finite difference Jacobian and output the differences
2760693365a8SJed Brown .    -snes_compare_explicit_draw  - Compare the computed Jacobian to the finite difference Jacobian and draw the result
2761693365a8SJed Brown .    -snes_compare_explicit_contour  - Compare the computed Jacobian to the finite difference Jacobian and draw a contour plot with the result
27624c30e9fbSJed Brown .    -snes_compare_operator  - Make the comparison options above use the operator instead of the preconditioning matrix
276394d6a431SBarry Smith .    -snes_compare_coloring - Compute the finite difference Jacobian using coloring and display norms of difference
2764a5b23f4aSJose E. Roman .    -snes_compare_coloring_display - Compute the finite difference Jacobian using coloring and display verbose differences
2765c01495d3SJed Brown .    -snes_compare_coloring_threshold - Display only those matrix entries that differ by more than a given threshold
2766c01495d3SJed Brown .    -snes_compare_coloring_threshold_atol - Absolute tolerance for difference in matrix entries to be displayed by -snes_compare_coloring_threshold
2767c01495d3SJed Brown .    -snes_compare_coloring_threshold_rtol - Relative tolerance for difference in matrix entries to be displayed by -snes_compare_coloring_threshold
2768a5b23f4aSJose E. Roman .    -snes_compare_coloring_draw - Compute the finite difference Jacobian using coloring and draw differences
2769a5b23f4aSJose E. Roman -    -snes_compare_coloring_draw_contour - Compute the finite difference Jacobian using coloring and show contours of matrices and differences
2770c01495d3SJed Brown 
277162fef451SLois Curfman McInnes    Notes:
277262fef451SLois Curfman McInnes    Most users should not need to explicitly call this routine, as it
277362fef451SLois Curfman McInnes    is used internally within the nonlinear solvers.
277462fef451SLois Curfman McInnes 
277595452b02SPatrick Sanan    Developer Notes:
277695452b02SPatrick Sanan     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
2777e885f1abSBarry Smith       for with the SNESType of test that has been removed.
2778e885f1abSBarry Smith 
277936851e7fSLois Curfman McInnes    Level: developer
278036851e7fSLois Curfman McInnes 
2781e35cf81dSBarry Smith .seealso:  SNESSetJacobian(), KSPSetOperators(), MatStructure, SNESSetLagPreconditioner(), SNESSetLagJacobian()
278262fef451SLois Curfman McInnes @*/
2783d1e9a80fSBarry Smith PetscErrorCode  SNESComputeJacobian(SNES snes,Vec X,Mat A,Mat B)
27849b94acceSBarry Smith {
2785ace3abfcSBarry Smith   PetscBool      flag;
27866cab3a1bSJed Brown   DM             dm;
2787942e3340SBarry Smith   DMSNES         sdm;
2788e0e3a89bSBarry Smith   KSP            ksp;
27893a40ed3dSBarry Smith 
27903a40ed3dSBarry Smith   PetscFunctionBegin;
27910700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
27920700a824SBarry Smith   PetscValidHeaderSpecific(X,VEC_CLASSID,2);
2793c9780b6fSBarry Smith   PetscCheckSameComm(snes,1,X,2);
27945f80ce2aSJacob Faibussowitsch   CHKERRQ(VecValidValues(X,2,PETSC_TRUE));
27955f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESGetDM(snes,&dm));
27965f80ce2aSJacob Faibussowitsch   CHKERRQ(DMGetDMSNES(dm,&sdm));
27973232da50SPeter Brune 
27985f80ce2aSJacob Faibussowitsch   PetscCheck(sdm->ops->computejacobian,PetscObjectComm((PetscObject)snes),PETSC_ERR_USER,"Must call SNESSetJacobian(), DMSNESSetJacobian(), DMDASNESSetJacobianLocal(), etc");
2799ebd3b9afSBarry Smith 
2800ebd3b9afSBarry Smith   /* make sure that MatAssemblyBegin/End() is called on A matrix if it is matrix free */
2801ebd3b9afSBarry Smith 
2802fe3ffe1eSBarry Smith   if (snes->lagjacobian == -2) {
2803fe3ffe1eSBarry Smith     snes->lagjacobian = -1;
2804f5af7f23SKarl Rupp 
28055f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscInfo(snes,"Recomputing Jacobian/preconditioner because lag is -2 (means compute Jacobian, but then never again) \n"));
2806fe3ffe1eSBarry Smith   } else if (snes->lagjacobian == -1) {
28075f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscInfo(snes,"Reusing Jacobian/preconditioner because lag is -1\n"));
28085f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscObjectTypeCompare((PetscObject)A,MATMFFD,&flag));
2809ebd3b9afSBarry Smith     if (flag) {
28105f80ce2aSJacob Faibussowitsch       CHKERRQ(MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY));
28115f80ce2aSJacob Faibussowitsch       CHKERRQ(MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY));
2812ebd3b9afSBarry Smith     }
2813e35cf81dSBarry Smith     PetscFunctionReturn(0);
281437ec4e1aSPeter Brune   } else if (snes->lagjacobian > 1 && (snes->iter + snes->jac_iter) % snes->lagjacobian) {
28155f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscInfo(snes,"Reusing Jacobian/preconditioner because lag is %D and SNES iteration is %D\n",snes->lagjacobian,snes->iter));
28165f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscObjectTypeCompare((PetscObject)A,MATMFFD,&flag));
2817ebd3b9afSBarry Smith     if (flag) {
28185f80ce2aSJacob Faibussowitsch       CHKERRQ(MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY));
28195f80ce2aSJacob Faibussowitsch       CHKERRQ(MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY));
2820ebd3b9afSBarry Smith     }
2821e35cf81dSBarry Smith     PetscFunctionReturn(0);
2822e35cf81dSBarry Smith   }
2823efd4aadfSBarry Smith   if (snes->npc && snes->npcside == PC_LEFT) {
28245f80ce2aSJacob Faibussowitsch     CHKERRQ(MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY));
28255f80ce2aSJacob Faibussowitsch     CHKERRQ(MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY));
2826d728fb7dSPeter Brune     PetscFunctionReturn(0);
2827d728fb7dSPeter Brune   }
2828e35cf81dSBarry Smith 
28295f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscLogEventBegin(SNES_JacobianEval,snes,X,A,B));
28305f80ce2aSJacob Faibussowitsch   CHKERRQ(VecLockReadPush(X));
2831d64ed03dSBarry Smith   PetscStackPush("SNES user Jacobian function");
28325f80ce2aSJacob Faibussowitsch   CHKERRQ((*sdm->ops->computejacobian)(snes,X,A,B,sdm->jacobianctx));
2833d64ed03dSBarry Smith   PetscStackPop;
28345f80ce2aSJacob Faibussowitsch   CHKERRQ(VecLockReadPop(X));
28355f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscLogEventEnd(SNES_JacobianEval,snes,X,A,B));
283628d58a37SPierre Jolivet 
283728d58a37SPierre Jolivet   /* attach latest linearization point to the preconditioning matrix */
28385f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscObjectCompose((PetscObject)B,"__SNES_latest_X",(PetscObject)X));
2839a8054027SBarry Smith 
2840e0e3a89bSBarry Smith   /* the next line ensures that snes->ksp exists */
28415f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESGetKSP(snes,&ksp));
28423b4f5425SBarry Smith   if (snes->lagpreconditioner == -2) {
28435f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscInfo(snes,"Rebuilding preconditioner exactly once since lag is -2\n"));
28445f80ce2aSJacob Faibussowitsch     CHKERRQ(KSPSetReusePreconditioner(snes->ksp,PETSC_FALSE));
28453b4f5425SBarry Smith     snes->lagpreconditioner = -1;
28463b4f5425SBarry Smith   } else if (snes->lagpreconditioner == -1) {
28475f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscInfo(snes,"Reusing preconditioner because lag is -1\n"));
28485f80ce2aSJacob Faibussowitsch     CHKERRQ(KSPSetReusePreconditioner(snes->ksp,PETSC_TRUE));
284937ec4e1aSPeter Brune   } else if (snes->lagpreconditioner > 1 && (snes->iter + snes->pre_iter) % snes->lagpreconditioner) {
28505f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscInfo(snes,"Reusing preconditioner because lag is %D and SNES iteration is %D\n",snes->lagpreconditioner,snes->iter));
28515f80ce2aSJacob Faibussowitsch     CHKERRQ(KSPSetReusePreconditioner(snes->ksp,PETSC_TRUE));
2852d1e9a80fSBarry Smith   } else {
28535f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscInfo(snes,"Rebuilding preconditioner\n"));
28545f80ce2aSJacob Faibussowitsch     CHKERRQ(KSPSetReusePreconditioner(snes->ksp,PETSC_FALSE));
2855a8054027SBarry Smith   }
2856a8054027SBarry Smith 
28575f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESTestJacobian(snes));
28586d84be18SBarry Smith   /* make sure user returned a correct Jacobian and preconditioner */
285994ab13aaSBarry Smith   /* PetscValidHeaderSpecific(A,MAT_CLASSID,3);
286094ab13aaSBarry Smith     PetscValidHeaderSpecific(B,MAT_CLASSID,4);   */
2861693365a8SJed Brown   {
2862693365a8SJed Brown     PetscBool flag = PETSC_FALSE,flag_draw = PETSC_FALSE,flag_contour = PETSC_FALSE,flag_operator = PETSC_FALSE;
28635f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject) snes)->options,((PetscObject)snes)->prefix,"-snes_compare_explicit",NULL,NULL,&flag));
28645f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject) snes)->options,((PetscObject)snes)->prefix,"-snes_compare_explicit_draw",NULL,NULL,&flag_draw));
28655f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject) snes)->options,((PetscObject)snes)->prefix,"-snes_compare_explicit_draw_contour",NULL,NULL,&flag_contour));
28665f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject) snes)->options,((PetscObject)snes)->prefix,"-snes_compare_operator",NULL,NULL,&flag_operator));
2867693365a8SJed Brown     if (flag || flag_draw || flag_contour) {
28680298fd71SBarry Smith       Mat          Bexp_mine = NULL,Bexp,FDexp;
2869693365a8SJed Brown       PetscViewer  vdraw,vstdout;
28706b3a5b13SJed Brown       PetscBool    flg;
2871693365a8SJed Brown       if (flag_operator) {
28725f80ce2aSJacob Faibussowitsch         CHKERRQ(MatComputeOperator(A,MATAIJ,&Bexp_mine));
2873693365a8SJed Brown         Bexp = Bexp_mine;
2874693365a8SJed Brown       } else {
2875693365a8SJed Brown         /* See if the preconditioning matrix can be viewed and added directly */
28765f80ce2aSJacob Faibussowitsch         CHKERRQ(PetscObjectBaseTypeCompareAny((PetscObject)B,&flg,MATSEQAIJ,MATMPIAIJ,MATSEQDENSE,MATMPIDENSE,MATSEQBAIJ,MATMPIBAIJ,MATSEQSBAIJ,MATMPIBAIJ,""));
287794ab13aaSBarry Smith         if (flg) Bexp = B;
2878693365a8SJed Brown         else {
2879693365a8SJed Brown           /* If the "preconditioning" matrix is itself MATSHELL or some other type without direct support */
28805f80ce2aSJacob Faibussowitsch           CHKERRQ(MatComputeOperator(B,MATAIJ,&Bexp_mine));
2881693365a8SJed Brown           Bexp = Bexp_mine;
2882693365a8SJed Brown         }
2883693365a8SJed Brown       }
28845f80ce2aSJacob Faibussowitsch       CHKERRQ(MatConvert(Bexp,MATSAME,MAT_INITIAL_MATRIX,&FDexp));
28855f80ce2aSJacob Faibussowitsch       CHKERRQ(SNESComputeJacobianDefault(snes,X,FDexp,FDexp,NULL));
28865f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes),&vstdout));
2887693365a8SJed Brown       if (flag_draw || flag_contour) {
28885f80ce2aSJacob Faibussowitsch         CHKERRQ(PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes),NULL,"Explicit Jacobians",PETSC_DECIDE,PETSC_DECIDE,300,300,&vdraw));
28895f80ce2aSJacob Faibussowitsch         if (flag_contour) CHKERRQ(PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR));
28900298fd71SBarry Smith       } else vdraw = NULL;
28915f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscViewerASCIIPrintf(vstdout,"Explicit %s\n",flag_operator ? "Jacobian" : "preconditioning Jacobian"));
28925f80ce2aSJacob Faibussowitsch       if (flag) CHKERRQ(MatView(Bexp,vstdout));
28935f80ce2aSJacob Faibussowitsch       if (vdraw) CHKERRQ(MatView(Bexp,vdraw));
28945f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscViewerASCIIPrintf(vstdout,"Finite difference Jacobian\n"));
28955f80ce2aSJacob Faibussowitsch       if (flag) CHKERRQ(MatView(FDexp,vstdout));
28965f80ce2aSJacob Faibussowitsch       if (vdraw) CHKERRQ(MatView(FDexp,vdraw));
28975f80ce2aSJacob Faibussowitsch       CHKERRQ(MatAYPX(FDexp,-1.0,Bexp,SAME_NONZERO_PATTERN));
28985f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscViewerASCIIPrintf(vstdout,"User-provided matrix minus finite difference Jacobian\n"));
28995f80ce2aSJacob Faibussowitsch       if (flag) CHKERRQ(MatView(FDexp,vstdout));
2900693365a8SJed Brown       if (vdraw) {              /* Always use contour for the difference */
29015f80ce2aSJacob Faibussowitsch         CHKERRQ(PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR));
29025f80ce2aSJacob Faibussowitsch         CHKERRQ(MatView(FDexp,vdraw));
29035f80ce2aSJacob Faibussowitsch         CHKERRQ(PetscViewerPopFormat(vdraw));
2904693365a8SJed Brown       }
29055f80ce2aSJacob Faibussowitsch       if (flag_contour) CHKERRQ(PetscViewerPopFormat(vdraw));
29065f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscViewerDestroy(&vdraw));
29075f80ce2aSJacob Faibussowitsch       CHKERRQ(MatDestroy(&Bexp_mine));
29085f80ce2aSJacob Faibussowitsch       CHKERRQ(MatDestroy(&FDexp));
2909693365a8SJed Brown     }
2910693365a8SJed Brown   }
29114c30e9fbSJed Brown   {
29126719d8e4SJed Brown     PetscBool flag = PETSC_FALSE,flag_display = PETSC_FALSE,flag_draw = PETSC_FALSE,flag_contour = PETSC_FALSE,flag_threshold = PETSC_FALSE;
29136719d8e4SJed Brown     PetscReal threshold_atol = PETSC_SQRT_MACHINE_EPSILON,threshold_rtol = 10*PETSC_SQRT_MACHINE_EPSILON;
29145f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring",NULL,NULL,&flag));
29155f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_display",NULL,NULL,&flag_display));
29165f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_draw",NULL,NULL,&flag_draw));
29175f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_draw_contour",NULL,NULL,&flag_contour));
29185f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_threshold",NULL,NULL,&flag_threshold));
291927b0f280SBarry Smith     if (flag_threshold) {
29205f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscOptionsGetReal(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_threshold_rtol",&threshold_rtol,NULL));
29215f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscOptionsGetReal(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_threshold_atol",&threshold_atol,NULL));
292227b0f280SBarry Smith     }
29236719d8e4SJed Brown     if (flag || flag_display || flag_draw || flag_contour || flag_threshold) {
29244c30e9fbSJed Brown       Mat            Bfd;
29254c30e9fbSJed Brown       PetscViewer    vdraw,vstdout;
2926335efc43SPeter Brune       MatColoring    coloring;
29274c30e9fbSJed Brown       ISColoring     iscoloring;
29284c30e9fbSJed Brown       MatFDColoring  matfdcoloring;
29294c30e9fbSJed Brown       PetscErrorCode (*func)(SNES,Vec,Vec,void*);
29304c30e9fbSJed Brown       void           *funcctx;
29316719d8e4SJed Brown       PetscReal      norm1,norm2,normmax;
29324c30e9fbSJed Brown 
29335f80ce2aSJacob Faibussowitsch       CHKERRQ(MatDuplicate(B,MAT_DO_NOT_COPY_VALUES,&Bfd));
29345f80ce2aSJacob Faibussowitsch       CHKERRQ(MatColoringCreate(Bfd,&coloring));
29355f80ce2aSJacob Faibussowitsch       CHKERRQ(MatColoringSetType(coloring,MATCOLORINGSL));
29365f80ce2aSJacob Faibussowitsch       CHKERRQ(MatColoringSetFromOptions(coloring));
29375f80ce2aSJacob Faibussowitsch       CHKERRQ(MatColoringApply(coloring,&iscoloring));
29385f80ce2aSJacob Faibussowitsch       CHKERRQ(MatColoringDestroy(&coloring));
29395f80ce2aSJacob Faibussowitsch       CHKERRQ(MatFDColoringCreate(Bfd,iscoloring,&matfdcoloring));
29405f80ce2aSJacob Faibussowitsch       CHKERRQ(MatFDColoringSetFromOptions(matfdcoloring));
29415f80ce2aSJacob Faibussowitsch       CHKERRQ(MatFDColoringSetUp(Bfd,iscoloring,matfdcoloring));
29425f80ce2aSJacob Faibussowitsch       CHKERRQ(ISColoringDestroy(&iscoloring));
29434c30e9fbSJed Brown 
29444c30e9fbSJed Brown       /* This method of getting the function is currently unreliable since it doesn't work for DM local functions. */
29455f80ce2aSJacob Faibussowitsch       CHKERRQ(SNESGetFunction(snes,NULL,&func,&funcctx));
29465f80ce2aSJacob Faibussowitsch       CHKERRQ(MatFDColoringSetFunction(matfdcoloring,(PetscErrorCode (*)(void))func,funcctx));
29475f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscObjectSetOptionsPrefix((PetscObject)matfdcoloring,((PetscObject)snes)->prefix));
29485f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscObjectAppendOptionsPrefix((PetscObject)matfdcoloring,"coloring_"));
29495f80ce2aSJacob Faibussowitsch       CHKERRQ(MatFDColoringSetFromOptions(matfdcoloring));
29505f80ce2aSJacob Faibussowitsch       CHKERRQ(MatFDColoringApply(Bfd,matfdcoloring,X,snes));
29515f80ce2aSJacob Faibussowitsch       CHKERRQ(MatFDColoringDestroy(&matfdcoloring));
29524c30e9fbSJed Brown 
29535f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes),&vstdout));
29544c30e9fbSJed Brown       if (flag_draw || flag_contour) {
29555f80ce2aSJacob Faibussowitsch         CHKERRQ(PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes),NULL,"Colored Jacobians",PETSC_DECIDE,PETSC_DECIDE,300,300,&vdraw));
29565f80ce2aSJacob Faibussowitsch         if (flag_contour) CHKERRQ(PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR));
29570298fd71SBarry Smith       } else vdraw = NULL;
29585f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscViewerASCIIPrintf(vstdout,"Explicit preconditioning Jacobian\n"));
29595f80ce2aSJacob Faibussowitsch       if (flag_display) CHKERRQ(MatView(B,vstdout));
29605f80ce2aSJacob Faibussowitsch       if (vdraw) CHKERRQ(MatView(B,vdraw));
29615f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscViewerASCIIPrintf(vstdout,"Colored Finite difference Jacobian\n"));
29625f80ce2aSJacob Faibussowitsch       if (flag_display) CHKERRQ(MatView(Bfd,vstdout));
29635f80ce2aSJacob Faibussowitsch       if (vdraw) CHKERRQ(MatView(Bfd,vdraw));
29645f80ce2aSJacob Faibussowitsch       CHKERRQ(MatAYPX(Bfd,-1.0,B,SAME_NONZERO_PATTERN));
29655f80ce2aSJacob Faibussowitsch       CHKERRQ(MatNorm(Bfd,NORM_1,&norm1));
29665f80ce2aSJacob Faibussowitsch       CHKERRQ(MatNorm(Bfd,NORM_FROBENIUS,&norm2));
29675f80ce2aSJacob Faibussowitsch       CHKERRQ(MatNorm(Bfd,NORM_MAX,&normmax));
29685f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscViewerASCIIPrintf(vstdout,"User-provided matrix minus finite difference Jacobian, norm1=%g normFrob=%g normmax=%g\n",(double)norm1,(double)norm2,(double)normmax));
29695f80ce2aSJacob Faibussowitsch       if (flag_display) CHKERRQ(MatView(Bfd,vstdout));
29704c30e9fbSJed Brown       if (vdraw) {              /* Always use contour for the difference */
29715f80ce2aSJacob Faibussowitsch         CHKERRQ(PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR));
29725f80ce2aSJacob Faibussowitsch         CHKERRQ(MatView(Bfd,vdraw));
29735f80ce2aSJacob Faibussowitsch         CHKERRQ(PetscViewerPopFormat(vdraw));
29744c30e9fbSJed Brown       }
29755f80ce2aSJacob Faibussowitsch       if (flag_contour) CHKERRQ(PetscViewerPopFormat(vdraw));
29766719d8e4SJed Brown 
29776719d8e4SJed Brown       if (flag_threshold) {
29786719d8e4SJed Brown         PetscInt bs,rstart,rend,i;
29795f80ce2aSJacob Faibussowitsch         CHKERRQ(MatGetBlockSize(B,&bs));
29805f80ce2aSJacob Faibussowitsch         CHKERRQ(MatGetOwnershipRange(B,&rstart,&rend));
29816719d8e4SJed Brown         for (i=rstart; i<rend; i++) {
29826719d8e4SJed Brown           const PetscScalar *ba,*ca;
29836719d8e4SJed Brown           const PetscInt    *bj,*cj;
29846719d8e4SJed Brown           PetscInt          bn,cn,j,maxentrycol = -1,maxdiffcol = -1,maxrdiffcol = -1;
29856719d8e4SJed Brown           PetscReal         maxentry = 0,maxdiff = 0,maxrdiff = 0;
29865f80ce2aSJacob Faibussowitsch           CHKERRQ(MatGetRow(B,i,&bn,&bj,&ba));
29875f80ce2aSJacob Faibussowitsch           CHKERRQ(MatGetRow(Bfd,i,&cn,&cj,&ca));
29885f80ce2aSJacob Faibussowitsch           PetscCheck(bn == cn,((PetscObject)A)->comm,PETSC_ERR_PLIB,"Unexpected different nonzero pattern in -snes_compare_coloring_threshold");
29896719d8e4SJed Brown           for (j=0; j<bn; j++) {
29906719d8e4SJed Brown             PetscReal rdiff = PetscAbsScalar(ca[j]) / (threshold_atol + threshold_rtol*PetscAbsScalar(ba[j]));
29916719d8e4SJed Brown             if (PetscAbsScalar(ba[j]) > PetscAbs(maxentry)) {
29926719d8e4SJed Brown               maxentrycol = bj[j];
29936719d8e4SJed Brown               maxentry    = PetscRealPart(ba[j]);
29946719d8e4SJed Brown             }
29956719d8e4SJed Brown             if (PetscAbsScalar(ca[j]) > PetscAbs(maxdiff)) {
29966719d8e4SJed Brown               maxdiffcol = bj[j];
29976719d8e4SJed Brown               maxdiff    = PetscRealPart(ca[j]);
29986719d8e4SJed Brown             }
29996719d8e4SJed Brown             if (rdiff > maxrdiff) {
30006719d8e4SJed Brown               maxrdiffcol = bj[j];
30016719d8e4SJed Brown               maxrdiff    = rdiff;
30026719d8e4SJed Brown             }
30036719d8e4SJed Brown           }
30046719d8e4SJed Brown           if (maxrdiff > 1) {
30055f80ce2aSJacob Faibussowitsch             CHKERRQ(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));
30066719d8e4SJed Brown             for (j=0; j<bn; j++) {
30076719d8e4SJed Brown               PetscReal rdiff;
30086719d8e4SJed Brown               rdiff = PetscAbsScalar(ca[j]) / (threshold_atol + threshold_rtol*PetscAbsScalar(ba[j]));
30096719d8e4SJed Brown               if (rdiff > 1) {
30105f80ce2aSJacob Faibussowitsch                 CHKERRQ(PetscViewerASCIIPrintf(vstdout," (%D,%g:%g)",bj[j],(double)PetscRealPart(ba[j]),(double)PetscRealPart(ca[j])));
30116719d8e4SJed Brown               }
30126719d8e4SJed Brown             }
30135f80ce2aSJacob Faibussowitsch             CHKERRQ(PetscViewerASCIIPrintf(vstdout,"\n",i,maxentry,maxdiff,maxrdiff));
30146719d8e4SJed Brown           }
30155f80ce2aSJacob Faibussowitsch           CHKERRQ(MatRestoreRow(B,i,&bn,&bj,&ba));
30165f80ce2aSJacob Faibussowitsch           CHKERRQ(MatRestoreRow(Bfd,i,&cn,&cj,&ca));
30176719d8e4SJed Brown         }
30186719d8e4SJed Brown       }
30195f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscViewerDestroy(&vdraw));
30205f80ce2aSJacob Faibussowitsch       CHKERRQ(MatDestroy(&Bfd));
30214c30e9fbSJed Brown     }
30224c30e9fbSJed Brown   }
30233a40ed3dSBarry Smith   PetscFunctionReturn(0);
30249b94acceSBarry Smith }
30259b94acceSBarry Smith 
3026bf388a1fSBarry Smith /*MC
3027411c0326SBarry Smith     SNESJacobianFunction - Function used to convey the nonlinear Jacobian of the function to be solved by SNES
3028bf388a1fSBarry Smith 
3029bf388a1fSBarry Smith      Synopsis:
3030411c0326SBarry Smith      #include "petscsnes.h"
3031411c0326SBarry Smith      PetscErrorCode SNESJacobianFunction(SNES snes,Vec x,Mat Amat,Mat Pmat,void *ctx);
3032bf388a1fSBarry Smith 
30331843f636SBarry Smith      Collective on snes
30341843f636SBarry Smith 
30351843f636SBarry Smith     Input Parameters:
30361843f636SBarry Smith +  x - input vector, the Jacobian is to be computed at this value
3037bf388a1fSBarry Smith -  ctx - [optional] user-defined Jacobian context
3038bf388a1fSBarry Smith 
30391843f636SBarry Smith     Output Parameters:
30401843f636SBarry Smith +  Amat - the matrix that defines the (approximate) Jacobian
30411843f636SBarry Smith -  Pmat - the matrix to be used in constructing the preconditioner, usually the same as Amat.
30421843f636SBarry Smith 
3043878cb397SSatish Balay    Level: intermediate
3044878cb397SSatish Balay 
3045bf388a1fSBarry Smith .seealso:   SNESSetFunction(), SNESGetFunction(), SNESSetJacobian(), SNESGetJacobian()
3046bf388a1fSBarry Smith M*/
3047bf388a1fSBarry Smith 
30489b94acceSBarry Smith /*@C
30499b94acceSBarry Smith    SNESSetJacobian - Sets the function to compute Jacobian as well as the
3050044dda88SLois Curfman McInnes    location to store the matrix.
30519b94acceSBarry Smith 
3052d083f849SBarry Smith    Logically Collective on SNES
3053c7afd0dbSLois Curfman McInnes 
30549b94acceSBarry Smith    Input Parameters:
3055c7afd0dbSLois Curfman McInnes +  snes - the SNES context
3056e5d3d808SBarry Smith .  Amat - the matrix that defines the (approximate) Jacobian
3057e5d3d808SBarry Smith .  Pmat - the matrix to be used in constructing the preconditioner, usually the same as Amat.
3058411c0326SBarry Smith .  J - Jacobian evaluation routine (if NULL then SNES retains any previously set value), see SNESJacobianFunction for details
3059c7afd0dbSLois Curfman McInnes -  ctx - [optional] user-defined context for private data for the
30600298fd71SBarry Smith          Jacobian evaluation routine (may be NULL) (if NULL then SNES retains any previously set value)
30619b94acceSBarry Smith 
30629b94acceSBarry Smith    Notes:
3063e5d3d808SBarry Smith    If the Amat matrix and Pmat matrix are different you must call MatAssemblyBegin/End() on
306416913363SBarry Smith    each matrix.
306516913363SBarry Smith 
3066895c21f2SBarry Smith    If you know the operator Amat has a null space you can use MatSetNullSpace() and MatSetTransposeNullSpace() to supply the null
3067895c21f2SBarry Smith    space to Amat and the KSP solvers will automatically use that null space as needed during the solution process.
3068895c21f2SBarry Smith 
30698d359177SBarry Smith    If using SNESComputeJacobianDefaultColor() to assemble a Jacobian, the ctx argument
3070a8a26c1eSJed Brown    must be a MatFDColoring.
3071a8a26c1eSJed Brown 
3072c3cc8fd1SJed Brown    Other defect-correction schemes can be used by computing a different matrix in place of the Jacobian.  One common
3073c3cc8fd1SJed Brown    example is to use the "Picard linearization" which only differentiates through the highest order parts of each term.
3074c3cc8fd1SJed Brown 
307536851e7fSLois Curfman McInnes    Level: beginner
307636851e7fSLois Curfman McInnes 
3077411c0326SBarry Smith .seealso: KSPSetOperators(), SNESSetFunction(), MatMFFDComputeJacobian(), SNESComputeJacobianDefaultColor(), MatStructure, J,
3078411c0326SBarry Smith           SNESSetPicard(), SNESJacobianFunction
30799b94acceSBarry Smith @*/
3080d1e9a80fSBarry Smith PetscErrorCode  SNESSetJacobian(SNES snes,Mat Amat,Mat Pmat,PetscErrorCode (*J)(SNES,Vec,Mat,Mat,void*),void *ctx)
30819b94acceSBarry Smith {
30826cab3a1bSJed Brown   DM             dm;
30833a7fca6bSBarry Smith 
30843a40ed3dSBarry Smith   PetscFunctionBegin;
30850700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3086e5d3d808SBarry Smith   if (Amat) PetscValidHeaderSpecific(Amat,MAT_CLASSID,2);
3087e5d3d808SBarry Smith   if (Pmat) PetscValidHeaderSpecific(Pmat,MAT_CLASSID,3);
3088e5d3d808SBarry Smith   if (Amat) PetscCheckSameComm(snes,1,Amat,2);
3089e5d3d808SBarry Smith   if (Pmat) PetscCheckSameComm(snes,1,Pmat,3);
30905f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESGetDM(snes,&dm));
30915f80ce2aSJacob Faibussowitsch   CHKERRQ(DMSNESSetJacobian(dm,J,ctx));
3092e5d3d808SBarry Smith   if (Amat) {
30935f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscObjectReference((PetscObject)Amat));
30945f80ce2aSJacob Faibussowitsch     CHKERRQ(MatDestroy(&snes->jacobian));
3095f5af7f23SKarl Rupp 
3096e5d3d808SBarry Smith     snes->jacobian = Amat;
30973a7fca6bSBarry Smith   }
3098e5d3d808SBarry Smith   if (Pmat) {
30995f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscObjectReference((PetscObject)Pmat));
31005f80ce2aSJacob Faibussowitsch     CHKERRQ(MatDestroy(&snes->jacobian_pre));
3101f5af7f23SKarl Rupp 
3102e5d3d808SBarry Smith     snes->jacobian_pre = Pmat;
31033a7fca6bSBarry Smith   }
31043a40ed3dSBarry Smith   PetscFunctionReturn(0);
31059b94acceSBarry Smith }
310662fef451SLois Curfman McInnes 
3107c2aafc4cSSatish Balay /*@C
3108b4fd4287SBarry Smith    SNESGetJacobian - Returns the Jacobian matrix and optionally the user
3109b4fd4287SBarry Smith    provided context for evaluating the Jacobian.
3110b4fd4287SBarry Smith 
3111c7afd0dbSLois Curfman McInnes    Not Collective, but Mat object will be parallel if SNES object is
3112c7afd0dbSLois Curfman McInnes 
3113b4fd4287SBarry Smith    Input Parameter:
3114b4fd4287SBarry Smith .  snes - the nonlinear solver context
3115b4fd4287SBarry Smith 
3116b4fd4287SBarry Smith    Output Parameters:
3117e5d3d808SBarry Smith +  Amat - location to stash (approximate) Jacobian matrix (or NULL)
3118e5d3d808SBarry Smith .  Pmat - location to stash matrix used to compute the preconditioner (or NULL)
3119411c0326SBarry Smith .  J - location to put Jacobian function (or NULL), see SNESJacobianFunction for details on its calling sequence
31200298fd71SBarry Smith -  ctx - location to stash Jacobian ctx (or NULL)
3121fee21e36SBarry Smith 
312236851e7fSLois Curfman McInnes    Level: advanced
312336851e7fSLois Curfman McInnes 
3124411c0326SBarry Smith .seealso: SNESSetJacobian(), SNESComputeJacobian(), SNESJacobianFunction, SNESGetFunction()
3125b4fd4287SBarry Smith @*/
3126d1e9a80fSBarry Smith PetscErrorCode SNESGetJacobian(SNES snes,Mat *Amat,Mat *Pmat,PetscErrorCode (**J)(SNES,Vec,Mat,Mat,void*),void **ctx)
3127b4fd4287SBarry Smith {
31286cab3a1bSJed Brown   DM             dm;
3129942e3340SBarry Smith   DMSNES         sdm;
31306cab3a1bSJed Brown 
31313a40ed3dSBarry Smith   PetscFunctionBegin;
31320700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3133e5d3d808SBarry Smith   if (Amat) *Amat = snes->jacobian;
3134e5d3d808SBarry Smith   if (Pmat) *Pmat = snes->jacobian_pre;
31355f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESGetDM(snes,&dm));
31365f80ce2aSJacob Faibussowitsch   CHKERRQ(DMGetDMSNES(dm,&sdm));
3137f8b49ee9SBarry Smith   if (J) *J = sdm->ops->computejacobian;
31386cab3a1bSJed Brown   if (ctx) *ctx = sdm->jacobianctx;
31393a40ed3dSBarry Smith   PetscFunctionReturn(0);
3140b4fd4287SBarry Smith }
3141b4fd4287SBarry Smith 
314258b371f3SBarry Smith static PetscErrorCode SNESSetDefaultComputeJacobian(SNES snes)
314358b371f3SBarry Smith {
314458b371f3SBarry Smith   DM             dm;
314558b371f3SBarry Smith   DMSNES         sdm;
314658b371f3SBarry Smith 
314758b371f3SBarry Smith   PetscFunctionBegin;
31485f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESGetDM(snes,&dm));
31495f80ce2aSJacob Faibussowitsch   CHKERRQ(DMGetDMSNES(dm,&sdm));
315058b371f3SBarry Smith   if (!sdm->ops->computejacobian && snes->jacobian_pre) {
315158b371f3SBarry Smith     DM        dm;
315258b371f3SBarry Smith     PetscBool isdense,ismf;
315358b371f3SBarry Smith 
31545f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESGetDM(snes,&dm));
31555f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscObjectTypeCompareAny((PetscObject)snes->jacobian_pre,&isdense,MATSEQDENSE,MATMPIDENSE,MATDENSE,NULL));
31565f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscObjectTypeCompareAny((PetscObject)snes->jacobian_pre,&ismf,MATMFFD,MATSHELL,NULL));
315758b371f3SBarry Smith     if (isdense) {
31585f80ce2aSJacob Faibussowitsch       CHKERRQ(DMSNESSetJacobian(dm,SNESComputeJacobianDefault,NULL));
315958b371f3SBarry Smith     } else if (!ismf) {
31605f80ce2aSJacob Faibussowitsch       CHKERRQ(DMSNESSetJacobian(dm,SNESComputeJacobianDefaultColor,NULL));
316158b371f3SBarry Smith     }
316258b371f3SBarry Smith   }
316358b371f3SBarry Smith   PetscFunctionReturn(0);
316458b371f3SBarry Smith }
316558b371f3SBarry Smith 
31669b94acceSBarry Smith /*@
31679b94acceSBarry Smith    SNESSetUp - Sets up the internal data structures for the later use
3168272ac6f2SLois Curfman McInnes    of a nonlinear solver.
31699b94acceSBarry Smith 
3170fee21e36SBarry Smith    Collective on SNES
3171fee21e36SBarry Smith 
3172c7afd0dbSLois Curfman McInnes    Input Parameters:
317370e92668SMatthew Knepley .  snes - the SNES context
3174c7afd0dbSLois Curfman McInnes 
3175272ac6f2SLois Curfman McInnes    Notes:
3176272ac6f2SLois Curfman McInnes    For basic use of the SNES solvers the user need not explicitly call
3177272ac6f2SLois Curfman McInnes    SNESSetUp(), since these actions will automatically occur during
3178272ac6f2SLois Curfman McInnes    the call to SNESSolve().  However, if one wishes to control this
3179272ac6f2SLois Curfman McInnes    phase separately, SNESSetUp() should be called after SNESCreate()
3180272ac6f2SLois Curfman McInnes    and optional routines of the form SNESSetXXX(), but before SNESSolve().
3181272ac6f2SLois Curfman McInnes 
318236851e7fSLois Curfman McInnes    Level: advanced
318336851e7fSLois Curfman McInnes 
31849b94acceSBarry Smith .seealso: SNESCreate(), SNESSolve(), SNESDestroy()
31859b94acceSBarry Smith @*/
31867087cfbeSBarry Smith PetscErrorCode  SNESSetUp(SNES snes)
31879b94acceSBarry Smith {
31886cab3a1bSJed Brown   DM             dm;
3189942e3340SBarry Smith   DMSNES         sdm;
3190c35f09e5SBarry Smith   SNESLineSearch linesearch, pclinesearch;
31916e2a1849SPeter Brune   void           *lsprectx,*lspostctx;
31926b2b7091SBarry Smith   PetscErrorCode (*precheck)(SNESLineSearch,Vec,Vec,PetscBool*,void*);
31936b2b7091SBarry Smith   PetscErrorCode (*postcheck)(SNESLineSearch,Vec,Vec,Vec,PetscBool*,PetscBool*,void*);
31946e2a1849SPeter Brune   PetscErrorCode (*func)(SNES,Vec,Vec,void*);
31956e2a1849SPeter Brune   Vec            f,fpc;
31966e2a1849SPeter Brune   void           *funcctx;
3197d1e9a80fSBarry Smith   PetscErrorCode (*jac)(SNES,Vec,Mat,Mat,void*);
31981eb13d49SPeter Brune   void           *jacctx,*appctx;
319932b97717SPeter Brune   Mat            j,jpre;
32003a40ed3dSBarry Smith 
32013a40ed3dSBarry Smith   PetscFunctionBegin;
32020700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
32034dc4c822SBarry Smith   if (snes->setupcalled) PetscFunctionReturn(0);
32045f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscLogEventBegin(SNES_Setup,snes,0,0,0));
32059b94acceSBarry Smith 
32067adad957SLisandro Dalcin   if (!((PetscObject)snes)->type_name) {
32075f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESSetType(snes,SNESNEWTONLS));
320885385478SLisandro Dalcin   }
320985385478SLisandro Dalcin 
32105f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESGetFunction(snes,&snes->vec_func,NULL,NULL));
321158c9b817SLisandro Dalcin 
32125f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESGetDM(snes,&dm));
32135f80ce2aSJacob Faibussowitsch   CHKERRQ(DMGetDMSNES(dm,&sdm));
32145f80ce2aSJacob Faibussowitsch   PetscCheck(sdm->ops->computefunction,PetscObjectComm((PetscObject)dm),PETSC_ERR_ARG_WRONGSTATE,"Function never provided to SNES object");
32155f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESSetDefaultComputeJacobian(snes));
321658b371f3SBarry Smith 
32176cab3a1bSJed Brown   if (!snes->vec_func) {
32185f80ce2aSJacob Faibussowitsch     CHKERRQ(DMCreateGlobalVector(dm,&snes->vec_func));
3219214df951SJed Brown   }
3220efd51863SBarry Smith 
322122d28d08SBarry Smith   if (!snes->ksp) {
32225f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESGetKSP(snes, &snes->ksp));
322322d28d08SBarry Smith   }
3224b710008aSBarry Smith 
3225d8d34be6SBarry Smith   if (snes->linesearch) {
32265f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESGetLineSearch(snes, &snes->linesearch));
32275f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESLineSearchSetFunction(snes->linesearch,SNESComputeFunction));
3228d8d34be6SBarry Smith   }
32299e764e56SPeter Brune 
3230b552625fSStefano Zampini   if (snes->npc && snes->npcside == PC_LEFT) {
3231172a4300SPeter Brune     snes->mf          = PETSC_TRUE;
3232172a4300SPeter Brune     snes->mf_operator = PETSC_FALSE;
3233172a4300SPeter Brune   }
3234d8f46077SPeter Brune 
3235efd4aadfSBarry Smith   if (snes->npc) {
32366e2a1849SPeter Brune     /* copy the DM over */
32375f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESGetDM(snes,&dm));
32385f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESSetDM(snes->npc,dm));
32396e2a1849SPeter Brune 
32405f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESGetFunction(snes,&f,&func,&funcctx));
32415f80ce2aSJacob Faibussowitsch     CHKERRQ(VecDuplicate(f,&fpc));
32425f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESSetFunction(snes->npc,fpc,func,funcctx));
32435f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESGetJacobian(snes,&j,&jpre,&jac,&jacctx));
32445f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESSetJacobian(snes->npc,j,jpre,jac,jacctx));
32455f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESGetApplicationContext(snes,&appctx));
32465f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESSetApplicationContext(snes->npc,appctx));
32475f80ce2aSJacob Faibussowitsch     CHKERRQ(VecDestroy(&fpc));
32486e2a1849SPeter Brune 
32496e2a1849SPeter Brune     /* copy the function pointers over */
32505f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscObjectCopyFortranFunctionPointers((PetscObject)snes,(PetscObject)snes->npc));
32516e2a1849SPeter Brune 
32526e2a1849SPeter Brune     /* default to 1 iteration */
32535f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESSetTolerances(snes->npc,0.0,0.0,0.0,1,snes->npc->max_funcs));
3254efd4aadfSBarry Smith     if (snes->npcside == PC_RIGHT) {
32555f80ce2aSJacob Faibussowitsch       CHKERRQ(SNESSetNormSchedule(snes->npc,SNES_NORM_FINAL_ONLY));
3256a9936a0cSPeter Brune     } else {
32575f80ce2aSJacob Faibussowitsch       CHKERRQ(SNESSetNormSchedule(snes->npc,SNES_NORM_NONE));
3258a9936a0cSPeter Brune     }
32595f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESSetFromOptions(snes->npc));
32606e2a1849SPeter Brune 
32616e2a1849SPeter Brune     /* copy the line search context over */
3262d8d34be6SBarry Smith     if (snes->linesearch && snes->npc->linesearch) {
32635f80ce2aSJacob Faibussowitsch       CHKERRQ(SNESGetLineSearch(snes,&linesearch));
32645f80ce2aSJacob Faibussowitsch       CHKERRQ(SNESGetLineSearch(snes->npc,&pclinesearch));
32655f80ce2aSJacob Faibussowitsch       CHKERRQ(SNESLineSearchGetPreCheck(linesearch,&precheck,&lsprectx));
32665f80ce2aSJacob Faibussowitsch       CHKERRQ(SNESLineSearchGetPostCheck(linesearch,&postcheck,&lspostctx));
32675f80ce2aSJacob Faibussowitsch       CHKERRQ(SNESLineSearchSetPreCheck(pclinesearch,precheck,lsprectx));
32685f80ce2aSJacob Faibussowitsch       CHKERRQ(SNESLineSearchSetPostCheck(pclinesearch,postcheck,lspostctx));
32695f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscObjectCopyFortranFunctionPointers((PetscObject)linesearch, (PetscObject)pclinesearch));
32706e2a1849SPeter Brune     }
3271d8d34be6SBarry Smith   }
327232b97717SPeter Brune   if (snes->mf) {
32735f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESSetUpMatrixFree_Private(snes, snes->mf_operator, snes->mf_version));
327432b97717SPeter Brune   }
327532b97717SPeter Brune   if (snes->ops->usercompute && !snes->user) {
32765f80ce2aSJacob Faibussowitsch     CHKERRQ((*snes->ops->usercompute)(snes,(void**)&snes->user));
327732b97717SPeter Brune   }
32786e2a1849SPeter Brune 
327937ec4e1aSPeter Brune   snes->jac_iter = 0;
328037ec4e1aSPeter Brune   snes->pre_iter = 0;
328137ec4e1aSPeter Brune 
3282410397dcSLisandro Dalcin   if (snes->ops->setup) {
32835f80ce2aSJacob Faibussowitsch     CHKERRQ((*snes->ops->setup)(snes));
3284410397dcSLisandro Dalcin   }
328558c9b817SLisandro Dalcin 
32865f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESSetDefaultComputeJacobian(snes));
328758b371f3SBarry Smith 
3288b552625fSStefano Zampini   if (snes->npc && snes->npcside == PC_LEFT) {
32896c67d002SPeter Brune     if (snes->functype == SNES_FUNCTION_PRECONDITIONED) {
3290d8d34be6SBarry Smith       if (snes->linesearch) {
32915f80ce2aSJacob Faibussowitsch         CHKERRQ(SNESGetLineSearch(snes,&linesearch));
32925f80ce2aSJacob Faibussowitsch         CHKERRQ(SNESLineSearchSetFunction(linesearch,SNESComputeFunctionDefaultNPC));
32936c67d002SPeter Brune       }
32946c67d002SPeter Brune     }
3295d8d34be6SBarry Smith   }
32965f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscLogEventEnd(SNES_Setup,snes,0,0,0));
32977aaed0d8SBarry Smith   snes->setupcalled = PETSC_TRUE;
32983a40ed3dSBarry Smith   PetscFunctionReturn(0);
32999b94acceSBarry Smith }
33009b94acceSBarry Smith 
330137596af1SLisandro Dalcin /*@
330237596af1SLisandro Dalcin    SNESReset - Resets a SNES context to the snessetupcalled = 0 state and removes any allocated Vecs and Mats
330337596af1SLisandro Dalcin 
330437596af1SLisandro Dalcin    Collective on SNES
330537596af1SLisandro Dalcin 
330637596af1SLisandro Dalcin    Input Parameter:
330737596af1SLisandro Dalcin .  snes - iterative context obtained from SNESCreate()
330837596af1SLisandro Dalcin 
3309d25893d9SBarry Smith    Level: intermediate
3310d25893d9SBarry Smith 
331195452b02SPatrick Sanan    Notes:
331295452b02SPatrick Sanan     Also calls the application context destroy routine set with SNESSetComputeApplicationContext()
331337596af1SLisandro Dalcin 
331437596af1SLisandro Dalcin .seealso: SNESCreate(), SNESSetUp(), SNESSolve()
331537596af1SLisandro Dalcin @*/
331637596af1SLisandro Dalcin PetscErrorCode  SNESReset(SNES snes)
331737596af1SLisandro Dalcin {
331837596af1SLisandro Dalcin   PetscFunctionBegin;
331937596af1SLisandro Dalcin   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3320d25893d9SBarry Smith   if (snes->ops->userdestroy && snes->user) {
33215f80ce2aSJacob Faibussowitsch     CHKERRQ((*snes->ops->userdestroy)((void**)&snes->user));
33220298fd71SBarry Smith     snes->user = NULL;
3323d25893d9SBarry Smith   }
3324efd4aadfSBarry Smith   if (snes->npc) {
33255f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESReset(snes->npc));
33268a23116dSBarry Smith   }
33278a23116dSBarry Smith 
332837596af1SLisandro Dalcin   if (snes->ops->reset) {
33295f80ce2aSJacob Faibussowitsch     CHKERRQ((*snes->ops->reset)(snes));
333037596af1SLisandro Dalcin   }
33319e764e56SPeter Brune   if (snes->ksp) {
33325f80ce2aSJacob Faibussowitsch     CHKERRQ(KSPReset(snes->ksp));
33339e764e56SPeter Brune   }
33349e764e56SPeter Brune 
33359e764e56SPeter Brune   if (snes->linesearch) {
33365f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESLineSearchReset(snes->linesearch));
33379e764e56SPeter Brune   }
33389e764e56SPeter Brune 
33395f80ce2aSJacob Faibussowitsch   CHKERRQ(VecDestroy(&snes->vec_rhs));
33405f80ce2aSJacob Faibussowitsch   CHKERRQ(VecDestroy(&snes->vec_sol));
33415f80ce2aSJacob Faibussowitsch   CHKERRQ(VecDestroy(&snes->vec_sol_update));
33425f80ce2aSJacob Faibussowitsch   CHKERRQ(VecDestroy(&snes->vec_func));
33435f80ce2aSJacob Faibussowitsch   CHKERRQ(MatDestroy(&snes->jacobian));
33445f80ce2aSJacob Faibussowitsch   CHKERRQ(MatDestroy(&snes->jacobian_pre));
33455f80ce2aSJacob Faibussowitsch   CHKERRQ(MatDestroy(&snes->picard));
33465f80ce2aSJacob Faibussowitsch   CHKERRQ(VecDestroyVecs(snes->nwork,&snes->work));
33475f80ce2aSJacob Faibussowitsch   CHKERRQ(VecDestroyVecs(snes->nvwork,&snes->vwork));
3348f5af7f23SKarl Rupp 
334940fdac6aSLawrence Mitchell   snes->alwayscomputesfinalresidual = PETSC_FALSE;
335040fdac6aSLawrence Mitchell 
335137596af1SLisandro Dalcin   snes->nwork       = snes->nvwork = 0;
335237596af1SLisandro Dalcin   snes->setupcalled = PETSC_FALSE;
335337596af1SLisandro Dalcin   PetscFunctionReturn(0);
335437596af1SLisandro Dalcin }
335537596af1SLisandro Dalcin 
335652baeb72SSatish Balay /*@
3357c4421ceaSFande Kong    SNESConvergedReasonViewCancel - Clears all the reasonview functions for a SNES object.
3358c4421ceaSFande Kong 
3359c4421ceaSFande Kong    Collective on SNES
3360c4421ceaSFande Kong 
3361c4421ceaSFande Kong    Input Parameter:
3362c4421ceaSFande Kong .  snes - iterative context obtained from SNESCreate()
3363c4421ceaSFande Kong 
3364c4421ceaSFande Kong    Level: intermediate
3365c4421ceaSFande Kong 
3366c4421ceaSFande Kong .seealso: SNESCreate(), SNESDestroy(), SNESReset()
3367c4421ceaSFande Kong @*/
3368c4421ceaSFande Kong PetscErrorCode  SNESConvergedReasonViewCancel(SNES snes)
3369c4421ceaSFande Kong {
3370c4421ceaSFande Kong   PetscInt       i;
3371c4421ceaSFande Kong 
3372c4421ceaSFande Kong   PetscFunctionBegin;
3373c4421ceaSFande Kong   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3374c4421ceaSFande Kong   for (i=0; i<snes->numberreasonviews; i++) {
3375c4421ceaSFande Kong     if (snes->reasonviewdestroy[i]) {
33765f80ce2aSJacob Faibussowitsch       CHKERRQ((*snes->reasonviewdestroy[i])(&snes->reasonviewcontext[i]));
3377c4421ceaSFande Kong     }
3378c4421ceaSFande Kong   }
3379c4421ceaSFande Kong   snes->numberreasonviews = 0;
3380c4421ceaSFande Kong   PetscFunctionReturn(0);
3381c4421ceaSFande Kong }
3382c4421ceaSFande Kong 
33831fb7b255SJunchao Zhang /*@C
33849b94acceSBarry Smith    SNESDestroy - Destroys the nonlinear solver context that was created
33859b94acceSBarry Smith    with SNESCreate().
33869b94acceSBarry Smith 
3387c7afd0dbSLois Curfman McInnes    Collective on SNES
3388c7afd0dbSLois Curfman McInnes 
33899b94acceSBarry Smith    Input Parameter:
33909b94acceSBarry Smith .  snes - the SNES context
33919b94acceSBarry Smith 
339236851e7fSLois Curfman McInnes    Level: beginner
339336851e7fSLois Curfman McInnes 
339463a78c88SLois Curfman McInnes .seealso: SNESCreate(), SNESSolve()
33959b94acceSBarry Smith @*/
33966bf464f9SBarry Smith PetscErrorCode  SNESDestroy(SNES *snes)
33979b94acceSBarry Smith {
33983a40ed3dSBarry Smith   PetscFunctionBegin;
33996bf464f9SBarry Smith   if (!*snes) PetscFunctionReturn(0);
34006bf464f9SBarry Smith   PetscValidHeaderSpecific((*snes),SNES_CLASSID,1);
34019e5d0892SLisandro Dalcin   if (--((PetscObject)(*snes))->refct > 0) {*snes = NULL; PetscFunctionReturn(0);}
3402d4bb536fSBarry Smith 
34035f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESReset((*snes)));
34045f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESDestroy(&(*snes)->npc));
34056b8b9a38SLisandro Dalcin 
3406e04113cfSBarry Smith   /* if memory was published with SAWs then destroy it */
34075f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscObjectSAWsViewOff((PetscObject)*snes));
34085f80ce2aSJacob Faibussowitsch   if ((*snes)->ops->destroy) CHKERRQ((*((*snes))->ops->destroy)((*snes)));
34096d4c513bSLisandro Dalcin 
34105f80ce2aSJacob Faibussowitsch   if ((*snes)->dm) CHKERRQ(DMCoarsenHookRemove((*snes)->dm,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,*snes));
34115f80ce2aSJacob Faibussowitsch   CHKERRQ(DMDestroy(&(*snes)->dm));
34125f80ce2aSJacob Faibussowitsch   CHKERRQ(KSPDestroy(&(*snes)->ksp));
34135f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESLineSearchDestroy(&(*snes)->linesearch));
34146b8b9a38SLisandro Dalcin 
34155f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscFree((*snes)->kspconvctx));
34166bf464f9SBarry Smith   if ((*snes)->ops->convergeddestroy) {
34175f80ce2aSJacob Faibussowitsch     CHKERRQ((*(*snes)->ops->convergeddestroy)((*snes)->cnvP));
34186b8b9a38SLisandro Dalcin   }
3419071fcb05SBarry Smith   if ((*snes)->conv_hist_alloc) {
34205f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscFree2((*snes)->conv_hist,(*snes)->conv_hist_its));
342158c9b817SLisandro Dalcin   }
34225f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESMonitorCancel((*snes)));
34235f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESConvergedReasonViewCancel((*snes)));
34245f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscHeaderDestroy(snes));
34253a40ed3dSBarry Smith   PetscFunctionReturn(0);
34269b94acceSBarry Smith }
34279b94acceSBarry Smith 
34289b94acceSBarry Smith /* ----------- Routines to set solver parameters ---------- */
34299b94acceSBarry Smith 
3430a8054027SBarry Smith /*@
3431a8054027SBarry Smith    SNESSetLagPreconditioner - Determines when the preconditioner is rebuilt in the nonlinear solve.
3432a8054027SBarry Smith 
34333f9fe445SBarry Smith    Logically Collective on SNES
3434a8054027SBarry Smith 
3435a8054027SBarry Smith    Input Parameters:
3436a8054027SBarry Smith +  snes - the SNES context
3437d8e291bfSBarry Smith -  lag - 1 means rebuild every time the Jacobian is computed within a single nonlinear solve, 2 means every second time
34383b4f5425SBarry Smith          the Jacobian is built etc. -2 indicates rebuild preconditioner at next chance but then never rebuild after that
3439a8054027SBarry Smith 
3440a8054027SBarry Smith    Options Database Keys:
34413d5a8a6aSBarry Smith +    -snes_lag_jacobian_persists <true,false> - sets the persistence
34423d5a8a6aSBarry Smith .    -snes_lag_jacobian <-2,1,2,...> - sets the lag
34433d5a8a6aSBarry Smith .    -snes_lag_preconditioner_persists <true,false> - sets the persistence
34443d5a8a6aSBarry Smith -    -snes_lag_preconditioner <-2,1,2,...> - sets the lag
3445a8054027SBarry Smith 
3446a8054027SBarry Smith    Notes:
3447a8054027SBarry Smith    The default is 1
34483d5a8a6aSBarry Smith    The preconditioner is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1 or SNESSetLagPreconditionerPersists() was called
3449d8e291bfSBarry Smith 
3450d8e291bfSBarry Smith    SNESSetLagPreconditionerPersists() allows using the same uniform lagging (for example every second solve) across multiple solves.
3451a8054027SBarry Smith 
3452a8054027SBarry Smith    Level: intermediate
3453a8054027SBarry Smith 
34543d5a8a6aSBarry Smith .seealso: SNESSetTrustRegionTolerance(), SNESGetLagPreconditioner(), SNESSetLagJacobian(), SNESGetLagJacobian(), SNESSetLagPreconditionerPersists(),
34553d5a8a6aSBarry Smith           SNESSetLagJacobianPersists()
3456a8054027SBarry Smith 
3457a8054027SBarry Smith @*/
34587087cfbeSBarry Smith PetscErrorCode  SNESSetLagPreconditioner(SNES snes,PetscInt lag)
3459a8054027SBarry Smith {
3460a8054027SBarry Smith   PetscFunctionBegin;
34610700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
34625f80ce2aSJacob Faibussowitsch   PetscCheck(lag >= -2,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag must be -2, -1, 1 or greater");
34635f80ce2aSJacob Faibussowitsch   PetscCheck(lag,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag cannot be 0");
3464c5eb9154SBarry Smith   PetscValidLogicalCollectiveInt(snes,lag,2);
3465a8054027SBarry Smith   snes->lagpreconditioner = lag;
3466a8054027SBarry Smith   PetscFunctionReturn(0);
3467a8054027SBarry Smith }
3468a8054027SBarry Smith 
3469efd51863SBarry Smith /*@
3470efd51863SBarry Smith    SNESSetGridSequence - sets the number of steps of grid sequencing that SNES does
3471efd51863SBarry Smith 
3472efd51863SBarry Smith    Logically Collective on SNES
3473efd51863SBarry Smith 
3474efd51863SBarry Smith    Input Parameters:
3475efd51863SBarry Smith +  snes - the SNES context
3476efd51863SBarry Smith -  steps - the number of refinements to do, defaults to 0
3477efd51863SBarry Smith 
3478efd51863SBarry Smith    Options Database Keys:
347967b8a455SSatish Balay .    -snes_grid_sequence <steps> - Use grid sequencing to generate initial guess
3480efd51863SBarry Smith 
3481efd51863SBarry Smith    Level: intermediate
3482efd51863SBarry Smith 
3483c0df2a02SJed Brown    Notes:
3484c0df2a02SJed Brown    Use SNESGetSolution() to extract the fine grid solution after grid sequencing.
3485c0df2a02SJed Brown 
3486fa19ca70SBarry Smith .seealso: SNESSetTrustRegionTolerance(), SNESGetLagPreconditioner(), SNESSetLagJacobian(), SNESGetLagJacobian(), SNESGetGridSequence()
3487efd51863SBarry Smith 
3488efd51863SBarry Smith @*/
3489efd51863SBarry Smith PetscErrorCode  SNESSetGridSequence(SNES snes,PetscInt steps)
3490efd51863SBarry Smith {
3491efd51863SBarry Smith   PetscFunctionBegin;
3492efd51863SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3493efd51863SBarry Smith   PetscValidLogicalCollectiveInt(snes,steps,2);
3494efd51863SBarry Smith   snes->gridsequence = steps;
3495efd51863SBarry Smith   PetscFunctionReturn(0);
3496efd51863SBarry Smith }
3497efd51863SBarry Smith 
3498fa19ca70SBarry Smith /*@
3499fa19ca70SBarry Smith    SNESGetGridSequence - gets the number of steps of grid sequencing that SNES does
3500fa19ca70SBarry Smith 
3501fa19ca70SBarry Smith    Logically Collective on SNES
3502fa19ca70SBarry Smith 
3503fa19ca70SBarry Smith    Input Parameter:
3504fa19ca70SBarry Smith .  snes - the SNES context
3505fa19ca70SBarry Smith 
3506fa19ca70SBarry Smith    Output Parameter:
3507fa19ca70SBarry Smith .  steps - the number of refinements to do, defaults to 0
3508fa19ca70SBarry Smith 
3509fa19ca70SBarry Smith    Options Database Keys:
351067b8a455SSatish Balay .    -snes_grid_sequence <steps> - set number of refinements
3511fa19ca70SBarry Smith 
3512fa19ca70SBarry Smith    Level: intermediate
3513fa19ca70SBarry Smith 
3514fa19ca70SBarry Smith    Notes:
3515fa19ca70SBarry Smith    Use SNESGetSolution() to extract the fine grid solution after grid sequencing.
3516fa19ca70SBarry Smith 
3517fa19ca70SBarry Smith .seealso: SNESSetTrustRegionTolerance(), SNESGetLagPreconditioner(), SNESSetLagJacobian(), SNESGetLagJacobian(), SNESSetGridSequence()
3518fa19ca70SBarry Smith 
3519fa19ca70SBarry Smith @*/
3520fa19ca70SBarry Smith PetscErrorCode  SNESGetGridSequence(SNES snes,PetscInt *steps)
3521fa19ca70SBarry Smith {
3522fa19ca70SBarry Smith   PetscFunctionBegin;
3523fa19ca70SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3524fa19ca70SBarry Smith   *steps = snes->gridsequence;
3525fa19ca70SBarry Smith   PetscFunctionReturn(0);
3526fa19ca70SBarry Smith }
3527fa19ca70SBarry Smith 
3528a8054027SBarry Smith /*@
3529a8054027SBarry Smith    SNESGetLagPreconditioner - Indicates how often the preconditioner is rebuilt
3530a8054027SBarry Smith 
35313f9fe445SBarry Smith    Not Collective
3532a8054027SBarry Smith 
3533a8054027SBarry Smith    Input Parameter:
3534a8054027SBarry Smith .  snes - the SNES context
3535a8054027SBarry Smith 
3536a8054027SBarry Smith    Output Parameter:
3537a8054027SBarry Smith .   lag - -1 indicates NEVER rebuild, 1 means rebuild every time the Jacobian is computed within a single nonlinear solve, 2 means every second time
35383b4f5425SBarry Smith          the Jacobian is built etc. -2 indicates rebuild preconditioner at next chance but then never rebuild after that
3539a8054027SBarry Smith 
3540a8054027SBarry Smith    Options Database Keys:
35413d5a8a6aSBarry Smith +    -snes_lag_jacobian_persists <true,false> - sets the persistence
35423d5a8a6aSBarry Smith .    -snes_lag_jacobian <-2,1,2,...> - sets the lag
35433d5a8a6aSBarry Smith .    -snes_lag_preconditioner_persists <true,false> - sets the persistence
35443d5a8a6aSBarry Smith -    -snes_lag_preconditioner <-2,1,2,...> - sets the lag
3545a8054027SBarry Smith 
3546a8054027SBarry Smith    Notes:
3547a8054027SBarry Smith    The default is 1
3548a8054027SBarry Smith    The preconditioner is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1
3549a8054027SBarry Smith 
3550a8054027SBarry Smith    Level: intermediate
3551a8054027SBarry Smith 
35523d5a8a6aSBarry Smith .seealso: SNESSetTrustRegionTolerance(), SNESSetLagPreconditioner(), SNESSetLagJacobianPersists(), SNESSetLagPreconditionerPersists()
3553a8054027SBarry Smith 
3554a8054027SBarry Smith @*/
35557087cfbeSBarry Smith PetscErrorCode  SNESGetLagPreconditioner(SNES snes,PetscInt *lag)
3556a8054027SBarry Smith {
3557a8054027SBarry Smith   PetscFunctionBegin;
35580700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3559a8054027SBarry Smith   *lag = snes->lagpreconditioner;
3560a8054027SBarry Smith   PetscFunctionReturn(0);
3561a8054027SBarry Smith }
3562a8054027SBarry Smith 
3563e35cf81dSBarry Smith /*@
3564e35cf81dSBarry Smith    SNESSetLagJacobian - Determines when the Jacobian is rebuilt in the nonlinear solve. See SNESSetLagPreconditioner() for determining how
3565e35cf81dSBarry Smith      often the preconditioner is rebuilt.
3566e35cf81dSBarry Smith 
35673f9fe445SBarry Smith    Logically Collective on SNES
3568e35cf81dSBarry Smith 
3569e35cf81dSBarry Smith    Input Parameters:
3570e35cf81dSBarry Smith +  snes - the SNES context
3571e35cf81dSBarry Smith -  lag - -1 indicates NEVER rebuild, 1 means rebuild every time the Jacobian is computed within a single nonlinear solve, 2 means every second time
3572fe3ffe1eSBarry Smith          the Jacobian is built etc. -2 means rebuild at next chance but then never again
3573e35cf81dSBarry Smith 
3574e35cf81dSBarry Smith    Options Database Keys:
35753d5a8a6aSBarry Smith +    -snes_lag_jacobian_persists <true,false> - sets the persistence
35763d5a8a6aSBarry Smith .    -snes_lag_jacobian <-2,1,2,...> - sets the lag
35773d5a8a6aSBarry Smith .    -snes_lag_preconditioner_persists <true,false> - sets the persistence
35783d5a8a6aSBarry Smith -    -snes_lag_preconditioner <-2,1,2,...> - sets the lag.
3579e35cf81dSBarry Smith 
3580e35cf81dSBarry Smith    Notes:
3581e35cf81dSBarry Smith    The default is 1
3582e35cf81dSBarry Smith    The Jacobian is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1
3583fe3ffe1eSBarry Smith    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
3584fe3ffe1eSBarry Smith    at the next Newton step but never again (unless it is reset to another value)
3585e35cf81dSBarry Smith 
3586e35cf81dSBarry Smith    Level: intermediate
3587e35cf81dSBarry Smith 
35883d5a8a6aSBarry Smith .seealso: SNESSetTrustRegionTolerance(), SNESGetLagPreconditioner(), SNESSetLagPreconditioner(), SNESGetLagJacobianPersists(), SNESSetLagPreconditionerPersists()
3589e35cf81dSBarry Smith 
3590e35cf81dSBarry Smith @*/
35917087cfbeSBarry Smith PetscErrorCode  SNESSetLagJacobian(SNES snes,PetscInt lag)
3592e35cf81dSBarry Smith {
3593e35cf81dSBarry Smith   PetscFunctionBegin;
35940700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
35955f80ce2aSJacob Faibussowitsch   PetscCheck(lag >= -2,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag must be -2, -1, 1 or greater");
35965f80ce2aSJacob Faibussowitsch   PetscCheck(lag,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag cannot be 0");
3597c5eb9154SBarry Smith   PetscValidLogicalCollectiveInt(snes,lag,2);
3598e35cf81dSBarry Smith   snes->lagjacobian = lag;
3599e35cf81dSBarry Smith   PetscFunctionReturn(0);
3600e35cf81dSBarry Smith }
3601e35cf81dSBarry Smith 
3602e35cf81dSBarry Smith /*@
3603e35cf81dSBarry Smith    SNESGetLagJacobian - Indicates how often the Jacobian is rebuilt. See SNESGetLagPreconditioner() to determine when the preconditioner is rebuilt
3604e35cf81dSBarry Smith 
36053f9fe445SBarry Smith    Not Collective
3606e35cf81dSBarry Smith 
3607e35cf81dSBarry Smith    Input Parameter:
3608e35cf81dSBarry Smith .  snes - the SNES context
3609e35cf81dSBarry Smith 
3610e35cf81dSBarry Smith    Output Parameter:
3611e35cf81dSBarry Smith .   lag - -1 indicates NEVER rebuild, 1 means rebuild every time the Jacobian is computed within a single nonlinear solve, 2 means every second time
3612e35cf81dSBarry Smith          the Jacobian is built etc.
3613e35cf81dSBarry Smith 
3614e35cf81dSBarry Smith    Notes:
3615e35cf81dSBarry Smith    The default is 1
36163d5a8a6aSBarry Smith    The jacobian is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1 or SNESSetLagJacobianPersists() was called.
3617e35cf81dSBarry Smith 
3618e35cf81dSBarry Smith    Level: intermediate
3619e35cf81dSBarry Smith 
36203d5a8a6aSBarry Smith .seealso: SNESSetTrustRegionTolerance(), SNESSetLagJacobian(), SNESSetLagPreconditioner(), SNESGetLagPreconditioner(), SNESSetLagJacobianPersists(), SNESSetLagPreconditionerPersists()
3621e35cf81dSBarry Smith 
3622e35cf81dSBarry Smith @*/
36237087cfbeSBarry Smith PetscErrorCode  SNESGetLagJacobian(SNES snes,PetscInt *lag)
3624e35cf81dSBarry Smith {
3625e35cf81dSBarry Smith   PetscFunctionBegin;
36260700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3627e35cf81dSBarry Smith   *lag = snes->lagjacobian;
3628e35cf81dSBarry Smith   PetscFunctionReturn(0);
3629e35cf81dSBarry Smith }
3630e35cf81dSBarry Smith 
363137ec4e1aSPeter Brune /*@
363237ec4e1aSPeter Brune    SNESSetLagJacobianPersists - Set whether or not the Jacobian lagging persists through multiple solves
363337ec4e1aSPeter Brune 
363437ec4e1aSPeter Brune    Logically collective on SNES
363537ec4e1aSPeter Brune 
3636d8d19677SJose E. Roman    Input Parameters:
363737ec4e1aSPeter Brune +  snes - the SNES context
36389d7e2deaSPeter Brune -   flg - jacobian lagging persists if true
363937ec4e1aSPeter Brune 
364037ec4e1aSPeter Brune    Options Database Keys:
36413d5a8a6aSBarry Smith +    -snes_lag_jacobian_persists <true,false> - sets the persistence
36423d5a8a6aSBarry Smith .    -snes_lag_jacobian <-2,1,2,...> - sets the lag
36433d5a8a6aSBarry Smith .    -snes_lag_preconditioner_persists <true,false> - sets the persistence
36443d5a8a6aSBarry Smith -    -snes_lag_preconditioner <-2,1,2,...> - sets the lag
36453d5a8a6aSBarry Smith 
364695452b02SPatrick Sanan    Notes:
364795452b02SPatrick Sanan     This is useful both for nonlinear preconditioning, where it's appropriate to have the Jacobian be stale by
364837ec4e1aSPeter Brune    several solves, and for implicit time-stepping, where Jacobian lagging in the inner nonlinear solve over several
364937ec4e1aSPeter Brune    timesteps may present huge efficiency gains.
365037ec4e1aSPeter Brune 
365137ec4e1aSPeter Brune    Level: developer
365237ec4e1aSPeter Brune 
36533d5a8a6aSBarry Smith .seealso: SNESSetLagPreconditionerPersists(), SNESSetLagJacobian(), SNESGetLagJacobian(), SNESGetNPC(), SNESSetLagJacobianPersists()
365437ec4e1aSPeter Brune 
365537ec4e1aSPeter Brune @*/
365637ec4e1aSPeter Brune PetscErrorCode  SNESSetLagJacobianPersists(SNES snes,PetscBool flg)
365737ec4e1aSPeter Brune {
365837ec4e1aSPeter Brune   PetscFunctionBegin;
365937ec4e1aSPeter Brune   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
366037ec4e1aSPeter Brune   PetscValidLogicalCollectiveBool(snes,flg,2);
366137ec4e1aSPeter Brune   snes->lagjac_persist = flg;
366237ec4e1aSPeter Brune   PetscFunctionReturn(0);
366337ec4e1aSPeter Brune }
366437ec4e1aSPeter Brune 
366537ec4e1aSPeter Brune /*@
3666d8e291bfSBarry Smith    SNESSetLagPreconditionerPersists - Set whether or not the preconditioner lagging persists through multiple nonlinear solves
366737ec4e1aSPeter Brune 
366837ec4e1aSPeter Brune    Logically Collective on SNES
366937ec4e1aSPeter Brune 
3670d8d19677SJose E. Roman    Input Parameters:
367137ec4e1aSPeter Brune +  snes - the SNES context
36729d7e2deaSPeter Brune -   flg - preconditioner lagging persists if true
367337ec4e1aSPeter Brune 
367437ec4e1aSPeter Brune    Options Database Keys:
36753d5a8a6aSBarry Smith +    -snes_lag_jacobian_persists <true,false> - sets the persistence
36763d5a8a6aSBarry Smith .    -snes_lag_jacobian <-2,1,2,...> - sets the lag
36773d5a8a6aSBarry Smith .    -snes_lag_preconditioner_persists <true,false> - sets the persistence
36783d5a8a6aSBarry Smith -    -snes_lag_preconditioner <-2,1,2,...> - sets the lag
367937ec4e1aSPeter Brune 
368095452b02SPatrick Sanan    Notes:
368195452b02SPatrick Sanan     This is useful both for nonlinear preconditioning, where it's appropriate to have the preconditioner be stale
368237ec4e1aSPeter Brune    by several solves, and for implicit time-stepping, where preconditioner lagging in the inner nonlinear solve over
368337ec4e1aSPeter Brune    several timesteps may present huge efficiency gains.
368437ec4e1aSPeter Brune 
368537ec4e1aSPeter Brune    Level: developer
368637ec4e1aSPeter Brune 
36873d5a8a6aSBarry Smith .seealso: SNESSetLagJacobianPersists(), SNESSetLagJacobian(), SNESGetLagJacobian(), SNESGetNPC(), SNESSetLagPreconditioner()
368837ec4e1aSPeter Brune 
368937ec4e1aSPeter Brune @*/
369037ec4e1aSPeter Brune PetscErrorCode  SNESSetLagPreconditionerPersists(SNES snes,PetscBool flg)
369137ec4e1aSPeter Brune {
369237ec4e1aSPeter Brune   PetscFunctionBegin;
369337ec4e1aSPeter Brune   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
369437ec4e1aSPeter Brune   PetscValidLogicalCollectiveBool(snes,flg,2);
369537ec4e1aSPeter Brune   snes->lagpre_persist = flg;
369637ec4e1aSPeter Brune   PetscFunctionReturn(0);
369737ec4e1aSPeter Brune }
369837ec4e1aSPeter Brune 
36999b94acceSBarry Smith /*@
3700be5caee7SBarry Smith    SNESSetForceIteration - force SNESSolve() to take at least one iteration regardless of the initial residual norm
3701be5caee7SBarry Smith 
3702be5caee7SBarry Smith    Logically Collective on SNES
3703be5caee7SBarry Smith 
3704be5caee7SBarry Smith    Input Parameters:
3705be5caee7SBarry Smith +  snes - the SNES context
3706be5caee7SBarry Smith -  force - PETSC_TRUE require at least one iteration
3707be5caee7SBarry Smith 
3708be5caee7SBarry Smith    Options Database Keys:
3709be5caee7SBarry Smith .    -snes_force_iteration <force> - Sets forcing an iteration
3710be5caee7SBarry Smith 
3711be5caee7SBarry Smith    Notes:
3712be5caee7SBarry Smith    This is used sometimes with TS to prevent TS from detecting a false steady state solution
3713be5caee7SBarry Smith 
3714be5caee7SBarry Smith    Level: intermediate
3715be5caee7SBarry Smith 
3716be5caee7SBarry Smith .seealso: SNESSetTrustRegionTolerance(), SNESSetDivergenceTolerance()
3717be5caee7SBarry Smith @*/
3718be5caee7SBarry Smith PetscErrorCode  SNESSetForceIteration(SNES snes,PetscBool force)
3719be5caee7SBarry Smith {
3720be5caee7SBarry Smith   PetscFunctionBegin;
3721be5caee7SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3722be5caee7SBarry Smith   snes->forceiteration = force;
3723be5caee7SBarry Smith   PetscFunctionReturn(0);
3724be5caee7SBarry Smith }
3725be5caee7SBarry Smith 
372685216dc7SFande Kong /*@
372785216dc7SFande Kong    SNESGetForceIteration - Whether or not to force SNESSolve() take at least one iteration regardless of the initial residual norm
372885216dc7SFande Kong 
372985216dc7SFande Kong    Logically Collective on SNES
373085216dc7SFande Kong 
373185216dc7SFande Kong    Input Parameters:
373285216dc7SFande Kong .  snes - the SNES context
373385216dc7SFande Kong 
373485216dc7SFande Kong    Output Parameter:
373585216dc7SFande Kong .  force - PETSC_TRUE requires at least one iteration.
373685216dc7SFande Kong 
373706dd6b0eSSatish Balay    Level: intermediate
373806dd6b0eSSatish Balay 
373985216dc7SFande Kong .seealso: SNESSetForceIteration(), SNESSetTrustRegionTolerance(), SNESSetDivergenceTolerance()
374085216dc7SFande Kong @*/
374185216dc7SFande Kong PetscErrorCode  SNESGetForceIteration(SNES snes,PetscBool *force)
374285216dc7SFande Kong {
374385216dc7SFande Kong   PetscFunctionBegin;
374485216dc7SFande Kong   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
374585216dc7SFande Kong   *force = snes->forceiteration;
374685216dc7SFande Kong   PetscFunctionReturn(0);
374785216dc7SFande Kong }
3748be5caee7SBarry Smith 
3749be5caee7SBarry Smith /*@
3750d7a720efSLois Curfman McInnes    SNESSetTolerances - Sets various parameters used in convergence tests.
37519b94acceSBarry Smith 
37523f9fe445SBarry Smith    Logically Collective on SNES
3753c7afd0dbSLois Curfman McInnes 
37549b94acceSBarry Smith    Input Parameters:
3755c7afd0dbSLois Curfman McInnes +  snes - the SNES context
375670441072SBarry Smith .  abstol - absolute convergence tolerance
375733174efeSLois Curfman McInnes .  rtol - relative convergence tolerance
37585358d0d4SBarry Smith .  stol -  convergence tolerance in terms of the norm of the change in the solution between steps,  || delta x || < stol*|| x ||
375933174efeSLois Curfman McInnes .  maxit - maximum number of iterations
3760e71169deSBarry Smith -  maxf - maximum number of function evaluations (-1 indicates no limit)
3761fee21e36SBarry Smith 
376233174efeSLois Curfman McInnes    Options Database Keys:
376370441072SBarry Smith +    -snes_atol <abstol> - Sets abstol
3764c7afd0dbSLois Curfman McInnes .    -snes_rtol <rtol> - Sets rtol
3765c7afd0dbSLois Curfman McInnes .    -snes_stol <stol> - Sets stol
3766c7afd0dbSLois Curfman McInnes .    -snes_max_it <maxit> - Sets maxit
3767c7afd0dbSLois Curfman McInnes -    -snes_max_funcs <maxf> - Sets maxf
37689b94acceSBarry Smith 
3769d7a720efSLois Curfman McInnes    Notes:
37709b94acceSBarry Smith    The default maximum number of iterations is 50.
37719b94acceSBarry Smith    The default maximum number of function evaluations is 1000.
37729b94acceSBarry Smith 
377336851e7fSLois Curfman McInnes    Level: intermediate
377436851e7fSLois Curfman McInnes 
3775be5caee7SBarry Smith .seealso: SNESSetTrustRegionTolerance(), SNESSetDivergenceTolerance(), SNESSetForceIteration()
37769b94acceSBarry Smith @*/
37777087cfbeSBarry Smith PetscErrorCode  SNESSetTolerances(SNES snes,PetscReal abstol,PetscReal rtol,PetscReal stol,PetscInt maxit,PetscInt maxf)
37789b94acceSBarry Smith {
37793a40ed3dSBarry Smith   PetscFunctionBegin;
37800700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3781c5eb9154SBarry Smith   PetscValidLogicalCollectiveReal(snes,abstol,2);
3782c5eb9154SBarry Smith   PetscValidLogicalCollectiveReal(snes,rtol,3);
3783c5eb9154SBarry Smith   PetscValidLogicalCollectiveReal(snes,stol,4);
3784c5eb9154SBarry Smith   PetscValidLogicalCollectiveInt(snes,maxit,5);
3785c5eb9154SBarry Smith   PetscValidLogicalCollectiveInt(snes,maxf,6);
3786c5eb9154SBarry Smith 
3787ab54825eSJed Brown   if (abstol != PETSC_DEFAULT) {
37885f80ce2aSJacob Faibussowitsch     PetscCheck(abstol >= 0.0,PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Absolute tolerance %g must be non-negative",(double)abstol);
3789ab54825eSJed Brown     snes->abstol = abstol;
3790ab54825eSJed Brown   }
3791ab54825eSJed Brown   if (rtol != PETSC_DEFAULT) {
37925f80ce2aSJacob Faibussowitsch     PetscCheck(rtol >= 0.0 && 1.0 > rtol,PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Relative tolerance %g must be non-negative and less than 1.0",(double)rtol);
3793ab54825eSJed Brown     snes->rtol = rtol;
3794ab54825eSJed Brown   }
3795ab54825eSJed Brown   if (stol != PETSC_DEFAULT) {
37965f80ce2aSJacob Faibussowitsch     PetscCheck(stol >= 0.0,PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Step tolerance %g must be non-negative",(double)stol);
3797c60f73f4SPeter Brune     snes->stol = stol;
3798ab54825eSJed Brown   }
3799ab54825eSJed Brown   if (maxit != PETSC_DEFAULT) {
38005f80ce2aSJacob Faibussowitsch     PetscCheck(maxit >= 0,PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of iterations %D must be non-negative",maxit);
3801ab54825eSJed Brown     snes->max_its = maxit;
3802ab54825eSJed Brown   }
3803ab54825eSJed Brown   if (maxf != PETSC_DEFAULT) {
38045f80ce2aSJacob Faibussowitsch     PetscCheck(maxf >= -1,PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of function evaluations %D must be -1 or nonnegative",maxf);
3805ab54825eSJed Brown     snes->max_funcs = maxf;
3806ab54825eSJed Brown   }
380788976e71SPeter Brune   snes->tolerancesset = PETSC_TRUE;
38083a40ed3dSBarry Smith   PetscFunctionReturn(0);
38099b94acceSBarry Smith }
38109b94acceSBarry Smith 
3811e4d06f11SPatrick Farrell /*@
3812e4d06f11SPatrick Farrell    SNESSetDivergenceTolerance - Sets the divergence tolerance used for the SNES divergence test.
3813e4d06f11SPatrick Farrell 
3814e4d06f11SPatrick Farrell    Logically Collective on SNES
3815e4d06f11SPatrick Farrell 
3816e4d06f11SPatrick Farrell    Input Parameters:
3817e4d06f11SPatrick Farrell +  snes - the SNES context
3818e4d06f11SPatrick Farrell -  divtol - the divergence tolerance. Use -1 to deactivate the test.
3819e4d06f11SPatrick Farrell 
3820e4d06f11SPatrick Farrell    Options Database Keys:
3821a2b725a8SWilliam Gropp .    -snes_divergence_tolerance <divtol> - Sets divtol
3822e4d06f11SPatrick Farrell 
3823e4d06f11SPatrick Farrell    Notes:
3824e4d06f11SPatrick Farrell    The default divergence tolerance is 1e4.
3825e4d06f11SPatrick Farrell 
3826e4d06f11SPatrick Farrell    Level: intermediate
3827e4d06f11SPatrick Farrell 
3828e4d06f11SPatrick Farrell .seealso: SNESSetTolerances(), SNESGetDivergenceTolerance
3829e4d06f11SPatrick Farrell @*/
3830e4d06f11SPatrick Farrell PetscErrorCode  SNESSetDivergenceTolerance(SNES snes,PetscReal divtol)
3831e4d06f11SPatrick Farrell {
3832e4d06f11SPatrick Farrell   PetscFunctionBegin;
3833e4d06f11SPatrick Farrell   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3834e4d06f11SPatrick Farrell   PetscValidLogicalCollectiveReal(snes,divtol,2);
3835e4d06f11SPatrick Farrell 
3836e4d06f11SPatrick Farrell   if (divtol != PETSC_DEFAULT) {
3837e4d06f11SPatrick Farrell     snes->divtol = divtol;
3838e4d06f11SPatrick Farrell   }
3839e4d06f11SPatrick Farrell   else {
3840e4d06f11SPatrick Farrell     snes->divtol = 1.0e4;
3841e4d06f11SPatrick Farrell   }
3842e4d06f11SPatrick Farrell   PetscFunctionReturn(0);
3843e4d06f11SPatrick Farrell }
3844e4d06f11SPatrick Farrell 
38459b94acceSBarry Smith /*@
384633174efeSLois Curfman McInnes    SNESGetTolerances - Gets various parameters used in convergence tests.
384733174efeSLois Curfman McInnes 
3848c7afd0dbSLois Curfman McInnes    Not Collective
3849c7afd0dbSLois Curfman McInnes 
385033174efeSLois Curfman McInnes    Input Parameters:
3851c7afd0dbSLois Curfman McInnes +  snes - the SNES context
385285385478SLisandro Dalcin .  atol - absolute convergence tolerance
385333174efeSLois Curfman McInnes .  rtol - relative convergence tolerance
385433174efeSLois Curfman McInnes .  stol -  convergence tolerance in terms of the norm
385533174efeSLois Curfman McInnes            of the change in the solution between steps
385633174efeSLois Curfman McInnes .  maxit - maximum number of iterations
3857c7afd0dbSLois Curfman McInnes -  maxf - maximum number of function evaluations
3858fee21e36SBarry Smith 
385933174efeSLois Curfman McInnes    Notes:
38600298fd71SBarry Smith    The user can specify NULL for any parameter that is not needed.
386133174efeSLois Curfman McInnes 
386236851e7fSLois Curfman McInnes    Level: intermediate
386336851e7fSLois Curfman McInnes 
386433174efeSLois Curfman McInnes .seealso: SNESSetTolerances()
386533174efeSLois Curfman McInnes @*/
38667087cfbeSBarry Smith PetscErrorCode  SNESGetTolerances(SNES snes,PetscReal *atol,PetscReal *rtol,PetscReal *stol,PetscInt *maxit,PetscInt *maxf)
386733174efeSLois Curfman McInnes {
38683a40ed3dSBarry Smith   PetscFunctionBegin;
38690700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
387085385478SLisandro Dalcin   if (atol)  *atol  = snes->abstol;
387133174efeSLois Curfman McInnes   if (rtol)  *rtol  = snes->rtol;
3872c60f73f4SPeter Brune   if (stol)  *stol  = snes->stol;
387333174efeSLois Curfman McInnes   if (maxit) *maxit = snes->max_its;
387433174efeSLois Curfman McInnes   if (maxf)  *maxf  = snes->max_funcs;
38753a40ed3dSBarry Smith   PetscFunctionReturn(0);
387633174efeSLois Curfman McInnes }
387733174efeSLois Curfman McInnes 
3878e4d06f11SPatrick Farrell /*@
3879e4d06f11SPatrick Farrell    SNESGetDivergenceTolerance - Gets divergence tolerance used in divergence test.
3880e4d06f11SPatrick Farrell 
3881e4d06f11SPatrick Farrell    Not Collective
3882e4d06f11SPatrick Farrell 
3883e4d06f11SPatrick Farrell    Input Parameters:
3884e4d06f11SPatrick Farrell +  snes - the SNES context
3885e4d06f11SPatrick Farrell -  divtol - divergence tolerance
3886e4d06f11SPatrick Farrell 
3887e4d06f11SPatrick Farrell    Level: intermediate
3888e4d06f11SPatrick Farrell 
3889e4d06f11SPatrick Farrell .seealso: SNESSetDivergenceTolerance()
3890e4d06f11SPatrick Farrell @*/
3891e4d06f11SPatrick Farrell PetscErrorCode  SNESGetDivergenceTolerance(SNES snes,PetscReal *divtol)
3892e4d06f11SPatrick Farrell {
3893e4d06f11SPatrick Farrell   PetscFunctionBegin;
3894e4d06f11SPatrick Farrell   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3895e4d06f11SPatrick Farrell   if (divtol) *divtol = snes->divtol;
3896e4d06f11SPatrick Farrell   PetscFunctionReturn(0);
3897e4d06f11SPatrick Farrell }
3898e4d06f11SPatrick Farrell 
389933174efeSLois Curfman McInnes /*@
39009b94acceSBarry Smith    SNESSetTrustRegionTolerance - Sets the trust region parameter tolerance.
39019b94acceSBarry Smith 
39023f9fe445SBarry Smith    Logically Collective on SNES
3903fee21e36SBarry Smith 
3904c7afd0dbSLois Curfman McInnes    Input Parameters:
3905c7afd0dbSLois Curfman McInnes +  snes - the SNES context
3906c7afd0dbSLois Curfman McInnes -  tol - tolerance
3907c7afd0dbSLois Curfman McInnes 
39089b94acceSBarry Smith    Options Database Key:
3909c7afd0dbSLois Curfman McInnes .  -snes_trtol <tol> - Sets tol
39109b94acceSBarry Smith 
391136851e7fSLois Curfman McInnes    Level: intermediate
391236851e7fSLois Curfman McInnes 
39132492ecdbSBarry Smith .seealso: SNESSetTolerances()
39149b94acceSBarry Smith @*/
39157087cfbeSBarry Smith PetscErrorCode  SNESSetTrustRegionTolerance(SNES snes,PetscReal tol)
39169b94acceSBarry Smith {
39173a40ed3dSBarry Smith   PetscFunctionBegin;
39180700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3919c5eb9154SBarry Smith   PetscValidLogicalCollectiveReal(snes,tol,2);
39209b94acceSBarry Smith   snes->deltatol = tol;
39213a40ed3dSBarry Smith   PetscFunctionReturn(0);
39229b94acceSBarry Smith }
39239b94acceSBarry Smith 
39246ba87a44SLisandro Dalcin PETSC_INTERN PetscErrorCode  SNESMonitorRange_Private(SNES,PetscInt,PetscReal*);
39256ba87a44SLisandro Dalcin 
39267087cfbeSBarry Smith PetscErrorCode  SNESMonitorLGRange(SNES snes,PetscInt n,PetscReal rnorm,void *monctx)
3927b271bb04SBarry Smith {
3928b271bb04SBarry Smith   PetscDrawLG      lg;
3929b271bb04SBarry Smith   PetscReal        x,y,per;
3930b271bb04SBarry Smith   PetscViewer      v = (PetscViewer)monctx;
3931b271bb04SBarry Smith   static PetscReal prev; /* should be in the context */
3932b271bb04SBarry Smith   PetscDraw        draw;
3933b271bb04SBarry Smith 
3934459f5d12SBarry Smith   PetscFunctionBegin;
39354d4332d5SBarry Smith   PetscValidHeaderSpecific(v,PETSC_VIEWER_CLASSID,4);
39365f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscViewerDrawGetDrawLG(v,0,&lg));
39375f80ce2aSJacob Faibussowitsch   if (!n) CHKERRQ(PetscDrawLGReset(lg));
39385f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscDrawLGGetDraw(lg,&draw));
39395f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscDrawSetTitle(draw,"Residual norm"));
3940b271bb04SBarry Smith   x    = (PetscReal)n;
394177b4d14cSPeter Brune   if (rnorm > 0.0) y = PetscLog10Real(rnorm);
394294c9c6d3SKarl Rupp   else y = -15.0;
39435f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscDrawLGAddPoint(lg,&x,&y));
39446934998bSLisandro Dalcin   if (n < 20 || !(n % 5) || snes->reason) {
39455f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscDrawLGDraw(lg));
39465f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscDrawLGSave(lg));
3947b271bb04SBarry Smith   }
3948b271bb04SBarry Smith 
39495f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscViewerDrawGetDrawLG(v,1,&lg));
39505f80ce2aSJacob Faibussowitsch   if (!n) CHKERRQ(PetscDrawLGReset(lg));
39515f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscDrawLGGetDraw(lg,&draw));
39525f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscDrawSetTitle(draw,"% elemts > .2*max elemt"));
39535f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESMonitorRange_Private(snes,n,&per));
3954b271bb04SBarry Smith   x    = (PetscReal)n;
3955b271bb04SBarry Smith   y    = 100.0*per;
39565f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscDrawLGAddPoint(lg,&x,&y));
39576934998bSLisandro Dalcin   if (n < 20 || !(n % 5) || snes->reason) {
39585f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscDrawLGDraw(lg));
39595f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscDrawLGSave(lg));
3960b271bb04SBarry Smith   }
3961b271bb04SBarry Smith 
39625f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscViewerDrawGetDrawLG(v,2,&lg));
39635f80ce2aSJacob Faibussowitsch   if (!n) {prev = rnorm;CHKERRQ(PetscDrawLGReset(lg));}
39645f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscDrawLGGetDraw(lg,&draw));
39655f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscDrawSetTitle(draw,"(norm -oldnorm)/oldnorm"));
3966b271bb04SBarry Smith   x    = (PetscReal)n;
3967b271bb04SBarry Smith   y    = (prev - rnorm)/prev;
39685f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscDrawLGAddPoint(lg,&x,&y));
39696934998bSLisandro Dalcin   if (n < 20 || !(n % 5) || snes->reason) {
39705f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscDrawLGDraw(lg));
39715f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscDrawLGSave(lg));
3972b271bb04SBarry Smith   }
3973b271bb04SBarry Smith 
39745f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscViewerDrawGetDrawLG(v,3,&lg));
39755f80ce2aSJacob Faibussowitsch   if (!n) CHKERRQ(PetscDrawLGReset(lg));
39765f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscDrawLGGetDraw(lg,&draw));
39775f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscDrawSetTitle(draw,"(norm -oldnorm)/oldnorm*(% > .2 max)"));
3978b271bb04SBarry Smith   x    = (PetscReal)n;
3979b271bb04SBarry Smith   y    = (prev - rnorm)/(prev*per);
3980b271bb04SBarry Smith   if (n > 2) { /*skip initial crazy value */
39815f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscDrawLGAddPoint(lg,&x,&y));
3982b271bb04SBarry Smith   }
39836934998bSLisandro Dalcin   if (n < 20 || !(n % 5) || snes->reason) {
39845f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscDrawLGDraw(lg));
39855f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscDrawLGSave(lg));
3986b271bb04SBarry Smith   }
3987b271bb04SBarry Smith   prev = rnorm;
3988b271bb04SBarry Smith   PetscFunctionReturn(0);
3989b271bb04SBarry Smith }
3990b271bb04SBarry Smith 
3991228d79bcSJed Brown /*@
3992228d79bcSJed Brown    SNESMonitor - runs the user provided monitor routines, if they exist
3993228d79bcSJed Brown 
3994228d79bcSJed Brown    Collective on SNES
3995228d79bcSJed Brown 
3996228d79bcSJed Brown    Input Parameters:
3997228d79bcSJed Brown +  snes - nonlinear solver context obtained from SNESCreate()
3998228d79bcSJed Brown .  iter - iteration number
3999228d79bcSJed Brown -  rnorm - relative norm of the residual
4000228d79bcSJed Brown 
4001228d79bcSJed Brown    Notes:
4002228d79bcSJed Brown    This routine is called by the SNES implementations.
4003228d79bcSJed Brown    It does not typically need to be called by the user.
4004228d79bcSJed Brown 
4005228d79bcSJed Brown    Level: developer
4006228d79bcSJed Brown 
4007228d79bcSJed Brown .seealso: SNESMonitorSet()
4008228d79bcSJed Brown @*/
40097a03ce2fSLisandro Dalcin PetscErrorCode  SNESMonitor(SNES snes,PetscInt iter,PetscReal rnorm)
40107a03ce2fSLisandro Dalcin {
40117a03ce2fSLisandro Dalcin   PetscInt       i,n = snes->numbermonitors;
40127a03ce2fSLisandro Dalcin 
40137a03ce2fSLisandro Dalcin   PetscFunctionBegin;
40145f80ce2aSJacob Faibussowitsch   CHKERRQ(VecLockReadPush(snes->vec_sol));
40157a03ce2fSLisandro Dalcin   for (i=0; i<n; i++) {
40165f80ce2aSJacob Faibussowitsch     CHKERRQ((*snes->monitor[i])(snes,iter,rnorm,snes->monitorcontext[i]));
40177a03ce2fSLisandro Dalcin   }
40185f80ce2aSJacob Faibussowitsch   CHKERRQ(VecLockReadPop(snes->vec_sol));
40197a03ce2fSLisandro Dalcin   PetscFunctionReturn(0);
40207a03ce2fSLisandro Dalcin }
40217a03ce2fSLisandro Dalcin 
40229b94acceSBarry Smith /* ------------ Routines to set performance monitoring options ----------- */
40239b94acceSBarry Smith 
4024bf388a1fSBarry Smith /*MC
4025bf388a1fSBarry Smith     SNESMonitorFunction - functional form passed to SNESMonitorSet() to monitor convergence of nonlinear solver
4026bf388a1fSBarry Smith 
4027bf388a1fSBarry Smith      Synopsis:
4028aaa7dc30SBarry Smith      #include <petscsnes.h>
4029bf388a1fSBarry Smith $    PetscErrorCode SNESMonitorFunction(SNES snes,PetscInt its, PetscReal norm,void *mctx)
4030bf388a1fSBarry Smith 
40311843f636SBarry Smith      Collective on snes
40321843f636SBarry Smith 
40331843f636SBarry Smith     Input Parameters:
4034bf388a1fSBarry Smith +    snes - the SNES context
4035bf388a1fSBarry Smith .    its - iteration number
4036bf388a1fSBarry Smith .    norm - 2-norm function value (may be estimated)
4037bf388a1fSBarry Smith -    mctx - [optional] monitoring context
4038bf388a1fSBarry Smith 
4039878cb397SSatish Balay    Level: advanced
4040878cb397SSatish Balay 
4041bf388a1fSBarry Smith .seealso:   SNESMonitorSet(), SNESMonitorGet()
4042bf388a1fSBarry Smith M*/
4043bf388a1fSBarry Smith 
40449b94acceSBarry Smith /*@C
4045a6570f20SBarry Smith    SNESMonitorSet - Sets an ADDITIONAL function that is to be used at every
40469b94acceSBarry Smith    iteration of the nonlinear solver to display the iteration's
40479b94acceSBarry Smith    progress.
40489b94acceSBarry Smith 
40493f9fe445SBarry Smith    Logically Collective on SNES
4050fee21e36SBarry Smith 
4051c7afd0dbSLois Curfman McInnes    Input Parameters:
4052c7afd0dbSLois Curfman McInnes +  snes - the SNES context
40536e4dcb14SBarry Smith .  f - the monitor function, see SNESMonitorFunction for the calling sequence
4054b8a78c4aSBarry Smith .  mctx - [optional] user-defined context for private data for the
40550298fd71SBarry Smith           monitor routine (use NULL if no context is desired)
4056b3006f0bSLois Curfman McInnes -  monitordestroy - [optional] routine that frees monitor context
40570298fd71SBarry Smith           (may be NULL)
40589b94acceSBarry Smith 
40599665c990SLois Curfman McInnes    Options Database Keys:
4060a6570f20SBarry Smith +    -snes_monitor        - sets SNESMonitorDefault()
4061798534f6SMatthew G. Knepley .    -snes_monitor draw::draw_lg - sets line graph monitor,
4062cca6129bSJed Brown -    -snes_monitor_cancel - cancels all monitors that have
4063c7afd0dbSLois Curfman McInnes                             been hardwired into a code by
4064a6570f20SBarry Smith                             calls to SNESMonitorSet(), but
4065c7afd0dbSLois Curfman McInnes                             does not cancel those set via
4066c7afd0dbSLois Curfman McInnes                             the options database.
40679665c990SLois Curfman McInnes 
4068639f9d9dSBarry Smith    Notes:
40696bc08f3fSLois Curfman McInnes    Several different monitoring routines may be set by calling
4070a6570f20SBarry Smith    SNESMonitorSet() multiple times; all will be called in the
40716bc08f3fSLois Curfman McInnes    order in which they were set.
4072639f9d9dSBarry Smith 
407395452b02SPatrick Sanan    Fortran Notes:
407495452b02SPatrick Sanan     Only a single monitor function can be set for each SNES object
4075025f1a04SBarry Smith 
407636851e7fSLois Curfman McInnes    Level: intermediate
407736851e7fSLois Curfman McInnes 
4078bf388a1fSBarry Smith .seealso: SNESMonitorDefault(), SNESMonitorCancel(), SNESMonitorFunction
40799b94acceSBarry Smith @*/
40806e4dcb14SBarry Smith PetscErrorCode  SNESMonitorSet(SNES snes,PetscErrorCode (*f)(SNES,PetscInt,PetscReal,void*),void *mctx,PetscErrorCode (*monitordestroy)(void**))
40819b94acceSBarry Smith {
4082b90d0a6eSBarry Smith   PetscInt       i;
408378064530SBarry Smith   PetscBool      identical;
4084b90d0a6eSBarry Smith 
40853a40ed3dSBarry Smith   PetscFunctionBegin;
40860700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
4087b90d0a6eSBarry Smith   for (i=0; i<snes->numbermonitors;i++) {
40885f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscMonitorCompare((PetscErrorCode (*)(void))f,mctx,monitordestroy,(PetscErrorCode (*)(void))snes->monitor[i],snes->monitorcontext[i],snes->monitordestroy[i],&identical));
408978064530SBarry Smith     if (identical) PetscFunctionReturn(0);
4090649052a6SBarry Smith   }
40915f80ce2aSJacob Faibussowitsch   PetscCheck(snes->numbermonitors < MAXSNESMONITORS,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Too many monitors set");
40926e4dcb14SBarry Smith   snes->monitor[snes->numbermonitors]          = f;
4093b8a78c4aSBarry Smith   snes->monitordestroy[snes->numbermonitors]   = monitordestroy;
4094639f9d9dSBarry Smith   snes->monitorcontext[snes->numbermonitors++] = (void*)mctx;
40953a40ed3dSBarry Smith   PetscFunctionReturn(0);
40969b94acceSBarry Smith }
40979b94acceSBarry Smith 
4098a278d85bSSatish Balay /*@
4099a6570f20SBarry Smith    SNESMonitorCancel - Clears all the monitor functions for a SNES object.
41005cd90555SBarry Smith 
41013f9fe445SBarry Smith    Logically Collective on SNES
4102c7afd0dbSLois Curfman McInnes 
41035cd90555SBarry Smith    Input Parameters:
41045cd90555SBarry Smith .  snes - the SNES context
41055cd90555SBarry Smith 
41061a480d89SAdministrator    Options Database Key:
4107a6570f20SBarry Smith .  -snes_monitor_cancel - cancels all monitors that have been hardwired
4108a6570f20SBarry Smith     into a code by calls to SNESMonitorSet(), but does not cancel those
4109c7afd0dbSLois Curfman McInnes     set via the options database
41105cd90555SBarry Smith 
41115cd90555SBarry Smith    Notes:
41125cd90555SBarry Smith    There is no way to clear one specific monitor from a SNES object.
41135cd90555SBarry Smith 
411436851e7fSLois Curfman McInnes    Level: intermediate
411536851e7fSLois Curfman McInnes 
4116a6570f20SBarry Smith .seealso: SNESMonitorDefault(), SNESMonitorSet()
41175cd90555SBarry Smith @*/
41187087cfbeSBarry Smith PetscErrorCode  SNESMonitorCancel(SNES snes)
41195cd90555SBarry Smith {
4120d952e501SBarry Smith   PetscInt       i;
4121d952e501SBarry Smith 
41225cd90555SBarry Smith   PetscFunctionBegin;
41230700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
4124d952e501SBarry Smith   for (i=0; i<snes->numbermonitors; i++) {
4125d952e501SBarry Smith     if (snes->monitordestroy[i]) {
41265f80ce2aSJacob Faibussowitsch       CHKERRQ((*snes->monitordestroy[i])(&snes->monitorcontext[i]));
4127d952e501SBarry Smith     }
4128d952e501SBarry Smith   }
41295cd90555SBarry Smith   snes->numbermonitors = 0;
41305cd90555SBarry Smith   PetscFunctionReturn(0);
41315cd90555SBarry Smith }
41325cd90555SBarry Smith 
4133bf388a1fSBarry Smith /*MC
4134bf388a1fSBarry Smith     SNESConvergenceTestFunction - functional form used for testing of convergence of nonlinear solver
4135bf388a1fSBarry Smith 
4136bf388a1fSBarry Smith      Synopsis:
4137aaa7dc30SBarry Smith      #include <petscsnes.h>
4138bf388a1fSBarry Smith $     PetscErrorCode SNESConvergenceTest(SNES snes,PetscInt it,PetscReal xnorm,PetscReal gnorm,PetscReal f,SNESConvergedReason *reason,void *cctx)
4139bf388a1fSBarry Smith 
41401843f636SBarry Smith      Collective on snes
41411843f636SBarry Smith 
41421843f636SBarry Smith     Input Parameters:
4143bf388a1fSBarry Smith +    snes - the SNES context
4144bf388a1fSBarry Smith .    it - current iteration (0 is the first and is before any Newton step)
4145bf388a1fSBarry Smith .    xnorm - 2-norm of current iterate
4146bf388a1fSBarry Smith .    gnorm - 2-norm of current step
41471843f636SBarry Smith .    f - 2-norm of function
41481843f636SBarry Smith -    cctx - [optional] convergence context
41491843f636SBarry Smith 
41501843f636SBarry Smith     Output Parameter:
41511843f636SBarry Smith .    reason - reason for convergence/divergence, only needs to be set when convergence or divergence is detected
4152bf388a1fSBarry Smith 
4153878cb397SSatish Balay    Level: intermediate
4154bf388a1fSBarry Smith 
4155bf388a1fSBarry Smith .seealso:   SNESSetConvergenceTest(), SNESGetConvergenceTest()
4156bf388a1fSBarry Smith M*/
4157bf388a1fSBarry Smith 
41589b94acceSBarry Smith /*@C
41599b94acceSBarry Smith    SNESSetConvergenceTest - Sets the function that is to be used
41609b94acceSBarry Smith    to test for convergence of the nonlinear iterative solution.
41619b94acceSBarry Smith 
41623f9fe445SBarry Smith    Logically Collective on SNES
4163fee21e36SBarry Smith 
4164c7afd0dbSLois Curfman McInnes    Input Parameters:
4165c7afd0dbSLois Curfman McInnes +  snes - the SNES context
4166bf388a1fSBarry Smith .  SNESConvergenceTestFunction - routine to test for convergence
41670298fd71SBarry Smith .  cctx - [optional] context for private data for the convergence routine  (may be NULL)
4168cf90aa19SBarry Smith -  destroy - [optional] destructor for the context (may be NULL; PETSC_NULL_FUNCTION in Fortran)
41699b94acceSBarry Smith 
417036851e7fSLois Curfman McInnes    Level: advanced
417136851e7fSLois Curfman McInnes 
4172e2a6519dSDmitry Karpeev .seealso: SNESConvergedDefault(), SNESConvergedSkip(), SNESConvergenceTestFunction
41739b94acceSBarry Smith @*/
4174bf388a1fSBarry Smith PetscErrorCode  SNESSetConvergenceTest(SNES snes,PetscErrorCode (*SNESConvergenceTestFunction)(SNES,PetscInt,PetscReal,PetscReal,PetscReal,SNESConvergedReason*,void*),void *cctx,PetscErrorCode (*destroy)(void*))
41759b94acceSBarry Smith {
41763a40ed3dSBarry Smith   PetscFunctionBegin;
41770700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
4178e2a6519dSDmitry Karpeev   if (!SNESConvergenceTestFunction) SNESConvergenceTestFunction = SNESConvergedSkip;
41797f7931b9SBarry Smith   if (snes->ops->convergeddestroy) {
41805f80ce2aSJacob Faibussowitsch     CHKERRQ((*snes->ops->convergeddestroy)(snes->cnvP));
41817f7931b9SBarry Smith   }
4182bf388a1fSBarry Smith   snes->ops->converged        = SNESConvergenceTestFunction;
41837f7931b9SBarry Smith   snes->ops->convergeddestroy = destroy;
418485385478SLisandro Dalcin   snes->cnvP                  = cctx;
41853a40ed3dSBarry Smith   PetscFunctionReturn(0);
41869b94acceSBarry Smith }
41879b94acceSBarry Smith 
418852baeb72SSatish Balay /*@
4189184914b5SBarry Smith    SNESGetConvergedReason - Gets the reason the SNES iteration was stopped.
4190184914b5SBarry Smith 
4191184914b5SBarry Smith    Not Collective
4192184914b5SBarry Smith 
4193184914b5SBarry Smith    Input Parameter:
4194184914b5SBarry Smith .  snes - the SNES context
4195184914b5SBarry Smith 
4196184914b5SBarry Smith    Output Parameter:
41974d0a8057SBarry Smith .  reason - negative value indicates diverged, positive value converged, see SNESConvergedReason or the
4198184914b5SBarry Smith             manual pages for the individual convergence tests for complete lists
4199184914b5SBarry Smith 
42006a4d7782SBarry Smith    Options Database:
42016a4d7782SBarry Smith .   -snes_converged_reason - prints the reason to standard out
42026a4d7782SBarry Smith 
4203184914b5SBarry Smith    Level: intermediate
4204184914b5SBarry Smith 
420595452b02SPatrick Sanan    Notes:
420695452b02SPatrick Sanan     Should only be called after the call the SNESSolve() is complete, if it is called earlier it returns the value SNES__CONVERGED_ITERATING.
4207184914b5SBarry Smith 
420833866048SMatthew G. Knepley .seealso: SNESSetConvergenceTest(), SNESSetConvergedReason(), SNESConvergedReason
4209184914b5SBarry Smith @*/
42107087cfbeSBarry Smith PetscErrorCode SNESGetConvergedReason(SNES snes,SNESConvergedReason *reason)
4211184914b5SBarry Smith {
4212184914b5SBarry Smith   PetscFunctionBegin;
42130700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
42144482741eSBarry Smith   PetscValidPointer(reason,2);
4215184914b5SBarry Smith   *reason = snes->reason;
4216184914b5SBarry Smith   PetscFunctionReturn(0);
4217184914b5SBarry Smith }
4218184914b5SBarry Smith 
4219c4421ceaSFande Kong /*@C
4220c4421ceaSFande Kong    SNESGetConvergedReasonString - Return a human readable string for snes converged reason
4221c4421ceaSFande Kong 
4222c4421ceaSFande Kong    Not Collective
4223c4421ceaSFande Kong 
4224c4421ceaSFande Kong    Input Parameter:
4225c4421ceaSFande Kong .  snes - the SNES context
4226c4421ceaSFande Kong 
4227c4421ceaSFande Kong    Output Parameter:
4228c4421ceaSFande Kong .  strreason - a human readable string that describes SNES converged reason
4229c4421ceaSFande Kong 
423099c90e12SSatish Balay    Level: beginner
4231c4421ceaSFande Kong 
4232c4421ceaSFande Kong .seealso: SNESGetConvergedReason()
4233c4421ceaSFande Kong @*/
4234c4421ceaSFande Kong PetscErrorCode SNESGetConvergedReasonString(SNES snes, const char** strreason)
4235c4421ceaSFande Kong {
4236c4421ceaSFande Kong   PetscFunctionBegin;
4237c4421ceaSFande Kong   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
4238*dadcf809SJacob Faibussowitsch   PetscValidPointer(strreason,2);
4239c4421ceaSFande Kong   *strreason = SNESConvergedReasons[snes->reason];
4240c4421ceaSFande Kong   PetscFunctionReturn(0);
4241c4421ceaSFande Kong }
4242c4421ceaSFande Kong 
424333866048SMatthew G. Knepley /*@
424433866048SMatthew G. Knepley    SNESSetConvergedReason - Sets the reason the SNES iteration was stopped.
424533866048SMatthew G. Knepley 
424633866048SMatthew G. Knepley    Not Collective
424733866048SMatthew G. Knepley 
424833866048SMatthew G. Knepley    Input Parameters:
424933866048SMatthew G. Knepley +  snes - the SNES context
425033866048SMatthew G. Knepley -  reason - negative value indicates diverged, positive value converged, see SNESConvergedReason or the
425133866048SMatthew G. Knepley             manual pages for the individual convergence tests for complete lists
425233866048SMatthew G. Knepley 
425333866048SMatthew G. Knepley    Level: intermediate
425433866048SMatthew G. Knepley 
425533866048SMatthew G. Knepley .seealso: SNESGetConvergedReason(), SNESSetConvergenceTest(), SNESConvergedReason
425633866048SMatthew G. Knepley @*/
425733866048SMatthew G. Knepley PetscErrorCode SNESSetConvergedReason(SNES snes,SNESConvergedReason reason)
425833866048SMatthew G. Knepley {
425933866048SMatthew G. Knepley   PetscFunctionBegin;
426033866048SMatthew G. Knepley   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
426133866048SMatthew G. Knepley   snes->reason = reason;
426233866048SMatthew G. Knepley   PetscFunctionReturn(0);
426333866048SMatthew G. Knepley }
426433866048SMatthew G. Knepley 
4265c9005455SLois Curfman McInnes /*@
4266c9005455SLois Curfman McInnes    SNESSetConvergenceHistory - Sets the array used to hold the convergence history.
4267c9005455SLois Curfman McInnes 
42683f9fe445SBarry Smith    Logically Collective on SNES
4269fee21e36SBarry Smith 
4270c7afd0dbSLois Curfman McInnes    Input Parameters:
4271c7afd0dbSLois Curfman McInnes +  snes - iterative context obtained from SNESCreate()
42728c7482ecSBarry Smith .  a   - array to hold history, this array will contain the function norms computed at each step
4273cd5578b5SBarry Smith .  its - integer array holds the number of linear iterations for each solve.
4274758f92a0SBarry Smith .  na  - size of a and its
427564731454SLois Curfman McInnes -  reset - PETSC_TRUE indicates each new nonlinear solve resets the history counter to zero,
4276758f92a0SBarry Smith            else it continues storing new values for new nonlinear solves after the old ones
4277c7afd0dbSLois Curfman McInnes 
4278308dcc3eSBarry Smith    Notes:
42790298fd71SBarry Smith    If 'a' and 'its' are NULL then space is allocated for the history. If 'na' PETSC_DECIDE or PETSC_DEFAULT then a
4280308dcc3eSBarry Smith    default array of length 10000 is allocated.
4281308dcc3eSBarry Smith 
4282c9005455SLois Curfman McInnes    This routine is useful, e.g., when running a code for purposes
4283c9005455SLois Curfman McInnes    of accurate performance monitoring, when no I/O should be done
4284c9005455SLois Curfman McInnes    during the section of code that is being timed.
4285c9005455SLois Curfman McInnes 
428636851e7fSLois Curfman McInnes    Level: intermediate
428736851e7fSLois Curfman McInnes 
428808405cd6SLois Curfman McInnes .seealso: SNESGetConvergenceHistory()
4289758f92a0SBarry Smith 
4290c9005455SLois Curfman McInnes @*/
42917087cfbeSBarry Smith PetscErrorCode  SNESSetConvergenceHistory(SNES snes,PetscReal a[],PetscInt its[],PetscInt na,PetscBool reset)
4292c9005455SLois Curfman McInnes {
42933a40ed3dSBarry Smith   PetscFunctionBegin;
42940700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
4295064a246eSJacob Faibussowitsch   if (a) PetscValidRealPointer(a,2);
4296a562a398SLisandro Dalcin   if (its) PetscValidIntPointer(its,3);
42977a1ec6d4SBarry Smith   if (!a) {
4298308dcc3eSBarry Smith     if (na == PETSC_DECIDE || na == PETSC_DEFAULT) na = 1000;
42995f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscCalloc2(na,&a,na,&its));
4300071fcb05SBarry Smith     snes->conv_hist_alloc = PETSC_TRUE;
4301308dcc3eSBarry Smith   }
4302c9005455SLois Curfman McInnes   snes->conv_hist       = a;
4303758f92a0SBarry Smith   snes->conv_hist_its   = its;
4304115dd874SBarry Smith   snes->conv_hist_max   = (size_t)na;
4305a12bc48fSLisandro Dalcin   snes->conv_hist_len   = 0;
4306758f92a0SBarry Smith   snes->conv_hist_reset = reset;
4307758f92a0SBarry Smith   PetscFunctionReturn(0);
4308758f92a0SBarry Smith }
4309758f92a0SBarry Smith 
4310308dcc3eSBarry Smith #if defined(PETSC_HAVE_MATLAB_ENGINE)
4311c6db04a5SJed Brown #include <engine.h>   /* MATLAB include file */
4312c6db04a5SJed Brown #include <mex.h>      /* MATLAB include file */
431399e0435eSBarry Smith 
43148cc058d9SJed Brown PETSC_EXTERN mxArray *SNESGetConvergenceHistoryMatlab(SNES snes)
4315308dcc3eSBarry Smith {
4316308dcc3eSBarry Smith   mxArray   *mat;
4317308dcc3eSBarry Smith   PetscInt  i;
4318308dcc3eSBarry Smith   PetscReal *ar;
4319308dcc3eSBarry Smith 
4320308dcc3eSBarry Smith   PetscFunctionBegin;
4321308dcc3eSBarry Smith   mat = mxCreateDoubleMatrix(snes->conv_hist_len,1,mxREAL);
4322308dcc3eSBarry Smith   ar  = (PetscReal*) mxGetData(mat);
4323f5af7f23SKarl Rupp   for (i=0; i<snes->conv_hist_len; i++) ar[i] = snes->conv_hist[i];
4324308dcc3eSBarry Smith   PetscFunctionReturn(mat);
4325308dcc3eSBarry Smith }
4326308dcc3eSBarry Smith #endif
4327308dcc3eSBarry Smith 
43280c4c9dddSBarry Smith /*@C
4329758f92a0SBarry Smith    SNESGetConvergenceHistory - Gets the array used to hold the convergence history.
4330758f92a0SBarry Smith 
43313f9fe445SBarry Smith    Not Collective
4332758f92a0SBarry Smith 
4333758f92a0SBarry Smith    Input Parameter:
4334758f92a0SBarry Smith .  snes - iterative context obtained from SNESCreate()
4335758f92a0SBarry Smith 
4336758f92a0SBarry Smith    Output Parameters:
4337a2b725a8SWilliam Gropp +  a   - array to hold history
4338758f92a0SBarry Smith .  its - integer array holds the number of linear iterations (or
4339758f92a0SBarry Smith          negative if not converged) for each solve.
4340758f92a0SBarry Smith -  na  - size of a and its
4341758f92a0SBarry Smith 
4342758f92a0SBarry Smith    Notes:
4343758f92a0SBarry Smith     The calling sequence for this routine in Fortran is
4344758f92a0SBarry Smith $   call SNESGetConvergenceHistory(SNES snes, integer na, integer ierr)
4345758f92a0SBarry Smith 
4346758f92a0SBarry Smith    This routine is useful, e.g., when running a code for purposes
4347758f92a0SBarry Smith    of accurate performance monitoring, when no I/O should be done
4348758f92a0SBarry Smith    during the section of code that is being timed.
4349758f92a0SBarry Smith 
4350758f92a0SBarry Smith    Level: intermediate
4351758f92a0SBarry Smith 
43525ea7661aSPierre Jolivet .seealso: SNESSetConvergenceHistory()
4353758f92a0SBarry Smith 
4354758f92a0SBarry Smith @*/
43557087cfbeSBarry Smith PetscErrorCode  SNESGetConvergenceHistory(SNES snes,PetscReal *a[],PetscInt *its[],PetscInt *na)
4356758f92a0SBarry Smith {
4357758f92a0SBarry Smith   PetscFunctionBegin;
43580700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
4359758f92a0SBarry Smith   if (a)   *a   = snes->conv_hist;
4360758f92a0SBarry Smith   if (its) *its = snes->conv_hist_its;
4361115dd874SBarry Smith   if (na)  *na  = (PetscInt) snes->conv_hist_len;
43623a40ed3dSBarry Smith   PetscFunctionReturn(0);
4363c9005455SLois Curfman McInnes }
4364c9005455SLois Curfman McInnes 
4365ac226902SBarry Smith /*@C
436676b2cf59SMatthew Knepley   SNESSetUpdate - Sets the general-purpose update function called
4367eec8f646SJed Brown   at the beginning of every iteration of the nonlinear solve. Specifically
43687e4bb74cSBarry Smith   it is called just before the Jacobian is "evaluated".
436976b2cf59SMatthew Knepley 
43703f9fe445SBarry Smith   Logically Collective on SNES
437176b2cf59SMatthew Knepley 
437276b2cf59SMatthew Knepley   Input Parameters:
4373a2b725a8SWilliam Gropp + snes - The nonlinear solver context
4374a2b725a8SWilliam Gropp - func - The function
437576b2cf59SMatthew Knepley 
437676b2cf59SMatthew Knepley   Calling sequence of func:
4377a2b725a8SWilliam Gropp $ func (SNES snes, PetscInt step);
437876b2cf59SMatthew Knepley 
437976b2cf59SMatthew Knepley . step - The current step of the iteration
438076b2cf59SMatthew Knepley 
4381fe97e370SBarry Smith   Level: advanced
4382fe97e370SBarry Smith 
43836b7fb656SBarry Smith   Note:
43846b7fb656SBarry Smith      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()
4385fe97e370SBarry Smith      This is not used by most users.
438676b2cf59SMatthew Knepley 
43876b7fb656SBarry Smith      There are a varity of function hooks one many set that are called at different stages of the nonlinear solution process, see the functions listed below.
43886b7fb656SBarry Smith 
43896b7fb656SBarry Smith .seealso SNESSetJacobian(), SNESSolve(), SNESLineSearchSetPreCheck(), SNESLineSearchSetPostCheck(), SNESNewtonTRSetPreCheck(), SNESNewtonTRSetPostCheck(),
43906b7fb656SBarry Smith          SNESMonitorSet(), SNESSetDivergenceTest()
439176b2cf59SMatthew Knepley @*/
43927087cfbeSBarry Smith PetscErrorCode  SNESSetUpdate(SNES snes, PetscErrorCode (*func)(SNES, PetscInt))
439376b2cf59SMatthew Knepley {
439476b2cf59SMatthew Knepley   PetscFunctionBegin;
43950700a824SBarry Smith   PetscValidHeaderSpecific(snes, SNES_CLASSID,1);
4396e7788613SBarry Smith   snes->ops->update = func;
439776b2cf59SMatthew Knepley   PetscFunctionReturn(0);
439876b2cf59SMatthew Knepley }
439976b2cf59SMatthew Knepley 
44009b94acceSBarry Smith /*
44019b94acceSBarry Smith    SNESScaleStep_Private - Scales a step so that its length is less than the
44029b94acceSBarry Smith    positive parameter delta.
44039b94acceSBarry Smith 
44049b94acceSBarry Smith     Input Parameters:
4405c7afd0dbSLois Curfman McInnes +   snes - the SNES context
44069b94acceSBarry Smith .   y - approximate solution of linear system
44079b94acceSBarry Smith .   fnorm - 2-norm of current function
4408c7afd0dbSLois Curfman McInnes -   delta - trust region size
44099b94acceSBarry Smith 
44109b94acceSBarry Smith     Output Parameters:
4411c7afd0dbSLois Curfman McInnes +   gpnorm - predicted function norm at the new point, assuming local
44129b94acceSBarry Smith     linearization.  The value is zero if the step lies within the trust
44139b94acceSBarry Smith     region, and exceeds zero otherwise.
4414c7afd0dbSLois Curfman McInnes -   ynorm - 2-norm of the step
44159b94acceSBarry Smith 
44169b94acceSBarry Smith     Note:
441704d7464bSBarry Smith     For non-trust region methods such as SNESNEWTONLS, the parameter delta
44189b94acceSBarry Smith     is set to be the maximum allowable step size.
44199b94acceSBarry Smith 
44209b94acceSBarry Smith */
4421dfbe8321SBarry Smith PetscErrorCode SNESScaleStep_Private(SNES snes,Vec y,PetscReal *fnorm,PetscReal *delta,PetscReal *gpnorm,PetscReal *ynorm)
44229b94acceSBarry Smith {
4423064f8208SBarry Smith   PetscReal      nrm;
4424ea709b57SSatish Balay   PetscScalar    cnorm;
44253a40ed3dSBarry Smith 
44263a40ed3dSBarry Smith   PetscFunctionBegin;
44270700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
44280700a824SBarry Smith   PetscValidHeaderSpecific(y,VEC_CLASSID,2);
4429c9780b6fSBarry Smith   PetscCheckSameComm(snes,1,y,2);
4430184914b5SBarry Smith 
44315f80ce2aSJacob Faibussowitsch   CHKERRQ(VecNorm(y,NORM_2,&nrm));
4432064f8208SBarry Smith   if (nrm > *delta) {
4433064f8208SBarry Smith     nrm     = *delta/nrm;
4434064f8208SBarry Smith     *gpnorm = (1.0 - nrm)*(*fnorm);
4435064f8208SBarry Smith     cnorm   = nrm;
44365f80ce2aSJacob Faibussowitsch     CHKERRQ(VecScale(y,cnorm));
44379b94acceSBarry Smith     *ynorm  = *delta;
44389b94acceSBarry Smith   } else {
44399b94acceSBarry Smith     *gpnorm = 0.0;
4440064f8208SBarry Smith     *ynorm  = nrm;
44419b94acceSBarry Smith   }
44423a40ed3dSBarry Smith   PetscFunctionReturn(0);
44439b94acceSBarry Smith }
44449b94acceSBarry Smith 
444591f3e32bSBarry Smith /*@C
444619a666eeSBarry Smith    SNESConvergedReasonView - Displays the reason a SNES solve converged or diverged to a viewer
44472a359c20SBarry Smith 
44482a359c20SBarry Smith    Collective on SNES
44492a359c20SBarry Smith 
44502a359c20SBarry Smith    Parameter:
44512a359c20SBarry Smith +  snes - iterative context obtained from SNESCreate()
44522a359c20SBarry Smith -  viewer - the viewer to display the reason
44532a359c20SBarry Smith 
44542a359c20SBarry Smith    Options Database Keys:
4455ee300463SSatish Balay +  -snes_converged_reason - print reason for converged or diverged, also prints number of iterations
4456ee300463SSatish Balay -  -snes_converged_reason ::failed - only print reason and number of iterations when diverged
4457eafd5ff0SAlex Lindsay 
445819a666eeSBarry Smith   Notes:
445919a666eeSBarry Smith      To change the format of the output call PetscViewerPushFormat(viewer,format) before this call. Use PETSC_VIEWER_DEFAULT for the default,
446019a666eeSBarry Smith      use PETSC_VIEWER_FAILED to only display a reason if it fails.
44612a359c20SBarry Smith 
44622a359c20SBarry Smith    Level: beginner
44632a359c20SBarry Smith 
446419a666eeSBarry Smith .seealso: SNESCreate(), SNESSetUp(), SNESDestroy(), SNESSetTolerances(), SNESConvergedDefault(), SNESGetConvergedReason(), SNESConvergedReasonViewFromOptions(),
446519a666eeSBarry Smith           PetscViewerPushFormat(), PetscViewerPopFormat()
44662a359c20SBarry Smith 
44672a359c20SBarry Smith @*/
446819a666eeSBarry Smith PetscErrorCode  SNESConvergedReasonView(SNES snes,PetscViewer viewer)
44692a359c20SBarry Smith {
447075cca76cSMatthew G. Knepley   PetscViewerFormat format;
44712a359c20SBarry Smith   PetscBool         isAscii;
44722a359c20SBarry Smith 
44732a359c20SBarry Smith   PetscFunctionBegin;
447419a666eeSBarry Smith   if (!viewer) viewer = PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)snes));
44755f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&isAscii));
44762a359c20SBarry Smith   if (isAscii) {
44775f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscViewerGetFormat(viewer, &format));
44785f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscViewerASCIIAddTab(viewer,((PetscObject)snes)->tablevel));
447975cca76cSMatthew G. Knepley     if (format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
448075cca76cSMatthew G. Knepley       DM              dm;
448175cca76cSMatthew G. Knepley       Vec             u;
448275cca76cSMatthew G. Knepley       PetscDS         prob;
448375cca76cSMatthew G. Knepley       PetscInt        Nf, f;
448495cbbfd3SMatthew G. Knepley       PetscErrorCode (**exactSol)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar[], void *);
448595cbbfd3SMatthew G. Knepley       void            **exactCtx;
448675cca76cSMatthew G. Knepley       PetscReal       error;
448775cca76cSMatthew G. Knepley 
44885f80ce2aSJacob Faibussowitsch       CHKERRQ(SNESGetDM(snes, &dm));
44895f80ce2aSJacob Faibussowitsch       CHKERRQ(SNESGetSolution(snes, &u));
44905f80ce2aSJacob Faibussowitsch       CHKERRQ(DMGetDS(dm, &prob));
44915f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscDSGetNumFields(prob, &Nf));
44925f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscMalloc2(Nf, &exactSol, Nf, &exactCtx));
44935f80ce2aSJacob Faibussowitsch       for (f = 0; f < Nf; ++f) CHKERRQ(PetscDSGetExactSolution(prob, f, &exactSol[f], &exactCtx[f]));
44945f80ce2aSJacob Faibussowitsch       CHKERRQ(DMComputeL2Diff(dm, 0.0, exactSol, exactCtx, u, &error));
44955f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscFree2(exactSol, exactCtx));
44965f80ce2aSJacob Faibussowitsch       if (error < 1.0e-11) CHKERRQ(PetscViewerASCIIPrintf(viewer, "L_2 Error: < 1.0e-11\n"));
44975f80ce2aSJacob Faibussowitsch       else                 CHKERRQ(PetscViewerASCIIPrintf(viewer, "L_2 Error: %g\n", error));
449875cca76cSMatthew G. Knepley     }
4499eafd5ff0SAlex Lindsay     if (snes->reason > 0 && format != PETSC_VIEWER_FAILED) {
45002a359c20SBarry Smith       if (((PetscObject) snes)->prefix) {
45015f80ce2aSJacob Faibussowitsch         CHKERRQ(PetscViewerASCIIPrintf(viewer,"Nonlinear %s solve converged due to %s iterations %D\n",((PetscObject) snes)->prefix,SNESConvergedReasons[snes->reason],snes->iter));
45022a359c20SBarry Smith       } else {
45035f80ce2aSJacob Faibussowitsch         CHKERRQ(PetscViewerASCIIPrintf(viewer,"Nonlinear solve converged due to %s iterations %D\n",SNESConvergedReasons[snes->reason],snes->iter));
45042a359c20SBarry Smith       }
4505eafd5ff0SAlex Lindsay     } else if (snes->reason <= 0) {
45062a359c20SBarry Smith       if (((PetscObject) snes)->prefix) {
45075f80ce2aSJacob Faibussowitsch         CHKERRQ(PetscViewerASCIIPrintf(viewer,"Nonlinear %s solve did not converge due to %s iterations %D\n",((PetscObject) snes)->prefix,SNESConvergedReasons[snes->reason],snes->iter));
45082a359c20SBarry Smith       } else {
45095f80ce2aSJacob Faibussowitsch         CHKERRQ(PetscViewerASCIIPrintf(viewer,"Nonlinear solve did not converge due to %s iterations %D\n",SNESConvergedReasons[snes->reason],snes->iter));
45102a359c20SBarry Smith       }
45112a359c20SBarry Smith     }
45125f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscViewerASCIISubtractTab(viewer,((PetscObject)snes)->tablevel));
45132a359c20SBarry Smith   }
45142a359c20SBarry Smith   PetscFunctionReturn(0);
45152a359c20SBarry Smith }
45162a359c20SBarry Smith 
4517c4421ceaSFande Kong /*@C
4518c4421ceaSFande Kong    SNESConvergedReasonViewSet - Sets an ADDITIONAL function that is to be used at the
4519c4421ceaSFande Kong     end of the nonlinear solver to display the conver reason of the nonlinear solver.
4520c4421ceaSFande Kong 
4521c4421ceaSFande Kong    Logically Collective on SNES
4522c4421ceaSFande Kong 
4523c4421ceaSFande Kong    Input Parameters:
4524c4421ceaSFande Kong +  snes - the SNES context
4525c4421ceaSFande Kong .  f - the snes converged reason view function
4526c4421ceaSFande Kong .  vctx - [optional] user-defined context for private data for the
4527c4421ceaSFande Kong           snes converged reason view routine (use NULL if no context is desired)
4528c4421ceaSFande Kong -  reasonviewdestroy - [optional] routine that frees reasonview context
4529c4421ceaSFande Kong           (may be NULL)
4530c4421ceaSFande Kong 
4531c4421ceaSFande Kong    Options Database Keys:
4532c4421ceaSFande Kong +    -snes_converged_reason        - sets a default SNESConvergedReasonView()
4533c4421ceaSFande Kong -    -snes_converged_reason_view_cancel - cancels all converged reason viewers that have
4534c4421ceaSFande Kong                             been hardwired into a code by
4535c4421ceaSFande Kong                             calls to SNESConvergedReasonViewSet(), but
4536c4421ceaSFande Kong                             does not cancel those set via
4537c4421ceaSFande Kong                             the options database.
4538c4421ceaSFande Kong 
4539c4421ceaSFande Kong    Notes:
4540c4421ceaSFande Kong    Several different converged reason view routines may be set by calling
4541c4421ceaSFande Kong    SNESConvergedReasonViewSet() multiple times; all will be called in the
4542c4421ceaSFande Kong    order in which they were set.
4543c4421ceaSFande Kong 
4544c4421ceaSFande Kong    Level: intermediate
4545c4421ceaSFande Kong 
4546c4421ceaSFande Kong .seealso: SNESConvergedReasonView(), SNESConvergedReasonViewCancel()
4547c4421ceaSFande Kong @*/
4548c4421ceaSFande Kong PetscErrorCode  SNESConvergedReasonViewSet(SNES snes,PetscErrorCode (*f)(SNES,void*),void *vctx,PetscErrorCode (*reasonviewdestroy)(void**))
4549c4421ceaSFande Kong {
4550c4421ceaSFande Kong   PetscInt       i;
4551c4421ceaSFande Kong   PetscBool      identical;
4552c4421ceaSFande Kong 
4553c4421ceaSFande Kong   PetscFunctionBegin;
4554c4421ceaSFande Kong   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
4555c4421ceaSFande Kong   for (i=0; i<snes->numberreasonviews;i++) {
45565f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscMonitorCompare((PetscErrorCode (*)(void))f,vctx,reasonviewdestroy,(PetscErrorCode (*)(void))snes->reasonview[i],snes->reasonviewcontext[i],snes->reasonviewdestroy[i],&identical));
4557c4421ceaSFande Kong     if (identical) PetscFunctionReturn(0);
4558c4421ceaSFande Kong   }
45595f80ce2aSJacob Faibussowitsch   PetscCheck(snes->numberreasonviews < MAXSNESREASONVIEWS,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Too many SNES reasonview set");
4560c4421ceaSFande Kong   snes->reasonview[snes->numberreasonviews]          = f;
4561c4421ceaSFande Kong   snes->reasonviewdestroy[snes->numberreasonviews]   = reasonviewdestroy;
4562c4421ceaSFande Kong   snes->reasonviewcontext[snes->numberreasonviews++] = (void*)vctx;
4563c4421ceaSFande Kong   PetscFunctionReturn(0);
4564c4421ceaSFande Kong }
4565c4421ceaSFande Kong 
456691f3e32bSBarry Smith /*@
456719a666eeSBarry Smith   SNESConvergedReasonViewFromOptions - Processes command line options to determine if/how a SNESReason is to be viewed.
4568c4421ceaSFande Kong                                        All the user-provided convergedReasonView routines will be involved as well, if they exist.
45692a359c20SBarry Smith 
45702a359c20SBarry Smith   Collective on SNES
45712a359c20SBarry Smith 
45722a359c20SBarry Smith   Input Parameters:
45732a359c20SBarry Smith . snes   - the SNES object
45742a359c20SBarry Smith 
45752a359c20SBarry Smith   Level: intermediate
45762a359c20SBarry Smith 
457719a666eeSBarry Smith .seealso: SNESCreate(), SNESSetUp(), SNESDestroy(), SNESSetTolerances(), SNESConvergedDefault(), SNESGetConvergedReason(), SNESConvergedReasonView()
457819a666eeSBarry Smith 
45792a359c20SBarry Smith @*/
458019a666eeSBarry Smith PetscErrorCode SNESConvergedReasonViewFromOptions(SNES snes)
45812a359c20SBarry Smith {
45822a359c20SBarry Smith   PetscViewer       viewer;
45832a359c20SBarry Smith   PetscBool         flg;
45842a359c20SBarry Smith   static PetscBool  incall = PETSC_FALSE;
45852a359c20SBarry Smith   PetscViewerFormat format;
4586c4421ceaSFande Kong   PetscInt          i;
45872a359c20SBarry Smith 
45882a359c20SBarry Smith   PetscFunctionBegin;
45892a359c20SBarry Smith   if (incall) PetscFunctionReturn(0);
45902a359c20SBarry Smith   incall = PETSC_TRUE;
4591c4421ceaSFande Kong 
4592c4421ceaSFande Kong   /* All user-provided viewers are called first, if they exist. */
4593c4421ceaSFande Kong   for (i=0; i<snes->numberreasonviews; i++) {
45945f80ce2aSJacob Faibussowitsch     CHKERRQ((*snes->reasonview[i])(snes,snes->reasonviewcontext[i]));
4595c4421ceaSFande Kong   }
4596c4421ceaSFande Kong 
4597c4421ceaSFande Kong   /* Call PETSc default routine if users ask for it */
45985f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_converged_reason",&viewer,&format,&flg));
45992a359c20SBarry Smith   if (flg) {
46005f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscViewerPushFormat(viewer,format));
46015f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESConvergedReasonView(snes,viewer));
46025f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscViewerPopFormat(viewer));
46035f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscViewerDestroy(&viewer));
46042a359c20SBarry Smith   }
46052a359c20SBarry Smith   incall = PETSC_FALSE;
46062a359c20SBarry Smith   PetscFunctionReturn(0);
46072a359c20SBarry Smith }
46082a359c20SBarry Smith 
4609487a658cSBarry Smith /*@
4610f69a0ea3SMatthew Knepley    SNESSolve - Solves a nonlinear system F(x) = b.
4611f69a0ea3SMatthew Knepley    Call SNESSolve() after calling SNESCreate() and optional routines of the form SNESSetXXX().
46129b94acceSBarry Smith 
4613c7afd0dbSLois Curfman McInnes    Collective on SNES
4614c7afd0dbSLois Curfman McInnes 
4615b2002411SLois Curfman McInnes    Input Parameters:
4616c7afd0dbSLois Curfman McInnes +  snes - the SNES context
46170298fd71SBarry Smith .  b - the constant part of the equation F(x) = b, or NULL to use zero.
461885385478SLisandro Dalcin -  x - the solution vector.
46199b94acceSBarry Smith 
4620b2002411SLois Curfman McInnes    Notes:
46218ddd3da0SLois Curfman McInnes    The user should initialize the vector,x, with the initial guess
46226b7fb656SBarry Smith    for the nonlinear solve prior to calling SNESSolve().  In particular,
46238ddd3da0SLois Curfman McInnes    to employ an initial guess of zero, the user should explicitly set
46248ddd3da0SLois Curfman McInnes    this vector to zero by calling VecSet().
46258ddd3da0SLois Curfman McInnes 
462636851e7fSLois Curfman McInnes    Level: beginner
462736851e7fSLois Curfman McInnes 
46286b7fb656SBarry Smith .seealso: SNESCreate(), SNESDestroy(), SNESSetFunction(), SNESSetJacobian(), SNESSetGridSequence(), SNESGetSolution(),
46296b7fb656SBarry Smith           SNESNewtonTRSetPreCheck(), SNESNewtonTRGetPreCheck(), SNESNewtonTRSetPostCheck(), SNESNewtonTRGetPostCheck(),
46306b7fb656SBarry Smith           SNESLineSearchSetPostCheck(), SNESLineSearchGetPostCheck(), SNESLineSearchSetPreCheck(), SNESLineSearchGetPreCheck()
46319b94acceSBarry Smith @*/
46327087cfbeSBarry Smith PetscErrorCode  SNESSolve(SNES snes,Vec b,Vec x)
46339b94acceSBarry Smith {
4634ace3abfcSBarry Smith   PetscBool         flg;
4635efd51863SBarry Smith   PetscInt          grid;
46360298fd71SBarry Smith   Vec               xcreated = NULL;
4637caa4e7f2SJed Brown   DM                dm;
4638052efed2SBarry Smith 
46393a40ed3dSBarry Smith   PetscFunctionBegin;
46400700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
4641a69afd8bSBarry Smith   if (x) PetscValidHeaderSpecific(x,VEC_CLASSID,3);
4642a69afd8bSBarry Smith   if (x) PetscCheckSameComm(snes,1,x,3);
46430700a824SBarry Smith   if (b) PetscValidHeaderSpecific(b,VEC_CLASSID,2);
464485385478SLisandro Dalcin   if (b) PetscCheckSameComm(snes,1,b,2);
464585385478SLisandro Dalcin 
464634b4d3a8SMatthew G. Knepley   /* High level operations using the nonlinear solver */
464706fc46c8SMatthew G. Knepley   {
464806fc46c8SMatthew G. Knepley     PetscViewer       viewer;
464906fc46c8SMatthew G. Knepley     PetscViewerFormat format;
46507c88af5aSMatthew G. Knepley     PetscInt          num;
465106fc46c8SMatthew G. Knepley     PetscBool         flg;
465206fc46c8SMatthew G. Knepley     static PetscBool  incall = PETSC_FALSE;
465306fc46c8SMatthew G. Knepley 
465406fc46c8SMatthew G. Knepley     if (!incall) {
465534b4d3a8SMatthew G. Knepley       /* Estimate the convergence rate of the discretization */
46565f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscOptionsGetViewer(PetscObjectComm((PetscObject) snes),((PetscObject)snes)->options, ((PetscObject) snes)->prefix, "-snes_convergence_estimate", &viewer, &format, &flg));
465706fc46c8SMatthew G. Knepley       if (flg) {
465806fc46c8SMatthew G. Knepley         PetscConvEst conv;
465946079b62SMatthew G. Knepley         DM           dm;
466046079b62SMatthew G. Knepley         PetscReal   *alpha; /* Convergence rate of the solution error for each field in the L_2 norm */
466146079b62SMatthew G. Knepley         PetscInt     Nf;
466206fc46c8SMatthew G. Knepley 
466306fc46c8SMatthew G. Knepley         incall = PETSC_TRUE;
46645f80ce2aSJacob Faibussowitsch         CHKERRQ(SNESGetDM(snes, &dm));
46655f80ce2aSJacob Faibussowitsch         CHKERRQ(DMGetNumFields(dm, &Nf));
46665f80ce2aSJacob Faibussowitsch         CHKERRQ(PetscCalloc1(Nf, &alpha));
46675f80ce2aSJacob Faibussowitsch         CHKERRQ(PetscConvEstCreate(PetscObjectComm((PetscObject) snes), &conv));
46685f80ce2aSJacob Faibussowitsch         CHKERRQ(PetscConvEstSetSolver(conv, (PetscObject) snes));
46695f80ce2aSJacob Faibussowitsch         CHKERRQ(PetscConvEstSetFromOptions(conv));
46705f80ce2aSJacob Faibussowitsch         CHKERRQ(PetscConvEstSetUp(conv));
46715f80ce2aSJacob Faibussowitsch         CHKERRQ(PetscConvEstGetConvRate(conv, alpha));
46725f80ce2aSJacob Faibussowitsch         CHKERRQ(PetscViewerPushFormat(viewer, format));
46735f80ce2aSJacob Faibussowitsch         CHKERRQ(PetscConvEstRateView(conv, alpha, viewer));
46745f80ce2aSJacob Faibussowitsch         CHKERRQ(PetscViewerPopFormat(viewer));
46755f80ce2aSJacob Faibussowitsch         CHKERRQ(PetscViewerDestroy(&viewer));
46765f80ce2aSJacob Faibussowitsch         CHKERRQ(PetscConvEstDestroy(&conv));
46775f80ce2aSJacob Faibussowitsch         CHKERRQ(PetscFree(alpha));
467806fc46c8SMatthew G. Knepley         incall = PETSC_FALSE;
467906fc46c8SMatthew G. Knepley       }
468034b4d3a8SMatthew G. Knepley       /* Adaptively refine the initial grid */
4681b2588ea6SMatthew G. Knepley       num  = 1;
46825f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscOptionsGetInt(NULL, ((PetscObject) snes)->prefix, "-snes_adapt_initial", &num, &flg));
468334b4d3a8SMatthew G. Knepley       if (flg) {
468434b4d3a8SMatthew G. Knepley         DMAdaptor adaptor;
468534b4d3a8SMatthew G. Knepley 
468634b4d3a8SMatthew G. Knepley         incall = PETSC_TRUE;
46875f80ce2aSJacob Faibussowitsch         CHKERRQ(DMAdaptorCreate(PetscObjectComm((PetscObject)snes), &adaptor));
46885f80ce2aSJacob Faibussowitsch         CHKERRQ(DMAdaptorSetSolver(adaptor, snes));
46895f80ce2aSJacob Faibussowitsch         CHKERRQ(DMAdaptorSetSequenceLength(adaptor, num));
46905f80ce2aSJacob Faibussowitsch         CHKERRQ(DMAdaptorSetFromOptions(adaptor));
46915f80ce2aSJacob Faibussowitsch         CHKERRQ(DMAdaptorSetUp(adaptor));
46925f80ce2aSJacob Faibussowitsch         CHKERRQ(DMAdaptorAdapt(adaptor, x, DM_ADAPTATION_INITIAL, &dm, &x));
46935f80ce2aSJacob Faibussowitsch         CHKERRQ(DMAdaptorDestroy(&adaptor));
469434b4d3a8SMatthew G. Knepley         incall = PETSC_FALSE;
469534b4d3a8SMatthew G. Knepley       }
46967c88af5aSMatthew G. Knepley       /* Use grid sequencing to adapt */
46977c88af5aSMatthew G. Knepley       num  = 0;
46985f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscOptionsGetInt(NULL, ((PetscObject) snes)->prefix, "-snes_adapt_sequence", &num, NULL));
46997c88af5aSMatthew G. Knepley       if (num) {
47007c88af5aSMatthew G. Knepley         DMAdaptor adaptor;
47017c88af5aSMatthew G. Knepley 
47027c88af5aSMatthew G. Knepley         incall = PETSC_TRUE;
47035f80ce2aSJacob Faibussowitsch         CHKERRQ(DMAdaptorCreate(PetscObjectComm((PetscObject)snes), &adaptor));
47045f80ce2aSJacob Faibussowitsch         CHKERRQ(DMAdaptorSetSolver(adaptor, snes));
47055f80ce2aSJacob Faibussowitsch         CHKERRQ(DMAdaptorSetSequenceLength(adaptor, num));
47065f80ce2aSJacob Faibussowitsch         CHKERRQ(DMAdaptorSetFromOptions(adaptor));
47075f80ce2aSJacob Faibussowitsch         CHKERRQ(DMAdaptorSetUp(adaptor));
47085f80ce2aSJacob Faibussowitsch         CHKERRQ(DMAdaptorAdapt(adaptor, x, DM_ADAPTATION_SEQUENTIAL, &dm, &x));
47095f80ce2aSJacob Faibussowitsch         CHKERRQ(DMAdaptorDestroy(&adaptor));
47107c88af5aSMatthew G. Knepley         incall = PETSC_FALSE;
47117c88af5aSMatthew G. Knepley       }
471206fc46c8SMatthew G. Knepley     }
471306fc46c8SMatthew G. Knepley   }
471441e867a5SStefano Zampini   if (!x) { x = snes->vec_sol; }
4715caa4e7f2SJed Brown   if (!x) {
47165f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESGetDM(snes,&dm));
47175f80ce2aSJacob Faibussowitsch     CHKERRQ(DMCreateGlobalVector(dm,&xcreated));
4718a69afd8bSBarry Smith     x    = xcreated;
4719a69afd8bSBarry Smith   }
47205f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESViewFromOptions(snes,NULL,"-snes_view_pre"));
4721f05ece33SBarry Smith 
47225f80ce2aSJacob Faibussowitsch   for (grid=0; grid<snes->gridsequence; grid++) CHKERRQ(PetscViewerASCIIPushTab(PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)snes))));
4723efd51863SBarry Smith   for (grid=0; grid<snes->gridsequence+1; grid++) {
4724efd51863SBarry Smith 
472585385478SLisandro Dalcin     /* set solution vector */
47265f80ce2aSJacob Faibussowitsch     if (!grid) CHKERRQ(PetscObjectReference((PetscObject)x));
47275f80ce2aSJacob Faibussowitsch     CHKERRQ(VecDestroy(&snes->vec_sol));
472885385478SLisandro Dalcin     snes->vec_sol = x;
47295f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESGetDM(snes,&dm));
4730caa4e7f2SJed Brown 
4731caa4e7f2SJed Brown     /* set affine vector if provided */
47325f80ce2aSJacob Faibussowitsch     if (b) CHKERRQ(PetscObjectReference((PetscObject)b));
47335f80ce2aSJacob Faibussowitsch     CHKERRQ(VecDestroy(&snes->vec_rhs));
473485385478SLisandro Dalcin     snes->vec_rhs = b;
473585385478SLisandro Dalcin 
47365f80ce2aSJacob Faibussowitsch     if (snes->vec_rhs) PetscCheck(snes->vec_func != snes->vec_rhs,PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"Right hand side vector cannot be function vector");
47375f80ce2aSJacob Faibussowitsch     PetscCheck(snes->vec_func != snes->vec_sol,PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"Solution vector cannot be function vector");
47385f80ce2aSJacob Faibussowitsch     PetscCheck(snes->vec_rhs  != snes->vec_sol,PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"Solution vector cannot be right hand side vector");
4739154060b5SMatthew G. Knepley     if (!snes->vec_sol_update /* && snes->vec_sol */) {
47405f80ce2aSJacob Faibussowitsch       CHKERRQ(VecDuplicate(snes->vec_sol,&snes->vec_sol_update));
47415f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->vec_sol_update));
4742154060b5SMatthew G. Knepley     }
47435f80ce2aSJacob Faibussowitsch     CHKERRQ(DMShellSetGlobalVector(dm,snes->vec_sol));
47445f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESSetUp(snes));
47453f149594SLisandro Dalcin 
47467eee914bSBarry Smith     if (!grid) {
47477eee914bSBarry Smith       if (snes->ops->computeinitialguess) {
47485f80ce2aSJacob Faibussowitsch         CHKERRQ((*snes->ops->computeinitialguess)(snes,snes->vec_sol,snes->initialguessP));
4749d25893d9SBarry Smith       }
4750dd568438SSatish Balay     }
4751d25893d9SBarry Smith 
4752abc0a331SBarry Smith     if (snes->conv_hist_reset) snes->conv_hist_len = 0;
4753971e163fSPeter Brune     if (snes->counters_reset) {snes->nfuncs = 0; snes->linear_its = 0; snes->numFailures = 0;}
4754d5e45103SBarry Smith 
47555f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscLogEventBegin(SNES_Solve,snes,0,0,0));
47565f80ce2aSJacob Faibussowitsch     CHKERRQ((*snes->ops->solve)(snes));
47575f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscLogEventEnd(SNES_Solve,snes,0,0,0));
47585f80ce2aSJacob Faibussowitsch     PetscCheck(snes->reason,PETSC_COMM_SELF,PETSC_ERR_PLIB,"Internal error, solver returned without setting converged reason");
4759422a814eSBarry Smith     snes->domainerror = PETSC_FALSE; /* clear the flag if it has been set */
47603f149594SLisandro Dalcin 
476137ec4e1aSPeter Brune     if (snes->lagjac_persist) snes->jac_iter += snes->iter;
476237ec4e1aSPeter Brune     if (snes->lagpre_persist) snes->pre_iter += snes->iter;
476337ec4e1aSPeter Brune 
47645f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_test_local_min",NULL,NULL,&flg));
47655f80ce2aSJacob Faibussowitsch     if (flg && !PetscPreLoadingOn) CHKERRQ(SNESTestLocalMin(snes));
4766c4421ceaSFande Kong     /* Call converged reason views. This may involve user-provided viewers as well */
47675f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESConvergedReasonViewFromOptions(snes));
47685968eb51SBarry Smith 
47695f80ce2aSJacob Faibussowitsch     if (snes->errorifnotconverged) PetscCheck(snes->reason >= 0,PetscObjectComm((PetscObject)snes),PETSC_ERR_NOT_CONVERGED,"SNESSolve has not converged");
47709c8e83a9SBarry Smith     if (snes->reason < 0) break;
4771efd51863SBarry Smith     if (grid <  snes->gridsequence) {
4772efd51863SBarry Smith       DM  fine;
4773efd51863SBarry Smith       Vec xnew;
4774efd51863SBarry Smith       Mat interp;
4775efd51863SBarry Smith 
47765f80ce2aSJacob Faibussowitsch       CHKERRQ(DMRefine(snes->dm,PetscObjectComm((PetscObject)snes),&fine));
47775f80ce2aSJacob Faibussowitsch       PetscCheck(fine,PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_INCOMP,"DMRefine() did not perform any refinement, cannot continue grid sequencing");
47785f80ce2aSJacob Faibussowitsch       CHKERRQ(DMCreateInterpolation(snes->dm,fine,&interp,NULL));
47795f80ce2aSJacob Faibussowitsch       CHKERRQ(DMCreateGlobalVector(fine,&xnew));
47805f80ce2aSJacob Faibussowitsch       CHKERRQ(MatInterpolate(interp,x,xnew));
47815f80ce2aSJacob Faibussowitsch       CHKERRQ(DMInterpolate(snes->dm,interp,fine));
47825f80ce2aSJacob Faibussowitsch       CHKERRQ(MatDestroy(&interp));
4783efd51863SBarry Smith       x    = xnew;
4784efd51863SBarry Smith 
47855f80ce2aSJacob Faibussowitsch       CHKERRQ(SNESReset(snes));
47865f80ce2aSJacob Faibussowitsch       CHKERRQ(SNESSetDM(snes,fine));
47875f80ce2aSJacob Faibussowitsch       CHKERRQ(SNESResetFromOptions(snes));
47885f80ce2aSJacob Faibussowitsch       CHKERRQ(DMDestroy(&fine));
47895f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscViewerASCIIPopTab(PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)snes))));
4790efd51863SBarry Smith     }
4791efd51863SBarry Smith   }
47925f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESViewFromOptions(snes,NULL,"-snes_view"));
47935f80ce2aSJacob Faibussowitsch   CHKERRQ(VecViewFromOptions(snes->vec_sol,(PetscObject)snes,"-snes_view_solution"));
47945f80ce2aSJacob Faibussowitsch   CHKERRQ(DMMonitor(snes->dm));
47955f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESMonitorPauseFinal_Internal(snes));
47963f7e2da0SPeter Brune 
47975f80ce2aSJacob Faibussowitsch   CHKERRQ(VecDestroy(&xcreated));
47985f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscObjectSAWsBlock((PetscObject)snes));
47993a40ed3dSBarry Smith   PetscFunctionReturn(0);
48009b94acceSBarry Smith }
48019b94acceSBarry Smith 
48029b94acceSBarry Smith /* --------- Internal routines for SNES Package --------- */
48039b94acceSBarry Smith 
480482bf6240SBarry Smith /*@C
48054b0e389bSBarry Smith    SNESSetType - Sets the method for the nonlinear solver.
48069b94acceSBarry Smith 
4807fee21e36SBarry Smith    Collective on SNES
4808fee21e36SBarry Smith 
4809c7afd0dbSLois Curfman McInnes    Input Parameters:
4810c7afd0dbSLois Curfman McInnes +  snes - the SNES context
4811454a90a3SBarry Smith -  type - a known method
4812c7afd0dbSLois Curfman McInnes 
4813c7afd0dbSLois Curfman McInnes    Options Database Key:
4814454a90a3SBarry Smith .  -snes_type <type> - Sets the method; use -help for a list
481504d7464bSBarry Smith    of available methods (for instance, newtonls or newtontr)
4816ae12b187SLois Curfman McInnes 
48179b94acceSBarry Smith    Notes:
4818e090d566SSatish Balay    See "petsc/include/petscsnes.h" for available methods (for instance)
481904d7464bSBarry Smith +    SNESNEWTONLS - Newton's method with line search
4820c7afd0dbSLois Curfman McInnes      (systems of nonlinear equations)
4821a2b725a8SWilliam Gropp -    SNESNEWTONTR - Newton's method with trust region
4822c7afd0dbSLois Curfman McInnes      (systems of nonlinear equations)
48239b94acceSBarry Smith 
4824ae12b187SLois Curfman McInnes   Normally, it is best to use the SNESSetFromOptions() command and then
4825ae12b187SLois Curfman McInnes   set the SNES solver type from the options database rather than by using
4826ae12b187SLois Curfman McInnes   this routine.  Using the options database provides the user with
4827ae12b187SLois Curfman McInnes   maximum flexibility in evaluating the many nonlinear solvers.
4828ae12b187SLois Curfman McInnes   The SNESSetType() routine is provided for those situations where it
4829ae12b187SLois Curfman McInnes   is necessary to set the nonlinear solver independently of the command
4830ae12b187SLois Curfman McInnes   line or options database.  This might be the case, for example, when
4831ae12b187SLois Curfman McInnes   the choice of solver changes during the execution of the program,
4832ae12b187SLois Curfman McInnes   and the user's application is taking responsibility for choosing the
4833b0a32e0cSBarry Smith   appropriate method.
483436851e7fSLois Curfman McInnes 
483595452b02SPatrick Sanan     Developer Notes:
483695452b02SPatrick Sanan     SNESRegister() adds a constructor for a new SNESType to SNESList, SNESSetType() locates
48378f6c3df8SBarry Smith     the constructor in that list and calls it to create the spexific object.
48388f6c3df8SBarry Smith 
483936851e7fSLois Curfman McInnes   Level: intermediate
4840a703fe33SLois Curfman McInnes 
48418f6c3df8SBarry Smith .seealso: SNESType, SNESCreate(), SNESDestroy(), SNESGetType(), SNESSetFromOptions()
4842435da068SBarry Smith 
48439b94acceSBarry Smith @*/
484419fd82e9SBarry Smith PetscErrorCode  SNESSetType(SNES snes,SNESType type)
48459b94acceSBarry Smith {
4846ace3abfcSBarry Smith   PetscBool      match;
48475f80ce2aSJacob Faibussowitsch   PetscErrorCode (*r)(SNES);
48483a40ed3dSBarry Smith 
48493a40ed3dSBarry Smith   PetscFunctionBegin;
48500700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
48514482741eSBarry Smith   PetscValidCharPointer(type,2);
485282bf6240SBarry Smith 
48535f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscObjectTypeCompare((PetscObject)snes,type,&match));
48540f5bd95cSBarry Smith   if (match) PetscFunctionReturn(0);
485592ff6ae8SBarry Smith 
48565f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscFunctionListFind(SNESList,type,&r));
48575f80ce2aSJacob Faibussowitsch   PetscCheck(r,PETSC_COMM_SELF,PETSC_ERR_ARG_UNKNOWN_TYPE,"Unable to find requested SNES type %s",type);
485875396ef9SLisandro Dalcin   /* Destroy the previous private SNES context */
4859b5c23020SJed Brown   if (snes->ops->destroy) {
48605f80ce2aSJacob Faibussowitsch     CHKERRQ((*(snes)->ops->destroy)(snes));
48610298fd71SBarry Smith     snes->ops->destroy = NULL;
4862b5c23020SJed Brown   }
486375396ef9SLisandro Dalcin   /* Reinitialize function pointers in SNESOps structure */
48649e5d0892SLisandro Dalcin   snes->ops->setup          = NULL;
48659e5d0892SLisandro Dalcin   snes->ops->solve          = NULL;
48669e5d0892SLisandro Dalcin   snes->ops->view           = NULL;
48679e5d0892SLisandro Dalcin   snes->ops->setfromoptions = NULL;
48689e5d0892SLisandro Dalcin   snes->ops->destroy        = NULL;
48697fe760d5SStefano Zampini 
48707fe760d5SStefano Zampini   /* It may happen the user has customized the line search before calling SNESSetType */
48715f80ce2aSJacob Faibussowitsch   if (((PetscObject)snes)->type_name) CHKERRQ(SNESLineSearchDestroy(&snes->linesearch));
48727fe760d5SStefano Zampini 
487375396ef9SLisandro Dalcin   /* Call the SNESCreate_XXX routine for this particular Nonlinear solver */
487475396ef9SLisandro Dalcin   snes->setupcalled = PETSC_FALSE;
4875f5af7f23SKarl Rupp 
48765f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscObjectChangeTypeName((PetscObject)snes,type));
48775f80ce2aSJacob Faibussowitsch   CHKERRQ((*r)(snes));
48783a40ed3dSBarry Smith   PetscFunctionReturn(0);
48799b94acceSBarry Smith }
48809b94acceSBarry Smith 
48819b94acceSBarry Smith /*@C
48829a28b0a6SLois Curfman McInnes    SNESGetType - Gets the SNES method type and name (as a string).
48839b94acceSBarry Smith 
4884c7afd0dbSLois Curfman McInnes    Not Collective
4885c7afd0dbSLois Curfman McInnes 
48869b94acceSBarry Smith    Input Parameter:
48874b0e389bSBarry Smith .  snes - nonlinear solver context
48889b94acceSBarry Smith 
48899b94acceSBarry Smith    Output Parameter:
48903a7fca6bSBarry Smith .  type - SNES method (a character string)
48919b94acceSBarry Smith 
489236851e7fSLois Curfman McInnes    Level: intermediate
489336851e7fSLois Curfman McInnes 
48949b94acceSBarry Smith @*/
489519fd82e9SBarry Smith PetscErrorCode  SNESGetType(SNES snes,SNESType *type)
48969b94acceSBarry Smith {
48973a40ed3dSBarry Smith   PetscFunctionBegin;
48980700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
48994482741eSBarry Smith   PetscValidPointer(type,2);
49007adad957SLisandro Dalcin   *type = ((PetscObject)snes)->type_name;
49013a40ed3dSBarry Smith   PetscFunctionReturn(0);
49029b94acceSBarry Smith }
49039b94acceSBarry Smith 
49043cd8a7caSMatthew G. Knepley /*@
49053cd8a7caSMatthew G. Knepley   SNESSetSolution - Sets the solution vector for use by the SNES routines.
49063cd8a7caSMatthew G. Knepley 
4907d083f849SBarry Smith   Logically Collective on SNES
49083cd8a7caSMatthew G. Knepley 
49093cd8a7caSMatthew G. Knepley   Input Parameters:
49103cd8a7caSMatthew G. Knepley + snes - the SNES context obtained from SNESCreate()
49113cd8a7caSMatthew G. Knepley - u    - the solution vector
49123cd8a7caSMatthew G. Knepley 
49133cd8a7caSMatthew G. Knepley   Level: beginner
49143cd8a7caSMatthew G. Knepley 
49153cd8a7caSMatthew G. Knepley @*/
49163cd8a7caSMatthew G. Knepley PetscErrorCode SNESSetSolution(SNES snes, Vec u)
49173cd8a7caSMatthew G. Knepley {
49183cd8a7caSMatthew G. Knepley   DM             dm;
49193cd8a7caSMatthew G. Knepley 
49203cd8a7caSMatthew G. Knepley   PetscFunctionBegin;
49213cd8a7caSMatthew G. Knepley   PetscValidHeaderSpecific(snes, SNES_CLASSID, 1);
49223cd8a7caSMatthew G. Knepley   PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
49235f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscObjectReference((PetscObject) u));
49245f80ce2aSJacob Faibussowitsch   CHKERRQ(VecDestroy(&snes->vec_sol));
49253cd8a7caSMatthew G. Knepley 
49263cd8a7caSMatthew G. Knepley   snes->vec_sol = u;
49273cd8a7caSMatthew G. Knepley 
49285f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESGetDM(snes, &dm));
49295f80ce2aSJacob Faibussowitsch   CHKERRQ(DMShellSetGlobalVector(dm, u));
49303cd8a7caSMatthew G. Knepley   PetscFunctionReturn(0);
49313cd8a7caSMatthew G. Knepley }
49323cd8a7caSMatthew G. Knepley 
493352baeb72SSatish Balay /*@
49349b94acceSBarry Smith    SNESGetSolution - Returns the vector where the approximate solution is
4935c0df2a02SJed Brown    stored. This is the fine grid solution when using SNESSetGridSequence().
49369b94acceSBarry Smith 
4937c7afd0dbSLois Curfman McInnes    Not Collective, but Vec is parallel if SNES is parallel
4938c7afd0dbSLois Curfman McInnes 
49399b94acceSBarry Smith    Input Parameter:
49409b94acceSBarry Smith .  snes - the SNES context
49419b94acceSBarry Smith 
49429b94acceSBarry Smith    Output Parameter:
49439b94acceSBarry Smith .  x - the solution
49449b94acceSBarry Smith 
494570e92668SMatthew Knepley    Level: intermediate
494636851e7fSLois Curfman McInnes 
494785385478SLisandro Dalcin .seealso:  SNESGetSolutionUpdate(), SNESGetFunction()
49489b94acceSBarry Smith @*/
49497087cfbeSBarry Smith PetscErrorCode  SNESGetSolution(SNES snes,Vec *x)
49509b94acceSBarry Smith {
49513a40ed3dSBarry Smith   PetscFunctionBegin;
49520700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
49534482741eSBarry Smith   PetscValidPointer(x,2);
495485385478SLisandro Dalcin   *x = snes->vec_sol;
495570e92668SMatthew Knepley   PetscFunctionReturn(0);
495670e92668SMatthew Knepley }
495770e92668SMatthew Knepley 
495852baeb72SSatish Balay /*@
49599b94acceSBarry Smith    SNESGetSolutionUpdate - Returns the vector where the solution update is
49609b94acceSBarry Smith    stored.
49619b94acceSBarry Smith 
4962c7afd0dbSLois Curfman McInnes    Not Collective, but Vec is parallel if SNES is parallel
4963c7afd0dbSLois Curfman McInnes 
49649b94acceSBarry Smith    Input Parameter:
49659b94acceSBarry Smith .  snes - the SNES context
49669b94acceSBarry Smith 
49679b94acceSBarry Smith    Output Parameter:
49689b94acceSBarry Smith .  x - the solution update
49699b94acceSBarry Smith 
497036851e7fSLois Curfman McInnes    Level: advanced
497136851e7fSLois Curfman McInnes 
497285385478SLisandro Dalcin .seealso: SNESGetSolution(), SNESGetFunction()
49739b94acceSBarry Smith @*/
49747087cfbeSBarry Smith PetscErrorCode  SNESGetSolutionUpdate(SNES snes,Vec *x)
49759b94acceSBarry Smith {
49763a40ed3dSBarry Smith   PetscFunctionBegin;
49770700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
49784482741eSBarry Smith   PetscValidPointer(x,2);
497985385478SLisandro Dalcin   *x = snes->vec_sol_update;
49803a40ed3dSBarry Smith   PetscFunctionReturn(0);
49819b94acceSBarry Smith }
49829b94acceSBarry Smith 
49839b94acceSBarry Smith /*@C
49843638b69dSLois Curfman McInnes    SNESGetFunction - Returns the vector where the function is stored.
49859b94acceSBarry Smith 
4986a63bb30eSJed Brown    Not Collective, but Vec is parallel if SNES is parallel. Collective if Vec is requested, but has not been created yet.
4987c7afd0dbSLois Curfman McInnes 
49889b94acceSBarry Smith    Input Parameter:
49899b94acceSBarry Smith .  snes - the SNES context
49909b94acceSBarry Smith 
4991d8d19677SJose E. Roman    Output Parameters:
49920298fd71SBarry Smith +  r - the vector that is used to store residuals (or NULL if you don't want it)
4993f8b49ee9SBarry Smith .  f - the function (or NULL if you don't want it); see SNESFunction for calling sequence details
49940298fd71SBarry Smith -  ctx - the function context (or NULL if you don't want it)
49959b94acceSBarry Smith 
499636851e7fSLois Curfman McInnes    Level: advanced
499736851e7fSLois Curfman McInnes 
499804edfde5SBarry Smith     Notes: The vector r DOES NOT, in general contain the current value of the SNES nonlinear function
499904edfde5SBarry Smith 
5000bf388a1fSBarry Smith .seealso: SNESSetFunction(), SNESGetSolution(), SNESFunction
50019b94acceSBarry Smith @*/
5002f8b49ee9SBarry Smith PetscErrorCode  SNESGetFunction(SNES snes,Vec *r,PetscErrorCode (**f)(SNES,Vec,Vec,void*),void **ctx)
50039b94acceSBarry Smith {
50046cab3a1bSJed Brown   DM             dm;
5005a63bb30eSJed Brown 
50063a40ed3dSBarry Smith   PetscFunctionBegin;
50070700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
5008a63bb30eSJed Brown   if (r) {
5009a63bb30eSJed Brown     if (!snes->vec_func) {
5010a63bb30eSJed Brown       if (snes->vec_rhs) {
50115f80ce2aSJacob Faibussowitsch         CHKERRQ(VecDuplicate(snes->vec_rhs,&snes->vec_func));
5012a63bb30eSJed Brown       } else if (snes->vec_sol) {
50135f80ce2aSJacob Faibussowitsch         CHKERRQ(VecDuplicate(snes->vec_sol,&snes->vec_func));
5014a63bb30eSJed Brown       } else if (snes->dm) {
50155f80ce2aSJacob Faibussowitsch         CHKERRQ(DMCreateGlobalVector(snes->dm,&snes->vec_func));
5016a63bb30eSJed Brown       }
5017a63bb30eSJed Brown     }
5018a63bb30eSJed Brown     *r = snes->vec_func;
5019a63bb30eSJed Brown   }
50205f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESGetDM(snes,&dm));
50215f80ce2aSJacob Faibussowitsch   CHKERRQ(DMSNESGetFunction(dm,f,ctx));
50223a40ed3dSBarry Smith   PetscFunctionReturn(0);
50239b94acceSBarry Smith }
50249b94acceSBarry Smith 
5025c79ef259SPeter Brune /*@C
5026be95d8f1SBarry Smith    SNESGetNGS - Returns the NGS function and context.
5027c79ef259SPeter Brune 
5028c79ef259SPeter Brune    Input Parameter:
5029c79ef259SPeter Brune .  snes - the SNES context
5030c79ef259SPeter Brune 
5031d8d19677SJose E. Roman    Output Parameters:
5032be95d8f1SBarry Smith +  f - the function (or NULL) see SNESNGSFunction for details
50330298fd71SBarry Smith -  ctx    - the function context (or NULL)
5034c79ef259SPeter Brune 
5035c79ef259SPeter Brune    Level: advanced
5036c79ef259SPeter Brune 
5037be95d8f1SBarry Smith .seealso: SNESSetNGS(), SNESGetFunction()
5038c79ef259SPeter Brune @*/
5039c79ef259SPeter Brune 
5040be95d8f1SBarry Smith PetscErrorCode SNESGetNGS (SNES snes, PetscErrorCode (**f)(SNES, Vec, Vec, void*), void ** ctx)
5041646217ecSPeter Brune {
50426cab3a1bSJed Brown   DM             dm;
50436cab3a1bSJed Brown 
5044646217ecSPeter Brune   PetscFunctionBegin;
5045646217ecSPeter Brune   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
50465f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESGetDM(snes,&dm));
50475f80ce2aSJacob Faibussowitsch   CHKERRQ(DMSNESGetNGS(dm,f,ctx));
5048646217ecSPeter Brune   PetscFunctionReturn(0);
5049646217ecSPeter Brune }
5050646217ecSPeter Brune 
50513c7409f5SSatish Balay /*@C
50523c7409f5SSatish Balay    SNESSetOptionsPrefix - Sets the prefix used for searching for all
5053d850072dSLois Curfman McInnes    SNES options in the database.
50543c7409f5SSatish Balay 
50553f9fe445SBarry Smith    Logically Collective on SNES
5056fee21e36SBarry Smith 
5057d8d19677SJose E. Roman    Input Parameters:
5058c7afd0dbSLois Curfman McInnes +  snes - the SNES context
5059c7afd0dbSLois Curfman McInnes -  prefix - the prefix to prepend to all option names
5060c7afd0dbSLois Curfman McInnes 
5061d850072dSLois Curfman McInnes    Notes:
5062a83b1b31SSatish Balay    A hyphen (-) must NOT be given at the beginning of the prefix name.
5063c7afd0dbSLois Curfman McInnes    The first character of all runtime options is AUTOMATICALLY the hyphen.
5064d850072dSLois Curfman McInnes 
506536851e7fSLois Curfman McInnes    Level: advanced
506636851e7fSLois Curfman McInnes 
5067a86d99e1SLois Curfman McInnes .seealso: SNESSetFromOptions()
50683c7409f5SSatish Balay @*/
50697087cfbeSBarry Smith PetscErrorCode  SNESSetOptionsPrefix(SNES snes,const char prefix[])
50703c7409f5SSatish Balay {
50713a40ed3dSBarry Smith   PetscFunctionBegin;
50720700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
50735f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscObjectSetOptionsPrefix((PetscObject)snes,prefix));
50745f80ce2aSJacob Faibussowitsch   if (!snes->ksp) CHKERRQ(SNESGetKSP(snes,&snes->ksp));
507535f5d045SPeter Brune   if (snes->linesearch) {
50765f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESGetLineSearch(snes,&snes->linesearch));
50775f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscObjectSetOptionsPrefix((PetscObject)snes->linesearch,prefix));
507835f5d045SPeter Brune   }
50795f80ce2aSJacob Faibussowitsch   CHKERRQ(KSPSetOptionsPrefix(snes->ksp,prefix));
50803a40ed3dSBarry Smith   PetscFunctionReturn(0);
50813c7409f5SSatish Balay }
50823c7409f5SSatish Balay 
50833c7409f5SSatish Balay /*@C
5084f525115eSLois Curfman McInnes    SNESAppendOptionsPrefix - Appends to the prefix used for searching for all
5085d850072dSLois Curfman McInnes    SNES options in the database.
50863c7409f5SSatish Balay 
50873f9fe445SBarry Smith    Logically Collective on SNES
5088fee21e36SBarry Smith 
5089c7afd0dbSLois Curfman McInnes    Input Parameters:
5090c7afd0dbSLois Curfman McInnes +  snes - the SNES context
5091c7afd0dbSLois Curfman McInnes -  prefix - the prefix to prepend to all option names
5092c7afd0dbSLois Curfman McInnes 
5093d850072dSLois Curfman McInnes    Notes:
5094a83b1b31SSatish Balay    A hyphen (-) must NOT be given at the beginning of the prefix name.
5095c7afd0dbSLois Curfman McInnes    The first character of all runtime options is AUTOMATICALLY the hyphen.
5096d850072dSLois Curfman McInnes 
509736851e7fSLois Curfman McInnes    Level: advanced
509836851e7fSLois Curfman McInnes 
5099a86d99e1SLois Curfman McInnes .seealso: SNESGetOptionsPrefix()
51003c7409f5SSatish Balay @*/
51017087cfbeSBarry Smith PetscErrorCode  SNESAppendOptionsPrefix(SNES snes,const char prefix[])
51023c7409f5SSatish Balay {
51033a40ed3dSBarry Smith   PetscFunctionBegin;
51040700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
51055f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscObjectAppendOptionsPrefix((PetscObject)snes,prefix));
51065f80ce2aSJacob Faibussowitsch   if (!snes->ksp) CHKERRQ(SNESGetKSP(snes,&snes->ksp));
510735f5d045SPeter Brune   if (snes->linesearch) {
51085f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESGetLineSearch(snes,&snes->linesearch));
51095f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscObjectAppendOptionsPrefix((PetscObject)snes->linesearch,prefix));
511035f5d045SPeter Brune   }
51115f80ce2aSJacob Faibussowitsch   CHKERRQ(KSPAppendOptionsPrefix(snes->ksp,prefix));
51123a40ed3dSBarry Smith   PetscFunctionReturn(0);
51133c7409f5SSatish Balay }
51143c7409f5SSatish Balay 
51159ab63eb5SSatish Balay /*@C
51163c7409f5SSatish Balay    SNESGetOptionsPrefix - Sets the prefix used for searching for all
51173c7409f5SSatish Balay    SNES options in the database.
51183c7409f5SSatish Balay 
5119c7afd0dbSLois Curfman McInnes    Not Collective
5120c7afd0dbSLois Curfman McInnes 
51213c7409f5SSatish Balay    Input Parameter:
51223c7409f5SSatish Balay .  snes - the SNES context
51233c7409f5SSatish Balay 
51243c7409f5SSatish Balay    Output Parameter:
51253c7409f5SSatish Balay .  prefix - pointer to the prefix string used
51263c7409f5SSatish Balay 
512795452b02SPatrick Sanan    Notes:
512895452b02SPatrick Sanan     On the fortran side, the user should pass in a string 'prefix' of
51299ab63eb5SSatish Balay    sufficient length to hold the prefix.
51309ab63eb5SSatish Balay 
513136851e7fSLois Curfman McInnes    Level: advanced
513236851e7fSLois Curfman McInnes 
5133a86d99e1SLois Curfman McInnes .seealso: SNESAppendOptionsPrefix()
51343c7409f5SSatish Balay @*/
51357087cfbeSBarry Smith PetscErrorCode  SNESGetOptionsPrefix(SNES snes,const char *prefix[])
51363c7409f5SSatish Balay {
51373a40ed3dSBarry Smith   PetscFunctionBegin;
51380700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
51395f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscObjectGetOptionsPrefix((PetscObject)snes,prefix));
51403a40ed3dSBarry Smith   PetscFunctionReturn(0);
51413c7409f5SSatish Balay }
51423c7409f5SSatish Balay 
51433cea93caSBarry Smith /*@C
51441c84c290SBarry Smith   SNESRegister - Adds a method to the nonlinear solver package.
51451c84c290SBarry Smith 
51461c84c290SBarry Smith    Not collective
51471c84c290SBarry Smith 
51481c84c290SBarry Smith    Input Parameters:
51491c84c290SBarry Smith +  name_solver - name of a new user-defined solver
51501c84c290SBarry Smith -  routine_create - routine to create method context
51511c84c290SBarry Smith 
51521c84c290SBarry Smith    Notes:
51531c84c290SBarry Smith    SNESRegister() may be called multiple times to add several user-defined solvers.
51541c84c290SBarry Smith 
51551c84c290SBarry Smith    Sample usage:
51561c84c290SBarry Smith .vb
5157bdf89e91SBarry Smith    SNESRegister("my_solver",MySolverCreate);
51581c84c290SBarry Smith .ve
51591c84c290SBarry Smith 
51601c84c290SBarry Smith    Then, your solver can be chosen with the procedural interface via
51611c84c290SBarry Smith $     SNESSetType(snes,"my_solver")
51621c84c290SBarry Smith    or at runtime via the option
51631c84c290SBarry Smith $     -snes_type my_solver
51641c84c290SBarry Smith 
51651c84c290SBarry Smith    Level: advanced
51661c84c290SBarry Smith 
51671c84c290SBarry Smith     Note: If your function is not being put into a shared library then use SNESRegister() instead
51681c84c290SBarry Smith 
51691c84c290SBarry Smith .seealso: SNESRegisterAll(), SNESRegisterDestroy()
51703cea93caSBarry Smith 
51717f6c08e0SMatthew Knepley   Level: advanced
51723cea93caSBarry Smith @*/
5173bdf89e91SBarry Smith PetscErrorCode  SNESRegister(const char sname[],PetscErrorCode (*function)(SNES))
5174b2002411SLois Curfman McInnes {
5175b2002411SLois Curfman McInnes   PetscFunctionBegin;
51765f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESInitializePackage());
51775f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscFunctionListAdd(&SNESList,sname,function));
5178b2002411SLois Curfman McInnes   PetscFunctionReturn(0);
5179b2002411SLois Curfman McInnes }
5180da9b6338SBarry Smith 
51817087cfbeSBarry Smith PetscErrorCode  SNESTestLocalMin(SNES snes)
5182da9b6338SBarry Smith {
518377431f27SBarry Smith   PetscInt       N,i,j;
5184da9b6338SBarry Smith   Vec            u,uh,fh;
5185da9b6338SBarry Smith   PetscScalar    value;
5186da9b6338SBarry Smith   PetscReal      norm;
5187da9b6338SBarry Smith 
5188da9b6338SBarry Smith   PetscFunctionBegin;
51895f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESGetSolution(snes,&u));
51905f80ce2aSJacob Faibussowitsch   CHKERRQ(VecDuplicate(u,&uh));
51915f80ce2aSJacob Faibussowitsch   CHKERRQ(VecDuplicate(u,&fh));
5192da9b6338SBarry Smith 
5193da9b6338SBarry Smith   /* currently only works for sequential */
51945f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscPrintf(PetscObjectComm((PetscObject)snes),"Testing FormFunction() for local min\n"));
51955f80ce2aSJacob Faibussowitsch   CHKERRQ(VecGetSize(u,&N));
5196da9b6338SBarry Smith   for (i=0; i<N; i++) {
51975f80ce2aSJacob Faibussowitsch     CHKERRQ(VecCopy(u,uh));
51985f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscPrintf(PetscObjectComm((PetscObject)snes),"i = %D\n",i));
5199da9b6338SBarry Smith     for (j=-10; j<11; j++) {
52008b49ba18SBarry Smith       value = PetscSign(j)*PetscExpReal(PetscAbs(j)-10.0);
52015f80ce2aSJacob Faibussowitsch       CHKERRQ(VecSetValue(uh,i,value,ADD_VALUES));
52025f80ce2aSJacob Faibussowitsch       CHKERRQ(SNESComputeFunction(snes,uh,fh));
52035f80ce2aSJacob Faibussowitsch       CHKERRQ(VecNorm(fh,NORM_2,&norm));
52045f80ce2aSJacob Faibussowitsch       CHKERRQ(PetscPrintf(PetscObjectComm((PetscObject)snes),"       j norm %D %18.16e\n",j,norm));
5205da9b6338SBarry Smith       value = -value;
52065f80ce2aSJacob Faibussowitsch       CHKERRQ(VecSetValue(uh,i,value,ADD_VALUES));
5207da9b6338SBarry Smith     }
5208da9b6338SBarry Smith   }
52095f80ce2aSJacob Faibussowitsch   CHKERRQ(VecDestroy(&uh));
52105f80ce2aSJacob Faibussowitsch   CHKERRQ(VecDestroy(&fh));
5211da9b6338SBarry Smith   PetscFunctionReturn(0);
5212da9b6338SBarry Smith }
521371f87433Sdalcinl 
521471f87433Sdalcinl /*@
5215fa9f3622SBarry Smith    SNESKSPSetUseEW - Sets SNES use Eisenstat-Walker method for
521671f87433Sdalcinl    computing relative tolerance for linear solvers within an inexact
521771f87433Sdalcinl    Newton method.
521871f87433Sdalcinl 
52193f9fe445SBarry Smith    Logically Collective on SNES
522071f87433Sdalcinl 
522171f87433Sdalcinl    Input Parameters:
522271f87433Sdalcinl +  snes - SNES context
522371f87433Sdalcinl -  flag - PETSC_TRUE or PETSC_FALSE
522471f87433Sdalcinl 
522564ba62caSBarry Smith     Options Database:
522664ba62caSBarry Smith +  -snes_ksp_ew - use Eisenstat-Walker method for determining linear system convergence
522764ba62caSBarry Smith .  -snes_ksp_ew_version ver - version of  Eisenstat-Walker method
522864ba62caSBarry Smith .  -snes_ksp_ew_rtol0 <rtol0> - Sets rtol0
522964ba62caSBarry Smith .  -snes_ksp_ew_rtolmax <rtolmax> - Sets rtolmax
523064ba62caSBarry Smith .  -snes_ksp_ew_gamma <gamma> - Sets gamma
523164ba62caSBarry Smith .  -snes_ksp_ew_alpha <alpha> - Sets alpha
523264ba62caSBarry Smith .  -snes_ksp_ew_alpha2 <alpha2> - Sets alpha2
523364ba62caSBarry Smith -  -snes_ksp_ew_threshold <threshold> - Sets threshold
523464ba62caSBarry Smith 
523571f87433Sdalcinl    Notes:
523671f87433Sdalcinl    Currently, the default is to use a constant relative tolerance for
523771f87433Sdalcinl    the inner linear solvers.  Alternatively, one can use the
523871f87433Sdalcinl    Eisenstat-Walker method, where the relative convergence tolerance
523971f87433Sdalcinl    is reset at each Newton iteration according progress of the nonlinear
524071f87433Sdalcinl    solver.
524171f87433Sdalcinl 
524271f87433Sdalcinl    Level: advanced
524371f87433Sdalcinl 
524471f87433Sdalcinl    Reference:
524571f87433Sdalcinl    S. C. Eisenstat and H. F. Walker, "Choosing the forcing terms in an
524671f87433Sdalcinl    inexact Newton method", SISC 17 (1), pp.16-32, 1996.
524771f87433Sdalcinl 
5248fa9f3622SBarry Smith .seealso: SNESKSPGetUseEW(), SNESKSPGetParametersEW(), SNESKSPSetParametersEW()
524971f87433Sdalcinl @*/
52507087cfbeSBarry Smith PetscErrorCode  SNESKSPSetUseEW(SNES snes,PetscBool flag)
525171f87433Sdalcinl {
525271f87433Sdalcinl   PetscFunctionBegin;
52530700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
5254acfcf0e5SJed Brown   PetscValidLogicalCollectiveBool(snes,flag,2);
525571f87433Sdalcinl   snes->ksp_ewconv = flag;
525671f87433Sdalcinl   PetscFunctionReturn(0);
525771f87433Sdalcinl }
525871f87433Sdalcinl 
525971f87433Sdalcinl /*@
5260fa9f3622SBarry Smith    SNESKSPGetUseEW - Gets if SNES is using Eisenstat-Walker method
526171f87433Sdalcinl    for computing relative tolerance for linear solvers within an
526271f87433Sdalcinl    inexact Newton method.
526371f87433Sdalcinl 
526471f87433Sdalcinl    Not Collective
526571f87433Sdalcinl 
526671f87433Sdalcinl    Input Parameter:
526771f87433Sdalcinl .  snes - SNES context
526871f87433Sdalcinl 
526971f87433Sdalcinl    Output Parameter:
527071f87433Sdalcinl .  flag - PETSC_TRUE or PETSC_FALSE
527171f87433Sdalcinl 
527271f87433Sdalcinl    Notes:
527371f87433Sdalcinl    Currently, the default is to use a constant relative tolerance for
527471f87433Sdalcinl    the inner linear solvers.  Alternatively, one can use the
527571f87433Sdalcinl    Eisenstat-Walker method, where the relative convergence tolerance
527671f87433Sdalcinl    is reset at each Newton iteration according progress of the nonlinear
527771f87433Sdalcinl    solver.
527871f87433Sdalcinl 
527971f87433Sdalcinl    Level: advanced
528071f87433Sdalcinl 
528171f87433Sdalcinl    Reference:
528271f87433Sdalcinl    S. C. Eisenstat and H. F. Walker, "Choosing the forcing terms in an
528371f87433Sdalcinl    inexact Newton method", SISC 17 (1), pp.16-32, 1996.
528471f87433Sdalcinl 
5285fa9f3622SBarry Smith .seealso: SNESKSPSetUseEW(), SNESKSPGetParametersEW(), SNESKSPSetParametersEW()
528671f87433Sdalcinl @*/
52877087cfbeSBarry Smith PetscErrorCode  SNESKSPGetUseEW(SNES snes, PetscBool  *flag)
528871f87433Sdalcinl {
528971f87433Sdalcinl   PetscFunctionBegin;
52900700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
5291534a8f05SLisandro Dalcin   PetscValidBoolPointer(flag,2);
529271f87433Sdalcinl   *flag = snes->ksp_ewconv;
529371f87433Sdalcinl   PetscFunctionReturn(0);
529471f87433Sdalcinl }
529571f87433Sdalcinl 
529671f87433Sdalcinl /*@
5297fa9f3622SBarry Smith    SNESKSPSetParametersEW - Sets parameters for Eisenstat-Walker
529871f87433Sdalcinl    convergence criteria for the linear solvers within an inexact
529971f87433Sdalcinl    Newton method.
530071f87433Sdalcinl 
53013f9fe445SBarry Smith    Logically Collective on SNES
530271f87433Sdalcinl 
530371f87433Sdalcinl    Input Parameters:
530471f87433Sdalcinl +    snes - SNES context
530571f87433Sdalcinl .    version - version 1, 2 (default is 2) or 3
530671f87433Sdalcinl .    rtol_0 - initial relative tolerance (0 <= rtol_0 < 1)
530771f87433Sdalcinl .    rtol_max - maximum relative tolerance (0 <= rtol_max < 1)
530871f87433Sdalcinl .    gamma - multiplicative factor for version 2 rtol computation
530971f87433Sdalcinl              (0 <= gamma2 <= 1)
531071f87433Sdalcinl .    alpha - power for version 2 rtol computation (1 < alpha <= 2)
531171f87433Sdalcinl .    alpha2 - power for safeguard
531271f87433Sdalcinl -    threshold - threshold for imposing safeguard (0 < threshold < 1)
531371f87433Sdalcinl 
531471f87433Sdalcinl    Note:
531571f87433Sdalcinl    Version 3 was contributed by Luis Chacon, June 2006.
531671f87433Sdalcinl 
531771f87433Sdalcinl    Use PETSC_DEFAULT to retain the default for any of the parameters.
531871f87433Sdalcinl 
531971f87433Sdalcinl    Level: advanced
532071f87433Sdalcinl 
532171f87433Sdalcinl    Reference:
532271f87433Sdalcinl    S. C. Eisenstat and H. F. Walker, "Choosing the forcing terms in an
532371f87433Sdalcinl    inexact Newton method", Utah State University Math. Stat. Dept. Res.
532471f87433Sdalcinl    Report 6/94/75, June, 1994, to appear in SIAM J. Sci. Comput.
532571f87433Sdalcinl 
5326fa9f3622SBarry Smith .seealso: SNESKSPSetUseEW(), SNESKSPGetUseEW(), SNESKSPGetParametersEW()
532771f87433Sdalcinl @*/
5328f5af7f23SKarl Rupp PetscErrorCode  SNESKSPSetParametersEW(SNES snes,PetscInt version,PetscReal rtol_0,PetscReal rtol_max,PetscReal gamma,PetscReal alpha,PetscReal alpha2,PetscReal threshold)
532971f87433Sdalcinl {
5330fa9f3622SBarry Smith   SNESKSPEW *kctx;
53315fd66863SKarl Rupp 
533271f87433Sdalcinl   PetscFunctionBegin;
53330700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
5334fa9f3622SBarry Smith   kctx = (SNESKSPEW*)snes->kspconvctx;
53355f80ce2aSJacob Faibussowitsch   PetscCheck(kctx,PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"No Eisenstat-Walker context existing");
5336c5eb9154SBarry Smith   PetscValidLogicalCollectiveInt(snes,version,2);
5337c5eb9154SBarry Smith   PetscValidLogicalCollectiveReal(snes,rtol_0,3);
5338c5eb9154SBarry Smith   PetscValidLogicalCollectiveReal(snes,rtol_max,4);
5339c5eb9154SBarry Smith   PetscValidLogicalCollectiveReal(snes,gamma,5);
5340c5eb9154SBarry Smith   PetscValidLogicalCollectiveReal(snes,alpha,6);
5341c5eb9154SBarry Smith   PetscValidLogicalCollectiveReal(snes,alpha2,7);
5342c5eb9154SBarry Smith   PetscValidLogicalCollectiveReal(snes,threshold,8);
534371f87433Sdalcinl 
534471f87433Sdalcinl   if (version != PETSC_DEFAULT)   kctx->version   = version;
534571f87433Sdalcinl   if (rtol_0 != PETSC_DEFAULT)    kctx->rtol_0    = rtol_0;
534671f87433Sdalcinl   if (rtol_max != PETSC_DEFAULT)  kctx->rtol_max  = rtol_max;
534771f87433Sdalcinl   if (gamma != PETSC_DEFAULT)     kctx->gamma     = gamma;
534871f87433Sdalcinl   if (alpha != PETSC_DEFAULT)     kctx->alpha     = alpha;
534971f87433Sdalcinl   if (alpha2 != PETSC_DEFAULT)    kctx->alpha2    = alpha2;
535071f87433Sdalcinl   if (threshold != PETSC_DEFAULT) kctx->threshold = threshold;
535171f87433Sdalcinl 
53525f80ce2aSJacob Faibussowitsch   PetscCheck(kctx->version >= 1 && kctx->version <= 3,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Only versions 1, 2 and 3 are supported: %D",kctx->version);
53532c71b3e2SJacob Faibussowitsch   PetscCheckFalse(kctx->rtol_0 < 0.0 || kctx->rtol_0 >= 1.0,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"0.0 <= rtol_0 < 1.0: %g",(double)kctx->rtol_0);
53542c71b3e2SJacob Faibussowitsch   PetscCheckFalse(kctx->rtol_max < 0.0 || kctx->rtol_max >= 1.0,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"0.0 <= rtol_max (%g) < 1.0",(double)kctx->rtol_max);
53552c71b3e2SJacob Faibussowitsch   PetscCheckFalse(kctx->gamma < 0.0 || kctx->gamma > 1.0,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"0.0 <= gamma (%g) <= 1.0",(double)kctx->gamma);
53562c71b3e2SJacob Faibussowitsch   PetscCheckFalse(kctx->alpha <= 1.0 || kctx->alpha > 2.0,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"1.0 < alpha (%g) <= 2.0",(double)kctx->alpha);
53572c71b3e2SJacob Faibussowitsch   PetscCheckFalse(kctx->threshold <= 0.0 || kctx->threshold >= 1.0,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"0.0 < threshold (%g) < 1.0",(double)kctx->threshold);
535871f87433Sdalcinl   PetscFunctionReturn(0);
535971f87433Sdalcinl }
536071f87433Sdalcinl 
536171f87433Sdalcinl /*@
5362fa9f3622SBarry Smith    SNESKSPGetParametersEW - Gets parameters for Eisenstat-Walker
536371f87433Sdalcinl    convergence criteria for the linear solvers within an inexact
536471f87433Sdalcinl    Newton method.
536571f87433Sdalcinl 
536671f87433Sdalcinl    Not Collective
536771f87433Sdalcinl 
536897bb3fdcSJose E. Roman    Input Parameter:
53696b867d5aSJose E. Roman .    snes - SNES context
537071f87433Sdalcinl 
537171f87433Sdalcinl    Output Parameters:
537271f87433Sdalcinl +    version - version 1, 2 (default is 2) or 3
537371f87433Sdalcinl .    rtol_0 - initial relative tolerance (0 <= rtol_0 < 1)
537471f87433Sdalcinl .    rtol_max - maximum relative tolerance (0 <= rtol_max < 1)
5375bf388a1fSBarry Smith .    gamma - multiplicative factor for version 2 rtol computation (0 <= gamma2 <= 1)
537671f87433Sdalcinl .    alpha - power for version 2 rtol computation (1 < alpha <= 2)
537771f87433Sdalcinl .    alpha2 - power for safeguard
537871f87433Sdalcinl -    threshold - threshold for imposing safeguard (0 < threshold < 1)
537971f87433Sdalcinl 
538071f87433Sdalcinl    Level: advanced
538171f87433Sdalcinl 
5382fa9f3622SBarry Smith .seealso: SNESKSPSetUseEW(), SNESKSPGetUseEW(), SNESKSPSetParametersEW()
538371f87433Sdalcinl @*/
5384bf388a1fSBarry Smith PetscErrorCode  SNESKSPGetParametersEW(SNES snes,PetscInt *version,PetscReal *rtol_0,PetscReal *rtol_max,PetscReal *gamma,PetscReal *alpha,PetscReal *alpha2,PetscReal *threshold)
538571f87433Sdalcinl {
5386fa9f3622SBarry Smith   SNESKSPEW *kctx;
53875fd66863SKarl Rupp 
538871f87433Sdalcinl   PetscFunctionBegin;
53890700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
5390fa9f3622SBarry Smith   kctx = (SNESKSPEW*)snes->kspconvctx;
53915f80ce2aSJacob Faibussowitsch   PetscCheck(kctx,PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"No Eisenstat-Walker context existing");
539271f87433Sdalcinl   if (version)   *version   = kctx->version;
539371f87433Sdalcinl   if (rtol_0)    *rtol_0    = kctx->rtol_0;
539471f87433Sdalcinl   if (rtol_max)  *rtol_max  = kctx->rtol_max;
539571f87433Sdalcinl   if (gamma)     *gamma     = kctx->gamma;
539671f87433Sdalcinl   if (alpha)     *alpha     = kctx->alpha;
539771f87433Sdalcinl   if (alpha2)    *alpha2    = kctx->alpha2;
539871f87433Sdalcinl   if (threshold) *threshold = kctx->threshold;
539971f87433Sdalcinl   PetscFunctionReturn(0);
540071f87433Sdalcinl }
540171f87433Sdalcinl 
5402d5378b5fSDmitry Karpeev  PetscErrorCode KSPPreSolve_SNESEW(KSP ksp, Vec b, Vec x, SNES snes)
540371f87433Sdalcinl {
5404fa9f3622SBarry Smith   SNESKSPEW      *kctx = (SNESKSPEW*)snes->kspconvctx;
540571f87433Sdalcinl   PetscReal      rtol  = PETSC_DEFAULT,stol;
540671f87433Sdalcinl 
540771f87433Sdalcinl   PetscFunctionBegin;
5408d4211eb9SBarry Smith   if (!snes->ksp_ewconv) PetscFunctionReturn(0);
540930058271SDmitry Karpeev   if (!snes->iter) {
541030058271SDmitry Karpeev     rtol = kctx->rtol_0; /* first time in, so use the original user rtol */
54115f80ce2aSJacob Faibussowitsch     CHKERRQ(VecNorm(snes->vec_func,NORM_2,&kctx->norm_first));
541230058271SDmitry Karpeev   }
5413f5af7f23SKarl Rupp   else {
541471f87433Sdalcinl     if (kctx->version == 1) {
541571f87433Sdalcinl       rtol = (snes->norm - kctx->lresid_last)/kctx->norm_last;
541671f87433Sdalcinl       if (rtol < 0.0) rtol = -rtol;
541785ec1a3cSBarry Smith       stol = PetscPowReal(kctx->rtol_last,kctx->alpha2);
541871f87433Sdalcinl       if (stol > kctx->threshold) rtol = PetscMax(rtol,stol);
541971f87433Sdalcinl     } else if (kctx->version == 2) {
542085ec1a3cSBarry Smith       rtol = kctx->gamma * PetscPowReal(snes->norm/kctx->norm_last,kctx->alpha);
542185ec1a3cSBarry Smith       stol = kctx->gamma * PetscPowReal(kctx->rtol_last,kctx->alpha);
542271f87433Sdalcinl       if (stol > kctx->threshold) rtol = PetscMax(rtol,stol);
542371f87433Sdalcinl     } else if (kctx->version == 3) { /* contributed by Luis Chacon, June 2006. */
542485ec1a3cSBarry Smith       rtol = kctx->gamma * PetscPowReal(snes->norm/kctx->norm_last,kctx->alpha);
542571f87433Sdalcinl       /* safeguard: avoid sharp decrease of rtol */
542685ec1a3cSBarry Smith       stol = kctx->gamma*PetscPowReal(kctx->rtol_last,kctx->alpha);
542771f87433Sdalcinl       stol = PetscMax(rtol,stol);
542871f87433Sdalcinl       rtol = PetscMin(kctx->rtol_0,stol);
542971f87433Sdalcinl       /* safeguard: avoid oversolving */
543030058271SDmitry Karpeev       stol = kctx->gamma*(kctx->norm_first*snes->rtol)/snes->norm;
543171f87433Sdalcinl       stol = PetscMax(rtol,stol);
543271f87433Sdalcinl       rtol = PetscMin(kctx->rtol_0,stol);
543398921bdaSJacob Faibussowitsch     } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Only versions 1, 2 or 3 are supported: %D",kctx->version);
543471f87433Sdalcinl   }
543571f87433Sdalcinl   /* safeguard: avoid rtol greater than one */
543671f87433Sdalcinl   rtol = PetscMin(rtol,kctx->rtol_max);
54375f80ce2aSJacob Faibussowitsch   CHKERRQ(KSPSetTolerances(ksp,rtol,PETSC_DEFAULT,PETSC_DEFAULT,PETSC_DEFAULT));
54385f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscInfo(snes,"iter %D, Eisenstat-Walker (version %D) KSP rtol=%g\n",snes->iter,kctx->version,(double)rtol));
543971f87433Sdalcinl   PetscFunctionReturn(0);
544071f87433Sdalcinl }
544171f87433Sdalcinl 
5442d5378b5fSDmitry Karpeev PetscErrorCode KSPPostSolve_SNESEW(KSP ksp, Vec b, Vec x, SNES snes)
544371f87433Sdalcinl {
5444fa9f3622SBarry Smith   SNESKSPEW      *kctx = (SNESKSPEW*)snes->kspconvctx;
544571f87433Sdalcinl   PCSide         pcside;
544671f87433Sdalcinl   Vec            lres;
544771f87433Sdalcinl 
544871f87433Sdalcinl   PetscFunctionBegin;
5449d4211eb9SBarry Smith   if (!snes->ksp_ewconv) PetscFunctionReturn(0);
54505f80ce2aSJacob Faibussowitsch   CHKERRQ(KSPGetTolerances(ksp,&kctx->rtol_last,NULL,NULL,NULL));
545171dbe336SPeter Brune   kctx->norm_last = snes->norm;
545271f87433Sdalcinl   if (kctx->version == 1) {
54534f00ce20SMatthew G. Knepley     PC        pc;
54544f00ce20SMatthew G. Knepley     PetscBool isNone;
54554f00ce20SMatthew G. Knepley 
54565f80ce2aSJacob Faibussowitsch     CHKERRQ(KSPGetPC(ksp, &pc));
54575f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscObjectTypeCompare((PetscObject) pc, PCNONE, &isNone));
54585f80ce2aSJacob Faibussowitsch     CHKERRQ(KSPGetPCSide(ksp,&pcside));
54594f00ce20SMatthew G. Knepley      if (pcside == PC_RIGHT || isNone) { /* XXX Should we also test KSP_UNPRECONDITIONED_NORM ? */
546071f87433Sdalcinl       /* KSP residual is true linear residual */
54615f80ce2aSJacob Faibussowitsch       CHKERRQ(KSPGetResidualNorm(ksp,&kctx->lresid_last));
546271f87433Sdalcinl     } else {
546371f87433Sdalcinl       /* KSP residual is preconditioned residual */
546471f87433Sdalcinl       /* compute true linear residual norm */
54655f80ce2aSJacob Faibussowitsch       CHKERRQ(VecDuplicate(b,&lres));
54665f80ce2aSJacob Faibussowitsch       CHKERRQ(MatMult(snes->jacobian,x,lres));
54675f80ce2aSJacob Faibussowitsch       CHKERRQ(VecAYPX(lres,-1.0,b));
54685f80ce2aSJacob Faibussowitsch       CHKERRQ(VecNorm(lres,NORM_2,&kctx->lresid_last));
54695f80ce2aSJacob Faibussowitsch       CHKERRQ(VecDestroy(&lres));
547071f87433Sdalcinl     }
547171f87433Sdalcinl   }
547271f87433Sdalcinl   PetscFunctionReturn(0);
547371f87433Sdalcinl }
547471f87433Sdalcinl 
5475d4211eb9SBarry Smith /*@
5476d4211eb9SBarry Smith    SNESGetKSP - Returns the KSP context for a SNES solver.
5477d4211eb9SBarry Smith 
5478d4211eb9SBarry Smith    Not Collective, but if SNES object is parallel, then KSP object is parallel
5479d4211eb9SBarry Smith 
5480d4211eb9SBarry Smith    Input Parameter:
5481d4211eb9SBarry Smith .  snes - the SNES context
5482d4211eb9SBarry Smith 
5483d4211eb9SBarry Smith    Output Parameter:
5484d4211eb9SBarry Smith .  ksp - the KSP context
5485d4211eb9SBarry Smith 
5486d4211eb9SBarry Smith    Notes:
5487d4211eb9SBarry Smith    The user can then directly manipulate the KSP context to set various
5488d4211eb9SBarry Smith    options, etc.  Likewise, the user can then extract and manipulate the
5489d4211eb9SBarry Smith    PC contexts as well.
5490d4211eb9SBarry Smith 
5491d4211eb9SBarry Smith    Level: beginner
5492d4211eb9SBarry Smith 
5493d4211eb9SBarry Smith .seealso: KSPGetPC(), SNESCreate(), KSPCreate(), SNESSetKSP()
5494d4211eb9SBarry Smith @*/
5495d4211eb9SBarry Smith PetscErrorCode  SNESGetKSP(SNES snes,KSP *ksp)
549671f87433Sdalcinl {
549771f87433Sdalcinl   PetscFunctionBegin;
5498d4211eb9SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
5499d4211eb9SBarry Smith   PetscValidPointer(ksp,2);
5500d4211eb9SBarry Smith 
5501d4211eb9SBarry Smith   if (!snes->ksp) {
55025f80ce2aSJacob Faibussowitsch     CHKERRQ(KSPCreate(PetscObjectComm((PetscObject)snes),&snes->ksp));
55035f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscObjectIncrementTabLevel((PetscObject)snes->ksp,(PetscObject)snes,1));
55045f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->ksp));
5505d4211eb9SBarry Smith 
55065f80ce2aSJacob Faibussowitsch     CHKERRQ(KSPSetPreSolve(snes->ksp,(PetscErrorCode (*)(KSP,Vec,Vec,void*))KSPPreSolve_SNESEW,snes));
55075f80ce2aSJacob Faibussowitsch     CHKERRQ(KSPSetPostSolve(snes->ksp,(PetscErrorCode (*)(KSP,Vec,Vec,void*))KSPPostSolve_SNESEW,snes));
5508a5c2985bSBarry Smith 
55095f80ce2aSJacob Faibussowitsch     CHKERRQ(KSPMonitorSetFromOptions(snes->ksp, "-snes_monitor_ksp", "snes_preconditioned_residual", snes));
55105f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscObjectSetOptions((PetscObject)snes->ksp,((PetscObject)snes)->options));
5511d4211eb9SBarry Smith   }
5512d4211eb9SBarry Smith   *ksp = snes->ksp;
551371f87433Sdalcinl   PetscFunctionReturn(0);
551471f87433Sdalcinl }
55156c699258SBarry Smith 
5516af0996ceSBarry Smith #include <petsc/private/dmimpl.h>
55176c699258SBarry Smith /*@
55182a808120SBarry Smith    SNESSetDM - Sets the DM that may be used by some nonlinear solvers or their underlying preconditioners
55196c699258SBarry Smith 
55203f9fe445SBarry Smith    Logically Collective on SNES
55216c699258SBarry Smith 
55226c699258SBarry Smith    Input Parameters:
55232a808120SBarry Smith +  snes - the nonlinear solver context
55242a808120SBarry Smith -  dm - the dm, cannot be NULL
55256c699258SBarry Smith 
5526e03a659cSJed Brown    Notes:
5527e03a659cSJed Brown    A DM can only be used for solving one problem at a time because information about the problem is stored on the DM,
5528e03a659cSJed Brown    even when not using interfaces like DMSNESSetFunction().  Use DMClone() to get a distinct DM when solving different
5529e03a659cSJed Brown    problems using the same function space.
5530e03a659cSJed Brown 
55316c699258SBarry Smith    Level: intermediate
55326c699258SBarry Smith 
55334c2026ceSFande Kong .seealso: SNESGetDM(), KSPSetDM(), KSPGetDM()
55346c699258SBarry Smith @*/
55357087cfbeSBarry Smith PetscErrorCode  SNESSetDM(SNES snes,DM dm)
55366c699258SBarry Smith {
5537345fed2cSBarry Smith   KSP            ksp;
5538942e3340SBarry Smith   DMSNES         sdm;
55396c699258SBarry Smith 
55406c699258SBarry Smith   PetscFunctionBegin;
55410700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
55422a808120SBarry Smith   PetscValidHeaderSpecific(dm,DM_CLASSID,2);
55435f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscObjectReference((PetscObject)dm));
5544942e3340SBarry Smith   if (snes->dm) {               /* Move the DMSNES context over to the new DM unless the new DM already has one */
554551f4b3c7SToby Isaac     if (snes->dm->dmsnes && !dm->dmsnes) {
55465f80ce2aSJacob Faibussowitsch       CHKERRQ(DMCopyDMSNES(snes->dm,dm));
55475f80ce2aSJacob Faibussowitsch       CHKERRQ(DMGetDMSNES(snes->dm,&sdm));
5548f5af7f23SKarl Rupp       if (sdm->originaldm == snes->dm) sdm->originaldm = dm; /* Grant write privileges to the replacement DM */
55496cab3a1bSJed Brown     }
55505f80ce2aSJacob Faibussowitsch     CHKERRQ(DMCoarsenHookRemove(snes->dm,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,snes));
55515f80ce2aSJacob Faibussowitsch     CHKERRQ(DMDestroy(&snes->dm));
55526cab3a1bSJed Brown   }
55536c699258SBarry Smith   snes->dm     = dm;
5554116d1032SJed Brown   snes->dmAuto = PETSC_FALSE;
5555f5af7f23SKarl Rupp 
55565f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESGetKSP(snes,&ksp));
55575f80ce2aSJacob Faibussowitsch   CHKERRQ(KSPSetDM(ksp,dm));
55585f80ce2aSJacob Faibussowitsch   CHKERRQ(KSPSetDMActive(ksp,PETSC_FALSE));
5559efd4aadfSBarry Smith   if (snes->npc) {
55605f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESSetDM(snes->npc,snes->dm));
55615f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESSetNPCSide(snes,snes->npcside));
55622c155ee1SBarry Smith   }
55636c699258SBarry Smith   PetscFunctionReturn(0);
55646c699258SBarry Smith }
55656c699258SBarry Smith 
55666c699258SBarry Smith /*@
55676c699258SBarry Smith    SNESGetDM - Gets the DM that may be used by some preconditioners
55686c699258SBarry Smith 
55693f9fe445SBarry Smith    Not Collective but DM obtained is parallel on SNES
55706c699258SBarry Smith 
55716c699258SBarry Smith    Input Parameter:
55726c699258SBarry Smith . snes - the preconditioner context
55736c699258SBarry Smith 
55746c699258SBarry Smith    Output Parameter:
55756c699258SBarry Smith .  dm - the dm
55766c699258SBarry Smith 
55776c699258SBarry Smith    Level: intermediate
55786c699258SBarry Smith 
55794c2026ceSFande Kong .seealso: SNESSetDM(), KSPSetDM(), KSPGetDM()
55806c699258SBarry Smith @*/
55817087cfbeSBarry Smith PetscErrorCode  SNESGetDM(SNES snes,DM *dm)
55826c699258SBarry Smith {
55836c699258SBarry Smith   PetscFunctionBegin;
55840700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
55856cab3a1bSJed Brown   if (!snes->dm) {
55865f80ce2aSJacob Faibussowitsch     CHKERRQ(DMShellCreate(PetscObjectComm((PetscObject)snes),&snes->dm));
5587116d1032SJed Brown     snes->dmAuto = PETSC_TRUE;
55886cab3a1bSJed Brown   }
55896c699258SBarry Smith   *dm = snes->dm;
55906c699258SBarry Smith   PetscFunctionReturn(0);
55916c699258SBarry Smith }
55920807856dSBarry Smith 
559331823bd8SMatthew G Knepley /*@
5594be95d8f1SBarry Smith   SNESSetNPC - Sets the nonlinear preconditioner to be used.
559531823bd8SMatthew G Knepley 
559631823bd8SMatthew G Knepley   Collective on SNES
559731823bd8SMatthew G Knepley 
559831823bd8SMatthew G Knepley   Input Parameters:
559931823bd8SMatthew G Knepley + snes - iterative context obtained from SNESCreate()
560031823bd8SMatthew G Knepley - pc   - the preconditioner object
560131823bd8SMatthew G Knepley 
560231823bd8SMatthew G Knepley   Notes:
5603be95d8f1SBarry Smith   Use SNESGetNPC() to retrieve the preconditioner context (for example,
560431823bd8SMatthew G Knepley   to configure it using the API).
560531823bd8SMatthew G Knepley 
560631823bd8SMatthew G Knepley   Level: developer
560731823bd8SMatthew G Knepley 
56083ad1a0b9SPatrick Farrell .seealso: SNESGetNPC(), SNESHasNPC()
560931823bd8SMatthew G Knepley @*/
5610be95d8f1SBarry Smith PetscErrorCode SNESSetNPC(SNES snes, SNES pc)
561131823bd8SMatthew G Knepley {
561231823bd8SMatthew G Knepley   PetscFunctionBegin;
561331823bd8SMatthew G Knepley   PetscValidHeaderSpecific(snes, SNES_CLASSID, 1);
561431823bd8SMatthew G Knepley   PetscValidHeaderSpecific(pc, SNES_CLASSID, 2);
561531823bd8SMatthew G Knepley   PetscCheckSameComm(snes, 1, pc, 2);
56165f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscObjectReference((PetscObject) pc));
56175f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESDestroy(&snes->npc));
5618efd4aadfSBarry Smith   snes->npc = pc;
56195f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->npc));
562031823bd8SMatthew G Knepley   PetscFunctionReturn(0);
562131823bd8SMatthew G Knepley }
562231823bd8SMatthew G Knepley 
562331823bd8SMatthew G Knepley /*@
5624be95d8f1SBarry Smith   SNESGetNPC - Creates a nonlinear preconditioning solver (SNES) to be used to precondition the nonlinear solver.
562531823bd8SMatthew G Knepley 
5626951fe5abSBarry Smith   Not Collective; but any changes to the obtained SNES object must be applied collectively
562731823bd8SMatthew G Knepley 
562831823bd8SMatthew G Knepley   Input Parameter:
562931823bd8SMatthew G Knepley . snes - iterative context obtained from SNESCreate()
563031823bd8SMatthew G Knepley 
563131823bd8SMatthew G Knepley   Output Parameter:
563231823bd8SMatthew G Knepley . pc - preconditioner context
563331823bd8SMatthew G Knepley 
5634b5badacbSBarry Smith   Options Database:
5635b5badacbSBarry Smith . -npc_snes_type <type> - set the type of the SNES to use as the nonlinear preconditioner
5636b5badacbSBarry Smith 
563795452b02SPatrick Sanan   Notes:
5638b5badacbSBarry Smith     If a SNES was previously set with SNESSetNPC() then that SNES is returned, otherwise a new SNES object is created.
5639be95d8f1SBarry Smith 
5640951fe5abSBarry Smith     The (preconditioner) SNES returned automatically inherits the same nonlinear function and Jacobian supplied to the original
5641951fe5abSBarry Smith     SNES during SNESSetUp()
5642951fe5abSBarry Smith 
564331823bd8SMatthew G Knepley   Level: developer
564431823bd8SMatthew G Knepley 
5645951fe5abSBarry Smith .seealso: SNESSetNPC(), SNESHasNPC(), SNES, SNESCreate()
564631823bd8SMatthew G Knepley @*/
5647be95d8f1SBarry Smith PetscErrorCode SNESGetNPC(SNES snes, SNES *pc)
564831823bd8SMatthew G Knepley {
5649a64e098fSPeter Brune   const char     *optionsprefix;
565031823bd8SMatthew G Knepley 
565131823bd8SMatthew G Knepley   PetscFunctionBegin;
565231823bd8SMatthew G Knepley   PetscValidHeaderSpecific(snes, SNES_CLASSID, 1);
565331823bd8SMatthew G Knepley   PetscValidPointer(pc, 2);
5654efd4aadfSBarry Smith   if (!snes->npc) {
56555f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESCreate(PetscObjectComm((PetscObject)snes),&snes->npc));
56565f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscObjectIncrementTabLevel((PetscObject)snes->npc,(PetscObject)snes,1));
56575f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->npc));
56585f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESGetOptionsPrefix(snes,&optionsprefix));
56595f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESSetOptionsPrefix(snes->npc,optionsprefix));
56605f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESAppendOptionsPrefix(snes->npc,"npc_"));
56615f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESSetCountersReset(snes->npc,PETSC_FALSE));
566231823bd8SMatthew G Knepley   }
5663efd4aadfSBarry Smith   *pc = snes->npc;
566431823bd8SMatthew G Knepley   PetscFunctionReturn(0);
566531823bd8SMatthew G Knepley }
566631823bd8SMatthew G Knepley 
56673ad1a0b9SPatrick Farrell /*@
56683ad1a0b9SPatrick Farrell   SNESHasNPC - Returns whether a nonlinear preconditioner exists
56693ad1a0b9SPatrick Farrell 
56703ad1a0b9SPatrick Farrell   Not Collective
56713ad1a0b9SPatrick Farrell 
56723ad1a0b9SPatrick Farrell   Input Parameter:
56733ad1a0b9SPatrick Farrell . snes - iterative context obtained from SNESCreate()
56743ad1a0b9SPatrick Farrell 
56753ad1a0b9SPatrick Farrell   Output Parameter:
56763ad1a0b9SPatrick Farrell . has_npc - whether the SNES has an NPC or not
56773ad1a0b9SPatrick Farrell 
56783ad1a0b9SPatrick Farrell   Level: developer
56793ad1a0b9SPatrick Farrell 
56803ad1a0b9SPatrick Farrell .seealso: SNESSetNPC(), SNESGetNPC()
56813ad1a0b9SPatrick Farrell @*/
56823ad1a0b9SPatrick Farrell PetscErrorCode SNESHasNPC(SNES snes, PetscBool *has_npc)
56833ad1a0b9SPatrick Farrell {
56843ad1a0b9SPatrick Farrell   PetscFunctionBegin;
56853ad1a0b9SPatrick Farrell   PetscValidHeaderSpecific(snes, SNES_CLASSID, 1);
5686efd4aadfSBarry Smith   *has_npc = (PetscBool) (snes->npc ? PETSC_TRUE : PETSC_FALSE);
56873ad1a0b9SPatrick Farrell   PetscFunctionReturn(0);
56883ad1a0b9SPatrick Farrell }
56893ad1a0b9SPatrick Farrell 
5690c40d0f55SPeter Brune /*@
5691be95d8f1SBarry Smith     SNESSetNPCSide - Sets the preconditioning side.
5692c40d0f55SPeter Brune 
5693c40d0f55SPeter Brune     Logically Collective on SNES
5694c40d0f55SPeter Brune 
5695c40d0f55SPeter Brune     Input Parameter:
5696c40d0f55SPeter Brune .   snes - iterative context obtained from SNESCreate()
5697c40d0f55SPeter Brune 
5698c40d0f55SPeter Brune     Output Parameter:
5699c40d0f55SPeter Brune .   side - the preconditioning side, where side is one of
5700c40d0f55SPeter Brune .vb
57012d547940SBarry Smith       PC_LEFT - left preconditioning
57022d547940SBarry Smith       PC_RIGHT - right preconditioning (default for most nonlinear solvers)
5703c40d0f55SPeter Brune .ve
5704c40d0f55SPeter Brune 
5705c40d0f55SPeter Brune     Options Database Keys:
570667b8a455SSatish Balay .   -snes_npc_side <right,left> - nonlinear preconditioner side
5707c40d0f55SPeter Brune 
570895452b02SPatrick Sanan     Notes:
570995452b02SPatrick Sanan     SNESNRICHARDSON and SNESNCG only support left preconditioning.
57102d547940SBarry Smith 
5711c40d0f55SPeter Brune     Level: intermediate
5712c40d0f55SPeter Brune 
5713be95d8f1SBarry Smith .seealso: SNESGetNPCSide(), KSPSetPCSide()
5714c40d0f55SPeter Brune @*/
5715be95d8f1SBarry Smith PetscErrorCode  SNESSetNPCSide(SNES snes,PCSide side)
5716c40d0f55SPeter Brune {
5717c40d0f55SPeter Brune   PetscFunctionBegin;
5718c40d0f55SPeter Brune   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
5719c40d0f55SPeter Brune   PetscValidLogicalCollectiveEnum(snes,side,2);
5720b552625fSStefano Zampini   if (side == PC_SIDE_DEFAULT) side = PC_RIGHT;
572154c59aa7SJacob Faibussowitsch   PetscCheck((side == PC_LEFT) || (side == PC_RIGHT),PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_WRONG,"Only PC_LEFT and PC_RIGHT are supported");
5722efd4aadfSBarry Smith   snes->npcside = side;
5723c40d0f55SPeter Brune   PetscFunctionReturn(0);
5724c40d0f55SPeter Brune }
5725c40d0f55SPeter Brune 
5726c40d0f55SPeter Brune /*@
5727be95d8f1SBarry Smith     SNESGetNPCSide - Gets the preconditioning side.
5728c40d0f55SPeter Brune 
5729c40d0f55SPeter Brune     Not Collective
5730c40d0f55SPeter Brune 
5731c40d0f55SPeter Brune     Input Parameter:
5732c40d0f55SPeter Brune .   snes - iterative context obtained from SNESCreate()
5733c40d0f55SPeter Brune 
5734c40d0f55SPeter Brune     Output Parameter:
5735c40d0f55SPeter Brune .   side - the preconditioning side, where side is one of
5736c40d0f55SPeter Brune .vb
57372d547940SBarry Smith       PC_LEFT - left preconditioning
57382d547940SBarry Smith       PC_RIGHT - right preconditioning (default for most nonlinear solvers)
5739c40d0f55SPeter Brune .ve
5740c40d0f55SPeter Brune 
5741c40d0f55SPeter Brune     Level: intermediate
5742c40d0f55SPeter Brune 
5743be95d8f1SBarry Smith .seealso: SNESSetNPCSide(), KSPGetPCSide()
5744c40d0f55SPeter Brune @*/
5745be95d8f1SBarry Smith PetscErrorCode  SNESGetNPCSide(SNES snes,PCSide *side)
5746c40d0f55SPeter Brune {
5747c40d0f55SPeter Brune   PetscFunctionBegin;
5748c40d0f55SPeter Brune   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
5749c40d0f55SPeter Brune   PetscValidPointer(side,2);
5750efd4aadfSBarry Smith   *side = snes->npcside;
5751c40d0f55SPeter Brune   PetscFunctionReturn(0);
5752c40d0f55SPeter Brune }
5753c40d0f55SPeter Brune 
57549e764e56SPeter Brune /*@
57557601faf0SJed Brown   SNESSetLineSearch - Sets the linesearch on the SNES instance.
57569e764e56SPeter Brune 
57579e764e56SPeter Brune   Collective on SNES
57589e764e56SPeter Brune 
57599e764e56SPeter Brune   Input Parameters:
57609e764e56SPeter Brune + snes - iterative context obtained from SNESCreate()
57619e764e56SPeter Brune - linesearch   - the linesearch object
57629e764e56SPeter Brune 
57639e764e56SPeter Brune   Notes:
57647601faf0SJed Brown   Use SNESGetLineSearch() to retrieve the preconditioner context (for example,
57659e764e56SPeter Brune   to configure it using the API).
57669e764e56SPeter Brune 
57679e764e56SPeter Brune   Level: developer
57689e764e56SPeter Brune 
57697601faf0SJed Brown .seealso: SNESGetLineSearch()
57709e764e56SPeter Brune @*/
57717601faf0SJed Brown PetscErrorCode SNESSetLineSearch(SNES snes, SNESLineSearch linesearch)
57729e764e56SPeter Brune {
57739e764e56SPeter Brune   PetscFunctionBegin;
57749e764e56SPeter Brune   PetscValidHeaderSpecific(snes, SNES_CLASSID, 1);
5775f1c6b773SPeter Brune   PetscValidHeaderSpecific(linesearch, SNESLINESEARCH_CLASSID, 2);
57769e764e56SPeter Brune   PetscCheckSameComm(snes, 1, linesearch, 2);
57775f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscObjectReference((PetscObject) linesearch));
57785f80ce2aSJacob Faibussowitsch   CHKERRQ(SNESLineSearchDestroy(&snes->linesearch));
5779f5af7f23SKarl Rupp 
57809e764e56SPeter Brune   snes->linesearch = linesearch;
5781f5af7f23SKarl Rupp 
57825f80ce2aSJacob Faibussowitsch   CHKERRQ(PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->linesearch));
57839e764e56SPeter Brune   PetscFunctionReturn(0);
57849e764e56SPeter Brune }
57859e764e56SPeter Brune 
5786a34ceb2aSJed Brown /*@
57877601faf0SJed Brown   SNESGetLineSearch - Returns a pointer to the line search context set with SNESSetLineSearch()
57888141a3b9SPeter Brune   or creates a default line search instance associated with the SNES and returns it.
57899e764e56SPeter Brune 
57909e764e56SPeter Brune   Not Collective
57919e764e56SPeter Brune 
57929e764e56SPeter Brune   Input Parameter:
57939e764e56SPeter Brune . snes - iterative context obtained from SNESCreate()
57949e764e56SPeter Brune 
57959e764e56SPeter Brune   Output Parameter:
57969e764e56SPeter Brune . linesearch - linesearch context
57979e764e56SPeter Brune 
5798162e0bf5SPeter Brune   Level: beginner
57999e764e56SPeter Brune 
5800162e0bf5SPeter Brune .seealso: SNESSetLineSearch(), SNESLineSearchCreate()
58019e764e56SPeter Brune @*/
58027601faf0SJed Brown PetscErrorCode SNESGetLineSearch(SNES snes, SNESLineSearch *linesearch)
58039e764e56SPeter Brune {
58049e764e56SPeter Brune   const char     *optionsprefix;
58059e764e56SPeter Brune 
58069e764e56SPeter Brune   PetscFunctionBegin;
58079e764e56SPeter Brune   PetscValidHeaderSpecific(snes, SNES_CLASSID, 1);
58089e764e56SPeter Brune   PetscValidPointer(linesearch, 2);
58099e764e56SPeter Brune   if (!snes->linesearch) {
58105f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESGetOptionsPrefix(snes, &optionsprefix));
58115f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESLineSearchCreate(PetscObjectComm((PetscObject)snes), &snes->linesearch));
58125f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESLineSearchSetSNES(snes->linesearch, snes));
58135f80ce2aSJacob Faibussowitsch     CHKERRQ(SNESLineSearchAppendOptionsPrefix(snes->linesearch, optionsprefix));
58145f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscObjectIncrementTabLevel((PetscObject) snes->linesearch, (PetscObject) snes, 1));
58155f80ce2aSJacob Faibussowitsch     CHKERRQ(PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->linesearch));
58169e764e56SPeter Brune   }
58179e764e56SPeter Brune   *linesearch = snes->linesearch;
58189e764e56SPeter Brune   PetscFunctionReturn(0);
58199e764e56SPeter Brune }
5820