MFEM  v4.4.0
Finite element discretization library
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Pages
ex10p.cpp
Go to the documentation of this file.
1 // MFEM Example 10 - Parallel Version
2 // SUNDIALS Modification
3 //
4 // Compile with: make ex10p
5 //
6 // Sample runs:
7 // mpirun -np 4 ex10p -m ../../data/beam-quad.mesh -rp 1 -o 2 -s 12 -dt 0.15 -vs 10
8 // mpirun -np 4 ex10p -m ../../data/beam-tri.mesh -rp 1 -o 2 -s 16 -dt 0.25 -vs 10
9 // mpirun -np 4 ex10p -m ../../data/beam-hex.mesh -rp 0 -o 2 -s 12 -dt 0.15 -vs 10
10 // mpirun -np 4 ex10p -m ../../data/beam-tri.mesh -rp 1 -o 2 -s 2 -dt 3 -nls kinsol
11 // mpirun -np 4 ex10p -m ../../data/beam-quad.mesh -rp 1 -o 2 -s 2 -dt 3 -nls kinsol
12 // mpirun -np 4 ex10p -m ../../data/beam-hex.mesh -rs 1 -o 2 -s 2 -dt 3 -nls kinsol
13 // mpirun -np 4 ex10p -m ../../data/beam-quad.mesh -rp 1 -o 2 -s 14 -dt 0.15 -vs 10
14 // mpirun -np 4 ex10p -m ../../data/beam-tri.mesh -rp 1 -o 2 -s 17 -dt 5e-3 -vs 60
15 // mpirun -np 4 ex10p -m ../../data/beam-hex.mesh -rp 0 -o 2 -s 14 -dt 0.15 -vs 10
16 // mpirun -np 4 ex10p -m ../../data/beam-quad-amr.mesh -rp 1 -o 2 -s 12 -dt 0.15 -vs 10
17 //
18 // Description: This examples solves a time dependent nonlinear elasticity
19 // problem of the form dv/dt = H(x) + S v, dx/dt = v, where H is a
20 // hyperelastic model and S is a viscosity operator of Laplacian
21 // type. The geometry of the domain is assumed to be as follows:
22 //
23 // +---------------------+
24 // boundary --->| |
25 // attribute 1 | |
26 // (fixed) +---------------------+
27 //
28 // The example demonstrates the use of nonlinear operators (the
29 // class HyperelasticOperator defining H(x)), as well as their
30 // implicit time integration using a Newton method for solving an
31 // associated reduced backward-Euler type nonlinear equation
32 // (class ReducedSystemOperator). Each Newton step requires the
33 // inversion of a Jacobian matrix, which is done through a
34 // (preconditioned) inner solver. Note that implementing the
35 // method HyperelasticOperator::ImplicitSolve is the only
36 // requirement for high-order implicit (SDIRK) time integration.
37 //
38 // We recommend viewing examples 2 and 9 before viewing this
39 // example.
40 
41 #include "mfem.hpp"
42 #include <memory>
43 #include <iostream>
44 #include <fstream>
45 #include <string>
46 #include <map>
47 
48 #ifndef MFEM_USE_SUNDIALS
49 #error This example requires that MFEM is built with MFEM_USE_SUNDIALS=YES
50 #endif
51 
52 using namespace std;
53 using namespace mfem;
54 
55 class ReducedSystemOperator;
56 
57 /** After spatial discretization, the hyperelastic model can be written as a
58  * system of ODEs:
59  * dv/dt = -M^{-1}*(H(x) + S*v)
60  * dx/dt = v,
61  * where x is the vector representing the deformation, v is the velocity field,
62  * M is the mass matrix, S is the viscosity matrix, and H(x) is the nonlinear
63  * hyperelastic operator.
64  *
65  * Class HyperelasticOperator represents the right-hand side of the above
66  * system of ODEs. */
67 class HyperelasticOperator : public TimeDependentOperator
68 {
69 protected:
70  ParFiniteElementSpace &fespace;
71  Array<int> ess_tdof_list;
72 
73  ParBilinearForm M, S;
75  double viscosity;
76  HyperelasticModel *model;
77 
78  HypreParMatrix *Mmat; // Mass matrix from ParallelAssemble()
79  CGSolver M_solver; // Krylov solver for inverting the mass matrix M
80  HypreSmoother M_prec; // Preconditioner for the mass matrix M
81 
82  /** Nonlinear operator defining the reduced backward Euler equation for the
83  velocity. Used in the implementation of method ImplicitSolve. */
84  ReducedSystemOperator *reduced_oper;
85 
86  /// Newton solver for the reduced backward Euler equation
87  NewtonSolver *newton_solver;
88 
89  /// Solver for the Jacobian solve in the Newton method
90  Solver *J_solver;
91  /// Preconditioner for the Jacobian solve in the Newton method
92  Solver *J_prec;
93 
94  mutable Vector z; // auxiliary vector
95 
96  const SparseMatrix *local_grad_H;
97  HypreParMatrix *Jacobian;
98 
99  double saved_gamma; // saved gamma value from implicit setup
100 
101 public:
102  /// Solver type to use in the ImplicitSolve() method, used by SDIRK methods.
103  enum NonlinearSolverType
104  {
105  NEWTON = 0, ///< Use MFEM's plain NewtonSolver
106  KINSOL = 1 ///< Use SUNDIALS' KINSOL (through MFEM's class KINSolver)
107  };
108 
109  HyperelasticOperator(ParFiniteElementSpace &f, Array<int> &ess_bdr,
110  double visc, double mu, double K,
111  NonlinearSolverType nls_type);
112 
113  /// Compute the right-hand side of the ODE system.
114  virtual void Mult(const Vector &vx, Vector &dvx_dt) const;
115 
116  /** Solve the Backward-Euler equation: k = f(x + dt*k, t), for the unknown k.
117  This is the only requirement for high-order SDIRK implicit integration.*/
118  virtual void ImplicitSolve(const double dt, const Vector &x, Vector &k);
119 
120 
121  /// Custom Jacobian system solver for the SUNDIALS time integrators.
122  /** For the ODE system represented by HyperelasticOperator
123 
124  M dv/dt = -(H(x) + S*v)
125  dx/dt = v,
126 
127  this class facilitates the solution of linear systems of the form
128 
129  (M + γS) yv + γJ yx = M bv, J=(dH/dx)(x)
130  - γ yv + yx = bx
131 
132  for given bv, bx, x, and γ = GetTimeStep(). */
133 
134  /** Linear solve applicable to the SUNDIALS format.
135  Solves (Mass - dt J) y = Mass b, where in our case:
136  Mass = | M 0 | J = | -S -grad_H | y = | v_hat | b = | b_v |
137  | 0 I | | I 0 | | x_hat | | b_x |
138  The result replaces the rhs b.
139  We substitute x_hat = b_x + dt v_hat and solve
140  (M + dt S + dt^2 grad_H) v_hat = M b_v - dt grad_H b_x. */
141 
142  /** Setup the linear system. This method is used by the implicit
143  SUNDIALS solvers. */
144  virtual int SUNImplicitSetup(const Vector &y, const Vector &fy,
145  int jok, int *jcur, double gamma);
146 
147  /** Solve the linear system. This method is used by the implicit
148  SUNDIALS solvers. */
149  virtual int SUNImplicitSolve(const Vector &b, Vector &x, double tol);
150 
151  double ElasticEnergy(const ParGridFunction &x) const;
152  double KineticEnergy(const ParGridFunction &v) const;
153  void GetElasticEnergyDensity(const ParGridFunction &x,
154  ParGridFunction &w) const;
155 
156  virtual ~HyperelasticOperator();
157 };
158 
159 /** Nonlinear operator of the form:
160  k --> (M + dt*S)*k + H(x + dt*v + dt^2*k) + S*v,
161  where M and S are given BilinearForms, H is a given NonlinearForm, v and x
162  are given vectors, and dt is a scalar. */
163 class ReducedSystemOperator : public Operator
164 {
165 private:
166  ParBilinearForm *M, *S;
167  ParNonlinearForm *H;
168  mutable HypreParMatrix *Jacobian;
169  double dt;
170  const Vector *v, *x;
171  mutable Vector w, z;
172  const Array<int> &ess_tdof_list;
173 
174 public:
175  ReducedSystemOperator(ParBilinearForm *M_, ParBilinearForm *S_,
176  ParNonlinearForm *H_, const Array<int> &ess_tdof_list);
177 
178  /// Set current dt, v, x values - needed to compute action and Jacobian.
179  void SetParameters(double dt_, const Vector *v_, const Vector *x_);
180 
181  /// Compute y = H(x + dt (v + dt k)) + M k + S (v + dt k).
182  virtual void Mult(const Vector &k, Vector &y) const;
183 
184  /// Compute J = M + dt S + dt^2 grad_H(x + dt (v + dt k)).
185  virtual Operator &GetGradient(const Vector &k) const;
186 
187  virtual ~ReducedSystemOperator();
188 };
189 
190 
191 /** Function representing the elastic energy density for the given hyperelastic
192  model+deformation. Used in HyperelasticOperator::GetElasticEnergyDensity. */
193 class ElasticEnergyCoefficient : public Coefficient
194 {
195 private:
196  HyperelasticModel &model;
197  const ParGridFunction &x;
198  DenseMatrix J;
199 
200 public:
201  ElasticEnergyCoefficient(HyperelasticModel &m, const ParGridFunction &x_)
202  : model(m), x(x_) { }
203  virtual double Eval(ElementTransformation &T, const IntegrationPoint &ip);
204  virtual ~ElasticEnergyCoefficient() { }
205 };
206 
207 void InitialDeformation(const Vector &x, Vector &y);
208 
209 void InitialVelocity(const Vector &x, Vector &v);
210 
211 void visualize(ostream &os, ParMesh *mesh, ParGridFunction *deformed_nodes,
212  ParGridFunction *field, const char *field_name = NULL,
213  bool init_vis = false);
214 
215 
216 int main(int argc, char *argv[])
217 {
218  // 1. Initialize MPI and HYPRE.
219  Mpi::Init(argc, argv);
220  int myid = Mpi::WorldRank();
221  Hypre::Init();
222 
223  // 2. Parse command-line options.
224  const char *mesh_file = "../../data/beam-quad.mesh";
225  int ser_ref_levels = 2;
226  int par_ref_levels = 0;
227  int order = 2;
228  int ode_solver_type = 3;
229  double t_final = 300.0;
230  double dt = 3.0;
231  double visc = 1e-2;
232  double mu = 0.25;
233  double K = 5.0;
234  bool visualization = true;
235  const char *nls = "newton";
236  int vis_steps = 1;
237 
238  // Relative and absolute tolerances for CVODE and ARKODE.
239  const double reltol = 1e-1, abstol = 1e-1;
240  // Since this example uses the loose tolerances defined above, it is
241  // necessary to lower the linear solver tolerance for CVODE which is relative
242  // to the above tolerances.
243  const double cvode_eps_lin = 1e-4;
244  // Similarly, the nonlinear tolerance for ARKODE needs to be tightened.
245  const double arkode_eps_nonlin = 1e-6;
246 
247  OptionsParser args(argc, argv);
248  args.AddOption(&mesh_file, "-m", "--mesh",
249  "Mesh file to use.");
250  args.AddOption(&ser_ref_levels, "-rs", "--refine-serial",
251  "Number of times to refine the mesh uniformly in serial.");
252  args.AddOption(&par_ref_levels, "-rp", "--refine-parallel",
253  "Number of times to refine the mesh uniformly in parallel.");
254  args.AddOption(&order, "-o", "--order",
255  "Order (degree) of the finite elements.");
256  args.AddOption(&ode_solver_type, "-s", "--ode-solver",
257  "ODE solver:\n\t"
258  "1 - Backward Euler,\n\t"
259  "2 - SDIRK2, L-stable\n\t"
260  "3 - SDIRK3, L-stable\n\t"
261  "4 - Implicit Midpoint,\n\t"
262  "5 - SDIRK2, A-stable,\n\t"
263  "6 - SDIRK3, A-stable,\n\t"
264  "7 - Forward Euler,\n\t"
265  "8 - RK2,\n\t"
266  "9 - RK3 SSP,\n\t"
267  "10 - RK4,\n\t"
268  "11 - CVODE implicit BDF, approximate Jacobian,\n\t"
269  "12 - CVODE implicit BDF, specified Jacobian,\n\t"
270  "13 - CVODE implicit ADAMS, approximate Jacobian,\n\t"
271  "14 - CVODE implicit ADAMS, specified Jacobian,\n\t"
272  "15 - ARKODE implicit, approximate Jacobian,\n\t"
273  "16 - ARKODE implicit, specified Jacobian,\n\t"
274  "17 - ARKODE explicit, 4th order.");
275  args.AddOption(&nls, "-nls", "--nonlinear-solver",
276  "Nonlinear systems solver: "
277  "\"newton\" (plain Newton) or \"kinsol\" (KINSOL).");
278  args.AddOption(&t_final, "-tf", "--t-final",
279  "Final time; start time is 0.");
280  args.AddOption(&dt, "-dt", "--time-step",
281  "Time step.");
282  args.AddOption(&visc, "-v", "--viscosity",
283  "Viscosity coefficient.");
284  args.AddOption(&mu, "-mu", "--shear-modulus",
285  "Shear modulus in the Neo-Hookean hyperelastic model.");
286  args.AddOption(&K, "-K", "--bulk-modulus",
287  "Bulk modulus in the Neo-Hookean hyperelastic model.");
288  args.AddOption(&visualization, "-vis", "--visualization", "-no-vis",
289  "--no-visualization",
290  "Enable or disable GLVis visualization.");
291  args.AddOption(&vis_steps, "-vs", "--visualization-steps",
292  "Visualize every n-th timestep.");
293  args.Parse();
294  if (!args.Good())
295  {
296  if (myid == 0)
297  {
298  args.PrintUsage(cout);
299  }
300  return 1;
301  }
302  if (myid == 0)
303  {
304  args.PrintOptions(cout);
305  }
306 
307  // check for valid ODE solver option
308  if (ode_solver_type < 1 || ode_solver_type > 17)
309  {
310  if (myid == 0)
311  {
312  cout << "Unknown ODE solver type: " << ode_solver_type << '\n';
313  }
314  return 1;
315  }
316 
317  // 3. Read the serial mesh from the given mesh file on all processors. We can
318  // handle triangular, quadrilateral, tetrahedral and hexahedral meshes
319  // with the same code.
320  Mesh *mesh = new Mesh(mesh_file, 1, 1);
321  int dim = mesh->Dimension();
322 
323  // 4. Nonlinear solver
324  map<string,HyperelasticOperator::NonlinearSolverType> nls_map;
325  nls_map["newton"] = HyperelasticOperator::NEWTON;
326  nls_map["kinsol"] = HyperelasticOperator::KINSOL;
327  if (nls_map.find(nls) == nls_map.end())
328  {
329  if (myid == 0)
330  {
331  cout << "Unknown type of nonlinear solver: " << nls << endl;
332  }
333  delete mesh;
334  return 4;
335  }
336 
337  // 5. Refine the mesh in serial to increase the resolution. In this example
338  // we do 'ser_ref_levels' of uniform refinement, where 'ser_ref_levels' is
339  // a command-line parameter.
340  for (int lev = 0; lev < ser_ref_levels; lev++)
341  {
342  mesh->UniformRefinement();
343  }
344 
345  // 6. Define a parallel mesh by a partitioning of the serial mesh. Refine
346  // this mesh further in parallel to increase the resolution. Once the
347  // parallel mesh is defined, the serial mesh can be deleted.
348  ParMesh *pmesh = new ParMesh(MPI_COMM_WORLD, *mesh);
349  delete mesh;
350  for (int lev = 0; lev < par_ref_levels; lev++)
351  {
352  pmesh->UniformRefinement();
353  }
354 
355  // 7. Define the parallel vector finite element spaces representing the mesh
356  // deformation x_gf, the velocity v_gf, and the initial configuration,
357  // x_ref. Define also the elastic energy density, w_gf, which is in a
358  // discontinuous higher-order space. Since x and v are integrated in time
359  // as a system, we group them together in block vector vx, on the unique
360  // parallel degrees of freedom, with offsets given by array true_offset.
361  H1_FECollection fe_coll(order, dim);
362  ParFiniteElementSpace fespace(pmesh, &fe_coll, dim);
363 
364  HYPRE_BigInt glob_size = fespace.GlobalTrueVSize();
365  if (myid == 0)
366  {
367  cout << "Number of velocity/deformation unknowns: " << glob_size << endl;
368  }
369  int true_size = fespace.TrueVSize();
370  Array<int> true_offset(3);
371  true_offset[0] = 0;
372  true_offset[1] = true_size;
373  true_offset[2] = 2*true_size;
374 
375  BlockVector vx(true_offset);
376  ParGridFunction v_gf, x_gf;
377  v_gf.MakeTRef(&fespace, vx, true_offset[0]);
378  x_gf.MakeTRef(&fespace, vx, true_offset[1]);
379 
380  ParGridFunction x_ref(&fespace);
381  pmesh->GetNodes(x_ref);
382 
383  L2_FECollection w_fec(order + 1, dim);
384  ParFiniteElementSpace w_fespace(pmesh, &w_fec);
385  ParGridFunction w_gf(&w_fespace);
386 
387  // 8. Set the initial conditions for v_gf, x_gf and vx, and define the
388  // boundary conditions on a beam-like mesh (see description above).
390  v_gf.ProjectCoefficient(velo);
391  v_gf.SetTrueVector();
393  x_gf.ProjectCoefficient(deform);
394  x_gf.SetTrueVector();
395 
396  v_gf.SetFromTrueVector(); x_gf.SetFromTrueVector();
397 
398  Array<int> ess_bdr(fespace.GetMesh()->bdr_attributes.Max());
399  ess_bdr = 0;
400  ess_bdr[0] = 1; // boundary attribute 1 (index 0) is fixed
401 
402  // 9. Initialize the hyperelastic operator, the GLVis visualization and print
403  // the initial energies.
404  HyperelasticOperator oper(fespace, ess_bdr, visc, mu, K, nls_map[nls]);
405 
406  socketstream vis_v, vis_w;
407  if (visualization)
408  {
409  char vishost[] = "localhost";
410  int visport = 19916;
411  vis_v.open(vishost, visport);
412  vis_v.precision(8);
413  visualize(vis_v, pmesh, &x_gf, &v_gf, "Velocity", true);
414  // Make sure all ranks have sent their 'v' solution before initiating
415  // another set of GLVis connections (one from each rank):
416  MPI_Barrier(pmesh->GetComm());
417  vis_w.open(vishost, visport);
418  if (vis_w)
419  {
420  oper.GetElasticEnergyDensity(x_gf, w_gf);
421  vis_w.precision(8);
422  visualize(vis_w, pmesh, &x_gf, &w_gf, "Elastic energy density", true);
423  }
424  }
425 
426  double ee0 = oper.ElasticEnergy(x_gf);
427  double ke0 = oper.KineticEnergy(v_gf);
428  if (myid == 0)
429  {
430  cout << "initial elastic energy (EE) = " << ee0 << endl;
431  cout << "initial kinetic energy (KE) = " << ke0 << endl;
432  cout << "initial total energy (TE) = " << (ee0 + ke0) << endl;
433  }
434 
435  // 10. Define the ODE solver used for time integration. Several implicit
436  // singly diagonal implicit Runge-Kutta (SDIRK) methods, as well as
437  // explicit Runge-Kutta methods are available.
438  double t = 0.0;
439  oper.SetTime(t);
440 
441  ODESolver *ode_solver = NULL;
442  CVODESolver *cvode = NULL;
443  ARKStepSolver *arkode = NULL;
444  switch (ode_solver_type)
445  {
446  // Implicit L-stable methods
447  case 1: ode_solver = new BackwardEulerSolver; break;
448  case 2: ode_solver = new SDIRK23Solver(2); break;
449  case 3: ode_solver = new SDIRK33Solver; break;
450  // Implicit A-stable methods (not L-stable)
451  case 4: ode_solver = new ImplicitMidpointSolver; break;
452  case 5: ode_solver = new SDIRK23Solver; break;
453  case 6: ode_solver = new SDIRK34Solver; break;
454  // Explicit methods
455  case 7: ode_solver = new ForwardEulerSolver; break;
456  case 8: ode_solver = new RK2Solver(0.5); break; // midpoint method
457  case 9: ode_solver = new RK3SSPSolver; break;
458  case 10: ode_solver = new RK4Solver; break;
459  // CVODE BDF
460  case 11:
461  case 12:
462  cvode = new CVODESolver(MPI_COMM_WORLD, CV_BDF);
463  cvode->Init(oper);
464  cvode->SetSStolerances(reltol, abstol);
465  CVodeSetEpsLin(cvode->GetMem(), cvode_eps_lin);
466  cvode->SetMaxStep(dt);
467  if (ode_solver_type == 11)
468  {
469  cvode->UseSundialsLinearSolver();
470  }
471  ode_solver = cvode; break;
472  // CVODE Adams
473  case 13:
474  case 14:
475  cvode = new CVODESolver(MPI_COMM_WORLD, CV_ADAMS);
476  cvode->Init(oper);
477  cvode->SetSStolerances(reltol, abstol);
478  CVodeSetEpsLin(cvode->GetMem(), cvode_eps_lin);
479  cvode->SetMaxStep(dt);
480  if (ode_solver_type == 13)
481  {
482  cvode->UseSundialsLinearSolver();
483  }
484  ode_solver = cvode; break;
485  // ARKStep Implicit methods
486  case 15:
487  case 16:
488  arkode = new ARKStepSolver(MPI_COMM_WORLD, ARKStepSolver::IMPLICIT);
489  arkode->Init(oper);
490  arkode->SetSStolerances(reltol, abstol);
491  ARKStepSetNonlinConvCoef(arkode->GetMem(), arkode_eps_nonlin);
492  arkode->SetMaxStep(dt);
493  if (ode_solver_type == 15)
494  {
495  arkode->UseSundialsLinearSolver();
496  }
497  ode_solver = arkode; break;
498  // ARKStep Explicit methods
499  case 17:
500  arkode = new ARKStepSolver(MPI_COMM_WORLD, ARKStepSolver::EXPLICIT);
501  arkode->Init(oper);
502  arkode->SetSStolerances(reltol, abstol);
503  arkode->SetMaxStep(dt);
504  ode_solver = arkode; break;
505  }
506 
507  // Initialize MFEM integrators, SUNDIALS integrators are initialized above
508  if (ode_solver_type < 11) { ode_solver->Init(oper); }
509 
510  // 11. Perform time-integration
511  // (looping over the time iterations, ti, with a time-step dt).
512  bool last_step = false;
513  for (int ti = 1; !last_step; ti++)
514  {
515  double dt_real = min(dt, t_final - t);
516 
517  ode_solver->Step(vx, t, dt_real);
518 
519  last_step = (t >= t_final - 1e-8*dt);
520 
521  if (last_step || (ti % vis_steps) == 0)
522  {
523  v_gf.SetFromTrueVector(); x_gf.SetFromTrueVector();
524 
525  double ee = oper.ElasticEnergy(x_gf);
526  double ke = oper.KineticEnergy(v_gf);
527 
528  if (myid == 0)
529  {
530  cout << "step " << ti << ", t = " << t << ", EE = " << ee
531  << ", KE = " << ke << ", ΔTE = " << (ee+ke)-(ee0+ke0) << endl;
532 
533  if (cvode) { cvode->PrintInfo(); }
534  else if (arkode) { arkode->PrintInfo(); }
535  }
536 
537  if (visualization)
538  {
539  visualize(vis_v, pmesh, &x_gf, &v_gf);
540  if (vis_w)
541  {
542  oper.GetElasticEnergyDensity(x_gf, w_gf);
543  visualize(vis_w, pmesh, &x_gf, &w_gf);
544  }
545  }
546  }
547  }
548 
549  // 12. Save the displaced mesh, the velocity and elastic energy.
550  {
551  v_gf.SetFromTrueVector(); x_gf.SetFromTrueVector();
552  GridFunction *nodes = &x_gf;
553  int owns_nodes = 0;
554  pmesh->SwapNodes(nodes, owns_nodes);
555 
556  ostringstream mesh_name, velo_name, ee_name;
557  mesh_name << "deformed." << setfill('0') << setw(6) << myid;
558  velo_name << "velocity." << setfill('0') << setw(6) << myid;
559  ee_name << "elastic_energy." << setfill('0') << setw(6) << myid;
560 
561  ofstream mesh_ofs(mesh_name.str().c_str());
562  mesh_ofs.precision(8);
563  pmesh->Print(mesh_ofs);
564  pmesh->SwapNodes(nodes, owns_nodes);
565  ofstream velo_ofs(velo_name.str().c_str());
566  velo_ofs.precision(8);
567  v_gf.Save(velo_ofs);
568  ofstream ee_ofs(ee_name.str().c_str());
569  ee_ofs.precision(8);
570  oper.GetElasticEnergyDensity(x_gf, w_gf);
571  w_gf.Save(ee_ofs);
572  }
573 
574  // 13. Free the used memory.
575  delete ode_solver;
576  delete pmesh;
577 
578  return 0;
579 }
580 
581 void visualize(ostream &os, ParMesh *mesh, ParGridFunction *deformed_nodes,
582  ParGridFunction *field, const char *field_name, bool init_vis)
583 {
584  if (!os)
585  {
586  return;
587  }
588 
589  GridFunction *nodes = deformed_nodes;
590  int owns_nodes = 0;
591 
592  mesh->SwapNodes(nodes, owns_nodes);
593 
594  os << "parallel " << mesh->GetNRanks() << " " << mesh->GetMyRank() << "\n";
595  os << "solution\n" << *mesh << *field;
596 
597  mesh->SwapNodes(nodes, owns_nodes);
598 
599  if (init_vis)
600  {
601  os << "window_size 800 800\n";
602  os << "window_title '" << field_name << "'\n";
603  if (mesh->SpaceDimension() == 2)
604  {
605  os << "view 0 0\n"; // view from top
606  os << "keys jl\n"; // turn off perspective and light
607  }
608  os << "keys cm\n"; // show colorbar and mesh
609  os << "autoscale value\n"; // update value-range; keep mesh-extents fixed
610  os << "pause\n";
611  }
612  os << flush;
613 }
614 
615 
616 ReducedSystemOperator::ReducedSystemOperator(
618  const Array<int> &ess_tdof_list_)
619  : Operator(M_->ParFESpace()->TrueVSize()), M(M_), S(S_), H(H_),
620  Jacobian(NULL), dt(0.0), v(NULL), x(NULL), w(height), z(height),
621  ess_tdof_list(ess_tdof_list_)
622 { }
623 
624 void ReducedSystemOperator::SetParameters(double dt_, const Vector *v_,
625  const Vector *x_)
626 {
627  dt = dt_; v = v_; x = x_;
628 }
629 
630 void ReducedSystemOperator::Mult(const Vector &k, Vector &y) const
631 {
632  // compute: y = H(x + dt*(v + dt*k)) + M*k + S*(v + dt*k)
633  add(*v, dt, k, w);
634  add(*x, dt, w, z);
635  H->Mult(z, y);
636  M->TrueAddMult(k, y);
637  S->TrueAddMult(w, y);
638  y.SetSubVector(ess_tdof_list, 0.0);
639 }
640 
641 Operator &ReducedSystemOperator::GetGradient(const Vector &k) const
642 {
643  delete Jacobian;
644  SparseMatrix *localJ = Add(1.0, M->SpMat(), dt, S->SpMat());
645  add(*v, dt, k, w);
646  add(*x, dt, w, z);
647  localJ->Add(dt*dt, H->GetLocalGradient(z));
648  Jacobian = M->ParallelAssemble(localJ);
649  delete localJ;
650  HypreParMatrix *Je = Jacobian->EliminateRowsCols(ess_tdof_list);
651  delete Je;
652  return *Jacobian;
653 }
654 
655 ReducedSystemOperator::~ReducedSystemOperator()
656 {
657  delete Jacobian;
658 }
659 
660 
661 HyperelasticOperator::HyperelasticOperator(ParFiniteElementSpace &f,
662  Array<int> &ess_bdr, double visc,
663  double mu, double K,
664  NonlinearSolverType nls_type)
665  : TimeDependentOperator(2*f.TrueVSize(), 0.0), fespace(f),
666  M(&fespace), S(&fespace), H(&fespace),
667  viscosity(visc), M_solver(f.GetComm()), z(height/2),
668  local_grad_H(NULL), Jacobian(NULL)
669 {
670  const double rel_tol = 1e-8;
671  const int skip_zero_entries = 0;
672 
673  const double ref_density = 1.0; // density in the reference configuration
674  ConstantCoefficient rho0(ref_density);
675  M.AddDomainIntegrator(new VectorMassIntegrator(rho0));
676  M.Assemble(skip_zero_entries);
677  M.Finalize(skip_zero_entries);
678  Mmat = M.ParallelAssemble();
679  fespace.GetEssentialTrueDofs(ess_bdr, ess_tdof_list);
680  HypreParMatrix *Me = Mmat->EliminateRowsCols(ess_tdof_list);
681  delete Me;
682 
683  M_solver.iterative_mode = false;
684  M_solver.SetRelTol(rel_tol);
685  M_solver.SetAbsTol(0.0);
686  M_solver.SetMaxIter(30);
687  M_solver.SetPrintLevel(0);
688  M_prec.SetType(HypreSmoother::Jacobi);
689  M_solver.SetPreconditioner(M_prec);
690  M_solver.SetOperator(*Mmat);
691 
692  model = new NeoHookeanModel(mu, K);
693  H.AddDomainIntegrator(new HyperelasticNLFIntegrator(model));
694  H.SetEssentialTrueDofs(ess_tdof_list);
695 
696  ConstantCoefficient visc_coeff(viscosity);
697  S.AddDomainIntegrator(new VectorDiffusionIntegrator(visc_coeff));
698  S.Assemble(skip_zero_entries);
699  S.Finalize(skip_zero_entries);
700 
701  reduced_oper = new ReducedSystemOperator(&M, &S, &H, ess_tdof_list);
702 
703  HypreSmoother *J_hypreSmoother = new HypreSmoother;
704  J_hypreSmoother->SetType(HypreSmoother::l1Jacobi);
705  J_hypreSmoother->SetPositiveDiagonal(true);
706  J_prec = J_hypreSmoother;
707 
708  MINRESSolver *J_minres = new MINRESSolver(f.GetComm());
709  J_minres->SetRelTol(rel_tol);
710  J_minres->SetAbsTol(0.0);
711  J_minres->SetMaxIter(300);
712  J_minres->SetPrintLevel(-1);
713  J_minres->SetPreconditioner(*J_prec);
714  J_solver = J_minres;
715 
716  if (nls_type == KINSOL)
717  {
718  KINSolver *kinsolver = new KINSolver(f.GetComm(), KIN_LINESEARCH, true);
719  kinsolver->SetJFNK(true);
720  kinsolver->SetLSMaxIter(100);
721  newton_solver = kinsolver;
722  newton_solver->SetOperator(*reduced_oper);
723  newton_solver->SetMaxIter(200);
724  newton_solver->SetRelTol(rel_tol);
725  newton_solver->SetPrintLevel(1);
726  kinsolver->SetMaxSetupCalls(4);
727  }
728  else
729  {
730  newton_solver = new NewtonSolver(f.GetComm());
731  newton_solver->SetOperator(*reduced_oper);
732  newton_solver->SetMaxIter(10);
733  newton_solver->SetRelTol(rel_tol);
734  newton_solver->SetPrintLevel(-1);
735  }
736  newton_solver->SetSolver(*J_solver);
737  newton_solver->iterative_mode = false;
738 }
739 
740 void HyperelasticOperator::Mult(const Vector &vx, Vector &dvx_dt) const
741 {
742  // Create views to the sub-vectors v, x of vx, and dv_dt, dx_dt of dvx_dt
743  int sc = height/2;
744  Vector v(vx.GetData() + 0, sc);
745  Vector x(vx.GetData() + sc, sc);
746  Vector dv_dt(dvx_dt.GetData() + 0, sc);
747  Vector dx_dt(dvx_dt.GetData() + sc, sc);
748 
749  H.Mult(x, z);
750  if (viscosity != 0.0)
751  {
752  S.TrueAddMult(v, z);
753  z.SetSubVector(ess_tdof_list, 0.0);
754  }
755  z.Neg(); // z = -z
756  M_solver.Mult(z, dv_dt);
757 
758  dx_dt = v;
759 }
760 
761 void HyperelasticOperator::ImplicitSolve(const double dt,
762  const Vector &vx, Vector &dvx_dt)
763 {
764  int sc = height/2;
765  Vector v(vx.GetData() + 0, sc);
766  Vector x(vx.GetData() + sc, sc);
767  Vector dv_dt(dvx_dt.GetData() + 0, sc);
768  Vector dx_dt(dvx_dt.GetData() + sc, sc);
769 
770  // By eliminating kx from the coupled system:
771  // kv = -M^{-1}*[H(x + dt*kx) + S*(v + dt*kv)]
772  // kx = v + dt*kv
773  // we reduce it to a nonlinear equation for kv, represented by the
774  // reduced_oper. This equation is solved with the newton_solver
775  // object (using J_solver and J_prec internally).
776  reduced_oper->SetParameters(dt, &v, &x);
777  Vector zero; // empty vector is interpreted as zero r.h.s. by NewtonSolver
778  newton_solver->Mult(zero, dv_dt);
779  MFEM_VERIFY(newton_solver->GetConverged(),
780  "Nonlinear solver did not converge.");
781 #ifdef MFEM_DEBUG
782  if (fespace.GetMyRank() == 0)
783  {
784  cout << " num nonlin sol iters = " << newton_solver->GetNumIterations()
785  << ", final norm = " << newton_solver->GetFinalNorm() << '\n';
786  }
787 #endif
788  add(v, dt, dv_dt, dx_dt);
789 }
790 
791 int HyperelasticOperator::SUNImplicitSetup(const Vector &y,
792  const Vector &fy, int jok, int *jcur,
793  double gamma)
794 {
795  int sc = y.Size() / 2;
796  const Vector x(y.GetData() + sc, sc);
797 
798  // J = M + dt*(S + dt*grad(H))
799  if (Jacobian) { delete Jacobian; }
800  SparseMatrix *localJ = Add(1.0, M.SpMat(), gamma, S.SpMat());
801  local_grad_H = &H.GetLocalGradient(x);
802  localJ->Add(gamma*gamma, *local_grad_H);
803  Jacobian = M.ParallelAssemble(localJ);
804  delete localJ;
805  HypreParMatrix *Je = Jacobian->EliminateRowsCols(ess_tdof_list);
806  delete Je;
807 
808  // Set Jacobian solve operator
809  J_solver->SetOperator(*Jacobian);
810 
811  // Indicate that the Jacobian was updated
812  *jcur = 1;
813 
814  // Save gamma for use in solve
815  saved_gamma = gamma;
816 
817  // Return success
818  return 0;
819 }
820 
821 int HyperelasticOperator::SUNImplicitSolve(const Vector &b, Vector &x,
822  double tol)
823 {
824  int sc = b.Size() / 2;
825  ParFiniteElementSpace *fes = H.ParFESpace();
826  Vector b_v(b.GetData() + 0, sc);
827  Vector b_x(b.GetData() + sc, sc);
828  Vector x_v(x.GetData() + 0, sc);
829  Vector x_x(x.GetData() + sc, sc);
830  Vector rhs(sc);
831 
832  // We can assume that b_v and b_x have zeros at essential tdofs.
833 
834  // rhs = M b_v - dt*grad(H) b_x
835  ParGridFunction lb_x(fes), lrhs(fes);
836  lb_x.Distribute(b_x);
837  local_grad_H->Mult(lb_x, lrhs);
838  lrhs.ParallelAssemble(rhs);
839  rhs *= -saved_gamma;
840  M.TrueAddMult(b_v, rhs);
841  rhs.SetSubVector(ess_tdof_list, 0.0);
842 
843  J_solver->iterative_mode = false;
844  J_solver->Mult(rhs, x_v);
845 
846  add(b_x, saved_gamma, x_v, x_x);
847 
848  return 0;
849 }
850 
851 double HyperelasticOperator::ElasticEnergy(const ParGridFunction &x) const
852 {
853  return H.GetEnergy(x);
854 }
855 
856 double HyperelasticOperator::KineticEnergy(const ParGridFunction &v) const
857 {
858  double loc_energy = 0.5*M.InnerProduct(v, v);
859  double energy;
860  MPI_Allreduce(&loc_energy, &energy, 1, MPI_DOUBLE, MPI_SUM,
861  fespace.GetComm());
862  return energy;
863 }
864 
865 void HyperelasticOperator::GetElasticEnergyDensity(
866  const ParGridFunction &x, ParGridFunction &w) const
867 {
868  ElasticEnergyCoefficient w_coeff(*model, x);
869  w.ProjectCoefficient(w_coeff);
870 }
871 
872 HyperelasticOperator::~HyperelasticOperator()
873 {
874  delete Jacobian;
875  delete newton_solver;
876  delete J_solver;
877  delete J_prec;
878  delete reduced_oper;
879  delete model;
880  delete Mmat;
881 }
882 
883 
885  const IntegrationPoint &ip)
886 {
887  model.SetTransformation(T);
888  x.GetVectorGradient(T, J);
889  // return model.EvalW(J); // in reference configuration
890  return model.EvalW(J)/J.Det(); // in deformed configuration
891 }
892 
893 
894 void InitialDeformation(const Vector &x, Vector &y)
895 {
896  // set the initial configuration to be the same as the reference, stress
897  // free, configuration
898  y = x;
899 }
900 
901 void InitialVelocity(const Vector &x, Vector &v)
902 {
903  const int dim = x.Size();
904  const double s = 0.1/64.;
905 
906  v = 0.0;
907  v(dim-1) = s*x(0)*x(0)*(8.0-x(0));
908  v(0) = -s*x(0)*x(0);
909 }
void Init(TimeDependentOperator &f_)
Initialize CVODE: calls CVodeCreate() to create the CVODE memory and set some defaults.
Definition: sundials.cpp:532
void EliminateRowsCols(const Array< int > &rows_cols, const HypreParVector &X, HypreParVector &B)
Definition: hypre.cpp:2240
void SetSubVector(const Array< int > &dofs, const double value)
Set the entries listed in dofs to the given value.
Definition: vector.cpp:560
double Eval(ElementTransformation &T, const IntegrationPoint &ip, double t)
Evaluate the coefficient in the element described by T at the point ip at time t. ...
Definition: coefficient.hpp:66
void InitialDeformation(const Vector &x, Vector &y)
Definition: ex10.cpp:592
Conjugate gradient method.
Definition: solvers.hpp:465
Class for grid function - Vector with associated FE space.
Definition: gridfunc.hpp:30
void SetSStolerances(double reltol, double abstol)
Set the scalar relative and scalar absolute tolerances.
Definition: sundials.cpp:698
A class to handle Vectors in a block fashion.
Definition: blockvector.hpp:30
void SetFromTrueVector()
Shortcut for calling SetFromTrueDofs() with GetTrueVector() as argument.
Definition: gridfunc.hpp:150
A coefficient that is constant across space and time.
Definition: coefficient.hpp:78
int TrueVSize() const
Obsolete, kept for backward compatibility.
Definition: pfespace.hpp:434
Base abstract class for first order time dependent operators.
Definition: operator.hpp:285
void SwapNodes(GridFunction *&nodes, int &own_nodes_)
Definition: mesh.cpp:7884
void Mult(const Table &A, const Table &B, Table &C)
C = A * B (as boolean matrices)
Definition: table.cpp:472
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]...
HYPRE_BigInt GlobalTrueVSize() const
Definition: pfespace.hpp:285
void * GetMem() const
Access the SUNDIALS memory structure.
Definition: sundials.hpp:240
Data type dense matrix using column-major storage.
Definition: densemat.hpp:23
int Size() const
Returns the size of the vector.
Definition: vector.hpp:199
Parallel non-linear operator on the true dofs.
Abstract class for solving systems of ODEs: dx/dt = f(x,t)
Definition: ode.hpp:22
virtual void Save(std::ostream &out) const
Definition: pgridfunc.cpp:873
void SetMaxStep(double dt_max)
Set the maximum time step.
Definition: sundials.cpp:1540
Abstract parallel finite element space.
Definition: pfespace.hpp:28
virtual void ProjectCoefficient(Coefficient &coeff)
Project coeff Coefficient to this GridFunction. The projection computation depends on the choice of t...
Definition: pgridfunc.cpp:525
MINRES method.
Definition: solvers.hpp:575
Backward Euler ODE solver. L-stable.
Definition: ode.hpp:391
double * GetData() const
Return a pointer to the beginning of the Vector data.
Definition: vector.hpp:208
void add(const Vector &v1, const Vector &v2, Vector &v)
Definition: vector.cpp:300
void SetMaxSetupCalls(int max_calls)
Set maximum number of nonlinear iterations without a Jacobian update.
Definition: sundials.cpp:1961
int GetNRanks() const
Definition: pmesh.hpp:289
void InitialVelocity(const Vector &x, Vector &v)
Definition: ex10.cpp:599
void SetPositiveDiagonal(bool pos=true)
After computing l1-norms, replace them with their absolute values.
Definition: hypre.hpp:1002
Interface to ARKode&#39;s ARKStep module – additive Runge-Kutta methods.
Definition: sundials.hpp:539
void Add(const DenseMatrix &A, const DenseMatrix &B, double alpha, DenseMatrix &C)
C = A + alpha*B.
Definition: densemat.cpp:1916
void SetTrueVector()
Shortcut for calling GetTrueDofs() with GetTrueVector() as argument.
Definition: gridfunc.hpp:144
virtual void SetPreconditioner(Solver &pr)
This should be called before SetOperator.
Definition: solvers.hpp:588
virtual void SetPrintLevel(int print_lvl)
Legacy method to set the level of verbosity of the solver output.
Definition: solvers.cpp:71
MPI_Comm GetComm() const
Definition: pfespace.hpp:273
void Parse()
Parse the command-line options. Note that this function expects all the options provided through the ...
Definition: optparser.cpp:151
Data type sparse matrix.
Definition: sparsemat.hpp:46
constexpr char vishost[]
Mesh * GetMesh() const
Returns the mesh.
Definition: fespace.hpp:433
Interface to the CVODE library – linear multi-step methods.
Definition: sundials.hpp:252
double b
Definition: lissajous.cpp:42
Interface to the KINSOL library – nonlinear solver methods.
Definition: sundials.hpp:713
void UniformRefinement(int i, const DSTable &, int *, int *, int *)
Definition: mesh.cpp:9737
constexpr int visport
void MakeTRef(FiniteElementSpace *f, double *tv)
Associate a new FiniteElementSpace and new true-dof data with the GridFunction.
Definition: gridfunc.cpp:219
void SetMaxIter(int max_it)
Definition: solvers.hpp:200
T Max() const
Find the maximal element in the array, using the comparison operator &lt; for class T.
Definition: array.cpp:68
void SetMaxStep(double dt_max)
Set the maximum time step.
Definition: sundials.cpp:716
void visualize(ostream &os, Mesh *mesh, GridFunction *deformed_nodes, GridFunction *field, const char *field_name=NULL, bool init_vis=false)
Definition: ex10.cpp:379
Newton&#39;s method for solving F(x)=b for a given operator F.
Definition: solvers.hpp:613
void SetJFNK(bool use_jfnk)
Set the Jacobian Free Newton Krylov flag. The default is false.
Definition: sundials.hpp:826
Parallel smoothers in hypre.
Definition: hypre.hpp:896
int Dimension() const
Definition: mesh.hpp:999
void PrintUsage(std::ostream &out) const
Print the usage message.
Definition: optparser.cpp:454
void Add(const int i, const int j, const double val)
Definition: sparsemat.cpp:2649
A general vector function coefficient.
int SpaceDimension() const
Definition: mesh.hpp:1000
The classical explicit forth-order Runge-Kutta method, RK4.
Definition: ode.hpp:162
void SetAbsTol(double atol)
Definition: solvers.hpp:199
Array< int > bdr_attributes
A list of all unique boundary attributes used by the Mesh.
Definition: mesh.hpp:270
int GetMyRank() const
Definition: pmesh.hpp:290
void SetRelTol(double rtol)
Definition: solvers.hpp:198
MPI_Comm GetComm() const
Definition: pmesh.hpp:288
virtual void SetOperator(const Operator &op)
Set the nonlinear Operator of the system and initialize KINSOL.
Definition: sundials.cpp:1776
Base class Coefficients that optionally depend on space and time. These are used by the BilinearFormI...
Definition: coefficient.hpp:39
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 &#39;var&#39; to receive the value. Enable/disable tags are used to set the bool...
Definition: optparser.hpp:82
Third-order, strong stability preserving (SSP) Runge-Kutta method.
Definition: ode.hpp:149
HYPRE_Int HYPRE_BigInt
void SetLSMaxIter(int m)
Set the maximum number of linear solver iterations.
Definition: sundials.hpp:830
void GetVectorGradient(ElementTransformation &tr, DenseMatrix &grad) const
Definition: gridfunc.cpp:1738
Implicit midpoint method. A-stable, not L-stable.
Definition: ode.hpp:404
Class for integration point with weight.
Definition: intrules.hpp:25
void PrintInfo() const
Print various ARKStep statistics.
Definition: sundials.cpp:1576
double mu
Definition: ex25.cpp:139
int dim
Definition: ex24.cpp:53
void PrintOptions(std::ostream &out) const
Print the options.
Definition: optparser.cpp:324
Class for parallel bilinear form.
Abstract class for hyperelastic models.
int open(const char hostname[], int port)
Open the socket stream on &#39;port&#39; at &#39;hostname&#39;.
RefCoord t[3]
Vector data type.
Definition: vector.hpp:60
void GetNodes(Vector &node_coord) const
Definition: mesh.cpp:7841
Arbitrary order H1-conforming (continuous) finite elements.
Definition: fe_coll.hpp:216
void PrintInfo() const
Print various CVODE statistics.
Definition: sundials.cpp:742
RefCoord s[3]
void Print(std::ostream &out=mfem::out) const override
Definition: pmesh.cpp:4684
Base class for solvers.
Definition: operator.hpp:651
Class for parallel grid function.
Definition: pgridfunc.hpp:32
The classical forward Euler method.
Definition: ode.hpp:116
Abstract operator.
Definition: operator.hpp:24
Wrapper for hypre&#39;s ParCSR matrix class.
Definition: hypre.hpp:337
void Init(TimeDependentOperator &f_)
Initialize ARKode: calls ARKStepCreate() to create the ARKStep memory and set some defaults...
Definition: sundials.cpp:1297
Class for parallel meshes.
Definition: pmesh.hpp:32
void SetSStolerances(double reltol, double abstol)
Set the scalar relative and scalar absolute tolerances.
Definition: sundials.cpp:1534
void UseSundialsLinearSolver()
Attach a SUNDIALS GMRES linear solver to ARKode.
Definition: sundials.cpp:1462
void SetType(HypreSmoother::Type type, int relax_times=1)
Set the relaxation type and number of sweeps.
Definition: hypre.cpp:3224
virtual void Init(TimeDependentOperator &f_)
Associate a TimeDependentOperator with the ODE solver.
Definition: ode.cpp:18
int main()
void UseSundialsLinearSolver()
Attach SUNDIALS GMRES linear solver to CVODE.
Definition: sundials.cpp:678
virtual void SetOperator(const Operator &op)
Also calls SetOperator for the preconditioner if there is one.
Definition: solvers.cpp:1793
Arbitrary order &quot;L2-conforming&quot; discontinuous finite elements.
Definition: fe_coll.hpp:284
double f(const Vector &p)
bool Good() const
Return true if the command line options were parsed successfully.
Definition: optparser.hpp:150