PolyFEM
Loading...
Searching...
No Matches
State.cpp
Go to the documentation of this file.
1#include <polyfem/State.hpp>
2#include <polyfem/Common.hpp>
3
7
10
19
22
24
27
30
33
36
41
44
45#include <polysolve/linear/FEMSolver.hpp>
46
48
49#include <igl/edges.h>
50#include <igl/Timer.h>
51
52#include <iostream>
53#include <algorithm>
54#include <memory>
55#include <filesystem>
56
58
61
62using namespace Eigen;
63
64namespace polyfem
65{
66 using namespace assembler;
67 using namespace mesh;
68 using namespace io;
69 using namespace utils;
70
71 namespace
72 {
74 void build_in_node_to_in_primitive(const Mesh &mesh, const MeshNodes &mesh_nodes,
75 Eigen::VectorXi &in_node_to_in_primitive,
76 Eigen::VectorXi &in_node_offset)
77 {
78 const int num_vertex_nodes = mesh_nodes.num_vertex_nodes();
79 const int num_edge_nodes = mesh_nodes.num_edge_nodes();
80 const int num_face_nodes = mesh_nodes.num_face_nodes();
81 const int num_cell_nodes = mesh_nodes.num_cell_nodes();
82
83 const int num_nodes = num_vertex_nodes + num_edge_nodes + num_face_nodes + num_cell_nodes;
84
85 const long n_vertices = num_vertex_nodes;
86 const int num_in_primitives = n_vertices + mesh.n_edges() + mesh.n_faces() + mesh.n_cells();
87 const int num_primitives = mesh.n_vertices() + mesh.n_edges() + mesh.n_faces() + mesh.n_cells();
88
89 in_node_to_in_primitive.resize(num_nodes);
90 in_node_offset.resize(num_nodes);
91
92 // Only one node per vertex, so this is an identity map.
93 in_node_to_in_primitive.head(num_vertex_nodes).setLinSpaced(num_vertex_nodes, 0, num_vertex_nodes - 1); // vertex nodes
94 in_node_offset.head(num_vertex_nodes).setZero();
95
96 int prim_offset = n_vertices;
97 int node_offset = num_vertex_nodes;
98 auto foo = [&](const int num_prims, const int num_prim_nodes) {
99 if (num_prims <= 0 || num_prim_nodes <= 0)
100 return;
101 const Eigen::VectorXi range = Eigen::VectorXi::LinSpaced(num_prim_nodes, 0, num_prim_nodes - 1);
102 // TODO: This assumes isotropic degree of element.
103 const int node_per_prim = num_prim_nodes / num_prims;
104
105 in_node_to_in_primitive.segment(node_offset, num_prim_nodes) =
106 range.array() / node_per_prim + prim_offset;
107
108 in_node_offset.segment(node_offset, num_prim_nodes) =
109 range.unaryExpr([&](const int x) { return x % node_per_prim; });
110
111 prim_offset += num_prims;
112 node_offset += num_prim_nodes;
113 };
114
115 foo(mesh.n_edges(), num_edge_nodes);
116 foo(mesh.n_faces(), num_face_nodes);
117 foo(mesh.n_cells(), num_cell_nodes);
118 }
119
120 bool build_in_primitive_to_primitive(
121 const Mesh &mesh, const MeshNodes &mesh_nodes,
122 const Eigen::VectorXi &in_ordered_vertices,
123 const Eigen::MatrixXi &in_ordered_edges,
124 const Eigen::MatrixXi &in_ordered_faces,
125 Eigen::VectorXi &in_primitive_to_primitive)
126 {
127 // NOTE: Assume in_cells_to_cells is identity
128 const int num_vertex_nodes = mesh_nodes.num_vertex_nodes();
129 const int num_edge_nodes = mesh_nodes.num_edge_nodes();
130 const int num_face_nodes = mesh_nodes.num_face_nodes();
131 const int num_cell_nodes = mesh_nodes.num_cell_nodes();
132 const int num_nodes = num_vertex_nodes + num_edge_nodes + num_face_nodes + num_cell_nodes;
133
134 const long n_vertices = num_vertex_nodes;
135 const int num_in_primitives = n_vertices + mesh.n_edges() + mesh.n_faces() + mesh.n_cells();
136 const int num_primitives = mesh.n_vertices() + mesh.n_edges() + mesh.n_faces() + mesh.n_cells();
137
138 in_primitive_to_primitive.setLinSpaced(num_in_primitives, 0, num_in_primitives - 1);
139
140 igl::Timer timer;
141
142 // ------------
143 // Map vertices
144 // ------------
145
146 if (in_ordered_vertices.rows() != n_vertices)
147 {
148 logger().warn("Node ordering disabled, in_ordered_vertices != n_vertices, {} != {}", in_ordered_vertices.rows(), n_vertices);
149 return false;
150 }
151
152 in_primitive_to_primitive.head(n_vertices) = in_ordered_vertices;
153
154 int in_offset = n_vertices;
155 int offset = mesh.n_vertices();
156
157 // ---------
158 // Map edges
159 // ---------
160
161 logger().trace("Building Mesh edges to IDs...");
162 timer.start();
163 const auto edges_to_ids = mesh.edges_to_ids();
164 if (in_ordered_edges.rows() != edges_to_ids.size())
165 {
166 logger().warn("Node ordering disabled, in_ordered_edges != edges_to_ids, {} != {}", in_ordered_edges.rows(), edges_to_ids.size());
167 return false;
168 }
169 timer.stop();
170 logger().trace("Done (took {}s)", timer.getElapsedTime());
171
172 logger().trace("Building in-edge to edge mapping...");
173 timer.start();
174 for (int in_ei = 0; in_ei < in_ordered_edges.rows(); in_ei++)
175 {
176 const std::pair<int, int> in_edge(
177 in_ordered_edges.row(in_ei).minCoeff(),
178 in_ordered_edges.row(in_ei).maxCoeff());
179 in_primitive_to_primitive[in_offset + in_ei] =
180 offset + edges_to_ids.at(in_edge); // offset edge ids
181 }
182 timer.stop();
183 logger().trace("Done (took {}s)", timer.getElapsedTime());
184
185 in_offset += mesh.n_edges();
186 offset += mesh.n_edges();
187
188 // ---------
189 // Map faces
190 // ---------
191
192 if (mesh.is_volume())
193 {
194 logger().trace("Building Mesh faces to IDs...");
195 timer.start();
196 const auto faces_to_ids = mesh.faces_to_ids();
197 if (in_ordered_faces.rows() != faces_to_ids.size())
198 {
199 logger().warn("Node ordering disabled, in_ordered_faces != faces_to_ids, {} != {}", in_ordered_faces.rows(), faces_to_ids.size());
200 return false;
201 }
202 timer.stop();
203 logger().trace("Done (took {}s)", timer.getElapsedTime());
204
205 logger().trace("Building in-face to face mapping...");
206 timer.start();
207 for (int in_fi = 0; in_fi < in_ordered_faces.rows(); in_fi++)
208 {
209 std::vector<int> in_face(in_ordered_faces.cols());
210 for (int i = 0; i < in_face.size(); i++)
211 in_face[i] = in_ordered_faces(in_fi, i);
212 std::sort(in_face.begin(), in_face.end());
213
214 in_primitive_to_primitive[in_offset + in_fi] =
215 offset + faces_to_ids.at(in_face); // offset face ids
216 }
217 timer.stop();
218 logger().trace("Done (took {}s)", timer.getElapsedTime());
219
220 in_offset += mesh.n_faces();
221 offset += mesh.n_faces();
222 }
223
224 return true;
225 }
226 } // namespace
227
228 std::vector<int> State::primitive_to_node() const
229 {
230 auto indices = iso_parametric() ? mesh_nodes->primitive_to_node() : geom_mesh_nodes->primitive_to_node();
231 indices.resize(mesh->n_vertices());
232 return indices;
233 }
234
235 std::vector<int> State::node_to_primitive() const
236 {
237 auto p2n = primitive_to_node();
238 std::vector<int> indices;
239 indices.resize(n_geom_bases);
240 for (int i = 0; i < p2n.size(); i++)
241 indices[p2n[i]] = i;
242 return indices;
243 }
244
246 {
247 if (args["space"]["basis_type"] == "Spline")
248 {
249 logger().warn("Node ordering disabled, it dosent work for splines!");
250 return;
251 }
252
253 if (disc_orders.maxCoeff() >= 4 || disc_orders.maxCoeff() != disc_orders.minCoeff())
254 {
255 logger().warn("Node ordering disabled, it works only for p < 4 and uniform order!");
256 return;
257 }
258
259 if (!mesh->is_conforming())
260 {
261 logger().warn("Node ordering disabled, not supported for non-conforming meshes!");
262 return;
263 }
264
265 if (mesh->has_poly())
266 {
267 logger().warn("Node ordering disabled, not supported for polygonal meshes!");
268 return;
269 }
270
271 if (mesh->in_ordered_vertices().size() <= 0 || mesh->in_ordered_edges().size() <= 0 || (mesh->is_volume() && mesh->in_ordered_faces().size() <= 0))
272 {
273 logger().warn("Node ordering disabled, input vertices/edges/faces not computed!");
274 return;
275 }
276
277 const int num_vertex_nodes = mesh_nodes->num_vertex_nodes();
278 const int num_edge_nodes = mesh_nodes->num_edge_nodes();
279 const int num_face_nodes = mesh_nodes->num_face_nodes();
280 const int num_cell_nodes = mesh_nodes->num_cell_nodes();
281
282 const int num_nodes = num_vertex_nodes + num_edge_nodes + num_face_nodes + num_cell_nodes;
283
284 const long n_vertices = num_vertex_nodes;
285 const int num_in_primitives = n_vertices + mesh->n_edges() + mesh->n_faces() + mesh->n_cells();
286 const int num_primitives = mesh->n_vertices() + mesh->n_edges() + mesh->n_faces() + mesh->n_cells();
287
288 igl::Timer timer;
289
290 logger().trace("Building in-node to in-primitive mapping...");
291 timer.start();
292 Eigen::VectorXi in_node_to_in_primitive;
293 Eigen::VectorXi in_node_offset;
294 build_in_node_to_in_primitive(*mesh, *mesh_nodes, in_node_to_in_primitive, in_node_offset);
295 timer.stop();
296 logger().trace("Done (took {}s)", timer.getElapsedTime());
297
298 logger().trace("Building in-primitive to primitive mapping...");
299 timer.start();
300 bool ok = build_in_primitive_to_primitive(
301 *mesh, *mesh_nodes,
302 mesh->in_ordered_vertices(),
303 mesh->in_ordered_edges(),
304 mesh->in_ordered_faces(),
306 timer.stop();
307 logger().trace("Done (took {}s)", timer.getElapsedTime());
308
309 if (!ok)
310 {
311 in_node_to_node.resize(0);
313 return;
314 }
315 const auto &tmp = mesh_nodes->in_ordered_vertices();
316 int max_tmp = -1;
317 for (auto v : tmp)
318 max_tmp = std::max(max_tmp, v);
319
320 in_node_to_node.resize(max_tmp + 1);
321 for (int i = 0; i < tmp.size(); ++i)
322 {
323 if (tmp[i] >= 0)
324 in_node_to_node[tmp[i]] = i;
325 }
326 }
327
328 std::string State::formulation() const
329 {
330 if (args["materials"].is_null())
331 {
332 logger().error("specify some 'materials'");
333 assert(!args["materials"].is_null());
334 throw std::runtime_error("invalid input");
335 }
336
337 if (args["materials"].is_array())
338 {
339 std::string current = "";
340 for (const auto &m : args["materials"])
341 {
342 const std::string tmp = m["type"];
343 if (current.empty())
344 current = tmp;
345 else if (current != tmp)
346 {
347 if (current == "LinearElasticity"
348 || current == "NeoHookean"
349 || current == "SaintVenant"
350 || current == "HookeLinearElasticity"
351 || current == "MooneyRivlin"
352 || current == "MooneyRivlin3Param"
353 || current == "UnconstrainedOgden"
354 || current == "IncompressibleOgden"
355 || current == "MultiModels")
356 {
357 if (tmp == "LinearElasticity"
358 || tmp == "NeoHookean"
359 || tmp == "SaintVenant"
360 || tmp == "HookeLinearElasticity"
361 || tmp == "MooneyRivlin"
362 || current == "MooneyRivlin3Param"
363 || tmp == "UnconstrainedOgden"
364 || tmp == "IncompressibleOgden")
365 current = "MultiModels";
366 else
367 {
368 logger().error("Current material is {}, new material is {}, multimaterial supported only for LinearElasticity and NeoHookean", current, tmp);
369 throw std::runtime_error("invalid input");
370 }
371 }
372 else
373 {
374 logger().error("Current material is {}, new material is {}, multimaterial supported only for LinearElasticity and NeoHookean", current, tmp);
375 throw std::runtime_error("invalid input");
376 }
377 }
378 }
379
380 return current;
381 }
382 else
383 return args["materials"]["type"];
384 }
385
386 void State::sol_to_pressure(Eigen::MatrixXd &sol, Eigen::MatrixXd &pressure)
387 {
388 if (n_pressure_bases <= 0)
389 {
390 logger().error("No pressure bases defined!");
391 return;
392 }
393
394 assert(mixed_assembler != nullptr);
395 Eigen::MatrixXd tmp = sol;
396
397 int fluid_offset = use_avg_pressure ? (assembler->is_fluid() ? 1 : 0) : 0;
398 sol = tmp.topRows(tmp.rows() - n_pressure_bases - fluid_offset);
399 assert(sol.size() == n_bases * (problem->is_scalar() ? 1 : mesh->dimension()));
400 pressure = tmp.middleRows(tmp.rows() - n_pressure_bases - fluid_offset, n_pressure_bases);
401 assert(pressure.size() == n_pressure_bases);
402 }
403
405 const Mesh3D &mesh,
406 const int n_bases,
407 const std::vector<basis::ElementBases> &bases,
408 const std::vector<basis::ElementBases> &gbases,
409 Eigen::MatrixXd &basis_integrals)
410 {
411 if (!mesh.is_volume())
412 {
413 logger().error("Works only on volumetric meshes!");
414 return;
415 }
416 assert(mesh.is_volume());
417
418 basis_integrals.resize(n_bases, 9);
419 basis_integrals.setZero();
420 Eigen::MatrixXd rhs(n_bases, 9);
421 rhs.setZero();
422
423 const int n_elements = mesh.n_elements();
424 for (int e = 0; e < n_elements; ++e)
425 {
426 // if (mesh.is_polytope(e)) {
427 // continue;
428 // }
429 // ElementAssemblyValues vals = values[e];
430 // const ElementAssemblyValues &gvals = gvalues[e];
432 vals.compute(e, mesh.is_volume(), bases[e], gbases[e]);
433
434 // Computes the discretized integral of the PDE over the element
435 const int n_local_bases = int(vals.basis_values.size());
436 for (int j = 0; j < n_local_bases; ++j)
437 {
438 const AssemblyValues &v = vals.basis_values[j];
439 const double integral_100 = (v.grad_t_m.col(0).array() * vals.det.array() * vals.quadrature.weights.array()).sum();
440 const double integral_010 = (v.grad_t_m.col(1).array() * vals.det.array() * vals.quadrature.weights.array()).sum();
441 const double integral_001 = (v.grad_t_m.col(2).array() * vals.det.array() * vals.quadrature.weights.array()).sum();
442
443 const double integral_110 = ((vals.val.col(1).array() * v.grad_t_m.col(0).array() + vals.val.col(0).array() * v.grad_t_m.col(1).array()) * vals.det.array() * vals.quadrature.weights.array()).sum();
444 const double integral_011 = ((vals.val.col(2).array() * v.grad_t_m.col(1).array() + vals.val.col(1).array() * v.grad_t_m.col(2).array()) * vals.det.array() * vals.quadrature.weights.array()).sum();
445 const double integral_101 = ((vals.val.col(0).array() * v.grad_t_m.col(2).array() + vals.val.col(2).array() * v.grad_t_m.col(0).array()) * vals.det.array() * vals.quadrature.weights.array()).sum();
446
447 const double integral_200 = 2 * (vals.val.col(0).array() * v.grad_t_m.col(0).array() * vals.det.array() * vals.quadrature.weights.array()).sum();
448 const double integral_020 = 2 * (vals.val.col(1).array() * v.grad_t_m.col(1).array() * vals.det.array() * vals.quadrature.weights.array()).sum();
449 const double integral_002 = 2 * (vals.val.col(2).array() * v.grad_t_m.col(2).array() * vals.det.array() * vals.quadrature.weights.array()).sum();
450
451 const double area = (v.val.array() * vals.det.array() * vals.quadrature.weights.array()).sum();
452
453 for (size_t ii = 0; ii < v.global.size(); ++ii)
454 {
455 basis_integrals(v.global[ii].index, 0) += integral_100 * v.global[ii].val;
456 basis_integrals(v.global[ii].index, 1) += integral_010 * v.global[ii].val;
457 basis_integrals(v.global[ii].index, 2) += integral_001 * v.global[ii].val;
458
459 basis_integrals(v.global[ii].index, 3) += integral_110 * v.global[ii].val;
460 basis_integrals(v.global[ii].index, 4) += integral_011 * v.global[ii].val;
461 basis_integrals(v.global[ii].index, 5) += integral_101 * v.global[ii].val;
462
463 basis_integrals(v.global[ii].index, 6) += integral_200 * v.global[ii].val;
464 basis_integrals(v.global[ii].index, 7) += integral_020 * v.global[ii].val;
465 basis_integrals(v.global[ii].index, 8) += integral_002 * v.global[ii].val;
466
467 rhs(v.global[ii].index, 6) += -2.0 * area * v.global[ii].val;
468 rhs(v.global[ii].index, 7) += -2.0 * area * v.global[ii].val;
469 rhs(v.global[ii].index, 8) += -2.0 * area * v.global[ii].val;
470 }
471 }
472 }
473
474 basis_integrals -= rhs;
475 }
476
478 {
479 if (mesh->has_poly())
480 return true;
481
482 if (args["space"]["basis_type"] == "Spline")
483 return true;
484
485 if (mesh->is_rational())
486 return false;
487
488 if (args["space"]["use_p_ref"])
489 return false;
490
491 if (has_periodic_bc())
492 return false;
493
495 return false;
496
497 if (mesh->orders().size() <= 0)
498 {
499 if (args["space"]["discr_order"] == 1)
500 return true;
501 else
502 return args["space"]["advanced"]["isoparametric"];
503 }
504
505 if (mesh->orders().minCoeff() != mesh->orders().maxCoeff())
506 return false;
507
508 if (args["space"]["discr_order"] == mesh->orders().minCoeff())
509 return true;
510
511 // TODO:
512 // if (args["space"]["discr_order"] == 1 && args["force_linear_geometry"])
513 // return true;
514
515 return args["space"]["advanced"]["isoparametric"];
516 }
517
519 {
520 if (!mesh)
521 {
522 logger().error("Load the mesh first!");
523 return;
524 }
525
526 mesh->prepare_mesh();
527
528 bases.clear();
529 pressure_bases.clear();
530 geom_bases_.clear();
531 boundary_nodes.clear();
532 dirichlet_nodes.clear();
533 neumann_nodes.clear();
534 local_boundary.clear();
535 total_local_boundary.clear();
538 local_pressure_cavity.clear();
539 polys.clear();
540 poly_edge_to_data.clear();
541 rhs.resize(0, 0);
542 basis_nodes_to_gbasis_nodes.resize(0, 0);
543
544 if (assembler::MultiModel *mm = dynamic_cast<assembler::MultiModel *>(assembler.get()))
545 {
546 assert(args["materials"].is_array());
547
548 std::vector<std::string> materials(mesh->n_elements());
549
550 std::map<int, std::string> mats;
551
552 for (const auto &m : args["materials"])
553 mats[m["id"].get<int>()] = m["type"];
554
555 for (int i = 0; i < materials.size(); ++i)
556 materials[i] = mats.at(mesh->get_body_id(i));
557
558 mm->init_multimodels(materials);
559 }
560
561 n_bases = 0;
562 n_geom_bases = 0;
564
565 stats.reset();
566
567 disc_orders.resize(mesh->n_elements());
568
569 problem->init(*mesh);
570 logger().info("Building {} basis...", (iso_parametric() ? "isoparametric" : "not isoparametric"));
571 const bool has_polys = mesh->has_poly();
572
573 local_boundary.clear();
576 local_pressure_cavity.clear();
577 std::map<int, basis::InterfaceData> poly_edge_to_data_geom; // temp dummy variable
578
579 const auto &tmp_json = args["space"]["discr_order"];
580 if (tmp_json.is_number_integer())
581 {
582 disc_orders.setConstant(tmp_json);
583 }
584 else if (tmp_json.is_string())
585 {
586 const std::string discr_orders_path = tmp_json;
587 Eigen::MatrixXi tmp;
588 read_matrix(discr_orders_path, tmp);
589 assert(tmp.size() == disc_orders.size());
590 assert(tmp.cols() == 1);
591 disc_orders = tmp;
592 }
593 else if (tmp_json.is_array())
594 {
595 const auto b_discr_orders = tmp_json;
596
597 std::map<int, int> b_orders;
598 for (size_t i = 0; i < b_discr_orders.size(); ++i)
599 {
600 assert(b_discr_orders[i]["id"].is_array() || b_discr_orders[i]["id"].is_number_integer());
601
602 const int order = b_discr_orders[i]["order"];
603 for (const int id : json_as_array<int>(b_discr_orders[i]["id"]))
604 {
605 b_orders[id] = order;
606 logger().trace("bid {}, discr {}", id, order);
607 }
608 }
609
610 for (int e = 0; e < mesh->n_elements(); ++e)
611 {
612 const int bid = mesh->get_body_id(e);
613 const auto order = b_orders.find(bid);
614 if (order == b_orders.end())
615 {
616 logger().debug("Missing discretization order for body {}; using 1", bid);
617 b_orders[bid] = 1;
618 disc_orders[e] = 1;
619 }
620 else
621 {
622 disc_orders[e] = order->second;
623 }
624 }
625 }
626 else
627 {
628 logger().error("space/discr_order must be either a number a path or an array");
629 throw std::runtime_error("invalid json");
630 }
631 // TODO: same for pressure!
632
633 Eigen::MatrixXi geom_disc_orders;
634 if (!iso_parametric())
635 {
636 if (mesh->orders().size() <= 0)
637 {
638 geom_disc_orders.resizeLike(disc_orders);
639 geom_disc_orders.setConstant(1);
640 }
641 else
642 geom_disc_orders = mesh->orders();
643 }
644
645 igl::Timer timer;
646 timer.start();
647 if (args["space"]["use_p_ref"])
648 {
650 *mesh,
651 args["space"]["advanced"]["B"],
652 args["space"]["advanced"]["h1_formula"],
653 args["space"]["discr_order"],
654 args["space"]["advanced"]["discr_order_max"],
655 stats,
657
658 logger().info("min p: {} max p: {}", disc_orders.minCoeff(), disc_orders.maxCoeff());
659 }
660
661 int quadrature_order = args["space"]["advanced"]["quadrature_order"].get<int>();
662 const int mass_quadrature_order = args["space"]["advanced"]["mass_quadrature_order"].get<int>();
663 if (mixed_assembler != nullptr)
664 {
665 const int disc_order = disc_orders.maxCoeff();
666 if (disc_order - disc_orders.minCoeff() != 0)
667 {
668 logger().error("p refinement not supported in mixed formulation!");
669 return;
670 }
671 }
672
673 // shape optimization needs continuous geometric basis
674 // const bool use_continuous_gbasis = optimization_enabled == solver::CacheLevel::Derivatives;
675 const bool use_continuous_gbasis = true;
676
677 if (mesh->is_volume())
678 {
679 const Mesh3D &tmp_mesh = *dynamic_cast<Mesh3D *>(mesh.get());
680 if (args["space"]["basis_type"] == "Spline")
681 {
682 // if (!iso_parametric())
683 // {
684 // logger().error("Splines must be isoparametric, ignoring...");
685 // // LagrangeBasis3d::build_bases(tmp_mesh, quadrature_order, geom_disc_orders, has_polys, geom_bases_, local_boundary, poly_edge_to_data_geom, mesh_nodes);
686 // SplineBasis3d::build_bases(tmp_mesh, quadrature_order, geom_bases_, local_boundary, poly_edge_to_data);
687 // }
688
689 n_bases = basis::SplineBasis3d::build_bases(tmp_mesh, assembler->name(), quadrature_order, mass_quadrature_order, bases, local_boundary, poly_edge_to_data);
690
691 // if (iso_parametric() && args["fit_nodes"])
692 // SplineBasis3d::fit_nodes(tmp_mesh, n_bases, bases);
693 }
694 else
695 {
696 if (!iso_parametric())
697 n_geom_bases = basis::LagrangeBasis3d::build_bases(tmp_mesh, assembler->name(), quadrature_order, mass_quadrature_order, geom_disc_orders, false, has_polys, !use_continuous_gbasis, geom_bases_, local_boundary, poly_edge_to_data_geom, geom_mesh_nodes);
698
699 n_bases = basis::LagrangeBasis3d::build_bases(tmp_mesh, assembler->name(), quadrature_order, mass_quadrature_order, disc_orders, args["space"]["basis_type"] == "Serendipity", has_polys, false, bases, local_boundary, poly_edge_to_data, mesh_nodes);
700 }
701
702 // if(problem->is_mixed())
703 if (mixed_assembler != nullptr)
704 {
705 n_pressure_bases = basis::LagrangeBasis3d::build_bases(tmp_mesh, assembler->name(), quadrature_order, mass_quadrature_order, int(args["space"]["pressure_discr_order"]), false, has_polys, false, pressure_bases, local_boundary, poly_edge_to_data_geom, pressure_mesh_nodes);
706 }
707 }
708 else
709 {
710 const Mesh2D &tmp_mesh = *dynamic_cast<Mesh2D *>(mesh.get());
711 if (args["space"]["basis_type"] == "Spline")
712 {
713 // TODO:
714 // if (!iso_parametric())
715 // {
716 // logger().error("Splines must be isoparametric, ignoring...");
717 // // LagrangeBasis2d::build_bases(tmp_mesh, quadrature_order, disc_orders, has_polys, geom_bases_, local_boundary, poly_edge_to_data_geom, mesh_nodes);
718 // n_bases = SplineBasis2d::build_bases(tmp_mesh, quadrature_order, geom_bases_, local_boundary, poly_edge_to_data);
719 // }
720
721 n_bases = basis::SplineBasis2d::build_bases(tmp_mesh, assembler->name(), quadrature_order, mass_quadrature_order, bases, local_boundary, poly_edge_to_data);
722
723 // if (iso_parametric() && args["fit_nodes"])
724 // SplineBasis2d::fit_nodes(tmp_mesh, n_bases, bases);
725 }
726 else
727 {
728 if (!iso_parametric())
729 n_geom_bases = basis::LagrangeBasis2d::build_bases(tmp_mesh, assembler->name(), quadrature_order, mass_quadrature_order, geom_disc_orders, false, has_polys, !use_continuous_gbasis, geom_bases_, local_boundary, poly_edge_to_data_geom, geom_mesh_nodes);
730
731 n_bases = basis::LagrangeBasis2d::build_bases(tmp_mesh, assembler->name(), quadrature_order, mass_quadrature_order, disc_orders, args["space"]["basis_type"] == "Serendipity", has_polys, false, bases, local_boundary, poly_edge_to_data, mesh_nodes);
732 }
733
734 // if(problem->is_mixed())
735 if (mixed_assembler != nullptr)
736 {
737 n_pressure_bases = basis::LagrangeBasis2d::build_bases(tmp_mesh, assembler->name(), quadrature_order, mass_quadrature_order, int(args["space"]["pressure_discr_order"]), false, has_polys, false, pressure_bases, local_boundary, poly_edge_to_data_geom, pressure_mesh_nodes);
738 }
739 }
740
741 if (mixed_assembler != nullptr)
742 {
743 assert(bases.size() == pressure_bases.size());
744 for (int i = 0; i < pressure_bases.size(); ++i)
745 {
747 bases[i].compute_quadrature(b_quad);
748 pressure_bases[i].set_quadrature([b_quad](quadrature::Quadrature &quad) { quad = b_quad; });
749 }
750 }
751
752 timer.stop();
753
755
756 if (n_geom_bases == 0)
758
759 auto &gbases = geom_bases();
760
762 {
763 std::map<std::array<int, 2>, double> pairs;
764 for (int e = 0; e < gbases.size(); e++)
765 {
766 const auto &gbs = gbases[e].bases;
767 const auto &bs = bases[e].bases;
768
769 Eigen::MatrixXd local_pts;
770 const int order = bs.front().order();
771 if (mesh->is_volume())
772 {
773 if (mesh->is_simplex(e))
774 autogen::p_nodes_3d(order, local_pts);
775 else
776 autogen::q_nodes_3d(order, local_pts);
777 }
778 else
779 {
780 if (mesh->is_simplex(e))
781 autogen::p_nodes_2d(order, local_pts);
782 else
783 autogen::q_nodes_2d(order, local_pts);
784 }
785
787 vals.compute(e, mesh->is_volume(), local_pts, gbases[e], gbases[e]);
788
789 for (int i = 0; i < bs.size(); i++)
790 {
791 for (int j = 0; j < gbs.size(); j++)
792 {
793 if (std::abs(vals.basis_values[j].val(i)) > 1e-7)
794 {
795 std::array<int, 2> index = {{gbs[j].global()[0].index, bs[i].global()[0].index}};
796 pairs.insert({index, vals.basis_values[j].val(i)});
797 }
798 }
799 }
800 }
801
802 const int dim = mesh->dimension();
803 std::vector<Eigen::Triplet<double>> coeffs;
804 coeffs.clear();
805 for (const auto &iter : pairs)
806 for (int d = 0; d < dim; d++)
807 coeffs.emplace_back(iter.first[0] * dim + d, iter.first[1] * dim + d, iter.second);
808
809 basis_nodes_to_gbasis_nodes.resize(n_geom_bases * mesh->dimension(), n_bases * mesh->dimension());
810 basis_nodes_to_gbasis_nodes.setFromTriplets(coeffs.begin(), coeffs.end());
811 }
812
813 for (const auto &lb : local_boundary)
814 total_local_boundary.emplace_back(lb);
815
816 const int dim = mesh->dimension();
817 const int problem_dim = problem->is_scalar() ? 1 : dim;
818
819 // handle periodic bc
820 if (has_periodic_bc())
821 {
822 // collect periodic directions
823 json directions = args["boundary_conditions"]["periodic_boundary"]["correspondence"];
824 Eigen::MatrixXd tile_offset = Eigen::MatrixXd::Identity(dim, dim);
825
826 if (directions.size() > 0)
827 {
828 Eigen::VectorXd tmp;
829 for (int d = 0; d < dim; d++)
830 {
831 tmp = directions[d];
832 if (tmp.size() != dim)
833 log_and_throw_error("Invalid size of periodic directions!");
834 tile_offset.col(d) = tmp;
835 }
836 }
837
838 periodic_bc = std::make_shared<PeriodicBoundary>(problem->is_scalar(), n_bases, bases, mesh_nodes, tile_offset, args["boundary_conditions"]["periodic_boundary"]["tolerance"].get<double>());
839
840 macro_strain_constraint.init(dim, args["boundary_conditions"]["periodic_boundary"]);
841 }
842
843 if (args["space"]["advanced"]["count_flipped_els"])
845
846 const int prev_bases = n_bases;
848
849 {
850 igl::Timer timer2;
851 logger().debug("Building node mapping...");
852 timer2.start();
854 problem->update_nodes(in_node_to_node);
855 mesh->update_nodes(in_node_to_node);
856 timer2.stop();
857 logger().debug("Done (took {}s)", timer2.getElapsedTime());
858 }
859
860 logger().info("Building collision mesh...");
862 if (periodic_bc && args["contact"]["periodic"])
864 logger().info("Done!");
865
866 const int prev_b_size = local_boundary.size();
867 problem->setup_bc(*mesh, n_bases - obstacle.n_vertices(),
876
877 // setp nodal values
878 {
880 for (int n = 0; n < dirichlet_nodes.size(); ++n)
881 {
882 const int n_id = dirichlet_nodes[n];
883 bool found = false;
884 for (const auto &bs : bases)
885 {
886 for (const auto &b : bs.bases)
887 {
888 for (const auto &lg : b.global())
889 {
890 if (lg.index == n_id)
891 {
892 dirichlet_nodes_position[n] = lg.node;
893 found = true;
894 break;
895 }
896 }
897
898 if (found)
899 break;
900 }
901
902 if (found)
903 break;
904 }
905
906 assert(found);
907 }
908
910 for (int n = 0; n < neumann_nodes.size(); ++n)
911 {
912 const int n_id = neumann_nodes[n];
913 bool found = false;
914 for (const auto &bs : bases)
915 {
916 for (const auto &b : bs.bases)
917 {
918 for (const auto &lg : b.global())
919 {
920 if (lg.index == n_id)
921 {
922 neumann_nodes_position[n] = lg.node;
923 found = true;
924 break;
925 }
926 }
927
928 if (found)
929 break;
930 }
931
932 if (found)
933 break;
934 }
935
936 assert(found);
937 }
938 }
939
940 const bool has_neumann = local_neumann_boundary.size() > 0 || local_boundary.size() < prev_b_size;
941 use_avg_pressure = !has_neumann;
942
943 for (int i = prev_bases; i < n_bases; ++i)
944 {
945 for (int d = 0; d < problem_dim; ++d)
946 boundary_nodes.push_back(i * problem_dim + d);
947 }
948
949 std::sort(boundary_nodes.begin(), boundary_nodes.end());
950 auto it = std::unique(boundary_nodes.begin(), boundary_nodes.end());
951 boundary_nodes.resize(std::distance(boundary_nodes.begin(), it));
952
953 // for elastic pure periodic problem, find an internal node and force zero dirichlet
954 if ((!problem->is_time_dependent() || args["time"]["quasistatic"]) && boundary_nodes.size() == 0 && has_periodic_bc())
955 {
956 // find an internal node to force zero dirichlet
957 std::vector<bool> isboundary(n_bases, false);
958 for (const auto &lb : total_local_boundary)
959 {
960 const int e = lb.element_id();
961 for (int i = 0; i < lb.size(); ++i)
962 {
963 const auto nodes = bases[e].local_nodes_for_primitive(lb.global_primitive_id(i), *mesh);
964
965 for (int n : nodes)
966 isboundary[bases[e].bases[n].global()[0].index] = true;
967 }
968 }
969 int i = 0;
970 for (; i < n_bases; i++)
971 if (!isboundary[i]) // (!periodic_bc->is_periodic_dof(i))
972 break;
973 if (i >= n_bases)
974 log_and_throw_error("Failed to find a non-periodic node!");
975 const int actual_dim = problem->is_scalar() ? 1 : mesh->dimension();
976 for (int d = 0; d < actual_dim; d++)
977 {
978 boundary_nodes.push_back(i * actual_dim + d);
979 }
980 logger().info("Fix solution at node {} to remove singularity due to periodic BC", i);
981 }
982
983 const auto &curret_bases = geom_bases();
984 const int n_samples = 10;
985 stats.compute_mesh_size(*mesh, curret_bases, n_samples, args["output"]["advanced"]["curved_mesh_size"]);
987 {
989 }
991 {
993 }
994
995 if (is_contact_enabled())
996 {
997 min_boundary_edge_length = std::numeric_limits<double>::max();
998 for (const auto &edge : collision_mesh.edges().rowwise())
999 {
1000 const VectorNd v0 = collision_mesh.rest_positions().row(edge(0));
1001 const VectorNd v1 = collision_mesh.rest_positions().row(edge(1));
1002 min_boundary_edge_length = std::min(min_boundary_edge_length, (v1 - v0).norm());
1003 }
1004
1005 double dhat = Units::convert(args["contact"]["dhat"], units.length());
1006 args["contact"]["epsv"] = Units::convert(args["contact"]["epsv"], units.velocity());
1007 args["contact"]["dhat"] = dhat;
1008
1009 if (!has_dhat && dhat > min_boundary_edge_length)
1010 {
1011 args["contact"]["dhat"] = double(args["contact"]["dhat_percentage"]) * min_boundary_edge_length;
1012 logger().info("dhat set to {}", double(args["contact"]["dhat"]));
1013 }
1014 else
1015 {
1016 if (dhat > min_boundary_edge_length)
1017 logger().warn("dhat larger than min boundary edge, {} > {}", dhat, min_boundary_edge_length);
1018 }
1019 }
1020
1021 logger().info("n_bases {}", n_bases);
1022
1023 timings.building_basis_time = timer.getElapsedTime();
1024 logger().info(" took {}s", timings.building_basis_time);
1025
1026 logger().info("flipped elements {}", stats.n_flipped);
1027 logger().info("h: {}", stats.mesh_size);
1028 logger().info("n bases: {}", n_bases);
1029 logger().info("n pressure bases: {}", n_pressure_bases);
1030
1033 if (n_bases <= args["solver"]["advanced"]["cache_size"])
1034 {
1035 timer.start();
1036 logger().info("Building cache...");
1037 ass_vals_cache.init(mesh->is_volume(), bases, curret_bases);
1038 mass_ass_vals_cache.init(mesh->is_volume(), bases, curret_bases, true);
1039 if (mixed_assembler != nullptr)
1040 pressure_ass_vals_cache.init(mesh->is_volume(), pressure_bases, curret_bases);
1041
1042 logger().info(" took {}s", timer.getElapsedTime());
1043 }
1044
1045 out_geom.build_grid(*mesh, args["output"]["advanced"]["sol_on_grid"]);
1046
1047 if ((!problem->is_time_dependent() || args["time"]["quasistatic"]) && boundary_nodes.empty())
1048 {
1049 if (has_periodic_bc())
1050 logger().warn("(Quasi-)Static problem without Dirichlet nodes, will fix solution at one node to find a unique solution!");
1051 else
1052 log_and_throw_error("Static problem need to have some Dirichlet nodes!");
1053 }
1054 }
1055
1057 {
1058 if (!mesh)
1059 {
1060 logger().error("Load the mesh first!");
1061 return;
1062 }
1063
1064 rhs.resize(0, 0);
1065
1066 if (poly_edge_to_data.empty() && polys.empty())
1067 {
1069 return;
1070 }
1071
1072 igl::Timer timer;
1073 timer.start();
1074 logger().info("Computing polygonal basis...");
1075
1076 // std::sort(boundary_nodes.begin(), boundary_nodes.end());
1077
1078 // mixed not supports polygonal bases
1079 assert(n_pressure_bases == 0 || poly_edge_to_data.size() == 0);
1080
1081 int new_bases = 0;
1082
1083 if (iso_parametric())
1084 {
1085 if (mesh->is_volume())
1086 {
1087 if (args["space"]["poly_basis_type"] == "MeanValue" || args["space"]["poly_basis_type"] == "Wachspress")
1088 logger().error("Barycentric bases not supported in 3D");
1089 assert(assembler->is_linear());
1091 *dynamic_cast<LinearAssembler *>(assembler.get()),
1092 args["space"]["advanced"]["n_harmonic_samples"],
1093 *dynamic_cast<Mesh3D *>(mesh.get()),
1094 n_bases,
1095 args["space"]["advanced"]["quadrature_order"],
1096 args["space"]["advanced"]["mass_quadrature_order"],
1097 args["space"]["advanced"]["integral_constraints"],
1098 bases,
1099 bases,
1101 polys_3d);
1102 }
1103 else
1104 {
1105 if (args["space"]["poly_basis_type"] == "MeanValue")
1106 {
1108 assembler->name(),
1109 assembler->is_tensor() ? 2 : 1,
1110 *dynamic_cast<Mesh2D *>(mesh.get()),
1111 n_bases,
1112 args["space"]["advanced"]["quadrature_order"],
1113 args["space"]["advanced"]["mass_quadrature_order"],
1115 }
1116 else if (args["space"]["poly_basis_type"] == "Wachspress")
1117 {
1119 assembler->name(),
1120 assembler->is_tensor() ? 2 : 1,
1121 *dynamic_cast<Mesh2D *>(mesh.get()),
1122 n_bases,
1123 args["space"]["advanced"]["quadrature_order"],
1124 args["space"]["advanced"]["mass_quadrature_order"],
1126 }
1127 else
1128 {
1129 assert(assembler->is_linear());
1131 *dynamic_cast<LinearAssembler *>(assembler.get()),
1132 args["space"]["advanced"]["n_harmonic_samples"],
1133 *dynamic_cast<Mesh2D *>(mesh.get()),
1134 n_bases,
1135 args["space"]["advanced"]["quadrature_order"],
1136 args["space"]["advanced"]["mass_quadrature_order"],
1137 args["space"]["advanced"]["integral_constraints"],
1138 bases,
1139 bases,
1141 polys);
1142 }
1143 }
1144 }
1145 else
1146 {
1147 if (mesh->is_volume())
1148 {
1149 if (args["space"]["poly_basis_type"] == "MeanValue" || args["space"]["poly_basis_type"] == "Wachspress")
1150 {
1151 logger().error("Barycentric bases not supported in 3D");
1152 throw std::runtime_error("not implemented");
1153 }
1154 else
1155 {
1156 assert(assembler->is_linear());
1158 *dynamic_cast<LinearAssembler *>(assembler.get()),
1159 args["space"]["advanced"]["n_harmonic_samples"],
1160 *dynamic_cast<Mesh3D *>(mesh.get()),
1161 n_bases,
1162 args["space"]["advanced"]["quadrature_order"],
1163 args["space"]["advanced"]["mass_quadrature_order"],
1164 args["space"]["advanced"]["integral_constraints"],
1165 bases,
1168 polys_3d);
1169 }
1170 }
1171 else
1172 {
1173 if (args["space"]["poly_basis_type"] == "MeanValue")
1174 {
1176 assembler->name(),
1177 assembler->is_tensor() ? 2 : 1,
1178 *dynamic_cast<Mesh2D *>(mesh.get()),
1179 n_bases, args["space"]["advanced"]["quadrature_order"],
1180 args["space"]["advanced"]["mass_quadrature_order"],
1182 }
1183 else if (args["space"]["poly_basis_type"] == "Wachspress")
1184 {
1186 assembler->name(),
1187 assembler->is_tensor() ? 2 : 1,
1188 *dynamic_cast<Mesh2D *>(mesh.get()),
1189 n_bases, args["space"]["advanced"]["quadrature_order"],
1190 args["space"]["advanced"]["mass_quadrature_order"],
1192 }
1193 else
1194 {
1195 assert(assembler->is_linear());
1197 *dynamic_cast<LinearAssembler *>(assembler.get()),
1198 args["space"]["advanced"]["n_harmonic_samples"],
1199 *dynamic_cast<Mesh2D *>(mesh.get()),
1200 n_bases,
1201 args["space"]["advanced"]["quadrature_order"],
1202 args["space"]["advanced"]["mass_quadrature_order"],
1203 args["space"]["advanced"]["integral_constraints"],
1204 bases,
1207 polys);
1208 }
1209 }
1210 }
1211
1212 timer.stop();
1213 timings.computing_poly_basis_time = timer.getElapsedTime();
1214 logger().info(" took {}s", timings.computing_poly_basis_time);
1215
1216 n_bases += new_bases;
1217 }
1218
1220 {
1221 assert(!mesh->is_volume());
1222 const int dim = mesh->dimension();
1223 const int n_tiles = 2;
1224
1225 if (mesh->dimension() != 2)
1226 log_and_throw_error("Periodic collision mesh is only implemented in 2D!");
1227
1228 Eigen::MatrixXd V(n_bases, dim);
1229 for (const auto &bs : bases)
1230 for (const auto &b : bs.bases)
1231 for (const auto &g : b.global())
1232 V.row(g.index) = g.node;
1233
1234 Eigen::MatrixXi E = collision_mesh.edges();
1235 for (int i = 0; i < E.size(); i++)
1236 E(i) = collision_mesh.to_full_vertex_id(E(i));
1237
1238 Eigen::MatrixXd bbox(V.cols(), 2);
1239 bbox.col(0) = V.colwise().minCoeff();
1240 bbox.col(1) = V.colwise().maxCoeff();
1241
1242 // remove boundary edges on periodic BC, buggy
1243 {
1244 std::vector<int> ind;
1245 for (int i = 0; i < E.rows(); i++)
1246 {
1247 if (!periodic_bc->is_periodic_dof(E(i, 0)) || !periodic_bc->is_periodic_dof(E(i, 1)))
1248 ind.push_back(i);
1249 }
1250
1251 E = E(ind, Eigen::all).eval();
1252 }
1253
1254 Eigen::MatrixXd Vtmp, Vnew;
1255 Eigen::MatrixXi Etmp, Enew;
1256 Vtmp.setZero(V.rows() * n_tiles * n_tiles, V.cols());
1257 Etmp.setZero(E.rows() * n_tiles * n_tiles, E.cols());
1258
1259 Eigen::MatrixXd tile_offset = periodic_bc->get_affine_matrix();
1260
1261 for (int i = 0, idx = 0; i < n_tiles; i++)
1262 {
1263 for (int j = 0; j < n_tiles; j++)
1264 {
1265 Eigen::Vector2d block_id;
1266 block_id << i, j;
1267
1268 Vtmp.middleRows(idx * V.rows(), V.rows()) = V;
1269 // Vtmp.block(idx * V.rows(), 0, V.rows(), 1).array() += tile_offset(0) * i;
1270 // Vtmp.block(idx * V.rows(), 1, V.rows(), 1).array() += tile_offset(1) * j;
1271 for (int vid = 0; vid < V.rows(); vid++)
1272 Vtmp.block(idx * V.rows() + vid, 0, 1, 2) += (tile_offset * block_id).transpose();
1273
1274 Etmp.middleRows(idx * E.rows(), E.rows()) = E.array() + idx * V.rows();
1275 idx += 1;
1276 }
1277 }
1278
1279 // clean duplicated vertices
1280 Eigen::VectorXi indices;
1281 {
1282 std::vector<int> tmp;
1283 for (int i = 0; i < V.rows(); i++)
1284 {
1285 if (periodic_bc->is_periodic_dof(i))
1286 tmp.push_back(i);
1287 }
1288
1289 indices.resize(tmp.size() * n_tiles * n_tiles);
1290 for (int i = 0; i < n_tiles * n_tiles; i++)
1291 {
1292 indices.segment(i * tmp.size(), tmp.size()) = Eigen::Map<Eigen::VectorXi, Eigen::Unaligned>(tmp.data(), tmp.size());
1293 indices.segment(i * tmp.size(), tmp.size()).array() += i * V.rows();
1294 }
1295 }
1296
1297 Eigen::VectorXi potentially_duplicate_mask(Vtmp.rows());
1298 potentially_duplicate_mask.setZero();
1299 potentially_duplicate_mask(indices).array() = 1;
1300
1301 Eigen::MatrixXd candidates = Vtmp(indices, Eigen::all);
1302
1303 Eigen::VectorXi SVI;
1304 std::vector<int> SVJ;
1305 SVI.setConstant(Vtmp.rows(), -1);
1306 int id = 0;
1307 const double eps = (bbox.col(1) - bbox.col(0)).maxCoeff() * args["boundary_conditions"]["periodic_boundary"]["tolerance"].get<double>();
1308 for (int i = 0; i < Vtmp.rows(); i++)
1309 {
1310 if (SVI[i] < 0)
1311 {
1312 SVI[i] = id;
1313 SVJ.push_back(i);
1314 if (potentially_duplicate_mask(i))
1315 {
1316 Eigen::VectorXd diffs = (candidates.rowwise() - Vtmp.row(i)).rowwise().norm();
1317 for (int j = 0; j < diffs.size(); j++)
1318 if (diffs(j) < eps)
1319 SVI[indices[j]] = id;
1320 }
1321 id++;
1322 }
1323 }
1324
1325 Vnew = Vtmp(SVJ, Eigen::all);
1326
1327 Enew.resizeLike(Etmp);
1328 for (int d = 0; d < Etmp.cols(); d++)
1329 Enew.col(d) = SVI(Etmp.col(d));
1330
1331 std::vector<bool> is_on_surface = ipc::CollisionMesh::construct_is_on_surface(Vnew.rows(), Enew);
1332
1333 Eigen::MatrixXi boundary_triangles;
1334 Eigen::SparseMatrix<double> displacement_map;
1335 periodic_collision_mesh = ipc::CollisionMesh(is_on_surface,
1336 Vnew,
1337 Enew,
1338 boundary_triangles,
1339 displacement_map);
1340
1341 periodic_collision_mesh.init_area_jacobians();
1342
1343 periodic_collision_mesh_to_basis.setConstant(Vnew.rows(), -1);
1344 for (int i = 0; i < V.rows(); i++)
1345 for (int j = 0; j < n_tiles * n_tiles; j++)
1346 periodic_collision_mesh_to_basis(SVI[j * V.rows() + i]) = i;
1347
1348 if (periodic_collision_mesh_to_basis.maxCoeff() + 1 != V.rows())
1349 log_and_throw_error("Failed to tile mesh!");
1350 }
1351
1353 {
1356 args, [this](const std::string &p) { return resolve_input_path(p); },
1358 }
1359
1361 const mesh::Mesh &mesh,
1362 const int n_bases,
1363 const std::vector<basis::ElementBases> &bases,
1364 const std::vector<basis::ElementBases> &geom_bases,
1365 const std::vector<mesh::LocalBoundary> &total_local_boundary,
1366 const mesh::Obstacle &obstacle,
1367 const json &args,
1368 const std::function<std::string(const std::string &)> &resolve_input_path,
1369 const Eigen::VectorXi &in_node_to_node,
1370 ipc::CollisionMesh &collision_mesh)
1371 {
1372 Eigen::MatrixXd collision_vertices;
1373 Eigen::VectorXi collision_codim_vids;
1374 Eigen::MatrixXi collision_edges, collision_triangles;
1375 std::vector<Eigen::Triplet<double>> displacement_map_entries;
1376
1377 if (args.contains("/contact/collision_mesh"_json_pointer)
1378 && args.at("/contact/collision_mesh/enabled"_json_pointer).get<bool>())
1379 {
1380 const json collision_mesh_args = args.at("/contact/collision_mesh"_json_pointer);
1381 if (collision_mesh_args.contains("linear_map"))
1382 {
1383 assert(displacement_map_entries.empty());
1384 assert(collision_mesh_args.contains("mesh"));
1385 const std::string root_path = utils::json_value<std::string>(args, "root_path", "");
1386 // TODO: handle transformation per geometry
1387 const json transformation = json_as_array(args["geometry"])[0]["transformation"];
1389 utils::resolve_path(collision_mesh_args["mesh"], root_path),
1390 utils::resolve_path(collision_mesh_args["linear_map"], root_path),
1391 in_node_to_node, transformation, collision_vertices, collision_codim_vids,
1392 collision_edges, collision_triangles, displacement_map_entries);
1393 }
1394 else
1395 {
1396 assert(collision_mesh_args.contains("max_edge_length"));
1397 logger().debug(
1398 "Building collision proxy with max edge length={} ...",
1399 collision_mesh_args["max_edge_length"].get<double>());
1400 igl::Timer timer;
1401 timer.start();
1404 collision_mesh_args["max_edge_length"], collision_vertices,
1405 collision_triangles, displacement_map_entries,
1406 collision_mesh_args["tessellation_type"]);
1407 if (collision_triangles.size())
1408 igl::edges(collision_triangles, collision_edges);
1409 timer.stop();
1410 logger().debug(fmt::format(
1411 std::locale("en_US.UTF-8"),
1412 "Done (took {:g}s, {:L} vertices, {:L} triangles)",
1413 timer.getElapsedTime(),
1414 collision_vertices.rows(), collision_triangles.rows()));
1415 }
1416 }
1417 else
1418 {
1421 collision_vertices, collision_edges, collision_triangles, displacement_map_entries);
1422 }
1423
1424 // n_bases already contains the obstacle vertices
1425 const int num_fe_nodes = n_bases - obstacle.n_vertices();
1426 const int num_fe_collision_vertices = collision_vertices.rows();
1427 assert(collision_edges.size() == 0 || collision_edges.maxCoeff() < num_fe_collision_vertices);
1428 assert(collision_triangles.size() == 0 || collision_triangles.maxCoeff() < num_fe_collision_vertices);
1429
1430 // Append the obstacles to the collision mesh
1431 if (obstacle.n_vertices() > 0)
1432 {
1433 append_rows(collision_vertices, obstacle.v());
1434 append_rows(collision_codim_vids, obstacle.codim_v().array() + num_fe_collision_vertices);
1435 append_rows(collision_edges, obstacle.e().array() + num_fe_collision_vertices);
1436 append_rows(collision_triangles, obstacle.f().array() + num_fe_collision_vertices);
1437
1438 if (!displacement_map_entries.empty())
1439 {
1440 displacement_map_entries.reserve(displacement_map_entries.size() + obstacle.n_vertices());
1441 for (int i = 0; i < obstacle.n_vertices(); i++)
1442 {
1443 displacement_map_entries.emplace_back(num_fe_collision_vertices + i, num_fe_nodes + i, 1.0);
1444 }
1445 }
1446 }
1447
1448 std::vector<bool> is_on_surface = ipc::CollisionMesh::construct_is_on_surface(
1449 collision_vertices.rows(), collision_edges);
1450 for (const int vid : collision_codim_vids)
1451 {
1452 is_on_surface[vid] = true;
1453 }
1454
1455 Eigen::SparseMatrix<double> displacement_map;
1456 if (!displacement_map_entries.empty())
1457 {
1458 displacement_map.resize(collision_vertices.rows(), n_bases);
1459 displacement_map.setFromTriplets(displacement_map_entries.begin(), displacement_map_entries.end());
1460 }
1461
1462 collision_mesh = ipc::CollisionMesh(
1463 is_on_surface, collision_vertices, collision_edges, collision_triangles,
1464 displacement_map);
1465
1466 collision_mesh.can_collide = [&collision_mesh, num_fe_collision_vertices](size_t vi, size_t vj) {
1467 // obstacles do not collide with other obstacles
1468 return collision_mesh.to_full_vertex_id(vi) < num_fe_collision_vertices
1469 || collision_mesh.to_full_vertex_id(vj) < num_fe_collision_vertices;
1470 };
1471
1472 collision_mesh.init_area_jacobians();
1473 }
1474
1476 {
1477 if (!mesh)
1478 {
1479 logger().error("Load the mesh first!");
1480 return;
1481 }
1482 if (n_bases <= 0)
1483 {
1484 logger().error("Build the bases first!");
1485 return;
1486 }
1487 if (assembler->name() == "OperatorSplitting")
1488 {
1490 avg_mass = 1;
1491 return;
1492 }
1493
1494 if (!problem->is_time_dependent())
1495 {
1496 avg_mass = 1;
1498 return;
1499 }
1500
1501 mass.resize(0, 0);
1502
1503 igl::Timer timer;
1504 timer.start();
1505 logger().info("Assembling mass mat...");
1506
1507 if (mixed_assembler != nullptr)
1508 {
1509 StiffnessMatrix velocity_mass;
1510 mass_matrix_assembler->assemble(mesh->is_volume(), n_bases, bases, geom_bases(), mass_ass_vals_cache, 0, velocity_mass, true);
1511
1512 std::vector<Eigen::Triplet<double>> mass_blocks;
1513 mass_blocks.reserve(velocity_mass.nonZeros());
1514
1515 for (int k = 0; k < velocity_mass.outerSize(); ++k)
1516 {
1517 for (StiffnessMatrix::InnerIterator it(velocity_mass, k); it; ++it)
1518 {
1519 mass_blocks.emplace_back(it.row(), it.col(), it.value());
1520 }
1521 }
1522
1523 mass.resize(n_bases * assembler->size(), n_bases * assembler->size());
1524 mass.setFromTriplets(mass_blocks.begin(), mass_blocks.end());
1525 mass.makeCompressed();
1526 }
1527 else
1528 {
1529 mass_matrix_assembler->assemble(mesh->is_volume(), n_bases, bases, geom_bases(), mass_ass_vals_cache, 0, mass, true);
1530 }
1531
1532 assert(mass.size() > 0);
1533
1534 avg_mass = 0;
1535 for (int k = 0; k < mass.outerSize(); ++k)
1536 {
1537
1538 for (StiffnessMatrix::InnerIterator it(mass, k); it; ++it)
1539 {
1540 assert(it.col() == k);
1541 avg_mass += it.value();
1542 }
1543 }
1544
1545 avg_mass /= mass.rows();
1546 logger().info("average mass {}", avg_mass);
1547
1548 if (args["solver"]["advanced"]["lump_mass_matrix"])
1549 {
1551 }
1552
1553 timer.stop();
1554 timings.assembling_mass_mat_time = timer.getElapsedTime();
1555 logger().info(" took {}s", timings.assembling_mass_mat_time);
1556
1557 stats.nn_zero = mass.nonZeros();
1558 stats.num_dofs = mass.rows();
1559 stats.mat_size = (long long)mass.rows() * (long long)mass.cols();
1560 logger().info("sparsity: {}/{}", stats.nn_zero, stats.mat_size);
1561 }
1562
1563 std::shared_ptr<RhsAssembler> State::build_rhs_assembler(
1564 const int n_bases_,
1565 const std::vector<basis::ElementBases> &bases_,
1566 const assembler::AssemblyValsCache &ass_vals_cache_) const
1567 {
1568 json rhs_solver_params = args["solver"]["linear"];
1569 if (!rhs_solver_params.contains("Pardiso"))
1570 rhs_solver_params["Pardiso"] = {};
1571 rhs_solver_params["Pardiso"]["mtype"] = -2; // matrix type for Pardiso (2 = SPD)
1572
1573 const int size = problem->is_scalar() ? 1 : mesh->dimension();
1574
1575 return std::make_shared<RhsAssembler>(
1579 n_bases_, size, bases_, geom_bases(), ass_vals_cache_, *problem,
1580 args["space"]["advanced"]["bc_method"],
1581 rhs_solver_params);
1582 }
1583
1584 std::shared_ptr<PressureAssembler> State::build_pressure_assembler(
1585 const int n_bases_,
1586 const std::vector<basis::ElementBases> &bases_) const
1587 {
1588 const int size = problem->is_scalar() ? 1 : mesh->dimension();
1589
1590 return std::make_shared<PressureAssembler>(
1596 n_bases_, size, bases_, geom_bases(), *problem);
1597 }
1598
1600 {
1601 if (!mesh)
1602 {
1603 logger().error("Load the mesh first!");
1604 return;
1605 }
1606 if (n_bases <= 0)
1607 {
1608 logger().error("Build the bases first!");
1609 return;
1610 }
1611
1612 igl::Timer timer;
1613
1614 json p_params = {};
1615 p_params["formulation"] = assembler->name();
1616 p_params["root_path"] = root_path();
1617 {
1618 RowVectorNd min, max, delta;
1619 mesh->bounding_box(min, max);
1620 delta = (max - min) / 2. + min;
1621 if (mesh->is_volume())
1622 p_params["bbox_center"] = {delta(0), delta(1), delta(2)};
1623 else
1624 p_params["bbox_center"] = {delta(0), delta(1)};
1625 }
1626 problem->set_parameters(p_params);
1627
1628 rhs.resize(0, 0);
1629
1630 timer.start();
1631 logger().info("Assigning rhs...");
1632
1634 solve_data.rhs_assembler->assemble(mass_matrix_assembler->density(), rhs);
1635 rhs *= -1;
1636
1637 // if(problem->is_mixed())
1638 if (mixed_assembler != nullptr)
1639 {
1640 const int prev_size = rhs.size();
1641 const int n_larger = n_pressure_bases + (use_avg_pressure ? (assembler->is_fluid() ? 1 : 0) : 0);
1642 rhs.conservativeResize(prev_size + n_larger, rhs.cols());
1643 if (assembler->name() == "OperatorSplitting")
1644 {
1646 return;
1647 }
1648 // Divergence free rhs
1649 if (assembler->name() != "Bilaplacian" || local_neumann_boundary.empty())
1650 {
1651 rhs.block(prev_size, 0, n_larger, rhs.cols()).setZero();
1652 }
1653 else
1654 {
1655 Eigen::MatrixXd tmp(n_pressure_bases, 1);
1656 tmp.setZero();
1657
1658 std::shared_ptr<RhsAssembler> tmp_rhs_assembler = build_rhs_assembler(
1660
1661 tmp_rhs_assembler->set_bc(std::vector<LocalBoundary>(), std::vector<int>(), n_boundary_samples(), local_neumann_boundary, tmp);
1662 rhs.block(prev_size, 0, n_larger, rhs.cols()) = tmp;
1663 }
1664 }
1665
1666 timer.stop();
1667 timings.assigning_rhs_time = timer.getElapsedTime();
1668 logger().info(" took {}s", timings.assigning_rhs_time);
1669 }
1670
1671 void State::solve_problem(Eigen::MatrixXd &sol, Eigen::MatrixXd &pressure)
1672 {
1673 if (!mesh)
1674 {
1675 logger().error("Load the mesh first!");
1676 return;
1677 }
1678 if (n_bases <= 0)
1679 {
1680 logger().error("Build the bases first!");
1681 return;
1682 }
1683
1684 // if (rhs.size() <= 0)
1685 // {
1686 // logger().error("Assemble the rhs first!");
1687 // return;
1688 // }
1689
1690 // sol.resize(0, 0);
1691 // pressure.resize(0, 0);
1692 stats.spectrum.setZero();
1693
1694 igl::Timer timer;
1695 timer.start();
1696 logger().info("Solving {}", assembler->name());
1697
1698 init_solve(sol, pressure);
1699
1700 if (problem->is_time_dependent())
1701 {
1702 const double t0 = args["time"]["t0"];
1703 const int time_steps = args["time"]["time_steps"];
1704 const double dt = args["time"]["dt"];
1705
1706 // Pre log the output path for easier watching
1707 if (args["output"]["advanced"]["save_time_sequence"])
1708 {
1709 logger().info("Time sequence of simulation will be written to: \"{}\"",
1710 resolve_output_path(args["output"]["paraview"]["file_name"]));
1711 }
1712
1713 if (assembler->name() == "NavierStokes")
1714 solve_transient_navier_stokes(time_steps, t0, dt, sol, pressure);
1715 else if (assembler->name() == "OperatorSplitting")
1716 solve_transient_navier_stokes_split(time_steps, dt, sol, pressure);
1717 else if (is_homogenization())
1718 solve_homogenization(time_steps, t0, dt, sol);
1719 else if (is_problem_linear())
1720 solve_transient_linear(time_steps, t0, dt, sol, pressure);
1721 else if (!assembler->is_linear() && problem->is_scalar())
1722 throw std::runtime_error("Nonlinear scalar problems are not supported yet!");
1723 else
1724 solve_transient_tensor_nonlinear(time_steps, t0, dt, sol);
1725 }
1726 else
1727 {
1728 if (assembler->name() == "NavierStokes")
1729 solve_navier_stokes(sol, pressure);
1730 else if (is_homogenization())
1731 solve_homogenization(/* time steps */ 0, /* t0 */ 0, /* dt */ 0, sol);
1732 else if (is_problem_linear())
1733 {
1734 init_linear_solve(sol);
1735 solve_linear(sol, pressure);
1737 cache_transient_adjoint_quantities(0, sol, Eigen::MatrixXd::Zero(mesh->dimension(), mesh->dimension()));
1738 }
1739 else if (!assembler->is_linear() && problem->is_scalar())
1740 throw std::runtime_error("Nonlinear scalar problems are not supported yet!");
1741 else
1742 {
1746 cache_transient_adjoint_quantities(0, sol, Eigen::MatrixXd::Zero(mesh->dimension(), mesh->dimension()));
1747
1748 const std::string state_path = resolve_output_path(args["output"]["data"]["state"]);
1749 if (!state_path.empty())
1750 write_matrix(state_path, "u", sol);
1751 }
1752 }
1753
1754 timer.stop();
1755 timings.solving_time = timer.getElapsedTime();
1756 logger().info(" took {}s", timings.solving_time);
1757 }
1758
1759} // namespace polyfem
int V
ElementAssemblyValues vals
Definition Assembler.cpp:22
int x
DECLARE_DIFFSCALAR_BASE()
io::OutRuntimeData timings
runtime statistics
Definition State.hpp:583
assembler::MacroStrainValue macro_strain_constraint
Definition State.hpp:705
std::shared_ptr< utils::PeriodicBoundary > periodic_bc
periodic BC and periodic mesh utils
Definition State.hpp:389
int n_bases
number of bases
Definition State.hpp:178
void cache_transient_adjoint_quantities(const int current_step, const Eigen::MatrixXd &sol, const Eigen::MatrixXd &disp_grad)
int n_pressure_bases
number of pressure bases
Definition State.hpp:180
std::string formulation() const
return the formulation (checks if the problem is scalar or not and deals with multiphysics)
Definition State.cpp:328
assembler::AssemblyValsCache ass_vals_cache
used to store assembly values for small problems
Definition State.hpp:196
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
double starting_max_edge_length
Definition State.hpp:587
std::vector< mesh::LocalBoundary > local_pressure_boundary
mapping from elements to nodes for pressure boundary conditions
Definition State.hpp:437
void sol_to_pressure(Eigen::MatrixXd &sol, Eigen::MatrixXd &pressure)
splits the solution in solution and pressure for mixed problems
Definition State.cpp:386
std::string root_path() const
Get the root path for the state (e.g., args["root_path"] or ".")
void assemble_mass_mat()
assemble mass, step 4 of solve build mass matrix based on defined basis modifies mass (and maybe more...
Definition State.cpp:1475
Eigen::VectorXi in_node_to_node
Inpute nodes (including high-order) to polyfem nodes, only for isoparametric.
Definition State.hpp:450
void build_polygonal_basis()
builds bases for polygons, called inside build_basis
Definition State.cpp:1056
mesh::Obstacle obstacle
Obstacles used in collisions.
Definition State.hpp:468
std::shared_ptr< assembler::Assembler > assembler
assemblers
Definition State.hpp:155
ipc::CollisionMesh periodic_collision_mesh
IPC collision mesh under periodic BC.
Definition State.hpp:518
void build_periodic_collision_mesh()
Definition State.cpp:1219
io::OutGeometryData out_geom
visualization stuff
Definition State.hpp:581
bool use_avg_pressure
use average pressure for stokes problem to fix the additional dofs, true by default if false,...
Definition State.hpp:211
std::string resolve_output_path(const std::string &path) const
Resolve output path relative to output_dir if the path is not absolute.
std::vector< int > neumann_nodes
per node neumann
Definition State.hpp:446
ipc::CollisionMesh collision_mesh
IPC collision mesh.
Definition State.hpp:515
std::vector< basis::ElementBases > geom_bases_
Geometric mapping bases, if the elements are isoparametric, this list is empty.
Definition State.hpp:175
solver::CacheLevel optimization_enabled
Definition State.hpp:647
Eigen::VectorXi in_primitive_to_primitive
maps in vertices/edges/faces/cells to polyfem vertices/edges/faces/cells
Definition State.hpp:452
std::map< int, basis::InterfaceData > poly_edge_to_data
nodes on the boundary of polygonal elements, used for harmonic bases
Definition State.hpp:441
std::vector< int > pressure_boundary_nodes
list of neumann boundary nodes
Definition State.hpp:429
std::vector< basis::ElementBases > pressure_bases
FE pressure bases for mixed elements, the size is #elements.
Definition State.hpp:173
bool is_homogenization() const
Definition State.hpp:711
void solve_transient_tensor_nonlinear(const int time_steps, const double t0, const double dt, Eigen::MatrixXd &sol)
solves transient tensor nonlinear problem
double starting_min_edge_length
Definition State.hpp:586
std::shared_ptr< assembler::Mass > mass_matrix_assembler
Definition State.hpp:157
void build_node_mapping()
build the mapping from input nodes to polyfem nodes
Definition State.cpp:245
std::vector< int > primitive_to_node() const
Definition State.cpp:228
bool has_dhat
stores if input json contains dhat
Definition State.hpp:566
std::shared_ptr< polyfem::mesh::MeshNodes > pressure_mesh_nodes
Definition State.hpp:193
std::unique_ptr< mesh::Mesh > mesh
current mesh, it can be a Mesh2D or Mesh3D
Definition State.hpp:466
std::shared_ptr< polyfem::mesh::MeshNodes > mesh_nodes
Mapping from input nodes to FE nodes.
Definition State.hpp:193
StiffnessMatrix mass
Mass matrix, it is computed only for time dependent problems.
Definition State.hpp:202
void solve_homogenization(const int time_steps, const double t0, const double dt, Eigen::MatrixXd &sol)
std::vector< int > dirichlet_nodes
per node dirichlet
Definition State.hpp:443
bool has_periodic_bc() const
Definition State.hpp:390
void solve_problem(Eigen::MatrixXd &sol, Eigen::MatrixXd &pressure)
solves the problems
Definition State.cpp:1671
void build_basis()
builds the bases step 2 of solve modifies bases, pressure_bases, geom_bases_, boundary_nodes,...
Definition State.cpp:518
void solve_navier_stokes(Eigen::MatrixXd &sol, Eigen::MatrixXd &pressure)
solves a navier stokes
std::shared_ptr< assembler::Problem > problem
current problem, it contains rhs and bc
Definition State.hpp:168
std::vector< RowVectorNd > dirichlet_nodes_position
Definition State.hpp:444
std::map< int, std::pair< Eigen::MatrixXd, Eigen::MatrixXi > > polys_3d
polyhedra, used since poly have no geom mapping
Definition State.hpp:187
std::vector< int > node_to_primitive() const
Definition State.cpp:235
json args
main input arguments containing all defaults
Definition State.hpp:101
io::OutStatsData stats
Other statistics.
Definition State.hpp:585
std::vector< RowVectorNd > neumann_nodes_position
Definition State.hpp:447
void assemble_rhs()
compute rhs, step 3 of solve build rhs vector based on defined basis and given rhs of the problem mod...
Definition State.cpp:1599
double min_boundary_edge_length
Definition State.hpp:588
Eigen::VectorXi periodic_collision_mesh_to_basis
index mapping from periodic 2x2 collision mesh to FE periodic mesh
Definition State.hpp:520
std::vector< basis::ElementBases > bases
FE bases, the size is #elements.
Definition State.hpp:171
void solve_transient_navier_stokes_split(const int time_steps, const double dt, Eigen::MatrixXd &sol, Eigen::MatrixXd &pressure)
solves transient navier stokes with operator splitting
int n_geom_bases
number of geometric bases
Definition State.hpp:182
assembler::AssemblyValsCache pressure_ass_vals_cache
used to store assembly values for pressure for small problems
Definition State.hpp:199
std::vector< mesh::LocalBoundary > local_boundary
mapping from elements to nodes for dirichlet boundary conditions
Definition State.hpp:433
double avg_mass
average system mass, used for contact with IPC
Definition State.hpp:204
bool iso_parametric() const
check if using iso parametric bases
Definition State.cpp:477
std::shared_ptr< assembler::RhsAssembler > build_rhs_assembler() const
build a RhsAssembler for the problem
Definition State.hpp:248
std::vector< mesh::LocalBoundary > total_local_boundary
mapping from elements to nodes for all mesh
Definition State.hpp:431
void solve_transient_navier_stokes(const int time_steps, const double t0, const double dt, Eigen::MatrixXd &sol, Eigen::MatrixXd &pressure)
solves transient navier stokes with FEM
void init_solve(Eigen::MatrixXd &sol, Eigen::MatrixXd &pressure)
initialize solver
void init_linear_solve(Eigen::MatrixXd &sol, const double t=1.0)
initialize the linear solve
assembler::AssemblyValsCache mass_ass_vals_cache
Definition State.hpp:197
void solve_tensor_nonlinear(Eigen::MatrixXd &sol, const int t=0, const bool init_lagging=true)
solves nonlinear problems
std::string resolve_input_path(const std::string &path, const bool only_if_exists=false) const
Resolve input path relative to root_path() if the path is not absolute.
std::vector< int > boundary_nodes
list of boundary nodes
Definition State.hpp:427
solver::SolveData solve_data
timedependent stuff cached
Definition State.hpp:324
std::shared_ptr< polyfem::mesh::MeshNodes > geom_mesh_nodes
Definition State.hpp:193
void solve_linear(Eigen::MatrixXd &sol, Eigen::MatrixXd &pressure)
solves a linear problem
void init_nonlinear_tensor_solve(Eigen::MatrixXd &sol, const double t=1.0, const bool init_time_integrator=true)
initialize the nonlinear solver
bool is_contact_enabled() const
does the simulation has contact
Definition State.hpp:551
void build_collision_mesh()
extracts the boundary mesh for collision, called in build_basis
Definition State.cpp:1352
Eigen::VectorXi disc_orders
vector of discretization orders, used when not all elements have the same degree, one per element
Definition State.hpp:190
std::vector< mesh::LocalBoundary > local_neumann_boundary
mapping from elements to nodes for neumann boundary conditions
Definition State.hpp:435
std::shared_ptr< assembler::PressureAssembler > build_pressure_assembler() const
Definition State.hpp:256
void solve_transient_linear(const int time_steps, const double t0, const double dt, Eigen::MatrixXd &sol, Eigen::MatrixXd &pressure)
solves transient linear problem
bool is_problem_linear() const
Returns whether the system is linear. Collisions and pressure add nonlinearity to the problem.
Definition State.hpp:410
std::shared_ptr< assembler::MixedAssembler > mixed_assembler
Definition State.hpp:159
std::map< int, Eigen::MatrixXd > polys
polygons, used since poly have no geom mapping
Definition State.hpp:185
Eigen::MatrixXd rhs
System right-hand side.
Definition State.hpp:207
std::unordered_map< int, std::vector< mesh::LocalBoundary > > local_pressure_cavity
mapping from elements to nodes for pressure boundary conditions
Definition State.hpp:439
StiffnessMatrix basis_nodes_to_gbasis_nodes
Definition State.hpp:699
std::string velocity() const
Definition Units.hpp:27
static double convert(const json &val, const std::string &unit_type)
Definition Units.cpp:31
const std::string & length() const
Definition Units.hpp:19
Caches basis evaluation and geometric mapping at every element.
void init(const bool is_volume, const std::vector< basis::ElementBases > &bases, const std::vector< basis::ElementBases > &gbases, const bool is_mass=false)
computes the basis evaluation and geometric mapping for each of the given ElementBases in bases initi...
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,...
assemble matrix based on the local assembler local assembler is eg Laplace, LinearElasticity etc
void init(const int dim, const json &param)
static int build_bases(const mesh::Mesh2D &mesh, const std::string &assembler, const int quadrature_order, const int mass_quadrature_order, const int discr_order, const bool serendipity, const bool has_polys, const bool is_geom_bases, std::vector< ElementBases > &bases, std::vector< mesh::LocalBoundary > &local_boundary, std::map< int, InterfaceData > &poly_edge_to_data, std::shared_ptr< mesh::MeshNodes > &mesh_nodes)
Builds FE basis functions over the entire mesh (P1, P2 over triangles, Q1, Q2 over quads).
static int build_bases(const mesh::Mesh3D &mesh, const std::string &assembler, const int quadrature_order, const int mass_quadrature_order, const int discr_order, const bool serendipity, const bool has_polys, const bool is_geom_bases, std::vector< ElementBases > &bases, std::vector< mesh::LocalBoundary > &local_boundary, std::map< int, InterfaceData > &poly_face_to_data, std::shared_ptr< mesh::MeshNodes > &mesh_nodes)
Builds FE basis functions over the entire mesh (P1, P2 over tets, Q1, Q2 over hes).
static int build_bases(const std::string &assembler_name, const int dim, const mesh::Mesh2D &mesh, const int n_bases, const int quadrature_order, const int mass_quadrature_order, std::vector< ElementBases > &bases, std::vector< mesh::LocalBoundary > &local_boundary, std::map< int, Eigen::MatrixXd > &mapped_boundary)
static int build_bases(const assembler::LinearAssembler &assembler, const int n_samples_per_edge, const mesh::Mesh2D &mesh, const int n_bases, const int quadrature_order, const int mass_quadrature_order, const int integral_constraints, std::vector< ElementBases > &bases, const std::vector< ElementBases > &gbases, const std::map< int, InterfaceData > &poly_edge_to_data, std::map< int, Eigen::MatrixXd > &mapped_boundary)
Build bases over the remaining polygons of a mesh.
static int build_bases(const assembler::LinearAssembler &assembler, const int n_samples_per_edge, const mesh::Mesh3D &mesh, const int n_bases, const int quadrature_order, const int mass_quadrature_order, const int integral_constraints, std::vector< ElementBases > &bases, const std::vector< ElementBases > &gbases, const std::map< int, InterfaceData > &poly_face_to_data, std::map< int, std::pair< Eigen::MatrixXd, Eigen::MatrixXi > > &mapped_boundary)
Build bases over the remaining polygons of a mesh.
static int build_bases(const mesh::Mesh2D &mesh, const std::string &assembler, const int quadrature_order, const int mass_quadrature_order, std::vector< ElementBases > &bases, std::vector< mesh::LocalBoundary > &local_boundary, std::map< int, InterfaceData > &poly_edge_to_data)
static int build_bases(const mesh::Mesh3D &mesh, const std::string &assembler, const int quadrature_order, const int mass_quadrature_order, std::vector< ElementBases > &bases, std::vector< mesh::LocalBoundary > &local_boundary, std::map< int, InterfaceData > &poly_face_to_data)
static int build_bases(const std::string &assembler_name, const int dim, const mesh::Mesh2D &mesh, const int n_bases, const int quadrature_order, const int mass_quadrature_order, std::vector< ElementBases > &bases, std::vector< mesh::LocalBoundary > &local_boundary, std::map< int, Eigen::MatrixXd > &mapped_boundary)
void build_grid(const polyfem::mesh::Mesh &mesh, const double spacing)
builds the grid to export the solution
Definition OutData.cpp:2320
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
double assembling_stiffness_mat_time
time to assembly
Definition OutData.hpp:373
double assigning_rhs_time
time to computing the rhs
Definition OutData.hpp:377
double assembling_mass_mat_time
time to assembly mass
Definition OutData.hpp:375
double building_basis_time
time to construct the basis
Definition OutData.hpp:367
double solving_time
time to solve
Definition OutData.hpp:379
double computing_poly_basis_time
time to build the polygonal/polyhedral bases
Definition OutData.hpp:371
int n_flipped
number of flipped elements, compute only when using count_flipped_els (false by default)
Definition OutData.hpp:420
Eigen::Vector4d spectrum
spectrum of the stiffness matrix, enable only if POLYSOLVE_WITH_SPECTRA is ON (off by default)
Definition OutData.hpp:394
void count_flipped_elements(const polyfem::mesh::Mesh &mesh, const std::vector< polyfem::basis::ElementBases > &gbases)
counts the number of flipped elements
Definition OutData.cpp:2505
void compute_mesh_size(const polyfem::mesh::Mesh &mesh_in, const std::vector< polyfem::basis::ElementBases > &bases_in, const int n_samples, const bool use_curved_mesh_size)
computes the mesh size, it samples every edges n_samples times uses curved_mesh_size (false by defaul...
Definition OutData.cpp:2418
long long nn_zero
non zeros and sytem matrix size num dof is the total dof in the system
Definition OutData.hpp:412
double mesh_size
max edge lenght
Definition OutData.hpp:401
void reset()
clears all stats
Definition OutData.cpp:2496
double min_edge_length
min edge lenght
Definition OutData.hpp:403
bool is_volume() const override
checks if mesh is volume
Definition Mesh3D.hpp:28
Abstract mesh class to capture 2d/3d conforming and non-conforming meshes.
Definition Mesh.hpp:39
int n_elements() const
utitlity to return the number of elements, cells or faces in 3d and 2d
Definition Mesh.hpp:161
const Eigen::MatrixXi & e() const
Definition Obstacle.hpp:44
const Eigen::MatrixXi & f() const
Definition Obstacle.hpp:43
const Eigen::MatrixXd & v() const
Definition Obstacle.hpp:41
const Eigen::VectorXi & codim_v() const
Definition Obstacle.hpp:42
static void p_refine(const mesh::Mesh &mesh, const double B, const bool h1_formula, const int base_p, const int discr_order_max, io::OutStatsData &stats, Eigen::VectorXi &disc_orders)
compute a priori prefinement
Definition APriori.cpp:242
std::shared_ptr< assembler::RhsAssembler > rhs_assembler
void q_nodes_2d(const int q, Eigen::MatrixXd &val)
void p_nodes_2d(const int p, Eigen::MatrixXd &val)
void p_nodes_3d(const int p, Eigen::MatrixXd &val)
void q_nodes_3d(const int q, Eigen::MatrixXd &val)
bool read_matrix(const std::string &path, Eigen::Matrix< T, Eigen::Dynamic, Eigen::Dynamic > &mat)
Reads a matrix from a file. Determines the file format based on the path's extension.
Definition MatrixIO.cpp:18
bool write_matrix(const std::string &path, const Mat &mat)
Writes a matrix to a file. Determines the file format based on the path's extension.
Definition MatrixIO.cpp:42
void load_collision_proxy(const std::string &mesh_filename, const std::string &weights_filename, const Eigen::VectorXi &in_node_to_node, const json &transformation, Eigen::MatrixXd &vertices, Eigen::VectorXi &codim_vertices, Eigen::MatrixXi &edges, Eigen::MatrixXi &faces, std::vector< Eigen::Triplet< double > > &displacement_map_entries)
Load a collision proxy mesh and displacement map from files.
void build_collision_proxy(const std::vector< basis::ElementBases > &bases, const std::vector< basis::ElementBases > &geom_bases, const std::vector< LocalBoundary > &total_local_boundary, const int n_bases, const int dim, const double max_edge_length, Eigen::MatrixXd &proxy_vertices, Eigen::MatrixXi &proxy_faces, std::vector< Eigen::Triplet< double > > &displacement_map_entries, const CollisionProxyTessellation tessellation)
Eigen::SparseMatrix< double > lump_matrix(const Eigen::SparseMatrix< double > &M)
Lump each row of a matrix into the diagonal.
std::string resolve_path(const std::string &path, const std::string &input_file_path, const bool only_if_exists=false)
std::vector< T > json_as_array(const json &j)
Return the value of a json object as an array.
Definition JSONUtils.hpp:38
void append_rows(DstMat &dst, const SrcMat &src)
spdlog::logger & logger()
Retrieves the current logger.
Definition Logger.cpp:42
void compute_integral_constraints(const Mesh3D &mesh, const int n_bases, const std::vector< basis::ElementBases > &bases, const std::vector< basis::ElementBases > &gbases, Eigen::MatrixXd &basis_integrals)
Definition State.cpp:404
Eigen::Matrix< double, Eigen::Dynamic, 1, 0, 3, 1 > VectorNd
Definition Types.hpp:11
nlohmann::json json
Definition Common.hpp:9
Eigen::Matrix< double, 1, Eigen::Dynamic, Eigen::RowMajor, 1, 3 > RowVectorNd
Definition Types.hpp:13
void log_and_throw_error(const std::string &msg)
Definition Logger.cpp:71
Eigen::SparseMatrix< double, Eigen::ColMajor > StiffnessMatrix
Definition Types.hpp:22