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