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