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