FEAT 3
Finite Element Analysis Toolbox
Loading...
Searching...
No Matches
export_vtk.hpp
1// FEAT3: Finite Element Analysis Toolbox, Version 3
2// Copyright (C) 2010 by Stefan Turek & the FEAT group
3// FEAT3 is released under the GNU General Public License version 3,
4// see the file 'copyright.txt' in the top level directory for details.
5
6#pragma once
7
8// includes, FEAT
10#include <kernel/geometry/conformal_mesh.hpp>
11#include <kernel/geometry/index_set.hpp>
12#include <kernel/geometry/mesh_part.hpp>
13#include <kernel/geometry/structured_mesh.hpp>
14#include <kernel/shape.hpp>
16#include <kernel/util/dist_file_io.hpp>
17#include <kernel/util/dist.hpp>
19#include <kernel/util/memory_arbiter.hpp>
20#include <kernel/util/pack.hpp>
21#include <kernel/util/string.hpp>
22#include <kernel/util/tiny_algebra.hpp>
23
24// includes, STL
25#include <deque>
26#include <fstream>
27#include <functional>
28#include <string_view>
29#include <vector>
30
31#ifdef FEAT_HAVE_CGAL
32#include <kernel/geometry/cgal.hpp>
33#endif
34
35
36namespace FEAT::Geometry
37{
39 namespace Intern
40 {
41 template<typename Shape_>
42 struct VTKShape;
43
44 template<>
45 struct VTKShape<Shape::Simplex<1>>
46 {
47 static constexpr std::uint32_t type = 3; // VTK_LINE
48 static inline int map(int i)
49 {
50 return i;
51 }
52 };
53
54 template<>
55 struct VTKShape<Shape::Simplex<2>>
56 {
57 static constexpr std::uint32_t type = 5; // VTK_TRIANGLE
58 static inline int map(int i)
59 {
60 return i;
61 }
62 };
63
64 template<>
65 struct VTKShape<Shape::Simplex<3>>
66 {
67 static constexpr std::uint32_t type = 10; // VTK_TETRA
68 static inline int map(int i)
69 {
70 return i;
71 }
72 };
73
74 template<>
75 struct VTKShape<Shape::Hypercube<1>>
76 {
77 static constexpr std::uint32_t type = 3; // VTK_LINE
78 static inline int map(int i)
79 {
80 return i;
81 }
82 };
83
84 template<>
85 struct VTKShape<Shape::Hypercube<2>>
86 {
87 static constexpr std::uint32_t type = 9; // VTK_QUAD
88 static inline int map(int i)
89 {
90 // bit-stunt: {0, 1, 2, 3} -> {0, 1, 3, 2}
91 return (i ^ ((i >> 1) & 1));
92 }
93 };
94
95 template<>
96 struct VTKShape<Shape::Hypercube<3>>
97 {
98 static constexpr std::uint32_t type = 12; // VTK_HEXAHEDRON
99 static inline int map(int i)
100 {
101 // bit-stunt: {0, 1, ..., 7} -> {0, 1, 3, 2, 4, 5, 7, 6}
102 return (i ^ ((i >> 1) & 1));
103 }
104 };
105
106 template<typename T_>
107 struct VTKType;
108
109 template<>
110 struct VTKType<std::uint8_t>
111 {
112 static constexpr std::string_view type = "UInt8";
113 };
114
115 template<>
116 struct VTKType<std::uint16_t>
117 {
118 static constexpr std::string_view type = "UInt16";
119 };
120
121 template<>
122 struct VTKType<std::uint32_t>
123 {
124 static constexpr std::string_view type = "UInt32";
125 };
126
127 template<>
128 struct VTKType<std::uint64_t>
129 {
130 static constexpr std::string_view type = "UInt64";
131 };
132
133 template<>
134 struct VTKType<std::int8_t>
135 {
136 static constexpr std::string_view type = "Int8";
137 };
138
139 template<>
140 struct VTKType<std::int16_t>
141 {
142 static constexpr std::string_view type = "Int16";
143 };
144
145 template<>
146 struct VTKType<std::int32_t>
147 {
148 static constexpr std::string_view type = "Int32";
149 };
150
151 template<>
152 struct VTKType<std::int64_t>
153 {
154 static constexpr std::string_view type = "Int64";
155 };
156
157 template<>
158 struct VTKType<float>
159 {
160 static constexpr std::string_view type = "Float32";
161 };
162
163 template<>
164 struct VTKType<double>
165 {
166 static constexpr std::string_view type = "Float64";
167 };
168 } // namespace Intern
170
194 template<typename Mesh_, int cell_dim_ = Mesh_::ShapeType::dimension>
196 {
197 public:
199 using MeshType = Mesh_;
201 using ShapeType = typename MeshType::ShapeType;
205 using VTKShapeType = Intern::VTKShape<CellShapeType>;
206
208 static constexpr int num_coords = 3;
209
212
213#ifdef FEAT_HAVE_ZLIB
214 static constexpr bool can_compress = true;
215#else
216 static constexpr bool can_compress = false;
217#endif
218
219 protected:
221 using VarDeque = std::deque<std::pair<String, std::vector<double>>>;
222
223 // NOTE(mmuegge): Depending on wether we are writing a mesh or a meshpart,
224 // we may need to do some additional handling of indices.
225 // The accessor functions allow us to do so,
226 // while presenting a consistent interface to the actual file writing logic.
227
247 bool _ascii_output = false;
249 bool _use_compression = can_compress;
250
251 public:
263 explicit ExportVTK(const MeshType& mesh, int var_prec = 0) :
264 _num_verts(mesh.get_num_entities(0)),
265 _num_cells(mesh.get_num_entities(cell_dim_)),
266 _var_prec(Math::max(0, var_prec))
267 {
268 const auto& vertex_set = mesh.get_vertex_set();
269 const auto& index_set = mesh.template get_index_set<cell_dim_, 0>();
270
271 _vertices = [&](Index i, auto& vert) {
272 // Actual vertex might not be 3D
273 // vert is zeroed before this is called
274 for(int j(0); j < vertex_set.num_coords; j++)
275 {
276 vert[j] = float(vertex_set[i][j]);
277 }
278 };
279 _cells = [&](Index i, auto& tuple) {
280 for(int j(0); j < verts_per_cell; j++)
281 {
282 tuple[j] = index_set(i, j);
283 }
284 };
285 }
286
302 explicit ExportVTK(const MeshType& mesh, const MeshPart<MeshType>& part, int var_prec = 0) :
303 _num_verts(part.get_num_entities(0)),
304 _num_cells(part.get_num_entities(cell_dim_)),
305 _var_prec(Math::max(0, var_prec))
306 {
307 const auto& vertex_set = mesh.get_vertex_set();
308 const auto& vertex_target_set = part.template get_target_set<0>();
309 const auto& cell_target_set = part.template get_target_set<cell_dim_>();
310
311 _vertices = [&](Index i, auto& vert) {
312 // Actual vertex might not be 3D
313 // vert is zeroed before this is called
314 for(int j(0); j < vertex_set.num_coords; j++)
315 {
316 vert[j] = float(vertex_set[vertex_target_set[i]][j]);
317 }
318 };
319
320 if(part.has_topology())
321 {
322 // The meshpart has its own topology. Use that.
323 const auto& index_set = part.template get_index_set<cell_dim_, 0>();
324 _cells = [&](Index i, auto& tuple) {
325 for(int j(0); j < verts_per_cell; j++)
326 {
327 tuple[j] = index_set(i, j);
328 }
329 };
330 }
331 else
332 {
333 // The meshpart has no own topology. Use the mesh topology.
334 const auto& index_set = mesh.template get_index_set<cell_dim_, 0>();
335
336 // The mesh index-set returns indices of vertices the mesh's index-space,
337 // but the .vtu will be written in the meshparts index-space.
338 // We thus need to search for the corresponding index on the meshpart for any vertex index.
339 _cells = [&](Index i, auto& tuple)
340 {
341 for(int j(0); j < verts_per_cell; j++)
342 {
343 const Index vertex = index_set(cell_target_set[i], j);
344 for(Index k(0); k < vertex_target_set.get_num_entities(); k++)
345 {
346 if(vertex_target_set[k] == vertex)
347 {
348 tuple[j] = k;
349 }
350 }
351 }
352 };
353 }
354 }
355
356#if defined(FEAT_HAVE_CGAL) || defined(DOXYGEN)
368 template<typename DT_>
369 explicit ExportVTK(const Geometry::CGALWrapper<DT_>& cw, int var_prec = 0) :
370 _num_verts(cw.get_num_entities(0)),
371 _num_cells(cw.get_num_entities(cell_dim_)),
372 _var_prec(Math::max(0, var_prec))
373 {
374 XASSERTM(cell_dim_ == 2, "CGAL Export only possible with surface mesh");
375
376 _vertices = [&](Index i, auto& vert) {
377 auto point = cw.point(i);
378 for(int j(0); j < verts_per_cell; j++)
379 {
380 vert[j] = float(point[j]);
381 }
382 };
383 _cells = [&](Index i, auto& tuple) {
384 auto it = cw.vertices_around_face().image_begin(i);
385 auto end = cw.vertices_around_face().image_end(i);
386 Index j(0);
387 for(;it != end; ++it)
388 {
389 tuple[j++] = *it;
390 }
391 };
392 }
393#endif
394
396 virtual ~ExportVTK() = default;
397
399 ExportVTK(const ExportVTK& other) = default;
400
402 ExportVTK(ExportVTK&& other) noexcept = default;
403
405 ExportVTK& operator=(const ExportVTK& other) = default;
406
409
413 void clear()
414 {
415 _cell_scalars.clear();
416 _vertex_scalars.clear();
417 _vertex_vectors.clear();
418 _cell_vectors.clear();
419 }
420
426 void enable_ascii_output(bool flag)
427 {
428 _ascii_output = flag;
429 }
430
438 void enable_compression(bool flag)
439 {
440 _use_compression = flag;
441 }
442
460 template<typename T_>
461 void add_vertex_scalar(const String& name, const T_* data, double scaling_factor = 1.0)
462 {
463 XASSERTM(data != nullptr, "data array is nullptr");
464 std::vector<double> d(_num_verts);
465 for(Index i(0); i < _num_verts; ++i)
466 {
467 d[i] = scaling_factor * double(data[i]);
468 }
469 _vertex_scalars.emplace_back(name, std::move(d));
470 }
471
488 template<typename Vector_>
489 void add_vertex_scalar(const String& name, const Vector_& v, double scaling_factor = 1.0,
490 typename Vector_::ValueType* = nullptr) // SFINAE
491 {
492 XASSERTM(this->_num_verts <= v.size(), "invalid number of vector elements!");
493 const Memory::TypedView<typename Vector_::ValueType> vx(v.elements_view_r());
494 std::vector<double> d(_num_verts);
495 for(Index i(0); i < _num_verts; ++i)
496 {
497 d[i] = scaling_factor * double(vx[i]);
498 }
499 _vertex_scalars.emplace_back(name, std::move(d));
500 }
501
521 template<typename T_>
523 const String& name,
524 const T_* x,
525 const T_* y = nullptr,
526 const T_* z = nullptr,
527 double scaling_factor = 1.0)
528 {
529 XASSERTM(x != nullptr, "x-data array is nullptr");
530 std::vector<double> d(3 * _num_verts);
531
532 if(y != nullptr && z != nullptr)
533 {
534 for(Index i(0); i < _num_verts; ++i)
535 {
536 d[(3 * i) + 0] = scaling_factor * double(x[i]);
537 d[(3 * i) + 1] = scaling_factor * double(y[i]);
538 d[(3 * i) + 2] = scaling_factor * double(z[i]);
539 }
540 }
541 else if(y != nullptr)
542 {
543 for(Index i(0); i < _num_verts; ++i)
544 {
545 d[(3 * i) + 0] = scaling_factor * double(x[i]);
546 d[(3 * i) + 1] = scaling_factor * double(y[i]);
547 d[(3 * i) + 2] = 0.0;
548 }
549 }
550 else
551 {
552 for(Index i(0); i < _num_verts; ++i)
553 {
554 d[(3 * i) + 0] = scaling_factor * double(x[i]);
555 d[(3 * i) + 1] = 0.0;
556 d[(3 * i) + 2] = 0.0;
557 }
558 }
559 _vertex_vectors.emplace_back(name, std::move(d));
560 }
561
582 template<typename VectorType_>
583 void add_vertex_vector(const String& name, const VectorType_& v, double scaling_factor = 1.0,
584 typename VectorType_::ValueType* = nullptr) // SFINAE
585 {
586 std::vector<double> d(3 * _num_verts);
587 const auto v_view = v.elements_view_r();
588
589 for(Index i(0); i < _num_verts; ++i)
590 {
591 for(Index j(0); j < 3; ++j)
592 {
593 d[(Index(3) * i) + j] = double(0);
594 }
595
596 for(int j(0); j < v.block_size; ++j)
597 {
598 d[(Index(3) * i) + Index(j)] = scaling_factor * double(v_view(i)[j]);
599 }
600 }
601 _vertex_vectors.emplace_back(name, std::move(d));
602 }
603
624 template<typename DT_, int dim_>
625 void add_vertex_vector(const String& name, const std::vector<Tiny::Vector<DT_, dim_>>& v, double scaling_factor = 1.0)
626 {
627 std::vector<double> d(3 * _num_verts);
628
629 for(Index i(0); i < _num_verts; ++i)
630 {
631 for(Index j(0); j < 3; ++j)
632 {
633 d[(Index(3) * i) + j] = double(0);
634 }
635
636 for(int j(0); j < dim_; ++j)
637 {
638 d[(Index(3) * i) + Index(j)] = scaling_factor * double(v[i][j]);
639 }
640 }
641 _vertex_vectors.emplace_back(name, std::move(d));
642 }
643
661 template<typename T_>
662 void add_cell_scalar(const String& name, const T_* data, double scaling_factor = 1.0)
663 {
664 XASSERTM(data != nullptr, "data array is nullptr");
665 std::vector<double> d(_num_cells);
666 for(Index i(0); i < _num_cells; ++i)
667 {
668 d[i] = scaling_factor * double(data[i]);
669 }
670 _cell_scalars.emplace_back(name, std::move(d));
671 }
672
689 template<typename Vector_>
690 void add_cell_scalar(const String& name, const Vector_& v, double scaling_factor = 1.0,
691 typename Vector_::ValueType* = nullptr) // SFINAE
692 {
693 XASSERTM(this->_num_cells <= v.size(), "invalid number of vector elements!");
694 const Memory::TypedView<typename Vector_::ValueType> vx(v.elements_view_r());
695 std::vector<double> d(_num_cells);
696 for(Index i(0); i < _num_cells; ++i)
697 {
698 d[i] = scaling_factor * double(vx[i]);
699 }
700 _cell_scalars.emplace_back(name, std::move(d));
701 }
702
722 template<typename T_>
724 const String& name,
725 const T_* x,
726 const T_* y = nullptr,
727 const T_* z = nullptr,
728 double scaling_factor = 1.0)
729 {
730 XASSERTM(x != nullptr, "x-data array is nullptr");
731 std::vector<double> d(3 * _num_cells);
732
733 if(y != nullptr && z != nullptr)
734 {
735 for(Index i(0); i < _num_cells; ++i)
736 {
737 d[(3 * i) + 0] = scaling_factor * double(x[i]);
738 d[(3 * i) + 1] = scaling_factor * double(y[i]);
739 d[(3 * i) + 2] = scaling_factor * double(z[i]);
740 }
741 }
742 else if(y != nullptr)
743 {
744 for(Index i(0); i < _num_cells; ++i)
745 {
746 d[(3 * i) + 0] = scaling_factor * double(x[i]);
747 d[(3 * i) + 1] = scaling_factor * double(y[i]);
748 d[(3 * i) + 2] = 0.0;
749 }
750 }
751 else
752 {
753 for(Index i(0); i < _num_cells; ++i)
754 {
755 d[(3 * i) + 0] = scaling_factor * double(x[i]);
756 d[(3 * i) + 1] = 0.0;
757 d[(3 * i) + 2] = 0.0;
758 }
759 }
760 _cell_vectors.emplace_back(name, std::move(d));
761 }
762
783 template<typename VectorType_>
784 void add_cell_vector(const String& name, const VectorType_& v, double scaling_factor = 1.0,
785 typename VectorType_::ValueType* = nullptr) // SFINAE
786 {
787 std::vector<double> d(3 * _num_cells);
788 const auto v_view = v.elements_view_r();
789
790 for(Index i(0); i < _num_cells; ++i)
791 {
792 for(Index j(0); j < 3; ++j)
793 {
794 d[(Index(3) * i) + j] = double(0);
795 }
796
797 for(int j(0); j < v.block_size; ++j)
798 {
799 d[(Index(3) * i) + Index(j)] = scaling_factor * double(v_view(i)[j]);
800 }
801 }
802 _cell_vectors.emplace_back(name, std::move(d));
803 }
804
825 template<typename DT_, int dim_>
826 void add_cell_vector(const String& name, const std::vector<Tiny::Vector<DT_, dim_>>& v, double scaling_factor = 1.0)
827 {
828 std::vector<double> d(3 * _num_cells);
829
830 for(Index i(0); i < _num_cells; ++i)
831 {
832 for(Index j(0); j < 3; ++j)
833 {
834 d[(Index(3) * i) + j] = double(0);
835 }
836
837 for(int j(0); j < dim_; ++j)
838 {
839 d[(Index(3) * i) + Index(j)] = scaling_factor * double(v[i][j]);
840 }
841 }
842 _cell_vectors.emplace_back(name, std::move(d));
843 }
844
851 void write(const String& filename) const
852 {
853 // try to open the output file
854 String vtu_name(filename + ".vtu");
855 std::ofstream ofs(vtu_name.c_str());
856 if(!(ofs.is_open() && ofs.good()))
857 {
858 throw FileError("Failed to create '" + vtu_name + "'");
859 }
860
861 // write
862 write_vtu(ofs);
863
864 // and close
865 ofs.close();
866 }
867
887 void write(const String& filename, const int rank, const int nparts)
888 {
889 // call the standard serial write version if nparts < 1
890 if(nparts <= 1)
891 {
892 write(filename);
893 return;
894 }
895
896 // verify rank
897 XASSERTM((rank >= 0) && (rank < nparts), "Invalid rank");
898
899 // Add rank cell array since we're parallel if we come to here
900 std::vector<double> rank_array((std::size_t(_num_cells)), double(rank));
901 add_cell_scalar("rank", rank_array.data());
902
903 // compute number of non-zero digits in (nparts-1) for padding
904 const std::size_t ndigits = Math::ilog10(std::size_t(nparts - 1));
905
906 // write serial VTU file: "filename.#rank.vtu"
907 write(filename + "." + stringify(rank).pad_front(ndigits, '0'));
908
909 // we're done unless we have rank = 0
910 if(rank != 0)
911 {
912 return;
913 }
914
915 // try to open our output file
916 String pvtu_name(filename + ".pvtu");
917 std::ofstream ofs(pvtu_name.c_str());
918 if(!(ofs.is_open() && ofs.good()))
919 {
920 throw FileError("Failed to create '" + pvtu_name + "'");
921 }
922
923 // extract the file title from our filename
924 std::size_t p = filename.find_last_of("\\/");
925 String file_title = filename.substr(p == FEAT::String::npos ? 0 : ++p);
926
927 // write PVTU file
928 write_pvtu(ofs, file_title, nparts);
929
930 // and close
931 ofs.close();
932 }
933
946 void write(const String& filename, const Dist::Comm& comm)
947 {
948 // Add rank cell array since we're parallel if we come to here
949 std::vector<double> rank_array(std::size_t(_num_cells), double(comm.rank()));
950 add_cell_scalar("rank", rank_array.data());
951
952 // compute number of non-zero digits in (nparts-1) for padding
953 const auto ndigits = std::size_t(Math::max(Math::ilog10(comm.size() - 1), 1));
954
955 // write serial VTU file into a stringstream
956 std::stringstream stream;
957 write_vtu(stream);
958
959 // generate pattern for filename: "filename.#rank.vtu"
960 String pattern = filename + "." + String(ndigits, '*') + ".vtu";
961
962 // write distributed VTU files
963 DistFileIO::write_sequence(stream, pattern, comm);
964
965 // we're done unless we have rank = 0
966 if(comm.rank() != 0)
967 {
968 return;
969 }
970
971 // try to open our output file
972 String pvtu_name(filename + ".pvtu");
973 std::ofstream ofs(pvtu_name.c_str());
974 if(!(ofs.is_open() && ofs.good()))
975 {
976 throw FileError("Failed to create '" + pvtu_name + "'");
977 }
978
979 // extract the file title from our filename
980 std::size_t p = filename.find_last_of("\\/");
981 String file_title = filename.substr(p == FEAT::String::npos ? 0 : ++p);
982
983 // write PVTU file
984 write_pvtu(ofs, file_title, comm.size());
985
986 // and close
987 ofs.close();
988 }
989
996 void write_vtu(std::ostream& os) const
997 {
998 // fetch basic information
999
1000 // write VTK header
1001 os << R"(<VTKFile type="UnstructuredGrid" version="0.1" byte_order=")";
1002 os << (_little_endian() ? "LittleEndian" : "BigEndian") << "\"";
1003
1004 if(!_ascii_output && _use_compression && can_compress)
1005 {
1006#ifndef FEAT_HAVE_ZLIB
1007 XABORTM("Requested compression in ExportVTK, but ZLib is not available!");
1008#endif
1009 os << " compressor=\"vtkZLibDataCompressor\"";
1010 }
1011
1012 os << ">\n";
1013 os << "<!-- Generated by FEAT v" << version_major << "." << version_minor;
1014 os << "." << version_patch << " -->\n";
1015
1016 // write mesh header
1017 os << "<UnstructuredGrid>\n";
1018 os << "<Piece NumberOfPoints=\"" << _num_verts << "\" NumberOfCells=\"" << _num_cells << "\">\n";
1019
1020 // write point data
1021 if((!_vertex_scalars.empty()) || (!_vertex_vectors.empty()))
1022 {
1023 os << "<PointData>\n";
1024 for(const auto& var : _vertex_scalars)
1025 {
1026 _write_data_array(os, var, 1);
1027 }
1028
1029 for(const auto& var : _vertex_vectors)
1030 {
1031 _write_data_array(os, var, 3);
1032 }
1033 os << "</PointData>\n";
1034 }
1035
1036 // write cell data
1037 if(!_cell_scalars.empty() || !_cell_vectors.empty())
1038 {
1039 os << "<CellData>\n";
1040
1041 for(const auto& var : _cell_scalars)
1042 {
1043 _write_data_array(os, var, 1);
1044 }
1045
1046 for(const auto& var : _cell_vectors)
1047 {
1048 _write_data_array(os, var, 3);
1049 }
1050
1051 os << "</CellData>\n";
1052 }
1053
1054 // write vertices
1055 os << "<Points>\n";
1056 if(_ascii_output)
1057 {
1058 // Ascii output. Write data array adhoc without copying all vertices.
1059 os << R"(<DataArray type="Float32" NumberOfComponents="3" format="ascii" Name="test">)" << "\n";
1061 for(Index i(0); i < _num_verts; ++i)
1062 {
1063 vertex.format(0);
1064 _vertices(i, vertex);
1065 os << vertex[0];
1066 for(int j(1); j < num_coords; ++j)
1067 {
1068 os << " " << vertex[j];
1069 }
1070 os << "\n";
1071 }
1072 os << "</DataArray>\n";
1073 }
1074 else
1075 {
1076 // Binary output. Copy vertices to buffer for base64 encoding
1077 // This might not be needed, but ensures we are independent of the internal representation of the vertices
1078 std::pair<String, std::vector<float>> vertices("", {});
1079 vertices.second.reserve(3 * _num_cells);
1080
1082 for(Index i(0); i < _num_verts; ++i)
1083 {
1084 vertex.format(0);
1085 _vertices(i, vertex);
1086 for(int j(0); j < num_coords; ++j)
1087 {
1088 vertices.second.push_back(static_cast<float>(vertex[j]));
1089 }
1090 }
1091
1092 _write_data_array(os, vertices, num_coords);
1093 }
1094 os << "</Points>\n";
1095
1096 // write cells
1097 os << "<Cells>\n";
1098 if(_ascii_output)
1099 {
1100 os << R"(<DataArray type="UInt32" Name="connectivity">)" << "\n";
1102 for(Index i(0); i < _num_cells; ++i)
1103 {
1104 _cells(i, cell);
1105 os << cell[VTKShapeType::map(0)];
1106 for(int j(1); j < verts_per_cell; ++j)
1107 {
1108 os << " " << cell[VTKShapeType::map(j)];
1109 }
1110 os << "\n";
1111 }
1112 os << "</DataArray>\n";
1113 }
1114 else
1115 {
1116 // Same as for vertices. Copy for base64 encoding
1117 std::pair<String, std::vector<std::uint32_t>> connectivity("connectivity", {});
1118 connectivity.second.reserve(_num_cells * verts_per_cell);
1119
1121 for(Index i(0); i < _num_cells; ++i)
1122 {
1123 _cells(i, cell);
1124 for(int j(0); j < verts_per_cell; ++j)
1125 {
1126 connectivity.second.push_back(static_cast<std::uint32_t>(cell[VTKShapeType::map(j)]));
1127 }
1128 }
1129
1130 _write_data_array(os, connectivity);
1131 }
1132
1133 if(_ascii_output)
1134 {
1135 os << R"(<DataArray type="UInt32" Name="offsets">)" << "\n";
1136 for(Index i(0); i < _num_cells; ++i)
1137 {
1138 os << ((i + 1) * verts_per_cell) << "\n";
1139 }
1140 os << "</DataArray>\n";
1141 }
1142 else
1143 {
1144 // Same as for vertices. Copy for base64 encoding
1145 std::pair<String, std::vector<std::uint32_t>> offsets("offsets", {});
1146 offsets.second.reserve(_num_cells);
1147
1148 for(Index i(0); i < _num_cells; ++i)
1149 {
1150 offsets.second.push_back(static_cast<std::uint32_t>((i + 1) * verts_per_cell));
1151 }
1152
1153 _write_data_array(os, offsets);
1154 }
1155
1156 if(_ascii_output)
1157 {
1158 os << R"(<DataArray type="UInt32" Name="types">)" << "\n";
1159 for(Index i(0); i < _num_cells; ++i)
1160 {
1161 os << VTKShapeType::type << "\n";
1162 }
1163 os << "</DataArray>\n";
1164 }
1165 else
1166 {
1167 // Same as for vertices. Copy for base64 encoding
1168 std::pair<String, std::vector<std::uint32_t>> types("types", {});
1169 types.second.reserve(_num_cells);
1170
1171 for(Index i(0); i < _num_cells; ++i)
1172 {
1173 types.second.push_back(VTKShapeType::type);
1174 }
1175
1176 _write_data_array(os, types);
1177 }
1178 os << "</Cells>\n";
1179
1180 // finish
1181 os << "</Piece>\n";
1182 os << "</UnstructuredGrid>\n";
1183 os << "</VTKFile>\n";
1184 }
1185
1198 void write_pvtu(std::ostream& os, const String& file_title, const int nparts) const
1199 {
1200 // write VTK header
1201 os << R"(<VTKFile type="PUnstructuredGrid" version="0.1" byte_order=")";
1202 os << (_little_endian() ? "LittleEndian" : "BigEndian") << "\"";
1203
1204 if(!_ascii_output && _use_compression && can_compress)
1205 {
1206#ifndef FEAT_HAVE_ZLIB
1207 XABORTM("Requested compression in ExportVTK, but ZLib is not available!");
1208#endif
1209 os << " compressor=\"vtkZLibDataCompressor\"";
1210 }
1211
1212 os << ">\n";
1213 os << "<!-- Generated by FEAT v" << version_major << "." << version_minor;
1214 os << "." << version_patch << " -->\n";
1215 os << "<PUnstructuredGrid GhostLevel=\"0\">\n";
1216
1217 // write vertex data
1218 if((!_vertex_scalars.empty()) || (!_vertex_vectors.empty()))
1219 {
1220 os << "<PPointData>\n";
1221
1222 // write vertex variables
1223 for(const auto& vertex_scalar : _vertex_scalars)
1224 {
1225 os << "<PDataArray type=\"Float64\" Name=\"" << vertex_scalar.first << "\" />\n";
1226 }
1227 // write vertex fields
1228 for(const auto& vertex_vector : _vertex_vectors)
1229 {
1230 os << "<PDataArray type=\"Float64\" Name=\"" << vertex_vector.first;
1231 os << "\" NumberOfComponents=\"3\" />\n";
1232 }
1233
1234 os << "</PPointData>\n";
1235 }
1236
1237 // write cell variables
1238 if(!_cell_scalars.empty() || !_cell_vectors.empty())
1239 {
1240 os << "<PCellData>\n";
1241 // write cell scalars
1242 for(const auto& cell_scalar : _cell_scalars)
1243 {
1244 os << "<PDataArray type=\"Float64\" Name=\"" << cell_scalar.first << "\" />\n";
1245 }
1246 // write cell fields
1247 for(const auto& cell_vector : _cell_vectors)
1248 {
1249 os << "<PDataArray type=\"Float64\" Name=\"" << cell_vector.first;
1250 os << "\" NumberOfComponents=\"3\" />\n";
1251 }
1252 os << "</PCellData>\n";
1253 }
1254
1255 // write vertices
1256 os << "<PPoints>\n";
1257 os << "<PDataArray type=\"Float32\" NumberOfComponents=\"3\" />\n";
1258 os << "</PPoints>\n";
1259
1260 // compute number of non-zero digits in (nparts-1) for padding
1261 const std::size_t ndigits = Math::ilog10(std::size_t(nparts - 1));
1262
1263 // now let's write our piece data
1264 for(int i(0); i < nparts; ++i)
1265 {
1266 os << "<Piece Source=\"" << file_title << "." << stringify(i).pad_front(ndigits, '0');
1267 os << ".vtu\" />\n";
1268 }
1269
1270 // finish
1271 os << "</PUnstructuredGrid>\n";
1272 os << "</VTKFile>\n";
1273 }
1274 private:
1275
1284 {
1285 std::uint32_t num_bytes;
1286
1287 explicit UncompressedHeader(std::uint32_t number_of_bytes) : num_bytes(number_of_bytes)
1288 {
1289 }
1290 };
1291
1298 {
1299 std::uint32_t blocks = 1;
1300 std::uint32_t blocksize;
1301 std::uint32_t last_blocksize;
1302 std::uint32_t compressed_blocksizes[1];
1303
1304 explicit CompressedHeader(std::uint32_t uncompressed_bytes, std::uint32_t compressed_bytes) :
1305 blocksize(uncompressed_bytes),
1306 last_blocksize(uncompressed_bytes),
1307 compressed_blocksizes{compressed_bytes}
1308 {
1309 }
1310 };
1311
1326 template<typename T_>
1327 void _write_data_array(std::ostream& os, const std::pair<String, std::vector<T_>>& data, Index number_of_components=0) const
1328 {
1329 // Ensure there is no padding in headers.
1330 // Otherwise the reinterpret_casts below would produce garbage data
1331 static_assert(sizeof(UncompressedHeader) == sizeof(std::uint32_t));
1332 static_assert(sizeof(CompressedHeader) == 4 * sizeof(std::uint32_t));
1333
1334 std::string_view format = _ascii_output ? "ascii" : "binary";
1335 std::string_view type = Intern::VTKType<T_>::type;
1336
1337 // Write XML-tag
1338 os << "<DataArray type=\"" << type << "\" format=\"" << format << "\"";
1339 if(data.first != "")
1340 {
1341 os << " Name = \"" << data.first << "\"";
1342 }
1343 if(number_of_components != 0)
1344 {
1345 os << " NumberOfComponents=\"" << number_of_components << "\"";
1346 }
1347 os << ">\n";
1348
1349 if(_ascii_output)
1350 {
1351 Index num_blocks = data.second.size() / number_of_components;
1352 for(Index i(0); i < num_blocks; ++i)
1353 {
1354 for(Index j(0); j < number_of_components; j++)
1355 {
1356 os << stringify_fp_sci(data.second[(i * number_of_components) + j], _var_prec);
1357 os << ((j == number_of_components - 1) ? "\n" : " ");
1358 }
1359 }
1360 }
1361 else if(_use_compression && can_compress)
1362 {
1363 auto uncompressed_size = static_cast<std::uint32_t>(data.second.size() * sizeof(T_));
1364
1365 // Encode with compression
1366 Pack::Type pack_type = Pack::deduct_type<T_>() | Pack::Type::Mask_Z;
1367 std::size_t buffer_size = Pack::estimate_size(data.second.size(), pack_type);
1368
1369 std::vector<Pack::u8> buffer(buffer_size, 0);
1370 std::size_t compressed_size = Pack::encode(buffer.data(), data.second.data(), buffer_size, data.second.size(), pack_type, false);
1371
1372 // Set up header and data pointers
1373 CompressedHeader header(uncompressed_size, static_cast<std::uint32_t>(compressed_size));
1374 const auto* header_begin = reinterpret_cast<const Pack::u8*>(&header);
1375 const auto* header_end = header_begin + sizeof(CompressedHeader);
1376
1377 const auto* data_begin = reinterpret_cast<const Pack::u8*>(buffer.data());
1378 const auto* data_end = data_begin + compressed_size;
1379
1380 // For compressed data, the header and the data are encoded separately
1381 os << Pack::base64_encode(header_begin, header_end) << Pack::base64_encode(data_begin, data_end) << "\n";
1382 }
1383 else
1384 {
1385 UncompressedHeader header(static_cast<std::uint32_t>(data.second.size() * sizeof(T_)));
1386
1387 const auto* header_begin = reinterpret_cast<const Pack::u8*>(&header);
1388 const auto* header_end = header_begin + sizeof(header);
1389
1390 const auto* data_begin = reinterpret_cast<const Pack::u8*>(data.second.data());
1391 const auto* data_end = data_begin + header.num_bytes;
1392
1393 os << Pack::base64_encode(header_begin, header_end) << Pack::base64_encode(data_begin, data_end) << "\n";
1394 }
1395
1396 // Close XML-tag
1397 os << "</DataArray>\n";
1398 }
1399
1400 // Copied from binary_stream-test.cpp
1401 bool _little_endian() const
1402 {
1403 std::int32_t x = 1;
1404 void* xv = (void*)&x;
1405 auto* x16 = (int16_t*)xv;
1406 return *x16 == 1;
1407 }
1408 }; // class ExportVTK
1409} // namespace FEAT::Geometry
#define XABORTM(msg)
Abortion macro definition with custom message.
Definition: assertion.hpp:192
#define XASSERTM(expr, msg)
Assertion macro definition with custom message.
Definition: assertion.hpp:263
FEAT Kernel base header.
Communicator class.
Definition: dist.hpp:1657
int size() const
Returns the size of this communicator.
Definition: dist.hpp:1814
int rank() const
Returns the rank of this process in this communicator.
Definition: dist.hpp:1802
static void write_sequence(std::stringstream &stream, const String &pattern, const Dist::Comm &comm, bool truncate=true)
Writes a rank-indexed text file sequence.
Base class for file related errors.
Definition: exception.hpp:173
Wrapper for the CGAL Library.
Definition: cgal.hpp:173
CGALVerticesAroundFaceAdjactor< DT_ > vertices_around_face() const
Returns an adjactor for vertices around faces of the mesh.
PointType point(std::uint32_t idx) const
Returns the point of the surface mesh with the given index.
VTK exporter class template.
Definition: export_vtk.hpp:196
ExportVTK(const MeshType &mesh, const MeshPart< MeshType > &part, int var_prec=0)
Constructor.
Definition: export_vtk.hpp:302
virtual ~ExportVTK()=default
destructor
VarDeque _vertex_scalars
vertex variable list
Definition: export_vtk.hpp:237
void add_vertex_scalar(const String &name, const Vector_ &v, double scaling_factor=1.0, typename Vector_::ValueType *=nullptr)
Adds a scalar vertex variable to the exporter.
Definition: export_vtk.hpp:489
void add_vertex_vector(const String &name, const T_ *x, const T_ *y=nullptr, const T_ *z=nullptr, double scaling_factor=1.0)
Adds a vector-field vertex variable to the exporter.
Definition: export_vtk.hpp:522
Index _num_verts
number of vertices in mesh
Definition: export_vtk.hpp:233
void add_cell_vector(const String &name, const std::vector< Tiny::Vector< DT_, dim_ > > &v, double scaling_factor=1.0)
Adds a vector-field cell variable given by a std::vector of Tiny::Vector to the exporter.
Definition: export_vtk.hpp:826
std::function< void(Index, Tiny::Vector< float, num_coords > &)> _vertices
Accessor function for vertices.
Definition: export_vtk.hpp:229
bool _use_compression
compressed output flag. Only applicable if _binary_output is true
Definition: export_vtk.hpp:249
static constexpr int num_coords
Coordinates per vertex. The VTK documentation states that this is always three.
Definition: export_vtk.hpp:208
ExportVTK & operator=(ExportVTK &&other)=default
Move-assignment constructor.
int _var_prec
precision of variables
Definition: export_vtk.hpp:245
void write(const String &filename, const Dist::Comm &comm)
Writes out the data to a parallel XML-PVTU file.
Definition: export_vtk.hpp:946
void write(const String &filename, const int rank, const int nparts)
Writes out the data to a parallel XML-PVTU file.
Definition: export_vtk.hpp:887
void enable_ascii_output(bool flag)
Enable or disable binary output.
Definition: export_vtk.hpp:426
void clear()
Clears all vertex and cell variables in the exporter.
Definition: export_vtk.hpp:413
void write(const String &filename) const
Writes out the data to a serial XML-VTU file.
Definition: export_vtk.hpp:851
typename MeshType::ShapeType ShapeType
our shape type
Definition: export_vtk.hpp:201
void write_vtu(std::ostream &os) const
Writes out the mesh and variable data in serial XML-VTU format.
Definition: export_vtk.hpp:996
typename Shape::FaceTraits< ShapeType, cell_dim_ >::ShapeType CellShapeType
shape type of exported cells
Definition: export_vtk.hpp:203
std::function< void(Index, IndexTuple< verts_per_cell > &)> _cells
Accessor function for cells.
Definition: export_vtk.hpp:231
VarDeque _vertex_vectors
vertex field list
Definition: export_vtk.hpp:239
void write_pvtu(std::ostream &os, const String &file_title, const int nparts) const
Writes out the partition data in parallel XML-PVTU format.
ExportVTK(const ExportVTK &other)=default
Copy constructor.
Index _num_cells
number of cells in mesh
Definition: export_vtk.hpp:235
void add_cell_vector(const String &name, const T_ *x, const T_ *y=nullptr, const T_ *z=nullptr, double scaling_factor=1.0)
Adds a vector-field cell variable to the exporter.
Definition: export_vtk.hpp:723
void add_vertex_vector(const String &name, const std::vector< Tiny::Vector< DT_, dim_ > > &v, double scaling_factor=1.0)
Adds a vector-field vertex variable given by a std::vector of Tiny::Vector to the exporter.
Definition: export_vtk.hpp:625
void add_vertex_vector(const String &name, const VectorType_ &v, double scaling_factor=1.0, typename VectorType_::ValueType *=nullptr)
Adds a vector-field vertex variable given by a LAFEM::***VectorBlocked to the exporter.
Definition: export_vtk.hpp:583
ExportVTK(ExportVTK &&other) noexcept=default
Move constructor.
VarDeque _cell_scalars
cell variable list
Definition: export_vtk.hpp:241
Intern::VTKShape< CellShapeType > VTKShapeType
our VTK shape type
Definition: export_vtk.hpp:205
ExportVTK & operator=(const ExportVTK &other)=default
Copy-assignment constructor.
ExportVTK(const MeshType &mesh, int var_prec=0)
Constructor.
Definition: export_vtk.hpp:263
void enable_compression(bool flag)
Enable or disable compression.
Definition: export_vtk.hpp:438
void add_cell_scalar(const String &name, const T_ *data, double scaling_factor=1.0)
Adds a scalar cell variable to the exporter.
Definition: export_vtk.hpp:662
VarDeque _cell_vectors
cell field list
Definition: export_vtk.hpp:243
void add_cell_vector(const String &name, const VectorType_ &v, double scaling_factor=1.0, typename VectorType_::ValueType *=nullptr)
Adds a vector-field cell variable given by a LAFEM::***VectorBlocked to the exporter.
Definition: export_vtk.hpp:784
bool _ascii_output
ascii output flag
Definition: export_vtk.hpp:247
void add_vertex_scalar(const String &name, const T_ *data, double scaling_factor=1.0)
Adds a scalar vertex variable to the exporter.
Definition: export_vtk.hpp:461
ExportVTK(const Geometry::CGALWrapper< DT_ > &cw, int var_prec=0)
Constructor.
Definition: export_vtk.hpp:369
void _write_data_array(std::ostream &os, const std::pair< String, std::vector< T_ > > &data, Index number_of_components=0) const
Writes an DataArray XML-node to the give output stream.
std::deque< std::pair< String, std::vector< double > > > VarDeque
our variable container
Definition: export_vtk.hpp:221
void add_cell_scalar(const String &name, const Vector_ &v, double scaling_factor=1.0, typename Vector_::ValueType *=nullptr)
Adds a scalar cell variable to the exporter.
Definition: export_vtk.hpp:690
static constexpr int verts_per_cell
Vertices per cell.
Definition: export_vtk.hpp:211
Class template for partial meshes.
Definition: mesh_part.hpp:90
bool has_topology() const
Checks if this MeshPart has a mesh topology.
Definition: mesh_part.hpp:297
Typed memory view class.
String class implementation.
Definition: string.hpp:47
String pad_front(size_type len, char c=' ') const
Pads the front of the string up to a desired length.
Definition: string.hpp:393
Tiny Vector class template.
CUDA_HOST_DEVICE void format(DataType alpha=DataType(0))
Formats the vector.
Geometry namespace.
@ other
generic/other permutation strategy
T_ ilog10(T_ x)
Computes the integral base-10 logarithm of an integer, i.e. its number of non-zero decimal digits.
Definition: math.hpp:231
T_ max(T_ a, T_ b)
Returns the maximum of two values.
Definition: math.hpp:137
std::size_t encode(void *buf, const T_ *src, const std::size_t buf_size, const std::size_t count, const Pack::Type pack_type, bool swap_bytes, double tolerance)
Encodes an array into a packed buffer.
Definition: pack.cpp:580
std::size_t estimate_size(const std::size_t count, const Pack::Type type, const double tolerance)
Computes the estimated (upper bound) pack buffer size for an array.
Definition: pack.cpp:557
String base64_encode(const Pack::u8 *begin, const Pack::u8 *end)
Encodes bytes into a Base64 string.
Definition: pack.cpp:1115
Type
Type enumeration.
Definition: pack.hpp:70
std::uint8_t u8
8-bit unsigned integer type
Definition: pack.hpp:36
String stringify(const T_ &item)
Converts an item into a String.
Definition: string.hpp:993
static constexpr int version_major
FEAT major version number.
static constexpr int version_patch
FEAT patch version number (month)
static constexpr int version_minor
FEAT minor version number (year)
String stringify_fp_sci(DataType_ value, int precision=0, int width=0, bool sign=false)
Prints a floating point value to a string in scientific notation.
Definition: string.hpp:1137
std::uint64_t Index
Index data type.
Header for compressed binary data.
Header for uncompressed binary data.
Index Tuple class template.
Definition: index_set.hpp:35
Face traits tag struct template.
Definition: shape.hpp:106