xref: /libCEED/tests/t312-basis.c (revision d99fa3c5cd91a1690aedf0679cbf290d44fec74c)
1 /// @file
2 /// Test polynomial interpolation in 1D
3 /// \test Test polynomial interpolation in 1D
4 #include <ceed.h>
5 #include <math.h>
6 
7 #define ALEN(a) (sizeof(a) / sizeof((a)[0]))
8 
9 static CeedScalar PolyEval(CeedScalar x, CeedInt n, const CeedScalar *p) {
10   CeedScalar y = p[n-1];
11   for (CeedInt i=n-2; i>=0; i--) y = y*x + p[i];
12   return y;
13 }
14 
15 int main(int argc, char **argv) {
16   Ceed ceed;
17   CeedVector X, Xq, U, Uq, W;
18   CeedBasis bxl, bxg, bug;
19   CeedInt Q = 6;
20   const CeedScalar p[6] = {1, 2, 3, 4, 5, 6}; // 1 + 2x + 3x^2 + ...
21   const CeedScalar *xq, *uq, *w;
22   CeedScalar u[Q], x[2], sum, error, pint[ALEN(p)+1];
23 
24   CeedInit(argv[1], &ceed);
25 
26   CeedVectorCreate(ceed, 2, &X);
27   CeedVectorCreate(ceed, Q, &Xq);
28   CeedVectorSetValue(Xq, 0);
29   CeedVectorCreate(ceed, Q, &U);
30   CeedVectorCreate(ceed, Q, &Uq);
31   CeedVectorSetValue(Uq, 0);
32   CeedVectorCreate(ceed, Q, &W);
33   CeedVectorSetValue(W, 0);
34 
35   CeedBasisCreateTensorH1Lagrange(ceed, 1, 1, 2, Q, CEED_GAUSS_LOBATTO, &bxl);
36 
37   for (int i = 0; i < 2; i++)
38     x[i] = CeedIntPow(-1, i+1);
39   CeedVectorSetArray(X, CEED_MEM_HOST, CEED_USE_POINTER, x);
40 
41   CeedBasisApply(bxl, 1, CEED_NOTRANSPOSE, CEED_EVAL_INTERP, X, Xq);
42 
43   CeedVectorGetArrayRead(Xq, CEED_MEM_HOST, &xq);
44   for (CeedInt i=0; i<Q; i++)
45     u[i] = PolyEval(xq[i], ALEN(p), p);
46   CeedVectorRestoreArrayRead(Xq, &xq);
47   CeedVectorSetArray(U, CEED_MEM_HOST, CEED_USE_POINTER, u);
48 
49   CeedBasisCreateTensorH1Lagrange(ceed, 1, 1, 2, Q, CEED_GAUSS, &bxg);
50   CeedBasisCreateTensorH1Lagrange(ceed, 1, 1, Q, Q, CEED_GAUSS, &bug);
51 
52   CeedBasisApply(bxg, 1, CEED_NOTRANSPOSE, CEED_EVAL_INTERP, X, Xq);
53   CeedBasisApply(bug, 1, CEED_NOTRANSPOSE, CEED_EVAL_INTERP, U, Uq);
54   CeedBasisApply(bug, 1, CEED_NOTRANSPOSE, CEED_EVAL_WEIGHT,
55                  CEED_VECTOR_NONE, W);
56 
57   CeedVectorGetArrayRead(W, CEED_MEM_HOST, &w);
58   CeedVectorGetArrayRead(Uq, CEED_MEM_HOST, &uq);
59   sum = 0;
60   for (CeedInt i=0; i<Q; i++)
61     sum += w[i] * uq[i];
62   CeedVectorRestoreArrayRead(W, &w);
63   CeedVectorRestoreArrayRead(Uq, &uq);
64 
65   pint[0] = 0;
66   for (CeedInt i=0; i<(int)ALEN(p); i++)
67     pint[i+1] = p[i] / (i+1);
68   error = sum - PolyEval(1, ALEN(pint), pint) + PolyEval(-1, ALEN(pint), pint);
69   if (error > 1.E-10)
70     // LCOV_EXCL_START
71     printf("Error %e  sum %g  exact %g\n", error, sum,
72            PolyEval(1, ALEN(pint), pint) - PolyEval(-1, ALEN(pint), pint));
73   // LCOV_EXCL_STOP
74 
75   CeedVectorDestroy(&X);
76   CeedVectorDestroy(&Xq);
77   CeedVectorDestroy(&U);
78   CeedVectorDestroy(&Uq);
79   CeedVectorDestroy(&W);
80   CeedBasisDestroy(&bxl);
81   CeedBasisDestroy(&bxg);
82   CeedBasisDestroy(&bug);
83   CeedDestroy(&ceed);
84   return 0;
85 }
86