MFEM  v4.1.0 Finite element discretization library
ex5.cpp
Go to the documentation of this file.
1 // MFEM Example 5
2 //
3 // Compile with: make ex5
4 //
5 // Sample runs: ex5 -m ../data/square-disc.mesh
6 // ex5 -m ../data/star.mesh
7 // ex5 -m ../data/beam-tet.mesh
8 // ex5 -m ../data/beam-hex.mesh
9 // ex5 -m ../data/escher.mesh
10 // ex5 -m ../data/fichera.mesh
11 //
12 // Description: This example code solves a simple 2D/3D mixed Darcy problem
13 // corresponding to the saddle point system
14 // k*u + grad p = f
15 // - div u = g
16 // with natural boundary condition -p = <given pressure>.
17 // Here, we use a given exact solution (u,p) and compute the
18 // corresponding r.h.s. (f,g). We discretize with Raviart-Thomas
19 // finite elements (velocity u) and piecewise discontinuous
20 // polynomials (pressure p).
21 //
22 // The example demonstrates the use of the BlockMatrix class, as
23 // well as the collective saving of several grid functions in
24 // VisIt (visit.llnl.gov) and ParaView (paraview.org) formats.
25 //
26 // We recommend viewing examples 1-4 before viewing this example.
27
28 #include "mfem.hpp"
29 #include <fstream>
30 #include <iostream>
31 #include <algorithm>
32
33 using namespace std;
34 using namespace mfem;
35
36 // Define the analytical solution and forcing terms / boundary conditions
37 void uFun_ex(const Vector & x, Vector & u);
38 double pFun_ex(const Vector & x);
39 void fFun(const Vector & x, Vector & f);
40 double gFun(const Vector & x);
41 double f_natural(const Vector & x);
42
43 int main(int argc, char *argv[])
44 {
45  StopWatch chrono;
46
47  // 1. Parse command-line options.
48  const char *mesh_file = "../data/star.mesh";
49  int order = 1;
50  bool visualization = 1;
51
52  OptionsParser args(argc, argv);
54  "Mesh file to use.");
56  "Finite element order (polynomial degree).");
58  "--no-visualization",
59  "Enable or disable GLVis visualization.");
60  args.Parse();
61  if (!args.Good())
62  {
63  args.PrintUsage(cout);
64  return 1;
65  }
66  args.PrintOptions(cout);
67
68  // 2. Read the mesh from the given mesh file. We can handle triangular,
69  // quadrilateral, tetrahedral, hexahedral, surface and volume meshes with
70  // the same code.
71  Mesh *mesh = new Mesh(mesh_file, 1, 1);
72  int dim = mesh->Dimension();
73
74  // 3. Refine the mesh to increase the resolution. In this example we do
75  // 'ref_levels' of uniform refinement. We choose 'ref_levels' to be the
76  // largest number that gives a final mesh with no more than 10,000
77  // elements.
78  {
79  int ref_levels =
80  (int)floor(log(10000./mesh->GetNE())/log(2.)/dim);
81  for (int l = 0; l < ref_levels; l++)
82  {
83  mesh->UniformRefinement();
84  }
85  }
86
87  // 4. Define a finite element space on the mesh. Here we use the
88  // Raviart-Thomas finite elements of the specified order.
89  FiniteElementCollection *hdiv_coll(new RT_FECollection(order, dim));
90  FiniteElementCollection *l2_coll(new L2_FECollection(order, dim));
91
92  FiniteElementSpace *R_space = new FiniteElementSpace(mesh, hdiv_coll);
93  FiniteElementSpace *W_space = new FiniteElementSpace(mesh, l2_coll);
94
95  // 5. Define the BlockStructure of the problem, i.e. define the array of
96  // offsets for each variable. The last component of the Array is the sum
97  // of the dimensions of each block.
98  Array<int> block_offsets(3); // number of variables + 1
99  block_offsets[0] = 0;
100  block_offsets[1] = R_space->GetVSize();
101  block_offsets[2] = W_space->GetVSize();
102  block_offsets.PartialSum();
103
104  std::cout << "***********************************************************\n";
105  std::cout << "dim(R) = " << block_offsets[1] - block_offsets[0] << "\n";
106  std::cout << "dim(W) = " << block_offsets[2] - block_offsets[1] << "\n";
107  std::cout << "dim(R+W) = " << block_offsets.Last() << "\n";
108  std::cout << "***********************************************************\n";
109
110  // 6. Define the coefficients, analytical solution, and rhs of the PDE.
111  ConstantCoefficient k(1.0);
112
113  VectorFunctionCoefficient fcoeff(dim, fFun);
114  FunctionCoefficient fnatcoeff(f_natural);
115  FunctionCoefficient gcoeff(gFun);
116
117  VectorFunctionCoefficient ucoeff(dim, uFun_ex);
119
120  // 7. Allocate memory (x, rhs) for the analytical solution and the right hand
121  // side. Define the GridFunction u,p for the finite element solution and
122  // linear forms fform and gform for the right hand side. The data
123  // allocated by x and rhs are passed as a reference to the grid functions
124  // (u,p) and the linear forms (fform, gform).
125  BlockVector x(block_offsets), rhs(block_offsets);
126
127  LinearForm *fform(new LinearForm);
128  fform->Update(R_space, rhs.GetBlock(0), 0);
131  fform->Assemble();
132
133  LinearForm *gform(new LinearForm);
134  gform->Update(W_space, rhs.GetBlock(1), 0);
136  gform->Assemble();
137
138  // 8. Assemble the finite element matrices for the Darcy operator
139  //
140  // D = [ M B^T ]
141  // [ B 0 ]
142  // where:
143  //
144  // M = \int_\Omega k u_h \cdot v_h d\Omega u_h, v_h \in R_h
145  // B = -\int_\Omega \div u_h q_h d\Omega u_h \in R_h, q_h \in W_h
146  BilinearForm *mVarf(new BilinearForm(R_space));
147  MixedBilinearForm *bVarf(new MixedBilinearForm(R_space, W_space));
148
150  mVarf->Assemble();
151  mVarf->Finalize();
152  SparseMatrix &M(mVarf->SpMat());
153
155  bVarf->Assemble();
156  bVarf->Finalize();
157  SparseMatrix & B(bVarf->SpMat());
158  B *= -1.;
159  SparseMatrix *BT = Transpose(B);
160
161  BlockMatrix darcyMatrix(block_offsets);
162  darcyMatrix.SetBlock(0,0, &M);
163  darcyMatrix.SetBlock(0,1, BT);
164  darcyMatrix.SetBlock(1,0, &B);
165
166  // 9. Construct the operators for preconditioner
167  //
168  // P = [ diag(M) 0 ]
169  // [ 0 B diag(M)^-1 B^T ]
170  //
171  // Here we use Symmetric Gauss-Seidel to approximate the inverse of the
172  // pressure Schur Complement
173  SparseMatrix *MinvBt = Transpose(B);
174  Vector Md(M.Height());
175  M.GetDiag(Md);
176  for (int i = 0; i < Md.Size(); i++)
177  {
178  MinvBt->ScaleRow(i, 1./Md(i));
179  }
180  SparseMatrix *S = Mult(B, *MinvBt);
181
182  Solver *invM, *invS;
183  invM = new DSmoother(M);
184 #ifndef MFEM_USE_SUITESPARSE
185  invS = new GSSmoother(*S);
186 #else
187  invS = new UMFPackSolver(*S);
188 #endif
189
190  invM->iterative_mode = false;
191  invS->iterative_mode = false;
192
193  BlockDiagonalPreconditioner darcyPrec(block_offsets);
194  darcyPrec.SetDiagonalBlock(0, invM);
195  darcyPrec.SetDiagonalBlock(1, invS);
196
197  // 10. Solve the linear system with MINRES.
198  // Check the norm of the unpreconditioned residual.
199  int maxIter(1000);
200  double rtol(1.e-6);
201  double atol(1.e-10);
202
203  chrono.Clear();
204  chrono.Start();
205  MINRESSolver solver;
206  solver.SetAbsTol(atol);
207  solver.SetRelTol(rtol);
208  solver.SetMaxIter(maxIter);
209  solver.SetOperator(darcyMatrix);
210  solver.SetPreconditioner(darcyPrec);
211  solver.SetPrintLevel(1);
212  x = 0.0;
213  solver.Mult(rhs, x);
214  chrono.Stop();
215
216  if (solver.GetConverged())
217  std::cout << "MINRES converged in " << solver.GetNumIterations()
218  << " iterations with a residual norm of " << solver.GetFinalNorm() << ".\n";
219  else
220  std::cout << "MINRES did not converge in " << solver.GetNumIterations()
221  << " iterations. Residual norm is " << solver.GetFinalNorm() << ".\n";
222  std::cout << "MINRES solver took " << chrono.RealTime() << "s. \n";
223
224  // 11. Create the grid functions u and p. Compute the L2 error norms.
225  GridFunction u, p;
226  u.MakeRef(R_space, x.GetBlock(0), 0);
227  p.MakeRef(W_space, x.GetBlock(1), 0);
228
229  int order_quad = max(2, 2*order+1);
230  const IntegrationRule *irs[Geometry::NumGeom];
231  for (int i=0; i < Geometry::NumGeom; ++i)
232  {
234  }
235
236  double err_u = u.ComputeL2Error(ucoeff, irs);
237  double norm_u = ComputeLpNorm(2., ucoeff, *mesh, irs);
238  double err_p = p.ComputeL2Error(pcoeff, irs);
239  double norm_p = ComputeLpNorm(2., pcoeff, *mesh, irs);
240
241  std::cout << "|| u_h - u_ex || / || u_ex || = " << err_u / norm_u << "\n";
242  std::cout << "|| p_h - p_ex || / || p_ex || = " << err_p / norm_p << "\n";
243
244  // 12. Save the mesh and the solution. This output can be viewed later using
245  // GLVis: "glvis -m ex5.mesh -g sol_u.gf" or "glvis -m ex5.mesh -g
246  // sol_p.gf".
247  {
248  ofstream mesh_ofs("ex5.mesh");
249  mesh_ofs.precision(8);
250  mesh->Print(mesh_ofs);
251
252  ofstream u_ofs("sol_u.gf");
253  u_ofs.precision(8);
254  u.Save(u_ofs);
255
256  ofstream p_ofs("sol_p.gf");
257  p_ofs.precision(8);
258  p.Save(p_ofs);
259  }
260
261  // 13. Save data in the VisIt format
262  VisItDataCollection visit_dc("Example5", mesh);
263  visit_dc.RegisterField("velocity", &u);
264  visit_dc.RegisterField("pressure", &p);
265  visit_dc.Save();
266
267  // 14. Save data in the ParaView format
268  ParaViewDataCollection paraview_dc("Example5", mesh);
269  paraview_dc.SetPrefixPath("ParaView");
270  paraview_dc.SetLevelsOfDetail(order);
271  paraview_dc.SetCycle(0);
272  paraview_dc.SetDataFormat(VTKFormat::BINARY);
273  paraview_dc.SetHighOrderOutput(true);
274  paraview_dc.SetTime(0.0); // set the time
275  paraview_dc.RegisterField("velocity",&u);
276  paraview_dc.RegisterField("pressure",&p);
277  paraview_dc.Save();
278
279  // 15. Send the solution by socket to a GLVis server.
280  if (visualization)
281  {
282  char vishost[] = "localhost";
283  int visport = 19916;
284  socketstream u_sock(vishost, visport);
285  u_sock.precision(8);
286  u_sock << "solution\n" << *mesh << u << "window_title 'Velocity'" << endl;
287  socketstream p_sock(vishost, visport);
288  p_sock.precision(8);
289  p_sock << "solution\n" << *mesh << p << "window_title 'Pressure'" << endl;
290  }
291
292  // 16. Free the used memory.
293  delete fform;
294  delete gform;
295  delete invM;
296  delete invS;
297  delete S;
298  delete MinvBt;
299  delete BT;
300  delete mVarf;
301  delete bVarf;
302  delete W_space;
303  delete R_space;
304  delete l2_coll;
305  delete hdiv_coll;
306  delete mesh;
307
308  return 0;
309 }
310
311
312 void uFun_ex(const Vector & x, Vector & u)
313 {
314  double xi(x(0));
315  double yi(x(1));
316  double zi(0.0);
317  if (x.Size() == 3)
318  {
319  zi = x(2);
320  }
321
322  u(0) = - exp(xi)*sin(yi)*cos(zi);
323  u(1) = - exp(xi)*cos(yi)*cos(zi);
324
325  if (x.Size() == 3)
326  {
327  u(2) = exp(xi)*sin(yi)*sin(zi);
328  }
329 }
330
331 // Change if needed
332 double pFun_ex(const Vector & x)
333 {
334  double xi(x(0));
335  double yi(x(1));
336  double zi(0.0);
337
338  if (x.Size() == 3)
339  {
340  zi = x(2);
341  }
342
343  return exp(xi)*sin(yi)*cos(zi);
344 }
345
346 void fFun(const Vector & x, Vector & f)
347 {
348  f = 0.0;
349 }
350
351 double gFun(const Vector & x)
352 {
353  if (x.Size() == 3)
354  {
355  return -pFun_ex(x);
356  }
357  else
358  {
359  return 0;
360  }
361 }
362
363 double f_natural(const Vector & x)
364 {
365  return (-pFun_ex(x));
366 }
Class for domain integration L(v) := (f, v)
Definition: lininteg.hpp:93
int GetVSize() const
Return the number of vector dofs, i.e. GetNDofs() x GetVDim().
Definition: fespace.hpp:381
virtual void Print(std::ostream &out=mfem::out) const
Definition: mesh.hpp:1188
Class for an integration rule - an Array of IntegrationPoint.
Definition: intrules.hpp:90
Class for grid function - Vector with associated FE space.
Definition: gridfunc.hpp:27
int GetNumIterations() const
Definition: solvers.hpp:68
void SetCycle(int c)
Set time cycle (for time-dependent simulations)
Data type for scaled Jacobi-type smoother of sparse matrix.
const IntegrationRule & Get(int GeomType, int Order)
Returns an integration rule for given GeomType and Order.
Definition: intrules.cpp:890
void fFun(const Vector &x, Vector &f)
Definition: ex5.cpp:346
A class to handle Vectors in a block fashion.
Definition: blockvector.hpp:30
void Assemble(int skip_zeros=1)
Assembles the form i.e. sums over all domain/bdr integrators.
void SetDataFormat(VTKFormat fmt)
Subclass constant coefficient.
Definition: coefficient.hpp:67
virtual double ComputeL2Error(Coefficient &exsol, const IntegrationRule *irs[]=NULL) const
Definition: gridfunc.hpp:318
Helper class for ParaView visualization data.
void Mult(const Table &A, const Table &B, Table &C)
C = A * B (as boolean matrices)
Definition: table.cpp:476
void Assemble()
Assembles the linear form i.e. sums over all domain/bdr integrators.
Definition: linearform.cpp:79
virtual void RegisterField(const std::string &field_name, mfem::GridFunction *gf) override
Add a grid function to the collection.
int Size() const
Returns the size of the vector.
Definition: vector.hpp:157
int GetNE() const
Returns number of elements.
Definition: mesh.hpp:693
virtual void Save()
Save the collection and a VisIt root file.
double RealTime()
Definition: tic_toc.cpp:426
bool iterative_mode
If true, use the second argument of Mult() as an initial guess.
Definition: operator.hpp:504
virtual void Finalize(int skip_zeros=1)
Finalizes the matrix initialization.
MINRES method.
Definition: solvers.hpp:262
int main(int argc, char *argv[])
Definition: ex1.cpp:62
void ScaleRow(const int row, const double scale)
Definition: sparsemat.cpp:2536
double GetFinalNorm() const
Definition: solvers.hpp:70
Data type for Gauss-Seidel smoother of sparse matrix.
Adds a domain integrator. Assumes ownership of bfi.
Direct sparse solver using UMFPACK.
Definition: solvers.hpp:580
virtual void Save(std::ostream &out) const
Save the GridFunction to an output stream.
Definition: gridfunc.cpp:2731
void SetBlock(int i, int j, SparseMatrix *mat)
Set A(i,j) = mat.
Definition: blockmatrix.cpp:62
virtual void Mult(const Vector &b, Vector &x) const
Operator application: y=A(x).
Definition: solvers.cpp:1144
double ComputeLpNorm(double p, Coefficient &coeff, Mesh &mesh, const IntegrationRule *irs[])
void SetPrintLevel(int print_lvl)
Definition: solvers.cpp:70
virtual void SetPreconditioner(Solver &pr)
This should be called before SetOperator.
Definition: solvers.hpp:275
A class to handle Block diagonal preconditioners in a matrix-free implementation. ...
Data type sparse matrix.
Definition: sparsemat.hpp:40
double f_natural(const Vector &x)
Definition: ex5.cpp:363
void UniformRefinement(int i, const DSTable &, int *, int *, int *)
Definition: mesh.cpp:7982
Timing object.
Definition: tic_toc.hpp:34
Data collection with VisIt I/O routines.
void SetMaxIter(int max_it)
Definition: solvers.hpp:65
void Assemble(int skip_zeros=1)
void Transpose(const Table &A, Table &At, int _ncols_A)
Transpose a Table.
Definition: table.cpp:414
double pFun_ex(const Vector &x)
Definition: ex5.cpp:332
virtual void MakeRef(FiniteElementSpace *f, double *v)
Make the GridFunction reference external data on a new FiniteElementSpace.
Definition: gridfunc.cpp:188
void SetHighOrderOutput(bool high_order_output_)
virtual void SetOperator(const Operator &op)
Also calls SetOperator for the preconditioner if there is one.
Definition: solvers.cpp:1130
int GetConverged() const
Definition: solvers.hpp:69
Adds new Boundary Integrator. Assumes ownership of lfi.
Definition: linearform.cpp:53
int Dimension() const
Definition: mesh.hpp:744
void PrintUsage(std::ostream &out) const
Definition: optparser.cpp:434
void SetTime(double t)
Set physical time (for time-dependent simulations)
Arbitrary order H(div)-conforming Raviart-Thomas finite elements.
Definition: fe_coll.hpp:191
Adds new Domain Integrator. Assumes ownership of lfi.
Definition: linearform.cpp:39
void SetAbsTol(double atol)
Definition: solvers.hpp:64
void SetRelTol(double rtol)
Definition: solvers.hpp:63
Class FiniteElementSpace - responsible for providing FEM view of the mesh, mainly managing the set of...
Definition: fespace.hpp:87
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:76
void PartialSum()
Partial Sum.
Definition: array.cpp:103
void Update()
Update the object according to the associated FE space fes.
Definition: linearform.hpp:166
const SparseMatrix & SpMat() const
virtual void RegisterField(const std::string &field_name, GridFunction *gf)
Add a grid function to the collection and update the root file.
void uFun_ex(const Vector &x, Vector &u)
Definition: ex5.cpp:312
double gFun(const Vector &x)
Definition: ex5.cpp:351
virtual void Finalize(int skip_zeros=1)
Finalizes the matrix initialization.
int dim
Definition: ex24.cpp:43
Adds new Domain Integrator. Assumes ownership of bfi.
void PrintOptions(std::ostream &out) const
Definition: optparser.cpp:304
T & Last()
Return the last element in the array.
Definition: array.hpp:740
void SetLevelsOfDetail(int levels_of_detail_)
for VectorFiniteElements (Nedelec, Raviart-Thomas)
Definition: lininteg.hpp:231
class for C-function coefficient
Vector data type.
Definition: vector.hpp:48
Class for linear form - Vector with associated FE space and LFIntegrators.
Definition: linearform.hpp:23
virtual void Save() override
const SparseMatrix & SpMat() const
Returns a reference to the sparse matrix.
Base class for solvers.
Definition: operator.hpp:500