MFEM v4.10.0
Finite element discretization library
Loading...
Searching...
No Matches
ex1p.cpp
Go to the documentation of this file.
1// MFEM Example 1 - Parallel Version
2// GINKGO Modification
3//
4// Compile with: make ex1p
5//
6// Sample runs: mpirun -np 4 ex1p -m ../../data/square-disc.mesh
7// mpirun -np 4 ex1p -m ../../data/star.mesh
8// mpirun -np 4 ex1p -m ../../data/star-mixed.mesh
9// mpirun -np 4 ex1p -m ../../data/escher.mesh
10// mpirun -np 4 ex1p -m ../../data/fichera.mesh
11// mpirun -np 4 ex1p -m ../../data/fichera-mixed.mesh
12// mpirun -np 4 ex1p -m ../../data/toroid-wedge.mesh
13// mpirun -np 4 ex1p -m ../../data/octahedron.mesh -o 1
14// mpirun -np 4 ex1p -m ../../data/periodic-annulus-sector.msh
15// mpirun -np 4 ex1p -m ../../data/periodic-torus-sector.msh
16// mpirun -np 4 ex1p -m ../../data/square-disc-p2.vtk -o 2
17// mpirun -np 4 ex1p -m ../../data/square-disc-p3.mesh -o 3
18// mpirun -np 4 ex1p -m ../../data/square-disc-nurbs.mesh -o -1
19// mpirun -np 4 ex1p -m ../../data/star-mixed-p2.mesh -o 2
20// mpirun -np 4 ex1p -m ../../data/disc-nurbs.mesh -o -1
21// mpirun -np 4 ex1p -m ../../data/pipe-nurbs.mesh -o -1
22// mpirun -np 4 ex1p -m ../../data/ball-nurbs.mesh -o 2
23// mpirun -np 4 ex1p -m ../../data/fichera-mixed-p2.mesh -o 2
24// mpirun -np 4 ex1p -m ../../data/star-surf.mesh
25// mpirun -np 4 ex1p -m ../../data/square-disc-surf.mesh
26// mpirun -np 4 ex1p -m ../../data/inline-segment.mesh
27// mpirun -np 4 ex1p -m ../../data/amr-quad.mesh
28// mpirun -np 4 ex1p -m ../../data/amr-hex.mesh
29// mpirun -np 4 ex1p -m ../../data/mobius-strip.mesh
30// mpirun -np 4 ex1p -m ../../data/mobius-strip.mesh -o -1 -sc
31//
32// Device sample runs:
33// mpirun -np 4 ex1p -pa -d cuda
34// mpirun -np 4 ex1p -fa -d cuda
35// mpirun -np 4 ex1p -pa -d occa-cuda
36// mpirun -np 4 ex1p -pa -d raja-omp
37// mpirun -np 4 ex1p -pa -d ceed-cpu
38// mpirun -np 4 ex1p -pa -d ceed-cpu -o 4 -a
39// mpirun -np 4 ex1p -pa -d ceed-cpu -m ../../data/square-mixed.mesh
40// mpirun -np 4 ex1p -pa -d ceed-cpu -m ../../data/fichera-mixed.mesh
41// * mpirun -np 4 ex1p -pa -d ceed-cuda
42// * mpirun -np 4 ex1p -pa -d ceed-hip
43// mpirun -np 4 ex1p -pa -d ceed-cuda:/gpu/cuda/shared
44// mpirun -np 4 ex1p -pa -d ceed-cuda:/gpu/cuda/shared -m ../../data/square-mixed.mesh
45// mpirun -np 4 ex1p -pa -d ceed-cuda:/gpu/cuda/shared -m ../../data/fichera-mixed.mesh
46// mpirun -np 4 ex1p -m ../../data/beam-tet.mesh -pa -d ceed-cpu
47//
48// Description: This example code demonstrates the use of MFEM to define a
49// simple finite element discretization of the Laplace problem
50// -Delta u = 1 with homogeneous Dirichlet boundary conditions.
51// Specifically, we discretize using a FE space of the specified
52// order, or if order < 1 using an isoparametric/isogeometric
53// space (i.e. quadratic for quadratic curvilinear mesh, NURBS for
54// NURBS mesh, etc.)
55//
56// The example highlights the use of mesh refinement, finite
57// element grid functions, as well as linear and bilinear forms
58// corresponding to the left-hand side and right-hand side of the
59// discrete linear system. We also cover the explicit elimination
60// of essential boundary conditions, static condensation, and the
61// optional connection to the GLVis tool for visualization.
62
63#include "mfem.hpp"
64#include <fstream>
65#include <iostream>
66
67#ifndef MFEM_USE_GINKGO
68#error This example requires that MFEM is built with MFEM_USE_GINKGO=YES
69#endif
70
71using namespace std;
72using namespace mfem;
73
74int main(int argc, char *argv[])
75{
76 // 1. Initialize MPI and HYPRE.
77 Mpi::Init();
78 int num_procs = Mpi::WorldSize();
79 int myid = Mpi::WorldRank();
81
82 // 2. Parse command-line options.
83 const char *mesh_file = "../../data/star.mesh";
84 int order = 1;
85 bool static_cond = false;
86 bool pa = false;
87 bool fa = false;
88 const char *device_config = "cpu";
89 bool visualization = true;
90 int solver_config = 0;
91 int print_lvl = 1;
92
93 OptionsParser args(argc, argv);
94 args.AddOption(&mesh_file, "-m", "--mesh",
95 "Mesh file to use.");
96 args.AddOption(&order, "-o", "--order",
97 "Finite element order (polynomial degree) or -1 for"
98 " isoparametric space.");
99 args.AddOption(&static_cond, "-sc", "--static-condensation", "-no-sc",
100 "--no-static-condensation", "Enable static condensation.");
101 args.AddOption(&pa, "-pa", "--partial-assembly", "-no-pa",
102 "--no-partial-assembly", "Enable Partial Assembly.");
103 args.AddOption(&fa, "-fa", "--full-assembly", "-no-fa",
104 "--no-full-assembly", "Enable Full Assembly.");
105 args.AddOption(&device_config, "-d", "--device",
106 "Device configuration string, see Device::Configure().");
107 args.AddOption(&visualization, "-vis", "--visualization", "-no-vis",
108 "--no-visualization",
109 "Enable or disable GLVis visualization.");
110 args.AddOption(&solver_config, "-s", "--solver-config",
111 "Solver and preconditioner combination: \n\t"
112 " 0 - Ginkgo solver and Ginkgo preconditioner, \n\t"
113 " 1 - Ginkgo solver and MFEM preconditioner, \n\t"
114 " 2 - MFEM solver and Ginkgo preconditioner, \n\t"
115 " 3 - MFEM solver and MFEM preconditioner.");
116 args.AddOption(&print_lvl, "-pl", "--print-level",
117 "Print level for iterative solver (1 prints every iteration).");
118 args.Parse();
119 if (!args.Good())
120 {
121 if (myid == 0)
122 {
123 args.PrintUsage(cout);
124 }
125 return 1;
126 }
127 if (myid == 0)
128 {
129 args.PrintOptions(cout);
130 }
131
132 // 3. Enable hardware devices such as GPUs, and programming models such as
133 // CUDA, OCCA, RAJA and OpenMP based on command line options.
134 Device device(device_config);
135 device.SetGPUAwareMPI(true);
136 if (myid == 0) { device.Print(); }
137
138 // 4. Read the (serial) mesh from the given mesh file on all processors. We
139 // can handle triangular, quadrilateral, tetrahedral, hexahedral, surface
140 // and volume meshes with the same code.
141 Mesh mesh(mesh_file, 1, 1);
142 int dim = mesh.Dimension();
143
144 // 5. Refine the serial mesh on all processors to increase the resolution. In
145 // this example we do 'ref_levels' of uniform refinement. We choose
146 // 'ref_levels' to be the largest number that gives a final mesh with no
147 // more than 10,000 elements.
148 {
149 int ref_levels =
150 (int)floor(log(10000./mesh.GetNE())/log(2.)/dim);
151 for (int l = 0; l < ref_levels; l++)
152 {
153 mesh.UniformRefinement();
154 }
155 }
156
157 // 6. Define a parallel mesh by a partitioning of the serial mesh. Refine
158 // this mesh further in parallel to increase the resolution. Once the
159 // parallel mesh is defined, the serial mesh can be deleted.
160 ParMesh pmesh(MPI_COMM_WORLD, mesh);
161 mesh.Clear();
162 {
163 int par_ref_levels = 2;
164 for (int l = 0; l < par_ref_levels; l++)
165 {
166 pmesh.UniformRefinement();
167 }
168 }
169
170 // 7. Define a parallel finite element space on the parallel mesh. Here we
171 // use continuous Lagrange finite elements of the specified order. If
172 // order < 1, we instead use an isoparametric/isogeometric space.
174 bool delete_fec;
175 if (order > 0)
176 {
177 fec = new H1_FECollection(order, dim);
178 delete_fec = true;
179 }
180 else if (pmesh.GetNodes())
181 {
182 fec = pmesh.GetNodes()->OwnFEC();
183 delete_fec = false;
184 if (myid == 0)
185 {
186 cout << "Using isoparametric FEs: " << fec->Name() << endl;
187 }
188 }
189 else
190 {
191 fec = new H1_FECollection(order = 1, dim);
192 delete_fec = true;
193 }
194 ParFiniteElementSpace fespace(&pmesh, fec);
195 HYPRE_BigInt size = fespace.GlobalTrueVSize();
196 if (myid == 0)
197 {
198 cout << "Number of finite element unknowns: " << size << endl;
199 }
200
201 // 8. Determine the list of true (i.e. parallel conforming) essential
202 // boundary dofs. In this example, the boundary conditions are defined
203 // by marking all the boundary attributes from the mesh as essential
204 // (Dirichlet) and converting them to a list of true dofs.
206 if (pmesh.bdr_attributes.Size())
207 {
208 Array<int> ess_bdr(pmesh.bdr_attributes.Max());
209 ess_bdr = 1;
210 fespace.GetEssentialTrueDofs(ess_bdr, ess_tdof_list);
211 }
212
213 // 9. Set up the parallel linear form b(.) which corresponds to the
214 // right-hand side of the FEM linear system, which in this case is
215 // (1,phi_i) where phi_i are the basis functions in fespace.
216 ParLinearForm b(&fespace);
217 ConstantCoefficient one(1.0);
218 b.AddDomainIntegrator(new DomainLFIntegrator(one));
219 b.Assemble();
220
221 // 10. Define the solution vector x as a parallel finite element grid
222 // function corresponding to fespace. Initialize x with initial guess of
223 // zero, which satisfies the boundary conditions.
224 ParGridFunction x(&fespace);
225 x = 0.0;
226
227 // 11. Set up the parallel bilinear form a(.,.) on the finite element space
228 // corresponding to the Laplacian operator -Delta, by adding the
229 // Diffusion domain integrator.
230 ParBilinearForm a(&fespace);
231 if (pa) { a.SetAssemblyLevel(AssemblyLevel::PARTIAL); }
232 if (fa)
233 {
234 a.SetAssemblyLevel(AssemblyLevel::FULL);
235 // Sort the matrix column indices when running on GPU or with OpenMP (i.e.
236 // when Device::IsEnabled() returns true). This makes the results
237 // bit-for-bit deterministic at the cost of somewhat longer run time.
238 a.EnableSparseMatrixSorting(Device::IsEnabled());
239 }
240 a.AddDomainIntegrator(new DiffusionIntegrator(one));
241
242 // 12. Assemble the parallel bilinear form and the corresponding linear
243 // system, applying any necessary transformations such as: parallel
244 // assembly, eliminating boundary conditions, applying conforming
245 // constraints for non-conforming AMR, static condensation, etc.
246 if (static_cond) { a.EnableStaticCondensation(); }
247 a.Assemble();
248
249 OperatorPtr A;
250 Vector B, X;
251 a.FormLinearSystem(ess_tdof_list, x, b, A, X, B);
252
253 // 13. Solve the linear system A X = B.
254 if (!pa)
255 {
256 switch (solver_config)
257 {
258 // Solve the linear system with CG + Schwarz (with IC) from Ginkgo
259 case 0:
260 {
261 if (myid == 0) { cout << "Using Ginkgo solver + preconditioner...\n"; }
262 Ginkgo::GinkgoExecutor exec(device);
263 Ginkgo::IcPreconditioner local_solver(exec, "exact");
264 Ginkgo::SchwarzPreconditioner gko_M(exec, MPI_COMM_WORLD, local_solver);
265 Ginkgo::CGSolver ginkgo_solver(exec, MPI_COMM_WORLD, gko_M);
266 ginkgo_solver.SetPrintLevel(print_lvl);
267 ginkgo_solver.SetRelTol(sqrt(1e-12));
268 ginkgo_solver.SetAbsTol(0.0);
269 ginkgo_solver.SetMaxIter(400);
270 ginkgo_solver.SetOperator(*(A.Ptr()));
271 ginkgo_solver.Mult(B, X);
272 break;
273 }
274
275 // Solve the linear system with CG from Ginkgo + MFEM preconditioner
276 case 1:
277 {
278 if (myid == 0) { cout << "Using Ginkgo solver + MFEM preconditioner...\n"; }
279 Ginkgo::GinkgoExecutor exec(device);
280 //Create MFEM preconditioner and wrap it for Ginkgo's use.
282 Ginkgo::MFEMPreconditioner gko_M(exec, M, MPI_COMM_WORLD);
283 Ginkgo::CGSolver ginkgo_solver(exec, MPI_COMM_WORLD, gko_M);
284 ginkgo_solver.SetPrintLevel(print_lvl);
285 ginkgo_solver.SetRelTol(sqrt(1e-12));
286 ginkgo_solver.SetAbsTol(0.0);
287 ginkgo_solver.SetMaxIter(400);
288 ginkgo_solver.SetOperator(*(A.Ptr()));
289 ginkgo_solver.Mult(B, X);
290 break;
291 }
292
293 // Ginkgo Schwarz preconditioner (local ParIC) + MFEM CG solver
294 case 2:
295 {
296 if (myid == 0) { cout << "Using MFEM solver + Ginkgo preconditioner...\n"; }
297 Ginkgo::GinkgoExecutor exec(device);
298 Ginkgo::IcPreconditioner local_M(exec, "exact");
299 Ginkgo::SchwarzPreconditioner M(exec, MPI_COMM_WORLD, local_M);
300 M.SetOperator(*(A.Ptr())); // Generate the preconditioner for the matrix A.
301 CGSolver cg(MPI_COMM_WORLD);
302 cg.SetRelTol(sqrt(1e-12));
303 cg.SetMaxIter(400);
304 cg.SetPrintLevel(1);
305 cg.SetPreconditioner(M);
306 cg.SetOperator(*A);
307 cg.Mult(B, X);
308 break;
309 }
310
311 // MFEM solver + MFEM preconditioner
312 case 3:
313 {
314 if (myid == 0) { cout << "Using MFEM solver + MFEM preconditioner...\n"; }
316 CGSolver cg(MPI_COMM_WORLD);
317 cg.SetRelTol(sqrt(1e-12));
318 cg.SetMaxIter(400);
319 cg.SetPrintLevel(1);
320 cg.SetPreconditioner(M);
321 cg.SetOperator(*A);
322 cg.Mult(B, X);
323 break;
324 }
325 } // End switch on solver_config
326 }
327 // Partial assembly mode. Cannot use Ginkgo preconditioners, but can use Ginkgo
328 // solvers.
329 else
330 {
331 if (UsesTensorBasis(fespace))
332 {
333 // Use Jacobi preconditioning in partial assembly mode.
335 switch (solver_config)
336 {
337 case 0:
338 {
339 if (myid == 0) { cout << "Using Ginkgo solver + preconditioner...\n"; }
340 MFEM_ABORT("Cannot use Ginkgo preconditioner in partial assembly mode.\n"
341 " Try -s 1 to test Ginkgo solver with an MFEM preconditioner.");
342 break;
343 }
344
345 // Use Ginkgo solver with MFEM preconditioner
346 case 1:
347 {
348 if (myid == 0) { cout << "Using Ginkgo solver + MFEM preconditioner...\n"; }
349 Ginkgo::GinkgoExecutor exec(device);
350 // Wrap MFEM preconditioner for Ginkgo's use.
351 Ginkgo::MFEMPreconditioner gko_M(exec, M, MPI_COMM_WORLD);
352 Ginkgo::CGSolver ginkgo_solver(exec, MPI_COMM_WORLD, gko_M);
353 ginkgo_solver.SetPrintLevel(print_lvl);
354 ginkgo_solver.SetRelTol(sqrt(1e-12));
355 ginkgo_solver.SetAbsTol(0.0);
356 ginkgo_solver.SetMaxIter(400);
357 ginkgo_solver.SetOperator(*(A.Ptr()));
358 ginkgo_solver.Mult(B, X);
359 break;
360 }
361
362 // No Ginkgo preconditioners work with matrix-free; error
363 case 2:
364 {
365 if (myid == 0) { cout << "Using Ginkgo solver + preconditioner...\n"; }
366 MFEM_ABORT("Cannot use Ginkgo preconditioner in partial assembly mode.\n"
367 " Try -s 1 to test Ginkgo solver with an MFEM preconditioner.");
368 break;
369 }
370
371 // Use MFEM solver and preconditioner
372 case 3:
373 {
374 if (myid == 0) { cout << "Using MFEM solver + MFEM preconditioner...\n"; }
375 CGSolver cg(MPI_COMM_WORLD);
376 cg.SetRelTol(sqrt(1e-12));
377 cg.SetMaxIter(400);
378 cg.SetPrintLevel(1);
379 cg.SetPreconditioner(M);
380 cg.SetOperator(*A);
381 cg.Mult(B, X);
382 break;
383 }
384 } // End switch on solver_config
385 }
386 else // CG with no preconditioning
387 {
388 if (myid == 0) { cout << "Using MFEM solver + no preconditioner...\n"; }
389 CGSolver cg(MPI_COMM_WORLD);
390 cg.SetRelTol(sqrt(1e-12));
391 cg.SetMaxIter(400);
392 cg.SetPrintLevel(1);
393 cg.SetOperator(*A);
394 cg.Mult(B, X);
395 }
396 }
397
398 // 14. Recover the parallel grid function corresponding to X. This is the
399 // local finite element solution on each processor.
400 a.RecoverFEMSolution(X, b, x);
401
402 // 15. Save the refined mesh and the solution in parallel. This output can
403 // be viewed later using GLVis: "glvis -np <np> -m mesh -g sol".
404 {
405 ostringstream mesh_name, sol_name;
406 mesh_name << "mesh." << setfill('0') << setw(6) << myid;
407 sol_name << "sol." << setfill('0') << setw(6) << myid;
408
409 ofstream mesh_ofs(mesh_name.str().c_str());
410 mesh_ofs.precision(8);
411 pmesh.Print(mesh_ofs);
412
413 ofstream sol_ofs(sol_name.str().c_str());
414 sol_ofs.precision(8);
415 x.Save(sol_ofs);
416 }
417
418 // 16. Send the solution by socket to a GLVis server.
419 if (visualization)
420 {
421 char vishost[] = "localhost";
422 int visport = 19916;
423 socketstream sol_sock(vishost, visport);
424 sol_sock << "parallel " << num_procs << " " << myid << "\n";
425 sol_sock.precision(8);
426 sol_sock << "solution\n" << pmesh << x << flush;
427 }
428
429 // 17. Free the used memory.
430 if (delete_fec)
431 {
432 delete fec;
433 }
434
435 return 0;
436}
T Max() const
Find the maximal element in the array, using the comparison operator < for class T.
Definition array.cpp:69
int Size() const
Return the logical size of the array.
Definition array.hpp:192
Conjugate gradient method.
Definition solvers.hpp:627
A coefficient that is constant across space and time.
The MFEM Device class abstracts hardware devices such as GPUs, as well as programming models such as ...
Definition device.hpp:129
static void SetGPUAwareMPI(const bool force=true)
Manually set the status of GPU-aware MPI flag for use in MPI communication routines which have optimi...
Definition device.hpp:315
void Print(std::ostream &os=mfem::out)
Print the configuration of the MFEM virtual device object.
Definition device.cpp:319
static bool IsEnabled()
Return true if any backend other than Backend::CPU is enabled.
Definition device.hpp:252
Class for domain integration .
Definition lininteg.hpp:108
Collection of finite elements from the same family in multiple dimensions. This class is used to matc...
Definition fe_coll.hpp:27
virtual const char * Name() const
Definition fe_coll.hpp:79
void SetOperator(const Operator &op) override
Definition ginkgo.cpp:856
void Mult(const Vector &x, Vector &y) const override
Definition ginkgo.cpp:653
void SetPrintLevel(int print_lvl)
Definition ginkgo.hpp:1082
void SetOperator(const Operator &op) override
Definition ginkgo.cpp:1972
Arbitrary order H1-conforming (continuous) finite elements.
Definition fe_coll.hpp:291
The BoomerAMG solver in hypre.
Definition hypre.hpp:1829
Wrapper for hypre's ParCSR matrix class.
Definition hypre.hpp:419
static void Init()
Initialize hypre by calling HYPRE_Init() and set default options. After calling Hypre::Init(),...
Definition hypre.cpp:33
Mesh data type.
Definition mesh.hpp:67
Array< int > bdr_attributes
A list of all unique boundary attributes used by the Mesh.
Definition mesh.hpp:309
void Clear()
Clear the contents of the Mesh.
Definition mesh.hpp:835
int GetNE() const
Returns number of elements.
Definition mesh.hpp:1390
int Dimension() const
Dimension of the reference space used within the elements.
Definition mesh.hpp:1314
void GetNodes(Vector &node_coord) const
Definition mesh.cpp:10112
void UniformRefinement(int i, const DSTable &, int *, int *, int *)
Definition mesh.cpp:12125
static int WorldRank()
Return the MPI rank in MPI_COMM_WORLD.
static int WorldSize()
Return the size of MPI_COMM_WORLD.
static void Init(int &argc, char **&argv, int required=default_thread_required, int *provided=nullptr)
Singleton creation with Mpi::Init(argc, argv).
Pointer to an Operator of a specified type.
Definition handle.hpp:34
Operator * Ptr() const
Access the underlying Operator pointer.
Definition handle.hpp:87
Jacobi smoothing for a given bilinear form (no matrix necessary).
Definition solvers.hpp:422
void Parse()
Parse the command-line options. Note that this function expects all the options provided through the ...
void PrintUsage(std::ostream &out) const
Print the usage message.
void PrintOptions(std::ostream &out) const
Print the options.
void AddOption(bool *var, const char *enable_short_name, const char *enable_long_name, const char *disable_short_name, const char *disable_long_name, const char *description, bool required=false)
Add a boolean option and set 'var' to receive the value. Enable/disable tags are used to set the bool...
Definition optparser.hpp:82
bool Good() const
Return true if the command line options were parsed successfully.
Class for parallel bilinear form.
Abstract parallel finite element space.
Definition pfespace.hpp:31
void GetEssentialTrueDofs(const Array< int > &bdr_attr_is_ess, Array< int > &ess_tdof_list, int component=-1) const override
HYPRE_BigInt GlobalTrueVSize() const
Definition pfespace.hpp:361
Class for parallel grid function.
Definition pgridfunc.hpp:50
void Save(std::ostream &out) const override
Class for parallel linear form.
Class for parallel meshes.
Definition pmesh.hpp:35
void Print(std::ostream &out=mfem::out, const std::string &comments="") const override
Definition pmesh.cpp:4856
Vector data type.
Definition vector.hpp:82
const int * ess_tdof_list
int dim
Definition ex24.cpp:53
int main()
HYPRE_Int HYPRE_BigInt
real_t b
Definition lissajous.cpp:42
real_t a
Definition lissajous.cpp:41
bool UsesTensorBasis(const FiniteElementSpace &fes)
Return true if the mesh contains only one topology and the elements are tensor elements.
Definition fespace.hpp:1644
const char vishost[]
STL namespace.