xref: /libCEED/examples/petsc/area.c (revision 4e2ba0c093a5dae39016e83cec5c5707e953377a)
1 // Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at
2 // the Lawrence Livermore National Laboratory. LLNL-CODE-734707. All Rights
3 // 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 + PETSc Example: Surface Area
18 //
19 // This example demonstrates a simple usage of libCEED with PETSc to calculate
20 // the surface area of a simple closed surface, such as the one of a cube or a
21 // tensor-product discrete sphere via the mass operator.
22 //
23 // The code uses higher level communication protocols in DMPlex.
24 //
25 // Build with:
26 //
27 //     make area [PETSC_DIR=</path/to/petsc>] [CEED_DIR=</path/to/libceed>]
28 //
29 // Sample runs:
30 //   Sequential:
31 //
32 //     ./area -problem cube -degree 3 -dm_refine 2
33 //     ./area -problem sphere -degree 3 -dm_refine 2
34 //
35 //   In parallel:
36 //
37 //     mpiexec -n 4 ./area -problem cube -degree 3 -dm_refine 2
38 //     mpiexec -n 4 ./area -problem sphere -degree 3 -dm_refine 2
39 //
40 //   The above example runs use 2 levels of refinement for the mesh.
41 //   Use -dm_refine k, for k levels of uniform refinement.
42 //
43 //TESTARGS -ceed {ceed_resource} -test -degree 3 -dm_refine 1
44 
45 /// @file
46 /// libCEED example using the mass operator to compute a cube or a cubed-sphere surface area using PETSc with DMPlex
47 static const char help[] =
48   "Compute surface area of a cube or a cubed-sphere using DMPlex in PETSc\n";
49 
50 #include <stdbool.h>
51 #include <string.h>
52 #include <ceed.h>
53 #include <petsc.h>
54 #include <petscdmplex.h>
55 
56 #include "area.h"
57 #include "include/areaproblemdata.h"
58 #include "include/petscutils.h"
59 #include "include/petscversion.h"
60 #include "include/matops.h"
61 #include "include/structs.h"
62 #include "include/libceedsetup.h"
63 
64 #if PETSC_VERSION_LT(3,12,0)
65 #ifdef PETSC_HAVE_CUDA
66 #include <petsccuda.h>
67 // Note: With PETSc prior to version 3.12.0, providing the source path to
68 //       include 'cublas_v2.h' will be needed to use 'petsccuda.h'.
69 #endif
70 #endif
71 
72 #ifndef M_PI
73 #  define M_PI 3.14159265358979323846
74 #endif
75 
76 int main(int argc, char **argv) {
77   PetscInt ierr;
78   MPI_Comm comm;
79   char filename[PETSC_MAX_PATH_LEN],
80        ceed_resource[PETSC_MAX_PATH_LEN] = "/cpu/self";
81   PetscInt l_size, g_size, xl_size,
82            q_extra     = 1, // default number of extra quadrature points
83            num_comp_x  = 3, // number of components of 3D physical coordinates
84            num_comp_u  = 1, // dimension of field to which apply mass operator
85            topo_dim    = 2, // topological dimension of manifold
86            degree      = 3; // default degree for finite element bases
87   PetscBool read_mesh = PETSC_FALSE,
88             test_mode = PETSC_FALSE,
89             simplex = PETSC_FALSE;
90   Vec U, U_loc, V, V_loc;
91   DM  dm;
92   UserO user;
93   Ceed ceed;
94   CeedData ceed_data;
95   ProblemType problem_choice;
96   VecType vec_type;
97   PetscMemType mem_type;
98 
99   ierr = PetscInitialize(&argc, &argv, NULL, help);
100   if (ierr) return ierr;
101   comm = PETSC_COMM_WORLD;
102 
103   // Read command line options
104   ierr = PetscOptionsBegin(comm, NULL, "CEED surface area problem with PETSc",
105                            NULL);
106   CHKERRQ(ierr);
107   problem_choice = SPHERE;
108   ierr = PetscOptionsEnum("-problem",
109                           "Problem to solve", NULL,
110                           problem_types, (PetscEnum)problem_choice,
111                           (PetscEnum *)&problem_choice,
112                           NULL); CHKERRQ(ierr);
113   ierr = PetscOptionsInt("-q_extra", "Number of extra quadrature points",
114                          NULL, q_extra, &q_extra, NULL); CHKERRQ(ierr);
115   ierr = PetscOptionsString("-ceed", "CEED resource specifier",
116                             NULL, ceed_resource, ceed_resource,
117                             sizeof(ceed_resource), NULL); CHKERRQ(ierr);
118   ierr = PetscOptionsBool("-test",
119                           "Testing mode (do not print unless error is large)",
120                           NULL, test_mode, &test_mode, NULL); CHKERRQ(ierr);
121   ierr = PetscOptionsString("-mesh", "Read mesh from file", NULL,
122                             filename, filename, sizeof(filename), &read_mesh);
123   CHKERRQ(ierr);
124   ierr = PetscOptionsBool("-simplex", "Use simplices, or tensor product cells",
125                           NULL, simplex, &simplex, NULL); CHKERRQ(ierr);
126   ierr = PetscOptionsInt("-degree", "Polynomial degree of tensor product basis",
127                          NULL, degree, &degree, NULL); CHKERRQ(ierr);
128   ierr = PetscOptionsEnd(); CHKERRQ(ierr);
129 
130   // Setup DM
131   if (read_mesh) {
132     ierr = DMPlexCreateFromFile(PETSC_COMM_WORLD, filename, NULL, PETSC_TRUE,
133                                 &dm);
134     CHKERRQ(ierr);
135   } else {
136     // Create the mesh as a 0-refined sphere. This will create a cubic surface, not a box
137     ierr = DMPlexCreateSphereMesh(PETSC_COMM_WORLD, topo_dim, simplex, 1., &dm);
138     CHKERRQ(ierr);
139     if (problem_choice == CUBE) {
140       ierr = DMPlexCreateCoordinateSpace(dm, 1, NULL); CHKERRQ(ierr);
141     }
142     // Set the object name
143     ierr = PetscObjectSetName((PetscObject)dm, problem_types[problem_choice]);
144     CHKERRQ(ierr);
145     // Refine DMPlex with uniform refinement using runtime option -dm_refine
146     ierr = DMPlexSetRefinementUniform(dm, PETSC_TRUE); CHKERRQ(ierr);
147     ierr = DMSetFromOptions(dm); CHKERRQ(ierr);
148     // View DMPlex via runtime option
149     ierr = DMViewFromOptions(dm, NULL, "-dm_view"); CHKERRQ(ierr);
150   }
151 
152   // Create DM
153   ierr = SetupDMByDegree(dm, degree, num_comp_u, topo_dim, false,
154                          (BCFunction)NULL);
155   CHKERRQ(ierr);
156 
157   // Create vectors
158   ierr = DMCreateGlobalVector(dm, &U); CHKERRQ(ierr);
159   ierr = VecGetLocalSize(U, &l_size); CHKERRQ(ierr);
160   ierr = VecGetSize(U, &g_size); CHKERRQ(ierr);
161   ierr = DMCreateLocalVector(dm, &U_loc); CHKERRQ(ierr);
162   ierr = VecGetSize(U_loc, &xl_size); CHKERRQ(ierr);
163   ierr = VecDuplicate(U, &V); CHKERRQ(ierr);
164   ierr = VecDuplicate(U_loc, &V_loc); CHKERRQ(ierr);
165 
166   // Setup user structure
167   ierr = PetscMalloc1(1, &user); CHKERRQ(ierr);
168 
169   // Set up libCEED
170   CeedInit(ceed_resource, &ceed);
171   CeedMemType mem_type_backend;
172   CeedGetPreferredMemType(ceed, &mem_type_backend);
173 
174   ierr = DMGetVecType(dm, &vec_type); CHKERRQ(ierr);
175   if (!vec_type) { // Not yet set by user -dm_vec_type
176     switch (mem_type_backend) {
177     case CEED_MEM_HOST: vec_type = VECSTANDARD; break;
178     case CEED_MEM_DEVICE: {
179       const char *resolved;
180       CeedGetResource(ceed, &resolved);
181       if (strstr(resolved, "/gpu/cuda")) vec_type = VECCUDA;
182       else if (strstr(resolved, "/gpu/hip/occa"))
183         vec_type = VECSTANDARD; // https://github.com/CEED/libCEED/issues/678
184       else if (strstr(resolved, "/gpu/hip")) vec_type = VECHIP;
185       else vec_type = VECSTANDARD;
186     }
187     }
188     ierr = DMSetVecType(dm, vec_type); CHKERRQ(ierr);
189   }
190 
191   // Print summary
192   if (!test_mode) {
193     PetscInt P = degree + 1, Q = P + q_extra;
194     const char *used_resource;
195     CeedGetResource(ceed, &used_resource);
196     ierr = PetscPrintf(comm,
197                        "\n-- libCEED + PETSc Surface Area of a Manifold --\n"
198                        "  libCEED:\n"
199                        "    libCEED Backend                    : %s\n"
200                        "    libCEED Backend MemType            : %s\n"
201                        "  Mesh:\n"
202                        "    Number of 1D Basis Nodes (p)       : %d\n"
203                        "    Number of 1D Quadrature Points (q) : %d\n"
204                        "    Global nodes                       : %D\n"
205                        "    DoF per node                       : %D\n"
206                        "    Global DoFs                        : %D\n",
207                        used_resource, CeedMemTypes[mem_type_backend], P, Q,
208                        g_size/num_comp_u, num_comp_u, g_size); CHKERRQ(ierr);
209   }
210 
211   // Setup libCEED's objects and apply setup operator
212   ierr = PetscMalloc1(1, &ceed_data); CHKERRQ(ierr);
213   ierr = SetupLibceedByDegree(dm, ceed, degree, topo_dim, q_extra, num_comp_x,
214                               num_comp_u, g_size, xl_size,
215                               problem_options[problem_choice], ceed_data,
216                               false, (CeedVector)NULL, (CeedVector *)NULL);
217   CHKERRQ(ierr);
218 
219   // Setup output vector
220   PetscScalar *v;
221   ierr = VecZeroEntries(V_loc); CHKERRQ(ierr);
222   ierr = VecGetArrayAndMemType(V_loc, &v, &mem_type); CHKERRQ(ierr);
223   CeedVectorSetArray(ceed_data->y_ceed, MemTypeP2C(mem_type), CEED_USE_POINTER,
224                      v);
225 
226   // Compute the mesh volume using the mass operator: area = 1^T \cdot M \cdot 1
227   if (!test_mode) {
228     ierr = PetscPrintf(comm,
229                        "Computing the mesh area using the formula: area = 1^T M 1\n");
230     CHKERRQ(ierr);
231   }
232 
233   // Initialize u with ones
234   CeedVectorSetValue(ceed_data->x_ceed, 1.0);
235 
236   // Apply the mass operator: 'u' -> 'v'
237   CeedOperatorApply(ceed_data->op_apply, ceed_data->x_ceed, ceed_data->y_ceed,
238                     CEED_REQUEST_IMMEDIATE);
239 
240   // Gather output vector
241   CeedVectorTakeArray(ceed_data->y_ceed, CEED_MEM_HOST, NULL);
242   ierr = VecRestoreArrayAndMemType(V_loc, &v); CHKERRQ(ierr);
243   ierr = VecZeroEntries(V); CHKERRQ(ierr);
244   ierr = DMLocalToGlobalBegin(dm, V_loc, ADD_VALUES, V); CHKERRQ(ierr);
245   ierr = DMLocalToGlobalEnd(dm, V_loc, ADD_VALUES, V); CHKERRQ(ierr);
246 
247   // Compute and print the sum of the entries of 'v' giving the mesh surface area
248   PetscScalar area;
249   ierr = VecSum(V, &area); CHKERRQ(ierr);
250 
251   // Compute the exact surface area and print the result
252   CeedScalar exact_surface_area = 4 * M_PI;
253   if (problem_choice == CUBE) {
254     exact_surface_area = 6 * 2 * 2; // surface of [-1, 1]^3
255   }
256 
257   PetscReal error = fabs(area - exact_surface_area);
258   PetscReal tol = 5e-6;
259   if (!test_mode || error > tol) {
260     ierr = PetscPrintf(comm, "Exact mesh surface area    : % .14g\n",
261                        exact_surface_area);
262     CHKERRQ(ierr);
263     ierr = PetscPrintf(comm, "Computed mesh surface area : % .14g\n", area);
264     CHKERRQ(ierr);
265     ierr = PetscPrintf(comm, "Area error                 : % .14g\n", error);
266     CHKERRQ(ierr);
267   }
268 
269   // Cleanup
270   ierr = DMDestroy(&dm); CHKERRQ(ierr);
271   ierr = VecDestroy(&U); CHKERRQ(ierr);
272   ierr = VecDestroy(&U_loc); CHKERRQ(ierr);
273   ierr = VecDestroy(&V); CHKERRQ(ierr);
274   ierr = VecDestroy(&V_loc); CHKERRQ(ierr);
275   ierr = PetscFree(user); CHKERRQ(ierr);
276   ierr = CeedDataDestroy(0, ceed_data); CHKERRQ(ierr);
277   CeedDestroy(&ceed);
278   return PetscFinalize();
279 }
280