MFEM v4.10.0
Finite element discretization library
Loading...
Searching...
No Matches
ex1.cpp
Go to the documentation of this file.
1// MFEM Example 1
2//
3// Compile with: make ex1
4//
5// Sample runs: ex1 -m ../data/square-disc.mesh
6// ex1 -m ../data/star.mesh
7// ex1 -m ../data/star-mixed.mesh
8// ex1 -m ../data/escher.mesh
9// ex1 -m ../data/fichera.mesh
10// ex1 -m ../data/fichera-mixed.mesh
11// ex1 -m ../data/toroid-wedge.mesh
12// ex1 -m ../data/octahedron.mesh -o 1
13// ex1 -m ../data/periodic-annulus-sector.msh
14// ex1 -m ../data/periodic-torus-sector.msh
15// ex1 -m ../data/square-disc-p2.vtk -o 2
16// ex1 -m ../data/square-disc-p3.mesh -o 3
17// ex1 -m ../data/square-disc-nurbs.mesh -o -1
18// ex1 -m ../data/star-mixed-p2.mesh -o 2
19// ex1 -m ../data/disc-nurbs.mesh -o -1
20// ex1 -m ../data/pipe-nurbs.mesh -o -1
21// ex1 -m ../data/fichera-mixed-p2.mesh -o 2
22// ex1 -m ../data/star-surf.mesh
23// ex1 -m ../data/square-disc-surf.mesh
24// ex1 -m ../data/inline-segment.mesh
25// ex1 -m ../data/amr-quad.mesh
26// ex1 -m ../data/amr-hex.mesh
27// ex1 -m ../data/fichera-amr.mesh
28// ex1 -m ../data/mobius-strip.mesh
29// ex1 -m ../data/mobius-strip.mesh -o -1 -sc
30// ex1 -m ../data/nc3-nurbs.mesh -o -1
31//
32// Device sample runs:
33// ex1 -pa -d cuda
34// ex1 -fa -d cuda
35// ex1 -pa -d raja-cuda
36// * ex1 -pa -d raja-hip
37// ex1 -pa -d occa-cuda
38// ex1 -pa -d raja-omp
39// ex1 -pa -d occa-omp
40// ex1 -pa -d ceed-cpu
41// ex1 -pa -d ceed-cpu -o 4 -a
42// ex1 -pa -d ceed-cpu -m ../data/square-mixed.mesh
43// ex1 -pa -d ceed-cpu -m ../data/fichera-mixed.mesh
44// * ex1 -pa -d ceed-cuda
45// * ex1 -pa -d ceed-hip
46// ex1 -pa -d ceed-cuda:/gpu/cuda/shared
47// ex1 -pa -d ceed-cuda:/gpu/cuda/shared -m ../data/square-mixed.mesh
48// ex1 -pa -d ceed-cuda:/gpu/cuda/shared -m ../data/fichera-mixed.mesh
49// ex1 -m ../data/beam-hex.mesh -pa -d cuda
50// ex1 -m ../data/beam-tet.mesh -pa -d ceed-cpu
51// ex1 -m ../data/beam-tet.mesh -pa -d ceed-cuda:/gpu/cuda/ref
52//
53// Device simplices sample runs:
54// ex1 -pa -d gpu -m ../data/inline-tet.mesh
55// ex1 -pa -d gpu -m ../data/inline-tri.mesh
56//
57// Description: This example code demonstrates the use of MFEM to define a
58// simple finite element discretization of the Poisson problem
59// -Delta u = 1 with homogeneous Dirichlet boundary conditions.
60// Specifically, we discretize using a FE space of the specified
61// order, or if order < 1 using an isoparametric/isogeometric
62// space (i.e. quadratic for quadratic curvilinear mesh, NURBS for
63// NURBS mesh, etc.)
64//
65// The example highlights the use of mesh refinement, finite
66// element grid functions, as well as linear and bilinear forms
67// corresponding to the left-hand side and right-hand side of the
68// discrete linear system. We also cover the explicit elimination
69// of essential boundary conditions, static condensation, and the
70// optional connection to the GLVis tool for visualization.
71
72#include "mfem.hpp"
73#include <fstream>
74#include <iostream>
75
76using namespace std;
77using namespace mfem;
78
79int main(int argc, char *argv[])
80{
81 // 1. Parse command-line options.
82 const char *mesh_file = "../data/star.mesh";
83 int order = 1;
84 bool static_cond = false;
85 bool pa = false;
86 bool fa = false;
87 const char *device_config = "cpu";
88 bool visualization = true;
89 bool algebraic_ceed = false;
90
91 OptionsParser args(argc, argv);
92 args.AddOption(&mesh_file, "-m", "--mesh",
93 "Mesh file to use.");
94 args.AddOption(&order, "-o", "--order",
95 "Finite element order (polynomial degree) or -1 for"
96 " isoparametric space.");
97 args.AddOption(&static_cond, "-sc", "--static-condensation", "-no-sc",
98 "--no-static-condensation", "Enable static condensation.");
99 args.AddOption(&pa, "-pa", "--partial-assembly", "-no-pa",
100 "--no-partial-assembly", "Enable Partial Assembly.");
101 args.AddOption(&fa, "-fa", "--full-assembly", "-no-fa",
102 "--no-full-assembly", "Enable Full Assembly.");
103 args.AddOption(&device_config, "-d", "--device",
104 "Device configuration string, see Device::Configure().");
105#ifdef MFEM_USE_CEED
106 args.AddOption(&algebraic_ceed, "-a", "--algebraic", "-no-a", "--no-algebraic",
107 "Use algebraic Ceed solver");
108#endif
109 args.AddOption(&visualization, "-vis", "--visualization", "-no-vis",
110 "--no-visualization",
111 "Enable or disable GLVis visualization.");
112 args.Parse();
113 if (!args.Good())
114 {
115 args.PrintUsage(cout);
116 return 1;
117 }
118 args.PrintOptions(cout);
119
120 // 2. Enable hardware devices such as GPUs, and programming models such as
121 // CUDA, OCCA, RAJA and OpenMP based on command line options.
122 Device device(device_config);
123 device.Print();
124
125 // 3. Read the mesh from the given mesh file. We can handle triangular,
126 // quadrilateral, tetrahedral, hexahedral, surface and volume meshes with
127 // the same code.
128 Mesh mesh(mesh_file, 1, 1);
129 int dim = mesh.Dimension();
130
131 // 4. Refine the mesh to increase the resolution. In this example we do
132 // 'ref_levels' of uniform refinement. We choose 'ref_levels' to be the
133 // largest number that gives a final mesh with no more than 50,000
134 // elements.
135 {
136 int ref_levels =
137 (int)floor(log(50000./mesh.GetNE())/log(2.)/dim);
138 for (int l = 0; l < ref_levels; l++)
139 {
140 mesh.UniformRefinement();
141 }
142 }
143
144 // 5. Define a finite element space on the mesh. Here we use continuous
145 // Lagrange finite elements of the specified order.
146 // - If order < 1, we instead use an isoparametric/isogeometric space.
147 // - If the mesh is simplicial and partial assembly is requested,
148 // we use the positive basis, which supports device execution.
150 auto basis_type = (pa && mesh.IsSimplexMesh()) ?
152 if (order > 0)
153 {
154 fec = new H1_FECollection(order, dim, basis_type);
155 }
156 else if (mesh.GetNodes())
157 {
158 fec = mesh.GetNodes()->OwnFEC();
159 cout << "Using isoparametric FEs: " << fec->Name() << endl;
160 }
161 else
162 {
163 fec = new H1_FECollection(order = 1, dim, basis_type);
164 }
165 FiniteElementSpace fespace(&mesh, fec);
166 cout << "Number of finite element unknowns: "
167 << fespace.GetTrueVSize() << endl;
168
169 // 6. Determine the list of true (i.e. conforming) essential boundary dofs.
170 // In this example, the boundary conditions are defined by marking all
171 // the external boundary attributes from the mesh as essential (Dirichlet)
172 // and converting them to a list of true dofs.
174 if (mesh.bdr_attributes.Size())
175 {
176 Array<int> ess_bdr(mesh.bdr_attributes.Max());
177 ess_bdr = 0;
178 // Apply boundary conditions on all external boundaries:
179 mesh.MarkExternalBoundaries(ess_bdr);
180 // Boundary conditions can also be applied based on named attributes:
181 // mesh.MarkNamedBoundaries(set_name, ess_bdr)
182
183 fespace.GetEssentialTrueDofs(ess_bdr, ess_tdof_list);
184 }
185
186 // 7. Set up the linear form b(.) which corresponds to the right-hand side of
187 // the FEM linear system, which in this case is (1,phi_i) where phi_i are
188 // the basis functions in the finite element fespace.
189 LinearForm b(&fespace);
190 ConstantCoefficient one(1.0);
191 b.AddDomainIntegrator(new DomainLFIntegrator(one));
192 b.Assemble();
193
194 // 8. Define the solution vector x as a finite element grid function
195 // corresponding to fespace. Initialize x with initial guess of zero,
196 // which satisfies the boundary conditions.
197 GridFunction x(&fespace);
198 x = 0.0;
199
200 // 9. Set up the bilinear form a(.,.) on the finite element space
201 // corresponding to the Laplacian operator -Delta, by adding the Diffusion
202 // domain integrator.
203 BilinearForm a(&fespace);
204 if (pa) { a.SetAssemblyLevel(AssemblyLevel::PARTIAL); }
205 if (fa)
206 {
207 a.SetAssemblyLevel(AssemblyLevel::FULL);
208 // Sort the matrix column indices when running on GPU or with OpenMP (i.e.
209 // when Device::IsEnabled() returns true). This makes the results
210 // bit-for-bit deterministic at the cost of somewhat longer run time.
211 a.EnableSparseMatrixSorting(Device::IsEnabled());
212 }
213 a.AddDomainIntegrator(new DiffusionIntegrator(one));
214
215 // 10. Assemble the bilinear form and the corresponding linear system,
216 // applying any necessary transformations such as: eliminating boundary
217 // conditions, applying conforming constraints for non-conforming AMR,
218 // static condensation, etc.
219 if (static_cond) { a.EnableStaticCondensation(); }
220 a.Assemble();
221
222 OperatorPtr A;
223 Vector B, X;
224 a.FormLinearSystem(ess_tdof_list, x, b, A, X, B);
225
226 cout << "Size of linear system: " << A->Height() << endl;
227
228 // 11. Solve the linear system A X = B.
229 if (!pa)
230 {
231#ifdef MFEM_USE_CUDSS
233 {
234 // Use cuDSS to solve the system.
235 CuDSSSolver cudss_solver;
236 cudss_solver.SetOperator(*A);
237 cudss_solver.Mult(B, X);
238 }
239 else
240#endif
241 {
242#ifndef MFEM_USE_SUITESPARSE
243 // Use a simple symmetric Gauss-Seidel preconditioner with PCG.
244 GSSmoother M((SparseMatrix&)(*A));
245 PCG(*A, M, B, X, 1, 200, 1e-12, 0.0);
246#else
247 // If MFEM was compiled with SuiteSparse, use UMFPACK to solve the system.
248 UMFPackSolver umf_solver;
249 umf_solver.Control[UMFPACK_ORDERING] = UMFPACK_ORDERING_METIS;
250 umf_solver.SetOperator(*A);
251 umf_solver.Mult(B, X);
252#endif
253 }
254 }
255 else
256 {
257 if (UsesTensorBasis(fespace))
258 {
259 if (algebraic_ceed)
260 {
262 PCG(*A, M, B, X, 1, 400, 1e-12, 0.0);
263 }
264 else
265 {
267 PCG(*A, M, B, X, 1, 400, 1e-12, 0.0);
268 }
269 }
270 else
271 {
272 CG(*A, B, X, 1, 400, 1e-12, 0.0);
273 }
274 }
275
276 // 12. Recover the solution as a finite element grid function.
277 a.RecoverFEMSolution(X, b, x);
278
279 // 13. Save the refined mesh and the solution. This output can be viewed later
280 // using GLVis: "glvis -m refined.mesh -g sol.gf".
281 ofstream mesh_ofs("refined.mesh");
282 mesh_ofs.precision(8);
283 mesh.Print(mesh_ofs);
284 ofstream sol_ofs("sol.gf");
285 sol_ofs.precision(8);
286 x.Save(sol_ofs);
287
288 // 14. Send the solution by socket to a GLVis server.
289 if (visualization)
290 {
291 char vishost[] = "localhost";
292 int visport = 19916;
293 socketstream sol_sock(vishost, visport);
294 sol_sock.precision(8);
295 sol_sock << "solution\n" << mesh << x << flush;
296 }
297
298 // 15. Free the used memory.
299 if (order > 0) { delete fec; }
300
301 return 0;
302}
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
@ GaussLobatto
Closed type.
Definition fe_base.hpp:36
@ Positive
Bernstein polynomials.
Definition fe_base.hpp:37
A "square matrix" operator for the associated FE space and BLFIntegrators The sum of all the BLFInteg...
A coefficient that is constant across space and time.
cuDSS: A high-performance CUDA Library for Direct Sparse Solvers
Definition cudss.hpp:38
void Mult(const Vector &x, Vector &y) const override
Solve .
Definition cudss.cpp:401
void SetOperator(const Operator &op) override
Set/update the solver for the given operator.
Definition cudss.cpp:350
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
static bool Allows(unsigned long b_mask)
Return true if any of the backends in the backend mask, b_mask, are allowed.
Definition device.hpp:271
static bool IsEnabled()
Return true if any backend other than Backend::CPU is enabled.
Definition device.hpp:252
Class for domain integration .
Definition lininteg.hpp:108
Collection of finite elements from the same family in multiple dimensions. This class is used to matc...
Definition fe_coll.hpp:27
virtual const char * Name() const
Definition fe_coll.hpp:79
Class FiniteElementSpace - responsible for providing FEM view of the mesh, mainly managing the set of...
Definition fespace.hpp:210
virtual int GetTrueVSize() const
Return the number of vector true (conforming) dofs.
Definition fespace.hpp:827
virtual void GetEssentialTrueDofs(const Array< int > &bdr_attr_is_ess, Array< int > &ess_tdof_list, int component=-1) const
Get a list of essential true dofs, ess_tdof_list, corresponding to the boundary attributes marked in ...
Definition fespace.cpp:624
Gauss-Seidel smoother of a sparse matrix.
Class for grid function - Vector with associated FE space.
Definition gridfunc.hpp:53
virtual void Save(std::ostream &out) const
Save the GridFunction to an output stream.
Arbitrary order H1-conforming (continuous) finite elements.
Definition fe_coll.hpp:291
Vector with associated FE space and LinearFormIntegrators.
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
virtual void MarkExternalBoundaries(Array< int > &bdr_marker, bool excl=true) const
Mark boundary attributes of external boundaries.
Definition mesh.cpp:1818
virtual void Print(std::ostream &os=mfem::out, const std::string &comments="") const
Print the mesh to the given stream using the default MFEM mesh format.
Definition mesh.hpp:2610
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
bool IsSimplexMesh() const
Returns true if the mesh is a simplex mesh, false otherwise.
Definition mesh.hpp:1370
void GetNodes(Vector &node_coord) const
Definition mesh.cpp:10112
void UniformRefinement(int i, const DSTable &, int *, int *, int *)
Definition mesh.cpp:12125
Pointer to an Operator of a specified type.
Definition handle.hpp:34
Jacobi smoothing for a given bilinear form (no matrix necessary).
Definition solvers.hpp:422
int Height() const
Get the height (size of output) of the Operator. Synonym with NumRows().
Definition operator.hpp:68
void Parse()
Parse the command-line options. Note that this function expects all the options provided through the ...
void PrintUsage(std::ostream &out) const
Print the usage message.
void PrintOptions(std::ostream &out) const
Print the options.
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
bool Good() const
Return true if the command line options were parsed successfully.
Data type sparse matrix.
Definition sparsemat.hpp:51
Direct sparse solver using UMFPACK.
Definition solvers.hpp:1210
real_t Control[UMFPACK_CONTROL]
Definition solvers.hpp:1220
void SetOperator(const Operator &op) override
Factorize the given Operator op which must be a SparseMatrix.
Definition solvers.cpp:3368
void Mult(const Vector &b, Vector &x) const override
Direct solution of the linear system using UMFPACK.
Definition solvers.cpp:3463
Vector data type.
Definition vector.hpp:82
Wrapper for AlgebraicMultigrid object.
const int * ess_tdof_list
int dim
Definition ex24.cpp:53
int main()
real_t b
Definition lissajous.cpp:42
real_t a
Definition lissajous.cpp:41
void PCG(const Operator &A, Solver &B, const Vector &b, Vector &x, int print_iter, int max_num_iter, real_t RTOLERANCE, real_t ATOLERANCE)
Preconditioned conjugate gradient method. (tolerances are squared)
Definition solvers.cpp:1067
void CG(const Operator &A, const Vector &b, Vector &x, int print_iter, int max_num_iter, real_t RTOLERANCE, real_t ATOLERANCE)
Conjugate gradient method. (tolerances are squared)
Definition solvers.cpp:1052
bool UsesTensorBasis(const FiniteElementSpace &fes)
Return true if the mesh contains only one topology and the elements are tensor elements.
Definition fespace.hpp:1644
const char vishost[]
STL namespace.
@ CUDA_MASK
Biwise-OR of all CUDA backends.
Definition device.hpp:96