xref: /petsc/src/snes/interface/snes.c (revision 792fecdfe9134cce4d631112660ddd34f063bc17)
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 
33db781477SPatrick Sanan .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 
57db781477SPatrick Sanan .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 
79db781477SPatrick Sanan .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 
102db781477SPatrick Sanan .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
114f0b84518SBarry Smith      in the functions domain. For example, a step with 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 
123f0b84518SBarry Smith    Note:
124f0b84518SBarry Smith    You can direct `SNES` to avoid certain steps by using `SNESVISetVariableBounds()`, `SNESVISetComputeVariableBounds()` or
125f0b84518SBarry Smith    `SNESLineSearchSetPreCheck()`, `SNESLineSearchSetPostCheck()`
126f0b84518SBarry Smith 
127f0b84518SBarry Smith .seealso: `SNESCreate()`, `SNESSetFunction()`, `SNESFunction`, `SNESSetJacobianDomainError()`, `SNESVISetVariableBounds()`,
128f0b84518SBarry Smith           `SNESVISetComputeVariableBounds()`, `SNESLineSearchSetPreCheck()`, `SNESLineSearchSetPostCheck()`
1294936397dSBarry Smith @*/
1307087cfbeSBarry Smith PetscErrorCode  SNESSetFunctionDomainError(SNES snes)
1314936397dSBarry Smith {
1324936397dSBarry Smith   PetscFunctionBegin;
1330700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
1345f80ce2aSJacob Faibussowitsch   PetscCheck(!snes->errorifnotconverged,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"User code indicates input vector is not in the function domain");
1354936397dSBarry Smith   snes->domainerror = PETSC_TRUE;
1364936397dSBarry Smith   PetscFunctionReturn(0);
1374936397dSBarry Smith }
1384936397dSBarry Smith 
1396a388c36SPeter Brune /*@
140f0b84518SBarry Smith    SNESSetJacobianDomainError - tells SNES that computeJacobian does not make sense at the proposed step. For example there is a negative element transformation.
14107b62357SFande Kong 
14207b62357SFande Kong    Logically Collective on SNES
14307b62357SFande Kong 
14407b62357SFande Kong    Input Parameters:
14507b62357SFande Kong .  snes - the SNES context
14607b62357SFande Kong 
14707b62357SFande Kong    Level: advanced
14807b62357SFande Kong 
149f0b84518SBarry Smith    Note:
150f0b84518SBarry Smith    You can direct `SNES` to avoid certain steps by using `SNESVISetVariableBounds()`, `SNESVISetComputeVariableBounds()` or
151f0b84518SBarry Smith    `SNESLineSearchSetPreCheck()`, `SNESLineSearchSetPostCheck()`
152f0b84518SBarry Smith 
153f0b84518SBarry Smith .seealso: `SNESCreate()`, `SNESSetFunction()`, `SNESFunction()`, `SNESSetFunctionDomainError()`, `SNESVISetVariableBounds()`,
154f0b84518SBarry Smith           `SNESVISetComputeVariableBounds()`, `SNESLineSearchSetPreCheck()`, `SNESLineSearchSetPostCheck()`
15507b62357SFande Kong @*/
15607b62357SFande Kong PetscErrorCode SNESSetJacobianDomainError(SNES snes)
15707b62357SFande Kong {
15807b62357SFande Kong   PetscFunctionBegin;
15907b62357SFande Kong   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
1605f80ce2aSJacob Faibussowitsch   PetscCheck(!snes->errorifnotconverged,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"User code indicates computeJacobian does not make sense");
16107b62357SFande Kong   snes->jacobiandomainerror = PETSC_TRUE;
16207b62357SFande Kong   PetscFunctionReturn(0);
16307b62357SFande Kong }
16407b62357SFande Kong 
16507b62357SFande Kong /*@
166b351a90bSFande Kong    SNESSetCheckJacobianDomainError - if or not to check jacobian domain error after each Jacobian evaluation. By default, we check Jacobian domain error
167b351a90bSFande Kong    in the debug mode, and do not check it in the optimized mode.
168b351a90bSFande Kong 
169b351a90bSFande Kong    Logically Collective on SNES
170b351a90bSFande Kong 
171b351a90bSFande Kong    Input Parameters:
172a2b725a8SWilliam Gropp +  snes - the SNES context
173a2b725a8SWilliam Gropp -  flg  - indicates if or not to check jacobian domain error after each Jacobian evaluation
174b351a90bSFande Kong 
175b351a90bSFande Kong    Level: advanced
176b351a90bSFande Kong 
177db781477SPatrick Sanan .seealso: `SNESCreate()`, `SNESSetFunction()`, `SNESFunction()`, `SNESSetFunctionDomainError()`, `SNESGetCheckJacobianDomainError()`
178b351a90bSFande Kong @*/
179b351a90bSFande Kong PetscErrorCode SNESSetCheckJacobianDomainError(SNES snes, PetscBool flg)
180b351a90bSFande Kong {
181b351a90bSFande Kong   PetscFunctionBegin;
182b351a90bSFande Kong   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
183b351a90bSFande Kong   snes->checkjacdomainerror = flg;
184b351a90bSFande Kong   PetscFunctionReturn(0);
185b351a90bSFande Kong }
186b351a90bSFande Kong 
187b351a90bSFande Kong /*@
1888383d7d7SFande Kong    SNESGetCheckJacobianDomainError - Get an indicator whether or not we are checking Jacobian domain errors after each Jacobian evaluation.
1898383d7d7SFande Kong 
1908383d7d7SFande Kong    Logically Collective on SNES
1918383d7d7SFande Kong 
1928383d7d7SFande Kong    Input Parameters:
1938383d7d7SFande Kong .  snes - the SNES context
1948383d7d7SFande Kong 
1958383d7d7SFande Kong    Output Parameters:
1968383d7d7SFande Kong .  flg  - PETSC_FALSE indicates that we don't check jacobian domain errors after each Jacobian evaluation
1978383d7d7SFande Kong 
1988383d7d7SFande Kong    Level: advanced
1998383d7d7SFande Kong 
200db781477SPatrick Sanan .seealso: `SNESCreate()`, `SNESSetFunction()`, `SNESFunction()`, `SNESSetFunctionDomainError()`, `SNESSetCheckJacobianDomainError()`
2018383d7d7SFande Kong @*/
2028383d7d7SFande Kong PetscErrorCode SNESGetCheckJacobianDomainError(SNES snes, PetscBool *flg)
2038383d7d7SFande Kong {
2048383d7d7SFande Kong   PetscFunctionBegin;
2058383d7d7SFande Kong   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
206534a8f05SLisandro Dalcin   PetscValidBoolPointer(flg,2);
2078383d7d7SFande Kong   *flg = snes->checkjacdomainerror;
2088383d7d7SFande Kong   PetscFunctionReturn(0);
2098383d7d7SFande Kong }
2108383d7d7SFande Kong 
2118383d7d7SFande Kong /*@
212c77b2880SPeter Brune    SNESGetFunctionDomainError - Gets the status of the domain error after a call to SNESComputeFunction;
2136a388c36SPeter Brune 
2146a388c36SPeter Brune    Logically Collective on SNES
2156a388c36SPeter Brune 
2166a388c36SPeter Brune    Input Parameters:
2176a388c36SPeter Brune .  snes - the SNES context
2186a388c36SPeter Brune 
2196a388c36SPeter Brune    Output Parameters:
220bf388a1fSBarry Smith .  domainerror - Set to PETSC_TRUE if there's a domain error; PETSC_FALSE otherwise.
2216a388c36SPeter Brune 
2226a388c36SPeter Brune    Level: advanced
2236a388c36SPeter Brune 
224db781477SPatrick Sanan .seealso: `SNESSetFunctionDomainError()`, `SNESComputeFunction()`
2256a388c36SPeter Brune @*/
2266a388c36SPeter Brune PetscErrorCode  SNESGetFunctionDomainError(SNES snes, PetscBool *domainerror)
2276a388c36SPeter Brune {
2286a388c36SPeter Brune   PetscFunctionBegin;
2296a388c36SPeter Brune   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
230534a8f05SLisandro Dalcin   PetscValidBoolPointer(domainerror,2);
2316a388c36SPeter Brune   *domainerror = snes->domainerror;
2326a388c36SPeter Brune   PetscFunctionReturn(0);
2336a388c36SPeter Brune }
2346a388c36SPeter Brune 
23507b62357SFande Kong /*@
23607b62357SFande Kong    SNESGetJacobianDomainError - Gets the status of the Jacobian domain error after a call to SNESComputeJacobian;
23707b62357SFande Kong 
23807b62357SFande Kong    Logically Collective on SNES
23907b62357SFande Kong 
24007b62357SFande Kong    Input Parameters:
24107b62357SFande Kong .  snes - the SNES context
24207b62357SFande Kong 
24307b62357SFande Kong    Output Parameters:
24407b62357SFande Kong .  domainerror - Set to PETSC_TRUE if there's a jacobian domain error; PETSC_FALSE otherwise.
24507b62357SFande Kong 
24607b62357SFande Kong    Level: advanced
24707b62357SFande Kong 
248c2e3fba1SPatrick Sanan .seealso: `SNESSetFunctionDomainError()`, `SNESComputeFunction()`, `SNESGetFunctionDomainError()`
24907b62357SFande Kong @*/
25007b62357SFande Kong PetscErrorCode SNESGetJacobianDomainError(SNES snes, PetscBool *domainerror)
25107b62357SFande Kong {
25207b62357SFande Kong   PetscFunctionBegin;
25307b62357SFande Kong   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
254534a8f05SLisandro Dalcin   PetscValidBoolPointer(domainerror,2);
25507b62357SFande Kong   *domainerror = snes->jacobiandomainerror;
25607b62357SFande Kong   PetscFunctionReturn(0);
25707b62357SFande Kong }
25807b62357SFande Kong 
25955849f57SBarry Smith /*@C
26055849f57SBarry Smith   SNESLoad - Loads a SNES that has been stored in binary  with SNESView().
26155849f57SBarry Smith 
26255849f57SBarry Smith   Collective on PetscViewer
26355849f57SBarry Smith 
26455849f57SBarry Smith   Input Parameters:
26555849f57SBarry Smith + newdm - the newly loaded SNES, this needs to have been created with SNESCreate() or
26655849f57SBarry Smith            some related function before a call to SNESLoad().
26755849f57SBarry Smith - viewer - binary file viewer, obtained from PetscViewerBinaryOpen()
26855849f57SBarry Smith 
26955849f57SBarry Smith    Level: intermediate
27055849f57SBarry Smith 
27155849f57SBarry Smith   Notes:
27255849f57SBarry Smith    The type is determined by the data in the file, any type set into the SNES before this call is ignored.
27355849f57SBarry Smith 
27455849f57SBarry Smith   Notes for advanced users:
27555849f57SBarry Smith   Most users should not need to know the details of the binary storage
27655849f57SBarry Smith   format, since SNESLoad() and TSView() completely hide these details.
27755849f57SBarry Smith   But for anyone who's interested, the standard binary matrix storage
27855849f57SBarry Smith   format is
27955849f57SBarry Smith .vb
28055849f57SBarry Smith      has not yet been determined
28155849f57SBarry Smith .ve
28255849f57SBarry Smith 
283db781477SPatrick Sanan .seealso: `PetscViewerBinaryOpen()`, `SNESView()`, `MatLoad()`, `VecLoad()`
28455849f57SBarry Smith @*/
2852d53ad75SBarry Smith PetscErrorCode  SNESLoad(SNES snes, PetscViewer viewer)
28655849f57SBarry Smith {
28755849f57SBarry Smith   PetscBool      isbinary;
288060da220SMatthew G. Knepley   PetscInt       classid;
28955849f57SBarry Smith   char           type[256];
29055849f57SBarry Smith   KSP            ksp;
2912d53ad75SBarry Smith   DM             dm;
2922d53ad75SBarry Smith   DMSNES         dmsnes;
29355849f57SBarry Smith 
29455849f57SBarry Smith   PetscFunctionBegin;
2952d53ad75SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
29655849f57SBarry Smith   PetscValidHeaderSpecific(viewer,PETSC_VIEWER_CLASSID,2);
2979566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary));
2985f80ce2aSJacob Faibussowitsch   PetscCheck(isbinary,PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Invalid viewer; open viewer with PetscViewerBinaryOpen()");
29955849f57SBarry Smith 
3009566063dSJacob Faibussowitsch   PetscCall(PetscViewerBinaryRead(viewer,&classid,1,NULL,PETSC_INT));
3015f80ce2aSJacob Faibussowitsch   PetscCheck(classid == SNES_FILE_CLASSID,PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_WRONG,"Not SNES next in file");
3029566063dSJacob Faibussowitsch   PetscCall(PetscViewerBinaryRead(viewer,type,256,NULL,PETSC_CHAR));
3039566063dSJacob Faibussowitsch   PetscCall(SNESSetType(snes, type));
3041baa6e33SBarry Smith   if (snes->ops->load) PetscCall((*snes->ops->load)(snes,viewer));
3059566063dSJacob Faibussowitsch   PetscCall(SNESGetDM(snes,&dm));
3069566063dSJacob Faibussowitsch   PetscCall(DMGetDMSNES(dm,&dmsnes));
3079566063dSJacob Faibussowitsch   PetscCall(DMSNESLoad(dmsnes,viewer));
3089566063dSJacob Faibussowitsch   PetscCall(SNESGetKSP(snes,&ksp));
3099566063dSJacob Faibussowitsch   PetscCall(KSPLoad(ksp,viewer));
31055849f57SBarry Smith   PetscFunctionReturn(0);
31155849f57SBarry Smith }
3126a388c36SPeter Brune 
3139804daf3SBarry Smith #include <petscdraw.h>
314e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
315e04113cfSBarry Smith #include <petscviewersaws.h>
316bfb97211SBarry Smith #endif
3178404b7f3SBarry Smith 
318fe2efc57SMark /*@C
319fe2efc57SMark    SNESViewFromOptions - View from Options
320fe2efc57SMark 
321fe2efc57SMark    Collective on SNES
322fe2efc57SMark 
323fe2efc57SMark    Input Parameters:
324fe2efc57SMark +  A - the application ordering context
325736c3998SJose E. Roman .  obj - Optional object
326736c3998SJose E. Roman -  name - command line option
327fe2efc57SMark 
328fe2efc57SMark    Level: intermediate
329db781477SPatrick Sanan .seealso: `SNES`, `SNESView`, `PetscObjectViewFromOptions()`, `SNESCreate()`
330fe2efc57SMark @*/
331fe2efc57SMark PetscErrorCode  SNESViewFromOptions(SNES A,PetscObject obj,const char name[])
332fe2efc57SMark {
333fe2efc57SMark   PetscFunctionBegin;
334fe2efc57SMark   PetscValidHeaderSpecific(A,SNES_CLASSID,1);
3359566063dSJacob Faibussowitsch   PetscCall(PetscObjectViewFromOptions((PetscObject)A,obj,name));
336fe2efc57SMark   PetscFunctionReturn(0);
337fe2efc57SMark }
338fe2efc57SMark 
339789d8953SBarry Smith PETSC_EXTERN PetscErrorCode SNESComputeJacobian_DMDA(SNES,Vec,Mat,Mat,void*);
340789d8953SBarry Smith 
3417e2c5f70SBarry Smith /*@C
3429b94acceSBarry Smith    SNESView - Prints the SNES data structure.
3439b94acceSBarry Smith 
3444c49b128SBarry Smith    Collective on SNES
345fee21e36SBarry Smith 
346c7afd0dbSLois Curfman McInnes    Input Parameters:
347c7afd0dbSLois Curfman McInnes +  SNES - the SNES context
348c7afd0dbSLois Curfman McInnes -  viewer - visualization context
349c7afd0dbSLois Curfman McInnes 
3509b94acceSBarry Smith    Options Database Key:
351c8a8ba5cSLois Curfman McInnes .  -snes_view - Calls SNESView() at end of SNESSolve()
3529b94acceSBarry Smith 
3539b94acceSBarry Smith    Notes:
3549b94acceSBarry Smith    The available visualization contexts include
355b0a32e0cSBarry Smith +     PETSC_VIEWER_STDOUT_SELF - standard output (default)
356b0a32e0cSBarry Smith -     PETSC_VIEWER_STDOUT_WORLD - synchronized standard
357c8a8ba5cSLois Curfman McInnes          output where only the first processor opens
358c8a8ba5cSLois Curfman McInnes          the file.  All other processors send their
359c8a8ba5cSLois Curfman McInnes          data to the first processor to print.
3609b94acceSBarry Smith 
361052bf0daSPierre Jolivet    The available formats include
362052bf0daSPierre Jolivet +     PETSC_VIEWER_DEFAULT - standard output (default)
363052bf0daSPierre Jolivet -     PETSC_VIEWER_ASCII_INFO_DETAIL - more verbose output for SNESNASM
364052bf0daSPierre Jolivet 
3653e081fefSLois Curfman McInnes    The user can open an alternative visualization context with
366b0a32e0cSBarry Smith    PetscViewerASCIIOpen() - output to a specified file.
3679b94acceSBarry Smith 
368595c91d4SBarry Smith   In the debugger you can do "call SNESView(snes,0)" to display the SNES solver. (The same holds for any PETSc object viewer).
369595c91d4SBarry Smith 
37036851e7fSLois Curfman McInnes    Level: beginner
37136851e7fSLois Curfman McInnes 
372db781477SPatrick Sanan .seealso: `PetscViewerASCIIOpen()`
3739b94acceSBarry Smith @*/
3747087cfbeSBarry Smith PetscErrorCode  SNESView(SNES snes,PetscViewer viewer)
3759b94acceSBarry Smith {
376fa9f3622SBarry Smith   SNESKSPEW      *kctx;
37794b7f48cSBarry Smith   KSP            ksp;
3787f1410a3SPeter Brune   SNESLineSearch linesearch;
37972a02f06SBarry Smith   PetscBool      iascii,isstring,isbinary,isdraw;
3802d53ad75SBarry Smith   DMSNES         dmsnes;
381e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
382536b137fSBarry Smith   PetscBool      issaws;
383bfb97211SBarry Smith #endif
3849b94acceSBarry Smith 
3853a40ed3dSBarry Smith   PetscFunctionBegin;
3860700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3873050cee2SBarry Smith   if (!viewer) {
3889566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes),&viewer));
3893050cee2SBarry Smith   }
3900700a824SBarry Smith   PetscValidHeaderSpecific(viewer,PETSC_VIEWER_CLASSID,2);
391c9780b6fSBarry Smith   PetscCheckSameComm(snes,1,viewer,2);
39274679c65SBarry Smith 
3939566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii));
3949566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSTRING,&isstring));
3959566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary));
3969566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERDRAW,&isdraw));
397e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
3989566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSAWS,&issaws));
399bfb97211SBarry Smith #endif
40032077d6dSBarry Smith   if (iascii) {
401dc0571f2SMatthew G. Knepley     SNESNormSchedule normschedule;
4028404b7f3SBarry Smith     DM               dm;
4038404b7f3SBarry Smith     PetscErrorCode   (*cJ)(SNES,Vec,Mat,Mat,void*);
4048404b7f3SBarry Smith     void             *ctx;
405789d8953SBarry Smith     const char       *pre = "";
406dc0571f2SMatthew G. Knepley 
4079566063dSJacob Faibussowitsch     PetscCall(PetscObjectPrintClassNamePrefixType((PetscObject)snes,viewer));
408fce1e034SJed Brown     if (!snes->setupcalled) {
4099566063dSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPrintf(viewer,"  SNES has not been set up so information may be incomplete\n"));
410fce1e034SJed Brown     }
411e7788613SBarry Smith     if (snes->ops->view) {
4129566063dSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPushTab(viewer));
4139566063dSJacob Faibussowitsch       PetscCall((*snes->ops->view)(snes,viewer));
4149566063dSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPopTab(viewer));
4150ef38995SBarry Smith     }
41663a3b9bcSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPrintf(viewer,"  maximum iterations=%" PetscInt_FMT ", maximum function evaluations=%" PetscInt_FMT "\n",snes->max_its,snes->max_funcs));
4179566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPrintf(viewer,"  tolerances: relative=%g, absolute=%g, solution=%g\n",(double)snes->rtol,(double)snes->abstol,(double)snes->stol));
418efd4aadfSBarry Smith     if (snes->usesksp) {
41963a3b9bcSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPrintf(viewer,"  total number of linear solver iterations=%" PetscInt_FMT "\n",snes->linear_its));
420efd4aadfSBarry Smith     }
42163a3b9bcSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPrintf(viewer,"  total number of function evaluations=%" PetscInt_FMT "\n",snes->nfuncs));
4229566063dSJacob Faibussowitsch     PetscCall(SNESGetNormSchedule(snes, &normschedule));
4239566063dSJacob Faibussowitsch     if (normschedule > 0) PetscCall(PetscViewerASCIIPrintf(viewer,"  norm schedule %s\n",SNESNormSchedules[normschedule]));
42417fe4bdfSPeter Brune     if (snes->gridsequence) {
42563a3b9bcSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPrintf(viewer,"  total number of grid sequence refinements=%" PetscInt_FMT "\n",snes->gridsequence));
42617fe4bdfSPeter Brune     }
4279b94acceSBarry Smith     if (snes->ksp_ewconv) {
428fa9f3622SBarry Smith       kctx = (SNESKSPEW*)snes->kspconvctx;
4299b94acceSBarry Smith       if (kctx) {
43063a3b9bcSJacob Faibussowitsch         PetscCall(PetscViewerASCIIPrintf(viewer,"  Eisenstat-Walker computation of KSP relative tolerance (version %" PetscInt_FMT ")\n",kctx->version));
4319566063dSJacob Faibussowitsch         PetscCall(PetscViewerASCIIPrintf(viewer,"    rtol_0=%g, rtol_max=%g, threshold=%g\n",(double)kctx->rtol_0,(double)kctx->rtol_max,(double)kctx->threshold));
4329566063dSJacob Faibussowitsch         PetscCall(PetscViewerASCIIPrintf(viewer,"    gamma=%g, alpha=%g, alpha2=%g\n",(double)kctx->gamma,(double)kctx->alpha,(double)kctx->alpha2));
4339b94acceSBarry Smith       }
4349b94acceSBarry Smith     }
435eb1f6c34SBarry Smith     if (snes->lagpreconditioner == -1) {
4369566063dSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPrintf(viewer,"  Preconditioned is never rebuilt\n"));
437eb1f6c34SBarry Smith     } else if (snes->lagpreconditioner > 1) {
43863a3b9bcSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPrintf(viewer,"  Preconditioned is rebuilt every %" PetscInt_FMT " new Jacobians\n",snes->lagpreconditioner));
439eb1f6c34SBarry Smith     }
440eb1f6c34SBarry Smith     if (snes->lagjacobian == -1) {
4419566063dSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPrintf(viewer,"  Jacobian is never rebuilt\n"));
442eb1f6c34SBarry Smith     } else if (snes->lagjacobian > 1) {
44363a3b9bcSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPrintf(viewer,"  Jacobian is rebuilt every %" PetscInt_FMT " SNES iterations\n",snes->lagjacobian));
444eb1f6c34SBarry Smith     }
4459566063dSJacob Faibussowitsch     PetscCall(SNESGetDM(snes,&dm));
4469566063dSJacob Faibussowitsch     PetscCall(DMSNESGetJacobian(dm,&cJ,&ctx));
447789d8953SBarry Smith     if (snes->mf_operator) {
4489566063dSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPrintf(viewer,"  Jacobian is applied matrix-free with differencing\n"));
449789d8953SBarry Smith       pre  = "Preconditioning ";
450789d8953SBarry Smith     }
4518404b7f3SBarry Smith     if (cJ == SNESComputeJacobianDefault) {
4529566063dSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPrintf(viewer,"  %sJacobian is built using finite differences one column at a time\n",pre));
4538404b7f3SBarry Smith     } else if (cJ == SNESComputeJacobianDefaultColor) {
4549566063dSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPrintf(viewer,"  %sJacobian is built using finite differences with coloring\n",pre));
455789d8953SBarry Smith     /* it slightly breaks data encapsulation for access the DMDA information directly */
456789d8953SBarry Smith     } else if (cJ == SNESComputeJacobian_DMDA) {
457789d8953SBarry Smith       MatFDColoring fdcoloring;
4589566063dSJacob Faibussowitsch       PetscCall(PetscObjectQuery((PetscObject)dm,"DMDASNES_FDCOLORING",(PetscObject*)&fdcoloring));
459789d8953SBarry Smith       if (fdcoloring) {
4609566063dSJacob Faibussowitsch         PetscCall(PetscViewerASCIIPrintf(viewer,"  %sJacobian is built using colored finite differences on a DMDA\n",pre));
461789d8953SBarry Smith       } else {
4629566063dSJacob Faibussowitsch         PetscCall(PetscViewerASCIIPrintf(viewer,"  %sJacobian is built using a DMDA local Jacobian\n",pre));
463789d8953SBarry Smith       }
464789d8953SBarry Smith     } else if (snes->mf) {
4659566063dSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPrintf(viewer,"  Jacobian is applied matrix-free with differencing, no explicit Jacobian\n"));
4668404b7f3SBarry Smith     }
4670f5bd95cSBarry Smith   } else if (isstring) {
468317d6ea6SBarry Smith     const char *type;
4699566063dSJacob Faibussowitsch     PetscCall(SNESGetType(snes,&type));
4709566063dSJacob Faibussowitsch     PetscCall(PetscViewerStringSPrintf(viewer," SNESType: %-7.7s",type));
4719566063dSJacob Faibussowitsch     if (snes->ops->view) PetscCall((*snes->ops->view)(snes,viewer));
47255849f57SBarry Smith   } else if (isbinary) {
47355849f57SBarry Smith     PetscInt    classid = SNES_FILE_CLASSID;
47455849f57SBarry Smith     MPI_Comm    comm;
47555849f57SBarry Smith     PetscMPIInt rank;
47655849f57SBarry Smith     char        type[256];
47755849f57SBarry Smith 
4789566063dSJacob Faibussowitsch     PetscCall(PetscObjectGetComm((PetscObject)snes,&comm));
4799566063dSJacob Faibussowitsch     PetscCallMPI(MPI_Comm_rank(comm,&rank));
480dd400576SPatrick Sanan     if (rank == 0) {
4819566063dSJacob Faibussowitsch       PetscCall(PetscViewerBinaryWrite(viewer,&classid,1,PETSC_INT));
4829566063dSJacob Faibussowitsch       PetscCall(PetscStrncpy(type,((PetscObject)snes)->type_name,sizeof(type)));
4839566063dSJacob Faibussowitsch       PetscCall(PetscViewerBinaryWrite(viewer,type,sizeof(type),PETSC_CHAR));
48455849f57SBarry Smith     }
4851baa6e33SBarry Smith     if (snes->ops->view) PetscCall((*snes->ops->view)(snes,viewer));
48672a02f06SBarry Smith   } else if (isdraw) {
48772a02f06SBarry Smith     PetscDraw draw;
48872a02f06SBarry Smith     char      str[36];
48989fd9fafSBarry Smith     PetscReal x,y,bottom,h;
49072a02f06SBarry Smith 
4919566063dSJacob Faibussowitsch     PetscCall(PetscViewerDrawGetDraw(viewer,0,&draw));
4929566063dSJacob Faibussowitsch     PetscCall(PetscDrawGetCurrentPoint(draw,&x,&y));
4939566063dSJacob Faibussowitsch     PetscCall(PetscStrncpy(str,"SNES: ",sizeof(str)));
4949566063dSJacob Faibussowitsch     PetscCall(PetscStrlcat(str,((PetscObject)snes)->type_name,sizeof(str)));
4959566063dSJacob Faibussowitsch     PetscCall(PetscDrawStringBoxed(draw,x,y,PETSC_DRAW_BLUE,PETSC_DRAW_BLACK,str,NULL,&h));
49689fd9fafSBarry Smith     bottom = y - h;
4979566063dSJacob Faibussowitsch     PetscCall(PetscDrawPushCurrentPoint(draw,x,bottom));
4981baa6e33SBarry Smith     if (snes->ops->view) PetscCall((*snes->ops->view)(snes,viewer));
499e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
500536b137fSBarry Smith   } else if (issaws) {
501d45a07a7SBarry Smith     PetscMPIInt rank;
5022657e9d9SBarry Smith     const char *name;
503d45a07a7SBarry Smith 
5049566063dSJacob Faibussowitsch     PetscCall(PetscObjectGetName((PetscObject)snes,&name));
5059566063dSJacob Faibussowitsch     PetscCallMPI(MPI_Comm_rank(PETSC_COMM_WORLD,&rank));
506dd400576SPatrick Sanan     if (!((PetscObject)snes)->amsmem && rank == 0) {
507d45a07a7SBarry Smith       char       dir[1024];
508d45a07a7SBarry Smith 
5099566063dSJacob Faibussowitsch       PetscCall(PetscObjectViewSAWs((PetscObject)snes,viewer));
5109566063dSJacob Faibussowitsch       PetscCall(PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/its",name));
511*792fecdfSBarry Smith       PetscCallSAWs(SAWs_Register,(dir,&snes->iter,1,SAWs_READ,SAWs_INT));
512bfb97211SBarry Smith       if (!snes->conv_hist) {
5139566063dSJacob Faibussowitsch         PetscCall(SNESSetConvergenceHistory(snes,NULL,NULL,PETSC_DECIDE,PETSC_TRUE));
514bfb97211SBarry Smith       }
5159566063dSJacob Faibussowitsch       PetscCall(PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/conv_hist",name));
516*792fecdfSBarry Smith       PetscCallSAWs(SAWs_Register,(dir,snes->conv_hist,10,SAWs_READ,SAWs_DOUBLE));
517f05ece33SBarry Smith     }
518bfb97211SBarry Smith #endif
51972a02f06SBarry Smith   }
52072a02f06SBarry Smith   if (snes->linesearch) {
5219566063dSJacob Faibussowitsch     PetscCall(SNESGetLineSearch(snes, &linesearch));
5229566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPushTab(viewer));
5239566063dSJacob Faibussowitsch     PetscCall(SNESLineSearchView(linesearch, viewer));
5249566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPopTab(viewer));
52519bcc07fSBarry Smith   }
526efd4aadfSBarry Smith   if (snes->npc && snes->usesnpc) {
5279566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPushTab(viewer));
5289566063dSJacob Faibussowitsch     PetscCall(SNESView(snes->npc, viewer));
5299566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPopTab(viewer));
5304a0c5b0cSMatthew G Knepley   }
5319566063dSJacob Faibussowitsch   PetscCall(PetscViewerASCIIPushTab(viewer));
5329566063dSJacob Faibussowitsch   PetscCall(DMGetDMSNES(snes->dm,&dmsnes));
5339566063dSJacob Faibussowitsch   PetscCall(DMSNESView(dmsnes, viewer));
5349566063dSJacob Faibussowitsch   PetscCall(PetscViewerASCIIPopTab(viewer));
5352c155ee1SBarry Smith   if (snes->usesksp) {
5369566063dSJacob Faibussowitsch     PetscCall(SNESGetKSP(snes,&ksp));
5379566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPushTab(viewer));
5389566063dSJacob Faibussowitsch     PetscCall(KSPView(ksp,viewer));
5399566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPopTab(viewer));
5402c155ee1SBarry Smith   }
54172a02f06SBarry Smith   if (isdraw) {
54272a02f06SBarry Smith     PetscDraw draw;
5439566063dSJacob Faibussowitsch     PetscCall(PetscViewerDrawGetDraw(viewer,0,&draw));
5449566063dSJacob Faibussowitsch     PetscCall(PetscDrawPopCurrentPoint(draw));
5457f1410a3SPeter Brune   }
5463a40ed3dSBarry Smith   PetscFunctionReturn(0);
5479b94acceSBarry Smith }
5489b94acceSBarry Smith 
54976b2cf59SMatthew Knepley /*
55076b2cf59SMatthew Knepley   We retain a list of functions that also take SNES command
55176b2cf59SMatthew Knepley   line options. These are called at the end SNESSetFromOptions()
55276b2cf59SMatthew Knepley */
55376b2cf59SMatthew Knepley #define MAXSETFROMOPTIONS 5
554a7cc72afSBarry Smith static PetscInt numberofsetfromoptions;
5556849ba73SBarry Smith static PetscErrorCode (*othersetfromoptions[MAXSETFROMOPTIONS])(SNES);
55676b2cf59SMatthew Knepley 
557ac226902SBarry Smith /*@C
55876b2cf59SMatthew Knepley   SNESAddOptionsChecker - Adds an additional function to check for SNES options.
55976b2cf59SMatthew Knepley 
56076b2cf59SMatthew Knepley   Not Collective
56176b2cf59SMatthew Knepley 
56276b2cf59SMatthew Knepley   Input Parameter:
56376b2cf59SMatthew Knepley . snescheck - function that checks for options
56476b2cf59SMatthew Knepley 
56576b2cf59SMatthew Knepley   Level: developer
56676b2cf59SMatthew Knepley 
567db781477SPatrick Sanan .seealso: `SNESSetFromOptions()`
56876b2cf59SMatthew Knepley @*/
5697087cfbeSBarry Smith PetscErrorCode  SNESAddOptionsChecker(PetscErrorCode (*snescheck)(SNES))
57076b2cf59SMatthew Knepley {
57176b2cf59SMatthew Knepley   PetscFunctionBegin;
57263a3b9bcSJacob Faibussowitsch   PetscCheck(numberofsetfromoptions < MAXSETFROMOPTIONS,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE, "Too many options checkers, only %d allowed", MAXSETFROMOPTIONS);
57376b2cf59SMatthew Knepley   othersetfromoptions[numberofsetfromoptions++] = snescheck;
57476b2cf59SMatthew Knepley   PetscFunctionReturn(0);
57576b2cf59SMatthew Knepley }
57676b2cf59SMatthew Knepley 
57725acbd8eSLisandro Dalcin PETSC_INTERN PetscErrorCode SNESDefaultMatrixFreeCreate2(SNES,Vec,Mat*);
578aa3661deSLisandro Dalcin 
579ace3abfcSBarry Smith static PetscErrorCode SNESSetUpMatrixFree_Private(SNES snes, PetscBool hasOperator, PetscInt version)
580aa3661deSLisandro Dalcin {
581aa3661deSLisandro Dalcin   Mat            J;
582895c21f2SBarry Smith   MatNullSpace   nullsp;
583aa3661deSLisandro Dalcin 
584aa3661deSLisandro Dalcin   PetscFunctionBegin;
5850700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
586aa3661deSLisandro Dalcin 
58798613b67SLisandro Dalcin   if (!snes->vec_func && (snes->jacobian || snes->jacobian_pre)) {
58898613b67SLisandro Dalcin     Mat A = snes->jacobian, B = snes->jacobian_pre;
5899566063dSJacob Faibussowitsch     PetscCall(MatCreateVecs(A ? A : B, NULL,&snes->vec_func));
59098613b67SLisandro Dalcin   }
59198613b67SLisandro Dalcin 
592aa3661deSLisandro Dalcin   if (version == 1) {
5939566063dSJacob Faibussowitsch     PetscCall(MatCreateSNESMF(snes,&J));
5949566063dSJacob Faibussowitsch     PetscCall(MatMFFDSetOptionsPrefix(J,((PetscObject)snes)->prefix));
5959566063dSJacob Faibussowitsch     PetscCall(MatSetFromOptions(J));
5961e2ae407SBarry Smith     /* TODO: the version 2 code should be merged into the MatCreateSNESMF() and MatCreateMFFD() infrastructure and then removed */
597aa3661deSLisandro Dalcin   } else if (version == 2) {
5985f80ce2aSJacob Faibussowitsch     PetscCheck(snes->vec_func,PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"SNESSetFunction() must be called first");
599570b7f6dSBarry Smith #if !defined(PETSC_USE_COMPLEX) && !defined(PETSC_USE_REAL_SINGLE) && !defined(PETSC_USE_REAL___FLOAT128) && !defined(PETSC_USE_REAL___FP16)
6009566063dSJacob Faibussowitsch     PetscCall(SNESDefaultMatrixFreeCreate2(snes,snes->vec_func,&J));
601aa3661deSLisandro Dalcin #else
6022479783cSJose E. Roman     SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP, "matrix-free operator routines (version 2)");
603aa3661deSLisandro Dalcin #endif
6042479783cSJose E. Roman   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE, "matrix-free operator routines, only version 1 and 2");
605aa3661deSLisandro Dalcin 
606895c21f2SBarry Smith   /* attach any user provided null space that was on Amat to the newly created matrix free matrix */
607895c21f2SBarry Smith   if (snes->jacobian) {
6089566063dSJacob Faibussowitsch     PetscCall(MatGetNullSpace(snes->jacobian,&nullsp));
6091baa6e33SBarry Smith     if (nullsp) PetscCall(MatSetNullSpace(J,nullsp));
610895c21f2SBarry Smith   }
611895c21f2SBarry Smith 
61263a3b9bcSJacob Faibussowitsch   PetscCall(PetscInfo(snes,"Setting default matrix-free operator routines (version %" PetscInt_FMT ")\n", version));
613d3462f78SMatthew Knepley   if (hasOperator) {
6143232da50SPeter Brune 
615aa3661deSLisandro Dalcin     /* This version replaces the user provided Jacobian matrix with a
616aa3661deSLisandro Dalcin        matrix-free version but still employs the user-provided preconditioner matrix. */
6179566063dSJacob Faibussowitsch     PetscCall(SNESSetJacobian(snes,J,NULL,NULL,NULL));
618aa3661deSLisandro Dalcin   } else {
619aa3661deSLisandro Dalcin     /* This version replaces both the user-provided Jacobian and the user-
6203232da50SPeter Brune      provided preconditioner Jacobian with the default matrix free version. */
621b552625fSStefano Zampini     if (snes->npcside == PC_LEFT && snes->npc) {
6229566063dSJacob Faibussowitsch       if (!snes->jacobian) PetscCall(SNESSetJacobian(snes,J,NULL,NULL,NULL));
623172a4300SPeter Brune     } else {
624789d8953SBarry Smith       KSP       ksp;
625789d8953SBarry Smith       PC        pc;
626789d8953SBarry Smith       PetscBool match;
627789d8953SBarry Smith 
6289566063dSJacob Faibussowitsch       PetscCall(SNESSetJacobian(snes,J,J,MatMFFDComputeJacobian,NULL));
629aa3661deSLisandro Dalcin       /* Force no preconditioner */
6309566063dSJacob Faibussowitsch       PetscCall(SNESGetKSP(snes,&ksp));
6319566063dSJacob Faibussowitsch       PetscCall(KSPGetPC(ksp,&pc));
6322698c518SLisandro Dalcin       PetscCall(PetscObjectTypeCompareAny((PetscObject)pc,&match,PCSHELL,PCH2OPUS,""));
633aa3661deSLisandro Dalcin       if (!match) {
6349566063dSJacob Faibussowitsch         PetscCall(PetscInfo(snes,"Setting default matrix-free preconditioner routines\nThat is no preconditioner is being used\n"));
6359566063dSJacob Faibussowitsch         PetscCall(PCSetType(pc,PCNONE));
636aa3661deSLisandro Dalcin       }
637aa3661deSLisandro Dalcin     }
638789d8953SBarry Smith   }
6399566063dSJacob Faibussowitsch   PetscCall(MatDestroy(&J));
640aa3661deSLisandro Dalcin   PetscFunctionReturn(0);
641aa3661deSLisandro Dalcin }
642aa3661deSLisandro Dalcin 
643dfe15315SJed Brown static PetscErrorCode DMRestrictHook_SNESVecSol(DM dmfine,Mat Restrict,Vec Rscale,Mat Inject,DM dmcoarse,void *ctx)
644dfe15315SJed Brown {
645dfe15315SJed Brown   SNES           snes = (SNES)ctx;
6460298fd71SBarry Smith   Vec            Xfine,Xfine_named = NULL,Xcoarse;
647dfe15315SJed Brown 
648dfe15315SJed Brown   PetscFunctionBegin;
64916ebb321SJed Brown   if (PetscLogPrintInfo) {
65016ebb321SJed Brown     PetscInt finelevel,coarselevel,fineclevel,coarseclevel;
6519566063dSJacob Faibussowitsch     PetscCall(DMGetRefineLevel(dmfine,&finelevel));
6529566063dSJacob Faibussowitsch     PetscCall(DMGetCoarsenLevel(dmfine,&fineclevel));
6539566063dSJacob Faibussowitsch     PetscCall(DMGetRefineLevel(dmcoarse,&coarselevel));
6549566063dSJacob Faibussowitsch     PetscCall(DMGetCoarsenLevel(dmcoarse,&coarseclevel));
65563a3b9bcSJacob Faibussowitsch     PetscCall(PetscInfo(dmfine,"Restricting SNES solution vector from level %" PetscInt_FMT "-%" PetscInt_FMT " to level %" PetscInt_FMT "-%" PetscInt_FMT "\n",finelevel,fineclevel,coarselevel,coarseclevel));
65616ebb321SJed Brown   }
657dfe15315SJed Brown   if (dmfine == snes->dm) Xfine = snes->vec_sol;
658dfe15315SJed Brown   else {
6599566063dSJacob Faibussowitsch     PetscCall(DMGetNamedGlobalVector(dmfine,"SNESVecSol",&Xfine_named));
660dfe15315SJed Brown     Xfine = Xfine_named;
661dfe15315SJed Brown   }
6629566063dSJacob Faibussowitsch   PetscCall(DMGetNamedGlobalVector(dmcoarse,"SNESVecSol",&Xcoarse));
663907f5c5aSLawrence Mitchell   if (Inject) {
6649566063dSJacob Faibussowitsch     PetscCall(MatRestrict(Inject,Xfine,Xcoarse));
665907f5c5aSLawrence Mitchell   } else {
6669566063dSJacob Faibussowitsch     PetscCall(MatRestrict(Restrict,Xfine,Xcoarse));
6679566063dSJacob Faibussowitsch     PetscCall(VecPointwiseMult(Xcoarse,Xcoarse,Rscale));
668907f5c5aSLawrence Mitchell   }
6699566063dSJacob Faibussowitsch   PetscCall(DMRestoreNamedGlobalVector(dmcoarse,"SNESVecSol",&Xcoarse));
6709566063dSJacob Faibussowitsch   if (Xfine_named) PetscCall(DMRestoreNamedGlobalVector(dmfine,"SNESVecSol",&Xfine_named));
671dfe15315SJed Brown   PetscFunctionReturn(0);
672dfe15315SJed Brown }
673dfe15315SJed Brown 
67416ebb321SJed Brown static PetscErrorCode DMCoarsenHook_SNESVecSol(DM dm,DM dmc,void *ctx)
67516ebb321SJed Brown {
67616ebb321SJed Brown   PetscFunctionBegin;
6779566063dSJacob Faibussowitsch   PetscCall(DMCoarsenHookAdd(dmc,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,ctx));
67816ebb321SJed Brown   PetscFunctionReturn(0);
67916ebb321SJed Brown }
68016ebb321SJed Brown 
681a6950cb2SJed Brown /* This may be called to rediscretize the operator on levels of linear multigrid. The DM shuffle is so the user can
682a6950cb2SJed Brown  * safely call SNESGetDM() in their residual evaluation routine. */
68323ee1639SBarry Smith static PetscErrorCode KSPComputeOperators_SNES(KSP ksp,Mat A,Mat B,void *ctx)
684caa4e7f2SJed Brown {
685caa4e7f2SJed Brown   SNES           snes = (SNES)ctx;
6860298fd71SBarry Smith   Vec            X,Xnamed = NULL;
687dfe15315SJed Brown   DM             dmsave;
6884e269d77SPeter Brune   void           *ctxsave;
68925ce1634SJed Brown   PetscErrorCode (*jac)(SNES,Vec,Mat,Mat,void*) = NULL;
690caa4e7f2SJed Brown 
691caa4e7f2SJed Brown   PetscFunctionBegin;
692dfe15315SJed Brown   dmsave = snes->dm;
6939566063dSJacob Faibussowitsch   PetscCall(KSPGetDM(ksp,&snes->dm));
694dfe15315SJed Brown   if (dmsave == snes->dm) X = snes->vec_sol; /* We are on the finest level */
695dfe15315SJed Brown   else {                                     /* We are on a coarser level, this vec was initialized using a DM restrict hook */
6969566063dSJacob Faibussowitsch     PetscCall(DMGetNamedGlobalVector(snes->dm,"SNESVecSol",&Xnamed));
697dfe15315SJed Brown     X    = Xnamed;
6989566063dSJacob Faibussowitsch     PetscCall(SNESGetJacobian(snes,NULL,NULL,&jac,&ctxsave));
6994e269d77SPeter Brune     /* If the DM's don't match up, the MatFDColoring context needed for the jacobian won't match up either -- fixit. */
7008d359177SBarry Smith     if (jac == SNESComputeJacobianDefaultColor) {
7019566063dSJacob Faibussowitsch       PetscCall(SNESSetJacobian(snes,NULL,NULL,SNESComputeJacobianDefaultColor,NULL));
702dfe15315SJed Brown     }
7034e269d77SPeter Brune   }
7044dde8bb0SMatthew G. Knepley   /* Make sure KSP DM has the Jacobian computation routine */
7054dde8bb0SMatthew G. Knepley   {
7064dde8bb0SMatthew G. Knepley     DMSNES sdm;
7074e269d77SPeter Brune 
7089566063dSJacob Faibussowitsch     PetscCall(DMGetDMSNES(snes->dm, &sdm));
7094dde8bb0SMatthew G. Knepley     if (!sdm->ops->computejacobian) {
7109566063dSJacob Faibussowitsch       PetscCall(DMCopyDMSNES(dmsave, snes->dm));
7114dde8bb0SMatthew G. Knepley     }
7124dde8bb0SMatthew G. Knepley   }
7132b93b426SMatthew G. Knepley   /* Compute the operators */
7149566063dSJacob Faibussowitsch   PetscCall(SNESComputeJacobian(snes,X,A,B));
7152b93b426SMatthew G. Knepley   /* Put the previous context back */
7168d359177SBarry Smith   if (snes->dm != dmsave && jac == SNESComputeJacobianDefaultColor) {
7179566063dSJacob Faibussowitsch     PetscCall(SNESSetJacobian(snes,NULL,NULL,jac,ctxsave));
7184e269d77SPeter Brune   }
7194e269d77SPeter Brune 
7209566063dSJacob Faibussowitsch   if (Xnamed) PetscCall(DMRestoreNamedGlobalVector(snes->dm,"SNESVecSol",&Xnamed));
721dfe15315SJed Brown   snes->dm = dmsave;
722caa4e7f2SJed Brown   PetscFunctionReturn(0);
723caa4e7f2SJed Brown }
724caa4e7f2SJed Brown 
7256cab3a1bSJed Brown /*@
7266cab3a1bSJed Brown    SNESSetUpMatrices - ensures that matrices are available for SNES, to be called by SNESSetUp_XXX()
7276cab3a1bSJed Brown 
7286cab3a1bSJed Brown    Collective
7296cab3a1bSJed Brown 
7304165533cSJose E. Roman    Input Parameter:
7316cab3a1bSJed Brown .  snes - snes to configure
7326cab3a1bSJed Brown 
7336cab3a1bSJed Brown    Level: developer
7346cab3a1bSJed Brown 
735db781477SPatrick Sanan .seealso: `SNESSetUp()`
7366cab3a1bSJed Brown @*/
7376cab3a1bSJed Brown PetscErrorCode SNESSetUpMatrices(SNES snes)
7386cab3a1bSJed Brown {
7396cab3a1bSJed Brown   DM             dm;
740942e3340SBarry Smith   DMSNES         sdm;
7416cab3a1bSJed Brown 
7426cab3a1bSJed Brown   PetscFunctionBegin;
7439566063dSJacob Faibussowitsch   PetscCall(SNESGetDM(snes,&dm));
7449566063dSJacob Faibussowitsch   PetscCall(DMGetDMSNES(dm,&sdm));
74558b371f3SBarry Smith   if (!snes->jacobian && snes->mf) {
7466cab3a1bSJed Brown     Mat  J;
7476cab3a1bSJed Brown     void *functx;
7489566063dSJacob Faibussowitsch     PetscCall(MatCreateSNESMF(snes,&J));
7499566063dSJacob Faibussowitsch     PetscCall(MatMFFDSetOptionsPrefix(J,((PetscObject)snes)->prefix));
7509566063dSJacob Faibussowitsch     PetscCall(MatSetFromOptions(J));
7519566063dSJacob Faibussowitsch     PetscCall(SNESGetFunction(snes,NULL,NULL,&functx));
7529566063dSJacob Faibussowitsch     PetscCall(SNESSetJacobian(snes,J,J,NULL,NULL));
7539566063dSJacob Faibussowitsch     PetscCall(MatDestroy(&J));
754caa4e7f2SJed Brown   } else if (snes->mf_operator && !snes->jacobian_pre && !snes->jacobian) {
7556cab3a1bSJed Brown     Mat J,B;
7569566063dSJacob Faibussowitsch     PetscCall(MatCreateSNESMF(snes,&J));
7579566063dSJacob Faibussowitsch     PetscCall(MatMFFDSetOptionsPrefix(J,((PetscObject)snes)->prefix));
7589566063dSJacob Faibussowitsch     PetscCall(MatSetFromOptions(J));
7599566063dSJacob Faibussowitsch     PetscCall(DMCreateMatrix(snes->dm,&B));
76006f20277SJed Brown     /* sdm->computejacobian was already set to reach here */
7619566063dSJacob Faibussowitsch     PetscCall(SNESSetJacobian(snes,J,B,NULL,NULL));
7629566063dSJacob Faibussowitsch     PetscCall(MatDestroy(&J));
7639566063dSJacob Faibussowitsch     PetscCall(MatDestroy(&B));
764caa4e7f2SJed Brown   } else if (!snes->jacobian_pre) {
7651ba9b98eSMatthew G. Knepley     PetscDS   prob;
7666cab3a1bSJed Brown     Mat       J, B;
7671ba9b98eSMatthew G. Knepley     PetscBool hasPrec   = PETSC_FALSE;
7681ba9b98eSMatthew G. Knepley 
7696cab3a1bSJed Brown     J    = snes->jacobian;
7709566063dSJacob Faibussowitsch     PetscCall(DMGetDS(dm, &prob));
7719566063dSJacob Faibussowitsch     if (prob) PetscCall(PetscDSHasJacobianPreconditioner(prob, &hasPrec));
7729566063dSJacob Faibussowitsch     if (J)            PetscCall(PetscObjectReference((PetscObject) J));
7739566063dSJacob Faibussowitsch     else if (hasPrec) PetscCall(DMCreateMatrix(snes->dm, &J));
7749566063dSJacob Faibussowitsch     PetscCall(DMCreateMatrix(snes->dm, &B));
7759566063dSJacob Faibussowitsch     PetscCall(SNESSetJacobian(snes, J ? J : B, B, NULL, NULL));
7769566063dSJacob Faibussowitsch     PetscCall(MatDestroy(&J));
7779566063dSJacob Faibussowitsch     PetscCall(MatDestroy(&B));
7786cab3a1bSJed Brown   }
779caa4e7f2SJed Brown   {
780caa4e7f2SJed Brown     KSP ksp;
7819566063dSJacob Faibussowitsch     PetscCall(SNESGetKSP(snes,&ksp));
7829566063dSJacob Faibussowitsch     PetscCall(KSPSetComputeOperators(ksp,KSPComputeOperators_SNES,snes));
7839566063dSJacob Faibussowitsch     PetscCall(DMCoarsenHookAdd(snes->dm,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,snes));
784caa4e7f2SJed Brown   }
7856cab3a1bSJed Brown   PetscFunctionReturn(0);
7866cab3a1bSJed Brown }
7876cab3a1bSJed Brown 
7885e7c47f3SMatthew G. Knepley static PetscErrorCode SNESMonitorPauseFinal_Internal(SNES snes)
7895e7c47f3SMatthew G. Knepley {
7905e7c47f3SMatthew G. Knepley   PetscInt       i;
7915e7c47f3SMatthew G. Knepley 
7925e7c47f3SMatthew G. Knepley   PetscFunctionBegin;
7935e7c47f3SMatthew G. Knepley   if (!snes->pauseFinal) PetscFunctionReturn(0);
7945e7c47f3SMatthew G. Knepley   for (i = 0; i < snes->numbermonitors; ++i) {
7955e7c47f3SMatthew G. Knepley     PetscViewerAndFormat *vf = (PetscViewerAndFormat *) snes->monitorcontext[i];
7965e7c47f3SMatthew G. Knepley     PetscDraw             draw;
7975e7c47f3SMatthew G. Knepley     PetscReal             lpause;
7985e7c47f3SMatthew G. Knepley 
7995e7c47f3SMatthew G. Knepley     if (!vf) continue;
8005e7c47f3SMatthew G. Knepley     if (vf->lg) {
8015e7c47f3SMatthew G. Knepley       if (!PetscCheckPointer(vf->lg, PETSC_OBJECT)) continue;
8025e7c47f3SMatthew G. Knepley       if (((PetscObject) vf->lg)->classid != PETSC_DRAWLG_CLASSID) continue;
8039566063dSJacob Faibussowitsch       PetscCall(PetscDrawLGGetDraw(vf->lg, &draw));
8049566063dSJacob Faibussowitsch       PetscCall(PetscDrawGetPause(draw, &lpause));
8059566063dSJacob Faibussowitsch       PetscCall(PetscDrawSetPause(draw, -1.0));
8069566063dSJacob Faibussowitsch       PetscCall(PetscDrawPause(draw));
8079566063dSJacob Faibussowitsch       PetscCall(PetscDrawSetPause(draw, lpause));
8085e7c47f3SMatthew G. Knepley     } else {
8095e7c47f3SMatthew G. Knepley       PetscBool isdraw;
8105e7c47f3SMatthew G. Knepley 
8115e7c47f3SMatthew G. Knepley       if (!PetscCheckPointer(vf->viewer, PETSC_OBJECT)) continue;
8125e7c47f3SMatthew G. Knepley       if (((PetscObject) vf->viewer)->classid != PETSC_VIEWER_CLASSID) continue;
8139566063dSJacob Faibussowitsch       PetscCall(PetscObjectTypeCompare((PetscObject) vf->viewer, PETSCVIEWERDRAW, &isdraw));
8145e7c47f3SMatthew G. Knepley       if (!isdraw) continue;
8159566063dSJacob Faibussowitsch       PetscCall(PetscViewerDrawGetDraw(vf->viewer, 0, &draw));
8169566063dSJacob Faibussowitsch       PetscCall(PetscDrawGetPause(draw, &lpause));
8179566063dSJacob Faibussowitsch       PetscCall(PetscDrawSetPause(draw, -1.0));
8189566063dSJacob Faibussowitsch       PetscCall(PetscDrawPause(draw));
8199566063dSJacob Faibussowitsch       PetscCall(PetscDrawSetPause(draw, lpause));
8205e7c47f3SMatthew G. Knepley     }
8215e7c47f3SMatthew G. Knepley   }
8225e7c47f3SMatthew G. Knepley   PetscFunctionReturn(0);
8235e7c47f3SMatthew G. Knepley }
8245e7c47f3SMatthew G. Knepley 
825fde5950dSBarry Smith /*@C
826fde5950dSBarry Smith    SNESMonitorSetFromOptions - Sets a monitor function and viewer appropriate for the type indicated by the user
827fde5950dSBarry Smith 
828fde5950dSBarry Smith    Collective on SNES
829fde5950dSBarry Smith 
830fde5950dSBarry Smith    Input Parameters:
831fde5950dSBarry Smith +  snes - SNES object you wish to monitor
832fde5950dSBarry Smith .  name - the monitor type one is seeking
833fde5950dSBarry Smith .  help - message indicating what monitoring is done
834fde5950dSBarry Smith .  manual - manual page for the monitor
835fde5950dSBarry Smith .  monitor - the monitor function
836fde5950dSBarry 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
837fde5950dSBarry Smith 
838fde5950dSBarry Smith    Level: developer
839fde5950dSBarry Smith 
840db781477SPatrick Sanan .seealso: `PetscOptionsGetViewer()`, `PetscOptionsGetReal()`, `PetscOptionsHasName()`, `PetscOptionsGetString()`,
841db781477SPatrick Sanan           `PetscOptionsGetIntArray()`, `PetscOptionsGetRealArray()`, `PetscOptionsBool()`
842db781477SPatrick Sanan           `PetscOptionsInt()`, `PetscOptionsString()`, `PetscOptionsReal()`, `PetscOptionsBool()`,
843db781477SPatrick Sanan           `PetscOptionsName()`, `PetscOptionsBegin()`, `PetscOptionsEnd()`, `PetscOptionsHeadBegin()`,
844c2e3fba1SPatrick Sanan           `PetscOptionsStringArray()`, `PetscOptionsRealArray()`, `PetscOptionsScalar()`,
845db781477SPatrick Sanan           `PetscOptionsBoolGroupBegin()`, `PetscOptionsBoolGroup()`, `PetscOptionsBoolGroupEnd()`,
846db781477SPatrick Sanan           `PetscOptionsFList()`, `PetscOptionsEList()`
847fde5950dSBarry Smith @*/
848d43b4f6eSBarry Smith PetscErrorCode  SNESMonitorSetFromOptions(SNES snes,const char name[],const char help[], const char manual[],PetscErrorCode (*monitor)(SNES,PetscInt,PetscReal,PetscViewerAndFormat*),PetscErrorCode (*monitorsetup)(SNES,PetscViewerAndFormat*))
849fde5950dSBarry Smith {
850fde5950dSBarry Smith   PetscViewer       viewer;
851fde5950dSBarry Smith   PetscViewerFormat format;
852fde5950dSBarry Smith   PetscBool         flg;
853fde5950dSBarry Smith 
854fde5950dSBarry Smith   PetscFunctionBegin;
8559566063dSJacob Faibussowitsch   PetscCall(PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject) snes)->options,((PetscObject)snes)->prefix,name,&viewer,&format,&flg));
856fde5950dSBarry Smith   if (flg) {
857d43b4f6eSBarry Smith     PetscViewerAndFormat *vf;
8589566063dSJacob Faibussowitsch     PetscCall(PetscViewerAndFormatCreate(viewer,format,&vf));
8599566063dSJacob Faibussowitsch     PetscCall(PetscObjectDereference((PetscObject)viewer));
8601baa6e33SBarry Smith     if (monitorsetup) PetscCall((*monitorsetup)(snes,vf));
8619566063dSJacob Faibussowitsch     PetscCall(SNESMonitorSet(snes,(PetscErrorCode (*)(SNES,PetscInt,PetscReal,void*))monitor,vf,(PetscErrorCode (*)(void**))PetscViewerAndFormatDestroy));
862fde5950dSBarry Smith   }
863fde5950dSBarry Smith   PetscFunctionReturn(0);
864fde5950dSBarry Smith }
865fde5950dSBarry Smith 
8660f0abf79SStefano Zampini PetscErrorCode SNESEWSetFromOptions_Private(SNESKSPEW* kctx, MPI_Comm comm, const char* prefix)
8670f0abf79SStefano Zampini {
8680f0abf79SStefano Zampini   PetscFunctionBegin;
8690f0abf79SStefano Zampini   PetscOptionsBegin(comm,prefix,"Eisenstat and Walker type forcing options","KSP");
8700f0abf79SStefano Zampini   PetscCall(PetscOptionsInt("-ksp_ew_version","Version 1, 2 or 3",NULL,kctx->version,&kctx->version,NULL));
8710f0abf79SStefano Zampini   PetscCall(PetscOptionsReal("-ksp_ew_rtol0","0 <= rtol0 < 1",NULL,kctx->rtol_0,&kctx->rtol_0,NULL));
8720f0abf79SStefano Zampini   PetscCall(PetscOptionsReal("-ksp_ew_rtolmax","0 <= rtolmax < 1",NULL,kctx->rtol_max,&kctx->rtol_max,NULL));
8730f0abf79SStefano Zampini   PetscCall(PetscOptionsReal("-ksp_ew_gamma","0 <= gamma <= 1",NULL,kctx->gamma,&kctx->gamma,NULL));
8740f0abf79SStefano Zampini   PetscCall(PetscOptionsReal("-ksp_ew_alpha","1 < alpha <= 2",NULL,kctx->alpha,&kctx->alpha,NULL));
8750f0abf79SStefano Zampini   PetscCall(PetscOptionsReal("-ksp_ew_alpha2","alpha2",NULL,kctx->alpha2,&kctx->alpha2,NULL));
8760f0abf79SStefano Zampini   PetscCall(PetscOptionsReal("-ksp_ew_threshold","0 < threshold < 1",NULL,kctx->threshold,&kctx->threshold,NULL));
8770f0abf79SStefano Zampini   PetscCall(PetscOptionsReal("-ksp_ew_v4_p1","p1",NULL,kctx->v4_p1,&kctx->v4_p1,NULL));
8780f0abf79SStefano Zampini   PetscCall(PetscOptionsReal("-ksp_ew_v4_p2","p2",NULL,kctx->v4_p2,&kctx->v4_p2,NULL));
8790f0abf79SStefano Zampini   PetscCall(PetscOptionsReal("-ksp_ew_v4_p3","p3",NULL,kctx->v4_p3,&kctx->v4_p3,NULL));
8800f0abf79SStefano Zampini   PetscCall(PetscOptionsReal("-ksp_ew_v4_m1","Scaling when rk-1 in [p2,p3)",NULL,kctx->v4_m1,&kctx->v4_m1,NULL));
8810f0abf79SStefano Zampini   PetscCall(PetscOptionsReal("-ksp_ew_v4_m2","Scaling when rk-1 in [p3,+infty)",NULL,kctx->v4_m2,&kctx->v4_m2,NULL));
8820f0abf79SStefano Zampini   PetscCall(PetscOptionsReal("-ksp_ew_v4_m3","Threshold for successive rtol (0.1 in Eq.7)",NULL,kctx->v4_m3,&kctx->v4_m3,NULL));
8830f0abf79SStefano Zampini   PetscCall(PetscOptionsReal("-ksp_ew_v4_m4","Adaptation scaling (0.5 in Eq.7)",NULL,kctx->v4_m4,&kctx->v4_m4,NULL));
8840f0abf79SStefano Zampini   PetscOptionsEnd();
8850f0abf79SStefano Zampini   PetscFunctionReturn(0);
8860f0abf79SStefano Zampini }
8870f0abf79SStefano Zampini 
8889b94acceSBarry Smith /*@
88994b7f48cSBarry Smith    SNESSetFromOptions - Sets various SNES and KSP parameters from user options.
8909b94acceSBarry Smith 
891c7afd0dbSLois Curfman McInnes    Collective on SNES
892c7afd0dbSLois Curfman McInnes 
8939b94acceSBarry Smith    Input Parameter:
8949b94acceSBarry Smith .  snes - the SNES context
8959b94acceSBarry Smith 
89636851e7fSLois Curfman McInnes    Options Database Keys:
897722329fbSBarry Smith +  -snes_type <type> - newtonls, newtontr, ngmres, ncg, nrichardson, qn, vi, fas, SNESType for complete list
89882738288SBarry Smith .  -snes_stol - convergence tolerance in terms of the norm
89982738288SBarry Smith                 of the change in the solution between steps
90070441072SBarry Smith .  -snes_atol <abstol> - absolute tolerance of residual norm
901b39c3a46SLois Curfman McInnes .  -snes_rtol <rtol> - relative decrease in tolerance norm from initial
902e4d06f11SPatrick Farrell .  -snes_divergence_tolerance <divtol> - if the residual goes above divtol*rnorm0, exit with divergence
903be5caee7SBarry Smith .  -snes_force_iteration <force> - force SNESSolve() to take at least one iteration
904b39c3a46SLois Curfman McInnes .  -snes_max_it <max_it> - maximum number of iterations
905b39c3a46SLois Curfman McInnes .  -snes_max_funcs <max_funcs> - maximum number of function evaluations
9064839bfe8SBarry Smith .  -snes_max_fail <max_fail> - maximum number of line search failures allowed before stopping, default is none
907ddf469c8SBarry Smith .  -snes_max_linear_solve_fail - number of linear solver failures before SNESSolve() stops
908a8054027SBarry Smith .  -snes_lag_preconditioner <lag> - how often preconditioner is rebuilt (use -1 to never rebuild)
9093d5a8a6aSBarry Smith .  -snes_lag_preconditioner_persists <true,false> - retains the -snes_lag_preconditioner information across multiple SNESSolve()
910e35cf81dSBarry Smith .  -snes_lag_jacobian <lag> - how often Jacobian is rebuilt (use -1 to never rebuild)
9113d5a8a6aSBarry Smith .  -snes_lag_jacobian_persists <true,false> - retains the -snes_lag_jacobian information across multiple SNESSolve()
912b39c3a46SLois Curfman McInnes .  -snes_trtol <trtol> - trust region tolerance
913f362779dSJed Brown .  -snes_convergence_test - <default,skip,correct_pressure> convergence test in nonlinear solver.
914f362779dSJed Brown                                default SNESConvergedDefault(). skip SNESConvergedSkip() means continue iterating until max_it or some other criterion is reached, saving expense
915f362779dSJed Brown                                of convergence test. correct_pressure SNESConvergedCorrectPressure() has special handling of a pressure null space.
916fde5950dSBarry Smith .  -snes_monitor [ascii][:filename][:viewer format] - prints residual norm at each iteration. if no filename given prints to stdout
917fde5950dSBarry Smith .  -snes_monitor_solution [ascii binary draw][:filename][:viewer format] - plots solution at each iteration
918fde5950dSBarry Smith .  -snes_monitor_residual [ascii binary draw][:filename][:viewer format] - plots residual (not its norm) at each iteration
919fde5950dSBarry Smith .  -snes_monitor_solution_update [ascii binary draw][:filename][:viewer format] - plots update to solution at each iteration
9204619e776SBarry Smith .  -snes_monitor_lg_residualnorm - plots residual norm at each iteration
921459f5d12SBarry Smith .  -snes_monitor_lg_range - plots residual norm at each iteration
9225e7c47f3SMatthew G. Knepley .  -snes_monitor_pause_final - Pauses all monitor drawing after the solver ends
923e24b481bSBarry Smith .  -snes_fd - use finite differences to compute Jacobian; very slow, only for testing
924e2e60de9SPeter Brune .  -snes_fd_color - use finite differences with coloring to compute Jacobian
9255968eb51SBarry Smith .  -snes_mf_ksp_monitor - if using matrix-free multiply then print h at each KSP iteration
926b5badacbSBarry Smith .  -snes_converged_reason - print the reason for convergence/divergence after each solve
927e62ac41dSBarry Smith .  -npc_snes_type <type> - the SNES type to use as a nonlinear preconditioner
928e62ac41dSBarry 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.
929e62ac41dSBarry 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.
93082738288SBarry Smith 
93182738288SBarry Smith     Options Database for Eisenstat-Walker method:
932fa9f3622SBarry Smith +  -snes_ksp_ew - use Eisenstat-Walker method for determining linear system convergence
9334b27c08aSLois Curfman McInnes .  -snes_ksp_ew_version ver - version of  Eisenstat-Walker method
93436851e7fSLois Curfman McInnes .  -snes_ksp_ew_rtol0 <rtol0> - Sets rtol0
93536851e7fSLois Curfman McInnes .  -snes_ksp_ew_rtolmax <rtolmax> - Sets rtolmax
93636851e7fSLois Curfman McInnes .  -snes_ksp_ew_gamma <gamma> - Sets gamma
93736851e7fSLois Curfman McInnes .  -snes_ksp_ew_alpha <alpha> - Sets alpha
93836851e7fSLois Curfman McInnes .  -snes_ksp_ew_alpha2 <alpha2> - Sets alpha2
93936851e7fSLois Curfman McInnes -  -snes_ksp_ew_threshold <threshold> - Sets threshold
94082738288SBarry Smith 
94111ca99fdSLois Curfman McInnes    Notes:
942ec5066bdSBarry Smith    To see all options, run your program with the -help option or consult the users manual
943ec5066bdSBarry Smith 
944ec5066bdSBarry Smith    Notes:
945a5b23f4aSJose E. Roman       SNES supports three approaches for computing (approximate) Jacobians: user provided via SNESSetJacobian(), matrix free, and computing explicitly with
946ec5066bdSBarry Smith       finite differences and coloring using MatFDColoring. It is also possible to use automatic differentiation and the MatFDColoring object.
94783e2fdc7SBarry Smith 
94836851e7fSLois Curfman McInnes    Level: beginner
94936851e7fSLois Curfman McInnes 
950db781477SPatrick Sanan .seealso: `SNESSetOptionsPrefix()`, `SNESResetFromOptions()`, `SNES`, `SNESCreate()`
9519b94acceSBarry Smith @*/
9527087cfbeSBarry Smith PetscErrorCode  SNESSetFromOptions(SNES snes)
9539b94acceSBarry Smith {
9548afaa268SBarry Smith   PetscBool      flg,pcset,persist,set;
955d8f46077SPeter Brune   PetscInt       i,indx,lag,grids;
95604d7464bSBarry Smith   const char     *deft        = SNESNEWTONLS;
957649ef022SMatthew Knepley   const char     *convtests[] = {"default","skip","correct_pressure"};
95885385478SLisandro Dalcin   SNESKSPEW      *kctx        = NULL;
9590f0abf79SStefano Zampini   char           type[256], monfilename[PETSC_MAX_PATH_LEN], ewprefix[256];
960c40d0f55SPeter Brune   PCSide         pcside;
961a64e098fSPeter Brune   const char     *optionsprefix;
9629b94acceSBarry Smith 
9633a40ed3dSBarry Smith   PetscFunctionBegin;
9640700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
9659566063dSJacob Faibussowitsch   PetscCall(SNESRegisterAll());
966d0609cedSBarry Smith   PetscObjectOptionsBegin((PetscObject)snes);
967639ff905SBarry Smith   if (((PetscObject)snes)->type_name) deft = ((PetscObject)snes)->type_name;
9689566063dSJacob Faibussowitsch   PetscCall(PetscOptionsFList("-snes_type","Nonlinear solver method","SNESSetType",SNESList,deft,type,256,&flg));
969d64ed03dSBarry Smith   if (flg) {
9709566063dSJacob Faibussowitsch     PetscCall(SNESSetType(snes,type));
9717adad957SLisandro Dalcin   } else if (!((PetscObject)snes)->type_name) {
9729566063dSJacob Faibussowitsch     PetscCall(SNESSetType(snes,deft));
973d64ed03dSBarry Smith   }
9749566063dSJacob Faibussowitsch   PetscCall(PetscOptionsReal("-snes_stol","Stop if step length less than","SNESSetTolerances",snes->stol,&snes->stol,NULL));
9759566063dSJacob Faibussowitsch   PetscCall(PetscOptionsReal("-snes_atol","Stop if function norm less than","SNESSetTolerances",snes->abstol,&snes->abstol,NULL));
976186905e3SBarry Smith 
9779566063dSJacob Faibussowitsch   PetscCall(PetscOptionsReal("-snes_rtol","Stop if decrease in function norm less than","SNESSetTolerances",snes->rtol,&snes->rtol,NULL));
9789566063dSJacob Faibussowitsch   PetscCall(PetscOptionsReal("-snes_divergence_tolerance","Stop if residual norm increases by this factor","SNESSetDivergenceTolerance",snes->divtol,&snes->divtol,NULL));
9799566063dSJacob Faibussowitsch   PetscCall(PetscOptionsInt("-snes_max_it","Maximum iterations","SNESSetTolerances",snes->max_its,&snes->max_its,NULL));
9809566063dSJacob Faibussowitsch   PetscCall(PetscOptionsInt("-snes_max_funcs","Maximum function evaluations","SNESSetTolerances",snes->max_funcs,&snes->max_funcs,NULL));
9819566063dSJacob Faibussowitsch   PetscCall(PetscOptionsInt("-snes_max_fail","Maximum nonlinear step failures","SNESSetMaxNonlinearStepFailures",snes->maxFailures,&snes->maxFailures,NULL));
9829566063dSJacob Faibussowitsch   PetscCall(PetscOptionsInt("-snes_max_linear_solve_fail","Maximum failures in linear solves allowed","SNESSetMaxLinearSolveFailures",snes->maxLinearSolveFailures,&snes->maxLinearSolveFailures,NULL));
9839566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-snes_error_if_not_converged","Generate error if solver does not converge","SNESSetErrorIfNotConverged",snes->errorifnotconverged,&snes->errorifnotconverged,NULL));
9849566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-snes_force_iteration","Force SNESSolve() to take at least one iteration","SNESSetForceIteration",snes->forceiteration,&snes->forceiteration,NULL));
9859566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-snes_check_jacobian_domain_error","Check Jacobian domain error after Jacobian evaluation","SNESCheckJacobianDomainError",snes->checkjacdomainerror,&snes->checkjacdomainerror,NULL));
98685385478SLisandro Dalcin 
9879566063dSJacob Faibussowitsch   PetscCall(PetscOptionsInt("-snes_lag_preconditioner","How often to rebuild preconditioner","SNESSetLagPreconditioner",snes->lagpreconditioner,&lag,&flg));
988a8054027SBarry Smith   if (flg) {
9895f80ce2aSJacob 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");
9909566063dSJacob Faibussowitsch     PetscCall(SNESSetLagPreconditioner(snes,lag));
991a8054027SBarry Smith   }
9929566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-snes_lag_preconditioner_persists","Preconditioner lagging through multiple SNES solves","SNESSetLagPreconditionerPersists",snes->lagjac_persist,&persist,&flg));
9931baa6e33SBarry Smith   if (flg) PetscCall(SNESSetLagPreconditionerPersists(snes,persist));
9949566063dSJacob Faibussowitsch   PetscCall(PetscOptionsInt("-snes_lag_jacobian","How often to rebuild Jacobian","SNESSetLagJacobian",snes->lagjacobian,&lag,&flg));
995e35cf81dSBarry Smith   if (flg) {
9965f80ce2aSJacob 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");
9979566063dSJacob Faibussowitsch     PetscCall(SNESSetLagJacobian(snes,lag));
998e35cf81dSBarry Smith   }
9999566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-snes_lag_jacobian_persists","Jacobian lagging through multiple SNES solves","SNESSetLagJacobianPersists",snes->lagjac_persist,&persist,&flg));
10001baa6e33SBarry Smith   if (flg) PetscCall(SNESSetLagJacobianPersists(snes,persist));
100137ec4e1aSPeter Brune 
10029566063dSJacob Faibussowitsch   PetscCall(PetscOptionsInt("-snes_grid_sequence","Use grid sequencing to generate initial guess","SNESSetGridSequence",snes->gridsequence,&grids,&flg));
10031baa6e33SBarry Smith   if (flg) PetscCall(SNESSetGridSequence(snes,grids));
1004a8054027SBarry Smith 
10059566063dSJacob Faibussowitsch   PetscCall(PetscOptionsEList("-snes_convergence_test","Convergence test","SNESSetConvergenceTest",convtests,sizeof(convtests)/sizeof(char*),"default",&indx,&flg));
100685385478SLisandro Dalcin   if (flg) {
100785385478SLisandro Dalcin     switch (indx) {
10089566063dSJacob Faibussowitsch     case 0: PetscCall(SNESSetConvergenceTest(snes,SNESConvergedDefault,NULL,NULL)); break;
10099566063dSJacob Faibussowitsch     case 1: PetscCall(SNESSetConvergenceTest(snes,SNESConvergedSkip,NULL,NULL)); break;
10109566063dSJacob Faibussowitsch     case 2: PetscCall(SNESSetConvergenceTest(snes,SNESConvergedCorrectPressure,NULL,NULL)); break;
101185385478SLisandro Dalcin     }
101285385478SLisandro Dalcin   }
101385385478SLisandro Dalcin 
10149566063dSJacob Faibussowitsch   PetscCall(PetscOptionsEList("-snes_norm_schedule","SNES Norm schedule","SNESSetNormSchedule",SNESNormSchedules,5,"function",&indx,&flg));
10159566063dSJacob Faibussowitsch   if (flg) PetscCall(SNESSetNormSchedule(snes,(SNESNormSchedule)indx));
1016fdacfa88SPeter Brune 
10179566063dSJacob Faibussowitsch   PetscCall(PetscOptionsEList("-snes_function_type","SNES Norm schedule","SNESSetFunctionType",SNESFunctionTypes,2,"unpreconditioned",&indx,&flg));
10189566063dSJacob Faibussowitsch   if (flg) PetscCall(SNESSetFunctionType(snes,(SNESFunctionType)indx));
1019186905e3SBarry Smith 
102085385478SLisandro Dalcin   kctx = (SNESKSPEW*)snes->kspconvctx;
102185385478SLisandro Dalcin 
10229566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-snes_ksp_ew","Use Eisentat-Walker linear system convergence test","SNESKSPSetUseEW",snes->ksp_ewconv,&snes->ksp_ewconv,NULL));
1023186905e3SBarry Smith 
10240f0abf79SStefano Zampini   PetscCall(SNESGetOptionsPrefix(snes,&optionsprefix));
10250f0abf79SStefano Zampini   PetscCall(PetscSNPrintf(ewprefix,sizeof(ewprefix),"%s%s",optionsprefix ? optionsprefix : "","snes_"));
10260f0abf79SStefano Zampini   PetscCall(SNESEWSetFromOptions_Private(kctx,PetscObjectComm((PetscObject)snes),ewprefix));
10270f0abf79SStefano Zampini 
10289566063dSJacob Faibussowitsch   PetscCall(PetscOptionsInt("-snes_ksp_ew_version","Version 1, 2 or 3","SNESKSPSetParametersEW",kctx->version,&kctx->version,NULL));
10299566063dSJacob Faibussowitsch   PetscCall(PetscOptionsReal("-snes_ksp_ew_rtol0","0 <= rtol0 < 1","SNESKSPSetParametersEW",kctx->rtol_0,&kctx->rtol_0,NULL));
10309566063dSJacob Faibussowitsch   PetscCall(PetscOptionsReal("-snes_ksp_ew_rtolmax","0 <= rtolmax < 1","SNESKSPSetParametersEW",kctx->rtol_max,&kctx->rtol_max,NULL));
10319566063dSJacob Faibussowitsch   PetscCall(PetscOptionsReal("-snes_ksp_ew_gamma","0 <= gamma <= 1","SNESKSPSetParametersEW",kctx->gamma,&kctx->gamma,NULL));
10329566063dSJacob Faibussowitsch   PetscCall(PetscOptionsReal("-snes_ksp_ew_alpha","1 < alpha <= 2","SNESKSPSetParametersEW",kctx->alpha,&kctx->alpha,NULL));
10339566063dSJacob Faibussowitsch   PetscCall(PetscOptionsReal("-snes_ksp_ew_alpha2","alpha2","SNESKSPSetParametersEW",kctx->alpha2,&kctx->alpha2,NULL));
10349566063dSJacob Faibussowitsch   PetscCall(PetscOptionsReal("-snes_ksp_ew_threshold","0 < threshold < 1","SNESKSPSetParametersEW",kctx->threshold,&kctx->threshold,NULL));
1035186905e3SBarry Smith 
103690d69ab7SBarry Smith   flg  = PETSC_FALSE;
10379566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-snes_monitor_cancel","Remove all monitors","SNESMonitorCancel",flg,&flg,&set));
10389566063dSJacob Faibussowitsch   if (set && flg) PetscCall(SNESMonitorCancel(snes));
1039eabae89aSBarry Smith 
10409566063dSJacob Faibussowitsch   PetscCall(SNESMonitorSetFromOptions(snes,"-snes_monitor","Monitor norm of function","SNESMonitorDefault",SNESMonitorDefault,SNESMonitorDefaultSetUp));
10419566063dSJacob Faibussowitsch   PetscCall(SNESMonitorSetFromOptions(snes,"-snes_monitor_short","Monitor norm of function with fewer digits","SNESMonitorDefaultShort",SNESMonitorDefaultShort,NULL));
10429566063dSJacob Faibussowitsch   PetscCall(SNESMonitorSetFromOptions(snes,"-snes_monitor_range","Monitor range of elements of function","SNESMonitorRange",SNESMonitorRange,NULL));
1043eabae89aSBarry Smith 
10449566063dSJacob Faibussowitsch   PetscCall(SNESMonitorSetFromOptions(snes,"-snes_monitor_ratio","Monitor ratios of the norm of function for consecutive steps","SNESMonitorRatio",SNESMonitorRatio,SNESMonitorRatioSetUp));
10459566063dSJacob Faibussowitsch   PetscCall(SNESMonitorSetFromOptions(snes,"-snes_monitor_field","Monitor norm of function (split into fields)","SNESMonitorDefaultField",SNESMonitorDefaultField,NULL));
10469566063dSJacob Faibussowitsch   PetscCall(SNESMonitorSetFromOptions(snes,"-snes_monitor_solution","View solution at each iteration","SNESMonitorSolution",SNESMonitorSolution,NULL));
10479566063dSJacob Faibussowitsch   PetscCall(SNESMonitorSetFromOptions(snes,"-snes_monitor_solution_update","View correction at each iteration","SNESMonitorSolutionUpdate",SNESMonitorSolutionUpdate,NULL));
10489566063dSJacob Faibussowitsch   PetscCall(SNESMonitorSetFromOptions(snes,"-snes_monitor_residual","View residual at each iteration","SNESMonitorResidual",SNESMonitorResidual,NULL));
10499566063dSJacob Faibussowitsch   PetscCall(SNESMonitorSetFromOptions(snes,"-snes_monitor_jacupdate_spectrum","Print the change in the spectrum of the Jacobian","SNESMonitorJacUpdateSpectrum",SNESMonitorJacUpdateSpectrum,NULL));
10509566063dSJacob Faibussowitsch   PetscCall(SNESMonitorSetFromOptions(snes,"-snes_monitor_fields","Monitor norm of function per field","SNESMonitorSet",SNESMonitorFields,NULL));
10519566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-snes_monitor_pause_final", "Pauses all draw monitors at the final iterate", "SNESMonitorPauseFinal_Internal", PETSC_FALSE, &snes->pauseFinal, NULL));
10522db13446SMatthew G. Knepley 
10539566063dSJacob Faibussowitsch   PetscCall(PetscOptionsString("-snes_monitor_python","Use Python function","SNESMonitorSet",NULL,monfilename,sizeof(monfilename),&flg));
10549566063dSJacob Faibussowitsch   if (flg) PetscCall(PetscPythonMonitorSet((PetscObject)snes,monfilename));
10555180491cSLisandro Dalcin 
105690d69ab7SBarry Smith   flg  = PETSC_FALSE;
10579566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-snes_monitor_lg_range","Plot function range at each iteration","SNESMonitorLGRange",flg,&flg,NULL));
1058459f5d12SBarry Smith   if (flg) {
1059459f5d12SBarry Smith     PetscViewer ctx;
1060e24b481bSBarry Smith 
10619566063dSJacob Faibussowitsch     PetscCall(PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,&ctx));
10629566063dSJacob Faibussowitsch     PetscCall(SNESMonitorSet(snes,SNESMonitorLGRange,ctx,(PetscErrorCode (*)(void**))PetscViewerDestroy));
1063459f5d12SBarry Smith   }
10642e7541e6SPeter Brune 
106590d69ab7SBarry Smith   flg  = PETSC_FALSE;
10669566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-snes_converged_reason_view_cancel","Remove all converged reason viewers","SNESConvergedReasonViewCancel",flg,&flg,&set));
10679566063dSJacob Faibussowitsch   if (set && flg) PetscCall(SNESConvergedReasonViewCancel(snes));
1068c4421ceaSFande Kong 
1069c4421ceaSFande Kong   flg  = PETSC_FALSE;
10709566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-snes_fd","Use finite differences (slow) to compute Jacobian","SNESComputeJacobianDefault",flg,&flg,NULL));
10714b27c08aSLois Curfman McInnes   if (flg) {
10726cab3a1bSJed Brown     void    *functx;
1073b1f624c7SBarry Smith     DM      dm;
1074b1f624c7SBarry Smith     DMSNES  sdm;
10759566063dSJacob Faibussowitsch     PetscCall(SNESGetDM(snes,&dm));
10769566063dSJacob Faibussowitsch     PetscCall(DMGetDMSNES(dm,&sdm));
1077b1f624c7SBarry Smith     sdm->jacobianctx = NULL;
10789566063dSJacob Faibussowitsch     PetscCall(SNESGetFunction(snes,NULL,NULL,&functx));
10799566063dSJacob Faibussowitsch     PetscCall(SNESSetJacobian(snes,snes->jacobian,snes->jacobian_pre,SNESComputeJacobianDefault,functx));
10809566063dSJacob Faibussowitsch     PetscCall(PetscInfo(snes,"Setting default finite difference Jacobian matrix\n"));
10819b94acceSBarry Smith   }
1082639f9d9dSBarry Smith 
108344848bc4SPeter Brune   flg  = PETSC_FALSE;
10849566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-snes_fd_function","Use finite differences (slow) to compute function from user objective","SNESObjectiveComputeFunctionDefaultFD",flg,&flg,NULL));
10851baa6e33SBarry Smith   if (flg) PetscCall(SNESSetFunction(snes,NULL,SNESObjectiveComputeFunctionDefaultFD,NULL));
108697584545SPeter Brune 
108797584545SPeter Brune   flg  = PETSC_FALSE;
10889566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-snes_fd_color","Use finite differences with coloring to compute Jacobian","SNESComputeJacobianDefaultColor",flg,&flg,NULL));
108944848bc4SPeter Brune   if (flg) {
1090c52e227fSPeter Brune     DM             dm;
1091c52e227fSPeter Brune     DMSNES         sdm;
10929566063dSJacob Faibussowitsch     PetscCall(SNESGetDM(snes,&dm));
10939566063dSJacob Faibussowitsch     PetscCall(DMGetDMSNES(dm,&sdm));
1094aace71b7SPeter Brune     sdm->jacobianctx = NULL;
10959566063dSJacob Faibussowitsch     PetscCall(SNESSetJacobian(snes,snes->jacobian,snes->jacobian_pre,SNESComputeJacobianDefaultColor,NULL));
10969566063dSJacob Faibussowitsch     PetscCall(PetscInfo(snes,"Setting default finite difference coloring Jacobian matrix\n"));
109744848bc4SPeter Brune   }
109844848bc4SPeter Brune 
1099aa3661deSLisandro Dalcin   flg  = PETSC_FALSE;
11009566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-snes_mf_operator","Use a Matrix-Free Jacobian with user-provided preconditioner matrix","SNESSetUseMatrixFree",PETSC_FALSE,&snes->mf_operator,&flg));
1101d8f46077SPeter Brune   if (flg && snes->mf_operator) {
1102a8248277SBarry Smith     snes->mf_operator = PETSC_TRUE;
1103d8f46077SPeter Brune     snes->mf          = PETSC_TRUE;
1104a8248277SBarry Smith   }
1105aa3661deSLisandro Dalcin   flg  = PETSC_FALSE;
11069566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-snes_mf","Use a Matrix-Free Jacobian with no preconditioner matrix","SNESSetUseMatrixFree",PETSC_FALSE,&snes->mf,&flg));
1107d8f46077SPeter Brune   if (!flg && snes->mf_operator) snes->mf = PETSC_TRUE;
11089566063dSJacob Faibussowitsch   PetscCall(PetscOptionsInt("-snes_mf_version","Matrix-Free routines version 1 or 2","None",snes->mf_version,&snes->mf_version,NULL));
1109d28543b3SPeter Brune 
1110c40d0f55SPeter Brune   flg  = PETSC_FALSE;
11119566063dSJacob Faibussowitsch   PetscCall(SNESGetNPCSide(snes,&pcside));
11129566063dSJacob Faibussowitsch   PetscCall(PetscOptionsEnum("-snes_npc_side","SNES nonlinear preconditioner side","SNESSetNPCSide",PCSides,(PetscEnum)pcside,(PetscEnum*)&pcside,&flg));
11139566063dSJacob Faibussowitsch   if (flg) PetscCall(SNESSetNPCSide(snes,pcside));
1114c40d0f55SPeter Brune 
1115e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
11168a70d858SHong Zhang   /*
11178a70d858SHong Zhang     Publish convergence information using SAWs
11188a70d858SHong Zhang   */
11198a70d858SHong Zhang   flg  = PETSC_FALSE;
11209566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-snes_monitor_saws","Publish SNES progress using SAWs","SNESMonitorSet",flg,&flg,NULL));
11218a70d858SHong Zhang   if (flg) {
11228a70d858SHong Zhang     void *ctx;
11239566063dSJacob Faibussowitsch     PetscCall(SNESMonitorSAWsCreate(snes,&ctx));
11249566063dSJacob Faibussowitsch     PetscCall(SNESMonitorSet(snes,SNESMonitorSAWs,ctx,SNESMonitorSAWsDestroy));
11258a70d858SHong Zhang   }
11268a70d858SHong Zhang #endif
11278a70d858SHong Zhang #if defined(PETSC_HAVE_SAWS)
1128b90c6cbeSBarry Smith   {
1129b90c6cbeSBarry Smith   PetscBool set;
1130b90c6cbeSBarry Smith   flg  = PETSC_FALSE;
11319566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-snes_saws_block","Block for SAWs at end of SNESSolve","PetscObjectSAWsBlock",((PetscObject)snes)->amspublishblock,&flg,&set));
11321baa6e33SBarry Smith   if (set) PetscCall(PetscObjectSAWsSetBlock((PetscObject)snes,flg));
1133b90c6cbeSBarry Smith   }
1134b90c6cbeSBarry Smith #endif
1135b90c6cbeSBarry Smith 
113676b2cf59SMatthew Knepley   for (i = 0; i < numberofsetfromoptions; i++) {
11379566063dSJacob Faibussowitsch     PetscCall((*othersetfromoptions[i])(snes));
113876b2cf59SMatthew Knepley   }
113976b2cf59SMatthew Knepley 
11401baa6e33SBarry Smith   if (snes->ops->setfromoptions) PetscCall((*snes->ops->setfromoptions)(PetscOptionsObject,snes));
11415d973c19SBarry Smith 
11425d973c19SBarry Smith   /* process any options handlers added with PetscObjectAddOptionsHandler() */
11439566063dSJacob Faibussowitsch   PetscCall(PetscObjectProcessOptionsHandlers(PetscOptionsObject,(PetscObject)snes));
1144d0609cedSBarry Smith   PetscOptionsEnd();
11454bbc92c1SBarry Smith 
1146d8d34be6SBarry Smith   if (snes->linesearch) {
11479566063dSJacob Faibussowitsch     PetscCall(SNESGetLineSearch(snes, &snes->linesearch));
11489566063dSJacob Faibussowitsch     PetscCall(SNESLineSearchSetFromOptions(snes->linesearch));
1149d8d34be6SBarry Smith   }
11509e764e56SPeter Brune 
11516aa5e7e9SBarry Smith   if (snes->usesksp) {
11529566063dSJacob Faibussowitsch     if (!snes->ksp) PetscCall(SNESGetKSP(snes,&snes->ksp));
11539566063dSJacob Faibussowitsch     PetscCall(KSPSetOperators(snes->ksp,snes->jacobian,snes->jacobian_pre));
11549566063dSJacob Faibussowitsch     PetscCall(KSPSetFromOptions(snes->ksp));
11556aa5e7e9SBarry Smith   }
11566991f827SBarry Smith 
1157b5badacbSBarry Smith   /* if user has set the SNES NPC type via options database, create it. */
11589566063dSJacob Faibussowitsch   PetscCall(SNESGetOptionsPrefix(snes, &optionsprefix));
11599566063dSJacob Faibussowitsch   PetscCall(PetscOptionsHasName(((PetscObject)snes)->options,optionsprefix, "-npc_snes_type", &pcset));
1160efd4aadfSBarry Smith   if (pcset && (!snes->npc)) {
11619566063dSJacob Faibussowitsch     PetscCall(SNESGetNPC(snes, &snes->npc));
116251e86f29SPeter Brune   }
11631baa6e33SBarry Smith   if (snes->npc) PetscCall(SNESSetFromOptions(snes->npc));
1164b3cd9a81SMatthew G. Knepley   snes->setfromoptionscalled++;
1165b3cd9a81SMatthew G. Knepley   PetscFunctionReturn(0);
1166b3cd9a81SMatthew G. Knepley }
1167b3cd9a81SMatthew G. Knepley 
1168b3cd9a81SMatthew G. Knepley /*@
1169b3cd9a81SMatthew G. Knepley    SNESResetFromOptions - Sets various SNES and KSP parameters from user options ONLY if the SNES was previously set from options
1170b3cd9a81SMatthew G. Knepley 
1171b3cd9a81SMatthew G. Knepley    Collective on SNES
1172b3cd9a81SMatthew G. Knepley 
1173b3cd9a81SMatthew G. Knepley    Input Parameter:
1174b3cd9a81SMatthew G. Knepley .  snes - the SNES context
1175b3cd9a81SMatthew G. Knepley 
1176b3cd9a81SMatthew G. Knepley    Level: beginner
1177b3cd9a81SMatthew G. Knepley 
1178db781477SPatrick Sanan .seealso: `SNESSetFromOptions()`, `SNESSetOptionsPrefix()`
1179b3cd9a81SMatthew G. Knepley @*/
1180b3cd9a81SMatthew G. Knepley PetscErrorCode SNESResetFromOptions(SNES snes)
1181b3cd9a81SMatthew G. Knepley {
1182b3cd9a81SMatthew G. Knepley   PetscFunctionBegin;
11839566063dSJacob Faibussowitsch   if (snes->setfromoptionscalled) PetscCall(SNESSetFromOptions(snes));
11843a40ed3dSBarry Smith   PetscFunctionReturn(0);
11859b94acceSBarry Smith }
11869b94acceSBarry Smith 
1187bb9467b5SJed Brown /*@C
1188d25893d9SBarry Smith    SNESSetComputeApplicationContext - Sets an optional function to compute a user-defined context for
1189d25893d9SBarry Smith    the nonlinear solvers.
1190d25893d9SBarry Smith 
1191d25893d9SBarry Smith    Logically Collective on SNES
1192d25893d9SBarry Smith 
1193d25893d9SBarry Smith    Input Parameters:
1194d25893d9SBarry Smith +  snes - the SNES context
1195d25893d9SBarry Smith .  compute - function to compute the context
1196d25893d9SBarry Smith -  destroy - function to destroy the context
1197d25893d9SBarry Smith 
1198d25893d9SBarry Smith    Level: intermediate
1199d25893d9SBarry Smith 
1200bb9467b5SJed Brown    Notes:
1201bb9467b5SJed Brown    This function is currently not available from Fortran.
1202bb9467b5SJed Brown 
1203db781477SPatrick Sanan .seealso: `SNESGetApplicationContext()`, `SNESSetComputeApplicationContext()`, `SNESGetApplicationContext()`
1204d25893d9SBarry Smith @*/
1205d25893d9SBarry Smith PetscErrorCode  SNESSetComputeApplicationContext(SNES snes,PetscErrorCode (*compute)(SNES,void**),PetscErrorCode (*destroy)(void**))
1206d25893d9SBarry Smith {
1207d25893d9SBarry Smith   PetscFunctionBegin;
1208d25893d9SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
1209d25893d9SBarry Smith   snes->ops->usercompute = compute;
1210d25893d9SBarry Smith   snes->ops->userdestroy = destroy;
1211d25893d9SBarry Smith   PetscFunctionReturn(0);
1212d25893d9SBarry Smith }
1213a847f771SSatish Balay 
1214b07ff414SBarry Smith /*@
12159b94acceSBarry Smith    SNESSetApplicationContext - Sets the optional user-defined context for
12169b94acceSBarry Smith    the nonlinear solvers.
12179b94acceSBarry Smith 
12183f9fe445SBarry Smith    Logically Collective on SNES
1219fee21e36SBarry Smith 
1220c7afd0dbSLois Curfman McInnes    Input Parameters:
1221c7afd0dbSLois Curfman McInnes +  snes - the SNES context
1222c7afd0dbSLois Curfman McInnes -  usrP - optional user context
1223c7afd0dbSLois Curfman McInnes 
122436851e7fSLois Curfman McInnes    Level: intermediate
122536851e7fSLois Curfman McInnes 
122695452b02SPatrick Sanan    Fortran Notes:
122795452b02SPatrick Sanan     To use this from Fortran you must write a Fortran interface definition for this
1228daf670e6SBarry Smith     function that tells Fortran the Fortran derived data type that you are passing in as the ctx argument.
1229daf670e6SBarry Smith 
1230db781477SPatrick Sanan .seealso: `SNESGetApplicationContext()`
12319b94acceSBarry Smith @*/
12327087cfbeSBarry Smith PetscErrorCode  SNESSetApplicationContext(SNES snes,void *usrP)
12339b94acceSBarry Smith {
1234b07ff414SBarry Smith   KSP            ksp;
12351b2093e4SBarry Smith 
12363a40ed3dSBarry Smith   PetscFunctionBegin;
12370700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
12389566063dSJacob Faibussowitsch   PetscCall(SNESGetKSP(snes,&ksp));
12399566063dSJacob Faibussowitsch   PetscCall(KSPSetApplicationContext(ksp,usrP));
12409b94acceSBarry Smith   snes->user = usrP;
12413a40ed3dSBarry Smith   PetscFunctionReturn(0);
12429b94acceSBarry Smith }
124374679c65SBarry Smith 
1244b07ff414SBarry Smith /*@
12459b94acceSBarry Smith    SNESGetApplicationContext - Gets the user-defined context for the
12469b94acceSBarry Smith    nonlinear solvers.
12479b94acceSBarry Smith 
1248c7afd0dbSLois Curfman McInnes    Not Collective
1249c7afd0dbSLois Curfman McInnes 
12509b94acceSBarry Smith    Input Parameter:
12519b94acceSBarry Smith .  snes - SNES context
12529b94acceSBarry Smith 
12539b94acceSBarry Smith    Output Parameter:
12549b94acceSBarry Smith .  usrP - user context
12559b94acceSBarry Smith 
125695452b02SPatrick Sanan    Fortran Notes:
125795452b02SPatrick Sanan     To use this from Fortran you must write a Fortran interface definition for this
1258daf670e6SBarry Smith     function that tells Fortran the Fortran derived data type that you are passing in as the ctx argument.
1259daf670e6SBarry Smith 
126036851e7fSLois Curfman McInnes    Level: intermediate
126136851e7fSLois Curfman McInnes 
1262db781477SPatrick Sanan .seealso: `SNESSetApplicationContext()`
12639b94acceSBarry Smith @*/
1264e71120c6SJed Brown PetscErrorCode  SNESGetApplicationContext(SNES snes,void *usrP)
12659b94acceSBarry Smith {
12663a40ed3dSBarry Smith   PetscFunctionBegin;
12670700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
1268e71120c6SJed Brown   *(void**)usrP = snes->user;
12693a40ed3dSBarry Smith   PetscFunctionReturn(0);
12709b94acceSBarry Smith }
127174679c65SBarry Smith 
12729b94acceSBarry Smith /*@
1273ec5066bdSBarry Smith    SNESSetUseMatrixFree - indicates that SNES should use matrix free finite difference matrix vector products internally to apply the Jacobian.
12743565c898SBarry Smith 
12753565c898SBarry Smith    Collective on SNES
12763565c898SBarry Smith 
12773565c898SBarry Smith    Input Parameters:
12783565c898SBarry Smith +  snes - SNES context
12794ddffce6SLisandro Dalcin .  mf_operator - use matrix-free only for the Amat used by SNESSetJacobian(), this means the user provided Pmat will continue to be used
12804ddffce6SLisandro 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
12813565c898SBarry Smith 
12823565c898SBarry Smith    Options Database:
12833565c898SBarry Smith + -snes_mf - use matrix free for both the mat and pmat operator
1284ec5066bdSBarry Smith . -snes_mf_operator - use matrix free only for the mat operator
1285ec5066bdSBarry Smith . -snes_fd_color - compute the Jacobian via coloring and finite differences.
1286ec5066bdSBarry Smith - -snes_fd - compute the Jacobian via finite differences (slow)
12873565c898SBarry Smith 
12883565c898SBarry Smith    Level: intermediate
12893565c898SBarry Smith 
1290ec5066bdSBarry Smith    Notes:
1291a5b23f4aSJose E. Roman       SNES supports three approaches for computing (approximate) Jacobians: user provided via SNESSetJacobian(), matrix free, and computing explicitly with
1292ec5066bdSBarry Smith       finite differences and coloring using MatFDColoring. It is also possible to use automatic differentiation and the MatFDColoring object.
1293ec5066bdSBarry Smith 
1294db781477SPatrick Sanan .seealso: `SNESGetUseMatrixFree()`, `MatCreateSNESMF()`, `SNESComputeJacobianDefaultColor()`
12953565c898SBarry Smith @*/
12963565c898SBarry Smith PetscErrorCode  SNESSetUseMatrixFree(SNES snes,PetscBool mf_operator,PetscBool mf)
12973565c898SBarry Smith {
12983565c898SBarry Smith   PetscFunctionBegin;
12993565c898SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
130088b4c220SStefano Zampini   PetscValidLogicalCollectiveBool(snes,mf_operator,2);
130188b4c220SStefano Zampini   PetscValidLogicalCollectiveBool(snes,mf,3);
13024ddffce6SLisandro Dalcin   snes->mf          = mf_operator ? PETSC_TRUE : mf;
13033565c898SBarry Smith   snes->mf_operator = mf_operator;
13043565c898SBarry Smith   PetscFunctionReturn(0);
13053565c898SBarry Smith }
13063565c898SBarry Smith 
13073565c898SBarry Smith /*@
1308ec5066bdSBarry Smith    SNESGetUseMatrixFree - indicates if the SNES uses matrix free finite difference matrix vector products to apply the Jacobian.
13093565c898SBarry Smith 
13103565c898SBarry Smith    Collective on SNES
13113565c898SBarry Smith 
13123565c898SBarry Smith    Input Parameter:
13133565c898SBarry Smith .  snes - SNES context
13143565c898SBarry Smith 
13153565c898SBarry Smith    Output Parameters:
13164ddffce6SLisandro Dalcin +  mf_operator - use matrix-free only for the Amat used by SNESSetJacobian(), this means the user provided Pmat will continue to be used
13174ddffce6SLisandro 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
13183565c898SBarry Smith 
13193565c898SBarry Smith    Options Database:
13203565c898SBarry Smith + -snes_mf - use matrix free for both the mat and pmat operator
13213565c898SBarry Smith - -snes_mf_operator - use matrix free only for the mat operator
13223565c898SBarry Smith 
13233565c898SBarry Smith    Level: intermediate
13243565c898SBarry Smith 
1325db781477SPatrick Sanan .seealso: `SNESSetUseMatrixFree()`, `MatCreateSNESMF()`
13263565c898SBarry Smith @*/
13273565c898SBarry Smith PetscErrorCode  SNESGetUseMatrixFree(SNES snes,PetscBool *mf_operator,PetscBool *mf)
13283565c898SBarry Smith {
13293565c898SBarry Smith   PetscFunctionBegin;
13303565c898SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
13313565c898SBarry Smith   if (mf)          *mf          = snes->mf;
13323565c898SBarry Smith   if (mf_operator) *mf_operator = snes->mf_operator;
13333565c898SBarry Smith   PetscFunctionReturn(0);
13343565c898SBarry Smith }
13353565c898SBarry Smith 
13363565c898SBarry Smith /*@
1337c8228a4eSBarry Smith    SNESGetIterationNumber - Gets the number of nonlinear iterations completed
1338c8228a4eSBarry Smith    at this time.
13399b94acceSBarry Smith 
1340c7afd0dbSLois Curfman McInnes    Not Collective
1341c7afd0dbSLois Curfman McInnes 
13429b94acceSBarry Smith    Input Parameter:
13439b94acceSBarry Smith .  snes - SNES context
13449b94acceSBarry Smith 
13459b94acceSBarry Smith    Output Parameter:
13469b94acceSBarry Smith .  iter - iteration number
13479b94acceSBarry Smith 
1348c8228a4eSBarry Smith    Notes:
1349c8228a4eSBarry Smith    For example, during the computation of iteration 2 this would return 1.
1350c8228a4eSBarry Smith 
1351c8228a4eSBarry Smith    This is useful for using lagged Jacobians (where one does not recompute the
135208405cd6SLois Curfman McInnes    Jacobian at each SNES iteration). For example, the code
135308405cd6SLois Curfman McInnes .vb
135408405cd6SLois Curfman McInnes       ierr = SNESGetIterationNumber(snes,&it);
135508405cd6SLois Curfman McInnes       if (!(it % 2)) {
135608405cd6SLois Curfman McInnes         [compute Jacobian here]
135708405cd6SLois Curfman McInnes       }
135808405cd6SLois Curfman McInnes .ve
1359c8228a4eSBarry Smith    can be used in your ComputeJacobian() function to cause the Jacobian to be
136008405cd6SLois Curfman McInnes    recomputed every second SNES iteration.
1361c8228a4eSBarry Smith 
1362c04deec6SBarry Smith    After the SNES solve is complete this will return the number of nonlinear iterations used.
1363c04deec6SBarry Smith 
136436851e7fSLois Curfman McInnes    Level: intermediate
136536851e7fSLois Curfman McInnes 
1366db781477SPatrick Sanan .seealso: `SNESGetLinearSolveIterations()`
13679b94acceSBarry Smith @*/
13687087cfbeSBarry Smith PetscErrorCode  SNESGetIterationNumber(SNES snes,PetscInt *iter)
13699b94acceSBarry Smith {
13703a40ed3dSBarry Smith   PetscFunctionBegin;
13710700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
13724482741eSBarry Smith   PetscValidIntPointer(iter,2);
13739b94acceSBarry Smith   *iter = snes->iter;
13743a40ed3dSBarry Smith   PetscFunctionReturn(0);
13759b94acceSBarry Smith }
137674679c65SBarry Smith 
1377360c497dSPeter Brune /*@
1378360c497dSPeter Brune    SNESSetIterationNumber - Sets the current iteration number.
1379360c497dSPeter Brune 
1380360c497dSPeter Brune    Not Collective
1381360c497dSPeter Brune 
1382d8d19677SJose E. Roman    Input Parameters:
1383a2b725a8SWilliam Gropp +  snes - SNES context
1384a2b725a8SWilliam Gropp -  iter - iteration number
1385360c497dSPeter Brune 
1386360c497dSPeter Brune    Level: developer
1387360c497dSPeter Brune 
1388db781477SPatrick Sanan .seealso: `SNESGetLinearSolveIterations()`
1389360c497dSPeter Brune @*/
1390360c497dSPeter Brune PetscErrorCode  SNESSetIterationNumber(SNES snes,PetscInt iter)
1391360c497dSPeter Brune {
1392360c497dSPeter Brune   PetscFunctionBegin;
1393360c497dSPeter Brune   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
13949566063dSJacob Faibussowitsch   PetscCall(PetscObjectSAWsTakeAccess((PetscObject)snes));
1395360c497dSPeter Brune   snes->iter = iter;
13969566063dSJacob Faibussowitsch   PetscCall(PetscObjectSAWsGrantAccess((PetscObject)snes));
1397360c497dSPeter Brune   PetscFunctionReturn(0);
1398360c497dSPeter Brune }
1399360c497dSPeter Brune 
14009b94acceSBarry Smith /*@
1401b850b91aSLisandro Dalcin    SNESGetNonlinearStepFailures - Gets the number of unsuccessful steps
14029b94acceSBarry Smith    attempted by the nonlinear solver.
14039b94acceSBarry Smith 
1404c7afd0dbSLois Curfman McInnes    Not Collective
1405c7afd0dbSLois Curfman McInnes 
14069b94acceSBarry Smith    Input Parameter:
14079b94acceSBarry Smith .  snes - SNES context
14089b94acceSBarry Smith 
14099b94acceSBarry Smith    Output Parameter:
14109b94acceSBarry Smith .  nfails - number of unsuccessful steps attempted
14119b94acceSBarry Smith 
1412c96a6f78SLois Curfman McInnes    Notes:
1413c96a6f78SLois Curfman McInnes    This counter is reset to zero for each successive call to SNESSolve().
1414c96a6f78SLois Curfman McInnes 
141536851e7fSLois Curfman McInnes    Level: intermediate
141636851e7fSLois Curfman McInnes 
1417db781477SPatrick Sanan .seealso: `SNESGetMaxLinearSolveFailures()`, `SNESGetLinearSolveIterations()`, `SNESSetMaxLinearSolveFailures()`, `SNESGetLinearSolveFailures()`,
1418db781477SPatrick Sanan           `SNESSetMaxNonlinearStepFailures()`, `SNESGetMaxNonlinearStepFailures()`
14199b94acceSBarry Smith @*/
14207087cfbeSBarry Smith PetscErrorCode  SNESGetNonlinearStepFailures(SNES snes,PetscInt *nfails)
14219b94acceSBarry Smith {
14223a40ed3dSBarry Smith   PetscFunctionBegin;
14230700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
14244482741eSBarry Smith   PetscValidIntPointer(nfails,2);
142550ffb88aSMatthew Knepley   *nfails = snes->numFailures;
142650ffb88aSMatthew Knepley   PetscFunctionReturn(0);
142750ffb88aSMatthew Knepley }
142850ffb88aSMatthew Knepley 
142950ffb88aSMatthew Knepley /*@
1430b850b91aSLisandro Dalcin    SNESSetMaxNonlinearStepFailures - Sets the maximum number of unsuccessful steps
143150ffb88aSMatthew Knepley    attempted by the nonlinear solver before it gives up.
143250ffb88aSMatthew Knepley 
143350ffb88aSMatthew Knepley    Not Collective
143450ffb88aSMatthew Knepley 
143550ffb88aSMatthew Knepley    Input Parameters:
143650ffb88aSMatthew Knepley +  snes     - SNES context
143750ffb88aSMatthew Knepley -  maxFails - maximum of unsuccessful steps
143850ffb88aSMatthew Knepley 
143950ffb88aSMatthew Knepley    Level: intermediate
144050ffb88aSMatthew Knepley 
1441db781477SPatrick Sanan .seealso: `SNESGetMaxLinearSolveFailures()`, `SNESGetLinearSolveIterations()`, `SNESSetMaxLinearSolveFailures()`, `SNESGetLinearSolveFailures()`,
1442db781477SPatrick Sanan           `SNESGetMaxNonlinearStepFailures()`, `SNESGetNonlinearStepFailures()`
144350ffb88aSMatthew Knepley @*/
14447087cfbeSBarry Smith PetscErrorCode  SNESSetMaxNonlinearStepFailures(SNES snes, PetscInt maxFails)
144550ffb88aSMatthew Knepley {
144650ffb88aSMatthew Knepley   PetscFunctionBegin;
14470700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
144850ffb88aSMatthew Knepley   snes->maxFailures = maxFails;
144950ffb88aSMatthew Knepley   PetscFunctionReturn(0);
145050ffb88aSMatthew Knepley }
145150ffb88aSMatthew Knepley 
145250ffb88aSMatthew Knepley /*@
1453b850b91aSLisandro Dalcin    SNESGetMaxNonlinearStepFailures - Gets the maximum number of unsuccessful steps
145450ffb88aSMatthew Knepley    attempted by the nonlinear solver before it gives up.
145550ffb88aSMatthew Knepley 
145650ffb88aSMatthew Knepley    Not Collective
145750ffb88aSMatthew Knepley 
145850ffb88aSMatthew Knepley    Input Parameter:
145950ffb88aSMatthew Knepley .  snes     - SNES context
146050ffb88aSMatthew Knepley 
146150ffb88aSMatthew Knepley    Output Parameter:
146250ffb88aSMatthew Knepley .  maxFails - maximum of unsuccessful steps
146350ffb88aSMatthew Knepley 
146450ffb88aSMatthew Knepley    Level: intermediate
146550ffb88aSMatthew Knepley 
1466db781477SPatrick Sanan .seealso: `SNESGetMaxLinearSolveFailures()`, `SNESGetLinearSolveIterations()`, `SNESSetMaxLinearSolveFailures()`, `SNESGetLinearSolveFailures()`,
1467db781477SPatrick Sanan           `SNESSetMaxNonlinearStepFailures()`, `SNESGetNonlinearStepFailures()`
146858ebbce7SBarry Smith 
146950ffb88aSMatthew Knepley @*/
14707087cfbeSBarry Smith PetscErrorCode  SNESGetMaxNonlinearStepFailures(SNES snes, PetscInt *maxFails)
147150ffb88aSMatthew Knepley {
147250ffb88aSMatthew Knepley   PetscFunctionBegin;
14730700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
14744482741eSBarry Smith   PetscValidIntPointer(maxFails,2);
147550ffb88aSMatthew Knepley   *maxFails = snes->maxFailures;
14763a40ed3dSBarry Smith   PetscFunctionReturn(0);
14779b94acceSBarry Smith }
1478a847f771SSatish Balay 
14792541af92SBarry Smith /*@
14802541af92SBarry Smith    SNESGetNumberFunctionEvals - Gets the number of user provided function evaluations
14812541af92SBarry Smith      done by SNES.
14822541af92SBarry Smith 
14832541af92SBarry Smith    Not Collective
14842541af92SBarry Smith 
14852541af92SBarry Smith    Input Parameter:
14862541af92SBarry Smith .  snes     - SNES context
14872541af92SBarry Smith 
14882541af92SBarry Smith    Output Parameter:
14892541af92SBarry Smith .  nfuncs - number of evaluations
14902541af92SBarry Smith 
14912541af92SBarry Smith    Level: intermediate
14922541af92SBarry Smith 
149395452b02SPatrick Sanan    Notes:
149495452b02SPatrick Sanan     Reset every time SNESSolve is called unless SNESSetCountersReset() is used.
1495971e163fSPeter Brune 
1496db781477SPatrick Sanan .seealso: `SNESGetMaxLinearSolveFailures()`, `SNESGetLinearSolveIterations()`, `SNESSetMaxLinearSolveFailures()`, `SNESGetLinearSolveFailures()`, `SNESSetCountersReset()`
14972541af92SBarry Smith @*/
14987087cfbeSBarry Smith PetscErrorCode  SNESGetNumberFunctionEvals(SNES snes, PetscInt *nfuncs)
14992541af92SBarry Smith {
15002541af92SBarry Smith   PetscFunctionBegin;
15010700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
15022541af92SBarry Smith   PetscValidIntPointer(nfuncs,2);
15032541af92SBarry Smith   *nfuncs = snes->nfuncs;
15042541af92SBarry Smith   PetscFunctionReturn(0);
15052541af92SBarry Smith }
15062541af92SBarry Smith 
15073d4c4710SBarry Smith /*@
15083d4c4710SBarry Smith    SNESGetLinearSolveFailures - Gets the number of failed (non-converged)
15093d4c4710SBarry Smith    linear solvers.
15103d4c4710SBarry Smith 
15113d4c4710SBarry Smith    Not Collective
15123d4c4710SBarry Smith 
15133d4c4710SBarry Smith    Input Parameter:
15143d4c4710SBarry Smith .  snes - SNES context
15153d4c4710SBarry Smith 
15163d4c4710SBarry Smith    Output Parameter:
15173d4c4710SBarry Smith .  nfails - number of failed solves
15183d4c4710SBarry Smith 
15199d85da0cSMatthew G. Knepley    Level: intermediate
15209d85da0cSMatthew G. Knepley 
15219d85da0cSMatthew G. Knepley    Options Database Keys:
15229d85da0cSMatthew G. Knepley . -snes_max_linear_solve_fail <num> - The number of failures before the solve is terminated
15239d85da0cSMatthew G. Knepley 
15243d4c4710SBarry Smith    Notes:
15253d4c4710SBarry Smith    This counter is reset to zero for each successive call to SNESSolve().
15263d4c4710SBarry Smith 
1527db781477SPatrick Sanan .seealso: `SNESGetMaxLinearSolveFailures()`, `SNESGetLinearSolveIterations()`, `SNESSetMaxLinearSolveFailures()`
15283d4c4710SBarry Smith @*/
15297087cfbeSBarry Smith PetscErrorCode  SNESGetLinearSolveFailures(SNES snes,PetscInt *nfails)
15303d4c4710SBarry Smith {
15313d4c4710SBarry Smith   PetscFunctionBegin;
15320700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
15333d4c4710SBarry Smith   PetscValidIntPointer(nfails,2);
15343d4c4710SBarry Smith   *nfails = snes->numLinearSolveFailures;
15353d4c4710SBarry Smith   PetscFunctionReturn(0);
15363d4c4710SBarry Smith }
15373d4c4710SBarry Smith 
15383d4c4710SBarry Smith /*@
15393d4c4710SBarry Smith    SNESSetMaxLinearSolveFailures - the number of failed linear solve attempts
15403d4c4710SBarry Smith    allowed before SNES returns with a diverged reason of SNES_DIVERGED_LINEAR_SOLVE
15413d4c4710SBarry Smith 
15423f9fe445SBarry Smith    Logically Collective on SNES
15433d4c4710SBarry Smith 
15443d4c4710SBarry Smith    Input Parameters:
15453d4c4710SBarry Smith +  snes     - SNES context
15463d4c4710SBarry Smith -  maxFails - maximum allowed linear solve failures
15473d4c4710SBarry Smith 
15483d4c4710SBarry Smith    Level: intermediate
15493d4c4710SBarry Smith 
15509d85da0cSMatthew G. Knepley    Options Database Keys:
15519d85da0cSMatthew G. Knepley . -snes_max_linear_solve_fail <num> - The number of failures before the solve is terminated
15529d85da0cSMatthew G. Knepley 
155395452b02SPatrick Sanan    Notes:
155495452b02SPatrick Sanan     By default this is 0; that is SNES returns on the first failed linear solve
15553d4c4710SBarry Smith 
1556db781477SPatrick Sanan .seealso: `SNESGetLinearSolveFailures()`, `SNESGetMaxLinearSolveFailures()`, `SNESGetLinearSolveIterations()`
15573d4c4710SBarry Smith @*/
15587087cfbeSBarry Smith PetscErrorCode  SNESSetMaxLinearSolveFailures(SNES snes, PetscInt maxFails)
15593d4c4710SBarry Smith {
15603d4c4710SBarry Smith   PetscFunctionBegin;
15610700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
1562c5eb9154SBarry Smith   PetscValidLogicalCollectiveInt(snes,maxFails,2);
15633d4c4710SBarry Smith   snes->maxLinearSolveFailures = maxFails;
15643d4c4710SBarry Smith   PetscFunctionReturn(0);
15653d4c4710SBarry Smith }
15663d4c4710SBarry Smith 
15673d4c4710SBarry Smith /*@
15683d4c4710SBarry Smith    SNESGetMaxLinearSolveFailures - gets the maximum number of linear solve failures that
15693d4c4710SBarry Smith      are allowed before SNES terminates
15703d4c4710SBarry Smith 
15713d4c4710SBarry Smith    Not Collective
15723d4c4710SBarry Smith 
15733d4c4710SBarry Smith    Input Parameter:
15743d4c4710SBarry Smith .  snes     - SNES context
15753d4c4710SBarry Smith 
15763d4c4710SBarry Smith    Output Parameter:
15773d4c4710SBarry Smith .  maxFails - maximum of unsuccessful solves allowed
15783d4c4710SBarry Smith 
15793d4c4710SBarry Smith    Level: intermediate
15803d4c4710SBarry Smith 
158195452b02SPatrick Sanan    Notes:
158295452b02SPatrick Sanan     By default this is 1; that is SNES returns on the first failed linear solve
15833d4c4710SBarry Smith 
1584db781477SPatrick Sanan .seealso: `SNESGetLinearSolveFailures()`, `SNESGetLinearSolveIterations()`, `SNESSetMaxLinearSolveFailures()`,
15853d4c4710SBarry Smith @*/
15867087cfbeSBarry Smith PetscErrorCode  SNESGetMaxLinearSolveFailures(SNES snes, PetscInt *maxFails)
15873d4c4710SBarry Smith {
15883d4c4710SBarry Smith   PetscFunctionBegin;
15890700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
15903d4c4710SBarry Smith   PetscValidIntPointer(maxFails,2);
15913d4c4710SBarry Smith   *maxFails = snes->maxLinearSolveFailures;
15923d4c4710SBarry Smith   PetscFunctionReturn(0);
15933d4c4710SBarry Smith }
15943d4c4710SBarry Smith 
1595c96a6f78SLois Curfman McInnes /*@
1596b850b91aSLisandro Dalcin    SNESGetLinearSolveIterations - Gets the total number of linear iterations
1597c96a6f78SLois Curfman McInnes    used by the nonlinear solver.
1598c96a6f78SLois Curfman McInnes 
1599c7afd0dbSLois Curfman McInnes    Not Collective
1600c7afd0dbSLois Curfman McInnes 
1601c96a6f78SLois Curfman McInnes    Input Parameter:
1602c96a6f78SLois Curfman McInnes .  snes - SNES context
1603c96a6f78SLois Curfman McInnes 
1604c96a6f78SLois Curfman McInnes    Output Parameter:
1605c96a6f78SLois Curfman McInnes .  lits - number of linear iterations
1606c96a6f78SLois Curfman McInnes 
1607c96a6f78SLois Curfman McInnes    Notes:
1608971e163fSPeter Brune    This counter is reset to zero for each successive call to SNESSolve() unless SNESSetCountersReset() is used.
1609c96a6f78SLois Curfman McInnes 
1610010be392SBarry 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
1611010be392SBarry Smith    then call KSPGetIterationNumber() after the failed solve.
1612010be392SBarry Smith 
161336851e7fSLois Curfman McInnes    Level: intermediate
161436851e7fSLois Curfman McInnes 
1615db781477SPatrick Sanan .seealso: `SNESGetIterationNumber()`, `SNESGetLinearSolveFailures()`, `SNESGetMaxLinearSolveFailures()`, `SNESSetCountersReset()`
1616c96a6f78SLois Curfman McInnes @*/
16177087cfbeSBarry Smith PetscErrorCode  SNESGetLinearSolveIterations(SNES snes,PetscInt *lits)
1618c96a6f78SLois Curfman McInnes {
16193a40ed3dSBarry Smith   PetscFunctionBegin;
16200700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
16214482741eSBarry Smith   PetscValidIntPointer(lits,2);
1622c96a6f78SLois Curfman McInnes   *lits = snes->linear_its;
16233a40ed3dSBarry Smith   PetscFunctionReturn(0);
1624c96a6f78SLois Curfman McInnes }
1625c96a6f78SLois Curfman McInnes 
1626971e163fSPeter Brune /*@
1627971e163fSPeter Brune    SNESSetCountersReset - Sets whether or not the counters for linear iterations and function evaluations
1628971e163fSPeter Brune    are reset every time SNESSolve() is called.
1629971e163fSPeter Brune 
1630971e163fSPeter Brune    Logically Collective on SNES
1631971e163fSPeter Brune 
1632d8d19677SJose E. Roman    Input Parameters:
1633971e163fSPeter Brune +  snes - SNES context
1634971e163fSPeter Brune -  reset - whether to reset the counters or not
1635971e163fSPeter Brune 
1636971e163fSPeter Brune    Notes:
1637fa19ca70SBarry Smith    This defaults to PETSC_TRUE
1638971e163fSPeter Brune 
1639971e163fSPeter Brune    Level: developer
1640971e163fSPeter Brune 
1641db781477SPatrick Sanan .seealso: `SNESGetNumberFunctionEvals()`, `SNESGetLinearSolveIterations()`, `SNESGetNPC()`
1642971e163fSPeter Brune @*/
1643971e163fSPeter Brune PetscErrorCode  SNESSetCountersReset(SNES snes,PetscBool reset)
1644971e163fSPeter Brune {
1645971e163fSPeter Brune   PetscFunctionBegin;
1646971e163fSPeter Brune   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
1647971e163fSPeter Brune   PetscValidLogicalCollectiveBool(snes,reset,2);
1648971e163fSPeter Brune   snes->counters_reset = reset;
1649971e163fSPeter Brune   PetscFunctionReturn(0);
1650971e163fSPeter Brune }
1651971e163fSPeter Brune 
16522999313aSBarry Smith /*@
16532999313aSBarry Smith    SNESSetKSP - Sets a KSP context for the SNES object to use
16542999313aSBarry Smith 
16552999313aSBarry Smith    Not Collective, but the SNES and KSP objects must live on the same MPI_Comm
16562999313aSBarry Smith 
16572999313aSBarry Smith    Input Parameters:
16582999313aSBarry Smith +  snes - the SNES context
16592999313aSBarry Smith -  ksp - the KSP context
16602999313aSBarry Smith 
16612999313aSBarry Smith    Notes:
16622999313aSBarry Smith    The SNES object already has its KSP object, you can obtain with SNESGetKSP()
16632999313aSBarry Smith    so this routine is rarely needed.
16642999313aSBarry Smith 
16652999313aSBarry Smith    The KSP object that is already in the SNES object has its reference count
16662999313aSBarry Smith    decreased by one.
16672999313aSBarry Smith 
16682999313aSBarry Smith    Level: developer
16692999313aSBarry Smith 
1670db781477SPatrick Sanan .seealso: `KSPGetPC()`, `SNESCreate()`, `KSPCreate()`, `SNESSetKSP()`
16712999313aSBarry Smith @*/
16727087cfbeSBarry Smith PetscErrorCode  SNESSetKSP(SNES snes,KSP ksp)
16732999313aSBarry Smith {
16742999313aSBarry Smith   PetscFunctionBegin;
16750700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
16760700a824SBarry Smith   PetscValidHeaderSpecific(ksp,KSP_CLASSID,2);
16772999313aSBarry Smith   PetscCheckSameComm(snes,1,ksp,2);
16789566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)ksp));
16799566063dSJacob Faibussowitsch   if (snes->ksp) PetscCall(PetscObjectDereference((PetscObject)snes->ksp));
16802999313aSBarry Smith   snes->ksp = ksp;
16812999313aSBarry Smith   PetscFunctionReturn(0);
16822999313aSBarry Smith }
16832999313aSBarry Smith 
16849b94acceSBarry Smith /* -----------------------------------------------------------*/
168552baeb72SSatish Balay /*@
16869b94acceSBarry Smith    SNESCreate - Creates a nonlinear solver context.
16879b94acceSBarry Smith 
1688d083f849SBarry Smith    Collective
1689c7afd0dbSLois Curfman McInnes 
1690c7afd0dbSLois Curfman McInnes    Input Parameters:
1691906ed7ccSBarry Smith .  comm - MPI communicator
16929b94acceSBarry Smith 
16939b94acceSBarry Smith    Output Parameter:
16949b94acceSBarry Smith .  outsnes - the new SNES context
16959b94acceSBarry Smith 
1696c7afd0dbSLois Curfman McInnes    Options Database Keys:
1697c7afd0dbSLois Curfman McInnes +   -snes_mf - Activates default matrix-free Jacobian-vector products,
1698c7afd0dbSLois Curfman McInnes                and no preconditioning matrix
1699c7afd0dbSLois Curfman McInnes .   -snes_mf_operator - Activates default matrix-free Jacobian-vector
1700c7afd0dbSLois Curfman McInnes                products, and a user-provided preconditioning matrix
1701c7afd0dbSLois Curfman McInnes                as set by SNESSetJacobian()
1702c7afd0dbSLois Curfman McInnes -   -snes_fd - Uses (slow!) finite differences to compute Jacobian
1703c1f60f51SBarry Smith 
170436851e7fSLois Curfman McInnes    Level: beginner
170536851e7fSLois Curfman McInnes 
170695452b02SPatrick Sanan    Developer Notes:
170795452b02SPatrick Sanan     SNES always creates a KSP object even though many SNES methods do not use it. This is
1708efd4aadfSBarry Smith                     unfortunate and should be fixed at some point. The flag snes->usesksp indicates if the
1709efd4aadfSBarry Smith                     particular method does use KSP and regulates if the information about the KSP is printed
1710efd4aadfSBarry Smith                     in SNESView(). TSSetFromOptions() does call SNESSetFromOptions() which can lead to users being confused
1711efd4aadfSBarry Smith                     by help messages about meaningless SNES options.
1712efd4aadfSBarry Smith 
1713efd4aadfSBarry Smith                     SNES always creates the snes->kspconvctx even though it is used by only one type. This should
1714efd4aadfSBarry Smith                     be fixed.
1715efd4aadfSBarry Smith 
1716db781477SPatrick Sanan .seealso: `SNESSolve()`, `SNESDestroy()`, `SNES`, `SNESSetLagPreconditioner()`, `SNESSetLagJacobian()`
1717a8054027SBarry Smith 
17189b94acceSBarry Smith @*/
17197087cfbeSBarry Smith PetscErrorCode  SNESCreate(MPI_Comm comm,SNES *outsnes)
17209b94acceSBarry Smith {
17219b94acceSBarry Smith   SNES      snes;
1722fa9f3622SBarry Smith   SNESKSPEW *kctx;
172337fcc0dbSBarry Smith 
17243a40ed3dSBarry Smith   PetscFunctionBegin;
1725ed1caa07SMatthew Knepley   PetscValidPointer(outsnes,2);
17260298fd71SBarry Smith   *outsnes = NULL;
17279566063dSJacob Faibussowitsch   PetscCall(SNESInitializePackage());
17288ba1e511SMatthew Knepley 
17299566063dSJacob Faibussowitsch   PetscCall(PetscHeaderCreate(snes,SNES_CLASSID,"SNES","Nonlinear solver","SNES",comm,SNESDestroy,SNESView));
17307adad957SLisandro Dalcin 
17318d359177SBarry Smith   snes->ops->converged    = SNESConvergedDefault;
17322c155ee1SBarry Smith   snes->usesksp           = PETSC_TRUE;
173388976e71SPeter Brune   snes->tolerancesset     = PETSC_FALSE;
17349b94acceSBarry Smith   snes->max_its           = 50;
17359750a799SBarry Smith   snes->max_funcs         = 10000;
17369b94acceSBarry Smith   snes->norm              = 0.0;
1737c1e67a49SFande Kong   snes->xnorm             = 0.0;
1738c1e67a49SFande Kong   snes->ynorm             = 0.0;
1739365a6726SPeter Brune   snes->normschedule      = SNES_NORM_ALWAYS;
17406c67d002SPeter Brune   snes->functype          = SNES_FUNCTION_DEFAULT;
17413a2046daSBarry Smith #if defined(PETSC_USE_REAL_SINGLE)
17423a2046daSBarry Smith   snes->rtol              = 1.e-5;
17433a2046daSBarry Smith #else
1744b4874afaSBarry Smith   snes->rtol              = 1.e-8;
17453a2046daSBarry Smith #endif
1746b4874afaSBarry Smith   snes->ttol              = 0.0;
17473a2046daSBarry Smith #if defined(PETSC_USE_REAL_SINGLE)
17483a2046daSBarry Smith   snes->abstol            = 1.e-25;
17493a2046daSBarry Smith #else
175070441072SBarry Smith   snes->abstol            = 1.e-50;
17513a2046daSBarry Smith #endif
17527cd0ae37SLisandro Dalcin #if defined(PETSC_USE_REAL_SINGLE)
17537cd0ae37SLisandro Dalcin   snes->stol              = 1.e-5;
17547cd0ae37SLisandro Dalcin #else
1755c60f73f4SPeter Brune   snes->stol              = 1.e-8;
17567cd0ae37SLisandro Dalcin #endif
17573a2046daSBarry Smith #if defined(PETSC_USE_REAL_SINGLE)
17583a2046daSBarry Smith   snes->deltatol          = 1.e-6;
17593a2046daSBarry Smith #else
17604b27c08aSLois Curfman McInnes   snes->deltatol          = 1.e-12;
17613a2046daSBarry Smith #endif
1762e37c518bSBarry Smith   snes->divtol            = 1.e4;
1763e37c518bSBarry Smith   snes->rnorm0            = 0;
17649b94acceSBarry Smith   snes->nfuncs            = 0;
176550ffb88aSMatthew Knepley   snes->numFailures       = 0;
176650ffb88aSMatthew Knepley   snes->maxFailures       = 1;
17677a00f4a9SLois Curfman McInnes   snes->linear_its        = 0;
1768e35cf81dSBarry Smith   snes->lagjacobian       = 1;
176937ec4e1aSPeter Brune   snes->jac_iter          = 0;
177037ec4e1aSPeter Brune   snes->lagjac_persist    = PETSC_FALSE;
1771a8054027SBarry Smith   snes->lagpreconditioner = 1;
177237ec4e1aSPeter Brune   snes->pre_iter          = 0;
177337ec4e1aSPeter Brune   snes->lagpre_persist    = PETSC_FALSE;
1774639f9d9dSBarry Smith   snes->numbermonitors    = 0;
1775c4421ceaSFande Kong   snes->numberreasonviews = 0;
17769e5d0892SLisandro Dalcin   snes->data              = NULL;
17774dc4c822SBarry Smith   snes->setupcalled       = PETSC_FALSE;
1778186905e3SBarry Smith   snes->ksp_ewconv        = PETSC_FALSE;
17796f24a144SLois Curfman McInnes   snes->nwork             = 0;
17809e5d0892SLisandro Dalcin   snes->work              = NULL;
178158c9b817SLisandro Dalcin   snes->nvwork            = 0;
17829e5d0892SLisandro Dalcin   snes->vwork             = NULL;
1783758f92a0SBarry Smith   snes->conv_hist_len     = 0;
1784758f92a0SBarry Smith   snes->conv_hist_max     = 0;
17850298fd71SBarry Smith   snes->conv_hist         = NULL;
17860298fd71SBarry Smith   snes->conv_hist_its     = NULL;
1787758f92a0SBarry Smith   snes->conv_hist_reset   = PETSC_TRUE;
1788971e163fSPeter Brune   snes->counters_reset    = PETSC_TRUE;
1789e4ed7901SPeter Brune   snes->vec_func_init_set = PETSC_FALSE;
1790184914b5SBarry Smith   snes->reason            = SNES_CONVERGED_ITERATING;
1791efd4aadfSBarry Smith   snes->npcside           = PC_RIGHT;
1792b3cd9a81SMatthew G. Knepley   snes->setfromoptionscalled = 0;
1793c40d0f55SPeter Brune 
1794d8f46077SPeter Brune   snes->mf          = PETSC_FALSE;
1795d8f46077SPeter Brune   snes->mf_operator = PETSC_FALSE;
1796d8f46077SPeter Brune   snes->mf_version  = 1;
1797d8f46077SPeter Brune 
17983d4c4710SBarry Smith   snes->numLinearSolveFailures = 0;
17993d4c4710SBarry Smith   snes->maxLinearSolveFailures = 1;
18003d4c4710SBarry Smith 
1801349187a7SBarry Smith   snes->vizerotolerance = 1.e-8;
180276bd3646SJed Brown   snes->checkjacdomainerror = PetscDefined(USE_DEBUG) ? PETSC_TRUE : PETSC_FALSE;
1803349187a7SBarry Smith 
18044fc747eaSLawrence Mitchell   /* Set this to true if the implementation of SNESSolve_XXX does compute the residual at the final solution. */
18054fc747eaSLawrence Mitchell   snes->alwayscomputesfinalresidual = PETSC_FALSE;
18064fc747eaSLawrence Mitchell 
18079b94acceSBarry Smith   /* Create context to compute Eisenstat-Walker relative tolerance for KSP */
18089566063dSJacob Faibussowitsch   PetscCall(PetscNewLog(snes,&kctx));
1809f5af7f23SKarl Rupp 
18109b94acceSBarry Smith   snes->kspconvctx  = (void*)kctx;
18119b94acceSBarry Smith   kctx->version     = 2;
18120f0abf79SStefano Zampini   kctx->rtol_0      = 0.3; /* Eisenstat and Walker suggest rtol_0=.5, but
18139b94acceSBarry Smith                              this was too large for some test cases */
181475567043SBarry Smith   kctx->rtol_last   = 0.0;
18150f0abf79SStefano Zampini   kctx->rtol_max    = 0.9;
18169b94acceSBarry Smith   kctx->gamma       = 1.0;
18170f0abf79SStefano Zampini   kctx->alpha       = 0.5*(1.0 + PetscSqrtReal(5.0));
181871f87433Sdalcinl   kctx->alpha2      = kctx->alpha;
18190f0abf79SStefano Zampini   kctx->threshold   = 0.1;
182075567043SBarry Smith   kctx->lresid_last = 0.0;
182175567043SBarry Smith   kctx->norm_last   = 0.0;
18229b94acceSBarry Smith 
18230f0abf79SStefano Zampini   kctx->rk_last     = 0.0;
18240f0abf79SStefano Zampini   kctx->rk_last_2   = 0.0;
18250f0abf79SStefano Zampini   kctx->rtol_last_2 = 0.0;
18260f0abf79SStefano Zampini   kctx->v4_p1       = 0.1;
18270f0abf79SStefano Zampini   kctx->v4_p2       = 0.4;
18280f0abf79SStefano Zampini   kctx->v4_p3       = 0.7;
18290f0abf79SStefano Zampini   kctx->v4_m1       = 0.8;
18300f0abf79SStefano Zampini   kctx->v4_m2       = 0.5;
18310f0abf79SStefano Zampini   kctx->v4_m3       = 0.1;
18320f0abf79SStefano Zampini   kctx->v4_m4       = 0.5;
18330f0abf79SStefano Zampini 
18349b94acceSBarry Smith   *outsnes = snes;
18353a40ed3dSBarry Smith   PetscFunctionReturn(0);
18369b94acceSBarry Smith }
18379b94acceSBarry Smith 
183888f0584fSBarry Smith /*MC
1839411c0326SBarry Smith     SNESFunction - Functional form used to convey the nonlinear function to be solved by SNES
184088f0584fSBarry Smith 
184188f0584fSBarry Smith      Synopsis:
1842411c0326SBarry Smith      #include "petscsnes.h"
1843411c0326SBarry Smith      PetscErrorCode SNESFunction(SNES snes,Vec x,Vec f,void *ctx);
184488f0584fSBarry Smith 
18451843f636SBarry Smith      Collective on snes
18461843f636SBarry Smith 
184788f0584fSBarry Smith      Input Parameters:
184888f0584fSBarry Smith +     snes - the SNES context
184988f0584fSBarry Smith .     x    - state at which to evaluate residual
185088f0584fSBarry Smith -     ctx     - optional user-defined function context, passed in with SNESSetFunction()
185188f0584fSBarry Smith 
185288f0584fSBarry Smith      Output Parameter:
185388f0584fSBarry Smith .     f  - vector to put residual (function value)
185488f0584fSBarry Smith 
1855878cb397SSatish Balay    Level: intermediate
1856878cb397SSatish Balay 
1857db781477SPatrick Sanan .seealso: `SNESSetFunction()`, `SNESGetFunction()`
185888f0584fSBarry Smith M*/
185988f0584fSBarry Smith 
18609b94acceSBarry Smith /*@C
18619b94acceSBarry Smith    SNESSetFunction - Sets the function evaluation routine and function
18629b94acceSBarry Smith    vector for use by the SNES routines in solving systems of nonlinear
18639b94acceSBarry Smith    equations.
18649b94acceSBarry Smith 
18653f9fe445SBarry Smith    Logically Collective on SNES
1866fee21e36SBarry Smith 
1867c7afd0dbSLois Curfman McInnes    Input Parameters:
1868c7afd0dbSLois Curfman McInnes +  snes - the SNES context
18696b7fb656SBarry Smith .  r - vector to store function values, may be NULL
1870f8b49ee9SBarry Smith .  f - function evaluation routine; see SNESFunction for calling sequence details
1871c7afd0dbSLois Curfman McInnes -  ctx - [optional] user-defined context for private data for the
18720298fd71SBarry Smith          function evaluation routine (may be NULL)
18739b94acceSBarry Smith 
18749b94acceSBarry Smith    Notes:
18759b94acceSBarry Smith    The Newton-like methods typically solve linear systems of the form
18769b94acceSBarry Smith $      f'(x) x = -f(x),
1877c7afd0dbSLois Curfman McInnes    where f'(x) denotes the Jacobian matrix and f(x) is the function.
18789b94acceSBarry Smith 
187936851e7fSLois Curfman McInnes    Level: beginner
188036851e7fSLois Curfman McInnes 
1881db781477SPatrick Sanan .seealso: `SNESGetFunction()`, `SNESComputeFunction()`, `SNESSetJacobian()`, `SNESSetPicard()`, `SNESFunction`
18829b94acceSBarry Smith @*/
1883f8b49ee9SBarry Smith PetscErrorCode  SNESSetFunction(SNES snes,Vec r,PetscErrorCode (*f)(SNES,Vec,Vec,void*),void *ctx)
18849b94acceSBarry Smith {
18856cab3a1bSJed Brown   DM             dm;
18866cab3a1bSJed Brown 
18873a40ed3dSBarry Smith   PetscFunctionBegin;
18880700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
1889d2a683ecSLisandro Dalcin   if (r) {
1890d2a683ecSLisandro Dalcin     PetscValidHeaderSpecific(r,VEC_CLASSID,2);
1891d2a683ecSLisandro Dalcin     PetscCheckSameComm(snes,1,r,2);
18929566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)r));
18939566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&snes->vec_func));
189485385478SLisandro Dalcin     snes->vec_func = r;
1895d2a683ecSLisandro Dalcin   }
18969566063dSJacob Faibussowitsch   PetscCall(SNESGetDM(snes,&dm));
18979566063dSJacob Faibussowitsch   PetscCall(DMSNESSetFunction(dm,f,ctx));
1898bbc1464cSBarry Smith   if (f == SNESPicardComputeFunction) {
18999566063dSJacob Faibussowitsch     PetscCall(DMSNESSetMFFunction(dm,SNESPicardComputeMFFunction,ctx));
1900bbc1464cSBarry Smith   }
19013a40ed3dSBarry Smith   PetscFunctionReturn(0);
19029b94acceSBarry Smith }
19039b94acceSBarry Smith 
1904e4ed7901SPeter Brune /*@C
1905e4ed7901SPeter Brune    SNESSetInitialFunction - Sets the function vector to be used as the
1906e4ed7901SPeter Brune    function norm at the initialization of the method.  In some
1907e4ed7901SPeter Brune    instances, the user has precomputed the function before calling
1908e4ed7901SPeter Brune    SNESSolve.  This function allows one to avoid a redundant call
1909e4ed7901SPeter Brune    to SNESComputeFunction in that case.
1910e4ed7901SPeter Brune 
1911e4ed7901SPeter Brune    Logically Collective on SNES
1912e4ed7901SPeter Brune 
1913e4ed7901SPeter Brune    Input Parameters:
1914e4ed7901SPeter Brune +  snes - the SNES context
1915e4ed7901SPeter Brune -  f - vector to store function value
1916e4ed7901SPeter Brune 
1917e4ed7901SPeter Brune    Notes:
1918e4ed7901SPeter Brune    This should not be modified during the solution procedure.
1919e4ed7901SPeter Brune 
1920e4ed7901SPeter Brune    This is used extensively in the SNESFAS hierarchy and in nonlinear preconditioning.
1921e4ed7901SPeter Brune 
1922e4ed7901SPeter Brune    Level: developer
1923e4ed7901SPeter Brune 
1924db781477SPatrick Sanan .seealso: `SNESSetFunction()`, `SNESComputeFunction()`, `SNESSetInitialFunctionNorm()`
1925e4ed7901SPeter Brune @*/
1926e4ed7901SPeter Brune PetscErrorCode  SNESSetInitialFunction(SNES snes, Vec f)
1927e4ed7901SPeter Brune {
1928e4ed7901SPeter Brune   Vec            vec_func;
1929e4ed7901SPeter Brune 
1930e4ed7901SPeter Brune   PetscFunctionBegin;
1931e4ed7901SPeter Brune   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
1932e4ed7901SPeter Brune   PetscValidHeaderSpecific(f,VEC_CLASSID,2);
1933e4ed7901SPeter Brune   PetscCheckSameComm(snes,1,f,2);
1934efd4aadfSBarry Smith   if (snes->npcside == PC_LEFT && snes->functype == SNES_FUNCTION_PRECONDITIONED) {
1935902f982fSPeter Brune     snes->vec_func_init_set = PETSC_FALSE;
1936902f982fSPeter Brune     PetscFunctionReturn(0);
1937902f982fSPeter Brune   }
19389566063dSJacob Faibussowitsch   PetscCall(SNESGetFunction(snes,&vec_func,NULL,NULL));
19399566063dSJacob Faibussowitsch   PetscCall(VecCopy(f,vec_func));
1940f5af7f23SKarl Rupp 
1941217b9c2eSPeter Brune   snes->vec_func_init_set = PETSC_TRUE;
1942e4ed7901SPeter Brune   PetscFunctionReturn(0);
1943e4ed7901SPeter Brune }
1944e4ed7901SPeter Brune 
1945534ebe21SPeter Brune /*@
1946a5b23f4aSJose E. Roman    SNESSetNormSchedule - Sets the SNESNormSchedule used in convergence and monitoring
1947534ebe21SPeter Brune    of the SNES method.
1948534ebe21SPeter Brune 
1949534ebe21SPeter Brune    Logically Collective on SNES
1950534ebe21SPeter Brune 
1951534ebe21SPeter Brune    Input Parameters:
1952534ebe21SPeter Brune +  snes - the SNES context
1953365a6726SPeter Brune -  normschedule - the frequency of norm computation
1954534ebe21SPeter Brune 
1955517f1916SMatthew G. Knepley    Options Database Key:
195667b8a455SSatish Balay .  -snes_norm_schedule <none, always, initialonly, finalonly, initialfinalonly> - set the schedule
1957517f1916SMatthew G. Knepley 
1958534ebe21SPeter Brune    Notes:
1959365a6726SPeter Brune    Only certain SNES methods support certain SNESNormSchedules.  Most require evaluation
1960534ebe21SPeter Brune    of the nonlinear function and the taking of its norm at every iteration to
1961534ebe21SPeter Brune    even ensure convergence at all.  However, methods such as custom Gauss-Seidel methods
1962a5b23f4aSJose E. Roman    (SNESNGS) and the like do not require the norm of the function to be computed, and therefore
1963534ebe21SPeter Brune    may either be monitored for convergence or not.  As these are often used as nonlinear
1964534ebe21SPeter Brune    preconditioners, monitoring the norm of their error is not a useful enterprise within
1965534ebe21SPeter Brune    their solution.
1966534ebe21SPeter Brune 
1967534ebe21SPeter Brune    Level: developer
1968534ebe21SPeter Brune 
1969db781477SPatrick Sanan .seealso: `SNESGetNormSchedule()`, `SNESComputeFunction()`, `VecNorm()`, `SNESSetFunction()`, `SNESSetInitialFunction()`, `SNESNormSchedule`
1970534ebe21SPeter Brune @*/
1971365a6726SPeter Brune PetscErrorCode  SNESSetNormSchedule(SNES snes, SNESNormSchedule normschedule)
1972534ebe21SPeter Brune {
1973534ebe21SPeter Brune   PetscFunctionBegin;
1974534ebe21SPeter Brune   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
1975365a6726SPeter Brune   snes->normschedule = normschedule;
1976534ebe21SPeter Brune   PetscFunctionReturn(0);
1977534ebe21SPeter Brune }
1978534ebe21SPeter Brune 
1979534ebe21SPeter Brune /*@
1980a5b23f4aSJose E. Roman    SNESGetNormSchedule - Gets the SNESNormSchedule used in convergence and monitoring
1981534ebe21SPeter Brune    of the SNES method.
1982534ebe21SPeter Brune 
1983534ebe21SPeter Brune    Logically Collective on SNES
1984534ebe21SPeter Brune 
1985534ebe21SPeter Brune    Input Parameters:
1986534ebe21SPeter Brune +  snes - the SNES context
1987365a6726SPeter Brune -  normschedule - the type of the norm used
1988534ebe21SPeter Brune 
1989534ebe21SPeter Brune    Level: advanced
1990534ebe21SPeter Brune 
1991db781477SPatrick Sanan .seealso: `SNESSetNormSchedule()`, `SNESComputeFunction()`, `VecNorm()`, `SNESSetFunction()`, `SNESSetInitialFunction()`, `SNESNormSchedule`
1992534ebe21SPeter Brune @*/
1993365a6726SPeter Brune PetscErrorCode  SNESGetNormSchedule(SNES snes, SNESNormSchedule *normschedule)
1994534ebe21SPeter Brune {
1995534ebe21SPeter Brune   PetscFunctionBegin;
1996534ebe21SPeter Brune   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
1997365a6726SPeter Brune   *normschedule = snes->normschedule;
1998534ebe21SPeter Brune   PetscFunctionReturn(0);
1999534ebe21SPeter Brune }
2000534ebe21SPeter Brune 
2001c5ce4427SMatthew G. Knepley /*@
2002c5ce4427SMatthew G. Knepley   SNESSetFunctionNorm - Sets the last computed residual norm.
2003c5ce4427SMatthew G. Knepley 
2004c5ce4427SMatthew G. Knepley   Logically Collective on SNES
2005c5ce4427SMatthew G. Knepley 
2006c5ce4427SMatthew G. Knepley   Input Parameters:
2007c5ce4427SMatthew G. Knepley + snes - the SNES context
2008c5ce4427SMatthew G. Knepley 
2009c5ce4427SMatthew G. Knepley - normschedule - the frequency of norm computation
2010c5ce4427SMatthew G. Knepley 
2011c5ce4427SMatthew G. Knepley   Level: developer
2012c5ce4427SMatthew G. Knepley 
2013db781477SPatrick Sanan .seealso: `SNESGetNormSchedule()`, `SNESComputeFunction()`, `VecNorm()`, `SNESSetFunction()`, `SNESSetInitialFunction()`, `SNESNormSchedule`
2014c5ce4427SMatthew G. Knepley @*/
2015c5ce4427SMatthew G. Knepley PetscErrorCode SNESSetFunctionNorm(SNES snes, PetscReal norm)
2016c5ce4427SMatthew G. Knepley {
2017c5ce4427SMatthew G. Knepley   PetscFunctionBegin;
2018c5ce4427SMatthew G. Knepley   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
2019c5ce4427SMatthew G. Knepley   snes->norm = norm;
2020c5ce4427SMatthew G. Knepley   PetscFunctionReturn(0);
2021c5ce4427SMatthew G. Knepley }
2022c5ce4427SMatthew G. Knepley 
2023c5ce4427SMatthew G. Knepley /*@
2024c5ce4427SMatthew G. Knepley   SNESGetFunctionNorm - Gets the last computed norm of the residual
2025c5ce4427SMatthew G. Knepley 
2026c5ce4427SMatthew G. Knepley   Not Collective
2027c5ce4427SMatthew G. Knepley 
2028c5ce4427SMatthew G. Knepley   Input Parameter:
2029c5ce4427SMatthew G. Knepley . snes - the SNES context
2030c5ce4427SMatthew G. Knepley 
2031c5ce4427SMatthew G. Knepley   Output Parameter:
2032c5ce4427SMatthew G. Knepley . norm - the last computed residual norm
2033c5ce4427SMatthew G. Knepley 
2034c5ce4427SMatthew G. Knepley   Level: developer
2035c5ce4427SMatthew G. Knepley 
2036db781477SPatrick Sanan .seealso: `SNESSetNormSchedule()`, `SNESComputeFunction()`, `VecNorm()`, `SNESSetFunction()`, `SNESSetInitialFunction()`, `SNESNormSchedule`
2037c5ce4427SMatthew G. Knepley @*/
2038c5ce4427SMatthew G. Knepley PetscErrorCode SNESGetFunctionNorm(SNES snes, PetscReal *norm)
2039c5ce4427SMatthew G. Knepley {
2040c5ce4427SMatthew G. Knepley   PetscFunctionBegin;
2041c5ce4427SMatthew G. Knepley   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
2042dadcf809SJacob Faibussowitsch   PetscValidRealPointer(norm, 2);
2043c5ce4427SMatthew G. Knepley   *norm = snes->norm;
2044c5ce4427SMatthew G. Knepley   PetscFunctionReturn(0);
2045c5ce4427SMatthew G. Knepley }
2046c5ce4427SMatthew G. Knepley 
2047c1e67a49SFande Kong /*@
2048c1e67a49SFande Kong   SNESGetUpdateNorm - Gets the last computed norm of the Newton update
2049c1e67a49SFande Kong 
2050c1e67a49SFande Kong   Not Collective
2051c1e67a49SFande Kong 
2052c1e67a49SFande Kong   Input Parameter:
2053c1e67a49SFande Kong . snes - the SNES context
2054c1e67a49SFande Kong 
2055c1e67a49SFande Kong   Output Parameter:
2056c1e67a49SFande Kong . ynorm - the last computed update norm
2057c1e67a49SFande Kong 
2058c1e67a49SFande Kong   Level: developer
2059c1e67a49SFande Kong 
2060db781477SPatrick Sanan .seealso: `SNESSetNormSchedule()`, `SNESComputeFunction()`, `SNESGetFunctionNorm()`
2061c1e67a49SFande Kong @*/
2062c1e67a49SFande Kong PetscErrorCode SNESGetUpdateNorm(SNES snes, PetscReal *ynorm)
2063c1e67a49SFande Kong {
2064c1e67a49SFande Kong   PetscFunctionBegin;
2065c1e67a49SFande Kong   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
2066dadcf809SJacob Faibussowitsch   PetscValidRealPointer(ynorm, 2);
2067c1e67a49SFande Kong   *ynorm = snes->ynorm;
2068c1e67a49SFande Kong   PetscFunctionReturn(0);
2069c1e67a49SFande Kong }
2070c1e67a49SFande Kong 
2071c1e67a49SFande Kong /*@
20724591eaf2SFande Kong   SNESGetSolutionNorm - Gets the last computed norm of the solution
2073c1e67a49SFande Kong 
2074c1e67a49SFande Kong   Not Collective
2075c1e67a49SFande Kong 
2076c1e67a49SFande Kong   Input Parameter:
2077c1e67a49SFande Kong . snes - the SNES context
2078c1e67a49SFande Kong 
2079c1e67a49SFande Kong   Output Parameter:
2080c1e67a49SFande Kong . xnorm - the last computed solution norm
2081c1e67a49SFande Kong 
2082c1e67a49SFande Kong   Level: developer
2083c1e67a49SFande Kong 
2084db781477SPatrick Sanan .seealso: `SNESSetNormSchedule()`, `SNESComputeFunction()`, `SNESGetFunctionNorm()`, `SNESGetUpdateNorm()`
2085c1e67a49SFande Kong @*/
2086c1e67a49SFande Kong PetscErrorCode SNESGetSolutionNorm(SNES snes, PetscReal *xnorm)
2087c1e67a49SFande Kong {
2088c1e67a49SFande Kong   PetscFunctionBegin;
2089c1e67a49SFande Kong   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
2090dadcf809SJacob Faibussowitsch   PetscValidRealPointer(xnorm, 2);
2091c1e67a49SFande Kong   *xnorm = snes->xnorm;
2092c1e67a49SFande Kong   PetscFunctionReturn(0);
2093c1e67a49SFande Kong }
2094c1e67a49SFande Kong 
209547073ea2SPeter Brune /*@C
2096a5b23f4aSJose E. Roman    SNESSetFunctionType - Sets the SNESNormSchedule used in convergence and monitoring
209747073ea2SPeter Brune    of the SNES method.
209847073ea2SPeter Brune 
209947073ea2SPeter Brune    Logically Collective on SNES
210047073ea2SPeter Brune 
210147073ea2SPeter Brune    Input Parameters:
210247073ea2SPeter Brune +  snes - the SNES context
210347073ea2SPeter Brune -  normschedule - the frequency of norm computation
210447073ea2SPeter Brune 
210547073ea2SPeter Brune    Notes:
210647073ea2SPeter Brune    Only certain SNES methods support certain SNESNormSchedules.  Most require evaluation
210747073ea2SPeter Brune    of the nonlinear function and the taking of its norm at every iteration to
210847073ea2SPeter Brune    even ensure convergence at all.  However, methods such as custom Gauss-Seidel methods
2109a5b23f4aSJose E. Roman    (SNESNGS) and the like do not require the norm of the function to be computed, and therefore
211047073ea2SPeter Brune    may either be monitored for convergence or not.  As these are often used as nonlinear
211147073ea2SPeter Brune    preconditioners, monitoring the norm of their error is not a useful enterprise within
211247073ea2SPeter Brune    their solution.
211347073ea2SPeter Brune 
211447073ea2SPeter Brune    Level: developer
211547073ea2SPeter Brune 
2116db781477SPatrick Sanan .seealso: `SNESGetNormSchedule()`, `SNESComputeFunction()`, `VecNorm()`, `SNESSetFunction()`, `SNESSetInitialFunction()`, `SNESNormSchedule`
211747073ea2SPeter Brune @*/
211847073ea2SPeter Brune PetscErrorCode  SNESSetFunctionType(SNES snes, SNESFunctionType type)
211947073ea2SPeter Brune {
212047073ea2SPeter Brune   PetscFunctionBegin;
212147073ea2SPeter Brune   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
212247073ea2SPeter Brune   snes->functype = type;
212347073ea2SPeter Brune   PetscFunctionReturn(0);
212447073ea2SPeter Brune }
212547073ea2SPeter Brune 
212647073ea2SPeter Brune /*@C
2127a5b23f4aSJose E. Roman    SNESGetFunctionType - Gets the SNESNormSchedule used in convergence and monitoring
212847073ea2SPeter Brune    of the SNES method.
212947073ea2SPeter Brune 
213047073ea2SPeter Brune    Logically Collective on SNES
213147073ea2SPeter Brune 
213247073ea2SPeter Brune    Input Parameters:
213347073ea2SPeter Brune +  snes - the SNES context
213447073ea2SPeter Brune -  normschedule - the type of the norm used
213547073ea2SPeter Brune 
213647073ea2SPeter Brune    Level: advanced
213747073ea2SPeter Brune 
2138db781477SPatrick Sanan .seealso: `SNESSetNormSchedule()`, `SNESComputeFunction()`, `VecNorm()`, `SNESSetFunction()`, `SNESSetInitialFunction()`, `SNESNormSchedule`
213947073ea2SPeter Brune @*/
214047073ea2SPeter Brune PetscErrorCode  SNESGetFunctionType(SNES snes, SNESFunctionType *type)
214147073ea2SPeter Brune {
214247073ea2SPeter Brune   PetscFunctionBegin;
214347073ea2SPeter Brune   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
214447073ea2SPeter Brune   *type = snes->functype;
2145534ebe21SPeter Brune   PetscFunctionReturn(0);
2146534ebe21SPeter Brune }
2147534ebe21SPeter Brune 
2148bf388a1fSBarry Smith /*MC
2149be95d8f1SBarry Smith     SNESNGSFunction - function used to convey a Gauss-Seidel sweep on the nonlinear function
2150bf388a1fSBarry Smith 
2151bf388a1fSBarry Smith      Synopsis:
2152aaa7dc30SBarry Smith      #include <petscsnes.h>
2153be95d8f1SBarry Smith $    SNESNGSFunction(SNES snes,Vec x,Vec b,void *ctx);
2154bf388a1fSBarry Smith 
21551843f636SBarry Smith      Collective on snes
21561843f636SBarry Smith 
21571843f636SBarry Smith      Input Parameters:
2158bf388a1fSBarry Smith +  X   - solution vector
2159bf388a1fSBarry Smith .  B   - RHS vector
2160bf388a1fSBarry Smith -  ctx - optional user-defined Gauss-Seidel context
2161bf388a1fSBarry Smith 
21621843f636SBarry Smith      Output Parameter:
21631843f636SBarry Smith .  X   - solution vector
21641843f636SBarry Smith 
2165878cb397SSatish Balay    Level: intermediate
2166878cb397SSatish Balay 
2167db781477SPatrick Sanan .seealso: `SNESSetNGS()`, `SNESGetNGS()`
2168bf388a1fSBarry Smith M*/
2169bf388a1fSBarry Smith 
2170c79ef259SPeter Brune /*@C
2171be95d8f1SBarry Smith    SNESSetNGS - Sets the user nonlinear Gauss-Seidel routine for
2172c79ef259SPeter Brune    use with composed nonlinear solvers.
2173c79ef259SPeter Brune 
2174c79ef259SPeter Brune    Input Parameters:
2175c79ef259SPeter Brune +  snes   - the SNES context
2176be95d8f1SBarry Smith .  f - function evaluation routine to apply Gauss-Seidel see SNESNGSFunction
2177c79ef259SPeter Brune -  ctx    - [optional] user-defined context for private data for the
21780298fd71SBarry Smith             smoother evaluation routine (may be NULL)
2179c79ef259SPeter Brune 
2180c79ef259SPeter Brune    Notes:
2181be95d8f1SBarry Smith    The NGS routines are used by the composed nonlinear solver to generate
2182c79ef259SPeter Brune     a problem appropriate update to the solution, particularly FAS.
2183c79ef259SPeter Brune 
2184d28543b3SPeter Brune    Level: intermediate
2185c79ef259SPeter Brune 
2186db781477SPatrick Sanan .seealso: `SNESGetFunction()`, `SNESComputeNGS()`
2187c79ef259SPeter Brune @*/
2188be95d8f1SBarry Smith PetscErrorCode SNESSetNGS(SNES snes,PetscErrorCode (*f)(SNES,Vec,Vec,void*),void *ctx)
21896cab3a1bSJed Brown {
21906cab3a1bSJed Brown   DM             dm;
21916cab3a1bSJed Brown 
2192646217ecSPeter Brune   PetscFunctionBegin;
21936cab3a1bSJed Brown   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
21949566063dSJacob Faibussowitsch   PetscCall(SNESGetDM(snes,&dm));
21959566063dSJacob Faibussowitsch   PetscCall(DMSNESSetNGS(dm,f,ctx));
2196646217ecSPeter Brune   PetscFunctionReturn(0);
2197646217ecSPeter Brune }
2198646217ecSPeter Brune 
2199bbc1464cSBarry Smith /*
2200bbc1464cSBarry Smith      This is used for -snes_mf_operator; it uses a duplicate of snes->jacobian_pre because snes->jacobian_pre cannot be
2201bbc1464cSBarry Smith    changed during the KSPSolve()
2202bbc1464cSBarry Smith */
2203bbc1464cSBarry Smith PetscErrorCode SNESPicardComputeMFFunction(SNES snes,Vec x,Vec f,void *ctx)
2204bbc1464cSBarry Smith {
2205bbc1464cSBarry Smith   DM             dm;
2206bbc1464cSBarry Smith   DMSNES         sdm;
2207bbc1464cSBarry Smith 
2208bbc1464cSBarry Smith   PetscFunctionBegin;
22099566063dSJacob Faibussowitsch   PetscCall(SNESGetDM(snes,&dm));
22109566063dSJacob Faibussowitsch   PetscCall(DMGetDMSNES(dm,&sdm));
22115f80ce2aSJacob Faibussowitsch   PetscCheck(sdm->ops->computepjacobian,PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetPicard() to provide Picard Jacobian.");
2212bbc1464cSBarry Smith   /*  A(x)*x - b(x) */
2213bbc1464cSBarry Smith   if (sdm->ops->computepfunction) {
2214*792fecdfSBarry Smith     PetscCallBack("SNES Picard callback function",(*sdm->ops->computepfunction)(snes,x,f,sdm->pctx));
22159566063dSJacob Faibussowitsch     PetscCall(VecScale(f,-1.0));
22160df40c35SBarry Smith     /* Cannot share nonzero pattern because of the possible use of SNESComputeJacobianDefault() */
2217ef1023bdSBarry Smith     if (!snes->picard) PetscCall(MatDuplicate(snes->jacobian_pre,MAT_DO_NOT_COPY_VALUES,&snes->picard));
2218*792fecdfSBarry Smith     PetscCallBack("SNES Picard callback Jacobian",(*sdm->ops->computepjacobian)(snes,x,snes->picard,snes->picard,sdm->pctx));
22199566063dSJacob Faibussowitsch     PetscCall(MatMultAdd(snes->picard,x,f,f));
2220bbc1464cSBarry Smith   } else {
2221*792fecdfSBarry Smith     PetscCallBack("SNES Picard callback Jacobian",(*sdm->ops->computepjacobian)(snes,x,snes->picard,snes->picard,sdm->pctx));
22229566063dSJacob Faibussowitsch     PetscCall(MatMult(snes->picard,x,f));
2223bbc1464cSBarry Smith   }
2224bbc1464cSBarry Smith   PetscFunctionReturn(0);
2225bbc1464cSBarry Smith }
2226bbc1464cSBarry Smith 
222725acbd8eSLisandro Dalcin PetscErrorCode SNESPicardComputeFunction(SNES snes,Vec x,Vec f,void *ctx)
22288b0a5094SBarry Smith {
2229e03ab78fSPeter Brune   DM             dm;
2230942e3340SBarry Smith   DMSNES         sdm;
22316cab3a1bSJed Brown 
22328b0a5094SBarry Smith   PetscFunctionBegin;
22339566063dSJacob Faibussowitsch   PetscCall(SNESGetDM(snes,&dm));
22349566063dSJacob Faibussowitsch   PetscCall(DMGetDMSNES(dm,&sdm));
22355f80ce2aSJacob Faibussowitsch   PetscCheck(sdm->ops->computepjacobian,PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetPicard() to provide Picard Jacobian.");
22368b0a5094SBarry Smith   /*  A(x)*x - b(x) */
2237bbc1464cSBarry Smith   if (sdm->ops->computepfunction) {
2238*792fecdfSBarry Smith     PetscCallBack("SNES Picard callback function",(*sdm->ops->computepfunction)(snes,x,f,sdm->pctx));
22399566063dSJacob Faibussowitsch     PetscCall(VecScale(f,-1.0));
2240*792fecdfSBarry Smith     PetscCallBack("SNES Picard callback Jacobian",(*sdm->ops->computepjacobian)(snes,x,snes->jacobian,snes->jacobian_pre,sdm->pctx));
22419566063dSJacob Faibussowitsch     PetscCall(MatMultAdd(snes->jacobian_pre,x,f,f));
2242bbc1464cSBarry Smith   } else {
2243*792fecdfSBarry Smith     PetscCallBack("SNES Picard callback Jacobian",(*sdm->ops->computepjacobian)(snes,x,snes->jacobian,snes->jacobian_pre,sdm->pctx));
22449566063dSJacob Faibussowitsch     PetscCall(MatMult(snes->jacobian_pre,x,f));
2245bbc1464cSBarry Smith   }
22468b0a5094SBarry Smith   PetscFunctionReturn(0);
22478b0a5094SBarry Smith }
22488b0a5094SBarry Smith 
224925acbd8eSLisandro Dalcin PetscErrorCode SNESPicardComputeJacobian(SNES snes,Vec x1,Mat J,Mat B,void *ctx)
22508b0a5094SBarry Smith {
22518b0a5094SBarry Smith   PetscFunctionBegin;
2252e03ab78fSPeter Brune   /* the jacobian matrix should be pre-filled in SNESPicardComputeFunction */
2253bbc1464cSBarry Smith   /* must assembly if matrix-free to get the last SNES solution */
22549566063dSJacob Faibussowitsch   PetscCall(MatAssemblyBegin(J,MAT_FINAL_ASSEMBLY));
22559566063dSJacob Faibussowitsch   PetscCall(MatAssemblyEnd(J,MAT_FINAL_ASSEMBLY));
22568b0a5094SBarry Smith   PetscFunctionReturn(0);
22578b0a5094SBarry Smith }
22588b0a5094SBarry Smith 
22598b0a5094SBarry Smith /*@C
2260bbc1464cSBarry Smith    SNESSetPicard - Use SNES to solve the system A(x) x = bp(x) + b via a Picard type iteration (Picard linearization)
22618b0a5094SBarry Smith 
22628b0a5094SBarry Smith    Logically Collective on SNES
22638b0a5094SBarry Smith 
22648b0a5094SBarry Smith    Input Parameters:
22658b0a5094SBarry Smith +  snes - the SNES context
22666b7fb656SBarry Smith .  r - vector to store function values, may be NULL
22676b7fb656SBarry Smith .  bp - function evaluation routine, may be NULL
22686b7fb656SBarry Smith .  Amat - matrix with which A(x) x - bp(x) - b is to be computed
2269e5d3d808SBarry Smith .  Pmat - matrix from which preconditioner is computed (usually the same as Amat)
22706b7fb656SBarry Smith .  J  - function to compute matrix values, see SNESJacobianFunction() for details on its calling sequence
22716b7fb656SBarry Smith -  ctx - [optional] user-defined context for private data for the function evaluation routine (may be NULL)
22728b0a5094SBarry Smith 
22738b0a5094SBarry Smith    Notes:
22746b7fb656SBarry Smith     It is often better to provide the nonlinear function F() and some approximation to its Jacobian directly and use
2275f450aa47SBarry 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.
2276f450aa47SBarry Smith 
22778b0a5094SBarry Smith     One can call SNESSetPicard() or SNESSetFunction() (and possibly SNESSetJacobian()) but cannot call both
22788b0a5094SBarry Smith 
22796b7fb656SBarry 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}
22806b7fb656SBarry 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.
22818b0a5094SBarry Smith 
22828b0a5094SBarry Smith      Run with -snes_mf_operator to solve the system with Newton's method using A(x^{n}) to construct the preconditioner.
22838b0a5094SBarry Smith 
22840d04baf8SBarry Smith    We implement the defect correction form of the Picard iteration because it converges much more generally when inexact linear solvers are used then
22856b7fb656SBarry Smith    the direct Picard iteration A(x^n) x^{n+1} = bp(x^n) + b
22868b0a5094SBarry Smith 
22878b0a5094SBarry 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
22888b0a5094SBarry 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
22898b0a5094SBarry Smith    different please contact us at petsc-dev@mcs.anl.gov and we'll have an entirely new argument :-).
22908b0a5094SBarry Smith 
22916b7fb656SBarry 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.
22926b7fb656SBarry Smith 
22936b7fb656SBarry 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.
22946b7fb656SBarry Smith 
22956b7fb656SBarry 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
22966b7fb656SBarry 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
22976b7fb656SBarry 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.
22986b7fb656SBarry Smith    See the commment in src/snes/tutorials/ex15.c.
2299bbc1464cSBarry Smith 
2300f450aa47SBarry Smith    Level: intermediate
23018b0a5094SBarry Smith 
2302db781477SPatrick Sanan .seealso: `SNESGetFunction()`, `SNESSetFunction()`, `SNESComputeFunction()`, `SNESSetJacobian()`, `SNESGetPicard()`, `SNESLineSearchPreCheckPicard()`, `SNESJacobianFunction`
23038b0a5094SBarry Smith @*/
2304bbc1464cSBarry 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)
23058b0a5094SBarry Smith {
2306e03ab78fSPeter Brune   DM             dm;
2307e03ab78fSPeter Brune 
23088b0a5094SBarry Smith   PetscFunctionBegin;
23098b0a5094SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
23109566063dSJacob Faibussowitsch   PetscCall(SNESGetDM(snes, &dm));
23119566063dSJacob Faibussowitsch   PetscCall(DMSNESSetPicard(dm,bp,J,ctx));
23129566063dSJacob Faibussowitsch   PetscCall(DMSNESSetMFFunction(dm,SNESPicardComputeMFFunction,ctx));
23139566063dSJacob Faibussowitsch   PetscCall(SNESSetFunction(snes,r,SNESPicardComputeFunction,ctx));
23149566063dSJacob Faibussowitsch   PetscCall(SNESSetJacobian(snes,Amat,Pmat,SNESPicardComputeJacobian,ctx));
23158b0a5094SBarry Smith   PetscFunctionReturn(0);
23168b0a5094SBarry Smith }
23178b0a5094SBarry Smith 
23187971a8bfSPeter Brune /*@C
23197971a8bfSPeter Brune    SNESGetPicard - Returns the context for the Picard iteration
23207971a8bfSPeter Brune 
23217971a8bfSPeter Brune    Not Collective, but Vec is parallel if SNES is parallel. Collective if Vec is requested, but has not been created yet.
23227971a8bfSPeter Brune 
23237971a8bfSPeter Brune    Input Parameter:
23247971a8bfSPeter Brune .  snes - the SNES context
23257971a8bfSPeter Brune 
2326d8d19677SJose E. Roman    Output Parameters:
23270298fd71SBarry Smith +  r - the function (or NULL)
2328f8b49ee9SBarry Smith .  f - the function (or NULL); see SNESFunction for calling sequence details
2329e4357dc4SBarry Smith .  Amat - the matrix used to defined the operation A(x) x - b(x) (or NULL)
2330e4357dc4SBarry Smith .  Pmat  - the matrix from which the preconditioner will be constructed (or NULL)
2331f8b49ee9SBarry Smith .  J - the function for matrix evaluation (or NULL); see SNESJacobianFunction for calling sequence details
23320298fd71SBarry Smith -  ctx - the function context (or NULL)
23337971a8bfSPeter Brune 
23347971a8bfSPeter Brune    Level: advanced
23357971a8bfSPeter Brune 
2336db781477SPatrick Sanan .seealso: `SNESSetPicard()`, `SNESGetFunction()`, `SNESGetJacobian()`, `SNESGetDM()`, `SNESFunction`, `SNESJacobianFunction`
23377971a8bfSPeter Brune @*/
2338d1e9a80fSBarry 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)
23397971a8bfSPeter Brune {
23407971a8bfSPeter Brune   DM             dm;
23417971a8bfSPeter Brune 
23427971a8bfSPeter Brune   PetscFunctionBegin;
23437971a8bfSPeter Brune   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
23449566063dSJacob Faibussowitsch   PetscCall(SNESGetFunction(snes,r,NULL,NULL));
23459566063dSJacob Faibussowitsch   PetscCall(SNESGetJacobian(snes,Amat,Pmat,NULL,NULL));
23469566063dSJacob Faibussowitsch   PetscCall(SNESGetDM(snes,&dm));
23479566063dSJacob Faibussowitsch   PetscCall(DMSNESGetPicard(dm,f,J,ctx));
23487971a8bfSPeter Brune   PetscFunctionReturn(0);
23497971a8bfSPeter Brune }
23507971a8bfSPeter Brune 
2351d25893d9SBarry Smith /*@C
2352d25893d9SBarry Smith    SNESSetComputeInitialGuess - Sets a routine used to compute an initial guess for the problem
2353d25893d9SBarry Smith 
2354d25893d9SBarry Smith    Logically Collective on SNES
2355d25893d9SBarry Smith 
2356d25893d9SBarry Smith    Input Parameters:
2357d25893d9SBarry Smith +  snes - the SNES context
2358d25893d9SBarry Smith .  func - function evaluation routine
2359d25893d9SBarry Smith -  ctx - [optional] user-defined context for private data for the
23600298fd71SBarry Smith          function evaluation routine (may be NULL)
2361d25893d9SBarry Smith 
2362d25893d9SBarry Smith    Calling sequence of func:
2363d25893d9SBarry Smith $    func (SNES snes,Vec x,void *ctx);
2364d25893d9SBarry Smith 
2365d25893d9SBarry Smith .  f - function vector
2366d25893d9SBarry Smith -  ctx - optional user-defined function context
2367d25893d9SBarry Smith 
2368d25893d9SBarry Smith    Level: intermediate
2369d25893d9SBarry Smith 
2370db781477SPatrick Sanan .seealso: `SNESGetFunction()`, `SNESComputeFunction()`, `SNESSetJacobian()`
2371d25893d9SBarry Smith @*/
2372d25893d9SBarry Smith PetscErrorCode  SNESSetComputeInitialGuess(SNES snes,PetscErrorCode (*func)(SNES,Vec,void*),void *ctx)
2373d25893d9SBarry Smith {
2374d25893d9SBarry Smith   PetscFunctionBegin;
2375d25893d9SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
2376d25893d9SBarry Smith   if (func) snes->ops->computeinitialguess = func;
2377d25893d9SBarry Smith   if (ctx)  snes->initialguessP            = ctx;
2378d25893d9SBarry Smith   PetscFunctionReturn(0);
2379d25893d9SBarry Smith }
2380d25893d9SBarry Smith 
23813ab0aad5SBarry Smith /* --------------------------------------------------------------- */
23821096aae1SMatthew Knepley /*@C
23831096aae1SMatthew Knepley    SNESGetRhs - Gets the vector for solving F(x) = rhs. If rhs is not set
23841096aae1SMatthew Knepley    it assumes a zero right hand side.
23851096aae1SMatthew Knepley 
23863f9fe445SBarry Smith    Logically Collective on SNES
23871096aae1SMatthew Knepley 
23881096aae1SMatthew Knepley    Input Parameter:
23891096aae1SMatthew Knepley .  snes - the SNES context
23901096aae1SMatthew Knepley 
23911096aae1SMatthew Knepley    Output Parameter:
23920298fd71SBarry Smith .  rhs - the right hand side vector or NULL if the right hand side vector is null
23931096aae1SMatthew Knepley 
23941096aae1SMatthew Knepley    Level: intermediate
23951096aae1SMatthew Knepley 
2396db781477SPatrick Sanan .seealso: `SNESGetSolution()`, `SNESGetFunction()`, `SNESComputeFunction()`, `SNESSetJacobian()`, `SNESSetFunction()`
23971096aae1SMatthew Knepley @*/
23987087cfbeSBarry Smith PetscErrorCode  SNESGetRhs(SNES snes,Vec *rhs)
23991096aae1SMatthew Knepley {
24001096aae1SMatthew Knepley   PetscFunctionBegin;
24010700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
24021096aae1SMatthew Knepley   PetscValidPointer(rhs,2);
240385385478SLisandro Dalcin   *rhs = snes->vec_rhs;
24041096aae1SMatthew Knepley   PetscFunctionReturn(0);
24051096aae1SMatthew Knepley }
24061096aae1SMatthew Knepley 
24079b94acceSBarry Smith /*@
2408bf388a1fSBarry Smith    SNESComputeFunction - Calls the function that has been set with SNESSetFunction().
24099b94acceSBarry Smith 
2410c7afd0dbSLois Curfman McInnes    Collective on SNES
2411c7afd0dbSLois Curfman McInnes 
24129b94acceSBarry Smith    Input Parameters:
2413c7afd0dbSLois Curfman McInnes +  snes - the SNES context
2414c7afd0dbSLois Curfman McInnes -  x - input vector
24159b94acceSBarry Smith 
24169b94acceSBarry Smith    Output Parameter:
24173638b69dSLois Curfman McInnes .  y - function vector, as set by SNESSetFunction()
24189b94acceSBarry Smith 
24191bffabb2SLois Curfman McInnes    Notes:
242036851e7fSLois Curfman McInnes    SNESComputeFunction() is typically used within nonlinear solvers
2421bbc1464cSBarry Smith    implementations, so users would not generally call this routine themselves.
242236851e7fSLois Curfman McInnes 
242336851e7fSLois Curfman McInnes    Level: developer
242436851e7fSLois Curfman McInnes 
2425db781477SPatrick Sanan .seealso: `SNESSetFunction()`, `SNESGetFunction()`, `SNESComputeMFFunction()`
24269b94acceSBarry Smith @*/
24277087cfbeSBarry Smith PetscErrorCode  SNESComputeFunction(SNES snes,Vec x,Vec y)
24289b94acceSBarry Smith {
24296cab3a1bSJed Brown   DM             dm;
2430942e3340SBarry Smith   DMSNES         sdm;
24319b94acceSBarry Smith 
24323a40ed3dSBarry Smith   PetscFunctionBegin;
24330700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
24340700a824SBarry Smith   PetscValidHeaderSpecific(x,VEC_CLASSID,2);
24350700a824SBarry Smith   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
2436c9780b6fSBarry Smith   PetscCheckSameComm(snes,1,x,2);
2437c9780b6fSBarry Smith   PetscCheckSameComm(snes,1,y,3);
24389566063dSJacob Faibussowitsch   PetscCall(VecValidValues(x,2,PETSC_TRUE));
2439184914b5SBarry Smith 
24409566063dSJacob Faibussowitsch   PetscCall(SNESGetDM(snes,&dm));
24419566063dSJacob Faibussowitsch   PetscCall(DMGetDMSNES(dm,&sdm));
244232f3f7c2SPeter Brune   if (sdm->ops->computefunction) {
244394db00ebSBarry Smith     if (sdm->ops->computefunction != SNESObjectiveComputeFunctionDefaultFD) {
24449566063dSJacob Faibussowitsch       PetscCall(PetscLogEventBegin(SNES_FunctionEval,snes,x,y,0));
244594db00ebSBarry Smith     }
24469566063dSJacob Faibussowitsch     PetscCall(VecLockReadPush(x));
24478ddeebeaSSteve Benbow     /* ensure domainerror is false prior to computefunction evaluation (may not have been reset) */
24488ddeebeaSSteve Benbow     snes->domainerror = PETSC_FALSE;
2449*792fecdfSBarry Smith     PetscCallBack("SNES callback function",(*sdm->ops->computefunction)(snes,x,y,sdm->functionctx));
24509566063dSJacob Faibussowitsch     PetscCall(VecLockReadPop(x));
245194db00ebSBarry Smith     if (sdm->ops->computefunction != SNESObjectiveComputeFunctionDefaultFD) {
24529566063dSJacob Faibussowitsch       PetscCall(PetscLogEventEnd(SNES_FunctionEval,snes,x,y,0));
245394db00ebSBarry Smith     }
2454c90fad12SPeter Brune   } else if (snes->vec_rhs) {
24559566063dSJacob Faibussowitsch     PetscCall(MatMult(snes->jacobian, x, y));
2456644e2e5bSBarry Smith   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetFunction() or SNESSetDM() before SNESComputeFunction(), likely called from SNESSolve().");
24571baa6e33SBarry Smith   if (snes->vec_rhs) PetscCall(VecAXPY(y,-1.0,snes->vec_rhs));
2458ae3c334cSLois Curfman McInnes   snes->nfuncs++;
2459422a814eSBarry Smith   /*
2460422a814eSBarry Smith      domainerror might not be set on all processes; so we tag vector locally with Inf and the next inner product or norm will
2461422a814eSBarry Smith      propagate the value to all processes
2462422a814eSBarry Smith   */
24631baa6e33SBarry Smith   if (snes->domainerror) PetscCall(VecSetInf(y));
24643a40ed3dSBarry Smith   PetscFunctionReturn(0);
24659b94acceSBarry Smith }
24669b94acceSBarry Smith 
2467c79ef259SPeter Brune /*@
2468bbc1464cSBarry Smith    SNESComputeMFFunction - Calls the function that has been set with SNESSetMFFunction().
2469bbc1464cSBarry Smith 
2470bbc1464cSBarry Smith    Collective on SNES
2471bbc1464cSBarry Smith 
2472bbc1464cSBarry Smith    Input Parameters:
2473bbc1464cSBarry Smith +  snes - the SNES context
2474bbc1464cSBarry Smith -  x - input vector
2475bbc1464cSBarry Smith 
2476bbc1464cSBarry Smith    Output Parameter:
2477bbc1464cSBarry Smith .  y - function vector, as set by SNESSetMFFunction()
2478bbc1464cSBarry Smith 
2479bbc1464cSBarry Smith    Notes:
2480bbc1464cSBarry Smith        SNESComputeMFFunction() is used within the matrix vector products called by the matrix created with MatCreateSNESMF()
2481bbc1464cSBarry Smith    so users would not generally call this routine themselves.
2482bbc1464cSBarry Smith 
2483bbc1464cSBarry Smith        Since this function is intended for use with finite differencing it does not subtract the right hand side vector provided with SNESSolve()
2484bbc1464cSBarry Smith     while SNESComputeFunction() does. As such, this routine cannot be used with  MatMFFDSetBase() with a provided F function value even if it applies the
2485bbc1464cSBarry 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.
2486bbc1464cSBarry Smith 
2487bbc1464cSBarry Smith    Level: developer
2488bbc1464cSBarry Smith 
2489db781477SPatrick Sanan .seealso: `SNESSetFunction()`, `SNESGetFunction()`, `SNESComputeFunction()`, `MatCreateSNESMF`
2490bbc1464cSBarry Smith @*/
2491bbc1464cSBarry Smith PetscErrorCode  SNESComputeMFFunction(SNES snes,Vec x,Vec y)
2492bbc1464cSBarry Smith {
2493bbc1464cSBarry Smith   DM             dm;
2494bbc1464cSBarry Smith   DMSNES         sdm;
2495bbc1464cSBarry Smith 
2496bbc1464cSBarry Smith   PetscFunctionBegin;
2497bbc1464cSBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
2498bbc1464cSBarry Smith   PetscValidHeaderSpecific(x,VEC_CLASSID,2);
2499bbc1464cSBarry Smith   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
2500bbc1464cSBarry Smith   PetscCheckSameComm(snes,1,x,2);
2501bbc1464cSBarry Smith   PetscCheckSameComm(snes,1,y,3);
25029566063dSJacob Faibussowitsch   PetscCall(VecValidValues(x,2,PETSC_TRUE));
2503bbc1464cSBarry Smith 
25049566063dSJacob Faibussowitsch   PetscCall(SNESGetDM(snes,&dm));
25059566063dSJacob Faibussowitsch   PetscCall(DMGetDMSNES(dm,&sdm));
25069566063dSJacob Faibussowitsch   PetscCall(PetscLogEventBegin(SNES_FunctionEval,snes,x,y,0));
25079566063dSJacob Faibussowitsch   PetscCall(VecLockReadPush(x));
2508bbc1464cSBarry Smith   /* ensure domainerror is false prior to computefunction evaluation (may not have been reset) */
2509bbc1464cSBarry Smith   snes->domainerror = PETSC_FALSE;
2510*792fecdfSBarry Smith   PetscCallBack("SNES callback function",(*sdm->ops->computemffunction)(snes,x,y,sdm->mffunctionctx));
25119566063dSJacob Faibussowitsch   PetscCall(VecLockReadPop(x));
25129566063dSJacob Faibussowitsch   PetscCall(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   */
25181baa6e33SBarry Smith   if (snes->domainerror) PetscCall(VecSetInf(y));
2519bbc1464cSBarry Smith   PetscFunctionReturn(0);
2520bbc1464cSBarry Smith }
2521bbc1464cSBarry Smith 
2522bbc1464cSBarry Smith /*@
2523be95d8f1SBarry Smith    SNESComputeNGS - Calls the Gauss-Seidel function that has been set with  SNESSetNGS().
2524c79ef259SPeter Brune 
2525c79ef259SPeter Brune    Collective on SNES
2526c79ef259SPeter Brune 
2527c79ef259SPeter Brune    Input Parameters:
2528c79ef259SPeter Brune +  snes - the SNES context
2529c79ef259SPeter Brune .  x - input vector
2530c79ef259SPeter Brune -  b - rhs vector
2531c79ef259SPeter Brune 
2532c79ef259SPeter Brune    Output Parameter:
2533c79ef259SPeter Brune .  x - new solution vector
2534c79ef259SPeter Brune 
2535c79ef259SPeter Brune    Notes:
2536be95d8f1SBarry Smith    SNESComputeNGS() is typically used within composed nonlinear solver
2537c79ef259SPeter Brune    implementations, so most users would not generally call this routine
2538c79ef259SPeter Brune    themselves.
2539c79ef259SPeter Brune 
2540c79ef259SPeter Brune    Level: developer
2541c79ef259SPeter Brune 
2542db781477SPatrick Sanan .seealso: `SNESSetNGS()`, `SNESComputeFunction()`
2543c79ef259SPeter Brune @*/
2544be95d8f1SBarry Smith PetscErrorCode  SNESComputeNGS(SNES snes,Vec b,Vec x)
2545646217ecSPeter Brune {
25466cab3a1bSJed Brown   DM             dm;
2547942e3340SBarry Smith   DMSNES         sdm;
2548646217ecSPeter Brune 
2549646217ecSPeter Brune   PetscFunctionBegin;
2550646217ecSPeter Brune   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
2551064a246eSJacob Faibussowitsch   PetscValidHeaderSpecific(x,VEC_CLASSID,3);
2552064a246eSJacob Faibussowitsch   if (b) PetscValidHeaderSpecific(b,VEC_CLASSID,2);
2553064a246eSJacob Faibussowitsch   PetscCheckSameComm(snes,1,x,3);
2554064a246eSJacob Faibussowitsch   if (b) PetscCheckSameComm(snes,1,b,2);
25559566063dSJacob Faibussowitsch   if (b) PetscCall(VecValidValues(b,2,PETSC_TRUE));
25569566063dSJacob Faibussowitsch   PetscCall(PetscLogEventBegin(SNES_NGSEval,snes,x,b,0));
25579566063dSJacob Faibussowitsch   PetscCall(SNESGetDM(snes,&dm));
25589566063dSJacob Faibussowitsch   PetscCall(DMGetDMSNES(dm,&sdm));
255922c6f798SBarry Smith   if (sdm->ops->computegs) {
25609566063dSJacob Faibussowitsch     if (b) PetscCall(VecLockReadPush(b));
2561*792fecdfSBarry Smith     PetscCallBack("SNES callback NGS",(*sdm->ops->computegs)(snes,x,b,sdm->gsctx));
25629566063dSJacob Faibussowitsch     if (b) PetscCall(VecLockReadPop(b));
2563be95d8f1SBarry Smith   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetNGS() before SNESComputeNGS(), likely called from SNESSolve().");
25649566063dSJacob Faibussowitsch   PetscCall(PetscLogEventEnd(SNES_NGSEval,snes,x,b,0));
2565646217ecSPeter Brune   PetscFunctionReturn(0);
2566646217ecSPeter Brune }
2567646217ecSPeter Brune 
2568e885f1abSBarry Smith PetscErrorCode SNESTestJacobian(SNES snes)
2569e885f1abSBarry Smith {
257012837594SBarry Smith   Mat               A,B,C,D,jacobian;
2571e885f1abSBarry Smith   Vec               x = snes->vec_sol,f = snes->vec_func;
2572e885f1abSBarry Smith   PetscReal         nrm,gnorm;
257381e7118cSBarry Smith   PetscReal         threshold = 1.e-5;
25740e276705SLisandro Dalcin   MatType           mattype;
2575e885f1abSBarry Smith   PetscInt          m,n,M,N;
2576e885f1abSBarry Smith   void              *functx;
25772cd624f9SStefano Zampini   PetscBool         complete_print = PETSC_FALSE,threshold_print = PETSC_FALSE,test = PETSC_FALSE,flg,istranspose;
25783325ff46SBarry Smith   PetscViewer       viewer,mviewer;
2579e885f1abSBarry Smith   MPI_Comm          comm;
2580e885f1abSBarry Smith   PetscInt          tabs;
258112837594SBarry Smith   static PetscBool  directionsprinted = PETSC_FALSE;
25823325ff46SBarry Smith   PetscViewerFormat format;
2583e885f1abSBarry Smith 
2584e885f1abSBarry Smith   PetscFunctionBegin;
2585d0609cedSBarry Smith   PetscObjectOptionsBegin((PetscObject)snes);
25869566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-snes_test_jacobian","Compare hand-coded and finite difference Jacobians","None",&test));
25879566063dSJacob Faibussowitsch   PetscCall(PetscOptionsReal("-snes_test_jacobian", "Threshold for element difference between hand-coded and finite difference being meaningful", "None", threshold, &threshold,NULL));
25889566063dSJacob Faibussowitsch   PetscCall(PetscOptionsViewer("-snes_test_jacobian_view","View difference between hand-coded and finite difference Jacobians element entries","None",&mviewer,&format,&complete_print));
258918d89885SKarl Rupp   if (!complete_print) {
25909566063dSJacob Faibussowitsch     PetscCall(PetscOptionsDeprecated("-snes_test_jacobian_display","-snes_test_jacobian_view","3.13",NULL));
25919566063dSJacob Faibussowitsch     PetscCall(PetscOptionsViewer("-snes_test_jacobian_display","Display difference between hand-coded and finite difference Jacobians","None",&mviewer,&format,&complete_print));
259218d89885SKarl Rupp   }
259318d89885SKarl Rupp   /* for compatibility with PETSc 3.9 and older. */
25949566063dSJacob Faibussowitsch   PetscCall(PetscOptionsDeprecated("-snes_test_jacobian_display_threshold","-snes_test_jacobian","3.13","-snes_test_jacobian accepts an optional threshold (since v3.10)"));
25959566063dSJacob Faibussowitsch   PetscCall(PetscOptionsReal("-snes_test_jacobian_display_threshold", "Display difference between hand-coded and finite difference Jacobians which exceed input threshold", "None", threshold, &threshold, &threshold_print));
2596d0609cedSBarry Smith   PetscOptionsEnd();
2597e885f1abSBarry Smith   if (!test) PetscFunctionReturn(0);
2598e885f1abSBarry Smith 
25999566063dSJacob Faibussowitsch   PetscCall(PetscObjectGetComm((PetscObject)snes,&comm));
26009566063dSJacob Faibussowitsch   PetscCall(PetscViewerASCIIGetStdout(comm,&viewer));
26019566063dSJacob Faibussowitsch   PetscCall(PetscViewerASCIIGetTab(viewer, &tabs));
26029566063dSJacob Faibussowitsch   PetscCall(PetscViewerASCIISetTab(viewer, ((PetscObject)snes)->tablevel));
26039566063dSJacob Faibussowitsch   PetscCall(PetscViewerASCIIPrintf(viewer,"  ---------- Testing Jacobian -------------\n"));
260412837594SBarry Smith   if (!complete_print && !directionsprinted) {
26059566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPrintf(viewer,"  Run with -snes_test_jacobian_view and optionally -snes_test_jacobian <threshold> to show difference\n"));
26069566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPrintf(viewer,"    of hand-coded and finite difference Jacobian entries greater than <threshold>.\n"));
260712837594SBarry Smith   }
260812837594SBarry Smith   if (!directionsprinted) {
26099566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPrintf(viewer,"  Testing hand-coded Jacobian, if (for double precision runs) ||J - Jfd||_F/||J||_F is\n"));
26109566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPrintf(viewer,"    O(1.e-8), the hand-coded Jacobian is probably correct.\n"));
261112837594SBarry Smith     directionsprinted = PETSC_TRUE;
2612e885f1abSBarry Smith   }
26131baa6e33SBarry Smith   if (complete_print) PetscCall(PetscViewerPushFormat(mviewer,format));
2614e885f1abSBarry Smith 
26159566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)snes->jacobian,MATMFFD,&flg));
261612837594SBarry Smith   if (!flg) jacobian = snes->jacobian;
261712837594SBarry Smith   else jacobian = snes->jacobian_pre;
261812837594SBarry Smith 
2619a82339d0SMatthew G. Knepley   if (!x) {
26209566063dSJacob Faibussowitsch     PetscCall(MatCreateVecs(jacobian, &x, NULL));
2621a82339d0SMatthew G. Knepley   } else {
26229566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject) x));
2623a82339d0SMatthew G. Knepley   }
2624a82339d0SMatthew G. Knepley   if (!f) {
26259566063dSJacob Faibussowitsch     PetscCall(VecDuplicate(x, &f));
2626a82339d0SMatthew G. Knepley   } else {
26279566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject) f));
2628a82339d0SMatthew G. Knepley   }
2629a82339d0SMatthew G. Knepley   /* evaluate the function at this point because SNESComputeJacobianDefault() assumes that the function has been evaluated and put into snes->vec_func */
26309566063dSJacob Faibussowitsch   PetscCall(SNESComputeFunction(snes,x,f));
26319566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&f));
26329566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)snes,SNESKSPTRANSPOSEONLY,&istranspose));
263312837594SBarry Smith   while (jacobian) {
26342cd624f9SStefano Zampini     Mat JT = NULL, Jsave = NULL;
26352cd624f9SStefano Zampini 
26362cd624f9SStefano Zampini     if (istranspose) {
26379566063dSJacob Faibussowitsch       PetscCall(MatCreateTranspose(jacobian,&JT));
26382cd624f9SStefano Zampini       Jsave = jacobian;
26392cd624f9SStefano Zampini       jacobian = JT;
26402cd624f9SStefano Zampini     }
26419566063dSJacob Faibussowitsch     PetscCall(PetscObjectBaseTypeCompareAny((PetscObject)jacobian,&flg,MATSEQAIJ,MATMPIAIJ,MATSEQDENSE,MATMPIDENSE,MATSEQBAIJ,MATMPIBAIJ,MATSEQSBAIJ,MATMPISBAIJ,""));
264212837594SBarry Smith     if (flg) {
264312837594SBarry Smith       A    = jacobian;
26449566063dSJacob Faibussowitsch       PetscCall(PetscObjectReference((PetscObject)A));
264512837594SBarry Smith     } else {
26469566063dSJacob Faibussowitsch       PetscCall(MatComputeOperator(jacobian,MATAIJ,&A));
264712837594SBarry Smith     }
2648e885f1abSBarry Smith 
26499566063dSJacob Faibussowitsch     PetscCall(MatGetType(A,&mattype));
26509566063dSJacob Faibussowitsch     PetscCall(MatGetSize(A,&M,&N));
26519566063dSJacob Faibussowitsch     PetscCall(MatGetLocalSize(A,&m,&n));
26529566063dSJacob Faibussowitsch     PetscCall(MatCreate(PetscObjectComm((PetscObject)A),&B));
26539566063dSJacob Faibussowitsch     PetscCall(MatSetType(B,mattype));
26549566063dSJacob Faibussowitsch     PetscCall(MatSetSizes(B,m,n,M,N));
26559566063dSJacob Faibussowitsch     PetscCall(MatSetBlockSizesFromMats(B,A,A));
26569566063dSJacob Faibussowitsch     PetscCall(MatSetUp(B));
26579566063dSJacob Faibussowitsch     PetscCall(MatSetOption(B,MAT_NEW_NONZERO_ALLOCATION_ERR,PETSC_FALSE));
2658e885f1abSBarry Smith 
26599566063dSJacob Faibussowitsch     PetscCall(SNESGetFunction(snes,NULL,NULL,&functx));
26609566063dSJacob Faibussowitsch     PetscCall(SNESComputeJacobianDefault(snes,x,B,B,functx));
266112837594SBarry Smith 
26629566063dSJacob Faibussowitsch     PetscCall(MatDuplicate(B,MAT_COPY_VALUES,&D));
26639566063dSJacob Faibussowitsch     PetscCall(MatAYPX(D,-1.0,A,DIFFERENT_NONZERO_PATTERN));
26649566063dSJacob Faibussowitsch     PetscCall(MatNorm(D,NORM_FROBENIUS,&nrm));
26659566063dSJacob Faibussowitsch     PetscCall(MatNorm(A,NORM_FROBENIUS,&gnorm));
26669566063dSJacob Faibussowitsch     PetscCall(MatDestroy(&D));
266712837594SBarry Smith     if (!gnorm) gnorm = 1; /* just in case */
26689566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPrintf(viewer,"  ||J - Jfd||_F/||J||_F = %g, ||J - Jfd||_F = %g\n",(double)(nrm/gnorm),(double)nrm));
266912837594SBarry Smith 
2670e885f1abSBarry Smith     if (complete_print) {
26719566063dSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPrintf(viewer,"  Hand-coded Jacobian ----------\n"));
26729566063dSJacob Faibussowitsch       PetscCall(MatView(A,mviewer));
26739566063dSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPrintf(viewer,"  Finite difference Jacobian ----------\n"));
26749566063dSJacob Faibussowitsch       PetscCall(MatView(B,mviewer));
2675e885f1abSBarry Smith     }
2676e885f1abSBarry Smith 
2677df10fb39SFande Kong     if (threshold_print || complete_print) {
2678e885f1abSBarry Smith       PetscInt          Istart, Iend, *ccols, bncols, cncols, j, row;
2679e885f1abSBarry Smith       PetscScalar       *cvals;
2680e885f1abSBarry Smith       const PetscInt    *bcols;
2681e885f1abSBarry Smith       const PetscScalar *bvals;
2682e885f1abSBarry Smith 
26839566063dSJacob Faibussowitsch       PetscCall(MatCreate(PetscObjectComm((PetscObject)A),&C));
26849566063dSJacob Faibussowitsch       PetscCall(MatSetType(C,mattype));
26859566063dSJacob Faibussowitsch       PetscCall(MatSetSizes(C,m,n,M,N));
26869566063dSJacob Faibussowitsch       PetscCall(MatSetBlockSizesFromMats(C,A,A));
26879566063dSJacob Faibussowitsch       PetscCall(MatSetUp(C));
26889566063dSJacob Faibussowitsch       PetscCall(MatSetOption(C,MAT_NEW_NONZERO_ALLOCATION_ERR,PETSC_FALSE));
26890e276705SLisandro Dalcin 
26909566063dSJacob Faibussowitsch       PetscCall(MatAYPX(B,-1.0,A,DIFFERENT_NONZERO_PATTERN));
26919566063dSJacob Faibussowitsch       PetscCall(MatGetOwnershipRange(B,&Istart,&Iend));
2692e885f1abSBarry Smith 
2693e885f1abSBarry Smith       for (row = Istart; row < Iend; row++) {
26949566063dSJacob Faibussowitsch         PetscCall(MatGetRow(B,row,&bncols,&bcols,&bvals));
26959566063dSJacob Faibussowitsch         PetscCall(PetscMalloc2(bncols,&ccols,bncols,&cvals));
2696e885f1abSBarry Smith         for (j = 0, cncols = 0; j < bncols; j++) {
269723a52b1dSBarry Smith           if (PetscAbsScalar(bvals[j]) > threshold) {
2698e885f1abSBarry Smith             ccols[cncols] = bcols[j];
2699e885f1abSBarry Smith             cvals[cncols] = bvals[j];
2700e885f1abSBarry Smith             cncols += 1;
2701e885f1abSBarry Smith           }
2702e885f1abSBarry Smith         }
2703e885f1abSBarry Smith         if (cncols) {
27049566063dSJacob Faibussowitsch           PetscCall(MatSetValues(C,1,&row,cncols,ccols,cvals,INSERT_VALUES));
2705e885f1abSBarry Smith         }
27069566063dSJacob Faibussowitsch         PetscCall(MatRestoreRow(B,row,&bncols,&bcols,&bvals));
27079566063dSJacob Faibussowitsch         PetscCall(PetscFree2(ccols,cvals));
2708e885f1abSBarry Smith       }
27099566063dSJacob Faibussowitsch       PetscCall(MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY));
27109566063dSJacob Faibussowitsch       PetscCall(MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY));
27119566063dSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPrintf(viewer,"  Hand-coded minus finite-difference Jacobian with tolerance %g ----------\n",(double)threshold));
27129566063dSJacob Faibussowitsch       PetscCall(MatView(C,complete_print ? mviewer : viewer));
27139566063dSJacob Faibussowitsch       PetscCall(MatDestroy(&C));
2714e885f1abSBarry Smith     }
27159566063dSJacob Faibussowitsch     PetscCall(MatDestroy(&A));
27169566063dSJacob Faibussowitsch     PetscCall(MatDestroy(&B));
27179566063dSJacob Faibussowitsch     PetscCall(MatDestroy(&JT));
27182cd624f9SStefano Zampini     if (Jsave) jacobian = Jsave;
271912837594SBarry Smith     if (jacobian != snes->jacobian_pre) {
272012837594SBarry Smith       jacobian = snes->jacobian_pre;
27219566063dSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPrintf(viewer,"  ---------- Testing Jacobian for preconditioner -------------\n"));
272212837594SBarry Smith     }
272312837594SBarry Smith     else jacobian = NULL;
272412837594SBarry Smith   }
27259566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&x));
27261baa6e33SBarry Smith   if (complete_print) PetscCall(PetscViewerPopFormat(mviewer));
27279566063dSJacob Faibussowitsch   if (mviewer) PetscCall(PetscViewerDestroy(&mviewer));
27289566063dSJacob Faibussowitsch   PetscCall(PetscViewerASCIISetTab(viewer,tabs));
2729e885f1abSBarry Smith   PetscFunctionReturn(0);
2730e885f1abSBarry Smith }
2731e885f1abSBarry Smith 
273262fef451SLois Curfman McInnes /*@
2733bf388a1fSBarry Smith    SNESComputeJacobian - Computes the Jacobian matrix that has been set with SNESSetJacobian().
273462fef451SLois Curfman McInnes 
2735d083f849SBarry Smith    Collective on SNES
2736c7afd0dbSLois Curfman McInnes 
273762fef451SLois Curfman McInnes    Input Parameters:
2738c7afd0dbSLois Curfman McInnes +  snes - the SNES context
2739c7afd0dbSLois Curfman McInnes -  x - input vector
274062fef451SLois Curfman McInnes 
274162fef451SLois Curfman McInnes    Output Parameters:
2742c7afd0dbSLois Curfman McInnes +  A - Jacobian matrix
2743d1e9a80fSBarry Smith -  B - optional preconditioning matrix
2744fee21e36SBarry Smith 
2745e35cf81dSBarry Smith   Options Database Keys:
274667b8a455SSatish Balay +    -snes_lag_preconditioner <lag> - how often to rebuild preconditioner
274767b8a455SSatish Balay .    -snes_lag_jacobian <lag> - how often to rebuild Jacobian
2748455a5933SJed 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.
2749455a5933SJed 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
2750693365a8SJed Brown .    -snes_compare_explicit - Compare the computed Jacobian to the finite difference Jacobian and output the differences
2751693365a8SJed Brown .    -snes_compare_explicit_draw  - Compare the computed Jacobian to the finite difference Jacobian and draw the result
2752693365a8SJed Brown .    -snes_compare_explicit_contour  - Compare the computed Jacobian to the finite difference Jacobian and draw a contour plot with the result
27534c30e9fbSJed Brown .    -snes_compare_operator  - Make the comparison options above use the operator instead of the preconditioning matrix
275494d6a431SBarry Smith .    -snes_compare_coloring - Compute the finite difference Jacobian using coloring and display norms of difference
2755a5b23f4aSJose E. Roman .    -snes_compare_coloring_display - Compute the finite difference Jacobian using coloring and display verbose differences
2756c01495d3SJed Brown .    -snes_compare_coloring_threshold - Display only those matrix entries that differ by more than a given threshold
2757c01495d3SJed Brown .    -snes_compare_coloring_threshold_atol - Absolute tolerance for difference in matrix entries to be displayed by -snes_compare_coloring_threshold
2758c01495d3SJed Brown .    -snes_compare_coloring_threshold_rtol - Relative tolerance for difference in matrix entries to be displayed by -snes_compare_coloring_threshold
2759a5b23f4aSJose E. Roman .    -snes_compare_coloring_draw - Compute the finite difference Jacobian using coloring and draw differences
2760a5b23f4aSJose E. Roman -    -snes_compare_coloring_draw_contour - Compute the finite difference Jacobian using coloring and show contours of matrices and differences
2761c01495d3SJed Brown 
276262fef451SLois Curfman McInnes    Notes:
276362fef451SLois Curfman McInnes    Most users should not need to explicitly call this routine, as it
276462fef451SLois Curfman McInnes    is used internally within the nonlinear solvers.
276562fef451SLois Curfman McInnes 
276695452b02SPatrick Sanan    Developer Notes:
276795452b02SPatrick 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
2768e885f1abSBarry Smith       for with the SNESType of test that has been removed.
2769e885f1abSBarry Smith 
277036851e7fSLois Curfman McInnes    Level: developer
277136851e7fSLois Curfman McInnes 
2772db781477SPatrick Sanan .seealso: `SNESSetJacobian()`, `KSPSetOperators()`, `MatStructure`, `SNESSetLagPreconditioner()`, `SNESSetLagJacobian()`
277362fef451SLois Curfman McInnes @*/
2774d1e9a80fSBarry Smith PetscErrorCode  SNESComputeJacobian(SNES snes,Vec X,Mat A,Mat B)
27759b94acceSBarry Smith {
2776ace3abfcSBarry Smith   PetscBool      flag;
27776cab3a1bSJed Brown   DM             dm;
2778942e3340SBarry Smith   DMSNES         sdm;
2779e0e3a89bSBarry Smith   KSP            ksp;
27803a40ed3dSBarry Smith 
27813a40ed3dSBarry Smith   PetscFunctionBegin;
27820700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
27830700a824SBarry Smith   PetscValidHeaderSpecific(X,VEC_CLASSID,2);
2784c9780b6fSBarry Smith   PetscCheckSameComm(snes,1,X,2);
27859566063dSJacob Faibussowitsch   PetscCall(VecValidValues(X,2,PETSC_TRUE));
27869566063dSJacob Faibussowitsch   PetscCall(SNESGetDM(snes,&dm));
27879566063dSJacob Faibussowitsch   PetscCall(DMGetDMSNES(dm,&sdm));
27883232da50SPeter Brune 
27895f80ce2aSJacob Faibussowitsch   PetscCheck(sdm->ops->computejacobian,PetscObjectComm((PetscObject)snes),PETSC_ERR_USER,"Must call SNESSetJacobian(), DMSNESSetJacobian(), DMDASNESSetJacobianLocal(), etc");
2790ebd3b9afSBarry Smith 
2791ebd3b9afSBarry Smith   /* make sure that MatAssemblyBegin/End() is called on A matrix if it is matrix free */
2792ebd3b9afSBarry Smith 
2793fe3ffe1eSBarry Smith   if (snes->lagjacobian == -2) {
2794fe3ffe1eSBarry Smith     snes->lagjacobian = -1;
2795f5af7f23SKarl Rupp 
27969566063dSJacob Faibussowitsch     PetscCall(PetscInfo(snes,"Recomputing Jacobian/preconditioner because lag is -2 (means compute Jacobian, but then never again) \n"));
2797fe3ffe1eSBarry Smith   } else if (snes->lagjacobian == -1) {
27989566063dSJacob Faibussowitsch     PetscCall(PetscInfo(snes,"Reusing Jacobian/preconditioner because lag is -1\n"));
27999566063dSJacob Faibussowitsch     PetscCall(PetscObjectTypeCompare((PetscObject)A,MATMFFD,&flag));
2800ebd3b9afSBarry Smith     if (flag) {
28019566063dSJacob Faibussowitsch       PetscCall(MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY));
28029566063dSJacob Faibussowitsch       PetscCall(MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY));
2803ebd3b9afSBarry Smith     }
2804e35cf81dSBarry Smith     PetscFunctionReturn(0);
280537ec4e1aSPeter Brune   } else if (snes->lagjacobian > 1 && (snes->iter + snes->jac_iter) % snes->lagjacobian) {
280663a3b9bcSJacob Faibussowitsch     PetscCall(PetscInfo(snes,"Reusing Jacobian/preconditioner because lag is %" PetscInt_FMT " and SNES iteration is %" PetscInt_FMT "\n",snes->lagjacobian,snes->iter));
28079566063dSJacob Faibussowitsch     PetscCall(PetscObjectTypeCompare((PetscObject)A,MATMFFD,&flag));
2808ebd3b9afSBarry Smith     if (flag) {
28099566063dSJacob Faibussowitsch       PetscCall(MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY));
28109566063dSJacob Faibussowitsch       PetscCall(MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY));
2811ebd3b9afSBarry Smith     }
2812e35cf81dSBarry Smith     PetscFunctionReturn(0);
2813e35cf81dSBarry Smith   }
2814efd4aadfSBarry Smith   if (snes->npc && snes->npcside == PC_LEFT) {
28159566063dSJacob Faibussowitsch     PetscCall(MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY));
28169566063dSJacob Faibussowitsch     PetscCall(MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY));
2817d728fb7dSPeter Brune     PetscFunctionReturn(0);
2818d728fb7dSPeter Brune   }
2819e35cf81dSBarry Smith 
28209566063dSJacob Faibussowitsch   PetscCall(PetscLogEventBegin(SNES_JacobianEval,snes,X,A,B));
28219566063dSJacob Faibussowitsch   PetscCall(VecLockReadPush(X));
2822*792fecdfSBarry Smith   PetscCallBack("SNES callback Jacobian",(*sdm->ops->computejacobian)(snes,X,A,B,sdm->jacobianctx));
28239566063dSJacob Faibussowitsch   PetscCall(VecLockReadPop(X));
28249566063dSJacob Faibussowitsch   PetscCall(PetscLogEventEnd(SNES_JacobianEval,snes,X,A,B));
282528d58a37SPierre Jolivet 
282628d58a37SPierre Jolivet   /* attach latest linearization point to the preconditioning matrix */
28279566063dSJacob Faibussowitsch   PetscCall(PetscObjectCompose((PetscObject)B,"__SNES_latest_X",(PetscObject)X));
2828a8054027SBarry Smith 
2829e0e3a89bSBarry Smith   /* the next line ensures that snes->ksp exists */
28309566063dSJacob Faibussowitsch   PetscCall(SNESGetKSP(snes,&ksp));
28313b4f5425SBarry Smith   if (snes->lagpreconditioner == -2) {
28329566063dSJacob Faibussowitsch     PetscCall(PetscInfo(snes,"Rebuilding preconditioner exactly once since lag is -2\n"));
28339566063dSJacob Faibussowitsch     PetscCall(KSPSetReusePreconditioner(snes->ksp,PETSC_FALSE));
28343b4f5425SBarry Smith     snes->lagpreconditioner = -1;
28353b4f5425SBarry Smith   } else if (snes->lagpreconditioner == -1) {
28369566063dSJacob Faibussowitsch     PetscCall(PetscInfo(snes,"Reusing preconditioner because lag is -1\n"));
28379566063dSJacob Faibussowitsch     PetscCall(KSPSetReusePreconditioner(snes->ksp,PETSC_TRUE));
283837ec4e1aSPeter Brune   } else if (snes->lagpreconditioner > 1 && (snes->iter + snes->pre_iter) % snes->lagpreconditioner) {
283963a3b9bcSJacob Faibussowitsch     PetscCall(PetscInfo(snes,"Reusing preconditioner because lag is %" PetscInt_FMT " and SNES iteration is %" PetscInt_FMT "\n",snes->lagpreconditioner,snes->iter));
28409566063dSJacob Faibussowitsch     PetscCall(KSPSetReusePreconditioner(snes->ksp,PETSC_TRUE));
2841d1e9a80fSBarry Smith   } else {
28429566063dSJacob Faibussowitsch     PetscCall(PetscInfo(snes,"Rebuilding preconditioner\n"));
28439566063dSJacob Faibussowitsch     PetscCall(KSPSetReusePreconditioner(snes->ksp,PETSC_FALSE));
2844a8054027SBarry Smith   }
2845a8054027SBarry Smith 
28469566063dSJacob Faibussowitsch   PetscCall(SNESTestJacobian(snes));
28476d84be18SBarry Smith   /* make sure user returned a correct Jacobian and preconditioner */
284894ab13aaSBarry Smith   /* PetscValidHeaderSpecific(A,MAT_CLASSID,3);
284994ab13aaSBarry Smith     PetscValidHeaderSpecific(B,MAT_CLASSID,4);   */
2850693365a8SJed Brown   {
2851693365a8SJed Brown     PetscBool flag = PETSC_FALSE,flag_draw = PETSC_FALSE,flag_contour = PETSC_FALSE,flag_operator = PETSC_FALSE;
28529566063dSJacob Faibussowitsch     PetscCall(PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject) snes)->options,((PetscObject)snes)->prefix,"-snes_compare_explicit",NULL,NULL,&flag));
28539566063dSJacob Faibussowitsch     PetscCall(PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject) snes)->options,((PetscObject)snes)->prefix,"-snes_compare_explicit_draw",NULL,NULL,&flag_draw));
28549566063dSJacob Faibussowitsch     PetscCall(PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject) snes)->options,((PetscObject)snes)->prefix,"-snes_compare_explicit_draw_contour",NULL,NULL,&flag_contour));
28559566063dSJacob Faibussowitsch     PetscCall(PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject) snes)->options,((PetscObject)snes)->prefix,"-snes_compare_operator",NULL,NULL,&flag_operator));
2856693365a8SJed Brown     if (flag || flag_draw || flag_contour) {
28570298fd71SBarry Smith       Mat          Bexp_mine = NULL,Bexp,FDexp;
2858693365a8SJed Brown       PetscViewer  vdraw,vstdout;
28596b3a5b13SJed Brown       PetscBool    flg;
2860693365a8SJed Brown       if (flag_operator) {
28619566063dSJacob Faibussowitsch         PetscCall(MatComputeOperator(A,MATAIJ,&Bexp_mine));
2862693365a8SJed Brown         Bexp = Bexp_mine;
2863693365a8SJed Brown       } else {
2864693365a8SJed Brown         /* See if the preconditioning matrix can be viewed and added directly */
28659566063dSJacob Faibussowitsch         PetscCall(PetscObjectBaseTypeCompareAny((PetscObject)B,&flg,MATSEQAIJ,MATMPIAIJ,MATSEQDENSE,MATMPIDENSE,MATSEQBAIJ,MATMPIBAIJ,MATSEQSBAIJ,MATMPIBAIJ,""));
286694ab13aaSBarry Smith         if (flg) Bexp = B;
2867693365a8SJed Brown         else {
2868693365a8SJed Brown           /* If the "preconditioning" matrix is itself MATSHELL or some other type without direct support */
28699566063dSJacob Faibussowitsch           PetscCall(MatComputeOperator(B,MATAIJ,&Bexp_mine));
2870693365a8SJed Brown           Bexp = Bexp_mine;
2871693365a8SJed Brown         }
2872693365a8SJed Brown       }
28739566063dSJacob Faibussowitsch       PetscCall(MatConvert(Bexp,MATSAME,MAT_INITIAL_MATRIX,&FDexp));
28749566063dSJacob Faibussowitsch       PetscCall(SNESComputeJacobianDefault(snes,X,FDexp,FDexp,NULL));
28759566063dSJacob Faibussowitsch       PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes),&vstdout));
2876693365a8SJed Brown       if (flag_draw || flag_contour) {
28779566063dSJacob Faibussowitsch         PetscCall(PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes),NULL,"Explicit Jacobians",PETSC_DECIDE,PETSC_DECIDE,300,300,&vdraw));
28789566063dSJacob Faibussowitsch         if (flag_contour) PetscCall(PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR));
28790298fd71SBarry Smith       } else vdraw = NULL;
28809566063dSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPrintf(vstdout,"Explicit %s\n",flag_operator ? "Jacobian" : "preconditioning Jacobian"));
28819566063dSJacob Faibussowitsch       if (flag) PetscCall(MatView(Bexp,vstdout));
28829566063dSJacob Faibussowitsch       if (vdraw) PetscCall(MatView(Bexp,vdraw));
28839566063dSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPrintf(vstdout,"Finite difference Jacobian\n"));
28849566063dSJacob Faibussowitsch       if (flag) PetscCall(MatView(FDexp,vstdout));
28859566063dSJacob Faibussowitsch       if (vdraw) PetscCall(MatView(FDexp,vdraw));
28869566063dSJacob Faibussowitsch       PetscCall(MatAYPX(FDexp,-1.0,Bexp,SAME_NONZERO_PATTERN));
28879566063dSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPrintf(vstdout,"User-provided matrix minus finite difference Jacobian\n"));
28889566063dSJacob Faibussowitsch       if (flag) PetscCall(MatView(FDexp,vstdout));
2889693365a8SJed Brown       if (vdraw) {              /* Always use contour for the difference */
28909566063dSJacob Faibussowitsch         PetscCall(PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR));
28919566063dSJacob Faibussowitsch         PetscCall(MatView(FDexp,vdraw));
28929566063dSJacob Faibussowitsch         PetscCall(PetscViewerPopFormat(vdraw));
2893693365a8SJed Brown       }
28949566063dSJacob Faibussowitsch       if (flag_contour) PetscCall(PetscViewerPopFormat(vdraw));
28959566063dSJacob Faibussowitsch       PetscCall(PetscViewerDestroy(&vdraw));
28969566063dSJacob Faibussowitsch       PetscCall(MatDestroy(&Bexp_mine));
28979566063dSJacob Faibussowitsch       PetscCall(MatDestroy(&FDexp));
2898693365a8SJed Brown     }
2899693365a8SJed Brown   }
29004c30e9fbSJed Brown   {
29016719d8e4SJed Brown     PetscBool flag = PETSC_FALSE,flag_display = PETSC_FALSE,flag_draw = PETSC_FALSE,flag_contour = PETSC_FALSE,flag_threshold = PETSC_FALSE;
29026719d8e4SJed Brown     PetscReal threshold_atol = PETSC_SQRT_MACHINE_EPSILON,threshold_rtol = 10*PETSC_SQRT_MACHINE_EPSILON;
29039566063dSJacob Faibussowitsch     PetscCall(PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring",NULL,NULL,&flag));
29049566063dSJacob Faibussowitsch     PetscCall(PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_display",NULL,NULL,&flag_display));
29059566063dSJacob Faibussowitsch     PetscCall(PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_draw",NULL,NULL,&flag_draw));
29069566063dSJacob Faibussowitsch     PetscCall(PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_draw_contour",NULL,NULL,&flag_contour));
29079566063dSJacob Faibussowitsch     PetscCall(PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_threshold",NULL,NULL,&flag_threshold));
290827b0f280SBarry Smith     if (flag_threshold) {
29099566063dSJacob Faibussowitsch       PetscCall(PetscOptionsGetReal(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_threshold_rtol",&threshold_rtol,NULL));
29109566063dSJacob Faibussowitsch       PetscCall(PetscOptionsGetReal(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_threshold_atol",&threshold_atol,NULL));
291127b0f280SBarry Smith     }
29126719d8e4SJed Brown     if (flag || flag_display || flag_draw || flag_contour || flag_threshold) {
29134c30e9fbSJed Brown       Mat            Bfd;
29144c30e9fbSJed Brown       PetscViewer    vdraw,vstdout;
2915335efc43SPeter Brune       MatColoring    coloring;
29164c30e9fbSJed Brown       ISColoring     iscoloring;
29174c30e9fbSJed Brown       MatFDColoring  matfdcoloring;
29184c30e9fbSJed Brown       PetscErrorCode (*func)(SNES,Vec,Vec,void*);
29194c30e9fbSJed Brown       void           *funcctx;
29206719d8e4SJed Brown       PetscReal      norm1,norm2,normmax;
29214c30e9fbSJed Brown 
29229566063dSJacob Faibussowitsch       PetscCall(MatDuplicate(B,MAT_DO_NOT_COPY_VALUES,&Bfd));
29239566063dSJacob Faibussowitsch       PetscCall(MatColoringCreate(Bfd,&coloring));
29249566063dSJacob Faibussowitsch       PetscCall(MatColoringSetType(coloring,MATCOLORINGSL));
29259566063dSJacob Faibussowitsch       PetscCall(MatColoringSetFromOptions(coloring));
29269566063dSJacob Faibussowitsch       PetscCall(MatColoringApply(coloring,&iscoloring));
29279566063dSJacob Faibussowitsch       PetscCall(MatColoringDestroy(&coloring));
29289566063dSJacob Faibussowitsch       PetscCall(MatFDColoringCreate(Bfd,iscoloring,&matfdcoloring));
29299566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetFromOptions(matfdcoloring));
29309566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetUp(Bfd,iscoloring,matfdcoloring));
29319566063dSJacob Faibussowitsch       PetscCall(ISColoringDestroy(&iscoloring));
29324c30e9fbSJed Brown 
29334c30e9fbSJed Brown       /* This method of getting the function is currently unreliable since it doesn't work for DM local functions. */
29349566063dSJacob Faibussowitsch       PetscCall(SNESGetFunction(snes,NULL,&func,&funcctx));
29359566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetFunction(matfdcoloring,(PetscErrorCode (*)(void))func,funcctx));
29369566063dSJacob Faibussowitsch       PetscCall(PetscObjectSetOptionsPrefix((PetscObject)matfdcoloring,((PetscObject)snes)->prefix));
29379566063dSJacob Faibussowitsch       PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)matfdcoloring,"coloring_"));
29389566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetFromOptions(matfdcoloring));
29399566063dSJacob Faibussowitsch       PetscCall(MatFDColoringApply(Bfd,matfdcoloring,X,snes));
29409566063dSJacob Faibussowitsch       PetscCall(MatFDColoringDestroy(&matfdcoloring));
29414c30e9fbSJed Brown 
29429566063dSJacob Faibussowitsch       PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes),&vstdout));
29434c30e9fbSJed Brown       if (flag_draw || flag_contour) {
29449566063dSJacob Faibussowitsch         PetscCall(PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes),NULL,"Colored Jacobians",PETSC_DECIDE,PETSC_DECIDE,300,300,&vdraw));
29459566063dSJacob Faibussowitsch         if (flag_contour) PetscCall(PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR));
29460298fd71SBarry Smith       } else vdraw = NULL;
29479566063dSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPrintf(vstdout,"Explicit preconditioning Jacobian\n"));
29489566063dSJacob Faibussowitsch       if (flag_display) PetscCall(MatView(B,vstdout));
29499566063dSJacob Faibussowitsch       if (vdraw) PetscCall(MatView(B,vdraw));
29509566063dSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPrintf(vstdout,"Colored Finite difference Jacobian\n"));
29519566063dSJacob Faibussowitsch       if (flag_display) PetscCall(MatView(Bfd,vstdout));
29529566063dSJacob Faibussowitsch       if (vdraw) PetscCall(MatView(Bfd,vdraw));
29539566063dSJacob Faibussowitsch       PetscCall(MatAYPX(Bfd,-1.0,B,SAME_NONZERO_PATTERN));
29549566063dSJacob Faibussowitsch       PetscCall(MatNorm(Bfd,NORM_1,&norm1));
29559566063dSJacob Faibussowitsch       PetscCall(MatNorm(Bfd,NORM_FROBENIUS,&norm2));
29569566063dSJacob Faibussowitsch       PetscCall(MatNorm(Bfd,NORM_MAX,&normmax));
29579566063dSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPrintf(vstdout,"User-provided matrix minus finite difference Jacobian, norm1=%g normFrob=%g normmax=%g\n",(double)norm1,(double)norm2,(double)normmax));
29589566063dSJacob Faibussowitsch       if (flag_display) PetscCall(MatView(Bfd,vstdout));
29594c30e9fbSJed Brown       if (vdraw) {              /* Always use contour for the difference */
29609566063dSJacob Faibussowitsch         PetscCall(PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR));
29619566063dSJacob Faibussowitsch         PetscCall(MatView(Bfd,vdraw));
29629566063dSJacob Faibussowitsch         PetscCall(PetscViewerPopFormat(vdraw));
29634c30e9fbSJed Brown       }
29649566063dSJacob Faibussowitsch       if (flag_contour) PetscCall(PetscViewerPopFormat(vdraw));
29656719d8e4SJed Brown 
29666719d8e4SJed Brown       if (flag_threshold) {
29676719d8e4SJed Brown         PetscInt bs,rstart,rend,i;
29689566063dSJacob Faibussowitsch         PetscCall(MatGetBlockSize(B,&bs));
29699566063dSJacob Faibussowitsch         PetscCall(MatGetOwnershipRange(B,&rstart,&rend));
29706719d8e4SJed Brown         for (i=rstart; i<rend; i++) {
29716719d8e4SJed Brown           const PetscScalar *ba,*ca;
29726719d8e4SJed Brown           const PetscInt    *bj,*cj;
29736719d8e4SJed Brown           PetscInt          bn,cn,j,maxentrycol = -1,maxdiffcol = -1,maxrdiffcol = -1;
29746719d8e4SJed Brown           PetscReal         maxentry = 0,maxdiff = 0,maxrdiff = 0;
29759566063dSJacob Faibussowitsch           PetscCall(MatGetRow(B,i,&bn,&bj,&ba));
29769566063dSJacob Faibussowitsch           PetscCall(MatGetRow(Bfd,i,&cn,&cj,&ca));
29775f80ce2aSJacob Faibussowitsch           PetscCheck(bn == cn,((PetscObject)A)->comm,PETSC_ERR_PLIB,"Unexpected different nonzero pattern in -snes_compare_coloring_threshold");
29786719d8e4SJed Brown           for (j=0; j<bn; j++) {
29796719d8e4SJed Brown             PetscReal rdiff = PetscAbsScalar(ca[j]) / (threshold_atol + threshold_rtol*PetscAbsScalar(ba[j]));
29806719d8e4SJed Brown             if (PetscAbsScalar(ba[j]) > PetscAbs(maxentry)) {
29816719d8e4SJed Brown               maxentrycol = bj[j];
29826719d8e4SJed Brown               maxentry    = PetscRealPart(ba[j]);
29836719d8e4SJed Brown             }
29846719d8e4SJed Brown             if (PetscAbsScalar(ca[j]) > PetscAbs(maxdiff)) {
29856719d8e4SJed Brown               maxdiffcol = bj[j];
29866719d8e4SJed Brown               maxdiff    = PetscRealPart(ca[j]);
29876719d8e4SJed Brown             }
29886719d8e4SJed Brown             if (rdiff > maxrdiff) {
29896719d8e4SJed Brown               maxrdiffcol = bj[j];
29906719d8e4SJed Brown               maxrdiff    = rdiff;
29916719d8e4SJed Brown             }
29926719d8e4SJed Brown           }
29936719d8e4SJed Brown           if (maxrdiff > 1) {
299463a3b9bcSJacob Faibussowitsch             PetscCall(PetscViewerASCIIPrintf(vstdout,"row %" PetscInt_FMT " (maxentry=%g at %" PetscInt_FMT ", maxdiff=%g at %" PetscInt_FMT ", maxrdiff=%g at %" PetscInt_FMT "):",i,(double)maxentry,maxentrycol,(double)maxdiff,maxdiffcol,(double)maxrdiff,maxrdiffcol));
29956719d8e4SJed Brown             for (j=0; j<bn; j++) {
29966719d8e4SJed Brown               PetscReal rdiff;
29976719d8e4SJed Brown               rdiff = PetscAbsScalar(ca[j]) / (threshold_atol + threshold_rtol*PetscAbsScalar(ba[j]));
29986719d8e4SJed Brown               if (rdiff > 1) {
299963a3b9bcSJacob Faibussowitsch                 PetscCall(PetscViewerASCIIPrintf(vstdout," (%" PetscInt_FMT ",%g:%g)",bj[j],(double)PetscRealPart(ba[j]),(double)PetscRealPart(ca[j])));
30006719d8e4SJed Brown               }
30016719d8e4SJed Brown             }
300263a3b9bcSJacob Faibussowitsch             PetscCall(PetscViewerASCIIPrintf(vstdout,"\n"));
30036719d8e4SJed Brown           }
30049566063dSJacob Faibussowitsch           PetscCall(MatRestoreRow(B,i,&bn,&bj,&ba));
30059566063dSJacob Faibussowitsch           PetscCall(MatRestoreRow(Bfd,i,&cn,&cj,&ca));
30066719d8e4SJed Brown         }
30076719d8e4SJed Brown       }
30089566063dSJacob Faibussowitsch       PetscCall(PetscViewerDestroy(&vdraw));
30099566063dSJacob Faibussowitsch       PetscCall(MatDestroy(&Bfd));
30104c30e9fbSJed Brown     }
30114c30e9fbSJed Brown   }
30123a40ed3dSBarry Smith   PetscFunctionReturn(0);
30139b94acceSBarry Smith }
30149b94acceSBarry Smith 
3015bf388a1fSBarry Smith /*MC
3016411c0326SBarry Smith     SNESJacobianFunction - Function used to convey the nonlinear Jacobian of the function to be solved by SNES
3017bf388a1fSBarry Smith 
3018bf388a1fSBarry Smith      Synopsis:
3019411c0326SBarry Smith      #include "petscsnes.h"
3020411c0326SBarry Smith      PetscErrorCode SNESJacobianFunction(SNES snes,Vec x,Mat Amat,Mat Pmat,void *ctx);
3021bf388a1fSBarry Smith 
30221843f636SBarry Smith      Collective on snes
30231843f636SBarry Smith 
30241843f636SBarry Smith     Input Parameters:
30251843f636SBarry Smith +  x - input vector, the Jacobian is to be computed at this value
3026bf388a1fSBarry Smith -  ctx - [optional] user-defined Jacobian context
3027bf388a1fSBarry Smith 
30281843f636SBarry Smith     Output Parameters:
30291843f636SBarry Smith +  Amat - the matrix that defines the (approximate) Jacobian
30301843f636SBarry Smith -  Pmat - the matrix to be used in constructing the preconditioner, usually the same as Amat.
30311843f636SBarry Smith 
3032878cb397SSatish Balay    Level: intermediate
3033878cb397SSatish Balay 
3034db781477SPatrick Sanan .seealso: `SNESSetFunction()`, `SNESGetFunction()`, `SNESSetJacobian()`, `SNESGetJacobian()`
3035bf388a1fSBarry Smith M*/
3036bf388a1fSBarry Smith 
30379b94acceSBarry Smith /*@C
30389b94acceSBarry Smith    SNESSetJacobian - Sets the function to compute Jacobian as well as the
3039044dda88SLois Curfman McInnes    location to store the matrix.
30409b94acceSBarry Smith 
3041d083f849SBarry Smith    Logically Collective on SNES
3042c7afd0dbSLois Curfman McInnes 
30439b94acceSBarry Smith    Input Parameters:
3044c7afd0dbSLois Curfman McInnes +  snes - the SNES context
3045e5d3d808SBarry Smith .  Amat - the matrix that defines the (approximate) Jacobian
3046e5d3d808SBarry Smith .  Pmat - the matrix to be used in constructing the preconditioner, usually the same as Amat.
3047411c0326SBarry Smith .  J - Jacobian evaluation routine (if NULL then SNES retains any previously set value), see SNESJacobianFunction for details
3048c7afd0dbSLois Curfman McInnes -  ctx - [optional] user-defined context for private data for the
30490298fd71SBarry Smith          Jacobian evaluation routine (may be NULL) (if NULL then SNES retains any previously set value)
30509b94acceSBarry Smith 
30519b94acceSBarry Smith    Notes:
3052e5d3d808SBarry Smith    If the Amat matrix and Pmat matrix are different you must call MatAssemblyBegin/End() on
305316913363SBarry Smith    each matrix.
305416913363SBarry Smith 
3055895c21f2SBarry Smith    If you know the operator Amat has a null space you can use MatSetNullSpace() and MatSetTransposeNullSpace() to supply the null
3056895c21f2SBarry Smith    space to Amat and the KSP solvers will automatically use that null space as needed during the solution process.
3057895c21f2SBarry Smith 
30588d359177SBarry Smith    If using SNESComputeJacobianDefaultColor() to assemble a Jacobian, the ctx argument
3059a8a26c1eSJed Brown    must be a MatFDColoring.
3060a8a26c1eSJed Brown 
3061c3cc8fd1SJed Brown    Other defect-correction schemes can be used by computing a different matrix in place of the Jacobian.  One common
3062c3cc8fd1SJed Brown    example is to use the "Picard linearization" which only differentiates through the highest order parts of each term.
3063c3cc8fd1SJed Brown 
306436851e7fSLois Curfman McInnes    Level: beginner
306536851e7fSLois Curfman McInnes 
3066db781477SPatrick Sanan .seealso: `KSPSetOperators()`, `SNESSetFunction()`, `MatMFFDComputeJacobian()`, `SNESComputeJacobianDefaultColor()`, `MatStructure`, `J`,
3067db781477SPatrick Sanan           `SNESSetPicard()`, `SNESJacobianFunction`
30689b94acceSBarry Smith @*/
3069d1e9a80fSBarry Smith PetscErrorCode  SNESSetJacobian(SNES snes,Mat Amat,Mat Pmat,PetscErrorCode (*J)(SNES,Vec,Mat,Mat,void*),void *ctx)
30709b94acceSBarry Smith {
30716cab3a1bSJed Brown   DM             dm;
30723a7fca6bSBarry Smith 
30733a40ed3dSBarry Smith   PetscFunctionBegin;
30740700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3075e5d3d808SBarry Smith   if (Amat) PetscValidHeaderSpecific(Amat,MAT_CLASSID,2);
3076e5d3d808SBarry Smith   if (Pmat) PetscValidHeaderSpecific(Pmat,MAT_CLASSID,3);
3077e5d3d808SBarry Smith   if (Amat) PetscCheckSameComm(snes,1,Amat,2);
3078e5d3d808SBarry Smith   if (Pmat) PetscCheckSameComm(snes,1,Pmat,3);
30799566063dSJacob Faibussowitsch   PetscCall(SNESGetDM(snes,&dm));
30809566063dSJacob Faibussowitsch   PetscCall(DMSNESSetJacobian(dm,J,ctx));
3081e5d3d808SBarry Smith   if (Amat) {
30829566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)Amat));
30839566063dSJacob Faibussowitsch     PetscCall(MatDestroy(&snes->jacobian));
3084f5af7f23SKarl Rupp 
3085e5d3d808SBarry Smith     snes->jacobian = Amat;
30863a7fca6bSBarry Smith   }
3087e5d3d808SBarry Smith   if (Pmat) {
30889566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)Pmat));
30899566063dSJacob Faibussowitsch     PetscCall(MatDestroy(&snes->jacobian_pre));
3090f5af7f23SKarl Rupp 
3091e5d3d808SBarry Smith     snes->jacobian_pre = Pmat;
30923a7fca6bSBarry Smith   }
30933a40ed3dSBarry Smith   PetscFunctionReturn(0);
30949b94acceSBarry Smith }
309562fef451SLois Curfman McInnes 
3096c2aafc4cSSatish Balay /*@C
3097b4fd4287SBarry Smith    SNESGetJacobian - Returns the Jacobian matrix and optionally the user
3098b4fd4287SBarry Smith    provided context for evaluating the Jacobian.
3099b4fd4287SBarry Smith 
3100c7afd0dbSLois Curfman McInnes    Not Collective, but Mat object will be parallel if SNES object is
3101c7afd0dbSLois Curfman McInnes 
3102b4fd4287SBarry Smith    Input Parameter:
3103b4fd4287SBarry Smith .  snes - the nonlinear solver context
3104b4fd4287SBarry Smith 
3105b4fd4287SBarry Smith    Output Parameters:
3106e5d3d808SBarry Smith +  Amat - location to stash (approximate) Jacobian matrix (or NULL)
3107e5d3d808SBarry Smith .  Pmat - location to stash matrix used to compute the preconditioner (or NULL)
3108411c0326SBarry Smith .  J - location to put Jacobian function (or NULL), see SNESJacobianFunction for details on its calling sequence
31090298fd71SBarry Smith -  ctx - location to stash Jacobian ctx (or NULL)
3110fee21e36SBarry Smith 
311136851e7fSLois Curfman McInnes    Level: advanced
311236851e7fSLois Curfman McInnes 
3113db781477SPatrick Sanan .seealso: `SNESSetJacobian()`, `SNESComputeJacobian()`, `SNESJacobianFunction`, `SNESGetFunction()`
3114b4fd4287SBarry Smith @*/
3115d1e9a80fSBarry Smith PetscErrorCode SNESGetJacobian(SNES snes,Mat *Amat,Mat *Pmat,PetscErrorCode (**J)(SNES,Vec,Mat,Mat,void*),void **ctx)
3116b4fd4287SBarry Smith {
31176cab3a1bSJed Brown   DM             dm;
3118942e3340SBarry Smith   DMSNES         sdm;
31196cab3a1bSJed Brown 
31203a40ed3dSBarry Smith   PetscFunctionBegin;
31210700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3122e5d3d808SBarry Smith   if (Amat) *Amat = snes->jacobian;
3123e5d3d808SBarry Smith   if (Pmat) *Pmat = snes->jacobian_pre;
31249566063dSJacob Faibussowitsch   PetscCall(SNESGetDM(snes,&dm));
31259566063dSJacob Faibussowitsch   PetscCall(DMGetDMSNES(dm,&sdm));
3126f8b49ee9SBarry Smith   if (J) *J = sdm->ops->computejacobian;
31276cab3a1bSJed Brown   if (ctx) *ctx = sdm->jacobianctx;
31283a40ed3dSBarry Smith   PetscFunctionReturn(0);
3129b4fd4287SBarry Smith }
3130b4fd4287SBarry Smith 
313158b371f3SBarry Smith static PetscErrorCode SNESSetDefaultComputeJacobian(SNES snes)
313258b371f3SBarry Smith {
313358b371f3SBarry Smith   DM             dm;
313458b371f3SBarry Smith   DMSNES         sdm;
313558b371f3SBarry Smith 
313658b371f3SBarry Smith   PetscFunctionBegin;
31379566063dSJacob Faibussowitsch   PetscCall(SNESGetDM(snes,&dm));
31389566063dSJacob Faibussowitsch   PetscCall(DMGetDMSNES(dm,&sdm));
313958b371f3SBarry Smith   if (!sdm->ops->computejacobian && snes->jacobian_pre) {
314058b371f3SBarry Smith     DM        dm;
314158b371f3SBarry Smith     PetscBool isdense,ismf;
314258b371f3SBarry Smith 
31439566063dSJacob Faibussowitsch     PetscCall(SNESGetDM(snes,&dm));
31449566063dSJacob Faibussowitsch     PetscCall(PetscObjectTypeCompareAny((PetscObject)snes->jacobian_pre,&isdense,MATSEQDENSE,MATMPIDENSE,MATDENSE,NULL));
31459566063dSJacob Faibussowitsch     PetscCall(PetscObjectTypeCompareAny((PetscObject)snes->jacobian_pre,&ismf,MATMFFD,MATSHELL,NULL));
314658b371f3SBarry Smith     if (isdense) {
31479566063dSJacob Faibussowitsch       PetscCall(DMSNESSetJacobian(dm,SNESComputeJacobianDefault,NULL));
314858b371f3SBarry Smith     } else if (!ismf) {
31499566063dSJacob Faibussowitsch       PetscCall(DMSNESSetJacobian(dm,SNESComputeJacobianDefaultColor,NULL));
315058b371f3SBarry Smith     }
315158b371f3SBarry Smith   }
315258b371f3SBarry Smith   PetscFunctionReturn(0);
315358b371f3SBarry Smith }
315458b371f3SBarry Smith 
31559b94acceSBarry Smith /*@
31569b94acceSBarry Smith    SNESSetUp - Sets up the internal data structures for the later use
3157272ac6f2SLois Curfman McInnes    of a nonlinear solver.
31589b94acceSBarry Smith 
3159fee21e36SBarry Smith    Collective on SNES
3160fee21e36SBarry Smith 
3161c7afd0dbSLois Curfman McInnes    Input Parameters:
316270e92668SMatthew Knepley .  snes - the SNES context
3163c7afd0dbSLois Curfman McInnes 
3164272ac6f2SLois Curfman McInnes    Notes:
3165272ac6f2SLois Curfman McInnes    For basic use of the SNES solvers the user need not explicitly call
3166272ac6f2SLois Curfman McInnes    SNESSetUp(), since these actions will automatically occur during
3167272ac6f2SLois Curfman McInnes    the call to SNESSolve().  However, if one wishes to control this
3168272ac6f2SLois Curfman McInnes    phase separately, SNESSetUp() should be called after SNESCreate()
3169272ac6f2SLois Curfman McInnes    and optional routines of the form SNESSetXXX(), but before SNESSolve().
3170272ac6f2SLois Curfman McInnes 
317136851e7fSLois Curfman McInnes    Level: advanced
317236851e7fSLois Curfman McInnes 
3173db781477SPatrick Sanan .seealso: `SNESCreate()`, `SNESSolve()`, `SNESDestroy()`
31749b94acceSBarry Smith @*/
31757087cfbeSBarry Smith PetscErrorCode  SNESSetUp(SNES snes)
31769b94acceSBarry Smith {
31776cab3a1bSJed Brown   DM             dm;
3178942e3340SBarry Smith   DMSNES         sdm;
3179c35f09e5SBarry Smith   SNESLineSearch linesearch, pclinesearch;
31806e2a1849SPeter Brune   void           *lsprectx,*lspostctx;
31816b2b7091SBarry Smith   PetscErrorCode (*precheck)(SNESLineSearch,Vec,Vec,PetscBool*,void*);
31826b2b7091SBarry Smith   PetscErrorCode (*postcheck)(SNESLineSearch,Vec,Vec,Vec,PetscBool*,PetscBool*,void*);
31836e2a1849SPeter Brune   PetscErrorCode (*func)(SNES,Vec,Vec,void*);
31846e2a1849SPeter Brune   Vec            f,fpc;
31856e2a1849SPeter Brune   void           *funcctx;
3186d1e9a80fSBarry Smith   PetscErrorCode (*jac)(SNES,Vec,Mat,Mat,void*);
31871eb13d49SPeter Brune   void           *jacctx,*appctx;
318832b97717SPeter Brune   Mat            j,jpre;
31893a40ed3dSBarry Smith 
31903a40ed3dSBarry Smith   PetscFunctionBegin;
31910700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
31924dc4c822SBarry Smith   if (snes->setupcalled) PetscFunctionReturn(0);
31939566063dSJacob Faibussowitsch   PetscCall(PetscLogEventBegin(SNES_Setup,snes,0,0,0));
31949b94acceSBarry Smith 
31957adad957SLisandro Dalcin   if (!((PetscObject)snes)->type_name) {
31969566063dSJacob Faibussowitsch     PetscCall(SNESSetType(snes,SNESNEWTONLS));
319785385478SLisandro Dalcin   }
319885385478SLisandro Dalcin 
31999566063dSJacob Faibussowitsch   PetscCall(SNESGetFunction(snes,&snes->vec_func,NULL,NULL));
320058c9b817SLisandro Dalcin 
32019566063dSJacob Faibussowitsch   PetscCall(SNESGetDM(snes,&dm));
32029566063dSJacob Faibussowitsch   PetscCall(DMGetDMSNES(dm,&sdm));
32035f80ce2aSJacob Faibussowitsch   PetscCheck(sdm->ops->computefunction,PetscObjectComm((PetscObject)dm),PETSC_ERR_ARG_WRONGSTATE,"Function never provided to SNES object");
32049566063dSJacob Faibussowitsch   PetscCall(SNESSetDefaultComputeJacobian(snes));
320558b371f3SBarry Smith 
32066cab3a1bSJed Brown   if (!snes->vec_func) {
32079566063dSJacob Faibussowitsch     PetscCall(DMCreateGlobalVector(dm,&snes->vec_func));
3208214df951SJed Brown   }
3209efd51863SBarry Smith 
321022d28d08SBarry Smith   if (!snes->ksp) {
32119566063dSJacob Faibussowitsch     PetscCall(SNESGetKSP(snes, &snes->ksp));
321222d28d08SBarry Smith   }
3213b710008aSBarry Smith 
3214d8d34be6SBarry Smith   if (snes->linesearch) {
32159566063dSJacob Faibussowitsch     PetscCall(SNESGetLineSearch(snes, &snes->linesearch));
32169566063dSJacob Faibussowitsch     PetscCall(SNESLineSearchSetFunction(snes->linesearch,SNESComputeFunction));
3217d8d34be6SBarry Smith   }
32189e764e56SPeter Brune 
3219b552625fSStefano Zampini   if (snes->npc && snes->npcside == PC_LEFT) {
3220172a4300SPeter Brune     snes->mf          = PETSC_TRUE;
3221172a4300SPeter Brune     snes->mf_operator = PETSC_FALSE;
3222172a4300SPeter Brune   }
3223d8f46077SPeter Brune 
3224efd4aadfSBarry Smith   if (snes->npc) {
32256e2a1849SPeter Brune     /* copy the DM over */
32269566063dSJacob Faibussowitsch     PetscCall(SNESGetDM(snes,&dm));
32279566063dSJacob Faibussowitsch     PetscCall(SNESSetDM(snes->npc,dm));
32286e2a1849SPeter Brune 
32299566063dSJacob Faibussowitsch     PetscCall(SNESGetFunction(snes,&f,&func,&funcctx));
32309566063dSJacob Faibussowitsch     PetscCall(VecDuplicate(f,&fpc));
32319566063dSJacob Faibussowitsch     PetscCall(SNESSetFunction(snes->npc,fpc,func,funcctx));
32329566063dSJacob Faibussowitsch     PetscCall(SNESGetJacobian(snes,&j,&jpre,&jac,&jacctx));
32339566063dSJacob Faibussowitsch     PetscCall(SNESSetJacobian(snes->npc,j,jpre,jac,jacctx));
32349566063dSJacob Faibussowitsch     PetscCall(SNESGetApplicationContext(snes,&appctx));
32359566063dSJacob Faibussowitsch     PetscCall(SNESSetApplicationContext(snes->npc,appctx));
32369566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&fpc));
32376e2a1849SPeter Brune 
32386e2a1849SPeter Brune     /* copy the function pointers over */
32399566063dSJacob Faibussowitsch     PetscCall(PetscObjectCopyFortranFunctionPointers((PetscObject)snes,(PetscObject)snes->npc));
32406e2a1849SPeter Brune 
32416e2a1849SPeter Brune     /* default to 1 iteration */
32429566063dSJacob Faibussowitsch     PetscCall(SNESSetTolerances(snes->npc,0.0,0.0,0.0,1,snes->npc->max_funcs));
3243efd4aadfSBarry Smith     if (snes->npcside == PC_RIGHT) {
32449566063dSJacob Faibussowitsch       PetscCall(SNESSetNormSchedule(snes->npc,SNES_NORM_FINAL_ONLY));
3245a9936a0cSPeter Brune     } else {
32469566063dSJacob Faibussowitsch       PetscCall(SNESSetNormSchedule(snes->npc,SNES_NORM_NONE));
3247a9936a0cSPeter Brune     }
32489566063dSJacob Faibussowitsch     PetscCall(SNESSetFromOptions(snes->npc));
32496e2a1849SPeter Brune 
32506e2a1849SPeter Brune     /* copy the line search context over */
3251d8d34be6SBarry Smith     if (snes->linesearch && snes->npc->linesearch) {
32529566063dSJacob Faibussowitsch       PetscCall(SNESGetLineSearch(snes,&linesearch));
32539566063dSJacob Faibussowitsch       PetscCall(SNESGetLineSearch(snes->npc,&pclinesearch));
32549566063dSJacob Faibussowitsch       PetscCall(SNESLineSearchGetPreCheck(linesearch,&precheck,&lsprectx));
32559566063dSJacob Faibussowitsch       PetscCall(SNESLineSearchGetPostCheck(linesearch,&postcheck,&lspostctx));
32569566063dSJacob Faibussowitsch       PetscCall(SNESLineSearchSetPreCheck(pclinesearch,precheck,lsprectx));
32579566063dSJacob Faibussowitsch       PetscCall(SNESLineSearchSetPostCheck(pclinesearch,postcheck,lspostctx));
32589566063dSJacob Faibussowitsch       PetscCall(PetscObjectCopyFortranFunctionPointers((PetscObject)linesearch, (PetscObject)pclinesearch));
32596e2a1849SPeter Brune     }
3260d8d34be6SBarry Smith   }
32611baa6e33SBarry Smith   if (snes->mf) PetscCall(SNESSetUpMatrixFree_Private(snes, snes->mf_operator, snes->mf_version));
326232b97717SPeter Brune   if (snes->ops->usercompute && !snes->user) {
32639566063dSJacob Faibussowitsch     PetscCall((*snes->ops->usercompute)(snes,(void**)&snes->user));
326432b97717SPeter Brune   }
32656e2a1849SPeter Brune 
326637ec4e1aSPeter Brune   snes->jac_iter = 0;
326737ec4e1aSPeter Brune   snes->pre_iter = 0;
326837ec4e1aSPeter Brune 
32691baa6e33SBarry Smith   if (snes->ops->setup) PetscCall((*snes->ops->setup)(snes));
327058c9b817SLisandro Dalcin 
32719566063dSJacob Faibussowitsch   PetscCall(SNESSetDefaultComputeJacobian(snes));
327258b371f3SBarry Smith 
3273b552625fSStefano Zampini   if (snes->npc && snes->npcside == PC_LEFT) {
32746c67d002SPeter Brune     if (snes->functype == SNES_FUNCTION_PRECONDITIONED) {
3275d8d34be6SBarry Smith       if (snes->linesearch) {
32769566063dSJacob Faibussowitsch         PetscCall(SNESGetLineSearch(snes,&linesearch));
32779566063dSJacob Faibussowitsch         PetscCall(SNESLineSearchSetFunction(linesearch,SNESComputeFunctionDefaultNPC));
32786c67d002SPeter Brune       }
32796c67d002SPeter Brune     }
3280d8d34be6SBarry Smith   }
32819566063dSJacob Faibussowitsch   PetscCall(PetscLogEventEnd(SNES_Setup,snes,0,0,0));
32827aaed0d8SBarry Smith   snes->setupcalled = PETSC_TRUE;
32833a40ed3dSBarry Smith   PetscFunctionReturn(0);
32849b94acceSBarry Smith }
32859b94acceSBarry Smith 
328637596af1SLisandro Dalcin /*@
328737596af1SLisandro Dalcin    SNESReset - Resets a SNES context to the snessetupcalled = 0 state and removes any allocated Vecs and Mats
328837596af1SLisandro Dalcin 
328937596af1SLisandro Dalcin    Collective on SNES
329037596af1SLisandro Dalcin 
329137596af1SLisandro Dalcin    Input Parameter:
329237596af1SLisandro Dalcin .  snes - iterative context obtained from SNESCreate()
329337596af1SLisandro Dalcin 
3294d25893d9SBarry Smith    Level: intermediate
3295d25893d9SBarry Smith 
329695452b02SPatrick Sanan    Notes:
329795452b02SPatrick Sanan     Also calls the application context destroy routine set with SNESSetComputeApplicationContext()
329837596af1SLisandro Dalcin 
3299db781477SPatrick Sanan .seealso: `SNESCreate()`, `SNESSetUp()`, `SNESSolve()`
330037596af1SLisandro Dalcin @*/
330137596af1SLisandro Dalcin PetscErrorCode  SNESReset(SNES snes)
330237596af1SLisandro Dalcin {
330337596af1SLisandro Dalcin   PetscFunctionBegin;
330437596af1SLisandro Dalcin   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3305d25893d9SBarry Smith   if (snes->ops->userdestroy && snes->user) {
33069566063dSJacob Faibussowitsch     PetscCall((*snes->ops->userdestroy)((void**)&snes->user));
33070298fd71SBarry Smith     snes->user = NULL;
3308d25893d9SBarry Smith   }
33091baa6e33SBarry Smith   if (snes->npc) PetscCall(SNESReset(snes->npc));
33108a23116dSBarry Smith 
33111baa6e33SBarry Smith   if (snes->ops->reset) PetscCall((*snes->ops->reset)(snes));
33121baa6e33SBarry Smith   if (snes->ksp) PetscCall(KSPReset(snes->ksp));
33139e764e56SPeter Brune 
33141baa6e33SBarry Smith   if (snes->linesearch) PetscCall(SNESLineSearchReset(snes->linesearch));
33159e764e56SPeter Brune 
33169566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&snes->vec_rhs));
33179566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&snes->vec_sol));
33189566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&snes->vec_sol_update));
33199566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&snes->vec_func));
33209566063dSJacob Faibussowitsch   PetscCall(MatDestroy(&snes->jacobian));
33219566063dSJacob Faibussowitsch   PetscCall(MatDestroy(&snes->jacobian_pre));
33229566063dSJacob Faibussowitsch   PetscCall(MatDestroy(&snes->picard));
33239566063dSJacob Faibussowitsch   PetscCall(VecDestroyVecs(snes->nwork,&snes->work));
33249566063dSJacob Faibussowitsch   PetscCall(VecDestroyVecs(snes->nvwork,&snes->vwork));
3325f5af7f23SKarl Rupp 
332640fdac6aSLawrence Mitchell   snes->alwayscomputesfinalresidual = PETSC_FALSE;
332740fdac6aSLawrence Mitchell 
332837596af1SLisandro Dalcin   snes->nwork       = snes->nvwork = 0;
332937596af1SLisandro Dalcin   snes->setupcalled = PETSC_FALSE;
333037596af1SLisandro Dalcin   PetscFunctionReturn(0);
333137596af1SLisandro Dalcin }
333237596af1SLisandro Dalcin 
333352baeb72SSatish Balay /*@
3334c4421ceaSFande Kong    SNESConvergedReasonViewCancel - Clears all the reasonview functions for a SNES object.
3335c4421ceaSFande Kong 
3336c4421ceaSFande Kong    Collective on SNES
3337c4421ceaSFande Kong 
3338c4421ceaSFande Kong    Input Parameter:
3339c4421ceaSFande Kong .  snes - iterative context obtained from SNESCreate()
3340c4421ceaSFande Kong 
3341c4421ceaSFande Kong    Level: intermediate
3342c4421ceaSFande Kong 
3343db781477SPatrick Sanan .seealso: `SNESCreate()`, `SNESDestroy()`, `SNESReset()`
3344c4421ceaSFande Kong @*/
3345c4421ceaSFande Kong PetscErrorCode  SNESConvergedReasonViewCancel(SNES snes)
3346c4421ceaSFande Kong {
3347c4421ceaSFande Kong   PetscInt       i;
3348c4421ceaSFande Kong 
3349c4421ceaSFande Kong   PetscFunctionBegin;
3350c4421ceaSFande Kong   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3351c4421ceaSFande Kong   for (i=0; i<snes->numberreasonviews; i++) {
3352c4421ceaSFande Kong     if (snes->reasonviewdestroy[i]) {
33539566063dSJacob Faibussowitsch       PetscCall((*snes->reasonviewdestroy[i])(&snes->reasonviewcontext[i]));
3354c4421ceaSFande Kong     }
3355c4421ceaSFande Kong   }
3356c4421ceaSFande Kong   snes->numberreasonviews = 0;
3357c4421ceaSFande Kong   PetscFunctionReturn(0);
3358c4421ceaSFande Kong }
3359c4421ceaSFande Kong 
33601fb7b255SJunchao Zhang /*@C
33619b94acceSBarry Smith    SNESDestroy - Destroys the nonlinear solver context that was created
33629b94acceSBarry Smith    with SNESCreate().
33639b94acceSBarry Smith 
3364c7afd0dbSLois Curfman McInnes    Collective on SNES
3365c7afd0dbSLois Curfman McInnes 
33669b94acceSBarry Smith    Input Parameter:
33679b94acceSBarry Smith .  snes - the SNES context
33689b94acceSBarry Smith 
336936851e7fSLois Curfman McInnes    Level: beginner
337036851e7fSLois Curfman McInnes 
3371db781477SPatrick Sanan .seealso: `SNESCreate()`, `SNESSolve()`
33729b94acceSBarry Smith @*/
33736bf464f9SBarry Smith PetscErrorCode  SNESDestroy(SNES *snes)
33749b94acceSBarry Smith {
33753a40ed3dSBarry Smith   PetscFunctionBegin;
33766bf464f9SBarry Smith   if (!*snes) PetscFunctionReturn(0);
33776bf464f9SBarry Smith   PetscValidHeaderSpecific((*snes),SNES_CLASSID,1);
33789e5d0892SLisandro Dalcin   if (--((PetscObject)(*snes))->refct > 0) {*snes = NULL; PetscFunctionReturn(0);}
3379d4bb536fSBarry Smith 
33809566063dSJacob Faibussowitsch   PetscCall(SNESReset((*snes)));
33819566063dSJacob Faibussowitsch   PetscCall(SNESDestroy(&(*snes)->npc));
33826b8b9a38SLisandro Dalcin 
3383e04113cfSBarry Smith   /* if memory was published with SAWs then destroy it */
33849566063dSJacob Faibussowitsch   PetscCall(PetscObjectSAWsViewOff((PetscObject)*snes));
33859566063dSJacob Faibussowitsch   if ((*snes)->ops->destroy) PetscCall((*((*snes))->ops->destroy)((*snes)));
33866d4c513bSLisandro Dalcin 
33879566063dSJacob Faibussowitsch   if ((*snes)->dm) PetscCall(DMCoarsenHookRemove((*snes)->dm,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,*snes));
33889566063dSJacob Faibussowitsch   PetscCall(DMDestroy(&(*snes)->dm));
33899566063dSJacob Faibussowitsch   PetscCall(KSPDestroy(&(*snes)->ksp));
33909566063dSJacob Faibussowitsch   PetscCall(SNESLineSearchDestroy(&(*snes)->linesearch));
33916b8b9a38SLisandro Dalcin 
33929566063dSJacob Faibussowitsch   PetscCall(PetscFree((*snes)->kspconvctx));
33936bf464f9SBarry Smith   if ((*snes)->ops->convergeddestroy) {
33949566063dSJacob Faibussowitsch     PetscCall((*(*snes)->ops->convergeddestroy)((*snes)->cnvP));
33956b8b9a38SLisandro Dalcin   }
3396071fcb05SBarry Smith   if ((*snes)->conv_hist_alloc) {
33979566063dSJacob Faibussowitsch     PetscCall(PetscFree2((*snes)->conv_hist,(*snes)->conv_hist_its));
339858c9b817SLisandro Dalcin   }
33999566063dSJacob Faibussowitsch   PetscCall(SNESMonitorCancel((*snes)));
34009566063dSJacob Faibussowitsch   PetscCall(SNESConvergedReasonViewCancel((*snes)));
34019566063dSJacob Faibussowitsch   PetscCall(PetscHeaderDestroy(snes));
34023a40ed3dSBarry Smith   PetscFunctionReturn(0);
34039b94acceSBarry Smith }
34049b94acceSBarry Smith 
34059b94acceSBarry Smith /* ----------- Routines to set solver parameters ---------- */
34069b94acceSBarry Smith 
3407a8054027SBarry Smith /*@
3408a8054027SBarry Smith    SNESSetLagPreconditioner - Determines when the preconditioner is rebuilt in the nonlinear solve.
3409a8054027SBarry Smith 
34103f9fe445SBarry Smith    Logically Collective on SNES
3411a8054027SBarry Smith 
3412a8054027SBarry Smith    Input Parameters:
3413a8054027SBarry Smith +  snes - the SNES context
3414d8e291bfSBarry Smith -  lag - 1 means rebuild every time the Jacobian is computed within a single nonlinear solve, 2 means every second time
34153b4f5425SBarry Smith          the Jacobian is built etc. -2 indicates rebuild preconditioner at next chance but then never rebuild after that
3416a8054027SBarry Smith 
3417a8054027SBarry Smith    Options Database Keys:
34183d5a8a6aSBarry Smith +    -snes_lag_jacobian_persists <true,false> - sets the persistence
34193d5a8a6aSBarry Smith .    -snes_lag_jacobian <-2,1,2,...> - sets the lag
34203d5a8a6aSBarry Smith .    -snes_lag_preconditioner_persists <true,false> - sets the persistence
34213d5a8a6aSBarry Smith -    -snes_lag_preconditioner <-2,1,2,...> - sets the lag
3422a8054027SBarry Smith 
3423a8054027SBarry Smith    Notes:
3424a8054027SBarry Smith    The default is 1
34253d5a8a6aSBarry Smith    The preconditioner is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1 or SNESSetLagPreconditionerPersists() was called
3426d8e291bfSBarry Smith 
3427d8e291bfSBarry Smith    SNESSetLagPreconditionerPersists() allows using the same uniform lagging (for example every second solve) across multiple solves.
3428a8054027SBarry Smith 
3429a8054027SBarry Smith    Level: intermediate
3430a8054027SBarry Smith 
3431db781477SPatrick Sanan .seealso: `SNESSetTrustRegionTolerance()`, `SNESGetLagPreconditioner()`, `SNESSetLagJacobian()`, `SNESGetLagJacobian()`, `SNESSetLagPreconditionerPersists()`,
3432db781477SPatrick Sanan           `SNESSetLagJacobianPersists()`
3433a8054027SBarry Smith 
3434a8054027SBarry Smith @*/
34357087cfbeSBarry Smith PetscErrorCode  SNESSetLagPreconditioner(SNES snes,PetscInt lag)
3436a8054027SBarry Smith {
3437a8054027SBarry Smith   PetscFunctionBegin;
34380700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
34395f80ce2aSJacob Faibussowitsch   PetscCheck(lag >= -2,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag must be -2, -1, 1 or greater");
34405f80ce2aSJacob Faibussowitsch   PetscCheck(lag,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag cannot be 0");
3441c5eb9154SBarry Smith   PetscValidLogicalCollectiveInt(snes,lag,2);
3442a8054027SBarry Smith   snes->lagpreconditioner = lag;
3443a8054027SBarry Smith   PetscFunctionReturn(0);
3444a8054027SBarry Smith }
3445a8054027SBarry Smith 
3446efd51863SBarry Smith /*@
3447efd51863SBarry Smith    SNESSetGridSequence - sets the number of steps of grid sequencing that SNES does
3448efd51863SBarry Smith 
3449efd51863SBarry Smith    Logically Collective on SNES
3450efd51863SBarry Smith 
3451efd51863SBarry Smith    Input Parameters:
3452efd51863SBarry Smith +  snes - the SNES context
3453efd51863SBarry Smith -  steps - the number of refinements to do, defaults to 0
3454efd51863SBarry Smith 
3455efd51863SBarry Smith    Options Database Keys:
345667b8a455SSatish Balay .    -snes_grid_sequence <steps> - Use grid sequencing to generate initial guess
3457efd51863SBarry Smith 
3458efd51863SBarry Smith    Level: intermediate
3459efd51863SBarry Smith 
3460c0df2a02SJed Brown    Notes:
3461c0df2a02SJed Brown    Use SNESGetSolution() to extract the fine grid solution after grid sequencing.
3462c0df2a02SJed Brown 
3463db781477SPatrick Sanan .seealso: `SNESSetTrustRegionTolerance()`, `SNESGetLagPreconditioner()`, `SNESSetLagJacobian()`, `SNESGetLagJacobian()`, `SNESGetGridSequence()`
3464efd51863SBarry Smith 
3465efd51863SBarry Smith @*/
3466efd51863SBarry Smith PetscErrorCode  SNESSetGridSequence(SNES snes,PetscInt steps)
3467efd51863SBarry Smith {
3468efd51863SBarry Smith   PetscFunctionBegin;
3469efd51863SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3470efd51863SBarry Smith   PetscValidLogicalCollectiveInt(snes,steps,2);
3471efd51863SBarry Smith   snes->gridsequence = steps;
3472efd51863SBarry Smith   PetscFunctionReturn(0);
3473efd51863SBarry Smith }
3474efd51863SBarry Smith 
3475fa19ca70SBarry Smith /*@
3476fa19ca70SBarry Smith    SNESGetGridSequence - gets the number of steps of grid sequencing that SNES does
3477fa19ca70SBarry Smith 
3478fa19ca70SBarry Smith    Logically Collective on SNES
3479fa19ca70SBarry Smith 
3480fa19ca70SBarry Smith    Input Parameter:
3481fa19ca70SBarry Smith .  snes - the SNES context
3482fa19ca70SBarry Smith 
3483fa19ca70SBarry Smith    Output Parameter:
3484fa19ca70SBarry Smith .  steps - the number of refinements to do, defaults to 0
3485fa19ca70SBarry Smith 
3486fa19ca70SBarry Smith    Options Database Keys:
348767b8a455SSatish Balay .    -snes_grid_sequence <steps> - set number of refinements
3488fa19ca70SBarry Smith 
3489fa19ca70SBarry Smith    Level: intermediate
3490fa19ca70SBarry Smith 
3491fa19ca70SBarry Smith    Notes:
3492fa19ca70SBarry Smith    Use SNESGetSolution() to extract the fine grid solution after grid sequencing.
3493fa19ca70SBarry Smith 
3494db781477SPatrick Sanan .seealso: `SNESSetTrustRegionTolerance()`, `SNESGetLagPreconditioner()`, `SNESSetLagJacobian()`, `SNESGetLagJacobian()`, `SNESSetGridSequence()`
3495fa19ca70SBarry Smith 
3496fa19ca70SBarry Smith @*/
3497fa19ca70SBarry Smith PetscErrorCode  SNESGetGridSequence(SNES snes,PetscInt *steps)
3498fa19ca70SBarry Smith {
3499fa19ca70SBarry Smith   PetscFunctionBegin;
3500fa19ca70SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3501fa19ca70SBarry Smith   *steps = snes->gridsequence;
3502fa19ca70SBarry Smith   PetscFunctionReturn(0);
3503fa19ca70SBarry Smith }
3504fa19ca70SBarry Smith 
3505a8054027SBarry Smith /*@
3506a8054027SBarry Smith    SNESGetLagPreconditioner - Indicates how often the preconditioner is rebuilt
3507a8054027SBarry Smith 
35083f9fe445SBarry Smith    Not Collective
3509a8054027SBarry Smith 
3510a8054027SBarry Smith    Input Parameter:
3511a8054027SBarry Smith .  snes - the SNES context
3512a8054027SBarry Smith 
3513a8054027SBarry Smith    Output Parameter:
3514a8054027SBarry 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
35153b4f5425SBarry Smith          the Jacobian is built etc. -2 indicates rebuild preconditioner at next chance but then never rebuild after that
3516a8054027SBarry Smith 
3517a8054027SBarry Smith    Options Database Keys:
35183d5a8a6aSBarry Smith +    -snes_lag_jacobian_persists <true,false> - sets the persistence
35193d5a8a6aSBarry Smith .    -snes_lag_jacobian <-2,1,2,...> - sets the lag
35203d5a8a6aSBarry Smith .    -snes_lag_preconditioner_persists <true,false> - sets the persistence
35213d5a8a6aSBarry Smith -    -snes_lag_preconditioner <-2,1,2,...> - sets the lag
3522a8054027SBarry Smith 
3523a8054027SBarry Smith    Notes:
3524a8054027SBarry Smith    The default is 1
3525a8054027SBarry Smith    The preconditioner is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1
3526a8054027SBarry Smith 
3527a8054027SBarry Smith    Level: intermediate
3528a8054027SBarry Smith 
3529db781477SPatrick Sanan .seealso: `SNESSetTrustRegionTolerance()`, `SNESSetLagPreconditioner()`, `SNESSetLagJacobianPersists()`, `SNESSetLagPreconditionerPersists()`
3530a8054027SBarry Smith 
3531a8054027SBarry Smith @*/
35327087cfbeSBarry Smith PetscErrorCode  SNESGetLagPreconditioner(SNES snes,PetscInt *lag)
3533a8054027SBarry Smith {
3534a8054027SBarry Smith   PetscFunctionBegin;
35350700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3536a8054027SBarry Smith   *lag = snes->lagpreconditioner;
3537a8054027SBarry Smith   PetscFunctionReturn(0);
3538a8054027SBarry Smith }
3539a8054027SBarry Smith 
3540e35cf81dSBarry Smith /*@
3541e35cf81dSBarry Smith    SNESSetLagJacobian - Determines when the Jacobian is rebuilt in the nonlinear solve. See SNESSetLagPreconditioner() for determining how
3542e35cf81dSBarry Smith      often the preconditioner is rebuilt.
3543e35cf81dSBarry Smith 
35443f9fe445SBarry Smith    Logically Collective on SNES
3545e35cf81dSBarry Smith 
3546e35cf81dSBarry Smith    Input Parameters:
3547e35cf81dSBarry Smith +  snes - the SNES context
3548e35cf81dSBarry 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
3549fe3ffe1eSBarry Smith          the Jacobian is built etc. -2 means rebuild at next chance but then never again
3550e35cf81dSBarry Smith 
3551e35cf81dSBarry Smith    Options Database Keys:
35523d5a8a6aSBarry Smith +    -snes_lag_jacobian_persists <true,false> - sets the persistence
35533d5a8a6aSBarry Smith .    -snes_lag_jacobian <-2,1,2,...> - sets the lag
35543d5a8a6aSBarry Smith .    -snes_lag_preconditioner_persists <true,false> - sets the persistence
35553d5a8a6aSBarry Smith -    -snes_lag_preconditioner <-2,1,2,...> - sets the lag.
3556e35cf81dSBarry Smith 
3557e35cf81dSBarry Smith    Notes:
3558e35cf81dSBarry Smith    The default is 1
3559e35cf81dSBarry Smith    The Jacobian is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1
3560fe3ffe1eSBarry 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
3561fe3ffe1eSBarry Smith    at the next Newton step but never again (unless it is reset to another value)
3562e35cf81dSBarry Smith 
3563e35cf81dSBarry Smith    Level: intermediate
3564e35cf81dSBarry Smith 
3565db781477SPatrick Sanan .seealso: `SNESSetTrustRegionTolerance()`, `SNESGetLagPreconditioner()`, `SNESSetLagPreconditioner()`, `SNESGetLagJacobianPersists()`, `SNESSetLagPreconditionerPersists()`
3566e35cf81dSBarry Smith 
3567e35cf81dSBarry Smith @*/
35687087cfbeSBarry Smith PetscErrorCode  SNESSetLagJacobian(SNES snes,PetscInt lag)
3569e35cf81dSBarry Smith {
3570e35cf81dSBarry Smith   PetscFunctionBegin;
35710700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
35725f80ce2aSJacob Faibussowitsch   PetscCheck(lag >= -2,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag must be -2, -1, 1 or greater");
35735f80ce2aSJacob Faibussowitsch   PetscCheck(lag,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag cannot be 0");
3574c5eb9154SBarry Smith   PetscValidLogicalCollectiveInt(snes,lag,2);
3575e35cf81dSBarry Smith   snes->lagjacobian = lag;
3576e35cf81dSBarry Smith   PetscFunctionReturn(0);
3577e35cf81dSBarry Smith }
3578e35cf81dSBarry Smith 
3579e35cf81dSBarry Smith /*@
3580e35cf81dSBarry Smith    SNESGetLagJacobian - Indicates how often the Jacobian is rebuilt. See SNESGetLagPreconditioner() to determine when the preconditioner is rebuilt
3581e35cf81dSBarry Smith 
35823f9fe445SBarry Smith    Not Collective
3583e35cf81dSBarry Smith 
3584e35cf81dSBarry Smith    Input Parameter:
3585e35cf81dSBarry Smith .  snes - the SNES context
3586e35cf81dSBarry Smith 
3587e35cf81dSBarry Smith    Output Parameter:
3588e35cf81dSBarry 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
3589e35cf81dSBarry Smith          the Jacobian is built etc.
3590e35cf81dSBarry Smith 
3591e35cf81dSBarry Smith    Notes:
3592e35cf81dSBarry Smith    The default is 1
35933d5a8a6aSBarry Smith    The jacobian is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1 or SNESSetLagJacobianPersists() was called.
3594e35cf81dSBarry Smith 
3595e35cf81dSBarry Smith    Level: intermediate
3596e35cf81dSBarry Smith 
3597db781477SPatrick Sanan .seealso: `SNESSetTrustRegionTolerance()`, `SNESSetLagJacobian()`, `SNESSetLagPreconditioner()`, `SNESGetLagPreconditioner()`, `SNESSetLagJacobianPersists()`, `SNESSetLagPreconditionerPersists()`
3598e35cf81dSBarry Smith 
3599e35cf81dSBarry Smith @*/
36007087cfbeSBarry Smith PetscErrorCode  SNESGetLagJacobian(SNES snes,PetscInt *lag)
3601e35cf81dSBarry Smith {
3602e35cf81dSBarry Smith   PetscFunctionBegin;
36030700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3604e35cf81dSBarry Smith   *lag = snes->lagjacobian;
3605e35cf81dSBarry Smith   PetscFunctionReturn(0);
3606e35cf81dSBarry Smith }
3607e35cf81dSBarry Smith 
360837ec4e1aSPeter Brune /*@
360937ec4e1aSPeter Brune    SNESSetLagJacobianPersists - Set whether or not the Jacobian lagging persists through multiple solves
361037ec4e1aSPeter Brune 
361137ec4e1aSPeter Brune    Logically collective on SNES
361237ec4e1aSPeter Brune 
3613d8d19677SJose E. Roman    Input Parameters:
361437ec4e1aSPeter Brune +  snes - the SNES context
36159d7e2deaSPeter Brune -   flg - jacobian lagging persists if true
361637ec4e1aSPeter Brune 
361737ec4e1aSPeter Brune    Options Database Keys:
36183d5a8a6aSBarry Smith +    -snes_lag_jacobian_persists <true,false> - sets the persistence
36193d5a8a6aSBarry Smith .    -snes_lag_jacobian <-2,1,2,...> - sets the lag
36203d5a8a6aSBarry Smith .    -snes_lag_preconditioner_persists <true,false> - sets the persistence
36213d5a8a6aSBarry Smith -    -snes_lag_preconditioner <-2,1,2,...> - sets the lag
36223d5a8a6aSBarry Smith 
362395452b02SPatrick Sanan    Notes:
362495452b02SPatrick Sanan     This is useful both for nonlinear preconditioning, where it's appropriate to have the Jacobian be stale by
362537ec4e1aSPeter Brune    several solves, and for implicit time-stepping, where Jacobian lagging in the inner nonlinear solve over several
362637ec4e1aSPeter Brune    timesteps may present huge efficiency gains.
362737ec4e1aSPeter Brune 
362837ec4e1aSPeter Brune    Level: developer
362937ec4e1aSPeter Brune 
3630db781477SPatrick Sanan .seealso: `SNESSetLagPreconditionerPersists()`, `SNESSetLagJacobian()`, `SNESGetLagJacobian()`, `SNESGetNPC()`, `SNESSetLagJacobianPersists()`
363137ec4e1aSPeter Brune 
363237ec4e1aSPeter Brune @*/
363337ec4e1aSPeter Brune PetscErrorCode  SNESSetLagJacobianPersists(SNES snes,PetscBool flg)
363437ec4e1aSPeter Brune {
363537ec4e1aSPeter Brune   PetscFunctionBegin;
363637ec4e1aSPeter Brune   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
363737ec4e1aSPeter Brune   PetscValidLogicalCollectiveBool(snes,flg,2);
363837ec4e1aSPeter Brune   snes->lagjac_persist = flg;
363937ec4e1aSPeter Brune   PetscFunctionReturn(0);
364037ec4e1aSPeter Brune }
364137ec4e1aSPeter Brune 
364237ec4e1aSPeter Brune /*@
3643d8e291bfSBarry Smith    SNESSetLagPreconditionerPersists - Set whether or not the preconditioner lagging persists through multiple nonlinear solves
364437ec4e1aSPeter Brune 
364537ec4e1aSPeter Brune    Logically Collective on SNES
364637ec4e1aSPeter Brune 
3647d8d19677SJose E. Roman    Input Parameters:
364837ec4e1aSPeter Brune +  snes - the SNES context
36499d7e2deaSPeter Brune -   flg - preconditioner lagging persists if true
365037ec4e1aSPeter Brune 
365137ec4e1aSPeter Brune    Options Database Keys:
36523d5a8a6aSBarry Smith +    -snes_lag_jacobian_persists <true,false> - sets the persistence
36533d5a8a6aSBarry Smith .    -snes_lag_jacobian <-2,1,2,...> - sets the lag
36543d5a8a6aSBarry Smith .    -snes_lag_preconditioner_persists <true,false> - sets the persistence
36553d5a8a6aSBarry Smith -    -snes_lag_preconditioner <-2,1,2,...> - sets the lag
365637ec4e1aSPeter Brune 
365795452b02SPatrick Sanan    Notes:
365895452b02SPatrick Sanan     This is useful both for nonlinear preconditioning, where it's appropriate to have the preconditioner be stale
365937ec4e1aSPeter Brune    by several solves, and for implicit time-stepping, where preconditioner lagging in the inner nonlinear solve over
366037ec4e1aSPeter Brune    several timesteps may present huge efficiency gains.
366137ec4e1aSPeter Brune 
366237ec4e1aSPeter Brune    Level: developer
366337ec4e1aSPeter Brune 
3664db781477SPatrick Sanan .seealso: `SNESSetLagJacobianPersists()`, `SNESSetLagJacobian()`, `SNESGetLagJacobian()`, `SNESGetNPC()`, `SNESSetLagPreconditioner()`
366537ec4e1aSPeter Brune 
366637ec4e1aSPeter Brune @*/
366737ec4e1aSPeter Brune PetscErrorCode  SNESSetLagPreconditionerPersists(SNES snes,PetscBool flg)
366837ec4e1aSPeter Brune {
366937ec4e1aSPeter Brune   PetscFunctionBegin;
367037ec4e1aSPeter Brune   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
367137ec4e1aSPeter Brune   PetscValidLogicalCollectiveBool(snes,flg,2);
367237ec4e1aSPeter Brune   snes->lagpre_persist = flg;
367337ec4e1aSPeter Brune   PetscFunctionReturn(0);
367437ec4e1aSPeter Brune }
367537ec4e1aSPeter Brune 
36769b94acceSBarry Smith /*@
3677be5caee7SBarry Smith    SNESSetForceIteration - force SNESSolve() to take at least one iteration regardless of the initial residual norm
3678be5caee7SBarry Smith 
3679be5caee7SBarry Smith    Logically Collective on SNES
3680be5caee7SBarry Smith 
3681be5caee7SBarry Smith    Input Parameters:
3682be5caee7SBarry Smith +  snes - the SNES context
3683be5caee7SBarry Smith -  force - PETSC_TRUE require at least one iteration
3684be5caee7SBarry Smith 
3685be5caee7SBarry Smith    Options Database Keys:
3686be5caee7SBarry Smith .    -snes_force_iteration <force> - Sets forcing an iteration
3687be5caee7SBarry Smith 
3688be5caee7SBarry Smith    Notes:
3689be5caee7SBarry Smith    This is used sometimes with TS to prevent TS from detecting a false steady state solution
3690be5caee7SBarry Smith 
3691be5caee7SBarry Smith    Level: intermediate
3692be5caee7SBarry Smith 
3693db781477SPatrick Sanan .seealso: `SNESSetTrustRegionTolerance()`, `SNESSetDivergenceTolerance()`
3694be5caee7SBarry Smith @*/
3695be5caee7SBarry Smith PetscErrorCode  SNESSetForceIteration(SNES snes,PetscBool force)
3696be5caee7SBarry Smith {
3697be5caee7SBarry Smith   PetscFunctionBegin;
3698be5caee7SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3699be5caee7SBarry Smith   snes->forceiteration = force;
3700be5caee7SBarry Smith   PetscFunctionReturn(0);
3701be5caee7SBarry Smith }
3702be5caee7SBarry Smith 
370385216dc7SFande Kong /*@
370485216dc7SFande Kong    SNESGetForceIteration - Whether or not to force SNESSolve() take at least one iteration regardless of the initial residual norm
370585216dc7SFande Kong 
370685216dc7SFande Kong    Logically Collective on SNES
370785216dc7SFande Kong 
370885216dc7SFande Kong    Input Parameters:
370985216dc7SFande Kong .  snes - the SNES context
371085216dc7SFande Kong 
371185216dc7SFande Kong    Output Parameter:
371285216dc7SFande Kong .  force - PETSC_TRUE requires at least one iteration.
371385216dc7SFande Kong 
371406dd6b0eSSatish Balay    Level: intermediate
371506dd6b0eSSatish Balay 
3716db781477SPatrick Sanan .seealso: `SNESSetForceIteration()`, `SNESSetTrustRegionTolerance()`, `SNESSetDivergenceTolerance()`
371785216dc7SFande Kong @*/
371885216dc7SFande Kong PetscErrorCode  SNESGetForceIteration(SNES snes,PetscBool *force)
371985216dc7SFande Kong {
372085216dc7SFande Kong   PetscFunctionBegin;
372185216dc7SFande Kong   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
372285216dc7SFande Kong   *force = snes->forceiteration;
372385216dc7SFande Kong   PetscFunctionReturn(0);
372485216dc7SFande Kong }
3725be5caee7SBarry Smith 
3726be5caee7SBarry Smith /*@
3727d7a720efSLois Curfman McInnes    SNESSetTolerances - Sets various parameters used in convergence tests.
37289b94acceSBarry Smith 
37293f9fe445SBarry Smith    Logically Collective on SNES
3730c7afd0dbSLois Curfman McInnes 
37319b94acceSBarry Smith    Input Parameters:
3732c7afd0dbSLois Curfman McInnes +  snes - the SNES context
373370441072SBarry Smith .  abstol - absolute convergence tolerance
373433174efeSLois Curfman McInnes .  rtol - relative convergence tolerance
37355358d0d4SBarry Smith .  stol -  convergence tolerance in terms of the norm of the change in the solution between steps,  || delta x || < stol*|| x ||
373633174efeSLois Curfman McInnes .  maxit - maximum number of iterations
3737e71169deSBarry Smith -  maxf - maximum number of function evaluations (-1 indicates no limit)
3738fee21e36SBarry Smith 
373933174efeSLois Curfman McInnes    Options Database Keys:
374070441072SBarry Smith +    -snes_atol <abstol> - Sets abstol
3741c7afd0dbSLois Curfman McInnes .    -snes_rtol <rtol> - Sets rtol
3742c7afd0dbSLois Curfman McInnes .    -snes_stol <stol> - Sets stol
3743c7afd0dbSLois Curfman McInnes .    -snes_max_it <maxit> - Sets maxit
3744c7afd0dbSLois Curfman McInnes -    -snes_max_funcs <maxf> - Sets maxf
37459b94acceSBarry Smith 
3746d7a720efSLois Curfman McInnes    Notes:
37479b94acceSBarry Smith    The default maximum number of iterations is 50.
37489b94acceSBarry Smith    The default maximum number of function evaluations is 1000.
37499b94acceSBarry Smith 
375036851e7fSLois Curfman McInnes    Level: intermediate
375136851e7fSLois Curfman McInnes 
3752db781477SPatrick Sanan .seealso: `SNESSetTrustRegionTolerance()`, `SNESSetDivergenceTolerance()`, `SNESSetForceIteration()`
37539b94acceSBarry Smith @*/
37547087cfbeSBarry Smith PetscErrorCode  SNESSetTolerances(SNES snes,PetscReal abstol,PetscReal rtol,PetscReal stol,PetscInt maxit,PetscInt maxf)
37559b94acceSBarry Smith {
37563a40ed3dSBarry Smith   PetscFunctionBegin;
37570700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3758c5eb9154SBarry Smith   PetscValidLogicalCollectiveReal(snes,abstol,2);
3759c5eb9154SBarry Smith   PetscValidLogicalCollectiveReal(snes,rtol,3);
3760c5eb9154SBarry Smith   PetscValidLogicalCollectiveReal(snes,stol,4);
3761c5eb9154SBarry Smith   PetscValidLogicalCollectiveInt(snes,maxit,5);
3762c5eb9154SBarry Smith   PetscValidLogicalCollectiveInt(snes,maxf,6);
3763c5eb9154SBarry Smith 
3764ab54825eSJed Brown   if (abstol != PETSC_DEFAULT) {
37655f80ce2aSJacob Faibussowitsch     PetscCheck(abstol >= 0.0,PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Absolute tolerance %g must be non-negative",(double)abstol);
3766ab54825eSJed Brown     snes->abstol = abstol;
3767ab54825eSJed Brown   }
3768ab54825eSJed Brown   if (rtol != PETSC_DEFAULT) {
37695f80ce2aSJacob 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);
3770ab54825eSJed Brown     snes->rtol = rtol;
3771ab54825eSJed Brown   }
3772ab54825eSJed Brown   if (stol != PETSC_DEFAULT) {
37735f80ce2aSJacob Faibussowitsch     PetscCheck(stol >= 0.0,PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Step tolerance %g must be non-negative",(double)stol);
3774c60f73f4SPeter Brune     snes->stol = stol;
3775ab54825eSJed Brown   }
3776ab54825eSJed Brown   if (maxit != PETSC_DEFAULT) {
377763a3b9bcSJacob Faibussowitsch     PetscCheck(maxit >= 0,PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of iterations %" PetscInt_FMT " must be non-negative",maxit);
3778ab54825eSJed Brown     snes->max_its = maxit;
3779ab54825eSJed Brown   }
3780ab54825eSJed Brown   if (maxf != PETSC_DEFAULT) {
378163a3b9bcSJacob Faibussowitsch     PetscCheck(maxf >= -1,PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of function evaluations %" PetscInt_FMT " must be -1 or nonnegative",maxf);
3782ab54825eSJed Brown     snes->max_funcs = maxf;
3783ab54825eSJed Brown   }
378488976e71SPeter Brune   snes->tolerancesset = PETSC_TRUE;
37853a40ed3dSBarry Smith   PetscFunctionReturn(0);
37869b94acceSBarry Smith }
37879b94acceSBarry Smith 
3788e4d06f11SPatrick Farrell /*@
3789e4d06f11SPatrick Farrell    SNESSetDivergenceTolerance - Sets the divergence tolerance used for the SNES divergence test.
3790e4d06f11SPatrick Farrell 
3791e4d06f11SPatrick Farrell    Logically Collective on SNES
3792e4d06f11SPatrick Farrell 
3793e4d06f11SPatrick Farrell    Input Parameters:
3794e4d06f11SPatrick Farrell +  snes - the SNES context
3795e4d06f11SPatrick Farrell -  divtol - the divergence tolerance. Use -1 to deactivate the test.
3796e4d06f11SPatrick Farrell 
3797e4d06f11SPatrick Farrell    Options Database Keys:
3798a2b725a8SWilliam Gropp .    -snes_divergence_tolerance <divtol> - Sets divtol
3799e4d06f11SPatrick Farrell 
3800e4d06f11SPatrick Farrell    Notes:
3801e4d06f11SPatrick Farrell    The default divergence tolerance is 1e4.
3802e4d06f11SPatrick Farrell 
3803e4d06f11SPatrick Farrell    Level: intermediate
3804e4d06f11SPatrick Farrell 
3805db781477SPatrick Sanan .seealso: `SNESSetTolerances()`, `SNESGetDivergenceTolerance`
3806e4d06f11SPatrick Farrell @*/
3807e4d06f11SPatrick Farrell PetscErrorCode  SNESSetDivergenceTolerance(SNES snes,PetscReal divtol)
3808e4d06f11SPatrick Farrell {
3809e4d06f11SPatrick Farrell   PetscFunctionBegin;
3810e4d06f11SPatrick Farrell   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3811e4d06f11SPatrick Farrell   PetscValidLogicalCollectiveReal(snes,divtol,2);
3812e4d06f11SPatrick Farrell 
3813e4d06f11SPatrick Farrell   if (divtol != PETSC_DEFAULT) {
3814e4d06f11SPatrick Farrell     snes->divtol = divtol;
3815e4d06f11SPatrick Farrell   }
3816e4d06f11SPatrick Farrell   else {
3817e4d06f11SPatrick Farrell     snes->divtol = 1.0e4;
3818e4d06f11SPatrick Farrell   }
3819e4d06f11SPatrick Farrell   PetscFunctionReturn(0);
3820e4d06f11SPatrick Farrell }
3821e4d06f11SPatrick Farrell 
38229b94acceSBarry Smith /*@
382333174efeSLois Curfman McInnes    SNESGetTolerances - Gets various parameters used in convergence tests.
382433174efeSLois Curfman McInnes 
3825c7afd0dbSLois Curfman McInnes    Not Collective
3826c7afd0dbSLois Curfman McInnes 
382733174efeSLois Curfman McInnes    Input Parameters:
3828c7afd0dbSLois Curfman McInnes +  snes - the SNES context
382985385478SLisandro Dalcin .  atol - absolute convergence tolerance
383033174efeSLois Curfman McInnes .  rtol - relative convergence tolerance
383133174efeSLois Curfman McInnes .  stol -  convergence tolerance in terms of the norm
383233174efeSLois Curfman McInnes            of the change in the solution between steps
383333174efeSLois Curfman McInnes .  maxit - maximum number of iterations
3834c7afd0dbSLois Curfman McInnes -  maxf - maximum number of function evaluations
3835fee21e36SBarry Smith 
383633174efeSLois Curfman McInnes    Notes:
38370298fd71SBarry Smith    The user can specify NULL for any parameter that is not needed.
383833174efeSLois Curfman McInnes 
383936851e7fSLois Curfman McInnes    Level: intermediate
384036851e7fSLois Curfman McInnes 
3841db781477SPatrick Sanan .seealso: `SNESSetTolerances()`
384233174efeSLois Curfman McInnes @*/
38437087cfbeSBarry Smith PetscErrorCode  SNESGetTolerances(SNES snes,PetscReal *atol,PetscReal *rtol,PetscReal *stol,PetscInt *maxit,PetscInt *maxf)
384433174efeSLois Curfman McInnes {
38453a40ed3dSBarry Smith   PetscFunctionBegin;
38460700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
384785385478SLisandro Dalcin   if (atol)  *atol  = snes->abstol;
384833174efeSLois Curfman McInnes   if (rtol)  *rtol  = snes->rtol;
3849c60f73f4SPeter Brune   if (stol)  *stol  = snes->stol;
385033174efeSLois Curfman McInnes   if (maxit) *maxit = snes->max_its;
385133174efeSLois Curfman McInnes   if (maxf)  *maxf  = snes->max_funcs;
38523a40ed3dSBarry Smith   PetscFunctionReturn(0);
385333174efeSLois Curfman McInnes }
385433174efeSLois Curfman McInnes 
3855e4d06f11SPatrick Farrell /*@
3856e4d06f11SPatrick Farrell    SNESGetDivergenceTolerance - Gets divergence tolerance used in divergence test.
3857e4d06f11SPatrick Farrell 
3858e4d06f11SPatrick Farrell    Not Collective
3859e4d06f11SPatrick Farrell 
3860e4d06f11SPatrick Farrell    Input Parameters:
3861e4d06f11SPatrick Farrell +  snes - the SNES context
3862e4d06f11SPatrick Farrell -  divtol - divergence tolerance
3863e4d06f11SPatrick Farrell 
3864e4d06f11SPatrick Farrell    Level: intermediate
3865e4d06f11SPatrick Farrell 
3866db781477SPatrick Sanan .seealso: `SNESSetDivergenceTolerance()`
3867e4d06f11SPatrick Farrell @*/
3868e4d06f11SPatrick Farrell PetscErrorCode  SNESGetDivergenceTolerance(SNES snes,PetscReal *divtol)
3869e4d06f11SPatrick Farrell {
3870e4d06f11SPatrick Farrell   PetscFunctionBegin;
3871e4d06f11SPatrick Farrell   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3872e4d06f11SPatrick Farrell   if (divtol) *divtol = snes->divtol;
3873e4d06f11SPatrick Farrell   PetscFunctionReturn(0);
3874e4d06f11SPatrick Farrell }
3875e4d06f11SPatrick Farrell 
387633174efeSLois Curfman McInnes /*@
38779b94acceSBarry Smith    SNESSetTrustRegionTolerance - Sets the trust region parameter tolerance.
38789b94acceSBarry Smith 
38793f9fe445SBarry Smith    Logically Collective on SNES
3880fee21e36SBarry Smith 
3881c7afd0dbSLois Curfman McInnes    Input Parameters:
3882c7afd0dbSLois Curfman McInnes +  snes - the SNES context
3883c7afd0dbSLois Curfman McInnes -  tol - tolerance
3884c7afd0dbSLois Curfman McInnes 
38859b94acceSBarry Smith    Options Database Key:
3886c7afd0dbSLois Curfman McInnes .  -snes_trtol <tol> - Sets tol
38879b94acceSBarry Smith 
388836851e7fSLois Curfman McInnes    Level: intermediate
388936851e7fSLois Curfman McInnes 
3890db781477SPatrick Sanan .seealso: `SNESSetTolerances()`
38919b94acceSBarry Smith @*/
38927087cfbeSBarry Smith PetscErrorCode  SNESSetTrustRegionTolerance(SNES snes,PetscReal tol)
38939b94acceSBarry Smith {
38943a40ed3dSBarry Smith   PetscFunctionBegin;
38950700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3896c5eb9154SBarry Smith   PetscValidLogicalCollectiveReal(snes,tol,2);
38979b94acceSBarry Smith   snes->deltatol = tol;
38983a40ed3dSBarry Smith   PetscFunctionReturn(0);
38999b94acceSBarry Smith }
39009b94acceSBarry Smith 
39016ba87a44SLisandro Dalcin PETSC_INTERN PetscErrorCode  SNESMonitorRange_Private(SNES,PetscInt,PetscReal*);
39026ba87a44SLisandro Dalcin 
39037087cfbeSBarry Smith PetscErrorCode  SNESMonitorLGRange(SNES snes,PetscInt n,PetscReal rnorm,void *monctx)
3904b271bb04SBarry Smith {
3905b271bb04SBarry Smith   PetscDrawLG      lg;
3906b271bb04SBarry Smith   PetscReal        x,y,per;
3907b271bb04SBarry Smith   PetscViewer      v = (PetscViewer)monctx;
3908b271bb04SBarry Smith   static PetscReal prev; /* should be in the context */
3909b271bb04SBarry Smith   PetscDraw        draw;
3910b271bb04SBarry Smith 
3911459f5d12SBarry Smith   PetscFunctionBegin;
39124d4332d5SBarry Smith   PetscValidHeaderSpecific(v,PETSC_VIEWER_CLASSID,4);
39139566063dSJacob Faibussowitsch   PetscCall(PetscViewerDrawGetDrawLG(v,0,&lg));
39149566063dSJacob Faibussowitsch   if (!n) PetscCall(PetscDrawLGReset(lg));
39159566063dSJacob Faibussowitsch   PetscCall(PetscDrawLGGetDraw(lg,&draw));
39169566063dSJacob Faibussowitsch   PetscCall(PetscDrawSetTitle(draw,"Residual norm"));
3917b271bb04SBarry Smith   x    = (PetscReal)n;
391877b4d14cSPeter Brune   if (rnorm > 0.0) y = PetscLog10Real(rnorm);
391994c9c6d3SKarl Rupp   else y = -15.0;
39209566063dSJacob Faibussowitsch   PetscCall(PetscDrawLGAddPoint(lg,&x,&y));
39216934998bSLisandro Dalcin   if (n < 20 || !(n % 5) || snes->reason) {
39229566063dSJacob Faibussowitsch     PetscCall(PetscDrawLGDraw(lg));
39239566063dSJacob Faibussowitsch     PetscCall(PetscDrawLGSave(lg));
3924b271bb04SBarry Smith   }
3925b271bb04SBarry Smith 
39269566063dSJacob Faibussowitsch   PetscCall(PetscViewerDrawGetDrawLG(v,1,&lg));
39279566063dSJacob Faibussowitsch   if (!n) PetscCall(PetscDrawLGReset(lg));
39289566063dSJacob Faibussowitsch   PetscCall(PetscDrawLGGetDraw(lg,&draw));
39299566063dSJacob Faibussowitsch   PetscCall(PetscDrawSetTitle(draw,"% elemts > .2*max elemt"));
39309566063dSJacob Faibussowitsch   PetscCall(SNESMonitorRange_Private(snes,n,&per));
3931b271bb04SBarry Smith   x    = (PetscReal)n;
3932b271bb04SBarry Smith   y    = 100.0*per;
39339566063dSJacob Faibussowitsch   PetscCall(PetscDrawLGAddPoint(lg,&x,&y));
39346934998bSLisandro Dalcin   if (n < 20 || !(n % 5) || snes->reason) {
39359566063dSJacob Faibussowitsch     PetscCall(PetscDrawLGDraw(lg));
39369566063dSJacob Faibussowitsch     PetscCall(PetscDrawLGSave(lg));
3937b271bb04SBarry Smith   }
3938b271bb04SBarry Smith 
39399566063dSJacob Faibussowitsch   PetscCall(PetscViewerDrawGetDrawLG(v,2,&lg));
39409566063dSJacob Faibussowitsch   if (!n) {prev = rnorm;PetscCall(PetscDrawLGReset(lg));}
39419566063dSJacob Faibussowitsch   PetscCall(PetscDrawLGGetDraw(lg,&draw));
39429566063dSJacob Faibussowitsch   PetscCall(PetscDrawSetTitle(draw,"(norm -oldnorm)/oldnorm"));
3943b271bb04SBarry Smith   x    = (PetscReal)n;
3944b271bb04SBarry Smith   y    = (prev - rnorm)/prev;
39459566063dSJacob Faibussowitsch   PetscCall(PetscDrawLGAddPoint(lg,&x,&y));
39466934998bSLisandro Dalcin   if (n < 20 || !(n % 5) || snes->reason) {
39479566063dSJacob Faibussowitsch     PetscCall(PetscDrawLGDraw(lg));
39489566063dSJacob Faibussowitsch     PetscCall(PetscDrawLGSave(lg));
3949b271bb04SBarry Smith   }
3950b271bb04SBarry Smith 
39519566063dSJacob Faibussowitsch   PetscCall(PetscViewerDrawGetDrawLG(v,3,&lg));
39529566063dSJacob Faibussowitsch   if (!n) PetscCall(PetscDrawLGReset(lg));
39539566063dSJacob Faibussowitsch   PetscCall(PetscDrawLGGetDraw(lg,&draw));
39549566063dSJacob Faibussowitsch   PetscCall(PetscDrawSetTitle(draw,"(norm -oldnorm)/oldnorm*(% > .2 max)"));
3955b271bb04SBarry Smith   x    = (PetscReal)n;
3956b271bb04SBarry Smith   y    = (prev - rnorm)/(prev*per);
3957b271bb04SBarry Smith   if (n > 2) { /*skip initial crazy value */
39589566063dSJacob Faibussowitsch     PetscCall(PetscDrawLGAddPoint(lg,&x,&y));
3959b271bb04SBarry Smith   }
39606934998bSLisandro Dalcin   if (n < 20 || !(n % 5) || snes->reason) {
39619566063dSJacob Faibussowitsch     PetscCall(PetscDrawLGDraw(lg));
39629566063dSJacob Faibussowitsch     PetscCall(PetscDrawLGSave(lg));
3963b271bb04SBarry Smith   }
3964b271bb04SBarry Smith   prev = rnorm;
3965b271bb04SBarry Smith   PetscFunctionReturn(0);
3966b271bb04SBarry Smith }
3967b271bb04SBarry Smith 
3968228d79bcSJed Brown /*@
3969228d79bcSJed Brown    SNESMonitor - runs the user provided monitor routines, if they exist
3970228d79bcSJed Brown 
3971228d79bcSJed Brown    Collective on SNES
3972228d79bcSJed Brown 
3973228d79bcSJed Brown    Input Parameters:
3974228d79bcSJed Brown +  snes - nonlinear solver context obtained from SNESCreate()
3975228d79bcSJed Brown .  iter - iteration number
3976228d79bcSJed Brown -  rnorm - relative norm of the residual
3977228d79bcSJed Brown 
3978228d79bcSJed Brown    Notes:
3979228d79bcSJed Brown    This routine is called by the SNES implementations.
3980228d79bcSJed Brown    It does not typically need to be called by the user.
3981228d79bcSJed Brown 
3982228d79bcSJed Brown    Level: developer
3983228d79bcSJed Brown 
3984db781477SPatrick Sanan .seealso: `SNESMonitorSet()`
3985228d79bcSJed Brown @*/
39867a03ce2fSLisandro Dalcin PetscErrorCode  SNESMonitor(SNES snes,PetscInt iter,PetscReal rnorm)
39877a03ce2fSLisandro Dalcin {
39887a03ce2fSLisandro Dalcin   PetscInt       i,n = snes->numbermonitors;
39897a03ce2fSLisandro Dalcin 
39907a03ce2fSLisandro Dalcin   PetscFunctionBegin;
39919566063dSJacob Faibussowitsch   PetscCall(VecLockReadPush(snes->vec_sol));
39927a03ce2fSLisandro Dalcin   for (i=0; i<n; i++) {
39939566063dSJacob Faibussowitsch     PetscCall((*snes->monitor[i])(snes,iter,rnorm,snes->monitorcontext[i]));
39947a03ce2fSLisandro Dalcin   }
39959566063dSJacob Faibussowitsch   PetscCall(VecLockReadPop(snes->vec_sol));
39967a03ce2fSLisandro Dalcin   PetscFunctionReturn(0);
39977a03ce2fSLisandro Dalcin }
39987a03ce2fSLisandro Dalcin 
39999b94acceSBarry Smith /* ------------ Routines to set performance monitoring options ----------- */
40009b94acceSBarry Smith 
4001bf388a1fSBarry Smith /*MC
4002bf388a1fSBarry Smith     SNESMonitorFunction - functional form passed to SNESMonitorSet() to monitor convergence of nonlinear solver
4003bf388a1fSBarry Smith 
4004bf388a1fSBarry Smith      Synopsis:
4005aaa7dc30SBarry Smith      #include <petscsnes.h>
4006bf388a1fSBarry Smith $    PetscErrorCode SNESMonitorFunction(SNES snes,PetscInt its, PetscReal norm,void *mctx)
4007bf388a1fSBarry Smith 
40081843f636SBarry Smith      Collective on snes
40091843f636SBarry Smith 
40101843f636SBarry Smith     Input Parameters:
4011bf388a1fSBarry Smith +    snes - the SNES context
4012bf388a1fSBarry Smith .    its - iteration number
4013bf388a1fSBarry Smith .    norm - 2-norm function value (may be estimated)
4014bf388a1fSBarry Smith -    mctx - [optional] monitoring context
4015bf388a1fSBarry Smith 
4016878cb397SSatish Balay    Level: advanced
4017878cb397SSatish Balay 
4018db781477SPatrick Sanan .seealso: `SNESMonitorSet()`, `SNESMonitorGet()`
4019bf388a1fSBarry Smith M*/
4020bf388a1fSBarry Smith 
40219b94acceSBarry Smith /*@C
4022a6570f20SBarry Smith    SNESMonitorSet - Sets an ADDITIONAL function that is to be used at every
40239b94acceSBarry Smith    iteration of the nonlinear solver to display the iteration's
40249b94acceSBarry Smith    progress.
40259b94acceSBarry Smith 
40263f9fe445SBarry Smith    Logically Collective on SNES
4027fee21e36SBarry Smith 
4028c7afd0dbSLois Curfman McInnes    Input Parameters:
4029c7afd0dbSLois Curfman McInnes +  snes - the SNES context
40306e4dcb14SBarry Smith .  f - the monitor function, see SNESMonitorFunction for the calling sequence
4031b8a78c4aSBarry Smith .  mctx - [optional] user-defined context for private data for the
40320298fd71SBarry Smith           monitor routine (use NULL if no context is desired)
4033b3006f0bSLois Curfman McInnes -  monitordestroy - [optional] routine that frees monitor context
40340298fd71SBarry Smith           (may be NULL)
40359b94acceSBarry Smith 
40369665c990SLois Curfman McInnes    Options Database Keys:
4037a6570f20SBarry Smith +    -snes_monitor        - sets SNESMonitorDefault()
4038798534f6SMatthew G. Knepley .    -snes_monitor draw::draw_lg - sets line graph monitor,
4039cca6129bSJed Brown -    -snes_monitor_cancel - cancels all monitors that have
4040c7afd0dbSLois Curfman McInnes                             been hardwired into a code by
4041a6570f20SBarry Smith                             calls to SNESMonitorSet(), but
4042c7afd0dbSLois Curfman McInnes                             does not cancel those set via
4043c7afd0dbSLois Curfman McInnes                             the options database.
40449665c990SLois Curfman McInnes 
4045639f9d9dSBarry Smith    Notes:
40466bc08f3fSLois Curfman McInnes    Several different monitoring routines may be set by calling
4047a6570f20SBarry Smith    SNESMonitorSet() multiple times; all will be called in the
40486bc08f3fSLois Curfman McInnes    order in which they were set.
4049639f9d9dSBarry Smith 
405095452b02SPatrick Sanan    Fortran Notes:
405195452b02SPatrick Sanan     Only a single monitor function can be set for each SNES object
4052025f1a04SBarry Smith 
405336851e7fSLois Curfman McInnes    Level: intermediate
405436851e7fSLois Curfman McInnes 
4055db781477SPatrick Sanan .seealso: `SNESMonitorDefault()`, `SNESMonitorCancel()`, `SNESMonitorFunction`
40569b94acceSBarry Smith @*/
40576e4dcb14SBarry Smith PetscErrorCode  SNESMonitorSet(SNES snes,PetscErrorCode (*f)(SNES,PetscInt,PetscReal,void*),void *mctx,PetscErrorCode (*monitordestroy)(void**))
40589b94acceSBarry Smith {
4059b90d0a6eSBarry Smith   PetscInt       i;
406078064530SBarry Smith   PetscBool      identical;
4061b90d0a6eSBarry Smith 
40623a40ed3dSBarry Smith   PetscFunctionBegin;
40630700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
4064b90d0a6eSBarry Smith   for (i=0; i<snes->numbermonitors;i++) {
40659566063dSJacob Faibussowitsch     PetscCall(PetscMonitorCompare((PetscErrorCode (*)(void))f,mctx,monitordestroy,(PetscErrorCode (*)(void))snes->monitor[i],snes->monitorcontext[i],snes->monitordestroy[i],&identical));
406678064530SBarry Smith     if (identical) PetscFunctionReturn(0);
4067649052a6SBarry Smith   }
40685f80ce2aSJacob Faibussowitsch   PetscCheck(snes->numbermonitors < MAXSNESMONITORS,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Too many monitors set");
40696e4dcb14SBarry Smith   snes->monitor[snes->numbermonitors]          = f;
4070b8a78c4aSBarry Smith   snes->monitordestroy[snes->numbermonitors]   = monitordestroy;
4071639f9d9dSBarry Smith   snes->monitorcontext[snes->numbermonitors++] = (void*)mctx;
40723a40ed3dSBarry Smith   PetscFunctionReturn(0);
40739b94acceSBarry Smith }
40749b94acceSBarry Smith 
4075a278d85bSSatish Balay /*@
4076a6570f20SBarry Smith    SNESMonitorCancel - Clears all the monitor functions for a SNES object.
40775cd90555SBarry Smith 
40783f9fe445SBarry Smith    Logically Collective on SNES
4079c7afd0dbSLois Curfman McInnes 
40805cd90555SBarry Smith    Input Parameters:
40815cd90555SBarry Smith .  snes - the SNES context
40825cd90555SBarry Smith 
40831a480d89SAdministrator    Options Database Key:
4084a6570f20SBarry Smith .  -snes_monitor_cancel - cancels all monitors that have been hardwired
4085a6570f20SBarry Smith     into a code by calls to SNESMonitorSet(), but does not cancel those
4086c7afd0dbSLois Curfman McInnes     set via the options database
40875cd90555SBarry Smith 
40885cd90555SBarry Smith    Notes:
40895cd90555SBarry Smith    There is no way to clear one specific monitor from a SNES object.
40905cd90555SBarry Smith 
409136851e7fSLois Curfman McInnes    Level: intermediate
409236851e7fSLois Curfman McInnes 
4093db781477SPatrick Sanan .seealso: `SNESMonitorDefault()`, `SNESMonitorSet()`
40945cd90555SBarry Smith @*/
40957087cfbeSBarry Smith PetscErrorCode  SNESMonitorCancel(SNES snes)
40965cd90555SBarry Smith {
4097d952e501SBarry Smith   PetscInt       i;
4098d952e501SBarry Smith 
40995cd90555SBarry Smith   PetscFunctionBegin;
41000700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
4101d952e501SBarry Smith   for (i=0; i<snes->numbermonitors; i++) {
4102d952e501SBarry Smith     if (snes->monitordestroy[i]) {
41039566063dSJacob Faibussowitsch       PetscCall((*snes->monitordestroy[i])(&snes->monitorcontext[i]));
4104d952e501SBarry Smith     }
4105d952e501SBarry Smith   }
41065cd90555SBarry Smith   snes->numbermonitors = 0;
41075cd90555SBarry Smith   PetscFunctionReturn(0);
41085cd90555SBarry Smith }
41095cd90555SBarry Smith 
4110bf388a1fSBarry Smith /*MC
4111bf388a1fSBarry Smith     SNESConvergenceTestFunction - functional form used for testing of convergence of nonlinear solver
4112bf388a1fSBarry Smith 
4113bf388a1fSBarry Smith      Synopsis:
4114aaa7dc30SBarry Smith      #include <petscsnes.h>
4115bf388a1fSBarry Smith $     PetscErrorCode SNESConvergenceTest(SNES snes,PetscInt it,PetscReal xnorm,PetscReal gnorm,PetscReal f,SNESConvergedReason *reason,void *cctx)
4116bf388a1fSBarry Smith 
41171843f636SBarry Smith      Collective on snes
41181843f636SBarry Smith 
41191843f636SBarry Smith     Input Parameters:
4120bf388a1fSBarry Smith +    snes - the SNES context
4121bf388a1fSBarry Smith .    it - current iteration (0 is the first and is before any Newton step)
4122bf388a1fSBarry Smith .    xnorm - 2-norm of current iterate
4123bf388a1fSBarry Smith .    gnorm - 2-norm of current step
41241843f636SBarry Smith .    f - 2-norm of function
41251843f636SBarry Smith -    cctx - [optional] convergence context
41261843f636SBarry Smith 
41271843f636SBarry Smith     Output Parameter:
41281843f636SBarry Smith .    reason - reason for convergence/divergence, only needs to be set when convergence or divergence is detected
4129bf388a1fSBarry Smith 
4130878cb397SSatish Balay    Level: intermediate
4131bf388a1fSBarry Smith 
4132db781477SPatrick Sanan .seealso: `SNESSetConvergenceTest()`, `SNESGetConvergenceTest()`
4133bf388a1fSBarry Smith M*/
4134bf388a1fSBarry Smith 
41359b94acceSBarry Smith /*@C
41369b94acceSBarry Smith    SNESSetConvergenceTest - Sets the function that is to be used
41379b94acceSBarry Smith    to test for convergence of the nonlinear iterative solution.
41389b94acceSBarry Smith 
41393f9fe445SBarry Smith    Logically Collective on SNES
4140fee21e36SBarry Smith 
4141c7afd0dbSLois Curfman McInnes    Input Parameters:
4142c7afd0dbSLois Curfman McInnes +  snes - the SNES context
4143bf388a1fSBarry Smith .  SNESConvergenceTestFunction - routine to test for convergence
41440298fd71SBarry Smith .  cctx - [optional] context for private data for the convergence routine  (may be NULL)
4145cf90aa19SBarry Smith -  destroy - [optional] destructor for the context (may be NULL; PETSC_NULL_FUNCTION in Fortran)
41469b94acceSBarry Smith 
414736851e7fSLois Curfman McInnes    Level: advanced
414836851e7fSLois Curfman McInnes 
4149db781477SPatrick Sanan .seealso: `SNESConvergedDefault()`, `SNESConvergedSkip()`, `SNESConvergenceTestFunction`
41509b94acceSBarry Smith @*/
4151bf388a1fSBarry Smith PetscErrorCode  SNESSetConvergenceTest(SNES snes,PetscErrorCode (*SNESConvergenceTestFunction)(SNES,PetscInt,PetscReal,PetscReal,PetscReal,SNESConvergedReason*,void*),void *cctx,PetscErrorCode (*destroy)(void*))
41529b94acceSBarry Smith {
41533a40ed3dSBarry Smith   PetscFunctionBegin;
41540700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
4155e2a6519dSDmitry Karpeev   if (!SNESConvergenceTestFunction) SNESConvergenceTestFunction = SNESConvergedSkip;
41561baa6e33SBarry Smith   if (snes->ops->convergeddestroy) PetscCall((*snes->ops->convergeddestroy)(snes->cnvP));
4157bf388a1fSBarry Smith   snes->ops->converged        = SNESConvergenceTestFunction;
41587f7931b9SBarry Smith   snes->ops->convergeddestroy = destroy;
415985385478SLisandro Dalcin   snes->cnvP                  = cctx;
41603a40ed3dSBarry Smith   PetscFunctionReturn(0);
41619b94acceSBarry Smith }
41629b94acceSBarry Smith 
416352baeb72SSatish Balay /*@
4164184914b5SBarry Smith    SNESGetConvergedReason - Gets the reason the SNES iteration was stopped.
4165184914b5SBarry Smith 
4166184914b5SBarry Smith    Not Collective
4167184914b5SBarry Smith 
4168184914b5SBarry Smith    Input Parameter:
4169184914b5SBarry Smith .  snes - the SNES context
4170184914b5SBarry Smith 
4171184914b5SBarry Smith    Output Parameter:
41724d0a8057SBarry Smith .  reason - negative value indicates diverged, positive value converged, see SNESConvergedReason or the
4173184914b5SBarry Smith             manual pages for the individual convergence tests for complete lists
4174184914b5SBarry Smith 
41756a4d7782SBarry Smith    Options Database:
41766a4d7782SBarry Smith .   -snes_converged_reason - prints the reason to standard out
41776a4d7782SBarry Smith 
4178184914b5SBarry Smith    Level: intermediate
4179184914b5SBarry Smith 
418095452b02SPatrick Sanan    Notes:
418195452b02SPatrick Sanan     Should only be called after the call the SNESSolve() is complete, if it is called earlier it returns the value SNES__CONVERGED_ITERATING.
4182184914b5SBarry Smith 
4183db781477SPatrick Sanan .seealso: `SNESSetConvergenceTest()`, `SNESSetConvergedReason()`, `SNESConvergedReason`
4184184914b5SBarry Smith @*/
41857087cfbeSBarry Smith PetscErrorCode SNESGetConvergedReason(SNES snes,SNESConvergedReason *reason)
4186184914b5SBarry Smith {
4187184914b5SBarry Smith   PetscFunctionBegin;
41880700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
41894482741eSBarry Smith   PetscValidPointer(reason,2);
4190184914b5SBarry Smith   *reason = snes->reason;
4191184914b5SBarry Smith   PetscFunctionReturn(0);
4192184914b5SBarry Smith }
4193184914b5SBarry Smith 
4194c4421ceaSFande Kong /*@C
4195c4421ceaSFande Kong    SNESGetConvergedReasonString - Return a human readable string for snes converged reason
4196c4421ceaSFande Kong 
4197c4421ceaSFande Kong    Not Collective
4198c4421ceaSFande Kong 
4199c4421ceaSFande Kong    Input Parameter:
4200c4421ceaSFande Kong .  snes - the SNES context
4201c4421ceaSFande Kong 
4202c4421ceaSFande Kong    Output Parameter:
4203c4421ceaSFande Kong .  strreason - a human readable string that describes SNES converged reason
4204c4421ceaSFande Kong 
420599c90e12SSatish Balay    Level: beginner
4206c4421ceaSFande Kong 
4207db781477SPatrick Sanan .seealso: `SNESGetConvergedReason()`
4208c4421ceaSFande Kong @*/
4209c4421ceaSFande Kong PetscErrorCode SNESGetConvergedReasonString(SNES snes, const char** strreason)
4210c4421ceaSFande Kong {
4211c4421ceaSFande Kong   PetscFunctionBegin;
4212c4421ceaSFande Kong   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
4213dadcf809SJacob Faibussowitsch   PetscValidPointer(strreason,2);
4214c4421ceaSFande Kong   *strreason = SNESConvergedReasons[snes->reason];
4215c4421ceaSFande Kong   PetscFunctionReturn(0);
4216c4421ceaSFande Kong }
4217c4421ceaSFande Kong 
421833866048SMatthew G. Knepley /*@
421933866048SMatthew G. Knepley    SNESSetConvergedReason - Sets the reason the SNES iteration was stopped.
422033866048SMatthew G. Knepley 
422133866048SMatthew G. Knepley    Not Collective
422233866048SMatthew G. Knepley 
422333866048SMatthew G. Knepley    Input Parameters:
422433866048SMatthew G. Knepley +  snes - the SNES context
422533866048SMatthew G. Knepley -  reason - negative value indicates diverged, positive value converged, see SNESConvergedReason or the
422633866048SMatthew G. Knepley             manual pages for the individual convergence tests for complete lists
422733866048SMatthew G. Knepley 
422833866048SMatthew G. Knepley    Level: intermediate
422933866048SMatthew G. Knepley 
4230db781477SPatrick Sanan .seealso: `SNESGetConvergedReason()`, `SNESSetConvergenceTest()`, `SNESConvergedReason`
423133866048SMatthew G. Knepley @*/
423233866048SMatthew G. Knepley PetscErrorCode SNESSetConvergedReason(SNES snes,SNESConvergedReason reason)
423333866048SMatthew G. Knepley {
423433866048SMatthew G. Knepley   PetscFunctionBegin;
423533866048SMatthew G. Knepley   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
423633866048SMatthew G. Knepley   snes->reason = reason;
423733866048SMatthew G. Knepley   PetscFunctionReturn(0);
423833866048SMatthew G. Knepley }
423933866048SMatthew G. Knepley 
4240c9005455SLois Curfman McInnes /*@
4241c9005455SLois Curfman McInnes    SNESSetConvergenceHistory - Sets the array used to hold the convergence history.
4242c9005455SLois Curfman McInnes 
42433f9fe445SBarry Smith    Logically Collective on SNES
4244fee21e36SBarry Smith 
4245c7afd0dbSLois Curfman McInnes    Input Parameters:
4246c7afd0dbSLois Curfman McInnes +  snes - iterative context obtained from SNESCreate()
42478c7482ecSBarry Smith .  a   - array to hold history, this array will contain the function norms computed at each step
4248cd5578b5SBarry Smith .  its - integer array holds the number of linear iterations for each solve.
4249758f92a0SBarry Smith .  na  - size of a and its
425064731454SLois Curfman McInnes -  reset - PETSC_TRUE indicates each new nonlinear solve resets the history counter to zero,
4251758f92a0SBarry Smith            else it continues storing new values for new nonlinear solves after the old ones
4252c7afd0dbSLois Curfman McInnes 
4253308dcc3eSBarry Smith    Notes:
42540298fd71SBarry Smith    If 'a' and 'its' are NULL then space is allocated for the history. If 'na' PETSC_DECIDE or PETSC_DEFAULT then a
4255308dcc3eSBarry Smith    default array of length 10000 is allocated.
4256308dcc3eSBarry Smith 
4257c9005455SLois Curfman McInnes    This routine is useful, e.g., when running a code for purposes
4258c9005455SLois Curfman McInnes    of accurate performance monitoring, when no I/O should be done
4259c9005455SLois Curfman McInnes    during the section of code that is being timed.
4260c9005455SLois Curfman McInnes 
426136851e7fSLois Curfman McInnes    Level: intermediate
426236851e7fSLois Curfman McInnes 
4263db781477SPatrick Sanan .seealso: `SNESGetConvergenceHistory()`
4264758f92a0SBarry Smith 
4265c9005455SLois Curfman McInnes @*/
42667087cfbeSBarry Smith PetscErrorCode  SNESSetConvergenceHistory(SNES snes,PetscReal a[],PetscInt its[],PetscInt na,PetscBool reset)
4267c9005455SLois Curfman McInnes {
42683a40ed3dSBarry Smith   PetscFunctionBegin;
42690700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
4270064a246eSJacob Faibussowitsch   if (a) PetscValidRealPointer(a,2);
4271a562a398SLisandro Dalcin   if (its) PetscValidIntPointer(its,3);
42727a1ec6d4SBarry Smith   if (!a) {
4273308dcc3eSBarry Smith     if (na == PETSC_DECIDE || na == PETSC_DEFAULT) na = 1000;
42749566063dSJacob Faibussowitsch     PetscCall(PetscCalloc2(na,&a,na,&its));
4275071fcb05SBarry Smith     snes->conv_hist_alloc = PETSC_TRUE;
4276308dcc3eSBarry Smith   }
4277c9005455SLois Curfman McInnes   snes->conv_hist       = a;
4278758f92a0SBarry Smith   snes->conv_hist_its   = its;
4279115dd874SBarry Smith   snes->conv_hist_max   = (size_t)na;
4280a12bc48fSLisandro Dalcin   snes->conv_hist_len   = 0;
4281758f92a0SBarry Smith   snes->conv_hist_reset = reset;
4282758f92a0SBarry Smith   PetscFunctionReturn(0);
4283758f92a0SBarry Smith }
4284758f92a0SBarry Smith 
4285308dcc3eSBarry Smith #if defined(PETSC_HAVE_MATLAB_ENGINE)
4286c6db04a5SJed Brown #include <engine.h>   /* MATLAB include file */
4287c6db04a5SJed Brown #include <mex.h>      /* MATLAB include file */
428899e0435eSBarry Smith 
42898cc058d9SJed Brown PETSC_EXTERN mxArray *SNESGetConvergenceHistoryMatlab(SNES snes)
4290308dcc3eSBarry Smith {
4291308dcc3eSBarry Smith   mxArray   *mat;
4292308dcc3eSBarry Smith   PetscInt  i;
4293308dcc3eSBarry Smith   PetscReal *ar;
4294308dcc3eSBarry Smith 
4295308dcc3eSBarry Smith   PetscFunctionBegin;
4296308dcc3eSBarry Smith   mat = mxCreateDoubleMatrix(snes->conv_hist_len,1,mxREAL);
4297308dcc3eSBarry Smith   ar  = (PetscReal*) mxGetData(mat);
4298f5af7f23SKarl Rupp   for (i=0; i<snes->conv_hist_len; i++) ar[i] = snes->conv_hist[i];
4299308dcc3eSBarry Smith   PetscFunctionReturn(mat);
4300308dcc3eSBarry Smith }
4301308dcc3eSBarry Smith #endif
4302308dcc3eSBarry Smith 
43030c4c9dddSBarry Smith /*@C
4304758f92a0SBarry Smith    SNESGetConvergenceHistory - Gets the array used to hold the convergence history.
4305758f92a0SBarry Smith 
43063f9fe445SBarry Smith    Not Collective
4307758f92a0SBarry Smith 
4308758f92a0SBarry Smith    Input Parameter:
4309758f92a0SBarry Smith .  snes - iterative context obtained from SNESCreate()
4310758f92a0SBarry Smith 
4311758f92a0SBarry Smith    Output Parameters:
4312a2b725a8SWilliam Gropp +  a   - array to hold history
4313758f92a0SBarry Smith .  its - integer array holds the number of linear iterations (or
4314758f92a0SBarry Smith          negative if not converged) for each solve.
4315758f92a0SBarry Smith -  na  - size of a and its
4316758f92a0SBarry Smith 
4317758f92a0SBarry Smith    Notes:
4318758f92a0SBarry Smith     The calling sequence for this routine in Fortran is
4319758f92a0SBarry Smith $   call SNESGetConvergenceHistory(SNES snes, integer na, integer ierr)
4320758f92a0SBarry Smith 
4321758f92a0SBarry Smith    This routine is useful, e.g., when running a code for purposes
4322758f92a0SBarry Smith    of accurate performance monitoring, when no I/O should be done
4323758f92a0SBarry Smith    during the section of code that is being timed.
4324758f92a0SBarry Smith 
4325758f92a0SBarry Smith    Level: intermediate
4326758f92a0SBarry Smith 
4327db781477SPatrick Sanan .seealso: `SNESSetConvergenceHistory()`
4328758f92a0SBarry Smith 
4329758f92a0SBarry Smith @*/
43307087cfbeSBarry Smith PetscErrorCode  SNESGetConvergenceHistory(SNES snes,PetscReal *a[],PetscInt *its[],PetscInt *na)
4331758f92a0SBarry Smith {
4332758f92a0SBarry Smith   PetscFunctionBegin;
43330700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
4334758f92a0SBarry Smith   if (a)   *a   = snes->conv_hist;
4335758f92a0SBarry Smith   if (its) *its = snes->conv_hist_its;
4336115dd874SBarry Smith   if (na)  *na  = (PetscInt) snes->conv_hist_len;
43373a40ed3dSBarry Smith   PetscFunctionReturn(0);
4338c9005455SLois Curfman McInnes }
4339c9005455SLois Curfman McInnes 
4340ac226902SBarry Smith /*@C
434176b2cf59SMatthew Knepley   SNESSetUpdate - Sets the general-purpose update function called
4342eec8f646SJed Brown   at the beginning of every iteration of the nonlinear solve. Specifically
43437e4bb74cSBarry Smith   it is called just before the Jacobian is "evaluated".
434476b2cf59SMatthew Knepley 
43453f9fe445SBarry Smith   Logically Collective on SNES
434676b2cf59SMatthew Knepley 
434776b2cf59SMatthew Knepley   Input Parameters:
4348a2b725a8SWilliam Gropp + snes - The nonlinear solver context
4349a2b725a8SWilliam Gropp - func - The function
435076b2cf59SMatthew Knepley 
435176b2cf59SMatthew Knepley   Calling sequence of func:
4352a2b725a8SWilliam Gropp $ func (SNES snes, PetscInt step);
435376b2cf59SMatthew Knepley 
435476b2cf59SMatthew Knepley . step - The current step of the iteration
435576b2cf59SMatthew Knepley 
4356fe97e370SBarry Smith   Level: advanced
4357fe97e370SBarry Smith 
43586b7fb656SBarry Smith   Note:
43596b7fb656SBarry 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()
4360fe97e370SBarry Smith      This is not used by most users.
436176b2cf59SMatthew Knepley 
43626b7fb656SBarry 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.
43636b7fb656SBarry Smith 
4364db781477SPatrick Sanan .seealso `SNESSetJacobian()`, `SNESSolve()`, `SNESLineSearchSetPreCheck()`, `SNESLineSearchSetPostCheck()`, `SNESNewtonTRSetPreCheck()`, `SNESNewtonTRSetPostCheck()`,
4365db781477SPatrick Sanan          `SNESMonitorSet()`, `SNESSetDivergenceTest()`
436676b2cf59SMatthew Knepley @*/
43677087cfbeSBarry Smith PetscErrorCode  SNESSetUpdate(SNES snes, PetscErrorCode (*func)(SNES, PetscInt))
436876b2cf59SMatthew Knepley {
436976b2cf59SMatthew Knepley   PetscFunctionBegin;
43700700a824SBarry Smith   PetscValidHeaderSpecific(snes, SNES_CLASSID,1);
4371e7788613SBarry Smith   snes->ops->update = func;
437276b2cf59SMatthew Knepley   PetscFunctionReturn(0);
437376b2cf59SMatthew Knepley }
437476b2cf59SMatthew Knepley 
43759b94acceSBarry Smith /*
43769b94acceSBarry Smith    SNESScaleStep_Private - Scales a step so that its length is less than the
43779b94acceSBarry Smith    positive parameter delta.
43789b94acceSBarry Smith 
43799b94acceSBarry Smith     Input Parameters:
4380c7afd0dbSLois Curfman McInnes +   snes - the SNES context
43819b94acceSBarry Smith .   y - approximate solution of linear system
43829b94acceSBarry Smith .   fnorm - 2-norm of current function
4383c7afd0dbSLois Curfman McInnes -   delta - trust region size
43849b94acceSBarry Smith 
43859b94acceSBarry Smith     Output Parameters:
4386c7afd0dbSLois Curfman McInnes +   gpnorm - predicted function norm at the new point, assuming local
43879b94acceSBarry Smith     linearization.  The value is zero if the step lies within the trust
43889b94acceSBarry Smith     region, and exceeds zero otherwise.
4389c7afd0dbSLois Curfman McInnes -   ynorm - 2-norm of the step
43909b94acceSBarry Smith 
43919b94acceSBarry Smith     Note:
439204d7464bSBarry Smith     For non-trust region methods such as SNESNEWTONLS, the parameter delta
43939b94acceSBarry Smith     is set to be the maximum allowable step size.
43949b94acceSBarry Smith 
43959b94acceSBarry Smith */
4396dfbe8321SBarry Smith PetscErrorCode SNESScaleStep_Private(SNES snes,Vec y,PetscReal *fnorm,PetscReal *delta,PetscReal *gpnorm,PetscReal *ynorm)
43979b94acceSBarry Smith {
4398064f8208SBarry Smith   PetscReal      nrm;
4399ea709b57SSatish Balay   PetscScalar    cnorm;
44003a40ed3dSBarry Smith 
44013a40ed3dSBarry Smith   PetscFunctionBegin;
44020700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
44030700a824SBarry Smith   PetscValidHeaderSpecific(y,VEC_CLASSID,2);
4404c9780b6fSBarry Smith   PetscCheckSameComm(snes,1,y,2);
4405184914b5SBarry Smith 
44069566063dSJacob Faibussowitsch   PetscCall(VecNorm(y,NORM_2,&nrm));
4407064f8208SBarry Smith   if (nrm > *delta) {
4408064f8208SBarry Smith     nrm     = *delta/nrm;
4409064f8208SBarry Smith     *gpnorm = (1.0 - nrm)*(*fnorm);
4410064f8208SBarry Smith     cnorm   = nrm;
44119566063dSJacob Faibussowitsch     PetscCall(VecScale(y,cnorm));
44129b94acceSBarry Smith     *ynorm  = *delta;
44139b94acceSBarry Smith   } else {
44149b94acceSBarry Smith     *gpnorm = 0.0;
4415064f8208SBarry Smith     *ynorm  = nrm;
44169b94acceSBarry Smith   }
44173a40ed3dSBarry Smith   PetscFunctionReturn(0);
44189b94acceSBarry Smith }
44199b94acceSBarry Smith 
442091f3e32bSBarry Smith /*@C
442119a666eeSBarry Smith    SNESConvergedReasonView - Displays the reason a SNES solve converged or diverged to a viewer
44222a359c20SBarry Smith 
44232a359c20SBarry Smith    Collective on SNES
44242a359c20SBarry Smith 
44252a359c20SBarry Smith    Parameter:
44262a359c20SBarry Smith +  snes - iterative context obtained from SNESCreate()
44272a359c20SBarry Smith -  viewer - the viewer to display the reason
44282a359c20SBarry Smith 
44292a359c20SBarry Smith    Options Database Keys:
4430ee300463SSatish Balay +  -snes_converged_reason - print reason for converged or diverged, also prints number of iterations
4431ee300463SSatish Balay -  -snes_converged_reason ::failed - only print reason and number of iterations when diverged
4432eafd5ff0SAlex Lindsay 
443319a666eeSBarry Smith   Notes:
443419a666eeSBarry Smith      To change the format of the output call PetscViewerPushFormat(viewer,format) before this call. Use PETSC_VIEWER_DEFAULT for the default,
443519a666eeSBarry Smith      use PETSC_VIEWER_FAILED to only display a reason if it fails.
44362a359c20SBarry Smith 
44372a359c20SBarry Smith    Level: beginner
44382a359c20SBarry Smith 
4439db781477SPatrick Sanan .seealso: `SNESCreate()`, `SNESSetUp()`, `SNESDestroy()`, `SNESSetTolerances()`, `SNESConvergedDefault()`, `SNESGetConvergedReason()`, `SNESConvergedReasonViewFromOptions()`,
4440db781477SPatrick Sanan           `PetscViewerPushFormat()`, `PetscViewerPopFormat()`
44412a359c20SBarry Smith 
44422a359c20SBarry Smith @*/
444319a666eeSBarry Smith PetscErrorCode  SNESConvergedReasonView(SNES snes,PetscViewer viewer)
44442a359c20SBarry Smith {
444575cca76cSMatthew G. Knepley   PetscViewerFormat format;
44462a359c20SBarry Smith   PetscBool         isAscii;
44472a359c20SBarry Smith 
44482a359c20SBarry Smith   PetscFunctionBegin;
444919a666eeSBarry Smith   if (!viewer) viewer = PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)snes));
44509566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&isAscii));
44512a359c20SBarry Smith   if (isAscii) {
44529566063dSJacob Faibussowitsch     PetscCall(PetscViewerGetFormat(viewer, &format));
44539566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIAddTab(viewer,((PetscObject)snes)->tablevel));
445475cca76cSMatthew G. Knepley     if (format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
445575cca76cSMatthew G. Knepley       DM              dm;
445675cca76cSMatthew G. Knepley       Vec             u;
445775cca76cSMatthew G. Knepley       PetscDS         prob;
445875cca76cSMatthew G. Knepley       PetscInt        Nf, f;
445995cbbfd3SMatthew G. Knepley       PetscErrorCode (**exactSol)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar[], void *);
446095cbbfd3SMatthew G. Knepley       void            **exactCtx;
446175cca76cSMatthew G. Knepley       PetscReal       error;
446275cca76cSMatthew G. Knepley 
44639566063dSJacob Faibussowitsch       PetscCall(SNESGetDM(snes, &dm));
44649566063dSJacob Faibussowitsch       PetscCall(SNESGetSolution(snes, &u));
44659566063dSJacob Faibussowitsch       PetscCall(DMGetDS(dm, &prob));
44669566063dSJacob Faibussowitsch       PetscCall(PetscDSGetNumFields(prob, &Nf));
44679566063dSJacob Faibussowitsch       PetscCall(PetscMalloc2(Nf, &exactSol, Nf, &exactCtx));
44689566063dSJacob Faibussowitsch       for (f = 0; f < Nf; ++f) PetscCall(PetscDSGetExactSolution(prob, f, &exactSol[f], &exactCtx[f]));
44699566063dSJacob Faibussowitsch       PetscCall(DMComputeL2Diff(dm, 0.0, exactSol, exactCtx, u, &error));
44709566063dSJacob Faibussowitsch       PetscCall(PetscFree2(exactSol, exactCtx));
44719566063dSJacob Faibussowitsch       if (error < 1.0e-11) PetscCall(PetscViewerASCIIPrintf(viewer, "L_2 Error: < 1.0e-11\n"));
447263a3b9bcSJacob Faibussowitsch       else                 PetscCall(PetscViewerASCIIPrintf(viewer, "L_2 Error: %g\n", (double)error));
447375cca76cSMatthew G. Knepley     }
4474eafd5ff0SAlex Lindsay     if (snes->reason > 0 && format != PETSC_VIEWER_FAILED) {
44752a359c20SBarry Smith       if (((PetscObject) snes)->prefix) {
447663a3b9bcSJacob Faibussowitsch         PetscCall(PetscViewerASCIIPrintf(viewer,"Nonlinear %s solve converged due to %s iterations %" PetscInt_FMT "\n",((PetscObject) snes)->prefix,SNESConvergedReasons[snes->reason],snes->iter));
44772a359c20SBarry Smith       } else {
447863a3b9bcSJacob Faibussowitsch         PetscCall(PetscViewerASCIIPrintf(viewer,"Nonlinear solve converged due to %s iterations %" PetscInt_FMT "\n",SNESConvergedReasons[snes->reason],snes->iter));
44792a359c20SBarry Smith       }
4480eafd5ff0SAlex Lindsay     } else if (snes->reason <= 0) {
44812a359c20SBarry Smith       if (((PetscObject) snes)->prefix) {
448263a3b9bcSJacob Faibussowitsch         PetscCall(PetscViewerASCIIPrintf(viewer,"Nonlinear %s solve did not converge due to %s iterations %" PetscInt_FMT "\n",((PetscObject) snes)->prefix,SNESConvergedReasons[snes->reason],snes->iter));
44832a359c20SBarry Smith       } else {
448463a3b9bcSJacob Faibussowitsch         PetscCall(PetscViewerASCIIPrintf(viewer,"Nonlinear solve did not converge due to %s iterations %" PetscInt_FMT "\n",SNESConvergedReasons[snes->reason],snes->iter));
44852a359c20SBarry Smith       }
44862a359c20SBarry Smith     }
44879566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIISubtractTab(viewer,((PetscObject)snes)->tablevel));
44882a359c20SBarry Smith   }
44892a359c20SBarry Smith   PetscFunctionReturn(0);
44902a359c20SBarry Smith }
44912a359c20SBarry Smith 
4492c4421ceaSFande Kong /*@C
4493c4421ceaSFande Kong    SNESConvergedReasonViewSet - Sets an ADDITIONAL function that is to be used at the
4494c4421ceaSFande Kong     end of the nonlinear solver to display the conver reason of the nonlinear solver.
4495c4421ceaSFande Kong 
4496c4421ceaSFande Kong    Logically Collective on SNES
4497c4421ceaSFande Kong 
4498c4421ceaSFande Kong    Input Parameters:
4499c4421ceaSFande Kong +  snes - the SNES context
4500c4421ceaSFande Kong .  f - the snes converged reason view function
4501c4421ceaSFande Kong .  vctx - [optional] user-defined context for private data for the
4502c4421ceaSFande Kong           snes converged reason view routine (use NULL if no context is desired)
4503c4421ceaSFande Kong -  reasonviewdestroy - [optional] routine that frees reasonview context
4504c4421ceaSFande Kong           (may be NULL)
4505c4421ceaSFande Kong 
4506c4421ceaSFande Kong    Options Database Keys:
4507c4421ceaSFande Kong +    -snes_converged_reason        - sets a default SNESConvergedReasonView()
4508c4421ceaSFande Kong -    -snes_converged_reason_view_cancel - cancels all converged reason viewers that have
4509c4421ceaSFande Kong                             been hardwired into a code by
4510c4421ceaSFande Kong                             calls to SNESConvergedReasonViewSet(), but
4511c4421ceaSFande Kong                             does not cancel those set via
4512c4421ceaSFande Kong                             the options database.
4513c4421ceaSFande Kong 
4514c4421ceaSFande Kong    Notes:
4515c4421ceaSFande Kong    Several different converged reason view routines may be set by calling
4516c4421ceaSFande Kong    SNESConvergedReasonViewSet() multiple times; all will be called in the
4517c4421ceaSFande Kong    order in which they were set.
4518c4421ceaSFande Kong 
4519c4421ceaSFande Kong    Level: intermediate
4520c4421ceaSFande Kong 
4521db781477SPatrick Sanan .seealso: `SNESConvergedReasonView()`, `SNESConvergedReasonViewCancel()`
4522c4421ceaSFande Kong @*/
4523c4421ceaSFande Kong PetscErrorCode  SNESConvergedReasonViewSet(SNES snes,PetscErrorCode (*f)(SNES,void*),void *vctx,PetscErrorCode (*reasonviewdestroy)(void**))
4524c4421ceaSFande Kong {
4525c4421ceaSFande Kong   PetscInt       i;
4526c4421ceaSFande Kong   PetscBool      identical;
4527c4421ceaSFande Kong 
4528c4421ceaSFande Kong   PetscFunctionBegin;
4529c4421ceaSFande Kong   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
4530c4421ceaSFande Kong   for (i=0; i<snes->numberreasonviews;i++) {
45319566063dSJacob Faibussowitsch     PetscCall(PetscMonitorCompare((PetscErrorCode (*)(void))f,vctx,reasonviewdestroy,(PetscErrorCode (*)(void))snes->reasonview[i],snes->reasonviewcontext[i],snes->reasonviewdestroy[i],&identical));
4532c4421ceaSFande Kong     if (identical) PetscFunctionReturn(0);
4533c4421ceaSFande Kong   }
45345f80ce2aSJacob Faibussowitsch   PetscCheck(snes->numberreasonviews < MAXSNESREASONVIEWS,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Too many SNES reasonview set");
4535c4421ceaSFande Kong   snes->reasonview[snes->numberreasonviews]          = f;
4536c4421ceaSFande Kong   snes->reasonviewdestroy[snes->numberreasonviews]   = reasonviewdestroy;
4537c4421ceaSFande Kong   snes->reasonviewcontext[snes->numberreasonviews++] = (void*)vctx;
4538c4421ceaSFande Kong   PetscFunctionReturn(0);
4539c4421ceaSFande Kong }
4540c4421ceaSFande Kong 
454191f3e32bSBarry Smith /*@
454219a666eeSBarry Smith   SNESConvergedReasonViewFromOptions - Processes command line options to determine if/how a SNESReason is to be viewed.
4543c4421ceaSFande Kong                                        All the user-provided convergedReasonView routines will be involved as well, if they exist.
45442a359c20SBarry Smith 
45452a359c20SBarry Smith   Collective on SNES
45462a359c20SBarry Smith 
45472a359c20SBarry Smith   Input Parameters:
45482a359c20SBarry Smith . snes   - the SNES object
45492a359c20SBarry Smith 
45502a359c20SBarry Smith   Level: intermediate
45512a359c20SBarry Smith 
4552db781477SPatrick Sanan .seealso: `SNESCreate()`, `SNESSetUp()`, `SNESDestroy()`, `SNESSetTolerances()`, `SNESConvergedDefault()`, `SNESGetConvergedReason()`, `SNESConvergedReasonView()`
455319a666eeSBarry Smith 
45542a359c20SBarry Smith @*/
455519a666eeSBarry Smith PetscErrorCode SNESConvergedReasonViewFromOptions(SNES snes)
45562a359c20SBarry Smith {
45572a359c20SBarry Smith   PetscViewer       viewer;
45582a359c20SBarry Smith   PetscBool         flg;
45592a359c20SBarry Smith   static PetscBool  incall = PETSC_FALSE;
45602a359c20SBarry Smith   PetscViewerFormat format;
4561c4421ceaSFande Kong   PetscInt          i;
45622a359c20SBarry Smith 
45632a359c20SBarry Smith   PetscFunctionBegin;
45642a359c20SBarry Smith   if (incall) PetscFunctionReturn(0);
45652a359c20SBarry Smith   incall = PETSC_TRUE;
4566c4421ceaSFande Kong 
4567c4421ceaSFande Kong   /* All user-provided viewers are called first, if they exist. */
4568c4421ceaSFande Kong   for (i=0; i<snes->numberreasonviews; i++) {
45699566063dSJacob Faibussowitsch     PetscCall((*snes->reasonview[i])(snes,snes->reasonviewcontext[i]));
4570c4421ceaSFande Kong   }
4571c4421ceaSFande Kong 
4572c4421ceaSFande Kong   /* Call PETSc default routine if users ask for it */
45739566063dSJacob Faibussowitsch   PetscCall(PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_converged_reason",&viewer,&format,&flg));
45742a359c20SBarry Smith   if (flg) {
45759566063dSJacob Faibussowitsch     PetscCall(PetscViewerPushFormat(viewer,format));
45769566063dSJacob Faibussowitsch     PetscCall(SNESConvergedReasonView(snes,viewer));
45779566063dSJacob Faibussowitsch     PetscCall(PetscViewerPopFormat(viewer));
45789566063dSJacob Faibussowitsch     PetscCall(PetscViewerDestroy(&viewer));
45792a359c20SBarry Smith   }
45802a359c20SBarry Smith   incall = PETSC_FALSE;
45812a359c20SBarry Smith   PetscFunctionReturn(0);
45822a359c20SBarry Smith }
45832a359c20SBarry Smith 
4584487a658cSBarry Smith /*@
4585f69a0ea3SMatthew Knepley    SNESSolve - Solves a nonlinear system F(x) = b.
4586f69a0ea3SMatthew Knepley    Call SNESSolve() after calling SNESCreate() and optional routines of the form SNESSetXXX().
45879b94acceSBarry Smith 
4588c7afd0dbSLois Curfman McInnes    Collective on SNES
4589c7afd0dbSLois Curfman McInnes 
4590b2002411SLois Curfman McInnes    Input Parameters:
4591c7afd0dbSLois Curfman McInnes +  snes - the SNES context
45920298fd71SBarry Smith .  b - the constant part of the equation F(x) = b, or NULL to use zero.
459385385478SLisandro Dalcin -  x - the solution vector.
45949b94acceSBarry Smith 
4595b2002411SLois Curfman McInnes    Notes:
45968ddd3da0SLois Curfman McInnes    The user should initialize the vector,x, with the initial guess
45976b7fb656SBarry Smith    for the nonlinear solve prior to calling SNESSolve().  In particular,
45988ddd3da0SLois Curfman McInnes    to employ an initial guess of zero, the user should explicitly set
45998ddd3da0SLois Curfman McInnes    this vector to zero by calling VecSet().
46008ddd3da0SLois Curfman McInnes 
460136851e7fSLois Curfman McInnes    Level: beginner
460236851e7fSLois Curfman McInnes 
4603db781477SPatrick Sanan .seealso: `SNESCreate()`, `SNESDestroy()`, `SNESSetFunction()`, `SNESSetJacobian()`, `SNESSetGridSequence()`, `SNESGetSolution()`,
4604db781477SPatrick Sanan           `SNESNewtonTRSetPreCheck()`, `SNESNewtonTRGetPreCheck()`, `SNESNewtonTRSetPostCheck()`, `SNESNewtonTRGetPostCheck()`,
4605db781477SPatrick Sanan           `SNESLineSearchSetPostCheck()`, `SNESLineSearchGetPostCheck()`, `SNESLineSearchSetPreCheck()`, `SNESLineSearchGetPreCheck()`
46069b94acceSBarry Smith @*/
46077087cfbeSBarry Smith PetscErrorCode  SNESSolve(SNES snes,Vec b,Vec x)
46089b94acceSBarry Smith {
4609ace3abfcSBarry Smith   PetscBool         flg;
4610efd51863SBarry Smith   PetscInt          grid;
46110298fd71SBarry Smith   Vec               xcreated = NULL;
4612caa4e7f2SJed Brown   DM                dm;
4613052efed2SBarry Smith 
46143a40ed3dSBarry Smith   PetscFunctionBegin;
46150700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
4616a69afd8bSBarry Smith   if (x) PetscValidHeaderSpecific(x,VEC_CLASSID,3);
4617a69afd8bSBarry Smith   if (x) PetscCheckSameComm(snes,1,x,3);
46180700a824SBarry Smith   if (b) PetscValidHeaderSpecific(b,VEC_CLASSID,2);
461985385478SLisandro Dalcin   if (b) PetscCheckSameComm(snes,1,b,2);
462085385478SLisandro Dalcin 
462134b4d3a8SMatthew G. Knepley   /* High level operations using the nonlinear solver */
462206fc46c8SMatthew G. Knepley   {
462306fc46c8SMatthew G. Knepley     PetscViewer       viewer;
462406fc46c8SMatthew G. Knepley     PetscViewerFormat format;
46257c88af5aSMatthew G. Knepley     PetscInt          num;
462606fc46c8SMatthew G. Knepley     PetscBool         flg;
462706fc46c8SMatthew G. Knepley     static PetscBool  incall = PETSC_FALSE;
462806fc46c8SMatthew G. Knepley 
462906fc46c8SMatthew G. Knepley     if (!incall) {
463034b4d3a8SMatthew G. Knepley       /* Estimate the convergence rate of the discretization */
46319566063dSJacob Faibussowitsch       PetscCall(PetscOptionsGetViewer(PetscObjectComm((PetscObject) snes),((PetscObject)snes)->options, ((PetscObject) snes)->prefix, "-snes_convergence_estimate", &viewer, &format, &flg));
463206fc46c8SMatthew G. Knepley       if (flg) {
463306fc46c8SMatthew G. Knepley         PetscConvEst conv;
463446079b62SMatthew G. Knepley         DM           dm;
463546079b62SMatthew G. Knepley         PetscReal   *alpha; /* Convergence rate of the solution error for each field in the L_2 norm */
463646079b62SMatthew G. Knepley         PetscInt     Nf;
463706fc46c8SMatthew G. Knepley 
463806fc46c8SMatthew G. Knepley         incall = PETSC_TRUE;
46399566063dSJacob Faibussowitsch         PetscCall(SNESGetDM(snes, &dm));
46409566063dSJacob Faibussowitsch         PetscCall(DMGetNumFields(dm, &Nf));
46419566063dSJacob Faibussowitsch         PetscCall(PetscCalloc1(Nf, &alpha));
46429566063dSJacob Faibussowitsch         PetscCall(PetscConvEstCreate(PetscObjectComm((PetscObject) snes), &conv));
46439566063dSJacob Faibussowitsch         PetscCall(PetscConvEstSetSolver(conv, (PetscObject) snes));
46449566063dSJacob Faibussowitsch         PetscCall(PetscConvEstSetFromOptions(conv));
46459566063dSJacob Faibussowitsch         PetscCall(PetscConvEstSetUp(conv));
46469566063dSJacob Faibussowitsch         PetscCall(PetscConvEstGetConvRate(conv, alpha));
46479566063dSJacob Faibussowitsch         PetscCall(PetscViewerPushFormat(viewer, format));
46489566063dSJacob Faibussowitsch         PetscCall(PetscConvEstRateView(conv, alpha, viewer));
46499566063dSJacob Faibussowitsch         PetscCall(PetscViewerPopFormat(viewer));
46509566063dSJacob Faibussowitsch         PetscCall(PetscViewerDestroy(&viewer));
46519566063dSJacob Faibussowitsch         PetscCall(PetscConvEstDestroy(&conv));
46529566063dSJacob Faibussowitsch         PetscCall(PetscFree(alpha));
465306fc46c8SMatthew G. Knepley         incall = PETSC_FALSE;
465406fc46c8SMatthew G. Knepley       }
465534b4d3a8SMatthew G. Knepley       /* Adaptively refine the initial grid */
4656b2588ea6SMatthew G. Knepley       num  = 1;
46579566063dSJacob Faibussowitsch       PetscCall(PetscOptionsGetInt(NULL, ((PetscObject) snes)->prefix, "-snes_adapt_initial", &num, &flg));
465834b4d3a8SMatthew G. Knepley       if (flg) {
465934b4d3a8SMatthew G. Knepley         DMAdaptor adaptor;
466034b4d3a8SMatthew G. Knepley 
466134b4d3a8SMatthew G. Knepley         incall = PETSC_TRUE;
46629566063dSJacob Faibussowitsch         PetscCall(DMAdaptorCreate(PetscObjectComm((PetscObject)snes), &adaptor));
46639566063dSJacob Faibussowitsch         PetscCall(DMAdaptorSetSolver(adaptor, snes));
46649566063dSJacob Faibussowitsch         PetscCall(DMAdaptorSetSequenceLength(adaptor, num));
46659566063dSJacob Faibussowitsch         PetscCall(DMAdaptorSetFromOptions(adaptor));
46669566063dSJacob Faibussowitsch         PetscCall(DMAdaptorSetUp(adaptor));
46679566063dSJacob Faibussowitsch         PetscCall(DMAdaptorAdapt(adaptor, x, DM_ADAPTATION_INITIAL, &dm, &x));
46689566063dSJacob Faibussowitsch         PetscCall(DMAdaptorDestroy(&adaptor));
466934b4d3a8SMatthew G. Knepley         incall = PETSC_FALSE;
467034b4d3a8SMatthew G. Knepley       }
46717c88af5aSMatthew G. Knepley       /* Use grid sequencing to adapt */
46727c88af5aSMatthew G. Knepley       num  = 0;
46739566063dSJacob Faibussowitsch       PetscCall(PetscOptionsGetInt(NULL, ((PetscObject) snes)->prefix, "-snes_adapt_sequence", &num, NULL));
46747c88af5aSMatthew G. Knepley       if (num) {
46757c88af5aSMatthew G. Knepley         DMAdaptor adaptor;
46767c88af5aSMatthew G. Knepley 
46777c88af5aSMatthew G. Knepley         incall = PETSC_TRUE;
46789566063dSJacob Faibussowitsch         PetscCall(DMAdaptorCreate(PetscObjectComm((PetscObject)snes), &adaptor));
46799566063dSJacob Faibussowitsch         PetscCall(DMAdaptorSetSolver(adaptor, snes));
46809566063dSJacob Faibussowitsch         PetscCall(DMAdaptorSetSequenceLength(adaptor, num));
46819566063dSJacob Faibussowitsch         PetscCall(DMAdaptorSetFromOptions(adaptor));
46829566063dSJacob Faibussowitsch         PetscCall(DMAdaptorSetUp(adaptor));
46839566063dSJacob Faibussowitsch         PetscCall(DMAdaptorAdapt(adaptor, x, DM_ADAPTATION_SEQUENTIAL, &dm, &x));
46849566063dSJacob Faibussowitsch         PetscCall(DMAdaptorDestroy(&adaptor));
46857c88af5aSMatthew G. Knepley         incall = PETSC_FALSE;
46867c88af5aSMatthew G. Knepley       }
468706fc46c8SMatthew G. Knepley     }
468806fc46c8SMatthew G. Knepley   }
468941e867a5SStefano Zampini   if (!x) { x = snes->vec_sol; }
4690caa4e7f2SJed Brown   if (!x) {
46919566063dSJacob Faibussowitsch     PetscCall(SNESGetDM(snes,&dm));
46929566063dSJacob Faibussowitsch     PetscCall(DMCreateGlobalVector(dm,&xcreated));
4693a69afd8bSBarry Smith     x    = xcreated;
4694a69afd8bSBarry Smith   }
46959566063dSJacob Faibussowitsch   PetscCall(SNESViewFromOptions(snes,NULL,"-snes_view_pre"));
4696f05ece33SBarry Smith 
46979566063dSJacob Faibussowitsch   for (grid=0; grid<snes->gridsequence; grid++) PetscCall(PetscViewerASCIIPushTab(PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)snes))));
4698efd51863SBarry Smith   for (grid=0; grid<snes->gridsequence+1; grid++) {
4699efd51863SBarry Smith 
470085385478SLisandro Dalcin     /* set solution vector */
47019566063dSJacob Faibussowitsch     if (!grid) PetscCall(PetscObjectReference((PetscObject)x));
47029566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&snes->vec_sol));
470385385478SLisandro Dalcin     snes->vec_sol = x;
47049566063dSJacob Faibussowitsch     PetscCall(SNESGetDM(snes,&dm));
4705caa4e7f2SJed Brown 
4706caa4e7f2SJed Brown     /* set affine vector if provided */
47079566063dSJacob Faibussowitsch     if (b) PetscCall(PetscObjectReference((PetscObject)b));
47089566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&snes->vec_rhs));
470985385478SLisandro Dalcin     snes->vec_rhs = b;
471085385478SLisandro Dalcin 
47115f80ce2aSJacob 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");
47125f80ce2aSJacob Faibussowitsch     PetscCheck(snes->vec_func != snes->vec_sol,PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"Solution vector cannot be function vector");
47135f80ce2aSJacob Faibussowitsch     PetscCheck(snes->vec_rhs  != snes->vec_sol,PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"Solution vector cannot be right hand side vector");
4714154060b5SMatthew G. Knepley     if (!snes->vec_sol_update /* && snes->vec_sol */) {
47159566063dSJacob Faibussowitsch       PetscCall(VecDuplicate(snes->vec_sol,&snes->vec_sol_update));
47169566063dSJacob Faibussowitsch       PetscCall(PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->vec_sol_update));
4717154060b5SMatthew G. Knepley     }
47189566063dSJacob Faibussowitsch     PetscCall(DMShellSetGlobalVector(dm,snes->vec_sol));
47199566063dSJacob Faibussowitsch     PetscCall(SNESSetUp(snes));
47203f149594SLisandro Dalcin 
47217eee914bSBarry Smith     if (!grid) {
47221baa6e33SBarry Smith       if (snes->ops->computeinitialguess) PetscCall((*snes->ops->computeinitialguess)(snes,snes->vec_sol,snes->initialguessP));
4723dd568438SSatish Balay     }
4724d25893d9SBarry Smith 
4725abc0a331SBarry Smith     if (snes->conv_hist_reset) snes->conv_hist_len = 0;
4726971e163fSPeter Brune     if (snes->counters_reset) {snes->nfuncs = 0; snes->linear_its = 0; snes->numFailures = 0;}
4727d5e45103SBarry Smith 
47289566063dSJacob Faibussowitsch     PetscCall(PetscLogEventBegin(SNES_Solve,snes,0,0,0));
47299566063dSJacob Faibussowitsch     PetscCall((*snes->ops->solve)(snes));
47309566063dSJacob Faibussowitsch     PetscCall(PetscLogEventEnd(SNES_Solve,snes,0,0,0));
47315f80ce2aSJacob Faibussowitsch     PetscCheck(snes->reason,PETSC_COMM_SELF,PETSC_ERR_PLIB,"Internal error, solver returned without setting converged reason");
4732422a814eSBarry Smith     snes->domainerror = PETSC_FALSE; /* clear the flag if it has been set */
47333f149594SLisandro Dalcin 
473437ec4e1aSPeter Brune     if (snes->lagjac_persist) snes->jac_iter += snes->iter;
473537ec4e1aSPeter Brune     if (snes->lagpre_persist) snes->pre_iter += snes->iter;
473637ec4e1aSPeter Brune 
47379566063dSJacob Faibussowitsch     PetscCall(PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_test_local_min",NULL,NULL,&flg));
47389566063dSJacob Faibussowitsch     if (flg && !PetscPreLoadingOn) PetscCall(SNESTestLocalMin(snes));
4739c4421ceaSFande Kong     /* Call converged reason views. This may involve user-provided viewers as well */
47409566063dSJacob Faibussowitsch     PetscCall(SNESConvergedReasonViewFromOptions(snes));
47415968eb51SBarry Smith 
47425f80ce2aSJacob Faibussowitsch     if (snes->errorifnotconverged) PetscCheck(snes->reason >= 0,PetscObjectComm((PetscObject)snes),PETSC_ERR_NOT_CONVERGED,"SNESSolve has not converged");
47439c8e83a9SBarry Smith     if (snes->reason < 0) break;
4744efd51863SBarry Smith     if (grid < snes->gridsequence) {
4745efd51863SBarry Smith       DM  fine;
4746efd51863SBarry Smith       Vec xnew;
4747efd51863SBarry Smith       Mat interp;
4748efd51863SBarry Smith 
47499566063dSJacob Faibussowitsch       PetscCall(DMRefine(snes->dm,PetscObjectComm((PetscObject)snes),&fine));
47505f80ce2aSJacob Faibussowitsch       PetscCheck(fine,PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_INCOMP,"DMRefine() did not perform any refinement, cannot continue grid sequencing");
47519566063dSJacob Faibussowitsch       PetscCall(DMCreateInterpolation(snes->dm,fine,&interp,NULL));
47529566063dSJacob Faibussowitsch       PetscCall(DMCreateGlobalVector(fine,&xnew));
47539566063dSJacob Faibussowitsch       PetscCall(MatInterpolate(interp,x,xnew));
47549566063dSJacob Faibussowitsch       PetscCall(DMInterpolate(snes->dm,interp,fine));
47559566063dSJacob Faibussowitsch       PetscCall(MatDestroy(&interp));
4756efd51863SBarry Smith       x    = xnew;
4757efd51863SBarry Smith 
47589566063dSJacob Faibussowitsch       PetscCall(SNESReset(snes));
47599566063dSJacob Faibussowitsch       PetscCall(SNESSetDM(snes,fine));
47609566063dSJacob Faibussowitsch       PetscCall(SNESResetFromOptions(snes));
47619566063dSJacob Faibussowitsch       PetscCall(DMDestroy(&fine));
47629566063dSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPopTab(PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)snes))));
4763efd51863SBarry Smith     }
4764efd51863SBarry Smith   }
47659566063dSJacob Faibussowitsch   PetscCall(SNESViewFromOptions(snes,NULL,"-snes_view"));
47669566063dSJacob Faibussowitsch   PetscCall(VecViewFromOptions(snes->vec_sol,(PetscObject)snes,"-snes_view_solution"));
47679566063dSJacob Faibussowitsch   PetscCall(DMMonitor(snes->dm));
47689566063dSJacob Faibussowitsch   PetscCall(SNESMonitorPauseFinal_Internal(snes));
47693f7e2da0SPeter Brune 
47709566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&xcreated));
47719566063dSJacob Faibussowitsch   PetscCall(PetscObjectSAWsBlock((PetscObject)snes));
47723a40ed3dSBarry Smith   PetscFunctionReturn(0);
47739b94acceSBarry Smith }
47749b94acceSBarry Smith 
47759b94acceSBarry Smith /* --------- Internal routines for SNES Package --------- */
47769b94acceSBarry Smith 
477782bf6240SBarry Smith /*@C
47784b0e389bSBarry Smith    SNESSetType - Sets the method for the nonlinear solver.
47799b94acceSBarry Smith 
4780fee21e36SBarry Smith    Collective on SNES
4781fee21e36SBarry Smith 
4782c7afd0dbSLois Curfman McInnes    Input Parameters:
4783c7afd0dbSLois Curfman McInnes +  snes - the SNES context
4784454a90a3SBarry Smith -  type - a known method
4785c7afd0dbSLois Curfman McInnes 
4786c7afd0dbSLois Curfman McInnes    Options Database Key:
4787454a90a3SBarry Smith .  -snes_type <type> - Sets the method; use -help for a list
478804d7464bSBarry Smith    of available methods (for instance, newtonls or newtontr)
4789ae12b187SLois Curfman McInnes 
47909b94acceSBarry Smith    Notes:
4791e090d566SSatish Balay    See "petsc/include/petscsnes.h" for available methods (for instance)
479204d7464bSBarry Smith +    SNESNEWTONLS - Newton's method with line search
4793c7afd0dbSLois Curfman McInnes      (systems of nonlinear equations)
4794a2b725a8SWilliam Gropp -    SNESNEWTONTR - Newton's method with trust region
4795c7afd0dbSLois Curfman McInnes      (systems of nonlinear equations)
47969b94acceSBarry Smith 
4797ae12b187SLois Curfman McInnes   Normally, it is best to use the SNESSetFromOptions() command and then
4798ae12b187SLois Curfman McInnes   set the SNES solver type from the options database rather than by using
4799ae12b187SLois Curfman McInnes   this routine.  Using the options database provides the user with
4800ae12b187SLois Curfman McInnes   maximum flexibility in evaluating the many nonlinear solvers.
4801ae12b187SLois Curfman McInnes   The SNESSetType() routine is provided for those situations where it
4802ae12b187SLois Curfman McInnes   is necessary to set the nonlinear solver independently of the command
4803ae12b187SLois Curfman McInnes   line or options database.  This might be the case, for example, when
4804ae12b187SLois Curfman McInnes   the choice of solver changes during the execution of the program,
4805ae12b187SLois Curfman McInnes   and the user's application is taking responsibility for choosing the
4806b0a32e0cSBarry Smith   appropriate method.
480736851e7fSLois Curfman McInnes 
480895452b02SPatrick Sanan     Developer Notes:
480995452b02SPatrick Sanan     SNESRegister() adds a constructor for a new SNESType to SNESList, SNESSetType() locates
48108f6c3df8SBarry Smith     the constructor in that list and calls it to create the spexific object.
48118f6c3df8SBarry Smith 
481236851e7fSLois Curfman McInnes   Level: intermediate
4813a703fe33SLois Curfman McInnes 
4814db781477SPatrick Sanan .seealso: `SNESType`, `SNESCreate()`, `SNESDestroy()`, `SNESGetType()`, `SNESSetFromOptions()`
4815435da068SBarry Smith 
48169b94acceSBarry Smith @*/
481719fd82e9SBarry Smith PetscErrorCode  SNESSetType(SNES snes,SNESType type)
48189b94acceSBarry Smith {
4819ace3abfcSBarry Smith   PetscBool      match;
48205f80ce2aSJacob Faibussowitsch   PetscErrorCode (*r)(SNES);
48213a40ed3dSBarry Smith 
48223a40ed3dSBarry Smith   PetscFunctionBegin;
48230700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
48244482741eSBarry Smith   PetscValidCharPointer(type,2);
482582bf6240SBarry Smith 
48269566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)snes,type,&match));
48270f5bd95cSBarry Smith   if (match) PetscFunctionReturn(0);
482892ff6ae8SBarry Smith 
48299566063dSJacob Faibussowitsch   PetscCall(PetscFunctionListFind(SNESList,type,&r));
48305f80ce2aSJacob Faibussowitsch   PetscCheck(r,PETSC_COMM_SELF,PETSC_ERR_ARG_UNKNOWN_TYPE,"Unable to find requested SNES type %s",type);
483175396ef9SLisandro Dalcin   /* Destroy the previous private SNES context */
4832a958fbfcSStefano Zampini   if (snes->ops->destroy) PetscCall((*snes->ops->destroy)(snes));
483375396ef9SLisandro Dalcin   /* Reinitialize function pointers in SNESOps structure */
48349e5d0892SLisandro Dalcin   snes->ops->setup          = NULL;
48359e5d0892SLisandro Dalcin   snes->ops->solve          = NULL;
48369e5d0892SLisandro Dalcin   snes->ops->view           = NULL;
48379e5d0892SLisandro Dalcin   snes->ops->setfromoptions = NULL;
48389e5d0892SLisandro Dalcin   snes->ops->destroy        = NULL;
48397fe760d5SStefano Zampini 
48407fe760d5SStefano Zampini   /* It may happen the user has customized the line search before calling SNESSetType */
48419566063dSJacob Faibussowitsch   if (((PetscObject)snes)->type_name) PetscCall(SNESLineSearchDestroy(&snes->linesearch));
48427fe760d5SStefano Zampini 
484375396ef9SLisandro Dalcin   /* Call the SNESCreate_XXX routine for this particular Nonlinear solver */
484475396ef9SLisandro Dalcin   snes->setupcalled = PETSC_FALSE;
4845f5af7f23SKarl Rupp 
48469566063dSJacob Faibussowitsch   PetscCall(PetscObjectChangeTypeName((PetscObject)snes,type));
48479566063dSJacob Faibussowitsch   PetscCall((*r)(snes));
48483a40ed3dSBarry Smith   PetscFunctionReturn(0);
48499b94acceSBarry Smith }
48509b94acceSBarry Smith 
48519b94acceSBarry Smith /*@C
48529a28b0a6SLois Curfman McInnes    SNESGetType - Gets the SNES method type and name (as a string).
48539b94acceSBarry Smith 
4854c7afd0dbSLois Curfman McInnes    Not Collective
4855c7afd0dbSLois Curfman McInnes 
48569b94acceSBarry Smith    Input Parameter:
48574b0e389bSBarry Smith .  snes - nonlinear solver context
48589b94acceSBarry Smith 
48599b94acceSBarry Smith    Output Parameter:
48603a7fca6bSBarry Smith .  type - SNES method (a character string)
48619b94acceSBarry Smith 
486236851e7fSLois Curfman McInnes    Level: intermediate
486336851e7fSLois Curfman McInnes 
48649b94acceSBarry Smith @*/
486519fd82e9SBarry Smith PetscErrorCode  SNESGetType(SNES snes,SNESType *type)
48669b94acceSBarry Smith {
48673a40ed3dSBarry Smith   PetscFunctionBegin;
48680700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
48694482741eSBarry Smith   PetscValidPointer(type,2);
48707adad957SLisandro Dalcin   *type = ((PetscObject)snes)->type_name;
48713a40ed3dSBarry Smith   PetscFunctionReturn(0);
48729b94acceSBarry Smith }
48739b94acceSBarry Smith 
48743cd8a7caSMatthew G. Knepley /*@
48753cd8a7caSMatthew G. Knepley   SNESSetSolution - Sets the solution vector for use by the SNES routines.
48763cd8a7caSMatthew G. Knepley 
4877d083f849SBarry Smith   Logically Collective on SNES
48783cd8a7caSMatthew G. Knepley 
48793cd8a7caSMatthew G. Knepley   Input Parameters:
48803cd8a7caSMatthew G. Knepley + snes - the SNES context obtained from SNESCreate()
48813cd8a7caSMatthew G. Knepley - u    - the solution vector
48823cd8a7caSMatthew G. Knepley 
48833cd8a7caSMatthew G. Knepley   Level: beginner
48843cd8a7caSMatthew G. Knepley 
48853cd8a7caSMatthew G. Knepley @*/
48863cd8a7caSMatthew G. Knepley PetscErrorCode SNESSetSolution(SNES snes, Vec u)
48873cd8a7caSMatthew G. Knepley {
48883cd8a7caSMatthew G. Knepley   DM             dm;
48893cd8a7caSMatthew G. Knepley 
48903cd8a7caSMatthew G. Knepley   PetscFunctionBegin;
48913cd8a7caSMatthew G. Knepley   PetscValidHeaderSpecific(snes, SNES_CLASSID, 1);
48923cd8a7caSMatthew G. Knepley   PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
48939566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject) u));
48949566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&snes->vec_sol));
48953cd8a7caSMatthew G. Knepley 
48963cd8a7caSMatthew G. Knepley   snes->vec_sol = u;
48973cd8a7caSMatthew G. Knepley 
48989566063dSJacob Faibussowitsch   PetscCall(SNESGetDM(snes, &dm));
48999566063dSJacob Faibussowitsch   PetscCall(DMShellSetGlobalVector(dm, u));
49003cd8a7caSMatthew G. Knepley   PetscFunctionReturn(0);
49013cd8a7caSMatthew G. Knepley }
49023cd8a7caSMatthew G. Knepley 
490352baeb72SSatish Balay /*@
49049b94acceSBarry Smith    SNESGetSolution - Returns the vector where the approximate solution is
4905c0df2a02SJed Brown    stored. This is the fine grid solution when using SNESSetGridSequence().
49069b94acceSBarry Smith 
4907c7afd0dbSLois Curfman McInnes    Not Collective, but Vec is parallel if SNES is parallel
4908c7afd0dbSLois Curfman McInnes 
49099b94acceSBarry Smith    Input Parameter:
49109b94acceSBarry Smith .  snes - the SNES context
49119b94acceSBarry Smith 
49129b94acceSBarry Smith    Output Parameter:
49139b94acceSBarry Smith .  x - the solution
49149b94acceSBarry Smith 
491570e92668SMatthew Knepley    Level: intermediate
491636851e7fSLois Curfman McInnes 
4917db781477SPatrick Sanan .seealso: `SNESGetSolutionUpdate()`, `SNESGetFunction()`
49189b94acceSBarry Smith @*/
49197087cfbeSBarry Smith PetscErrorCode  SNESGetSolution(SNES snes,Vec *x)
49209b94acceSBarry Smith {
49213a40ed3dSBarry Smith   PetscFunctionBegin;
49220700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
49234482741eSBarry Smith   PetscValidPointer(x,2);
492485385478SLisandro Dalcin   *x = snes->vec_sol;
492570e92668SMatthew Knepley   PetscFunctionReturn(0);
492670e92668SMatthew Knepley }
492770e92668SMatthew Knepley 
492852baeb72SSatish Balay /*@
49299b94acceSBarry Smith    SNESGetSolutionUpdate - Returns the vector where the solution update is
49309b94acceSBarry Smith    stored.
49319b94acceSBarry Smith 
4932c7afd0dbSLois Curfman McInnes    Not Collective, but Vec is parallel if SNES is parallel
4933c7afd0dbSLois Curfman McInnes 
49349b94acceSBarry Smith    Input Parameter:
49359b94acceSBarry Smith .  snes - the SNES context
49369b94acceSBarry Smith 
49379b94acceSBarry Smith    Output Parameter:
49389b94acceSBarry Smith .  x - the solution update
49399b94acceSBarry Smith 
494036851e7fSLois Curfman McInnes    Level: advanced
494136851e7fSLois Curfman McInnes 
4942db781477SPatrick Sanan .seealso: `SNESGetSolution()`, `SNESGetFunction()`
49439b94acceSBarry Smith @*/
49447087cfbeSBarry Smith PetscErrorCode  SNESGetSolutionUpdate(SNES snes,Vec *x)
49459b94acceSBarry Smith {
49463a40ed3dSBarry Smith   PetscFunctionBegin;
49470700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
49484482741eSBarry Smith   PetscValidPointer(x,2);
494985385478SLisandro Dalcin   *x = snes->vec_sol_update;
49503a40ed3dSBarry Smith   PetscFunctionReturn(0);
49519b94acceSBarry Smith }
49529b94acceSBarry Smith 
49539b94acceSBarry Smith /*@C
49543638b69dSLois Curfman McInnes    SNESGetFunction - Returns the vector where the function is stored.
49559b94acceSBarry Smith 
4956a63bb30eSJed Brown    Not Collective, but Vec is parallel if SNES is parallel. Collective if Vec is requested, but has not been created yet.
4957c7afd0dbSLois Curfman McInnes 
49589b94acceSBarry Smith    Input Parameter:
49599b94acceSBarry Smith .  snes - the SNES context
49609b94acceSBarry Smith 
4961d8d19677SJose E. Roman    Output Parameters:
49620298fd71SBarry Smith +  r - the vector that is used to store residuals (or NULL if you don't want it)
4963f8b49ee9SBarry Smith .  f - the function (or NULL if you don't want it); see SNESFunction for calling sequence details
49640298fd71SBarry Smith -  ctx - the function context (or NULL if you don't want it)
49659b94acceSBarry Smith 
496636851e7fSLois Curfman McInnes    Level: advanced
496736851e7fSLois Curfman McInnes 
496804edfde5SBarry Smith     Notes: The vector r DOES NOT, in general contain the current value of the SNES nonlinear function
496904edfde5SBarry Smith 
4970db781477SPatrick Sanan .seealso: `SNESSetFunction()`, `SNESGetSolution()`, `SNESFunction`
49719b94acceSBarry Smith @*/
4972f8b49ee9SBarry Smith PetscErrorCode  SNESGetFunction(SNES snes,Vec *r,PetscErrorCode (**f)(SNES,Vec,Vec,void*),void **ctx)
49739b94acceSBarry Smith {
49746cab3a1bSJed Brown   DM             dm;
4975a63bb30eSJed Brown 
49763a40ed3dSBarry Smith   PetscFunctionBegin;
49770700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
4978a63bb30eSJed Brown   if (r) {
4979a63bb30eSJed Brown     if (!snes->vec_func) {
4980a63bb30eSJed Brown       if (snes->vec_rhs) {
49819566063dSJacob Faibussowitsch         PetscCall(VecDuplicate(snes->vec_rhs,&snes->vec_func));
4982a63bb30eSJed Brown       } else if (snes->vec_sol) {
49839566063dSJacob Faibussowitsch         PetscCall(VecDuplicate(snes->vec_sol,&snes->vec_func));
4984a63bb30eSJed Brown       } else if (snes->dm) {
49859566063dSJacob Faibussowitsch         PetscCall(DMCreateGlobalVector(snes->dm,&snes->vec_func));
4986a63bb30eSJed Brown       }
4987a63bb30eSJed Brown     }
4988a63bb30eSJed Brown     *r = snes->vec_func;
4989a63bb30eSJed Brown   }
49909566063dSJacob Faibussowitsch   PetscCall(SNESGetDM(snes,&dm));
49919566063dSJacob Faibussowitsch   PetscCall(DMSNESGetFunction(dm,f,ctx));
49923a40ed3dSBarry Smith   PetscFunctionReturn(0);
49939b94acceSBarry Smith }
49949b94acceSBarry Smith 
4995c79ef259SPeter Brune /*@C
4996be95d8f1SBarry Smith    SNESGetNGS - Returns the NGS function and context.
4997c79ef259SPeter Brune 
4998c79ef259SPeter Brune    Input Parameter:
4999c79ef259SPeter Brune .  snes - the SNES context
5000c79ef259SPeter Brune 
5001d8d19677SJose E. Roman    Output Parameters:
5002be95d8f1SBarry Smith +  f - the function (or NULL) see SNESNGSFunction for details
50030298fd71SBarry Smith -  ctx    - the function context (or NULL)
5004c79ef259SPeter Brune 
5005c79ef259SPeter Brune    Level: advanced
5006c79ef259SPeter Brune 
5007db781477SPatrick Sanan .seealso: `SNESSetNGS()`, `SNESGetFunction()`
5008c79ef259SPeter Brune @*/
5009c79ef259SPeter Brune 
5010be95d8f1SBarry Smith PetscErrorCode SNESGetNGS (SNES snes, PetscErrorCode (**f)(SNES, Vec, Vec, void*), void ** ctx)
5011646217ecSPeter Brune {
50126cab3a1bSJed Brown   DM             dm;
50136cab3a1bSJed Brown 
5014646217ecSPeter Brune   PetscFunctionBegin;
5015646217ecSPeter Brune   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
50169566063dSJacob Faibussowitsch   PetscCall(SNESGetDM(snes,&dm));
50179566063dSJacob Faibussowitsch   PetscCall(DMSNESGetNGS(dm,f,ctx));
5018646217ecSPeter Brune   PetscFunctionReturn(0);
5019646217ecSPeter Brune }
5020646217ecSPeter Brune 
50213c7409f5SSatish Balay /*@C
50223c7409f5SSatish Balay    SNESSetOptionsPrefix - Sets the prefix used for searching for all
5023d850072dSLois Curfman McInnes    SNES options in the database.
50243c7409f5SSatish Balay 
50253f9fe445SBarry Smith    Logically Collective on SNES
5026fee21e36SBarry Smith 
5027d8d19677SJose E. Roman    Input Parameters:
5028c7afd0dbSLois Curfman McInnes +  snes - the SNES context
5029c7afd0dbSLois Curfman McInnes -  prefix - the prefix to prepend to all option names
5030c7afd0dbSLois Curfman McInnes 
5031d850072dSLois Curfman McInnes    Notes:
5032a83b1b31SSatish Balay    A hyphen (-) must NOT be given at the beginning of the prefix name.
5033c7afd0dbSLois Curfman McInnes    The first character of all runtime options is AUTOMATICALLY the hyphen.
5034d850072dSLois Curfman McInnes 
503536851e7fSLois Curfman McInnes    Level: advanced
503636851e7fSLois Curfman McInnes 
5037db781477SPatrick Sanan .seealso: `SNESSetFromOptions()`
50383c7409f5SSatish Balay @*/
50397087cfbeSBarry Smith PetscErrorCode  SNESSetOptionsPrefix(SNES snes,const char prefix[])
50403c7409f5SSatish Balay {
50413a40ed3dSBarry Smith   PetscFunctionBegin;
50420700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
50439566063dSJacob Faibussowitsch   PetscCall(PetscObjectSetOptionsPrefix((PetscObject)snes,prefix));
50449566063dSJacob Faibussowitsch   if (!snes->ksp) PetscCall(SNESGetKSP(snes,&snes->ksp));
504535f5d045SPeter Brune   if (snes->linesearch) {
50469566063dSJacob Faibussowitsch     PetscCall(SNESGetLineSearch(snes,&snes->linesearch));
50479566063dSJacob Faibussowitsch     PetscCall(PetscObjectSetOptionsPrefix((PetscObject)snes->linesearch,prefix));
504835f5d045SPeter Brune   }
50499566063dSJacob Faibussowitsch   PetscCall(KSPSetOptionsPrefix(snes->ksp,prefix));
50503a40ed3dSBarry Smith   PetscFunctionReturn(0);
50513c7409f5SSatish Balay }
50523c7409f5SSatish Balay 
50533c7409f5SSatish Balay /*@C
5054f525115eSLois Curfman McInnes    SNESAppendOptionsPrefix - Appends to the prefix used for searching for all
5055d850072dSLois Curfman McInnes    SNES options in the database.
50563c7409f5SSatish Balay 
50573f9fe445SBarry Smith    Logically Collective on SNES
5058fee21e36SBarry Smith 
5059c7afd0dbSLois Curfman McInnes    Input Parameters:
5060c7afd0dbSLois Curfman McInnes +  snes - the SNES context
5061c7afd0dbSLois Curfman McInnes -  prefix - the prefix to prepend to all option names
5062c7afd0dbSLois Curfman McInnes 
5063d850072dSLois Curfman McInnes    Notes:
5064a83b1b31SSatish Balay    A hyphen (-) must NOT be given at the beginning of the prefix name.
5065c7afd0dbSLois Curfman McInnes    The first character of all runtime options is AUTOMATICALLY the hyphen.
5066d850072dSLois Curfman McInnes 
506736851e7fSLois Curfman McInnes    Level: advanced
506836851e7fSLois Curfman McInnes 
5069db781477SPatrick Sanan .seealso: `SNESGetOptionsPrefix()`
50703c7409f5SSatish Balay @*/
50717087cfbeSBarry Smith PetscErrorCode  SNESAppendOptionsPrefix(SNES snes,const char prefix[])
50723c7409f5SSatish Balay {
50733a40ed3dSBarry Smith   PetscFunctionBegin;
50740700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
50759566063dSJacob Faibussowitsch   PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)snes,prefix));
50769566063dSJacob Faibussowitsch   if (!snes->ksp) PetscCall(SNESGetKSP(snes,&snes->ksp));
507735f5d045SPeter Brune   if (snes->linesearch) {
50789566063dSJacob Faibussowitsch     PetscCall(SNESGetLineSearch(snes,&snes->linesearch));
50799566063dSJacob Faibussowitsch     PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)snes->linesearch,prefix));
508035f5d045SPeter Brune   }
50819566063dSJacob Faibussowitsch   PetscCall(KSPAppendOptionsPrefix(snes->ksp,prefix));
50823a40ed3dSBarry Smith   PetscFunctionReturn(0);
50833c7409f5SSatish Balay }
50843c7409f5SSatish Balay 
50859ab63eb5SSatish Balay /*@C
50863c7409f5SSatish Balay    SNESGetOptionsPrefix - Sets the prefix used for searching for all
50873c7409f5SSatish Balay    SNES options in the database.
50883c7409f5SSatish Balay 
5089c7afd0dbSLois Curfman McInnes    Not Collective
5090c7afd0dbSLois Curfman McInnes 
50913c7409f5SSatish Balay    Input Parameter:
50923c7409f5SSatish Balay .  snes - the SNES context
50933c7409f5SSatish Balay 
50943c7409f5SSatish Balay    Output Parameter:
50953c7409f5SSatish Balay .  prefix - pointer to the prefix string used
50963c7409f5SSatish Balay 
509795452b02SPatrick Sanan    Notes:
509895452b02SPatrick Sanan     On the fortran side, the user should pass in a string 'prefix' of
50999ab63eb5SSatish Balay    sufficient length to hold the prefix.
51009ab63eb5SSatish Balay 
510136851e7fSLois Curfman McInnes    Level: advanced
510236851e7fSLois Curfman McInnes 
5103db781477SPatrick Sanan .seealso: `SNESAppendOptionsPrefix()`
51043c7409f5SSatish Balay @*/
51057087cfbeSBarry Smith PetscErrorCode  SNESGetOptionsPrefix(SNES snes,const char *prefix[])
51063c7409f5SSatish Balay {
51073a40ed3dSBarry Smith   PetscFunctionBegin;
51080700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
51099566063dSJacob Faibussowitsch   PetscCall(PetscObjectGetOptionsPrefix((PetscObject)snes,prefix));
51103a40ed3dSBarry Smith   PetscFunctionReturn(0);
51113c7409f5SSatish Balay }
51123c7409f5SSatish Balay 
51133cea93caSBarry Smith /*@C
51141c84c290SBarry Smith   SNESRegister - Adds a method to the nonlinear solver package.
51151c84c290SBarry Smith 
51161c84c290SBarry Smith    Not collective
51171c84c290SBarry Smith 
51181c84c290SBarry Smith    Input Parameters:
51191c84c290SBarry Smith +  name_solver - name of a new user-defined solver
51201c84c290SBarry Smith -  routine_create - routine to create method context
51211c84c290SBarry Smith 
51221c84c290SBarry Smith    Notes:
51231c84c290SBarry Smith    SNESRegister() may be called multiple times to add several user-defined solvers.
51241c84c290SBarry Smith 
51251c84c290SBarry Smith    Sample usage:
51261c84c290SBarry Smith .vb
5127bdf89e91SBarry Smith    SNESRegister("my_solver",MySolverCreate);
51281c84c290SBarry Smith .ve
51291c84c290SBarry Smith 
51301c84c290SBarry Smith    Then, your solver can be chosen with the procedural interface via
51311c84c290SBarry Smith $     SNESSetType(snes,"my_solver")
51321c84c290SBarry Smith    or at runtime via the option
51331c84c290SBarry Smith $     -snes_type my_solver
51341c84c290SBarry Smith 
51351c84c290SBarry Smith    Level: advanced
51361c84c290SBarry Smith 
51371c84c290SBarry Smith     Note: If your function is not being put into a shared library then use SNESRegister() instead
51381c84c290SBarry Smith 
5139db781477SPatrick Sanan .seealso: `SNESRegisterAll()`, `SNESRegisterDestroy()`
51403cea93caSBarry Smith 
51417f6c08e0SMatthew Knepley   Level: advanced
51423cea93caSBarry Smith @*/
5143bdf89e91SBarry Smith PetscErrorCode  SNESRegister(const char sname[],PetscErrorCode (*function)(SNES))
5144b2002411SLois Curfman McInnes {
5145b2002411SLois Curfman McInnes   PetscFunctionBegin;
51469566063dSJacob Faibussowitsch   PetscCall(SNESInitializePackage());
51479566063dSJacob Faibussowitsch   PetscCall(PetscFunctionListAdd(&SNESList,sname,function));
5148b2002411SLois Curfman McInnes   PetscFunctionReturn(0);
5149b2002411SLois Curfman McInnes }
5150da9b6338SBarry Smith 
51517087cfbeSBarry Smith PetscErrorCode  SNESTestLocalMin(SNES snes)
5152da9b6338SBarry Smith {
515377431f27SBarry Smith   PetscInt       N,i,j;
5154da9b6338SBarry Smith   Vec            u,uh,fh;
5155da9b6338SBarry Smith   PetscScalar    value;
5156da9b6338SBarry Smith   PetscReal      norm;
5157da9b6338SBarry Smith 
5158da9b6338SBarry Smith   PetscFunctionBegin;
51599566063dSJacob Faibussowitsch   PetscCall(SNESGetSolution(snes,&u));
51609566063dSJacob Faibussowitsch   PetscCall(VecDuplicate(u,&uh));
51619566063dSJacob Faibussowitsch   PetscCall(VecDuplicate(u,&fh));
5162da9b6338SBarry Smith 
5163da9b6338SBarry Smith   /* currently only works for sequential */
51649566063dSJacob Faibussowitsch   PetscCall(PetscPrintf(PetscObjectComm((PetscObject)snes),"Testing FormFunction() for local min\n"));
51659566063dSJacob Faibussowitsch   PetscCall(VecGetSize(u,&N));
5166da9b6338SBarry Smith   for (i=0; i<N; i++) {
51679566063dSJacob Faibussowitsch     PetscCall(VecCopy(u,uh));
516863a3b9bcSJacob Faibussowitsch     PetscCall(PetscPrintf(PetscObjectComm((PetscObject)snes),"i = %" PetscInt_FMT "\n",i));
5169da9b6338SBarry Smith     for (j=-10; j<11; j++) {
51708b49ba18SBarry Smith       value = PetscSign(j)*PetscExpReal(PetscAbs(j)-10.0);
51719566063dSJacob Faibussowitsch       PetscCall(VecSetValue(uh,i,value,ADD_VALUES));
51729566063dSJacob Faibussowitsch       PetscCall(SNESComputeFunction(snes,uh,fh));
51739566063dSJacob Faibussowitsch       PetscCall(VecNorm(fh,NORM_2,&norm));
517463a3b9bcSJacob Faibussowitsch       PetscCall(PetscPrintf(PetscObjectComm((PetscObject)snes),"       j norm %" PetscInt_FMT " %18.16e\n",j,(double)norm));
5175da9b6338SBarry Smith       value = -value;
51769566063dSJacob Faibussowitsch       PetscCall(VecSetValue(uh,i,value,ADD_VALUES));
5177da9b6338SBarry Smith     }
5178da9b6338SBarry Smith   }
51799566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&uh));
51809566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&fh));
5181da9b6338SBarry Smith   PetscFunctionReturn(0);
5182da9b6338SBarry Smith }
518371f87433Sdalcinl 
518471f87433Sdalcinl /*@
5185fa9f3622SBarry Smith    SNESKSPSetUseEW - Sets SNES use Eisenstat-Walker method for
518671f87433Sdalcinl    computing relative tolerance for linear solvers within an inexact
518771f87433Sdalcinl    Newton method.
518871f87433Sdalcinl 
51893f9fe445SBarry Smith    Logically Collective on SNES
519071f87433Sdalcinl 
519171f87433Sdalcinl    Input Parameters:
519271f87433Sdalcinl +  snes - SNES context
519371f87433Sdalcinl -  flag - PETSC_TRUE or PETSC_FALSE
519471f87433Sdalcinl 
519564ba62caSBarry Smith     Options Database:
519664ba62caSBarry Smith +  -snes_ksp_ew - use Eisenstat-Walker method for determining linear system convergence
519764ba62caSBarry Smith .  -snes_ksp_ew_version ver - version of  Eisenstat-Walker method
519864ba62caSBarry Smith .  -snes_ksp_ew_rtol0 <rtol0> - Sets rtol0
519964ba62caSBarry Smith .  -snes_ksp_ew_rtolmax <rtolmax> - Sets rtolmax
520064ba62caSBarry Smith .  -snes_ksp_ew_gamma <gamma> - Sets gamma
520164ba62caSBarry Smith .  -snes_ksp_ew_alpha <alpha> - Sets alpha
520264ba62caSBarry Smith .  -snes_ksp_ew_alpha2 <alpha2> - Sets alpha2
520364ba62caSBarry Smith -  -snes_ksp_ew_threshold <threshold> - Sets threshold
520464ba62caSBarry Smith 
520571f87433Sdalcinl    Notes:
520671f87433Sdalcinl    Currently, the default is to use a constant relative tolerance for
520771f87433Sdalcinl    the inner linear solvers.  Alternatively, one can use the
520871f87433Sdalcinl    Eisenstat-Walker method, where the relative convergence tolerance
520971f87433Sdalcinl    is reset at each Newton iteration according progress of the nonlinear
521071f87433Sdalcinl    solver.
521171f87433Sdalcinl 
521271f87433Sdalcinl    Level: advanced
521371f87433Sdalcinl 
521471f87433Sdalcinl    Reference:
521571f87433Sdalcinl    S. C. Eisenstat and H. F. Walker, "Choosing the forcing terms in an
521671f87433Sdalcinl    inexact Newton method", SISC 17 (1), pp.16-32, 1996.
521771f87433Sdalcinl 
5218db781477SPatrick Sanan .seealso: `SNESKSPGetUseEW()`, `SNESKSPGetParametersEW()`, `SNESKSPSetParametersEW()`
521971f87433Sdalcinl @*/
52207087cfbeSBarry Smith PetscErrorCode  SNESKSPSetUseEW(SNES snes,PetscBool flag)
522171f87433Sdalcinl {
522271f87433Sdalcinl   PetscFunctionBegin;
52230700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
5224acfcf0e5SJed Brown   PetscValidLogicalCollectiveBool(snes,flag,2);
522571f87433Sdalcinl   snes->ksp_ewconv = flag;
522671f87433Sdalcinl   PetscFunctionReturn(0);
522771f87433Sdalcinl }
522871f87433Sdalcinl 
522971f87433Sdalcinl /*@
5230fa9f3622SBarry Smith    SNESKSPGetUseEW - Gets if SNES is using Eisenstat-Walker method
523171f87433Sdalcinl    for computing relative tolerance for linear solvers within an
523271f87433Sdalcinl    inexact Newton method.
523371f87433Sdalcinl 
523471f87433Sdalcinl    Not Collective
523571f87433Sdalcinl 
523671f87433Sdalcinl    Input Parameter:
523771f87433Sdalcinl .  snes - SNES context
523871f87433Sdalcinl 
523971f87433Sdalcinl    Output Parameter:
524071f87433Sdalcinl .  flag - PETSC_TRUE or PETSC_FALSE
524171f87433Sdalcinl 
524271f87433Sdalcinl    Notes:
524371f87433Sdalcinl    Currently, the default is to use a constant relative tolerance for
524471f87433Sdalcinl    the inner linear solvers.  Alternatively, one can use the
524571f87433Sdalcinl    Eisenstat-Walker method, where the relative convergence tolerance
524671f87433Sdalcinl    is reset at each Newton iteration according progress of the nonlinear
524771f87433Sdalcinl    solver.
524871f87433Sdalcinl 
524971f87433Sdalcinl    Level: advanced
525071f87433Sdalcinl 
525171f87433Sdalcinl    Reference:
525271f87433Sdalcinl    S. C. Eisenstat and H. F. Walker, "Choosing the forcing terms in an
525371f87433Sdalcinl    inexact Newton method", SISC 17 (1), pp.16-32, 1996.
525471f87433Sdalcinl 
5255db781477SPatrick Sanan .seealso: `SNESKSPSetUseEW()`, `SNESKSPGetParametersEW()`, `SNESKSPSetParametersEW()`
525671f87433Sdalcinl @*/
52577087cfbeSBarry Smith PetscErrorCode  SNESKSPGetUseEW(SNES snes, PetscBool  *flag)
525871f87433Sdalcinl {
525971f87433Sdalcinl   PetscFunctionBegin;
52600700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
5261534a8f05SLisandro Dalcin   PetscValidBoolPointer(flag,2);
526271f87433Sdalcinl   *flag = snes->ksp_ewconv;
526371f87433Sdalcinl   PetscFunctionReturn(0);
526471f87433Sdalcinl }
526571f87433Sdalcinl 
526671f87433Sdalcinl /*@
5267fa9f3622SBarry Smith    SNESKSPSetParametersEW - Sets parameters for Eisenstat-Walker
526871f87433Sdalcinl    convergence criteria for the linear solvers within an inexact
526971f87433Sdalcinl    Newton method.
527071f87433Sdalcinl 
52713f9fe445SBarry Smith    Logically Collective on SNES
527271f87433Sdalcinl 
527371f87433Sdalcinl    Input Parameters:
527471f87433Sdalcinl +    snes - SNES context
52750f0abf79SStefano Zampini .    version - version 1, 2 (default is 2), 3 or 4
527671f87433Sdalcinl .    rtol_0 - initial relative tolerance (0 <= rtol_0 < 1)
527771f87433Sdalcinl .    rtol_max - maximum relative tolerance (0 <= rtol_max < 1)
527871f87433Sdalcinl .    gamma - multiplicative factor for version 2 rtol computation
527971f87433Sdalcinl              (0 <= gamma2 <= 1)
528071f87433Sdalcinl .    alpha - power for version 2 rtol computation (1 < alpha <= 2)
528171f87433Sdalcinl .    alpha2 - power for safeguard
528271f87433Sdalcinl -    threshold - threshold for imposing safeguard (0 < threshold < 1)
528371f87433Sdalcinl 
528471f87433Sdalcinl    Note:
528571f87433Sdalcinl    Version 3 was contributed by Luis Chacon, June 2006.
528671f87433Sdalcinl 
528771f87433Sdalcinl    Use PETSC_DEFAULT to retain the default for any of the parameters.
528871f87433Sdalcinl 
528971f87433Sdalcinl    Level: advanced
529071f87433Sdalcinl 
529171f87433Sdalcinl    Reference:
529271f87433Sdalcinl    S. C. Eisenstat and H. F. Walker, "Choosing the forcing terms in an
529371f87433Sdalcinl    inexact Newton method", Utah State University Math. Stat. Dept. Res.
529471f87433Sdalcinl    Report 6/94/75, June, 1994, to appear in SIAM J. Sci. Comput.
529571f87433Sdalcinl 
5296db781477SPatrick Sanan .seealso: `SNESKSPSetUseEW()`, `SNESKSPGetUseEW()`, `SNESKSPGetParametersEW()`
529771f87433Sdalcinl @*/
5298f5af7f23SKarl Rupp PetscErrorCode  SNESKSPSetParametersEW(SNES snes,PetscInt version,PetscReal rtol_0,PetscReal rtol_max,PetscReal gamma,PetscReal alpha,PetscReal alpha2,PetscReal threshold)
529971f87433Sdalcinl {
5300fa9f3622SBarry Smith   SNESKSPEW *kctx;
53015fd66863SKarl Rupp 
530271f87433Sdalcinl   PetscFunctionBegin;
53030700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
5304fa9f3622SBarry Smith   kctx = (SNESKSPEW*)snes->kspconvctx;
53055f80ce2aSJacob Faibussowitsch   PetscCheck(kctx,PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"No Eisenstat-Walker context existing");
5306c5eb9154SBarry Smith   PetscValidLogicalCollectiveInt(snes,version,2);
5307c5eb9154SBarry Smith   PetscValidLogicalCollectiveReal(snes,rtol_0,3);
5308c5eb9154SBarry Smith   PetscValidLogicalCollectiveReal(snes,rtol_max,4);
5309c5eb9154SBarry Smith   PetscValidLogicalCollectiveReal(snes,gamma,5);
5310c5eb9154SBarry Smith   PetscValidLogicalCollectiveReal(snes,alpha,6);
5311c5eb9154SBarry Smith   PetscValidLogicalCollectiveReal(snes,alpha2,7);
5312c5eb9154SBarry Smith   PetscValidLogicalCollectiveReal(snes,threshold,8);
531371f87433Sdalcinl 
531471f87433Sdalcinl   if (version != PETSC_DEFAULT)   kctx->version   = version;
531571f87433Sdalcinl   if (rtol_0 != PETSC_DEFAULT)    kctx->rtol_0    = rtol_0;
531671f87433Sdalcinl   if (rtol_max != PETSC_DEFAULT)  kctx->rtol_max  = rtol_max;
531771f87433Sdalcinl   if (gamma != PETSC_DEFAULT)     kctx->gamma     = gamma;
531871f87433Sdalcinl   if (alpha != PETSC_DEFAULT)     kctx->alpha     = alpha;
531971f87433Sdalcinl   if (alpha2 != PETSC_DEFAULT)    kctx->alpha2    = alpha2;
532071f87433Sdalcinl   if (threshold != PETSC_DEFAULT) kctx->threshold = threshold;
532171f87433Sdalcinl 
53220f0abf79SStefano Zampini   PetscCheck(kctx->version >= 1 && kctx->version <= 4,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Only versions 1 to 4 are supported: %" PetscInt_FMT,kctx->version);
53230b121fc5SBarry Smith   PetscCheck(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);
53240b121fc5SBarry Smith   PetscCheck(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);
53250b121fc5SBarry Smith   PetscCheck(kctx->gamma >= 0.0 && kctx->gamma <= 1.0,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"0.0 <= gamma (%g) <= 1.0",(double)kctx->gamma);
53260b121fc5SBarry Smith   PetscCheck(kctx->alpha > 1.0 && kctx->alpha <= 2.0,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"1.0 < alpha (%g) <= 2.0",(double)kctx->alpha);
53270b121fc5SBarry Smith   PetscCheck(kctx->threshold > 0.0 && kctx->threshold < 1.0,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"0.0 < threshold (%g) < 1.0",(double)kctx->threshold);
532871f87433Sdalcinl   PetscFunctionReturn(0);
532971f87433Sdalcinl }
533071f87433Sdalcinl 
533171f87433Sdalcinl /*@
5332fa9f3622SBarry Smith    SNESKSPGetParametersEW - Gets parameters for Eisenstat-Walker
533371f87433Sdalcinl    convergence criteria for the linear solvers within an inexact
533471f87433Sdalcinl    Newton method.
533571f87433Sdalcinl 
533671f87433Sdalcinl    Not Collective
533771f87433Sdalcinl 
533897bb3fdcSJose E. Roman    Input Parameter:
53396b867d5aSJose E. Roman .    snes - SNES context
534071f87433Sdalcinl 
534171f87433Sdalcinl    Output Parameters:
53420f0abf79SStefano Zampini +    version - version 1, 2 (default is 2), 3 or 4
534371f87433Sdalcinl .    rtol_0 - initial relative tolerance (0 <= rtol_0 < 1)
534471f87433Sdalcinl .    rtol_max - maximum relative tolerance (0 <= rtol_max < 1)
5345bf388a1fSBarry Smith .    gamma - multiplicative factor for version 2 rtol computation (0 <= gamma2 <= 1)
534671f87433Sdalcinl .    alpha - power for version 2 rtol computation (1 < alpha <= 2)
534771f87433Sdalcinl .    alpha2 - power for safeguard
534871f87433Sdalcinl -    threshold - threshold for imposing safeguard (0 < threshold < 1)
534971f87433Sdalcinl 
535071f87433Sdalcinl    Level: advanced
535171f87433Sdalcinl 
5352db781477SPatrick Sanan .seealso: `SNESKSPSetUseEW()`, `SNESKSPGetUseEW()`, `SNESKSPSetParametersEW()`
535371f87433Sdalcinl @*/
5354bf388a1fSBarry Smith PetscErrorCode  SNESKSPGetParametersEW(SNES snes,PetscInt *version,PetscReal *rtol_0,PetscReal *rtol_max,PetscReal *gamma,PetscReal *alpha,PetscReal *alpha2,PetscReal *threshold)
535571f87433Sdalcinl {
5356fa9f3622SBarry Smith   SNESKSPEW *kctx;
53575fd66863SKarl Rupp 
535871f87433Sdalcinl   PetscFunctionBegin;
53590700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
5360fa9f3622SBarry Smith   kctx = (SNESKSPEW*)snes->kspconvctx;
53615f80ce2aSJacob Faibussowitsch   PetscCheck(kctx,PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"No Eisenstat-Walker context existing");
536271f87433Sdalcinl   if (version)   *version   = kctx->version;
536371f87433Sdalcinl   if (rtol_0)    *rtol_0    = kctx->rtol_0;
536471f87433Sdalcinl   if (rtol_max)  *rtol_max  = kctx->rtol_max;
536571f87433Sdalcinl   if (gamma)     *gamma     = kctx->gamma;
536671f87433Sdalcinl   if (alpha)     *alpha     = kctx->alpha;
536771f87433Sdalcinl   if (alpha2)    *alpha2    = kctx->alpha2;
536871f87433Sdalcinl   if (threshold) *threshold = kctx->threshold;
536971f87433Sdalcinl   PetscFunctionReturn(0);
537071f87433Sdalcinl }
537171f87433Sdalcinl 
5372d5378b5fSDmitry Karpeev PetscErrorCode KSPPreSolve_SNESEW(KSP ksp, Vec b, Vec x, SNES snes)
537371f87433Sdalcinl {
5374fa9f3622SBarry Smith   SNESKSPEW *kctx = (SNESKSPEW*)snes->kspconvctx;
537571f87433Sdalcinl   PetscReal rtol  = PETSC_DEFAULT,stol;
537671f87433Sdalcinl 
537771f87433Sdalcinl   PetscFunctionBegin;
5378d4211eb9SBarry Smith   if (!snes->ksp_ewconv) PetscFunctionReturn(0);
537930058271SDmitry Karpeev   if (!snes->iter) {
538030058271SDmitry Karpeev     rtol = kctx->rtol_0; /* first time in, so use the original user rtol */
53819566063dSJacob Faibussowitsch     PetscCall(VecNorm(snes->vec_func,NORM_2,&kctx->norm_first));
53820f0abf79SStefano Zampini   } else {
538371f87433Sdalcinl     if (kctx->version == 1) {
53840f0abf79SStefano Zampini       rtol = PetscAbsReal(snes->norm - kctx->lresid_last)/kctx->norm_last;
538585ec1a3cSBarry Smith       stol = PetscPowReal(kctx->rtol_last,kctx->alpha2);
538671f87433Sdalcinl       if (stol > kctx->threshold) rtol = PetscMax(rtol,stol);
538771f87433Sdalcinl     } else if (kctx->version == 2) {
538885ec1a3cSBarry Smith       rtol = kctx->gamma * PetscPowReal(snes->norm/kctx->norm_last,kctx->alpha);
538985ec1a3cSBarry Smith       stol = kctx->gamma * PetscPowReal(kctx->rtol_last,kctx->alpha);
539071f87433Sdalcinl       if (stol > kctx->threshold) rtol = PetscMax(rtol,stol);
539171f87433Sdalcinl     } else if (kctx->version == 3) { /* contributed by Luis Chacon, June 2006. */
539285ec1a3cSBarry Smith       rtol = kctx->gamma * PetscPowReal(snes->norm/kctx->norm_last,kctx->alpha);
539371f87433Sdalcinl       /* safeguard: avoid sharp decrease of rtol */
539485ec1a3cSBarry Smith       stol = kctx->gamma*PetscPowReal(kctx->rtol_last,kctx->alpha);
539571f87433Sdalcinl       stol = PetscMax(rtol,stol);
539671f87433Sdalcinl       rtol = PetscMin(kctx->rtol_0,stol);
539771f87433Sdalcinl       /* safeguard: avoid oversolving */
539830058271SDmitry Karpeev       stol = kctx->gamma*(kctx->norm_first*snes->rtol)/snes->norm;
539971f87433Sdalcinl       stol = PetscMax(rtol,stol);
540071f87433Sdalcinl       rtol = PetscMin(kctx->rtol_0,stol);
54010f0abf79SStefano Zampini     } else if (kctx->version == 4) { /* H.-B. An et al. Journal of Computational and Applied Mathematics 200 (2007) 47-60 */
54020f0abf79SStefano Zampini       PetscReal ared = PetscAbsReal(kctx->norm_last - snes->norm);
54030f0abf79SStefano Zampini       PetscReal pred = PetscAbsReal(kctx->norm_last - kctx->lresid_last);
54040f0abf79SStefano Zampini       PetscReal rk = ared / pred;
54050f0abf79SStefano Zampini       if (rk < kctx->v4_p1) rtol = 1. - 2.*kctx->v4_p1;
54060f0abf79SStefano Zampini       else if (rk < kctx->v4_p2) rtol = kctx->rtol_last;
54070f0abf79SStefano Zampini       else if (rk < kctx->v4_p3) rtol = kctx->v4_m1 * kctx->rtol_last;
54080f0abf79SStefano Zampini       else rtol = kctx->v4_m2 * kctx->rtol_last;
54090f0abf79SStefano Zampini 
54100f0abf79SStefano Zampini       if (kctx->rtol_last_2 > kctx->v4_m3 && kctx->rtol_last > kctx->v4_m3 &&
54110f0abf79SStefano Zampini           kctx->rk_last_2 < kctx->v4_p1 && kctx->rk_last < kctx->v4_p1) {
54120f0abf79SStefano Zampini         rtol = kctx->v4_m4 * kctx->rtol_last;
54130f0abf79SStefano Zampini         //printf("iter %" PetscInt_FMT ", Eisenstat-Walker (version %" PetscInt_FMT ") KSP rtol=%g (rk %g ps %g %g %g) (AD)\n",snes->iter,kctx->version,(double)rtol,rk,kctx->v4_p1,kctx->v4_p2,kctx->v4_p3);
54140f0abf79SStefano Zampini       } else {
54150f0abf79SStefano Zampini         //printf("iter %" PetscInt_FMT ", Eisenstat-Walker (version %" PetscInt_FMT ") KSP rtol=%g (rk %g ps %g %g %g)\n",snes->iter,kctx->version,(double)rtol,rk,kctx->v4_p1,kctx->v4_p2,kctx->v4_p3);
541671f87433Sdalcinl       }
54170f0abf79SStefano Zampini       kctx->rtol_last_2 = kctx->rtol_last;
54180f0abf79SStefano Zampini       kctx->rk_last_2 = kctx->rk_last;
54190f0abf79SStefano Zampini       kctx->rk_last = rk;
54200f0abf79SStefano Zampini     } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Only versions 1-4 are supported: %" PetscInt_FMT,kctx->version);
54210f0abf79SStefano Zampini   }
54220f0abf79SStefano Zampini   /* safeguard: avoid rtol greater than rtol_max */
542371f87433Sdalcinl   rtol = PetscMin(rtol,kctx->rtol_max);
54249566063dSJacob Faibussowitsch   PetscCall(KSPSetTolerances(ksp,rtol,PETSC_DEFAULT,PETSC_DEFAULT,PETSC_DEFAULT));
542563a3b9bcSJacob Faibussowitsch   PetscCall(PetscInfo(snes,"iter %" PetscInt_FMT ", Eisenstat-Walker (version %" PetscInt_FMT ") KSP rtol=%g\n",snes->iter,kctx->version,(double)rtol));
542671f87433Sdalcinl   PetscFunctionReturn(0);
542771f87433Sdalcinl }
542871f87433Sdalcinl 
5429d5378b5fSDmitry Karpeev PetscErrorCode KSPPostSolve_SNESEW(KSP ksp, Vec b, Vec x, SNES snes)
543071f87433Sdalcinl {
5431fa9f3622SBarry Smith   SNESKSPEW *kctx = (SNESKSPEW*)snes->kspconvctx;
543271f87433Sdalcinl   PCSide    pcside;
543371f87433Sdalcinl   Vec       lres;
543471f87433Sdalcinl 
543571f87433Sdalcinl   PetscFunctionBegin;
5436d4211eb9SBarry Smith   if (!snes->ksp_ewconv) PetscFunctionReturn(0);
54379566063dSJacob Faibussowitsch   PetscCall(KSPGetTolerances(ksp,&kctx->rtol_last,NULL,NULL,NULL));
543871dbe336SPeter Brune   kctx->norm_last = snes->norm;
54390f0abf79SStefano Zampini   if (kctx->version == 1 || kctx->version == 4) {
54404f00ce20SMatthew G. Knepley     PC        pc;
54410f0abf79SStefano Zampini     PetscBool getRes;
54424f00ce20SMatthew G. Knepley 
54439566063dSJacob Faibussowitsch     PetscCall(KSPGetPC(ksp,&pc));
54440f0abf79SStefano Zampini     PetscCall(PetscObjectTypeCompare((PetscObject)pc,PCNONE,&getRes));
54450f0abf79SStefano Zampini     if (!getRes) {
54460f0abf79SStefano Zampini       KSPNormType normtype;
54470f0abf79SStefano Zampini 
54480f0abf79SStefano Zampini       PetscCall(KSPGetNormType(ksp,&normtype));
54490f0abf79SStefano Zampini       getRes = (PetscBool)(normtype == KSP_NORM_UNPRECONDITIONED);
54500f0abf79SStefano Zampini     }
54519566063dSJacob Faibussowitsch     PetscCall(KSPGetPCSide(ksp,&pcside));
54520f0abf79SStefano Zampini     if (pcside == PC_RIGHT || getRes) { /* KSP residual is true linear residual */
54539566063dSJacob Faibussowitsch       PetscCall(KSPGetResidualNorm(ksp,&kctx->lresid_last));
545471f87433Sdalcinl     } else {
545571f87433Sdalcinl       /* KSP residual is preconditioned residual */
545671f87433Sdalcinl       /* compute true linear residual norm */
54570f0abf79SStefano Zampini       Mat J;
54580f0abf79SStefano Zampini       PetscCall(KSPGetOperators(ksp,&J,NULL));
54599566063dSJacob Faibussowitsch       PetscCall(VecDuplicate(b,&lres));
54600f0abf79SStefano Zampini       PetscCall(MatMult(J,x,lres));
54619566063dSJacob Faibussowitsch       PetscCall(VecAYPX(lres,-1.0,b));
54629566063dSJacob Faibussowitsch       PetscCall(VecNorm(lres,NORM_2,&kctx->lresid_last));
54639566063dSJacob Faibussowitsch       PetscCall(VecDestroy(&lres));
546471f87433Sdalcinl     }
546571f87433Sdalcinl   }
546671f87433Sdalcinl   PetscFunctionReturn(0);
546771f87433Sdalcinl }
546871f87433Sdalcinl 
5469d4211eb9SBarry Smith /*@
5470d4211eb9SBarry Smith    SNESGetKSP - Returns the KSP context for a SNES solver.
5471d4211eb9SBarry Smith 
5472d4211eb9SBarry Smith    Not Collective, but if SNES object is parallel, then KSP object is parallel
5473d4211eb9SBarry Smith 
5474d4211eb9SBarry Smith    Input Parameter:
5475d4211eb9SBarry Smith .  snes - the SNES context
5476d4211eb9SBarry Smith 
5477d4211eb9SBarry Smith    Output Parameter:
5478d4211eb9SBarry Smith .  ksp - the KSP context
5479d4211eb9SBarry Smith 
5480d4211eb9SBarry Smith    Notes:
5481d4211eb9SBarry Smith    The user can then directly manipulate the KSP context to set various
5482d4211eb9SBarry Smith    options, etc.  Likewise, the user can then extract and manipulate the
5483d4211eb9SBarry Smith    PC contexts as well.
5484d4211eb9SBarry Smith 
5485d4211eb9SBarry Smith    Level: beginner
5486d4211eb9SBarry Smith 
5487db781477SPatrick Sanan .seealso: `KSPGetPC()`, `SNESCreate()`, `KSPCreate()`, `SNESSetKSP()`
5488d4211eb9SBarry Smith @*/
5489d4211eb9SBarry Smith PetscErrorCode  SNESGetKSP(SNES snes,KSP *ksp)
549071f87433Sdalcinl {
549171f87433Sdalcinl   PetscFunctionBegin;
5492d4211eb9SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
5493d4211eb9SBarry Smith   PetscValidPointer(ksp,2);
5494d4211eb9SBarry Smith 
5495d4211eb9SBarry Smith   if (!snes->ksp) {
54969566063dSJacob Faibussowitsch     PetscCall(KSPCreate(PetscObjectComm((PetscObject)snes),&snes->ksp));
54979566063dSJacob Faibussowitsch     PetscCall(PetscObjectIncrementTabLevel((PetscObject)snes->ksp,(PetscObject)snes,1));
54989566063dSJacob Faibussowitsch     PetscCall(PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->ksp));
5499d4211eb9SBarry Smith 
55009566063dSJacob Faibussowitsch     PetscCall(KSPSetPreSolve(snes->ksp,(PetscErrorCode (*)(KSP,Vec,Vec,void*))KSPPreSolve_SNESEW,snes));
55019566063dSJacob Faibussowitsch     PetscCall(KSPSetPostSolve(snes->ksp,(PetscErrorCode (*)(KSP,Vec,Vec,void*))KSPPostSolve_SNESEW,snes));
5502a5c2985bSBarry Smith 
55039566063dSJacob Faibussowitsch     PetscCall(KSPMonitorSetFromOptions(snes->ksp, "-snes_monitor_ksp", "snes_preconditioned_residual", snes));
55049566063dSJacob Faibussowitsch     PetscCall(PetscObjectSetOptions((PetscObject)snes->ksp,((PetscObject)snes)->options));
5505d4211eb9SBarry Smith   }
5506d4211eb9SBarry Smith   *ksp = snes->ksp;
550771f87433Sdalcinl   PetscFunctionReturn(0);
550871f87433Sdalcinl }
55096c699258SBarry Smith 
5510af0996ceSBarry Smith #include <petsc/private/dmimpl.h>
55116c699258SBarry Smith /*@
55122a808120SBarry Smith    SNESSetDM - Sets the DM that may be used by some nonlinear solvers or their underlying preconditioners
55136c699258SBarry Smith 
55143f9fe445SBarry Smith    Logically Collective on SNES
55156c699258SBarry Smith 
55166c699258SBarry Smith    Input Parameters:
55172a808120SBarry Smith +  snes - the nonlinear solver context
55182a808120SBarry Smith -  dm - the dm, cannot be NULL
55196c699258SBarry Smith 
5520e03a659cSJed Brown    Notes:
5521e03a659cSJed Brown    A DM can only be used for solving one problem at a time because information about the problem is stored on the DM,
5522e03a659cSJed Brown    even when not using interfaces like DMSNESSetFunction().  Use DMClone() to get a distinct DM when solving different
5523e03a659cSJed Brown    problems using the same function space.
5524e03a659cSJed Brown 
55256c699258SBarry Smith    Level: intermediate
55266c699258SBarry Smith 
5527db781477SPatrick Sanan .seealso: `SNESGetDM()`, `KSPSetDM()`, `KSPGetDM()`
55286c699258SBarry Smith @*/
55297087cfbeSBarry Smith PetscErrorCode  SNESSetDM(SNES snes,DM dm)
55306c699258SBarry Smith {
5531345fed2cSBarry Smith   KSP            ksp;
5532942e3340SBarry Smith   DMSNES         sdm;
55336c699258SBarry Smith 
55346c699258SBarry Smith   PetscFunctionBegin;
55350700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
55362a808120SBarry Smith   PetscValidHeaderSpecific(dm,DM_CLASSID,2);
55379566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)dm));
5538942e3340SBarry Smith   if (snes->dm) {               /* Move the DMSNES context over to the new DM unless the new DM already has one */
553951f4b3c7SToby Isaac     if (snes->dm->dmsnes && !dm->dmsnes) {
55409566063dSJacob Faibussowitsch       PetscCall(DMCopyDMSNES(snes->dm,dm));
55419566063dSJacob Faibussowitsch       PetscCall(DMGetDMSNES(snes->dm,&sdm));
5542f5af7f23SKarl Rupp       if (sdm->originaldm == snes->dm) sdm->originaldm = dm; /* Grant write privileges to the replacement DM */
55436cab3a1bSJed Brown     }
55449566063dSJacob Faibussowitsch     PetscCall(DMCoarsenHookRemove(snes->dm,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,snes));
55459566063dSJacob Faibussowitsch     PetscCall(DMDestroy(&snes->dm));
55466cab3a1bSJed Brown   }
55476c699258SBarry Smith   snes->dm     = dm;
5548116d1032SJed Brown   snes->dmAuto = PETSC_FALSE;
5549f5af7f23SKarl Rupp 
55509566063dSJacob Faibussowitsch   PetscCall(SNESGetKSP(snes,&ksp));
55519566063dSJacob Faibussowitsch   PetscCall(KSPSetDM(ksp,dm));
55529566063dSJacob Faibussowitsch   PetscCall(KSPSetDMActive(ksp,PETSC_FALSE));
5553efd4aadfSBarry Smith   if (snes->npc) {
55549566063dSJacob Faibussowitsch     PetscCall(SNESSetDM(snes->npc,snes->dm));
55559566063dSJacob Faibussowitsch     PetscCall(SNESSetNPCSide(snes,snes->npcside));
55562c155ee1SBarry Smith   }
55576c699258SBarry Smith   PetscFunctionReturn(0);
55586c699258SBarry Smith }
55596c699258SBarry Smith 
55606c699258SBarry Smith /*@
55616c699258SBarry Smith    SNESGetDM - Gets the DM that may be used by some preconditioners
55626c699258SBarry Smith 
55633f9fe445SBarry Smith    Not Collective but DM obtained is parallel on SNES
55646c699258SBarry Smith 
55656c699258SBarry Smith    Input Parameter:
55666c699258SBarry Smith . snes - the preconditioner context
55676c699258SBarry Smith 
55686c699258SBarry Smith    Output Parameter:
55696c699258SBarry Smith .  dm - the dm
55706c699258SBarry Smith 
55716c699258SBarry Smith    Level: intermediate
55726c699258SBarry Smith 
5573db781477SPatrick Sanan .seealso: `SNESSetDM()`, `KSPSetDM()`, `KSPGetDM()`
55746c699258SBarry Smith @*/
55757087cfbeSBarry Smith PetscErrorCode  SNESGetDM(SNES snes,DM *dm)
55766c699258SBarry Smith {
55776c699258SBarry Smith   PetscFunctionBegin;
55780700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
55796cab3a1bSJed Brown   if (!snes->dm) {
55809566063dSJacob Faibussowitsch     PetscCall(DMShellCreate(PetscObjectComm((PetscObject)snes),&snes->dm));
5581116d1032SJed Brown     snes->dmAuto = PETSC_TRUE;
55826cab3a1bSJed Brown   }
55836c699258SBarry Smith   *dm = snes->dm;
55846c699258SBarry Smith   PetscFunctionReturn(0);
55856c699258SBarry Smith }
55860807856dSBarry Smith 
558731823bd8SMatthew G Knepley /*@
5588be95d8f1SBarry Smith   SNESSetNPC - Sets the nonlinear preconditioner to be used.
558931823bd8SMatthew G Knepley 
559031823bd8SMatthew G Knepley   Collective on SNES
559131823bd8SMatthew G Knepley 
559231823bd8SMatthew G Knepley   Input Parameters:
559331823bd8SMatthew G Knepley + snes - iterative context obtained from SNESCreate()
559431823bd8SMatthew G Knepley - pc   - the preconditioner object
559531823bd8SMatthew G Knepley 
559631823bd8SMatthew G Knepley   Notes:
5597be95d8f1SBarry Smith   Use SNESGetNPC() to retrieve the preconditioner context (for example,
559831823bd8SMatthew G Knepley   to configure it using the API).
559931823bd8SMatthew G Knepley 
560031823bd8SMatthew G Knepley   Level: developer
560131823bd8SMatthew G Knepley 
5602db781477SPatrick Sanan .seealso: `SNESGetNPC()`, `SNESHasNPC()`
560331823bd8SMatthew G Knepley @*/
5604be95d8f1SBarry Smith PetscErrorCode SNESSetNPC(SNES snes, SNES pc)
560531823bd8SMatthew G Knepley {
560631823bd8SMatthew G Knepley   PetscFunctionBegin;
560731823bd8SMatthew G Knepley   PetscValidHeaderSpecific(snes, SNES_CLASSID, 1);
560831823bd8SMatthew G Knepley   PetscValidHeaderSpecific(pc, SNES_CLASSID, 2);
560931823bd8SMatthew G Knepley   PetscCheckSameComm(snes, 1, pc, 2);
56109566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject) pc));
56119566063dSJacob Faibussowitsch   PetscCall(SNESDestroy(&snes->npc));
5612efd4aadfSBarry Smith   snes->npc = pc;
56139566063dSJacob Faibussowitsch   PetscCall(PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->npc));
561431823bd8SMatthew G Knepley   PetscFunctionReturn(0);
561531823bd8SMatthew G Knepley }
561631823bd8SMatthew G Knepley 
561731823bd8SMatthew G Knepley /*@
5618be95d8f1SBarry Smith   SNESGetNPC - Creates a nonlinear preconditioning solver (SNES) to be used to precondition the nonlinear solver.
561931823bd8SMatthew G Knepley 
5620951fe5abSBarry Smith   Not Collective; but any changes to the obtained SNES object must be applied collectively
562131823bd8SMatthew G Knepley 
562231823bd8SMatthew G Knepley   Input Parameter:
562331823bd8SMatthew G Knepley . snes - iterative context obtained from SNESCreate()
562431823bd8SMatthew G Knepley 
562531823bd8SMatthew G Knepley   Output Parameter:
562631823bd8SMatthew G Knepley . pc - preconditioner context
562731823bd8SMatthew G Knepley 
5628b5badacbSBarry Smith   Options Database:
5629b5badacbSBarry Smith . -npc_snes_type <type> - set the type of the SNES to use as the nonlinear preconditioner
5630b5badacbSBarry Smith 
563195452b02SPatrick Sanan   Notes:
5632b5badacbSBarry Smith     If a SNES was previously set with SNESSetNPC() then that SNES is returned, otherwise a new SNES object is created.
5633be95d8f1SBarry Smith 
5634951fe5abSBarry Smith     The (preconditioner) SNES returned automatically inherits the same nonlinear function and Jacobian supplied to the original
5635951fe5abSBarry Smith     SNES during SNESSetUp()
5636951fe5abSBarry Smith 
563731823bd8SMatthew G Knepley   Level: developer
563831823bd8SMatthew G Knepley 
5639db781477SPatrick Sanan .seealso: `SNESSetNPC()`, `SNESHasNPC()`, `SNES`, `SNESCreate()`
564031823bd8SMatthew G Knepley @*/
5641be95d8f1SBarry Smith PetscErrorCode SNESGetNPC(SNES snes, SNES *pc)
564231823bd8SMatthew G Knepley {
5643a64e098fSPeter Brune   const char     *optionsprefix;
564431823bd8SMatthew G Knepley 
564531823bd8SMatthew G Knepley   PetscFunctionBegin;
564631823bd8SMatthew G Knepley   PetscValidHeaderSpecific(snes, SNES_CLASSID, 1);
564731823bd8SMatthew G Knepley   PetscValidPointer(pc, 2);
5648efd4aadfSBarry Smith   if (!snes->npc) {
56499566063dSJacob Faibussowitsch     PetscCall(SNESCreate(PetscObjectComm((PetscObject)snes),&snes->npc));
56509566063dSJacob Faibussowitsch     PetscCall(PetscObjectIncrementTabLevel((PetscObject)snes->npc,(PetscObject)snes,1));
56519566063dSJacob Faibussowitsch     PetscCall(PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->npc));
56529566063dSJacob Faibussowitsch     PetscCall(SNESGetOptionsPrefix(snes,&optionsprefix));
56539566063dSJacob Faibussowitsch     PetscCall(SNESSetOptionsPrefix(snes->npc,optionsprefix));
56549566063dSJacob Faibussowitsch     PetscCall(SNESAppendOptionsPrefix(snes->npc,"npc_"));
56559566063dSJacob Faibussowitsch     PetscCall(SNESSetCountersReset(snes->npc,PETSC_FALSE));
565631823bd8SMatthew G Knepley   }
5657efd4aadfSBarry Smith   *pc = snes->npc;
565831823bd8SMatthew G Knepley   PetscFunctionReturn(0);
565931823bd8SMatthew G Knepley }
566031823bd8SMatthew G Knepley 
56613ad1a0b9SPatrick Farrell /*@
56623ad1a0b9SPatrick Farrell   SNESHasNPC - Returns whether a nonlinear preconditioner exists
56633ad1a0b9SPatrick Farrell 
56643ad1a0b9SPatrick Farrell   Not Collective
56653ad1a0b9SPatrick Farrell 
56663ad1a0b9SPatrick Farrell   Input Parameter:
56673ad1a0b9SPatrick Farrell . snes - iterative context obtained from SNESCreate()
56683ad1a0b9SPatrick Farrell 
56693ad1a0b9SPatrick Farrell   Output Parameter:
56703ad1a0b9SPatrick Farrell . has_npc - whether the SNES has an NPC or not
56713ad1a0b9SPatrick Farrell 
56723ad1a0b9SPatrick Farrell   Level: developer
56733ad1a0b9SPatrick Farrell 
5674db781477SPatrick Sanan .seealso: `SNESSetNPC()`, `SNESGetNPC()`
56753ad1a0b9SPatrick Farrell @*/
56763ad1a0b9SPatrick Farrell PetscErrorCode SNESHasNPC(SNES snes, PetscBool *has_npc)
56773ad1a0b9SPatrick Farrell {
56783ad1a0b9SPatrick Farrell   PetscFunctionBegin;
56793ad1a0b9SPatrick Farrell   PetscValidHeaderSpecific(snes, SNES_CLASSID, 1);
5680efd4aadfSBarry Smith   *has_npc = (PetscBool) (snes->npc ? PETSC_TRUE : PETSC_FALSE);
56813ad1a0b9SPatrick Farrell   PetscFunctionReturn(0);
56823ad1a0b9SPatrick Farrell }
56833ad1a0b9SPatrick Farrell 
5684c40d0f55SPeter Brune /*@
5685be95d8f1SBarry Smith     SNESSetNPCSide - Sets the preconditioning side.
5686c40d0f55SPeter Brune 
5687c40d0f55SPeter Brune     Logically Collective on SNES
5688c40d0f55SPeter Brune 
5689c40d0f55SPeter Brune     Input Parameter:
5690c40d0f55SPeter Brune .   snes - iterative context obtained from SNESCreate()
5691c40d0f55SPeter Brune 
5692c40d0f55SPeter Brune     Output Parameter:
5693c40d0f55SPeter Brune .   side - the preconditioning side, where side is one of
5694c40d0f55SPeter Brune .vb
56952d547940SBarry Smith       PC_LEFT - left preconditioning
56962d547940SBarry Smith       PC_RIGHT - right preconditioning (default for most nonlinear solvers)
5697c40d0f55SPeter Brune .ve
5698c40d0f55SPeter Brune 
5699c40d0f55SPeter Brune     Options Database Keys:
570067b8a455SSatish Balay .   -snes_npc_side <right,left> - nonlinear preconditioner side
5701c40d0f55SPeter Brune 
570295452b02SPatrick Sanan     Notes:
570395452b02SPatrick Sanan     SNESNRICHARDSON and SNESNCG only support left preconditioning.
57042d547940SBarry Smith 
5705c40d0f55SPeter Brune     Level: intermediate
5706c40d0f55SPeter Brune 
5707db781477SPatrick Sanan .seealso: `SNESGetNPCSide()`, `KSPSetPCSide()`
5708c40d0f55SPeter Brune @*/
5709be95d8f1SBarry Smith PetscErrorCode  SNESSetNPCSide(SNES snes,PCSide side)
5710c40d0f55SPeter Brune {
5711c40d0f55SPeter Brune   PetscFunctionBegin;
5712c40d0f55SPeter Brune   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
5713c40d0f55SPeter Brune   PetscValidLogicalCollectiveEnum(snes,side,2);
5714b552625fSStefano Zampini   if (side == PC_SIDE_DEFAULT) side = PC_RIGHT;
571554c59aa7SJacob Faibussowitsch   PetscCheck((side == PC_LEFT) || (side == PC_RIGHT),PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_WRONG,"Only PC_LEFT and PC_RIGHT are supported");
5716efd4aadfSBarry Smith   snes->npcside = side;
5717c40d0f55SPeter Brune   PetscFunctionReturn(0);
5718c40d0f55SPeter Brune }
5719c40d0f55SPeter Brune 
5720c40d0f55SPeter Brune /*@
5721be95d8f1SBarry Smith     SNESGetNPCSide - Gets the preconditioning side.
5722c40d0f55SPeter Brune 
5723c40d0f55SPeter Brune     Not Collective
5724c40d0f55SPeter Brune 
5725c40d0f55SPeter Brune     Input Parameter:
5726c40d0f55SPeter Brune .   snes - iterative context obtained from SNESCreate()
5727c40d0f55SPeter Brune 
5728c40d0f55SPeter Brune     Output Parameter:
5729c40d0f55SPeter Brune .   side - the preconditioning side, where side is one of
5730c40d0f55SPeter Brune .vb
57312d547940SBarry Smith       PC_LEFT - left preconditioning
57322d547940SBarry Smith       PC_RIGHT - right preconditioning (default for most nonlinear solvers)
5733c40d0f55SPeter Brune .ve
5734c40d0f55SPeter Brune 
5735c40d0f55SPeter Brune     Level: intermediate
5736c40d0f55SPeter Brune 
5737db781477SPatrick Sanan .seealso: `SNESSetNPCSide()`, `KSPGetPCSide()`
5738c40d0f55SPeter Brune @*/
5739be95d8f1SBarry Smith PetscErrorCode  SNESGetNPCSide(SNES snes,PCSide *side)
5740c40d0f55SPeter Brune {
5741c40d0f55SPeter Brune   PetscFunctionBegin;
5742c40d0f55SPeter Brune   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
5743c40d0f55SPeter Brune   PetscValidPointer(side,2);
5744efd4aadfSBarry Smith   *side = snes->npcside;
5745c40d0f55SPeter Brune   PetscFunctionReturn(0);
5746c40d0f55SPeter Brune }
5747c40d0f55SPeter Brune 
57489e764e56SPeter Brune /*@
57497601faf0SJed Brown   SNESSetLineSearch - Sets the linesearch on the SNES instance.
57509e764e56SPeter Brune 
57519e764e56SPeter Brune   Collective on SNES
57529e764e56SPeter Brune 
57539e764e56SPeter Brune   Input Parameters:
57549e764e56SPeter Brune + snes - iterative context obtained from SNESCreate()
57559e764e56SPeter Brune - linesearch   - the linesearch object
57569e764e56SPeter Brune 
57579e764e56SPeter Brune   Notes:
57587601faf0SJed Brown   Use SNESGetLineSearch() to retrieve the preconditioner context (for example,
57599e764e56SPeter Brune   to configure it using the API).
57609e764e56SPeter Brune 
57619e764e56SPeter Brune   Level: developer
57629e764e56SPeter Brune 
5763db781477SPatrick Sanan .seealso: `SNESGetLineSearch()`
57649e764e56SPeter Brune @*/
57657601faf0SJed Brown PetscErrorCode SNESSetLineSearch(SNES snes, SNESLineSearch linesearch)
57669e764e56SPeter Brune {
57679e764e56SPeter Brune   PetscFunctionBegin;
57689e764e56SPeter Brune   PetscValidHeaderSpecific(snes, SNES_CLASSID, 1);
5769f1c6b773SPeter Brune   PetscValidHeaderSpecific(linesearch, SNESLINESEARCH_CLASSID, 2);
57709e764e56SPeter Brune   PetscCheckSameComm(snes, 1, linesearch, 2);
57719566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject) linesearch));
57729566063dSJacob Faibussowitsch   PetscCall(SNESLineSearchDestroy(&snes->linesearch));
5773f5af7f23SKarl Rupp 
57749e764e56SPeter Brune   snes->linesearch = linesearch;
5775f5af7f23SKarl Rupp 
57769566063dSJacob Faibussowitsch   PetscCall(PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->linesearch));
57779e764e56SPeter Brune   PetscFunctionReturn(0);
57789e764e56SPeter Brune }
57799e764e56SPeter Brune 
5780a34ceb2aSJed Brown /*@
57817601faf0SJed Brown   SNESGetLineSearch - Returns a pointer to the line search context set with SNESSetLineSearch()
57828141a3b9SPeter Brune   or creates a default line search instance associated with the SNES and returns it.
57839e764e56SPeter Brune 
57849e764e56SPeter Brune   Not Collective
57859e764e56SPeter Brune 
57869e764e56SPeter Brune   Input Parameter:
57879e764e56SPeter Brune . snes - iterative context obtained from SNESCreate()
57889e764e56SPeter Brune 
57899e764e56SPeter Brune   Output Parameter:
57909e764e56SPeter Brune . linesearch - linesearch context
57919e764e56SPeter Brune 
5792162e0bf5SPeter Brune   Level: beginner
57939e764e56SPeter Brune 
5794db781477SPatrick Sanan .seealso: `SNESSetLineSearch()`, `SNESLineSearchCreate()`
57959e764e56SPeter Brune @*/
57967601faf0SJed Brown PetscErrorCode SNESGetLineSearch(SNES snes, SNESLineSearch *linesearch)
57979e764e56SPeter Brune {
57989e764e56SPeter Brune   const char     *optionsprefix;
57999e764e56SPeter Brune 
58009e764e56SPeter Brune   PetscFunctionBegin;
58019e764e56SPeter Brune   PetscValidHeaderSpecific(snes, SNES_CLASSID, 1);
58029e764e56SPeter Brune   PetscValidPointer(linesearch, 2);
58039e764e56SPeter Brune   if (!snes->linesearch) {
58049566063dSJacob Faibussowitsch     PetscCall(SNESGetOptionsPrefix(snes, &optionsprefix));
58059566063dSJacob Faibussowitsch     PetscCall(SNESLineSearchCreate(PetscObjectComm((PetscObject)snes), &snes->linesearch));
58069566063dSJacob Faibussowitsch     PetscCall(SNESLineSearchSetSNES(snes->linesearch, snes));
58079566063dSJacob Faibussowitsch     PetscCall(SNESLineSearchAppendOptionsPrefix(snes->linesearch, optionsprefix));
58089566063dSJacob Faibussowitsch     PetscCall(PetscObjectIncrementTabLevel((PetscObject) snes->linesearch, (PetscObject) snes, 1));
58099566063dSJacob Faibussowitsch     PetscCall(PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->linesearch));
58109e764e56SPeter Brune   }
58119e764e56SPeter Brune   *linesearch = snes->linesearch;
58129e764e56SPeter Brune   PetscFunctionReturn(0);
58139e764e56SPeter Brune }
5814