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