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 if (!mesh->is_simplicial())
634 {
635 args["space"]["advanced"]["count_flipped_els_continuous"] = false;
636 args["output"]["paraview"]["options"]["jacobian_validity"] = false;
637 args["solver"]["advanced"]["check_inversion"] = "Discrete";
638 }
639 else if (args["solver"]["advanced"]["check_inversion"] != "Discrete")
640 {
641 args["space"]["advanced"]["use_corner_quadrature"] = true;
642 }
643
644 Eigen::MatrixXi geom_disc_orders;
645 if (!iso_parametric())
646 {
647 if (mesh->orders().size() <= 0)
648 {
649 geom_disc_orders.resizeLike(disc_orders);
650 geom_disc_orders.setConstant(1);
651 }
652 else
653 geom_disc_orders = mesh->orders();
654 }
655
656 igl::Timer timer;
657 timer.start();
658 if (args["space"]["use_p_ref"])
659 {
661 *mesh,
662 args["space"]["advanced"]["B"],
663 args["space"]["advanced"]["h1_formula"],
664 args["space"]["discr_order"],
665 args["space"]["advanced"]["discr_order_max"],
666 stats,
668
669 logger().info("min p: {} max p: {}", disc_orders.minCoeff(), disc_orders.maxCoeff());
670 }
671
672 int quadrature_order = args["space"]["advanced"]["quadrature_order"].get<int>();
673 const int mass_quadrature_order = args["space"]["advanced"]["mass_quadrature_order"].get<int>();
674 if (mixed_assembler != nullptr)
675 {
676 const int disc_order = disc_orders.maxCoeff();
677 if (disc_order - disc_orders.minCoeff() != 0)
678 {
679 logger().error("p refinement not supported in mixed formulation!");
680 return;
681 }
682 }
683
684 // shape optimization needs continuous geometric basis
685 // const bool use_continuous_gbasis = optimization_enabled == solver::CacheLevel::Derivatives;
686 const bool use_continuous_gbasis = true;
687 const bool use_corner_quadrature = args["space"]["advanced"]["use_corner_quadrature"];
688
689 if (mesh->is_volume())
690 {
691 const Mesh3D &tmp_mesh = *dynamic_cast<Mesh3D *>(mesh.get());
692 if (args["space"]["basis_type"] == "Spline")
693 {
694 // if (!iso_parametric())
695 // {
696 // logger().error("Splines must be isoparametric, ignoring...");
697 // // LagrangeBasis3d::build_bases(tmp_mesh, quadrature_order, geom_disc_orders, has_polys, geom_bases_, local_boundary, poly_edge_to_data_geom, mesh_nodes);
698 // SplineBasis3d::build_bases(tmp_mesh, quadrature_order, geom_bases_, local_boundary, poly_edge_to_data);
699 // }
700
701 n_bases = basis::SplineBasis3d::build_bases(tmp_mesh, assembler->name(), quadrature_order, mass_quadrature_order, bases, local_boundary, poly_edge_to_data);
702
703 // if (iso_parametric() && args["fit_nodes"])
704 // SplineBasis3d::fit_nodes(tmp_mesh, n_bases, bases);
705 }
706 else
707 {
708 if (!iso_parametric())
709 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, use_corner_quadrature, geom_bases_, local_boundary, poly_edge_to_data_geom, geom_mesh_nodes);
710
711 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, use_corner_quadrature, bases, local_boundary, poly_edge_to_data, mesh_nodes);
712 }
713
714 // if(problem->is_mixed())
715 if (mixed_assembler != nullptr)
716 {
717 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, use_corner_quadrature, pressure_bases, local_boundary, poly_edge_to_data_geom, pressure_mesh_nodes);
718 }
719 }
720 else
721 {
722 const Mesh2D &tmp_mesh = *dynamic_cast<Mesh2D *>(mesh.get());
723 if (args["space"]["basis_type"] == "Spline")
724 {
725 // TODO:
726 // if (!iso_parametric())
727 // {
728 // logger().error("Splines must be isoparametric, ignoring...");
729 // // LagrangeBasis2d::build_bases(tmp_mesh, quadrature_order, disc_orders, has_polys, geom_bases_, local_boundary, poly_edge_to_data_geom, mesh_nodes);
730 // n_bases = SplineBasis2d::build_bases(tmp_mesh, quadrature_order, geom_bases_, local_boundary, poly_edge_to_data);
731 // }
732
733 n_bases = basis::SplineBasis2d::build_bases(tmp_mesh, assembler->name(), quadrature_order, mass_quadrature_order, bases, local_boundary, poly_edge_to_data);
734
735 // if (iso_parametric() && args["fit_nodes"])
736 // SplineBasis2d::fit_nodes(tmp_mesh, n_bases, bases);
737 }
738 else
739 {
740 if (!iso_parametric())
741 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, use_corner_quadrature, geom_bases_, local_boundary, poly_edge_to_data_geom, geom_mesh_nodes);
742
743 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, use_corner_quadrature, bases, local_boundary, poly_edge_to_data, mesh_nodes);
744 }
745
746 // if(problem->is_mixed())
747 if (mixed_assembler != nullptr)
748 {
749 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, use_corner_quadrature, pressure_bases, local_boundary, poly_edge_to_data_geom, pressure_mesh_nodes);
750 }
751 }
752
753 if (mixed_assembler != nullptr)
754 {
755 assert(bases.size() == pressure_bases.size());
756 for (int i = 0; i < pressure_bases.size(); ++i)
757 {
759 bases[i].compute_quadrature(b_quad);
760 pressure_bases[i].set_quadrature([b_quad](quadrature::Quadrature &quad) { quad = b_quad; });
761 }
762 }
763
764 timer.stop();
765
767
768 if (n_geom_bases == 0)
770
771 auto &gbases = geom_bases();
772
774 {
775 std::map<std::array<int, 2>, double> pairs;
776 for (int e = 0; e < gbases.size(); e++)
777 {
778 const auto &gbs = gbases[e].bases;
779 const auto &bs = bases[e].bases;
780
781 Eigen::MatrixXd local_pts;
782 const int order = bs.front().order();
783 if (mesh->is_volume())
784 {
785 if (mesh->is_simplex(e))
786 autogen::p_nodes_3d(order, local_pts);
787 else
788 autogen::q_nodes_3d(order, local_pts);
789 }
790 else
791 {
792 if (mesh->is_simplex(e))
793 autogen::p_nodes_2d(order, local_pts);
794 else
795 autogen::q_nodes_2d(order, local_pts);
796 }
797
799 vals.compute(e, mesh->is_volume(), local_pts, gbases[e], gbases[e]);
800
801 for (int i = 0; i < bs.size(); i++)
802 {
803 for (int j = 0; j < gbs.size(); j++)
804 {
805 if (std::abs(vals.basis_values[j].val(i)) > 1e-7)
806 {
807 std::array<int, 2> index = {{gbs[j].global()[0].index, bs[i].global()[0].index}};
808 pairs.insert({index, vals.basis_values[j].val(i)});
809 }
810 }
811 }
812 }
813
814 const int dim = mesh->dimension();
815 std::vector<Eigen::Triplet<double>> coeffs;
816 coeffs.clear();
817 for (const auto &iter : pairs)
818 for (int d = 0; d < dim; d++)
819 coeffs.emplace_back(iter.first[0] * dim + d, iter.first[1] * dim + d, iter.second);
820
821 basis_nodes_to_gbasis_nodes.resize(n_geom_bases * mesh->dimension(), n_bases * mesh->dimension());
822 basis_nodes_to_gbasis_nodes.setFromTriplets(coeffs.begin(), coeffs.end());
823 }
824
825 for (const auto &lb : local_boundary)
826 total_local_boundary.emplace_back(lb);
827
828 const int dim = mesh->dimension();
829 const int problem_dim = problem->is_scalar() ? 1 : dim;
830
831 // handle periodic bc
832 if (has_periodic_bc())
833 {
834 // collect periodic directions
835 json directions = args["boundary_conditions"]["periodic_boundary"]["correspondence"];
836 Eigen::MatrixXd tile_offset = Eigen::MatrixXd::Identity(dim, dim);
837
838 if (directions.size() > 0)
839 {
840 Eigen::VectorXd tmp;
841 for (int d = 0; d < dim; d++)
842 {
843 tmp = directions[d];
844 if (tmp.size() != dim)
845 log_and_throw_error("Invalid size of periodic directions!");
846 tile_offset.col(d) = tmp;
847 }
848 }
849
850 periodic_bc = std::make_shared<PeriodicBoundary>(problem->is_scalar(), n_bases, bases, mesh_nodes, tile_offset, args["boundary_conditions"]["periodic_boundary"]["tolerance"].get<double>());
851
852 macro_strain_constraint.init(dim, args["boundary_conditions"]["periodic_boundary"]);
853 }
854
855 if (args["space"]["advanced"]["count_flipped_els"])
857
858 const int prev_bases = n_bases;
860
861 {
862 igl::Timer timer2;
863 logger().debug("Building node mapping...");
864 timer2.start();
866 problem->update_nodes(in_node_to_node);
867 mesh->update_nodes(in_node_to_node);
868 timer2.stop();
869 logger().debug("Done (took {}s)", timer2.getElapsedTime());
870 }
871
872 logger().info("Building collision mesh...");
874 if (periodic_bc && args["contact"]["periodic"])
876 logger().info("Done!");
877
878 const int prev_b_size = local_boundary.size();
879 problem->setup_bc(*mesh, n_bases - obstacle.n_vertices(),
888
889 // setp nodal values
890 {
892 for (int n = 0; n < dirichlet_nodes.size(); ++n)
893 {
894 const int n_id = dirichlet_nodes[n];
895 bool found = false;
896 for (const auto &bs : bases)
897 {
898 for (const auto &b : bs.bases)
899 {
900 for (const auto &lg : b.global())
901 {
902 if (lg.index == n_id)
903 {
904 dirichlet_nodes_position[n] = lg.node;
905 found = true;
906 break;
907 }
908 }
909
910 if (found)
911 break;
912 }
913
914 if (found)
915 break;
916 }
917
918 assert(found);
919 }
920
922 for (int n = 0; n < neumann_nodes.size(); ++n)
923 {
924 const int n_id = neumann_nodes[n];
925 bool found = false;
926 for (const auto &bs : bases)
927 {
928 for (const auto &b : bs.bases)
929 {
930 for (const auto &lg : b.global())
931 {
932 if (lg.index == n_id)
933 {
934 neumann_nodes_position[n] = lg.node;
935 found = true;
936 break;
937 }
938 }
939
940 if (found)
941 break;
942 }
943
944 if (found)
945 break;
946 }
947
948 assert(found);
949 }
950 }
951
952 const bool has_neumann = local_neumann_boundary.size() > 0 || local_boundary.size() < prev_b_size;
953 use_avg_pressure = !has_neumann;
954
955 for (int i = prev_bases; i < n_bases; ++i)
956 {
957 for (int d = 0; d < problem_dim; ++d)
958 boundary_nodes.push_back(i * problem_dim + d);
959 }
960
961 std::sort(boundary_nodes.begin(), boundary_nodes.end());
962 auto it = std::unique(boundary_nodes.begin(), boundary_nodes.end());
963 boundary_nodes.resize(std::distance(boundary_nodes.begin(), it));
964
965 // for elastic pure periodic problem, find an internal node and force zero dirichlet
966 if ((!problem->is_time_dependent() || args["time"]["quasistatic"]) && boundary_nodes.size() == 0 && has_periodic_bc())
967 {
968 // find an internal node to force zero dirichlet
969 std::vector<bool> isboundary(n_bases, false);
970 for (const auto &lb : total_local_boundary)
971 {
972 const int e = lb.element_id();
973 for (int i = 0; i < lb.size(); ++i)
974 {
975 const auto nodes = bases[e].local_nodes_for_primitive(lb.global_primitive_id(i), *mesh);
976
977 for (int n : nodes)
978 isboundary[bases[e].bases[n].global()[0].index] = true;
979 }
980 }
981 int i = 0;
982 for (; i < n_bases; i++)
983 if (!isboundary[i]) // (!periodic_bc->is_periodic_dof(i))
984 break;
985 if (i >= n_bases)
986 log_and_throw_error("Failed to find a non-periodic node!");
987 const int actual_dim = problem->is_scalar() ? 1 : mesh->dimension();
988 for (int d = 0; d < actual_dim; d++)
989 {
990 boundary_nodes.push_back(i * actual_dim + d);
991 }
992 logger().info("Fix solution at node {} to remove singularity due to periodic BC", i);
993 }
994
995 const auto &curret_bases = geom_bases();
996 const int n_samples = 10;
997 stats.compute_mesh_size(*mesh, curret_bases, n_samples, args["output"]["advanced"]["curved_mesh_size"]);
999 {
1001 }
1003 {
1005 }
1006
1007 if (is_contact_enabled())
1008 {
1009 min_boundary_edge_length = std::numeric_limits<double>::max();
1010 for (const auto &edge : collision_mesh.edges().rowwise())
1011 {
1012 const VectorNd v0 = collision_mesh.rest_positions().row(edge(0));
1013 const VectorNd v1 = collision_mesh.rest_positions().row(edge(1));
1014 min_boundary_edge_length = std::min(min_boundary_edge_length, (v1 - v0).norm());
1015 }
1016
1017 double dhat = Units::convert(args["contact"]["dhat"], units.length());
1018 args["contact"]["epsv"] = Units::convert(args["contact"]["epsv"], units.velocity());
1019 args["contact"]["dhat"] = dhat;
1020
1021 if (!has_dhat && dhat > min_boundary_edge_length)
1022 {
1023 args["contact"]["dhat"] = double(args["contact"]["dhat_percentage"]) * min_boundary_edge_length;
1024 logger().info("dhat set to {}", double(args["contact"]["dhat"]));
1025 }
1026 else
1027 {
1028 if (dhat > min_boundary_edge_length)
1029 logger().warn("dhat larger than min boundary edge, {} > {}", dhat, min_boundary_edge_length);
1030 }
1031 }
1032
1033 logger().info("n_bases {}", n_bases);
1034
1035 timings.building_basis_time = timer.getElapsedTime();
1036 logger().info(" took {}s", timings.building_basis_time);
1037
1038 logger().info("flipped elements {}", stats.n_flipped);
1039 logger().info("h: {}", stats.mesh_size);
1040 logger().info("n bases: {}", n_bases);
1041 logger().info("n pressure bases: {}", n_pressure_bases);
1042
1045 if (n_bases <= args["solver"]["advanced"]["cache_size"])
1046 {
1047 timer.start();
1048 logger().info("Building cache...");
1049 ass_vals_cache.init(mesh->is_volume(), bases, curret_bases);
1050 mass_ass_vals_cache.init(mesh->is_volume(), bases, curret_bases, true);
1051 if (mixed_assembler != nullptr)
1052 pressure_ass_vals_cache.init(mesh->is_volume(), pressure_bases, curret_bases);
1053
1054 logger().info(" took {}s", timer.getElapsedTime());
1055 }
1056
1057 out_geom.build_grid(*mesh, args["output"]["advanced"]["sol_on_grid"]);
1058
1059 if ((!problem->is_time_dependent() || args["time"]["quasistatic"]) && boundary_nodes.empty())
1060 {
1061 if (has_periodic_bc())
1062 logger().warn("(Quasi-)Static problem without Dirichlet nodes, will fix solution at one node to find a unique solution!");
1063 else
1064 log_and_throw_error("Static problem need to have some Dirichlet nodes!");
1065 }
1066 }
1067
1069 {
1070 if (!mesh)
1071 {
1072 logger().error("Load the mesh first!");
1073 return;
1074 }
1075
1076 rhs.resize(0, 0);
1077
1078 if (poly_edge_to_data.empty() && polys.empty())
1079 {
1081 return;
1082 }
1083
1084 igl::Timer timer;
1085 timer.start();
1086 logger().info("Computing polygonal basis...");
1087
1088 // std::sort(boundary_nodes.begin(), boundary_nodes.end());
1089
1090 // mixed not supports polygonal bases
1091 assert(n_pressure_bases == 0 || poly_edge_to_data.size() == 0);
1092
1093 int new_bases = 0;
1094
1095 if (iso_parametric())
1096 {
1097 if (mesh->is_volume())
1098 {
1099 if (args["space"]["poly_basis_type"] == "MeanValue" || args["space"]["poly_basis_type"] == "Wachspress")
1100 logger().error("Barycentric bases not supported in 3D");
1101 assert(assembler->is_linear());
1103 *dynamic_cast<LinearAssembler *>(assembler.get()),
1104 args["space"]["advanced"]["n_harmonic_samples"],
1105 *dynamic_cast<Mesh3D *>(mesh.get()),
1106 n_bases,
1107 args["space"]["advanced"]["quadrature_order"],
1108 args["space"]["advanced"]["mass_quadrature_order"],
1109 args["space"]["advanced"]["integral_constraints"],
1110 bases,
1111 bases,
1113 polys_3d);
1114 }
1115 else
1116 {
1117 if (args["space"]["poly_basis_type"] == "MeanValue")
1118 {
1120 assembler->name(),
1121 assembler->is_tensor() ? 2 : 1,
1122 *dynamic_cast<Mesh2D *>(mesh.get()),
1123 n_bases,
1124 args["space"]["advanced"]["quadrature_order"],
1125 args["space"]["advanced"]["mass_quadrature_order"],
1127 }
1128 else if (args["space"]["poly_basis_type"] == "Wachspress")
1129 {
1131 assembler->name(),
1132 assembler->is_tensor() ? 2 : 1,
1133 *dynamic_cast<Mesh2D *>(mesh.get()),
1134 n_bases,
1135 args["space"]["advanced"]["quadrature_order"],
1136 args["space"]["advanced"]["mass_quadrature_order"],
1138 }
1139 else
1140 {
1141 assert(assembler->is_linear());
1143 *dynamic_cast<LinearAssembler *>(assembler.get()),
1144 args["space"]["advanced"]["n_harmonic_samples"],
1145 *dynamic_cast<Mesh2D *>(mesh.get()),
1146 n_bases,
1147 args["space"]["advanced"]["quadrature_order"],
1148 args["space"]["advanced"]["mass_quadrature_order"],
1149 args["space"]["advanced"]["integral_constraints"],
1150 bases,
1151 bases,
1153 polys);
1154 }
1155 }
1156 }
1157 else
1158 {
1159 if (mesh->is_volume())
1160 {
1161 if (args["space"]["poly_basis_type"] == "MeanValue" || args["space"]["poly_basis_type"] == "Wachspress")
1162 {
1163 logger().error("Barycentric bases not supported in 3D");
1164 throw std::runtime_error("not implemented");
1165 }
1166 else
1167 {
1168 assert(assembler->is_linear());
1170 *dynamic_cast<LinearAssembler *>(assembler.get()),
1171 args["space"]["advanced"]["n_harmonic_samples"],
1172 *dynamic_cast<Mesh3D *>(mesh.get()),
1173 n_bases,
1174 args["space"]["advanced"]["quadrature_order"],
1175 args["space"]["advanced"]["mass_quadrature_order"],
1176 args["space"]["advanced"]["integral_constraints"],
1177 bases,
1180 polys_3d);
1181 }
1182 }
1183 else
1184 {
1185 if (args["space"]["poly_basis_type"] == "MeanValue")
1186 {
1188 assembler->name(),
1189 assembler->is_tensor() ? 2 : 1,
1190 *dynamic_cast<Mesh2D *>(mesh.get()),
1191 n_bases, args["space"]["advanced"]["quadrature_order"],
1192 args["space"]["advanced"]["mass_quadrature_order"],
1194 }
1195 else if (args["space"]["poly_basis_type"] == "Wachspress")
1196 {
1198 assembler->name(),
1199 assembler->is_tensor() ? 2 : 1,
1200 *dynamic_cast<Mesh2D *>(mesh.get()),
1201 n_bases, args["space"]["advanced"]["quadrature_order"],
1202 args["space"]["advanced"]["mass_quadrature_order"],
1204 }
1205 else
1206 {
1207 assert(assembler->is_linear());
1209 *dynamic_cast<LinearAssembler *>(assembler.get()),
1210 args["space"]["advanced"]["n_harmonic_samples"],
1211 *dynamic_cast<Mesh2D *>(mesh.get()),
1212 n_bases,
1213 args["space"]["advanced"]["quadrature_order"],
1214 args["space"]["advanced"]["mass_quadrature_order"],
1215 args["space"]["advanced"]["integral_constraints"],
1216 bases,
1219 polys);
1220 }
1221 }
1222 }
1223
1224 timer.stop();
1225 timings.computing_poly_basis_time = timer.getElapsedTime();
1226 logger().info(" took {}s", timings.computing_poly_basis_time);
1227
1228 n_bases += new_bases;
1229 }
1230
1232 {
1233 assert(!mesh->is_volume());
1234 const int dim = mesh->dimension();
1235 const int n_tiles = 2;
1236
1237 if (mesh->dimension() != 2)
1238 log_and_throw_error("Periodic collision mesh is only implemented in 2D!");
1239
1240 Eigen::MatrixXd V(n_bases, dim);
1241 for (const auto &bs : bases)
1242 for (const auto &b : bs.bases)
1243 for (const auto &g : b.global())
1244 V.row(g.index) = g.node;
1245
1246 Eigen::MatrixXi E = collision_mesh.edges();
1247 for (int i = 0; i < E.size(); i++)
1248 E(i) = collision_mesh.to_full_vertex_id(E(i));
1249
1250 Eigen::MatrixXd bbox(V.cols(), 2);
1251 bbox.col(0) = V.colwise().minCoeff();
1252 bbox.col(1) = V.colwise().maxCoeff();
1253
1254 // remove boundary edges on periodic BC, buggy
1255 {
1256 std::vector<int> ind;
1257 for (int i = 0; i < E.rows(); i++)
1258 {
1259 if (!periodic_bc->is_periodic_dof(E(i, 0)) || !periodic_bc->is_periodic_dof(E(i, 1)))
1260 ind.push_back(i);
1261 }
1262
1263 E = E(ind, Eigen::all).eval();
1264 }
1265
1266 Eigen::MatrixXd Vtmp, Vnew;
1267 Eigen::MatrixXi Etmp, Enew;
1268 Vtmp.setZero(V.rows() * n_tiles * n_tiles, V.cols());
1269 Etmp.setZero(E.rows() * n_tiles * n_tiles, E.cols());
1270
1271 Eigen::MatrixXd tile_offset = periodic_bc->get_affine_matrix();
1272
1273 for (int i = 0, idx = 0; i < n_tiles; i++)
1274 {
1275 for (int j = 0; j < n_tiles; j++)
1276 {
1277 Eigen::Vector2d block_id;
1278 block_id << i, j;
1279
1280 Vtmp.middleRows(idx * V.rows(), V.rows()) = V;
1281 // Vtmp.block(idx * V.rows(), 0, V.rows(), 1).array() += tile_offset(0) * i;
1282 // Vtmp.block(idx * V.rows(), 1, V.rows(), 1).array() += tile_offset(1) * j;
1283 for (int vid = 0; vid < V.rows(); vid++)
1284 Vtmp.block(idx * V.rows() + vid, 0, 1, 2) += (tile_offset * block_id).transpose();
1285
1286 Etmp.middleRows(idx * E.rows(), E.rows()) = E.array() + idx * V.rows();
1287 idx += 1;
1288 }
1289 }
1290
1291 // clean duplicated vertices
1292 Eigen::VectorXi indices;
1293 {
1294 std::vector<int> tmp;
1295 for (int i = 0; i < V.rows(); i++)
1296 {
1297 if (periodic_bc->is_periodic_dof(i))
1298 tmp.push_back(i);
1299 }
1300
1301 indices.resize(tmp.size() * n_tiles * n_tiles);
1302 for (int i = 0; i < n_tiles * n_tiles; i++)
1303 {
1304 indices.segment(i * tmp.size(), tmp.size()) = Eigen::Map<Eigen::VectorXi, Eigen::Unaligned>(tmp.data(), tmp.size());
1305 indices.segment(i * tmp.size(), tmp.size()).array() += i * V.rows();
1306 }
1307 }
1308
1309 Eigen::VectorXi potentially_duplicate_mask(Vtmp.rows());
1310 potentially_duplicate_mask.setZero();
1311 potentially_duplicate_mask(indices).array() = 1;
1312
1313 Eigen::MatrixXd candidates = Vtmp(indices, Eigen::all);
1314
1315 Eigen::VectorXi SVI;
1316 std::vector<int> SVJ;
1317 SVI.setConstant(Vtmp.rows(), -1);
1318 int id = 0;
1319 const double eps = (bbox.col(1) - bbox.col(0)).maxCoeff() * args["boundary_conditions"]["periodic_boundary"]["tolerance"].get<double>();
1320 for (int i = 0; i < Vtmp.rows(); i++)
1321 {
1322 if (SVI[i] < 0)
1323 {
1324 SVI[i] = id;
1325 SVJ.push_back(i);
1326 if (potentially_duplicate_mask(i))
1327 {
1328 Eigen::VectorXd diffs = (candidates.rowwise() - Vtmp.row(i)).rowwise().norm();
1329 for (int j = 0; j < diffs.size(); j++)
1330 if (diffs(j) < eps)
1331 SVI[indices[j]] = id;
1332 }
1333 id++;
1334 }
1335 }
1336
1337 Vnew = Vtmp(SVJ, Eigen::all);
1338
1339 Enew.resizeLike(Etmp);
1340 for (int d = 0; d < Etmp.cols(); d++)
1341 Enew.col(d) = SVI(Etmp.col(d));
1342
1343 std::vector<bool> is_on_surface = ipc::CollisionMesh::construct_is_on_surface(Vnew.rows(), Enew);
1344
1345 Eigen::MatrixXi boundary_triangles;
1346 Eigen::SparseMatrix<double> displacement_map;
1347 periodic_collision_mesh = ipc::CollisionMesh(is_on_surface,
1348 Vnew,
1349 Enew,
1350 boundary_triangles,
1351 displacement_map);
1352
1353 periodic_collision_mesh.init_area_jacobians();
1354
1355 periodic_collision_mesh_to_basis.setConstant(Vnew.rows(), -1);
1356 for (int i = 0; i < V.rows(); i++)
1357 for (int j = 0; j < n_tiles * n_tiles; j++)
1358 periodic_collision_mesh_to_basis(SVI[j * V.rows() + i]) = i;
1359
1360 if (periodic_collision_mesh_to_basis.maxCoeff() + 1 != V.rows())
1361 log_and_throw_error("Failed to tile mesh!");
1362 }
1363
1365 {
1368 args, [this](const std::string &p) { return resolve_input_path(p); },
1370 }
1371
1373 const mesh::Mesh &mesh,
1374 const int n_bases,
1375 const std::vector<basis::ElementBases> &bases,
1376 const std::vector<basis::ElementBases> &geom_bases,
1377 const std::vector<mesh::LocalBoundary> &total_local_boundary,
1378 const mesh::Obstacle &obstacle,
1379 const json &args,
1380 const std::function<std::string(const std::string &)> &resolve_input_path,
1381 const Eigen::VectorXi &in_node_to_node,
1382 ipc::CollisionMesh &collision_mesh)
1383 {
1384 Eigen::MatrixXd collision_vertices;
1385 Eigen::VectorXi collision_codim_vids;
1386 Eigen::MatrixXi collision_edges, collision_triangles;
1387 std::vector<Eigen::Triplet<double>> displacement_map_entries;
1388
1389 if (args.contains("/contact/collision_mesh"_json_pointer)
1390 && args.at("/contact/collision_mesh/enabled"_json_pointer).get<bool>())
1391 {
1392 const json collision_mesh_args = args.at("/contact/collision_mesh"_json_pointer);
1393 if (collision_mesh_args.contains("linear_map"))
1394 {
1395 assert(displacement_map_entries.empty());
1396 assert(collision_mesh_args.contains("mesh"));
1397 const std::string root_path = utils::json_value<std::string>(args, "root_path", "");
1398 // TODO: handle transformation per geometry
1399 const json transformation = json_as_array(args["geometry"])[0]["transformation"];
1401 utils::resolve_path(collision_mesh_args["mesh"], root_path),
1402 utils::resolve_path(collision_mesh_args["linear_map"], root_path),
1403 in_node_to_node, transformation, collision_vertices, collision_codim_vids,
1404 collision_edges, collision_triangles, displacement_map_entries);
1405 }
1406 else
1407 {
1408 assert(collision_mesh_args.contains("max_edge_length"));
1409 logger().debug(
1410 "Building collision proxy with max edge length={} ...",
1411 collision_mesh_args["max_edge_length"].get<double>());
1412 igl::Timer timer;
1413 timer.start();
1416 collision_mesh_args["max_edge_length"], collision_vertices,
1417 collision_triangles, displacement_map_entries,
1418 collision_mesh_args["tessellation_type"]);
1419 if (collision_triangles.size())
1420 igl::edges(collision_triangles, collision_edges);
1421 timer.stop();
1422 logger().debug(fmt::format(
1423 std::locale("en_US.UTF-8"),
1424 "Done (took {:g}s, {:L} vertices, {:L} triangles)",
1425 timer.getElapsedTime(),
1426 collision_vertices.rows(), collision_triangles.rows()));
1427 }
1428 }
1429 else
1430 {
1433 collision_vertices, collision_edges, collision_triangles, displacement_map_entries);
1434 }
1435
1436 // n_bases already contains the obstacle vertices
1437 const int num_fe_nodes = n_bases - obstacle.n_vertices();
1438 const int num_fe_collision_vertices = collision_vertices.rows();
1439 assert(collision_edges.size() == 0 || collision_edges.maxCoeff() < num_fe_collision_vertices);
1440 assert(collision_triangles.size() == 0 || collision_triangles.maxCoeff() < num_fe_collision_vertices);
1441
1442 // Append the obstacles to the collision mesh
1443 if (obstacle.n_vertices() > 0)
1444 {
1445 append_rows(collision_vertices, obstacle.v());
1446 append_rows(collision_codim_vids, obstacle.codim_v().array() + num_fe_collision_vertices);
1447 append_rows(collision_edges, obstacle.e().array() + num_fe_collision_vertices);
1448 append_rows(collision_triangles, obstacle.f().array() + num_fe_collision_vertices);
1449
1450 if (!displacement_map_entries.empty())
1451 {
1452 displacement_map_entries.reserve(displacement_map_entries.size() + obstacle.n_vertices());
1453 for (int i = 0; i < obstacle.n_vertices(); i++)
1454 {
1455 displacement_map_entries.emplace_back(num_fe_collision_vertices + i, num_fe_nodes + i, 1.0);
1456 }
1457 }
1458 }
1459
1460 std::vector<bool> is_on_surface = ipc::CollisionMesh::construct_is_on_surface(
1461 collision_vertices.rows(), collision_edges);
1462 for (const int vid : collision_codim_vids)
1463 {
1464 is_on_surface[vid] = true;
1465 }
1466
1467 Eigen::SparseMatrix<double> displacement_map;
1468 if (!displacement_map_entries.empty())
1469 {
1470 displacement_map.resize(collision_vertices.rows(), n_bases);
1471 displacement_map.setFromTriplets(displacement_map_entries.begin(), displacement_map_entries.end());
1472 }
1473
1474 collision_mesh = ipc::CollisionMesh(
1475 is_on_surface, collision_vertices, collision_edges, collision_triangles,
1476 displacement_map);
1477
1478 collision_mesh.can_collide = [&collision_mesh, num_fe_collision_vertices](size_t vi, size_t vj) {
1479 // obstacles do not collide with other obstacles
1480 return collision_mesh.to_full_vertex_id(vi) < num_fe_collision_vertices
1481 || collision_mesh.to_full_vertex_id(vj) < num_fe_collision_vertices;
1482 };
1483
1484 collision_mesh.init_area_jacobians();
1485 }
1486
1488 {
1489 if (!mesh)
1490 {
1491 logger().error("Load the mesh first!");
1492 return;
1493 }
1494 if (n_bases <= 0)
1495 {
1496 logger().error("Build the bases first!");
1497 return;
1498 }
1499 if (assembler->name() == "OperatorSplitting")
1500 {
1502 avg_mass = 1;
1503 return;
1504 }
1505
1506 if (!problem->is_time_dependent())
1507 {
1508 avg_mass = 1;
1510 return;
1511 }
1512
1513 mass.resize(0, 0);
1514
1515 igl::Timer timer;
1516 timer.start();
1517 logger().info("Assembling mass mat...");
1518
1519 if (mixed_assembler != nullptr)
1520 {
1521 StiffnessMatrix velocity_mass;
1522 mass_matrix_assembler->assemble(mesh->is_volume(), n_bases, bases, geom_bases(), mass_ass_vals_cache, 0, velocity_mass, true);
1523
1524 std::vector<Eigen::Triplet<double>> mass_blocks;
1525 mass_blocks.reserve(velocity_mass.nonZeros());
1526
1527 for (int k = 0; k < velocity_mass.outerSize(); ++k)
1528 {
1529 for (StiffnessMatrix::InnerIterator it(velocity_mass, k); it; ++it)
1530 {
1531 mass_blocks.emplace_back(it.row(), it.col(), it.value());
1532 }
1533 }
1534
1535 mass.resize(n_bases * assembler->size(), n_bases * assembler->size());
1536 mass.setFromTriplets(mass_blocks.begin(), mass_blocks.end());
1537 mass.makeCompressed();
1538 }
1539 else
1540 {
1541 mass_matrix_assembler->assemble(mesh->is_volume(), n_bases, bases, geom_bases(), mass_ass_vals_cache, 0, mass, true);
1542 }
1543
1544 assert(mass.size() > 0);
1545
1546 avg_mass = 0;
1547 for (int k = 0; k < mass.outerSize(); ++k)
1548 {
1549
1550 for (StiffnessMatrix::InnerIterator it(mass, k); it; ++it)
1551 {
1552 assert(it.col() == k);
1553 avg_mass += it.value();
1554 }
1555 }
1556
1557 avg_mass /= mass.rows();
1558 logger().info("average mass {}", avg_mass);
1559
1560 if (args["solver"]["advanced"]["lump_mass_matrix"])
1561 {
1563 }
1564
1565 timer.stop();
1566 timings.assembling_mass_mat_time = timer.getElapsedTime();
1567 logger().info(" took {}s", timings.assembling_mass_mat_time);
1568
1569 stats.nn_zero = mass.nonZeros();
1570 stats.num_dofs = mass.rows();
1571 stats.mat_size = (long long)mass.rows() * (long long)mass.cols();
1572 logger().info("sparsity: {}/{}", stats.nn_zero, stats.mat_size);
1573 }
1574
1575 std::shared_ptr<RhsAssembler> State::build_rhs_assembler(
1576 const int n_bases_,
1577 const std::vector<basis::ElementBases> &bases_,
1578 const assembler::AssemblyValsCache &ass_vals_cache_) const
1579 {
1580 json rhs_solver_params = args["solver"]["linear"];
1581 if (!rhs_solver_params.contains("Pardiso"))
1582 rhs_solver_params["Pardiso"] = {};
1583 rhs_solver_params["Pardiso"]["mtype"] = -2; // matrix type for Pardiso (2 = SPD)
1584
1585 const int size = problem->is_scalar() ? 1 : mesh->dimension();
1586
1587 return std::make_shared<RhsAssembler>(
1591 n_bases_, size, bases_, geom_bases(), ass_vals_cache_, *problem,
1592 args["space"]["advanced"]["bc_method"],
1593 rhs_solver_params);
1594 }
1595
1596 std::shared_ptr<PressureAssembler> State::build_pressure_assembler(
1597 const int n_bases_,
1598 const std::vector<basis::ElementBases> &bases_) const
1599 {
1600 const int size = problem->is_scalar() ? 1 : mesh->dimension();
1601
1602 return std::make_shared<PressureAssembler>(
1608 n_bases_, size, bases_, geom_bases(), *problem);
1609 }
1610
1612 {
1613 if (!mesh)
1614 {
1615 logger().error("Load the mesh first!");
1616 return;
1617 }
1618 if (n_bases <= 0)
1619 {
1620 logger().error("Build the bases first!");
1621 return;
1622 }
1623
1624 igl::Timer timer;
1625
1626 json p_params = {};
1627 p_params["formulation"] = assembler->name();
1628 p_params["root_path"] = root_path();
1629 {
1630 RowVectorNd min, max, delta;
1631 mesh->bounding_box(min, max);
1632 delta = (max - min) / 2. + min;
1633 if (mesh->is_volume())
1634 p_params["bbox_center"] = {delta(0), delta(1), delta(2)};
1635 else
1636 p_params["bbox_center"] = {delta(0), delta(1)};
1637 }
1638 problem->set_parameters(p_params);
1639
1640 rhs.resize(0, 0);
1641
1642 timer.start();
1643 logger().info("Assigning rhs...");
1644
1646 solve_data.rhs_assembler->assemble(mass_matrix_assembler->density(), rhs);
1647 rhs *= -1;
1648
1649 // if(problem->is_mixed())
1650 if (mixed_assembler != nullptr)
1651 {
1652 const int prev_size = rhs.size();
1653 const int n_larger = n_pressure_bases + (use_avg_pressure ? (assembler->is_fluid() ? 1 : 0) : 0);
1654 rhs.conservativeResize(prev_size + n_larger, rhs.cols());
1655 if (assembler->name() == "OperatorSplitting")
1656 {
1658 return;
1659 }
1660 // Divergence free rhs
1661 if (assembler->name() != "Bilaplacian" || local_neumann_boundary.empty())
1662 {
1663 rhs.block(prev_size, 0, n_larger, rhs.cols()).setZero();
1664 }
1665 else
1666 {
1667 Eigen::MatrixXd tmp(n_pressure_bases, 1);
1668 tmp.setZero();
1669
1670 std::shared_ptr<RhsAssembler> tmp_rhs_assembler = build_rhs_assembler(
1672
1673 tmp_rhs_assembler->set_bc(std::vector<LocalBoundary>(), std::vector<int>(), n_boundary_samples(), local_neumann_boundary, tmp);
1674 rhs.block(prev_size, 0, n_larger, rhs.cols()) = tmp;
1675 }
1676 }
1677
1678 timer.stop();
1679 timings.assigning_rhs_time = timer.getElapsedTime();
1680 logger().info(" took {}s", timings.assigning_rhs_time);
1681 }
1682
1683 void State::solve_problem(Eigen::MatrixXd &sol, Eigen::MatrixXd &pressure)
1684 {
1685 if (!mesh)
1686 {
1687 logger().error("Load the mesh first!");
1688 return;
1689 }
1690 if (n_bases <= 0)
1691 {
1692 logger().error("Build the bases first!");
1693 return;
1694 }
1695
1696 // if (rhs.size() <= 0)
1697 // {
1698 // logger().error("Assemble the rhs first!");
1699 // return;
1700 // }
1701
1702 // sol.resize(0, 0);
1703 // pressure.resize(0, 0);
1704 stats.spectrum.setZero();
1705
1706 igl::Timer timer;
1707 timer.start();
1708 logger().info("Solving {}", assembler->name());
1709
1710 init_solve(sol, pressure);
1711
1712 if (problem->is_time_dependent())
1713 {
1714 const double t0 = args["time"]["t0"];
1715 const int time_steps = args["time"]["time_steps"];
1716 const double dt = args["time"]["dt"];
1717
1718 // Pre log the output path for easier watching
1719 if (args["output"]["advanced"]["save_time_sequence"])
1720 {
1721 logger().info("Time sequence of simulation will be written to: \"{}\"",
1722 resolve_output_path(args["output"]["paraview"]["file_name"]));
1723 }
1724
1725 if (assembler->name() == "NavierStokes")
1726 solve_transient_navier_stokes(time_steps, t0, dt, sol, pressure);
1727 else if (assembler->name() == "OperatorSplitting")
1728 solve_transient_navier_stokes_split(time_steps, dt, sol, pressure);
1729 else if (is_homogenization())
1730 solve_homogenization(time_steps, t0, dt, sol);
1731 else if (is_problem_linear())
1732 solve_transient_linear(time_steps, t0, dt, sol, pressure);
1733 else if (!assembler->is_linear() && problem->is_scalar())
1734 throw std::runtime_error("Nonlinear scalar problems are not supported yet!");
1735 else
1736 solve_transient_tensor_nonlinear(time_steps, t0, dt, sol);
1737 }
1738 else
1739 {
1740 if (assembler->name() == "NavierStokes")
1741 solve_navier_stokes(sol, pressure);
1742 else if (is_homogenization())
1743 solve_homogenization(/* time steps */ 0, /* t0 */ 0, /* dt */ 0, sol);
1744 else if (is_problem_linear())
1745 {
1746 init_linear_solve(sol);
1747 solve_linear(sol, pressure);
1749 cache_transient_adjoint_quantities(0, sol, Eigen::MatrixXd::Zero(mesh->dimension(), mesh->dimension()));
1750 }
1751 else if (!assembler->is_linear() && problem->is_scalar())
1752 throw std::runtime_error("Nonlinear scalar problems are not supported yet!");
1753 else
1754 {
1758 cache_transient_adjoint_quantities(0, sol, Eigen::MatrixXd::Zero(mesh->dimension(), mesh->dimension()));
1759
1760 const std::string state_path = resolve_output_path(args["output"]["data"]["state"]);
1761 if (!state_path.empty())
1762 write_matrix(state_path, "u", sol);
1763 }
1764 }
1765
1766 timer.stop();
1767 timings.solving_time = timer.getElapsedTime();
1768 logger().info(" took {}s", timings.solving_time);
1769 }
1770
1771} // 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:1487
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:1068
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:1231
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:1683
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:1611
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:1364
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, const bool use_corner_quadrature, 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, const bool use_corner_quadrature, 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:2330
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:145
double assembling_stiffness_mat_time
time to assembly
Definition OutData.hpp:374
double assigning_rhs_time
time to computing the rhs
Definition OutData.hpp:378
double assembling_mass_mat_time
time to assembly mass
Definition OutData.hpp:376
double building_basis_time
time to construct the basis
Definition OutData.hpp:368
double solving_time
time to solve
Definition OutData.hpp:380
double computing_poly_basis_time
time to build the polygonal/polyhedral bases
Definition OutData.hpp:372
int n_flipped
number of flipped elements, compute only when using count_flipped_els (false by default)
Definition OutData.hpp:421
Eigen::Vector4d spectrum
spectrum of the stiffness matrix, enable only if POLYSOLVE_WITH_SPECTRA is ON (off by default)
Definition OutData.hpp:395
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:2515
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:2428
long long nn_zero
non zeros and sytem matrix size num dof is the total dof in the system
Definition OutData.hpp:413
double mesh_size
max edge lenght
Definition OutData.hpp:402
void reset()
clears all stats
Definition OutData.cpp:2506
double min_edge_length
min edge lenght
Definition OutData.hpp:404
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