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