xref: /libCEED/examples/ceed/ex1-volume.c (revision d37d859eee1531992dd1ea62f7bfb512322d748a)
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 1
9 //
10 // This example illustrates a simple usage of libCEED to compute the volume of a 3D body using matrix-free application of a mass 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 ex1-volume [CEED_DIR=</path/to/libceed>]
21 //
22 // Sample runs:
23 //
24 //     ./ex1-volume
25 //     ./ex1-volume -ceed /cpu/self
26 //     ./ex1-volume -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 mass operator to compute volume
38 
39 #include "ex1-volume.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[dim]);
48 int        BuildCartesianRestriction(Ceed ceed, CeedInt dim, CeedInt num_xyz[dim], 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[dim], 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 ? 8 * 16 : 256 * 1024;
95 
96   // Print the values of all options:
97   if (!test || help) {
98     // LCOV_EXCL_START
99     printf("Selected options: [command line option] : <current value>\n");
100     printf("  Ceed specification     [-c] : %s\n", ceed_spec);
101     printf("  Mesh dimension         [-d] : %" CeedInt_FMT "\n", dim);
102     printf("  Mesh degree            [-m] : %" CeedInt_FMT "\n", mesh_degree);
103     printf("  Solution degree        [-p] : %" CeedInt_FMT "\n", sol_degree);
104     printf("  Num. 1D quadrature pts [-q] : %" CeedInt_FMT "\n", num_qpts);
105     printf("  Approx. # unknowns     [-s] : %" CeedInt_FMT "\n", prob_size);
106     printf("  QFunction source       [-g] : %s\n", gallery ? "gallery" : "header");
107     if (help) {
108       printf("Test/quiet mode is %s\n", (test ? "ON" : "OFF (use -t to enable)"));
109       return 0;
110     }
111     printf("\n");
112     // LCOV_EXCL_STOP
113   }
114 
115   // Select appropriate backend and logical device based on the (-ceed) command line argument.
116   Ceed ceed;
117   CeedInit(ceed_spec, &ceed);
118 
119   // Construct the mesh and solution bases.
120   CeedBasis mesh_basis, sol_basis;
121   CeedBasisCreateTensorH1Lagrange(ceed, dim, num_comp_x, mesh_degree + 1, num_qpts, CEED_GAUSS, &mesh_basis);
122   CeedBasisCreateTensorH1Lagrange(ceed, dim, 1, sol_degree + 1, num_qpts, CEED_GAUSS, &sol_basis);
123 
124   // Determine the mesh size based on the given approximate problem size.
125   CeedInt num_xyz[dim];
126   GetCartesianMeshSize(dim, sol_degree, prob_size, num_xyz);
127   if (!test) {
128     // LCOV_EXCL_START
129     printf("Mesh size: nx = %" CeedInt_FMT, num_xyz[0]);
130     if (dim > 1) printf(", ny = %" CeedInt_FMT, num_xyz[1]);
131     if (dim > 2) printf(", nz = %" CeedInt_FMT, num_xyz[2]);
132     printf("\n");
133     // LCOV_EXCL_STOP
134   }
135 
136   // Build CeedElemRestriction objects describing the mesh and solution discrete representations.
137   CeedInt             mesh_size, sol_size;
138   CeedElemRestriction mesh_restriction, sol_restriction, q_data_restriction;
139   BuildCartesianRestriction(ceed, dim, num_xyz, mesh_degree, num_comp_x, &mesh_size, num_qpts, &mesh_restriction, NULL);
140   BuildCartesianRestriction(ceed, dim, num_xyz, sol_degree, 1, &sol_size, num_qpts, &sol_restriction, &q_data_restriction);
141   if (!test) {
142     // LCOV_EXCL_START
143     printf("Number of mesh nodes     : %" CeedInt_FMT "\n", mesh_size / dim);
144     printf("Number of solution nodes : %" CeedInt_FMT "\n", sol_size);
145     // LCOV_EXCL_STOP
146   }
147 
148   // Create a CeedVector with the mesh coordinates.
149   CeedVector mesh_coords;
150   CeedVectorCreate(ceed, mesh_size, &mesh_coords);
151   SetCartesianMeshCoords(dim, num_xyz, mesh_degree, mesh_coords);
152 
153   // Apply a transformation to the mesh.
154   CeedScalar exact_volume = TransformMeshCoords(dim, mesh_size, mesh_coords);
155 
156   // Context data to be passed to the 'build_mass' QFunction.
157   CeedQFunctionContext build_ctx;
158   struct BuildContext  build_ctx_data;
159   build_ctx_data.dim = build_ctx_data.space_dim = dim;
160   CeedQFunctionContextCreate(ceed, &build_ctx);
161   CeedQFunctionContextSetData(build_ctx, CEED_MEM_HOST, CEED_USE_POINTER, sizeof(build_ctx_data), &build_ctx_data);
162 
163   // Create the QFunction that builds the mass operator (i.e. computes its quadrature data) and set its context data.
164   CeedQFunction qf_build;
165   if (gallery) {
166     // This creates the QFunction via the gallery.
167     char name[13] = "";
168     snprintf(name, sizeof name, "Mass%" CeedInt_FMT "DBuild", dim);
169     CeedQFunctionCreateInteriorByName(ceed, name, &qf_build);
170   } else {
171     // This creates the QFunction directly.
172     CeedQFunctionCreateInterior(ceed, 1, build_mass, build_mass_loc, &qf_build);
173     CeedQFunctionAddInput(qf_build, "dx", num_comp_x * dim, CEED_EVAL_GRAD);
174     CeedQFunctionAddInput(qf_build, "weights", 1, CEED_EVAL_WEIGHT);
175     CeedQFunctionAddOutput(qf_build, "qdata", 1, CEED_EVAL_NONE);
176     CeedQFunctionSetContext(qf_build, build_ctx);
177   }
178 
179   // Create the operator that builds the quadrature data for the mass operator.
180   CeedOperator op_build;
181   CeedOperatorCreate(ceed, qf_build, CEED_QFUNCTION_NONE, CEED_QFUNCTION_NONE, &op_build);
182   CeedOperatorSetField(op_build, "dx", mesh_restriction, mesh_basis, CEED_VECTOR_ACTIVE);
183   CeedOperatorSetField(op_build, "weights", CEED_ELEMRESTRICTION_NONE, mesh_basis, CEED_VECTOR_NONE);
184   CeedOperatorSetField(op_build, "qdata", q_data_restriction, CEED_BASIS_COLLOCATED, CEED_VECTOR_ACTIVE);
185 
186   // Compute the quadrature data for the mass operator.
187   CeedVector q_data;
188   CeedInt    elem_qpts = CeedIntPow(num_qpts, dim);
189   CeedInt    num_elem  = 1;
190   for (CeedInt d = 0; d < dim; d++) num_elem *= num_xyz[d];
191   CeedVectorCreate(ceed, num_elem * elem_qpts, &q_data);
192   CeedOperatorApply(op_build, mesh_coords, q_data, CEED_REQUEST_IMMEDIATE);
193 
194   // Create the QFunction that defines the action of the mass operator.
195   CeedQFunction qf_apply;
196   if (gallery) {
197     // This creates the QFunction via the gallery.
198     CeedQFunctionCreateInteriorByName(ceed, "MassApply", &qf_apply);
199   } else {
200     // This creates the QFunction directly.
201     CeedQFunctionCreateInterior(ceed, 1, apply_mass, apply_mass_loc, &qf_apply);
202     CeedQFunctionAddInput(qf_apply, "u", 1, CEED_EVAL_INTERP);
203     CeedQFunctionAddInput(qf_apply, "qdata", 1, CEED_EVAL_NONE);
204     CeedQFunctionAddOutput(qf_apply, "v", 1, CEED_EVAL_INTERP);
205   }
206 
207   // Create the mass operator.
208   CeedOperator op_apply;
209   CeedOperatorCreate(ceed, qf_apply, CEED_QFUNCTION_NONE, CEED_QFUNCTION_NONE, &op_apply);
210   CeedOperatorSetField(op_apply, "u", sol_restriction, sol_basis, CEED_VECTOR_ACTIVE);
211   CeedOperatorSetField(op_apply, "qdata", q_data_restriction, CEED_BASIS_COLLOCATED, q_data);
212   CeedOperatorSetField(op_apply, "v", sol_restriction, sol_basis, CEED_VECTOR_ACTIVE);
213 
214   // Create auxiliary solution-size vectors.
215   CeedVector u, v;
216   CeedVectorCreate(ceed, sol_size, &u);
217   CeedVectorCreate(ceed, sol_size, &v);
218 
219   // Initialize 'u' and 'v' with ones.
220   CeedVectorSetValue(u, 1.0);
221 
222   // Compute the mesh volume using the mass operator: volume = 1^T \cdot M \cdot 1
223   CeedOperatorApply(op_apply, u, v, CEED_REQUEST_IMMEDIATE);
224 
225   // Compute and print the sum of the entries of 'v' giving the mesh volume.
226   CeedScalar volume = 0.;
227   {
228     const CeedScalar *v_array;
229     CeedVectorGetArrayRead(v, CEED_MEM_HOST, &v_array);
230     for (CeedInt i = 0; i < sol_size; i++) volume += v_array[i];
231     CeedVectorRestoreArrayRead(v, &v_array);
232   }
233   if (!test) {
234     // LCOV_EXCL_START
235     printf(" done.\n");
236     printf("Exact mesh volume    : % .14g\n", exact_volume);
237     printf("Computed mesh volume : % .14g\n", volume);
238     printf("Volume error         : % .14g\n", volume - exact_volume);
239     // LCOV_EXCL_STOP
240   } else {
241     CeedScalar tol = (dim == 1 ? 100. * CEED_EPSILON : dim == 2 ? 1E-5 : 1E-5);
242     if (fabs(volume - exact_volume) > tol) printf("Volume error : % .1e\n", volume - exact_volume);
243   }
244 
245   // Free dynamically allocated memory.
246   CeedVectorDestroy(&u);
247   CeedVectorDestroy(&v);
248   CeedVectorDestroy(&q_data);
249   CeedVectorDestroy(&mesh_coords);
250   CeedOperatorDestroy(&op_apply);
251   CeedQFunctionDestroy(&qf_apply);
252   CeedQFunctionContextDestroy(&build_ctx);
253   CeedOperatorDestroy(&op_build);
254   CeedQFunctionDestroy(&qf_build);
255   CeedElemRestrictionDestroy(&sol_restriction);
256   CeedElemRestrictionDestroy(&mesh_restriction);
257   CeedElemRestrictionDestroy(&q_data_restriction);
258   CeedBasisDestroy(&sol_basis);
259   CeedBasisDestroy(&mesh_basis);
260   CeedDestroy(&ceed);
261   return 0;
262 }
263 
264 int GetCartesianMeshSize(CeedInt dim, CeedInt degree, CeedInt prob_size, CeedInt num_xyz[dim]) {
265   // Use the approximate formula:
266   //    prob_size ~ num_elem * degree^dim
267   CeedInt num_elem = prob_size / CeedIntPow(degree, dim);
268   CeedInt s        = 0;  // find s: num_elem/2 < 2^s <= num_elem
269   while (num_elem > 1) {
270     num_elem /= 2;
271     s++;
272   }
273   CeedInt r = s % dim;
274   for (CeedInt d = 0; d < dim; d++) {
275     CeedInt sd = s / dim;
276     if (r > 0) {
277       sd++;
278       r--;
279     }
280     num_xyz[d] = 1 << sd;
281   }
282   return 0;
283 }
284 
285 int BuildCartesianRestriction(Ceed ceed, CeedInt dim, CeedInt num_xyz[dim], CeedInt degree, CeedInt num_comp, CeedInt *size, CeedInt num_qpts,
286                               CeedElemRestriction *restriction, CeedElemRestriction *q_data_restriction) {
287   CeedInt p         = degree + 1;
288   CeedInt num_nodes = CeedIntPow(p, dim);         // number of scalar nodes per element
289   CeedInt elem_qpts = CeedIntPow(num_qpts, dim);  // number of qpts per element
290   CeedInt nd[3], num_elem = 1, scalar_size = 1;
291   for (CeedInt d = 0; d < dim; d++) {
292     num_elem *= num_xyz[d];
293     nd[d] = num_xyz[d] * (p - 1) + 1;
294     scalar_size *= nd[d];
295   }
296   *size = scalar_size * num_comp;
297   // elem:         0             1                 n-1
298   //           |---*-...-*---|---*-...-*---|- ... -|--...--|
299   // num_nodes:   0   1    p-1  p  p+1       2*p             n*p
300   CeedInt *elem_nodes = malloc(sizeof(CeedInt) * num_elem * num_nodes);
301   for (CeedInt e = 0; e < num_elem; e++) {
302     CeedInt e_xyz[3] = {1, 1, 1}, re = e;
303     for (CeedInt d = 0; d < dim; d++) {
304       e_xyz[d] = re % num_xyz[d];
305       re /= num_xyz[d];
306     }
307     CeedInt *local_elem_nodes = elem_nodes + e * num_nodes;
308     for (CeedInt l_nodes = 0; l_nodes < num_nodes; l_nodes++) {
309       CeedInt g_nodes = 0, g_nodes_stride = 1, r_nodes = l_nodes;
310       for (CeedInt d = 0; d < dim; d++) {
311         g_nodes += (e_xyz[d] * (p - 1) + r_nodes % p) * g_nodes_stride;
312         g_nodes_stride *= nd[d];
313         r_nodes /= p;
314       }
315       local_elem_nodes[l_nodes] = g_nodes;
316     }
317   }
318   CeedElemRestrictionCreate(ceed, num_elem, num_nodes, num_comp, scalar_size, num_comp * scalar_size, CEED_MEM_HOST, CEED_COPY_VALUES, elem_nodes,
319                             restriction);
320   if (q_data_restriction)
321     CeedElemRestrictionCreateStrided(ceed, num_elem, elem_qpts, num_comp, num_comp * elem_qpts * num_elem, CEED_STRIDES_BACKEND, q_data_restriction);
322   free(elem_nodes);
323   return 0;
324 }
325 
326 int SetCartesianMeshCoords(CeedInt dim, CeedInt num_xyz[dim], CeedInt mesh_degree, CeedVector mesh_coords) {
327   CeedInt p = mesh_degree + 1;
328   CeedInt nd[3], num_elem = 1, scalar_size = 1;
329   for (CeedInt d = 0; d < dim; d++) {
330     num_elem *= num_xyz[d];
331     nd[d] = num_xyz[d] * (p - 1) + 1;
332     scalar_size *= nd[d];
333   }
334   CeedScalar *coords;
335   CeedVectorGetArrayWrite(mesh_coords, CEED_MEM_HOST, &coords);
336   CeedScalar *nodes = malloc(sizeof(CeedScalar) * p);
337   // The H1 basis uses Lobatto quadrature points as nodes.
338   CeedLobattoQuadrature(p, nodes, NULL);  // nodes are in [-1,1]
339   for (CeedInt i = 0; i < p; i++) nodes[i] = 0.5 + 0.5 * nodes[i];
340   for (CeedInt gs_nodes = 0; gs_nodes < scalar_size; gs_nodes++) {
341     CeedInt r_nodes = gs_nodes;
342     for (CeedInt d = 0; d < dim; d++) {
343       CeedInt d_1d                       = r_nodes % nd[d];
344       coords[gs_nodes + scalar_size * d] = ((d_1d / (p - 1)) + nodes[d_1d % (p - 1)]) / num_xyz[d];
345       r_nodes /= nd[d];
346     }
347   }
348   free(nodes);
349   CeedVectorRestoreArray(mesh_coords, &coords);
350   return 0;
351 }
352 
353 #ifndef M_PI
354 #define M_PI 3.14159265358979323846
355 #define M_PI_2 1.57079632679489661923
356 #endif
357 
358 CeedScalar TransformMeshCoords(CeedInt dim, CeedInt mesh_size, CeedVector mesh_coords) {
359   CeedScalar  exact_volume;
360   CeedScalar *coords;
361   CeedVectorGetArray(mesh_coords, CEED_MEM_HOST, &coords);
362   if (dim == 1) {
363     for (CeedInt i = 0; i < mesh_size; i++) {
364       // map [0,1] to [0,1] varying the mesh density
365       coords[i] = 0.5 + 1. / sqrt(3.) * sin((2. / 3.) * M_PI * (coords[i] - 0.5));
366     }
367     exact_volume = 1.;
368   } else {
369     CeedInt num_nodes = mesh_size / dim;
370     for (CeedInt i = 0; i < num_nodes; i++) {
371       // map (x,y) from [0,1]x[0,1] to the quarter annulus with polar
372       // coordinates, (r,phi) in [1,2]x[0,pi/2] with area = 3/4*pi
373       CeedScalar u = coords[i], v = coords[i + num_nodes];
374       u                     = 1. + u;
375       v                     = M_PI_2 * v;
376       coords[i]             = u * cos(v);
377       coords[i + num_nodes] = u * sin(v);
378     }
379     exact_volume = 3. / 4. * M_PI;
380   }
381   CeedVectorRestoreArray(mesh_coords, &coords);
382   return exact_volume;
383 }
384