PolyFEM
Loading...
Searching...
No Matches
BarrierForms.cpp
Go to the documentation of this file.
1#include "BarrierForms.hpp"
2#include <polyfem/State.hpp>
3
4namespace polyfem::solver
5{
6 namespace
7 {
8 class QuadraticBarrier : public ipc::Barrier
9 {
10 public:
11 QuadraticBarrier(const double weight = 1) : weight_(weight) {}
12
13 double operator()(const double d, const double dhat) const override
14 {
15 if (d > dhat)
16 return 0;
17 else
18 return weight_ * (d - dhat) * (d - dhat);
19 }
20 double first_derivative(const double d, const double dhat) const override
21 {
22 if (d > dhat)
23 return 0;
24 else
25 return 2 * weight_ * (d - dhat);
26 }
27 double second_derivative(const double d, const double dhat) const override
28 {
29 if (d > dhat)
30 return 0;
31 else
32 return 2 * weight_;
33 }
34
35 private:
36 const double weight_;
37 };
38
39 } // namespace
40
41 CollisionBarrierForm::CollisionBarrierForm(const VariableToSimulationGroup &variable_to_simulation, const State &state, const double dhat, const double dmin)
42 : AdjointForm(variable_to_simulation), state_(state), dhat_(dhat), dmin_(dmin), barrier_potential_(dhat)
43 {
47 [this](const std::string &p) { return this->state_.resolve_input_path(p); },
49
50 Eigen::MatrixXd V;
53
54 broad_phase_method_ = ipc::BroadPhaseMethod::HASH_GRID;
55 }
56
57 double CollisionBarrierForm::value_unweighted(const Eigen::VectorXd &x) const
58 {
59 const Eigen::MatrixXd displaced_surface = collision_mesh_.vertices(utils::unflatten(get_updated_mesh_nodes(x), state_.mesh->dimension()));
60 return barrier_potential_(collision_set, collision_mesh_, displaced_surface);
61 }
62
63 void CollisionBarrierForm::compute_partial_gradient(const Eigen::VectorXd &x, Eigen::VectorXd &gradv) const
64 {
66 const Eigen::MatrixXd displaced_surface = collision_mesh_.vertices(utils::unflatten(get_updated_mesh_nodes(x), state_.mesh->dimension()));
67 const Eigen::VectorXd grad = collision_mesh_.to_full_dof(barrier_potential_.gradient(collision_set, collision_mesh_, displaced_surface));
69 });
70 }
71
72 void CollisionBarrierForm::solution_changed(const Eigen::VectorXd &x)
73 {
75
76 const Eigen::MatrixXd displaced_surface = collision_mesh_.vertices(utils::unflatten(get_updated_mesh_nodes(x), state_.mesh->dimension()));
77 build_collision_set(displaced_surface);
78 }
79
80 bool CollisionBarrierForm::is_step_collision_free(const Eigen::VectorXd &x0, const Eigen::VectorXd &x1) const
81 {
82 const Eigen::MatrixXd V0 = utils::unflatten(get_updated_mesh_nodes(x0), state_.mesh->dimension());
83 const Eigen::MatrixXd V1 = utils::unflatten(get_updated_mesh_nodes(x1), state_.mesh->dimension());
84
85 // Skip CCD if the displacement is zero.
86 if ((V1 - V0).lpNorm<Eigen::Infinity>() == 0.0)
87 return true;
88
89 bool is_valid = ipc::is_step_collision_free(
91 collision_mesh_.vertices(V0),
92 collision_mesh_.vertices(V1),
94 1e-6, 1e6);
95
96 return is_valid;
97 }
98
99 double CollisionBarrierForm::max_step_size(const Eigen::VectorXd &x0, const Eigen::VectorXd &x1) const
100 {
101 const Eigen::MatrixXd V0 = utils::unflatten(get_updated_mesh_nodes(x0), state_.mesh->dimension());
102 const Eigen::MatrixXd V1 = utils::unflatten(get_updated_mesh_nodes(x1), state_.mesh->dimension());
103
104 double max_step = ipc::compute_collision_free_stepsize(
106 collision_mesh_.vertices(V0),
107 collision_mesh_.vertices(V1),
108 broad_phase_method_, dmin_, 1e-6, 1e6);
109
110 adjoint_logger().info("Objective {}: max step size is {}.", name(), max_step);
111
112 return max_step;
113 }
114
115 void CollisionBarrierForm::build_collision_set(const Eigen::MatrixXd &displaced_surface)
116 {
117 static Eigen::MatrixXd cached_displaced_surface;
118 if (cached_displaced_surface.size() == displaced_surface.size() && cached_displaced_surface == displaced_surface)
119 return;
120
121 collision_set.build(collision_mesh_, displaced_surface, dhat_, dmin_, broad_phase_method_);
122
123 cached_displaced_surface = displaced_surface;
124 }
125
126 Eigen::VectorXd CollisionBarrierForm::get_updated_mesh_nodes(const Eigen::VectorXd &x) const
127 {
128 Eigen::VectorXd X = X_init;
131 }
132
133 DeformedCollisionBarrierForm::DeformedCollisionBarrierForm(const VariableToSimulationGroup &variable_to_simulation, const State &state, const double dhat)
134 : AdjointForm(variable_to_simulation), state_(state), dhat_(dhat), barrier_potential_(dhat)
135 {
137 log_and_throw_adjoint_error("[{}] Should use linear FE basis!", name());
138
142 [this](const std::string &p) { return this->state_.resolve_input_path(p); },
144
145 Eigen::MatrixXd V;
148
149 broad_phase_method_ = ipc::BroadPhaseMethod::HASH_GRID;
150 }
151
152 double DeformedCollisionBarrierForm::value_unweighted(const Eigen::VectorXd &x) const
153 {
154 const Eigen::MatrixXd displaced_surface = collision_mesh_.vertices(utils::unflatten(get_updated_mesh_nodes(x), state_.mesh->dimension()));
155
156 return barrier_potential_(collision_set, collision_mesh_, displaced_surface);
157 }
158
159 void DeformedCollisionBarrierForm::compute_partial_gradient(const Eigen::VectorXd &x, Eigen::VectorXd &gradv) const
160 {
162 const Eigen::MatrixXd displaced_surface = collision_mesh_.vertices(utils::unflatten(get_updated_mesh_nodes(x), state_.mesh->dimension()));
163 const Eigen::VectorXd grad = collision_mesh_.to_full_dof(barrier_potential_.gradient(collision_set, collision_mesh_, displaced_surface));
165 });
166 }
167
169 {
171
172 const Eigen::MatrixXd displaced_surface = collision_mesh_.vertices(utils::unflatten(get_updated_mesh_nodes(x), state_.mesh->dimension()));
173 build_collision_set(displaced_surface);
174 }
175
176 bool DeformedCollisionBarrierForm::is_step_collision_free(const Eigen::VectorXd &x0, const Eigen::VectorXd &x1) const
177 {
178 // const Eigen::MatrixXd V0 = utils::unflatten(get_updated_mesh_nodes(x0), state_.mesh->dimension());
179 // const Eigen::MatrixXd V1 = utils::unflatten(get_updated_mesh_nodes(x1), state_.mesh->dimension());
180
181 // // Skip CCD if the displacement is zero.
182 // if ((V1 - V0).lpNorm<Eigen::Infinity>() == 0.0)
183 // return true;
184
185 // bool is_valid = ipc::is_step_collision_free(
186 // collision_mesh_,
187 // collision_mesh_.vertices(V0),
188 // collision_mesh_.vertices(V1),
189 // broad_phase_method_,
190 // 1e-6, 1e6);
191
192 return true; // is_valid;
193 }
194
195 double DeformedCollisionBarrierForm::max_step_size(const Eigen::VectorXd &x0, const Eigen::VectorXd &x1) const
196 {
197 // const Eigen::MatrixXd V0 = utils::unflatten(get_updated_mesh_nodes(x0), state_.mesh->dimension());
198 // const Eigen::MatrixXd V1 = utils::unflatten(get_updated_mesh_nodes(x1), state_.mesh->dimension());
199
200 // double max_step = ipc::compute_collision_free_stepsize(
201 // collision_mesh_,
202 // collision_mesh_.vertices(V0),
203 // collision_mesh_.vertices(V1),
204 // broad_phase_method_, 1e-6, 1e6);
205
206 return 1; // max_step;
207 }
208
209 void DeformedCollisionBarrierForm::build_collision_set(const Eigen::MatrixXd &displaced_surface)
210 {
211 static Eigen::MatrixXd cached_displaced_surface;
212 if (cached_displaced_surface.size() == displaced_surface.size() && cached_displaced_surface == displaced_surface)
213 return;
214
215 collision_set.build(collision_mesh_, displaced_surface, dhat_, 0, broad_phase_method_);
216
217 cached_displaced_surface = displaced_surface;
218 }
219
226
228 const State &state,
229 const std::vector<int> &boundary_ids,
230 const double dhat,
231 const bool use_log_barrier,
232 const double dmin)
233 : CollisionBarrierForm(variable_to_simulations, state, dhat, dmin),
234 boundary_ids_(boundary_ids)
235 {
236 for (const auto &id : boundary_ids_)
237 boundary_ids_to_dof_[id] = std::set<int>();
238
240
241 if (!use_log_barrier)
242 barrier_potential_.set_barrier(std::make_shared<QuadraticBarrier>());
243 }
244
246 {
247 Eigen::MatrixXd node_positions;
248 Eigen::MatrixXi boundary_edges, boundary_triangles;
249 std::vector<Eigen::Triplet<double>> displacement_map_entries;
251 node_positions, boundary_edges, boundary_triangles, displacement_map_entries);
252
253 std::vector<bool> is_on_surface;
254 is_on_surface.resize(node_positions.rows(), false);
255
257 Eigen::MatrixXd points, uv, normals;
258 Eigen::VectorXd weights;
259 Eigen::VectorXi global_primitive_ids;
260 for (const auto &lb : state_.total_local_boundary)
261 {
262 const int e = lb.element_id();
263 bool has_samples = utils::BoundarySampler::boundary_quadrature(lb, state_.n_boundary_samples(), *state_.mesh, false, uv, points, normals, weights, global_primitive_ids);
264
265 if (!has_samples)
266 continue;
267
268 const basis::ElementBases &gbs = state_.geom_bases()[e];
269
270 vals.compute(e, state_.mesh->is_volume(), points, gbs, gbs);
271
272 for (int i = 0; i < lb.size(); ++i)
273 {
274 const int primitive_global_id = lb.global_primitive_id(i);
275 const auto nodes = gbs.local_nodes_for_primitive(primitive_global_id, *state_.mesh);
276 const int boundary_id = state_.mesh->get_boundary_id(primitive_global_id);
277
278 if (!std::count(boundary_ids_.begin(), boundary_ids_.end(), boundary_id))
279 continue;
280
281 for (long n = 0; n < nodes.size(); ++n)
282 {
283 const assembler::AssemblyValues &v = vals.basis_values[nodes(n)];
284 is_on_surface[v.global[0].index] = true;
285 assert(v.global[0].index < node_positions.rows());
286 boundary_ids_to_dof_[boundary_id].insert(v.global[0].index);
287 }
288 }
289 }
290
291 Eigen::SparseMatrix<double> displacement_map;
292 if (!displacement_map_entries.empty())
293 {
294 displacement_map.resize(node_positions.rows(), state_.n_geom_bases);
295 displacement_map.setFromTriplets(displacement_map_entries.begin(), displacement_map_entries.end());
296 }
297
298 // Fix boundary edges and boundary triangles to exclude vertices not on triangles
299 Eigen::MatrixXi boundary_edges_alt(0, 2), boundary_triangles_alt(0, 3);
300 {
301 for (int i = 0; i < boundary_edges.rows(); ++i)
302 {
303 bool on_surface = true;
304 for (int j = 0; j < boundary_edges.cols(); ++j)
305 on_surface &= is_on_surface[boundary_edges(i, j)];
306 if (on_surface)
307 {
308 boundary_edges_alt.conservativeResize(boundary_edges_alt.rows() + 1, 2);
309 boundary_edges_alt.row(boundary_edges_alt.rows() - 1) = boundary_edges.row(i);
310 }
311 }
312
313 if (state_.mesh->is_volume())
314 {
315 for (int i = 0; i < boundary_triangles.rows(); ++i)
316 {
317 bool on_surface = true;
318 for (int j = 0; j < boundary_triangles.cols(); ++j)
319 on_surface &= is_on_surface[boundary_triangles(i, j)];
320 if (on_surface)
321 {
322 boundary_triangles_alt.conservativeResize(boundary_triangles_alt.rows() + 1, 3);
323 boundary_triangles_alt.row(boundary_triangles_alt.rows() - 1) = boundary_triangles.row(i);
324 }
325 }
326 }
327 else
328 boundary_triangles_alt.resize(0, 0);
329 }
330
331 collision_mesh_ = ipc::CollisionMesh(is_on_surface,
332 node_positions,
333 boundary_edges_alt,
334 boundary_triangles_alt,
335 displacement_map);
336
337 can_collide_cache_.resize(collision_mesh_.num_vertices(), collision_mesh_.num_vertices());
338 for (int i = 0; i < can_collide_cache_.rows(); ++i)
339 {
340 int dof_idx_i = collision_mesh_.to_full_vertex_id(i);
341 if (!is_on_surface[dof_idx_i])
342 continue;
343 for (int j = 0; j < can_collide_cache_.cols(); ++j)
344 {
345 int dof_idx_j = collision_mesh_.to_full_vertex_id(j);
346 if (!is_on_surface[dof_idx_j])
347 continue;
348
349 bool collision_allowed = true;
350 for (const auto &id : boundary_ids_)
351 if (boundary_ids_to_dof_[id].count(dof_idx_i) && boundary_ids_to_dof_[id].count(dof_idx_j))
352 collision_allowed = false;
353 can_collide_cache_(i, j) = collision_allowed;
354 }
355 }
356
357 collision_mesh_.can_collide = [&](size_t vi, size_t vj) {
358 return (bool)can_collide_cache_(vi, vj);
359 };
360
361 collision_mesh_.init_area_jacobians();
362 }
363
364} // namespace polyfem::solver
int V
ElementAssemblyValues vals
Definition Assembler.cpp:22
const double weight_
int x
main class that contains the polyfem solver and all its state
Definition State.hpp:79
void get_vertices(Eigen::MatrixXd &vertices) const
Definition StateDiff.cpp:69
int n_bases
number of bases
Definition State.hpp:178
int n_boundary_samples() const
quadrature used for projecting boundary conditions
Definition State.hpp:263
const std::vector< basis::ElementBases > & geom_bases() const
Get a constant reference to the geometry mapping bases.
Definition State.hpp:223
Eigen::VectorXi in_node_to_node
Inpute nodes (including high-order) to polyfem nodes, only for isoparametric.
Definition State.hpp:450
mesh::Obstacle obstacle
Obstacles used in collisions.
Definition State.hpp:468
std::unique_ptr< mesh::Mesh > mesh
current mesh, it can be a Mesh2D or Mesh3D
Definition State.hpp:466
json args
main input arguments containing all defaults
Definition State.hpp:101
solver::DiffCache diff_cached
Definition State.hpp:649
int n_geom_bases
number of geometric bases
Definition State.hpp:182
std::vector< mesh::LocalBoundary > total_local_boundary
mapping from elements to nodes for all mesh
Definition State.hpp:431
void build_collision_mesh()
extracts the boundary mesh for collision, called in build_basis
Definition State.cpp:1352
stores per local bases evaluations
std::vector< basis::Local2Global > global
stores per element basis values at given quadrature points and geometric mapping
Stores the basis functions for a given element in a mesh (facet in 2d, cell in 3d).
Eigen::VectorXi local_nodes_for_primitive(const int local_index, const mesh::Mesh &mesh) const
static void extract_boundary_mesh(const mesh::Mesh &mesh, const int n_bases, const std::vector< basis::ElementBases > &bases, const std::vector< mesh::LocalBoundary > &total_local_boundary, Eigen::MatrixXd &node_positions, Eigen::MatrixXi &boundary_edges, Eigen::MatrixXi &boundary_triangles, std::vector< Eigen::Triplet< double > > &displacement_map_entries)
extracts the boundary mesh
Definition OutData.cpp:146
virtual void solution_changed(const Eigen::VectorXd &new_x) override
Update cached fields upon a change in the solution.
const VariableToSimulationGroup variable_to_simulations_
ipc::BarrierPotential barrier_potential_
std::string name() const override
void build_collision_set(const Eigen::MatrixXd &displaced_surface)
ipc::BroadPhaseMethod broad_phase_method_
bool is_step_collision_free(const Eigen::VectorXd &x0, const Eigen::VectorXd &x1) const override
Checks if the step is collision free.
double max_step_size(const Eigen::VectorXd &x0, const Eigen::VectorXd &x1) const override
Determine the maximum step size allowable between the current and next solution.
CollisionBarrierForm(const VariableToSimulationGroup &variable_to_simulation, const State &state, const double dhat, const double dmin=0)
void compute_partial_gradient(const Eigen::VectorXd &x, Eigen::VectorXd &gradv) const override
void solution_changed(const Eigen::VectorXd &x) override
Update cached fields upon a change in the solution.
double value_unweighted(const Eigen::VectorXd &x) const override
Compute the value of the form.
Eigen::VectorXd get_updated_mesh_nodes(const Eigen::VectorXd &x) const
bool is_step_collision_free(const Eigen::VectorXd &x0, const Eigen::VectorXd &x1) const override
Checks if the step is collision free.
void compute_partial_gradient(const Eigen::VectorXd &x, Eigen::VectorXd &gradv) const override
double max_step_size(const Eigen::VectorXd &x0, const Eigen::VectorXd &x1) const override
Determine the maximum step size allowable between the current and next solution.
DeformedCollisionBarrierForm(const VariableToSimulationGroup &variable_to_simulation, const State &state, const double dhat)
double value_unweighted(const Eigen::VectorXd &x) const override
Compute the value of the form.
const ipc::BarrierPotential barrier_potential_
void build_collision_set(const Eigen::MatrixXd &displaced_surface)
Eigen::VectorXd get_updated_mesh_nodes(const Eigen::VectorXd &x) const
void solution_changed(const Eigen::VectorXd &x) override
Update cached fields upon a change in the solution.
Eigen::VectorXd u(int step) const
virtual double weight() const
Get the form's multiplicative constant weight.
Definition Form.hpp:126
LayerThicknessForm(const VariableToSimulationGroup &variable_to_simulations, const State &state, const std::vector< int > &boundary_ids, const double dhat, const bool use_log_barrier=false, const double dmin=0)
std::map< int, std::set< int > > boundary_ids_to_dof_
A collection of VariableToSimulation.
void compute_state_variable(const ParameterType type, const State *state_ptr, const Eigen::VectorXd &x, Eigen::VectorXd &state_variable) const
Evaluate the variable to simulations and overwrite the state_variable based on x.
virtual Eigen::VectorXd apply_parametrization_jacobian(const ParameterType type, const State *state_ptr, const Eigen::VectorXd &x, const std::function< Eigen::VectorXd()> &grad) const
Maps the partial gradient wrt.
static bool boundary_quadrature(const mesh::LocalBoundary &local_boundary, const int order, const mesh::Mesh &mesh, const bool skip_computation, Eigen::MatrixXd &uv, Eigen::MatrixXd &points, Eigen::MatrixXd &normals, Eigen::VectorXd &weights, Eigen::VectorXi &global_primitive_ids)
Eigen::VectorXd map_primitive_to_node_order(const State &state, const Eigen::VectorXd &primitives)
Eigen::VectorXd map_node_to_primitive_order(const State &state, const Eigen::VectorXd &nodes)
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 & adjoint_logger()
Retrieves the current logger for adjoint.
Definition Logger.cpp:28
void log_and_throw_adjoint_error(const std::string &msg)
Definition Logger.cpp:77