MFEM  v4.0
Finite element discretization library
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Pages
ex16.cpp
Go to the documentation of this file.
1 // MFEM Example 16
2 //
3 // Compile with: make ex16
4 //
5 // Sample runs: ex16
6 // ex16 -m ../data/inline-tri.mesh
7 // ex16 -m ../data/disc-nurbs.mesh -tf 2
8 // ex16 -s 1 -a 0.0 -k 1.0
9 // ex16 -s 2 -a 1.0 -k 0.0
10 // ex16 -s 3 -a 0.5 -k 0.5 -o 4
11 // ex16 -s 14 -dt 1.0e-4 -tf 4.0e-2 -vs 40
12 // ex16 -m ../data/fichera-q2.mesh
13 // ex16 -m ../data/fichera-mixed.mesh
14 // ex16 -m ../data/escher.mesh
15 // ex16 -m ../data/beam-tet.mesh -tf 10 -dt 0.1
16 // ex16 -m ../data/amr-quad.mesh -o 4 -r 0
17 // ex16 -m ../data/amr-hex.mesh -o 2 -r 0
18 //
19 // Description: This example solves a time dependent nonlinear heat equation
20 // problem of the form du/dt = C(u), with a non-linear diffusion
21 // operator C(u) = \nabla \cdot (\kappa + \alpha u) \nabla u.
22 //
23 // The example demonstrates the use of nonlinear operators (the
24 // class ConductionOperator defining C(u)), as well as their
25 // implicit time integration. Note that implementing the method
26 // ConductionOperator::ImplicitSolve is the only requirement for
27 // high-order implicit (SDIRK) time integration.
28 //
29 // We recommend viewing examples 2, 9 and 10 before viewing this
30 // example.
31 
32 #include "mfem.hpp"
33 #include <fstream>
34 #include <iostream>
35 
36 using namespace std;
37 using namespace mfem;
38 
39 /** After spatial discretization, the conduction model can be written as:
40  *
41  * du/dt = M^{-1}(-Ku)
42  *
43  * where u is the vector representing the temperature, M is the mass matrix,
44  * and K is the diffusion operator with diffusivity depending on u:
45  * (\kappa + \alpha u).
46  *
47  * Class ConductionOperator represents the right-hand side of the above ODE.
48  */
49 class ConductionOperator : public TimeDependentOperator
50 {
51 protected:
52  FiniteElementSpace &fespace;
53  Array<int> ess_tdof_list; // this list remains empty for pure Neumann b.c.
54 
55  BilinearForm *M;
56  BilinearForm *K;
57 
58  SparseMatrix Mmat, Kmat;
59  SparseMatrix *T; // T = M + dt K
60  double current_dt;
61 
62  CGSolver M_solver; // Krylov solver for inverting the mass matrix M
63  DSmoother M_prec; // Preconditioner for the mass matrix M
64 
65  CGSolver T_solver; // Implicit solver for T = M + dt K
66  DSmoother T_prec; // Preconditioner for the implicit solver
67 
68  double alpha, kappa;
69 
70  mutable Vector z; // auxiliary vector
71 
72 public:
73  ConductionOperator(FiniteElementSpace &f, double alpha, double kappa,
74  const Vector &u);
75 
76  virtual void Mult(const Vector &u, Vector &du_dt) const;
77  /** Solve the Backward-Euler equation: k = f(u + dt*k, t), for the unknown k.
78  This is the only requirement for high-order SDIRK implicit integration.*/
79  virtual void ImplicitSolve(const double dt, const Vector &u, Vector &k);
80 
81  /// Update the diffusion BilinearForm K using the given true-dof vector `u`.
82  void SetParameters(const Vector &u);
83 
84  virtual ~ConductionOperator();
85 };
86 
87 double InitialTemperature(const Vector &x);
88 
89 int main(int argc, char *argv[])
90 {
91  // 1. Parse command-line options.
92  const char *mesh_file = "../data/star.mesh";
93  int ref_levels = 2;
94  int order = 2;
95  int ode_solver_type = 3;
96  double t_final = 0.5;
97  double dt = 1.0e-2;
98  double alpha = 1.0e-2;
99  double kappa = 0.5;
100  bool visualization = true;
101  bool visit = false;
102  int vis_steps = 5;
103 
104  int precision = 8;
105  cout.precision(precision);
106 
107  OptionsParser args(argc, argv);
108  args.AddOption(&mesh_file, "-m", "--mesh",
109  "Mesh file to use.");
110  args.AddOption(&ref_levels, "-r", "--refine",
111  "Number of times to refine the mesh uniformly.");
112  args.AddOption(&order, "-o", "--order",
113  "Order (degree) of the finite elements.");
114  args.AddOption(&ode_solver_type, "-s", "--ode-solver",
115  "ODE solver: 1 - Backward Euler, 2 - SDIRK2, 3 - SDIRK3,\n\t"
116  "\t 11 - Forward Euler, 12 - RK2, 13 - RK3 SSP, 14 - RK4.");
117  args.AddOption(&t_final, "-tf", "--t-final",
118  "Final time; start time is 0.");
119  args.AddOption(&dt, "-dt", "--time-step",
120  "Time step.");
121  args.AddOption(&alpha, "-a", "--alpha",
122  "Alpha coefficient.");
123  args.AddOption(&kappa, "-k", "--kappa",
124  "Kappa coefficient offset.");
125  args.AddOption(&visualization, "-vis", "--visualization", "-no-vis",
126  "--no-visualization",
127  "Enable or disable GLVis visualization.");
128  args.AddOption(&visit, "-visit", "--visit-datafiles", "-no-visit",
129  "--no-visit-datafiles",
130  "Save data files for VisIt (visit.llnl.gov) visualization.");
131  args.AddOption(&vis_steps, "-vs", "--visualization-steps",
132  "Visualize every n-th timestep.");
133  args.Parse();
134  if (!args.Good())
135  {
136  args.PrintUsage(cout);
137  return 1;
138  }
139  args.PrintOptions(cout);
140 
141  // 2. Read the mesh from the given mesh file. We can handle triangular,
142  // quadrilateral, tetrahedral and hexahedral meshes with the same code.
143  Mesh *mesh = new Mesh(mesh_file, 1, 1);
144  int dim = mesh->Dimension();
145 
146  // 3. Define the ODE solver used for time integration. Several implicit
147  // singly diagonal implicit Runge-Kutta (SDIRK) methods, as well as
148  // explicit Runge-Kutta methods are available.
149  ODESolver *ode_solver;
150  switch (ode_solver_type)
151  {
152  // Implicit L-stable methods
153  case 1: ode_solver = new BackwardEulerSolver; break;
154  case 2: ode_solver = new SDIRK23Solver(2); break;
155  case 3: ode_solver = new SDIRK33Solver; break;
156  // Explicit methods
157  case 11: ode_solver = new ForwardEulerSolver; break;
158  case 12: ode_solver = new RK2Solver(0.5); break; // midpoint method
159  case 13: ode_solver = new RK3SSPSolver; break;
160  case 14: ode_solver = new RK4Solver; break;
161  case 15: ode_solver = new GeneralizedAlphaSolver(0.5); break;
162  // Implicit A-stable methods (not L-stable)
163  case 22: ode_solver = new ImplicitMidpointSolver; break;
164  case 23: ode_solver = new SDIRK23Solver; break;
165  case 24: ode_solver = new SDIRK34Solver; break;
166  default:
167  cout << "Unknown ODE solver type: " << ode_solver_type << '\n';
168  delete mesh;
169  return 3;
170  }
171 
172  // 4. Refine the mesh to increase the resolution. In this example we do
173  // 'ref_levels' of uniform refinement, where 'ref_levels' is a
174  // command-line parameter.
175  for (int lev = 0; lev < ref_levels; lev++)
176  {
177  mesh->UniformRefinement();
178  }
179 
180  // 5. Define the vector finite element space representing the current and the
181  // initial temperature, u_ref.
182  H1_FECollection fe_coll(order, dim);
183  FiniteElementSpace fespace(mesh, &fe_coll);
184 
185  int fe_size = fespace.GetTrueVSize();
186  cout << "Number of temperature unknowns: " << fe_size << endl;
187 
188  GridFunction u_gf(&fespace);
189 
190  // 6. Set the initial conditions for u. All boundaries are considered
191  // natural.
193  u_gf.ProjectCoefficient(u_0);
194  Vector u;
195  u_gf.GetTrueDofs(u);
196 
197  // 7. Initialize the conduction operator and the visualization.
198  ConductionOperator oper(fespace, alpha, kappa, u);
199 
200  u_gf.SetFromTrueDofs(u);
201  {
202  ofstream omesh("ex16.mesh");
203  omesh.precision(precision);
204  mesh->Print(omesh);
205  ofstream osol("ex16-init.gf");
206  osol.precision(precision);
207  u_gf.Save(osol);
208  }
209 
210  VisItDataCollection visit_dc("Example16", mesh);
211  visit_dc.RegisterField("temperature", &u_gf);
212  if (visit)
213  {
214  visit_dc.SetCycle(0);
215  visit_dc.SetTime(0.0);
216  visit_dc.Save();
217  }
218 
219  socketstream sout;
220  if (visualization)
221  {
222  char vishost[] = "localhost";
223  int visport = 19916;
224  sout.open(vishost, visport);
225  if (!sout)
226  {
227  cout << "Unable to connect to GLVis server at "
228  << vishost << ':' << visport << endl;
229  visualization = false;
230  cout << "GLVis visualization disabled.\n";
231  }
232  else
233  {
234  sout.precision(precision);
235  sout << "solution\n" << *mesh << u_gf;
236  sout << "pause\n";
237  sout << flush;
238  cout << "GLVis visualization paused."
239  << " Press space (in the GLVis window) to resume it.\n";
240  }
241  }
242 
243  // 8. Perform time-integration (looping over the time iterations, ti, with a
244  // time-step dt).
245  ode_solver->Init(oper);
246  double t = 0.0;
247 
248  bool last_step = false;
249  for (int ti = 1; !last_step; ti++)
250  {
251  if (t + dt >= t_final - dt/2)
252  {
253  last_step = true;
254  }
255 
256  ode_solver->Step(u, t, dt);
257 
258  if (last_step || (ti % vis_steps) == 0)
259  {
260  cout << "step " << ti << ", t = " << t << endl;
261 
262  u_gf.SetFromTrueDofs(u);
263  if (visualization)
264  {
265  sout << "solution\n" << *mesh << u_gf << flush;
266  }
267 
268  if (visit)
269  {
270  visit_dc.SetCycle(ti);
271  visit_dc.SetTime(t);
272  visit_dc.Save();
273  }
274  }
275  oper.SetParameters(u);
276  }
277 
278  // 9. Save the final solution. This output can be viewed later using GLVis:
279  // "glvis -m ex16.mesh -g ex16-final.gf".
280  {
281  ofstream osol("ex16-final.gf");
282  osol.precision(precision);
283  u_gf.Save(osol);
284  }
285 
286  // 10. Free the used memory.
287  delete ode_solver;
288  delete mesh;
289 
290  return 0;
291 }
292 
293 ConductionOperator::ConductionOperator(FiniteElementSpace &f, double al,
294  double kap, const Vector &u)
295  : TimeDependentOperator(f.GetTrueVSize(), 0.0), fespace(f), M(NULL), K(NULL),
296  T(NULL), current_dt(0.0), z(height)
297 {
298  const double rel_tol = 1e-8;
299 
300  M = new BilinearForm(&fespace);
301  M->AddDomainIntegrator(new MassIntegrator());
302  M->Assemble();
303  M->FormSystemMatrix(ess_tdof_list, Mmat);
304 
305  M_solver.iterative_mode = false;
306  M_solver.SetRelTol(rel_tol);
307  M_solver.SetAbsTol(0.0);
308  M_solver.SetMaxIter(30);
309  M_solver.SetPrintLevel(0);
310  M_solver.SetPreconditioner(M_prec);
311  M_solver.SetOperator(Mmat);
312 
313  alpha = al;
314  kappa = kap;
315 
316  T_solver.iterative_mode = false;
317  T_solver.SetRelTol(rel_tol);
318  T_solver.SetAbsTol(0.0);
319  T_solver.SetMaxIter(100);
320  T_solver.SetPrintLevel(0);
321  T_solver.SetPreconditioner(T_prec);
322 
323  SetParameters(u);
324 }
325 
326 void ConductionOperator::Mult(const Vector &u, Vector &du_dt) const
327 {
328  // Compute:
329  // du_dt = M^{-1}*-K(u)
330  // for du_dt
331  Kmat.Mult(u, z);
332  z.Neg(); // z = -z
333  M_solver.Mult(z, du_dt);
334 }
335 
336 void ConductionOperator::ImplicitSolve(const double dt,
337  const Vector &u, Vector &du_dt)
338 {
339  // Solve the equation:
340  // du_dt = M^{-1}*[-K(u + dt*du_dt)]
341  // for du_dt
342  if (!T)
343  {
344  T = Add(1.0, Mmat, dt, Kmat);
345  current_dt = dt;
346  T_solver.SetOperator(*T);
347  }
348  MFEM_VERIFY(dt == current_dt, ""); // SDIRK methods use the same dt
349  Kmat.Mult(u, z);
350  z.Neg();
351  T_solver.Mult(z, du_dt);
352 }
353 
354 void ConductionOperator::SetParameters(const Vector &u)
355 {
356  GridFunction u_alpha_gf(&fespace);
357  u_alpha_gf.SetFromTrueDofs(u);
358  for (int i = 0; i < u_alpha_gf.Size(); i++)
359  {
360  u_alpha_gf(i) = kappa + alpha*u_alpha_gf(i);
361  }
362 
363  delete K;
364  K = new BilinearForm(&fespace);
365 
366  GridFunctionCoefficient u_coeff(&u_alpha_gf);
367 
368  K->AddDomainIntegrator(new DiffusionIntegrator(u_coeff));
369  K->Assemble();
370  K->FormSystemMatrix(ess_tdof_list, Kmat);
371  delete T;
372  T = NULL; // re-compute T on the next ImplicitSolve
373 }
374 
375 ConductionOperator::~ConductionOperator()
376 {
377  delete T;
378  delete M;
379  delete K;
380 }
381 
382 double InitialTemperature(const Vector &x)
383 {
384  if (x.Norml2() < 0.5)
385  {
386  return 2.0;
387  }
388  else
389  {
390  return 1.0;
391  }
392 }
virtual void Print(std::ostream &out=mfem::out) const
Definition: mesh.hpp:1156
Conjugate gradient method.
Definition: solvers.hpp:111
Class for grid function - Vector with associated FE space.
Definition: gridfunc.hpp:27
double InitialTemperature(const Vector &x)
Definition: ex16.cpp:382
void SetCycle(int c)
Set time cycle (for time-dependent simulations)
Data type for scaled Jacobi-type smoother of sparse matrix.
Base abstract class for time dependent operators.
Definition: operator.hpp:162
void Mult(const Table &A, const Table &B, Table &C)
C = A * B (as boolean matrices)
Definition: table.cpp:476
double Norml2() const
Returns the l2 norm of the vector.
Definition: vector.cpp:709
virtual void Step(Vector &x, double &t, double &dt)=0
Perform a time step from time t [in] to time t [out] based on the requested step size dt [in]...
virtual void Init(TimeDependentOperator &f)
Associate a TimeDependentOperator with the ODE solver.
Definition: ode.cpp:18
Coefficient defined by a GridFunction. This coefficient is mesh dependent.
Abstract class for solving systems of ODEs: dx/dt = f(x,t)
Definition: ode.hpp:22
virtual void Save()
Save the collection and a VisIt root file.
int main(int argc, char *argv[])
Definition: ex1.cpp:58
Backward Euler ODE solver. L-stable.
Definition: ode.hpp:210
virtual void Save(std::ostream &out) const
Save the GridFunction to an output stream.
Definition: gridfunc.cpp:2627
void Add(const DenseMatrix &A, const DenseMatrix &B, double alpha, DenseMatrix &C)
C = A + alpha*B.
Definition: densemat.cpp:3030
int dim
Definition: ex3.cpp:48
Data type sparse matrix.
Definition: sparsemat.hpp:40
void UniformRefinement(int i, const DSTable &, int *, int *, int *)
Definition: mesh.cpp:7591
Data collection with VisIt I/O routines.
void GetTrueDofs(Vector &tv) const
Extract the true-dofs from the GridFunction. If all dofs are true, then tv will be set to point to th...
Definition: gridfunc.cpp:323
virtual int GetTrueVSize() const
Return the number of vector true (conforming) dofs.
Definition: fespace.hpp:350
int Dimension() const
Definition: mesh.hpp:713
void PrintUsage(std::ostream &out) const
Definition: optparser.cpp:434
void SetTime(double t)
Set physical time (for time-dependent simulations)
The classical explicit forth-order Runge-Kutta method, RK4.
Definition: ode.hpp:145
Class FiniteElementSpace - responsible for providing FEM view of the mesh, mainly managing the set of...
Definition: fespace.hpp:85
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
Third-order, strong stability preserving (SSP) Runge-Kutta method.
Definition: ode.hpp:132
virtual void RegisterField(const std::string &field_name, GridFunction *gf)
Add a grid function to the collection and update the root file.
Implicit midpoint method. A-stable, not L-stable.
Definition: ode.hpp:223
void PrintOptions(std::ostream &out) const
Definition: optparser.cpp:304
virtual void ProjectCoefficient(Coefficient &coeff)
Definition: gridfunc.cpp:1582
int open(const char hostname[], int port)
const double alpha
Definition: ex15.cpp:339
class for C-function coefficient
double kappa
Definition: ex3.cpp:47
Vector data type.
Definition: vector.hpp:48
Arbitrary order H1-conforming (continuous) finite elements.
Definition: fe_coll.hpp:83
The classical forward Euler method.
Definition: ode.hpp:99
virtual void SetFromTrueDofs(const Vector &tv)
Set the GridFunction from the given true-dof vector.
Definition: gridfunc.cpp:338
bool Good() const
Definition: optparser.hpp:122