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