47 #ifndef MFEM_USE_SUNDIALS
48 #error This example requires that MFEM is built with MFEM_USE_SUNDIALS=YES
54 class ReducedSystemOperator;
55 class SundialsJacSolver;
83 ReducedSystemOperator *reduced_oper;
97 enum NonlinearSolverType
104 double visc,
double mu,
double K,
105 NonlinearSolverType nls_type);
111 virtual void ImplicitSolve(
const double dt,
const Vector &x,
Vector &k);
117 void InitSundialsJacSolver(SundialsJacSolver &sjsolv);
123 virtual ~HyperelasticOperator();
130 class ReducedSystemOperator :
public Operator
145 void SetParameters(
double dt_,
const Vector *v_,
const Vector *x_);
153 virtual ~ReducedSystemOperator();
179 : M(), S(), H(), local_grad_H(), Jacobian(), J_solver() { }
185 M = &M_; S = &S_; H = &H_; J_solver = &solver;
195 int InitSystem(
void *sundials_mem);
196 int SetupSystem(
void *sundials_mem,
int conv_fail,
197 const Vector &y_pred,
const Vector &f_pred,
int &jac_cur,
199 int SolveSystem(
void *sundials_mem,
Vector &b,
const Vector &weight,
201 int FreeSystem(
void *sundials_mem);
207 class ElasticEnergyCoefficient :
public Coefficient
216 : model(m), x(x_) { }
218 virtual ~ElasticEnergyCoefficient() { }
227 bool init_vis =
false);
230 int main(
int argc,
char *argv[])
234 MPI_Init(&argc, &argv);
235 MPI_Comm_size(MPI_COMM_WORLD, &num_procs);
236 MPI_Comm_rank(MPI_COMM_WORLD, &myid);
239 const char *mesh_file =
"../../data/beam-quad.mesh";
240 int ser_ref_levels = 2;
241 int par_ref_levels = 0;
243 int ode_solver_type = 3;
244 double t_final = 300.0;
249 bool visualization =
true;
250 const char *nls =
"newton";
254 const double reltol = 1e-1, abstol = 1e-1;
257 args.
AddOption(&mesh_file,
"-m",
"--mesh",
258 "Mesh file to use.");
259 args.
AddOption(&ser_ref_levels,
"-rs",
"--refine-serial",
260 "Number of times to refine the mesh uniformly in serial.");
261 args.
AddOption(&par_ref_levels,
"-rp",
"--refine-parallel",
262 "Number of times to refine the mesh uniformly in parallel.");
264 "Order (degree) of the finite elements.");
265 args.
AddOption(&ode_solver_type,
"-s",
"--ode-solver",
266 "ODE solver: 1 - Backward Euler, 2 - SDIRK2, 3 - SDIRK3,\n\t"
267 " 4 - CVODE implicit, approximate Jacobian,\n\t"
268 " 5 - CVODE implicit, specified Jacobian,\n\t"
269 " 6 - ARKODE implicit, approximate Jacobian,\n\t"
270 " 7 - ARKODE implicit, specified Jacobian,\n\t"
271 " 11 - Forward Euler, 12 - RK2,\n\t"
272 " 13 - RK3 SSP, 14 - RK4,\n\t"
273 " 15 - CVODE (adaptive order) explicit,\n\t"
274 " 16 - ARKODE default (4th order) explicit.");
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",
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.");
311 Mesh *mesh =
new Mesh(mesh_file, 1, 1);
320 SundialsJacSolver *sjsolver = NULL;
321 switch (ode_solver_type)
329 cvode =
new CVODESolver(MPI_COMM_WORLD, CV_BDF, CV_NEWTON);
332 if (ode_solver_type == 5)
334 sjsolver =
new SundialsJacSolver;
337 ode_solver = cvode;
break;
340 arkode =
new ARKODESolver(MPI_COMM_WORLD, ARKODESolver::IMPLICIT);
343 if (ode_solver_type == 7)
345 sjsolver =
new SundialsJacSolver;
348 ode_solver = arkode;
break;
351 case 12: ode_solver =
new RK2Solver(0.5);
break;
353 case 14: ode_solver =
new RK4Solver;
break;
355 cvode =
new CVODESolver(MPI_COMM_WORLD, CV_ADAMS, CV_FUNCTIONAL);
358 ode_solver = cvode;
break;
360 arkode =
new ARKODESolver(MPI_COMM_WORLD, ARKODESolver::EXPLICIT);
363 ode_solver = arkode;
break;
371 cout <<
"Unknown ODE solver type: " << ode_solver_type <<
'\n';
377 map<string,HyperelasticOperator::NonlinearSolverType> nls_map;
378 nls_map[
"newton"] = HyperelasticOperator::NEWTON;
379 nls_map[
"kinsol"] = HyperelasticOperator::KINSOL;
380 if (nls_map.find(nls) == nls_map.end())
384 cout <<
"Unknown type of nonlinear solver: " << nls << endl;
393 for (
int lev = 0; lev < ser_ref_levels; lev++)
403 for (
int lev = 0; lev < par_ref_levels; lev++)
420 cout <<
"Number of velocity/deformation unknowns: " << glob_size << endl;
425 true_offset[1] = true_size;
426 true_offset[2] = 2*true_size;
441 v_gf.ProjectCoefficient(velo);
454 HyperelasticOperator oper(fespace, ess_bdr, visc, mu, K, nls_map[nls]);
459 char vishost[] =
"localhost";
461 vis_v.
open(vishost, visport);
463 visualize(vis_v, pmesh, &x_gf, &v_gf,
"Velocity",
true);
467 vis_w.
open(vishost, visport);
470 oper.GetElasticEnergyDensity(x_gf, w_gf);
472 visualize(vis_w, pmesh, &x_gf, &w_gf,
"Elastic energy density",
true);
476 double ee0 = oper.ElasticEnergy(x_gf);
477 double ke0 = oper.KineticEnergy(v_gf);
480 cout <<
"initial elastic energy (EE) = " << ee0 << endl;
481 cout <<
"initial kinetic energy (KE) = " << ke0 << endl;
482 cout <<
"initial total energy (TE) = " << (ee0 + ke0) << endl;
487 ode_solver->
Init(oper);
491 bool last_step =
false;
492 for (
int ti = 1; !last_step; ti++)
494 double dt_real = min(dt, t_final - t);
496 ode_solver->
Step(vx, t, dt_real);
498 last_step = (t >= t_final - 1e-8*dt);
500 if (last_step || (ti % vis_steps) == 0)
505 double ee = oper.ElasticEnergy(x_gf);
506 double ke = oper.KineticEnergy(v_gf);
510 cout <<
"step " << ti <<
", t = " << t <<
", EE = " << ee
511 <<
", KE = " << ke <<
", ΔTE = " << (ee+ke)-(ee0+ke0) << endl;
514 else if (arkode) { arkode->
PrintInfo(); }
522 oper.GetElasticEnergyDensity(x_gf, w_gf);
535 ostringstream mesh_name, velo_name, ee_name;
536 mesh_name <<
"deformed." << setfill(
'0') << setw(6) << myid;
537 velo_name <<
"velocity." << setfill(
'0') << setw(6) << myid;
538 ee_name <<
"elastic_energy." << setfill(
'0') << setw(6) << myid;
540 ofstream mesh_ofs(mesh_name.str().c_str());
541 mesh_ofs.precision(8);
542 pmesh->
Print(mesh_ofs);
544 ofstream velo_ofs(velo_name.str().c_str());
545 velo_ofs.precision(8);
547 ofstream ee_ofs(ee_name.str().c_str());
549 oper.GetElasticEnergyDensity(x_gf, w_gf);
577 out <<
"solution\n" << *mesh << *field;
583 out <<
"window_size 800 800\n";
584 out <<
"window_title '" << field_name <<
"'\n";
591 out <<
"autoscale value\n";
598 ReducedSystemOperator::ReducedSystemOperator(
600 :
Operator(M_->ParFESpace()->TrueVSize()), M(M_), S(S_), H(H_),
601 Jacobian(NULL), dt(0.0), v(NULL), x(NULL), w(height), z(height)
604 void ReducedSystemOperator::SetParameters(
double dt_,
const Vector *v_,
607 dt = dt_; v = v_; x = x_;
616 M->TrueAddMult(k, y);
617 S->TrueAddMult(w, y);
620 Operator &ReducedSystemOperator::GetGradient(
const Vector &k)
const
626 localJ->
Add(dt*dt, H->GetLocalGradient(z));
627 Jacobian = M->ParallelAssemble(localJ);
632 ReducedSystemOperator::~ReducedSystemOperator()
638 int SundialsJacSolver::InitSystem(
void *sundials_mem)
641 HyperelasticOperator *he_oper;
644 he_oper =
dynamic_cast<HyperelasticOperator*
>(td_oper);
645 MFEM_VERIFY(he_oper,
"operator is not HyperelasticOperator");
650 he_oper->InitSundialsJacSolver(*
this);
654 int SundialsJacSolver::SetupSystem(
void *sundials_mem,
int conv_fail,
656 int &jac_cur,
Vector &v_temp1,
659 int sc = y_pred.
Size() / 2;
661 double dt = GetTimeStep(sundials_mem);
666 local_grad_H = &H->GetLocalGradient(x);
667 localJ->
Add(dt*dt, *local_grad_H);
668 Jacobian = M->ParallelAssemble(localJ);
671 J_solver->SetOperator(*Jacobian);
677 int SundialsJacSolver::SolveSystem(
void *sundials_mem,
Vector &b,
681 int sc = b.
Size() / 2;
687 double dt = GetTimeStep(sundials_mem);
691 lb_x.Distribute(b_x);
692 local_grad_H->Mult(lb_x, lrhs);
693 lrhs.ParallelAssemble(rhs);
695 M->TrueAddMult(b_v, rhs);
697 J_solver->iterative_mode =
false;
698 J_solver->Mult(rhs, b_v);
705 int SundialsJacSolver::FreeSystem(
void *sundials_mem)
715 NonlinearSolverType nls_type)
717 M(&fespace), S(&fespace), H(&fespace),
718 viscosity(visc), M_solver(f.GetComm()), z(height/2)
720 const double rel_tol = 1e-8;
721 const int skip_zero_entries = 0;
723 const double ref_density = 1.0;
726 M.Assemble(skip_zero_entries);
727 M.EliminateEssentialBC(ess_bdr);
728 M.Finalize(skip_zero_entries);
729 Mmat = M.ParallelAssemble();
731 M_solver.iterative_mode =
false;
732 M_solver.SetRelTol(rel_tol);
733 M_solver.SetAbsTol(0.0);
734 M_solver.SetMaxIter(30);
735 M_solver.SetPrintLevel(0);
736 M_prec.SetType(HypreSmoother::Jacobi);
737 M_solver.SetPreconditioner(M_prec);
738 M_solver.SetOperator(*Mmat);
742 H.SetEssentialBC(ess_bdr);
746 S.Assemble(skip_zero_entries);
747 S.EliminateEssentialBC(ess_bdr);
748 S.Finalize(skip_zero_entries);
750 reduced_oper =
new ReducedSystemOperator(&M, &S, &H);
753 J_hypreSmoother->
SetType(HypreSmoother::l1Jacobi);
755 J_prec = J_hypreSmoother;
765 if (nls_type == KINSOL)
769 newton_solver = kinsolver;
771 newton_solver->SetRelTol(rel_tol);
772 newton_solver->SetPrintLevel(0);
778 newton_solver->SetRelTol(rel_tol);
779 newton_solver->SetPrintLevel(-1);
781 newton_solver->SetSolver(*J_solver);
782 newton_solver->iterative_mode =
false;
783 newton_solver->SetOperator(*reduced_oper);
796 if (viscosity != 0.0)
801 M_solver.Mult(z, dv_dt);
806 void HyperelasticOperator::ImplicitSolve(
const double dt,
821 reduced_oper->SetParameters(dt, &v, &x);
823 newton_solver->Mult(zero, dv_dt);
824 MFEM_VERIFY(newton_solver->GetConverged(),
825 "Nonlinear solver did not converge.");
827 if (fespace.GetMyRank() == 0)
829 cout <<
" num nonlin sol iters = " << newton_solver->GetNumIterations()
830 <<
", final norm = " << newton_solver->GetFinalNorm() <<
'\n';
833 add(v, dt, dv_dt, dx_dt);
836 void HyperelasticOperator::InitSundialsJacSolver(SundialsJacSolver &sjsolv)
838 sjsolv.SetOperators(M, S, H, *J_solver);
843 return H.GetEnergy(x);
848 double loc_energy = 0.5*M.InnerProduct(v, v);
850 MPI_Allreduce(&loc_energy, &energy, 1, MPI_DOUBLE, MPI_SUM,
855 void HyperelasticOperator::GetElasticEnergyDensity(
858 ElasticEnergyCoefficient w_coeff(*model, x);
862 HyperelasticOperator::~HyperelasticOperator()
864 delete newton_solver;
876 model.SetTransformation(T);
879 return model.EvalW(J)/J.Det();
893 const double s = 0.1/64.;
896 v(dim-1) = s*x(0)*x(0)*(8.0-x(0));
void visualize(ostream &out, Mesh *mesh, GridFunction *deformed_nodes, GridFunction *field, const char *field_name=NULL, bool init_vis=false)
double Eval(ElementTransformation &T, const IntegrationPoint &ip, double t)
void Add(const int i, const int j, const double a)
void InitialDeformation(const Vector &x, Vector &y)
Conjugate gradient method.
Class for grid function - Vector with associated FE space.
void SetSStolerances(double reltol, double abstol)
Set the scalar relative and scalar absolute tolerances.
void SetMaxSetupCalls(int max_calls)
Set maximum number of nonlinear iterations without a Jacobian update.
Subclass constant coefficient.
virtual void Init(TimeDependentOperator &f)
Associate a TimeDependentOperator with the ODE solver.
Base abstract class for time dependent operators.
void SwapNodes(GridFunction *&nodes, int &own_nodes_)
void Mult(const Table &A, const Table &B, Table &C)
C = A * B (as boolean matrices)
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]...
Data type dense matrix using column-major storage.
int Size() const
Returns the size of the vector.
Abstract class for solving systems of ODEs: dx/dt = f(x,t)
virtual void Save(std::ostream &out) const
void SetLinearSolver(SundialsODELinearSolver &ls_spec)
Abstract parallel finite element space.
virtual void ProjectCoefficient(Coefficient &coeff)
Backward Euler ODE solver. L-stable.
void add(const Vector &v1, const Vector &v2, Vector &v)
void SetSStolerances(double reltol, double abstol)
Specify the scalar relative and scalar absolute tolerances.
void InitialVelocity(const Vector &x, Vector &v)
void SetPositiveDiagonal(bool pos=true)
After computing l1-norms, replace them with their absolute values.
void Add(const DenseMatrix &A, const DenseMatrix &B, double alpha, DenseMatrix &C)
C = A + alpha*B.
virtual void SetPreconditioner(Solver &pr)
This should be called before SetOperator.
void SetPrintLevel(int print_lvl)
Wrapper for SUNDIALS' KINSOL library – Nonlinear solvers.
Mesh * GetMesh() const
Returns the mesh.
Wrapper for SUNDIALS' CVODE library – Multi-step time integration.
void UniformRefinement(int i, const DSTable &, int *, int *, int *)
void SetMaxIter(int max_it)
T Max() const
Find the maximal element in the array, using the comparison operator < for class T.
HYPRE_Int GlobalTrueVSize() const
void SetMaxStep(double dt_max)
Set the maximum time step of the linear multistep method.
Newton's method for solving F(x)=b for a given operator F.
virtual void Print(std::ostream &out=mfem::out) const
Parallel smoothers in hypre.
void PrintUsage(std::ostream &out) const
Wrapper for SUNDIALS' ARKODE library – Runge-Kutta time integration.
void SetLinearSolver(SundialsODELinearSolver &ls_spec)
Set a custom Jacobian system solver for implicit methods.
int SpaceDimension() const
The classical explicit forth-order Runge-Kutta method, RK4.
void SetAbsTol(double atol)
Array< int > bdr_attributes
A list of all unique boundary attributes used by the Mesh.
void SetRelTol(double rtol)
Base class Coefficient that may optionally depend on time.
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)
Third-order, strong stability preserving (SSP) Runge-Kutta method.
void Distribute(const Vector *tv)
Abstract base class, wrapping the custom linear solvers interface in SUNDIALS' CVODE and ARKODE solve...
Implicit midpoint method. A-stable, not L-stable.
Class for integration point with weight.
void PrintOptions(std::ostream &out) const
HypreParVector * GetTrueDofs() const
Returns the true dofs in a new HypreParVector.
Abstract class for hyperelastic models.
int open(const char hostname[], int port)
void GetNodes(Vector &node_coord) const
Arbitrary order H1-conforming (continuous) finite elements.
void PrintInfo() const
Print CVODE statistics.
Class for parallel grid function.
OutStream out(std::cout)
Global stream used by the library for standard output. Initially it uses the same std::streambuf as s...
The classical forward Euler method.
void SetMaxStep(double dt_max)
Set the maximum time step of the Runge-Kutta method.
Wrapper for hypre's ParCSR matrix class.
void GetVectorGradient(ElementTransformation &tr, DenseMatrix &grad)
Vector & GetBlock(int i)
Get the i-th vector in the block.
Class for parallel meshes.
void PrintInfo() const
Print ARKODE statistics.
void SetType(HypreSmoother::Type type, int relax_times=1)
Set the relaxation type and number of sweeps.
Arbitrary order "L2-conforming" discontinuous finite elements.
void Neg()
(*this) = -(*this)