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