7#include <polysolve/linear/FEMSolver.hpp>
8#include <polysolve/nonlinear/Solver.hpp>
14#include <unsupported/Eigen/SparseExtra>
24 using namespace assembler;
26 using namespace solver;
27 using namespace utils;
32 const int dim =
mesh->dimension();
41 args[
"solver"][
"advanced"][
"jacobian_threshold"],
args[
"solver"][
"advanced"][
"check_inversion"],
48 args.value(
"/time/quasistatic"_json_pointer,
true),
mass,
51 args[
"solver"][
"advanced"][
"lagged_regularization_weight"],
52 args[
"solver"][
"advanced"][
"lagged_regularization_iterations"],
58 args[
"solver"][
"contact"][
"barrier_stiffness"],
59 args[
"solver"][
"contact"][
"CCD"][
"broad_phase"],
60 args[
"solver"][
"contact"][
"CCD"][
"tolerance"],
61 args[
"solver"][
"contact"][
"CCD"][
"max_iterations"],
68 args[
"contact"][
"friction_coefficient"],
69 args[
"contact"][
"epsv"],
70 args[
"solver"][
"contact"][
"friction_iterations"],
72 args[
"solver"][
"rayleigh_damping"]);
76 if (name ==
"augmented_lagrangian")
83 bool solve_symmetric_flag =
false;
86 for (
int i = 0; i < dim; i++)
88 for (
int j = 0; j < i; j++)
90 if (std::find(fixed_entry.data(), fixed_entry.data() + fixed_entry.size(), i + j * dim) == fixed_entry.data() + fixed_entry.size() && std::find(fixed_entry.data(), fixed_entry.data() + fixed_entry.size(), j + i * dim) == fixed_entry.data() + fixed_entry.size())
92 logger().info(
"Strain entry [{},{}] and [{},{}] are not fixed, solve for symmetric strain...", i, j, j, i);
93 solve_symmetric_flag =
true;
97 if (solve_symmetric_flag)
102 std::shared_ptr<NLHomoProblem> homo_problem = std::make_shared<NLHomoProblem>(
112 solve_data.
nl_problem->init(Eigen::VectorXd::Zero(homo_problem->reduced_size() + homo_problem->macro_reduced_size()));
113 solve_data.
nl_problem->update_quantities(t, Eigen::VectorXd::Zero(homo_problem->reduced_size() + homo_problem->macro_reduced_size()));
118 const int dim =
mesh->dimension();
123 Eigen::VectorXd extended_sol;
124 extended_sol.setZero(
ndof + dim * dim);
126 if (sol.size() == extended_sol.size())
130 homo_problem->set_fixed_entry({});
132 std::shared_ptr<polysolve::nonlinear::Solver> nl_solver =
make_nl_solver(
true);
134 Eigen::VectorXi al_indices = fixed_entry.array() + homo_problem->full_size();
140 const double initial_weight =
args[
"solver"][
"augmented_lagrangian"][
"initial_weight"];
141 const double max_weight =
args[
"solver"][
"augmented_lagrangian"][
"max_weight"];
142 const double eta_tol =
args[
"solver"][
"augmented_lagrangian"][
"eta"];
143 const double scaling =
args[
"solver"][
"augmented_lagrangian"][
"scaling"];
144 double al_weight = initial_weight;
146 Eigen::VectorXd tmp_sol = homo_problem->extended_to_reduced(extended_sol);
147 const Eigen::VectorXd initial_sol = tmp_sol;
148 const double initial_error = lagr_form->compute_error(extended_sol);
149 double current_error = initial_error;
152 extended_sol(al_indices) = al_values;
153 Eigen::VectorXd reduced_sol = homo_problem->extended_to_reduced(extended_sol);
155 homo_problem->line_search_begin(tmp_sol, reduced_sol);
157 bool force_al =
true;
159 lagr_form->set_initial_weight(al_weight);
162 || !std::isfinite(homo_problem->value(reduced_sol))
163 || !homo_problem->is_step_valid(tmp_sol, reduced_sol)
164 || !homo_problem->is_step_collision_free(tmp_sol, reduced_sol))
167 homo_problem->line_search_end();
169 logger().info(
"Solving AL Problem with weight {}", al_weight);
171 homo_problem->init(tmp_sol);
174 nl_solver->minimize(*homo_problem, tmp_sol);
176 catch (
const std::runtime_error &e)
178 logger().error(
"AL solve failed!");
181 extended_sol = homo_problem->reduced_to_extended(tmp_sol);
182 logger().debug(
"Current macro strain: {}", extended_sol.tail(dim * dim));
184 current_error = lagr_form->compute_error(extended_sol);
185 const double eta = 1 - sqrt(current_error / initial_error);
187 logger().info(
"Current eta = {}, current error = {}, initial error = {}", eta, current_error, initial_error);
189 if (eta < eta_tol && al_weight < max_weight)
190 al_weight *= scaling;
192 lagr_form->update_lagrangian(extended_sol, al_weight);
196 if (adaptive_initial_weight)
198 args[
"solver"][
"augmented_lagrangian"][
"initial_weight"] =
args[
"solver"][
"augmented_lagrangian"][
"initial_weight"].get<
double>() * scaling;
200 json tmp = json::object();
201 tmp[
"/solver/augmented_lagrangian/initial_weight"_json_pointer] =
args[
"solver"][
"augmented_lagrangian"][
"initial_weight"];
203 logger().warn(
"AL weight too small, increase weight and revert solution, new initial weight is {}",
args[
"solver"][
"augmented_lagrangian"][
"initial_weight"].get<double>());
205 tmp_sol = initial_sol;
209 extended_sol(al_indices) = al_values;
210 reduced_sol = homo_problem->extended_to_reduced(extended_sol);
212 homo_problem->line_search_begin(tmp_sol, reduced_sol);
214 homo_problem->line_search_end();
215 lagr_form->disable();
218 homo_problem->set_fixed_entry(fixed_entry);
220 Eigen::VectorXd reduced_sol = homo_problem->extended_to_reduced(extended_sol);
222 homo_problem->init(reduced_sol);
223 std::shared_ptr<polysolve::nonlinear::Solver> nl_solver =
make_nl_solver(
false);
224 nl_solver->minimize(*homo_problem, reduced_sol);
226 logger().info(
"Macro Strain: {}", extended_sol.tail(dim * dim).transpose());
230 json linear_args =
args[
"solver"][
"linear"];
231 std::string solver_name = linear_args[
"solver"];
232 if (solver_name.find(
"Pardiso") != std::string::npos)
234 linear_args[
"solver"] =
"Eigen::PardisoLLT";
235 std::unique_ptr<polysolve::linear::Solver> solver =
236 polysolve::linear::Solver::create(linear_args,
logger());
239 homo_problem->hessian(reduced_sol, A);
240 Eigen::VectorXd
x, b = Eigen::VectorXd::Zero(A.rows());
244 *solver, A, b, {},
x, A.rows(),
args[
"output"][
"data"][
"stiffness_mat"],
false,
false,
false);
246 catch (
const std::runtime_error &error)
248 logger().error(
"The solution is a saddle point!");
253 sol = homo_problem->reduced_to_extended(reduced_sol);
254 if (
args[
"/boundary_conditions/periodic_boundary/force_zero_mean"_json_pointer].get<bool>())
258 for (
int d = 0; d < dim; d++)
259 sol(Eigen::seqN(d,
n_bases, dim), 0).array() -= integral(d) / area;
261 reduced_sol = homo_problem->extended_to_reduced(sol);
271 if (!is_static && !
args[
"time"][
"quasistatic"])
276 const int dim =
mesh->dimension();
277 Eigen::MatrixXd extended_sol;
278 for (
int t = 0; t <= time_steps; ++t)
280 double forward_solve_time = 0, remeshing_time = 0, global_relaxation_time = 0;
292 save_timestep(t0 + dt * t, t, t0, dt, sol, Eigen::MatrixXd());
305 logger().info(
"{}/{} t={}", t, time_steps, t0 + dt * t);
#define POLYFEM_SCOPED_TIMER(...)
assembler::MacroStrainValue macro_strain_constraint
std::shared_ptr< utils::PeriodicBoundary > periodic_bc
periodic BC and periodic mesh utils
int n_bases
number of bases
void cache_transient_adjoint_quantities(const int current_step, const Eigen::MatrixXd &sol, const Eigen::MatrixXd &disp_grad)
int n_pressure_bases
number of pressure bases
assembler::AssemblyValsCache ass_vals_cache
used to store assembly values for small problems
int n_boundary_samples() const
quadrature used for projecting boundary conditions
const std::vector< basis::ElementBases > & geom_bases() const
Get a constant reference to the geometry mapping bases.
std::vector< mesh::LocalBoundary > local_pressure_boundary
mapping from elements to nodes for pressure boundary conditions
mesh::Obstacle obstacle
Obstacles used in collisions.
std::shared_ptr< assembler::Assembler > assembler
assemblers
ipc::CollisionMesh periodic_collision_mesh
IPC collision mesh under periodic BC.
ipc::CollisionMesh collision_mesh
IPC collision mesh.
solver::CacheLevel optimization_enabled
void solve_homogenization_step(Eigen::MatrixXd &sol, const int t=0, bool adaptive_initial_weight=false)
In Elasticity PDE, solve for "min W(disp_grad + \grad u)" instead of "min W(\grad u)".
void save_timestep(const double time, const int t, const double t0, const double dt, const Eigen::MatrixXd &sol, const Eigen::MatrixXd &pressure)
saves a timestep
std::shared_ptr< polysolve::nonlinear::Solver > make_nl_solver(bool for_al) const
factory to create the nl solver depending on input
std::shared_ptr< assembler::Mass > mass_matrix_assembler
std::unique_ptr< mesh::Mesh > mesh
current mesh, it can be a Mesh2D or Mesh3D
std::shared_ptr< polyfem::mesh::MeshNodes > mesh_nodes
Mapping from input nodes to FE nodes.
StiffnessMatrix mass
Mass matrix, it is computed only for time dependent problems.
void solve_homogenization(const int time_steps, const double t0, const double dt, Eigen::MatrixXd &sol)
json args
main input arguments containing all defaults
void save_restart_json(const double t0, const double dt, const int t) const
Save a JSON sim file for restarting the simulation at time t.
Eigen::VectorXi periodic_collision_mesh_to_basis
index mapping from periodic 2x2 collision mesh to FE periodic mesh
std::vector< basis::ElementBases > bases
FE bases, the size is #elements.
std::vector< mesh::LocalBoundary > local_boundary
mapping from elements to nodes for dirichlet boundary conditions
double avg_mass
average system mass, used for contact with IPC
assembler::AssemblyValsCache mass_ass_vals_cache
std::vector< int > boundary_nodes
list of boundary nodes
solver::SolveData solve_data
timedependent stuff cached
std::vector< mesh::LocalBoundary > local_neumann_boundary
mapping from elements to nodes for neumann boundary conditions
std::shared_ptr< assembler::PressureAssembler > elasticity_pressure_assembler
Eigen::MatrixXd rhs
System right-hand side.
std::unordered_map< int, std::vector< mesh::LocalBoundary > > local_pressure_cavity
mapping from elements to nodes for pressure boundary conditions
void init_homogenization_solve(const double t)
Eigen::MatrixXd eval(const double t) const
const Eigen::VectorXi & get_fixed_entry() const
static Eigen::MatrixXd generate_linear_field(const int n_bases, const std::shared_ptr< mesh::MeshNodes > mesh_nodes, const Eigen::MatrixXd &grad)
static Eigen::VectorXd integrate_function(const std::vector< basis::ElementBases > &bases, const std::vector< basis::ElementBases > &gbases, const Eigen::MatrixXd &fun, const int dim, const int actual_dim)
std::vector< std::shared_ptr< Form > > init_forms(const Units &units, const int dim, const double t, const int n_bases, std::vector< basis::ElementBases > &bases, const std::vector< basis::ElementBases > &geom_bases, const assembler::Assembler &assembler, assembler::AssemblyValsCache &ass_vals_cache, const assembler::AssemblyValsCache &mass_ass_vals_cache, const double jacobian_threshold, const solver::ElementInversionCheck check_inversion, const int n_pressure_bases, const std::vector< int > &boundary_nodes, const std::vector< mesh::LocalBoundary > &local_boundary, const std::vector< mesh::LocalBoundary > &local_neumann_boundary, const int n_boundary_samples, const Eigen::MatrixXd &rhs, const Eigen::MatrixXd &sol, const assembler::Density &density, const std::vector< mesh::LocalBoundary > &local_pressure_boundary, const std::unordered_map< int, std::vector< mesh::LocalBoundary > > &local_pressure_cavity, const std::shared_ptr< assembler::PressureAssembler > pressure_assembler, const bool ignore_inertia, const StiffnessMatrix &mass, const std::shared_ptr< assembler::ViscousDamping > damping_assembler, const double lagged_regularization_weight, const int lagged_regularization_iterations, const size_t obstacle_ndof, const bool contact_enabled, const ipc::CollisionMesh &collision_mesh, const double dhat, const double avg_mass, const bool use_convergent_contact_formulation, const json &barrier_stiffness, const ipc::BroadPhaseMethod broad_phase, const double ccd_tolerance, const long ccd_max_iterations, const bool enable_shape_derivatives, const assembler::MacroStrainValue ¯o_strain_constraint, const bool periodic_contact, const Eigen::VectorXi &tiled_to_single, const std::shared_ptr< utils::PeriodicBoundary > &periodic_bc, const double friction_coefficient, const double epsv, const int friction_iterations, const json &rayleigh_damping)
Initialize the forms and return a vector of pointers to them.
std::shared_ptr< solver::PeriodicContactForm > periodic_contact_form
void update_dt()
updates the dt inside the different forms
std::shared_ptr< solver::NLProblem > nl_problem
std::shared_ptr< solver::MacroStrainLagrangianForm > strain_al_lagr_form
std::vector< std::pair< std::string, std::shared_ptr< solver::Form > > > named_forms() const
std::vector< std::shared_ptr< solver::AugmentedLagrangianForm > > al_form
void update_barrier_stiffness(const Eigen::VectorXd &x)
update the barrier stiffness for the forms
bool is_param_valid(const json ¶ms, const std::string &key)
Determine if a key exists and is non-null in a json object.
Eigen::MatrixXd unflatten(const Eigen::VectorXd &x, int dim)
Unflatten rowwises, so every dim elements in x become a row.
Eigen::VectorXd flatten(const Eigen::MatrixXd &X)
Flatten rowwises.
spdlog::logger & logger()
Retrieves the current logger.
void log_and_throw_error(const std::string &msg)
Eigen::SparseMatrix< double, Eigen::ColMajor > StiffnessMatrix