xref: /petsc/src/snes/interface/snes.c (revision 36a9e3b9f6565ce1252c167e0dc4a4cf71b0f2ec)
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;
1394db00ebSBarry Smith PetscLogEvent SNES_Solve, 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:
25e113a28aSBarry Smith .  -snes_error_if_not_converged : this takes an optional truth value (0/1/no/yes/true/false)
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 
33e113a28aSBarry Smith .keywords: SNES, set, initial guess, nonzero
34e113a28aSBarry Smith 
35e113a28aSBarry Smith .seealso: SNESGetErrorIfNotConverged(), KSPGetErrorIfNotConverged(), KSPSetErrorIFNotConverged()
36e113a28aSBarry Smith @*/
377087cfbeSBarry Smith PetscErrorCode  SNESSetErrorIfNotConverged(SNES snes,PetscBool flg)
38e113a28aSBarry Smith {
39e113a28aSBarry Smith   PetscFunctionBegin;
40e113a28aSBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
41acfcf0e5SJed Brown   PetscValidLogicalCollectiveBool(snes,flg,2);
42e113a28aSBarry Smith   snes->errorifnotconverged = flg;
43e113a28aSBarry Smith   PetscFunctionReturn(0);
44e113a28aSBarry Smith }
45e113a28aSBarry Smith 
46e113a28aSBarry Smith /*@
47e113a28aSBarry Smith    SNESGetErrorIfNotConverged - Will SNESSolve() generate an error if the solver does not converge?
48e113a28aSBarry Smith 
49e113a28aSBarry Smith    Not Collective
50e113a28aSBarry Smith 
51e113a28aSBarry Smith    Input Parameter:
52e113a28aSBarry Smith .  snes - iterative context obtained from SNESCreate()
53e113a28aSBarry Smith 
54e113a28aSBarry Smith    Output Parameter:
55e113a28aSBarry Smith .  flag - PETSC_TRUE if it will generate an error, else PETSC_FALSE
56e113a28aSBarry Smith 
57e113a28aSBarry Smith    Level: intermediate
58e113a28aSBarry Smith 
59e113a28aSBarry Smith .keywords: SNES, set, initial guess, nonzero
60e113a28aSBarry Smith 
61e113a28aSBarry Smith .seealso:  SNESSetErrorIfNotConverged(), KSPGetErrorIfNotConverged(), KSPSetErrorIFNotConverged()
62e113a28aSBarry Smith @*/
637087cfbeSBarry Smith PetscErrorCode  SNESGetErrorIfNotConverged(SNES snes,PetscBool  *flag)
64e113a28aSBarry Smith {
65e113a28aSBarry Smith   PetscFunctionBegin;
66e113a28aSBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
67e113a28aSBarry Smith   PetscValidPointer(flag,2);
68e113a28aSBarry Smith   *flag = snes->errorifnotconverged;
69e113a28aSBarry Smith   PetscFunctionReturn(0);
70e113a28aSBarry Smith }
71e113a28aSBarry Smith 
724fc747eaSLawrence Mitchell /*@
734fc747eaSLawrence Mitchell     SNESSetAlwaysComputesFinalResidual - does the SNES always compute the residual at the final solution?
744fc747eaSLawrence Mitchell 
754fc747eaSLawrence Mitchell    Logically Collective on SNES
764fc747eaSLawrence Mitchell 
774fc747eaSLawrence Mitchell     Input Parameters:
784fc747eaSLawrence Mitchell +   snes - the shell SNES
794fc747eaSLawrence Mitchell -   flg - is the residual computed?
804fc747eaSLawrence Mitchell 
814fc747eaSLawrence Mitchell    Level: advanced
824fc747eaSLawrence Mitchell 
834fc747eaSLawrence Mitchell .seealso: SNESGetAlwaysComputesFinalResidual()
844fc747eaSLawrence Mitchell @*/
854fc747eaSLawrence Mitchell PetscErrorCode  SNESSetAlwaysComputesFinalResidual(SNES snes, PetscBool flg)
864fc747eaSLawrence Mitchell {
874fc747eaSLawrence Mitchell   PetscFunctionBegin;
884fc747eaSLawrence Mitchell   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
894fc747eaSLawrence Mitchell   snes->alwayscomputesfinalresidual = flg;
904fc747eaSLawrence Mitchell   PetscFunctionReturn(0);
914fc747eaSLawrence Mitchell }
924fc747eaSLawrence Mitchell 
934fc747eaSLawrence Mitchell /*@
944fc747eaSLawrence Mitchell     SNESGetAlwaysComputesFinalResidual - does the SNES always compute the residual at the final solution?
954fc747eaSLawrence Mitchell 
964fc747eaSLawrence Mitchell    Logically Collective on SNES
974fc747eaSLawrence Mitchell 
984fc747eaSLawrence Mitchell     Input Parameter:
994fc747eaSLawrence Mitchell .   snes - the shell SNES
1004fc747eaSLawrence Mitchell 
1014fc747eaSLawrence Mitchell     Output Parameter:
1024fc747eaSLawrence Mitchell .   flg - is the residual computed?
1034fc747eaSLawrence Mitchell 
1044fc747eaSLawrence Mitchell    Level: advanced
1054fc747eaSLawrence Mitchell 
1064fc747eaSLawrence Mitchell .seealso: SNESSetAlwaysComputesFinalResidual()
1074fc747eaSLawrence Mitchell @*/
1084fc747eaSLawrence Mitchell PetscErrorCode  SNESGetAlwaysComputesFinalResidual(SNES snes, PetscBool *flg)
1094fc747eaSLawrence Mitchell {
1104fc747eaSLawrence Mitchell   PetscFunctionBegin;
1114fc747eaSLawrence Mitchell   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
1124fc747eaSLawrence Mitchell   *flg = snes->alwayscomputesfinalresidual;
1134fc747eaSLawrence Mitchell   PetscFunctionReturn(0);
1144fc747eaSLawrence Mitchell }
1154fc747eaSLawrence Mitchell 
116e725d27bSBarry Smith /*@
117bf388a1fSBarry Smith    SNESSetFunctionDomainError - tells SNES that the input vector to your SNESFunction is not
1184936397dSBarry Smith      in the functions domain. For example, negative pressure.
1194936397dSBarry Smith 
1203f9fe445SBarry Smith    Logically Collective on SNES
1214936397dSBarry Smith 
1224936397dSBarry Smith    Input Parameters:
1236a388c36SPeter Brune .  snes - the SNES context
1244936397dSBarry Smith 
12528529972SSatish Balay    Level: advanced
1264936397dSBarry Smith 
1274936397dSBarry Smith .keywords: SNES, view
1284936397dSBarry Smith 
129bf388a1fSBarry Smith .seealso: SNESCreate(), SNESSetFunction(), SNESFunction
1304936397dSBarry Smith @*/
1317087cfbeSBarry Smith PetscErrorCode  SNESSetFunctionDomainError(SNES snes)
1324936397dSBarry Smith {
1334936397dSBarry Smith   PetscFunctionBegin;
1340700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
135422a814eSBarry Smith   if (snes->errorifnotconverged) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"User code indicates input vector is not in the function domain");
1364936397dSBarry Smith   snes->domainerror = PETSC_TRUE;
1374936397dSBarry Smith   PetscFunctionReturn(0);
1384936397dSBarry Smith }
1394936397dSBarry Smith 
1406a388c36SPeter Brune /*@
14107b62357SFande Kong    SNESSetJacobianDomainError - tells SNES that computeJacobian does not make sense any more. For example there is a negative element transformation.
14207b62357SFande Kong 
14307b62357SFande Kong    Logically Collective on SNES
14407b62357SFande Kong 
14507b62357SFande Kong    Input Parameters:
14607b62357SFande Kong .  snes - the SNES context
14707b62357SFande Kong 
14807b62357SFande Kong    Level: advanced
14907b62357SFande Kong 
15007b62357SFande Kong .keywords: SNES, view
15107b62357SFande Kong 
15207b62357SFande Kong .seealso: SNESCreate(), SNESSetFunction(), SNESFunction(), SNESSetFunctionDomainError()
15307b62357SFande Kong @*/
15407b62357SFande Kong PetscErrorCode SNESSetJacobianDomainError(SNES snes)
15507b62357SFande Kong {
15607b62357SFande Kong   PetscFunctionBegin;
15707b62357SFande Kong   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
15807b62357SFande Kong   if (snes->errorifnotconverged) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"User code indicates computeJacobian does not make sense");
15907b62357SFande Kong   snes->jacobiandomainerror = PETSC_TRUE;
16007b62357SFande Kong   PetscFunctionReturn(0);
16107b62357SFande Kong }
16207b62357SFande Kong 
16307b62357SFande Kong /*@
164b351a90bSFande Kong    SNESSetCheckJacobianDomainError - if or not to check jacobian domain error after each Jacobian evaluation. By default, we check Jacobian domain error
165b351a90bSFande Kong    in the debug mode, and do not check it in the optimized mode.
166b351a90bSFande Kong 
167b351a90bSFande Kong    Logically Collective on SNES
168b351a90bSFande Kong 
169b351a90bSFande Kong    Input Parameters:
170b351a90bSFande Kong .  snes - the SNES context
171b351a90bSFande Kong .  flg  - indicates if or not to check jacobian domain error after each Jacobian evaluation
172b351a90bSFande Kong 
173b351a90bSFande Kong    Level: advanced
174b351a90bSFande Kong 
175b351a90bSFande Kong .keywords: SNES, view
176b351a90bSFande Kong 
1778383d7d7SFande Kong .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 
2008383d7d7SFande Kong .keywords: SNES, view
2018383d7d7SFande Kong 
2028383d7d7SFande Kong .seealso: SNESCreate(), SNESSetFunction(), SNESFunction(), SNESSetFunctionDomainError(), SNESSetCheckJacobianDomainError()
2038383d7d7SFande Kong @*/
2048383d7d7SFande Kong PetscErrorCode SNESGetCheckJacobianDomainError(SNES snes, PetscBool *flg)
2058383d7d7SFande Kong {
2068383d7d7SFande Kong   PetscFunctionBegin;
2078383d7d7SFande Kong   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
2088383d7d7SFande Kong   PetscValidPointer(flg, 2);
2098383d7d7SFande Kong   *flg = snes->checkjacdomainerror;
2108383d7d7SFande Kong   PetscFunctionReturn(0);
2118383d7d7SFande Kong }
2128383d7d7SFande Kong 
2138383d7d7SFande Kong /*@
214c77b2880SPeter Brune    SNESGetFunctionDomainError - Gets the status of the domain error after a call to SNESComputeFunction;
2156a388c36SPeter Brune 
2166a388c36SPeter Brune    Logically Collective on SNES
2176a388c36SPeter Brune 
2186a388c36SPeter Brune    Input Parameters:
2196a388c36SPeter Brune .  snes - the SNES context
2206a388c36SPeter Brune 
2216a388c36SPeter Brune    Output Parameters:
222bf388a1fSBarry Smith .  domainerror - Set to PETSC_TRUE if there's a domain error; PETSC_FALSE otherwise.
2236a388c36SPeter Brune 
2246a388c36SPeter Brune    Level: advanced
2256a388c36SPeter Brune 
2266a388c36SPeter Brune .keywords: SNES, view
2276a388c36SPeter Brune 
228bf388a1fSBarry Smith .seealso: SNESSetFunctionDomainError(), SNESComputeFunction()
2296a388c36SPeter Brune @*/
2306a388c36SPeter Brune PetscErrorCode  SNESGetFunctionDomainError(SNES snes, PetscBool *domainerror)
2316a388c36SPeter Brune {
2326a388c36SPeter Brune   PetscFunctionBegin;
2336a388c36SPeter Brune   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
2346a388c36SPeter Brune   PetscValidPointer(domainerror, 2);
2356a388c36SPeter Brune   *domainerror = snes->domainerror;
2366a388c36SPeter Brune   PetscFunctionReturn(0);
2376a388c36SPeter Brune }
2386a388c36SPeter Brune 
23907b62357SFande Kong /*@
24007b62357SFande Kong    SNESGetJacobianDomainError - Gets the status of the Jacobian domain error after a call to SNESComputeJacobian;
24107b62357SFande Kong 
24207b62357SFande Kong    Logically Collective on SNES
24307b62357SFande Kong 
24407b62357SFande Kong    Input Parameters:
24507b62357SFande Kong .  snes - the SNES context
24607b62357SFande Kong 
24707b62357SFande Kong    Output Parameters:
24807b62357SFande Kong .  domainerror - Set to PETSC_TRUE if there's a jacobian domain error; PETSC_FALSE otherwise.
24907b62357SFande Kong 
25007b62357SFande Kong    Level: advanced
25107b62357SFande Kong 
25207b62357SFande Kong .keywords: SNES, view
25307b62357SFande Kong 
25407b62357SFande Kong .seealso: SNESSetFunctionDomainError(), SNESComputeFunction(),SNESGetFunctionDomainError()
25507b62357SFande Kong @*/
25607b62357SFande Kong PetscErrorCode SNESGetJacobianDomainError(SNES snes, PetscBool *domainerror)
25707b62357SFande Kong {
25807b62357SFande Kong   PetscFunctionBegin;
25907b62357SFande Kong   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
26007b62357SFande Kong   PetscValidPointer(domainerror, 2);
26107b62357SFande Kong   *domainerror = snes->jacobiandomainerror;
26207b62357SFande Kong   PetscFunctionReturn(0);
26307b62357SFande Kong }
26407b62357SFande Kong 
26555849f57SBarry Smith /*@C
26655849f57SBarry Smith   SNESLoad - Loads a SNES that has been stored in binary  with SNESView().
26755849f57SBarry Smith 
26855849f57SBarry Smith   Collective on PetscViewer
26955849f57SBarry Smith 
27055849f57SBarry Smith   Input Parameters:
27155849f57SBarry Smith + newdm - the newly loaded SNES, this needs to have been created with SNESCreate() or
27255849f57SBarry Smith            some related function before a call to SNESLoad().
27355849f57SBarry Smith - viewer - binary file viewer, obtained from PetscViewerBinaryOpen()
27455849f57SBarry Smith 
27555849f57SBarry Smith    Level: intermediate
27655849f57SBarry Smith 
27755849f57SBarry Smith   Notes:
27855849f57SBarry Smith    The type is determined by the data in the file, any type set into the SNES before this call is ignored.
27955849f57SBarry Smith 
28055849f57SBarry Smith   Notes for advanced users:
28155849f57SBarry Smith   Most users should not need to know the details of the binary storage
28255849f57SBarry Smith   format, since SNESLoad() and TSView() completely hide these details.
28355849f57SBarry Smith   But for anyone who's interested, the standard binary matrix storage
28455849f57SBarry Smith   format is
28555849f57SBarry Smith .vb
28655849f57SBarry Smith      has not yet been determined
28755849f57SBarry Smith .ve
28855849f57SBarry Smith 
28955849f57SBarry Smith .seealso: PetscViewerBinaryOpen(), SNESView(), MatLoad(), VecLoad()
29055849f57SBarry Smith @*/
2912d53ad75SBarry Smith PetscErrorCode  SNESLoad(SNES snes, PetscViewer viewer)
29255849f57SBarry Smith {
29355849f57SBarry Smith   PetscErrorCode ierr;
29455849f57SBarry Smith   PetscBool      isbinary;
295060da220SMatthew G. Knepley   PetscInt       classid;
29655849f57SBarry Smith   char           type[256];
29755849f57SBarry Smith   KSP            ksp;
2982d53ad75SBarry Smith   DM             dm;
2992d53ad75SBarry Smith   DMSNES         dmsnes;
30055849f57SBarry Smith 
30155849f57SBarry Smith   PetscFunctionBegin;
3022d53ad75SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
30355849f57SBarry Smith   PetscValidHeaderSpecific(viewer,PETSC_VIEWER_CLASSID,2);
30455849f57SBarry Smith   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);CHKERRQ(ierr);
30555849f57SBarry Smith   if (!isbinary) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Invalid viewer; open viewer with PetscViewerBinaryOpen()");
30655849f57SBarry Smith 
307060da220SMatthew G. Knepley   ierr = PetscViewerBinaryRead(viewer,&classid,1,NULL,PETSC_INT);CHKERRQ(ierr);
308ce94432eSBarry Smith   if (classid != SNES_FILE_CLASSID) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_WRONG,"Not SNES next in file");
309060da220SMatthew G. Knepley   ierr = PetscViewerBinaryRead(viewer,type,256,NULL,PETSC_CHAR);CHKERRQ(ierr);
3102d53ad75SBarry Smith   ierr = SNESSetType(snes, type);CHKERRQ(ierr);
3112d53ad75SBarry Smith   if (snes->ops->load) {
3122d53ad75SBarry Smith     ierr = (*snes->ops->load)(snes,viewer);CHKERRQ(ierr);
313f2c2a1b9SBarry Smith   }
3142d53ad75SBarry Smith   ierr = SNESGetDM(snes,&dm);CHKERRQ(ierr);
3152d53ad75SBarry Smith   ierr = DMGetDMSNES(dm,&dmsnes);CHKERRQ(ierr);
3162d53ad75SBarry Smith   ierr = DMSNESLoad(dmsnes,viewer);CHKERRQ(ierr);
3172d53ad75SBarry Smith   ierr = SNESGetKSP(snes,&ksp);CHKERRQ(ierr);
31855849f57SBarry Smith   ierr = KSPLoad(ksp,viewer);CHKERRQ(ierr);
31955849f57SBarry Smith   PetscFunctionReturn(0);
32055849f57SBarry Smith }
3216a388c36SPeter Brune 
3229804daf3SBarry Smith #include <petscdraw.h>
323e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
324e04113cfSBarry Smith #include <petscviewersaws.h>
325bfb97211SBarry Smith #endif
3268404b7f3SBarry Smith 
3277e2c5f70SBarry Smith /*@C
3289b94acceSBarry Smith    SNESView - Prints the SNES data structure.
3299b94acceSBarry Smith 
3304c49b128SBarry Smith    Collective on SNES
331fee21e36SBarry Smith 
332c7afd0dbSLois Curfman McInnes    Input Parameters:
333c7afd0dbSLois Curfman McInnes +  SNES - the SNES context
334c7afd0dbSLois Curfman McInnes -  viewer - visualization context
335c7afd0dbSLois Curfman McInnes 
3369b94acceSBarry Smith    Options Database Key:
337c8a8ba5cSLois Curfman McInnes .  -snes_view - Calls SNESView() at end of SNESSolve()
3389b94acceSBarry Smith 
3399b94acceSBarry Smith    Notes:
3409b94acceSBarry Smith    The available visualization contexts include
341b0a32e0cSBarry Smith +     PETSC_VIEWER_STDOUT_SELF - standard output (default)
342b0a32e0cSBarry Smith -     PETSC_VIEWER_STDOUT_WORLD - synchronized standard
343c8a8ba5cSLois Curfman McInnes          output where only the first processor opens
344c8a8ba5cSLois Curfman McInnes          the file.  All other processors send their
345c8a8ba5cSLois Curfman McInnes          data to the first processor to print.
3469b94acceSBarry Smith 
3473e081fefSLois Curfman McInnes    The user can open an alternative visualization context with
348b0a32e0cSBarry Smith    PetscViewerASCIIOpen() - output to a specified file.
3499b94acceSBarry Smith 
35036851e7fSLois Curfman McInnes    Level: beginner
35136851e7fSLois Curfman McInnes 
3529b94acceSBarry Smith .keywords: SNES, view
3539b94acceSBarry Smith 
354b0a32e0cSBarry Smith .seealso: PetscViewerASCIIOpen()
3559b94acceSBarry Smith @*/
3567087cfbeSBarry Smith PetscErrorCode  SNESView(SNES snes,PetscViewer viewer)
3579b94acceSBarry Smith {
358fa9f3622SBarry Smith   SNESKSPEW      *kctx;
359dfbe8321SBarry Smith   PetscErrorCode ierr;
36094b7f48cSBarry Smith   KSP            ksp;
3617f1410a3SPeter Brune   SNESLineSearch linesearch;
36272a02f06SBarry Smith   PetscBool      iascii,isstring,isbinary,isdraw;
3632d53ad75SBarry Smith   DMSNES         dmsnes;
364e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
365536b137fSBarry Smith   PetscBool      issaws;
366bfb97211SBarry Smith #endif
3679b94acceSBarry Smith 
3683a40ed3dSBarry Smith   PetscFunctionBegin;
3690700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3703050cee2SBarry Smith   if (!viewer) {
371ce94432eSBarry Smith     ierr = PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes),&viewer);CHKERRQ(ierr);
3723050cee2SBarry Smith   }
3730700a824SBarry Smith   PetscValidHeaderSpecific(viewer,PETSC_VIEWER_CLASSID,2);
374c9780b6fSBarry Smith   PetscCheckSameComm(snes,1,viewer,2);
37574679c65SBarry Smith 
376251f4c67SDmitry Karpeev   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);CHKERRQ(ierr);
377251f4c67SDmitry Karpeev   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSTRING,&isstring);CHKERRQ(ierr);
37855849f57SBarry Smith   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);CHKERRQ(ierr);
37972a02f06SBarry Smith   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERDRAW,&isdraw);CHKERRQ(ierr);
380e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
381536b137fSBarry Smith   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSAWS,&issaws);CHKERRQ(ierr);
382bfb97211SBarry Smith #endif
38332077d6dSBarry Smith   if (iascii) {
384dc0571f2SMatthew G. Knepley     SNESNormSchedule normschedule;
3858404b7f3SBarry Smith     DM               dm;
3868404b7f3SBarry Smith     PetscErrorCode   (*cJ)(SNES,Vec,Mat,Mat,void*);
3878404b7f3SBarry Smith     void             *ctx;
388dc0571f2SMatthew G. Knepley 
389dae58748SBarry Smith     ierr = PetscObjectPrintClassNamePrefixType((PetscObject)snes,viewer);CHKERRQ(ierr);
390fce1e034SJed Brown     if (!snes->setupcalled) {
391fce1e034SJed Brown       ierr = PetscViewerASCIIPrintf(viewer,"  SNES has not been set up so information may be incomplete\n");CHKERRQ(ierr);
392fce1e034SJed Brown     }
393e7788613SBarry Smith     if (snes->ops->view) {
394b0a32e0cSBarry Smith       ierr = PetscViewerASCIIPushTab(viewer);CHKERRQ(ierr);
395e7788613SBarry Smith       ierr = (*snes->ops->view)(snes,viewer);CHKERRQ(ierr);
396b0a32e0cSBarry Smith       ierr = PetscViewerASCIIPopTab(viewer);CHKERRQ(ierr);
3970ef38995SBarry Smith     }
39877431f27SBarry Smith     ierr = PetscViewerASCIIPrintf(viewer,"  maximum iterations=%D, maximum function evaluations=%D\n",snes->max_its,snes->max_funcs);CHKERRQ(ierr);
39957622a8eSBarry Smith     ierr = PetscViewerASCIIPrintf(viewer,"  tolerances: relative=%g, absolute=%g, solution=%g\n",(double)snes->rtol,(double)snes->abstol,(double)snes->stol);CHKERRQ(ierr);
400efd4aadfSBarry Smith     if (snes->usesksp) {
40177431f27SBarry Smith       ierr = PetscViewerASCIIPrintf(viewer,"  total number of linear solver iterations=%D\n",snes->linear_its);CHKERRQ(ierr);
402efd4aadfSBarry Smith     }
40377431f27SBarry Smith     ierr = PetscViewerASCIIPrintf(viewer,"  total number of function evaluations=%D\n",snes->nfuncs);CHKERRQ(ierr);
404dc0571f2SMatthew G. Knepley     ierr = SNESGetNormSchedule(snes, &normschedule);CHKERRQ(ierr);
405dc0571f2SMatthew G. Knepley     if (normschedule > 0) {ierr = PetscViewerASCIIPrintf(viewer,"  norm schedule %s\n",SNESNormSchedules[normschedule]);CHKERRQ(ierr);}
40617fe4bdfSPeter Brune     if (snes->gridsequence) {
40717fe4bdfSPeter Brune       ierr = PetscViewerASCIIPrintf(viewer,"  total number of grid sequence refinements=%D\n",snes->gridsequence);CHKERRQ(ierr);
40817fe4bdfSPeter Brune     }
4099b94acceSBarry Smith     if (snes->ksp_ewconv) {
410fa9f3622SBarry Smith       kctx = (SNESKSPEW*)snes->kspconvctx;
4119b94acceSBarry Smith       if (kctx) {
41277431f27SBarry Smith         ierr = PetscViewerASCIIPrintf(viewer,"  Eisenstat-Walker computation of KSP relative tolerance (version %D)\n",kctx->version);CHKERRQ(ierr);
41357622a8eSBarry Smith         ierr = PetscViewerASCIIPrintf(viewer,"    rtol_0=%g, rtol_max=%g, threshold=%g\n",(double)kctx->rtol_0,(double)kctx->rtol_max,(double)kctx->threshold);CHKERRQ(ierr);
41457622a8eSBarry Smith         ierr = PetscViewerASCIIPrintf(viewer,"    gamma=%g, alpha=%g, alpha2=%g\n",(double)kctx->gamma,(double)kctx->alpha,(double)kctx->alpha2);CHKERRQ(ierr);
4159b94acceSBarry Smith       }
4169b94acceSBarry Smith     }
417eb1f6c34SBarry Smith     if (snes->lagpreconditioner == -1) {
418eb1f6c34SBarry Smith       ierr = PetscViewerASCIIPrintf(viewer,"  Preconditioned is never rebuilt\n");CHKERRQ(ierr);
419eb1f6c34SBarry Smith     } else if (snes->lagpreconditioner > 1) {
420eb1f6c34SBarry Smith       ierr = PetscViewerASCIIPrintf(viewer,"  Preconditioned is rebuilt every %D new Jacobians\n",snes->lagpreconditioner);CHKERRQ(ierr);
421eb1f6c34SBarry Smith     }
422eb1f6c34SBarry Smith     if (snes->lagjacobian == -1) {
423eb1f6c34SBarry Smith       ierr = PetscViewerASCIIPrintf(viewer,"  Jacobian is never rebuilt\n");CHKERRQ(ierr);
424eb1f6c34SBarry Smith     } else if (snes->lagjacobian > 1) {
42542f4f86dSBarry Smith       ierr = PetscViewerASCIIPrintf(viewer,"  Jacobian is rebuilt every %D SNES iterations\n",snes->lagjacobian);CHKERRQ(ierr);
426eb1f6c34SBarry Smith     }
4278404b7f3SBarry Smith     ierr = SNESGetDM(snes,&dm);CHKERRQ(ierr);
4288404b7f3SBarry Smith     ierr = DMSNESGetJacobian(dm,&cJ,&ctx);CHKERRQ(ierr);
4298404b7f3SBarry Smith     if (cJ == SNESComputeJacobianDefault) {
4308404b7f3SBarry Smith       ierr = PetscViewerASCIIPrintf(viewer,"  Jacobian is built using finite differences one column at a time\n");CHKERRQ(ierr);
4318404b7f3SBarry Smith     } else if (cJ == SNESComputeJacobianDefaultColor) {
4328404b7f3SBarry Smith       ierr = PetscViewerASCIIPrintf(viewer,"  Jacobian is built using finite differences with coloring\n");CHKERRQ(ierr);
4338404b7f3SBarry Smith     }
4340f5bd95cSBarry Smith   } else if (isstring) {
435317d6ea6SBarry Smith     const char *type;
436454a90a3SBarry Smith     ierr = SNESGetType(snes,&type);CHKERRQ(ierr);
437*36a9e3b9SBarry Smith     ierr = PetscViewerStringSPrintf(viewer," SNESType: %-7.7s",type);CHKERRQ(ierr);
438*36a9e3b9SBarry Smith     if (snes->ops->view) {ierr = (*snes->ops->view)(snes,viewer);CHKERRQ(ierr);}
43955849f57SBarry Smith   } else if (isbinary) {
44055849f57SBarry Smith     PetscInt    classid = SNES_FILE_CLASSID;
44155849f57SBarry Smith     MPI_Comm    comm;
44255849f57SBarry Smith     PetscMPIInt rank;
44355849f57SBarry Smith     char        type[256];
44455849f57SBarry Smith 
44555849f57SBarry Smith     ierr = PetscObjectGetComm((PetscObject)snes,&comm);CHKERRQ(ierr);
44655849f57SBarry Smith     ierr = MPI_Comm_rank(comm,&rank);CHKERRQ(ierr);
44755849f57SBarry Smith     if (!rank) {
44855849f57SBarry Smith       ierr = PetscViewerBinaryWrite(viewer,&classid,1,PETSC_INT,PETSC_FALSE);CHKERRQ(ierr);
44989d949e2SBarry Smith       ierr = PetscStrncpy(type,((PetscObject)snes)->type_name,sizeof(type));CHKERRQ(ierr);
45089d949e2SBarry Smith       ierr = PetscViewerBinaryWrite(viewer,type,sizeof(type),PETSC_CHAR,PETSC_FALSE);CHKERRQ(ierr);
45155849f57SBarry Smith     }
45255849f57SBarry Smith     if (snes->ops->view) {
45355849f57SBarry Smith       ierr = (*snes->ops->view)(snes,viewer);CHKERRQ(ierr);
45455849f57SBarry Smith     }
45572a02f06SBarry Smith   } else if (isdraw) {
45672a02f06SBarry Smith     PetscDraw draw;
45772a02f06SBarry Smith     char      str[36];
45889fd9fafSBarry Smith     PetscReal x,y,bottom,h;
45972a02f06SBarry Smith 
46072a02f06SBarry Smith     ierr   = PetscViewerDrawGetDraw(viewer,0,&draw);CHKERRQ(ierr);
46172a02f06SBarry Smith     ierr   = PetscDrawGetCurrentPoint(draw,&x,&y);CHKERRQ(ierr);
462a126751eSBarry Smith     ierr   = PetscStrncpy(str,"SNES: ",sizeof(str));CHKERRQ(ierr);
463a126751eSBarry Smith     ierr   = PetscStrlcat(str,((PetscObject)snes)->type_name,sizeof(str));CHKERRQ(ierr);
46451fa3d41SBarry Smith     ierr   = PetscDrawStringBoxed(draw,x,y,PETSC_DRAW_BLUE,PETSC_DRAW_BLACK,str,NULL,&h);CHKERRQ(ierr);
46589fd9fafSBarry Smith     bottom = y - h;
46672a02f06SBarry Smith     ierr   = PetscDrawPushCurrentPoint(draw,x,bottom);CHKERRQ(ierr);
467c4646bacSPeter Brune     if (snes->ops->view) {
468c4646bacSPeter Brune       ierr = (*snes->ops->view)(snes,viewer);CHKERRQ(ierr);
469c4646bacSPeter Brune     }
470e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
471536b137fSBarry Smith   } else if (issaws) {
472d45a07a7SBarry Smith     PetscMPIInt rank;
4732657e9d9SBarry Smith     const char *name;
474d45a07a7SBarry Smith 
4752657e9d9SBarry Smith     ierr = PetscObjectGetName((PetscObject)snes,&name);CHKERRQ(ierr);
476d45a07a7SBarry Smith     ierr = MPI_Comm_rank(PETSC_COMM_WORLD,&rank);CHKERRQ(ierr);
477d45a07a7SBarry Smith     if (!((PetscObject)snes)->amsmem && !rank) {
478d45a07a7SBarry Smith       char       dir[1024];
479d45a07a7SBarry Smith 
480e04113cfSBarry Smith       ierr = PetscObjectViewSAWs((PetscObject)snes,viewer);CHKERRQ(ierr);
4812657e9d9SBarry Smith       ierr = PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/its",name);CHKERRQ(ierr);
4822657e9d9SBarry Smith       PetscStackCallSAWs(SAWs_Register,(dir,&snes->iter,1,SAWs_READ,SAWs_INT));
483bfb97211SBarry Smith       if (!snes->conv_hist) {
484a0931e03SBarry Smith         ierr = SNESSetConvergenceHistory(snes,NULL,NULL,PETSC_DECIDE,PETSC_TRUE);CHKERRQ(ierr);
485bfb97211SBarry Smith       }
4862657e9d9SBarry Smith       ierr = PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/conv_hist",name);CHKERRQ(ierr);
4872657e9d9SBarry Smith       PetscStackCallSAWs(SAWs_Register,(dir,snes->conv_hist,10,SAWs_READ,SAWs_DOUBLE));
488f05ece33SBarry Smith     }
489bfb97211SBarry Smith #endif
49072a02f06SBarry Smith   }
49172a02f06SBarry Smith   if (snes->linesearch) {
4927601faf0SJed Brown     ierr = SNESGetLineSearch(snes, &linesearch);CHKERRQ(ierr);
49385928a98SStefano Zampini     ierr = PetscViewerASCIIPushTab(viewer);CHKERRQ(ierr);
49472a02f06SBarry Smith     ierr = SNESLineSearchView(linesearch, viewer);CHKERRQ(ierr);
49585928a98SStefano Zampini     ierr = PetscViewerASCIIPopTab(viewer);CHKERRQ(ierr);
49619bcc07fSBarry Smith   }
497efd4aadfSBarry Smith   if (snes->npc && snes->usesnpc) {
49885928a98SStefano Zampini     ierr = PetscViewerASCIIPushTab(viewer);CHKERRQ(ierr);
499efd4aadfSBarry Smith     ierr = SNESView(snes->npc, viewer);CHKERRQ(ierr);
50085928a98SStefano Zampini     ierr = PetscViewerASCIIPopTab(viewer);CHKERRQ(ierr);
5014a0c5b0cSMatthew G Knepley   }
5022d53ad75SBarry Smith   ierr = PetscViewerASCIIPushTab(viewer);CHKERRQ(ierr);
5032d53ad75SBarry Smith   ierr = DMGetDMSNES(snes->dm,&dmsnes);CHKERRQ(ierr);
5042d53ad75SBarry Smith   ierr = DMSNESView(dmsnes, viewer);CHKERRQ(ierr);
5052d53ad75SBarry Smith   ierr = PetscViewerASCIIPopTab(viewer);CHKERRQ(ierr);
5062c155ee1SBarry Smith   if (snes->usesksp) {
5072c155ee1SBarry Smith     ierr = SNESGetKSP(snes,&ksp);CHKERRQ(ierr);
50885928a98SStefano Zampini     ierr = PetscViewerASCIIPushTab(viewer);CHKERRQ(ierr);
50994b7f48cSBarry Smith     ierr = KSPView(ksp,viewer);CHKERRQ(ierr);
51085928a98SStefano Zampini     ierr = PetscViewerASCIIPopTab(viewer);CHKERRQ(ierr);
5112c155ee1SBarry Smith   }
51272a02f06SBarry Smith   if (isdraw) {
51372a02f06SBarry Smith     PetscDraw draw;
51472a02f06SBarry Smith     ierr = PetscViewerDrawGetDraw(viewer,0,&draw);CHKERRQ(ierr);
51572a02f06SBarry Smith     ierr = PetscDrawPopCurrentPoint(draw);CHKERRQ(ierr);
5167f1410a3SPeter Brune   }
5173a40ed3dSBarry Smith   PetscFunctionReturn(0);
5189b94acceSBarry Smith }
5199b94acceSBarry Smith 
52076b2cf59SMatthew Knepley /*
52176b2cf59SMatthew Knepley   We retain a list of functions that also take SNES command
52276b2cf59SMatthew Knepley   line options. These are called at the end SNESSetFromOptions()
52376b2cf59SMatthew Knepley */
52476b2cf59SMatthew Knepley #define MAXSETFROMOPTIONS 5
525a7cc72afSBarry Smith static PetscInt numberofsetfromoptions;
5266849ba73SBarry Smith static PetscErrorCode (*othersetfromoptions[MAXSETFROMOPTIONS])(SNES);
52776b2cf59SMatthew Knepley 
528ac226902SBarry Smith /*@C
52976b2cf59SMatthew Knepley   SNESAddOptionsChecker - Adds an additional function to check for SNES options.
53076b2cf59SMatthew Knepley 
53176b2cf59SMatthew Knepley   Not Collective
53276b2cf59SMatthew Knepley 
53376b2cf59SMatthew Knepley   Input Parameter:
53476b2cf59SMatthew Knepley . snescheck - function that checks for options
53576b2cf59SMatthew Knepley 
53676b2cf59SMatthew Knepley   Level: developer
53776b2cf59SMatthew Knepley 
53876b2cf59SMatthew Knepley .seealso: SNESSetFromOptions()
53976b2cf59SMatthew Knepley @*/
5407087cfbeSBarry Smith PetscErrorCode  SNESAddOptionsChecker(PetscErrorCode (*snescheck)(SNES))
54176b2cf59SMatthew Knepley {
54276b2cf59SMatthew Knepley   PetscFunctionBegin;
543f23aa3ddSBarry Smith   if (numberofsetfromoptions >= MAXSETFROMOPTIONS) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE, "Too many options checkers, only %D allowed", MAXSETFROMOPTIONS);
54476b2cf59SMatthew Knepley   othersetfromoptions[numberofsetfromoptions++] = snescheck;
54576b2cf59SMatthew Knepley   PetscFunctionReturn(0);
54676b2cf59SMatthew Knepley }
54776b2cf59SMatthew Knepley 
54825acbd8eSLisandro Dalcin PETSC_INTERN PetscErrorCode SNESDefaultMatrixFreeCreate2(SNES,Vec,Mat*);
549aa3661deSLisandro Dalcin 
550ace3abfcSBarry Smith static PetscErrorCode SNESSetUpMatrixFree_Private(SNES snes, PetscBool hasOperator, PetscInt version)
551aa3661deSLisandro Dalcin {
552aa3661deSLisandro Dalcin   Mat            J;
553aa3661deSLisandro Dalcin   KSP            ksp;
554aa3661deSLisandro Dalcin   PC             pc;
555ace3abfcSBarry Smith   PetscBool      match;
556aa3661deSLisandro Dalcin   PetscErrorCode ierr;
557895c21f2SBarry Smith   MatNullSpace   nullsp;
558aa3661deSLisandro Dalcin 
559aa3661deSLisandro Dalcin   PetscFunctionBegin;
5600700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
561aa3661deSLisandro Dalcin 
56298613b67SLisandro Dalcin   if (!snes->vec_func && (snes->jacobian || snes->jacobian_pre)) {
56398613b67SLisandro Dalcin     Mat A = snes->jacobian, B = snes->jacobian_pre;
5642a7a6963SBarry Smith     ierr = MatCreateVecs(A ? A : B, NULL,&snes->vec_func);CHKERRQ(ierr);
56598613b67SLisandro Dalcin   }
56698613b67SLisandro Dalcin 
567aa3661deSLisandro Dalcin   if (version == 1) {
568aa3661deSLisandro Dalcin     ierr = MatCreateSNESMF(snes,&J);CHKERRQ(ierr);
56998613b67SLisandro Dalcin     ierr = MatMFFDSetOptionsPrefix(J,((PetscObject)snes)->prefix);CHKERRQ(ierr);
5709c6ac3b3SBarry Smith     ierr = MatSetFromOptions(J);CHKERRQ(ierr);
571aa3661deSLisandro Dalcin   } else if (version == 2) {
572e32f2f54SBarry Smith     if (!snes->vec_func) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"SNESSetFunction() must be called first");
573570b7f6dSBarry Smith #if !defined(PETSC_USE_COMPLEX) && !defined(PETSC_USE_REAL_SINGLE) && !defined(PETSC_USE_REAL___FLOAT128) && !defined(PETSC_USE_REAL___FP16)
574aa3661deSLisandro Dalcin     ierr = SNESDefaultMatrixFreeCreate2(snes,snes->vec_func,&J);CHKERRQ(ierr);
575aa3661deSLisandro Dalcin #else
576e32f2f54SBarry Smith     SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP, "matrix-free operator rutines (version 2)");
577aa3661deSLisandro Dalcin #endif
578a8248277SBarry Smith   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE, "matrix-free operator rutines, only version 1 and 2");
579aa3661deSLisandro Dalcin 
580895c21f2SBarry Smith   /* attach any user provided null space that was on Amat to the newly created matrix free matrix */
581895c21f2SBarry Smith   if (snes->jacobian) {
582895c21f2SBarry Smith     ierr = MatGetNullSpace(snes->jacobian,&nullsp);CHKERRQ(ierr);
583895c21f2SBarry Smith     if (nullsp) {
584895c21f2SBarry Smith       ierr = MatSetNullSpace(J,nullsp);CHKERRQ(ierr);
585895c21f2SBarry Smith     }
586895c21f2SBarry Smith   }
587895c21f2SBarry Smith 
588aa3661deSLisandro Dalcin   ierr = PetscInfo1(snes,"Setting default matrix-free operator routines (version %D)\n", version);CHKERRQ(ierr);
589d3462f78SMatthew Knepley   if (hasOperator) {
5903232da50SPeter Brune 
591aa3661deSLisandro Dalcin     /* This version replaces the user provided Jacobian matrix with a
592aa3661deSLisandro Dalcin        matrix-free version but still employs the user-provided preconditioner matrix. */
593aa3661deSLisandro Dalcin     ierr = SNESSetJacobian(snes,J,0,0,0);CHKERRQ(ierr);
594aa3661deSLisandro Dalcin   } else {
595aa3661deSLisandro Dalcin     /* This version replaces both the user-provided Jacobian and the user-
5963232da50SPeter Brune      provided preconditioner Jacobian with the default matrix free version. */
597efd4aadfSBarry Smith     if ((snes->npcside== PC_LEFT) && snes->npc) {
598d728fb7dSPeter Brune       if (!snes->jacobian){ierr = SNESSetJacobian(snes,J,0,0,0);CHKERRQ(ierr);}
599172a4300SPeter Brune     } else {
60028a52e04SBarry Smith       ierr = SNESSetJacobian(snes,J,J,MatMFFDComputeJacobian,0);CHKERRQ(ierr);
601172a4300SPeter Brune     }
602aa3661deSLisandro Dalcin     /* Force no preconditioner */
603aa3661deSLisandro Dalcin     ierr = SNESGetKSP(snes,&ksp);CHKERRQ(ierr);
604aa3661deSLisandro Dalcin     ierr = KSPGetPC(ksp,&pc);CHKERRQ(ierr);
605251f4c67SDmitry Karpeev     ierr = PetscObjectTypeCompare((PetscObject)pc,PCSHELL,&match);CHKERRQ(ierr);
606aa3661deSLisandro Dalcin     if (!match) {
607aa3661deSLisandro Dalcin       ierr = PetscInfo(snes,"Setting default matrix-free preconditioner routines\nThat is no preconditioner is being used\n");CHKERRQ(ierr);
608aa3661deSLisandro Dalcin       ierr = PCSetType(pc,PCNONE);CHKERRQ(ierr);
609aa3661deSLisandro Dalcin     }
610aa3661deSLisandro Dalcin   }
6116bf464f9SBarry Smith   ierr = MatDestroy(&J);CHKERRQ(ierr);
612aa3661deSLisandro Dalcin   PetscFunctionReturn(0);
613aa3661deSLisandro Dalcin }
614aa3661deSLisandro Dalcin 
615dfe15315SJed Brown static PetscErrorCode DMRestrictHook_SNESVecSol(DM dmfine,Mat Restrict,Vec Rscale,Mat Inject,DM dmcoarse,void *ctx)
616dfe15315SJed Brown {
617dfe15315SJed Brown   SNES           snes = (SNES)ctx;
618dfe15315SJed Brown   PetscErrorCode ierr;
6190298fd71SBarry Smith   Vec            Xfine,Xfine_named = NULL,Xcoarse;
620dfe15315SJed Brown 
621dfe15315SJed Brown   PetscFunctionBegin;
62216ebb321SJed Brown   if (PetscLogPrintInfo) {
62316ebb321SJed Brown     PetscInt finelevel,coarselevel,fineclevel,coarseclevel;
62416ebb321SJed Brown     ierr = DMGetRefineLevel(dmfine,&finelevel);CHKERRQ(ierr);
62516ebb321SJed Brown     ierr = DMGetCoarsenLevel(dmfine,&fineclevel);CHKERRQ(ierr);
62616ebb321SJed Brown     ierr = DMGetRefineLevel(dmcoarse,&coarselevel);CHKERRQ(ierr);
62716ebb321SJed Brown     ierr = DMGetCoarsenLevel(dmcoarse,&coarseclevel);CHKERRQ(ierr);
62816ebb321SJed Brown     ierr = PetscInfo4(dmfine,"Restricting SNES solution vector from level %D-%D to level %D-%D\n",finelevel,fineclevel,coarselevel,coarseclevel);CHKERRQ(ierr);
62916ebb321SJed Brown   }
630dfe15315SJed Brown   if (dmfine == snes->dm) Xfine = snes->vec_sol;
631dfe15315SJed Brown   else {
632dfe15315SJed Brown     ierr  = DMGetNamedGlobalVector(dmfine,"SNESVecSol",&Xfine_named);CHKERRQ(ierr);
633dfe15315SJed Brown     Xfine = Xfine_named;
634dfe15315SJed Brown   }
635dfe15315SJed Brown   ierr = DMGetNamedGlobalVector(dmcoarse,"SNESVecSol",&Xcoarse);CHKERRQ(ierr);
636907f5c5aSLawrence Mitchell   if (Inject) {
637907f5c5aSLawrence Mitchell     ierr = MatRestrict(Inject,Xfine,Xcoarse);CHKERRQ(ierr);
638907f5c5aSLawrence Mitchell   } else {
639dfe15315SJed Brown     ierr = MatRestrict(Restrict,Xfine,Xcoarse);CHKERRQ(ierr);
640dfe15315SJed Brown     ierr = VecPointwiseMult(Xcoarse,Xcoarse,Rscale);CHKERRQ(ierr);
641907f5c5aSLawrence Mitchell   }
642dfe15315SJed Brown   ierr = DMRestoreNamedGlobalVector(dmcoarse,"SNESVecSol",&Xcoarse);CHKERRQ(ierr);
643dfe15315SJed Brown   if (Xfine_named) {ierr = DMRestoreNamedGlobalVector(dmfine,"SNESVecSol",&Xfine_named);CHKERRQ(ierr);}
644dfe15315SJed Brown   PetscFunctionReturn(0);
645dfe15315SJed Brown }
646dfe15315SJed Brown 
64716ebb321SJed Brown static PetscErrorCode DMCoarsenHook_SNESVecSol(DM dm,DM dmc,void *ctx)
64816ebb321SJed Brown {
64916ebb321SJed Brown   PetscErrorCode ierr;
65016ebb321SJed Brown 
65116ebb321SJed Brown   PetscFunctionBegin;
65216ebb321SJed Brown   ierr = DMCoarsenHookAdd(dmc,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,ctx);CHKERRQ(ierr);
65316ebb321SJed Brown   PetscFunctionReturn(0);
65416ebb321SJed Brown }
65516ebb321SJed Brown 
656a6950cb2SJed Brown /* This may be called to rediscretize the operator on levels of linear multigrid. The DM shuffle is so the user can
657a6950cb2SJed Brown  * safely call SNESGetDM() in their residual evaluation routine. */
65823ee1639SBarry Smith static PetscErrorCode KSPComputeOperators_SNES(KSP ksp,Mat A,Mat B,void *ctx)
659caa4e7f2SJed Brown {
660caa4e7f2SJed Brown   SNES           snes = (SNES)ctx;
661caa4e7f2SJed Brown   PetscErrorCode ierr;
6620298fd71SBarry Smith   Vec            X,Xnamed = NULL;
663dfe15315SJed Brown   DM             dmsave;
6644e269d77SPeter Brune   void           *ctxsave;
66525ce1634SJed Brown   PetscErrorCode (*jac)(SNES,Vec,Mat,Mat,void*) = NULL;
666caa4e7f2SJed Brown 
667caa4e7f2SJed Brown   PetscFunctionBegin;
668dfe15315SJed Brown   dmsave = snes->dm;
669dfe15315SJed Brown   ierr   = KSPGetDM(ksp,&snes->dm);CHKERRQ(ierr);
670dfe15315SJed Brown   if (dmsave == snes->dm) X = snes->vec_sol; /* We are on the finest level */
671dfe15315SJed Brown   else {                                     /* We are on a coarser level, this vec was initialized using a DM restrict hook */
672dfe15315SJed Brown     ierr = DMGetNamedGlobalVector(snes->dm,"SNESVecSol",&Xnamed);CHKERRQ(ierr);
673dfe15315SJed Brown     X    = Xnamed;
6740298fd71SBarry Smith     ierr = SNESGetJacobian(snes,NULL,NULL,&jac,&ctxsave);CHKERRQ(ierr);
6754e269d77SPeter Brune     /* If the DM's don't match up, the MatFDColoring context needed for the jacobian won't match up either -- fixit. */
6768d359177SBarry Smith     if (jac == SNESComputeJacobianDefaultColor) {
6778d359177SBarry Smith       ierr = SNESSetJacobian(snes,NULL,NULL,SNESComputeJacobianDefaultColor,0);CHKERRQ(ierr);
678dfe15315SJed Brown     }
6794e269d77SPeter Brune   }
6804dde8bb0SMatthew G. Knepley   /* Make sure KSP DM has the Jacobian computation routine */
6814dde8bb0SMatthew G. Knepley   {
6824dde8bb0SMatthew G. Knepley     DMSNES sdm;
6834e269d77SPeter Brune 
6844dde8bb0SMatthew G. Knepley     ierr = DMGetDMSNES(snes->dm, &sdm);CHKERRQ(ierr);
6854dde8bb0SMatthew G. Knepley     if (!sdm->ops->computejacobian) {
6864dde8bb0SMatthew G. Knepley       ierr = DMCopyDMSNES(dmsave, snes->dm);CHKERRQ(ierr);
6874dde8bb0SMatthew G. Knepley     }
6884dde8bb0SMatthew G. Knepley   }
6892b93b426SMatthew G. Knepley   /* Compute the operators */
690d1e9a80fSBarry Smith   ierr = SNESComputeJacobian(snes,X,A,B);CHKERRQ(ierr);
6912b93b426SMatthew G. Knepley   /* Put the previous context back */
6928d359177SBarry Smith   if (snes->dm != dmsave && jac == SNESComputeJacobianDefaultColor) {
6930298fd71SBarry Smith     ierr = SNESSetJacobian(snes,NULL,NULL,jac,ctxsave);CHKERRQ(ierr);
6944e269d77SPeter Brune   }
6954e269d77SPeter Brune 
6962b93b426SMatthew G. Knepley   if (Xnamed) {ierr = DMRestoreNamedGlobalVector(snes->dm,"SNESVecSol",&Xnamed);CHKERRQ(ierr);}
697dfe15315SJed Brown   snes->dm = dmsave;
698caa4e7f2SJed Brown   PetscFunctionReturn(0);
699caa4e7f2SJed Brown }
700caa4e7f2SJed Brown 
7016cab3a1bSJed Brown /*@
7026cab3a1bSJed Brown    SNESSetUpMatrices - ensures that matrices are available for SNES, to be called by SNESSetUp_XXX()
7036cab3a1bSJed Brown 
7046cab3a1bSJed Brown    Collective
7056cab3a1bSJed Brown 
7066cab3a1bSJed Brown    Input Arguments:
7076cab3a1bSJed Brown .  snes - snes to configure
7086cab3a1bSJed Brown 
7096cab3a1bSJed Brown    Level: developer
7106cab3a1bSJed Brown 
7116cab3a1bSJed Brown .seealso: SNESSetUp()
7126cab3a1bSJed Brown @*/
7136cab3a1bSJed Brown PetscErrorCode SNESSetUpMatrices(SNES snes)
7146cab3a1bSJed Brown {
7156cab3a1bSJed Brown   PetscErrorCode ierr;
7166cab3a1bSJed Brown   DM             dm;
717942e3340SBarry Smith   DMSNES         sdm;
7186cab3a1bSJed Brown 
7196cab3a1bSJed Brown   PetscFunctionBegin;
7206cab3a1bSJed Brown   ierr = SNESGetDM(snes,&dm);CHKERRQ(ierr);
721942e3340SBarry Smith   ierr = DMGetDMSNES(dm,&sdm);CHKERRQ(ierr);
722ce94432eSBarry Smith   if (!sdm->ops->computejacobian) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_PLIB,"DMSNES not properly configured");
723f5af7f23SKarl Rupp   else if (!snes->jacobian && snes->mf) {
7246cab3a1bSJed Brown     Mat  J;
7256cab3a1bSJed Brown     void *functx;
7266cab3a1bSJed Brown     ierr = MatCreateSNESMF(snes,&J);CHKERRQ(ierr);
7276cab3a1bSJed Brown     ierr = MatMFFDSetOptionsPrefix(J,((PetscObject)snes)->prefix);CHKERRQ(ierr);
7286cab3a1bSJed Brown     ierr = MatSetFromOptions(J);CHKERRQ(ierr);
7290298fd71SBarry Smith     ierr = SNESGetFunction(snes,NULL,NULL,&functx);CHKERRQ(ierr);
7303232da50SPeter Brune     ierr = SNESSetJacobian(snes,J,J,0,0);CHKERRQ(ierr);
7316cab3a1bSJed Brown     ierr = MatDestroy(&J);CHKERRQ(ierr);
732caa4e7f2SJed Brown   } else if (snes->mf_operator && !snes->jacobian_pre && !snes->jacobian) {
7336cab3a1bSJed Brown     Mat J,B;
7346cab3a1bSJed Brown     ierr = MatCreateSNESMF(snes,&J);CHKERRQ(ierr);
7356cab3a1bSJed Brown     ierr = MatMFFDSetOptionsPrefix(J,((PetscObject)snes)->prefix);CHKERRQ(ierr);
7366cab3a1bSJed Brown     ierr = MatSetFromOptions(J);CHKERRQ(ierr);
737b412c318SBarry Smith     ierr = DMCreateMatrix(snes->dm,&B);CHKERRQ(ierr);
73806f20277SJed Brown     /* sdm->computejacobian was already set to reach here */
7390298fd71SBarry Smith     ierr = SNESSetJacobian(snes,J,B,NULL,NULL);CHKERRQ(ierr);
7406cab3a1bSJed Brown     ierr = MatDestroy(&J);CHKERRQ(ierr);
7416cab3a1bSJed Brown     ierr = MatDestroy(&B);CHKERRQ(ierr);
742caa4e7f2SJed Brown   } else if (!snes->jacobian_pre) {
7434f3e65b0SMatthew G. Knepley     PetscErrorCode (*nspconstr)(DM, PetscInt, MatNullSpace *);
7441ba9b98eSMatthew G. Knepley     PetscDS          prob;
7456cab3a1bSJed Brown     Mat              J, B;
7464f3e65b0SMatthew G. Knepley     MatNullSpace     nullspace = NULL;
7471ba9b98eSMatthew G. Knepley     PetscBool        hasPrec   = PETSC_FALSE;
7484f3e65b0SMatthew G. Knepley     PetscInt         Nf;
7491ba9b98eSMatthew G. Knepley 
7506cab3a1bSJed Brown     J    = snes->jacobian;
7511ba9b98eSMatthew G. Knepley     ierr = DMGetDS(dm, &prob);CHKERRQ(ierr);
7521ba9b98eSMatthew G. Knepley     if (prob) {ierr = PetscDSHasJacobianPreconditioner(prob, &hasPrec);CHKERRQ(ierr);}
753ec9a985fSMatthew G. Knepley     if (J)            {ierr = PetscObjectReference((PetscObject) J);CHKERRQ(ierr);}
754ec9a985fSMatthew G. Knepley     else if (hasPrec) {ierr = DMCreateMatrix(snes->dm, &J);CHKERRQ(ierr);}
755b412c318SBarry Smith     ierr = DMCreateMatrix(snes->dm, &B);CHKERRQ(ierr);
7564f3e65b0SMatthew G. Knepley     ierr = PetscDSGetNumFields(prob, &Nf);CHKERRQ(ierr);
7574f3e65b0SMatthew G. Knepley     ierr = DMGetNullSpaceConstructor(snes->dm, Nf, &nspconstr);CHKERRQ(ierr);
7584f3e65b0SMatthew G. Knepley     if (nspconstr) (*nspconstr)(snes->dm, -1, &nullspace);
7594f3e65b0SMatthew G. Knepley     ierr = MatSetNullSpace(B, nullspace);CHKERRQ(ierr);
7604f3e65b0SMatthew G. Knepley     ierr = MatNullSpaceDestroy(&nullspace);CHKERRQ(ierr);
7610298fd71SBarry Smith     ierr = SNESSetJacobian(snes, J ? J : B, B, NULL, NULL);CHKERRQ(ierr);
7621ba9b98eSMatthew G. Knepley     ierr = MatDestroy(&J);CHKERRQ(ierr);
7636cab3a1bSJed Brown     ierr = MatDestroy(&B);CHKERRQ(ierr);
7646cab3a1bSJed Brown   }
765caa4e7f2SJed Brown   {
766caa4e7f2SJed Brown     KSP ksp;
767caa4e7f2SJed Brown     ierr = SNESGetKSP(snes,&ksp);CHKERRQ(ierr);
768caa4e7f2SJed Brown     ierr = KSPSetComputeOperators(ksp,KSPComputeOperators_SNES,snes);CHKERRQ(ierr);
76916ebb321SJed Brown     ierr = DMCoarsenHookAdd(snes->dm,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,snes);CHKERRQ(ierr);
770caa4e7f2SJed Brown   }
7716cab3a1bSJed Brown   PetscFunctionReturn(0);
7726cab3a1bSJed Brown }
7736cab3a1bSJed Brown 
774fde5950dSBarry Smith /*@C
775fde5950dSBarry Smith    SNESMonitorSetFromOptions - Sets a monitor function and viewer appropriate for the type indicated by the user
776fde5950dSBarry Smith 
777fde5950dSBarry Smith    Collective on SNES
778fde5950dSBarry Smith 
779fde5950dSBarry Smith    Input Parameters:
780fde5950dSBarry Smith +  snes - SNES object you wish to monitor
781fde5950dSBarry Smith .  name - the monitor type one is seeking
782fde5950dSBarry Smith .  help - message indicating what monitoring is done
783fde5950dSBarry Smith .  manual - manual page for the monitor
784fde5950dSBarry Smith .  monitor - the monitor function
785fde5950dSBarry 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
786fde5950dSBarry Smith 
787fde5950dSBarry Smith    Level: developer
788fde5950dSBarry Smith 
789fde5950dSBarry Smith .seealso: PetscOptionsGetViewer(), PetscOptionsGetReal(), PetscOptionsHasName(), PetscOptionsGetString(),
790fde5950dSBarry Smith           PetscOptionsGetIntArray(), PetscOptionsGetRealArray(), PetscOptionsBool()
791fde5950dSBarry Smith           PetscOptionsInt(), PetscOptionsString(), PetscOptionsReal(), PetscOptionsBool(),
792fde5950dSBarry Smith           PetscOptionsName(), PetscOptionsBegin(), PetscOptionsEnd(), PetscOptionsHead(),
793fde5950dSBarry Smith           PetscOptionsStringArray(),PetscOptionsRealArray(), PetscOptionsScalar(),
794fde5950dSBarry Smith           PetscOptionsBoolGroupBegin(), PetscOptionsBoolGroup(), PetscOptionsBoolGroupEnd(),
795fde5950dSBarry Smith           PetscOptionsFList(), PetscOptionsEList()
796fde5950dSBarry Smith @*/
797d43b4f6eSBarry Smith PetscErrorCode  SNESMonitorSetFromOptions(SNES snes,const char name[],const char help[], const char manual[],PetscErrorCode (*monitor)(SNES,PetscInt,PetscReal,PetscViewerAndFormat*),PetscErrorCode (*monitorsetup)(SNES,PetscViewerAndFormat*))
798fde5950dSBarry Smith {
799fde5950dSBarry Smith   PetscErrorCode    ierr;
800fde5950dSBarry Smith   PetscViewer       viewer;
801fde5950dSBarry Smith   PetscViewerFormat format;
802fde5950dSBarry Smith   PetscBool         flg;
803fde5950dSBarry Smith 
804fde5950dSBarry Smith   PetscFunctionBegin;
80516413a6aSBarry Smith   ierr = PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject) snes)->options,((PetscObject)snes)->prefix,name,&viewer,&format,&flg);CHKERRQ(ierr);
806fde5950dSBarry Smith   if (flg) {
807d43b4f6eSBarry Smith     PetscViewerAndFormat *vf;
808d43b4f6eSBarry Smith     ierr = PetscViewerAndFormatCreate(viewer,format,&vf);CHKERRQ(ierr);
809d43b4f6eSBarry Smith     ierr = PetscObjectDereference((PetscObject)viewer);CHKERRQ(ierr);
810fde5950dSBarry Smith     if (monitorsetup) {
811d43b4f6eSBarry Smith       ierr = (*monitorsetup)(snes,vf);CHKERRQ(ierr);
812fde5950dSBarry Smith     }
813d43b4f6eSBarry Smith     ierr = SNESMonitorSet(snes,(PetscErrorCode (*)(SNES,PetscInt,PetscReal,void*))monitor,vf,(PetscErrorCode (*)(void**))PetscViewerAndFormatDestroy);CHKERRQ(ierr);
814fde5950dSBarry Smith   }
815fde5950dSBarry Smith   PetscFunctionReturn(0);
816fde5950dSBarry Smith }
817fde5950dSBarry Smith 
8189b94acceSBarry Smith /*@
81994b7f48cSBarry Smith    SNESSetFromOptions - Sets various SNES and KSP parameters from user options.
8209b94acceSBarry Smith 
821c7afd0dbSLois Curfman McInnes    Collective on SNES
822c7afd0dbSLois Curfman McInnes 
8239b94acceSBarry Smith    Input Parameter:
8249b94acceSBarry Smith .  snes - the SNES context
8259b94acceSBarry Smith 
82636851e7fSLois Curfman McInnes    Options Database Keys:
827722329fbSBarry Smith +  -snes_type <type> - newtonls, newtontr, ngmres, ncg, nrichardson, qn, vi, fas, SNESType for complete list
82882738288SBarry Smith .  -snes_stol - convergence tolerance in terms of the norm
82982738288SBarry Smith                 of the change in the solution between steps
83070441072SBarry Smith .  -snes_atol <abstol> - absolute tolerance of residual norm
831b39c3a46SLois Curfman McInnes .  -snes_rtol <rtol> - relative decrease in tolerance norm from initial
832e4d06f11SPatrick Farrell .  -snes_divergence_tolerance <divtol> - if the residual goes above divtol*rnorm0, exit with divergence
833be5caee7SBarry Smith .  -snes_force_iteration <force> - force SNESSolve() to take at least one iteration
834b39c3a46SLois Curfman McInnes .  -snes_max_it <max_it> - maximum number of iterations
835b39c3a46SLois Curfman McInnes .  -snes_max_funcs <max_funcs> - maximum number of function evaluations
8364839bfe8SBarry Smith .  -snes_max_fail <max_fail> - maximum number of line search failures allowed before stopping, default is none
837ddf469c8SBarry Smith .  -snes_max_linear_solve_fail - number of linear solver failures before SNESSolve() stops
838a8054027SBarry Smith .  -snes_lag_preconditioner <lag> - how often preconditioner is rebuilt (use -1 to never rebuild)
839e35cf81dSBarry Smith .  -snes_lag_jacobian <lag> - how often Jacobian is rebuilt (use -1 to never rebuild)
840b39c3a46SLois Curfman McInnes .  -snes_trtol <trtol> - trust region tolerance
8412492ecdbSBarry Smith .  -snes_no_convergence_test - skip convergence test in nonlinear
84282738288SBarry Smith                                solver; hence iterations will continue until max_it
8431fbbfb26SLois Curfman McInnes                                or some other criterion is reached. Saves expense
84482738288SBarry Smith                                of convergence test
845fde5950dSBarry Smith .  -snes_monitor [ascii][:filename][:viewer format] - prints residual norm at each iteration. if no filename given prints to stdout
846fde5950dSBarry Smith .  -snes_monitor_solution [ascii binary draw][:filename][:viewer format] - plots solution at each iteration
847fde5950dSBarry Smith .  -snes_monitor_residual [ascii binary draw][:filename][:viewer format] - plots residual (not its norm) at each iteration
848fde5950dSBarry Smith .  -snes_monitor_solution_update [ascii binary draw][:filename][:viewer format] - plots update to solution at each iteration
8494619e776SBarry Smith .  -snes_monitor_lg_residualnorm - plots residual norm at each iteration
850459f5d12SBarry Smith .  -snes_monitor_lg_range - plots residual norm at each iteration
851e24b481bSBarry Smith .  -snes_fd - use finite differences to compute Jacobian; very slow, only for testing
852e2e60de9SPeter Brune .  -snes_fd_color - use finite differences with coloring to compute Jacobian
8535968eb51SBarry Smith .  -snes_mf_ksp_monitor - if using matrix-free multiply then print h at each KSP iteration
854fee2055bSBarry Smith -  -snes_converged_reason - print the reason for convergence/divergence after each solve
85582738288SBarry Smith 
85682738288SBarry Smith     Options Database for Eisenstat-Walker method:
857fa9f3622SBarry Smith +  -snes_ksp_ew - use Eisenstat-Walker method for determining linear system convergence
8584b27c08aSLois Curfman McInnes .  -snes_ksp_ew_version ver - version of  Eisenstat-Walker method
85936851e7fSLois Curfman McInnes .  -snes_ksp_ew_rtol0 <rtol0> - Sets rtol0
86036851e7fSLois Curfman McInnes .  -snes_ksp_ew_rtolmax <rtolmax> - Sets rtolmax
86136851e7fSLois Curfman McInnes .  -snes_ksp_ew_gamma <gamma> - Sets gamma
86236851e7fSLois Curfman McInnes .  -snes_ksp_ew_alpha <alpha> - Sets alpha
86336851e7fSLois Curfman McInnes .  -snes_ksp_ew_alpha2 <alpha2> - Sets alpha2
86436851e7fSLois Curfman McInnes -  -snes_ksp_ew_threshold <threshold> - Sets threshold
86582738288SBarry Smith 
86611ca99fdSLois Curfman McInnes    Notes:
86711ca99fdSLois Curfman McInnes    To see all options, run your program with the -help option or consult
868a7f22e61SSatish Balay    Users-Manual: ch_snes
86983e2fdc7SBarry Smith 
87036851e7fSLois Curfman McInnes    Level: beginner
87136851e7fSLois Curfman McInnes 
8729b94acceSBarry Smith .keywords: SNES, nonlinear, set, options, database
8739b94acceSBarry Smith 
874b3cd9a81SMatthew G. Knepley .seealso: SNESSetOptionsPrefix(), SNESResetFromOptions()
8759b94acceSBarry Smith @*/
8767087cfbeSBarry Smith PetscErrorCode  SNESSetFromOptions(SNES snes)
8779b94acceSBarry Smith {
8788afaa268SBarry Smith   PetscBool      flg,pcset,persist,set;
879d8f46077SPeter Brune   PetscInt       i,indx,lag,grids;
88004d7464bSBarry Smith   const char     *deft        = SNESNEWTONLS;
88185385478SLisandro Dalcin   const char     *convtests[] = {"default","skip"};
88285385478SLisandro Dalcin   SNESKSPEW      *kctx        = NULL;
883e8105e01SRichard Katz   char           type[256], monfilename[PETSC_MAX_PATH_LEN];
88485385478SLisandro Dalcin   PetscErrorCode ierr;
885c40d0f55SPeter Brune   PCSide         pcside;
886a64e098fSPeter Brune   const char     *optionsprefix;
8879b94acceSBarry Smith 
8883a40ed3dSBarry Smith   PetscFunctionBegin;
8890700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
8900f51fdf8SToby Isaac   ierr = SNESRegisterAll();CHKERRQ(ierr);
8913194b578SJed Brown   ierr = PetscObjectOptionsBegin((PetscObject)snes);CHKERRQ(ierr);
892639ff905SBarry Smith   if (((PetscObject)snes)->type_name) deft = ((PetscObject)snes)->type_name;
893a264d7a6SBarry Smith   ierr = PetscOptionsFList("-snes_type","Nonlinear solver method","SNESSetType",SNESList,deft,type,256,&flg);CHKERRQ(ierr);
894d64ed03dSBarry Smith   if (flg) {
895186905e3SBarry Smith     ierr = SNESSetType(snes,type);CHKERRQ(ierr);
8967adad957SLisandro Dalcin   } else if (!((PetscObject)snes)->type_name) {
897186905e3SBarry Smith     ierr = SNESSetType(snes,deft);CHKERRQ(ierr);
898d64ed03dSBarry Smith   }
89994ae4db5SBarry Smith   ierr = PetscOptionsReal("-snes_stol","Stop if step length less than","SNESSetTolerances",snes->stol,&snes->stol,NULL);CHKERRQ(ierr);
90094ae4db5SBarry Smith   ierr = PetscOptionsReal("-snes_atol","Stop if function norm less than","SNESSetTolerances",snes->abstol,&snes->abstol,NULL);CHKERRQ(ierr);
901186905e3SBarry Smith 
90294ae4db5SBarry Smith   ierr = PetscOptionsReal("-snes_rtol","Stop if decrease in function norm less than","SNESSetTolerances",snes->rtol,&snes->rtol,NULL);CHKERRQ(ierr);
903e4d06f11SPatrick Farrell   ierr = PetscOptionsReal("-snes_divergence_tolerance","Stop if residual norm increases by this factor","SNESSetDivergenceTolerance",snes->divtol,&snes->divtol,NULL);CHKERRQ(ierr);
9040298fd71SBarry Smith   ierr = PetscOptionsInt("-snes_max_it","Maximum iterations","SNESSetTolerances",snes->max_its,&snes->max_its,NULL);CHKERRQ(ierr);
9050298fd71SBarry Smith   ierr = PetscOptionsInt("-snes_max_funcs","Maximum function evaluations","SNESSetTolerances",snes->max_funcs,&snes->max_funcs,NULL);CHKERRQ(ierr);
9060298fd71SBarry Smith   ierr = PetscOptionsInt("-snes_max_fail","Maximum nonlinear step failures","SNESSetMaxNonlinearStepFailures",snes->maxFailures,&snes->maxFailures,NULL);CHKERRQ(ierr);
9070298fd71SBarry Smith   ierr = PetscOptionsInt("-snes_max_linear_solve_fail","Maximum failures in linear solves allowed","SNESSetMaxLinearSolveFailures",snes->maxLinearSolveFailures,&snes->maxLinearSolveFailures,NULL);CHKERRQ(ierr);
9080298fd71SBarry Smith   ierr = PetscOptionsBool("-snes_error_if_not_converged","Generate error if solver does not converge","SNESSetErrorIfNotConverged",snes->errorifnotconverged,&snes->errorifnotconverged,NULL);CHKERRQ(ierr);
9090d6f27a8SBarry Smith   ierr = PetscOptionsBool("-snes_force_iteration","Force SNESSolve() to take at least one iteration","SNESSetForceIteration",snes->forceiteration,&snes->forceiteration,NULL);CHKERRQ(ierr);
910b351a90bSFande Kong   ierr = PetscOptionsBool("-snes_check_jacobian_domain_error","Check Jacobian domain error after Jacobian evaluation","SNESCheckJacobianDomainError",snes->checkjacdomainerror,&snes->checkjacdomainerror,NULL);CHKERRQ(ierr);
91185385478SLisandro Dalcin 
912a8054027SBarry Smith   ierr = PetscOptionsInt("-snes_lag_preconditioner","How often to rebuild preconditioner","SNESSetLagPreconditioner",snes->lagpreconditioner,&lag,&flg);CHKERRQ(ierr);
913a8054027SBarry Smith   if (flg) {
914a8054027SBarry Smith     ierr = SNESSetLagPreconditioner(snes,lag);CHKERRQ(ierr);
915a8054027SBarry Smith   }
91637ec4e1aSPeter Brune   ierr = PetscOptionsBool("-snes_lag_preconditioner_persists","Preconditioner lagging through multiple solves","SNESSetLagPreconditionerPersists",snes->lagjac_persist,&persist,&flg);CHKERRQ(ierr);
91737ec4e1aSPeter Brune   if (flg) {
91837ec4e1aSPeter Brune     ierr = SNESSetLagPreconditionerPersists(snes,persist);CHKERRQ(ierr);
91937ec4e1aSPeter Brune   }
920e35cf81dSBarry Smith   ierr = PetscOptionsInt("-snes_lag_jacobian","How often to rebuild Jacobian","SNESSetLagJacobian",snes->lagjacobian,&lag,&flg);CHKERRQ(ierr);
921e35cf81dSBarry Smith   if (flg) {
922e35cf81dSBarry Smith     ierr = SNESSetLagJacobian(snes,lag);CHKERRQ(ierr);
923e35cf81dSBarry Smith   }
92437ec4e1aSPeter Brune   ierr = PetscOptionsBool("-snes_lag_jacobian_persists","Jacobian lagging through multiple solves","SNESSetLagJacobianPersists",snes->lagjac_persist,&persist,&flg);CHKERRQ(ierr);
92537ec4e1aSPeter Brune   if (flg) {
92637ec4e1aSPeter Brune     ierr = SNESSetLagJacobianPersists(snes,persist);CHKERRQ(ierr);
92737ec4e1aSPeter Brune   }
92837ec4e1aSPeter Brune 
929efd51863SBarry Smith   ierr = PetscOptionsInt("-snes_grid_sequence","Use grid sequencing to generate initial guess","SNESSetGridSequence",snes->gridsequence,&grids,&flg);CHKERRQ(ierr);
930efd51863SBarry Smith   if (flg) {
931efd51863SBarry Smith     ierr = SNESSetGridSequence(snes,grids);CHKERRQ(ierr);
932efd51863SBarry Smith   }
933a8054027SBarry Smith 
93485385478SLisandro Dalcin   ierr = PetscOptionsEList("-snes_convergence_test","Convergence test","SNESSetConvergenceTest",convtests,2,"default",&indx,&flg);CHKERRQ(ierr);
93585385478SLisandro Dalcin   if (flg) {
93685385478SLisandro Dalcin     switch (indx) {
9378d359177SBarry Smith     case 0: ierr = SNESSetConvergenceTest(snes,SNESConvergedDefault,NULL,NULL);CHKERRQ(ierr); break;
938e2a6519dSDmitry Karpeev     case 1: ierr = SNESSetConvergenceTest(snes,SNESConvergedSkip,NULL,NULL);CHKERRQ(ierr);    break;
93985385478SLisandro Dalcin     }
94085385478SLisandro Dalcin   }
94185385478SLisandro Dalcin 
942365a6726SPeter Brune   ierr = PetscOptionsEList("-snes_norm_schedule","SNES Norm schedule","SNESSetNormSchedule",SNESNormSchedules,5,"function",&indx,&flg);CHKERRQ(ierr);
943365a6726SPeter Brune   if (flg) { ierr = SNESSetNormSchedule(snes,(SNESNormSchedule)indx);CHKERRQ(ierr); }
944fdacfa88SPeter Brune 
94547073ea2SPeter Brune   ierr = PetscOptionsEList("-snes_function_type","SNES Norm schedule","SNESSetFunctionType",SNESFunctionTypes,2,"unpreconditioned",&indx,&flg);CHKERRQ(ierr);
94647073ea2SPeter Brune   if (flg) { ierr = SNESSetFunctionType(snes,(SNESFunctionType)indx);CHKERRQ(ierr); }
947186905e3SBarry Smith 
94885385478SLisandro Dalcin   kctx = (SNESKSPEW*)snes->kspconvctx;
94985385478SLisandro Dalcin 
9500298fd71SBarry Smith   ierr = PetscOptionsBool("-snes_ksp_ew","Use Eisentat-Walker linear system convergence test","SNESKSPSetUseEW",snes->ksp_ewconv,&snes->ksp_ewconv,NULL);CHKERRQ(ierr);
951186905e3SBarry Smith 
95294ae4db5SBarry Smith   ierr = PetscOptionsInt("-snes_ksp_ew_version","Version 1, 2 or 3","SNESKSPSetParametersEW",kctx->version,&kctx->version,NULL);CHKERRQ(ierr);
95394ae4db5SBarry Smith   ierr = PetscOptionsReal("-snes_ksp_ew_rtol0","0 <= rtol0 < 1","SNESKSPSetParametersEW",kctx->rtol_0,&kctx->rtol_0,NULL);CHKERRQ(ierr);
95494ae4db5SBarry Smith   ierr = PetscOptionsReal("-snes_ksp_ew_rtolmax","0 <= rtolmax < 1","SNESKSPSetParametersEW",kctx->rtol_max,&kctx->rtol_max,NULL);CHKERRQ(ierr);
95594ae4db5SBarry Smith   ierr = PetscOptionsReal("-snes_ksp_ew_gamma","0 <= gamma <= 1","SNESKSPSetParametersEW",kctx->gamma,&kctx->gamma,NULL);CHKERRQ(ierr);
95694ae4db5SBarry Smith   ierr = PetscOptionsReal("-snes_ksp_ew_alpha","1 < alpha <= 2","SNESKSPSetParametersEW",kctx->alpha,&kctx->alpha,NULL);CHKERRQ(ierr);
95794ae4db5SBarry Smith   ierr = PetscOptionsReal("-snes_ksp_ew_alpha2","alpha2","SNESKSPSetParametersEW",kctx->alpha2,&kctx->alpha2,NULL);CHKERRQ(ierr);
95894ae4db5SBarry Smith   ierr = PetscOptionsReal("-snes_ksp_ew_threshold","0 < threshold < 1","SNESKSPSetParametersEW",kctx->threshold,&kctx->threshold,NULL);CHKERRQ(ierr);
959186905e3SBarry Smith 
96090d69ab7SBarry Smith   flg  = PETSC_FALSE;
9618afaa268SBarry Smith   ierr = PetscOptionsBool("-snes_monitor_cancel","Remove all monitors","SNESMonitorCancel",flg,&flg,&set);CHKERRQ(ierr);
9628afaa268SBarry Smith   if (set && flg) {ierr = SNESMonitorCancel(snes);CHKERRQ(ierr);}
963eabae89aSBarry Smith 
964fde5950dSBarry Smith   ierr = SNESMonitorSetFromOptions(snes,"-snes_monitor","Monitor norm of function","SNESMonitorDefault",SNESMonitorDefault,NULL);CHKERRQ(ierr);
965fde5950dSBarry Smith   ierr = SNESMonitorSetFromOptions(snes,"-snes_monitor_short","Monitor norm of function with fewer digits","SNESMonitorDefaultShort",SNESMonitorDefaultShort,NULL);CHKERRQ(ierr);
966fde5950dSBarry Smith   ierr = SNESMonitorSetFromOptions(snes,"-snes_monitor_range","Monitor range of elements of function","SNESMonitorRange",SNESMonitorRange,NULL);CHKERRQ(ierr);
967eabae89aSBarry Smith 
968fde5950dSBarry Smith   ierr = SNESMonitorSetFromOptions(snes,"-snes_monitor_ratio","Monitor ratios of the norm of function for consecutive steps","SNESMonitorRatio",SNESMonitorRatio,SNESMonitorRatioSetUp);CHKERRQ(ierr);
969fde5950dSBarry Smith   ierr = SNESMonitorSetFromOptions(snes,"-snes_monitor_field","Monitor norm of function (split into fields)","SNESMonitorDefaultField",SNESMonitorDefaultField,NULL);CHKERRQ(ierr);
970fde5950dSBarry Smith   ierr = SNESMonitorSetFromOptions(snes,"-snes_monitor_solution","View solution at each iteration","SNESMonitorSolution",SNESMonitorSolution,NULL);CHKERRQ(ierr);
971fde5950dSBarry Smith   ierr = SNESMonitorSetFromOptions(snes,"-snes_monitor_solution_update","View correction at each iteration","SNESMonitorSolutionUpdate",SNESMonitorSolutionUpdate,NULL);CHKERRQ(ierr);
972fde5950dSBarry Smith   ierr = SNESMonitorSetFromOptions(snes,"-snes_monitor_residual","View residual at each iteration","SNESMonitorResidual",SNESMonitorResidual,NULL);CHKERRQ(ierr);
973fde5950dSBarry Smith   ierr = SNESMonitorSetFromOptions(snes,"-snes_monitor_jacupdate_spectrum","Print the change in the spectrum of the Jacobian","SNESMonitorJacUpdateSpectrum",SNESMonitorJacUpdateSpectrum,NULL);CHKERRQ(ierr);
974fde5950dSBarry Smith   ierr = SNESMonitorSetFromOptions(snes,"-snes_monitor_fields","Monitor norm of function per field","SNESMonitorSet",SNESMonitorFields,NULL);CHKERRQ(ierr);
9752db13446SMatthew G. Knepley 
9765180491cSLisandro Dalcin   ierr = PetscOptionsString("-snes_monitor_python","Use Python function","SNESMonitorSet",0,monfilename,PETSC_MAX_PATH_LEN,&flg);CHKERRQ(ierr);
9775180491cSLisandro Dalcin   if (flg) {ierr = PetscPythonMonitorSet((PetscObject)snes,monfilename);CHKERRQ(ierr);}
9785180491cSLisandro Dalcin 
979fde5950dSBarry Smith 
98090d69ab7SBarry Smith   flg  = PETSC_FALSE;
9810298fd71SBarry Smith   ierr = PetscOptionsBool("-snes_monitor_lg_residualnorm","Plot function norm at each iteration","SNESMonitorLGResidualNorm",flg,&flg,NULL);CHKERRQ(ierr);
982459f5d12SBarry Smith   if (flg) {
983d96771aaSLisandro Dalcin     PetscDrawLG ctx;
984459f5d12SBarry Smith 
9856ba87a44SLisandro Dalcin     ierr = SNESMonitorLGCreate(PetscObjectComm((PetscObject)snes),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,&ctx);CHKERRQ(ierr);
986d96771aaSLisandro Dalcin     ierr = SNESMonitorSet(snes,SNESMonitorLGResidualNorm,ctx,(PetscErrorCode (*)(void**))PetscDrawLGDestroy);CHKERRQ(ierr);
987459f5d12SBarry Smith   }
98890d69ab7SBarry Smith   flg  = PETSC_FALSE;
9890298fd71SBarry Smith   ierr = PetscOptionsBool("-snes_monitor_lg_range","Plot function range at each iteration","SNESMonitorLGRange",flg,&flg,NULL);CHKERRQ(ierr);
990459f5d12SBarry Smith   if (flg) {
991459f5d12SBarry Smith     PetscViewer ctx;
992e24b481bSBarry Smith 
9936ba87a44SLisandro Dalcin     ierr = PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,&ctx);CHKERRQ(ierr);
994459f5d12SBarry Smith     ierr = SNESMonitorSet(snes,SNESMonitorLGRange,ctx,(PetscErrorCode (*)(void**))PetscViewerDestroy);CHKERRQ(ierr);
995459f5d12SBarry Smith   }
9962e7541e6SPeter Brune 
9972e7541e6SPeter Brune 
998cc0c4584SMatthew G. Knepley 
99990d69ab7SBarry Smith   flg  = PETSC_FALSE;
10008d359177SBarry Smith   ierr = PetscOptionsBool("-snes_fd","Use finite differences (slow) to compute Jacobian","SNESComputeJacobianDefault",flg,&flg,NULL);CHKERRQ(ierr);
10014b27c08aSLois Curfman McInnes   if (flg) {
10026cab3a1bSJed Brown     void    *functx;
1003b1f624c7SBarry Smith     DM      dm;
1004b1f624c7SBarry Smith     DMSNES  sdm;
1005b1f624c7SBarry Smith     ierr = SNESGetDM(snes,&dm);CHKERRQ(ierr);
1006b1f624c7SBarry Smith     ierr = DMGetDMSNES(dm,&sdm);CHKERRQ(ierr);
1007b1f624c7SBarry Smith     sdm->jacobianctx = NULL;
10080298fd71SBarry Smith     ierr = SNESGetFunction(snes,NULL,NULL,&functx);CHKERRQ(ierr);
10098d359177SBarry Smith     ierr = SNESSetJacobian(snes,snes->jacobian,snes->jacobian_pre,SNESComputeJacobianDefault,functx);CHKERRQ(ierr);
1010ae15b995SBarry Smith     ierr = PetscInfo(snes,"Setting default finite difference Jacobian matrix\n");CHKERRQ(ierr);
10119b94acceSBarry Smith   }
1012639f9d9dSBarry Smith 
101344848bc4SPeter Brune   flg  = PETSC_FALSE;
10148d359177SBarry Smith   ierr = PetscOptionsBool("-snes_fd_function","Use finite differences (slow) to compute function from user objective","SNESObjectiveComputeFunctionDefaultFD",flg,&flg,NULL);CHKERRQ(ierr);
101597584545SPeter Brune   if (flg) {
10168d359177SBarry Smith     ierr = SNESSetFunction(snes,NULL,SNESObjectiveComputeFunctionDefaultFD,NULL);CHKERRQ(ierr);
101797584545SPeter Brune   }
101897584545SPeter Brune 
101997584545SPeter Brune   flg  = PETSC_FALSE;
10208d359177SBarry Smith   ierr = PetscOptionsBool("-snes_fd_color","Use finite differences with coloring to compute Jacobian","SNESComputeJacobianDefaultColor",flg,&flg,NULL);CHKERRQ(ierr);
102144848bc4SPeter Brune   if (flg) {
1022c52e227fSPeter Brune     DM             dm;
1023c52e227fSPeter Brune     DMSNES         sdm;
1024c52e227fSPeter Brune     ierr = SNESGetDM(snes,&dm);CHKERRQ(ierr);
1025aace71b7SPeter Brune     ierr = DMGetDMSNES(dm,&sdm);CHKERRQ(ierr);
1026aace71b7SPeter Brune     sdm->jacobianctx = NULL;
10278d359177SBarry Smith     ierr = SNESSetJacobian(snes,snes->jacobian,snes->jacobian_pre,SNESComputeJacobianDefaultColor,0);CHKERRQ(ierr);
102844848bc4SPeter Brune     ierr = PetscInfo(snes,"Setting default finite difference coloring Jacobian matrix\n");CHKERRQ(ierr);
102944848bc4SPeter Brune   }
103044848bc4SPeter Brune 
1031aa3661deSLisandro Dalcin   flg  = PETSC_FALSE;
1032f871313dSBarry Smith   ierr = PetscOptionsBool("-snes_mf_operator","Use a Matrix-Free Jacobian with user-provided preconditioner matrix","SNESSetUseMatrixFree",PETSC_FALSE,&snes->mf_operator,&flg);CHKERRQ(ierr);
1033d8f46077SPeter Brune   if (flg && snes->mf_operator) {
1034a8248277SBarry Smith     snes->mf_operator = PETSC_TRUE;
1035d8f46077SPeter Brune     snes->mf          = PETSC_TRUE;
1036a8248277SBarry Smith   }
1037aa3661deSLisandro Dalcin   flg  = PETSC_FALSE;
1038f871313dSBarry Smith   ierr = PetscOptionsBool("-snes_mf","Use a Matrix-Free Jacobian with no preconditioner matrix","SNESSetUseMatrixFree",PETSC_FALSE,&snes->mf,&flg);CHKERRQ(ierr);
1039d8f46077SPeter Brune   if (!flg && snes->mf_operator) snes->mf = PETSC_TRUE;
1040d8f46077SPeter Brune   ierr = PetscOptionsInt("-snes_mf_version","Matrix-Free routines version 1 or 2","None",snes->mf_version,&snes->mf_version,0);CHKERRQ(ierr);
1041d28543b3SPeter Brune 
1042c40d0f55SPeter Brune   flg  = PETSC_FALSE;
1043be95d8f1SBarry Smith   ierr = SNESGetNPCSide(snes,&pcside);CHKERRQ(ierr);
1044be95d8f1SBarry Smith   ierr = PetscOptionsEnum("-snes_npc_side","SNES nonlinear preconditioner side","SNESSetNPCSide",PCSides,(PetscEnum)pcside,(PetscEnum*)&pcside,&flg);CHKERRQ(ierr);
1045be95d8f1SBarry Smith   if (flg) {ierr = SNESSetNPCSide(snes,pcside);CHKERRQ(ierr);}
1046c40d0f55SPeter Brune 
1047e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
10488a70d858SHong Zhang   /*
10498a70d858SHong Zhang     Publish convergence information using SAWs
10508a70d858SHong Zhang   */
10518a70d858SHong Zhang   flg  = PETSC_FALSE;
10528a70d858SHong Zhang   ierr = PetscOptionsBool("-snes_monitor_saws","Publish SNES progress using SAWs","SNESMonitorSet",flg,&flg,NULL);CHKERRQ(ierr);
10538a70d858SHong Zhang   if (flg) {
10548a70d858SHong Zhang     void *ctx;
10558a70d858SHong Zhang     ierr = SNESMonitorSAWsCreate(snes,&ctx);CHKERRQ(ierr);
10568a70d858SHong Zhang     ierr = SNESMonitorSet(snes,SNESMonitorSAWs,ctx,SNESMonitorSAWsDestroy);CHKERRQ(ierr);
10578a70d858SHong Zhang   }
10588a70d858SHong Zhang #endif
10598a70d858SHong Zhang #if defined(PETSC_HAVE_SAWS)
1060b90c6cbeSBarry Smith   {
1061b90c6cbeSBarry Smith   PetscBool set;
1062b90c6cbeSBarry Smith   flg  = PETSC_FALSE;
10638a70d858SHong Zhang   ierr = PetscOptionsBool("-snes_saws_block","Block for SAWs at end of SNESSolve","PetscObjectSAWsBlock",((PetscObject)snes)->amspublishblock,&flg,&set);CHKERRQ(ierr);
1064b90c6cbeSBarry Smith   if (set) {
1065e04113cfSBarry Smith     ierr = PetscObjectSAWsSetBlock((PetscObject)snes,flg);CHKERRQ(ierr);
1066b90c6cbeSBarry Smith   }
1067b90c6cbeSBarry Smith   }
1068b90c6cbeSBarry Smith #endif
1069b90c6cbeSBarry Smith 
107076b2cf59SMatthew Knepley   for (i = 0; i < numberofsetfromoptions; i++) {
107176b2cf59SMatthew Knepley     ierr = (*othersetfromoptions[i])(snes);CHKERRQ(ierr);
107276b2cf59SMatthew Knepley   }
107376b2cf59SMatthew Knepley 
1074e7788613SBarry Smith   if (snes->ops->setfromoptions) {
1075e55864a3SBarry Smith     ierr = (*snes->ops->setfromoptions)(PetscOptionsObject,snes);CHKERRQ(ierr);
1076639f9d9dSBarry Smith   }
10775d973c19SBarry Smith 
10785d973c19SBarry Smith   /* process any options handlers added with PetscObjectAddOptionsHandler() */
10790633abcbSJed Brown   ierr = PetscObjectProcessOptionsHandlers(PetscOptionsObject,(PetscObject)snes);CHKERRQ(ierr);
1080b0a32e0cSBarry Smith   ierr = PetscOptionsEnd();CHKERRQ(ierr);
10814bbc92c1SBarry Smith 
10829e764e56SPeter Brune   if (!snes->linesearch) {
10837601faf0SJed Brown     ierr = SNESGetLineSearch(snes, &snes->linesearch);CHKERRQ(ierr);
10849e764e56SPeter Brune   }
1085f1c6b773SPeter Brune   ierr = SNESLineSearchSetFromOptions(snes->linesearch);CHKERRQ(ierr);
10869e764e56SPeter Brune 
10876aa5e7e9SBarry Smith   if (snes->usesksp) {
10886991f827SBarry Smith     if (!snes->ksp) {ierr = SNESGetKSP(snes,&snes->ksp);CHKERRQ(ierr);}
10896991f827SBarry Smith     ierr = KSPSetOperators(snes->ksp,snes->jacobian,snes->jacobian_pre);CHKERRQ(ierr);
10906991f827SBarry Smith     ierr = KSPSetFromOptions(snes->ksp);CHKERRQ(ierr);
10916aa5e7e9SBarry Smith   }
10926991f827SBarry Smith 
1093be95d8f1SBarry Smith   /* if someone has set the SNES NPC type, create it. */
109451e86f29SPeter Brune   ierr = SNESGetOptionsPrefix(snes, &optionsprefix);CHKERRQ(ierr);
1095c5929fdfSBarry Smith   ierr = PetscOptionsHasName(((PetscObject)snes)->options,optionsprefix, "-npc_snes_type", &pcset);CHKERRQ(ierr);
1096efd4aadfSBarry Smith   if (pcset && (!snes->npc)) {
1097efd4aadfSBarry Smith     ierr = SNESGetNPC(snes, &snes->npc);CHKERRQ(ierr);
109851e86f29SPeter Brune   }
1099b3cd9a81SMatthew G. Knepley   snes->setfromoptionscalled++;
1100b3cd9a81SMatthew G. Knepley   PetscFunctionReturn(0);
1101b3cd9a81SMatthew G. Knepley }
1102b3cd9a81SMatthew G. Knepley 
1103b3cd9a81SMatthew G. Knepley /*@
1104b3cd9a81SMatthew G. Knepley    SNESResetFromOptions - Sets various SNES and KSP parameters from user options ONLY if the SNES was previously set from options
1105b3cd9a81SMatthew G. Knepley 
1106b3cd9a81SMatthew G. Knepley    Collective on SNES
1107b3cd9a81SMatthew G. Knepley 
1108b3cd9a81SMatthew G. Knepley    Input Parameter:
1109b3cd9a81SMatthew G. Knepley .  snes - the SNES context
1110b3cd9a81SMatthew G. Knepley 
1111b3cd9a81SMatthew G. Knepley    Level: beginner
1112b3cd9a81SMatthew G. Knepley 
1113b3cd9a81SMatthew G. Knepley .keywords: SNES, nonlinear, set, options, database
1114b3cd9a81SMatthew G. Knepley 
1115b3cd9a81SMatthew G. Knepley .seealso: SNESSetFromOptions(), SNESSetOptionsPrefix()
1116b3cd9a81SMatthew G. Knepley @*/
1117b3cd9a81SMatthew G. Knepley PetscErrorCode SNESResetFromOptions(SNES snes)
1118b3cd9a81SMatthew G. Knepley {
1119b3cd9a81SMatthew G. Knepley   PetscErrorCode ierr;
1120b3cd9a81SMatthew G. Knepley 
1121b3cd9a81SMatthew G. Knepley   PetscFunctionBegin;
1122b3cd9a81SMatthew G. Knepley   if (snes->setfromoptionscalled) {ierr = SNESSetFromOptions(snes);CHKERRQ(ierr);}
11233a40ed3dSBarry Smith   PetscFunctionReturn(0);
11249b94acceSBarry Smith }
11259b94acceSBarry Smith 
1126bb9467b5SJed Brown /*@C
1127d25893d9SBarry Smith    SNESSetComputeApplicationContext - Sets an optional function to compute a user-defined context for
1128d25893d9SBarry Smith    the nonlinear solvers.
1129d25893d9SBarry Smith 
1130d25893d9SBarry Smith    Logically Collective on SNES
1131d25893d9SBarry Smith 
1132d25893d9SBarry Smith    Input Parameters:
1133d25893d9SBarry Smith +  snes - the SNES context
1134d25893d9SBarry Smith .  compute - function to compute the context
1135d25893d9SBarry Smith -  destroy - function to destroy the context
1136d25893d9SBarry Smith 
1137d25893d9SBarry Smith    Level: intermediate
1138d25893d9SBarry Smith 
1139bb9467b5SJed Brown    Notes:
1140bb9467b5SJed Brown    This function is currently not available from Fortran.
1141bb9467b5SJed Brown 
1142d25893d9SBarry Smith .keywords: SNES, nonlinear, set, application, context
1143d25893d9SBarry Smith 
1144d25893d9SBarry Smith .seealso: SNESGetApplicationContext(), SNESSetComputeApplicationContext(), SNESGetApplicationContext()
1145d25893d9SBarry Smith @*/
1146d25893d9SBarry Smith PetscErrorCode  SNESSetComputeApplicationContext(SNES snes,PetscErrorCode (*compute)(SNES,void**),PetscErrorCode (*destroy)(void**))
1147d25893d9SBarry Smith {
1148d25893d9SBarry Smith   PetscFunctionBegin;
1149d25893d9SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
1150d25893d9SBarry Smith   snes->ops->usercompute = compute;
1151d25893d9SBarry Smith   snes->ops->userdestroy = destroy;
1152d25893d9SBarry Smith   PetscFunctionReturn(0);
1153d25893d9SBarry Smith }
1154a847f771SSatish Balay 
1155b07ff414SBarry Smith /*@
11569b94acceSBarry Smith    SNESSetApplicationContext - Sets the optional user-defined context for
11579b94acceSBarry Smith    the nonlinear solvers.
11589b94acceSBarry Smith 
11593f9fe445SBarry Smith    Logically Collective on SNES
1160fee21e36SBarry Smith 
1161c7afd0dbSLois Curfman McInnes    Input Parameters:
1162c7afd0dbSLois Curfman McInnes +  snes - the SNES context
1163c7afd0dbSLois Curfman McInnes -  usrP - optional user context
1164c7afd0dbSLois Curfman McInnes 
116536851e7fSLois Curfman McInnes    Level: intermediate
116636851e7fSLois Curfman McInnes 
116795452b02SPatrick Sanan    Fortran Notes:
116895452b02SPatrick Sanan     To use this from Fortran you must write a Fortran interface definition for this
1169daf670e6SBarry Smith     function that tells Fortran the Fortran derived data type that you are passing in as the ctx argument.
1170daf670e6SBarry Smith 
11719b94acceSBarry Smith .keywords: SNES, nonlinear, set, application, context
11729b94acceSBarry Smith 
1173ecaffddaSVictor Eijkhout .seealso: SNESGetApplicationContext()
11749b94acceSBarry Smith @*/
11757087cfbeSBarry Smith PetscErrorCode  SNESSetApplicationContext(SNES snes,void *usrP)
11769b94acceSBarry Smith {
11771b2093e4SBarry Smith   PetscErrorCode ierr;
1178b07ff414SBarry Smith   KSP            ksp;
11791b2093e4SBarry Smith 
11803a40ed3dSBarry Smith   PetscFunctionBegin;
11810700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
1182b07ff414SBarry Smith   ierr       = SNESGetKSP(snes,&ksp);CHKERRQ(ierr);
1183b07ff414SBarry Smith   ierr       = KSPSetApplicationContext(ksp,usrP);CHKERRQ(ierr);
11849b94acceSBarry Smith   snes->user = usrP;
11853a40ed3dSBarry Smith   PetscFunctionReturn(0);
11869b94acceSBarry Smith }
118774679c65SBarry Smith 
1188b07ff414SBarry Smith /*@
11899b94acceSBarry Smith    SNESGetApplicationContext - Gets the user-defined context for the
11909b94acceSBarry Smith    nonlinear solvers.
11919b94acceSBarry Smith 
1192c7afd0dbSLois Curfman McInnes    Not Collective
1193c7afd0dbSLois Curfman McInnes 
11949b94acceSBarry Smith    Input Parameter:
11959b94acceSBarry Smith .  snes - SNES context
11969b94acceSBarry Smith 
11979b94acceSBarry Smith    Output Parameter:
11989b94acceSBarry Smith .  usrP - user context
11999b94acceSBarry Smith 
120095452b02SPatrick Sanan    Fortran Notes:
120195452b02SPatrick Sanan     To use this from Fortran you must write a Fortran interface definition for this
1202daf670e6SBarry Smith     function that tells Fortran the Fortran derived data type that you are passing in as the ctx argument.
1203daf670e6SBarry Smith 
120436851e7fSLois Curfman McInnes    Level: intermediate
120536851e7fSLois Curfman McInnes 
12069b94acceSBarry Smith .keywords: SNES, nonlinear, get, application, context
12079b94acceSBarry Smith 
12089b94acceSBarry Smith .seealso: SNESSetApplicationContext()
12099b94acceSBarry Smith @*/
1210e71120c6SJed Brown PetscErrorCode  SNESGetApplicationContext(SNES snes,void *usrP)
12119b94acceSBarry Smith {
12123a40ed3dSBarry Smith   PetscFunctionBegin;
12130700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
1214e71120c6SJed Brown   *(void**)usrP = snes->user;
12153a40ed3dSBarry Smith   PetscFunctionReturn(0);
12169b94acceSBarry Smith }
121774679c65SBarry Smith 
12189b94acceSBarry Smith /*@
12193565c898SBarry Smith    SNESSetUseMatrixFree - indicates that SNES should use matrix free finite difference matrix vector products internally to apply
12203565c898SBarry Smith                           the Jacobian.
12213565c898SBarry Smith 
12223565c898SBarry Smith    Collective on SNES
12233565c898SBarry Smith 
12243565c898SBarry Smith    Input Parameters:
12253565c898SBarry Smith +  snes - SNES context
12263565c898SBarry Smith .  mf - use matrix-free for both the Amat and Pmat used by SNESSetJacobian(), both the Amat and Pmat set in SNESSetJacobian() will be ignored
12273565c898SBarry Smith -  mf_operator - use matrix-free only for the Amat used by SNESSetJacobian(), this means the user provided Pmat will continue to be used
12283565c898SBarry Smith 
12293565c898SBarry Smith    Options Database:
12303565c898SBarry Smith + -snes_mf - use matrix free for both the mat and pmat operator
12313565c898SBarry Smith - -snes_mf_operator - use matrix free only for the mat operator
12323565c898SBarry Smith 
12333565c898SBarry Smith    Level: intermediate
12343565c898SBarry Smith 
12353565c898SBarry Smith .keywords: SNES, nonlinear, get, iteration, number,
12363565c898SBarry Smith 
12373565c898SBarry Smith .seealso:   SNESGetUseMatrixFree(), MatCreateSNESMF()
12383565c898SBarry Smith @*/
12393565c898SBarry Smith PetscErrorCode  SNESSetUseMatrixFree(SNES snes,PetscBool mf_operator,PetscBool mf)
12403565c898SBarry Smith {
12413565c898SBarry Smith   PetscFunctionBegin;
12423565c898SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
124388b4c220SStefano Zampini   PetscValidLogicalCollectiveBool(snes,mf_operator,2);
124488b4c220SStefano Zampini   PetscValidLogicalCollectiveBool(snes,mf,3);
12453565c898SBarry Smith   if (mf && !mf_operator) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_INCOMP,"If using mf must also use mf_operator");
12463565c898SBarry Smith   snes->mf          = mf;
12473565c898SBarry Smith   snes->mf_operator = mf_operator;
12483565c898SBarry Smith   PetscFunctionReturn(0);
12493565c898SBarry Smith }
12503565c898SBarry Smith 
12513565c898SBarry Smith /*@
12523565c898SBarry Smith    SNESGetUseMatrixFree - indicates if the SNES uses matrix free finite difference matrix vector products to apply
12533565c898SBarry Smith                           the Jacobian.
12543565c898SBarry Smith 
12553565c898SBarry Smith    Collective on SNES
12563565c898SBarry Smith 
12573565c898SBarry Smith    Input Parameter:
12583565c898SBarry Smith .  snes - SNES context
12593565c898SBarry Smith 
12603565c898SBarry Smith    Output Parameters:
12613565c898SBarry Smith +  mf - use matrix-free for both the Amat and Pmat used by SNESSetJacobian(), both the Amat and Pmat set in SNESSetJacobian() will be ignored
12623565c898SBarry Smith -  mf_operator - use matrix-free only for the Amat used by SNESSetJacobian(), this means the user provided Pmat will continue to be used
12633565c898SBarry Smith 
12643565c898SBarry Smith    Options Database:
12653565c898SBarry Smith + -snes_mf - use matrix free for both the mat and pmat operator
12663565c898SBarry Smith - -snes_mf_operator - use matrix free only for the mat operator
12673565c898SBarry Smith 
12683565c898SBarry Smith    Level: intermediate
12693565c898SBarry Smith 
12703565c898SBarry Smith .keywords: SNES, nonlinear, get, iteration, number,
12713565c898SBarry Smith 
12723565c898SBarry Smith .seealso:   SNESSetUseMatrixFree(), MatCreateSNESMF()
12733565c898SBarry Smith @*/
12743565c898SBarry Smith PetscErrorCode  SNESGetUseMatrixFree(SNES snes,PetscBool *mf_operator,PetscBool *mf)
12753565c898SBarry Smith {
12763565c898SBarry Smith   PetscFunctionBegin;
12773565c898SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
12783565c898SBarry Smith   if (mf)          *mf          = snes->mf;
12793565c898SBarry Smith   if (mf_operator) *mf_operator = snes->mf_operator;
12803565c898SBarry Smith   PetscFunctionReturn(0);
12813565c898SBarry Smith }
12823565c898SBarry Smith 
12833565c898SBarry Smith /*@
1284c8228a4eSBarry Smith    SNESGetIterationNumber - Gets the number of nonlinear iterations completed
1285c8228a4eSBarry Smith    at this time.
12869b94acceSBarry Smith 
1287c7afd0dbSLois Curfman McInnes    Not Collective
1288c7afd0dbSLois Curfman McInnes 
12899b94acceSBarry Smith    Input Parameter:
12909b94acceSBarry Smith .  snes - SNES context
12919b94acceSBarry Smith 
12929b94acceSBarry Smith    Output Parameter:
12939b94acceSBarry Smith .  iter - iteration number
12949b94acceSBarry Smith 
1295c8228a4eSBarry Smith    Notes:
1296c8228a4eSBarry Smith    For example, during the computation of iteration 2 this would return 1.
1297c8228a4eSBarry Smith 
1298c8228a4eSBarry Smith    This is useful for using lagged Jacobians (where one does not recompute the
129908405cd6SLois Curfman McInnes    Jacobian at each SNES iteration). For example, the code
130008405cd6SLois Curfman McInnes .vb
130108405cd6SLois Curfman McInnes       ierr = SNESGetIterationNumber(snes,&it);
130208405cd6SLois Curfman McInnes       if (!(it % 2)) {
130308405cd6SLois Curfman McInnes         [compute Jacobian here]
130408405cd6SLois Curfman McInnes       }
130508405cd6SLois Curfman McInnes .ve
1306c8228a4eSBarry Smith    can be used in your ComputeJacobian() function to cause the Jacobian to be
130708405cd6SLois Curfman McInnes    recomputed every second SNES iteration.
1308c8228a4eSBarry Smith 
1309c04deec6SBarry Smith    After the SNES solve is complete this will return the number of nonlinear iterations used.
1310c04deec6SBarry Smith 
131136851e7fSLois Curfman McInnes    Level: intermediate
131236851e7fSLois Curfman McInnes 
13132b668275SBarry Smith .keywords: SNES, nonlinear, get, iteration, number,
13142b668275SBarry Smith 
131571dbe336SPeter Brune .seealso:   SNESGetLinearSolveIterations()
13169b94acceSBarry Smith @*/
13177087cfbeSBarry Smith PetscErrorCode  SNESGetIterationNumber(SNES snes,PetscInt *iter)
13189b94acceSBarry Smith {
13193a40ed3dSBarry Smith   PetscFunctionBegin;
13200700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
13214482741eSBarry Smith   PetscValidIntPointer(iter,2);
13229b94acceSBarry Smith   *iter = snes->iter;
13233a40ed3dSBarry Smith   PetscFunctionReturn(0);
13249b94acceSBarry Smith }
132574679c65SBarry Smith 
1326360c497dSPeter Brune /*@
1327360c497dSPeter Brune    SNESSetIterationNumber - Sets the current iteration number.
1328360c497dSPeter Brune 
1329360c497dSPeter Brune    Not Collective
1330360c497dSPeter Brune 
1331360c497dSPeter Brune    Input Parameter:
1332360c497dSPeter Brune .  snes - SNES context
1333360c497dSPeter Brune .  iter - iteration number
1334360c497dSPeter Brune 
1335360c497dSPeter Brune    Level: developer
1336360c497dSPeter Brune 
1337360c497dSPeter Brune .keywords: SNES, nonlinear, set, iteration, number,
1338360c497dSPeter Brune 
133971dbe336SPeter Brune .seealso:   SNESGetLinearSolveIterations()
1340360c497dSPeter Brune @*/
1341360c497dSPeter Brune PetscErrorCode  SNESSetIterationNumber(SNES snes,PetscInt iter)
1342360c497dSPeter Brune {
1343360c497dSPeter Brune   PetscErrorCode ierr;
1344360c497dSPeter Brune 
1345360c497dSPeter Brune   PetscFunctionBegin;
1346360c497dSPeter Brune   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
1347e04113cfSBarry Smith   ierr       = PetscObjectSAWsTakeAccess((PetscObject)snes);CHKERRQ(ierr);
1348360c497dSPeter Brune   snes->iter = iter;
1349e04113cfSBarry Smith   ierr       = PetscObjectSAWsGrantAccess((PetscObject)snes);CHKERRQ(ierr);
1350360c497dSPeter Brune   PetscFunctionReturn(0);
1351360c497dSPeter Brune }
1352360c497dSPeter Brune 
13539b94acceSBarry Smith /*@
1354b850b91aSLisandro Dalcin    SNESGetNonlinearStepFailures - Gets the number of unsuccessful steps
13559b94acceSBarry Smith    attempted by the nonlinear solver.
13569b94acceSBarry Smith 
1357c7afd0dbSLois Curfman McInnes    Not Collective
1358c7afd0dbSLois Curfman McInnes 
13599b94acceSBarry Smith    Input Parameter:
13609b94acceSBarry Smith .  snes - SNES context
13619b94acceSBarry Smith 
13629b94acceSBarry Smith    Output Parameter:
13639b94acceSBarry Smith .  nfails - number of unsuccessful steps attempted
13649b94acceSBarry Smith 
1365c96a6f78SLois Curfman McInnes    Notes:
1366c96a6f78SLois Curfman McInnes    This counter is reset to zero for each successive call to SNESSolve().
1367c96a6f78SLois Curfman McInnes 
136836851e7fSLois Curfman McInnes    Level: intermediate
136936851e7fSLois Curfman McInnes 
13709b94acceSBarry Smith .keywords: SNES, nonlinear, get, number, unsuccessful, steps
137158ebbce7SBarry Smith 
1372e1c61ce8SBarry Smith .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(),
137358ebbce7SBarry Smith           SNESSetMaxNonlinearStepFailures(), SNESGetMaxNonlinearStepFailures()
13749b94acceSBarry Smith @*/
13757087cfbeSBarry Smith PetscErrorCode  SNESGetNonlinearStepFailures(SNES snes,PetscInt *nfails)
13769b94acceSBarry Smith {
13773a40ed3dSBarry Smith   PetscFunctionBegin;
13780700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
13794482741eSBarry Smith   PetscValidIntPointer(nfails,2);
138050ffb88aSMatthew Knepley   *nfails = snes->numFailures;
138150ffb88aSMatthew Knepley   PetscFunctionReturn(0);
138250ffb88aSMatthew Knepley }
138350ffb88aSMatthew Knepley 
138450ffb88aSMatthew Knepley /*@
1385b850b91aSLisandro Dalcin    SNESSetMaxNonlinearStepFailures - Sets the maximum number of unsuccessful steps
138650ffb88aSMatthew Knepley    attempted by the nonlinear solver before it gives up.
138750ffb88aSMatthew Knepley 
138850ffb88aSMatthew Knepley    Not Collective
138950ffb88aSMatthew Knepley 
139050ffb88aSMatthew Knepley    Input Parameters:
139150ffb88aSMatthew Knepley +  snes     - SNES context
139250ffb88aSMatthew Knepley -  maxFails - maximum of unsuccessful steps
139350ffb88aSMatthew Knepley 
139450ffb88aSMatthew Knepley    Level: intermediate
139550ffb88aSMatthew Knepley 
139650ffb88aSMatthew Knepley .keywords: SNES, nonlinear, set, maximum, unsuccessful, steps
139758ebbce7SBarry Smith 
1398e1c61ce8SBarry Smith .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(),
139958ebbce7SBarry Smith           SNESGetMaxNonlinearStepFailures(), SNESGetNonlinearStepFailures()
140050ffb88aSMatthew Knepley @*/
14017087cfbeSBarry Smith PetscErrorCode  SNESSetMaxNonlinearStepFailures(SNES snes, PetscInt maxFails)
140250ffb88aSMatthew Knepley {
140350ffb88aSMatthew Knepley   PetscFunctionBegin;
14040700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
140550ffb88aSMatthew Knepley   snes->maxFailures = maxFails;
140650ffb88aSMatthew Knepley   PetscFunctionReturn(0);
140750ffb88aSMatthew Knepley }
140850ffb88aSMatthew Knepley 
140950ffb88aSMatthew Knepley /*@
1410b850b91aSLisandro Dalcin    SNESGetMaxNonlinearStepFailures - Gets the maximum number of unsuccessful steps
141150ffb88aSMatthew Knepley    attempted by the nonlinear solver before it gives up.
141250ffb88aSMatthew Knepley 
141350ffb88aSMatthew Knepley    Not Collective
141450ffb88aSMatthew Knepley 
141550ffb88aSMatthew Knepley    Input Parameter:
141650ffb88aSMatthew Knepley .  snes     - SNES context
141750ffb88aSMatthew Knepley 
141850ffb88aSMatthew Knepley    Output Parameter:
141950ffb88aSMatthew Knepley .  maxFails - maximum of unsuccessful steps
142050ffb88aSMatthew Knepley 
142150ffb88aSMatthew Knepley    Level: intermediate
142250ffb88aSMatthew Knepley 
142350ffb88aSMatthew Knepley .keywords: SNES, nonlinear, get, maximum, unsuccessful, steps
142458ebbce7SBarry Smith 
1425e1c61ce8SBarry Smith .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(),
142658ebbce7SBarry Smith           SNESSetMaxNonlinearStepFailures(), SNESGetNonlinearStepFailures()
142758ebbce7SBarry Smith 
142850ffb88aSMatthew Knepley @*/
14297087cfbeSBarry Smith PetscErrorCode  SNESGetMaxNonlinearStepFailures(SNES snes, PetscInt *maxFails)
143050ffb88aSMatthew Knepley {
143150ffb88aSMatthew Knepley   PetscFunctionBegin;
14320700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
14334482741eSBarry Smith   PetscValidIntPointer(maxFails,2);
143450ffb88aSMatthew Knepley   *maxFails = snes->maxFailures;
14353a40ed3dSBarry Smith   PetscFunctionReturn(0);
14369b94acceSBarry Smith }
1437a847f771SSatish Balay 
14382541af92SBarry Smith /*@
14392541af92SBarry Smith    SNESGetNumberFunctionEvals - Gets the number of user provided function evaluations
14402541af92SBarry Smith      done by SNES.
14412541af92SBarry Smith 
14422541af92SBarry Smith    Not Collective
14432541af92SBarry Smith 
14442541af92SBarry Smith    Input Parameter:
14452541af92SBarry Smith .  snes     - SNES context
14462541af92SBarry Smith 
14472541af92SBarry Smith    Output Parameter:
14482541af92SBarry Smith .  nfuncs - number of evaluations
14492541af92SBarry Smith 
14502541af92SBarry Smith    Level: intermediate
14512541af92SBarry Smith 
145295452b02SPatrick Sanan    Notes:
145395452b02SPatrick Sanan     Reset every time SNESSolve is called unless SNESSetCountersReset() is used.
1454971e163fSPeter Brune 
14552541af92SBarry Smith .keywords: SNES, nonlinear, get, maximum, unsuccessful, steps
145658ebbce7SBarry Smith 
1457971e163fSPeter Brune .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(), SNESSetCountersReset()
14582541af92SBarry Smith @*/
14597087cfbeSBarry Smith PetscErrorCode  SNESGetNumberFunctionEvals(SNES snes, PetscInt *nfuncs)
14602541af92SBarry Smith {
14612541af92SBarry Smith   PetscFunctionBegin;
14620700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
14632541af92SBarry Smith   PetscValidIntPointer(nfuncs,2);
14642541af92SBarry Smith   *nfuncs = snes->nfuncs;
14652541af92SBarry Smith   PetscFunctionReturn(0);
14662541af92SBarry Smith }
14672541af92SBarry Smith 
14683d4c4710SBarry Smith /*@
14693d4c4710SBarry Smith    SNESGetLinearSolveFailures - Gets the number of failed (non-converged)
14703d4c4710SBarry Smith    linear solvers.
14713d4c4710SBarry Smith 
14723d4c4710SBarry Smith    Not Collective
14733d4c4710SBarry Smith 
14743d4c4710SBarry Smith    Input Parameter:
14753d4c4710SBarry Smith .  snes - SNES context
14763d4c4710SBarry Smith 
14773d4c4710SBarry Smith    Output Parameter:
14783d4c4710SBarry Smith .  nfails - number of failed solves
14793d4c4710SBarry Smith 
14809d85da0cSMatthew G. Knepley    Level: intermediate
14819d85da0cSMatthew G. Knepley 
14829d85da0cSMatthew G. Knepley    Options Database Keys:
14839d85da0cSMatthew G. Knepley . -snes_max_linear_solve_fail <num> - The number of failures before the solve is terminated
14849d85da0cSMatthew G. Knepley 
14853d4c4710SBarry Smith    Notes:
14863d4c4710SBarry Smith    This counter is reset to zero for each successive call to SNESSolve().
14873d4c4710SBarry Smith 
14883d4c4710SBarry Smith .keywords: SNES, nonlinear, get, number, unsuccessful, steps
148958ebbce7SBarry Smith 
1490e1c61ce8SBarry Smith .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures()
14913d4c4710SBarry Smith @*/
14927087cfbeSBarry Smith PetscErrorCode  SNESGetLinearSolveFailures(SNES snes,PetscInt *nfails)
14933d4c4710SBarry Smith {
14943d4c4710SBarry Smith   PetscFunctionBegin;
14950700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
14963d4c4710SBarry Smith   PetscValidIntPointer(nfails,2);
14973d4c4710SBarry Smith   *nfails = snes->numLinearSolveFailures;
14983d4c4710SBarry Smith   PetscFunctionReturn(0);
14993d4c4710SBarry Smith }
15003d4c4710SBarry Smith 
15013d4c4710SBarry Smith /*@
15023d4c4710SBarry Smith    SNESSetMaxLinearSolveFailures - the number of failed linear solve attempts
15033d4c4710SBarry Smith    allowed before SNES returns with a diverged reason of SNES_DIVERGED_LINEAR_SOLVE
15043d4c4710SBarry Smith 
15053f9fe445SBarry Smith    Logically Collective on SNES
15063d4c4710SBarry Smith 
15073d4c4710SBarry Smith    Input Parameters:
15083d4c4710SBarry Smith +  snes     - SNES context
15093d4c4710SBarry Smith -  maxFails - maximum allowed linear solve failures
15103d4c4710SBarry Smith 
15113d4c4710SBarry Smith    Level: intermediate
15123d4c4710SBarry Smith 
15139d85da0cSMatthew G. Knepley    Options Database Keys:
15149d85da0cSMatthew G. Knepley . -snes_max_linear_solve_fail <num> - The number of failures before the solve is terminated
15159d85da0cSMatthew G. Knepley 
151695452b02SPatrick Sanan    Notes:
151795452b02SPatrick Sanan     By default this is 0; that is SNES returns on the first failed linear solve
15183d4c4710SBarry Smith 
15193d4c4710SBarry Smith .keywords: SNES, nonlinear, set, maximum, unsuccessful, steps
15203d4c4710SBarry Smith 
152158ebbce7SBarry Smith .seealso: SNESGetLinearSolveFailures(), SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations()
15223d4c4710SBarry Smith @*/
15237087cfbeSBarry Smith PetscErrorCode  SNESSetMaxLinearSolveFailures(SNES snes, PetscInt maxFails)
15243d4c4710SBarry Smith {
15253d4c4710SBarry Smith   PetscFunctionBegin;
15260700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
1527c5eb9154SBarry Smith   PetscValidLogicalCollectiveInt(snes,maxFails,2);
15283d4c4710SBarry Smith   snes->maxLinearSolveFailures = maxFails;
15293d4c4710SBarry Smith   PetscFunctionReturn(0);
15303d4c4710SBarry Smith }
15313d4c4710SBarry Smith 
15323d4c4710SBarry Smith /*@
15333d4c4710SBarry Smith    SNESGetMaxLinearSolveFailures - gets the maximum number of linear solve failures that
15343d4c4710SBarry Smith      are allowed before SNES terminates
15353d4c4710SBarry Smith 
15363d4c4710SBarry Smith    Not Collective
15373d4c4710SBarry Smith 
15383d4c4710SBarry Smith    Input Parameter:
15393d4c4710SBarry Smith .  snes     - SNES context
15403d4c4710SBarry Smith 
15413d4c4710SBarry Smith    Output Parameter:
15423d4c4710SBarry Smith .  maxFails - maximum of unsuccessful solves allowed
15433d4c4710SBarry Smith 
15443d4c4710SBarry Smith    Level: intermediate
15453d4c4710SBarry Smith 
154695452b02SPatrick Sanan    Notes:
154795452b02SPatrick Sanan     By default this is 1; that is SNES returns on the first failed linear solve
15483d4c4710SBarry Smith 
15493d4c4710SBarry Smith .keywords: SNES, nonlinear, get, maximum, unsuccessful, steps
15503d4c4710SBarry Smith 
1551e1c61ce8SBarry Smith .seealso: SNESGetLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(),
15523d4c4710SBarry Smith @*/
15537087cfbeSBarry Smith PetscErrorCode  SNESGetMaxLinearSolveFailures(SNES snes, PetscInt *maxFails)
15543d4c4710SBarry Smith {
15553d4c4710SBarry Smith   PetscFunctionBegin;
15560700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
15573d4c4710SBarry Smith   PetscValidIntPointer(maxFails,2);
15583d4c4710SBarry Smith   *maxFails = snes->maxLinearSolveFailures;
15593d4c4710SBarry Smith   PetscFunctionReturn(0);
15603d4c4710SBarry Smith }
15613d4c4710SBarry Smith 
1562c96a6f78SLois Curfman McInnes /*@
1563b850b91aSLisandro Dalcin    SNESGetLinearSolveIterations - Gets the total number of linear iterations
1564c96a6f78SLois Curfman McInnes    used by the nonlinear solver.
1565c96a6f78SLois Curfman McInnes 
1566c7afd0dbSLois Curfman McInnes    Not Collective
1567c7afd0dbSLois Curfman McInnes 
1568c96a6f78SLois Curfman McInnes    Input Parameter:
1569c96a6f78SLois Curfman McInnes .  snes - SNES context
1570c96a6f78SLois Curfman McInnes 
1571c96a6f78SLois Curfman McInnes    Output Parameter:
1572c96a6f78SLois Curfman McInnes .  lits - number of linear iterations
1573c96a6f78SLois Curfman McInnes 
1574c96a6f78SLois Curfman McInnes    Notes:
1575971e163fSPeter Brune    This counter is reset to zero for each successive call to SNESSolve() unless SNESSetCountersReset() is used.
1576c96a6f78SLois Curfman McInnes 
1577010be392SBarry 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
1578010be392SBarry Smith    then call KSPGetIterationNumber() after the failed solve.
1579010be392SBarry Smith 
158036851e7fSLois Curfman McInnes    Level: intermediate
158136851e7fSLois Curfman McInnes 
1582c96a6f78SLois Curfman McInnes .keywords: SNES, nonlinear, get, number, linear, iterations
15832b668275SBarry Smith 
158471dbe336SPeter Brune .seealso:  SNESGetIterationNumber(), SNESGetLinearSolveFailures(), SNESGetMaxLinearSolveFailures(), SNESSetCountersReset()
1585c96a6f78SLois Curfman McInnes @*/
15867087cfbeSBarry Smith PetscErrorCode  SNESGetLinearSolveIterations(SNES snes,PetscInt *lits)
1587c96a6f78SLois Curfman McInnes {
15883a40ed3dSBarry Smith   PetscFunctionBegin;
15890700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
15904482741eSBarry Smith   PetscValidIntPointer(lits,2);
1591c96a6f78SLois Curfman McInnes   *lits = snes->linear_its;
15923a40ed3dSBarry Smith   PetscFunctionReturn(0);
1593c96a6f78SLois Curfman McInnes }
1594c96a6f78SLois Curfman McInnes 
1595971e163fSPeter Brune /*@
1596971e163fSPeter Brune    SNESSetCountersReset - Sets whether or not the counters for linear iterations and function evaluations
1597971e163fSPeter Brune    are reset every time SNESSolve() is called.
1598971e163fSPeter Brune 
1599971e163fSPeter Brune    Logically Collective on SNES
1600971e163fSPeter Brune 
1601971e163fSPeter Brune    Input Parameter:
1602971e163fSPeter Brune +  snes - SNES context
1603971e163fSPeter Brune -  reset - whether to reset the counters or not
1604971e163fSPeter Brune 
1605971e163fSPeter Brune    Notes:
1606fa19ca70SBarry Smith    This defaults to PETSC_TRUE
1607971e163fSPeter Brune 
1608971e163fSPeter Brune    Level: developer
1609971e163fSPeter Brune 
1610971e163fSPeter Brune .keywords: SNES, nonlinear, set, reset, number, linear, iterations
1611971e163fSPeter Brune 
1612734794cfSBarry Smith .seealso:  SNESGetNumberFunctionEvals(), SNESGetLinearSolveIterations(), SNESGetNPC()
1613971e163fSPeter Brune @*/
1614971e163fSPeter Brune PetscErrorCode  SNESSetCountersReset(SNES snes,PetscBool reset)
1615971e163fSPeter Brune {
1616971e163fSPeter Brune   PetscFunctionBegin;
1617971e163fSPeter Brune   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
1618971e163fSPeter Brune   PetscValidLogicalCollectiveBool(snes,reset,2);
1619971e163fSPeter Brune   snes->counters_reset = reset;
1620971e163fSPeter Brune   PetscFunctionReturn(0);
1621971e163fSPeter Brune }
1622971e163fSPeter Brune 
162382bf6240SBarry Smith 
16242999313aSBarry Smith /*@
16252999313aSBarry Smith    SNESSetKSP - Sets a KSP context for the SNES object to use
16262999313aSBarry Smith 
16272999313aSBarry Smith    Not Collective, but the SNES and KSP objects must live on the same MPI_Comm
16282999313aSBarry Smith 
16292999313aSBarry Smith    Input Parameters:
16302999313aSBarry Smith +  snes - the SNES context
16312999313aSBarry Smith -  ksp - the KSP context
16322999313aSBarry Smith 
16332999313aSBarry Smith    Notes:
16342999313aSBarry Smith    The SNES object already has its KSP object, you can obtain with SNESGetKSP()
16352999313aSBarry Smith    so this routine is rarely needed.
16362999313aSBarry Smith 
16372999313aSBarry Smith    The KSP object that is already in the SNES object has its reference count
16382999313aSBarry Smith    decreased by one.
16392999313aSBarry Smith 
16402999313aSBarry Smith    Level: developer
16412999313aSBarry Smith 
16422999313aSBarry Smith .keywords: SNES, nonlinear, get, KSP, context
16432999313aSBarry Smith 
16442999313aSBarry Smith .seealso: KSPGetPC(), SNESCreate(), KSPCreate(), SNESSetKSP()
16452999313aSBarry Smith @*/
16467087cfbeSBarry Smith PetscErrorCode  SNESSetKSP(SNES snes,KSP ksp)
16472999313aSBarry Smith {
16482999313aSBarry Smith   PetscErrorCode ierr;
16492999313aSBarry Smith 
16502999313aSBarry Smith   PetscFunctionBegin;
16510700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
16520700a824SBarry Smith   PetscValidHeaderSpecific(ksp,KSP_CLASSID,2);
16532999313aSBarry Smith   PetscCheckSameComm(snes,1,ksp,2);
16547dcf0eaaSdalcinl   ierr = PetscObjectReference((PetscObject)ksp);CHKERRQ(ierr);
1655906ed7ccSBarry Smith   if (snes->ksp) {ierr = PetscObjectDereference((PetscObject)snes->ksp);CHKERRQ(ierr);}
16562999313aSBarry Smith   snes->ksp = ksp;
16572999313aSBarry Smith   PetscFunctionReturn(0);
16582999313aSBarry Smith }
16592999313aSBarry Smith 
16609b94acceSBarry Smith /* -----------------------------------------------------------*/
166152baeb72SSatish Balay /*@
16629b94acceSBarry Smith    SNESCreate - Creates a nonlinear solver context.
16639b94acceSBarry Smith 
1664c7afd0dbSLois Curfman McInnes    Collective on MPI_Comm
1665c7afd0dbSLois Curfman McInnes 
1666c7afd0dbSLois Curfman McInnes    Input Parameters:
1667906ed7ccSBarry Smith .  comm - MPI communicator
16689b94acceSBarry Smith 
16699b94acceSBarry Smith    Output Parameter:
16709b94acceSBarry Smith .  outsnes - the new SNES context
16719b94acceSBarry Smith 
1672c7afd0dbSLois Curfman McInnes    Options Database Keys:
1673c7afd0dbSLois Curfman McInnes +   -snes_mf - Activates default matrix-free Jacobian-vector products,
1674c7afd0dbSLois Curfman McInnes                and no preconditioning matrix
1675c7afd0dbSLois Curfman McInnes .   -snes_mf_operator - Activates default matrix-free Jacobian-vector
1676c7afd0dbSLois Curfman McInnes                products, and a user-provided preconditioning matrix
1677c7afd0dbSLois Curfman McInnes                as set by SNESSetJacobian()
1678c7afd0dbSLois Curfman McInnes -   -snes_fd - Uses (slow!) finite differences to compute Jacobian
1679c1f60f51SBarry Smith 
168036851e7fSLois Curfman McInnes    Level: beginner
168136851e7fSLois Curfman McInnes 
168295452b02SPatrick Sanan    Developer Notes:
168395452b02SPatrick Sanan     SNES always creates a KSP object even though many SNES methods do not use it. This is
1684efd4aadfSBarry Smith                     unfortunate and should be fixed at some point. The flag snes->usesksp indicates if the
1685efd4aadfSBarry Smith                     particular method does use KSP and regulates if the information about the KSP is printed
1686efd4aadfSBarry Smith                     in SNESView(). TSSetFromOptions() does call SNESSetFromOptions() which can lead to users being confused
1687efd4aadfSBarry Smith                     by help messages about meaningless SNES options.
1688efd4aadfSBarry Smith 
1689efd4aadfSBarry Smith                     SNES always creates the snes->kspconvctx even though it is used by only one type. This should
1690efd4aadfSBarry Smith                     be fixed.
1691efd4aadfSBarry Smith 
16929b94acceSBarry Smith .keywords: SNES, nonlinear, create, context
16939b94acceSBarry Smith 
1694a8054027SBarry Smith .seealso: SNESSolve(), SNESDestroy(), SNES, SNESSetLagPreconditioner()
1695a8054027SBarry Smith 
16969b94acceSBarry Smith @*/
16977087cfbeSBarry Smith PetscErrorCode  SNESCreate(MPI_Comm comm,SNES *outsnes)
16989b94acceSBarry Smith {
1699dfbe8321SBarry Smith   PetscErrorCode ierr;
17009b94acceSBarry Smith   SNES           snes;
1701fa9f3622SBarry Smith   SNESKSPEW      *kctx;
170237fcc0dbSBarry Smith 
17033a40ed3dSBarry Smith   PetscFunctionBegin;
1704ed1caa07SMatthew Knepley   PetscValidPointer(outsnes,2);
17050298fd71SBarry Smith   *outsnes = NULL;
1706607a6623SBarry Smith   ierr = SNESInitializePackage();CHKERRQ(ierr);
17078ba1e511SMatthew Knepley 
170873107ff1SLisandro Dalcin   ierr = PetscHeaderCreate(snes,SNES_CLASSID,"SNES","Nonlinear solver","SNES",comm,SNESDestroy,SNESView);CHKERRQ(ierr);
17097adad957SLisandro Dalcin 
17108d359177SBarry Smith   snes->ops->converged    = SNESConvergedDefault;
17112c155ee1SBarry Smith   snes->usesksp           = PETSC_TRUE;
171288976e71SPeter Brune   snes->tolerancesset     = PETSC_FALSE;
17139b94acceSBarry Smith   snes->max_its           = 50;
17149750a799SBarry Smith   snes->max_funcs         = 10000;
17159b94acceSBarry Smith   snes->norm              = 0.0;
1716c1e67a49SFande Kong   snes->xnorm             = 0.0;
1717c1e67a49SFande Kong   snes->ynorm             = 0.0;
1718365a6726SPeter Brune   snes->normschedule      = SNES_NORM_ALWAYS;
17196c67d002SPeter Brune   snes->functype          = SNES_FUNCTION_DEFAULT;
17203a2046daSBarry Smith #if defined(PETSC_USE_REAL_SINGLE)
17213a2046daSBarry Smith   snes->rtol              = 1.e-5;
17223a2046daSBarry Smith #else
1723b4874afaSBarry Smith   snes->rtol              = 1.e-8;
17243a2046daSBarry Smith #endif
1725b4874afaSBarry Smith   snes->ttol              = 0.0;
17263a2046daSBarry Smith #if defined(PETSC_USE_REAL_SINGLE)
17273a2046daSBarry Smith   snes->abstol            = 1.e-25;
17283a2046daSBarry Smith #else
172970441072SBarry Smith   snes->abstol            = 1.e-50;
17303a2046daSBarry Smith #endif
17317cd0ae37SLisandro Dalcin #if defined(PETSC_USE_REAL_SINGLE)
17327cd0ae37SLisandro Dalcin   snes->stol              = 1.e-5;
17337cd0ae37SLisandro Dalcin #else
1734c60f73f4SPeter Brune   snes->stol              = 1.e-8;
17357cd0ae37SLisandro Dalcin #endif
17363a2046daSBarry Smith #if defined(PETSC_USE_REAL_SINGLE)
17373a2046daSBarry Smith   snes->deltatol          = 1.e-6;
17383a2046daSBarry Smith #else
17394b27c08aSLois Curfman McInnes   snes->deltatol          = 1.e-12;
17403a2046daSBarry Smith #endif
1741e37c518bSBarry Smith   snes->divtol            = 1.e4;
1742e37c518bSBarry Smith   snes->rnorm0            = 0;
17439b94acceSBarry Smith   snes->nfuncs            = 0;
174450ffb88aSMatthew Knepley   snes->numFailures       = 0;
174550ffb88aSMatthew Knepley   snes->maxFailures       = 1;
17467a00f4a9SLois Curfman McInnes   snes->linear_its        = 0;
1747e35cf81dSBarry Smith   snes->lagjacobian       = 1;
174837ec4e1aSPeter Brune   snes->jac_iter          = 0;
174937ec4e1aSPeter Brune   snes->lagjac_persist    = PETSC_FALSE;
1750a8054027SBarry Smith   snes->lagpreconditioner = 1;
175137ec4e1aSPeter Brune   snes->pre_iter          = 0;
175237ec4e1aSPeter Brune   snes->lagpre_persist    = PETSC_FALSE;
1753639f9d9dSBarry Smith   snes->numbermonitors    = 0;
17549b94acceSBarry Smith   snes->data              = 0;
17554dc4c822SBarry Smith   snes->setupcalled       = PETSC_FALSE;
1756186905e3SBarry Smith   snes->ksp_ewconv        = PETSC_FALSE;
17576f24a144SLois Curfman McInnes   snes->nwork             = 0;
175858c9b817SLisandro Dalcin   snes->work              = 0;
175958c9b817SLisandro Dalcin   snes->nvwork            = 0;
176058c9b817SLisandro Dalcin   snes->vwork             = 0;
1761758f92a0SBarry Smith   snes->conv_hist_len     = 0;
1762758f92a0SBarry Smith   snes->conv_hist_max     = 0;
17630298fd71SBarry Smith   snes->conv_hist         = NULL;
17640298fd71SBarry Smith   snes->conv_hist_its     = NULL;
1765758f92a0SBarry Smith   snes->conv_hist_reset   = PETSC_TRUE;
1766971e163fSPeter Brune   snes->counters_reset    = PETSC_TRUE;
1767e4ed7901SPeter Brune   snes->vec_func_init_set = PETSC_FALSE;
1768184914b5SBarry Smith   snes->reason            = SNES_CONVERGED_ITERATING;
1769efd4aadfSBarry Smith   snes->npcside           = PC_RIGHT;
1770b3cd9a81SMatthew G. Knepley   snes->setfromoptionscalled = 0;
1771c40d0f55SPeter Brune 
1772d8f46077SPeter Brune   snes->mf          = PETSC_FALSE;
1773d8f46077SPeter Brune   snes->mf_operator = PETSC_FALSE;
1774d8f46077SPeter Brune   snes->mf_version  = 1;
1775d8f46077SPeter Brune 
17763d4c4710SBarry Smith   snes->numLinearSolveFailures = 0;
17773d4c4710SBarry Smith   snes->maxLinearSolveFailures = 1;
17783d4c4710SBarry Smith 
1779349187a7SBarry Smith   snes->vizerotolerance = 1.e-8;
1780b351a90bSFande Kong #if defined(PETSC_USE_DEBUG)
1781b351a90bSFande Kong   snes->checkjacdomainerror = PETSC_TRUE;
1782b351a90bSFande Kong #else
1783b351a90bSFande Kong   snes->checkjacdomainerror = PETSC_FALSE;
1784b351a90bSFande Kong #endif
1785349187a7SBarry Smith 
17864fc747eaSLawrence Mitchell   /* Set this to true if the implementation of SNESSolve_XXX does compute the residual at the final solution. */
17874fc747eaSLawrence Mitchell   snes->alwayscomputesfinalresidual = PETSC_FALSE;
17884fc747eaSLawrence Mitchell 
17899b94acceSBarry Smith   /* Create context to compute Eisenstat-Walker relative tolerance for KSP */
1790b00a9115SJed Brown   ierr = PetscNewLog(snes,&kctx);CHKERRQ(ierr);
1791f5af7f23SKarl Rupp 
17929b94acceSBarry Smith   snes->kspconvctx  = (void*)kctx;
17939b94acceSBarry Smith   kctx->version     = 2;
17949b94acceSBarry Smith   kctx->rtol_0      = .3; /* Eisenstat and Walker suggest rtol_0=.5, but
17959b94acceSBarry Smith                              this was too large for some test cases */
179675567043SBarry Smith   kctx->rtol_last   = 0.0;
17979b94acceSBarry Smith   kctx->rtol_max    = .9;
17989b94acceSBarry Smith   kctx->gamma       = 1.0;
179962d1f40fSBarry Smith   kctx->alpha       = .5*(1.0 + PetscSqrtReal(5.0));
180071f87433Sdalcinl   kctx->alpha2      = kctx->alpha;
18019b94acceSBarry Smith   kctx->threshold   = .1;
180275567043SBarry Smith   kctx->lresid_last = 0.0;
180375567043SBarry Smith   kctx->norm_last   = 0.0;
18049b94acceSBarry Smith 
18059b94acceSBarry Smith   *outsnes = snes;
18063a40ed3dSBarry Smith   PetscFunctionReturn(0);
18079b94acceSBarry Smith }
18089b94acceSBarry Smith 
180988f0584fSBarry Smith /*MC
1810411c0326SBarry Smith     SNESFunction - Functional form used to convey the nonlinear function to be solved by SNES
181188f0584fSBarry Smith 
181288f0584fSBarry Smith      Synopsis:
1813411c0326SBarry Smith      #include "petscsnes.h"
1814411c0326SBarry Smith      PetscErrorCode SNESFunction(SNES snes,Vec x,Vec f,void *ctx);
181588f0584fSBarry Smith 
181688f0584fSBarry Smith      Input Parameters:
181788f0584fSBarry Smith +     snes - the SNES context
181888f0584fSBarry Smith .     x    - state at which to evaluate residual
181988f0584fSBarry Smith -     ctx     - optional user-defined function context, passed in with SNESSetFunction()
182088f0584fSBarry Smith 
182188f0584fSBarry Smith      Output Parameter:
182288f0584fSBarry Smith .     f  - vector to put residual (function value)
182388f0584fSBarry Smith 
1824878cb397SSatish Balay    Level: intermediate
1825878cb397SSatish Balay 
182688f0584fSBarry Smith .seealso:   SNESSetFunction(), SNESGetFunction()
182788f0584fSBarry Smith M*/
182888f0584fSBarry Smith 
18299b94acceSBarry Smith /*@C
18309b94acceSBarry Smith    SNESSetFunction - Sets the function evaluation routine and function
18319b94acceSBarry Smith    vector for use by the SNES routines in solving systems of nonlinear
18329b94acceSBarry Smith    equations.
18339b94acceSBarry Smith 
18343f9fe445SBarry Smith    Logically Collective on SNES
1835fee21e36SBarry Smith 
1836c7afd0dbSLois Curfman McInnes    Input Parameters:
1837c7afd0dbSLois Curfman McInnes +  snes - the SNES context
1838c7afd0dbSLois Curfman McInnes .  r - vector to store function value
1839f8b49ee9SBarry Smith .  f - function evaluation routine; see SNESFunction for calling sequence details
1840c7afd0dbSLois Curfman McInnes -  ctx - [optional] user-defined context for private data for the
18410298fd71SBarry Smith          function evaluation routine (may be NULL)
18429b94acceSBarry Smith 
18439b94acceSBarry Smith    Notes:
18449b94acceSBarry Smith    The Newton-like methods typically solve linear systems of the form
18459b94acceSBarry Smith $      f'(x) x = -f(x),
1846c7afd0dbSLois Curfman McInnes    where f'(x) denotes the Jacobian matrix and f(x) is the function.
18479b94acceSBarry Smith 
184836851e7fSLois Curfman McInnes    Level: beginner
184936851e7fSLois Curfman McInnes 
18509b94acceSBarry Smith .keywords: SNES, nonlinear, set, function
18519b94acceSBarry Smith 
1852bf388a1fSBarry Smith .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetPicard(), SNESFunction
18539b94acceSBarry Smith @*/
1854f8b49ee9SBarry Smith PetscErrorCode  SNESSetFunction(SNES snes,Vec r,PetscErrorCode (*f)(SNES,Vec,Vec,void*),void *ctx)
18559b94acceSBarry Smith {
185685385478SLisandro Dalcin   PetscErrorCode ierr;
18576cab3a1bSJed Brown   DM             dm;
18586cab3a1bSJed Brown 
18593a40ed3dSBarry Smith   PetscFunctionBegin;
18600700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
1861d2a683ecSLisandro Dalcin   if (r) {
1862d2a683ecSLisandro Dalcin     PetscValidHeaderSpecific(r,VEC_CLASSID,2);
1863d2a683ecSLisandro Dalcin     PetscCheckSameComm(snes,1,r,2);
186485385478SLisandro Dalcin     ierr = PetscObjectReference((PetscObject)r);CHKERRQ(ierr);
18656bf464f9SBarry Smith     ierr = VecDestroy(&snes->vec_func);CHKERRQ(ierr);
1866f5af7f23SKarl Rupp 
186785385478SLisandro Dalcin     snes->vec_func = r;
1868d2a683ecSLisandro Dalcin   }
18696cab3a1bSJed Brown   ierr = SNESGetDM(snes,&dm);CHKERRQ(ierr);
1870f8b49ee9SBarry Smith   ierr = DMSNESSetFunction(dm,f,ctx);CHKERRQ(ierr);
18713a40ed3dSBarry Smith   PetscFunctionReturn(0);
18729b94acceSBarry Smith }
18739b94acceSBarry Smith 
1874646217ecSPeter Brune 
1875e4ed7901SPeter Brune /*@C
1876e4ed7901SPeter Brune    SNESSetInitialFunction - Sets the function vector to be used as the
1877e4ed7901SPeter Brune    function norm at the initialization of the method.  In some
1878e4ed7901SPeter Brune    instances, the user has precomputed the function before calling
1879e4ed7901SPeter Brune    SNESSolve.  This function allows one to avoid a redundant call
1880e4ed7901SPeter Brune    to SNESComputeFunction in that case.
1881e4ed7901SPeter Brune 
1882e4ed7901SPeter Brune    Logically Collective on SNES
1883e4ed7901SPeter Brune 
1884e4ed7901SPeter Brune    Input Parameters:
1885e4ed7901SPeter Brune +  snes - the SNES context
1886e4ed7901SPeter Brune -  f - vector to store function value
1887e4ed7901SPeter Brune 
1888e4ed7901SPeter Brune    Notes:
1889e4ed7901SPeter Brune    This should not be modified during the solution procedure.
1890e4ed7901SPeter Brune 
1891e4ed7901SPeter Brune    This is used extensively in the SNESFAS hierarchy and in nonlinear preconditioning.
1892e4ed7901SPeter Brune 
1893e4ed7901SPeter Brune    Level: developer
1894e4ed7901SPeter Brune 
1895e4ed7901SPeter Brune .keywords: SNES, nonlinear, set, function
1896e4ed7901SPeter Brune 
1897e4ed7901SPeter Brune .seealso: SNESSetFunction(), SNESComputeFunction(), SNESSetInitialFunctionNorm()
1898e4ed7901SPeter Brune @*/
1899e4ed7901SPeter Brune PetscErrorCode  SNESSetInitialFunction(SNES snes, Vec f)
1900e4ed7901SPeter Brune {
1901e4ed7901SPeter Brune   PetscErrorCode ierr;
1902e4ed7901SPeter Brune   Vec            vec_func;
1903e4ed7901SPeter Brune 
1904e4ed7901SPeter Brune   PetscFunctionBegin;
1905e4ed7901SPeter Brune   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
1906e4ed7901SPeter Brune   PetscValidHeaderSpecific(f,VEC_CLASSID,2);
1907e4ed7901SPeter Brune   PetscCheckSameComm(snes,1,f,2);
1908efd4aadfSBarry Smith   if (snes->npcside== PC_LEFT && snes->functype == SNES_FUNCTION_PRECONDITIONED) {
1909902f982fSPeter Brune     snes->vec_func_init_set = PETSC_FALSE;
1910902f982fSPeter Brune     PetscFunctionReturn(0);
1911902f982fSPeter Brune   }
19120298fd71SBarry Smith   ierr = SNESGetFunction(snes,&vec_func,NULL,NULL);CHKERRQ(ierr);
1913e4ed7901SPeter Brune   ierr = VecCopy(f, vec_func);CHKERRQ(ierr);
1914f5af7f23SKarl Rupp 
1915217b9c2eSPeter Brune   snes->vec_func_init_set = PETSC_TRUE;
1916e4ed7901SPeter Brune   PetscFunctionReturn(0);
1917e4ed7901SPeter Brune }
1918e4ed7901SPeter Brune 
1919534ebe21SPeter Brune /*@
1920365a6726SPeter Brune    SNESSetNormSchedule - Sets the SNESNormSchedule used in covergence and monitoring
1921534ebe21SPeter Brune    of the SNES method.
1922534ebe21SPeter Brune 
1923534ebe21SPeter Brune    Logically Collective on SNES
1924534ebe21SPeter Brune 
1925534ebe21SPeter Brune    Input Parameters:
1926534ebe21SPeter Brune +  snes - the SNES context
1927365a6726SPeter Brune -  normschedule - the frequency of norm computation
1928534ebe21SPeter Brune 
1929517f1916SMatthew G. Knepley    Options Database Key:
1930517f1916SMatthew G. Knepley .  -snes_norm_schedule <none, always, initialonly, finalonly, initalfinalonly>
1931517f1916SMatthew G. Knepley 
1932534ebe21SPeter Brune    Notes:
1933365a6726SPeter Brune    Only certain SNES methods support certain SNESNormSchedules.  Most require evaluation
1934534ebe21SPeter Brune    of the nonlinear function and the taking of its norm at every iteration to
1935534ebe21SPeter Brune    even ensure convergence at all.  However, methods such as custom Gauss-Seidel methods
1936be95d8f1SBarry Smith    (SNESNGS) and the like do not require the norm of the function to be computed, and therfore
1937534ebe21SPeter Brune    may either be monitored for convergence or not.  As these are often used as nonlinear
1938534ebe21SPeter Brune    preconditioners, monitoring the norm of their error is not a useful enterprise within
1939534ebe21SPeter Brune    their solution.
1940534ebe21SPeter Brune 
1941534ebe21SPeter Brune    Level: developer
1942534ebe21SPeter Brune 
1943534ebe21SPeter Brune .keywords: SNES, nonlinear, set, function, norm, type
1944534ebe21SPeter Brune 
1945365a6726SPeter Brune .seealso: SNESGetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1946534ebe21SPeter Brune @*/
1947365a6726SPeter Brune PetscErrorCode  SNESSetNormSchedule(SNES snes, SNESNormSchedule normschedule)
1948534ebe21SPeter Brune {
1949534ebe21SPeter Brune   PetscFunctionBegin;
1950534ebe21SPeter Brune   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
1951365a6726SPeter Brune   snes->normschedule = normschedule;
1952534ebe21SPeter Brune   PetscFunctionReturn(0);
1953534ebe21SPeter Brune }
1954534ebe21SPeter Brune 
1955534ebe21SPeter Brune 
1956534ebe21SPeter Brune /*@
1957365a6726SPeter Brune    SNESGetNormSchedule - Gets the SNESNormSchedule used in covergence and monitoring
1958534ebe21SPeter Brune    of the SNES method.
1959534ebe21SPeter Brune 
1960534ebe21SPeter Brune    Logically Collective on SNES
1961534ebe21SPeter Brune 
1962534ebe21SPeter Brune    Input Parameters:
1963534ebe21SPeter Brune +  snes - the SNES context
1964365a6726SPeter Brune -  normschedule - the type of the norm used
1965534ebe21SPeter Brune 
1966534ebe21SPeter Brune    Level: advanced
1967534ebe21SPeter Brune 
1968534ebe21SPeter Brune .keywords: SNES, nonlinear, set, function, norm, type
1969534ebe21SPeter Brune 
1970365a6726SPeter Brune .seealso: SNESSetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1971534ebe21SPeter Brune @*/
1972365a6726SPeter Brune PetscErrorCode  SNESGetNormSchedule(SNES snes, SNESNormSchedule *normschedule)
1973534ebe21SPeter Brune {
1974534ebe21SPeter Brune   PetscFunctionBegin;
1975534ebe21SPeter Brune   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
1976365a6726SPeter Brune   *normschedule = snes->normschedule;
1977534ebe21SPeter Brune   PetscFunctionReturn(0);
1978534ebe21SPeter Brune }
1979534ebe21SPeter Brune 
198047073ea2SPeter Brune 
1981c5ce4427SMatthew G. Knepley /*@
1982c5ce4427SMatthew G. Knepley   SNESSetFunctionNorm - Sets the last computed residual norm.
1983c5ce4427SMatthew G. Knepley 
1984c5ce4427SMatthew G. Knepley   Logically Collective on SNES
1985c5ce4427SMatthew G. Knepley 
1986c5ce4427SMatthew G. Knepley   Input Parameters:
1987c5ce4427SMatthew G. Knepley + snes - the SNES context
1988c5ce4427SMatthew G. Knepley 
1989c5ce4427SMatthew G. Knepley - normschedule - the frequency of norm computation
1990c5ce4427SMatthew G. Knepley 
1991c5ce4427SMatthew G. Knepley   Level: developer
1992c5ce4427SMatthew G. Knepley 
1993c5ce4427SMatthew G. Knepley .keywords: SNES, nonlinear, set, function, norm, type
1994c5ce4427SMatthew G. Knepley .seealso: SNESGetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1995c5ce4427SMatthew G. Knepley @*/
1996c5ce4427SMatthew G. Knepley PetscErrorCode SNESSetFunctionNorm(SNES snes, PetscReal norm)
1997c5ce4427SMatthew G. Knepley {
1998c5ce4427SMatthew G. Knepley   PetscFunctionBegin;
1999c5ce4427SMatthew G. Knepley   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
2000c5ce4427SMatthew G. Knepley   snes->norm = norm;
2001c5ce4427SMatthew G. Knepley   PetscFunctionReturn(0);
2002c5ce4427SMatthew G. Knepley }
2003c5ce4427SMatthew G. Knepley 
2004c5ce4427SMatthew G. Knepley /*@
2005c5ce4427SMatthew G. Knepley   SNESGetFunctionNorm - Gets the last computed norm of the residual
2006c5ce4427SMatthew G. Knepley 
2007c5ce4427SMatthew G. Knepley   Not Collective
2008c5ce4427SMatthew G. Knepley 
2009c5ce4427SMatthew G. Knepley   Input Parameter:
2010c5ce4427SMatthew G. Knepley . snes - the SNES context
2011c5ce4427SMatthew G. Knepley 
2012c5ce4427SMatthew G. Knepley   Output Parameter:
2013c5ce4427SMatthew G. Knepley . norm - the last computed residual norm
2014c5ce4427SMatthew G. Knepley 
2015c5ce4427SMatthew G. Knepley   Level: developer
2016c5ce4427SMatthew G. Knepley 
2017c5ce4427SMatthew G. Knepley .keywords: SNES, nonlinear, set, function, norm, type
2018c5ce4427SMatthew G. Knepley .seealso: SNESSetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
2019c5ce4427SMatthew G. Knepley @*/
2020c5ce4427SMatthew G. Knepley PetscErrorCode SNESGetFunctionNorm(SNES snes, PetscReal *norm)
2021c5ce4427SMatthew G. Knepley {
2022c5ce4427SMatthew G. Knepley   PetscFunctionBegin;
2023c5ce4427SMatthew G. Knepley   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
2024c5ce4427SMatthew G. Knepley   PetscValidPointer(norm, 2);
2025c5ce4427SMatthew G. Knepley   *norm = snes->norm;
2026c5ce4427SMatthew G. Knepley   PetscFunctionReturn(0);
2027c5ce4427SMatthew G. Knepley }
2028c5ce4427SMatthew G. Knepley 
2029c1e67a49SFande Kong /*@
2030c1e67a49SFande Kong   SNESGetUpdateNorm - Gets the last computed norm of the Newton update
2031c1e67a49SFande Kong 
2032c1e67a49SFande Kong   Not Collective
2033c1e67a49SFande Kong 
2034c1e67a49SFande Kong   Input Parameter:
2035c1e67a49SFande Kong . snes - the SNES context
2036c1e67a49SFande Kong 
2037c1e67a49SFande Kong   Output Parameter:
2038c1e67a49SFande Kong . ynorm - the last computed update norm
2039c1e67a49SFande Kong 
2040c1e67a49SFande Kong   Level: developer
2041c1e67a49SFande Kong 
2042c1e67a49SFande Kong .keywords: SNES, nonlinear, set, function, norm, type
2043c1e67a49SFande Kong .seealso: SNESSetNormSchedule(), SNESComputeFunction(), SNESGetFunctionNorm()
2044c1e67a49SFande Kong @*/
2045c1e67a49SFande Kong PetscErrorCode SNESGetUpdateNorm(SNES snes, PetscReal *ynorm)
2046c1e67a49SFande Kong {
2047c1e67a49SFande Kong   PetscFunctionBegin;
2048c1e67a49SFande Kong   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
2049c1e67a49SFande Kong   PetscValidPointer(ynorm, 2);
2050c1e67a49SFande Kong   *ynorm = snes->ynorm;
2051c1e67a49SFande Kong   PetscFunctionReturn(0);
2052c1e67a49SFande Kong }
2053c1e67a49SFande Kong 
2054c1e67a49SFande Kong /*@
20554591eaf2SFande Kong   SNESGetSolutionNorm - Gets the last computed norm of the solution
2056c1e67a49SFande Kong 
2057c1e67a49SFande Kong   Not Collective
2058c1e67a49SFande Kong 
2059c1e67a49SFande Kong   Input Parameter:
2060c1e67a49SFande Kong . snes - the SNES context
2061c1e67a49SFande Kong 
2062c1e67a49SFande Kong   Output Parameter:
2063c1e67a49SFande Kong . xnorm - the last computed solution norm
2064c1e67a49SFande Kong 
2065c1e67a49SFande Kong   Level: developer
2066c1e67a49SFande Kong 
2067c1e67a49SFande Kong .keywords: SNES, nonlinear, set, function, norm, type
2068c1e67a49SFande Kong .seealso: SNESSetNormSchedule(), SNESComputeFunction(), SNESGetFunctionNorm(), SNESGetUpdateNorm()
2069c1e67a49SFande Kong @*/
2070c1e67a49SFande Kong PetscErrorCode SNESGetSolutionNorm(SNES snes, PetscReal *xnorm)
2071c1e67a49SFande Kong {
2072c1e67a49SFande Kong   PetscFunctionBegin;
2073c1e67a49SFande Kong   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
2074c1e67a49SFande Kong   PetscValidPointer(xnorm, 2);
2075c1e67a49SFande Kong   *xnorm = snes->xnorm;
2076c1e67a49SFande Kong   PetscFunctionReturn(0);
2077c1e67a49SFande Kong }
2078c1e67a49SFande Kong 
207947073ea2SPeter Brune /*@C
208047073ea2SPeter Brune    SNESSetFunctionType - Sets the SNESNormSchedule used in covergence and monitoring
208147073ea2SPeter Brune    of the SNES method.
208247073ea2SPeter Brune 
208347073ea2SPeter Brune    Logically Collective on SNES
208447073ea2SPeter Brune 
208547073ea2SPeter Brune    Input Parameters:
208647073ea2SPeter Brune +  snes - the SNES context
208747073ea2SPeter Brune -  normschedule - the frequency of norm computation
208847073ea2SPeter Brune 
208947073ea2SPeter Brune    Notes:
209047073ea2SPeter Brune    Only certain SNES methods support certain SNESNormSchedules.  Most require evaluation
209147073ea2SPeter Brune    of the nonlinear function and the taking of its norm at every iteration to
209247073ea2SPeter Brune    even ensure convergence at all.  However, methods such as custom Gauss-Seidel methods
2093be95d8f1SBarry Smith    (SNESNGS) and the like do not require the norm of the function to be computed, and therfore
209447073ea2SPeter Brune    may either be monitored for convergence or not.  As these are often used as nonlinear
209547073ea2SPeter Brune    preconditioners, monitoring the norm of their error is not a useful enterprise within
209647073ea2SPeter Brune    their solution.
209747073ea2SPeter Brune 
209847073ea2SPeter Brune    Level: developer
209947073ea2SPeter Brune 
210047073ea2SPeter Brune .keywords: SNES, nonlinear, set, function, norm, type
210147073ea2SPeter Brune 
210247073ea2SPeter Brune .seealso: SNESGetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
210347073ea2SPeter Brune @*/
210447073ea2SPeter Brune PetscErrorCode  SNESSetFunctionType(SNES snes, SNESFunctionType type)
210547073ea2SPeter Brune {
210647073ea2SPeter Brune   PetscFunctionBegin;
210747073ea2SPeter Brune   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
210847073ea2SPeter Brune   snes->functype = type;
210947073ea2SPeter Brune   PetscFunctionReturn(0);
211047073ea2SPeter Brune }
211147073ea2SPeter Brune 
211247073ea2SPeter Brune 
211347073ea2SPeter Brune /*@C
211447073ea2SPeter Brune    SNESGetFunctionType - Gets the SNESNormSchedule used in covergence and monitoring
211547073ea2SPeter Brune    of the SNES method.
211647073ea2SPeter Brune 
211747073ea2SPeter Brune    Logically Collective on SNES
211847073ea2SPeter Brune 
211947073ea2SPeter Brune    Input Parameters:
212047073ea2SPeter Brune +  snes - the SNES context
212147073ea2SPeter Brune -  normschedule - the type of the norm used
212247073ea2SPeter Brune 
212347073ea2SPeter Brune    Level: advanced
212447073ea2SPeter Brune 
212547073ea2SPeter Brune .keywords: SNES, nonlinear, set, function, norm, type
212647073ea2SPeter Brune 
212747073ea2SPeter Brune .seealso: SNESSetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
212847073ea2SPeter Brune @*/
212947073ea2SPeter Brune PetscErrorCode  SNESGetFunctionType(SNES snes, SNESFunctionType *type)
213047073ea2SPeter Brune {
213147073ea2SPeter Brune   PetscFunctionBegin;
213247073ea2SPeter Brune   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
213347073ea2SPeter Brune   *type = snes->functype;
2134534ebe21SPeter Brune   PetscFunctionReturn(0);
2135534ebe21SPeter Brune }
2136534ebe21SPeter Brune 
2137bf388a1fSBarry Smith /*MC
2138be95d8f1SBarry Smith     SNESNGSFunction - function used to convey a Gauss-Seidel sweep on the nonlinear function
2139bf388a1fSBarry Smith 
2140bf388a1fSBarry Smith      Synopsis:
2141aaa7dc30SBarry Smith      #include <petscsnes.h>
2142be95d8f1SBarry Smith $    SNESNGSFunction(SNES snes,Vec x,Vec b,void *ctx);
2143bf388a1fSBarry Smith 
2144bf388a1fSBarry Smith +  X   - solution vector
2145bf388a1fSBarry Smith .  B   - RHS vector
2146bf388a1fSBarry Smith -  ctx - optional user-defined Gauss-Seidel context
2147bf388a1fSBarry Smith 
2148878cb397SSatish Balay    Level: intermediate
2149878cb397SSatish Balay 
2150be95d8f1SBarry Smith .seealso:   SNESSetNGS(), SNESGetNGS()
2151bf388a1fSBarry Smith M*/
2152bf388a1fSBarry Smith 
2153c79ef259SPeter Brune /*@C
2154be95d8f1SBarry Smith    SNESSetNGS - Sets the user nonlinear Gauss-Seidel routine for
2155c79ef259SPeter Brune    use with composed nonlinear solvers.
2156c79ef259SPeter Brune 
2157c79ef259SPeter Brune    Input Parameters:
2158c79ef259SPeter Brune +  snes   - the SNES context
2159be95d8f1SBarry Smith .  f - function evaluation routine to apply Gauss-Seidel see SNESNGSFunction
2160c79ef259SPeter Brune -  ctx    - [optional] user-defined context for private data for the
21610298fd71SBarry Smith             smoother evaluation routine (may be NULL)
2162c79ef259SPeter Brune 
2163c79ef259SPeter Brune    Notes:
2164be95d8f1SBarry Smith    The NGS routines are used by the composed nonlinear solver to generate
2165c79ef259SPeter Brune     a problem appropriate update to the solution, particularly FAS.
2166c79ef259SPeter Brune 
2167d28543b3SPeter Brune    Level: intermediate
2168c79ef259SPeter Brune 
2169d28543b3SPeter Brune .keywords: SNES, nonlinear, set, Gauss-Seidel
2170c79ef259SPeter Brune 
2171be95d8f1SBarry Smith .seealso: SNESGetFunction(), SNESComputeNGS()
2172c79ef259SPeter Brune @*/
2173be95d8f1SBarry Smith PetscErrorCode SNESSetNGS(SNES snes,PetscErrorCode (*f)(SNES,Vec,Vec,void*),void *ctx)
21746cab3a1bSJed Brown {
21756cab3a1bSJed Brown   PetscErrorCode ierr;
21766cab3a1bSJed Brown   DM             dm;
21776cab3a1bSJed Brown 
2178646217ecSPeter Brune   PetscFunctionBegin;
21796cab3a1bSJed Brown   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
21806cab3a1bSJed Brown   ierr = SNESGetDM(snes,&dm);CHKERRQ(ierr);
2181be95d8f1SBarry Smith   ierr = DMSNESSetNGS(dm,f,ctx);CHKERRQ(ierr);
2182646217ecSPeter Brune   PetscFunctionReturn(0);
2183646217ecSPeter Brune }
2184646217ecSPeter Brune 
218525acbd8eSLisandro Dalcin PetscErrorCode SNESPicardComputeFunction(SNES snes,Vec x,Vec f,void *ctx)
21868b0a5094SBarry Smith {
21878b0a5094SBarry Smith   PetscErrorCode ierr;
2188e03ab78fSPeter Brune   DM             dm;
2189942e3340SBarry Smith   DMSNES         sdm;
21906cab3a1bSJed Brown 
21918b0a5094SBarry Smith   PetscFunctionBegin;
2192e03ab78fSPeter Brune   ierr = SNESGetDM(snes,&dm);CHKERRQ(ierr);
2193942e3340SBarry Smith   ierr = DMGetDMSNES(dm,&sdm);CHKERRQ(ierr);
219425acbd8eSLisandro Dalcin   if (!sdm->ops->computepfunction) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetPicard() to provide Picard function.");
219525acbd8eSLisandro Dalcin   if (!sdm->ops->computepjacobian) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetPicard() to provide Picard Jacobian.");
21968b0a5094SBarry Smith   /*  A(x)*x - b(x) */
219725acbd8eSLisandro Dalcin   PetscStackPush("SNES Picard user function");
219822c6f798SBarry Smith   ierr = (*sdm->ops->computepfunction)(snes,x,f,sdm->pctx);CHKERRQ(ierr);
219925acbd8eSLisandro Dalcin   PetscStackPop;
220025acbd8eSLisandro Dalcin   PetscStackPush("SNES Picard user Jacobian");
2201d1e9a80fSBarry Smith   ierr = (*sdm->ops->computepjacobian)(snes,x,snes->jacobian,snes->jacobian_pre,sdm->pctx);CHKERRQ(ierr);
220225acbd8eSLisandro Dalcin   PetscStackPop;
22038b0a5094SBarry Smith   ierr = VecScale(f,-1.0);CHKERRQ(ierr);
220495eabcedSBarry Smith   ierr = MatMultAdd(snes->jacobian,x,f,f);CHKERRQ(ierr);
22058b0a5094SBarry Smith   PetscFunctionReturn(0);
22068b0a5094SBarry Smith }
22078b0a5094SBarry Smith 
220825acbd8eSLisandro Dalcin PetscErrorCode SNESPicardComputeJacobian(SNES snes,Vec x1,Mat J,Mat B,void *ctx)
22098b0a5094SBarry Smith {
22108b0a5094SBarry Smith   PetscFunctionBegin;
2211e03ab78fSPeter Brune   /* the jacobian matrix should be pre-filled in SNESPicardComputeFunction */
22128b0a5094SBarry Smith   PetscFunctionReturn(0);
22138b0a5094SBarry Smith }
22148b0a5094SBarry Smith 
22158b0a5094SBarry Smith /*@C
22160d04baf8SBarry Smith    SNESSetPicard - Use SNES to solve the semilinear-system A(x) x = b(x) via a Picard type iteration (Picard linearization)
22178b0a5094SBarry Smith 
22188b0a5094SBarry Smith    Logically Collective on SNES
22198b0a5094SBarry Smith 
22208b0a5094SBarry Smith    Input Parameters:
22218b0a5094SBarry Smith +  snes - the SNES context
22228b0a5094SBarry Smith .  r - vector to store function value
2223f8b49ee9SBarry Smith .  b - function evaluation routine
2224e5d3d808SBarry Smith .  Amat - matrix with which A(x) x - b(x) is to be computed
2225e5d3d808SBarry Smith .  Pmat - matrix from which preconditioner is computed (usually the same as Amat)
2226411c0326SBarry Smith .  J  - function to compute matrix value, see SNESJacobianFunction for details on its calling sequence
22278b0a5094SBarry Smith -  ctx - [optional] user-defined context for private data for the
22280298fd71SBarry Smith          function evaluation routine (may be NULL)
22298b0a5094SBarry Smith 
22308b0a5094SBarry Smith    Notes:
2231f450aa47SBarry Smith     We do not recomemend using this routine. It is far better to provide the nonlinear function F() and some approximation to the Jacobian and use
2232f450aa47SBarry 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.
2233f450aa47SBarry Smith 
22348b0a5094SBarry Smith     One can call SNESSetPicard() or SNESSetFunction() (and possibly SNESSetJacobian()) but cannot call both
22358b0a5094SBarry Smith 
22368b0a5094SBarry Smith $     Solves the equation A(x) x = b(x) via the defect correction algorithm A(x^{n}) (x^{n+1} - x^{n}) = b(x^{n}) - A(x^{n})x^{n}
22378b0a5094SBarry Smith $     Note that when an exact solver is used this corresponds to the "classic" Picard A(x^{n}) x^{n+1} = b(x^{n}) iteration.
22388b0a5094SBarry Smith 
22398b0a5094SBarry Smith      Run with -snes_mf_operator to solve the system with Newton's method using A(x^{n}) to construct the preconditioner.
22408b0a5094SBarry Smith 
22410d04baf8SBarry Smith    We implement the defect correction form of the Picard iteration because it converges much more generally when inexact linear solvers are used then
22420d04baf8SBarry Smith    the direct Picard iteration A(x^n) x^{n+1} = b(x^n)
22438b0a5094SBarry Smith 
22448b0a5094SBarry 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
22458b0a5094SBarry 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
22468b0a5094SBarry Smith    different please contact us at petsc-dev@mcs.anl.gov and we'll have an entirely new argument :-).
22478b0a5094SBarry Smith 
2248f450aa47SBarry Smith    Level: intermediate
22498b0a5094SBarry Smith 
22508b0a5094SBarry Smith .keywords: SNES, nonlinear, set, function
22518b0a5094SBarry Smith 
2252411c0326SBarry Smith .seealso: SNESGetFunction(), SNESSetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESGetPicard(), SNESLineSearchPreCheckPicard(), SNESJacobianFunction
22538b0a5094SBarry Smith @*/
2254d1e9a80fSBarry Smith PetscErrorCode  SNESSetPicard(SNES snes,Vec r,PetscErrorCode (*b)(SNES,Vec,Vec,void*),Mat Amat, Mat Pmat, PetscErrorCode (*J)(SNES,Vec,Mat,Mat,void*),void *ctx)
22558b0a5094SBarry Smith {
22568b0a5094SBarry Smith   PetscErrorCode ierr;
2257e03ab78fSPeter Brune   DM             dm;
2258e03ab78fSPeter Brune 
22598b0a5094SBarry Smith   PetscFunctionBegin;
22608b0a5094SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
2261e03ab78fSPeter Brune   ierr = SNESGetDM(snes, &dm);CHKERRQ(ierr);
2262f8b49ee9SBarry Smith   ierr = DMSNESSetPicard(dm,b,J,ctx);CHKERRQ(ierr);
22638b0a5094SBarry Smith   ierr = SNESSetFunction(snes,r,SNESPicardComputeFunction,ctx);CHKERRQ(ierr);
2264e5d3d808SBarry Smith   ierr = SNESSetJacobian(snes,Amat,Pmat,SNESPicardComputeJacobian,ctx);CHKERRQ(ierr);
22658b0a5094SBarry Smith   PetscFunctionReturn(0);
22668b0a5094SBarry Smith }
22678b0a5094SBarry Smith 
22687971a8bfSPeter Brune /*@C
22697971a8bfSPeter Brune    SNESGetPicard - Returns the context for the Picard iteration
22707971a8bfSPeter Brune 
22717971a8bfSPeter Brune    Not Collective, but Vec is parallel if SNES is parallel. Collective if Vec is requested, but has not been created yet.
22727971a8bfSPeter Brune 
22737971a8bfSPeter Brune    Input Parameter:
22747971a8bfSPeter Brune .  snes - the SNES context
22757971a8bfSPeter Brune 
22767971a8bfSPeter Brune    Output Parameter:
22770298fd71SBarry Smith +  r - the function (or NULL)
2278f8b49ee9SBarry Smith .  f - the function (or NULL); see SNESFunction for calling sequence details
2279e4357dc4SBarry Smith .  Amat - the matrix used to defined the operation A(x) x - b(x) (or NULL)
2280e4357dc4SBarry Smith .  Pmat  - the matrix from which the preconditioner will be constructed (or NULL)
2281f8b49ee9SBarry Smith .  J - the function for matrix evaluation (or NULL); see SNESJacobianFunction for calling sequence details
22820298fd71SBarry Smith -  ctx - the function context (or NULL)
22837971a8bfSPeter Brune 
22847971a8bfSPeter Brune    Level: advanced
22857971a8bfSPeter Brune 
22867971a8bfSPeter Brune .keywords: SNES, nonlinear, get, function
22877971a8bfSPeter Brune 
2288e4357dc4SBarry Smith .seealso: SNESSetPicard(), SNESGetFunction(), SNESGetJacobian(), SNESGetDM(), SNESFunction, SNESJacobianFunction
22897971a8bfSPeter Brune @*/
2290d1e9a80fSBarry 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)
22917971a8bfSPeter Brune {
22927971a8bfSPeter Brune   PetscErrorCode ierr;
22937971a8bfSPeter Brune   DM             dm;
22947971a8bfSPeter Brune 
22957971a8bfSPeter Brune   PetscFunctionBegin;
22967971a8bfSPeter Brune   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
22970298fd71SBarry Smith   ierr = SNESGetFunction(snes,r,NULL,NULL);CHKERRQ(ierr);
2298e4357dc4SBarry Smith   ierr = SNESGetJacobian(snes,Amat,Pmat,NULL,NULL);CHKERRQ(ierr);
22997971a8bfSPeter Brune   ierr = SNESGetDM(snes,&dm);CHKERRQ(ierr);
2300f8b49ee9SBarry Smith   ierr = DMSNESGetPicard(dm,f,J,ctx);CHKERRQ(ierr);
23017971a8bfSPeter Brune   PetscFunctionReturn(0);
23027971a8bfSPeter Brune }
23037971a8bfSPeter Brune 
2304d25893d9SBarry Smith /*@C
2305d25893d9SBarry Smith    SNESSetComputeInitialGuess - Sets a routine used to compute an initial guess for the problem
2306d25893d9SBarry Smith 
2307d25893d9SBarry Smith    Logically Collective on SNES
2308d25893d9SBarry Smith 
2309d25893d9SBarry Smith    Input Parameters:
2310d25893d9SBarry Smith +  snes - the SNES context
2311d25893d9SBarry Smith .  func - function evaluation routine
2312d25893d9SBarry Smith -  ctx - [optional] user-defined context for private data for the
23130298fd71SBarry Smith          function evaluation routine (may be NULL)
2314d25893d9SBarry Smith 
2315d25893d9SBarry Smith    Calling sequence of func:
2316d25893d9SBarry Smith $    func (SNES snes,Vec x,void *ctx);
2317d25893d9SBarry Smith 
2318d25893d9SBarry Smith .  f - function vector
2319d25893d9SBarry Smith -  ctx - optional user-defined function context
2320d25893d9SBarry Smith 
2321d25893d9SBarry Smith    Level: intermediate
2322d25893d9SBarry Smith 
2323d25893d9SBarry Smith .keywords: SNES, nonlinear, set, function
2324d25893d9SBarry Smith 
2325d25893d9SBarry Smith .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian()
2326d25893d9SBarry Smith @*/
2327d25893d9SBarry Smith PetscErrorCode  SNESSetComputeInitialGuess(SNES snes,PetscErrorCode (*func)(SNES,Vec,void*),void *ctx)
2328d25893d9SBarry Smith {
2329d25893d9SBarry Smith   PetscFunctionBegin;
2330d25893d9SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
2331d25893d9SBarry Smith   if (func) snes->ops->computeinitialguess = func;
2332d25893d9SBarry Smith   if (ctx)  snes->initialguessP            = ctx;
2333d25893d9SBarry Smith   PetscFunctionReturn(0);
2334d25893d9SBarry Smith }
2335d25893d9SBarry Smith 
23363ab0aad5SBarry Smith /* --------------------------------------------------------------- */
23371096aae1SMatthew Knepley /*@C
23381096aae1SMatthew Knepley    SNESGetRhs - Gets the vector for solving F(x) = rhs. If rhs is not set
23391096aae1SMatthew Knepley    it assumes a zero right hand side.
23401096aae1SMatthew Knepley 
23413f9fe445SBarry Smith    Logically Collective on SNES
23421096aae1SMatthew Knepley 
23431096aae1SMatthew Knepley    Input Parameter:
23441096aae1SMatthew Knepley .  snes - the SNES context
23451096aae1SMatthew Knepley 
23461096aae1SMatthew Knepley    Output Parameter:
23470298fd71SBarry Smith .  rhs - the right hand side vector or NULL if the right hand side vector is null
23481096aae1SMatthew Knepley 
23491096aae1SMatthew Knepley    Level: intermediate
23501096aae1SMatthew Knepley 
23511096aae1SMatthew Knepley .keywords: SNES, nonlinear, get, function, right hand side
23521096aae1SMatthew Knepley 
235385385478SLisandro Dalcin .seealso: SNESGetSolution(), SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetFunction()
23541096aae1SMatthew Knepley @*/
23557087cfbeSBarry Smith PetscErrorCode  SNESGetRhs(SNES snes,Vec *rhs)
23561096aae1SMatthew Knepley {
23571096aae1SMatthew Knepley   PetscFunctionBegin;
23580700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
23591096aae1SMatthew Knepley   PetscValidPointer(rhs,2);
236085385478SLisandro Dalcin   *rhs = snes->vec_rhs;
23611096aae1SMatthew Knepley   PetscFunctionReturn(0);
23621096aae1SMatthew Knepley }
23631096aae1SMatthew Knepley 
23649b94acceSBarry Smith /*@
2365bf388a1fSBarry Smith    SNESComputeFunction - Calls the function that has been set with SNESSetFunction().
23669b94acceSBarry Smith 
2367c7afd0dbSLois Curfman McInnes    Collective on SNES
2368c7afd0dbSLois Curfman McInnes 
23699b94acceSBarry Smith    Input Parameters:
2370c7afd0dbSLois Curfman McInnes +  snes - the SNES context
2371c7afd0dbSLois Curfman McInnes -  x - input vector
23729b94acceSBarry Smith 
23739b94acceSBarry Smith    Output Parameter:
23743638b69dSLois Curfman McInnes .  y - function vector, as set by SNESSetFunction()
23759b94acceSBarry Smith 
23761bffabb2SLois Curfman McInnes    Notes:
237736851e7fSLois Curfman McInnes    SNESComputeFunction() is typically used within nonlinear solvers
237836851e7fSLois Curfman McInnes    implementations, so most users would not generally call this routine
237936851e7fSLois Curfman McInnes    themselves.
238036851e7fSLois Curfman McInnes 
238136851e7fSLois Curfman McInnes    Level: developer
238236851e7fSLois Curfman McInnes 
23839b94acceSBarry Smith .keywords: SNES, nonlinear, compute, function
23849b94acceSBarry Smith 
2385a86d99e1SLois Curfman McInnes .seealso: SNESSetFunction(), SNESGetFunction()
23869b94acceSBarry Smith @*/
23877087cfbeSBarry Smith PetscErrorCode  SNESComputeFunction(SNES snes,Vec x,Vec y)
23889b94acceSBarry Smith {
2389dfbe8321SBarry Smith   PetscErrorCode ierr;
23906cab3a1bSJed Brown   DM             dm;
2391942e3340SBarry Smith   DMSNES         sdm;
23929b94acceSBarry Smith 
23933a40ed3dSBarry Smith   PetscFunctionBegin;
23940700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
23950700a824SBarry Smith   PetscValidHeaderSpecific(x,VEC_CLASSID,2);
23960700a824SBarry Smith   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
2397c9780b6fSBarry Smith   PetscCheckSameComm(snes,1,x,2);
2398c9780b6fSBarry Smith   PetscCheckSameComm(snes,1,y,3);
239962796dfbSBarry Smith   ierr = VecValidValues(x,2,PETSC_TRUE);CHKERRQ(ierr);
2400184914b5SBarry Smith 
24016cab3a1bSJed Brown   ierr = SNESGetDM(snes,&dm);CHKERRQ(ierr);
2402942e3340SBarry Smith   ierr = DMGetDMSNES(dm,&sdm);CHKERRQ(ierr);
240332f3f7c2SPeter Brune   if (sdm->ops->computefunction) {
240494db00ebSBarry Smith     if (sdm->ops->computefunction != SNESObjectiveComputeFunctionDefaultFD) {
2405ccf3c845SPeter Brune       ierr = PetscLogEventBegin(SNES_FunctionEval,snes,x,y,0);CHKERRQ(ierr);
240694db00ebSBarry Smith     }
24078860a134SJunchao Zhang     ierr = VecLockReadPush(x);CHKERRQ(ierr);
2408d64ed03dSBarry Smith     PetscStackPush("SNES user function");
240922c6f798SBarry Smith     ierr = (*sdm->ops->computefunction)(snes,x,y,sdm->functionctx);CHKERRQ(ierr);
2410d64ed03dSBarry Smith     PetscStackPop;
24118860a134SJunchao Zhang     ierr = VecLockReadPop(x);CHKERRQ(ierr);
241294db00ebSBarry Smith     if (sdm->ops->computefunction != SNESObjectiveComputeFunctionDefaultFD) {
2413ccf3c845SPeter Brune       ierr = PetscLogEventEnd(SNES_FunctionEval,snes,x,y,0);CHKERRQ(ierr);
241494db00ebSBarry Smith     }
2415c90fad12SPeter Brune   } else if (snes->vec_rhs) {
2416c90fad12SPeter Brune     ierr = MatMult(snes->jacobian, x, y);CHKERRQ(ierr);
2417644e2e5bSBarry Smith   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetFunction() or SNESSetDM() before SNESComputeFunction(), likely called from SNESSolve().");
241885385478SLisandro Dalcin   if (snes->vec_rhs) {
241985385478SLisandro Dalcin     ierr = VecAXPY(y,-1.0,snes->vec_rhs);CHKERRQ(ierr);
24203ab0aad5SBarry Smith   }
2421ae3c334cSLois Curfman McInnes   snes->nfuncs++;
2422422a814eSBarry Smith   /*
2423422a814eSBarry Smith      domainerror might not be set on all processes; so we tag vector locally with Inf and the next inner product or norm will
2424422a814eSBarry Smith      propagate the value to all processes
2425422a814eSBarry Smith   */
2426422a814eSBarry Smith   if (snes->domainerror) {
2427422a814eSBarry Smith     ierr = VecSetInf(y);CHKERRQ(ierr);
2428422a814eSBarry Smith   }
24293a40ed3dSBarry Smith   PetscFunctionReturn(0);
24309b94acceSBarry Smith }
24319b94acceSBarry Smith 
2432c79ef259SPeter Brune /*@
2433be95d8f1SBarry Smith    SNESComputeNGS - Calls the Gauss-Seidel function that has been set with  SNESSetNGS().
2434c79ef259SPeter Brune 
2435c79ef259SPeter Brune    Collective on SNES
2436c79ef259SPeter Brune 
2437c79ef259SPeter Brune    Input Parameters:
2438c79ef259SPeter Brune +  snes - the SNES context
2439c79ef259SPeter Brune .  x - input vector
2440c79ef259SPeter Brune -  b - rhs vector
2441c79ef259SPeter Brune 
2442c79ef259SPeter Brune    Output Parameter:
2443c79ef259SPeter Brune .  x - new solution vector
2444c79ef259SPeter Brune 
2445c79ef259SPeter Brune    Notes:
2446be95d8f1SBarry Smith    SNESComputeNGS() is typically used within composed nonlinear solver
2447c79ef259SPeter Brune    implementations, so most users would not generally call this routine
2448c79ef259SPeter Brune    themselves.
2449c79ef259SPeter Brune 
2450c79ef259SPeter Brune    Level: developer
2451c79ef259SPeter Brune 
2452c79ef259SPeter Brune .keywords: SNES, nonlinear, compute, function
2453c79ef259SPeter Brune 
2454be95d8f1SBarry Smith .seealso: SNESSetNGS(), SNESComputeFunction()
2455c79ef259SPeter Brune @*/
2456be95d8f1SBarry Smith PetscErrorCode  SNESComputeNGS(SNES snes,Vec b,Vec x)
2457646217ecSPeter Brune {
2458646217ecSPeter Brune   PetscErrorCode ierr;
24596cab3a1bSJed Brown   DM             dm;
2460942e3340SBarry Smith   DMSNES         sdm;
2461646217ecSPeter Brune 
2462646217ecSPeter Brune   PetscFunctionBegin;
2463646217ecSPeter Brune   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
2464646217ecSPeter Brune   PetscValidHeaderSpecific(x,VEC_CLASSID,2);
2465646217ecSPeter Brune   if (b) PetscValidHeaderSpecific(b,VEC_CLASSID,3);
2466646217ecSPeter Brune   PetscCheckSameComm(snes,1,x,2);
2467646217ecSPeter Brune   if (b) PetscCheckSameComm(snes,1,b,3);
246862796dfbSBarry Smith   if (b) {ierr = VecValidValues(b,2,PETSC_TRUE);CHKERRQ(ierr);}
2469be95d8f1SBarry Smith   ierr = PetscLogEventBegin(SNES_NGSEval,snes,x,b,0);CHKERRQ(ierr);
24706cab3a1bSJed Brown   ierr = SNESGetDM(snes,&dm);CHKERRQ(ierr);
2471942e3340SBarry Smith   ierr = DMGetDMSNES(dm,&sdm);CHKERRQ(ierr);
247222c6f798SBarry Smith   if (sdm->ops->computegs) {
24738860a134SJunchao Zhang     if (b) {ierr = VecLockReadPush(b);CHKERRQ(ierr);}
2474be95d8f1SBarry Smith     PetscStackPush("SNES user NGS");
247522c6f798SBarry Smith     ierr = (*sdm->ops->computegs)(snes,x,b,sdm->gsctx);CHKERRQ(ierr);
2476646217ecSPeter Brune     PetscStackPop;
24778860a134SJunchao Zhang     if (b) {ierr = VecLockReadPop(b);CHKERRQ(ierr);}
2478be95d8f1SBarry Smith   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetNGS() before SNESComputeNGS(), likely called from SNESSolve().");
2479be95d8f1SBarry Smith   ierr = PetscLogEventEnd(SNES_NGSEval,snes,x,b,0);CHKERRQ(ierr);
2480646217ecSPeter Brune   PetscFunctionReturn(0);
2481646217ecSPeter Brune }
2482646217ecSPeter Brune 
2483e885f1abSBarry Smith PetscErrorCode SNESTestJacobian(SNES snes)
2484e885f1abSBarry Smith {
248512837594SBarry Smith   Mat               A,B,C,D,jacobian;
2486e885f1abSBarry Smith   Vec               x = snes->vec_sol,f = snes->vec_func;
2487e885f1abSBarry Smith   PetscErrorCode    ierr;
2488e885f1abSBarry Smith   PetscReal         nrm,gnorm;
248981e7118cSBarry Smith   PetscReal         threshold = 1.e-5;
2490e885f1abSBarry Smith   PetscInt          m,n,M,N;
2491e885f1abSBarry Smith   void              *functx;
249218d89885SKarl Rupp   PetscBool         complete_print = PETSC_FALSE,threshold_print = PETSC_FALSE,test = PETSC_FALSE,flg;
24933325ff46SBarry Smith   PetscViewer       viewer,mviewer;
2494e885f1abSBarry Smith   MPI_Comm          comm;
2495e885f1abSBarry Smith   PetscInt          tabs;
249612837594SBarry Smith   static PetscBool  directionsprinted = PETSC_FALSE;
24973325ff46SBarry Smith   PetscViewerFormat format;
2498e885f1abSBarry Smith 
2499e885f1abSBarry Smith   PetscFunctionBegin;
2500fc35ed60SBarry Smith   ierr = PetscObjectOptionsBegin((PetscObject)snes);CHKERRQ(ierr);
250112837594SBarry Smith   ierr = PetscOptionsName("-snes_test_jacobian","Compare hand-coded and finite difference Jacobians","None",&test);CHKERRQ(ierr);
250212837594SBarry Smith   ierr = PetscOptionsReal("-snes_test_jacobian", "Threshold for element difference between hand-coded and finite difference being meaningful", "None", threshold, &threshold,NULL);CHKERRQ(ierr);
25033325ff46SBarry Smith   ierr = PetscOptionsViewer("-snes_test_jacobian_view","View difference between hand-coded and finite difference Jacobians element entries","None",&mviewer,&format,&complete_print);CHKERRQ(ierr);
250418d89885SKarl Rupp   if (!complete_print) {
250518d89885SKarl Rupp     ierr = PetscOptionsViewer("-snes_test_jacobian_display","Display difference between hand-coded and finite difference Jacobians","None",&mviewer,&format,&complete_print);CHKERRQ(ierr);
250618d89885SKarl Rupp   }
250718d89885SKarl Rupp   /* for compatibility with PETSc 3.9 and older. */
250818d89885SKarl Rupp   ierr = PetscOptionsReal("-snes_test_jacobian_display_threshold", "Display difference between hand-coded and finite difference Jacobians which exceed input threshold", "None", threshold, &threshold, &threshold_print);CHKERRQ(ierr);
2509e885f1abSBarry Smith   ierr = PetscOptionsEnd();CHKERRQ(ierr);
2510e885f1abSBarry Smith   if (!test) PetscFunctionReturn(0);
2511e885f1abSBarry Smith 
2512e885f1abSBarry Smith   ierr = PetscObjectGetComm((PetscObject)snes,&comm);CHKERRQ(ierr);
2513e885f1abSBarry Smith   ierr = PetscViewerASCIIGetStdout(comm,&viewer);CHKERRQ(ierr);
2514e885f1abSBarry Smith   ierr = PetscViewerASCIIGetTab(viewer, &tabs);CHKERRQ(ierr);
2515e885f1abSBarry Smith   ierr = PetscViewerASCIISetTab(viewer, ((PetscObject)snes)->tablevel);CHKERRQ(ierr);
251612837594SBarry Smith   ierr = PetscViewerASCIIPrintf(viewer,"  ---------- Testing Jacobian -------------\n");CHKERRQ(ierr);
251712837594SBarry Smith   if (!complete_print && !directionsprinted) {
251812837594SBarry Smith     ierr = PetscViewerASCIIPrintf(viewer,"  Run with -snes_test_jacobian_view and optionally -snes_test_jacobian <threshold> to show difference\n");CHKERRQ(ierr);
2519fc35ed60SBarry Smith     ierr = PetscViewerASCIIPrintf(viewer,"    of hand-coded and finite difference Jacobian entries greater than <threshold>.\n");CHKERRQ(ierr);
252012837594SBarry Smith   }
252112837594SBarry Smith   if (!directionsprinted) {
252212837594SBarry Smith     ierr = PetscViewerASCIIPrintf(viewer,"  Testing hand-coded Jacobian, if (for double precision runs) ||J - Jfd||_F/||J||_F is\n");CHKERRQ(ierr);
2523e885f1abSBarry Smith     ierr = PetscViewerASCIIPrintf(viewer,"    O(1.e-8), the hand-coded Jacobian is probably correct.\n");CHKERRQ(ierr);
252412837594SBarry Smith     directionsprinted = PETSC_TRUE;
2525e885f1abSBarry Smith   }
25263325ff46SBarry Smith   if (complete_print) {
25273325ff46SBarry Smith     ierr = PetscViewerPushFormat(mviewer,format);CHKERRQ(ierr);
2528e885f1abSBarry Smith   }
2529e885f1abSBarry Smith 
253012837594SBarry Smith   /* evaluate the function at this point because SNESComputeJacobianDefault() assumes that the function has been evaluated and put into snes->vec_func */
2531e885f1abSBarry Smith   ierr = SNESComputeFunction(snes,x,f);CHKERRQ(ierr);
253212837594SBarry Smith 
253312837594SBarry Smith   ierr = PetscObjectTypeCompare((PetscObject)snes->jacobian,MATMFFD,&flg);CHKERRQ(ierr);
253412837594SBarry Smith   if (!flg) jacobian = snes->jacobian;
253512837594SBarry Smith   else jacobian = snes->jacobian_pre;
253612837594SBarry Smith 
253712837594SBarry Smith   while (jacobian) {
253812837594SBarry Smith     ierr = PetscObjectTypeCompareAny((PetscObject)jacobian,&flg,MATSEQAIJ,MATMPIAIJ,MATSEQDENSE,MATMPIDENSE,MATSEQBAIJ,MATMPIBAIJ,MATSEQSBAIJ,MATMPIBAIJ,"");CHKERRQ(ierr);
253912837594SBarry Smith     if (flg) {
254012837594SBarry Smith       A    = jacobian;
254112837594SBarry Smith       ierr = PetscObjectReference((PetscObject)A);CHKERRQ(ierr);
254212837594SBarry Smith     } else {
25430bacdadaSStefano Zampini       ierr = MatComputeOperator(jacobian,MATAIJ,&A);CHKERRQ(ierr);
254412837594SBarry Smith     }
2545e885f1abSBarry Smith 
2546e885f1abSBarry Smith     ierr = MatCreate(PetscObjectComm((PetscObject)A),&B);CHKERRQ(ierr);
2547e885f1abSBarry Smith     ierr = MatGetSize(A,&M,&N);CHKERRQ(ierr);
2548e885f1abSBarry Smith     ierr = MatGetLocalSize(A,&m,&n);CHKERRQ(ierr);
2549e885f1abSBarry Smith     ierr = MatSetSizes(B,m,n,M,N);CHKERRQ(ierr);
2550e885f1abSBarry Smith     ierr = MatSetType(B,((PetscObject)A)->type_name);CHKERRQ(ierr);
2551e885f1abSBarry Smith     ierr = MatSetUp(B);CHKERRQ(ierr);
2552e885f1abSBarry Smith     ierr = MatSetOption(B,MAT_NEW_NONZERO_ALLOCATION_ERR,PETSC_FALSE);CHKERRQ(ierr);
2553e885f1abSBarry Smith 
2554e885f1abSBarry Smith     ierr = SNESGetFunction(snes,NULL,NULL,&functx);CHKERRQ(ierr);
2555e885f1abSBarry Smith     ierr = SNESComputeJacobianDefault(snes,x,B,B,functx);CHKERRQ(ierr);
255612837594SBarry Smith 
255712837594SBarry Smith     ierr = MatDuplicate(B,MAT_COPY_VALUES,&D);CHKERRQ(ierr);
255812837594SBarry Smith     ierr = MatAYPX(D,-1.0,A,DIFFERENT_NONZERO_PATTERN);CHKERRQ(ierr);
255912837594SBarry Smith     ierr = MatNorm(D,NORM_FROBENIUS,&nrm);CHKERRQ(ierr);
2560e885f1abSBarry Smith     ierr = MatNorm(A,NORM_FROBENIUS,&gnorm);CHKERRQ(ierr);
256112837594SBarry Smith     ierr = MatDestroy(&D);CHKERRQ(ierr);
256212837594SBarry Smith     if (!gnorm) gnorm = 1; /* just in case */
256312837594SBarry Smith     ierr = PetscViewerASCIIPrintf(viewer,"  ||J - Jfd||_F/||J||_F = %g, ||J - Jfd||_F = %g\n",(double)(nrm/gnorm),(double)nrm);CHKERRQ(ierr);
256412837594SBarry Smith 
2565e885f1abSBarry Smith     if (complete_print) {
256612837594SBarry Smith       ierr = PetscViewerASCIIPrintf(viewer,"  Hand-coded Jacobian ----------\n");CHKERRQ(ierr);
25673325ff46SBarry Smith       ierr = MatView(jacobian,mviewer);CHKERRQ(ierr);
256812837594SBarry Smith       ierr = PetscViewerASCIIPrintf(viewer,"  Finite difference Jacobian ----------\n");CHKERRQ(ierr);
25693325ff46SBarry Smith       ierr = MatView(B,mviewer);CHKERRQ(ierr);
2570e885f1abSBarry Smith     }
2571e885f1abSBarry Smith 
2572df10fb39SFande Kong     if (threshold_print || complete_print) {
2573e885f1abSBarry Smith       PetscInt          Istart, Iend, *ccols, bncols, cncols, j, row;
2574e885f1abSBarry Smith       PetscScalar       *cvals;
2575e885f1abSBarry Smith       const PetscInt    *bcols;
2576e885f1abSBarry Smith       const PetscScalar *bvals;
2577e885f1abSBarry Smith 
257812837594SBarry Smith       ierr = MatAYPX(B,-1.0,A,DIFFERENT_NONZERO_PATTERN);CHKERRQ(ierr);
2579e885f1abSBarry Smith       ierr = MatCreate(PetscObjectComm((PetscObject)A),&C);CHKERRQ(ierr);
2580e885f1abSBarry Smith       ierr = MatSetSizes(C,m,n,M,N);CHKERRQ(ierr);
2581e885f1abSBarry Smith       ierr = MatSetType(C,((PetscObject)A)->type_name);CHKERRQ(ierr);
2582e885f1abSBarry Smith       ierr = MatSetUp(C);CHKERRQ(ierr);
2583e885f1abSBarry Smith       ierr = MatSetOption(C,MAT_NEW_NONZERO_ALLOCATION_ERR,PETSC_FALSE);CHKERRQ(ierr);
2584e885f1abSBarry Smith       ierr = MatGetOwnershipRange(B,&Istart,&Iend);CHKERRQ(ierr);
2585e885f1abSBarry Smith 
2586e885f1abSBarry Smith       for (row = Istart; row < Iend; row++) {
2587e885f1abSBarry Smith         ierr = MatGetRow(B,row,&bncols,&bcols,&bvals);CHKERRQ(ierr);
2588e885f1abSBarry Smith         ierr = PetscMalloc2(bncols,&ccols,bncols,&cvals);CHKERRQ(ierr);
2589e885f1abSBarry Smith         for (j = 0, cncols = 0; j < bncols; j++) {
259023a52b1dSBarry Smith           if (PetscAbsScalar(bvals[j]) > threshold) {
2591e885f1abSBarry Smith             ccols[cncols] = bcols[j];
2592e885f1abSBarry Smith             cvals[cncols] = bvals[j];
2593e885f1abSBarry Smith             cncols += 1;
2594e885f1abSBarry Smith           }
2595e885f1abSBarry Smith         }
2596e885f1abSBarry Smith         if (cncols) {
2597e885f1abSBarry Smith           ierr = MatSetValues(C,1,&row,cncols,ccols,cvals,INSERT_VALUES);CHKERRQ(ierr);
2598e885f1abSBarry Smith         }
2599e885f1abSBarry Smith         ierr = MatRestoreRow(B,row,&bncols,&bcols,&bvals);CHKERRQ(ierr);
2600e885f1abSBarry Smith         ierr = PetscFree2(ccols,cvals);CHKERRQ(ierr);
2601e885f1abSBarry Smith       }
2602e885f1abSBarry Smith       ierr = MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
2603e885f1abSBarry Smith       ierr = MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
260412837594SBarry Smith       ierr = PetscViewerASCIIPrintf(viewer,"  Hand-coded minus finite-difference Jacobian with tolerance %g ----------\n",(double)threshold);CHKERRQ(ierr);
260518d89885SKarl Rupp       ierr = MatView(C,complete_print ? mviewer : viewer);CHKERRQ(ierr);
2606e885f1abSBarry Smith       ierr = MatDestroy(&C);CHKERRQ(ierr);
2607e885f1abSBarry Smith     }
260812837594SBarry Smith     ierr = MatDestroy(&A);CHKERRQ(ierr);
2609e885f1abSBarry Smith     ierr = MatDestroy(&B);CHKERRQ(ierr);
261012837594SBarry Smith 
261112837594SBarry Smith     if (jacobian != snes->jacobian_pre) {
261212837594SBarry Smith       jacobian = snes->jacobian_pre;
261312837594SBarry Smith       ierr = PetscViewerASCIIPrintf(viewer,"  ---------- Testing Jacobian for preconditioner -------------\n");CHKERRQ(ierr);
261412837594SBarry Smith     }
261512837594SBarry Smith     else jacobian = NULL;
261612837594SBarry Smith   }
26173325ff46SBarry Smith   if (complete_print) {
26183325ff46SBarry Smith     ierr = PetscViewerPopFormat(mviewer);CHKERRQ(ierr);
26193325ff46SBarry Smith   }
2620a0c90127SFande Kong   if (mviewer) { ierr = PetscViewerDestroy(&mviewer);CHKERRQ(ierr); }
2621e885f1abSBarry Smith   ierr = PetscViewerASCIISetTab(viewer,tabs);CHKERRQ(ierr);
2622e885f1abSBarry Smith   PetscFunctionReturn(0);
2623e885f1abSBarry Smith }
2624e885f1abSBarry Smith 
262562fef451SLois Curfman McInnes /*@
2626bf388a1fSBarry Smith    SNESComputeJacobian - Computes the Jacobian matrix that has been set with SNESSetJacobian().
262762fef451SLois Curfman McInnes 
2628c7afd0dbSLois Curfman McInnes    Collective on SNES and Mat
2629c7afd0dbSLois Curfman McInnes 
263062fef451SLois Curfman McInnes    Input Parameters:
2631c7afd0dbSLois Curfman McInnes +  snes - the SNES context
2632c7afd0dbSLois Curfman McInnes -  x - input vector
263362fef451SLois Curfman McInnes 
263462fef451SLois Curfman McInnes    Output Parameters:
2635c7afd0dbSLois Curfman McInnes +  A - Jacobian matrix
2636d1e9a80fSBarry Smith -  B - optional preconditioning matrix
2637fee21e36SBarry Smith 
2638e35cf81dSBarry Smith   Options Database Keys:
2639e35cf81dSBarry Smith +    -snes_lag_preconditioner <lag>
2640693365a8SJed Brown .    -snes_lag_jacobian <lag>
2641e885f1abSBarry Smith .    -snes_test_jacobian - compare the user provided Jacobian with one compute via finite differences to check for errors
2642e885f1abSBarry Smith .    -snes_test_jacobian_display - 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
2643e885f1abSBarry Smith .    -snes_test_jacobian_display_threshold <numerical value>  - display entries in the difference between the user provided Jacobian and finite difference Jacobian that are greater than a certain value to help users detect errors
2644693365a8SJed Brown .    -snes_compare_explicit - Compare the computed Jacobian to the finite difference Jacobian and output the differences
2645693365a8SJed Brown .    -snes_compare_explicit_draw  - Compare the computed Jacobian to the finite difference Jacobian and draw the result
2646693365a8SJed Brown .    -snes_compare_explicit_contour  - Compare the computed Jacobian to the finite difference Jacobian and draw a contour plot with the result
26474c30e9fbSJed Brown .    -snes_compare_operator  - Make the comparison options above use the operator instead of the preconditioning matrix
264894d6a431SBarry Smith .    -snes_compare_coloring - Compute the finite difference Jacobian using coloring and display norms of difference
2649c01495d3SJed Brown .    -snes_compare_coloring_display - Compute the finite differece Jacobian using coloring and display verbose differences
2650c01495d3SJed Brown .    -snes_compare_coloring_threshold - Display only those matrix entries that differ by more than a given threshold
2651c01495d3SJed Brown .    -snes_compare_coloring_threshold_atol - Absolute tolerance for difference in matrix entries to be displayed by -snes_compare_coloring_threshold
2652c01495d3SJed Brown .    -snes_compare_coloring_threshold_rtol - Relative tolerance for difference in matrix entries to be displayed by -snes_compare_coloring_threshold
26534c30e9fbSJed Brown .    -snes_compare_coloring_draw - Compute the finite differece Jacobian using coloring and draw differences
2654c01495d3SJed Brown -    -snes_compare_coloring_draw_contour - Compute the finite differece Jacobian using coloring and show contours of matrices and differences
2655c01495d3SJed Brown 
2656e35cf81dSBarry Smith 
265762fef451SLois Curfman McInnes    Notes:
265862fef451SLois Curfman McInnes    Most users should not need to explicitly call this routine, as it
265962fef451SLois Curfman McInnes    is used internally within the nonlinear solvers.
266062fef451SLois Curfman McInnes 
266195452b02SPatrick Sanan    Developer Notes:
266295452b02SPatrick 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
2663e885f1abSBarry Smith       for with the SNESType of test that has been removed.
2664e885f1abSBarry Smith 
266536851e7fSLois Curfman McInnes    Level: developer
266636851e7fSLois Curfman McInnes 
266762fef451SLois Curfman McInnes .keywords: SNES, compute, Jacobian, matrix
266862fef451SLois Curfman McInnes 
2669e35cf81dSBarry Smith .seealso:  SNESSetJacobian(), KSPSetOperators(), MatStructure, SNESSetLagPreconditioner(), SNESSetLagJacobian()
267062fef451SLois Curfman McInnes @*/
2671d1e9a80fSBarry Smith PetscErrorCode  SNESComputeJacobian(SNES snes,Vec X,Mat A,Mat B)
26729b94acceSBarry Smith {
2673dfbe8321SBarry Smith   PetscErrorCode ierr;
2674ace3abfcSBarry Smith   PetscBool      flag;
26756cab3a1bSJed Brown   DM             dm;
2676942e3340SBarry Smith   DMSNES         sdm;
2677e0e3a89bSBarry Smith   KSP            ksp;
26783a40ed3dSBarry Smith 
26793a40ed3dSBarry Smith   PetscFunctionBegin;
26800700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
26810700a824SBarry Smith   PetscValidHeaderSpecific(X,VEC_CLASSID,2);
2682c9780b6fSBarry Smith   PetscCheckSameComm(snes,1,X,2);
268362796dfbSBarry Smith   ierr = VecValidValues(X,2,PETSC_TRUE);CHKERRQ(ierr);
26846cab3a1bSJed Brown   ierr = SNESGetDM(snes,&dm);CHKERRQ(ierr);
2685942e3340SBarry Smith   ierr = DMGetDMSNES(dm,&sdm);CHKERRQ(ierr);
26863232da50SPeter Brune 
2687ce94432eSBarry Smith   if (!sdm->ops->computejacobian) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_USER,"Must call SNESSetJacobian(), DMSNESSetJacobian(), DMDASNESSetJacobianLocal(), etc");
2688ebd3b9afSBarry Smith 
2689ebd3b9afSBarry Smith   /* make sure that MatAssemblyBegin/End() is called on A matrix if it is matrix free */
2690ebd3b9afSBarry Smith 
2691fe3ffe1eSBarry Smith   if (snes->lagjacobian == -2) {
2692fe3ffe1eSBarry Smith     snes->lagjacobian = -1;
2693f5af7f23SKarl Rupp 
2694fe3ffe1eSBarry Smith     ierr = PetscInfo(snes,"Recomputing Jacobian/preconditioner because lag is -2 (means compute Jacobian, but then never again) \n");CHKERRQ(ierr);
2695fe3ffe1eSBarry Smith   } else if (snes->lagjacobian == -1) {
2696e35cf81dSBarry Smith     ierr = PetscInfo(snes,"Reusing Jacobian/preconditioner because lag is -1\n");CHKERRQ(ierr);
269794ab13aaSBarry Smith     ierr = PetscObjectTypeCompare((PetscObject)A,MATMFFD,&flag);CHKERRQ(ierr);
2698ebd3b9afSBarry Smith     if (flag) {
269994ab13aaSBarry Smith       ierr = MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
270094ab13aaSBarry Smith       ierr = MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
2701ebd3b9afSBarry Smith     }
2702e35cf81dSBarry Smith     PetscFunctionReturn(0);
270337ec4e1aSPeter Brune   } else if (snes->lagjacobian > 1 && (snes->iter + snes->jac_iter) % snes->lagjacobian) {
2704e35cf81dSBarry Smith     ierr = PetscInfo2(snes,"Reusing Jacobian/preconditioner because lag is %D and SNES iteration is %D\n",snes->lagjacobian,snes->iter);CHKERRQ(ierr);
270594ab13aaSBarry Smith     ierr = PetscObjectTypeCompare((PetscObject)A,MATMFFD,&flag);CHKERRQ(ierr);
2706ebd3b9afSBarry Smith     if (flag) {
270794ab13aaSBarry Smith       ierr = MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
270894ab13aaSBarry Smith       ierr = MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
2709ebd3b9afSBarry Smith     }
2710e35cf81dSBarry Smith     PetscFunctionReturn(0);
2711e35cf81dSBarry Smith   }
2712efd4aadfSBarry Smith   if (snes->npc && snes->npcside== PC_LEFT) {
271394ab13aaSBarry Smith       ierr = MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
271494ab13aaSBarry Smith       ierr = MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
2715d728fb7dSPeter Brune       PetscFunctionReturn(0);
2716d728fb7dSPeter Brune   }
2717e35cf81dSBarry Smith 
271894ab13aaSBarry Smith   ierr = PetscLogEventBegin(SNES_JacobianEval,snes,X,A,B);CHKERRQ(ierr);
27198860a134SJunchao Zhang   ierr = VecLockReadPush(X);CHKERRQ(ierr);
2720d64ed03dSBarry Smith   PetscStackPush("SNES user Jacobian function");
2721d1e9a80fSBarry Smith   ierr = (*sdm->ops->computejacobian)(snes,X,A,B,sdm->jacobianctx);CHKERRQ(ierr);
2722d64ed03dSBarry Smith   PetscStackPop;
27238860a134SJunchao Zhang   ierr = VecLockReadPop(X);CHKERRQ(ierr);
272494ab13aaSBarry Smith   ierr = PetscLogEventEnd(SNES_JacobianEval,snes,X,A,B);CHKERRQ(ierr);
2725a8054027SBarry Smith 
2726e0e3a89bSBarry Smith   /* the next line ensures that snes->ksp exists */
2727e0e3a89bSBarry Smith   ierr = SNESGetKSP(snes,&ksp);CHKERRQ(ierr);
27283b4f5425SBarry Smith   if (snes->lagpreconditioner == -2) {
27293b4f5425SBarry Smith     ierr = PetscInfo(snes,"Rebuilding preconditioner exactly once since lag is -2\n");CHKERRQ(ierr);
2730d1e9a80fSBarry Smith     ierr = KSPSetReusePreconditioner(snes->ksp,PETSC_FALSE);CHKERRQ(ierr);
27313b4f5425SBarry Smith     snes->lagpreconditioner = -1;
27323b4f5425SBarry Smith   } else if (snes->lagpreconditioner == -1) {
2733a8054027SBarry Smith     ierr = PetscInfo(snes,"Reusing preconditioner because lag is -1\n");CHKERRQ(ierr);
2734d1e9a80fSBarry Smith     ierr = KSPSetReusePreconditioner(snes->ksp,PETSC_TRUE);CHKERRQ(ierr);
273537ec4e1aSPeter Brune   } else if (snes->lagpreconditioner > 1 && (snes->iter + snes->pre_iter) % snes->lagpreconditioner) {
2736a8054027SBarry Smith     ierr = PetscInfo2(snes,"Reusing preconditioner because lag is %D and SNES iteration is %D\n",snes->lagpreconditioner,snes->iter);CHKERRQ(ierr);
2737d1e9a80fSBarry Smith     ierr = KSPSetReusePreconditioner(snes->ksp,PETSC_TRUE);CHKERRQ(ierr);
2738d1e9a80fSBarry Smith   } else {
2739d1e9a80fSBarry Smith     ierr = PetscInfo(snes,"Rebuilding preconditioner\n");CHKERRQ(ierr);
2740d1e9a80fSBarry Smith     ierr = KSPSetReusePreconditioner(snes->ksp,PETSC_FALSE);CHKERRQ(ierr);
2741a8054027SBarry Smith   }
2742a8054027SBarry Smith 
2743e885f1abSBarry Smith   ierr = SNESTestJacobian(snes);CHKERRQ(ierr);
27446d84be18SBarry Smith   /* make sure user returned a correct Jacobian and preconditioner */
274594ab13aaSBarry Smith   /* PetscValidHeaderSpecific(A,MAT_CLASSID,3);
274694ab13aaSBarry Smith     PetscValidHeaderSpecific(B,MAT_CLASSID,4);   */
2747693365a8SJed Brown   {
2748693365a8SJed Brown     PetscBool flag = PETSC_FALSE,flag_draw = PETSC_FALSE,flag_contour = PETSC_FALSE,flag_operator = PETSC_FALSE;
274916413a6aSBarry Smith     ierr = PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject) snes)->options,((PetscObject)snes)->prefix,"-snes_compare_explicit",NULL,NULL,&flag);CHKERRQ(ierr);
275016413a6aSBarry Smith     ierr = PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject) snes)->options,((PetscObject)snes)->prefix,"-snes_compare_explicit_draw",NULL,NULL,&flag_draw);CHKERRQ(ierr);
275116413a6aSBarry Smith     ierr = PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject) snes)->options,((PetscObject)snes)->prefix,"-snes_compare_explicit_draw_contour",NULL,NULL,&flag_contour);CHKERRQ(ierr);
275216413a6aSBarry Smith     ierr = PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject) snes)->options,((PetscObject)snes)->prefix,"-snes_compare_operator",NULL,NULL,&flag_operator);CHKERRQ(ierr);
2753693365a8SJed Brown     if (flag || flag_draw || flag_contour) {
27540298fd71SBarry Smith       Mat          Bexp_mine = NULL,Bexp,FDexp;
2755693365a8SJed Brown       PetscViewer  vdraw,vstdout;
27566b3a5b13SJed Brown       PetscBool    flg;
2757693365a8SJed Brown       if (flag_operator) {
27580bacdadaSStefano Zampini         ierr = MatComputeOperator(A,MATAIJ,&Bexp_mine);CHKERRQ(ierr);
2759693365a8SJed Brown         Bexp = Bexp_mine;
2760693365a8SJed Brown       } else {
2761693365a8SJed Brown         /* See if the preconditioning matrix can be viewed and added directly */
276294ab13aaSBarry Smith         ierr = PetscObjectTypeCompareAny((PetscObject)B,&flg,MATSEQAIJ,MATMPIAIJ,MATSEQDENSE,MATMPIDENSE,MATSEQBAIJ,MATMPIBAIJ,MATSEQSBAIJ,MATMPIBAIJ,"");CHKERRQ(ierr);
276394ab13aaSBarry Smith         if (flg) Bexp = B;
2764693365a8SJed Brown         else {
2765693365a8SJed Brown           /* If the "preconditioning" matrix is itself MATSHELL or some other type without direct support */
27660bacdadaSStefano Zampini           ierr = MatComputeOperator(B,MATAIJ,&Bexp_mine);CHKERRQ(ierr);
2767693365a8SJed Brown           Bexp = Bexp_mine;
2768693365a8SJed Brown         }
2769693365a8SJed Brown       }
2770693365a8SJed Brown       ierr = MatConvert(Bexp,MATSAME,MAT_INITIAL_MATRIX,&FDexp);CHKERRQ(ierr);
2771d1e9a80fSBarry Smith       ierr = SNESComputeJacobianDefault(snes,X,FDexp,FDexp,NULL);CHKERRQ(ierr);
2772ce94432eSBarry Smith       ierr = PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes),&vstdout);CHKERRQ(ierr);
2773693365a8SJed Brown       if (flag_draw || flag_contour) {
2774ce94432eSBarry Smith         ierr = PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes),0,"Explicit Jacobians",PETSC_DECIDE,PETSC_DECIDE,300,300,&vdraw);CHKERRQ(ierr);
2775693365a8SJed Brown         if (flag_contour) {ierr = PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR);CHKERRQ(ierr);}
27760298fd71SBarry Smith       } else vdraw = NULL;
2777693365a8SJed Brown       ierr = PetscViewerASCIIPrintf(vstdout,"Explicit %s\n",flag_operator ? "Jacobian" : "preconditioning Jacobian");CHKERRQ(ierr);
2778693365a8SJed Brown       if (flag) {ierr = MatView(Bexp,vstdout);CHKERRQ(ierr);}
2779693365a8SJed Brown       if (vdraw) {ierr = MatView(Bexp,vdraw);CHKERRQ(ierr);}
2780693365a8SJed Brown       ierr = PetscViewerASCIIPrintf(vstdout,"Finite difference Jacobian\n");CHKERRQ(ierr);
2781693365a8SJed Brown       if (flag) {ierr = MatView(FDexp,vstdout);CHKERRQ(ierr);}
2782693365a8SJed Brown       if (vdraw) {ierr = MatView(FDexp,vdraw);CHKERRQ(ierr);}
2783693365a8SJed Brown       ierr = MatAYPX(FDexp,-1.0,Bexp,SAME_NONZERO_PATTERN);CHKERRQ(ierr);
2784693365a8SJed Brown       ierr = PetscViewerASCIIPrintf(vstdout,"User-provided matrix minus finite difference Jacobian\n");CHKERRQ(ierr);
2785693365a8SJed Brown       if (flag) {ierr = MatView(FDexp,vstdout);CHKERRQ(ierr);}
2786693365a8SJed Brown       if (vdraw) {              /* Always use contour for the difference */
2787693365a8SJed Brown         ierr = PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR);CHKERRQ(ierr);
2788693365a8SJed Brown         ierr = MatView(FDexp,vdraw);CHKERRQ(ierr);
2789693365a8SJed Brown         ierr = PetscViewerPopFormat(vdraw);CHKERRQ(ierr);
2790693365a8SJed Brown       }
2791693365a8SJed Brown       if (flag_contour) {ierr = PetscViewerPopFormat(vdraw);CHKERRQ(ierr);}
2792693365a8SJed Brown       ierr = PetscViewerDestroy(&vdraw);CHKERRQ(ierr);
2793693365a8SJed Brown       ierr = MatDestroy(&Bexp_mine);CHKERRQ(ierr);
2794693365a8SJed Brown       ierr = MatDestroy(&FDexp);CHKERRQ(ierr);
2795693365a8SJed Brown     }
2796693365a8SJed Brown   }
27974c30e9fbSJed Brown   {
27986719d8e4SJed Brown     PetscBool flag = PETSC_FALSE,flag_display = PETSC_FALSE,flag_draw = PETSC_FALSE,flag_contour = PETSC_FALSE,flag_threshold = PETSC_FALSE;
27996719d8e4SJed Brown     PetscReal threshold_atol = PETSC_SQRT_MACHINE_EPSILON,threshold_rtol = 10*PETSC_SQRT_MACHINE_EPSILON;
280016413a6aSBarry Smith     ierr = PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring",NULL,NULL,&flag);CHKERRQ(ierr);
280116413a6aSBarry Smith     ierr = PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_display",NULL,NULL,&flag_display);CHKERRQ(ierr);
280216413a6aSBarry Smith     ierr = PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_draw",NULL,NULL,&flag_draw);CHKERRQ(ierr);
280316413a6aSBarry Smith     ierr = PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_draw_contour",NULL,NULL,&flag_contour);CHKERRQ(ierr);
280416413a6aSBarry Smith     ierr = PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_threshold",NULL,NULL,&flag_threshold);CHKERRQ(ierr);
280527b0f280SBarry Smith     if (flag_threshold) {
2806c5929fdfSBarry Smith       ierr = PetscOptionsGetReal(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_threshold_rtol",&threshold_rtol,NULL);CHKERRQ(ierr);
2807c5929fdfSBarry Smith       ierr = PetscOptionsGetReal(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_threshold_atol",&threshold_atol,NULL);CHKERRQ(ierr);
280827b0f280SBarry Smith     }
28096719d8e4SJed Brown     if (flag || flag_display || flag_draw || flag_contour || flag_threshold) {
28104c30e9fbSJed Brown       Mat            Bfd;
28114c30e9fbSJed Brown       PetscViewer    vdraw,vstdout;
2812335efc43SPeter Brune       MatColoring    coloring;
28134c30e9fbSJed Brown       ISColoring     iscoloring;
28144c30e9fbSJed Brown       MatFDColoring  matfdcoloring;
28154c30e9fbSJed Brown       PetscErrorCode (*func)(SNES,Vec,Vec,void*);
28164c30e9fbSJed Brown       void           *funcctx;
28176719d8e4SJed Brown       PetscReal      norm1,norm2,normmax;
28184c30e9fbSJed Brown 
281994ab13aaSBarry Smith       ierr = MatDuplicate(B,MAT_DO_NOT_COPY_VALUES,&Bfd);CHKERRQ(ierr);
2820335efc43SPeter Brune       ierr = MatColoringCreate(Bfd,&coloring);CHKERRQ(ierr);
2821335efc43SPeter Brune       ierr = MatColoringSetType(coloring,MATCOLORINGSL);CHKERRQ(ierr);
2822335efc43SPeter Brune       ierr = MatColoringSetFromOptions(coloring);CHKERRQ(ierr);
2823335efc43SPeter Brune       ierr = MatColoringApply(coloring,&iscoloring);CHKERRQ(ierr);
2824335efc43SPeter Brune       ierr = MatColoringDestroy(&coloring);CHKERRQ(ierr);
28254c30e9fbSJed Brown       ierr = MatFDColoringCreate(Bfd,iscoloring,&matfdcoloring);CHKERRQ(ierr);
2826f86b9fbaSHong Zhang       ierr = MatFDColoringSetFromOptions(matfdcoloring);CHKERRQ(ierr);
2827f86b9fbaSHong Zhang       ierr = MatFDColoringSetUp(Bfd,iscoloring,matfdcoloring);CHKERRQ(ierr);
28284c30e9fbSJed Brown       ierr = ISColoringDestroy(&iscoloring);CHKERRQ(ierr);
28294c30e9fbSJed Brown 
28304c30e9fbSJed Brown       /* This method of getting the function is currently unreliable since it doesn't work for DM local functions. */
28310298fd71SBarry Smith       ierr = SNESGetFunction(snes,NULL,&func,&funcctx);CHKERRQ(ierr);
28324c30e9fbSJed Brown       ierr = MatFDColoringSetFunction(matfdcoloring,(PetscErrorCode (*)(void))func,funcctx);CHKERRQ(ierr);
28334c30e9fbSJed Brown       ierr = PetscObjectSetOptionsPrefix((PetscObject)matfdcoloring,((PetscObject)snes)->prefix);CHKERRQ(ierr);
28344c30e9fbSJed Brown       ierr = PetscObjectAppendOptionsPrefix((PetscObject)matfdcoloring,"coloring_");CHKERRQ(ierr);
28354c30e9fbSJed Brown       ierr = MatFDColoringSetFromOptions(matfdcoloring);CHKERRQ(ierr);
2836d1e9a80fSBarry Smith       ierr = MatFDColoringApply(Bfd,matfdcoloring,X,snes);CHKERRQ(ierr);
28374c30e9fbSJed Brown       ierr = MatFDColoringDestroy(&matfdcoloring);CHKERRQ(ierr);
28384c30e9fbSJed Brown 
2839ce94432eSBarry Smith       ierr = PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes),&vstdout);CHKERRQ(ierr);
28404c30e9fbSJed Brown       if (flag_draw || flag_contour) {
2841ce94432eSBarry Smith         ierr = PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes),0,"Colored Jacobians",PETSC_DECIDE,PETSC_DECIDE,300,300,&vdraw);CHKERRQ(ierr);
28424c30e9fbSJed Brown         if (flag_contour) {ierr = PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR);CHKERRQ(ierr);}
28430298fd71SBarry Smith       } else vdraw = NULL;
28444c30e9fbSJed Brown       ierr = PetscViewerASCIIPrintf(vstdout,"Explicit preconditioning Jacobian\n");CHKERRQ(ierr);
284594ab13aaSBarry Smith       if (flag_display) {ierr = MatView(B,vstdout);CHKERRQ(ierr);}
284694ab13aaSBarry Smith       if (vdraw) {ierr = MatView(B,vdraw);CHKERRQ(ierr);}
28474c30e9fbSJed Brown       ierr = PetscViewerASCIIPrintf(vstdout,"Colored Finite difference Jacobian\n");CHKERRQ(ierr);
28486719d8e4SJed Brown       if (flag_display) {ierr = MatView(Bfd,vstdout);CHKERRQ(ierr);}
28494c30e9fbSJed Brown       if (vdraw) {ierr = MatView(Bfd,vdraw);CHKERRQ(ierr);}
285094ab13aaSBarry Smith       ierr = MatAYPX(Bfd,-1.0,B,SAME_NONZERO_PATTERN);CHKERRQ(ierr);
28514c30e9fbSJed Brown       ierr = MatNorm(Bfd,NORM_1,&norm1);CHKERRQ(ierr);
28526719d8e4SJed Brown       ierr = MatNorm(Bfd,NORM_FROBENIUS,&norm2);CHKERRQ(ierr);
28534c30e9fbSJed Brown       ierr = MatNorm(Bfd,NORM_MAX,&normmax);CHKERRQ(ierr);
285457622a8eSBarry Smith       ierr = PetscViewerASCIIPrintf(vstdout,"User-provided matrix minus finite difference Jacobian, norm1=%g normFrob=%g normmax=%g\n",(double)norm1,(double)norm2,(double)normmax);CHKERRQ(ierr);
28556719d8e4SJed Brown       if (flag_display) {ierr = MatView(Bfd,vstdout);CHKERRQ(ierr);}
28564c30e9fbSJed Brown       if (vdraw) {              /* Always use contour for the difference */
28574c30e9fbSJed Brown         ierr = PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR);CHKERRQ(ierr);
28584c30e9fbSJed Brown         ierr = MatView(Bfd,vdraw);CHKERRQ(ierr);
28594c30e9fbSJed Brown         ierr = PetscViewerPopFormat(vdraw);CHKERRQ(ierr);
28604c30e9fbSJed Brown       }
28614c30e9fbSJed Brown       if (flag_contour) {ierr = PetscViewerPopFormat(vdraw);CHKERRQ(ierr);}
28626719d8e4SJed Brown 
28636719d8e4SJed Brown       if (flag_threshold) {
28646719d8e4SJed Brown         PetscInt bs,rstart,rend,i;
286594ab13aaSBarry Smith         ierr = MatGetBlockSize(B,&bs);CHKERRQ(ierr);
286694ab13aaSBarry Smith         ierr = MatGetOwnershipRange(B,&rstart,&rend);CHKERRQ(ierr);
28676719d8e4SJed Brown         for (i=rstart; i<rend; i++) {
28686719d8e4SJed Brown           const PetscScalar *ba,*ca;
28696719d8e4SJed Brown           const PetscInt    *bj,*cj;
28706719d8e4SJed Brown           PetscInt          bn,cn,j,maxentrycol = -1,maxdiffcol = -1,maxrdiffcol = -1;
28716719d8e4SJed Brown           PetscReal         maxentry = 0,maxdiff = 0,maxrdiff = 0;
287294ab13aaSBarry Smith           ierr = MatGetRow(B,i,&bn,&bj,&ba);CHKERRQ(ierr);
28736719d8e4SJed Brown           ierr = MatGetRow(Bfd,i,&cn,&cj,&ca);CHKERRQ(ierr);
287494ab13aaSBarry Smith           if (bn != cn) SETERRQ(((PetscObject)A)->comm,PETSC_ERR_PLIB,"Unexpected different nonzero pattern in -snes_compare_coloring_threshold");
28756719d8e4SJed Brown           for (j=0; j<bn; j++) {
28766719d8e4SJed Brown             PetscReal rdiff = PetscAbsScalar(ca[j]) / (threshold_atol + threshold_rtol*PetscAbsScalar(ba[j]));
28776719d8e4SJed Brown             if (PetscAbsScalar(ba[j]) > PetscAbs(maxentry)) {
28786719d8e4SJed Brown               maxentrycol = bj[j];
28796719d8e4SJed Brown               maxentry    = PetscRealPart(ba[j]);
28806719d8e4SJed Brown             }
28816719d8e4SJed Brown             if (PetscAbsScalar(ca[j]) > PetscAbs(maxdiff)) {
28826719d8e4SJed Brown               maxdiffcol = bj[j];
28836719d8e4SJed Brown               maxdiff    = PetscRealPart(ca[j]);
28846719d8e4SJed Brown             }
28856719d8e4SJed Brown             if (rdiff > maxrdiff) {
28866719d8e4SJed Brown               maxrdiffcol = bj[j];
28876719d8e4SJed Brown               maxrdiff    = rdiff;
28886719d8e4SJed Brown             }
28896719d8e4SJed Brown           }
28906719d8e4SJed Brown           if (maxrdiff > 1) {
289157622a8eSBarry Smith             ierr = PetscViewerASCIIPrintf(vstdout,"row %D (maxentry=%g at %D, maxdiff=%g at %D, maxrdiff=%g at %D):",i,(double)maxentry,maxentrycol,(double)maxdiff,maxdiffcol,(double)maxrdiff,maxrdiffcol);CHKERRQ(ierr);
28926719d8e4SJed Brown             for (j=0; j<bn; j++) {
28936719d8e4SJed Brown               PetscReal rdiff;
28946719d8e4SJed Brown               rdiff = PetscAbsScalar(ca[j]) / (threshold_atol + threshold_rtol*PetscAbsScalar(ba[j]));
28956719d8e4SJed Brown               if (rdiff > 1) {
289657622a8eSBarry Smith                 ierr = PetscViewerASCIIPrintf(vstdout," (%D,%g:%g)",bj[j],(double)PetscRealPart(ba[j]),(double)PetscRealPart(ca[j]));CHKERRQ(ierr);
28976719d8e4SJed Brown               }
28986719d8e4SJed Brown             }
28996719d8e4SJed Brown             ierr = PetscViewerASCIIPrintf(vstdout,"\n",i,maxentry,maxdiff,maxrdiff);CHKERRQ(ierr);
29006719d8e4SJed Brown           }
290194ab13aaSBarry Smith           ierr = MatRestoreRow(B,i,&bn,&bj,&ba);CHKERRQ(ierr);
29026719d8e4SJed Brown           ierr = MatRestoreRow(Bfd,i,&cn,&cj,&ca);CHKERRQ(ierr);
29036719d8e4SJed Brown         }
29046719d8e4SJed Brown       }
29054c30e9fbSJed Brown       ierr = PetscViewerDestroy(&vdraw);CHKERRQ(ierr);
29064c30e9fbSJed Brown       ierr = MatDestroy(&Bfd);CHKERRQ(ierr);
29074c30e9fbSJed Brown     }
29084c30e9fbSJed Brown   }
29093a40ed3dSBarry Smith   PetscFunctionReturn(0);
29109b94acceSBarry Smith }
29119b94acceSBarry Smith 
2912bf388a1fSBarry Smith /*MC
2913411c0326SBarry Smith     SNESJacobianFunction - Function used to convey the nonlinear Jacobian of the function to be solved by SNES
2914bf388a1fSBarry Smith 
2915bf388a1fSBarry Smith      Synopsis:
2916411c0326SBarry Smith      #include "petscsnes.h"
2917411c0326SBarry Smith      PetscErrorCode SNESJacobianFunction(SNES snes,Vec x,Mat Amat,Mat Pmat,void *ctx);
2918bf388a1fSBarry Smith 
2919bf388a1fSBarry Smith +  x - input vector
2920e5d3d808SBarry Smith .  Amat - the matrix that defines the (approximate) Jacobian
2921e5d3d808SBarry Smith .  Pmat - the matrix to be used in constructing the preconditioner, usually the same as Amat.
2922bf388a1fSBarry Smith -  ctx - [optional] user-defined Jacobian context
2923bf388a1fSBarry Smith 
2924878cb397SSatish Balay    Level: intermediate
2925878cb397SSatish Balay 
2926bf388a1fSBarry Smith .seealso:   SNESSetFunction(), SNESGetFunction(), SNESSetJacobian(), SNESGetJacobian()
2927bf388a1fSBarry Smith M*/
2928bf388a1fSBarry Smith 
29299b94acceSBarry Smith /*@C
29309b94acceSBarry Smith    SNESSetJacobian - Sets the function to compute Jacobian as well as the
2931044dda88SLois Curfman McInnes    location to store the matrix.
29329b94acceSBarry Smith 
29333f9fe445SBarry Smith    Logically Collective on SNES and Mat
2934c7afd0dbSLois Curfman McInnes 
29359b94acceSBarry Smith    Input Parameters:
2936c7afd0dbSLois Curfman McInnes +  snes - the SNES context
2937e5d3d808SBarry Smith .  Amat - the matrix that defines the (approximate) Jacobian
2938e5d3d808SBarry Smith .  Pmat - the matrix to be used in constructing the preconditioner, usually the same as Amat.
2939411c0326SBarry Smith .  J - Jacobian evaluation routine (if NULL then SNES retains any previously set value), see SNESJacobianFunction for details
2940c7afd0dbSLois Curfman McInnes -  ctx - [optional] user-defined context for private data for the
29410298fd71SBarry Smith          Jacobian evaluation routine (may be NULL) (if NULL then SNES retains any previously set value)
29429b94acceSBarry Smith 
29439b94acceSBarry Smith    Notes:
2944e5d3d808SBarry Smith    If the Amat matrix and Pmat matrix are different you must call MatAssemblyBegin/End() on
294516913363SBarry Smith    each matrix.
294616913363SBarry Smith 
2947895c21f2SBarry Smith    If you know the operator Amat has a null space you can use MatSetNullSpace() and MatSetTransposeNullSpace() to supply the null
2948895c21f2SBarry Smith    space to Amat and the KSP solvers will automatically use that null space as needed during the solution process.
2949895c21f2SBarry Smith 
29508d359177SBarry Smith    If using SNESComputeJacobianDefaultColor() to assemble a Jacobian, the ctx argument
2951a8a26c1eSJed Brown    must be a MatFDColoring.
2952a8a26c1eSJed Brown 
2953c3cc8fd1SJed Brown    Other defect-correction schemes can be used by computing a different matrix in place of the Jacobian.  One common
2954c3cc8fd1SJed Brown    example is to use the "Picard linearization" which only differentiates through the highest order parts of each term.
2955c3cc8fd1SJed Brown 
295636851e7fSLois Curfman McInnes    Level: beginner
295736851e7fSLois Curfman McInnes 
29589b94acceSBarry Smith .keywords: SNES, nonlinear, set, Jacobian, matrix
29599b94acceSBarry Smith 
2960411c0326SBarry Smith .seealso: KSPSetOperators(), SNESSetFunction(), MatMFFDComputeJacobian(), SNESComputeJacobianDefaultColor(), MatStructure, J,
2961411c0326SBarry Smith           SNESSetPicard(), SNESJacobianFunction
29629b94acceSBarry Smith @*/
2963d1e9a80fSBarry Smith PetscErrorCode  SNESSetJacobian(SNES snes,Mat Amat,Mat Pmat,PetscErrorCode (*J)(SNES,Vec,Mat,Mat,void*),void *ctx)
29649b94acceSBarry Smith {
2965dfbe8321SBarry Smith   PetscErrorCode ierr;
29666cab3a1bSJed Brown   DM             dm;
29673a7fca6bSBarry Smith 
29683a40ed3dSBarry Smith   PetscFunctionBegin;
29690700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
2970e5d3d808SBarry Smith   if (Amat) PetscValidHeaderSpecific(Amat,MAT_CLASSID,2);
2971e5d3d808SBarry Smith   if (Pmat) PetscValidHeaderSpecific(Pmat,MAT_CLASSID,3);
2972e5d3d808SBarry Smith   if (Amat) PetscCheckSameComm(snes,1,Amat,2);
2973e5d3d808SBarry Smith   if (Pmat) PetscCheckSameComm(snes,1,Pmat,3);
29746cab3a1bSJed Brown   ierr = SNESGetDM(snes,&dm);CHKERRQ(ierr);
2975f8b49ee9SBarry Smith   ierr = DMSNESSetJacobian(dm,J,ctx);CHKERRQ(ierr);
2976e5d3d808SBarry Smith   if (Amat) {
2977e5d3d808SBarry Smith     ierr = PetscObjectReference((PetscObject)Amat);CHKERRQ(ierr);
29786bf464f9SBarry Smith     ierr = MatDestroy(&snes->jacobian);CHKERRQ(ierr);
2979f5af7f23SKarl Rupp 
2980e5d3d808SBarry Smith     snes->jacobian = Amat;
29813a7fca6bSBarry Smith   }
2982e5d3d808SBarry Smith   if (Pmat) {
2983e5d3d808SBarry Smith     ierr = PetscObjectReference((PetscObject)Pmat);CHKERRQ(ierr);
29846bf464f9SBarry Smith     ierr = MatDestroy(&snes->jacobian_pre);CHKERRQ(ierr);
2985f5af7f23SKarl Rupp 
2986e5d3d808SBarry Smith     snes->jacobian_pre = Pmat;
29873a7fca6bSBarry Smith   }
29883a40ed3dSBarry Smith   PetscFunctionReturn(0);
29899b94acceSBarry Smith }
299062fef451SLois Curfman McInnes 
2991c2aafc4cSSatish Balay /*@C
2992b4fd4287SBarry Smith    SNESGetJacobian - Returns the Jacobian matrix and optionally the user
2993b4fd4287SBarry Smith    provided context for evaluating the Jacobian.
2994b4fd4287SBarry Smith 
2995c7afd0dbSLois Curfman McInnes    Not Collective, but Mat object will be parallel if SNES object is
2996c7afd0dbSLois Curfman McInnes 
2997b4fd4287SBarry Smith    Input Parameter:
2998b4fd4287SBarry Smith .  snes - the nonlinear solver context
2999b4fd4287SBarry Smith 
3000b4fd4287SBarry Smith    Output Parameters:
3001e5d3d808SBarry Smith +  Amat - location to stash (approximate) Jacobian matrix (or NULL)
3002e5d3d808SBarry Smith .  Pmat - location to stash matrix used to compute the preconditioner (or NULL)
3003411c0326SBarry Smith .  J - location to put Jacobian function (or NULL), see SNESJacobianFunction for details on its calling sequence
30040298fd71SBarry Smith -  ctx - location to stash Jacobian ctx (or NULL)
3005fee21e36SBarry Smith 
300636851e7fSLois Curfman McInnes    Level: advanced
300736851e7fSLois Curfman McInnes 
3008411c0326SBarry Smith .seealso: SNESSetJacobian(), SNESComputeJacobian(), SNESJacobianFunction, SNESGetFunction()
3009b4fd4287SBarry Smith @*/
3010d1e9a80fSBarry Smith PetscErrorCode SNESGetJacobian(SNES snes,Mat *Amat,Mat *Pmat,PetscErrorCode (**J)(SNES,Vec,Mat,Mat,void*),void **ctx)
3011b4fd4287SBarry Smith {
30126cab3a1bSJed Brown   PetscErrorCode ierr;
30136cab3a1bSJed Brown   DM             dm;
3014942e3340SBarry Smith   DMSNES         sdm;
30156cab3a1bSJed Brown 
30163a40ed3dSBarry Smith   PetscFunctionBegin;
30170700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3018e5d3d808SBarry Smith   if (Amat) *Amat = snes->jacobian;
3019e5d3d808SBarry Smith   if (Pmat) *Pmat = snes->jacobian_pre;
30206cab3a1bSJed Brown   ierr = SNESGetDM(snes,&dm);CHKERRQ(ierr);
3021942e3340SBarry Smith   ierr = DMGetDMSNES(dm,&sdm);CHKERRQ(ierr);
3022f8b49ee9SBarry Smith   if (J) *J = sdm->ops->computejacobian;
30236cab3a1bSJed Brown   if (ctx) *ctx = sdm->jacobianctx;
30243a40ed3dSBarry Smith   PetscFunctionReturn(0);
3025b4fd4287SBarry Smith }
3026b4fd4287SBarry Smith 
30279b94acceSBarry Smith /*@
30289b94acceSBarry Smith    SNESSetUp - Sets up the internal data structures for the later use
3029272ac6f2SLois Curfman McInnes    of a nonlinear solver.
30309b94acceSBarry Smith 
3031fee21e36SBarry Smith    Collective on SNES
3032fee21e36SBarry Smith 
3033c7afd0dbSLois Curfman McInnes    Input Parameters:
303470e92668SMatthew Knepley .  snes - the SNES context
3035c7afd0dbSLois Curfman McInnes 
3036272ac6f2SLois Curfman McInnes    Notes:
3037272ac6f2SLois Curfman McInnes    For basic use of the SNES solvers the user need not explicitly call
3038272ac6f2SLois Curfman McInnes    SNESSetUp(), since these actions will automatically occur during
3039272ac6f2SLois Curfman McInnes    the call to SNESSolve().  However, if one wishes to control this
3040272ac6f2SLois Curfman McInnes    phase separately, SNESSetUp() should be called after SNESCreate()
3041272ac6f2SLois Curfman McInnes    and optional routines of the form SNESSetXXX(), but before SNESSolve().
3042272ac6f2SLois Curfman McInnes 
304336851e7fSLois Curfman McInnes    Level: advanced
304436851e7fSLois Curfman McInnes 
30459b94acceSBarry Smith .keywords: SNES, nonlinear, setup
30469b94acceSBarry Smith 
30479b94acceSBarry Smith .seealso: SNESCreate(), SNESSolve(), SNESDestroy()
30489b94acceSBarry Smith @*/
30497087cfbeSBarry Smith PetscErrorCode  SNESSetUp(SNES snes)
30509b94acceSBarry Smith {
3051dfbe8321SBarry Smith   PetscErrorCode ierr;
30526cab3a1bSJed Brown   DM             dm;
3053942e3340SBarry Smith   DMSNES         sdm;
3054c35f09e5SBarry Smith   SNESLineSearch linesearch, pclinesearch;
30556e2a1849SPeter Brune   void           *lsprectx,*lspostctx;
30566b2b7091SBarry Smith   PetscErrorCode (*precheck)(SNESLineSearch,Vec,Vec,PetscBool*,void*);
30576b2b7091SBarry Smith   PetscErrorCode (*postcheck)(SNESLineSearch,Vec,Vec,Vec,PetscBool*,PetscBool*,void*);
30586e2a1849SPeter Brune   PetscErrorCode (*func)(SNES,Vec,Vec,void*);
30596e2a1849SPeter Brune   Vec            f,fpc;
30606e2a1849SPeter Brune   void           *funcctx;
3061d1e9a80fSBarry Smith   PetscErrorCode (*jac)(SNES,Vec,Mat,Mat,void*);
30621eb13d49SPeter Brune   void           *jacctx,*appctx;
306332b97717SPeter Brune   Mat            j,jpre;
30643a40ed3dSBarry Smith 
30653a40ed3dSBarry Smith   PetscFunctionBegin;
30660700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
30674dc4c822SBarry Smith   if (snes->setupcalled) PetscFunctionReturn(0);
30689b94acceSBarry Smith 
30697adad957SLisandro Dalcin   if (!((PetscObject)snes)->type_name) {
307004d7464bSBarry Smith     ierr = SNESSetType(snes,SNESNEWTONLS);CHKERRQ(ierr);
307185385478SLisandro Dalcin   }
307285385478SLisandro Dalcin 
30730298fd71SBarry Smith   ierr = SNESGetFunction(snes,&snes->vec_func,NULL,NULL);CHKERRQ(ierr);
307458c9b817SLisandro Dalcin 
30756cab3a1bSJed Brown   ierr = SNESGetDM(snes,&dm);CHKERRQ(ierr);
3076942e3340SBarry Smith   ierr = DMGetDMSNES(dm,&sdm);CHKERRQ(ierr);
3077ce94432eSBarry Smith   if (!sdm->ops->computefunction) SETERRQ(PetscObjectComm((PetscObject)dm),PETSC_ERR_ARG_WRONGSTATE,"Function never provided to SNES object");
307822c6f798SBarry Smith   if (!sdm->ops->computejacobian) {
30798d359177SBarry Smith     ierr = DMSNESSetJacobian(dm,SNESComputeJacobianDefaultColor,NULL);CHKERRQ(ierr);
308019f7a02aSBarry Smith   }
30816cab3a1bSJed Brown   if (!snes->vec_func) {
30826cab3a1bSJed Brown     ierr = DMCreateGlobalVector(dm,&snes->vec_func);CHKERRQ(ierr);
3083214df951SJed Brown   }
3084efd51863SBarry Smith 
308522d28d08SBarry Smith   if (!snes->ksp) {
308622d28d08SBarry Smith     ierr = SNESGetKSP(snes, &snes->ksp);CHKERRQ(ierr);
308722d28d08SBarry Smith   }
3088b710008aSBarry Smith 
308922d28d08SBarry Smith   if (!snes->linesearch) {
30907601faf0SJed Brown     ierr = SNESGetLineSearch(snes, &snes->linesearch);CHKERRQ(ierr);
309122d28d08SBarry Smith   }
3092ed07d7d7SPeter Brune   ierr = SNESLineSearchSetFunction(snes->linesearch,SNESComputeFunction);CHKERRQ(ierr);
30939e764e56SPeter Brune 
3094efd4aadfSBarry Smith   if (snes->npc && (snes->npcside== PC_LEFT)) {
3095172a4300SPeter Brune     snes->mf          = PETSC_TRUE;
3096172a4300SPeter Brune     snes->mf_operator = PETSC_FALSE;
3097172a4300SPeter Brune   }
3098d8f46077SPeter Brune 
3099efd4aadfSBarry Smith   if (snes->npc) {
31006e2a1849SPeter Brune     /* copy the DM over */
31016e2a1849SPeter Brune     ierr = SNESGetDM(snes,&dm);CHKERRQ(ierr);
3102efd4aadfSBarry Smith     ierr = SNESSetDM(snes->npc,dm);CHKERRQ(ierr);
31036e2a1849SPeter Brune 
31046e2a1849SPeter Brune     ierr = SNESGetFunction(snes,&f,&func,&funcctx);CHKERRQ(ierr);
31056e2a1849SPeter Brune     ierr = VecDuplicate(f,&fpc);CHKERRQ(ierr);
3106efd4aadfSBarry Smith     ierr = SNESSetFunction(snes->npc,fpc,func,funcctx);CHKERRQ(ierr);
310732b97717SPeter Brune     ierr = SNESGetJacobian(snes,&j,&jpre,&jac,&jacctx);CHKERRQ(ierr);
3108efd4aadfSBarry Smith     ierr = SNESSetJacobian(snes->npc,j,jpre,jac,jacctx);CHKERRQ(ierr);
31091eb13d49SPeter Brune     ierr = SNESGetApplicationContext(snes,&appctx);CHKERRQ(ierr);
3110efd4aadfSBarry Smith     ierr = SNESSetApplicationContext(snes->npc,appctx);CHKERRQ(ierr);
31116e2a1849SPeter Brune     ierr = VecDestroy(&fpc);CHKERRQ(ierr);
31126e2a1849SPeter Brune 
31136e2a1849SPeter Brune     /* copy the function pointers over */
3114efd4aadfSBarry Smith     ierr = PetscObjectCopyFortranFunctionPointers((PetscObject)snes,(PetscObject)snes->npc);CHKERRQ(ierr);
31156e2a1849SPeter Brune 
31166e2a1849SPeter Brune     /* default to 1 iteration */
3117efd4aadfSBarry Smith     ierr = SNESSetTolerances(snes->npc,0.0,0.0,0.0,1,snes->npc->max_funcs);CHKERRQ(ierr);
3118efd4aadfSBarry Smith     if (snes->npcside==PC_RIGHT) {
3119efd4aadfSBarry Smith       ierr = SNESSetNormSchedule(snes->npc,SNES_NORM_FINAL_ONLY);CHKERRQ(ierr);
3120a9936a0cSPeter Brune     } else {
3121efd4aadfSBarry Smith       ierr = SNESSetNormSchedule(snes->npc,SNES_NORM_NONE);CHKERRQ(ierr);
3122a9936a0cSPeter Brune     }
3123efd4aadfSBarry Smith     ierr = SNESSetFromOptions(snes->npc);CHKERRQ(ierr);
31246e2a1849SPeter Brune 
31256e2a1849SPeter Brune     /* copy the line search context over */
31267601faf0SJed Brown     ierr = SNESGetLineSearch(snes,&linesearch);CHKERRQ(ierr);
3127efd4aadfSBarry Smith     ierr = SNESGetLineSearch(snes->npc,&pclinesearch);CHKERRQ(ierr);
31286b2b7091SBarry Smith     ierr = SNESLineSearchGetPreCheck(linesearch,&precheck,&lsprectx);CHKERRQ(ierr);
31296b2b7091SBarry Smith     ierr = SNESLineSearchGetPostCheck(linesearch,&postcheck,&lspostctx);CHKERRQ(ierr);
31306b2b7091SBarry Smith     ierr = SNESLineSearchSetPreCheck(pclinesearch,precheck,lsprectx);CHKERRQ(ierr);
31316b2b7091SBarry Smith     ierr = SNESLineSearchSetPostCheck(pclinesearch,postcheck,lspostctx);CHKERRQ(ierr);
31326e2a1849SPeter Brune     ierr = PetscObjectCopyFortranFunctionPointers((PetscObject)linesearch, (PetscObject)pclinesearch);CHKERRQ(ierr);
31336e2a1849SPeter Brune   }
313432b97717SPeter Brune   if (snes->mf) {
313532b97717SPeter Brune     ierr = SNESSetUpMatrixFree_Private(snes, snes->mf_operator, snes->mf_version);CHKERRQ(ierr);
313632b97717SPeter Brune   }
313732b97717SPeter Brune   if (snes->ops->usercompute && !snes->user) {
313832b97717SPeter Brune     ierr = (*snes->ops->usercompute)(snes,(void**)&snes->user);CHKERRQ(ierr);
313932b97717SPeter Brune   }
31406e2a1849SPeter Brune 
314137ec4e1aSPeter Brune   snes->jac_iter = 0;
314237ec4e1aSPeter Brune   snes->pre_iter = 0;
314337ec4e1aSPeter Brune 
3144410397dcSLisandro Dalcin   if (snes->ops->setup) {
3145410397dcSLisandro Dalcin     ierr = (*snes->ops->setup)(snes);CHKERRQ(ierr);
3146410397dcSLisandro Dalcin   }
314758c9b817SLisandro Dalcin 
3148efd4aadfSBarry Smith   if (snes->npc && (snes->npcside== PC_LEFT)) {
31496c67d002SPeter Brune     if (snes->functype == SNES_FUNCTION_PRECONDITIONED) {
315055d4788fSPeter Brune       ierr = SNESGetLineSearch(snes,&linesearch);CHKERRQ(ierr);
3151be95d8f1SBarry Smith       ierr = SNESLineSearchSetFunction(linesearch,SNESComputeFunctionDefaultNPC);CHKERRQ(ierr);
31526c67d002SPeter Brune     }
31536c67d002SPeter Brune   }
31546c67d002SPeter Brune 
31557aaed0d8SBarry Smith   snes->setupcalled = PETSC_TRUE;
31563a40ed3dSBarry Smith   PetscFunctionReturn(0);
31579b94acceSBarry Smith }
31589b94acceSBarry Smith 
315937596af1SLisandro Dalcin /*@
316037596af1SLisandro Dalcin    SNESReset - Resets a SNES context to the snessetupcalled = 0 state and removes any allocated Vecs and Mats
316137596af1SLisandro Dalcin 
316237596af1SLisandro Dalcin    Collective on SNES
316337596af1SLisandro Dalcin 
316437596af1SLisandro Dalcin    Input Parameter:
316537596af1SLisandro Dalcin .  snes - iterative context obtained from SNESCreate()
316637596af1SLisandro Dalcin 
3167d25893d9SBarry Smith    Level: intermediate
3168d25893d9SBarry Smith 
316995452b02SPatrick Sanan    Notes:
317095452b02SPatrick Sanan     Also calls the application context destroy routine set with SNESSetComputeApplicationContext()
317137596af1SLisandro Dalcin 
317237596af1SLisandro Dalcin .keywords: SNES, destroy
317337596af1SLisandro Dalcin 
317437596af1SLisandro Dalcin .seealso: SNESCreate(), SNESSetUp(), SNESSolve()
317537596af1SLisandro Dalcin @*/
317637596af1SLisandro Dalcin PetscErrorCode  SNESReset(SNES snes)
317737596af1SLisandro Dalcin {
317837596af1SLisandro Dalcin   PetscErrorCode ierr;
317937596af1SLisandro Dalcin 
318037596af1SLisandro Dalcin   PetscFunctionBegin;
318137596af1SLisandro Dalcin   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3182d25893d9SBarry Smith   if (snes->ops->userdestroy && snes->user) {
3183d25893d9SBarry Smith     ierr       = (*snes->ops->userdestroy)((void**)&snes->user);CHKERRQ(ierr);
31840298fd71SBarry Smith     snes->user = NULL;
3185d25893d9SBarry Smith   }
3186efd4aadfSBarry Smith   if (snes->npc) {
3187efd4aadfSBarry Smith     ierr = SNESReset(snes->npc);CHKERRQ(ierr);
31888a23116dSBarry Smith   }
31898a23116dSBarry Smith 
319037596af1SLisandro Dalcin   if (snes->ops->reset) {
319137596af1SLisandro Dalcin     ierr = (*snes->ops->reset)(snes);CHKERRQ(ierr);
319237596af1SLisandro Dalcin   }
31939e764e56SPeter Brune   if (snes->ksp) {
31949e764e56SPeter Brune     ierr = KSPReset(snes->ksp);CHKERRQ(ierr);
31959e764e56SPeter Brune   }
31969e764e56SPeter Brune 
31979e764e56SPeter Brune   if (snes->linesearch) {
3198f1c6b773SPeter Brune     ierr = SNESLineSearchReset(snes->linesearch);CHKERRQ(ierr);
31999e764e56SPeter Brune   }
32009e764e56SPeter Brune 
32016bf464f9SBarry Smith   ierr = VecDestroy(&snes->vec_rhs);CHKERRQ(ierr);
32026bf464f9SBarry Smith   ierr = VecDestroy(&snes->vec_sol);CHKERRQ(ierr);
32036bf464f9SBarry Smith   ierr = VecDestroy(&snes->vec_sol_update);CHKERRQ(ierr);
32046bf464f9SBarry Smith   ierr = VecDestroy(&snes->vec_func);CHKERRQ(ierr);
32056bf464f9SBarry Smith   ierr = MatDestroy(&snes->jacobian);CHKERRQ(ierr);
32066bf464f9SBarry Smith   ierr = MatDestroy(&snes->jacobian_pre);CHKERRQ(ierr);
3207c41d97abSJed Brown   ierr = VecDestroyVecs(snes->nwork,&snes->work);CHKERRQ(ierr);
3208c41d97abSJed Brown   ierr = VecDestroyVecs(snes->nvwork,&snes->vwork);CHKERRQ(ierr);
3209f5af7f23SKarl Rupp 
321040fdac6aSLawrence Mitchell   snes->alwayscomputesfinalresidual = PETSC_FALSE;
321140fdac6aSLawrence Mitchell 
321237596af1SLisandro Dalcin   snes->nwork       = snes->nvwork = 0;
321337596af1SLisandro Dalcin   snes->setupcalled = PETSC_FALSE;
321437596af1SLisandro Dalcin   PetscFunctionReturn(0);
321537596af1SLisandro Dalcin }
321637596af1SLisandro Dalcin 
321752baeb72SSatish Balay /*@
32189b94acceSBarry Smith    SNESDestroy - Destroys the nonlinear solver context that was created
32199b94acceSBarry Smith    with SNESCreate().
32209b94acceSBarry Smith 
3221c7afd0dbSLois Curfman McInnes    Collective on SNES
3222c7afd0dbSLois Curfman McInnes 
32239b94acceSBarry Smith    Input Parameter:
32249b94acceSBarry Smith .  snes - the SNES context
32259b94acceSBarry Smith 
322636851e7fSLois Curfman McInnes    Level: beginner
322736851e7fSLois Curfman McInnes 
32289b94acceSBarry Smith .keywords: SNES, nonlinear, destroy
32299b94acceSBarry Smith 
323063a78c88SLois Curfman McInnes .seealso: SNESCreate(), SNESSolve()
32319b94acceSBarry Smith @*/
32326bf464f9SBarry Smith PetscErrorCode  SNESDestroy(SNES *snes)
32339b94acceSBarry Smith {
32346849ba73SBarry Smith   PetscErrorCode ierr;
32353a40ed3dSBarry Smith 
32363a40ed3dSBarry Smith   PetscFunctionBegin;
32376bf464f9SBarry Smith   if (!*snes) PetscFunctionReturn(0);
32386bf464f9SBarry Smith   PetscValidHeaderSpecific((*snes),SNES_CLASSID,1);
32396bf464f9SBarry Smith   if (--((PetscObject)(*snes))->refct > 0) {*snes = 0; PetscFunctionReturn(0);}
3240d4bb536fSBarry Smith 
32416bf464f9SBarry Smith   ierr = SNESReset((*snes));CHKERRQ(ierr);
3242efd4aadfSBarry Smith   ierr = SNESDestroy(&(*snes)->npc);CHKERRQ(ierr);
32436b8b9a38SLisandro Dalcin 
3244e04113cfSBarry Smith   /* if memory was published with SAWs then destroy it */
3245e04113cfSBarry Smith   ierr = PetscObjectSAWsViewOff((PetscObject)*snes);CHKERRQ(ierr);
32466bf464f9SBarry Smith   if ((*snes)->ops->destroy) {ierr = (*((*snes))->ops->destroy)((*snes));CHKERRQ(ierr);}
32476d4c513bSLisandro Dalcin 
324833124788SMatthew G. Knepley   if ((*snes)->dm) {ierr = DMCoarsenHookRemove((*snes)->dm,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,*snes);CHKERRQ(ierr);}
32496bf464f9SBarry Smith   ierr = DMDestroy(&(*snes)->dm);CHKERRQ(ierr);
32506bf464f9SBarry Smith   ierr = KSPDestroy(&(*snes)->ksp);CHKERRQ(ierr);
3251f1c6b773SPeter Brune   ierr = SNESLineSearchDestroy(&(*snes)->linesearch);CHKERRQ(ierr);
32526b8b9a38SLisandro Dalcin 
32536bf464f9SBarry Smith   ierr = PetscFree((*snes)->kspconvctx);CHKERRQ(ierr);
32546bf464f9SBarry Smith   if ((*snes)->ops->convergeddestroy) {
32556bf464f9SBarry Smith     ierr = (*(*snes)->ops->convergeddestroy)((*snes)->cnvP);CHKERRQ(ierr);
32566b8b9a38SLisandro Dalcin   }
32576bf464f9SBarry Smith   if ((*snes)->conv_malloc) {
32586bf464f9SBarry Smith     ierr = PetscFree((*snes)->conv_hist);CHKERRQ(ierr);
32596bf464f9SBarry Smith     ierr = PetscFree((*snes)->conv_hist_its);CHKERRQ(ierr);
326058c9b817SLisandro Dalcin   }
32616bf464f9SBarry Smith   ierr = SNESMonitorCancel((*snes));CHKERRQ(ierr);
3262a79aaaedSSatish Balay   ierr = PetscHeaderDestroy(snes);CHKERRQ(ierr);
32633a40ed3dSBarry Smith   PetscFunctionReturn(0);
32649b94acceSBarry Smith }
32659b94acceSBarry Smith 
32669b94acceSBarry Smith /* ----------- Routines to set solver parameters ---------- */
32679b94acceSBarry Smith 
3268a8054027SBarry Smith /*@
3269a8054027SBarry Smith    SNESSetLagPreconditioner - Determines when the preconditioner is rebuilt in the nonlinear solve.
3270a8054027SBarry Smith 
32713f9fe445SBarry Smith    Logically Collective on SNES
3272a8054027SBarry Smith 
3273a8054027SBarry Smith    Input Parameters:
3274a8054027SBarry Smith +  snes - the SNES context
3275a8054027SBarry 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
32763b4f5425SBarry Smith          the Jacobian is built etc. -2 indicates rebuild preconditioner at next chance but then never rebuild after that
3277a8054027SBarry Smith 
3278a8054027SBarry Smith    Options Database Keys:
3279a8054027SBarry Smith .    -snes_lag_preconditioner <lag>
3280a8054027SBarry Smith 
3281a8054027SBarry Smith    Notes:
3282a8054027SBarry Smith    The default is 1
3283a8054027SBarry Smith    The preconditioner is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1
3284a8054027SBarry Smith    If  -1 is used before the very first nonlinear solve the preconditioner is still built because there is no previous preconditioner to use
3285a8054027SBarry Smith 
3286a8054027SBarry Smith    Level: intermediate
3287a8054027SBarry Smith 
3288a8054027SBarry Smith .keywords: SNES, nonlinear, set, convergence, tolerances
3289a8054027SBarry Smith 
3290e35cf81dSBarry Smith .seealso: SNESSetTrustRegionTolerance(), SNESGetLagPreconditioner(), SNESSetLagJacobian(), SNESGetLagJacobian()
3291a8054027SBarry Smith 
3292a8054027SBarry Smith @*/
32937087cfbeSBarry Smith PetscErrorCode  SNESSetLagPreconditioner(SNES snes,PetscInt lag)
3294a8054027SBarry Smith {
3295a8054027SBarry Smith   PetscFunctionBegin;
32960700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3297e32f2f54SBarry Smith   if (lag < -2) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag must be -2, -1, 1 or greater");
3298e32f2f54SBarry Smith   if (!lag) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag cannot be 0");
3299c5eb9154SBarry Smith   PetscValidLogicalCollectiveInt(snes,lag,2);
3300a8054027SBarry Smith   snes->lagpreconditioner = lag;
3301a8054027SBarry Smith   PetscFunctionReturn(0);
3302a8054027SBarry Smith }
3303a8054027SBarry Smith 
3304efd51863SBarry Smith /*@
3305efd51863SBarry Smith    SNESSetGridSequence - sets the number of steps of grid sequencing that SNES does
3306efd51863SBarry Smith 
3307efd51863SBarry Smith    Logically Collective on SNES
3308efd51863SBarry Smith 
3309efd51863SBarry Smith    Input Parameters:
3310efd51863SBarry Smith +  snes - the SNES context
3311efd51863SBarry Smith -  steps - the number of refinements to do, defaults to 0
3312efd51863SBarry Smith 
3313efd51863SBarry Smith    Options Database Keys:
3314efd51863SBarry Smith .    -snes_grid_sequence <steps>
3315efd51863SBarry Smith 
3316efd51863SBarry Smith    Level: intermediate
3317efd51863SBarry Smith 
3318c0df2a02SJed Brown    Notes:
3319c0df2a02SJed Brown    Use SNESGetSolution() to extract the fine grid solution after grid sequencing.
3320c0df2a02SJed Brown 
3321efd51863SBarry Smith .keywords: SNES, nonlinear, set, convergence, tolerances
3322efd51863SBarry Smith 
3323fa19ca70SBarry Smith .seealso: SNESSetTrustRegionTolerance(), SNESGetLagPreconditioner(), SNESSetLagJacobian(), SNESGetLagJacobian(), SNESGetGridSequence()
3324efd51863SBarry Smith 
3325efd51863SBarry Smith @*/
3326efd51863SBarry Smith PetscErrorCode  SNESSetGridSequence(SNES snes,PetscInt steps)
3327efd51863SBarry Smith {
3328efd51863SBarry Smith   PetscFunctionBegin;
3329efd51863SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3330efd51863SBarry Smith   PetscValidLogicalCollectiveInt(snes,steps,2);
3331efd51863SBarry Smith   snes->gridsequence = steps;
3332efd51863SBarry Smith   PetscFunctionReturn(0);
3333efd51863SBarry Smith }
3334efd51863SBarry Smith 
3335fa19ca70SBarry Smith /*@
3336fa19ca70SBarry Smith    SNESGetGridSequence - gets the number of steps of grid sequencing that SNES does
3337fa19ca70SBarry Smith 
3338fa19ca70SBarry Smith    Logically Collective on SNES
3339fa19ca70SBarry Smith 
3340fa19ca70SBarry Smith    Input Parameter:
3341fa19ca70SBarry Smith .  snes - the SNES context
3342fa19ca70SBarry Smith 
3343fa19ca70SBarry Smith    Output Parameter:
3344fa19ca70SBarry Smith .  steps - the number of refinements to do, defaults to 0
3345fa19ca70SBarry Smith 
3346fa19ca70SBarry Smith    Options Database Keys:
3347fa19ca70SBarry Smith .    -snes_grid_sequence <steps>
3348fa19ca70SBarry Smith 
3349fa19ca70SBarry Smith    Level: intermediate
3350fa19ca70SBarry Smith 
3351fa19ca70SBarry Smith    Notes:
3352fa19ca70SBarry Smith    Use SNESGetSolution() to extract the fine grid solution after grid sequencing.
3353fa19ca70SBarry Smith 
3354fa19ca70SBarry Smith .keywords: SNES, nonlinear, set, convergence, tolerances
3355fa19ca70SBarry Smith 
3356fa19ca70SBarry Smith .seealso: SNESSetTrustRegionTolerance(), SNESGetLagPreconditioner(), SNESSetLagJacobian(), SNESGetLagJacobian(), SNESSetGridSequence()
3357fa19ca70SBarry Smith 
3358fa19ca70SBarry Smith @*/
3359fa19ca70SBarry Smith PetscErrorCode  SNESGetGridSequence(SNES snes,PetscInt *steps)
3360fa19ca70SBarry Smith {
3361fa19ca70SBarry Smith   PetscFunctionBegin;
3362fa19ca70SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3363fa19ca70SBarry Smith   *steps = snes->gridsequence;
3364fa19ca70SBarry Smith   PetscFunctionReturn(0);
3365fa19ca70SBarry Smith }
3366fa19ca70SBarry Smith 
3367a8054027SBarry Smith /*@
3368a8054027SBarry Smith    SNESGetLagPreconditioner - Indicates how often the preconditioner is rebuilt
3369a8054027SBarry Smith 
33703f9fe445SBarry Smith    Not Collective
3371a8054027SBarry Smith 
3372a8054027SBarry Smith    Input Parameter:
3373a8054027SBarry Smith .  snes - the SNES context
3374a8054027SBarry Smith 
3375a8054027SBarry Smith    Output Parameter:
3376a8054027SBarry 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
33773b4f5425SBarry Smith          the Jacobian is built etc. -2 indicates rebuild preconditioner at next chance but then never rebuild after that
3378a8054027SBarry Smith 
3379a8054027SBarry Smith    Options Database Keys:
3380a8054027SBarry Smith .    -snes_lag_preconditioner <lag>
3381a8054027SBarry Smith 
3382a8054027SBarry Smith    Notes:
3383a8054027SBarry Smith    The default is 1
3384a8054027SBarry Smith    The preconditioner is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1
3385a8054027SBarry Smith 
3386a8054027SBarry Smith    Level: intermediate
3387a8054027SBarry Smith 
3388a8054027SBarry Smith .keywords: SNES, nonlinear, set, convergence, tolerances
3389a8054027SBarry Smith 
3390a8054027SBarry Smith .seealso: SNESSetTrustRegionTolerance(), SNESSetLagPreconditioner()
3391a8054027SBarry Smith 
3392a8054027SBarry Smith @*/
33937087cfbeSBarry Smith PetscErrorCode  SNESGetLagPreconditioner(SNES snes,PetscInt *lag)
3394a8054027SBarry Smith {
3395a8054027SBarry Smith   PetscFunctionBegin;
33960700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3397a8054027SBarry Smith   *lag = snes->lagpreconditioner;
3398a8054027SBarry Smith   PetscFunctionReturn(0);
3399a8054027SBarry Smith }
3400a8054027SBarry Smith 
3401e35cf81dSBarry Smith /*@
3402e35cf81dSBarry Smith    SNESSetLagJacobian - Determines when the Jacobian is rebuilt in the nonlinear solve. See SNESSetLagPreconditioner() for determining how
3403e35cf81dSBarry Smith      often the preconditioner is rebuilt.
3404e35cf81dSBarry Smith 
34053f9fe445SBarry Smith    Logically Collective on SNES
3406e35cf81dSBarry Smith 
3407e35cf81dSBarry Smith    Input Parameters:
3408e35cf81dSBarry Smith +  snes - the SNES context
3409e35cf81dSBarry 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
3410fe3ffe1eSBarry Smith          the Jacobian is built etc. -2 means rebuild at next chance but then never again
3411e35cf81dSBarry Smith 
3412e35cf81dSBarry Smith    Options Database Keys:
3413e35cf81dSBarry Smith .    -snes_lag_jacobian <lag>
3414e35cf81dSBarry Smith 
3415e35cf81dSBarry Smith    Notes:
3416e35cf81dSBarry Smith    The default is 1
3417e35cf81dSBarry Smith    The Jacobian is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1
3418fe3ffe1eSBarry 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
3419fe3ffe1eSBarry Smith    at the next Newton step but never again (unless it is reset to another value)
3420e35cf81dSBarry Smith 
3421e35cf81dSBarry Smith    Level: intermediate
3422e35cf81dSBarry Smith 
3423e35cf81dSBarry Smith .keywords: SNES, nonlinear, set, convergence, tolerances
3424e35cf81dSBarry Smith 
3425e35cf81dSBarry Smith .seealso: SNESSetTrustRegionTolerance(), SNESGetLagPreconditioner(), SNESSetLagPreconditioner(), SNESGetLagJacobian()
3426e35cf81dSBarry Smith 
3427e35cf81dSBarry Smith @*/
34287087cfbeSBarry Smith PetscErrorCode  SNESSetLagJacobian(SNES snes,PetscInt lag)
3429e35cf81dSBarry Smith {
3430e35cf81dSBarry Smith   PetscFunctionBegin;
34310700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3432e32f2f54SBarry Smith   if (lag < -2) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag must be -2, -1, 1 or greater");
3433e32f2f54SBarry Smith   if (!lag) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag cannot be 0");
3434c5eb9154SBarry Smith   PetscValidLogicalCollectiveInt(snes,lag,2);
3435e35cf81dSBarry Smith   snes->lagjacobian = lag;
3436e35cf81dSBarry Smith   PetscFunctionReturn(0);
3437e35cf81dSBarry Smith }
3438e35cf81dSBarry Smith 
3439e35cf81dSBarry Smith /*@
3440e35cf81dSBarry Smith    SNESGetLagJacobian - Indicates how often the Jacobian is rebuilt. See SNESGetLagPreconditioner() to determine when the preconditioner is rebuilt
3441e35cf81dSBarry Smith 
34423f9fe445SBarry Smith    Not Collective
3443e35cf81dSBarry Smith 
3444e35cf81dSBarry Smith    Input Parameter:
3445e35cf81dSBarry Smith .  snes - the SNES context
3446e35cf81dSBarry Smith 
3447e35cf81dSBarry Smith    Output Parameter:
3448e35cf81dSBarry 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
3449e35cf81dSBarry Smith          the Jacobian is built etc.
3450e35cf81dSBarry Smith 
3451e35cf81dSBarry Smith    Options Database Keys:
3452e35cf81dSBarry Smith .    -snes_lag_jacobian <lag>
3453e35cf81dSBarry Smith 
3454e35cf81dSBarry Smith    Notes:
3455e35cf81dSBarry Smith    The default is 1
3456e35cf81dSBarry Smith    The jacobian is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1
3457e35cf81dSBarry Smith 
3458e35cf81dSBarry Smith    Level: intermediate
3459e35cf81dSBarry Smith 
3460e35cf81dSBarry Smith .keywords: SNES, nonlinear, set, convergence, tolerances
3461e35cf81dSBarry Smith 
3462e35cf81dSBarry Smith .seealso: SNESSetTrustRegionTolerance(), SNESSetLagJacobian(), SNESSetLagPreconditioner(), SNESGetLagPreconditioner()
3463e35cf81dSBarry Smith 
3464e35cf81dSBarry Smith @*/
34657087cfbeSBarry Smith PetscErrorCode  SNESGetLagJacobian(SNES snes,PetscInt *lag)
3466e35cf81dSBarry Smith {
3467e35cf81dSBarry Smith   PetscFunctionBegin;
34680700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3469e35cf81dSBarry Smith   *lag = snes->lagjacobian;
3470e35cf81dSBarry Smith   PetscFunctionReturn(0);
3471e35cf81dSBarry Smith }
3472e35cf81dSBarry Smith 
347337ec4e1aSPeter Brune /*@
347437ec4e1aSPeter Brune    SNESSetLagJacobianPersists - Set whether or not the Jacobian lagging persists through multiple solves
347537ec4e1aSPeter Brune 
347637ec4e1aSPeter Brune    Logically collective on SNES
347737ec4e1aSPeter Brune 
347837ec4e1aSPeter Brune    Input Parameter:
347937ec4e1aSPeter Brune +  snes - the SNES context
34809d7e2deaSPeter Brune -   flg - jacobian lagging persists if true
348137ec4e1aSPeter Brune 
348237ec4e1aSPeter Brune    Options Database Keys:
348337ec4e1aSPeter Brune .    -snes_lag_jacobian_persists <flg>
348437ec4e1aSPeter Brune 
348595452b02SPatrick Sanan    Notes:
348695452b02SPatrick Sanan     This is useful both for nonlinear preconditioning, where it's appropriate to have the Jacobian be stale by
348737ec4e1aSPeter Brune    several solves, and for implicit time-stepping, where Jacobian lagging in the inner nonlinear solve over several
348837ec4e1aSPeter Brune    timesteps may present huge efficiency gains.
348937ec4e1aSPeter Brune 
349037ec4e1aSPeter Brune    Level: developer
349137ec4e1aSPeter Brune 
3492be95d8f1SBarry Smith .keywords: SNES, nonlinear, lag
349337ec4e1aSPeter Brune 
3494be95d8f1SBarry Smith .seealso: SNESSetLagPreconditionerPersists(), SNESSetLagJacobian(), SNESGetLagJacobian(), SNESGetNPC()
349537ec4e1aSPeter Brune 
349637ec4e1aSPeter Brune @*/
349737ec4e1aSPeter Brune PetscErrorCode  SNESSetLagJacobianPersists(SNES snes,PetscBool flg)
349837ec4e1aSPeter Brune {
349937ec4e1aSPeter Brune   PetscFunctionBegin;
350037ec4e1aSPeter Brune   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
350137ec4e1aSPeter Brune   PetscValidLogicalCollectiveBool(snes,flg,2);
350237ec4e1aSPeter Brune   snes->lagjac_persist = flg;
350337ec4e1aSPeter Brune   PetscFunctionReturn(0);
350437ec4e1aSPeter Brune }
350537ec4e1aSPeter Brune 
350637ec4e1aSPeter Brune /*@
350737ec4e1aSPeter Brune    SNESSetLagPreconditionerPersists - Set whether or not the preconditioner lagging persists through multiple solves
350837ec4e1aSPeter Brune 
350937ec4e1aSPeter Brune    Logically Collective on SNES
351037ec4e1aSPeter Brune 
351137ec4e1aSPeter Brune    Input Parameter:
351237ec4e1aSPeter Brune +  snes - the SNES context
35139d7e2deaSPeter Brune -   flg - preconditioner lagging persists if true
351437ec4e1aSPeter Brune 
351537ec4e1aSPeter Brune    Options Database Keys:
351637ec4e1aSPeter Brune .    -snes_lag_jacobian_persists <flg>
351737ec4e1aSPeter Brune 
351895452b02SPatrick Sanan    Notes:
351995452b02SPatrick Sanan     This is useful both for nonlinear preconditioning, where it's appropriate to have the preconditioner be stale
352037ec4e1aSPeter Brune    by several solves, and for implicit time-stepping, where preconditioner lagging in the inner nonlinear solve over
352137ec4e1aSPeter Brune    several timesteps may present huge efficiency gains.
352237ec4e1aSPeter Brune 
352337ec4e1aSPeter Brune    Level: developer
352437ec4e1aSPeter Brune 
3525be95d8f1SBarry Smith .keywords: SNES, nonlinear, lag
352637ec4e1aSPeter Brune 
3527be95d8f1SBarry Smith .seealso: SNESSetLagJacobianPersists(), SNESSetLagJacobian(), SNESGetLagJacobian(), SNESGetNPC()
352837ec4e1aSPeter Brune 
352937ec4e1aSPeter Brune @*/
353037ec4e1aSPeter Brune PetscErrorCode  SNESSetLagPreconditionerPersists(SNES snes,PetscBool flg)
353137ec4e1aSPeter Brune {
353237ec4e1aSPeter Brune   PetscFunctionBegin;
353337ec4e1aSPeter Brune   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
353437ec4e1aSPeter Brune   PetscValidLogicalCollectiveBool(snes,flg,2);
353537ec4e1aSPeter Brune   snes->lagpre_persist = flg;
353637ec4e1aSPeter Brune   PetscFunctionReturn(0);
353737ec4e1aSPeter Brune }
353837ec4e1aSPeter Brune 
35399b94acceSBarry Smith /*@
3540be5caee7SBarry Smith    SNESSetForceIteration - force SNESSolve() to take at least one iteration regardless of the initial residual norm
3541be5caee7SBarry Smith 
3542be5caee7SBarry Smith    Logically Collective on SNES
3543be5caee7SBarry Smith 
3544be5caee7SBarry Smith    Input Parameters:
3545be5caee7SBarry Smith +  snes - the SNES context
3546be5caee7SBarry Smith -  force - PETSC_TRUE require at least one iteration
3547be5caee7SBarry Smith 
3548be5caee7SBarry Smith    Options Database Keys:
3549be5caee7SBarry Smith .    -snes_force_iteration <force> - Sets forcing an iteration
3550be5caee7SBarry Smith 
3551be5caee7SBarry Smith    Notes:
3552be5caee7SBarry Smith    This is used sometimes with TS to prevent TS from detecting a false steady state solution
3553be5caee7SBarry Smith 
3554be5caee7SBarry Smith    Level: intermediate
3555be5caee7SBarry Smith 
3556be5caee7SBarry Smith .keywords: SNES, nonlinear, set, convergence, tolerances
3557be5caee7SBarry Smith 
3558be5caee7SBarry Smith .seealso: SNESSetTrustRegionTolerance(), SNESSetDivergenceTolerance()
3559be5caee7SBarry Smith @*/
3560be5caee7SBarry Smith PetscErrorCode  SNESSetForceIteration(SNES snes,PetscBool force)
3561be5caee7SBarry Smith {
3562be5caee7SBarry Smith   PetscFunctionBegin;
3563be5caee7SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3564be5caee7SBarry Smith   snes->forceiteration = force;
3565be5caee7SBarry Smith   PetscFunctionReturn(0);
3566be5caee7SBarry Smith }
3567be5caee7SBarry Smith 
356885216dc7SFande Kong /*@
356985216dc7SFande Kong    SNESGetForceIteration - Whether or not to force SNESSolve() take at least one iteration regardless of the initial residual norm
357085216dc7SFande Kong 
357185216dc7SFande Kong    Logically Collective on SNES
357285216dc7SFande Kong 
357385216dc7SFande Kong    Input Parameters:
357485216dc7SFande Kong .  snes - the SNES context
357585216dc7SFande Kong 
357685216dc7SFande Kong    Output Parameter:
357785216dc7SFande Kong .  force - PETSC_TRUE requires at least one iteration.
357885216dc7SFande Kong 
357985216dc7SFande Kong .keywords: SNES, nonlinear, set, convergence, tolerances
358085216dc7SFande Kong 
358106dd6b0eSSatish Balay    Level: intermediate
358206dd6b0eSSatish Balay 
358385216dc7SFande Kong .seealso: SNESSetForceIteration(), SNESSetTrustRegionTolerance(), SNESSetDivergenceTolerance()
358485216dc7SFande Kong @*/
358585216dc7SFande Kong PetscErrorCode  SNESGetForceIteration(SNES snes,PetscBool *force)
358685216dc7SFande Kong {
358785216dc7SFande Kong   PetscFunctionBegin;
358885216dc7SFande Kong   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
358985216dc7SFande Kong   *force = snes->forceiteration;
359085216dc7SFande Kong   PetscFunctionReturn(0);
359185216dc7SFande Kong }
3592be5caee7SBarry Smith 
3593be5caee7SBarry Smith /*@
3594d7a720efSLois Curfman McInnes    SNESSetTolerances - Sets various parameters used in convergence tests.
35959b94acceSBarry Smith 
35963f9fe445SBarry Smith    Logically Collective on SNES
3597c7afd0dbSLois Curfman McInnes 
35989b94acceSBarry Smith    Input Parameters:
3599c7afd0dbSLois Curfman McInnes +  snes - the SNES context
360070441072SBarry Smith .  abstol - absolute convergence tolerance
360133174efeSLois Curfman McInnes .  rtol - relative convergence tolerance
36025358d0d4SBarry Smith .  stol -  convergence tolerance in terms of the norm of the change in the solution between steps,  || delta x || < stol*|| x ||
360333174efeSLois Curfman McInnes .  maxit - maximum number of iterations
3604e71169deSBarry Smith -  maxf - maximum number of function evaluations (-1 indicates no limit)
3605fee21e36SBarry Smith 
360633174efeSLois Curfman McInnes    Options Database Keys:
360770441072SBarry Smith +    -snes_atol <abstol> - Sets abstol
3608c7afd0dbSLois Curfman McInnes .    -snes_rtol <rtol> - Sets rtol
3609c7afd0dbSLois Curfman McInnes .    -snes_stol <stol> - Sets stol
3610c7afd0dbSLois Curfman McInnes .    -snes_max_it <maxit> - Sets maxit
3611c7afd0dbSLois Curfman McInnes -    -snes_max_funcs <maxf> - Sets maxf
36129b94acceSBarry Smith 
3613d7a720efSLois Curfman McInnes    Notes:
36149b94acceSBarry Smith    The default maximum number of iterations is 50.
36159b94acceSBarry Smith    The default maximum number of function evaluations is 1000.
36169b94acceSBarry Smith 
361736851e7fSLois Curfman McInnes    Level: intermediate
361836851e7fSLois Curfman McInnes 
361933174efeSLois Curfman McInnes .keywords: SNES, nonlinear, set, convergence, tolerances
36209b94acceSBarry Smith 
3621be5caee7SBarry Smith .seealso: SNESSetTrustRegionTolerance(), SNESSetDivergenceTolerance(), SNESSetForceIteration()
36229b94acceSBarry Smith @*/
36237087cfbeSBarry Smith PetscErrorCode  SNESSetTolerances(SNES snes,PetscReal abstol,PetscReal rtol,PetscReal stol,PetscInt maxit,PetscInt maxf)
36249b94acceSBarry Smith {
36253a40ed3dSBarry Smith   PetscFunctionBegin;
36260700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3627c5eb9154SBarry Smith   PetscValidLogicalCollectiveReal(snes,abstol,2);
3628c5eb9154SBarry Smith   PetscValidLogicalCollectiveReal(snes,rtol,3);
3629c5eb9154SBarry Smith   PetscValidLogicalCollectiveReal(snes,stol,4);
3630c5eb9154SBarry Smith   PetscValidLogicalCollectiveInt(snes,maxit,5);
3631c5eb9154SBarry Smith   PetscValidLogicalCollectiveInt(snes,maxf,6);
3632c5eb9154SBarry Smith 
3633ab54825eSJed Brown   if (abstol != PETSC_DEFAULT) {
363457622a8eSBarry Smith     if (abstol < 0.0) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Absolute tolerance %g must be non-negative",(double)abstol);
3635ab54825eSJed Brown     snes->abstol = abstol;
3636ab54825eSJed Brown   }
3637ab54825eSJed Brown   if (rtol != PETSC_DEFAULT) {
363857622a8eSBarry Smith     if (rtol < 0.0 || 1.0 <= rtol) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Relative tolerance %g must be non-negative and less than 1.0",(double)rtol);
3639ab54825eSJed Brown     snes->rtol = rtol;
3640ab54825eSJed Brown   }
3641ab54825eSJed Brown   if (stol != PETSC_DEFAULT) {
364257622a8eSBarry Smith     if (stol < 0.0) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Step tolerance %g must be non-negative",(double)stol);
3643c60f73f4SPeter Brune     snes->stol = stol;
3644ab54825eSJed Brown   }
3645ab54825eSJed Brown   if (maxit != PETSC_DEFAULT) {
3646ce94432eSBarry Smith     if (maxit < 0) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of iterations %D must be non-negative",maxit);
3647ab54825eSJed Brown     snes->max_its = maxit;
3648ab54825eSJed Brown   }
3649ab54825eSJed Brown   if (maxf != PETSC_DEFAULT) {
3650e71169deSBarry Smith     if (maxf < -1) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of function evaluations %D must be -1 or nonnegative",maxf);
3651ab54825eSJed Brown     snes->max_funcs = maxf;
3652ab54825eSJed Brown   }
365388976e71SPeter Brune   snes->tolerancesset = PETSC_TRUE;
36543a40ed3dSBarry Smith   PetscFunctionReturn(0);
36559b94acceSBarry Smith }
36569b94acceSBarry Smith 
3657e4d06f11SPatrick Farrell /*@
3658e4d06f11SPatrick Farrell    SNESSetDivergenceTolerance - Sets the divergence tolerance used for the SNES divergence test.
3659e4d06f11SPatrick Farrell 
3660e4d06f11SPatrick Farrell    Logically Collective on SNES
3661e4d06f11SPatrick Farrell 
3662e4d06f11SPatrick Farrell    Input Parameters:
3663e4d06f11SPatrick Farrell +  snes - the SNES context
3664e4d06f11SPatrick Farrell -  divtol - the divergence tolerance. Use -1 to deactivate the test.
3665e4d06f11SPatrick Farrell 
3666e4d06f11SPatrick Farrell    Options Database Keys:
3667e4d06f11SPatrick Farrell +    -snes_divergence_tolerance <divtol> - Sets divtol
3668e4d06f11SPatrick Farrell 
3669e4d06f11SPatrick Farrell    Notes:
3670e4d06f11SPatrick Farrell    The default divergence tolerance is 1e4.
3671e4d06f11SPatrick Farrell 
3672e4d06f11SPatrick Farrell    Level: intermediate
3673e4d06f11SPatrick Farrell 
3674e4d06f11SPatrick Farrell .keywords: SNES, nonlinear, set, divergence, tolerance
3675e4d06f11SPatrick Farrell 
3676e4d06f11SPatrick Farrell .seealso: SNESSetTolerances(), SNESGetDivergenceTolerance
3677e4d06f11SPatrick Farrell @*/
3678e4d06f11SPatrick Farrell PetscErrorCode  SNESSetDivergenceTolerance(SNES snes,PetscReal divtol)
3679e4d06f11SPatrick Farrell {
3680e4d06f11SPatrick Farrell   PetscFunctionBegin;
3681e4d06f11SPatrick Farrell   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3682e4d06f11SPatrick Farrell   PetscValidLogicalCollectiveReal(snes,divtol,2);
3683e4d06f11SPatrick Farrell 
3684e4d06f11SPatrick Farrell   if (divtol != PETSC_DEFAULT) {
3685e4d06f11SPatrick Farrell     snes->divtol = divtol;
3686e4d06f11SPatrick Farrell   }
3687e4d06f11SPatrick Farrell   else {
3688e4d06f11SPatrick Farrell     snes->divtol = 1.0e4;
3689e4d06f11SPatrick Farrell   }
3690e4d06f11SPatrick Farrell   PetscFunctionReturn(0);
3691e4d06f11SPatrick Farrell }
3692e4d06f11SPatrick Farrell 
36939b94acceSBarry Smith /*@
369433174efeSLois Curfman McInnes    SNESGetTolerances - Gets various parameters used in convergence tests.
369533174efeSLois Curfman McInnes 
3696c7afd0dbSLois Curfman McInnes    Not Collective
3697c7afd0dbSLois Curfman McInnes 
369833174efeSLois Curfman McInnes    Input Parameters:
3699c7afd0dbSLois Curfman McInnes +  snes - the SNES context
370085385478SLisandro Dalcin .  atol - absolute convergence tolerance
370133174efeSLois Curfman McInnes .  rtol - relative convergence tolerance
370233174efeSLois Curfman McInnes .  stol -  convergence tolerance in terms of the norm
370333174efeSLois Curfman McInnes            of the change in the solution between steps
370433174efeSLois Curfman McInnes .  maxit - maximum number of iterations
3705c7afd0dbSLois Curfman McInnes -  maxf - maximum number of function evaluations
3706fee21e36SBarry Smith 
370733174efeSLois Curfman McInnes    Notes:
37080298fd71SBarry Smith    The user can specify NULL for any parameter that is not needed.
370933174efeSLois Curfman McInnes 
371036851e7fSLois Curfman McInnes    Level: intermediate
371136851e7fSLois Curfman McInnes 
371233174efeSLois Curfman McInnes .keywords: SNES, nonlinear, get, convergence, tolerances
371333174efeSLois Curfman McInnes 
371433174efeSLois Curfman McInnes .seealso: SNESSetTolerances()
371533174efeSLois Curfman McInnes @*/
37167087cfbeSBarry Smith PetscErrorCode  SNESGetTolerances(SNES snes,PetscReal *atol,PetscReal *rtol,PetscReal *stol,PetscInt *maxit,PetscInt *maxf)
371733174efeSLois Curfman McInnes {
37183a40ed3dSBarry Smith   PetscFunctionBegin;
37190700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
372085385478SLisandro Dalcin   if (atol)  *atol  = snes->abstol;
372133174efeSLois Curfman McInnes   if (rtol)  *rtol  = snes->rtol;
3722c60f73f4SPeter Brune   if (stol)  *stol  = snes->stol;
372333174efeSLois Curfman McInnes   if (maxit) *maxit = snes->max_its;
372433174efeSLois Curfman McInnes   if (maxf)  *maxf  = snes->max_funcs;
37253a40ed3dSBarry Smith   PetscFunctionReturn(0);
372633174efeSLois Curfman McInnes }
372733174efeSLois Curfman McInnes 
3728e4d06f11SPatrick Farrell /*@
3729e4d06f11SPatrick Farrell    SNESGetDivergenceTolerance - Gets divergence tolerance used in divergence test.
3730e4d06f11SPatrick Farrell 
3731e4d06f11SPatrick Farrell    Not Collective
3732e4d06f11SPatrick Farrell 
3733e4d06f11SPatrick Farrell    Input Parameters:
3734e4d06f11SPatrick Farrell +  snes - the SNES context
3735e4d06f11SPatrick Farrell -  divtol - divergence tolerance
3736e4d06f11SPatrick Farrell 
3737e4d06f11SPatrick Farrell    Level: intermediate
3738e4d06f11SPatrick Farrell 
3739e4d06f11SPatrick Farrell .keywords: SNES, nonlinear, get, divergence, tolerance
3740e4d06f11SPatrick Farrell 
3741e4d06f11SPatrick Farrell .seealso: SNESSetDivergenceTolerance()
3742e4d06f11SPatrick Farrell @*/
3743e4d06f11SPatrick Farrell PetscErrorCode  SNESGetDivergenceTolerance(SNES snes,PetscReal *divtol)
3744e4d06f11SPatrick Farrell {
3745e4d06f11SPatrick Farrell   PetscFunctionBegin;
3746e4d06f11SPatrick Farrell   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3747e4d06f11SPatrick Farrell   if (divtol) *divtol = snes->divtol;
3748e4d06f11SPatrick Farrell   PetscFunctionReturn(0);
3749e4d06f11SPatrick Farrell }
3750e4d06f11SPatrick Farrell 
375133174efeSLois Curfman McInnes /*@
37529b94acceSBarry Smith    SNESSetTrustRegionTolerance - Sets the trust region parameter tolerance.
37539b94acceSBarry Smith 
37543f9fe445SBarry Smith    Logically Collective on SNES
3755fee21e36SBarry Smith 
3756c7afd0dbSLois Curfman McInnes    Input Parameters:
3757c7afd0dbSLois Curfman McInnes +  snes - the SNES context
3758c7afd0dbSLois Curfman McInnes -  tol - tolerance
3759c7afd0dbSLois Curfman McInnes 
37609b94acceSBarry Smith    Options Database Key:
3761c7afd0dbSLois Curfman McInnes .  -snes_trtol <tol> - Sets tol
37629b94acceSBarry Smith 
376336851e7fSLois Curfman McInnes    Level: intermediate
376436851e7fSLois Curfman McInnes 
37659b94acceSBarry Smith .keywords: SNES, nonlinear, set, trust region, tolerance
37669b94acceSBarry Smith 
37672492ecdbSBarry Smith .seealso: SNESSetTolerances()
37689b94acceSBarry Smith @*/
37697087cfbeSBarry Smith PetscErrorCode  SNESSetTrustRegionTolerance(SNES snes,PetscReal tol)
37709b94acceSBarry Smith {
37713a40ed3dSBarry Smith   PetscFunctionBegin;
37720700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3773c5eb9154SBarry Smith   PetscValidLogicalCollectiveReal(snes,tol,2);
37749b94acceSBarry Smith   snes->deltatol = tol;
37753a40ed3dSBarry Smith   PetscFunctionReturn(0);
37769b94acceSBarry Smith }
37779b94acceSBarry Smith 
3778df9fa365SBarry Smith /*
3779df9fa365SBarry Smith    Duplicate the lg monitors for SNES from KSP; for some reason with
3780df9fa365SBarry Smith    dynamic libraries things don't work under Sun4 if we just use
3781df9fa365SBarry Smith    macros instead of functions
3782df9fa365SBarry Smith */
3783d96771aaSLisandro Dalcin PetscErrorCode  SNESMonitorLGResidualNorm(SNES snes,PetscInt it,PetscReal norm,void *ctx)
3784ce1608b8SBarry Smith {
3785dfbe8321SBarry Smith   PetscErrorCode ierr;
3786ce1608b8SBarry Smith 
3787ce1608b8SBarry Smith   PetscFunctionBegin;
37880700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3789d96771aaSLisandro Dalcin   ierr = KSPMonitorLGResidualNorm((KSP)snes,it,norm,ctx);CHKERRQ(ierr);
3790ce1608b8SBarry Smith   PetscFunctionReturn(0);
3791ce1608b8SBarry Smith }
3792ce1608b8SBarry Smith 
3793d96771aaSLisandro Dalcin PetscErrorCode  SNESMonitorLGCreate(MPI_Comm comm,const char host[],const char label[],int x,int y,int m,int n,PetscDrawLG *lgctx)
3794df9fa365SBarry Smith {
3795dfbe8321SBarry Smith   PetscErrorCode ierr;
3796df9fa365SBarry Smith 
3797df9fa365SBarry Smith   PetscFunctionBegin;
3798d96771aaSLisandro Dalcin   ierr = KSPMonitorLGResidualNormCreate(comm,host,label,x,y,m,n,lgctx);CHKERRQ(ierr);
3799df9fa365SBarry Smith   PetscFunctionReturn(0);
3800df9fa365SBarry Smith }
3801df9fa365SBarry Smith 
38026ba87a44SLisandro Dalcin PETSC_INTERN PetscErrorCode  SNESMonitorRange_Private(SNES,PetscInt,PetscReal*);
38036ba87a44SLisandro Dalcin 
38047087cfbeSBarry Smith PetscErrorCode  SNESMonitorLGRange(SNES snes,PetscInt n,PetscReal rnorm,void *monctx)
3805b271bb04SBarry Smith {
3806b271bb04SBarry Smith   PetscDrawLG      lg;
3807b271bb04SBarry Smith   PetscErrorCode   ierr;
3808b271bb04SBarry Smith   PetscReal        x,y,per;
3809b271bb04SBarry Smith   PetscViewer      v = (PetscViewer)monctx;
3810b271bb04SBarry Smith   static PetscReal prev; /* should be in the context */
3811b271bb04SBarry Smith   PetscDraw        draw;
3812b271bb04SBarry Smith 
3813459f5d12SBarry Smith   PetscFunctionBegin;
38144d4332d5SBarry Smith   PetscValidHeaderSpecific(v,PETSC_VIEWER_CLASSID,4);
3815b271bb04SBarry Smith   ierr = PetscViewerDrawGetDrawLG(v,0,&lg);CHKERRQ(ierr);
3816b271bb04SBarry Smith   if (!n) {ierr = PetscDrawLGReset(lg);CHKERRQ(ierr);}
3817b271bb04SBarry Smith   ierr = PetscDrawLGGetDraw(lg,&draw);CHKERRQ(ierr);
3818b271bb04SBarry Smith   ierr = PetscDrawSetTitle(draw,"Residual norm");CHKERRQ(ierr);
3819b271bb04SBarry Smith   x    = (PetscReal)n;
382077b4d14cSPeter Brune   if (rnorm > 0.0) y = PetscLog10Real(rnorm);
382194c9c6d3SKarl Rupp   else y = -15.0;
3822b271bb04SBarry Smith   ierr = PetscDrawLGAddPoint(lg,&x,&y);CHKERRQ(ierr);
38236934998bSLisandro Dalcin   if (n < 20 || !(n % 5) || snes->reason) {
3824b271bb04SBarry Smith     ierr = PetscDrawLGDraw(lg);CHKERRQ(ierr);
38256934998bSLisandro Dalcin     ierr = PetscDrawLGSave(lg);CHKERRQ(ierr);
3826b271bb04SBarry Smith   }
3827b271bb04SBarry Smith 
3828b271bb04SBarry Smith   ierr = PetscViewerDrawGetDrawLG(v,1,&lg);CHKERRQ(ierr);
3829b271bb04SBarry Smith   if (!n) {ierr = PetscDrawLGReset(lg);CHKERRQ(ierr);}
3830b271bb04SBarry Smith   ierr = PetscDrawLGGetDraw(lg,&draw);CHKERRQ(ierr);
3831b271bb04SBarry Smith   ierr = PetscDrawSetTitle(draw,"% elemts > .2*max elemt");CHKERRQ(ierr);
3832b271bb04SBarry Smith   ierr =  SNESMonitorRange_Private(snes,n,&per);CHKERRQ(ierr);
3833b271bb04SBarry Smith   x    = (PetscReal)n;
3834b271bb04SBarry Smith   y    = 100.0*per;
3835b271bb04SBarry Smith   ierr = PetscDrawLGAddPoint(lg,&x,&y);CHKERRQ(ierr);
38366934998bSLisandro Dalcin   if (n < 20 || !(n % 5) || snes->reason) {
3837b271bb04SBarry Smith     ierr = PetscDrawLGDraw(lg);CHKERRQ(ierr);
38386934998bSLisandro Dalcin     ierr = PetscDrawLGSave(lg);CHKERRQ(ierr);
3839b271bb04SBarry Smith   }
3840b271bb04SBarry Smith 
3841b271bb04SBarry Smith   ierr = PetscViewerDrawGetDrawLG(v,2,&lg);CHKERRQ(ierr);
3842b271bb04SBarry Smith   if (!n) {prev = rnorm;ierr = PetscDrawLGReset(lg);CHKERRQ(ierr);}
3843b271bb04SBarry Smith   ierr = PetscDrawLGGetDraw(lg,&draw);CHKERRQ(ierr);
3844b271bb04SBarry Smith   ierr = PetscDrawSetTitle(draw,"(norm -oldnorm)/oldnorm");CHKERRQ(ierr);
3845b271bb04SBarry Smith   x    = (PetscReal)n;
3846b271bb04SBarry Smith   y    = (prev - rnorm)/prev;
3847b271bb04SBarry Smith   ierr = PetscDrawLGAddPoint(lg,&x,&y);CHKERRQ(ierr);
38486934998bSLisandro Dalcin   if (n < 20 || !(n % 5) || snes->reason) {
3849b271bb04SBarry Smith     ierr = PetscDrawLGDraw(lg);CHKERRQ(ierr);
38506934998bSLisandro Dalcin     ierr = PetscDrawLGSave(lg);CHKERRQ(ierr);
3851b271bb04SBarry Smith   }
3852b271bb04SBarry Smith 
3853b271bb04SBarry Smith   ierr = PetscViewerDrawGetDrawLG(v,3,&lg);CHKERRQ(ierr);
3854b271bb04SBarry Smith   if (!n) {ierr = PetscDrawLGReset(lg);CHKERRQ(ierr);}
3855b271bb04SBarry Smith   ierr = PetscDrawLGGetDraw(lg,&draw);CHKERRQ(ierr);
3856b271bb04SBarry Smith   ierr = PetscDrawSetTitle(draw,"(norm -oldnorm)/oldnorm*(% > .2 max)");CHKERRQ(ierr);
3857b271bb04SBarry Smith   x    = (PetscReal)n;
3858b271bb04SBarry Smith   y    = (prev - rnorm)/(prev*per);
3859b271bb04SBarry Smith   if (n > 2) { /*skip initial crazy value */
3860b271bb04SBarry Smith     ierr = PetscDrawLGAddPoint(lg,&x,&y);CHKERRQ(ierr);
3861b271bb04SBarry Smith   }
38626934998bSLisandro Dalcin   if (n < 20 || !(n % 5) || snes->reason) {
3863b271bb04SBarry Smith     ierr = PetscDrawLGDraw(lg);CHKERRQ(ierr);
38646934998bSLisandro Dalcin     ierr = PetscDrawLGSave(lg);CHKERRQ(ierr);
3865b271bb04SBarry Smith   }
3866b271bb04SBarry Smith   prev = rnorm;
3867b271bb04SBarry Smith   PetscFunctionReturn(0);
3868b271bb04SBarry Smith }
3869b271bb04SBarry Smith 
3870228d79bcSJed Brown /*@
3871228d79bcSJed Brown    SNESMonitor - runs the user provided monitor routines, if they exist
3872228d79bcSJed Brown 
3873228d79bcSJed Brown    Collective on SNES
3874228d79bcSJed Brown 
3875228d79bcSJed Brown    Input Parameters:
3876228d79bcSJed Brown +  snes - nonlinear solver context obtained from SNESCreate()
3877228d79bcSJed Brown .  iter - iteration number
3878228d79bcSJed Brown -  rnorm - relative norm of the residual
3879228d79bcSJed Brown 
3880228d79bcSJed Brown    Notes:
3881228d79bcSJed Brown    This routine is called by the SNES implementations.
3882228d79bcSJed Brown    It does not typically need to be called by the user.
3883228d79bcSJed Brown 
3884228d79bcSJed Brown    Level: developer
3885228d79bcSJed Brown 
3886228d79bcSJed Brown .seealso: SNESMonitorSet()
3887228d79bcSJed Brown @*/
38887a03ce2fSLisandro Dalcin PetscErrorCode  SNESMonitor(SNES snes,PetscInt iter,PetscReal rnorm)
38897a03ce2fSLisandro Dalcin {
38907a03ce2fSLisandro Dalcin   PetscErrorCode ierr;
38917a03ce2fSLisandro Dalcin   PetscInt       i,n = snes->numbermonitors;
38927a03ce2fSLisandro Dalcin 
38937a03ce2fSLisandro Dalcin   PetscFunctionBegin;
38948860a134SJunchao Zhang   ierr = VecLockReadPush(snes->vec_sol);CHKERRQ(ierr);
38957a03ce2fSLisandro Dalcin   for (i=0; i<n; i++) {
38967a03ce2fSLisandro Dalcin     ierr = (*snes->monitor[i])(snes,iter,rnorm,snes->monitorcontext[i]);CHKERRQ(ierr);
38977a03ce2fSLisandro Dalcin   }
38988860a134SJunchao Zhang   ierr = VecLockReadPop(snes->vec_sol);CHKERRQ(ierr);
38997a03ce2fSLisandro Dalcin   PetscFunctionReturn(0);
39007a03ce2fSLisandro Dalcin }
39017a03ce2fSLisandro Dalcin 
39029b94acceSBarry Smith /* ------------ Routines to set performance monitoring options ----------- */
39039b94acceSBarry Smith 
3904bf388a1fSBarry Smith /*MC
3905bf388a1fSBarry Smith     SNESMonitorFunction - functional form passed to SNESMonitorSet() to monitor convergence of nonlinear solver
3906bf388a1fSBarry Smith 
3907bf388a1fSBarry Smith      Synopsis:
3908aaa7dc30SBarry Smith      #include <petscsnes.h>
3909bf388a1fSBarry Smith $    PetscErrorCode SNESMonitorFunction(SNES snes,PetscInt its, PetscReal norm,void *mctx)
3910bf388a1fSBarry Smith 
3911bf388a1fSBarry Smith +    snes - the SNES context
3912bf388a1fSBarry Smith .    its - iteration number
3913bf388a1fSBarry Smith .    norm - 2-norm function value (may be estimated)
3914bf388a1fSBarry Smith -    mctx - [optional] monitoring context
3915bf388a1fSBarry Smith 
3916878cb397SSatish Balay    Level: advanced
3917878cb397SSatish Balay 
3918bf388a1fSBarry Smith .seealso:   SNESMonitorSet(), SNESMonitorGet()
3919bf388a1fSBarry Smith M*/
3920bf388a1fSBarry Smith 
39219b94acceSBarry Smith /*@C
3922a6570f20SBarry Smith    SNESMonitorSet - Sets an ADDITIONAL function that is to be used at every
39239b94acceSBarry Smith    iteration of the nonlinear solver to display the iteration's
39249b94acceSBarry Smith    progress.
39259b94acceSBarry Smith 
39263f9fe445SBarry Smith    Logically Collective on SNES
3927fee21e36SBarry Smith 
3928c7afd0dbSLois Curfman McInnes    Input Parameters:
3929c7afd0dbSLois Curfman McInnes +  snes - the SNES context
39306e4dcb14SBarry Smith .  f - the monitor function, see SNESMonitorFunction for the calling sequence
3931b8a78c4aSBarry Smith .  mctx - [optional] user-defined context for private data for the
39320298fd71SBarry Smith           monitor routine (use NULL if no context is desired)
3933b3006f0bSLois Curfman McInnes -  monitordestroy - [optional] routine that frees monitor context
39340298fd71SBarry Smith           (may be NULL)
39359b94acceSBarry Smith 
39369665c990SLois Curfman McInnes    Options Database Keys:
3937a6570f20SBarry Smith +    -snes_monitor        - sets SNESMonitorDefault()
39384619e776SBarry Smith .    -snes_monitor_lg_residualnorm    - sets line graph monitor,
3939a6570f20SBarry Smith                             uses SNESMonitorLGCreate()
3940cca6129bSJed Brown -    -snes_monitor_cancel - cancels all monitors that have
3941c7afd0dbSLois Curfman McInnes                             been hardwired into a code by
3942a6570f20SBarry Smith                             calls to SNESMonitorSet(), but
3943c7afd0dbSLois Curfman McInnes                             does not cancel those set via
3944c7afd0dbSLois Curfman McInnes                             the options database.
39459665c990SLois Curfman McInnes 
3946639f9d9dSBarry Smith    Notes:
39476bc08f3fSLois Curfman McInnes    Several different monitoring routines may be set by calling
3948a6570f20SBarry Smith    SNESMonitorSet() multiple times; all will be called in the
39496bc08f3fSLois Curfman McInnes    order in which they were set.
3950639f9d9dSBarry Smith 
395195452b02SPatrick Sanan    Fortran Notes:
395295452b02SPatrick Sanan     Only a single monitor function can be set for each SNES object
3953025f1a04SBarry Smith 
395436851e7fSLois Curfman McInnes    Level: intermediate
395536851e7fSLois Curfman McInnes 
39569b94acceSBarry Smith .keywords: SNES, nonlinear, set, monitor
39579b94acceSBarry Smith 
3958bf388a1fSBarry Smith .seealso: SNESMonitorDefault(), SNESMonitorCancel(), SNESMonitorFunction
39599b94acceSBarry Smith @*/
39606e4dcb14SBarry Smith PetscErrorCode  SNESMonitorSet(SNES snes,PetscErrorCode (*f)(SNES,PetscInt,PetscReal,void*),void *mctx,PetscErrorCode (*monitordestroy)(void**))
39619b94acceSBarry Smith {
3962b90d0a6eSBarry Smith   PetscInt       i;
3963649052a6SBarry Smith   PetscErrorCode ierr;
396478064530SBarry Smith   PetscBool      identical;
3965b90d0a6eSBarry Smith 
39663a40ed3dSBarry Smith   PetscFunctionBegin;
39670700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3968b90d0a6eSBarry Smith   for (i=0; i<snes->numbermonitors;i++) {
396978064530SBarry Smith     ierr = PetscMonitorCompare((PetscErrorCode (*)(void))f,mctx,monitordestroy,(PetscErrorCode (*)(void))snes->monitor[i],snes->monitorcontext[i],snes->monitordestroy[i],&identical);CHKERRQ(ierr);
397078064530SBarry Smith     if (identical) PetscFunctionReturn(0);
3971649052a6SBarry Smith   }
397278064530SBarry Smith   if (snes->numbermonitors >= MAXSNESMONITORS) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Too many monitors set");
39736e4dcb14SBarry Smith   snes->monitor[snes->numbermonitors]          = f;
3974b8a78c4aSBarry Smith   snes->monitordestroy[snes->numbermonitors]   = monitordestroy;
3975639f9d9dSBarry Smith   snes->monitorcontext[snes->numbermonitors++] = (void*)mctx;
39763a40ed3dSBarry Smith   PetscFunctionReturn(0);
39779b94acceSBarry Smith }
39789b94acceSBarry Smith 
3979a278d85bSSatish Balay /*@
3980a6570f20SBarry Smith    SNESMonitorCancel - Clears all the monitor functions for a SNES object.
39815cd90555SBarry Smith 
39823f9fe445SBarry Smith    Logically Collective on SNES
3983c7afd0dbSLois Curfman McInnes 
39845cd90555SBarry Smith    Input Parameters:
39855cd90555SBarry Smith .  snes - the SNES context
39865cd90555SBarry Smith 
39871a480d89SAdministrator    Options Database Key:
3988a6570f20SBarry Smith .  -snes_monitor_cancel - cancels all monitors that have been hardwired
3989a6570f20SBarry Smith     into a code by calls to SNESMonitorSet(), but does not cancel those
3990c7afd0dbSLois Curfman McInnes     set via the options database
39915cd90555SBarry Smith 
39925cd90555SBarry Smith    Notes:
39935cd90555SBarry Smith    There is no way to clear one specific monitor from a SNES object.
39945cd90555SBarry Smith 
399536851e7fSLois Curfman McInnes    Level: intermediate
399636851e7fSLois Curfman McInnes 
39975cd90555SBarry Smith .keywords: SNES, nonlinear, set, monitor
39985cd90555SBarry Smith 
3999a6570f20SBarry Smith .seealso: SNESMonitorDefault(), SNESMonitorSet()
40005cd90555SBarry Smith @*/
40017087cfbeSBarry Smith PetscErrorCode  SNESMonitorCancel(SNES snes)
40025cd90555SBarry Smith {
4003d952e501SBarry Smith   PetscErrorCode ierr;
4004d952e501SBarry Smith   PetscInt       i;
4005d952e501SBarry Smith 
40065cd90555SBarry Smith   PetscFunctionBegin;
40070700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
4008d952e501SBarry Smith   for (i=0; i<snes->numbermonitors; i++) {
4009d952e501SBarry Smith     if (snes->monitordestroy[i]) {
40103c4aec1bSBarry Smith       ierr = (*snes->monitordestroy[i])(&snes->monitorcontext[i]);CHKERRQ(ierr);
4011d952e501SBarry Smith     }
4012d952e501SBarry Smith   }
40135cd90555SBarry Smith   snes->numbermonitors = 0;
40145cd90555SBarry Smith   PetscFunctionReturn(0);
40155cd90555SBarry Smith }
40165cd90555SBarry Smith 
4017bf388a1fSBarry Smith /*MC
4018bf388a1fSBarry Smith     SNESConvergenceTestFunction - functional form used for testing of convergence of nonlinear solver
4019bf388a1fSBarry Smith 
4020bf388a1fSBarry Smith      Synopsis:
4021aaa7dc30SBarry Smith      #include <petscsnes.h>
4022bf388a1fSBarry Smith $     PetscErrorCode SNESConvergenceTest(SNES snes,PetscInt it,PetscReal xnorm,PetscReal gnorm,PetscReal f,SNESConvergedReason *reason,void *cctx)
4023bf388a1fSBarry Smith 
4024bf388a1fSBarry Smith +    snes - the SNES context
4025bf388a1fSBarry Smith .    it - current iteration (0 is the first and is before any Newton step)
4026bf388a1fSBarry Smith .    cctx - [optional] convergence context
4027bf388a1fSBarry Smith .    reason - reason for convergence/divergence
4028bf388a1fSBarry Smith .    xnorm - 2-norm of current iterate
4029bf388a1fSBarry Smith .    gnorm - 2-norm of current step
4030bf388a1fSBarry Smith -    f - 2-norm of function
4031bf388a1fSBarry Smith 
4032878cb397SSatish Balay    Level: intermediate
4033bf388a1fSBarry Smith 
4034bf388a1fSBarry Smith .seealso:   SNESSetConvergenceTest(), SNESGetConvergenceTest()
4035bf388a1fSBarry Smith M*/
4036bf388a1fSBarry Smith 
40379b94acceSBarry Smith /*@C
40389b94acceSBarry Smith    SNESSetConvergenceTest - Sets the function that is to be used
40399b94acceSBarry Smith    to test for convergence of the nonlinear iterative solution.
40409b94acceSBarry Smith 
40413f9fe445SBarry Smith    Logically Collective on SNES
4042fee21e36SBarry Smith 
4043c7afd0dbSLois Curfman McInnes    Input Parameters:
4044c7afd0dbSLois Curfman McInnes +  snes - the SNES context
4045bf388a1fSBarry Smith .  SNESConvergenceTestFunction - routine to test for convergence
40460298fd71SBarry Smith .  cctx - [optional] context for private data for the convergence routine  (may be NULL)
4047cf90aa19SBarry Smith -  destroy - [optional] destructor for the context (may be NULL; PETSC_NULL_FUNCTION in Fortran)
40489b94acceSBarry Smith 
404936851e7fSLois Curfman McInnes    Level: advanced
405036851e7fSLois Curfman McInnes 
40519b94acceSBarry Smith .keywords: SNES, nonlinear, set, convergence, test
40529b94acceSBarry Smith 
4053e2a6519dSDmitry Karpeev .seealso: SNESConvergedDefault(), SNESConvergedSkip(), SNESConvergenceTestFunction
40549b94acceSBarry Smith @*/
4055bf388a1fSBarry Smith PetscErrorCode  SNESSetConvergenceTest(SNES snes,PetscErrorCode (*SNESConvergenceTestFunction)(SNES,PetscInt,PetscReal,PetscReal,PetscReal,SNESConvergedReason*,void*),void *cctx,PetscErrorCode (*destroy)(void*))
40569b94acceSBarry Smith {
40577f7931b9SBarry Smith   PetscErrorCode ierr;
40587f7931b9SBarry Smith 
40593a40ed3dSBarry Smith   PetscFunctionBegin;
40600700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
4061e2a6519dSDmitry Karpeev   if (!SNESConvergenceTestFunction) SNESConvergenceTestFunction = SNESConvergedSkip;
40627f7931b9SBarry Smith   if (snes->ops->convergeddestroy) {
40637f7931b9SBarry Smith     ierr = (*snes->ops->convergeddestroy)(snes->cnvP);CHKERRQ(ierr);
40647f7931b9SBarry Smith   }
4065bf388a1fSBarry Smith   snes->ops->converged        = SNESConvergenceTestFunction;
40667f7931b9SBarry Smith   snes->ops->convergeddestroy = destroy;
406785385478SLisandro Dalcin   snes->cnvP                  = cctx;
40683a40ed3dSBarry Smith   PetscFunctionReturn(0);
40699b94acceSBarry Smith }
40709b94acceSBarry Smith 
407152baeb72SSatish Balay /*@
4072184914b5SBarry Smith    SNESGetConvergedReason - Gets the reason the SNES iteration was stopped.
4073184914b5SBarry Smith 
4074184914b5SBarry Smith    Not Collective
4075184914b5SBarry Smith 
4076184914b5SBarry Smith    Input Parameter:
4077184914b5SBarry Smith .  snes - the SNES context
4078184914b5SBarry Smith 
4079184914b5SBarry Smith    Output Parameter:
40804d0a8057SBarry Smith .  reason - negative value indicates diverged, positive value converged, see SNESConvergedReason or the
4081184914b5SBarry Smith             manual pages for the individual convergence tests for complete lists
4082184914b5SBarry Smith 
40836a4d7782SBarry Smith    Options Database:
40846a4d7782SBarry Smith .   -snes_converged_reason - prints the reason to standard out
40856a4d7782SBarry Smith 
4086184914b5SBarry Smith    Level: intermediate
4087184914b5SBarry Smith 
408895452b02SPatrick Sanan    Notes:
408995452b02SPatrick Sanan     Should only be called after the call the SNESSolve() is complete, if it is called earlier it returns the value SNES__CONVERGED_ITERATING.
4090184914b5SBarry Smith 
4091184914b5SBarry Smith .keywords: SNES, nonlinear, set, convergence, test
4092184914b5SBarry Smith 
409333866048SMatthew G. Knepley .seealso: SNESSetConvergenceTest(), SNESSetConvergedReason(), SNESConvergedReason
4094184914b5SBarry Smith @*/
40957087cfbeSBarry Smith PetscErrorCode SNESGetConvergedReason(SNES snes,SNESConvergedReason *reason)
4096184914b5SBarry Smith {
4097184914b5SBarry Smith   PetscFunctionBegin;
40980700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
40994482741eSBarry Smith   PetscValidPointer(reason,2);
4100184914b5SBarry Smith   *reason = snes->reason;
4101184914b5SBarry Smith   PetscFunctionReturn(0);
4102184914b5SBarry Smith }
4103184914b5SBarry Smith 
410433866048SMatthew G. Knepley /*@
410533866048SMatthew G. Knepley    SNESSetConvergedReason - Sets the reason the SNES iteration was stopped.
410633866048SMatthew G. Knepley 
410733866048SMatthew G. Knepley    Not Collective
410833866048SMatthew G. Knepley 
410933866048SMatthew G. Knepley    Input Parameters:
411033866048SMatthew G. Knepley +  snes - the SNES context
411133866048SMatthew G. Knepley -  reason - negative value indicates diverged, positive value converged, see SNESConvergedReason or the
411233866048SMatthew G. Knepley             manual pages for the individual convergence tests for complete lists
411333866048SMatthew G. Knepley 
411433866048SMatthew G. Knepley    Level: intermediate
411533866048SMatthew G. Knepley 
411633866048SMatthew G. Knepley .keywords: SNES, nonlinear, set, convergence, test
411733866048SMatthew G. Knepley .seealso: SNESGetConvergedReason(), SNESSetConvergenceTest(), SNESConvergedReason
411833866048SMatthew G. Knepley @*/
411933866048SMatthew G. Knepley PetscErrorCode SNESSetConvergedReason(SNES snes,SNESConvergedReason reason)
412033866048SMatthew G. Knepley {
412133866048SMatthew G. Knepley   PetscFunctionBegin;
412233866048SMatthew G. Knepley   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
412333866048SMatthew G. Knepley   snes->reason = reason;
412433866048SMatthew G. Knepley   PetscFunctionReturn(0);
412533866048SMatthew G. Knepley }
412633866048SMatthew G. Knepley 
4127c9005455SLois Curfman McInnes /*@
4128c9005455SLois Curfman McInnes    SNESSetConvergenceHistory - Sets the array used to hold the convergence history.
4129c9005455SLois Curfman McInnes 
41303f9fe445SBarry Smith    Logically Collective on SNES
4131fee21e36SBarry Smith 
4132c7afd0dbSLois Curfman McInnes    Input Parameters:
4133c7afd0dbSLois Curfman McInnes +  snes - iterative context obtained from SNESCreate()
41348c7482ecSBarry Smith .  a   - array to hold history, this array will contain the function norms computed at each step
4135cd5578b5SBarry Smith .  its - integer array holds the number of linear iterations for each solve.
4136758f92a0SBarry Smith .  na  - size of a and its
413764731454SLois Curfman McInnes -  reset - PETSC_TRUE indicates each new nonlinear solve resets the history counter to zero,
4138758f92a0SBarry Smith            else it continues storing new values for new nonlinear solves after the old ones
4139c7afd0dbSLois Curfman McInnes 
4140308dcc3eSBarry Smith    Notes:
41410298fd71SBarry Smith    If 'a' and 'its' are NULL then space is allocated for the history. If 'na' PETSC_DECIDE or PETSC_DEFAULT then a
4142308dcc3eSBarry Smith    default array of length 10000 is allocated.
4143308dcc3eSBarry Smith 
4144c9005455SLois Curfman McInnes    This routine is useful, e.g., when running a code for purposes
4145c9005455SLois Curfman McInnes    of accurate performance monitoring, when no I/O should be done
4146c9005455SLois Curfman McInnes    during the section of code that is being timed.
4147c9005455SLois Curfman McInnes 
414836851e7fSLois Curfman McInnes    Level: intermediate
414936851e7fSLois Curfman McInnes 
4150c9005455SLois Curfman McInnes .keywords: SNES, set, convergence, history
4151758f92a0SBarry Smith 
415208405cd6SLois Curfman McInnes .seealso: SNESGetConvergenceHistory()
4153758f92a0SBarry Smith 
4154c9005455SLois Curfman McInnes @*/
41557087cfbeSBarry Smith PetscErrorCode  SNESSetConvergenceHistory(SNES snes,PetscReal a[],PetscInt its[],PetscInt na,PetscBool reset)
4156c9005455SLois Curfman McInnes {
4157308dcc3eSBarry Smith   PetscErrorCode ierr;
4158308dcc3eSBarry Smith 
41593a40ed3dSBarry Smith   PetscFunctionBegin;
41600700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
41617a1ec6d4SBarry Smith   if (a) PetscValidScalarPointer(a,2);
4162a562a398SLisandro Dalcin   if (its) PetscValidIntPointer(its,3);
41637a1ec6d4SBarry Smith   if (!a) {
4164308dcc3eSBarry Smith     if (na == PETSC_DECIDE || na == PETSC_DEFAULT) na = 1000;
41657fdeb8b9SBarry Smith     ierr = PetscCalloc1(na,&a);CHKERRQ(ierr);
41667fdeb8b9SBarry Smith     ierr = PetscCalloc1(na,&its);CHKERRQ(ierr);
4167f5af7f23SKarl Rupp 
4168308dcc3eSBarry Smith     snes->conv_malloc = PETSC_TRUE;
4169308dcc3eSBarry Smith   }
4170c9005455SLois Curfman McInnes   snes->conv_hist       = a;
4171758f92a0SBarry Smith   snes->conv_hist_its   = its;
4172758f92a0SBarry Smith   snes->conv_hist_max   = na;
4173a12bc48fSLisandro Dalcin   snes->conv_hist_len   = 0;
4174758f92a0SBarry Smith   snes->conv_hist_reset = reset;
4175758f92a0SBarry Smith   PetscFunctionReturn(0);
4176758f92a0SBarry Smith }
4177758f92a0SBarry Smith 
4178308dcc3eSBarry Smith #if defined(PETSC_HAVE_MATLAB_ENGINE)
4179c6db04a5SJed Brown #include <engine.h>   /* MATLAB include file */
4180c6db04a5SJed Brown #include <mex.h>      /* MATLAB include file */
418199e0435eSBarry Smith 
41828cc058d9SJed Brown PETSC_EXTERN mxArray *SNESGetConvergenceHistoryMatlab(SNES snes)
4183308dcc3eSBarry Smith {
4184308dcc3eSBarry Smith   mxArray   *mat;
4185308dcc3eSBarry Smith   PetscInt  i;
4186308dcc3eSBarry Smith   PetscReal *ar;
4187308dcc3eSBarry Smith 
4188308dcc3eSBarry Smith   PetscFunctionBegin;
4189308dcc3eSBarry Smith   mat = mxCreateDoubleMatrix(snes->conv_hist_len,1,mxREAL);
4190308dcc3eSBarry Smith   ar  = (PetscReal*) mxGetData(mat);
4191f5af7f23SKarl Rupp   for (i=0; i<snes->conv_hist_len; i++) ar[i] = snes->conv_hist[i];
4192308dcc3eSBarry Smith   PetscFunctionReturn(mat);
4193308dcc3eSBarry Smith }
4194308dcc3eSBarry Smith #endif
4195308dcc3eSBarry Smith 
41960c4c9dddSBarry Smith /*@C
4197758f92a0SBarry Smith    SNESGetConvergenceHistory - Gets the array used to hold the convergence history.
4198758f92a0SBarry Smith 
41993f9fe445SBarry Smith    Not Collective
4200758f92a0SBarry Smith 
4201758f92a0SBarry Smith    Input Parameter:
4202758f92a0SBarry Smith .  snes - iterative context obtained from SNESCreate()
4203758f92a0SBarry Smith 
4204758f92a0SBarry Smith    Output Parameters:
4205758f92a0SBarry Smith .  a   - array to hold history
4206758f92a0SBarry Smith .  its - integer array holds the number of linear iterations (or
4207758f92a0SBarry Smith          negative if not converged) for each solve.
4208758f92a0SBarry Smith -  na  - size of a and its
4209758f92a0SBarry Smith 
4210758f92a0SBarry Smith    Notes:
4211758f92a0SBarry Smith     The calling sequence for this routine in Fortran is
4212758f92a0SBarry Smith $   call SNESGetConvergenceHistory(SNES snes, integer na, integer ierr)
4213758f92a0SBarry Smith 
4214758f92a0SBarry Smith    This routine is useful, e.g., when running a code for purposes
4215758f92a0SBarry Smith    of accurate performance monitoring, when no I/O should be done
4216758f92a0SBarry Smith    during the section of code that is being timed.
4217758f92a0SBarry Smith 
4218758f92a0SBarry Smith    Level: intermediate
4219758f92a0SBarry Smith 
4220758f92a0SBarry Smith .keywords: SNES, get, convergence, history
4221758f92a0SBarry Smith 
4222758f92a0SBarry Smith .seealso: SNESSetConvergencHistory()
4223758f92a0SBarry Smith 
4224758f92a0SBarry Smith @*/
42257087cfbeSBarry Smith PetscErrorCode  SNESGetConvergenceHistory(SNES snes,PetscReal *a[],PetscInt *its[],PetscInt *na)
4226758f92a0SBarry Smith {
4227758f92a0SBarry Smith   PetscFunctionBegin;
42280700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
4229758f92a0SBarry Smith   if (a)   *a   = snes->conv_hist;
4230758f92a0SBarry Smith   if (its) *its = snes->conv_hist_its;
4231758f92a0SBarry Smith   if (na)  *na  = snes->conv_hist_len;
42323a40ed3dSBarry Smith   PetscFunctionReturn(0);
4233c9005455SLois Curfman McInnes }
4234c9005455SLois Curfman McInnes 
4235ac226902SBarry Smith /*@C
423676b2cf59SMatthew Knepley   SNESSetUpdate - Sets the general-purpose update function called
4237eec8f646SJed Brown   at the beginning of every iteration of the nonlinear solve. Specifically
42387e4bb74cSBarry Smith   it is called just before the Jacobian is "evaluated".
423976b2cf59SMatthew Knepley 
42403f9fe445SBarry Smith   Logically Collective on SNES
424176b2cf59SMatthew Knepley 
424276b2cf59SMatthew Knepley   Input Parameters:
424376b2cf59SMatthew Knepley . snes - The nonlinear solver context
424476b2cf59SMatthew Knepley . func - The function
424576b2cf59SMatthew Knepley 
424676b2cf59SMatthew Knepley   Calling sequence of func:
4247b5d30489SBarry Smith . func (SNES snes, PetscInt step);
424876b2cf59SMatthew Knepley 
424976b2cf59SMatthew Knepley . step - The current step of the iteration
425076b2cf59SMatthew Knepley 
4251fe97e370SBarry Smith   Level: advanced
4252fe97e370SBarry Smith 
4253fe97e370SBarry Smith   Note: This is NOT what one uses to update the ghost points before a function evaluation, that should be done at the beginning of your FormFunction()
4254fe97e370SBarry Smith         This is not used by most users.
425576b2cf59SMatthew Knepley 
425676b2cf59SMatthew Knepley .keywords: SNES, update
4257b5d30489SBarry Smith 
42588d359177SBarry Smith .seealso SNESSetJacobian(), SNESSolve()
425976b2cf59SMatthew Knepley @*/
42607087cfbeSBarry Smith PetscErrorCode  SNESSetUpdate(SNES snes, PetscErrorCode (*func)(SNES, PetscInt))
426176b2cf59SMatthew Knepley {
426276b2cf59SMatthew Knepley   PetscFunctionBegin;
42630700a824SBarry Smith   PetscValidHeaderSpecific(snes, SNES_CLASSID,1);
4264e7788613SBarry Smith   snes->ops->update = func;
426576b2cf59SMatthew Knepley   PetscFunctionReturn(0);
426676b2cf59SMatthew Knepley }
426776b2cf59SMatthew Knepley 
42689b94acceSBarry Smith /*
42699b94acceSBarry Smith    SNESScaleStep_Private - Scales a step so that its length is less than the
42709b94acceSBarry Smith    positive parameter delta.
42719b94acceSBarry Smith 
42729b94acceSBarry Smith     Input Parameters:
4273c7afd0dbSLois Curfman McInnes +   snes - the SNES context
42749b94acceSBarry Smith .   y - approximate solution of linear system
42759b94acceSBarry Smith .   fnorm - 2-norm of current function
4276c7afd0dbSLois Curfman McInnes -   delta - trust region size
42779b94acceSBarry Smith 
42789b94acceSBarry Smith     Output Parameters:
4279c7afd0dbSLois Curfman McInnes +   gpnorm - predicted function norm at the new point, assuming local
42809b94acceSBarry Smith     linearization.  The value is zero if the step lies within the trust
42819b94acceSBarry Smith     region, and exceeds zero otherwise.
4282c7afd0dbSLois Curfman McInnes -   ynorm - 2-norm of the step
42839b94acceSBarry Smith 
42849b94acceSBarry Smith     Note:
428504d7464bSBarry Smith     For non-trust region methods such as SNESNEWTONLS, the parameter delta
42869b94acceSBarry Smith     is set to be the maximum allowable step size.
42879b94acceSBarry Smith 
42889b94acceSBarry Smith .keywords: SNES, nonlinear, scale, step
42899b94acceSBarry Smith */
4290dfbe8321SBarry Smith PetscErrorCode SNESScaleStep_Private(SNES snes,Vec y,PetscReal *fnorm,PetscReal *delta,PetscReal *gpnorm,PetscReal *ynorm)
42919b94acceSBarry Smith {
4292064f8208SBarry Smith   PetscReal      nrm;
4293ea709b57SSatish Balay   PetscScalar    cnorm;
4294dfbe8321SBarry Smith   PetscErrorCode ierr;
42953a40ed3dSBarry Smith 
42963a40ed3dSBarry Smith   PetscFunctionBegin;
42970700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
42980700a824SBarry Smith   PetscValidHeaderSpecific(y,VEC_CLASSID,2);
4299c9780b6fSBarry Smith   PetscCheckSameComm(snes,1,y,2);
4300184914b5SBarry Smith 
4301064f8208SBarry Smith   ierr = VecNorm(y,NORM_2,&nrm);CHKERRQ(ierr);
4302064f8208SBarry Smith   if (nrm > *delta) {
4303064f8208SBarry Smith     nrm     = *delta/nrm;
4304064f8208SBarry Smith     *gpnorm = (1.0 - nrm)*(*fnorm);
4305064f8208SBarry Smith     cnorm   = nrm;
43062dcb1b2aSMatthew Knepley     ierr    = VecScale(y,cnorm);CHKERRQ(ierr);
43079b94acceSBarry Smith     *ynorm  = *delta;
43089b94acceSBarry Smith   } else {
43099b94acceSBarry Smith     *gpnorm = 0.0;
4310064f8208SBarry Smith     *ynorm  = nrm;
43119b94acceSBarry Smith   }
43123a40ed3dSBarry Smith   PetscFunctionReturn(0);
43139b94acceSBarry Smith }
43149b94acceSBarry Smith 
43152a359c20SBarry Smith /*@
43162a359c20SBarry Smith    SNESReasonView - Displays the reason a SNES solve converged or diverged to a viewer
43172a359c20SBarry Smith 
43182a359c20SBarry Smith    Collective on SNES
43192a359c20SBarry Smith 
43202a359c20SBarry Smith    Parameter:
43212a359c20SBarry Smith +  snes - iterative context obtained from SNESCreate()
43222a359c20SBarry Smith -  viewer - the viewer to display the reason
43232a359c20SBarry Smith 
43242a359c20SBarry Smith 
43252a359c20SBarry Smith    Options Database Keys:
43262a359c20SBarry Smith .  -snes_converged_reason - print reason for converged or diverged, also prints number of iterations
43272a359c20SBarry Smith 
43282a359c20SBarry Smith    Level: beginner
43292a359c20SBarry Smith 
43302a359c20SBarry Smith .keywords: SNES, solve, linear system
43312a359c20SBarry Smith 
43322a359c20SBarry Smith .seealso: SNESCreate(), SNESSetUp(), SNESDestroy(), SNESSetTolerances(), SNESConvergedDefault()
43332a359c20SBarry Smith 
43342a359c20SBarry Smith @*/
43352a359c20SBarry Smith PetscErrorCode  SNESReasonView(SNES snes,PetscViewer viewer)
43362a359c20SBarry Smith {
433775cca76cSMatthew G. Knepley   PetscViewerFormat format;
43382a359c20SBarry Smith   PetscBool         isAscii;
433975cca76cSMatthew G. Knepley   PetscErrorCode    ierr;
43402a359c20SBarry Smith 
43412a359c20SBarry Smith   PetscFunctionBegin;
43422a359c20SBarry Smith   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&isAscii);CHKERRQ(ierr);
43432a359c20SBarry Smith   if (isAscii) {
434475cca76cSMatthew G. Knepley     ierr = PetscViewerGetFormat(viewer, &format);CHKERRQ(ierr);
43452a359c20SBarry Smith     ierr = PetscViewerASCIIAddTab(viewer,((PetscObject)snes)->tablevel);CHKERRQ(ierr);
434675cca76cSMatthew G. Knepley     if (format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
434775cca76cSMatthew G. Knepley       DM                dm;
434875cca76cSMatthew G. Knepley       Vec               u;
434975cca76cSMatthew G. Knepley       PetscDS           prob;
435075cca76cSMatthew G. Knepley       PetscInt          Nf, f;
435195cbbfd3SMatthew G. Knepley       PetscErrorCode (**exactSol)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar[], void *);
435295cbbfd3SMatthew G. Knepley       void            **exactCtx;
435375cca76cSMatthew G. Knepley       PetscReal         error;
435475cca76cSMatthew G. Knepley 
435575cca76cSMatthew G. Knepley       ierr = SNESGetDM(snes, &dm);CHKERRQ(ierr);
435675cca76cSMatthew G. Knepley       ierr = SNESGetSolution(snes, &u);CHKERRQ(ierr);
435775cca76cSMatthew G. Knepley       ierr = DMGetDS(dm, &prob);CHKERRQ(ierr);
435875cca76cSMatthew G. Knepley       ierr = PetscDSGetNumFields(prob, &Nf);CHKERRQ(ierr);
435995cbbfd3SMatthew G. Knepley       ierr = PetscMalloc2(Nf, &exactSol, Nf, &exactCtx);CHKERRQ(ierr);
436095cbbfd3SMatthew G. Knepley       for (f = 0; f < Nf; ++f) {ierr = PetscDSGetExactSolution(prob, f, &exactSol[f], &exactCtx[f]);CHKERRQ(ierr);}
436195cbbfd3SMatthew G. Knepley       ierr = DMComputeL2Diff(dm, 0.0, exactSol, exactCtx, u, &error);CHKERRQ(ierr);
436295cbbfd3SMatthew G. Knepley       ierr = PetscFree2(exactSol, exactCtx);CHKERRQ(ierr);
436375cca76cSMatthew G. Knepley       if (error < 1.0e-11) {ierr = PetscViewerASCIIPrintf(viewer, "L_2 Error: < 1.0e-11\n");CHKERRQ(ierr);}
436475cca76cSMatthew G. Knepley       else                 {ierr = PetscViewerASCIIPrintf(viewer, "L_2 Error: %g\n", error);CHKERRQ(ierr);}
436575cca76cSMatthew G. Knepley     }
43662a359c20SBarry Smith     if (snes->reason > 0) {
43672a359c20SBarry Smith       if (((PetscObject) snes)->prefix) {
43682a359c20SBarry Smith         ierr = PetscViewerASCIIPrintf(viewer,"Nonlinear %s solve converged due to %s iterations %D\n",((PetscObject) snes)->prefix,SNESConvergedReasons[snes->reason],snes->iter);CHKERRQ(ierr);
43692a359c20SBarry Smith       } else {
43702a359c20SBarry Smith         ierr = PetscViewerASCIIPrintf(viewer,"Nonlinear solve converged due to %s iterations %D\n",SNESConvergedReasons[snes->reason],snes->iter);CHKERRQ(ierr);
43712a359c20SBarry Smith       }
43722a359c20SBarry Smith     } else {
43732a359c20SBarry Smith       if (((PetscObject) snes)->prefix) {
43742a359c20SBarry Smith         ierr = PetscViewerASCIIPrintf(viewer,"Nonlinear %s solve did not converge due to %s iterations %D\n",((PetscObject) snes)->prefix,SNESConvergedReasons[snes->reason],snes->iter);CHKERRQ(ierr);
43752a359c20SBarry Smith       } else {
43762a359c20SBarry Smith         ierr = PetscViewerASCIIPrintf(viewer,"Nonlinear solve did not converge due to %s iterations %D\n",SNESConvergedReasons[snes->reason],snes->iter);CHKERRQ(ierr);
43772a359c20SBarry Smith       }
43782a359c20SBarry Smith     }
43792a359c20SBarry Smith     ierr = PetscViewerASCIISubtractTab(viewer,((PetscObject)snes)->tablevel);CHKERRQ(ierr);
43802a359c20SBarry Smith   }
43812a359c20SBarry Smith   PetscFunctionReturn(0);
43822a359c20SBarry Smith }
43832a359c20SBarry Smith 
43842a359c20SBarry Smith /*@C
43852a359c20SBarry Smith   SNESReasonViewFromOptions - Processes command line options to determine if/how a SNESReason is to be viewed.
43862a359c20SBarry Smith 
43872a359c20SBarry Smith   Collective on SNES
43882a359c20SBarry Smith 
43892a359c20SBarry Smith   Input Parameters:
43902a359c20SBarry Smith . snes   - the SNES object
43912a359c20SBarry Smith 
43922a359c20SBarry Smith   Level: intermediate
43932a359c20SBarry Smith 
43942a359c20SBarry Smith @*/
43952a359c20SBarry Smith PetscErrorCode SNESReasonViewFromOptions(SNES snes)
43962a359c20SBarry Smith {
43972a359c20SBarry Smith   PetscErrorCode    ierr;
43982a359c20SBarry Smith   PetscViewer       viewer;
43992a359c20SBarry Smith   PetscBool         flg;
44002a359c20SBarry Smith   static PetscBool  incall = PETSC_FALSE;
44012a359c20SBarry Smith   PetscViewerFormat format;
44022a359c20SBarry Smith 
44032a359c20SBarry Smith   PetscFunctionBegin;
44042a359c20SBarry Smith   if (incall) PetscFunctionReturn(0);
44052a359c20SBarry Smith   incall = PETSC_TRUE;
440616413a6aSBarry Smith   ierr   = PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_converged_reason",&viewer,&format,&flg);CHKERRQ(ierr);
44072a359c20SBarry Smith   if (flg) {
44082a359c20SBarry Smith     ierr = PetscViewerPushFormat(viewer,format);CHKERRQ(ierr);
44092a359c20SBarry Smith     ierr = SNESReasonView(snes,viewer);CHKERRQ(ierr);
44102a359c20SBarry Smith     ierr = PetscViewerPopFormat(viewer);CHKERRQ(ierr);
44112a359c20SBarry Smith     ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr);
44122a359c20SBarry Smith   }
44132a359c20SBarry Smith   incall = PETSC_FALSE;
44142a359c20SBarry Smith   PetscFunctionReturn(0);
44152a359c20SBarry Smith }
44162a359c20SBarry Smith 
4417487a658cSBarry Smith /*@
4418f69a0ea3SMatthew Knepley    SNESSolve - Solves a nonlinear system F(x) = b.
4419f69a0ea3SMatthew Knepley    Call SNESSolve() after calling SNESCreate() and optional routines of the form SNESSetXXX().
44209b94acceSBarry Smith 
4421c7afd0dbSLois Curfman McInnes    Collective on SNES
4422c7afd0dbSLois Curfman McInnes 
4423b2002411SLois Curfman McInnes    Input Parameters:
4424c7afd0dbSLois Curfman McInnes +  snes - the SNES context
44250298fd71SBarry Smith .  b - the constant part of the equation F(x) = b, or NULL to use zero.
442685385478SLisandro Dalcin -  x - the solution vector.
44279b94acceSBarry Smith 
4428b2002411SLois Curfman McInnes    Notes:
44298ddd3da0SLois Curfman McInnes    The user should initialize the vector,x, with the initial guess
44308ddd3da0SLois Curfman McInnes    for the nonlinear solve prior to calling SNESSolve.  In particular,
44318ddd3da0SLois Curfman McInnes    to employ an initial guess of zero, the user should explicitly set
44328ddd3da0SLois Curfman McInnes    this vector to zero by calling VecSet().
44338ddd3da0SLois Curfman McInnes 
443436851e7fSLois Curfman McInnes    Level: beginner
443536851e7fSLois Curfman McInnes 
44369b94acceSBarry Smith .keywords: SNES, nonlinear, solve
44379b94acceSBarry Smith 
4438c0df2a02SJed Brown .seealso: SNESCreate(), SNESDestroy(), SNESSetFunction(), SNESSetJacobian(), SNESSetGridSequence(), SNESGetSolution()
44399b94acceSBarry Smith @*/
44407087cfbeSBarry Smith PetscErrorCode  SNESSolve(SNES snes,Vec b,Vec x)
44419b94acceSBarry Smith {
4442dfbe8321SBarry Smith   PetscErrorCode    ierr;
4443ace3abfcSBarry Smith   PetscBool         flg;
4444efd51863SBarry Smith   PetscInt          grid;
44450298fd71SBarry Smith   Vec               xcreated = NULL;
4446caa4e7f2SJed Brown   DM                dm;
4447052efed2SBarry Smith 
44483a40ed3dSBarry Smith   PetscFunctionBegin;
44490700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
4450a69afd8bSBarry Smith   if (x) PetscValidHeaderSpecific(x,VEC_CLASSID,3);
4451a69afd8bSBarry Smith   if (x) PetscCheckSameComm(snes,1,x,3);
44520700a824SBarry Smith   if (b) PetscValidHeaderSpecific(b,VEC_CLASSID,2);
445385385478SLisandro Dalcin   if (b) PetscCheckSameComm(snes,1,b,2);
445485385478SLisandro Dalcin 
445534b4d3a8SMatthew G. Knepley   /* High level operations using the nonlinear solver */
445606fc46c8SMatthew G. Knepley   {
445706fc46c8SMatthew G. Knepley     PetscViewer       viewer;
445806fc46c8SMatthew G. Knepley     PetscViewerFormat format;
44597c88af5aSMatthew G. Knepley     PetscInt          num;
446006fc46c8SMatthew G. Knepley     PetscBool         flg;
446106fc46c8SMatthew G. Knepley     static PetscBool  incall = PETSC_FALSE;
446206fc46c8SMatthew G. Knepley 
446306fc46c8SMatthew G. Knepley     if (!incall) {
446434b4d3a8SMatthew G. Knepley       /* Estimate the convergence rate of the discretization */
446516413a6aSBarry Smith       ierr = PetscOptionsGetViewer(PetscObjectComm((PetscObject) snes),((PetscObject)snes)->options, ((PetscObject) snes)->prefix, "-snes_convergence_estimate", &viewer, &format, &flg);CHKERRQ(ierr);
446606fc46c8SMatthew G. Knepley       if (flg) {
446706fc46c8SMatthew G. Knepley         PetscConvEst conv;
446846079b62SMatthew G. Knepley         DM           dm;
446946079b62SMatthew G. Knepley         PetscReal   *alpha; /* Convergence rate of the solution error for each field in the L_2 norm */
447046079b62SMatthew G. Knepley         PetscInt     Nf;
447106fc46c8SMatthew G. Knepley 
447206fc46c8SMatthew G. Knepley         incall = PETSC_TRUE;
447346079b62SMatthew G. Knepley         ierr = SNESGetDM(snes, &dm);CHKERRQ(ierr);
447446079b62SMatthew G. Knepley         ierr = DMGetNumFields(dm, &Nf);CHKERRQ(ierr);
447546079b62SMatthew G. Knepley         ierr = PetscMalloc1(Nf, &alpha);CHKERRQ(ierr);
447606fc46c8SMatthew G. Knepley         ierr = PetscConvEstCreate(PetscObjectComm((PetscObject) snes), &conv);CHKERRQ(ierr);
447706fc46c8SMatthew G. Knepley         ierr = PetscConvEstSetSolver(conv, snes);CHKERRQ(ierr);
447806fc46c8SMatthew G. Knepley         ierr = PetscConvEstSetFromOptions(conv);CHKERRQ(ierr);
44790955ed61SMatthew G. Knepley         ierr = PetscConvEstSetUp(conv);CHKERRQ(ierr);
448046079b62SMatthew G. Knepley         ierr = PetscConvEstGetConvRate(conv, alpha);CHKERRQ(ierr);
448106fc46c8SMatthew G. Knepley         ierr = PetscViewerPushFormat(viewer, format);CHKERRQ(ierr);
448206fc46c8SMatthew G. Knepley         ierr = PetscConvEstRateView(conv, alpha, viewer);CHKERRQ(ierr);
448306fc46c8SMatthew G. Knepley         ierr = PetscViewerPopFormat(viewer);CHKERRQ(ierr);
448406fc46c8SMatthew G. Knepley         ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr);
448506fc46c8SMatthew G. Knepley         ierr = PetscConvEstDestroy(&conv);CHKERRQ(ierr);
448646079b62SMatthew G. Knepley         ierr = PetscFree(alpha);CHKERRQ(ierr);
448706fc46c8SMatthew G. Knepley         incall = PETSC_FALSE;
448806fc46c8SMatthew G. Knepley       }
448934b4d3a8SMatthew G. Knepley       /* Adaptively refine the initial grid */
4490b2588ea6SMatthew G. Knepley       num  = 1;
4491b2588ea6SMatthew G. Knepley       ierr = PetscOptionsGetInt(NULL, ((PetscObject) snes)->prefix, "-snes_adapt_initial", &num, &flg);CHKERRQ(ierr);
449234b4d3a8SMatthew G. Knepley       if (flg) {
449334b4d3a8SMatthew G. Knepley         DMAdaptor adaptor;
449434b4d3a8SMatthew G. Knepley 
449534b4d3a8SMatthew G. Knepley         incall = PETSC_TRUE;
449634b4d3a8SMatthew G. Knepley         ierr = DMAdaptorCreate(PETSC_COMM_WORLD, &adaptor);CHKERRQ(ierr);
449734b4d3a8SMatthew G. Knepley         ierr = DMAdaptorSetSolver(adaptor, snes);CHKERRQ(ierr);
4498b2588ea6SMatthew G. Knepley         ierr = DMAdaptorSetSequenceLength(adaptor, num);CHKERRQ(ierr);
449934b4d3a8SMatthew G. Knepley         ierr = DMAdaptorSetFromOptions(adaptor);CHKERRQ(ierr);
450034b4d3a8SMatthew G. Knepley         ierr = DMAdaptorSetUp(adaptor);CHKERRQ(ierr);
450134b4d3a8SMatthew G. Knepley         ierr = DMAdaptorAdapt(adaptor, x, DM_ADAPTATION_INITIAL, &dm, &x);CHKERRQ(ierr);
450234b4d3a8SMatthew G. Knepley         ierr = DMAdaptorDestroy(&adaptor);CHKERRQ(ierr);
450334b4d3a8SMatthew G. Knepley         incall = PETSC_FALSE;
450434b4d3a8SMatthew G. Knepley       }
45057c88af5aSMatthew G. Knepley       /* Use grid sequencing to adapt */
45067c88af5aSMatthew G. Knepley       num  = 0;
45077c88af5aSMatthew G. Knepley       ierr = PetscOptionsGetInt(NULL, ((PetscObject) snes)->prefix, "-snes_adapt_sequence", &num, NULL);CHKERRQ(ierr);
45087c88af5aSMatthew G. Knepley       if (num) {
45097c88af5aSMatthew G. Knepley         DMAdaptor adaptor;
45107c88af5aSMatthew G. Knepley 
45117c88af5aSMatthew G. Knepley         incall = PETSC_TRUE;
45127c88af5aSMatthew G. Knepley         ierr = DMAdaptorCreate(PETSC_COMM_WORLD, &adaptor);CHKERRQ(ierr);
45137c88af5aSMatthew G. Knepley         ierr = DMAdaptorSetSolver(adaptor, snes);CHKERRQ(ierr);
45147c88af5aSMatthew G. Knepley         ierr = DMAdaptorSetSequenceLength(adaptor, num);CHKERRQ(ierr);
45157c88af5aSMatthew G. Knepley         ierr = DMAdaptorSetFromOptions(adaptor);CHKERRQ(ierr);
45167c88af5aSMatthew G. Knepley         ierr = DMAdaptorSetUp(adaptor);CHKERRQ(ierr);
45177c88af5aSMatthew G. Knepley         ierr = DMAdaptorAdapt(adaptor, x, DM_ADAPTATION_SEQUENTIAL, &dm, &x);CHKERRQ(ierr);
45187c88af5aSMatthew G. Knepley         ierr = DMAdaptorDestroy(&adaptor);CHKERRQ(ierr);
45197c88af5aSMatthew G. Knepley         incall = PETSC_FALSE;
45207c88af5aSMatthew G. Knepley       }
452106fc46c8SMatthew G. Knepley     }
452206fc46c8SMatthew G. Knepley   }
4523caa4e7f2SJed Brown   if (!x) {
4524caa4e7f2SJed Brown     ierr = SNESGetDM(snes,&dm);CHKERRQ(ierr);
4525caa4e7f2SJed Brown     ierr = DMCreateGlobalVector(dm,&xcreated);CHKERRQ(ierr);
4526a69afd8bSBarry Smith     x    = xcreated;
4527a69afd8bSBarry Smith   }
4528ce1779c8SBarry Smith   ierr = SNESViewFromOptions(snes,NULL,"-snes_view_pre");CHKERRQ(ierr);
4529f05ece33SBarry Smith 
4530ce94432eSBarry Smith   for (grid=0; grid<snes->gridsequence; grid++) {ierr = PetscViewerASCIIPushTab(PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)snes)));CHKERRQ(ierr);}
4531efd51863SBarry Smith   for (grid=0; grid<snes->gridsequence+1; grid++) {
4532efd51863SBarry Smith 
453385385478SLisandro Dalcin     /* set solution vector */
4534efd51863SBarry Smith     if (!grid) {ierr = PetscObjectReference((PetscObject)x);CHKERRQ(ierr);}
45356bf464f9SBarry Smith     ierr          = VecDestroy(&snes->vec_sol);CHKERRQ(ierr);
453685385478SLisandro Dalcin     snes->vec_sol = x;
4537caa4e7f2SJed Brown     ierr          = SNESGetDM(snes,&dm);CHKERRQ(ierr);
4538caa4e7f2SJed Brown 
4539caa4e7f2SJed Brown     /* set affine vector if provided */
454085385478SLisandro Dalcin     if (b) { ierr = PetscObjectReference((PetscObject)b);CHKERRQ(ierr); }
45416bf464f9SBarry Smith     ierr          = VecDestroy(&snes->vec_rhs);CHKERRQ(ierr);
454285385478SLisandro Dalcin     snes->vec_rhs = b;
454385385478SLisandro Dalcin 
4544bfdd6862SPatrick Farrell     if (snes->vec_rhs && (snes->vec_func == snes->vec_rhs)) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"Right hand side vector cannot be function vector");
4545154060b5SMatthew G. Knepley     if (snes->vec_func == snes->vec_sol) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"Solution vector cannot be function vector");
4546154060b5SMatthew G. Knepley     if (snes->vec_rhs  == snes->vec_sol) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"Solution vector cannot be right hand side vector");
4547154060b5SMatthew G. Knepley     if (!snes->vec_sol_update /* && snes->vec_sol */) {
4548154060b5SMatthew G. Knepley       ierr = VecDuplicate(snes->vec_sol,&snes->vec_sol_update);CHKERRQ(ierr);
4549154060b5SMatthew G. Knepley       ierr = PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->vec_sol_update);CHKERRQ(ierr);
4550154060b5SMatthew G. Knepley     }
4551154060b5SMatthew G. Knepley     ierr = DMShellSetGlobalVector(dm,snes->vec_sol);CHKERRQ(ierr);
455270e92668SMatthew Knepley     ierr = SNESSetUp(snes);CHKERRQ(ierr);
45533f149594SLisandro Dalcin 
45547eee914bSBarry Smith     if (!grid) {
45557eee914bSBarry Smith       if (snes->ops->computeinitialguess) {
4556d25893d9SBarry Smith         ierr = (*snes->ops->computeinitialguess)(snes,snes->vec_sol,snes->initialguessP);CHKERRQ(ierr);
4557d25893d9SBarry Smith       }
4558dd568438SSatish Balay     }
4559d25893d9SBarry Smith 
4560abc0a331SBarry Smith     if (snes->conv_hist_reset) snes->conv_hist_len = 0;
4561971e163fSPeter Brune     if (snes->counters_reset) {snes->nfuncs = 0; snes->linear_its = 0; snes->numFailures = 0;}
4562d5e45103SBarry Smith 
45633f149594SLisandro Dalcin     ierr = PetscLogEventBegin(SNES_Solve,snes,0,0,0);CHKERRQ(ierr);
45644936397dSBarry Smith     ierr = (*snes->ops->solve)(snes);CHKERRQ(ierr);
456585385478SLisandro Dalcin     ierr = PetscLogEventEnd(SNES_Solve,snes,0,0,0);CHKERRQ(ierr);
456617186662SBarry Smith     if (!snes->reason) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Internal error, solver returned without setting converged reason");
4567422a814eSBarry Smith     snes->domainerror = PETSC_FALSE; /* clear the flag if it has been set */
45683f149594SLisandro Dalcin 
456937ec4e1aSPeter Brune     if (snes->lagjac_persist) snes->jac_iter += snes->iter;
457037ec4e1aSPeter Brune     if (snes->lagpre_persist) snes->pre_iter += snes->iter;
457137ec4e1aSPeter Brune 
457216413a6aSBarry Smith     ierr   = PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_test_local_min",NULL,NULL,&flg);CHKERRQ(ierr);
4573da9b6338SBarry Smith     if (flg && !PetscPreLoadingOn) { ierr = SNESTestLocalMin(snes);CHKERRQ(ierr); }
45742a359c20SBarry Smith     ierr = SNESReasonViewFromOptions(snes);CHKERRQ(ierr);
45755968eb51SBarry Smith 
4576ce94432eSBarry Smith     if (snes->errorifnotconverged && snes->reason < 0) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_NOT_CONVERGED,"SNESSolve has not converged");
45779c8e83a9SBarry Smith     if (snes->reason < 0) break;
4578efd51863SBarry Smith     if (grid <  snes->gridsequence) {
4579efd51863SBarry Smith       DM  fine;
4580efd51863SBarry Smith       Vec xnew;
4581efd51863SBarry Smith       Mat interp;
4582efd51863SBarry Smith 
4583ce94432eSBarry Smith       ierr = DMRefine(snes->dm,PetscObjectComm((PetscObject)snes),&fine);CHKERRQ(ierr);
4584ce94432eSBarry Smith       if (!fine) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_INCOMP,"DMRefine() did not perform any refinement, cannot continue grid sequencing");
45850298fd71SBarry Smith       ierr = DMCreateInterpolation(snes->dm,fine,&interp,NULL);CHKERRQ(ierr);
4586efd51863SBarry Smith       ierr = DMCreateGlobalVector(fine,&xnew);CHKERRQ(ierr);
4587efd51863SBarry Smith       ierr = MatInterpolate(interp,x,xnew);CHKERRQ(ierr);
4588c833c3b5SJed Brown       ierr = DMInterpolate(snes->dm,interp,fine);CHKERRQ(ierr);
4589efd51863SBarry Smith       ierr = MatDestroy(&interp);CHKERRQ(ierr);
4590efd51863SBarry Smith       x    = xnew;
4591efd51863SBarry Smith 
4592efd51863SBarry Smith       ierr = SNESReset(snes);CHKERRQ(ierr);
4593efd51863SBarry Smith       ierr = SNESSetDM(snes,fine);CHKERRQ(ierr);
4594352f405dSMatthew G. Knepley       ierr = SNESResetFromOptions(snes);CHKERRQ(ierr);
4595efd51863SBarry Smith       ierr = DMDestroy(&fine);CHKERRQ(ierr);
4596ce94432eSBarry Smith       ierr = PetscViewerASCIIPopTab(PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)snes)));CHKERRQ(ierr);
4597efd51863SBarry Smith     }
4598efd51863SBarry Smith   }
4599ce1779c8SBarry Smith   ierr = SNESViewFromOptions(snes,NULL,"-snes_view");CHKERRQ(ierr);
4600685405a1SBarry Smith   ierr = VecViewFromOptions(snes->vec_sol,(PetscObject)snes,"-snes_view_solution");CHKERRQ(ierr);
46013f7e2da0SPeter Brune 
4602a69afd8bSBarry Smith   ierr = VecDestroy(&xcreated);CHKERRQ(ierr);
4603e04113cfSBarry Smith   ierr = PetscObjectSAWsBlock((PetscObject)snes);CHKERRQ(ierr);
46043a40ed3dSBarry Smith   PetscFunctionReturn(0);
46059b94acceSBarry Smith }
46069b94acceSBarry Smith 
46079b94acceSBarry Smith /* --------- Internal routines for SNES Package --------- */
46089b94acceSBarry Smith 
460982bf6240SBarry Smith /*@C
46104b0e389bSBarry Smith    SNESSetType - Sets the method for the nonlinear solver.
46119b94acceSBarry Smith 
4612fee21e36SBarry Smith    Collective on SNES
4613fee21e36SBarry Smith 
4614c7afd0dbSLois Curfman McInnes    Input Parameters:
4615c7afd0dbSLois Curfman McInnes +  snes - the SNES context
4616454a90a3SBarry Smith -  type - a known method
4617c7afd0dbSLois Curfman McInnes 
4618c7afd0dbSLois Curfman McInnes    Options Database Key:
4619454a90a3SBarry Smith .  -snes_type <type> - Sets the method; use -help for a list
462004d7464bSBarry Smith    of available methods (for instance, newtonls or newtontr)
4621ae12b187SLois Curfman McInnes 
46229b94acceSBarry Smith    Notes:
4623e090d566SSatish Balay    See "petsc/include/petscsnes.h" for available methods (for instance)
462404d7464bSBarry Smith +    SNESNEWTONLS - Newton's method with line search
4625c7afd0dbSLois Curfman McInnes      (systems of nonlinear equations)
462604d7464bSBarry Smith .    SNESNEWTONTR - Newton's method with trust region
4627c7afd0dbSLois Curfman McInnes      (systems of nonlinear equations)
46289b94acceSBarry Smith 
4629ae12b187SLois Curfman McInnes   Normally, it is best to use the SNESSetFromOptions() command and then
4630ae12b187SLois Curfman McInnes   set the SNES solver type from the options database rather than by using
4631ae12b187SLois Curfman McInnes   this routine.  Using the options database provides the user with
4632ae12b187SLois Curfman McInnes   maximum flexibility in evaluating the many nonlinear solvers.
4633ae12b187SLois Curfman McInnes   The SNESSetType() routine is provided for those situations where it
4634ae12b187SLois Curfman McInnes   is necessary to set the nonlinear solver independently of the command
4635ae12b187SLois Curfman McInnes   line or options database.  This might be the case, for example, when
4636ae12b187SLois Curfman McInnes   the choice of solver changes during the execution of the program,
4637ae12b187SLois Curfman McInnes   and the user's application is taking responsibility for choosing the
4638b0a32e0cSBarry Smith   appropriate method.
463936851e7fSLois Curfman McInnes 
464095452b02SPatrick Sanan     Developer Notes:
464195452b02SPatrick Sanan     SNESRegister() adds a constructor for a new SNESType to SNESList, SNESSetType() locates
46428f6c3df8SBarry Smith     the constructor in that list and calls it to create the spexific object.
46438f6c3df8SBarry Smith 
464436851e7fSLois Curfman McInnes   Level: intermediate
4645a703fe33SLois Curfman McInnes 
4646454a90a3SBarry Smith .keywords: SNES, set, type
4647435da068SBarry Smith 
46488f6c3df8SBarry Smith .seealso: SNESType, SNESCreate(), SNESDestroy(), SNESGetType(), SNESSetFromOptions()
4649435da068SBarry Smith 
46509b94acceSBarry Smith @*/
465119fd82e9SBarry Smith PetscErrorCode  SNESSetType(SNES snes,SNESType type)
46529b94acceSBarry Smith {
4653dfbe8321SBarry Smith   PetscErrorCode ierr,(*r)(SNES);
4654ace3abfcSBarry Smith   PetscBool      match;
46553a40ed3dSBarry Smith 
46563a40ed3dSBarry Smith   PetscFunctionBegin;
46570700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
46584482741eSBarry Smith   PetscValidCharPointer(type,2);
465982bf6240SBarry Smith 
4660251f4c67SDmitry Karpeev   ierr = PetscObjectTypeCompare((PetscObject)snes,type,&match);CHKERRQ(ierr);
46610f5bd95cSBarry Smith   if (match) PetscFunctionReturn(0);
466292ff6ae8SBarry Smith 
46631c9cd337SJed Brown   ierr =  PetscFunctionListFind(SNESList,type,&r);CHKERRQ(ierr);
4664e32f2f54SBarry Smith   if (!r) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_UNKNOWN_TYPE,"Unable to find requested SNES type %s",type);
466575396ef9SLisandro Dalcin   /* Destroy the previous private SNES context */
4666b5c23020SJed Brown   if (snes->ops->destroy) {
4667b5c23020SJed Brown     ierr               = (*(snes)->ops->destroy)(snes);CHKERRQ(ierr);
46680298fd71SBarry Smith     snes->ops->destroy = NULL;
4669b5c23020SJed Brown   }
467075396ef9SLisandro Dalcin   /* Reinitialize function pointers in SNESOps structure */
467175396ef9SLisandro Dalcin   snes->ops->setup          = 0;
467275396ef9SLisandro Dalcin   snes->ops->solve          = 0;
467375396ef9SLisandro Dalcin   snes->ops->view           = 0;
467475396ef9SLisandro Dalcin   snes->ops->setfromoptions = 0;
467575396ef9SLisandro Dalcin   snes->ops->destroy        = 0;
467675396ef9SLisandro Dalcin   /* Call the SNESCreate_XXX routine for this particular Nonlinear solver */
467775396ef9SLisandro Dalcin   snes->setupcalled = PETSC_FALSE;
4678f5af7f23SKarl Rupp 
4679454a90a3SBarry Smith   ierr = PetscObjectChangeTypeName((PetscObject)snes,type);CHKERRQ(ierr);
468003bfa161SLisandro Dalcin   ierr = (*r)(snes);CHKERRQ(ierr);
46813a40ed3dSBarry Smith   PetscFunctionReturn(0);
46829b94acceSBarry Smith }
46839b94acceSBarry Smith 
46849b94acceSBarry Smith /*@C
46859a28b0a6SLois Curfman McInnes    SNESGetType - Gets the SNES method type and name (as a string).
46869b94acceSBarry Smith 
4687c7afd0dbSLois Curfman McInnes    Not Collective
4688c7afd0dbSLois Curfman McInnes 
46899b94acceSBarry Smith    Input Parameter:
46904b0e389bSBarry Smith .  snes - nonlinear solver context
46919b94acceSBarry Smith 
46929b94acceSBarry Smith    Output Parameter:
46933a7fca6bSBarry Smith .  type - SNES method (a character string)
46949b94acceSBarry Smith 
469536851e7fSLois Curfman McInnes    Level: intermediate
469636851e7fSLois Curfman McInnes 
4697454a90a3SBarry Smith .keywords: SNES, nonlinear, get, type, name
46989b94acceSBarry Smith @*/
469919fd82e9SBarry Smith PetscErrorCode  SNESGetType(SNES snes,SNESType *type)
47009b94acceSBarry Smith {
47013a40ed3dSBarry Smith   PetscFunctionBegin;
47020700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
47034482741eSBarry Smith   PetscValidPointer(type,2);
47047adad957SLisandro Dalcin   *type = ((PetscObject)snes)->type_name;
47053a40ed3dSBarry Smith   PetscFunctionReturn(0);
47069b94acceSBarry Smith }
47079b94acceSBarry Smith 
47083cd8a7caSMatthew G. Knepley /*@
47093cd8a7caSMatthew G. Knepley   SNESSetSolution - Sets the solution vector for use by the SNES routines.
47103cd8a7caSMatthew G. Knepley 
47113cd8a7caSMatthew G. Knepley   Logically Collective on SNES and Vec
47123cd8a7caSMatthew G. Knepley 
47133cd8a7caSMatthew G. Knepley   Input Parameters:
47143cd8a7caSMatthew G. Knepley + snes - the SNES context obtained from SNESCreate()
47153cd8a7caSMatthew G. Knepley - u    - the solution vector
47163cd8a7caSMatthew G. Knepley 
47173cd8a7caSMatthew G. Knepley   Level: beginner
47183cd8a7caSMatthew G. Knepley 
47193cd8a7caSMatthew G. Knepley .keywords: SNES, set, solution
47203cd8a7caSMatthew G. Knepley @*/
47213cd8a7caSMatthew G. Knepley PetscErrorCode SNESSetSolution(SNES snes, Vec u)
47223cd8a7caSMatthew G. Knepley {
47233cd8a7caSMatthew G. Knepley   DM             dm;
47243cd8a7caSMatthew G. Knepley   PetscErrorCode ierr;
47253cd8a7caSMatthew G. Knepley 
47263cd8a7caSMatthew G. Knepley   PetscFunctionBegin;
47273cd8a7caSMatthew G. Knepley   PetscValidHeaderSpecific(snes, SNES_CLASSID, 1);
47283cd8a7caSMatthew G. Knepley   PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
47293cd8a7caSMatthew G. Knepley   ierr = PetscObjectReference((PetscObject) u);CHKERRQ(ierr);
47303cd8a7caSMatthew G. Knepley   ierr = VecDestroy(&snes->vec_sol);CHKERRQ(ierr);
47313cd8a7caSMatthew G. Knepley 
47323cd8a7caSMatthew G. Knepley   snes->vec_sol = u;
47333cd8a7caSMatthew G. Knepley 
47343cd8a7caSMatthew G. Knepley   ierr = SNESGetDM(snes, &dm);CHKERRQ(ierr);
47353cd8a7caSMatthew G. Knepley   ierr = DMShellSetGlobalVector(dm, u);CHKERRQ(ierr);
47363cd8a7caSMatthew G. Knepley   PetscFunctionReturn(0);
47373cd8a7caSMatthew G. Knepley }
47383cd8a7caSMatthew G. Knepley 
473952baeb72SSatish Balay /*@
47409b94acceSBarry Smith    SNESGetSolution - Returns the vector where the approximate solution is
4741c0df2a02SJed Brown    stored. This is the fine grid solution when using SNESSetGridSequence().
47429b94acceSBarry Smith 
4743c7afd0dbSLois Curfman McInnes    Not Collective, but Vec is parallel if SNES is parallel
4744c7afd0dbSLois Curfman McInnes 
47459b94acceSBarry Smith    Input Parameter:
47469b94acceSBarry Smith .  snes - the SNES context
47479b94acceSBarry Smith 
47489b94acceSBarry Smith    Output Parameter:
47499b94acceSBarry Smith .  x - the solution
47509b94acceSBarry Smith 
475170e92668SMatthew Knepley    Level: intermediate
475236851e7fSLois Curfman McInnes 
47539b94acceSBarry Smith .keywords: SNES, nonlinear, get, solution
47549b94acceSBarry Smith 
475585385478SLisandro Dalcin .seealso:  SNESGetSolutionUpdate(), SNESGetFunction()
47569b94acceSBarry Smith @*/
47577087cfbeSBarry Smith PetscErrorCode  SNESGetSolution(SNES snes,Vec *x)
47589b94acceSBarry Smith {
47593a40ed3dSBarry Smith   PetscFunctionBegin;
47600700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
47614482741eSBarry Smith   PetscValidPointer(x,2);
476285385478SLisandro Dalcin   *x = snes->vec_sol;
476370e92668SMatthew Knepley   PetscFunctionReturn(0);
476470e92668SMatthew Knepley }
476570e92668SMatthew Knepley 
476652baeb72SSatish Balay /*@
47679b94acceSBarry Smith    SNESGetSolutionUpdate - Returns the vector where the solution update is
47689b94acceSBarry Smith    stored.
47699b94acceSBarry Smith 
4770c7afd0dbSLois Curfman McInnes    Not Collective, but Vec is parallel if SNES is parallel
4771c7afd0dbSLois Curfman McInnes 
47729b94acceSBarry Smith    Input Parameter:
47739b94acceSBarry Smith .  snes - the SNES context
47749b94acceSBarry Smith 
47759b94acceSBarry Smith    Output Parameter:
47769b94acceSBarry Smith .  x - the solution update
47779b94acceSBarry Smith 
477836851e7fSLois Curfman McInnes    Level: advanced
477936851e7fSLois Curfman McInnes 
47809b94acceSBarry Smith .keywords: SNES, nonlinear, get, solution, update
47819b94acceSBarry Smith 
478285385478SLisandro Dalcin .seealso: SNESGetSolution(), SNESGetFunction()
47839b94acceSBarry Smith @*/
47847087cfbeSBarry Smith PetscErrorCode  SNESGetSolutionUpdate(SNES snes,Vec *x)
47859b94acceSBarry Smith {
47863a40ed3dSBarry Smith   PetscFunctionBegin;
47870700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
47884482741eSBarry Smith   PetscValidPointer(x,2);
478985385478SLisandro Dalcin   *x = snes->vec_sol_update;
47903a40ed3dSBarry Smith   PetscFunctionReturn(0);
47919b94acceSBarry Smith }
47929b94acceSBarry Smith 
47939b94acceSBarry Smith /*@C
47943638b69dSLois Curfman McInnes    SNESGetFunction - Returns the vector where the function is stored.
47959b94acceSBarry Smith 
4796a63bb30eSJed Brown    Not Collective, but Vec is parallel if SNES is parallel. Collective if Vec is requested, but has not been created yet.
4797c7afd0dbSLois Curfman McInnes 
47989b94acceSBarry Smith    Input Parameter:
47999b94acceSBarry Smith .  snes - the SNES context
48009b94acceSBarry Smith 
48019b94acceSBarry Smith    Output Parameter:
48020298fd71SBarry Smith +  r - the vector that is used to store residuals (or NULL if you don't want it)
4803f8b49ee9SBarry Smith .  f - the function (or NULL if you don't want it); see SNESFunction for calling sequence details
48040298fd71SBarry Smith -  ctx - the function context (or NULL if you don't want it)
48059b94acceSBarry Smith 
480636851e7fSLois Curfman McInnes    Level: advanced
480736851e7fSLois Curfman McInnes 
480804edfde5SBarry Smith     Notes: The vector r DOES NOT, in general contain the current value of the SNES nonlinear function
480904edfde5SBarry Smith 
4810a86d99e1SLois Curfman McInnes .keywords: SNES, nonlinear, get, function
48119b94acceSBarry Smith 
4812bf388a1fSBarry Smith .seealso: SNESSetFunction(), SNESGetSolution(), SNESFunction
48139b94acceSBarry Smith @*/
4814f8b49ee9SBarry Smith PetscErrorCode  SNESGetFunction(SNES snes,Vec *r,PetscErrorCode (**f)(SNES,Vec,Vec,void*),void **ctx)
48159b94acceSBarry Smith {
4816a63bb30eSJed Brown   PetscErrorCode ierr;
48176cab3a1bSJed Brown   DM             dm;
4818a63bb30eSJed Brown 
48193a40ed3dSBarry Smith   PetscFunctionBegin;
48200700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
4821a63bb30eSJed Brown   if (r) {
4822a63bb30eSJed Brown     if (!snes->vec_func) {
4823a63bb30eSJed Brown       if (snes->vec_rhs) {
4824a63bb30eSJed Brown         ierr = VecDuplicate(snes->vec_rhs,&snes->vec_func);CHKERRQ(ierr);
4825a63bb30eSJed Brown       } else if (snes->vec_sol) {
4826a63bb30eSJed Brown         ierr = VecDuplicate(snes->vec_sol,&snes->vec_func);CHKERRQ(ierr);
4827a63bb30eSJed Brown       } else if (snes->dm) {
4828a63bb30eSJed Brown         ierr = DMCreateGlobalVector(snes->dm,&snes->vec_func);CHKERRQ(ierr);
4829a63bb30eSJed Brown       }
4830a63bb30eSJed Brown     }
4831a63bb30eSJed Brown     *r = snes->vec_func;
4832a63bb30eSJed Brown   }
48336cab3a1bSJed Brown   ierr = SNESGetDM(snes,&dm);CHKERRQ(ierr);
4834f8b49ee9SBarry Smith   ierr = DMSNESGetFunction(dm,f,ctx);CHKERRQ(ierr);
48353a40ed3dSBarry Smith   PetscFunctionReturn(0);
48369b94acceSBarry Smith }
48379b94acceSBarry Smith 
4838c79ef259SPeter Brune /*@C
4839be95d8f1SBarry Smith    SNESGetNGS - Returns the NGS function and context.
4840c79ef259SPeter Brune 
4841c79ef259SPeter Brune    Input Parameter:
4842c79ef259SPeter Brune .  snes - the SNES context
4843c79ef259SPeter Brune 
4844c79ef259SPeter Brune    Output Parameter:
4845be95d8f1SBarry Smith +  f - the function (or NULL) see SNESNGSFunction for details
48460298fd71SBarry Smith -  ctx    - the function context (or NULL)
4847c79ef259SPeter Brune 
4848c79ef259SPeter Brune    Level: advanced
4849c79ef259SPeter Brune 
4850c79ef259SPeter Brune .keywords: SNES, nonlinear, get, function
4851c79ef259SPeter Brune 
4852be95d8f1SBarry Smith .seealso: SNESSetNGS(), SNESGetFunction()
4853c79ef259SPeter Brune @*/
4854c79ef259SPeter Brune 
4855be95d8f1SBarry Smith PetscErrorCode SNESGetNGS (SNES snes, PetscErrorCode (**f)(SNES, Vec, Vec, void*), void ** ctx)
4856646217ecSPeter Brune {
48576cab3a1bSJed Brown   PetscErrorCode ierr;
48586cab3a1bSJed Brown   DM             dm;
48596cab3a1bSJed Brown 
4860646217ecSPeter Brune   PetscFunctionBegin;
4861646217ecSPeter Brune   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
48626cab3a1bSJed Brown   ierr = SNESGetDM(snes,&dm);CHKERRQ(ierr);
4863be95d8f1SBarry Smith   ierr = DMSNESGetNGS(dm,f,ctx);CHKERRQ(ierr);
4864646217ecSPeter Brune   PetscFunctionReturn(0);
4865646217ecSPeter Brune }
4866646217ecSPeter Brune 
48673c7409f5SSatish Balay /*@C
48683c7409f5SSatish Balay    SNESSetOptionsPrefix - Sets the prefix used for searching for all
4869d850072dSLois Curfman McInnes    SNES options in the database.
48703c7409f5SSatish Balay 
48713f9fe445SBarry Smith    Logically Collective on SNES
4872fee21e36SBarry Smith 
4873c7afd0dbSLois Curfman McInnes    Input Parameter:
4874c7afd0dbSLois Curfman McInnes +  snes - the SNES context
4875c7afd0dbSLois Curfman McInnes -  prefix - the prefix to prepend to all option names
4876c7afd0dbSLois Curfman McInnes 
4877d850072dSLois Curfman McInnes    Notes:
4878a83b1b31SSatish Balay    A hyphen (-) must NOT be given at the beginning of the prefix name.
4879c7afd0dbSLois Curfman McInnes    The first character of all runtime options is AUTOMATICALLY the hyphen.
4880d850072dSLois Curfman McInnes 
488136851e7fSLois Curfman McInnes    Level: advanced
488236851e7fSLois Curfman McInnes 
48833c7409f5SSatish Balay .keywords: SNES, set, options, prefix, database
4884a86d99e1SLois Curfman McInnes 
4885a86d99e1SLois Curfman McInnes .seealso: SNESSetFromOptions()
48863c7409f5SSatish Balay @*/
48877087cfbeSBarry Smith PetscErrorCode  SNESSetOptionsPrefix(SNES snes,const char prefix[])
48883c7409f5SSatish Balay {
4889dfbe8321SBarry Smith   PetscErrorCode ierr;
48903c7409f5SSatish Balay 
48913a40ed3dSBarry Smith   PetscFunctionBegin;
48920700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
4893639f9d9dSBarry Smith   ierr = PetscObjectSetOptionsPrefix((PetscObject)snes,prefix);CHKERRQ(ierr);
48941cee3971SBarry Smith   if (!snes->ksp) {ierr = SNESGetKSP(snes,&snes->ksp);CHKERRQ(ierr);}
489535f5d045SPeter Brune   if (snes->linesearch) {
48967601faf0SJed Brown     ierr = SNESGetLineSearch(snes,&snes->linesearch);CHKERRQ(ierr);
489708b6c495SPeter Brune     ierr = PetscObjectSetOptionsPrefix((PetscObject)snes->linesearch,prefix);CHKERRQ(ierr);
489835f5d045SPeter Brune   }
489935f5d045SPeter Brune   ierr = KSPSetOptionsPrefix(snes->ksp,prefix);CHKERRQ(ierr);
49003a40ed3dSBarry Smith   PetscFunctionReturn(0);
49013c7409f5SSatish Balay }
49023c7409f5SSatish Balay 
49033c7409f5SSatish Balay /*@C
4904f525115eSLois Curfman McInnes    SNESAppendOptionsPrefix - Appends to the prefix used for searching for all
4905d850072dSLois Curfman McInnes    SNES options in the database.
49063c7409f5SSatish Balay 
49073f9fe445SBarry Smith    Logically Collective on SNES
4908fee21e36SBarry Smith 
4909c7afd0dbSLois Curfman McInnes    Input Parameters:
4910c7afd0dbSLois Curfman McInnes +  snes - the SNES context
4911c7afd0dbSLois Curfman McInnes -  prefix - the prefix to prepend to all option names
4912c7afd0dbSLois Curfman McInnes 
4913d850072dSLois Curfman McInnes    Notes:
4914a83b1b31SSatish Balay    A hyphen (-) must NOT be given at the beginning of the prefix name.
4915c7afd0dbSLois Curfman McInnes    The first character of all runtime options is AUTOMATICALLY the hyphen.
4916d850072dSLois Curfman McInnes 
491736851e7fSLois Curfman McInnes    Level: advanced
491836851e7fSLois Curfman McInnes 
49193c7409f5SSatish Balay .keywords: SNES, append, options, prefix, database
4920a86d99e1SLois Curfman McInnes 
4921a86d99e1SLois Curfman McInnes .seealso: SNESGetOptionsPrefix()
49223c7409f5SSatish Balay @*/
49237087cfbeSBarry Smith PetscErrorCode  SNESAppendOptionsPrefix(SNES snes,const char prefix[])
49243c7409f5SSatish Balay {
4925dfbe8321SBarry Smith   PetscErrorCode ierr;
49263c7409f5SSatish Balay 
49273a40ed3dSBarry Smith   PetscFunctionBegin;
49280700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
4929639f9d9dSBarry Smith   ierr = PetscObjectAppendOptionsPrefix((PetscObject)snes,prefix);CHKERRQ(ierr);
49301cee3971SBarry Smith   if (!snes->ksp) {ierr = SNESGetKSP(snes,&snes->ksp);CHKERRQ(ierr);}
493135f5d045SPeter Brune   if (snes->linesearch) {
49327601faf0SJed Brown     ierr = SNESGetLineSearch(snes,&snes->linesearch);CHKERRQ(ierr);
493308b6c495SPeter Brune     ierr = PetscObjectAppendOptionsPrefix((PetscObject)snes->linesearch,prefix);CHKERRQ(ierr);
493435f5d045SPeter Brune   }
493535f5d045SPeter Brune   ierr = KSPAppendOptionsPrefix(snes->ksp,prefix);CHKERRQ(ierr);
49363a40ed3dSBarry Smith   PetscFunctionReturn(0);
49373c7409f5SSatish Balay }
49383c7409f5SSatish Balay 
49399ab63eb5SSatish Balay /*@C
49403c7409f5SSatish Balay    SNESGetOptionsPrefix - Sets the prefix used for searching for all
49413c7409f5SSatish Balay    SNES options in the database.
49423c7409f5SSatish Balay 
4943c7afd0dbSLois Curfman McInnes    Not Collective
4944c7afd0dbSLois Curfman McInnes 
49453c7409f5SSatish Balay    Input Parameter:
49463c7409f5SSatish Balay .  snes - the SNES context
49473c7409f5SSatish Balay 
49483c7409f5SSatish Balay    Output Parameter:
49493c7409f5SSatish Balay .  prefix - pointer to the prefix string used
49503c7409f5SSatish Balay 
495195452b02SPatrick Sanan    Notes:
495295452b02SPatrick Sanan     On the fortran side, the user should pass in a string 'prefix' of
49539ab63eb5SSatish Balay    sufficient length to hold the prefix.
49549ab63eb5SSatish Balay 
495536851e7fSLois Curfman McInnes    Level: advanced
495636851e7fSLois Curfman McInnes 
49573c7409f5SSatish Balay .keywords: SNES, get, options, prefix, database
4958a86d99e1SLois Curfman McInnes 
4959a86d99e1SLois Curfman McInnes .seealso: SNESAppendOptionsPrefix()
49603c7409f5SSatish Balay @*/
49617087cfbeSBarry Smith PetscErrorCode  SNESGetOptionsPrefix(SNES snes,const char *prefix[])
49623c7409f5SSatish Balay {
4963dfbe8321SBarry Smith   PetscErrorCode ierr;
49643c7409f5SSatish Balay 
49653a40ed3dSBarry Smith   PetscFunctionBegin;
49660700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
4967639f9d9dSBarry Smith   ierr = PetscObjectGetOptionsPrefix((PetscObject)snes,prefix);CHKERRQ(ierr);
49683a40ed3dSBarry Smith   PetscFunctionReturn(0);
49693c7409f5SSatish Balay }
49703c7409f5SSatish Balay 
4971b2002411SLois Curfman McInnes 
49723cea93caSBarry Smith /*@C
49731c84c290SBarry Smith   SNESRegister - Adds a method to the nonlinear solver package.
49741c84c290SBarry Smith 
49751c84c290SBarry Smith    Not collective
49761c84c290SBarry Smith 
49771c84c290SBarry Smith    Input Parameters:
49781c84c290SBarry Smith +  name_solver - name of a new user-defined solver
49791c84c290SBarry Smith -  routine_create - routine to create method context
49801c84c290SBarry Smith 
49811c84c290SBarry Smith    Notes:
49821c84c290SBarry Smith    SNESRegister() may be called multiple times to add several user-defined solvers.
49831c84c290SBarry Smith 
49841c84c290SBarry Smith    Sample usage:
49851c84c290SBarry Smith .vb
4986bdf89e91SBarry Smith    SNESRegister("my_solver",MySolverCreate);
49871c84c290SBarry Smith .ve
49881c84c290SBarry Smith 
49891c84c290SBarry Smith    Then, your solver can be chosen with the procedural interface via
49901c84c290SBarry Smith $     SNESSetType(snes,"my_solver")
49911c84c290SBarry Smith    or at runtime via the option
49921c84c290SBarry Smith $     -snes_type my_solver
49931c84c290SBarry Smith 
49941c84c290SBarry Smith    Level: advanced
49951c84c290SBarry Smith 
49961c84c290SBarry Smith     Note: If your function is not being put into a shared library then use SNESRegister() instead
49971c84c290SBarry Smith 
49981c84c290SBarry Smith .keywords: SNES, nonlinear, register
49991c84c290SBarry Smith 
50001c84c290SBarry Smith .seealso: SNESRegisterAll(), SNESRegisterDestroy()
50013cea93caSBarry Smith 
50027f6c08e0SMatthew Knepley   Level: advanced
50033cea93caSBarry Smith @*/
5004bdf89e91SBarry Smith PetscErrorCode  SNESRegister(const char sname[],PetscErrorCode (*function)(SNES))
5005b2002411SLois Curfman McInnes {
5006dfbe8321SBarry Smith   PetscErrorCode ierr;
5007b2002411SLois Curfman McInnes 
5008b2002411SLois Curfman McInnes   PetscFunctionBegin;
50091d36bdfdSBarry Smith   ierr = SNESInitializePackage();CHKERRQ(ierr);
5010a240a19fSJed Brown   ierr = PetscFunctionListAdd(&SNESList,sname,function);CHKERRQ(ierr);
5011b2002411SLois Curfman McInnes   PetscFunctionReturn(0);
5012b2002411SLois Curfman McInnes }
5013da9b6338SBarry Smith 
50147087cfbeSBarry Smith PetscErrorCode  SNESTestLocalMin(SNES snes)
5015da9b6338SBarry Smith {
5016dfbe8321SBarry Smith   PetscErrorCode ierr;
501777431f27SBarry Smith   PetscInt       N,i,j;
5018da9b6338SBarry Smith   Vec            u,uh,fh;
5019da9b6338SBarry Smith   PetscScalar    value;
5020da9b6338SBarry Smith   PetscReal      norm;
5021da9b6338SBarry Smith 
5022da9b6338SBarry Smith   PetscFunctionBegin;
5023da9b6338SBarry Smith   ierr = SNESGetSolution(snes,&u);CHKERRQ(ierr);
5024da9b6338SBarry Smith   ierr = VecDuplicate(u,&uh);CHKERRQ(ierr);
5025da9b6338SBarry Smith   ierr = VecDuplicate(u,&fh);CHKERRQ(ierr);
5026da9b6338SBarry Smith 
5027da9b6338SBarry Smith   /* currently only works for sequential */
502822d28d08SBarry Smith   ierr = PetscPrintf(PETSC_COMM_WORLD,"Testing FormFunction() for local min\n");CHKERRQ(ierr);
5029da9b6338SBarry Smith   ierr = VecGetSize(u,&N);CHKERRQ(ierr);
5030da9b6338SBarry Smith   for (i=0; i<N; i++) {
5031da9b6338SBarry Smith     ierr = VecCopy(u,uh);CHKERRQ(ierr);
503277431f27SBarry Smith     ierr = PetscPrintf(PETSC_COMM_WORLD,"i = %D\n",i);CHKERRQ(ierr);
5033da9b6338SBarry Smith     for (j=-10; j<11; j++) {
50348b49ba18SBarry Smith       value = PetscSign(j)*PetscExpReal(PetscAbs(j)-10.0);
5035da9b6338SBarry Smith       ierr  = VecSetValue(uh,i,value,ADD_VALUES);CHKERRQ(ierr);
50363ab0aad5SBarry Smith       ierr  = SNESComputeFunction(snes,uh,fh);CHKERRQ(ierr);
5037da9b6338SBarry Smith       ierr  = VecNorm(fh,NORM_2,&norm);CHKERRQ(ierr);
503877431f27SBarry Smith       ierr  = PetscPrintf(PETSC_COMM_WORLD,"       j norm %D %18.16e\n",j,norm);CHKERRQ(ierr);
5039da9b6338SBarry Smith       value = -value;
5040da9b6338SBarry Smith       ierr  = VecSetValue(uh,i,value,ADD_VALUES);CHKERRQ(ierr);
5041da9b6338SBarry Smith     }
5042da9b6338SBarry Smith   }
50436bf464f9SBarry Smith   ierr = VecDestroy(&uh);CHKERRQ(ierr);
50446bf464f9SBarry Smith   ierr = VecDestroy(&fh);CHKERRQ(ierr);
5045da9b6338SBarry Smith   PetscFunctionReturn(0);
5046da9b6338SBarry Smith }
504771f87433Sdalcinl 
504871f87433Sdalcinl /*@
5049fa9f3622SBarry Smith    SNESKSPSetUseEW - Sets SNES use Eisenstat-Walker method for
505071f87433Sdalcinl    computing relative tolerance for linear solvers within an inexact
505171f87433Sdalcinl    Newton method.
505271f87433Sdalcinl 
50533f9fe445SBarry Smith    Logically Collective on SNES
505471f87433Sdalcinl 
505571f87433Sdalcinl    Input Parameters:
505671f87433Sdalcinl +  snes - SNES context
505771f87433Sdalcinl -  flag - PETSC_TRUE or PETSC_FALSE
505871f87433Sdalcinl 
505964ba62caSBarry Smith     Options Database:
506064ba62caSBarry Smith +  -snes_ksp_ew - use Eisenstat-Walker method for determining linear system convergence
506164ba62caSBarry Smith .  -snes_ksp_ew_version ver - version of  Eisenstat-Walker method
506264ba62caSBarry Smith .  -snes_ksp_ew_rtol0 <rtol0> - Sets rtol0
506364ba62caSBarry Smith .  -snes_ksp_ew_rtolmax <rtolmax> - Sets rtolmax
506464ba62caSBarry Smith .  -snes_ksp_ew_gamma <gamma> - Sets gamma
506564ba62caSBarry Smith .  -snes_ksp_ew_alpha <alpha> - Sets alpha
506664ba62caSBarry Smith .  -snes_ksp_ew_alpha2 <alpha2> - Sets alpha2
506764ba62caSBarry Smith -  -snes_ksp_ew_threshold <threshold> - Sets threshold
506864ba62caSBarry Smith 
506971f87433Sdalcinl    Notes:
507071f87433Sdalcinl    Currently, the default is to use a constant relative tolerance for
507171f87433Sdalcinl    the inner linear solvers.  Alternatively, one can use the
507271f87433Sdalcinl    Eisenstat-Walker method, where the relative convergence tolerance
507371f87433Sdalcinl    is reset at each Newton iteration according progress of the nonlinear
507471f87433Sdalcinl    solver.
507571f87433Sdalcinl 
507671f87433Sdalcinl    Level: advanced
507771f87433Sdalcinl 
507871f87433Sdalcinl    Reference:
507971f87433Sdalcinl    S. C. Eisenstat and H. F. Walker, "Choosing the forcing terms in an
508071f87433Sdalcinl    inexact Newton method", SISC 17 (1), pp.16-32, 1996.
508171f87433Sdalcinl 
508271f87433Sdalcinl .keywords: SNES, KSP, Eisenstat, Walker, convergence, test, inexact, Newton
508371f87433Sdalcinl 
5084fa9f3622SBarry Smith .seealso: SNESKSPGetUseEW(), SNESKSPGetParametersEW(), SNESKSPSetParametersEW()
508571f87433Sdalcinl @*/
50867087cfbeSBarry Smith PetscErrorCode  SNESKSPSetUseEW(SNES snes,PetscBool flag)
508771f87433Sdalcinl {
508871f87433Sdalcinl   PetscFunctionBegin;
50890700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
5090acfcf0e5SJed Brown   PetscValidLogicalCollectiveBool(snes,flag,2);
509171f87433Sdalcinl   snes->ksp_ewconv = flag;
509271f87433Sdalcinl   PetscFunctionReturn(0);
509371f87433Sdalcinl }
509471f87433Sdalcinl 
509571f87433Sdalcinl /*@
5096fa9f3622SBarry Smith    SNESKSPGetUseEW - Gets if SNES is using Eisenstat-Walker method
509771f87433Sdalcinl    for computing relative tolerance for linear solvers within an
509871f87433Sdalcinl    inexact Newton method.
509971f87433Sdalcinl 
510071f87433Sdalcinl    Not Collective
510171f87433Sdalcinl 
510271f87433Sdalcinl    Input Parameter:
510371f87433Sdalcinl .  snes - SNES context
510471f87433Sdalcinl 
510571f87433Sdalcinl    Output Parameter:
510671f87433Sdalcinl .  flag - PETSC_TRUE or PETSC_FALSE
510771f87433Sdalcinl 
510871f87433Sdalcinl    Notes:
510971f87433Sdalcinl    Currently, the default is to use a constant relative tolerance for
511071f87433Sdalcinl    the inner linear solvers.  Alternatively, one can use the
511171f87433Sdalcinl    Eisenstat-Walker method, where the relative convergence tolerance
511271f87433Sdalcinl    is reset at each Newton iteration according progress of the nonlinear
511371f87433Sdalcinl    solver.
511471f87433Sdalcinl 
511571f87433Sdalcinl    Level: advanced
511671f87433Sdalcinl 
511771f87433Sdalcinl    Reference:
511871f87433Sdalcinl    S. C. Eisenstat and H. F. Walker, "Choosing the forcing terms in an
511971f87433Sdalcinl    inexact Newton method", SISC 17 (1), pp.16-32, 1996.
512071f87433Sdalcinl 
512171f87433Sdalcinl .keywords: SNES, KSP, Eisenstat, Walker, convergence, test, inexact, Newton
512271f87433Sdalcinl 
5123fa9f3622SBarry Smith .seealso: SNESKSPSetUseEW(), SNESKSPGetParametersEW(), SNESKSPSetParametersEW()
512471f87433Sdalcinl @*/
51257087cfbeSBarry Smith PetscErrorCode  SNESKSPGetUseEW(SNES snes, PetscBool  *flag)
512671f87433Sdalcinl {
512771f87433Sdalcinl   PetscFunctionBegin;
51280700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
512971f87433Sdalcinl   PetscValidPointer(flag,2);
513071f87433Sdalcinl   *flag = snes->ksp_ewconv;
513171f87433Sdalcinl   PetscFunctionReturn(0);
513271f87433Sdalcinl }
513371f87433Sdalcinl 
513471f87433Sdalcinl /*@
5135fa9f3622SBarry Smith    SNESKSPSetParametersEW - Sets parameters for Eisenstat-Walker
513671f87433Sdalcinl    convergence criteria for the linear solvers within an inexact
513771f87433Sdalcinl    Newton method.
513871f87433Sdalcinl 
51393f9fe445SBarry Smith    Logically Collective on SNES
514071f87433Sdalcinl 
514171f87433Sdalcinl    Input Parameters:
514271f87433Sdalcinl +    snes - SNES context
514371f87433Sdalcinl .    version - version 1, 2 (default is 2) or 3
514471f87433Sdalcinl .    rtol_0 - initial relative tolerance (0 <= rtol_0 < 1)
514571f87433Sdalcinl .    rtol_max - maximum relative tolerance (0 <= rtol_max < 1)
514671f87433Sdalcinl .    gamma - multiplicative factor for version 2 rtol computation
514771f87433Sdalcinl              (0 <= gamma2 <= 1)
514871f87433Sdalcinl .    alpha - power for version 2 rtol computation (1 < alpha <= 2)
514971f87433Sdalcinl .    alpha2 - power for safeguard
515071f87433Sdalcinl -    threshold - threshold for imposing safeguard (0 < threshold < 1)
515171f87433Sdalcinl 
515271f87433Sdalcinl    Note:
515371f87433Sdalcinl    Version 3 was contributed by Luis Chacon, June 2006.
515471f87433Sdalcinl 
515571f87433Sdalcinl    Use PETSC_DEFAULT to retain the default for any of the parameters.
515671f87433Sdalcinl 
515771f87433Sdalcinl    Level: advanced
515871f87433Sdalcinl 
515971f87433Sdalcinl    Reference:
516071f87433Sdalcinl    S. C. Eisenstat and H. F. Walker, "Choosing the forcing terms in an
516171f87433Sdalcinl    inexact Newton method", Utah State University Math. Stat. Dept. Res.
516271f87433Sdalcinl    Report 6/94/75, June, 1994, to appear in SIAM J. Sci. Comput.
516371f87433Sdalcinl 
516471f87433Sdalcinl .keywords: SNES, KSP, Eisenstat, Walker, set, parameters
516571f87433Sdalcinl 
5166fa9f3622SBarry Smith .seealso: SNESKSPSetUseEW(), SNESKSPGetUseEW(), SNESKSPGetParametersEW()
516771f87433Sdalcinl @*/
5168f5af7f23SKarl Rupp PetscErrorCode  SNESKSPSetParametersEW(SNES snes,PetscInt version,PetscReal rtol_0,PetscReal rtol_max,PetscReal gamma,PetscReal alpha,PetscReal alpha2,PetscReal threshold)
516971f87433Sdalcinl {
5170fa9f3622SBarry Smith   SNESKSPEW *kctx;
51715fd66863SKarl Rupp 
517271f87433Sdalcinl   PetscFunctionBegin;
51730700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
5174fa9f3622SBarry Smith   kctx = (SNESKSPEW*)snes->kspconvctx;
5175e32f2f54SBarry Smith   if (!kctx) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"No Eisenstat-Walker context existing");
5176c5eb9154SBarry Smith   PetscValidLogicalCollectiveInt(snes,version,2);
5177c5eb9154SBarry Smith   PetscValidLogicalCollectiveReal(snes,rtol_0,3);
5178c5eb9154SBarry Smith   PetscValidLogicalCollectiveReal(snes,rtol_max,4);
5179c5eb9154SBarry Smith   PetscValidLogicalCollectiveReal(snes,gamma,5);
5180c5eb9154SBarry Smith   PetscValidLogicalCollectiveReal(snes,alpha,6);
5181c5eb9154SBarry Smith   PetscValidLogicalCollectiveReal(snes,alpha2,7);
5182c5eb9154SBarry Smith   PetscValidLogicalCollectiveReal(snes,threshold,8);
518371f87433Sdalcinl 
518471f87433Sdalcinl   if (version != PETSC_DEFAULT)   kctx->version   = version;
518571f87433Sdalcinl   if (rtol_0 != PETSC_DEFAULT)    kctx->rtol_0    = rtol_0;
518671f87433Sdalcinl   if (rtol_max != PETSC_DEFAULT)  kctx->rtol_max  = rtol_max;
518771f87433Sdalcinl   if (gamma != PETSC_DEFAULT)     kctx->gamma     = gamma;
518871f87433Sdalcinl   if (alpha != PETSC_DEFAULT)     kctx->alpha     = alpha;
518971f87433Sdalcinl   if (alpha2 != PETSC_DEFAULT)    kctx->alpha2    = alpha2;
519071f87433Sdalcinl   if (threshold != PETSC_DEFAULT) kctx->threshold = threshold;
519171f87433Sdalcinl 
5192f23aa3ddSBarry Smith   if (kctx->version < 1 || kctx->version > 3) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Only versions 1, 2 and 3 are supported: %D",kctx->version);
519357622a8eSBarry Smith   if (kctx->rtol_0 < 0.0 || kctx->rtol_0 >= 1.0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"0.0 <= rtol_0 < 1.0: %g",(double)kctx->rtol_0);
519457622a8eSBarry Smith   if (kctx->rtol_max < 0.0 || kctx->rtol_max >= 1.0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"0.0 <= rtol_max (%g) < 1.0\n",(double)kctx->rtol_max);
519557622a8eSBarry Smith   if (kctx->gamma < 0.0 || kctx->gamma > 1.0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"0.0 <= gamma (%g) <= 1.0\n",(double)kctx->gamma);
519657622a8eSBarry Smith   if (kctx->alpha <= 1.0 || kctx->alpha > 2.0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"1.0 < alpha (%g) <= 2.0\n",(double)kctx->alpha);
519757622a8eSBarry Smith   if (kctx->threshold <= 0.0 || kctx->threshold >= 1.0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"0.0 < threshold (%g) < 1.0\n",(double)kctx->threshold);
519871f87433Sdalcinl   PetscFunctionReturn(0);
519971f87433Sdalcinl }
520071f87433Sdalcinl 
520171f87433Sdalcinl /*@
5202fa9f3622SBarry Smith    SNESKSPGetParametersEW - Gets parameters for Eisenstat-Walker
520371f87433Sdalcinl    convergence criteria for the linear solvers within an inexact
520471f87433Sdalcinl    Newton method.
520571f87433Sdalcinl 
520671f87433Sdalcinl    Not Collective
520771f87433Sdalcinl 
520871f87433Sdalcinl    Input Parameters:
520971f87433Sdalcinl      snes - SNES context
521071f87433Sdalcinl 
521171f87433Sdalcinl    Output Parameters:
521271f87433Sdalcinl +    version - version 1, 2 (default is 2) or 3
521371f87433Sdalcinl .    rtol_0 - initial relative tolerance (0 <= rtol_0 < 1)
521471f87433Sdalcinl .    rtol_max - maximum relative tolerance (0 <= rtol_max < 1)
5215bf388a1fSBarry Smith .    gamma - multiplicative factor for version 2 rtol computation (0 <= gamma2 <= 1)
521671f87433Sdalcinl .    alpha - power for version 2 rtol computation (1 < alpha <= 2)
521771f87433Sdalcinl .    alpha2 - power for safeguard
521871f87433Sdalcinl -    threshold - threshold for imposing safeguard (0 < threshold < 1)
521971f87433Sdalcinl 
522071f87433Sdalcinl    Level: advanced
522171f87433Sdalcinl 
522271f87433Sdalcinl .keywords: SNES, KSP, Eisenstat, Walker, get, parameters
522371f87433Sdalcinl 
5224fa9f3622SBarry Smith .seealso: SNESKSPSetUseEW(), SNESKSPGetUseEW(), SNESKSPSetParametersEW()
522571f87433Sdalcinl @*/
5226bf388a1fSBarry Smith PetscErrorCode  SNESKSPGetParametersEW(SNES snes,PetscInt *version,PetscReal *rtol_0,PetscReal *rtol_max,PetscReal *gamma,PetscReal *alpha,PetscReal *alpha2,PetscReal *threshold)
522771f87433Sdalcinl {
5228fa9f3622SBarry Smith   SNESKSPEW *kctx;
52295fd66863SKarl Rupp 
523071f87433Sdalcinl   PetscFunctionBegin;
52310700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
5232fa9f3622SBarry Smith   kctx = (SNESKSPEW*)snes->kspconvctx;
5233e32f2f54SBarry Smith   if (!kctx) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"No Eisenstat-Walker context existing");
523471f87433Sdalcinl   if (version)   *version   = kctx->version;
523571f87433Sdalcinl   if (rtol_0)    *rtol_0    = kctx->rtol_0;
523671f87433Sdalcinl   if (rtol_max)  *rtol_max  = kctx->rtol_max;
523771f87433Sdalcinl   if (gamma)     *gamma     = kctx->gamma;
523871f87433Sdalcinl   if (alpha)     *alpha     = kctx->alpha;
523971f87433Sdalcinl   if (alpha2)    *alpha2    = kctx->alpha2;
524071f87433Sdalcinl   if (threshold) *threshold = kctx->threshold;
524171f87433Sdalcinl   PetscFunctionReturn(0);
524271f87433Sdalcinl }
524371f87433Sdalcinl 
5244d5378b5fSDmitry Karpeev  PetscErrorCode KSPPreSolve_SNESEW(KSP ksp, Vec b, Vec x, SNES snes)
524571f87433Sdalcinl {
524671f87433Sdalcinl   PetscErrorCode ierr;
5247fa9f3622SBarry Smith   SNESKSPEW      *kctx = (SNESKSPEW*)snes->kspconvctx;
524871f87433Sdalcinl   PetscReal      rtol  = PETSC_DEFAULT,stol;
524971f87433Sdalcinl 
525071f87433Sdalcinl   PetscFunctionBegin;
5251d4211eb9SBarry Smith   if (!snes->ksp_ewconv) PetscFunctionReturn(0);
525230058271SDmitry Karpeev   if (!snes->iter) {
525330058271SDmitry Karpeev     rtol = kctx->rtol_0; /* first time in, so use the original user rtol */
525430058271SDmitry Karpeev     ierr = VecNorm(snes->vec_func,NORM_2,&kctx->norm_first);CHKERRQ(ierr);
525530058271SDmitry Karpeev   }
5256f5af7f23SKarl Rupp   else {
525771f87433Sdalcinl     if (kctx->version == 1) {
525871f87433Sdalcinl       rtol = (snes->norm - kctx->lresid_last)/kctx->norm_last;
525971f87433Sdalcinl       if (rtol < 0.0) rtol = -rtol;
526085ec1a3cSBarry Smith       stol = PetscPowReal(kctx->rtol_last,kctx->alpha2);
526171f87433Sdalcinl       if (stol > kctx->threshold) rtol = PetscMax(rtol,stol);
526271f87433Sdalcinl     } else if (kctx->version == 2) {
526385ec1a3cSBarry Smith       rtol = kctx->gamma * PetscPowReal(snes->norm/kctx->norm_last,kctx->alpha);
526485ec1a3cSBarry Smith       stol = kctx->gamma * PetscPowReal(kctx->rtol_last,kctx->alpha);
526571f87433Sdalcinl       if (stol > kctx->threshold) rtol = PetscMax(rtol,stol);
526671f87433Sdalcinl     } else if (kctx->version == 3) { /* contributed by Luis Chacon, June 2006. */
526785ec1a3cSBarry Smith       rtol = kctx->gamma * PetscPowReal(snes->norm/kctx->norm_last,kctx->alpha);
526871f87433Sdalcinl       /* safeguard: avoid sharp decrease of rtol */
526985ec1a3cSBarry Smith       stol = kctx->gamma*PetscPowReal(kctx->rtol_last,kctx->alpha);
527071f87433Sdalcinl       stol = PetscMax(rtol,stol);
527171f87433Sdalcinl       rtol = PetscMin(kctx->rtol_0,stol);
527271f87433Sdalcinl       /* safeguard: avoid oversolving */
527330058271SDmitry Karpeev       stol = kctx->gamma*(kctx->norm_first*snes->rtol)/snes->norm;
527471f87433Sdalcinl       stol = PetscMax(rtol,stol);
527571f87433Sdalcinl       rtol = PetscMin(kctx->rtol_0,stol);
5276e32f2f54SBarry Smith     } else SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Only versions 1, 2 or 3 are supported: %D",kctx->version);
527771f87433Sdalcinl   }
527871f87433Sdalcinl   /* safeguard: avoid rtol greater than one */
527971f87433Sdalcinl   rtol = PetscMin(rtol,kctx->rtol_max);
528071f87433Sdalcinl   ierr = KSPSetTolerances(ksp,rtol,PETSC_DEFAULT,PETSC_DEFAULT,PETSC_DEFAULT);CHKERRQ(ierr);
528157622a8eSBarry Smith   ierr = PetscInfo3(snes,"iter %D, Eisenstat-Walker (version %D) KSP rtol=%g\n",snes->iter,kctx->version,(double)rtol);CHKERRQ(ierr);
528271f87433Sdalcinl   PetscFunctionReturn(0);
528371f87433Sdalcinl }
528471f87433Sdalcinl 
5285d5378b5fSDmitry Karpeev PetscErrorCode KSPPostSolve_SNESEW(KSP ksp, Vec b, Vec x, SNES snes)
528671f87433Sdalcinl {
528771f87433Sdalcinl   PetscErrorCode ierr;
5288fa9f3622SBarry Smith   SNESKSPEW      *kctx = (SNESKSPEW*)snes->kspconvctx;
528971f87433Sdalcinl   PCSide         pcside;
529071f87433Sdalcinl   Vec            lres;
529171f87433Sdalcinl 
529271f87433Sdalcinl   PetscFunctionBegin;
5293d4211eb9SBarry Smith   if (!snes->ksp_ewconv) PetscFunctionReturn(0);
529471f87433Sdalcinl   ierr = KSPGetTolerances(ksp,&kctx->rtol_last,0,0,0);CHKERRQ(ierr);
529571dbe336SPeter Brune   kctx->norm_last = snes->norm;
529671f87433Sdalcinl   if (kctx->version == 1) {
52974f00ce20SMatthew G. Knepley     PC        pc;
52984f00ce20SMatthew G. Knepley     PetscBool isNone;
52994f00ce20SMatthew G. Knepley 
53004f00ce20SMatthew G. Knepley     ierr = KSPGetPC(ksp, &pc);CHKERRQ(ierr);
53014f00ce20SMatthew G. Knepley     ierr = PetscObjectTypeCompare((PetscObject) pc, PCNONE, &isNone);CHKERRQ(ierr);
5302b037da10SBarry Smith     ierr = KSPGetPCSide(ksp,&pcside);CHKERRQ(ierr);
53034f00ce20SMatthew G. Knepley      if (pcside == PC_RIGHT || isNone) { /* XXX Should we also test KSP_UNPRECONDITIONED_NORM ? */
530471f87433Sdalcinl       /* KSP residual is true linear residual */
530571f87433Sdalcinl       ierr = KSPGetResidualNorm(ksp,&kctx->lresid_last);CHKERRQ(ierr);
530671f87433Sdalcinl     } else {
530771f87433Sdalcinl       /* KSP residual is preconditioned residual */
530871f87433Sdalcinl       /* compute true linear residual norm */
530971f87433Sdalcinl       ierr = VecDuplicate(b,&lres);CHKERRQ(ierr);
531071f87433Sdalcinl       ierr = MatMult(snes->jacobian,x,lres);CHKERRQ(ierr);
531171f87433Sdalcinl       ierr = VecAYPX(lres,-1.0,b);CHKERRQ(ierr);
531271f87433Sdalcinl       ierr = VecNorm(lres,NORM_2,&kctx->lresid_last);CHKERRQ(ierr);
53136bf464f9SBarry Smith       ierr = VecDestroy(&lres);CHKERRQ(ierr);
531471f87433Sdalcinl     }
531571f87433Sdalcinl   }
531671f87433Sdalcinl   PetscFunctionReturn(0);
531771f87433Sdalcinl }
531871f87433Sdalcinl 
5319d4211eb9SBarry Smith /*@
5320d4211eb9SBarry Smith    SNESGetKSP - Returns the KSP context for a SNES solver.
5321d4211eb9SBarry Smith 
5322d4211eb9SBarry Smith    Not Collective, but if SNES object is parallel, then KSP object is parallel
5323d4211eb9SBarry Smith 
5324d4211eb9SBarry Smith    Input Parameter:
5325d4211eb9SBarry Smith .  snes - the SNES context
5326d4211eb9SBarry Smith 
5327d4211eb9SBarry Smith    Output Parameter:
5328d4211eb9SBarry Smith .  ksp - the KSP context
5329d4211eb9SBarry Smith 
5330d4211eb9SBarry Smith    Notes:
5331d4211eb9SBarry Smith    The user can then directly manipulate the KSP context to set various
5332d4211eb9SBarry Smith    options, etc.  Likewise, the user can then extract and manipulate the
5333d4211eb9SBarry Smith    PC contexts as well.
5334d4211eb9SBarry Smith 
5335d4211eb9SBarry Smith    Level: beginner
5336d4211eb9SBarry Smith 
5337d4211eb9SBarry Smith .keywords: SNES, nonlinear, get, KSP, context
5338d4211eb9SBarry Smith 
5339d4211eb9SBarry Smith .seealso: KSPGetPC(), SNESCreate(), KSPCreate(), SNESSetKSP()
5340d4211eb9SBarry Smith @*/
5341d4211eb9SBarry Smith PetscErrorCode  SNESGetKSP(SNES snes,KSP *ksp)
534271f87433Sdalcinl {
534371f87433Sdalcinl   PetscErrorCode ierr;
534471f87433Sdalcinl 
534571f87433Sdalcinl   PetscFunctionBegin;
5346d4211eb9SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
5347d4211eb9SBarry Smith   PetscValidPointer(ksp,2);
5348d4211eb9SBarry Smith 
5349d4211eb9SBarry Smith   if (!snes->ksp) {
5350a5c2985bSBarry Smith     PetscBool monitor = PETSC_FALSE;
5351a5c2985bSBarry Smith 
5352d4211eb9SBarry Smith     ierr = KSPCreate(PetscObjectComm((PetscObject)snes),&snes->ksp);CHKERRQ(ierr);
5353d4211eb9SBarry Smith     ierr = PetscObjectIncrementTabLevel((PetscObject)snes->ksp,(PetscObject)snes,1);CHKERRQ(ierr);
53543bb1ff40SBarry Smith     ierr = PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->ksp);CHKERRQ(ierr);
5355d4211eb9SBarry Smith 
5356d5378b5fSDmitry Karpeev     ierr = KSPSetPreSolve(snes->ksp,(PetscErrorCode (*)(KSP,Vec,Vec,void*))KSPPreSolve_SNESEW,snes);CHKERRQ(ierr);
5357d5378b5fSDmitry Karpeev     ierr = KSPSetPostSolve(snes->ksp,(PetscErrorCode (*)(KSP,Vec,Vec,void*))KSPPostSolve_SNESEW,snes);CHKERRQ(ierr);
5358a5c2985bSBarry Smith 
5359c5929fdfSBarry Smith     ierr = PetscOptionsGetBool(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-ksp_monitor_snes",&monitor,NULL);CHKERRQ(ierr);
5360a5c2985bSBarry Smith     if (monitor) {
5361a5c2985bSBarry Smith       ierr = KSPMonitorSet(snes->ksp,KSPMonitorSNES,snes,NULL);CHKERRQ(ierr);
5362a5c2985bSBarry Smith     }
5363e5f7ee39SBarry Smith     monitor = PETSC_FALSE;
5364c5929fdfSBarry Smith     ierr = PetscOptionsGetBool(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-ksp_monitor_snes_lg",&monitor,NULL);CHKERRQ(ierr);
5365e5f7ee39SBarry Smith     if (monitor) {
5366e5f7ee39SBarry Smith       PetscObject *objs;
53678b0b5a47SLisandro Dalcin       ierr = KSPMonitorSNESLGResidualNormCreate(PetscObjectComm((PetscObject)snes),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,600,600,&objs);CHKERRQ(ierr);
5368e5f7ee39SBarry Smith       objs[0] = (PetscObject) snes;
5369e5f7ee39SBarry Smith       ierr = KSPMonitorSet(snes->ksp,(PetscErrorCode (*)(KSP,PetscInt,PetscReal,void*))KSPMonitorSNESLGResidualNorm,objs,(PetscErrorCode (*)(void**))KSPMonitorSNESLGResidualNormDestroy);CHKERRQ(ierr);
5370e5f7ee39SBarry Smith     }
537116413a6aSBarry Smith     ierr = PetscObjectSetOptions((PetscObject)snes->ksp,((PetscObject)snes)->options);CHKERRQ(ierr);
5372d4211eb9SBarry Smith   }
5373d4211eb9SBarry Smith   *ksp = snes->ksp;
537471f87433Sdalcinl   PetscFunctionReturn(0);
537571f87433Sdalcinl }
53766c699258SBarry Smith 
5377d4211eb9SBarry Smith 
5378af0996ceSBarry Smith #include <petsc/private/dmimpl.h>
53796c699258SBarry Smith /*@
53802a808120SBarry Smith    SNESSetDM - Sets the DM that may be used by some nonlinear solvers or their underlying preconditioners
53816c699258SBarry Smith 
53823f9fe445SBarry Smith    Logically Collective on SNES
53836c699258SBarry Smith 
53846c699258SBarry Smith    Input Parameters:
53852a808120SBarry Smith +  snes - the nonlinear solver context
53862a808120SBarry Smith -  dm - the dm, cannot be NULL
53876c699258SBarry Smith 
5388e03a659cSJed Brown    Notes:
5389e03a659cSJed Brown    A DM can only be used for solving one problem at a time because information about the problem is stored on the DM,
5390e03a659cSJed Brown    even when not using interfaces like DMSNESSetFunction().  Use DMClone() to get a distinct DM when solving different
5391e03a659cSJed Brown    problems using the same function space.
5392e03a659cSJed Brown 
53936c699258SBarry Smith    Level: intermediate
53946c699258SBarry Smith 
53954c2026ceSFande Kong .seealso: SNESGetDM(), KSPSetDM(), KSPGetDM()
53966c699258SBarry Smith @*/
53977087cfbeSBarry Smith PetscErrorCode  SNESSetDM(SNES snes,DM dm)
53986c699258SBarry Smith {
53996c699258SBarry Smith   PetscErrorCode ierr;
5400345fed2cSBarry Smith   KSP            ksp;
5401942e3340SBarry Smith   DMSNES         sdm;
54026c699258SBarry Smith 
54036c699258SBarry Smith   PetscFunctionBegin;
54040700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
54052a808120SBarry Smith   PetscValidHeaderSpecific(dm,DM_CLASSID,2);
54062a808120SBarry Smith   ierr = PetscObjectReference((PetscObject)dm);CHKERRQ(ierr);
5407942e3340SBarry Smith   if (snes->dm) {               /* Move the DMSNES context over to the new DM unless the new DM already has one */
540851f4b3c7SToby Isaac     if (snes->dm->dmsnes && !dm->dmsnes) {
5409942e3340SBarry Smith       ierr = DMCopyDMSNES(snes->dm,dm);CHKERRQ(ierr);
5410942e3340SBarry Smith       ierr = DMGetDMSNES(snes->dm,&sdm);CHKERRQ(ierr);
5411f5af7f23SKarl Rupp       if (sdm->originaldm == snes->dm) sdm->originaldm = dm; /* Grant write privileges to the replacement DM */
54126cab3a1bSJed Brown     }
5413dc822a44SJed Brown     ierr = DMCoarsenHookRemove(snes->dm,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,snes);CHKERRQ(ierr);
54146bf464f9SBarry Smith     ierr = DMDestroy(&snes->dm);CHKERRQ(ierr);
54156cab3a1bSJed Brown   }
54166c699258SBarry Smith   snes->dm     = dm;
5417116d1032SJed Brown   snes->dmAuto = PETSC_FALSE;
5418f5af7f23SKarl Rupp 
5419345fed2cSBarry Smith   ierr = SNESGetKSP(snes,&ksp);CHKERRQ(ierr);
5420345fed2cSBarry Smith   ierr = KSPSetDM(ksp,dm);CHKERRQ(ierr);
5421f22f69f0SBarry Smith   ierr = KSPSetDMActive(ksp,PETSC_FALSE);CHKERRQ(ierr);
5422efd4aadfSBarry Smith   if (snes->npc) {
5423efd4aadfSBarry Smith     ierr = SNESSetDM(snes->npc, snes->dm);CHKERRQ(ierr);
5424efd4aadfSBarry Smith     ierr = SNESSetNPCSide(snes,snes->npcside);CHKERRQ(ierr);
54252c155ee1SBarry Smith   }
54266c699258SBarry Smith   PetscFunctionReturn(0);
54276c699258SBarry Smith }
54286c699258SBarry Smith 
54296c699258SBarry Smith /*@
54306c699258SBarry Smith    SNESGetDM - Gets the DM that may be used by some preconditioners
54316c699258SBarry Smith 
54323f9fe445SBarry Smith    Not Collective but DM obtained is parallel on SNES
54336c699258SBarry Smith 
54346c699258SBarry Smith    Input Parameter:
54356c699258SBarry Smith . snes - the preconditioner context
54366c699258SBarry Smith 
54376c699258SBarry Smith    Output Parameter:
54386c699258SBarry Smith .  dm - the dm
54396c699258SBarry Smith 
54406c699258SBarry Smith    Level: intermediate
54416c699258SBarry Smith 
54424c2026ceSFande Kong .seealso: SNESSetDM(), KSPSetDM(), KSPGetDM()
54436c699258SBarry Smith @*/
54447087cfbeSBarry Smith PetscErrorCode  SNESGetDM(SNES snes,DM *dm)
54456c699258SBarry Smith {
54466cab3a1bSJed Brown   PetscErrorCode ierr;
54476cab3a1bSJed Brown 
54486c699258SBarry Smith   PetscFunctionBegin;
54490700a824SBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
54506cab3a1bSJed Brown   if (!snes->dm) {
5451ce94432eSBarry Smith     ierr         = DMShellCreate(PetscObjectComm((PetscObject)snes),&snes->dm);CHKERRQ(ierr);
5452116d1032SJed Brown     snes->dmAuto = PETSC_TRUE;
54536cab3a1bSJed Brown   }
54546c699258SBarry Smith   *dm = snes->dm;
54556c699258SBarry Smith   PetscFunctionReturn(0);
54566c699258SBarry Smith }
54570807856dSBarry Smith 
545831823bd8SMatthew G Knepley /*@
5459be95d8f1SBarry Smith   SNESSetNPC - Sets the nonlinear preconditioner to be used.
546031823bd8SMatthew G Knepley 
546131823bd8SMatthew G Knepley   Collective on SNES
546231823bd8SMatthew G Knepley 
546331823bd8SMatthew G Knepley   Input Parameters:
546431823bd8SMatthew G Knepley + snes - iterative context obtained from SNESCreate()
546531823bd8SMatthew G Knepley - pc   - the preconditioner object
546631823bd8SMatthew G Knepley 
546731823bd8SMatthew G Knepley   Notes:
5468be95d8f1SBarry Smith   Use SNESGetNPC() to retrieve the preconditioner context (for example,
546931823bd8SMatthew G Knepley   to configure it using the API).
547031823bd8SMatthew G Knepley 
547131823bd8SMatthew G Knepley   Level: developer
547231823bd8SMatthew G Knepley 
547331823bd8SMatthew G Knepley .keywords: SNES, set, precondition
54743ad1a0b9SPatrick Farrell .seealso: SNESGetNPC(), SNESHasNPC()
547531823bd8SMatthew G Knepley @*/
5476be95d8f1SBarry Smith PetscErrorCode SNESSetNPC(SNES snes, SNES pc)
547731823bd8SMatthew G Knepley {
547831823bd8SMatthew G Knepley   PetscErrorCode ierr;
547931823bd8SMatthew G Knepley 
548031823bd8SMatthew G Knepley   PetscFunctionBegin;
548131823bd8SMatthew G Knepley   PetscValidHeaderSpecific(snes, SNES_CLASSID, 1);
548231823bd8SMatthew G Knepley   PetscValidHeaderSpecific(pc, SNES_CLASSID, 2);
548331823bd8SMatthew G Knepley   PetscCheckSameComm(snes, 1, pc, 2);
548431823bd8SMatthew G Knepley   ierr     = PetscObjectReference((PetscObject) pc);CHKERRQ(ierr);
5485efd4aadfSBarry Smith   ierr     = SNESDestroy(&snes->npc);CHKERRQ(ierr);
5486efd4aadfSBarry Smith   snes->npc = pc;
5487efd4aadfSBarry Smith   ierr     = PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->npc);CHKERRQ(ierr);
548831823bd8SMatthew G Knepley   PetscFunctionReturn(0);
548931823bd8SMatthew G Knepley }
549031823bd8SMatthew G Knepley 
549131823bd8SMatthew G Knepley /*@
5492be95d8f1SBarry Smith   SNESGetNPC - Creates a nonlinear preconditioning solver (SNES) to be used to precondition the nonlinear solver.
549331823bd8SMatthew G Knepley 
5494951fe5abSBarry Smith   Not Collective; but any changes to the obtained SNES object must be applied collectively
549531823bd8SMatthew G Knepley 
549631823bd8SMatthew G Knepley   Input Parameter:
549731823bd8SMatthew G Knepley . snes - iterative context obtained from SNESCreate()
549831823bd8SMatthew G Knepley 
549931823bd8SMatthew G Knepley   Output Parameter:
550031823bd8SMatthew G Knepley . pc - preconditioner context
550131823bd8SMatthew G Knepley 
550295452b02SPatrick Sanan   Notes:
550395452b02SPatrick Sanan     If a SNES was previously set with SNESSetNPC() then that SNES is returned.
5504be95d8f1SBarry Smith 
5505951fe5abSBarry Smith     The (preconditioner) SNES returned automatically inherits the same nonlinear function and Jacobian supplied to the original
5506951fe5abSBarry Smith     SNES during SNESSetUp()
5507951fe5abSBarry Smith 
550831823bd8SMatthew G Knepley   Level: developer
550931823bd8SMatthew G Knepley 
551031823bd8SMatthew G Knepley .keywords: SNES, get, preconditioner
5511951fe5abSBarry Smith .seealso: SNESSetNPC(), SNESHasNPC(), SNES, SNESCreate()
551231823bd8SMatthew G Knepley @*/
5513be95d8f1SBarry Smith PetscErrorCode SNESGetNPC(SNES snes, SNES *pc)
551431823bd8SMatthew G Knepley {
551531823bd8SMatthew G Knepley   PetscErrorCode ierr;
5516a64e098fSPeter Brune   const char     *optionsprefix;
551731823bd8SMatthew G Knepley 
551831823bd8SMatthew G Knepley   PetscFunctionBegin;
551931823bd8SMatthew G Knepley   PetscValidHeaderSpecific(snes, SNES_CLASSID, 1);
552031823bd8SMatthew G Knepley   PetscValidPointer(pc, 2);
5521efd4aadfSBarry Smith   if (!snes->npc) {
5522efd4aadfSBarry Smith     ierr = SNESCreate(PetscObjectComm((PetscObject)snes),&snes->npc);CHKERRQ(ierr);
5523efd4aadfSBarry Smith     ierr = PetscObjectIncrementTabLevel((PetscObject)snes->npc,(PetscObject)snes,1);CHKERRQ(ierr);
5524efd4aadfSBarry Smith     ierr = PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->npc);CHKERRQ(ierr);
5525a64e098fSPeter Brune     ierr = SNESGetOptionsPrefix(snes,&optionsprefix);CHKERRQ(ierr);
5526efd4aadfSBarry Smith     ierr = SNESSetOptionsPrefix(snes->npc,optionsprefix);CHKERRQ(ierr);
5527efd4aadfSBarry Smith     ierr = SNESAppendOptionsPrefix(snes->npc,"npc_");CHKERRQ(ierr);
5528efd4aadfSBarry Smith     ierr = SNESSetCountersReset(snes->npc,PETSC_FALSE);CHKERRQ(ierr);
552931823bd8SMatthew G Knepley   }
5530efd4aadfSBarry Smith   *pc = snes->npc;
553131823bd8SMatthew G Knepley   PetscFunctionReturn(0);
553231823bd8SMatthew G Knepley }
553331823bd8SMatthew G Knepley 
55343ad1a0b9SPatrick Farrell /*@
55353ad1a0b9SPatrick Farrell   SNESHasNPC - Returns whether a nonlinear preconditioner exists
55363ad1a0b9SPatrick Farrell 
55373ad1a0b9SPatrick Farrell   Not Collective
55383ad1a0b9SPatrick Farrell 
55393ad1a0b9SPatrick Farrell   Input Parameter:
55403ad1a0b9SPatrick Farrell . snes - iterative context obtained from SNESCreate()
55413ad1a0b9SPatrick Farrell 
55423ad1a0b9SPatrick Farrell   Output Parameter:
55433ad1a0b9SPatrick Farrell . has_npc - whether the SNES has an NPC or not
55443ad1a0b9SPatrick Farrell 
55453ad1a0b9SPatrick Farrell   Level: developer
55463ad1a0b9SPatrick Farrell 
55473ad1a0b9SPatrick Farrell .keywords: SNES, has, preconditioner
55483ad1a0b9SPatrick Farrell .seealso: SNESSetNPC(), SNESGetNPC()
55493ad1a0b9SPatrick Farrell @*/
55503ad1a0b9SPatrick Farrell PetscErrorCode SNESHasNPC(SNES snes, PetscBool *has_npc)
55513ad1a0b9SPatrick Farrell {
55523ad1a0b9SPatrick Farrell   PetscFunctionBegin;
55533ad1a0b9SPatrick Farrell   PetscValidHeaderSpecific(snes, SNES_CLASSID, 1);
5554efd4aadfSBarry Smith   *has_npc = (PetscBool) (snes->npc ? PETSC_TRUE : PETSC_FALSE);
55553ad1a0b9SPatrick Farrell   PetscFunctionReturn(0);
55563ad1a0b9SPatrick Farrell }
55573ad1a0b9SPatrick Farrell 
5558c40d0f55SPeter Brune /*@
5559be95d8f1SBarry Smith     SNESSetNPCSide - Sets the preconditioning side.
5560c40d0f55SPeter Brune 
5561c40d0f55SPeter Brune     Logically Collective on SNES
5562c40d0f55SPeter Brune 
5563c40d0f55SPeter Brune     Input Parameter:
5564c40d0f55SPeter Brune .   snes - iterative context obtained from SNESCreate()
5565c40d0f55SPeter Brune 
5566c40d0f55SPeter Brune     Output Parameter:
5567c40d0f55SPeter Brune .   side - the preconditioning side, where side is one of
5568c40d0f55SPeter Brune .vb
55692d547940SBarry Smith       PC_LEFT - left preconditioning
55702d547940SBarry Smith       PC_RIGHT - right preconditioning (default for most nonlinear solvers)
5571c40d0f55SPeter Brune .ve
5572c40d0f55SPeter Brune 
5573c40d0f55SPeter Brune     Options Database Keys:
5574c40d0f55SPeter Brune .   -snes_pc_side <right,left>
5575c40d0f55SPeter Brune 
557695452b02SPatrick Sanan     Notes:
557795452b02SPatrick Sanan     SNESNRICHARDSON and SNESNCG only support left preconditioning.
55782d547940SBarry Smith 
5579c40d0f55SPeter Brune     Level: intermediate
5580c40d0f55SPeter Brune 
5581c40d0f55SPeter Brune .keywords: SNES, set, right, left, side, preconditioner, flag
5582c40d0f55SPeter Brune 
5583be95d8f1SBarry Smith .seealso: SNESGetNPCSide(), KSPSetPCSide()
5584c40d0f55SPeter Brune @*/
5585be95d8f1SBarry Smith PetscErrorCode  SNESSetNPCSide(SNES snes,PCSide side)
5586c40d0f55SPeter Brune {
5587c40d0f55SPeter Brune   PetscFunctionBegin;
5588c40d0f55SPeter Brune   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
5589c40d0f55SPeter Brune   PetscValidLogicalCollectiveEnum(snes,side,2);
5590efd4aadfSBarry Smith   snes->npcside= side;
5591c40d0f55SPeter Brune   PetscFunctionReturn(0);
5592c40d0f55SPeter Brune }
5593c40d0f55SPeter Brune 
5594c40d0f55SPeter Brune /*@
5595be95d8f1SBarry Smith     SNESGetNPCSide - Gets the preconditioning side.
5596c40d0f55SPeter Brune 
5597c40d0f55SPeter Brune     Not Collective
5598c40d0f55SPeter Brune 
5599c40d0f55SPeter Brune     Input Parameter:
5600c40d0f55SPeter Brune .   snes - iterative context obtained from SNESCreate()
5601c40d0f55SPeter Brune 
5602c40d0f55SPeter Brune     Output Parameter:
5603c40d0f55SPeter Brune .   side - the preconditioning side, where side is one of
5604c40d0f55SPeter Brune .vb
56052d547940SBarry Smith       PC_LEFT - left preconditioning
56062d547940SBarry Smith       PC_RIGHT - right preconditioning (default for most nonlinear solvers)
5607c40d0f55SPeter Brune .ve
5608c40d0f55SPeter Brune 
5609c40d0f55SPeter Brune     Level: intermediate
5610c40d0f55SPeter Brune 
5611c40d0f55SPeter Brune .keywords: SNES, get, right, left, side, preconditioner, flag
5612c40d0f55SPeter Brune 
5613be95d8f1SBarry Smith .seealso: SNESSetNPCSide(), KSPGetPCSide()
5614c40d0f55SPeter Brune @*/
5615be95d8f1SBarry Smith PetscErrorCode  SNESGetNPCSide(SNES snes,PCSide *side)
5616c40d0f55SPeter Brune {
5617c40d0f55SPeter Brune   PetscFunctionBegin;
5618c40d0f55SPeter Brune   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
5619c40d0f55SPeter Brune   PetscValidPointer(side,2);
5620efd4aadfSBarry Smith   *side = snes->npcside;
5621c40d0f55SPeter Brune   PetscFunctionReturn(0);
5622c40d0f55SPeter Brune }
5623c40d0f55SPeter Brune 
56249e764e56SPeter Brune /*@
56257601faf0SJed Brown   SNESSetLineSearch - Sets the linesearch on the SNES instance.
56269e764e56SPeter Brune 
56279e764e56SPeter Brune   Collective on SNES
56289e764e56SPeter Brune 
56299e764e56SPeter Brune   Input Parameters:
56309e764e56SPeter Brune + snes - iterative context obtained from SNESCreate()
56319e764e56SPeter Brune - linesearch   - the linesearch object
56329e764e56SPeter Brune 
56339e764e56SPeter Brune   Notes:
56347601faf0SJed Brown   Use SNESGetLineSearch() to retrieve the preconditioner context (for example,
56359e764e56SPeter Brune   to configure it using the API).
56369e764e56SPeter Brune 
56379e764e56SPeter Brune   Level: developer
56389e764e56SPeter Brune 
56399e764e56SPeter Brune .keywords: SNES, set, linesearch
56407601faf0SJed Brown .seealso: SNESGetLineSearch()
56419e764e56SPeter Brune @*/
56427601faf0SJed Brown PetscErrorCode SNESSetLineSearch(SNES snes, SNESLineSearch linesearch)
56439e764e56SPeter Brune {
56449e764e56SPeter Brune   PetscErrorCode ierr;
56459e764e56SPeter Brune 
56469e764e56SPeter Brune   PetscFunctionBegin;
56479e764e56SPeter Brune   PetscValidHeaderSpecific(snes, SNES_CLASSID, 1);
5648f1c6b773SPeter Brune   PetscValidHeaderSpecific(linesearch, SNESLINESEARCH_CLASSID, 2);
56499e764e56SPeter Brune   PetscCheckSameComm(snes, 1, linesearch, 2);
56509e764e56SPeter Brune   ierr = PetscObjectReference((PetscObject) linesearch);CHKERRQ(ierr);
5651f1c6b773SPeter Brune   ierr = SNESLineSearchDestroy(&snes->linesearch);CHKERRQ(ierr);
5652f5af7f23SKarl Rupp 
56539e764e56SPeter Brune   snes->linesearch = linesearch;
5654f5af7f23SKarl Rupp 
56553bb1ff40SBarry Smith   ierr = PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->linesearch);CHKERRQ(ierr);
56569e764e56SPeter Brune   PetscFunctionReturn(0);
56579e764e56SPeter Brune }
56589e764e56SPeter Brune 
5659a34ceb2aSJed Brown /*@
56607601faf0SJed Brown   SNESGetLineSearch - Returns a pointer to the line search context set with SNESSetLineSearch()
56618141a3b9SPeter Brune   or creates a default line search instance associated with the SNES and returns it.
56629e764e56SPeter Brune 
56639e764e56SPeter Brune   Not Collective
56649e764e56SPeter Brune 
56659e764e56SPeter Brune   Input Parameter:
56669e764e56SPeter Brune . snes - iterative context obtained from SNESCreate()
56679e764e56SPeter Brune 
56689e764e56SPeter Brune   Output Parameter:
56699e764e56SPeter Brune . linesearch - linesearch context
56709e764e56SPeter Brune 
5671162e0bf5SPeter Brune   Level: beginner
56729e764e56SPeter Brune 
56739e764e56SPeter Brune .keywords: SNES, get, linesearch
5674162e0bf5SPeter Brune .seealso: SNESSetLineSearch(), SNESLineSearchCreate()
56759e764e56SPeter Brune @*/
56767601faf0SJed Brown PetscErrorCode SNESGetLineSearch(SNES snes, SNESLineSearch *linesearch)
56779e764e56SPeter Brune {
56789e764e56SPeter Brune   PetscErrorCode ierr;
56799e764e56SPeter Brune   const char     *optionsprefix;
56809e764e56SPeter Brune 
56819e764e56SPeter Brune   PetscFunctionBegin;
56829e764e56SPeter Brune   PetscValidHeaderSpecific(snes, SNES_CLASSID, 1);
56839e764e56SPeter Brune   PetscValidPointer(linesearch, 2);
56849e764e56SPeter Brune   if (!snes->linesearch) {
56859e764e56SPeter Brune     ierr = SNESGetOptionsPrefix(snes, &optionsprefix);CHKERRQ(ierr);
568682f516ccSBarry Smith     ierr = SNESLineSearchCreate(PetscObjectComm((PetscObject)snes), &snes->linesearch);CHKERRQ(ierr);
5687f1c6b773SPeter Brune     ierr = SNESLineSearchSetSNES(snes->linesearch, snes);CHKERRQ(ierr);
5688b1dca40bSPeter Brune     ierr = SNESLineSearchAppendOptionsPrefix(snes->linesearch, optionsprefix);CHKERRQ(ierr);
56899e764e56SPeter Brune     ierr = PetscObjectIncrementTabLevel((PetscObject) snes->linesearch, (PetscObject) snes, 1);CHKERRQ(ierr);
56903bb1ff40SBarry Smith     ierr = PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->linesearch);CHKERRQ(ierr);
56919e764e56SPeter Brune   }
56929e764e56SPeter Brune   *linesearch = snes->linesearch;
56939e764e56SPeter Brune   PetscFunctionReturn(0);
56949e764e56SPeter Brune }
56959e764e56SPeter Brune 
569669b4f73cSBarry Smith #if defined(PETSC_HAVE_MATLAB_ENGINE)
5697c6db04a5SJed Brown #include <mex.h>
569869b4f73cSBarry Smith 
56998f6e6473SBarry Smith typedef struct {char *funcname; mxArray *ctx;} SNESMatlabContext;
57008f6e6473SBarry Smith 
57010807856dSBarry Smith /*
5702bf388a1fSBarry Smith    SNESComputeFunction_Matlab - Calls the function that has been set with SNESSetFunctionMatlab().
57030807856dSBarry Smith 
57040807856dSBarry Smith    Collective on SNES
57050807856dSBarry Smith 
57060807856dSBarry Smith    Input Parameters:
57070807856dSBarry Smith +  snes - the SNES context
57080807856dSBarry Smith -  x - input vector
57090807856dSBarry Smith 
57100807856dSBarry Smith    Output Parameter:
57110807856dSBarry Smith .  y - function vector, as set by SNESSetFunction()
57120807856dSBarry Smith 
57130807856dSBarry Smith    Notes:
57140807856dSBarry Smith    SNESComputeFunction() is typically used within nonlinear solvers
57150807856dSBarry Smith    implementations, so most users would not generally call this routine
57160807856dSBarry Smith    themselves.
57170807856dSBarry Smith 
57180807856dSBarry Smith    Level: developer
57190807856dSBarry Smith 
57200807856dSBarry Smith .keywords: SNES, nonlinear, compute, function
57210807856dSBarry Smith 
57220807856dSBarry Smith .seealso: SNESSetFunction(), SNESGetFunction()
572361b2408cSBarry Smith */
57247087cfbeSBarry Smith PetscErrorCode  SNESComputeFunction_Matlab(SNES snes,Vec x,Vec y, void *ctx)
57250807856dSBarry Smith {
5726e650e774SBarry Smith   PetscErrorCode    ierr;
57278f6e6473SBarry Smith   SNESMatlabContext *sctx = (SNESMatlabContext*)ctx;
57288f6e6473SBarry Smith   int               nlhs  = 1,nrhs = 5;
57298f6e6473SBarry Smith   mxArray           *plhs[1],*prhs[5];
573091621f2eSBarry Smith   long long int     lx = 0,ly = 0,ls = 0;
5731e650e774SBarry Smith 
57320807856dSBarry Smith   PetscFunctionBegin;
57330807856dSBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
57340807856dSBarry Smith   PetscValidHeaderSpecific(x,VEC_CLASSID,2);
57350807856dSBarry Smith   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
57360807856dSBarry Smith   PetscCheckSameComm(snes,1,x,2);
57370807856dSBarry Smith   PetscCheckSameComm(snes,1,y,3);
57380807856dSBarry Smith 
57390807856dSBarry Smith   /* call Matlab function in ctx with arguments x and y */
5740e650e774SBarry Smith 
574191621f2eSBarry Smith   ierr    = PetscMemcpy(&ls,&snes,sizeof(snes));CHKERRQ(ierr);
5742e650e774SBarry Smith   ierr    = PetscMemcpy(&lx,&x,sizeof(x));CHKERRQ(ierr);
5743e650e774SBarry Smith   ierr    = PetscMemcpy(&ly,&y,sizeof(x));CHKERRQ(ierr);
574491621f2eSBarry Smith   prhs[0] = mxCreateDoubleScalar((double)ls);
574591621f2eSBarry Smith   prhs[1] = mxCreateDoubleScalar((double)lx);
574691621f2eSBarry Smith   prhs[2] = mxCreateDoubleScalar((double)ly);
57478f6e6473SBarry Smith   prhs[3] = mxCreateString(sctx->funcname);
57488f6e6473SBarry Smith   prhs[4] = sctx->ctx;
5749b807a863SBarry Smith   ierr    = mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscSNESComputeFunctionInternal");CHKERRQ(ierr);
5750e650e774SBarry Smith   ierr    = mxGetScalar(plhs[0]);CHKERRQ(ierr);
5751e650e774SBarry Smith   mxDestroyArray(prhs[0]);
5752e650e774SBarry Smith   mxDestroyArray(prhs[1]);
5753e650e774SBarry Smith   mxDestroyArray(prhs[2]);
57548f6e6473SBarry Smith   mxDestroyArray(prhs[3]);
5755e650e774SBarry Smith   mxDestroyArray(plhs[0]);
57560807856dSBarry Smith   PetscFunctionReturn(0);
57570807856dSBarry Smith }
57580807856dSBarry Smith 
575961b2408cSBarry Smith /*
57600807856dSBarry Smith    SNESSetFunctionMatlab - Sets the function evaluation routine and function
57610807856dSBarry Smith    vector for use by the SNES routines in solving systems of nonlinear
5762e3c5b3baSBarry Smith    equations from MATLAB. Here the function is a string containing the name of a MATLAB function
57630807856dSBarry Smith 
57640807856dSBarry Smith    Logically Collective on SNES
57650807856dSBarry Smith 
57660807856dSBarry Smith    Input Parameters:
57670807856dSBarry Smith +  snes - the SNES context
57680807856dSBarry Smith .  r - vector to store function value
5769f8b49ee9SBarry Smith -  f - function evaluation routine
57700807856dSBarry Smith 
57710807856dSBarry Smith    Notes:
57720807856dSBarry Smith    The Newton-like methods typically solve linear systems of the form
57730807856dSBarry Smith $      f'(x) x = -f(x),
57740807856dSBarry Smith    where f'(x) denotes the Jacobian matrix and f(x) is the function.
57750807856dSBarry Smith 
57760807856dSBarry Smith    Level: beginner
57770807856dSBarry Smith 
5778c5b75c40SBarry Smith    Developer Note:  This bleeds the allocated memory SNESMatlabContext *sctx;
5779c5b75c40SBarry Smith 
57800807856dSBarry Smith .keywords: SNES, nonlinear, set, function
57810807856dSBarry Smith 
57820807856dSBarry Smith .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetFunction()
578361b2408cSBarry Smith */
5784f8b49ee9SBarry Smith PetscErrorCode  SNESSetFunctionMatlab(SNES snes,Vec r,const char *f,mxArray *ctx)
57850807856dSBarry Smith {
57860807856dSBarry Smith   PetscErrorCode    ierr;
57878f6e6473SBarry Smith   SNESMatlabContext *sctx;
57880807856dSBarry Smith 
57890807856dSBarry Smith   PetscFunctionBegin;
57908f6e6473SBarry Smith   /* currently sctx is memory bleed */
5791854ce69bSBarry Smith   ierr = PetscNew(&sctx);CHKERRQ(ierr);
5792f8b49ee9SBarry Smith   ierr = PetscStrallocpy(f,&sctx->funcname);CHKERRQ(ierr);
57938f6e6473SBarry Smith   /*
57948f6e6473SBarry Smith      This should work, but it doesn't
57958f6e6473SBarry Smith   sctx->ctx = ctx;
57968f6e6473SBarry Smith   mexMakeArrayPersistent(sctx->ctx);
57978f6e6473SBarry Smith   */
57988f6e6473SBarry Smith   sctx->ctx = mxDuplicateArray(ctx);
57998f6e6473SBarry Smith   ierr      = SNESSetFunction(snes,r,SNESComputeFunction_Matlab,sctx);CHKERRQ(ierr);
58000807856dSBarry Smith   PetscFunctionReturn(0);
58010807856dSBarry Smith }
580269b4f73cSBarry Smith 
580361b2408cSBarry Smith /*
5804bf388a1fSBarry Smith    SNESComputeJacobian_Matlab - Calls the function that has been set with SNESSetJacobianMatlab().
580561b2408cSBarry Smith 
580661b2408cSBarry Smith    Collective on SNES
580761b2408cSBarry Smith 
580861b2408cSBarry Smith    Input Parameters:
580961b2408cSBarry Smith +  snes - the SNES context
581061b2408cSBarry Smith .  x - input vector
581161b2408cSBarry Smith .  A, B - the matrices
581261b2408cSBarry Smith -  ctx - user context
581361b2408cSBarry Smith 
581461b2408cSBarry Smith    Level: developer
581561b2408cSBarry Smith 
581661b2408cSBarry Smith .keywords: SNES, nonlinear, compute, function
581761b2408cSBarry Smith 
581861b2408cSBarry Smith .seealso: SNESSetFunction(), SNESGetFunction()
581961b2408cSBarry Smith @*/
5820f3229a78SSatish Balay PetscErrorCode  SNESComputeJacobian_Matlab(SNES snes,Vec x,Mat A,Mat B,void *ctx)
582161b2408cSBarry Smith {
582261b2408cSBarry Smith   PetscErrorCode    ierr;
582361b2408cSBarry Smith   SNESMatlabContext *sctx = (SNESMatlabContext*)ctx;
582461b2408cSBarry Smith   int               nlhs  = 2,nrhs = 6;
582561b2408cSBarry Smith   mxArray           *plhs[2],*prhs[6];
582661b2408cSBarry Smith   long long int     lx = 0,lA = 0,ls = 0, lB = 0;
582761b2408cSBarry Smith 
582861b2408cSBarry Smith   PetscFunctionBegin;
582961b2408cSBarry Smith   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
583061b2408cSBarry Smith   PetscValidHeaderSpecific(x,VEC_CLASSID,2);
583161b2408cSBarry Smith 
583261b2408cSBarry Smith   /* call Matlab function in ctx with arguments x and y */
583361b2408cSBarry Smith 
583461b2408cSBarry Smith   ierr    = PetscMemcpy(&ls,&snes,sizeof(snes));CHKERRQ(ierr);
583561b2408cSBarry Smith   ierr    = PetscMemcpy(&lx,&x,sizeof(x));CHKERRQ(ierr);
583661b2408cSBarry Smith   ierr    = PetscMemcpy(&lA,A,sizeof(x));CHKERRQ(ierr);
583761b2408cSBarry Smith   ierr    = PetscMemcpy(&lB,B,sizeof(x));CHKERRQ(ierr);
583861b2408cSBarry Smith   prhs[0] = mxCreateDoubleScalar((double)ls);
583961b2408cSBarry Smith   prhs[1] = mxCreateDoubleScalar((double)lx);
584061b2408cSBarry Smith   prhs[2] = mxCreateDoubleScalar((double)lA);
584161b2408cSBarry Smith   prhs[3] = mxCreateDoubleScalar((double)lB);
584261b2408cSBarry Smith   prhs[4] = mxCreateString(sctx->funcname);
584361b2408cSBarry Smith   prhs[5] = sctx->ctx;
5844b807a863SBarry Smith   ierr    = mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscSNESComputeJacobianInternal");CHKERRQ(ierr);
584561b2408cSBarry Smith   ierr    = mxGetScalar(plhs[0]);CHKERRQ(ierr);
584661b2408cSBarry Smith   mxDestroyArray(prhs[0]);
584761b2408cSBarry Smith   mxDestroyArray(prhs[1]);
584861b2408cSBarry Smith   mxDestroyArray(prhs[2]);
584961b2408cSBarry Smith   mxDestroyArray(prhs[3]);
585061b2408cSBarry Smith   mxDestroyArray(prhs[4]);
585161b2408cSBarry Smith   mxDestroyArray(plhs[0]);
585261b2408cSBarry Smith   mxDestroyArray(plhs[1]);
585361b2408cSBarry Smith   PetscFunctionReturn(0);
585461b2408cSBarry Smith }
585561b2408cSBarry Smith 
585661b2408cSBarry Smith /*
585761b2408cSBarry Smith    SNESSetJacobianMatlab - Sets the Jacobian function evaluation routine and two empty Jacobian matrices
585861b2408cSBarry Smith    vector for use by the SNES routines in solving systems of nonlinear
5859e3c5b3baSBarry Smith    equations from MATLAB. Here the function is a string containing the name of a MATLAB function
586061b2408cSBarry Smith 
586161b2408cSBarry Smith    Logically Collective on SNES
586261b2408cSBarry Smith 
586361b2408cSBarry Smith    Input Parameters:
586461b2408cSBarry Smith +  snes - the SNES context
586561b2408cSBarry Smith .  A,B - Jacobian matrices
5866f8b49ee9SBarry Smith .  J - function evaluation routine
586761b2408cSBarry Smith -  ctx - user context
586861b2408cSBarry Smith 
586961b2408cSBarry Smith    Level: developer
587061b2408cSBarry Smith 
5871c5b75c40SBarry Smith    Developer Note:  This bleeds the allocated memory SNESMatlabContext *sctx;
5872c5b75c40SBarry Smith 
587361b2408cSBarry Smith .keywords: SNES, nonlinear, set, function
587461b2408cSBarry Smith 
5875f8b49ee9SBarry Smith .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetFunction(), J
587661b2408cSBarry Smith */
5877f8b49ee9SBarry Smith PetscErrorCode  SNESSetJacobianMatlab(SNES snes,Mat A,Mat B,const char *J,mxArray *ctx)
587861b2408cSBarry Smith {
587961b2408cSBarry Smith   PetscErrorCode    ierr;
588061b2408cSBarry Smith   SNESMatlabContext *sctx;
588161b2408cSBarry Smith 
588261b2408cSBarry Smith   PetscFunctionBegin;
588361b2408cSBarry Smith   /* currently sctx is memory bleed */
5884854ce69bSBarry Smith   ierr = PetscNew(&sctx);CHKERRQ(ierr);
5885f8b49ee9SBarry Smith   ierr = PetscStrallocpy(J,&sctx->funcname);CHKERRQ(ierr);
588661b2408cSBarry Smith   /*
588761b2408cSBarry Smith      This should work, but it doesn't
588861b2408cSBarry Smith   sctx->ctx = ctx;
588961b2408cSBarry Smith   mexMakeArrayPersistent(sctx->ctx);
589061b2408cSBarry Smith   */
589161b2408cSBarry Smith   sctx->ctx = mxDuplicateArray(ctx);
589261b2408cSBarry Smith   ierr      = SNESSetJacobian(snes,A,B,SNESComputeJacobian_Matlab,sctx);CHKERRQ(ierr);
589361b2408cSBarry Smith   PetscFunctionReturn(0);
589461b2408cSBarry Smith }
589569b4f73cSBarry Smith 
5896f9eb7ae2SShri Abhyankar /*
5897f9eb7ae2SShri Abhyankar    SNESMonitor_Matlab - Calls the function that has been set with SNESMonitorSetMatlab().
5898f9eb7ae2SShri Abhyankar 
5899f9eb7ae2SShri Abhyankar    Collective on SNES
5900f9eb7ae2SShri Abhyankar 
5901f9eb7ae2SShri Abhyankar .seealso: SNESSetFunction(), SNESGetFunction()
5902f9eb7ae2SShri Abhyankar @*/
59037087cfbeSBarry Smith PetscErrorCode  SNESMonitor_Matlab(SNES snes,PetscInt it, PetscReal fnorm, void *ctx)
5904f9eb7ae2SShri Abhyankar {
5905f9eb7ae2SShri Abhyankar   PetscErrorCode    ierr;
590648f37e70SShri Abhyankar   SNESMatlabContext *sctx = (SNESMatlabContext*)ctx;
5907f9eb7ae2SShri Abhyankar   int               nlhs  = 1,nrhs = 6;
5908f9eb7ae2SShri Abhyankar   mxArray           *plhs[1],*prhs[6];
5909f9eb7ae2SShri Abhyankar   long long int     lx = 0,ls = 0;
5910f9eb7ae2SShri Abhyankar   Vec               x  = snes->vec_sol;
5911f9eb7ae2SShri Abhyankar 
5912f9eb7ae2SShri Abhyankar   PetscFunctionBegin;
5913f9eb7ae2SShri Abhyankar   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
5914f9eb7ae2SShri Abhyankar 
5915f9eb7ae2SShri Abhyankar   ierr    = PetscMemcpy(&ls,&snes,sizeof(snes));CHKERRQ(ierr);
5916f9eb7ae2SShri Abhyankar   ierr    = PetscMemcpy(&lx,&x,sizeof(x));CHKERRQ(ierr);
5917f9eb7ae2SShri Abhyankar   prhs[0] = mxCreateDoubleScalar((double)ls);
5918f9eb7ae2SShri Abhyankar   prhs[1] = mxCreateDoubleScalar((double)it);
5919f9eb7ae2SShri Abhyankar   prhs[2] = mxCreateDoubleScalar((double)fnorm);
5920f9eb7ae2SShri Abhyankar   prhs[3] = mxCreateDoubleScalar((double)lx);
5921f9eb7ae2SShri Abhyankar   prhs[4] = mxCreateString(sctx->funcname);
5922f9eb7ae2SShri Abhyankar   prhs[5] = sctx->ctx;
5923f9eb7ae2SShri Abhyankar   ierr    = mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscSNESMonitorInternal");CHKERRQ(ierr);
5924f9eb7ae2SShri Abhyankar   ierr    = mxGetScalar(plhs[0]);CHKERRQ(ierr);
5925f9eb7ae2SShri Abhyankar   mxDestroyArray(prhs[0]);
5926f9eb7ae2SShri Abhyankar   mxDestroyArray(prhs[1]);
5927f9eb7ae2SShri Abhyankar   mxDestroyArray(prhs[2]);
5928f9eb7ae2SShri Abhyankar   mxDestroyArray(prhs[3]);
5929f9eb7ae2SShri Abhyankar   mxDestroyArray(prhs[4]);
5930f9eb7ae2SShri Abhyankar   mxDestroyArray(plhs[0]);
5931f9eb7ae2SShri Abhyankar   PetscFunctionReturn(0);
5932f9eb7ae2SShri Abhyankar }
5933f9eb7ae2SShri Abhyankar 
5934f9eb7ae2SShri Abhyankar /*
5935e3c5b3baSBarry Smith    SNESMonitorSetMatlab - Sets the monitor function from MATLAB
5936f9eb7ae2SShri Abhyankar 
5937f9eb7ae2SShri Abhyankar    Level: developer
5938f9eb7ae2SShri Abhyankar 
5939c5b75c40SBarry Smith    Developer Note:  This bleeds the allocated memory SNESMatlabContext *sctx;
5940c5b75c40SBarry Smith 
5941f9eb7ae2SShri Abhyankar .keywords: SNES, nonlinear, set, function
5942f9eb7ae2SShri Abhyankar 
5943f9eb7ae2SShri Abhyankar .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetFunction()
5944f9eb7ae2SShri Abhyankar */
59456e4dcb14SBarry Smith PetscErrorCode  SNESMonitorSetMatlab(SNES snes,const char *f,mxArray *ctx)
5946f9eb7ae2SShri Abhyankar {
5947f9eb7ae2SShri Abhyankar   PetscErrorCode    ierr;
5948f9eb7ae2SShri Abhyankar   SNESMatlabContext *sctx;
5949f9eb7ae2SShri Abhyankar 
5950f9eb7ae2SShri Abhyankar   PetscFunctionBegin;
5951f9eb7ae2SShri Abhyankar   /* currently sctx is memory bleed */
5952854ce69bSBarry Smith   ierr = PetscNew(&sctx);CHKERRQ(ierr);
59536e4dcb14SBarry Smith   ierr = PetscStrallocpy(f,&sctx->funcname);CHKERRQ(ierr);
5954f9eb7ae2SShri Abhyankar   /*
5955f9eb7ae2SShri Abhyankar      This should work, but it doesn't
5956f9eb7ae2SShri Abhyankar   sctx->ctx = ctx;
5957f9eb7ae2SShri Abhyankar   mexMakeArrayPersistent(sctx->ctx);
5958f9eb7ae2SShri Abhyankar   */
5959f9eb7ae2SShri Abhyankar   sctx->ctx = mxDuplicateArray(ctx);
59600298fd71SBarry Smith   ierr      = SNESMonitorSet(snes,SNESMonitor_Matlab,sctx,NULL);CHKERRQ(ierr);
5961f9eb7ae2SShri Abhyankar   PetscFunctionReturn(0);
5962f9eb7ae2SShri Abhyankar }
5963f9eb7ae2SShri Abhyankar 
596469b4f73cSBarry Smith #endif
5965