1 #include <petsc/private/snesimpl.h> /*I "petscsnes.h" I*/ 2 #include <petscdmshell.h> 3 #include <petscdraw.h> 4 #include <petscds.h> 5 #include <petscdmadaptor.h> 6 #include <petscconvest.h> 7 8 PetscBool SNESRegisterAllCalled = PETSC_FALSE; 9 PetscFunctionList SNESList = NULL; 10 11 /* Logging support */ 12 PetscClassId SNES_CLASSID, DMSNES_CLASSID; 13 PetscLogEvent SNES_Solve, SNES_Setup, SNES_FunctionEval, SNES_JacobianEval, SNES_NGSEval, SNES_NGSFuncEval, SNES_NPCSolve, SNES_ObjectiveEval; 14 15 /*@ 16 SNESSetErrorIfNotConverged - Causes SNESSolve() to generate an error if the solver has not converged. 17 18 Logically Collective on SNES 19 20 Input Parameters: 21 + snes - iterative context obtained from SNESCreate() 22 - flg - PETSC_TRUE indicates you want the error generated 23 24 Options database keys: 25 . -snes_error_if_not_converged <true,false> - cause an immediate error condition and stop the program if the solver does not converge 26 27 Level: intermediate 28 29 Notes: 30 Normally PETSc continues if a linear solver fails to converge, you can call SNESGetConvergedReason() after a SNESSolve() 31 to determine if it has converged. 32 33 .seealso: `SNESGetErrorIfNotConverged()`, `KSPGetErrorIfNotConverged()`, `KSPSetErrorIfNotConverged()` 34 @*/ 35 PetscErrorCode SNESSetErrorIfNotConverged(SNES snes,PetscBool flg) 36 { 37 PetscFunctionBegin; 38 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 39 PetscValidLogicalCollectiveBool(snes,flg,2); 40 snes->errorifnotconverged = flg; 41 PetscFunctionReturn(0); 42 } 43 44 /*@ 45 SNESGetErrorIfNotConverged - Will SNESSolve() generate an error if the solver does not converge? 46 47 Not Collective 48 49 Input Parameter: 50 . snes - iterative context obtained from SNESCreate() 51 52 Output Parameter: 53 . flag - PETSC_TRUE if it will generate an error, else PETSC_FALSE 54 55 Level: intermediate 56 57 .seealso: `SNESSetErrorIfNotConverged()`, `KSPGetErrorIfNotConverged()`, `KSPSetErrorIfNotConverged()` 58 @*/ 59 PetscErrorCode SNESGetErrorIfNotConverged(SNES snes,PetscBool *flag) 60 { 61 PetscFunctionBegin; 62 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 63 PetscValidBoolPointer(flag,2); 64 *flag = snes->errorifnotconverged; 65 PetscFunctionReturn(0); 66 } 67 68 /*@ 69 SNESSetAlwaysComputesFinalResidual - does the SNES always compute the residual at the final solution? 70 71 Logically Collective on SNES 72 73 Input Parameters: 74 + snes - the shell SNES 75 - flg - is the residual computed? 76 77 Level: advanced 78 79 .seealso: `SNESGetAlwaysComputesFinalResidual()` 80 @*/ 81 PetscErrorCode SNESSetAlwaysComputesFinalResidual(SNES snes, PetscBool flg) 82 { 83 PetscFunctionBegin; 84 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 85 snes->alwayscomputesfinalresidual = flg; 86 PetscFunctionReturn(0); 87 } 88 89 /*@ 90 SNESGetAlwaysComputesFinalResidual - does the SNES always compute the residual at the final solution? 91 92 Logically Collective on SNES 93 94 Input Parameter: 95 . snes - the shell SNES 96 97 Output Parameter: 98 . flg - is the residual computed? 99 100 Level: advanced 101 102 .seealso: `SNESSetAlwaysComputesFinalResidual()` 103 @*/ 104 PetscErrorCode SNESGetAlwaysComputesFinalResidual(SNES snes, PetscBool *flg) 105 { 106 PetscFunctionBegin; 107 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 108 *flg = snes->alwayscomputesfinalresidual; 109 PetscFunctionReturn(0); 110 } 111 112 /*@ 113 SNESSetFunctionDomainError - tells SNES that the input vector to your SNESFunction is not 114 in the functions domain. For example, a step with negative pressure. 115 116 Logically Collective on SNES 117 118 Input Parameters: 119 . snes - the SNES context 120 121 Level: advanced 122 123 Note: 124 You can direct `SNES` to avoid certain steps by using `SNESVISetVariableBounds()`, `SNESVISetComputeVariableBounds()` or 125 `SNESLineSearchSetPreCheck()`, `SNESLineSearchSetPostCheck()` 126 127 .seealso: `SNESCreate()`, `SNESSetFunction()`, `SNESFunction`, `SNESSetJacobianDomainError()`, `SNESVISetVariableBounds()`, 128 `SNESVISetComputeVariableBounds()`, `SNESLineSearchSetPreCheck()`, `SNESLineSearchSetPostCheck()` 129 @*/ 130 PetscErrorCode SNESSetFunctionDomainError(SNES snes) 131 { 132 PetscFunctionBegin; 133 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 134 PetscCheck(!snes->errorifnotconverged,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"User code indicates input vector is not in the function domain"); 135 snes->domainerror = PETSC_TRUE; 136 PetscFunctionReturn(0); 137 } 138 139 /*@ 140 SNESSetJacobianDomainError - tells SNES that computeJacobian does not make sense at the proposed step. For example there is a negative element transformation. 141 142 Logically Collective on SNES 143 144 Input Parameters: 145 . snes - the SNES context 146 147 Level: advanced 148 149 Note: 150 You can direct `SNES` to avoid certain steps by using `SNESVISetVariableBounds()`, `SNESVISetComputeVariableBounds()` or 151 `SNESLineSearchSetPreCheck()`, `SNESLineSearchSetPostCheck()` 152 153 .seealso: `SNESCreate()`, `SNESSetFunction()`, `SNESFunction()`, `SNESSetFunctionDomainError()`, `SNESVISetVariableBounds()`, 154 `SNESVISetComputeVariableBounds()`, `SNESLineSearchSetPreCheck()`, `SNESLineSearchSetPostCheck()` 155 @*/ 156 PetscErrorCode SNESSetJacobianDomainError(SNES snes) 157 { 158 PetscFunctionBegin; 159 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 160 PetscCheck(!snes->errorifnotconverged,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"User code indicates computeJacobian does not make sense"); 161 snes->jacobiandomainerror = PETSC_TRUE; 162 PetscFunctionReturn(0); 163 } 164 165 /*@ 166 SNESSetCheckJacobianDomainError - if or not to check jacobian domain error after each Jacobian evaluation. By default, we check Jacobian domain error 167 in the debug mode, and do not check it in the optimized mode. 168 169 Logically Collective on SNES 170 171 Input Parameters: 172 + snes - the SNES context 173 - flg - indicates if or not to check jacobian domain error after each Jacobian evaluation 174 175 Level: advanced 176 177 .seealso: `SNESCreate()`, `SNESSetFunction()`, `SNESFunction()`, `SNESSetFunctionDomainError()`, `SNESGetCheckJacobianDomainError()` 178 @*/ 179 PetscErrorCode SNESSetCheckJacobianDomainError(SNES snes, PetscBool flg) 180 { 181 PetscFunctionBegin; 182 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 183 snes->checkjacdomainerror = flg; 184 PetscFunctionReturn(0); 185 } 186 187 /*@ 188 SNESGetCheckJacobianDomainError - Get an indicator whether or not we are checking Jacobian domain errors after each Jacobian evaluation. 189 190 Logically Collective on SNES 191 192 Input Parameters: 193 . snes - the SNES context 194 195 Output Parameters: 196 . flg - PETSC_FALSE indicates that we don't check jacobian domain errors after each Jacobian evaluation 197 198 Level: advanced 199 200 .seealso: `SNESCreate()`, `SNESSetFunction()`, `SNESFunction()`, `SNESSetFunctionDomainError()`, `SNESSetCheckJacobianDomainError()` 201 @*/ 202 PetscErrorCode SNESGetCheckJacobianDomainError(SNES snes, PetscBool *flg) 203 { 204 PetscFunctionBegin; 205 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 206 PetscValidBoolPointer(flg,2); 207 *flg = snes->checkjacdomainerror; 208 PetscFunctionReturn(0); 209 } 210 211 /*@ 212 SNESGetFunctionDomainError - Gets the status of the domain error after a call to SNESComputeFunction; 213 214 Logically Collective on SNES 215 216 Input Parameters: 217 . snes - the SNES context 218 219 Output Parameters: 220 . domainerror - Set to PETSC_TRUE if there's a domain error; PETSC_FALSE otherwise. 221 222 Level: advanced 223 224 .seealso: `SNESSetFunctionDomainError()`, `SNESComputeFunction()` 225 @*/ 226 PetscErrorCode SNESGetFunctionDomainError(SNES snes, PetscBool *domainerror) 227 { 228 PetscFunctionBegin; 229 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 230 PetscValidBoolPointer(domainerror,2); 231 *domainerror = snes->domainerror; 232 PetscFunctionReturn(0); 233 } 234 235 /*@ 236 SNESGetJacobianDomainError - Gets the status of the Jacobian domain error after a call to SNESComputeJacobian; 237 238 Logically Collective on SNES 239 240 Input Parameters: 241 . snes - the SNES context 242 243 Output Parameters: 244 . domainerror - Set to PETSC_TRUE if there's a jacobian domain error; PETSC_FALSE otherwise. 245 246 Level: advanced 247 248 .seealso: `SNESSetFunctionDomainError()`, `SNESComputeFunction()`, `SNESGetFunctionDomainError()` 249 @*/ 250 PetscErrorCode SNESGetJacobianDomainError(SNES snes, PetscBool *domainerror) 251 { 252 PetscFunctionBegin; 253 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 254 PetscValidBoolPointer(domainerror,2); 255 *domainerror = snes->jacobiandomainerror; 256 PetscFunctionReturn(0); 257 } 258 259 /*@C 260 SNESLoad - Loads a SNES that has been stored in binary with SNESView(). 261 262 Collective on PetscViewer 263 264 Input Parameters: 265 + newdm - the newly loaded SNES, this needs to have been created with SNESCreate() or 266 some related function before a call to SNESLoad(). 267 - viewer - binary file viewer, obtained from PetscViewerBinaryOpen() 268 269 Level: intermediate 270 271 Notes: 272 The type is determined by the data in the file, any type set into the SNES before this call is ignored. 273 274 Notes for advanced users: 275 Most users should not need to know the details of the binary storage 276 format, since SNESLoad() and TSView() completely hide these details. 277 But for anyone who's interested, the standard binary matrix storage 278 format is 279 .vb 280 has not yet been determined 281 .ve 282 283 .seealso: `PetscViewerBinaryOpen()`, `SNESView()`, `MatLoad()`, `VecLoad()` 284 @*/ 285 PetscErrorCode SNESLoad(SNES snes, PetscViewer viewer) 286 { 287 PetscBool isbinary; 288 PetscInt classid; 289 char type[256]; 290 KSP ksp; 291 DM dm; 292 DMSNES dmsnes; 293 294 PetscFunctionBegin; 295 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 296 PetscValidHeaderSpecific(viewer,PETSC_VIEWER_CLASSID,2); 297 PetscCall(PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary)); 298 PetscCheck(isbinary,PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Invalid viewer; open viewer with PetscViewerBinaryOpen()"); 299 300 PetscCall(PetscViewerBinaryRead(viewer,&classid,1,NULL,PETSC_INT)); 301 PetscCheck(classid == SNES_FILE_CLASSID,PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_WRONG,"Not SNES next in file"); 302 PetscCall(PetscViewerBinaryRead(viewer,type,256,NULL,PETSC_CHAR)); 303 PetscCall(SNESSetType(snes, type)); 304 PetscTryTypeMethod(snes,load,viewer); 305 PetscCall(SNESGetDM(snes,&dm)); 306 PetscCall(DMGetDMSNES(dm,&dmsnes)); 307 PetscCall(DMSNESLoad(dmsnes,viewer)); 308 PetscCall(SNESGetKSP(snes,&ksp)); 309 PetscCall(KSPLoad(ksp,viewer)); 310 PetscFunctionReturn(0); 311 } 312 313 #include <petscdraw.h> 314 #if defined(PETSC_HAVE_SAWS) 315 #include <petscviewersaws.h> 316 #endif 317 318 /*@C 319 SNESViewFromOptions - View from Options 320 321 Collective on SNES 322 323 Input Parameters: 324 + A - the application ordering context 325 . obj - Optional object 326 - name - command line option 327 328 Level: intermediate 329 .seealso: `SNES`, `SNESView`, `PetscObjectViewFromOptions()`, `SNESCreate()` 330 @*/ 331 PetscErrorCode SNESViewFromOptions(SNES A,PetscObject obj,const char name[]) 332 { 333 PetscFunctionBegin; 334 PetscValidHeaderSpecific(A,SNES_CLASSID,1); 335 PetscCall(PetscObjectViewFromOptions((PetscObject)A,obj,name)); 336 PetscFunctionReturn(0); 337 } 338 339 PETSC_EXTERN PetscErrorCode SNESComputeJacobian_DMDA(SNES,Vec,Mat,Mat,void*); 340 341 /*@C 342 SNESView - Prints the SNES data structure. 343 344 Collective on SNES 345 346 Input Parameters: 347 + SNES - the SNES context 348 - viewer - visualization context 349 350 Options Database Key: 351 . -snes_view - Calls SNESView() at end of SNESSolve() 352 353 Notes: 354 The available visualization contexts include 355 + PETSC_VIEWER_STDOUT_SELF - standard output (default) 356 - PETSC_VIEWER_STDOUT_WORLD - synchronized standard 357 output where only the first processor opens 358 the file. All other processors send their 359 data to the first processor to print. 360 361 The available formats include 362 + PETSC_VIEWER_DEFAULT - standard output (default) 363 - PETSC_VIEWER_ASCII_INFO_DETAIL - more verbose output for SNESNASM 364 365 The user can open an alternative visualization context with 366 PetscViewerASCIIOpen() - output to a specified file. 367 368 In the debugger you can do "call SNESView(snes,0)" to display the SNES solver. (The same holds for any PETSc object viewer). 369 370 Level: beginner 371 372 .seealso: `PetscViewerASCIIOpen()` 373 @*/ 374 PetscErrorCode SNESView(SNES snes,PetscViewer viewer) 375 { 376 SNESKSPEW *kctx; 377 KSP ksp; 378 SNESLineSearch linesearch; 379 PetscBool iascii,isstring,isbinary,isdraw; 380 DMSNES dmsnes; 381 #if defined(PETSC_HAVE_SAWS) 382 PetscBool issaws; 383 #endif 384 385 PetscFunctionBegin; 386 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 387 if (!viewer) { 388 PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes),&viewer)); 389 } 390 PetscValidHeaderSpecific(viewer,PETSC_VIEWER_CLASSID,2); 391 PetscCheckSameComm(snes,1,viewer,2); 392 393 PetscCall(PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii)); 394 PetscCall(PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSTRING,&isstring)); 395 PetscCall(PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary)); 396 PetscCall(PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERDRAW,&isdraw)); 397 #if defined(PETSC_HAVE_SAWS) 398 PetscCall(PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSAWS,&issaws)); 399 #endif 400 if (iascii) { 401 SNESNormSchedule normschedule; 402 DM dm; 403 PetscErrorCode (*cJ)(SNES,Vec,Mat,Mat,void*); 404 void *ctx; 405 const char *pre = ""; 406 407 PetscCall(PetscObjectPrintClassNamePrefixType((PetscObject)snes,viewer)); 408 if (!snes->setupcalled) { 409 PetscCall(PetscViewerASCIIPrintf(viewer," SNES has not been set up so information may be incomplete\n")); 410 } 411 if (snes->ops->view) { 412 PetscCall(PetscViewerASCIIPushTab(viewer)); 413 PetscUseTypeMethod(snes,view ,viewer); 414 PetscCall(PetscViewerASCIIPopTab(viewer)); 415 } 416 PetscCall(PetscViewerASCIIPrintf(viewer," maximum iterations=%" PetscInt_FMT ", maximum function evaluations=%" PetscInt_FMT "\n",snes->max_its,snes->max_funcs)); 417 PetscCall(PetscViewerASCIIPrintf(viewer," tolerances: relative=%g, absolute=%g, solution=%g\n",(double)snes->rtol,(double)snes->abstol,(double)snes->stol)); 418 if (snes->usesksp) { 419 PetscCall(PetscViewerASCIIPrintf(viewer," total number of linear solver iterations=%" PetscInt_FMT "\n",snes->linear_its)); 420 } 421 PetscCall(PetscViewerASCIIPrintf(viewer," total number of function evaluations=%" PetscInt_FMT "\n",snes->nfuncs)); 422 PetscCall(SNESGetNormSchedule(snes, &normschedule)); 423 if (normschedule > 0) PetscCall(PetscViewerASCIIPrintf(viewer," norm schedule %s\n",SNESNormSchedules[normschedule])); 424 if (snes->gridsequence) { 425 PetscCall(PetscViewerASCIIPrintf(viewer," total number of grid sequence refinements=%" PetscInt_FMT "\n",snes->gridsequence)); 426 } 427 if (snes->ksp_ewconv) { 428 kctx = (SNESKSPEW*)snes->kspconvctx; 429 if (kctx) { 430 PetscCall(PetscViewerASCIIPrintf(viewer," Eisenstat-Walker computation of KSP relative tolerance (version %" PetscInt_FMT ")\n",kctx->version)); 431 PetscCall(PetscViewerASCIIPrintf(viewer," rtol_0=%g, rtol_max=%g, threshold=%g\n",(double)kctx->rtol_0,(double)kctx->rtol_max,(double)kctx->threshold)); 432 PetscCall(PetscViewerASCIIPrintf(viewer," gamma=%g, alpha=%g, alpha2=%g\n",(double)kctx->gamma,(double)kctx->alpha,(double)kctx->alpha2)); 433 } 434 } 435 if (snes->lagpreconditioner == -1) { 436 PetscCall(PetscViewerASCIIPrintf(viewer," Preconditioned is never rebuilt\n")); 437 } else if (snes->lagpreconditioner > 1) { 438 PetscCall(PetscViewerASCIIPrintf(viewer," Preconditioned is rebuilt every %" PetscInt_FMT " new Jacobians\n",snes->lagpreconditioner)); 439 } 440 if (snes->lagjacobian == -1) { 441 PetscCall(PetscViewerASCIIPrintf(viewer," Jacobian is never rebuilt\n")); 442 } else if (snes->lagjacobian > 1) { 443 PetscCall(PetscViewerASCIIPrintf(viewer," Jacobian is rebuilt every %" PetscInt_FMT " SNES iterations\n",snes->lagjacobian)); 444 } 445 PetscCall(SNESGetDM(snes,&dm)); 446 PetscCall(DMSNESGetJacobian(dm,&cJ,&ctx)); 447 if (snes->mf_operator) { 448 PetscCall(PetscViewerASCIIPrintf(viewer," Jacobian is applied matrix-free with differencing\n")); 449 pre = "Preconditioning "; 450 } 451 if (cJ == SNESComputeJacobianDefault) { 452 PetscCall(PetscViewerASCIIPrintf(viewer," %sJacobian is built using finite differences one column at a time\n",pre)); 453 } else if (cJ == SNESComputeJacobianDefaultColor) { 454 PetscCall(PetscViewerASCIIPrintf(viewer," %sJacobian is built using finite differences with coloring\n",pre)); 455 /* it slightly breaks data encapsulation for access the DMDA information directly */ 456 } else if (cJ == SNESComputeJacobian_DMDA) { 457 MatFDColoring fdcoloring; 458 PetscCall(PetscObjectQuery((PetscObject)dm,"DMDASNES_FDCOLORING",(PetscObject*)&fdcoloring)); 459 if (fdcoloring) { 460 PetscCall(PetscViewerASCIIPrintf(viewer," %sJacobian is built using colored finite differences on a DMDA\n",pre)); 461 } else { 462 PetscCall(PetscViewerASCIIPrintf(viewer," %sJacobian is built using a DMDA local Jacobian\n",pre)); 463 } 464 } else if (snes->mf) { 465 PetscCall(PetscViewerASCIIPrintf(viewer," Jacobian is applied matrix-free with differencing, no explicit Jacobian\n")); 466 } 467 } else if (isstring) { 468 const char *type; 469 PetscCall(SNESGetType(snes,&type)); 470 PetscCall(PetscViewerStringSPrintf(viewer," SNESType: %-7.7s",type)); 471 PetscTryTypeMethod(snes,view,viewer); 472 } else if (isbinary) { 473 PetscInt classid = SNES_FILE_CLASSID; 474 MPI_Comm comm; 475 PetscMPIInt rank; 476 char type[256]; 477 478 PetscCall(PetscObjectGetComm((PetscObject)snes,&comm)); 479 PetscCallMPI(MPI_Comm_rank(comm,&rank)); 480 if (rank == 0) { 481 PetscCall(PetscViewerBinaryWrite(viewer,&classid,1,PETSC_INT)); 482 PetscCall(PetscStrncpy(type,((PetscObject)snes)->type_name,sizeof(type))); 483 PetscCall(PetscViewerBinaryWrite(viewer,type,sizeof(type),PETSC_CHAR)); 484 } 485 PetscTryTypeMethod(snes,view,viewer); 486 } else if (isdraw) { 487 PetscDraw draw; 488 char str[36]; 489 PetscReal x,y,bottom,h; 490 491 PetscCall(PetscViewerDrawGetDraw(viewer,0,&draw)); 492 PetscCall(PetscDrawGetCurrentPoint(draw,&x,&y)); 493 PetscCall(PetscStrncpy(str,"SNES: ",sizeof(str))); 494 PetscCall(PetscStrlcat(str,((PetscObject)snes)->type_name,sizeof(str))); 495 PetscCall(PetscDrawStringBoxed(draw,x,y,PETSC_DRAW_BLUE,PETSC_DRAW_BLACK,str,NULL,&h)); 496 bottom = y - h; 497 PetscCall(PetscDrawPushCurrentPoint(draw,x,bottom)); 498 PetscTryTypeMethod(snes,view,viewer); 499 #if defined(PETSC_HAVE_SAWS) 500 } else if (issaws) { 501 PetscMPIInt rank; 502 const char *name; 503 504 PetscCall(PetscObjectGetName((PetscObject)snes,&name)); 505 PetscCallMPI(MPI_Comm_rank(PETSC_COMM_WORLD,&rank)); 506 if (!((PetscObject)snes)->amsmem && rank == 0) { 507 char dir[1024]; 508 509 PetscCall(PetscObjectViewSAWs((PetscObject)snes,viewer)); 510 PetscCall(PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/its",name)); 511 PetscCallSAWs(SAWs_Register,(dir,&snes->iter,1,SAWs_READ,SAWs_INT)); 512 if (!snes->conv_hist) { 513 PetscCall(SNESSetConvergenceHistory(snes,NULL,NULL,PETSC_DECIDE,PETSC_TRUE)); 514 } 515 PetscCall(PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/conv_hist",name)); 516 PetscCallSAWs(SAWs_Register,(dir,snes->conv_hist,10,SAWs_READ,SAWs_DOUBLE)); 517 } 518 #endif 519 } 520 if (snes->linesearch) { 521 PetscCall(SNESGetLineSearch(snes, &linesearch)); 522 PetscCall(PetscViewerASCIIPushTab(viewer)); 523 PetscCall(SNESLineSearchView(linesearch, viewer)); 524 PetscCall(PetscViewerASCIIPopTab(viewer)); 525 } 526 if (snes->npc && snes->usesnpc) { 527 PetscCall(PetscViewerASCIIPushTab(viewer)); 528 PetscCall(SNESView(snes->npc, viewer)); 529 PetscCall(PetscViewerASCIIPopTab(viewer)); 530 } 531 PetscCall(PetscViewerASCIIPushTab(viewer)); 532 PetscCall(DMGetDMSNES(snes->dm,&dmsnes)); 533 PetscCall(DMSNESView(dmsnes, viewer)); 534 PetscCall(PetscViewerASCIIPopTab(viewer)); 535 if (snes->usesksp) { 536 PetscCall(SNESGetKSP(snes,&ksp)); 537 PetscCall(PetscViewerASCIIPushTab(viewer)); 538 PetscCall(KSPView(ksp,viewer)); 539 PetscCall(PetscViewerASCIIPopTab(viewer)); 540 } 541 if (isdraw) { 542 PetscDraw draw; 543 PetscCall(PetscViewerDrawGetDraw(viewer,0,&draw)); 544 PetscCall(PetscDrawPopCurrentPoint(draw)); 545 } 546 PetscFunctionReturn(0); 547 } 548 549 /* 550 We retain a list of functions that also take SNES command 551 line options. These are called at the end SNESSetFromOptions() 552 */ 553 #define MAXSETFROMOPTIONS 5 554 static PetscInt numberofsetfromoptions; 555 static PetscErrorCode (*othersetfromoptions[MAXSETFROMOPTIONS])(SNES); 556 557 /*@C 558 SNESAddOptionsChecker - Adds an additional function to check for SNES options. 559 560 Not Collective 561 562 Input Parameter: 563 . snescheck - function that checks for options 564 565 Level: developer 566 567 .seealso: `SNESSetFromOptions()` 568 @*/ 569 PetscErrorCode SNESAddOptionsChecker(PetscErrorCode (*snescheck)(SNES)) 570 { 571 PetscFunctionBegin; 572 PetscCheck(numberofsetfromoptions < MAXSETFROMOPTIONS,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE, "Too many options checkers, only %d allowed", MAXSETFROMOPTIONS); 573 othersetfromoptions[numberofsetfromoptions++] = snescheck; 574 PetscFunctionReturn(0); 575 } 576 577 PETSC_INTERN PetscErrorCode SNESDefaultMatrixFreeCreate2(SNES,Vec,Mat*); 578 579 static PetscErrorCode SNESSetUpMatrixFree_Private(SNES snes, PetscBool hasOperator, PetscInt version) 580 { 581 Mat J; 582 MatNullSpace nullsp; 583 584 PetscFunctionBegin; 585 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 586 587 if (!snes->vec_func && (snes->jacobian || snes->jacobian_pre)) { 588 Mat A = snes->jacobian, B = snes->jacobian_pre; 589 PetscCall(MatCreateVecs(A ? A : B, NULL,&snes->vec_func)); 590 } 591 592 if (version == 1) { 593 PetscCall(MatCreateSNESMF(snes,&J)); 594 PetscCall(MatMFFDSetOptionsPrefix(J,((PetscObject)snes)->prefix)); 595 PetscCall(MatSetFromOptions(J)); 596 /* TODO: the version 2 code should be merged into the MatCreateSNESMF() and MatCreateMFFD() infrastructure and then removed */ 597 } else if (version == 2) { 598 PetscCheck(snes->vec_func,PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"SNESSetFunction() must be called first"); 599 #if !defined(PETSC_USE_COMPLEX) && !defined(PETSC_USE_REAL_SINGLE) && !defined(PETSC_USE_REAL___FLOAT128) && !defined(PETSC_USE_REAL___FP16) 600 PetscCall(SNESDefaultMatrixFreeCreate2(snes,snes->vec_func,&J)); 601 #else 602 SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP, "matrix-free operator routines (version 2)"); 603 #endif 604 } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE, "matrix-free operator routines, only version 1 and 2"); 605 606 /* attach any user provided null space that was on Amat to the newly created matrix free matrix */ 607 if (snes->jacobian) { 608 PetscCall(MatGetNullSpace(snes->jacobian,&nullsp)); 609 if (nullsp) PetscCall(MatSetNullSpace(J,nullsp)); 610 } 611 612 PetscCall(PetscInfo(snes,"Setting default matrix-free operator routines (version %" PetscInt_FMT ")\n", version)); 613 if (hasOperator) { 614 615 /* This version replaces the user provided Jacobian matrix with a 616 matrix-free version but still employs the user-provided preconditioner matrix. */ 617 PetscCall(SNESSetJacobian(snes,J,NULL,NULL,NULL)); 618 } else { 619 /* This version replaces both the user-provided Jacobian and the user- 620 provided preconditioner Jacobian with the default matrix free version. */ 621 if (snes->npcside == PC_LEFT && snes->npc) { 622 if (!snes->jacobian) PetscCall(SNESSetJacobian(snes,J,NULL,NULL,NULL)); 623 } else { 624 KSP ksp; 625 PC pc; 626 PetscBool match; 627 628 PetscCall(SNESSetJacobian(snes,J,J,MatMFFDComputeJacobian,NULL)); 629 /* Force no preconditioner */ 630 PetscCall(SNESGetKSP(snes,&ksp)); 631 PetscCall(KSPGetPC(ksp,&pc)); 632 PetscCall(PetscObjectTypeCompareAny((PetscObject)pc,&match,PCSHELL,PCH2OPUS,"")); 633 if (!match) { 634 PetscCall(PetscInfo(snes,"Setting default matrix-free preconditioner routines\nThat is no preconditioner is being used\n")); 635 PetscCall(PCSetType(pc,PCNONE)); 636 } 637 } 638 } 639 PetscCall(MatDestroy(&J)); 640 PetscFunctionReturn(0); 641 } 642 643 static PetscErrorCode DMRestrictHook_SNESVecSol(DM dmfine,Mat Restrict,Vec Rscale,Mat Inject,DM dmcoarse,void *ctx) 644 { 645 SNES snes = (SNES)ctx; 646 Vec Xfine,Xfine_named = NULL,Xcoarse; 647 648 PetscFunctionBegin; 649 if (PetscLogPrintInfo) { 650 PetscInt finelevel,coarselevel,fineclevel,coarseclevel; 651 PetscCall(DMGetRefineLevel(dmfine,&finelevel)); 652 PetscCall(DMGetCoarsenLevel(dmfine,&fineclevel)); 653 PetscCall(DMGetRefineLevel(dmcoarse,&coarselevel)); 654 PetscCall(DMGetCoarsenLevel(dmcoarse,&coarseclevel)); 655 PetscCall(PetscInfo(dmfine,"Restricting SNES solution vector from level %" PetscInt_FMT "-%" PetscInt_FMT " to level %" PetscInt_FMT "-%" PetscInt_FMT "\n",finelevel,fineclevel,coarselevel,coarseclevel)); 656 } 657 if (dmfine == snes->dm) Xfine = snes->vec_sol; 658 else { 659 PetscCall(DMGetNamedGlobalVector(dmfine,"SNESVecSol",&Xfine_named)); 660 Xfine = Xfine_named; 661 } 662 PetscCall(DMGetNamedGlobalVector(dmcoarse,"SNESVecSol",&Xcoarse)); 663 if (Inject) { 664 PetscCall(MatRestrict(Inject,Xfine,Xcoarse)); 665 } else { 666 PetscCall(MatRestrict(Restrict,Xfine,Xcoarse)); 667 PetscCall(VecPointwiseMult(Xcoarse,Xcoarse,Rscale)); 668 } 669 PetscCall(DMRestoreNamedGlobalVector(dmcoarse,"SNESVecSol",&Xcoarse)); 670 if (Xfine_named) PetscCall(DMRestoreNamedGlobalVector(dmfine,"SNESVecSol",&Xfine_named)); 671 PetscFunctionReturn(0); 672 } 673 674 static PetscErrorCode DMCoarsenHook_SNESVecSol(DM dm,DM dmc,void *ctx) 675 { 676 PetscFunctionBegin; 677 PetscCall(DMCoarsenHookAdd(dmc,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,ctx)); 678 PetscFunctionReturn(0); 679 } 680 681 /* This may be called to rediscretize the operator on levels of linear multigrid. The DM shuffle is so the user can 682 * safely call SNESGetDM() in their residual evaluation routine. */ 683 static PetscErrorCode KSPComputeOperators_SNES(KSP ksp,Mat A,Mat B,void *ctx) 684 { 685 SNES snes = (SNES)ctx; 686 Vec X,Xnamed = NULL; 687 DM dmsave; 688 void *ctxsave; 689 PetscErrorCode (*jac)(SNES,Vec,Mat,Mat,void*) = NULL; 690 691 PetscFunctionBegin; 692 dmsave = snes->dm; 693 PetscCall(KSPGetDM(ksp,&snes->dm)); 694 if (dmsave == snes->dm) X = snes->vec_sol; /* We are on the finest level */ 695 else { /* We are on a coarser level, this vec was initialized using a DM restrict hook */ 696 PetscCall(DMGetNamedGlobalVector(snes->dm,"SNESVecSol",&Xnamed)); 697 X = Xnamed; 698 PetscCall(SNESGetJacobian(snes,NULL,NULL,&jac,&ctxsave)); 699 /* If the DM's don't match up, the MatFDColoring context needed for the jacobian won't match up either -- fixit. */ 700 if (jac == SNESComputeJacobianDefaultColor) { 701 PetscCall(SNESSetJacobian(snes,NULL,NULL,SNESComputeJacobianDefaultColor,NULL)); 702 } 703 } 704 /* Make sure KSP DM has the Jacobian computation routine */ 705 { 706 DMSNES sdm; 707 708 PetscCall(DMGetDMSNES(snes->dm, &sdm)); 709 if (!sdm->ops->computejacobian) { 710 PetscCall(DMCopyDMSNES(dmsave, snes->dm)); 711 } 712 } 713 /* Compute the operators */ 714 PetscCall(SNESComputeJacobian(snes,X,A,B)); 715 /* Put the previous context back */ 716 if (snes->dm != dmsave && jac == SNESComputeJacobianDefaultColor) { 717 PetscCall(SNESSetJacobian(snes,NULL,NULL,jac,ctxsave)); 718 } 719 720 if (Xnamed) PetscCall(DMRestoreNamedGlobalVector(snes->dm,"SNESVecSol",&Xnamed)); 721 snes->dm = dmsave; 722 PetscFunctionReturn(0); 723 } 724 725 /*@ 726 SNESSetUpMatrices - ensures that matrices are available for SNES, to be called by SNESSetUp_XXX() 727 728 Collective 729 730 Input Parameter: 731 . snes - snes to configure 732 733 Level: developer 734 735 .seealso: `SNESSetUp()` 736 @*/ 737 PetscErrorCode SNESSetUpMatrices(SNES snes) 738 { 739 DM dm; 740 DMSNES sdm; 741 742 PetscFunctionBegin; 743 PetscCall(SNESGetDM(snes,&dm)); 744 PetscCall(DMGetDMSNES(dm,&sdm)); 745 if (!snes->jacobian && snes->mf) { 746 Mat J; 747 void *functx; 748 PetscCall(MatCreateSNESMF(snes,&J)); 749 PetscCall(MatMFFDSetOptionsPrefix(J,((PetscObject)snes)->prefix)); 750 PetscCall(MatSetFromOptions(J)); 751 PetscCall(SNESGetFunction(snes,NULL,NULL,&functx)); 752 PetscCall(SNESSetJacobian(snes,J,J,NULL,NULL)); 753 PetscCall(MatDestroy(&J)); 754 } else if (snes->mf_operator && !snes->jacobian_pre && !snes->jacobian) { 755 Mat J,B; 756 PetscCall(MatCreateSNESMF(snes,&J)); 757 PetscCall(MatMFFDSetOptionsPrefix(J,((PetscObject)snes)->prefix)); 758 PetscCall(MatSetFromOptions(J)); 759 PetscCall(DMCreateMatrix(snes->dm,&B)); 760 /* sdm->computejacobian was already set to reach here */ 761 PetscCall(SNESSetJacobian(snes,J,B,NULL,NULL)); 762 PetscCall(MatDestroy(&J)); 763 PetscCall(MatDestroy(&B)); 764 } else if (!snes->jacobian_pre) { 765 PetscDS prob; 766 Mat J, B; 767 PetscBool hasPrec = PETSC_FALSE; 768 769 J = snes->jacobian; 770 PetscCall(DMGetDS(dm, &prob)); 771 if (prob) PetscCall(PetscDSHasJacobianPreconditioner(prob, &hasPrec)); 772 if (J) PetscCall(PetscObjectReference((PetscObject) J)); 773 else if (hasPrec) PetscCall(DMCreateMatrix(snes->dm, &J)); 774 PetscCall(DMCreateMatrix(snes->dm, &B)); 775 PetscCall(SNESSetJacobian(snes, J ? J : B, B, NULL, NULL)); 776 PetscCall(MatDestroy(&J)); 777 PetscCall(MatDestroy(&B)); 778 } 779 { 780 KSP ksp; 781 PetscCall(SNESGetKSP(snes,&ksp)); 782 PetscCall(KSPSetComputeOperators(ksp,KSPComputeOperators_SNES,snes)); 783 PetscCall(DMCoarsenHookAdd(snes->dm,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,snes)); 784 } 785 PetscFunctionReturn(0); 786 } 787 788 static PetscErrorCode SNESMonitorPauseFinal_Internal(SNES snes) 789 { 790 PetscInt i; 791 792 PetscFunctionBegin; 793 if (!snes->pauseFinal) PetscFunctionReturn(0); 794 for (i = 0; i < snes->numbermonitors; ++i) { 795 PetscViewerAndFormat *vf = (PetscViewerAndFormat *) snes->monitorcontext[i]; 796 PetscDraw draw; 797 PetscReal lpause; 798 799 if (!vf) continue; 800 if (vf->lg) { 801 if (!PetscCheckPointer(vf->lg, PETSC_OBJECT)) continue; 802 if (((PetscObject) vf->lg)->classid != PETSC_DRAWLG_CLASSID) continue; 803 PetscCall(PetscDrawLGGetDraw(vf->lg, &draw)); 804 PetscCall(PetscDrawGetPause(draw, &lpause)); 805 PetscCall(PetscDrawSetPause(draw, -1.0)); 806 PetscCall(PetscDrawPause(draw)); 807 PetscCall(PetscDrawSetPause(draw, lpause)); 808 } else { 809 PetscBool isdraw; 810 811 if (!PetscCheckPointer(vf->viewer, PETSC_OBJECT)) continue; 812 if (((PetscObject) vf->viewer)->classid != PETSC_VIEWER_CLASSID) continue; 813 PetscCall(PetscObjectTypeCompare((PetscObject) vf->viewer, PETSCVIEWERDRAW, &isdraw)); 814 if (!isdraw) continue; 815 PetscCall(PetscViewerDrawGetDraw(vf->viewer, 0, &draw)); 816 PetscCall(PetscDrawGetPause(draw, &lpause)); 817 PetscCall(PetscDrawSetPause(draw, -1.0)); 818 PetscCall(PetscDrawPause(draw)); 819 PetscCall(PetscDrawSetPause(draw, lpause)); 820 } 821 } 822 PetscFunctionReturn(0); 823 } 824 825 /*@C 826 SNESMonitorSetFromOptions - Sets a monitor function and viewer appropriate for the type indicated by the user 827 828 Collective on SNES 829 830 Input Parameters: 831 + snes - SNES object you wish to monitor 832 . name - the monitor type one is seeking 833 . help - message indicating what monitoring is done 834 . manual - manual page for the monitor 835 . monitor - the monitor function 836 - 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 837 838 Level: developer 839 840 .seealso: `PetscOptionsGetViewer()`, `PetscOptionsGetReal()`, `PetscOptionsHasName()`, `PetscOptionsGetString()`, 841 `PetscOptionsGetIntArray()`, `PetscOptionsGetRealArray()`, `PetscOptionsBool()` 842 `PetscOptionsInt()`, `PetscOptionsString()`, `PetscOptionsReal()`, `PetscOptionsBool()`, 843 `PetscOptionsName()`, `PetscOptionsBegin()`, `PetscOptionsEnd()`, `PetscOptionsHeadBegin()`, 844 `PetscOptionsStringArray()`, `PetscOptionsRealArray()`, `PetscOptionsScalar()`, 845 `PetscOptionsBoolGroupBegin()`, `PetscOptionsBoolGroup()`, `PetscOptionsBoolGroupEnd()`, 846 `PetscOptionsFList()`, `PetscOptionsEList()` 847 @*/ 848 PetscErrorCode SNESMonitorSetFromOptions(SNES snes,const char name[],const char help[], const char manual[],PetscErrorCode (*monitor)(SNES,PetscInt,PetscReal,PetscViewerAndFormat*),PetscErrorCode (*monitorsetup)(SNES,PetscViewerAndFormat*)) 849 { 850 PetscViewer viewer; 851 PetscViewerFormat format; 852 PetscBool flg; 853 854 PetscFunctionBegin; 855 PetscCall(PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject) snes)->options,((PetscObject)snes)->prefix,name,&viewer,&format,&flg)); 856 if (flg) { 857 PetscViewerAndFormat *vf; 858 PetscCall(PetscViewerAndFormatCreate(viewer,format,&vf)); 859 PetscCall(PetscObjectDereference((PetscObject)viewer)); 860 if (monitorsetup) PetscCall((*monitorsetup)(snes,vf)); 861 PetscCall(SNESMonitorSet(snes,(PetscErrorCode (*)(SNES,PetscInt,PetscReal,void*))monitor,vf,(PetscErrorCode (*)(void**))PetscViewerAndFormatDestroy)); 862 } 863 PetscFunctionReturn(0); 864 } 865 866 PetscErrorCode SNESEWSetFromOptions_Private(SNESKSPEW* kctx, MPI_Comm comm, const char* prefix) 867 { 868 PetscFunctionBegin; 869 PetscOptionsBegin(comm,prefix,"Eisenstat and Walker type forcing options","KSP"); 870 PetscCall(PetscOptionsInt("-ksp_ew_version","Version 1, 2 or 3",NULL,kctx->version,&kctx->version,NULL)); 871 PetscCall(PetscOptionsReal("-ksp_ew_rtol0","0 <= rtol0 < 1",NULL,kctx->rtol_0,&kctx->rtol_0,NULL)); 872 PetscCall(PetscOptionsReal("-ksp_ew_rtolmax","0 <= rtolmax < 1",NULL,kctx->rtol_max,&kctx->rtol_max,NULL)); 873 PetscCall(PetscOptionsReal("-ksp_ew_gamma","0 <= gamma <= 1",NULL,kctx->gamma,&kctx->gamma,NULL)); 874 PetscCall(PetscOptionsReal("-ksp_ew_alpha","1 < alpha <= 2",NULL,kctx->alpha,&kctx->alpha,NULL)); 875 PetscCall(PetscOptionsReal("-ksp_ew_alpha2","alpha2",NULL,kctx->alpha2,&kctx->alpha2,NULL)); 876 PetscCall(PetscOptionsReal("-ksp_ew_threshold","0 < threshold < 1",NULL,kctx->threshold,&kctx->threshold,NULL)); 877 PetscCall(PetscOptionsReal("-ksp_ew_v4_p1","p1",NULL,kctx->v4_p1,&kctx->v4_p1,NULL)); 878 PetscCall(PetscOptionsReal("-ksp_ew_v4_p2","p2",NULL,kctx->v4_p2,&kctx->v4_p2,NULL)); 879 PetscCall(PetscOptionsReal("-ksp_ew_v4_p3","p3",NULL,kctx->v4_p3,&kctx->v4_p3,NULL)); 880 PetscCall(PetscOptionsReal("-ksp_ew_v4_m1","Scaling when rk-1 in [p2,p3)",NULL,kctx->v4_m1,&kctx->v4_m1,NULL)); 881 PetscCall(PetscOptionsReal("-ksp_ew_v4_m2","Scaling when rk-1 in [p3,+infty)",NULL,kctx->v4_m2,&kctx->v4_m2,NULL)); 882 PetscCall(PetscOptionsReal("-ksp_ew_v4_m3","Threshold for successive rtol (0.1 in Eq.7)",NULL,kctx->v4_m3,&kctx->v4_m3,NULL)); 883 PetscCall(PetscOptionsReal("-ksp_ew_v4_m4","Adaptation scaling (0.5 in Eq.7)",NULL,kctx->v4_m4,&kctx->v4_m4,NULL)); 884 PetscOptionsEnd(); 885 PetscFunctionReturn(0); 886 } 887 888 /*@ 889 SNESSetFromOptions - Sets various SNES and KSP parameters from user options. 890 891 Collective on SNES 892 893 Input Parameter: 894 . snes - the SNES context 895 896 Options Database Keys: 897 + -snes_type <type> - newtonls, newtontr, ngmres, ncg, nrichardson, qn, vi, fas, SNESType for complete list 898 . -snes_stol - convergence tolerance in terms of the norm 899 of the change in the solution between steps 900 . -snes_atol <abstol> - absolute tolerance of residual norm 901 . -snes_rtol <rtol> - relative decrease in tolerance norm from initial 902 . -snes_divergence_tolerance <divtol> - if the residual goes above divtol*rnorm0, exit with divergence 903 . -snes_force_iteration <force> - force SNESSolve() to take at least one iteration 904 . -snes_max_it <max_it> - maximum number of iterations 905 . -snes_max_funcs <max_funcs> - maximum number of function evaluations 906 . -snes_max_fail <max_fail> - maximum number of line search failures allowed before stopping, default is none 907 . -snes_max_linear_solve_fail - number of linear solver failures before SNESSolve() stops 908 . -snes_lag_preconditioner <lag> - how often preconditioner is rebuilt (use -1 to never rebuild) 909 . -snes_lag_preconditioner_persists <true,false> - retains the -snes_lag_preconditioner information across multiple SNESSolve() 910 . -snes_lag_jacobian <lag> - how often Jacobian is rebuilt (use -1 to never rebuild) 911 . -snes_lag_jacobian_persists <true,false> - retains the -snes_lag_jacobian information across multiple SNESSolve() 912 . -snes_trtol <trtol> - trust region tolerance 913 . -snes_convergence_test - <default,skip,correct_pressure> convergence test in nonlinear solver. 914 default SNESConvergedDefault(). skip SNESConvergedSkip() means continue iterating until max_it or some other criterion is reached, saving expense 915 of convergence test. correct_pressure SNESConvergedCorrectPressure() has special handling of a pressure null space. 916 . -snes_monitor [ascii][:filename][:viewer format] - prints residual norm at each iteration. if no filename given prints to stdout 917 . -snes_monitor_solution [ascii binary draw][:filename][:viewer format] - plots solution at each iteration 918 . -snes_monitor_residual [ascii binary draw][:filename][:viewer format] - plots residual (not its norm) at each iteration 919 . -snes_monitor_solution_update [ascii binary draw][:filename][:viewer format] - plots update to solution at each iteration 920 . -snes_monitor_lg_residualnorm - plots residual norm at each iteration 921 . -snes_monitor_lg_range - plots residual norm at each iteration 922 . -snes_monitor_pause_final - Pauses all monitor drawing after the solver ends 923 . -snes_fd - use finite differences to compute Jacobian; very slow, only for testing 924 . -snes_fd_color - use finite differences with coloring to compute Jacobian 925 . -snes_mf_ksp_monitor - if using matrix-free multiply then print h at each KSP iteration 926 . -snes_converged_reason - print the reason for convergence/divergence after each solve 927 . -npc_snes_type <type> - the SNES type to use as a nonlinear preconditioner 928 . -snes_test_jacobian <optional threshold> - compare the user provided Jacobian with one computed via finite differences to check for errors. If a threshold is given, display only those entries whose difference is greater than the threshold. 929 - -snes_test_jacobian_view - display the user provided Jacobian, the finite difference Jacobian and the difference between them to help users detect the location of errors in the user provided Jacobian. 930 931 Options Database for Eisenstat-Walker method: 932 + -snes_ksp_ew - use Eisenstat-Walker method for determining linear system convergence 933 . -snes_ksp_ew_version ver - version of Eisenstat-Walker method 934 . -snes_ksp_ew_rtol0 <rtol0> - Sets rtol0 935 . -snes_ksp_ew_rtolmax <rtolmax> - Sets rtolmax 936 . -snes_ksp_ew_gamma <gamma> - Sets gamma 937 . -snes_ksp_ew_alpha <alpha> - Sets alpha 938 . -snes_ksp_ew_alpha2 <alpha2> - Sets alpha2 939 - -snes_ksp_ew_threshold <threshold> - Sets threshold 940 941 Notes: 942 To see all options, run your program with the -help option or consult the users manual 943 944 Notes: 945 SNES supports three approaches for computing (approximate) Jacobians: user provided via SNESSetJacobian(), matrix free, and computing explicitly with 946 finite differences and coloring using MatFDColoring. It is also possible to use automatic differentiation and the MatFDColoring object. 947 948 Level: beginner 949 950 .seealso: `SNESSetOptionsPrefix()`, `SNESResetFromOptions()`, `SNES`, `SNESCreate()` 951 @*/ 952 PetscErrorCode SNESSetFromOptions(SNES snes) 953 { 954 PetscBool flg,pcset,persist,set; 955 PetscInt i,indx,lag,grids; 956 const char *deft = SNESNEWTONLS; 957 const char *convtests[] = {"default","skip","correct_pressure"}; 958 SNESKSPEW *kctx = NULL; 959 char type[256], monfilename[PETSC_MAX_PATH_LEN], ewprefix[256]; 960 PCSide pcside; 961 const char *optionsprefix; 962 963 PetscFunctionBegin; 964 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 965 PetscCall(SNESRegisterAll()); 966 PetscObjectOptionsBegin((PetscObject)snes); 967 if (((PetscObject)snes)->type_name) deft = ((PetscObject)snes)->type_name; 968 PetscCall(PetscOptionsFList("-snes_type","Nonlinear solver method","SNESSetType",SNESList,deft,type,256,&flg)); 969 if (flg) { 970 PetscCall(SNESSetType(snes,type)); 971 } else if (!((PetscObject)snes)->type_name) { 972 PetscCall(SNESSetType(snes,deft)); 973 } 974 PetscCall(PetscOptionsReal("-snes_stol","Stop if step length less than","SNESSetTolerances",snes->stol,&snes->stol,NULL)); 975 PetscCall(PetscOptionsReal("-snes_atol","Stop if function norm less than","SNESSetTolerances",snes->abstol,&snes->abstol,NULL)); 976 977 PetscCall(PetscOptionsReal("-snes_rtol","Stop if decrease in function norm less than","SNESSetTolerances",snes->rtol,&snes->rtol,NULL)); 978 PetscCall(PetscOptionsReal("-snes_divergence_tolerance","Stop if residual norm increases by this factor","SNESSetDivergenceTolerance",snes->divtol,&snes->divtol,NULL)); 979 PetscCall(PetscOptionsInt("-snes_max_it","Maximum iterations","SNESSetTolerances",snes->max_its,&snes->max_its,NULL)); 980 PetscCall(PetscOptionsInt("-snes_max_funcs","Maximum function evaluations","SNESSetTolerances",snes->max_funcs,&snes->max_funcs,NULL)); 981 PetscCall(PetscOptionsInt("-snes_max_fail","Maximum nonlinear step failures","SNESSetMaxNonlinearStepFailures",snes->maxFailures,&snes->maxFailures,NULL)); 982 PetscCall(PetscOptionsInt("-snes_max_linear_solve_fail","Maximum failures in linear solves allowed","SNESSetMaxLinearSolveFailures",snes->maxLinearSolveFailures,&snes->maxLinearSolveFailures,NULL)); 983 PetscCall(PetscOptionsBool("-snes_error_if_not_converged","Generate error if solver does not converge","SNESSetErrorIfNotConverged",snes->errorifnotconverged,&snes->errorifnotconverged,NULL)); 984 PetscCall(PetscOptionsBool("-snes_force_iteration","Force SNESSolve() to take at least one iteration","SNESSetForceIteration",snes->forceiteration,&snes->forceiteration,NULL)); 985 PetscCall(PetscOptionsBool("-snes_check_jacobian_domain_error","Check Jacobian domain error after Jacobian evaluation","SNESCheckJacobianDomainError",snes->checkjacdomainerror,&snes->checkjacdomainerror,NULL)); 986 987 PetscCall(PetscOptionsInt("-snes_lag_preconditioner","How often to rebuild preconditioner","SNESSetLagPreconditioner",snes->lagpreconditioner,&lag,&flg)); 988 if (flg) { 989 PetscCheck(lag != -1,PetscObjectComm((PetscObject)snes),PETSC_ERR_USER,"Cannot set the lag to -1 from the command line since the preconditioner must be built as least once, perhaps you mean -2"); 990 PetscCall(SNESSetLagPreconditioner(snes,lag)); 991 } 992 PetscCall(PetscOptionsBool("-snes_lag_preconditioner_persists","Preconditioner lagging through multiple SNES solves","SNESSetLagPreconditionerPersists",snes->lagjac_persist,&persist,&flg)); 993 if (flg) PetscCall(SNESSetLagPreconditionerPersists(snes,persist)); 994 PetscCall(PetscOptionsInt("-snes_lag_jacobian","How often to rebuild Jacobian","SNESSetLagJacobian",snes->lagjacobian,&lag,&flg)); 995 if (flg) { 996 PetscCheck(lag != -1,PetscObjectComm((PetscObject)snes),PETSC_ERR_USER,"Cannot set the lag to -1 from the command line since the Jacobian must be built as least once, perhaps you mean -2"); 997 PetscCall(SNESSetLagJacobian(snes,lag)); 998 } 999 PetscCall(PetscOptionsBool("-snes_lag_jacobian_persists","Jacobian lagging through multiple SNES solves","SNESSetLagJacobianPersists",snes->lagjac_persist,&persist,&flg)); 1000 if (flg) PetscCall(SNESSetLagJacobianPersists(snes,persist)); 1001 1002 PetscCall(PetscOptionsInt("-snes_grid_sequence","Use grid sequencing to generate initial guess","SNESSetGridSequence",snes->gridsequence,&grids,&flg)); 1003 if (flg) PetscCall(SNESSetGridSequence(snes,grids)); 1004 1005 PetscCall(PetscOptionsEList("-snes_convergence_test","Convergence test","SNESSetConvergenceTest",convtests,sizeof(convtests)/sizeof(char*),"default",&indx,&flg)); 1006 if (flg) { 1007 switch (indx) { 1008 case 0: PetscCall(SNESSetConvergenceTest(snes,SNESConvergedDefault,NULL,NULL)); break; 1009 case 1: PetscCall(SNESSetConvergenceTest(snes,SNESConvergedSkip,NULL,NULL)); break; 1010 case 2: PetscCall(SNESSetConvergenceTest(snes,SNESConvergedCorrectPressure,NULL,NULL)); break; 1011 } 1012 } 1013 1014 PetscCall(PetscOptionsEList("-snes_norm_schedule","SNES Norm schedule","SNESSetNormSchedule",SNESNormSchedules,5,"function",&indx,&flg)); 1015 if (flg) PetscCall(SNESSetNormSchedule(snes,(SNESNormSchedule)indx)); 1016 1017 PetscCall(PetscOptionsEList("-snes_function_type","SNES Norm schedule","SNESSetFunctionType",SNESFunctionTypes,2,"unpreconditioned",&indx,&flg)); 1018 if (flg) PetscCall(SNESSetFunctionType(snes,(SNESFunctionType)indx)); 1019 1020 kctx = (SNESKSPEW*)snes->kspconvctx; 1021 1022 PetscCall(PetscOptionsBool("-snes_ksp_ew","Use Eisentat-Walker linear system convergence test","SNESKSPSetUseEW",snes->ksp_ewconv,&snes->ksp_ewconv,NULL)); 1023 1024 PetscCall(SNESGetOptionsPrefix(snes,&optionsprefix)); 1025 PetscCall(PetscSNPrintf(ewprefix,sizeof(ewprefix),"%s%s",optionsprefix ? optionsprefix : "","snes_")); 1026 PetscCall(SNESEWSetFromOptions_Private(kctx,PetscObjectComm((PetscObject)snes),ewprefix)); 1027 1028 PetscCall(PetscOptionsInt("-snes_ksp_ew_version","Version 1, 2 or 3","SNESKSPSetParametersEW",kctx->version,&kctx->version,NULL)); 1029 PetscCall(PetscOptionsReal("-snes_ksp_ew_rtol0","0 <= rtol0 < 1","SNESKSPSetParametersEW",kctx->rtol_0,&kctx->rtol_0,NULL)); 1030 PetscCall(PetscOptionsReal("-snes_ksp_ew_rtolmax","0 <= rtolmax < 1","SNESKSPSetParametersEW",kctx->rtol_max,&kctx->rtol_max,NULL)); 1031 PetscCall(PetscOptionsReal("-snes_ksp_ew_gamma","0 <= gamma <= 1","SNESKSPSetParametersEW",kctx->gamma,&kctx->gamma,NULL)); 1032 PetscCall(PetscOptionsReal("-snes_ksp_ew_alpha","1 < alpha <= 2","SNESKSPSetParametersEW",kctx->alpha,&kctx->alpha,NULL)); 1033 PetscCall(PetscOptionsReal("-snes_ksp_ew_alpha2","alpha2","SNESKSPSetParametersEW",kctx->alpha2,&kctx->alpha2,NULL)); 1034 PetscCall(PetscOptionsReal("-snes_ksp_ew_threshold","0 < threshold < 1","SNESKSPSetParametersEW",kctx->threshold,&kctx->threshold,NULL)); 1035 1036 flg = PETSC_FALSE; 1037 PetscCall(PetscOptionsBool("-snes_monitor_cancel","Remove all monitors","SNESMonitorCancel",flg,&flg,&set)); 1038 if (set && flg) PetscCall(SNESMonitorCancel(snes)); 1039 1040 PetscCall(SNESMonitorSetFromOptions(snes,"-snes_monitor","Monitor norm of function","SNESMonitorDefault",SNESMonitorDefault,SNESMonitorDefaultSetUp)); 1041 PetscCall(SNESMonitorSetFromOptions(snes,"-snes_monitor_short","Monitor norm of function with fewer digits","SNESMonitorDefaultShort",SNESMonitorDefaultShort,NULL)); 1042 PetscCall(SNESMonitorSetFromOptions(snes,"-snes_monitor_range","Monitor range of elements of function","SNESMonitorRange",SNESMonitorRange,NULL)); 1043 1044 PetscCall(SNESMonitorSetFromOptions(snes,"-snes_monitor_ratio","Monitor ratios of the norm of function for consecutive steps","SNESMonitorRatio",SNESMonitorRatio,SNESMonitorRatioSetUp)); 1045 PetscCall(SNESMonitorSetFromOptions(snes,"-snes_monitor_field","Monitor norm of function (split into fields)","SNESMonitorDefaultField",SNESMonitorDefaultField,NULL)); 1046 PetscCall(SNESMonitorSetFromOptions(snes,"-snes_monitor_solution","View solution at each iteration","SNESMonitorSolution",SNESMonitorSolution,NULL)); 1047 PetscCall(SNESMonitorSetFromOptions(snes,"-snes_monitor_solution_update","View correction at each iteration","SNESMonitorSolutionUpdate",SNESMonitorSolutionUpdate,NULL)); 1048 PetscCall(SNESMonitorSetFromOptions(snes,"-snes_monitor_residual","View residual at each iteration","SNESMonitorResidual",SNESMonitorResidual,NULL)); 1049 PetscCall(SNESMonitorSetFromOptions(snes,"-snes_monitor_jacupdate_spectrum","Print the change in the spectrum of the Jacobian","SNESMonitorJacUpdateSpectrum",SNESMonitorJacUpdateSpectrum,NULL)); 1050 PetscCall(SNESMonitorSetFromOptions(snes,"-snes_monitor_fields","Monitor norm of function per field","SNESMonitorSet",SNESMonitorFields,NULL)); 1051 PetscCall(PetscOptionsBool("-snes_monitor_pause_final", "Pauses all draw monitors at the final iterate", "SNESMonitorPauseFinal_Internal", PETSC_FALSE, &snes->pauseFinal, NULL)); 1052 1053 PetscCall(PetscOptionsString("-snes_monitor_python","Use Python function","SNESMonitorSet",NULL,monfilename,sizeof(monfilename),&flg)); 1054 if (flg) PetscCall(PetscPythonMonitorSet((PetscObject)snes,monfilename)); 1055 1056 flg = PETSC_FALSE; 1057 PetscCall(PetscOptionsBool("-snes_monitor_lg_range","Plot function range at each iteration","SNESMonitorLGRange",flg,&flg,NULL)); 1058 if (flg) { 1059 PetscViewer ctx; 1060 1061 PetscCall(PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,&ctx)); 1062 PetscCall(SNESMonitorSet(snes,SNESMonitorLGRange,ctx,(PetscErrorCode (*)(void**))PetscViewerDestroy)); 1063 } 1064 1065 flg = PETSC_FALSE; 1066 PetscCall(PetscOptionsBool("-snes_converged_reason_view_cancel","Remove all converged reason viewers","SNESConvergedReasonViewCancel",flg,&flg,&set)); 1067 if (set && flg) PetscCall(SNESConvergedReasonViewCancel(snes)); 1068 1069 flg = PETSC_FALSE; 1070 PetscCall(PetscOptionsBool("-snes_fd","Use finite differences (slow) to compute Jacobian","SNESComputeJacobianDefault",flg,&flg,NULL)); 1071 if (flg) { 1072 void *functx; 1073 DM dm; 1074 PetscCall(SNESGetDM(snes,&dm)); 1075 PetscCall(DMSNESUnsetJacobianContext_Internal(dm)); 1076 PetscCall(SNESGetFunction(snes,NULL,NULL,&functx)); 1077 PetscCall(SNESSetJacobian(snes,snes->jacobian,snes->jacobian_pre,SNESComputeJacobianDefault,functx)); 1078 PetscCall(PetscInfo(snes,"Setting default finite difference Jacobian matrix\n")); 1079 } 1080 1081 flg = PETSC_FALSE; 1082 PetscCall(PetscOptionsBool("-snes_fd_function","Use finite differences (slow) to compute function from user objective","SNESObjectiveComputeFunctionDefaultFD",flg,&flg,NULL)); 1083 if (flg) PetscCall(SNESSetFunction(snes,NULL,SNESObjectiveComputeFunctionDefaultFD,NULL)); 1084 1085 flg = PETSC_FALSE; 1086 PetscCall(PetscOptionsBool("-snes_fd_color","Use finite differences with coloring to compute Jacobian","SNESComputeJacobianDefaultColor",flg,&flg,NULL)); 1087 if (flg) { 1088 DM dm; 1089 PetscCall(SNESGetDM(snes,&dm)); 1090 PetscCall(DMSNESUnsetJacobianContext_Internal(dm)); 1091 PetscCall(SNESSetJacobian(snes,snes->jacobian,snes->jacobian_pre,SNESComputeJacobianDefaultColor,NULL)); 1092 PetscCall(PetscInfo(snes,"Setting default finite difference coloring Jacobian matrix\n")); 1093 } 1094 1095 flg = PETSC_FALSE; 1096 PetscCall(PetscOptionsBool("-snes_mf_operator","Use a Matrix-Free Jacobian with user-provided preconditioner matrix","SNESSetUseMatrixFree",PETSC_FALSE,&snes->mf_operator,&flg)); 1097 if (flg && snes->mf_operator) { 1098 snes->mf_operator = PETSC_TRUE; 1099 snes->mf = PETSC_TRUE; 1100 } 1101 flg = PETSC_FALSE; 1102 PetscCall(PetscOptionsBool("-snes_mf","Use a Matrix-Free Jacobian with no preconditioner matrix","SNESSetUseMatrixFree",PETSC_FALSE,&snes->mf,&flg)); 1103 if (!flg && snes->mf_operator) snes->mf = PETSC_TRUE; 1104 PetscCall(PetscOptionsInt("-snes_mf_version","Matrix-Free routines version 1 or 2","None",snes->mf_version,&snes->mf_version,NULL)); 1105 1106 flg = PETSC_FALSE; 1107 PetscCall(SNESGetNPCSide(snes,&pcside)); 1108 PetscCall(PetscOptionsEnum("-snes_npc_side","SNES nonlinear preconditioner side","SNESSetNPCSide",PCSides,(PetscEnum)pcside,(PetscEnum*)&pcside,&flg)); 1109 if (flg) PetscCall(SNESSetNPCSide(snes,pcside)); 1110 1111 #if defined(PETSC_HAVE_SAWS) 1112 /* 1113 Publish convergence information using SAWs 1114 */ 1115 flg = PETSC_FALSE; 1116 PetscCall(PetscOptionsBool("-snes_monitor_saws","Publish SNES progress using SAWs","SNESMonitorSet",flg,&flg,NULL)); 1117 if (flg) { 1118 void *ctx; 1119 PetscCall(SNESMonitorSAWsCreate(snes,&ctx)); 1120 PetscCall(SNESMonitorSet(snes,SNESMonitorSAWs,ctx,SNESMonitorSAWsDestroy)); 1121 } 1122 #endif 1123 #if defined(PETSC_HAVE_SAWS) 1124 { 1125 PetscBool set; 1126 flg = PETSC_FALSE; 1127 PetscCall(PetscOptionsBool("-snes_saws_block","Block for SAWs at end of SNESSolve","PetscObjectSAWsBlock",((PetscObject)snes)->amspublishblock,&flg,&set)); 1128 if (set) PetscCall(PetscObjectSAWsSetBlock((PetscObject)snes,flg)); 1129 } 1130 #endif 1131 1132 for (i = 0; i < numberofsetfromoptions; i++) { 1133 PetscCall((*othersetfromoptions[i])(snes)); 1134 } 1135 1136 PetscTryTypeMethod(snes,setfromoptions,PetscOptionsObject); 1137 1138 /* process any options handlers added with PetscObjectAddOptionsHandler() */ 1139 PetscCall(PetscObjectProcessOptionsHandlers((PetscObject)snes,PetscOptionsObject)); 1140 PetscOptionsEnd(); 1141 1142 if (snes->linesearch) { 1143 PetscCall(SNESGetLineSearch(snes, &snes->linesearch)); 1144 PetscCall(SNESLineSearchSetFromOptions(snes->linesearch)); 1145 } 1146 1147 if (snes->usesksp) { 1148 if (!snes->ksp) PetscCall(SNESGetKSP(snes,&snes->ksp)); 1149 PetscCall(KSPSetOperators(snes->ksp,snes->jacobian,snes->jacobian_pre)); 1150 PetscCall(KSPSetFromOptions(snes->ksp)); 1151 } 1152 1153 /* if user has set the SNES NPC type via options database, create it. */ 1154 PetscCall(SNESGetOptionsPrefix(snes, &optionsprefix)); 1155 PetscCall(PetscOptionsHasName(((PetscObject)snes)->options,optionsprefix, "-npc_snes_type", &pcset)); 1156 if (pcset && (!snes->npc)) { 1157 PetscCall(SNESGetNPC(snes, &snes->npc)); 1158 } 1159 if (snes->npc) PetscCall(SNESSetFromOptions(snes->npc)); 1160 snes->setfromoptionscalled++; 1161 PetscFunctionReturn(0); 1162 } 1163 1164 /*@ 1165 SNESResetFromOptions - Sets various SNES and KSP parameters from user options ONLY if the SNES was previously set from options 1166 1167 Collective on SNES 1168 1169 Input Parameter: 1170 . snes - the SNES context 1171 1172 Level: beginner 1173 1174 .seealso: `SNESSetFromOptions()`, `SNESSetOptionsPrefix()` 1175 @*/ 1176 PetscErrorCode SNESResetFromOptions(SNES snes) 1177 { 1178 PetscFunctionBegin; 1179 if (snes->setfromoptionscalled) PetscCall(SNESSetFromOptions(snes)); 1180 PetscFunctionReturn(0); 1181 } 1182 1183 /*@C 1184 SNESSetComputeApplicationContext - Sets an optional function to compute a user-defined context for 1185 the nonlinear solvers. 1186 1187 Logically Collective on SNES 1188 1189 Input Parameters: 1190 + snes - the SNES context 1191 . compute - function to compute the context 1192 - destroy - function to destroy the context 1193 1194 Level: intermediate 1195 1196 Notes: 1197 This function is currently not available from Fortran. 1198 1199 .seealso: `SNESGetApplicationContext()`, `SNESSetComputeApplicationContext()`, `SNESGetApplicationContext()` 1200 @*/ 1201 PetscErrorCode SNESSetComputeApplicationContext(SNES snes,PetscErrorCode (*compute)(SNES,void**),PetscErrorCode (*destroy)(void**)) 1202 { 1203 PetscFunctionBegin; 1204 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 1205 snes->ops->usercompute = compute; 1206 snes->ops->userdestroy = destroy; 1207 PetscFunctionReturn(0); 1208 } 1209 1210 /*@ 1211 SNESSetApplicationContext - Sets the optional user-defined context for 1212 the nonlinear solvers. 1213 1214 Logically Collective on SNES 1215 1216 Input Parameters: 1217 + snes - the SNES context 1218 - usrP - optional user context 1219 1220 Level: intermediate 1221 1222 Fortran Notes: 1223 To use this from Fortran you must write a Fortran interface definition for this 1224 function that tells Fortran the Fortran derived data type that you are passing in as the ctx argument. 1225 1226 .seealso: `SNESGetApplicationContext()` 1227 @*/ 1228 PetscErrorCode SNESSetApplicationContext(SNES snes,void *usrP) 1229 { 1230 KSP ksp; 1231 1232 PetscFunctionBegin; 1233 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 1234 PetscCall(SNESGetKSP(snes,&ksp)); 1235 PetscCall(KSPSetApplicationContext(ksp,usrP)); 1236 snes->user = usrP; 1237 PetscFunctionReturn(0); 1238 } 1239 1240 /*@ 1241 SNESGetApplicationContext - Gets the user-defined context for the 1242 nonlinear solvers. 1243 1244 Not Collective 1245 1246 Input Parameter: 1247 . snes - SNES context 1248 1249 Output Parameter: 1250 . usrP - user context 1251 1252 Fortran Notes: 1253 To use this from Fortran you must write a Fortran interface definition for this 1254 function that tells Fortran the Fortran derived data type that you are passing in as the ctx argument. 1255 1256 Level: intermediate 1257 1258 .seealso: `SNESSetApplicationContext()` 1259 @*/ 1260 PetscErrorCode SNESGetApplicationContext(SNES snes,void *usrP) 1261 { 1262 PetscFunctionBegin; 1263 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 1264 *(void**)usrP = snes->user; 1265 PetscFunctionReturn(0); 1266 } 1267 1268 /*@ 1269 SNESSetUseMatrixFree - indicates that SNES should use matrix free finite difference matrix vector products internally to apply the Jacobian. 1270 1271 Collective on SNES 1272 1273 Input Parameters: 1274 + snes - SNES context 1275 . mf_operator - use matrix-free only for the Amat used by SNESSetJacobian(), this means the user provided Pmat will continue to be used 1276 - mf - use matrix-free for both the Amat and Pmat used by SNESSetJacobian(), both the Amat and Pmat set in SNESSetJacobian() will be ignored 1277 1278 Options Database: 1279 + -snes_mf - use matrix free for both the mat and pmat operator 1280 . -snes_mf_operator - use matrix free only for the mat operator 1281 . -snes_fd_color - compute the Jacobian via coloring and finite differences. 1282 - -snes_fd - compute the Jacobian via finite differences (slow) 1283 1284 Level: intermediate 1285 1286 Notes: 1287 SNES supports three approaches for computing (approximate) Jacobians: user provided via SNESSetJacobian(), matrix free, and computing explicitly with 1288 finite differences and coloring using MatFDColoring. It is also possible to use automatic differentiation and the MatFDColoring object. 1289 1290 .seealso: `SNESGetUseMatrixFree()`, `MatCreateSNESMF()`, `SNESComputeJacobianDefaultColor()` 1291 @*/ 1292 PetscErrorCode SNESSetUseMatrixFree(SNES snes,PetscBool mf_operator,PetscBool mf) 1293 { 1294 PetscFunctionBegin; 1295 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 1296 PetscValidLogicalCollectiveBool(snes,mf_operator,2); 1297 PetscValidLogicalCollectiveBool(snes,mf,3); 1298 snes->mf = mf_operator ? PETSC_TRUE : mf; 1299 snes->mf_operator = mf_operator; 1300 PetscFunctionReturn(0); 1301 } 1302 1303 /*@ 1304 SNESGetUseMatrixFree - indicates if the SNES uses matrix free finite difference matrix vector products to apply the Jacobian. 1305 1306 Collective on SNES 1307 1308 Input Parameter: 1309 . snes - SNES context 1310 1311 Output Parameters: 1312 + mf_operator - use matrix-free only for the Amat used by SNESSetJacobian(), this means the user provided Pmat will continue to be used 1313 - mf - use matrix-free for both the Amat and Pmat used by SNESSetJacobian(), both the Amat and Pmat set in SNESSetJacobian() will be ignored 1314 1315 Options Database: 1316 + -snes_mf - use matrix free for both the mat and pmat operator 1317 - -snes_mf_operator - use matrix free only for the mat operator 1318 1319 Level: intermediate 1320 1321 .seealso: `SNESSetUseMatrixFree()`, `MatCreateSNESMF()` 1322 @*/ 1323 PetscErrorCode SNESGetUseMatrixFree(SNES snes,PetscBool *mf_operator,PetscBool *mf) 1324 { 1325 PetscFunctionBegin; 1326 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 1327 if (mf) *mf = snes->mf; 1328 if (mf_operator) *mf_operator = snes->mf_operator; 1329 PetscFunctionReturn(0); 1330 } 1331 1332 /*@ 1333 SNESGetIterationNumber - Gets the number of nonlinear iterations completed 1334 at this time. 1335 1336 Not Collective 1337 1338 Input Parameter: 1339 . snes - SNES context 1340 1341 Output Parameter: 1342 . iter - iteration number 1343 1344 Notes: 1345 For example, during the computation of iteration 2 this would return 1. 1346 1347 This is useful for using lagged Jacobians (where one does not recompute the 1348 Jacobian at each SNES iteration). For example, the code 1349 .vb 1350 ierr = SNESGetIterationNumber(snes,&it); 1351 if (!(it % 2)) { 1352 [compute Jacobian here] 1353 } 1354 .ve 1355 can be used in your ComputeJacobian() function to cause the Jacobian to be 1356 recomputed every second SNES iteration. 1357 1358 After the SNES solve is complete this will return the number of nonlinear iterations used. 1359 1360 Level: intermediate 1361 1362 .seealso: `SNESGetLinearSolveIterations()` 1363 @*/ 1364 PetscErrorCode SNESGetIterationNumber(SNES snes,PetscInt *iter) 1365 { 1366 PetscFunctionBegin; 1367 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 1368 PetscValidIntPointer(iter,2); 1369 *iter = snes->iter; 1370 PetscFunctionReturn(0); 1371 } 1372 1373 /*@ 1374 SNESSetIterationNumber - Sets the current iteration number. 1375 1376 Not Collective 1377 1378 Input Parameters: 1379 + snes - SNES context 1380 - iter - iteration number 1381 1382 Level: developer 1383 1384 .seealso: `SNESGetLinearSolveIterations()` 1385 @*/ 1386 PetscErrorCode SNESSetIterationNumber(SNES snes,PetscInt iter) 1387 { 1388 PetscFunctionBegin; 1389 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 1390 PetscCall(PetscObjectSAWsTakeAccess((PetscObject)snes)); 1391 snes->iter = iter; 1392 PetscCall(PetscObjectSAWsGrantAccess((PetscObject)snes)); 1393 PetscFunctionReturn(0); 1394 } 1395 1396 /*@ 1397 SNESGetNonlinearStepFailures - Gets the number of unsuccessful steps 1398 attempted by the nonlinear solver. 1399 1400 Not Collective 1401 1402 Input Parameter: 1403 . snes - SNES context 1404 1405 Output Parameter: 1406 . nfails - number of unsuccessful steps attempted 1407 1408 Notes: 1409 This counter is reset to zero for each successive call to SNESSolve(). 1410 1411 Level: intermediate 1412 1413 .seealso: `SNESGetMaxLinearSolveFailures()`, `SNESGetLinearSolveIterations()`, `SNESSetMaxLinearSolveFailures()`, `SNESGetLinearSolveFailures()`, 1414 `SNESSetMaxNonlinearStepFailures()`, `SNESGetMaxNonlinearStepFailures()` 1415 @*/ 1416 PetscErrorCode SNESGetNonlinearStepFailures(SNES snes,PetscInt *nfails) 1417 { 1418 PetscFunctionBegin; 1419 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 1420 PetscValidIntPointer(nfails,2); 1421 *nfails = snes->numFailures; 1422 PetscFunctionReturn(0); 1423 } 1424 1425 /*@ 1426 SNESSetMaxNonlinearStepFailures - Sets the maximum number of unsuccessful steps 1427 attempted by the nonlinear solver before it gives up. 1428 1429 Not Collective 1430 1431 Input Parameters: 1432 + snes - SNES context 1433 - maxFails - maximum of unsuccessful steps 1434 1435 Level: intermediate 1436 1437 .seealso: `SNESGetMaxLinearSolveFailures()`, `SNESGetLinearSolveIterations()`, `SNESSetMaxLinearSolveFailures()`, `SNESGetLinearSolveFailures()`, 1438 `SNESGetMaxNonlinearStepFailures()`, `SNESGetNonlinearStepFailures()` 1439 @*/ 1440 PetscErrorCode SNESSetMaxNonlinearStepFailures(SNES snes, PetscInt maxFails) 1441 { 1442 PetscFunctionBegin; 1443 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 1444 snes->maxFailures = maxFails; 1445 PetscFunctionReturn(0); 1446 } 1447 1448 /*@ 1449 SNESGetMaxNonlinearStepFailures - Gets the maximum number of unsuccessful steps 1450 attempted by the nonlinear solver before it gives up. 1451 1452 Not Collective 1453 1454 Input Parameter: 1455 . snes - SNES context 1456 1457 Output Parameter: 1458 . maxFails - maximum of unsuccessful steps 1459 1460 Level: intermediate 1461 1462 .seealso: `SNESGetMaxLinearSolveFailures()`, `SNESGetLinearSolveIterations()`, `SNESSetMaxLinearSolveFailures()`, `SNESGetLinearSolveFailures()`, 1463 `SNESSetMaxNonlinearStepFailures()`, `SNESGetNonlinearStepFailures()` 1464 1465 @*/ 1466 PetscErrorCode SNESGetMaxNonlinearStepFailures(SNES snes, PetscInt *maxFails) 1467 { 1468 PetscFunctionBegin; 1469 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 1470 PetscValidIntPointer(maxFails,2); 1471 *maxFails = snes->maxFailures; 1472 PetscFunctionReturn(0); 1473 } 1474 1475 /*@ 1476 SNESGetNumberFunctionEvals - Gets the number of user provided function evaluations 1477 done by SNES. 1478 1479 Not Collective 1480 1481 Input Parameter: 1482 . snes - SNES context 1483 1484 Output Parameter: 1485 . nfuncs - number of evaluations 1486 1487 Level: intermediate 1488 1489 Notes: 1490 Reset every time SNESSolve is called unless SNESSetCountersReset() is used. 1491 1492 .seealso: `SNESGetMaxLinearSolveFailures()`, `SNESGetLinearSolveIterations()`, `SNESSetMaxLinearSolveFailures()`, `SNESGetLinearSolveFailures()`, `SNESSetCountersReset()` 1493 @*/ 1494 PetscErrorCode SNESGetNumberFunctionEvals(SNES snes, PetscInt *nfuncs) 1495 { 1496 PetscFunctionBegin; 1497 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 1498 PetscValidIntPointer(nfuncs,2); 1499 *nfuncs = snes->nfuncs; 1500 PetscFunctionReturn(0); 1501 } 1502 1503 /*@ 1504 SNESGetLinearSolveFailures - Gets the number of failed (non-converged) 1505 linear solvers. 1506 1507 Not Collective 1508 1509 Input Parameter: 1510 . snes - SNES context 1511 1512 Output Parameter: 1513 . nfails - number of failed solves 1514 1515 Level: intermediate 1516 1517 Options Database Keys: 1518 . -snes_max_linear_solve_fail <num> - The number of failures before the solve is terminated 1519 1520 Notes: 1521 This counter is reset to zero for each successive call to SNESSolve(). 1522 1523 .seealso: `SNESGetMaxLinearSolveFailures()`, `SNESGetLinearSolveIterations()`, `SNESSetMaxLinearSolveFailures()` 1524 @*/ 1525 PetscErrorCode SNESGetLinearSolveFailures(SNES snes,PetscInt *nfails) 1526 { 1527 PetscFunctionBegin; 1528 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 1529 PetscValidIntPointer(nfails,2); 1530 *nfails = snes->numLinearSolveFailures; 1531 PetscFunctionReturn(0); 1532 } 1533 1534 /*@ 1535 SNESSetMaxLinearSolveFailures - the number of failed linear solve attempts 1536 allowed before SNES returns with a diverged reason of SNES_DIVERGED_LINEAR_SOLVE 1537 1538 Logically Collective on SNES 1539 1540 Input Parameters: 1541 + snes - SNES context 1542 - maxFails - maximum allowed linear solve failures 1543 1544 Level: intermediate 1545 1546 Options Database Keys: 1547 . -snes_max_linear_solve_fail <num> - The number of failures before the solve is terminated 1548 1549 Notes: 1550 By default this is 0; that is SNES returns on the first failed linear solve 1551 1552 .seealso: `SNESGetLinearSolveFailures()`, `SNESGetMaxLinearSolveFailures()`, `SNESGetLinearSolveIterations()` 1553 @*/ 1554 PetscErrorCode SNESSetMaxLinearSolveFailures(SNES snes, PetscInt maxFails) 1555 { 1556 PetscFunctionBegin; 1557 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 1558 PetscValidLogicalCollectiveInt(snes,maxFails,2); 1559 snes->maxLinearSolveFailures = maxFails; 1560 PetscFunctionReturn(0); 1561 } 1562 1563 /*@ 1564 SNESGetMaxLinearSolveFailures - gets the maximum number of linear solve failures that 1565 are allowed before SNES terminates 1566 1567 Not Collective 1568 1569 Input Parameter: 1570 . snes - SNES context 1571 1572 Output Parameter: 1573 . maxFails - maximum of unsuccessful solves allowed 1574 1575 Level: intermediate 1576 1577 Notes: 1578 By default this is 1; that is SNES returns on the first failed linear solve 1579 1580 .seealso: `SNESGetLinearSolveFailures()`, `SNESGetLinearSolveIterations()`, `SNESSetMaxLinearSolveFailures()`, 1581 @*/ 1582 PetscErrorCode SNESGetMaxLinearSolveFailures(SNES snes, PetscInt *maxFails) 1583 { 1584 PetscFunctionBegin; 1585 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 1586 PetscValidIntPointer(maxFails,2); 1587 *maxFails = snes->maxLinearSolveFailures; 1588 PetscFunctionReturn(0); 1589 } 1590 1591 /*@ 1592 SNESGetLinearSolveIterations - Gets the total number of linear iterations 1593 used by the nonlinear solver. 1594 1595 Not Collective 1596 1597 Input Parameter: 1598 . snes - SNES context 1599 1600 Output Parameter: 1601 . lits - number of linear iterations 1602 1603 Notes: 1604 This counter is reset to zero for each successive call to SNESSolve() unless SNESSetCountersReset() is used. 1605 1606 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 1607 then call KSPGetIterationNumber() after the failed solve. 1608 1609 Level: intermediate 1610 1611 .seealso: `SNESGetIterationNumber()`, `SNESGetLinearSolveFailures()`, `SNESGetMaxLinearSolveFailures()`, `SNESSetCountersReset()` 1612 @*/ 1613 PetscErrorCode SNESGetLinearSolveIterations(SNES snes,PetscInt *lits) 1614 { 1615 PetscFunctionBegin; 1616 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 1617 PetscValidIntPointer(lits,2); 1618 *lits = snes->linear_its; 1619 PetscFunctionReturn(0); 1620 } 1621 1622 /*@ 1623 SNESSetCountersReset - Sets whether or not the counters for linear iterations and function evaluations 1624 are reset every time SNESSolve() is called. 1625 1626 Logically Collective on SNES 1627 1628 Input Parameters: 1629 + snes - SNES context 1630 - reset - whether to reset the counters or not 1631 1632 Notes: 1633 This defaults to PETSC_TRUE 1634 1635 Level: developer 1636 1637 .seealso: `SNESGetNumberFunctionEvals()`, `SNESGetLinearSolveIterations()`, `SNESGetNPC()` 1638 @*/ 1639 PetscErrorCode SNESSetCountersReset(SNES snes,PetscBool reset) 1640 { 1641 PetscFunctionBegin; 1642 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 1643 PetscValidLogicalCollectiveBool(snes,reset,2); 1644 snes->counters_reset = reset; 1645 PetscFunctionReturn(0); 1646 } 1647 1648 /*@ 1649 SNESSetKSP - Sets a KSP context for the SNES object to use 1650 1651 Not Collective, but the SNES and KSP objects must live on the same MPI_Comm 1652 1653 Input Parameters: 1654 + snes - the SNES context 1655 - ksp - the KSP context 1656 1657 Notes: 1658 The SNES object already has its KSP object, you can obtain with SNESGetKSP() 1659 so this routine is rarely needed. 1660 1661 The KSP object that is already in the SNES object has its reference count 1662 decreased by one. 1663 1664 Level: developer 1665 1666 .seealso: `KSPGetPC()`, `SNESCreate()`, `KSPCreate()`, `SNESSetKSP()` 1667 @*/ 1668 PetscErrorCode SNESSetKSP(SNES snes,KSP ksp) 1669 { 1670 PetscFunctionBegin; 1671 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 1672 PetscValidHeaderSpecific(ksp,KSP_CLASSID,2); 1673 PetscCheckSameComm(snes,1,ksp,2); 1674 PetscCall(PetscObjectReference((PetscObject)ksp)); 1675 if (snes->ksp) PetscCall(PetscObjectDereference((PetscObject)snes->ksp)); 1676 snes->ksp = ksp; 1677 PetscFunctionReturn(0); 1678 } 1679 1680 /* -----------------------------------------------------------*/ 1681 /*@ 1682 SNESCreate - Creates a nonlinear solver context. 1683 1684 Collective 1685 1686 Input Parameters: 1687 . comm - MPI communicator 1688 1689 Output Parameter: 1690 . outsnes - the new SNES context 1691 1692 Options Database Keys: 1693 + -snes_mf - Activates default matrix-free Jacobian-vector products, 1694 and no preconditioning matrix 1695 . -snes_mf_operator - Activates default matrix-free Jacobian-vector 1696 products, and a user-provided preconditioning matrix 1697 as set by SNESSetJacobian() 1698 - -snes_fd - Uses (slow!) finite differences to compute Jacobian 1699 1700 Level: beginner 1701 1702 Developer Notes: 1703 SNES always creates a KSP object even though many SNES methods do not use it. This is 1704 unfortunate and should be fixed at some point. The flag snes->usesksp indicates if the 1705 particular method does use KSP and regulates if the information about the KSP is printed 1706 in SNESView(). TSSetFromOptions() does call SNESSetFromOptions() which can lead to users being confused 1707 by help messages about meaningless SNES options. 1708 1709 SNES always creates the snes->kspconvctx even though it is used by only one type. This should 1710 be fixed. 1711 1712 .seealso: `SNESSolve()`, `SNESDestroy()`, `SNES`, `SNESSetLagPreconditioner()`, `SNESSetLagJacobian()` 1713 1714 @*/ 1715 PetscErrorCode SNESCreate(MPI_Comm comm,SNES *outsnes) 1716 { 1717 SNES snes; 1718 SNESKSPEW *kctx; 1719 1720 PetscFunctionBegin; 1721 PetscValidPointer(outsnes,2); 1722 *outsnes = NULL; 1723 PetscCall(SNESInitializePackage()); 1724 1725 PetscCall(PetscHeaderCreate(snes,SNES_CLASSID,"SNES","Nonlinear solver","SNES",comm,SNESDestroy,SNESView)); 1726 1727 snes->ops->converged = SNESConvergedDefault; 1728 snes->usesksp = PETSC_TRUE; 1729 snes->tolerancesset = PETSC_FALSE; 1730 snes->max_its = 50; 1731 snes->max_funcs = 10000; 1732 snes->norm = 0.0; 1733 snes->xnorm = 0.0; 1734 snes->ynorm = 0.0; 1735 snes->normschedule = SNES_NORM_ALWAYS; 1736 snes->functype = SNES_FUNCTION_DEFAULT; 1737 #if defined(PETSC_USE_REAL_SINGLE) 1738 snes->rtol = 1.e-5; 1739 #else 1740 snes->rtol = 1.e-8; 1741 #endif 1742 snes->ttol = 0.0; 1743 #if defined(PETSC_USE_REAL_SINGLE) 1744 snes->abstol = 1.e-25; 1745 #else 1746 snes->abstol = 1.e-50; 1747 #endif 1748 #if defined(PETSC_USE_REAL_SINGLE) 1749 snes->stol = 1.e-5; 1750 #else 1751 snes->stol = 1.e-8; 1752 #endif 1753 #if defined(PETSC_USE_REAL_SINGLE) 1754 snes->deltatol = 1.e-6; 1755 #else 1756 snes->deltatol = 1.e-12; 1757 #endif 1758 snes->divtol = 1.e4; 1759 snes->rnorm0 = 0; 1760 snes->nfuncs = 0; 1761 snes->numFailures = 0; 1762 snes->maxFailures = 1; 1763 snes->linear_its = 0; 1764 snes->lagjacobian = 1; 1765 snes->jac_iter = 0; 1766 snes->lagjac_persist = PETSC_FALSE; 1767 snes->lagpreconditioner = 1; 1768 snes->pre_iter = 0; 1769 snes->lagpre_persist = PETSC_FALSE; 1770 snes->numbermonitors = 0; 1771 snes->numberreasonviews = 0; 1772 snes->data = NULL; 1773 snes->setupcalled = PETSC_FALSE; 1774 snes->ksp_ewconv = PETSC_FALSE; 1775 snes->nwork = 0; 1776 snes->work = NULL; 1777 snes->nvwork = 0; 1778 snes->vwork = NULL; 1779 snes->conv_hist_len = 0; 1780 snes->conv_hist_max = 0; 1781 snes->conv_hist = NULL; 1782 snes->conv_hist_its = NULL; 1783 snes->conv_hist_reset = PETSC_TRUE; 1784 snes->counters_reset = PETSC_TRUE; 1785 snes->vec_func_init_set = PETSC_FALSE; 1786 snes->reason = SNES_CONVERGED_ITERATING; 1787 snes->npcside = PC_RIGHT; 1788 snes->setfromoptionscalled = 0; 1789 1790 snes->mf = PETSC_FALSE; 1791 snes->mf_operator = PETSC_FALSE; 1792 snes->mf_version = 1; 1793 1794 snes->numLinearSolveFailures = 0; 1795 snes->maxLinearSolveFailures = 1; 1796 1797 snes->vizerotolerance = 1.e-8; 1798 snes->checkjacdomainerror = PetscDefined(USE_DEBUG) ? PETSC_TRUE : PETSC_FALSE; 1799 1800 /* Set this to true if the implementation of SNESSolve_XXX does compute the residual at the final solution. */ 1801 snes->alwayscomputesfinalresidual = PETSC_FALSE; 1802 1803 /* Create context to compute Eisenstat-Walker relative tolerance for KSP */ 1804 PetscCall(PetscNewLog(snes,&kctx)); 1805 1806 snes->kspconvctx = (void*)kctx; 1807 kctx->version = 2; 1808 kctx->rtol_0 = 0.3; /* Eisenstat and Walker suggest rtol_0=.5, but 1809 this was too large for some test cases */ 1810 kctx->rtol_last = 0.0; 1811 kctx->rtol_max = 0.9; 1812 kctx->gamma = 1.0; 1813 kctx->alpha = 0.5*(1.0 + PetscSqrtReal(5.0)); 1814 kctx->alpha2 = kctx->alpha; 1815 kctx->threshold = 0.1; 1816 kctx->lresid_last = 0.0; 1817 kctx->norm_last = 0.0; 1818 1819 kctx->rk_last = 0.0; 1820 kctx->rk_last_2 = 0.0; 1821 kctx->rtol_last_2 = 0.0; 1822 kctx->v4_p1 = 0.1; 1823 kctx->v4_p2 = 0.4; 1824 kctx->v4_p3 = 0.7; 1825 kctx->v4_m1 = 0.8; 1826 kctx->v4_m2 = 0.5; 1827 kctx->v4_m3 = 0.1; 1828 kctx->v4_m4 = 0.5; 1829 1830 *outsnes = snes; 1831 PetscFunctionReturn(0); 1832 } 1833 1834 /*MC 1835 SNESFunction - Functional form used to convey the nonlinear function to be solved by SNES 1836 1837 Synopsis: 1838 #include "petscsnes.h" 1839 PetscErrorCode SNESFunction(SNES snes,Vec x,Vec f,void *ctx); 1840 1841 Collective on snes 1842 1843 Input Parameters: 1844 + snes - the SNES context 1845 . x - state at which to evaluate residual 1846 - ctx - optional user-defined function context, passed in with SNESSetFunction() 1847 1848 Output Parameter: 1849 . f - vector to put residual (function value) 1850 1851 Level: intermediate 1852 1853 .seealso: `SNESSetFunction()`, `SNESGetFunction()` 1854 M*/ 1855 1856 /*@C 1857 SNESSetFunction - Sets the function evaluation routine and function 1858 vector for use by the SNES routines in solving systems of nonlinear 1859 equations. 1860 1861 Logically Collective on SNES 1862 1863 Input Parameters: 1864 + snes - the SNES context 1865 . r - vector to store function values, may be NULL 1866 . f - function evaluation routine; see SNESFunction for calling sequence details 1867 - ctx - [optional] user-defined context for private data for the 1868 function evaluation routine (may be NULL) 1869 1870 Notes: 1871 The Newton-like methods typically solve linear systems of the form 1872 $ f'(x) x = -f(x), 1873 where f'(x) denotes the Jacobian matrix and f(x) is the function. 1874 1875 Level: beginner 1876 1877 .seealso: `SNESGetFunction()`, `SNESComputeFunction()`, `SNESSetJacobian()`, `SNESSetPicard()`, `SNESFunction` 1878 @*/ 1879 PetscErrorCode SNESSetFunction(SNES snes,Vec r,PetscErrorCode (*f)(SNES,Vec,Vec,void*),void *ctx) 1880 { 1881 DM dm; 1882 1883 PetscFunctionBegin; 1884 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 1885 if (r) { 1886 PetscValidHeaderSpecific(r,VEC_CLASSID,2); 1887 PetscCheckSameComm(snes,1,r,2); 1888 PetscCall(PetscObjectReference((PetscObject)r)); 1889 PetscCall(VecDestroy(&snes->vec_func)); 1890 snes->vec_func = r; 1891 } 1892 PetscCall(SNESGetDM(snes,&dm)); 1893 PetscCall(DMSNESSetFunction(dm,f,ctx)); 1894 if (f == SNESPicardComputeFunction) { 1895 PetscCall(DMSNESSetMFFunction(dm,SNESPicardComputeMFFunction,ctx)); 1896 } 1897 PetscFunctionReturn(0); 1898 } 1899 1900 /*@C 1901 SNESSetInitialFunction - Sets the function vector to be used as the 1902 function norm at the initialization of the method. In some 1903 instances, the user has precomputed the function before calling 1904 SNESSolve. This function allows one to avoid a redundant call 1905 to SNESComputeFunction in that case. 1906 1907 Logically Collective on SNES 1908 1909 Input Parameters: 1910 + snes - the SNES context 1911 - f - vector to store function value 1912 1913 Notes: 1914 This should not be modified during the solution procedure. 1915 1916 This is used extensively in the SNESFAS hierarchy and in nonlinear preconditioning. 1917 1918 Level: developer 1919 1920 .seealso: `SNESSetFunction()`, `SNESComputeFunction()`, `SNESSetInitialFunctionNorm()` 1921 @*/ 1922 PetscErrorCode SNESSetInitialFunction(SNES snes, Vec f) 1923 { 1924 Vec vec_func; 1925 1926 PetscFunctionBegin; 1927 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 1928 PetscValidHeaderSpecific(f,VEC_CLASSID,2); 1929 PetscCheckSameComm(snes,1,f,2); 1930 if (snes->npcside == PC_LEFT && snes->functype == SNES_FUNCTION_PRECONDITIONED) { 1931 snes->vec_func_init_set = PETSC_FALSE; 1932 PetscFunctionReturn(0); 1933 } 1934 PetscCall(SNESGetFunction(snes,&vec_func,NULL,NULL)); 1935 PetscCall(VecCopy(f,vec_func)); 1936 1937 snes->vec_func_init_set = PETSC_TRUE; 1938 PetscFunctionReturn(0); 1939 } 1940 1941 /*@ 1942 SNESSetNormSchedule - Sets the SNESNormSchedule used in convergence and monitoring 1943 of the SNES method. 1944 1945 Logically Collective on SNES 1946 1947 Input Parameters: 1948 + snes - the SNES context 1949 - normschedule - the frequency of norm computation 1950 1951 Options Database Key: 1952 . -snes_norm_schedule <none, always, initialonly, finalonly, initialfinalonly> - set the schedule 1953 1954 Notes: 1955 Only certain SNES methods support certain SNESNormSchedules. Most require evaluation 1956 of the nonlinear function and the taking of its norm at every iteration to 1957 even ensure convergence at all. However, methods such as custom Gauss-Seidel methods 1958 (SNESNGS) and the like do not require the norm of the function to be computed, and therefore 1959 may either be monitored for convergence or not. As these are often used as nonlinear 1960 preconditioners, monitoring the norm of their error is not a useful enterprise within 1961 their solution. 1962 1963 Level: developer 1964 1965 .seealso: `SNESGetNormSchedule()`, `SNESComputeFunction()`, `VecNorm()`, `SNESSetFunction()`, `SNESSetInitialFunction()`, `SNESNormSchedule` 1966 @*/ 1967 PetscErrorCode SNESSetNormSchedule(SNES snes, SNESNormSchedule normschedule) 1968 { 1969 PetscFunctionBegin; 1970 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 1971 snes->normschedule = normschedule; 1972 PetscFunctionReturn(0); 1973 } 1974 1975 /*@ 1976 SNESGetNormSchedule - Gets the SNESNormSchedule used in convergence and monitoring 1977 of the SNES method. 1978 1979 Logically Collective on SNES 1980 1981 Input Parameters: 1982 + snes - the SNES context 1983 - normschedule - the type of the norm used 1984 1985 Level: advanced 1986 1987 .seealso: `SNESSetNormSchedule()`, `SNESComputeFunction()`, `VecNorm()`, `SNESSetFunction()`, `SNESSetInitialFunction()`, `SNESNormSchedule` 1988 @*/ 1989 PetscErrorCode SNESGetNormSchedule(SNES snes, SNESNormSchedule *normschedule) 1990 { 1991 PetscFunctionBegin; 1992 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 1993 *normschedule = snes->normschedule; 1994 PetscFunctionReturn(0); 1995 } 1996 1997 /*@ 1998 SNESSetFunctionNorm - Sets the last computed residual norm. 1999 2000 Logically Collective on SNES 2001 2002 Input Parameters: 2003 + snes - the SNES context 2004 2005 - normschedule - the frequency of norm computation 2006 2007 Level: developer 2008 2009 .seealso: `SNESGetNormSchedule()`, `SNESComputeFunction()`, `VecNorm()`, `SNESSetFunction()`, `SNESSetInitialFunction()`, `SNESNormSchedule` 2010 @*/ 2011 PetscErrorCode SNESSetFunctionNorm(SNES snes, PetscReal norm) 2012 { 2013 PetscFunctionBegin; 2014 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 2015 snes->norm = norm; 2016 PetscFunctionReturn(0); 2017 } 2018 2019 /*@ 2020 SNESGetFunctionNorm - Gets the last computed norm of the residual 2021 2022 Not Collective 2023 2024 Input Parameter: 2025 . snes - the SNES context 2026 2027 Output Parameter: 2028 . norm - the last computed residual norm 2029 2030 Level: developer 2031 2032 .seealso: `SNESSetNormSchedule()`, `SNESComputeFunction()`, `VecNorm()`, `SNESSetFunction()`, `SNESSetInitialFunction()`, `SNESNormSchedule` 2033 @*/ 2034 PetscErrorCode SNESGetFunctionNorm(SNES snes, PetscReal *norm) 2035 { 2036 PetscFunctionBegin; 2037 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 2038 PetscValidRealPointer(norm, 2); 2039 *norm = snes->norm; 2040 PetscFunctionReturn(0); 2041 } 2042 2043 /*@ 2044 SNESGetUpdateNorm - Gets the last computed norm of the Newton update 2045 2046 Not Collective 2047 2048 Input Parameter: 2049 . snes - the SNES context 2050 2051 Output Parameter: 2052 . ynorm - the last computed update norm 2053 2054 Level: developer 2055 2056 .seealso: `SNESSetNormSchedule()`, `SNESComputeFunction()`, `SNESGetFunctionNorm()` 2057 @*/ 2058 PetscErrorCode SNESGetUpdateNorm(SNES snes, PetscReal *ynorm) 2059 { 2060 PetscFunctionBegin; 2061 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 2062 PetscValidRealPointer(ynorm, 2); 2063 *ynorm = snes->ynorm; 2064 PetscFunctionReturn(0); 2065 } 2066 2067 /*@ 2068 SNESGetSolutionNorm - Gets the last computed norm of the solution 2069 2070 Not Collective 2071 2072 Input Parameter: 2073 . snes - the SNES context 2074 2075 Output Parameter: 2076 . xnorm - the last computed solution norm 2077 2078 Level: developer 2079 2080 .seealso: `SNESSetNormSchedule()`, `SNESComputeFunction()`, `SNESGetFunctionNorm()`, `SNESGetUpdateNorm()` 2081 @*/ 2082 PetscErrorCode SNESGetSolutionNorm(SNES snes, PetscReal *xnorm) 2083 { 2084 PetscFunctionBegin; 2085 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 2086 PetscValidRealPointer(xnorm, 2); 2087 *xnorm = snes->xnorm; 2088 PetscFunctionReturn(0); 2089 } 2090 2091 /*@C 2092 SNESSetFunctionType - Sets the SNESNormSchedule used in convergence and monitoring 2093 of the SNES method. 2094 2095 Logically Collective on SNES 2096 2097 Input Parameters: 2098 + snes - the SNES context 2099 - normschedule - the frequency of norm computation 2100 2101 Notes: 2102 Only certain SNES methods support certain SNESNormSchedules. Most require evaluation 2103 of the nonlinear function and the taking of its norm at every iteration to 2104 even ensure convergence at all. However, methods such as custom Gauss-Seidel methods 2105 (SNESNGS) and the like do not require the norm of the function to be computed, and therefore 2106 may either be monitored for convergence or not. As these are often used as nonlinear 2107 preconditioners, monitoring the norm of their error is not a useful enterprise within 2108 their solution. 2109 2110 Level: developer 2111 2112 .seealso: `SNESGetNormSchedule()`, `SNESComputeFunction()`, `VecNorm()`, `SNESSetFunction()`, `SNESSetInitialFunction()`, `SNESNormSchedule` 2113 @*/ 2114 PetscErrorCode SNESSetFunctionType(SNES snes, SNESFunctionType type) 2115 { 2116 PetscFunctionBegin; 2117 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 2118 snes->functype = type; 2119 PetscFunctionReturn(0); 2120 } 2121 2122 /*@C 2123 SNESGetFunctionType - Gets the SNESNormSchedule used in convergence and monitoring 2124 of the SNES method. 2125 2126 Logically Collective on SNES 2127 2128 Input Parameters: 2129 + snes - the SNES context 2130 - normschedule - the type of the norm used 2131 2132 Level: advanced 2133 2134 .seealso: `SNESSetNormSchedule()`, `SNESComputeFunction()`, `VecNorm()`, `SNESSetFunction()`, `SNESSetInitialFunction()`, `SNESNormSchedule` 2135 @*/ 2136 PetscErrorCode SNESGetFunctionType(SNES snes, SNESFunctionType *type) 2137 { 2138 PetscFunctionBegin; 2139 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 2140 *type = snes->functype; 2141 PetscFunctionReturn(0); 2142 } 2143 2144 /*MC 2145 SNESNGSFunction - function used to convey a Gauss-Seidel sweep on the nonlinear function 2146 2147 Synopsis: 2148 #include <petscsnes.h> 2149 $ SNESNGSFunction(SNES snes,Vec x,Vec b,void *ctx); 2150 2151 Collective on snes 2152 2153 Input Parameters: 2154 + X - solution vector 2155 . B - RHS vector 2156 - ctx - optional user-defined Gauss-Seidel context 2157 2158 Output Parameter: 2159 . X - solution vector 2160 2161 Level: intermediate 2162 2163 .seealso: `SNESSetNGS()`, `SNESGetNGS()` 2164 M*/ 2165 2166 /*@C 2167 SNESSetNGS - Sets the user nonlinear Gauss-Seidel routine for 2168 use with composed nonlinear solvers. 2169 2170 Input Parameters: 2171 + snes - the SNES context 2172 . f - function evaluation routine to apply Gauss-Seidel see SNESNGSFunction 2173 - ctx - [optional] user-defined context for private data for the 2174 smoother evaluation routine (may be NULL) 2175 2176 Notes: 2177 The NGS routines are used by the composed nonlinear solver to generate 2178 a problem appropriate update to the solution, particularly FAS. 2179 2180 Level: intermediate 2181 2182 .seealso: `SNESGetFunction()`, `SNESComputeNGS()` 2183 @*/ 2184 PetscErrorCode SNESSetNGS(SNES snes,PetscErrorCode (*f)(SNES,Vec,Vec,void*),void *ctx) 2185 { 2186 DM dm; 2187 2188 PetscFunctionBegin; 2189 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 2190 PetscCall(SNESGetDM(snes,&dm)); 2191 PetscCall(DMSNESSetNGS(dm,f,ctx)); 2192 PetscFunctionReturn(0); 2193 } 2194 2195 /* 2196 This is used for -snes_mf_operator; it uses a duplicate of snes->jacobian_pre because snes->jacobian_pre cannot be 2197 changed during the KSPSolve() 2198 */ 2199 PetscErrorCode SNESPicardComputeMFFunction(SNES snes,Vec x,Vec f,void *ctx) 2200 { 2201 DM dm; 2202 DMSNES sdm; 2203 2204 PetscFunctionBegin; 2205 PetscCall(SNESGetDM(snes,&dm)); 2206 PetscCall(DMGetDMSNES(dm,&sdm)); 2207 /* A(x)*x - b(x) */ 2208 if (sdm->ops->computepfunction) { 2209 PetscCallBack("SNES Picard callback function",(*sdm->ops->computepfunction)(snes,x,f,sdm->pctx)); 2210 PetscCall(VecScale(f,-1.0)); 2211 /* Cannot share nonzero pattern because of the possible use of SNESComputeJacobianDefault() */ 2212 if (!snes->picard) PetscCall(MatDuplicate(snes->jacobian_pre,MAT_DO_NOT_COPY_VALUES,&snes->picard)); 2213 PetscCallBack("SNES Picard callback Jacobian",(*sdm->ops->computepjacobian)(snes,x,snes->picard,snes->picard,sdm->pctx)); 2214 PetscCall(MatMultAdd(snes->picard,x,f,f)); 2215 } else { 2216 PetscCallBack("SNES Picard callback Jacobian",(*sdm->ops->computepjacobian)(snes,x,snes->picard,snes->picard,sdm->pctx)); 2217 PetscCall(MatMult(snes->picard,x,f)); 2218 } 2219 PetscFunctionReturn(0); 2220 } 2221 2222 PetscErrorCode SNESPicardComputeFunction(SNES snes,Vec x,Vec f,void *ctx) 2223 { 2224 DM dm; 2225 DMSNES sdm; 2226 2227 PetscFunctionBegin; 2228 PetscCall(SNESGetDM(snes,&dm)); 2229 PetscCall(DMGetDMSNES(dm,&sdm)); 2230 /* A(x)*x - b(x) */ 2231 if (sdm->ops->computepfunction) { 2232 PetscCallBack("SNES Picard callback function",(*sdm->ops->computepfunction)(snes,x,f,sdm->pctx)); 2233 PetscCall(VecScale(f,-1.0)); 2234 PetscCallBack("SNES Picard callback Jacobian",(*sdm->ops->computepjacobian)(snes,x,snes->jacobian,snes->jacobian_pre,sdm->pctx)); 2235 PetscCall(MatMultAdd(snes->jacobian_pre,x,f,f)); 2236 } else { 2237 PetscCallBack("SNES Picard callback Jacobian",(*sdm->ops->computepjacobian)(snes,x,snes->jacobian,snes->jacobian_pre,sdm->pctx)); 2238 PetscCall(MatMult(snes->jacobian_pre,x,f)); 2239 } 2240 PetscFunctionReturn(0); 2241 } 2242 2243 PetscErrorCode SNESPicardComputeJacobian(SNES snes,Vec x1,Mat J,Mat B,void *ctx) 2244 { 2245 PetscFunctionBegin; 2246 /* the jacobian matrix should be pre-filled in SNESPicardComputeFunction */ 2247 /* must assembly if matrix-free to get the last SNES solution */ 2248 PetscCall(MatAssemblyBegin(J,MAT_FINAL_ASSEMBLY)); 2249 PetscCall(MatAssemblyEnd(J,MAT_FINAL_ASSEMBLY)); 2250 PetscFunctionReturn(0); 2251 } 2252 2253 /*@C 2254 SNESSetPicard - Use SNES to solve the system A(x) x = bp(x) + b via a Picard type iteration (Picard linearization) 2255 2256 Logically Collective on SNES 2257 2258 Input Parameters: 2259 + snes - the SNES context 2260 . r - vector to store function values, may be NULL 2261 . bp - function evaluation routine, may be NULL 2262 . Amat - matrix with which A(x) x - bp(x) - b is to be computed 2263 . Pmat - matrix from which preconditioner is computed (usually the same as Amat) 2264 . J - function to compute matrix values, see SNESJacobianFunction() for details on its calling sequence 2265 - ctx - [optional] user-defined context for private data for the function evaluation routine (may be NULL) 2266 2267 Notes: 2268 It is often better to provide the nonlinear function F() and some approximation to its Jacobian directly and use 2269 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. 2270 2271 One can call SNESSetPicard() or SNESSetFunction() (and possibly SNESSetJacobian()) but cannot call both 2272 2273 $ Solves the equation A(x) x = bp(x) - b via the defect correction algorithm A(x^{n}) (x^{n+1} - x^{n}) = bp(x^{n}) + b - A(x^{n})x^{n} 2274 $ Note that when an exact solver is used this corresponds to the "classic" Picard A(x^{n}) x^{n+1} = bp(x^{n}) + b iteration. 2275 2276 Run with -snes_mf_operator to solve the system with Newton's method using A(x^{n}) to construct the preconditioner. 2277 2278 We implement the defect correction form of the Picard iteration because it converges much more generally when inexact linear solvers are used then 2279 the direct Picard iteration A(x^n) x^{n+1} = bp(x^n) + b 2280 2281 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 2282 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 2283 different please contact us at petsc-dev@mcs.anl.gov and we'll have an entirely new argument :-). 2284 2285 When used with -snes_mf_operator this will run matrix-free Newton's method where the matrix-vector product is of the true Jacobian of A(x)x - bp(x) -b. 2286 2287 When used with -snes_fd this will compute the true Jacobian (very slowly one column at at time) and thus represent Newton's method. 2288 2289 When used with -snes_fd_coloring this will compute the Jacobian via coloring and thus represent a faster implementation of Newton's method. But the 2290 the nonzero structure of the Jacobian is, in general larger than that of the Picard matrix A so you must provide in A the needed nonzero structure for the correct 2291 coloring. When using DMDA this may mean creating the matrix A with DMCreateMatrix() using a wider stencil than strictly needed for A or with a DMDA_STENCIL_BOX. 2292 See the commment in src/snes/tutorials/ex15.c. 2293 2294 Level: intermediate 2295 2296 .seealso: `SNESGetFunction()`, `SNESSetFunction()`, `SNESComputeFunction()`, `SNESSetJacobian()`, `SNESGetPicard()`, `SNESLineSearchPreCheckPicard()`, `SNESJacobianFunction` 2297 @*/ 2298 PetscErrorCode SNESSetPicard(SNES snes,Vec r,PetscErrorCode (*bp)(SNES,Vec,Vec,void*),Mat Amat, Mat Pmat, PetscErrorCode (*J)(SNES,Vec,Mat,Mat,void*),void *ctx) 2299 { 2300 DM dm; 2301 2302 PetscFunctionBegin; 2303 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 2304 PetscCall(SNESGetDM(snes, &dm)); 2305 PetscCall(DMSNESSetPicard(dm,bp,J,ctx)); 2306 PetscCall(DMSNESSetMFFunction(dm,SNESPicardComputeMFFunction,ctx)); 2307 PetscCall(SNESSetFunction(snes,r,SNESPicardComputeFunction,ctx)); 2308 PetscCall(SNESSetJacobian(snes,Amat,Pmat,SNESPicardComputeJacobian,ctx)); 2309 PetscFunctionReturn(0); 2310 } 2311 2312 /*@C 2313 SNESGetPicard - Returns the context for the Picard iteration 2314 2315 Not Collective, but Vec is parallel if SNES is parallel. Collective if Vec is requested, but has not been created yet. 2316 2317 Input Parameter: 2318 . snes - the SNES context 2319 2320 Output Parameters: 2321 + r - the function (or NULL) 2322 . f - the function (or NULL); see SNESFunction for calling sequence details 2323 . Amat - the matrix used to defined the operation A(x) x - b(x) (or NULL) 2324 . Pmat - the matrix from which the preconditioner will be constructed (or NULL) 2325 . J - the function for matrix evaluation (or NULL); see SNESJacobianFunction for calling sequence details 2326 - ctx - the function context (or NULL) 2327 2328 Level: advanced 2329 2330 .seealso: `SNESSetPicard()`, `SNESGetFunction()`, `SNESGetJacobian()`, `SNESGetDM()`, `SNESFunction`, `SNESJacobianFunction` 2331 @*/ 2332 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) 2333 { 2334 DM dm; 2335 2336 PetscFunctionBegin; 2337 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 2338 PetscCall(SNESGetFunction(snes,r,NULL,NULL)); 2339 PetscCall(SNESGetJacobian(snes,Amat,Pmat,NULL,NULL)); 2340 PetscCall(SNESGetDM(snes,&dm)); 2341 PetscCall(DMSNESGetPicard(dm,f,J,ctx)); 2342 PetscFunctionReturn(0); 2343 } 2344 2345 /*@C 2346 SNESSetComputeInitialGuess - Sets a routine used to compute an initial guess for the problem 2347 2348 Logically Collective on SNES 2349 2350 Input Parameters: 2351 + snes - the SNES context 2352 . func - function evaluation routine 2353 - ctx - [optional] user-defined context for private data for the 2354 function evaluation routine (may be NULL) 2355 2356 Calling sequence of func: 2357 $ func (SNES snes,Vec x,void *ctx); 2358 2359 . f - function vector 2360 - ctx - optional user-defined function context 2361 2362 Level: intermediate 2363 2364 .seealso: `SNESGetFunction()`, `SNESComputeFunction()`, `SNESSetJacobian()` 2365 @*/ 2366 PetscErrorCode SNESSetComputeInitialGuess(SNES snes,PetscErrorCode (*func)(SNES,Vec,void*),void *ctx) 2367 { 2368 PetscFunctionBegin; 2369 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 2370 if (func) snes->ops->computeinitialguess = func; 2371 if (ctx) snes->initialguessP = ctx; 2372 PetscFunctionReturn(0); 2373 } 2374 2375 /* --------------------------------------------------------------- */ 2376 /*@C 2377 SNESGetRhs - Gets the vector for solving F(x) = rhs. If rhs is not set 2378 it assumes a zero right hand side. 2379 2380 Logically Collective on SNES 2381 2382 Input Parameter: 2383 . snes - the SNES context 2384 2385 Output Parameter: 2386 . rhs - the right hand side vector or NULL if the right hand side vector is null 2387 2388 Level: intermediate 2389 2390 .seealso: `SNESGetSolution()`, `SNESGetFunction()`, `SNESComputeFunction()`, `SNESSetJacobian()`, `SNESSetFunction()` 2391 @*/ 2392 PetscErrorCode SNESGetRhs(SNES snes,Vec *rhs) 2393 { 2394 PetscFunctionBegin; 2395 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 2396 PetscValidPointer(rhs,2); 2397 *rhs = snes->vec_rhs; 2398 PetscFunctionReturn(0); 2399 } 2400 2401 /*@ 2402 SNESComputeFunction - Calls the function that has been set with SNESSetFunction(). 2403 2404 Collective on SNES 2405 2406 Input Parameters: 2407 + snes - the SNES context 2408 - x - input vector 2409 2410 Output Parameter: 2411 . y - function vector, as set by SNESSetFunction() 2412 2413 Notes: 2414 SNESComputeFunction() is typically used within nonlinear solvers 2415 implementations, so users would not generally call this routine themselves. 2416 2417 Level: developer 2418 2419 .seealso: `SNESSetFunction()`, `SNESGetFunction()`, `SNESComputeMFFunction()` 2420 @*/ 2421 PetscErrorCode SNESComputeFunction(SNES snes,Vec x,Vec y) 2422 { 2423 DM dm; 2424 DMSNES sdm; 2425 2426 PetscFunctionBegin; 2427 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 2428 PetscValidHeaderSpecific(x,VEC_CLASSID,2); 2429 PetscValidHeaderSpecific(y,VEC_CLASSID,3); 2430 PetscCheckSameComm(snes,1,x,2); 2431 PetscCheckSameComm(snes,1,y,3); 2432 PetscCall(VecValidValues(x,2,PETSC_TRUE)); 2433 2434 PetscCall(SNESGetDM(snes,&dm)); 2435 PetscCall(DMGetDMSNES(dm,&sdm)); 2436 if (sdm->ops->computefunction) { 2437 if (sdm->ops->computefunction != SNESObjectiveComputeFunctionDefaultFD) { 2438 PetscCall(PetscLogEventBegin(SNES_FunctionEval,snes,x,y,0)); 2439 } 2440 PetscCall(VecLockReadPush(x)); 2441 /* ensure domainerror is false prior to computefunction evaluation (may not have been reset) */ 2442 snes->domainerror = PETSC_FALSE; 2443 { 2444 void *ctx; 2445 PetscErrorCode (*computefunction)(SNES,Vec,Vec,void*); 2446 PetscCall(DMSNESGetFunction(dm,&computefunction,&ctx)); 2447 PetscCallBack("SNES callback function",(*computefunction)(snes,x,y,ctx)); 2448 } 2449 PetscCall(VecLockReadPop(x)); 2450 if (sdm->ops->computefunction != SNESObjectiveComputeFunctionDefaultFD) { 2451 PetscCall(PetscLogEventEnd(SNES_FunctionEval,snes,x,y,0)); 2452 } 2453 } else if (snes->vec_rhs) { 2454 PetscCall(MatMult(snes->jacobian, x, y)); 2455 } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetFunction() or SNESSetDM() before SNESComputeFunction(), likely called from SNESSolve()."); 2456 if (snes->vec_rhs) PetscCall(VecAXPY(y,-1.0,snes->vec_rhs)); 2457 snes->nfuncs++; 2458 /* 2459 domainerror might not be set on all processes; so we tag vector locally with Inf and the next inner product or norm will 2460 propagate the value to all processes 2461 */ 2462 if (snes->domainerror) PetscCall(VecSetInf(y)); 2463 PetscFunctionReturn(0); 2464 } 2465 2466 /*@ 2467 SNESComputeMFFunction - Calls the function that has been set with SNESSetMFFunction(). 2468 2469 Collective on SNES 2470 2471 Input Parameters: 2472 + snes - the SNES context 2473 - x - input vector 2474 2475 Output Parameter: 2476 . y - function vector, as set by SNESSetMFFunction() 2477 2478 Notes: 2479 SNESComputeMFFunction() is used within the matrix vector products called by the matrix created with MatCreateSNESMF() 2480 so users would not generally call this routine themselves. 2481 2482 Since this function is intended for use with finite differencing it does not subtract the right hand side vector provided with SNESSolve() 2483 while SNESComputeFunction() does. As such, this routine cannot be used with MatMFFDSetBase() with a provided F function value even if it applies the 2484 same function as SNESComputeFunction() if a SNESSolve() right hand side vector is use because the two functions difference would include this right hand side function. 2485 2486 Level: developer 2487 2488 .seealso: `SNESSetFunction()`, `SNESGetFunction()`, `SNESComputeFunction()`, `MatCreateSNESMF` 2489 @*/ 2490 PetscErrorCode SNESComputeMFFunction(SNES snes,Vec x,Vec y) 2491 { 2492 DM dm; 2493 DMSNES sdm; 2494 2495 PetscFunctionBegin; 2496 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 2497 PetscValidHeaderSpecific(x,VEC_CLASSID,2); 2498 PetscValidHeaderSpecific(y,VEC_CLASSID,3); 2499 PetscCheckSameComm(snes,1,x,2); 2500 PetscCheckSameComm(snes,1,y,3); 2501 PetscCall(VecValidValues(x,2,PETSC_TRUE)); 2502 2503 PetscCall(SNESGetDM(snes,&dm)); 2504 PetscCall(DMGetDMSNES(dm,&sdm)); 2505 PetscCall(PetscLogEventBegin(SNES_FunctionEval,snes,x,y,0)); 2506 PetscCall(VecLockReadPush(x)); 2507 /* ensure domainerror is false prior to computefunction evaluation (may not have been reset) */ 2508 snes->domainerror = PETSC_FALSE; 2509 PetscCallBack("SNES callback function",(*sdm->ops->computemffunction)(snes,x,y,sdm->mffunctionctx)); 2510 PetscCall(VecLockReadPop(x)); 2511 PetscCall(PetscLogEventEnd(SNES_FunctionEval,snes,x,y,0)); 2512 snes->nfuncs++; 2513 /* 2514 domainerror might not be set on all processes; so we tag vector locally with Inf and the next inner product or norm will 2515 propagate the value to all processes 2516 */ 2517 if (snes->domainerror) PetscCall(VecSetInf(y)); 2518 PetscFunctionReturn(0); 2519 } 2520 2521 /*@ 2522 SNESComputeNGS - Calls the Gauss-Seidel function that has been set with SNESSetNGS(). 2523 2524 Collective on SNES 2525 2526 Input Parameters: 2527 + snes - the SNES context 2528 . x - input vector 2529 - b - rhs vector 2530 2531 Output Parameter: 2532 . x - new solution vector 2533 2534 Notes: 2535 SNESComputeNGS() is typically used within composed nonlinear solver 2536 implementations, so most users would not generally call this routine 2537 themselves. 2538 2539 Level: developer 2540 2541 .seealso: `SNESSetNGS()`, `SNESComputeFunction()` 2542 @*/ 2543 PetscErrorCode SNESComputeNGS(SNES snes,Vec b,Vec x) 2544 { 2545 DM dm; 2546 DMSNES sdm; 2547 2548 PetscFunctionBegin; 2549 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 2550 PetscValidHeaderSpecific(x,VEC_CLASSID,3); 2551 if (b) PetscValidHeaderSpecific(b,VEC_CLASSID,2); 2552 PetscCheckSameComm(snes,1,x,3); 2553 if (b) PetscCheckSameComm(snes,1,b,2); 2554 if (b) PetscCall(VecValidValues(b,2,PETSC_TRUE)); 2555 PetscCall(PetscLogEventBegin(SNES_NGSEval,snes,x,b,0)); 2556 PetscCall(SNESGetDM(snes,&dm)); 2557 PetscCall(DMGetDMSNES(dm,&sdm)); 2558 if (sdm->ops->computegs) { 2559 if (b) PetscCall(VecLockReadPush(b)); 2560 PetscCallBack("SNES callback NGS",(*sdm->ops->computegs)(snes,x,b,sdm->gsctx)); 2561 if (b) PetscCall(VecLockReadPop(b)); 2562 } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetNGS() before SNESComputeNGS(), likely called from SNESSolve()."); 2563 PetscCall(PetscLogEventEnd(SNES_NGSEval,snes,x,b,0)); 2564 PetscFunctionReturn(0); 2565 } 2566 2567 PetscErrorCode SNESTestJacobian(SNES snes) 2568 { 2569 Mat A,B,C,D,jacobian; 2570 Vec x = snes->vec_sol,f = snes->vec_func; 2571 PetscReal nrm,gnorm; 2572 PetscReal threshold = 1.e-5; 2573 MatType mattype; 2574 PetscInt m,n,M,N; 2575 void *functx; 2576 PetscBool complete_print = PETSC_FALSE,threshold_print = PETSC_FALSE,test = PETSC_FALSE,flg,istranspose; 2577 PetscViewer viewer,mviewer; 2578 MPI_Comm comm; 2579 PetscInt tabs; 2580 static PetscBool directionsprinted = PETSC_FALSE; 2581 PetscViewerFormat format; 2582 2583 PetscFunctionBegin; 2584 PetscObjectOptionsBegin((PetscObject)snes); 2585 PetscCall(PetscOptionsName("-snes_test_jacobian","Compare hand-coded and finite difference Jacobians","None",&test)); 2586 PetscCall(PetscOptionsReal("-snes_test_jacobian", "Threshold for element difference between hand-coded and finite difference being meaningful", "None", threshold, &threshold,NULL)); 2587 PetscCall(PetscOptionsViewer("-snes_test_jacobian_view","View difference between hand-coded and finite difference Jacobians element entries","None",&mviewer,&format,&complete_print)); 2588 if (!complete_print) { 2589 PetscCall(PetscOptionsDeprecated("-snes_test_jacobian_display","-snes_test_jacobian_view","3.13",NULL)); 2590 PetscCall(PetscOptionsViewer("-snes_test_jacobian_display","Display difference between hand-coded and finite difference Jacobians","None",&mviewer,&format,&complete_print)); 2591 } 2592 /* for compatibility with PETSc 3.9 and older. */ 2593 PetscCall(PetscOptionsDeprecated("-snes_test_jacobian_display_threshold","-snes_test_jacobian","3.13","-snes_test_jacobian accepts an optional threshold (since v3.10)")); 2594 PetscCall(PetscOptionsReal("-snes_test_jacobian_display_threshold", "Display difference between hand-coded and finite difference Jacobians which exceed input threshold", "None", threshold, &threshold, &threshold_print)); 2595 PetscOptionsEnd(); 2596 if (!test) PetscFunctionReturn(0); 2597 2598 PetscCall(PetscObjectGetComm((PetscObject)snes,&comm)); 2599 PetscCall(PetscViewerASCIIGetStdout(comm,&viewer)); 2600 PetscCall(PetscViewerASCIIGetTab(viewer, &tabs)); 2601 PetscCall(PetscViewerASCIISetTab(viewer, ((PetscObject)snes)->tablevel)); 2602 PetscCall(PetscViewerASCIIPrintf(viewer," ---------- Testing Jacobian -------------\n")); 2603 if (!complete_print && !directionsprinted) { 2604 PetscCall(PetscViewerASCIIPrintf(viewer," Run with -snes_test_jacobian_view and optionally -snes_test_jacobian <threshold> to show difference\n")); 2605 PetscCall(PetscViewerASCIIPrintf(viewer," of hand-coded and finite difference Jacobian entries greater than <threshold>.\n")); 2606 } 2607 if (!directionsprinted) { 2608 PetscCall(PetscViewerASCIIPrintf(viewer," Testing hand-coded Jacobian, if (for double precision runs) ||J - Jfd||_F/||J||_F is\n")); 2609 PetscCall(PetscViewerASCIIPrintf(viewer," O(1.e-8), the hand-coded Jacobian is probably correct.\n")); 2610 directionsprinted = PETSC_TRUE; 2611 } 2612 if (complete_print) PetscCall(PetscViewerPushFormat(mviewer,format)); 2613 2614 PetscCall(PetscObjectTypeCompare((PetscObject)snes->jacobian,MATMFFD,&flg)); 2615 if (!flg) jacobian = snes->jacobian; 2616 else jacobian = snes->jacobian_pre; 2617 2618 if (!x) { 2619 PetscCall(MatCreateVecs(jacobian, &x, NULL)); 2620 } else { 2621 PetscCall(PetscObjectReference((PetscObject) x)); 2622 } 2623 if (!f) { 2624 PetscCall(VecDuplicate(x, &f)); 2625 } else { 2626 PetscCall(PetscObjectReference((PetscObject) f)); 2627 } 2628 /* evaluate the function at this point because SNESComputeJacobianDefault() assumes that the function has been evaluated and put into snes->vec_func */ 2629 PetscCall(SNESComputeFunction(snes,x,f)); 2630 PetscCall(VecDestroy(&f)); 2631 PetscCall(PetscObjectTypeCompare((PetscObject)snes,SNESKSPTRANSPOSEONLY,&istranspose)); 2632 while (jacobian) { 2633 Mat JT = NULL, Jsave = NULL; 2634 2635 if (istranspose) { 2636 PetscCall(MatCreateTranspose(jacobian,&JT)); 2637 Jsave = jacobian; 2638 jacobian = JT; 2639 } 2640 PetscCall(PetscObjectBaseTypeCompareAny((PetscObject)jacobian,&flg,MATSEQAIJ,MATMPIAIJ,MATSEQDENSE,MATMPIDENSE,MATSEQBAIJ,MATMPIBAIJ,MATSEQSBAIJ,MATMPISBAIJ,"")); 2641 if (flg) { 2642 A = jacobian; 2643 PetscCall(PetscObjectReference((PetscObject)A)); 2644 } else { 2645 PetscCall(MatComputeOperator(jacobian,MATAIJ,&A)); 2646 } 2647 2648 PetscCall(MatGetType(A,&mattype)); 2649 PetscCall(MatGetSize(A,&M,&N)); 2650 PetscCall(MatGetLocalSize(A,&m,&n)); 2651 PetscCall(MatCreate(PetscObjectComm((PetscObject)A),&B)); 2652 PetscCall(MatSetType(B,mattype)); 2653 PetscCall(MatSetSizes(B,m,n,M,N)); 2654 PetscCall(MatSetBlockSizesFromMats(B,A,A)); 2655 PetscCall(MatSetUp(B)); 2656 PetscCall(MatSetOption(B,MAT_NEW_NONZERO_ALLOCATION_ERR,PETSC_FALSE)); 2657 2658 PetscCall(SNESGetFunction(snes,NULL,NULL,&functx)); 2659 PetscCall(SNESComputeJacobianDefault(snes,x,B,B,functx)); 2660 2661 PetscCall(MatDuplicate(B,MAT_COPY_VALUES,&D)); 2662 PetscCall(MatAYPX(D,-1.0,A,DIFFERENT_NONZERO_PATTERN)); 2663 PetscCall(MatNorm(D,NORM_FROBENIUS,&nrm)); 2664 PetscCall(MatNorm(A,NORM_FROBENIUS,&gnorm)); 2665 PetscCall(MatDestroy(&D)); 2666 if (!gnorm) gnorm = 1; /* just in case */ 2667 PetscCall(PetscViewerASCIIPrintf(viewer," ||J - Jfd||_F/||J||_F = %g, ||J - Jfd||_F = %g\n",(double)(nrm/gnorm),(double)nrm)); 2668 2669 if (complete_print) { 2670 PetscCall(PetscViewerASCIIPrintf(viewer," Hand-coded Jacobian ----------\n")); 2671 PetscCall(MatView(A,mviewer)); 2672 PetscCall(PetscViewerASCIIPrintf(viewer," Finite difference Jacobian ----------\n")); 2673 PetscCall(MatView(B,mviewer)); 2674 } 2675 2676 if (threshold_print || complete_print) { 2677 PetscInt Istart, Iend, *ccols, bncols, cncols, j, row; 2678 PetscScalar *cvals; 2679 const PetscInt *bcols; 2680 const PetscScalar *bvals; 2681 2682 PetscCall(MatCreate(PetscObjectComm((PetscObject)A),&C)); 2683 PetscCall(MatSetType(C,mattype)); 2684 PetscCall(MatSetSizes(C,m,n,M,N)); 2685 PetscCall(MatSetBlockSizesFromMats(C,A,A)); 2686 PetscCall(MatSetUp(C)); 2687 PetscCall(MatSetOption(C,MAT_NEW_NONZERO_ALLOCATION_ERR,PETSC_FALSE)); 2688 2689 PetscCall(MatAYPX(B,-1.0,A,DIFFERENT_NONZERO_PATTERN)); 2690 PetscCall(MatGetOwnershipRange(B,&Istart,&Iend)); 2691 2692 for (row = Istart; row < Iend; row++) { 2693 PetscCall(MatGetRow(B,row,&bncols,&bcols,&bvals)); 2694 PetscCall(PetscMalloc2(bncols,&ccols,bncols,&cvals)); 2695 for (j = 0, cncols = 0; j < bncols; j++) { 2696 if (PetscAbsScalar(bvals[j]) > threshold) { 2697 ccols[cncols] = bcols[j]; 2698 cvals[cncols] = bvals[j]; 2699 cncols += 1; 2700 } 2701 } 2702 if (cncols) { 2703 PetscCall(MatSetValues(C,1,&row,cncols,ccols,cvals,INSERT_VALUES)); 2704 } 2705 PetscCall(MatRestoreRow(B,row,&bncols,&bcols,&bvals)); 2706 PetscCall(PetscFree2(ccols,cvals)); 2707 } 2708 PetscCall(MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY)); 2709 PetscCall(MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY)); 2710 PetscCall(PetscViewerASCIIPrintf(viewer," Hand-coded minus finite-difference Jacobian with tolerance %g ----------\n",(double)threshold)); 2711 PetscCall(MatView(C,complete_print ? mviewer : viewer)); 2712 PetscCall(MatDestroy(&C)); 2713 } 2714 PetscCall(MatDestroy(&A)); 2715 PetscCall(MatDestroy(&B)); 2716 PetscCall(MatDestroy(&JT)); 2717 if (Jsave) jacobian = Jsave; 2718 if (jacobian != snes->jacobian_pre) { 2719 jacobian = snes->jacobian_pre; 2720 PetscCall(PetscViewerASCIIPrintf(viewer," ---------- Testing Jacobian for preconditioner -------------\n")); 2721 } 2722 else jacobian = NULL; 2723 } 2724 PetscCall(VecDestroy(&x)); 2725 if (complete_print) PetscCall(PetscViewerPopFormat(mviewer)); 2726 if (mviewer) PetscCall(PetscViewerDestroy(&mviewer)); 2727 PetscCall(PetscViewerASCIISetTab(viewer,tabs)); 2728 PetscFunctionReturn(0); 2729 } 2730 2731 /*@ 2732 SNESComputeJacobian - Computes the Jacobian matrix that has been set with SNESSetJacobian(). 2733 2734 Collective on SNES 2735 2736 Input Parameters: 2737 + snes - the SNES context 2738 - x - input vector 2739 2740 Output Parameters: 2741 + A - Jacobian matrix 2742 - B - optional preconditioning matrix 2743 2744 Options Database Keys: 2745 + -snes_lag_preconditioner <lag> - how often to rebuild preconditioner 2746 . -snes_lag_jacobian <lag> - how often to rebuild Jacobian 2747 . -snes_test_jacobian <optional threshold> - compare the user provided Jacobian with one compute via finite differences to check for errors. If a threshold is given, display only those entries whose difference is greater than the threshold. 2748 . -snes_test_jacobian_view - display the user provided Jacobian, the finite difference Jacobian and the difference between them to help users detect the location of errors in the user provided Jacobian 2749 . -snes_compare_explicit - Compare the computed Jacobian to the finite difference Jacobian and output the differences 2750 . -snes_compare_explicit_draw - Compare the computed Jacobian to the finite difference Jacobian and draw the result 2751 . -snes_compare_explicit_contour - Compare the computed Jacobian to the finite difference Jacobian and draw a contour plot with the result 2752 . -snes_compare_operator - Make the comparison options above use the operator instead of the preconditioning matrix 2753 . -snes_compare_coloring - Compute the finite difference Jacobian using coloring and display norms of difference 2754 . -snes_compare_coloring_display - Compute the finite difference Jacobian using coloring and display verbose differences 2755 . -snes_compare_coloring_threshold - Display only those matrix entries that differ by more than a given threshold 2756 . -snes_compare_coloring_threshold_atol - Absolute tolerance for difference in matrix entries to be displayed by -snes_compare_coloring_threshold 2757 . -snes_compare_coloring_threshold_rtol - Relative tolerance for difference in matrix entries to be displayed by -snes_compare_coloring_threshold 2758 . -snes_compare_coloring_draw - Compute the finite difference Jacobian using coloring and draw differences 2759 - -snes_compare_coloring_draw_contour - Compute the finite difference Jacobian using coloring and show contours of matrices and differences 2760 2761 Notes: 2762 Most users should not need to explicitly call this routine, as it 2763 is used internally within the nonlinear solvers. 2764 2765 Developer Notes: 2766 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 2767 for with the SNESType of test that has been removed. 2768 2769 Level: developer 2770 2771 .seealso: `SNESSetJacobian()`, `KSPSetOperators()`, `MatStructure`, `SNESSetLagPreconditioner()`, `SNESSetLagJacobian()` 2772 @*/ 2773 PetscErrorCode SNESComputeJacobian(SNES snes,Vec X,Mat A,Mat B) 2774 { 2775 PetscBool flag; 2776 DM dm; 2777 DMSNES sdm; 2778 KSP ksp; 2779 2780 PetscFunctionBegin; 2781 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 2782 PetscValidHeaderSpecific(X,VEC_CLASSID,2); 2783 PetscCheckSameComm(snes,1,X,2); 2784 PetscCall(VecValidValues(X,2,PETSC_TRUE)); 2785 PetscCall(SNESGetDM(snes,&dm)); 2786 PetscCall(DMGetDMSNES(dm,&sdm)); 2787 2788 /* make sure that MatAssemblyBegin/End() is called on A matrix if it is matrix free */ 2789 if (snes->lagjacobian == -2) { 2790 snes->lagjacobian = -1; 2791 2792 PetscCall(PetscInfo(snes,"Recomputing Jacobian/preconditioner because lag is -2 (means compute Jacobian, but then never again) \n")); 2793 } else if (snes->lagjacobian == -1) { 2794 PetscCall(PetscInfo(snes,"Reusing Jacobian/preconditioner because lag is -1\n")); 2795 PetscCall(PetscObjectTypeCompare((PetscObject)A,MATMFFD,&flag)); 2796 if (flag) { 2797 PetscCall(MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY)); 2798 PetscCall(MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY)); 2799 } 2800 PetscFunctionReturn(0); 2801 } else if (snes->lagjacobian > 1 && (snes->iter + snes->jac_iter) % snes->lagjacobian) { 2802 PetscCall(PetscInfo(snes,"Reusing Jacobian/preconditioner because lag is %" PetscInt_FMT " and SNES iteration is %" PetscInt_FMT "\n",snes->lagjacobian,snes->iter)); 2803 PetscCall(PetscObjectTypeCompare((PetscObject)A,MATMFFD,&flag)); 2804 if (flag) { 2805 PetscCall(MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY)); 2806 PetscCall(MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY)); 2807 } 2808 PetscFunctionReturn(0); 2809 } 2810 if (snes->npc && snes->npcside == PC_LEFT) { 2811 PetscCall(MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY)); 2812 PetscCall(MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY)); 2813 PetscFunctionReturn(0); 2814 } 2815 2816 PetscCall(PetscLogEventBegin(SNES_JacobianEval,snes,X,A,B)); 2817 PetscCall(VecLockReadPush(X)); 2818 { 2819 void *ctx; 2820 PetscErrorCode (*J)(SNES,Vec,Mat,Mat,void*); 2821 PetscCall(DMSNESGetJacobian(dm,&J,&ctx)); 2822 PetscCallBack("SNES callback Jacobian",(*J)(snes,X,A,B,ctx)); 2823 } 2824 PetscCall(VecLockReadPop(X)); 2825 PetscCall(PetscLogEventEnd(SNES_JacobianEval,snes,X,A,B)); 2826 2827 /* attach latest linearization point to the preconditioning matrix */ 2828 PetscCall(PetscObjectCompose((PetscObject)B,"__SNES_latest_X",(PetscObject)X)); 2829 2830 /* the next line ensures that snes->ksp exists */ 2831 PetscCall(SNESGetKSP(snes,&ksp)); 2832 if (snes->lagpreconditioner == -2) { 2833 PetscCall(PetscInfo(snes,"Rebuilding preconditioner exactly once since lag is -2\n")); 2834 PetscCall(KSPSetReusePreconditioner(snes->ksp,PETSC_FALSE)); 2835 snes->lagpreconditioner = -1; 2836 } else if (snes->lagpreconditioner == -1) { 2837 PetscCall(PetscInfo(snes,"Reusing preconditioner because lag is -1\n")); 2838 PetscCall(KSPSetReusePreconditioner(snes->ksp,PETSC_TRUE)); 2839 } else if (snes->lagpreconditioner > 1 && (snes->iter + snes->pre_iter) % snes->lagpreconditioner) { 2840 PetscCall(PetscInfo(snes,"Reusing preconditioner because lag is %" PetscInt_FMT " and SNES iteration is %" PetscInt_FMT "\n",snes->lagpreconditioner,snes->iter)); 2841 PetscCall(KSPSetReusePreconditioner(snes->ksp,PETSC_TRUE)); 2842 } else { 2843 PetscCall(PetscInfo(snes,"Rebuilding preconditioner\n")); 2844 PetscCall(KSPSetReusePreconditioner(snes->ksp,PETSC_FALSE)); 2845 } 2846 2847 PetscCall(SNESTestJacobian(snes)); 2848 /* make sure user returned a correct Jacobian and preconditioner */ 2849 /* PetscValidHeaderSpecific(A,MAT_CLASSID,3); 2850 PetscValidHeaderSpecific(B,MAT_CLASSID,4); */ 2851 { 2852 PetscBool flag = PETSC_FALSE,flag_draw = PETSC_FALSE,flag_contour = PETSC_FALSE,flag_operator = PETSC_FALSE; 2853 PetscCall(PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject) snes)->options,((PetscObject)snes)->prefix,"-snes_compare_explicit",NULL,NULL,&flag)); 2854 PetscCall(PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject) snes)->options,((PetscObject)snes)->prefix,"-snes_compare_explicit_draw",NULL,NULL,&flag_draw)); 2855 PetscCall(PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject) snes)->options,((PetscObject)snes)->prefix,"-snes_compare_explicit_draw_contour",NULL,NULL,&flag_contour)); 2856 PetscCall(PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject) snes)->options,((PetscObject)snes)->prefix,"-snes_compare_operator",NULL,NULL,&flag_operator)); 2857 if (flag || flag_draw || flag_contour) { 2858 Mat Bexp_mine = NULL,Bexp,FDexp; 2859 PetscViewer vdraw,vstdout; 2860 PetscBool flg; 2861 if (flag_operator) { 2862 PetscCall(MatComputeOperator(A,MATAIJ,&Bexp_mine)); 2863 Bexp = Bexp_mine; 2864 } else { 2865 /* See if the preconditioning matrix can be viewed and added directly */ 2866 PetscCall(PetscObjectBaseTypeCompareAny((PetscObject)B,&flg,MATSEQAIJ,MATMPIAIJ,MATSEQDENSE,MATMPIDENSE,MATSEQBAIJ,MATMPIBAIJ,MATSEQSBAIJ,MATMPIBAIJ,"")); 2867 if (flg) Bexp = B; 2868 else { 2869 /* If the "preconditioning" matrix is itself MATSHELL or some other type without direct support */ 2870 PetscCall(MatComputeOperator(B,MATAIJ,&Bexp_mine)); 2871 Bexp = Bexp_mine; 2872 } 2873 } 2874 PetscCall(MatConvert(Bexp,MATSAME,MAT_INITIAL_MATRIX,&FDexp)); 2875 PetscCall(SNESComputeJacobianDefault(snes,X,FDexp,FDexp,NULL)); 2876 PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes),&vstdout)); 2877 if (flag_draw || flag_contour) { 2878 PetscCall(PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes),NULL,"Explicit Jacobians",PETSC_DECIDE,PETSC_DECIDE,300,300,&vdraw)); 2879 if (flag_contour) PetscCall(PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR)); 2880 } else vdraw = NULL; 2881 PetscCall(PetscViewerASCIIPrintf(vstdout,"Explicit %s\n",flag_operator ? "Jacobian" : "preconditioning Jacobian")); 2882 if (flag) PetscCall(MatView(Bexp,vstdout)); 2883 if (vdraw) PetscCall(MatView(Bexp,vdraw)); 2884 PetscCall(PetscViewerASCIIPrintf(vstdout,"Finite difference Jacobian\n")); 2885 if (flag) PetscCall(MatView(FDexp,vstdout)); 2886 if (vdraw) PetscCall(MatView(FDexp,vdraw)); 2887 PetscCall(MatAYPX(FDexp,-1.0,Bexp,SAME_NONZERO_PATTERN)); 2888 PetscCall(PetscViewerASCIIPrintf(vstdout,"User-provided matrix minus finite difference Jacobian\n")); 2889 if (flag) PetscCall(MatView(FDexp,vstdout)); 2890 if (vdraw) { /* Always use contour for the difference */ 2891 PetscCall(PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR)); 2892 PetscCall(MatView(FDexp,vdraw)); 2893 PetscCall(PetscViewerPopFormat(vdraw)); 2894 } 2895 if (flag_contour) PetscCall(PetscViewerPopFormat(vdraw)); 2896 PetscCall(PetscViewerDestroy(&vdraw)); 2897 PetscCall(MatDestroy(&Bexp_mine)); 2898 PetscCall(MatDestroy(&FDexp)); 2899 } 2900 } 2901 { 2902 PetscBool flag = PETSC_FALSE,flag_display = PETSC_FALSE,flag_draw = PETSC_FALSE,flag_contour = PETSC_FALSE,flag_threshold = PETSC_FALSE; 2903 PetscReal threshold_atol = PETSC_SQRT_MACHINE_EPSILON,threshold_rtol = 10*PETSC_SQRT_MACHINE_EPSILON; 2904 PetscCall(PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring",NULL,NULL,&flag)); 2905 PetscCall(PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_display",NULL,NULL,&flag_display)); 2906 PetscCall(PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_draw",NULL,NULL,&flag_draw)); 2907 PetscCall(PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_draw_contour",NULL,NULL,&flag_contour)); 2908 PetscCall(PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_threshold",NULL,NULL,&flag_threshold)); 2909 if (flag_threshold) { 2910 PetscCall(PetscOptionsGetReal(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_threshold_rtol",&threshold_rtol,NULL)); 2911 PetscCall(PetscOptionsGetReal(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_threshold_atol",&threshold_atol,NULL)); 2912 } 2913 if (flag || flag_display || flag_draw || flag_contour || flag_threshold) { 2914 Mat Bfd; 2915 PetscViewer vdraw,vstdout; 2916 MatColoring coloring; 2917 ISColoring iscoloring; 2918 MatFDColoring matfdcoloring; 2919 PetscErrorCode (*func)(SNES,Vec,Vec,void*); 2920 void *funcctx; 2921 PetscReal norm1,norm2,normmax; 2922 2923 PetscCall(MatDuplicate(B,MAT_DO_NOT_COPY_VALUES,&Bfd)); 2924 PetscCall(MatColoringCreate(Bfd,&coloring)); 2925 PetscCall(MatColoringSetType(coloring,MATCOLORINGSL)); 2926 PetscCall(MatColoringSetFromOptions(coloring)); 2927 PetscCall(MatColoringApply(coloring,&iscoloring)); 2928 PetscCall(MatColoringDestroy(&coloring)); 2929 PetscCall(MatFDColoringCreate(Bfd,iscoloring,&matfdcoloring)); 2930 PetscCall(MatFDColoringSetFromOptions(matfdcoloring)); 2931 PetscCall(MatFDColoringSetUp(Bfd,iscoloring,matfdcoloring)); 2932 PetscCall(ISColoringDestroy(&iscoloring)); 2933 2934 /* This method of getting the function is currently unreliable since it doesn't work for DM local functions. */ 2935 PetscCall(SNESGetFunction(snes,NULL,&func,&funcctx)); 2936 PetscCall(MatFDColoringSetFunction(matfdcoloring,(PetscErrorCode (*)(void))func,funcctx)); 2937 PetscCall(PetscObjectSetOptionsPrefix((PetscObject)matfdcoloring,((PetscObject)snes)->prefix)); 2938 PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)matfdcoloring,"coloring_")); 2939 PetscCall(MatFDColoringSetFromOptions(matfdcoloring)); 2940 PetscCall(MatFDColoringApply(Bfd,matfdcoloring,X,snes)); 2941 PetscCall(MatFDColoringDestroy(&matfdcoloring)); 2942 2943 PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes),&vstdout)); 2944 if (flag_draw || flag_contour) { 2945 PetscCall(PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes),NULL,"Colored Jacobians",PETSC_DECIDE,PETSC_DECIDE,300,300,&vdraw)); 2946 if (flag_contour) PetscCall(PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR)); 2947 } else vdraw = NULL; 2948 PetscCall(PetscViewerASCIIPrintf(vstdout,"Explicit preconditioning Jacobian\n")); 2949 if (flag_display) PetscCall(MatView(B,vstdout)); 2950 if (vdraw) PetscCall(MatView(B,vdraw)); 2951 PetscCall(PetscViewerASCIIPrintf(vstdout,"Colored Finite difference Jacobian\n")); 2952 if (flag_display) PetscCall(MatView(Bfd,vstdout)); 2953 if (vdraw) PetscCall(MatView(Bfd,vdraw)); 2954 PetscCall(MatAYPX(Bfd,-1.0,B,SAME_NONZERO_PATTERN)); 2955 PetscCall(MatNorm(Bfd,NORM_1,&norm1)); 2956 PetscCall(MatNorm(Bfd,NORM_FROBENIUS,&norm2)); 2957 PetscCall(MatNorm(Bfd,NORM_MAX,&normmax)); 2958 PetscCall(PetscViewerASCIIPrintf(vstdout,"User-provided matrix minus finite difference Jacobian, norm1=%g normFrob=%g normmax=%g\n",(double)norm1,(double)norm2,(double)normmax)); 2959 if (flag_display) PetscCall(MatView(Bfd,vstdout)); 2960 if (vdraw) { /* Always use contour for the difference */ 2961 PetscCall(PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR)); 2962 PetscCall(MatView(Bfd,vdraw)); 2963 PetscCall(PetscViewerPopFormat(vdraw)); 2964 } 2965 if (flag_contour) PetscCall(PetscViewerPopFormat(vdraw)); 2966 2967 if (flag_threshold) { 2968 PetscInt bs,rstart,rend,i; 2969 PetscCall(MatGetBlockSize(B,&bs)); 2970 PetscCall(MatGetOwnershipRange(B,&rstart,&rend)); 2971 for (i=rstart; i<rend; i++) { 2972 const PetscScalar *ba,*ca; 2973 const PetscInt *bj,*cj; 2974 PetscInt bn,cn,j,maxentrycol = -1,maxdiffcol = -1,maxrdiffcol = -1; 2975 PetscReal maxentry = 0,maxdiff = 0,maxrdiff = 0; 2976 PetscCall(MatGetRow(B,i,&bn,&bj,&ba)); 2977 PetscCall(MatGetRow(Bfd,i,&cn,&cj,&ca)); 2978 PetscCheck(bn == cn,((PetscObject)A)->comm,PETSC_ERR_PLIB,"Unexpected different nonzero pattern in -snes_compare_coloring_threshold"); 2979 for (j=0; j<bn; j++) { 2980 PetscReal rdiff = PetscAbsScalar(ca[j]) / (threshold_atol + threshold_rtol*PetscAbsScalar(ba[j])); 2981 if (PetscAbsScalar(ba[j]) > PetscAbs(maxentry)) { 2982 maxentrycol = bj[j]; 2983 maxentry = PetscRealPart(ba[j]); 2984 } 2985 if (PetscAbsScalar(ca[j]) > PetscAbs(maxdiff)) { 2986 maxdiffcol = bj[j]; 2987 maxdiff = PetscRealPart(ca[j]); 2988 } 2989 if (rdiff > maxrdiff) { 2990 maxrdiffcol = bj[j]; 2991 maxrdiff = rdiff; 2992 } 2993 } 2994 if (maxrdiff > 1) { 2995 PetscCall(PetscViewerASCIIPrintf(vstdout,"row %" PetscInt_FMT " (maxentry=%g at %" PetscInt_FMT ", maxdiff=%g at %" PetscInt_FMT ", maxrdiff=%g at %" PetscInt_FMT "):",i,(double)maxentry,maxentrycol,(double)maxdiff,maxdiffcol,(double)maxrdiff,maxrdiffcol)); 2996 for (j=0; j<bn; j++) { 2997 PetscReal rdiff; 2998 rdiff = PetscAbsScalar(ca[j]) / (threshold_atol + threshold_rtol*PetscAbsScalar(ba[j])); 2999 if (rdiff > 1) { 3000 PetscCall(PetscViewerASCIIPrintf(vstdout," (%" PetscInt_FMT ",%g:%g)",bj[j],(double)PetscRealPart(ba[j]),(double)PetscRealPart(ca[j]))); 3001 } 3002 } 3003 PetscCall(PetscViewerASCIIPrintf(vstdout,"\n")); 3004 } 3005 PetscCall(MatRestoreRow(B,i,&bn,&bj,&ba)); 3006 PetscCall(MatRestoreRow(Bfd,i,&cn,&cj,&ca)); 3007 } 3008 } 3009 PetscCall(PetscViewerDestroy(&vdraw)); 3010 PetscCall(MatDestroy(&Bfd)); 3011 } 3012 } 3013 PetscFunctionReturn(0); 3014 } 3015 3016 /*MC 3017 SNESJacobianFunction - Function used to convey the nonlinear Jacobian of the function to be solved by SNES 3018 3019 Synopsis: 3020 #include "petscsnes.h" 3021 PetscErrorCode SNESJacobianFunction(SNES snes,Vec x,Mat Amat,Mat Pmat,void *ctx); 3022 3023 Collective on snes 3024 3025 Input Parameters: 3026 + x - input vector, the Jacobian is to be computed at this value 3027 - ctx - [optional] user-defined Jacobian context 3028 3029 Output Parameters: 3030 + Amat - the matrix that defines the (approximate) Jacobian 3031 - Pmat - the matrix to be used in constructing the preconditioner, usually the same as Amat. 3032 3033 Level: intermediate 3034 3035 .seealso: `SNESSetFunction()`, `SNESGetFunction()`, `SNESSetJacobian()`, `SNESGetJacobian()` 3036 M*/ 3037 3038 /*@C 3039 SNESSetJacobian - Sets the function to compute Jacobian as well as the 3040 location to store the matrix. 3041 3042 Logically Collective on SNES 3043 3044 Input Parameters: 3045 + snes - the SNES context 3046 . Amat - the matrix that defines the (approximate) Jacobian 3047 . Pmat - the matrix to be used in constructing the preconditioner, usually the same as Amat. 3048 . J - Jacobian evaluation routine (if NULL then SNES retains any previously set value), see SNESJacobianFunction for details 3049 - ctx - [optional] user-defined context for private data for the 3050 Jacobian evaluation routine (may be NULL) (if NULL then SNES retains any previously set value) 3051 3052 Notes: 3053 If the Amat matrix and Pmat matrix are different you must call MatAssemblyBegin/End() on 3054 each matrix. 3055 3056 If you know the operator Amat has a null space you can use MatSetNullSpace() and MatSetTransposeNullSpace() to supply the null 3057 space to Amat and the KSP solvers will automatically use that null space as needed during the solution process. 3058 3059 If using SNESComputeJacobianDefaultColor() to assemble a Jacobian, the ctx argument 3060 must be a MatFDColoring. 3061 3062 Other defect-correction schemes can be used by computing a different matrix in place of the Jacobian. One common 3063 example is to use the "Picard linearization" which only differentiates through the highest order parts of each term. 3064 3065 Level: beginner 3066 3067 .seealso: `KSPSetOperators()`, `SNESSetFunction()`, `MatMFFDComputeJacobian()`, `SNESComputeJacobianDefaultColor()`, `MatStructure`, `J`, 3068 `SNESSetPicard()`, `SNESJacobianFunction` 3069 @*/ 3070 PetscErrorCode SNESSetJacobian(SNES snes,Mat Amat,Mat Pmat,PetscErrorCode (*J)(SNES,Vec,Mat,Mat,void*),void *ctx) 3071 { 3072 DM dm; 3073 3074 PetscFunctionBegin; 3075 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 3076 if (Amat) PetscValidHeaderSpecific(Amat,MAT_CLASSID,2); 3077 if (Pmat) PetscValidHeaderSpecific(Pmat,MAT_CLASSID,3); 3078 if (Amat) PetscCheckSameComm(snes,1,Amat,2); 3079 if (Pmat) PetscCheckSameComm(snes,1,Pmat,3); 3080 PetscCall(SNESGetDM(snes,&dm)); 3081 PetscCall(DMSNESSetJacobian(dm,J,ctx)); 3082 if (Amat) { 3083 PetscCall(PetscObjectReference((PetscObject)Amat)); 3084 PetscCall(MatDestroy(&snes->jacobian)); 3085 3086 snes->jacobian = Amat; 3087 } 3088 if (Pmat) { 3089 PetscCall(PetscObjectReference((PetscObject)Pmat)); 3090 PetscCall(MatDestroy(&snes->jacobian_pre)); 3091 3092 snes->jacobian_pre = Pmat; 3093 } 3094 PetscFunctionReturn(0); 3095 } 3096 3097 /*@C 3098 SNESGetJacobian - Returns the Jacobian matrix and optionally the user 3099 provided context for evaluating the Jacobian. 3100 3101 Not Collective, but Mat object will be parallel if SNES object is 3102 3103 Input Parameter: 3104 . snes - the nonlinear solver context 3105 3106 Output Parameters: 3107 + Amat - location to stash (approximate) Jacobian matrix (or NULL) 3108 . Pmat - location to stash matrix used to compute the preconditioner (or NULL) 3109 . J - location to put Jacobian function (or NULL), see SNESJacobianFunction for details on its calling sequence 3110 - ctx - location to stash Jacobian ctx (or NULL) 3111 3112 Level: advanced 3113 3114 .seealso: `SNESSetJacobian()`, `SNESComputeJacobian()`, `SNESJacobianFunction`, `SNESGetFunction()` 3115 @*/ 3116 PetscErrorCode SNESGetJacobian(SNES snes,Mat *Amat,Mat *Pmat,PetscErrorCode (**J)(SNES,Vec,Mat,Mat,void*),void **ctx) 3117 { 3118 DM dm; 3119 3120 PetscFunctionBegin; 3121 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 3122 if (Amat) *Amat = snes->jacobian; 3123 if (Pmat) *Pmat = snes->jacobian_pre; 3124 PetscCall(SNESGetDM(snes,&dm)); 3125 PetscCall(DMSNESGetJacobian(dm,J,ctx)); 3126 PetscFunctionReturn(0); 3127 } 3128 3129 static PetscErrorCode SNESSetDefaultComputeJacobian(SNES snes) 3130 { 3131 DM dm; 3132 DMSNES sdm; 3133 3134 PetscFunctionBegin; 3135 PetscCall(SNESGetDM(snes,&dm)); 3136 PetscCall(DMGetDMSNES(dm,&sdm)); 3137 if (!sdm->ops->computejacobian && snes->jacobian_pre) { 3138 DM dm; 3139 PetscBool isdense,ismf; 3140 3141 PetscCall(SNESGetDM(snes,&dm)); 3142 PetscCall(PetscObjectTypeCompareAny((PetscObject)snes->jacobian_pre,&isdense,MATSEQDENSE,MATMPIDENSE,MATDENSE,NULL)); 3143 PetscCall(PetscObjectTypeCompareAny((PetscObject)snes->jacobian_pre,&ismf,MATMFFD,MATSHELL,NULL)); 3144 if (isdense) { 3145 PetscCall(DMSNESSetJacobian(dm,SNESComputeJacobianDefault,NULL)); 3146 } else if (!ismf) { 3147 PetscCall(DMSNESSetJacobian(dm,SNESComputeJacobianDefaultColor,NULL)); 3148 } 3149 } 3150 PetscFunctionReturn(0); 3151 } 3152 3153 /*@ 3154 SNESSetUp - Sets up the internal data structures for the later use 3155 of a nonlinear solver. 3156 3157 Collective on SNES 3158 3159 Input Parameters: 3160 . snes - the SNES context 3161 3162 Notes: 3163 For basic use of the SNES solvers the user need not explicitly call 3164 SNESSetUp(), since these actions will automatically occur during 3165 the call to SNESSolve(). However, if one wishes to control this 3166 phase separately, SNESSetUp() should be called after SNESCreate() 3167 and optional routines of the form SNESSetXXX(), but before SNESSolve(). 3168 3169 Level: advanced 3170 3171 .seealso: `SNESCreate()`, `SNESSolve()`, `SNESDestroy()` 3172 @*/ 3173 PetscErrorCode SNESSetUp(SNES snes) 3174 { 3175 DM dm; 3176 DMSNES sdm; 3177 SNESLineSearch linesearch, pclinesearch; 3178 void *lsprectx,*lspostctx; 3179 PetscErrorCode (*precheck)(SNESLineSearch,Vec,Vec,PetscBool*,void*); 3180 PetscErrorCode (*postcheck)(SNESLineSearch,Vec,Vec,Vec,PetscBool*,PetscBool*,void*); 3181 PetscErrorCode (*func)(SNES,Vec,Vec,void*); 3182 Vec f,fpc; 3183 void *funcctx; 3184 PetscErrorCode (*jac)(SNES,Vec,Mat,Mat,void*); 3185 void *jacctx,*appctx; 3186 Mat j,jpre; 3187 3188 PetscFunctionBegin; 3189 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 3190 if (snes->setupcalled) PetscFunctionReturn(0); 3191 PetscCall(PetscLogEventBegin(SNES_Setup,snes,0,0,0)); 3192 3193 if (!((PetscObject)snes)->type_name) { 3194 PetscCall(SNESSetType(snes,SNESNEWTONLS)); 3195 } 3196 3197 PetscCall(SNESGetFunction(snes,&snes->vec_func,NULL,NULL)); 3198 3199 PetscCall(SNESGetDM(snes,&dm)); 3200 PetscCall(DMGetDMSNES(dm,&sdm)); 3201 PetscCall(SNESSetDefaultComputeJacobian(snes)); 3202 3203 if (!snes->vec_func) { 3204 PetscCall(DMCreateGlobalVector(dm,&snes->vec_func)); 3205 } 3206 3207 if (!snes->ksp) { 3208 PetscCall(SNESGetKSP(snes, &snes->ksp)); 3209 } 3210 3211 if (snes->linesearch) { 3212 PetscCall(SNESGetLineSearch(snes, &snes->linesearch)); 3213 PetscCall(SNESLineSearchSetFunction(snes->linesearch,SNESComputeFunction)); 3214 } 3215 3216 if (snes->npc && snes->npcside == PC_LEFT) { 3217 snes->mf = PETSC_TRUE; 3218 snes->mf_operator = PETSC_FALSE; 3219 } 3220 3221 if (snes->npc) { 3222 /* copy the DM over */ 3223 PetscCall(SNESGetDM(snes,&dm)); 3224 PetscCall(SNESSetDM(snes->npc,dm)); 3225 3226 PetscCall(SNESGetFunction(snes,&f,&func,&funcctx)); 3227 PetscCall(VecDuplicate(f,&fpc)); 3228 PetscCall(SNESSetFunction(snes->npc,fpc,func,funcctx)); 3229 PetscCall(SNESGetJacobian(snes,&j,&jpre,&jac,&jacctx)); 3230 PetscCall(SNESSetJacobian(snes->npc,j,jpre,jac,jacctx)); 3231 PetscCall(SNESGetApplicationContext(snes,&appctx)); 3232 PetscCall(SNESSetApplicationContext(snes->npc,appctx)); 3233 PetscCall(VecDestroy(&fpc)); 3234 3235 /* copy the function pointers over */ 3236 PetscCall(PetscObjectCopyFortranFunctionPointers((PetscObject)snes,(PetscObject)snes->npc)); 3237 3238 /* default to 1 iteration */ 3239 PetscCall(SNESSetTolerances(snes->npc,0.0,0.0,0.0,1,snes->npc->max_funcs)); 3240 if (snes->npcside == PC_RIGHT) { 3241 PetscCall(SNESSetNormSchedule(snes->npc,SNES_NORM_FINAL_ONLY)); 3242 } else { 3243 PetscCall(SNESSetNormSchedule(snes->npc,SNES_NORM_NONE)); 3244 } 3245 PetscCall(SNESSetFromOptions(snes->npc)); 3246 3247 /* copy the line search context over */ 3248 if (snes->linesearch && snes->npc->linesearch) { 3249 PetscCall(SNESGetLineSearch(snes,&linesearch)); 3250 PetscCall(SNESGetLineSearch(snes->npc,&pclinesearch)); 3251 PetscCall(SNESLineSearchGetPreCheck(linesearch,&precheck,&lsprectx)); 3252 PetscCall(SNESLineSearchGetPostCheck(linesearch,&postcheck,&lspostctx)); 3253 PetscCall(SNESLineSearchSetPreCheck(pclinesearch,precheck,lsprectx)); 3254 PetscCall(SNESLineSearchSetPostCheck(pclinesearch,postcheck,lspostctx)); 3255 PetscCall(PetscObjectCopyFortranFunctionPointers((PetscObject)linesearch, (PetscObject)pclinesearch)); 3256 } 3257 } 3258 if (snes->mf) PetscCall(SNESSetUpMatrixFree_Private(snes, snes->mf_operator, snes->mf_version)); 3259 if (snes->ops->usercompute && !snes->user) { 3260 PetscCall((*snes->ops->usercompute)(snes,(void**)&snes->user)); 3261 } 3262 3263 snes->jac_iter = 0; 3264 snes->pre_iter = 0; 3265 3266 PetscTryTypeMethod(snes,setup); 3267 3268 PetscCall(SNESSetDefaultComputeJacobian(snes)); 3269 3270 if (snes->npc && snes->npcside == PC_LEFT) { 3271 if (snes->functype == SNES_FUNCTION_PRECONDITIONED) { 3272 if (snes->linesearch) { 3273 PetscCall(SNESGetLineSearch(snes,&linesearch)); 3274 PetscCall(SNESLineSearchSetFunction(linesearch,SNESComputeFunctionDefaultNPC)); 3275 } 3276 } 3277 } 3278 PetscCall(PetscLogEventEnd(SNES_Setup,snes,0,0,0)); 3279 snes->setupcalled = PETSC_TRUE; 3280 PetscFunctionReturn(0); 3281 } 3282 3283 /*@ 3284 SNESReset - Resets a SNES context to the snessetupcalled = 0 state and removes any allocated Vecs and Mats 3285 3286 Collective on SNES 3287 3288 Input Parameter: 3289 . snes - iterative context obtained from SNESCreate() 3290 3291 Level: intermediate 3292 3293 Notes: 3294 Also calls the application context destroy routine set with SNESSetComputeApplicationContext() 3295 3296 .seealso: `SNESCreate()`, `SNESSetUp()`, `SNESSolve()` 3297 @*/ 3298 PetscErrorCode SNESReset(SNES snes) 3299 { 3300 PetscFunctionBegin; 3301 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 3302 if (snes->ops->userdestroy && snes->user) { 3303 PetscCall((*snes->ops->userdestroy)((void**)&snes->user)); 3304 snes->user = NULL; 3305 } 3306 if (snes->npc) PetscCall(SNESReset(snes->npc)); 3307 3308 PetscTryTypeMethod(snes,reset); 3309 if (snes->ksp) PetscCall(KSPReset(snes->ksp)); 3310 3311 if (snes->linesearch) PetscCall(SNESLineSearchReset(snes->linesearch)); 3312 3313 PetscCall(VecDestroy(&snes->vec_rhs)); 3314 PetscCall(VecDestroy(&snes->vec_sol)); 3315 PetscCall(VecDestroy(&snes->vec_sol_update)); 3316 PetscCall(VecDestroy(&snes->vec_func)); 3317 PetscCall(MatDestroy(&snes->jacobian)); 3318 PetscCall(MatDestroy(&snes->jacobian_pre)); 3319 PetscCall(MatDestroy(&snes->picard)); 3320 PetscCall(VecDestroyVecs(snes->nwork,&snes->work)); 3321 PetscCall(VecDestroyVecs(snes->nvwork,&snes->vwork)); 3322 3323 snes->alwayscomputesfinalresidual = PETSC_FALSE; 3324 3325 snes->nwork = snes->nvwork = 0; 3326 snes->setupcalled = PETSC_FALSE; 3327 PetscFunctionReturn(0); 3328 } 3329 3330 /*@ 3331 SNESConvergedReasonViewCancel - Clears all the reasonview functions for a SNES object. 3332 3333 Collective on SNES 3334 3335 Input Parameter: 3336 . snes - iterative context obtained from SNESCreate() 3337 3338 Level: intermediate 3339 3340 .seealso: `SNESCreate()`, `SNESDestroy()`, `SNESReset()` 3341 @*/ 3342 PetscErrorCode SNESConvergedReasonViewCancel(SNES snes) 3343 { 3344 PetscInt i; 3345 3346 PetscFunctionBegin; 3347 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 3348 for (i=0; i<snes->numberreasonviews; i++) { 3349 if (snes->reasonviewdestroy[i]) { 3350 PetscCall((*snes->reasonviewdestroy[i])(&snes->reasonviewcontext[i])); 3351 } 3352 } 3353 snes->numberreasonviews = 0; 3354 PetscFunctionReturn(0); 3355 } 3356 3357 /*@C 3358 SNESDestroy - Destroys the nonlinear solver context that was created 3359 with SNESCreate(). 3360 3361 Collective on SNES 3362 3363 Input Parameter: 3364 . snes - the SNES context 3365 3366 Level: beginner 3367 3368 .seealso: `SNESCreate()`, `SNESSolve()` 3369 @*/ 3370 PetscErrorCode SNESDestroy(SNES *snes) 3371 { 3372 PetscFunctionBegin; 3373 if (!*snes) PetscFunctionReturn(0); 3374 PetscValidHeaderSpecific((*snes),SNES_CLASSID,1); 3375 if (--((PetscObject)(*snes))->refct > 0) {*snes = NULL; PetscFunctionReturn(0);} 3376 3377 PetscCall(SNESReset((*snes))); 3378 PetscCall(SNESDestroy(&(*snes)->npc)); 3379 3380 /* if memory was published with SAWs then destroy it */ 3381 PetscCall(PetscObjectSAWsViewOff((PetscObject)*snes)); 3382 PetscTryTypeMethod((*snes),destroy); 3383 3384 if ((*snes)->dm) PetscCall(DMCoarsenHookRemove((*snes)->dm,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,*snes)); 3385 PetscCall(DMDestroy(&(*snes)->dm)); 3386 PetscCall(KSPDestroy(&(*snes)->ksp)); 3387 PetscCall(SNESLineSearchDestroy(&(*snes)->linesearch)); 3388 3389 PetscCall(PetscFree((*snes)->kspconvctx)); 3390 if ((*snes)->ops->convergeddestroy) { 3391 PetscCall((*(*snes)->ops->convergeddestroy)((*snes)->cnvP)); 3392 } 3393 if ((*snes)->conv_hist_alloc) { 3394 PetscCall(PetscFree2((*snes)->conv_hist,(*snes)->conv_hist_its)); 3395 } 3396 PetscCall(SNESMonitorCancel((*snes))); 3397 PetscCall(SNESConvergedReasonViewCancel((*snes))); 3398 PetscCall(PetscHeaderDestroy(snes)); 3399 PetscFunctionReturn(0); 3400 } 3401 3402 /* ----------- Routines to set solver parameters ---------- */ 3403 3404 /*@ 3405 SNESSetLagPreconditioner - Determines when the preconditioner is rebuilt in the nonlinear solve. 3406 3407 Logically Collective on SNES 3408 3409 Input Parameters: 3410 + snes - the SNES context 3411 - lag - 1 means rebuild every time the Jacobian is computed within a single nonlinear solve, 2 means every second time 3412 the Jacobian is built etc. -2 indicates rebuild preconditioner at next chance but then never rebuild after that 3413 3414 Options Database Keys: 3415 + -snes_lag_jacobian_persists <true,false> - sets the persistence 3416 . -snes_lag_jacobian <-2,1,2,...> - sets the lag 3417 . -snes_lag_preconditioner_persists <true,false> - sets the persistence 3418 - -snes_lag_preconditioner <-2,1,2,...> - sets the lag 3419 3420 Notes: 3421 The default is 1 3422 The preconditioner is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1 or SNESSetLagPreconditionerPersists() was called 3423 3424 SNESSetLagPreconditionerPersists() allows using the same uniform lagging (for example every second solve) across multiple solves. 3425 3426 Level: intermediate 3427 3428 .seealso: `SNESSetTrustRegionTolerance()`, `SNESGetLagPreconditioner()`, `SNESSetLagJacobian()`, `SNESGetLagJacobian()`, `SNESSetLagPreconditionerPersists()`, 3429 `SNESSetLagJacobianPersists()` 3430 3431 @*/ 3432 PetscErrorCode SNESSetLagPreconditioner(SNES snes,PetscInt lag) 3433 { 3434 PetscFunctionBegin; 3435 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 3436 PetscCheck(lag >= -2,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag must be -2, -1, 1 or greater"); 3437 PetscCheck(lag,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag cannot be 0"); 3438 PetscValidLogicalCollectiveInt(snes,lag,2); 3439 snes->lagpreconditioner = lag; 3440 PetscFunctionReturn(0); 3441 } 3442 3443 /*@ 3444 SNESSetGridSequence - sets the number of steps of grid sequencing that SNES does 3445 3446 Logically Collective on SNES 3447 3448 Input Parameters: 3449 + snes - the SNES context 3450 - steps - the number of refinements to do, defaults to 0 3451 3452 Options Database Keys: 3453 . -snes_grid_sequence <steps> - Use grid sequencing to generate initial guess 3454 3455 Level: intermediate 3456 3457 Notes: 3458 Use SNESGetSolution() to extract the fine grid solution after grid sequencing. 3459 3460 .seealso: `SNESSetTrustRegionTolerance()`, `SNESGetLagPreconditioner()`, `SNESSetLagJacobian()`, `SNESGetLagJacobian()`, `SNESGetGridSequence()` 3461 3462 @*/ 3463 PetscErrorCode SNESSetGridSequence(SNES snes,PetscInt steps) 3464 { 3465 PetscFunctionBegin; 3466 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 3467 PetscValidLogicalCollectiveInt(snes,steps,2); 3468 snes->gridsequence = steps; 3469 PetscFunctionReturn(0); 3470 } 3471 3472 /*@ 3473 SNESGetGridSequence - gets the number of steps of grid sequencing that SNES does 3474 3475 Logically Collective on SNES 3476 3477 Input Parameter: 3478 . snes - the SNES context 3479 3480 Output Parameter: 3481 . steps - the number of refinements to do, defaults to 0 3482 3483 Options Database Keys: 3484 . -snes_grid_sequence <steps> - set number of refinements 3485 3486 Level: intermediate 3487 3488 Notes: 3489 Use SNESGetSolution() to extract the fine grid solution after grid sequencing. 3490 3491 .seealso: `SNESSetTrustRegionTolerance()`, `SNESGetLagPreconditioner()`, `SNESSetLagJacobian()`, `SNESGetLagJacobian()`, `SNESSetGridSequence()` 3492 3493 @*/ 3494 PetscErrorCode SNESGetGridSequence(SNES snes,PetscInt *steps) 3495 { 3496 PetscFunctionBegin; 3497 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 3498 *steps = snes->gridsequence; 3499 PetscFunctionReturn(0); 3500 } 3501 3502 /*@ 3503 SNESGetLagPreconditioner - Indicates how often the preconditioner is rebuilt 3504 3505 Not Collective 3506 3507 Input Parameter: 3508 . snes - the SNES context 3509 3510 Output Parameter: 3511 . lag - -1 indicates NEVER rebuild, 1 means rebuild every time the Jacobian is computed within a single nonlinear solve, 2 means every second time 3512 the Jacobian is built etc. -2 indicates rebuild preconditioner at next chance but then never rebuild after that 3513 3514 Options Database Keys: 3515 + -snes_lag_jacobian_persists <true,false> - sets the persistence 3516 . -snes_lag_jacobian <-2,1,2,...> - sets the lag 3517 . -snes_lag_preconditioner_persists <true,false> - sets the persistence 3518 - -snes_lag_preconditioner <-2,1,2,...> - sets the lag 3519 3520 Notes: 3521 The default is 1 3522 The preconditioner is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1 3523 3524 Level: intermediate 3525 3526 .seealso: `SNESSetTrustRegionTolerance()`, `SNESSetLagPreconditioner()`, `SNESSetLagJacobianPersists()`, `SNESSetLagPreconditionerPersists()` 3527 3528 @*/ 3529 PetscErrorCode SNESGetLagPreconditioner(SNES snes,PetscInt *lag) 3530 { 3531 PetscFunctionBegin; 3532 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 3533 *lag = snes->lagpreconditioner; 3534 PetscFunctionReturn(0); 3535 } 3536 3537 /*@ 3538 SNESSetLagJacobian - Determines when the Jacobian is rebuilt in the nonlinear solve. See SNESSetLagPreconditioner() for determining how 3539 often the preconditioner is rebuilt. 3540 3541 Logically Collective on SNES 3542 3543 Input Parameters: 3544 + snes - the SNES context 3545 - lag - -1 indicates NEVER rebuild, 1 means rebuild every time the Jacobian is computed within a single nonlinear solve, 2 means every second time 3546 the Jacobian is built etc. -2 means rebuild at next chance but then never again 3547 3548 Options Database Keys: 3549 + -snes_lag_jacobian_persists <true,false> - sets the persistence 3550 . -snes_lag_jacobian <-2,1,2,...> - sets the lag 3551 . -snes_lag_preconditioner_persists <true,false> - sets the persistence 3552 - -snes_lag_preconditioner <-2,1,2,...> - sets the lag. 3553 3554 Notes: 3555 The default is 1 3556 The Jacobian is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1 3557 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 3558 at the next Newton step but never again (unless it is reset to another value) 3559 3560 Level: intermediate 3561 3562 .seealso: `SNESSetTrustRegionTolerance()`, `SNESGetLagPreconditioner()`, `SNESSetLagPreconditioner()`, `SNESGetLagJacobianPersists()`, `SNESSetLagPreconditionerPersists()` 3563 3564 @*/ 3565 PetscErrorCode SNESSetLagJacobian(SNES snes,PetscInt lag) 3566 { 3567 PetscFunctionBegin; 3568 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 3569 PetscCheck(lag >= -2,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag must be -2, -1, 1 or greater"); 3570 PetscCheck(lag,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag cannot be 0"); 3571 PetscValidLogicalCollectiveInt(snes,lag,2); 3572 snes->lagjacobian = lag; 3573 PetscFunctionReturn(0); 3574 } 3575 3576 /*@ 3577 SNESGetLagJacobian - Indicates how often the Jacobian is rebuilt. See SNESGetLagPreconditioner() to determine when the preconditioner is rebuilt 3578 3579 Not Collective 3580 3581 Input Parameter: 3582 . snes - the SNES context 3583 3584 Output Parameter: 3585 . lag - -1 indicates NEVER rebuild, 1 means rebuild every time the Jacobian is computed within a single nonlinear solve, 2 means every second time 3586 the Jacobian is built etc. 3587 3588 Notes: 3589 The default is 1 3590 The jacobian is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1 or SNESSetLagJacobianPersists() was called. 3591 3592 Level: intermediate 3593 3594 .seealso: `SNESSetTrustRegionTolerance()`, `SNESSetLagJacobian()`, `SNESSetLagPreconditioner()`, `SNESGetLagPreconditioner()`, `SNESSetLagJacobianPersists()`, `SNESSetLagPreconditionerPersists()` 3595 3596 @*/ 3597 PetscErrorCode SNESGetLagJacobian(SNES snes,PetscInt *lag) 3598 { 3599 PetscFunctionBegin; 3600 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 3601 *lag = snes->lagjacobian; 3602 PetscFunctionReturn(0); 3603 } 3604 3605 /*@ 3606 SNESSetLagJacobianPersists - Set whether or not the Jacobian lagging persists through multiple solves 3607 3608 Logically collective on SNES 3609 3610 Input Parameters: 3611 + snes - the SNES context 3612 - flg - jacobian lagging persists if true 3613 3614 Options Database Keys: 3615 + -snes_lag_jacobian_persists <true,false> - sets the persistence 3616 . -snes_lag_jacobian <-2,1,2,...> - sets the lag 3617 . -snes_lag_preconditioner_persists <true,false> - sets the persistence 3618 - -snes_lag_preconditioner <-2,1,2,...> - sets the lag 3619 3620 Notes: 3621 This is useful both for nonlinear preconditioning, where it's appropriate to have the Jacobian be stale by 3622 several solves, and for implicit time-stepping, where Jacobian lagging in the inner nonlinear solve over several 3623 timesteps may present huge efficiency gains. 3624 3625 Level: developer 3626 3627 .seealso: `SNESSetLagPreconditionerPersists()`, `SNESSetLagJacobian()`, `SNESGetLagJacobian()`, `SNESGetNPC()`, `SNESSetLagJacobianPersists()` 3628 3629 @*/ 3630 PetscErrorCode SNESSetLagJacobianPersists(SNES snes,PetscBool flg) 3631 { 3632 PetscFunctionBegin; 3633 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 3634 PetscValidLogicalCollectiveBool(snes,flg,2); 3635 snes->lagjac_persist = flg; 3636 PetscFunctionReturn(0); 3637 } 3638 3639 /*@ 3640 SNESSetLagPreconditionerPersists - Set whether or not the preconditioner lagging persists through multiple nonlinear solves 3641 3642 Logically Collective on SNES 3643 3644 Input Parameters: 3645 + snes - the SNES context 3646 - flg - preconditioner lagging persists if true 3647 3648 Options Database Keys: 3649 + -snes_lag_jacobian_persists <true,false> - sets the persistence 3650 . -snes_lag_jacobian <-2,1,2,...> - sets the lag 3651 . -snes_lag_preconditioner_persists <true,false> - sets the persistence 3652 - -snes_lag_preconditioner <-2,1,2,...> - sets the lag 3653 3654 Notes: 3655 This is useful both for nonlinear preconditioning, where it's appropriate to have the preconditioner be stale 3656 by several solves, and for implicit time-stepping, where preconditioner lagging in the inner nonlinear solve over 3657 several timesteps may present huge efficiency gains. 3658 3659 Level: developer 3660 3661 .seealso: `SNESSetLagJacobianPersists()`, `SNESSetLagJacobian()`, `SNESGetLagJacobian()`, `SNESGetNPC()`, `SNESSetLagPreconditioner()` 3662 3663 @*/ 3664 PetscErrorCode SNESSetLagPreconditionerPersists(SNES snes,PetscBool flg) 3665 { 3666 PetscFunctionBegin; 3667 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 3668 PetscValidLogicalCollectiveBool(snes,flg,2); 3669 snes->lagpre_persist = flg; 3670 PetscFunctionReturn(0); 3671 } 3672 3673 /*@ 3674 SNESSetForceIteration - force SNESSolve() to take at least one iteration regardless of the initial residual norm 3675 3676 Logically Collective on SNES 3677 3678 Input Parameters: 3679 + snes - the SNES context 3680 - force - PETSC_TRUE require at least one iteration 3681 3682 Options Database Keys: 3683 . -snes_force_iteration <force> - Sets forcing an iteration 3684 3685 Notes: 3686 This is used sometimes with TS to prevent TS from detecting a false steady state solution 3687 3688 Level: intermediate 3689 3690 .seealso: `SNESSetTrustRegionTolerance()`, `SNESSetDivergenceTolerance()` 3691 @*/ 3692 PetscErrorCode SNESSetForceIteration(SNES snes,PetscBool force) 3693 { 3694 PetscFunctionBegin; 3695 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 3696 snes->forceiteration = force; 3697 PetscFunctionReturn(0); 3698 } 3699 3700 /*@ 3701 SNESGetForceIteration - Whether or not to force SNESSolve() take at least one iteration regardless of the initial residual norm 3702 3703 Logically Collective on SNES 3704 3705 Input Parameters: 3706 . snes - the SNES context 3707 3708 Output Parameter: 3709 . force - PETSC_TRUE requires at least one iteration. 3710 3711 Level: intermediate 3712 3713 .seealso: `SNESSetForceIteration()`, `SNESSetTrustRegionTolerance()`, `SNESSetDivergenceTolerance()` 3714 @*/ 3715 PetscErrorCode SNESGetForceIteration(SNES snes,PetscBool *force) 3716 { 3717 PetscFunctionBegin; 3718 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 3719 *force = snes->forceiteration; 3720 PetscFunctionReturn(0); 3721 } 3722 3723 /*@ 3724 SNESSetTolerances - Sets various parameters used in convergence tests. 3725 3726 Logically Collective on SNES 3727 3728 Input Parameters: 3729 + snes - the SNES context 3730 . abstol - absolute convergence tolerance 3731 . rtol - relative convergence tolerance 3732 . stol - convergence tolerance in terms of the norm of the change in the solution between steps, || delta x || < stol*|| x || 3733 . maxit - maximum number of iterations 3734 - maxf - maximum number of function evaluations (-1 indicates no limit) 3735 3736 Options Database Keys: 3737 + -snes_atol <abstol> - Sets abstol 3738 . -snes_rtol <rtol> - Sets rtol 3739 . -snes_stol <stol> - Sets stol 3740 . -snes_max_it <maxit> - Sets maxit 3741 - -snes_max_funcs <maxf> - Sets maxf 3742 3743 Notes: 3744 The default maximum number of iterations is 50. 3745 The default maximum number of function evaluations is 1000. 3746 3747 Level: intermediate 3748 3749 .seealso: `SNESSetTrustRegionTolerance()`, `SNESSetDivergenceTolerance()`, `SNESSetForceIteration()` 3750 @*/ 3751 PetscErrorCode SNESSetTolerances(SNES snes,PetscReal abstol,PetscReal rtol,PetscReal stol,PetscInt maxit,PetscInt maxf) 3752 { 3753 PetscFunctionBegin; 3754 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 3755 PetscValidLogicalCollectiveReal(snes,abstol,2); 3756 PetscValidLogicalCollectiveReal(snes,rtol,3); 3757 PetscValidLogicalCollectiveReal(snes,stol,4); 3758 PetscValidLogicalCollectiveInt(snes,maxit,5); 3759 PetscValidLogicalCollectiveInt(snes,maxf,6); 3760 3761 if (abstol != PETSC_DEFAULT) { 3762 PetscCheck(abstol >= 0.0,PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Absolute tolerance %g must be non-negative",(double)abstol); 3763 snes->abstol = abstol; 3764 } 3765 if (rtol != PETSC_DEFAULT) { 3766 PetscCheck(rtol >= 0.0 && 1.0 > rtol,PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Relative tolerance %g must be non-negative and less than 1.0",(double)rtol); 3767 snes->rtol = rtol; 3768 } 3769 if (stol != PETSC_DEFAULT) { 3770 PetscCheck(stol >= 0.0,PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Step tolerance %g must be non-negative",(double)stol); 3771 snes->stol = stol; 3772 } 3773 if (maxit != PETSC_DEFAULT) { 3774 PetscCheck(maxit >= 0,PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of iterations %" PetscInt_FMT " must be non-negative",maxit); 3775 snes->max_its = maxit; 3776 } 3777 if (maxf != PETSC_DEFAULT) { 3778 PetscCheck(maxf >= -1,PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of function evaluations %" PetscInt_FMT " must be -1 or nonnegative",maxf); 3779 snes->max_funcs = maxf; 3780 } 3781 snes->tolerancesset = PETSC_TRUE; 3782 PetscFunctionReturn(0); 3783 } 3784 3785 /*@ 3786 SNESSetDivergenceTolerance - Sets the divergence tolerance used for the SNES divergence test. 3787 3788 Logically Collective on SNES 3789 3790 Input Parameters: 3791 + snes - the SNES context 3792 - divtol - the divergence tolerance. Use -1 to deactivate the test. 3793 3794 Options Database Keys: 3795 . -snes_divergence_tolerance <divtol> - Sets divtol 3796 3797 Notes: 3798 The default divergence tolerance is 1e4. 3799 3800 Level: intermediate 3801 3802 .seealso: `SNESSetTolerances()`, `SNESGetDivergenceTolerance` 3803 @*/ 3804 PetscErrorCode SNESSetDivergenceTolerance(SNES snes,PetscReal divtol) 3805 { 3806 PetscFunctionBegin; 3807 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 3808 PetscValidLogicalCollectiveReal(snes,divtol,2); 3809 3810 if (divtol != PETSC_DEFAULT) { 3811 snes->divtol = divtol; 3812 } 3813 else { 3814 snes->divtol = 1.0e4; 3815 } 3816 PetscFunctionReturn(0); 3817 } 3818 3819 /*@ 3820 SNESGetTolerances - Gets various parameters used in convergence tests. 3821 3822 Not Collective 3823 3824 Input Parameters: 3825 + snes - the SNES context 3826 . atol - absolute convergence tolerance 3827 . rtol - relative convergence tolerance 3828 . stol - convergence tolerance in terms of the norm 3829 of the change in the solution between steps 3830 . maxit - maximum number of iterations 3831 - maxf - maximum number of function evaluations 3832 3833 Notes: 3834 The user can specify NULL for any parameter that is not needed. 3835 3836 Level: intermediate 3837 3838 .seealso: `SNESSetTolerances()` 3839 @*/ 3840 PetscErrorCode SNESGetTolerances(SNES snes,PetscReal *atol,PetscReal *rtol,PetscReal *stol,PetscInt *maxit,PetscInt *maxf) 3841 { 3842 PetscFunctionBegin; 3843 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 3844 if (atol) *atol = snes->abstol; 3845 if (rtol) *rtol = snes->rtol; 3846 if (stol) *stol = snes->stol; 3847 if (maxit) *maxit = snes->max_its; 3848 if (maxf) *maxf = snes->max_funcs; 3849 PetscFunctionReturn(0); 3850 } 3851 3852 /*@ 3853 SNESGetDivergenceTolerance - Gets divergence tolerance used in divergence test. 3854 3855 Not Collective 3856 3857 Input Parameters: 3858 + snes - the SNES context 3859 - divtol - divergence tolerance 3860 3861 Level: intermediate 3862 3863 .seealso: `SNESSetDivergenceTolerance()` 3864 @*/ 3865 PetscErrorCode SNESGetDivergenceTolerance(SNES snes,PetscReal *divtol) 3866 { 3867 PetscFunctionBegin; 3868 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 3869 if (divtol) *divtol = snes->divtol; 3870 PetscFunctionReturn(0); 3871 } 3872 3873 /*@ 3874 SNESSetTrustRegionTolerance - Sets the trust region parameter tolerance. 3875 3876 Logically Collective on SNES 3877 3878 Input Parameters: 3879 + snes - the SNES context 3880 - tol - tolerance 3881 3882 Options Database Key: 3883 . -snes_trtol <tol> - Sets tol 3884 3885 Level: intermediate 3886 3887 .seealso: `SNESSetTolerances()` 3888 @*/ 3889 PetscErrorCode SNESSetTrustRegionTolerance(SNES snes,PetscReal tol) 3890 { 3891 PetscFunctionBegin; 3892 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 3893 PetscValidLogicalCollectiveReal(snes,tol,2); 3894 snes->deltatol = tol; 3895 PetscFunctionReturn(0); 3896 } 3897 3898 PETSC_INTERN PetscErrorCode SNESMonitorRange_Private(SNES,PetscInt,PetscReal*); 3899 3900 PetscErrorCode SNESMonitorLGRange(SNES snes,PetscInt n,PetscReal rnorm,void *monctx) 3901 { 3902 PetscDrawLG lg; 3903 PetscReal x,y,per; 3904 PetscViewer v = (PetscViewer)monctx; 3905 static PetscReal prev; /* should be in the context */ 3906 PetscDraw draw; 3907 3908 PetscFunctionBegin; 3909 PetscValidHeaderSpecific(v,PETSC_VIEWER_CLASSID,4); 3910 PetscCall(PetscViewerDrawGetDrawLG(v,0,&lg)); 3911 if (!n) PetscCall(PetscDrawLGReset(lg)); 3912 PetscCall(PetscDrawLGGetDraw(lg,&draw)); 3913 PetscCall(PetscDrawSetTitle(draw,"Residual norm")); 3914 x = (PetscReal)n; 3915 if (rnorm > 0.0) y = PetscLog10Real(rnorm); 3916 else y = -15.0; 3917 PetscCall(PetscDrawLGAddPoint(lg,&x,&y)); 3918 if (n < 20 || !(n % 5) || snes->reason) { 3919 PetscCall(PetscDrawLGDraw(lg)); 3920 PetscCall(PetscDrawLGSave(lg)); 3921 } 3922 3923 PetscCall(PetscViewerDrawGetDrawLG(v,1,&lg)); 3924 if (!n) PetscCall(PetscDrawLGReset(lg)); 3925 PetscCall(PetscDrawLGGetDraw(lg,&draw)); 3926 PetscCall(PetscDrawSetTitle(draw,"% elemts > .2*max elemt")); 3927 PetscCall(SNESMonitorRange_Private(snes,n,&per)); 3928 x = (PetscReal)n; 3929 y = 100.0*per; 3930 PetscCall(PetscDrawLGAddPoint(lg,&x,&y)); 3931 if (n < 20 || !(n % 5) || snes->reason) { 3932 PetscCall(PetscDrawLGDraw(lg)); 3933 PetscCall(PetscDrawLGSave(lg)); 3934 } 3935 3936 PetscCall(PetscViewerDrawGetDrawLG(v,2,&lg)); 3937 if (!n) {prev = rnorm;PetscCall(PetscDrawLGReset(lg));} 3938 PetscCall(PetscDrawLGGetDraw(lg,&draw)); 3939 PetscCall(PetscDrawSetTitle(draw,"(norm -oldnorm)/oldnorm")); 3940 x = (PetscReal)n; 3941 y = (prev - rnorm)/prev; 3942 PetscCall(PetscDrawLGAddPoint(lg,&x,&y)); 3943 if (n < 20 || !(n % 5) || snes->reason) { 3944 PetscCall(PetscDrawLGDraw(lg)); 3945 PetscCall(PetscDrawLGSave(lg)); 3946 } 3947 3948 PetscCall(PetscViewerDrawGetDrawLG(v,3,&lg)); 3949 if (!n) PetscCall(PetscDrawLGReset(lg)); 3950 PetscCall(PetscDrawLGGetDraw(lg,&draw)); 3951 PetscCall(PetscDrawSetTitle(draw,"(norm -oldnorm)/oldnorm*(% > .2 max)")); 3952 x = (PetscReal)n; 3953 y = (prev - rnorm)/(prev*per); 3954 if (n > 2) { /*skip initial crazy value */ 3955 PetscCall(PetscDrawLGAddPoint(lg,&x,&y)); 3956 } 3957 if (n < 20 || !(n % 5) || snes->reason) { 3958 PetscCall(PetscDrawLGDraw(lg)); 3959 PetscCall(PetscDrawLGSave(lg)); 3960 } 3961 prev = rnorm; 3962 PetscFunctionReturn(0); 3963 } 3964 3965 /*@ 3966 SNESMonitor - runs the user provided monitor routines, if they exist 3967 3968 Collective on SNES 3969 3970 Input Parameters: 3971 + snes - nonlinear solver context obtained from SNESCreate() 3972 . iter - iteration number 3973 - rnorm - relative norm of the residual 3974 3975 Notes: 3976 This routine is called by the SNES implementations. 3977 It does not typically need to be called by the user. 3978 3979 Level: developer 3980 3981 .seealso: `SNESMonitorSet()` 3982 @*/ 3983 PetscErrorCode SNESMonitor(SNES snes,PetscInt iter,PetscReal rnorm) 3984 { 3985 PetscInt i,n = snes->numbermonitors; 3986 3987 PetscFunctionBegin; 3988 PetscCall(VecLockReadPush(snes->vec_sol)); 3989 for (i=0; i<n; i++) { 3990 PetscCall((*snes->monitor[i])(snes,iter,rnorm,snes->monitorcontext[i])); 3991 } 3992 PetscCall(VecLockReadPop(snes->vec_sol)); 3993 PetscFunctionReturn(0); 3994 } 3995 3996 /* ------------ Routines to set performance monitoring options ----------- */ 3997 3998 /*MC 3999 SNESMonitorFunction - functional form passed to SNESMonitorSet() to monitor convergence of nonlinear solver 4000 4001 Synopsis: 4002 #include <petscsnes.h> 4003 $ PetscErrorCode SNESMonitorFunction(SNES snes,PetscInt its, PetscReal norm,void *mctx) 4004 4005 Collective on snes 4006 4007 Input Parameters: 4008 + snes - the SNES context 4009 . its - iteration number 4010 . norm - 2-norm function value (may be estimated) 4011 - mctx - [optional] monitoring context 4012 4013 Level: advanced 4014 4015 .seealso: `SNESMonitorSet()`, `SNESMonitorGet()` 4016 M*/ 4017 4018 /*@C 4019 SNESMonitorSet - Sets an ADDITIONAL function that is to be used at every 4020 iteration of the nonlinear solver to display the iteration's 4021 progress. 4022 4023 Logically Collective on SNES 4024 4025 Input Parameters: 4026 + snes - the SNES context 4027 . f - the monitor function, see SNESMonitorFunction for the calling sequence 4028 . mctx - [optional] user-defined context for private data for the 4029 monitor routine (use NULL if no context is desired) 4030 - monitordestroy - [optional] routine that frees monitor context 4031 (may be NULL) 4032 4033 Options Database Keys: 4034 + -snes_monitor - sets SNESMonitorDefault() 4035 . -snes_monitor draw::draw_lg - sets line graph monitor, 4036 - -snes_monitor_cancel - cancels all monitors that have 4037 been hardwired into a code by 4038 calls to SNESMonitorSet(), but 4039 does not cancel those set via 4040 the options database. 4041 4042 Notes: 4043 Several different monitoring routines may be set by calling 4044 SNESMonitorSet() multiple times; all will be called in the 4045 order in which they were set. 4046 4047 Fortran Notes: 4048 Only a single monitor function can be set for each SNES object 4049 4050 Level: intermediate 4051 4052 .seealso: `SNESMonitorDefault()`, `SNESMonitorCancel()`, `SNESMonitorFunction` 4053 @*/ 4054 PetscErrorCode SNESMonitorSet(SNES snes,PetscErrorCode (*f)(SNES,PetscInt,PetscReal,void*),void *mctx,PetscErrorCode (*monitordestroy)(void**)) 4055 { 4056 PetscInt i; 4057 PetscBool identical; 4058 4059 PetscFunctionBegin; 4060 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 4061 for (i=0; i<snes->numbermonitors;i++) { 4062 PetscCall(PetscMonitorCompare((PetscErrorCode (*)(void))f,mctx,monitordestroy,(PetscErrorCode (*)(void))snes->monitor[i],snes->monitorcontext[i],snes->monitordestroy[i],&identical)); 4063 if (identical) PetscFunctionReturn(0); 4064 } 4065 PetscCheck(snes->numbermonitors < MAXSNESMONITORS,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Too many monitors set"); 4066 snes->monitor[snes->numbermonitors] = f; 4067 snes->monitordestroy[snes->numbermonitors] = monitordestroy; 4068 snes->monitorcontext[snes->numbermonitors++] = (void*)mctx; 4069 PetscFunctionReturn(0); 4070 } 4071 4072 /*@ 4073 SNESMonitorCancel - Clears all the monitor functions for a SNES object. 4074 4075 Logically Collective on SNES 4076 4077 Input Parameters: 4078 . snes - the SNES context 4079 4080 Options Database Key: 4081 . -snes_monitor_cancel - cancels all monitors that have been hardwired 4082 into a code by calls to SNESMonitorSet(), but does not cancel those 4083 set via the options database 4084 4085 Notes: 4086 There is no way to clear one specific monitor from a SNES object. 4087 4088 Level: intermediate 4089 4090 .seealso: `SNESMonitorDefault()`, `SNESMonitorSet()` 4091 @*/ 4092 PetscErrorCode SNESMonitorCancel(SNES snes) 4093 { 4094 PetscInt i; 4095 4096 PetscFunctionBegin; 4097 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 4098 for (i=0; i<snes->numbermonitors; i++) { 4099 if (snes->monitordestroy[i]) { 4100 PetscCall((*snes->monitordestroy[i])(&snes->monitorcontext[i])); 4101 } 4102 } 4103 snes->numbermonitors = 0; 4104 PetscFunctionReturn(0); 4105 } 4106 4107 /*MC 4108 SNESConvergenceTestFunction - functional form used for testing of convergence of nonlinear solver 4109 4110 Synopsis: 4111 #include <petscsnes.h> 4112 $ PetscErrorCode SNESConvergenceTest(SNES snes,PetscInt it,PetscReal xnorm,PetscReal gnorm,PetscReal f,SNESConvergedReason *reason,void *cctx) 4113 4114 Collective on snes 4115 4116 Input Parameters: 4117 + snes - the SNES context 4118 . it - current iteration (0 is the first and is before any Newton step) 4119 . xnorm - 2-norm of current iterate 4120 . gnorm - 2-norm of current step 4121 . f - 2-norm of function 4122 - cctx - [optional] convergence context 4123 4124 Output Parameter: 4125 . reason - reason for convergence/divergence, only needs to be set when convergence or divergence is detected 4126 4127 Level: intermediate 4128 4129 .seealso: `SNESSetConvergenceTest()`, `SNESGetConvergenceTest()` 4130 M*/ 4131 4132 /*@C 4133 SNESSetConvergenceTest - Sets the function that is to be used 4134 to test for convergence of the nonlinear iterative solution. 4135 4136 Logically Collective on SNES 4137 4138 Input Parameters: 4139 + snes - the SNES context 4140 . SNESConvergenceTestFunction - routine to test for convergence 4141 . cctx - [optional] context for private data for the convergence routine (may be NULL) 4142 - destroy - [optional] destructor for the context (may be NULL; PETSC_NULL_FUNCTION in Fortran) 4143 4144 Level: advanced 4145 4146 .seealso: `SNESConvergedDefault()`, `SNESConvergedSkip()`, `SNESConvergenceTestFunction` 4147 @*/ 4148 PetscErrorCode SNESSetConvergenceTest(SNES snes,PetscErrorCode (*SNESConvergenceTestFunction)(SNES,PetscInt,PetscReal,PetscReal,PetscReal,SNESConvergedReason*,void*),void *cctx,PetscErrorCode (*destroy)(void*)) 4149 { 4150 PetscFunctionBegin; 4151 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 4152 if (!SNESConvergenceTestFunction) SNESConvergenceTestFunction = SNESConvergedSkip; 4153 if (snes->ops->convergeddestroy) PetscCall((*snes->ops->convergeddestroy)(snes->cnvP)); 4154 snes->ops->converged = SNESConvergenceTestFunction; 4155 snes->ops->convergeddestroy = destroy; 4156 snes->cnvP = cctx; 4157 PetscFunctionReturn(0); 4158 } 4159 4160 /*@ 4161 SNESGetConvergedReason - Gets the reason the SNES iteration was stopped. 4162 4163 Not Collective 4164 4165 Input Parameter: 4166 . snes - the SNES context 4167 4168 Output Parameter: 4169 . reason - negative value indicates diverged, positive value converged, see SNESConvergedReason or the 4170 manual pages for the individual convergence tests for complete lists 4171 4172 Options Database: 4173 . -snes_converged_reason - prints the reason to standard out 4174 4175 Level: intermediate 4176 4177 Notes: 4178 Should only be called after the call the SNESSolve() is complete, if it is called earlier it returns the value SNES__CONVERGED_ITERATING. 4179 4180 .seealso: `SNESSetConvergenceTest()`, `SNESSetConvergedReason()`, `SNESConvergedReason` 4181 @*/ 4182 PetscErrorCode SNESGetConvergedReason(SNES snes,SNESConvergedReason *reason) 4183 { 4184 PetscFunctionBegin; 4185 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 4186 PetscValidPointer(reason,2); 4187 *reason = snes->reason; 4188 PetscFunctionReturn(0); 4189 } 4190 4191 /*@C 4192 SNESGetConvergedReasonString - Return a human readable string for snes converged reason 4193 4194 Not Collective 4195 4196 Input Parameter: 4197 . snes - the SNES context 4198 4199 Output Parameter: 4200 . strreason - a human readable string that describes SNES converged reason 4201 4202 Level: beginner 4203 4204 .seealso: `SNESGetConvergedReason()` 4205 @*/ 4206 PetscErrorCode SNESGetConvergedReasonString(SNES snes, const char** strreason) 4207 { 4208 PetscFunctionBegin; 4209 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 4210 PetscValidPointer(strreason,2); 4211 *strreason = SNESConvergedReasons[snes->reason]; 4212 PetscFunctionReturn(0); 4213 } 4214 4215 /*@ 4216 SNESSetConvergedReason - Sets the reason the SNES iteration was stopped. 4217 4218 Not Collective 4219 4220 Input Parameters: 4221 + snes - the SNES context 4222 - reason - negative value indicates diverged, positive value converged, see SNESConvergedReason or the 4223 manual pages for the individual convergence tests for complete lists 4224 4225 Level: intermediate 4226 4227 .seealso: `SNESGetConvergedReason()`, `SNESSetConvergenceTest()`, `SNESConvergedReason` 4228 @*/ 4229 PetscErrorCode SNESSetConvergedReason(SNES snes,SNESConvergedReason reason) 4230 { 4231 PetscFunctionBegin; 4232 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 4233 snes->reason = reason; 4234 PetscFunctionReturn(0); 4235 } 4236 4237 /*@ 4238 SNESSetConvergenceHistory - Sets the array used to hold the convergence history. 4239 4240 Logically Collective on SNES 4241 4242 Input Parameters: 4243 + snes - iterative context obtained from SNESCreate() 4244 . a - array to hold history, this array will contain the function norms computed at each step 4245 . its - integer array holds the number of linear iterations for each solve. 4246 . na - size of a and its 4247 - reset - PETSC_TRUE indicates each new nonlinear solve resets the history counter to zero, 4248 else it continues storing new values for new nonlinear solves after the old ones 4249 4250 Notes: 4251 If 'a' and 'its' are NULL then space is allocated for the history. If 'na' PETSC_DECIDE or PETSC_DEFAULT then a 4252 default array of length 10000 is allocated. 4253 4254 This routine is useful, e.g., when running a code for purposes 4255 of accurate performance monitoring, when no I/O should be done 4256 during the section of code that is being timed. 4257 4258 Level: intermediate 4259 4260 .seealso: `SNESGetConvergenceHistory()` 4261 4262 @*/ 4263 PetscErrorCode SNESSetConvergenceHistory(SNES snes,PetscReal a[],PetscInt its[],PetscInt na,PetscBool reset) 4264 { 4265 PetscFunctionBegin; 4266 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 4267 if (a) PetscValidRealPointer(a,2); 4268 if (its) PetscValidIntPointer(its,3); 4269 if (!a) { 4270 if (na == PETSC_DECIDE || na == PETSC_DEFAULT) na = 1000; 4271 PetscCall(PetscCalloc2(na,&a,na,&its)); 4272 snes->conv_hist_alloc = PETSC_TRUE; 4273 } 4274 snes->conv_hist = a; 4275 snes->conv_hist_its = its; 4276 snes->conv_hist_max = (size_t)na; 4277 snes->conv_hist_len = 0; 4278 snes->conv_hist_reset = reset; 4279 PetscFunctionReturn(0); 4280 } 4281 4282 #if defined(PETSC_HAVE_MATLAB_ENGINE) 4283 #include <engine.h> /* MATLAB include file */ 4284 #include <mex.h> /* MATLAB include file */ 4285 4286 PETSC_EXTERN mxArray *SNESGetConvergenceHistoryMatlab(SNES snes) 4287 { 4288 mxArray *mat; 4289 PetscInt i; 4290 PetscReal *ar; 4291 4292 PetscFunctionBegin; 4293 mat = mxCreateDoubleMatrix(snes->conv_hist_len,1,mxREAL); 4294 ar = (PetscReal*) mxGetData(mat); 4295 for (i=0; i<snes->conv_hist_len; i++) ar[i] = snes->conv_hist[i]; 4296 PetscFunctionReturn(mat); 4297 } 4298 #endif 4299 4300 /*@C 4301 SNESGetConvergenceHistory - Gets the array used to hold the convergence history. 4302 4303 Not Collective 4304 4305 Input Parameter: 4306 . snes - iterative context obtained from SNESCreate() 4307 4308 Output Parameters: 4309 + a - array to hold history 4310 . its - integer array holds the number of linear iterations (or 4311 negative if not converged) for each solve. 4312 - na - size of a and its 4313 4314 Notes: 4315 The calling sequence for this routine in Fortran is 4316 $ call SNESGetConvergenceHistory(SNES snes, integer na, integer ierr) 4317 4318 This routine is useful, e.g., when running a code for purposes 4319 of accurate performance monitoring, when no I/O should be done 4320 during the section of code that is being timed. 4321 4322 Level: intermediate 4323 4324 .seealso: `SNESSetConvergenceHistory()` 4325 4326 @*/ 4327 PetscErrorCode SNESGetConvergenceHistory(SNES snes,PetscReal *a[],PetscInt *its[],PetscInt *na) 4328 { 4329 PetscFunctionBegin; 4330 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 4331 if (a) *a = snes->conv_hist; 4332 if (its) *its = snes->conv_hist_its; 4333 if (na) *na = (PetscInt) snes->conv_hist_len; 4334 PetscFunctionReturn(0); 4335 } 4336 4337 /*@C 4338 SNESSetUpdate - Sets the general-purpose update function called 4339 at the beginning of every iteration of the nonlinear solve. Specifically 4340 it is called just before the Jacobian is "evaluated". 4341 4342 Logically Collective on SNES 4343 4344 Input Parameters: 4345 + snes - The nonlinear solver context 4346 - func - The function 4347 4348 Calling sequence of func: 4349 $ func (SNES snes, PetscInt step); 4350 4351 . step - The current step of the iteration 4352 4353 Level: advanced 4354 4355 Note: 4356 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() 4357 This is not used by most users. 4358 4359 There are a varity of function hooks one many set that are called at different stages of the nonlinear solution process, see the functions listed below. 4360 4361 .seealso `SNESSetJacobian()`, `SNESSolve()`, `SNESLineSearchSetPreCheck()`, `SNESLineSearchSetPostCheck()`, `SNESNewtonTRSetPreCheck()`, `SNESNewtonTRSetPostCheck()`, 4362 `SNESMonitorSet()`, `SNESSetDivergenceTest()` 4363 @*/ 4364 PetscErrorCode SNESSetUpdate(SNES snes, PetscErrorCode (*func)(SNES, PetscInt)) 4365 { 4366 PetscFunctionBegin; 4367 PetscValidHeaderSpecific(snes, SNES_CLASSID,1); 4368 snes->ops->update = func; 4369 PetscFunctionReturn(0); 4370 } 4371 4372 /* 4373 SNESScaleStep_Private - Scales a step so that its length is less than the 4374 positive parameter delta. 4375 4376 Input Parameters: 4377 + snes - the SNES context 4378 . y - approximate solution of linear system 4379 . fnorm - 2-norm of current function 4380 - delta - trust region size 4381 4382 Output Parameters: 4383 + gpnorm - predicted function norm at the new point, assuming local 4384 linearization. The value is zero if the step lies within the trust 4385 region, and exceeds zero otherwise. 4386 - ynorm - 2-norm of the step 4387 4388 Note: 4389 For non-trust region methods such as SNESNEWTONLS, the parameter delta 4390 is set to be the maximum allowable step size. 4391 4392 */ 4393 PetscErrorCode SNESScaleStep_Private(SNES snes,Vec y,PetscReal *fnorm,PetscReal *delta,PetscReal *gpnorm,PetscReal *ynorm) 4394 { 4395 PetscReal nrm; 4396 PetscScalar cnorm; 4397 4398 PetscFunctionBegin; 4399 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 4400 PetscValidHeaderSpecific(y,VEC_CLASSID,2); 4401 PetscCheckSameComm(snes,1,y,2); 4402 4403 PetscCall(VecNorm(y,NORM_2,&nrm)); 4404 if (nrm > *delta) { 4405 nrm = *delta/nrm; 4406 *gpnorm = (1.0 - nrm)*(*fnorm); 4407 cnorm = nrm; 4408 PetscCall(VecScale(y,cnorm)); 4409 *ynorm = *delta; 4410 } else { 4411 *gpnorm = 0.0; 4412 *ynorm = nrm; 4413 } 4414 PetscFunctionReturn(0); 4415 } 4416 4417 /*@C 4418 SNESConvergedReasonView - Displays the reason a SNES solve converged or diverged to a viewer 4419 4420 Collective on SNES 4421 4422 Parameter: 4423 + snes - iterative context obtained from SNESCreate() 4424 - viewer - the viewer to display the reason 4425 4426 Options Database Keys: 4427 + -snes_converged_reason - print reason for converged or diverged, also prints number of iterations 4428 - -snes_converged_reason ::failed - only print reason and number of iterations when diverged 4429 4430 Notes: 4431 To change the format of the output call PetscViewerPushFormat(viewer,format) before this call. Use PETSC_VIEWER_DEFAULT for the default, 4432 use PETSC_VIEWER_FAILED to only display a reason if it fails. 4433 4434 Level: beginner 4435 4436 .seealso: `SNESCreate()`, `SNESSetUp()`, `SNESDestroy()`, `SNESSetTolerances()`, `SNESConvergedDefault()`, `SNESGetConvergedReason()`, `SNESConvergedReasonViewFromOptions()`, 4437 `PetscViewerPushFormat()`, `PetscViewerPopFormat()` 4438 4439 @*/ 4440 PetscErrorCode SNESConvergedReasonView(SNES snes,PetscViewer viewer) 4441 { 4442 PetscViewerFormat format; 4443 PetscBool isAscii; 4444 4445 PetscFunctionBegin; 4446 if (!viewer) viewer = PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)snes)); 4447 PetscCall(PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&isAscii)); 4448 if (isAscii) { 4449 PetscCall(PetscViewerGetFormat(viewer, &format)); 4450 PetscCall(PetscViewerASCIIAddTab(viewer,((PetscObject)snes)->tablevel)); 4451 if (format == PETSC_VIEWER_ASCII_INFO_DETAIL) { 4452 DM dm; 4453 Vec u; 4454 PetscDS prob; 4455 PetscInt Nf, f; 4456 PetscErrorCode (**exactSol)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar[], void *); 4457 void **exactCtx; 4458 PetscReal error; 4459 4460 PetscCall(SNESGetDM(snes, &dm)); 4461 PetscCall(SNESGetSolution(snes, &u)); 4462 PetscCall(DMGetDS(dm, &prob)); 4463 PetscCall(PetscDSGetNumFields(prob, &Nf)); 4464 PetscCall(PetscMalloc2(Nf, &exactSol, Nf, &exactCtx)); 4465 for (f = 0; f < Nf; ++f) PetscCall(PetscDSGetExactSolution(prob, f, &exactSol[f], &exactCtx[f])); 4466 PetscCall(DMComputeL2Diff(dm, 0.0, exactSol, exactCtx, u, &error)); 4467 PetscCall(PetscFree2(exactSol, exactCtx)); 4468 if (error < 1.0e-11) PetscCall(PetscViewerASCIIPrintf(viewer, "L_2 Error: < 1.0e-11\n")); 4469 else PetscCall(PetscViewerASCIIPrintf(viewer, "L_2 Error: %g\n", (double)error)); 4470 } 4471 if (snes->reason > 0 && format != PETSC_VIEWER_FAILED) { 4472 if (((PetscObject) snes)->prefix) { 4473 PetscCall(PetscViewerASCIIPrintf(viewer,"Nonlinear %s solve converged due to %s iterations %" PetscInt_FMT "\n",((PetscObject) snes)->prefix,SNESConvergedReasons[snes->reason],snes->iter)); 4474 } else { 4475 PetscCall(PetscViewerASCIIPrintf(viewer,"Nonlinear solve converged due to %s iterations %" PetscInt_FMT "\n",SNESConvergedReasons[snes->reason],snes->iter)); 4476 } 4477 } else if (snes->reason <= 0) { 4478 if (((PetscObject) snes)->prefix) { 4479 PetscCall(PetscViewerASCIIPrintf(viewer,"Nonlinear %s solve did not converge due to %s iterations %" PetscInt_FMT "\n",((PetscObject) snes)->prefix,SNESConvergedReasons[snes->reason],snes->iter)); 4480 } else { 4481 PetscCall(PetscViewerASCIIPrintf(viewer,"Nonlinear solve did not converge due to %s iterations %" PetscInt_FMT "\n",SNESConvergedReasons[snes->reason],snes->iter)); 4482 } 4483 } 4484 PetscCall(PetscViewerASCIISubtractTab(viewer,((PetscObject)snes)->tablevel)); 4485 } 4486 PetscFunctionReturn(0); 4487 } 4488 4489 /*@C 4490 SNESConvergedReasonViewSet - Sets an ADDITIONAL function that is to be used at the 4491 end of the nonlinear solver to display the conver reason of the nonlinear solver. 4492 4493 Logically Collective on SNES 4494 4495 Input Parameters: 4496 + snes - the SNES context 4497 . f - the snes converged reason view function 4498 . vctx - [optional] user-defined context for private data for the 4499 snes converged reason view routine (use NULL if no context is desired) 4500 - reasonviewdestroy - [optional] routine that frees reasonview context 4501 (may be NULL) 4502 4503 Options Database Keys: 4504 + -snes_converged_reason - sets a default SNESConvergedReasonView() 4505 - -snes_converged_reason_view_cancel - cancels all converged reason viewers that have 4506 been hardwired into a code by 4507 calls to SNESConvergedReasonViewSet(), but 4508 does not cancel those set via 4509 the options database. 4510 4511 Notes: 4512 Several different converged reason view routines may be set by calling 4513 SNESConvergedReasonViewSet() multiple times; all will be called in the 4514 order in which they were set. 4515 4516 Level: intermediate 4517 4518 .seealso: `SNESConvergedReasonView()`, `SNESConvergedReasonViewCancel()` 4519 @*/ 4520 PetscErrorCode SNESConvergedReasonViewSet(SNES snes,PetscErrorCode (*f)(SNES,void*),void *vctx,PetscErrorCode (*reasonviewdestroy)(void**)) 4521 { 4522 PetscInt i; 4523 PetscBool identical; 4524 4525 PetscFunctionBegin; 4526 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 4527 for (i=0; i<snes->numberreasonviews;i++) { 4528 PetscCall(PetscMonitorCompare((PetscErrorCode (*)(void))f,vctx,reasonviewdestroy,(PetscErrorCode (*)(void))snes->reasonview[i],snes->reasonviewcontext[i],snes->reasonviewdestroy[i],&identical)); 4529 if (identical) PetscFunctionReturn(0); 4530 } 4531 PetscCheck(snes->numberreasonviews < MAXSNESREASONVIEWS,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Too many SNES reasonview set"); 4532 snes->reasonview[snes->numberreasonviews] = f; 4533 snes->reasonviewdestroy[snes->numberreasonviews] = reasonviewdestroy; 4534 snes->reasonviewcontext[snes->numberreasonviews++] = (void*)vctx; 4535 PetscFunctionReturn(0); 4536 } 4537 4538 /*@ 4539 SNESConvergedReasonViewFromOptions - Processes command line options to determine if/how a SNESReason is to be viewed. 4540 All the user-provided convergedReasonView routines will be involved as well, if they exist. 4541 4542 Collective on SNES 4543 4544 Input Parameters: 4545 . snes - the SNES object 4546 4547 Level: intermediate 4548 4549 .seealso: `SNESCreate()`, `SNESSetUp()`, `SNESDestroy()`, `SNESSetTolerances()`, `SNESConvergedDefault()`, `SNESGetConvergedReason()`, `SNESConvergedReasonView()` 4550 4551 @*/ 4552 PetscErrorCode SNESConvergedReasonViewFromOptions(SNES snes) 4553 { 4554 PetscViewer viewer; 4555 PetscBool flg; 4556 static PetscBool incall = PETSC_FALSE; 4557 PetscViewerFormat format; 4558 PetscInt i; 4559 4560 PetscFunctionBegin; 4561 if (incall) PetscFunctionReturn(0); 4562 incall = PETSC_TRUE; 4563 4564 /* All user-provided viewers are called first, if they exist. */ 4565 for (i=0; i<snes->numberreasonviews; i++) { 4566 PetscCall((*snes->reasonview[i])(snes,snes->reasonviewcontext[i])); 4567 } 4568 4569 /* Call PETSc default routine if users ask for it */ 4570 PetscCall(PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_converged_reason",&viewer,&format,&flg)); 4571 if (flg) { 4572 PetscCall(PetscViewerPushFormat(viewer,format)); 4573 PetscCall(SNESConvergedReasonView(snes,viewer)); 4574 PetscCall(PetscViewerPopFormat(viewer)); 4575 PetscCall(PetscViewerDestroy(&viewer)); 4576 } 4577 incall = PETSC_FALSE; 4578 PetscFunctionReturn(0); 4579 } 4580 4581 /*@ 4582 SNESSolve - Solves a nonlinear system F(x) = b. 4583 Call SNESSolve() after calling SNESCreate() and optional routines of the form SNESSetXXX(). 4584 4585 Collective on SNES 4586 4587 Input Parameters: 4588 + snes - the SNES context 4589 . b - the constant part of the equation F(x) = b, or NULL to use zero. 4590 - x - the solution vector. 4591 4592 Notes: 4593 The user should initialize the vector,x, with the initial guess 4594 for the nonlinear solve prior to calling SNESSolve(). In particular, 4595 to employ an initial guess of zero, the user should explicitly set 4596 this vector to zero by calling VecSet(). 4597 4598 Level: beginner 4599 4600 .seealso: `SNESCreate()`, `SNESDestroy()`, `SNESSetFunction()`, `SNESSetJacobian()`, `SNESSetGridSequence()`, `SNESGetSolution()`, 4601 `SNESNewtonTRSetPreCheck()`, `SNESNewtonTRGetPreCheck()`, `SNESNewtonTRSetPostCheck()`, `SNESNewtonTRGetPostCheck()`, 4602 `SNESLineSearchSetPostCheck()`, `SNESLineSearchGetPostCheck()`, `SNESLineSearchSetPreCheck()`, `SNESLineSearchGetPreCheck()` 4603 @*/ 4604 PetscErrorCode SNESSolve(SNES snes,Vec b,Vec x) 4605 { 4606 PetscBool flg; 4607 PetscInt grid; 4608 Vec xcreated = NULL; 4609 DM dm; 4610 4611 PetscFunctionBegin; 4612 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 4613 if (x) PetscValidHeaderSpecific(x,VEC_CLASSID,3); 4614 if (x) PetscCheckSameComm(snes,1,x,3); 4615 if (b) PetscValidHeaderSpecific(b,VEC_CLASSID,2); 4616 if (b) PetscCheckSameComm(snes,1,b,2); 4617 4618 /* High level operations using the nonlinear solver */ 4619 { 4620 PetscViewer viewer; 4621 PetscViewerFormat format; 4622 PetscInt num; 4623 PetscBool flg; 4624 static PetscBool incall = PETSC_FALSE; 4625 4626 if (!incall) { 4627 /* Estimate the convergence rate of the discretization */ 4628 PetscCall(PetscOptionsGetViewer(PetscObjectComm((PetscObject) snes),((PetscObject)snes)->options, ((PetscObject) snes)->prefix, "-snes_convergence_estimate", &viewer, &format, &flg)); 4629 if (flg) { 4630 PetscConvEst conv; 4631 DM dm; 4632 PetscReal *alpha; /* Convergence rate of the solution error for each field in the L_2 norm */ 4633 PetscInt Nf; 4634 4635 incall = PETSC_TRUE; 4636 PetscCall(SNESGetDM(snes, &dm)); 4637 PetscCall(DMGetNumFields(dm, &Nf)); 4638 PetscCall(PetscCalloc1(Nf, &alpha)); 4639 PetscCall(PetscConvEstCreate(PetscObjectComm((PetscObject) snes), &conv)); 4640 PetscCall(PetscConvEstSetSolver(conv, (PetscObject) snes)); 4641 PetscCall(PetscConvEstSetFromOptions(conv)); 4642 PetscCall(PetscConvEstSetUp(conv)); 4643 PetscCall(PetscConvEstGetConvRate(conv, alpha)); 4644 PetscCall(PetscViewerPushFormat(viewer, format)); 4645 PetscCall(PetscConvEstRateView(conv, alpha, viewer)); 4646 PetscCall(PetscViewerPopFormat(viewer)); 4647 PetscCall(PetscViewerDestroy(&viewer)); 4648 PetscCall(PetscConvEstDestroy(&conv)); 4649 PetscCall(PetscFree(alpha)); 4650 incall = PETSC_FALSE; 4651 } 4652 /* Adaptively refine the initial grid */ 4653 num = 1; 4654 PetscCall(PetscOptionsGetInt(NULL, ((PetscObject) snes)->prefix, "-snes_adapt_initial", &num, &flg)); 4655 if (flg) { 4656 DMAdaptor adaptor; 4657 4658 incall = PETSC_TRUE; 4659 PetscCall(DMAdaptorCreate(PetscObjectComm((PetscObject)snes), &adaptor)); 4660 PetscCall(DMAdaptorSetSolver(adaptor, snes)); 4661 PetscCall(DMAdaptorSetSequenceLength(adaptor, num)); 4662 PetscCall(DMAdaptorSetFromOptions(adaptor)); 4663 PetscCall(DMAdaptorSetUp(adaptor)); 4664 PetscCall(DMAdaptorAdapt(adaptor, x, DM_ADAPTATION_INITIAL, &dm, &x)); 4665 PetscCall(DMAdaptorDestroy(&adaptor)); 4666 incall = PETSC_FALSE; 4667 } 4668 /* Use grid sequencing to adapt */ 4669 num = 0; 4670 PetscCall(PetscOptionsGetInt(NULL, ((PetscObject) snes)->prefix, "-snes_adapt_sequence", &num, NULL)); 4671 if (num) { 4672 DMAdaptor adaptor; 4673 4674 incall = PETSC_TRUE; 4675 PetscCall(DMAdaptorCreate(PetscObjectComm((PetscObject)snes), &adaptor)); 4676 PetscCall(DMAdaptorSetSolver(adaptor, snes)); 4677 PetscCall(DMAdaptorSetSequenceLength(adaptor, num)); 4678 PetscCall(DMAdaptorSetFromOptions(adaptor)); 4679 PetscCall(DMAdaptorSetUp(adaptor)); 4680 PetscCall(DMAdaptorAdapt(adaptor, x, DM_ADAPTATION_SEQUENTIAL, &dm, &x)); 4681 PetscCall(DMAdaptorDestroy(&adaptor)); 4682 incall = PETSC_FALSE; 4683 } 4684 } 4685 } 4686 if (!x) { x = snes->vec_sol; } 4687 if (!x) { 4688 PetscCall(SNESGetDM(snes,&dm)); 4689 PetscCall(DMCreateGlobalVector(dm,&xcreated)); 4690 x = xcreated; 4691 } 4692 PetscCall(SNESViewFromOptions(snes,NULL,"-snes_view_pre")); 4693 4694 for (grid=0; grid<snes->gridsequence; grid++) PetscCall(PetscViewerASCIIPushTab(PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)snes)))); 4695 for (grid=0; grid<snes->gridsequence+1; grid++) { 4696 4697 /* set solution vector */ 4698 if (!grid) PetscCall(PetscObjectReference((PetscObject)x)); 4699 PetscCall(VecDestroy(&snes->vec_sol)); 4700 snes->vec_sol = x; 4701 PetscCall(SNESGetDM(snes,&dm)); 4702 4703 /* set affine vector if provided */ 4704 if (b) PetscCall(PetscObjectReference((PetscObject)b)); 4705 PetscCall(VecDestroy(&snes->vec_rhs)); 4706 snes->vec_rhs = b; 4707 4708 if (snes->vec_rhs) PetscCheck(snes->vec_func != snes->vec_rhs,PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"Right hand side vector cannot be function vector"); 4709 PetscCheck(snes->vec_func != snes->vec_sol,PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"Solution vector cannot be function vector"); 4710 PetscCheck(snes->vec_rhs != snes->vec_sol,PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"Solution vector cannot be right hand side vector"); 4711 if (!snes->vec_sol_update /* && snes->vec_sol */) { 4712 PetscCall(VecDuplicate(snes->vec_sol,&snes->vec_sol_update)); 4713 PetscCall(PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->vec_sol_update)); 4714 } 4715 PetscCall(DMShellSetGlobalVector(dm,snes->vec_sol)); 4716 PetscCall(SNESSetUp(snes)); 4717 4718 if (!grid) { 4719 if (snes->ops->computeinitialguess) PetscCallBack("SNES callback initial guess",(*snes->ops->computeinitialguess)(snes,snes->vec_sol,snes->initialguessP)); 4720 } 4721 4722 if (snes->conv_hist_reset) snes->conv_hist_len = 0; 4723 if (snes->counters_reset) {snes->nfuncs = 0; snes->linear_its = 0; snes->numFailures = 0;} 4724 4725 PetscCall(PetscLogEventBegin(SNES_Solve,snes,0,0,0)); 4726 PetscUseTypeMethod(snes,solve); 4727 PetscCall(PetscLogEventEnd(SNES_Solve,snes,0,0,0)); 4728 PetscCheck(snes->reason,PETSC_COMM_SELF,PETSC_ERR_PLIB,"Internal error, solver returned without setting converged reason"); 4729 snes->domainerror = PETSC_FALSE; /* clear the flag if it has been set */ 4730 4731 if (snes->lagjac_persist) snes->jac_iter += snes->iter; 4732 if (snes->lagpre_persist) snes->pre_iter += snes->iter; 4733 4734 PetscCall(PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_test_local_min",NULL,NULL,&flg)); 4735 if (flg && !PetscPreLoadingOn) PetscCall(SNESTestLocalMin(snes)); 4736 /* Call converged reason views. This may involve user-provided viewers as well */ 4737 PetscCall(SNESConvergedReasonViewFromOptions(snes)); 4738 4739 if (snes->errorifnotconverged) PetscCheck(snes->reason >= 0,PetscObjectComm((PetscObject)snes),PETSC_ERR_NOT_CONVERGED,"SNESSolve has not converged"); 4740 if (snes->reason < 0) break; 4741 if (grid < snes->gridsequence) { 4742 DM fine; 4743 Vec xnew; 4744 Mat interp; 4745 4746 PetscCall(DMRefine(snes->dm,PetscObjectComm((PetscObject)snes),&fine)); 4747 PetscCheck(fine,PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_INCOMP,"DMRefine() did not perform any refinement, cannot continue grid sequencing"); 4748 PetscCall(DMCreateInterpolation(snes->dm,fine,&interp,NULL)); 4749 PetscCall(DMCreateGlobalVector(fine,&xnew)); 4750 PetscCall(MatInterpolate(interp,x,xnew)); 4751 PetscCall(DMInterpolate(snes->dm,interp,fine)); 4752 PetscCall(MatDestroy(&interp)); 4753 x = xnew; 4754 4755 PetscCall(SNESReset(snes)); 4756 PetscCall(SNESSetDM(snes,fine)); 4757 PetscCall(SNESResetFromOptions(snes)); 4758 PetscCall(DMDestroy(&fine)); 4759 PetscCall(PetscViewerASCIIPopTab(PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)snes)))); 4760 } 4761 } 4762 PetscCall(SNESViewFromOptions(snes,NULL,"-snes_view")); 4763 PetscCall(VecViewFromOptions(snes->vec_sol,(PetscObject)snes,"-snes_view_solution")); 4764 PetscCall(DMMonitor(snes->dm)); 4765 PetscCall(SNESMonitorPauseFinal_Internal(snes)); 4766 4767 PetscCall(VecDestroy(&xcreated)); 4768 PetscCall(PetscObjectSAWsBlock((PetscObject)snes)); 4769 PetscFunctionReturn(0); 4770 } 4771 4772 /* --------- Internal routines for SNES Package --------- */ 4773 4774 /*@C 4775 SNESSetType - Sets the method for the nonlinear solver. 4776 4777 Collective on SNES 4778 4779 Input Parameters: 4780 + snes - the SNES context 4781 - type - a known method 4782 4783 Options Database Key: 4784 . -snes_type <type> - Sets the method; use -help for a list 4785 of available methods (for instance, newtonls or newtontr) 4786 4787 Notes: 4788 See "petsc/include/petscsnes.h" for available methods (for instance) 4789 + SNESNEWTONLS - Newton's method with line search 4790 (systems of nonlinear equations) 4791 - SNESNEWTONTR - Newton's method with trust region 4792 (systems of nonlinear equations) 4793 4794 Normally, it is best to use the SNESSetFromOptions() command and then 4795 set the SNES solver type from the options database rather than by using 4796 this routine. Using the options database provides the user with 4797 maximum flexibility in evaluating the many nonlinear solvers. 4798 The SNESSetType() routine is provided for those situations where it 4799 is necessary to set the nonlinear solver independently of the command 4800 line or options database. This might be the case, for example, when 4801 the choice of solver changes during the execution of the program, 4802 and the user's application is taking responsibility for choosing the 4803 appropriate method. 4804 4805 Developer Notes: 4806 SNESRegister() adds a constructor for a new SNESType to SNESList, SNESSetType() locates 4807 the constructor in that list and calls it to create the spexific object. 4808 4809 Level: intermediate 4810 4811 .seealso: `SNESType`, `SNESCreate()`, `SNESDestroy()`, `SNESGetType()`, `SNESSetFromOptions()` 4812 4813 @*/ 4814 PetscErrorCode SNESSetType(SNES snes,SNESType type) 4815 { 4816 PetscBool match; 4817 PetscErrorCode (*r)(SNES); 4818 4819 PetscFunctionBegin; 4820 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 4821 PetscValidCharPointer(type,2); 4822 4823 PetscCall(PetscObjectTypeCompare((PetscObject)snes,type,&match)); 4824 if (match) PetscFunctionReturn(0); 4825 4826 PetscCall(PetscFunctionListFind(SNESList,type,&r)); 4827 PetscCheck(r,PETSC_COMM_SELF,PETSC_ERR_ARG_UNKNOWN_TYPE,"Unable to find requested SNES type %s",type); 4828 /* Destroy the previous private SNES context */ 4829 PetscTryTypeMethod(snes,destroy); 4830 /* Reinitialize function pointers in SNESOps structure */ 4831 snes->ops->setup = NULL; 4832 snes->ops->solve = NULL; 4833 snes->ops->view = NULL; 4834 snes->ops->setfromoptions = NULL; 4835 snes->ops->destroy = NULL; 4836 4837 /* It may happen the user has customized the line search before calling SNESSetType */ 4838 if (((PetscObject)snes)->type_name) PetscCall(SNESLineSearchDestroy(&snes->linesearch)); 4839 4840 /* Call the SNESCreate_XXX routine for this particular Nonlinear solver */ 4841 snes->setupcalled = PETSC_FALSE; 4842 4843 PetscCall(PetscObjectChangeTypeName((PetscObject)snes,type)); 4844 PetscCall((*r)(snes)); 4845 PetscFunctionReturn(0); 4846 } 4847 4848 /*@C 4849 SNESGetType - Gets the SNES method type and name (as a string). 4850 4851 Not Collective 4852 4853 Input Parameter: 4854 . snes - nonlinear solver context 4855 4856 Output Parameter: 4857 . type - SNES method (a character string) 4858 4859 Level: intermediate 4860 4861 @*/ 4862 PetscErrorCode SNESGetType(SNES snes,SNESType *type) 4863 { 4864 PetscFunctionBegin; 4865 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 4866 PetscValidPointer(type,2); 4867 *type = ((PetscObject)snes)->type_name; 4868 PetscFunctionReturn(0); 4869 } 4870 4871 /*@ 4872 SNESSetSolution - Sets the solution vector for use by the SNES routines. 4873 4874 Logically Collective on SNES 4875 4876 Input Parameters: 4877 + snes - the SNES context obtained from SNESCreate() 4878 - u - the solution vector 4879 4880 Level: beginner 4881 4882 @*/ 4883 PetscErrorCode SNESSetSolution(SNES snes, Vec u) 4884 { 4885 DM dm; 4886 4887 PetscFunctionBegin; 4888 PetscValidHeaderSpecific(snes, SNES_CLASSID, 1); 4889 PetscValidHeaderSpecific(u, VEC_CLASSID, 2); 4890 PetscCall(PetscObjectReference((PetscObject) u)); 4891 PetscCall(VecDestroy(&snes->vec_sol)); 4892 4893 snes->vec_sol = u; 4894 4895 PetscCall(SNESGetDM(snes, &dm)); 4896 PetscCall(DMShellSetGlobalVector(dm, u)); 4897 PetscFunctionReturn(0); 4898 } 4899 4900 /*@ 4901 SNESGetSolution - Returns the vector where the approximate solution is 4902 stored. This is the fine grid solution when using SNESSetGridSequence(). 4903 4904 Not Collective, but Vec is parallel if SNES is parallel 4905 4906 Input Parameter: 4907 . snes - the SNES context 4908 4909 Output Parameter: 4910 . x - the solution 4911 4912 Level: intermediate 4913 4914 .seealso: `SNESGetSolutionUpdate()`, `SNESGetFunction()` 4915 @*/ 4916 PetscErrorCode SNESGetSolution(SNES snes,Vec *x) 4917 { 4918 PetscFunctionBegin; 4919 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 4920 PetscValidPointer(x,2); 4921 *x = snes->vec_sol; 4922 PetscFunctionReturn(0); 4923 } 4924 4925 /*@ 4926 SNESGetSolutionUpdate - Returns the vector where the solution update is 4927 stored. 4928 4929 Not Collective, but Vec is parallel if SNES is parallel 4930 4931 Input Parameter: 4932 . snes - the SNES context 4933 4934 Output Parameter: 4935 . x - the solution update 4936 4937 Level: advanced 4938 4939 .seealso: `SNESGetSolution()`, `SNESGetFunction()` 4940 @*/ 4941 PetscErrorCode SNESGetSolutionUpdate(SNES snes,Vec *x) 4942 { 4943 PetscFunctionBegin; 4944 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 4945 PetscValidPointer(x,2); 4946 *x = snes->vec_sol_update; 4947 PetscFunctionReturn(0); 4948 } 4949 4950 /*@C 4951 SNESGetFunction - Returns the vector where the function is stored. 4952 4953 Not Collective, but Vec is parallel if SNES is parallel. Collective if Vec is requested, but has not been created yet. 4954 4955 Input Parameter: 4956 . snes - the SNES context 4957 4958 Output Parameters: 4959 + r - the vector that is used to store residuals (or NULL if you don't want it) 4960 . f - the function (or NULL if you don't want it); see SNESFunction for calling sequence details 4961 - ctx - the function context (or NULL if you don't want it) 4962 4963 Level: advanced 4964 4965 Notes: The vector r DOES NOT, in general contain the current value of the SNES nonlinear function 4966 4967 .seealso: `SNESSetFunction()`, `SNESGetSolution()`, `SNESFunction` 4968 @*/ 4969 PetscErrorCode SNESGetFunction(SNES snes,Vec *r,PetscErrorCode (**f)(SNES,Vec,Vec,void*),void **ctx) 4970 { 4971 DM dm; 4972 4973 PetscFunctionBegin; 4974 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 4975 if (r) { 4976 if (!snes->vec_func) { 4977 if (snes->vec_rhs) { 4978 PetscCall(VecDuplicate(snes->vec_rhs,&snes->vec_func)); 4979 } else if (snes->vec_sol) { 4980 PetscCall(VecDuplicate(snes->vec_sol,&snes->vec_func)); 4981 } else if (snes->dm) { 4982 PetscCall(DMCreateGlobalVector(snes->dm,&snes->vec_func)); 4983 } 4984 } 4985 *r = snes->vec_func; 4986 } 4987 PetscCall(SNESGetDM(snes,&dm)); 4988 PetscCall(DMSNESGetFunction(dm,f,ctx)); 4989 PetscFunctionReturn(0); 4990 } 4991 4992 /*@C 4993 SNESGetNGS - Returns the NGS function and context. 4994 4995 Input Parameter: 4996 . snes - the SNES context 4997 4998 Output Parameters: 4999 + f - the function (or NULL) see SNESNGSFunction for details 5000 - ctx - the function context (or NULL) 5001 5002 Level: advanced 5003 5004 .seealso: `SNESSetNGS()`, `SNESGetFunction()` 5005 @*/ 5006 5007 PetscErrorCode SNESGetNGS (SNES snes, PetscErrorCode (**f)(SNES, Vec, Vec, void*), void ** ctx) 5008 { 5009 DM dm; 5010 5011 PetscFunctionBegin; 5012 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 5013 PetscCall(SNESGetDM(snes,&dm)); 5014 PetscCall(DMSNESGetNGS(dm,f,ctx)); 5015 PetscFunctionReturn(0); 5016 } 5017 5018 /*@C 5019 SNESSetOptionsPrefix - Sets the prefix used for searching for all 5020 SNES options in the database. 5021 5022 Logically Collective on SNES 5023 5024 Input Parameters: 5025 + snes - the SNES context 5026 - prefix - the prefix to prepend to all option names 5027 5028 Notes: 5029 A hyphen (-) must NOT be given at the beginning of the prefix name. 5030 The first character of all runtime options is AUTOMATICALLY the hyphen. 5031 5032 Level: advanced 5033 5034 .seealso: `SNESSetFromOptions()` 5035 @*/ 5036 PetscErrorCode SNESSetOptionsPrefix(SNES snes,const char prefix[]) 5037 { 5038 PetscFunctionBegin; 5039 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 5040 PetscCall(PetscObjectSetOptionsPrefix((PetscObject)snes,prefix)); 5041 if (!snes->ksp) PetscCall(SNESGetKSP(snes,&snes->ksp)); 5042 if (snes->linesearch) { 5043 PetscCall(SNESGetLineSearch(snes,&snes->linesearch)); 5044 PetscCall(PetscObjectSetOptionsPrefix((PetscObject)snes->linesearch,prefix)); 5045 } 5046 PetscCall(KSPSetOptionsPrefix(snes->ksp,prefix)); 5047 PetscFunctionReturn(0); 5048 } 5049 5050 /*@C 5051 SNESAppendOptionsPrefix - Appends to the prefix used for searching for all 5052 SNES options in the database. 5053 5054 Logically Collective on SNES 5055 5056 Input Parameters: 5057 + snes - the SNES context 5058 - prefix - the prefix to prepend to all option names 5059 5060 Notes: 5061 A hyphen (-) must NOT be given at the beginning of the prefix name. 5062 The first character of all runtime options is AUTOMATICALLY the hyphen. 5063 5064 Level: advanced 5065 5066 .seealso: `SNESGetOptionsPrefix()` 5067 @*/ 5068 PetscErrorCode SNESAppendOptionsPrefix(SNES snes,const char prefix[]) 5069 { 5070 PetscFunctionBegin; 5071 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 5072 PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)snes,prefix)); 5073 if (!snes->ksp) PetscCall(SNESGetKSP(snes,&snes->ksp)); 5074 if (snes->linesearch) { 5075 PetscCall(SNESGetLineSearch(snes,&snes->linesearch)); 5076 PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)snes->linesearch,prefix)); 5077 } 5078 PetscCall(KSPAppendOptionsPrefix(snes->ksp,prefix)); 5079 PetscFunctionReturn(0); 5080 } 5081 5082 /*@C 5083 SNESGetOptionsPrefix - Sets the prefix used for searching for all 5084 SNES options in the database. 5085 5086 Not Collective 5087 5088 Input Parameter: 5089 . snes - the SNES context 5090 5091 Output Parameter: 5092 . prefix - pointer to the prefix string used 5093 5094 Notes: 5095 On the fortran side, the user should pass in a string 'prefix' of 5096 sufficient length to hold the prefix. 5097 5098 Level: advanced 5099 5100 .seealso: `SNESAppendOptionsPrefix()` 5101 @*/ 5102 PetscErrorCode SNESGetOptionsPrefix(SNES snes,const char *prefix[]) 5103 { 5104 PetscFunctionBegin; 5105 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 5106 PetscCall(PetscObjectGetOptionsPrefix((PetscObject)snes,prefix)); 5107 PetscFunctionReturn(0); 5108 } 5109 5110 /*@C 5111 SNESRegister - Adds a method to the nonlinear solver package. 5112 5113 Not collective 5114 5115 Input Parameters: 5116 + name_solver - name of a new user-defined solver 5117 - routine_create - routine to create method context 5118 5119 Notes: 5120 SNESRegister() may be called multiple times to add several user-defined solvers. 5121 5122 Sample usage: 5123 .vb 5124 SNESRegister("my_solver",MySolverCreate); 5125 .ve 5126 5127 Then, your solver can be chosen with the procedural interface via 5128 $ SNESSetType(snes,"my_solver") 5129 or at runtime via the option 5130 $ -snes_type my_solver 5131 5132 Level: advanced 5133 5134 Note: If your function is not being put into a shared library then use SNESRegister() instead 5135 5136 .seealso: `SNESRegisterAll()`, `SNESRegisterDestroy()` 5137 5138 Level: advanced 5139 @*/ 5140 PetscErrorCode SNESRegister(const char sname[],PetscErrorCode (*function)(SNES)) 5141 { 5142 PetscFunctionBegin; 5143 PetscCall(SNESInitializePackage()); 5144 PetscCall(PetscFunctionListAdd(&SNESList,sname,function)); 5145 PetscFunctionReturn(0); 5146 } 5147 5148 PetscErrorCode SNESTestLocalMin(SNES snes) 5149 { 5150 PetscInt N,i,j; 5151 Vec u,uh,fh; 5152 PetscScalar value; 5153 PetscReal norm; 5154 5155 PetscFunctionBegin; 5156 PetscCall(SNESGetSolution(snes,&u)); 5157 PetscCall(VecDuplicate(u,&uh)); 5158 PetscCall(VecDuplicate(u,&fh)); 5159 5160 /* currently only works for sequential */ 5161 PetscCall(PetscPrintf(PetscObjectComm((PetscObject)snes),"Testing FormFunction() for local min\n")); 5162 PetscCall(VecGetSize(u,&N)); 5163 for (i=0; i<N; i++) { 5164 PetscCall(VecCopy(u,uh)); 5165 PetscCall(PetscPrintf(PetscObjectComm((PetscObject)snes),"i = %" PetscInt_FMT "\n",i)); 5166 for (j=-10; j<11; j++) { 5167 value = PetscSign(j)*PetscExpReal(PetscAbs(j)-10.0); 5168 PetscCall(VecSetValue(uh,i,value,ADD_VALUES)); 5169 PetscCall(SNESComputeFunction(snes,uh,fh)); 5170 PetscCall(VecNorm(fh,NORM_2,&norm)); 5171 PetscCall(PetscPrintf(PetscObjectComm((PetscObject)snes)," j norm %" PetscInt_FMT " %18.16e\n",j,(double)norm)); 5172 value = -value; 5173 PetscCall(VecSetValue(uh,i,value,ADD_VALUES)); 5174 } 5175 } 5176 PetscCall(VecDestroy(&uh)); 5177 PetscCall(VecDestroy(&fh)); 5178 PetscFunctionReturn(0); 5179 } 5180 5181 /*@ 5182 SNESKSPSetUseEW - Sets SNES use Eisenstat-Walker method for 5183 computing relative tolerance for linear solvers within an inexact 5184 Newton method. 5185 5186 Logically Collective on SNES 5187 5188 Input Parameters: 5189 + snes - SNES context 5190 - flag - PETSC_TRUE or PETSC_FALSE 5191 5192 Options Database: 5193 + -snes_ksp_ew - use Eisenstat-Walker method for determining linear system convergence 5194 . -snes_ksp_ew_version ver - version of Eisenstat-Walker method 5195 . -snes_ksp_ew_rtol0 <rtol0> - Sets rtol0 5196 . -snes_ksp_ew_rtolmax <rtolmax> - Sets rtolmax 5197 . -snes_ksp_ew_gamma <gamma> - Sets gamma 5198 . -snes_ksp_ew_alpha <alpha> - Sets alpha 5199 . -snes_ksp_ew_alpha2 <alpha2> - Sets alpha2 5200 - -snes_ksp_ew_threshold <threshold> - Sets threshold 5201 5202 Notes: 5203 Currently, the default is to use a constant relative tolerance for 5204 the inner linear solvers. Alternatively, one can use the 5205 Eisenstat-Walker method, where the relative convergence tolerance 5206 is reset at each Newton iteration according progress of the nonlinear 5207 solver. 5208 5209 Level: advanced 5210 5211 Reference: 5212 S. C. Eisenstat and H. F. Walker, "Choosing the forcing terms in an 5213 inexact Newton method", SISC 17 (1), pp.16-32, 1996. 5214 5215 .seealso: `SNESKSPGetUseEW()`, `SNESKSPGetParametersEW()`, `SNESKSPSetParametersEW()` 5216 @*/ 5217 PetscErrorCode SNESKSPSetUseEW(SNES snes,PetscBool flag) 5218 { 5219 PetscFunctionBegin; 5220 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 5221 PetscValidLogicalCollectiveBool(snes,flag,2); 5222 snes->ksp_ewconv = flag; 5223 PetscFunctionReturn(0); 5224 } 5225 5226 /*@ 5227 SNESKSPGetUseEW - Gets if SNES is using Eisenstat-Walker method 5228 for computing relative tolerance for linear solvers within an 5229 inexact Newton method. 5230 5231 Not Collective 5232 5233 Input Parameter: 5234 . snes - SNES context 5235 5236 Output Parameter: 5237 . flag - PETSC_TRUE or PETSC_FALSE 5238 5239 Notes: 5240 Currently, the default is to use a constant relative tolerance for 5241 the inner linear solvers. Alternatively, one can use the 5242 Eisenstat-Walker method, where the relative convergence tolerance 5243 is reset at each Newton iteration according progress of the nonlinear 5244 solver. 5245 5246 Level: advanced 5247 5248 Reference: 5249 S. C. Eisenstat and H. F. Walker, "Choosing the forcing terms in an 5250 inexact Newton method", SISC 17 (1), pp.16-32, 1996. 5251 5252 .seealso: `SNESKSPSetUseEW()`, `SNESKSPGetParametersEW()`, `SNESKSPSetParametersEW()` 5253 @*/ 5254 PetscErrorCode SNESKSPGetUseEW(SNES snes, PetscBool *flag) 5255 { 5256 PetscFunctionBegin; 5257 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 5258 PetscValidBoolPointer(flag,2); 5259 *flag = snes->ksp_ewconv; 5260 PetscFunctionReturn(0); 5261 } 5262 5263 /*@ 5264 SNESKSPSetParametersEW - Sets parameters for Eisenstat-Walker 5265 convergence criteria for the linear solvers within an inexact 5266 Newton method. 5267 5268 Logically Collective on SNES 5269 5270 Input Parameters: 5271 + snes - SNES context 5272 . version - version 1, 2 (default is 2), 3 or 4 5273 . rtol_0 - initial relative tolerance (0 <= rtol_0 < 1) 5274 . rtol_max - maximum relative tolerance (0 <= rtol_max < 1) 5275 . gamma - multiplicative factor for version 2 rtol computation 5276 (0 <= gamma2 <= 1) 5277 . alpha - power for version 2 rtol computation (1 < alpha <= 2) 5278 . alpha2 - power for safeguard 5279 - threshold - threshold for imposing safeguard (0 < threshold < 1) 5280 5281 Note: 5282 Version 3 was contributed by Luis Chacon, June 2006. 5283 5284 Use PETSC_DEFAULT to retain the default for any of the parameters. 5285 5286 Level: advanced 5287 5288 Reference: 5289 S. C. Eisenstat and H. F. Walker, "Choosing the forcing terms in an 5290 inexact Newton method", Utah State University Math. Stat. Dept. Res. 5291 Report 6/94/75, June, 1994, to appear in SIAM J. Sci. Comput. 5292 5293 .seealso: `SNESKSPSetUseEW()`, `SNESKSPGetUseEW()`, `SNESKSPGetParametersEW()` 5294 @*/ 5295 PetscErrorCode SNESKSPSetParametersEW(SNES snes,PetscInt version,PetscReal rtol_0,PetscReal rtol_max,PetscReal gamma,PetscReal alpha,PetscReal alpha2,PetscReal threshold) 5296 { 5297 SNESKSPEW *kctx; 5298 5299 PetscFunctionBegin; 5300 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 5301 kctx = (SNESKSPEW*)snes->kspconvctx; 5302 PetscCheck(kctx,PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"No Eisenstat-Walker context existing"); 5303 PetscValidLogicalCollectiveInt(snes,version,2); 5304 PetscValidLogicalCollectiveReal(snes,rtol_0,3); 5305 PetscValidLogicalCollectiveReal(snes,rtol_max,4); 5306 PetscValidLogicalCollectiveReal(snes,gamma,5); 5307 PetscValidLogicalCollectiveReal(snes,alpha,6); 5308 PetscValidLogicalCollectiveReal(snes,alpha2,7); 5309 PetscValidLogicalCollectiveReal(snes,threshold,8); 5310 5311 if (version != PETSC_DEFAULT) kctx->version = version; 5312 if (rtol_0 != PETSC_DEFAULT) kctx->rtol_0 = rtol_0; 5313 if (rtol_max != PETSC_DEFAULT) kctx->rtol_max = rtol_max; 5314 if (gamma != PETSC_DEFAULT) kctx->gamma = gamma; 5315 if (alpha != PETSC_DEFAULT) kctx->alpha = alpha; 5316 if (alpha2 != PETSC_DEFAULT) kctx->alpha2 = alpha2; 5317 if (threshold != PETSC_DEFAULT) kctx->threshold = threshold; 5318 5319 PetscCheck(kctx->version >= 1 && kctx->version <= 4,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Only versions 1 to 4 are supported: %" PetscInt_FMT,kctx->version); 5320 PetscCheck(kctx->rtol_0 >= 0.0 && kctx->rtol_0 < 1.0,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"0.0 <= rtol_0 < 1.0: %g",(double)kctx->rtol_0); 5321 PetscCheck(kctx->rtol_max >= 0.0 && kctx->rtol_max < 1.0,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"0.0 <= rtol_max (%g) < 1.0",(double)kctx->rtol_max); 5322 PetscCheck(kctx->gamma >= 0.0 && kctx->gamma <= 1.0,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"0.0 <= gamma (%g) <= 1.0",(double)kctx->gamma); 5323 PetscCheck(kctx->alpha > 1.0 && kctx->alpha <= 2.0,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"1.0 < alpha (%g) <= 2.0",(double)kctx->alpha); 5324 PetscCheck(kctx->threshold > 0.0 && kctx->threshold < 1.0,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"0.0 < threshold (%g) < 1.0",(double)kctx->threshold); 5325 PetscFunctionReturn(0); 5326 } 5327 5328 /*@ 5329 SNESKSPGetParametersEW - Gets parameters for Eisenstat-Walker 5330 convergence criteria for the linear solvers within an inexact 5331 Newton method. 5332 5333 Not Collective 5334 5335 Input Parameter: 5336 . snes - SNES context 5337 5338 Output Parameters: 5339 + version - version 1, 2 (default is 2), 3 or 4 5340 . rtol_0 - initial relative tolerance (0 <= rtol_0 < 1) 5341 . rtol_max - maximum relative tolerance (0 <= rtol_max < 1) 5342 . gamma - multiplicative factor for version 2 rtol computation (0 <= gamma2 <= 1) 5343 . alpha - power for version 2 rtol computation (1 < alpha <= 2) 5344 . alpha2 - power for safeguard 5345 - threshold - threshold for imposing safeguard (0 < threshold < 1) 5346 5347 Level: advanced 5348 5349 .seealso: `SNESKSPSetUseEW()`, `SNESKSPGetUseEW()`, `SNESKSPSetParametersEW()` 5350 @*/ 5351 PetscErrorCode SNESKSPGetParametersEW(SNES snes,PetscInt *version,PetscReal *rtol_0,PetscReal *rtol_max,PetscReal *gamma,PetscReal *alpha,PetscReal *alpha2,PetscReal *threshold) 5352 { 5353 SNESKSPEW *kctx; 5354 5355 PetscFunctionBegin; 5356 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 5357 kctx = (SNESKSPEW*)snes->kspconvctx; 5358 PetscCheck(kctx,PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"No Eisenstat-Walker context existing"); 5359 if (version) *version = kctx->version; 5360 if (rtol_0) *rtol_0 = kctx->rtol_0; 5361 if (rtol_max) *rtol_max = kctx->rtol_max; 5362 if (gamma) *gamma = kctx->gamma; 5363 if (alpha) *alpha = kctx->alpha; 5364 if (alpha2) *alpha2 = kctx->alpha2; 5365 if (threshold) *threshold = kctx->threshold; 5366 PetscFunctionReturn(0); 5367 } 5368 5369 PetscErrorCode KSPPreSolve_SNESEW(KSP ksp, Vec b, Vec x, SNES snes) 5370 { 5371 SNESKSPEW *kctx = (SNESKSPEW*)snes->kspconvctx; 5372 PetscReal rtol = PETSC_DEFAULT,stol; 5373 5374 PetscFunctionBegin; 5375 if (!snes->ksp_ewconv) PetscFunctionReturn(0); 5376 if (!snes->iter) { 5377 rtol = kctx->rtol_0; /* first time in, so use the original user rtol */ 5378 PetscCall(VecNorm(snes->vec_func,NORM_2,&kctx->norm_first)); 5379 } else { 5380 if (kctx->version == 1) { 5381 rtol = PetscAbsReal(snes->norm - kctx->lresid_last)/kctx->norm_last; 5382 stol = PetscPowReal(kctx->rtol_last,kctx->alpha2); 5383 if (stol > kctx->threshold) rtol = PetscMax(rtol,stol); 5384 } else if (kctx->version == 2) { 5385 rtol = kctx->gamma * PetscPowReal(snes->norm/kctx->norm_last,kctx->alpha); 5386 stol = kctx->gamma * PetscPowReal(kctx->rtol_last,kctx->alpha); 5387 if (stol > kctx->threshold) rtol = PetscMax(rtol,stol); 5388 } else if (kctx->version == 3) { /* contributed by Luis Chacon, June 2006. */ 5389 rtol = kctx->gamma * PetscPowReal(snes->norm/kctx->norm_last,kctx->alpha); 5390 /* safeguard: avoid sharp decrease of rtol */ 5391 stol = kctx->gamma*PetscPowReal(kctx->rtol_last,kctx->alpha); 5392 stol = PetscMax(rtol,stol); 5393 rtol = PetscMin(kctx->rtol_0,stol); 5394 /* safeguard: avoid oversolving */ 5395 stol = kctx->gamma*(kctx->norm_first*snes->rtol)/snes->norm; 5396 stol = PetscMax(rtol,stol); 5397 rtol = PetscMin(kctx->rtol_0,stol); 5398 } else if (kctx->version == 4) { /* H.-B. An et al. Journal of Computational and Applied Mathematics 200 (2007) 47-60 */ 5399 PetscReal ared = PetscAbsReal(kctx->norm_last - snes->norm); 5400 PetscReal pred = PetscAbsReal(kctx->norm_last - kctx->lresid_last); 5401 PetscReal rk = ared / pred; 5402 if (rk < kctx->v4_p1) rtol = 1. - 2.*kctx->v4_p1; 5403 else if (rk < kctx->v4_p2) rtol = kctx->rtol_last; 5404 else if (rk < kctx->v4_p3) rtol = kctx->v4_m1 * kctx->rtol_last; 5405 else rtol = kctx->v4_m2 * kctx->rtol_last; 5406 5407 if (kctx->rtol_last_2 > kctx->v4_m3 && kctx->rtol_last > kctx->v4_m3 && 5408 kctx->rk_last_2 < kctx->v4_p1 && kctx->rk_last < kctx->v4_p1) { 5409 rtol = kctx->v4_m4 * kctx->rtol_last; 5410 //printf("iter %" PetscInt_FMT ", Eisenstat-Walker (version %" PetscInt_FMT ") KSP rtol=%g (rk %g ps %g %g %g) (AD)\n",snes->iter,kctx->version,(double)rtol,rk,kctx->v4_p1,kctx->v4_p2,kctx->v4_p3); 5411 } else { 5412 //printf("iter %" PetscInt_FMT ", Eisenstat-Walker (version %" PetscInt_FMT ") KSP rtol=%g (rk %g ps %g %g %g)\n",snes->iter,kctx->version,(double)rtol,rk,kctx->v4_p1,kctx->v4_p2,kctx->v4_p3); 5413 } 5414 kctx->rtol_last_2 = kctx->rtol_last; 5415 kctx->rk_last_2 = kctx->rk_last; 5416 kctx->rk_last = rk; 5417 } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Only versions 1-4 are supported: %" PetscInt_FMT,kctx->version); 5418 } 5419 /* safeguard: avoid rtol greater than rtol_max */ 5420 rtol = PetscMin(rtol,kctx->rtol_max); 5421 PetscCall(KSPSetTolerances(ksp,rtol,PETSC_DEFAULT,PETSC_DEFAULT,PETSC_DEFAULT)); 5422 PetscCall(PetscInfo(snes,"iter %" PetscInt_FMT ", Eisenstat-Walker (version %" PetscInt_FMT ") KSP rtol=%g\n",snes->iter,kctx->version,(double)rtol)); 5423 PetscFunctionReturn(0); 5424 } 5425 5426 PetscErrorCode KSPPostSolve_SNESEW(KSP ksp, Vec b, Vec x, SNES snes) 5427 { 5428 SNESKSPEW *kctx = (SNESKSPEW*)snes->kspconvctx; 5429 PCSide pcside; 5430 Vec lres; 5431 5432 PetscFunctionBegin; 5433 if (!snes->ksp_ewconv) PetscFunctionReturn(0); 5434 PetscCall(KSPGetTolerances(ksp,&kctx->rtol_last,NULL,NULL,NULL)); 5435 kctx->norm_last = snes->norm; 5436 if (kctx->version == 1 || kctx->version == 4) { 5437 PC pc; 5438 PetscBool getRes; 5439 5440 PetscCall(KSPGetPC(ksp,&pc)); 5441 PetscCall(PetscObjectTypeCompare((PetscObject)pc,PCNONE,&getRes)); 5442 if (!getRes) { 5443 KSPNormType normtype; 5444 5445 PetscCall(KSPGetNormType(ksp,&normtype)); 5446 getRes = (PetscBool)(normtype == KSP_NORM_UNPRECONDITIONED); 5447 } 5448 PetscCall(KSPGetPCSide(ksp,&pcside)); 5449 if (pcside == PC_RIGHT || getRes) { /* KSP residual is true linear residual */ 5450 PetscCall(KSPGetResidualNorm(ksp,&kctx->lresid_last)); 5451 } else { 5452 /* KSP residual is preconditioned residual */ 5453 /* compute true linear residual norm */ 5454 Mat J; 5455 PetscCall(KSPGetOperators(ksp,&J,NULL)); 5456 PetscCall(VecDuplicate(b,&lres)); 5457 PetscCall(MatMult(J,x,lres)); 5458 PetscCall(VecAYPX(lres,-1.0,b)); 5459 PetscCall(VecNorm(lres,NORM_2,&kctx->lresid_last)); 5460 PetscCall(VecDestroy(&lres)); 5461 } 5462 } 5463 PetscFunctionReturn(0); 5464 } 5465 5466 /*@ 5467 SNESGetKSP - Returns the KSP context for a SNES solver. 5468 5469 Not Collective, but if SNES object is parallel, then KSP object is parallel 5470 5471 Input Parameter: 5472 . snes - the SNES context 5473 5474 Output Parameter: 5475 . ksp - the KSP context 5476 5477 Notes: 5478 The user can then directly manipulate the KSP context to set various 5479 options, etc. Likewise, the user can then extract and manipulate the 5480 PC contexts as well. 5481 5482 Level: beginner 5483 5484 .seealso: `KSPGetPC()`, `SNESCreate()`, `KSPCreate()`, `SNESSetKSP()` 5485 @*/ 5486 PetscErrorCode SNESGetKSP(SNES snes,KSP *ksp) 5487 { 5488 PetscFunctionBegin; 5489 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 5490 PetscValidPointer(ksp,2); 5491 5492 if (!snes->ksp) { 5493 PetscCall(KSPCreate(PetscObjectComm((PetscObject)snes),&snes->ksp)); 5494 PetscCall(PetscObjectIncrementTabLevel((PetscObject)snes->ksp,(PetscObject)snes,1)); 5495 PetscCall(PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->ksp)); 5496 5497 PetscCall(KSPSetPreSolve(snes->ksp,(PetscErrorCode (*)(KSP,Vec,Vec,void*))KSPPreSolve_SNESEW,snes)); 5498 PetscCall(KSPSetPostSolve(snes->ksp,(PetscErrorCode (*)(KSP,Vec,Vec,void*))KSPPostSolve_SNESEW,snes)); 5499 5500 PetscCall(KSPMonitorSetFromOptions(snes->ksp, "-snes_monitor_ksp", "snes_preconditioned_residual", snes)); 5501 PetscCall(PetscObjectSetOptions((PetscObject)snes->ksp,((PetscObject)snes)->options)); 5502 } 5503 *ksp = snes->ksp; 5504 PetscFunctionReturn(0); 5505 } 5506 5507 #include <petsc/private/dmimpl.h> 5508 /*@ 5509 SNESSetDM - Sets the DM that may be used by some nonlinear solvers or their underlying preconditioners 5510 5511 Logically Collective on SNES 5512 5513 Input Parameters: 5514 + snes - the nonlinear solver context 5515 - dm - the dm, cannot be NULL 5516 5517 Notes: 5518 A DM can only be used for solving one problem at a time because information about the problem is stored on the DM, 5519 even when not using interfaces like DMSNESSetFunction(). Use DMClone() to get a distinct DM when solving different 5520 problems using the same function space. 5521 5522 Level: intermediate 5523 5524 .seealso: `SNESGetDM()`, `KSPSetDM()`, `KSPGetDM()` 5525 @*/ 5526 PetscErrorCode SNESSetDM(SNES snes,DM dm) 5527 { 5528 KSP ksp; 5529 DMSNES sdm; 5530 5531 PetscFunctionBegin; 5532 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 5533 PetscValidHeaderSpecific(dm,DM_CLASSID,2); 5534 PetscCall(PetscObjectReference((PetscObject)dm)); 5535 if (snes->dm) { /* Move the DMSNES context over to the new DM unless the new DM already has one */ 5536 if (snes->dm->dmsnes && !dm->dmsnes) { 5537 PetscCall(DMCopyDMSNES(snes->dm,dm)); 5538 PetscCall(DMGetDMSNES(snes->dm,&sdm)); 5539 if (sdm->originaldm == snes->dm) sdm->originaldm = dm; /* Grant write privileges to the replacement DM */ 5540 } 5541 PetscCall(DMCoarsenHookRemove(snes->dm,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,snes)); 5542 PetscCall(DMDestroy(&snes->dm)); 5543 } 5544 snes->dm = dm; 5545 snes->dmAuto = PETSC_FALSE; 5546 5547 PetscCall(SNESGetKSP(snes,&ksp)); 5548 PetscCall(KSPSetDM(ksp,dm)); 5549 PetscCall(KSPSetDMActive(ksp,PETSC_FALSE)); 5550 if (snes->npc) { 5551 PetscCall(SNESSetDM(snes->npc,snes->dm)); 5552 PetscCall(SNESSetNPCSide(snes,snes->npcside)); 5553 } 5554 PetscFunctionReturn(0); 5555 } 5556 5557 /*@ 5558 SNESGetDM - Gets the DM that may be used by some preconditioners 5559 5560 Not Collective but DM obtained is parallel on SNES 5561 5562 Input Parameter: 5563 . snes - the preconditioner context 5564 5565 Output Parameter: 5566 . dm - the dm 5567 5568 Level: intermediate 5569 5570 .seealso: `SNESSetDM()`, `KSPSetDM()`, `KSPGetDM()` 5571 @*/ 5572 PetscErrorCode SNESGetDM(SNES snes,DM *dm) 5573 { 5574 PetscFunctionBegin; 5575 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 5576 if (!snes->dm) { 5577 PetscCall(DMShellCreate(PetscObjectComm((PetscObject)snes),&snes->dm)); 5578 snes->dmAuto = PETSC_TRUE; 5579 } 5580 *dm = snes->dm; 5581 PetscFunctionReturn(0); 5582 } 5583 5584 /*@ 5585 SNESSetNPC - Sets the nonlinear preconditioner to be used. 5586 5587 Collective on SNES 5588 5589 Input Parameters: 5590 + snes - iterative context obtained from SNESCreate() 5591 - pc - the preconditioner object 5592 5593 Notes: 5594 Use SNESGetNPC() to retrieve the preconditioner context (for example, 5595 to configure it using the API). 5596 5597 Level: developer 5598 5599 .seealso: `SNESGetNPC()`, `SNESHasNPC()` 5600 @*/ 5601 PetscErrorCode SNESSetNPC(SNES snes, SNES pc) 5602 { 5603 PetscFunctionBegin; 5604 PetscValidHeaderSpecific(snes, SNES_CLASSID, 1); 5605 PetscValidHeaderSpecific(pc, SNES_CLASSID, 2); 5606 PetscCheckSameComm(snes, 1, pc, 2); 5607 PetscCall(PetscObjectReference((PetscObject) pc)); 5608 PetscCall(SNESDestroy(&snes->npc)); 5609 snes->npc = pc; 5610 PetscCall(PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->npc)); 5611 PetscFunctionReturn(0); 5612 } 5613 5614 /*@ 5615 SNESGetNPC - Creates a nonlinear preconditioning solver (SNES) to be used to precondition the nonlinear solver. 5616 5617 Not Collective; but any changes to the obtained SNES object must be applied collectively 5618 5619 Input Parameter: 5620 . snes - iterative context obtained from SNESCreate() 5621 5622 Output Parameter: 5623 . pc - preconditioner context 5624 5625 Options Database: 5626 . -npc_snes_type <type> - set the type of the SNES to use as the nonlinear preconditioner 5627 5628 Notes: 5629 If a SNES was previously set with SNESSetNPC() then that SNES is returned, otherwise a new SNES object is created. 5630 5631 The (preconditioner) SNES returned automatically inherits the same nonlinear function and Jacobian supplied to the original 5632 SNES during SNESSetUp() 5633 5634 Level: developer 5635 5636 .seealso: `SNESSetNPC()`, `SNESHasNPC()`, `SNES`, `SNESCreate()` 5637 @*/ 5638 PetscErrorCode SNESGetNPC(SNES snes, SNES *pc) 5639 { 5640 const char *optionsprefix; 5641 5642 PetscFunctionBegin; 5643 PetscValidHeaderSpecific(snes, SNES_CLASSID, 1); 5644 PetscValidPointer(pc, 2); 5645 if (!snes->npc) { 5646 PetscCall(SNESCreate(PetscObjectComm((PetscObject)snes),&snes->npc)); 5647 PetscCall(PetscObjectIncrementTabLevel((PetscObject)snes->npc,(PetscObject)snes,1)); 5648 PetscCall(PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->npc)); 5649 PetscCall(SNESGetOptionsPrefix(snes,&optionsprefix)); 5650 PetscCall(SNESSetOptionsPrefix(snes->npc,optionsprefix)); 5651 PetscCall(SNESAppendOptionsPrefix(snes->npc,"npc_")); 5652 PetscCall(SNESSetCountersReset(snes->npc,PETSC_FALSE)); 5653 } 5654 *pc = snes->npc; 5655 PetscFunctionReturn(0); 5656 } 5657 5658 /*@ 5659 SNESHasNPC - Returns whether a nonlinear preconditioner exists 5660 5661 Not Collective 5662 5663 Input Parameter: 5664 . snes - iterative context obtained from SNESCreate() 5665 5666 Output Parameter: 5667 . has_npc - whether the SNES has an NPC or not 5668 5669 Level: developer 5670 5671 .seealso: `SNESSetNPC()`, `SNESGetNPC()` 5672 @*/ 5673 PetscErrorCode SNESHasNPC(SNES snes, PetscBool *has_npc) 5674 { 5675 PetscFunctionBegin; 5676 PetscValidHeaderSpecific(snes, SNES_CLASSID, 1); 5677 *has_npc = (PetscBool) (snes->npc ? PETSC_TRUE : PETSC_FALSE); 5678 PetscFunctionReturn(0); 5679 } 5680 5681 /*@ 5682 SNESSetNPCSide - Sets the preconditioning side. 5683 5684 Logically Collective on SNES 5685 5686 Input Parameter: 5687 . snes - iterative context obtained from SNESCreate() 5688 5689 Output Parameter: 5690 . side - the preconditioning side, where side is one of 5691 .vb 5692 PC_LEFT - left preconditioning 5693 PC_RIGHT - right preconditioning (default for most nonlinear solvers) 5694 .ve 5695 5696 Options Database Keys: 5697 . -snes_npc_side <right,left> - nonlinear preconditioner side 5698 5699 Notes: 5700 SNESNRICHARDSON and SNESNCG only support left preconditioning. 5701 5702 Level: intermediate 5703 5704 .seealso: `SNESGetNPCSide()`, `KSPSetPCSide()` 5705 @*/ 5706 PetscErrorCode SNESSetNPCSide(SNES snes,PCSide side) 5707 { 5708 PetscFunctionBegin; 5709 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 5710 PetscValidLogicalCollectiveEnum(snes,side,2); 5711 if (side == PC_SIDE_DEFAULT) side = PC_RIGHT; 5712 PetscCheck((side == PC_LEFT) || (side == PC_RIGHT),PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_WRONG,"Only PC_LEFT and PC_RIGHT are supported"); 5713 snes->npcside = side; 5714 PetscFunctionReturn(0); 5715 } 5716 5717 /*@ 5718 SNESGetNPCSide - Gets the preconditioning side. 5719 5720 Not Collective 5721 5722 Input Parameter: 5723 . snes - iterative context obtained from SNESCreate() 5724 5725 Output Parameter: 5726 . side - the preconditioning side, where side is one of 5727 .vb 5728 PC_LEFT - left preconditioning 5729 PC_RIGHT - right preconditioning (default for most nonlinear solvers) 5730 .ve 5731 5732 Level: intermediate 5733 5734 .seealso: `SNESSetNPCSide()`, `KSPGetPCSide()` 5735 @*/ 5736 PetscErrorCode SNESGetNPCSide(SNES snes,PCSide *side) 5737 { 5738 PetscFunctionBegin; 5739 PetscValidHeaderSpecific(snes,SNES_CLASSID,1); 5740 PetscValidPointer(side,2); 5741 *side = snes->npcside; 5742 PetscFunctionReturn(0); 5743 } 5744 5745 /*@ 5746 SNESSetLineSearch - Sets the linesearch on the SNES instance. 5747 5748 Collective on SNES 5749 5750 Input Parameters: 5751 + snes - iterative context obtained from SNESCreate() 5752 - linesearch - the linesearch object 5753 5754 Notes: 5755 Use SNESGetLineSearch() to retrieve the preconditioner context (for example, 5756 to configure it using the API). 5757 5758 Level: developer 5759 5760 .seealso: `SNESGetLineSearch()` 5761 @*/ 5762 PetscErrorCode SNESSetLineSearch(SNES snes, SNESLineSearch linesearch) 5763 { 5764 PetscFunctionBegin; 5765 PetscValidHeaderSpecific(snes, SNES_CLASSID, 1); 5766 PetscValidHeaderSpecific(linesearch, SNESLINESEARCH_CLASSID, 2); 5767 PetscCheckSameComm(snes, 1, linesearch, 2); 5768 PetscCall(PetscObjectReference((PetscObject) linesearch)); 5769 PetscCall(SNESLineSearchDestroy(&snes->linesearch)); 5770 5771 snes->linesearch = linesearch; 5772 5773 PetscCall(PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->linesearch)); 5774 PetscFunctionReturn(0); 5775 } 5776 5777 /*@ 5778 SNESGetLineSearch - Returns a pointer to the line search context set with SNESSetLineSearch() 5779 or creates a default line search instance associated with the SNES and returns it. 5780 5781 Not Collective 5782 5783 Input Parameter: 5784 . snes - iterative context obtained from SNESCreate() 5785 5786 Output Parameter: 5787 . linesearch - linesearch context 5788 5789 Level: beginner 5790 5791 .seealso: `SNESSetLineSearch()`, `SNESLineSearchCreate()` 5792 @*/ 5793 PetscErrorCode SNESGetLineSearch(SNES snes, SNESLineSearch *linesearch) 5794 { 5795 const char *optionsprefix; 5796 5797 PetscFunctionBegin; 5798 PetscValidHeaderSpecific(snes, SNES_CLASSID, 1); 5799 PetscValidPointer(linesearch, 2); 5800 if (!snes->linesearch) { 5801 PetscCall(SNESGetOptionsPrefix(snes, &optionsprefix)); 5802 PetscCall(SNESLineSearchCreate(PetscObjectComm((PetscObject)snes), &snes->linesearch)); 5803 PetscCall(SNESLineSearchSetSNES(snes->linesearch, snes)); 5804 PetscCall(SNESLineSearchAppendOptionsPrefix(snes->linesearch, optionsprefix)); 5805 PetscCall(PetscObjectIncrementTabLevel((PetscObject) snes->linesearch, (PetscObject) snes, 1)); 5806 PetscCall(PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->linesearch)); 5807 } 5808 *linesearch = snes->linesearch; 5809 PetscFunctionReturn(0); 5810 } 5811