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