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