Actual source code: dt.c
1: /* Discretization tools */
3: #include <petscdt.h>
4: #include <petscblaslapack.h>
5: #include <petsc/private/petscimpl.h>
6: #include <petsc/private/dtimpl.h>
7: #include <petsc/private/petscfeimpl.h>
8: #include <petscdmplex.h>
9: #include <petscdmshell.h>
11: #if PetscDefined(HAVE_MPFR)
12: #include <mpfr.h>
13: #endif
15: const char *const PetscDTNodeTypes_shifted[] = {"default", "gaussjacobi", "equispaced", "tanhsinh", "PetscDTNodeType", "PETSCDTNODES_", NULL};
16: const char *const *const PetscDTNodeTypes = PetscDTNodeTypes_shifted + 1;
18: const char *const PetscDTSimplexQuadratureTypes_shifted[] = {"default", "conic", "minsym", "diagsym", "PetscDTSimplexQuadratureType", "PETSCDTSIMPLEXQUAD_", NULL};
19: const char *const *const PetscDTSimplexQuadratureTypes = PetscDTSimplexQuadratureTypes_shifted + 1;
21: static PetscBool GolubWelschCite = PETSC_FALSE;
22: const char GolubWelschCitation[] = "@article{GolubWelsch1969,\n"
23: " author = {Golub and Welsch},\n"
24: " title = {Calculation of Quadrature Rules},\n"
25: " journal = {Math. Comp.},\n"
26: " volume = {23},\n"
27: " number = {106},\n"
28: " pages = {221--230},\n"
29: " year = {1969}\n}\n";
31: /* Numerical tests in src/dm/dt/tests/ex1.c show that when computing the nodes and weights of Gauss-Jacobi
32: quadrature rules:
34: - in double precision, Newton's method and Golub & Welsch both work for moderate degrees (< 100),
35: - in single precision, Newton's method starts producing incorrect roots around n = 15, but
36: the weights from Golub & Welsch become a problem before then: they produces errors
37: in computing the Jacobi-polynomial Gram matrix around n = 6.
39: So we default to Newton's method (required fewer dependencies) */
40: PetscBool PetscDTGaussQuadratureNewton_Internal = PETSC_TRUE;
42: PetscClassId PETSCQUADRATURE_CLASSID = 0;
44: /*@
45: PetscQuadratureCreate - Create a `PetscQuadrature` object
47: Collective
49: Input Parameter:
50: . comm - The communicator for the `PetscQuadrature` object
52: Output Parameter:
53: . q - The `PetscQuadrature` object
55: Level: beginner
57: .seealso: `PetscQuadrature`, `Petscquadraturedestroy()`, `PetscQuadratureGetData()`
58: @*/
59: PetscErrorCode PetscQuadratureCreate(MPI_Comm comm, PetscQuadrature *q)
60: {
61: PetscFunctionBegin;
62: PetscAssertPointer(q, 2);
63: PetscCall(DMInitializePackage());
64: PetscCall(PetscHeaderCreate(*q, PETSCQUADRATURE_CLASSID, "PetscQuadrature", "Quadrature", "DT", comm, PetscQuadratureDestroy, PetscQuadratureView));
65: (*q)->ct = DM_POLYTOPE_UNKNOWN;
66: (*q)->dim = -1;
67: (*q)->Nc = 1;
68: (*q)->order = -1;
69: (*q)->numPoints = 0;
70: (*q)->points = NULL;
71: (*q)->weights = NULL;
72: PetscFunctionReturn(PETSC_SUCCESS);
73: }
75: /*@
76: PetscQuadratureDuplicate - Create a deep copy of the `PetscQuadrature` object
78: Collective
80: Input Parameter:
81: . q - The `PetscQuadrature` object
83: Output Parameter:
84: . r - The new `PetscQuadrature` object
86: Level: beginner
88: .seealso: `PetscQuadrature`, `PetscQuadratureCreate()`, `PetscQuadratureDestroy()`, `PetscQuadratureGetData()`
89: @*/
90: PetscErrorCode PetscQuadratureDuplicate(PetscQuadrature q, PetscQuadrature *r)
91: {
92: DMPolytopeType ct;
93: PetscInt order, dim, Nc, Nq;
94: const PetscReal *points, *weights;
95: PetscReal *p, *w;
97: PetscFunctionBegin;
98: PetscAssertPointer(q, 1);
99: PetscCall(PetscQuadratureCreate(PetscObjectComm((PetscObject)q), r));
100: PetscCall(PetscQuadratureGetCellType(q, &ct));
101: PetscCall(PetscQuadratureSetCellType(*r, ct));
102: PetscCall(PetscQuadratureGetOrder(q, &order));
103: PetscCall(PetscQuadratureSetOrder(*r, order));
104: PetscCall(PetscQuadratureGetData(q, &dim, &Nc, &Nq, &points, &weights));
105: PetscCall(PetscMalloc1(Nq * dim, &p));
106: PetscCall(PetscMalloc1(Nq * Nc, &w));
107: PetscCall(PetscArraycpy(p, points, Nq * dim));
108: PetscCall(PetscArraycpy(w, weights, Nc * Nq));
109: PetscCall(PetscQuadratureSetData(*r, dim, Nc, Nq, p, w));
110: PetscFunctionReturn(PETSC_SUCCESS);
111: }
113: static PetscErrorCode PetscQuadratureClearPermutations_Private(PetscQuadrature q)
114: {
115: PetscFunctionBegin;
116: for (PetscInt a = 0; a < q->Na; ++a) PetscCall(ISDestroy(&q->perms[a]));
117: PetscCall(PetscFree(q->perms));
118: q->Na = 0;
119: PetscFunctionReturn(PETSC_SUCCESS);
120: }
122: /*@
123: PetscQuadratureDestroy - Destroys a `PetscQuadrature` object
125: Collective
127: Input Parameter:
128: . q - The `PetscQuadrature` object
130: Level: beginner
132: .seealso: `PetscQuadrature`, `PetscQuadratureCreate()`, `PetscQuadratureGetData()`
133: @*/
134: PetscErrorCode PetscQuadratureDestroy(PetscQuadrature *q)
135: {
136: PetscFunctionBegin;
137: if (!*q) PetscFunctionReturn(PETSC_SUCCESS);
139: if (--((PetscObject)*q)->refct > 0) {
140: *q = NULL;
141: PetscFunctionReturn(PETSC_SUCCESS);
142: }
143: PetscCall(PetscFree((*q)->points));
144: PetscCall(PetscFree((*q)->weights));
145: PetscCall(PetscQuadratureClearPermutations_Private(*q));
146: PetscCall(PetscHeaderDestroy(q));
147: PetscFunctionReturn(PETSC_SUCCESS);
148: }
150: /*@
151: PetscQuadratureGetCellType - Return the cell type of the integration domain
153: Not Collective
155: Input Parameter:
156: . q - The `PetscQuadrature` object
158: Output Parameter:
159: . ct - The cell type of the integration domain
161: Level: intermediate
163: .seealso: `PetscQuadrature`, `PetscQuadratureSetCellType()`, `PetscQuadratureGetData()`, `PetscQuadratureSetData()`
164: @*/
165: PetscErrorCode PetscQuadratureGetCellType(PetscQuadrature q, DMPolytopeType *ct)
166: {
167: PetscFunctionBegin;
169: PetscAssertPointer(ct, 2);
170: *ct = q->ct;
171: PetscFunctionReturn(PETSC_SUCCESS);
172: }
174: /*@
175: PetscQuadratureSetCellType - Set the cell type of the integration domain
177: Not Collective
179: Input Parameters:
180: + q - The `PetscQuadrature` object
181: - ct - The cell type of the integration domain
183: Level: intermediate
185: .seealso: `PetscQuadrature`, `PetscQuadratureGetCellType()`, `PetscQuadratureGetData()`, `PetscQuadratureSetData()`
186: @*/
187: PetscErrorCode PetscQuadratureSetCellType(PetscQuadrature q, DMPolytopeType ct)
188: {
189: PetscFunctionBegin;
191: PetscCall(PetscQuadratureClearPermutations_Private(q));
192: q->ct = ct;
193: PetscFunctionReturn(PETSC_SUCCESS);
194: }
196: /*@
197: PetscQuadratureGetOrder - Return the order of the method in the `PetscQuadrature`
199: Not Collective
201: Input Parameter:
202: . q - The `PetscQuadrature` object
204: Output Parameter:
205: . order - The order of the quadrature, i.e. the highest degree polynomial that is exactly integrated
207: Level: intermediate
209: .seealso: `PetscQuadrature`, `PetscQuadratureSetOrder()`, `PetscQuadratureGetData()`, `PetscQuadratureSetData()`
210: @*/
211: PetscErrorCode PetscQuadratureGetOrder(PetscQuadrature q, PetscInt *order)
212: {
213: PetscFunctionBegin;
215: PetscAssertPointer(order, 2);
216: *order = q->order;
217: PetscFunctionReturn(PETSC_SUCCESS);
218: }
220: /*@
221: PetscQuadratureSetOrder - Set the order of the method in the `PetscQuadrature`
223: Not Collective
225: Input Parameters:
226: + q - The `PetscQuadrature` object
227: - order - The order of the quadrature, i.e. the highest degree polynomial that is exactly integrated
229: Level: intermediate
231: .seealso: `PetscQuadrature`, `PetscQuadratureGetOrder()`, `PetscQuadratureGetData()`, `PetscQuadratureSetData()`
232: @*/
233: PetscErrorCode PetscQuadratureSetOrder(PetscQuadrature q, PetscInt order)
234: {
235: PetscFunctionBegin;
237: q->order = order;
238: PetscFunctionReturn(PETSC_SUCCESS);
239: }
241: /*@
242: PetscQuadratureGetNumComponents - Return the number of components for functions to be integrated
244: Not Collective
246: Input Parameter:
247: . q - The `PetscQuadrature` object
249: Output Parameter:
250: . Nc - The number of components
252: Level: intermediate
254: Note:
255: We are performing an integral $\int f(x) w(x) dx$, where both $f$ and $w$ (the weight) have `Nc` components.
257: .seealso: `PetscQuadrature`, `PetscQuadratureSetNumComponents()`, `PetscQuadratureGetData()`, `PetscQuadratureSetData()`
258: @*/
259: PetscErrorCode PetscQuadratureGetNumComponents(PetscQuadrature q, PetscInt *Nc)
260: {
261: PetscFunctionBegin;
263: PetscAssertPointer(Nc, 2);
264: *Nc = q->Nc;
265: PetscFunctionReturn(PETSC_SUCCESS);
266: }
268: /*@
269: PetscQuadratureSetNumComponents - Sets the number of components for functions to be integrated
271: Not Collective
273: Input Parameters:
274: + q - The `PetscQuadrature` object
275: - Nc - The number of components
277: Level: intermediate
279: Note:
280: We are performing an integral $\int f(x) w(x) dx$, where both $f$ and $w$ (the weight) have `Nc` components.
282: .seealso: `PetscQuadrature`, `PetscQuadratureGetNumComponents()`, `PetscQuadratureGetData()`, `PetscQuadratureSetData()`
283: @*/
284: PetscErrorCode PetscQuadratureSetNumComponents(PetscQuadrature q, PetscInt Nc)
285: {
286: PetscFunctionBegin;
288: q->Nc = Nc;
289: PetscFunctionReturn(PETSC_SUCCESS);
290: }
292: /*@
293: PetscQuadratureGetData - Returns the data defining the `PetscQuadrature`
295: Not Collective
297: Input Parameter:
298: . q - The `PetscQuadrature` object
300: Output Parameters:
301: + dim - The spatial dimension
302: . Nc - The number of components
303: . npoints - The number of quadrature points
304: . points - The coordinates of each quadrature point
305: - weights - The weight of each quadrature point
307: Level: intermediate
309: Note:
310: All output arguments are optional, pass `NULL` for any argument not required
312: Fortran Note:
313: Call `PetscQuadratureRestoreData()` when you are done with the data
315: .seealso: `PetscQuadrature`, `PetscQuadratureCreate()`, `PetscQuadratureSetData()`
316: @*/
317: PetscErrorCode PetscQuadratureGetData(PetscQuadrature q, PeOp PetscInt *dim, PeOp PetscInt *Nc, PeOp PetscInt *npoints, PeOp const PetscReal *points[], PeOp const PetscReal *weights[])
318: {
319: PetscFunctionBegin;
321: if (dim) {
322: PetscAssertPointer(dim, 2);
323: *dim = q->dim;
324: }
325: if (Nc) {
326: PetscAssertPointer(Nc, 3);
327: *Nc = q->Nc;
328: }
329: if (npoints) {
330: PetscAssertPointer(npoints, 4);
331: *npoints = q->numPoints;
332: }
333: if (points) {
334: PetscAssertPointer(points, 5);
335: *points = q->points;
336: }
337: if (weights) {
338: PetscAssertPointer(weights, 6);
339: *weights = q->weights;
340: }
341: PetscFunctionReturn(PETSC_SUCCESS);
342: }
344: /*@
345: PetscQuadratureEqual - determine whether two quadratures are equivalent
347: Input Parameters:
348: + A - A `PetscQuadrature` object
349: - B - Another `PetscQuadrature` object
351: Output Parameter:
352: . equal - `PETSC_TRUE` if the quadratures are the same
354: Level: intermediate
356: .seealso: `PetscQuadrature`, `PetscQuadratureCreate()`
357: @*/
358: PetscErrorCode PetscQuadratureEqual(PetscQuadrature A, PetscQuadrature B, PetscBool *equal)
359: {
360: PetscFunctionBegin;
363: PetscAssertPointer(equal, 3);
364: *equal = PETSC_FALSE;
365: if (A->ct != B->ct || A->dim != B->dim || A->Nc != B->Nc || A->order != B->order || A->numPoints != B->numPoints) PetscFunctionReturn(PETSC_SUCCESS);
366: for (PetscInt i = 0; i < A->numPoints * A->dim; i++) {
367: if (PetscAbsReal(A->points[i] - B->points[i]) > PETSC_SMALL) PetscFunctionReturn(PETSC_SUCCESS);
368: }
369: if (!A->weights && !B->weights) {
370: *equal = PETSC_TRUE;
371: PetscFunctionReturn(PETSC_SUCCESS);
372: }
373: if (A->weights && B->weights) {
374: for (PetscInt i = 0; i < A->numPoints; i++) {
375: if (PetscAbsReal(A->weights[i] - B->weights[i]) > PETSC_SMALL) PetscFunctionReturn(PETSC_SUCCESS);
376: }
377: *equal = PETSC_TRUE;
378: }
379: PetscFunctionReturn(PETSC_SUCCESS);
380: }
382: static PetscErrorCode PetscDTJacobianInverse_Internal(PetscInt m, PetscInt n, const PetscReal J[], PetscReal Jinv[])
383: {
384: PetscScalar *Js, *Jinvs;
385: PetscInt i, j, k;
386: PetscBLASInt bm, bn;
388: PetscFunctionBegin;
389: if (!m || !n) PetscFunctionReturn(PETSC_SUCCESS);
390: PetscCall(PetscBLASIntCast(m, &bm));
391: PetscCall(PetscBLASIntCast(n, &bn));
392: #if PetscDefined(USE_COMPLEX)
393: PetscCall(PetscMalloc2(m * n, &Js, m * n, &Jinvs));
394: for (i = 0; i < m * n; i++) Js[i] = J[i];
395: #else
396: Js = (PetscReal *)J;
397: Jinvs = Jinv;
398: #endif
399: if (m == n) {
400: PetscBLASInt *pivots;
401: PetscScalar *W;
403: PetscCall(PetscMalloc2(m, &pivots, m, &W));
405: PetscCall(PetscArraycpy(Jinvs, Js, m * m));
406: PetscCallLAPACKInfo("LAPACKgetrf", LAPACKgetrf_(&bm, &bm, Jinvs, &bm, pivots, &info));
407: PetscCallLAPACKInfo("LAPACKgetri", LAPACKgetri_(&bm, Jinvs, &bm, pivots, W, &bm, &info));
408: PetscCall(PetscFree2(pivots, W));
409: } else if (m < n) {
410: PetscScalar *JJT;
411: PetscBLASInt *pivots;
412: PetscScalar *W;
414: PetscCall(PetscMalloc1(m * m, &JJT));
415: PetscCall(PetscMalloc2(m, &pivots, m, &W));
416: for (i = 0; i < m; i++) {
417: for (j = 0; j < m; j++) {
418: PetscScalar val = 0.;
420: for (k = 0; k < n; k++) val += Js[i * n + k] * Js[j * n + k];
421: JJT[i * m + j] = val;
422: }
423: }
425: PetscCallLAPACKInfo("LAPACKgetrf", LAPACKgetrf_(&bm, &bm, JJT, &bm, pivots, &info));
426: PetscCallLAPACKInfo("LAPACKgetri", LAPACKgetri_(&bm, JJT, &bm, pivots, W, &bm, &info));
427: for (i = 0; i < n; i++) {
428: for (j = 0; j < m; j++) {
429: PetscScalar val = 0.;
431: for (k = 0; k < m; k++) val += Js[k * n + i] * JJT[k * m + j];
432: Jinvs[i * m + j] = val;
433: }
434: }
435: PetscCall(PetscFree2(pivots, W));
436: PetscCall(PetscFree(JJT));
437: } else {
438: PetscScalar *JTJ;
439: PetscBLASInt *pivots;
440: PetscScalar *W;
442: PetscCall(PetscMalloc1(n * n, &JTJ));
443: PetscCall(PetscMalloc2(n, &pivots, n, &W));
444: for (i = 0; i < n; i++) {
445: for (j = 0; j < n; j++) {
446: PetscScalar val = 0.;
448: for (k = 0; k < m; k++) val += Js[k * n + i] * Js[k * n + j];
449: JTJ[i * n + j] = val;
450: }
451: }
453: PetscCallLAPACKInfo("LAPACKgetrf", LAPACKgetrf_(&bn, &bn, JTJ, &bn, pivots, &info));
454: PetscCallLAPACKInfo("LAPACKgetri", LAPACKgetri_(&bn, JTJ, &bn, pivots, W, &bn, &info));
455: for (i = 0; i < n; i++) {
456: for (j = 0; j < m; j++) {
457: PetscScalar val = 0.;
459: for (k = 0; k < n; k++) val += JTJ[i * n + k] * Js[j * n + k];
460: Jinvs[i * m + j] = val;
461: }
462: }
463: PetscCall(PetscFree2(pivots, W));
464: PetscCall(PetscFree(JTJ));
465: }
466: #if PetscDefined(USE_COMPLEX)
467: for (i = 0; i < m * n; i++) Jinv[i] = PetscRealPart(Jinvs[i]);
468: PetscCall(PetscFree2(Js, Jinvs));
469: #endif
470: PetscFunctionReturn(PETSC_SUCCESS);
471: }
473: /*@
474: PetscQuadraturePushForward - Push forward a quadrature functional under an affine transformation.
476: Collective
478: Input Parameters:
479: + q - the quadrature functional
480: . imageDim - the dimension of the image of the transformation
481: . origin - a point in the original space
482: . originImage - the image of the origin under the transformation
483: . J - the Jacobian of the image: an [imageDim x dim] matrix in row major order
484: - formDegree - transform the quadrature weights as k-forms of this form degree (if the number of components is a multiple of (dim choose `formDegree`),
485: it is assumed that they represent multiple k-forms) [see `PetscDTAltVPullback()` for interpretation of `formDegree`]
487: Output Parameter:
488: . Jinvstarq - a quadrature rule where each point is the image of a point in the original quadrature rule, and where the k-form weights have
489: been pulled-back by the pseudoinverse of `J` to the k-form weights in the image space.
491: Level: intermediate
493: Note:
494: The new quadrature rule will have a different number of components if spaces have different dimensions.
495: For example, pushing a 2-form forward from a two dimensional space to a three dimensional space changes the number of components from 1 to 3.
497: .seealso: `PetscQuadrature`, `PetscDTAltVPullback()`, `PetscDTAltVPullbackMatrix()`
498: @*/
499: PetscErrorCode PetscQuadraturePushForward(PetscQuadrature q, PetscInt imageDim, const PetscReal origin[], const PetscReal originImage[], const PetscReal J[], PetscInt formDegree, PetscQuadrature *Jinvstarq)
500: {
501: PetscInt dim, Nc, imageNc, formSize, Ncopies, imageFormSize, Npoints, pt, i, j, c;
502: const PetscReal *points;
503: const PetscReal *weights;
504: PetscReal *imagePoints, *imageWeights;
505: PetscReal *Jinv;
506: PetscReal *Jinvstar;
508: PetscFunctionBegin;
510: PetscCheck(imageDim >= PetscAbsInt(formDegree), PetscObjectComm((PetscObject)q), PETSC_ERR_ARG_INCOMP, "Cannot represent a %" PetscInt_FMT "-form in %" PetscInt_FMT " dimensions", PetscAbsInt(formDegree), imageDim);
511: PetscCall(PetscQuadratureGetData(q, &dim, &Nc, &Npoints, &points, &weights));
512: PetscCall(PetscDTBinomialInt(dim, PetscAbsInt(formDegree), &formSize));
513: PetscCheck(Nc % formSize == 0, PetscObjectComm((PetscObject)q), PETSC_ERR_ARG_INCOMP, "Number of components %" PetscInt_FMT " is not a multiple of formSize %" PetscInt_FMT, Nc, formSize);
514: Ncopies = Nc / formSize;
515: PetscCall(PetscDTBinomialInt(imageDim, PetscAbsInt(formDegree), &imageFormSize));
516: imageNc = Ncopies * imageFormSize;
517: PetscCall(PetscMalloc1(Npoints * imageDim, &imagePoints));
518: PetscCall(PetscMalloc1(Npoints * imageNc, &imageWeights));
519: PetscCall(PetscMalloc2(imageDim * dim, &Jinv, formSize * imageFormSize, &Jinvstar));
520: PetscCall(PetscDTJacobianInverse_Internal(imageDim, dim, J, Jinv));
521: PetscCall(PetscDTAltVPullbackMatrix(imageDim, dim, Jinv, formDegree, Jinvstar));
522: for (pt = 0; pt < Npoints; pt++) {
523: const PetscReal *point = PetscSafePointerPlusOffset(points, pt * dim);
524: PetscReal *imagePoint = &imagePoints[pt * imageDim];
526: for (i = 0; i < imageDim; i++) {
527: PetscReal val = originImage[i];
529: for (j = 0; j < dim; j++) val += J[i * dim + j] * (point[j] - origin[j]);
530: imagePoint[i] = val;
531: }
532: for (c = 0; c < Ncopies; c++) {
533: const PetscReal *form = &weights[pt * Nc + c * formSize];
534: PetscReal *imageForm = &imageWeights[pt * imageNc + c * imageFormSize];
536: for (i = 0; i < imageFormSize; i++) {
537: PetscReal val = 0.;
539: for (j = 0; j < formSize; j++) val += Jinvstar[i * formSize + j] * form[j];
540: imageForm[i] = val;
541: }
542: }
543: }
544: PetscCall(PetscQuadratureCreate(PetscObjectComm((PetscObject)q), Jinvstarq));
545: PetscCall(PetscQuadratureSetData(*Jinvstarq, imageDim, imageNc, Npoints, imagePoints, imageWeights));
546: PetscCall(PetscFree2(Jinv, Jinvstar));
547: PetscFunctionReturn(PETSC_SUCCESS);
548: }
550: /*@
551: PetscQuadratureSetData - Sets the data defining the quadrature
553: Not Collective
555: Input Parameters:
556: + q - The `PetscQuadrature` object
557: . dim - The spatial dimension
558: . Nc - The number of components
559: . npoints - The number of quadrature points
560: . points - The coordinates of each quadrature point
561: - weights - The weight of each quadrature point
563: Level: intermediate
565: Note:
566: `q` owns the references to points and weights, so they must be allocated using `PetscMalloc()` and the user should not free them.
568: .seealso: `PetscQuadrature`, `PetscQuadratureCreate()`, `PetscQuadratureGetData()`
569: @*/
570: PetscErrorCode PetscQuadratureSetData(PetscQuadrature q, PetscInt dim, PetscInt Nc, PetscInt npoints, const PetscReal points[], const PetscReal weights[]) PeNSS
571: {
572: PetscFunctionBegin;
574: PetscCall(PetscQuadratureClearPermutations_Private(q));
575: if (dim >= 0) q->dim = dim;
576: if (Nc >= 0) q->Nc = Nc;
577: if (npoints >= 0) q->numPoints = npoints;
578: if (points) {
579: PetscAssertPointer(points, 5);
580: q->points = points;
581: }
582: if (weights) {
583: PetscAssertPointer(weights, 6);
584: q->weights = weights;
585: }
586: PetscFunctionReturn(PETSC_SUCCESS);
587: }
589: static PetscErrorCode PetscQuadratureView_Ascii(PetscQuadrature quad, PetscViewer v)
590: {
591: PetscInt q, d, c;
592: PetscViewerFormat format;
594: PetscFunctionBegin;
595: if (quad->Nc > 1)
596: PetscCall(PetscViewerASCIIPrintf(v, "Quadrature on a %s of order %" PetscInt_FMT " on %" PetscInt_FMT " points (dim %" PetscInt_FMT ") with %" PetscInt_FMT " components\n", DMPolytopeTypes[quad->ct], quad->order, quad->numPoints, quad->dim, quad->Nc));
597: else PetscCall(PetscViewerASCIIPrintf(v, "Quadrature on a %s of order %" PetscInt_FMT " on %" PetscInt_FMT " points (dim %" PetscInt_FMT ")\n", DMPolytopeTypes[quad->ct], quad->order, quad->numPoints, quad->dim));
598: PetscCall(PetscViewerGetFormat(v, &format));
599: if (format != PETSC_VIEWER_ASCII_INFO_DETAIL) PetscFunctionReturn(PETSC_SUCCESS);
600: for (q = 0; q < quad->numPoints; ++q) {
601: PetscCall(PetscViewerASCIIPrintf(v, "p%" PetscInt_FMT " (", q));
602: PetscCall(PetscViewerASCIIUseTabs(v, PETSC_FALSE));
603: for (d = 0; d < quad->dim; ++d) {
604: if (d) PetscCall(PetscViewerASCIIPrintf(v, ", "));
605: PetscCall(PetscViewerASCIIPrintf(v, "%+g", (double)quad->points[q * quad->dim + d]));
606: }
607: PetscCall(PetscViewerASCIIPrintf(v, ") "));
608: if (quad->Nc > 1) PetscCall(PetscViewerASCIIPrintf(v, "w%" PetscInt_FMT " (", q));
609: for (c = 0; c < quad->Nc; ++c) {
610: if (c) PetscCall(PetscViewerASCIIPrintf(v, ", "));
611: PetscCall(PetscViewerASCIIPrintf(v, "%+g", (double)quad->weights[q * quad->Nc + c]));
612: }
613: if (quad->Nc > 1) PetscCall(PetscViewerASCIIPrintf(v, ")"));
614: PetscCall(PetscViewerASCIIPrintf(v, "\n"));
615: PetscCall(PetscViewerASCIIUseTabs(v, PETSC_TRUE));
616: }
617: PetscFunctionReturn(PETSC_SUCCESS);
618: }
620: /*@
621: PetscQuadratureView - View a `PetscQuadrature` object
623: Collective
625: Input Parameters:
626: + quad - The `PetscQuadrature` object
627: - viewer - The `PetscViewer` object
629: Level: beginner
631: .seealso: `PetscQuadrature`, `PetscViewer`, `PetscQuadratureCreate()`, `PetscQuadratureGetData()`
632: @*/
633: PetscErrorCode PetscQuadratureView(PetscQuadrature quad, PetscViewer viewer)
634: {
635: PetscBool isascii;
637: PetscFunctionBegin;
640: if (!viewer) PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)quad), &viewer));
641: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
642: PetscCall(PetscViewerASCIIPushTab(viewer));
643: if (isascii) PetscCall(PetscQuadratureView_Ascii(quad, viewer));
644: PetscCall(PetscViewerASCIIPopTab(viewer));
645: PetscFunctionReturn(PETSC_SUCCESS);
646: }
648: /*@
649: PetscQuadratureExpandComposite - Return a quadrature over the composite element, which has the original quadrature in each subelement
651: Not Collective; No Fortran Support
653: Input Parameters:
654: + q - The original `PetscQuadrature`
655: . numSubelements - The number of subelements the original element is divided into
656: . v0 - An array of the initial points for each subelement
657: - jac - An array of the Jacobian mappings from the reference to each subelement
659: Output Parameter:
660: . qref - The dimension
662: Level: intermediate
664: Note:
665: Together `v0` and `jac` define an affine mapping from the original reference element to each subelement
667: .seealso: `PetscQuadrature`, `PetscFECreate()`, `PetscSpaceGetDimension()`, `PetscDualSpaceGetDimension()`
668: @*/
669: PetscErrorCode PetscQuadratureExpandComposite(PetscQuadrature q, PetscInt numSubelements, const PetscReal v0[], const PetscReal jac[], PetscQuadrature *qref)
670: {
671: DMPolytopeType ct;
672: const PetscReal *points, *weights;
673: PetscReal *pointsRef, *weightsRef;
674: PetscInt dim, Nc, order, npoints, npointsRef, c, p, cp, d, e;
676: PetscFunctionBegin;
678: PetscAssertPointer(v0, 3);
679: PetscAssertPointer(jac, 4);
680: PetscAssertPointer(qref, 5);
681: PetscCall(PetscQuadratureCreate(PETSC_COMM_SELF, qref));
682: PetscCall(PetscQuadratureGetCellType(q, &ct));
683: PetscCall(PetscQuadratureGetOrder(q, &order));
684: PetscCall(PetscQuadratureGetData(q, &dim, &Nc, &npoints, &points, &weights));
685: npointsRef = npoints * numSubelements;
686: PetscCall(PetscMalloc1(npointsRef * dim, &pointsRef));
687: PetscCall(PetscMalloc1(npointsRef * Nc, &weightsRef));
688: for (c = 0; c < numSubelements; ++c) {
689: for (p = 0; p < npoints; ++p) {
690: for (d = 0; d < dim; ++d) {
691: pointsRef[(c * npoints + p) * dim + d] = v0[c * dim + d];
692: for (e = 0; e < dim; ++e) pointsRef[(c * npoints + p) * dim + d] += jac[(c * dim + d) * dim + e] * (points[p * dim + e] + 1.0);
693: }
694: /* Could also use detJ here */
695: for (cp = 0; cp < Nc; ++cp) weightsRef[(c * npoints + p) * Nc + cp] = weights[p * Nc + cp] / numSubelements;
696: }
697: }
698: PetscCall(PetscQuadratureSetCellType(*qref, ct));
699: PetscCall(PetscQuadratureSetOrder(*qref, order));
700: PetscCall(PetscQuadratureSetData(*qref, dim, Nc, npointsRef, pointsRef, weightsRef));
701: PetscFunctionReturn(PETSC_SUCCESS);
702: }
704: /* Compute the coefficients for the Jacobi polynomial recurrence,
706: J^{a,b}_n(x) = (cnm1 + cnm1x * x) * J^{a,b}_{n-1}(x) - cnm2 * J^{a,b}_{n-2}(x).
707: */
708: #define PetscDTJacobiRecurrence_Internal(n, a, b, cnm1, cnm1x, cnm2) \
709: do { \
710: PetscReal _a = (a); \
711: PetscReal _b = (b); \
712: PetscReal _n = (n); \
713: if (n == 1) { \
714: (cnm1) = (_a - _b) * 0.5; \
715: (cnm1x) = (_a + _b + 2.) * 0.5; \
716: (cnm2) = 0.; \
717: } else { \
718: PetscReal _2n = _n + _n; \
719: PetscReal _d = (_2n * (_n + _a + _b) * (_2n + _a + _b - 2)); \
720: PetscReal _n1 = (_2n + _a + _b - 1.) * (_a * _a - _b * _b); \
721: PetscReal _n1x = (_2n + _a + _b - 1.) * (_2n + _a + _b) * (_2n + _a + _b - 2); \
722: PetscReal _n2 = 2. * ((_n + _a - 1.) * (_n + _b - 1.) * (_2n + _a + _b)); \
723: (cnm1) = _n1 / _d; \
724: (cnm1x) = _n1x / _d; \
725: (cnm2) = _n2 / _d; \
726: } \
727: } while (0)
729: /*@
730: PetscDTJacobiNorm - Compute the weighted L2 norm of a Jacobi polynomial.
732: $\| P^{\alpha,\beta}_n \|_{\alpha,\beta}^2 = \int_{-1}^1 (1 + x)^{\alpha} (1 - x)^{\beta} P^{\alpha,\beta}_n (x)^2 dx.$
734: Input Parameters:
735: + alpha - the left exponent > -1
736: . beta - the right exponent > -1
737: - n - the polynomial degree
739: Output Parameter:
740: . norm - the weighted L2 norm
742: Level: beginner
744: .seealso: `PetscQuadrature`, `PetscDTJacobiEval()`
745: @*/
746: PetscErrorCode PetscDTJacobiNorm(PetscReal alpha, PetscReal beta, PetscInt n, PetscReal *norm)
747: {
748: PetscReal twoab1;
749: PetscReal gr;
751: PetscFunctionBegin;
752: PetscCheck(alpha > -1., PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Exponent alpha %g <= -1. invalid", (double)alpha);
753: PetscCheck(beta > -1., PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Exponent beta %g <= -1. invalid", (double)beta);
754: PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "n %" PetscInt_FMT " < 0 invalid", n);
755: twoab1 = PetscPowReal(2., alpha + beta + 1.);
756: #if PetscDefined(HAVE_LGAMMA)
757: if (!n) {
758: gr = PetscExpReal(PetscLGamma(alpha + 1.) + PetscLGamma(beta + 1.) - PetscLGamma(alpha + beta + 2.));
759: } else {
760: gr = PetscExpReal(PetscLGamma(n + alpha + 1.) + PetscLGamma(n + beta + 1.) - (PetscLGamma(n + 1.) + PetscLGamma(n + alpha + beta + 1.))) / (n + n + alpha + beta + 1.);
761: }
762: #else
763: {
764: PetscInt alphai = (PetscInt)alpha;
765: PetscInt betai = (PetscInt)beta;
766: PetscInt i;
768: gr = n ? (1. / (n + n + alpha + beta + 1.)) : 1.;
769: if ((PetscReal)alphai == alpha) {
770: if (!n) {
771: for (i = 0; i < alphai; i++) gr *= (i + 1.) / (beta + i + 1.);
772: gr /= (alpha + beta + 1.);
773: } else {
774: for (i = 0; i < alphai; i++) gr *= (n + i + 1.) / (n + beta + i + 1.);
775: }
776: } else if ((PetscReal)betai == beta) {
777: if (!n) {
778: for (i = 0; i < betai; i++) gr *= (i + 1.) / (alpha + i + 2.);
779: gr /= (alpha + beta + 1.);
780: } else {
781: for (i = 0; i < betai; i++) gr *= (n + i + 1.) / (n + alpha + i + 1.);
782: }
783: } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "lgamma() - math routine is unavailable.");
784: }
785: #endif
786: *norm = PetscSqrtReal(twoab1 * gr);
787: PetscFunctionReturn(PETSC_SUCCESS);
788: }
790: static PetscErrorCode PetscDTJacobiEval_Internal(PetscInt npoints, PetscReal a, PetscReal b, PetscInt k, const PetscReal *points, PetscInt ndegree, const PetscInt *degrees, PetscReal *p)
791: {
792: PetscReal ak, bk;
793: PetscReal abk1;
794: PetscInt i, l, maxdegree;
796: PetscFunctionBegin;
797: maxdegree = degrees[ndegree - 1] - k;
798: ak = a + k;
799: bk = b + k;
800: abk1 = a + b + k + 1.;
801: if (maxdegree < 0) {
802: for (i = 0; i < npoints; i++)
803: for (l = 0; l < ndegree; l++) p[i * ndegree + l] = 0.;
804: PetscFunctionReturn(PETSC_SUCCESS);
805: }
806: for (i = 0; i < npoints; i++) {
807: PetscReal pm1, pm2, x;
808: PetscReal cnm1, cnm1x, cnm2;
809: PetscInt j;
811: x = points[i];
812: pm2 = 1.;
813: PetscDTJacobiRecurrence_Internal(1, ak, bk, cnm1, cnm1x, cnm2);
814: pm1 = (cnm1 + cnm1x * x);
815: l = 0;
816: while (l < ndegree && degrees[l] - k < 0) p[l++] = 0.;
817: while (l < ndegree && degrees[l] - k == 0) {
818: p[l] = pm2;
819: for (PetscInt m = 0; m < k; m++) p[l] *= (abk1 + m) * 0.5;
820: l++;
821: }
822: while (l < ndegree && degrees[l] - k == 1) {
823: p[l] = pm1;
824: for (PetscInt m = 0; m < k; m++) p[l] *= (abk1 + 1 + m) * 0.5;
825: l++;
826: }
827: for (j = 2; j <= maxdegree; j++) {
828: PetscReal pp;
830: PetscDTJacobiRecurrence_Internal(j, ak, bk, cnm1, cnm1x, cnm2);
831: pp = (cnm1 + cnm1x * x) * pm1 - cnm2 * pm2;
832: pm2 = pm1;
833: pm1 = pp;
834: while (l < ndegree && degrees[l] - k == j) {
835: p[l] = pp;
836: for (PetscInt m = 0; m < k; m++) p[l] *= (abk1 + j + m) * 0.5;
837: l++;
838: }
839: }
840: p += ndegree;
841: }
842: PetscFunctionReturn(PETSC_SUCCESS);
843: }
845: /*@
846: PetscDTJacobiEvalJet - Evaluate the jet (function and derivatives) of the Jacobi polynomials basis up to a given degree.
848: Input Parameters:
849: + alpha - the left exponent of the weight
850: . beta - the right exponetn of the weight
851: . npoints - the number of points to evaluate the polynomials at
852: . points - [npoints] array of point coordinates
853: . degree - the maximm degree polynomial space to evaluate, (degree + 1) will be evaluated total.
854: - k - the maximum derivative to evaluate in the jet, (k + 1) will be evaluated total.
856: Output Parameter:
857: . p - an array containing the evaluations of the Jacobi polynomials's jets on the points. the size is (degree + 1) x
858: (k + 1) x npoints, which also describes the order of the dimensions of this three-dimensional array: the first
859: (slowest varying) dimension is polynomial degree; the second dimension is derivative order; the third (fastest
860: varying) dimension is the index of the evaluation point.
862: Level: advanced
864: Notes:
865: The Jacobi polynomials with indices $\alpha$ and $\beta$ are orthogonal with respect to the
866: weighted inner product $\langle f, g \rangle = \int_{-1}^1 (1+x)^{\alpha} (1-x)^{\beta} f(x)
867: g(x) dx$.
869: .seealso: `PetscDTJacobiEval()`, `PetscDTPKDEvalJet()`
870: @*/
871: PetscErrorCode PetscDTJacobiEvalJet(PetscReal alpha, PetscReal beta, PetscInt npoints, const PetscReal points[], PetscInt degree, PetscInt k, PetscReal p[])
872: {
873: PetscInt i, j, l;
874: PetscInt *degrees;
875: PetscReal *psingle;
877: PetscFunctionBegin;
878: if (degree == 0) {
879: PetscInt zero = 0;
881: for (i = 0; i <= k; i++) PetscCall(PetscDTJacobiEval_Internal(npoints, alpha, beta, i, points, 1, &zero, &p[i * npoints]));
882: PetscFunctionReturn(PETSC_SUCCESS);
883: }
884: PetscCall(PetscMalloc1(degree + 1, °rees));
885: PetscCall(PetscMalloc1((degree + 1) * npoints, &psingle));
886: for (i = 0; i <= degree; i++) degrees[i] = i;
887: for (i = 0; i <= k; i++) {
888: PetscCall(PetscDTJacobiEval_Internal(npoints, alpha, beta, i, points, degree + 1, degrees, psingle));
889: for (j = 0; j <= degree; j++) {
890: for (l = 0; l < npoints; l++) p[(j * (k + 1) + i) * npoints + l] = psingle[l * (degree + 1) + j];
891: }
892: }
893: PetscCall(PetscFree(psingle));
894: PetscCall(PetscFree(degrees));
895: PetscFunctionReturn(PETSC_SUCCESS);
896: }
898: /*@
899: PetscDTJacobiEval - evaluate Jacobi polynomials for the weight function $(1.+x)^{\alpha} (1.-x)^{\beta}$ at a set of points
900: at points
902: Not Collective
904: Input Parameters:
905: + npoints - number of spatial points to evaluate at
906: . alpha - the left exponent > -1
907: . beta - the right exponent > -1
908: . points - array of locations to evaluate at
909: . ndegree - number of basis degrees to evaluate
910: - degrees - sorted array of degrees to evaluate
912: Output Parameters:
913: + B - row-oriented basis evaluation matrix B[point*ndegree + degree] (dimension npoints*ndegrees, allocated by caller) (or `NULL`)
914: . D - row-oriented derivative evaluation matrix (or `NULL`)
915: - D2 - row-oriented second derivative evaluation matrix (or `NULL`)
917: Level: intermediate
919: .seealso: `PetscDTGaussQuadrature()`, `PetscDTLegendreEval()`
920: @*/
921: PetscErrorCode PetscDTJacobiEval(PetscInt npoints, PetscReal alpha, PetscReal beta, const PetscReal *points, PetscInt ndegree, const PetscInt *degrees, PeOp PetscReal B[], PeOp PetscReal D[], PeOp PetscReal D2[])
922: {
923: PetscFunctionBegin;
924: PetscCheck(alpha > -1., PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "alpha must be > -1.");
925: PetscCheck(beta > -1., PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "beta must be > -1.");
926: if (!npoints || !ndegree) PetscFunctionReturn(PETSC_SUCCESS);
927: if (B) PetscCall(PetscDTJacobiEval_Internal(npoints, alpha, beta, 0, points, ndegree, degrees, B));
928: if (D) PetscCall(PetscDTJacobiEval_Internal(npoints, alpha, beta, 1, points, ndegree, degrees, D));
929: if (D2) PetscCall(PetscDTJacobiEval_Internal(npoints, alpha, beta, 2, points, ndegree, degrees, D2));
930: PetscFunctionReturn(PETSC_SUCCESS);
931: }
933: /*@
934: PetscDTLegendreEval - evaluate Legendre polynomials at points
936: Not Collective
938: Input Parameters:
939: + npoints - number of spatial points to evaluate at
940: . points - array of locations to evaluate at
941: . ndegree - number of basis degrees to evaluate
942: - degrees - sorted array of degrees to evaluate
944: Output Parameters:
945: + B - row-oriented basis evaluation matrix B[point*ndegree + degree] (dimension `npoints`*`ndegrees`, allocated by caller) (or `NULL`)
946: . D - row-oriented derivative evaluation matrix (or `NULL`)
947: - D2 - row-oriented second derivative evaluation matrix (or `NULL`)
949: Level: intermediate
951: .seealso: `PetscDTGaussQuadrature()`
952: @*/
953: PetscErrorCode PetscDTLegendreEval(PetscInt npoints, const PetscReal *points, PetscInt ndegree, const PetscInt *degrees, PeOp PetscReal B[], PeOp PetscReal D[], PeOp PetscReal D2[])
954: {
955: PetscFunctionBegin;
956: PetscCall(PetscDTJacobiEval(npoints, 0., 0., points, ndegree, degrees, B, D, D2));
957: PetscFunctionReturn(PETSC_SUCCESS);
958: }
960: /*@
961: PetscDTIndexToGradedOrder - convert an index into a tuple of monomial degrees in a graded order (that is, if the degree sum of tuple x is less than the degree sum of tuple y,
962: then the index of x is smaller than the index of y)
964: Input Parameters:
965: + len - the desired length of the degree tuple
966: - index - the index to convert: should be >= 0
968: Output Parameter:
969: . degtup - filled with a tuple of degrees
971: Level: beginner
973: Note:
974: For two tuples x and y with the same degree sum, partial degree sums over the final elements of the tuples
975: acts as a tiebreaker. For example, (2, 1, 1) and (1, 2, 1) have the same degree sum, but the degree sum over the
976: last two elements is smaller for the former, so (2, 1, 1) < (1, 2, 1).
978: .seealso: `PetscDTGradedOrderToIndex()`
979: @*/
980: PetscErrorCode PetscDTIndexToGradedOrder(PetscInt len, PetscInt index, PetscInt degtup[])
981: {
982: PetscInt i, total;
983: PetscInt sum;
985: PetscFunctionBeginHot;
986: PetscCheck(len >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "length must be non-negative");
987: PetscCheck(index >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "index must be non-negative");
988: total = 1;
989: sum = 0;
990: while (index >= total) {
991: index -= total;
992: total = (total * (len + sum)) / (sum + 1);
993: sum++;
994: }
995: for (i = 0; i < len; i++) {
996: PetscInt c;
998: degtup[i] = sum;
999: for (c = 0, total = 1; c < sum; c++) {
1000: /* going into the loop, total is the number of way to have a tuple of sum exactly c with length len - 1 - i */
1001: if (index < total) break;
1002: index -= total;
1003: total = (total * (len - 1 - i + c)) / (c + 1);
1004: degtup[i]--;
1005: }
1006: sum -= degtup[i];
1007: }
1008: PetscFunctionReturn(PETSC_SUCCESS);
1009: }
1011: /*@
1012: PetscDTGradedOrderToIndex - convert a tuple into an index in a graded order, the inverse of `PetscDTIndexToGradedOrder()`.
1014: Input Parameters:
1015: + len - the length of the degree tuple
1016: - degtup - tuple with this length
1018: Output Parameter:
1019: . index - index in graded order: >= 0
1021: Level: beginner
1023: Note:
1024: For two tuples x and y with the same degree sum, partial degree sums over the final elements of the tuples
1025: acts as a tiebreaker. For example, (2, 1, 1) and (1, 2, 1) have the same degree sum, but the degree sum over the
1026: last two elements is smaller for the former, so (2, 1, 1) < (1, 2, 1).
1028: .seealso: `PetscDTIndexToGradedOrder()`
1029: @*/
1030: PetscErrorCode PetscDTGradedOrderToIndex(PetscInt len, const PetscInt degtup[], PetscInt *index)
1031: {
1032: PetscInt i, idx, sum, total;
1034: PetscFunctionBeginHot;
1035: PetscCheck(len >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "length must be non-negative");
1036: for (i = 0, sum = 0; i < len; i++) sum += degtup[i];
1037: idx = 0;
1038: total = 1;
1039: for (i = 0; i < sum; i++) {
1040: idx += total;
1041: total = (total * (len + i)) / (i + 1);
1042: }
1043: for (i = 0; i < len - 1; i++) {
1044: total = 1;
1045: sum -= degtup[i];
1046: for (PetscInt c = 0; c < sum; c++) {
1047: idx += total;
1048: total = (total * (len - 1 - i + c)) / (c + 1);
1049: }
1050: }
1051: *index = idx;
1052: PetscFunctionReturn(PETSC_SUCCESS);
1053: }
1055: static PetscBool PKDCite = PETSC_FALSE;
1056: const char PKDCitation[] = "@article{Kirby2010,\n"
1057: " title={Singularity-free evaluation of collapsed-coordinate orthogonal polynomials},\n"
1058: " author={Kirby, Robert C},\n"
1059: " journal={ACM Transactions on Mathematical Software (TOMS)},\n"
1060: " volume={37},\n"
1061: " number={1},\n"
1062: " pages={1--16},\n"
1063: " year={2010},\n"
1064: " publisher={ACM New York, NY, USA}\n}\n";
1066: /*@
1067: PetscDTPKDEvalJet - Evaluate the jet (function and derivatives) of the Proriol-Koornwinder-Dubiner (PKD) basis for
1068: the space of polynomials up to a given degree.
1070: Input Parameters:
1071: + dim - the number of variables in the multivariate polynomials
1072: . npoints - the number of points to evaluate the polynomials at
1073: . points - [npoints x dim] array of point coordinates
1074: . degree - the degree (sum of degrees on the variables in a monomial) of the polynomial space to evaluate. There are ((dim + degree) choose dim) polynomials in this space.
1075: - k - the maximum order partial derivative to evaluate in the jet. There are (dim + k choose dim) partial derivatives
1076: in the jet. Choosing k = 0 means to evaluate just the function and no derivatives
1078: Output Parameter:
1079: . p - an array containing the evaluations of the PKD polynomials' jets on the points. The size is ((dim + degree)
1080: choose dim) x ((dim + k) choose dim) x npoints, which also describes the order of the dimensions of this
1081: three-dimensional array: the first (slowest varying) dimension is basis function index; the second dimension is jet
1082: index; the third (fastest varying) dimension is the index of the evaluation point.
1084: Level: advanced
1086: Notes:
1087: The PKD basis is L2-orthonormal on the biunit simplex (which is used as the reference element
1088: for finite elements in PETSc), which makes it a stable basis to use for evaluating
1089: polynomials in that domain.
1091: The ordering of the basis functions, and the ordering of the derivatives in the jet, both follow the graded
1092: ordering of `PetscDTIndexToGradedOrder()` and `PetscDTGradedOrderToIndex()`. For example, in 3D, the polynomial with
1093: leading monomial x^2,y^0,z^1, which has degree tuple (2,0,1), which by `PetscDTGradedOrderToIndex()` has index 12 (it is the 13th basis function in the space);
1094: the partial derivative $\partial_x \partial_z$ has order tuple (1,0,1), appears at index 6 in the jet (it is the 7th partial derivative in the jet).
1096: The implementation uses Kirby's singularity-free evaluation algorithm, <https://doi.org/10.1145/1644001.1644006>.
1098: .seealso: `PetscDTGradedOrderToIndex()`, `PetscDTIndexToGradedOrder()`, `PetscDTJacobiEvalJet()`
1099: @*/
1100: PetscErrorCode PetscDTPKDEvalJet(PetscInt dim, PetscInt npoints, const PetscReal points[], PetscInt degree, PetscInt k, PetscReal p[])
1101: {
1102: PetscInt degidx, kidx, d, pt;
1103: PetscInt Nk, Ndeg;
1104: PetscInt *ktup, *degtup;
1105: PetscReal *scales, initscale, scaleexp;
1107: PetscFunctionBegin;
1108: PetscCall(PetscCitationsRegister(PKDCitation, &PKDCite));
1109: PetscCall(PetscDTBinomialInt(dim + k, k, &Nk));
1110: PetscCall(PetscDTBinomialInt(degree + dim, degree, &Ndeg));
1111: PetscCall(PetscMalloc2(dim, °tup, dim, &ktup));
1112: PetscCall(PetscMalloc1(Ndeg, &scales));
1113: initscale = 1.;
1114: if (dim > 1) {
1115: PetscCall(PetscDTBinomial(dim, 2, &scaleexp));
1116: initscale = PetscPowReal(2., scaleexp * 0.5);
1117: }
1118: for (degidx = 0; degidx < Ndeg; degidx++) {
1119: PetscInt e;
1120: PetscInt m1idx = -1, m2idx = -1;
1121: PetscInt n;
1122: PetscInt degsum;
1123: PetscReal alpha;
1124: PetscReal cnm1, cnm1x, cnm2;
1125: PetscReal norm;
1127: PetscCall(PetscDTIndexToGradedOrder(dim, degidx, degtup));
1128: for (d = dim - 1; d >= 0; d--)
1129: if (degtup[d]) break;
1130: if (d < 0) { /* constant is 1 everywhere, all derivatives are zero */
1131: scales[degidx] = initscale;
1132: for (e = 0; e < dim; e++) {
1133: PetscCall(PetscDTJacobiNorm(e, 0., 0, &norm));
1134: scales[degidx] /= norm;
1135: }
1136: for (PetscInt i = 0; i < npoints; i++) p[degidx * Nk * npoints + i] = 1.;
1137: for (PetscInt i = 0; i < (Nk - 1) * npoints; i++) p[(degidx * Nk + 1) * npoints + i] = 0.;
1138: continue;
1139: }
1140: n = degtup[d];
1141: degtup[d]--;
1142: PetscCall(PetscDTGradedOrderToIndex(dim, degtup, &m1idx));
1143: if (degtup[d] > 0) {
1144: degtup[d]--;
1145: PetscCall(PetscDTGradedOrderToIndex(dim, degtup, &m2idx));
1146: degtup[d]++;
1147: }
1148: degtup[d]++;
1149: for (e = 0, degsum = 0; e < d; e++) degsum += degtup[e];
1150: alpha = 2 * degsum + d;
1151: PetscDTJacobiRecurrence_Internal(n, alpha, 0., cnm1, cnm1x, cnm2);
1153: scales[degidx] = initscale;
1154: for (e = 0, degsum = 0; e < dim; e++) {
1155: PetscReal ealpha;
1156: PetscReal enorm;
1158: ealpha = 2 * degsum + e;
1159: for (PetscInt f = 0; f < degsum; f++) scales[degidx] *= 2.;
1160: PetscCall(PetscDTJacobiNorm(ealpha, 0., degtup[e], &enorm));
1161: scales[degidx] /= enorm;
1162: degsum += degtup[e];
1163: }
1165: for (pt = 0; pt < npoints; pt++) {
1166: /* compute the multipliers */
1167: PetscReal thetanm1, thetanm1x, thetanm2;
1169: thetanm1x = dim - (d + 1) + 2. * points[pt * dim + d];
1170: for (e = d + 1; e < dim; e++) thetanm1x += points[pt * dim + e];
1171: thetanm1x *= 0.5;
1172: thetanm1 = (2. - (dim - (d + 1)));
1173: for (e = d + 1; e < dim; e++) thetanm1 -= points[pt * dim + e];
1174: thetanm1 *= 0.5;
1175: thetanm2 = thetanm1 * thetanm1;
1177: for (kidx = 0; kidx < Nk; kidx++) {
1178: PetscCall(PetscDTIndexToGradedOrder(dim, kidx, ktup));
1179: /* first sum in the same derivative terms */
1180: p[(degidx * Nk + kidx) * npoints + pt] = (cnm1 * thetanm1 + cnm1x * thetanm1x) * p[(m1idx * Nk + kidx) * npoints + pt];
1181: if (m2idx >= 0) p[(degidx * Nk + kidx) * npoints + pt] -= cnm2 * thetanm2 * p[(m2idx * Nk + kidx) * npoints + pt];
1183: for (PetscInt f = d; f < dim; f++) {
1184: PetscInt km1idx, mplty = ktup[f];
1186: if (!mplty) continue;
1187: ktup[f]--;
1188: PetscCall(PetscDTGradedOrderToIndex(dim, ktup, &km1idx));
1190: /* the derivative of cnm1x * thetanm1x wrt x variable f is 0.5 * cnm1x if f > d otherwise it is cnm1x */
1191: /* the derivative of cnm1 * thetanm1 wrt x variable f is 0 if f == d, otherwise it is -0.5 * cnm1 */
1192: /* the derivative of -cnm2 * thetanm2 wrt x variable f is 0 if f == d, otherwise it is cnm2 * thetanm1 */
1193: if (f > d) {
1194: p[(degidx * Nk + kidx) * npoints + pt] += mplty * 0.5 * (cnm1x - cnm1) * p[(m1idx * Nk + km1idx) * npoints + pt];
1195: if (m2idx >= 0) {
1196: p[(degidx * Nk + kidx) * npoints + pt] += mplty * cnm2 * thetanm1 * p[(m2idx * Nk + km1idx) * npoints + pt];
1197: /* second derivatives of -cnm2 * thetanm2 wrt x variable f,f2 is like - 0.5 * cnm2 */
1198: for (PetscInt f2 = f; f2 < dim; f2++) {
1199: PetscInt km2idx, mplty2 = ktup[f2];
1200: PetscInt factor;
1202: if (!mplty2) continue;
1203: ktup[f2]--;
1204: PetscCall(PetscDTGradedOrderToIndex(dim, ktup, &km2idx));
1206: factor = mplty * mplty2;
1207: if (f == f2) factor /= 2;
1208: p[(degidx * Nk + kidx) * npoints + pt] -= 0.5 * factor * cnm2 * p[(m2idx * Nk + km2idx) * npoints + pt];
1209: ktup[f2]++;
1210: }
1211: }
1212: } else {
1213: p[(degidx * Nk + kidx) * npoints + pt] += mplty * cnm1x * p[(m1idx * Nk + km1idx) * npoints + pt];
1214: }
1215: ktup[f]++;
1216: }
1217: }
1218: }
1219: }
1220: for (degidx = 0; degidx < Ndeg; degidx++) {
1221: PetscReal scale = scales[degidx];
1223: for (PetscInt i = 0; i < Nk * npoints; i++) p[degidx * Nk * npoints + i] *= scale;
1224: }
1225: PetscCall(PetscFree(scales));
1226: PetscCall(PetscFree2(degtup, ktup));
1227: PetscFunctionReturn(PETSC_SUCCESS);
1228: }
1230: /*@
1231: PetscDTPTrimmedSize - The size of the trimmed polynomial space of k-forms with a given degree and form degree,
1232: which can be evaluated in `PetscDTPTrimmedEvalJet()`.
1234: Input Parameters:
1235: + dim - the number of variables in the multivariate polynomials
1236: . degree - the degree (sum of degrees on the variables in a monomial) of the trimmed polynomial space.
1237: - formDegree - the degree of the form
1239: Output Parameter:
1240: . size - The number ((`dim` + `degree`) choose (`dim` + `formDegree`)) x ((`degree` + `formDegree` - 1) choose (`formDegree`))
1242: Level: advanced
1244: .seealso: `PetscDTPTrimmedEvalJet()`
1245: @*/
1246: PetscErrorCode PetscDTPTrimmedSize(PetscInt dim, PetscInt degree, PetscInt formDegree, PetscInt *size)
1247: {
1248: PetscInt Nrk, Nbpt; // number of trimmed polynomials
1250: PetscFunctionBegin;
1251: formDegree = PetscAbsInt(formDegree);
1252: PetscCall(PetscDTBinomialInt(degree + dim, degree + formDegree, &Nbpt));
1253: PetscCall(PetscDTBinomialInt(degree + formDegree - 1, formDegree, &Nrk));
1254: Nbpt *= Nrk;
1255: *size = Nbpt;
1256: PetscFunctionReturn(PETSC_SUCCESS);
1257: }
1259: /* there was a reference implementation based on section 4.4 of Arnold, Falk & Winther (acta numerica, 2006), but it
1260: * was inferior to this implementation */
1261: static PetscErrorCode PetscDTPTrimmedEvalJet_Internal(PetscInt dim, PetscInt npoints, const PetscReal points[], PetscInt degree, PetscInt formDegree, PetscInt jetDegree, PetscReal p[])
1262: {
1263: PetscInt formDegreeOrig = formDegree;
1264: PetscBool formNegative = (formDegreeOrig < 0) ? PETSC_TRUE : PETSC_FALSE;
1266: PetscFunctionBegin;
1267: formDegree = PetscAbsInt(formDegreeOrig);
1268: if (formDegree == 0) {
1269: PetscCall(PetscDTPKDEvalJet(dim, npoints, points, degree, jetDegree, p));
1270: PetscFunctionReturn(PETSC_SUCCESS);
1271: }
1272: if (formDegree == dim) {
1273: PetscCall(PetscDTPKDEvalJet(dim, npoints, points, degree - 1, jetDegree, p));
1274: PetscFunctionReturn(PETSC_SUCCESS);
1275: }
1276: PetscInt Nbpt;
1277: PetscCall(PetscDTPTrimmedSize(dim, degree, formDegree, &Nbpt));
1278: PetscInt Nf;
1279: PetscCall(PetscDTBinomialInt(dim, formDegree, &Nf));
1280: PetscInt Nk;
1281: PetscCall(PetscDTBinomialInt(dim + jetDegree, dim, &Nk));
1282: PetscCall(PetscArrayzero(p, Nbpt * Nf * Nk * npoints));
1284: PetscInt Nbpm1; // number of scalar polynomials up to degree - 1;
1285: PetscCall(PetscDTBinomialInt(dim + degree - 1, dim, &Nbpm1));
1286: PetscReal *p_scalar;
1287: PetscCall(PetscMalloc1(Nbpm1 * Nk * npoints, &p_scalar));
1288: PetscCall(PetscDTPKDEvalJet(dim, npoints, points, degree - 1, jetDegree, p_scalar));
1289: PetscInt total = 0;
1290: // First add the full polynomials up to degree - 1 into the basis: take the scalar
1291: // and copy one for each form component
1292: for (PetscInt i = 0; i < Nbpm1; i++) {
1293: const PetscReal *src = &p_scalar[i * Nk * npoints];
1294: for (PetscInt f = 0; f < Nf; f++) {
1295: PetscReal *dest = &p[(total++ * Nf + f) * Nk * npoints];
1296: PetscCall(PetscArraycpy(dest, src, Nk * npoints));
1297: }
1298: }
1299: PetscInt *form_atoms;
1300: PetscCall(PetscMalloc1(formDegree + 1, &form_atoms));
1301: // construct the interior product pattern
1302: PetscInt (*pattern)[3];
1303: PetscInt Nf1; // number of formDegree + 1 forms
1304: PetscCall(PetscDTBinomialInt(dim, formDegree + 1, &Nf1));
1305: PetscInt nnz = Nf1 * (formDegree + 1);
1306: PetscCall(PetscMalloc1(Nf1 * (formDegree + 1), &pattern));
1307: PetscCall(PetscDTAltVInteriorPattern(dim, formDegree + 1, pattern));
1308: PetscReal centroid = (1. - dim) / (dim + 1.);
1309: PetscInt *deriv;
1310: PetscCall(PetscMalloc1(dim, &deriv));
1311: for (PetscInt d = dim; d >= formDegree + 1; d--) {
1312: PetscInt Nfd1; // number of formDegree + 1 forms in dimension d that include dx_0
1313: // (equal to the number of formDegree forms in dimension d-1)
1314: PetscCall(PetscDTBinomialInt(d - 1, formDegree, &Nfd1));
1315: // The number of homogeneous (degree-1) scalar polynomials in d variables
1316: PetscInt Nh;
1317: PetscCall(PetscDTBinomialInt(d - 1 + degree - 1, d - 1, &Nh));
1318: const PetscReal *h_scalar = &p_scalar[(Nbpm1 - Nh) * Nk * npoints];
1319: for (PetscInt b = 0; b < Nh; b++) {
1320: const PetscReal *h_s = &h_scalar[b * Nk * npoints];
1321: for (PetscInt f = 0; f < Nfd1; f++) {
1322: // construct all formDegree+1 forms that start with dx_(dim - d) /\ ...
1323: form_atoms[0] = dim - d;
1324: PetscCall(PetscDTEnumSubset(d - 1, formDegree, f, &form_atoms[1]));
1325: for (PetscInt i = 0; i < formDegree; i++) form_atoms[1 + i] += form_atoms[0] + 1;
1326: PetscInt f_ind; // index of the resulting form
1327: PetscCall(PetscDTSubsetIndex(dim, formDegree + 1, form_atoms, &f_ind));
1328: PetscReal *p_f = &p[total++ * Nf * Nk * npoints];
1329: for (PetscInt nz = 0; nz < nnz; nz++) {
1330: PetscInt i = pattern[nz][0]; // formDegree component
1331: PetscInt j = pattern[nz][1]; // (formDegree + 1) component
1332: PetscInt v = pattern[nz][2]; // coordinate component
1333: PetscReal scale = v < 0 ? -1. : 1.;
1335: i = formNegative ? (Nf - 1 - i) : i;
1336: scale = (formNegative && (i & 1)) ? -scale : scale;
1337: v = v < 0 ? -(v + 1) : v;
1338: if (j != f_ind) continue;
1339: PetscReal *p_i = &p_f[i * Nk * npoints];
1340: for (PetscInt jet = 0; jet < Nk; jet++) {
1341: const PetscReal *h_jet = &h_s[jet * npoints];
1342: PetscReal *p_jet = &p_i[jet * npoints];
1344: for (PetscInt pt = 0; pt < npoints; pt++) p_jet[pt] += scale * h_jet[pt] * (points[pt * dim + v] - centroid);
1345: PetscCall(PetscDTIndexToGradedOrder(dim, jet, deriv));
1346: deriv[v]++;
1347: PetscReal mult = deriv[v];
1348: PetscInt l;
1349: PetscCall(PetscDTGradedOrderToIndex(dim, deriv, &l));
1350: if (l >= Nk) continue;
1351: p_jet = &p_i[l * npoints];
1352: for (PetscInt pt = 0; pt < npoints; pt++) p_jet[pt] += scale * mult * h_jet[pt];
1353: deriv[v]--;
1354: }
1355: }
1356: }
1357: }
1358: }
1359: PetscCheck(total == Nbpt, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Incorrectly counted P trimmed polynomials");
1360: PetscCall(PetscFree(deriv));
1361: PetscCall(PetscFree(pattern));
1362: PetscCall(PetscFree(form_atoms));
1363: PetscCall(PetscFree(p_scalar));
1364: PetscFunctionReturn(PETSC_SUCCESS);
1365: }
1367: /*@
1368: PetscDTPTrimmedEvalJet - Evaluate the jet (function and derivatives) of a basis of the trimmed polynomial k-forms up to
1369: a given degree.
1371: Input Parameters:
1372: + dim - the number of variables in the multivariate polynomials
1373: . npoints - the number of points to evaluate the polynomials at
1374: . points - [npoints x dim] array of point coordinates
1375: . degree - the degree (sum of degrees on the variables in a monomial) of the trimmed polynomial space to evaluate.
1376: There are ((dim + degree) choose (dim + formDegree)) x ((degree + formDegree - 1) choose (formDegree)) polynomials in this space.
1377: (You can use `PetscDTPTrimmedSize()` to compute this size.)
1378: . formDegree - the degree of the form
1379: - jetDegree - the maximum order partial derivative to evaluate in the jet. There are ((dim + jetDegree) choose dim) partial derivatives
1380: in the jet. Choosing jetDegree = 0 means to evaluate just the function and no derivatives
1382: Output Parameter:
1383: . p - an array containing the evaluations of the PKD polynomials' jets on the points.
1385: Level: advanced
1387: Notes:
1388: The size of `p` is `PetscDTPTrimmedSize()` x ((dim + formDegree) choose dim) x ((dim + k)
1389: choose dim) x npoints,which also describes the order of the dimensions of this
1390: four-dimensional array\:
1392: the first (slowest varying) dimension is basis function index;
1393: the second dimension is component of the form;
1394: the third dimension is jet index;
1395: the fourth (fastest varying) dimension is the index of the evaluation point.
1397: The ordering of the basis functions is not graded, so the basis functions are not nested by degree like `PetscDTPKDEvalJet()`.
1398: The basis functions are not an L2-orthonormal basis on any particular domain.
1400: The implementation is based on the description of the trimmed polynomials up to degree r as
1401: the direct sum of polynomials up to degree (r-1) and the Koszul differential applied to
1402: homogeneous polynomials of degree (r-1).
1404: .seealso: `PetscDTPKDEvalJet()`, `PetscDTPTrimmedSize()`
1405: @*/
1406: PetscErrorCode PetscDTPTrimmedEvalJet(PetscInt dim, PetscInt npoints, const PetscReal points[], PetscInt degree, PetscInt formDegree, PetscInt jetDegree, PetscReal p[])
1407: {
1408: PetscFunctionBegin;
1409: PetscCall(PetscDTPTrimmedEvalJet_Internal(dim, npoints, points, degree, formDegree, jetDegree, p));
1410: PetscFunctionReturn(PETSC_SUCCESS);
1411: }
1413: /* solve the symmetric tridiagonal eigenvalue system, writing the eigenvalues into eigs and the eigenvectors into V
1414: * with lds n; diag and subdiag are overwritten */
1415: static PetscErrorCode PetscDTSymmetricTridiagonalEigensolve(PetscInt n, PetscReal diag[], PetscReal subdiag[], PetscReal eigs[], PetscScalar V[])
1416: {
1417: char jobz = 'V'; /* eigenvalues and eigenvectors */
1418: char range = 'A'; /* all eigenvalues will be found */
1419: PetscReal VL = 0.; /* ignored because range is 'A' */
1420: PetscReal VU = 0.; /* ignored because range is 'A' */
1421: PetscBLASInt IL = 0; /* ignored because range is 'A' */
1422: PetscBLASInt IU = 0; /* ignored because range is 'A' */
1423: PetscReal abstol = 0.; /* unused */
1424: PetscBLASInt bn, bm, ldz; /* bm will equal bn on exit */
1425: PetscBLASInt *isuppz;
1426: PetscBLASInt lwork, liwork;
1427: PetscReal workquery;
1428: PetscBLASInt iworkquery;
1429: PetscBLASInt *iwork;
1430: PetscReal *work = NULL;
1432: PetscFunctionBegin;
1433: #if !defined(PETSCDTGAUSSIANQUADRATURE_EIG)
1434: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP_SYS, "A LAPACK symmetric tridiagonal eigensolver could not be found");
1435: #endif
1436: PetscCall(PetscBLASIntCast(n, &bn));
1437: PetscCall(PetscBLASIntCast(n, &ldz));
1438: #if !PetscDefined(MISSING_LAPACK_STEGR)
1439: PetscCall(PetscMalloc1(2 * n, &isuppz));
1440: lwork = -1;
1441: liwork = -1;
1442: PetscCallLAPACKInfo("LAPACKstegr", LAPACKstegr_(&jobz, &range, &bn, diag, subdiag, &VL, &VU, &IL, &IU, &abstol, &bm, eigs, V, &ldz, isuppz, &workquery, &lwork, &iworkquery, &liwork, &info));
1443: lwork = (PetscBLASInt)workquery;
1444: liwork = iworkquery;
1445: PetscCall(PetscMalloc2(lwork, &work, liwork, &iwork));
1446: PetscCall(PetscFPTrapPush(PETSC_FP_TRAP_OFF));
1447: PetscCallLAPACKInfo("LAPACKstegr", LAPACKstegr_(&jobz, &range, &bn, diag, subdiag, &VL, &VU, &IL, &IU, &abstol, &bm, eigs, V, &ldz, isuppz, work, &lwork, iwork, &liwork, &info));
1448: PetscCall(PetscFPTrapPop());
1449: PetscCall(PetscFree2(work, iwork));
1450: PetscCall(PetscFree(isuppz));
1451: #elif !PetscDefined(MISSING_LAPACK_STEQR)
1452: jobz = 'I'; /* Compute eigenvalues and eigenvectors of the
1453: tridiagonal matrix. Z is initialized to the identity
1454: matrix. */
1455: PetscCall(PetscMalloc1(PetscMax(1, 2 * n - 2), &work));
1456: PetscCallLAPACKInfo("LAPACKsteqr", LAPACKsteqr_("I", &bn, diag, subdiag, V, &ldz, work, &info));
1457: PetscCall(PetscFPTrapPop());
1458: PetscCall(PetscFree(work));
1459: PetscCall(PetscArraycpy(eigs, diag, n));
1460: #endif
1461: PetscFunctionReturn(PETSC_SUCCESS);
1462: }
1464: /* Formula for the weights at the endpoints (-1 and 1) of Gauss-Lobatto-Jacobi
1465: * quadrature rules on the interval [-1, 1] */
1466: static PetscErrorCode PetscDTGaussLobattoJacobiEndweights_Internal(PetscInt n, PetscReal alpha, PetscReal beta, PetscReal *leftw, PetscReal *rightw)
1467: {
1468: PetscReal twoab1;
1469: PetscInt m = n - 2;
1470: PetscReal a = alpha + 1.;
1471: PetscReal b = beta + 1.;
1472: PetscReal gra, grb;
1474: PetscFunctionBegin;
1475: twoab1 = PetscPowReal(2., a + b - 1.);
1476: #if PetscDefined(HAVE_LGAMMA)
1477: grb = PetscExpReal(2. * PetscLGamma(b + 1.) + PetscLGamma(m + 1.) + PetscLGamma(m + a + 1.) - (PetscLGamma(m + b + 1) + PetscLGamma(m + a + b + 1.)));
1478: gra = PetscExpReal(2. * PetscLGamma(a + 1.) + PetscLGamma(m + 1.) + PetscLGamma(m + b + 1.) - (PetscLGamma(m + a + 1) + PetscLGamma(m + a + b + 1.)));
1479: #else
1480: {
1481: PetscReal binom1, binom2;
1482: PetscInt alphai = (PetscInt)alpha;
1483: PetscInt betai = (PetscInt)beta;
1485: PetscCheck((PetscReal)alphai == alpha && (PetscReal)betai == beta, PETSC_COMM_SELF, PETSC_ERR_SUP, "lgamma() - math routine is unavailable.");
1486: PetscCall(PetscDTBinomial(m + b, b, &binom1));
1487: PetscCall(PetscDTBinomial(m + a + b, b, &binom2));
1488: grb = 1. / (binom1 * binom2);
1489: PetscCall(PetscDTBinomial(m + a, a, &binom1));
1490: PetscCall(PetscDTBinomial(m + a + b, a, &binom2));
1491: gra = 1. / (binom1 * binom2);
1492: }
1493: #endif
1494: *leftw = twoab1 * grb / b;
1495: *rightw = twoab1 * gra / a;
1496: PetscFunctionReturn(PETSC_SUCCESS);
1497: }
1499: /* Evaluates the nth jacobi polynomial with weight parameters a,b at a point x.
1500: Recurrence relations implemented from the pseudocode given in Karniadakis and Sherwin, Appendix B */
1501: static inline PetscErrorCode PetscDTComputeJacobi(PetscReal a, PetscReal b, PetscInt n, PetscReal x, PetscReal *P)
1502: {
1503: PetscReal pn1, pn2;
1504: PetscReal cnm1, cnm1x, cnm2;
1506: PetscFunctionBegin;
1507: if (!n) {
1508: *P = 1.0;
1509: PetscFunctionReturn(PETSC_SUCCESS);
1510: }
1511: PetscDTJacobiRecurrence_Internal(1, a, b, cnm1, cnm1x, cnm2);
1512: pn2 = 1.;
1513: pn1 = cnm1 + cnm1x * x;
1514: if (n == 1) {
1515: *P = pn1;
1516: PetscFunctionReturn(PETSC_SUCCESS);
1517: }
1518: *P = 0.0;
1519: for (PetscInt k = 2; k < n + 1; ++k) {
1520: PetscDTJacobiRecurrence_Internal(k, a, b, cnm1, cnm1x, cnm2);
1522: *P = (cnm1 + cnm1x * x) * pn1 - cnm2 * pn2;
1523: pn2 = pn1;
1524: pn1 = *P;
1525: }
1526: PetscFunctionReturn(PETSC_SUCCESS);
1527: }
1529: /* Evaluates the first derivative of P_{n}^{a,b} at a point x. */
1530: static inline PetscErrorCode PetscDTComputeJacobiDerivative(PetscReal a, PetscReal b, PetscInt n, PetscReal x, PetscInt k, PetscReal *P)
1531: {
1532: PetscReal nP;
1533: PetscInt i;
1535: PetscFunctionBegin;
1536: *P = 0.0;
1537: if (k > n) PetscFunctionReturn(PETSC_SUCCESS);
1538: PetscCall(PetscDTComputeJacobi(a + k, b + k, n - k, x, &nP));
1539: for (i = 0; i < k; i++) nP *= (a + b + n + 1. + i) * 0.5;
1540: *P = nP;
1541: PetscFunctionReturn(PETSC_SUCCESS);
1542: }
1544: static PetscErrorCode PetscDTGaussJacobiQuadrature_Newton_Internal(PetscInt npoints, PetscReal a, PetscReal b, PetscReal x[], PetscReal w[])
1545: {
1546: PetscInt maxIter = 100;
1547: PetscReal eps = PetscExpReal(0.75 * PetscLogReal(PETSC_MACHINE_EPSILON));
1548: PetscReal a1, a6, gf;
1550: PetscFunctionBegin;
1551: a1 = PetscPowReal(2.0, a + b + 1);
1552: #if PetscDefined(HAVE_LGAMMA)
1553: {
1554: PetscReal a2, a3, a4, a5;
1555: a2 = PetscLGamma(a + npoints + 1);
1556: a3 = PetscLGamma(b + npoints + 1);
1557: a4 = PetscLGamma(a + b + npoints + 1);
1558: a5 = PetscLGamma(npoints + 1);
1559: gf = PetscExpReal(a2 + a3 - (a4 + a5));
1560: }
1561: #else
1562: {
1563: PetscInt ia, ib;
1565: ia = (PetscInt)a;
1566: ib = (PetscInt)b;
1567: gf = 1.;
1568: if (ia == a && ia >= 0) { /* compute ratio of rising factorals wrt a */
1569: for (PetscInt k = 0; k < ia; k++) gf *= (npoints + 1. + k) / (npoints + b + 1. + k);
1570: } else if (b == b && ib >= 0) { /* compute ratio of rising factorials wrt b */
1571: for (PetscInt k = 0; k < ib; k++) gf *= (npoints + 1. + k) / (npoints + a + 1. + k);
1572: } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "lgamma() - math routine is unavailable.");
1573: }
1574: #endif
1576: a6 = a1 * gf;
1577: /* Computes the m roots of P_{m}^{a,b} on [-1,1] by Newton's method with Chebyshev points as initial guesses.
1578: Algorithm implemented from the pseudocode given by Karniadakis and Sherwin and Python in FIAT */
1579: for (PetscInt k = 0; k < npoints; ++k) {
1580: PetscReal r = PetscCosReal(PETSC_PI * (1. - (4. * k + 3. + 2. * b) / (4. * npoints + 2. * (a + b + 1.)))), dP;
1582: if (k > 0) r = 0.5 * (r + x[k - 1]);
1583: for (PetscInt j = 0; j < maxIter; ++j) {
1584: PetscReal s = 0.0, delta, f, fp;
1585: PetscInt i;
1587: for (i = 0; i < k; ++i) s = s + 1.0 / (r - x[i]);
1588: PetscCall(PetscDTComputeJacobi(a, b, npoints, r, &f));
1589: PetscCall(PetscDTComputeJacobiDerivative(a, b, npoints, r, 1, &fp));
1590: delta = f / (fp - f * s);
1591: r = r - delta;
1592: if (PetscAbsReal(delta) < eps) break;
1593: }
1594: x[k] = r;
1595: PetscCall(PetscDTComputeJacobiDerivative(a, b, npoints, x[k], 1, &dP));
1596: w[k] = a6 / (1.0 - PetscSqr(x[k])) / PetscSqr(dP);
1597: }
1598: PetscFunctionReturn(PETSC_SUCCESS);
1599: }
1601: /* Compute the diagonals of the Jacobi matrix used in Golub & Welsch algorithms for Gauss-Jacobi
1602: * quadrature weight calculations on [-1,1] for exponents (1. + x)^a (1.-x)^b */
1603: static PetscErrorCode PetscDTJacobiMatrix_Internal(PetscInt nPoints, PetscReal a, PetscReal b, PetscReal *d, PetscReal *s)
1604: {
1605: PetscInt i;
1607: PetscFunctionBegin;
1608: for (i = 0; i < nPoints; i++) {
1609: PetscReal A, B, C;
1611: PetscDTJacobiRecurrence_Internal(i + 1, a, b, A, B, C);
1612: d[i] = -A / B;
1613: if (i) s[i - 1] *= C / B;
1614: if (i < nPoints - 1) s[i] = 1. / B;
1615: }
1616: PetscFunctionReturn(PETSC_SUCCESS);
1617: }
1619: static PetscErrorCode PetscDTGaussJacobiQuadrature_GolubWelsch_Internal(PetscInt npoints, PetscReal a, PetscReal b, PetscReal *x, PetscReal *w)
1620: {
1621: PetscReal mu0;
1622: PetscReal ga, gb, gab;
1623: PetscInt i;
1625: PetscFunctionBegin;
1626: PetscCall(PetscCitationsRegister(GolubWelschCitation, &GolubWelschCite));
1628: #if PetscDefined(HAVE_TGAMMA)
1629: ga = PetscTGamma(a + 1);
1630: gb = PetscTGamma(b + 1);
1631: gab = PetscTGamma(a + b + 2);
1632: #else
1633: {
1634: PetscInt ia = (PetscInt)a, ib = (PetscInt)b;
1636: PetscCheck(ia == a && ib == b && ia + 1 > 0 && ib + 1 > 0 && ia + ib + 2 > 0, PETSC_COMM_SELF, PETSC_ERR_SUP, "tgamma() - math routine is unavailable.");
1637: /* All gamma(x) terms are (x-1)! terms */
1638: PetscCall(PetscDTFactorial(ia, &ga));
1639: PetscCall(PetscDTFactorial(ib, &gb));
1640: PetscCall(PetscDTFactorial(ia + ib + 1, &gab));
1641: }
1642: #endif
1643: mu0 = PetscPowReal(2., a + b + 1.) * ga * gb / gab;
1645: #if defined(PETSCDTGAUSSIANQUADRATURE_EIG)
1646: {
1647: PetscReal *diag, *subdiag;
1648: PetscScalar *V;
1650: PetscCall(PetscMalloc2(npoints, &diag, npoints, &subdiag));
1651: PetscCall(PetscMalloc1(npoints * npoints, &V));
1652: PetscCall(PetscDTJacobiMatrix_Internal(npoints, a, b, diag, subdiag));
1653: for (i = 0; i < npoints - 1; i++) subdiag[i] = PetscSqrtReal(subdiag[i]);
1654: PetscCall(PetscDTSymmetricTridiagonalEigensolve(npoints, diag, subdiag, x, V));
1655: for (i = 0; i < npoints; i++) w[i] = PetscSqr(PetscRealPart(V[i * npoints])) * mu0;
1656: PetscCall(PetscFree(V));
1657: PetscCall(PetscFree2(diag, subdiag));
1658: }
1659: #else
1660: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP_SYS, "A LAPACK symmetric tridiagonal eigensolver could not be found");
1661: #endif
1662: { /* As of March 2, 2020, The Sun Performance Library breaks the LAPACK contract for xstegr and xsteqr: the
1663: eigenvalues are not guaranteed to be in ascending order. So we heave a passive aggressive sigh and check that
1664: the eigenvalues are sorted */
1665: PetscBool sorted;
1667: PetscCall(PetscSortedReal(npoints, x, &sorted));
1668: if (!sorted) {
1669: PetscInt *order, i;
1670: PetscReal *tmp;
1672: PetscCall(PetscMalloc2(npoints, &order, npoints, &tmp));
1673: for (i = 0; i < npoints; i++) order[i] = i;
1674: PetscCall(PetscSortRealWithPermutation(npoints, x, order));
1675: PetscCall(PetscArraycpy(tmp, x, npoints));
1676: for (i = 0; i < npoints; i++) x[i] = tmp[order[i]];
1677: PetscCall(PetscArraycpy(tmp, w, npoints));
1678: for (i = 0; i < npoints; i++) w[i] = tmp[order[i]];
1679: PetscCall(PetscFree2(order, tmp));
1680: }
1681: }
1682: PetscFunctionReturn(PETSC_SUCCESS);
1683: }
1685: static PetscErrorCode PetscDTGaussJacobiQuadrature_Internal(PetscInt npoints, PetscReal alpha, PetscReal beta, PetscReal x[], PetscReal w[], PetscBool newton)
1686: {
1687: PetscFunctionBegin;
1688: PetscCheck(npoints >= 1, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Number of points must be positive");
1689: /* If asking for a 1D Lobatto point, just return the non-Lobatto 1D point */
1690: PetscCheck(alpha > -1., PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "alpha must be > -1.");
1691: PetscCheck(beta > -1., PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "beta must be > -1.");
1693: if (newton) PetscCall(PetscDTGaussJacobiQuadrature_Newton_Internal(npoints, alpha, beta, x, w));
1694: else PetscCall(PetscDTGaussJacobiQuadrature_GolubWelsch_Internal(npoints, alpha, beta, x, w));
1695: if (alpha == beta) { /* symmetrize */
1696: PetscInt i;
1697: for (i = 0; i < (npoints + 1) / 2; i++) {
1698: PetscInt j = npoints - 1 - i;
1699: PetscReal xi = x[i];
1700: PetscReal xj = x[j];
1701: PetscReal wi = w[i];
1702: PetscReal wj = w[j];
1704: x[i] = (xi - xj) / 2.;
1705: x[j] = (xj - xi) / 2.;
1706: w[i] = w[j] = (wi + wj) / 2.;
1707: }
1708: }
1709: PetscFunctionReturn(PETSC_SUCCESS);
1710: }
1712: /*@
1713: PetscDTGaussJacobiQuadrature - quadrature for the interval $[a, b]$ with the weight function
1714: $(x-a)^\alpha (x-b)^\beta$.
1716: Not Collective
1718: Input Parameters:
1719: + npoints - the number of points in the quadrature rule
1720: . a - the left endpoint of the interval
1721: . b - the right endpoint of the interval
1722: . alpha - the left exponent
1723: - beta - the right exponent
1725: Output Parameters:
1726: + x - array of length `npoints`, the locations of the quadrature points
1727: - w - array of length `npoints`, the weights of the quadrature points
1729: Level: intermediate
1731: Note:
1732: This quadrature rule is exact for polynomials up to degree 2*`npoints` - 1.
1734: .seealso: `PetscDTGaussQuadrature()`
1735: @*/
1736: PetscErrorCode PetscDTGaussJacobiQuadrature(PetscInt npoints, PetscReal a, PetscReal b, PetscReal alpha, PetscReal beta, PetscReal x[], PetscReal w[])
1737: {
1738: PetscInt i;
1740: PetscFunctionBegin;
1741: PetscCall(PetscDTGaussJacobiQuadrature_Internal(npoints, alpha, beta, x, w, PetscDTGaussQuadratureNewton_Internal));
1742: if (a != -1. || b != 1.) { /* shift */
1743: for (i = 0; i < npoints; i++) {
1744: x[i] = (x[i] + 1.) * ((b - a) / 2.) + a;
1745: w[i] *= (b - a) / 2.;
1746: }
1747: }
1748: PetscFunctionReturn(PETSC_SUCCESS);
1749: }
1751: static PetscErrorCode PetscDTGaussLobattoJacobiQuadrature_Internal(PetscInt npoints, PetscReal alpha, PetscReal beta, PetscReal x[], PetscReal w[], PetscBool newton)
1752: {
1753: PetscFunctionBegin;
1754: PetscCheck(npoints >= 2, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Number of points must be positive");
1755: /* If asking for a 1D Lobatto point, just return the non-Lobatto 1D point */
1756: PetscCheck(alpha > -1., PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "alpha must be > -1.");
1757: PetscCheck(beta > -1., PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "beta must be > -1.");
1759: x[0] = -1.;
1760: x[npoints - 1] = 1.;
1761: if (npoints > 2) PetscCall(PetscDTGaussJacobiQuadrature_Internal(npoints - 2, alpha + 1., beta + 1., &x[1], &w[1], newton));
1762: for (PetscInt i = 1; i < npoints - 1; i++) w[i] /= (1. - x[i] * x[i]);
1763: PetscCall(PetscDTGaussLobattoJacobiEndweights_Internal(npoints, alpha, beta, &w[0], &w[npoints - 1]));
1764: PetscFunctionReturn(PETSC_SUCCESS);
1765: }
1767: /*@
1768: PetscDTGaussLobattoJacobiQuadrature - quadrature for the interval $[a, b]$ with the weight function
1769: $(x-a)^\alpha (x-b)^\beta$, with endpoints `a` and `b` included as quadrature points.
1771: Not Collective
1773: Input Parameters:
1774: + npoints - the number of points in the quadrature rule
1775: . a - the left endpoint of the interval
1776: . b - the right endpoint of the interval
1777: . alpha - the left exponent
1778: - beta - the right exponent
1780: Output Parameters:
1781: + x - array of length `npoints`, the locations of the quadrature points
1782: - w - array of length `npoints`, the weights of the quadrature points
1784: Level: intermediate
1786: Note:
1787: This quadrature rule is exact for polynomials up to degree 2*`npoints` - 3.
1789: .seealso: `PetscDTGaussJacobiQuadrature()`
1790: @*/
1791: PetscErrorCode PetscDTGaussLobattoJacobiQuadrature(PetscInt npoints, PetscReal a, PetscReal b, PetscReal alpha, PetscReal beta, PetscReal x[], PetscReal w[])
1792: {
1793: PetscFunctionBegin;
1794: PetscCall(PetscDTGaussLobattoJacobiQuadrature_Internal(npoints, alpha, beta, x, w, PetscDTGaussQuadratureNewton_Internal));
1795: if (a != -1. || b != 1.) { /* shift */
1796: for (PetscInt i = 0; i < npoints; i++) {
1797: x[i] = (x[i] + 1.) * ((b - a) / 2.) + a;
1798: w[i] *= (b - a) / 2.;
1799: }
1800: }
1801: PetscFunctionReturn(PETSC_SUCCESS);
1802: }
1804: /*@
1805: PetscDTGaussQuadrature - create Gauss-Legendre quadrature
1807: Not Collective
1809: Input Parameters:
1810: + npoints - number of points
1811: . a - left end of interval (often-1)
1812: - b - right end of interval (often +1)
1814: Output Parameters:
1815: + x - quadrature points
1816: - w - quadrature weights
1818: Level: intermediate
1820: Note:
1821: See {cite}`golub1969calculation`
1823: .seealso: `PetscDTLegendreEval()`, `PetscDTGaussJacobiQuadrature()`
1824: @*/
1825: PetscErrorCode PetscDTGaussQuadrature(PetscInt npoints, PetscReal a, PetscReal b, PetscReal x[], PetscReal w[])
1826: {
1827: PetscFunctionBegin;
1828: PetscCall(PetscDTGaussJacobiQuadrature_Internal(npoints, 0., 0., x, w, PetscDTGaussQuadratureNewton_Internal));
1829: if (a != -1. || b != 1.) { /* shift */
1830: for (PetscInt i = 0; i < npoints; i++) {
1831: x[i] = (x[i] + 1.) * ((b - a) / 2.) + a;
1832: w[i] *= (b - a) / 2.;
1833: }
1834: }
1835: PetscFunctionReturn(PETSC_SUCCESS);
1836: }
1838: /*@
1839: PetscDTGaussLobattoLegendreQuadrature - creates a set of the locations and weights of the Gauss-Lobatto-Legendre
1840: nodes of a given size on the domain $[-1,1]$
1842: Not Collective
1844: Input Parameters:
1845: + npoints - number of grid nodes
1846: - type - `PETSCGAUSSLOBATTOLEGENDRE_VIA_LINEAR_ALGEBRA` or `PETSCGAUSSLOBATTOLEGENDRE_VIA_NEWTON`
1848: Output Parameters:
1849: + x - quadrature points, pass in an array of length `npoints`
1850: - w - quadrature weights, pass in an array of length `npoints`
1852: Level: intermediate
1854: Notes:
1855: For n > 30 the Newton approach computes duplicate (incorrect) values for some nodes because the initial guess is apparently not
1856: close enough to the desired solution
1858: These are useful for implementing spectral methods based on Gauss-Lobatto-Legendre (GLL) nodes
1860: See <https://epubs.siam.org/doi/abs/10.1137/110855442> <https://epubs.siam.org/doi/abs/10.1137/120889873> for better ways to compute GLL nodes
1862: .seealso: `PetscDTGaussQuadrature()`, `PetscGaussLobattoLegendreCreateType`
1863: @*/
1864: PetscErrorCode PetscDTGaussLobattoLegendreQuadrature(PetscInt npoints, PetscGaussLobattoLegendreCreateType type, PetscReal x[], PetscReal w[])
1865: {
1866: PetscBool newton;
1868: PetscFunctionBegin;
1869: PetscCheck(npoints >= 2, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Must provide at least 2 grid points per element");
1870: newton = (PetscBool)(type == PETSCGAUSSLOBATTOLEGENDRE_VIA_NEWTON);
1871: PetscCall(PetscDTGaussLobattoJacobiQuadrature_Internal(npoints, 0., 0., x, w, newton));
1872: PetscFunctionReturn(PETSC_SUCCESS);
1873: }
1875: /*@
1876: PetscDTGaussTensorQuadrature - creates a tensor-product Gauss quadrature
1878: Not Collective
1880: Input Parameters:
1881: + dim - The spatial dimension
1882: . Nc - The number of components
1883: . npoints - number of points in one dimension
1884: . a - left end of interval (often-1)
1885: - b - right end of interval (often +1)
1887: Output Parameter:
1888: . q - A `PetscQuadrature` object
1890: Level: intermediate
1892: .seealso: `PetscDTGaussQuadrature()`, `PetscDTLegendreEval()`
1893: @*/
1894: PetscErrorCode PetscDTGaussTensorQuadrature(PetscInt dim, PetscInt Nc, PetscInt npoints, PetscReal a, PetscReal b, PetscQuadrature *q)
1895: {
1896: DMPolytopeType ct;
1897: PetscInt totpoints = dim > 1 ? dim > 2 ? npoints * PetscSqr(npoints) : PetscSqr(npoints) : npoints;
1898: PetscReal *x, *w, *xw, *ww;
1900: PetscFunctionBegin;
1901: PetscCall(PetscMalloc1(totpoints * dim, &x));
1902: PetscCall(PetscMalloc1(totpoints * Nc, &w));
1903: /* Set up the Golub-Welsch system */
1904: switch (dim) {
1905: case 0:
1906: ct = DM_POLYTOPE_POINT;
1907: PetscCall(PetscFree(x));
1908: PetscCall(PetscFree(w));
1909: PetscCall(PetscMalloc1(1, &x));
1910: PetscCall(PetscMalloc1(Nc, &w));
1911: totpoints = 1;
1912: x[0] = 0.0;
1913: for (PetscInt c = 0; c < Nc; ++c) w[c] = 1.0;
1914: break;
1915: case 1:
1916: ct = DM_POLYTOPE_SEGMENT;
1917: PetscCall(PetscMalloc1(npoints, &ww));
1918: PetscCall(PetscDTGaussQuadrature(npoints, a, b, x, ww));
1919: for (PetscInt i = 0; i < npoints; ++i)
1920: for (PetscInt c = 0; c < Nc; ++c) w[i * Nc + c] = ww[i];
1921: PetscCall(PetscFree(ww));
1922: break;
1923: case 2:
1924: ct = DM_POLYTOPE_QUADRILATERAL;
1925: PetscCall(PetscMalloc2(npoints, &xw, npoints, &ww));
1926: PetscCall(PetscDTGaussQuadrature(npoints, a, b, xw, ww));
1927: for (PetscInt i = 0; i < npoints; ++i) {
1928: for (PetscInt j = 0; j < npoints; ++j) {
1929: x[(i * npoints + j) * dim + 0] = xw[i];
1930: x[(i * npoints + j) * dim + 1] = xw[j];
1931: for (PetscInt c = 0; c < Nc; ++c) w[(i * npoints + j) * Nc + c] = ww[i] * ww[j];
1932: }
1933: }
1934: PetscCall(PetscFree2(xw, ww));
1935: break;
1936: case 3:
1937: ct = DM_POLYTOPE_HEXAHEDRON;
1938: PetscCall(PetscMalloc2(npoints, &xw, npoints, &ww));
1939: PetscCall(PetscDTGaussQuadrature(npoints, a, b, xw, ww));
1940: for (PetscInt i = 0; i < npoints; ++i) {
1941: for (PetscInt j = 0; j < npoints; ++j) {
1942: for (PetscInt k = 0; k < npoints; ++k) {
1943: x[((i * npoints + j) * npoints + k) * dim + 0] = xw[i];
1944: x[((i * npoints + j) * npoints + k) * dim + 1] = xw[j];
1945: x[((i * npoints + j) * npoints + k) * dim + 2] = xw[k];
1946: for (PetscInt c = 0; c < Nc; ++c) w[((i * npoints + j) * npoints + k) * Nc + c] = ww[i] * ww[j] * ww[k];
1947: }
1948: }
1949: }
1950: PetscCall(PetscFree2(xw, ww));
1951: break;
1952: default:
1953: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Cannot construct quadrature rule for dimension %" PetscInt_FMT, dim);
1954: }
1955: PetscCall(PetscQuadratureCreate(PETSC_COMM_SELF, q));
1956: PetscCall(PetscQuadratureSetCellType(*q, ct));
1957: PetscCall(PetscQuadratureSetOrder(*q, 2 * npoints - 1));
1958: PetscCall(PetscQuadratureSetData(*q, dim, Nc, totpoints, x, w));
1959: PetscCall(PetscObjectChangeTypeName((PetscObject)*q, "GaussTensor"));
1960: PetscFunctionReturn(PETSC_SUCCESS);
1961: }
1963: /*@
1964: PetscDTStroudConicalQuadrature - create Stroud conical quadrature for a simplex {cite}`karniadakis2005spectral`
1966: Not Collective
1968: Input Parameters:
1969: + dim - The simplex dimension
1970: . Nc - The number of components
1971: . npoints - The number of points in one dimension
1972: . a - left end of interval (often-1)
1973: - b - right end of interval (often +1)
1975: Output Parameter:
1976: . q - A `PetscQuadrature` object
1978: Level: intermediate
1980: Note:
1981: For `dim` == 1, this is Gauss-Legendre quadrature
1983: .seealso: `PetscDTGaussTensorQuadrature()`, `PetscDTGaussQuadrature()`
1984: @*/
1985: PetscErrorCode PetscDTStroudConicalQuadrature(PetscInt dim, PetscInt Nc, PetscInt npoints, PetscReal a, PetscReal b, PetscQuadrature *q)
1986: {
1987: DMPolytopeType ct;
1988: PetscInt totpoints;
1989: PetscReal *p1, *w1;
1990: PetscReal *x, *w;
1992: PetscFunctionBegin;
1993: PetscCheck(!(a != -1.0) && !(b != 1.0), PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Must use default internal right now");
1994: switch (dim) {
1995: case 0:
1996: ct = DM_POLYTOPE_POINT;
1997: break;
1998: case 1:
1999: ct = DM_POLYTOPE_SEGMENT;
2000: break;
2001: case 2:
2002: ct = DM_POLYTOPE_TRIANGLE;
2003: break;
2004: case 3:
2005: ct = DM_POLYTOPE_TETRAHEDRON;
2006: break;
2007: default:
2008: ct = DM_POLYTOPE_UNKNOWN;
2009: }
2010: totpoints = 1;
2011: for (PetscInt i = 0; i < dim; ++i) totpoints *= npoints;
2012: PetscCall(PetscMalloc1(totpoints * dim, &x));
2013: PetscCall(PetscMalloc1(totpoints * Nc, &w));
2014: PetscCall(PetscMalloc2(npoints, &p1, npoints, &w1));
2015: for (PetscInt i = 0; i < totpoints * Nc; ++i) w[i] = 1.;
2016: for (PetscInt i = 0, totprev = 1, totrem = totpoints / npoints; i < dim; ++i) {
2017: PetscReal mul;
2019: mul = PetscPowReal(2., -i);
2020: PetscCall(PetscDTGaussJacobiQuadrature(npoints, -1., 1., i, 0.0, p1, w1));
2021: for (PetscInt pt = 0, l = 0; l < totprev; l++) {
2022: for (PetscInt j = 0; j < npoints; j++) {
2023: for (PetscInt m = 0; m < totrem; m++, pt++) {
2024: for (PetscInt k = 0; k < i; k++) x[pt * dim + k] = (x[pt * dim + k] + 1.) * (1. - p1[j]) * 0.5 - 1.;
2025: x[pt * dim + i] = p1[j];
2026: for (PetscInt c = 0; c < Nc; c++) w[pt * Nc + c] *= mul * w1[j];
2027: }
2028: }
2029: }
2030: totprev *= npoints;
2031: totrem /= npoints;
2032: }
2033: PetscCall(PetscFree2(p1, w1));
2034: PetscCall(PetscQuadratureCreate(PETSC_COMM_SELF, q));
2035: PetscCall(PetscQuadratureSetCellType(*q, ct));
2036: PetscCall(PetscQuadratureSetOrder(*q, 2 * npoints - 1));
2037: PetscCall(PetscQuadratureSetData(*q, dim, Nc, totpoints, x, w));
2038: PetscCall(PetscObjectChangeTypeName((PetscObject)*q, "StroudConical"));
2039: PetscFunctionReturn(PETSC_SUCCESS);
2040: }
2042: static PetscBool MinSymTriQuadCite = PETSC_FALSE;
2043: const char MinSymTriQuadCitation[] = "@article{WitherdenVincent2015,\n"
2044: " title = {On the identification of symmetric quadrature rules for finite element methods},\n"
2045: " journal = {Computers & Mathematics with Applications},\n"
2046: " volume = {69},\n"
2047: " number = {10},\n"
2048: " pages = {1232-1241},\n"
2049: " year = {2015},\n"
2050: " issn = {0898-1221},\n"
2051: " doi = {10.1016/j.camwa.2015.03.017},\n"
2052: " url = {https://www.sciencedirect.com/science/article/pii/S0898122115001224},\n"
2053: " author = {F.D. Witherden and P.E. Vincent},\n"
2054: "}\n";
2056: #include "petscdttriquadrules.h"
2058: static PetscBool MinSymTetQuadCite = PETSC_FALSE;
2059: const char MinSymTetQuadCitation[] = "@article{JaskowiecSukumar2021\n"
2060: " author = {Jaskowiec, Jan and Sukumar, N.},\n"
2061: " title = {High-order symmetric cubature rules for tetrahedra and pyramids},\n"
2062: " journal = {International Journal for Numerical Methods in Engineering},\n"
2063: " volume = {122},\n"
2064: " number = {1},\n"
2065: " pages = {148-171},\n"
2066: " doi = {10.1002/nme.6528},\n"
2067: " url = {https://onlinelibrary.wiley.com/doi/abs/10.1002/nme.6528},\n"
2068: " eprint = {https://onlinelibrary.wiley.com/doi/pdf/10.1002/nme.6528},\n"
2069: " year = {2021}\n"
2070: "}\n";
2072: #include "petscdttetquadrules.h"
2074: static PetscBool DiagSymTriQuadCite = PETSC_FALSE;
2075: const char DiagSymTriQuadCitation[] = "@article{KongMulderVeldhuizen1999,\n"
2076: " title = {Higher-order triangular and tetrahedral finite elements with mass lumping for solving the wave equation},\n"
2077: " journal = {Journal of Engineering Mathematics},\n"
2078: " volume = {35},\n"
2079: " number = {4},\n"
2080: " pages = {405--426},\n"
2081: " year = {1999},\n"
2082: " doi = {10.1023/A:1004420829610},\n"
2083: " url = {https://link.springer.com/article/10.1023/A:1004420829610},\n"
2084: " author = {MJS Chin-Joe-Kong and Wim A Mulder and Marinus Van Veldhuizen},\n"
2085: "}\n";
2087: #include "petscdttridiagquadrules.h"
2089: // https://en.wikipedia.org/wiki/Partition_(number_theory)
2090: static PetscErrorCode PetscDTPartitionNumber(PetscInt n, PetscInt *p)
2091: {
2092: // sequence A000041 in the OEIS
2093: const PetscInt partition[] = {1, 1, 2, 3, 5, 7, 11, 15, 22, 30, 42, 56, 77, 101, 135, 176, 231, 297, 385, 490, 627, 792, 1002, 1255, 1575, 1958, 2436, 3010, 3718, 4565, 5604};
2094: PetscInt tabulated_max = PETSC_STATIC_ARRAY_LENGTH(partition) - 1;
2096: PetscFunctionBegin;
2097: PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Partition number not defined for negative number %" PetscInt_FMT, n);
2098: // not implementing the pentagonal number recurrence, we don't need partition numbers for n that high
2099: PetscCheck(n <= tabulated_max, PETSC_COMM_SELF, PETSC_ERR_SUP, "Partition numbers only tabulated up to %" PetscInt_FMT ", not computed for %" PetscInt_FMT, tabulated_max, n);
2100: *p = partition[n];
2101: PetscFunctionReturn(PETSC_SUCCESS);
2102: }
2104: /*@
2105: PetscDTSimplexQuadrature - Create a quadrature rule for a simplex that exactly integrates polynomials up to a given degree.
2107: Not Collective
2109: Input Parameters:
2110: + dim - The spatial dimension of the simplex (1 = segment, 2 = triangle, 3 = tetrahedron)
2111: . degree - The largest polynomial degree that is required to be integrated exactly
2112: - type - `PetscDTSimplexQuadratureType` indicating the type of quadrature rule
2114: Output Parameter:
2115: . quad - A `PetscQuadrature` object for integration over the biunit simplex
2116: (defined by the bounds $x_i >= -1$ and $\sum_i x_i <= 2 - d$) that is exact for
2117: polynomials up to the given degree
2119: Level: intermediate
2121: .seealso: `PetscDTSimplexQuadratureType`, `PetscDTGaussQuadrature()`, `PetscDTStroudCononicalQuadrature()`, `PetscQuadrature`
2122: @*/
2123: PetscErrorCode PetscDTSimplexQuadrature(PetscInt dim, PetscInt degree, PetscDTSimplexQuadratureType type, PetscQuadrature *quad)
2124: {
2125: PetscDTSimplexQuadratureType orig_type = type;
2127: PetscFunctionBegin;
2128: PetscCheck(dim >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Negative dimension %" PetscInt_FMT, dim);
2129: PetscCheck(degree >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Negative degree %" PetscInt_FMT, degree);
2130: if (type == PETSCDTSIMPLEXQUAD_DEFAULT) type = PETSCDTSIMPLEXQUAD_MINSYM;
2131: if (type == PETSCDTSIMPLEXQUAD_CONIC || dim < 2) {
2132: PetscInt points_per_dim = (degree + 2) / 2; // ceil((degree + 1) / 2);
2133: PetscCall(PetscDTStroudConicalQuadrature(dim, 1, points_per_dim, -1, 1, quad));
2134: } else {
2135: DMPolytopeType ct;
2136: PetscInt n = dim + 1;
2137: PetscInt fact = 1;
2138: PetscInt *part, *perm;
2139: PetscInt p = 0;
2140: PetscInt max_degree;
2141: const PetscInt *nodes_per_type = NULL;
2142: const PetscInt *all_num_full_nodes = NULL;
2143: const PetscReal **weights_list = NULL;
2144: const PetscReal **compact_nodes_list = NULL;
2145: const char *citation = NULL;
2146: PetscBool *cited = NULL;
2148: switch (dim) {
2149: case 0:
2150: ct = DM_POLYTOPE_POINT;
2151: break;
2152: case 1:
2153: ct = DM_POLYTOPE_SEGMENT;
2154: break;
2155: case 2:
2156: ct = DM_POLYTOPE_TRIANGLE;
2157: break;
2158: case 3:
2159: ct = DM_POLYTOPE_TETRAHEDRON;
2160: break;
2161: default:
2162: ct = DM_POLYTOPE_UNKNOWN;
2163: }
2164: if (type == PETSCDTSIMPLEXQUAD_MINSYM) {
2165: switch (dim) {
2166: case 2:
2167: cited = &MinSymTriQuadCite;
2168: citation = MinSymTriQuadCitation;
2169: max_degree = PetscDTWVTriQuad_max_degree;
2170: nodes_per_type = PetscDTWVTriQuad_num_orbits;
2171: all_num_full_nodes = PetscDTWVTriQuad_num_nodes;
2172: weights_list = PetscDTWVTriQuad_weights;
2173: compact_nodes_list = PetscDTWVTriQuad_orbits;
2174: break;
2175: case 3:
2176: cited = &MinSymTetQuadCite;
2177: citation = MinSymTetQuadCitation;
2178: max_degree = PetscDTJSTetQuad_max_degree;
2179: nodes_per_type = PetscDTJSTetQuad_num_orbits;
2180: all_num_full_nodes = PetscDTJSTetQuad_num_nodes;
2181: weights_list = PetscDTJSTetQuad_weights;
2182: compact_nodes_list = PetscDTJSTetQuad_orbits;
2183: break;
2184: default:
2185: max_degree = -1;
2186: break;
2187: }
2188: } else {
2189: switch (dim) {
2190: case 2:
2191: cited = &DiagSymTriQuadCite;
2192: citation = DiagSymTriQuadCitation;
2193: max_degree = PetscDTKMVTriQuad_max_degree;
2194: nodes_per_type = PetscDTKMVTriQuad_num_orbits;
2195: all_num_full_nodes = PetscDTKMVTriQuad_num_nodes;
2196: weights_list = PetscDTKMVTriQuad_weights;
2197: compact_nodes_list = PetscDTKMVTriQuad_orbits;
2198: break;
2199: default:
2200: max_degree = -1;
2201: break;
2202: }
2203: }
2205: if (degree > max_degree) {
2206: PetscCheck(orig_type == PETSCDTSIMPLEXQUAD_DEFAULT, PETSC_COMM_SELF, PETSC_ERR_SUP, "%s symmetric quadrature for dim %" PetscInt_FMT ", degree %" PetscInt_FMT " unsupported", orig_type == PETSCDTSIMPLEXQUAD_MINSYM ? "Minimal" : "Diagonal", dim, degree);
2207: // fall back to conic
2208: PetscCall(PetscDTSimplexQuadrature(dim, degree, PETSCDTSIMPLEXQUAD_CONIC, quad));
2209: PetscFunctionReturn(PETSC_SUCCESS);
2210: }
2212: PetscCall(PetscCitationsRegister(citation, cited));
2214: PetscCall(PetscDTPartitionNumber(n, &p));
2215: for (PetscInt d = 2; d <= n; d++) fact *= d;
2217: PetscInt num_full_nodes = all_num_full_nodes[degree];
2218: const PetscReal *all_compact_nodes = compact_nodes_list[degree];
2219: const PetscReal *all_compact_weights = weights_list[degree];
2220: nodes_per_type = &nodes_per_type[p * degree];
2222: PetscReal *points;
2223: PetscReal *counts;
2224: PetscReal *weights;
2225: PetscReal *bary_to_biunit; // row-major transformation of barycentric coordinate to biunit
2226: PetscQuadrature q;
2228: // compute the transformation
2229: PetscCall(PetscMalloc1(n * dim, &bary_to_biunit));
2230: for (PetscInt d = 0; d < dim; d++) {
2231: for (PetscInt b = 0; b < n; b++) bary_to_biunit[d * n + b] = (d == b) ? 1.0 : -1.0;
2232: }
2234: PetscCall(PetscMalloc3(n, &part, n, &perm, n, &counts));
2235: PetscCall(PetscCalloc1(num_full_nodes * dim, &points));
2236: PetscCall(PetscMalloc1(num_full_nodes, &weights));
2238: // (0, 0, ...) is the first partition lexicographically
2239: PetscCall(PetscArrayzero(part, n));
2240: PetscCall(PetscArrayzero(counts, n));
2241: counts[0] = n;
2243: // for each partition
2244: for (PetscInt s = 0, node_offset = 0; s < p; s++) {
2245: PetscInt num_compact_coords = part[n - 1] + 1;
2247: const PetscReal *compact_nodes = all_compact_nodes;
2248: const PetscReal *compact_weights = all_compact_weights;
2249: all_compact_nodes += num_compact_coords * nodes_per_type[s];
2250: all_compact_weights += nodes_per_type[s];
2252: // for every permutation of the vertices
2253: for (PetscInt f = 0; f < fact; f++) {
2254: PetscCall(PetscDTEnumPerm(n, f, perm, NULL));
2256: // check if it is a valid permutation
2257: PetscInt digit;
2258: for (digit = 1; digit < n; digit++) {
2259: // skip permutations that would duplicate a node because it has a smaller symmetry group
2260: if (part[digit - 1] == part[digit] && perm[digit - 1] > perm[digit]) break;
2261: }
2262: if (digit < n) continue;
2264: // create full nodes from this permutation of the compact nodes
2265: PetscReal *full_nodes = &points[node_offset * dim];
2266: PetscReal *full_weights = &weights[node_offset];
2268: PetscCall(PetscArraycpy(full_weights, compact_weights, nodes_per_type[s]));
2269: for (PetscInt b = 0; b < n; b++) {
2270: for (PetscInt d = 0; d < dim; d++) {
2271: for (PetscInt node = 0; node < nodes_per_type[s]; node++) full_nodes[node * dim + d] += bary_to_biunit[d * n + perm[b]] * compact_nodes[node * num_compact_coords + part[b]];
2272: }
2273: }
2274: node_offset += nodes_per_type[s];
2275: }
2277: if (s < p - 1) { // Generate the next partition
2278: /* A partition is described by the number of coordinates that are in
2279: * each set of duplicates (counts) and redundantly by mapping each
2280: * index to its set of duplicates (part)
2281: *
2282: * Counts should always be in nonincreasing order
2283: *
2284: * We want to generate the partitions lexically by part, which means
2285: * finding the last index where count > 1 and reducing by 1.
2286: *
2287: * For the new counts beyond that index, we eagerly assign the remaining
2288: * capacity of the partition to smaller indices (ensures lexical ordering),
2289: * while respecting the nonincreasing invariant of the counts
2290: */
2291: PetscInt last_digit = part[n - 1];
2292: PetscInt last_digit_with_extra = last_digit;
2293: while (counts[last_digit_with_extra] == 1) last_digit_with_extra--;
2294: PetscInt limit = --counts[last_digit_with_extra];
2295: PetscInt total_to_distribute = last_digit - last_digit_with_extra + 1;
2296: for (PetscInt digit = last_digit_with_extra + 1; digit < n; digit++) {
2297: counts[digit] = PetscMin(limit, total_to_distribute);
2298: total_to_distribute -= PetscMin(limit, total_to_distribute);
2299: }
2300: for (PetscInt digit = 0, offset = 0; digit < n; digit++) {
2301: PetscInt count = counts[digit];
2302: for (PetscInt c = 0; c < count; c++) part[offset++] = digit;
2303: }
2304: }
2305: PetscCheck(node_offset <= num_full_nodes, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Node offset %" PetscInt_FMT " > %" PetscInt_FMT " number of nodes", node_offset, num_full_nodes);
2306: }
2307: PetscCall(PetscFree3(part, perm, counts));
2308: PetscCall(PetscFree(bary_to_biunit));
2309: PetscCall(PetscQuadratureCreate(PETSC_COMM_SELF, &q));
2310: PetscCall(PetscQuadratureSetCellType(q, ct));
2311: PetscCall(PetscQuadratureSetOrder(q, degree));
2312: PetscCall(PetscQuadratureSetData(q, dim, 1, num_full_nodes, points, weights));
2313: *quad = q;
2314: }
2315: PetscFunctionReturn(PETSC_SUCCESS);
2316: }
2318: /*@
2319: PetscDTTanhSinhTensorQuadrature - create tanh-sinh quadrature for a tensor product cell
2321: Not Collective
2323: Input Parameters:
2324: + dim - The cell dimension
2325: . level - The number of points in one dimension, $2^l$
2326: . a - left end of interval (often-1)
2327: - b - right end of interval (often +1)
2329: Output Parameter:
2330: . q - A `PetscQuadrature` object
2332: Level: intermediate
2334: .seealso: `PetscDTGaussTensorQuadrature()`, `PetscQuadrature`
2335: @*/
2336: PetscErrorCode PetscDTTanhSinhTensorQuadrature(PetscInt dim, PetscInt level, PetscReal a, PetscReal b, PetscQuadrature *q)
2337: {
2338: DMPolytopeType ct;
2339: const PetscInt p = 16; /* Digits of precision in the evaluation */
2340: const PetscReal alpha = (b - a) / 2.; /* Half-width of the integration interval */
2341: const PetscReal beta = (b + a) / 2.; /* Center of the integration interval */
2342: const PetscReal h = PetscPowReal(2.0, -level); /* Step size, length between x_k */
2343: PetscReal xk; /* Quadrature point x_k on reference domain [-1, 1] */
2344: PetscReal wk = 0.5 * PETSC_PI; /* Quadrature weight at x_k */
2345: PetscReal *x, *w;
2346: PetscInt K, k, npoints;
2348: PetscFunctionBegin;
2349: PetscCheck(dim <= 1, PETSC_COMM_SELF, PETSC_ERR_SUP, "Dimension %" PetscInt_FMT " not yet implemented", dim);
2350: PetscCheck(level, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Must give a number of significant digits");
2351: switch (dim) {
2352: case 0:
2353: ct = DM_POLYTOPE_POINT;
2354: break;
2355: case 1:
2356: ct = DM_POLYTOPE_SEGMENT;
2357: break;
2358: case 2:
2359: ct = DM_POLYTOPE_QUADRILATERAL;
2360: break;
2361: case 3:
2362: ct = DM_POLYTOPE_HEXAHEDRON;
2363: break;
2364: default:
2365: ct = DM_POLYTOPE_UNKNOWN;
2366: }
2367: /* Find K such that the weights are < 32 digits of precision */
2368: for (K = 1; PetscAbsReal(PetscLog10Real(wk)) < 2 * p; ++K) wk = 0.5 * h * PETSC_PI * PetscCoshReal(K * h) / PetscSqr(PetscCoshReal(0.5 * PETSC_PI * PetscSinhReal(K * h)));
2369: PetscCall(PetscQuadratureCreate(PETSC_COMM_SELF, q));
2370: PetscCall(PetscQuadratureSetCellType(*q, ct));
2371: PetscCall(PetscQuadratureSetOrder(*q, 2 * K + 1));
2372: npoints = 2 * K - 1;
2373: PetscCall(PetscMalloc1(npoints * dim, &x));
2374: PetscCall(PetscMalloc1(npoints, &w));
2375: /* Center term */
2376: x[0] = beta;
2377: w[0] = 0.5 * alpha * h * PETSC_PI;
2378: for (k = 1; k < K; ++k) {
2379: wk = 0.5 * alpha * h * PETSC_PI * PetscCoshReal(k * h) / PetscSqr(PetscCoshReal(0.5 * PETSC_PI * PetscSinhReal(k * h)));
2380: xk = PetscTanhReal(0.5 * PETSC_PI * PetscSinhReal(k * h));
2381: x[2 * k - 1] = -alpha * xk + beta;
2382: w[2 * k - 1] = wk;
2383: x[2 * k + 0] = alpha * xk + beta;
2384: w[2 * k + 0] = wk;
2385: }
2386: PetscCall(PetscQuadratureSetData(*q, dim, 1, npoints, x, w));
2387: PetscFunctionReturn(PETSC_SUCCESS);
2388: }
2390: /*@
2391: PetscDTTanhSinhIntegrate - Approximate $\int_a^b f(x)\,dx$ to a requested precision using adaptive tanh-sinh (double-exponential) quadrature
2393: Not Collective; No Fortran Support
2395: Input Parameters:
2396: + func - the integrand callback (`func(x, ctx, &value)` evaluates the integrand at point `x`)
2397: . a - lower limit of integration
2398: . b - upper limit of integration
2399: . digits - target number of correct decimal digits
2400: - ctx - optional application context passed to `func`
2402: Output Parameter:
2403: . sol - the approximate value of the integral
2405: Level: developer
2407: Notes:
2408: Doubles the number of quadrature points at each refinement level until the change in the
2409: integral falls below the requested tolerance. Suitable for smooth integrands and integrands
2410: with endpoint singularities.
2412: For arbitrary-precision arithmetic via MPFR, see `PetscDTTanhSinhIntegrateMPFR()`.
2414: .seealso: `PetscDTTanhSinhIntegrateMPFR()`, `PetscDTGaussQuadrature()`
2415: @*/
2416: PetscErrorCode PetscDTTanhSinhIntegrate(void (*func)(const PetscReal[], PetscCtx, PetscReal *), PetscReal a, PetscReal b, PetscInt digits, PetscCtx ctx, PetscReal *sol)
2417: {
2418: const PetscInt p = 16; /* Digits of precision in the evaluation */
2419: const PetscReal alpha = (b - a) / 2.; /* Half-width of the integration interval */
2420: const PetscReal beta = (b + a) / 2.; /* Center of the integration interval */
2421: PetscReal h = 1.0; /* Step size, length between x_k */
2422: PetscInt l = 0; /* Level of refinement, h = 2^{-l} */
2423: PetscReal osum = 0.0; /* Integral on last level */
2424: PetscReal psum = 0.0; /* Integral on the level before the last level */
2425: PetscReal sum; /* Integral on current level */
2426: PetscReal yk; /* Quadrature point 1 - x_k on reference domain [-1, 1] */
2427: PetscReal lx, rx; /* Quadrature points to the left and right of 0 on the real domain [a, b] */
2428: PetscReal wk; /* Quadrature weight at x_k */
2429: PetscReal lval, rval; /* Terms in the quadature sum to the left and right of 0 */
2430: PetscInt d; /* Digits of precision in the integral */
2432: PetscFunctionBegin;
2433: PetscCheck(digits > 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Must give a positive number of significant digits");
2434: PetscCall(PetscFPTrapPush(PETSC_FP_TRAP_OFF));
2435: /* Center term */
2436: func(&beta, ctx, &lval);
2437: sum = 0.5 * alpha * PETSC_PI * lval;
2438: /* */
2439: do {
2440: PetscReal lterm, rterm, maxTerm = 0.0, d1, d2, d3, d4;
2441: PetscInt k = 1;
2443: ++l;
2444: /* PetscPrintf(PETSC_COMM_SELF, "LEVEL %" PetscInt_FMT " sum: %15.15f\n", l, sum); */
2445: /* At each level of refinement, h --> h/2 and sum --> sum/2 */
2446: psum = osum;
2447: osum = sum;
2448: h *= 0.5;
2449: sum *= 0.5;
2450: do {
2451: wk = 0.5 * h * PETSC_PI * PetscCoshReal(k * h) / PetscSqr(PetscCoshReal(0.5 * PETSC_PI * PetscSinhReal(k * h)));
2452: yk = 1.0 / (PetscExpReal(0.5 * PETSC_PI * PetscSinhReal(k * h)) * PetscCoshReal(0.5 * PETSC_PI * PetscSinhReal(k * h)));
2453: lx = -alpha * (1.0 - yk) + beta;
2454: rx = alpha * (1.0 - yk) + beta;
2455: func(&lx, ctx, &lval);
2456: func(&rx, ctx, &rval);
2457: lterm = alpha * wk * lval;
2458: maxTerm = PetscMax(PetscAbsReal(lterm), maxTerm);
2459: sum += lterm;
2460: rterm = alpha * wk * rval;
2461: maxTerm = PetscMax(PetscAbsReal(rterm), maxTerm);
2462: sum += rterm;
2463: ++k;
2464: /* Only need to evaluate every other point on refined levels */
2465: if (l != 1) ++k;
2466: } while (PetscAbsReal(PetscLog10Real(wk)) < p); /* Only need to evaluate sum until weights are < 32 digits of precision */
2468: d1 = PetscLog10Real(PetscAbsReal(sum - osum));
2469: d2 = PetscLog10Real(PetscAbsReal(sum - psum));
2470: d3 = PetscLog10Real(maxTerm) - p;
2471: if (PetscMax(PetscAbsReal(lterm), PetscAbsReal(rterm)) == 0.0) d4 = 0.0;
2472: else d4 = PetscLog10Real(PetscMax(PetscAbsReal(lterm), PetscAbsReal(rterm)));
2473: d = PetscAbsInt(PetscMin(0, PetscMax(PetscMax(PetscMax(PetscSqr(d1) / d2, 2 * d1), d3), d4)));
2474: } while (d < digits && l < 12);
2475: *sol = sum;
2476: PetscCall(PetscFPTrapPop());
2477: PetscFunctionReturn(PETSC_SUCCESS);
2478: }
2480: /*@
2481: PetscDTTanhSinhIntegrateMPFR - High-precision version of `PetscDTTanhSinhIntegrate()` that uses the MPFR arbitrary-precision library to evaluate the quadrature
2483: Not Collective; No Fortran Support
2485: Input Parameters:
2486: + func - the integrand callback (`func(x, ctx, &value)` evaluates the integrand at point `x`)
2487: . a - lower limit of integration
2488: . b - upper limit of integration
2489: . digits - target number of correct decimal digits (also drives the working MPFR precision)
2490: - ctx - optional application context passed to `func`
2492: Output Parameter:
2493: . sol - the approximate value of the integral
2495: Level: developer
2497: Note:
2498: Requires PETSc to be configured with `--with-mpfr`; otherwise an error is raised.
2500: .seealso: `PetscDTTanhSinhIntegrate()`, `PetscDTGaussQuadrature()`
2501: @*/
2502: #if PetscDefined(HAVE_MPFR)
2503: PetscErrorCode PetscDTTanhSinhIntegrateMPFR(void (*func)(const PetscReal[], PetscCtx, PetscReal *), PetscReal a, PetscReal b, PetscInt digits, PetscCtx ctx, PetscReal *sol)
2504: {
2505: const PetscInt safetyFactor = 2; /* Calculate abscissa until 2*p digits */
2506: PetscInt l = 0; /* Level of refinement, h = 2^{-l} */
2507: mpfr_t alpha; /* Half-width of the integration interval */
2508: mpfr_t beta; /* Center of the integration interval */
2509: mpfr_t h; /* Step size, length between x_k */
2510: mpfr_t osum; /* Integral on last level */
2511: mpfr_t psum; /* Integral on the level before the last level */
2512: mpfr_t sum; /* Integral on current level */
2513: mpfr_t yk; /* Quadrature point 1 - x_k on reference domain [-1, 1] */
2514: mpfr_t lx, rx; /* Quadrature points to the left and right of 0 on the real domain [a, b] */
2515: mpfr_t wk; /* Quadrature weight at x_k */
2516: PetscReal lval, rval, rtmp; /* Terms in the quadature sum to the left and right of 0 */
2517: PetscInt d; /* Digits of precision in the integral */
2518: mpfr_t pi2, kh, msinh, mcosh, maxTerm, curTerm, tmp;
2520: PetscFunctionBegin;
2521: PetscCheck(digits > 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Must give a positive number of significant digits");
2522: /* Create high precision storage */
2523: mpfr_inits2(PetscCeilReal(safetyFactor * digits * PetscLogReal(10.) / PetscLogReal(2.)), alpha, beta, h, sum, osum, psum, yk, wk, lx, rx, tmp, maxTerm, curTerm, pi2, kh, msinh, mcosh, NULL);
2524: /* Initialization */
2525: mpfr_set_d(alpha, 0.5 * (b - a), MPFR_RNDN);
2526: mpfr_set_d(beta, 0.5 * (b + a), MPFR_RNDN);
2527: mpfr_set_d(osum, 0.0, MPFR_RNDN);
2528: mpfr_set_d(psum, 0.0, MPFR_RNDN);
2529: mpfr_set_d(h, 1.0, MPFR_RNDN);
2530: mpfr_const_pi(pi2, MPFR_RNDN);
2531: mpfr_mul_d(pi2, pi2, 0.5, MPFR_RNDN);
2532: /* Center term */
2533: rtmp = 0.5 * (b + a);
2534: func(&rtmp, ctx, &lval);
2535: mpfr_set(sum, pi2, MPFR_RNDN);
2536: mpfr_mul(sum, sum, alpha, MPFR_RNDN);
2537: mpfr_mul_d(sum, sum, lval, MPFR_RNDN);
2538: /* */
2539: do {
2540: PetscReal d1, d2, d3, d4;
2541: PetscInt k = 1;
2543: ++l;
2544: mpfr_set_d(maxTerm, 0.0, MPFR_RNDN);
2545: /* PetscPrintf(PETSC_COMM_SELF, "LEVEL %" PetscInt_FMT " sum: %15.15f\n", l, sum); */
2546: /* At each level of refinement, h --> h/2 and sum --> sum/2 */
2547: mpfr_set(psum, osum, MPFR_RNDN);
2548: mpfr_set(osum, sum, MPFR_RNDN);
2549: mpfr_mul_d(h, h, 0.5, MPFR_RNDN);
2550: mpfr_mul_d(sum, sum, 0.5, MPFR_RNDN);
2551: do {
2552: mpfr_set_si(kh, k, MPFR_RNDN);
2553: mpfr_mul(kh, kh, h, MPFR_RNDN);
2554: /* Weight */
2555: mpfr_set(wk, h, MPFR_RNDN);
2556: mpfr_sinh_cosh(msinh, mcosh, kh, MPFR_RNDN);
2557: mpfr_mul(msinh, msinh, pi2, MPFR_RNDN);
2558: mpfr_mul(mcosh, mcosh, pi2, MPFR_RNDN);
2559: mpfr_cosh(tmp, msinh, MPFR_RNDN);
2560: mpfr_sqr(tmp, tmp, MPFR_RNDN);
2561: mpfr_mul(wk, wk, mcosh, MPFR_RNDN);
2562: mpfr_div(wk, wk, tmp, MPFR_RNDN);
2563: /* Abscissa */
2564: mpfr_set_d(yk, 1.0, MPFR_RNDZ);
2565: mpfr_cosh(tmp, msinh, MPFR_RNDN);
2566: mpfr_div(yk, yk, tmp, MPFR_RNDZ);
2567: mpfr_exp(tmp, msinh, MPFR_RNDN);
2568: mpfr_div(yk, yk, tmp, MPFR_RNDZ);
2569: /* Quadrature points */
2570: mpfr_sub_d(lx, yk, 1.0, MPFR_RNDZ);
2571: mpfr_mul(lx, lx, alpha, MPFR_RNDU);
2572: mpfr_add(lx, lx, beta, MPFR_RNDU);
2573: mpfr_d_sub(rx, 1.0, yk, MPFR_RNDZ);
2574: mpfr_mul(rx, rx, alpha, MPFR_RNDD);
2575: mpfr_add(rx, rx, beta, MPFR_RNDD);
2576: /* Evaluation */
2577: rtmp = mpfr_get_d(lx, MPFR_RNDU);
2578: func(&rtmp, ctx, &lval);
2579: rtmp = mpfr_get_d(rx, MPFR_RNDD);
2580: func(&rtmp, ctx, &rval);
2581: /* Update */
2582: mpfr_mul(tmp, wk, alpha, MPFR_RNDN);
2583: mpfr_mul_d(tmp, tmp, lval, MPFR_RNDN);
2584: mpfr_add(sum, sum, tmp, MPFR_RNDN);
2585: mpfr_abs(tmp, tmp, MPFR_RNDN);
2586: mpfr_max(maxTerm, maxTerm, tmp, MPFR_RNDN);
2587: mpfr_set(curTerm, tmp, MPFR_RNDN);
2588: mpfr_mul(tmp, wk, alpha, MPFR_RNDN);
2589: mpfr_mul_d(tmp, tmp, rval, MPFR_RNDN);
2590: mpfr_add(sum, sum, tmp, MPFR_RNDN);
2591: mpfr_abs(tmp, tmp, MPFR_RNDN);
2592: mpfr_max(maxTerm, maxTerm, tmp, MPFR_RNDN);
2593: mpfr_max(curTerm, curTerm, tmp, MPFR_RNDN);
2594: ++k;
2595: /* Only need to evaluate every other point on refined levels */
2596: if (l != 1) ++k;
2597: mpfr_log10(tmp, wk, MPFR_RNDN);
2598: mpfr_abs(tmp, tmp, MPFR_RNDN);
2599: } while (mpfr_get_d(tmp, MPFR_RNDN) < safetyFactor * digits); /* Only need to evaluate sum until weights are < 32 digits of precision */
2600: mpfr_sub(tmp, sum, osum, MPFR_RNDN);
2601: mpfr_abs(tmp, tmp, MPFR_RNDN);
2602: mpfr_log10(tmp, tmp, MPFR_RNDN);
2603: d1 = mpfr_get_d(tmp, MPFR_RNDN);
2604: mpfr_sub(tmp, sum, psum, MPFR_RNDN);
2605: mpfr_abs(tmp, tmp, MPFR_RNDN);
2606: mpfr_log10(tmp, tmp, MPFR_RNDN);
2607: d2 = mpfr_get_d(tmp, MPFR_RNDN);
2608: mpfr_log10(tmp, maxTerm, MPFR_RNDN);
2609: d3 = mpfr_get_d(tmp, MPFR_RNDN) - digits;
2610: mpfr_log10(tmp, curTerm, MPFR_RNDN);
2611: d4 = mpfr_get_d(tmp, MPFR_RNDN);
2612: d = PetscAbsInt(PetscMin(0, PetscMax(PetscMax(PetscMax(PetscSqr(d1) / d2, 2 * d1), d3), d4)));
2613: } while (d < digits && l < 8);
2614: *sol = mpfr_get_d(sum, MPFR_RNDN);
2615: /* Cleanup */
2616: mpfr_clears(alpha, beta, h, sum, osum, psum, yk, wk, lx, rx, tmp, maxTerm, curTerm, pi2, kh, msinh, mcosh, NULL);
2617: PetscFunctionReturn(PETSC_SUCCESS);
2618: }
2619: #else
2621: PetscErrorCode PetscDTTanhSinhIntegrateMPFR(void (*func)(const PetscReal[], void *, PetscReal *), PetscReal a, PetscReal b, PetscInt digits, PetscCtx ctx, PetscReal *sol)
2622: {
2623: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "This method will not work without MPFR. Reconfigure using --download-mpfr --download-gmp");
2624: }
2625: #endif
2627: /*@
2628: PetscDTTensorQuadratureCreate - create the tensor product quadrature from two lower-dimensional quadratures
2630: Not Collective
2632: Input Parameters:
2633: + q1 - The first quadrature
2634: - q2 - The second quadrature
2636: Output Parameter:
2637: . q - A `PetscQuadrature` object
2639: Level: intermediate
2641: .seealso: `PetscQuadrature`, `PetscDTGaussTensorQuadrature()`
2642: @*/
2643: PetscErrorCode PetscDTTensorQuadratureCreate(PetscQuadrature q1, PetscQuadrature q2, PetscQuadrature *q)
2644: {
2645: DMPolytopeType ct1, ct2, ct;
2646: const PetscReal *x1, *w1, *x2, *w2;
2647: PetscReal *x, *w;
2648: PetscInt dim1, Nc1, Np1, order1, qa, d1;
2649: PetscInt dim2, Nc2, Np2, order2, qb, d2;
2650: PetscInt dim, Nc, Np, order, qc, d;
2652: PetscFunctionBegin;
2655: PetscAssertPointer(q, 3);
2657: PetscCall(PetscQuadratureGetOrder(q1, &order1));
2658: PetscCall(PetscQuadratureGetOrder(q2, &order2));
2659: PetscCheck(order1 == order2, PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Order1 %" PetscInt_FMT " != %" PetscInt_FMT " Order2", order1, order2);
2660: PetscCall(PetscQuadratureGetData(q1, &dim1, &Nc1, &Np1, &x1, &w1));
2661: PetscCall(PetscQuadratureGetCellType(q1, &ct1));
2662: PetscCall(PetscQuadratureGetData(q2, &dim2, &Nc2, &Np2, &x2, &w2));
2663: PetscCall(PetscQuadratureGetCellType(q2, &ct2));
2664: PetscCheck(Nc1 == Nc2, PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "NumComp1 %" PetscInt_FMT " != %" PetscInt_FMT " NumComp2", Nc1, Nc2);
2666: switch (ct1) {
2667: case DM_POLYTOPE_POINT:
2668: ct = ct2;
2669: break;
2670: case DM_POLYTOPE_SEGMENT:
2671: switch (ct2) {
2672: case DM_POLYTOPE_POINT:
2673: ct = ct1;
2674: break;
2675: case DM_POLYTOPE_SEGMENT:
2676: ct = DM_POLYTOPE_QUADRILATERAL;
2677: break;
2678: case DM_POLYTOPE_TRIANGLE:
2679: ct = DM_POLYTOPE_TRI_PRISM;
2680: break;
2681: case DM_POLYTOPE_QUADRILATERAL:
2682: ct = DM_POLYTOPE_HEXAHEDRON;
2683: break;
2684: case DM_POLYTOPE_TETRAHEDRON:
2685: ct = DM_POLYTOPE_UNKNOWN;
2686: break;
2687: case DM_POLYTOPE_HEXAHEDRON:
2688: ct = DM_POLYTOPE_UNKNOWN;
2689: break;
2690: default:
2691: ct = DM_POLYTOPE_UNKNOWN;
2692: }
2693: break;
2694: case DM_POLYTOPE_TRIANGLE:
2695: switch (ct2) {
2696: case DM_POLYTOPE_POINT:
2697: ct = ct1;
2698: break;
2699: case DM_POLYTOPE_SEGMENT:
2700: ct = DM_POLYTOPE_TRI_PRISM;
2701: break;
2702: case DM_POLYTOPE_TRIANGLE:
2703: ct = DM_POLYTOPE_UNKNOWN;
2704: break;
2705: case DM_POLYTOPE_QUADRILATERAL:
2706: ct = DM_POLYTOPE_UNKNOWN;
2707: break;
2708: case DM_POLYTOPE_TETRAHEDRON:
2709: ct = DM_POLYTOPE_UNKNOWN;
2710: break;
2711: case DM_POLYTOPE_HEXAHEDRON:
2712: ct = DM_POLYTOPE_UNKNOWN;
2713: break;
2714: default:
2715: ct = DM_POLYTOPE_UNKNOWN;
2716: }
2717: break;
2718: case DM_POLYTOPE_QUADRILATERAL:
2719: switch (ct2) {
2720: case DM_POLYTOPE_POINT:
2721: ct = ct1;
2722: break;
2723: case DM_POLYTOPE_SEGMENT:
2724: ct = DM_POLYTOPE_HEXAHEDRON;
2725: break;
2726: case DM_POLYTOPE_TRIANGLE:
2727: ct = DM_POLYTOPE_UNKNOWN;
2728: break;
2729: case DM_POLYTOPE_QUADRILATERAL:
2730: ct = DM_POLYTOPE_UNKNOWN;
2731: break;
2732: case DM_POLYTOPE_TETRAHEDRON:
2733: ct = DM_POLYTOPE_UNKNOWN;
2734: break;
2735: case DM_POLYTOPE_HEXAHEDRON:
2736: ct = DM_POLYTOPE_UNKNOWN;
2737: break;
2738: default:
2739: ct = DM_POLYTOPE_UNKNOWN;
2740: }
2741: break;
2742: case DM_POLYTOPE_TETRAHEDRON:
2743: switch (ct2) {
2744: case DM_POLYTOPE_POINT:
2745: ct = ct1;
2746: break;
2747: case DM_POLYTOPE_SEGMENT:
2748: ct = DM_POLYTOPE_UNKNOWN;
2749: break;
2750: case DM_POLYTOPE_TRIANGLE:
2751: ct = DM_POLYTOPE_UNKNOWN;
2752: break;
2753: case DM_POLYTOPE_QUADRILATERAL:
2754: ct = DM_POLYTOPE_UNKNOWN;
2755: break;
2756: case DM_POLYTOPE_TETRAHEDRON:
2757: ct = DM_POLYTOPE_UNKNOWN;
2758: break;
2759: case DM_POLYTOPE_HEXAHEDRON:
2760: ct = DM_POLYTOPE_UNKNOWN;
2761: break;
2762: default:
2763: ct = DM_POLYTOPE_UNKNOWN;
2764: }
2765: break;
2766: case DM_POLYTOPE_HEXAHEDRON:
2767: switch (ct2) {
2768: case DM_POLYTOPE_POINT:
2769: ct = ct1;
2770: break;
2771: case DM_POLYTOPE_SEGMENT:
2772: ct = DM_POLYTOPE_UNKNOWN;
2773: break;
2774: case DM_POLYTOPE_TRIANGLE:
2775: ct = DM_POLYTOPE_UNKNOWN;
2776: break;
2777: case DM_POLYTOPE_QUADRILATERAL:
2778: ct = DM_POLYTOPE_UNKNOWN;
2779: break;
2780: case DM_POLYTOPE_TETRAHEDRON:
2781: ct = DM_POLYTOPE_UNKNOWN;
2782: break;
2783: case DM_POLYTOPE_HEXAHEDRON:
2784: ct = DM_POLYTOPE_UNKNOWN;
2785: break;
2786: default:
2787: ct = DM_POLYTOPE_UNKNOWN;
2788: }
2789: break;
2790: default:
2791: ct = DM_POLYTOPE_UNKNOWN;
2792: }
2793: dim = dim1 + dim2;
2794: Nc = Nc1;
2795: Np = Np1 * Np2;
2796: order = order1;
2797: PetscCall(PetscQuadratureCreate(PETSC_COMM_SELF, q));
2798: PetscCall(PetscQuadratureSetCellType(*q, ct));
2799: PetscCall(PetscQuadratureSetOrder(*q, order));
2800: PetscCall(PetscMalloc1(Np * dim, &x));
2801: PetscCall(PetscMalloc1(Np, &w));
2802: for (qa = 0, qc = 0; qa < Np1; ++qa) {
2803: for (qb = 0; qb < Np2; ++qb, ++qc) {
2804: for (d1 = 0, d = 0; d1 < dim1; ++d1, ++d) x[qc * dim + d] = x1[qa * dim1 + d1];
2805: for (d2 = 0; d2 < dim2; ++d2, ++d) x[qc * dim + d] = x2[qb * dim2 + d2];
2806: w[qc] = w1[qa] * w2[qb];
2807: }
2808: }
2809: PetscCall(PetscQuadratureSetData(*q, dim, Nc, Np, x, w));
2810: PetscFunctionReturn(PETSC_SUCCESS);
2811: }
2813: /* Overwrites A. Can only handle full-rank problems with m>=n
2814: A in column-major format
2815: Ainv in row-major format
2816: tau has length m
2817: worksize must be >= max(1,n)
2818: */
2819: static PetscErrorCode PetscDTPseudoInverseQR(PetscInt m, PetscInt mstride, PetscInt n, PetscReal *A_in, PetscReal *Ainv_out, PetscScalar *tau, PetscInt worksize, PetscScalar *work)
2820: {
2821: PetscBLASInt M, N, K, lda, ldb, ldwork;
2822: PetscScalar *A, *Ainv, *R, *Q, Alpha;
2824: PetscFunctionBegin;
2825: #if PetscDefined(USE_COMPLEX)
2826: {
2827: PetscInt i, j;
2828: PetscCall(PetscMalloc2(m * n, &A, m * n, &Ainv));
2829: for (j = 0; j < n; j++) {
2830: for (i = 0; i < m; i++) A[i + m * j] = A_in[i + mstride * j];
2831: }
2832: mstride = m;
2833: }
2834: #else
2835: A = A_in;
2836: Ainv = Ainv_out;
2837: #endif
2839: PetscCall(PetscBLASIntCast(m, &M));
2840: PetscCall(PetscBLASIntCast(n, &N));
2841: PetscCall(PetscBLASIntCast(mstride, &lda));
2842: PetscCall(PetscBLASIntCast(worksize, &ldwork));
2843: PetscCall(PetscFPTrapPush(PETSC_FP_TRAP_OFF));
2844: PetscCallLAPACKInfo("LAPACKgeqrf", LAPACKgeqrf_(&M, &N, A, &lda, tau, work, &ldwork, &info));
2845: PetscCall(PetscFPTrapPop());
2846: R = A; /* Upper triangular part of A now contains R, the rest contains the elementary reflectors */
2848: /* Extract an explicit representation of Q */
2849: Q = Ainv;
2850: PetscCall(PetscArraycpy(Q, A, mstride * n));
2851: K = N; /* full rank */
2852: PetscCallLAPACKInfo("LAPACKorgqr", LAPACKorgqr_(&M, &N, &K, Q, &lda, tau, work, &ldwork, &info));
2854: /* Compute A^{-T} = (R^{-1} Q^T)^T = Q R^{-T} */
2855: Alpha = 1.0;
2856: ldb = lda;
2857: PetscCallBLAS("BLAStrsm", BLAStrsm_("Right", "Upper", "ConjugateTranspose", "NotUnitTriangular", &M, &N, &Alpha, R, &lda, Q, &ldb));
2858: /* Ainv is Q, overwritten with inverse */
2860: #if PetscDefined(USE_COMPLEX)
2861: {
2862: PetscInt i;
2863: for (i = 0; i < m * n; i++) Ainv_out[i] = PetscRealPart(Ainv[i]);
2864: PetscCall(PetscFree2(A, Ainv));
2865: }
2866: #endif
2867: PetscFunctionReturn(PETSC_SUCCESS);
2868: }
2870: /* Computes integral of L_p' over intervals {(x0,x1),(x1,x2),...} */
2871: static PetscErrorCode PetscDTLegendreIntegrate(PetscInt ninterval, const PetscReal *x, PetscInt ndegree, const PetscInt *degrees, PetscBool Transpose, PetscReal *B)
2872: {
2873: PetscReal *Bv;
2874: PetscInt i, j;
2876: PetscFunctionBegin;
2877: PetscCall(PetscMalloc1((ninterval + 1) * ndegree, &Bv));
2878: /* Point evaluation of L_p on all the source vertices */
2879: PetscCall(PetscDTLegendreEval(ninterval + 1, x, ndegree, degrees, Bv, NULL, NULL));
2880: /* Integral over each interval: \int_a^b L_p' = L_p(b)-L_p(a) */
2881: for (i = 0; i < ninterval; i++) {
2882: for (j = 0; j < ndegree; j++) {
2883: if (Transpose) B[i + ninterval * j] = Bv[(i + 1) * ndegree + j] - Bv[i * ndegree + j];
2884: else B[i * ndegree + j] = Bv[(i + 1) * ndegree + j] - Bv[i * ndegree + j];
2885: }
2886: }
2887: PetscCall(PetscFree(Bv));
2888: PetscFunctionReturn(PETSC_SUCCESS);
2889: }
2891: /*@
2892: PetscDTReconstructPoly - create matrix representing polynomial reconstruction using cell intervals and evaluation at target intervals
2894: Not Collective
2896: Input Parameters:
2897: + degree - degree of reconstruction polynomial
2898: . nsource - number of source intervals
2899: . sourcex - sorted coordinates of source cell boundaries (length `nsource`+1)
2900: . ntarget - number of target intervals
2901: - targetx - sorted coordinates of target cell boundaries (length `ntarget`+1)
2903: Output Parameter:
2904: . R - reconstruction matrix, utarget = sum_s R[t*nsource+s] * usource[s]
2906: Level: advanced
2908: .seealso: `PetscDTLegendreEval()`
2909: @*/
2910: PetscErrorCode PetscDTReconstructPoly(PetscInt degree, PetscInt nsource, const PetscReal sourcex[], PetscInt ntarget, const PetscReal targetx[], PetscReal R[])
2911: {
2912: PetscInt i, j, k, *bdegrees, worksize;
2913: PetscReal xmin, xmax, center, hscale, *sourcey, *targety, *Bsource, *Bsinv, *Btarget;
2914: PetscScalar *tau, *work;
2916: PetscFunctionBegin;
2917: PetscAssertPointer(sourcex, 3);
2918: PetscAssertPointer(targetx, 5);
2919: PetscAssertPointer(R, 6);
2920: PetscCheck(degree < nsource, PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Reconstruction degree %" PetscInt_FMT " must be less than number of source intervals %" PetscInt_FMT, degree, nsource);
2921: if (PetscDefined(USE_DEBUG)) {
2922: for (i = 0; i < nsource; i++) PetscCheck(sourcex[i] < sourcex[i + 1], PETSC_COMM_SELF, PETSC_ERR_ARG_CORRUPT, "Source interval %" PetscInt_FMT " has negative orientation (%g,%g)", i, (double)sourcex[i], (double)sourcex[i + 1]);
2923: for (i = 0; i < ntarget; i++) PetscCheck(targetx[i] < targetx[i + 1], PETSC_COMM_SELF, PETSC_ERR_ARG_CORRUPT, "Target interval %" PetscInt_FMT " has negative orientation (%g,%g)", i, (double)targetx[i], (double)targetx[i + 1]);
2924: }
2925: xmin = PetscMin(sourcex[0], targetx[0]);
2926: xmax = PetscMax(sourcex[nsource], targetx[ntarget]);
2927: center = (xmin + xmax) / 2;
2928: hscale = (xmax - xmin) / 2;
2929: worksize = nsource;
2930: PetscCall(PetscMalloc4(degree + 1, &bdegrees, nsource + 1, &sourcey, nsource * (degree + 1), &Bsource, worksize, &work));
2931: PetscCall(PetscMalloc4(nsource, &tau, nsource * (degree + 1), &Bsinv, ntarget + 1, &targety, ntarget * (degree + 1), &Btarget));
2932: for (i = 0; i <= nsource; i++) sourcey[i] = (sourcex[i] - center) / hscale;
2933: for (i = 0; i <= degree; i++) bdegrees[i] = i + 1;
2934: PetscCall(PetscDTLegendreIntegrate(nsource, sourcey, degree + 1, bdegrees, PETSC_TRUE, Bsource));
2935: PetscCall(PetscDTPseudoInverseQR(nsource, nsource, degree + 1, Bsource, Bsinv, tau, nsource, work));
2936: for (i = 0; i <= ntarget; i++) targety[i] = (targetx[i] - center) / hscale;
2937: PetscCall(PetscDTLegendreIntegrate(ntarget, targety, degree + 1, bdegrees, PETSC_FALSE, Btarget));
2938: for (i = 0; i < ntarget; i++) {
2939: PetscReal rowsum = 0;
2940: for (j = 0; j < nsource; j++) {
2941: PetscReal sum = 0;
2942: for (k = 0; k < degree + 1; k++) sum += Btarget[i * (degree + 1) + k] * Bsinv[k * nsource + j];
2943: R[i * nsource + j] = sum;
2944: rowsum += sum;
2945: }
2946: for (j = 0; j < nsource; j++) R[i * nsource + j] /= rowsum; /* normalize each row */
2947: }
2948: PetscCall(PetscFree4(bdegrees, sourcey, Bsource, work));
2949: PetscCall(PetscFree4(tau, Bsinv, targety, Btarget));
2950: PetscFunctionReturn(PETSC_SUCCESS);
2951: }
2953: /*@
2954: PetscGaussLobattoLegendreIntegrate - Compute the L2 integral of a function on the GLL points
2956: Not Collective
2958: Input Parameters:
2959: + n - the number of GLL nodes
2960: . nodes - the GLL nodes
2961: . weights - the GLL weights
2962: - f - the function values at the nodes
2964: Output Parameter:
2965: . in - the value of the integral
2967: Level: beginner
2969: .seealso: `PetscDTGaussLobattoLegendreQuadrature()`
2970: @*/
2971: PetscErrorCode PetscGaussLobattoLegendreIntegrate(PetscInt n, PetscReal nodes[], PetscReal weights[], const PetscReal f[], PetscReal *in)
2972: {
2973: PetscInt i;
2975: PetscFunctionBegin;
2976: *in = 0.;
2977: for (i = 0; i < n; i++) *in += f[i] * f[i] * weights[i];
2978: PetscFunctionReturn(PETSC_SUCCESS);
2979: }
2981: /*@
2982: PetscGaussLobattoLegendreElementLaplacianCreate - computes the Laplacian for a single 1d GLL element
2984: Not Collective
2986: Input Parameters:
2987: + n - the number of GLL nodes
2988: . nodes - the GLL nodes, of length `n`
2989: - weights - the GLL weights, of length `n`
2991: Output Parameter:
2992: . AA - the stiffness element, of size `n` by `n`
2994: Level: beginner
2996: Notes:
2997: Destroy this with `PetscGaussLobattoLegendreElementLaplacianDestroy()`
2999: You can access entries in this array with AA[i][j] but in memory it is stored in contiguous memory, row-oriented (the array is symmetric)
3001: .seealso: `PetscDTGaussLobattoLegendreQuadrature()`, `PetscGaussLobattoLegendreElementLaplacianDestroy()`
3002: @*/
3003: PetscErrorCode PetscGaussLobattoLegendreElementLaplacianCreate(PetscInt n, PetscReal nodes[], PetscReal weights[], PetscReal ***AA)
3004: {
3005: PetscReal **A;
3006: const PetscReal *gllnodes = nodes;
3007: const PetscInt p = n - 1;
3008: PetscReal z0, z1, z2 = -1, x, Lpj, Lpr;
3009: PetscInt i, j, nn, r;
3011: PetscFunctionBegin;
3012: PetscCall(PetscMalloc1(n, &A));
3013: PetscCall(PetscMalloc1(n * n, &A[0]));
3014: for (i = 1; i < n; i++) A[i] = A[i - 1] + n;
3016: for (j = 1; j < p; j++) {
3017: x = gllnodes[j];
3018: z0 = 1.;
3019: z1 = x;
3020: for (nn = 1; nn < p; nn++) {
3021: z2 = x * z1 * (2. * ((PetscReal)nn) + 1.) / (((PetscReal)nn) + 1.) - z0 * (((PetscReal)nn) / (((PetscReal)nn) + 1.));
3022: z0 = z1;
3023: z1 = z2;
3024: }
3025: Lpj = z2;
3026: for (r = 1; r < p; r++) {
3027: if (r == j) {
3028: A[j][j] = 2. / (3. * (1. - gllnodes[j] * gllnodes[j]) * Lpj * Lpj);
3029: } else {
3030: x = gllnodes[r];
3031: z0 = 1.;
3032: z1 = x;
3033: for (nn = 1; nn < p; nn++) {
3034: z2 = x * z1 * (2. * ((PetscReal)nn) + 1.) / (((PetscReal)nn) + 1.) - z0 * (((PetscReal)nn) / (((PetscReal)nn) + 1.));
3035: z0 = z1;
3036: z1 = z2;
3037: }
3038: Lpr = z2;
3039: A[r][j] = 4. / (((PetscReal)p) * (((PetscReal)p) + 1.) * Lpj * Lpr * (gllnodes[j] - gllnodes[r]) * (gllnodes[j] - gllnodes[r]));
3040: }
3041: }
3042: }
3043: for (j = 1; j < p + 1; j++) {
3044: x = gllnodes[j];
3045: z0 = 1.;
3046: z1 = x;
3047: for (nn = 1; nn < p; nn++) {
3048: z2 = x * z1 * (2. * ((PetscReal)nn) + 1.) / (((PetscReal)nn) + 1.) - z0 * (((PetscReal)nn) / (((PetscReal)nn) + 1.));
3049: z0 = z1;
3050: z1 = z2;
3051: }
3052: Lpj = z2;
3053: A[j][0] = 4. * PetscPowRealInt(-1., p) / (((PetscReal)p) * (((PetscReal)p) + 1.) * Lpj * (1. + gllnodes[j]) * (1. + gllnodes[j]));
3054: A[0][j] = A[j][0];
3055: }
3056: for (j = 0; j < p; j++) {
3057: x = gllnodes[j];
3058: z0 = 1.;
3059: z1 = x;
3060: for (nn = 1; nn < p; nn++) {
3061: z2 = x * z1 * (2. * ((PetscReal)nn) + 1.) / (((PetscReal)nn) + 1.) - z0 * (((PetscReal)nn) / (((PetscReal)nn) + 1.));
3062: z0 = z1;
3063: z1 = z2;
3064: }
3065: Lpj = z2;
3067: A[p][j] = 4. / (((PetscReal)p) * (((PetscReal)p) + 1.) * Lpj * (1. - gllnodes[j]) * (1. - gllnodes[j]));
3068: A[j][p] = A[p][j];
3069: }
3070: A[0][0] = 0.5 + (((PetscReal)p) * (((PetscReal)p) + 1.) - 2.) / 6.;
3071: A[p][p] = A[0][0];
3072: *AA = A;
3073: PetscFunctionReturn(PETSC_SUCCESS);
3074: }
3076: /*@
3077: PetscGaussLobattoLegendreElementLaplacianDestroy - frees the Laplacian for a single 1d GLL element created with `PetscGaussLobattoLegendreElementLaplacianCreate()`
3079: Not Collective
3081: Input Parameters:
3082: + n - the number of GLL nodes
3083: . nodes - the GLL nodes, ignored
3084: . weights - the GLL weightss, ignored
3085: - AA - the stiffness element from `PetscGaussLobattoLegendreElementLaplacianCreate()`
3087: Level: beginner
3089: .seealso: `PetscDTGaussLobattoLegendreQuadrature()`, `PetscGaussLobattoLegendreElementLaplacianCreate()`
3090: @*/
3091: PetscErrorCode PetscGaussLobattoLegendreElementLaplacianDestroy(PetscInt n, PetscReal nodes[], PetscReal weights[], PetscReal ***AA)
3092: {
3093: PetscFunctionBegin;
3094: PetscCall(PetscFree((*AA)[0]));
3095: PetscCall(PetscFree(*AA));
3096: PetscFunctionReturn(PETSC_SUCCESS);
3097: }
3099: /*@
3100: PetscGaussLobattoLegendreElementGradientCreate - computes the gradient for a single 1d GLL element
3102: Not Collective
3104: Input Parameters:
3105: + n - the number of GLL nodes
3106: . nodes - the GLL nodes, of length `n`
3107: - weights - the GLL weights, of length `n`
3109: Output Parameters:
3110: + AA - the stiffness element, of dimension `n` by `n`
3111: - AAT - the transpose of AA (pass in `NULL` if you do not need this array), of dimension `n` by `n`
3113: Level: beginner
3115: Notes:
3116: Destroy this with `PetscGaussLobattoLegendreElementGradientDestroy()`
3118: You can access entries in these arrays with AA[i][j] but in memory it is stored in contiguous memory, row-oriented
3120: .seealso: `PetscDTGaussLobattoLegendreQuadrature()`, `PetscGaussLobattoLegendreElementLaplacianDestroy()`, `PetscGaussLobattoLegendreElementGradientDestroy()`
3121: @*/
3122: PetscErrorCode PetscGaussLobattoLegendreElementGradientCreate(PetscInt n, PetscReal nodes[], PetscReal weights[], PetscReal ***AA, PetscReal ***AAT)
3123: {
3124: PetscReal **A, **AT = NULL;
3125: const PetscReal *gllnodes = nodes;
3126: const PetscInt p = n - 1;
3127: PetscReal Li, Lj, d0;
3128: PetscInt i, j;
3130: PetscFunctionBegin;
3131: PetscCall(PetscMalloc1(n, &A));
3132: PetscCall(PetscMalloc1(n * n, &A[0]));
3133: for (i = 1; i < n; i++) A[i] = A[i - 1] + n;
3135: if (AAT) {
3136: PetscCall(PetscMalloc1(n, &AT));
3137: PetscCall(PetscMalloc1(n * n, &AT[0]));
3138: for (i = 1; i < n; i++) AT[i] = AT[i - 1] + n;
3139: }
3141: if (n == 1) A[0][0] = 0.;
3142: d0 = (PetscReal)p * ((PetscReal)p + 1.) / 4.;
3143: for (i = 0; i < n; i++) {
3144: for (j = 0; j < n; j++) {
3145: A[i][j] = 0.;
3146: PetscCall(PetscDTComputeJacobi(0., 0., p, gllnodes[i], &Li));
3147: PetscCall(PetscDTComputeJacobi(0., 0., p, gllnodes[j], &Lj));
3148: if (i != j) A[i][j] = Li / (Lj * (gllnodes[i] - gllnodes[j]));
3149: if (j == i && i == 0) A[i][j] = -d0;
3150: if (j == i && i == p) A[i][j] = d0;
3151: if (AT) AT[j][i] = A[i][j];
3152: }
3153: }
3154: if (AAT) *AAT = AT;
3155: *AA = A;
3156: PetscFunctionReturn(PETSC_SUCCESS);
3157: }
3159: /*@
3160: PetscGaussLobattoLegendreElementGradientDestroy - frees the gradient for a single 1d GLL element obtained with `PetscGaussLobattoLegendreElementGradientCreate()`
3162: Not Collective
3164: Input Parameters:
3165: + n - the number of GLL nodes
3166: . nodes - the GLL nodes, ignored
3167: . weights - the GLL weights, ignored
3168: . AA - the stiffness element obtained with `PetscGaussLobattoLegendreElementGradientCreate()`
3169: - AAT - the transpose of the element obtained with `PetscGaussLobattoLegendreElementGradientCreate()`
3171: Level: beginner
3173: .seealso: `PetscDTGaussLobattoLegendreQuadrature()`, `PetscGaussLobattoLegendreElementLaplacianCreate()`, `PetscGaussLobattoLegendreElementAdvectionCreate()`
3174: @*/
3175: PetscErrorCode PetscGaussLobattoLegendreElementGradientDestroy(PetscInt n, PetscReal nodes[], PetscReal weights[], PetscReal ***AA, PetscReal ***AAT)
3176: {
3177: PetscFunctionBegin;
3178: PetscCall(PetscFree((*AA)[0]));
3179: PetscCall(PetscFree(*AA));
3180: if (AAT) {
3181: PetscCall(PetscFree((*AAT)[0]));
3182: PetscCall(PetscFree(*AAT));
3183: }
3184: PetscFunctionReturn(PETSC_SUCCESS);
3185: }
3187: /*@
3188: PetscGaussLobattoLegendreElementAdvectionCreate - computes the advection operator for a single 1d GLL element
3190: Not Collective
3192: Input Parameters:
3193: + n - the number of GLL nodes
3194: . nodes - the GLL nodes, of length `n`
3195: - weights - the GLL weights, of length `n`
3197: Output Parameter:
3198: . AA - the stiffness element, of dimension `n` by `n`
3200: Level: beginner
3202: Notes:
3203: Destroy this with `PetscGaussLobattoLegendreElementAdvectionDestroy()`
3205: This is the same as the Gradient operator multiplied by the diagonal mass matrix
3207: You can access entries in this array with AA[i][j] but in memory it is stored in contiguous memory, row-oriented
3209: .seealso: `PetscDTGaussLobattoLegendreQuadrature()`, `PetscGaussLobattoLegendreElementLaplacianCreate()`, `PetscGaussLobattoLegendreElementAdvectionDestroy()`
3210: @*/
3211: PetscErrorCode PetscGaussLobattoLegendreElementAdvectionCreate(PetscInt n, PetscReal nodes[], PetscReal weights[], PetscReal ***AA)
3212: {
3213: PetscReal **D;
3214: const PetscReal *gllweights = weights;
3215: const PetscInt glln = n;
3216: PetscInt j;
3218: PetscFunctionBegin;
3219: PetscCall(PetscGaussLobattoLegendreElementGradientCreate(n, nodes, weights, &D, NULL));
3220: for (PetscInt i = 0; i < glln; i++) {
3221: for (j = 0; j < glln; j++) D[i][j] = gllweights[i] * D[i][j];
3222: }
3223: *AA = D;
3224: PetscFunctionReturn(PETSC_SUCCESS);
3225: }
3227: /*@
3228: PetscGaussLobattoLegendreElementAdvectionDestroy - frees the advection stiffness for a single 1d GLL element created with `PetscGaussLobattoLegendreElementAdvectionCreate()`
3230: Not Collective
3232: Input Parameters:
3233: + n - the number of GLL nodes
3234: . nodes - the GLL nodes, ignored
3235: . weights - the GLL weights, ignored
3236: - AA - advection obtained with `PetscGaussLobattoLegendreElementAdvectionCreate()`
3238: Level: beginner
3240: .seealso: `PetscDTGaussLobattoLegendreQuadrature()`, `PetscGaussLobattoLegendreElementAdvectionCreate()`
3241: @*/
3242: PetscErrorCode PetscGaussLobattoLegendreElementAdvectionDestroy(PetscInt n, PetscReal nodes[], PetscReal weights[], PetscReal ***AA)
3243: {
3244: PetscFunctionBegin;
3245: PetscCall(PetscFree((*AA)[0]));
3246: PetscCall(PetscFree(*AA));
3247: PetscFunctionReturn(PETSC_SUCCESS);
3248: }
3250: /*@
3251: PetscGaussLobattoLegendreElementMassCreate - Build the elemental mass matrix for a single 1D Gauss-Lobatto-Legendre (GLL) spectral element
3253: Not Collective; No Fortran Support
3255: Input Parameters:
3256: + n - number of GLL nodes
3257: . nodes - the GLL quadrature nodes
3258: - weights - the GLL quadrature weights
3260: Output Parameter:
3261: . AA - newly allocated `n` x `n` mass matrix as `PetscReal **`
3263: Level: beginner
3265: Note:
3266: Free with `PetscGaussLobattoLegendreElementMassDestroy()`.
3268: .seealso: `PetscDTGaussLobattoLegendreQuadrature()`, `PetscGaussLobattoLegendreElementMassDestroy()`, `PetscGaussLobattoLegendreElementLaplacianCreate()`, `PetscGaussLobattoLegendreElementAdvectionCreate()`
3269: @*/
3270: PetscErrorCode PetscGaussLobattoLegendreElementMassCreate(PetscInt n, PetscReal *nodes, PetscReal *weights, PetscReal ***AA)
3271: {
3272: PetscReal **A;
3273: const PetscReal *gllweights = weights;
3274: const PetscInt glln = n;
3276: PetscFunctionBegin;
3277: PetscCall(PetscMalloc1(glln, &A));
3278: PetscCall(PetscMalloc1(glln * glln, &A[0]));
3279: for (PetscInt i = 1; i < glln; i++) A[i] = A[i - 1] + glln;
3280: if (glln == 1) A[0][0] = 0.;
3281: for (PetscInt i = 0; i < glln; i++) {
3282: for (PetscInt j = 0; j < glln; j++) {
3283: A[i][j] = 0.;
3284: if (j == i) A[i][j] = gllweights[i];
3285: }
3286: }
3287: *AA = A;
3288: PetscFunctionReturn(PETSC_SUCCESS);
3289: }
3291: /*@
3292: PetscGaussLobattoLegendreElementMassDestroy - Free a 1D GLL elemental mass matrix created with `PetscGaussLobattoLegendreElementMassCreate()`
3294: Not Collective; No Fortran Support
3296: Input Parameters:
3297: + n - number of GLL nodes (ignored)
3298: . nodes - the GLL quadrature nodes (ignored)
3299: . weights - the GLL quadrature weights (ignored)
3300: - AA - the mass matrix to free; `*AA` is set to `NULL` on return
3302: Level: beginner
3304: .seealso: `PetscGaussLobattoLegendreElementMassCreate()`, `PetscDTGaussLobattoLegendreQuadrature()`
3305: @*/
3306: PetscErrorCode PetscGaussLobattoLegendreElementMassDestroy(PetscInt n, PetscReal *nodes, PetscReal *weights, PetscReal ***AA)
3307: {
3308: PetscFunctionBegin;
3309: PetscCall(PetscFree((*AA)[0]));
3310: PetscCall(PetscFree(*AA));
3311: PetscFunctionReturn(PETSC_SUCCESS);
3312: }
3314: /*@
3315: PetscDTIndexToBary - convert an index into a barycentric coordinate.
3317: Input Parameters:
3318: + len - the desired length of the barycentric tuple (usually 1 more than the dimension it represents, so a barycentric coordinate in a triangle has length 3)
3319: . sum - the value that the sum of the barycentric coordinates (which will be non-negative integers) should sum to
3320: - index - the index to convert: should be >= 0 and < Binomial(len - 1 + sum, sum)
3322: Output Parameter:
3323: . coord - will be filled with the barycentric coordinate, of length `n`
3325: Level: beginner
3327: Note:
3328: The indices map to barycentric coordinates in lexicographic order, where the first index is the
3329: least significant and the last index is the most significant.
3331: .seealso: `PetscDTBaryToIndex()`
3332: @*/
3333: PetscErrorCode PetscDTIndexToBary(PetscInt len, PetscInt sum, PetscInt index, PetscInt coord[])
3334: {
3335: PetscInt c, d, s, total, subtotal, nexttotal;
3337: PetscFunctionBeginHot;
3338: PetscCheck(len >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "length must be non-negative");
3339: PetscCheck(index >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "index must be non-negative");
3340: if (!len) {
3341: PetscCheck(!sum && !index, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Invalid index or sum for length 0 barycentric coordinate");
3342: PetscFunctionReturn(PETSC_SUCCESS);
3343: }
3344: for (c = 1, total = 1; c <= len; c++) {
3345: /* total is the number of ways to have a tuple of length c with sum */
3346: if (index < total) break;
3347: total = (total * (sum + c)) / c;
3348: }
3349: PetscCheck(c <= len, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "index out of range");
3350: for (d = c; d < len; d++) coord[d] = 0;
3351: for (s = 0, subtotal = 1, nexttotal = 1; c > 0;) {
3352: /* subtotal is the number of ways to have a tuple of length c with sum s */
3353: /* nexttotal is the number of ways to have a tuple of length c-1 with sum s */
3354: if (index + subtotal >= total) {
3355: coord[--c] = sum - s;
3356: index -= (total - subtotal);
3357: sum = s;
3358: total = nexttotal;
3359: subtotal = 1;
3360: nexttotal = 1;
3361: s = 0;
3362: } else {
3363: subtotal = (subtotal * (c + s)) / (s + 1);
3364: nexttotal = (nexttotal * (c - 1 + s)) / (s + 1);
3365: s++;
3366: }
3367: }
3368: PetscFunctionReturn(PETSC_SUCCESS);
3369: }
3371: /*@
3372: PetscDTBaryToIndex - convert a barycentric coordinate to an index
3374: Input Parameters:
3375: + len - the desired length of the barycentric tuple (usually 1 more than the dimension it represents, so a barycentric coordinate in a triangle has length 3)
3376: . sum - the value that the sum of the barycentric coordinates (which will be non-negative integers) should sum to
3377: - coord - a barycentric coordinate with the given length `len` and `sum`
3379: Output Parameter:
3380: . index - the unique index for the coordinate, >= 0 and < Binomial(len - 1 + sum, sum)
3382: Level: beginner
3384: Note:
3385: The indices map to barycentric coordinates in lexicographic order, where the first index is the
3386: least significant and the last index is the most significant.
3388: .seealso: `PetscDTIndexToBary`
3389: @*/
3390: PetscErrorCode PetscDTBaryToIndex(PetscInt len, PetscInt sum, const PetscInt coord[], PetscInt *index)
3391: {
3392: PetscInt c;
3393: PetscInt i;
3394: PetscInt total;
3396: PetscFunctionBeginHot;
3397: PetscCheck(len >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "length must be non-negative");
3398: if (!len) {
3399: PetscCheck(!sum, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Invalid index or sum for length 0 barycentric coordinate");
3400: *index = 0;
3401: PetscFunctionReturn(PETSC_SUCCESS);
3402: }
3403: for (c = 1, total = 1; c < len; c++) total = (total * (sum + c)) / c;
3404: i = total - 1;
3405: c = len - 1;
3406: sum -= coord[c];
3407: while (sum > 0) {
3408: PetscInt subtotal;
3409: PetscInt s;
3411: for (s = 1, subtotal = 1; s < sum; s++) subtotal = (subtotal * (c + s)) / s;
3412: i -= subtotal;
3413: sum -= coord[--c];
3414: }
3415: *index = i;
3416: PetscFunctionReturn(PETSC_SUCCESS);
3417: }
3419: /*@
3420: PetscQuadratureComputePermutations - Compute permutations of quadrature points corresponding to domain orientations
3422: Not Collective
3424: Input Parameter:
3425: . quad - The `PetscQuadrature`
3427: Output Parameters:
3428: + Np - The number of domain orientations
3429: - perm - An array of `Np` `IS` permutations, where `perm[o + Np/2]` is the permutation for orientation `o`
3431: Level: developer
3433: Note:
3434: The user must destroy the permutation `IS` structures and free the array with `PetscFree()`.
3436: .seealso: `PetscQuadratureGetPermutations()`, `PetscQuadratureSetCellType()`, `PetscQuadrature`
3437: @*/
3438: PetscErrorCode PetscQuadratureComputePermutations(PetscQuadrature quad, PeOp PetscInt *Np, IS *perm[])
3439: {
3440: DMPolytopeType ct;
3441: const PetscReal *xq, *wq;
3442: PetscInt dim, qdim, d, Na, o, Nq, q, qp;
3444: PetscFunctionBegin;
3445: PetscCall(PetscQuadratureGetData(quad, &qdim, NULL, &Nq, &xq, &wq));
3446: PetscCall(PetscQuadratureGetCellType(quad, &ct));
3447: dim = DMPolytopeTypeGetDim(ct);
3448: Na = DMPolytopeTypeGetNumArrangements(ct);
3449: PetscCheck(Na > 0, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot compute permutations for quadrature cell type %s. Set the cell type with PetscQuadratureSetCellType()", DMPolytopeTypes[ct]);
3450: PetscCall(PetscMalloc1(Na, perm));
3451: if (Np) *Np = Na;
3452: Na /= 2;
3453: for (o = -Na; o < Na; ++o) {
3454: DM refdm;
3455: PetscInt *idx;
3456: PetscReal xi0[3] = {-1., -1., -1.}, v0[3], J[9], detJ, txq[3];
3457: PetscBool flg;
3459: PetscCall(DMPlexCreateReferenceCell(PETSC_COMM_SELF, ct, &refdm));
3460: PetscCall(DMPlexOrientPoint(refdm, 0, o));
3461: PetscCall(DMPlexComputeCellGeometryFEM(refdm, 0, NULL, v0, J, NULL, &detJ));
3462: PetscCall(PetscMalloc1(Nq, &idx));
3463: for (q = 0; q < Nq; ++q) {
3464: CoordinatesRefToReal(dim, dim, xi0, v0, J, &xq[q * dim], txq);
3465: for (qp = 0; qp < Nq; ++qp) {
3466: PetscReal diff = 0.;
3468: for (d = 0; d < dim; ++d) diff += PetscAbsReal(txq[d] - xq[qp * dim + d]);
3469: if (diff < PETSC_SMALL) break;
3470: }
3471: PetscCheck(qp < Nq, PETSC_COMM_SELF, PETSC_ERR_SUP, "Quadrature rule is not symmetric. Transformed quad point %" PetscInt_FMT " does not match another quad point", q);
3472: idx[q] = qp;
3473: }
3474: PetscCall(DMDestroy(&refdm));
3475: PetscCall(ISCreateGeneral(PETSC_COMM_SELF, Nq, idx, PETSC_OWN_POINTER, &(*perm)[o + Na]));
3476: PetscCall(ISGetInfo((*perm)[o + Na], IS_PERMUTATION, IS_LOCAL, PETSC_TRUE, &flg));
3477: PetscCheck(flg, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Ordering for orientation %" PetscInt_FMT " was not a permutation", o);
3478: PetscCall(ISSetPermutation((*perm)[o + Na]));
3479: }
3480: if (!Na) (*perm)[0] = NULL;
3481: PetscFunctionReturn(PETSC_SUCCESS);
3482: }
3484: /*@
3485: PetscQuadratureGetPermutations - Retrieve permutations of quadrature points corresponding to domain orientations
3487: Not Collective
3489: Input Parameter:
3490: . quad - The `PetscQuadrature`
3492: Output Parameters:
3493: + Np - The number of domain orientations
3494: - perm - An array of `Np` `IS` permutations, where `perm[o + Np/2]` is the permutation for orientation `o`
3496: Level: developer
3498: Note:
3499: The array and its `IS` permutations are borrowed from `quad`, so do not free or destroy them. They stay valid until `quad` is modified or destroyed.
3501: .seealso: `PetscQuadratureComputePermutations()`, `PetscQuadratureSetCellType()`, `PetscQuadrature`
3502: @*/
3503: PetscErrorCode PetscQuadratureGetPermutations(PetscQuadrature quad, PeOp PetscInt *Np, IS *perm[])
3504: {
3505: PetscFunctionBegin;
3507: if (Np != NULL) PetscAssertPointer(Np, 2);
3508: if (perm != NULL) PetscAssertPointer(perm, 3);
3509: if (quad->perms == NULL) PetscCall(PetscQuadratureComputePermutations(quad, &quad->Na, &quad->perms));
3510: if (Np != NULL) *Np = quad->Na;
3511: if (perm != NULL) *perm = quad->perms;
3512: PetscFunctionReturn(PETSC_SUCCESS);
3513: }
3515: /*@
3516: PetscDTCreateQuadratureByCell - Create default quadrature for a given cell
3518: Not collective
3520: Input Parameters:
3521: + ct - The integration domain
3522: . qorder - The desired quadrature order
3523: - qtype - The type of simplex quadrature, or PETSCDTSIMPLEXQUAD_DEFAULT
3525: Output Parameters:
3526: + q - The cell quadrature
3527: - fq - The face quadrature
3529: Level: developer
3531: .seealso: `PetscDTCreateDefaultQuadrature()`, `PetscFECreateDefault()`, `PetscDTGaussTensorQuadrature()`, `PetscDTSimplexQuadrature()`, `PetscDTTensorQuadratureCreate()`
3532: @*/
3533: PetscErrorCode PetscDTCreateQuadratureByCell(DMPolytopeType ct, PetscInt qorder, PetscDTSimplexQuadratureType qtype, PetscQuadrature *q, PetscQuadrature *fq)
3534: {
3535: const PetscInt quadPointsPerEdge = PetscMax(qorder + 1, 1);
3536: const PetscInt dim = DMPolytopeTypeGetDim(ct);
3538: PetscFunctionBegin;
3539: switch (ct) {
3540: case DM_POLYTOPE_POINT: {
3541: PetscReal *x, *w;
3543: PetscCall(PetscQuadratureCreate(PETSC_COMM_SELF, q));
3544: PetscCall(PetscQuadratureSetCellType(*q, ct));
3545: PetscCall(PetscQuadratureSetOrder(*q, 0));
3546: PetscCall(PetscMalloc1(1, &x));
3547: PetscCall(PetscMalloc1(1, &w));
3548: x[0] = 0.;
3549: w[0] = 1.;
3550: PetscCall(PetscQuadratureSetData(*q, dim, 1, 1, x, w));
3551: *fq = NULL;
3552: } break;
3553: case DM_POLYTOPE_SEGMENT:
3554: case DM_POLYTOPE_POINT_PRISM_TENSOR:
3555: case DM_POLYTOPE_QUADRILATERAL:
3556: case DM_POLYTOPE_SEG_PRISM_TENSOR:
3557: case DM_POLYTOPE_HEXAHEDRON:
3558: case DM_POLYTOPE_QUAD_PRISM_TENSOR:
3559: PetscCall(PetscDTGaussTensorQuadrature(dim, 1, quadPointsPerEdge, -1.0, 1.0, q));
3560: PetscCall(PetscDTGaussTensorQuadrature(dim - 1, 1, quadPointsPerEdge, -1.0, 1.0, fq));
3561: break;
3562: case DM_POLYTOPE_TRIANGLE:
3563: case DM_POLYTOPE_TETRAHEDRON:
3564: PetscCall(PetscDTSimplexQuadrature(dim, 2 * qorder, qtype, q));
3565: PetscCall(PetscDTSimplexQuadrature(dim - 1, 2 * qorder, qtype, fq));
3566: break;
3567: case DM_POLYTOPE_TRI_PRISM:
3568: case DM_POLYTOPE_TRI_PRISM_TENSOR: {
3569: PetscQuadrature q1, q2;
3571: // TODO: this should be able to use symmetric rules, but doing so causes tests to fail
3572: PetscCall(PetscDTSimplexQuadrature(2, 2 * qorder, PETSCDTSIMPLEXQUAD_CONIC, &q1));
3573: PetscCall(PetscDTGaussTensorQuadrature(1, 1, quadPointsPerEdge, -1.0, 1.0, &q2));
3574: PetscCall(PetscDTTensorQuadratureCreate(q1, q2, q));
3575: PetscCall(PetscQuadratureDestroy(&q2));
3576: *fq = q1;
3577: /* TODO Need separate quadratures for each face */
3578: } break;
3579: default:
3580: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "No quadrature for celltype %s", DMPolytopeTypes[PetscMin(ct, DM_POLYTOPE_UNKNOWN)]);
3581: }
3582: PetscFunctionReturn(PETSC_SUCCESS);
3583: }
3585: /*@
3586: PetscDTCreateDefaultQuadrature - Create default quadrature for a given cell
3588: Not collective
3590: Input Parameters:
3591: + ct - The integration domain
3592: - qorder - The desired quadrature order
3594: Output Parameters:
3595: + q - The cell quadrature
3596: - fq - The face quadrature
3598: Level: developer
3600: .seealso: `PetscDTCreateQuadratureByCell()`, `PetscFECreateDefault()`, `PetscDTGaussTensorQuadrature()`, `PetscDTSimplexQuadrature()`, `PetscDTTensorQuadratureCreate()`
3601: @*/
3602: PetscErrorCode PetscDTCreateDefaultQuadrature(DMPolytopeType ct, PetscInt qorder, PetscQuadrature *q, PetscQuadrature *fq)
3603: {
3604: PetscFunctionBegin;
3605: PetscCall(PetscDTCreateQuadratureByCell(ct, qorder, PETSCDTSIMPLEXQUAD_DEFAULT, q, fq));
3606: PetscFunctionReturn(PETSC_SUCCESS);
3607: }