xref: /libCEED/examples/ceed/ex1-volume.c (revision 5ebd836c59d60a2e5e1cb67f6731404c7da26f85)
1 // Copyright (c) 2017-2024, 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 <stdio.h>
44 #include <stdlib.h>
45 #include <string.h>
46 
47 // Auxiliary functions
48 int        GetCartesianMeshSize(CeedInt dim, CeedInt degree, CeedInt prob_size, CeedInt num_xyz[dim]);
49 int        BuildCartesianRestriction(Ceed ceed, CeedInt dim, CeedInt num_xyz[dim], CeedInt degree, CeedInt num_comp, CeedInt *size, CeedInt num_qpts,
50                                      CeedElemRestriction *restriction, CeedElemRestriction *q_data_restriction);
51 int        SetCartesianMeshCoords(CeedInt dim, CeedInt num_xyz[dim], CeedInt mesh_degree, CeedVector mesh_coords);
52 CeedScalar TransformMeshCoords(CeedInt dim, CeedInt mesh_size, CeedVector mesh_coords);
53 
54 // Main example
55 int main(int argc, const char *argv[]) {
56   const char *ceed_spec   = "/cpu/self";
57   CeedInt     dim         = 3;               // dimension of the mesh
58   CeedInt     num_comp_x  = 3;               // number of x components
59   CeedInt     mesh_degree = 4;               // polynomial degree for the mesh
60   CeedInt     sol_degree  = 4;               // polynomial degree for the solution
61   CeedInt     num_qpts    = sol_degree + 2;  // number of 1D quadrature points
62   CeedInt     prob_size   = -1;              // approximate problem size
63   CeedInt     help = 0, test = 0, gallery = 0;
64 
65   // Process command line arguments.
66   for (int ia = 1; ia < argc; ia++) {
67     // LCOV_EXCL_START
68     int next_arg = ((ia + 1) < argc), parse_error = 0;
69     if (!strcmp(argv[ia], "-h")) {
70       help = 1;
71     } else if (!strcmp(argv[ia], "-c") || !strcmp(argv[ia], "-ceed")) {
72       parse_error = next_arg ? ceed_spec = argv[++ia], 0 : 1;
73     } else if (!strcmp(argv[ia], "-d")) {
74       parse_error = next_arg ? dim = atoi(argv[++ia]), 0 : 1;
75       num_comp_x                   = dim;
76     } else if (!strcmp(argv[ia], "-m")) {
77       parse_error = next_arg ? mesh_degree = atoi(argv[++ia]), 0 : 1;
78     } else if (!strcmp(argv[ia], "-p")) {
79       parse_error = next_arg ? sol_degree = atoi(argv[++ia]), 0 : 1;
80     } else if (!strcmp(argv[ia], "-q")) {
81       parse_error = next_arg ? num_qpts = atoi(argv[++ia]), 0 : 1;
82     } else if (!strcmp(argv[ia], "-s")) {
83       parse_error = next_arg ? prob_size = atoi(argv[++ia]), 0 : 1;
84     } else if (!strcmp(argv[ia], "-t")) {
85       test = 1;
86     } else if (!strcmp(argv[ia], "-g")) {
87       gallery = 1;
88     }
89     if (parse_error) {
90       printf("Error parsing command line options.\n");
91       return 1;
92     }
93     // LCOV_EXCL_STOP
94   }
95   if (prob_size < 0) prob_size = test ? 8 * 16 : 256 * 1024;
96 
97   // Print the values of all options:
98   if (!test || help) {
99     // LCOV_EXCL_START
100     printf("Selected options: [command line option] : <current value>\n");
101     printf("  Ceed specification     [-c] : %s\n", ceed_spec);
102     printf("  Mesh dimension         [-d] : %" CeedInt_FMT "\n", dim);
103     printf("  Mesh degree            [-m] : %" CeedInt_FMT "\n", mesh_degree);
104     printf("  Solution degree        [-p] : %" CeedInt_FMT "\n", sol_degree);
105     printf("  Num. 1D quadrature pts [-q] : %" CeedInt_FMT "\n", num_qpts);
106     printf("  Approx. # unknowns     [-s] : %" CeedInt_FMT "\n", prob_size);
107     printf("  QFunction source       [-g] : %s\n", gallery ? "gallery" : "header");
108     if (help) {
109       printf("Test/quiet mode is %s\n", (test ? "ON" : "OFF (use -t to enable)"));
110       return 0;
111     }
112     printf("\n");
113     // LCOV_EXCL_STOP
114   }
115 
116   // Select appropriate backend and logical device based on the (-ceed) command line argument.
117   Ceed ceed;
118   CeedInit(ceed_spec, &ceed);
119 
120   // Construct the mesh and solution bases.
121   CeedBasis mesh_basis, sol_basis;
122   CeedBasisCreateTensorH1Lagrange(ceed, dim, num_comp_x, mesh_degree + 1, num_qpts, CEED_GAUSS, &mesh_basis);
123   CeedBasisCreateTensorH1Lagrange(ceed, dim, 1, sol_degree + 1, num_qpts, CEED_GAUSS, &sol_basis);
124 
125   // Determine the mesh size based on the given approximate problem size.
126   CeedInt num_xyz[dim];
127   GetCartesianMeshSize(dim, sol_degree, prob_size, num_xyz);
128   if (!test) {
129     // LCOV_EXCL_START
130     printf("Mesh size: nx = %" CeedInt_FMT, num_xyz[0]);
131     if (dim > 1) printf(", ny = %" CeedInt_FMT, num_xyz[1]);
132     if (dim > 2) printf(", nz = %" CeedInt_FMT, num_xyz[2]);
133     printf("\n");
134     // LCOV_EXCL_STOP
135   }
136 
137   // Build CeedElemRestriction objects describing the mesh and solution discrete representations.
138   CeedInt             mesh_size, sol_size;
139   CeedElemRestriction mesh_restriction, sol_restriction, q_data_restriction;
140   BuildCartesianRestriction(ceed, dim, num_xyz, mesh_degree, num_comp_x, &mesh_size, num_qpts, &mesh_restriction, NULL);
141   BuildCartesianRestriction(ceed, dim, num_xyz, sol_degree, 1, &sol_size, num_qpts, &sol_restriction, &q_data_restriction);
142   if (!test) {
143     // LCOV_EXCL_START
144     printf("Number of mesh nodes     : %" CeedInt_FMT "\n", mesh_size / dim);
145     printf("Number of solution nodes : %" CeedInt_FMT "\n", sol_size);
146     // LCOV_EXCL_STOP
147   }
148 
149   // Create a CeedVector with the mesh coordinates.
150   CeedVector mesh_coords;
151   CeedVectorCreate(ceed, mesh_size, &mesh_coords);
152   SetCartesianMeshCoords(dim, num_xyz, mesh_degree, mesh_coords);
153 
154   // Apply a transformation to the mesh.
155   CeedScalar exact_volume = TransformMeshCoords(dim, mesh_size, mesh_coords);
156 
157   // Context data to be passed to the 'build_mass' QFunction.
158   CeedQFunctionContext build_ctx;
159   struct BuildContext  build_ctx_data;
160   build_ctx_data.dim = build_ctx_data.space_dim = dim;
161   CeedQFunctionContextCreate(ceed, &build_ctx);
162   CeedQFunctionContextSetData(build_ctx, CEED_MEM_HOST, CEED_USE_POINTER, sizeof(build_ctx_data), &build_ctx_data);
163 
164   // Create the QFunction that builds the mass operator (i.e. computes its quadrature data) and set its context data.
165   CeedQFunction qf_build;
166   if (gallery) {
167     // This creates the QFunction via the gallery.
168     char name[13] = "";
169     snprintf(name, sizeof name, "Mass%" CeedInt_FMT "DBuild", dim);
170     CeedQFunctionCreateInteriorByName(ceed, name, &qf_build);
171   } else {
172     // This creates the QFunction directly.
173     CeedQFunctionCreateInterior(ceed, 1, build_mass, build_mass_loc, &qf_build);
174     CeedQFunctionAddInput(qf_build, "dx", num_comp_x * dim, CEED_EVAL_GRAD);
175     CeedQFunctionAddInput(qf_build, "weights", 1, CEED_EVAL_WEIGHT);
176     CeedQFunctionAddOutput(qf_build, "qdata", 1, CEED_EVAL_NONE);
177     CeedQFunctionSetContext(qf_build, build_ctx);
178   }
179 
180   // Create the operator that builds the quadrature data for the mass operator.
181   CeedOperator op_build;
182   CeedOperatorCreate(ceed, qf_build, CEED_QFUNCTION_NONE, CEED_QFUNCTION_NONE, &op_build);
183   CeedOperatorSetField(op_build, "dx", mesh_restriction, mesh_basis, CEED_VECTOR_ACTIVE);
184   CeedOperatorSetField(op_build, "weights", CEED_ELEMRESTRICTION_NONE, mesh_basis, CEED_VECTOR_NONE);
185   CeedOperatorSetField(op_build, "qdata", q_data_restriction, CEED_BASIS_NONE, CEED_VECTOR_ACTIVE);
186 
187   // Compute the quadrature data for the mass operator.
188   CeedVector q_data;
189   CeedInt    elem_qpts = CeedIntPow(num_qpts, dim);
190   CeedInt    num_elem  = 1;
191   for (CeedInt d = 0; d < dim; d++) num_elem *= num_xyz[d];
192   CeedVectorCreate(ceed, num_elem * elem_qpts, &q_data);
193   CeedOperatorApply(op_build, mesh_coords, q_data, CEED_REQUEST_IMMEDIATE);
194 
195   // Create the QFunction that defines the action of the mass operator.
196   CeedQFunction qf_apply;
197   if (gallery) {
198     // This creates the QFunction via the gallery.
199     CeedQFunctionCreateInteriorByName(ceed, "MassApply", &qf_apply);
200   } else {
201     // This creates the QFunction directly.
202     CeedQFunctionCreateInterior(ceed, 1, apply_mass, apply_mass_loc, &qf_apply);
203     CeedQFunctionAddInput(qf_apply, "u", 1, CEED_EVAL_INTERP);
204     CeedQFunctionAddInput(qf_apply, "qdata", 1, CEED_EVAL_NONE);
205     CeedQFunctionAddOutput(qf_apply, "v", 1, CEED_EVAL_INTERP);
206   }
207 
208   // Create the mass operator.
209   CeedOperator op_apply;
210   CeedOperatorCreate(ceed, qf_apply, CEED_QFUNCTION_NONE, CEED_QFUNCTION_NONE, &op_apply);
211   CeedOperatorSetField(op_apply, "u", sol_restriction, sol_basis, CEED_VECTOR_ACTIVE);
212   CeedOperatorSetField(op_apply, "qdata", q_data_restriction, CEED_BASIS_NONE, q_data);
213   CeedOperatorSetField(op_apply, "v", sol_restriction, sol_basis, CEED_VECTOR_ACTIVE);
214 
215   // Create auxiliary solution-size vectors.
216   CeedVector u, v;
217   CeedVectorCreate(ceed, sol_size, &u);
218   CeedVectorCreate(ceed, sol_size, &v);
219 
220   // Initialize 'u' with ones.
221   CeedVectorSetValue(u, 1.0);
222 
223   // Compute the mesh volume using the mass operator: volume = 1^T \cdot M \cdot 1
224   CeedOperatorApply(op_apply, u, v, CEED_REQUEST_IMMEDIATE);
225 
226   // Compute and print the sum of the entries of 'v' giving the mesh volume.
227   CeedScalar volume = 0.;
228   {
229     const CeedScalar *v_array;
230     CeedVectorGetArrayRead(v, CEED_MEM_HOST, &v_array);
231     for (CeedInt i = 0; i < sol_size; i++) volume += v_array[i];
232     CeedVectorRestoreArrayRead(v, &v_array);
233   }
234   if (!test) {
235     // LCOV_EXCL_START
236     printf(" done.\n");
237     printf("Exact mesh volume    : % .14g\n", exact_volume);
238     printf("Computed mesh volume : % .14g\n", volume);
239     printf("Volume error         : % .14g\n", volume - exact_volume);
240     // LCOV_EXCL_STOP
241   } else {
242     CeedScalar tol = (dim == 1 ? 200. * CEED_EPSILON : dim == 2 ? 1E-5 : 1E-5);
243     if (fabs(volume - exact_volume) > tol) printf("Volume error : % .1e\n", volume - exact_volume);
244   }
245 
246   // Free dynamically allocated memory.
247   CeedVectorDestroy(&u);
248   CeedVectorDestroy(&v);
249   CeedVectorDestroy(&q_data);
250   CeedVectorDestroy(&mesh_coords);
251   CeedOperatorDestroy(&op_apply);
252   CeedQFunctionDestroy(&qf_apply);
253   CeedQFunctionContextDestroy(&build_ctx);
254   CeedOperatorDestroy(&op_build);
255   CeedQFunctionDestroy(&qf_build);
256   CeedElemRestrictionDestroy(&sol_restriction);
257   CeedElemRestrictionDestroy(&mesh_restriction);
258   CeedElemRestrictionDestroy(&q_data_restriction);
259   CeedBasisDestroy(&sol_basis);
260   CeedBasisDestroy(&mesh_basis);
261   CeedDestroy(&ceed);
262   return 0;
263 }
264 
265 int GetCartesianMeshSize(CeedInt dim, CeedInt degree, CeedInt prob_size, CeedInt num_xyz[dim]) {
266   // Use the approximate formula:
267   //    prob_size ~ num_elem * degree^dim
268   CeedInt num_elem = prob_size / CeedIntPow(degree, dim);
269   CeedInt s        = 0;  // find s: num_elem/2 < 2^s <= num_elem
270   while (num_elem > 1) {
271     num_elem /= 2;
272     s++;
273   }
274   CeedInt r = s % dim;
275   for (CeedInt d = 0; d < dim; d++) {
276     CeedInt sd = s / dim;
277     if (r > 0) {
278       sd++;
279       r--;
280     }
281     num_xyz[d] = 1 << sd;
282   }
283   return 0;
284 }
285 
286 int BuildCartesianRestriction(Ceed ceed, CeedInt dim, CeedInt num_xyz[dim], CeedInt degree, CeedInt num_comp, CeedInt *size, CeedInt num_qpts,
287                               CeedElemRestriction *restriction, CeedElemRestriction *q_data_restriction) {
288   CeedInt p         = degree + 1;
289   CeedInt num_nodes = CeedIntPow(p, dim);         // number of scalar nodes per element
290   CeedInt elem_qpts = CeedIntPow(num_qpts, dim);  // number of qpts per element
291   CeedInt nd[3], num_elem = 1, scalar_size = 1;
292   for (CeedInt d = 0; d < dim; d++) {
293     num_elem *= num_xyz[d];
294     nd[d] = num_xyz[d] * (p - 1) + 1;
295     scalar_size *= nd[d];
296   }
297   *size = scalar_size * num_comp;
298   // elem:         0             1                 n-1
299   //           |---*-...-*---|---*-...-*---|- ... -|--...--|
300   // num_nodes:   0   1    p-1  p  p+1       2*p             n*p
301   CeedInt *elem_nodes = malloc(sizeof(CeedInt) * num_elem * num_nodes);
302   for (CeedInt e = 0; e < num_elem; e++) {
303     CeedInt e_xyz[3] = {1, 1, 1}, re = e;
304     for (CeedInt d = 0; d < dim; d++) {
305       e_xyz[d] = re % num_xyz[d];
306       re /= num_xyz[d];
307     }
308     CeedInt *local_elem_nodes = elem_nodes + e * num_nodes;
309     for (CeedInt l_nodes = 0; l_nodes < num_nodes; l_nodes++) {
310       CeedInt g_nodes = 0, g_nodes_stride = 1, r_nodes = l_nodes;
311       for (CeedInt d = 0; d < dim; d++) {
312         g_nodes += (e_xyz[d] * (p - 1) + r_nodes % p) * g_nodes_stride;
313         g_nodes_stride *= nd[d];
314         r_nodes /= p;
315       }
316       local_elem_nodes[l_nodes] = g_nodes;
317     }
318   }
319   CeedElemRestrictionCreate(ceed, num_elem, num_nodes, num_comp, scalar_size, num_comp * scalar_size, CEED_MEM_HOST, CEED_COPY_VALUES, elem_nodes,
320                             restriction);
321   if (q_data_restriction)
322     CeedElemRestrictionCreateStrided(ceed, num_elem, elem_qpts, num_comp, num_comp * elem_qpts * num_elem, CEED_STRIDES_BACKEND, q_data_restriction);
323   free(elem_nodes);
324   return 0;
325 }
326 
327 int SetCartesianMeshCoords(CeedInt dim, CeedInt num_xyz[dim], CeedInt mesh_degree, CeedVector mesh_coords) {
328   CeedInt p = mesh_degree + 1;
329   CeedInt nd[3], scalar_size = 1;
330   for (CeedInt d = 0; d < dim; 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