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