44#include <paraviewo/VTMWriter.hpp>
45#include <paraviewo/PVDWriter.hpp>
47#include <SimpleBVH/BVH.hpp>
49#include <igl/write_triangle_mesh.h>
51#include <igl/facet_adjacency_matrix.h>
52#include <igl/connected_components.h>
62 void compute_traction_forces(
const State &state,
const Eigen::MatrixXd &solution,
const double t, Eigen::MatrixXd &traction_forces,
bool skip_dirichlet =
true)
65 if (!state.problem->is_scalar())
66 actual_dim = state.mesh->dimension();
70 const std::vector<basis::ElementBases> &bases = state.bases;
71 const std::vector<basis::ElementBases> &gbases = state.geom_bases();
73 Eigen::MatrixXd uv, samples, gtmp, rhs_fun, deform_mat, trafo;
74 Eigen::VectorXi global_primitive_ids;
75 Eigen::MatrixXd
points, normals;
76 Eigen::VectorXd weights;
79 traction_forces.setZero(state.n_bases * actual_dim, 1);
81 for (
const auto &lb : state.total_local_boundary)
83 const int e = lb.element_id();
89 const basis::ElementBases &gbs = gbases[
e];
90 const basis::ElementBases &bs = bases[
e];
92 vals.
compute(e, state.mesh->is_volume(), points, bs, gbs);
94 for (
int n = 0; n < normals.rows(); ++n)
98 if (solution.size() > 0)
100 assert(actual_dim == 2 || actual_dim == 3);
101 deform_mat.resize(actual_dim, actual_dim);
102 deform_mat.setZero();
103 for (
const auto &b :
vals.basis_values)
105 for (
const auto &g : b.global)
107 for (
int d = 0; d < actual_dim; ++d)
109 deform_mat.row(d) += solution(
g.index * actual_dim + d) * b.grad.row(n);
117 normals.row(n) = normals.row(n) * trafo.inverse();
118 normals.row(n).normalize();
121 std::vector<assembler::Assembler::NamedMatrix> tensor_flat;
122 state.assembler->compute_tensor_value(assembler::OutputData(t, e, bs, gbs, points, solution), tensor_flat);
128 const int g_index = v.
global[0].index * actual_dim;
130 for (
int q = 0; q <
points.rows(); ++q)
133 assert(tensor_flat[0].first ==
"cauchy_stess");
134 assert(tensor_flat[0].second.row(q).size() == actual_dim * actual_dim);
136 Eigen::MatrixXd stress_tensor =
utils::unflatten(tensor_flat[0].second.row(q), actual_dim);
138 traction_forces.block(g_index, 0, actual_dim, 1) += stress_tensor * normals.row(q).transpose() * v.
val(q) * weights(q);
148 const std::vector<basis::ElementBases> &bases,
149 const std::vector<mesh::LocalBoundary> &total_local_boundary,
150 Eigen::MatrixXd &node_positions,
151 Eigen::MatrixXi &boundary_edges,
152 Eigen::MatrixXi &boundary_triangles,
153 std::vector<Eigen::Triplet<double>> &displacement_map_entries)
157 displacement_map_entries.clear();
163 logger().warn(
"Skipping as the mesh has polygons");
169 node_positions.resize(n_bases + (is_simplicial ? 0 : mesh.
n_faces()), 3);
170 node_positions.setZero();
171 const Mesh3D &mesh3d =
dynamic_cast<const Mesh3D &
>(mesh);
173 std::vector<std::tuple<int, int, int>> tris;
175 std::vector<bool> visited_node(n_bases,
false);
177 std::stringstream print_warning;
183 for (
int j = 0; j < lb.size(); ++j)
185 const int eid = lb.global_primitive_id(j);
186 const int lid = lb[j];
189 if (mesh.
is_cube(lb.element_id()))
191 assert(!is_simplicial);
193 std::vector<int> loc_nodes;
196 for (
long n = 0; n < nodes.size(); ++n)
198 auto &bs = b.
bases[nodes(n)];
199 const auto &glob = bs.global();
200 if (glob.size() != 1)
203 int gindex = glob.front().index;
204 node_positions.row(gindex) = glob.front().node;
205 bary += glob.front().node;
206 loc_nodes.push_back(gindex);
209 if (loc_nodes.size() != 4)
211 logger().trace(
"skipping element {} since it is not Q1", eid);
217 const int new_node = n_bases + eid;
218 node_positions.row(new_node) = bary;
219 tris.emplace_back(loc_nodes[1], loc_nodes[0], new_node);
220 tris.emplace_back(loc_nodes[2], loc_nodes[1], new_node);
221 tris.emplace_back(loc_nodes[3], loc_nodes[2], new_node);
222 tris.emplace_back(loc_nodes[0], loc_nodes[3], new_node);
224 for (
int q = 0; q < 4; ++q)
226 if (!visited_node[loc_nodes[q]])
227 displacement_map_entries.emplace_back(loc_nodes[q], loc_nodes[q], 1);
229 visited_node[loc_nodes[q]] =
true;
230 displacement_map_entries.emplace_back(new_node, loc_nodes[q], 0.25);
238 logger().trace(
"skipping element {} since it is not a simplex or hex", eid);
244 std::vector<int> loc_nodes;
246 bool is_follower =
false;
249 for (
long n = 0; n < nodes.size(); ++n)
251 auto &bs = b.
bases[nodes(n)];
252 const auto &glob = bs.global();
253 if (glob.size() != 1)
264 for (
long n = 0; n < nodes.size(); ++n)
267 const std::vector<basis::Local2Global> &glob = bs.
global();
268 if (glob.size() != 1)
271 int gindex = glob.front().index;
272 node_positions.row(gindex) = glob.front().node;
273 loc_nodes.push_back(gindex);
276 if (loc_nodes.size() == 3)
278 tris.emplace_back(loc_nodes[0], loc_nodes[1], loc_nodes[2]);
280 else if (loc_nodes.size() == 6)
282 tris.emplace_back(loc_nodes[0], loc_nodes[3], loc_nodes[5]);
283 tris.emplace_back(loc_nodes[3], loc_nodes[1], loc_nodes[4]);
284 tris.emplace_back(loc_nodes[4], loc_nodes[2], loc_nodes[5]);
285 tris.emplace_back(loc_nodes[3], loc_nodes[4], loc_nodes[5]);
287 else if (loc_nodes.size() == 10)
289 tris.emplace_back(loc_nodes[0], loc_nodes[3], loc_nodes[8]);
290 tris.emplace_back(loc_nodes[3], loc_nodes[4], loc_nodes[9]);
291 tris.emplace_back(loc_nodes[4], loc_nodes[1], loc_nodes[5]);
292 tris.emplace_back(loc_nodes[5], loc_nodes[6], loc_nodes[9]);
293 tris.emplace_back(loc_nodes[6], loc_nodes[2], loc_nodes[7]);
294 tris.emplace_back(loc_nodes[7], loc_nodes[8], loc_nodes[9]);
295 tris.emplace_back(loc_nodes[8], loc_nodes[3], loc_nodes[9]);
296 tris.emplace_back(loc_nodes[9], loc_nodes[4], loc_nodes[5]);
297 tris.emplace_back(loc_nodes[6], loc_nodes[7], loc_nodes[9]);
299 else if (loc_nodes.size() == 15)
301 tris.emplace_back(loc_nodes[0], loc_nodes[3], loc_nodes[11]);
302 tris.emplace_back(loc_nodes[3], loc_nodes[4], loc_nodes[12]);
303 tris.emplace_back(loc_nodes[3], loc_nodes[12], loc_nodes[11]);
304 tris.emplace_back(loc_nodes[12], loc_nodes[10], loc_nodes[11]);
305 tris.emplace_back(loc_nodes[4], loc_nodes[5], loc_nodes[13]);
306 tris.emplace_back(loc_nodes[4], loc_nodes[13], loc_nodes[12]);
307 tris.emplace_back(loc_nodes[12], loc_nodes[13], loc_nodes[14]);
308 tris.emplace_back(loc_nodes[12], loc_nodes[14], loc_nodes[10]);
309 tris.emplace_back(loc_nodes[14], loc_nodes[9], loc_nodes[10]);
310 tris.emplace_back(loc_nodes[5], loc_nodes[1], loc_nodes[6]);
311 tris.emplace_back(loc_nodes[5], loc_nodes[6], loc_nodes[13]);
312 tris.emplace_back(loc_nodes[6], loc_nodes[7], loc_nodes[13]);
313 tris.emplace_back(loc_nodes[13], loc_nodes[7], loc_nodes[14]);
314 tris.emplace_back(loc_nodes[7], loc_nodes[8], loc_nodes[14]);
315 tris.emplace_back(loc_nodes[14], loc_nodes[8], loc_nodes[9]);
316 tris.emplace_back(loc_nodes[8], loc_nodes[2], loc_nodes[9]);
320 print_warning << loc_nodes.size() <<
" ";
326 for (
int k = 0; k < loc_nodes.size(); ++k)
328 if (!visited_node[loc_nodes[k]])
329 displacement_map_entries.emplace_back(loc_nodes[k], loc_nodes[k], 1);
331 visited_node[loc_nodes[k]] =
true;
337 if (print_warning.str().size() > 0)
338 logger().warn(
"Skipping faces as theys have {} nodes, boundary export supported up to p4", print_warning.str());
340 boundary_triangles.resize(tris.size(), 3);
341 for (
int i = 0; i < tris.size(); ++i)
343 boundary_triangles.row(i) << std::get<0>(tris[i]), std::get<2>(tris[i]), std::get<1>(tris[i]);
346 if (boundary_triangles.rows() > 0)
348 igl::edges(boundary_triangles, boundary_edges);
353 node_positions.resize(n_bases, 2);
354 node_positions.setZero();
355 const Mesh2D &mesh2d =
dynamic_cast<const Mesh2D &
>(mesh);
357 std::vector<std::pair<int, int>> edges;
363 for (
int j = 0; j < lb.size(); ++j)
365 const int eid = lb.global_primitive_id(j);
366 const int lid = lb[j];
371 for (
long n = 0; n < nodes.size(); ++n)
374 const std::vector<basis::Local2Global> &glob = bs.
global();
375 if (glob.size() != 1)
378 int gindex = glob.front().index;
379 node_positions.row(gindex) = glob.front().node.head<2>();
382 edges.emplace_back(prev_node, gindex);
388 boundary_triangles.resize(0, 0);
389 boundary_edges.resize(edges.size(), 2);
390 for (
int i = 0; i < edges.size(); ++i)
392 boundary_edges.row(i) << edges[i].first, edges[i].second;
399 const std::vector<basis::ElementBases> &bases,
400 const std::vector<basis::ElementBases> &gbases,
401 const std::vector<mesh::LocalBoundary> &total_local_boundary,
402 const Eigen::MatrixXd &solution,
403 const int problem_dim,
404 Eigen::MatrixXd &boundary_vis_vertices,
405 Eigen::MatrixXd &boundary_vis_local_vertices,
406 Eigen::MatrixXi &boundary_vis_elements,
407 Eigen::MatrixXi &boundary_vis_elements_ids,
408 Eigen::MatrixXi &boundary_vis_primitive_ids,
409 Eigen::MatrixXd &boundary_vis_normals,
410 Eigen::MatrixXd &displaced_boundary_vis_normals)
const
414 std::vector<Eigen::MatrixXd> lv, vertices, allnormals, displaced_allnormals;
415 std::vector<int> el_ids, global_primitive_ids;
416 Eigen::MatrixXd uv, local_pts, tmp_n, normals, displaced_normals, trafo, deform_mat;
422 std::vector<std::pair<int, int>> edges;
423 std::vector<std::tuple<int, int, int>> tris;
425 for (
auto it = total_local_boundary.begin(); it != total_local_boundary.end(); ++it)
427 const auto &lb = *it;
428 const auto &gbs = gbases[lb.element_id()];
429 const auto &bs = bases[lb.element_id()];
431 for (
int k = 0; k < lb.size(); ++k)
435 case BoundaryType::TRI_LINE:
439 case BoundaryType::QUAD_LINE:
443 case BoundaryType::QUAD:
447 case BoundaryType::TRI:
451 case BoundaryType::POLYGON:
455 case BoundaryType::POLYHEDRON:
458 case BoundaryType::INVALID:
465 vertices.emplace_back();
466 lv.emplace_back(local_pts);
467 el_ids.push_back(lb.element_id());
468 global_primitive_ids.push_back(lb.global_primitive_id(k));
469 gbs.eval_geom_mapping(local_pts, vertices.back());
470 vals.compute(lb.element_id(), mesh.
is_volume(), local_pts, bs, gbs);
471 const int tris_start = tris.size();
475 if (lb.type() == BoundaryType::QUAD)
477 const auto map = [n_samples, size](
int i,
int j) {
return j * n_samples + i + size; };
479 for (
int j = 0; j < n_samples - 1; ++j)
481 for (
int i = 0; i < n_samples - 1; ++i)
483 tris.emplace_back(map(i, j), map(i + 1, j), map(i, j + 1));
484 tris.emplace_back(map(i + 1, j + 1), map(i, j + 1), map(i + 1, j));
488 else if (lb.type() == BoundaryType::TRI)
491 std::vector<int> mapp(n_samples * n_samples, -1);
492 for (
int j = 0; j < n_samples; ++j)
494 for (
int i = 0; i < n_samples - j; ++i)
496 mapp[j * n_samples + i] = index;
500 const auto map = [mapp, n_samples](
int i,
int j) {
501 if (j * n_samples + i >= mapp.size())
503 return mapp[j * n_samples + i];
506 for (
int j = 0; j < n_samples - 1; ++j)
508 for (
int i = 0; i < n_samples - j; ++i)
510 if (map(i, j) >= 0 && map(i + 1, j) >= 0 && map(i, j + 1) >= 0)
511 tris.emplace_back(map(i, j) + size, map(i + 1, j) + size, map(i, j + 1) + size);
513 if (map(i + 1, j + 1) >= 0 && map(i, j + 1) >= 0 && map(i + 1, j) >= 0)
514 tris.emplace_back(map(i + 1, j + 1) + size, map(i, j + 1) + size, map(i + 1, j) + size);
525 for (
int i = 0; i < vertices.back().rows() - 1; ++i)
526 edges.emplace_back(i + size, i + size + 1);
529 normals.resize(
vals.jac_it.size(), tmp_n.cols());
530 displaced_normals.resize(
vals.jac_it.size(), tmp_n.cols());
532 for (
int n = 0; n <
vals.jac_it.size(); ++n)
534 trafo =
vals.jac_it[n].inverse();
536 if (problem_dim == 2 || problem_dim == 3)
539 if (solution.size() > 0)
541 deform_mat.resize(problem_dim, problem_dim);
542 deform_mat.setZero();
543 for (
const auto &b :
vals.basis_values)
544 for (
const auto &g : b.global)
545 for (
int d = 0; d < problem_dim; ++d)
546 deform_mat.row(d) += solution(g.index * problem_dim + d) * b.grad.row(n);
552 normals.row(n) = tmp_n *
vals.jac_it[n];
553 normals.row(n).normalize();
555 displaced_normals.row(n) = tmp_n * trafo.inverse();
556 displaced_normals.row(n).normalize();
559 allnormals.push_back(normals);
560 displaced_allnormals.push_back(displaced_normals);
563 for (
int n = 0; n <
vals.jac_it.size(); ++n)
565 tmp_n += normals.row(n);
570 Eigen::Vector3d e1 = vertices.back().row(std::get<1>(tris.back()) - size) - vertices.back().row(std::get<0>(tris.back()) - size);
571 Eigen::Vector3d e2 = vertices.back().row(std::get<2>(tris.back()) - size) - vertices.back().row(std::get<0>(tris.back()) - size);
573 Eigen::Vector3d n = e1.cross(e2);
574 Eigen::Vector3d nn = tmp_n.transpose();
578 for (
int i = tris_start; i < tris.size(); ++i)
580 tris[i] = std::tuple<int, int, int>(std::get<0>(tris[i]), std::get<2>(tris[i]), std::get<1>(tris[i]));
585 size += vertices.back().rows();
589 boundary_vis_vertices.resize(size, vertices.front().cols());
590 boundary_vis_local_vertices.resize(size, vertices.front().cols());
591 boundary_vis_elements_ids.resize(size, 1);
592 boundary_vis_primitive_ids.resize(size, 1);
593 boundary_vis_normals.resize(size, vertices.front().cols());
594 displaced_boundary_vis_normals.resize(size, vertices.front().cols());
597 boundary_vis_elements.resize(tris.size(), 3);
599 boundary_vis_elements.resize(edges.size(), 2);
603 for (
const auto &v : vertices)
605 boundary_vis_vertices.block(index, 0, v.rows(), v.cols()) = v;
606 boundary_vis_local_vertices.block(index, 0, v.rows(), v.cols()) = lv[ii];
607 boundary_vis_elements_ids.block(index, 0, v.rows(), 1).setConstant(el_ids[ii]);
608 boundary_vis_primitive_ids.block(index, 0, v.rows(), 1).setConstant(global_primitive_ids[ii++]);
613 for (
const auto &n : allnormals)
615 boundary_vis_normals.block(index, 0, n.rows(), n.cols()) = n;
620 for (
const auto &n : displaced_allnormals)
622 displaced_boundary_vis_normals.block(index, 0, n.rows(), n.cols()) = n;
629 for (
const auto &t : tris)
631 boundary_vis_elements.row(index) << std::get<0>(t), std::get<1>(t), std::get<2>(t);
637 for (
const auto &e : edges)
639 boundary_vis_elements.row(index) << e.first, e.second;
647 const Eigen::VectorXi &disc_orders,
648 const std::vector<basis::ElementBases> &gbases,
649 const std::map<int, Eigen::MatrixXd> &polys,
650 const std::map<
int, std::pair<Eigen::MatrixXd, Eigen::MatrixXi>> &polys_3d,
651 const bool boundary_only,
652 Eigen::MatrixXd &points,
653 Eigen::MatrixXi &tets,
654 Eigen::MatrixXi &el_id,
655 Eigen::MatrixXd &discr)
const
670 const auto ¤t_bases = gbases;
671 int tet_total_size = 0;
672 int pts_total_size = 0;
674 Eigen::MatrixXd vis_pts_poly;
675 Eigen::MatrixXi vis_faces_poly, vis_edges_poly;
677 for (
size_t i = 0; i < current_bases.size(); ++i)
679 const auto &bs = current_bases[i];
687 pts_total_size += sampler.simplex_points().rows();
691 tet_total_size += sampler.cube_volume().rows();
692 pts_total_size += sampler.cube_points().rows();
698 sampler.sample_polyhedron(polys_3d.at(i).first, polys_3d.at(i).second, vis_pts_poly, vis_faces_poly, vis_edges_poly);
700 tet_total_size += vis_faces_poly.rows();
701 pts_total_size += vis_pts_poly.rows();
705 sampler.sample_polygon(polys.at(i), vis_pts_poly, vis_faces_poly, vis_edges_poly);
707 tet_total_size += vis_faces_poly.rows();
708 pts_total_size += vis_pts_poly.rows();
713 points.resize(pts_total_size, mesh.
dimension());
714 tets.resize(tet_total_size, mesh.
is_volume() ? 4 : 3);
716 el_id.resize(pts_total_size, 1);
717 discr.resize(pts_total_size, 1);
719 Eigen::MatrixXd mapped, tmp;
720 int tet_index = 0, pts_index = 0;
722 for (
size_t i = 0; i < current_bases.size(); ++i)
724 const auto &bs = current_bases[i];
731 bs.eval_geom_mapping(sampler.simplex_points(), mapped);
733 tets.block(tet_index, 0, sampler.simplex_volume().rows(), tets.cols()) = sampler.simplex_volume().array() + pts_index;
734 tet_index += sampler.simplex_volume().rows();
736 points.block(pts_index, 0, mapped.rows(), points.cols()) = mapped;
737 discr.block(pts_index, 0, mapped.rows(), 1).setConstant(disc_orders(i));
738 el_id.block(pts_index, 0, mapped.rows(), 1).setConstant(i);
739 pts_index += mapped.rows();
743 bs.eval_geom_mapping(sampler.cube_points(), mapped);
745 tets.block(tet_index, 0, sampler.cube_volume().rows(), tets.cols()) = sampler.cube_volume().array() + pts_index;
746 tet_index += sampler.cube_volume().rows();
748 points.block(pts_index, 0, mapped.rows(), points.cols()) = mapped;
749 discr.block(pts_index, 0, mapped.rows(), 1).setConstant(disc_orders(i));
750 el_id.block(pts_index, 0, mapped.rows(), 1).setConstant(i);
751 pts_index += mapped.rows();
757 sampler.sample_polyhedron(polys_3d.at(i).first, polys_3d.at(i).second, vis_pts_poly, vis_faces_poly, vis_edges_poly);
758 bs.eval_geom_mapping(vis_pts_poly, mapped);
760 tets.block(tet_index, 0, vis_faces_poly.rows(), tets.cols()) = vis_faces_poly.array() + pts_index;
761 tet_index += vis_faces_poly.rows();
763 points.block(pts_index, 0, mapped.rows(), points.cols()) = mapped;
764 discr.block(pts_index, 0, mapped.rows(), 1).setConstant(-1);
765 el_id.block(pts_index, 0, mapped.rows(), 1).setConstant(i);
766 pts_index += mapped.rows();
770 sampler.sample_polygon(polys.at(i), vis_pts_poly, vis_faces_poly, vis_edges_poly);
771 bs.eval_geom_mapping(vis_pts_poly, mapped);
773 tets.block(tet_index, 0, vis_faces_poly.rows(), tets.cols()) = vis_faces_poly.array() + pts_index;
774 tet_index += vis_faces_poly.rows();
776 points.block(pts_index, 0, mapped.rows(), points.cols()) = mapped;
777 discr.block(pts_index, 0, mapped.rows(), 1).setConstant(-1);
778 el_id.block(pts_index, 0, mapped.rows(), 1).setConstant(i);
779 pts_index += mapped.rows();
784 assert(pts_index == points.rows());
785 assert(tet_index == tets.rows());
790 const Eigen::VectorXi &disc_orders,
791 const std::vector<basis::ElementBases> &bases,
792 Eigen::MatrixXd &points,
793 std::vector<std::vector<int>> &elements,
794 Eigen::MatrixXi &el_id,
795 Eigen::MatrixXd &discr)
const
809 std::vector<RowVectorNd> nodes;
810 int pts_total_size = 0;
811 elements.resize(bases.size());
812 Eigen::MatrixXd ref_pts;
814 for (
size_t i = 0; i < bases.size(); ++i)
816 const auto &bs = bases[i];
834 const int n_v =
static_cast<const mesh::Mesh2D &
>(mesh).n_face_vertices(i);
835 ref_pts.resize(n_v, 2);
839 pts_total_size += ref_pts.rows();
842 points.resize(pts_total_size, mesh.
dimension());
844 el_id.resize(pts_total_size, 1);
845 discr.resize(pts_total_size, 1);
847 Eigen::MatrixXd mapped;
850 std::string error_msg =
"";
852 for (
size_t i = 0; i < bases.size(); ++i)
854 const auto &bs = bases[i];
874 bs.eval_geom_mapping(ref_pts, mapped);
876 for (
int j = 0; j < mapped.rows(); ++j)
878 points.row(pts_index) = mapped.row(j);
879 el_id(pts_index) = i;
880 discr(pts_index) = disc_orders(i);
881 elements[i].push_back(pts_index);
890 const int n_nodes = elements[i].size();
891 if (disc_orders(i) >= 3)
893 std::swap(elements[i][16], elements[i][17]);
894 std::swap(elements[i][17], elements[i][18]);
895 std::swap(elements[i][18], elements[i][19]);
897 if (disc_orders(i) > 4)
898 error_msg =
"Saving high-order meshes not implemented for P5+ elements!";
902 if (disc_orders(i) == 4)
904 const int n_nodes = elements[i].size();
905 std::swap(elements[i][n_nodes - 1], elements[i][n_nodes - 2]);
907 if (disc_orders(i) > 4)
908 error_msg =
"Saving high-order meshes not implemented for P5+ elements!";
911 else if (disc_orders(i) > 1)
912 error_msg =
"Saving high-order meshes not implemented for Q2+ elements!";
915 if (!error_msg.empty())
918 for (
size_t i = 0; i < bases.size(); ++i)
923 const auto &mesh2d =
static_cast<const mesh::Mesh2D &
>(mesh);
926 for (
int j = 0; j < n_v; ++j)
928 points.row(pts_index) = mesh2d.point(mesh2d.face_vertex(i, j));
929 el_id(pts_index) = i;
930 discr(pts_index) = disc_orders(i);
931 elements[i].push_back(pts_index);
937 assert(pts_index == points.rows());
942 const Eigen::MatrixXd &sol,
943 const Eigen::MatrixXd &pressure,
944 const bool is_time_dependent,
945 const double tend_in,
948 const std::string &vis_mesh_path,
949 const std::string &nodes_path,
950 const std::string &solution_path,
951 const std::string &stress_path,
952 const std::string &mises_path,
953 const bool is_contact_enabled,
954 std::vector<SolutionFrame> &solution_frames)
const
958 logger().error(
"Load the mesh first!");
961 const int n_bases = state.
n_bases;
962 const std::vector<basis::ElementBases> &bases = state.
bases;
963 const std::vector<basis::ElementBases> &gbases = state.
geom_bases();
966 const Eigen::MatrixXd &rhs = state.
rhs;
971 logger().error(
"Build the bases first!");
981 logger().error(
"Solve the problem first!");
985 if (!solution_path.empty())
987 std::ofstream out(solution_path);
989 out << std::scientific;
993 Eigen::VectorXi reordering(n_bases);
994 reordering.setConstant(-1);
996 for (
int i = 0; i < in_node_to_node.size(); ++i)
998 reordering[in_node_to_node[i]] = i;
1001 Eigen::MatrixXd tmp(tmp_sol.rows(), tmp_sol.cols());
1003 for (
int i = 0; i < reordering.size(); ++i)
1005 if (reordering[i] < 0)
1008 tmp.row(reordering[i]) = tmp_sol.row(i);
1011 for (
int i = 0; i < tmp.rows(); ++i)
1013 for (
int j = 0; j < tmp.cols(); ++j)
1014 out << tmp(i, j) <<
" ";
1020 out << sol << std::endl;
1024 double tend = tend_in;
1028 if (!vis_mesh_path.empty() && !is_time_dependent)
1031 vis_mesh_path, state, sol, pressure,
1033 is_contact_enabled, solution_frames);
1035 if (!nodes_path.empty())
1037 Eigen::MatrixXd nodes(n_bases, mesh.
dimension());
1043 for (
size_t ii = 0; ii < b.global().size(); ++ii)
1045 const auto &lg = b.global()[ii];
1046 nodes.row(lg.index) = lg.node;
1050 std::ofstream out(nodes_path);
1055 if (!stress_path.empty())
1057 Eigen::MatrixXd result;
1058 Eigen::VectorXd mises;
1062 sol, tend, result, mises);
1063 std::ofstream out(stress_path);
1067 if (!mises_path.empty())
1069 Eigen::MatrixXd result;
1070 Eigen::VectorXd mises;
1074 sol, tend, result, mises);
1075 std::ofstream out(mises_path);
1083 volume = args[
"output"][
"paraview"][
"volume"];
1084 surface = args[
"output"][
"paraview"][
"surface"];
1085 wire = args[
"output"][
"paraview"][
"wireframe"];
1086 points = args[
"output"][
"paraview"][
"points"];
1087 contact_forces = args[
"output"][
"paraview"][
"options"][
"contact_forces"] && !is_problem_scalar;
1088 friction_forces = args[
"output"][
"paraview"][
"options"][
"friction_forces"] && !is_problem_scalar;
1093 body_ids = args[
"output"][
"paraview"][
"options"][
"body_ids"];
1094 sol_on_grid = args[
"output"][
"advanced"][
"sol_on_grid"] > 0;
1095 velocity = args[
"output"][
"paraview"][
"options"][
"velocity"];
1096 acceleration = args[
"output"][
"paraview"][
"options"][
"acceleration"];
1097 forces = args[
"output"][
"paraview"][
"options"][
"forces"] && !is_problem_scalar;
1098 jacobian_validity = args[
"output"][
"paraview"][
"options"][
"jacobian_validity"] && !is_problem_scalar;
1100 scalar_values = args[
"output"][
"paraview"][
"options"][
"scalar_values"];
1101 tensor_values = args[
"output"][
"paraview"][
"options"][
"tensor_values"] && !is_problem_scalar;
1103 nodes = args[
"output"][
"paraview"][
"options"][
"nodes"] && !is_problem_scalar;
1105 use_spline = args[
"space"][
"basis_type"] ==
"Spline";
1107 reorder_output = args[
"output"][
"data"][
"advanced"][
"reorder_nodes"];
1109 use_hdf5 = args[
"output"][
"paraview"][
"options"][
"use_hdf5"];
1115 const std::string &path,
1117 const Eigen::MatrixXd &sol,
1118 const Eigen::MatrixXd &pressure,
1122 const bool is_contact_enabled,
1123 std::vector<SolutionFrame> &solution_frames)
const
1127 logger().error(
"Load the mesh first!");
1131 const Eigen::MatrixXd &rhs = state.
rhs;
1135 logger().error(
"Build the bases first!");
1143 if (sol.size() <= 0)
1145 logger().error(
"Solve the problem first!");
1149 const std::filesystem::path fs_path(path);
1150 const std::string path_stem = fs_path.stem().string();
1151 const std::string base_path = (fs_path.parent_path() / path_stem).
string();
1161 is_contact_enabled, solution_frames);
1167 is_contact_enabled, solution_frames);
1183 paraviewo::VTMWriter vtm(t);
1185 vtm.add_dataset(
"Volume",
"data", path_stem + opts.
file_extension());
1187 vtm.add_dataset(
"Surface",
"data", path_stem +
"_surf" + opts.
file_extension());
1189 vtm.add_dataset(
"Contact",
"data", path_stem +
"_surf_contact" + opts.
file_extension());
1191 vtm.add_dataset(
"Wireframe",
"data", path_stem +
"_wire" + opts.
file_extension());
1193 vtm.add_dataset(
"Points",
"data", path_stem +
"_points" + opts.
file_extension());
1194 vtm.save(base_path +
".vtm");
1198 const std::string &path,
1200 const Eigen::MatrixXd &sol,
1201 const Eigen::MatrixXd &pressure,
1205 std::vector<SolutionFrame> &solution_frames)
const
1207 const Eigen::VectorXi &disc_orders = state.
disc_orders;
1209 const std::vector<basis::ElementBases> &bases = state.
bases;
1210 const std::vector<basis::ElementBases> &pressure_bases = state.
pressure_bases;
1211 const std::vector<basis::ElementBases> &gbases = state.
geom_bases();
1212 const std::map<int, Eigen::MatrixXd> &polys = state.
polys;
1213 const std::map<int, std::pair<Eigen::MatrixXd, Eigen::MatrixXi>> &polys_3d = state.
polys_3d;
1220 Eigen::MatrixXd points;
1221 Eigen::MatrixXi tets;
1222 Eigen::MatrixXi el_id;
1223 Eigen::MatrixXd discr;
1224 std::vector<std::vector<int>> elements;
1229 points, tets, el_id, discr);
1232 points, elements, el_id, discr);
1234 Eigen::MatrixXd fun, exact_fun, err, node_fun;
1239 Eigen::MatrixXd tmp, tmp_grad;
1240 Eigen::MatrixXd tmp_p, tmp_grad_p;
1242 res.setConstant(std::numeric_limits<double>::quiet_NaN());
1244 res_grad.setConstant(std::numeric_limits<double>::quiet_NaN());
1247 res_p.setConstant(std::numeric_limits<double>::quiet_NaN());
1249 res_grad_p.setConstant(std::numeric_limits<double>::quiet_NaN());
1258 Eigen::MatrixXd pt(1, bc.cols() - 1);
1259 for (
int d = 1; d < bc.cols(); ++d)
1262 mesh, problem.
is_scalar(), bases, gbases,
1263 el_id, pt, sol, tmp, tmp_grad);
1266 res_grad.row(i) = tmp_grad;
1271 mesh, 1, pressure_bases, gbases,
1272 el_id, pt, pressure, tmp_p, tmp_grad_p);
1273 res_p.row(i) = tmp_p;
1274 res_grad_p.row(i) = tmp_grad_p;
1278 std::ofstream os(path +
"_sol.txt");
1281 std::ofstream osg(path +
"_grad.txt");
1284 std::ofstream osgg(path +
"_grid.txt");
1289 std::ofstream osp(path +
"_p_sol.txt");
1292 std::ofstream osgp(path +
"_p_grad.txt");
1297 Eigen::Vector<bool, -1> validity;
1310 Eigen::MatrixXd tmp = Eigen::VectorXd::LinSpaced(sol.size(), 0, sol.size() - 1);
1320 fun.conservativeResize(fun.rows() + obstacle.
n_vertices(), fun.cols());
1321 node_fun.conservativeResize(node_fun.rows() + obstacle.
n_vertices(), node_fun.cols());
1322 node_fun.bottomRows(obstacle.
n_vertices()).setZero();
1330 problem.
exact(points, t, exact_fun);
1331 err = (fun - exact_fun).eval().rowwise().norm();
1335 exact_fun.conservativeResize(exact_fun.rows() + obstacle.
n_vertices(), exact_fun.cols());
1339 err.conservativeResize(err.rows() + obstacle.
n_vertices(), 1);
1340 err.bottomRows(obstacle.
n_vertices()).setZero();
1344 std::shared_ptr<paraviewo::ParaviewWriter> tmpw;
1346 tmpw = std::make_shared<paraviewo::HDF5VTUWriter>();
1348 tmpw = std::make_shared<paraviewo::VTUWriter>();
1349 paraviewo::ParaviewWriter &writer = *tmpw;
1351 if (validity.size())
1352 writer.add_field(
"validity", validity.cast<
double>());
1355 writer.add_field(
"nodes", node_fun);
1359 bool is_time_integrator_valid = time_integrator !=
nullptr;
1363 const Eigen::VectorXd velocity =
1364 is_time_integrator_valid ? (time_integrator->v_prev()) : Eigen::VectorXd::Zero(sol.size());
1370 const Eigen::VectorXd acceleration =
1371 is_time_integrator_valid ? (time_integrator->a_prev()) : Eigen::VectorXd::Zero(sol.size());
1385 if (form ==
nullptr)
1388 Eigen::VectorXd force;
1389 if (form->enabled())
1391 form->first_derivative(sol, force);
1396 force.setZero(sol.size());
1406 Eigen::MatrixXd interp_p;
1414 interp_p.conservativeResize(interp_p.size() + obstacle.
n_vertices(), 1);
1415 interp_p.bottomRows(obstacle.
n_vertices()).setZero();
1419 writer.add_field(
"pressure", interp_p);
1421 solution_frames.back().pressure = interp_p;
1426 discr.conservativeResize(discr.size() + obstacle.
n_vertices(), 1);
1427 discr.bottomRows(obstacle.
n_vertices()).setZero();
1431 writer.add_field(
"discr", discr);
1437 writer.add_field(
"exact", exact_fun);
1438 writer.add_field(
"error", err);
1442 solution_frames.back().exact = exact_fun;
1443 solution_frames.back().error = err;
1447 if (fun.cols() != 1)
1449 std::vector<assembler::Assembler::NamedMatrix>
vals, tvals;
1451 mesh, problem.
is_scalar(), bases, gbases,
1456 for (
auto &[_, v] :
vals)
1463 for (
const auto &[name, v] :
vals)
1464 writer.add_field(name, v);
1466 else if (
vals.size() > 0)
1467 solution_frames.back().scalar_value =
vals[0].second;
1477 for (
auto &[_, v] : tvals)
1480 for (
const auto &[name, v] : tvals)
1483 assert(v.cols() % stride == 0);
1485 for (
int i = 0; i < v.cols(); i += stride)
1487 const Eigen::MatrixXd tmp = v.middleCols(i, stride);
1488 assert(tmp.cols() == stride);
1490 const int ii = (i / stride) + 1;
1491 writer.add_field(fmt::format(
"{:s}_{:d}", name, ii), tmp);
1506 for (
auto &v :
vals)
1508 v.second.conservativeResize(v.second.size() + obstacle.
n_vertices(), 1);
1509 v.second.bottomRows(obstacle.
n_vertices()).setZero();
1517 for (
const auto &v :
vals)
1518 writer.add_field(fmt::format(
"{:s}_avg", v.first), v.second);
1520 else if (
vals.size() > 0)
1521 solution_frames.back().scalar_value_avg =
vals[0].second;
1535 std::map<std::string, Eigen::MatrixXd> param_val;
1536 for (
const auto &[p, _] : params)
1537 param_val[p] = Eigen::MatrixXd(points.rows(), 1);
1538 Eigen::MatrixXd rhos(points.rows(), 1);
1540 Eigen::MatrixXd local_pts;
1541 Eigen::MatrixXi vis_faces_poly, vis_edges_poly;
1545 for (
int e = 0; e < int(bases.size()); ++e)
1553 local_pts = sampler.simplex_points();
1555 local_pts = sampler.cube_points();
1559 sampler.sample_polyhedron(polys_3d.at(e).first, polys_3d.at(e).second, local_pts, vis_faces_poly, vis_edges_poly);
1561 sampler.sample_polygon(polys.at(e), local_pts, vis_faces_poly, vis_edges_poly);
1583 const auto &mesh2d =
static_cast<const mesh::Mesh2D &
>(mesh);
1585 local_pts.resize(n_v, 2);
1587 for (
int j = 0; j < n_v; ++j)
1589 local_pts.row(j) = mesh2d.point(mesh2d.face_vertex(e, j));
1598 for (
int j = 0; j <
vals.val.rows(); ++j)
1600 for (
const auto &[p, func] : params)
1601 param_val.at(p)(index) = func(local_pts.row(j),
vals.val.row(j), t, e);
1603 rhos(index) = density(local_pts.row(j),
vals.val.row(j), t, e);
1609 assert(index == points.rows());
1613 for (
auto &[_, tmp] : param_val)
1615 tmp.conservativeResize(tmp.size() + obstacle.
n_vertices(), 1);
1616 tmp.bottomRows(obstacle.
n_vertices()).setZero();
1619 rhos.conservativeResize(rhos.size() + obstacle.
n_vertices(), 1);
1620 rhos.bottomRows(obstacle.
n_vertices()).setZero();
1622 for (
const auto &[p, tmp] : param_val)
1623 writer.add_field(p, tmp);
1624 writer.add_field(
"rho", rhos);
1630 Eigen::MatrixXd ids(points.rows(), 1);
1632 for (
int i = 0; i < points.rows(); ++i)
1639 ids.conservativeResize(ids.size() + obstacle.
n_vertices(), 1);
1640 ids.bottomRows(obstacle.
n_vertices()).setZero();
1643 writer.add_field(
"body_ids", ids);
1651 Eigen::MatrixXd traction_forces, traction_forces_fun;
1652 compute_traction_forces(state, sol, t, traction_forces,
false);
1661 traction_forces_fun.conservativeResize(traction_forces_fun.rows() + obstacle.
n_vertices(), traction_forces_fun.cols());
1662 traction_forces_fun.bottomRows(obstacle.
n_vertices()).setZero();
1665 writer.add_field(
"traction_force", traction_forces_fun);
1672 Eigen::MatrixXd potential_grad, potential_grad_fun;
1682 potential_grad_fun.conservativeResize(potential_grad_fun.rows() + obstacle.
n_vertices(), potential_grad_fun.cols());
1683 potential_grad_fun.bottomRows(obstacle.
n_vertices()).setZero();
1686 writer.add_field(
"gradient_of_potential", potential_grad_fun);
1688 catch (std::exception &)
1695 writer.add_field(
"solution", fun);
1697 solution_frames.back().solution = fun;
1703 const int orig_p = points.rows();
1704 points.conservativeResize(points.rows() + obstacle.
n_vertices(), points.cols());
1705 points.bottomRows(obstacle.
n_vertices()) = obstacle.
v();
1707 if (elements.empty())
1709 for (
int i = 0; i < tets.rows(); ++i)
1711 elements.emplace_back();
1712 for (
int j = 0; j < tets.cols(); ++j)
1713 elements.back().push_back(tets(i, j));
1719 elements.emplace_back();
1726 elements.emplace_back();
1733 elements.emplace_back();
1738 if (elements.empty())
1739 writer.write_mesh(path, points, tets);
1741 writer.write_mesh(path, points, elements,
true, disc_orders.maxCoeff() == 1);
1745 solution_frames.back().name = path;
1746 solution_frames.back().points = points;
1747 solution_frames.back().connectivity = tets;
1753 const Eigen::MatrixXd &points,
1755 const std::string &name,
1756 const Eigen::VectorXd &field,
1757 paraviewo::ParaviewWriter &writer)
const
1759 Eigen::MatrixXd inerpolated_field;
1767 inerpolated_field.conservativeResize(
1775 writer.add_field(name, inerpolated_field);
1781 const std::string &export_surface,
1783 const Eigen::MatrixXd &sol,
1784 const Eigen::MatrixXd &pressure,
1788 const bool is_contact_enabled,
1789 std::vector<SolutionFrame> &solution_frames)
const
1792 const Eigen::VectorXi &disc_orders = state.
disc_orders;
1794 const std::vector<basis::ElementBases> &bases = state.
bases;
1795 const std::vector<basis::ElementBases> &pressure_bases = state.
pressure_bases;
1796 const std::vector<basis::ElementBases> &gbases = state.
geom_bases();
1802 Eigen::MatrixXd boundary_vis_vertices;
1803 Eigen::MatrixXd boundary_vis_local_vertices;
1804 Eigen::MatrixXi boundary_vis_elements;
1805 Eigen::MatrixXi boundary_vis_elements_ids;
1806 Eigen::MatrixXi boundary_vis_primitive_ids;
1807 Eigen::MatrixXd boundary_vis_normals;
1808 Eigen::MatrixXd displaced_boundary_vis_normals;
1811 boundary_vis_vertices, boundary_vis_local_vertices, boundary_vis_elements,
1812 boundary_vis_elements_ids, boundary_vis_primitive_ids, boundary_vis_normals,
1813 displaced_boundary_vis_normals);
1815 Eigen::MatrixXd fun, interp_p, discr, vect, b_sidesets;
1817 Eigen::MatrixXd lsol, lp, lgrad, lpgrad;
1823 discr.resize(boundary_vis_vertices.rows(), 1);
1824 fun.resize(boundary_vis_vertices.rows(), actual_dim);
1825 interp_p.resize(boundary_vis_vertices.rows(), 1);
1826 vect.resize(boundary_vis_vertices.rows(), mesh.
dimension());
1828 b_sidesets.resize(boundary_vis_vertices.rows(), 1);
1829 b_sidesets.setZero();
1831 for (
int i = 0; i < boundary_vis_vertices.rows(); ++i)
1833 const auto s_id = mesh.
get_boundary_id(boundary_vis_primitive_ids(i));
1836 b_sidesets(i) = s_id;
1839 const int el_index = boundary_vis_elements_ids(i);
1841 mesh, problem.
is_scalar(), bases, gbases,
1842 el_index, boundary_vis_local_vertices.row(i), sol, lsol, lgrad);
1843 assert(lsol.size() == actual_dim);
1847 mesh, 1, pressure_bases, gbases,
1848 el_index, boundary_vis_local_vertices.row(i), pressure, lp, lpgrad);
1849 assert(lp.size() == 1);
1850 interp_p(i) = lp(0);
1853 discr(i) = disc_orders(el_index);
1854 for (
int j = 0; j < actual_dim; ++j)
1856 fun(i, j) = lsol(j);
1859 if (actual_dim == 1)
1861 assert(lgrad.size() == mesh.
dimension());
1862 for (
int j = 0; j < mesh.
dimension(); ++j)
1864 vect(i, j) = lgrad(j);
1869 assert(lgrad.size() == actual_dim * actual_dim);
1870 std::vector<assembler::Assembler::NamedMatrix> tensor_flat;
1875 assert(tensor_flat[0].first ==
"cauchy_stess");
1876 assert(tensor_flat[0].second.size() == actual_dim * actual_dim);
1878 Eigen::Map<Eigen::MatrixXd> tensor(tensor_flat[0].second.data(), actual_dim, actual_dim);
1879 vect.row(i) = displaced_boundary_vis_normals.row(i) * tensor;
1885 area = mesh.
tri_area(boundary_vis_primitive_ids(i));
1886 else if (mesh.
is_cube(el_index))
1887 area = mesh.
quad_area(boundary_vis_primitive_ids(i));
1890 area = mesh.
edge_length(boundary_vis_primitive_ids(i));
1892 vect.row(i) *= area;
1896 std::shared_ptr<paraviewo::ParaviewWriter> tmpw;
1898 tmpw = std::make_shared<paraviewo::HDF5VTUWriter>();
1900 tmpw = std::make_shared<paraviewo::VTUWriter>();
1901 paraviewo::ParaviewWriter &writer = *tmpw;
1906 writer.add_field(
"normals", boundary_vis_normals);
1907 writer.add_field(
"displaced_normals", displaced_boundary_vis_normals);
1909 writer.add_field(
"pressure", interp_p);
1910 writer.add_field(
"discr", discr);
1911 writer.add_field(
"sidesets", b_sidesets);
1913 if (actual_dim == 1)
1914 writer.add_field(
"solution_grad", vect);
1917 writer.add_field(
"traction_force", vect);
1923 solution_frames.back().pressure = interp_p;
1930 std::map<std::string, Eigen::MatrixXd> param_val;
1931 for (
const auto &[p, _] : params)
1932 param_val[p] = Eigen::MatrixXd(boundary_vis_vertices.rows(), 1);
1933 Eigen::MatrixXd rhos(boundary_vis_vertices.rows(), 1);
1935 for (
int i = 0; i < boundary_vis_vertices.rows(); ++i)
1939 for (
const auto &[p, func] : params)
1940 param_val.at(p)(i) = func(boundary_vis_local_vertices.row(i), boundary_vis_vertices.row(i), t, boundary_vis_elements_ids(i));
1942 rhos(i) = density(boundary_vis_local_vertices.row(i), boundary_vis_vertices.row(i), t, boundary_vis_elements_ids(i));
1945 for (
const auto &[p, tmp] : param_val)
1946 writer.add_field(p, tmp);
1947 writer.add_field(
"rho", rhos);
1953 Eigen::MatrixXd ids(boundary_vis_vertices.rows(), 1);
1955 for (
int i = 0; i < boundary_vis_vertices.rows(); ++i)
1957 ids(i) = mesh.
get_body_id(boundary_vis_elements_ids(i));
1960 writer.add_field(
"body_ids", ids);
1965 writer.add_field(
"solution", fun);
1967 solution_frames.back().solution = fun;
1970 writer.write_mesh(export_surface, boundary_vis_vertices, boundary_vis_elements);
1973 solution_frames.back().name = export_surface;
1974 solution_frames.back().points = boundary_vis_vertices;
1975 solution_frames.back().connectivity = boundary_vis_elements;
1980 const std::string &export_surface,
1982 const Eigen::MatrixXd &sol,
1983 const Eigen::MatrixXd &pressure,
1987 const bool is_contact_enabled,
1988 std::vector<SolutionFrame> &solution_frames)
const
1992 const double dhat = state.
args[
"contact"][
"dhat"];
1993 const double friction_coefficient = state.
args[
"contact"][
"friction_coefficient"];
1994 const double epsv = state.
args[
"contact"][
"epsv"];
2000 std::shared_ptr<paraviewo::ParaviewWriter> tmpw;
2002 tmpw = std::make_shared<paraviewo::HDF5VTUWriter>();
2004 tmpw = std::make_shared<paraviewo::VTUWriter>();
2005 paraviewo::ParaviewWriter &writer = *tmpw;
2007 const int problem_dim = mesh.
dimension();
2008 const Eigen::MatrixXd full_displacements =
utils::unflatten(sol, problem_dim);
2009 const Eigen::MatrixXd surface_displacements = collision_mesh.map_displacements(full_displacements);
2011 const Eigen::MatrixXd displaced_surface = collision_mesh.displace_vertices(full_displacements);
2013 ipc::Collisions collision_set;
2014 collision_set.set_use_convergent_formulation(state.
args[
"contact"][
"use_convergent_formulation"]);
2015 collision_set.build(
2016 collision_mesh, displaced_surface, dhat,
2017 0, state.
args[
"solver"][
"contact"][
"CCD"][
"broad_phase"]);
2019 ipc::BarrierPotential barrier_potential(dhat);
2021 const double barrier_stiffness = contact_form !=
nullptr ? contact_form->barrier_stiffness() : 1;
2025 Eigen::MatrixXd forces = -barrier_stiffness * barrier_potential.gradient(collision_set, collision_mesh, displaced_surface);
2029 assert(forces_reshaped.rows() == surface_displacements.rows());
2030 assert(forces_reshaped.cols() == surface_displacements.cols());
2031 writer.add_field(
"contact_forces", forces_reshaped);
2036 ipc::FrictionCollisions friction_collision_set;
2037 friction_collision_set.build(
2038 collision_mesh, displaced_surface, collision_set,
2039 barrier_potential, barrier_stiffness, friction_coefficient);
2041 ipc::FrictionPotential friction_potential(epsv);
2043 Eigen::MatrixXd velocities;
2048 velocities = collision_mesh.map_displacements(
utils::unflatten(velocities, collision_mesh.dim()));
2050 Eigen::MatrixXd forces = -friction_potential.gradient(
2051 friction_collision_set, collision_mesh, velocities);
2055 assert(forces_reshaped.rows() == surface_displacements.rows());
2056 assert(forces_reshaped.cols() == surface_displacements.cols());
2057 writer.add_field(
"friction_forces", forces_reshaped);
2060 assert(collision_mesh.rest_positions().rows() == surface_displacements.rows());
2061 assert(collision_mesh.rest_positions().cols() == surface_displacements.cols());
2064 writer.add_field(
"solution", surface_displacements);
2067 export_surface.substr(0, export_surface.length() - 4) +
"_contact.vtu",
2068 collision_mesh.rest_positions(),
2069 problem_dim == 3 ? collision_mesh.faces() : collision_mesh.edges());
2074 const std::string &name,
2076 const Eigen::MatrixXd &sol,
2079 std::vector<SolutionFrame> &solution_frames)
const
2081 const std::vector<basis::ElementBases> &gbases = state.
geom_bases();
2089 Eigen::MatrixXi vis_faces_poly, vis_edges_poly;
2090 Eigen::MatrixXd vis_pts_poly;
2092 const auto ¤t_bases = gbases;
2093 int seg_total_size = 0;
2094 int pts_total_size = 0;
2095 int faces_total_size = 0;
2097 for (
size_t i = 0; i < current_bases.size(); ++i)
2099 const auto &bs = current_bases[i];
2104 seg_total_size += sampler.simplex_edges().rows();
2105 faces_total_size += sampler.simplex_faces().rows();
2109 pts_total_size += sampler.cube_points().rows();
2110 seg_total_size += sampler.cube_edges().rows();
2111 faces_total_size += sampler.cube_faces().rows();
2116 sampler.sample_polyhedron(state.
polys_3d.at(i).first, state.
polys_3d.at(i).second, vis_pts_poly, vis_faces_poly, vis_edges_poly);
2118 sampler.sample_polygon(state.
polys.at(i), vis_pts_poly, vis_faces_poly, vis_edges_poly);
2120 pts_total_size += vis_pts_poly.rows();
2121 seg_total_size += vis_edges_poly.rows();
2122 faces_total_size += vis_faces_poly.rows();
2126 Eigen::MatrixXd points(pts_total_size, mesh.
dimension());
2127 Eigen::MatrixXi edges(seg_total_size, 2);
2128 Eigen::MatrixXi
faces(faces_total_size, 3);
2131 Eigen::MatrixXd mapped, tmp;
2132 int seg_index = 0, pts_index = 0, face_index = 0;
2133 for (
size_t i = 0; i < current_bases.size(); ++i)
2135 const auto &bs = current_bases[i];
2139 bs.eval_geom_mapping(sampler.simplex_points(), mapped);
2140 edges.block(seg_index, 0, sampler.simplex_edges().rows(), edges.cols()) = sampler.simplex_edges().array() + pts_index;
2141 seg_index += sampler.simplex_edges().rows();
2143 faces.block(face_index, 0, sampler.simplex_faces().rows(), 3) = sampler.simplex_faces().array() + pts_index;
2144 face_index += sampler.simplex_faces().rows();
2146 points.block(pts_index, 0, mapped.rows(), points.cols()) = mapped;
2147 pts_index += mapped.rows();
2151 bs.eval_geom_mapping(sampler.cube_points(), mapped);
2152 edges.block(seg_index, 0, sampler.cube_edges().rows(), edges.cols()) = sampler.cube_edges().array() + pts_index;
2153 seg_index += sampler.cube_edges().rows();
2155 faces.block(face_index, 0, sampler.cube_faces().rows(), 3) = sampler.cube_faces().array() + pts_index;
2156 face_index += sampler.cube_faces().rows();
2158 points.block(pts_index, 0, mapped.rows(), points.cols()) = mapped;
2159 pts_index += mapped.rows();
2164 sampler.sample_polyhedron(state.
polys_3d.at(i).first, state.
polys_3d.at(i).second, vis_pts_poly, vis_faces_poly, vis_edges_poly);
2166 sampler.sample_polygon(state.
polys.at(i), vis_pts_poly, vis_faces_poly, vis_edges_poly);
2168 edges.block(seg_index, 0, vis_edges_poly.rows(), edges.cols()) = vis_edges_poly.array() + pts_index;
2169 seg_index += vis_edges_poly.rows();
2171 faces.block(face_index, 0, vis_faces_poly.rows(), 3) = vis_faces_poly.array() + pts_index;
2172 face_index += vis_faces_poly.rows();
2174 points.block(pts_index, 0, vis_pts_poly.rows(), points.cols()) = vis_pts_poly;
2175 pts_index += vis_pts_poly.rows();
2179 assert(pts_index == points.rows());
2180 assert(face_index ==
faces.rows());
2185 for (
long i = 0; i <
faces.rows(); ++i)
2187 const int v0 =
faces(i, 0);
2188 const int v1 =
faces(i, 1);
2189 const int v2 =
faces(i, 2);
2191 int tmpc =
faces(i, 2);
2198 Eigen::Matrix2d mmat;
2199 for (
long i = 0; i <
faces.rows(); ++i)
2201 const int v0 =
faces(i, 0);
2202 const int v1 =
faces(i, 1);
2203 const int v2 =
faces(i, 2);
2205 mmat.row(0) = points.row(v2) - points.row(v0);
2206 mmat.row(1) = points.row(v1) - points.row(v0);
2208 if (mmat.determinant() > 0)
2210 int tmpc =
faces(i, 2);
2217 Eigen::MatrixXd fun;
2221 pts_index, sol, fun,
true,
false);
2223 Eigen::MatrixXd exact_fun, err;
2227 problem.
exact(points, t, exact_fun);
2228 err = (fun - exact_fun).eval().rowwise().norm();
2231 std::shared_ptr<paraviewo::ParaviewWriter> tmpw;
2233 tmpw = std::make_shared<paraviewo::HDF5VTUWriter>();
2235 tmpw = std::make_shared<paraviewo::VTUWriter>();
2236 paraviewo::ParaviewWriter &writer = *tmpw;
2240 writer.add_field(
"exact", exact_fun);
2241 writer.add_field(
"error", err);
2244 if (fun.cols() != 1)
2246 std::vector<assembler::Assembler::NamedMatrix> scalar_val;
2252 for (
const auto &v : scalar_val)
2253 writer.add_field(v.first, v.second);
2256 writer.add_field(
"solution", fun);
2258 writer.write_mesh(name, points, edges);
2262 const std::string &path,
2264 const Eigen::MatrixXd &sol,
2266 std::vector<SolutionFrame> &solution_frames)
const
2277 Eigen::MatrixXd fun(dirichlet_nodes_position.size(), actual_dim);
2278 Eigen::MatrixXd b_sidesets(dirichlet_nodes_position.size(), 1);
2279 b_sidesets.setZero();
2280 Eigen::MatrixXd points(dirichlet_nodes_position.size(), mesh.
dimension());
2281 std::vector<std::vector<int>> cells(dirichlet_nodes_position.size());
2283 for (
int i = 0; i < dirichlet_nodes_position.size(); ++i)
2285 const int n_id = dirichlet_nodes[i];
2289 b_sidesets(i) = s_id;
2292 for (
int j = 0; j < actual_dim; ++j)
2294 fun(i, j) = sol(n_id * actual_dim + j);
2297 points.row(i) = dirichlet_nodes_position[i];
2298 cells[i].push_back(i);
2301 std::shared_ptr<paraviewo::ParaviewWriter> tmpw;
2303 tmpw = std::make_shared<paraviewo::HDF5VTUWriter>();
2305 tmpw = std::make_shared<paraviewo::VTUWriter>();
2306 paraviewo::ParaviewWriter &writer = *tmpw;
2310 writer.add_field(
"sidesets", b_sidesets);
2312 writer.add_field(
"solution", fun);
2313 writer.write_mesh(path, points, cells,
false,
false);
2318 const std::string &name,
2319 const std::function<std::string(
int)> &vtu_names,
2320 int time_steps,
double t0,
double dt,
int skip_frame)
const
2322 paraviewo::PVDWriter::save_pvd(name, vtu_names, time_steps, t0, dt, skip_frame);
2338 const int nx = delta[0] / spacing + 1;
2339 const int ny = delta[1] / spacing + 1;
2340 const int nz = delta.cols() >= 3 ? (delta[2] / spacing + 1) : 1;
2341 const int n = nx * ny * nz;
2345 for (
int i = 0; i < nx; ++i)
2347 const double x = (delta[0] / (nx - 1)) * i + min[0];
2349 for (
int j = 0; j < ny; ++j)
2351 const double y = (delta[1] / (ny - 1)) * j + min[1];
2353 if (delta.cols() <= 2)
2359 for (
int k = 0; k < nz; ++k)
2361 const double z = (delta[2] / (nz - 1)) * k + min[2];
2370 std::vector<std::array<Eigen::Vector3d, 2>> boxes;
2376 const double eps = 1e-6;
2385 const Eigen::Vector3d min(
2390 const Eigen::Vector3d max(
2395 std::vector<unsigned int> candidates;
2397 bvh.intersect_box(min, max, candidates);
2399 for (
const auto cand : candidates)
2403 logger().warn(
"Element {} is not simplex, skipping", cand);
2407 Eigen::MatrixXd coords;
2410 for (
int d = 0; d < coords.size(); ++d)
2412 if (fabs(coords(d)) < 1e-8)
2414 else if (fabs(coords(d) - 1) < 1e-8)
2418 if (coords.array().minCoeff() >= 0 && coords.array().maxCoeff() <= 1)
2430 Eigen::MatrixXd samples_simplex, samples_cube, mapped, p0, p1, p;
2433 average_edge_length = 0;
2434 min_edge_length = std::numeric_limits<double>::max();
2436 if (!use_curved_mesh_size)
2440 min_edge_length = p.rowwise().norm().minCoeff();
2441 average_edge_length = p.rowwise().norm().mean();
2442 mesh_size = p.rowwise().norm().maxCoeff();
2444 logger().info(
"hmin: {}", min_edge_length);
2445 logger().info(
"hmax: {}", mesh_size);
2446 logger().info(
"havg: {}", average_edge_length);
2463 for (
size_t i = 0; i < bases_in.size(); ++i)
2472 bases_in[i].eval_geom_mapping(samples_simplex, mapped);
2477 bases_in[i].eval_geom_mapping(samples_cube, mapped);
2480 for (
int j = 0; j < n_edges; ++j)
2482 double current_edge = 0;
2483 for (
int k = 0; k < n_samples - 1; ++k)
2485 p0 = mapped.row(j * n_samples + k);
2486 p1 = mapped.row(j * n_samples + k + 1);
2489 current_edge += p.norm();
2492 mesh_size = std::max(current_edge, mesh_size);
2493 min_edge_length = std::min(current_edge, min_edge_length);
2494 average_edge_length += current_edge;
2499 average_edge_length /= n;
2501 logger().info(
"hmin: {}", min_edge_length);
2502 logger().info(
"hmax: {}", mesh_size);
2503 logger().info(
"havg: {}", average_edge_length);
2517 using namespace mesh;
2519 logger().info(
"Counting flipped elements...");
2523 for (
size_t i = 0; i < gbases.size(); ++i)
2529 if (!
vals.is_geom_mapping_positive(mesh.
is_volume(), gbases[i]))
2533 static const std::vector<std::string> element_type_names{{
2535 "RegularInteriorCube",
2536 "RegularBoundaryCube",
2537 "SimpleSingularInteriorCube",
2538 "MultiSingularInteriorCube",
2539 "SimpleSingularBoundaryCube",
2541 "MultiSingularBoundaryCube",
2547 log_and_throw_error(
"element {} is flipped, type {}", i, element_type_names[
static_cast<int>(els_tag[i])]);
2562 const std::vector<polyfem::basis::ElementBases> &bases,
2563 const std::vector<polyfem::basis::ElementBases> &gbases,
2567 const Eigen::MatrixXd &sol)
2571 logger().error(
"Build the bases first!");
2574 if (sol.size() <= 0)
2576 logger().error(
"Solve the problem first!");
2586 logger().info(
"Computing errors...");
2589 const int n_el = int(bases.size());
2591 Eigen::MatrixXd v_exact, v_approx;
2592 Eigen::MatrixXd v_exact_grad(0, 0), v_approx_grad;
2602 static const int p = 8;
2607 for (
int e = 0; e < n_el; ++e)
2617 v_approx.resize(
vals.val.rows(), actual_dim);
2620 v_approx_grad.resize(
vals.val.rows(), mesh.
dimension() * actual_dim);
2621 v_approx_grad.setZero();
2623 const int n_loc_bases = int(
vals.basis_values.size());
2625 for (
int i = 0; i < n_loc_bases; ++i)
2627 const auto &
val =
vals.basis_values[i];
2629 for (
size_t ii = 0; ii <
val.global.size(); ++ii)
2631 for (
int d = 0; d < actual_dim; ++d)
2633 v_approx.col(d) +=
val.global[ii].val * sol(
val.global[ii].index * actual_dim + d) *
val.val;
2634 v_approx_grad.block(0, d *
val.grad_t_m.cols(), v_approx_grad.rows(),
val.grad_t_m.cols()) +=
val.global[ii].val * sol(
val.global[ii].index * actual_dim + d) *
val.grad_t_m;
2639 const auto err = problem.
has_exact_sol() ? (v_exact - v_approx).eval().rowwise().norm().eval() : (v_approx).eval().rowwise().norm().eval();
2640 const auto err_grad = problem.
has_exact_sol() ? (v_exact_grad - v_approx_grad).eval().rowwise().norm().eval() : (v_approx_grad).eval().rowwise().norm().eval();
2645 linf_err = std::max(linf_err, err.maxCoeff());
2646 grad_max_err = std::max(linf_err, err_grad.maxCoeff());
2688 l2_err += (err.array() * err.array() *
vals.det.array() *
vals.quadrature.weights.array()).sum();
2689 h1_err += (err_grad.array() * err_grad.array() *
vals.det.array() *
vals.quadrature.weights.array()).sum();
2690 lp_err += (err.array().pow(p) *
vals.det.array() *
vals.quadrature.weights.array()).sum();
2693 h1_semi_err = sqrt(fabs(h1_err));
2694 h1_err = sqrt(fabs(l2_err) + fabs(h1_err));
2695 l2_err = sqrt(fabs(l2_err));
2697 lp_err = pow(fabs(lp_err), 1. / p);
2702 const double computing_errors_time = timer.getElapsedTime();
2703 logger().info(
" took {}s", computing_errors_time);
2705 logger().info(
"-- L2 error: {}", l2_err);
2706 logger().info(
"-- Lp error: {}", lp_err);
2707 logger().info(
"-- H1 error: {}", h1_err);
2708 logger().info(
"-- H1 semi error: {}", h1_semi_err);
2711 logger().info(
"-- Linf error: {}", linf_err);
2712 logger().info(
"-- grad max error: {}", grad_max_err);
2727 regular_boundary_count = 0;
2728 simple_singular_count = 0;
2729 multi_singular_count = 0;
2731 non_regular_boundary_count = 0;
2732 non_regular_count = 0;
2733 undefined_count = 0;
2734 multi_singular_boundary_count = 0;
2738 for (
size_t i = 0; i < els_tag.size(); ++i)
2744 case ElementType::SIMPLEX:
2747 case ElementType::REGULAR_INTERIOR_CUBE:
2750 case ElementType::REGULAR_BOUNDARY_CUBE:
2751 regular_boundary_count++;
2753 case ElementType::SIMPLE_SINGULAR_INTERIOR_CUBE:
2754 simple_singular_count++;
2756 case ElementType::MULTI_SINGULAR_INTERIOR_CUBE:
2757 multi_singular_count++;
2759 case ElementType::SIMPLE_SINGULAR_BOUNDARY_CUBE:
2762 case ElementType::INTERFACE_CUBE:
2763 case ElementType::MULTI_SINGULAR_BOUNDARY_CUBE:
2764 multi_singular_boundary_count++;
2766 case ElementType::BOUNDARY_POLYTOPE:
2767 non_regular_boundary_count++;
2769 case ElementType::INTERIOR_POLYTOPE:
2770 non_regular_count++;
2772 case ElementType::UNDEFINED:
2776 throw std::runtime_error(
"Unknown element type");
2780 logger().info(
"simplex_count: \t{}", simplex_count);
2781 logger().info(
"regular_count: \t{}", regular_count);
2782 logger().info(
"regular_boundary_count: \t{}", regular_boundary_count);
2783 logger().info(
"simple_singular_count: \t{}", simple_singular_count);
2784 logger().info(
"multi_singular_count: \t{}", multi_singular_count);
2785 logger().info(
"boundary_count: \t{}", boundary_count);
2786 logger().info(
"multi_singular_boundary_count: \t{}", multi_singular_boundary_count);
2787 logger().info(
"non_regular_count: \t{}", non_regular_count);
2788 logger().info(
"non_regular_boundary_count: \t{}", non_regular_boundary_count);
2789 logger().info(
"undefined_count: \t{}", undefined_count);
2794 const nlohmann::json &args,
2795 const int n_bases,
const int n_pressure_bases,
2796 const Eigen::MatrixXd &sol,
2798 const Eigen::VectorXi &disc_orders,
2801 const std::string &formulation,
2802 const bool isoparametric,
2803 const int sol_at_node_id,
2809 j[
"geom_order"] = mesh.
orders().size() > 0 ? mesh.
orders().maxCoeff() : 1;
2810 j[
"geom_order_min"] = mesh.
orders().size() > 0 ? mesh.
orders().minCoeff() : 1;
2811 j[
"discr_order_min"] = disc_orders.minCoeff();
2812 j[
"discr_order_max"] = disc_orders.maxCoeff();
2813 j[
"iso_parametric"] = isoparametric;
2814 j[
"problem"] = problem.
name();
2815 j[
"mat_size"] = mat_size;
2816 j[
"num_bases"] = n_bases;
2817 j[
"num_pressure_bases"] = n_pressure_bases;
2818 j[
"num_non_zero"] = nn_zero;
2819 j[
"num_flipped"] = n_flipped;
2820 j[
"num_dofs"] = num_dofs;
2824 j[
"num_p1"] = (disc_orders.array() == 1).count();
2825 j[
"num_p2"] = (disc_orders.array() == 2).count();
2826 j[
"num_p3"] = (disc_orders.array() == 3).count();
2827 j[
"num_p4"] = (disc_orders.array() == 4).count();
2828 j[
"num_p5"] = (disc_orders.array() == 5).count();
2830 j[
"mesh_size"] = mesh_size;
2831 j[
"max_angle"] = max_angle;
2833 j[
"sigma_max"] = sigma_max;
2834 j[
"sigma_min"] = sigma_min;
2835 j[
"sigma_avg"] = sigma_avg;
2837 j[
"min_edge_length"] = min_edge_length;
2838 j[
"average_edge_length"] = average_edge_length;
2840 j[
"err_l2"] = l2_err;
2841 j[
"err_h1"] = h1_err;
2842 j[
"err_h1_semi"] = h1_semi_err;
2843 j[
"err_linf"] = linf_err;
2844 j[
"err_linf_grad"] = grad_max_err;
2845 j[
"err_lp"] = lp_err;
2847 j[
"spectrum"] = {spectrum(0), spectrum(1), spectrum(2), spectrum(3)};
2848 j[
"spectrum_condest"] = std::abs(spectrum(3)) / std::abs(spectrum(0));
2861 j[
"solver_info"] = solver_info;
2863 j[
"count_simplex"] = simplex_count;
2864 j[
"count_regular"] = regular_count;
2865 j[
"count_regular_boundary"] = regular_boundary_count;
2866 j[
"count_simple_singular"] = simple_singular_count;
2867 j[
"count_multi_singular"] = multi_singular_count;
2868 j[
"count_boundary"] = boundary_count;
2869 j[
"count_non_regular_boundary"] = non_regular_boundary_count;
2870 j[
"count_non_regular"] = non_regular_count;
2871 j[
"count_undefined"] = undefined_count;
2872 j[
"count_multi_singular_boundary"] = multi_singular_boundary_count;
2874 j[
"is_simplicial"] = mesh.
n_elements() == simplex_count;
2876 j[
"peak_memory"] =
getPeakRSS() / (1024 * 1024);
2880 std::vector<double> mmin(actual_dim);
2881 std::vector<double> mmax(actual_dim);
2883 for (
int d = 0; d < actual_dim; ++d)
2885 mmin[d] = std::numeric_limits<double>::max();
2886 mmax[d] = -std::numeric_limits<double>::max();
2889 for (
int i = 0; i < sol.size(); i += actual_dim)
2891 for (
int d = 0; d < actual_dim; ++d)
2893 mmin[d] = std::min(mmin[d], sol(i + d));
2894 mmax[d] = std::max(mmax[d], sol(i + d));
2898 std::vector<double> sol_at_node(actual_dim);
2900 if (sol_at_node_id >= 0)
2902 const int node_id = sol_at_node_id;
2904 for (
int d = 0; d < actual_dim; ++d)
2906 sol_at_node[d] = sol(node_id * actual_dim + d);
2910 j[
"sol_at_node"] = sol_at_node;
2911 j[
"sol_min"] = mmin;
2912 j[
"sol_max"] = mmax;
2914#if defined(POLYFEM_WITH_CPP_THREADS)
2916#elif defined(POLYFEM_WITH_TBB)
2919 j[
"num_threads"] = 1;
2922 j[
"formulation"] = formulation;
2928 : file(path), solve_data(solve_data)
2933 file << name <<
",";
2935 file <<
"total_energy" << std::endl;
2952 file << ((form && form->enabled()) ? form->value(sol) : 0) / s <<
",";
2959 : file(path), state(state), t0(t0), dt(dt)
2961 file <<
"step,time,forward,remeshing,global_relaxation,peak_mem,#V,#T" << std::endl;
2985 const double peak_mem =
getPeakRSS() / double(1 << 30);
2988 file << fmt::format(
2989 "{},{},{},{},{},{},{},{}\n",
2990 t,
t0 +
dt * t, forward, remeshing, global_relaxation, peak_mem,
ElementAssemblyValues vals
std::vector< Eigen::VectorXi > faces
main class that contains the polyfem solver and all its state
int n_bases
number of bases
assembler::AssemblyValsCache ass_vals_cache
used to store assembly values for small problems
const std::vector< basis::ElementBases > & geom_bases() const
Get a constant reference to the geometry mapping bases.
Eigen::VectorXi in_node_to_node
Inpute nodes (including high-order) to polyfem nodes, only for isoparametric.
mesh::Obstacle obstacle
Obstacles used in collisions.
std::shared_ptr< assembler::Assembler > assembler
assemblers
ipc::CollisionMesh collision_mesh
IPC collision mesh.
std::vector< basis::ElementBases > pressure_bases
FE pressure bases for mixed elements, the size is #elements.
std::shared_ptr< assembler::Mass > mass_matrix_assembler
std::unique_ptr< mesh::Mesh > mesh
current mesh, it can be a Mesh2D or Mesh3D
std::vector< int > dirichlet_nodes
per node dirichlet
std::shared_ptr< assembler::Problem > problem
current problem, it contains rhs and bc
std::vector< RowVectorNd > dirichlet_nodes_position
std::map< int, std::pair< Eigen::MatrixXd, Eigen::MatrixXi > > polys_3d
polyhedra, used since poly have no geom mapping
json args
main input arguments containing all defaults
std::vector< basis::ElementBases > bases
FE bases, the size is #elements.
std::vector< mesh::LocalBoundary > total_local_boundary
mapping from elements to nodes for all mesh
solver::SolveData solve_data
timedependent stuff cached
Eigen::VectorXi disc_orders
vector of discretization orders, used when not all elements have the same degree, one per element
std::shared_ptr< assembler::MixedAssembler > mixed_assembler
std::map< int, Eigen::MatrixXd > polys
polygons, used since poly have no geom mapping
Eigen::MatrixXd rhs
System right-hand side.
virtual std::map< std::string, ParamFunc > parameters() const =0
virtual void compute_tensor_value(const OutputData &data, std::vector< NamedMatrix > &result) const
stores per local bases evaluations
std::vector< basis::Local2Global > global
stores per element basis values at given quadrature points and geometric mapping
std::vector< AssemblyValues > basis_values
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,...
std::vector< Eigen::Matrix< double, Eigen::Dynamic, Eigen::Dynamic, 0, 3, 3 > > jac_it
const std::string & name() const
virtual void exact_grad(const Eigen::MatrixXd &pts, const double t, Eigen::MatrixXd &val) const
virtual bool is_scalar() const =0
virtual bool has_exact_sol() const =0
virtual void exact(const Eigen::MatrixXd &pts, const double t, Eigen::MatrixXd &val) const
virtual bool is_time_dependent() const
Represents one basis function and its gradient.
const std::vector< Local2Global > & global() const
Stores the basis functions for a given element in a mesh (facet in 2d, cell in 3d).
Eigen::VectorXi local_nodes_for_primitive(const int local_index, const mesh::Mesh &mesh) const
std::vector< Basis > bases
one basis function per node in the element
EnergyCSVWriter(const std::string &path, const solver::SolveData &solve_data)
const solver::SolveData & solve_data
void write(const int i, const Eigen::MatrixXd &sol)
static void interpolate_at_local_vals(const mesh::Mesh &mesh, const bool is_problem_scalar, const std::vector< basis::ElementBases > &bases, const std::vector< basis::ElementBases > &gbases, const int el_index, const Eigen::MatrixXd &local_pts, const Eigen::MatrixXd &fun, Eigen::MatrixXd &result, Eigen::MatrixXd &result_grad)
interpolate solution and gradient at element (calls interpolate_at_local_vals with sol)
static void compute_stress_at_quadrature_points(const mesh::Mesh &mesh, const bool is_problem_scalar, const std::vector< basis::ElementBases > &bases, const std::vector< basis::ElementBases > &gbases, const Eigen::VectorXi &disc_orders, const assembler::Assembler &assembler, const Eigen::MatrixXd &fun, const double t, Eigen::MatrixXd &result, Eigen::VectorXd &von_mises)
compute von mises stress at quadrature points for the function fun, also compute the interpolated fun...
static void mark_flipped_cells(const mesh::Mesh &mesh, const std::vector< basis::ElementBases > &gbasis, const std::vector< basis::ElementBases > &basis, const Eigen::VectorXi &disc_orders, const std::map< int, Eigen::MatrixXd > &polys, const std::map< int, std::pair< Eigen::MatrixXd, Eigen::MatrixXi > > &polys_3d, const utils::RefElementSampler &sampler, const int n_points, const Eigen::MatrixXd &fun, Eigen::Vector< bool, -1 > &result, const bool use_sampler, const bool boundary_only)
static void interpolate_function(const mesh::Mesh &mesh, const bool is_problem_scalar, const std::vector< basis::ElementBases > &bases, const Eigen::VectorXi &disc_orders, const std::map< int, Eigen::MatrixXd > &polys, const std::map< int, std::pair< Eigen::MatrixXd, Eigen::MatrixXi > > &polys_3d, const utils::RefElementSampler &sampler, const int n_points, const Eigen::MatrixXd &fun, Eigen::MatrixXd &result, const bool use_sampler, const bool boundary_only)
interpolate the function fun.
static void average_grad_based_function(const mesh::Mesh &mesh, const bool is_problem_scalar, const int n_bases, const std::vector< basis::ElementBases > &bases, const std::vector< basis::ElementBases > &gbases, const Eigen::VectorXi &disc_orders, const std::map< int, Eigen::MatrixXd > &polys, const std::map< int, std::pair< Eigen::MatrixXd, Eigen::MatrixXi > > &polys_3d, const assembler::Assembler &assembler, const utils::RefElementSampler &sampler, const double t, const int n_points, const Eigen::MatrixXd &fun, std::vector< assembler::Assembler::NamedMatrix > &result_scalar, std::vector< assembler::Assembler::NamedMatrix > &result_tensor, const bool use_sampler, const bool boundary_only)
computes scalar quantity of funtion (ie von mises for elasticity and norm of velocity for fluid) the ...
static void compute_scalar_value(const mesh::Mesh &mesh, const bool is_problem_scalar, const std::vector< basis::ElementBases > &bases, const std::vector< basis::ElementBases > &gbases, const Eigen::VectorXi &disc_orders, const std::map< int, Eigen::MatrixXd > &polys, const std::map< int, std::pair< Eigen::MatrixXd, Eigen::MatrixXi > > &polys_3d, const assembler::Assembler &assembler, const utils::RefElementSampler &sampler, const int n_points, const Eigen::MatrixXd &fun, const double t, std::vector< assembler::Assembler::NamedMatrix > &result, const bool use_sampler, const bool boundary_only)
computes scalar quantity of funtion (ie von mises for elasticity and norm of velocity for fluid)
static void compute_tensor_value(const mesh::Mesh &mesh, const bool is_problem_scalar, const std::vector< basis::ElementBases > &bases, const std::vector< basis::ElementBases > &gbases, const Eigen::VectorXi &disc_orders, const std::map< int, Eigen::MatrixXd > &polys, const std::map< int, std::pair< Eigen::MatrixXd, Eigen::MatrixXi > > &polys_3d, const assembler::Assembler &assembler, const utils::RefElementSampler &sampler, const int n_points, const Eigen::MatrixXd &fun, const double t, std::vector< assembler::Assembler::NamedMatrix > &result, const bool use_sampler, const bool boundary_only)
compute tensor quantity (ie stress tensor or velocy)
void build_vis_mesh(const mesh::Mesh &mesh, const Eigen::VectorXi &disc_orders, const std::vector< basis::ElementBases > &gbases, const std::map< int, Eigen::MatrixXd > &polys, const std::map< int, std::pair< Eigen::MatrixXd, Eigen::MatrixXi > > &polys_3d, const bool boundary_only, Eigen::MatrixXd &points, Eigen::MatrixXi &tets, Eigen::MatrixXi &el_id, Eigen::MatrixXd &discr) const
builds visualzation mesh, upsampled mesh used for visualization the visualization mesh is a dense mes...
void build_high_order_vis_mesh(const mesh::Mesh &mesh, const Eigen::VectorXi &disc_orders, const std::vector< basis::ElementBases > &bases, Eigen::MatrixXd &points, std::vector< std::vector< int > > &elements, Eigen::MatrixXi &el_id, Eigen::MatrixXd &discr) const
builds high-der visualzation mesh per element all disconnected it also retuns the mapping to element ...
void save_points(const std::string &path, const State &state, const Eigen::MatrixXd &sol, const ExportOptions &opts, std::vector< SolutionFrame > &solution_frames) const
saves the nodal values
void save_volume_vector_field(const State &state, const Eigen::MatrixXd &points, const ExportOptions &opts, const std::string &name, const Eigen::VectorXd &field, paraviewo::ParaviewWriter &writer) const
Eigen::MatrixXd grid_points_bc
grid mesh boundaries
Eigen::MatrixXd grid_points
grid mesh points to export solution sampled on a grid
void save_wire(const std::string &name, const State &state, const Eigen::MatrixXd &sol, const double t, const ExportOptions &opts, std::vector< SolutionFrame > &solution_frames) const
saves the wireframe
void save_surface(const std::string &export_surface, const State &state, const Eigen::MatrixXd &sol, const Eigen::MatrixXd &pressure, const double t, const double dt_in, const ExportOptions &opts, const bool is_contact_enabled, std::vector< SolutionFrame > &solution_frames) const
saves the surface vtu file for for surface quantites, eg traction forces
void build_vis_boundary_mesh(const mesh::Mesh &mesh, const std::vector< basis::ElementBases > &bases, const std::vector< basis::ElementBases > &gbases, const std::vector< mesh::LocalBoundary > &total_local_boundary, const Eigen::MatrixXd &solution, const int problem_dim, Eigen::MatrixXd &boundary_vis_vertices, Eigen::MatrixXd &boundary_vis_local_vertices, Eigen::MatrixXi &boundary_vis_elements, Eigen::MatrixXi &boundary_vis_elements_ids, Eigen::MatrixXi &boundary_vis_primitive_ids, Eigen::MatrixXd &boundary_vis_normals, Eigen::MatrixXd &displaced_boundary_vis_normals) const
builds the boundary mesh for visualization
void build_grid(const polyfem::mesh::Mesh &mesh, const double spacing)
builds the grid to export the solution
void save_volume(const std::string &path, const State &state, const Eigen::MatrixXd &sol, const Eigen::MatrixXd &pressure, const double t, const double dt, const ExportOptions &opts, std::vector< SolutionFrame > &solution_frames) const
saves the volume vtu file
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
void save_pvd(const std::string &name, const std::function< std::string(int)> &vtu_names, int time_steps, double t0, double dt, int skip_frame=1) const
save a PVD of a time dependent simulation
void export_data(const State &state, const Eigen::MatrixXd &sol, const Eigen::MatrixXd &pressure, const bool is_time_dependent, const double tend_in, const double dt, const ExportOptions &opts, const std::string &vis_mesh_path, const std::string &nodes_path, const std::string &solution_path, const std::string &stress_path, const std::string &mises_path, const bool is_contact_enabled, std::vector< SolutionFrame > &solution_frames) const
exports everytihng, txt, vtu, etc
void save_vtu(const std::string &path, const State &state, const Eigen::MatrixXd &sol, const Eigen::MatrixXd &pressure, const double t, const double dt, const ExportOptions &opts, const bool is_contact_enabled, std::vector< SolutionFrame > &solution_frames) const
saves the vtu file for time t
void save_contact_surface(const std::string &export_surface, const State &state, const Eigen::MatrixXd &sol, const Eigen::MatrixXd &pressure, const double t, const double dt_in, const ExportOptions &opts, const bool is_contact_enabled, std::vector< SolutionFrame > &solution_frames) const
saves the surface vtu file for for constact quantites, eg contact or friction forces
void init_sampler(const polyfem::mesh::Mesh &mesh, const double vismesh_rel_area)
unitalize the ref element sampler
Eigen::MatrixXi grid_points_to_elements
grid mesh mapping to fe elements
utils::RefElementSampler ref_element_sampler
used to sample the solution
double loading_mesh_time
time to load the mesh
double assembling_stiffness_mat_time
time to assembly
double assigning_rhs_time
time to computing the rhs
double assembling_mass_mat_time
time to assembly mass
double building_basis_time
time to construct the basis
double solving_time
time to solve
double computing_poly_basis_time
time to build the polygonal/polyhedral bases
void save_json(const nlohmann::json &args, const int n_bases, const int n_pressure_bases, const Eigen::MatrixXd &sol, const mesh::Mesh &mesh, const Eigen::VectorXi &disc_orders, const assembler::Problem &problem, const OutRuntimeData &runtime, const std::string &formulation, const bool isoparametric, const int sol_at_node_id, nlohmann::json &j)
saves the output statistic to a json object
void count_flipped_elements(const polyfem::mesh::Mesh &mesh, const std::vector< polyfem::basis::ElementBases > &gbases)
counts the number of flipped elements
void compute_errors(const int n_bases, const std::vector< polyfem::basis::ElementBases > &bases, const std::vector< polyfem::basis::ElementBases > &gbases, const polyfem::mesh::Mesh &mesh, const assembler::Problem &problem, const double tend, const Eigen::MatrixXd &sol)
compute errors
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...
void reset()
clears all stats
void compute_mesh_stats(const polyfem::mesh::Mesh &mesh)
compute stats (counts els type, mesh lenght, etc), step 1 of solve
double total_forward_solve_time
void write(const int t, const double forward, const double remeshing, const double global_relaxation, const Eigen::MatrixXd &sol)
double total_remeshing_time
RuntimeStatsCSVWriter(const std::string &path, const State &state, const double t0, const double dt)
double total_global_relaxation_time
Boundary primitive IDs for a single element.
Abstract mesh class to capture 2d/3d conforming and non-conforming meshes.
int n_elements() const
utitlity to return the number of elements, cells or faces in 3d and 2d
virtual int n_vertices() const =0
number of vertices
virtual int get_body_id(const int primitive) const
Get the volume selection of an element (cell in 3d, face in 2d)
virtual double edge_length(const int gid) const
edge length
bool is_polytope(const int el_id) const
checks if element is polygon compatible
virtual void get_edges(Eigen::MatrixXd &p0, Eigen::MatrixXd &p1) const =0
Get all the edges.
virtual double tri_area(const int gid) const
area of a tri face of a tet mesh
bool is_simplicial() const
checks if the mesh is simplicial
virtual bool is_conforming() const =0
if the mesh is conforming
virtual void bounding_box(RowVectorNd &min, RowVectorNd &max) const =0
computes the bbox of the mesh
virtual void barycentric_coords(const RowVectorNd &p, const int el_id, Eigen::MatrixXd &coord) const =0
constructs barycentric coodiantes for a point p.
bool is_cube(const int el_id) const
checks if element is cube compatible
const Eigen::MatrixXi & orders() const
order of each element
virtual int get_boundary_id(const int primitive) const
Get the boundary selection of an element (face in 3d, edge in 2d)
bool is_simplex(const int el_id) const
checks if element is simples compatible
virtual double quad_area(const int gid) const
area of a quad face of an hex mesh
bool is_linear() const
check if the mesh is linear
virtual bool is_volume() const =0
checks if mesh is volume
bool has_poly() const
checks if the mesh has polytopes
int dimension() const
utily for dimension
virtual int n_faces() const =0
number of faces
const std::vector< ElementType > & elements_tag() const
Returns the elements types.
virtual int n_face_vertices(const int f_id) const =0
number of vertices of a face
virtual void elements_boxes(std::vector< std::array< Eigen::Vector3d, 2 > > &boxes) const =0
constructs a box around every element (3d cell, 2d face)
virtual bool is_boundary_element(const int element_global_id) const =0
is cell boundary
virtual int get_node_id(const int node_id) const
Get the boundary selection of a node.
const Eigen::MatrixXi & get_edge_connectivity() const
const Eigen::MatrixXi & get_face_connectivity() const
const Eigen::MatrixXd & v() const
const Eigen::VectorXi & get_vertex_connectivity() const
class to store time stepping data
std::shared_ptr< solver::FrictionForm > friction_form
std::shared_ptr< solver::NLProblem > nl_problem
std::shared_ptr< solver::ContactForm > contact_form
std::vector< std::pair< std::string, std::shared_ptr< solver::Form > > > named_forms() const
std::shared_ptr< time_integrator::ImplicitTimeIntegrator > time_integrator
static void normal_for_quad_edge(int index, Eigen::MatrixXd &normal)
static void normal_for_tri_edge(int index, Eigen::MatrixXd &normal)
static void normal_for_quad_face(int index, Eigen::MatrixXd &normal)
static void sample_parametric_tri_face(int index, int n_samples, Eigen::MatrixXd &uv, Eigen::MatrixXd &samples)
static void normal_for_tri_face(int index, Eigen::MatrixXd &normal)
static void sample_parametric_quad_face(int index, int n_samples, Eigen::MatrixXd &uv, Eigen::MatrixXd &samples)
static void normal_for_polygon_edge(int face_id, int edge_id, const mesh::Mesh &mesh, Eigen::MatrixXd &normal)
static void sample_parametric_quad_edge(int index, int n_samples, Eigen::MatrixXd &uv, Eigen::MatrixXd &samples)
static void sample_polygon_edge(int face_id, int edge_id, int n_samples, const mesh::Mesh &mesh, Eigen::MatrixXd &uv, Eigen::MatrixXd &samples)
static bool boundary_quadrature(const mesh::LocalBoundary &local_boundary, const int order, const mesh::Mesh &mesh, const bool skip_computation, Eigen::MatrixXd &uv, Eigen::MatrixXd &points, Eigen::MatrixXd &normals, Eigen::VectorXd &weights, Eigen::VectorXi &global_primitive_ids)
static void sample_parametric_tri_edge(int index, int n_samples, Eigen::MatrixXd &uv, Eigen::MatrixXd &samples)
static void sample_3d_simplex(const int resolution, Eigen::MatrixXd &samples)
static void sample_3d_cube(const int resolution, Eigen::MatrixXd &samples)
static void sample_2d_cube(const int resolution, Eigen::MatrixXd &samples)
static void sample_2d_simplex(const int resolution, Eigen::MatrixXd &samples)
void init(const bool is_volume, const int n_elements, const double target_rel_area)
const Eigen::MatrixXd & simplex_points() const
const Eigen::MatrixXi & simplex_volume() const
size_t getPeakRSS(void)
Returns the peak (maximum so far) resident set size (physical memory use) measured in bytes,...
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)
ElementType
Type of Element, check [Poly-Spline Finite Element Method] for a complete description.
Eigen::MatrixXd unflatten(const Eigen::VectorXd &x, int dim)
Unflatten rowwises, so every dim elements in x become a row.
void append_rows_of_zeros(DstMat &dst, const size_t n_zero_rows)
spdlog::logger & logger()
Retrieves the current logger.
Eigen::Matrix< double, 1, Eigen::Dynamic, Eigen::RowMajor, 1, 3 > RowVectorNd
void log_and_throw_error(const std::string &msg)
std::string file_extension() const
return the extension of the output paraview files depending on use_hdf5
ExportOptions(const json &args, const bool is_mesh_linear, const bool is_problem_scalar, const bool solve_export_to_file)
initialize the flags based on the input args
bool discretization_order
bool solve_export_to_file