PolyFEM
Loading...
Searching...
No Matches
OutData.cpp
Go to the documentation of this file.
1#include "OutData.hpp"
2
3#include <tuple>
4#include <utility>
5
6#include <array>
7#include <map>
8#include <set>
9
10#include "Evaluator.hpp"
11#include "MatrixIO.hpp"
12
17
19
24
32
37
38#include <paraviewo/VTMWriter.hpp>
39#include <paraviewo/PVDWriter.hpp>
40
41#include <ipc/potentials/normal_adhesion_potential.hpp>
42#include <ipc/potentials/tangential_adhesion_potential.hpp>
43
44#include <SimpleBVH/BVH.hpp>
45
46#include <igl/write_triangle_mesh.h>
47#include <igl/edges.h>
48#include <igl/facet_adjacency_matrix.h>
49#include <igl/connected_components.h>
50
51#include <ipc/ipc.hpp>
52
53#include <algorithm>
54#include <cmath>
55#include <set>
56
57#include <filesystem>
58
59namespace polyfem::io
60{
61 namespace
62 {
63 template <typename... MeshData>
64 void write_output_mesh(OutGeometryData::WriteJobs *writes,
65 const std::shared_ptr<paraviewo::ParaviewWriter> &writer,
66 const std::string &path, MeshData &&...mesh_data)
67 {
68 auto write = [writer, path, data = std::make_tuple(std::forward<MeshData>(mesh_data)...)] {
69 std::apply([&](const auto &...geometry) {
70 if (!writer->write_mesh(path, geometry...))
71 log_and_throw_error("Unable to write output mesh {}", path);
72 },
73 data);
74 };
75 if (writes)
76 writes->emplace_back(std::move(write));
77 else
78 write();
79 }
80 } // namespace
81
82 bool OutputFieldOptions::export_field(const std::string &field) const
83 {
84 return fields.empty() || std::find(fields.begin(), fields.end(), field) != fields.end();
85 }
86
87 using CellType = paraviewo::CellType;
88 using CellElement = paraviewo::CellElement;
89
90 namespace
91 {
92 void add_output_fields(
93 paraviewo::ParaviewWriter &writer,
94 const OutputSample &sample,
95 const OutputFieldFunction &output_fields)
96 {
97 if (!output_fields)
98 return;
99
100 for (const OutputField &field : output_fields(sample))
101 {
102 if (field.values.rows() <= 0)
103 continue;
104
105 const int expected_rows =
106 field.association == OutputField::Association::Cell
107 ? sample.cell_count
108 : sample.points.rows();
109 if (field.values.rows() != expected_rows)
110 {
111 logger().warn(
112 "Skipping output field '{}' with {} rows; expected {} {} rows",
113 field.name, field.values.rows(), expected_rows,
114 field.association == OutputField::Association::Cell ? "cell" : "point");
115 continue;
116 }
117
118 if (field.association == OutputField::Association::Cell)
119 writer.add_cell_field(field.name, field.values);
120 else
121 writer.add_field(field.name, field.values);
122 }
123 }
124
125 void avoid_pyramid_apex(Eigen::MatrixXd &points)
126 {
127 assert(points.cols() == 3);
128 constexpr double eps = 1e-8;
129 for (int i = 0; i < points.rows(); ++i)
130 {
131 if (std::abs(points(i, 2) - 1.0) < eps)
132 points(i, 2) = 1.0 - eps;
133 }
134 }
135
136 void pyramid_nodes_for_output(const int order, Eigen::MatrixXd &points)
137 {
138 autogen::pyramid_nodes_3d(order, points);
139 avoid_pyramid_apex(points);
140 }
141
142 // ------------------------------------------------------------------
143 // helpers for the hybrid (prism/pyramid) collision-proxy paths
144 // ------------------------------------------------------------------
145
146 // face/edge parameters are fractions k/n with n <= 8, so coordinates
147 // in units of 1/PROXY_PARAM_SCALE are exact integers (lcm of 1..8)
148 constexpr long PROXY_PARAM_SCALE = 840;
149
150 int prism_q_order(const basis::ElementBases &b)
151 {
152 const int p = b.bases.empty() ? 1 : b.bases.front().order();
153 const int n_tri = (p + 1) * (p + 2) / 2;
154 const int q = (n_tri > 0 && b.bases.size() % n_tri == 0) ? int(b.bases.size()) / n_tri - 1 : p;
155 return std::max(1, q);
156 }
157
158 // reference-node layout of an element (vertices first); false if unsupported
159 bool element_ref_nodes(const mesh::Mesh &mesh, const int el, const basis::ElementBases &b, Eigen::MatrixXd &ref_nodes)
160 {
161 const int p = b.bases.empty() ? 1 : b.bases.front().order();
162 if (mesh.is_simplex(el))
163 autogen::p_nodes_3d(p, ref_nodes);
164 else if (mesh.is_cube(el))
165 autogen::q_nodes_3d(p, ref_nodes);
166 else if (mesh.is_prism(el))
167 autogen::prism_nodes_3d(p, prism_q_order(b), ref_nodes);
168 else if (mesh.is_pyramid(el))
169 autogen::pyramid_nodes_3d(p, ref_nodes);
170 else
171 return false;
172 return ref_nodes.rows() == long(b.bases.size());
173 }
174
175 int element_n_vertices(const mesh::Mesh &mesh, const int el)
176 {
177 if (mesh.is_simplex(el))
178 return 4;
179 if (mesh.is_pyramid(el))
180 return 5;
181 if (mesh.is_prism(el))
182 return 6;
183 assert(mesh.is_cube(el));
184 return 8;
185 }
186
187 // local vertex pairs forming the element's edges, derived from the
188 // reference vertex coordinates (no vertex-ordering assumptions)
189 std::vector<std::pair<int, int>> element_ref_edges(const mesh::Mesh &mesh, const int el, const Eigen::MatrixXd &ref_nodes)
190 {
191 const int nv = element_n_vertices(mesh, el);
192 const auto n_coord_diffs = [&](int a, int b) {
193 int d = 0;
194 for (int c = 0; c < 3; ++c)
195 if (std::abs(ref_nodes(a, c) - ref_nodes(b, c)) > 1e-12)
196 ++d;
197 return d;
198 };
199 int apex = -1;
200 if (mesh.is_pyramid(el))
201 for (int a = 0; a < nv; ++a)
202 if (std::abs(ref_nodes(a, 2) - 1.0) < 1e-12)
203 apex = a;
204
205 std::vector<std::pair<int, int>> edges;
206 for (int a = 0; a < nv; ++a)
207 {
208 for (int b = a + 1; b < nv; ++b)
209 {
210 bool is_edge;
211 if (mesh.is_simplex(el)) // every vertex pair
212 is_edge = true;
213 else if (mesh.is_prism(el)) // triangle x [0,1]
214 is_edge = std::abs(ref_nodes(a, 2) - ref_nodes(b, 2)) < 1e-12
215 || (std::abs(ref_nodes(a, 0) - ref_nodes(b, 0)) < 1e-12
216 && std::abs(ref_nodes(a, 1) - ref_nodes(b, 1)) < 1e-12);
217 else if (mesh.is_pyramid(el)) // base square + base-to-apex
218 is_edge = (a == apex || b == apex) || n_coord_diffs(a, b) == 1;
219 else // hex
220 is_edge = n_coord_diffs(a, b) == 1;
221 if (is_edge)
222 edges.emplace_back(a, b);
223 }
224 }
225 return edges;
226 }
227
228 // For every mesh edge, keyed by its endpoint DOFs (smaller first): the
229 // owned edge-interior DOFs located on it as (parameter from the
230 // smaller-DOF endpoint in units of 1/PROXY_PARAM_SCALE, dof, node
231 // position), sorted by parameter. Built from ALL elements: an edge on
232 // the domain boundary can get its DOFs from an interior element (e.g. a
233 // prism wedged between two promoted tets). Stitched nodes
234 // (glob.size() != 1, no DOF of their own) are not registered.
235 using EdgeDofs = std::vector<std::tuple<long, int, Eigen::Vector3d>>;
236 std::map<std::pair<int, int>, EdgeDofs> build_edge_dofs(const mesh::Mesh &mesh, const std::vector<basis::ElementBases> &bases)
237 {
238 std::map<std::pair<int, int>, EdgeDofs> edge_dofs;
239 Eigen::MatrixXd ref_nodes;
240 for (int el = 0; el < int(bases.size()); ++el)
241 {
242 const basis::ElementBases &b = bases[el];
243 if (b.bases.empty() || !element_ref_nodes(mesh, el, b, ref_nodes))
244 continue;
245
246 const int nv = element_n_vertices(mesh, el);
247 std::vector<int> vd(nv, -1);
248 bool ok = true;
249 for (int i = 0; i < nv; ++i)
250 {
251 const auto &glob = b.bases[i].global();
252 assert(glob.size() == 1); // vertices always own their DOF
253 if (glob.size() != 1)
254 {
255 ok = false;
256 break;
257 }
258 vd[i] = glob.front().index;
259 }
260 if (!ok)
261 continue;
262
263 const auto edges = element_ref_edges(mesh, el, ref_nodes);
264 for (int j = nv; j < int(b.bases.size()); ++j)
265 {
266 const auto &glob = b.bases[j].global();
267 if (glob.size() != 1)
268 continue;
269 const Eigen::RowVector3d r = ref_nodes.row(j);
270 for (const auto &e : edges)
271 {
272 const Eigen::RowVector3d pa = ref_nodes.row(e.first);
273 const Eigen::RowVector3d d = ref_nodes.row(e.second) - pa;
274 const double t = (r - pa).dot(d) / d.squaredNorm();
275 if (t < 1e-9 || t > 1 - 1e-9 || ((r - pa) - t * d).norm() > 1e-9)
276 continue; // not on this edge
277 long tl = std::lround(t * PROXY_PARAM_SCALE);
278 assert(std::abs(t * PROXY_PARAM_SCALE - tl) < 1e-6);
279 int va = vd[e.first], vb = vd[e.second];
280 if (va > vb)
281 {
282 std::swap(va, vb);
283 tl = PROXY_PARAM_SCALE - tl;
284 }
285 EdgeDofs &ed = edge_dofs[{va, vb}];
286 const int dof = glob.front().index;
287 bool present = false;
288 for (const auto &existing : ed)
289 if (std::get<1>(existing) == dof)
290 {
291 assert(std::get<0>(existing) == tl);
292 present = true;
293 break;
294 }
295 if (!present)
296 ed.emplace_back(tl, dof, glob.front().node.transpose());
297 break;
298 }
299 }
300 }
301 for (auto &kv : edge_dofs)
302 std::sort(kv.second.begin(), kv.second.end(),
303 [](const EdgeDofs::value_type &x, const EdgeDofs::value_type &y) { return std::get<0>(x) < std::get<0>(y); });
304 return edge_dofs;
305 }
306
307 // Structured triangulation for faces whose points form a complete
308 // regular lattice (all faces away from mixed-order interfaces). The
309 // row-wise patterns keep vertex valence balanced -- the lexicographic
310 // sweep below concentrates fan triangles on lex-extreme corners, which
311 // at order 3+ can push one-ring sizes past the smooth-contact
312 // N_VERT_NEIGHBORS_3D cap. Returns false if the points are not a
313 // complete lattice (caller falls back to the sweep).
314 bool triangulate_lattice(const std::vector<std::array<long, 2>> &pts, const int nfv, std::vector<std::array<int, 3>> &tris)
315 {
316 constexpr long S = PROXY_PARAM_SCALE;
317 const int n = int(pts.size());
318 std::map<std::array<long, 2>, int> id;
319 for (int i = 0; i < n; ++i)
320 if (!id.emplace(pts[i], i).second)
321 return false;
322 tris.clear();
323
324 if (nfv == 3)
325 {
326 // n == (k+1)(k+2)/2 for a complete triangular lattice of order k
327 const int k = int(std::lround((std::sqrt(8.0 * n + 1.0) - 3.0) / 2.0));
328 if ((k + 1) * (k + 2) / 2 != n || k < 1 || S % k != 0)
329 return false;
330 const long h = S / k;
331 const auto at = [&](int i, int j) -> int {
332 const auto it = id.find({{i * h, j * h}});
333 return it == id.end() ? -1 : it->second;
334 };
335 for (int j = 0; j <= k; ++j)
336 for (int i = 0; i <= k - j; ++i)
337 if (at(i, j) < 0)
338 return false;
339 for (int j = 0; j < k; ++j)
340 {
341 for (int i = 0; i < k - j; ++i)
342 {
343 tris.push_back({{at(i, j), at(i + 1, j), at(i, j + 1)}});
344 if (i + j < k - 1)
345 tris.push_back({{at(i + 1, j), at(i + 1, j + 1), at(i, j + 1)}});
346 }
347 }
348 return true;
349 }
350
351 // quad: complete (k1+1) x (k2+1) tensor grid, possibly anisotropic
352 std::set<long> us, vs;
353 for (const auto &p : pts)
354 {
355 us.insert(p[0]);
356 vs.insert(p[1]);
357 }
358 const int k1 = int(us.size()) - 1, k2 = int(vs.size()) - 1;
359 if (k1 < 1 || k2 < 1 || (k1 + 1) * (k2 + 1) != n || S % k1 != 0 || S % k2 != 0)
360 return false;
361 const long h1 = S / k1, h2 = S / k2;
362 const auto at = [&](int i, int j) -> int {
363 const auto it = id.find({{i * h1, j * h2}});
364 return it == id.end() ? -1 : it->second;
365 };
366 for (int j = 0; j <= k2; ++j)
367 for (int i = 0; i <= k1; ++i)
368 if (at(i, j) < 0)
369 return false;
370 for (int j = 0; j < k2; ++j)
371 {
372 for (int i = 0; i < k1; ++i)
373 {
374 tris.push_back({{at(i, j), at(i + 1, j), at(i, j + 1)}});
375 tris.push_back({{at(i + 1, j + 1), at(i, j + 1), at(i + 1, j)}});
376 }
377 }
378 return true;
379 }
380
381 // Triangulate a 2D point set in convex position (boundary points lie on
382 // the convex hull, possibly collinear; interior points allowed) into
383 // strictly positive-area CCW triangles via an incremental lexicographic
384 // sweep. Collinear boundary chains are preserved -- no triangle edge
385 // ever spans a boundary point -- which is what keeps neighboring faces
386 // of the proxy conforming. Coordinates must be exact integers.
387 void triangulate_convex_pointset(const std::vector<std::array<long, 2>> &pts, std::vector<std::array<int, 3>> &tris)
388 {
389 const int n = int(pts.size());
390 tris.clear();
391 std::vector<int> order(n);
392 for (int i = 0; i < n; ++i)
393 order[i] = i;
394 std::sort(order.begin(), order.end(), [&](int a, int b) { return pts[a] < pts[b]; });
395 const auto orient = [&](int a, int b, int c) -> long long {
396 return (long long)(pts[b][0] - pts[a][0]) * (pts[c][1] - pts[a][1])
397 - (long long)(pts[b][1] - pts[a][1]) * (pts[c][0] - pts[a][0]);
398 };
399
400 // initial (possibly collinear) chain
401 std::vector<int> hull;
402 int k = 0;
403 for (; k < n; ++k)
404 {
405 if (hull.size() >= 2 && orient(hull[0], hull[1], order[k]) != 0)
406 break;
407 hull.push_back(order[k]);
408 }
409 if (k == n)
410 return; // all points collinear: nothing to emit
411
412 // attach the first off-line point: fan over the chain, make hull CCW
413 {
414 const int p = order[k];
415 const bool left = orient(hull[0], hull[1], p) > 0;
416 for (int i = 0; i + 1 < int(hull.size()); ++i)
417 {
418 if (left)
419 tris.push_back({{hull[i], hull[i + 1], p}});
420 else
421 tris.push_back({{hull[i + 1], hull[i], p}});
422 }
423 if (!left)
424 std::reverse(hull.begin(), hull.end());
425 hull.push_back(p);
426 ++k;
427 }
428
429 for (; k < n; ++k)
430 {
431 const int p = order[k];
432 const int m = int(hull.size());
433 // visible hull edges: p strictly right of a->b on the CCW cycle
434 std::vector<bool> vis(m);
435 for (int i = 0; i < m; ++i)
436 vis[i] = orient(hull[i], hull[(i + 1) % m], p) < 0;
437 int s = 0;
438 while (s < m && !(vis[s] && !vis[(s + m - 1) % m]))
439 ++s;
440 assert(s < m); // p is outside the hull (lexicographic order)
441 int e = s;
442 while (vis[e % m])
443 {
444 // orient(a, b, p) < 0 => (a, p, b) is CCW
445 tris.push_back({{hull[e % m], p, hull[(e + 1) % m]}});
446 ++e;
447 }
448 // replace the strictly-visible part of the hull with p
449 std::vector<int> new_hull;
450 new_hull.push_back(p);
451 for (int i = e % m; i != s; i = (i + 1) % m)
452 new_hull.push_back(hull[i]);
453 new_hull.push_back(hull[s]);
454 hull.swap(new_hull);
455 }
456 }
457
458 } // namespace
459
461 const mesh::Mesh &mesh, const int n_bases,
462 const std::vector<basis::ElementBases> &bases,
463 const std::vector<basis::ElementBases> &geom_bases,
464 const std::vector<mesh::LocalBoundary> &total_local_boundary,
465 Eigen::MatrixXd &node_positions, Eigen::MatrixXi &boundary_edges,
466 Eigen::MatrixXi &boundary_triangles,
467 std::vector<Eigen::Triplet<double>> &displacement_map_entries,
468 const int sampling_order)
469 {
470 assert(!mesh.is_volume());
471 if (mesh.has_poly())
472 {
473 logger().warn("Sampled 2D collision mesh requires triangle or quadrilateral elements; falling back to the standard boundary extraction");
474 extract_boundary_mesh(mesh, n_bases, bases, total_local_boundary,
475 node_positions, boundary_edges, boundary_triangles, displacement_map_entries);
476 return;
477 }
478 if (sampling_order > 0)
479 {
480 displacement_map_entries.clear();
481 std::map<std::array<int, 3>, int> sample_ids;
482 std::vector<Eigen::RowVector2d> vertices;
483 std::vector<std::pair<int, int>> edges;
484 std::set<int> visited_edges;
485 for (const auto &lb : total_local_boundary)
486 {
487 const int el = lb.element_id();
488 const auto &b = bases[el];
489 if (b.bases.empty())
490 continue;
491 Eigen::MatrixXd ref_nodes;
492 if (mesh.is_simplex(el))
493 autogen::p_nodes_2d(b.bases.front().order(), ref_nodes);
494 else if (mesh.is_cube(el))
495 autogen::q_nodes_2d(b.bases.front().order(), ref_nodes);
496 else
497 log_and_throw_error("Sampled 2D collision mesh requires triangle or quadrilateral elements.");
498 for (int j = 0; j < lb.size(); ++j)
499 {
500 const int eid = lb.global_primitive_id(j);
501 if (!visited_edges.insert(eid).second)
502 continue;
503 const auto nodes = b.local_nodes_for_primitive(eid, mesh);
504 const int first = nodes(0), last = nodes(nodes.size() - 1);
505 // Corner identity is topological even when its basis depends on multiple DOFs.
506 const int v0 = mesh.face_vertex(el, first);
507 const int v1 = mesh.face_vertex(el, last);
508 Eigen::MatrixXd points(sampling_order + 1, 2), positions;
509 for (int i = 0; i <= sampling_order; ++i)
510 {
511 const double t = double(i) / sampling_order;
512 points.row(i) = (1 - t) * ref_nodes.row(first) + t * ref_nodes.row(last);
513 }
514 geom_bases[el].eval_geom_mapping(points, positions);
515 std::vector<assembler::AssemblyValues> values;
516 b.evaluate_bases(points, values);
517 int previous = -1;
518 for (int i = 0; i <= sampling_order; ++i)
519 {
520 // Share corners topologically, not by coordinate tolerance.
521 const std::array<int, 3> key = i == 0 ? std::array<int, 3>{{0, v0, 0}}
522 : i == sampling_order ? std::array<int, 3>{{0, v1, 0}}
523 : std::array<int, 3>{{1, eid, i}};
524 const auto [it, inserted] = sample_ids.emplace(key, int(vertices.size()));
525 const int row = it->second;
526 if (inserted)
527 {
528 vertices.push_back(positions.row(i));
529 for (size_t k = 0; k < values.size(); ++k)
530 for (const auto &g : b.bases[k].global())
531 {
532 const double weight = values[k].val(i) * g.val;
533 if (weight != 0)
534 displacement_map_entries.emplace_back(row, g.index, weight);
535 }
536 }
537 if (previous >= 0)
538 edges.emplace_back(previous, row);
539 previous = row;
540 }
541 }
542 }
543 node_positions.resize(vertices.size(), 2);
544 for (int i = 0; i < int(vertices.size()); ++i)
545 node_positions.row(i) = vertices[i];
546 boundary_edges.resize(edges.size(), 2);
547 for (int i = 0; i < int(edges.size()); ++i)
548 boundary_edges.row(i) << edges[i].first, edges[i].second;
549 boundary_triangles.resize(0, 0);
550 return;
551 }
552
553 extract_boundary_mesh(mesh, n_bases, bases, total_local_boundary,
554 node_positions, boundary_edges, boundary_triangles, displacement_map_entries);
555
556 // Keep the nodal boundary connectivity, but evaluate the FE field at
557 // those reference nodes instead of treating its coefficients as values.
558 std::vector<bool> visited(n_bases, false);
559 for (const auto &lb : total_local_boundary)
560 {
561 const int el = lb.element_id();
562 const auto &b = bases[el];
563 if (b.bases.empty())
564 continue;
565 Eigen::MatrixXd points, positions;
566 if (mesh.is_simplex(el))
567 autogen::p_nodes_2d(b.bases.front().order(), points);
568 else if (mesh.is_cube(el))
569 autogen::q_nodes_2d(b.bases.front().order(), points);
570 else
571 log_and_throw_error("Sampled 2D collision mesh requires triangle or quadrilateral elements.");
572 geom_bases[el].eval_geom_mapping(points, positions);
573 std::vector<assembler::AssemblyValues> values;
574 b.evaluate_bases(points, values);
575 for (int j = 0; j < lb.size(); ++j)
576 {
577 const auto nodes = b.local_nodes_for_primitive(lb.global_primitive_id(j), mesh);
578 for (const int node : nodes)
579 {
580 const auto &global = b.bases[node].global();
581 if (global.size() != 1)
582 continue;
583 const int row = global.front().index;
584 if (visited[row])
585 continue;
586 visited[row] = true;
587 node_positions.row(row) = positions.row(node);
588 for (size_t k = 0; k < values.size(); ++k)
589 for (const auto &g : b.bases[k].global())
590 {
591 const double weight = values[k].val(node) * g.val;
592 if (weight != 0)
593 displacement_map_entries.emplace_back(row, g.index, weight);
594 }
595 }
596 }
597 }
598 }
599
601 const mesh::Mesh &mesh,
602 const int n_bases,
603 const std::vector<basis::ElementBases> &bases,
604 const std::vector<mesh::LocalBoundary> &total_local_boundary,
605 Eigen::MatrixXd &node_positions,
606 Eigen::MatrixXi &boundary_edges,
607 Eigen::MatrixXi &boundary_triangles,
608 std::vector<Eigen::Triplet<double>> &displacement_map_entries,
609 const int sampling_order,
610 const std::vector<basis::ElementBases> *geom_bases)
611 {
612 using namespace polyfem::mesh;
613
614 // Sample every boundary face on a uniform lattice of the globally
615 // maximal order M through the element bases: the proxy is conforming
616 // and watertight regardless of order mismatches across interfaces
617 // (every shared edge is split into M chords on both sides), stitched
618 // interface nodes are handled intrinsically by the basis evaluation,
619 // and the displacement map carries each proxy vertex's (possibly
620 // weighted) dependence on the real DOFs.
621 if (!mesh.is_volume() || mesh.has_poly()
622 || !dynamic_cast<const Mesh3D &>(mesh).is_conforming())
623 {
624 logger().warn("max_order collision-proxy sampling requires a conforming volume mesh without polytopes; falling back to the standard boundary extraction");
625 extract_boundary_mesh(mesh, n_bases, bases, total_local_boundary,
626 node_positions, boundary_edges, boundary_triangles, displacement_map_entries);
627 return;
628 }
629
630 displacement_map_entries.clear();
631 const Mesh3D &mesh3d = dynamic_cast<const Mesh3D &>(mesh);
632
633 int M = 1;
634 if (sampling_order > 0)
635 M = sampling_order; // explicit lattice order (finer OR coarser than the elements)
636 else
637 for (const LocalBoundary &lb : total_local_boundary)
638 {
639 const basis::ElementBases &b = bases[lb.element_id()];
640 if (b.bases.empty())
641 continue;
642 int o = b.bases.front().order();
643 if (mesh.is_prism(lb.element_id()))
644 o = std::max(o, prism_q_order(b));
645 M = std::max(M, o);
646 }
647
648 // samples shared between neighboring faces merge combinatorially, by
649 // the mesh primitive they lie on -- {0, vertex_id} for face corners,
650 // {1, vmin, vmax, step-from-vmin} for edge samples (every face uses
651 // the same global lattice order M, so steps coincide exactly), and
652 // {2, face_id, i, r} for face-interior samples (a boundary face
653 // belongs to exactly one element) -- no floating-point tolerance
654 std::map<std::array<int, 4>, int> vertex_id;
655 std::vector<Eigen::Vector3d> vertices;
656 std::vector<std::tuple<int, int, int>> proxy_tris;
657
658 for (const LocalBoundary &lb : total_local_boundary)
659 {
660 const int el = lb.element_id();
661 const basis::ElementBases &b = bases[el];
662 Eigen::MatrixXd ref_nodes;
663 if (b.bases.empty() || !element_ref_nodes(mesh, el, b, ref_nodes))
664 continue;
665
666 // the rational pyramid bases are 0/0 at the apex (z=1), which is a
667 // corner of every triangular pyramid face; apex samples are instead
668 // evaluated below via the nodal limit (apex basis 1, all others 0)
669 int apex_node = -1;
670 if (mesh.is_pyramid(el))
671 for (int i = 0; i < ref_nodes.rows(); ++i)
672 if (std::abs(ref_nodes(i, 2) - 1.0) < 1e-12)
673 {
674 apex_node = i;
675 break;
676 }
677
678 for (int j = 0; j < lb.size(); ++j)
679 {
680 const int eid = lb.global_primitive_id(j);
681 const int nfv = mesh3d.n_face_vertices(eid);
682 assert(nfv == 3 || nfv == 4);
683
685 for (int lf = 0; lf < mesh3d.n_cell_faces(el); ++lf)
686 {
687 nav = mesh3d.get_index_from_element(el, lf, 0);
688 if (nav.face == eid)
689 break;
690 }
691 assert(nav.face == eid);
692 std::vector<int> gv(nfv);
693 {
694 Navigation3D::Index cur = nav;
695 for (int k = 0; k < nfv; ++k)
696 {
697 gv[k] = cur.vertex;
698 cur = mesh3d.next_around_face(cur);
699 }
700 }
701
702 // Map the global face vertices to canonical element-reference
703 // vertices. This cannot use the first entries of `nodes`: nodal
704 // Lagrange faces store corners first, but spline faces use tensor-grid
705 // ordering (where the first four entries are generally not corners).
706 Eigen::MatrixXd ref_vertices;
707 std::vector<int> local_to_global;
708 if (mesh.is_simplex(el))
709 {
710 autogen::p_nodes_3d(1, ref_vertices);
711 const auto vertices = mesh3d.get_ordered_vertices_from_tet(el);
712 local_to_global.assign(vertices.begin(), vertices.end());
713 }
714 else if (mesh.is_cube(el))
715 {
716 autogen::q_nodes_3d(1, ref_vertices);
717 const auto vertices = mesh3d.get_ordered_vertices_from_hex(el);
718 local_to_global.assign(vertices.begin(), vertices.end());
719 }
720 else if (mesh.is_prism(el))
721 {
722 autogen::prism_nodes_3d(1, 1, ref_vertices);
723 const auto vertices = mesh3d.get_ordered_vertices_from_prism(el);
724 local_to_global.assign(vertices.begin(), vertices.end());
725 }
726 else
727 {
728 assert(mesh.is_pyramid(el));
729 autogen::pyramid_nodes_3d(1, ref_vertices);
730 const auto vertices = mesh3d.get_ordered_vertices_from_pyramid(el);
731 local_to_global.assign(vertices.begin(), vertices.end());
732 }
733
734 std::vector<Eigen::RowVector3d> c(nfv);
735 for (int k = 0; k < nfv; ++k)
736 {
737 const auto it = std::find(local_to_global.begin(), local_to_global.end(), gv[k]);
738 assert(it != local_to_global.end());
739 c[k] = ref_vertices.row(std::distance(local_to_global.begin(), it));
740 }
741
742 Eigen::MatrixXd pts;
743 std::vector<std::array<int, 2>> coords;
744 std::vector<std::tuple<int, int, int>> local_tris;
745 if (nfv == 3)
746 {
747 pts.resize((M + 1) * (M + 2) / 2, 3);
748 coords.resize(pts.rows());
749 std::vector<int> off(M + 2, 0);
750 for (int r = 0; r <= M; ++r)
751 off[r + 1] = off[r] + (M + 1 - r);
752 for (int r = 0; r <= M; ++r)
753 for (int i = 0; i <= M - r; ++i)
754 {
755 pts.row(off[r] + i) = c[0] + (double(i) / M) * (c[1] - c[0]) + (double(r) / M) * (c[2] - c[0]);
756 coords[off[r] + i] = {{i, r}};
757 }
758 for (int r = 0; r < M; ++r)
759 {
760 for (int i = 0; i < M - r; ++i)
761 {
762 local_tris.emplace_back(off[r] + i, off[r] + i + 1, off[r + 1] + i);
763 if (i + r < M - 1)
764 local_tris.emplace_back(off[r] + i + 1, off[r + 1] + i + 1, off[r + 1] + i);
765 }
766 }
767 }
768 else
769 {
770 pts.resize((M + 1) * (M + 1), 3);
771 coords.resize(pts.rows());
772 const auto gid = [M](const int i, const int r) { return r * (M + 1) + i; };
773 for (int r = 0; r <= M; ++r)
774 {
775 for (int i = 0; i <= M; ++i)
776 {
777 const double u = double(i) / M, v = double(r) / M;
778 pts.row(gid(i, r)) = (1 - u) * (1 - v) * c[0] + u * (1 - v) * c[1] + u * v * c[2] + (1 - u) * v * c[3];
779 coords[gid(i, r)] = {{i, r}};
780 }
781 }
782 for (int r = 0; r < M; ++r)
783 {
784 for (int i = 0; i < M; ++i)
785 {
786 local_tris.emplace_back(gid(i, r), gid(i + 1, r), gid(i, r + 1));
787 local_tris.emplace_back(gid(i + 1, r + 1), gid(i, r + 1), gid(i + 1, r));
788 }
789 }
790 }
791
792 std::vector<polyfem::assembler::AssemblyValues> vals;
793 b.evaluate_bases(pts, vals);
794 Eigen::MatrixXd mapped_positions;
795 if (geom_bases)
796 {
797 // The geometry may have a different basis/order than displacement.
798 // Avoid the rational pyramid apex singularity during evaluation.
799 Eigen::MatrixXd geometry_points = pts;
800 if (apex_node >= 0)
801 for (int s = 0; s < pts.rows(); ++s)
802 if (std::abs(pts(s, 2) - 1.0) < 1e-12)
803 geometry_points.row(s).setZero();
804 geom_bases->at(el).eval_geom_mapping(geometry_points, mapped_positions);
805 if (apex_node >= 0)
806 for (int s = 0; s < pts.rows(); ++s)
807 if (std::abs(pts(s, 2) - 1.0) < 1e-12)
808 mapped_positions.row(s) = mesh3d.point(mesh3d.get_ordered_vertices_from_pyramid(el).back());
809 }
810
811 const auto edge_key = [M](const int va, const int vb, const int step) {
812 return va < vb ? std::array<int, 4>{{1, va, vb, step}}
813 : std::array<int, 4>{{1, vb, va, M - step}};
814 };
815
816 std::vector<int> ids(pts.rows());
817 for (int s = 0; s < pts.rows(); ++s)
818 {
819 const int i = coords[s][0], r = coords[s][1];
820 std::array<int, 4> key;
821 if (nfv == 3)
822 {
823 if (r == 0 && i == 0)
824 key = {{0, gv[0], 0, 0}};
825 else if (r == 0 && i == M)
826 key = {{0, gv[1], 0, 0}};
827 else if (r == M)
828 key = {{0, gv[2], 0, 0}};
829 else if (r == 0)
830 key = edge_key(gv[0], gv[1], i);
831 else if (i == 0)
832 key = edge_key(gv[0], gv[2], r);
833 else if (i + r == M)
834 key = edge_key(gv[1], gv[2], r);
835 else
836 key = {{2, eid, i, r}};
837 }
838 else
839 {
840 if (i == 0 && r == 0)
841 key = {{0, gv[0], 0, 0}};
842 else if (i == M && r == 0)
843 key = {{0, gv[1], 0, 0}};
844 else if (i == M && r == M)
845 key = {{0, gv[2], 0, 0}};
846 else if (i == 0 && r == M)
847 key = {{0, gv[3], 0, 0}};
848 else if (r == 0)
849 key = edge_key(gv[0], gv[1], i);
850 else if (i == M)
851 key = edge_key(gv[1], gv[2], r);
852 else if (r == M)
853 key = edge_key(gv[3], gv[2], i);
854 else if (i == 0)
855 key = edge_key(gv[0], gv[3], r);
856 else
857 key = {{2, eid, i, r}};
858 }
859
860 const auto it = vertex_id.find(key);
861 if (it != vertex_id.end())
862 {
863 ids[s] = it->second;
864 continue;
865 }
866
867 Eigen::Vector3d pos = Eigen::Vector3d::Zero();
868 std::map<int, double> weights;
869 if (apex_node >= 0 && std::abs(pts(s, 2) - 1.0) < 1e-12)
870 {
871 for (const auto &g : b.bases[apex_node].global())
872 {
873 pos += g.val * g.node.transpose();
874 weights[g.index] += g.val;
875 }
876 }
877 else
878 for (size_t i2 = 0; i2 < vals.size(); ++i2)
879 {
880 const double Ni = vals[i2].val(s);
881 if (std::abs(Ni) < 1e-12)
882 continue;
883 for (const auto &g : b.bases[i2].global())
884 {
885 pos += Ni * g.val * g.node.transpose();
886 weights[g.index] += Ni * g.val;
887 }
888 }
889 if (geom_bases)
890 pos = mapped_positions.row(s).transpose();
891 assert(pos.allFinite());
892
893 const int vid = int(vertices.size());
894 vertex_id[key] = vid;
895 vertices.push_back(pos);
896 for (const auto &kv : weights)
897 if (std::abs(kv.second) > 1e-10)
898 displacement_map_entries.emplace_back(vid, kv.first, kv.second);
899 ids[s] = vid;
900 }
901
902 for (const auto &t : local_tris)
903 proxy_tris.emplace_back(ids[std::get<0>(t)], ids[std::get<1>(t)], ids[std::get<2>(t)]);
904 }
905 }
906
907 node_positions.resize(vertices.size(), 3);
908 for (int i = 0; i < int(vertices.size()); ++i)
909 node_positions.row(i) = vertices[i];
910
911 boundary_triangles.resize(proxy_tris.size(), 3);
912 for (int i = 0; i < int(proxy_tris.size()); ++i)
913 boundary_triangles.row(i) << std::get<0>(proxy_tris[i]), std::get<2>(proxy_tris[i]), std::get<1>(proxy_tris[i]);
914
915 if (boundary_triangles.rows() > 0)
916 igl::edges(boundary_triangles, boundary_edges);
917
918 if (const char *dump = getenv("POLYFEM_DUMP_COLLISION_PROXY"))
919 igl::write_triangle_mesh(dump, node_positions, boundary_triangles);
920 }
921
923 const mesh::Mesh &mesh,
924 const int n_bases,
925 const std::vector<basis::ElementBases> &bases,
926 const std::vector<mesh::LocalBoundary> &total_local_boundary,
927 Eigen::MatrixXd &node_positions,
928 Eigen::MatrixXi &boundary_edges,
929 Eigen::MatrixXi &boundary_triangles,
930 std::vector<Eigen::Triplet<double>> &displacement_map_entries)
931 {
932 using namespace polyfem::mesh;
933
934 displacement_map_entries.clear();
935
936 if (mesh.is_volume())
937 {
938 if (mesh.has_poly())
939 {
940 logger().warn("Skipping as the mesh has polygons");
941 return;
942 }
943
944 const bool is_simplicial = mesh.is_simplicial();
945
946 std::vector<Eigen::Vector3d> node_positions_vec;
947 node_positions_vec.reserve(n_bases + (is_simplicial ? 0 : mesh.n_faces()));
948
949 // node_positions.resize(n_bases + (is_simplicial ? 0 : mesh.n_faces()), 3);
950 // node_positions.setZero();
951 const Mesh3D &mesh3d = dynamic_cast<const Mesh3D &>(mesh);
952
953 std::vector<std::tuple<int, int, int>> tris;
954
955 std::vector<bool> visited_node(n_bases, false);
956
957 std::stringstream print_warning;
958
959 // Hybrid (prism/pyramid) meshes: element orders can differ across an
960 // interface (anisotropic prisms promote their tet/pyramid neighbors),
961 // so tessellating each boundary face at its own order produces
962 // T-junctions along shared edges, and stitched interface nodes have
963 // no DOF of their own. Build the proxy from the DOFs on the
964 // boundary instead: every proxy vertex IS a global DOF (weight-1
965 // displacement map), each face edge is subdivided by the DOFs
966 // located on it -- a property of the edge, not of the element
967 // looking at it, so neighboring faces conform by construction --
968 // and face interiors by the element's own owned face nodes.
969 // Stitched nodes are skipped; the DOFs they depend on subdivide the
970 // edge instead.
971 bool has_prism_or_pyramid = false;
972 for (const LocalBoundary &lb : total_local_boundary)
973 {
974 if (mesh.is_prism(lb.element_id()) || mesh.is_pyramid(lb.element_id()))
975 {
976 has_prism_or_pyramid = true;
977 break;
978 }
979 }
980
981 if (has_prism_or_pyramid && mesh3d.is_conforming())
982 {
983 const auto edge_dofs = build_edge_dofs(mesh, bases);
984 constexpr long S = PROXY_PARAM_SCALE;
985
986 const auto emit_dof = [&](const int gindex, const Eigen::Vector3d &pos) {
987 if (gindex >= int(node_positions_vec.size()))
988 node_positions_vec.resize(gindex + 1, Eigen::Vector3d::Zero());
989 node_positions_vec[gindex] = pos;
990 if (!visited_node[gindex])
991 displacement_map_entries.emplace_back(gindex, gindex, 1);
992 visited_node[gindex] = true;
993 };
994
995 Eigen::MatrixXd ref_nodes;
996 for (const LocalBoundary &lb : total_local_boundary)
997 {
998 const int el = lb.element_id();
999 const basis::ElementBases &b = bases[el];
1000 if (b.bases.empty() || !element_ref_nodes(mesh, el, b, ref_nodes))
1001 continue;
1002
1003 for (int j = 0; j < lb.size(); ++j)
1004 {
1005 const int eid = lb.global_primitive_id(j);
1006 const Eigen::VectorXi nodes = b.local_nodes_for_primitive(eid, mesh3d);
1007 const int nfv = mesh3d.n_face_vertices(eid);
1008 assert(nfv == 3 || nfv == 4);
1009 assert(nodes.size() >= nfv);
1010
1011 // exact face parameters (units of 1/S) and the DOF of each point
1012 std::vector<std::array<long, 2>> pts;
1013 std::vector<int> dof;
1014
1015 // face corners come first in the local ordering (cyclic for quads)
1016 std::array<std::array<long, 2>, 4> cp;
1017 if (nfv == 3)
1018 cp = {{{{0, 0}}, {{S, 0}}, {{0, S}}, {{0, 0}}}};
1019 else
1020 cp = {{{{0, 0}}, {{S, 0}}, {{S, S}}, {{0, S}}}};
1021 std::array<int, 4> cd{{-1, -1, -1, -1}};
1022 bool ok = true;
1023 for (int k = 0; k < nfv; ++k)
1024 {
1025 const auto &glob = b.bases[nodes(k)].global();
1026 assert(glob.size() == 1); // face corners always own their DOF
1027 if (glob.size() != 1)
1028 {
1029 ok = false;
1030 break;
1031 }
1032 cd[k] = glob.front().index;
1033 pts.push_back(cp[k]);
1034 dof.push_back(cd[k]);
1035 emit_dof(cd[k], glob.front().node.transpose());
1036 }
1037 if (!ok)
1038 continue;
1039
1040 // edge subdivision: the DOFs located on each face edge
1041 for (int k = 0; k < nfv; ++k)
1042 {
1043 const int va = cd[k], vb = cd[(k + 1) % nfv];
1044 const auto it = edge_dofs.find({std::min(va, vb), std::max(va, vb)});
1045 if (it == edge_dofs.end())
1046 continue;
1047 for (const auto &ed : it->second)
1048 {
1049 const long s = va < vb ? std::get<0>(ed) : S - std::get<0>(ed);
1050 const auto &A = cp[k];
1051 const auto &B = cp[(k + 1) % nfv];
1052 pts.push_back({{(A[0] * (S - s) + B[0] * s) / S, (A[1] * (S - s) + B[1] * s) / S}});
1053 dof.push_back(std::get<1>(ed));
1054 emit_dof(std::get<1>(ed), std::get<2>(ed));
1055 }
1056 }
1057
1058 // owned face-interior nodes at the element's own resolution
1059 // (reference faces are planar parallelograms -> affine map)
1060 const Eigen::RowVector3d c0 = ref_nodes.row(nodes(0));
1061 const Eigen::RowVector3d A3 = ref_nodes.row(nodes(1)) - c0;
1062 const Eigen::RowVector3d B3 = ref_nodes.row(nodes(nfv - 1)) - c0;
1063 const double aa = A3.squaredNorm(), bb = B3.squaredNorm(), ab = A3.dot(B3);
1064 const double det = aa * bb - ab * ab;
1065 for (long n = nfv; n < nodes.size(); ++n)
1066 {
1067 const auto &glob = b.bases[nodes(n)].global();
1068 if (glob.size() != 1)
1069 continue; // stitched interface node
1070 const Eigen::RowVector3d d3 = ref_nodes.row(nodes(n)) - c0;
1071 const double du = d3.dot(A3), dv = d3.dot(B3);
1072 const double u = (du * bb - dv * ab) / det;
1073 const double v = (dv * aa - du * ab) / det;
1074 const long lu = std::lround(u * S), lv = std::lround(v * S);
1075 assert(std::abs(u * S - lu) < 1e-6 && std::abs(v * S - lv) < 1e-6);
1076 // nodes on a face edge already subdivide the edge above
1077 const bool on_edge = nfv == 3
1078 ? (lu == 0 || lv == 0 || lu + lv == S)
1079 : (lu == 0 || lu == S || lv == 0 || lv == S);
1080 if (on_edge)
1081 continue;
1082 pts.push_back({{lu, lv}});
1083 dof.push_back(glob.front().index);
1084 emit_dof(glob.front().index, glob.front().node.transpose());
1085 }
1086
1087 std::vector<std::array<int, 3>> local_tris;
1088 if (!triangulate_lattice(pts, nfv, local_tris))
1089 triangulate_convex_pointset(pts, local_tris);
1090 for (const auto &t : local_tris)
1091 tris.emplace_back(dof[t[0]], dof[t[1]], dof[t[2]]);
1092 }
1093 }
1094
1095 // downstream consumers (e.g. the shape-derivative code) expect every
1096 // FE node to have a row, as the pre-split extraction guaranteed
1097 node_positions_vec.resize(
1098 std::max(node_positions_vec.size(), size_t(n_bases)), Eigen::Vector3d::Zero());
1099
1100 node_positions.resize(node_positions_vec.size(), 3);
1101 for (int i = 0; i < int(node_positions_vec.size()); ++i)
1102 node_positions.row(i) = node_positions_vec[i];
1103
1104 boundary_triangles.resize(tris.size(), 3);
1105 for (int i = 0; i < int(tris.size()); ++i)
1106 boundary_triangles.row(i) << std::get<0>(tris[i]), std::get<2>(tris[i]), std::get<1>(tris[i]);
1107
1108 if (boundary_triangles.rows() > 0)
1109 igl::edges(boundary_triangles, boundary_edges);
1110
1111 if (const char *dump = getenv("POLYFEM_DUMP_COLLISION_PROXY"))
1112 igl::write_triangle_mesh(dump, node_positions, boundary_triangles);
1113
1114 return;
1115 }
1116
1117 for (const LocalBoundary &lb : total_local_boundary)
1118 {
1119 const basis::ElementBases &b = bases[lb.element_id()];
1120
1121 for (int j = 0; j < lb.size(); ++j)
1122 {
1123 const int eid = lb.global_primitive_id(j);
1124 const int lid = lb[j];
1125 const Eigen::VectorXi nodes = b.local_nodes_for_primitive(eid, mesh3d);
1126
1127 if (mesh.is_cube(lb.element_id()))
1128 {
1129 assert(!is_simplicial);
1130 assert(!mesh.has_poly());
1131 std::vector<int> loc_nodes;
1132 RowVectorNd bary = RowVectorNd::Zero(3);
1133
1134 for (long n = 0; n < nodes.size(); ++n)
1135 {
1136 auto &bs = b.bases[nodes(n)];
1137 const auto &glob = bs.global();
1138 if (glob.size() != 1)
1139 continue;
1140
1141 int gindex = glob.front().index;
1142 node_positions_vec.resize(std::max(int(node_positions_vec.size()), gindex + 1));
1143 node_positions_vec[gindex] = glob.front().node;
1144 bary += glob.front().node;
1145 loc_nodes.push_back(gindex);
1146 }
1147
1148 if (loc_nodes.size() != 4)
1149 {
1150 logger().trace("skipping element {} since it is not Q1", eid);
1151 continue;
1152 }
1153
1154 bary /= 4;
1155
1156 const int new_node = n_bases + eid;
1157 node_positions_vec.resize(std::max(int(node_positions_vec.size()), new_node + 1));
1158 node_positions_vec[new_node] = bary;
1159 tris.emplace_back(loc_nodes[1], loc_nodes[0], new_node);
1160 tris.emplace_back(loc_nodes[2], loc_nodes[1], new_node);
1161 tris.emplace_back(loc_nodes[3], loc_nodes[2], new_node);
1162 tris.emplace_back(loc_nodes[0], loc_nodes[3], new_node);
1163
1164 for (int q = 0; q < 4; ++q)
1165 {
1166 if (!visited_node[loc_nodes[q]])
1167 displacement_map_entries.emplace_back(loc_nodes[q], loc_nodes[q], 1);
1168
1169 visited_node[loc_nodes[q]] = true;
1170 displacement_map_entries.emplace_back(new_node, loc_nodes[q], 0.25);
1171 }
1172
1173 continue;
1174 }
1175 else if (mesh.is_prism(lb.element_id()))
1176 {
1177 assert(!is_simplicial);
1178 assert(!mesh.has_poly());
1179 std::vector<int> loc_nodes;
1180 std::vector<int> loc_local_nodes;
1181
1182 for (long n = 0; n < nodes.size(); ++n)
1183 {
1184 auto &bs = b.bases[nodes(n)];
1185 const auto &glob = bs.global();
1186 if (glob.size() != 1)
1187 continue;
1188
1189 int gindex = glob.front().index;
1190 node_positions_vec.resize(std::max(int(node_positions_vec.size()), gindex + 1));
1191 node_positions_vec[gindex] = glob.front().node;
1192 loc_nodes.push_back(gindex);
1193 loc_local_nodes.push_back(nodes(n));
1194 }
1195
1196 auto update_mapping = [&displacement_map_entries, &visited_node](const std::vector<int> &loc_nodes) {
1197 for (int k = 0; k < loc_nodes.size(); ++k)
1198 {
1199 if (!visited_node[loc_nodes[k]])
1200 displacement_map_entries.emplace_back(loc_nodes[k], loc_nodes[k], 1);
1201
1202 visited_node[loc_nodes[k]] = true;
1203 }
1204 };
1205
1206 // tri face
1207 if (lid < 2)
1208 {
1209 if (loc_nodes.size() == 3)
1210 {
1211 tris.emplace_back(loc_nodes[0], loc_nodes[1], loc_nodes[2]);
1212
1213 update_mapping(loc_nodes);
1214 }
1215 else if (loc_nodes.size() == 6)
1216 {
1217 tris.emplace_back(loc_nodes[0], loc_nodes[3], loc_nodes[5]);
1218 tris.emplace_back(loc_nodes[3], loc_nodes[1], loc_nodes[4]);
1219 tris.emplace_back(loc_nodes[4], loc_nodes[2], loc_nodes[5]);
1220 tris.emplace_back(loc_nodes[3], loc_nodes[4], loc_nodes[5]);
1221
1222 update_mapping(loc_nodes);
1223 }
1224 else if (loc_nodes.size() == 10)
1225 {
1226 tris.emplace_back(loc_nodes[0], loc_nodes[3], loc_nodes[8]);
1227 tris.emplace_back(loc_nodes[3], loc_nodes[4], loc_nodes[9]);
1228 tris.emplace_back(loc_nodes[4], loc_nodes[1], loc_nodes[5]);
1229 tris.emplace_back(loc_nodes[5], loc_nodes[6], loc_nodes[9]);
1230 tris.emplace_back(loc_nodes[6], loc_nodes[2], loc_nodes[7]);
1231 tris.emplace_back(loc_nodes[7], loc_nodes[8], loc_nodes[9]);
1232 tris.emplace_back(loc_nodes[8], loc_nodes[3], loc_nodes[9]);
1233 tris.emplace_back(loc_nodes[9], loc_nodes[4], loc_nodes[5]);
1234 tris.emplace_back(loc_nodes[6], loc_nodes[7], loc_nodes[9]);
1235 update_mapping(loc_nodes);
1236 }
1237 else
1238 {
1239 logger().trace("skipping element {} since it is not linear, it has {} nodes", eid, loc_nodes.size());
1240 }
1241 }
1242 else
1243 {
1244 if (loc_nodes.size() < 4 || loc_local_nodes.size() < 4)
1245 {
1246 logger().trace("skipping prism quad face {} since it has only {} complete nodes", eid, loc_nodes.size());
1247 continue;
1248 }
1249
1250 const int p = b.bases.empty() ? -1 : b.bases.front().order();
1251 const int n_tri_nodes = (p + 1) * (p + 2) / 2;
1252 const int q = n_tri_nodes > 0 && b.bases.size() % n_tri_nodes == 0 ? int(b.bases.size()) / n_tri_nodes - 1 : -1;
1253
1254 if (p < 1 || p > 3 || q < 1 || q > 3 || (p == 3 && q == 3))
1255 {
1256 logger().trace("skipping prism quad face {} with unsupported p={}, q={}", eid, p, q);
1257 continue;
1258 }
1259
1260 auto is_vertical_prism_edge = [](const int a, const int b) {
1261 return (a >= 0 && a < 3 && b == a + 3) || (b >= 0 && b < 3 && a == b + 3);
1262 };
1263
1264 std::vector<int> edge_orders(4);
1265 for (int k = 0; k < 4; ++k)
1266 edge_orders[k] = is_vertical_prism_edge(loc_local_nodes[k], loc_local_nodes[(k + 1) % 4]) ? q : p;
1267
1268 const int u_order = edge_orders[0];
1269 const int v_order = edge_orders[1];
1270 const int expected_nodes = (u_order + 1) * (v_order + 1);
1271 if (loc_nodes.size() != expected_nodes || edge_orders[0] != edge_orders[2] || edge_orders[1] != edge_orders[3])
1272 {
1273 logger().trace("skipping prism quad face {} with p={}, q={} and {} nodes", eid, p, q, loc_nodes.size());
1274 continue;
1275 }
1276
1277 std::vector<int> grid(expected_nodes, -1);
1278 auto grid_index = [u_order](const int i, const int j) {
1279 return j * (u_order + 1) + i;
1280 };
1281
1282 grid[grid_index(0, 0)] = loc_nodes[0];
1283 grid[grid_index(u_order, 0)] = loc_nodes[1];
1284 grid[grid_index(u_order, v_order)] = loc_nodes[2];
1285 grid[grid_index(0, v_order)] = loc_nodes[3];
1286
1287 int node_index = 4;
1288 for (int i = 1; i < u_order; ++i)
1289 grid[grid_index(i, 0)] = loc_nodes[node_index++];
1290 for (int j = 1; j < v_order; ++j)
1291 grid[grid_index(u_order, j)] = loc_nodes[node_index++];
1292 for (int i = u_order - 1; i > 0; --i)
1293 grid[grid_index(i, v_order)] = loc_nodes[node_index++];
1294 for (int j = v_order - 1; j > 0; --j)
1295 grid[grid_index(0, j)] = loc_nodes[node_index++];
1296
1297 for (int j = 1; j < v_order; ++j)
1298 for (int i = 1; i < u_order; ++i)
1299 grid[grid_index(i, j)] = loc_nodes[node_index++];
1300
1301 assert(node_index == loc_nodes.size());
1302 assert(std::all_of(grid.begin(), grid.end(), [](const int n) { return n >= 0; }));
1303
1304 for (int j = 0; j < v_order; ++j)
1305 {
1306 for (int i = 0; i < u_order; ++i)
1307 {
1308 tris.emplace_back(grid[grid_index(i, j)], grid[grid_index(i + 1, j)], grid[grid_index(i, j + 1)]);
1309 tris.emplace_back(grid[grid_index(i + 1, j + 1)], grid[grid_index(i, j + 1)], grid[grid_index(i + 1, j)]);
1310 }
1311 }
1312
1313 update_mapping(loc_nodes);
1314 }
1315
1316 continue;
1317 }
1318 else if (mesh.is_pyramid(lb.element_id()))
1319 {
1320 assert(!is_simplicial);
1321 assert(!mesh.has_poly());
1322 std::vector<int> loc_nodes;
1323 std::vector<int> loc_local_nodes;
1324
1325 for (long n = 0; n < nodes.size(); ++n)
1326 {
1327 auto &bs = b.bases[nodes(n)];
1328 const auto &glob = bs.global();
1329 if (glob.size() != 1)
1330 continue;
1331
1332 int gindex = glob.front().index;
1333 node_positions_vec.resize(std::max(int(node_positions_vec.size()), gindex + 1));
1334 node_positions_vec[gindex] = glob.front().node;
1335 loc_nodes.push_back(gindex);
1336 loc_local_nodes.push_back(nodes(n));
1337 }
1338
1339 auto update_mapping = [&displacement_map_entries, &visited_node](const std::vector<int> &loc_nodes) {
1340 for (int k = 0; k < loc_nodes.size(); ++k)
1341 {
1342 if (!visited_node[loc_nodes[k]])
1343 displacement_map_entries.emplace_back(loc_nodes[k], loc_nodes[k], 1);
1344
1345 visited_node[loc_nodes[k]] = true;
1346 }
1347 };
1348
1349 const int p = b.bases.empty() ? -1 : b.bases.front().order();
1350 if (p < 1 || p > 3)
1351 {
1352 logger().trace("skipping pyramid face {} with unsupported p={}", eid, p);
1353 continue;
1354 }
1355
1356 if (lid == 0)
1357 {
1358 const int expected_nodes = (p + 1) * (p + 1);
1359 if (loc_nodes.size() != expected_nodes || loc_local_nodes.size() != expected_nodes)
1360 {
1361 logger().trace("skipping pyramid quad face {} with p={} and {} nodes", eid, p, loc_nodes.size());
1362 continue;
1363 }
1364
1365 Eigen::MatrixXd pyramid_nodes;
1366 autogen::pyramid_nodes_3d(p, pyramid_nodes);
1367
1368 const Eigen::RowVector3d origin = pyramid_nodes.row(loc_local_nodes[0]);
1369 const Eigen::RowVector3d u_axis = pyramid_nodes.row(loc_local_nodes[1]) - origin;
1370 const Eigen::RowVector3d v_axis = pyramid_nodes.row(loc_local_nodes[3]) - origin;
1371
1372 std::vector<int> grid(expected_nodes, -1);
1373 auto grid_index = [p](const int i, const int j) {
1374 return j * (p + 1) + i;
1375 };
1376
1377 bool valid_grid = true;
1378 for (int n = 0; n < loc_nodes.size(); ++n)
1379 {
1380 const Eigen::RowVector3d rel = pyramid_nodes.row(loc_local_nodes[n]) - origin;
1381 const int i = int(std::lround(p * rel.dot(u_axis) / u_axis.squaredNorm()));
1382 const int j = int(std::lround(p * rel.dot(v_axis) / v_axis.squaredNorm()));
1383 if (i < 0 || i > p || j < 0 || j > p)
1384 {
1385 logger().trace("skipping pyramid quad face {} with invalid local grid coordinate ({}, {})", eid, i, j);
1386 valid_grid = false;
1387 break;
1388 }
1389 if (grid[grid_index(i, j)] >= 0)
1390 {
1391 logger().trace("skipping pyramid quad face {} with duplicate local grid coordinate ({}, {})", eid, i, j);
1392 valid_grid = false;
1393 break;
1394 }
1395 grid[grid_index(i, j)] = loc_nodes[n];
1396 }
1397
1398 if (!valid_grid || !std::all_of(grid.begin(), grid.end(), [](const int n) { return n >= 0; }))
1399 continue;
1400
1401 for (int j = 0; j < p; ++j)
1402 {
1403 for (int i = 0; i < p; ++i)
1404 {
1405 tris.emplace_back(grid[grid_index(i, j)], grid[grid_index(i + 1, j)], grid[grid_index(i, j + 1)]);
1406 tris.emplace_back(grid[grid_index(i + 1, j + 1)], grid[grid_index(i, j + 1)], grid[grid_index(i + 1, j)]);
1407 }
1408 }
1409
1410 update_mapping(loc_nodes);
1411 }
1412 else if (loc_nodes.size() == 3)
1413 {
1414 tris.emplace_back(loc_nodes[0], loc_nodes[1], loc_nodes[2]);
1415 update_mapping(loc_nodes);
1416 }
1417 else if (loc_nodes.size() == 6)
1418 {
1419 tris.emplace_back(loc_nodes[0], loc_nodes[3], loc_nodes[5]);
1420 tris.emplace_back(loc_nodes[3], loc_nodes[1], loc_nodes[4]);
1421 tris.emplace_back(loc_nodes[4], loc_nodes[2], loc_nodes[5]);
1422 tris.emplace_back(loc_nodes[3], loc_nodes[4], loc_nodes[5]);
1423 update_mapping(loc_nodes);
1424 }
1425 else if (loc_nodes.size() == 10)
1426 {
1427 tris.emplace_back(loc_nodes[0], loc_nodes[3], loc_nodes[8]);
1428 tris.emplace_back(loc_nodes[3], loc_nodes[4], loc_nodes[9]);
1429 tris.emplace_back(loc_nodes[4], loc_nodes[1], loc_nodes[5]);
1430 tris.emplace_back(loc_nodes[5], loc_nodes[6], loc_nodes[9]);
1431 tris.emplace_back(loc_nodes[6], loc_nodes[2], loc_nodes[7]);
1432 tris.emplace_back(loc_nodes[7], loc_nodes[8], loc_nodes[9]);
1433 tris.emplace_back(loc_nodes[8], loc_nodes[3], loc_nodes[9]);
1434 tris.emplace_back(loc_nodes[9], loc_nodes[4], loc_nodes[5]);
1435 tris.emplace_back(loc_nodes[6], loc_nodes[7], loc_nodes[9]);
1436 update_mapping(loc_nodes);
1437 }
1438 else
1439 {
1440 logger().trace("skipping pyramid tri face {} with p={} and {} nodes", eid, p, loc_nodes.size());
1441 continue;
1442 }
1443
1444 continue;
1445 }
1446
1447 if (!mesh.is_simplex(lb.element_id()))
1448 {
1449 logger().trace("skipping element {} since it is not a simplex or hex", eid);
1450 continue;
1451 }
1452
1453 assert(mesh.is_simplex(lb.element_id()));
1454
1455 std::vector<int> loc_nodes;
1456
1457 bool is_follower = false;
1458 if (!mesh3d.is_conforming())
1459 {
1460 for (long n = 0; n < nodes.size(); ++n)
1461 {
1462 auto &bs = b.bases[nodes(n)];
1463 const auto &glob = bs.global();
1464 if (glob.size() != 1)
1465 {
1466 is_follower = true;
1467 break;
1468 }
1469 }
1470 }
1471
1472 if (is_follower)
1473 continue;
1474
1475 for (long n = 0; n < nodes.size(); ++n)
1476 {
1477 const basis::Basis &bs = b.bases[nodes(n)];
1478 const std::vector<basis::Local2Global> &glob = bs.global();
1479 if (glob.size() != 1)
1480 continue;
1481
1482 int gindex = glob.front().index;
1483 node_positions_vec.resize(std::max(int(node_positions_vec.size()), gindex + 1));
1484 node_positions_vec[gindex] = glob.front().node;
1485 loc_nodes.push_back(gindex);
1486 }
1487
1488 if (loc_nodes.size() == 3)
1489 {
1490 tris.emplace_back(loc_nodes[0], loc_nodes[1], loc_nodes[2]);
1491 }
1492 else if (loc_nodes.size() == 6)
1493 {
1494 tris.emplace_back(loc_nodes[0], loc_nodes[3], loc_nodes[5]);
1495 tris.emplace_back(loc_nodes[3], loc_nodes[1], loc_nodes[4]);
1496 tris.emplace_back(loc_nodes[4], loc_nodes[2], loc_nodes[5]);
1497 tris.emplace_back(loc_nodes[3], loc_nodes[4], loc_nodes[5]);
1498 }
1499 else if (loc_nodes.size() == 10)
1500 {
1501 tris.emplace_back(loc_nodes[0], loc_nodes[3], loc_nodes[8]);
1502 tris.emplace_back(loc_nodes[3], loc_nodes[4], loc_nodes[9]);
1503 tris.emplace_back(loc_nodes[4], loc_nodes[1], loc_nodes[5]);
1504 tris.emplace_back(loc_nodes[5], loc_nodes[6], loc_nodes[9]);
1505 tris.emplace_back(loc_nodes[6], loc_nodes[2], loc_nodes[7]);
1506 tris.emplace_back(loc_nodes[7], loc_nodes[8], loc_nodes[9]);
1507 tris.emplace_back(loc_nodes[8], loc_nodes[3], loc_nodes[9]);
1508 tris.emplace_back(loc_nodes[9], loc_nodes[4], loc_nodes[5]);
1509 tris.emplace_back(loc_nodes[6], loc_nodes[7], loc_nodes[9]);
1510 }
1511 else if (loc_nodes.size() == 15)
1512 {
1513 tris.emplace_back(loc_nodes[0], loc_nodes[3], loc_nodes[11]);
1514 tris.emplace_back(loc_nodes[3], loc_nodes[4], loc_nodes[12]);
1515 tris.emplace_back(loc_nodes[3], loc_nodes[12], loc_nodes[11]);
1516 tris.emplace_back(loc_nodes[12], loc_nodes[10], loc_nodes[11]);
1517 tris.emplace_back(loc_nodes[4], loc_nodes[5], loc_nodes[13]);
1518 tris.emplace_back(loc_nodes[4], loc_nodes[13], loc_nodes[12]);
1519 tris.emplace_back(loc_nodes[12], loc_nodes[13], loc_nodes[14]);
1520 tris.emplace_back(loc_nodes[12], loc_nodes[14], loc_nodes[10]);
1521 tris.emplace_back(loc_nodes[14], loc_nodes[9], loc_nodes[10]);
1522 tris.emplace_back(loc_nodes[5], loc_nodes[1], loc_nodes[6]);
1523 tris.emplace_back(loc_nodes[5], loc_nodes[6], loc_nodes[13]);
1524 tris.emplace_back(loc_nodes[6], loc_nodes[7], loc_nodes[13]);
1525 tris.emplace_back(loc_nodes[13], loc_nodes[7], loc_nodes[14]);
1526 tris.emplace_back(loc_nodes[7], loc_nodes[8], loc_nodes[14]);
1527 tris.emplace_back(loc_nodes[14], loc_nodes[8], loc_nodes[9]);
1528 tris.emplace_back(loc_nodes[8], loc_nodes[2], loc_nodes[9]);
1529 }
1530 else
1531 {
1532 print_warning << loc_nodes.size() << " ";
1533 // assert(false);
1534 }
1535
1536 if (!is_simplicial)
1537 {
1538 for (int k = 0; k < loc_nodes.size(); ++k)
1539 {
1540 if (!visited_node[loc_nodes[k]])
1541 displacement_map_entries.emplace_back(loc_nodes[k], loc_nodes[k], 1);
1542
1543 visited_node[loc_nodes[k]] = true;
1544 }
1545 }
1546 }
1547 }
1548
1549 if (print_warning.str().size() > 0)
1550 logger().warn("Skipping faces as theys have {} nodes, boundary export supported up to p4", print_warning.str());
1551
1552 // downstream consumers (e.g. the shape-derivative code) expect every
1553 // FE node to have a row, as the pre-split extraction guaranteed
1554 node_positions_vec.resize(
1555 std::max(node_positions_vec.size(), size_t(n_bases + (is_simplicial ? 0 : mesh.n_faces()))),
1556 Eigen::Vector3d::Zero());
1557
1558 node_positions.resize(node_positions_vec.size(), 3);
1559 for (int i = 0; i < node_positions_vec.size(); ++i)
1560 node_positions.row(i) = node_positions_vec[i];
1561
1562 boundary_triangles.resize(tris.size(), 3);
1563 for (int i = 0; i < tris.size(); ++i)
1564 {
1565 boundary_triangles.row(i) << std::get<0>(tris[i]), std::get<2>(tris[i]), std::get<1>(tris[i]);
1566 }
1567
1568 if (boundary_triangles.rows() > 0)
1569 {
1570 igl::edges(boundary_triangles, boundary_edges);
1571 }
1572
1573 if (const char *dump = getenv("POLYFEM_DUMP_COLLISION_PROXY"))
1574 igl::write_triangle_mesh(dump, node_positions, boundary_triangles);
1575 }
1576 else
1577 {
1578 node_positions.resize(n_bases, 2);
1579 node_positions.setZero();
1580 const Mesh2D &mesh2d = dynamic_cast<const Mesh2D &>(mesh);
1581
1582 std::vector<std::pair<int, int>> edges;
1583
1584 for (const LocalBoundary &lb : total_local_boundary)
1585 {
1586 const basis::ElementBases &b = bases[lb.element_id()];
1587 if (b.bases.empty())
1588 continue;
1589
1590 for (int j = 0; j < lb.size(); ++j)
1591 {
1592 const int eid = lb.global_primitive_id(j);
1593 const int lid = lb[j];
1594 const Eigen::VectorXi nodes = b.local_nodes_for_primitive(eid, mesh2d);
1595
1596 int prev_node = -1;
1597
1598 for (long n = 0; n < nodes.size(); ++n)
1599 {
1600 const basis::Basis &bs = b.bases[nodes(n)];
1601 const std::vector<basis::Local2Global> &glob = bs.global();
1602 if (glob.size() != 1)
1603 continue;
1604
1605 int gindex = glob.front().index;
1606 node_positions.row(gindex) = glob.front().node.head<2>();
1607
1608 if (prev_node >= 0)
1609 edges.emplace_back(prev_node, gindex);
1610
1611 prev_node = gindex;
1612 }
1613 }
1614 }
1615
1616 boundary_triangles.resize(0, 0);
1617 boundary_edges.resize(edges.size(), 2);
1618 for (int i = 0; i < edges.size(); ++i)
1619 {
1620 boundary_edges.row(i) << edges[i].first, edges[i].second;
1621 }
1622 }
1623 }
1624
1626 const mesh::Mesh &mesh,
1627 const std::vector<basis::ElementBases> &gbases,
1628 const std::vector<mesh::LocalBoundary> &total_local_boundary,
1629 Eigen::MatrixXd &boundary_vis_vertices,
1630 Eigen::MatrixXd &boundary_vis_local_vertices,
1631 Eigen::MatrixXi &boundary_vis_elements,
1632 Eigen::MatrixXi &boundary_vis_elements_ids,
1633 Eigen::MatrixXi &boundary_vis_primitive_ids,
1634 Eigen::MatrixXd &boundary_vis_normals) const
1635 {
1636 using namespace polyfem::mesh;
1637
1638 std::vector<Eigen::MatrixXd> lv, vertices, allnormals;
1639 std::vector<int> el_ids, global_primitive_ids;
1640 Eigen::MatrixXd uv, local_pts, tmp_n, normals;
1642 const auto &sampler = ref_element_sampler;
1643 const int n_samples = sampler.num_samples();
1644 int size = 0;
1645
1646 std::vector<std::pair<int, int>> edges;
1647 std::vector<std::tuple<int, int, int>> tris;
1648
1649 for (auto it = total_local_boundary.begin(); it != total_local_boundary.end(); ++it)
1650 {
1651 const auto &lb = *it;
1652 const auto &gbs = gbases[lb.element_id()];
1653
1654 for (int k = 0; k < lb.size(); ++k)
1655 {
1656 switch (lb.type())
1657 {
1658 case BoundaryType::TRI_LINE:
1660 utils::BoundarySampler::sample_parametric_tri_edge(lb[k], n_samples, uv, local_pts);
1661 break;
1662 case BoundaryType::QUAD_LINE:
1664 utils::BoundarySampler::sample_parametric_quad_edge(lb[k], n_samples, uv, local_pts);
1665 break;
1666 case BoundaryType::QUAD:
1668 utils::BoundarySampler::sample_parametric_quad_face(lb[k], n_samples, uv, local_pts);
1669 break;
1670 case BoundaryType::TRI:
1672 utils::BoundarySampler::sample_parametric_tri_face(lb[k], n_samples, uv, local_pts);
1673 break;
1674 case BoundaryType::PRISM:
1676 utils::BoundarySampler::sample_parametric_prism_face(lb[k], n_samples, uv, local_pts);
1677 break;
1678 case BoundaryType::PYRAMID:
1680 utils::BoundarySampler::sample_parametric_pyramid_face(lb[k], n_samples, uv, local_pts);
1681 break;
1682 case BoundaryType::POLYGON:
1683 utils::BoundarySampler::normal_for_polygon_edge(lb.element_id(), lb.global_primitive_id(k), mesh, tmp_n);
1684 utils::BoundarySampler::sample_polygon_edge(lb.element_id(), lb.global_primitive_id(k), n_samples, mesh, uv, local_pts);
1685 break;
1686 case BoundaryType::POLYHEDRON:
1687 assert(false);
1688 break;
1689 case BoundaryType::INVALID:
1690 assert(false);
1691 break;
1692 default:
1693 assert(false);
1694 }
1695
1696 vertices.emplace_back();
1697 lv.emplace_back(local_pts);
1698 el_ids.push_back(lb.element_id());
1699 global_primitive_ids.push_back(lb.global_primitive_id(k));
1700 gbs.eval_geom_mapping(local_pts, vertices.back());
1701 vals.compute(lb.element_id(), mesh.is_volume(), local_pts, gbs, gbs);
1702 const int tris_start = tris.size();
1703
1704 if (mesh.is_volume())
1705 {
1706 const bool prism_quad = lb.type() == BoundaryType::PRISM && lb[k] >= 2;
1707 const bool prism_tri = lb.type() == BoundaryType::PRISM && lb[k] < 2;
1708
1709 const bool pyramid_quad = lb.type() == BoundaryType::PYRAMID && lb[k] == 0;
1710 const bool pyramid_tri = lb.type() == BoundaryType::PYRAMID && lb[k] > 0;
1711
1712 if (lb.type() == BoundaryType::QUAD || prism_quad || pyramid_quad)
1713 {
1714 const auto map = [n_samples, size](int i, int j) { return j * n_samples + i + size; };
1715
1716 for (int j = 0; j < n_samples - 1; ++j)
1717 {
1718 for (int i = 0; i < n_samples - 1; ++i)
1719 {
1720 tris.emplace_back(map(i, j), map(i + 1, j), map(i, j + 1));
1721 tris.emplace_back(map(i + 1, j + 1), map(i, j + 1), map(i + 1, j));
1722 }
1723 }
1724 }
1725 else if (lb.type() == BoundaryType::TRI || prism_tri || pyramid_tri)
1726 {
1727 int index = 0;
1728 std::vector<int> mapp(n_samples * n_samples, -1);
1729 for (int j = 0; j < n_samples; ++j)
1730 {
1731 for (int i = 0; i < n_samples - j; ++i)
1732 {
1733 mapp[j * n_samples + i] = index;
1734 ++index;
1735 }
1736 }
1737 const auto map = [mapp, n_samples](int i, int j) {
1738 if (j * n_samples + i >= mapp.size())
1739 return -1;
1740 return mapp[j * n_samples + i];
1741 };
1742
1743 for (int j = 0; j < n_samples - 1; ++j)
1744 {
1745 for (int i = 0; i < n_samples - j; ++i)
1746 {
1747 if (map(i, j) >= 0 && map(i + 1, j) >= 0 && map(i, j + 1) >= 0)
1748 tris.emplace_back(map(i, j) + size, map(i + 1, j) + size, map(i, j + 1) + size);
1749
1750 if (map(i + 1, j + 1) >= 0 && map(i, j + 1) >= 0 && map(i + 1, j) >= 0)
1751 tris.emplace_back(map(i + 1, j + 1) + size, map(i, j + 1) + size, map(i + 1, j) + size);
1752 }
1753 }
1754 }
1755 else
1756 {
1757 assert(false);
1758 }
1759 }
1760 else
1761 {
1762 for (int i = 0; i < vertices.back().rows() - 1; ++i)
1763 edges.emplace_back(i + size, i + size + 1);
1764 }
1765
1766 normals.resize(vals.jac_it.size(), tmp_n.cols());
1767
1768 for (int n = 0; n < vals.jac_it.size(); ++n)
1769 {
1770 normals.row(n) = tmp_n * vals.jac_it[n];
1771 normals.row(n).normalize();
1772 }
1773
1774 allnormals.push_back(normals);
1775
1776 tmp_n.setZero();
1777 for (int n = 0; n < vals.jac_it.size(); ++n)
1778 {
1779 tmp_n += normals.row(n);
1780 }
1781
1782 if (mesh.is_volume())
1783 {
1784 Eigen::Vector3d e1 = vertices.back().row(std::get<1>(tris.back()) - size) - vertices.back().row(std::get<0>(tris.back()) - size);
1785 Eigen::Vector3d e2 = vertices.back().row(std::get<2>(tris.back()) - size) - vertices.back().row(std::get<0>(tris.back()) - size);
1786
1787 Eigen::Vector3d n = e1.cross(e2);
1788 Eigen::Vector3d nn = tmp_n.transpose();
1789
1790 if (n.dot(nn) < 0)
1791 {
1792 for (int i = tris_start; i < tris.size(); ++i)
1793 {
1794 tris[i] = std::tuple<int, int, int>(std::get<0>(tris[i]), std::get<2>(tris[i]), std::get<1>(tris[i]));
1795 }
1796 }
1797 }
1798
1799 size += vertices.back().rows();
1800 }
1801 }
1802
1803 boundary_vis_vertices.resize(size, vertices.front().cols());
1804 boundary_vis_local_vertices.resize(size, vertices.front().cols());
1805 boundary_vis_elements_ids.resize(size, 1);
1806 boundary_vis_primitive_ids.resize(size, 1);
1807 boundary_vis_normals.resize(size, vertices.front().cols());
1808
1809 if (mesh.is_volume())
1810 boundary_vis_elements.resize(tris.size(), 3);
1811 else
1812 boundary_vis_elements.resize(edges.size(), 2);
1813
1814 int index = 0;
1815 int ii = 0;
1816 for (const auto &v : vertices)
1817 {
1818 boundary_vis_vertices.block(index, 0, v.rows(), v.cols()) = v;
1819 boundary_vis_local_vertices.block(index, 0, v.rows(), v.cols()) = lv[ii];
1820 boundary_vis_elements_ids.block(index, 0, v.rows(), 1).setConstant(el_ids[ii]);
1821 boundary_vis_primitive_ids.block(index, 0, v.rows(), 1).setConstant(global_primitive_ids[ii++]);
1822 index += v.rows();
1823 }
1824
1825 index = 0;
1826 for (const auto &n : allnormals)
1827 {
1828 boundary_vis_normals.block(index, 0, n.rows(), n.cols()) = n;
1829 index += n.rows();
1830 }
1831
1832 index = 0;
1833 if (mesh.is_volume())
1834 {
1835 for (const auto &t : tris)
1836 {
1837 boundary_vis_elements.row(index) << std::get<0>(t), std::get<1>(t), std::get<2>(t);
1838 ++index;
1839 }
1840 }
1841 else
1842 {
1843 for (const auto &e : edges)
1844 {
1845 boundary_vis_elements.row(index) << e.first, e.second;
1846 ++index;
1847 }
1848 }
1849 }
1850
1852 const mesh::Mesh &mesh,
1853 const Eigen::VectorXi &disc_orders,
1854 const std::vector<basis::ElementBases> &gbases,
1855 const std::map<int, Eigen::MatrixXd> &polys,
1856 const std::map<int, std::pair<Eigen::MatrixXd, Eigen::MatrixXi>> &polys_3d,
1857 const bool boundary_only,
1858 Eigen::MatrixXd &points,
1859 Eigen::MatrixXi &tets,
1860 Eigen::MatrixXi &el_id,
1861 Eigen::MatrixXd &discr,
1862 Eigen::MatrixXd &local_points) const
1863 {
1864 const auto &sampler = ref_element_sampler;
1865
1866 const auto &current_bases = gbases;
1867 int tet_total_size = 0;
1868 int pts_total_size = 0;
1869
1870 Eigen::MatrixXd vis_pts_poly;
1871 Eigen::MatrixXi vis_faces_poly, vis_edges_poly;
1872
1873 for (size_t i = 0; i < current_bases.size(); ++i)
1874 {
1875 const auto &bs = current_bases[i];
1876
1877 if (boundary_only && mesh.is_volume() && !mesh.is_boundary_element(i))
1878 continue;
1879
1880 if (mesh.is_simplex(i))
1881 {
1882 tet_total_size += sampler.simplex_volume().rows();
1883 pts_total_size += sampler.simplex_points().rows();
1884 }
1885 else if (mesh.is_cube(i))
1886 {
1887 tet_total_size += sampler.cube_volume().rows();
1888 pts_total_size += sampler.cube_points().rows();
1889 }
1890 else if (mesh.is_prism(i))
1891 {
1892 tet_total_size += sampler.prism_volume().rows();
1893 pts_total_size += sampler.prism_points().rows();
1894 }
1895 else if (mesh.is_pyramid(i))
1896 {
1897 tet_total_size += sampler.pyramid_volume().rows();
1898 pts_total_size += sampler.pyramid_points().rows();
1899 }
1900 else
1901 {
1902 if (mesh.is_volume())
1903 {
1904 sampler.sample_polyhedron(polys_3d.at(i).first, polys_3d.at(i).second, vis_pts_poly, vis_faces_poly, vis_edges_poly);
1905
1906 tet_total_size += vis_faces_poly.rows();
1907 pts_total_size += vis_pts_poly.rows();
1908 }
1909 else
1910 {
1911 sampler.sample_polygon(polys.at(i), vis_pts_poly, vis_faces_poly, vis_edges_poly);
1912
1913 tet_total_size += vis_faces_poly.rows();
1914 pts_total_size += vis_pts_poly.rows();
1915 }
1916 }
1917 }
1918
1919 points.resize(pts_total_size, mesh.dimension());
1920 local_points.resize(pts_total_size, mesh.dimension());
1921 local_points.setZero();
1922 tets.resize(tet_total_size, mesh.is_volume() ? 4 : 3);
1923
1924 el_id.resize(pts_total_size, 1);
1925 discr.resize(pts_total_size, 1);
1926
1927 Eigen::MatrixXd mapped, tmp;
1928 int tet_index = 0, pts_index = 0;
1929
1930 for (size_t i = 0; i < current_bases.size(); ++i)
1931 {
1932 const auto &bs = current_bases[i];
1933
1934 if (boundary_only && mesh.is_volume() && !mesh.is_boundary_element(i))
1935 continue;
1936
1937 if (mesh.is_simplex(i))
1938 {
1939 bs.eval_geom_mapping(sampler.simplex_points(), mapped);
1940
1941 tets.block(tet_index, 0, sampler.simplex_volume().rows(), tets.cols()) = sampler.simplex_volume().array() + pts_index;
1942 tet_index += sampler.simplex_volume().rows();
1943
1944 points.block(pts_index, 0, mapped.rows(), points.cols()) = mapped;
1945 local_points.block(pts_index, 0, sampler.simplex_points().rows(), sampler.simplex_points().cols()) = sampler.simplex_points();
1946 discr.block(pts_index, 0, mapped.rows(), 1).setConstant(disc_orders(i));
1947 el_id.block(pts_index, 0, mapped.rows(), 1).setConstant(i);
1948 pts_index += mapped.rows();
1949 }
1950 else if (mesh.is_cube(i))
1951 {
1952 bs.eval_geom_mapping(sampler.cube_points(), mapped);
1953
1954 tets.block(tet_index, 0, sampler.cube_volume().rows(), tets.cols()) = sampler.cube_volume().array() + pts_index;
1955 tet_index += sampler.cube_volume().rows();
1956
1957 points.block(pts_index, 0, mapped.rows(), points.cols()) = mapped;
1958 local_points.block(pts_index, 0, sampler.cube_points().rows(), sampler.cube_points().cols()) = sampler.cube_points();
1959 discr.block(pts_index, 0, mapped.rows(), 1).setConstant(disc_orders(i));
1960 el_id.block(pts_index, 0, mapped.rows(), 1).setConstant(i);
1961 pts_index += mapped.rows();
1962 }
1963 else if (mesh.is_prism(i))
1964 {
1965 bs.eval_geom_mapping(sampler.prism_points(), mapped);
1966
1967 tets.block(tet_index, 0, sampler.prism_volume().rows(), tets.cols()) = sampler.prism_volume().array() + pts_index;
1968 tet_index += sampler.prism_volume().rows();
1969
1970 points.block(pts_index, 0, mapped.rows(), points.cols()) = mapped;
1971 local_points.block(pts_index, 0, sampler.prism_points().rows(), sampler.prism_points().cols()) = sampler.prism_points();
1972 discr.block(pts_index, 0, mapped.rows(), 1).setConstant(disc_orders(i));
1973 el_id.block(pts_index, 0, mapped.rows(), 1).setConstant(i);
1974 pts_index += mapped.rows();
1975 }
1976 else if (mesh.is_pyramid(i))
1977 {
1978 bs.eval_geom_mapping(sampler.pyramid_points(), mapped);
1979
1980 tets.block(tet_index, 0, sampler.pyramid_volume().rows(), tets.cols()) = sampler.pyramid_volume().array() + pts_index;
1981 tet_index += sampler.pyramid_volume().rows();
1982
1983 points.block(pts_index, 0, mapped.rows(), points.cols()) = mapped;
1984 local_points.block(pts_index, 0, sampler.pyramid_points().rows(), sampler.pyramid_points().cols()) = sampler.pyramid_points();
1985 discr.block(pts_index, 0, mapped.rows(), 1).setConstant(disc_orders(i));
1986 el_id.block(pts_index, 0, mapped.rows(), 1).setConstant(i);
1987 pts_index += mapped.rows();
1988 }
1989 else
1990 {
1991 if (mesh.is_volume())
1992 {
1993 sampler.sample_polyhedron(polys_3d.at(i).first, polys_3d.at(i).second, vis_pts_poly, vis_faces_poly, vis_edges_poly);
1994 bs.eval_geom_mapping(vis_pts_poly, mapped);
1995
1996 tets.block(tet_index, 0, vis_faces_poly.rows(), tets.cols()) = vis_faces_poly.array() + pts_index;
1997 tet_index += vis_faces_poly.rows();
1998
1999 points.block(pts_index, 0, mapped.rows(), points.cols()) = mapped;
2000 local_points.block(pts_index, 0, vis_pts_poly.rows(), vis_pts_poly.cols()) = vis_pts_poly;
2001 discr.block(pts_index, 0, mapped.rows(), 1).setConstant(-1);
2002 el_id.block(pts_index, 0, mapped.rows(), 1).setConstant(i);
2003 pts_index += mapped.rows();
2004 }
2005 else
2006 {
2007 sampler.sample_polygon(polys.at(i), vis_pts_poly, vis_faces_poly, vis_edges_poly);
2008 bs.eval_geom_mapping(vis_pts_poly, mapped);
2009
2010 tets.block(tet_index, 0, vis_faces_poly.rows(), tets.cols()) = vis_faces_poly.array() + pts_index;
2011 tet_index += vis_faces_poly.rows();
2012
2013 points.block(pts_index, 0, mapped.rows(), points.cols()) = mapped;
2014 local_points.block(pts_index, 0, vis_pts_poly.rows(), vis_pts_poly.cols()) = vis_pts_poly;
2015 discr.block(pts_index, 0, mapped.rows(), 1).setConstant(-1);
2016 el_id.block(pts_index, 0, mapped.rows(), 1).setConstant(i);
2017 pts_index += mapped.rows();
2018 }
2019 }
2020 }
2021
2022 assert(pts_index == points.rows());
2023 assert(tet_index == tets.rows());
2024 }
2025
2027 const mesh::Mesh &mesh,
2028 const Eigen::VectorXi &output_orders,
2029 const std::vector<basis::ElementBases> &bases,
2030 Eigen::MatrixXd &points,
2031 std::vector<CellElement> &elements,
2032 Eigen::MatrixXi &el_id,
2033 Eigen::MatrixXd &discr,
2034 Eigen::MatrixXd &local_points) const
2035 {
2036 // if (!mesh)
2037 // {
2038 // logger().error("Load the mesh first!");
2039 // return;
2040 // }
2041 // if (n_bases <= 0)
2042 // {
2043 // logger().error("Build the bases first!");
2044 // return;
2045 // }
2046 // assert(mesh.is_linear());
2047
2048 std::vector<RowVectorNd> nodes;
2049 int pts_total_size = 0;
2050 elements.resize(bases.size());
2051 Eigen::MatrixXd ref_pts;
2052
2053 for (size_t i = 0; i < bases.size(); ++i)
2054 {
2055 const auto &bs = bases[i];
2056 if (mesh.is_volume())
2057 {
2058 if (mesh.is_simplex(i))
2059 autogen::p_nodes_3d(output_orders(i), ref_pts);
2060 else if (mesh.is_cube(i))
2061 autogen::q_nodes_3d(output_orders(i), ref_pts);
2062 else if (mesh.is_prism(i))
2063 {
2064 autogen::prism_nodes_3d(output_orders(i), output_orders(i), ref_pts);
2065 }
2066 else if (mesh.is_pyramid(i))
2067 {
2068 if (output_orders(i) == 1)
2069 pyramid_nodes_for_output(1, ref_pts);
2070 else
2072 }
2073 else
2074 continue;
2075 }
2076 else
2077 {
2078 if (mesh.is_simplex(i))
2079 autogen::p_nodes_2d(output_orders(i), ref_pts);
2080 else if (mesh.is_cube(i))
2081 autogen::q_nodes_2d(output_orders(i), ref_pts);
2082 else
2083 {
2084 const int n_v = static_cast<const mesh::Mesh2D &>(mesh).n_face_vertices(i);
2085 ref_pts.resize(n_v, 2);
2086 }
2087 }
2088
2089 pts_total_size += ref_pts.rows();
2090 }
2091
2092 points.resize(pts_total_size, mesh.dimension());
2093 local_points.resize(pts_total_size, mesh.dimension());
2094 local_points.setZero();
2095
2096 el_id.resize(pts_total_size, 1);
2097 discr.resize(pts_total_size, 1);
2098
2099 Eigen::MatrixXd mapped;
2100 int pts_index = 0;
2101
2102 std::string error_msg = "";
2103
2104 for (size_t i = 0; i < bases.size(); ++i)
2105 {
2106 const auto &bs = bases[i];
2107 if (mesh.is_volume())
2108 {
2109 if (mesh.is_simplex(i))
2110 autogen::p_nodes_3d(output_orders(i), ref_pts);
2111 else if (mesh.is_cube(i))
2112 autogen::q_nodes_3d(output_orders(i), ref_pts);
2113 else if (mesh.is_prism(i))
2114 {
2115 autogen::prism_nodes_3d(output_orders(i), output_orders(i), ref_pts);
2116 }
2117 else if (mesh.is_pyramid(i))
2118 {
2119 if (output_orders(i) == 1)
2120 pyramid_nodes_for_output(1, ref_pts);
2121 else
2123 }
2124 else
2125 continue;
2126 }
2127 else
2128 {
2129 if (mesh.is_simplex(i))
2130 autogen::p_nodes_2d(output_orders(i), ref_pts);
2131 else if (mesh.is_cube(i))
2132 autogen::q_nodes_2d(output_orders(i), ref_pts);
2133 else
2134 continue;
2135 }
2136
2137 bs.eval_geom_mapping(ref_pts, mapped);
2138
2139 for (int j = 0; j < mapped.rows(); ++j)
2140 {
2141 points.row(pts_index) = mapped.row(j);
2142 local_points.row(pts_index).leftCols(ref_pts.cols()) = ref_pts.row(j);
2143 el_id(pts_index) = i;
2144 discr(pts_index) = output_orders(i);
2145 elements[i].vertices.push_back(pts_index);
2146
2147 pts_index++;
2148 }
2149
2150 if (mesh.is_simplex(i))
2151 {
2152 if (mesh.is_volume())
2153 {
2154 const int n_nodes = elements[i].vertices.size();
2155 if (output_orders(i) >= 3)
2156 {
2157 std::swap(elements[i].vertices[16], elements[i].vertices[17]);
2158 std::swap(elements[i].vertices[17], elements[i].vertices[18]);
2159 std::swap(elements[i].vertices[18], elements[i].vertices[19]);
2160 }
2161 if (output_orders(i) > 4)
2162 error_msg = "Saving high-order meshes not implemented for P5+ elements!";
2163 }
2164 else
2165 {
2166 if (output_orders(i) == 4)
2167 {
2168 const int n_nodes = elements[i].vertices.size();
2169 std::swap(elements[i].vertices[n_nodes - 1], elements[i].vertices[n_nodes - 2]);
2170 }
2171 if (output_orders(i) > 4)
2172 error_msg = "Saving high-order meshes not implemented for P5+ elements!";
2173 }
2174 }
2175 else if (mesh.is_cube(i) && mesh.is_volume())
2176 {
2177 const int n_nodes = elements[i].vertices.size();
2178 if (output_orders(i) == 2) // Lagrange hex, order=2
2179 {
2180 std::swap(elements[i].vertices[12], elements[i].vertices[16]);
2181 std::swap(elements[i].vertices[13], elements[i].vertices[17]);
2182 std::swap(elements[i].vertices[14], elements[i].vertices[18]);
2183 std::swap(elements[i].vertices[15], elements[i].vertices[19]);
2184 std::swap(elements[i].vertices[18], elements[i].vertices[19]); // a hack fix
2185 }
2186 // if (disc_orders(i) == 3) // Incomplete fix, need to fix order on the edge
2187 // {
2188 // std::swap(elements[i].vertices[24], elements[i].vertices[16]);
2189 // std::swap(elements[i].vertices[25], elements[i].vertices[17]);
2190 // std::swap(elements[i].vertices[26], elements[i].vertices[18]);
2191 // std::swap(elements[i].vertices[27], elements[i].vertices[19]);
2192 // std::swap(elements[i].vertices[28], elements[i].vertices[20]);
2193 // std::swap(elements[i].vertices[29], elements[i].vertices[21]);
2194 // std::swap(elements[i].vertices[30], elements[i].vertices[22]);
2195 // std::swap(elements[i].vertices[31], elements[i].vertices[23]);
2196 // std::swap(elements[i].vertices[28], elements[i].vertices[30]); // hack
2197 // std::swap(elements[i].vertices[29], elements[i].vertices[31]); // hack
2198 // }
2199 if (output_orders(i) > 2)
2200 error_msg = "Saving high-order meshes not implemented for Q2+ elements!";
2201 }
2202 else if (output_orders(i) > 1)
2203 {
2204 if (mesh.is_cube(i))
2205 error_msg = "Saving high-order meshes not implemented for Q2+ elements!";
2206 }
2207 }
2208
2209 if (!error_msg.empty())
2210 logger().warn(error_msg);
2211
2212 for (size_t i = 0; i < bases.size(); ++i)
2213 {
2214 if (mesh.is_volume() || !mesh.is_polytope(i))
2215 continue;
2216
2217 const auto &mesh2d = static_cast<const mesh::Mesh2D &>(mesh);
2218 const int n_v = mesh2d.n_face_vertices(i);
2219
2220 for (int j = 0; j < n_v; ++j)
2221 {
2222 points.row(pts_index) = mesh2d.point(mesh2d.face_vertex(i, j));
2223 local_points.row(pts_index) = mesh2d.point(mesh2d.face_vertex(i, j));
2224 el_id(pts_index) = i;
2225 discr(pts_index) = output_orders(i);
2226 elements[i].vertices.push_back(pts_index);
2227
2228 pts_index++;
2229 }
2230 }
2231
2232 for (size_t i = 0; i < bases.size(); ++i)
2233 {
2234 if (!mesh.is_volume())
2235 {
2236 if (elements[i].vertices.size() == 1)
2237 elements[i].ctype = CellType::Vertex;
2238 else if (elements[i].vertices.size() == 2)
2239 elements[i].ctype = CellType::Line;
2240 else if (mesh.is_simplex(i))
2241 elements[i].ctype = CellType::Triangle;
2242 else if (mesh.is_cube(i))
2243 elements[i].ctype = CellType::Quadrilateral;
2244 else
2245 elements[i].ctype = CellType::Polygon;
2246 }
2247 else
2248 {
2249 if (mesh.is_simplex(i))
2250 elements[i].ctype = CellType::Tetrahedron;
2251 else if (mesh.is_cube(i))
2252 elements[i].ctype = CellType::Hexahedron;
2253 else if (mesh.is_prism(i))
2254 elements[i].ctype = CellType::Wedge;
2255 else if (mesh.is_pyramid(i))
2256 elements[i].ctype = CellType::Pyramid;
2257 }
2258 }
2259
2260 if (mesh.is_volume())
2261 {
2262 // ParaView does not reliably render high-order Lagrange pyramids;
2263 // tessellate only those cells while keeping linear pyramids and the
2264 // other element types in their native representation.
2265 std::vector<CellElement> expanded_elements;
2266 expanded_elements.reserve(elements.size());
2267 for (size_t i = 0; i < bases.size(); ++i)
2268 {
2269 if (!mesh.is_pyramid(i) || output_orders(i) == 1)
2270 {
2271 expanded_elements.push_back(std::move(elements[i]));
2272 continue;
2273 }
2274
2275 for (int t = 0; t < ref_element_sampler.pyramid_volume().rows(); ++t)
2276 {
2277 CellElement tet;
2278 tet.ctype = CellType::Tetrahedron;
2279 for (int j = 0; j < ref_element_sampler.pyramid_volume().cols(); ++j)
2280 tet.vertices.push_back(elements[i].vertices[ref_element_sampler.pyramid_volume()(t, j)]);
2281 expanded_elements.push_back(std::move(tet));
2282 }
2283 }
2284 elements.swap(expanded_elements);
2285 }
2286
2287 assert(pts_index == points.rows());
2288 }
2289
2291 const OutputSpace &space,
2292 const OutputFieldFunction &output_fields,
2293 const bool is_time_dependent,
2294 const double tend_in,
2295 const double dt,
2296 const ExportOptions &opts,
2297 const std::string &vis_mesh_path) const
2298 {
2299 if (!space.mesh)
2300 {
2301 logger().error("Load the mesh first!");
2302 return;
2303 }
2304
2305 double tend = tend_in;
2306 if (tend <= 0)
2307 tend = 1;
2308
2309 if (!vis_mesh_path.empty() && !is_time_dependent)
2310 {
2311 save_vtu(
2312 vis_mesh_path, space, output_fields,
2313 tend, dt, opts);
2314 }
2315 }
2316
2317 bool OutGeometryData::ExportOptions::export_field(const std::string &field) const
2318 {
2319 return fields.empty() || std::find(fields.begin(), fields.end(), field) != fields.end();
2320 }
2321
2322 OutGeometryData::ExportOptions::ExportOptions(const json &args, const bool is_mesh_linear, const bool mesh_has_prisms, const bool is_problem_scalar)
2323 {
2324 fields = args["output"]["paraview"]["fields"];
2325
2326 volume = args["output"]["paraview"]["volume"];
2327 surface = args["output"]["paraview"]["surface"];
2328 wire = args["output"]["paraview"]["wireframe"];
2329 points = args["output"]["paraview"]["points"];
2330 contact_forces = args["output"]["paraview"]["options"]["contact_forces"] && !is_problem_scalar;
2331 friction_forces = args["output"]["paraview"]["options"]["friction_forces"] && !is_problem_scalar;
2332 normal_adhesion_forces = args["output"]["paraview"]["options"]["normal_adhesion_forces"] && !is_problem_scalar;
2333 tangential_adhesion_forces = args["output"]["paraview"]["options"]["tangential_adhesion_forces"] && !is_problem_scalar;
2334
2335 if (args["output"]["paraview"]["options"]["force_high_order"])
2336 use_sampler = false;
2337 else
2338 use_sampler = !(is_mesh_linear && args["output"]["paraview"]["high_order_mesh"]);
2339 boundary_only = use_sampler && args["output"]["advanced"]["vis_boundary_only"];
2340 sol_on_grid = args["output"]["advanced"]["sol_on_grid"] > 0;
2341
2342 discretization_order = args["output"]["paraview"]["options"]["discretization_order"];
2343
2344 reorder_output = args["output"]["data"]["advanced"]["reorder_nodes"];
2345
2346 use_hdf5 = args["output"]["paraview"]["options"]["use_hdf5"];
2347
2348 obstacle_volume = args["output"]["paraview"]["options"]["obstacle_volume"];
2349 }
2350
2352 const std::string &path,
2353 const OutputSpace &space,
2354 const OutputFieldFunction &output_fields,
2355 const double t,
2356 const double dt,
2357 const ExportOptions &opts) const
2358 {
2359 if (!space.mesh)
2360 {
2361 logger().error("Load the mesh first!");
2362 return;
2363 }
2364
2365 const std::filesystem::path fs_path(path);
2366 const std::string path_stem = fs_path.stem().string();
2367 const std::string base_path = (fs_path.parent_path() / path_stem).string();
2368 paraviewo::VTMWriter vtm(t);
2369 save_vtu(path, space, output_fields, t, dt, opts, vtm, "");
2370 vtm.save(base_path + ".vtm");
2371 }
2372
2374 const std::string &path,
2375 const OutputSpace &space,
2376 const OutputFieldFunction &output_fields,
2377 const double t,
2378 const double dt,
2379 const ExportOptions &opts,
2380 paraviewo::VTMWriter &vtm,
2381 const std::string &block_prefix, WriteJobs *writes) const
2382 {
2383 if (!space.mesh)
2384 {
2385 logger().error("Load the mesh first!");
2386 return;
2387 }
2388
2389 const bool save_contact =
2390 space.collision_mesh
2392 || (!opts.fields.empty() && opts.export_field("adaptive_dhat")));
2393
2394 logger().info("Saving vtu to {}; volume={}, surface={}, contact={}, points={}, wireframe={}",
2395 path, opts.volume, opts.surface, save_contact, opts.points, opts.wire);
2396
2397 const std::filesystem::path fs_path(path);
2398 const std::string path_stem = fs_path.stem().string();
2399 const std::string base_path = (fs_path.parent_path() / path_stem).string();
2400
2401 if (opts.volume)
2402 {
2403 save_volume(base_path + opts.file_extension(), space, output_fields, t, dt, opts, writes);
2404 }
2405
2406 if (opts.surface)
2407 {
2408 save_surface(base_path + "_surf" + opts.file_extension(), space, output_fields, t, dt, opts, writes);
2409 }
2410
2411 if (save_contact)
2412 {
2413 save_contact_surface(base_path + "_surf" + opts.file_extension(), space, output_fields, t, dt, opts, writes);
2414 }
2415
2416 if (opts.wire)
2417 {
2418 save_wire(base_path + "_wire" + opts.file_extension(), space, output_fields, t, opts, writes);
2419 }
2420
2421 if (opts.points)
2422 {
2423 save_points(base_path + "_points" + opts.file_extension(), space, output_fields, opts, writes);
2424 }
2425
2426 const auto block_name = [&block_prefix](const std::string &name) {
2427 return block_prefix.empty() ? name : block_prefix + " " + name;
2428 };
2429 if (opts.volume)
2430 vtm.add_dataset(block_name("Volume"), "data", path_stem + opts.file_extension());
2431 if (opts.surface)
2432 vtm.add_dataset(block_name("Surface"), "data", path_stem + "_surf" + opts.file_extension());
2433 if (save_contact)
2434 vtm.add_dataset(block_name("Contact"), "data", path_stem + "_surf_contact" + opts.file_extension());
2435 if (opts.wire)
2436 vtm.add_dataset(block_name("Wireframe"), "data", path_stem + "_wire" + opts.file_extension());
2437 if (opts.points)
2438 vtm.add_dataset(block_name("Points"), "data", path_stem + "_points" + opts.file_extension());
2439 }
2440
2442 const std::string &path,
2443 const OutputSpace &space,
2444 const OutputFieldFunction &output_fields,
2445 const double t,
2446 const double dt,
2447 const ExportOptions &opts, WriteJobs *writes) const
2448 {
2449 if (!space.mesh || !space.geometry_bases)
2450 return;
2451
2452 static const std::map<int, Eigen::MatrixXd> empty_polys;
2453 static const std::map<int, std::pair<Eigen::MatrixXd, Eigen::MatrixXi>> empty_polys_3d;
2454
2455 const mesh::Mesh &mesh = *space.mesh;
2456 const std::vector<basis::ElementBases> &gbases = *space.geometry_bases;
2457 const std::map<int, Eigen::MatrixXd> &polys = space.polys ? *space.polys : empty_polys;
2458 const std::map<int, std::pair<Eigen::MatrixXd, Eigen::MatrixXi>> &polys_3d = space.polys_3d ? *space.polys_3d : empty_polys_3d;
2459 const Eigen::VectorXi output_orders =
2460 space.output_orders.size() == mesh.n_elements()
2461 ? space.output_orders
2462 : Eigen::VectorXi::Ones(mesh.n_elements());
2463 const mesh::Obstacle *obstacle = space.obstacle;
2464
2465 Eigen::MatrixXd points;
2466 Eigen::MatrixXi tets;
2467 Eigen::MatrixXi el_id;
2468 Eigen::MatrixXd discr;
2469 Eigen::MatrixXd local_points;
2470 std::vector<CellElement> elements;
2471
2472 if (opts.use_sampler)
2473 build_vis_mesh(mesh, output_orders, gbases,
2474 polys, polys_3d, opts.boundary_only,
2475 points, tets, el_id, discr, local_points);
2476 else
2477 {
2478 build_high_order_vis_mesh(mesh, output_orders, gbases,
2479 points, elements, el_id, discr, local_points);
2480 }
2481
2482 std::shared_ptr<paraviewo::ParaviewWriter> tmpw;
2483 if (opts.use_hdf5)
2484 tmpw = std::make_shared<paraviewo::HDF5VTUWriter>();
2485 else
2486 tmpw = std::make_shared<paraviewo::VTUWriter>();
2487 paraviewo::ParaviewWriter &writer = *tmpw;
2488
2489 if (obstacle && obstacle->n_vertices() > 0)
2490 {
2491 discr.conservativeResize(discr.size() + obstacle->n_vertices(), 1);
2492 discr.bottomRows(obstacle->n_vertices()).setZero();
2493 }
2494
2495 if (opts.discretization_order && opts.export_field("discr"))
2496 writer.add_field("discr", discr);
2497
2498 if (obstacle && obstacle->n_vertices() > 0)
2499 {
2500 const int orig_p = points.rows();
2501 points.conservativeResize(points.rows() + obstacle->n_vertices(), points.cols());
2502 points.bottomRows(obstacle->n_vertices()) = obstacle->v();
2503
2504 if (elements.empty())
2505 {
2506 for (int i = 0; i < tets.rows(); ++i)
2507 {
2508 elements.emplace_back();
2509 elements.back().ctype = mesh.is_volume() ? CellType::Tetrahedron : CellType::Triangle;
2510 for (int j = 0; j < tets.cols(); ++j)
2511 elements.back().vertices.push_back(tets(i, j));
2512 }
2513 }
2514
2515 const bool emit_obstacle_volume = opts.obstacle_volume && obstacle->n_tets() > 0;
2516
2517 if (emit_obstacle_volume)
2518 {
2519 // Volumetric export: emit obstacle tets only. Their boundary faces
2520 // will be shown by ParaView as the visible surface.
2521 for (int i = 0; i < obstacle->get_tet_connectivity().rows(); ++i)
2522 {
2523 elements.emplace_back();
2524 elements.back().ctype = CellType::Tetrahedron;
2525 for (int j = 0; j < obstacle->get_tet_connectivity().cols(); ++j)
2526 elements.back().vertices.push_back(obstacle->get_tet_connectivity()(i, j) + orig_p);
2527 }
2528 }
2529 else
2530 {
2531 for (int i = 0; i < obstacle->get_face_connectivity().rows(); ++i)
2532 {
2533 elements.emplace_back();
2534 elements.back().ctype = CellType::Triangle;
2535 for (int j = 0; j < obstacle->get_face_connectivity().cols(); ++j)
2536 elements.back().vertices.push_back(obstacle->get_face_connectivity()(i, j) + orig_p);
2537 }
2538
2539 for (int i = 0; i < obstacle->get_edge_connectivity().rows(); ++i)
2540 {
2541 elements.emplace_back();
2542 elements.back().ctype = CellType::Line;
2543 for (int j = 0; j < obstacle->get_edge_connectivity().cols(); ++j)
2544 elements.back().vertices.push_back(obstacle->get_edge_connectivity()(i, j) + orig_p);
2545 }
2546
2547 for (int i = 0; i < obstacle->get_vertex_connectivity().size(); ++i)
2548 {
2549 elements.emplace_back();
2550 elements.back().ctype = CellType::Vertex;
2551 elements.back().vertices.push_back(obstacle->get_vertex_connectivity()(i) + orig_p);
2552 }
2553 }
2554 }
2555
2556 // Write the solution alias last so it is the default for warp-by-vector.
2557 OutputSample sample;
2558 sample.points = points;
2559 sample.local_points = local_points;
2560 sample.element_ids = el_id.col(0);
2562 sample.cell_count = elements.empty() ? tets.rows() : static_cast<int>(elements.size());
2563 sample.time = t;
2564 sample.dt = dt;
2565 add_output_fields(writer, sample, output_fields);
2566
2567 if (opts.sol_on_grid && output_fields && grid_points.rows() > 0)
2568 {
2569 OutputSample grid_sample;
2570 grid_sample.points = grid_points;
2571 grid_sample.element_ids = grid_points_to_elements.col(0);
2572 grid_sample.domain = OutputSample::Domain::Grid;
2573 grid_sample.local_points.resize(grid_points.rows(), mesh.dimension());
2574 grid_sample.local_points.setZero();
2575 for (int i = 0; i < grid_points.rows(); ++i)
2576 {
2577 if (grid_sample.element_ids(i) >= 0)
2578 grid_sample.local_points.row(i) = grid_points_bc.row(i).rightCols(mesh.dimension());
2579 }
2580 grid_sample.time = t;
2581 grid_sample.dt = dt;
2582 grid_sample.requested_fields = {
2583 "solution",
2584 "solution_gradient",
2585 "pressure",
2586 "pressure_gradient",
2587 };
2588
2589 io::write_matrix(path + "_grid.txt", grid_points);
2590 for (const OutputField &field : output_fields(grid_sample))
2591 {
2592 if (field.association != OutputField::Association::Point || field.values.rows() != grid_points.rows())
2593 continue;
2594 if (field.name == "solution")
2595 io::write_matrix(path + "_sol.txt", field.values);
2596 else if (field.name == "solution_gradient")
2597 io::write_matrix(path + "_grad.txt", field.values);
2598 else if (field.name == "pressure")
2599 io::write_matrix(path + "_p_sol.txt", field.values);
2600 else if (field.name == "pressure_gradient")
2601 io::write_matrix(path + "_p_grad.txt", field.values);
2602 }
2603 }
2604
2605 if (elements.empty())
2606 write_output_mesh(writes, tmpw, path, std::move(points), std::move(tets), mesh.is_volume() ? CellType::Tetrahedron : CellType::Triangle);
2607 else
2608 write_output_mesh(writes, tmpw, path, std::move(points), std::move(elements));
2609 }
2610
2612 const std::string &export_surface,
2613 const OutputSpace &space,
2614 const OutputFieldFunction &output_fields,
2615 const double t,
2616 const double dt_in,
2617 const ExportOptions &opts, WriteJobs *writes) const
2618 {
2619 if (!space.mesh || !space.geometry_bases || !space.total_local_boundary)
2620 return;
2621
2622 const mesh::Mesh &mesh = *space.mesh;
2623 const std::vector<basis::ElementBases> &gbases = *space.geometry_bases;
2624
2625 Eigen::MatrixXd boundary_vis_vertices;
2626 Eigen::MatrixXd boundary_vis_local_vertices;
2627 Eigen::MatrixXi boundary_vis_elements;
2628 Eigen::MatrixXi boundary_vis_elements_ids;
2629 Eigen::MatrixXi boundary_vis_primitive_ids;
2630 Eigen::MatrixXd boundary_vis_normals;
2631
2632 build_vis_boundary_mesh(mesh, gbases, *space.total_local_boundary,
2633 boundary_vis_vertices, boundary_vis_local_vertices, boundary_vis_elements,
2634 boundary_vis_elements_ids, boundary_vis_primitive_ids, boundary_vis_normals);
2635
2636 Eigen::MatrixXd discr, b_sidesets;
2637 discr.resize(boundary_vis_vertices.rows(), 1);
2638 b_sidesets.resize(boundary_vis_vertices.rows(), 1);
2639 b_sidesets.setZero();
2640
2641 for (int i = 0; i < boundary_vis_vertices.rows(); ++i)
2642 {
2643 const auto s_id = mesh.get_boundary_id(boundary_vis_primitive_ids(i));
2644 if (s_id > 0)
2645 {
2646 b_sidesets(i) = s_id;
2647 }
2648
2649 const int el_index = boundary_vis_elements_ids(i);
2650 discr(i) = space.output_orders.size() == mesh.n_elements() ? space.output_orders(el_index) : 1;
2651 }
2652
2653 std::shared_ptr<paraviewo::ParaviewWriter> tmpw;
2654 if (opts.use_hdf5)
2655 tmpw = std::make_shared<paraviewo::HDF5VTUWriter>();
2656 else
2657 tmpw = std::make_shared<paraviewo::VTUWriter>();
2658 paraviewo::ParaviewWriter &writer = *tmpw;
2659
2660 if (opts.export_field("normals"))
2661 writer.add_field("normals", boundary_vis_normals);
2662 if (opts.export_field("discr"))
2663 writer.add_field("discr", discr);
2664 if (opts.export_field("sidesets"))
2665 writer.add_field("sidesets", b_sidesets);
2666
2667 // Write the solution alias last so it is the default for warp-by-vector.
2668 OutputSample sample;
2669 sample.points = boundary_vis_vertices;
2670 sample.local_points = boundary_vis_local_vertices;
2671 sample.element_ids = boundary_vis_elements_ids.col(0);
2672 sample.primitive_ids = boundary_vis_primitive_ids;
2673 sample.normals = boundary_vis_normals;
2675 sample.cell_count = boundary_vis_elements.rows();
2676 sample.time = t;
2677 sample.dt = dt_in;
2678 add_output_fields(writer, sample, output_fields);
2679 write_output_mesh(writes, tmpw, export_surface, std::move(boundary_vis_vertices), std::move(boundary_vis_elements), mesh.is_volume() ? CellType::Triangle : CellType::Line);
2680 }
2681
2683 const std::string &export_surface,
2684 const OutputSpace &space,
2685 const OutputFieldFunction &output_fields,
2686 const double t,
2687 const double dt_in,
2688 const ExportOptions &opts, WriteJobs *writes) const
2689 {
2690 if (!space.collision_mesh)
2691 return;
2692
2693 const ipc::CollisionMesh &collision_mesh = *space.collision_mesh;
2694
2695 std::shared_ptr<paraviewo::ParaviewWriter> tmpw;
2696 if (opts.use_hdf5)
2697 tmpw = std::make_shared<paraviewo::HDF5VTUWriter>();
2698 else
2699 tmpw = std::make_shared<paraviewo::VTUWriter>();
2700 paraviewo::ParaviewWriter &writer = *tmpw;
2701
2702 // Write the solution alias last so it is the default for warp-by-vector.
2703 OutputSample sample;
2704 sample.points = collision_mesh.rest_positions();
2706 sample.cell_count = static_cast<int>(
2707 collision_mesh.dim() == 3 ? collision_mesh.num_faces() : collision_mesh.num_edges());
2708 sample.time = t;
2709 sample.dt = dt_in;
2710 add_output_fields(writer, sample, output_fields);
2711
2712 const std::filesystem::path surface_path(export_surface);
2713 const std::string contact_path =
2714 (surface_path.parent_path() / (surface_path.stem().string() + "_contact" + surface_path.extension().string())).string();
2715 write_output_mesh(writes, tmpw,
2716 contact_path,
2717 collision_mesh.rest_positions(),
2718 collision_mesh.dim() == 3 ? collision_mesh.faces() : collision_mesh.edges(),
2719 collision_mesh.dim() == 3 ? CellType::Triangle : CellType::Line);
2720 }
2721
2723 const std::string &name,
2724 const OutputSpace &space,
2725 const OutputFieldFunction &output_fields,
2726 const double t,
2727 const ExportOptions &opts, WriteJobs *writes) const
2728 {
2729 if (!space.mesh || !space.geometry_bases)
2730 return;
2731
2732 static const std::map<int, Eigen::MatrixXd> empty_polys;
2733 static const std::map<int, std::pair<Eigen::MatrixXd, Eigen::MatrixXi>> empty_polys_3d;
2734
2735 const std::vector<basis::ElementBases> &gbases = *space.geometry_bases;
2736 const mesh::Mesh &mesh = *space.mesh;
2737 const std::map<int, Eigen::MatrixXd> &polys = space.polys ? *space.polys : empty_polys;
2738 const std::map<int, std::pair<Eigen::MatrixXd, Eigen::MatrixXi>> &polys_3d = space.polys_3d ? *space.polys_3d : empty_polys_3d;
2739 const Eigen::VectorXi output_orders =
2740 space.output_orders.size() == mesh.n_elements()
2741 ? space.output_orders
2742 : Eigen::VectorXi::Ones(mesh.n_elements());
2743
2744 Eigen::MatrixXd points, discr, local_points;
2745 Eigen::MatrixXi cells, element_ids, edges;
2746 build_vis_mesh(mesh, output_orders, gbases, polys, polys_3d, /*boundary_only=*/false, points, cells, element_ids, discr, local_points);
2747 if (cells.size() > 0)
2748 igl::edges(cells, edges);
2749 else
2750 edges.resize(0, 2);
2751
2752 std::shared_ptr<paraviewo::ParaviewWriter> tmpw;
2753 if (opts.use_hdf5)
2754 tmpw = std::make_shared<paraviewo::HDF5VTUWriter>();
2755 else
2756 tmpw = std::make_shared<paraviewo::VTUWriter>();
2757 paraviewo::ParaviewWriter &writer = *tmpw;
2758
2759 // Write the solution alias last so it is the default for warp-by-vector.
2760 OutputSample sample;
2761 sample.points = points;
2762 sample.local_points = local_points;
2763 if (element_ids.cols() > 0)
2764 sample.element_ids = element_ids.col(0);
2766 sample.cell_count = edges.rows();
2767 sample.time = t;
2768 add_output_fields(writer, sample, output_fields);
2769
2770 write_output_mesh(writes, tmpw, name, std::move(points), std::move(edges), CellType::Line);
2771 }
2772
2774 const std::string &path,
2775 const OutputSpace &space,
2776 const OutputFieldFunction &output_fields,
2777 const ExportOptions &opts, WriteJobs *writes) const
2778 {
2779 if (!space.mesh || !space.dirichlet_nodes || !space.dirichlet_nodes_position)
2780 return;
2781
2782 const auto &dirichlet_nodes = *space.dirichlet_nodes;
2783 const auto &dirichlet_nodes_position = *space.dirichlet_nodes_position;
2784 const mesh::Mesh &mesh = *space.mesh;
2785
2786 Eigen::MatrixXd b_sidesets(dirichlet_nodes_position.size(), 1);
2787 b_sidesets.setZero();
2788 Eigen::MatrixXd points(dirichlet_nodes_position.size(), mesh.dimension());
2789 std::vector<CellElement> cells(dirichlet_nodes_position.size());
2790
2791 for (int i = 0; i < dirichlet_nodes_position.size(); ++i)
2792 {
2793 const int n_id = dirichlet_nodes[i];
2794 const int s_id = space.mesh_nodes ? space.mesh_nodes->node_tag(n_id) : -1;
2795 if (s_id > 0)
2796 {
2797 b_sidesets(i) = s_id;
2798 }
2799
2800 points.row(i) = dirichlet_nodes_position[i];
2801 cells[i].vertices.push_back(i);
2802 cells[i].ctype = CellType::Vertex;
2803 }
2804
2805 std::shared_ptr<paraviewo::ParaviewWriter> tmpw;
2806 if (opts.use_hdf5)
2807 tmpw = std::make_shared<paraviewo::HDF5VTUWriter>();
2808 else
2809 tmpw = std::make_shared<paraviewo::VTUWriter>();
2810 paraviewo::ParaviewWriter &writer = *tmpw;
2811
2812 if (opts.export_field("sidesets"))
2813 writer.add_field("sidesets", b_sidesets);
2814
2815 // Write the solution alias last so it is the default for warp-by-vector.
2816 OutputSample sample;
2817 sample.points = points;
2818 sample.node_ids.resize(dirichlet_nodes.size());
2819 for (int i = 0; i < dirichlet_nodes.size(); ++i)
2820 sample.node_ids(i) = dirichlet_nodes[i];
2822 sample.cell_count = static_cast<int>(cells.size());
2823 add_output_fields(writer, sample, output_fields);
2824 write_output_mesh(writes, tmpw, path, std::move(points), std::move(cells));
2825 }
2826
2828 const std::string &name,
2829 const std::function<std::string(int)> &vtu_names,
2830 int time_steps, double t0, double dt, int skip_frame) const
2831 {
2832 paraviewo::PVDWriter::save_pvd(name, vtu_names, time_steps, t0, dt, skip_frame);
2833 }
2834
2835 void OutGeometryData::init_sampler(const polyfem::mesh::Mesh &mesh, const double vismesh_rel_area)
2836 {
2837 ref_element_sampler.init(mesh.is_volume(), mesh.n_elements(), vismesh_rel_area);
2838 }
2839
2840 void OutGeometryData::build_grid(const polyfem::mesh::Mesh &mesh, const double spacing)
2841 {
2842 if (spacing <= 0)
2843 return;
2844
2845 RowVectorNd min, max;
2846 mesh.bounding_box(min, max);
2847 const RowVectorNd delta = max - min;
2848 const int nx = delta[0] / spacing + 1;
2849 const int ny = delta[1] / spacing + 1;
2850 const int nz = delta.cols() >= 3 ? (delta[2] / spacing + 1) : 1;
2851 const int n = nx * ny * nz;
2852
2853 grid_points.resize(n, delta.cols());
2854 int index = 0;
2855 for (int i = 0; i < nx; ++i)
2856 {
2857 const double x = (delta[0] / (nx - 1)) * i + min[0];
2858
2859 for (int j = 0; j < ny; ++j)
2860 {
2861 const double y = (delta[1] / (ny - 1)) * j + min[1];
2862
2863 if (delta.cols() <= 2)
2864 {
2865 grid_points.row(index++) << x, y;
2866 }
2867 else
2868 {
2869 for (int k = 0; k < nz; ++k)
2870 {
2871 const double z = (delta[2] / (nz - 1)) * k + min[2];
2872 grid_points.row(index++) << x, y, z;
2873 }
2874 }
2875 }
2876 }
2877
2878 assert(index == n);
2879
2880 std::vector<std::array<Eigen::Vector3d, 2>> boxes;
2881 mesh.elements_boxes(boxes);
2882
2883 SimpleBVH::BVH bvh;
2884 bvh.init(boxes);
2885
2886 const double eps = 1e-6;
2887
2888 grid_points_to_elements.resize(grid_points.rows(), 1);
2889 grid_points_to_elements.setConstant(-1);
2890
2891 grid_points_bc.resize(grid_points.rows(), mesh.is_volume() ? 4 : 3);
2892
2893 for (int i = 0; i < grid_points.rows(); ++i)
2894 {
2895 const Eigen::Vector3d min(
2896 grid_points(i, 0) - eps,
2897 grid_points(i, 1) - eps,
2898 (mesh.is_volume() ? grid_points(i, 2) : 0) - eps);
2899
2900 const Eigen::Vector3d max(
2901 grid_points(i, 0) + eps,
2902 grid_points(i, 1) + eps,
2903 (mesh.is_volume() ? grid_points(i, 2) : 0) + eps);
2904
2905 std::vector<unsigned int> candidates;
2906
2907 bvh.intersect_box(min, max, candidates);
2908
2909 for (const auto cand : candidates)
2910 {
2911 if (!mesh.is_simplex(cand))
2912 {
2913 logger().warn("Element {} is not simplex, skipping", cand);
2914 continue;
2915 }
2916
2917 Eigen::MatrixXd coords;
2918 mesh.barycentric_coords(grid_points.row(i), cand, coords);
2919
2920 for (int d = 0; d < coords.size(); ++d)
2921 {
2922 if (fabs(coords(d)) < 1e-8)
2923 coords(d) = 0;
2924 else if (fabs(coords(d) - 1) < 1e-8)
2925 coords(d) = 1;
2926 }
2927
2928 if (coords.array().minCoeff() >= 0 && coords.array().maxCoeff() <= 1)
2929 {
2930 grid_points_to_elements(i) = cand;
2931 grid_points_bc.row(i) = coords;
2932 break;
2933 }
2934 }
2935 }
2936 }
2937
2938 void OutStatsData::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)
2939 {
2940 Eigen::MatrixXd samples_simplex, samples_cube, mapped, p0, p1, p;
2941
2942 mesh_size = 0;
2943 average_edge_length = 0;
2944 min_edge_length = std::numeric_limits<double>::max();
2945
2946 if (!use_curved_mesh_size)
2947 {
2948 mesh_in.get_edges(p0, p1);
2949 p = p0 - p1;
2950 min_edge_length = p.rowwise().norm().minCoeff();
2951 average_edge_length = p.rowwise().norm().mean();
2952 mesh_size = p.rowwise().norm().maxCoeff();
2953
2954 logger().info("hmin: {}", min_edge_length);
2955 logger().info("hmax: {}", mesh_size);
2956 logger().info("havg: {}", average_edge_length);
2957
2958 return;
2959 }
2960
2961 if (mesh_in.is_volume())
2962 {
2963 utils::EdgeSampler::sample_3d_simplex(n_samples, samples_simplex);
2964 utils::EdgeSampler::sample_3d_cube(n_samples, samples_cube);
2965 }
2966 else
2967 {
2968 utils::EdgeSampler::sample_2d_simplex(n_samples, samples_simplex);
2969 utils::EdgeSampler::sample_2d_cube(n_samples, samples_cube);
2970 }
2971
2972 int n = 0;
2973 for (size_t i = 0; i < bases_in.size(); ++i)
2974 {
2975 if (mesh_in.is_polytope(i))
2976 continue;
2977 int n_edges;
2978
2979 if (mesh_in.is_simplex(i))
2980 {
2981 n_edges = mesh_in.is_volume() ? 6 : 3;
2982 bases_in[i].eval_geom_mapping(samples_simplex, mapped);
2983 }
2984 else
2985 {
2986 n_edges = mesh_in.is_volume() ? 12 : 4;
2987 bases_in[i].eval_geom_mapping(samples_cube, mapped);
2988 }
2989
2990 for (int j = 0; j < n_edges; ++j)
2991 {
2992 double current_edge = 0;
2993 for (int k = 0; k < n_samples - 1; ++k)
2994 {
2995 p0 = mapped.row(j * n_samples + k);
2996 p1 = mapped.row(j * n_samples + k + 1);
2997 p = p0 - p1;
2998
2999 current_edge += p.norm();
3000 }
3001
3002 mesh_size = std::max(current_edge, mesh_size);
3003 min_edge_length = std::min(current_edge, min_edge_length);
3004 average_edge_length += current_edge;
3005 ++n;
3006 }
3007 }
3008
3009 average_edge_length /= n;
3010
3011 logger().info("hmin: {}", min_edge_length);
3012 logger().info("hmax: {}", mesh_size);
3013 logger().info("havg: {}", average_edge_length);
3014 }
3015
3017 {
3018 *this = OutStatsData();
3019 }
3020
3021 void OutStatsData::count_flipped_elements(const polyfem::mesh::Mesh &mesh, const std::vector<polyfem::basis::ElementBases> &gbases)
3022 {
3023 using namespace mesh;
3024
3025 logger().info("Counting flipped elements...");
3026 const auto &els_tag = mesh.elements_tag();
3027
3028 // flipped_elements.clear();
3029 for (size_t i = 0; i < gbases.size(); ++i)
3030 {
3031 if (mesh.is_polytope(i))
3032 continue;
3033
3035 if (!vals.is_geom_mapping_positive(mesh.is_volume(), gbases[i]))
3036 {
3037 ++n_flipped;
3038
3039 static const std::vector<std::string> element_type_names{{
3040 "Simplex",
3041 "RegularInteriorCube",
3042 "RegularBoundaryCube",
3043 "SimpleSingularInteriorCube",
3044 "MultiSingularInteriorCube",
3045 "SimpleSingularBoundaryCube",
3046 "InterfaceCube",
3047 "MultiSingularBoundaryCube",
3048 "BoundaryPolytope",
3049 "InteriorPolytope",
3050 "Undefined",
3051 }};
3052
3053 log_and_throw_error("element {} is flipped, type {}", i, element_type_names[static_cast<int>(els_tag[i])]);
3054 }
3055 }
3056
3057 logger().info(" done");
3058
3059 // dynamic_cast<Mesh3D *>(mesh.get())->save({56}, 1, "mesh.HYBRID");
3060
3061 // std::sort(flipped_elements.begin(), flipped_elements.end());
3062 // auto it = std::unique(flipped_elements.begin(), flipped_elements.end());
3063 // flipped_elements.resize(std::distance(flipped_elements.begin(), it));
3064 }
3065
3067 const int n_bases,
3068 const std::vector<polyfem::basis::ElementBases> &bases,
3069 const std::vector<polyfem::basis::ElementBases> &gbases,
3070 const polyfem::mesh::Mesh &mesh,
3071 const assembler::Problem &problem,
3072 const double tend,
3073 const Eigen::MatrixXd &sol)
3074 {
3075 if (n_bases <= 0)
3076 {
3077 logger().error("Build the bases first!");
3078 return;
3079 }
3080 if (sol.size() <= 0)
3081 {
3082 logger().error("Solve the problem first!");
3083 return;
3084 }
3085
3086 int actual_dim = 1;
3087 if (!problem.is_scalar())
3088 actual_dim = mesh.dimension();
3089
3090 igl::Timer timer;
3091 timer.start();
3092 logger().info("Computing errors...");
3093 using std::max;
3094
3095 const int n_el = int(bases.size());
3096
3097 Eigen::MatrixXd v_exact, v_approx;
3098 Eigen::MatrixXd v_exact_grad(0, 0), v_approx_grad;
3099
3100 l2_err = 0;
3101 h1_err = 0;
3102 grad_max_err = 0;
3103 h1_semi_err = 0;
3104 linf_err = 0;
3105 lp_err = 0;
3106 // double pred_norm = 0;
3107
3108 static const int p = 8;
3109
3110 // Eigen::MatrixXd err_per_el(n_el, 5);
3112
3113 for (int e = 0; e < n_el; ++e)
3114 {
3115 vals.compute(e, mesh.is_volume(), bases[e], gbases[e]);
3116
3117 if (problem.has_exact_sol())
3118 {
3119 problem.exact(vals.val, tend, v_exact);
3120 problem.exact_grad(vals.val, tend, v_exact_grad);
3121 }
3122
3123 v_approx.resize(vals.val.rows(), actual_dim);
3124 v_approx.setZero();
3125
3126 v_approx_grad.resize(vals.val.rows(), mesh.dimension() * actual_dim);
3127 v_approx_grad.setZero();
3128
3129 const int n_loc_bases = int(vals.basis_values.size());
3130
3131 for (int i = 0; i < n_loc_bases; ++i)
3132 {
3133 const auto &val = vals.basis_values[i];
3134
3135 for (size_t ii = 0; ii < val.global.size(); ++ii)
3136 {
3137 for (int d = 0; d < actual_dim; ++d)
3138 {
3139 v_approx.col(d) += val.global[ii].val * sol(val.global[ii].index * actual_dim + d) * val.val;
3140 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;
3141 }
3142 }
3143 }
3144
3145 const auto err = problem.has_exact_sol() ? (v_exact - v_approx).eval().rowwise().norm().eval() : (v_approx).eval().rowwise().norm().eval();
3146 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();
3147
3148 // for(long i = 0; i < err.size(); ++i)
3149 // errors.push_back(err(i));
3150
3151 linf_err = std::max(linf_err, err.maxCoeff());
3152 grad_max_err = std::max(linf_err, err_grad.maxCoeff());
3153
3154 // {
3155 // const auto &mesh3d = *dynamic_cast<Mesh3D *>(mesh.get());
3156 // const auto v0 = mesh3d.point(mesh3d.cell_vertex(e, 0));
3157 // const auto v1 = mesh3d.point(mesh3d.cell_vertex(e, 1));
3158 // const auto v2 = mesh3d.point(mesh3d.cell_vertex(e, 2));
3159 // const auto v3 = mesh3d.point(mesh3d.cell_vertex(e, 3));
3160
3161 // Eigen::Matrix<double, 6, 3> ee;
3162 // ee.row(0) = v0 - v1;
3163 // ee.row(1) = v1 - v2;
3164 // ee.row(2) = v2 - v0;
3165
3166 // ee.row(3) = v0 - v3;
3167 // ee.row(4) = v1 - v3;
3168 // ee.row(5) = v2 - v3;
3169
3170 // Eigen::Matrix<double, 6, 1> en = ee.rowwise().norm();
3171
3172 // // Eigen::Matrix<double, 3*4, 1> alpha;
3173 // // alpha(0) = angle3(e.row(0), -e.row(1)); alpha(1) = angle3(e.row(1), -e.row(2)); alpha(2) = angle3(e.row(2), -e.row(0));
3174 // // alpha(3) = angle3(e.row(0), -e.row(4)); alpha(4) = angle3(e.row(4), e.row(3)); alpha(5) = angle3(-e.row(3), -e.row(0));
3175 // // alpha(6) = angle3(-e.row(4), -e.row(1)); alpha(7) = angle3(e.row(1), -e.row(5)); alpha(8) = angle3(e.row(5), e.row(4));
3176 // // alpha(9) = angle3(-e.row(2), -e.row(5)); alpha(10) = angle3(e.row(5), e.row(3)); alpha(11) = angle3(-e.row(3), e.row(2));
3177
3178 // const double S = (ee.row(0).cross(ee.row(1)).norm() + ee.row(0).cross(ee.row(4)).norm() + ee.row(4).cross(ee.row(1)).norm() + ee.row(2).cross(ee.row(5)).norm()) / 2;
3179 // const double V = std::abs(ee.row(3).dot(ee.row(2).cross(-ee.row(0))))/6;
3180 // const double rho = 3 * V / S;
3181 // const double hp = en.maxCoeff();
3182 // const int pp = disc_orders(e);
3183 // const int p_ref = args["space"]["discr_order"];
3184
3185 // err_per_el(e, 0) = err.mean();
3186 // err_per_el(e, 1) = err.maxCoeff();
3187 // err_per_el(e, 2) = std::pow(hp, pp+1)/(rho/hp); // /std::pow(average_edge_length, p_ref+1) * (sqrt(6)/12);
3188 // err_per_el(e, 3) = rho/hp;
3189 // err_per_el(e, 4) = (vals.det.array() * vals.quadrature.weights.array()).sum();
3190
3191 // // pred_norm += (pow(std::pow(hp, pp+1)/(rho/hp),p) * vals.det.array() * vals.quadrature.weights.array()).sum();
3192 // }
3193
3194 l2_err += (err.array() * err.array() * vals.det.array() * vals.quadrature.weights.array()).sum();
3195 h1_err += (err_grad.array() * err_grad.array() * vals.det.array() * vals.quadrature.weights.array()).sum();
3196 lp_err += (err.array().pow(p) * vals.det.array() * vals.quadrature.weights.array()).sum();
3197 }
3198
3199 h1_semi_err = sqrt(fabs(h1_err));
3200 h1_err = sqrt(fabs(l2_err) + fabs(h1_err));
3201 l2_err = sqrt(fabs(l2_err));
3202
3203 lp_err = pow(fabs(lp_err), 1. / p);
3204
3205 // pred_norm = pow(fabs(pred_norm), 1./p);
3206
3207 timer.stop();
3208 const double computing_errors_time = timer.getElapsedTime();
3209 logger().info(" took {}s", computing_errors_time);
3210
3211 logger().info("-- L2 error: {}", l2_err);
3212 logger().info("-- Lp error: {}", lp_err);
3213 logger().info("-- H1 error: {}", h1_err);
3214 logger().info("-- H1 semi error: {}", h1_semi_err);
3215 // logger().info("-- Perd norm: {}", pred_norm);
3216
3217 logger().info("-- Linf error: {}", linf_err);
3218 logger().info("-- grad max error: {}", grad_max_err);
3219
3220 // {
3221 // std::ofstream out("errs.txt");
3222 // out<<err_per_el;
3223 // out.close();
3224 // }
3225 }
3226
3228 {
3229 using namespace polyfem::mesh;
3230
3231 simplex_count = 0;
3232 prism_count = 0;
3233 pyramid_count = 0;
3234 regular_count = 0;
3235 regular_boundary_count = 0;
3236 simple_singular_count = 0;
3237 multi_singular_count = 0;
3238 boundary_count = 0;
3239 non_regular_boundary_count = 0;
3240 non_regular_count = 0;
3241 undefined_count = 0;
3242 multi_singular_boundary_count = 0;
3243
3244 const auto &els_tag = mesh.elements_tag();
3245
3246 for (size_t i = 0; i < els_tag.size(); ++i)
3247 {
3248 const ElementType type = els_tag[i];
3249
3250 switch (type)
3251 {
3252 case ElementType::SIMPLEX:
3253 simplex_count++;
3254 break;
3255 case ElementType::PRISM:
3256 prism_count++;
3257 break;
3258 case ElementType::PYRAMID:
3259 pyramid_count++;
3260 break;
3261 case ElementType::REGULAR_INTERIOR_CUBE:
3262 regular_count++;
3263 break;
3264 case ElementType::REGULAR_BOUNDARY_CUBE:
3265 regular_boundary_count++;
3266 break;
3267 case ElementType::SIMPLE_SINGULAR_INTERIOR_CUBE:
3268 simple_singular_count++;
3269 break;
3270 case ElementType::MULTI_SINGULAR_INTERIOR_CUBE:
3271 multi_singular_count++;
3272 break;
3273 case ElementType::SIMPLE_SINGULAR_BOUNDARY_CUBE:
3274 boundary_count++;
3275 break;
3276 case ElementType::INTERFACE_CUBE:
3277 case ElementType::MULTI_SINGULAR_BOUNDARY_CUBE:
3278 multi_singular_boundary_count++;
3279 break;
3280 case ElementType::BOUNDARY_POLYTOPE:
3281 non_regular_boundary_count++;
3282 break;
3283 case ElementType::INTERIOR_POLYTOPE:
3284 non_regular_count++;
3285 break;
3286 case ElementType::UNDEFINED:
3287 undefined_count++;
3288 break;
3289 default:
3290 throw std::runtime_error("Unknown element type");
3291 }
3292 }
3293
3294 logger().info("simplex_count: \t{}", simplex_count);
3295 logger().info("prism_count: \t{}", prism_count);
3296 logger().info("pyramid_count: \t{}", pyramid_count);
3297 logger().info("regular_count: \t{}", regular_count);
3298 logger().info("regular_boundary_count: \t{}", regular_boundary_count);
3299 logger().info("simple_singular_count: \t{}", simple_singular_count);
3300 logger().info("multi_singular_count: \t{}", multi_singular_count);
3301 logger().info("boundary_count: \t{}", boundary_count);
3302 logger().info("multi_singular_boundary_count: \t{}", multi_singular_boundary_count);
3303 logger().info("non_regular_count: \t{}", non_regular_count);
3304 logger().info("non_regular_boundary_count: \t{}", non_regular_boundary_count);
3305 logger().info("undefined_count: \t{}", undefined_count);
3306 logger().info("total count:\t {}", mesh.n_elements());
3307 }
3308
3310 const nlohmann::json &args,
3311 const int n_bases, const int n_pressure_bases,
3312 const Eigen::MatrixXd &sol,
3313 const mesh::Mesh &mesh,
3314 const Eigen::VectorXi &disc_orders,
3315 const Eigen::VectorXi &disc_ordersq,
3316 const assembler::Problem &problem,
3317 const OutRuntimeData &runtime,
3318 const std::string &formulation,
3319 const bool isoparametric,
3320 const int sol_at_node_id,
3321 nlohmann::json &j) const
3322 {
3323
3324 j["args"] = args;
3325
3326 j["geom_order"] = mesh.orders().size() > 0 ? mesh.orders().maxCoeff() : 1;
3327 j["geom_order_min"] = mesh.orders().size() > 0 ? mesh.orders().minCoeff() : 1;
3328 j["discr_order_min"] = disc_orders.minCoeff();
3329 j["discr_order_max"] = disc_orders.maxCoeff();
3330 j["discr_orderq_min"] = disc_ordersq.minCoeff();
3331 j["discr_orderq_max"] = disc_ordersq.maxCoeff();
3332 j["iso_parametric"] = isoparametric;
3333 j["problem"] = problem.name();
3334 j["mat_size"] = mat_size;
3335 j["num_bases"] = n_bases;
3336 j["num_pressure_bases"] = n_pressure_bases;
3337 j["num_non_zero"] = nn_zero;
3338 j["num_flipped"] = n_flipped;
3339 j["num_dofs"] = num_dofs;
3340 j["num_vertices"] = mesh.n_vertices();
3341 j["num_elements"] = mesh.n_elements();
3342
3343 j["num_p1"] = (disc_orders.array() == 1).count();
3344 j["num_p2"] = (disc_orders.array() == 2).count();
3345 j["num_p3"] = (disc_orders.array() == 3).count();
3346 j["num_p4"] = (disc_orders.array() == 4).count();
3347 j["num_p5"] = (disc_orders.array() == 5).count();
3348
3349 j["mesh_size"] = mesh_size;
3350 j["max_angle"] = max_angle;
3351
3352 j["sigma_max"] = sigma_max;
3353 j["sigma_min"] = sigma_min;
3354 j["sigma_avg"] = sigma_avg;
3355
3356 j["min_edge_length"] = min_edge_length;
3357 j["average_edge_length"] = average_edge_length;
3358
3359 j["err_l2"] = l2_err;
3360 j["err_h1"] = h1_err;
3361 j["err_h1_semi"] = h1_semi_err;
3362 j["err_linf"] = linf_err;
3363 j["err_linf_grad"] = grad_max_err;
3364 j["err_lp"] = lp_err;
3365
3366 j["spectrum"] = {spectrum(0), spectrum(1), spectrum(2), spectrum(3)};
3367 j["spectrum_condest"] = std::abs(spectrum(3)) / std::abs(spectrum(0));
3368
3369 // j["errors"] = errors;
3370
3371 j["time_building_basis"] = runtime.building_basis_time;
3372 j["time_loading_mesh"] = runtime.loading_mesh_time;
3373 j["time_computing_poly_basis"] = runtime.computing_poly_basis_time;
3374 j["time_assembling_stiffness_mat"] = runtime.assembling_stiffness_mat_time;
3375 j["time_assembling_mass_mat"] = runtime.assembling_mass_mat_time;
3376 j["time_assigning_rhs"] = runtime.assigning_rhs_time;
3377 j["time_solving"] = runtime.solving_time;
3378 // j["time_computing_errors"] = runtime.computing_errors_time;
3379
3380 j["solver_info"] = solver_info;
3381
3382 j["count_simplex"] = simplex_count;
3383 j["count_prism"] = prism_count;
3384 j["count_pyramid"] = pyramid_count;
3385 j["count_regular"] = regular_count;
3386 j["count_regular_boundary"] = regular_boundary_count;
3387 j["count_simple_singular"] = simple_singular_count;
3388 j["count_multi_singular"] = multi_singular_count;
3389 j["count_boundary"] = boundary_count;
3390 j["count_non_regular_boundary"] = non_regular_boundary_count;
3391 j["count_non_regular"] = non_regular_count;
3392 j["count_undefined"] = undefined_count;
3393 j["count_multi_singular_boundary"] = multi_singular_boundary_count;
3394
3395 j["is_simplicial"] = mesh.n_elements() == simplex_count;
3396
3397 j["peak_memory"] = getPeakRSS() / (1024 * 1024);
3398
3399 const int actual_dim = problem.is_scalar() ? 1 : mesh.dimension();
3400
3401 std::vector<double> mmin(actual_dim);
3402 std::vector<double> mmax(actual_dim);
3403
3404 for (int d = 0; d < actual_dim; ++d)
3405 {
3406 mmin[d] = std::numeric_limits<double>::max();
3407 mmax[d] = -std::numeric_limits<double>::max();
3408 }
3409
3410 for (int i = 0; i < sol.size(); i += actual_dim)
3411 {
3412 for (int d = 0; d < actual_dim; ++d)
3413 {
3414 mmin[d] = std::min(mmin[d], sol(i + d));
3415 mmax[d] = std::max(mmax[d], sol(i + d));
3416 }
3417 }
3418
3419 std::vector<double> sol_at_node(actual_dim);
3420
3421 if (sol_at_node_id >= 0)
3422 {
3423 const int node_id = sol_at_node_id;
3424
3425 for (int d = 0; d < actual_dim; ++d)
3426 {
3427 sol_at_node[d] = sol(node_id * actual_dim + d);
3428 }
3429 }
3430
3431 j["sol_at_node"] = sol_at_node;
3432 j["sol_min"] = mmin;
3433 j["sol_max"] = mmax;
3434
3435#if defined(POLYFEM_WITH_CPP_THREADS)
3436 j["num_threads"] = utils::get_n_threads();
3437#elif defined(POLYFEM_WITH_TBB)
3438 j["num_threads"] = utils::get_n_threads();
3439#else
3440 j["num_threads"] = 1;
3441#endif
3442
3443 j["formulation"] = formulation;
3444
3445 logger().info("done");
3446 }
3447
3448} // namespace polyfem::io
double val
ElementAssemblyValues vals
std::vector< std::pair< int, double > > weights
int y
int z
int x
stores per element basis values at given quadrature points and geometric mapping
void compute(const int el_index, const bool is_volume, const Eigen::MatrixXd &pts, const basis::ElementBases &basis, const basis::ElementBases &gbasis)
computes the per element values at the local (ref el) points (pts) sets basis_values,...
const std::string & name() const
Definition Problem.hpp:32
virtual void exact_grad(const Eigen::MatrixXd &pts, const double t, Eigen::MatrixXd &val) const
Definition Problem.hpp:64
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
Definition Problem.hpp:63
Represents one basis function and its gradient.
Definition Basis.hpp:44
const std::vector< Local2Global > & global() const
Definition Basis.hpp:104
Stores the basis functions for a given element in a mesh (facet in 2d, cell in 3d).
void build_vis_boundary_mesh(const mesh::Mesh &mesh, const std::vector< basis::ElementBases > &gbases, const std::vector< mesh::LocalBoundary > &total_local_boundary, 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) const
builds the boundary mesh for visualization
Definition OutData.cpp:1625
Eigen::MatrixXd grid_points_bc
grid mesh boundaries
Definition OutData.hpp:269
void build_high_order_vis_mesh(const mesh::Mesh &mesh, const Eigen::VectorXi &output_orders, const std::vector< basis::ElementBases > &bases, Eigen::MatrixXd &points, std::vector< paraviewo::CellElement > &elements, Eigen::MatrixXi &el_id, Eigen::MatrixXd &discr, Eigen::MatrixXd &local_points) const
builds high-der visualzation mesh per element all disconnected it also retuns the mapping to element ...
Definition OutData.cpp:2026
Eigen::MatrixXd grid_points
grid mesh points to export solution sampled on a grid
Definition OutData.hpp:265
void save_wire(const std::string &name, const OutputSpace &space, const OutputFieldFunction &output_fields, const double t, const ExportOptions &opts, WriteJobs *writes=nullptr) const
saves the wireframe
Definition OutData.cpp:2722
static void extract_boundary_mesh_2d_sampled(const mesh::Mesh &mesh, const int n_bases, const std::vector< basis::ElementBases > &bases, const std::vector< basis::ElementBases > &geom_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, const int sampling_order=0)
Sample 2D FE boundary displacements at Lagrange nodes, using the geometry bases for rest positions (i...
Definition OutData.cpp:460
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, Eigen::MatrixXd &local_points) const
builds visualzation mesh, upsampled mesh used for visualization the visualization mesh is a dense mes...
Definition OutData.cpp:1851
void save_points(const std::string &path, const OutputSpace &space, const OutputFieldFunction &output_fields, const ExportOptions &opts, WriteJobs *writes=nullptr) const
saves the nodal values
Definition OutData.cpp:2773
void save_contact_surface(const std::string &export_surface, const OutputSpace &space, const OutputFieldFunction &output_fields, const double t, const double dt_in, const ExportOptions &opts, WriteJobs *writes=nullptr) const
saves the surface vtu file for for constact quantites, eg contact or friction forces
Definition OutData.cpp:2682
void build_grid(const polyfem::mesh::Mesh &mesh, const double spacing)
builds the grid to export the solution
Definition OutData.cpp:2840
static void extract_boundary_mesh(const mesh::Mesh &mesh, const int n_bases, const std::vector< basis::ElementBases > &bases, const std::vector< mesh::LocalBoundary > &total_local_boundary, Eigen::MatrixXd &node_positions, Eigen::MatrixXi &boundary_edges, Eigen::MatrixXi &boundary_triangles, std::vector< Eigen::Triplet< double > > &displacement_map_entries)
extracts the boundary mesh
Definition OutData.cpp:922
static void extract_boundary_mesh_sampled(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, const int sampling_order=0, const std::vector< basis::ElementBases > *geom_bases=nullptr)
extracts a collision proxy sampling every boundary face on a uniform lattice of the globally maximal ...
Definition OutData.cpp:600
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
Definition OutData.cpp:2827
void export_data(const OutputSpace &space, const OutputFieldFunction &output_fields, const bool is_time_dependent, const double tend_in, const double dt, const ExportOptions &opts, const std::string &vis_mesh_path) const
exports everytihng, txt, vtu, etc
Definition OutData.cpp:2290
void save_vtu(const std::string &path, const OutputSpace &space, const OutputFieldFunction &output_fields, const double t, const double dt, const ExportOptions &opts) const
saves the vtu file for time t
Definition OutData.cpp:2351
std::vector< std::function< void()> > WriteJobs
Definition OutData.hpp:31
void init_sampler(const polyfem::mesh::Mesh &mesh, const double vismesh_rel_area)
unitalize the ref element sampler
Definition OutData.cpp:2835
void save_surface(const std::string &export_surface, const OutputSpace &space, const OutputFieldFunction &output_fields, const double t, const double dt_in, const ExportOptions &opts, WriteJobs *writes=nullptr) const
saves the surface vtu file for for surface quantites, eg traction forces
Definition OutData.cpp:2611
void save_volume(const std::string &path, const OutputSpace &space, const OutputFieldFunction &output_fields, const double t, const double dt, const ExportOptions &opts, WriteJobs *writes=nullptr) const
saves the volume vtu file
Definition OutData.cpp:2441
Eigen::MatrixXi grid_points_to_elements
grid mesh mapping to fe elements
Definition OutData.hpp:267
utils::RefElementSampler ref_element_sampler
used to sample the solution
Definition OutData.hpp:262
timers from polyfem.
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
all stats from polyfem
void count_flipped_elements(const polyfem::mesh::Mesh &mesh, const std::vector< polyfem::basis::ElementBases > &gbases)
counts the number of flipped elements
Definition OutData.cpp:3021
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
Definition OutData.cpp:3066
void compute_mesh_size(const polyfem::mesh::Mesh &mesh_in, const std::vector< polyfem::basis::ElementBases > &bases_in, const int n_samples, const bool use_curved_mesh_size)
computes the mesh size, it samples every edges n_samples times uses curved_mesh_size (false by defaul...
Definition OutData.cpp:2938
void reset()
clears all stats
Definition OutData.cpp:3016
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 Eigen::VectorXi &disc_ordersq, const assembler::Problem &problem, const OutRuntimeData &runtime, const std::string &formulation, const bool isoparametric, const int sol_at_node_id, nlohmann::json &j) const
saves the output statistic to a json object
Definition OutData.cpp:3309
void compute_mesh_stats(const polyfem::mesh::Mesh &mesh)
compute stats (counts els type, mesh lenght, etc), step 1 of solve
Definition OutData.cpp:3227
Boundary primitive IDs for a single element.
2D mesh interface: the elements are the faces (polygons) and the boundary elements are the edges.
Definition Mesh2D.hpp:18
3D mesh interface: the elements are the cells (tetrahedra, hexahedra, prisms, pyramids or general pol...
Definition Mesh3D.hpp:22
virtual Navigation3D::Index get_index_from_element(int hi, int lf, int lv) const =0
std::array< int, 5 > get_ordered_vertices_from_pyramid(const int element_index) const
Definition Mesh3D.cpp:581
std::array< int, 8 > get_ordered_vertices_from_hex(const int element_index) const
Definition Mesh3D.cpp:503
virtual int n_cell_faces(const int c_id) const =0
virtual std::array< int, 4 > get_ordered_vertices_from_tet(const int element_index) const
Definition Mesh3D.cpp:527
std::array< int, 6 > get_ordered_vertices_from_prism(const int element_index) const
Definition Mesh3D.cpp:550
virtual Navigation3D::Index next_around_face(Navigation3D::Index idx) const =0
Abstract mesh class to capture 2d/3d conforming and non-conforming meshes.
Definition Mesh.hpp:77
int n_elements() const
utitlity to return the number of elements, cells or faces in 3d and 2d
Definition Mesh.hpp:181
virtual int n_vertices() const =0
number of vertices
bool is_polytope(const int el_id) const
checks if element is polygon compatible
Definition Mesh.cpp:374
virtual void get_edges(Eigen::MatrixXd &p0, Eigen::MatrixXd &p1) const =0
Get all the edges.
bool is_simplicial() const
checks if the mesh is simplicial
Definition Mesh.hpp:641
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
Definition Mesh.cpp:361
virtual RowVectorNd point(const int global_index) const =0
point coordinates
const Eigen::MatrixXi & orders() const
order of each element
Definition Mesh.hpp:301
virtual int get_boundary_id(const int primitive) const
Get the boundary selection of an element (face in 3d, edge in 2d)
Definition Mesh.hpp:499
bool is_simplex(const int el_id) const
checks if element is simplex
Definition Mesh.cpp:392
bool is_prism(const int el_id) const
checks if element is a prism
Definition Mesh.cpp:397
virtual bool is_volume() const =0
checks if mesh is volume
bool has_poly() const
checks if the mesh has polytopes
Definition Mesh.hpp:599
int dimension() const
utily for dimension
Definition Mesh.hpp:171
virtual int n_faces() const =0
number of faces
const std::vector< ElementType > & elements_tag() const
Returns the elements types.
Definition Mesh.hpp:444
bool is_pyramid(const int el_id) const
checks if element is a pyramid
Definition Mesh.cpp:402
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 face_vertex(const int f_id, const int lv_id) const =0
id of the face vertex
int node_tag(const int node_id) const
Point-selection id of a node (Mesh::get_node_id of its vertex): -1 for nodes that are not on a vertex...
Definition MeshNodes.hpp:77
const Eigen::MatrixXi & get_edge_connectivity() const
Definition Obstacle.hpp:52
const Eigen::MatrixXi & get_face_connectivity() const
Definition Obstacle.hpp:51
const Eigen::MatrixXi & get_tet_connectivity() const
Definition Obstacle.hpp:54
const Eigen::MatrixXd & v() const
Definition Obstacle.hpp:45
const Eigen::VectorXi & get_vertex_connectivity() const
Definition Obstacle.hpp:53
static void sample_parametric_prism_face(int index, int n_samples, Eigen::MatrixXd &uv, Eigen::MatrixXd &samples)
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_pyramid_face(int index, int n_samples, Eigen::MatrixXd &uv, Eigen::MatrixXd &samples)
static void sample_parametric_tri_face(int index, int n_samples, Eigen::MatrixXd &uv, Eigen::MatrixXd &samples)
static void normal_for_prism_face(int index, Eigen::MatrixXd &normal)
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 normal_for_pyramid_face(int index, 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 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::MatrixXi & pyramid_volume() const
const Eigen::MatrixXd & pyramid_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,...
Definition getRSS.c:37
void q_nodes_2d(const int q, Eigen::MatrixXd &val)
void pyramid_nodes_3d(const int pyramid, Eigen::MatrixXd &val)
void prism_nodes_3d(const int p, 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)
std::function< std::vector< OutputField >(const OutputSample &)> OutputFieldFunction
paraviewo::CellElement CellElement
Definition OutData.cpp:88
paraviewo::CellType CellType
Definition OutData.cpp:87
bool write_matrix(const std::string &path, const Mat &mat)
Writes a matrix to a file. Determines the file format based on the path's extension.
Definition MatrixIO.cpp:43
ElementType
Type of Element, check [Poly-Spline Finite Element Method] for a complete description.
Definition Mesh.hpp:31
size_t get_n_threads()
Definition par_for.hpp:71
spdlog::logger & logger()
Retrieves the current logger.
Definition Logger.cpp:44
nlohmann::json json
Definition Common.hpp:9
Eigen::Matrix< double, 1, Eigen::Dynamic, Eigen::RowMajor, 1, 3 > RowVectorNd
Definition Types.hpp:13
void log_and_throw_error(const std::string &msg)
Definition Logger.cpp:73
std::string file_extension() const
return the extension of the output paraview files depending on use_hdf5
Definition OutData.hpp:68
std::vector< std::string > fields
Definition OutData.hpp:35
ExportOptions(const json &args, const bool is_mesh_linear, const bool mesh_has_prisms, const bool is_problem_scalar)
initialize the flags based on the input args
Definition OutData.cpp:2322
bool export_field(const std::string &field) const
Definition OutData.cpp:2317
bool export_field(const std::string &field) const
Definition OutData.cpp:82
std::vector< std::string > fields
Eigen::VectorXi node_ids
Eigen::MatrixXd normals
Eigen::VectorXi primitive_ids
std::vector< std::string > requested_fields
Eigen::VectorXi element_ids
Eigen::MatrixXd local_points
const mesh::Mesh * mesh
Eigen::VectorXi output_orders
const std::vector< mesh::LocalBoundary > * total_local_boundary
const mesh::MeshNodes * mesh_nodes
nodes of the FE space of dirichlet_nodes, for their tags
const std::vector< basis::ElementBases > * geometry_bases
const std::vector< RowVectorNd > * dirichlet_nodes_position
const std::vector< int > * dirichlet_nodes
const std::map< int, Eigen::MatrixXd > * polys
const mesh::Obstacle * obstacle
const ipc::CollisionMesh * collision_mesh
const std::map< int, std::pair< Eigen::MatrixXd, Eigen::MatrixXi > > * polys_3d