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 n_bases, mesh_nodes, t, forms, solve_data.al_form, solve_symmetric_flag,
140 polysolve::linear::Solver::create(args["solver"]["linear"], logger()),
143 homo_problem->add_form(solve_data.periodic_contact_form);
145 homo_problem->add_form(solve_data.strain_al_lagr_form);
146
147 solve_data.nl_problem = homo_problem;
148 solve_data.nl_problem->init(Eigen::VectorXd::Zero(homo_problem->reduced_size() + homo_problem->macro_reduced_size()));
149 solve_data.nl_problem->update_quantities(t, Eigen::VectorXd::Zero(homo_problem->reduced_size() + homo_problem->macro_reduced_size()));
150 }
151
152 void State::solve_homogenization_step(int step, Eigen::MatrixXd &sol, bool adaptive_initial_weight, UserPostStepCallback user_post_step)
153 {
154 const int dim = mesh->dimension();
155 const int ndof = n_bases * dim;
156
157 auto homo_problem = std::dynamic_pointer_cast<solver::NLHomoProblem>(solve_data.nl_problem);
158
159 Eigen::VectorXd extended_sol;
160 extended_sol.setZero(ndof + dim * dim);
161
162 if (sol.size() == extended_sol.size())
163 extended_sol = sol;
164
165 const auto &fixed_entry = macro_strain_constraint.get_fixed_entry();
166 homo_problem->set_fixed_entry({});
167 {
168 std::shared_ptr<polysolve::nonlinear::Solver> nl_solver = make_nl_solver(true);
169
170 Eigen::VectorXi al_indices = fixed_entry.array() + homo_problem->full_size();
171 Eigen::VectorXd al_values = utils::flatten(macro_strain_constraint.eval(step))(fixed_entry);
172
173 std::shared_ptr<MacroStrainLagrangianForm> lagr_form = solve_data.strain_al_lagr_form;
174 lagr_form->enable();
175
176 const double initial_weight = args["solver"]["augmented_lagrangian"]["initial_weight"];
177 const double max_weight = args["solver"]["augmented_lagrangian"]["max_weight"];
178 const double eta_tol = args["solver"]["augmented_lagrangian"]["eta"];
179 const double scaling = args["solver"]["augmented_lagrangian"]["scaling"];
180 double al_weight = initial_weight;
181
182 Eigen::VectorXd tmp_sol = homo_problem->extended_to_reduced(extended_sol);
183 const Eigen::VectorXd initial_sol = tmp_sol;
184 const double initial_error = lagr_form->compute_error(extended_sol);
185 double current_error = initial_error;
186
187 // try to enforce fixed values on macro strain
188 extended_sol(al_indices) = al_values;
189 Eigen::VectorXd reduced_sol = homo_problem->extended_to_reduced(extended_sol);
190
191 homo_problem->line_search_begin(tmp_sol, reduced_sol);
192 int al_steps = 0;
193 bool force_al = true;
194
195 lagr_form->set_initial_weight(al_weight);
196
197 while (force_al
198 || !std::isfinite(homo_problem->value(reduced_sol))
199 || !homo_problem->is_step_valid(tmp_sol, reduced_sol)
200 || !homo_problem->is_step_collision_free(tmp_sol, reduced_sol))
201 {
202 force_al = false;
203 homo_problem->line_search_end();
204
205 logger().info("Solving AL Problem with weight {}", al_weight);
206
207 homo_problem->init(tmp_sol);
208 try
209 {
210 homo_problem->normalize_forms();
211 nl_solver->minimize(*homo_problem, tmp_sol);
212 }
213 catch (const std::runtime_error &e)
214 {
215 logger().error("AL solve failed!");
216 }
217
218 extended_sol = homo_problem->reduced_to_extended(tmp_sol);
219 logger().debug("Current macro strain: {}", extended_sol.tail(dim * dim));
220
221 current_error = lagr_form->compute_error(extended_sol);
222 const double eta = 1 - sqrt(current_error / initial_error);
223
224 logger().info("Current eta = {}, current error = {}, initial error = {}", eta, current_error, initial_error);
225
226 if (eta < eta_tol && al_weight < max_weight)
227 al_weight *= scaling;
228 else
229 lagr_form->update_lagrangian(extended_sol, al_weight);
230
231 if (eta <= 0)
232 {
233 if (adaptive_initial_weight)
234 {
235 args["solver"]["augmented_lagrangian"]["initial_weight"] = args["solver"]["augmented_lagrangian"]["initial_weight"].get<double>() * scaling;
236 {
237 json tmp = json::object();
238 tmp["/solver/augmented_lagrangian/initial_weight"_json_pointer] = args["solver"]["augmented_lagrangian"]["initial_weight"];
239 }
240 logger().warn("AL weight too small, increase weight and revert solution, new initial weight is {}", args["solver"]["augmented_lagrangian"]["initial_weight"].get<double>());
241 }
242 tmp_sol = initial_sol;
243 }
244
245 // try to enforce fixed values on macro strain
246 extended_sol(al_indices) = al_values;
247 reduced_sol = homo_problem->extended_to_reduced(extended_sol);
248
249 homo_problem->line_search_begin(tmp_sol, reduced_sol);
250 }
251 homo_problem->line_search_end();
252 lagr_form->disable();
253 }
254
255 homo_problem->set_fixed_entry(fixed_entry);
256
257 Eigen::VectorXd reduced_sol = homo_problem->extended_to_reduced(extended_sol);
258
259 homo_problem->init(reduced_sol);
260 std::shared_ptr<polysolve::nonlinear::Solver> nl_solver = make_nl_solver(false);
261 homo_problem->normalize_forms();
262 nl_solver->minimize(*homo_problem, reduced_sol);
263
264 logger().info("Macro Strain: {}", extended_sol.tail(dim * dim).transpose());
265
266 // check saddle point
267 {
268 json linear_args = args["solver"]["linear"];
269 std::string solver_name = linear_args["solver"];
270 if (solver_name.find("Pardiso") != std::string::npos)
271 {
272 linear_args["solver"] = "Eigen::PardisoLLT";
273 std::unique_ptr<polysolve::linear::Solver> solver =
274 polysolve::linear::Solver::create(linear_args, logger());
275
277 homo_problem->hessian(reduced_sol, A);
278 Eigen::VectorXd x, b = Eigen::VectorXd::Zero(A.rows());
279 try
280 {
281 dirichlet_solve(
282 *solver, A, b, {}, x, A.rows(), args["output"]["data"]["stiffness_mat"], false, false, false);
283 }
284 catch (const std::runtime_error &error)
285 {
286 logger().error("The solution is a saddle point!");
287 }
288 }
289 }
290
291 sol = homo_problem->reduced_to_extended(reduced_sol);
292
293 if (user_post_step)
294 {
295 Eigen::MatrixXd disp_grad = utils::unflatten(sol.bottomRows(dim * dim), dim);
296 user_post_step(step, *this, homo_problem->reduced_to_full(reduced_sol), &disp_grad, nullptr);
297 }
298 }
299
300 void State::solve_homogenization(const int time_steps, const double t0, const double dt, Eigen::MatrixXd &sol, UserPostStepCallback user_post_step)
301 {
302 bool is_static = !is_param_valid(args, "time");
303 if (!is_static && !args["time"]["quasistatic"])
304 log_and_throw_error("Transient homogenization can only do quasi-static!");
305
307
308 const int t_offset = args["output"]["data"]["file_index_offset"].get<int>();
309 const int dim = mesh->dimension();
310 Eigen::MatrixXd extended_sol;
311 for (int t = 0; t <= time_steps; ++t)
312 {
313 double forward_solve_time = 0, remeshing_time = 0, global_relaxation_time = 0;
314
315 {
316 POLYFEM_SCOPED_TIMER(forward_solve_time);
317 solve_homogenization_step(t, extended_sol, false, user_post_step);
318 }
319 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));
320
321 if (is_static)
322 return;
323
324 // Always save the solution for consistency
325 save_timestep(t0 + dt * t, t + t_offset, t0, dt, sol, Eigen::MatrixXd()); // no pressure
326
327 {
328 POLYFEM_SCOPED_TIMER("Update quantities");
329
330 // solve_data.time_integrator->update_quantities(sol);
331
332 solve_data.nl_problem->update_quantities(t0 + (t + 1) * dt, sol);
333
336 }
337
338 logger().info("{}/{} t={}", t, time_steps, t0 + dt * t);
339
340 // const std::string rest_mesh_path = args["output"]["data"]["rest_mesh"].get<std::string>();
341 // if (!rest_mesh_path.empty())
342 // {
343 // Eigen::MatrixXd V;
344 // Eigen::MatrixXi F;
345 // build_mesh_matrices(V, F);
346 // polyfem::io::MshWriter::write(
347 // resolve_output_path(fmt::format(args["output"]["data"]["rest_mesh"], t)),
348 // V, F, mesh->get_body_ids(), mesh->is_volume(), /*binary=*/true);
349 // }
350
351 // const std::string &state_path = resolve_output_path(fmt::format(args["output"]["data"]["state"], t));
352 // if (!state_path.empty())
353 // solve_data.time_integrator->save_state(state_path);
354
355 // save restart file
356 save_restart_json(t0, dt, t);
357 // stats_csv.write(t, forward_solve_time, remeshing_time, global_relaxation_time, sol);
358 }
359 }
360
361} // 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