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