45#include <paraviewo/VTMWriter.hpp>
46#include <paraviewo/PVDWriter.hpp>
48#include <SimpleBVH/BVH.hpp>
50#include <igl/write_triangle_mesh.h>
52#include <igl/facet_adjacency_matrix.h>
53#include <igl/connected_components.h>
63 void compute_traction_forces(
const State &state,
const Eigen::MatrixXd &solution,
const double t, Eigen::MatrixXd &traction_forces,
bool skip_dirichlet =
true)
66 if (!state.problem->is_scalar())
67 actual_dim = state.mesh->dimension();
71 const std::vector<basis::ElementBases> &bases = state.bases;
72 const std::vector<basis::ElementBases> &gbases = state.geom_bases();
74 Eigen::MatrixXd uv, samples, gtmp, rhs_fun, deform_mat, trafo;
75 Eigen::VectorXi global_primitive_ids;
76 Eigen::MatrixXd
points, normals;
77 Eigen::VectorXd weights;
80 traction_forces.setZero(state.n_bases * actual_dim, 1);
82 for (
const auto &lb : state.total_local_boundary)
84 const int e = lb.element_id();
90 const basis::ElementBases &gbs = gbases[
e];
91 const basis::ElementBases &bs = bases[
e];
93 vals.
compute(e, state.mesh->is_volume(), points, bs, gbs);
95 for (
int n = 0; n < normals.rows(); ++n)
99 if (solution.size() > 0)
101 assert(actual_dim == 2 || actual_dim == 3);
102 deform_mat.resize(actual_dim, actual_dim);
103 deform_mat.setZero();
104 for (
const auto &b :
vals.basis_values)
106 for (
const auto &g : b.global)
108 for (
int d = 0; d < actual_dim; ++d)
110 deform_mat.row(d) += solution(
g.index * actual_dim + d) * b.grad.row(n);
118 normals.row(n) = normals.row(n) * trafo.inverse();
119 normals.row(n).normalize();
122 std::vector<assembler::Assembler::NamedMatrix> tensor_flat;
123 state.assembler->compute_tensor_value(assembler::OutputData(t, e, bs, gbs, points, solution), tensor_flat);
129 const int g_index = v.
global[0].index * actual_dim;
131 for (
int q = 0; q <
points.rows(); ++q)
134 assert(tensor_flat[0].first ==
"cauchy_stess");
135 assert(tensor_flat[0].second.row(q).size() == actual_dim * actual_dim);
137 Eigen::MatrixXd stress_tensor =
utils::unflatten(tensor_flat[0].second.row(q), actual_dim);
139 traction_forces.block(g_index, 0, actual_dim, 1) += stress_tensor * normals.row(q).transpose() * v.
val(q) * weights(q);
149 const std::vector<basis::ElementBases> &bases,
150 const std::vector<mesh::LocalBoundary> &total_local_boundary,
151 Eigen::MatrixXd &node_positions,
152 Eigen::MatrixXi &boundary_edges,
153 Eigen::MatrixXi &boundary_triangles,
154 std::vector<Eigen::Triplet<double>> &displacement_map_entries)
158 displacement_map_entries.clear();
164 logger().warn(
"Skipping as the mesh has polygons");
170 node_positions.resize(n_bases + (is_simplicial ? 0 : mesh.
n_faces()), 3);
171 node_positions.setZero();
172 const Mesh3D &mesh3d =
dynamic_cast<const Mesh3D &
>(mesh);
174 std::vector<std::tuple<int, int, int>> tris;
176 std::vector<bool> visited_node(n_bases,
false);
178 std::stringstream print_warning;
184 for (
int j = 0; j < lb.size(); ++j)
186 const int eid = lb.global_primitive_id(j);
187 const int lid = lb[j];
190 if (mesh.
is_cube(lb.element_id()))
192 assert(!is_simplicial);
194 std::vector<int> loc_nodes;
197 for (
long n = 0; n < nodes.size(); ++n)
199 auto &bs = b.
bases[nodes(n)];
200 const auto &glob = bs.global();
201 if (glob.size() != 1)
204 int gindex = glob.front().index;
205 node_positions.row(gindex) = glob.front().node;
206 bary += glob.front().node;
207 loc_nodes.push_back(gindex);
210 if (loc_nodes.size() != 4)
212 logger().trace(
"skipping element {} since it is not Q1", eid);
218 const int new_node = n_bases + eid;
219 node_positions.row(new_node) = bary;
220 tris.emplace_back(loc_nodes[1], loc_nodes[0], new_node);
221 tris.emplace_back(loc_nodes[2], loc_nodes[1], new_node);
222 tris.emplace_back(loc_nodes[3], loc_nodes[2], new_node);
223 tris.emplace_back(loc_nodes[0], loc_nodes[3], new_node);
225 for (
int q = 0; q < 4; ++q)
227 if (!visited_node[loc_nodes[q]])
228 displacement_map_entries.emplace_back(loc_nodes[q], loc_nodes[q], 1);
230 visited_node[loc_nodes[q]] =
true;
231 displacement_map_entries.emplace_back(new_node, loc_nodes[q], 0.25);
239 logger().trace(
"skipping element {} since it is not a simplex or hex", eid);
245 std::vector<int> loc_nodes;
247 bool is_follower =
false;
250 for (
long n = 0; n < nodes.size(); ++n)
252 auto &bs = b.
bases[nodes(n)];
253 const auto &glob = bs.global();
254 if (glob.size() != 1)
265 for (
long n = 0; n < nodes.size(); ++n)
268 const std::vector<basis::Local2Global> &glob = bs.
global();
269 if (glob.size() != 1)
272 int gindex = glob.front().index;
273 node_positions.row(gindex) = glob.front().node;
274 loc_nodes.push_back(gindex);
277 if (loc_nodes.size() == 3)
279 tris.emplace_back(loc_nodes[0], loc_nodes[1], loc_nodes[2]);
281 else if (loc_nodes.size() == 6)
283 tris.emplace_back(loc_nodes[0], loc_nodes[3], loc_nodes[5]);
284 tris.emplace_back(loc_nodes[3], loc_nodes[1], loc_nodes[4]);
285 tris.emplace_back(loc_nodes[4], loc_nodes[2], loc_nodes[5]);
286 tris.emplace_back(loc_nodes[3], loc_nodes[4], loc_nodes[5]);
288 else if (loc_nodes.size() == 10)
290 tris.emplace_back(loc_nodes[0], loc_nodes[3], loc_nodes[8]);
291 tris.emplace_back(loc_nodes[3], loc_nodes[4], loc_nodes[9]);
292 tris.emplace_back(loc_nodes[4], loc_nodes[1], loc_nodes[5]);
293 tris.emplace_back(loc_nodes[5], loc_nodes[6], loc_nodes[9]);
294 tris.emplace_back(loc_nodes[6], loc_nodes[2], loc_nodes[7]);
295 tris.emplace_back(loc_nodes[7], loc_nodes[8], loc_nodes[9]);
296 tris.emplace_back(loc_nodes[8], loc_nodes[3], loc_nodes[9]);
297 tris.emplace_back(loc_nodes[9], loc_nodes[4], loc_nodes[5]);
298 tris.emplace_back(loc_nodes[6], loc_nodes[7], loc_nodes[9]);
300 else if (loc_nodes.size() == 15)
302 tris.emplace_back(loc_nodes[0], loc_nodes[3], loc_nodes[11]);
303 tris.emplace_back(loc_nodes[3], loc_nodes[4], loc_nodes[12]);
304 tris.emplace_back(loc_nodes[3], loc_nodes[12], loc_nodes[11]);
305 tris.emplace_back(loc_nodes[12], loc_nodes[10], loc_nodes[11]);
306 tris.emplace_back(loc_nodes[4], loc_nodes[5], loc_nodes[13]);
307 tris.emplace_back(loc_nodes[4], loc_nodes[13], loc_nodes[12]);
308 tris.emplace_back(loc_nodes[12], loc_nodes[13], loc_nodes[14]);
309 tris.emplace_back(loc_nodes[12], loc_nodes[14], loc_nodes[10]);
310 tris.emplace_back(loc_nodes[14], loc_nodes[9], loc_nodes[10]);
311 tris.emplace_back(loc_nodes[5], loc_nodes[1], loc_nodes[6]);
312 tris.emplace_back(loc_nodes[5], loc_nodes[6], loc_nodes[13]);
313 tris.emplace_back(loc_nodes[6], loc_nodes[7], loc_nodes[13]);
314 tris.emplace_back(loc_nodes[13], loc_nodes[7], loc_nodes[14]);
315 tris.emplace_back(loc_nodes[7], loc_nodes[8], loc_nodes[14]);
316 tris.emplace_back(loc_nodes[14], loc_nodes[8], loc_nodes[9]);
317 tris.emplace_back(loc_nodes[8], loc_nodes[2], loc_nodes[9]);
321 print_warning << loc_nodes.size() <<
" ";
327 for (
int k = 0; k < loc_nodes.size(); ++k)
329 if (!visited_node[loc_nodes[k]])
330 displacement_map_entries.emplace_back(loc_nodes[k], loc_nodes[k], 1);
332 visited_node[loc_nodes[k]] =
true;
338 if (print_warning.str().size() > 0)
339 logger().warn(
"Skipping faces as theys have {} nodes, boundary export supported up to p4", print_warning.str());
341 boundary_triangles.resize(tris.size(), 3);
342 for (
int i = 0; i < tris.size(); ++i)
344 boundary_triangles.row(i) << std::get<0>(tris[i]), std::get<2>(tris[i]), std::get<1>(tris[i]);
347 if (boundary_triangles.rows() > 0)
349 igl::edges(boundary_triangles, boundary_edges);
354 node_positions.resize(n_bases, 2);
355 node_positions.setZero();
356 const Mesh2D &mesh2d =
dynamic_cast<const Mesh2D &
>(mesh);
358 std::vector<std::pair<int, int>> edges;
364 for (
int j = 0; j < lb.size(); ++j)
366 const int eid = lb.global_primitive_id(j);
367 const int lid = lb[j];
372 for (
long n = 0; n < nodes.size(); ++n)
375 const std::vector<basis::Local2Global> &glob = bs.
global();
376 if (glob.size() != 1)
379 int gindex = glob.front().index;
380 node_positions.row(gindex) = glob.front().node.head<2>();
383 edges.emplace_back(prev_node, gindex);
389 boundary_triangles.resize(0, 0);
390 boundary_edges.resize(edges.size(), 2);
391 for (
int i = 0; i < edges.size(); ++i)
393 boundary_edges.row(i) << edges[i].first, edges[i].second;
400 const std::vector<basis::ElementBases> &bases,
401 const std::vector<basis::ElementBases> &gbases,
402 const std::vector<mesh::LocalBoundary> &total_local_boundary,
403 const Eigen::MatrixXd &solution,
404 const int problem_dim,
405 Eigen::MatrixXd &boundary_vis_vertices,
406 Eigen::MatrixXd &boundary_vis_local_vertices,
407 Eigen::MatrixXi &boundary_vis_elements,
408 Eigen::MatrixXi &boundary_vis_elements_ids,
409 Eigen::MatrixXi &boundary_vis_primitive_ids,
410 Eigen::MatrixXd &boundary_vis_normals,
411 Eigen::MatrixXd &displaced_boundary_vis_normals)
const
415 std::vector<Eigen::MatrixXd> lv, vertices, allnormals, displaced_allnormals;
416 std::vector<int> el_ids, global_primitive_ids;
417 Eigen::MatrixXd uv, local_pts, tmp_n, normals, displaced_normals, trafo, deform_mat;
423 std::vector<std::pair<int, int>> edges;
424 std::vector<std::tuple<int, int, int>> tris;
426 for (
auto it = total_local_boundary.begin(); it != total_local_boundary.end(); ++it)
428 const auto &lb = *it;
429 const auto &gbs = gbases[lb.element_id()];
430 const auto &bs = bases[lb.element_id()];
432 for (
int k = 0; k < lb.size(); ++k)
436 case BoundaryType::TRI_LINE:
440 case BoundaryType::QUAD_LINE:
444 case BoundaryType::QUAD:
448 case BoundaryType::TRI:
452 case BoundaryType::POLYGON:
456 case BoundaryType::POLYHEDRON:
459 case BoundaryType::INVALID:
466 vertices.emplace_back();
467 lv.emplace_back(local_pts);
468 el_ids.push_back(lb.element_id());
469 global_primitive_ids.push_back(lb.global_primitive_id(k));
470 gbs.eval_geom_mapping(local_pts, vertices.back());
471 vals.compute(lb.element_id(), mesh.
is_volume(), local_pts, bs, gbs);
472 const int tris_start = tris.size();
476 if (lb.type() == BoundaryType::QUAD)
478 const auto map = [n_samples, size](
int i,
int j) {
return j * n_samples + i + size; };
480 for (
int j = 0; j < n_samples - 1; ++j)
482 for (
int i = 0; i < n_samples - 1; ++i)
484 tris.emplace_back(map(i, j), map(i + 1, j), map(i, j + 1));
485 tris.emplace_back(map(i + 1, j + 1), map(i, j + 1), map(i + 1, j));
489 else if (lb.type() == BoundaryType::TRI)
492 std::vector<int> mapp(n_samples * n_samples, -1);
493 for (
int j = 0; j < n_samples; ++j)
495 for (
int i = 0; i < n_samples - j; ++i)
497 mapp[j * n_samples + i] = index;
501 const auto map = [mapp, n_samples](
int i,
int j) {
502 if (j * n_samples + i >= mapp.size())
504 return mapp[j * n_samples + i];
507 for (
int j = 0; j < n_samples - 1; ++j)
509 for (
int i = 0; i < n_samples - j; ++i)
511 if (map(i, j) >= 0 && map(i + 1, j) >= 0 && map(i, j + 1) >= 0)
512 tris.emplace_back(map(i, j) + size, map(i + 1, j) + size, map(i, j + 1) + size);
514 if (map(i + 1, j + 1) >= 0 && map(i, j + 1) >= 0 && map(i + 1, j) >= 0)
515 tris.emplace_back(map(i + 1, j + 1) + size, map(i, j + 1) + size, map(i + 1, j) + size);
526 for (
int i = 0; i < vertices.back().rows() - 1; ++i)
527 edges.emplace_back(i + size, i + size + 1);
530 normals.resize(
vals.jac_it.size(), tmp_n.cols());
531 displaced_normals.resize(
vals.jac_it.size(), tmp_n.cols());
533 for (
int n = 0; n <
vals.jac_it.size(); ++n)
535 trafo =
vals.jac_it[n].inverse();
537 if (problem_dim == 2 || problem_dim == 3)
540 if (solution.size() > 0)
542 deform_mat.resize(problem_dim, problem_dim);
543 deform_mat.setZero();
544 for (
const auto &b :
vals.basis_values)
545 for (
const auto &g : b.global)
546 for (
int d = 0; d < problem_dim; ++d)
547 deform_mat.row(d) += solution(g.index * problem_dim + d) * b.grad.row(n);
553 normals.row(n) = tmp_n *
vals.jac_it[n];
554 normals.row(n).normalize();
556 displaced_normals.row(n) = tmp_n * trafo.inverse();
557 displaced_normals.row(n).normalize();
560 allnormals.push_back(normals);
561 displaced_allnormals.push_back(displaced_normals);
564 for (
int n = 0; n <
vals.jac_it.size(); ++n)
566 tmp_n += normals.row(n);
571 Eigen::Vector3d e1 = vertices.back().row(std::get<1>(tris.back()) - size) - vertices.back().row(std::get<0>(tris.back()) - size);
572 Eigen::Vector3d e2 = vertices.back().row(std::get<2>(tris.back()) - size) - vertices.back().row(std::get<0>(tris.back()) - size);
574 Eigen::Vector3d n = e1.cross(e2);
575 Eigen::Vector3d nn = tmp_n.transpose();
579 for (
int i = tris_start; i < tris.size(); ++i)
581 tris[i] = std::tuple<int, int, int>(std::get<0>(tris[i]), std::get<2>(tris[i]), std::get<1>(tris[i]));
586 size += vertices.back().rows();
590 boundary_vis_vertices.resize(size, vertices.front().cols());
591 boundary_vis_local_vertices.resize(size, vertices.front().cols());
592 boundary_vis_elements_ids.resize(size, 1);
593 boundary_vis_primitive_ids.resize(size, 1);
594 boundary_vis_normals.resize(size, vertices.front().cols());
595 displaced_boundary_vis_normals.resize(size, vertices.front().cols());
598 boundary_vis_elements.resize(tris.size(), 3);
600 boundary_vis_elements.resize(edges.size(), 2);
604 for (
const auto &v : vertices)
606 boundary_vis_vertices.block(index, 0, v.rows(), v.cols()) = v;
607 boundary_vis_local_vertices.block(index, 0, v.rows(), v.cols()) = lv[ii];
608 boundary_vis_elements_ids.block(index, 0, v.rows(), 1).setConstant(el_ids[ii]);
609 boundary_vis_primitive_ids.block(index, 0, v.rows(), 1).setConstant(global_primitive_ids[ii++]);
614 for (
const auto &n : allnormals)
616 boundary_vis_normals.block(index, 0, n.rows(), n.cols()) = n;
621 for (
const auto &n : displaced_allnormals)
623 displaced_boundary_vis_normals.block(index, 0, n.rows(), n.cols()) = n;
630 for (
const auto &t : tris)
632 boundary_vis_elements.row(index) << std::get<0>(t), std::get<1>(t), std::get<2>(t);
638 for (
const auto &e : edges)
640 boundary_vis_elements.row(index) << e.first, e.second;
648 const Eigen::VectorXi &disc_orders,
649 const std::vector<basis::ElementBases> &gbases,
650 const std::map<int, Eigen::MatrixXd> &polys,
651 const std::map<
int, std::pair<Eigen::MatrixXd, Eigen::MatrixXi>> &polys_3d,
652 const bool boundary_only,
653 Eigen::MatrixXd &points,
654 Eigen::MatrixXi &tets,
655 Eigen::MatrixXi &el_id,
656 Eigen::MatrixXd &discr)
const
671 const auto ¤t_bases = gbases;
672 int tet_total_size = 0;
673 int pts_total_size = 0;
675 Eigen::MatrixXd vis_pts_poly;
676 Eigen::MatrixXi vis_faces_poly, vis_edges_poly;
678 for (
size_t i = 0; i < current_bases.size(); ++i)
680 const auto &bs = current_bases[i];
688 pts_total_size += sampler.simplex_points().rows();
692 tet_total_size += sampler.cube_volume().rows();
693 pts_total_size += sampler.cube_points().rows();
699 sampler.sample_polyhedron(polys_3d.at(i).first, polys_3d.at(i).second, vis_pts_poly, vis_faces_poly, vis_edges_poly);
701 tet_total_size += vis_faces_poly.rows();
702 pts_total_size += vis_pts_poly.rows();
706 sampler.sample_polygon(polys.at(i), vis_pts_poly, vis_faces_poly, vis_edges_poly);
708 tet_total_size += vis_faces_poly.rows();
709 pts_total_size += vis_pts_poly.rows();
714 points.resize(pts_total_size, mesh.
dimension());
715 tets.resize(tet_total_size, mesh.
is_volume() ? 4 : 3);
717 el_id.resize(pts_total_size, 1);
718 discr.resize(pts_total_size, 1);
720 Eigen::MatrixXd mapped, tmp;
721 int tet_index = 0, pts_index = 0;
723 for (
size_t i = 0; i < current_bases.size(); ++i)
725 const auto &bs = current_bases[i];
732 bs.eval_geom_mapping(sampler.simplex_points(), mapped);
734 tets.block(tet_index, 0, sampler.simplex_volume().rows(), tets.cols()) = sampler.simplex_volume().array() + pts_index;
735 tet_index += sampler.simplex_volume().rows();
737 points.block(pts_index, 0, mapped.rows(), points.cols()) = mapped;
738 discr.block(pts_index, 0, mapped.rows(), 1).setConstant(disc_orders(i));
739 el_id.block(pts_index, 0, mapped.rows(), 1).setConstant(i);
740 pts_index += mapped.rows();
744 bs.eval_geom_mapping(sampler.cube_points(), mapped);
746 tets.block(tet_index, 0, sampler.cube_volume().rows(), tets.cols()) = sampler.cube_volume().array() + pts_index;
747 tet_index += sampler.cube_volume().rows();
749 points.block(pts_index, 0, mapped.rows(), points.cols()) = mapped;
750 discr.block(pts_index, 0, mapped.rows(), 1).setConstant(disc_orders(i));
751 el_id.block(pts_index, 0, mapped.rows(), 1).setConstant(i);
752 pts_index += mapped.rows();
758 sampler.sample_polyhedron(polys_3d.at(i).first, polys_3d.at(i).second, vis_pts_poly, vis_faces_poly, vis_edges_poly);
759 bs.eval_geom_mapping(vis_pts_poly, mapped);
761 tets.block(tet_index, 0, vis_faces_poly.rows(), tets.cols()) = vis_faces_poly.array() + pts_index;
762 tet_index += vis_faces_poly.rows();
764 points.block(pts_index, 0, mapped.rows(), points.cols()) = mapped;
765 discr.block(pts_index, 0, mapped.rows(), 1).setConstant(-1);
766 el_id.block(pts_index, 0, mapped.rows(), 1).setConstant(i);
767 pts_index += mapped.rows();
771 sampler.sample_polygon(polys.at(i), vis_pts_poly, vis_faces_poly, vis_edges_poly);
772 bs.eval_geom_mapping(vis_pts_poly, mapped);
774 tets.block(tet_index, 0, vis_faces_poly.rows(), tets.cols()) = vis_faces_poly.array() + pts_index;
775 tet_index += vis_faces_poly.rows();
777 points.block(pts_index, 0, mapped.rows(), points.cols()) = mapped;
778 discr.block(pts_index, 0, mapped.rows(), 1).setConstant(-1);
779 el_id.block(pts_index, 0, mapped.rows(), 1).setConstant(i);
780 pts_index += mapped.rows();
785 assert(pts_index == points.rows());
786 assert(tet_index == tets.rows());
791 const Eigen::VectorXi &disc_orders,
792 const std::vector<basis::ElementBases> &bases,
793 Eigen::MatrixXd &points,
794 std::vector<std::vector<int>> &elements,
795 Eigen::MatrixXi &el_id,
796 Eigen::MatrixXd &discr)
const
810 std::vector<RowVectorNd> nodes;
811 int pts_total_size = 0;
812 elements.resize(bases.size());
813 Eigen::MatrixXd ref_pts;
815 for (
size_t i = 0; i < bases.size(); ++i)
817 const auto &bs = bases[i];
835 const int n_v =
static_cast<const mesh::Mesh2D &
>(mesh).n_face_vertices(i);
836 ref_pts.resize(n_v, 2);
840 pts_total_size += ref_pts.rows();
843 points.resize(pts_total_size, mesh.
dimension());
845 el_id.resize(pts_total_size, 1);
846 discr.resize(pts_total_size, 1);
848 Eigen::MatrixXd mapped;
851 std::string error_msg =
"";
853 for (
size_t i = 0; i < bases.size(); ++i)
855 const auto &bs = bases[i];
875 bs.eval_geom_mapping(ref_pts, mapped);
877 for (
int j = 0; j < mapped.rows(); ++j)
879 points.row(pts_index) = mapped.row(j);
880 el_id(pts_index) = i;
881 discr(pts_index) = disc_orders(i);
882 elements[i].push_back(pts_index);
891 const int n_nodes = elements[i].size();
892 if (disc_orders(i) >= 3)
894 std::swap(elements[i][16], elements[i][17]);
895 std::swap(elements[i][17], elements[i][18]);
896 std::swap(elements[i][18], elements[i][19]);
898 if (disc_orders(i) > 4)
899 error_msg =
"Saving high-order meshes not implemented for P5+ elements!";
903 if (disc_orders(i) == 4)
905 const int n_nodes = elements[i].size();
906 std::swap(elements[i][n_nodes - 1], elements[i][n_nodes - 2]);
908 if (disc_orders(i) > 4)
909 error_msg =
"Saving high-order meshes not implemented for P5+ elements!";
912 else if (disc_orders(i) > 1)
913 error_msg =
"Saving high-order meshes not implemented for Q2+ elements!";
916 if (!error_msg.empty())
919 for (
size_t i = 0; i < bases.size(); ++i)
924 const auto &mesh2d =
static_cast<const mesh::Mesh2D &
>(mesh);
927 for (
int j = 0; j < n_v; ++j)
929 points.row(pts_index) = mesh2d.point(mesh2d.face_vertex(i, j));
930 el_id(pts_index) = i;
931 discr(pts_index) = disc_orders(i);
932 elements[i].push_back(pts_index);
938 assert(pts_index == points.rows());
943 const Eigen::MatrixXd &sol,
944 const Eigen::MatrixXd &pressure,
945 const bool is_time_dependent,
946 const double tend_in,
949 const std::string &vis_mesh_path,
950 const std::string &nodes_path,
951 const std::string &solution_path,
952 const std::string &stress_path,
953 const std::string &mises_path,
954 const bool is_contact_enabled,
955 std::vector<SolutionFrame> &solution_frames)
const
959 logger().error(
"Load the mesh first!");
962 const int n_bases = state.
n_bases;
963 const std::vector<basis::ElementBases> &bases = state.
bases;
964 const std::vector<basis::ElementBases> &gbases = state.
geom_bases();
967 const Eigen::MatrixXd &rhs = state.
rhs;
972 logger().error(
"Build the bases first!");
982 logger().error(
"Solve the problem first!");
986 if (!solution_path.empty())
988 std::ofstream out(solution_path);
990 out << std::scientific;
994 Eigen::VectorXi reordering(n_bases);
995 reordering.setConstant(-1);
997 for (
int i = 0; i < in_node_to_node.size(); ++i)
999 reordering[in_node_to_node[i]] = i;
1002 Eigen::MatrixXd tmp(tmp_sol.rows(), tmp_sol.cols());
1004 for (
int i = 0; i < reordering.size(); ++i)
1006 if (reordering[i] < 0)
1009 tmp.row(reordering[i]) = tmp_sol.row(i);
1012 for (
int i = 0; i < tmp.rows(); ++i)
1014 for (
int j = 0; j < tmp.cols(); ++j)
1015 out << tmp(i, j) <<
" ";
1021 out << sol << std::endl;
1025 double tend = tend_in;
1029 if (!vis_mesh_path.empty() && !is_time_dependent)
1032 vis_mesh_path, state, sol, pressure,
1034 is_contact_enabled, solution_frames);
1036 if (!nodes_path.empty())
1038 Eigen::MatrixXd nodes(n_bases, mesh.
dimension());
1044 for (
size_t ii = 0; ii < b.global().size(); ++ii)
1046 const auto &lg = b.global()[ii];
1047 nodes.row(lg.index) = lg.node;
1051 std::ofstream out(nodes_path);
1056 if (!stress_path.empty())
1058 Eigen::MatrixXd result;
1059 Eigen::VectorXd mises;
1063 sol, tend, result, mises);
1064 std::ofstream out(stress_path);
1068 if (!mises_path.empty())
1070 Eigen::MatrixXd result;
1071 Eigen::VectorXd mises;
1075 sol, tend, result, mises);
1076 std::ofstream out(mises_path);
1084 volume = args[
"output"][
"paraview"][
"volume"];
1085 surface = args[
"output"][
"paraview"][
"surface"];
1086 wire = args[
"output"][
"paraview"][
"wireframe"];
1087 points = args[
"output"][
"paraview"][
"points"];
1088 contact_forces = args[
"output"][
"paraview"][
"options"][
"contact_forces"] && !is_problem_scalar;
1089 friction_forces = args[
"output"][
"paraview"][
"options"][
"friction_forces"] && !is_problem_scalar;
1094 body_ids = args[
"output"][
"paraview"][
"options"][
"body_ids"];
1095 sol_on_grid = args[
"output"][
"advanced"][
"sol_on_grid"] > 0;
1096 velocity = args[
"output"][
"paraview"][
"options"][
"velocity"];
1097 acceleration = args[
"output"][
"paraview"][
"options"][
"acceleration"];
1098 forces = args[
"output"][
"paraview"][
"options"][
"forces"] && !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");
1303 Eigen::MatrixXd tmp = Eigen::VectorXd::LinSpaced(sol.size(), 0, sol.size() - 1);
1313 fun.conservativeResize(fun.rows() + obstacle.
n_vertices(), fun.cols());
1314 node_fun.conservativeResize(node_fun.rows() + obstacle.
n_vertices(), node_fun.cols());
1315 node_fun.bottomRows(obstacle.
n_vertices()).setZero();
1323 problem.
exact(points, t, exact_fun);
1324 err = (fun - exact_fun).eval().rowwise().norm();
1328 exact_fun.conservativeResize(exact_fun.rows() + obstacle.
n_vertices(), exact_fun.cols());
1332 err.conservativeResize(err.rows() + obstacle.
n_vertices(), 1);
1333 err.bottomRows(obstacle.
n_vertices()).setZero();
1337 std::shared_ptr<paraviewo::ParaviewWriter> tmpw;
1339 tmpw = std::make_shared<paraviewo::HDF5VTUWriter>();
1341 tmpw = std::make_shared<paraviewo::VTUWriter>();
1342 paraviewo::ParaviewWriter &writer = *tmpw;
1345 writer.add_field(
"nodes", node_fun);
1349 bool is_time_integrator_valid = time_integrator !=
nullptr;
1353 const Eigen::VectorXd velocity =
1354 is_time_integrator_valid ? (time_integrator->v_prev()) : Eigen::VectorXd::Zero(sol.size());
1360 const Eigen::VectorXd acceleration =
1361 is_time_integrator_valid ? (time_integrator->a_prev()) : Eigen::VectorXd::Zero(sol.size());
1375 if (form ==
nullptr)
1378 Eigen::VectorXd force;
1379 if (form->enabled())
1381 form->first_derivative(sol, force);
1386 force.setZero(sol.size());
1396 Eigen::MatrixXd interp_p;
1404 interp_p.conservativeResize(interp_p.size() + obstacle.
n_vertices(), 1);
1405 interp_p.bottomRows(obstacle.
n_vertices()).setZero();
1409 writer.add_field(
"pressure", interp_p);
1411 solution_frames.back().pressure = interp_p;
1416 discr.conservativeResize(discr.size() + obstacle.
n_vertices(), 1);
1417 discr.bottomRows(obstacle.
n_vertices()).setZero();
1421 writer.add_field(
"discr", discr);
1427 writer.add_field(
"exact", exact_fun);
1428 writer.add_field(
"error", err);
1432 solution_frames.back().exact = exact_fun;
1433 solution_frames.back().error = err;
1437 if (fun.cols() != 1)
1439 std::vector<assembler::Assembler::NamedMatrix>
vals, tvals;
1441 mesh, problem.
is_scalar(), bases, gbases,
1446 for (
auto &[_, v] :
vals)
1453 for (
const auto &[name, v] :
vals)
1454 writer.add_field(name, v);
1456 else if (
vals.size() > 0)
1457 solution_frames.back().scalar_value =
vals[0].second;
1467 for (
auto &[_, v] : tvals)
1470 for (
const auto &[name, v] : tvals)
1473 assert(v.cols() % stride == 0);
1475 for (
int i = 0; i < v.cols(); i += stride)
1477 const Eigen::MatrixXd tmp = v.middleCols(i, stride);
1478 assert(tmp.cols() == stride);
1480 const int ii = (i / stride) + 1;
1481 writer.add_field(fmt::format(
"{:s}_{:d}", name, ii), tmp);
1496 for (
auto &v :
vals)
1498 v.second.conservativeResize(v.second.size() + obstacle.
n_vertices(), 1);
1499 v.second.bottomRows(obstacle.
n_vertices()).setZero();
1507 for (
const auto &v :
vals)
1508 writer.add_field(fmt::format(
"{:s}_avg", v.first), v.second);
1510 else if (
vals.size() > 0)
1511 solution_frames.back().scalar_value_avg =
vals[0].second;
1525 std::map<std::string, Eigen::MatrixXd> param_val;
1526 for (
const auto &[p, _] : params)
1527 param_val[p] = Eigen::MatrixXd(points.rows(), 1);
1528 Eigen::MatrixXd rhos(points.rows(), 1);
1530 Eigen::MatrixXd local_pts;
1531 Eigen::MatrixXi vis_faces_poly, vis_edges_poly;
1535 for (
int e = 0; e < int(bases.size()); ++e)
1543 local_pts = sampler.simplex_points();
1545 local_pts = sampler.cube_points();
1549 sampler.sample_polyhedron(polys_3d.at(e).first, polys_3d.at(e).second, local_pts, vis_faces_poly, vis_edges_poly);
1551 sampler.sample_polygon(polys.at(e), local_pts, vis_faces_poly, vis_edges_poly);
1573 const auto &mesh2d =
static_cast<const mesh::Mesh2D &
>(mesh);
1575 local_pts.resize(n_v, 2);
1577 for (
int j = 0; j < n_v; ++j)
1579 local_pts.row(j) = mesh2d.point(mesh2d.face_vertex(e, j));
1588 for (
int j = 0; j <
vals.val.rows(); ++j)
1590 for (
const auto &[p, func] : params)
1591 param_val.at(p)(index) = func(local_pts.row(j),
vals.val.row(j), t, e);
1593 rhos(index) = density(local_pts.row(j),
vals.val.row(j), t, e);
1599 assert(index == points.rows());
1603 for (
auto &[_, tmp] : param_val)
1605 tmp.conservativeResize(tmp.size() + obstacle.
n_vertices(), 1);
1606 tmp.bottomRows(obstacle.
n_vertices()).setZero();
1609 rhos.conservativeResize(rhos.size() + obstacle.
n_vertices(), 1);
1610 rhos.bottomRows(obstacle.
n_vertices()).setZero();
1612 for (
const auto &[p, tmp] : param_val)
1613 writer.add_field(p, tmp);
1614 writer.add_field(
"rho", rhos);
1620 Eigen::MatrixXd ids(points.rows(), 1);
1622 for (
int i = 0; i < points.rows(); ++i)
1629 ids.conservativeResize(ids.size() + obstacle.
n_vertices(), 1);
1630 ids.bottomRows(obstacle.
n_vertices()).setZero();
1633 writer.add_field(
"body_ids", ids);
1641 Eigen::MatrixXd traction_forces, traction_forces_fun;
1642 compute_traction_forces(state, sol, t, traction_forces,
false);
1651 traction_forces_fun.conservativeResize(traction_forces_fun.rows() + obstacle.
n_vertices(), traction_forces_fun.cols());
1652 traction_forces_fun.bottomRows(obstacle.
n_vertices()).setZero();
1655 writer.add_field(
"traction_force", traction_forces_fun);
1662 Eigen::MatrixXd potential_grad, potential_grad_fun;
1672 potential_grad_fun.conservativeResize(potential_grad_fun.rows() + obstacle.
n_vertices(), potential_grad_fun.cols());
1673 potential_grad_fun.bottomRows(obstacle.
n_vertices()).setZero();
1676 writer.add_field(
"gradient_of_potential", potential_grad_fun);
1678 catch (std::exception &)
1685 writer.add_field(
"solution", fun);
1687 solution_frames.back().solution = fun;
1693 const int orig_p = points.rows();
1694 points.conservativeResize(points.rows() + obstacle.
n_vertices(), points.cols());
1695 points.bottomRows(obstacle.
n_vertices()) = obstacle.
v();
1697 if (elements.empty())
1699 for (
int i = 0; i < tets.rows(); ++i)
1701 elements.emplace_back();
1702 for (
int j = 0; j < tets.cols(); ++j)
1703 elements.back().push_back(tets(i, j));
1709 elements.emplace_back();
1716 elements.emplace_back();
1723 elements.emplace_back();
1728 if (elements.empty())
1729 writer.write_mesh(path, points, tets);
1731 writer.write_mesh(path, points, elements,
true, disc_orders.maxCoeff() == 1);
1735 solution_frames.back().name = path;
1736 solution_frames.back().points = points;
1737 solution_frames.back().connectivity = tets;
1743 const Eigen::MatrixXd &points,
1745 const std::string &name,
1746 const Eigen::VectorXd &field,
1747 paraviewo::ParaviewWriter &writer)
const
1749 Eigen::MatrixXd inerpolated_field;
1757 inerpolated_field.conservativeResize(
1765 writer.add_field(name, inerpolated_field);
1771 const std::string &export_surface,
1773 const Eigen::MatrixXd &sol,
1774 const Eigen::MatrixXd &pressure,
1778 const bool is_contact_enabled,
1779 std::vector<SolutionFrame> &solution_frames)
const
1782 const Eigen::VectorXi &disc_orders = state.
disc_orders;
1784 const std::vector<basis::ElementBases> &bases = state.
bases;
1785 const std::vector<basis::ElementBases> &pressure_bases = state.
pressure_bases;
1786 const std::vector<basis::ElementBases> &gbases = state.
geom_bases();
1792 Eigen::MatrixXd boundary_vis_vertices;
1793 Eigen::MatrixXd boundary_vis_local_vertices;
1794 Eigen::MatrixXi boundary_vis_elements;
1795 Eigen::MatrixXi boundary_vis_elements_ids;
1796 Eigen::MatrixXi boundary_vis_primitive_ids;
1797 Eigen::MatrixXd boundary_vis_normals;
1798 Eigen::MatrixXd displaced_boundary_vis_normals;
1801 boundary_vis_vertices, boundary_vis_local_vertices, boundary_vis_elements,
1802 boundary_vis_elements_ids, boundary_vis_primitive_ids, boundary_vis_normals,
1803 displaced_boundary_vis_normals);
1805 Eigen::MatrixXd fun, interp_p, discr, vect, b_sidesets;
1807 Eigen::MatrixXd lsol, lp, lgrad, lpgrad;
1813 discr.resize(boundary_vis_vertices.rows(), 1);
1814 fun.resize(boundary_vis_vertices.rows(), actual_dim);
1815 interp_p.resize(boundary_vis_vertices.rows(), 1);
1816 vect.resize(boundary_vis_vertices.rows(), mesh.
dimension());
1818 b_sidesets.resize(boundary_vis_vertices.rows(), 1);
1819 b_sidesets.setZero();
1821 for (
int i = 0; i < boundary_vis_vertices.rows(); ++i)
1823 const auto s_id = mesh.
get_boundary_id(boundary_vis_primitive_ids(i));
1826 b_sidesets(i) = s_id;
1829 const int el_index = boundary_vis_elements_ids(i);
1831 mesh, problem.
is_scalar(), bases, gbases,
1832 el_index, boundary_vis_local_vertices.row(i), sol, lsol, lgrad);
1833 assert(lsol.size() == actual_dim);
1837 mesh, 1, pressure_bases, gbases,
1838 el_index, boundary_vis_local_vertices.row(i), pressure, lp, lpgrad);
1839 assert(lp.size() == 1);
1840 interp_p(i) = lp(0);
1843 discr(i) = disc_orders(el_index);
1844 for (
int j = 0; j < actual_dim; ++j)
1846 fun(i, j) = lsol(j);
1849 if (actual_dim == 1)
1851 assert(lgrad.size() == mesh.
dimension());
1852 for (
int j = 0; j < mesh.
dimension(); ++j)
1854 vect(i, j) = lgrad(j);
1859 assert(lgrad.size() == actual_dim * actual_dim);
1860 std::vector<assembler::Assembler::NamedMatrix> tensor_flat;
1865 assert(tensor_flat[0].first ==
"cauchy_stess");
1866 assert(tensor_flat[0].second.size() == actual_dim * actual_dim);
1868 Eigen::Map<Eigen::MatrixXd> tensor(tensor_flat[0].second.data(), actual_dim, actual_dim);
1869 vect.row(i) = displaced_boundary_vis_normals.row(i) * tensor;
1875 area = mesh.
tri_area(boundary_vis_primitive_ids(i));
1876 else if (mesh.
is_cube(el_index))
1877 area = mesh.
quad_area(boundary_vis_primitive_ids(i));
1880 area = mesh.
edge_length(boundary_vis_primitive_ids(i));
1882 vect.row(i) *= area;
1886 std::shared_ptr<paraviewo::ParaviewWriter> tmpw;
1888 tmpw = std::make_shared<paraviewo::HDF5VTUWriter>();
1890 tmpw = std::make_shared<paraviewo::VTUWriter>();
1891 paraviewo::ParaviewWriter &writer = *tmpw;
1896 writer.add_field(
"normals", boundary_vis_normals);
1897 writer.add_field(
"displaced_normals", displaced_boundary_vis_normals);
1899 writer.add_field(
"pressure", interp_p);
1900 writer.add_field(
"discr", discr);
1901 writer.add_field(
"sidesets", b_sidesets);
1903 if (actual_dim == 1)
1904 writer.add_field(
"solution_grad", vect);
1907 writer.add_field(
"traction_force", vect);
1913 solution_frames.back().pressure = interp_p;
1920 std::map<std::string, Eigen::MatrixXd> param_val;
1921 for (
const auto &[p, _] : params)
1922 param_val[p] = Eigen::MatrixXd(boundary_vis_vertices.rows(), 1);
1923 Eigen::MatrixXd rhos(boundary_vis_vertices.rows(), 1);
1925 for (
int i = 0; i < boundary_vis_vertices.rows(); ++i)
1929 for (
const auto &[p, func] : params)
1930 param_val.at(p)(i) = func(boundary_vis_local_vertices.row(i), boundary_vis_vertices.row(i), t, boundary_vis_elements_ids(i));
1932 rhos(i) = density(boundary_vis_local_vertices.row(i), boundary_vis_vertices.row(i), t, boundary_vis_elements_ids(i));
1935 for (
const auto &[p, tmp] : param_val)
1936 writer.add_field(p, tmp);
1937 writer.add_field(
"rho", rhos);
1943 Eigen::MatrixXd ids(boundary_vis_vertices.rows(), 1);
1945 for (
int i = 0; i < boundary_vis_vertices.rows(); ++i)
1947 ids(i) = mesh.
get_body_id(boundary_vis_elements_ids(i));
1950 writer.add_field(
"body_ids", ids);
1955 writer.add_field(
"solution", fun);
1957 solution_frames.back().solution = fun;
1960 writer.write_mesh(export_surface, boundary_vis_vertices, boundary_vis_elements);
1963 solution_frames.back().name = export_surface;
1964 solution_frames.back().points = boundary_vis_vertices;
1965 solution_frames.back().connectivity = boundary_vis_elements;
1970 const std::string &export_surface,
1972 const Eigen::MatrixXd &sol,
1973 const Eigen::MatrixXd &pressure,
1977 const bool is_contact_enabled,
1978 std::vector<SolutionFrame> &solution_frames)
const
1982 const double dhat = state.
args[
"contact"][
"dhat"];
1983 const double friction_coefficient = state.
args[
"contact"][
"friction_coefficient"];
1984 const double epsv = state.
args[
"contact"][
"epsv"];
1990 std::shared_ptr<paraviewo::ParaviewWriter> tmpw;
1992 tmpw = std::make_shared<paraviewo::HDF5VTUWriter>();
1994 tmpw = std::make_shared<paraviewo::VTUWriter>();
1995 paraviewo::ParaviewWriter &writer = *tmpw;
1997 const int problem_dim = mesh.
dimension();
1998 const Eigen::MatrixXd full_displacements =
utils::unflatten(sol, problem_dim);
1999 const Eigen::MatrixXd surface_displacements = collision_mesh.map_displacements(full_displacements);
2001 const Eigen::MatrixXd displaced_surface = collision_mesh.displace_vertices(full_displacements);
2003 ipc::Collisions collision_set;
2004 collision_set.set_use_convergent_formulation(state.
args[
"contact"][
"use_convergent_formulation"]);
2005 collision_set.build(
2006 collision_mesh, displaced_surface, dhat,
2007 0, state.
args[
"solver"][
"contact"][
"CCD"][
"broad_phase"]);
2009 ipc::BarrierPotential barrier_potential(dhat);
2011 const double barrier_stiffness = contact_form !=
nullptr ? contact_form->barrier_stiffness() : 1;
2015 Eigen::MatrixXd forces = -barrier_stiffness * barrier_potential.gradient(collision_set, collision_mesh, displaced_surface);
2019 assert(forces_reshaped.rows() == surface_displacements.rows());
2020 assert(forces_reshaped.cols() == surface_displacements.cols());
2021 writer.add_field(
"contact_forces", forces_reshaped);
2026 ipc::FrictionCollisions friction_collision_set;
2027 friction_collision_set.build(
2028 collision_mesh, displaced_surface, collision_set,
2029 barrier_potential, barrier_stiffness, friction_coefficient);
2031 ipc::FrictionPotential friction_potential(epsv);
2033 Eigen::MatrixXd velocities;
2038 velocities = collision_mesh.map_displacements(
utils::unflatten(velocities, collision_mesh.dim()));
2040 Eigen::MatrixXd forces = -friction_potential.gradient(
2041 friction_collision_set, collision_mesh, velocities);
2045 assert(forces_reshaped.rows() == surface_displacements.rows());
2046 assert(forces_reshaped.cols() == surface_displacements.cols());
2047 writer.add_field(
"friction_forces", forces_reshaped);
2050 assert(collision_mesh.rest_positions().rows() == surface_displacements.rows());
2051 assert(collision_mesh.rest_positions().cols() == surface_displacements.cols());
2054 writer.add_field(
"solution", surface_displacements);
2057 export_surface.substr(0, export_surface.length() - 4) +
"_contact.vtu",
2058 collision_mesh.rest_positions(),
2059 problem_dim == 3 ? collision_mesh.faces() : collision_mesh.edges());
2064 const std::string &name,
2066 const Eigen::MatrixXd &sol,
2069 std::vector<SolutionFrame> &solution_frames)
const
2071 const std::vector<basis::ElementBases> &gbases = state.
geom_bases();
2079 Eigen::MatrixXi vis_faces_poly, vis_edges_poly;
2080 Eigen::MatrixXd vis_pts_poly;
2082 const auto ¤t_bases = gbases;
2083 int seg_total_size = 0;
2084 int pts_total_size = 0;
2085 int faces_total_size = 0;
2087 for (
size_t i = 0; i < current_bases.size(); ++i)
2089 const auto &bs = current_bases[i];
2094 seg_total_size += sampler.simplex_edges().rows();
2095 faces_total_size += sampler.simplex_faces().rows();
2099 pts_total_size += sampler.cube_points().rows();
2100 seg_total_size += sampler.cube_edges().rows();
2101 faces_total_size += sampler.cube_faces().rows();
2106 sampler.sample_polyhedron(state.
polys_3d.at(i).first, state.
polys_3d.at(i).second, vis_pts_poly, vis_faces_poly, vis_edges_poly);
2108 sampler.sample_polygon(state.
polys.at(i), vis_pts_poly, vis_faces_poly, vis_edges_poly);
2110 pts_total_size += vis_pts_poly.rows();
2111 seg_total_size += vis_edges_poly.rows();
2112 faces_total_size += vis_faces_poly.rows();
2116 Eigen::MatrixXd points(pts_total_size, mesh.
dimension());
2117 Eigen::MatrixXi edges(seg_total_size, 2);
2118 Eigen::MatrixXi
faces(faces_total_size, 3);
2121 Eigen::MatrixXd mapped, tmp;
2122 int seg_index = 0, pts_index = 0, face_index = 0;
2123 for (
size_t i = 0; i < current_bases.size(); ++i)
2125 const auto &bs = current_bases[i];
2129 bs.eval_geom_mapping(sampler.simplex_points(), mapped);
2130 edges.block(seg_index, 0, sampler.simplex_edges().rows(), edges.cols()) = sampler.simplex_edges().array() + pts_index;
2131 seg_index += sampler.simplex_edges().rows();
2133 faces.block(face_index, 0, sampler.simplex_faces().rows(), 3) = sampler.simplex_faces().array() + pts_index;
2134 face_index += sampler.simplex_faces().rows();
2136 points.block(pts_index, 0, mapped.rows(), points.cols()) = mapped;
2137 pts_index += mapped.rows();
2141 bs.eval_geom_mapping(sampler.cube_points(), mapped);
2142 edges.block(seg_index, 0, sampler.cube_edges().rows(), edges.cols()) = sampler.cube_edges().array() + pts_index;
2143 seg_index += sampler.cube_edges().rows();
2145 faces.block(face_index, 0, sampler.cube_faces().rows(), 3) = sampler.cube_faces().array() + pts_index;
2146 face_index += sampler.cube_faces().rows();
2148 points.block(pts_index, 0, mapped.rows(), points.cols()) = mapped;
2149 pts_index += mapped.rows();
2154 sampler.sample_polyhedron(state.
polys_3d.at(i).first, state.
polys_3d.at(i).second, vis_pts_poly, vis_faces_poly, vis_edges_poly);
2156 sampler.sample_polygon(state.
polys.at(i), vis_pts_poly, vis_faces_poly, vis_edges_poly);
2158 edges.block(seg_index, 0, vis_edges_poly.rows(), edges.cols()) = vis_edges_poly.array() + pts_index;
2159 seg_index += vis_edges_poly.rows();
2161 faces.block(face_index, 0, vis_faces_poly.rows(), 3) = vis_faces_poly.array() + pts_index;
2162 face_index += vis_faces_poly.rows();
2164 points.block(pts_index, 0, vis_pts_poly.rows(), points.cols()) = vis_pts_poly;
2165 pts_index += vis_pts_poly.rows();
2169 assert(pts_index == points.rows());
2170 assert(face_index ==
faces.rows());
2175 for (
long i = 0; i <
faces.rows(); ++i)
2177 const int v0 =
faces(i, 0);
2178 const int v1 =
faces(i, 1);
2179 const int v2 =
faces(i, 2);
2181 int tmpc =
faces(i, 2);
2188 Eigen::Matrix2d mmat;
2189 for (
long i = 0; i <
faces.rows(); ++i)
2191 const int v0 =
faces(i, 0);
2192 const int v1 =
faces(i, 1);
2193 const int v2 =
faces(i, 2);
2195 mmat.row(0) = points.row(v2) - points.row(v0);
2196 mmat.row(1) = points.row(v1) - points.row(v0);
2198 if (mmat.determinant() > 0)
2200 int tmpc =
faces(i, 2);
2207 Eigen::MatrixXd fun;
2211 pts_index, sol, fun,
true,
false);
2213 Eigen::MatrixXd exact_fun, err;
2217 problem.
exact(points, t, exact_fun);
2218 err = (fun - exact_fun).eval().rowwise().norm();
2221 std::shared_ptr<paraviewo::ParaviewWriter> tmpw;
2223 tmpw = std::make_shared<paraviewo::HDF5VTUWriter>();
2225 tmpw = std::make_shared<paraviewo::VTUWriter>();
2226 paraviewo::ParaviewWriter &writer = *tmpw;
2230 writer.add_field(
"exact", exact_fun);
2231 writer.add_field(
"error", err);
2234 if (fun.cols() != 1)
2236 std::vector<assembler::Assembler::NamedMatrix> scalar_val;
2242 for (
const auto &v : scalar_val)
2243 writer.add_field(v.first, v.second);
2246 writer.add_field(
"solution", fun);
2248 writer.write_mesh(name, points, edges);
2252 const std::string &path,
2254 const Eigen::MatrixXd &sol,
2256 std::vector<SolutionFrame> &solution_frames)
const
2267 Eigen::MatrixXd fun(dirichlet_nodes_position.size(), actual_dim);
2268 Eigen::MatrixXd b_sidesets(dirichlet_nodes_position.size(), 1);
2269 b_sidesets.setZero();
2270 Eigen::MatrixXd points(dirichlet_nodes_position.size(), mesh.
dimension());
2271 std::vector<std::vector<int>> cells(dirichlet_nodes_position.size());
2273 for (
int i = 0; i < dirichlet_nodes_position.size(); ++i)
2275 const int n_id = dirichlet_nodes[i];
2279 b_sidesets(i) = s_id;
2282 for (
int j = 0; j < actual_dim; ++j)
2284 fun(i, j) = sol(n_id * actual_dim + j);
2287 points.row(i) = dirichlet_nodes_position[i];
2288 cells[i].push_back(i);
2291 std::shared_ptr<paraviewo::ParaviewWriter> tmpw;
2293 tmpw = std::make_shared<paraviewo::HDF5VTUWriter>();
2295 tmpw = std::make_shared<paraviewo::VTUWriter>();
2296 paraviewo::ParaviewWriter &writer = *tmpw;
2300 writer.add_field(
"sidesets", b_sidesets);
2302 writer.add_field(
"solution", fun);
2303 writer.write_mesh(path, points, cells,
false,
false);
2308 const std::string &name,
2309 const std::function<std::string(
int)> &vtu_names,
2310 int time_steps,
double t0,
double dt,
int skip_frame)
const
2312 paraviewo::PVDWriter::save_pvd(name, vtu_names, time_steps, t0, dt, skip_frame);
2328 const int nx = delta[0] / spacing + 1;
2329 const int ny = delta[1] / spacing + 1;
2330 const int nz = delta.cols() >= 3 ? (delta[2] / spacing + 1) : 1;
2331 const int n = nx * ny * nz;
2335 for (
int i = 0; i < nx; ++i)
2337 const double x = (delta[0] / (nx - 1)) * i + min[0];
2339 for (
int j = 0; j < ny; ++j)
2341 const double y = (delta[1] / (ny - 1)) * j + min[1];
2343 if (delta.cols() <= 2)
2349 for (
int k = 0; k < nz; ++k)
2351 const double z = (delta[2] / (nz - 1)) * k + min[2];
2360 std::vector<std::array<Eigen::Vector3d, 2>> boxes;
2366 const double eps = 1e-6;
2375 const Eigen::Vector3d min(
2380 const Eigen::Vector3d max(
2385 std::vector<unsigned int> candidates;
2387 bvh.intersect_box(min, max, candidates);
2389 for (
const auto cand : candidates)
2393 logger().warn(
"Element {} is not simplex, skipping", cand);
2397 Eigen::MatrixXd coords;
2400 for (
int d = 0; d < coords.size(); ++d)
2402 if (fabs(coords(d)) < 1e-8)
2404 else if (fabs(coords(d) - 1) < 1e-8)
2408 if (coords.array().minCoeff() >= 0 && coords.array().maxCoeff() <= 1)
2420 Eigen::MatrixXd samples_simplex, samples_cube, mapped, p0, p1, p;
2423 average_edge_length = 0;
2424 min_edge_length = std::numeric_limits<double>::max();
2426 if (!use_curved_mesh_size)
2430 min_edge_length = p.rowwise().norm().minCoeff();
2431 average_edge_length = p.rowwise().norm().mean();
2432 mesh_size = p.rowwise().norm().maxCoeff();
2434 logger().info(
"hmin: {}", min_edge_length);
2435 logger().info(
"hmax: {}", mesh_size);
2436 logger().info(
"havg: {}", average_edge_length);
2453 for (
size_t i = 0; i < bases_in.size(); ++i)
2462 bases_in[i].eval_geom_mapping(samples_simplex, mapped);
2467 bases_in[i].eval_geom_mapping(samples_cube, mapped);
2470 for (
int j = 0; j < n_edges; ++j)
2472 double current_edge = 0;
2473 for (
int k = 0; k < n_samples - 1; ++k)
2475 p0 = mapped.row(j * n_samples + k);
2476 p1 = mapped.row(j * n_samples + k + 1);
2479 current_edge += p.norm();
2482 mesh_size = std::max(current_edge, mesh_size);
2483 min_edge_length = std::min(current_edge, min_edge_length);
2484 average_edge_length += current_edge;
2489 average_edge_length /= n;
2491 logger().info(
"hmin: {}", min_edge_length);
2492 logger().info(
"hmax: {}", mesh_size);
2493 logger().info(
"havg: {}", average_edge_length);
2507 using namespace mesh;
2509 logger().info(
"Counting flipped elements...");
2513 for (
size_t i = 0; i < gbases.size(); ++i)
2519 if (!
vals.is_geom_mapping_positive(mesh.
is_volume(), gbases[i]))
2523 static const std::vector<std::string> element_type_names{{
2525 "RegularInteriorCube",
2526 "RegularBoundaryCube",
2527 "SimpleSingularInteriorCube",
2528 "MultiSingularInteriorCube",
2529 "SimpleSingularBoundaryCube",
2531 "MultiSingularBoundaryCube",
2537 log_and_throw_error(
"element {} is flipped, type {}", i, element_type_names[
static_cast<int>(els_tag[i])]);
2552 const std::vector<polyfem::basis::ElementBases> &bases,
2553 const std::vector<polyfem::basis::ElementBases> &gbases,
2557 const Eigen::MatrixXd &sol)
2561 logger().error(
"Build the bases first!");
2564 if (sol.size() <= 0)
2566 logger().error(
"Solve the problem first!");
2576 logger().info(
"Computing errors...");
2579 const int n_el = int(bases.size());
2581 Eigen::MatrixXd v_exact, v_approx;
2582 Eigen::MatrixXd v_exact_grad(0, 0), v_approx_grad;
2592 static const int p = 8;
2597 for (
int e = 0; e < n_el; ++e)
2607 v_approx.resize(
vals.val.rows(), actual_dim);
2610 v_approx_grad.resize(
vals.val.rows(), mesh.
dimension() * actual_dim);
2611 v_approx_grad.setZero();
2613 const int n_loc_bases = int(
vals.basis_values.size());
2615 for (
int i = 0; i < n_loc_bases; ++i)
2617 const auto &
val =
vals.basis_values[i];
2619 for (
size_t ii = 0; ii <
val.global.size(); ++ii)
2621 for (
int d = 0; d < actual_dim; ++d)
2623 v_approx.col(d) +=
val.global[ii].val * sol(
val.global[ii].index * actual_dim + d) *
val.val;
2624 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;
2629 const auto err = problem.
has_exact_sol() ? (v_exact - v_approx).eval().rowwise().norm().eval() : (v_approx).eval().rowwise().norm().eval();
2630 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();
2635 linf_err = std::max(linf_err, err.maxCoeff());
2636 grad_max_err = std::max(linf_err, err_grad.maxCoeff());
2678 l2_err += (err.array() * err.array() *
vals.det.array() *
vals.quadrature.weights.array()).sum();
2679 h1_err += (err_grad.array() * err_grad.array() *
vals.det.array() *
vals.quadrature.weights.array()).sum();
2680 lp_err += (err.array().pow(p) *
vals.det.array() *
vals.quadrature.weights.array()).sum();
2683 h1_semi_err = sqrt(fabs(h1_err));
2684 h1_err = sqrt(fabs(l2_err) + fabs(h1_err));
2685 l2_err = sqrt(fabs(l2_err));
2687 lp_err = pow(fabs(lp_err), 1. / p);
2692 const double computing_errors_time = timer.getElapsedTime();
2693 logger().info(
" took {}s", computing_errors_time);
2695 logger().info(
"-- L2 error: {}", l2_err);
2696 logger().info(
"-- Lp error: {}", lp_err);
2697 logger().info(
"-- H1 error: {}", h1_err);
2698 logger().info(
"-- H1 semi error: {}", h1_semi_err);
2701 logger().info(
"-- Linf error: {}", linf_err);
2702 logger().info(
"-- grad max error: {}", grad_max_err);
2717 regular_boundary_count = 0;
2718 simple_singular_count = 0;
2719 multi_singular_count = 0;
2721 non_regular_boundary_count = 0;
2722 non_regular_count = 0;
2723 undefined_count = 0;
2724 multi_singular_boundary_count = 0;
2728 for (
size_t i = 0; i < els_tag.size(); ++i)
2734 case ElementType::SIMPLEX:
2737 case ElementType::REGULAR_INTERIOR_CUBE:
2740 case ElementType::REGULAR_BOUNDARY_CUBE:
2741 regular_boundary_count++;
2743 case ElementType::SIMPLE_SINGULAR_INTERIOR_CUBE:
2744 simple_singular_count++;
2746 case ElementType::MULTI_SINGULAR_INTERIOR_CUBE:
2747 multi_singular_count++;
2749 case ElementType::SIMPLE_SINGULAR_BOUNDARY_CUBE:
2752 case ElementType::INTERFACE_CUBE:
2753 case ElementType::MULTI_SINGULAR_BOUNDARY_CUBE:
2754 multi_singular_boundary_count++;
2756 case ElementType::BOUNDARY_POLYTOPE:
2757 non_regular_boundary_count++;
2759 case ElementType::INTERIOR_POLYTOPE:
2760 non_regular_count++;
2762 case ElementType::UNDEFINED:
2766 throw std::runtime_error(
"Unknown element type");
2770 logger().info(
"simplex_count: \t{}", simplex_count);
2771 logger().info(
"regular_count: \t{}", regular_count);
2772 logger().info(
"regular_boundary_count: \t{}", regular_boundary_count);
2773 logger().info(
"simple_singular_count: \t{}", simple_singular_count);
2774 logger().info(
"multi_singular_count: \t{}", multi_singular_count);
2775 logger().info(
"boundary_count: \t{}", boundary_count);
2776 logger().info(
"multi_singular_boundary_count: \t{}", multi_singular_boundary_count);
2777 logger().info(
"non_regular_count: \t{}", non_regular_count);
2778 logger().info(
"non_regular_boundary_count: \t{}", non_regular_boundary_count);
2779 logger().info(
"undefined_count: \t{}", undefined_count);
2784 const nlohmann::json &args,
2785 const int n_bases,
const int n_pressure_bases,
2786 const Eigen::MatrixXd &sol,
2788 const Eigen::VectorXi &disc_orders,
2791 const std::string &formulation,
2792 const bool isoparametric,
2793 const int sol_at_node_id,
2799 j[
"geom_order"] = mesh.
orders().size() > 0 ? mesh.
orders().maxCoeff() : 1;
2800 j[
"geom_order_min"] = mesh.
orders().size() > 0 ? mesh.
orders().minCoeff() : 1;
2801 j[
"discr_order_min"] = disc_orders.minCoeff();
2802 j[
"discr_order_max"] = disc_orders.maxCoeff();
2803 j[
"iso_parametric"] = isoparametric;
2804 j[
"problem"] = problem.
name();
2805 j[
"mat_size"] = mat_size;
2806 j[
"num_bases"] = n_bases;
2807 j[
"num_pressure_bases"] = n_pressure_bases;
2808 j[
"num_non_zero"] = nn_zero;
2809 j[
"num_flipped"] = n_flipped;
2810 j[
"num_dofs"] = num_dofs;
2814 j[
"num_p1"] = (disc_orders.array() == 1).count();
2815 j[
"num_p2"] = (disc_orders.array() == 2).count();
2816 j[
"num_p3"] = (disc_orders.array() == 3).count();
2817 j[
"num_p4"] = (disc_orders.array() == 4).count();
2818 j[
"num_p5"] = (disc_orders.array() == 5).count();
2820 j[
"mesh_size"] = mesh_size;
2821 j[
"max_angle"] = max_angle;
2823 j[
"sigma_max"] = sigma_max;
2824 j[
"sigma_min"] = sigma_min;
2825 j[
"sigma_avg"] = sigma_avg;
2827 j[
"min_edge_length"] = min_edge_length;
2828 j[
"average_edge_length"] = average_edge_length;
2830 j[
"err_l2"] = l2_err;
2831 j[
"err_h1"] = h1_err;
2832 j[
"err_h1_semi"] = h1_semi_err;
2833 j[
"err_linf"] = linf_err;
2834 j[
"err_linf_grad"] = grad_max_err;
2835 j[
"err_lp"] = lp_err;
2837 j[
"spectrum"] = {spectrum(0), spectrum(1), spectrum(2), spectrum(3)};
2838 j[
"spectrum_condest"] = std::abs(spectrum(3)) / std::abs(spectrum(0));
2851 j[
"solver_info"] = solver_info;
2853 j[
"count_simplex"] = simplex_count;
2854 j[
"count_regular"] = regular_count;
2855 j[
"count_regular_boundary"] = regular_boundary_count;
2856 j[
"count_simple_singular"] = simple_singular_count;
2857 j[
"count_multi_singular"] = multi_singular_count;
2858 j[
"count_boundary"] = boundary_count;
2859 j[
"count_non_regular_boundary"] = non_regular_boundary_count;
2860 j[
"count_non_regular"] = non_regular_count;
2861 j[
"count_undefined"] = undefined_count;
2862 j[
"count_multi_singular_boundary"] = multi_singular_boundary_count;
2864 j[
"is_simplicial"] = mesh.
n_elements() == simplex_count;
2866 j[
"peak_memory"] =
getPeakRSS() / (1024 * 1024);
2870 std::vector<double> mmin(actual_dim);
2871 std::vector<double> mmax(actual_dim);
2873 for (
int d = 0; d < actual_dim; ++d)
2875 mmin[d] = std::numeric_limits<double>::max();
2876 mmax[d] = -std::numeric_limits<double>::max();
2879 for (
int i = 0; i < sol.size(); i += actual_dim)
2881 for (
int d = 0; d < actual_dim; ++d)
2883 mmin[d] = std::min(mmin[d], sol(i + d));
2884 mmax[d] = std::max(mmax[d], sol(i + d));
2888 std::vector<double> sol_at_node(actual_dim);
2890 if (sol_at_node_id >= 0)
2892 const int node_id = sol_at_node_id;
2894 for (
int d = 0; d < actual_dim; ++d)
2896 sol_at_node[d] = sol(node_id * actual_dim + d);
2900 j[
"sol_at_node"] = sol_at_node;
2901 j[
"sol_min"] = mmin;
2902 j[
"sol_max"] = mmax;
2904#if defined(POLYFEM_WITH_CPP_THREADS)
2906#elif defined(POLYFEM_WITH_TBB)
2909 j[
"num_threads"] = 1;
2912 j[
"formulation"] = formulation;
2918 : file(path), solve_data(solve_data)
2923 file << name <<
",";
2925 file <<
"total_energy" << std::endl;
2942 file << ((form && form->enabled()) ? form->value(sol) : 0) / s <<
",";
2949 : file(path), state(state), t0(t0), dt(dt)
2951 file <<
"step,time,forward,remeshing,global_relaxation,peak_mem,#V,#T" << std::endl;
2975 const double peak_mem =
getPeakRSS() / double(1 << 30);
2978 file << fmt::format(
2979 "{},{},{},{},{},{},{},{}\n",
2980 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 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