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