Actual source code: mffd.c
1: #define PETSCMAT_DLL
3: #include private/matimpl.h
4: #include ../src/mat/impls/mffd/mffdimpl.h
6: PetscFList MatMFFDList = 0;
7: PetscTruth MatMFFDRegisterAllCalled = PETSC_FALSE;
9: PetscCookie MATMFFD_COOKIE;
10: PetscLogEvent MATMFFD_Mult;
12: static PetscTruth MatMFFDPackageInitialized = PETSC_FALSE;
15: /*@C
16: MatMFFDFinalizePackage - This function destroys everything in the MatMFFD package. It is
17: called from PetscFinalize().
19: Level: developer
21: .keywords: Petsc, destroy, package
22: .seealso: PetscFinalize()
23: @*/
24: PetscErrorCode MatMFFDFinalizePackage(void)
25: {
27: MatMFFDPackageInitialized = PETSC_FALSE;
28: MatMFFDRegisterAllCalled = PETSC_FALSE;
29: MatMFFDList = PETSC_NULL;
30: return(0);
31: }
35: /*@C
36: MatMFFDInitializePackage - This function initializes everything in the MatMFFD package. It is called
37: from PetscDLLibraryRegister() when using dynamic libraries, and on the first call to MatCreate_MFFD()
38: when using static libraries.
40: Input Parameter:
41: . path - The dynamic library path, or PETSC_NULL
43: Level: developer
45: .keywords: Vec, initialize, package
46: .seealso: PetscInitialize()
47: @*/
48: PetscErrorCode MatMFFDInitializePackage(const char path[])
49: {
50: char logList[256];
51: char *className;
52: PetscTruth opt;
53: PetscErrorCode ierr;
56: if (MatMFFDPackageInitialized) return(0);
57: MatMFFDPackageInitialized = PETSC_TRUE;
58: /* Register Classes */
59: PetscCookieRegister("MatMFFD",&MATMFFD_COOKIE);
60: /* Register Constructors */
61: MatMFFDRegisterAll(path);
62: /* Register Events */
63: PetscLogEventRegister("MatMult MF", MATMFFD_COOKIE,&MATMFFD_Mult);
65: /* Process info exclusions */
66: PetscOptionsGetString(PETSC_NULL, "-info_exclude", logList, 256, &opt);
67: if (opt) {
68: PetscStrstr(logList, "matmffd", &className);
69: if (className) {
70: PetscInfoDeactivateClass(MATMFFD_COOKIE);
71: }
72: }
73: /* Process summary exclusions */
74: PetscOptionsGetString(PETSC_NULL, "-log_summary_exclude", logList, 256, &opt);
75: if (opt) {
76: PetscStrstr(logList, "matmffd", &className);
77: if (className) {
78: PetscLogEventDeactivateClass(MATMFFD_COOKIE);
79: }
80: }
81: PetscRegisterFinalize(MatMFFDFinalizePackage);
82: return(0);
83: }
87: /*@C
88: MatMFFDSetType - Sets the method that is used to compute the
89: differencing parameter for finite differene matrix-free formulations.
91: Input Parameters:
92: + mat - the "matrix-free" matrix created via MatCreateSNESMF(), or MatCreateMFFD()
93: or MatSetType(mat,MATMFFD);
94: - ftype - the type requested, either MATMFFD_WP or MATMFFD_DS
96: Level: advanced
98: Notes:
99: For example, such routines can compute h for use in
100: Jacobian-vector products of the form
102: F(x+ha) - F(x)
103: F'(u)a ~= ----------------
104: h
106: .seealso: MatCreateSNESMF(), MatMFFDRegisterDynamic(), MatMFFDSetFunction()
107: @*/
108: PetscErrorCode MatMFFDSetType(Mat mat,const MatMFFDType ftype)
109: {
110: PetscErrorCode ierr,(*r)(MatMFFD);
111: MatMFFD ctx = (MatMFFD)mat->data;
112: PetscTruth match;
113:
118: /* already set, so just return */
119: PetscTypeCompare((PetscObject)ctx,ftype,&match);
120: if (match) return(0);
122: /* destroy the old one if it exists */
123: if (ctx->ops->destroy) {
124: (*ctx->ops->destroy)(ctx);
125: }
127: PetscFListFind(MatMFFDList,((PetscObject)ctx)->comm,ftype,(void (**)(void)) &r);
128: if (!r) SETERRQ1(PETSC_ERR_ARG_UNKNOWN_TYPE,"Unknown MatMFFD type %s given",ftype);
129: (*r)(ctx);
130: PetscObjectChangeTypeName((PetscObject)ctx,ftype);
131: return(0);
132: }
138: PetscErrorCode MatMFFDSetFunctioniBase_MFFD(Mat mat,FCN1 func)
139: {
140: MatMFFD ctx = (MatMFFD)mat->data;
143: ctx->funcisetbase = func;
144: return(0);
145: }
152: PetscErrorCode MatMFFDSetFunctioni_MFFD(Mat mat,FCN2 funci)
153: {
154: MatMFFD ctx = (MatMFFD)mat->data;
157: ctx->funci = funci;
158: return(0);
159: }
165: PetscErrorCode MatMFFDRegister(const char sname[],const char path[],const char name[],PetscErrorCode (*function)(MatMFFD))
166: {
168: char fullname[PETSC_MAX_PATH_LEN];
171: PetscFListConcat(path,name,fullname);
172: PetscFListAdd(&MatMFFDList,sname,fullname,(void (*)(void))function);
173: return(0);
174: }
179: /*@C
180: MatMFFDRegisterDestroy - Frees the list of MatMFFD methods that were
181: registered by MatMFFDRegisterDynamic).
183: Not Collective
185: Level: developer
187: .keywords: MatMFFD, register, destroy
189: .seealso: MatMFFDRegisterDynamic), MatMFFDRegisterAll()
190: @*/
191: PetscErrorCode MatMFFDRegisterDestroy(void)
192: {
196: PetscFListDestroy(&MatMFFDList);
197: MatMFFDRegisterAllCalled = PETSC_FALSE;
198: return(0);
199: }
201: /* ----------------------------------------------------------------------------------------*/
204: PetscErrorCode MatDestroy_MFFD(Mat mat)
205: {
207: MatMFFD ctx = (MatMFFD)mat->data;
210: if (ctx->w) {
211: VecDestroy(ctx->w);
212: }
213: if (ctx->current_f_allocated) {
214: VecDestroy(ctx->current_f);
215: }
216: if (ctx->ops->destroy) {(*ctx->ops->destroy)(ctx);}
217: if (ctx->sp) {MatNullSpaceDestroy(ctx->sp);}
218: PetscHeaderDestroy(ctx);
220: PetscObjectComposeFunction((PetscObject)mat,"MatMFFDSetBase_C","",PETSC_NULL);
221: PetscObjectComposeFunction((PetscObject)mat,"MatMFFDSetFunctioniBase_C","",PETSC_NULL);
222: PetscObjectComposeFunction((PetscObject)mat,"MatMFFDSetFunctioni_C","",PETSC_NULL);
223: PetscObjectComposeFunction((PetscObject)mat,"MatMFFDSetCheckh_C","",PETSC_NULL);
225: return(0);
226: }
230: /*
231: MatMFFDView_MFFD - Views matrix-free parameters.
233: */
234: PetscErrorCode MatView_MFFD(Mat J,PetscViewer viewer)
235: {
237: MatMFFD ctx = (MatMFFD)J->data;
238: PetscTruth iascii;
241: PetscTypeCompare((PetscObject)viewer,PETSC_VIEWER_ASCII,&iascii);
242: if (iascii) {
243: PetscViewerASCIIPrintf(viewer," matrix-free approximation:\n");
244: PetscViewerASCIIPrintf(viewer," err=%G (relative error in function evaluation)\n",ctx->error_rel);
245: if (!((PetscObject)ctx)->type_name) {
246: PetscViewerASCIIPrintf(viewer," The compute h routine has not yet been set\n");
247: } else {
248: PetscViewerASCIIPrintf(viewer," Using %s compute h routine\n",((PetscObject)ctx)->type_name);
249: }
250: if (ctx->ops->view) {
251: (*ctx->ops->view)(ctx,viewer);
252: }
253: } else {
254: SETERRQ1(PETSC_ERR_SUP,"Viewer type %s not supported for matrix-free matrix",((PetscObject)viewer)->type_name);
255: }
256: return(0);
257: }
261: /*
262: MatAssemblyEnd_MFFD - Resets the ctx->ncurrenth to zero. This
263: allows the user to indicate the beginning of a new linear solve by calling
264: MatAssemblyXXX() on the matrix free matrix. This then allows the
265: MatCreateMFFD_WP() to properly compute ||U|| only the first time
266: in the linear solver rather than every time.
267: */
268: PetscErrorCode MatAssemblyEnd_MFFD(Mat J,MatAssemblyType mt)
269: {
271: MatMFFD j = (MatMFFD)J->data;
274: MatMFFDResetHHistory(J);
275: j->vshift = 0.0;
276: j->vscale = 1.0;
277: return(0);
278: }
282: /*
283: MatMult_MFFD - Default matrix-free form for Jacobian-vector product, y = F'(u)*a:
285: y ~= (F(u + ha) - F(u))/h,
286: where F = nonlinear function, as set by SNESSetFunction()
287: u = current iterate
288: h = difference interval
289: */
290: PetscErrorCode MatMult_MFFD(Mat mat,Vec a,Vec y)
291: {
292: MatMFFD ctx = (MatMFFD)mat->data;
293: PetscScalar h;
294: Vec w,U,F;
296: PetscTruth zeroa;
299: /* We log matrix-free matrix-vector products separately, so that we can
300: separate the performance monitoring from the cases that use conventional
301: storage. We may eventually modify event logging to associate events
302: with particular objects, hence alleviating the more general problem. */
303: PetscLogEventBegin(MATMFFD_Mult,a,y,0,0);
305: w = ctx->w;
306: U = ctx->current_u;
307: F = ctx->current_f;
308: /*
309: Compute differencing parameter
310: */
311: if (!ctx->ops->compute) {
312: MatMFFDSetType(mat,MATMFFD_WP);
313: MatMFFDSetFromOptions(mat);
314: }
315: (*ctx->ops->compute)(ctx,U,a,&h,&zeroa);
316: if (zeroa) {
317: VecSet(y,0.0);
318: return(0);
319: }
321: if (h != h) SETERRQ(PETSC_ERR_PLIB,"Computed Nan differencing parameter h");
322: if (ctx->checkh) {
323: (*ctx->checkh)(ctx->checkhctx,U,a,&h);
324: }
326: /* keep a record of the current differencing parameter h */
327: ctx->currenth = h;
328: #if defined(PETSC_USE_COMPLEX)
329: PetscInfo2(mat,"Current differencing parameter: %G + %G i\n",PetscRealPart(h),PetscImaginaryPart(h));
330: #else
331: PetscInfo1(mat,"Current differencing parameter: %15.12e\n",h);
332: #endif
333: if (ctx->historyh && ctx->ncurrenth < ctx->maxcurrenth) {
334: ctx->historyh[ctx->ncurrenth] = h;
335: }
336: ctx->ncurrenth++;
338: /* w = u + ha */
339: VecWAXPY(w,h,a,U);
341: /* compute func(U) as base for differencing; only needed first time in and not when provided by user */
342: if (ctx->ncurrenth == 1 && ctx->current_f_allocated) {
343: (*ctx->func)(ctx->funcctx,U,F);
344: }
345: (*ctx->func)(ctx->funcctx,w,y);
347: VecAXPY(y,-1.0,F);
348: VecScale(y,1.0/h);
350: VecAXPBY(y,ctx->vshift,ctx->vscale,a);
352: if (ctx->sp) {MatNullSpaceRemove(ctx->sp,y,PETSC_NULL);}
354: PetscLogEventEnd(MATMFFD_Mult,a,y,0,0);
355: return(0);
356: }
360: /*
361: MatGetDiagonal_MFFD - Gets the diagonal for a matrix free matrix
363: y ~= (F(u + ha) - F(u))/h,
364: where F = nonlinear function, as set by SNESSetFunction()
365: u = current iterate
366: h = difference interval
367: */
368: PetscErrorCode MatGetDiagonal_MFFD(Mat mat,Vec a)
369: {
370: MatMFFD ctx = (MatMFFD)mat->data;
371: PetscScalar h,*aa,*ww,v;
372: PetscReal epsilon = PETSC_SQRT_MACHINE_EPSILON,umin = 100.0*PETSC_SQRT_MACHINE_EPSILON;
373: Vec w,U;
375: PetscInt i,rstart,rend;
378: if (!ctx->funci) {
379: SETERRQ(PETSC_ERR_ORDER,"Requires calling MatMFFDSetFunctioni() first");
380: }
382: w = ctx->w;
383: U = ctx->current_u;
384: (*ctx->func)(ctx->funcctx,U,a);
385: (*ctx->funcisetbase)(ctx->funcctx,U);
386: VecCopy(U,w);
388: VecGetOwnershipRange(a,&rstart,&rend);
389: VecGetArray(a,&aa);
390: for (i=rstart; i<rend; i++) {
391: VecGetArray(w,&ww);
392: h = ww[i-rstart];
393: if (h == 0.0) h = 1.0;
394: #if !defined(PETSC_USE_COMPLEX)
395: if (h < umin && h >= 0.0) h = umin;
396: else if (h < 0.0 && h > -umin) h = -umin;
397: #else
398: if (PetscAbsScalar(h) < umin && PetscRealPart(h) >= 0.0) h = umin;
399: else if (PetscRealPart(h) < 0.0 && PetscAbsScalar(h) < umin) h = -umin;
400: #endif
401: h *= epsilon;
402:
403: ww[i-rstart] += h;
404: VecRestoreArray(w,&ww);
405: (*ctx->funci)(ctx->funcctx,i,w,&v);
406: aa[i-rstart] = (v - aa[i-rstart])/h;
408: /* possibly shift and scale result */
409: aa[i - rstart] = ctx->vshift + ctx->vscale*aa[i-rstart];
411: VecGetArray(w,&ww);
412: ww[i-rstart] -= h;
413: VecRestoreArray(w,&ww);
414: }
415: VecRestoreArray(a,&aa);
416: return(0);
417: }
421: PetscErrorCode MatShift_MFFD(Mat Y,PetscScalar a)
422: {
423: MatMFFD shell = (MatMFFD)Y->data;
425: shell->vshift += a;
426: return(0);
427: }
431: PetscErrorCode MatScale_MFFD(Mat Y,PetscScalar a)
432: {
433: MatMFFD shell = (MatMFFD)Y->data;
435: shell->vscale *= a;
436: return(0);
437: }
442: PetscErrorCode MatMFFDSetBase_MFFD(Mat J,Vec U,Vec F)
443: {
445: MatMFFD ctx = (MatMFFD)J->data;
448: MatMFFDResetHHistory(J);
449: ctx->current_u = U;
450: if (F) {
451: if (ctx->current_f_allocated) {VecDestroy(ctx->current_f);}
452: ctx->current_f = F;
453: ctx->current_f_allocated = PETSC_FALSE;
454: } else if (!ctx->current_f_allocated) {
455: VecDuplicate(ctx->current_u, &ctx->current_f);
456: ctx->current_f_allocated = PETSC_TRUE;
457: }
458: if (!ctx->w) {
459: VecDuplicate(ctx->current_u, &ctx->w);
460: }
461: J->assembled = PETSC_TRUE;
462: return(0);
463: }
469: PetscErrorCode MatMFFDSetCheckh_MFFD(Mat J,FCN3 fun,void*ectx)
470: {
471: MatMFFD ctx = (MatMFFD)J->data;
474: ctx->checkh = fun;
475: ctx->checkhctx = ectx;
476: return(0);
477: }
482: /*@C
483: MatMFFDSetOptionsPrefix - Sets the prefix used for searching for all
484: MatMFFD options in the database.
486: Collective on Mat
488: Input Parameter:
489: + A - the Mat context
490: - prefix - the prefix to prepend to all option names
492: Notes:
493: A hyphen (-) must NOT be given at the beginning of the prefix name.
494: The first character of all runtime options is AUTOMATICALLY the hyphen.
496: Level: advanced
498: .keywords: SNES, matrix-free, parameters
500: .seealso: MatMFFDSetFromOptions(), MatCreateSNESMF()
501: @*/
502: PetscErrorCode MatMFFDSetOptionsPrefix(Mat mat,const char prefix[])
504: {
505: MatMFFD mfctx = mat ? (MatMFFD)mat->data : PETSC_NULL;
510: PetscObjectSetOptionsPrefix((PetscObject)mfctx,prefix);
511: return(0);
512: }
516: /*@
517: MatMFFDSetFromOptions - Sets the MatMFFD options from the command line
518: parameter.
520: Collective on Mat
522: Input Parameters:
523: . mat - the matrix obtained with MatCreateMFFD() or MatCreateSNESMF()
525: Options Database Keys:
526: + -mat_mffd_type - wp or ds (see MATMFFD_WP or MATMFFD_DS)
527: - -mat_mffd_err - square root of estimated relative error in function evaluation
528: - -mat_mffd_period - how often h is recomputed, defaults to 1, everytime
530: Level: advanced
532: .keywords: SNES, matrix-free, parameters
534: .seealso: MatCreateSNESMF(),MatMFFDSetHHistory(), MatMFFDResetHHistory()
535: @*/
536: PetscErrorCode MatMFFDSetFromOptions(Mat mat)
537: {
538: MatMFFD mfctx = mat ? (MatMFFD)mat->data : PETSC_NULL;
540: PetscTruth flg;
541: char ftype[256];
546: PetscOptionsBegin(((PetscObject)mfctx)->comm,((PetscObject)mfctx)->prefix,"Set matrix free computation parameters","MatMFFD");
547: PetscOptionsList("-mat_mffd_type","Matrix free type","MatMFFDSetType",MatMFFDList,((PetscObject)mfctx)->type_name,ftype,256,&flg);
548: if (flg) {
549: MatMFFDSetType(mat,ftype);
550: }
552: PetscOptionsReal("-mat_mffd_err","set sqrt relative error in function","MatMFFDSetFunctionError",mfctx->error_rel,&mfctx->error_rel,0);
553: PetscOptionsInt("-mat_mffd_period","how often h is recomputed","MatMFFDSetPeriod",mfctx->recomputeperiod,&mfctx->recomputeperiod,0);
555: flg = PETSC_FALSE;
556: PetscOptionsTruth("-mat_mffd_check_positivity","Insure that U + h*a is nonnegative","MatMFFDSetCheckh",flg,&flg,PETSC_NULL);
557: if (flg) {
558: MatMFFDSetCheckh(mat,MatMFFDCheckPositivity,0);
559: }
560: if (mfctx->ops->setfromoptions) {
561: (*mfctx->ops->setfromoptions)(mfctx);
562: }
563: PetscOptionsEnd();
564: return(0);
565: }
567: /*MC
568: MATMFFD - MATMFFD = "mffd" - A matrix free matrix type.
570: Level: advanced
572: .seealso: MatCreateMFFD(), MatCreateSNESMF(), MatMFFDSetFunction()
573: M*/
577: PetscErrorCode MatCreate_MFFD(Mat A)
578: {
579: MatMFFD mfctx;
580: PetscErrorCode ierr;
583: #ifndef PETSC_USE_DYNAMIC_LIBRARIES
584: MatMFFDInitializePackage(PETSC_NULL);
585: #endif
587: PetscHeaderCreate(mfctx,_p_MatMFFD,struct _MFOps,MATMFFD_COOKIE,0,"MatMFFD",((PetscObject)A)->comm,MatDestroy_MFFD,MatView_MFFD);
588: mfctx->sp = 0;
589: mfctx->error_rel = PETSC_SQRT_MACHINE_EPSILON;
590: mfctx->recomputeperiod = 1;
591: mfctx->count = 0;
592: mfctx->currenth = 0.0;
593: mfctx->historyh = PETSC_NULL;
594: mfctx->ncurrenth = 0;
595: mfctx->maxcurrenth = 0;
596: ((PetscObject)mfctx)->type_name = 0;
598: mfctx->vshift = 0.0;
599: mfctx->vscale = 1.0;
601: /*
602: Create the empty data structure to contain compute-h routines.
603: These will be filled in below from the command line options or
604: a later call with MatMFFDSetType() or if that is not called
605: then it will default in the first use of MatMult_MFFD()
606: */
607: mfctx->ops->compute = 0;
608: mfctx->ops->destroy = 0;
609: mfctx->ops->view = 0;
610: mfctx->ops->setfromoptions = 0;
611: mfctx->hctx = 0;
613: mfctx->func = 0;
614: mfctx->funcctx = 0;
615: mfctx->w = PETSC_NULL;
617: A->data = mfctx;
619: A->ops->mult = MatMult_MFFD;
620: A->ops->destroy = MatDestroy_MFFD;
621: A->ops->view = MatView_MFFD;
622: A->ops->assemblyend = MatAssemblyEnd_MFFD;
623: A->ops->getdiagonal = MatGetDiagonal_MFFD;
624: A->ops->scale = MatScale_MFFD;
625: A->ops->shift = MatShift_MFFD;
626: A->ops->setfromoptions = MatMFFDSetFromOptions;
627: A->assembled = PETSC_TRUE;
629: PetscLayoutSetBlockSize(A->rmap,1);
630: PetscLayoutSetBlockSize(A->cmap,1);
631: PetscLayoutSetUp(A->rmap);
632: PetscLayoutSetUp(A->cmap);
634: PetscObjectComposeFunctionDynamic((PetscObject)A,"MatMFFDSetBase_C","MatMFFDSetBase_MFFD",MatMFFDSetBase_MFFD);
635: PetscObjectComposeFunctionDynamic((PetscObject)A,"MatMFFDSetFunctioniBase_C","MatMFFDSetFunctioniBase_MFFD",MatMFFDSetFunctioniBase_MFFD);
636: PetscObjectComposeFunctionDynamic((PetscObject)A,"MatMFFDSetFunctioni_C","MatMFFDSetFunctioni_MFFD",MatMFFDSetFunctioni_MFFD);
637: PetscObjectComposeFunctionDynamic((PetscObject)A,"MatMFFDSetCheckh_C","MatMFFDSetCheckh_MFFD",MatMFFDSetCheckh_MFFD);
638: mfctx->mat = A;
639: PetscObjectChangeTypeName((PetscObject)A,MATMFFD);
640: return(0);
641: }
646: /*@
647: MatCreateMFFD - Creates a matrix-free matrix. See also MatCreateSNESMF()
649: Collective on Vec
651: Input Parameters:
652: + comm - MPI communicator
653: . m - number of local rows (or PETSC_DECIDE to have calculated if M is given)
654: This value should be the same as the local size used in creating the
655: y vector for the matrix-vector product y = Ax.
656: . n - This value should be the same as the local size used in creating the
657: x vector for the matrix-vector product y = Ax. (or PETSC_DECIDE to have
658: calculated if N is given) For square matrices n is almost always m.
659: . M - number of global rows (or PETSC_DETERMINE to have calculated if m is given)
660: - N - number of global columns (or PETSC_DETERMINE to have calculated if n is given)
663: Output Parameter:
664: . J - the matrix-free matrix
666: Level: advanced
668: Notes:
669: The matrix-free matrix context merely contains the function pointers
670: and work space for performing finite difference approximations of
671: Jacobian-vector products, F'(u)*a,
673: The default code uses the following approach to compute h
675: .vb
676: F'(u)*a = [F(u+h*a) - F(u)]/h where
677: h = error_rel*u'a/||a||^2 if |u'a| > umin*||a||_{1}
678: = error_rel*umin*sign(u'a)*||a||_{1}/||a||^2 otherwise
679: where
680: error_rel = square root of relative error in function evaluation
681: umin = minimum iterate parameter
682: .ve
684: The user can set the error_rel via MatMFFDSetFunctionError() and
685: umin via MatMFFDDSSetUmin(); see the nonlinear solvers chapter
686: of the users manual for details.
688: The user should call MatDestroy() when finished with the matrix-free
689: matrix context.
691: Options Database Keys:
692: + -mat_mffd_err <error_rel> - Sets error_rel
693: . -mat_mffd_unim <umin> - Sets umin (for default PETSc routine that computes h only)
694: - -mat_mffd_check_positivity
696: .keywords: default, matrix-free, create, matrix
698: .seealso: MatDestroy(), MatMFFDSetFunctionError(), MatMFFDDSSetUmin(), MatMFFDSetFunction()
699: MatMFFDSetHHistory(), MatMFFDResetHHistory(), MatCreateSNESMF(),
700: MatMFFDGetH(), MatMFFDRegisterDynamic), MatMFFDComputeJacobian()
701:
702: @*/
703: PetscErrorCode MatCreateMFFD(MPI_Comm comm,PetscInt m,PetscInt n,PetscInt M,PetscInt N,Mat *J)
704: {
708: MatCreate(comm,J);
709: MatSetSizes(*J,m,n,M,N);
710: MatSetType(*J,MATMFFD);
711: return(0);
712: }
717: /*@
718: MatMFFDGetH - Gets the last value that was used as the differencing
719: parameter.
721: Not Collective
723: Input Parameters:
724: . mat - the matrix obtained with MatCreateSNESMF()
726: Output Paramter:
727: . h - the differencing step size
729: Level: advanced
731: .keywords: SNES, matrix-free, parameters
733: .seealso: MatCreateSNESMF(),MatMFFDSetHHistory(), MatCreateMFFD(), MATMFFD, MatMFFDResetHHistory()
734: @*/
735: PetscErrorCode MatMFFDGetH(Mat mat,PetscScalar *h)
736: {
737: MatMFFD ctx = (MatMFFD)mat->data;
740: *h = ctx->currenth;
741: return(0);
742: }
747: /*@C
748: MatMFFDSetFunction - Sets the function used in applying the matrix free.
750: Collective on Mat
752: Input Parameters:
753: + mat - the matrix free matrix created via MatCreateSNESMF()
754: . func - the function to use
755: - funcctx - optional function context passed to function
757: Level: advanced
759: Notes:
760: If you use this you MUST call MatAssemblyBegin()/MatAssemblyEnd() on the matrix free
761: matrix inside your compute Jacobian routine
763: If this is not set then it will use the function set with SNESSetFunction() if MatCreateSNESMF() was used.
765: .keywords: SNES, matrix-free, function
767: .seealso: MatCreateSNESMF(),MatMFFDGetH(), MatCreateMFFD(), MATMFFD,
768: MatMFFDSetHHistory(), MatMFFDResetHHistory(), SNESetFunction()
769: @*/
770: PetscErrorCode MatMFFDSetFunction(Mat mat,PetscErrorCode (*func)(void*,Vec,Vec),void *funcctx)
771: {
772: MatMFFD ctx = (MatMFFD)mat->data;
775: ctx->func = func;
776: ctx->funcctx = funcctx;
777: return(0);
778: }
782: /*@C
783: MatMFFDSetFunctioni - Sets the function for a single component
785: Collective on Mat
787: Input Parameters:
788: + mat - the matrix free matrix created via MatCreateSNESMF()
789: - funci - the function to use
791: Level: advanced
793: Notes:
794: If you use this you MUST call MatAssemblyBegin()/MatAssemblyEnd() on the matrix free
795: matrix inside your compute Jacobian routine
798: .keywords: SNES, matrix-free, function
800: .seealso: MatCreateSNESMF(),MatMFFDGetH(), MatMFFDSetHHistory(), MatMFFDResetHHistory(), SNESetFunction()
802: @*/
803: PetscErrorCode MatMFFDSetFunctioni(Mat mat,PetscErrorCode (*funci)(void*,PetscInt,Vec,PetscScalar*))
804: {
805: PetscErrorCode ierr,(*f)(Mat,PetscErrorCode (*)(void*,PetscInt,Vec,PetscScalar*));
809: PetscObjectQueryFunction((PetscObject)mat,"MatMFFDSetFunctioni_C",(void (**)(void))&f);
810: if (f) {
811: (*f)(mat,funci);
812: }
813: return(0);
814: }
819: /*@C
820: MatMFFDSetFunctioniBase - Sets the base vector for a single component function evaluation
822: Collective on Mat
824: Input Parameters:
825: + mat - the matrix free matrix created via MatCreateSNESMF()
826: - func - the function to use
828: Level: advanced
830: Notes:
831: If you use this you MUST call MatAssemblyBegin()/MatAssemblyEnd() on the matrix free
832: matrix inside your compute Jacobian routine
835: .keywords: SNES, matrix-free, function
837: .seealso: MatCreateSNESMF(),MatMFFDGetH(), MatCreateMFFD(), MATMFFD
838: MatMFFDSetHHistory(), MatMFFDResetHHistory(), SNESetFunction()
839: @*/
840: PetscErrorCode MatMFFDSetFunctioniBase(Mat mat,PetscErrorCode (*func)(void*,Vec))
841: {
842: PetscErrorCode ierr,(*f)(Mat,PetscErrorCode (*)(void*,Vec));
846: PetscObjectQueryFunction((PetscObject)mat,"MatMFFDSetFunctioniBase_C",(void (**)(void))&f);
847: if (f) {
848: (*f)(mat,func);
849: }
850: return(0);
851: }
856: /*@
857: MatMFFDSetPeriod - Sets how often h is recomputed, by default it is everytime
859: Collective on Mat
861: Input Parameters:
862: + mat - the matrix free matrix created via MatCreateSNESMF()
863: - period - 1 for everytime, 2 for every second etc
865: Options Database Keys:
866: + -mat_mffd_period <period>
868: Level: advanced
871: .keywords: SNES, matrix-free, parameters
873: .seealso: MatCreateSNESMF(),MatMFFDGetH(),
874: MatMFFDSetHHistory(), MatMFFDResetHHistory()
875: @*/
876: PetscErrorCode MatMFFDSetPeriod(Mat mat,PetscInt period)
877: {
878: MatMFFD ctx = (MatMFFD)mat->data;
881: ctx->recomputeperiod = period;
882: return(0);
883: }
887: /*@
888: MatMFFDSetFunctionError - Sets the error_rel for the approximation of
889: matrix-vector products using finite differences.
891: Collective on Mat
893: Input Parameters:
894: + mat - the matrix free matrix created via MatCreateMFFD() or MatCreateSNESMF()
895: - error_rel - relative error (should be set to the square root of
896: the relative error in the function evaluations)
898: Options Database Keys:
899: + -mat_mffd_err <error_rel> - Sets error_rel
901: Level: advanced
903: Notes:
904: The default matrix-free matrix-vector product routine computes
905: .vb
906: F'(u)*a = [F(u+h*a) - F(u)]/h where
907: h = error_rel*u'a/||a||^2 if |u'a| > umin*||a||_{1}
908: = error_rel*umin*sign(u'a)*||a||_{1}/||a||^2 else
909: .ve
911: .keywords: SNES, matrix-free, parameters
913: .seealso: MatCreateSNESMF(),MatMFFDGetH(), MatCreateMFFD(), MATMFFD
914: MatMFFDSetHHistory(), MatMFFDResetHHistory()
915: @*/
916: PetscErrorCode MatMFFDSetFunctionError(Mat mat,PetscReal error)
917: {
918: MatMFFD ctx = (MatMFFD)mat->data;
921: if (error != PETSC_DEFAULT) ctx->error_rel = error;
922: return(0);
923: }
927: /*@
928: MatMFFDAddNullSpace - Provides a null space that an operator is
929: supposed to have. Since roundoff will create a small component in
930: the null space, if you know the null space you may have it
931: automatically removed.
933: Collective on Mat
935: Input Parameters:
936: + J - the matrix-free matrix context
937: - nullsp - object created with MatNullSpaceCreate()
939: Level: advanced
941: .keywords: SNES, matrix-free, null space
943: .seealso: MatNullSpaceCreate(), MatMFFDGetH(), MatCreateSNESMF(), MatCreateMFFD(), MATMFFD
944: MatMFFDSetHHistory(), MatMFFDResetHHistory()
945: @*/
946: PetscErrorCode MatMFFDAddNullSpace(Mat J,MatNullSpace nullsp)
947: {
949: MatMFFD ctx = (MatMFFD)J->data;
952: PetscObjectReference((PetscObject)nullsp);
953: if (ctx->sp) { MatNullSpaceDestroy(ctx->sp); }
954: ctx->sp = nullsp;
955: return(0);
956: }
960: /*@
961: MatMFFDSetHHistory - Sets an array to collect a history of the
962: differencing values (h) computed for the matrix-free product.
964: Collective on Mat
966: Input Parameters:
967: + J - the matrix-free matrix context
968: . histroy - space to hold the history
969: - nhistory - number of entries in history, if more entries are generated than
970: nhistory, then the later ones are discarded
972: Level: advanced
974: Notes:
975: Use MatMFFDResetHHistory() to reset the history counter and collect
976: a new batch of differencing parameters, h.
978: .keywords: SNES, matrix-free, h history, differencing history
980: .seealso: MatMFFDGetH(), MatCreateSNESMF(),
981: MatMFFDResetHHistory(), MatMFFDSetFunctionError()
983: @*/
984: PetscErrorCode MatMFFDSetHHistory(Mat J,PetscScalar history[],PetscInt nhistory)
985: {
986: MatMFFD ctx = (MatMFFD)J->data;
989: ctx->historyh = history;
990: ctx->maxcurrenth = nhistory;
991: ctx->currenth = 0.;
992: return(0);
993: }
997: /*@
998: MatMFFDResetHHistory - Resets the counter to zero to begin
999: collecting a new set of differencing histories.
1001: Collective on Mat
1003: Input Parameters:
1004: . J - the matrix-free matrix context
1006: Level: advanced
1008: Notes:
1009: Use MatMFFDSetHHistory() to create the original history counter.
1011: .keywords: SNES, matrix-free, h history, differencing history
1013: .seealso: MatMFFDGetH(), MatCreateSNESMF(),
1014: MatMFFDSetHHistory(), MatMFFDSetFunctionError()
1016: @*/
1017: PetscErrorCode MatMFFDResetHHistory(Mat J)
1018: {
1019: MatMFFD ctx = (MatMFFD)J->data;
1022: ctx->ncurrenth = 0;
1023: return(0);
1024: }
1029: /*@
1030: MatMFFDSetBase - Sets the vector U at which matrix vector products of the
1031: Jacobian are computed
1033: Collective on Mat
1035: Input Parameters:
1036: + J - the MatMFFD matrix
1037: . U - the vector
1038: - F - (optional) vector that contains F(u) if it has been already computed
1040: Notes: This is rarely used directly
1042: If F is provided then it is not recomputed. Otherwise the function is evaluated at the base
1043: point during the first MatMult() after each call to MatMFFDSetBase().
1045: Level: advanced
1047: @*/
1048: PetscErrorCode MatMFFDSetBase(Mat J,Vec U,Vec F)
1049: {
1050: PetscErrorCode ierr,(*f)(Mat,Vec,Vec);
1056: PetscObjectQueryFunction((PetscObject)J,"MatMFFDSetBase_C",(void (**)(void))&f);
1057: if (f) {
1058: (*f)(J,U,F);
1059: }
1060: return(0);
1061: }
1065: /*@C
1066: MatMFFDSetCheckh - Sets a function that checks the computed h and adjusts
1067: it to satisfy some criteria
1069: Collective on Mat
1071: Input Parameters:
1072: + J - the MatMFFD matrix
1073: . fun - the function that checks h
1074: - ctx - any context needed by the function
1076: Options Database Keys:
1077: . -mat_mffd_check_positivity
1079: Level: advanced
1081: Notes: For example, MatMFFDSetCheckPositivity() insures that all entries
1082: of U + h*a are non-negative
1084: .seealso: MatMFFDSetCheckPositivity()
1085: @*/
1086: PetscErrorCode MatMFFDSetCheckh(Mat J,PetscErrorCode (*fun)(void*,Vec,Vec,PetscScalar*),void* ctx)
1087: {
1088: PetscErrorCode ierr,(*f)(Mat,PetscErrorCode (*)(void*,Vec,Vec,PetscScalar*),void*);
1092: PetscObjectQueryFunction((PetscObject)J,"MatMFFDSetCheckh_C",(void (**)(void))&f);
1093: if (f) {
1094: (*f)(J,fun,ctx);
1095: }
1096: return(0);
1097: }
1101: /*@
1102: MatMFFDCheckPositivity - Checks that all entries in U + h*a are positive or
1103: zero, decreases h until this is satisfied.
1105: Collective on Vec
1107: Input Parameters:
1108: + U - base vector that is added to
1109: . a - vector that is added
1110: . h - scaling factor on a
1111: - dummy - context variable (unused)
1113: Options Database Keys:
1114: . -mat_mffd_check_positivity
1116: Level: advanced
1118: Notes: This is rarely used directly, rather it is passed as an argument to
1119: MatMFFDSetCheckh()
1121: .seealso: MatMFFDSetCheckh()
1122: @*/
1123: PetscErrorCode MatMFFDCheckPositivity(void* dummy,Vec U,Vec a,PetscScalar *h)
1124: {
1125: PetscReal val, minval;
1126: PetscScalar *u_vec, *a_vec;
1128: PetscInt i,n;
1129: MPI_Comm comm;
1132: PetscObjectGetComm((PetscObject)U,&comm);
1133: VecGetArray(U,&u_vec);
1134: VecGetArray(a,&a_vec);
1135: VecGetLocalSize(U,&n);
1136: minval = PetscAbsScalar(*h*1.01);
1137: for(i=0;i<n;i++) {
1138: if (PetscRealPart(u_vec[i] + *h*a_vec[i]) <= 0.0) {
1139: val = PetscAbsScalar(u_vec[i]/a_vec[i]);
1140: if (val < minval) minval = val;
1141: }
1142: }
1143: VecRestoreArray(U,&u_vec);
1144: VecRestoreArray(a,&a_vec);
1145: PetscGlobalMin(&minval,&val,comm);
1146: if (val <= PetscAbsScalar(*h)) {
1147: PetscInfo2(U,"Scaling back h from %G to %G\n",PetscRealPart(*h),.99*val);
1148: if (PetscRealPart(*h) > 0.0) *h = 0.99*val;
1149: else *h = -0.99*val;
1150: }
1151: return(0);
1152: }