MFEM  v4.3.0
Finite element discretization library
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Pages
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
13 // where sigma(u)=lambda*div(u)*I+mu*(grad*u+u*grad) is the stress
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 // We recommend viewing Example 1 before viewing this example.
35 
36 #include "mfem.hpp"
37 #include <fstream>
38 #include <iostream>
39 
40 #ifndef MFEM_USE_PETSC
41 #error This example requires that MFEM is built with MFEM_USE_PETSC=YES
42 #endif
43 
44 using namespace std;
45 using namespace mfem;
46 
47 int main(int argc, char *argv[])
48 {
49  // 1. Initialize MPI.
50  int num_procs, myid;
51  MPI_Init(&argc, &argv);
52  MPI_Comm_size(MPI_COMM_WORLD, &num_procs);
53  MPI_Comm_rank(MPI_COMM_WORLD, &myid);
54 
55  // 2. Parse command-line options.
56  const char *mesh_file = "../../data/beam-tri.mesh";
57  int order = 1;
58  bool static_cond = false;
59  bool visualization = 1;
60  bool amg_elast = 0;
61  bool use_petsc = true;
62  const char *petscrc_file = "";
63  bool use_nonoverlapping = false;
64 
65  OptionsParser args(argc, argv);
66  args.AddOption(&mesh_file, "-m", "--mesh",
67  "Mesh file to use.");
68  args.AddOption(&order, "-o", "--order",
69  "Finite element order (polynomial degree).");
70  args.AddOption(&amg_elast, "-elast", "--amg-for-elasticity", "-sys",
71  "--amg-for-systems",
72  "Use the special AMG elasticity solver (GM/LN approaches), "
73  "or standard AMG for systems (unknown approach).");
74  args.AddOption(&static_cond, "-sc", "--static-condensation", "-no-sc",
75  "--no-static-condensation", "Enable static condensation.");
76  args.AddOption(&visualization, "-vis", "--visualization", "-no-vis",
77  "--no-visualization",
78  "Enable or disable GLVis visualization.");
79  args.AddOption(&use_petsc, "-usepetsc", "--usepetsc", "-no-petsc",
80  "--no-petsc",
81  "Use or not PETSc to solve the linear system.");
82  args.AddOption(&petscrc_file, "-petscopts", "--petscopts",
83  "PetscOptions file to use.");
84  args.AddOption(&use_nonoverlapping, "-nonoverlapping", "--nonoverlapping",
85  "-no-nonoverlapping", "--no-nonoverlapping",
86  "Use or not the block diagonal PETSc's matrix format "
87  "for non-overlapping domain decomposition.");
88  args.Parse();
89  if (!args.Good())
90  {
91  if (myid == 0)
92  {
93  args.PrintUsage(cout);
94  }
95  MPI_Finalize();
96  return 1;
97  }
98  if (myid == 0)
99  {
100  args.PrintOptions(cout);
101  }
102 
103  // 2b. We initialize PETSc
104  if (use_petsc) { MFEMInitializePetsc(NULL,NULL,petscrc_file,NULL); }
105 
106  // 3. Read the (serial) mesh from the given mesh file on all processors. We
107  // can handle triangular, quadrilateral, tetrahedral, hexahedral, surface
108  // and volume meshes with the same code.
109  Mesh *mesh = new Mesh(mesh_file, 1, 1);
110  int dim = mesh->Dimension();
111 
112  if (mesh->attributes.Max() < 2 || mesh->bdr_attributes.Max() < 2)
113  {
114  if (myid == 0)
115  cerr << "\nInput mesh should have at least two materials and "
116  << "two boundary attributes! (See schematic in ex2.cpp)\n"
117  << endl;
118  MPI_Finalize();
119  return 3;
120  }
121 
122  // 4. Select the order of the finite element discretization space. For NURBS
123  // meshes, we increase the order by degree elevation.
124  if (mesh->NURBSext)
125  {
126  mesh->DegreeElevate(order, order);
127  }
128 
129  // 5. Refine the serial mesh on all processors to increase the resolution. In
130  // this example we do 'ref_levels' of uniform refinement. We choose
131  // 'ref_levels' to be the largest number that gives a final mesh with no
132  // more than 1,000 elements.
133  {
134  int ref_levels =
135  (int)floor(log(1000./mesh->GetNE())/log(2.)/dim);
136  for (int l = 0; l < ref_levels; l++)
137  {
138  mesh->UniformRefinement();
139  }
140  }
141 
142  // 6. Define a parallel mesh by a partitioning of the serial mesh. Refine
143  // this mesh further in parallel to increase the resolution. Once the
144  // parallel mesh is defined, the serial mesh can be deleted.
145  ParMesh *pmesh = new ParMesh(MPI_COMM_WORLD, *mesh);
146  delete mesh;
147  {
148  int par_ref_levels = 1;
149  for (int l = 0; l < par_ref_levels; l++)
150  {
151  pmesh->UniformRefinement();
152  }
153  }
154 
155  // 7. Define a parallel finite element space on the parallel mesh. Here we
156  // use vector finite elements, i.e. dim copies of a scalar finite element
157  // space. We use the ordering by vector dimension (the last argument of
158  // the FiniteElementSpace constructor) which is expected in the systems
159  // version of BoomerAMG preconditioner. For NURBS meshes, we use the
160  // (degree elevated) NURBS space associated with the mesh nodes.
162  ParFiniteElementSpace *fespace;
163  const bool use_nodal_fespace = pmesh->NURBSext && !amg_elast;
164  if (use_nodal_fespace)
165  {
166  fec = NULL;
167  fespace = (ParFiniteElementSpace *)pmesh->GetNodes()->FESpace();
168  }
169  else
170  {
171  fec = new H1_FECollection(order, dim);
172  fespace = new ParFiniteElementSpace(pmesh, fec, dim, Ordering::byVDIM);
173  }
174  HYPRE_BigInt size = fespace->GlobalTrueVSize();
175  if (myid == 0)
176  {
177  cout << "Number of finite element unknowns: " << size << endl
178  << "Assembling: " << flush;
179  }
180 
181  // 8. Determine the list of true (i.e. parallel conforming) essential
182  // boundary dofs. In this example, the boundary conditions are defined by
183  // marking only boundary attribute 1 from the mesh as essential and
184  // converting it to a list of true dofs.
185  Array<int> ess_tdof_list, ess_bdr(pmesh->bdr_attributes.Max());
186  ess_bdr = 0;
187  ess_bdr[0] = 1;
188  fespace->GetEssentialTrueDofs(ess_bdr, ess_tdof_list);
189 
190  // 9. Set up the parallel linear form b(.) which corresponds to the
191  // right-hand side of the FEM linear system. In this case, b_i equals the
192  // boundary integral of f*phi_i where f represents a "pull down" force on
193  // the Neumann part of the boundary and phi_i are the basis functions in
194  // the finite element fespace. The force is defined by the object f, which
195  // is a vector of Coefficient objects. The fact that f is non-zero on
196  // boundary attribute 2 is indicated by the use of piece-wise constants
197  // coefficient for its last component.
199  for (int i = 0; i < dim-1; i++)
200  {
201  f.Set(i, new ConstantCoefficient(0.0));
202  }
203  {
204  Vector pull_force(pmesh->bdr_attributes.Max());
205  pull_force = 0.0;
206  pull_force(1) = -1.0e-2;
207  f.Set(dim-1, new PWConstCoefficient(pull_force));
208  }
209 
210  ParLinearForm *b = new ParLinearForm(fespace);
212  if (myid == 0)
213  {
214  cout << "r.h.s. ... " << flush;
215  }
216  b->Assemble();
217 
218  // 10. Define the solution vector x as a parallel finite element grid
219  // function corresponding to fespace. Initialize x with initial guess of
220  // zero, which satisfies the boundary conditions.
221  ParGridFunction x(fespace);
222  x = 0.0;
223 
224  // 11. Set up the parallel bilinear form a(.,.) on the finite element space
225  // corresponding to the linear elasticity integrator with piece-wise
226  // constants coefficient lambda and mu.
227  Vector lambda(pmesh->attributes.Max());
228  lambda = 1.0;
229  lambda(0) = lambda(1)*50;
230  PWConstCoefficient lambda_func(lambda);
231  Vector mu(pmesh->attributes.Max());
232  mu = 1.0;
233  mu(0) = mu(1)*50;
234  PWConstCoefficient mu_func(mu);
235 
236  ParBilinearForm *a = new ParBilinearForm(fespace);
237  a->AddDomainIntegrator(new ElasticityIntegrator(lambda_func, mu_func));
238 
239  // 12. Assemble the parallel bilinear form and the corresponding linear
240  // system, applying any necessary transformations such as: parallel
241  // assembly, eliminating boundary conditions, applying conforming
242  // constraints for non-conforming AMR, static condensation, etc.
243  if (myid == 0) { cout << "matrix ... " << flush; }
244  if (static_cond) { a->EnableStaticCondensation(); }
245  a->Assemble();
246 
247  Vector B, X;
248  if (!use_petsc)
249  {
250  HypreParMatrix A;
251  a->FormLinearSystem(ess_tdof_list, x, *b, A, X, B);
252  if (myid == 0)
253  {
254  cout << "done." << endl;
255  cout << "Size of linear system: " << A.GetGlobalNumRows() << endl;
256  }
257 
258  // 13. Define and apply a parallel PCG solver for A X = B with the BoomerAMG
259  // preconditioner from hypre.
260  HypreBoomerAMG *amg = new HypreBoomerAMG(A);
261  if (amg_elast && !a->StaticCondensationIsEnabled())
262  {
263  amg->SetElasticityOptions(fespace);
264  }
265  else
266  {
267  amg->SetSystemsOptions(dim);
268  }
269  HyprePCG *pcg = new HyprePCG(A);
270  pcg->SetTol(1e-8);
271  pcg->SetMaxIter(500);
272  pcg->SetPrintLevel(2);
273  pcg->SetPreconditioner(*amg);
274  pcg->Mult(B, X);
275  delete pcg;
276  delete amg;
277  }
278  else
279  {
280  // 13b. Use PETSc to solve the linear system.
281  // Assemble a PETSc matrix, so that PETSc solvers can be used natively.
282  PetscParMatrix A;
283  a->SetOperatorType(use_nonoverlapping ?
284  Operator::PETSC_MATIS : Operator::PETSC_MATAIJ);
285  a->FormLinearSystem(ess_tdof_list, x, *b, A, X, B);
286  if (myid == 0)
287  {
288  cout << "done." << endl;
289  cout << "Size of linear system: " << A.M() << endl;
290  }
291  PetscPCGSolver *pcg = new PetscPCGSolver(A);
292 
293  // The preconditioner for the PCG solver defined below is specified in the
294  // PETSc config file, rc_ex2p, since a Krylov solver in PETSc can also
295  // customize its preconditioner.
296  PetscPreconditioner *prec = NULL;
297  if (use_nonoverlapping)
298  {
299  // Auxiliary class for BDDC customization
301  // Inform the solver about the finite element space
302  opts.SetSpace(fespace);
303  // Inform the solver about essential dofs
304  opts.SetEssBdrDofs(&ess_tdof_list);
305  // Create a BDDC solver with parameters
306  prec = new PetscBDDCSolver(A,opts);
307  pcg->SetPreconditioner(*prec);
308  }
309 
310  pcg->SetMaxIter(500);
311  pcg->SetTol(1e-8);
312  pcg->SetPrintLevel(2);
313  pcg->Mult(B, X);
314  delete pcg;
315  delete prec;
316  }
317 
318  // 14. Recover the parallel grid function corresponding to X. This is the
319  // local finite element solution on each processor.
320  a->RecoverFEMSolution(X, *b, x);
321 
322  // 15. For non-NURBS meshes, make the mesh curved based on the finite element
323  // space. This means that we define the mesh elements through a fespace
324  // based transformation of the reference element. This allows us to save
325  // the displaced mesh as a curved mesh when using high-order finite
326  // element displacement field. We assume that the initial mesh (read from
327  // the file) is not higher order curved mesh compared to the chosen FE
328  // space.
329  if (!use_nodal_fespace)
330  {
331  pmesh->SetNodalFESpace(fespace);
332  }
333 
334  // 16. Save in parallel the displaced mesh and the inverted solution (which
335  // gives the backward displacements to the original grid). This output
336  // can be viewed later using GLVis: "glvis -np <np> -m mesh -g sol".
337  {
338  GridFunction *nodes = pmesh->GetNodes();
339  *nodes += x;
340  x *= -1;
341 
342  ostringstream mesh_name, sol_name;
343  mesh_name << "mesh." << setfill('0') << setw(6) << myid;
344  sol_name << "sol." << setfill('0') << setw(6) << myid;
345 
346  ofstream mesh_ofs(mesh_name.str().c_str());
347  mesh_ofs.precision(8);
348  pmesh->Print(mesh_ofs);
349 
350  ofstream sol_ofs(sol_name.str().c_str());
351  sol_ofs.precision(8);
352  x.Save(sol_ofs);
353  }
354 
355  // 17. Send the above data by socket to a GLVis server. Use the "n" and "b"
356  // keys in GLVis to visualize the displacements.
357  if (visualization)
358  {
359  char vishost[] = "localhost";
360  int visport = 19916;
361  socketstream sol_sock(vishost, visport);
362  sol_sock << "parallel " << num_procs << " " << myid << "\n";
363  sol_sock.precision(8);
364  sol_sock << "solution\n" << *pmesh << x << flush;
365  }
366 
367  // 18. Free the used memory.
368  delete a;
369  delete b;
370  if (fec)
371  {
372  delete fespace;
373  delete fec;
374  }
375  delete pmesh;
376 
377  // We finalize PETSc
378  if (use_petsc) { MFEMFinalizePetsc(); }
379 
380  MPI_Finalize();
381 
382  return 0;
383 }
void SetTol(double tol)
Definition: hypre.cpp:3569
void SetPreconditioner(Solver &precond)
Definition: petsc.cpp:3025
void SetPrintLevel(int plev)
Definition: petsc.cpp:2374
virtual void GetEssentialTrueDofs(const Array< int > &bdr_attr_is_ess, Array< int > &ess_tdof_list, int component=-1)
Definition: pfespace.cpp:790
Vector coefficient defined by an array of scalar coefficients. Coefficients that are not set will eva...
Class for grid function - Vector with associated FE space.
Definition: gridfunc.hpp:30
Abstract class for PETSc&#39;s preconditioners.
Definition: petsc.hpp:775
A coefficient that is constant across space and time.
Definition: coefficient.hpp:78
virtual void FormLinearSystem(const Array< int > &ess_tdof_list, Vector &x, Vector &b, OperatorHandle &A, Vector &X, Vector &B, int copy_interior=0)
Form the linear system A X = B, corresponding to this bilinear form and the linear form b(...
Wrapper for PETSc&#39;s matrix class.
Definition: petsc.hpp:307
HYPRE_BigInt GlobalTrueVSize() const
Definition: pfespace.hpp:275
int GetNE() const
Returns number of elements.
Definition: mesh.hpp:846
virtual void Save(std::ostream &out) const
Definition: pgridfunc.cpp:841
Abstract parallel finite element space.
Definition: pfespace.hpp:28
void SetMaxIter(int max_iter)
Definition: petsc.cpp:2347
void SetPrintLevel(int print_lvl)
Definition: hypre.cpp:3589
PetscInt M() const
Returns the global number of rows.
Definition: petsc.cpp:928
The BoomerAMG solver in hypre.
Definition: hypre.hpp:1387
void SetOperatorType(Operator::Type tid)
Set the operator type id for the parallel matrix/operator when using AssemblyLevel::LEGACY.
Class for parallel linear form.
Definition: plinearform.hpp:26
void Parse()
Parse the command-line options. Note that this function expects all the options provided through the ...
Definition: optparser.cpp:150
constexpr char vishost[]
double b
Definition: lissajous.cpp:42
void UniformRefinement(int i, const DSTable &, int *, int *, int *)
Definition: mesh.cpp:9143
constexpr int visport
Auxiliary class for BDDC customization.
Definition: petsc.hpp:801
T Max() const
Find the maximal element in the array, using the comparison operator &lt; for class T.
Definition: array.cpp:68
void Assemble(int skip_zeros=1)
Assemble the local matrix.
void Set(int i, Coefficient *c, bool own=true)
Sets coefficient in the vector.
virtual void Print(std::ostream &out=mfem::out) const
Definition: pmesh.cpp:4382
void SetElasticityOptions(ParFiniteElementSpace *fespace)
Definition: hypre.cpp:4569
void SetNodalFESpace(FiniteElementSpace *nfes)
Definition: mesh.cpp:4843
void AddBoundaryIntegrator(LinearFormIntegrator *lfi)
Adds new Boundary Integrator. Assumes ownership of lfi.
Definition: linearform.cpp:70
int Dimension() const
Definition: mesh.hpp:911
void PrintUsage(std::ostream &out) const
Print the usage message.
Definition: optparser.cpp:457
void SetMaxIter(int max_iter)
Definition: hypre.cpp:3579
bool StaticCondensationIsEnabled() const
Check if static condensation was actually enabled by a previous call to EnableStaticCondensation().
Array< int > bdr_attributes
A list of all unique boundary attributes used by the Mesh.
Definition: mesh.hpp:204
PCG solver in hypre.
Definition: hypre.hpp:1060
Collection of finite elements from the same family in multiple dimensions. This class is used to matc...
Definition: fe_coll.hpp:26
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 &#39;var&#39; to receive the value. Enable/disable tags are used to set the bool...
Definition: optparser.hpp:82
HYPRE_Int HYPRE_BigInt
virtual void RecoverFEMSolution(const Vector &X, const Vector &b, Vector &x)
double a
Definition: lissajous.cpp:41
NURBSExtension * NURBSext
Optional NURBS mesh extension.
Definition: mesh.hpp:206
void MFEMFinalizePetsc()
Definition: petsc.cpp:192
A piecewise constant coefficient with the constants keyed off the element attribute numbers...
Definition: coefficient.hpp:94
HYPRE_BigInt GetGlobalNumRows() const
Return the global number of rows.
Definition: hypre.hpp:573
void MFEMInitializePetsc()
Convenience functions to initialize/finalize PETSc.
Definition: petsc.cpp:168
double mu
Definition: ex25.cpp:139
void SetSpace(ParFiniteElementSpace *fe)
Definition: petsc.hpp:816
void DegreeElevate(int rel_degree, int degree=16)
Definition: mesh.cpp:4665
int dim
Definition: ex24.cpp:53
void SetPreconditioner(HypreSolver &precond)
Set the hypre solver to be used as a preconditioner.
Definition: hypre.cpp:3594
void AddDomainIntegrator(BilinearFormIntegrator *bfi)
Adds new Domain Integrator. Assumes ownership of bfi.
void PrintOptions(std::ostream &out) const
Print the options.
Definition: optparser.cpp:327
void SetTol(double tol)
Definition: petsc.cpp:2292
Class for parallel bilinear form.
Vector data type.
Definition: vector.hpp:60
void GetNodes(Vector &node_coord) const
Definition: mesh.cpp:7343
void SetSystemsOptions(int dim, bool order_bynodes=false)
Definition: hypre.cpp:4466
Arbitrary order H1-conforming (continuous) finite elements.
Definition: fe_coll.hpp:216
Class for parallel grid function.
Definition: pgridfunc.hpp:32
Wrapper for hypre&#39;s ParCSR matrix class.
Definition: hypre.hpp:277
virtual void Mult(const HypreParVector &b, HypreParVector &x) const
Solve Ax=b with hypre&#39;s PCG.
Definition: hypre.cpp:3617
virtual void Mult(const Vector &b, Vector &x) const
Application of the solver.
Definition: petsc.cpp:3105
Class for parallel meshes.
Definition: pmesh.hpp:32
void SetEssBdrDofs(const Array< int > *essdofs, bool loc=false)
Specify dofs on the essential boundary.
Definition: petsc.hpp:821
int main()
Array< int > attributes
A list of all unique element attributes used by the Mesh.
Definition: mesh.hpp:202
void EnableStaticCondensation()
Enable the use of static condensation. For details see the description for class StaticCondensation i...
double f(const Vector &p)
bool Good() const
Return true if the command line options were parsed successfully.
Definition: optparser.hpp:150