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 // PETSc Modification
3 //
4 // Compile with: make ex10p
5 //
6 // Sample runs:
7 // mpirun -np 4 ex10p -m ../../data/beam-quad.mesh --petscopts rc_ex10p -s 3 -rs 2 -dt 3
8 // mpirun -np 4 ex10p -m ../../data/beam-quad-amr.mesh --petscopts rc_ex10p -s 3 -rs 2 -dt 3
9 //
10 // Description: This examples solves a time dependent nonlinear elasticity
11 // problem of the form dv/dt = H(x) + S v, dx/dt = v, where H is a
12 // hyperelastic model and S is a viscosity operator of Laplacian
13 // type. The geometry of the domain is assumed to be as follows:
14 //
15 // +---------------------+
16 // boundary --->| |
17 // attribute 1 | |
18 // (fixed) +---------------------+
19 //
20 // The example demonstrates the use of nonlinear operators (the
21 // class HyperelasticOperator defining H(x)), as well as their
22 // implicit time integration using a Newton method for solving an
23 // associated reduced backward-Euler type nonlinear equation
24 // (class ReducedSystemOperator). Each Newton step requires the
25 // inversion of a Jacobian matrix, which is done through a
26 // (preconditioned) inner solver. Note that implementing the
27 // method HyperelasticOperator::ImplicitSolve is the only
28 // requirement for high-order implicit (SDIRK) time integration.
29 // If using PETSc to solve the nonlinear problem, use the option
30 // files provided (see rc_ex10p, rc_ex10p_mf, rc_ex10p_mfop) that
31 // customize the Newton-Krylov method.
32 // When option --jfnk is used, PETSc will use a Jacobian-free
33 // Newton-Krylov method, using a user-defined preconditioner
34 // constructed with the PetscPreconditionerFactory class.
35 //
36 // We recommend viewing examples 2 and 9 before viewing this
37 // example.
38 
39 #include "mfem.hpp"
40 #include <memory>
41 #include <iostream>
42 #include <fstream>
43 
44 #ifndef MFEM_USE_PETSC
45 #error This example requires that MFEM is built with MFEM_USE_PETSC=YES
46 #endif
47 
48 using namespace std;
49 using namespace mfem;
50 
51 class ReducedSystemOperator;
52 
53 /** After spatial discretization, the hyperelastic model can be written as a
54  * system of ODEs:
55  * dv/dt = -M^{-1}*(H(x) + S*v)
56  * dx/dt = v,
57  * where x is the vector representing the deformation, v is the velocity field,
58  * M is the mass matrix, S is the viscosity matrix, and H(x) is the nonlinear
59  * hyperelastic operator.
60  *
61  * Class HyperelasticOperator represents the right-hand side of the above
62  * system of ODEs. */
63 class HyperelasticOperator : public TimeDependentOperator
64 {
65 protected:
66  ParFiniteElementSpace &fespace;
67  Array<int> ess_tdof_list;
68 
69  ParBilinearForm M, S;
71  double viscosity;
72  HyperelasticModel *model;
73 
74  HypreParMatrix *Mmat; // Mass matrix from ParallelAssemble()
75  CGSolver M_solver; // Krylov solver for inverting the mass matrix M
76  HypreSmoother M_prec; // Preconditioner for the mass matrix M
77 
78  /** Nonlinear operator defining the reduced backward Euler equation for the
79  velocity. Used in the implementation of method ImplicitSolve. */
80  ReducedSystemOperator *reduced_oper;
81 
82  /// Newton solver for the reduced backward Euler equation
83  NewtonSolver newton_solver;
84 
85  /// Newton solver for the reduced backward Euler equation (PETSc SNES)
86  PetscNonlinearSolver* pnewton_solver;
87 
88  /// Solver for the Jacobian solve in the Newton method
89  Solver *J_solver;
90  /// Preconditioner for the Jacobian solve in the Newton method
91  Solver *J_prec;
92  /// Preconditioner factory for JFNK
93  PetscPreconditionerFactory *J_factory;
94 
95  mutable Vector z; // auxiliary vector
96 
97 public:
98  HyperelasticOperator(ParFiniteElementSpace &f, Array<int> &ess_bdr,
99  double visc, double mu, double K,
100  bool use_petsc, bool petsc_use_jfnk);
101 
102  /// Compute the right-hand side of the ODE system.
103  virtual void Mult(const Vector &vx, Vector &dvx_dt) const;
104  /** Solve the Backward-Euler equation: k = f(x + dt*k, t), for the unknown k.
105  This is the only requirement for high-order SDIRK implicit integration.*/
106  virtual void ImplicitSolve(const double dt, const Vector &x, Vector &k);
107 
108  double ElasticEnergy(const ParGridFunction &x) const;
109  double KineticEnergy(const ParGridFunction &v) const;
110  void GetElasticEnergyDensity(const ParGridFunction &x,
111  ParGridFunction &w) const;
112 
113  virtual ~HyperelasticOperator();
114 };
115 
116 /** Nonlinear operator of the form:
117  k --> (M + dt*S)*k + H(x + dt*v + dt^2*k) + S*v,
118  where M and S are given BilinearForms, H is a given NonlinearForm, v and x
119  are given vectors, and dt is a scalar. */
120 class ReducedSystemOperator : public Operator
121 {
122 private:
123  ParBilinearForm *M, *S;
124  ParNonlinearForm *H;
125  mutable HypreParMatrix *Jacobian;
126  double dt;
127  const Vector *v, *x;
128  mutable Vector w, z;
129  const Array<int> &ess_tdof_list;
130 
131 public:
132  ReducedSystemOperator(ParBilinearForm *M_, ParBilinearForm *S_,
133  ParNonlinearForm *H_, const Array<int> &ess_tdof_list);
134 
135  /// Set current dt, v, x values - needed to compute action and Jacobian.
136  void SetParameters(double dt_, const Vector *v_, const Vector *x_);
137 
138  /// Compute y = H(x + dt (v + dt k)) + M k + S (v + dt k).
139  virtual void Mult(const Vector &k, Vector &y) const;
140 
141  /// Compute J = M + dt S + dt^2 grad_H(x + dt (v + dt k)).
142  virtual Operator &GetGradient(const Vector &k) const;
143 
144  virtual ~ReducedSystemOperator();
145 
146 };
147 
148 /** Auxiliary class to provide preconditioners for matrix-free methods */
149 class PreconditionerFactory : public PetscPreconditionerFactory
150 {
151 private:
152  // const ReducedSystemOperator& op; // unused for now (generates warning)
153 
154 public:
155  PreconditionerFactory(const ReducedSystemOperator& op_, const string& name_)
156  : PetscPreconditionerFactory(name_) /* , op(op_) */ {}
157  virtual mfem::Solver* NewPreconditioner(const mfem::OperatorHandle&);
158  virtual ~PreconditionerFactory() {}
159 };
160 
161 /** Function representing the elastic energy density for the given hyperelastic
162  model+deformation. Used in HyperelasticOperator::GetElasticEnergyDensity. */
163 class ElasticEnergyCoefficient : public Coefficient
164 {
165 private:
166  HyperelasticModel &model;
167  const ParGridFunction &x;
168  DenseMatrix J;
169 
170 public:
171  ElasticEnergyCoefficient(HyperelasticModel &m, const ParGridFunction &x_)
172  : model(m), x(x_) { }
173  virtual double Eval(ElementTransformation &T, const IntegrationPoint &ip);
174  virtual ~ElasticEnergyCoefficient() { }
175 };
176 
177 void InitialDeformation(const Vector &x, Vector &y);
178 
179 void InitialVelocity(const Vector &x, Vector &v);
180 
181 void visualize(ostream &os, ParMesh *mesh, ParGridFunction *deformed_nodes,
182  ParGridFunction *field, const char *field_name = NULL,
183  bool init_vis = false);
184 
185 
186 int main(int argc, char *argv[])
187 {
188  // 1. Initialize MPI and HYPRE.
189  Mpi::Init(argc, argv);
190  int num_procs = Mpi::WorldSize();
191  int myid = Mpi::WorldRank();
192  Hypre::Init();
193 
194  // 2. Parse command-line options.
195  const char *mesh_file = "../../data/beam-quad.mesh";
196  int ser_ref_levels = 2;
197  int par_ref_levels = 0;
198  int order = 2;
199  int ode_solver_type = 3;
200  double t_final = 300.0;
201  double dt = 3.0;
202  double visc = 1e-2;
203  double mu = 0.25;
204  double K = 5.0;
205  bool visualization = true;
206  int vis_steps = 1;
207  bool use_petsc = true;
208  const char *petscrc_file = "";
209  bool petsc_use_jfnk = false;
210 
211  OptionsParser args(argc, argv);
212  args.AddOption(&mesh_file, "-m", "--mesh",
213  "Mesh file to use.");
214  args.AddOption(&ser_ref_levels, "-rs", "--refine-serial",
215  "Number of times to refine the mesh uniformly in serial.");
216  args.AddOption(&par_ref_levels, "-rp", "--refine-parallel",
217  "Number of times to refine the mesh uniformly in parallel.");
218  args.AddOption(&order, "-o", "--order",
219  "Order (degree) of the finite elements.");
220  args.AddOption(&ode_solver_type, "-s", "--ode-solver",
221  "ODE solver: 1 - Backward Euler, 2 - SDIRK2, 3 - SDIRK3,\n\t"
222  " 11 - Forward Euler, 12 - RK2,\n\t"
223  " 13 - RK3 SSP, 14 - RK4.");
224  args.AddOption(&t_final, "-tf", "--t-final",
225  "Final time; start time is 0.");
226  args.AddOption(&dt, "-dt", "--time-step",
227  "Time step.");
228  args.AddOption(&visc, "-v", "--viscosity",
229  "Viscosity coefficient.");
230  args.AddOption(&mu, "-mu", "--shear-modulus",
231  "Shear modulus in the Neo-Hookean hyperelastic model.");
232  args.AddOption(&K, "-K", "--bulk-modulus",
233  "Bulk modulus in the Neo-Hookean hyperelastic model.");
234  args.AddOption(&visualization, "-vis", "--visualization", "-no-vis",
235  "--no-visualization",
236  "Enable or disable GLVis visualization.");
237  args.AddOption(&vis_steps, "-vs", "--visualization-steps",
238  "Visualize every n-th timestep.");
239  args.AddOption(&use_petsc, "-usepetsc", "--usepetsc", "-no-petsc",
240  "--no-petsc",
241  "Use or not PETSc to solve the nonlinear system.");
242  args.AddOption(&petscrc_file, "-petscopts", "--petscopts",
243  "PetscOptions file to use.");
244  args.AddOption(&petsc_use_jfnk, "-jfnk", "--jfnk", "-no-jfnk",
245  "--no-jfnk",
246  "Use JFNK with user-defined preconditioner factory.");
247  args.Parse();
248  if (!args.Good())
249  {
250  if (myid == 0)
251  {
252  args.PrintUsage(cout);
253  }
254  return 1;
255  }
256  if (myid == 0)
257  {
258  args.PrintOptions(cout);
259  }
260 
261  // 2b. We initialize PETSc
262  if (use_petsc)
263  {
264  MFEMInitializePetsc(NULL,NULL,petscrc_file,NULL);
265  }
266 
267  // 3. Read the serial mesh from the given mesh file on all processors. We can
268  // handle triangular, quadrilateral, tetrahedral and hexahedral meshes
269  // with the same code.
270  Mesh *mesh = new Mesh(mesh_file, 1, 1);
271  int dim = mesh->Dimension();
272 
273  // 4. Define the ODE solver used for time integration. Several implicit
274  // singly diagonal implicit Runge-Kutta (SDIRK) methods, as well as
275  // explicit Runge-Kutta methods are available.
276  ODESolver *ode_solver;
277  switch (ode_solver_type)
278  {
279  // Implicit L-stable methods
280  case 1: ode_solver = new BackwardEulerSolver; break;
281  case 2: ode_solver = new SDIRK23Solver(2); break;
282  case 3: ode_solver = new SDIRK33Solver; break;
283  // Explicit methods
284  case 11: ode_solver = new ForwardEulerSolver; break;
285  case 12: ode_solver = new RK2Solver(0.5); break; // midpoint method
286  case 13: ode_solver = new RK3SSPSolver; break;
287  case 14: ode_solver = new RK4Solver; break;
288  // Implicit A-stable methods (not L-stable)
289  case 22: ode_solver = new ImplicitMidpointSolver; break;
290  case 23: ode_solver = new SDIRK23Solver; break;
291  case 24: ode_solver = new SDIRK34Solver; break;
292  default:
293  if (myid == 0)
294  {
295  cout << "Unknown ODE solver type: " << ode_solver_type << '\n';
296  }
297  return 3;
298  }
299 
300  // 5. Refine the mesh in serial to increase the resolution. In this example
301  // we do 'ser_ref_levels' of uniform refinement, where 'ser_ref_levels' is
302  // a command-line parameter.
303  for (int lev = 0; lev < ser_ref_levels; lev++)
304  {
305  mesh->UniformRefinement();
306  }
307 
308  // 6. Define a parallel mesh by a partitioning of the serial mesh. Refine
309  // this mesh further in parallel to increase the resolution. Once the
310  // parallel mesh is defined, the serial mesh can be deleted.
311  ParMesh *pmesh = new ParMesh(MPI_COMM_WORLD, *mesh);
312  delete mesh;
313  for (int lev = 0; lev < par_ref_levels; lev++)
314  {
315  pmesh->UniformRefinement();
316  }
317 
318  // 7. Define the parallel vector finite element spaces representing the mesh
319  // deformation x_gf, the velocity v_gf, and the initial configuration,
320  // x_ref. Define also the elastic energy density, w_gf, which is in a
321  // discontinuous higher-order space. Since x and v are integrated in time
322  // as a system, we group them together in block vector vx, on the unique
323  // parallel degrees of freedom, with offsets given by array true_offset.
324  H1_FECollection fe_coll(order, dim);
325  ParFiniteElementSpace fespace(pmesh, &fe_coll, dim);
326 
327  HYPRE_BigInt glob_size = fespace.GlobalTrueVSize();
328  if (myid == 0)
329  {
330  cout << "Number of velocity/deformation unknowns: " << glob_size << endl;
331  }
332  int true_size = fespace.TrueVSize();
333  Array<int> true_offset(3);
334  true_offset[0] = 0;
335  true_offset[1] = true_size;
336  true_offset[2] = 2*true_size;
337 
338  BlockVector vx(true_offset);
339  ParGridFunction v_gf, x_gf;
340  v_gf.MakeTRef(&fespace, vx, true_offset[0]);
341  x_gf.MakeTRef(&fespace, vx, true_offset[1]);
342 
343  ParGridFunction x_ref(&fespace);
344  pmesh->GetNodes(x_ref);
345 
346  L2_FECollection w_fec(order + 1, dim);
347  ParFiniteElementSpace w_fespace(pmesh, &w_fec);
348  ParGridFunction w_gf(&w_fespace);
349 
350  // 8. Set the initial conditions for v_gf, x_gf and vx, and define the
351  // boundary conditions on a beam-like mesh (see description above).
353  v_gf.ProjectCoefficient(velo);
354  v_gf.SetTrueVector();
356  x_gf.ProjectCoefficient(deform);
357  x_gf.SetTrueVector();
358 
359  v_gf.SetFromTrueVector(); x_gf.SetFromTrueVector();
360 
361  Array<int> ess_bdr(fespace.GetMesh()->bdr_attributes.Max());
362  ess_bdr = 0;
363  ess_bdr[0] = 1; // boundary attribute 1 (index 0) is fixed
364 
365  // 9. Initialize the hyperelastic operator, the GLVis visualization and print
366  // the initial energies.
367  HyperelasticOperator *oper = new HyperelasticOperator(fespace, ess_bdr, visc,
368  mu, K, use_petsc,
369  petsc_use_jfnk);
370 
371  socketstream vis_v, vis_w;
372  if (visualization)
373  {
374  char vishost[] = "localhost";
375  int visport = 19916;
376  vis_v.open(vishost, visport);
377  vis_v.precision(8);
378  visualize(vis_v, pmesh, &x_gf, &v_gf, "Velocity", true);
379  // Make sure all ranks have sent their 'v' solution before initiating
380  // another set of GLVis connections (one from each rank):
381  MPI_Barrier(pmesh->GetComm());
382  vis_w.open(vishost, visport);
383  if (vis_w)
384  {
385  oper->GetElasticEnergyDensity(x_gf, w_gf);
386  vis_w.precision(8);
387  visualize(vis_w, pmesh, &x_gf, &w_gf, "Elastic energy density", true);
388  }
389  }
390 
391  double ee0 = oper->ElasticEnergy(x_gf);
392  double ke0 = oper->KineticEnergy(v_gf);
393  if (myid == 0)
394  {
395  cout << "initial elastic energy (EE) = " << ee0 << endl;
396  cout << "initial kinetic energy (KE) = " << ke0 << endl;
397  cout << "initial total energy (TE) = " << (ee0 + ke0) << endl;
398  }
399 
400  double t = 0.0;
401  oper->SetTime(t);
402  ode_solver->Init(*oper);
403 
404  // 10. Perform time-integration
405  // (looping over the time iterations, ti, with a time-step dt).
406  bool last_step = false;
407  for (int ti = 1; !last_step; ti++)
408  {
409  double dt_real = min(dt, t_final - t);
410 
411  ode_solver->Step(vx, t, dt_real);
412 
413  last_step = (t >= t_final - 1e-8*dt);
414 
415  if (last_step || (ti % vis_steps) == 0)
416  {
417  v_gf.SetFromTrueVector(); x_gf.SetFromTrueVector();
418 
419  double ee = oper->ElasticEnergy(x_gf);
420  double ke = oper->KineticEnergy(v_gf);
421 
422  if (myid == 0)
423  {
424  cout << "step " << ti << ", t = " << t << ", EE = " << ee
425  << ", KE = " << ke << ", ΔTE = " << (ee+ke)-(ee0+ke0) << endl;
426  }
427 
428  if (visualization)
429  {
430  visualize(vis_v, pmesh, &x_gf, &v_gf);
431  if (vis_w)
432  {
433  oper->GetElasticEnergyDensity(x_gf, w_gf);
434  visualize(vis_w, pmesh, &x_gf, &w_gf);
435  }
436  }
437  }
438  }
439 
440  // 11. Save the displaced mesh, the velocity and elastic energy.
441  {
442  v_gf.SetFromTrueVector(); x_gf.SetFromTrueVector();
443  GridFunction *nodes = &x_gf;
444  int owns_nodes = 0;
445  pmesh->SwapNodes(nodes, owns_nodes);
446 
447  ostringstream mesh_name, velo_name, ee_name;
448  mesh_name << "deformed." << setfill('0') << setw(6) << myid;
449  velo_name << "velocity." << setfill('0') << setw(6) << myid;
450  ee_name << "elastic_energy." << setfill('0') << setw(6) << myid;
451 
452  ofstream mesh_ofs(mesh_name.str().c_str());
453  mesh_ofs.precision(8);
454  pmesh->Print(mesh_ofs);
455  pmesh->SwapNodes(nodes, owns_nodes);
456  ofstream velo_ofs(velo_name.str().c_str());
457  velo_ofs.precision(8);
458  v_gf.Save(velo_ofs);
459  ofstream ee_ofs(ee_name.str().c_str());
460  ee_ofs.precision(8);
461  oper->GetElasticEnergyDensity(x_gf, w_gf);
462  w_gf.Save(ee_ofs);
463  }
464 
465  // 12. Free the used memory.
466  delete ode_solver;
467  delete pmesh;
468  delete oper;
469 
470  // We finalize PETSc
471  if (use_petsc) { MFEMFinalizePetsc(); }
472 
473  return 0;
474 }
475 
476 void visualize(ostream &os, ParMesh *mesh, ParGridFunction *deformed_nodes,
477  ParGridFunction *field, const char *field_name, bool init_vis)
478 {
479  if (!os)
480  {
481  return;
482  }
483 
484  GridFunction *nodes = deformed_nodes;
485  int owns_nodes = 0;
486 
487  mesh->SwapNodes(nodes, owns_nodes);
488 
489  os << "parallel " << mesh->GetNRanks() << " " << mesh->GetMyRank() << "\n";
490  os << "solution\n" << *mesh << *field;
491 
492  mesh->SwapNodes(nodes, owns_nodes);
493 
494  if (init_vis)
495  {
496  os << "window_size 800 800\n";
497  os << "window_title '" << field_name << "'\n";
498  if (mesh->SpaceDimension() == 2)
499  {
500  os << "view 0 0\n"; // view from top
501  os << "keys jl\n"; // turn off perspective and light
502  }
503  os << "keys cm\n"; // show colorbar and mesh
504  os << "autoscale value\n"; // update value-range; keep mesh-extents fixed
505  os << "pause\n";
506  }
507  os << flush;
508 }
509 
510 
511 ReducedSystemOperator::ReducedSystemOperator(
513  const Array<int> &ess_tdof_list_)
514  : Operator(M_->ParFESpace()->TrueVSize()), M(M_), S(S_), H(H_),
515  Jacobian(NULL), dt(0.0), v(NULL), x(NULL), w(height), z(height),
516  ess_tdof_list(ess_tdof_list_)
517 { }
518 
519 void ReducedSystemOperator::SetParameters(double dt_, const Vector *v_,
520  const Vector *x_)
521 {
522  dt = dt_; v = v_; x = x_;
523 }
524 
525 void ReducedSystemOperator::Mult(const Vector &k, Vector &y) const
526 {
527  // compute: y = H(x + dt*(v + dt*k)) + M*k + S*(v + dt*k)
528  add(*v, dt, k, w);
529  add(*x, dt, w, z);
530  H->Mult(z, y);
531  M->TrueAddMult(k, y);
532  S->TrueAddMult(w, y);
533  y.SetSubVector(ess_tdof_list, 0.0);
534 }
535 
536 Operator &ReducedSystemOperator::GetGradient(const Vector &k) const
537 {
538  delete Jacobian;
539  SparseMatrix *localJ = Add(1.0, M->SpMat(), dt, S->SpMat());
540  add(*v, dt, k, w);
541  add(*x, dt, w, z);
542  localJ->Add(dt*dt, H->GetLocalGradient(z));
543  // if we are using PETSc, the HypreParCSR Jacobian will be converted to
544  // PETSc's AIJ on the fly
545  Jacobian = M->ParallelAssemble(localJ);
546  delete localJ;
547  HypreParMatrix *Je = Jacobian->EliminateRowsCols(ess_tdof_list);
548  delete Je;
549  return *Jacobian;
550 }
551 
552 ReducedSystemOperator::~ReducedSystemOperator()
553 {
554  delete Jacobian;
555 }
556 
557 
558 HyperelasticOperator::HyperelasticOperator(ParFiniteElementSpace &f,
559  Array<int> &ess_bdr, double visc,
560  double mu, double K, bool use_petsc,
561  bool use_petsc_factory)
562  : TimeDependentOperator(2*f.TrueVSize(), 0.0), fespace(f),
563  M(&fespace), S(&fespace), H(&fespace),
564  viscosity(visc), M_solver(f.GetComm()),
565  newton_solver(f.GetComm()), pnewton_solver(NULL), z(height/2)
566 {
567  const double rel_tol = 1e-8;
568  const int skip_zero_entries = 0;
569 
570  const double ref_density = 1.0; // density in the reference configuration
571  ConstantCoefficient rho0(ref_density);
572  M.AddDomainIntegrator(new VectorMassIntegrator(rho0));
573  M.Assemble(skip_zero_entries);
574  M.Finalize(skip_zero_entries);
575  Mmat = M.ParallelAssemble();
576  fespace.GetEssentialTrueDofs(ess_bdr, ess_tdof_list);
577  HypreParMatrix *Me = Mmat->EliminateRowsCols(ess_tdof_list);
578  delete Me;
579 
580  M_solver.iterative_mode = false;
581  M_solver.SetRelTol(rel_tol);
582  M_solver.SetAbsTol(0.0);
583  M_solver.SetMaxIter(30);
584  M_solver.SetPrintLevel(0);
585  M_prec.SetType(HypreSmoother::Jacobi);
586  M_solver.SetPreconditioner(M_prec);
587  M_solver.SetOperator(*Mmat);
588 
589  model = new NeoHookeanModel(mu, K);
590  H.AddDomainIntegrator(new HyperelasticNLFIntegrator(model));
591  H.SetEssentialTrueDofs(ess_tdof_list);
592 
593  ConstantCoefficient visc_coeff(viscosity);
594  S.AddDomainIntegrator(new VectorDiffusionIntegrator(visc_coeff));
595  S.Assemble(skip_zero_entries);
596  S.Finalize(skip_zero_entries);
597 
598  reduced_oper = new ReducedSystemOperator(&M, &S, &H, ess_tdof_list);
599  if (!use_petsc)
600  {
601  HypreSmoother *J_hypreSmoother = new HypreSmoother;
602  J_hypreSmoother->SetType(HypreSmoother::l1Jacobi);
603  J_hypreSmoother->SetPositiveDiagonal(true);
604  J_prec = J_hypreSmoother;
605 
606  MINRESSolver *J_minres = new MINRESSolver(f.GetComm());
607  J_minres->SetRelTol(rel_tol);
608  J_minres->SetAbsTol(0.0);
609  J_minres->SetMaxIter(300);
610  J_minres->SetPrintLevel(-1);
611  J_minres->SetPreconditioner(*J_prec);
612  J_solver = J_minres;
613 
614  J_factory = NULL;
615 
616  newton_solver.iterative_mode = false;
617  newton_solver.SetSolver(*J_solver);
618  newton_solver.SetOperator(*reduced_oper);
619  newton_solver.SetPrintLevel(1); // print Newton iterations
620  newton_solver.SetRelTol(rel_tol);
621  newton_solver.SetAbsTol(0.0);
622  newton_solver.SetMaxIter(10);
623  }
624  else
625  {
626  // if using PETSc, we create the same solver (Newton + MINRES + Jacobi)
627  // by command line options (see rc_ex10p)
628  J_solver = NULL;
629  J_prec = NULL;
630  J_factory = NULL;
631  pnewton_solver = new PetscNonlinearSolver(f.GetComm(),
632  *reduced_oper);
633 
634  // we can setup a factory to construct a "physics-based" preconditioner
635  if (use_petsc_factory)
636  {
637  J_factory = new PreconditionerFactory(*reduced_oper, "JFNK preconditioner");
638  pnewton_solver->SetPreconditionerFactory(J_factory);
639  }
640  pnewton_solver->SetPrintLevel(1); // print Newton iterations
641  pnewton_solver->SetRelTol(rel_tol);
642  pnewton_solver->SetAbsTol(0.0);
643  pnewton_solver->SetMaxIter(10);
644  }
645 }
646 
647 void HyperelasticOperator::Mult(const Vector &vx, Vector &dvx_dt) const
648 {
649  // Create views to the sub-vectors v, x of vx, and dv_dt, dx_dt of dvx_dt
650  int sc = height/2;
651  Vector v(vx.GetData() + 0, sc);
652  Vector x(vx.GetData() + sc, sc);
653  Vector dv_dt(dvx_dt.GetData() + 0, sc);
654  Vector dx_dt(dvx_dt.GetData() + sc, sc);
655 
656  H.Mult(x, z);
657  if (viscosity != 0.0)
658  {
659  S.TrueAddMult(v, z);
660  z.SetSubVector(ess_tdof_list, 0.0);
661  }
662  z.Neg(); // z = -z
663  M_solver.Mult(z, dv_dt);
664 
665  dx_dt = v;
666 }
667 
668 void HyperelasticOperator::ImplicitSolve(const double dt,
669  const Vector &vx, Vector &dvx_dt)
670 {
671  int sc = height/2;
672  Vector v(vx.GetData() + 0, sc);
673  Vector x(vx.GetData() + sc, sc);
674  Vector dv_dt(dvx_dt.GetData() + 0, sc);
675  Vector dx_dt(dvx_dt.GetData() + sc, sc);
676 
677  // By eliminating kx from the coupled system:
678  // kv = -M^{-1}*[H(x + dt*kx) + S*(v + dt*kv)]
679  // kx = v + dt*kv
680  // we reduce it to a nonlinear equation for kv, represented by the
681  // reduced_oper. This equation is solved with the newton_solver
682  // object (using J_solver and J_prec internally).
683  reduced_oper->SetParameters(dt, &v, &x);
684  Vector zero; // empty vector is interpreted as zero r.h.s. by NewtonSolver
685  if (!pnewton_solver)
686  {
687  newton_solver.Mult(zero, dv_dt);
688  MFEM_VERIFY(newton_solver.GetConverged(),
689  "Newton solver did not converge.");
690  }
691  else
692  {
693  pnewton_solver->Mult(zero, dv_dt);
694  MFEM_VERIFY(pnewton_solver->GetConverged(),
695  "Newton solver did not converge.");
696  }
697  add(v, dt, dv_dt, dx_dt);
698 }
699 
700 double HyperelasticOperator::ElasticEnergy(const ParGridFunction &x) const
701 {
702  return H.GetEnergy(x);
703 }
704 
705 double HyperelasticOperator::KineticEnergy(const ParGridFunction &v) const
706 {
707  double loc_energy = 0.5*M.InnerProduct(v, v);
708  double energy;
709  MPI_Allreduce(&loc_energy, &energy, 1, MPI_DOUBLE, MPI_SUM,
710  fespace.GetComm());
711  return energy;
712 }
713 
714 void HyperelasticOperator::GetElasticEnergyDensity(
715  const ParGridFunction &x, ParGridFunction &w) const
716 {
717  ElasticEnergyCoefficient w_coeff(*model, x);
718  w.ProjectCoefficient(w_coeff);
719 }
720 
721 HyperelasticOperator::~HyperelasticOperator()
722 {
723  delete J_solver;
724  delete J_prec;
725  delete J_factory;
726  delete reduced_oper;
727  delete model;
728  delete Mmat;
729  delete pnewton_solver;
730 }
731 
732 // This method gets called every time we need a preconditioner "oh"
733 // contains the PetscParMatrix that wraps the operator constructed in
734 // the GetGradient() method (see also PetscSolver::SetJacobianType()).
735 // In this example, we just return a customizable PetscPreconditioner
736 // using that matrix. However, the OperatorHandle argument can be
737 // ignored, and any "physics-based" solver can be constructed since we
738 // have access to the HyperElasticOperator class.
739 Solver* PreconditionerFactory::NewPreconditioner(const mfem::OperatorHandle& oh)
740 {
741  PetscParMatrix *pP;
742  oh.Get(pP);
743  return new PetscPreconditioner(*pP,"jfnk_");
744 }
745 
747  const IntegrationPoint &ip)
748 {
749  model.SetTransformation(T);
750  x.GetVectorGradient(T, J);
751  // return model.EvalW(J); // in reference configuration
752  return model.EvalW(J)/J.Det(); // in deformed configuration
753 }
754 
755 
756 void InitialDeformation(const Vector &x, Vector &y)
757 {
758  // set the initial configuration to be the same as the reference,
759  // stress free, configuration
760  y = x;
761 }
762 
763 void InitialVelocity(const Vector &x, Vector &v)
764 {
765  const int dim = x.Size();
766  const double s = 0.1/64.;
767 
768  v = 0.0;
769  v(dim-1) = s*x(0)*x(0)*(8.0-x(0));
770  v(0) = -s*x(0)*x(0);
771 }
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
Abstract class for PETSc&#39;s preconditioners.
Definition: petsc.hpp:775
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
Wrapper for PETSc&#39;s matrix class.
Definition: petsc.hpp:307
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
Pointer to an Operator of a specified type.
Definition: handle.hpp:33
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
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
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
bool iterative_mode
If true, use the second argument of Mult() as an initial guess.
Definition: operator.hpp:655
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
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
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
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 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
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
Abstract class for PETSc&#39;s nonlinear solvers.
Definition: petsc.hpp:877
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
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 GetVectorGradient(ElementTransformation &tr, DenseMatrix &grad) const
Definition: gridfunc.cpp:1738
Implicit midpoint method. A-stable, not L-stable.
Definition: ode.hpp:404
void MFEMFinalizePetsc()
Definition: petsc.cpp:192
Class for integration point with weight.
Definition: intrules.hpp:25
void MFEMInitializePetsc()
Convenience functions to initialize/finalize PETSc.
Definition: petsc.cpp:168
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]
void Get(OpType *&A) const
Return the Operator pointer statically cast to a given OpType.
Definition: handle.hpp:114
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
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
Class for parallel meshes.
Definition: pmesh.hpp:32
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()
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