MFEM  v4.4.0
Finite element discretization library
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Pages
ex29p.cpp
Go to the documentation of this file.
1 // MFEM Example 29 - Parallel Version
2 //
3 // Compile with: make ex29p
4 //
5 // Sample runs: mpirun -np 4 ex29p
6 // mpirun -np 4 ex29p -sc
7 // mpirun -np 4 ex29p -mt 3 -o 3 -sc
8 // mpirun -np 4 ex29p -mt 3 -rs 1 -o 4 -sc
9 //
10 // Description: This example code demonstrates the use of MFEM to define a
11 // finite element discretization of a PDE on a 2 dimensional
12 // surface embedded in a 3 dimensional domain. In this case we
13 // solve the Laplace problem -Div(sigma Grad u) = 1, with
14 // homogeneous Dirichlet boundary conditions, where sigma is an
15 // anisotropic diffusion constant defined as a 3x3 matrix
16 // coefficient.
17 //
18 // This example demonstrates the use of finite element integrators
19 // on 2D domains with 3D coefficients.
20 //
21 // We recommend viewing examples 1 and 7 before viewing this
22 // example.
23 
24 #include "mfem.hpp"
25 #include <fstream>
26 #include <iostream>
27 
28 using namespace std;
29 using namespace mfem;
30 
31 Mesh * GetMesh(int type);
32 
33 void trans(const Vector &x, Vector &r);
34 
35 void sigmaFunc(const Vector &x, DenseMatrix &s);
36 
37 double uExact(const Vector &x)
38 {
39  return (0.25 * (2.0 + x[0]) - x[2]) * (x[2] + 0.25 * (2.0 + x[0]));
40 }
41 
42 void duExact(const Vector &x, Vector &du)
43 {
44  du.SetSize(3);
45  du[0] = 0.125 * (2.0 + x[0]) * x[1] * x[1];
46  du[1] = -0.125 * (2.0 + x[0]) * x[0] * x[1];
47  du[2] = -2.0 * x[2];
48 }
49 
50 void fluxExact(const Vector &x, Vector &f)
51 {
52  f.SetSize(3);
53 
54  DenseMatrix s(3);
55  sigmaFunc(x, s);
56 
57  Vector du(3);
58  duExact(x, du);
59 
60  s.Mult(du, f);
61  f *= -1.0;
62 }
63 
64 int main(int argc, char *argv[])
65 {
66  // 1. Initialize MPI and HYPRE.
67  Mpi::Init(argc, argv);
68  int num_procs = Mpi::WorldSize();
69  int myid = Mpi::WorldRank();
70  Hypre::Init();
71 
72  // 2. Parse command-line options.
73  int order = 3;
74  int mesh_type = 4; // Default to Quadrilateral mesh
75  int mesh_order = 3;
76  int ser_ref_levels = 2;
77  int par_ref_levels = 1;
78  bool static_cond = false;
79  bool visualization = true;
80 
81  OptionsParser args(argc, argv);
82  args.AddOption(&mesh_type, "-mt", "--mesh-type",
83  "Mesh type: 3 - Triangular, 4 - Quadrilateral.");
84  args.AddOption(&mesh_order, "-mo", "--mesh-order",
85  "Geometric order of the curved mesh.");
86  args.AddOption(&ser_ref_levels, "-rs", "--refine-serial",
87  "Number of times to refine the mesh uniformly in serial.");
88  args.AddOption(&par_ref_levels, "-rp", "--refine-parallel",
89  "Number of times to refine the mesh uniformly in parallel.");
90  args.AddOption(&order, "-o", "--order",
91  "Finite element order (polynomial degree) or -1 for"
92  " isoparametric space.");
93  args.AddOption(&static_cond, "-sc", "--static-condensation", "-no-sc",
94  "--no-static-condensation", "Enable static condensation.");
95  args.AddOption(&visualization, "-vis", "--visualization", "-no-vis",
96  "--no-visualization",
97  "Enable or disable GLVis visualization.");
98  args.ParseCheck();
99 
100  // 3. Construct a quadrilateral or triangular mesh with the topology of a
101  // cylindrical surface.
102  Mesh *mesh = GetMesh(mesh_type);
103  int dim = mesh->Dimension();
104 
105  // 4. Refine the mesh to increase the resolution. In this example we do
106  // 'ser_ref_levels' of uniform refinement.
107  for (int l = 0; l < ser_ref_levels; l++)
108  {
109  mesh->UniformRefinement();
110  }
111 
112  // 5. Define a parallel mesh by a partitioning of the serial mesh. Refine
113  // this mesh further in parallel to increase the resolution. Once the
114  // parallel mesh is defined, the serial mesh can be deleted.
115  ParMesh pmesh(MPI_COMM_WORLD, *mesh);
116  delete mesh;
117  for (int l = 0; l < par_ref_levels; l++)
118  {
119  pmesh.UniformRefinement();
120  }
121 
122  // 6. Transform the mesh so that it has a more interesting geometry.
123  pmesh.SetCurvature(mesh_order);
124  pmesh.Transform(trans);
125 
126  // 7. Define a finite element space on the mesh. Here we use continuous
127  // Lagrange finite elements of the specified order.
128  H1_FECollection fec(order, dim);
129  ParFiniteElementSpace fespace(&pmesh, &fec);
130  HYPRE_Int total_num_dofs = fespace.GlobalTrueVSize();
131  if (Mpi::Root())
132  {
133  cout << "Number of unknowns: " << total_num_dofs << endl;
134  }
135 
136  // 8. Determine the list of true (i.e. conforming) essential boundary dofs.
137  // In this example, the boundary conditions are defined by marking all
138  // the boundary attributes from the mesh as essential (Dirichlet) and
139  // converting them to a list of true dofs.
140  Array<int> ess_tdof_list;
141  if (pmesh.bdr_attributes.Size())
142  {
143  Array<int> ess_bdr(pmesh.bdr_attributes.Max());
144  ess_bdr = 1;
145  fespace.GetEssentialTrueDofs(ess_bdr, ess_tdof_list);
146  }
147 
148  // 9. Set up the linear form b(.) which corresponds to the right-hand side of
149  // the FEM linear system, which in this case is (1,phi_i) where phi_i are
150  // the basis functions in the finite element fespace.
151  ParLinearForm b(&fespace);
152  ConstantCoefficient one(1.0);
154  b.Assemble();
155 
156  // 10. Define the solution vector x as a finite element grid function
157  // corresponding to fespace. Initialize x with initial guess of zero,
158  // which satisfies the boundary conditions.
159  ParGridFunction x(&fespace);
160  x = 0.0;
161 
162  // 11. Set up the bilinear form a(.,.) on the finite element space
163  // corresponding to the Laplacian operator -Delta, by adding the
164  // Diffusion domain integrator.
165  ParBilinearForm a(&fespace);
167  BilinearFormIntegrator *integ = new DiffusionIntegrator(sigma);
168  a.AddDomainIntegrator(integ);
169 
170  // 12. Assemble the bilinear form and the corresponding linear system,
171  // applying any necessary transformations such as: eliminating boundary
172  // conditions, applying conforming constraints for non-conforming AMR,
173  // static condensation, etc.
174  if (static_cond) { a.EnableStaticCondensation(); }
175  a.Assemble();
176 
177  OperatorPtr A;
178  Vector B, X;
179  a.FormLinearSystem(ess_tdof_list, x, b, A, X, B);
180 
181  if (myid == 0)
182  {
183  cout << "Size of linear system: "
184  << A.As<HypreParMatrix>()->GetGlobalNumRows() << endl;
185  }
186 
187  // 13. Define and apply a parallel PCG solver for A X = B with the BoomerAMG
188  // preconditioner from hypre.
189  HypreBoomerAMG *amg = new HypreBoomerAMG;
190  CGSolver cg(MPI_COMM_WORLD);
191  cg.SetRelTol(1e-12);
192  cg.SetMaxIter(2000);
193  cg.SetPrintLevel(1);
194  cg.SetPreconditioner(*amg);
195  cg.SetOperator(*A);
196  cg.Mult(B, X);
197  delete amg;
198 
199  // 14. Recover the solution as a finite element grid function.
200  a.RecoverFEMSolution(X, b, x);
201 
202  // 15. Compute error in the solution and its flux
204  double error = x.ComputeL2Error(uCoef);
205 
206  if (myid == 0) { cout << "|u - u_h|_2 = " << error << endl; }
207 
208  ParFiniteElementSpace flux_fespace(&pmesh, &fec, 3);
209  ParGridFunction flux(&flux_fespace);
210  x.ComputeFlux(*integ, flux); flux *= -1.0;
211 
213  double flux_err = flux.ComputeL2Error(fluxCoef);
214 
215  if (myid == 0) { cout << "|f - f_h|_2 = " << flux_err << endl; }
216 
217  // 16. Save the refined mesh and the solution. This output can be viewed
218  // later using GLVis: "glvis -np <np> -m mesh -g sol".
219  {
220  ostringstream mesh_name, sol_name, flux_name;
221  mesh_name << "mesh." << setfill('0') << setw(6) << myid;
222  sol_name << "sol." << setfill('0') << setw(6) << myid;
223  flux_name << "flux." << setfill('0') << setw(6) << myid;
224 
225  ofstream mesh_ofs(mesh_name.str().c_str());
226  mesh_ofs.precision(8);
227  pmesh.Print(mesh_ofs);
228 
229  ofstream sol_ofs(sol_name.str().c_str());
230  sol_ofs.precision(8);
231  x.Save(sol_ofs);
232 
233  ofstream flux_ofs(flux_name.str().c_str());
234  flux_ofs.precision(8);
235  flux.Save(flux_ofs);
236  }
237 
238  // 17. Send the solution by socket to a GLVis server.
239  if (visualization)
240  {
241  char vishost[] = "localhost";
242  int visport = 19916;
243  socketstream sol_sock(vishost, visport);
244  sol_sock << "parallel " << num_procs << " " << myid << "\n";
245  sol_sock.precision(8);
246  sol_sock << "solution\n" << pmesh << x
247  << "window_title 'Solution'\n" << flush;
248 
249  socketstream flux_sock(vishost, visport);
250  flux_sock << "parallel " << num_procs << " " << myid << "\n";
251  flux_sock.precision(8);
252  flux_sock << "solution\n" << pmesh << flux
253  << "keys vvv\n"
254  << "window_geometry 402 0 400 350\n"
255  << "window_title 'Flux'\n" << flush;
256  }
257 
258  return 0;
259 }
260 
261 // Defines a mesh consisting of four flat rectangular surfaces connected to form
262 // a loop.
263 Mesh * GetMesh(int type)
264 {
265  Mesh * mesh = NULL;
266 
267  if (type == 3)
268  {
269  mesh = new Mesh(2, 12, 16, 8, 3);
270 
271  mesh->AddVertex(-1.0, -1.0, 0.0);
272  mesh->AddVertex( 1.0, -1.0, 0.0);
273  mesh->AddVertex( 1.0, 1.0, 0.0);
274  mesh->AddVertex(-1.0, 1.0, 0.0);
275  mesh->AddVertex(-1.0, -1.0, 1.0);
276  mesh->AddVertex( 1.0, -1.0, 1.0);
277  mesh->AddVertex( 1.0, 1.0, 1.0);
278  mesh->AddVertex(-1.0, 1.0, 1.0);
279  mesh->AddVertex( 0.0, -1.0, 0.5);
280  mesh->AddVertex( 1.0, 0.0, 0.5);
281  mesh->AddVertex( 0.0, 1.0, 0.5);
282  mesh->AddVertex(-1.0, 0.0, 0.5);
283 
284  mesh->AddTriangle(0, 1, 8);
285  mesh->AddTriangle(1, 5, 8);
286  mesh->AddTriangle(5, 4, 8);
287  mesh->AddTriangle(4, 0, 8);
288  mesh->AddTriangle(1, 2, 9);
289  mesh->AddTriangle(2, 6, 9);
290  mesh->AddTriangle(6, 5, 9);
291  mesh->AddTriangle(5, 1, 9);
292  mesh->AddTriangle(2, 3, 10);
293  mesh->AddTriangle(3, 7, 10);
294  mesh->AddTriangle(7, 6, 10);
295  mesh->AddTriangle(6, 2, 10);
296  mesh->AddTriangle(3, 0, 11);
297  mesh->AddTriangle(0, 4, 11);
298  mesh->AddTriangle(4, 7, 11);
299  mesh->AddTriangle(7, 3, 11);
300 
301  mesh->AddBdrSegment(0, 1, 1);
302  mesh->AddBdrSegment(1, 2, 1);
303  mesh->AddBdrSegment(2, 3, 1);
304  mesh->AddBdrSegment(3, 0, 1);
305  mesh->AddBdrSegment(5, 4, 2);
306  mesh->AddBdrSegment(6, 5, 2);
307  mesh->AddBdrSegment(7, 6, 2);
308  mesh->AddBdrSegment(4, 7, 2);
309  }
310  else if (type == 4)
311  {
312  mesh = new Mesh(2, 8, 4, 8, 3);
313 
314  mesh->AddVertex(-1.0, -1.0, 0.0);
315  mesh->AddVertex( 1.0, -1.0, 0.0);
316  mesh->AddVertex( 1.0, 1.0, 0.0);
317  mesh->AddVertex(-1.0, 1.0, 0.0);
318  mesh->AddVertex(-1.0, -1.0, 1.0);
319  mesh->AddVertex( 1.0, -1.0, 1.0);
320  mesh->AddVertex( 1.0, 1.0, 1.0);
321  mesh->AddVertex(-1.0, 1.0, 1.0);
322 
323  mesh->AddQuad(0, 1, 5, 4);
324  mesh->AddQuad(1, 2, 6, 5);
325  mesh->AddQuad(2, 3, 7, 6);
326  mesh->AddQuad(3, 0, 4, 7);
327 
328  mesh->AddBdrSegment(0, 1, 1);
329  mesh->AddBdrSegment(1, 2, 1);
330  mesh->AddBdrSegment(2, 3, 1);
331  mesh->AddBdrSegment(3, 0, 1);
332  mesh->AddBdrSegment(5, 4, 2);
333  mesh->AddBdrSegment(6, 5, 2);
334  mesh->AddBdrSegment(7, 6, 2);
335  mesh->AddBdrSegment(4, 7, 2);
336  }
337  else
338  {
339  MFEM_ABORT("Unrecognized mesh type " << type << "!");
340  }
341  mesh->FinalizeTopology();
342 
343  return mesh;
344 }
345 
346 // Transforms the four-sided loop into a curved cylinder with skewed top and
347 // base.
348 void trans(const Vector &x, Vector &r)
349 {
350  r.SetSize(3);
351 
352  double tol = 1e-6;
353  double theta = 0.0;
354  if (fabs(x[1] + 1.0) < tol)
355  {
356  theta = 0.25 * M_PI * (x[0] - 2.0);
357  }
358  else if (fabs(x[0] - 1.0) < tol)
359  {
360  theta = 0.25 * M_PI * x[1];
361  }
362  else if (fabs(x[1] - 1.0) < tol)
363  {
364  theta = 0.25 * M_PI * (2.0 - x[0]);
365  }
366  else if (fabs(x[0] + 1.0) < tol)
367  {
368  theta = 0.25 * M_PI * (4.0 - x[1]);
369  }
370  else
371  {
372  cerr << "side not recognized "
373  << x[0] << " " << x[1] << " " << x[2] << endl;
374  }
375 
376  r[0] = cos(theta);
377  r[1] = sin(theta);
378  r[2] = 0.25 * (2.0 * x[2] - 1.0) * (r[0] + 2.0);
379 }
380 
381 // Anisotropic diffusion coefficient
382 void sigmaFunc(const Vector &x, DenseMatrix &s)
383 {
384  s.SetSize(3);
385  double a = 17.0 - 2.0 * x[0] * (1.0 + x[0]);
386  s(0,0) = 0.5 + x[0] * x[0] * (8.0 / a - 0.5);
387  s(0,1) = x[0] * x[1] * (8.0 / a - 0.5);
388  s(0,2) = 0.0;
389  s(1,0) = s(0,1);
390  s(1,1) = 0.5 * x[0] * x[0] + 8.0 * x[1] * x[1] / a;
391  s(1,2) = 0.0;
392  s(2,0) = 0.0;
393  s(2,1) = 0.0;
394  s(2,2) = a / 32.0;
395 }
int Size() const
Return the logical size of the array.
Definition: array.hpp:138
Class for domain integration L(v) := (f, v)
Definition: lininteg.hpp:97
void duExact(const Vector &x, Vector &du)
Definition: ex29.cpp:42
virtual void GetEssentialTrueDofs(const Array< int > &bdr_attr_is_ess, Array< int > &ess_tdof_list, int component=-1)
Definition: pfespace.cpp:1032
Conjugate gradient method.
Definition: solvers.hpp:465
void trans(const Vector &u, Vector &x)
Definition: ex27.cpp:412
OpType * As() const
Return the Operator pointer statically cast to a specified OpType. Similar to the method Get()...
Definition: handle.hpp:104
int AddQuad(int v1, int v2, int v3, int v4, int attr=1)
Definition: mesh.cpp:1662
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(...
virtual void Mult(const Vector &b, Vector &x) const
Operator application: y=A(x).
Definition: solvers.cpp:711
void SetSize(int s)
Resize the vector to size s.
Definition: vector.hpp:521
Pointer to an Operator of a specified type.
Definition: handle.hpp:33
HYPRE_BigInt GlobalTrueVSize() const
Definition: pfespace.hpp:285
void sigmaFunc(const Vector &x, DenseMatrix &s)
Definition: ex29.cpp:337
int AddTriangle(int v1, int v2, int v3, int attr=1)
Definition: mesh.cpp:1648
Data type dense matrix using column-major storage.
Definition: densemat.hpp:23
void Transform(void(*f)(const Vector &, Vector &))
Definition: mesh.cpp:11551
virtual void Save(std::ostream &out) const
Definition: pgridfunc.cpp:873
Abstract parallel finite element space.
Definition: pfespace.hpp:28
The BoomerAMG solver in hypre.
Definition: hypre.hpp:1443
int AddVertex(double x, double y=0.0, double z=0.0)
Definition: mesh.cpp:1601
Class for parallel linear form.
Definition: plinearform.hpp:26
virtual void SetPrintLevel(int print_lvl)
Legacy method to set the level of verbosity of the solver output.
Definition: solvers.cpp:71
A matrix coefficient with an optional scalar coefficient multiplier q. The matrix function can either...
constexpr char vishost[]
double b
Definition: lissajous.cpp:42
void UniformRefinement(int i, const DSTable &, int *, int *, int *)
Definition: mesh.cpp:9737
constexpr int visport
void SetMaxIter(int max_it)
Definition: solvers.hpp:200
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.
int AddBdrSegment(int v1, int v2, int attr=1)
Definition: mesh.cpp:1811
int Dimension() const
Definition: mesh.hpp:999
FDualNumber< tbase > cos(const FDualNumber< tbase > &f)
cos([dual number])
Definition: fdual.hpp:471
A general vector function coefficient.
void AddDomainIntegrator(LinearFormIntegrator *lfi)
Adds new Domain Integrator. Assumes ownership of lfi.
Definition: linearform.cpp:39
Abstract base class BilinearFormIntegrator.
Definition: bilininteg.hpp:34
Array< int > bdr_attributes
A list of all unique boundary attributes used by the Mesh.
Definition: mesh.hpp:270
void SetRelTol(double rtol)
Definition: solvers.hpp:198
FDualNumber< tbase > sin(const FDualNumber< tbase > &f)
sin([dual number])
Definition: fdual.hpp:572
virtual void ComputeFlux(BilinearFormIntegrator &blfi, GridFunction &flux, bool wcoef=true, int subdomain=-1)
Definition: pgridfunc.cpp:1100
void FinalizeTopology(bool generate_bdr=true)
Finalize the construction of the secondary topology (connectivity) data of a Mesh.
Definition: mesh.cpp:2878
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
virtual void RecoverFEMSolution(const Vector &X, const Vector &b, Vector &x)
double a
Definition: lissajous.cpp:41
virtual double ComputeL2Error(Coefficient *exsol[], const IntegrationRule *irs[]=NULL) const
Definition: pgridfunc.hpp:281
double uExact(const Vector &x)
Definition: ex29.cpp:37
Mesh * GetMesh(int type)
Definition: ex29.cpp:218
int dim
Definition: ex24.cpp:53
void SetCurvature(int order, bool discont=false, int space_dim=-1, int ordering=1) override
Definition: pmesh.cpp:1973
void AddDomainIntegrator(BilinearFormIntegrator *bfi)
Adds new Domain Integrator. Assumes ownership of bfi.
Class for parallel bilinear form.
virtual void SetOperator(const Operator &op)
Also calls SetOperator for the preconditioner if there is one.
Definition: solvers.hpp:479
A general function coefficient.
Vector data type.
Definition: vector.hpp:60
void Mult(const double *x, double *y) const
Matrix vector multiplication.
Definition: densemat.cpp:160
virtual void SetPreconditioner(Solver &pr)
This should be called before SetOperator.
Definition: solvers.cpp:173
Arbitrary order H1-conforming (continuous) finite elements.
Definition: fe_coll.hpp:216
RefCoord s[3]
void Print(std::ostream &out=mfem::out) const override
Definition: pmesh.cpp:4684
Class for parallel grid function.
Definition: pgridfunc.hpp:32
void fluxExact(const Vector &x, Vector &f)
Definition: ex29.cpp:50
void SetSize(int s)
Change the size of the DenseMatrix to s x s.
Definition: densemat.hpp:105
Wrapper for hypre&#39;s ParCSR matrix class.
Definition: hypre.hpp:337
Class for parallel meshes.
Definition: pmesh.hpp:32
int main()
void ParseCheck(std::ostream &out=mfem::out)
Definition: optparser.cpp:252
void EnableStaticCondensation()
Enable the use of static condensation. For details see the description for class StaticCondensation i...
double f(const Vector &p)
double sigma(const Vector &x)
Definition: maxwell.cpp:102