41 if (state.
args[
"time"][
"integrator"].is_string())
43 if (state.
args[
"time"][
"integrator"][
"type"] ==
"ImplicitEuler")
45 if (state.
args[
"time"][
"integrator"][
"type"] ==
"BDF")
46 return state.
args[
"time"][
"integrator"][
"steps"].get<
int>();
57 double dot(
const Eigen::MatrixXd &A,
const Eigen::MatrixXd &B) {
return (A.array() * B.array()).sum(); }
59 class LocalThreadScalarStorage
66 LocalThreadScalarStorage()
72 class LocalThreadVecStorage
79 LocalThreadVecStorage(
const int size)
89 T triangle_area(
const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> &
V)
91 Eigen::Matrix<T, Eigen::Dynamic, 1> l1 =
V.row(1) -
V.row(0);
92 Eigen::Matrix<T, Eigen::Dynamic, 1> l2 =
V.row(2) -
V.row(0);
93 T area = 0.5 * sqrt(pow(l1(1) * l2(2) - l1(2) * l2(1), 2) + pow(l1(0) * l2(2) - l1(2) * l2(0), 2) + pow(l1(1) * l2(0) - l1(0) * l2(1), 2));
97 Eigen::MatrixXd triangle_area_grad(
const Eigen::MatrixXd &
F)
100 Eigen::Matrix<Diff, Eigen::Dynamic, Eigen::Dynamic> full_diff(
F.rows(),
F.cols());
101 for (
int i = 0; i <
F.rows(); i++)
102 for (
int j = 0; j <
F.cols(); j++)
103 full_diff(i, j) =
Diff(i + j *
F.rows(),
F(i, j));
106 Eigen::MatrixXd
grad(
F.rows(),
F.cols());
107 for (
int i = 0; i <
F.rows(); ++i)
108 for (
int j = 0; j <
F.cols(); ++j)
109 grad(i, j) = reduced_diff.getGradient()(i + j *
F.rows());
114 template <
typename T>
115 T line_length(
const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> &
V)
117 Eigen::Matrix<T, Eigen::Dynamic, 1> L =
V.row(1) -
V.row(0);
122 Eigen::MatrixXd line_length_grad(
const Eigen::MatrixXd &
F)
125 Eigen::Matrix<Diff, Eigen::Dynamic, Eigen::Dynamic> full_diff(
F.rows(),
F.cols());
126 for (
int i = 0; i <
F.rows(); i++)
127 for (
int j = 0; j <
F.cols(); j++)
128 full_diff(i, j) =
Diff(i + j *
F.rows(),
F(i, j));
129 auto reduced_diff = line_length(full_diff);
131 Eigen::MatrixXd
grad(
F.rows(),
F.cols());
132 for (
int i = 0; i <
F.rows(); ++i)
133 for (
int j = 0; j <
F.cols(); ++j)
134 grad(i, j) = reduced_diff.getGradient()(i + j *
F.rows());
139 template <
typename T>
140 Eigen::Matrix<T, 2, 1> edge_normal(
const Eigen::Matrix<T, 4, 1> &
V)
142 Eigen::Matrix<T, 2, 1> v1 =
V.segment(0, 2);
143 Eigen::Matrix<T, 2, 1> v2 =
V.segment(2, 2);
144 Eigen::Matrix<T, 2, 1> normal = v1 - v2;
146 normal = normal / normal.norm();
150 template <
typename T>
151 Eigen::Matrix<T, 3, 1> face_normal(
const Eigen::Matrix<T, 9, 1> &
V)
153 Eigen::Matrix<T, 3, 1> v1 =
V.segment(0, 3);
154 Eigen::Matrix<T, 3, 1> v2 =
V.segment(3, 3);
155 Eigen::Matrix<T, 3, 1> v3 =
V.segment(6, 3);
156 Eigen::Matrix<T, 3, 1> normal = (v2 - v1).
cross(v3 - v1);
157 normal = normal / normal.norm();
161 Eigen::MatrixXd extract_lame_params(
const std::map<std::string, Assembler::ParamFunc> &lame_params,
const int e,
const int t,
const Eigen::MatrixXd &local_pts,
const Eigen::MatrixXd &pts)
163 Eigen::MatrixXd params = Eigen::MatrixXd::Zero(local_pts.rows(), 2);
165 auto search_lambda = lame_params.find(
"lambda");
166 auto search_mu = lame_params.find(
"mu");
168 if (search_lambda == lame_params.end() || search_mu == lame_params.end())
171 for (
int p = 0; p < local_pts.rows(); p++)
173 params(p, 0) = search_lambda->second(local_pts.row(p), pts.row(p), t, e);
174 params(p, 1) = search_mu->second(local_pts.row(p), pts.row(p), t, e);
184 const Eigen::MatrixXd &solution,
185 const std::set<int> &interested_ids,
189 const auto &bases = state.
bases;
192 const int dim = state.
mesh->dimension();
193 const int actual_dim = state.
problem->is_scalar() ? 1 : dim;
194 const int n_elements = int(bases.size());
195 const double t0 = state.
problem->is_time_dependent() ? state.
args[
"time"][
"t0"].get<
double>() : 0.0;
196 const double dt = state.
problem->is_time_dependent() ? state.
args[
"time"][
"dt"].get<
double>() : 0.0;
206 params.
t = dt * cur_step + t0;
207 params.
step = cur_step;
209 Eigen::MatrixXd u, grad_u;
210 Eigen::MatrixXd result;
212 for (
int e = start; e < end; ++e)
214 if (interested_ids.size() != 0 && interested_ids.find(state.
mesh->get_body_id(e)) == interested_ids.end())
230 local_storage.val += dot(result, local_storage.da);
233 for (
const LocalThreadScalarStorage &local_storage : storage)
234 integral += local_storage.val;
240 LocalThreadScalarStorage &local_storage = utils::get_local_thread_storage(storage, thread_id);
243 Eigen::MatrixXd points, normal;
244 Eigen::VectorXd weights;
246 Eigen::MatrixXd u, grad_u;
247 Eigen::MatrixXd result;
248 IntegrableFunctional::ParameterType params;
249 params.t = dt * cur_step + t0;
250 params.step = cur_step;
252 for (int lb_id = start; lb_id < end; ++lb_id)
254 const auto &lb = state.total_local_boundary[lb_id];
255 const int e = lb.element_id();
257 for (int i = 0; i < lb.size(); i++)
259 const int global_primitive_id = lb.global_primitive_id(i);
260 if (interested_ids.size() != 0 && interested_ids.find(state.mesh->get_boundary_id(global_primitive_id)) == interested_ids.end())
263 utils::BoundarySampler::boundary_quadrature(lb, state.n_boundary_samples(), *state.mesh, i, false, uv, points, normal, weights);
265 assembler::ElementAssemblyValues &vals = local_storage.vals;
266 vals.compute(e, state.mesh->is_volume(), points, bases[e], gbases[e]);
267 io::Evaluator::interpolate_at_local_vals(e, dim, actual_dim, vals, solution, u, grad_u);
269 const Eigen::MatrixXd lame_params = extract_lame_params(state.assembler->parameters(), e, params.t, points, vals.val);
272 params.body_id = state.mesh->get_body_id(e);
273 params.boundary_id = state.mesh->get_boundary_id(global_primitive_id);
274 j.evaluate(lame_params, points, vals.val, u, grad_u, normal, vals, params, result);
276 local_storage.val += dot(result, weights);
280 for (
const LocalThreadScalarStorage &local_storage : storage)
281 integral += local_storage.val;
285 std::vector<bool> traversed(state.
n_bases,
false);
287 params.
t = dt * cur_step + t0;
288 params.
step = cur_step;
289 for (
int e = 0; e < bases.size(); e++)
291 const auto &bs = bases[e];
292 for (
int i = 0; i < bs.bases.size(); i++)
294 const auto &b = bs.bases[i];
295 assert(b.global().size() == 1);
296 const auto &g = b.global()[0];
297 if (traversed[g.index])
300 const Eigen::MatrixXd lame_params = extract_lame_params(state.
assembler->parameters(), e, params.
t, Eigen::MatrixXd::Zero(1, dim) , g.node);
302 params.
node = g.index;
306 j.evaluate(lame_params, Eigen::MatrixXd::Zero(1, dim) , g.node, solution.block(g.index * dim, 0, dim, 1).transpose(), Eigen::MatrixXd::Zero(1, dim * actual_dim) , Eigen::MatrixXd::Zero(0, 0) ,
assembler::ElementAssemblyValues(), params,
val);
308 traversed[g.index] =
true;
316 void AdjointTools::compute_shape_derivative_functional_term(
318 const Eigen::MatrixXd &solution,
320 const std::set<int> &interested_ids,
322 Eigen::VectorXd &term,
323 const int cur_time_step)
326 const auto &bases = state.
bases;
327 const int dim = state.
mesh->dimension();
328 const int actual_dim = state.
problem->is_scalar() ? 1 : dim;
329 const double t0 = state.
problem->is_time_dependent() ? state.
args[
"time"][
"t0"].get<
double>() : 0.0;
330 const double dt = state.
problem->is_time_dependent() ? state.
args[
"time"][
"dt"].get<
double>() : 0.0;
332 const int n_elements = int(bases.size());
335 auto storage = utils::create_thread_storage(LocalThreadVecStorage(term.size()));
337 if (spatial_integral_type == SpatialIntegralType::Volume)
339 utils::maybe_parallel_for(n_elements, [&](
int start,
int end,
int thread_id) {
340 LocalThreadVecStorage &local_storage = utils::get_local_thread_storage(storage, thread_id);
342 Eigen::MatrixXd u, grad_u, j_val, dj_dgradu, dj_dx;
345 params.
t = cur_time_step * dt + t0;
346 params.
step = cur_time_step;
348 for (
int e = start; e < end; ++e)
350 if (interested_ids.size() != 0 && interested_ids.find(state.
mesh->get_body_id(e)) == interested_ids.end())
355 io::Evaluator::interpolate_at_local_vals(e, dim, actual_dim,
vals, solution, u, grad_u);
376 Eigen::MatrixXd tau_q, grad_u_q;
377 for (
auto &v :
gvals.basis_values)
379 for (
int q = 0; q < local_storage.da.size(); ++q)
381 local_storage.vec.block(v.global[0].index * dim, 0, dim, 1) += (j_val(q) * local_storage.da(q)) * v.grad_t_m.row(q).transpose();
384 local_storage.vec.block(v.global[0].index * dim, 0, dim, 1) += (v.val(q) * local_storage.da(q)) * dj_dx.row(q).transpose();
388 if (dim == actual_dim)
395 tau_q = dj_dgradu.row(q);
396 grad_u_q = grad_u.row(q);
398 for (
int d = 0; d < dim; d++)
399 local_storage.vec(v.global[0].index * dim + d) += -dot(tau_q, grad_u_q.col(d) * v.grad_t_m.row(q)) * local_storage.da(q);
406 else if (spatial_integral_type == SpatialIntegralType::Surface)
408 utils::maybe_parallel_for(state.
total_local_boundary.size(), [&](
int start,
int end,
int thread_id) {
409 LocalThreadVecStorage &local_storage = utils::get_local_thread_storage(storage, thread_id);
411 Eigen::MatrixXd uv, points, normal;
412 Eigen::VectorXd &weights = local_storage.da;
414 Eigen::MatrixXd u, grad_u, x, grad_x, j_val, dj_dgradu, dj_dgradx, dj_dx;
416 IntegrableFunctional::ParameterType params;
417 params.t = cur_time_step * dt + t0;
418 params.step = cur_time_step;
420 for (int lb_id = start; lb_id < end; ++lb_id)
422 const auto &lb = state.total_local_boundary[lb_id];
423 const int e = lb.element_id();
425 for (int i = 0; i < lb.size(); i++)
427 const int global_primitive_id = lb.global_primitive_id(i);
428 if (interested_ids.size() != 0 && interested_ids.find(state.mesh->get_boundary_id(global_primitive_id)) == interested_ids.end())
431 utils::BoundarySampler::boundary_quadrature(lb, state.n_boundary_samples(), *state.mesh, i, false, uv, points, normal, weights);
433 assembler::ElementAssemblyValues &vals = local_storage.vals;
434 io::Evaluator::interpolate_at_local_vals(*state.mesh, state.problem->is_scalar(), bases, gbases, e, points, solution, u, grad_u);
437 vals.compute(e, state.mesh->is_volume(), points, gbases[e], gbases[e]);
441 const int n_loc_bases_ = int(vals.basis_values.size());
443 const Eigen::MatrixXd lame_params = extract_lame_params(state.assembler->parameters(), e, params.t, points, vals.val);
446 params.body_id = state.mesh->get_body_id(e);
447 params.boundary_id = state.mesh->get_boundary_id(global_primitive_id);
449 j.evaluate(lame_params, points, vals.val, u, grad_u, normal, vals, params, j_val);
450 j_val = j_val.array().colwise() * weights.array();
452 if (j.depend_on_gradu())
454 j.dj_dgradu(lame_params, points, vals.val, u, grad_u, normal, vals, params, dj_dgradu);
455 dj_dgradu = dj_dgradu.array().colwise() * weights.array();
458 if (j.depend_on_gradx())
460 j.dj_dgradx(lame_params, points, vals.val, u, grad_u, normal, vals, params, dj_dgradx);
461 dj_dgradx = dj_dgradx.array().colwise() * weights.array();
466 j.dj_dx(lame_params, points, vals.val, u, grad_u, normal, vals, params, dj_dx);
467 dj_dx = dj_dx.array().colwise() * weights.array();
470 const auto nodes = gbases[e].local_nodes_for_primitive(lb.global_primitive_id(i), *state.mesh);
472 if (nodes.size() != dim)
473 log_and_throw_adjoint_error(
"Only linear geometry is supported in differentiable surface integral functional!");
475 Eigen::MatrixXd velocity_div_mat;
476 if (state.mesh->is_volume())
479 for (int d = 0; d < 3; d++)
480 V.row(d) = gbases[e].bases[nodes(d)].global()[0].node;
481 velocity_div_mat = face_velocity_divergence(V);
486 for (int d = 0; d < 2; d++)
487 V.row(d) = gbases[e].bases[nodes(d)].global()[0].node;
488 velocity_div_mat = edge_velocity_divergence(V);
491 Eigen::MatrixXd grad_u_q, tau_q, grad_x_q;
492 for (long n = 0; n < nodes.size(); ++n)
494 const assembler::AssemblyValues &v = vals.basis_values[nodes(n)];
496 local_storage.vec.block(v.global[0].index * dim, 0, dim, 1) += j_val.sum() * velocity_div_mat.row(n).transpose();
499 for (long n = 0; n < n_loc_bases_; ++n)
501 const assembler::AssemblyValues &v = vals.basis_values[n];
504 local_storage.vec.block(v.global[0].index * dim, 0, dim, 1) += dj_dx.transpose() * v.val;
507 if (j.depend_on_gradu())
509 for (int q = 0; q < weights.size(); ++q)
511 if (dim == actual_dim)
513 vector2matrix(grad_u.row(q), grad_u_q);
514 vector2matrix(dj_dgradu.row(q), tau_q);
518 grad_u_q = grad_u.row(q);
519 tau_q = dj_dgradu.row(q);
522 for (int d = 0; d < dim; d++)
523 local_storage.vec(v.global[0].index * dim + d) += -dot(tau_q, grad_u_q.col(d) * v.grad_t_m.row(q));
527 if (j.depend_on_gradx())
529 for (int d = 0; d < dim; d++)
531 for (int q = 0; q < weights.size(); ++q)
532 local_storage.vec(v.global[0].index * dim + d) += dot(dj_dgradx.block(q, d * dim, 1, dim), v.grad.row(q));
540 else if (spatial_integral_type == SpatialIntegralType::VertexSum)
544 for (
const LocalThreadVecStorage &local_storage : storage)
545 term += local_storage.
vec;
547 term = utils::flatten(utils::unflatten(term, dim)(state.
primitive_to_node(), Eigen::all));
550 void AdjointTools::dJ_shape_static_adjoint_term(
552 const Eigen::MatrixXd &sol,
553 const Eigen::MatrixXd &adjoint,
554 Eigen::VectorXd &one_form)
556 Eigen::VectorXd elasticity_term, rhs_term, pressure_term, contact_term;
566 rhs_term.setZero(one_form.size());
574 pressure_term.setZero(one_form.size());
582 contact_term.setZero(elasticity_term.size());
583 one_form -= elasticity_term + rhs_term + pressure_term + contact_term;
585 one_form = utils::flatten(utils::unflatten(one_form, state.
mesh->dimension())(state.
primitive_to_node(), Eigen::all));
588 void AdjointTools::dJ_shape_homogenization_adjoint_term(
590 const Eigen::MatrixXd &sol,
591 const Eigen::MatrixXd &adjoint,
592 Eigen::VectorXd &one_form)
594 Eigen::VectorXd elasticity_term, contact_term;
596 std::shared_ptr<NLHomoProblem> homo_problem = std::dynamic_pointer_cast<NLHomoProblem>(state.
solve_data.
nl_problem);
597 assert(homo_problem);
599 const int dim = state.
mesh->dimension();
602 const Eigen::MatrixXd affine_adjoint = homo_problem->reduced_to_disp_grad(adjoint,
true);
603 const Eigen::VectorXd full_adjoint = homo_problem->NLProblem::reduced_to_full(adjoint.topRows(homo_problem->reduced_size())) + io::Evaluator::generate_linear_field(state.
n_bases, state.
mesh_nodes, affine_adjoint);
613 contact_term.setZero(elasticity_term.size());
615 one_form = -(elasticity_term + contact_term);
617 Eigen::VectorXd force;
618 homo_problem->FullNLProblem::gradient(sol, force);
621 one_form = utils::flatten(utils::unflatten(one_form, dim)(state.
primitive_to_node(), Eigen::all));
624 void AdjointTools::dJ_periodic_shape_adjoint_term(
627 const Eigen::VectorXd &periodic_mesh_representation,
628 const Eigen::MatrixXd &sol,
629 const Eigen::MatrixXd &adjoint,
630 Eigen::VectorXd &one_form)
632 std::shared_ptr<NLHomoProblem> homo_problem = std::dynamic_pointer_cast<NLHomoProblem>(state.
solve_data.
nl_problem);
633 assert(homo_problem);
635 const Eigen::MatrixXd reduced_sol = homo_problem->full_to_reduced(sol, state.
diff_cached.
disp_grad());
636 const Eigen::VectorXd extended_sol = homo_problem->reduced_to_extended(reduced_sol);
638 const Eigen::VectorXd extended_adjoint = homo_problem->reduced_to_extended(adjoint,
true);
639 const Eigen::MatrixXd affine_adjoint = homo_problem->reduced_to_disp_grad(adjoint,
true);
640 const Eigen::VectorXd full_adjoint = homo_problem->NLProblem::reduced_to_full(adjoint.topRows(homo_problem->reduced_size())) + io::Evaluator::generate_linear_field(state.
n_bases, state.
mesh_nodes, affine_adjoint);
642 const int dim = state.
mesh->dimension();
647 homo_problem->set_project_to_psd(
false);
648 homo_problem->FullNLProblem::hessian(sol, hessian);
649 Eigen::VectorXd partial_term = full_adjoint.transpose() * hessian;
651 one_form -= utils::flatten(utils::unflatten(partial_term, dim)(state.
primitive_to_node(), Eigen::all));
653 one_form = periodic_mesh_map.
apply_jacobian(one_form, periodic_mesh_representation);
657 Eigen::VectorXd contact_term;
660 one_form -= contact_term;
664 void AdjointTools::dJ_shape_transient_adjoint_term(
666 const Eigen::MatrixXd &adjoint_nu,
667 const Eigen::MatrixXd &adjoint_p,
668 Eigen::VectorXd &one_form)
670 const double t0 = state.
args[
"time"][
"t0"];
671 const double dt = state.
args[
"time"][
"dt"];
672 const int time_steps = state.
args[
"time"][
"time_steps"];
673 const int bdf_order = get_bdf_order(state);
675 Eigen::VectorXd elasticity_term, rhs_term, pressure_term, damping_term, mass_term, contact_term, friction_term;
678 Eigen::VectorXd cur_p, cur_nu;
679 for (
int i = time_steps; i > 0; --i)
681 const int real_order = std::min(bdf_order, i);
682 double beta = time_integrator::BDF::betas(real_order - 1);
683 double beta_dt = beta * dt;
684 const double t = i * dt + t0;
688 cur_p = adjoint_p.col(i);
689 cur_nu = adjoint_nu.col(i);
703 damping_term.setZero(mass_term.size());
712 contact_term.setZero(mass_term.size());
721 friction_term.setZero(mass_term.size());
724 one_form += beta_dt * (elasticity_term + rhs_term + pressure_term + damping_term + contact_term + friction_term + mass_term);
728 Eigen::VectorXd sum_alpha_p;
730 sum_alpha_p.setZero(adjoint_p.rows());
731 int num = std::min(bdf_order, time_steps);
732 for (
int j = 0; j < num; ++j)
734 int order = std::min(bdf_order - 1, j);
735 sum_alpha_p -= time_integrator::BDF::alphas(order)[j] * adjoint_p.col(j + 1);
741 one_form += mass_term;
743 one_form = utils::flatten(utils::unflatten(one_form, state.
mesh->dimension())(state.
primitive_to_node(), Eigen::all));
746 void AdjointTools::dJ_material_static_adjoint_term(
748 const Eigen::MatrixXd &sol,
749 const Eigen::MatrixXd &adjoint,
750 Eigen::VectorXd &one_form)
755 void AdjointTools::dJ_material_transient_adjoint_term(
757 const Eigen::MatrixXd &adjoint_nu,
758 const Eigen::MatrixXd &adjoint_p,
759 Eigen::VectorXd &one_form)
761 const double t0 = state.
args[
"time"][
"t0"];
762 const double dt = state.
args[
"time"][
"dt"];
763 const int time_steps = state.
args[
"time"][
"time_steps"];
764 const int bdf_order = get_bdf_order(state);
766 one_form.setZero(state.
bases.size() * 2);
768 auto storage = utils::create_thread_storage(LocalThreadVecStorage(one_form.size()));
770 utils::maybe_parallel_for(time_steps, [&](
int start,
int end,
int thread_id) {
771 LocalThreadVecStorage &local_storage = utils::get_local_thread_storage(storage, thread_id);
772 Eigen::VectorXd elasticity_term;
773 for (
int i_aux = start; i_aux < end; ++i_aux)
775 const int i = time_steps - i_aux;
776 const int real_order = std::min(bdf_order, i);
777 double beta_dt = time_integrator::BDF::betas(real_order - 1) * dt;
779 Eigen::VectorXd cur_p = adjoint_p.col(i);
783 local_storage.vec += beta_dt * elasticity_term;
787 for (
const LocalThreadVecStorage &local_storage : storage)
788 one_form += local_storage.vec;
791 void AdjointTools::dJ_friction_transient_adjoint_term(
793 const Eigen::MatrixXd &adjoint_nu,
794 const Eigen::MatrixXd &adjoint_p,
795 Eigen::VectorXd &one_form)
797 const double dt = state.
args[
"time"][
"dt"];
799 const int time_steps = state.
args[
"time"][
"time_steps"];
800 const int dim = state.
mesh->dimension();
801 const int bdf_order = get_bdf_order(state);
805 std::shared_ptr<time_integrator::ImplicitTimeIntegrator> time_integrator =
806 time_integrator::ImplicitTimeIntegrator::construct_time_integrator(state.
args[
"time"][
"integrator"]);
808 Eigen::MatrixXd solution, velocity, acceleration;
814 const double dt = state.
args[
"time"][
"dt"];
815 time_integrator->init(solution, velocity, acceleration, dt);
818 for (
int t = 1; t <= time_steps; ++t)
820 const int real_order = std::min(bdf_order, t);
821 double beta = time_integrator::BDF::betas(real_order - 1);
823 const Eigen::MatrixXd surface_solution_prev = state.
collision_mesh.vertices(utils::unflatten(state.
diff_cached.
u(t - 1), dim));
827 time_integrator->update_quantities(state.
diff_cached.
u(t));
834 surface_solution_prev,
840 Eigen::VectorXd cur_p = adjoint_p.col(t);
843 one_form(0) += dot(cur_p, force) * beta * dt;
847 void AdjointTools::dJ_damping_transient_adjoint_term(
849 const Eigen::MatrixXd &adjoint_nu,
850 const Eigen::MatrixXd &adjoint_p,
851 Eigen::VectorXd &one_form)
853 const double t0 = state.
args[
"time"][
"t0"];
854 const double dt = state.
args[
"time"][
"dt"];
855 const int time_steps = state.
args[
"time"][
"time_steps"];
856 const int bdf_order = get_bdf_order(state);
860 auto storage = utils::create_thread_storage(LocalThreadVecStorage(one_form.size()));
862 utils::maybe_parallel_for(time_steps, [&](
int start,
int end,
int thread_id) {
863 LocalThreadVecStorage &local_storage = utils::get_local_thread_storage(storage, thread_id);
864 Eigen::VectorXd damping_term;
865 for (
int t_aux = start; t_aux < end; ++t_aux)
867 const int t = time_steps - t_aux;
868 const int real_order = std::min(bdf_order, t);
869 const double beta = time_integrator::BDF::betas(real_order - 1);
871 Eigen::VectorXd cur_p = adjoint_p.col(t);
875 local_storage.vec += (beta * dt) * damping_term;
879 for (
const LocalThreadVecStorage &local_storage : storage)
880 one_form += local_storage.vec;
883 void AdjointTools::dJ_initial_condition_adjoint_term(
885 const Eigen::MatrixXd &adjoint_nu,
886 const Eigen::MatrixXd &adjoint_p,
887 Eigen::VectorXd &one_form)
889 const int ndof = state.
ndof();
890 one_form.setZero(ndof * 2);
893 one_form.segment(0, ndof) = -adjoint_nu.col(0);
894 one_form.segment(ndof, ndof) = -adjoint_p.col(0);
899 one_form(ndof + b) = 0;
903 void AdjointTools::dJ_dirichlet_transient_adjoint_term(
905 const Eigen::MatrixXd &adjoint_nu,
906 const Eigen::MatrixXd &adjoint_p,
907 Eigen::VectorXd &one_form)
909 const double dt = state.
args[
"time"][
"dt"];
910 const int time_steps = state.
args[
"time"][
"time_steps"];
911 const int bdf_order = get_bdf_order(state);
916 one_form.setZero(time_steps * n_dirichlet_dof);
917 for (
int i = 1; i <= time_steps; ++i)
919 const int real_order = std::min(bdf_order, i);
920 const double beta_dt = time_integrator::BDF::betas(real_order - 1) * dt;
922 one_form.segment((i - 1) * n_dirichlet_dof, n_dirichlet_dof) = -(1. / beta_dt) * adjoint_p(state.
boundary_nodes, i);
926 void AdjointTools::dJ_pressure_static_adjoint_term(
928 const std::vector<int> &boundary_ids,
929 const Eigen::MatrixXd &sol,
930 const Eigen::MatrixXd &adjoint,
931 Eigen::VectorXd &one_form)
933 const int n_pressure_dof = boundary_ids.size();
935 one_form.setZero(n_pressure_dof);
937 for (
int i = 0; i < boundary_ids.size(); ++i)
945 one_form(i) = pressure_term;
949 void AdjointTools::dJ_pressure_transient_adjoint_term(
951 const std::vector<int> &boundary_ids,
952 const Eigen::MatrixXd &adjoint_nu,
953 const Eigen::MatrixXd &adjoint_p,
954 Eigen::VectorXd &one_form)
956 const double t0 = state.
args[
"time"][
"t0"];
957 const double dt = state.
args[
"time"][
"dt"];
958 const int time_steps = state.
args[
"time"][
"time_steps"];
959 const int bdf_order = get_bdf_order(state);
961 const int n_pressure_dof = boundary_ids.size();
963 one_form.setZero(time_steps * n_pressure_dof);
964 Eigen::VectorXd cur_p, cur_nu;
965 for (
int i = time_steps; i > 0; --i)
967 const int real_order = std::min(bdf_order, i);
968 double beta = time_integrator::BDF::betas(real_order - 1);
969 double beta_dt = beta * dt;
970 const double t = i * dt + t0;
972 cur_p = adjoint_p.col(i);
973 cur_nu = adjoint_nu.col(i);
977 for (
int b = 0; b < boundary_ids.size(); ++b)
985 one_form((i - 1) * n_pressure_dof + b) = -beta_dt * pressure_term;
990 void AdjointTools::dJ_du_step(
993 const Eigen::MatrixXd &solution,
994 const std::set<int> &interested_ids,
997 Eigen::VectorXd &term)
999 const auto &bases = state.
bases;
1002 const int dim = state.
mesh->dimension();
1003 const int actual_dim = state.
problem->is_scalar() ? 1 : dim;
1004 const int n_elements = int(bases.size());
1005 const double t0 = state.
problem->is_time_dependent() ? state.
args[
"time"][
"t0"].get<
double>() : 0.0;
1006 const double dt = state.
problem->is_time_dependent() ? state.
args[
"time"][
"dt"].get<
double>() : 0.0;
1008 term = Eigen::MatrixXd::Zero(state.
n_bases * actual_dim, 1);
1013 if (spatial_integral_type == SpatialIntegralType::Volume)
1015 auto storage = utils::create_thread_storage(LocalThreadVecStorage(term.size()));
1016 utils::maybe_parallel_for(n_elements, [&](
int start,
int end,
int thread_id) {
1017 LocalThreadVecStorage &local_storage = utils::get_local_thread_storage(storage, thread_id);
1019 Eigen::MatrixXd u, grad_u;
1020 Eigen::MatrixXd lambda, mu;
1021 Eigen::MatrixXd dj_du, dj_dgradu, dj_dgradx;
1024 params.
t = dt * cur_step + t0;
1025 params.
step = cur_step;
1027 for (
int e = start; e < end; ++e)
1029 if (interested_ids.size() != 0 && interested_ids.find(state.
mesh->get_body_id(e)) == interested_ids.end())
1040 const int n_loc_bases_ = int(
vals.basis_values.size());
1042 io::Evaluator::interpolate_at_local_vals(e, dim, actual_dim,
vals, solution, u, grad_u);
1047 dj_dgradu.resize(0, 0);
1051 for (
int q = 0; q < dj_dgradu.rows(); q++)
1052 dj_dgradu.row(q) *= local_storage.da(q);
1059 for (
int q = 0; q < dj_du.rows(); q++)
1060 dj_du.row(q) *= local_storage.da(q);
1063 for (
int i = 0; i < n_loc_bases_; ++i)
1066 assert(v.
global.size() == 1);
1067 for (
int d = 0; d < actual_dim; d++)
1074 for (
int q = 0; q < local_storage.da.size(); ++q)
1075 val += dot(dj_dgradu.block(q, d * dim, 1, dim), v.
grad_t_m.row(q));
1081 for (
int q = 0; q < local_storage.da.size(); ++q)
1082 val += dj_du(q, d) * v.
val(q);
1084 local_storage.vec(v.
global[0].index * actual_dim + d) +=
val;
1089 for (
const LocalThreadVecStorage &local_storage : storage)
1090 term += local_storage.vec;
1092 else if (spatial_integral_type == SpatialIntegralType::Surface)
1094 auto storage = utils::create_thread_storage(LocalThreadVecStorage(term.size()));
1095 utils::maybe_parallel_for(state.
total_local_boundary.size(), [&](
int start,
int end,
int thread_id) {
1096 LocalThreadVecStorage &local_storage = utils::get_local_thread_storage(storage, thread_id);
1098 Eigen::MatrixXd uv, samples, gtmp;
1099 Eigen::MatrixXd points, normal;
1100 Eigen::VectorXd weights;
1102 Eigen::MatrixXd u, grad_u;
1103 Eigen::MatrixXd lambda, mu;
1104 Eigen::MatrixXd dj_du, dj_dgradu, dj_dgradu_local;
1106 IntegrableFunctional::ParameterType params;
1107 params.t = dt * cur_step + t0;
1108 params.step = cur_step;
1110 for (int lb_id = start; lb_id < end; ++lb_id)
1112 const auto &lb = state.total_local_boundary[lb_id];
1113 const int e = lb.element_id();
1115 for (int i = 0; i < lb.size(); i++)
1117 const int global_primitive_id = lb.global_primitive_id(i);
1118 if (interested_ids.size() != 0 && interested_ids.find(state.mesh->get_boundary_id(global_primitive_id)) == interested_ids.end())
1121 utils::BoundarySampler::boundary_quadrature(lb, state.n_boundary_samples(), *state.mesh, i, false, uv, points, normal, weights);
1123 assembler::ElementAssemblyValues &vals = local_storage.vals;
1124 vals.compute(e, state.mesh->is_volume(), points, bases[e], gbases[e]);
1125 io::Evaluator::interpolate_at_local_vals(e, dim, actual_dim, vals, solution, u, grad_u);
1127 const Eigen::MatrixXd lame_params = extract_lame_params(state.assembler->parameters(), e, params.t, points, vals.val);
1131 const int n_loc_bases_ = int(vals.basis_values.size());
1134 params.body_id = state.mesh->get_body_id(e);
1135 params.boundary_id = state.mesh->get_boundary_id(global_primitive_id);
1137 dj_dgradu.resize(0, 0);
1138 if (j.depend_on_gradu())
1140 j.dj_dgradu(lame_params, points, vals.val, u, grad_u, normal, vals, params, dj_dgradu);
1141 for (int q = 0; q < dj_dgradu.rows(); q++)
1142 dj_dgradu.row(q) *= weights(q);
1145 dj_dgradu_local.resize(0, 0);
1146 if (j.depend_on_gradu_local())
1148 j.dj_dgradu_local(lame_params, points, vals.val, u, grad_u, normal, vals, params, dj_dgradu_local);
1149 for (int q = 0; q < dj_dgradu_local.rows(); q++)
1150 dj_dgradu_local.row(q) *= weights(q);
1154 if (j.depend_on_u())
1156 j.dj_du(lame_params, points, vals.val, u, grad_u, normal, vals, params, dj_du);
1157 for (int q = 0; q < dj_du.rows(); q++)
1158 dj_du.row(q) *= weights(q);
1161 for (int l = 0; l < lb.size(); ++l)
1163 const auto nodes = bases[e].local_nodes_for_primitive(lb.global_primitive_id(l), *state.mesh);
1165 for (long n = 0; n < nodes.size(); ++n)
1167 const assembler::AssemblyValues &v = vals.basis_values[nodes(n)];
1168 assert(v.global.size() == 1);
1169 for (int d = 0; d < actual_dim; d++)
1174 if (j.depend_on_gradu())
1176 for (int q = 0; q < weights.size(); ++q)
1177 val += dot(dj_dgradu.block(q, d * dim, 1, dim), v.grad_t_m.row(q));
1180 if (j.depend_on_gradu_local())
1182 for (int q = 0; q < weights.size(); ++q)
1183 val += dot(dj_dgradu_local.block(q, d * dim, 1, dim), v.grad.row(q));
1186 if (j.depend_on_u())
1188 for (int q = 0; q < weights.size(); ++q)
1189 val += dj_du(q, d) * v.val(q);
1191 local_storage.vec(v.global[0].index * actual_dim + d) += val;
1198 for (
const LocalThreadVecStorage &local_storage : storage)
1199 term += local_storage.vec;
1201 else if (spatial_integral_type == SpatialIntegralType::VertexSum)
1203 std::vector<bool> traversed(state.
n_bases,
false);
1205 params.
t = dt * cur_step + t0;
1206 params.
step = cur_step;
1207 for (
int e = 0; e < bases.size(); e++)
1209 const auto &bs = bases[e];
1210 for (
int i = 0; i < bs.bases.size(); i++)
1212 const auto &b = bs.bases[i];
1213 assert(b.global().size() == 1);
1214 const auto &g = b.global()[0];
1215 if (traversed[g.index])
1218 const Eigen::MatrixXd lame_params = extract_lame_params(state.
assembler->parameters(), e, params.
t, Eigen::MatrixXd::Zero(1, dim) , g.node);
1220 params.
node = g.index;
1223 Eigen::MatrixXd
val;
1224 j.dj_du(lame_params, Eigen::MatrixXd::Zero(1, dim) , g.node, solution.block(g.index * dim, 0, dim, 1).transpose(), Eigen::MatrixXd::Zero(1, dim * actual_dim) , Eigen::MatrixXd::Zero(0, 0) ,
assembler::ElementAssemblyValues(), params,
val);
1225 term.block(g.index * actual_dim, 0, actual_dim, 1) +=
val.transpose();
1226 traversed[g.index] =
true;
1232 Eigen::VectorXd AdjointTools::map_primitive_to_node_order(
const State &state,
const Eigen::VectorXd &primitives)
1234 int dim = state.
mesh->dimension();
1235 assert(primitives.size() == (state.
n_geom_bases * dim));
1236 Eigen::VectorXd nodes(primitives.size());
1239 nodes.segment(map[v] * dim, dim) = primitives.segment(v * dim, dim);
1243 Eigen::VectorXd AdjointTools::map_node_to_primitive_order(
const State &state,
const Eigen::VectorXd &nodes)
1245 int dim = state.
mesh->dimension();
1247 Eigen::VectorXd primitives(nodes.size());
1250 primitives.segment(map[v] * dim, dim) = nodes.segment(v * dim, dim);
1254 Eigen::MatrixXd AdjointTools::edge_normal_gradient(
const Eigen::MatrixXd &
V)
1257 Eigen::Matrix<Diff, 4, 1> full_diff(4, 1);
1258 for (
int i = 0; i < 2; i++)
1259 for (
int j = 0; j < 2; j++)
1260 full_diff(i * 2 + j) =
Diff(i * 2 + j,
V(i, j));
1261 auto reduced_diff = edge_normal(full_diff);
1263 Eigen::MatrixXd grad(2, 4);
1264 for (
int i = 0; i < 2; ++i)
1265 grad.row(i) = reduced_diff[i].getGradient();
1270 Eigen::MatrixXd AdjointTools::face_normal_gradient(
const Eigen::MatrixXd &
V)
1273 Eigen::Matrix<Diff, 9, 1> full_diff(9, 1);
1274 for (
int i = 0; i < 3; i++)
1275 for (
int j = 0; j < 3; j++)
1276 full_diff(i * 3 + j) =
Diff(i * 3 + j,
V(i, j));
1277 auto reduced_diff = face_normal(full_diff);
1279 Eigen::MatrixXd grad(3, 9);
1280 for (
int i = 0; i < 3; ++i)
1281 grad.row(i) = reduced_diff[i].getGradient();
1286 Eigen::MatrixXd AdjointTools::edge_velocity_divergence(
const Eigen::MatrixXd &
V)
1288 return line_length_grad(
V) / line_length<double>(
V);
1291 Eigen::MatrixXd AdjointTools::face_velocity_divergence(
const Eigen::MatrixXd &
V)
1293 return triangle_area_grad(
V) / triangle_area<double>(
V);
1296 double AdjointTools::triangle_jacobian(
const Eigen::VectorXd &v1,
const Eigen::VectorXd &v2,
const Eigen::VectorXd &v3)
1298 Eigen::VectorXd a = v2 - v1, b = v3 - v1;
1299 return a(0) * b(1) - b(0) * a(1);
1302 double AdjointTools::tet_determinant(
const Eigen::VectorXd &v1,
const Eigen::VectorXd &v2,
const Eigen::VectorXd &v3,
const Eigen::VectorXd &v4)
1304 Eigen::Matrix3d mat;
1305 mat.col(0) << v2 - v1;
1306 mat.col(1) << v3 - v1;
1307 mat.col(2) << v4 - v1;
1308 return mat.determinant();
1311 void AdjointTools::scaled_jacobian(
const Eigen::MatrixXd &
V,
const Eigen::MatrixXi &F, Eigen::VectorXd &quality)
1313 const int dim = F.cols() - 1;
1315 quality.setZero(F.rows());
1318 for (
int i = 0; i < F.rows(); i++)
1320 Eigen::RowVector3d e0;
1322 e0.head(2) =
V.row(F(i, 2)) -
V.row(F(i, 1));
1323 Eigen::RowVector3d e1;
1325 e1.head(2) =
V.row(F(i, 0)) -
V.row(F(i, 2));
1326 Eigen::RowVector3d e2;
1328 e2.head(2) =
V.row(F(i, 1)) -
V.row(F(i, 0));
1330 double l0 = e0.norm();
1331 double l1 = e1.norm();
1332 double l2 = e2.norm();
1334 double A = 0.5 * (e0.cross(e1)).norm();
1335 double Lmax = std::max(l0 * l1, std::max(l1 * l2, l0 * l2));
1337 quality(i) = 2 * A * (2 / sqrt(3)) / Lmax;
1342 for (
int i = 0; i < F.rows(); i++)
1344 Eigen::RowVector3d e0 =
V.row(F(i, 1)) -
V.row(F(i, 0));
1345 Eigen::RowVector3d e1 =
V.row(F(i, 2)) -
V.row(F(i, 1));
1346 Eigen::RowVector3d e2 =
V.row(F(i, 0)) -
V.row(F(i, 2));
1347 Eigen::RowVector3d e3 =
V.row(F(i, 3)) -
V.row(F(i, 0));
1348 Eigen::RowVector3d e4 =
V.row(F(i, 3)) -
V.row(F(i, 1));
1349 Eigen::RowVector3d e5 =
V.row(F(i, 3)) -
V.row(F(i, 2));
1351 double l0 = e0.norm();
1352 double l1 = e1.norm();
1353 double l2 = e2.norm();
1354 double l3 = e3.norm();
1355 double l4 = e4.norm();
1356 double l5 = e5.norm();
1358 double J = std::abs((e0.cross(e3)).dot(e2));
1360 double a1 = l0 * l2 * l3;
1361 double a2 = l0 * l1 * l4;
1362 double a3 = l1 * l2 * l5;
1363 double a4 = l3 * l4 * l5;
1365 double a = std::max({a1, a2, a3, a4, J});
1366 quality(i) = J * sqrt(2) / a;
1371 bool AdjointTools::is_flipped(
const Eigen::MatrixXd &
V,
const Eigen::MatrixXi &F)
1375 for (
int i = 0; i < F.rows(); i++)
1379 else if (F.cols() == 4)
1381 for (
int i = 0; i < F.rows(); i++)
ElementAssemblyValues vals
assembler::ElementAssemblyValues gvals
bool depend_on_gradu_local() const
void dj_du(const Eigen::MatrixXd &elastic_params, const Eigen::MatrixXd &local_pts, const Eigen::MatrixXd &pts, const Eigen::MatrixXd &u, const Eigen::MatrixXd &grad_u, const Eigen::MatrixXd &reference_normals, const assembler::ElementAssemblyValues &vals, ParameterType ¶ms, Eigen::MatrixXd &val) const
bool depend_on_gradu() const
void dj_dgradu(const Eigen::MatrixXd &elastic_params, const Eigen::MatrixXd &local_pts, const Eigen::MatrixXd &pts, const Eigen::MatrixXd &u, const Eigen::MatrixXd &grad_u, const Eigen::MatrixXd &reference_normals, const assembler::ElementAssemblyValues &vals, ParameterType ¶ms, Eigen::MatrixXd &val) const
void evaluate(const Eigen::MatrixXd &elastic_params, const Eigen::MatrixXd &local_pts, const Eigen::MatrixXd &pts, const Eigen::MatrixXd &u, const Eigen::MatrixXd &grad_u, const Eigen::MatrixXd &reference_normals, const assembler::ElementAssemblyValues &vals, ParameterType ¶ms, Eigen::MatrixXd &val) const
void dj_dx(const Eigen::MatrixXd &elastic_params, const Eigen::MatrixXd &local_pts, const Eigen::MatrixXd &pts, const Eigen::MatrixXd &u, const Eigen::MatrixXd &grad_u, const Eigen::MatrixXd &reference_normals, const assembler::ElementAssemblyValues &vals, ParameterType ¶ms, Eigen::MatrixXd &val) const
main class that contains the polyfem solver and all its state
Eigen::MatrixXd initial_vel_update
int n_bases
number of bases
assembler::AssemblyValsCache ass_vals_cache
used to store assembly values for small problems
const std::vector< basis::ElementBases > & geom_bases() const
Get a constant reference to the geometry mapping bases.
std::shared_ptr< assembler::Assembler > assembler
assemblers
ipc::CollisionMesh collision_mesh
IPC collision mesh.
std::shared_ptr< assembler::Mass > mass_matrix_assembler
std::vector< int > primitive_to_node() const
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.
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
void initial_velocity(Eigen::MatrixXd &velocity) const
Load or compute the initial velocity.
void initial_acceleration(Eigen::MatrixXd &acceleration) const
Load or compute the initial acceleration.
std::vector< basis::ElementBases > bases
FE bases, the size is #elements.
int n_geom_bases
number of geometric bases
std::vector< mesh::LocalBoundary > total_local_boundary
mapping from elements to nodes for all mesh
assembler::AssemblyValsCache mass_ass_vals_cache
std::vector< int > boundary_nodes
list of boundary nodes
solver::SolveData solve_data
timedependent stuff cached
bool is_contact_enabled() const
does the simulation has contact
StiffnessMatrix basis_nodes_to_gbasis_nodes
void compute(const int el_index, const bool is_volume, const basis::ElementBases &basis, const basis::ElementBases &gbasis, ElementAssemblyValues &vals) const
retrieves cached basis evaluation and geometric for the given element if it doesn't exist,...
stores per local bases evaluations
std::vector< basis::Local2Global > global
stores per element basis values at given quadrature points and geometric mapping
void compute(const int el_index, const bool is_volume, const Eigen::MatrixXd &pts, const basis::ElementBases &basis, const basis::ElementBases &gbasis)
computes the per element values at the local (ref el) points (pts) sets basis_values,...
quadrature::Quadrature quadrature
static void interpolate_at_local_vals(const mesh::Mesh &mesh, const bool is_problem_scalar, const std::vector< basis::ElementBases > &bases, const std::vector< basis::ElementBases > &gbases, const int el_index, const Eigen::MatrixXd &local_pts, const Eigen::MatrixXd &fun, Eigen::MatrixXd &result, Eigen::MatrixXd &result_grad)
interpolate solution and gradient at element (calls interpolate_at_local_vals with sol)
Eigen::MatrixXd disp_grad(int step=0) const
const ipc::Collisions & collision_set(int step) const
Eigen::VectorXd v(int step) const
Eigen::VectorXd u(int step) const
const ipc::FrictionCollisions & friction_collision_set(int step) const
Eigen::VectorXd apply_jacobian(const Eigen::VectorXd &grad, const Eigen::VectorXd &x) const override
std::shared_ptr< solver::FrictionForm > friction_form
std::shared_ptr< solver::InertiaForm > inertia_form
std::shared_ptr< solver::PeriodicContactForm > periodic_contact_form
std::shared_ptr< solver::PressureForm > pressure_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< solver::ElasticForm > damping_form
std::shared_ptr< solver::ElasticForm > elastic_form
Eigen::Matrix< double, dim, 1 > cross(const Eigen::Matrix< double, dim, 1 > &x, const Eigen::Matrix< double, dim, 1 > &y)
DScalar1< double, Eigen::Matrix< double, Eigen::Dynamic, 1 > > Diff
void vector2matrix(const Eigen::VectorXd &vec, Eigen::MatrixXd &mat)
auto & get_local_thread_storage(Storages &storage, int thread_id)
auto create_thread_storage(const LocalStorage &initial_local_storage)
double triangle_area(const Eigen::MatrixXd V)
Compute the signed area of a triangle defined by three points.
void maybe_parallel_for(int size, const std::function< void(int, int, int)> &partial_for)
Eigen::Matrix< double, Eigen::Dynamic, 1, 0, MAX_QUAD_POINTS, 1 > QuadratureVector
void log_and_throw_adjoint_error(const std::string &msg)
Eigen::SparseMatrix< double, Eigen::ColMajor > StiffnessMatrix
Automatic differentiation scalar with first-order derivatives.
static void setVariableCount(size_t value)
Set the independent variable count used by the automatic differentiation layer.
Parameters for the functional evaluation.