xref: /libCEED/tests/t409-qfunction.c (revision 41bdf1c9f3b677ca0cd3704eec13319d41b7356c)
1 /// @file
2 /// Test creation, evaluation, and destruction for QFunction
3 /// \test Test creation, evaluation, and destruction for QFunction
4 #include <ceed.h>
5 #include <math.h>
6 
7 #include "t409-qfunction.h"
8 
9 int main(int argc, char **argv) {
10   Ceed ceed;
11   CeedVector in[16], out[16];
12   CeedVector U, V;
13   CeedQFunction qf;
14   CeedQFunctionContext ctx;
15   CeedInt Q = 8;
16   const CeedScalar *v;
17   bool is_writable = true;
18   CeedScalar ctx_data[5] = {1, 2, 3, 4, 5};
19 
20   CeedInit(argv[1], &ceed);
21 
22   CeedQFunctionCreateInterior(ceed, 1, scale, scale_loc, &qf);
23   CeedQFunctionAddInput(qf, "u", 1, CEED_EVAL_INTERP);
24   CeedQFunctionAddOutput(qf, "v", 1, CEED_EVAL_INTERP);
25 
26   CeedQFunctionContextCreate(ceed, &ctx);
27   CeedQFunctionContextSetData(ctx, CEED_MEM_HOST, CEED_COPY_VALUES,
28                               sizeof(ctx_data), &ctx_data);
29   CeedQFunctionSetContext(qf, ctx);
30   CeedQFunctionSetContextWritable(qf, is_writable);
31 
32   CeedVectorCreate(ceed, Q, &U);
33   CeedVectorSetValue(U, 1.0);
34   CeedVectorCreate(ceed, Q, &V);
35   CeedVectorSetValue(V, 0.0);
36 
37   {
38     in[0] = U;
39     out[0] = V;
40     CeedQFunctionApply(qf, Q, in, out);
41   }
42 
43   CeedVectorGetArrayRead(V, CEED_MEM_HOST, &v);
44   for (CeedInt i=0; i<Q; i++)
45     if (fabs(v[i] - ctx_data[1]) > 100.*CEED_EPSILON)
46       // LCOV_EXCL_START
47       printf("v[%" CeedInt_FMT "] %f != 2.0\n", i, v[i]);
48   // LCOV_EXCL_STOP
49   CeedVectorRestoreArrayRead(V, &v);
50 
51   // Check for written context data
52   CeedScalar *ctx_data_new;
53   CeedQFunctionContextGetDataRead(ctx, CEED_MEM_HOST, &ctx_data_new);
54   if (ctx_data_new[0] != 42)
55     // LCOV_EXCL_START
56     printf("Context data not written: %f != 42\n", ctx_data_new[0]);
57   // LCOV_EXCL_STOP
58   CeedQFunctionContextRestoreDataRead(ctx, &ctx_data_new);
59 
60   // Assert that context will not be written
61   // Note: The interface cannot enforce this in user code
62   //   so setting is_writable == false and then calling
63   //   CeedQFunctionApply to mutate the context would lead
64   //   to inconsistent data on the GPU.
65   //   Only the `/cpu/self/memcheck/*` backends verify that
66   //   read-only access resulted in no changes to the context data
67   CeedQFunctionContextGetData(ctx, CEED_MEM_HOST, &ctx_data_new);
68   ctx_data_new[0] = 5;
69   CeedQFunctionContextRestoreData(ctx, &ctx_data_new);
70   is_writable = false;
71   CeedQFunctionSetContextWritable(qf, is_writable);
72   {
73     in[0] = U;
74     out[0] = V;
75     // Will only error in `/cpu/self/memcheck/*` backends
76     CeedQFunctionApply(qf, Q, in, out);
77   }
78 
79   CeedVectorDestroy(&U);
80   CeedVectorDestroy(&V);
81   CeedQFunctionDestroy(&qf);
82   CeedQFunctionContextDestroy(&ctx);
83   CeedDestroy(&ceed);
84   return 0;
85 }
86