MFEM  v4.3.0
Finite element discretization library
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Pages
ex26p.cpp
Go to the documentation of this file.
1 // MFEM Example 26 - Parallel Version
2 //
3 // Compile with: make ex26p
4 //
5 // Sample runs: mpirun -np 4 ex26p -m ../data/star.mesh
6 // mpirun -np 4 ex26p -m ../data/fichera.mesh
7 // mpirun -np 4 ex26p -m ../data/beam-hex.mesh
8 //
9 // Device sample runs:
10 // mpirun -np 4 ex26p -d cuda
11 // mpirun -np 4 ex26p -d occa-cuda
12 // mpirun -np 4 ex26p -d raja-omp
13 // mpirun -np 4 ex26p -d ceed-cpu
14 // mpirun -np 4 ex26p -d ceed-cuda
15 //
16 // Description: This example code demonstrates the use of MFEM to define a
17 // simple finite element discretization of the Laplace problem
18 // -Delta u = 1 with homogeneous Dirichlet boundary conditions
19 // as in Example 1.
20 //
21 // It highlights on the creation of a hierarchy of discretization
22 // spaces with partial assembly and the construction of an
23 // efficient multigrid preconditioner for the iterative solver.
24 //
25 // We recommend viewing Example 1 before viewing this example.
26 
27 #include "mfem.hpp"
28 #include <fstream>
29 #include <iostream>
30 
31 using namespace std;
32 using namespace mfem;
33 
34 // Class for constructing a multigrid preconditioner for the diffusion operator.
35 // This example multigrid preconditioner class demonstrates the creation of the
36 // parallel diffusion bilinear forms and operators using partial assembly for
37 // all spaces except the coarsest one in the ParFiniteElementSpaceHierarchy.
38 // The multigrid uses a PCG solver preconditioned with AMG on the coarsest level
39 // and second order Chebyshev accelerated smoothers on the other levels.
40 class DiffusionMultigrid : public GeometricMultigrid
41 {
42 private:
44  HypreBoomerAMG* amg;
45 
46 public:
47  // Constructs a diffusion multigrid for the ParFiniteElementSpaceHierarchy
48  // and the array of essential boundaries
49  DiffusionMultigrid(ParFiniteElementSpaceHierarchy& fespaces,
50  Array<int>& ess_bdr)
51  : GeometricMultigrid(fespaces), one(1.0)
52  {
53  ConstructCoarseOperatorAndSolver(fespaces.GetFESpaceAtLevel(0), ess_bdr);
54 
55  for (int level = 1; level < fespaces.GetNumLevels(); ++level)
56  {
57  ConstructOperatorAndSmoother(fespaces.GetFESpaceAtLevel(level), ess_bdr);
58  }
59  }
60 
61  virtual ~DiffusionMultigrid()
62  {
63  delete amg;
64  }
65 
66 private:
67  void ConstructBilinearForm(ParFiniteElementSpace& fespace, Array<int>& ess_bdr,
68  bool partial_assembly)
69  {
70  ParBilinearForm* form = new ParBilinearForm(&fespace);
71  if (partial_assembly)
72  {
73  form->SetAssemblyLevel(AssemblyLevel::PARTIAL);
74  }
76  form->Assemble();
77  bfs.Append(form);
78 
79  essentialTrueDofs.Append(new Array<int>());
80  fespace.GetEssentialTrueDofs(ess_bdr, *essentialTrueDofs.Last());
81  }
82 
83  void ConstructCoarseOperatorAndSolver(ParFiniteElementSpace& coarse_fespace,
84  Array<int>& ess_bdr)
85  {
86  ConstructBilinearForm(coarse_fespace, ess_bdr, false);
87 
88  HypreParMatrix* hypreCoarseMat = new HypreParMatrix();
89  bfs.Last()->FormSystemMatrix(*essentialTrueDofs.Last(), *hypreCoarseMat);
90 
91  amg = new HypreBoomerAMG(*hypreCoarseMat);
92  amg->SetPrintLevel(-1);
93 
94  CGSolver* pcg = new CGSolver(MPI_COMM_WORLD);
95  pcg->SetPrintLevel(-1);
96  pcg->SetMaxIter(10);
97  pcg->SetRelTol(sqrt(1e-4));
98  pcg->SetAbsTol(0.0);
99  pcg->SetOperator(*hypreCoarseMat);
100  pcg->SetPreconditioner(*amg);
101 
102  AddLevel(hypreCoarseMat, pcg, true, true);
103  }
104 
105  void ConstructOperatorAndSmoother(ParFiniteElementSpace& fespace,
106  Array<int>& ess_bdr)
107  {
108  ConstructBilinearForm(fespace, ess_bdr, true);
109 
110  OperatorPtr opr;
111  opr.SetType(Operator::ANY_TYPE);
112  bfs.Last()->FormSystemMatrix(*essentialTrueDofs.Last(), opr);
113  opr.SetOperatorOwner(false);
114 
115  Vector diag(fespace.GetTrueVSize());
116  bfs.Last()->AssembleDiagonal(diag);
117 
118  Solver* smoother = new OperatorChebyshevSmoother(*opr, diag,
119  *essentialTrueDofs.Last(), 2, fespace.GetParMesh()->GetComm());
120 
121  AddLevel(opr.Ptr(), smoother, true, true);
122  }
123 };
124 
125 
126 int main(int argc, char *argv[])
127 {
128  // 1. Initialize MPI.
129  int num_procs, myid;
130  MPI_Init(&argc, &argv);
131  MPI_Comm_size(MPI_COMM_WORLD, &num_procs);
132  MPI_Comm_rank(MPI_COMM_WORLD, &myid);
133 
134  // 2. Parse command-line options.
135  const char *mesh_file = "../data/star.mesh";
136  int geometric_refinements = 0;
137  int order_refinements = 2;
138  const char *device_config = "cpu";
139  bool visualization = true;
140 
141  OptionsParser args(argc, argv);
142  args.AddOption(&mesh_file, "-m", "--mesh",
143  "Mesh file to use.");
144  args.AddOption(&geometric_refinements, "-gr", "--geometric-refinements",
145  "Number of geometric refinements done prior to order refinements.");
146  args.AddOption(&order_refinements, "-or", "--order-refinements",
147  "Number of order refinements. Finest level in the hierarchy has order 2^{or}.");
148  args.AddOption(&device_config, "-d", "--device",
149  "Device configuration string, see Device::Configure().");
150  args.AddOption(&visualization, "-vis", "--visualization", "-no-vis",
151  "--no-visualization",
152  "Enable or disable GLVis visualization.");
153  args.Parse();
154  if (!args.Good())
155  {
156  if (myid == 0)
157  {
158  args.PrintUsage(cout);
159  }
160  MPI_Finalize();
161  return 1;
162  }
163  if (myid == 0)
164  {
165  args.PrintOptions(cout);
166  }
167 
168  // 3. Enable hardware devices such as GPUs, and programming models such as
169  // CUDA, OCCA, RAJA and OpenMP based on command line options.
170  Device device(device_config);
171  if (myid == 0) { device.Print(); }
172 
173  // 4. Read the (serial) mesh from the given mesh file on all processors. We
174  // can handle triangular, quadrilateral, tetrahedral, hexahedral, surface
175  // and volume meshes with the same code.
176  Mesh *mesh = new Mesh(mesh_file, 1, 1);
177  int dim = mesh->Dimension();
178 
179  // 5. Refine the serial mesh on all processors to increase the resolution. In
180  // this example we do 'ref_levels' of uniform refinement. We choose
181  // 'ref_levels' to be the largest number that gives a final mesh with no
182  // more than 1,000 elements.
183  {
184  int ref_levels =
185  (int)floor(log(1000./mesh->GetNE())/log(2.)/dim);
186  for (int l = 0; l < ref_levels; l++)
187  {
188  mesh->UniformRefinement();
189  }
190  }
191 
192  // 6. Define a parallel mesh by a partitioning of the serial mesh. Refine
193  // this mesh further in parallel to increase the resolution. Once the
194  // parallel mesh is defined, the serial mesh can be deleted.
195  ParMesh *pmesh = new ParMesh(MPI_COMM_WORLD, *mesh);
196  delete mesh;
197  {
198  int par_ref_levels = 2;
199  for (int l = 0; l < par_ref_levels; l++)
200  {
201  pmesh->UniformRefinement();
202  }
203  }
204 
205  // 7. Define a parallel finite element space hierarchy on the parallel mesh.
206  // Here we use continuous Lagrange finite elements. We start with order 1
207  // on the coarse level and geometrically refine the spaces by the specified
208  // amount. Afterwards, we increase the order of the finite elements by a
209  // factor of 2 for each additional level.
210  FiniteElementCollection *fec = new H1_FECollection(1, dim);
211  ParFiniteElementSpace *coarse_fespace = new ParFiniteElementSpace(pmesh, fec);
212 
214  collections.Append(fec);
216  pmesh, coarse_fespace, true, true);
217  for (int level = 0; level < geometric_refinements; ++level)
218  {
219  fespaces->AddUniformlyRefinedLevel();
220  }
221  for (int level = 0; level < order_refinements; ++level)
222  {
223  collections.Append(new H1_FECollection(std::pow(2, level+1), dim));
224  fespaces->AddOrderRefinedLevel(collections.Last());
225  }
226 
227  HYPRE_BigInt size = fespaces->GetFinestFESpace().GlobalTrueVSize();
228  if (myid == 0)
229  {
230  cout << "Number of finite element unknowns: " << size << endl;
231  }
232 
233  // 8. Set up the parallel linear form b(.) which corresponds to the
234  // right-hand side of the FEM linear system, which in this case is
235  // (1,phi_i) where phi_i are the basis functions in fespace.
236  ParLinearForm *b = new ParLinearForm(&fespaces->GetFinestFESpace());
237  ConstantCoefficient one(1.0);
239  b->Assemble();
240 
241  // 9. Define the solution vector x as a parallel finite element grid function
242  // corresponding to fespace. Initialize x with initial guess of zero,
243  // which satisfies the boundary conditions.
244  ParGridFunction x(&fespaces->GetFinestFESpace());
245  x = 0.0;
246 
247  // 10. Create the multigrid operator using the previously created parallel
248  // FiniteElementSpaceHierarchy and additional boundary information. This
249  // operator is then used to create the MultigridSolver as preconditioner
250  // in the iterative solver.
251  Array<int> ess_bdr(pmesh->bdr_attributes.Max());
252  if (pmesh->bdr_attributes.Size())
253  {
254  ess_bdr = 1;
255  }
256 
257  DiffusionMultigrid* M = new DiffusionMultigrid(*fespaces, ess_bdr);
258  M->SetCycleType(Multigrid::CycleType::VCYCLE, 1, 1);
259 
260  OperatorPtr A;
261  Vector X, B;
262  M->FormFineLinearSystem(x, *b, A, X, B);
263 
264  // 11. Solve the linear system A X = B.
265  CGSolver cg(MPI_COMM_WORLD);
266  cg.SetRelTol(1e-12);
267  cg.SetMaxIter(2000);
268  cg.SetPrintLevel(1);
269  cg.SetOperator(*A);
270  cg.SetPreconditioner(*M);
271  cg.Mult(B, X);
272 
273  // 12. Recover the parallel grid function corresponding to X. This is the
274  // local finite element solution on each processor.
275  M->RecoverFineFEMSolution(X, *b, x);
276 
277  // 13. Save the refined mesh and the solution in parallel. This output can be
278  // viewed later using GLVis: "glvis -np <np> -m mesh -g sol".
279  {
280  ostringstream mesh_name, sol_name;
281  mesh_name << "mesh." << setfill('0') << setw(6) << myid;
282  sol_name << "sol." << setfill('0') << setw(6) << myid;
283 
284  ofstream mesh_ofs(mesh_name.str().c_str());
285  mesh_ofs.precision(8);
286  fespaces->GetFinestFESpace().GetParMesh()->Print(mesh_ofs);
287 
288  ofstream sol_ofs(sol_name.str().c_str());
289  sol_ofs.precision(8);
290  x.Save(sol_ofs);
291  }
292 
293  // 14. Send the solution by socket to a GLVis server.
294  if (visualization)
295  {
296  char vishost[] = "localhost";
297  int visport = 19916;
298  socketstream sol_sock(vishost, visport);
299  sol_sock << "parallel " << num_procs << " " << myid << "\n";
300  sol_sock.precision(8);
301  sol_sock << "solution\n" << *fespaces->GetFinestFESpace().GetParMesh()
302  << x << flush;
303  }
304 
305  // 15. Free the used memory.
306  delete M;
307  delete b;
308  delete fespaces;
309  for (int level = 0; level < collections.Size(); ++level)
310  {
311  delete collections[level];
312  }
313 
314  MPI_Finalize();
315 
316  return 0;
317 }
int Size() const
Return the logical size of the array.
Definition: array.hpp:134
Class for domain integration L(v) := (f, v)
Definition: lininteg.hpp:97
virtual void GetEssentialTrueDofs(const Array< int > &bdr_attr_is_ess, Array< int > &ess_tdof_list, int component=-1)
Definition: pfespace.cpp:790
Conjugate gradient method.
Definition: solvers.hpp:316
Chebyshev accelerated smoothing with given vector, no matrix necessary.
Definition: solvers.hpp:202
ParMesh * GetParMesh() const
Definition: pfespace.hpp:267
A coefficient that is constant across space and time.
Definition: coefficient.hpp:78
virtual void Mult(const Vector &b, Vector &x) const
Operator application: y=A(x).
Definition: solvers.cpp:616
Geometric multigrid associated with a hierarchy of finite element spaces.
Definition: multigrid.hpp:119
Pointer to an Operator of a specified type.
Definition: handle.hpp:33
HYPRE_BigInt GlobalTrueVSize() const
Definition: pfespace.hpp:275
const ParFiniteElementSpace & GetFinestFESpace() const override
Returns the finite element space at the finest level.
int GetNE() const
Returns number of elements.
Definition: mesh.hpp:846
void Print(std::ostream &out=mfem::out)
Print the configuration of the MFEM virtual device object.
Definition: device.cpp:279
void SetAssemblyLevel(AssemblyLevel assembly_level)
Set the desired assembly level.
Abstract parallel finite element space.
Definition: pfespace.hpp:28
virtual int GetTrueVSize() const
Return the number of local vector true dofs.
Definition: pfespace.hpp:279
const ParFiniteElementSpace & GetFESpaceAtLevel(int level) const override
Returns the finite element space at the given level.
The BoomerAMG solver in hypre.
Definition: hypre.hpp:1387
Class for parallel linear form.
Definition: plinearform.hpp:26
void AddOrderRefinedLevel(FiniteElementCollection *fec, int dim=1, int ordering=Ordering::byVDIM) override
Adds one level to the hierarchy by using a different finite element order defined through FiniteEleme...
void SetPrintLevel(int print_lvl)
Definition: solvers.cpp:71
void AddUniformlyRefinedLevel(int dim=1, int ordering=Ordering::byVDIM) override
Adds one level to the hierarchy by uniformly refining the mesh on the previous level.
void Parse()
Parse the command-line options. Note that this function expects all the options provided through the ...
Definition: optparser.cpp:150
int Append(const T &el)
Append element &#39;el&#39; to array, resize if necessary.
Definition: array.hpp:746
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
void SetMaxIter(int max_it)
Definition: solvers.hpp:100
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.
virtual void Print(std::ostream &out=mfem::out) const
Definition: pmesh.cpp:4382
int GetNumLevels() const
Returns the number of levels in the hierarchy.
int Dimension() const
Definition: mesh.hpp:911
void PrintUsage(std::ostream &out) const
Print the usage message.
Definition: optparser.cpp:457
Operator * Ptr() const
Access the underlying Operator pointer.
Definition: handle.hpp:82
void AddDomainIntegrator(LinearFormIntegrator *lfi)
Adds new Domain Integrator. Assumes ownership of lfi.
Definition: linearform.cpp:39
void SetAbsTol(double atol)
Definition: solvers.hpp:99
Array< int > bdr_attributes
A list of all unique boundary attributes used by the Mesh.
Definition: mesh.hpp:204
void SetRelTol(double rtol)
Definition: solvers.hpp:98
MPI_Comm GetComm() const
Definition: pmesh.hpp:276
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
void SetOperatorOwner(bool own=true)
Set the ownership flag for the held Operator.
Definition: handle.hpp:115
int dim
Definition: ex24.cpp:53
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
Class for parallel bilinear form.
T & Last()
Return the last element in the array.
Definition: array.hpp:779
virtual void SetOperator(const Operator &op)
Also calls SetOperator for the preconditioner if there is one.
Definition: solvers.hpp:330
Vector data type.
Definition: vector.hpp:60
virtual void SetPreconditioner(Solver &pr)
This should be called before SetOperator.
Definition: solvers.cpp:92
Arbitrary order H1-conforming (continuous) finite elements.
Definition: fe_coll.hpp:216
Base class for solvers.
Definition: operator.hpp:648
Class for parallel grid function.
Definition: pgridfunc.hpp:32
The MFEM Device class abstracts hardware devices such as GPUs, as well as programming models such as ...
Definition: device.hpp:121
Wrapper for hypre&#39;s ParCSR matrix class.
Definition: hypre.hpp:277
Class for parallel meshes.
Definition: pmesh.hpp:32
int main()
void SetType(Operator::Type tid)
Invoke Clear() and set a new type id.
Definition: handle.hpp:127
bool Good() const
Return true if the command line options were parsed successfully.
Definition: optparser.hpp:150