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//
3// Compile with: make ex1p
4//
5// Sample runs: mpirun -np 4 ex1p -m ../data/square-disc.mesh
6// mpirun -np 4 ex1p -m ../data/star.mesh
7// mpirun -np 4 ex1p -m ../data/star-mixed.mesh
8// mpirun -np 4 ex1p -m ../data/escher.mesh
9// mpirun -np 4 ex1p -m ../data/fichera.mesh
10// mpirun -np 4 ex1p -m ../data/fichera-mixed.mesh
11// mpirun -np 4 ex1p -m ../data/toroid-wedge.mesh
12// mpirun -np 4 ex1p -m ../data/octahedron.mesh -o 1
13// mpirun -np 4 ex1p -m ../data/periodic-annulus-sector.msh
14// mpirun -np 4 ex1p -m ../data/periodic-torus-sector.msh
15// mpirun -np 4 ex1p -m ../data/square-disc-p2.vtk -o 2
16// mpirun -np 4 ex1p -m ../data/square-disc-p3.mesh -o 3
17// mpirun -np 4 ex1p -m ../data/square-disc-nurbs.mesh -o -1
18// mpirun -np 4 ex1p -m ../data/star-mixed-p2.mesh -o 2
19// mpirun -np 4 ex1p -m ../data/disc-nurbs.mesh -o -1
20// mpirun -np 4 ex1p -m ../data/pipe-nurbs.mesh -o -1
21// mpirun -np 4 ex1p -m ../data/ball-nurbs.mesh -o 2
22// mpirun -np 4 ex1p -m ../data/fichera-mixed-p2.mesh -o 2
23// mpirun -np 4 ex1p -m ../data/star-surf.mesh
24// mpirun -np 4 ex1p -m ../data/square-disc-surf.mesh
25// mpirun -np 4 ex1p -m ../data/inline-segment.mesh
26// mpirun -np 4 ex1p -m ../data/amr-quad.mesh
27// mpirun -np 4 ex1p -m ../data/amr-hex.mesh
28// mpirun -np 4 ex1p -m ../data/mobius-strip.mesh
29// mpirun -np 4 ex1p -m ../data/mobius-strip.mesh -o -1 -sc
30//
31// Device sample runs:
32// mpirun -np 4 ex1p -pa -d cuda
33// mpirun -np 4 ex1p -fa -d cuda
34// mpirun -np 4 ex1p -pa -d occa-cuda
35// mpirun -np 4 ex1p -pa -d raja-omp
36// mpirun -np 4 ex1p -pa -d ceed-cpu
37// mpirun -np 4 ex1p -pa -d ceed-cpu -o 4 -a
38// mpirun -np 4 ex1p -pa -d ceed-cpu -m ../data/square-mixed.mesh
39// mpirun -np 4 ex1p -pa -d ceed-cpu -m ../data/fichera-mixed.mesh
40// * mpirun -np 4 ex1p -pa -d ceed-cuda
41// * mpirun -np 4 ex1p -pa -d ceed-hip
42// mpirun -np 4 ex1p -pa -d ceed-cuda:/gpu/cuda/shared
43// mpirun -np 4 ex1p -pa -d ceed-cuda:/gpu/cuda/shared -m ../data/square-mixed.mesh
44// mpirun -np 4 ex1p -pa -d ceed-cuda:/gpu/cuda/shared -m ../data/fichera-mixed.mesh
45// mpirun -np 4 ex1p -pa -d ceed-cpu -m ../data/beam-tet.mesh
46//
47// Device simplices sample runs:
48// mpirun -np 4 ex1p -pa -d gpu -m ../data/inline-tet.mesh
49// mpirun -np 4 ex1p -pa -d gpu -m ../data/inline-tri.mesh
50//
51// Description: This example code demonstrates the use of MFEM to define a
52// simple finite element discretization of the Poisson problem
53// -Delta u = 1 with homogeneous Dirichlet boundary conditions.
54// Specifically, we discretize using a FE space of the specified
55// order, or if order < 1 using an isoparametric/isogeometric
56// space (i.e. quadratic for quadratic curvilinear mesh, NURBS for
57// NURBS mesh, etc.)
58//
59// The example highlights the use of mesh refinement, finite
60// element grid functions, as well as linear and bilinear forms
61// corresponding to the left-hand side and right-hand side of the
62// discrete linear system. We also cover the explicit elimination
63// of essential boundary conditions, static condensation, and the
64// optional connection to the GLVis tool for visualization.
65
66#include "mfem.hpp"
67#include <fstream>
68#include <iostream>
69
70using namespace std;
71using namespace mfem;
72
73int main(int argc, char *argv[])
74{
75 // 1. Initialize MPI and HYPRE.
76 Mpi::Init();
77 int num_procs = Mpi::WorldSize();
78 int myid = Mpi::WorldRank();
80
81 // 2. Parse command-line options.
82 const char *mesh_file = "../data/star.mesh";
83 int order = 1;
84 bool static_cond = false;
85 bool pa = false;
86 bool fa = false;
87 const char *device_config = "cpu";
88 bool visualization = true;
89 bool algebraic_ceed = false;
90#ifdef MFEM_USE_CUDSS
91 bool cudss_solver = false;
92#endif
93
94 OptionsParser args(argc, argv);
95 args.AddOption(&mesh_file, "-m", "--mesh",
96 "Mesh file to use.");
97 args.AddOption(&order, "-o", "--order",
98 "Finite element order (polynomial degree) or -1 for"
99 " isoparametric space.");
100 args.AddOption(&static_cond, "-sc", "--static-condensation", "-no-sc",
101 "--no-static-condensation", "Enable static condensation.");
102 args.AddOption(&pa, "-pa", "--partial-assembly", "-no-pa",
103 "--no-partial-assembly", "Enable Partial Assembly.");
104 args.AddOption(&fa, "-fa", "--full-assembly", "-no-fa",
105 "--no-full-assembly", "Enable Full Assembly.");
106 args.AddOption(&device_config, "-d", "--device",
107 "Device configuration string, see Device::Configure().");
108#ifdef MFEM_USE_CEED
109 args.AddOption(&algebraic_ceed, "-a", "--algebraic",
110 "-no-a", "--no-algebraic",
111 "Use algebraic Ceed solver");
112#endif
113#ifdef MFEM_USE_CUDSS
114 args.AddOption(&cudss_solver, "-cudss", "--cudss-solver", "-no-cudss",
115 "--no-cudss-solver", "Use the cuDSS Solver.");
116#endif
117 args.AddOption(&visualization, "-vis", "--visualization", "-no-vis",
118 "--no-visualization",
119 "Enable or disable GLVis visualization.");
120 args.Parse();
121 if (!args.Good())
122 {
123 if (myid == 0)
124 {
125 args.PrintUsage(cout);
126 }
127 return 1;
128 }
129 if (myid == 0)
130 {
131 args.PrintOptions(cout);
132 }
133
134 // 3. Enable hardware devices such as GPUs, and programming models such as
135 // CUDA, OCCA, RAJA and OpenMP based on command line options.
136 Device device(device_config);
137 if (myid == 0) { device.Print(); }
138
139 // 4. Read the (serial) mesh from the given mesh file on all processors. We
140 // can handle triangular, quadrilateral, tetrahedral, hexahedral, surface
141 // and volume meshes with the same code.
142 Mesh mesh(mesh_file, 1, 1);
143 int dim = mesh.Dimension();
144
145 // 5. Refine the serial mesh on all processors to increase the resolution. In
146 // this example we do 'ref_levels' of uniform refinement. We choose
147 // 'ref_levels' to be the largest number that gives a final mesh with no
148 // more than 10,000 elements.
149 {
150 int ref_levels =
151 (int)floor(log(10000./mesh.GetNE())/log(2.)/dim);
152 for (int l = 0; l < ref_levels; l++)
153 {
154 mesh.UniformRefinement();
155 }
156 }
157
158 // 6. Define a parallel mesh by a partitioning of the serial mesh. Refine
159 // this mesh further in parallel to increase the resolution. Once the
160 // parallel mesh is defined, the serial mesh can be deleted.
161 ParMesh pmesh(MPI_COMM_WORLD, mesh);
162 mesh.Clear();
163 {
164 int par_ref_levels = 2;
165 for (int l = 0; l < par_ref_levels; l++)
166 {
167 pmesh.UniformRefinement();
168 }
169 }
170
171 // 7. Define a parallel finite element space on the parallel mesh. Here we
172 // use continuous Lagrange finite elements of the specified order.
173 // - If order < 1, we instead use an isoparametric/isogeometric space.
174 // - If the mesh is simplicial and partial assembly is requested,
175 // we use the positive basis, which supports device execution.
177 auto basis_type = (pa && pmesh.IsSimplexMesh()) ?
179 if (order > 0)
180 {
181 fec = new H1_FECollection(order, dim, basis_type);
182 }
183 else if (pmesh.GetNodes())
184 {
185 fec = pmesh.GetNodes()->OwnFEC();
186 if (myid == 0)
187 {
188 cout << "Using isoparametric FEs: " << fec->Name() << endl;
189 }
190 }
191 else
192 {
193 fec = new H1_FECollection(order = 1, dim, basis_type);
194 }
195 ParFiniteElementSpace fespace(&pmesh, fec);
196 HYPRE_BigInt size = fespace.GlobalTrueVSize();
197 if (myid == 0)
198 {
199 cout << "Number of finite element unknowns: " << size << endl;
200 }
201
202 // 8. Determine the list of true (i.e. parallel conforming) essential
203 // boundary dofs. In this example, the boundary conditions are defined
204 // by marking all the external boundary attributes from the mesh as
205 // essential (Dirichlet) and converting them to a list of true dofs.
207 if (pmesh.bdr_attributes.Size())
208 {
209 Array<int> ess_bdr(pmesh.bdr_attributes.Max());
210 ess_bdr = 0;
211 // Apply boundary conditions on all external boundaries:
212 pmesh.MarkExternalBoundaries(ess_bdr);
213 // Boundary conditions can also be applied based on named attributes:
214 // pmesh.MarkNamedBoundaries(set_name, ess_bdr)
215
216 fespace.GetEssentialTrueDofs(ess_bdr, ess_tdof_list);
217 }
218
219 // 9. Set up the parallel linear form b(.) which corresponds to the
220 // right-hand side of the FEM linear system, which in this case is
221 // (1,phi_i) where phi_i are the basis functions in fespace.
222 ParLinearForm b(&fespace);
223 ConstantCoefficient one(1.0);
224 b.AddDomainIntegrator(new DomainLFIntegrator(one));
225 b.Assemble();
226
227 // 10. Define the solution vector x as a parallel finite element grid
228 // function corresponding to fespace. Initialize x with initial guess of
229 // zero, which satisfies the boundary conditions.
230 ParGridFunction x(&fespace);
231 x = 0.0;
232
233 // 11. Set up the parallel bilinear form a(.,.) on the finite element space
234 // corresponding to the Laplacian operator -Delta, by adding the
235 // Diffusion domain integrator.
236 ParBilinearForm a(&fespace);
237 if (pa) { a.SetAssemblyLevel(AssemblyLevel::PARTIAL); }
238 if (fa)
239 {
240 a.SetAssemblyLevel(AssemblyLevel::FULL);
241 // Sort the matrix column indices when running on GPU or with OpenMP (i.e.
242 // when Device::IsEnabled() returns true). This makes the results
243 // bit-for-bit deterministic at the cost of somewhat longer run time.
244 a.EnableSparseMatrixSorting(Device::IsEnabled());
245 }
246 a.AddDomainIntegrator(new DiffusionIntegrator(one));
247
248 // 12. Assemble the parallel bilinear form and the corresponding linear
249 // system, applying any necessary transformations such as: parallel
250 // assembly, eliminating boundary conditions, applying conforming
251 // constraints for non-conforming AMR, static condensation, etc.
252 if (static_cond) { a.EnableStaticCondensation(); }
253 a.Assemble();
254
255 OperatorPtr A;
256 Vector B, X;
257 a.FormLinearSystem(ess_tdof_list, x, b, A, X, B);
258
259 // 13. Solve the linear system A X = B.
260 // * With full assembly, use the BoomerAMG preconditioner from hypre.
261 // * With partial assembly, use Jacobi smoothing, for now.
262#ifdef MFEM_USE_CUDSS
263 if (!pa && (Device::Allows(Backend::CUDA_MASK) && cudss_solver))
264 {
265 // Solve using a direct solver with cuDSS
266 CuDSSSolver cudss_solver(MPI_COMM_WORLD);
267 cudss_solver.SetMatrixSymType(
270 cudss_solver.SetOperator(*A);
271 cudss_solver.Mult(B, X);
272 }
273 else
274#endif
275 {
276 Solver *prec = NULL;
277 if (pa)
278 {
279 if (UsesTensorBasis(fespace))
280 {
281 if (algebraic_ceed)
282 {
284 }
285 else
286 {
288 }
289 }
290 }
291 else
292 {
293 prec = new HypreBoomerAMG;
294 }
295 CGSolver cg(MPI_COMM_WORLD);
296 cg.SetRelTol(1e-12);
297 cg.SetMaxIter(2000);
298 cg.SetPrintLevel(1);
299 if (prec)
300 {
301 cg.SetPreconditioner(*prec);
302 }
303 cg.SetOperator(*A);
304 cg.Mult(B, X);
305 delete prec;
306 }
307
308 // 14. Recover the parallel grid function corresponding to X. This is the
309 // local finite element solution on each processor.
310 a.RecoverFEMSolution(X, b, x);
311
312 // 15. Save the refined mesh and the solution in parallel. This output can
313 // be viewed later using GLVis: "glvis -np <np> -m mesh -g sol".
314 {
315 ostringstream mesh_name, sol_name;
316 mesh_name << "mesh." << setfill('0') << setw(6) << myid;
317 sol_name << "sol." << setfill('0') << setw(6) << myid;
318
319 ofstream mesh_ofs(mesh_name.str().c_str());
320 mesh_ofs.precision(8);
321 pmesh.Print(mesh_ofs);
322
323 ofstream sol_ofs(sol_name.str().c_str());
324 sol_ofs.precision(8);
325 x.Save(sol_ofs);
326 }
327
328 // 16. Send the solution by socket to a GLVis server.
329 if (visualization)
330 {
331 char vishost[] = "localhost";
332 int visport = 19916;
333 socketstream sol_sock(vishost, visport);
334 sol_sock << "parallel " << num_procs << " " << myid << "\n";
335 sol_sock.precision(8);
336 sol_sock << "solution\n" << pmesh << x << flush;
337 }
338
339 // 17. Free the used memory.
340 if (order > 0) { delete fec; }
341
342 return 0;
343}
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
@ GaussLobatto
Closed type.
Definition fe_base.hpp:36
@ Positive
Bernstein polynomials.
Definition fe_base.hpp:37
Conjugate gradient method.
Definition solvers.hpp:627
A coefficient that is constant across space and time.
cuDSS: A high-performance CUDA Library for Direct Sparse Solvers
Definition cudss.hpp:38
void Mult(const Vector &x, Vector &y) const override
Solve .
Definition cudss.cpp:401
void SetOperator(const Operator &op) override
Set/update the solver for the given operator.
Definition cudss.cpp:350
@ SYMMETRIC_POSITIVE_DEFINITE
CUDSS_MTYPE_SPD: Symmetric positive-definite matrix.
Definition cudss.hpp:48
@ UPPER
CUDSS_MVIEW_UPPER: Upper-triangular matrix (including the diagonal).
Definition cudss.hpp:59
void SetMatrixViewType(MatViewType mvtype)
Set the matrix view type.
Definition cudss.cpp:167
void SetMatrixSymType(MatType mtype_)
Set the matrix type.
Definition cudss.cpp:151
The MFEM Device class abstracts hardware devices such as GPUs, as well as programming models such as ...
Definition device.hpp:129
void Print(std::ostream &os=mfem::out)
Print the configuration of the MFEM virtual device object.
Definition device.cpp:319
static bool Allows(unsigned long b_mask)
Return true if any of the backends in the backend mask, b_mask, are allowed.
Definition device.hpp:271
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
Arbitrary order H1-conforming (continuous) finite elements.
Definition fe_coll.hpp:291
The BoomerAMG solver in hypre.
Definition hypre.hpp:1829
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
bool IsSimplexMesh() const
Returns true if the mesh is a simplex mesh, false otherwise.
Definition mesh.hpp:1370
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
Jacobi smoothing for a given bilinear form (no matrix necessary).
Definition solvers.hpp:422
virtual void RecoverFEMSolution(const Vector &X, const Vector &b, Vector &x)
Reconstruct a solution vector x (e.g. a GridFunction) from the solution X of a constrained linear sys...
Definition operator.cpp:163
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 MarkExternalBoundaries(Array< int > &bdr_marker, bool excl=true) const override
Mark boundary attributes of external boundaries.
Definition pmesh.cpp:7011
void Print(std::ostream &out=mfem::out, const std::string &comments="") const override
Definition pmesh.cpp:4856
Base class for solvers.
Definition operator.hpp:855
Vector data type.
Definition vector.hpp:82
Wrapper for AlgebraicMultigrid object.
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.
@ CUDA_MASK
Biwise-OR of all CUDA backends.
Definition device.hpp:96