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