KASKADE 7 development version
Loading...
Searching...
No Matches
vtkreader.hh
Go to the documentation of this file.
1/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
2/* */
3/* This file is part of the library KASKADE 7 */
4/* https://www.zib.de/research/projects/kaskade7-finite-element-toolbox */
5/* */
6/* Copyright (C) 2014-2025 Zuse Institute Berlin */
7/* */
8/* KASKADE 7 is distributed under the terms of the ZIB Academic License. */
9/* see $KASKADE/academic.txt */
10/* */
11/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
12
13#ifndef VTKREADER_HH
14#define VTKREADER_HH
15
16
17#include <vector>
18#include <map>
19#include <string>
20#include <memory>
21#include <iostream>
22#include <algorithm>
23#include <sstream>
24#include <cassert>
25
26#include <boost/fusion/container/vector.hpp>
27#include <boost/fusion/include/zip_view.hpp>
28
29#include <dune/grid/config.h>
30#include <dune/grid/common/gridfactory.hh>
31
32#include <fem/functionspace.hh>
33#include <fem/lagrangespace.hh>
35#include "utilities/timing.hh"
36
37namespace Kaskade
38{
40 namespace VTKReaderDetail
41 {
42 enum CoefficientDataType
43 {
44 pointData,
45 cellData
46 };
47
48 struct CoefficientData
49 {
50 CoefficientDataType type;
51 std::size_t numComponents = 0;
52 std::vector<double> data;
53 };
54
55 struct VTKData
56 {
57 bool reverseByteOrder = false; // if loading binary
58 std::string headerType = "UInt32"; // data type for binary data size header
59 std::string compressor; // compression method for binary data (not yet supported)
60 std::string filename;
61 std::size_t dimVertex = 0, numPoints = 0, numCells = 0;
62 std::vector<double> coordinates;
63 std::vector<std::size_t> connectivity, offsets, types;
64 std::map<std::string, CoefficientData> coefficientData; // this includes PointData and CellData
65 };
66
67 struct VTKCell
68 {
69 int vtkGeomType;
70 std::vector<std::size_t> corners, edges;
71 };
72
73 } // namespace VTKReaderDetail
75
95 {
96 public:
109
114 {
115 bool dataProvided = false;
116 bool continuous = false;
117 int order = 0;
119 };
120
124 VTKReader() = default;
125
130 VTKReader(std::string const& filename);
131
136 void load(std::string const& filename);
137
143 void loadOnlyData(std::string const& filename);
144
153 template<class Grid>
154 std::unique_ptr<Grid> createGrid();
155
156 template<class Grid, class Deformation>
157 std::unique_ptr<Grid> createGrid(Deformation const& deformation);
158
177 template<class VariableSet>
178 void getCoefficients(VariableSet& varSet, int interpolationFlags = noInterpolation) const;
179
189 template<class FSE>
190 void getCoefficients(std::string const& functionName, FSE& fse,
191 int interpolationFlags = noInterpolation) const;
192
197
201 std::vector<std::string> functionNames() const;
202
209 FunctionInfo getFunctionInfo(std::string const& functionName) const;
210
214
215 private:
216
217 enum LoadOption
218 {
219 loadOptionEverything,
220 loadOptionOnlyData
221 };
222
223 enum CoefficientMapping
224 {
225 continuous,
226 discontinuous
227 };
228
229 template<class VariableSet, class FSEVarDescPair>
230 void copyCoefficientsByName(VariableSet const& varSet, FSEVarDescPair& pair, int interpolationFlags) const;
231
232 template<class FSE>
233 void copyCoefficients(std::string const& functionName, VTKReaderDetail::CoefficientData const& coefficientData, FSE& fse, int interpolationFlags) const;
234
235 template<class FSE>
236 void copyCoefficientsInterpolated(std::string const& functionName,
237 VTKReaderDetail::CoefficientData const& coefficientData,
238 FSE& fse) const;
239
240 template<class FSE>
241 void copyCoefficientsDirectly(std::string const& functionName,
242 VTKReaderDetail::CoefficientData const& coefficientData,
243 FSE& fse) const;
244
245 void loadVTKInternal(std::string const& filename, LoadOption option);
246 void prepareGridCreation(std::vector<VTKReaderDetail::VTKCell>& vtkCells, std::vector<char>& isCorner);
247 void reset();
248 void clearCoefficientData();
249
250
251 VTKReaderDetail::VTKData vtk; // stores global information about the VTK file
252
253 bool gridWasLoaded = false,
254 gridWasCreated = false;
255
256 // coefficientMapping and polynomialOrder refer only to PointData. CellData is handled separately.
257 CoefficientMapping coefficientMapping = continuous;
258 int polynomialOrder = 0;
259
260 // index mapping: for a coefficient-index i, dataIndices[i] is the corresponding vtk-index
261 std::vector<std::size_t> pointDataIndices, cellDataIndices;
262 };
263
264
265 std::ostream& operator<<(std::ostream& stream, VTKReader::FunctionInfo const& info);
266
267 // ----------------------------------------------------------------------------------------------
268 // ----------------------------------------------------------------------------------------------
269
271 namespace VTKReaderDetail
272 {
273 // used to find duplicate points
274 struct IndexedPoint
275 {
276 std::size_t vtkIdx = 0, numComponents = 0;
277 std::vector<double>::const_iterator coordinates;
278
279 bool operator<(IndexedPoint const& other) const;
280 bool operator==(IndexedPoint const& other) const; // for std::adjacent_find
281 };
282
283 // used to keep track of indices during grid creation
284 template<class Grid>
285 class VTKFactoryHelper
286 {
287 public:
288 template<class Deformation> void insertVertices(std::vector<char> const& isCorner, VTKData const& vtk, Deformation const& deformation);
289 void insertVertices(std::vector<char> const& isCorner, VTKData const& vtk);
290 void insertCells(std::vector<VTKCell> const& vtkCells);
291 std::unique_ptr<Grid> createGrid();
292 void setIndicesForDuplicatePoints(std::vector<IndexedPoint> const& indexedPoints, std::vector<std::size_t> const& vertexVTKToMerged);
293 void getDataIndicesContinuous(typename Grid::LeafGridView const& leafView, std::vector<VTKCell> const& vtkCells, std::vector<std::size_t>& dataIndicesOut) const;
294 void getDataIndicesDiscontinuous(typename Grid::LeafGridView const& leafView, std::vector<VTKCell> const& vtkCells, std::vector<std::size_t>& dataIndicesOut) const;
295 void getCellDataIndices(typename Grid::LeafGridView const& leafView, std::vector<std::size_t>& dataIndicesOut) const;
296
297 private:
298
299 template<class ElementEntity>
300 void getIndicesLocalToVTK(VTKCell const& vtkCell, ElementEntity const& element, std::vector<std::size_t>& vertexLocalToVTK, std::vector<std::size_t>& edgeLocalToVTK) const;
301
302 Dune::GridFactory<Grid> factory;
303 std::vector<std::size_t> vertexVTKToInsertion, vertexInsertionToVTK;
304 std::size_t totalCorners = 0, totalEdges = 0;
305 };
306
307 std::string formatWarning(std::string const& filename, std::string const& message);
308
309 Dune::GeometryType getDuneGeomType(int vtkGeomType);
310 std::size_t getDuneCorner(int vtkGeomType, std::size_t corner);
311 void countCornersAndEdges(int vtkGeomType, std::size_t& numCorners, std::size_t& numEdges);
312 int countCellDim(int vtkGeomType);
313 // compare index-pairs as sets
314 struct CompareTwoSet
315 {
316 bool operator()(std::pair<std::size_t, std::size_t> const& p1, std::pair<std::size_t, std::size_t> const& p2) const;
317 };
318 using EdgeTable = std::map<std::pair<std::size_t, std::size_t>, std::size_t, CompareTwoSet>;
319
320 std::size_t findEdgeIndex(EdgeTable const& edgeTable, std::size_t a, std::size_t b);
321 std::pair<std::size_t, std::size_t> getVTKLocalCorners(int vtkGeomType, std::size_t edge);
322 std::vector<std::size_t> getIndicesPerCell(std::vector<std::size_t> const& corners, std::vector<std::size_t> const& edges, int vtkGeomType);
323
324 template<class ElementEntity, class IndexSet>
325 EdgeTable createEdgeTable(ElementEntity const& element, IndexSet const& indexSet, std::vector<std::size_t> const& vertexGridToVTK)
326 {
327 // for an element, create a map {c0, c1} -> e.
328 // {c0, c1} and e define the same edge. {c0, c1} are the vtk-indices of its corners and e is the grid-index of the edge-entity.
329
330 constexpr int dim = IndexSet::dimension;
331 constexpr int codimEdge = dim - 1, codimVertex = dim;
332 EdgeTable edgeTable;
333 auto refElement = Dune::ReferenceElements<double, dim>::general(element.type());
334
335 unsigned numEdges = refElement.size(codimEdge);
336 for(unsigned i = 0; i < numEdges; ++i)
337 {
338 // get local corner indices for local edge i
339 std::size_t c0 = refElement.subEntity(i, codimEdge, 0, codimVertex);
340 std::size_t c1 = refElement.subEntity(i, codimEdge, 1, codimVertex);
341
342 // transform {c0, c1} and i to grid
343 c0 = indexSet.subIndex(element, c0, codimVertex);
344 c1 = indexSet.subIndex(element, c1, codimVertex);
345 std::size_t e = indexSet.subIndex(element, i, codimEdge);
346
347 // transform {c0, c1} to vtk
348 c0 = vertexGridToVTK[c0];
349 c1 = vertexGridToVTK[c1];
350
351 // insert into edgeTable
352 edgeTable[std::make_pair(c0, c1)] = e;
353 }
354 return edgeTable;
355 }
356
357 // match FSEs with their names
358 template<class DataSequence, class VariableDescriptionSequence>
359 boost::fusion::zip_view<boost::fusion::vector<DataSequence&, VariableDescriptionSequence const&>>
360 makeZipView(DataSequence& data, VariableDescriptionSequence const& descriptions)
361 {
362 using Sequences = boost::fusion::vector<DataSequence&, VariableDescriptionSequence const&>;
363 return boost::fusion::zip_view<Sequences>(Sequences(data, descriptions));
364 }
365
366 // VTKFactoryHelper
367
368 template<class Grid>
369 template<class Deformation>
370 void VTKFactoryHelper<Grid>::insertVertices(std::vector<char> const& isCorner, VTKData const& vtk, Deformation const& deformation)
371 {
372 // Insert vertices from VTK's coordinate vector into grid and keep track of indices.
373 // If too many or too few coordinates are provided, excess values are ignored or set to 0 respectively.
374 constexpr int dim = Grid::dimension;
375 using Vertex = Dune::FieldVector<double, dim>;
376 std::size_t numComponentsToRead = std::min((std::size_t)dim, vtk.dimVertex);
377 vertexVTKToInsertion.resize(vtk.numPoints, 0);
378 std::size_t countInsertion = 0;
379
380 for(std::size_t i = 0; i < vtk.numPoints; ++i)
381 {
382 // only insert marked corners
383 if(isCorner[i])
384 {
385 std::size_t offs = i * vtk.dimVertex;
386 Vertex vertex(0);
387 auto it = vtk.coordinates.begin() + offs;
388 std::copy(it, it + numComponentsToRead, vertex.begin());
389 factory.insertVertex(deformation(vertex));
390
391 vertexInsertionToVTK.push_back(i);
392 vertexVTKToInsertion[i] = countInsertion;
393 ++countInsertion;
394 }
395 }
396 totalCorners = countInsertion;
397 // totalEdges is used only for continuous coefficient mapping
398 // otherwise the number is wrong due to duplicate points
399 totalEdges = vtk.numPoints - totalCorners;
400 }
401
402 template<class Grid>
403 void VTKFactoryHelper<Grid>::insertVertices(std::vector<char> const& isCorner, VTKData const& vtk)
404 {
405 auto identity = [] (auto x) {return x;};
406 insertVertices(isCorner, vtk, identity);
407 }
408
409 template<class Grid>
410 void VTKFactoryHelper<Grid>::insertCells(std::vector<VTKCell> const& vtkCells)
411 {
412 int dim = Grid::dimension;
413 // insert cells using the insertion-indices of their corners
414 for(VTKCell const& vtkCell : vtkCells)
415 {
416 int geoType = vtkCell.vtkGeomType;
417 int cellDim = countCellDim(geoType);
418
419 if(dim !=cellDim){
420 continue;
421 }
422
423 std::vector<unsigned int> corners(vtkCell.corners.size());
424 for(std::size_t k = 0; k < corners.size(); ++k)
425 {
426 std::size_t corner = getDuneCorner(vtkCell.vtkGeomType, k);
427 std::size_t vtkCornerIdx = vtkCell.corners[corner];
428 corners[k] = (unsigned int) vertexVTKToInsertion[vtkCornerIdx];
429 }
430 factory.insertElement(getDuneGeomType(vtkCell.vtkGeomType), corners);
431 }
432 }
433
434 template<class Grid>
435 std::unique_ptr<Grid> VTKFactoryHelper<Grid>::createGrid()
436 {
437 return std::unique_ptr<Grid>(factory.createGrid());
438 }
439
440 template<class Grid>
441 void VTKFactoryHelper<Grid>::setIndicesForDuplicatePoints(std::vector<IndexedPoint> const& indexedPoints, std::vector<std::size_t> const& vertexVTKToMerged)
442 {
443 // duplicate points get the insertion index of their representative
444 for(IndexedPoint const& p : indexedPoints)
445 {
446 std::size_t mergedIdx = vertexVTKToMerged[p.vtkIdx];
447 std::size_t insertionIdx = vertexVTKToInsertion[mergedIdx];
448 vertexVTKToInsertion[p.vtkIdx] = insertionIdx;
449 }
450 }
451
452 template<class Grid>
453 void VTKFactoryHelper<Grid>::getDataIndicesContinuous(typename Grid::LeafGridView const& leafView, std::vector<VTKCell> const& vtkCells, std::vector<std::size_t>& dataIndicesOut) const
454 {
455 std::vector<std::size_t> vertexGridToVTK(totalCorners), edgeGridToVTK(totalEdges);
456
457 // vertices
458 auto const& indexSet = leafView.indexSet();
459 for(auto const& vertexEntity : vertices(leafView))
460 {
461 std::size_t insertionIdx = factory.insertionIndex(vertexEntity);
462 std::size_t gridIdx = indexSet.index(vertexEntity);
463
464 if(insertionIdx >= vertexInsertionToVTK.size() || gridIdx >= vertexGridToVTK.size())
465 {
466 // Grid returned invalid index?
467 throw Kaskade::GridException("Vertex index is out of bounds.", __FILE__, __LINE__);
468 }
469
470 std::size_t vtkIdx = vertexInsertionToVTK[insertionIdx];
471 vertexGridToVTK[gridIdx] = vtkIdx;
472 }
473
474 // edges
475 for(auto const& elementEntity : elements(leafView))
476 {
477 // get the vtk-definition used to create this cell
478 std::size_t insertionIdx = factory.insertionIndex(elementEntity);
479 // out of bounds check
480 if(insertionIdx >= vtkCells.size())
481 {
482 // Grid returned invalid index?
483 throw Kaskade::GridException("Cell insertion index is out of bounds.", __FILE__, __LINE__);
484 }
485
486 VTKCell const& vtkCell = vtkCells[insertionIdx];
487
488 // the EdgeTable for this cell maps {c0, c1} -> e,
489 // where c0, c1 are the vtk-indices of two of its corners and e is the grid-index of the edge between c0 and c1
490 EdgeTable edgeTable = createEdgeTable(elementEntity, indexSet, vertexGridToVTK);
491 for(std::size_t i = 0; i < vtkCell.edges.size(); ++i)
492 {
493 // get the vtk-index of an edge
494 std::size_t vtkIdx = vtkCell.edges[i];
495
496 // get vtk's local indices of the corresponding corners
497 std::pair<int, int> vtkLocalCorners = getVTKLocalCorners(vtkCell.vtkGeomType, i);
498
499 // use the local indices to look up the vtk-indices of these corners
500 // finally find the grid-index of the edge via the EdgeTable
501 std::size_t gridIdx = findEdgeIndex(edgeTable, vtkCell.corners[vtkLocalCorners.first], vtkCell.corners[vtkLocalCorners.second]);
502
503 if(gridIdx >= edgeGridToVTK.size())
504 {
505 // Grid returned invalid index?
506 throw Kaskade::GridException("Edge index is out of bounds.", __FILE__, __LINE__);
507 }
508 edgeGridToVTK[gridIdx]= vtkIdx;
509 }
510 }
511
512 dataIndicesOut.resize(totalCorners + totalEdges);
513 std::copy(edgeGridToVTK.begin(), edgeGridToVTK.end(), dataIndicesOut.begin());
514 std::copy(vertexGridToVTK.begin(), vertexGridToVTK.end(), dataIndicesOut.begin() + totalEdges);
515 }
516
517 template<class Grid>
518 void VTKFactoryHelper<Grid>::getDataIndicesDiscontinuous(typename Grid::LeafGridView const& leafView, std::vector<VTKCell> const& vtkCells, std::vector<std::size_t>& dataIndicesOut) const
519 {
520 // per cell indices are first stored as blocks
521 std::vector<std::vector<std::size_t>> dataIndicesPerCell(vtkCells.size());
522
523 for(auto const& elementEntity : elements(leafView))
524 {
525 // get the corresponding vtk-cell
526 std::size_t insertionIdx = factory.insertionIndex(elementEntity);
527 if(insertionIdx >= vtkCells.size())
528 {
529 // Grid returned invalid index?
530 throw Kaskade::GridException("Cell insertion index is out of bounds.", __FILE__, __LINE__);
531 }
532 VTKCell const& vtkCell = vtkCells[insertionIdx];
533
534 // get the data-indices for this cell in Kaskade discontinuous order
535 std::vector<std::size_t> vertexLocalToVTK, edgeLocalToVTK;
536 getIndicesLocalToVTK(vtkCell, elementEntity, vertexLocalToVTK, edgeLocalToVTK);
537 std::vector<std::size_t> cellIndices = getIndicesPerCell(vertexLocalToVTK, edgeLocalToVTK, vtkCell.vtkGeomType);
538
539 // insert in the right place
540 std::size_t gridIdx = leafView.indexSet().index(elementEntity);
541 // out of bounds check
542 if(gridIdx >= dataIndicesPerCell.size())
543 {
544 // Grid returned invalid index?
545 throw Kaskade::GridException("Cell index is out of bounds.", __FILE__, __LINE__);
546 }
547 dataIndicesPerCell[gridIdx] = cellIndices;
548 }
549
550 // make a sequence out of the blocks
551 for(std::vector<std::size_t> const& cellIndices : dataIndicesPerCell)
552 {
553 for(std::size_t idx : cellIndices)
554 {
555 dataIndicesOut.push_back(idx);
556 }
557 }
558 }
559
560 template<class Grid>
561 void VTKFactoryHelper<Grid>::getCellDataIndices(typename Grid::LeafGridView const& leafView, std::vector<std::size_t>& dataIndicesOut) const
562 {
563 std::size_t numCells = leafView.size(0);
564 dataIndicesOut.resize(numCells);
565
566 for(auto const& elementEntity : elements(leafView))
567 {
568 // cells were inserted in vtk order, so vtk-index == insertion-index
569 std::size_t vtkIdx = factory.insertionIndex(elementEntity);
570 std::size_t gridIdx = leafView.indexSet().index(elementEntity);
571 if(gridIdx >= dataIndicesOut.size())
572 {
573 // Grid returned invalid index?
574 throw Kaskade::GridException("Cell index is out of bounds.", __FILE__, __LINE__);
575 }
576 dataIndicesOut[gridIdx] = vtkIdx;
577 }
578 }
579
580 template<class Grid>
581 template<class ElementEntity>
582 void VTKFactoryHelper<Grid>::getIndicesLocalToVTK(VTKCell const& vtkCell, ElementEntity const& element, std::vector<std::size_t>& vertexLocalToVTK, std::vector<std::size_t>& edgeLocalToVTK) const
583 {
584 // this function takes one grid-element and maps its local indices (corners and edges) to the right vtk data indices
585 // edges are identified via the insertion-indices of their corners
586 // vtkCell and element must define the same cell for this to work
587
588 using IndexPair = std::pair<std::size_t, std::size_t>;
589
590 // abusing std::map, the desired mapping will be in the values
591 std::map<std::size_t, IndexPair> cornerLookup; // c(ins) ---> (c(grid_local), c(vtk-data))
592 std::map<IndexPair, IndexPair, CompareTwoSet> edgeLookup; // {a, b}(ins) ---> (e(grid_local), e(vtk-data))
593
594 std::size_t numCorners = vtkCell.corners.size(), numEdges = vtkCell.edges.size();
595 constexpr int dim = Grid::dimension;
596 constexpr int codimVertex = dim, codimEdge = dim - 1;
597
598 assert(element.subEntities(codimVertex) == numCorners);
599 assert(numEdges == 0 || element.subEntities(codimEdge) == numEdges);
600
601 // corners
602 std::vector<std::size_t> vertexLocalToInsertion(numCorners);
603
604 for(std::size_t i = 0; i < numCorners; ++i)
605 {
606 // grid
607 auto vertexEntity = element.template subEntity<codimVertex>(i);
608 std::size_t insertionIndex = factory.insertionIndex(vertexEntity);
609 cornerLookup[insertionIndex].first = i;
610 vertexLocalToInsertion[i] = insertionIndex;
611
612 // vtk
613 std::size_t vtkIndex = vtkCell.corners[i];
614 insertionIndex = vertexVTKToInsertion[vtkIndex];
615 cornerLookup[insertionIndex].second = vtkIndex;
616 }
617
618 // edges
619 auto refElement = Dune::ReferenceElements<double, dim>::general(element.type());
620
621 for(std::size_t i = 0; i < numEdges; ++i)
622 {
623 // grid
624 std::size_t c0 = refElement.subEntity(i, codimEdge, 0, codimVertex); // local
625 std::size_t c1 = refElement.subEntity(i, codimEdge, 1, codimVertex); // local
626 c0 = vertexLocalToInsertion[c0]; // insertion
627 c1 = vertexLocalToInsertion[c1]; // insertion
628 edgeLookup[std::make_pair(c0, c1)].first = i; // local
629
630 // vtk
631 IndexPair p = getVTKLocalCorners(vtkCell.vtkGeomType, i); // local
632 c0 = vtkCell.corners[p.first]; // vtk
633 c1 = vtkCell.corners[p.second]; // vtk
634 c0 = vertexVTKToInsertion[c0]; // insertion
635 c1 = vertexVTKToInsertion[c1]; // insertion
636 std::size_t edgeDataIdx = vtkCell.edges[i]; // vtk
637 edgeLookup[std::make_pair(c0, c1)].second = edgeDataIdx;
638 }
639
640 assert(cornerLookup.size() == numCorners);
641 assert(edgeLookup.size() == numEdges);
642
643 // fill vectors to return
644 vertexLocalToVTK.resize(numCorners);
645
646 for(auto const& p : cornerLookup)
647 {
648 IndexPair const& ip = p.second;
649 vertexLocalToVTK[ip.first] = ip.second;
650 }
651
652 edgeLocalToVTK.resize(numEdges);
653
654 for(auto const& p : edgeLookup)
655 {
656 IndexPair const& ip = p.second;
657 edgeLocalToVTK[ip.first] = ip.second;
658 }
659 }
660
661 } // namespace VTKReaderDetail
663
664 // VTKReader
665
666
667 template<class Grid>
668 std::unique_ptr<Grid> VTKReader::createGrid()
669 {
670 // identity means grid vertices are not transformed
671 auto identity = [] (auto x) {return x;};
672 return createGrid<Grid>(identity);
673 }
674
675 template<class Grid, class Deformation>
676 std::unique_ptr<Grid> VTKReader::createGrid(Deformation const& deformation)
677 {
678 using namespace VTKReaderDetail;
679
680 if (!gridWasLoaded)
681 throw Kaskade::FileIOException("No grid data has been loaded.", vtk.filename,
682 __FILE__, __LINE__);
683
684 ScopedTimingSection timer("grid preparation");
685
686 std::vector<char> isCorner(vtk.numPoints, 0);
687 std::vector<VTKCell> vtkCells(vtk.numCells);
688
689 // reset indices, group cells, mark corners, set polynomialOrder
690 prepareGridCreation(vtkCells, isCorner);
691
692 std::vector<IndexedPoint> indexedPoints;
693 std::vector<std::size_t> vertexVTKToMerged;
694
695 // collect non-edge points
696 for(std::size_t i = 0; i < vtk.numPoints; ++i)
697 {
698 if(isCorner[i])
699 {
700 std::size_t offs = i * vtk.dimVertex;
701 IndexedPoint p;
702 p.vtkIdx = i;
703 p.numComponents = vtk.dimVertex;
704 p.coordinates = vtk.coordinates.begin() + offs;
705 indexedPoints.push_back(p);
706 }
707 }
708
709 std::sort(indexedPoints.begin(), indexedPoints.end());
710
711 // detect duplicates and set coefficientMapping.
712 // coefficientMapping is set to discontinuous if there is at least one duplicate point.
713 bool hasDuplicatePoints = std::adjacent_find(indexedPoints.begin(), indexedPoints.end())
714 != indexedPoints.end();
715 coefficientMapping = hasDuplicatePoints? discontinuous : continuous;
716
717 if (hasDuplicatePoints)
718 {
719 // The isCorner vector will be used to prevent insertion of duplicate points.
720 vertexVTKToMerged.resize(vtk.numPoints, 0);
721 // unmark all corners
722 std::fill(isCorner.begin(), isCorner.end(), 0);
723
724 auto P = indexedPoints.begin();
725 while(P != indexedPoints.end())
726 {
727 // mark P as corner
728 isCorner[P->vtkIdx] = 1;
729 // map duplicates' vtk-indices to P's vtk-index
730 std::size_t currentRepresentativeIdx = P->vtkIdx;
731 auto range = std::equal_range(P, indexedPoints.end(), *P);
732 for(auto it = range.first; it != range.second; ++it)
733 {
734 vertexVTKToMerged[it->vtkIdx] = currentRepresentativeIdx;
735 }
736 P = range.second;
737 }
738 }
739
740 timer.restart("Dune factory");
741
742 VTKFactoryHelper<Grid> factoryHelper;
743 std::unique_ptr<Grid> grid;
744
745 // create the grid
746 try
747 {
748 factoryHelper.insertVertices(isCorner, vtk, deformation);
749
750 // If points have been merged, map vtk-indices of duplicate points to the same insertion index.
751 if (coefficientMapping == discontinuous)
752 factoryHelper.setIndicesForDuplicatePoints(indexedPoints, vertexVTKToMerged);
753
754 factoryHelper.insertCells(vtkCells);
755 grid = factoryHelper.createGrid();
756 }
757 catch(Dune::GridError const& e)
758 {
759 throw Kaskade::FileIOException(e.what(), vtk.filename, __FILE__, __LINE__);
760 }
761
762 // Get the indices. We always obtain index-mappings for PointData and CellData.
763 auto leafView = grid->leafGridView();
764
765 if (coefficientMapping == continuous)
766 {
767 factoryHelper.getDataIndicesContinuous(leafView, vtkCells, pointDataIndices);
768 }
769 else // discontinuous
770 {
771 factoryHelper.getDataIndicesDiscontinuous(leafView, vtkCells, pointDataIndices);
772 }
773
774 factoryHelper.getCellDataIndices(leafView, cellDataIndices);
775
776 gridWasCreated = true;
777 return grid;
778 }
779
780 template<class VariableSet>
781 void VTKReader::getCoefficients(VariableSet& varSet, int interpolationFlags) const
782 {
783 using namespace VTKReaderDetail;
784
785 if (!gridWasCreated)
786 {
787 throw Kaskade::FileIOException("Grid must be created before accessing data.", vtk.filename, __FILE__, __LINE__);
788 }
789
790 // Loop through FSEs and their descriptions simultaneously to match input data by name.
791 auto functions = makeZipView(varSet.data, typename VariableSet::Descriptions::Variables());
792 boost::fusion::for_each(functions, [&](auto const& f){this->copyCoefficientsByName(varSet, f, interpolationFlags);});
793 }
794
795 template<class FSE>
796 void VTKReader::getCoefficients(std::string const& functionName, FSE& fse,
797 int interpolationFlags) const
798 {
799 using namespace VTKReaderDetail;
800
801 if(!gridWasCreated)
802 {
803 throw Kaskade::FileIOException("Grid must be created before accessing data.", vtk.filename, __FILE__, __LINE__);
804 }
805
806 auto it = vtk.coefficientData.find(functionName);
807 if (it == vtk.coefficientData.end())
808 throw Kaskade::LookupException("Function '" + functionName + "' not found in VTK file.",
809 __FILE__,__LINE__);
810
811 copyCoefficients(functionName, it->second, fse, interpolationFlags);
812 }
813
814 template<class VariableSet, class FSEVarDescPair>
815 void VTKReader::copyCoefficientsByName(VariableSet const& varSet, FSEVarDescPair& pair, int interpolationFlags) const
816 {
817 using namespace boost::fusion;
818 using namespace VTKReaderDetail;
819
820 auto& fse = at_c<0>(pair);
821 auto const& desc = at_c<1>(pair);
822 std::string functionName = varSet.descriptions->names[desc.id];
823
824 // find data-values associated with fse's name
825 auto it = vtk.coefficientData.find(functionName);
826 if(it != vtk.coefficientData.end())
827 {
828 copyCoefficients(functionName, it->second, fse, interpolationFlags);
829 }
830 else
831 {
832 // warning
833 std::ostringstream out;
834 out << "No data provided for " << functionName << ".";
835 std::cout << formatWarning(vtk.filename, out.str()) << '\n';
836 }
837 }
838
839 template<class FSE>
840 void VTKReader::copyCoefficients(std::string const& functionName,
841 VTKReaderDetail::CoefficientData const& coefficientData,
842 FSE& fse,
843 int interpolationFlags) const
844 {
845 using namespace VTKReaderDetail;
846
847 constexpr int fseCoefficientDim = FSE::StorageValueType::dimension;
848 int fseMaxOrder = fse.space().mapper().maxOrder(), fseContinuity = FSE::Space::continuity;
849
850 bool interpolationNeeded = false;
851
852 if ((std::size_t)fseCoefficientDim != coefficientData.numComponents)
853 {
854 if((interpolationFlags & allowCoefficientDimensionMismatch) == 0)
855 {
856 std::ostringstream out;
857 out << "\"" << functionName << "\": Coefficient dimension mismatch.\nfunction info: "
858 << getFunctionInfo(functionName);
859 throw Kaskade::FileIOException(out.str(), vtk.filename, __FILE__, __LINE__);
860 }
861 }
862
863 // order is always 0 for CellData
864 int order = coefficientData.type==cellData? 0: polynomialOrder;
865
866 if (fseMaxOrder != order)
867 {
868 if (interpolationFlags & allowOrderMismatch)
869 interpolationNeeded = true;
870 else
871 {
872 std::ostringstream out;
873 out << "\"" << functionName << "\": Order mismatch.\nfunction info: "
874 << getFunctionInfo(functionName);
875 throw Kaskade::FileIOException(out.str(), vtk.filename, __FILE__, __LINE__);
876 }
877 }
878
879 // continuity is always discontinuous for CellData
880 CoefficientMapping continuity = coefficientData.type==cellData? discontinuous: coefficientMapping;
881
882 if ( (fseContinuity < 0 && continuity == continuous)
883 || (fseContinuity >= 0 && continuity == discontinuous))
884 {
885 if (interpolationFlags & allowContinuityMismatch)
886 interpolationNeeded = true;
887 else
888 {
889 std::ostringstream out;
890 out << "\"" << functionName << "\": Continuity mismatch.\nfunction info: "
891 << getFunctionInfo(functionName);
892 throw Kaskade::FileIOException(out.str(), vtk.filename, __FILE__, __LINE__);
893 }
894 }
895
896 if (interpolationNeeded)
897 copyCoefficientsInterpolated(functionName, coefficientData, fse);
898 else
899 copyCoefficientsDirectly(functionName, coefficientData, fse);
900 }
901
902 template<class FSE>
903 void VTKReader::copyCoefficientsInterpolated(std::string const& functionName,
904 VTKReaderDetail::CoefficientData const& coefficientData,
905 FSE& fse) const
906 {
907 using namespace Kaskade;
908 using namespace VTKReaderDetail;
909
910 using Mapper = typename FSE::Space::Mapper;
911 using Scalar = typename FSE::Space::Scalar;
912 using LeafView = typename Mapper::Grid::LeafGridView;
913 constexpr int fseCoefficientDim = FSE::StorageValueType::dimension;
914
915 // If interpolation is necessary, we create a function space matching the
916 // data format, load the data into such a function, and then use the
917 // FE function interpolated assignment functionality.
918
919 if (coefficientData.type == pointData)
920 {
921 if (coefficientMapping == continuous)
922 {
923 using Space = FEFunctionSpace<ContinuousLagrangeMapper<Scalar, LeafView>>;
924
925 Space space(fse.space().gridManager(), fse.space().grid().leafGridView(), polynomialOrder);
926 auto otherFSE = space.template element<fseCoefficientDim>();
927 copyCoefficientsDirectly(functionName, coefficientData, otherFSE);
928 fse = otherFSE;
929 }
930 else // discontinuous
931 {
932 using Space = FEFunctionSpace<DiscontinuousLagrangeMapper<Scalar, LeafView>>;
933
934 Space space(fse.space().gridManager(), fse.space().grid().leafGridView(), polynomialOrder);
935 auto otherFSE = space.template element<fseCoefficientDim>();
936 copyCoefficientsDirectly(functionName, coefficientData, otherFSE);
937 fse = otherFSE;
938 }
939 }
940 else if (coefficientData.type == cellData)
941 {
942 // CellData means discontinuous, order 0
943 using Space = FEFunctionSpace<DiscontinuousLagrangeMapper<Scalar, LeafView>>;
944
945 Space space(fse.space().gridManager(), fse.space().grid().leafGridView(), 0);
946 auto otherFSE = space.template element<fseCoefficientDim>();
947 copyCoefficientsDirectly(functionName, coefficientData, otherFSE);
948 fse = otherFSE;
949 }
950 }
951
952 template<class FSE>
953 void VTKReader::copyCoefficientsDirectly(std::string const& functionName,
954 VTKReaderDetail::CoefficientData const& coefficientData,
955 FSE& fse) const
956 {
957 using namespace VTKReaderDetail;
958
959 constexpr int fseCoefficientDim = FSE::StorageValueType::dimension;
960 std::size_t numComponentsToCopy = std::min(std::size_t(fseCoefficientDim), coefficientData.numComponents);
961 std::vector<std::size_t> const& indices = coefficientData.type == pointData? pointDataIndices : cellDataIndices;
962
963 if(indices.size() != fse.coefficients().size())
964 {
965 std::ostringstream out;
966 out << "\"" << functionName << "\": Number of coefficients doesn't match number of data points.\nfunction info: " << getFunctionInfo(functionName);
967 throw Kaskade::FileIOException(out.str(), vtk.filename, __FILE__, __LINE__);
968 }
969 for(std::size_t i = 0; i < indices.size(); ++i)
970 {
971 std::size_t dataIdx = indices[i];
972 auto& block = fse.coefficients()[i];
973 auto itData = coefficientData.data.begin() + dataIdx * coefficientData.numComponents;
974 std::copy(itData, itData + numComponentsToCopy, block.begin());
975 }
976 }
977} // namespace Kaskade
978
979#endif
An exception class for file IO errors.
An exception that can be thrown whenever a key lookup fails.
A scope guard object that automatically closes a timing section on destruction.
Definition timing.hh:181
void restart(std::string const &name)
Start new section.
FunctionInfo getFunctionInfo(std::string const &functionName) const
Information about the expected type of function. Meet these criteria to copy values into your variabl...
std::unique_ptr< Grid > createGrid()
Create a grid from a previously loaded VTK file.
Definition vtkreader.hh:668
VTKReader()=default
Default constructor.
Flags
Options for getCoefficients().
Definition vtkreader.hh:101
@ allowCoefficientDimensionMismatch
Definition vtkreader.hh:105
VTKReader(std::string const &filename)
Constructor that loads a VTK file.
void loadOnlyData(std::string const &filename)
Loads only coefficient data, omitting the grid. This can be used for time series.
void getCoefficients(VariableSet &varSet, int interpolationFlags=noInterpolation) const
Copy the data from the current VTK file into the coefficients of your FEFunctions.
Definition vtkreader.hh:781
std::vector< std::string > functionNames() const
Lists the functions stored in the file by their name.
void load(std::string const &filename)
Loads a VTK file.
A class for storing a heterogeneous collection of FunctionSpaceElement s.
Definition variables.hh:337
Descriptions const * descriptions
Descriptions of variable set, of type VariableSetDescription (lots of useful infos)
Definition variables.hh:529
FEFunctionSpace and FunctionSpaceElement and the like.
Lagrange Finite Elements.
int const LagrangeCubeShapeFunction< ctype, dimension, Scalar, O >::order
std::ostream & operator<<(std::ostream &stream, VTKReader::FunctionInfo const &info)
Information about a data set loaded from a file.
Definition vtkreader.hh:114