MFEM v4.10.0
Finite element discretization library
Loading...
Searching...
No Matches
ex2p.cpp
Go to the documentation of this file.
1// MFEM Example 2 - Parallel Version
2//
3// Compile with: make ex2p
4//
5// Sample runs: mpirun -np 4 ex2p -m ../data/beam-tri.mesh
6// mpirun -np 4 ex2p -m ../data/beam-quad.mesh
7// mpirun -np 4 ex2p -m ../data/beam-tet.mesh
8// mpirun -np 4 ex2p -m ../data/beam-hex.mesh
9// mpirun -np 4 ex2p -m ../data/beam-wedge.mesh
10// mpirun -np 4 ex2p -m ../data/beam-tri.mesh -o 2 -sys
11// mpirun -np 4 ex2p -m ../data/beam-quad.mesh -o 3 -elast
12// mpirun -np 4 ex2p -m ../data/beam-quad.mesh -o 3 -sc
13// mpirun -np 4 ex2p -m ../data/beam-quad-nurbs.mesh
14// mpirun -np 4 ex2p -m ../data/beam-hex-nurbs.mesh
15//
16// Description: This example code solves a simple linear elasticity problem
17// describing a multi-material cantilever beam.
18//
19// Specifically, we approximate the weak form of -div(sigma(u))=0
20// where sigma(u)=lambda*div(u)*I+mu*(grad*u+u*grad) is the stress
21// tensor corresponding to displacement field u, and lambda and mu
22// are the material Lame constants. The boundary conditions are
23// u=0 on the fixed part of the boundary with attribute 1, and
24// sigma(u).n=f on the remainder with f being a constant pull down
25// vector on boundary elements with attribute 2, and zero
26// otherwise. The geometry of the domain is assumed to be as
27// follows:
28//
29// +----------+----------+
30// boundary --->| material | material |<--- boundary
31// attribute 1 | 1 | 2 | attribute 2
32// (fixed) +----------+----------+ (pull down)
33//
34// The example demonstrates the use of high-order and NURBS vector
35// finite element spaces with the linear elasticity bilinear form,
36// meshes with curved elements, and the definition of piece-wise
37// constant and vector coefficient objects. Static condensation is
38// also illustrated.
39//
40// We recommend viewing Example 1 before viewing this example.
41
42#include "mfem.hpp"
43#include <fstream>
44#include <iostream>
45
46using namespace std;
47using namespace mfem;
48
49int main(int argc, char *argv[])
50{
51 // 1. Initialize MPI and HYPRE.
52 Mpi::Init(argc, argv);
53 int num_procs = Mpi::WorldSize();
54 int myid = Mpi::WorldRank();
56
57 // 2. Parse command-line options.
58 const char *mesh_file = "../data/beam-tri.mesh";
59 int order = 1;
60 bool static_cond = false;
61 bool visualization = 1;
62 bool amg_elast = 0;
63 bool reorder_space = false;
64 const char *device_config = "cpu";
65
66 OptionsParser args(argc, argv);
67 args.AddOption(&mesh_file, "-m", "--mesh",
68 "Mesh file to use.");
69 args.AddOption(&order, "-o", "--order",
70 "Finite element order (polynomial degree).");
71 args.AddOption(&amg_elast, "-elast", "--amg-for-elasticity", "-sys",
72 "--amg-for-systems",
73 "Use the special AMG elasticity solver (GM/LN approaches), "
74 "or standard AMG for systems (unknown approach).");
75 args.AddOption(&static_cond, "-sc", "--static-condensation", "-no-sc",
76 "--no-static-condensation", "Enable static condensation.");
77 args.AddOption(&visualization, "-vis", "--visualization", "-no-vis",
78 "--no-visualization",
79 "Enable or disable GLVis visualization.");
80 args.AddOption(&reorder_space, "-nodes", "--by-nodes", "-vdim", "--by-vdim",
81 "Use byNODES ordering of vector space instead of byVDIM");
82 args.AddOption(&device_config, "-d", "--device",
83 "Device configuration string, see Device::Configure().");
84 args.Parse();
85 if (!args.Good())
86 {
87 if (myid == 0)
88 {
89 args.PrintUsage(cout);
90 }
91 return 1;
92 }
93 if (myid == 0)
94 {
95 args.PrintOptions(cout);
96 }
97
98 if (amg_elast && !static_cond && reorder_space)
99 {
100 if (myid == 0)
101 cerr << "\nThe AMG elasticity solver requires ordering byVDIM! "
102 << "Ignoring the specified option -nodes/--by-nodes.\n"
103 << endl;
104 reorder_space = false;
105 }
106
107 // 3. Enable hardware devices such as GPUs, and programming models such as
108 // CUDA, OCCA, RAJA and OpenMP based on command line options.
109 Device device(device_config);
110 if (myid == 0) { device.Print(); }
111
112 // 4. Read the (serial) mesh from the given mesh file on all processors. We
113 // can handle triangular, quadrilateral, tetrahedral, hexahedral, surface
114 // and volume meshes with the same code.
115 Mesh *mesh = new Mesh(mesh_file, 1, 1);
116 int dim = mesh->Dimension();
117
118 if (mesh->attributes.Max() < 2 || mesh->bdr_attributes.Max() < 2)
119 {
120 if (myid == 0)
121 cerr << "\nInput mesh should have at least two materials and "
122 << "two boundary attributes! (See schematic in ex2.cpp)\n"
123 << endl;
124 return 3;
125 }
126
127 // 5. Select the order of the finite element discretization space. For NURBS
128 // meshes, we increase the order by degree elevation.
129 if (mesh->NURBSext)
130 {
131 mesh->DegreeElevate(order, order);
132 }
133
134 // 6. Refine the serial mesh on all processors to increase the resolution. In
135 // this example we do 'ref_levels' of uniform refinement. We choose
136 // 'ref_levels' to be the largest number that gives a final mesh with no
137 // more than 1,000 elements.
138 {
139 int ref_levels =
140 (int)floor(log(1000./mesh->GetNE())/log(2.)/dim);
141 for (int l = 0; l < ref_levels; l++)
142 {
143 mesh->UniformRefinement();
144 }
145 }
146
147 // 7. Define a parallel mesh by a partitioning of the serial mesh. Refine
148 // this mesh further in parallel to increase the resolution. Once the
149 // parallel mesh is defined, the serial mesh can be deleted.
150 ParMesh *pmesh = new ParMesh(MPI_COMM_WORLD, *mesh);
151 delete mesh;
152 {
153 int par_ref_levels = 1;
154 for (int l = 0; l < par_ref_levels; l++)
155 {
156 pmesh->UniformRefinement();
157 }
158 }
159
160 // 8. Define a parallel finite element space on the parallel mesh. Here we
161 // use vector finite elements, i.e. dim copies of a scalar finite element
162 // space. We use the ordering by vector dimension (the last argument of
163 // the FiniteElementSpace constructor) which is expected in the systems
164 // version of BoomerAMG preconditioner. For NURBS meshes, we use the
165 // (degree elevated) NURBS space associated with the mesh nodes.
167 ParFiniteElementSpace *fespace;
168 const bool use_nodal_fespace = pmesh->NURBSext && !amg_elast;
169 if (use_nodal_fespace)
170 {
171 fec = NULL;
172 fespace = (ParFiniteElementSpace *)pmesh->GetNodes()->FESpace();
173 }
174 else
175 {
176 fec = new H1_FECollection(order, dim);
177 if (reorder_space)
178 {
179 fespace = new ParFiniteElementSpace(pmesh, fec, dim, Ordering::byNODES);
180 }
181 else
182 {
183 fespace = new ParFiniteElementSpace(pmesh, fec, dim, Ordering::byVDIM);
184 }
185 }
186 HYPRE_BigInt size = fespace->GlobalTrueVSize();
187 if (myid == 0)
188 {
189 cout << "Number of finite element unknowns: " << size << endl
190 << "Assembling: " << flush;
191 }
192
193 // 9. Determine the list of true (i.e. parallel conforming) essential
194 // boundary dofs. In this example, the boundary conditions are defined by
195 // marking only boundary attribute 1 from the mesh as essential and
196 // converting it to a list of true dofs.
197 Array<int> ess_tdof_list, ess_bdr(pmesh->bdr_attributes.Max());
198 ess_bdr = 0;
199 ess_bdr[0] = 1;
200 fespace->GetEssentialTrueDofs(ess_bdr, ess_tdof_list);
201
202 // 10. Set up the parallel linear form b(.) which corresponds to the
203 // right-hand side of the FEM linear system. In this case, b_i equals the
204 // boundary integral of f*phi_i where f represents a "pull down" force on
205 // the Neumann part of the boundary and phi_i are the basis functions in
206 // the finite element fespace. The force is defined by the object f, which
207 // is a vector of Coefficient objects. The fact that f is non-zero on
208 // boundary attribute 2 is indicated by the use of piece-wise constants
209 // coefficient for its last component.
211 for (int i = 0; i < dim-1; i++)
212 {
213 f.Set(i, new ConstantCoefficient(0.0));
214 }
215 {
216 Vector pull_force(pmesh->bdr_attributes.Max());
217 pull_force = 0.0;
218 pull_force(1) = -1.0e-2;
219 f.Set(dim-1, new PWConstCoefficient(pull_force));
220 }
221
222 ParLinearForm *b = new ParLinearForm(fespace);
223 b->AddBoundaryIntegrator(new VectorBoundaryLFIntegrator(f));
224 if (myid == 0)
225 {
226 cout << "r.h.s. ... " << flush;
227 }
228 b->Assemble();
229
230 // 11. Define the solution vector x as a parallel finite element grid
231 // function corresponding to fespace. Initialize x with initial guess of
232 // zero, which satisfies the boundary conditions.
233 ParGridFunction x(fespace);
234 x = 0.0;
235
236 // 12. Set up the parallel bilinear form a(.,.) on the finite element space
237 // corresponding to the linear elasticity integrator with piece-wise
238 // constants coefficient lambda and mu.
239 Vector lambda(pmesh->attributes.Max());
240 lambda = 1.0;
241 lambda(0) = lambda(1)*50;
242 PWConstCoefficient lambda_func(lambda);
243 Vector mu(pmesh->attributes.Max());
244 mu = 1.0;
245 mu(0) = mu(1)*50;
246 PWConstCoefficient mu_func(mu);
247
248 ParBilinearForm *a = new ParBilinearForm(fespace);
249 a->AddDomainIntegrator(new ElasticityIntegrator(lambda_func, mu_func));
250
251 // 13. Assemble the parallel bilinear form and the corresponding linear
252 // system, applying any necessary transformations such as: parallel
253 // assembly, eliminating boundary conditions, applying conforming
254 // constraints for non-conforming AMR, static condensation, etc.
255 if (myid == 0) { cout << "matrix ... " << flush; }
256 if (static_cond) { a->EnableStaticCondensation(); }
257 a->Assemble();
258
260 Vector B, X;
261 a->FormLinearSystem(ess_tdof_list, x, *b, A, X, B);
262 if (myid == 0)
263 {
264 cout << "done." << endl;
265 cout << "Size of linear system: " << A.GetGlobalNumRows() << endl;
266 }
267
268 // 14. Define and apply a parallel PCG solver for A X = B with the BoomerAMG
269 // preconditioner from hypre.
270 HypreBoomerAMG *amg = new HypreBoomerAMG(A);
271 if (amg_elast && !a->StaticCondensationIsEnabled())
272 {
273 amg->SetElasticityOptions(fespace);
274 }
275 else
276 {
277 amg->SetSystemsOptions(dim, reorder_space);
278 }
279 HyprePCG *pcg = new HyprePCG(A);
280 pcg->SetTol(1e-8);
281 pcg->SetMaxIter(500);
282 pcg->SetPrintLevel(2);
283 pcg->SetPreconditioner(*amg);
284 pcg->Mult(B, X);
285
286 // 15. Recover the parallel grid function corresponding to X. This is the
287 // local finite element solution on each processor.
288 a->RecoverFEMSolution(X, *b, x);
289
290 // 16. For non-NURBS meshes, make the mesh curved based on the finite element
291 // space. This means that we define the mesh elements through a fespace
292 // based transformation of the reference element. This allows us to save
293 // the displaced mesh as a curved mesh when using high-order finite
294 // element displacement field. We assume that the initial mesh (read from
295 // the file) is not higher order curved mesh compared to the chosen FE
296 // space.
297 if (!use_nodal_fespace)
298 {
299 pmesh->SetNodalFESpace(fespace);
300 }
301
302 // 17. Save in parallel the displaced mesh and the inverted solution (which
303 // gives the backward displacements to the original grid). This output
304 // can be viewed later using GLVis: "glvis -np <np> -m mesh -g sol".
305 {
306 GridFunction *nodes = pmesh->GetNodes();
307 *nodes += x;
308 x *= -1;
309
310 ostringstream mesh_name, sol_name;
311 mesh_name << "mesh." << setfill('0') << setw(6) << myid;
312 sol_name << "sol." << setfill('0') << setw(6) << myid;
313
314 ofstream mesh_ofs(mesh_name.str().c_str());
315 mesh_ofs.precision(8);
316 pmesh->Print(mesh_ofs);
317
318 ofstream sol_ofs(sol_name.str().c_str());
319 sol_ofs.precision(8);
320 x.Save(sol_ofs);
321 }
322
323 // 18. Send the above data by socket to a GLVis server. Use the "n" and "b"
324 // keys in GLVis to visualize the displacements.
325 if (visualization)
326 {
327 char vishost[] = "localhost";
328 int visport = 19916;
329 socketstream sol_sock(vishost, visport);
330 sol_sock << "parallel " << num_procs << " " << myid << "\n";
331 sol_sock.precision(8);
332 sol_sock << "solution\n" << *pmesh << x << flush;
333 }
334
335 // 19. Free the used memory.
336 delete pcg;
337 delete amg;
338 delete a;
339 delete b;
340 if (fec)
341 {
342 delete fespace;
343 delete fec;
344 }
345 delete pmesh;
346
347 return 0;
348}
T Max() const
Find the maximal element in the array, using the comparison operator < for class T.
Definition array.cpp:69
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
void Print(std::ostream &os=mfem::out)
Print the configuration of the MFEM virtual device object.
Definition device.cpp:319
Collection of finite elements from the same family in multiple dimensions. This class is used to matc...
Definition fe_coll.hpp:27
Class for grid function - Vector with associated FE space.
Definition gridfunc.hpp:53
Arbitrary order H1-conforming (continuous) finite elements.
Definition fe_coll.hpp:291
The BoomerAMG solver in hypre.
Definition hypre.hpp:1829
void SetSystemsOptions(int dim, bool order_bynodes=false)
Definition hypre.cpp:5400
void SetElasticityOptions(ParFiniteElementSpace *fespace, bool interp_refine=true)
Definition hypre.cpp:5527
void Mult(const HypreParVector &b, HypreParVector &x) const override
Solve Ax=b with hypre's PCG.
Definition hypre.cpp:4373
void SetPrintLevel(int print_lvl)
Definition hypre.cpp:4345
void SetPreconditioner(HypreSolver &precond)
Set the hypre solver to be used as a preconditioner.
Definition hypre.cpp:4350
void SetMaxIter(int max_iter)
Definition hypre.cpp:4328
void SetTol(real_t tol)
Definition hypre.cpp:4304
Wrapper for hypre's ParCSR matrix class.
Definition hypre.hpp:419
HYPRE_BigInt GetGlobalNumRows() const
Return the global number of rows.
Definition hypre.hpp:713
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
NURBSExtension * NURBSext
Optional NURBS mesh extension.
Definition mesh.hpp:317
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 DegreeElevate(int rel_degree, int degree=16)
Definition mesh.cpp:6551
void UniformRefinement(int i, const DSTable &, int *, int *, int *)
Definition mesh.cpp:12125
Array< int > attributes
A list of all unique element attributes used by the Mesh.
Definition mesh.hpp:307
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).
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.
A piecewise constant coefficient with the constants keyed off the element attribute numbers.
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 SetNodalFESpace(FiniteElementSpace *nfes) override
Definition pmesh.cpp:2057
void Print(std::ostream &out=mfem::out, const std::string &comments="") const override
Definition pmesh.cpp:4856
Vector coefficient defined by an array of scalar coefficients. Coefficients that are not set will eva...
Vector data type.
Definition vector.hpp:82
Vector & Set(const real_t a, const Vector &x)
(*this) = a * x
Definition vector.cpp:341
const int * ess_tdof_list
int dim
Definition ex24.cpp:53
real_t mu
Definition ex25.cpp:140
int main()
HYPRE_Int HYPRE_BigInt
real_t b
Definition lissajous.cpp:42
real_t a
Definition lissajous.cpp:41
std::function< real_t(const Vector &)> f(real_t mass_coeff)
Definition lor_mms.hpp:30
const char vishost[]
STL namespace.
std::array< int, NCMesh::MaxFaceNodes > nodes