MFEM v4.7.0 Finite element discretization library
Searching...
No Matches
ex2p.cpp
Go to the documentation of this file.
1// MFEM Example 2 - Parallel Version
2// PETSc Modification
3//
4// Compile with: make ex2p
5//
6// Sample runs:
7// mpirun -np 4 ex2p -m ../../data/beam-quad.mesh --petscopts rc_ex2p
8//
9// Description: This example code solves a simple linear elasticity problem
10// describing a multi-material cantilever beam.
11//
12// Specifically, we approximate the weak form of -div(sigma(u))=0
14// tensor corresponding to displacement field u, and lambda and mu
15// are the material Lame constants. The boundary conditions are
16// u=0 on the fixed part of the boundary with attribute 1, and
17// sigma(u).n=f on the remainder with f being a constant pull down
18// vector on boundary elements with attribute 2, and zero
19// otherwise. The geometry of the domain is assumed to be as
20// follows:
21//
22// +----------+----------+
23// boundary --->| material | material |<--- boundary
24// attribute 1 | 1 | 2 | attribute 2
25// (fixed) +----------+----------+ (pull down)
26//
27// The example demonstrates the use of high-order and NURBS vector
28// finite element spaces with the linear elasticity bilinear form,
29// meshes with curved elements, and the definition of piece-wise
30// constant and vector coefficient objects. Static condensation is
31// also illustrated. The example also shows how to form a linear
32// system using a PETSc matrix and solve with a PETSc solver.
33//
34// The example also show how to use the non-overlapping feature of
35// the ParBilinearForm class to obtain the linear operator in
36// a format suitable for the BDDC preconditioner in PETSc.
37//
38// We recommend viewing Example 1 before viewing this example.
39
40#include "mfem.hpp"
41#include <fstream>
42#include <iostream>
43
44#ifndef MFEM_USE_PETSC
45#error This example requires that MFEM is built with MFEM_USE_PETSC=YES
46#endif
47
48using namespace std;
49using namespace mfem;
50
51int main(int argc, char *argv[])
52{
53 // 1. Initialize MPI and HYPRE.
54 Mpi::Init(argc, argv);
55 int num_procs = Mpi::WorldSize();
56 int myid = Mpi::WorldRank();
58
59 // 2. Parse command-line options.
60 const char *mesh_file = "../../data/beam-tri.mesh";
61 int ser_ref_levels = -1;
62 int par_ref_levels = 1;
63 int order = 1;
64 bool static_cond = false;
65 bool visualization = 1;
66 bool amg_elast = 0;
67 bool use_petsc = true;
68 const char *petscrc_file = "";
69 bool use_nonoverlapping = false;
70
71 OptionsParser args(argc, argv);
73 "Mesh file to use.");
75 "Number of times to refine the mesh uniformly in serial.");
77 "Number of times to refine the mesh uniformly in parallel.");
79 "Finite element order (polynomial degree).");
81 "--amg-for-systems",
82 "Use the special AMG elasticity solver (GM/LN approaches), "
83 "or standard AMG for systems (unknown approach).");
85 "--no-static-condensation", "Enable static condensation.");
87 "--no-visualization",
88 "Enable or disable GLVis visualization.");
90 "--no-petsc",
91 "Use or not PETSc to solve the linear system.");
93 "PetscOptions file to use.");
95 "-no-nonoverlapping", "--no-nonoverlapping",
96 "Use or not the block diagonal PETSc's matrix format "
97 "for non-overlapping domain decomposition.");
98 args.Parse();
99 if (!args.Good())
100 {
101 if (myid == 0)
102 {
103 args.PrintUsage(cout);
104 }
105 return 1;
106 }
107 if (myid == 0)
108 {
109 args.PrintOptions(cout);
110 }
111
112 // 2b. We initialize PETSc
113 if (use_petsc) { MFEMInitializePetsc(NULL,NULL,petscrc_file,NULL); }
114
115 // 3. Read the (serial) mesh from the given mesh file on all processors. We
116 // can handle triangular, quadrilateral, tetrahedral, hexahedral, surface
117 // and volume meshes with the same code.
118 Mesh *mesh = new Mesh(mesh_file, 1, 1);
119 int dim = mesh->Dimension();
120
121 if (mesh->attributes.Max() < 2 || mesh->bdr_attributes.Max() < 2)
122 {
123 if (myid == 0)
124 cerr << "\nInput mesh should have at least two materials and "
125 << "two boundary attributes! (See schematic in ex2.cpp)\n"
126 << endl;
127 return 3;
128 }
129
130 // 4. Select the order of the finite element discretization space. For NURBS
131 // meshes, we increase the order by degree elevation.
132 if (mesh->NURBSext)
133 {
134 mesh->DegreeElevate(order, order);
135 }
136
137 // 5. Refine the serial mesh on all processors to increase the resolution. In
138 // this example we do 'ref_levels' of uniform refinement. We choose
139 // 'ref_levels' to be the largest number that gives a final mesh with no
140 // more than 1,000 elements.
141 {
142 int ref_levels = ser_ref_levels >= 0 ? ser_ref_levels :
143 (int)floor(log(1000./mesh->GetNE())/log(2.)/dim);
144 for (int l = 0; l < ref_levels; l++)
145 {
146 mesh->UniformRefinement();
147 }
148 }
149
150 // 6. Define a parallel mesh by a partitioning of the serial mesh. Refine
151 // this mesh further in parallel to increase the resolution. Once the
152 // parallel mesh is defined, the serial mesh can be deleted.
153 ParMesh *pmesh = new ParMesh(MPI_COMM_WORLD, *mesh);
154 delete mesh;
155 {
156 for (int l = 0; l < par_ref_levels; l++)
157 {
158 pmesh->UniformRefinement();
159 }
160 }
161
162 // 7. Define a parallel finite element space on the parallel mesh. Here we
163 // use vector finite elements, i.e. dim copies of a scalar finite element
164 // space. We use the ordering by vector dimension (the last argument of
165 // the FiniteElementSpace constructor) which is expected in the systems
166 // version of BoomerAMG preconditioner. For NURBS meshes, we use the
167 // (degree elevated) NURBS space associated with the mesh nodes.
169 ParFiniteElementSpace *fespace;
170 const bool use_nodal_fespace = pmesh->NURBSext && !amg_elast;
171 if (use_nodal_fespace)
172 {
173 fec = NULL;
174 fespace = (ParFiniteElementSpace *)pmesh->GetNodes()->FESpace();
175 }
176 else
177 {
178 fec = new H1_FECollection(order, dim);
179 fespace = new ParFiniteElementSpace(pmesh, fec, dim, Ordering::byVDIM);
180 }
181 HYPRE_BigInt size = fespace->GlobalTrueVSize();
182 if (myid == 0)
183 {
184 cout << "Number of finite element unknowns: " << size << endl
185 << "Assembling: " << flush;
186 }
187
188 // 8. Determine the list of true (i.e. parallel conforming) essential
189 // boundary dofs. In this example, the boundary conditions are defined by
190 // marking only boundary attribute 1 from the mesh as essential and
191 // converting it to a list of true dofs.
192 Array<int> ess_tdof_list, ess_bdr(pmesh->bdr_attributes.Max());
193 ess_bdr = 0;
194 ess_bdr[0] = 1;
195 fespace->GetEssentialTrueDofs(ess_bdr, ess_tdof_list);
196
197 // 9. Set up the parallel linear form b(.) which corresponds to the
198 // right-hand side of the FEM linear system. In this case, b_i equals the
199 // boundary integral of f*phi_i where f represents a "pull down" force on
200 // the Neumann part of the boundary and phi_i are the basis functions in
201 // the finite element fespace. The force is defined by the object f, which
202 // is a vector of Coefficient objects. The fact that f is non-zero on
203 // boundary attribute 2 is indicated by the use of piece-wise constants
204 // coefficient for its last component.
206 for (int i = 0; i < dim-1; i++)
207 {
208 f.Set(i, new ConstantCoefficient(0.0));
209 }
210 {
211 Vector pull_force(pmesh->bdr_attributes.Max());
212 pull_force = 0.0;
213 pull_force(1) = -1.0e-2;
214 f.Set(dim-1, new PWConstCoefficient(pull_force));
215 }
216
217 ParLinearForm *b = new ParLinearForm(fespace);
219 if (myid == 0)
220 {
221 cout << "r.h.s. ... " << flush;
222 }
223 b->Assemble();
224
225 // 10. Define the solution vector x as a parallel finite element grid
226 // function corresponding to fespace. Initialize x with initial guess of
227 // zero, which satisfies the boundary conditions.
228 ParGridFunction x(fespace);
229 x = 0.0;
230
231 // 11. Set up the parallel bilinear form a(.,.) on the finite element space
232 // corresponding to the linear elasticity integrator with piece-wise
233 // constants coefficient lambda and mu.
234 Vector lambda(pmesh->attributes.Max());
235 lambda = 1.0;
236 lambda(0) = lambda(1)*50;
237 PWConstCoefficient lambda_func(lambda);
238 Vector mu(pmesh->attributes.Max());
239 mu = 1.0;
240 mu(0) = mu(1)*50;
241 PWConstCoefficient mu_func(mu);
242
243 ParBilinearForm *a = new ParBilinearForm(fespace);
245
246 // 12. Assemble the parallel bilinear form and the corresponding linear
247 // system, applying any necessary transformations such as: parallel
248 // assembly, eliminating boundary conditions, applying conforming
249 // constraints for non-conforming AMR, static condensation, etc.
250 if (myid == 0) { cout << "matrix ... " << flush; }
251 if (static_cond) { a->EnableStaticCondensation(); }
252 // Here we want to try out block-size aware AMG solver in PETSc.
253 // For that to work properly, we need a fully-compliant block-size
254 // structure and we do not skip zeros when assembling.
255 a->Assemble(use_petsc ? 0 : 1);
256
257 Vector B, X;
258 if (!use_petsc)
259 {
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 // 13. 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 {
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 delete pcg;
286 delete amg;
287 }
288 else
289 {
290 // 13b. Use PETSc to solve the linear system.
291 // Assemble a PETSc matrix, so that PETSc solvers can be used natively.
293 a->SetOperatorType(use_nonoverlapping ?
295 a->FormLinearSystem(ess_tdof_list, x, *b, A, X, B);
296 if (myid == 0)
297 {
298 cout << "done." << endl;
299 cout << "Size of linear system: " << A.M() << endl;
300 }
301 // Tell PETSc the matrix has a block structure
302 A.SetBlockSize(dim);
303
304 // The preconditioner for the PCG solver can be specified in the
305 // PETSc config file
306 PetscPCGSolver *pcg = new PetscPCGSolver(A);
307 PetscPreconditioner *prec = NULL;
308 if (use_nonoverlapping) // Specialized BDDC construction
309 {
310 // Compute dofs belonging to the natural boundary
311 Array<int> nat_tdof_list, nat_bdr(pmesh->bdr_attributes.Max());
312 nat_bdr = 1;
313 nat_bdr[0] = 0;
314 fespace->GetEssentialTrueDofs(nat_bdr, nat_tdof_list);
315
316 // Auxiliary class for BDDC customization
318 // Inform the solver about the finite element space
319 opts.SetSpace(fespace);
320 // Inform the solver about essential dofs
321 opts.SetEssBdrDofs(&ess_tdof_list);
322 // Inform the solver about natural dofs
323 opts.SetNatBdrDofs(&nat_tdof_list);
324 // Create a BDDC solver with parameters
325 prec = new PetscBDDCSolver(A,opts);
326 pcg->SetPreconditioner(*prec);
327 }
328
329 pcg->SetMaxIter(500);
330 pcg->SetTol(1e-8);
331 pcg->SetPrintLevel(2);
332 pcg->Mult(B, X);
333 delete pcg;
334 delete prec;
335 }
336
337 // 14. Recover the parallel grid function corresponding to X. This is the
338 // local finite element solution on each processor.
339 a->RecoverFEMSolution(X, *b, x);
340
341 // 15. For non-NURBS meshes, make the mesh curved based on the finite element
342 // space. This means that we define the mesh elements through a fespace
343 // based transformation of the reference element. This allows us to save
344 // the displaced mesh as a curved mesh when using high-order finite
345 // element displacement field. We assume that the initial mesh (read from
346 // the file) is not higher order curved mesh compared to the chosen FE
347 // space.
348 if (!use_nodal_fespace)
349 {
350 pmesh->SetNodalFESpace(fespace);
351 }
352
353 // 16. Save in parallel the displaced mesh and the inverted solution (which
354 // gives the backward displacements to the original grid). This output
355 // can be viewed later using GLVis: "glvis -np <np> -m mesh -g sol".
356 {
357 GridFunction *nodes = pmesh->GetNodes();
358 *nodes += x;
359 x *= -1;
360
361 ostringstream mesh_name, sol_name;
362 mesh_name << "mesh." << setfill('0') << setw(6) << myid;
363 sol_name << "sol." << setfill('0') << setw(6) << myid;
364
365 ofstream mesh_ofs(mesh_name.str().c_str());
366 mesh_ofs.precision(8);
367 pmesh->Print(mesh_ofs);
368
369 ofstream sol_ofs(sol_name.str().c_str());
370 sol_ofs.precision(8);
371 x.Save(sol_ofs);
372 }
373
374 // 17. Send the above data by socket to a GLVis server. Use the "n" and "b"
375 // keys in GLVis to visualize the displacements.
376 if (visualization)
377 {
378 char vishost[] = "localhost";
379 int visport = 19916;
380 socketstream sol_sock(vishost, visport);
381 sol_sock << "parallel " << num_procs << " " << myid << "\n";
382 sol_sock.precision(8);
383 sol_sock << "solution\n" << *pmesh << x << flush;
384 }
385
386 // 18. Free the used memory.
387 delete a;
388 delete b;
389 if (fec)
390 {
391 delete fespace;
392 delete fec;
393 }
394 delete pmesh;
395
396 // We finalize PETSc
397 if (use_petsc) { MFEMFinalizePetsc(); }
398
399 return 0;
400}
T Max() const
Find the maximal element in the array, using the comparison operator < for class T.
Definition array.cpp:68
A coefficient that is constant across space and time.
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:31
Arbitrary order H1-conforming (continuous) finite elements.
Definition fe_coll.hpp:260
The BoomerAMG solver in hypre.
Definition hypre.hpp:1691
void SetSystemsOptions(int dim, bool order_bynodes=false)
Definition hypre.cpp:5111
void SetElasticityOptions(ParFiniteElementSpace *fespace, bool interp_refine=true)
Definition hypre.cpp:5238
PCG solver in hypre.
Definition hypre.hpp:1275
void SetPrintLevel(int print_lvl)
Definition hypre.cpp:4156
void SetPreconditioner(HypreSolver &precond)
Set the hypre solver to be used as a preconditioner.
Definition hypre.cpp:4161
virtual void Mult(const HypreParVector &b, HypreParVector &x) const
Solve Ax=b with hypre's PCG.
Definition hypre.cpp:4184
void SetMaxIter(int max_iter)
Definition hypre.cpp:4146
void SetTol(real_t tol)
Definition hypre.cpp:4136
Wrapper for hypre's ParCSR matrix class.
Definition hypre.hpp:388
HYPRE_BigInt GetGlobalNumRows() const
Return the global number of rows.
Definition hypre.hpp:679
static void Init()
Initialize hypre by calling HYPRE_Init() and set default options. After calling Hypre::Init(),...
Definition hypre.hpp:74
Mesh data type.
Definition mesh.hpp:56
Array< int > bdr_attributes
A list of all unique boundary attributes used by the Mesh.
Definition mesh.hpp:282
NURBSExtension * NURBSext
Optional NURBS mesh extension.
Definition mesh.hpp:290
int GetNE() const
Returns number of elements.
Definition mesh.hpp:1226
int Dimension() const
Dimension of the reference space used within the elements.
Definition mesh.hpp:1160
void GetNodes(Vector &node_coord) const
Definition mesh.cpp:8973
void DegreeElevate(int rel_degree, int degree=16)
Definition mesh.cpp:5779
void UniformRefinement(int i, const DSTable &, int *, int *, int *)
Definition mesh.cpp:10970
Array< int > attributes
A list of all unique element attributes used by the Mesh.
Definition mesh.hpp:280
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 FormLinearSystem(const Array< int > &ess_tdof_list, Vector &x, Vector &b, Operator *&A, Vector &X, Vector &B, int copy_interior=0)
Form a constrained linear system using a matrix-free approach.
Definition operator.cpp:114
@ PETSC_MATIS
ID for class PetscParMatrix, MATIS format.
Definition operator.hpp:289
@ PETSC_MATAIJ
ID for class PetscParMatrix, MATAIJ format.
Definition operator.hpp:288
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:148
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:29
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:285
Class for parallel grid function.
Definition pgridfunc.hpp:33
void Save(std::ostream &out) const override
Class for parallel linear form.
Class for parallel meshes.
Definition pmesh.hpp:34
void SetNodalFESpace(FiniteElementSpace *nfes) override
Definition pmesh.cpp:2028
void Print(std::ostream &out=mfem::out, const std::string &comments="") const override
Definition pmesh.cpp:4801
Auxiliary class for BDDC customization.
Definition petsc.hpp:831
void SetEssBdrDofs(const Array< int > *essdofs, bool loc=false)
Specify dofs on the essential boundary.
Definition petsc.hpp:850
void SetSpace(ParFiniteElementSpace *fe)
Definition petsc.hpp:845
void SetNatBdrDofs(const Array< int > *natdofs, bool loc=false)
Specify dofs on the natural boundary.
Definition petsc.hpp:858
void SetPreconditioner(Solver &precond)
Definition petsc.cpp:3110
virtual void Mult(const Vector &b, Vector &x) const
Application of the solver.
Definition petsc.cpp:3190
Wrapper for PETSc's matrix class.
Definition petsc.hpp:319
PetscInt M() const
Returns the global number of rows.
Definition petsc.cpp:1005
void SetBlockSize(PetscInt rbs, PetscInt cbs=-1)
Set row and column block sizes of a matrix.
Definition petsc.cpp:1026
Abstract class for PETSc's preconditioners.
Definition petsc.hpp:805
void SetTol(real_t tol)
Definition petsc.cpp:2371
void SetPrintLevel(int plev)
Definition petsc.cpp:2453
void SetMaxIter(int max_iter)
Definition petsc.cpp:2426
Vector coefficient defined by an array of scalar coefficients. Coefficients that are not set will eva...
Vector data type.
Definition vector.hpp:80
Vector & Set(const real_t a, const Vector &x)
(*this) = a * x
Definition vector.cpp:262
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
const int visport
void MFEMInitializePetsc()
Convenience functions to initialize/finalize PETSc.
Definition petsc.cpp:201
void MFEMFinalizePetsc()
Definition petsc.cpp:241
std::function< real_t(const Vector &)> f(real_t mass_coeff)
Definition lor_mms.hpp:30
const char vishost[]