MFEM v4.10.0
Finite element discretization library
Loading...
Searching...
No Matches
ex4p.cpp
Go to the documentation of this file.
1// MFEM Example 4 - Parallel Version
2//
3// Compile with: make ex4p
4//
5// Sample runs: mpirun -np 4 ex4p -m ../data/square-disc.mesh
6// mpirun -np 4 ex4p -m ../data/star.mesh
7// mpirun -np 4 ex4p -m ../data/beam-tet.mesh
8// mpirun -np 4 ex4p -m ../data/beam-hex.mesh
9// mpirun -np 4 ex4p -m ../data/beam-hex.mesh -o 2 -pa
10// mpirun -np 4 ex4p -m ../data/escher.mesh -o 2 -sc
11// mpirun -np 4 ex4p -m ../data/fichera.mesh -o 2 -hb
12// mpirun -np 4 ex4p -m ../data/fichera.mesh -o 2 -hb -ea
13// mpirun -np 4 ex4p -m ../data/fichera-q2.vtk
14// mpirun -np 4 ex4p -m ../data/fichera-q3.mesh -o 2 -sc
15// mpirun -np 4 ex4p -m ../data/square-disc-nurbs.mesh -o 3
16// mpirun -np 4 ex4p -m ../data/beam-hex-nurbs.mesh -o 3
17// mpirun -np 4 ex4p -m ../data/periodic-square.mesh -no-bc
18// mpirun -np 4 ex4p -m ../data/periodic-cube.mesh -no-bc
19// mpirun -np 4 ex4p -m ../data/amr-quad.mesh
20// mpirun -np 3 ex4p -m ../data/amr-quad.mesh -o 2 -hb
21// mpirun -np 3 ex4p -m ../data/amr-quad.mesh -o 2 -hb -ea
22// mpirun -np 4 ex4p -m ../data/amr-hex.mesh -o 2 -sc
23// mpirun -np 4 ex4p -m ../data/amr-hex.mesh -o 2 -hb
24// mpirun -np 4 ex4p -m ../data/amr-hex.mesh -o 2 -hb -ea
25// mpirun -np 4 ex4p -m ../data/ref-prism.mesh -o 1
26// mpirun -np 4 ex4p -m ../data/octahedron.mesh -o 1
27// mpirun -np 4 ex4p -m ../data/star-surf.mesh -o 3 -hb
28//
29// Device sample runs:
30// mpirun -np 4 ex4p -m ../data/star.mesh -pa -d cuda
31// mpirun -np 4 ex4p -m ../data/star.mesh -ea -hb -d cuda
32// mpirun -np 4 ex4p -m ../data/amr-hex.mesh -ea -hb -d cuda
33// mpirun -np 4 ex4p -m ../data/star.mesh -pa -d raja-cuda
34// mpirun -np 4 ex4p -m ../data/star.mesh -pa -d raja-omp
35// mpirun -np 4 ex4p -m ../data/beam-hex.mesh -pa -d cuda
36//
37// Description: This example code solves a simple 2D/3D H(div) diffusion
38// problem corresponding to the second order definite equation
39// -grad(alpha div F) + beta F = f with boundary condition F dot n
40// = <given normal field>. Here, we use a given exact solution F
41// and compute the corresponding r.h.s. f. We discretize with
42// Raviart-Thomas finite elements.
43//
44// The example demonstrates the use of H(div) finite element
45// spaces with the grad-div and H(div) vector finite element mass
46// bilinear form, as well as the computation of discretization
47// error when the exact solution is known. Bilinear form
48// hybridization and static condensation are also illustrated.
49//
50// We recommend viewing examples 1-3 before viewing this example.
51
52#include "mfem.hpp"
53#include <fstream>
54#include <iostream>
55
56using namespace std;
57using namespace mfem;
58
59// Exact solution, F, and r.h.s., f. See below for implementation.
60void F_exact(const Vector &, Vector &);
61void f_exact(const Vector &, Vector &);
63
64int 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();
71
72 // 2. Parse command-line options.
73 const char *mesh_file = "../data/star.mesh";
74 int order = 1;
75 bool set_bc = true;
76 bool static_cond = false;
77 bool hybridization = false;
78 bool pa = false;
79 bool ea = false;
80 const char *device_config = "cpu";
81 bool visualization = 1;
82
83 OptionsParser args(argc, argv);
84 args.AddOption(&mesh_file, "-m", "--mesh",
85 "Mesh file to use.");
86 args.AddOption(&order, "-o", "--order",
87 "Finite element order (polynomial degree).");
88 args.AddOption(&set_bc, "-bc", "--impose-bc", "-no-bc", "--dont-impose-bc",
89 "Impose or not essential boundary conditions.");
90 args.AddOption(&freq, "-f", "--frequency", "Set the frequency for the exact"
91 " solution.");
92 args.AddOption(&static_cond, "-sc", "--static-condensation", "-no-sc",
93 "--no-static-condensation", "Enable static condensation.");
94 args.AddOption(&hybridization, "-hb", "--hybridization", "-no-hb",
95 "--no-hybridization", "Enable hybridization.");
96 args.AddOption(&pa, "-pa", "--partial-assembly", "-no-pa",
97 "--no-partial-assembly", "Enable Partial Assembly.");
98 args.AddOption(&ea, "-ea", "--element-assembly", "-no-ea",
99 "--no-element-assembly", "Enable Element Assembly.");
100 args.AddOption(&device_config, "-d", "--device",
101 "Device configuration string, see Device::Configure().");
102 args.AddOption(&visualization, "-vis", "--visualization", "-no-vis",
103 "--no-visualization",
104 "Enable or disable GLVis visualization.");
105 args.ParseCheck();
106 kappa = freq * M_PI;
107
108 // 3. Enable hardware devices such as GPUs, and programming models such as
109 // CUDA, OCCA, RAJA and OpenMP based on command line options.
110 Device device(device_config);
111 if (myid == 0) { device.Print(); }
112
113 // 4. Read the (serial) mesh from the given mesh file on all processors. We
114 // can handle triangular, quadrilateral, tetrahedral, hexahedral, surface
115 // and volume, as well as periodic meshes with the same code.
116 Mesh *mesh = new Mesh(mesh_file, 1, 1);
117 int dim = mesh->Dimension();
118 int sdim = mesh->SpaceDimension();
119
120 // 5. Refine the serial mesh on all processors to increase the resolution. In
121 // this example we do 'ref_levels' of uniform refinement. We choose
122 // 'ref_levels' to be the largest number that gives a final mesh with no
123 // more than 1,000 elements.
124 {
125 int ref_levels =
126 (int)floor(log(1000./mesh->GetNE())/log(2.)/dim);
127 for (int l = 0; l < ref_levels; l++)
128 {
129 mesh->UniformRefinement();
130 }
131 }
132
133 // 6. Define a parallel mesh by a partitioning of the serial mesh. Refine
134 // this mesh further in parallel to increase the resolution. Once the
135 // parallel mesh is defined, the serial mesh can be deleted.
136 ParMesh *pmesh = new ParMesh(MPI_COMM_WORLD, *mesh);
137 delete mesh;
138 {
139 int par_ref_levels = 2;
140 for (int l = 0; l < par_ref_levels; l++)
141 {
142 pmesh->UniformRefinement();
143 }
144 }
145
146 // 7. Define a parallel finite element space on the parallel mesh. Here we
147 // use the Raviart-Thomas finite elements of the specified order.
148 FiniteElementCollection *fec = new RT_FECollection(order-1, dim);
149 ParFiniteElementSpace *fespace = new ParFiniteElementSpace(pmesh, fec);
150 HYPRE_BigInt size = fespace->GlobalTrueVSize();
151 if (myid == 0)
152 {
153 cout << "Number of finite element unknowns: " << size << endl;
154 }
155
156 // 8. Determine the list of true (i.e. parallel conforming) essential
157 // boundary dofs. In this example, the boundary conditions are defined
158 // by marking all the boundary attributes from the mesh as essential
159 // (Dirichlet) and converting them to a list of true dofs.
161 if (pmesh->bdr_attributes.Size())
162 {
163 Array<int> ess_bdr(pmesh->bdr_attributes.Max());
164 ess_bdr = set_bc ? 1 : 0;
165 fespace->GetEssentialTrueDofs(ess_bdr, ess_tdof_list);
166 }
167
168 // 9. Set up the parallel linear form b(.) which corresponds to the
169 // right-hand side of the FEM linear system, which in this case is
170 // (f,phi_i) where f is given by the function f_exact and phi_i are the
171 // basis functions in the finite element fespace.
173 ParLinearForm *b = new ParLinearForm(fespace);
174 b->AddDomainIntegrator(new VectorFEDomainLFIntegrator(f));
175 b->Assemble();
176
177 // 10. Define the solution vector x as a parallel finite element grid function
178 // corresponding to fespace. Initialize x by projecting the exact
179 // solution. Note that only values from the boundary faces will be used
180 // when eliminating the non-homogeneous boundary condition to modify the
181 // r.h.s. vector b.
182 ParGridFunction x(fespace);
185
186 // 11. Set up the parallel bilinear form corresponding to the H(div)
187 // diffusion operator grad alpha div + beta I, by adding the div-div and
188 // the mass domain integrators.
190 Coefficient *beta = new ConstantCoefficient(1.0);
191 ParBilinearForm *a = new ParBilinearForm(fespace);
192 if (pa) { a->SetAssemblyLevel(AssemblyLevel::PARTIAL); }
193 if (ea) { a->SetAssemblyLevel(AssemblyLevel::ELEMENT); }
194 a->AddDomainIntegrator(new DivDivIntegrator(*alpha));
195 a->AddDomainIntegrator(new VectorFEMassIntegrator(*beta));
196
197 // 12. Assemble the parallel bilinear form and the corresponding linear
198 // system, applying any necessary transformations such as: parallel
199 // assembly, eliminating boundary conditions, applying conforming
200 // constraints for non-conforming AMR, static condensation,
201 // hybridization, etc.
202 FiniteElementCollection *hfec = NULL;
203 ParFiniteElementSpace *hfes = NULL;
204 if (static_cond)
205 {
206 a->EnableStaticCondensation();
207 }
208 else if (hybridization)
209 {
210 hfec = new DG_Interface_FECollection(order-1, dim);
211 hfes = new ParFiniteElementSpace(pmesh, hfec);
212 a->EnableHybridization(hfes, new NormalTraceJumpIntegrator(),
214 }
215 a->Assemble();
216
217 OperatorPtr A;
218 Vector B, X;
219 a->FormLinearSystem(ess_tdof_list, x, *b, A, X, B);
220
221 if (myid == 0 && !pa)
222 {
223 cout << "Size of linear system: "
224 << A.As<HypreParMatrix>()->GetGlobalNumRows() << endl;
225 }
226
227 // 13. Define and apply a parallel PCG solver for A X = B with the 2D AMS or
228 // the 3D ADS preconditioners from hypre. If using hybridization, the
229 // system is preconditioned with hypre's BoomerAMG. In the partial
230 // assembly case, use Jacobi preconditioning.
231 Solver *prec = NULL;
232 CGSolver *pcg = new CGSolver(MPI_COMM_WORLD);
233 pcg->SetOperator(*A);
234 pcg->SetRelTol(1e-12);
235 pcg->SetMaxIter(2000);
236 pcg->SetPrintLevel(1);
237 if (hybridization) { prec = new HypreBoomerAMG(*A.As<HypreParMatrix>()); }
238 else if (pa || ea) { prec = new OperatorJacobiSmoother(*a, ess_tdof_list); }
239 else
240 {
241 ParFiniteElementSpace *prec_fespace =
242 (a->StaticCondensationIsEnabled() ? a->SCParFESpace() : fespace);
243 if (dim == 2) { prec = new HypreAMS(*A.As<HypreParMatrix>(), prec_fespace); }
244 else { prec = new HypreADS(*A.As<HypreParMatrix>(), prec_fespace); }
245 }
246 pcg->SetPreconditioner(*prec);
247 pcg->Mult(B, X);
248
249 // 14. Recover the parallel grid function corresponding to X. This is the
250 // local finite element solution on each processor.
251 a->RecoverFEMSolution(X, *b, x);
252
253 // 15. Compute and print the L^2 norm of the error.
254 {
255 real_t error = x.ComputeL2Error(F);
256 if (myid == 0)
257 {
258 cout << "\n|| F_h - F ||_{L^2} = " << error << '\n' << endl;
259 }
260 }
261
262 // 16. Save the refined mesh and the solution in parallel. This output can
263 // be viewed later using GLVis: "glvis -np <np> -m mesh -g sol".
264 {
265 ostringstream mesh_name, sol_name;
266 mesh_name << "mesh." << setfill('0') << setw(6) << myid;
267 sol_name << "sol." << setfill('0') << setw(6) << myid;
268
269 ofstream mesh_ofs(mesh_name.str().c_str());
270 mesh_ofs.precision(8);
271 pmesh->Print(mesh_ofs);
272
273 ofstream sol_ofs(sol_name.str().c_str());
274 sol_ofs.precision(8);
275 x.Save(sol_ofs);
276 }
277
278 // 17. Send the solution by socket to a GLVis server.
279 if (visualization)
280 {
281 char vishost[] = "localhost";
282 int visport = 19916;
283 socketstream sol_sock(vishost, visport);
284 sol_sock << "parallel " << num_procs << " " << myid << "\n";
285 sol_sock.precision(8);
286 sol_sock << "solution\n" << *pmesh << x << flush;
287 }
288
289 // 18. Free the used memory.
290 delete pcg;
291 delete prec;
292 delete hfes;
293 delete hfec;
294 delete a;
295 delete alpha;
296 delete beta;
297 delete b;
298 delete fespace;
299 delete fec;
300 delete pmesh;
301
302 return 0;
303}
304
305
306// The exact solution (for non-surface meshes)
307void F_exact(const Vector &p, Vector &F)
308{
309 int dim = p.Size();
310
311 real_t x = p(0);
312 real_t y = p(1);
313 // real_t z = (dim == 3) ? p(2) : 0.0; // Uncomment if F is changed to depend on z
314
315 F(0) = cos(kappa*x)*sin(kappa*y);
316 F(1) = cos(kappa*y)*sin(kappa*x);
317 if (dim == 3)
318 {
319 F(2) = 0.0;
320 }
321}
322
323// The right hand side
324void f_exact(const Vector &p, Vector &f)
325{
326 int dim = p.Size();
327
328 real_t x = p(0);
329 real_t y = p(1);
330 // real_t z = (dim == 3) ? p(2) : 0.0; // Uncomment if f is changed to depend on z
331
332 real_t temp = 1 + 2*kappa*kappa;
333
334 f(0) = temp*cos(kappa*x)*sin(kappa*y);
335 f(1) = temp*cos(kappa*y)*sin(kappa*x);
336 if (dim == 3)
337 {
338 f(2) = 0;
339 }
340}
T Max() const
Find the maximal element in the array, using the comparison operator < for class T.
Definition array.cpp:69
int Size() const
Return the logical size of the array.
Definition array.hpp:192
Conjugate gradient method.
Definition solvers.hpp:627
void Mult(const Vector &b, Vector &x) const override
Iterative solution of the linear system using the Conjugate Gradient method.
Definition solvers.cpp:869
void SetOperator(const Operator &op) override
Set/update the solver for the given operator.
Definition solvers.hpp:640
Base class Coefficients that optionally depend on space and time. These are used by the BilinearFormI...
A coefficient that is constant across space and time.
The MFEM Device class abstracts hardware devices such as GPUs, as well as programming models such as ...
Definition device.hpp:129
void Print(std::ostream &os=mfem::out)
Print the configuration of the MFEM virtual device object.
Definition device.cpp:319
for Raviart-Thomas elements
Collection of finite elements from the same family in multiple dimensions. This class is used to matc...
Definition fe_coll.hpp:27
The Auxiliary-space Divergence Solver in hypre.
Definition hypre.hpp:2066
The Auxiliary-space Maxwell Solver in hypre.
Definition hypre.hpp:1989
The BoomerAMG solver in hypre.
Definition hypre.hpp:1829
Wrapper for hypre's ParCSR matrix class.
Definition hypre.hpp:419
static void Init()
Initialize hypre by calling HYPRE_Init() and set default options. After calling Hypre::Init(),...
Definition hypre.cpp:33
void SetRelTol(real_t rtol)
Definition solvers.hpp:238
virtual void SetPreconditioner(Solver &pr)
This should be called before SetOperator.
Definition solvers.cpp:178
virtual void SetPrintLevel(int print_lvl)
Legacy method to set the level of verbosity of the solver output.
Definition solvers.cpp:76
void SetMaxIter(int max_it)
Definition solvers.hpp:240
Mesh data type.
Definition mesh.hpp:67
Array< int > bdr_attributes
A list of all unique boundary attributes used by the Mesh.
Definition mesh.hpp:309
int GetNE() const
Returns number of elements.
Definition mesh.hpp:1390
int Dimension() const
Dimension of the reference space used within the elements.
Definition mesh.hpp:1314
int SpaceDimension() const
Dimension of the physical space containing the mesh.
Definition mesh.hpp:1317
void UniformRefinement(int i, const DSTable &, int *, int *, int *)
Definition mesh.cpp:12125
static int WorldRank()
Return the MPI rank in MPI_COMM_WORLD.
static int WorldSize()
Return the size of MPI_COMM_WORLD.
static void Init(int &argc, char **&argv, int required=default_thread_required, int *provided=nullptr)
Singleton creation with Mpi::Init(argc, argv).
Pointer to an Operator of a specified type.
Definition handle.hpp:34
OpType * As() const
Return the Operator pointer statically cast to a specified OpType. Similar to the method Get().
Definition handle.hpp:104
Jacobi smoothing for a given bilinear form (no matrix necessary).
Definition solvers.hpp:422
void ParseCheck(std::ostream &out=mfem::out)
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 'var' to receive the value. Enable/disable tags are used to set the bool...
Definition optparser.hpp:82
Class for parallel bilinear form.
Abstract parallel finite element space.
Definition pfespace.hpp:31
void GetEssentialTrueDofs(const Array< int > &bdr_attr_is_ess, Array< int > &ess_tdof_list, int component=-1) const override
HYPRE_BigInt GlobalTrueVSize() const
Definition pfespace.hpp:361
Class for parallel grid function.
Definition pgridfunc.hpp:50
void Save(std::ostream &out) const override
real_t ComputeL2Error(Coefficient *exsol[], const IntegrationRule *irs[]=NULL, const Array< int > *elems=NULL) const override
Returns ||u_ex - u_h||_L2 in parallel for H1 or L2 elements.
void ProjectCoefficient(Coefficient &coeff, ProjectType type=ProjectType::DEFAULT) override
Project coeff Coefficient to this GridFunction. The projection computation depends on the choice of t...
Class for parallel linear form.
Class for parallel meshes.
Definition pmesh.hpp:35
void Print(std::ostream &out=mfem::out, const std::string &comments="") const override
Definition pmesh.cpp:4856
Arbitrary order H(div)-conforming Raviart-Thomas finite elements.
Definition fe_coll.hpp:430
Base class for solvers.
Definition operator.hpp:855
for VectorFiniteElements (Nedelec, Raviart-Thomas)
Definition lininteg.hpp:365
A general vector function coefficient.
Vector data type.
Definition vector.hpp:82
int Size() const
Returns the size of the vector.
Definition vector.hpp:234
const int * ess_tdof_list
const real_t alpha
Definition ex15.cpp:369
int dim
Definition ex24.cpp:53
real_t kappa
Definition ex4p.cpp:62
void f_exact(const Vector &, Vector &)
Definition ex4p.cpp:324
real_t freq
Definition ex4p.cpp:62
void F_exact(const Vector &, Vector &)
Definition ex4p.cpp:307
int main()
HYPRE_Int HYPRE_BigInt
real_t b
Definition lissajous.cpp:42
real_t a
Definition lissajous.cpp:41
float real_t
Definition config.hpp:46
std::function< real_t(const Vector &)> f(real_t mass_coeff)
Definition lor_mms.hpp:30
const char vishost[]
STL namespace.
real_t p(const Vector &x, real_t t)