MFEM v4.8.0
Finite element discretization library
Loading...
Searching...
No Matches
ex23.cpp
Go to the documentation of this file.
1// MFEM Example 23
2//
3// Compile with: make ex23
4//
5// Sample runs: ex23
6// ex23 -o 4 -tf 5
7// ex23 -m ../data/square-disc.mesh -o 2 -tf 2 --neumann
8// ex23 -m ../data/disc-nurbs.mesh -r 3 -o 4 -tf 2
9// ex23 -m ../data/inline-hex.mesh -o 1 -tf 2 --neumann
10// ex23 -m ../data/inline-tet.mesh -o 1 -tf 2 --neumann
11//
12// Description: This example solves the wave equation problem of the form:
13//
14// d^2u/dt^2 = c^2 \Delta u.
15//
16// The example demonstrates the use of time dependent operators,
17// implicit solvers and second order time integration.
18//
19// We recommend viewing examples 9 and 10 before viewing this
20// example.
21
22#include "mfem.hpp"
23#include <fstream>
24#include <iostream>
25
26using namespace std;
27using namespace mfem;
28
29/** After spatial discretization, the wave model can be written as:
30 *
31 * d^2u/dt^2 = M^{-1}(-Ku)
32 *
33 * where u is the vector representing the temperature, M is the mass,
34 * and K is the stiffness matrix.
35 *
36 * Class WaveOperator represents the right-hand side of the above ODE.
37 */
38class WaveOperator : public SecondOrderTimeDependentOperator
39{
40protected:
41 FiniteElementSpace &fespace;
42 Array<int> ess_tdof_list; // this list remains empty for pure Neumann b.c.
43
44 BilinearForm *M;
45 BilinearForm *K;
46
47 SparseMatrix Mmat, Kmat;
48 SparseMatrix *T; // T = M + dt K
49 real_t current_dt;
50
51 CGSolver M_solver; // Krylov solver for inverting the mass matrix M
52 DSmoother M_prec; // Preconditioner for the mass matrix M
53
54 CGSolver T_solver; // Implicit solver for T = M + fac0*K
55 DSmoother T_prec; // Preconditioner for the implicit solver
56
57 Coefficient *c2;
58 mutable Vector z; // auxiliary vector
59
60public:
61 WaveOperator(FiniteElementSpace &f, Array<int> &ess_bdr, real_t speed);
62
64 void Mult(const Vector &u, const Vector &du_dt,
65 Vector &d2udt2) const override;
66
67 /** Solve the Backward-Euler equation:
68 d2udt2 = f(u + fac0*d2udt2,dudt + fac1*d2udt2, t),
69 for the unknown d2udt2. */
71 void ImplicitSolve(const real_t fac0, const real_t fac1,
72 const Vector &u, const Vector &dudt, Vector &d2udt2) override;
73
74 ///
75 void SetParameters(const Vector &u);
76
77 ~WaveOperator() override;
78};
79
80
81WaveOperator::WaveOperator(FiniteElementSpace &f,
82 Array<int> &ess_bdr, real_t speed)
83 : SecondOrderTimeDependentOperator(f.GetTrueVSize(), (real_t) 0.0),
84 fespace(f), M(NULL), K(NULL), T(NULL), current_dt(0.0), z(height)
85{
86 // Assemble Laplace matrix
87 c2 = new ConstantCoefficient(speed*speed);
88 K = new BilinearForm(&fespace);
89 K->AddDomainIntegrator(new DiffusionIntegrator(*c2));
90 K->Assemble();
91
92 // Assemble Mass matrix
93 M = new BilinearForm(&fespace);
94 M->AddDomainIntegrator(new MassIntegrator());
95 M->Assemble();
96
97 // Apply BCs
98 fespace.GetEssentialTrueDofs(ess_bdr, ess_tdof_list);
99 K->FormSystemMatrix(ess_tdof_list, Kmat);
100 M->FormSystemMatrix(ess_tdof_list, Mmat);
101
102 // Configure preconditioner
103 const real_t rel_tol = 1e-8;
104 M_solver.iterative_mode = false;
105 M_solver.SetRelTol(rel_tol);
106 M_solver.SetAbsTol(0.0);
107 M_solver.SetMaxIter(30);
108 M_solver.SetPrintLevel(0);
109 M_solver.SetPreconditioner(M_prec);
110 M_solver.SetOperator(Mmat);
111
112 // Configure solver
113 T_solver.iterative_mode = false;
114 T_solver.SetRelTol(rel_tol);
115 T_solver.SetAbsTol(0.0);
116 T_solver.SetMaxIter(100);
117 T_solver.SetPrintLevel(0);
118 T_solver.SetPreconditioner(T_prec);
119}
120
121void WaveOperator::Mult(const Vector &u, const Vector &du_dt,
122 Vector &d2udt2) const
123{
124 // Compute:
125 // d2udt2 = M^{-1}*-K(u)
126 // for d2udt2
127 K->FullMult(u, z);
128 z.Neg(); // z = -z
129 z.SetSubVector(ess_tdof_list, 0.0);
130 M_solver.Mult(z, d2udt2);
131 d2udt2.SetSubVector(ess_tdof_list, 0.0);
132}
133
134void WaveOperator::ImplicitSolve(const real_t fac0, const real_t fac1,
135 const Vector &u, const Vector &dudt, Vector &d2udt2)
136{
137 // Solve the equation:
138 // d2udt2 = M^{-1}*[-K(u + fac0*d2udt2)]
139 // for d2udt2
140 if (!T)
141 {
142 T = Add(1.0, Mmat, fac0, Kmat);
143 T_solver.SetOperator(*T);
144 }
145 K->FullMult(u, z);
146 z.Neg();
147 z.SetSubVector(ess_tdof_list, 0.0);
148 T_solver.Mult(z, d2udt2);
149 d2udt2.SetSubVector(ess_tdof_list, 0.0);
150}
151
152void WaveOperator::SetParameters(const Vector &u)
153{
154 delete T;
155 T = NULL; // re-compute T on the next ImplicitSolve
156}
157
158WaveOperator::~WaveOperator()
159{
160 delete T;
161 delete M;
162 delete K;
163 delete c2;
164}
165
167{
168 return exp(-x.Norml2()*x.Norml2()*30);
169}
170
172{
173 return 0.0;
174}
175
176
177int main(int argc, char *argv[])
178{
179 // 1. Parse command-line options.
180 const char *mesh_file = "../data/star.mesh";
181 const char *ref_dir = "";
182 int ref_levels = 2;
183 int order = 2;
184 int ode_solver_type = 10;
185 real_t t_final = 0.5;
186 real_t dt = 1.0e-2;
187 real_t speed = 1.0;
188 bool visualization = true;
189 bool visit = true;
190 bool dirichlet = true;
191 int vis_steps = 5;
192
193 int precision = 8;
194 cout.precision(precision);
195
196 OptionsParser args(argc, argv);
197 args.AddOption(&mesh_file, "-m", "--mesh",
198 "Mesh file to use.");
199 args.AddOption(&ref_levels, "-r", "--refine",
200 "Number of times to refine the mesh uniformly.");
201 args.AddOption(&order, "-o", "--order",
202 "Order (degree) of the finite elements.");
203 args.AddOption(&ode_solver_type, "-s", "--ode-solver",
205 args.AddOption(&t_final, "-tf", "--t-final",
206 "Final time; start time is 0.");
207 args.AddOption(&dt, "-dt", "--time-step",
208 "Time step.");
209 args.AddOption(&speed, "-c", "--speed",
210 "Wave speed.");
211 args.AddOption(&dirichlet, "-dir", "--dirichlet", "-neu",
212 "--neumann",
213 "BC switch.");
214 args.AddOption(&ref_dir, "-r", "--ref",
215 "Reference directory for checking final solution.");
216 args.AddOption(&visualization, "-vis", "--visualization", "-no-vis",
217 "--no-visualization",
218 "Enable or disable GLVis visualization.");
219 args.AddOption(&visit, "-visit", "--visit-datafiles", "-no-visit",
220 "--no-visit-datafiles",
221 "Save data files for VisIt (visit.llnl.gov) visualization.");
222 args.AddOption(&vis_steps, "-vs", "--visualization-steps",
223 "Visualize every n-th timestep.");
224 args.Parse();
225 if (!args.Good())
226 {
227 args.PrintUsage(cout);
228 return 1;
229 }
230 args.PrintOptions(cout);
231
232 // 2. Read the mesh from the given mesh file. We can handle triangular,
233 // quadrilateral, tetrahedral and hexahedral meshes with the same code.
234 Mesh *mesh = new Mesh(mesh_file, 1, 1);
235 int dim = mesh->Dimension();
236
237 // 3. Define the ODE solver used for time integration. Several second order
238 // time integrators are available.
239 SecondOrderODESolver *ode_solver= SecondOrderODESolver::Select(ode_solver_type);
240
241 // 4. Refine the mesh to increase the resolution. In this example we do
242 // 'ref_levels' of uniform refinement, where 'ref_levels' is a
243 // command-line parameter.
244 for (int lev = 0; lev < ref_levels; lev++)
245 {
246 mesh->UniformRefinement();
247 }
248
249 // 5. Define the vector finite element space representing the current and the
250 // initial temperature, u_ref.
251 H1_FECollection fe_coll(order, dim);
252 FiniteElementSpace fespace(mesh, &fe_coll);
253
254 int fe_size = fespace.GetTrueVSize();
255 cout << "Number of temperature unknowns: " << fe_size << endl;
256
257 GridFunction u_gf(&fespace);
258 GridFunction dudt_gf(&fespace);
259
260 // 6. Set the initial conditions for u. All boundaries are considered
261 // natural.
263 u_gf.ProjectCoefficient(u_0);
264 Vector u;
265 u_gf.GetTrueDofs(u);
266
268 dudt_gf.ProjectCoefficient(dudt_0);
269 Vector dudt;
270 dudt_gf.GetTrueDofs(dudt);
271
272 // 7. Initialize the wave operator and the visualization.
273 Array<int> ess_bdr;
274 if (mesh->bdr_attributes.Size())
275 {
276 ess_bdr.SetSize(mesh->bdr_attributes.Max());
277
278 if (dirichlet)
279 {
280 ess_bdr = 1;
281 }
282 else
283 {
284 ess_bdr = 0;
285 }
286 }
287 WaveOperator oper(fespace, ess_bdr, speed);
288
289 u_gf.SetFromTrueDofs(u);
290 {
291 ofstream omesh("ex23.mesh");
292 omesh.precision(precision);
293 mesh->Print(omesh);
294 ofstream osol("ex23-init.gf");
295 osol.precision(precision);
296 u_gf.Save(osol);
297 dudt_gf.Save(osol);
298 }
299
300 VisItDataCollection visit_dc("Example23", mesh);
301 visit_dc.RegisterField("solution", &u_gf);
302 visit_dc.RegisterField("rate", &dudt_gf);
303 if (visit)
304 {
305 visit_dc.SetCycle(0);
306 visit_dc.SetTime(0.0);
307 visit_dc.Save();
308 }
309
310 socketstream sout;
311 if (visualization)
312 {
313 char vishost[] = "localhost";
314 int visport = 19916;
315 sout.open(vishost, visport);
316 if (!sout)
317 {
318 cout << "Unable to connect to GLVis server at "
319 << vishost << ':' << visport << endl;
320 visualization = false;
321 cout << "GLVis visualization disabled.\n";
322 }
323 else
324 {
325 sout.precision(precision);
326 sout << "solution\n" << *mesh << u_gf;
327 sout << "pause\n";
328 sout << flush;
329 cout << "GLVis visualization paused."
330 << " Press space (in the GLVis window) to resume it.\n";
331 }
332 }
333
334 // 8. Perform time-integration (looping over the time iterations, ti, with a
335 // time-step dt).
336 ode_solver->Init(oper);
337 real_t t = 0.0;
338
339 bool last_step = false;
340 for (int ti = 1; !last_step; ti++)
341 {
342
343 if (t + dt >= t_final - dt/2)
344 {
345 last_step = true;
346 }
347
348 ode_solver->Step(u, dudt, t, dt);
349
350 if (last_step || (ti % vis_steps) == 0)
351 {
352 cout << "step " << ti << ", t = " << t << endl;
353
354 u_gf.SetFromTrueDofs(u);
355 dudt_gf.SetFromTrueDofs(dudt);
356 if (visualization)
357 {
358 sout << "solution\n" << *mesh << u_gf << flush;
359 }
360
361 if (visit)
362 {
363 visit_dc.SetCycle(ti);
364 visit_dc.SetTime(t);
365 visit_dc.Save();
366 }
367 }
368 oper.SetParameters(u);
369 }
370
371 // 9. Save the final solution. This output can be viewed later using GLVis:
372 // "glvis -m ex23.mesh -g ex23-final.gf".
373 {
374 ofstream osol("ex23-final.gf");
375 osol.precision(precision);
376 u_gf.Save(osol);
377 dudt_gf.Save(osol);
378 }
379
380 // 10. Free the used memory.
381 delete ode_solver;
382 delete mesh;
383
384 return 0;
385}
T Max() const
Find the maximal element in the array, using the comparison operator < for class T.
Definition array.cpp:68
void SetSize(int nsize)
Change the logical size of the array, keep existing entries.
Definition array.hpp:758
int Size() const
Return the logical size of the array.
Definition array.hpp:147
A "square matrix" operator for the associated FE space and BLFIntegrators The sum of all the BLFInteg...
void FullMult(const Vector &x, Vector &y) const
Matrix vector multiplication with the original uneliminated matrix. The original matrix is so we hav...
Conjugate gradient method.
Definition solvers.hpp:538
void Mult(const Vector &b, Vector &x) const override
Iterative solution of the linear system using the Conjugate Gradient method.
Definition solvers.cpp:751
void SetOperator(const Operator &op) override
Set/update the solver for the given operator.
Definition solvers.hpp:551
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.
Data type for scaled Jacobi-type smoother of sparse matrix.
void SetCycle(int c)
Set time cycle (for time-dependent simulations)
void SetTime(real_t t)
Set physical time (for time-dependent simulations)
Class FiniteElementSpace - responsible for providing FEM view of the mesh, mainly managing the set of...
Definition fespace.hpp:244
virtual int GetTrueVSize() const
Return the number of vector true (conforming) dofs.
Definition fespace.hpp:851
A general function coefficient.
Class for grid function - Vector with associated FE space.
Definition gridfunc.hpp:31
virtual void Save(std::ostream &out) const
Save the GridFunction to an output stream.
virtual void SetFromTrueDofs(const Vector &tv)
Set the GridFunction from the given true-dof vector.
Definition gridfunc.cpp:378
virtual void ProjectCoefficient(Coefficient &coeff)
Project coeff Coefficient to this GridFunction. The projection computation depends on the choice of t...
void GetTrueDofs(Vector &tv) const
Extract the true-dofs from the GridFunction.
Definition gridfunc.cpp:363
Arbitrary order H1-conforming (continuous) finite elements.
Definition fe_coll.hpp:275
Mesh data type.
Definition mesh.hpp:64
Array< int > bdr_attributes
A list of all unique boundary attributes used by the Mesh.
Definition mesh.hpp:290
virtual void Print(std::ostream &os=mfem::out, const std::string &comments="") const
Definition mesh.hpp:2433
int Dimension() const
Dimension of the reference space used within the elements.
Definition mesh.hpp:1216
void UniformRefinement(int i, const DSTable &, int *, int *, int *)
Definition mesh.cpp:11295
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.
Abstract class for solving systems of ODEs: d2x/dt2 = f(x,dx/dt,t)
Definition ode.hpp:705
static MFEM_EXPORT std::string Types
Help info for SecondOrderODESolver options.
Definition ode.hpp:796
static MFEM_EXPORT SecondOrderODESolver * Select(const int ode_solver_type)
Function selecting the desired SecondOrderODESolver.
Definition ode.cpp:1061
virtual void Init(SecondOrderTimeDependentOperator &f)
Associate a TimeDependentOperator with the ODE solver.
Definition ode.cpp:1119
virtual void Step(Vector &x, Vector &dxdt, real_t &t, real_t &dt)=0
Perform a time step from time t [in] to time t [out] based on the requested step size dt [in].
Base abstract class for second order time dependent operators.
Definition operator.hpp:732
virtual void Mult(const Vector &x, const Vector &dxdt, Vector &y) const
Perform the action of the operator: y = k = f(x,@ dxdt, t), where k solves the algebraic equation F(x...
Definition operator.cpp:352
virtual void ImplicitSolve(const real_t fac0, const real_t fac1, const Vector &x, const Vector &dxdt, Vector &k)
Solve the equation: k = f(x + fac0 k, dxdt + fac1 k, t), for the unknown k at the current time t.
Definition operator.cpp:359
Data type sparse matrix.
Definition sparsemat.hpp:51
Vector data type.
Definition vector.hpp:82
void Neg()
(*this) = -(*this)
Definition vector.cpp:375
void SetSubVector(const Array< int > &dofs, const real_t value)
Set the entries listed in dofs to the given value.
Definition vector.cpp:679
real_t Norml2() const
Returns the l2 norm of the vector.
Definition vector.cpp:931
Data collection with VisIt I/O routines.
void Save() override
Save the collection and a VisIt root file.
void RegisterField(const std::string &field_name, GridFunction *gf) override
Add a grid function to the collection and update the root file.
int open(const char hostname[], int port)
Open the socket stream on 'port' at 'hostname'.
real_t InitialRate(const Vector &x)
Definition ex23.cpp:171
real_t InitialSolution(const Vector &x)
Definition ex23.cpp:166
int dim
Definition ex24.cpp:53
int main()
real_t u(const Vector &xvec)
Definition lor_mms.hpp:22
float real_t
Definition config.hpp:43
std::function< real_t(const Vector &)> f(real_t mass_coeff)
Definition lor_mms.hpp:30
void Add(const DenseMatrix &A, const DenseMatrix &B, real_t alpha, DenseMatrix &C)
C = A + alpha*B.
const char vishost[]