MFEM  v4.1.0 Finite element discretization library
ex16.cpp
Go to the documentation of this file.
1 // MFEM Example 16
2 // SUNDIALS Modification
3 //
4 // Compile with: make ex16
5 //
6 // Sample runs: ex16
7 // ex16 -m ../../data/inline-tri.mesh
8 // ex16 -m ../../data/disc-nurbs.mesh -tf 2
9 // ex16 -s 12 -a 0.0 -k 1.0
10 // ex16 -s 8 -a 1.0 -k 0.0 -dt 1e-4 -tf 5e-2 -vs 25
11 // ex16 -s 9 -a 0.5 -k 0.5 -o 4 -dt 1e-4 -tf 2e-2 -vs 25
12 // ex16 -s 10 -dt 1.0e-4 -tf 4.0e-2 -vs 40
13 // ex16 -m ../../data/fichera-q2.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. By default, this
28 // example uses the SUNDIALS ODE solvers from CVODE and ARKODE.
29 //
30 // We recommend viewing examples 2, 9 and 10 before viewing this
31 // example.
32
33 #include "mfem.hpp"
34 #include <fstream>
35 #include <iostream>
36
37 using namespace std;
38 using namespace mfem;
39
40 /** After spatial discretization, the conduction model can be written as:
41  *
42  * du/dt = M^{-1}(-Ku)
43  *
44  * where u is the vector representing the temperature, M is the mass matrix,
45  * and K is the diffusion operator with diffusivity depending on u:
46  * (\kappa + \alpha u).
47  *
48  * Class ConductionOperator represents the right-hand side of the above ODE.
49  */
50 class ConductionOperator : public TimeDependentOperator
51 {
52 protected:
53  FiniteElementSpace &fespace;
54  Array<int> ess_tdof_list; // this list remains empty for pure Neumann b.c.
55
56  BilinearForm *M;
57  BilinearForm *K;
58
59  SparseMatrix Mmat, Kmat;
60  SparseMatrix *T; // T = M + dt K
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
78  /** Solve the Backward-Euler equation: k = f(u + dt*k, t), for the unknown k.
79  This is the only requirement for high-order SDIRK implicit integration.*/
80  virtual void ImplicitSolve(const double dt, const Vector &u, Vector &k);
81
82  /// Custom Jacobian system solver for the SUNDIALS time integrators.
83  /** For the ODE system represented by ConductionOperator
84
85  M du/dt = -K(u),
86
87  this class facilitates the solution of linear systems of the form
88
89  (M + γK) y = M b,
90
91  for given b, u (not used), and γ = GetTimeStep(). */
92
93  /** Setup the system (M + dt K) x = M b. This method is used by the implicit
94  SUNDIALS solvers. */
95  virtual int SUNImplicitSetup(const Vector &x, const Vector &fx,
96  int jok, int *jcur, double gamma);
97
98  /** Solve the system (M + dt K) x = M b. This method is used by the implicit
99  SUNDIALS solvers. */
100  virtual int SUNImplicitSolve(const Vector &b, Vector &x, double tol);
101
102  /// Update the diffusion BilinearForm K using the given true-dof vector u.
103  void SetParameters(const Vector &u);
104
105  virtual ~ConductionOperator();
106 };
107
108 double InitialTemperature(const Vector &x);
109
110 int main(int argc, char *argv[])
111 {
112  // 1. Parse command-line options.
113  const char *mesh_file = "../../data/star.mesh";
114  int ref_levels = 2;
115  int order = 2;
116  int ode_solver_type = 9; // CVODE implicit BDF
117  double t_final = 0.5;
118  double dt = 1.0e-2;
119  double alpha = 1.0e-2;
120  double kappa = 0.5;
121  bool visualization = true;
122  bool visit = false;
123  int vis_steps = 5;
124
125  // Relative and absolute tolerances for CVODE and ARKODE.
126  const double reltol = 1e-4, abstol = 1e-4;
127
128  int precision = 8;
129  cout.precision(precision);
130
131  OptionsParser args(argc, argv);
133  "Mesh file to use.");
135  "Number of times to refine the mesh uniformly.");
137  "Order (degree) of the finite elements.");
139  "ODE solver:\n\t"
140  "1 - Forward Euler,\n\t"
141  "2 - RK2,\n\t"
142  "3 - RK3 SSP,\n\t"
143  "4 - RK4,\n\t"
144  "5 - Backward Euler,\n\t"
145  "6 - SDIRK 2,\n\t"
146  "7 - SDIRK 3,\n\t"
147  "8 - CVODE (implicit Adams),\n\t"
148  "9 - CVODE (implicit BDF),\n\t"
149  "10 - ARKODE (default explicit),\n\t"
150  "11 - ARKODE (explicit Fehlberg-6-4-5),\n\t"
151  "12 - ARKODE (default impicit).");
153  "Final time; start time is 0.");
155  "Time step.");
157  "Alpha coefficient.");
159  "Kappa coefficient offset.");
161  "--no-visualization",
162  "Enable or disable GLVis visualization.");
164  "--no-visit-datafiles",
165  "Save data files for VisIt (visit.llnl.gov) visualization.");
167  "Visualize every n-th timestep.");
168  args.Parse();
169  if (!args.Good())
170  {
171  args.PrintUsage(cout);
172  return 1;
173  }
174  if (ode_solver_type < 1 || ode_solver_type > 12)
175  {
176  cout << "Unknown ODE solver type: " << ode_solver_type << '\n';
177  return 3;
178  }
179  args.PrintOptions(cout);
180
181  // 2. Read the mesh from the given mesh file. We can handle triangular,
182  // quadrilateral, tetrahedral and hexahedral meshes with the same code.
183  Mesh *mesh = new Mesh(mesh_file, 1, 1);
184  int dim = mesh->Dimension();
185
186  // 3. Refine the mesh to increase the resolution. In this example we do
187  // 'ref_levels' of uniform refinement, where 'ref_levels' is a
188  // command-line parameter.
189  for (int lev = 0; lev < ref_levels; lev++)
190  {
191  mesh->UniformRefinement();
192  }
193
194  // 4. Define the vector finite element space representing the current and the
195  // initial temperature, u_ref.
196  H1_FECollection fe_coll(order, dim);
197  FiniteElementSpace fespace(mesh, &fe_coll);
198
199  int fe_size = fespace.GetTrueVSize();
200  cout << "Number of temperature unknowns: " << fe_size << endl;
201
202  GridFunction u_gf(&fespace);
203
204  // 5. Set the initial conditions for u. All boundaries are considered
205  // natural.
207  u_gf.ProjectCoefficient(u_0);
208  Vector u;
209  u_gf.GetTrueDofs(u);
210
211  // 6. Initialize the conduction operator and the visualization.
212  ConductionOperator oper(fespace, alpha, kappa, u);
213
214  u_gf.SetFromTrueDofs(u);
215  {
216  ofstream omesh("ex16.mesh");
217  omesh.precision(precision);
218  mesh->Print(omesh);
219  ofstream osol("ex16-init.gf");
220  osol.precision(precision);
221  u_gf.Save(osol);
222  }
223
224  VisItDataCollection visit_dc("Example16", mesh);
225  visit_dc.RegisterField("temperature", &u_gf);
226  if (visit)
227  {
228  visit_dc.SetCycle(0);
229  visit_dc.SetTime(0.0);
230  visit_dc.Save();
231  }
232
233  socketstream sout;
234  if (visualization)
235  {
236  char vishost[] = "localhost";
237  int visport = 19916;
238  sout.open(vishost, visport);
239  if (!sout)
240  {
241  cout << "Unable to connect to GLVis server at "
242  << vishost << ':' << visport << endl;
243  visualization = false;
244  cout << "GLVis visualization disabled.\n";
245  }
246  else
247  {
248  sout.precision(precision);
249  sout << "solution\n" << *mesh << u_gf;
250  sout << "pause\n";
251  sout << flush;
252  cout << "GLVis visualization paused."
253  << " Press space (in the GLVis window) to resume it.\n";
254  }
255  }
256
257  // 7. Define the ODE solver used for time integration.
258  double t = 0.0;
259  ODESolver *ode_solver = NULL;
260  CVODESolver *cvode = NULL;
261  ARKStepSolver *arkode = NULL;
262  switch (ode_solver_type)
263  {
264  // MFEM explicit methods
265  case 1: ode_solver = new ForwardEulerSolver; break;
266  case 2: ode_solver = new RK2Solver(0.5); break; // midpoint method
267  case 3: ode_solver = new RK3SSPSolver; break;
268  case 4: ode_solver = new RK4Solver; break;
269  // MFEM implicit L-stable methods
270  case 5: ode_solver = new BackwardEulerSolver; break;
271  case 6: ode_solver = new SDIRK23Solver(2); break;
272  case 7: ode_solver = new SDIRK33Solver; break;
273  // CVODE
274  case 8:
276  cvode->Init(oper);
277  cvode->SetSStolerances(reltol, abstol);
278  cvode->SetMaxStep(dt);
279  ode_solver = cvode; break;
280  case 9:
281  cvode = new CVODESolver(CV_BDF);
282  cvode->Init(oper);
283  cvode->SetSStolerances(reltol, abstol);
284  cvode->SetMaxStep(dt);
285  ode_solver = cvode; break;
286  // ARKODE
287  case 10:
288  case 11:
289  arkode = new ARKStepSolver(ARKStepSolver::EXPLICIT);
290  arkode->Init(oper);
291  arkode->SetSStolerances(reltol, abstol);
292  arkode->SetMaxStep(dt);
293  if (ode_solver_type == 11) { arkode->SetERKTableNum(FEHLBERG_13_7_8); }
294  ode_solver = arkode; break;
295  case 12:
296  arkode = new ARKStepSolver(ARKStepSolver::IMPLICIT);
297  arkode->Init(oper);
298  arkode->SetSStolerances(reltol, abstol);
299  arkode->SetMaxStep(dt);
300  ode_solver = arkode; break;
301  }
302
303  // Initialize MFEM integrators, SUNDIALS integrators are initialized above
304  if (ode_solver_type < 8) { ode_solver->Init(oper); }
305
306  // Since we want to update the diffusion coefficient after every time step,
307  // we need to use the "one-step" mode of the SUNDIALS solvers.
308  if (cvode) { cvode->SetStepMode(CV_ONE_STEP); }
309  if (arkode) { arkode->SetStepMode(ARK_ONE_STEP); }
310
311  // 8. Perform time-integration (looping over the time iterations, ti, with a
312  // time-step dt).
313  cout << "Integrating the ODE ..." << endl;
314  tic_toc.Clear();
315  tic_toc.Start();
316
317  bool last_step = false;
318  for (int ti = 1; !last_step; ti++)
319  {
320  double dt_real = min(dt, t_final - t);
321
322  // Note that since we are using the "one-step" mode of the SUNDIALS
323  // solvers, they will, generally, step over the final time and will not
324  // explicitly perform the interpolation to t_final as they do in the
325  // "normal" step mode.
326
327  ode_solver->Step(u, t, dt_real);
328
329  last_step = (t >= t_final - 1e-8*dt);
330
331  if (last_step || (ti % vis_steps) == 0)
332  {
333  cout << "step " << ti << ", t = " << t << endl;
334  if (cvode) { cvode->PrintInfo(); }
335  if (arkode) { arkode->PrintInfo(); }
336
337  u_gf.SetFromTrueDofs(u);
338  if (visualization)
339  {
340  sout << "solution\n" << *mesh << u_gf << flush;
341  }
342
343  if (visit)
344  {
345  visit_dc.SetCycle(ti);
346  visit_dc.SetTime(t);
347  visit_dc.Save();
348  }
349  }
350  oper.SetParameters(u);
351  }
352  tic_toc.Stop();
353  cout << "Done, " << tic_toc.RealTime() << "s." << endl;
354
355  // 9. Save the final solution. This output can be viewed later using GLVis:
356  // "glvis -m ex16.mesh -g ex16-final.gf".
357  {
358  ofstream osol("ex16-final.gf");
359  osol.precision(precision);
360  u_gf.Save(osol);
361  }
362
363  // 10. Free the used memory.
364  delete ode_solver;
365  delete mesh;
366
367  return 0;
368 }
369
370 ConductionOperator::ConductionOperator(FiniteElementSpace &f, double al,
371  double kap, const Vector &u)
372  : TimeDependentOperator(f.GetTrueVSize(), 0.0), fespace(f), M(NULL), K(NULL),
373  T(NULL), z(height)
374 {
375  const double rel_tol = 1e-8;
376
377  M = new BilinearForm(&fespace);
379  M->Assemble();
380  M->FormSystemMatrix(ess_tdof_list, Mmat);
381
382  M_solver.iterative_mode = false;
383  M_solver.SetRelTol(rel_tol);
384  M_solver.SetAbsTol(0.0);
385  M_solver.SetMaxIter(50);
386  M_solver.SetPrintLevel(0);
387  M_solver.SetPreconditioner(M_prec);
388  M_solver.SetOperator(Mmat);
389
390  alpha = al;
391  kappa = kap;
392
393  T_solver.iterative_mode = false;
394  T_solver.SetRelTol(rel_tol);
395  T_solver.SetAbsTol(0.0);
396  T_solver.SetMaxIter(100);
397  T_solver.SetPrintLevel(0);
398  T_solver.SetPreconditioner(T_prec);
399
400  SetParameters(u);
401 }
402
403 void ConductionOperator::Mult(const Vector &u, Vector &du_dt) const
404 {
405  // Compute:
406  // du_dt = M^{-1}*-K(u)
407  // for du_dt
408  Kmat.Mult(u, z);
409  z.Neg(); // z = -z
410  M_solver.Mult(z, du_dt);
411 }
412
413 void ConductionOperator::ImplicitSolve(const double dt,
414  const Vector &u, Vector &du_dt)
415 {
416  // Solve the equation:
417  // du_dt = M^{-1}*[-K(u + dt*du_dt)]
418  // for du_dt
419  if (T) { delete T; }
420  T = Add(1.0, Mmat, dt, Kmat);
421  T_solver.SetOperator(*T);
422  Kmat.Mult(u, z);
423  z.Neg();
424  T_solver.Mult(z, du_dt);
425 }
426
427 void ConductionOperator::SetParameters(const Vector &u)
428 {
429  GridFunction u_alpha_gf(&fespace);
430  u_alpha_gf.SetFromTrueDofs(u);
431  for (int i = 0; i < u_alpha_gf.Size(); i++)
432  {
433  u_alpha_gf(i) = kappa + alpha*u_alpha_gf(i);
434  }
435
436  delete K;
437  K = new BilinearForm(&fespace);
438
439  GridFunctionCoefficient u_coeff(&u_alpha_gf);
440
442  K->Assemble();
443  K->FormSystemMatrix(ess_tdof_list, Kmat);
444 }
445
446 int ConductionOperator::SUNImplicitSetup(const Vector &x,
447  const Vector &fx, int jok, int *jcur,
448  double gamma)
449 {
450  // Setup the ODE Jacobian T = M + gamma K.
451  if (T) { delete T; }
452  T = Add(1.0, Mmat, gamma, Kmat);
453  T_solver.SetOperator(*T);
454  *jcur = 1;
455  return (0);
456 }
457
458 int ConductionOperator::SUNImplicitSolve(const Vector &b, Vector &x, double tol)
459 {
460  // Solve the system A x = z => (M - gamma K) x = M b.
461  Mmat.Mult(b, z);
462  T_solver.Mult(z, x);
463  return (0);
464 }
465
466 ConductionOperator::~ConductionOperator()
467 {
468  delete T;
469  delete M;
470  delete K;
471 }
472
473 double InitialTemperature(const Vector &x)
474 {
475  if (x.Norml2() < 0.5)
476  {
477  return 2.0;
478  }
479  else
480  {
481  return 1.0;
482  }
483 }
void Init(TimeDependentOperator &f_)
Initialize CVODE: calls CVodeCreate() to create the CVODE memory and set some defaults.
Definition: sundials.cpp:151
virtual void Print(std::ostream &out=mfem::out) const
Definition: mesh.hpp:1188
Definition: solvers.hpp:152
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.
void SetSStolerances(double reltol, double abstol)
Set the scalar relative and scalar absolute tolerances.
Definition: sundials.cpp:342
Select the ARKode step mode: ARK_NORMAL (default) or ARK_ONE_STEP.
Definition: sundials.cpp:824
Base abstract class for first order time dependent operators.
Definition: operator.hpp:259
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:711
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.
void SetMaxStep(double dt_max)
Set the maximum time step.
Definition: sundials.cpp:835
StopWatch tic_toc
Definition: tic_toc.cpp:447
double RealTime()
Definition: tic_toc.cpp:426
int main(int argc, char *argv[])
Definition: ex1.cpp:62
Backward Euler ODE solver. L-stable.
Definition: ode.hpp:360
Interface to ARKode&#39;s ARKStep module – additive Runge-Kutta methods.
Definition: sundials.hpp:197
virtual void Save(std::ostream &out) const
Save the GridFunction to an output stream.
Definition: gridfunc.cpp:2731
void Add(const DenseMatrix &A, const DenseMatrix &B, double alpha, DenseMatrix &C)
C = A + alpha*B.
Definition: densemat.cpp:1926
Data type sparse matrix.
Definition: sparsemat.hpp:40
Interface to the CVODE library – linear multi-step methods.
Definition: sundials.hpp:92
double b
Definition: lissajous.cpp:42
void UniformRefinement(int i, const DSTable &, int *, int *, int *)
Definition: mesh.cpp:7982
Data collection with VisIt I/O routines.
void SetMaxStep(double dt_max)
Set the maximum time step.
Definition: sundials.cpp:348
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:384
int Dimension() const
Definition: mesh.hpp:744
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:87
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.
void PrintInfo() const
Print various ARKStep statistics.
Definition: sundials.cpp:871
int dim
Definition: ex24.cpp:43
void PrintOptions(std::ostream &out) const
Definition: optparser.cpp:304
virtual void ProjectCoefficient(Coefficient &coeff)
Definition: gridfunc.cpp:1685
int open(const char hostname[], int port)
const double alpha
Definition: ex15.cpp:336
class for C-function coefficient
double kappa
Definition: ex3.cpp:54
Vector data type.
Definition: vector.hpp:48
Arbitrary order H1-conforming (continuous) finite elements.
Definition: fe_coll.hpp:83
void PrintInfo() const
Print various CVODE statistics.
Definition: sundials.cpp:360
void SetERKTableNum(int table_num)
Choose a specific Butcher table for an explicit RK method.
Definition: sundials.cpp:847
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
void Init(TimeDependentOperator &f_)
Initialize ARKode: calls ARKStepCreate() to create the ARKStep memory and set some defaults...
Definition: sundials.cpp:565
void SetSStolerances(double reltol, double abstol)
Set the scalar relative and scalar absolute tolerances.
Definition: sundials.cpp:829