8#include <polysolve/linear/FEMSolver.hpp>
25#include <ipc/barrier/barrier.hpp>
26#include <ipc/utils/local_to_global.hpp>
27#include <ipc/potentials/friction_potential.hpp>
30#include <unsupported/Eigen/SparseExtra>
45 reduced_mat.resize(mat.rows(), mat.cols());
47 std::vector<bool> mask(mat.rows(),
false);
51 std::vector<Eigen::Triplet<double>> coeffs;
52 for (
int k = 0; k < mat.outerSize(); ++k)
54 for (StiffnessMatrix::InnerIterator it(mat, k); it; ++it)
58 if (it.row() == it.col())
59 coeffs.emplace_back(it.row(), it.col(), 1.0);
62 coeffs.emplace_back(it.row(), it.col(), it.value());
65 reduced_mat.setFromTriplets(coeffs.begin(), coeffs.end());
71 vertices.setZero(
mesh->n_vertices(),
mesh->dimension());
73 for (
int v = 0; v <
mesh->n_vertices(); v++)
74 vertices.row(v) =
mesh->point(v);
79 assert(
mesh->is_simplicial());
84 int dim =
mesh->dimension();
85 elements.setZero(gbases.size(), dim + 1);
86 for (
int e = 0; e < gbases.size(); e++)
89 for (
const auto &gbs : gbases[e].bases)
90 elements(e, i++) = node_to_primitive_map[gbs.global()[0].index];
96 assert(vertex.size() ==
mesh->dimension());
97 mesh->set_point(v_id, vertex);
103 if (current_step == 0)
106 ipc::Collisions cur_collision_set;
107 ipc::FrictionCollisions cur_friction_set;
111 if (!
problem->is_time_dependent() || current_step > 0)
119 cur_collision_set = ipc::Collisions();
120 cur_friction_set = ipc::FrictionCollisions();
123 if (
problem->is_time_dependent())
125 if (
args[
"time"][
"quasistatic"].get<bool>())
131 Eigen::MatrixXd vel, acc;
132 if (current_step == 0)
142 vel = euler_integrator->
v_prev();
147 acc.setZero(
ndof(), 1);
166 if (
problem->is_time_dependent())
190 Eigen::VectorXd reduced;
193 std::shared_ptr<solver::NLHomoProblem> homo_problem = std::dynamic_pointer_cast<solver::NLHomoProblem>(
solve_data.
nl_problem);
194 reduced = homo_problem->full_to_reduced(sol, disp_grad);
207 assert(force_step > 0);
208 assert(force_step > sol_step);
221 if (
problem->is_time_dependent())
225 if (sol_step == force_step - 1)
231 const Eigen::MatrixXd surface_velocities = (surface_solution - surface_solution_prev) / dt;
232 const double dv_dut = -1 / dt;
239 surface_solution_prev,
243 ipc::FrictionPotential::DiffWRT::LAGGED_DISPLACEMENTS)
248 surface_solution_prev,
252 ipc::FrictionPotential::DiffWRT::VELOCITIES)
305 damping_prev_assembler->assemble_hessian(
mesh->is_volume(),
n_bases,
false,
bases,
geom_bases(),
ass_vals_cache, force_step *
args[
"time"][
"dt"].get<double>() +
args[
"time"][
"t0"].get<double>(), dt, u, u_prev, mat_cache, damping_hessian_prev);
307 hessian_prev += damping_hessian_prev;
310 if (sol_step == force_step - 1)
314 hessian_prev += body_force_hessian;
327 if (
problem->is_time_dependent())
335 Eigen::MatrixXd b = adjoint_rhs;
337 Eigen::MatrixXd adjoint;
343 const int full_size = A.rows();
344 const int problem_dim =
problem->is_scalar() ? 1 :
mesh->dimension();
345 int precond_num = problem_dim *
n_bases;
347 b.conservativeResizeLike(Eigen::MatrixXd::Zero(A.rows(), b.cols()));
349 std::vector<int> boundary_nodes_tmp;
359 adjoint.setZero(
ndof(), adjoint_rhs.cols());
360 for (
int i = 0; i < b.cols(); i++)
362 Eigen::VectorXd
x, tmp;
367 adjoint.col(i) =
periodic_bc->periodic_to_full(full_size,
x);
374 auto solver = polysolve::linear::Solver::create(
args[
"solver"][
"adjoint_linear"],
adjoint_logger());
377 solver->analyze_pattern(A, A.rows());
378 solver->factorize(A);
386 adjoint.setZero(
ndof(), adjoint_rhs.cols());
387 for (
int i = 0; i < b.cols(); i++)
389 Eigen::MatrixXd tmp = b.col(i);
392 x.setZero(tmp.size());
393 solver->solve(tmp,
x);
402 adjoint.setZero(adjoint_rhs.rows(), adjoint_rhs.cols());
403 for (
int i = 0; i < b.cols(); i++)
405 Eigen::MatrixXd tmp = b.col(i);
408 x.setZero(tmp.size());
409 solver->solve(tmp,
x);
410 x.conservativeResize(adjoint.rows());
422 const double dt =
args[
"time"][
"dt"];
423 const int time_steps =
args[
"time"][
"time_steps"];
426 if (
args[
"time"][
"integrator"].is_string())
428 else if (
args[
"time"][
"integrator"][
"type"] ==
"ImplicitEuler")
430 else if (
args[
"time"][
"integrator"][
"type"] ==
"BDF")
431 bdf_order =
args[
"time"][
"integrator"][
"steps"].get<
int>();
435 assert(adjoint_rhs.cols() == time_steps + 1);
437 const int cols_per_adjoint = time_steps + 1;
438 Eigen::MatrixXd adjoints;
439 adjoints.setZero(
ndof(), cols_per_adjoint * 2);
445 Eigen::MatrixXd sum_alpha_p, sum_alpha_nu;
446 for (
int i = time_steps; i >= 0; --i)
449 sum_alpha_p.setZero(
ndof(), 1);
450 sum_alpha_nu.setZero(
ndof(), 1);
452 const int num = std::min(bdf_order, time_steps - i);
454 Eigen::VectorXd bdf_coeffs = Eigen::VectorXd::Zero(num);
455 for (
int j = 0; j < bdf_order && i + j < time_steps; ++j)
458 sum_alpha_p = adjoints.middleCols(i + 1, num) * bdf_coeffs;
459 sum_alpha_nu = adjoints.middleCols(cols_per_adjoint + i + 1, num) * bdf_coeffs;
462 Eigen::VectorXd rhs_ = -reduced_mass.transpose() * sum_alpha_nu - adjoint_rhs.col(i);
463 for (
int j = 1; j <= bdf_order; j++)
465 if (i + j > time_steps)
472 rhs_ += -gradu_h_prev.transpose() * tmp;
479 rhs_ += (1. / beta_dt) * (
diff_cached.
gradu_h(i) - reduced_mass).transpose() * sum_alpha_p;
483 Eigen::VectorXd b_ = rhs_;
486 auto solver = polysolve::linear::Solver::create(
args[
"solver"][
"adjoint_linear"],
adjoint_logger());
489 dirichlet_solve(*solver, A, b_,
boundary_nodes,
x, A.rows(),
"",
false,
false,
false);
490 adjoints.col(i + cols_per_adjoint) =
x;
495 if (i + 1 < cols_per_adjoint)
497 if (i + 2 < cols_per_adjoint)
502 adjoints.col(i) = beta_dt * adjoints.col(i + cols_per_adjoint) - sum_alpha_p;
506 adjoints.col(i) = -reduced_mass.transpose() * sum_alpha_p;
507 adjoints.col(i + cols_per_adjoint) = rhs_;
520 const int e = lb.element_id();
521 for (
int i = 0; i < lb.size(); ++i)
523 const int primitive_global_id = lb.global_primitive_id(i);
524 const int boundary_id =
mesh->get_boundary_id(primitive_global_id);
525 const auto nodes = gbases[e].local_nodes_for_primitive(primitive_global_id, *
mesh);
527 if (boundary_id == surface_selection)
529 for (
long n = 0; n < nodes.size(); ++n)
531 const int g_id = gbases[e].bases[nodes(n)].global()[0].index;
533 if (std::count(node_ids.begin(), node_ids.end(), g_id) == 0)
534 node_ids.push_back(g_id);
548 const int e = lb.element_id();
549 for (
int i = 0; i < lb.size(); ++i)
551 const int primitive_global_id = lb.global_primitive_id(i);
552 const auto nodes = gbases[e].local_nodes_for_primitive(primitive_global_id, *
mesh);
554 for (
long n = 0; n < nodes.size(); ++n)
556 const int g_id = gbases[e].bases[nodes(n)].global()[0].index;
558 if (std::count(node_ids.begin(), node_ids.end(), g_id) == 0)
559 node_ids.push_back(g_id);
570 for (
int e = 0; e < gbases.size(); e++)
572 const int body_id =
mesh->get_body_id(e);
573 if (body_id == volume_selection)
574 for (
const auto &gbs : gbases[e].bases)
575 for (
const auto &g : gbs.global())
576 node_ids.push_back(g.index);
void get_vertices(Eigen::MatrixXd &vertices) const
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)
assembler::AssemblyValsCache ass_vals_cache
used to store assembly values for small problems
void set_mesh_vertex(int v_id, const Eigen::VectorXd &vertex)
const std::vector< basis::ElementBases > & geom_bases() const
Get a constant reference to the geometry mapping bases.
std::shared_ptr< assembler::ViscousDamping > damping_assembler
std::shared_ptr< assembler::Assembler > assembler
assemblers
ipc::CollisionMesh collision_mesh
IPC collision mesh.
solver::CacheLevel optimization_enabled
bool is_homogenization() const
Eigen::MatrixXd solve_static_adjoint(const Eigen::MatrixXd &adjoint_rhs) const
void compute_force_jacobian(const Eigen::MatrixXd &sol, const Eigen::MatrixXd &disp_grad, StiffnessMatrix &hessian)
std::unique_ptr< mesh::Mesh > mesh
current mesh, it can be a Mesh2D or Mesh3D
StiffnessMatrix mass
Mass matrix, it is computed only for time dependent problems.
bool has_periodic_bc() const
std::shared_ptr< assembler::Problem > problem
current problem, it contains rhs and bc
std::vector< int > node_to_primitive() const
json args
main input arguments containing all defaults
solver::DiffCache diff_cached
std::vector< basis::ElementBases > bases
FE bases, the size is #elements.
void solve_adjoint_cached(const Eigen::MatrixXd &rhs)
Eigen::MatrixXd solve_adjoint(const Eigen::MatrixXd &rhs) const
void get_elements(Eigen::MatrixXi &elements) const
void build_stiffness_mat(StiffnessMatrix &stiffness)
utility that builds the stiffness matrix and collects stats, used only for linear problems
void compute_volume_node_ids(const int volume_selection, std::vector< int > &node_ids) const
std::vector< mesh::LocalBoundary > total_local_boundary
mapping from elements to nodes for all mesh
std::vector< int > boundary_nodes
list of boundary nodes
solver::SolveData solve_data
timedependent stuff cached
std::unique_ptr< polysolve::linear::Solver > lin_solver_cached
std::shared_ptr< assembler::ViscousDampingPrev > damping_prev_assembler
bool is_contact_enabled() const
does the simulation has contact
Eigen::MatrixXd solve_transient_adjoint(const Eigen::MatrixXd &adjoint_rhs) const
void compute_force_jacobian_prev(const int force_step, const int sol_step, StiffnessMatrix &hessian_prev) const
void compute_total_surface_node_ids(std::vector< int > &node_ids) const
void compute_surface_node_ids(const int surface_selection, std::vector< int > &node_ids) const
Eigen::MatrixXd rhs
System right-hand side.
const StiffnessMatrix & gradu_h(int step) const
int bdf_order(int step) const
void cache_quantities_quasistatic(const int cur_step, const Eigen::MatrixXd &u, const StiffnessMatrix &gradu_h, const ipc::Collisions &contact_set, const Eigen::MatrixXd &disp_grad)
void init(const int dimension, const int ndof, const int n_time_steps=0)
void cache_quantities_static(const Eigen::MatrixXd &u, const StiffnessMatrix &gradu_h, const ipc::Collisions &contact_set, const ipc::FrictionCollisions &friction_constraint_set, const Eigen::MatrixXd &disp_grad)
void cache_adjoints(const Eigen::MatrixXd &adjoint_mat)
void cache_quantities_transient(const int cur_step, const int cur_bdf_order, const Eigen::MatrixXd &u, const Eigen::MatrixXd &v, const Eigen::MatrixXd &acc, const StiffnessMatrix &gradu_h, const ipc::Collisions &collision_set, const ipc::FrictionCollisions &friction_collision_set)
Eigen::VectorXd u(int step) const
const ipc::FrictionCollisions & friction_collision_set(int step) const
std::shared_ptr< solver::FrictionForm > friction_form
std::shared_ptr< solver::BodyForm > body_form
std::shared_ptr< solver::NLProblem > nl_problem
std::shared_ptr< solver::ContactForm > contact_form
std::shared_ptr< time_integrator::ImplicitTimeIntegrator > time_integrator
Backward Differential Formulas.
static double betas(const int i)
Retrieve the value of beta used for BDF with i steps.
Eigen::VectorXd weighted_sum_v_prevs() const
Compute the weighted sum of the previous velocities.
static const std::vector< double > & alphas(const int i)
Retrieve the alphas used for BDF with i steps.
Implicit Euler time integrator of a second order ODE (equivently a system of coupled first order ODEs...
const Eigen::VectorXd & v_prev() const
Get the most recent previous velocity value.
Eigen::MatrixXd unflatten(const Eigen::VectorXd &x, int dim)
Unflatten rowwises, so every dim elements in x become a row.
spdlog::logger & adjoint_logger()
Retrieves the current logger for adjoint.
void log_and_throw_adjoint_error(const std::string &msg)
void log_and_throw_error(const std::string &msg)
Eigen::SparseMatrix< double, Eigen::ColMajor > StiffnessMatrix