xref: /libCEED/examples/ceed/ex2-surface.c (revision ce18bed930e8f3bfebcf709a18844aba97fe4630)
1 // Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and other CEED contributors.
2 // All Rights Reserved. See the top-level LICENSE and NOTICE files for details.
3 //
4 // SPDX-License-Identifier: BSD-2-Clause
5 //
6 // This file is part of CEED:  http://github.com/ceed
7 
8 //                             libCEED Example 2
9 //
10 // This example illustrates a simple usage of libCEED to compute the surface
11 // area of a 3D body using matrix-free application of a diffusion operator.
12 // Arbitrary mesh and solution degrees in 1D, 2D and 3D are supported from the
13 // same code.
14 //
15 // The example has no dependencies, and is designed to be self-contained. For
16 // additional examples that use external discretization libraries (MFEM, PETSc,
17 // etc.) see the subdirectories in libceed/examples.
18 //
19 // All libCEED objects use a Ceed device object constructed based on a command
20 // line argument (-ceed).
21 //
22 // Build with:
23 //
24 //     make ex2-surface [CEED_DIR=</path/to/libceed>]
25 //
26 // Sample runs:
27 //
28 //     ./ex2-surface
29 //     ./ex2-surface -ceed /cpu/self
30 //     ./ex2-surface -ceed /gpu/cuda
31 //
32 // Next line is grep'd from tap.sh to set its arguments
33 // Test in 1D-3D
34 //TESTARGS(name="1D_user_QFunction") -ceed {ceed_resource} -d 1 -t
35 //TESTARGS(name="2D_user_QFunction") -ceed {ceed_resource} -d 2 -t
36 //TESTARGS(name="3D_user_QFunction") -ceed {ceed_resource} -d 3 -t
37 //TESTARGS(name="1D_Gallery_QFunction") -ceed {ceed_resource} -d 1 -t -g
38 //TESTARGS(name="2D_Gallery_QFunction") -ceed {ceed_resource} -d 2 -t -g
39 //TESTARGS(name="3D_Gallery_QFunction") -ceed {ceed_resource} -d 3 -t -g
40 
41 /// @file
42 /// libCEED example using diffusion operator to compute surface area
43 
44 #include <ceed.h>
45 #include <math.h>
46 #include <stdlib.h>
47 #include <string.h>
48 #include "ex2-surface.h"
49 
50 // Auxiliary functions.
51 int GetCartesianMeshSize(int dim, int degree, int prob_size, int num_xyz[3]);
52 int BuildCartesianRestriction(Ceed ceed, int dim, int num_xyz[3], int degree,
53                               int num_comp, CeedInt *size, CeedInt num_qpts,
54                               CeedElemRestriction *restr,
55                               CeedElemRestriction *restr_i);
56 int SetCartesianMeshCoords(int dim, int num_xyz[3], int mesh_degree,
57                            CeedVector mesh_coords);
58 CeedScalar TransformMeshCoords(int dim, int mesh_size, CeedVector mesh_coords);
59 
60 int main(int argc, const char *argv[]) {
61   const char *ceed_spec = "/cpu/self";
62   int dim         = 3;              // dimension of the mesh
63   int num_comp_x  = 3;              // number of x components
64   int mesh_degree = 4;              // polynomial degree for the mesh
65   int sol_degree  = 4;              // polynomial degree for the solution
66   int num_qpts    = sol_degree + 2; // number of 1D quadrature points
67   int prob_size   = -1;             // approximate problem size
68   int help = 0, test = 0, gallery = 0;
69 
70   // Process command line arguments.
71   for (int ia = 1; ia < argc; ia++) {
72     // LCOV_EXCL_START
73     int next_arg = ((ia+1) < argc), parse_error = 0;
74     if (!strcmp(argv[ia],"-h")) {
75       help = 1;
76     } else if (!strcmp(argv[ia],"-c") || !strcmp(argv[ia],"-ceed")) {
77       parse_error = next_arg ? ceed_spec = argv[++ia], 0 : 1;
78     } else if (!strcmp(argv[ia],"-d")) {
79       parse_error = next_arg ? dim = atoi(argv[++ia]), 0 : 1;
80       num_comp_x = dim;
81     } else if (!strcmp(argv[ia],"-m")) {
82       parse_error = next_arg ? mesh_degree = atoi(argv[++ia]), 0 : 1;
83     } else if (!strcmp(argv[ia],"-p")) {
84       parse_error = next_arg ? sol_degree = atoi(argv[++ia]), 0 : 1;
85     } else if (!strcmp(argv[ia],"-q")) {
86       parse_error = next_arg ? num_qpts = atoi(argv[++ia]), 0 : 1;
87     } else if (!strcmp(argv[ia],"-s")) {
88       parse_error = next_arg ? prob_size = atoi(argv[++ia]), 0 : 1;
89     } else if (!strcmp(argv[ia],"-t")) {
90       test = 1;
91     } else if (!strcmp(argv[ia],"-g")) {
92       gallery = 1;
93     }
94     if (parse_error) {
95       printf("Error parsing command line options.\n");
96       return 1;
97     }
98     // LCOV_EXCL_STOP
99   }
100   if (prob_size < 0) prob_size = test ? 16*16*dim*dim : 256*1024;
101 
102   // Set mesh_degree = sol_degree.
103   mesh_degree = fmax(mesh_degree, sol_degree);
104   sol_degree = mesh_degree;
105 
106   // Print the values of all options:
107   if (!test || help) {
108     // LCOV_EXCL_START
109     printf("Selected options: [command line option] : <current value>\n");
110     printf("  Ceed specification [-c] : %s\n", ceed_spec);
111     printf("  Mesh dimension     [-d] : %d\n", dim);
112     printf("  Mesh degree        [-m] : %d\n", mesh_degree);
113     printf("  Solution degree    [-p] : %d\n", sol_degree);
114     printf("  Num. 1D quadr. pts [-q] : %d\n", num_qpts);
115     printf("  Approx. # unknowns [-s] : %d\n", prob_size);
116     printf("  QFunction source   [-g] : %s\n", gallery?"gallery":"header");
117     if (help) {
118       printf("Test/quiet mode is %s\n", (test?"ON":"OFF (use -t to enable)"));
119       return 0;
120     }
121     printf("\n");
122     // LCOV_EXCL_STOP
123   }
124 
125   // Select appropriate backend and logical device based on the <ceed-spec>
126   // command line argument.
127   Ceed ceed;
128   CeedInit(ceed_spec, &ceed);
129 
130   // Construct the mesh and solution bases.
131   CeedBasis mesh_basis, sol_basis;
132   CeedBasisCreateTensorH1Lagrange(ceed, dim, num_comp_x, mesh_degree + 1,
133                                   num_qpts, CEED_GAUSS, &mesh_basis);
134   CeedBasisCreateTensorH1Lagrange(ceed, dim, 1, sol_degree + 1, num_qpts,
135                                   CEED_GAUSS, &sol_basis);
136 
137   // Determine the mesh size based on the given approximate problem size.
138   int num_xyz[3];
139   GetCartesianMeshSize(dim, sol_degree, prob_size, num_xyz);
140 
141   if (!test) {
142     // LCOV_EXCL_START
143     printf("Mesh size: nx = %d", num_xyz[0]);
144     if (dim > 1) { printf(", ny = %d", num_xyz[1]); }
145     if (dim > 2) { printf(", nz = %d", num_xyz[2]); }
146     printf("\n");
147     // LCOV_EXCL_STOP
148   }
149 
150   // Build CeedElemRestriction objects describing the mesh and solution discrete
151   // representations.
152   CeedInt mesh_size, sol_size;
153   CeedElemRestriction mesh_restr, sol_restr, q_data_restr_i;
154   BuildCartesianRestriction(ceed, dim, num_xyz, mesh_degree, num_comp_x,
155                             &mesh_size, num_qpts, &mesh_restr, NULL);
156   BuildCartesianRestriction(ceed, dim, num_xyz, sol_degree, dim*(dim+1)/2,
157                             &sol_size, num_qpts, NULL, &q_data_restr_i);
158   BuildCartesianRestriction(ceed, dim, num_xyz, sol_degree, 1, &sol_size,
159                             num_qpts, &sol_restr, NULL);
160   if (!test) {
161     // LCOV_EXCL_START
162     printf("Number of mesh nodes     : %d\n", mesh_size/dim);
163     printf("Number of solution nodes : %d\n", sol_size);
164     // LCOV_EXCL_STOP
165   }
166 
167   // Create a CeedVector with the mesh coordinates.
168   CeedVector mesh_coords;
169   CeedVectorCreate(ceed, mesh_size, &mesh_coords);
170   SetCartesianMeshCoords(dim, num_xyz, mesh_degree, mesh_coords);
171 
172   // Apply a transformation to the mesh.
173   CeedScalar exact_sa = TransformMeshCoords(dim, mesh_size, mesh_coords);
174 
175   // Context data to be passed to the 'f_build_diff' QFunction.
176   CeedQFunctionContext build_ctx;
177   struct BuildContext build_ctx_data;
178   build_ctx_data.dim = build_ctx_data.space_dim = dim;
179   CeedQFunctionContextCreate(ceed, &build_ctx);
180   CeedQFunctionContextSetData(build_ctx, CEED_MEM_HOST, CEED_USE_POINTER,
181                               sizeof(build_ctx_data), &build_ctx_data);
182 
183   // Create the QFunction that builds the diffusion operator (i.e. computes its
184   // quadrature data) and set its context data.
185   CeedQFunction qf_build;
186   switch (gallery) {
187   case 0:
188     // This creates the QFunction directly.
189     CeedQFunctionCreateInterior(ceed, 1, f_build_diff,
190                                 f_build_diff_loc, &qf_build);
191     CeedQFunctionAddInput(qf_build, "dx", num_comp_x*dim, CEED_EVAL_GRAD);
192     CeedQFunctionAddInput(qf_build, "weights", 1, CEED_EVAL_WEIGHT);
193     CeedQFunctionAddOutput(qf_build, "qdata", dim*(dim+1)/2, CEED_EVAL_NONE);
194     CeedQFunctionSetContext(qf_build, build_ctx);
195     break;
196   case 1: {
197     // This creates the QFunction via the gallery.
198     char name[16] = "";
199     snprintf(name, sizeof name, "Poisson%dDBuild", dim);
200     CeedQFunctionCreateInteriorByName(ceed, name, &qf_build);
201     break;
202   }
203   }
204 
205   // Create the operator that builds the quadrature data for the diffusion
206   // operator.
207   CeedOperator op_build;
208   CeedOperatorCreate(ceed, qf_build, CEED_QFUNCTION_NONE,
209                      CEED_QFUNCTION_NONE, &op_build);
210   CeedOperatorSetField(op_build, "dx", mesh_restr, mesh_basis,
211                        CEED_VECTOR_ACTIVE);
212   CeedOperatorSetField(op_build, "weights", CEED_ELEMRESTRICTION_NONE,
213                        mesh_basis, CEED_VECTOR_NONE);
214   CeedOperatorSetField(op_build, "qdata", q_data_restr_i,
215                        CEED_BASIS_COLLOCATED, CEED_VECTOR_ACTIVE);
216 
217   // Compute the quadrature data for the diffusion operator.
218   CeedVector q_data;
219   CeedInt elem_qpts = CeedIntPow(num_qpts, dim);
220   CeedInt num_elem = 1;
221   for (int d = 0; d < dim; d++)
222     num_elem *= num_xyz[d];
223   CeedVectorCreate(ceed, num_elem*elem_qpts*dim*(dim+1)/2, &q_data);
224   CeedOperatorApply(op_build, mesh_coords, q_data,
225                     CEED_REQUEST_IMMEDIATE);
226 
227   // Create the QFunction that defines the action of the diffusion operator.
228   CeedQFunction qf_apply;
229   switch (gallery) {
230   case 0:
231     // This creates the QFunction directly.
232     CeedQFunctionCreateInterior(ceed, 1, f_apply_diff,
233                                 f_apply_diff_loc, &qf_apply);
234     CeedQFunctionAddInput(qf_apply, "du", dim, CEED_EVAL_GRAD);
235     CeedQFunctionAddInput(qf_apply, "qdata", dim*(dim+1)/2, CEED_EVAL_NONE);
236     CeedQFunctionAddOutput(qf_apply, "dv", dim, CEED_EVAL_GRAD);
237     CeedQFunctionSetContext(qf_apply, build_ctx);
238     break;
239   case 1: {
240     // This creates the QFunction via the gallery.
241     char name[16] = "";
242     snprintf(name, sizeof name, "Poisson%dDApply", dim);
243     CeedQFunctionCreateInteriorByName(ceed, name, &qf_apply);
244     break;
245   }
246   }
247 
248   // Create the diffusion operator.
249   CeedOperator op_apply;
250   CeedOperatorCreate(ceed, qf_apply, CEED_QFUNCTION_NONE,
251                      CEED_QFUNCTION_NONE, &op_apply);
252   CeedOperatorSetField(op_apply, "du", sol_restr, sol_basis, CEED_VECTOR_ACTIVE);
253   CeedOperatorSetField(op_apply, "qdata", q_data_restr_i, CEED_BASIS_COLLOCATED,
254                        q_data);
255   CeedOperatorSetField(op_apply, "dv", sol_restr, sol_basis, CEED_VECTOR_ACTIVE);
256 
257   // Create auxiliary solution-size vectors.
258   CeedVector u, v;
259   CeedVectorCreate(ceed, sol_size, &u);
260   CeedVectorCreate(ceed, sol_size, &v);
261 
262   // Initialize 'u' with sum of coordinates, x+y+z.
263   CeedScalar *u_array;
264   const CeedScalar *x_array;
265   CeedVectorGetArrayWrite(u, CEED_MEM_HOST, &u_array);
266   CeedVectorGetArrayRead(mesh_coords, CEED_MEM_HOST, &x_array);
267   for (CeedInt i = 0; i < sol_size; i++) {
268     u_array[i] = 0;
269     for (CeedInt d = 0; d < dim; d++)
270       u_array[i] += x_array[i+d*sol_size];
271   }
272   CeedVectorRestoreArray(u, &u_array);
273   CeedVectorRestoreArrayRead(mesh_coords, &x_array);
274 
275   // Compute the mesh surface area using the diff operator:
276   //                                             sa = 1^T \cdot abs( K \cdot x).
277   CeedOperatorApply(op_apply, u, v, CEED_REQUEST_IMMEDIATE);
278 
279   // Compute and print the sum of the entries of 'v' giving the mesh surface area.
280   const CeedScalar *v_array;
281   CeedVectorGetArrayRead(v, CEED_MEM_HOST, &v_array);
282   CeedScalar sa = 0.;
283   for (CeedInt i = 0; i < sol_size; i++) {
284     sa += fabs(v_array[i]);
285   }
286   CeedVectorRestoreArrayRead(v, &v_array);
287   if (!test) {
288     // LCOV_EXCL_START
289     printf(" done.\n");
290     printf("Exact mesh surface area    : % .14g\n", exact_sa);
291     printf("Computed mesh surface area : % .14g\n", sa);
292     printf("Surface area error         : % .14g\n", sa-exact_sa);
293     // LCOV_EXCL_STOP
294   } else {
295     CeedScalar tol = (dim==1 ? 10000.*CEED_EPSILON : dim==2 ? 1E-1 : 1E-1);
296     if (fabs(sa-exact_sa)>tol)
297       // LCOV_EXCL_START
298       printf("Surface area error         : % .14g\n", sa-exact_sa);
299     // LCOV_EXCL_STOP
300   }
301 
302   // Free dynamically allocated memory.
303   CeedVectorDestroy(&u);
304   CeedVectorDestroy(&v);
305   CeedVectorDestroy(&q_data);
306   CeedVectorDestroy(&mesh_coords);
307   CeedOperatorDestroy(&op_apply);
308   CeedQFunctionDestroy(&qf_apply);
309   CeedQFunctionContextDestroy(&build_ctx);
310   CeedOperatorDestroy(&op_build);
311   CeedQFunctionDestroy(&qf_build);
312   CeedElemRestrictionDestroy(&sol_restr);
313   CeedElemRestrictionDestroy(&mesh_restr);
314   CeedElemRestrictionDestroy(&q_data_restr_i);
315   CeedBasisDestroy(&sol_basis);
316   CeedBasisDestroy(&mesh_basis);
317   CeedDestroy(&ceed);
318   return 0;
319 }
320 
321 int GetCartesianMeshSize(int dim, int degree, int prob_size, int num_xyz[3]) {
322   // Use the approximate formula:
323   //    prob_size ~ num_elem * degree^dim
324   CeedInt num_elem = prob_size / CeedIntPow(degree, dim);
325   CeedInt s = 0;  // find s: num_elem/2 < 2^s <= num_elem
326   while (num_elem > 1) {
327     num_elem /= 2;
328     s++;
329   }
330   CeedInt r = s%dim;
331   for (int d = 0; d < dim; d++) {
332     int sd = s/dim;
333     if (r > 0) { sd++; r--; }
334     num_xyz[d] = 1 << sd;
335   }
336   return 0;
337 }
338 
339 int BuildCartesianRestriction(Ceed ceed, int dim, int num_xyz[3], int degree,
340                               int num_comp, CeedInt *size, CeedInt num_qpts,
341                               CeedElemRestriction *restr,
342                               CeedElemRestriction *restr_i) {
343   CeedInt p = degree + 1;
344   CeedInt num_nodes = CeedIntPow(p, dim); // number of scalar nodes per element
345   CeedInt elem_qpts = CeedIntPow(num_qpts, dim); // number of qpts per element
346   CeedInt nd[3], num_elem = 1, scalar_size = 1;
347   for (int d = 0; d < dim; d++) {
348     num_elem *= num_xyz[d];
349     nd[d] = num_xyz[d] * (p - 1) + 1;
350     scalar_size *= nd[d];
351   }
352   *size = scalar_size*num_comp;
353   // elem:         0             1                 n-1
354   //           |---*-...-*---|---*-...-*---|- ... -|--...--|
355   // num_nodes:   0   1    p-1  p  p+1       2*p             n*p
356   CeedInt *el_nodes = malloc(sizeof(CeedInt)*num_elem*num_nodes);
357   for (CeedInt e = 0; e < num_elem; e++) {
358     CeedInt e_xyz[3] = {1, 1, 1}, re = e;
359     for (int d = 0; d < dim; d++) { e_xyz[d] = re%num_xyz[d]; re /= num_xyz[d]; }
360     CeedInt *loc_el_nodes = el_nodes + e*num_nodes;
361     for (int l_nodes = 0; l_nodes < num_nodes; l_nodes++) {
362       CeedInt g_nodes = 0, g_nodes_stride = 1, r_nodes = l_nodes;
363       for (int d = 0; d < dim; d++) {
364         g_nodes += (e_xyz[d] * (p - 1) + r_nodes % p) * g_nodes_stride;
365         g_nodes_stride *= nd[d];
366         r_nodes /= p;
367       }
368       loc_el_nodes[l_nodes] = g_nodes;
369     }
370   }
371   if (restr)
372     CeedElemRestrictionCreate(ceed, num_elem, num_nodes, num_comp, scalar_size,
373                               num_comp * scalar_size, CEED_MEM_HOST,
374                               CEED_COPY_VALUES, el_nodes, restr);
375   free(el_nodes);
376 
377   if (restr_i) {
378     CeedElemRestrictionCreateStrided(ceed, num_elem, elem_qpts,
379                                      num_comp, num_comp * elem_qpts * num_elem,
380                                      CEED_STRIDES_BACKEND, restr_i);
381   }
382 
383   return 0;
384 }
385 
386 int SetCartesianMeshCoords(int dim, int num_xyz[3], int mesh_degree,
387                            CeedVector mesh_coords) {
388   CeedInt p = mesh_degree + 1;
389   CeedInt nd[3], num_elem = 1, scalar_size = 1;
390   for (int d = 0; d < dim; d++) {
391     num_elem *= num_xyz[d];
392     nd[d] = num_xyz[d] * (p - 1) + 1;
393     scalar_size *= nd[d];
394   }
395   CeedScalar *coords;
396   CeedVectorGetArrayWrite(mesh_coords, CEED_MEM_HOST, &coords);
397   CeedScalar *nodes = malloc(sizeof(CeedScalar) * p);
398   // The H1 basis uses Lobatto quadrature points as nodes.
399   CeedLobattoQuadrature(p, nodes, NULL); // nodes are in [-1,1]
400   for (CeedInt i = 0; i < p; i++) { nodes[i] = 0.5 + 0.5 * nodes[i]; }
401   for (CeedInt gs_nodes = 0; gs_nodes < scalar_size; gs_nodes++) {
402     CeedInt r_nodes = gs_nodes;
403     for (int d = 0; d < dim; d++) {
404       CeedInt d1d = r_nodes % nd[d];
405       coords[gs_nodes + scalar_size * d] = ((d1d / (p - 1)) + nodes[d1d %
406                                             (p - 1)]) / num_xyz[d];
407       r_nodes /= nd[d];
408     }
409   }
410   free(nodes);
411   CeedVectorRestoreArray(mesh_coords, &coords);
412   return 0;
413 }
414 
415 #ifndef M_PI
416 #define M_PI    3.14159265358979323846
417 #endif
418 
419 CeedScalar TransformMeshCoords(int dim, int mesh_size, CeedVector mesh_coords) {
420   CeedScalar exact_sa = (dim == 1 ? 2 : dim == 2 ? 4 : 6);
421   CeedScalar *coords;
422 
423   CeedVectorGetArray(mesh_coords, CEED_MEM_HOST, &coords);
424   for (CeedInt i = 0; i < mesh_size; i++) {
425     // map [0,1] to [0,1] varying the mesh density
426     coords[i] = 0.5 + 1./sqrt(3.) * sin((2./3.) * M_PI * (coords[i] - 0.5));
427   }
428   CeedVectorRestoreArray(mesh_coords, &coords);
429 
430   return exact_sa;
431 }
432