PolyFEM
Loading...
Searching...
No Matches
StateHomogenization.cpp
Go to the documentation of this file.
2#include <polyfem/Common.hpp>
13
17
18#include <Eigen/Core>
19#include <unsupported/Eigen/SparseExtra>
20#include <polysolve/linear/FEMSolver.hpp>
21#include <polysolve/nonlinear/Solver.hpp>
22#include <ipc/ipc.hpp>
23#include <spdlog/fmt/fmt.h>
24
25#include <algorithm>
26#include <memory>
27#include <stdexcept>
28#include <string>
29#include <vector>
30
31namespace polyfem::legacy
32{
33
34 using namespace assembler;
35 using namespace mesh;
36 using namespace solver;
37 using namespace utils;
38 using namespace quadrature;
39
41 {
42 const int dim = mesh->dimension();
43 const int ndof = n_bases * dim;
44
45 const std::vector<std::shared_ptr<Form>> forms = solve_data.init_forms(
46 // General
47 units,
48 mesh->dimension(), t, in_node_to_node,
49 // Elastic form
51 args["solver"]["advanced"]["jacobian_threshold"], args["solver"]["advanced"]["check_inversion"],
52 args["solver"]["advanced"]["conservative_max_iter"],
53 // Body form
55 n_boundary_samples(), rhs, Eigen::VectorXd::Zero(ndof) /* only to set neumann BC, not used*/, mass_matrix_assembler->density(),
56 // Pressure form
58 // Inertia form
59 args.value("/time/quasistatic"_json_pointer, true), mass,
60 nullptr,
61 // Lagged regularization form
62 args["solver"]["advanced"]["lagged_regularization_weight"],
63 args["solver"]["advanced"]["lagged_regularization_iterations"],
64 // Augmented lagrangian form
65 obstacle.ndof(), args["constraints"]["hard"], args["constraints"]["soft"], args["constraints"]["zero_mean"],
66 // Contact form
67 args["contact"]["enabled"], args["contact"]["periodic"].get<bool>() ? periodic_collision_mesh : collision_mesh, args["contact"]["dhat"],
68 avg_mass, args["contact"]["use_convergent_formulation"] ? bool(args["contact"]["use_area_weighting"]) : false,
69 args["contact"]["use_convergent_formulation"] ? bool(args["contact"]["use_improved_max_operator"]) : false,
70 args["contact"]["use_convergent_formulation"] ? bool(args["contact"]["use_physical_barrier"]) : false,
71 args["solver"]["contact"]["barrier_stiffness"],
72 args["solver"]["contact"]["initial_barrier_stiffness"],
73 args["solver"]["contact"]["CCD"]["broad_phase"],
74 args["solver"]["contact"]["CCD"]["tolerance"],
75 args["solver"]["contact"]["CCD"]["max_iterations"],
77 // Smooth Contact Form
78 args["contact"]["use_gcp_formulation"],
79 args["contact"]["alpha_t"],
80 args["contact"]["alpha_n"],
81 args["contact"]["use_adaptive_dhat"],
82 args["contact"]["min_distance_ratio"],
83 // Normal Adhesion Form
85 args["contact"]["adhesion"]["dhat_p"],
86 args["contact"]["adhesion"]["dhat_a"],
87 args["contact"]["adhesion"]["adhesion_strength"],
88 // Tangential Adhesion Form
89 args["contact"]["adhesion"]["tangential_adhesion_coefficient"],
90 args["contact"]["adhesion"]["epsa"],
91 args["solver"]["contact"]["tangential_adhesion_iterations"],
92 // Homogenization
94 // Periodic contact
95 args["contact"]["periodic"], periodic_collision_mesh_to_basis,
96 // Friction form
97 args["contact"]["friction_coefficient"],
98 args["contact"]["epsv"],
99 args["solver"]["contact"]["friction_iterations"],
100 // Rayleigh damping form
101 args["solver"]["rayleigh_damping"],
102 // BC AL lumping
103 args["solver"]["augmented_lagrangian"]["lumping"],
104 // Boundary-ID periodic constraints
106 args["boundary_conditions"]["periodic"], /*fe_space_id=*/-1);
107
108 for (const auto &[name, form] : solve_data.named_forms())
109 {
110 if (name == "augmented_lagrangian")
111 {
112 form->set_weight(0);
113 form->disable();
114 }
115 }
116
117 bool solve_symmetric_flag = false;
118 {
119 const auto &fixed_entry = macro_strain_constraint.get_fixed_entry();
120 for (int i = 0; i < dim; i++)
121 {
122 for (int j = 0; j < i; j++)
123 {
124 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())
125 {
126 logger().info("Strain entry [{},{}] and [{},{}] are not fixed, solve for symmetric strain...", i, j, j, i);
127 solve_symmetric_flag = true;
128 break;
129 }
130 }
131 if (solve_symmetric_flag)
132 break;
133 }
134 }
135
136 std::shared_ptr<solver::NLHomoProblem> homo_problem = std::make_shared<solver::NLHomoProblem>(
137 ndof,
139 *this, t, forms, solve_data.al_form, solve_symmetric_flag, polysolve::linear::Solver::create(args["solver"]["linear"], logger()), characteristic_length, characteristic_force_density, pure_mass, mesh->dimension());
141 homo_problem->add_form(solve_data.periodic_contact_form);
143 homo_problem->add_form(solve_data.strain_al_lagr_form);
144
145 solve_data.nl_problem = homo_problem;
146 solve_data.nl_problem->init(Eigen::VectorXd::Zero(homo_problem->reduced_size() + homo_problem->macro_reduced_size()));
147 solve_data.nl_problem->update_quantities(t, Eigen::VectorXd::Zero(homo_problem->reduced_size() + homo_problem->macro_reduced_size()));
148 }
149
150 void State::solve_homogenization_step(int step, Eigen::MatrixXd &sol, bool adaptive_initial_weight, UserPostStepCallback user_post_step)
151 {
152 const int dim = mesh->dimension();
153 const int ndof = n_bases * dim;
154
155 auto homo_problem = std::dynamic_pointer_cast<solver::NLHomoProblem>(solve_data.nl_problem);
156
157 Eigen::VectorXd extended_sol;
158 extended_sol.setZero(ndof + dim * dim);
159
160 if (sol.size() == extended_sol.size())
161 extended_sol = sol;
162
163 const auto &fixed_entry = macro_strain_constraint.get_fixed_entry();
164 homo_problem->set_fixed_entry({});
165 {
166 std::shared_ptr<polysolve::nonlinear::Solver> nl_solver = make_nl_solver(true);
167
168 Eigen::VectorXi al_indices = fixed_entry.array() + homo_problem->full_size();
169 Eigen::VectorXd al_values = utils::flatten(macro_strain_constraint.eval(step))(fixed_entry);
170
171 std::shared_ptr<MacroStrainLagrangianForm> lagr_form = solve_data.strain_al_lagr_form;
172 lagr_form->enable();
173
174 const double initial_weight = args["solver"]["augmented_lagrangian"]["initial_weight"];
175 const double max_weight = args["solver"]["augmented_lagrangian"]["max_weight"];
176 const double eta_tol = args["solver"]["augmented_lagrangian"]["eta"];
177 const double scaling = args["solver"]["augmented_lagrangian"]["scaling"];
178 double al_weight = initial_weight;
179
180 Eigen::VectorXd tmp_sol = homo_problem->extended_to_reduced(extended_sol);
181 const Eigen::VectorXd initial_sol = tmp_sol;
182 const double initial_error = lagr_form->compute_error(extended_sol);
183 double current_error = initial_error;
184
185 // try to enforce fixed values on macro strain
186 extended_sol(al_indices) = al_values;
187 Eigen::VectorXd reduced_sol = homo_problem->extended_to_reduced(extended_sol);
188
189 homo_problem->line_search_begin(tmp_sol, reduced_sol);
190 int al_steps = 0;
191 bool force_al = true;
192
193 lagr_form->set_initial_weight(al_weight);
194
195 while (force_al
196 || !std::isfinite(homo_problem->value(reduced_sol))
197 || !homo_problem->is_step_valid(tmp_sol, reduced_sol)
198 || !homo_problem->is_step_collision_free(tmp_sol, reduced_sol))
199 {
200 force_al = false;
201 homo_problem->line_search_end();
202
203 logger().info("Solving AL Problem with weight {}", al_weight);
204
205 homo_problem->init(tmp_sol);
206 try
207 {
208 homo_problem->normalize_forms();
209 nl_solver->minimize(*homo_problem, tmp_sol);
210 }
211 catch (const std::runtime_error &e)
212 {
213 logger().error("AL solve failed!");
214 }
215
216 extended_sol = homo_problem->reduced_to_extended(tmp_sol);
217 logger().debug("Current macro strain: {}", extended_sol.tail(dim * dim));
218
219 current_error = lagr_form->compute_error(extended_sol);
220 const double eta = 1 - sqrt(current_error / initial_error);
221
222 logger().info("Current eta = {}, current error = {}, initial error = {}", eta, current_error, initial_error);
223
224 if (eta < eta_tol && al_weight < max_weight)
225 al_weight *= scaling;
226 else
227 lagr_form->update_lagrangian(extended_sol, al_weight);
228
229 if (eta <= 0)
230 {
231 if (adaptive_initial_weight)
232 {
233 args["solver"]["augmented_lagrangian"]["initial_weight"] = args["solver"]["augmented_lagrangian"]["initial_weight"].get<double>() * scaling;
234 {
235 json tmp = json::object();
236 tmp["/solver/augmented_lagrangian/initial_weight"_json_pointer] = args["solver"]["augmented_lagrangian"]["initial_weight"];
237 }
238 logger().warn("AL weight too small, increase weight and revert solution, new initial weight is {}", args["solver"]["augmented_lagrangian"]["initial_weight"].get<double>());
239 }
240 tmp_sol = initial_sol;
241 }
242
243 // try to enforce fixed values on macro strain
244 extended_sol(al_indices) = al_values;
245 reduced_sol = homo_problem->extended_to_reduced(extended_sol);
246
247 homo_problem->line_search_begin(tmp_sol, reduced_sol);
248 }
249 homo_problem->line_search_end();
250 lagr_form->disable();
251 }
252
253 homo_problem->set_fixed_entry(fixed_entry);
254
255 Eigen::VectorXd reduced_sol = homo_problem->extended_to_reduced(extended_sol);
256
257 homo_problem->init(reduced_sol);
258 std::shared_ptr<polysolve::nonlinear::Solver> nl_solver = make_nl_solver(false);
259 homo_problem->normalize_forms();
260 nl_solver->minimize(*homo_problem, reduced_sol);
261
262 logger().info("Macro Strain: {}", extended_sol.tail(dim * dim).transpose());
263
264 // check saddle point
265 {
266 json linear_args = args["solver"]["linear"];
267 std::string solver_name = linear_args["solver"];
268 if (solver_name.find("Pardiso") != std::string::npos)
269 {
270 linear_args["solver"] = "Eigen::PardisoLLT";
271 std::unique_ptr<polysolve::linear::Solver> solver =
272 polysolve::linear::Solver::create(linear_args, logger());
273
275 homo_problem->hessian(reduced_sol, A);
276 Eigen::VectorXd x, b = Eigen::VectorXd::Zero(A.rows());
277 try
278 {
279 dirichlet_solve(
280 *solver, A, b, {}, x, A.rows(), args["output"]["data"]["stiffness_mat"], false, false, false);
281 }
282 catch (const std::runtime_error &error)
283 {
284 logger().error("The solution is a saddle point!");
285 }
286 }
287 }
288
289 sol = homo_problem->reduced_to_extended(reduced_sol);
290
291 if (user_post_step)
292 {
293 Eigen::MatrixXd disp_grad = utils::unflatten(sol.bottomRows(dim * dim), dim);
294 user_post_step(step, *this, homo_problem->reduced_to_full(reduced_sol), &disp_grad, nullptr);
295 }
296 }
297
298 void State::solve_homogenization(const int time_steps, const double t0, const double dt, Eigen::MatrixXd &sol, UserPostStepCallback user_post_step)
299 {
300 bool is_static = !is_param_valid(args, "time");
301 if (!is_static && !args["time"]["quasistatic"])
302 log_and_throw_error("Transient homogenization can only do quasi-static!");
303
305
306 const int t_offset = args["output"]["data"]["file_index_offset"].get<int>();
307 const int dim = mesh->dimension();
308 Eigen::MatrixXd extended_sol;
309 for (int t = 0; t <= time_steps; ++t)
310 {
311 double forward_solve_time = 0, remeshing_time = 0, global_relaxation_time = 0;
312
313 {
314 POLYFEM_SCOPED_TIMER(forward_solve_time);
315 solve_homogenization_step(t, extended_sol, false, user_post_step);
316 }
317 sol = extended_sol.topRows(extended_sol.size() - dim * dim) + polyfem::io::Evaluator::generate_linear_field(n_bases, mesh_nodes, utils::unflatten(extended_sol.bottomRows(dim * dim), dim));
318
319 if (is_static)
320 return;
321
322 // Always save the solution for consistency
323 save_timestep(t0 + dt * t, t + t_offset, t0, dt, sol, Eigen::MatrixXd()); // no pressure
324
325 {
326 POLYFEM_SCOPED_TIMER("Update quantities");
327
328 // solve_data.time_integrator->update_quantities(sol);
329
330 solve_data.nl_problem->update_quantities(t0 + (t + 1) * dt, sol);
331
334 }
335
336 logger().info("{}/{} t={}", t, time_steps, t0 + dt * t);
337
338 // const std::string rest_mesh_path = args["output"]["data"]["rest_mesh"].get<std::string>();
339 // if (!rest_mesh_path.empty())
340 // {
341 // Eigen::MatrixXd V;
342 // Eigen::MatrixXi F;
343 // build_mesh_matrices(V, F);
344 // polyfem::io::MshWriter::write(
345 // resolve_output_path(fmt::format(args["output"]["data"]["rest_mesh"], t)),
346 // V, F, mesh->get_body_ids(), mesh->is_volume(), /*binary=*/true);
347 // }
348
349 // const std::string &state_path = resolve_output_path(fmt::format(args["output"]["data"]["state"], t));
350 // if (!state_path.empty())
351 // solve_data.time_integrator->save_state(state_path);
352
353 // save restart file
354 save_restart_json(t0, dt, t);
355 // stats_csv.write(t, forward_solve_time, remeshing_time, global_relaxation_time, sol);
356 }
357 }
358
359} // namespace polyfem::legacy
Quadrature quadrature
int x
#define POLYFEM_SCOPED_TIMER(...)
Definition Timer.hpp:10
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)
StiffnessMatrix pure_mass
Definition State.hpp:239
const std::vector< basis::ElementBases > & geom_bases() const
Get a constant reference to the geometry mapping bases.
Definition State.hpp:263
ipc::CollisionMesh collision_mesh
IPC collision mesh.
Definition State.hpp:651
StiffnessMatrix mass
Mass matrix, it is computed only for time dependent problems.
Definition State.hpp:238
std::vector< mesh::LocalBoundary > local_boundary
mapping from elements to nodes for dirichlet boundary conditions
Definition State.hpp:540
std::vector< mesh::LocalBoundary > local_pressure_boundary
mapping from elements to nodes for pressure boundary conditions
Definition State.hpp:544
std::shared_ptr< polyfem::mesh::MeshNodes > mesh_nodes
Mapping from input nodes to FE nodes.
Definition State.hpp:228
std::shared_ptr< assembler::Mass > mass_matrix_assembler
Definition State.hpp:191
std::unordered_map< int, std::vector< mesh::LocalBoundary > > local_pressure_cavity
mapping from elements to nodes for pressure boundary conditions
Definition State.hpp:546
std::unique_ptr< mesh::Mesh > mesh
current mesh, it can be a Mesh2D or Mesh3D
Definition State.hpp:573
Eigen::MatrixXd rhs
System right-hand side.
Definition State.hpp:247
json args
main input arguments containing all defaults
Definition State.hpp:135
void solve_homogenization(const int time_steps, const double t0, const double dt, Eigen::MatrixXd &sol, UserPostStepCallback user_post_step={})
int n_pressure_bases
number of pressure bases
Definition State.hpp:215
int n_bases
number of bases
Definition State.hpp:213
void solve_homogenization_step(int step, Eigen::MatrixXd &sol, bool adaptive_initial_weight=false, UserPostStepCallback user_post_step={})
In Elasticity PDE, solve for "min W(disp_grad + \grad u)" instead of "min W(\grad u)".
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.
mesh::Obstacle obstacle
Obstacles used in collisions.
Definition State.hpp:575
assembler::AssemblyValsCache ass_vals_cache
used to store assembly values for small problems
Definition State.hpp:231
void init_homogenization_solve(const double t)
assembler::AssemblyValsCache mass_ass_vals_cache
Definition State.hpp:232
QuadratureOrders n_boundary_samples() const
quadrature used for projecting boundary conditions
Definition State.hpp:303
double characteristic_length
Definition State.hpp:243
std::shared_ptr< assembler::Assembler > assembler
assemblers
Definition State.hpp:189
double avg_mass
average system mass, used for contact with IPC
Definition State.hpp:241
std::vector< basis::ElementBases > bases
FE bases, the size is #elements.
Definition State.hpp:206
std::shared_ptr< assembler::PressureAssembler > elasticity_pressure_assembler
Definition State.hpp:197
bool is_adhesion_enabled() const
does the simulation have adhesion
Definition State.hpp:695
ipc::CollisionMesh periodic_collision_mesh
IPC collision mesh under periodic BC.
Definition State.hpp:654
Eigen::VectorXi periodic_collision_mesh_to_basis
index mapping from periodic 2x2 collision mesh to FE periodic mesh
Definition State.hpp:656
assembler::MacroStrainValue macro_strain_constraint
Definition State.hpp:793
std::vector< mesh::LocalBoundary > total_local_boundary
mapping from elements to nodes for all mesh
Definition State.hpp:538
std::shared_ptr< polysolve::nonlinear::Solver > make_nl_solver(bool for_al) const
factory to create the nl solver depending on input
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::vector< mesh::LocalBoundary > local_neumann_boundary
mapping from elements to nodes for neumann boundary conditions
Definition State.hpp:542
std::vector< int > boundary_nodes
list of boundary nodes
Definition State.hpp:534
solver::SolveData solve_data
timedependent stuff cached
Definition State.hpp:380
Eigen::VectorXi in_node_to_node
Inpute nodes (including high-order) to polyfem nodes, only for isoparametric.
Definition State.hpp:557
double characteristic_force_density
Definition State.hpp:244
std::vector< std::shared_ptr< Form > > init_forms(const Units &units, const int dim, const double t, const Eigen::VectorXi &in_node_to_node, 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 unsigned conservative_max_iter, 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 QuadratureOrders &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 std::vector< std::string > &hard_constraint_files, const std::vector< json > &soft_constraint_files, const json &zero_mean, const bool contact_enabled, const ipc::CollisionMesh &collision_mesh, const double dhat, const double avg_mass, const bool use_area_weighting, const bool use_improved_max_operator, const bool use_physical_barrier, const json &barrier_stiffness, const double initial_barrier_stiffness, const ipc::BroadPhaseMethod broad_phase, const double ccd_tolerance, const long ccd_max_iterations, const bool enable_shape_derivatives, const bool use_gcp_formulation, const double alpha_t, const double alpha_n, const bool use_adaptive_dhat, const double min_distance_ratio, const bool adhesion_enabled, const double dhat_p, const double dhat_a, const double Y, const double tangential_adhesion_coefficient, const double epsa, const int tangential_adhesion_iterations, const assembler::MacroStrainValue &macro_strain_constraint, const bool periodic_contact, const Eigen::VectorXi &tiled_to_single, const double friction_coefficient, const double epsv, const int friction_iterations, const json &rayleigh_damping, const BCLumpingMode al_lumping=BCLumpingMode::ROW_SUM, const mesh::Mesh *periodic_mesh=nullptr, const std::vector< mesh::LocalBoundary > *periodic_local_boundary=nullptr, const json &periodic_conditions=json::array(), const int fe_space_id=-1)
Initialize the forms and return a vector of pointers to them.
Definition SolveData.cpp:35
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
std::function< void(int step, State &state, const Eigen::MatrixXd &sol, const Eigen::MatrixXd *disp_grad, const Eigen::MatrixXd *pressure)> UserPostStepCallback
User callback at the end of every solver step.
Definition State.hpp:86
bool is_param_valid(const json &params, 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.
Definition Logger.cpp:44
nlohmann::json json
Definition Common.hpp:9
void log_and_throw_error(const std::string &msg)
Definition Logger.cpp:73
Eigen::SparseMatrix< double, Eigen::ColMajor > StiffnessMatrix
Definition Types.hpp:24