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