12#ifndef DUMUX_IO_VTK_VTKREADER_HH
13#define DUMUX_IO_VTK_VTKREADER_HH
20#include <unordered_map>
24#include <dune/common/parallel/mpihelper.hh>
25#include <dune/common/exceptions.hh>
26#include <dune/grid/common/capabilities.hh>
27#include <dune/grid/io/file/vtk/common.hh>
28#include <dune/grid/common/gridfactory.hh>
32#if DUMUX_HAVE_GRIDFORMAT
34#include <gridformat/gridformat.hpp>
35#include <gridformat/traits/dune.hpp>
36#include <gridformat/reader.hpp>
37#include <gridformat/decorators/reader_polylines_subdivider.hpp>
41template<Gr
idFormat::Concepts::Communicator C>
42auto makeGridformatReaderFactory(
const C& c)
44 return [fac = GridFormat::AnyReaderFactory<C>{c}] (
const std::string& f)
45 -> std::unique_ptr<GridFormat::GridReader> {
47 if (f.ends_with(
"vtp"))
48 return std::make_unique<GridFormat::ReaderDecorators::PolylinesSubdivider>(fac.make_for(f));
49 return fac.make_for(f);
64 enum class DataType { cellData, pointData, fieldData };
67 using Data = std::unordered_map<std::string, std::vector<double>>;
69 explicit VTKReader(
const std::string& fileName)
70 : reader_(GridFormat::Reader::from(fileName,
71 Detail::
VTKReader::makeGridformatReaderFactory(
72 Dune::MPIHelper::instance().getCommunicator()
85 return std::ranges::any_of(
86 cell_field_names(reader_),
87 [&] (
const auto& n) {
return name == n; }
90 return std::ranges::any_of(
91 point_field_names(reader_),
92 [&] (
const auto& n) {
return name == n; }
94 else if (type == DataType::fieldData)
95 return std::ranges::any_of(
96 meta_data_field_names(reader_),
97 [&] (
const auto& n) {
return name == n; }
100 DUNE_THROW(Dune::IOError,
"Unknown data type for field '" << name <<
"'");
109 template<
class Container>
114 Container values(reader_.number_of_cells());
115 reader_.cell_field(name)->export_to(values);
120 Container values(reader_.number_of_points());
121 reader_.point_field(name)->export_to(values);
124 else if (type == DataType::fieldData)
126 DUNE_THROW(Dune::NotImplemented,
"Reading meta data not yet implemented");
129 DUNE_THROW(Dune::IOError,
"Unknown data type for field '" << name <<
"'");
137 std::unique_ptr<Grid>
readGrid(
bool verbose =
false)
const
139 Dune::GridFactory<Grid> factory;
150 std::unique_ptr<Grid>
readGrid(Dune::GridFactory<Grid>& factory,
bool verbose =
false)
const
152 if (Dune::MPIHelper::instance().rank() == 0)
155 std::cout <<
"Reading " << Grid::dimension <<
"d grid from vtk file " << reader_.filename() <<
"." << std::endl;
158 GridFormat::Dune::GridFactoryAdapter<Grid> adapter{ factory };
159 reader_.export_grid(adapter);
163 return std::unique_ptr<Grid>(factory.createGrid());
175 std::unique_ptr<Grid>
readGrid(Dune::GridFactory<Grid>& factory,
Data& cellData,
Data& pointData,
bool verbose =
false)
const
177 auto grid =
readGrid(factory, verbose);
178 if (Dune::MPIHelper::instance().rank() == 0)
180 for (
const auto& [name, field_ptr] : cell_fields(reader_))
181 field_ptr->export_to(cellData[name]);
183 for (
const auto& [name, field_ptr] : point_fields(reader_))
184 field_ptr->export_to(pointData[name]);
186 return std::unique_ptr<Grid>(std::move(grid));
190 GridFormat::Reader reader_;
197#include <dumux/io/xml/tinyxml2.h>
209const tinyxml2::XMLElement*
getPieceNode(
const tinyxml2::XMLDocument& doc,
const std::string& fileName)
211 using namespace tinyxml2;
213 const XMLElement* pieceNode = doc.FirstChildElement(
"VTKFile");
214 if (pieceNode ==
nullptr)
215 DUNE_THROW(Dune::IOError,
"Couldn't get 'VTKFile' node in " << fileName <<
".");
217 pieceNode = pieceNode->FirstChildElement(
"UnstructuredGrid");
218 if (pieceNode ==
nullptr)
219 pieceNode = doc.FirstChildElement(
"VTKFile")->FirstChildElement(
"PolyData");
220 if (pieceNode ==
nullptr)
221 pieceNode = doc.FirstChildElement(
"VTKFile")->FirstChildElement(
"PUnstructuredGrid");
222 if (pieceNode ==
nullptr)
223 pieceNode = doc.FirstChildElement(
"VTKFile")->FirstChildElement(
"PPolyData");
224 if (pieceNode ==
nullptr)
225 DUNE_THROW(Dune::IOError,
"Couldn't get 'UnstructuredGrid', 'PUnstructuredGrid', 'PolyData', or 'PPolyData' node in " << fileName <<
".");
227 return pieceNode->FirstChildElement(
"Piece");
235 using namespace tinyxml2;
238 const auto eResult = pDoc.LoadFile(pvtkFileName.c_str());
239 if (eResult != XML_SUCCESS)
240 DUNE_THROW(Dune::IOError,
"Couldn't open XML file " << pvtkFileName <<
".");
243 const XMLElement* pieceNode =
getPieceNode(pDoc, pvtkFileName);
244 const auto myrank = Dune::MPIHelper::instance().rank();
245 for (
int rank = 0; rank < myrank; ++rank)
247 pieceNode = pieceNode->NextSiblingElement(
"Piece");
248 if (pieceNode ==
nullptr)
249 DUNE_THROW(Dune::IOError,
"Couldn't find 'Piece' node for rank "
250 << rank <<
" in " << pvtkFileName <<
".");
253 const char *vtkFileName = pieceNode->Attribute(
"Source");
254 if (vtkFileName ==
nullptr)
255 DUNE_THROW(Dune::IOError,
"Couldn't get 'Source' attribute of 'Piece' node no. " << myrank <<
" in " << pvtkFileName);
277 using Data = std::unordered_map<std::string, std::vector<double>>;
284 using namespace tinyxml2;
285 const auto ext = std::filesystem::path(fileName).extension().string();
289 fileName_ = Dune::MPIHelper::instance().size() > 1 && ext[1] ==
'p' ?
292 const auto eResult = doc_.LoadFile(fileName_.c_str());
293 if (eResult != tinyxml2::XML_SUCCESS)
294 DUNE_THROW(Dune::IOError,
"Couldn't open XML file " << fileName_ <<
".");
296 const XMLElement* pieceNode = getPieceNode_();
297 if (pieceNode ==
nullptr)
298 DUNE_THROW(Dune::IOError,
"Couldn't get 'Piece' node in " << fileName_ <<
".");
308 using namespace tinyxml2;
310 const XMLElement* pieceNode = getPieceNode_();
311 const XMLElement* dataNode = getDataNode_(pieceNode, type);
312 if (dataNode ==
nullptr)
315 const XMLElement* dataArray = findDataArray_(dataNode, name);
316 if (dataArray ==
nullptr)
328 template<
class Container>
331 using namespace tinyxml2;
333 const XMLElement* pieceNode = getPieceNode_();
334 const XMLElement* dataNode = getDataNode_(pieceNode, type);
335 if (dataNode ==
nullptr)
336 DUNE_THROW(Dune::IOError,
"Couldn't get 'PointData' or 'CellData' node in " << fileName_ <<
".");
338 const XMLElement* dataArray = findDataArray_(dataNode, name);
339 if (dataArray ==
nullptr)
340 DUNE_THROW(Dune::IOError,
"Couldn't find the data array " << name <<
".");
342 return parseDataArray_<Container>(dataArray);
350 std::unique_ptr<Grid>
readGrid(
bool verbose =
false)
const
352 static_assert(!Dune::Capabilities::isCartesian<Grid>::v,
"Grid reader only supports unstructured grid implementations");
355 Dune::GridFactory<Grid> factory;
358 if (Dune::MPIHelper::instance().rank() == 0)
361 std::cout <<
"Reading " << Grid::dimension <<
"d grid from vtk file " << fileName_ <<
"." << std::endl;
362 readGrid_(factory, verbose);
365 return std::unique_ptr<Grid>(factory.createGrid());
375 std::unique_ptr<Grid>
readGrid(Dune::GridFactory<Grid>& factory,
bool verbose =
false)
const
377 static_assert(!Dune::Capabilities::isCartesian<Grid>::v,
"Grid reader only supports unstructured grid implementations");
379 if (Dune::MPIHelper::instance().rank() == 0)
382 std::cout <<
"Reading " << Grid::dimension <<
"d grid from vtk file " << fileName_ <<
"." << std::endl;
383 readGrid_(factory, verbose);
386 return std::unique_ptr<Grid>(factory.createGrid());
398 std::unique_ptr<Grid>
readGrid(Dune::GridFactory<Grid>& factory,
Data& cellData,
Data& pointData,
bool verbose =
false)
const
400 static_assert(!Dune::Capabilities::isCartesian<Grid>::v,
"Grid reader only supports unstructured grid implementations");
402 if (Dune::MPIHelper::instance().rank() == 0)
405 std::cout <<
"Reading " << Grid::dimension <<
"d grid from vtk file " << fileName_ <<
"." << std::endl;
406 readGrid_(factory, verbose);
407 readGridData_(cellData, pointData, verbose);
410 return std::unique_ptr<Grid>(factory.createGrid());
420 void readGrid_(Dune::GridFactory<Grid>& factory,
bool verbose =
false)
const
422 using namespace tinyxml2;
424 const XMLElement* pieceNode = getPieceNode_();
425 const XMLElement* pointsNode = pieceNode->FirstChildElement(
"Points")->FirstChildElement(
"DataArray");
426 if (pointsNode ==
nullptr)
427 DUNE_THROW(Dune::IOError,
"Couldn't get data array of points in " << fileName_ <<
".");
429 using Point3D = Dune::FieldVector<double, 3>;
430 std::vector<Point3D> points3D;
431 std::stringstream dataStream(pointsNode->GetText());
432 std::istream_iterator<Point3D> it(dataStream);
433 std::copy(it, std::istream_iterator<Point3D>(), std::back_inserter(points3D));
436 auto points = adaptPointDimension_<Grid::dimensionworld>(std::move(points3D));
438 if (verbose) std::cout <<
"Found " << points.size() <<
" vertices." << std::endl;
441 for (
auto&& point : points)
442 factory.insertVertex(std::move(point));
444 const XMLElement* cellsNode = pieceNode->FirstChildElement(
"Cells");
445 const XMLElement* linesNode = pieceNode->FirstChildElement(
"Lines");
448 const XMLElement* connectivityNode = findDataArray_(cellsNode,
"connectivity");
449 const XMLElement* offsetsNode = findDataArray_(cellsNode,
"offsets");
450 const XMLElement* typesNode = findDataArray_(cellsNode,
"types");
452 const auto connectivity = parseDataArray_<std::vector<unsigned int>>(connectivityNode);
453 const auto offsets = parseDataArray_<std::vector<unsigned int>>(offsetsNode);
454 const auto types = parseDataArray_<std::vector<unsigned int>>(typesNode);
456 if (verbose) std::cout <<
"Found " << offsets.size() <<
" elements." << std::endl;
458 unsigned int lastOffset = 0;
459 for (
unsigned int i = 0; i < offsets.size(); ++i)
461 const auto geomType = vtkToDuneGeomType_(types[i]);
462 unsigned int offset = offsets[i];
463 std::vector<unsigned int> corners; corners.resize(offset-lastOffset);
464 for (
unsigned int j = 0; j < offset-lastOffset; ++j)
465 corners[Dune::VTK::renumber(geomType, j)] = connectivity[lastOffset+j];
466 factory.insertElement(geomType, std::move(corners));
474 if (Grid::dimension != 1)
475 DUNE_THROW(Dune::IOError,
"Grid expects dimension " << Grid::dimension
476 <<
" but " << fileName_ <<
" contains a 1D grid.");
478 const XMLElement* connectivityNode = findDataArray_(linesNode,
"connectivity");
479 const XMLElement* offsetsNode = findDataArray_(linesNode,
"offsets");
481 const auto connectivity = parseDataArray_<std::vector<unsigned int>>(connectivityNode);
482 const auto offsets = parseDataArray_<std::vector<unsigned int>>(offsetsNode);
484 if (verbose) std::cout <<
"Found " << offsets.size() <<
" polylines." << std::endl;
486 unsigned int lastOffset = 0;
487 for (
unsigned int i = 0; i < offsets.size(); ++i)
491 unsigned int offset = offsets[i];
492 for (
unsigned int j = 0; j < offset-lastOffset-1; ++j)
494 std::vector<unsigned int>({ connectivity[lastOffset+j], connectivity[lastOffset+j+1] }));
499 DUNE_THROW(Dune::IOError,
"No Cells or Lines element found in " << fileName_);
508 void readGridData_(Data& cellData, Data& pointData,
bool verbose =
false)
const
510 using namespace tinyxml2;
512 const XMLElement* pieceNode = getPieceNode_();
513 const XMLElement* cellDataNode = getDataNode_(pieceNode, DataType::cellData);
514 if (cellDataNode !=
nullptr)
516 const XMLElement* cellsNode = pieceNode->FirstChildElement(
"Cells");
517 const XMLElement* linesNode = pieceNode->FirstChildElement(
"Lines");
521 const XMLElement* dataArray = cellDataNode->FirstChildElement(
"DataArray");
522 for (; dataArray !=
nullptr; dataArray = dataArray->NextSiblingElement(
"DataArray"))
524 const char *attributeText = dataArray->Attribute(
"Name");
526 if (attributeText ==
nullptr)
527 DUNE_THROW(Dune::IOError,
"Couldn't get Name attribute of a cell data array.");
529 cellData[std::string(attributeText)] = parseDataArray_<std::vector<double>>(dataArray);
532 std::cout <<
"Read cell data field " << attributeText << std::endl;
539 const XMLElement* dataArray = cellDataNode->FirstChildElement(
"DataArray");
542 Data polyLineCellData;
543 for (; dataArray !=
nullptr; dataArray = dataArray->NextSiblingElement(
"DataArray"))
545 const char *attributeText = dataArray->Attribute(
"Name");
547 if (attributeText ==
nullptr)
548 DUNE_THROW(Dune::IOError,
"Couldn't get Name attribute of a cell data array.");
550 polyLineCellData[std::string(attributeText)] = parseDataArray_<std::vector<double>>(dataArray);
553 std::cout <<
"Read cell data field " << attributeText << std::endl;
559 const XMLElement* offsetsNode = findDataArray_(linesNode,
"offsets");
560 const auto offsets = parseDataArray_<std::vector<unsigned int>>(offsetsNode);
562 if (offsets.size() != polyLineCellData.begin()->second.size())
563 DUNE_THROW(Dune::IOError,
"Expected the same number of cell data entries (is "
564 << polyLineCellData.begin()->second.size()
565 <<
") as polylines (" << offsets.size() <<
")!");
568 unsigned int lastOffset = 0;
569 std::size_t numCells = 0;
570 for (
unsigned int i = 0; i < offsets.size(); ++i)
572 unsigned int offset = offsets[i];
573 for (
unsigned int j = 0; j < offset-lastOffset-1; ++j)
579 for (
const auto& dArray : polyLineCellData)
581 cellData[dArray.first] = std::vector<double>(numCells);
582 auto& cd = cellData[dArray.first];
583 const auto& pd = dArray.second;
586 std::size_t cellIdx = 0;
587 for (
unsigned int i = 0; i < offsets.size(); ++i)
589 unsigned int offset = offsets[i];
590 for (
unsigned int j = 0; j < offset-lastOffset-1; ++j)
591 cd[cellIdx++] = pd[i];
598 DUNE_THROW(Dune::IOError,
"No Cells or Lines element found in " << fileName_);
601 const XMLElement* pointDataNode = getDataNode_(pieceNode, DataType::pointData);
602 if (pointDataNode !=
nullptr)
604 const XMLElement* dataArray = pointDataNode->FirstChildElement(
"DataArray");
605 for (; dataArray !=
nullptr; dataArray = dataArray->NextSiblingElement(
"DataArray"))
607 const char *attributeText = dataArray->Attribute(
"Name");
609 if (attributeText ==
nullptr)
610 DUNE_THROW(Dune::IOError,
"Couldn't get Name attribute of a point data array.");
612 pointData[std::string(attributeText)] = parseDataArray_<std::vector<double>>(dataArray);
615 std::cout <<
"Read point data field " << attributeText << std::endl;
624 const tinyxml2::XMLElement* getPieceNode_()
const
633 const tinyxml2::XMLElement* getDataNode_(
const tinyxml2::XMLElement* pieceNode,
const DataType& type)
const
635 using namespace tinyxml2;
637 const XMLElement* dataNode =
nullptr;
638 if (type == DataType::pointData)
639 dataNode = pieceNode->FirstChildElement(
"PointData");
640 else if (type == DataType::cellData)
641 dataNode = pieceNode->FirstChildElement(
"CellData");
643 DUNE_THROW(Dune::IOError,
"Only cell and point data are supported.");
654 const tinyxml2::XMLElement* findDataArray_(
const tinyxml2::XMLElement* dataNode,
const std::string& name)
const
656 using namespace tinyxml2;
659 const XMLElement* dataArray = dataNode->FirstChildElement(
"DataArray");
660 for (; dataArray !=
nullptr; dataArray = dataArray->NextSiblingElement(
"DataArray"))
662 const char *attributeText = dataArray->Attribute(
"Name");
664 if (attributeText ==
nullptr)
665 DUNE_THROW(Dune::IOError,
"Couldn't get Name attribute of a data array.");
667 if (attributeText == name)
679 template<
class Container>
680 Container parseDataArray_(
const tinyxml2::XMLElement* dataArray)
const
682 std::stringstream dataStream(dataArray->GetText());
683 return readStreamToContainer<Container>(dataStream);
690 Dune::GeometryType vtkToDuneGeomType_(
unsigned int vtkCellType)
const
694 case Dune::VTK::GeometryType::vertex:
return Dune::GeometryTypes::vertex;
696 case Dune::VTK::GeometryType::triangle:
return Dune::GeometryTypes::triangle;
697 case Dune::VTK::GeometryType::quadrilateral:
return Dune::GeometryTypes::quadrilateral;
698 case Dune::VTK::GeometryType::tetrahedron:
return Dune::GeometryTypes::tetrahedron;
699 case Dune::VTK::GeometryType::hexahedron:
return Dune::GeometryTypes::hexahedron;
700 case Dune::VTK::GeometryType::prism:
return Dune::GeometryTypes::prism;
701 case Dune::VTK::GeometryType::pyramid:
return Dune::GeometryTypes::pyramid;
702 default: DUNE_THROW(Dune::NotImplemented,
"VTK cell type " << vtkCellType);
706 template<
int dim, std::enable_if_t<(dim < 3),
int> = 0>
707 std::vector<Dune::FieldVector<
double, dim>>
708 adaptPo
intDimension_(std::vector<Dune::FieldVector<
double, 3>>&& po
ints3D) const
710 std::vector<Dune::FieldVector<
double, dim>> po
ints(po
ints3D.size());
711 for (std::
size_t i = 0; i < po
ints.size(); ++i)
712 for (
int j = 0; j < dim; ++j)
713 po
ints[i][j] = po
ints3D[i][j];
717 template<
int dim, std::enable_if_t<(dim == 3),
int> = 0>
718 std::vector<Dune::FieldVector<double, dim>>
719 adaptPointDimension_(std::vector<Dune::FieldVector<double, 3>>&& points3D)
const
720 {
return std::move(points3D); }
722 std::string fileName_;
723 tinyxml2::XMLDocument doc_;
A vtk file reader using tinyxml2 as xml backend.
Definition: vtkreader.hh:269
std::unique_ptr< Grid > readGrid(Dune::GridFactory< Grid > &factory, Data &cellData, Data &pointData, bool verbose=false) const
Read a grid from a vtk/vtu/vtp file, reading all cell and point data.
Definition: vtkreader.hh:398
bool hasData(const std::string &name, const DataType &type) const
Reviews data from the vtk file to check if there is a data array with a specified name.
Definition: vtkreader.hh:306
Container readData(const std::string &name, const DataType &type) const
read data from the vtk file to a container, e.g. std::vector<double>
Definition: vtkreader.hh:329
VTKReader(const std::string &fileName)
The constructor creates a tinyxml2::XMLDocument from file.
Definition: vtkreader.hh:282
std::unique_ptr< Grid > readGrid(Dune::GridFactory< Grid > &factory, bool verbose=false) const
Read a grid from a vtk/vtu/vtp file, ignoring cell and point data.
Definition: vtkreader.hh:375
std::unique_ptr< Grid > readGrid(bool verbose=false) const
Read a grid from a vtk/vtu/vtp file, ignoring cell and point data.
Definition: vtkreader.hh:350
DataType
The data array types.
Definition: vtkreader.hh:274
std::unordered_map< std::string, std::vector< double > > Data
the cell / point data type for point data read from a grid file
Definition: vtkreader.hh:277
Free functions to write and read a sequence container to and from a file.
Definition: vtkreader.hh:201
const tinyxml2::XMLElement * getPieceNode(const tinyxml2::XMLDocument &doc, const std::string &fileName)
Get the piece node an xml document.
Definition: vtkreader.hh:209
std::string getProcessPieceFileName(const std::string &pvtkFileName)
get the vtk filename for the current processor
Definition: vtkreader.hh:233
constexpr Line line
Definition: couplingmanager1d3d_line.hh:31
Definition: common/pdesolver.hh:24