Vulpes  0.1.0
Versatile and parallel compUtational Library for high-order discontinuous Polytopal Element Simulations
Loading...
Searching...
No Matches
mesh_exporter.hpp
Go to the documentation of this file.
1// ----------------------------------------------------------------------
2//
3// Copyright (C) 2024 - 2026 by the Vulpes authors.
4// This file is part of Vulpes.
5//
6// Vulpes is free software; you can redistribute it and/or modify
7// it under the terms of the GNU General Public License as published by
8// the Free Software Foundation, either version 3 of the License, or
9// (at your option) any later version.
10//
11// Vulpes is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14// General Public License for more details.
15//
16// You should have received a copy of the GNU General Public License
17// along with Vulpes. If not, see <http://www.gnu.org/licenses/>.
18//
19// ----------------------------------------------------------------------
20
21// Author: Francesco Rosnati <francesco.rosnati@polimi.it>
22// Author: Matteo Caldana <matteo.caldana@polimi.it>
23// Author: Nicola De March <nicola.demarch@polimi.it>
24// Author: Pedro Peixoto <ppeixoto@usp.br>
25
26#ifndef VULPES_GEOMETRY_MESH_EXPORTER_HPP_
27#define VULPES_GEOMETRY_MESH_EXPORTER_HPP_
28
29#include <algorithm>
30#include <cstddef>
31#include <cstdint>
32#include <fstream>
33#include <iostream>
34#include <map>
35#include <numeric>
36#include <stdexcept>
37#include <string>
38#include <type_traits>
39#include <unordered_map>
40#include <utility>
41#include <vector>
42
43#include <Eigen/Dense>
44
45#include <vtkAppendFilter.h>
46#include <vtkCell.h>
47#include <vtkCellArray.h>
48#include <vtkCellData.h>
49#include <vtkDoubleArray.h>
50#include <vtkFieldData.h>
51#include <vtkFloatArray.h>
52#include <vtkIdList.h>
53#include <vtkIntArray.h>
54#include <vtkLongLongArray.h>
55#include <vtkMPIController.h>
56#include <vtkNew.h>
57#include <vtkPointData.h>
58#include <vtkPoints.h>
59#include <vtkPolyData.h>
60#include <vtkPolyDataReader.h>
61#include <vtkPolygon.h>
62#include <vtkPolyhedron.h>
63#include <vtkSmartPointer.h>
64#include <vtkTetra.h>
65#include <vtkTriangle.h>
66#include <vtkType.h>
67#include <vtkUnstructuredGrid.h>
68#include <vtkUnstructuredGridWriter.h>
69#include <vtkXMLPUnstructuredGridWriter.h>
70#include <vtkXMLUnstructuredGridReader.h>
71
79
80namespace vulpes {
81namespace geometry {
82
89enum DataMode : std::uint8_t {
93 Ascii = vtkXMLWriterBase::Ascii,
97 Binary = vtkXMLWriterBase::Binary,
103 Base64 = vtkXMLWriterBase::Appended
104};
105
112enum CoordinatePrecision : std::uint8_t {
118 Float32 = VTK_FLOAT,
124 Float64 = VTK_DOUBLE
125};
126
139 vtkXMLWriterBase::CompressorType compressor_type =
140 vtkXMLWriterBase::CompressorType::ZLIB;
154};
155
166template <typename MeshDerived>
168 public:
172 using index_t = MeshDerived::index_t;
173
180 const MeshDerived& mesh, const VtuOptions& options = {})
181 : m_mesh(mesh), m_export_options(options) {};
182
196 void save(
197 const std::string& filename,
198 const std::optional<VtuOptions>& options = std::nullopt) const;
199
204 const auto& getMesh() const { return m_mesh; }
205
210 const auto& getVtkGrids() const { return m_vtk_grids; }
211
212 protected:
213 const MeshDerived& m_mesh;
215
216 std::vector<vtkSmartPointer<vtkUnstructuredGrid>> m_vtk_grids;
217 // Stores modified mesh if needed
218 mutable std::optional<MeshDerived> m_modified_mesh;
219
229 void savePvtu(
230 const std::string& filename, const VtuOptions& write_options) const;
231
240 // TODO: currently if mesh parallel all the periodic-mesh code is ignored
241 if constexpr (MeshDerived::self_dim == 2 && !MeshDerived::parallel()) {
242 if (shouldModifyPeriodicMesh(this->m_mesh)) {
244 }
245 }
246 }
247
254 const MeshDerived& getMeshRef() const {
255 if (m_modified_mesh.has_value()) {
256 return *m_modified_mesh;
257 }
258 return this->m_mesh;
259 }
260};
261
262template <typename MeshDerived>
264 const std::string& filename,
265 const std::optional<VtuOptions>& options) const {
266 // Use stored export options, or override with provided options
267 const VtuOptions& write_options = options.value_or(m_export_options);
268
269 if (filename.ends_with(".pvtu")) {
270 if constexpr (MeshDerived::parallel()) {
271 savePvtu(filename, write_options);
272 } else {
273 throw std::invalid_argument(
274 ".pvtu output is only implemented for ParallelMesh");
275 }
276 return;
277 }
278
279 vtkNew<vtkAppendFilter> merged_grids;
280 for (const auto& grid : m_vtk_grids) {
281 merged_grids->AddInputData(grid);
282 }
283 merged_grids->MergePointsOff();
284 merged_grids->Update();
285 if (filename.ends_with(".vtu")) {
286 vtkNew<vtkXMLUnstructuredGridWriter> writer;
287 writer->SetFileName(filename.c_str());
288 writer->SetInputConnection(merged_grids->GetOutputPort());
289 writer->SetCompressorType(write_options.compressor_type);
290 writer->SetDataMode(write_options.data_mode);
291 writer->Write();
292 } else if (filename.ends_with(".vtk")) {
293 vtkNew<vtkUnstructuredGridWriter> writer;
294 writer->SetFileName(filename.c_str());
295 writer->SetInputConnection(merged_grids->GetOutputPort());
296 writer->SetFileTypeToASCII();
297 writer->Write();
298 } else {
299 throw std::invalid_argument("Unhandled output format: " + filename);
300 }
301}
302
303template <typename MeshDerived>
305 const std::string& filename, const VtuOptions& write_options) const {
306 static_assert(
307 MeshDerived::parallel(),
308 "savePvtu is only implemented for ParallelMesh exporters.");
309
310 vtkNew<vtkAppendFilter> merged_grids;
311 for (const auto& grid : m_vtk_grids) {
312 merged_grids->AddInputData(grid);
313 }
314 merged_grids->MergePointsOff();
315 merged_grids->Update();
316
317 // VTK MPI controller so the parallel XML writer can coordinate ranks.
318 // Constructed and initialized once (kept static) and reused across calls
319 // to avoid repeated MPI-init warnings on every save().
320 static vtkNew<vtkMPIController> vtk_controller;
321 static const bool controller_initialized = []() {
322 vtk_controller->Initialize(nullptr, nullptr, 1);
323 return true;
324 }();
325 (void)controller_initialized;
326
327 vtkNew<vtkXMLPUnstructuredGridWriter> writer;
328 // Set roles of ranks through controller
329 // Only rank 0 writes the .pvtu summary file;
330 // each rank writes its .vtu piece.
331 writer->SetController(vtk_controller);
332 writer->SetFileName(filename.c_str());
333 writer->SetInputConnection(merged_grids->GetOutputPort());
334 writer->SetNumberOfPieces(mpi::size());
335 writer->SetStartPiece(mpi::rank());
336 writer->SetEndPiece(mpi::rank());
337 writer->SetCompressorType(write_options.compressor_type);
338 writer->SetDataMode(write_options.data_mode);
339 writer->Write();
340}
341
343
354template <typename MeshDerived>
355class MeshExporter : public MeshExporterBase<MeshDerived> {
356 public:
360 using float_t = MeshDerived::float_t;
364 using index_t = MeshDerived::index_t;
365
375 explicit MeshExporter(const MeshDerived& mesh, const VtuOptions& options = {})
376 : MeshExporterBase<MeshDerived>(mesh, options) {
377 // Initialize mesh for export (may create modified copy for
378 // 2D periodic meshes)
380
381 // MeshExporter builds a single shared-vertex grid (unlike
382 // MeshExporterSubmesh, which resolves periodicity per-cell via Cell2D),
383 // so a periodic ParallelMesh here would silently export wrong geometry
384 // at the periodic boundary.
385 if constexpr (MeshDerived::self_dim == 2 && MeshDerived::parallel()) {
386 assert(
387 !mesh2d::isPeriodic(mesh) &&
388 ".pvtu/.vtu export of a periodic ParallelMesh is not supported");
389 if (mesh2d::isPeriodic(mesh)) {
390 std::cerr << "MeshExporter: periodic ParallelMesh export is not "
391 "supported; output geometry will be wrong at "
392 "periodic boundaries."
393 << std::endl;
394 }
395 }
396
397 // Build VTK mesh based on dimension
398 if constexpr (MeshDerived::self_dim == 2) {
400 } else if constexpr (MeshDerived::self_dim == 3) {
402 } else {
403 static_assert(
404 MeshDerived::self_dim == 2 || MeshDerived::self_dim == 3,
405 "Only 2D and 3D meshes are supported.");
406 }
407
408 const auto& mesh_ref = this->getMeshRef();
409 const auto& vtxs = mesh_ref.getVertexes();
410
411 // Attach vertex tags (dimension 0)
412 for (const auto& [tag_name, tag] : mesh_ref.getMeshTags().tags[0]) {
413 if constexpr (MeshDerived::parallel()) {
414 const auto num_exported_vtx =
415 static_cast<std::size_t>(mesh_ref.nLocEntity(0));
416 if (tag.size() == num_exported_vtx || tag.size() == vtxs.size()) {
417 attachVertexData(tag_name, tag);
418 }
419 } else {
420 if (tag.size() == vtxs.size()) {
421 attachVertexData(tag_name, tag);
422 }
423 }
424 }
425 // Attach cell Global ID
426 std::vector<index_t> cell_id;
427 if constexpr (MeshDerived::parallel()) {
428 cell_id.resize(mesh_ref.nOwnedCells());
429 const auto& local_to_global =
430 mesh_ref.localToGlobal(MeshDerived::self_dim);
431 assert(local_to_global.size() >= cell_id.size());
432 std::copy_n(local_to_global.begin(), cell_id.size(), cell_id.begin());
433 } else {
434 cell_id.resize(mesh_ref.numCells());
435 std::iota(cell_id.begin(), cell_id.end(), index_t{0});
436 }
437 attachCellData("CellID", cell_id);
438 // Attach OwnerRank
439 if constexpr (MeshDerived::parallel()) {
440 std::vector<int> owner_rank(mesh_ref.nOwnedCells(), mpi::rank());
441 attachCellData("OwnerRank", owner_rank);
442 }
443 // Attach cell tags (dimension self_dim)
444 const auto& cell_tags = mesh_ref.getMeshTags().tags[MeshDerived::self_dim];
445 for (const auto& [tag_name, tag] : cell_tags) {
446 const auto num_cells = static_cast<std::size_t>(mesh_ref.numCells());
447 if constexpr (MeshDerived::parallel()) {
448 const auto num_exported_cells =
449 static_cast<std::size_t>(mesh_ref.nOwnedCells());
450
451 if (tag.size() == num_exported_cells || tag.size() == num_cells) {
452 attachCellData(tag_name, tag);
453 }
454 } else {
455 if (tag.size() == num_cells) {
456 attachCellData(tag_name, tag);
457 }
458 }
459 }
460 attachMetadata(mesh_ref);
461 };
462
474 void attachVertexData(
475 const std::string& label,
476 const Eigen::Map<const Eigen::Matrix<float_t, -1, -1>> data_view) const;
489 const std::string& label,
490 const Eigen::Matrix<float_t, -1, -1>& data) const {
492 label, Eigen::Map<const Eigen::Matrix<float_t, -1, -1>>{
493 data.data(), data.rows(), data.cols()});
494 };
495
508 const std::string& label, const std::vector<float_t>& data) const {
510 label, Eigen::Map<const Eigen::Matrix<float_t, -1, -1>>{
511 data.data(), 1, static_cast<Eigen::Index>(data.size())});
512 }
513
522 void attachVertexData(
523 const std::string& label, const std::vector<index_t>& data) const;
524
532 template <typename DataType>
533 void attachCellData(
534 const std::string& label,
535 const Eigen::Map<const Eigen::Vector<DataType, -1>> data_view) const;
536
544 template <typename DataType>
546 const std::string& label, const std::vector<DataType>& data) const {
548 label, Eigen::Map<const Eigen::Vector<DataType, -1>>{
549 data.data(), static_cast<Eigen::Index>(data.size())});
550 }
551
559 void attachMetadata(const MeshDerived& mesh) const;
560
561 protected:
569 void buildVtkMesh2D();
570
578 void buildVtkMesh3D();
579};
580
581// Handles multi-component floating-point vertex data
582// (e.g., coordinates, vectors).
583template <typename MeshDerived>
585 const std::string& label,
586 const Eigen::Map<const Eigen::Matrix<float_t, -1, -1>> data_view) const {
587 assert(this->m_vtk_grids.size() == 1);
588 auto vtk_unstructured_grid = this->m_vtk_grids[0];
589 Eigen::Index num_values_to_write = data_view.cols();
590 if constexpr (MeshDerived::parallel()) {
591 const auto num_exported_vtx =
592 static_cast<Eigen::Index>(this->getMeshRef().nLocEntity(0));
593 assert(
594 data_view.cols() == num_exported_vtx ||
595 data_view.cols() ==
596 static_cast<Eigen::Index>(this->getMeshRef().getVertexes().size()));
597 num_values_to_write = num_exported_vtx;
598 } else {
599 assert(
600 data_view.cols() ==
601 static_cast<Eigen::Index>(this->getMeshRef().getVertexes().size()));
602 }
603 for (Eigen::Index c = 0; c < data_view.rows(); ++c) {
604 vtkNew<vtkFloatArray> scalar;
605 const std::string curr_label =
606 (data_view.rows() == 1) ? label : (label + "_" + std::to_string(c));
607 scalar->SetName(curr_label.c_str());
608
609 for (Eigen::Index i = 0; i < num_values_to_write; ++i) {
610 scalar->InsertNextValue(data_view(c, i));
611 }
612 vtk_unstructured_grid->GetPointData()->AddArray(scalar);
613 }
614}
615
616// Handles integer vertex data (e.g., vertex indices, tags).
617template <typename MeshDerived>
619 const std::string& label, const std::vector<index_t>& data) const {
620 assert(this->m_vtk_grids.size() == 1);
621 auto vtk_unstructured_grid = this->m_vtk_grids[0];
622 std::size_t num_values_to_write = data.size();
623 if constexpr (MeshDerived::parallel()) {
624 const auto num_exported_vtx =
625 static_cast<std::size_t>(this->getMeshRef().nLocEntity(0));
626 assert(
627 data.size() == num_exported_vtx ||
628 data.size() == this->getMeshRef().getVertexes().size());
629 num_values_to_write = num_exported_vtx;
630 } else {
631 assert(data.size() == this->getMeshRef().getVertexes().size());
632 }
633
634 auto add = [&](auto& scalar) {
635 scalar->SetName(label.c_str());
636 for (std::size_t i = 0; i < num_values_to_write; ++i) {
637 scalar->InsertNextValue(data[i]);
638 }
639 vtk_unstructured_grid->GetPointData()->AddArray(scalar);
640 };
641
642 if constexpr (std::is_integral_v<index_t> && sizeof(index_t) <= 4) {
643 vtkNew<vtkIntArray> scalar;
644 add(scalar);
645 } else if constexpr (std::is_integral_v<index_t> && sizeof(index_t) == 8) {
646 vtkNew<vtkLongLongArray> scalar;
647 add(scalar);
648 } else {
649 static_assert(
650 std::is_integral_v<index_t>,
651 "MeshExporter vertex integer data requires integral index_t");
652 }
653}
654
655template <typename MeshDerived>
656template <typename DataType>
658 const std::string& label,
659 const Eigen::Map<const Eigen::Vector<DataType, -1>> data_view) const {
660 assert(this->m_vtk_grids.size() == 1);
661 auto vtk_unstructured_grid = this->m_vtk_grids[0];
662 Eigen::Index num_values_to_write = data_view.size();
663 if constexpr (MeshDerived::parallel()) {
664 const auto num_exported_cells =
665 static_cast<Eigen::Index>(this->getMeshRef().nOwnedCells());
666 assert(
667 data_view.size() == num_exported_cells ||
668 data_view.size() ==
669 static_cast<Eigen::Index>(this->getMeshRef().numCells()));
670 num_values_to_write = num_exported_cells;
671 } else {
672 assert(
673 data_view.size() ==
674 static_cast<Eigen::Index>(this->getMeshRef().numCells()));
675 }
676 auto add = [&](auto& arr) {
677 arr->SetName(label.c_str());
678 for (Eigen::Index i = 0; i < num_values_to_write; ++i) {
679 arr->InsertNextValue(data_view[i]);
680 }
681 vtk_unstructured_grid->GetCellData()->AddArray(arr);
682 };
683 if constexpr (std::is_same_v<DataType, double>) {
684 vtkNew<vtkDoubleArray> arr;
685 add(arr);
686 } else if constexpr (std::is_integral_v<DataType> && sizeof(DataType) <= 4) {
687 vtkNew<vtkIntArray> arr;
688 add(arr);
689 } else if constexpr (std::is_integral_v<DataType> && sizeof(DataType) == 8) {
690 vtkNew<vtkLongLongArray> arr;
691 add(arr);
692 } else {
693 vtkNew<vtkFloatArray> arr;
694 add(arr);
695 }
696 // This is probably a leftover that needs to be removed
697 // once I am sure i will remove
698 // vtk_unstructured_grid->GetCellData()->AddArray(scalar);
699}
700
701template <typename MeshDerived>
702void MeshExporter<MeshDerived>::attachMetadata(const MeshDerived& mesh) const {
703 assert(this->m_vtk_grids.size() == 1);
704 auto vtk_unstructured_grid = this->m_vtk_grids[0];
705 const auto& metadata = mesh.getMetadata();
706
707 // Attach double metadata
708 for (const auto& [name, values] : metadata.doubles) {
709 vtkNew<vtkDoubleArray> array;
710 array->SetName(name.c_str());
711 array->SetNumberOfComponents(1);
712 array->SetNumberOfTuples(values.size());
713 for (std::size_t i = 0; i < values.size(); ++i) {
714 array->SetValue(i, values[i]);
715 }
716 vtk_unstructured_grid->GetFieldData()->AddArray(array);
717 }
718
719 // Attach integer metadata
720 for (const auto& [name, values] : metadata.ints) {
721 vtkNew<vtkLongLongArray> array;
722 array->SetName(name.c_str());
723 array->SetNumberOfComponents(1);
724 array->SetNumberOfTuples(values.size());
725 for (std::size_t i = 0; i < values.size(); ++i) {
726 array->SetValue(i, static_cast<int64_t>(values[i]));
727 }
728 vtk_unstructured_grid->GetFieldData()->AddArray(array);
729 }
730}
731
732template <typename MeshDerived>
734 this->m_vtk_grids.resize(1);
735 this->m_vtk_grids[0] = vtkSmartPointer<vtkUnstructuredGrid>::New();
736 auto vtk_unstructured_grid = this->m_vtk_grids[0];
737 // set vertices
738 vtkNew<vtkPoints> points;
739 points->SetDataType(this->m_export_options.coordinate_precision);
740 const auto& mesh_ref = this->getMeshRef();
741 const auto& vtxs = mesh_ref.getVertexes();
742 if constexpr (MeshDerived::parallel()) {
743 // ParallelMesh stores owned/local vertices first, followed by ghost-only
744 // vertices. The 2D parallel export writes only the owned/local prefix.
745 for (index_t vtx_id = 0; vtx_id < mesh_ref.nLocEntity(0); ++vtx_id) {
746 const auto& point = vtxs[vtx_id];
747 points->InsertNextPoint(point[0], point[1], 0.0);
748 }
749 } else {
750 for (const auto& point : vtxs) {
751 points->InsertNextPoint(point[0], point[1], 0.0);
752 }
753 }
754 vtk_unstructured_grid->SetPoints(points);
755 // set cells
756 vtkNew<vtkCellArray> cells;
757 const index_t num_cells = [&mesh_ref]() -> index_t {
758 // ParallelMesh stores owned/local cells first, followed by ghost-only
759 // cells. The 2D parallel export writes only the owned/local prefix.
760 if constexpr (MeshDerived::parallel()) {
761 return mesh_ref.nOwnedCells();
762 } else {
763 return mesh_ref.numCells();
764 }
765 }();
766 for (index_t cell_id = 0; cell_id < num_cells; ++cell_id) {
767 const auto cell = mesh_ref.getCellToVtxMap().getRow(cell_id);
768 vtkNew<vtkPolygon> vtk_cell;
769 vtk_cell->GetPointIds()->SetNumberOfIds(cell.size());
770 for (index_t i = 0; i < cell.size(); ++i) {
771 vtk_cell->GetPointIds()->SetId(i, cell[i]);
772 }
773 cells->InsertNextCell(vtk_cell);
774 }
775 vtk_unstructured_grid->SetCells(VTK_POLYGON, cells);
776}
777
778template <typename MeshDerived>
780 this->m_vtk_grids.resize(1);
781 this->m_vtk_grids[0] = vtkSmartPointer<vtkUnstructuredGrid>::New();
782 auto vtk_unstructured_grid = this->m_vtk_grids[0];
783 const auto& mesh_ref = this->getMeshRef();
784 const auto& vtxs = mesh_ref.getVertexes();
785 // set points
786 vtkNew<vtkPoints> points;
787 points->SetDataType(this->m_export_options.coordinate_precision);
788 if constexpr (MeshDerived::parallel()) {
789 // ParallelMesh stores owned/local vertices first, followed by ghost-only
790 // vertices. The 3D parallel export writes only the owned/local prefix.
791 for (index_t vtx_id = 0; vtx_id < mesh_ref.nLocEntity(0); ++vtx_id) {
792 const auto& point = vtxs[vtx_id];
793 points->InsertNextPoint(point.data());
794 }
795 } else {
796 for (const auto& point : vtxs) {
797 points->InsertNextPoint(point.data());
798 }
799 }
800 vtk_unstructured_grid->SetPoints(points);
801 // set cells
802 const index_t num_cells = [&mesh_ref]() -> index_t {
803 // ParallelMesh stores owned/local cells first, followed by ghost-only
804 // cells. The 3D parallel export writes only the owned/local prefix.
805 if constexpr (MeshDerived::parallel()) {
806 return mesh_ref.nOwnedCells();
807 } else {
808 return mesh_ref.numCells();
809 }
810 }();
811 for (index_t cell_id = 0; cell_id < num_cells; ++cell_id) {
812 const auto cell = mesh_ref.getCellToVtxMap().getRow(cell_id);
813 std::vector<vtkIdType> vtk_vtx_ids;
814 for (index_t i = 0; i < cell.size(); ++i) {
815 vtk_vtx_ids.push_back(cell[i]);
816 }
817 vtkNew<vtkIdList> faces;
818 const auto& facet_map = mesh_ref.getCellToFacetMap();
819 const index_t n_faces = facet_map[cell_id].size();
820 for (index_t i = 0; i < n_faces; ++i) {
821 const index_t face_id = facet_map[cell_id][i];
822 const auto face_vtxs = mesh_ref.getFacetToVtxMap()[face_id];
823 const index_t face_size = face_vtxs.size();
824 faces->InsertNextId(face_size);
825
826 const auto fw_order =
827 (mesh_ref.getFacetToCellMap()[face_id][0] == cell_id);
828 if (fw_order) {
829 for (auto vid : face_vtxs) {
830 faces->InsertNextId(vid);
831 }
832 } else {
833 for (auto it = face_vtxs.end(); it != face_vtxs.begin();) {
834 faces->InsertNextId(*(--it));
835 }
836 }
837 }
838 vtk_unstructured_grid->InsertNextCell(
839 VTK_POLYHEDRON, cell.size(), vtk_vtx_ids.data(), n_faces,
840 faces->GetPointer(0));
841 }
842}
843
845
856template <typename MeshDerived>
857class MeshExporterSubmesh : public MeshExporterBase<MeshDerived> {
858 public:
862 using float_t = MeshDerived::float_t;
866 using index_t = MeshDerived::index_t;
867
881 const MeshDerived& mesh,
882 std::size_t min_n_submesh_elem,
883 const VtuOptions& options = {})
884 : MeshExporterBase<MeshDerived>(mesh, options) {
885 // Initialize mesh for export (may create modified copy for
886 // 2D periodic meshes)
888
889 if constexpr (MeshDerived::self_dim == 2) {
890 buildVtkMesh2D(min_n_submesh_elem);
891 } else if constexpr (MeshDerived::self_dim == 3) {
892 buildVtkMesh3D(min_n_submesh_elem);
893 } else {
894 static_assert(
895 MeshDerived::self_dim == 2 || MeshDerived::self_dim == 3,
896 "Only 2D and 3D meshes are supported.");
897 }
898
899 // Attach global CellID
900 std::vector<index_t> cell_id(this->m_vtk_grids.size());
901 if constexpr (MeshDerived::parallel()) {
902 const auto& local_to_global =
903 this->getMeshRef().localToGlobal(MeshDerived::self_dim);
904 assert(local_to_global.size() >= this->m_vtk_grids.size());
905 std::copy_n(local_to_global.begin(), cell_id.size(), cell_id.begin());
906 } else {
907 std::iota(cell_id.begin(), cell_id.end(), index_t{0});
908 }
909 attachCellData("CellID", cell_id);
910 // Attach OwnerRank
911 if constexpr (MeshDerived::parallel()) {
912 std::vector<int> owner_rank(this->m_vtk_grids.size(), mpi::rank());
913 attachCellData("OwnerRank", owner_rank);
914 }
915 // Attach cell tags
916 for (const auto& [tag_name, tag] :
917 this->getMeshRef().getMeshTags().tags[MeshDerived::self_dim]) {
918 const auto& mesh_ref = this->getMeshRef();
919 const auto num_cells = static_cast<std::size_t>(mesh_ref.numCells());
920 if constexpr (MeshDerived::parallel()) {
921 const auto num_exported_cells =
922 static_cast<std::size_t>(mesh_ref.nOwnedCells());
923 if (tag.size() == num_exported_cells || tag.size() == num_cells) {
924 attachCellData(tag_name, tag);
925 }
926 } else {
927 if (tag.size() == num_cells) {
928 attachCellData(tag_name, tag);
929 }
930 }
931 }
932 // TODO: attachMetadata() is completely missing in MeshExporterSubmesh
933 };
934
944 void attachVertexData(
945 const std::string& label,
946 const datastructure::CrsMap<float_t, index_t>& data) const;
947
959 template <typename DataType>
960 void attachCellData(
961 const std::string& label,
962 const Eigen::Map<const Eigen::Vector<DataType, -1>> data_view) const;
963
971 template <typename DataType>
973 const std::string& label, const std::vector<DataType>& data) const {
975 label, Eigen::Map<const Eigen::Vector<DataType, -1>>{
976 data.data(), static_cast<Eigen::Index>(data.size())});
977 }
978
979 protected:
989 void buildVtkMesh2D(std::size_t min_n_submesh_elem);
990
1000 void buildVtkMesh3D(std::size_t min_n_submesh_elem);
1001};
1002
1003template <typename MeshDerived>
1005 const std::string& label,
1006 const datastructure::CrsMap<float_t, index_t>& data) const {
1007 auto& grids = this->m_vtk_grids;
1008 if constexpr (MeshDerived::parallel()) {
1009 assert(
1010 data.size() == static_cast<index_t>(grids.size()) ||
1011 data.size() == this->getMeshRef().numCells());
1012 } else {
1013 assert(data.size() == static_cast<index_t>(grids.size()));
1014 }
1015 for (std::size_t grid_id = 0; grid_id < grids.size(); ++grid_id) {
1016 auto grid = grids[grid_id];
1017 const auto cell_data = data[grid_id];
1018 assert(cell_data.size() % grid->GetNumberOfPoints() == 0);
1019 const auto block_size = cell_data.size() / grid->GetNumberOfPoints();
1020
1021 for (Eigen::Index b = 0; b < block_size; ++b) {
1022 vtkNew<vtkFloatArray> scalar;
1023 const std::string curr_label =
1024 (block_size == 1) ? label : (label + "_" + std::to_string(b));
1025 scalar->SetName(curr_label.c_str());
1026 for (index_t i = b; i < cell_data.size(); i += block_size) {
1027 scalar->InsertNextValue(cell_data[i]);
1028 }
1029 grid->GetPointData()->AddArray(scalar);
1030 }
1031 }
1032}
1033
1034template <typename MeshDerived>
1035template <typename DataType>
1037 const std::string& label,
1038 const Eigen::Map<const Eigen::Vector<DataType, -1>> data_view) const {
1039 auto& grids = this->m_vtk_grids;
1040 if constexpr (MeshDerived::parallel()) {
1041 assert(
1042 data_view.size() == static_cast<Eigen::Index>(grids.size()) ||
1043 data_view.size() ==
1044 static_cast<Eigen::Index>(this->getMeshRef().numCells()));
1045 } else {
1046 assert(data_view.size() == static_cast<Eigen::Index>(grids.size()));
1047 }
1048 for (std::size_t grid_id = 0; grid_id < grids.size(); ++grid_id) {
1049 auto grid = grids[grid_id];
1050 auto add = [&](auto& arr) {
1051 arr->SetName(label.c_str());
1052 for (vtkIdType i = 0; i < grid->GetNumberOfCells(); ++i) {
1053 arr->InsertNextValue(data_view[grid_id]);
1054 }
1055 grid->GetCellData()->AddArray(arr);
1056 };
1057 if constexpr (std::is_same_v<DataType, double>) {
1058 vtkNew<vtkDoubleArray> arr;
1059 add(arr);
1060 } else if constexpr (
1061 std::is_integral_v<DataType> && sizeof(DataType) <= 4) {
1062 vtkNew<vtkIntArray> arr;
1063 add(arr);
1064 } else if constexpr (
1065 std::is_integral_v<DataType> && sizeof(DataType) == 8) {
1066 vtkNew<vtkLongLongArray> arr;
1067 add(arr);
1068 } else {
1069 vtkNew<vtkFloatArray> arr;
1070 add(arr);
1071 }
1072 }
1073}
1074
1075template <typename MeshDerived>
1077 std::size_t min_n_submesh_elem) {
1078 const auto& mesh_ref = this->getMeshRef();
1079 const index_t num_cells = [&mesh_ref]() -> index_t {
1080 // ParallelMesh stores owned/local cells first, followed by ghost-only
1081 // cells. The submesh export writes only the owned/local prefix.
1082 if constexpr (MeshDerived::parallel()) {
1083 return mesh_ref.nOwnedCells();
1084 } else {
1085 return mesh_ref.numCells();
1086 }
1087 }();
1088 for (index_t cell_id = 0; cell_id < num_cells; ++cell_id) {
1089 this->m_vtk_grids.push_back(vtkSmartPointer<vtkUnstructuredGrid>::New());
1090 auto vtk_unstructured_grid = this->m_vtk_grids.back();
1091
1092 Cell2D<double> cell(mesh_ref, cell_id, CellInitFaces | CellInitMeasure);
1093 const auto max_area =
1094 cell.measure() / static_cast<double>(min_n_submesh_elem);
1096 options.maxarea = max_area;
1097 options.fixedarea = 1;
1098 Triangulation triangulation(cell, options);
1099
1100 const auto pts = triangulation.getPointList();
1101 const auto tria = triangulation.getTriangleList();
1102
1103 // set vertices
1104 vtkNew<vtkPoints> points;
1105 if (this->m_export_options.coordinate_precision ==
1107 points->SetDataType(VTK_DOUBLE);
1108 }
1109 for (Eigen::Index i = 0; i < pts.cols(); ++i) {
1110 points->InsertNextPoint(pts(0, i), pts(1, i), 0.0);
1111 }
1112 vtk_unstructured_grid->SetPoints(points);
1113
1114 // set cells
1115 vtkNew<vtkCellArray> cells;
1116 for (index_t tri_id = 0; tri_id < tria.cols(); ++tri_id) {
1117 vtkNew<vtkTriangle> vtk_cell;
1118 for (int32_t d = 0; d < 3; ++d) {
1119 vtk_cell->GetPointIds()->SetId(d, tria(d, tri_id));
1120 }
1121 cells->InsertNextCell(vtk_cell);
1122 }
1123 vtk_unstructured_grid->SetCells(VTK_TRIANGLE, cells);
1124 }
1125}
1126
1127template <typename MeshDerived>
1129 std::size_t min_n_submesh_elem) {
1130 const auto& mesh_ref = this->getMeshRef();
1131 const index_t num_cells = [&mesh_ref]() -> index_t {
1132 // ParallelMesh stores owned/local cells first, followed by ghost-only
1133 // cells. The submesh export writes only the owned/local prefix.
1134 if constexpr (MeshDerived::parallel()) {
1135 return mesh_ref.nOwnedCells();
1136 } else {
1137 return mesh_ref.numCells();
1138 }
1139 }();
1140 for (index_t cell_id = 0; cell_id < num_cells; ++cell_id) {
1141 this->m_vtk_grids.push_back(vtkSmartPointer<vtkUnstructuredGrid>::New());
1142 auto vtk_unstructured_grid = this->m_vtk_grids.back();
1143 const auto cell_options = CellInitFaces | CellInitMeasure;
1144 Cell3D<double, index_t> cell(mesh_ref, cell_id, cell_options);
1145 const auto max_volume =
1146 cell.measure() / static_cast<double>(min_n_submesh_elem);
1147 assert(max_volume > 0);
1149 options.maxvolume = max_volume;
1150 options.fixedvolume = 1;
1151 options.maxvolume_length = std::pow(max_volume, 1. / 3.) / 3.;
1152 Tetrahedralization tetrahedralization(cell, false, options);
1153
1154 const auto pts = tetrahedralization.getPointList();
1155 const auto tets = tetrahedralization.getTetrahedronList();
1156
1157 // set points
1158 vtkNew<vtkPoints> points;
1159 if (this->m_export_options.coordinate_precision ==
1161 points->SetDataType(VTK_DOUBLE);
1162 }
1163 for (Eigen::Index i = 0; i < pts.cols(); ++i) {
1164 points->InsertNextPoint(pts(0, i), pts(1, i), pts(2, i));
1165 }
1166 vtk_unstructured_grid->SetPoints(points);
1167
1168 // set cells
1169 for (index_t tet_id = 0; tet_id < tets.cols(); ++tet_id) {
1170 vtkNew<vtkTetra> tetra;
1171 for (int32_t d = 0; d < 4; ++d) {
1172 tetra->GetPointIds()->SetId(d, tets(d, tet_id));
1173 }
1174 vtk_unstructured_grid->InsertNextCell(
1175 tetra->GetCellType(), tetra->GetPointIds());
1176 }
1177 }
1178}
1179
1180template <typename MeshType>
1181void exportMesh(const MeshType& mesh, const std::string& filename) {
1182 MeshExporter<MeshType> exporter(mesh);
1183 exporter.save(filename);
1184}
1185
1187// PERIODIC MESH RELATED TOOLS
1189
1201template <typename MeshDerived>
1202bool shouldModifyPeriodicMesh(const MeshDerived& mesh) {
1203 // Only modify 2D periodic meshes
1204 if (MeshDerived::self_dim != 2) {
1205 return false;
1206 }
1207
1208 const auto& md = mesh.getMetadata();
1209
1210 // Check if mesh has periodic metadata indicating it's closed
1211 if (!md.ints.contains("MeshPeriodicTopologyClosed")) {
1212 return false; // Not a periodic mesh
1213 }
1214
1215 const auto closed_status = md.ints.at("MeshPeriodicTopologyClosed").front();
1216 // true if closed, false if already open
1217 return closed_status == 1;
1218}
1219
1232template <typename ScalarType, typename IndexType>
1234 const Mesh2D<ScalarType, IndexType>& mesh) {
1235 // Ensure mesh is closed before reopening
1236 const auto& md = mesh.getMetadata();
1237 assert(md.ints.contains("MeshPeriodicTopologyClosed"));
1238 assert(md.ints.at("MeshPeriodicTopologyClosed").front() == 1);
1239 (void)md; // Avoid unused variable warning when asserts are disabled
1240
1241 Mesh2D<ScalarType, IndexType> reopened_mesh = mesh; // Copy the mesh
1242
1243 // Call openPeriodicTopology to restore ghost cells
1244 reopened_mesh = vulpes::geometry::mesh2d::openPeriodicTopology(reopened_mesh);
1245 return reopened_mesh;
1246}
1247
1248} // namespace geometry
1249} // namespace vulpes
1250
1251#endif // VULPES_GEOMETRY_MESH_EXPORTER_HPP_
Definition crs_map.hpp:72
IndexType size() const
Get the number of rows in the CRS map.
Definition crs_map.hpp:331
Definition cell.hpp:98
auto measure() const
Definition cell.hpp:128
Definition cell.hpp:151
auto measure() const
Definition cell.hpp:213
A class for a 2D mesh, inheriting from MeshBase.
Definition mesh_2d.hpp:94
Base class for exporting a mesh to VTK file formats.
Definition mesh_exporter.hpp:167
void initializeMeshForExport() const
Initializes the mesh for export, modifying if necessary.
Definition mesh_exporter.hpp:239
const MeshDerived & getMeshRef() const
Gets a reference to the mesh for export (original/modified).
Definition mesh_exporter.hpp:254
std::optional< MeshDerived > m_modified_mesh
Definition mesh_exporter.hpp:218
void save(const std::string &filename, const std::optional< VtuOptions > &options=std::nullopt) const
Saves the mesh data to a file.
Definition mesh_exporter.hpp:263
const MeshDerived & m_mesh
Definition mesh_exporter.hpp:213
VtuOptions m_export_options
Definition mesh_exporter.hpp:214
const auto & getVtkGrids() const
Gets a constant reference to the generated VTK grids.
Definition mesh_exporter.hpp:210
const auto & getMesh() const
Gets a constant reference to the mesh.
Definition mesh_exporter.hpp:204
std::vector< vtkSmartPointer< vtkUnstructuredGrid > > m_vtk_grids
Definition mesh_exporter.hpp:216
void savePvtu(const std::string &filename, const VtuOptions &write_options) const
Saves the mesh data to a parallel VTU file.
Definition mesh_exporter.hpp:304
MeshExporterBase(const MeshDerived &mesh, const VtuOptions &options={})
Constructs a MeshExporterBase for a given mesh.
Definition mesh_exporter.hpp:179
MeshDerived::index_t index_t
The index type used by the mesh.
Definition mesh_exporter.hpp:172
void attachCellData(const std::string &label, const std::vector< DataType > &data) const
Attaches cell data to the sub-meshes.
Definition mesh_exporter.hpp:972
MeshDerived::index_t index_t
The index type used by the mesh.
Definition mesh_exporter.hpp:866
void attachVertexData(const std::string &label, const datastructure::CrsMap< float_t, index_t > &data) const
Attaches vertex data to the sub-meshes.
Definition mesh_exporter.hpp:1004
void buildVtkMesh3D(std::size_t min_n_submesh_elem)
Builds 3D sub-meshes from each cell.
Definition mesh_exporter.hpp:1128
MeshDerived::float_t float_t
The float type used by the mesh.
Definition mesh_exporter.hpp:862
void attachCellData(const std::string &label, const Eigen::Map< const Eigen::Vector< DataType, -1 > > data_view) const
Attaches cell data to the sub-meshes.
Definition mesh_exporter.hpp:1036
MeshExporterSubmesh(const MeshDerived &mesh, std::size_t min_n_submesh_elem, const VtuOptions &options={})
Constructs a MeshExporterSubmesh for a given mesh.
Definition mesh_exporter.hpp:880
void buildVtkMesh2D(std::size_t min_n_submesh_elem)
Builds 2D sub-meshes from each cell.
Definition mesh_exporter.hpp:1076
Exports a single mesh as a single VTK grid.
Definition mesh_exporter.hpp:355
void attachVertexData(const std::string &label, const Eigen::Map< const Eigen::Matrix< float_t, -1, -1 > > data_view) const
Attaches a list of vertex data to the VTK grid.
Definition mesh_exporter.hpp:584
void attachMetadata(const MeshDerived &mesh) const
Attaches metadata (field data) to the VTK grid.
Definition mesh_exporter.hpp:702
void attachVertexData(const std::string &label, const Eigen::Matrix< float_t, -1, -1 > &data) const
Attaches a list of vertex data to the VTK grid.
Definition mesh_exporter.hpp:488
void buildVtkMesh2D()
Builds a 2D VTK mesh from the internal mesh data.
Definition mesh_exporter.hpp:733
void attachCellData(const std::string &label, const std::vector< DataType > &data) const
Attaches a vector of cell data to the VTK grid.
Definition mesh_exporter.hpp:545
void attachCellData(const std::string &label, const Eigen::Map< const Eigen::Vector< DataType, -1 > > data_view) const
Attaches a vector of cell data to the VTK grid.
Definition mesh_exporter.hpp:657
void buildVtkMesh3D()
Builds a 3D VTK mesh from the internal mesh data.
Definition mesh_exporter.hpp:779
MeshDerived::index_t index_t
The index type used by the mesh.
Definition mesh_exporter.hpp:364
MeshDerived::float_t float_t
The float type used by the mesh.
Definition mesh_exporter.hpp:360
MeshExporter(const MeshDerived &mesh, const VtuOptions &options={})
Constructs a MeshExporter for a given mesh.
Definition mesh_exporter.hpp:375
void attachVertexData(const std::string &label, const std::vector< float_t > &data) const
Attaches an instance of vertex data to the VTK grid.
Definition mesh_exporter.hpp:507
Performs tetrahedralization of a 3D cell using the TetGen library.
Definition simplexify.hpp:214
const PointsViewType & getPointList() const
Gets the list of points in the tetrahedralization.
Definition simplexify.hpp:280
const SimplexesViewType & getTetrahedronList() const
Gets the list of tetrahedra in the tetrahedralization.
Definition simplexify.hpp:289
static const tetgen::tetgenbehavior s_tetgen_default_options
Definition simplexify.hpp:235
Performs triangulation of a 2D cell using the Triangle library.
Definition simplexify.hpp:49
const SimplexesViewType & getTriangleList() const
Gets the list of triangles in the triangulation.
Definition simplexify.hpp:125
const PointsViewType & getPointList() const
Gets the list of points in the triangulation.
Definition simplexify.hpp:116
static const triangle::behavior s_triangle_default_options
Definition simplexify.hpp:70
Mesh2D< FloatType, IndexType > openPeriodicTopology(const Mesh2D< FloatType, IndexType > &mesh)
Definition mesh_2d.cpp:1775
bool isPeriodic(const Mesh2D< FloatType, IndexType > &mesh)
Definition mesh_2d.cpp:1598
Definition abs_agg_model.cpp:40
Mesh2D< ScalarType, IndexType > reopenPeriodicMeshForExport(const Mesh2D< ScalarType, IndexType > &mesh)
Reopens a closed 2D periodic mesh for export.
Definition mesh_exporter.hpp:1233
CoordinatePrecision
Specifies the precision for point coordinates in VTU files.
Definition mesh_exporter.hpp:112
@ Float64
64-bit floating-point precision (double).
Definition mesh_exporter.hpp:124
@ Float32
32-bit floating-point precision (float).
Definition mesh_exporter.hpp:118
void exportMesh(const MeshType &mesh, const std::string &filename)
Definition mesh_exporter.hpp:1181
DataMode
Specifies the data mode for writing XML files.
Definition mesh_exporter.hpp:89
@ Ascii
Data is written as plain text (ASCII).
Definition mesh_exporter.hpp:93
@ Binary
Data is written as raw binary.
Definition mesh_exporter.hpp:97
@ Base64
Data is appended in a Base64-encoded format.
Definition mesh_exporter.hpp:103
bool shouldModifyPeriodicMesh(const MeshDerived &mesh)
Determines if a periodic mesh should be modified for export.
Definition mesh_exporter.hpp:1202
@ CellInitFaces
Definition cell.hpp:84
@ CellInitMeasure
Definition cell.hpp:87
static int rank()
Return the MPI rank in MPI_COMM_WORLD.
Definition mpi_wrappers.hpp:116
static int size()
Return the size of MPI_COMM_WORLD.
Definition mpi_wrappers.hpp:124
Definition cell_manager.hpp:38
Configuration options for VTU file export.
Definition mesh_exporter.hpp:133
DataMode data_mode
The data encoding mode.
Definition mesh_exporter.hpp:146
vtkXMLWriterBase::CompressorType compressor_type
The compression type to use for the output file.
Definition mesh_exporter.hpp:139
CoordinatePrecision coordinate_precision
The precision for point coordinates.
Definition mesh_exporter.hpp:153